-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.py
More file actions
2447 lines (2098 loc) · 90.6 KB
/
Copy pathinit.py
File metadata and controls
2447 lines (2098 loc) · 90.6 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 -*-
"""
Created on Mon Apr 29 11:31:49 2019
@author: jdesk
"""
#%%
import numpy as np
import math
# import matplotlib.pyplot as plt
import sys
from numba import njit
import constants as c
from grid import Grid
from grid import interpolate_velocity_from_cell_bilinear
from microphysics import compute_mass_from_radius_jit
from microphysics import compute_initial_mass_fraction_solute_m_s_NaCl
from microphysics import compute_initial_mass_fraction_solute_m_s_AS, \
compute_dml_and_gamma_impl_Newton_full_NaCl,\
compute_dml_and_gamma_impl_Newton_full_AS,\
compute_R_p_w_s_rho_p_NaCl, \
compute_R_p_w_s_rho_p_AS, \
compute_surface_tension_NaCl, \
compute_surface_tension_AS
# compute_mass_from_radius_vec,\
# compute_radius_from_mass_vec,\
# compute_density_particle,\
# compute_initial_mass_fraction_solute_NaCl,\
from atmosphere import compute_kappa_air_moist,\
compute_diffusion_constant,\
compute_thermal_conductivity_air,\
compute_heat_of_vaporization,\
compute_saturation_pressure_vapor_liquid,\
compute_pressure_vapor,\
epsilon_gc, compute_surface_tension_water,\
kappa_air_dry,\
compute_beta_without_liquid
from file_handling import save_grid_and_particles_full
#from generate_SIP_ensemble_dst import gen_mass_ensemble_weights_SinSIP_lognormal
#from generate_SIP_ensemble_dst import gen_mass_ensemble_weights_SinSIP_lognormal_grid
from generate_SIP_ensemble_dst import \
gen_mass_ensemble_weights_SinSIP_lognormal_z_lvl
#%%
# IN WORK: what do you need from grid.py?
# from grid import *
# from physical_relations_and_constants import *
# stream function
pi_inv = 1.0/np.pi
def compute_stream_function_Arabas(x_, z_, j_max_, x_domain_, z_domain_):
return -j_max_ * x_domain_ * pi_inv * np.sin(np.pi * z_ / z_domain_)\
* np.cos( 2 * np.pi * x_ / x_domain_)
# dry mass flux j_d = rho_d * vel
# Z = domain height z
# X = domain width x
# X_over_Z = X/Z
# k_z = pi/Z
# k_x = 2 * pi / X
# j_max = Amplitude
def compute_mass_flux_air_dry_Arabas( x_, z_, j_max_, k_x_, k_z_, X_over_Z_ ):
j_x = j_max_ * X_over_Z_ * np.cos(k_x_ * x_) * np.cos(k_z_ * z_ )
j_z = 2 * j_max_ * np.sin(k_x_ * x_) * np.sin(k_z_ * z_)
return j_x, j_z
#def compute_mass_flux_air_dry_x( x_, z_, j_max_, k_x_, k_z_, X_over_Z_ ):
# return j_max_ * X_over_Z_ * np.cos(k_x_ * x_) * np.cos(k_z_ * z_ )
#def compute_mass_flux_air_dry_z( x_, z_, j_max_, k_x_, k_z_, X_over_Z_ ):
# return 2 * j_max_ * np.sin(k_x_ * x_) * np.sin(k_z_ * z_)
#def mass_flux_air_dry(x_, z_):
# return compute_mass_flux_air_dry_Arabas(x_, z_, j_max, k_x, k_z, X_over_Z)
#
#def mass_flux_air_dry_x(x_, z_):
# return compute_mass_flux_air_dry_x(x_, z_, j_max, k_x, k_z, X_over_Z)
#def mass_flux_air_dry_z(x_, z_):
# return compute_mass_flux_air_dry_z(x_, z_, j_max, k_x, k_z, X_over_Z)
def compute_initial_mass_flux_air_dry_kinematic_2D_ICMW_2012_case1( grid_,
j_max_ ):
X = grid_.sizes[0]
Z = grid_.sizes[1]
k_x = 2.0 * np.pi / X
k_z = np.pi / Z
X_over_Z = X / Z
# j_max = 0.6 # (m/s)*(m^3/kg)
# grid only has corners as positions...
vel_pos_u = [grid_.corners[0], grid_.corners[1] + 0.5 * grid_.steps[1]]
vel_pos_w = [grid_.corners[0] + 0.5 * grid_.steps[0], grid_.corners[1]]
j_x = compute_mass_flux_air_dry_Arabas( *vel_pos_u, j_max_,
k_x, k_z, X_over_Z )[0]
j_z = compute_mass_flux_air_dry_Arabas( *vel_pos_w, j_max_,
k_x, k_z, X_over_Z )[1]
return j_x, j_z
# j_max_base = the appropriate value for a grid of 1500 x 1500 m^2
def compute_j_max(j_max_base, grid):
return np.sqrt( grid.sizes[0] * grid.sizes[0]
+ grid.sizes[1] * grid.sizes[1] ) \
/ np.sqrt(2.0 * 1500.0 * 1500.0)
####
#%% DISTRIBUTIONS
# par[0] = mu
# par[1] = sigma
two_pi_sqrt = math.sqrt(2.0 * math.pi)
def dst_normal(x, par):
return np.exp( -0.5 * ( ( x - par[0] ) / par[1] )**2 ) \
/ (two_pi_sqrt * par[1])
# par[0] = mu^* = geometric mean of the log-normal dist
# par[1] = ln(sigma^*) = lognat of geometric std dev of log-normal dist
def dst_log_normal(x, par):
# sig = math.log(par[1])
f = np.exp( -0.5 * ( np.log( x / par[0] ) / par[1] )**2 ) \
/ ( x * math.sqrt(2 * math.pi) * par[1] )
return f
def dst_expo_np(x,k):
return np.exp(-x*k) * k
dst_expo = njit()(dst_expo_np)
def num_int_np(func, x0, x1, steps=1E5):
dx = (x1 - x0) / steps
x = x0
intl = 0.0
# cnt = 0
while (x < x1):
intl += dx * func(x)
x += dx
# cnt += 1
return intl
# num_int = njit()(num_int_np)
def num_int_expo_np(x0, x1, k, steps=1E5):
dx = (x1 - x0) / steps
x = x0
intl = 0.0
f1 = dst_expo(x,k)
# cnt = 0
while (x < x1):
f2 = dst_expo(x + 0.5*dx, k)
f3 = dst_expo(x + dx, k)
# intl_bef = intl
intl += 0.1666666666667 * dx * (f1 + 4 * f2 + f3)
x += dx
f1 = f3
# cnt += 1
# intl += dx * x * dst_expo(x,k)
# x += dx
# cnt += 1
return intl
num_int_expo = njit()(num_int_expo_np)
# def num_int_expo_np(x0, x1, k, steps=1.0E5):
# dx = (x1 - x0) / steps
# x = x0
# intl = 0.0
# # cnt = 0
# while (x < x1):
# intl += dx * dst_expo(x,k)
# x += dx
# # cnt += 1
# return intl
# num_int_expo = njit()(num_int_expo_np)
def num_int_expo_mean_np(x0, x1, k, steps=1E5):
dx = (x1 - x0) / steps
x = x0
intl = 0.0
f1 = dst_expo(x,k) * x
# cnt = 0
while (x < x1):
f2 = dst_expo(x + 0.5*dx, k) * (x + 0.5*dx)
f3 = dst_expo(x + dx, k) * (x + dx)
# intl_bef = intl
intl += 0.1666666666667 * dx * (f1 + 4 * f2 + f3)
x += dx
f1 = f3
# cnt += 1
# intl += dx * x * dst_expo(x,k)
# x += dx
# cnt += 1
return intl
num_int_expo_mean = njit()(num_int_expo_mean_np)
def num_int_impl_right_border(func, x0, intl_value, dx, cnt_lim=1E7):
dx0 = dx
x = x0
intl = 0.0
cnt = 0
f1 = func(x)
print("dx0 =", dx0)
while (intl < intl_value and cnt < cnt_lim):
# if cnt % 100 == 0:
# dx = dx0
# while (np.abs((func(x0+dx)-func(x0))/func(x0)) < 1.0E-6) :
# dx *= 2.0
# while (np.abs((func(x0+dx)-func(x0))/func(x0)) > 1.0E-6) :
# dx *= 0.5
# dp_lim = 1.0E-5
# if cnt % 100 == 0:
# dx = dx0
# if f1*dx > dp_lim:
# dx = dp_lim/f1
# print("cnt=",cnt,"dx=",dx)
f2 = func(x + 0.5*dx)
f3 = func(x + dx)
intl_bef = intl
intl += 0.1666666666667 * dx * (f1 + 4 * f2 + f3)
x += dx
f1 = f3
cnt += 1
# print(f"{cnt:.2e}")
# if x > dx:
# x = x - dx
# elif x > 0.5 * dx:
# x = x - 0.5 * dx
# else: x = 0.0
# return x + 0.5 *dx
return x - dx + dx * (intl_value - intl_bef)/(intl - intl_bef)
def num_int_expo_impl_right_border_np(x0, intl_value, dx, k, cnt_lim=1E7):
# dx0 = dx
x = x0
intl = 0.0
cnt = 0
f1 = dst_expo(x,k)
# print("dx0 =", dx0)
while (intl < intl_value and cnt < cnt_lim):
f2 = dst_expo(x + 0.5*dx, k)
f3 = dst_expo(x + dx, k)
intl_bef = intl
intl += 0.1666666666667 * dx * (f1 + 4 * f2 + f3)
x += dx
f1 = f3
cnt += 1
return x - dx + dx * (intl_value - intl_bef)/(intl - intl_bef)
num_int_expo_impl_right_border = njit()(num_int_expo_impl_right_border_np)
def prob_exp(x,k):
return 1.0 - np.exp(-k*x)
def compute_right_border_impl_exp(x0, intl_value, k):
return -1.0/k * np.log( np.exp(-k * x0) - intl_value )
#%% STOCHASTICS
# input: prob = [p1, p2, p3, ...] = quantile probab. -> need to set no_q = None
# OR (if prob = None)
# input: no_q = number of quantiles (including prob = 1.0)
# returns N-1 quantiles q with given (prob)
# or equal probability distances (no_q):
# N = 4 -> P(X < q[0]) = 1/4, P(X < q[1]) = 2/4, P(X < q[2]) = 3/4
# this function was checked with the std normal distribution
def compute_quantiles(func, par, x0, x1, dx, prob, no_q=None):
# probabilities of the quantiles
if par is not None:
f = lambda x : func(x, par)
else: f = func
if prob is None:
prob = np.linspace(1.0/no_q,1.0,no_q)[:-1]
print ("quantile probabilities = ", prob)
intl = 0.0
x = x0
q = []
cnt = 0
for i,p in enumerate(prob):
while (intl < p and p < 1.0 and x <= x1 and cnt < 1E8):
intl += dx * f(x)
x += dx
cnt += 1
# the quantile value is somewhere between x - dx and x
# q.append(x)
# q.append(x - 0.5 * dx)
q.append(max(x - dx,x0))
print ("quantile values = ", q)
return q, prob
# for a given grid with grid center positions grid_centers[i,j]:
# create random radii rad[i,j] = array of shape (Nx, Ny, no_spc)
# and the corresp. values of the distribution p[i,j]
# input:
# p_min, p_max: quantile probs to cut off e.g. (0.001,0.999)
# no_spc: number of super-droplets per cell (scalar!)
# dst: distribution to use
# par: params of the distribution par -> "None" possible if dst = dst(x)
# r0, r1, dr: parameters for the numerical integration to find the cutoffs
def generate_random_radii_monomodal(grid, dst, par, no_spc, p_min, p_max,
r0, r1, dr, seed, setseed = True):
if setseed: np.random.seed(seed)
if par is not None:
func = lambda x : dst(x, par)
else: func = dst
qs, Ps = compute_quantiles(func, None, r0, r1, dr, [p_min, p_max], None)
r_min = qs[0]
r_max = qs[1]
bins = np.linspace(r_min, r_max, no_spc+1)
rnd = []
for i,b in enumerate(bins[0:-1]):
# we need 1 radius value for each bin for each cell
rnd.append( np.random.uniform(b, bins[i+1], grid.no_cells_tot) )
rnd = np.array(rnd)
rnd = np.transpose(rnd)
shape = np.hstack( [np.array(np.shape(grid.centers)[1:]), [no_spc]] )
rnd = np.reshape(rnd, shape)
weights = func(rnd)
for p_row in weights:
for p_cell in p_row:
p_cell /= np.sum(p_cell)
return rnd, weights #, bins
# no_spc = super particles per cell
# creates no_spc random radii per cell and the no_spc weights per cell
# where sum(weight_i) = 1.0
# the weights are drawn from a normal distribution with mu = 1.0, sigma = 0.2
# and rejected if weight < 0. The weights are then normalized such that sum = 1
# par = (mu*, ln(sigma*)), where mu* and sigma* are the
# GEOMETRIC expectation value and standard dev. of the lognormal distr. resp.
def generate_random_radii_monomodal_lognorm(grid, par, no_spc,
seed, setseed = True):
if setseed: np.random.seed(seed)
no_spt = grid.no_cells_tot * no_spc
# draw random numbers from log normal distr. by this procedure
Rs = np.random.normal(0.0, par[1], no_spt)
Rs = np.exp(Rs)
Rs *= par[0]
# draw random weights
weights = np.abs(np.random.normal(1.0, 0.2, no_spt))
# bring to shape Rs[i,j,k], where Rs[i,j] = arr[k] k = 0...no_spc-1
shape = np.hstack( [np.array(np.shape(grid.centers)[1:]), [no_spc]] )
Rs = np.reshape(Rs, shape)
weights = np.reshape(weights, shape)
for p_row in weights:
for p_cell in p_row:
p_cell /= np.sum(p_cell)
return Rs, weights #, bins
# no_spcm MUST be a list/array with [no_1, no_2, .., no_N], N = number of modes
# no_spcm[k] = 0 is possible for some mode k. Then no particles are generated
# for this mode...
# par MUST be a list with [par1, par2, .., parN]
# where par1 = [p11, p12, ...] , par2 = [...] etc
# everything else CAN be a list or a scalar single float/int
# if given as scalar, all modes will use the same value
# the seed is set at least once
# reseed = True will reset the seed everytime for every new mode with the value
# given in the seed list, it can also be used with seed being a single scalar
# about the seeds:
# using np.random.seed(seed) in a function sets the seed globaly
# after leaving the function, the seed remains the set seed
def generate_random_radii_multimodal(grid, dst, par, no_spcm, p_min, p_max,
r0, r1, dr, seed, reseed = False):
no_modes = len(no_spcm)
if not isinstance(p_min, (list, tuple, np.ndarray)):
p_min = [p_min] * no_modes
if not isinstance(p_max, (list, tuple, np.ndarray)):
p_max = [p_max] * no_modes
if not isinstance(dst, (list, tuple, np.ndarray)):
dst = [dst] * no_modes
if not isinstance(r0, (list, tuple, np.ndarray)):
r0 = [r0] * no_modes
if not isinstance(r1, (list, tuple, np.ndarray)):
r1 = [r1] * no_modes
if not isinstance(dr, (list, tuple, np.ndarray)):
dr = [dr] * no_modes
if not isinstance(seed, (list, tuple, np.ndarray)):
seed = [seed] * no_modes
rad = []
weights = []
print(p_min)
# set seed always once
setseed = True
for k in range(no_modes):
if no_spcm[k] > 0:
r, w = generate_random_radii_monomodal(
grid, dst[k], par[k], no_spcm[k], p_min[k], p_max[k],
r0[k], r1[k], dr[k], seed[k], setseed)
rad.append( r )
weights.append( w )
setseed = reseed
# we need the different modes separately, because they
# are weighted with different total concentrations
# if len(rad)>1:
# rad = np.concatenate(rad, axis = 2)
# weights = np.concatenate(weights, axis = 2)
return np.array(rad), np.array(weights)
#
def generate_random_radii_multimodal_lognorm(grid, par, no_spcm,
seed, reseed = False):
no_modes = len(no_spcm)
if not isinstance(seed, (list, tuple, np.ndarray)):
seed = [seed] * no_modes
rad = []
weights = []
# set seed always once
setseed = True
for k in range(no_modes):
if no_spcm[k] > 0:
r, w = generate_random_radii_monomodal_lognorm(
grid, par[k], no_spcm[k], seed[k], setseed)
rad.append( r )
weights.append( w )
setseed = reseed
# we need the different modes separately, because they
# are weighted with different total concentrations
# if len(rad)>1:
# rad = np.concatenate(rad, axis = 2)
# weights = np.concatenate(weights, axis = 2)
return np.array(rad), np.array(weights)
# no_spcm = super-part/cell in modes [N_mode1_per_cell, N_mode2_per_cell, ...]
# no_spc = # super-part/cell
# no_spt = # SP total in full domain
# returns positions of particles of shape (2, no_spt)
def generate_random_positions(grid, no_spc, seed, set_seed = False):
if isinstance(no_spc, (list, tuple, np.ndarray)):
no_spt = np.sum(no_spc)
else:
no_spt = grid.no_cells_tot * no_spc
no_spc = np.ones(grid.no_cells, dtype = np.int64) * no_spc
if set_seed:
np.random.seed(seed)
rnd_x = np.random.rand(no_spt)
rnd_z = np.random.rand(no_spt)
dx = grid.steps[0]
dz = grid.steps[1]
x = []
z = []
cells = [[],[]]
n = 0
for j in range(grid.no_cells[1]):
z0 = grid.corners[1][0,j]
for i in range(grid.no_cells[0]):
x0 = grid.corners[0][i,j]
for k in range(no_spc[i,j]):
x.append(x0 + dx * rnd_x[n])
z.append(z0 + dz * rnd_z[n])
cells[0].append(i)
cells[1].append(j)
n += 1
pos = np.array([x, z])
rel_pos = np.array([rnd_x, rnd_z])
return pos, rel_pos, np.array(cells)
## no_spcm = super-part/cell in modes [N_mode1_per_cell, N_mode2_per_cell, ...]
## no_spc = # super-part/cell
## no_spt = # SP total in full domain
## returns positions of particles of shape (2, no_spt)
#def generate_random_positions_cells(grid, cells, seed, set_seed = False):
# if isinstance(no_spc, (list, tuple, np.ndarray)):
# no_spt = np.sum(no_spc)
# else:
# no_spt = grid.no_cells_tot * no_spc
# no_spc = np.ones(grid.no_cells, dtype = np.int64) * no_spc
# if set_seed:
# np.random.seed(seed)
# rnd_x = np.random.rand(no_spt)
# rnd_z = np.random.rand(no_spt)
# dx = grid.steps[0]
# dz = grid.steps[1]
# x = []
# z = []
# cells = [[],[]]
# n = 0
# for j in range(grid.no_cells[1]):
# z0 = grid.corners[1][0,j]
# for i in range(grid.no_cells[0]):
# x0 = grid.corners[0][i,j]
# for k in range(no_spc[i,j]):
# x.append(x0 + dx * rnd_x[n])
# z.append(z0 + dz * rnd_z[n])
# cells[0].append(i)
# cells[1].append(j)
# n += 1
# pos = np.array([x, z])
# rel_pos = np.array([rnd_x, rnd_z])
# return pos, rel_pos, np.array(cells)
#%%
#grid_ranges = [[0.,1500.], [0.,1500.]]
#grid_steps = [150.,150.]
#dy = 1.0
#
#grid = Grid(grid_ranges, grid_steps, dy)
#
#no_spc = np.random.randint(5,10,grid.no_cells)
#
#seed = 3711
#
#pos, rel_pos, cells = generate_random_positions(grid, no_spc, seed, True)
#%% GENERATE SIP ENSEMBLES
### NEW APPROACH AFTER UNTERSTRASSER CODE
#############################################################################
### OLD APPROACH
# par = "rate" parameter "k" of the expo distr: k*exp(-k*m) (in 10^18 kg)
# no_rpc = number of real particles in cell
def generate_SIP_ensemble_expo_SingleSIP_weak_threshold(
par, no_rpc, r_critmin, m_high_by_m_low, kappa,
eta, seed, setseed):
if setseed: np.random.seed(seed)
m_low = compute_mass_from_radius_jit(r_critmin,
c.mass_density_water_liquid_NTP)
# m_high = num_int_expo_impl_right_border(0.0, p_max, 1.0/par*0E-6, par,
# cnt_lim=1E8)
m_high = m_low * m_high_by_m_low
# since we consider only particles with m > m_low, the total number of
# placed particles and the total placed mass will be underestimated
# to fix this, we could adjust the PDF
# by e.g. one of the two possibilities:
# 1. decrease the total number of particles and thereby the total pt conc.
# 2. keep the total number of particles, and thus increase the PDF
# in the interval [m_low, m_high]
# # For 1.: decrease the total number of particles by multiplication
# # with factor num_int_expo_np(m_low, m_high, par, steps=1.0E6)
# print(no_rpc)
# no_rpc *= num_int_expo(m_low, m_high, par, steps=1.0E6)
# for 2.:
# increase the total number of
# real particle "no_rpc" by 1.0 / int_(m_low)^(m_high)
# no_rpc *= 1.0/num_int_expo(m_low, m_high, par, steps=1.0E6)
kappa_inv = 1.0/kappa
bin_fac = 10**kappa_inv
masses = []
xis = []
bins = [m_low]
no_rp_set = 0
no_sp_set = 0
bin_n = 0
m = np.random.uniform(m_low/2, m_low)
xi = dst_expo(m,par) * m_low * no_rpc
masses.append(m)
xis.append(xi)
no_rp_set += xi
no_sp_set += 1
m_left = m_low
# m = 0.0
# print("no_rpc =", no_rpc)
# while(no_rp_set < no_rpc and m < m_high):
while(m < m_high):
# m_right = m_left * 10**kappa_inv
m_right = m_left * bin_fac
# print("missing particles =", no_rpc - no_rp_set)
# print("m_left, m_right, m_high")
# print(bin_n, m_left, m_right, m_high)
m = np.random.uniform(m_left, m_right)
# print("m =", m)
# we do not round to integer here, because of the weak threshold below
# the rounding is done afterwards
xi = dst_expo(m,par) * (m_right - m_left) * no_rpc
# xi = int((dst_expo(m,par) * (m_right - m_left) * no_rpc))
# if xi < 1 : xi = 1
# if no_rp_set + xi > no_rpc:
# xi = no_rpc - no_rp_set
# print("no_rpc reached")
# print("xi =", xi)
masses.append(m)
xis.append(xi)
no_rp_set += xi
no_sp_set += 1
m_left = m_right
bins.append(m_right)
bin_n += 1
xis = np.array(xis)
masses = np.array(masses)
xi_max = xis.max()
# print("xi_max =", f"{xi_max:.2e}")
xi_critmin = int(xi_max * eta)
if xi_critmin < 1: xi_critmin = 1
# print("xi_critmin =", xi_critmin)
for bin_n,xi in enumerate(xis):
if xi < xi_critmin:
# print("")
p = xi / xi_critmin
if np.random.rand() >= p:
xis[bin_n] = 0
else: xis[bin_n] = xi_critmin
ind = np.nonzero(xis)
xis = xis[ind].astype(np.int64)
masses = masses[ind]
# now, some bins are empty, thus the total number sum(xis) is not right
# moreover, the total mass sum(masses*xis) is not right ...
# FIRST: test, how badly the total number and total mass of the cell
# is violated, if this is bad:
# -> create a number of particles, such that the total number is right
# and assign the average mass to it
# then reweight all of the masses such that the total mass is right.
return masses, xis, m_low, m_high, bins
# par = "rate" parameter "k" of the expo distr: k*exp(-k*m) (in 10^18 kg)
# no_rpc = number of real particles in cell
# NON INTERGER WEIGHTS ARE POSSIBLE A SIN UNTERSTRASSER 2017
def generate_SIP_ensemble_expo_SingleSIP_weak_threshold_nonint(
par, no_rpc, r_critmin=0.6, m_high_by_m_low=1.0E6, kappa=40,
eta=1.0E-9, seed=4711, setseed = True):
if setseed: np.random.seed(seed)
m_low = compute_mass_from_radius_jit(r_critmin,
c.mass_density_water_liquid_NTP)
# m_high = num_int_expo_impl_right_border(0.0, p_max, 1.0/par*0E-6, par,
# cnt_lim=1E8)
m_high = m_low * m_high_by_m_low
# since we consider only particles with m > m_low, the total number of
# placed particles and the total placed mass will be underestimated
# to fix this, we could adjust the PDF
# by e.g. one of the two possibilities:
# 1. decrease the total number of particles and thereby the total pt conc.
# 2. keep the total number of particles, and thus increase the PDF
# in the interval [m_low, m_high]
# # For 1.: decrease the total number of particles by multiplication
# # with factor num_int_expo_np(m_low, m_high, par, steps=1.0E6)
# print(no_rpc)
# no_rpc *= num_int_expo(m_low, m_high, par, steps=1.0E6)
# for 2.:
# increase the total number of
# real particle "no_rpc" by 1.0 / int_(m_low)^(m_high)
# no_rpc *= 1.0/num_int_expo(m_low, m_high, par, steps=1.0E6)
kappa_inv = 1.0/kappa
bin_fac = 10**kappa_inv
masses = []
xis = []
bins = [m_low]
no_rp_set = 0
no_sp_set = 0
bin_n = 0
m = np.random.uniform(m_low/2, m_low)
xi = dst_expo(m,par) * m_low * no_rpc
masses.append(m)
xis.append(xi)
no_rp_set += xi
no_sp_set += 1
m_left = m_low
# m = 0.0
# print("no_rpc =", no_rpc)
# while(no_rp_set < no_rpc and m < m_high):
while(m < m_high):
# m_right = m_left * 10**kappa_inv
m_right = m_left * bin_fac
# print("missing particles =", no_rpc - no_rp_set)
# print("m_left, m_right, m_high")
# print(bin_n, m_left, m_right, m_high)
m = np.random.uniform(m_left, m_right)
# print("m =", m)
# we do not round to integer here, because of the weak threshold below
# the rounding is done afterwards
xi = dst_expo(m,par) * (m_right - m_left) * no_rpc
# xi = int((dst_expo(m,par) * (m_right - m_left) * no_rpc))
# if xi < 1 : xi = 1
# if no_rp_set + xi > no_rpc:
# xi = no_rpc - no_rp_set
# print("no_rpc reached")
# print("xi =", xi)
masses.append(m)
xis.append(xi)
no_rp_set += xi
no_sp_set += 1
m_left = m_right
bins.append(m_right)
bin_n += 1
xis = np.array(xis)
masses = np.array(masses)
xi_max = xis.max()
# print("xi_max =", f"{xi_max:.2e}")
# xi_critmin = int(xi_max * eta)
xi_critmin = xi_max * eta
# if xi_critmin < 1: xi_critmin = 1
# print("xi_critmin =", xi_critmin)
valid_ind = []
for bin_n,xi in enumerate(xis):
if xi < xi_critmin:
# print("")
p = xi / xi_critmin
if np.random.rand() >= p:
xis[bin_n] = 0
else:
xis[bin_n] = xi_critmin
valid_ind.append(bin_n)
else: valid_ind.append(bin_n)
# ind = np.nonzero(xis)
# xis = xis[ind].astype(np.int64)
valid_ind = np.array(valid_ind)
xis = xis[valid_ind]
masses = masses[valid_ind]
# now, some bins are empty, thus the total number sum(xis) is not right
# moreover, the total mass sum(masses*xis) is not right ...
# FIRST: test, how badly the total number and total mass of the cell
# is violated, if this is bad:
# -> create a number of particles, such that the total number is right
# and assign the average mass to it
# then reweight all of the masses such that the total mass is right.
return masses, xis, m_low, m_high, bins
@njit()
def generate_SIP_ensemble_expo_SingleSIP_weak_threshold_nonint2(
par, no_rpc, r_critmin=0.6, m_high_by_m_low=1.0E6, kappa=40,
eta=1.0E-9, seed=4711, setseed = True):
bin_factor = 10**(1.0/kappa)
m_low = compute_mass_from_radius_jit(r_critmin,c.mass_density_water_liquid_NTP)
m_left = m_low
# l_max = kappa * log_10(m_high/m_low)
l_max = int(kappa * np.log10(m_high_by_m_low)) + 1
rnd = np.random.rand( l_max )
# cnt = 0
masses = np.zeros(l_max, dtype = np.float64)
xis = np.zeros(l_max, dtype = np.float64)
bins = np.zeros(l_max+1, dtype = np.float64)
bins[0] = m_left
for l in range(l_max):
m_right = m_left * bin_factor
bins[l+1] = m_right
dm = m_right - m_left
m = m_left + dm * rnd[l]
masses[l] = m
xis[l] = no_rpc * dm * dst_expo(m, par)
m_left = m_right
# cnt += 1
xi_max = xis.max()
xi_critmin = xi_max * eta
switch = np.ones(l_max, dtype=np.int64)
for l in range(l_max):
if xis[l] < xi_critmin:
if np.random.rand() < xis[l] / xi_critmin:
xis[l] = xi_critmin
else: switch[l] = 0
ind = np.nonzero(switch)[0]
xis = xis[ind]
masses = masses[ind]
return masses, xis, m_low, bins
# no_spc is the intended number of super particles per cell,
# this will right on average, but will vary due to the random assigning
# process of the xi_i
# m0, m1, dm: parameters for the numerical integration to find the cutoffs
# and for the numerical integration of integrals
# dV = volume size of the cell (in m^3)
# n0: initial particle number distribution (in 1/m^3)
# IN WORK: make the bin size smaller for low masses to get
# finer resolution here...
# -> "steer against" the expo PDF for low m -> something in between
# we need higher resolution in very small radii (Unterstrasser has
# R_min = 0.8 mu
# at least need to go down to 1 mu (resolution there...)
# eps = parameter for the bin linear spreading:
# bin_size(m = m_high) = eps * bin_size(m = m_low)
# @njit()
def generate_SIP_ensemble_expo_my_xi_rnd(par, no_spc, no_rpc,
total_mass_in_cell,
p_min, p_max, eps,
m0, m1, dm, seed, setseed = True):
if setseed: np.random.seed(seed)
# if par is not None:
# func = lambda x : dst(x, par)
# else: func = dst
# define m_low, m_high by probability threshold p_min
# m_thresh = [m_low, m_high]
# (m_low, m_high), Ps = compute_quantiles(func, None, m0, m1, dm,
# [p_min, p_max], None)
m_low = 0.0
m_high = num_int_expo_impl_right_border(m_low,p_max, dm, par, 1.0E8)
# if p_min == 0:
# m_low = 0.0
# estimate value for dm, which is the bin size of the hypothetical
# bin assignment, which is approximated by the random process:
# the bin mean size must be adjusted by ~np.log10(eps)
# to get to a SIP number in the cell of about the intended number
# if the reweighting is not done, the SIP number will be much larger
# due to small bins for low masses
bin_size_mean = (m_high - m_low) / no_spc * np.log10(eps)
# eps = 10
a = bin_size_mean * (eps - 1) / (m_high * 0.5 * (eps + 1))
b = bin_size_mean / (0.5 * (eps + 1))
# no of real particle cell
# no_rpc = dV*n0
# the current position of the left bin border
m_left = m_low
# generate list of masses and multiplicities
masses = []
xis = []
# no of particles placed:
no_pt = 0
# let f(m) be the PDF!! (m can be the mass or the radius, depending,
# which distr. is given), NOTE that f(m) is not the number concentration..
pt_n = 0
while no_pt < no_rpc:
### i) determine the next xi_mean by
# integrating xi_mean = no_rpc * int_(m_left)^(m_left+dm) dm f(m)
# print(pt_n, "m_left=", m_left)
# m = m_left
bin_size = a * m_left + b
m_right = m_left + bin_size
intl = num_int_expo(m_left, m_right, par, steps=1.0E5)
# intl = 0.0
# cnt = 0
# while (m < m_right and cnt < 1E6):
# intl += dm * func(m)
# m += dm
# cnt += 1
# if cnt == 1E6:
# print(pt_n, "cnt=1E6")
xi_mean = no_rpc * intl
# print(pt_n, "xi_mean=", xi_mean)
### ii) draw xi from distribution:
# try here normal distribution if xi_mean > 10
# else Poisson
# with parms: mu = xi_mean, sigma = sqrt(xi_mean)
if xi_mean > 10:
# xi = np.random.normal(xi_mean, np.sqrt(xi_mean))
xi = np.random.normal(xi_mean, 0.2*xi_mean)
else:
xi = np.random.poisson(xi_mean)
xi = int(math.ceil(xi))
if xi <= 0: xi = 1
if no_pt + xi >= no_rpc:
xi = no_rpc - no_pt
# last = True
M_sys = np.sum( np.array(xis)*np.array(masses) )
M_should = no_rpc * num_int_expo_mean(0.0,m_left,par,1.0E7)
masses = [m * M_should / M_sys for m in masses]
# M = p_max * total_mass_in_cell - M
M_diff = total_mass_in_cell - M_should
if M_diff <= 0.0:
M_diff = 1.0/par
# if M_diff <= 0.0:
# M_diff = total_mass_in_cell - M_should
# xis = np.array(xis, dtype=np.int64)
# masses = np.array(masses)
# masses *= p_max*total_mass_in_cell/M_sys
# masses = [m*p_max*total_mass_in_cell/M_sys for m in masses]
# M_sys = p_max*total_mass_in_cell
# M_diff = total_mass_in_cell * (1 - p_max)
# else:
# mu = max(p_max*M/xi,m_left)
mu = M_diff/xi
if mu <= 1.02*masses[pt_n-1]:
xi_sum = xi + xis[pt_n-1]
m_sum = xi*mu + xis[pt_n-1] * masses[pt_n-1]
xis[pt_n-1] = xi_sum
masses[pt_n-1] = m_sum / xi_sum
no_pt += xi
# print(pt_n, xi, mu, no_pt)
else:
masses.append(mu)
xis.append(xi)
no_pt += xi
# print(pt_n, xi, mu, no_pt)
pt_n += 1
# masses.append(mu)
# xis.append(xi)
# no_pt += xi
# print(pt_n, xi, mu, no_pt)
# pt_n += 1
# xi = no_rpc - no_pt
# # last = True
# M_sys = np.sum( np.array(xis)*np.array(masses) )
# # M = p_max * total_mass_in_cell - M
# M_diff = total_mass_in_cell - M_sys
# if M_diff <= 0.0:
# # xis = np.array(xis, dtype=np.int64)
# masses = [m*p_max*total_mass_in_cell/M_sys for m in masses]
# # masses = np.array(masses)
# # masses *= p_max*total_mass_in_cell/M_sys
# else:
# # mu = max(p_max*M/xi,m_left)
# mu = M_diff/xi
# masses.append(mu)
# xis.append(xi)
# no_pt += xi
# print(pt_n, xi, mu, no_pt)
# pt_n += 1
# print("no_pt + xi=", no_pt + xi, "no_rpc =", no_rpc )
# xi = no_rpc - no_pt
# last = True
# M = np.sum( np.array(xis)*np.array(masses) )
# M = p_max * total_mass_in_cell - M
# M = total_mass_in_cell - M
# mu = max(p_max*M/xi,m_left)
# mu = M/xi
# masses.append(mu)
else:
### iii) set the right right bin border
# by no_rpc * int_(m_left)^m_right dm f(m) = xi
m_right = num_int_expo_impl_right_border(m_left, xi/no_rpc,
dm, par)
# m = m_left
# intl = 0.0
# cnt = 0
# while (intl < xi/no_rpc and cnt < 1E7):
# intl += dm * func(m)
# m += dm
# cnt += 1
# if cnt == 1E7:
# print(pt_n, "cnt=", cnt)
# m_right = m
# if m_right >= m_high:
# print(pt_n, "new m_right=", m_right)
# iv) set SIP mass mu by mu=M/xi (M = total mass in the bin)