-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathintegration.py
More file actions
2148 lines (1933 loc) · 91.5 KB
/
Copy pathintegration.py
File metadata and controls
2148 lines (1933 loc) · 91.5 KB
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TROPOS LAGRANGIAN CLOUD MODEL
Super-Droplet method in two-dimensional kinematic framework
(Test Case 1 ICMW 2012)
Author: Jan Bohrer (bohrer@tropos.de)
Further contact: Oswald Knoth (knoth@tropos.de)
TIME INTEGRATION ALGORITHMS
the all-or-nothing collision algorithm is motivated by
Shima et al. 2009, Q. J. R. Meteorol. Soc. 135: 1307–1320 and
Unterstrasser 2017, GMD 10: 1521–1548
basic units:
particle mass, water mass, solute mass in femto gram = 10^-18 kg
particle radius in micro meter ("mu")
all other quantities in SI units
"""
#%% MODULE IMPORTS
import math
import numpy as np
from numba import njit
from datetime import datetime
import constants as c
from grid import interpolate_velocity_from_cell_bilinear, update_grid_r_l
import material_properties as mat
import atmosphere as atm
import microphysics as mp
from collision.all_or_nothing import \
collision_step_Ecol_grid_R_all_cells_2D_multicomp_np
from file_handling import \
dump_particle_data, save_grid_scalar_fields,\
dump_particle_tracer_data_block,\
save_grid_and_particles_full,\
save_sim_paras_to_file, dump_particle_data_all
#%% ADVECTION
# compute timestep estimate by courant number (CFL number)
# CFL = dt * ( u_x/dx + u_z/dz ) < cfl_max
# => dt < cfl_max / | ( u_x/dx + u_z/dz ) | for all u_x, u_z
# rhs is smallest for largest term1:
def compute_dt_max_from_CFL(grid, cfl_max):
"""Computes the maximum time step allowed for a given (Courant) CFL number
Compute timestep estimate by Courant number (CFL number)
CFL = dt * ( u_x/dx + u_z/dz ) < cfl_max
=> dt < cfl_max / | ( u_x/dx + u_z/dz ) | for all u_x, u_z
Parameters
----------
grid: :obj:`Grid`
Grid-class object, holding the velocity field.
cfl_max: float
Maximum Courant (CFL) number.
Returns
-------
dt_max: float
Maximum time step allowed corresponding to cfl_max
"""
term1 = np.abs( grid.velocity[0] / grid.steps[0] )\
+ np.abs (grid.velocity[1] / grid.steps[1] )
term1_max = np.amax(term1)
dt_max = cfl_max / term1_max
print("dt_max from CFL = ", dt_max)
return dt_max
@njit()
def compute_limiter(r, delta = 2.0):
"""Limiter for the 3rd order upwind advection scheme
Advection scheme by Hundsdorfer 1995, J. Comp. Phys 117: 35
Parameters
----------
r: float
Limiter argument = (a_(n+1) - a_n) / (a_n - a_(n-1)),
where 'a_n' is the state variable in cell 'n'
delta: float, optional
Parameter, largest allowed value of the limiter
Returns
-------
Limiter function evaluated at the limiter argument
"""
K = (1.0 + 2.0 * r) * c.one_third
# np.fmin: elementwise minimum when comparing two arrays,
# NaN is not propagated
return np.maximum(0.0, np.fmin (2.0 * r, np.fmin( K, delta ) ) )
# Currently not in use:
#def compute_limiter_from_scalars_upwind( a0, a1, da12 ):
# if ( np.abs(da12) > 1.0E-16 ):
# limiter_argument = ( a0 - a1 ) / ( da12 )
# else:
# limiter_argument = 1.0
# return compute_limiter(limiter_argument)
@njit()
def compute_limiter_from_scalar_grid_upwind( a0, a1, a2 ):
"""Compute advection scheme limiter values for a 2D spatial grid
3rd order advection scheme by Hundsdorfer 1995, J. Comp. Phys 117: 35
Let a1[i,j] be a discretized state variable in a 2D grid [i,j].
This function computes the limiter values in each grid cell for the
advection in one specific spatial transport direction (x or z).
For example in x: a0[i,j] = a1[i+1,j] and a2[i,j] = a1[i-1,j]
Then, the limiter argument is
(a1[i+1,j] - a1[i,j]) / (a1[i,j] - a1[i-1,j])
= (a0[i,j] - a1[i,j]) / (a1[i,j] - a2[i,j])
Parameters
----------
a0: ndarray, dtype=float
2D array holding the state-variable, but shifted by one index in
the transport-direction (s.a.)
a1: ndarray, dtype=float
2D array holding the state-variable
a2: ndarray, dtype=float
2D array holding the state-variable, but shifted by one index against
the transport-direction (s.a.)
Returns
-------
ndarray, dtype=float
2D array with limiter function in each cell for
the given transport direction
"""
r = np.where( np.abs( a1 - a2 ) > 1.0E-8 * np.abs( a0 - a1 ) ,
( a0 - a1 ) / ( a1 - a2 ),
( a0 - a1 ) * 1.0E8 * np.sign( a1 - a2 )
)
return compute_limiter( r )
def compute_divergence_upwind_np(field, flux_field,
grid_no_cells, grid_steps,
boundary_conditions = np.array([0, 1])):
"""Compute divergence of a flux at the grid cell surfaces
3rd order advection scheme by Hundsdorfer 1995, J. Comp. Phys 117: 35.
The flux is actually 'field'*'flux_field' and 'flux_field' can
either be the velocity or the mass flux density of dry air at the
grid cell surfaces, as required.
The calculated divergence is given by div( field * flux_field )
= d/dx (field * flux_field_x) + d/dz (field * flux_field_z)
The boundary conditions at the domain borders can either be
solid or periodic.
Parameters
----------
field: ndarray, dtype=float
2D array holding the transported field (state variable)
flux_field: ndarray, dtype=float
Provide either velocity (m/s) or mass flux density (kg/(s m^2))
of dry air.
flux_field[0] is a 2D array holding the x-components of the flux_field
projected onto the grid cell surface centers.
flux_field[1] is a 2D array holding the z-components of the flux_field
projected onto the grid cell surface centers.
grid_no_cells: ndarray, dtype=int
grid_no_cells[0] = number of grid cells in x (horizontal)
grid_no_cells[1] = number of grid cells in z (vertical)
grid_steps: ndarray, dtype=float
grid_steps[0] = horizontal grid step size in x (m)
grid_steps[1] = vertical grid step size in z (m)
boundary_conditions: ndarray, dtype=int
boundary_conditions[0] = boundary conditions in x (horizontal)
boundary_conditions[1] = boundary conditions in z (vertical)
choose '0' for periodic BC and '1' for solid BC
Returns
-------
ndarray, dtype=float
2D array providing the divergence of 'field'*'flux_field' in each
grid cell
"""
Nx = grid_no_cells[0]
Nz = grid_no_cells[1]
u = flux_field[0][:, 0:-1]
# transpose w to get same dimensions and routine
w = np.transpose(flux_field[1][0:-1, :])
N = Nx
if (boundary_conditions[0] == 0):
# periodic BC
field_x =\
np.vstack( ( np.vstack((field[N-2], field[N-1])),
field, np.vstack((field[0], field[1])) ) )
elif (boundary_conditions[0] == 1):
# fixed BC
field_x =\
np.vstack( ( np.vstack((field[0], field[0])),
field, np.vstack((field[N-1], field[N-1])) ) )
else:
print ('ERROR: invalid boundary type' )
a0 = field_x[2:N+3]
a1 = field_x[1:N+2]
a2 = field_x[0:N+1]
limiter = compute_limiter_from_scalar_grid_upwind( a0, a1, a2 )
# calc f_i_pos = F_i^(+) / u_i
# where F_i^(+) = flux through surface cell 'i' LEFT BORDER in case u > 0
f_pos = a1 + 0.5 * limiter * (a1 - a2)
# now negative u_i case:
# a1 and a0 switch places
# a1 = a0
# a0 = a1
a2 = field_x[3:N+4]
limiter = compute_limiter_from_scalar_grid_upwind( a1, a0, a2 )
f_neg = a0 + 0.5 * limiter * (a0 - a2)
# np.where to make cases u <> 0
# flux through LEFT BORDER cell i
F = np.where( u >= 0.0,
u * f_pos,
u * f_neg)
if (boundary_conditions[0] == 1):
F[0] = 0.0
F[-1] = 0.0
div = (F[1:] - F[0:-1]) / grid_steps[0]
# now for z / w component
# transpose to get same dimensions and routine
N = Nz
field_x = np.transpose( field )
if (boundary_conditions[1] == 0):
field_x = np.vstack( ( np.vstack((field_x[N-2], field_x[N-1])), field_x,
np.vstack((field_x[0], field_x[1])) ) )
elif (boundary_conditions[1] == 1):
field_x = np.vstack( ( np.vstack((field_x[0], field_x[0])), field_x,
np.vstack((field_x[N-1], field_x[N-1])) ) )
else:
print ('ERROR: invalid boundary type' )
a0 = field_x[2:N+3]
a1 = field_x[1:N+2]
a2 = field_x[0:N+1]
limiter = compute_limiter_from_scalar_grid_upwind( a0, a1, a2 )
# calc f_i_pos = F_i^(+) / u_i
# where F_i^(+) = flux through surface cell 'i' LEFT BORDER in case u > 0
f_pos = a1 + 0.5 * limiter * (a1 - a2)
# now negative u_i case:
# a1 and a0 switch places
# a1 = a0
# a0 = a1
a2 = field_x[3:N+4]
limiter = compute_limiter_from_scalar_grid_upwind( a1, a0, a2 )
f_neg = a0 + 0.5 * limiter * (a0 - a2)
# np.where to make cases w <> 0
# flux through LEFT BORDER cell
F = np.where( w >= 0.0,
w * f_pos,
w * f_neg )
if(boundary_conditions[1] == 1):
F[0] = 0.0
F[-1] = 0.0
return div + np.transpose( (F[1:] - F[0:-1]) / grid_steps[1] )
compute_divergence_upwind = njit()(compute_divergence_upwind_np)
#%% RELAXATION SOURCE TERM
def compute_relaxation_time_profile(z):
"""Computes the height dependent relaxation time
The horizontal means of the state variables (pot. temp. and water vapor)
are relaxed towards the initial values with the height dependent
relaxation time according to ICMW 2012 Test case 1
(Muhlbauer 2013, used in Arabas 2015)
Parameters
----------
z: float
Height in meter
Returns
-------
float
Relaxation time in seconds
"""
return 300 * np.exp(z/200)
# field is an 2D array(x,z)
# profile0 is an 1D profile(z)
# t_relax is the relaxation time profile(z)
# dt is the time step
# return: relaxation source term profile(z) for one time step dt
# note that the same value is added to every grid cell in a certain height
# thus, if the horizontal mean at some z is equal or very close to
# the horizontal mean of the initial profile (z), then there is no
# contribution to the source term of Theta or r_v
# this can be the case, when we have an updraft and downdraft tunnel of equal
# strength
@njit()
def compute_relaxation_term(field, profile0, t_relax, dt):
"""Compute height dependent relaxation terms for the state variables
The horizontal means of the state variables (pot. temp. and water vapor)
are relaxed towards the initial profiles with the height dependent
relaxation time according to ICMW 2012 Test case 1
(Muhlbauer 2013, used in Arabas 2015)
Parameters
----------
field: ndarray, dtype=float
2D array. Either potential temp. 'Theta' or water vapor content 'r_v'
profile0: ndarray, dtype=float
1D array with the height dependent initial profile of 'field'
t_relax: ndarray, dtype=float
1D array with the height dependent relaxation time (s)
dt: float
time step for the relaxation (s)
Returns
-------
ndarray, dtype=float
1D array with the height dependent right-hand-site relaxation terms
These terms do only depend on the height z
"""
# np.average is not allowed with njit
# return dt * (profile0 - np.average(field, axis = 0)) / t_relax
return dt * (profile0 - np.sum(field, axis = 0) / field.shape[0]) / t_relax
#%% GRID PROPAGATION
@njit()
def update_material_properties(grid_scalar_fields, grid_mat_prop):
"""Updates the material property grids based on the scalar field grids
Parameters
----------
grid_scalar_fields: ndarray, dtype=float
Array components are 2D arrays of the discretized scalar fields
grid_scalar_fields[0] = temperature
grid_scalar_fields[1] = pressure
grid_scalar_fields[2] = potential_temperature
grid_scalar_fields[3] = mass_density_air_dry
grid_scalar_fields[4] = mixing_ratio_water_vapor
grid_scalar_fields[5] = mixing_ratio_water_liquid
grid_scalar_fields[6] = saturation
grid_scalar_fields[7] = saturation_pressure
grid_scalar_fields[8] = mass_dry_inv
grid_scalar_fields[9] = rho_dry_inv
grid_mat_prop: ndarray, dtype=float
Array components are 2D arrays of the material properties in the
grid cells.
All material property grids get updated based on the scalar fields.
grid_mat_prop[0] = thermal_conductivity
grid_mat_prop[1] = diffusion_constant
grid_mat_prop[2] = heat_of_vaporization
grid_mat_prop[3] = surface_tension
grid_mat_prop[4] = specific_heat_capacity
grid_mat_prop[5] = viscosity
grid_mat_prop[6] = mass_density_fluid
"""
grid_mat_prop[0] = mat.compute_thermal_conductivity_air(
grid_scalar_fields[0])
grid_mat_prop[1] = mat.compute_diffusion_constant(grid_scalar_fields[0],
grid_scalar_fields[1])
grid_mat_prop[2] = mat.compute_heat_of_vaporization(grid_scalar_fields[0])
grid_mat_prop[3] = mat.compute_surface_tension_water(grid_scalar_fields[0])
grid_mat_prop[4] = atm.compute_specific_heat_capacity_air_moist(
grid_scalar_fields[4])
grid_mat_prop[5] = mat.compute_viscosity_air(grid_scalar_fields[0])
grid_mat_prop[6] = grid_scalar_fields[3]\
* (1.0 + grid_scalar_fields[4])
def propagate_grid_subloop_step_np(grid_scalar_fields, grid_mat_prop,
p_ref, p_ref_inv,
delta_Theta_ad, delta_r_v_ad,
delta_m_l,
grid_volume_cell):
"""Executes one subloop time step for the atmospheric scalar fields
One advection time step is divided into two subloops with refined time
step 'h'. In this refined time step, particle movement and
condensation/evaporation are conducted and the scalar fields are updated.
Parameters
----------
grid_scalar_fields: ndarray, dtype=float
Array components are 2D arrays of the discretized scalar fields
grid_scalar_fields[0] = temperature
grid_scalar_fields[1] = pressure
grid_scalar_fields[2] = potential_temperature
grid_scalar_fields[3] = mass_density_air_dry
grid_scalar_fields[4] = mixing_ratio_water_vapor
grid_scalar_fields[5] = mixing_ratio_water_liquid
grid_scalar_fields[6] = saturation
grid_scalar_fields[7] = saturation_pressure
grid_scalar_fields[8] = mass_dry_inv
grid_scalar_fields[9] = rho_dry_inv
grid_mat_prop: ndarray, dtype=float
Array components are 2D arrays of the material properties in the
grid cells.
All material property grids get updated based on the scalar fields.
grid_mat_prop[0] = thermal_conductivity
grid_mat_prop[1] = diffusion_constant
grid_mat_prop[2] = heat_of_vaporization
grid_mat_prop[3] = surface_tension
grid_mat_prop[4] = specific_heat_capacity
grid_mat_prop[5] = viscosity
grid_mat_prop[6] = mass_density_fluid
p_ref: float
Reference pressure for potential temperature
p_ref_inv: float
Inverse of the reference pressure (1/p_ref) for potential temperature
delta_Theta_ad: ndarray, dtype=float
2D array with the change in potential temperature (K) by advection
in each grid cell during one subloop step.
delta_r_v_ad: ndarray, dtype=float
2D array with the change in water vapor mixing ratio by advection
in each grid cell during one subloop step.
delta_m_l: ndarray, dtype=float
2D array with the change in liquid water mass (1E-18 kg) due to
condensation in each grid cell during one subloop step.
grid_volume_cell: float
Volume of one grid cell (m^3)
"""
grid_scalar_fields[2] += delta_Theta_ad
grid_scalar_fields[4] += delta_r_v_ad - delta_m_l*grid_scalar_fields[8]
Theta_over_T = atm.compute_Theta_over_T(grid_scalar_fields[3],
grid_scalar_fields[2],
p_ref_inv)
grid_scalar_fields[2] += \
Theta_over_T * (grid_mat_prop[2] * delta_m_l) \
/ (c.specific_heat_capacity_air_dry_NTP * grid_scalar_fields[3]
* grid_volume_cell
* ( 1.0 + grid_scalar_fields[4] * atm.heat_factor_r_v ) )
# update other grid properties
p_dry_over_p_ref = atm.compute_p_dry_over_p_ref(grid_scalar_fields[3],
grid_scalar_fields[2],
p_ref_inv)
grid_scalar_fields[0] = grid_scalar_fields[2]\
* p_dry_over_p_ref**atm.kappa_air_dry
grid_scalar_fields[1] = p_dry_over_p_ref * p_ref\
* ( 1 + grid_scalar_fields[4] / atm.epsilon_gc )
grid_scalar_fields[7] =\
mat.compute_saturation_pressure_vapor_liquid(grid_scalar_fields[0])
grid_scalar_fields[6] =\
atm.compute_pressure_vapor(
grid_scalar_fields[3] * grid_scalar_fields[4],
grid_scalar_fields[0] ) / grid_scalar_fields[7]
update_material_properties(grid_scalar_fields, grid_mat_prop)
propagate_grid_subloop_step = njit()(propagate_grid_subloop_step_np)
#%% PARTICLE PROPAGATION
@njit()
def update_T_p(grid_temp, cells, T_p):
"""Updates the particle temperatures to the atmos. grid cell temperatures
Parameters
----------
grid_temp: ndarray, dtype=float
2D array holding the discretized temperature of the atmosphere
cells: ndarray, dtype=int
2D array, holding the particle cell indices, i.e.
cells[0] = 1D array of horizontal indices
cells[1] = 1D array of vertical indices
(cells[0,n], cells[1,n]) gives the cell of particle 'n'
T_p: ndarray, dtype=float
1D array holding the particle temperatures sorted by particle IDs
"""
for ID in range(len(T_p)):
T_p[ID] = grid_temp[cells[0,ID],cells[1,ID]]
def update_cells_and_rel_pos_np(pos, cells, rel_pos, active_ids,
grid_ranges, grid_steps):
"""Updates particle cells and relative positions from absolute positions
Parameters
----------
pos: ndarray, dtype=float
2D array, where
pos[0] = 1D array of horizontal coordinates (m)
pos[1] = 1D array of vertical coordinates (m)
(pos[0,n], pos[1,n]) is the position of particle 'n'
cells: ndarray, dtype=int
2D array, holding the particle cell indices, i.e.
cells[0] = 1D array of horizontal indices
cells[1] = 1D array of vertical indices
(cells[0,n], cells[1,n]) gives the cell of particle 'n'
rel_pos: ndarray, dtype=float
2D array with relative cell positions corresponding to 'pos'
active_ids: ndarray, dtype=bool
1D mask-array. Each particle gets a flag 'True' or 'False', defining
if it still resides in the simulation domain or has already hit the
ground and is thereby removed from the simulation
grid_ranges: ndarray, dtype=float
2D array holding the coordinates of the domain box in two dimensions
grid_ranges[0] = [x_min, x_max]
grid_ranges[1] = [z_min, z_max]
grid_steps: ndarray, dtype=float
grid_steps[0] = horizontal grid step size in x (m)
grid_steps[1] = vertical grid step size in z (m)
"""
x = pos[0][active_ids]
y = pos[1][active_ids]
rel_pos[0][active_ids] = x - grid_ranges[0,0]
rel_pos[1][active_ids] = y - grid_ranges[1,0]
cells[0][active_ids] = np.floor(x/grid_steps[0]).astype(np.int64)
cells[1][active_ids] = np.floor(y/grid_steps[1]).astype(np.int64)
rel_pos[0] = rel_pos[0] / grid_steps[0] - cells[0]
rel_pos[1] = rel_pos[1] / grid_steps[1] - cells[1]
update_cells_and_rel_pos = njit()(update_cells_and_rel_pos_np)
def update_pos_from_vel_BC_PS_np(m_w, pos, vel, xi, cells,
water_removed,
id_list, active_ids,
grid_ranges, grid_steps, dt):
"""Updates particle positions by one Euler step, given their velocities
Used boundary conditions: periodic in x, solid in z.
If a particle hits the ground, its cell and position are set
to negative values, its velocity is set to zero and its 'active_ids'
flag is set to False.
Parameters
----------
m_w: ndarray, dtype=float
1D array holding the particle water masses (1E-18 kg)
pos: ndarray, dtype=float
2D array, where
pos[0] = 1D array of horizontal coordinates (m)
pos[1] = 1D array of vertical coordinates (m)
(pos[0,n], pos[1,n]) is the position of particle 'n'
vel: ndarray, dtype=float
2D array, where
vel[0] = 1D array of horizontal velocity components (m/s)
vel[1] = 1D array of vertical velocity components (m/s)
(vel[0,n], vel[1,n]) is the velocity of particle 'n'
xi: ndarray, dtype=float
1D array holding the particle multiplicities
cells: ndarray, dtype=int
2D array, holding the particle cell indices, i.e.
cells[0] = 1D array of horizontal indices
cells[1] = 1D array of vertical indices
(cells[0,n], cells[1,n]) gives the cell of particle 'n'
water_removed: ndarray, shape=(1,), dtype=float
1D array holding only one value, which counts the water removed
from the simulation domain by sedimentation
id_list: ndarray, dtype=float
1D array holding the ordered particle IDs.
Other arrays, like 'm_w', 'm_s', 'xi' etc. refer to this list.
I.e. 'm_w[n]' is the water mass of particle with ID 'id_list[n]'
active_ids: ndarray, dtype=bool
1D mask-array. Each particle gets a flag 'True' or 'False', defining
if it still resides in the simulation domain or has already hit the
ground and is thereby removed from the simulation
grid_ranges: ndarray, dtype=float
2D array holding the coordinates of the domain box in two dimensions
grid_ranges[0] = [x_min, x_max]
grid_ranges[1] = [z_min, z_max]
grid_steps: ndarray, dtype=float
grid_steps[0] = horizontal grid step size in x (m)
grid_steps[1] = vertical grid step size in z (m)
dt: float
Euler time step for the update of positions (s)
"""
z_min = grid_ranges[1,0]
pos += dt * vel
# periodic BC
# works only if x_grid_min = 0.0
# there might be trouble if x is exactly = 1500.0 (?),
# because then x will stay 1500.0 and the calc. cell will be 75,
# i.e. one too large for eg. grid.centers
pos[0] = pos[0] % grid_ranges[0,1]
# dont allow particles to cross z_max (upper domain boundary)
pos[1] = np.minimum(pos[1], grid_ranges[1,1]*0.999999)
# if particle hits ground, set z < 0 and active_ID = False
# this is the indicator for inactive IDs from here on
for ID in id_list[active_ids]:
if pos[1,ID] <= z_min:
# keep z-position constant just below ground
pos[1,ID] = z_min - 0.01 * grid_steps[1]
vel[0,ID] = 0.0
vel[1,ID] = 0.0
active_ids[ID] = False
water_removed[0] += xi[ID] * m_w[ID]
cells[1,ID] = -1
update_pos_from_vel_BC_PS =\
njit()(update_pos_from_vel_BC_PS_np)
def update_vel_impl_np(vel, cells, rel_pos, xi, id_list, active_ids,
R_p, rho_p,
grid_vel, grid_viscosity, grid_mass_density_fluid,
grid_no_cells, grav, dt):
"""Updates particle velocities by one implicit Euler step
Update scheme from time step n -> n+1
v_(n+1) = (v_n + ( u(x_(n+1/2)) * k_d - g ) * dt ) / (1 + k_d * dt)
x: Particle position, v: Particle velocity, u: Wind velocity.
g: Earth gravity (only in z-direction, here positive)
k_d: Drag factor, piecewise def., depends on particle Reynolds number.
Parameters
----------
vel: ndarray, dtype=float
2D array, where
vel[0] = 1D array of horizontal velocity components (m/s)
vel[1] = 1D array of vertical velocity components (m/s)
(vel[0,n], vel[1,n]) is the velocity of particle 'n'
cells: ndarray, dtype=int
2D array, holding the particle cell indices, i.e.
cells[0] = 1D array of horizontal indices
cells[1] = 1D array of vertical indices
(cells[0,n], cells[1,n]) gives the cell of particle 'n'
rel_pos: ndarray, dtype=float
2D array with relative cell positions corresponding to 'pos'
xi: ndarray, dtype=float
1D array holding the particle multiplicities
id_list: ndarray, dtype=float
1D array holding the ordered particle IDs.
Other arrays, like 'm_w', 'm_s', 'xi' etc. refer to this list.
I.e. 'm_w[n]' is the water mass of particle with ID 'id_list[n]'
active_ids: ndarray, dtype=bool
1D mask-array. Each particle gets a flag 'True' or 'False', defining
if it still resides in the simulation domain or has already hit the
ground and is thereby removed from the simulation
R_p: ndarray, dtype=float
1D array holding the particle radii (microns)
rho_p: ndarray, dtype=float
1D array holding the particle mass densities (kg/m^3)
grid_vel: ndarray, dtype=float
Discretized velocity field (m/s) of dry air.
grid_vel[0] is a 2D array holding the x-components of the vel. field
projected onto the grid cell surface centers.
grid_vel[1] is a 2D array holding the z-components of the vel. field
projected onto the grid cell surface centers.
grid_viscosity: ndarray, dtype=float
2D array holding the discretized dynamic viscosity
of the surrounding air (SI units)
grid_mass_density_fluid: ndarray, dtype=float
2D array holding the mass density of the surrounding air (SI units)
2D array holding the coordinates of the domain box in two dimensions
grid_ranges[0] = [x_min, x_max]
grid_ranges[1] = [z_min, z_max]
grid_no_cells: ndarray, dtype=int
grid_no_cells[0] = number of grid cells in x (horizontal)
grid_no_cells[1] = number of grid cells in z (vertical)
grav: float
Gravity of earth. Set larger zero for active gravity or zero during
spin-up phase
dt: float
Time step (s)
"""
vel_f = interpolate_velocity_from_cell_bilinear(cells, rel_pos,
grid_vel, grid_no_cells)
for ID in id_list[active_ids]:
R_p_ = R_p[ID]
cell = (cells[0,ID], cells[1,ID])
mu_f = grid_viscosity[cell]
rho_f_amb = grid_mass_density_fluid[cell]
dv = vel_f[:,ID] - vel[:,ID]
vel_dev = np.sqrt(dv[0]*dv[0] + dv[1]*dv[1])
Re_p = mp.compute_particle_reynolds_number(R_p_, vel_dev, rho_f_amb,
mu_f )
k_dt = 4.5E12 * dt * mu_f / ( rho_p[ID] * R_p_ * R_p_)
if Re_p > 0.5:
if Re_p < 1000.0:
k_dt *= (1 + 0.15 * Re_p**0.687)
# 0.018333333 = 0.44/24
else: k_dt *= 0.0183333333333 * Re_p
vel[0,ID] = (vel[0,ID] + k_dt * vel_f[0,ID]) / (1.0 + k_dt)
vel[1,ID] = (vel[1,ID] + k_dt * vel_f[1,ID] - dt * grav)\
/ (1.0 + k_dt)
update_vel_impl = njit()(update_vel_impl_np)
#%% MASS PROPAGATION
w_s_max_NaCl_inv = 1. / mat.w_s_max_NaCl
w_s_max_AS_inv = 1. / mat.w_s_max_AS
# Full Newton method with no_iter iterations,
# the derivative is calculated every iteration
def compute_dml_and_gamma_impl_Newton_full_np(
dt_sub, no_iter_impl_mass, m_w, m_s, w_s, R_p, T_p, rho_p,
T_amb, p_amb, S_amb, e_s_amb, L_v, K, D_v, sigma_p, solute_type):
"""Compute the change in droplet water mass by condensation
Implicit Newton method with 'no_iter_impl_mass' iterations to evaluate
the amount of condensed/evaporated water of a cloud particle/droplet.
For the condensation mass rate, the formula
by Fukuta 1970, J. Atm. Sci. 27: 1160 is applied.
Note, that the function is documented for one single particle. However,
it will also work for an array of particles, i.e. m_w, m_s, ... as
1D arrays.
Parameters
----------
dt_sub: float
Time step used for the implicit Newton method
no_iter_impl_mass: int
Number of iteration steps for the implicit Newton method
m_w: float
Particle water mass (1E-18 kg)
m_s: float
Particle solute mass (1E-18 kg)
w_s: float
Particle solute mass fraction = m_s/m_p, where m_p = m_s + m_w
R_p: float
Particle radius (microns)
T_p: float
Particle temperature (K)
rho_p: float
Particle mass density (kg/m^3)
T_amb: float
Ambient temperature (K)
p_amb: float
Ambient pressure (Pa)
e_s_amb: float
Ambient saturation pressure vapor-liquid (Pa)
L_v: float
Specific heat of vaporization (J/kg)
K: float
Thermal conductivity of the ambient air
D_v: float
Diffusion coefficient (m^2/s)
sigma_p: float
Particle surface tension (N/m)
solute_type: str
Particle solute material.
Either 'AS' (ammonium sulfate) or 'NaCl' (sodium chloride)
Returns
-------
mass_new - m_w: float
Change in particle water mass by condensation (1E-18 kg)
gamma0: float
Mass rate at the beginning of the Newton iterations
"""
m_w_effl = m_s * (w_s_max_AS_inv - 1.0)
if solute_type == "AS":
gamma0, dgamma_dm = mp.compute_mass_rate_and_derivative_AS(
m_w, m_s, w_s, R_p, T_p, rho_p,
T_amb, p_amb, S_amb, e_s_amb,
L_v, K, D_v, sigma_p)
elif solute_type == "NaCl":
gamma0, dgamma_dm = mp.compute_mass_rate_and_derivative_NaCl(
m_w, m_s, w_s, R_p, T_p, rho_p,
T_amb, p_amb, S_amb, e_s_amb,
L_v, K, D_v, sigma_p)
dt_sub_times_dgamma_dm = dt_sub * dgamma_dm
denom_inv = np.where(dt_sub_times_dgamma_dm < 0.9,
1.0 / (1.0 - dt_sub_times_dgamma_dm),
np.ones_like(dt_sub_times_dgamma_dm) * 10.0)
mass_new = np.maximum(m_w_effl, m_w + dt_sub * gamma0 * denom_inv)
for cnt in range(no_iter_impl_mass-1):
m_p = mass_new + m_s
w_s = m_s / m_p
rho = mat.compute_density_AS_solution(w_s, T_p)
R = mp.compute_radius_from_mass(m_p, rho)
sigma = mat.compute_surface_tension_AS(w_s,T_p)
if solute_type == "AS":
gamma, dgamma_dm = mp.compute_mass_rate_and_derivative_AS(
mass_new, m_s, w_s, R, T_p, rho,
T_amb, p_amb, S_amb, e_s_amb,
L_v, K, D_v, sigma)
elif solute_type == "NaCl":
gamma, dgamma_dm = mp.compute_mass_rate_and_derivative_NaCl(
mass_new, m_s, w_s, R, T_p, rho,
T_amb, p_amb, S_amb, e_s_amb,
L_v, K, D_v, sigma)
dt_sub_times_dgamma_dm = dt_sub * dgamma_dm
denom_inv = np.where(dt_sub_times_dgamma_dm < 0.9,
1.0 / (1.0 - dt_sub_times_dgamma_dm),
np.ones_like(dt_sub_times_dgamma_dm) * 10.0)
mass_new += ( dt_sub * gamma + m_w - mass_new) * denom_inv
mass_new = np.maximum( m_w_effl, mass_new )
return mass_new - m_w, gamma0
compute_dml_and_gamma_impl_Newton_full =\
njit()(compute_dml_and_gamma_impl_Newton_full_np)
#%% UPDATE m_w
def update_m_w_and_delta_m_l_impl_Newton_np(
grid_temperature, grid_pressure, grid_saturation,
grid_saturation_pressure, grid_thermal_conductivity,
grid_diffusion_constant, grid_heat_of_vaporization,
cells, m_w, m_s, xi, solute_type,
id_list, active_ids,
R_p, w_s, rho_p, T_p,
delta_m_l, dt_sub, no_iter_impl_mass):
"""Update particle water masses due to condensation/evaporation
Implicit Newton method with 'no_iter_impl_mass' iterations to evaluate
the amount of condensed/evaporated water of a cloud particle/droplet.
For the condensation mass rate, the formula
by Fukuta 1970, J. Atm. Sci. 27: 1160 is applied.
Parameters
----------
grid_temperature: ndarray, dtype=float
2D array holding the discretized temperature of the atmosphere
grid_pressure: ndarray, dtype=float
2D array holding the discretized pressure of the atmosphere
grid_saturation: ndarray, dtype=float
2D array holding the discretized saturation of the atmosphere
grid_saturation_pressure: ndarray, dtype=float
2D array holding the discretized saturation pressure of the atmosphere
grid_thermal_conductivity: ndarray, dtype=float
2D array holding the discretized thermal conductivity of the
ambient air in each grid cell
grid_diffusion_constant: ndarray, dtype=float
2D array holding the discretized diffusion coefficient of the
ambient air in each grid cell
grid_heat_of_vaporization: ndarray, dtype=float
2D array holding the discretized heat of vaporization
in each grid cell
cells: ndarray, dtype=int
2D array, holding the particle cell indices, i.e.
cells[0] = 1D array of horizontal indices
cells[1] = 1D array of vertical indices
(cells[0,n], cells[1,n]) gives the cell of particle 'n'
m_w: ndarray, dtype=float
1D array holding the particle water masses (1E-18 kg)
This array gets updated by the function.
m_s: ndarray, dtype=float
1D array holding the particle solute masses (1E-18 kg)
xi: ndarray, dtype=float
1D array holding the particle multiplicities
solute_type: str
Particle solute material.
Either 'AS' (ammonium sulfate) or 'NaCl' (sodium chloride)
id_list: ndarray, dtype=float
1D array holding the ordered particle IDs.
Other arrays, like 'm_w', 'm_s', 'xi' etc. refer to this list.
I.e. 'm_w[n]' is the water mass of particle with ID 'id_list[n]'
active_ids: ndarray, dtype=bool
1D mask-array. Each particle gets a flag 'True' or 'False', defining
if it still resides in the simulation domain or has already hit the
ground and is thereby removed from the simulation
R_p: ndarray, dtype=float
1D array holding the particle radii (microns)
w_s: ndarray, dtype=float
1D array holding the particle solute mass fractions
w_s = m_s / (m_s + m_w)
rho_p: ndarray, dtype=float
1D array holding the particle mass densities (kg/m^3)
T_p: ndarray, dtype=float
1D array holding the particle temperatures (kg/m^3)
delta_m_l: ndarray, dtype=float
2D array, sampling the change in water mass in each grid cell (kg)
dt_sub: float
Time step used for the implicit Newton method
no_iter_impl_mass: int
Number of iteration steps for the implicit Newton method
"""
delta_m_l.fill(0.0)
for ID in id_list[active_ids]:
cell = (cells[0,ID], cells[1,ID])
T_amb = grid_temperature[cell]
p_amb = grid_pressure[cell]
S_amb = grid_saturation[cell]
e_s_amb = grid_saturation_pressure[cell]
L_v = grid_heat_of_vaporization[cell]
K = grid_thermal_conductivity[cell]
D_v = grid_diffusion_constant[cell]
sigma_p = mat.compute_surface_tension_solution(w_s[ID], T_p[ID],
solute_type)
dm, gamma = compute_dml_and_gamma_impl_Newton_full(
dt_sub, no_iter_impl_mass, m_w[ID], m_s[ID],
w_s[ID], R_p[ID],
T_p[ID], rho_p[ID],
T_amb, p_amb, S_amb, e_s_amb, L_v, K, D_v, sigma_p,
solute_type)
m_w[ID] += dm
delta_m_l[cell] += dm * xi[ID]
delta_m_l *= 1.0E-18
update_m_w_and_delta_m_l_impl_Newton =\
njit()(update_m_w_and_delta_m_l_impl_Newton_np)
#%% PARTICLE PROPAGATION ONE SUBLOOP STEP
def propagate_particles_subloop_step_np(grid_scalar_fields, grid_mat_prop,
grid_velocity,
grid_no_cells, grid_ranges, grid_steps,
pos, vel, cells, rel_pos, m_w, m_s, xi,
water_removed, id_list, active_ids,
T_p, solute_type,
delta_m_l,
dt_sub, dt_sub_pos,
no_iter_impl_mass, g_set):
"""Update particle positions, velocities and masses, excluding collisions
One advection step is divided into two subsequent subloops for the
particle-ambience interactions with condensation time step 'dt_sub'.
'dt_sub' is used for calculation of the changes in velocity by dynamic
forces and mass by condensation/evaporation. 'dt_sub_pos' is used when
updating the particles positions. This allows adjustment for overlapping
schemes like Velocity Verlet. Usually dt_sub = dt_sub_pos.
Parameters
----------
grid_scalar_fields: ndarray, dtype=float
Array components are 2D arrays of the discretized scalar fields
grid_scalar_fields[0] = temperature
grid_scalar_fields[1] = pressure
grid_scalar_fields[2] = potential_temperature
grid_scalar_fields[3] = mass_density_air_dry
grid_scalar_fields[4] = mixing_ratio_water_vapor
grid_scalar_fields[5] = mixing_ratio_water_liquid
grid_scalar_fields[6] = saturation
grid_scalar_fields[7] = saturation_pressure
grid_scalar_fields[8] = mass_dry_inv
grid_scalar_fields[9] = rho_dry_inv
grid_mat_prop: ndarray, dtype=float
Array components are 2D arrays of the material properties in the
grid cells.
All material property grids get updated based on the scalar fields.
grid_mat_prop[0] = thermal_conductivity
grid_mat_prop[1] = diffusion_constant
grid_mat_prop[2] = heat_of_vaporization
grid_mat_prop[3] = surface_tension
grid_mat_prop[4] = specific_heat_capacity
grid_mat_prop[5] = viscosity
grid_mat_prop[6] = mass_density_fluid
grid_velocity: ndarray, dtype=float
Discretized velocity field (m/s) of dry air.
grid_vel[0] is a 2D array holding the x-components of the vel. field
projected onto the grid cell surface centers.
grid_vel[1] is a 2D array holding the z-components of the vel. field
projected onto the grid cell surface centers.
grid_no_cells: ndarray, dtype=int
grid_no_cells[0] = number of grid cells in x (horizontal)
grid_no_cells[1] = number of grid cells in z (vertical)
grid_ranges: ndarray, dtype=float
2D array holding the coordinates of the domain box in two dimensions
grid_ranges[0] = [x_min, x_max]
grid_ranges[1] = [z_min, z_max]
grid_steps: ndarray, dtype=float