forked from dainaromeo/CoDo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CoDo.py
1360 lines (1151 loc) · 62 KB
/
CoDo.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
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
'''
CoDo, a combined dosimetry model
Copyright ©, 2021 , Empa, Daina Romeo
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import math
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import time
from datetime import date
import pyautogui
import sys
# PLEASE NOT THAT THE FILEPATH USES "/" AND NOT "\"
# -------- INDICATE THE FULL PATH OF THE MPPD DATASET CSV FILE -------------------------
MPPD_dataset = 'C:/Users/roda/Documents/Python Scripts/CoDo/MPPD_df_auto.csv'
# ------ INDICATE THE LOCATION OF THE MPPD SOFTWARE FOLDER - USUALLY FOUND IN DOCUMENTS
MPPD_results = 'C:/Users/roda/Documents/MPPD'
# ------- INDICATE THE FULL PATH OF THE TEMPLATE FILE --------------------------------------
template_file = 'C:/Users/roda/Documents/Python Scripts/CoDo/CoDo template.xlsx'
# ------- INDICATE THE FULL PATH OF THE MPPD ICON IMAGE --------------------------------
MPPD_icon = 'C:/Users/roda/Documents/Python Scripts/CoDo/MPPD_icon.png'
# - INDICATE THE FIRST AND LAST LINE TO COMPUTE (IF ONLY ONE LINE, START_VALUE=END_VALUE)
start_value = 4
end_value = 7
# ------------------------------------------------------------------------------------
# END OF USER'S INPUTS - DO NOT MODIFY AFTER THIS LINE
# ------------------------------------------------------------------------------------
####Added: check time at which deposited concentration becomes constant and returns it
def in_vitro_simulation(ID=None, Output_file='missing name', Substance=None,
media_viscosity=0.00089, media_density=1.0104, media_temperature=37,
pp_density=None, agg_diameter=None,
agg_effective_density=None, pp_diameter=None, column_height=None,
initial_concentration=None,
simulation_time=None, subcompartment_height=0.005, simulation_time_interval=0.5,
output_time_interval=30, eq_change_rate=0.002, output_compartment_height=0.01,
to_plot=False, save=False, sedimentation_cdependence=0.0,
diffusion_cdependence=0.0,
initial_dissolution=0, dissolution_rate_type=0, dissolution_rate=0,
dissolution_times=0, dissolution_fractions=0, sticky=False,
adsorption_dissociation_constant=1e-9, Eq=False, **kwargs):
Today = date.today()
Date_to_report = Today.strftime("%d-%m-%Y")
if Output_file == 'missing name':
Output_file = f"{Substance}_{ID}_{Date_to_report}"
# The in vitro simulation is based on the DG_NANOTRANSPORT_SIMULATE - DISTORTED GRID NANOTRANSPORT SIMULATOR
# from Glen DeLoid 07/13/15 (Copyright 2015, Harvard T. H. Chan School of Public Health)
# Which has been converted to Python programming language and modified by Daina Romeo, 12/10/2020
# Input data - constants
# define constants
# Boltzman constant
kB = 1.3806503e-23 # m^2 kg s^-2 K^-1
# absolute zero (degrees C below 0C)
absZ = 273.15
# gravitational acceleration (m/s^2)
Ga = 9.8
# Na Avigadro's number
Na = 6.0221413e23
# Media and Particle/agglomerate variables are stored in a dictionary
Media = dict()
P = dict()
# Media properties
# absolute temperature
Media['absT'] = absZ + media_temperature
# media density ( in kg/m^3)
Media['dens'] = media_density * 1.0e3
# Particle/Agglomerate-related properties
# agglomerate radius in m
P['rad'] = 0.5e-9 * agg_diameter
# agglomerate cross-sectional areas
P['CrossArea'] = P['rad'] ** 2 * math.pi
# density of material (convert to mg/cm3 == kg/m3)
P['pp_density'] = pp_density * 1.0e3
# agglomerate effective density converted in kg/m^3 e.g. g/cm3 x 1000
P['agg_effective_density'] = agg_effective_density * 1.0e3
# mass of the agglomerates (kg)
P['mass'] = P['agg_effective_density'] * (4 / 3) * math.pi * P['rad'] ** 3
# agglomerate molar concentration per mass concentration
# n/m^3 = (kg/m^3)/kg = C/P.mass
# n/L = 1e-3 * n/m^3 = 1e-3*C/P.mass
# moles/L = (n/L)/Na = (1/Na)*1e-3*C/P.mass
P['molpermass'] = 1e-3 / (P['mass'] * Na)
# agglomerate cross-sectional area per unit mass
P['CrossAreaMass'] = P['CrossArea'] / P['mass']
# Coefficient for sedimentation concentration dependence
P['SedCod'] = sedimentation_cdependence
# Coefficient for diffusion concentration dependence (Dc = Do/(1 + Kd*c)), usually 0.1, or 0;
P['DiffCod'] = diffusion_cdependence
# type of dissolution rate
# 0 = no further dissolution after initial dissolution (stable)
# 1 = fraction of original per hour (constant)
# 2 = specified times and fractions (specified curve, interpolated linearly)
P['DissRateType'] = int(dissolution_rate_type)
# initial dissolution fraction
P['initial_dissolution'] = initial_dissolution
# rate of dissolution (after initial)
# only relevant for rate_type = 0 or 1
P['DissRate'] = dissolution_rate
# times for dissolution fraction data (h)
# only relevant for rate_type = 2;
P['DissT'] = dissolution_times
# dissolution fractions corresponding to specified times
P['TDissFrx'] = dissolution_fractions
# Simulation/experimental parameters
# column height (m)
colH = column_height * 1.0e-3
# compartment height(m)
subH = subcompartment_height * 1.0e-3
# output data compartment height
BottomH = output_compartment_height * 1.0e-3
# number of compartments - use floor to round
# top of top compartment will be at or <subH below top of column
# requires assumption of initial homogeneous mixture
ncomp = round(colH / subH)
# number of compartments to include in "bottom fraction"
BottN = round(BottomH / subH)
# number of BottomH sized compartments (combined/averaged compartments)
ncompBott = ncomp / BottN
# simulation time (sec)
Tend = simulation_time * 3600
# simulation time interval(sec)
dt = simulation_time_interval
# initial total concentration (mg/ml) (same as kg/m^3) of primary material
C0p = initial_concentration
# output time interval (min)
OutputIntervalMin = output_time_interval
# output time interval (h)
OutputIntervalHrs = OutputIntervalMin / 60.0
# number of output points
NOutPoints = math.ceil(simulation_time * 60 / OutputIntervalMin) + 1
# N x g
Ng = 1
# material/media/agglomerate fractional and multiplier values
# Fraction of agglomerate that is particle
P['PFracAgg'] = (P['agg_effective_density'] - Media['dens']) / (P['pp_density'] - Media['dens'])
# fraction in agglomerate that is media
P['MediaFracAgg'] = 1 - P['PFracAgg']
# mass of media per unit mass (e.g. kg) of material (in agglomerate)
P['mm'] = (P['MediaFracAgg'] * Media['dens']) / (P['PFracAgg'] * P['pp_density'])
# total mass of agglomerate per mass of material (multiplier for nm
# concentration for calculating agglomerate mass/concentration for a given
# raw material mass/concentration). Equal to the mass of media per unit mass
# of material (P.mm) plus the unit mass (1.0) of material
P['Magg'] = P['mm'] + 1.0
# initial transport coefficients for all agglomerate size species
# agglomerate sed coeff (at C=0)
P['Scoeff'] = 2.0 * (P['rad'] ** 2) * (P['agg_effective_density'] - Media['dens']) / (9.0 * media_viscosity) # sec
# agglomerate diff coeff (at C=0)
P['Dcoeff'] = (kB * Media['absT']) / (6.0 * math.pi * media_viscosity * P['rad'])
# P.dcoeff = (kB * Sol.tabs * P.DiffCorrGD)./(6.0 * pi * Sol.visc * P.rad);
# initial concentration of agglomerate species and dissolved material
# initial agglomerates concentrations without dissolution
C0a = C0p * P['Magg']
# Initial agglomerates concentration when accounting for initially dissolved fraction
C0a = C0a * (1.0 - P['initial_dissolution'])
# initial concentration of dissolved fraction
DissC = C0p * P['initial_dissolution']
# Starting dissolved and undissolved fractions (above and beyond initial
# dissolution fraction)
DissFrx = P['initial_dissolution']
UndissFrx = 1.0 - P['initial_dissolution']
# initial bound concentrations of agglomerates at bottom
Cabound = np.array([0])
# initial fraction of bottom area occupied
FrxBottomOccupied = 0.0
# kill back diffusion from bottom
BotDoff = 0
# Surface adsorption (Langmuir) approach to stickiness
# Surface molar dissociation constant (mol m
Kd = adsorption_dissociation_constant
# starting compartment agglomerate concentrations - equal concentration in every compartment
Ca = np.tile(C0a, [ncomp, 1])
# total mass of material per area
MPAp = C0p * ncomp
# initial concentration-adjusted sedimentation coefficients
# (at centers of compartments, always)
S = P['Scoeff'] / (1 + P['SedCod'] * Ca)
# initial concentration-adjusted diffusion coefficients
# at boundaries
D = np.zeros((ncomp + 1, 1))
for k in range(1, ncomp):
D[k, :] = P['Dcoeff'] / (1 + P['DiffCod'] * np.mean(Ca[(k - 1):(k + 1), ], axis=0))
if BotDoff != 0:
D[ncomp - 1, ] *= 0.5
# Z positions of subcompartment centers for output data (mm)
# gets middle position, than adds the subcompartment height to go to next middle position
Z = np.arange(subH / 2, (ncomp * subH), subH) * 1e3
# Calculate maximum fractional compartment distance sedimented in dt
MaxSdx = abs(P['Scoeff']) * (Ng * Ga * dt / subH)
# Calculate max fractional concentration change from diffusion in dt
MaxDdcdx = P['Dcoeff'] * (dt / subH ** 2)
# if either max is above 0.5 (.49 to be safe), throw error and recommend
if MaxSdx >= 0.49 or MaxDdcdx >= 0.49:
# calculate maximum time for sedimentation
maxdts = 0.49 * subH / (Ng * Ga * abs(P['Scoeff']))
# calculate maximum time for diffusion
maxdtd = (0.49 * subH ** 2) / P['Dcoeff']
# maximum time for a step (maxdt) is min of max diffusion and sedimentation
maxdt = min(maxdts, maxdtd)
#raise ValueError(f'the simulation time interval is too long, please use a value < {maxdt} seconds')
# diffusion concentration change calculation constant
Diffint = dt / subH ** 2
# sedimentation distance sedimented calculation constant
Sedint = Ng * Ga * dt / subH
# SedCoeffConst (s = SConst * rad^2)
SConst = 2.0 * (P['agg_effective_density'] - Media['dens']) / (9.0 * media_viscosity)
# DiffCoeffConst (D = DConst/rad)
DConst = (kB * Media['absT']) / (6.0 * math.pi * media_viscosity)
# number of time intervals (counts) before output
outcount = int(round(OutputIntervalMin * 60 / dt))
# output time counter
outcounter = 0
# Initialize output data time point counter
I = 0
# Initial time in seconds
T = 0.0
##################################################################################################################
# Simulation at T0
# At T=0, adjust for dissolution if needed and output first data point
###Create empty result lists of lists to set size before loop
ConcPerBottHcomp = []
MassPerBottHcomp = []
DepMassBott = []
DepMassDissBottcomp = []
NBottcomp = []
NDepBottcomp = []
OutSATpdzbot = []
SADepBottcomp = []
OutFrxMassdzbot = []
OutT = []
OutCa = []
OutSumCa = []
OutCp = []
OutTotalCp = []
OutDissC = []
OutFrxOcc = []
OutMBound = []
OutTotalCpd = []
OutFrxMass = []
DepMasscomp= []
DepMassDisscomp = []
OutNp = []
OutNTp = []
OutNTpDep = []
NDepBottcomp = []
OutSAp = []
OutSATp = []
OutSATpDep = []
OutCpdzbot = []
OutMpdzbot = []
OutNpdzbot = []
OutNpDepdzbot = []
OutSApdzbot = []
OutSADepdzbot = []
# Perform Dissolution (if necessary) for T=0
if P['DissRateType'] > 0:
diss_result = perform_dissolution(P, T, C0p, UndissFrx, Ca, SConst, DConst)
DissC = diss_result[0]
Ca = diss_result[1]
P['rad'] = diss_result[2]
P['Scoeff'] = diss_result[3]
P['Dcoeff'] = diss_result[4]
DissFrx = diss_result[5]
UndissFrx = diss_result[6]
# Calculate output point
result = calculate_output_point(P, T, Ca, DissC, FrxBottomOccupied, Cabound,
subH, ncompBott, BottN, MPAp, ncomp)
OutT.append(result[0])
OutCa.append(result[1])
OutSumCa.append(result[2])
OutCp.append(result[3])
OutTotalCp.append(result[4])
OutDissC.append(result[5])
OutFrxOcc.append(result[6])
OutMBound.append(result[7])
ConcPerBottHcomp.append(result[8])
OutTotalCpd.append(result[9])
MassPerBottHcomp.append(result[10])
OutFrxMass.append(result[11])
OutFrxMassdzbot.append(result[12])
DepMasscomp.append(result[13])
DepMassBott.append(result[14])
DepMassDisscomp.append(result[15])
DepMassDissBottcomp.append(result[16])
OutNp.append(result[17])
OutNTp.append(result[18])
NBottcomp.append(result[19])
OutNTpDep.append(result[20])
NDepBottcomp.append(result[21])
OutSAp.append(result[22])
OutSATp.append(result[23])
OutSATpdzbot.append(result[24])
OutSATpDep.append(result[25])
SADepBottcomp.append(result[26])
OutCpdzbot.append(result[27])
OutMpdzbot.append(result[28])
OutNpdzbot.append(result[29])
OutNpDepdzbot.append(result[30])
OutSApdzbot.append(result[31])
OutSADepdzbot.append(result[32])
# Increment output data time point counter
I = I + 1
## variables to check for reaching equiibrium in deposition over time
eq_count = []
print(f'Loop starts - particle ID {ID}')
#########START LOOP#################################################################################################
# Loop through time in seconds
while T <= Tend:
# Perform round of SEDIMENTATION
# calculate sedimentation distances (in compartment heights (dx's)) of compartment
# center= (note, compartment center!) 'pseudo boundaries.'
Sd = S * Sedint
CaSd = Ca * Sd
Ca1mSd = Ca * (1 - Sd)
firstCapr = Ca1mSd[0, np.newaxis]
middleCapr = CaSd[0:ncomp - 2] + Ca1mSd[1:ncomp - 1]
lastCapr = (CaSd[ncomp - 2] + Ca[ncomp - 1])[np.newaxis, :]
Capr = np.concatenate((firstCapr, middleCapr, lastCapr), axis=0)
# to allow diffusion to act on same concentrations used in
# sedimentation
# concentration deltas for sedimentation
dCaS = Capr - Ca
# Perform round of DIFFUSION
# concentration differences across boundaries (i+1 - i)
CaDiff = Ca[1:] - Ca[0:ncomp - 1]
if sticky:
CaDiff[-1] = CaDiff[-1] - Cabound
# diffusion for first compartment (movement only from 2nd compartment
# back to first (this) compartment)
Capr[0] = Ca[0] + (Diffint * D[1] * CaDiff[0])
# diffusion for last compartment (movement only from this compartment
# to compartment above) with CaDiff adjusted for Cabound
Capr[-1] = Ca[-1] - (Diffint * D[ncomp - 1] * CaDiff[-1])
# diffusion for all other compartments (from next compartment (+) into
# current compartment and from current compartment (-) into compartment
# above
Capr[1:-1] = Ca[1:-1] + Diffint * (
(D[2:ncomp] * CaDiff[1:(ncomp - 1)]) - (D[1:(ncomp - 1)] * CaDiff[0:(ncomp - 2)]))
# to allow diffusion to act on same concentrations used in
# sedimentation, set Ca to diffused Capr and add sed deltas
Ca = Capr + dCaS
for conc, name in zip([Ca, Capr, dCaS, Sd], ['Ca', 'Capr', 'dCaS', 'Sd']):
if np.isnan(conc).any():
raise ValueError(name)
# Adjust for dissolution if needed
if P['DissRateType'] > 0:
diss_result = perform_dissolution(P, T, C0p, UndissFrx, Ca, SConst, DConst)
DissC = diss_result[0]
Ca = diss_result[1]
P['rad'] = diss_result[2]
P['Scoeff'] = diss_result[3]
P['Dcoeff'] = diss_result[4]
DissFrx = diss_result[5]
UndissFrx = diss_result[6]
# Update bound at bottom
if sticky:
bottom_result = update_bottom_bound_by_adsorption(P, Ca, Kd, subH)
MaxFrxBottomOccupied = bottom_result[0]
Frxavail = bottom_result[1]
Frxbound = bottom_result[2]
FrxBottomOccupied = bottom_result[3]
Cabound = bottom_result[4]
# Adjust sedimentation and diffusion coefficients for concentration
# new concentration-adjusted sedimentation coefficients
# at centers of compartments
if P['SedCod'] != 0.0:
S = P['Scoeff'] / (1 + P['SedCod'] * Ca)
# new concentration-adjusted diffusion coefficients
# at boundaries
if P['DiffCod'] != 0.0:
for k in range(1, ncomp):
D[k] = P['Dcoeff'] / (1 + P['DiffCod'] * np.mean(np.array([Ca[k - 1], Ca[k]]), axis=0))
# other concentration or time-dependent changes can be made here
# Increment time and counter
T += dt
outcounter += 1
# Calculate and plot output data if time
# reset counter each time it reaches the reporting time, and calculate and save output
if outcounter == outcount:
outcounter = 0
# if mod(T,60*OutputIntervalMin)==0
# # if exactly at output interval mark
# Calculate output point
result = calculate_output_point(P, T, Ca, DissC, FrxBottomOccupied,
Cabound, subH, ncompBott, BottN, MPAp, ncomp)
# raise error if variables become nan - indicates non-convergence
for conc, name in zip([T, Ca, DissC, FrxBottomOccupied,
Cabound, subH, ncompBott, BottN, MPAp, ncomp], ['T', 'Ca', 'DissC', 'FrxBottomOccupied',
'Cabound', 'subH', 'ncompBott', 'BottN',
'MPAp', 'ncomp']):
if np.isnan(conc).any():
raise ValueError(name)
OutT.append(result[0])
OutCa.append(result[1])
OutSumCa.append(result[2])
OutCp.append(result[3])
OutTotalCp.append(result[4])
OutDissC.append(result[5])
OutFrxOcc.append(result[6])
OutMBound.append(result[7])
ConcPerBottHcomp.append(result[8])
OutTotalCpd.append(result[9])
MassPerBottHcomp.append(result[10])
OutFrxMass.append(result[11])
OutFrxMassdzbot.append(result[12])
DepMasscomp.append(result[13])
DepMassBott.append(result[14])
DepMassDisscomp.append(result[15])
DepMassDissBottcomp.append(result[16])
OutNp.append(result[17])
OutNTp.append(result[18])
NBottcomp.append(result[19])
OutNTpDep.append(result[20])
NDepBottcomp.append(result[21])
OutSAp.append(result[22])
OutSATp.append(result[23])
OutSATpdzbot.append(result[24])
OutSATpDep.append(result[25])
SADepBottcomp.append(result[26])
OutCpdzbot.append(result[27])
OutMpdzbot.append(result[28])
OutNpdzbot.append(result[29])
OutNpDepdzbot.append(result[30])
OutSApdzbot.append(result[31])
OutSADepdzbot.append(result[32])
# Check if the rate of deposition (as deposited fraction tx+1 - deposited fraction tx) is below the threshold
# defined by eq_change_rate
if (OutFrxMassdzbot[-1][-1, -1] - OutFrxMassdzbot[-2][-1, -1]) / OutputIntervalHrs <= eq_change_rate:
# print(OutFrxMassdzbot[-1][-1, -1] - OutFrxMassdzbot[-2][-1, -1])
eq_count.append(I)
# Increment output data time point counter
I = I + 1
print(f'ID {ID}, end loop {T},calculating point {I}')
# increase simulation time if deposition rate is not under the threshold
if T >= Tend:
if not eq_count and Eq:
Tend += OutputIntervalMin * 60
else:
if not Eq:
eq_time = 'not defined'
elif len(eq_count) == len(OutT[eq_count[0]:]):
begin_eq = eq_count[0]
eq_time = OutT[begin_eq]
else:
print(
f'Deposited fraction decreases over time after reaching threshold value. Please check it out. ID {ID}')
eq_time = 'not defined - decresing deposited fraction'
if to_plot:
plot_output(ConcPerBottHcomp, OutputIntervalHrs, DepMassBott, OutFrxMassdzbot,
Output_file, SADepBottcomp)
print(f'ID {ID}: simulation complete')
# Save output data
if save:
write_output_data(OutT, sticky, OutFrxMassdzbot, DepMassBott, DepMassDissBottcomp, NDepBottcomp,
SADepBottcomp, OutDissC, OutFrxOcc, OutMBound, Output_file, eq_time, eq_change_rate)
if not Eq:
eq_frac, eq_mass, eq_sa, eq_num = np.nan, np.nan, np.nan, np.nan
else:
eq_frac, eq_mass, eq_sa, eq_num = float(OutFrxMassdzbot[begin_eq][-1]), float(DepMassBott[begin_eq][-1]), \
float(SADepBottcomp[begin_eq][-1]), float(NDepBottcomp[begin_eq][-1])
one_line_result = [ID, Substance, pp_diameter, float(agg_diameter), initial_concentration,
simulation_time, eq_time, float(OutFrxMassdzbot[-1][-1]),
float(DepMassBott[-1][-1]), float(DepMassDissBottcomp[-1][-1]),
float(SADepBottcomp[-1][-1]), float(NDepBottcomp[-1][-1]),
eq_frac, eq_mass, eq_sa, eq_num]
print(f'ID {ID}: In vitro simulation complete')
return one_line_result
# ----------------------END OF MAIN FUNCTION-----------------------#
# -----------------------------------------------------------------#
#
# OUTPUT DATA POINT FUNCTION
#
# -----------------------------------------------------------------#
def calculate_output_point(P, T, Ca, DissC, FrxBottomOccupied, Cabound, subH, ncompBott, BottN, MPAp, ncomp):
# save the time, in hours
OutT = T / 3600
# mass concentrations of each agglomerate species (mg/ml)
OutCa = Ca
# total mass agglomerage concentrations
OutSumCa = np.sum(Ca, axis=1, keepdims=True)
# mass raw material/particle concentrations for individual agglomerates
OutCp = Ca / P['Magg']
# total undissolved mass material/particle concentrations
OutTotalCp = np.sum(Ca, axis=1, keepdims=True) / P['Magg']
# dissolved concentration
OutDissC = DissC
# fraction of floor occupied
OutFrxOcc = FrxBottomOccupied
# mass of material bound per area = c bound * height of compartment
# (mg/cm^2). multiply concentration bound mg/cm^3 by subH in cm (subH * 100)
OutMBound = (np.sum(Cabound) / P['Magg']) * subH * 1.0e2
#
# MASS AND FRACTION OF MASS
#
# CONCENTRATION
# undissolved particle mass at BottomH per diameter size (shape num BottomH intervals * number of particle sizes)
OutCpdzbot = np.zeros((int(ncompBott), 1))
for k in range(0, ncomp, BottN):
OutCpdzbot[int(k / BottN)] = np.sum(OutCp[k:k + BottN], axis=0) / BottN
# average total undissolved mass material/particle concentrations at BottomH
# intervals (e.g. 10 microns)
ConcPerBottHcomp = np.zeros((int(ncompBott), 1))
for k in range(0, ncomp, BottN):
ConcPerBottHcomp[int(k / BottN), :] = np.sum(OutTotalCp[k:k + BottN, ]) / BottN
# total mass material/particle concentrations including dissolved (mg/cm^3 == kg/m^3)
OutTotalCpd = OutTotalCp + DissC
# average total mass material/particle concentrations at BottomH
# intervals (e.g. 10 microns)
MassPerBottHcomp = np.zeros((int(ncompBott), 1))
for k in range(0, ncomp, BottN):
MassPerBottHcomp[int(k / BottN), :] = np.sum(OutTotalCpd[k:k + BottN, ]) / BottN
# FRACTION PER COMPARTMENT AND "DEPOSITED"
# Fraction of material/particle mass in each compartment
# fx = mass in compartment/total mass in all compartments initially
# fx = (c * pi*r^2*h)/(c0 * ncompartments * pi*r^2*h)
OutFrxMass = OutTotalCp / MPAp
# total Fraction mass material/particle at BottomH
# intervals (e.g. 10 microns)
OutFrxMassdzbot = np.zeros((int(ncompBott), 1))
for k in range(0, ncomp, BottN):
OutFrxMassdzbot[int(k / BottN), :] = np.sum(OutFrxMass[k:k + BottN, ])
# MASS DEPOSITED PER FLOOR AREA
# total mass of material "deposited" per unit floor area in each
# compartment (mg/cm^2)
DepMasscomp = OutTotalCp * subH * 1.0e2
# total mass "deposited" per unit floor at BottomH
# intervals (e.g. 10 microns)
DepMassBott = np.zeros((int(ncompBott), 1))
for k in range(0, ncomp, BottN):
DepMassBott[int(k / BottN), :] = np.sum(DepMasscomp[k:k + BottN, ])
## mass deposited per unit floor at BottomH intervals, per particle diameter
OutMpdzbot = OutCpdzbot * subH * 1.0e2 * BottN
# total "deposited" mass including dissolved per unit floor in each
# compartment (mg/cm^2) *mult by 1e2 to convert from kg/m^3 to mg/cm^2
DepMassDisscomp = OutTotalCpd * subH * 1.0e2
# total mass "deposited" per unit floor including dissolved at BottomH
# intervals (e.g. 10 microns)
DepMassDissBottcomp = np.zeros((int(ncompBott), 1))
for k in range(0, ncomp, BottN):
DepMassDissBottcomp[int(k / BottN), :] = np.sum(DepMassDisscomp[k:k + BottN, ])
#
# PARTICLE NUMBER
#
# CONCENTRATION
# number concentration for each agglomerate
# converted from m^-3 to cm^-3 by dividing by 1e6
OutNp = OutCp * 3 / (math.pi * 4 * (P['rad'] ** 3) * 1.0e6 * P['pp_density'] * P['PFracAgg'])
# total number concentration (a bit silly, combining all different sizes, but for consistency
OutNTp = np.sum(OutNp, axis=1, keepdims=True)
## number concentration at BottomH per particle diameter
OutNpdzbot = np.zeros((int(ncompBott), 1))
for k in range(0, ncomp, BottN):
OutNpdzbot[int(k / BottN)] = np.sum(OutNp[k:k + BottN], axis=0) / BottN
# average number concentration at BottomH
# intervals (e.g. 10 microns)
NBottcomp = np.zeros((int(ncompBott), 1))
for k in range(0, ncomp, BottN):
NBottcomp[int(k / BottN)] = np.sum(OutNTp[k:k + BottN, ]) / BottN
# DEPOSITED
# total number concentration of material "deposited" per unit floor area
# (cm^-2). multiply concentration cm^-3 by subH in cm (subH * 100)
OutNTpDep = OutNTp * subH * 1.0e2
# total number concentration "deposited" per floor area at BottomH
# intervals (e.g. 10 microns)
NDepBottcomp = np.zeros((int(ncompBott), 1))
for k in range(0, ncomp, BottN):
NDepBottcomp[int(k / BottN), :] = np.sum(OutNTpDep[k:k + BottN, ])
## number of particle of different diameter deposited per cm2
OutNpDepdzbot = OutNpdzbot * subH * 1.0e2 * BottN
#
# SURFACE AREA
#
# CONCENTRATION
# surface area concentration of material/particle for each agglomerate
# converted from (m^2/m^3)to (cm^2/cm^3) by dividing by 10e2
OutSAp = OutCp * 3 / (P['rad'] * 1.0e2 * P['pp_density'])
# total surface area concentration of material (cm^2/cm^3)
OutSATp = np.sum(OutSAp, axis=1, keepdims=True)
# average surface area concentration at BottomH
# intervals (e.g. 10 microns)
OutSATpdzbot = np.zeros((int(ncompBott), 1))
for k in range(0, ncomp, BottN):
OutSATpdzbot[int(k / BottN), :] = np.sum(OutSATp[k:k + BottN, ]) / BottN
## surface area deposited at BottomH per particle size
OutSApdzbot = np.zeros((int(ncompBott), 1))
for k in range(0, ncomp, BottN):
OutSApdzbot[int(k / BottN)] = np.sum(OutSAp[k:k + BottN], axis=0) / BottN
# DEPOSITED
# total surface area concentration of material "deposited" per unit floor area
# (cm^2/cm^2). multiply concentration cm^2/cm^3 by subH in cm (subH * 100)
OutSATpDep = OutSATp * subH * 1.0e2
# total surface area concentration "deposited" per floor area at BottomH
# intervals (e.g. 10 microns)
SADepBottcomp = np.zeros((int(ncompBott), 1))
for k in range(0, ncomp, BottN):
SADepBottcomp[int(k / BottN), :] = np.sum(OutSATpDep[k:k + BottN, ])
## surface area deposited per floor area at BottomH per particle size
OutSADepdzbot = OutSApdzbot * subH * 1.0e2 * BottN
return (OutT, OutCa, OutSumCa, OutCp, OutTotalCp, OutDissC, OutFrxOcc,
OutMBound, ConcPerBottHcomp, OutTotalCpd, MassPerBottHcomp,
OutFrxMass, OutFrxMassdzbot, DepMasscomp, DepMassBott,
DepMassDisscomp, DepMassDissBottcomp, OutNp, OutNTp, NBottcomp,
OutNTpDep, NDepBottcomp, OutSAp, OutSATp, OutSATpdzbot,
OutSATpDep, SADepBottcomp, OutCpdzbot, OutMpdzbot, OutNpdzbot,
OutNpDepdzbot, OutSApdzbot, OutSADepdzbot)
# -----------------------------------------------------------------#
#
# PLOT TO DATA POINT FUNCTION
#
# -----------------------------------------------------------------#
def plot_output(ConcPerBottHcomp, OutputIntervalHrs, DepMassBott, OutFrxMassdzbot, Output_file,
SADepBottcomp):
# get number of timepoints from data
ntime = len(ConcPerBottHcomp)
figdepositfinal, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(15, 5))
x1 = list(np.arange(float(ntime)) * OutputIntervalHrs)
y1 = np.array(DepMassBott)[:, -1].flatten()
# plot bottom mass concentration vs time
ax1.plot(x1, y1)
ax1.set_title('Bottom mass per area over time')
ax1.set_xlabel('Time [h]')
ax1.set_ylabel('Total particle mass per bottom area [mg/cm2]')
# plot frx deposited vs time
y2 = np.array(OutFrxMassdzbot)[:, -1].flatten()
ax2.plot(x1, y2)
ax2.set_title('Fraction deposited over time')
ax2.set_xlabel('Time [h]')
ax2.set_ylabel('Fraction deposited')
y3 = np.array(SADepBottcomp)[:, -1].flatten()
# plot bottom mass concentration vs time
ax3.plot(x1, y3)
ax3.set_title('Bottom particle surface area per area over time')
ax3.set_xlabel('Time [h]')
ax3.set_ylabel('Total particle surface area per bottom area [cm2/cm2]')
plt.tight_layout()
figdepositfinal.savefig('Deposited_' + Output_file + '.pdf')
plt.close(figdepositfinal)
# -----------------------------------------------------------------#
#
# WRITE OUTPUT DATA FUNCTION
#
# -----------------------------------------------------------------#
def write_output_data(OutT, sticky, OutFrxMassdzbot, DepMassBott,
DepMassDissBottcomp, NDepBottcomp,
SADepBottcomp, OutDissC, OutFrxOcc, OutMBound, Output_file, eq_time, eq_change_rate):
print('Writing output data, please wait.')
# BOTTOM SUMMARY
name_row = [f'Time at which the marginal increase in deposited fraction per h is < {eq_change_rate} (h)', 'Deposited fraction (of total mass)',
'Mass deposited per area (mg cm^-2)', 'Mass deposited and dissolved fraction per area (mg cm^-2)', 'Number of particles per area (cm^-2)',
'Particles surface area per area (cm^2 cm^-2)', 'Concentration of dissolved fraction (mg cm^-3)']
name_col = [('Time: ' + str(OutT[x]) + ' hours') for x in range(len(OutT))]
time_row = [0 for x in range(len(OutT))]
time_row[0] = eq_time
if sticky:
name_row += ['% floor occ. (%)', 'mass bound area^-1 (mg cm^-2)']
matrix = np.concatenate((np.array(time_row)[np.newaxis, :],
np.array(OutFrxMassdzbot)[:, -1].swapaxes(1, 0),
np.array(DepMassBott)[:, -1].swapaxes(1, 0),
np.array(DepMassDissBottcomp)[:, -1].swapaxes(1, 0),
np.array(NDepBottcomp)[:, -1].swapaxes(1, 0),
np.array(SADepBottcomp)[:, -1].swapaxes(1, 0), np.array(OutDissC)[np.newaxis, :],
np.array(OutFrxOcc)[np.newaxis, :], np.array(OutMBound)[np.newaxis, :]), axis=0)
else:
matrix = np.concatenate((np.array(time_row)[np.newaxis, :],
np.array(OutFrxMassdzbot)[:, -1].swapaxes(1, 0),
np.array(DepMassBott)[:, -1].swapaxes(1, 0),
np.array(DepMassDissBottcomp)[:, -1].swapaxes(1, 0),
np.array(NDepBottcomp)[:, -1].swapaxes(1, 0),
np.array(SADepBottcomp)[:, -1].swapaxes(1, 0), np.array(OutDissC)[np.newaxis, :]),
axis=0)
file_to_save = pd.DataFrame(matrix, columns=name_col, index=name_row)
filename = Output_file + '.csv'
file_to_save.to_csv(filename)
print('File saved')
# -----------------------------------------------------------------#
#
# DISSOLUTION FUNCTION
#
# -----------------------------------------------------------------#
def perform_dissolution(P, T, C0p, UndissFrx, Ca, SConst, DConst):
if P['DissRateType'] > 0:
# if dissolution occurs beyond initial dissolution that occured
# prior to start of simulation
# calculate current dissolution fraction over and above
# P['dissFrx0, the dissolution that has occured since start of
# simulation
if P['DissRateType'] == 1:
# if constant dissolution rate per hour
# never allow to reach 1, but very close - negligible undissolved)
dissfrac = P['initial_dissolution'] + (P['DissRate'] * T / 3600.0)
NewDissFrx = min(0.9999, dissfrac)
else:
# dissolution fractions over time (curve) provided by user, allow
# more complex/realistic dissolution models
interp = np.interp(xp=P['DissT'], fp=P['TDissFrx'], x=T / 3600.0)
NewDissFrx = min(0.9999, (P['initial_dissolution'] + interp))
# New value of undissolved fraction (of what was undissolved after
# initial dissolution start point)
NewUndissFrx = 1.0 - NewDissFrx
# new total dissolved material concentration
DissC = C0p * NewDissFrx
# fraction of undissolved at previous iteration remaining
# undissolved at present iteration or time point = c2/c1
FrxRemUndiss = NewUndissFrx / UndissFrx
# new compartment agglomerate concentrations
Ca *= FrxRemUndiss
# concentration change shrinks agglomerates
# calculate new agglomerate radii
# v = 4/3*pi*r^3
# v2/v1 = c2/c1 = r2^3/r1^3
# r2/r1 = (c2/c1)^(1/3)
P['rad'] *= FrxRemUndiss ** (1 / 3)
# calculate new agglomerate species diffusion and
# sedimentation coefficients
# agglomerate sed coeff (at C=0)
P['Scoeff'] = SConst * P['rad'] ** 2 # sec
# agglomerate diff coeff (at C=0)
P['Dcoeff'] = DConst / P['rad']
# set current dissolved and undissolved fraction values to new values
DissFrx = NewDissFrx
UndissFrx = NewUndissFrx
return DissC, Ca, P['rad'], P['Scoeff'], P['Dcoeff'], DissFrx, UndissFrx
# -----------------------------------------------------------------
def update_bottom_bound_by_adsorption(P, Ca, Kd, subH):
# molar concentration of all agglomerates in bottom compartment
L = Ca[-1, :] * P['molpermass']
# sum of molar concentrations
Lsum = sum(L)
# fraction occupied theta
MaxFrxBottomOccupied = Lsum / (Kd + Lsum)
Frxavail = sum(P['CrossAreaMass'] * Ca[-1, :] * subH)
# fraction of available material bound
Frxbound = min(1.0, (MaxFrxBottomOccupied / Frxavail))
# actual fraction bottom occupied
FrxBottomOccupied = min(MaxFrxBottomOccupied, Frxavail)
# Concentrations bound
Cabound = Ca[-1, :] * Frxbound
return MaxFrxBottomOccupied, Frxavail, Frxbound, FrxBottomOccupied, Cabound
# ----------------------------------------------------------------
# calculate specific surface area from diameter and density of primary particle
def ssa(diameter, density):
# radius in cm: nm/0.0000001
radius = diameter * 0.0000001 / 2
volume = 4 / 3 * np.pi * radius ** 3
surface_area = 4 * np.pi * radius ** 2
# mass in grams
mass = volume * density
# ssa in m2/g: cm2/g = 0.0001 m2/g
ssa = surface_area * 0.0001 / mass
return ssa
# ---------------------------------------------------------
# Density calculation functions
# calculate agglomerate effective density if missing
def sterling_density(aggl_diam, pp_diam, media_dens, pp_dens):
if np.isnan(pp_diam):
raise ValueError('The diameter of the primary particle is missing. '
'Impossible to calculate the agglomerate effective density.')
DF = 2.1
agglomerate_porosity = 1 - (aggl_diam / pp_diam) ** (DF - 3)
agg_dens = (1 - agglomerate_porosity) * pp_dens + agglomerate_porosity * media_dens
return agg_dens
# calculate density of agglomerates in air
def air_density(agg_effective_density, media_density, pp_density):
return (agg_effective_density - media_density) / (pp_density - media_density) * pp_density
# ---------------------------------------------------------------
# Find location of sample in MPPD database
def find_in_MPPD(MPPD_database, Input_parameters):
if Input_parameters['air_type'] == 'pp':
air_diameter = float(Input_parameters['pp_diameter'])
elif Input_parameters['air_type'] == 'agg':
air_diameter = float(Input_parameters['agg_diameter'])
else:
air_diameter = Input_parameters['aero_diam']
MPPD_line = MPPD_database[(MPPD_database.Substance == Input_parameters['Substance']) & (
MPPD_database.agg_diameter_nm == air_diameter) & (
MPPD_database.pp_diameter_nm == float(Input_parameters['pp_diameter'])) &
(MPPD_database.Exposure_time_h == Input_parameters['simulation_time']) & (
MPPD_database.sex == Input_parameters['sex'])
& (abs(
MPPD_database['density_g/cm2'] - Input_parameters['air_agg_density']) < 0.00000001)]
MPPD_line_long = MPPD_database[(MPPD_database.Substance == Input_parameters['Substance']) & (
MPPD_database.agg_diameter_nm == air_diameter) & (
MPPD_database.pp_diameter_nm == float(Input_parameters['pp_diameter'])) &
(MPPD_database.Exposure_time_w == 1820) & (
MPPD_database.sex == Input_parameters['sex']) &
(abs(MPPD_database['density_g/cm2'] - Input_parameters[
'air_agg_density']) < 0.00000001)]
return MPPD_line, MPPD_line_long
# ------------------------------------------------
# functions for running the MPPD model
def coordinates(x, y):
global BASE_LEFT, BASE_TOP
return {
'x': x / 1.703225806 + BASE_LEFT,
'y': y / 1.703225806 + BASE_TOP
}
def clear_input(x, y, val):
pyautogui.click(x=x, y=y)
pyautogui.hotkey('ctrl', 'a')
pyautogui.write(str(val))
######################################################################
###EXECUTING CODE
#######################################################################
csv = False
start = time.time()
try:
Input_df = pd.read_csv(template_file)
csv = True
except:
Input_df = pd.read_excel(template_file, sheet_name='Data',