Skip to content

vulcan.op

op


Module that includes all the numerical functions of VULCAN.

Copyright (C) 2016 Shang-Min Tsai (Shami)

  • ReadRate() reads in the chemical network and construct the rate constants based on the T-P structure.
  • Integration() is the backbone of integrating for one time step
  • ODESolver() contains the functions for solving system of ODEs (e.g. dy/dt, Jacobian, etc.)
Imports
  • vulcan.config: Config class for handling configuration settings.
  • vulcan.paths: Paths to various files and directories used in VULCAN.
  • vulcan.build_atm: compo and compo_row functions for building the atmospheric composition.
  • vulcan.phy_const: Physical constants used in VULCAN.
  • vulcan.chem_funs: Functions related to the chemical network.

ReadRate(vulcan_cfg)

Bases: object

to read in rate constants from the network file and compute the reaction rates for the corresponding Tco and pco

Source code in src/vulcan/op.py
148
149
150
151
152
153
154
def __init__(self, vulcan_cfg: Config):

    self.cfg = vulcan_cfg
    self.i = 1
    # flag of trimolecular reaction
    self.re_tri, self.re_tri_k0 = False, False
    self.list_tri = []

cfg = vulcan_cfg instance-attribute

i = 1 instance-attribute

list_tri = [] instance-attribute

lim_lowT_rates(var, atm)

Source code in src/vulcan/op.py
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
def lim_lowT_rates(
    self, var, atm
):  # for setting up the lower limit of rate coefficients for low T
    for i in range(1, nr, 2):
        if var.Rf[i] == 'H + CH3 + M -> CH4 + M':
            T_mask = atm.Tco <= 277.5
            k0 = 6e-29
            kinf = 2.06e-10 * atm.Tco**-0.4  # from Moses+2005
            lowT_lim = k0 / (1.0 + k0 * atm.M / kinf)
            log.debug('using the low temperature limit for CH3 + H + M -> CH4 + M')
            log.debug('capping ')
            log.debug(var.k[i][T_mask])
            log.debug('at ')
            log.debug(lowT_lim[T_mask])
            var.k[i][T_mask] = lowT_lim[T_mask]

        elif var.Rf[i] == 'H + C2H4 + M -> C2H5 + M':
            T_mask = atm.Tco <= 300
            log.debug('using the low temperature limit for H + C2H4 + M -> C2H5 + M')
            log.debug('capping ')
            log.debug(var.k[i][T_mask])
            log.debug('at ')
            log.debug(3.7e-30)
            var.k[i][T_mask] = 3.7e-30  # from Moses+2005

        elif var.Rf[i] == 'H + C2H5 + M -> C2H6 + M':
            T_mask = atm.Tco <= 200
            log.debug('using the low temperature limit for H + C2H5 + M -> C2H6 + M')
            log.debug('capping ')
            log.debug(var.k[i][T_mask])
            log.debug('at ')
            log.debug(2.49e-27)
            var.k[i][T_mask] = 2.49e-27  # from Moses+2005

    return var

make_bins_read_cross(var, atm)

determining the bin range and only use the min and max wavelength that the molecules absorb to avoid photons with w0=1 (pure scatteing) in certain wavelengths var.cross stores the total absorption cross sections of each species, e.g. var.cross['H2O'] var.cross stores the IDIVIDUAL photodissociation cross sections for each bracnh, e.g. var.cross_J[('H2O',1)], which is equvilent to var.cross['H2O'] times the branching ratio of branch 1

Source code in src/vulcan/op.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
def make_bins_read_cross(self, var, atm):
    """
    determining the bin range and only use the min and max wavelength that the molecules absorb
    to avoid photons with w0=1 (pure scatteing) in certain wavelengths
    var.cross stores the total absorption cross sections of each species, e.g. var.cross['H2O']
    var.cross stores the IDIVIDUAL photodissociation cross sections for each bracnh, e.g. var.cross_J[('H2O',1)], which is equvilent to var.cross['H2O'] times the branching ratio of branch 1
    """
    photo_sp = list(var.photo_sp)
    ion_sp = list(var.ion_sp)
    absp_sp = photo_sp + ion_sp
    sp0 = photo_sp[0]
    nz = self.cfg.nz

    cross_raw, scat_raw = {}, {}
    ratio_raw, ion_ratio_raw = {}, {}
    cross_T_raw = {}

    # In the end, we do not need photons beyond the longest-wavelength threshold from all species (different from absorption)
    sp_label = np.genfromtxt(
        CROSS_DIR + 'thresholds.txt', dtype=str, usecols=0
    )  # taking the first column as labels
    lmd_data = np.genfromtxt(CROSS_DIR + 'thresholds.txt', skip_header=1)[
        :, 1
    ]  # discarding the fist column

    # for setting up the wavelength coverage
    threshold = {
        label: row for label, row in zip(sp_label, lmd_data) if label in species
    }  # only include the species in the current network
    var.threshold = threshold

    # reading in cross sections into dictionaries
    for n, sp in enumerate(absp_sp):
        if self.cfg.use_ion:
            try:
                cross_raw[sp] = np.genfromtxt(
                    CROSS_DIR + sp + '/' + sp + '_cross.csv',
                    dtype=float,
                    delimiter=',',
                    skip_header=1,
                    names=['lambda', 'cross', 'disso', 'ion'],
                )
            except FileNotFoundError:
                raise RuntimeError('Missing the cross section from ' + sp)
            if sp in ion_sp:
                try:
                    ion_ratio_raw[sp] = np.genfromtxt(
                        CROSS_DIR + sp + '/' + sp + '_ion_branch.csv',
                        dtype=float,
                        delimiter=',',
                        skip_header=1,
                        names=True,
                    )
                except FileNotFoundError:
                    raise RuntimeError('Missing the ion branching ratio from ' + sp)
        else:
            try:
                cross_raw[sp] = np.genfromtxt(
                    CROSS_DIR + sp + '/' + sp + '_cross.csv',
                    dtype=float,
                    delimiter=',',
                    skip_header=1,
                    names=['lambda', 'cross', 'disso'],
                )
            except FileNotFoundError:
                raise RuntimeError('Missing the cross section from ' + sp)

        # reading in the branching ratios
        # for i in range(1,var.n_branch[sp]+1): # branch index should start from 1
        if sp in photo_sp:  # excluding ion_sp
            try:
                ratio_raw[sp] = np.genfromtxt(
                    CROSS_DIR + sp + '/' + sp + '_branch.csv',
                    dtype=float,
                    delimiter=',',
                    skip_header=1,
                    names=True,
                )
            except FileNotFoundError:
                raise RuntimeError('Missing the branching ratio from ' + sp)

        # reading in temperature dependent cross sections
        if sp in self.cfg.T_cross_sp:
            T_list = []
            for temp_file in os.listdir('thermo/photo_cross/' + sp + '/'):
                if temp_file.startswith(sp) and temp_file.endswith('K.csv'):
                    temp = temp_file
                    temp = temp.replace(sp, '')
                    temp = temp.replace('_cross_', '')
                    temp = temp.replace('K.csv', '')
                    T_list.append(int(temp))
                    var.cross_T_sp_list[sp] = T_list
            for tt in T_list:
                if self.cfg.use_ion:  # usually the T-dependent cross sections are only measured in the photodissociation-relavent wavelengths so cross_tot = cross_diss
                    cross_T_raw[(sp, tt)] = np.genfromtxt(
                        CROSS_DIR + sp + '/' + sp + '_cross_' + str(tt) + 'K.csv',
                        dtype=float,
                        delimiter=',',
                        skip_header=1,
                        names=['lambda', 'cross', 'disso', 'ion'],
                    )
                else:
                    cross_T_raw[(sp, tt)] = np.genfromtxt(
                        CROSS_DIR + sp + '/' + sp + '_cross_' + str(tt) + 'K.csv',
                        dtype=float,
                        delimiter=',',
                        skip_header=1,
                        names=['lambda', 'cross', 'disso'],
                    )
            # room-T cross section
            cross_T_raw[(sp, 300)] = cross_raw[sp]
            var.cross_T_sp_list[sp].append(300)

        if cross_raw[sp]['cross'][0] == 0 or cross_raw[sp]['cross'][-1] == 0:
            raise IOError('Please remove the zeros in the cross file of ' + sp)

        if n == 0:  # the first species
            bin_min = cross_raw[sp]['lambda'][0]
            bin_max = cross_raw[sp]['lambda'][-1]
            # photolysis threshold
            try:
                diss_max = threshold[sp]
            except (KeyError, IndexError):
                raise RuntimeError(sp + ' not in threshol.txt')

        else:
            sp_min, sp_max = cross_raw[sp]['lambda'][0], cross_raw[sp]['lambda'][-1]
            if sp_min < bin_min:
                bin_min = sp_min
            if sp_max > bin_max:
                bin_max = sp_max
            try:
                if threshold[sp] > diss_max:
                    diss_max = threshold[sp]
            except (KeyError, IndexError):
                raise RuntimeError(sp + ' not in threshol.txt')

    # constraining the bin_min and bin_max by the default values defined in store.py
    bin_min = max(bin_min, var.def_bin_min)
    bin_max = min(bin_max, var.def_bin_max, diss_max)
    log.info(
        'Input stellar spectrum from '
        + '{:.1f}'.format(var.def_bin_min)
        + ' to '
        + '{:.1f}'.format(var.def_bin_max)
    )
    log.debug('Photodissociation threshold: ' + '{:.1f}'.format(diss_max))
    log.info(
        'Using wavelength bins from ' + '{:.1f}'.format(bin_min) + ' to ' + str(bin_max)
    )

    var.dbin1 = self.cfg.dbin1
    var.dbin2 = self.cfg.dbin2
    if self.cfg.dbin_12trans >= bin_min and self.cfg.dbin_12trans <= bin_max:
        bins = np.concatenate(
            (
                np.arange(bin_min, self.cfg.dbin_12trans, var.dbin1),
                np.arange(self.cfg.dbin_12trans, bin_max, var.dbin2),
            )
        )
    else:
        bins = np.arange(bin_min, bin_max, var.dbin1)
    var.bins = bins
    var.nbin = len(bins)

    # all variables that depend on the size of nbins
    # the direct beam (staggered)
    var.sflux = np.zeros((nz + 1, var.nbin))
    # the diffusive flux (staggered)
    var.dflux_u, var.dflux_d = np.zeros((nz + 1, var.nbin)), np.zeros((nz + 1, var.nbin))
    # the total actinic flux (non-staggered)
    var.aflux = np.zeros((nz, var.nbin))
    # the total actinic flux from the previous calculation
    prev_aflux = np.zeros((nz, var.nbin))

    # staggered
    var.tau = np.zeros((nz + 1, var.nbin))
    # the stellar flux at TOA
    var.sflux_top = np.zeros(var.nbin)

    # read_cross
    # creat a dict of cross section with key=sp and values=bins in data_var
    var.cross = dict(
        [(sp, np.zeros(var.nbin)) for sp in absp_sp]
    )  # including photo_sp and ion_sp

    # read cross of disscoiation
    var.cross_J = dict(
        [
            ((sp, i), np.zeros(var.nbin))
            for sp in photo_sp
            for i in range(1, var.n_branch[sp] + 1)
        ]
    )
    var.cross_scat = dict([(sp, np.zeros(var.nbin)) for sp in self.cfg.scat_sp])

    # for temperature-dependent cross sections
    var.cross_T = dict([(sp, np.zeros((nz, var.nbin))) for sp in self.cfg.T_cross_sp])
    var.cross_J_T = dict(
        [
            ((sp, i), np.zeros((nz, var.nbin)))
            for sp in self.cfg.T_cross_sp
            for i in range(1, var.n_branch[sp] + 1)
        ]
    )

    # read cross of ionisation
    if self.cfg.use_ion:
        var.cross_Jion = dict(
            [
                ((sp, i), np.zeros(var.nbin))
                for sp in ion_sp
                for i in range(1, var.ion_branch[sp] + 1)
            ]
        )

    for sp in (
        photo_sp
    ):  # photodissociation only; photoionization takes a separate branch ratio file
        # for values outside the boundary => fill_value = 0
        inter_cross = interpolate.interp1d(
            cross_raw[sp]['lambda'],
            cross_raw[sp]['cross'],
            bounds_error=False,
            fill_value=0,
        )
        inter_cross_J = interpolate.interp1d(
            cross_raw[sp]['lambda'],
            cross_raw[sp]['disso'],
            bounds_error=False,
            fill_value=0,
        )
        inter_ratio = {}  # excluding ionization branches

        for i in range(
            1, var.n_branch[sp] + 1
        ):  # fill_value extends the first and last elements for branching ratios
            br_key = 'br_ratio_' + str(i)
            try:
                inter_ratio[i] = interpolate.interp1d(
                    ratio_raw[sp]['lambda'],
                    ratio_raw[sp][br_key],
                    bounds_error=False,
                    fill_value=(ratio_raw[sp][br_key][0], ratio_raw[sp][br_key][-1]),
                )
            except (ValueError, KeyError, IndexError):
                log.error(
                    'The branches in the network file does not match the branchong ratio file for '
                    + str(sp)
                )

        # using a loop instead of an array because it's easier to handle the branching ratios
        for n, ld in enumerate(bins):
            var.cross[sp][n] = inter_cross(ld)

            # using the branching ratio (from the files) to construct the individual cross section of each branch
            for i in range(1, var.n_branch[sp] + 1):
                var.cross_J[(sp, i)][n] = inter_cross_J(ld) * inter_ratio[i](ld)

        # make var.cross_T[(sp,i)] and var.cross_J_T[(sp,i)] here in 2D array: nz * bins (same shape as tau)
        # T-dependent cross sections are usually only measured in the photodissociation-relavent wavelengths so cross_tot = cross_diss
        if sp in self.cfg.T_cross_sp:
            # T list of species sp that have T-depedent cross sections (inclduing 300 K for inter_cross)
            T_list = np.array(var.cross_T_sp_list[sp])
            max_T_sp = np.amax(T_list)
            min_T_sp = np.amin(T_list)

            for lev, Tz in enumerate(atm.Tco):  # looping z
                Tz_between = False  # flag for Tz in between any two elements in T_list
                # define the interpolating T range
                if list(T_list[T_list <= Tz]) and list(T_list[T_list > Tz]):
                    Tlow = T_list[T_list <= Tz].max()  # closest T in T_list smaller than Tz
                    Thigh = T_list[T_list > Tz].min()  # closest T in T_list larger than Tz
                    Tz_between = True

                    # find the wavelength range that are included in both cross_T_raw[(sp,Tlow)] and cross_T_raw[(sp,Thigh)]
                    ld_min = max(
                        cross_T_raw[(sp, Tlow)]['lambda'][0],
                        cross_T_raw[(sp, Thigh)]['lambda'][0],
                    )
                    ld_max = min(
                        cross_T_raw[(sp, Tlow)]['lambda'][-1],
                        cross_T_raw[(sp, Thigh)]['lambda'][-1],
                    )
                    inter_cross_lowT = interpolate.interp1d(
                        cross_T_raw[(sp, Tlow)]['lambda'],
                        cross_T_raw[(sp, Tlow)]['cross'],
                        bounds_error=False,
                        fill_value=0,
                    )
                    inter_cross_highT = interpolate.interp1d(
                        cross_T_raw[(sp, Thigh)]['lambda'],
                        cross_T_raw[(sp, Thigh)]['cross'],
                        bounds_error=False,
                        fill_value=0,
                    )
                    inter_cross_J_lowT = interpolate.interp1d(
                        cross_T_raw[(sp, Tlow)]['lambda'],
                        cross_T_raw[(sp, Tlow)]['disso'],
                        bounds_error=False,
                        fill_value=0,
                    )
                    inter_cross_J_highT = interpolate.interp1d(
                        cross_T_raw[(sp, Thigh)]['lambda'],
                        cross_T_raw[(sp, Thigh)]['disso'],
                        bounds_error=False,
                        fill_value=0,
                    )

                    for n, ld in enumerate(bins):  # looping bins
                        # not within the T-cross wavelength range
                        if ld < ld_min or ld > ld_max:
                            var.cross_T[sp][lev, n] = var.cross[sp][n]
                            # don't forget the cross_J_T branches
                            for i in range(1, var.n_branch[sp] + 1):
                                var.cross_J_T[(sp, i)][lev, n] = var.cross_J[(sp, i)][n]

                        else:
                            # update: inerpolation in log10 for cross sections and linearly between Tlow and Thigh
                            log_lowT = np.log10(inter_cross_lowT(ld))
                            log_highT = np.log10(inter_cross_highT(ld))
                            if np.isinf(log_lowT):
                                log_lowT = -100.0  # replacing -inf with -100
                            if np.isinf(log_highT):
                                log_highT = -100.0

                            inter_T = interpolate.interp1d(
                                [Tlow, Thigh], [log_lowT, log_highT], axis=0
                            )  # at wavelength ld, interpolating between Tlow and Thigh in log10
                            if inter_T(Tz) == -100:
                                var.cross_T[sp][lev, n] == 0.0
                            else:
                                var.cross_T[sp][lev, n] = 10 ** (inter_T(Tz))

                            # update: inerpolation in log10 for cross sections and linearly between Tlow and Thigh
                            # using the branching ratio (from the files) to construct the individual cross section of each branch
                            for i in range(1, var.n_branch[sp] + 1):
                                J_log_lowT = np.log10(inter_cross_J_lowT(ld))
                                J_log_highT = np.log10(inter_cross_J_highT(ld))
                                if np.isinf(J_log_lowT):
                                    J_log_lowT = -100.0  # replacing -inf with -100
                                if np.isinf(J_log_highT):
                                    J_log_highT = -100.0

                                inter_cross_J_T = interpolate.interp1d(
                                    [Tlow, Thigh], [J_log_lowT, J_log_highT], axis=0
                                )

                                if inter_cross_J_T(Tz) == -100:
                                    var.cross_J_T[(sp, i)][lev, n] = 0.0
                                else:
                                    var.cross_J_T[(sp, i)][lev, n] = 10 ** (
                                        inter_cross_J_T(Tz)
                                    ) * inter_ratio[i](
                                        ld
                                    )  # same inter_ratio[i](ld) as the standard one above

                elif not list(
                    T_list[T_list < Tz]
                ):  # Tz equal or smaller than all T in T_list including 300K (empty list)
                    if min_T_sp == 300:
                        var.cross_T[sp][lev] = var.cross[
                            sp
                        ]  # using the cross section at room T
                        for i in range(1, var.n_branch[sp] + 1):
                            var.cross_J_T[(sp, i)][lev] = var.cross_J[(sp, i)]
                    else:  # min_T_sp != 300; T-cross lower than room temperature
                        # the wavelength range of cross_T_raw at T = min_T_sp
                        ld_min, ld_max = (
                            cross_T_raw[(sp, min_T_sp)]['lambda'][0],
                            cross_T_raw[(sp, min_T_sp)]['lambda'][-1],
                        )
                        inter_cross_lowT = interpolate.interp1d(
                            cross_T_raw[(sp, min_T_sp)]['lambda'],
                            cross_T_raw[(sp, min_T_sp)]['cross'],
                            bounds_error=False,
                            fill_value=0,
                        )
                        inter_cross_J_lowT = interpolate.interp1d(
                            cross_T_raw[(sp, min_T_sp)]['lambda'],
                            cross_T_raw[(sp, min_T_sp)]['disso'],
                            bounds_error=False,
                            fill_value=0,
                        )
                        for n, ld in enumerate(bins):  # looping bins
                            # not within the T-cross wavelength range
                            if ld < ld_min or ld > ld_max:
                                var.cross_T[sp][lev, n] = var.cross[sp][n]
                                # don't forget the cross_J_T branches
                                for i in range(1, var.n_branch[sp] + 1):
                                    var.cross_J_T[(sp, i)][lev, n] = var.cross_J[(sp, i)][n]
                            else:
                                var.cross_T[sp][lev, n] = inter_cross_lowT(ld)
                                # using the branching ratio (from the files) to construct the individual cross section of each branch
                                for i in range(1, var.n_branch[sp] + 1):
                                    var.cross_J_T[(sp, i)][lev, n] = inter_cross_J_lowT(
                                        ld
                                    ) * inter_ratio[i](
                                        ld
                                    )  # same inter_ratio[i](ld) as the standard one above

                else:  # Tz equal or larger than all T in T_list (empty list)
                    # the wavelength range of cross_T_raw[(sp,Thigh)]

                    if max_T_sp == 300:
                        var.cross_T[sp][lev] = var.cross[
                            sp
                        ]  # using the cross section at room T
                        for i in range(1, var.n_branch[sp] + 1):
                            var.cross_J_T[(sp, i)][lev] = var.cross_J[(sp, i)]
                    else:  # the wavelength range of cross_T_raw at T = max_T_sp
                        ld_min, ld_max = (
                            cross_T_raw[(sp, max_T_sp)]['lambda'][0],
                            cross_T_raw[(sp, max_T_sp)]['lambda'][-1],
                        )
                        inter_cross_highT = interpolate.interp1d(
                            cross_T_raw[(sp, max_T_sp)]['lambda'],
                            cross_T_raw[(sp, max_T_sp)]['cross'],
                            bounds_error=False,
                            fill_value=0,
                        )
                        inter_cross_J_highT = interpolate.interp1d(
                            cross_T_raw[(sp, max_T_sp)]['lambda'],
                            cross_T_raw[(sp, max_T_sp)]['disso'],
                            bounds_error=False,
                            fill_value=0,
                        )
                        for n, ld in enumerate(bins):  # looping bins
                            # not within the T-cross wavelength range
                            if ld < ld_min or ld > ld_max:
                                var.cross_T[sp][lev, n] = var.cross[sp][n]
                                # don't forget the cross_J_T branches
                                for i in range(1, var.n_branch[sp] + 1):
                                    var.cross_J_T[(sp, i)][lev, n] = var.cross_J[(sp, i)][n]
                            else:
                                var.cross_T[sp][lev, n] = inter_cross_highT(ld)

                                # using the branching ratio (from the files) to construct the individual cross section of each branch
                                for i in range(1, var.n_branch[sp] + 1):
                                    var.cross_J_T[(sp, i)][lev, n] = inter_cross_J_highT(
                                        ld
                                    ) * inter_ratio[i](
                                        ld
                                    )  # same inter_ratio[i](ld) as the standard one above

    if self.cfg.use_ion:
        for sp in ion_sp:
            if sp not in photo_sp:
                inter_cross = interpolate.interp1d(
                    cross_raw[sp]['lambda'],
                    cross_raw[sp]['cross'],
                    bounds_error=False,
                    fill_value=0,
                )

            inter_cross_Jion = interpolate.interp1d(
                cross_raw[sp]['lambda'],
                cross_raw[sp]['ion'],
                bounds_error=False,
                fill_value=0,
            )
            ion_inter_ratio = {}  # For ionization branches

            for i in range(
                1, var.ion_branch[sp] + 1
            ):  # fill_value extends the first and last elements for branching ratios
                br_key = 'br_ratio_' + str(i)
                try:
                    ion_inter_ratio[i] = interpolate.interp1d(
                        ion_ratio_raw[sp]['lambda'],
                        ion_ratio_raw[sp][br_key],
                        bounds_error=False,
                        fill_value=(
                            ion_ratio_raw[sp][br_key][0],
                            ion_ratio_raw[sp][br_key][-1],
                        ),
                    )
                except (KeyError, IndexError, ValueError):
                    log.error(
                        'The ionic branches in the network file does not match the branchong ratio file for '
                        + str(sp)
                    )

            for n, ld in enumerate(bins):
                # for species noe appeared in photodissociation but only in photoionization, like H
                if sp not in photo_sp:
                    var.cross[sp][n] = inter_cross(ld)
                for i in range(1, var.ion_branch[sp] + 1):
                    var.cross_Jion[(sp, i)][n] = inter_cross_Jion(ld) * ion_inter_ratio[i](
                        ld
                    )
    # end of if self.cfg.use_ion :

    # reading in cross sections of Rayleigh Scattering
    for sp in self.cfg.scat_sp:
        scat_raw[sp] = np.genfromtxt(
            CROSS_DIR + 'rayleigh/' + sp + '_scat.txt',
            dtype=float,
            skip_header=1,
            names=['lambda', 'cross'],
        )

        # for values outside the boundary => fill_value = 0
        inter_scat = interpolate.interp1d(
            scat_raw[sp]['lambda'], scat_raw[sp]['cross'], bounds_error=False, fill_value=0
        )

        for n, ld in enumerate(bins):
            var.cross_scat[sp][n] = inter_scat(ld)

read_rate(var, atm)

Source code in src/vulcan/op.py
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
def read_rate(self, var, atm):

    nz = self.cfg.nz

    (
        Rf,
        Rindx,
        a,
        n,
        E,
        a_inf,
        n_inf,
        E_inf,
        k,
        k_fun,
        k_inf,
        kinf_fun,
        k_fun_new,
        pho_rate_index,
    ) = (
        var.Rf,
        var.Rindx,
        var.a,
        var.n,
        var.E,
        var.a_inf,
        var.n_inf,
        var.E_inf,
        var.k,
        var.k_fun,
        var.k_inf,
        var.kinf_fun,
        var.k_fun_new,
        var.pho_rate_index,
    )
    ion_rate_index = var.ion_rate_index

    i = self.i
    re_tri, re_tri_k0 = self.re_tri, self.re_tri_k0
    list_tri = self.list_tri

    Tco = atm.Tco
    M = atm.M.copy()

    special_re = False
    conden_re = False
    recomb_re = False
    photo_re = False
    ion_re = False
    # end_re = False
    # br_read  = False
    # ion_br_read = False

    photo_sp = []
    ion_sp = []

    with open(self.cfg.network) as f:
        all_lines = f.readlines()
        for line_indx, line in enumerate(all_lines):
            # switch to 3-body and dissociation reations
            if line.startswith('# 3-body'):
                re_tri = True

            if line.startswith('# 3-body reactions without high-pressure rates'):
                re_tri_k0 = True

            elif line.startswith('# special'):
                re_tri = False
                re_tri_k0 = False
                special_re = True  # switch to reactions with special forms (hard coded)

            elif line.startswith('# condensation'):
                re_tri = False
                re_tri_k0 = False
                special_re = False
                conden_re = True
                var.conden_indx = i

            elif line.startswith('# radiative'):
                re_tri = False
                re_tri_k0 = False
                special_re = False
                conden_re = False
                recomb_re = True
                var.recomb_indx = i

            elif line.startswith('# photo'):
                re_tri = False
                re_tri_k0 = False
                special_re = False  # turn off reading in the special form
                conden_re = False
                recomb_re = False
                photo_re = True
                var.photo_indx = i

            elif line.startswith('# ionisation'):
                re_tri = False
                re_tri_k0 = False
                special_re = False  # turn off reading in the special form
                conden_re = False
                recomb_re = False
                photo_re = False
                ion_re = True
                var.ion_indx = i

            elif line.startswith('# reverse stops'):
                var.special_re = False
                var.stop_rev_indx = i

            # skip common lines and blank lines
            # ========================================================================================
            if (
                not line.startswith('#')
                and line.strip()
                and not special_re
                and not conden_re
                and not photo_re
                and not ion_re
            ):  # if not starts
                Rf[i] = line.partition('[')[-1].rpartition(']')[0].strip()
                li = line.partition(']')[-1].strip()
                columns = li.split()
                Rindx[i] = int(line.partition('[')[0].strip())
                a[i] = float(columns[0])
                n[i] = float(columns[1])
                E[i] = float(columns[2])

                # switching to trimolecular reactions (len(columns) > 3 for those with high-P limit rates)
                if re_tri and not re_tri_k0:
                    a_inf[i] = float(columns[3])
                    n_inf[i] = float(columns[4])
                    E_inf[i] = float(columns[5])
                    list_tri.append(i)

                if columns[-1].strip() == 'He':
                    re_He = i
                elif columns[-1].strip() == 'ex1':
                    re_CH3OH = i

                # Note: make the defaut i=i
                k_fun[i] = lambda temp, mm, i=i: a[i] * temp ** n[i] * np.exp(-E[i] / temp)

                if not re_tri:
                    k[i] = k_fun[i](Tco, M)

                # for 3-body reactions, also calculating k_inf
                elif re_tri and len(columns) >= 6:
                    kinf_fun[i] = lambda temp, i=i: (
                        a_inf[i] * temp ** n_inf[i] * np.exp(-E_inf[i] / temp)
                    )
                    k_fun_new[i] = lambda temp, mm, i=i: (
                        (a[i] * temp ** n[i] * np.exp(-E[i] / temp))
                        / (
                            1
                            + (a[i] * temp ** n[i] * np.exp(-E[i] / temp))
                            * mm
                            / (a_inf[i] * temp ** n_inf[i] * np.exp(-E_inf[i] / temp))
                        )
                    )

                    # k[i] = k_fun_new[i](Tco, M)
                    k_inf = a_inf[i] * Tco ** n_inf[i] * np.exp(-E_inf[i] / Tco)
                    k[i] = k_fun[i](Tco, M)
                    k[i] = k[i] / (1 + k[i] * M / k_inf)

                else:  # for 3-body reactions without high-pressure rates
                    k[i] = k_fun[i](Tco, M)

                i += 2
                # end if not
            # ========================================================================================
            elif special_re and line.strip() and not line.startswith('#'):
                Rindx[i] = int(line.partition('[')[0].strip())
                Rf[i] = line.partition('[')[-1].rpartition(']')[0].strip()

                if Rf[i] == 'OH + CH3 + M -> CH3OH + M':
                    log.debug('Using special form for the reaction: ' + Rf[i])

                    k[i] = 1.932e3 * Tco**-9.88 * np.exp(
                        -7544.0 / Tco
                    ) + 5.109e-11 * Tco**-6.25 * np.exp(-1433.0 / Tco)
                    k_inf = 1.031e-10 * Tco**-0.018 * np.exp(16.74 / Tco)
                    # the pressure dependence from Jasper 2017
                    Fc = (
                        0.1855 * np.exp(-Tco / 155.8)
                        + 0.8145 * np.exp(-Tco / 1675.0)
                        + np.exp(-4531.0 / Tco)
                    )
                    nn = 0.75 - 1.27 * np.log(Fc)
                    ff = np.exp(
                        np.log(Fc) / (1.0 + (np.log(k[i] * M / k_inf) / nn**2) ** 2)
                    )

                    k[i] = k[i] / (1 + k[i] * M / k_inf) * ff

                    k_fun[i] = lambda temp, mm, i=i: (
                        1.932e3 * temp**-9.88 * np.exp(-7544.0 / temp)
                        + 5.109e-11 * temp**-6.25 * np.exp(-1433.0 / temp)
                    )
                    kinf_fun[i] = lambda temp, mm, i=i: (
                        1.031e-10 * temp**-0.018 * np.exp(16.74 / temp)
                    )
                    k_fun_new[i] = lambda temp, mm, i=i: (
                        (
                            1.932e3 * temp**-9.88 * np.exp(-7544.0 / temp)
                            + 5.109e-11 * temp**-6.25 * np.exp(-1433.0 / temp)
                        )
                        / (
                            1
                            + (
                                1.932e3 * temp**-9.88 * np.exp(-7544.0 / temp)
                                + 5.109e-11 * temp**-6.25 * np.exp(-1433.0 / temp)
                            )
                            * mm
                            / (1.031e-10 * temp**-0.018 * np.exp(16.74 / temp))
                        )
                    )

                i += 2

            # Testing condensation
            elif conden_re and line.strip() and not line.startswith('#'):
                Rindx[i] = int(line.partition('[')[0].strip())
                Rf[i] = line.partition('[')[-1].rpartition(']')[0].strip()

                var.conden_re_list.append(i)
                k[i] = np.zeros(nz)
                k[i + 1] = np.zeros(nz)

                i += 2

            # setting photo dissociation reactions to zeros
            elif photo_re and line.strip() and not line.startswith('#'):
                k[i] = np.zeros(nz)
                Rf[i] = line.partition('[')[-1].rpartition(']')[0].strip()

                # adding the photo species
                photo_sp.append(Rf[i].split()[0])

                li = line.partition(']')[-1].strip()
                columns = li.split()
                Rindx[i] = int(line.partition('[')[0].strip())
                # columns[0]: the species being dissocited; branch index: columns[1]
                pho_rate_index[(columns[0], int(columns[1]))] = Rindx[i]

                # store the number of branches
                var.n_branch[columns[0]] = int(columns[1])

                i += 2

            # setting photo ionization reactions to zeros
            elif (
                ion_re and line.strip() and not line.startswith('#')
            ):  # and end_re == False
                k[i] = np.zeros(nz)
                Rf[i] = line.partition('[')[-1].rpartition(']')[0].strip()

                # chekcing if it already existed in the photo species
                ion_sp.append(Rf[i].split()[0])

                li = line.partition(']')[-1].strip()
                columns = li.split()
                Rindx[i] = int(line.partition('[')[0].strip())
                # columns[0]: the species being dissocited; branch index: columns[1]
                ion_rate_index[(columns[0], int(columns[1]))] = Rindx[i]

                # store the number of branches
                var.ion_branch[columns[0]] = int(columns[1])

                i += 2

    k_fun.update(k_fun_new)

    # store k into data_var
    # remeber k_fun has not removed reactions from remove_list
    var.k = k
    var.k_fun = k_fun
    var.kinf_fun = kinf_fun

    var.photo_sp = set(photo_sp)
    if self.cfg.use_ion:
        var.ion_sp = set(ion_sp)

    return var

remove_rate(var)

Source code in src/vulcan/op.py
473
474
475
476
477
478
479
480
481
def remove_rate(self, var):

    nz = self.cfg.nz

    for i in self.cfg.remove_list:
        var.k[i] = np.repeat(0.0, nz)
        var.k_fun[i] = lambda temp, mm, i=i: np.repeat(0.0, nz)

    return var

rev_rate(var, atm)

Source code in src/vulcan/op.py
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
def rev_rate(self, var, atm):

    nz = self.cfg.nz

    rev_list = range(2, var.stop_rev_indx, 2)
    # setting the rest reversal zeros
    for i in range(var.stop_rev_indx + 1, nr + 1, 2):
        var.k[i] = np.zeros(nz)

    Tco = atm.Tco

    # reversing rates and storing into data_var
    log.debug('Reverse rates from R1 to R' + str(var.stop_rev_indx - 2))
    log.debug('Rates greater than 1e-6:')
    for i in rev_list:
        if i in self.cfg.remove_list:
            var.k[i] = np.repeat(0.0, nz)
        else:
            var.k_fun[i] = lambda temp, mm, i=i: (
                var.k_fun[i - 1](temp, mm) / Gibbs(i - 1, temp)
            )
            var.k[i] = var.k[i - 1] / Gibbs(i - 1, Tco)

        if np.any(var.k[i] > 1.0e-6):
            log.debug('R' + str(i) + ' ' + var.Rf[i - 1] + ' :  ' + str(np.amax(var.k[i])))
        if np.any(var.k[i - 1] > 1.0e-6):
            log.debug(
                'R' + str(i - 1) + ' ' + var.Rf[i - 1] + ' :  ' + str(np.amax(var.k[i - 1]))
            )

    return var

Integration(odesolver, output, vulcan_cfg)

Bases: object

time-stepping until the stopping criteria (steady-state) is satisfied

all the operators required in the continuity equation: dn/dt + dphi/dz = P - L

or class incorporating the esential numerical operations?

Source code in src/vulcan/op.py
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
def __init__(self, odesolver, output, vulcan_cfg: Config):

    self.cfg = vulcan_cfg
    self.mtol = self.cfg.mtol
    self.atol = self.cfg.atol
    self.output = output

    self.odesolver = odesolver
    self.non_gas_sp = self.cfg.non_gas_sp
    self.use_settling = self.cfg.use_settling

    # warn about in-development features
    if self.cfg.use_vm_mol:
        log.warning(
            'New upwind scheme for molecular diffusion has been enabled in VULCAN (in development)'
        )
        raise RuntimeError(
            'You must disable the upwind scheme by setting `use_vm_mol=False`'
        )

    # import AGNI?
    if self.cfg.agni_call_frq > 0:
        from .agni import run_agni

        self.run_agni = run_agni

    # including photoionisation
    if self.cfg.use_photo:
        self.update_photo_frq = self.cfg.ini_update_photo_frq

    if self.cfg.use_condense:
        self.non_gas_sp_index = [species.index(sp) for sp in self.non_gas_sp]
        self.condense_sp_index = [species.index(sp) for sp in self.cfg.condense_sp]

atol = self.cfg.atol instance-attribute

cfg = vulcan_cfg instance-attribute

condense_sp_index = [(species.index(sp)) for sp in (self.cfg.condense_sp)] instance-attribute

mtol = self.cfg.mtol instance-attribute

non_gas_sp = self.cfg.non_gas_sp instance-attribute

non_gas_sp_index = [(species.index(sp)) for sp in (self.non_gas_sp)] instance-attribute

odesolver = odesolver instance-attribute

output = output instance-attribute

run_agni = run_agni instance-attribute

update_photo_frq = self.cfg.ini_update_photo_frq instance-attribute

use_settling = self.cfg.use_settling instance-attribute

backup(var)

Source code in src/vulcan/op.py
1250
1251
1252
1253
1254
def backup(self, var):
    var.y_prev = np.copy(var.y)
    var.dy_prev = np.copy(var.dy)
    var.atom_loss_prev = var.atom_loss.copy()
    return var

conden(var, atm)

Updating the condensation reactions according to the new number density using the condensation growth timescale in the contiuum regime (not in the kinetic regime)

Note that when n_g -> n_s, n_s is still the number density of "molecules", not "particles." So I scaled down the evaporation rate by n_mol. n_s / n_mol should also be used for plotting.

Source code in src/vulcan/op.py
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
def conden(self, var, atm):
    """
    Updating the condensation reactions according to the new number density
    using the condensation growth timescale in the contiuum regime (not in the kinetic regime)

    Note that when n_g -> n_s, n_s is still the number density of "molecules", not "particles."
    So I scaled down the evaporation rate by n_mol.
    n_s / n_mol should also be used for plotting.
    """

    nz = self.cfg.nz

    for re in var.conden_re_list:
        if var.Rf[re] == 'H2O -> H2O_l_s' and 'H2O' in self.cfg.condense_sp:
            # using realxation for water condensation
            if self.cfg.use_relax:
                var.k[re] = np.repeat(0.0, nz)
                var.k[re + 1] = np.repeat(0.0, nz)
            else:
                m = 18.0 / Navo
                rho_p = atm.rho_p['H2O_l_s']
                r_p = atm.r_p['H2O_l_s']
                # relative humidity
                sat_humidity = atm.sat_p['H2O'] / kb / atm.Tco * self.cfg.humidity

                # this is based on the kinetic regime
                rate_c = (
                    m
                    / (4 * rho_p)
                    * (8 * kb * atm.Tco / np.pi / m) ** 0.5
                    * (var.y[:, species.index('H2O')] - sat_humidity)
                    / r_p
                )

                # new approach: contiuum regime DM/rho c
                Dg = np.insert(
                    atm.Dzz[:, species.index('H2O')], 0, atm.Dzz[0, species.index('H2O')]
                )
                rate = (
                    Dg
                    * m
                    / rho_p
                    / r_p**2
                    * (var.y[:, species.index('H2O')] - sat_humidity)
                )

                # how many gas molecules are contained in one particle with the assumed size r_p
                n_mol = 4.0 / 3 * np.pi * r_p**3 * rho_p / m

                var.k[re] = rate
                var.k[re + 1] = rate  # /n_mol

                # positive: condensation
                var.k[re] = np.maximum(var.k[re], 0)
                # negative: evaporation
                var.k[re + 1] = np.minimum(var.k[re + 1], 0)
                var.k[re + 1] = np.abs(var.k[re + 1])

        elif var.Rf[re] == 'NH3 -> NH3_l' and 'NH3' in self.cfg.condense_sp:
            # using realxation for water condensation
            if self.cfg.use_relax:
                var.k[re] = np.repeat(0.0, nz)
                var.k[re + 1] = np.repeat(0.0, nz)
            else:
                m = 17.0 / Navo
                rho_p = atm.rho_p['NH3_l_s']
                r_p = atm.r_p['NH3_l_s']  # assuming 1 micron

                # rate_c = m/(4*rho_p)*(8*kb*atm.Tco/np.pi/m)**0.5 *(var.y[:,species.index('NH3')]-atm.sat_p['NH3']/kb/atm.Tco)/r_p

                # new approach: contiuum regime DM/rho c
                Dg = np.insert(
                    atm.Dzz[:, species.index('NH3')], 0, atm.Dzz[0, species.index('NH3')]
                )
                rate = (
                    Dg
                    * m
                    / rho_p
                    / r_p**2
                    * (var.y[:, species.index('NH3')] - atm.sat_p['NH3'] / kb / atm.Tco)
                )

                # how many gas molecules are contained in one particle with the assumed size r_p
                n_mol = 4.0 / 3 * np.pi * r_p**3 * rho_p / m

                var.k[re] = rate
                var.k[re + 1] = rate  # /n_mol

                # positive: condensation
                var.k[re] = np.maximum(var.k[re], 0)
                # negative: evaporation
                var.k[re + 1] = np.minimum(var.k[re + 1], 0)
                var.k[re + 1] = np.abs(var.k[re + 1])

        elif var.Rf[re] == 'H2SO4 -> H2SO4_l' and 'H2SO4' in self.cfg.condense_sp:
            m = 98.022 / Navo
            rho_p = atm.rho_p['H2SO4_l']
            r_p = atm.r_p['H2SO4_l']

            # new approach: contiuum regime DM/rho c
            Dg = np.insert(
                atm.Dzz[:, species.index('H2SO4')], 0, atm.Dzz[0, species.index('H2SO4')]
            )
            rate = (
                Dg
                * m
                / rho_p
                / r_p**2
                * (var.y[:, species.index('H2SO4')] - atm.sat_p['H2SO4'] / kb / atm.Tco)
            )

            # rate_c = m/(4*rho_p)*(8*kb*atm.Tco/np.pi/m)**0.5 *(var.y[:,species.index('H2SO4')]-atm.sat_p['H2SO4']/kb/atm.Tco)/r_p

            # how many gas molecules are contained in one particle with the assumed size r_p
            n_mol = 4.0 / 3 * np.pi * r_p**3 * rho_p / m

            var.k[re] = rate
            var.k[re + 1] = rate  # /n_mol

            # positive: condensation
            var.k[re] = np.maximum(var.k[re], 0)
            # negative: evaporation
            var.k[re + 1] = np.minimum(var.k[re + 1], 0)
            var.k[re + 1] = np.abs(var.k[re + 1])

        elif var.Rf[re] == 'S2 -> S2_l_s' and 'S2' in self.cfg.condense_sp:
            m = 45.019 / Navo
            rho_p = atm.rho_p['S2_l_s']
            r_p = atm.r_p['S2_l_s']

            # new approach: contiuum regime DM/rho c
            Dg = np.insert(
                atm.Dzz[:, species.index('S2')], 0, atm.Dzz[0, species.index('S2')]
            )
            rate = (
                Dg
                * m
                / rho_p
                / r_p**2
                * (var.y[:, species.index('S2')] - atm.sat_p['S2'] / kb / atm.Tco)
            )

            # how many gas molecules are contained in one particle with the assumed size r_p
            n_mol = 4.0 / 3 * np.pi * r_p**3 * rho_p / m

            var.k[re] = rate
            var.k[re + 1] = rate  # /n_mol

            # positive: condensation
            var.k[re] = np.maximum(var.k[re], 0)
            # negative: evaporation
            var.k[re + 1] = np.minimum(var.k[re + 1], 0)
            var.k[re + 1] = np.abs(var.k[re + 1])

        elif var.Rf[re] == 'S4 -> S4_l_s' and 'S4' in self.cfg.condense_sp:
            m = 32.06 * 4 / Navo
            rho_p = atm.rho_p['S4_l_s']
            r_p = atm.r_p['S4_l_s']

            # new approach: contiuum regime DM/rho c
            Dg = np.insert(
                atm.Dzz[:, species.index('S4')], 0, atm.Dzz[0, species.index('S4')]
            )
            rate = (
                Dg
                * m
                / rho_p
                / r_p**2
                * (var.y[:, species.index('S4')] - atm.sat_p['S4'] / kb / atm.Tco)
            )

            # how many gas molecules are contained in one particle with the assumed size r_p
            n_mol = 4.0 / 3 * np.pi * r_p**3 * rho_p / m

            # acc_ratio = var.y[:,species.index('S4_l_s')]/n_mol /self.cfg.n_ccn # accomdation ratio: 0 all ccn available 1=no more free ccn
            # lim_factor = 1-acc_ratio
            # lim_factor[lim_factor<0] = 0

            var.k[re] = rate  # *lim_factor
            var.k[re + 1] = rate  # /n_mol

            # positive: condensation
            var.k[re] = np.maximum(var.k[re], 0)
            # negative: evaporation
            var.k[re + 1] = np.minimum(var.k[re + 1], 0)
            var.k[re + 1] = np.abs(var.k[re + 1])

        elif var.Rf[re] == 'S8 -> S8_l_s' and 'S8' in self.cfg.condense_sp:
            m = 360.152 / Navo
            rho_p = atm.rho_p['S8_l_s']
            r_p = atm.r_p['S8_l_s']

            # new approach: contiuum regime DM/rho c
            Dg = np.insert(
                atm.Dzz[:, species.index('S8')], 0, atm.Dzz[0, species.index('S8')]
            )
            rate = (
                Dg
                * m
                / rho_p
                / r_p**2
                * (var.y[:, species.index('S8')] - atm.sat_p['S8'] / kb / atm.Tco)
            )

            # how many gas molecules are contained in one particle with the assumed size r_p
            n_mol = 4.0 / 3 * np.pi * r_p**3 * rho_p / m

            var.k[re] = rate
            var.k[re + 1] = rate  # /n_mol

            # positive: condensation
            var.k[re] = np.maximum(var.k[re], 0)
            # negative: evaporation
            var.k[re + 1] = np.minimum(var.k[re + 1], 0)
            var.k[re + 1] = np.abs(var.k[re + 1])

        elif var.Rf[re] == 'C -> C_s' and 'C' in self.cfg.condense_sp:
            m = 12.011 / Navo
            rho_p = atm.rho_p['C_s']
            r_p = atm.r_p['C_s']

            # new approach: contiuum regime DM/rho c
            Dg = np.insert(
                atm.Dzz[:, species.index('C')], 0, atm.Dzz[0, species.index('C')]
            )
            rate = (
                Dg
                * m
                / rho_p
                / r_p**2
                * (var.y[:, species.index('C')] - atm.sat_p['C'] / kb / atm.Tco)
            )

            # how many gas molecules are contained in one particle with the assumed size r_p
            n_mol = 4.0 / 3 * np.pi * r_p**3 * rho_p / m

            var.k[re] = rate
            var.k[re + 1] = rate  # /n_mol

            # positive: condensation
            var.k[re] = np.maximum(var.k[re], 0)
            # negative: evaporation
            var.k[re + 1] = np.minimum(var.k[re + 1], 0)
            var.k[re + 1] = np.abs(var.k[re + 1])

    return var

conv(var, para, atm, out=False, print_freq=100)

funtion returns TRUE if the convergence condition is satisfied

Source code in src/vulcan/op.py
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
def conv(self, var, para, atm, out=False, print_freq=100):
    """
    funtion returns TRUE if the convergence condition is satisfied
    """
    st_factor, mtol_conv, atol, yconv_cri, slope_cri, yconv_min = (
        self.cfg.st_factor,
        self.cfg.mtol_conv,
        self.cfg.atol,
        self.cfg.yconv_cri,
        self.cfg.slope_cri,
        self.cfg.yconv_min,
    )
    y, ymix, y_time, t_time = var.y.copy(), var.ymix.copy(), var.y_time, var.t_time
    count = para.count

    # slope_min = min( np.amin(atm.Kzz)/np.amax(0.1*atm.Hp)**2 , 1.e-8)
    slope_min = min(np.amin(atm.Kzz / (0.1 * atm.Hp[:-1]) ** 2), 1.0e-8)
    slope_min = max(slope_min, 1.0e-10)

    indx = np.abs(t_time - var.t * st_factor).argmin()
    if indx == para.count - 1:
        indx -= 1  # Important!! For dt larger than half of the runtime (count-1 is the last one)

    # Don't check more than self.cfg.conv_step (1000) steps back
    indx = max(para.count - self.cfg.conv_step, indx)

    # TEST
    longdy = np.abs((y_time[count - 1] - y_time[indx]) / np.vstack(atm.n_0))
    longdy[ymix < mtol_conv] = 0
    longdy[y < atol] = 0

    # to get rid off non-convergent species, e.g. HC3N without sinks
    if 'conver_ignore' in dir(self.cfg):
        for sp in self.cfg.conver_ignore:
            longdy[:, species.index(sp)] = 0  # added 2023

    if self.cfg.use_condense:
        longdy[:, self.non_gas_sp_index] = 0

    with np.errstate(
        divide='ignore', invalid='ignore'
    ):  # ignoring nan when devided by zero
        where_varies_most = longdy / ymix
    para.where_varies_most = where_varies_most

    longdy = np.amax(longdy[ymix > 0] / ymix[ymix > 0])
    longdydt = longdy / (t_time[-1] - t_time[indx])
    # store longdy and longdydt
    var.longdy, var.longdydt = longdy, longdydt

    if (
        longdy < yconv_cri
        and longdydt < slope_cri
        or longdy < yconv_min
        and longdydt < slope_min
    ) and var.aflux_change < self.cfg.flux_cri:
        return True

    return False

f_dy(var, para)

Source code in src/vulcan/op.py
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
def f_dy(self, var, para):  # y, y_prev, ymix, yconv, count, dt
    if para.count == 0:
        var.dy, var.dydt = 1.0, 1.0
        return var
    y, ymix, y_prev = var.y, var.ymix, var.y_prev
    dy = np.abs(y - y_prev)
    dy[ymix < self.cfg.mtol] = 0
    dy[y < self.cfg.atol] = 0
    dy = np.amax(dy[y > 0] / y[y > 0])

    var.dy, var.dydt = dy, dy / var.dt

    return var

h2o_conden_evap_relax(var, atm)

Source code in src/vulcan/op.py
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
def h2o_conden_evap_relax(self, var, atm):
    m = 18.0 / Navo
    rho_p = atm.rho_p['H2O_l_s']  # mix of water and ice
    r_p = atm.r_p['H2O_l_s']
    # relative humidity
    sat_humidity = atm.sat_p['H2O'] / kb / atm.Tco * self.cfg.humidity

    # new approach: contiuum regime DM/rho c
    Dg = np.insert(atm.Dzz[:, species.index('H2O')], 0, atm.Dzz[0, species.index('H2O')])
    tau = 1.0 / (Dg * m / rho_p / r_p**2 * (var.y[:, species.index('H2O')] - sat_humidity))
    conden_indx = np.where(tau > 0)
    evap_indx = np.where(tau < 0)
    sat_mix = sat_humidity / atm.n_0
    # tau = np.abs(tau)

    # implicit-Euler to remove water
    y_conden = (var.ymix[:, species.index('H2O')] + var.dt / tau * sat_mix) / (
        1.0 + var.dt / tau
    )

    # evaporation to remove ice/water(liquid)
    ice_loss = (
        (var.y[:, species.index('H2O')] - sat_humidity) * var.dt / tau
    )  # both tau < 0 and y_H2O - sat < 0
    # cannot lose more than it has
    ice_loss = np.minimum(var.y[:, species.index('H2O_l_s')], ice_loss)

    # how many gas molecules are contained in one particle with the assumed size r_p
    # n_mol = 4./3*np.pi*r_p**3 *rho_p /m
    # and converting the mixing ratio of molecules /cm3 to droplets/cm3
    # "move" the condensed water to H2O_l_s
    var.ymix[conden_indx, species.index('H2O_l_s')] += (
        var.ymix[conden_indx, species.index('H2O')] - y_conden[conden_indx]
    )
    var.ymix[conden_indx, species.index('H2O')] = y_conden[conden_indx]
    # store the saturated parts (only relax where ymix > ysat)

    var.ymix[evap_indx, species.index('H2O')] += ice_loss[evap_indx] / atm.n_0[evap_indx]
    var.ymix[evap_indx, species.index('H2O_l_s')] -= (
        ice_loss[evap_indx] / atm.n_0[evap_indx]
    )

    var.y = var.ymix * np.vstack(np.sum(var.y[:, atm.gas_indx], axis=1))

    return var

h2o_conden_relax(var, atm)

Source code in src/vulcan/op.py
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
def h2o_conden_relax(self, var, atm):
    m = 18.0 / Navo
    rho_p = 0.95  # mix of water and ice
    r_p = atm.r_p['H2O_l_s']
    # relative humidity
    sat_humidity = atm.sat_p['H2O'] / kb / atm.Tco * self.cfg.humidity

    # new approach: contiuum regime DM/rho c
    Dg = np.insert(atm.Dzz[:, species.index('H2O')], 0, atm.Dzz[0, species.index('H2O')])
    tau = np.abs(
        1.0 / (Dg * m / rho_p / r_p**2 * (var.y[:, species.index('H2O')] - sat_humidity))
    )
    sat_mix = sat_humidity / atm.n_0

    # implicit-Euler to remove water
    y_conden = (var.ymix[:, species.index('H2O')] + var.dt / tau * sat_mix) / (
        1.0 + var.dt / tau
    )
    conden_indx = np.where(var.ymix[:, species.index('H2O')] > sat_mix)

    # how many gas molecules are contained in one particle with the assumed size r_p
    n_mol = 4.0 / 3 * np.pi * r_p**3 * rho_p / m
    # and converting the mixing ratio of molecules /cm3 to droplets/cm3
    # "move" the condensed water to H2O_l_s
    var.ymix[conden_indx, species.index('H2O_l_s')] += (
        var.ymix[conden_indx, species.index('H2O')] - y_conden[conden_indx]
    )  # /n_mol

    var.ymix[conden_indx, species.index('H2O')] = y_conden[conden_indx]
    # restore the unsaturated parts (only relax where ymix > ysat)

    var.y = var.ymix * np.vstack(np.sum(var.y[:, atm.gas_indx], axis=1))

    return var

nh3_conden_evap_relax(var, atm)

Source code in src/vulcan/op.py
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
def nh3_conden_evap_relax(self, var, atm):
    m = 17.0 / Navo
    rho_p = atm.rho_p['NH3_l_s']  # mix of water and ice
    r_p = atm.r_p['NH3_l_s']
    # relative humidity
    sat_p = atm.sat_p['NH3'] / kb / atm.Tco
    sat_mix = sat_p / atm.n_0

    conden_top = np.argmin(sat_mix)

    # new approach: contiuum regime DM/rho c
    Dg = np.insert(atm.Dzz[:, species.index('NH3')], 0, atm.Dzz[0, species.index('NH3')])
    tau = 1.0 / (Dg * m / rho_p / r_p**2 * (var.y[:, species.index('NH3')] - sat_p))
    conden_indx = np.where(tau > 0)[0]
    evap_indx = np.where(tau < 0)[0]

    # above the top of condensation zone, there should NOT be any condensation when using the relaxiation method
    conden_indx = [i for i in conden_indx if i <= conden_top]
    # evap_indx = [i for i in evap_indx if i <= conden_top]

    # implicit-Euler to remove water
    y_conden = (var.ymix[:, species.index('NH3')] + var.dt / tau * sat_mix) / (
        1.0 + var.dt / tau
    )

    # evaporation to remove ice/water(liquid)
    ice_loss = (
        (var.y[:, species.index('NH3')] - sat_p) * var.dt / tau
    )  # both tau < 0 and y_H2O - sat < 0
    # cannot lose more than it has
    ice_loss = np.minimum(var.y[:, species.index('NH3_l_s')], ice_loss)

    # how many gas molecules are contained in one particle with the assumed size r_p
    # n_mol = 4./3*np.pi*r_p**3 *rho_p /m
    # and converting the mixing ratio of molecules /cm3 to droplets/cm3
    # "move" the condensed water to H2O_l_s
    var.ymix[conden_indx, species.index('NH3_l_s')] += (
        var.ymix[conden_indx, species.index('NH3')] - y_conden[conden_indx]
    )
    var.ymix[conden_indx, species.index('NH3')] = y_conden[conden_indx]
    # store the saturated parts (only relax where ymix > ysat)

    var.ymix[evap_indx, species.index('NH3')] += ice_loss[evap_indx] / atm.n_0[evap_indx]
    # instaneous evaporation
    var.ymix[evap_indx, species.index('NH3_l_s')] -= (
        ice_loss[evap_indx] / atm.n_0[evap_indx]
    )
    # var.ymix[evap_indx,species.index('NH3_l_s')] = 0

    var.ymix[:, species.index('NH3_l_s')] = np.maximum(
        var.ymix[:, species.index('NH3_l_s')], 0
    )  # cannot lose more than it has

    var.y = var.ymix * np.vstack(np.sum(var.y[:, atm.gas_indx], axis=1))

    return var

save_step(var, para)

save current values of y and add 1 to the counter

Source code in src/vulcan/op.py
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
def save_step(self, var, para):
    """
    save current values of y and add 1 to the counter
    """
    var.t += var.dt
    para.count += 1

    # tmp = list(var.y)
    # if para.count % self.y_time_freq ==0:
    var.y_time.append(var.y)
    # var.ymix_time.append(var.ymix.copy())
    var.t_time.append(var.t)

    # only used in PI_control
    # var.dy_time.append(var.y)
    # var.dydt_time.append(var.dydt)
    var.atom_loss_time.append(list(var.atom_loss.values()))

    return var, para

stop(var, para, atm)

To check the convergence criteria and stop the integration

Source code in src/vulcan/op.py
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
def stop(self, var, para, atm):
    """
    To check the convergence criteria and stop the integration
    """
    if (
        var.t > self.cfg.trun_min
        and para.count > self.cfg.count_min
        and self.conv(var, para, atm)
    ):
        log.info('Integration successful with ' + str(para.count) + ' steps')
        log.info('long dy, long dydt = ' + str(var.longdy) + ', ' + str(var.longdydt))
        log.debug('Actinic flux change: ' + '{:.2E}'.format(var.aflux_change))
        self.output.print_end_msg(var, para)
        para.end_case = 1
        return True
    elif var.t > self.cfg.runtime:
        log.warning(
            'After ------- %s seconds -------' % (time.time() - para.start_time)
            + ' s CPU time'
        )
        log.warning('Integration not completed...')
        log.warning('Maximal allowed runtime exceeded (' + str(self.cfg.runtime) + ' sec)!')
        para.end_case = 2
        return True
    elif para.count > self.cfg.count_max:
        log.warning(
            'After ------- %s seconds -------' % (time.time() - para.start_time)
            + ' s CPU time'
        )
        log.warning('Integration not completed...')
        log.warning('Maximal allowed steps exceeded (' + str(self.cfg.count_max) + ')!')
        para.end_case = 3
        return True

update_mu_dz(var, atm, make_atm)

Source code in src/vulcan/op.py
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
def update_mu_dz(self, var, atm, make_atm):  # y, ni, spec, Tco, pco

    # gravity
    gz = atm.g
    pref_indx = atm.pref_indx
    Tco, pico = atm.Tco, atm.pico.copy()
    # calculating mu (mean molecular weight)
    atm = make_atm.mean_mass(var, atm, ni)
    Hp = atm.Hp
    nz = self.cfg.nz

    for i in range(pref_indx, nz):
        if i == pref_indx:
            atm.g[i] = atm.gs
            Hp[i] = kb * Tco[i] / (atm.mu[i] / Navo * atm.gs)
        else:
            atm.g[i] = atm.gs * (self.cfg.Rp / (self.cfg.Rp + atm.zco[i])) ** 2
            Hp[i] = kb * Tco[i] / (atm.mu[i] / Navo * atm.g[i])
        atm.dz[i] = Hp[i] * np.log(
            pico[i] / pico[i + 1]
        )  # pico[i+1] has a lower P than pico[i] (higer height)
        atm.zco[i + 1] = atm.zco[i] + atm.dz[i]  # zco is set zero at 1bar for gas giants

    # for pref_indx != zero
    if not pref_indx == 0:
        for i in range(pref_indx - 1, -1, -1):
            atm.g[i] = atm.gs * (self.cfg.Rp / (self.cfg.Rp + atm.zco[i + 1])) ** 2
            Hp[i] = kb * Tco[i] / (atm.mu[i] / Navo * atm.g[i])
            atm.dz[i] = Hp[i] * np.log(pico[i] / pico[i + 1])
            atm.zco[i] = atm.zco[i + 1] - atm.dz[i]  # from i+1 propogating down to i

    zmco = 0.5 * (atm.zco + np.roll(atm.zco, -1))
    atm.zmco = zmco[:-1]
    dzi = 0.5 * (atm.dz + np.roll(atm.dz, 1))
    atm.dzi = dzi[1:]

    # for the molecular diffsuion
    if self.cfg.use_moldiff:
        Ti = 0.5 * (Tco + np.roll(Tco, -1))
        atm.Ti = Ti[:-1]
        Hpi = 0.5 * (Hp + np.roll(Hp, -1))
        atm.Hpi = Hpi[:-1]

    return atm

update_phi_esc(var, atm)

Source code in src/vulcan/op.py
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
def update_phi_esc(self, var, atm):  # updating diffusion-mimited escape

    # Diffusion limited escape
    for sp in self.cfg.diff_esc:
        # atm.top_flux[species.index(sp)] = - atm.Dzz[-1,species.index(sp)] *var.y[-1,species.index(sp)] /atm.Hp[-1]
        atm.top_flux[species.index(sp)] = (
            -atm.Dzz[-1, species.index(sp)]
            * var.y[-1, species.index(sp)]
            * (
                1.0 / atm.Hp[-1]
                - atm.ms[species.index(sp)] * atm.g[-1] / (Navo * kb * atm.Tco[-1])
            )
        )
        atm.top_flux[species.index(sp)] = max(
            atm.top_flux[species.index(sp)], self.cfg.max_flux * (-1)
        )

    return atm

ODESolver(vulcan_cfg)

Bases: object

Source code in src/vulcan/op.py
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
def __init__(self, vulcan_cfg: Config):  # do I always need to update var, atm, para ?

    self.cfg = vulcan_cfg
    self.mtol = self.cfg.mtol
    self.atol = self.cfg.atol
    self.non_gas_sp = self.cfg.non_gas_sp

    if self.cfg.use_condense:
        self.non_gas_sp_index = [species.index(sp) for sp in self.non_gas_sp]
        self.condense_sp_index = [species.index(sp) for sp in self.cfg.condense_sp]

    self.fix_sp_bot_index = [species.index(sp) for sp in self.cfg.use_fix_sp_bot.keys()]
    self.fix_sp_bot_mix = np.array(
        [self.cfg.use_fix_sp_bot[sp] for sp in self.cfg.use_fix_sp_bot.keys()]
    )

atol = self.cfg.atol instance-attribute

cfg = vulcan_cfg instance-attribute

condense_sp_index = [(species.index(sp)) for sp in (self.cfg.condense_sp)] instance-attribute

fix_sp_bot_index = [(species.index(sp)) for sp in (self.cfg.use_fix_sp_bot.keys())] instance-attribute

fix_sp_bot_mix = np.array([(self.cfg.use_fix_sp_bot[sp]) for sp in (self.cfg.use_fix_sp_bot.keys())]) instance-attribute

mtol = self.cfg.mtol instance-attribute

non_gas_sp = self.cfg.non_gas_sp instance-attribute

non_gas_sp_index = [(species.index(sp)) for sp in (self.non_gas_sp)] instance-attribute

clip(var, para, atm, pos_cut=0, nega_cut=-1)

function to clip samll and negative values and to calculate the particle loss

Source code in src/vulcan/op.py
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
def clip(self, var, para, atm, pos_cut=0, nega_cut=-1):
    """
    function to clip samll and negative values
    and to calculate the particle loss
    """
    y, ymix = var.y, var.ymix.copy()

    para.small_y += np.abs(np.sum(y[np.logical_and(y < pos_cut, y >= 0)]))
    para.nega_y += np.abs(np.sum(y[np.logical_and(y > nega_cut, y <= 0)]))
    y[np.logical_and(y < pos_cut, y >= nega_cut)] = 0.0

    # Also setting y=0 when ymix<mtol
    y[np.logical_and(ymix < self.mtol, y < 0)] = 0.0

    var = self.loss(var)

    # store y and ymix
    # TEST condensation excluding non-gaseous species
    if self.cfg.non_gas_sp:
        var.y, var.ymix = y, var.y / np.vstack(np.sum(var.y[:, atm.gas_indx], axis=1))
    else:
        var.y, var.ymix = y, y / np.vstack(np.sum(y, axis=1))
    # TEST condensation excluding non-gaseous species

    return var, para

compute_J(var, atm)

computes photodissociation/photoionization rates; including T-dependent cross sections

Source code in src/vulcan/op.py
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
def compute_J(self, var, atm):  # the vectorized version
    """
    computes photodissociation/photoionization rates; including T-dependent cross sections
    """
    flux = var.aflux
    nz = self.cfg.nz

    diss_cross = var.cross_J  # use the key (sp, branch index) e.g. ("H2O", 1); 1D array
    diss_cross_T = var.cross_J_T  # 2D array with the shape of nz * bins

    bins = var.bins
    n_branch = var.n_branch

    # reset to zeros every time
    var.J_sp = dict(
        [((sp, bn), np.zeros(nz)) for sp in var.photo_sp for bn in range(n_branch[sp] + 1)]
    )

    for sp in var.photo_sp:
        # shape: flux (nz,nbin) cross (nbin)

        for nbr in range(1, n_branch[sp] + 1):  # axis=1 is to sum over all wavelength
            if sp in self.cfg.T_cross_sp:
                var.J_sp[(sp, nbr)] = np.sum(
                    flux[:, : var.sflux_din12_indx]
                    * diss_cross_T[(sp, nbr)][:, : var.sflux_din12_indx]
                    * var.dbin1,
                    axis=1,
                )
                var.J_sp[(sp, nbr)] -= (
                    0.5
                    * (
                        flux[:, 0] * diss_cross_T[(sp, nbr)][:, 0]
                        + flux[:, var.sflux_din12_indx - 1]
                        * diss_cross_T[(sp, nbr)][:, var.sflux_din12_indx - 1]
                    )
                    * var.dbin1
                )
                var.J_sp[(sp, nbr)] += np.sum(
                    flux[:, var.sflux_din12_indx :]
                    * diss_cross_T[(sp, nbr)][:, var.sflux_din12_indx :]
                    * var.dbin2,
                    axis=1,
                )
                var.J_sp[(sp, nbr)] -= (
                    0.5
                    * (
                        flux[:, var.sflux_din12_indx]
                        * diss_cross_T[(sp, nbr)][:, var.sflux_din12_indx]
                        + flux[:, -1] * diss_cross_T[(sp, nbr)][:, -1]
                    )
                    * var.dbin2
                )

            else:
                var.J_sp[(sp, nbr)] = np.sum(
                    flux[:, : var.sflux_din12_indx]
                    * diss_cross[(sp, nbr)][: var.sflux_din12_indx]
                    * var.dbin1,
                    axis=1,
                )
                var.J_sp[(sp, nbr)] -= (
                    0.5
                    * (
                        flux[:, 0] * diss_cross[(sp, nbr)][0]
                        + flux[:, var.sflux_din12_indx - 1]
                        * diss_cross[(sp, nbr)][var.sflux_din12_indx - 1]
                    )
                    * var.dbin1
                )
                var.J_sp[(sp, nbr)] += np.sum(
                    flux[:, var.sflux_din12_indx :]
                    * diss_cross[(sp, nbr)][var.sflux_din12_indx :]
                    * var.dbin2,
                    axis=1,
                )
                var.J_sp[(sp, nbr)] -= (
                    0.5
                    * (
                        flux[:, var.sflux_din12_indx]
                        * diss_cross[(sp, nbr)][var.sflux_din12_indx]
                        + flux[:, -1] * diss_cross[(sp, nbr)][-1]
                    )
                    * var.dbin2
                )

            # summing over all branches
            var.J_sp[(sp, 0)] += var.J_sp[(sp, nbr)]
            # incoperating J into rate coefficients
            if var.pho_rate_index[(sp, nbr)] not in self.cfg.remove_list:
                var.k[var.pho_rate_index[(sp, nbr)]] = (
                    var.J_sp[(sp, nbr)] * self.cfg.f_diurnal
                )  # f_diurnal = 0.5 for Earth; = 1 for tidally-loced planets

compute_Jion(var, atm)

compute the photoionization rate haven't considered any temperature dependence yet

Source code in src/vulcan/op.py
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
def compute_Jion(self, var, atm):
    """
    compute the photoionization rate
    haven't considered any temperature dependence yet
    """
    nz = self.cfg.nz
    flux = var.aflux
    ion_cross = var.cross_Jion  # use the key (sp, br) e.g. ("H2O", 1)

    bins = var.bins
    n_branch = var.ion_branch

    # reset to zeros every time
    var.Jion_sp = dict(
        [((sp, bn), np.zeros(nz)) for sp in var.ion_sp for bn in range(n_branch[sp] + 1)]
    )

    for sp in var.ion_sp:
        # shape: flux (nz,nbin) cross (nbin)

        # convert to actinic flux *1/(hc/ld)
        for nbr in range(1, n_branch[sp] + 1):
            # axis=1 is to sum over all wavelength
            var.Jion_sp[(sp, nbr)] = np.sum(
                flux[:, : var.sflux_din12_indx]
                * ion_cross[(sp, nbr)][: var.sflux_din12_indx]
                * var.dbin1,
                axis=1,
            )
            var.Jion_sp[(sp, nbr)] -= (
                0.5
                * (
                    flux[:, 0] * ion_cross[(sp, nbr)][0]
                    + flux[:, var.sflux_din12_indx - 1]
                    * ion_cross[(sp, nbr)][var.sflux_din12_indx - 1]
                )
                * var.dbin1
            )
            var.Jion_sp[(sp, nbr)] += np.sum(
                flux[:, var.sflux_din12_indx :]
                * ion_cross[(sp, nbr)][var.sflux_din12_indx :]
                * var.dbin2,
                axis=1,
            )
            var.Jion_sp[(sp, nbr)] -= (
                0.5
                * (
                    flux[:, var.sflux_din12_indx]
                    * ion_cross[(sp, nbr)][var.sflux_din12_indx]
                    + flux[:, -1] * ion_cross[(sp, nbr)][-1]
                )
                * var.dbin2
            )

            # 0 is the total dissociation rate
            # summing all branches

            var.Jion_sp[(sp, 0)] += var.Jion_sp[(sp, nbr)]
            # incoperating J into rate coefficients
            if var.ion_rate_index[(sp, nbr)] not in self.cfg.remove_list:
                var.k[var.ion_rate_index[(sp, nbr)]] = (
                    var.Jion_sp[(sp, nbr)] * self.cfg.f_diurnal
                )  # f_diurnal = 0.5 for Earth; = 1 for tidally-loced planets

compute_flux(var, atm)

Source code in src/vulcan/op.py
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
def compute_flux(self, var, atm):  # Vectorise this loop!
    # change it to stagerred grids
    # top: stellar flux
    # bottom BC: zero upcoming flux

    # Note!!! Matej's mu is defined in the outgoing hemisphere so his mu<0
    # My cos[sl_angle] is always 0<=mu<=1
    # Converting my mu to Matej's mu (e.g. 45 deg -> 135 deg)

    nz = self.cfg.nz

    mu_ang = -1.0 * np.cos(self.cfg.sl_angle)
    edd = self.cfg.edd
    tau = var.tau

    # delta_tau (length nz) is used in the transmission function
    delta_tau = tau - np.roll(
        tau, -1, axis=0
    )  # np.roll(tau,-1,axis=0) are the upper layers
    delta_tau = delta_tau[:-1]

    # single-scattering albedo
    nbins = len(var.bins)
    tot_abs, tot_scat = np.zeros((nz, nbins)), np.zeros((nz, nbins))
    for sp in var.photo_sp:
        tot_abs += np.vstack(var.ymix[:, species.index(sp)]) * var.cross[sp]  # nz * nbins
    for sp in self.cfg.scat_sp:
        tot_scat += np.vstack(var.ymix[:, species.index(sp)]) * var.cross_scat[sp]

    total = tot_abs + tot_scat

    w0 = tot_scat / (tot_abs + tot_scat)  # 2D: nz * nbins
    # tot_abs + tot_scat can be zero when certain gas (e.g. H2) does not exist

    # Replace nan with zero and inf with very large numbers
    w0 = np.nan_to_num(w0)

    # to avoit w0=1
    w0 = np.minimum(w0, 1.0 - 1.0e-8)

    # sflux: the direct beam; dflux: diffusive flux
    """ Beer's law for the intensity"""
    var.sflux = var.sflux_top * np.exp(-1.0 * tau / np.cos(self.cfg.sl_angle))
    # converting the intensity to flux for the raditive transfer calculation
    dir_flux = (
        var.sflux * np.cos(self.cfg.sl_angle)
    )  # need to convert to diffuse flux in the RT definition so it can covert back to total intensity with eps

    # scattering
    # the transmission function (length nz)
    if ag0 == 0:  # to save memory
        tran = np.exp(-1.0 / edd * (1.0 - w0) ** 0.5 * delta_tau)  # 2D: nz * nbins
        zeta_p = 0.5 * (1.0 + (1.0 - w0) ** 0.5)
        zeta_m = 0.5 * (1.0 - (1.0 - w0) ** 0.5)
        ll = -1.0 * w0 / (1.0 / mu_ang**2 - 1.0 / edd**2 * (1.0 - w0))
        g_p = 0.5 * (ll * (1.0 / edd + 1.0 / mu_ang))
        g_m = 0.5 * (ll * (1.0 / edd - 1.0 / mu_ang))

    else:
        tran = np.exp(-1.0 / edd * ((1.0 - w0 * ag0) * (1.0 - w0)) ** 0.5 * delta_tau)
        zeta_p = 0.5 * (1.0 + ((1.0 - w0) / (1 - w0 * ag0)) ** 0.5)
        zeta_m = 0.5 * (1.0 - ((1.0 - w0) / (1 - w0 * ag0)) ** 0.5)
        ll = ((1.0 - w0) * (1 - w0 * ag0) - 1.0) / (
            1.0 / mu_ang**2 - 1.0 / edd**2 * (1.0 - w0) * (1 - w0 * ag0)
        )
        g_p = 0.5 * (
            ll * (1.0 / edd + 1 / (mu_ang * (1.0 - w0 * ag0)))
            + w0 * ag0 * mu_ang / (1.0 - w0 * ag0)
        )
        g_m = 0.5 * (
            ll * (1.0 / edd - 1 / (mu_ang * (1.0 - w0 * ag0)))
            - w0 * ag0 * mu_ang / (1.0 - w0 * ag0)
        )

    # to avoit zero denominator
    ll = np.minimum(ll, 1.0e10)
    ll = np.maximum(ll, -1.0e10)

    # 2D: nz * nbins
    chi = zeta_m**2 * tran**2 - zeta_p**2
    xi = zeta_p * zeta_m * (1.0 - tran**2)
    phi = (zeta_m**2 - zeta_p**2) * tran

    # 2D: nz * nbins
    i_u = phi * g_p * dir_flux[:-1] - (xi * g_m + chi * g_p) * dir_flux[1:]
    i_d = phi * g_m * dir_flux[1:] - (chi * g_m + xi * g_p) * dir_flux[:-1]
    # sflux[1:] are all the layers above and sflux[:-1] are all the layers abelow

    var.zeta_m = zeta_m
    var.zeta_p = zeta_p
    var.tran = tran

    # For testing computating speed
    # starting recording time
    # start_time = timeit.default_timer()

    # propagating downward layer by layer and then upward
    # var.dflux_d and var.dflux_p are defined at the interfaces (staggerred)
    # the rest is defined in the center of the layer
    for j in range(
        nz - 1, -1, -1
    ):  # dflux_d goes from the second top interface (nz+1 interfaces)
        var.dflux_d[j] = (
            1.0
            / chi[j]
            * (phi[j] * var.dflux_d[j + 1] - xi[j] * var.dflux_u[j] + i_d[j] / mu_ang)
        )
    for j in range(1, nz + 1):
        var.dflux_u[j] = (
            1.0
            / chi[j - 1]
            * (
                phi[j - 1] * var.dflux_u[j - 1]
                - xi[j - 1] * var.dflux_d[j]
                + i_u[j - 1] / mu_ang
            )
        )

    # the average flux from the direct beam
    # !!! WITHOUT multiplied by the cos zenith angle (flux per unit area perpendicular to the direction of propagationat) !!!
    ave_dir_flux = 0.5 * (var.sflux[:-1] + var.sflux[1:])
    # devided by the Eddington coefficient to recover the total intensity (integrated over all directions)
    tot_flux = (
        ave_dir_flux
        + 0.5
        * (var.dflux_u[:-1] + var.dflux_u[1:] + var.dflux_d[1:] + var.dflux_d[:-1])
        / edd
    )

    # store the previous actinic flux into prev_aflux
    var.prev_aflux = np.copy(var.aflux)
    # converting to the actinic flux and storing the current flux
    var.aflux = tot_flux / (hc / var.bins)
    # the change of the actinic flux
    var.aflux_change = np.nanmax(
        np.abs(var.aflux - var.prev_aflux)[var.aflux > self.cfg.flux_atol]
        / var.aflux[var.aflux > self.cfg.flux_atol]
    )

compute_tau(var, atm)

compute the optical depth

Source code in src/vulcan/op.py
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
def compute_tau(self, var, atm):
    """compute the optical depth"""

    nz = self.cfg.nz

    # reset to zero
    var.tau.fill(0)
    # absorption species
    absp_sp = set.union(var.photo_sp, var.ion_sp)

    for j in range(nz - 1, -1, -1):
        for sp in absp_sp:
            # summing over all T-dependentphoto species
            if sp in self.cfg.T_cross_sp:
                var.tau[j] += (
                    var.y[j, species.index(sp)] * atm.dz[j] * var.cross_T[sp][j]
                )  # 1-D shape of nbins from the j level
            else:  # summing over all T-independent photo species
                var.tau[j] += (
                    var.y[j, species.index(sp)] * atm.dz[j] * var.cross[sp]
                )  # only the j-th laye

        for sp in self.cfg.scat_sp:  # scat_sp are not necessary photo_sp, e.g. He
            var.tau[j] += var.y[j, species.index(sp)] * atm.dz[j] * var.cross_scat[sp]
        # adding the layer above at the end of species loop
        var.tau[j] += var.tau[j + 1]

diffdf(y, atm)

function of eddy diffusion including molecular diffusion, with zero-flux boundary conditions and non-uniform grids (dzi) in the form of Ajy_j + Bj+1y_j+1 + Cj-1*y_j-1

Source code in src/vulcan/op.py
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
def diffdf(self, y, atm):
    """
    function of eddy diffusion including molecular diffusion, with zero-flux boundary conditions and non-uniform grids (dzi)
    in the form of Aj*y_j + Bj+1*y_j+1 + Cj-1*y_j-1
    """

    nz = self.cfg.nz

    y = y.copy()

    # TEST condensation excluding non-gaseous species
    if self.cfg.non_gas_sp:
        ysum = np.sum(y[:, atm.gas_indx], axis=1)
    else:
        ysum = np.sum(y, axis=1)
    # TEST condensation excluding non-gaseous species

    dzi = atm.dzi.copy()
    Kzz = atm.Kzz.copy()
    vz = atm.vz.copy()
    Dzz = atm.Dzz.copy()
    alpha = atm.alpha.copy()
    Tco = atm.Tco
    ms = atm.ms.copy()
    Hp = atm.Hp.copy()
    g = atm.g
    Ti = atm.Ti
    Hpi = atm.Hpi

    # # define T_1/2 for the molecular diffusion
    # Ti = 0.5*(Tco + np.roll(Tco,-1))
    # Ti = Ti[:-1]
    # Hpi = 0.5*(Hp + np.roll(Hp,-1))
    # Hpi = Hpi[:-1]
    # # store Ti and Hpi
    # atm.Ti = Ti
    # atm.Hpi = Hpi

    A, B, C = np.zeros(nz), np.zeros(nz), np.zeros(nz)
    Ai, Bi, Ci = [np.zeros((nz, ni)) for i in range(3)]

    A[0] = -1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[0]
    B[0] = 1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[1]
    C[0] = 0
    A[nz - 1] = (
        -1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / 2.0
        / ysum[nz - 1]
    )
    B[nz - 1] = 0
    C[nz - 1] = (
        1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / 2.0
        / ysum[nz - 2]
    )

    # vertical adection (with closed B.C.)
    A[0] += -((vz[0] > 0) * vz[0]) / dzi[0]
    B[0] += -((vz[0] < 0) * vz[0]) / dzi[0]
    A[-1] += ((vz[-1] < 0) * vz[-1]) / dzi[-1]
    C[-1] += ((vz[-1] > 0) * vz[-1]) / dzi[-1]
    # vertical adection

    # shape of ni-long 1D array
    Ai[0] = -1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[
        0
    ] + 1.0 / (dzi[0]) * Dzz[0] / 2.0 * (
        -1.0 / Hpi[0]
        + ms * g[0] / (Navo * kb * Ti[0])
        + alpha / Ti[0] * (Tco[1] - Tco[0]) / dzi[0]
    )
    Bi[0] = 1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[
        1
    ] + 1.0 / (dzi[0]) * Dzz[0] / 2.0 * (
        -1.0 / Hpi[0]
        + ms * g[0] / (Navo * kb * Ti[0])
        + alpha / Ti[0] * (Tco[1] - Tco[0]) / dzi[0]
    )
    Ci[0] = 0
    Ai[nz - 1] = -1.0 / (dzi[-1]) * (Dzz[nz - 2] / dzi[-1]) * (
        ysum[nz - 1] + ysum[nz - 2]
    ) / 2.0 / ysum[nz - 1] - 1.0 / (dzi[-1]) * Dzz[-1] / 2.0 * (
        -1.0 / Hpi[-1]
        + ms * g[-1] / (Navo * kb * Ti[-1])
        + alpha / Ti[-1] * (Tco[-1] - Tco[-2]) / dzi[-1]
    )
    Bi[nz - 1] = 0
    Ci[nz - 1] = 1.0 / (dzi[-1]) * (Dzz[nz - 2] / dzi[-1]) * (
        ysum[nz - 1] + ysum[nz - 2]
    ) / 2.0 / ysum[nz - 2] - 1.0 / (dzi[-1]) * Dzz[-1] / 2.0 * (
        -1.0 / Hpi[-1]
        + ms * g[-1] / (Navo * kb * Ti[-1])
        + alpha / Ti[-1] * (Tco[-1] - Tco[-2]) / dzi[-1]
    )

    for j in range(1, nz - 1):
        dz_ave = 0.5 * (dzi[j - 1] + dzi[j])
        A[j] = (
            -1.0
            / dz_ave
            * (
                Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Kzz[j - 1] / dzi[j - 1] * (ysum[j] + ysum[j - 1]) / 2.0
            )
            / ysum[j]
        )
        B[j] = 1.0 / dz_ave * Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0 / ysum[j + 1]
        C[j] = (
            1.0
            / dz_ave
            * Kzz[j - 1]
            / dzi[j - 1]
            * (ysum[j] + ysum[j - 1])
            / 2.0
            / ysum[j - 1]
        )

        # vertical adection
        A[j] += -((vz[j] > 0) * vz[j] - (vz[j - 1] < 0) * vz[j - 1]) / dz_ave
        B[j] += -((vz[j] < 0) * vz[j]) / dz_ave
        C[j] += ((vz[j - 1] > 0) * vz[j - 1]) / dz_ave
        # vertical adection

        # Ai in the shape of nz*ni and Ai[j] in the shape of ni
        Ai[j] = (
            -1.0
            / dz_ave
            * (
                Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Dzz[j - 1] / dzi[j - 1] * (ysum[j] + ysum[j - 1]) / 2.0
            )
            / ysum[j]
        )
        Bi[j] = 1.0 / dz_ave * Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0 / ysum[j + 1]
        Ci[j] = (
            1.0
            / dz_ave
            * Dzz[j - 1]
            / dzi[j - 1]
            * (ysum[j] + ysum[j - 1])
            / 2.0
            / ysum[j - 1]
        )

        Ai[j] += (
            1.0
            / (2.0 * dz_ave)
            * (
                Dzz[j]
                * (
                    -1.0 / Hpi[j]
                    + ms * g[j] / (Navo * kb * Ti[j])
                    + alpha / Ti[j] * (Tco[j + 1] - Tco[j]) / dzi[j]
                )
                - Dzz[j - 1]
                * (
                    -1.0 / Hpi[j - 1]
                    + ms * g[j] / (Navo * kb * Ti[j - 1])
                    + alpha / Ti[j - 1] * (Tco[j] - Tco[j - 1]) / dzi[j - 1]
                )
            )
        )  # /ysum[j]
        Bi[j] += (
            1.0
            / (2.0 * dz_ave)
            * Dzz[j]
            * (
                -1.0 / Hpi[j]
                + ms * g[j + 1] / (Navo * kb * Ti[j])
                + alpha / Ti[j] * (Tco[j + 1] - Tco[j]) / dzi[j]
            )
        )
        Ci[j] += (
            -1.0
            / (2.0 * dz_ave)
            * Dzz[j - 1]
            * (
                -1.0 / Hpi[j - 1]
                + ms * g[j - 1] / (Navo * kb * Ti[j - 1])
                + alpha / Ti[j - 1] * (Tco[j] - Tco[j - 1]) / dzi[j - 1]
            )
        )

    tmp0 = (A[0] + Ai[0]) * y[0] + (B[0] + Bi[0]) * y[1]  # shape of ni-long 1D array
    tmp1 = np.ndarray.flatten(
        (
            np.vstack(A[1 : nz - 1]) * y[1 : (nz - 1)]
            + np.vstack(B[1 : nz - 1]) * y[1 + 1 : (nz - 1) + 1]
            + np.vstack(C[1 : nz - 1]) * y[1 - 1 : (nz - 1) - 1]
        )
    )
    tmp1 += np.ndarray.flatten(
        Ai[1 : nz - 1] * y[1 : (nz - 1)]
        + Bi[1 : nz - 1] * y[1 + 1 : (nz - 1) + 1]
        + Ci[1 : nz - 1] * y[1 - 1 : (nz - 1) - 1]
    )  # shape of (nz-2,ni)
    tmp2 = (A[nz - 1] + Ai[nz - 1]) * y[nz - 1] + (C[nz - 1] + Ci[nz - 1]) * y[nz - 2]
    diff = np.append(np.append(tmp0, tmp1), tmp2)
    diff = diff.reshape(nz, ni)

    if self.cfg.use_topflux:
        # Don't forget dz!!! -d phi/ dz
        ### the const flux has no contribution to the jacobian ###
        diff[-1] += atm.top_flux / dzi[-1]
    if self.cfg.use_botflux:
        ### the deposition term needs to be included in the jacobian!!!
        diff[0] += (atm.bot_flux - y[0] * atm.bot_vdep) / dzi[0]

    return diff

diffdf_no_mol(y, atm)

function of eddy diffusion without molecular diffusion, with zero-flux boundary conditions and non-uniform grids (dzi) in the form of Ajy_j + Bj+1y_j+1 + Cj-1*y_j-1

Source code in src/vulcan/op.py
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
def diffdf_no_mol(self, y, atm):
    """
    function of eddy diffusion without molecular diffusion, with zero-flux boundary conditions and non-uniform grids (dzi)
    in the form of Aj*y_j + Bj+1*y_j+1 + Cj-1*y_j-1
    """

    nz = self.cfg.nz

    y = y.copy()
    # TEST excluding non-gaseous species
    if self.cfg.non_gas_sp:
        ysum = np.sum(y[:, atm.gas_indx], axis=1)
    else:
        ysum = np.sum(y, axis=1)
    # TEST excluding non-gaseous species
    dzi = atm.dzi.copy()
    Kzz = atm.Kzz.copy()
    vz = atm.vz.copy()

    A, B, C = np.zeros(nz), np.zeros(nz), np.zeros(nz)

    A[0] = -1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[0]
    B[0] = 1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[1]
    C[0] = 0
    A[nz - 1] = (
        -1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / 2.0
        / ysum[nz - 1]
    )
    B[nz - 1] = 0
    C[nz - 1] = (
        1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / 2.0
        / ysum[nz - 2]
    )

    # vertical adection with zero-flux B.C.
    A[0] += -((vz[0] > 0) * vz[0]) / dzi[0]
    B[0] += -((vz[0] < 0) * vz[0]) / dzi[0]
    A[-1] += ((vz[-1] < 0) * vz[-1]) / dzi[-1]
    C[-1] += ((vz[-1] > 0) * vz[-1]) / dzi[-1]
    # vertical adection

    for j in range(1, nz - 1):
        dz_ave = 0.5 * (dzi[j - 1] + dzi[j])
        A[j] = (
            -2.0
            / (dzi[j - 1] + dzi[j])
            * (
                Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Kzz[j - 1] / dzi[j - 1] * (ysum[j] + ysum[j - 1]) / 2.0
            )
            / ysum[j]
        )
        B[j] = (
            2.0
            / (dzi[j - 1] + dzi[j])
            * Kzz[j]
            / dzi[j]
            * (ysum[j + 1] + ysum[j])
            / 2.0
            / ysum[j + 1]
        )
        C[j] = (
            2.0
            / (dzi[j - 1] + dzi[j])
            * Kzz[j - 1]
            / dzi[j - 1]
            * (ysum[j] + ysum[j - 1])
            / 2.0
            / ysum[j - 1]
        )

        # vertical adection
        A[j] += -((vz[j] > 0) * vz[j] - (vz[j - 1] < 0) * vz[j - 1]) / dz_ave
        B[j] += -((vz[j] < 0) * vz[j]) / dz_ave
        C[j] += ((vz[j - 1] > 0) * vz[j - 1]) / dz_ave
        # vertical adection

    tmp0 = A[0] * y[0] + B[0] * y[1]
    tmp1 = np.ndarray.flatten(
        (
            np.vstack(A[1 : nz - 1]) * y[1 : (nz - 1)]
            + np.vstack(B[1 : nz - 1]) * y[1 + 1 : (nz - 1) + 1]
            + np.vstack(C[1 : nz - 1]) * y[1 - 1 : (nz - 1) - 1]
        )
    )
    tmp2 = A[nz - 1] * y[nz - 1] + C[nz - 1] * y[nz - 2]
    diff = np.append(np.append(tmp0, tmp1), tmp2)
    diff = diff.reshape(nz, ni)

    if self.cfg.use_topflux:
        # Don't forget dz!!! -d phi/ dz
        ### the const flux has no contribution to the jacobian ###
        diff[-1] += atm.top_flux / dzi[-1]
    if self.cfg.use_botflux:
        ### the deposition term needs to be included in the jacobian!!!
        diff[0] += (atm.bot_flux - y[0] * atm.bot_vdep) / dzi[0]
    return diff

diffdf_settling(y, atm)

function of eddy diffusion including molecular diffusion and the settling velocity for particles, with zero-flux boundary conditions and non-uniform grids (dzi) in the form of Ajy_j + Bj+1y_j+1 + Cj-1*y_j-1

Source code in src/vulcan/op.py
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
def diffdf_settling(self, y, atm):
    """
    function of eddy diffusion including molecular diffusion and the settling velocity for particles, with zero-flux boundary conditions and non-uniform grids (dzi)
    in the form of Aj*y_j + Bj+1*y_j+1 + Cj-1*y_j-1
    """

    nz = self.cfg.nz

    y = y.copy()

    # TEST condensation excluding non-gaseous species
    if self.cfg.non_gas_sp:
        ysum = np.sum(y[:, atm.gas_indx], axis=1)
    else:
        ysum = np.sum(y, axis=1)
    # TEST condensation excluding non-gaseous species

    dzi = atm.dzi.copy()
    Kzz = atm.Kzz.copy()
    vz = atm.vz.copy()
    Dzz = atm.Dzz.copy()
    vs = atm.vs.copy()
    alpha = atm.alpha.copy()
    Tco = atm.Tco
    ms = atm.ms.copy()
    Hp = atm.Hp.copy()
    g = atm.g
    Ti = atm.Ti
    Hpi = atm.Hpi
    # # define T_1/2 for the molecular diffusion
    #         Ti = 0.5*(Tco + np.roll(Tco,-1))
    #         Ti = Ti[:-1]
    #         Hpi = 0.5*(Hp + np.roll(Hp,-1))
    #         Hpi = Hpi[:-1]
    #         # store Ti and Hpi
    #         atm.Ti = Ti
    #         atm.Hpi = Hpi

    A, B, C = np.zeros(nz), np.zeros(nz), np.zeros(nz)
    Ai, Bi, Ci = [np.zeros((nz, ni)) for i in range(3)]

    A[0] = -1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[0]
    B[0] = 1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[1]
    C[0] = 0
    A[nz - 1] = (
        -1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / 2.0
        / ysum[nz - 1]
    )
    B[nz - 1] = 0
    C[nz - 1] = (
        1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / 2.0
        / ysum[nz - 2]
    )

    # vertical adection (with closed B.C.)
    A[0] += -((vz[0] > 0) * vz[0]) / dzi[0]
    B[0] += -((vz[0] < 0) * vz[0]) / dzi[0]
    A[-1] += ((vz[-1] < 0) * vz[-1]) / dzi[-1]
    C[-1] += ((vz[-1] > 0) * vz[-1]) / dzi[-1]
    # vertical adection

    # shape of ni-long 1D array
    # Including the settling velocity of the particles
    Ai[0] = (
        -1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[0]
        + 1.0
        / (dzi[0])
        * Dzz[0]
        / 2.0
        * (
            -1.0 / Hpi[0]
            + ms * g[0] / (Navo * kb * Ti[0])
            + alpha / Ti[0] * (Tco[1] - Tco[0]) / dzi[0]
        )
        - ((vs[0] > 0) * vs[0]) / dzi[0]
    )
    Bi[0] = (
        1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[1]
        + 1.0
        / (dzi[0])
        * Dzz[0]
        / 2.0
        * (
            -1.0 / Hpi[0]
            + ms * g[0] / (Navo * kb * Ti[0])
            + alpha / Ti[0] * (Tco[1] - Tco[0]) / dzi[0]
        )
        - ((vs[0] < 0) * vs[0]) / dzi[0]
    )
    # Ci[0] = 0
    Ai[nz - 1] = (
        -1.0
        / (dzi[-1])
        * (Dzz[nz - 2] / dzi[-1])
        * (ysum[nz - 1] + ysum[nz - 2])
        / 2.0
        / ysum[nz - 1]
        - 1.0
        / (dzi[-1])
        * Dzz[-1]
        / 2.0
        * (
            -1.0 / Hpi[-1]
            + ms * g[-1] / (Navo * kb * Ti[-1])
            + alpha / Ti[-1] * (Tco[-1] - Tco[-2]) / dzi[-1]
        )
        + ((vs[-1] < 0) * vs[-1]) / dzi[-1]
    )
    # Bi[nz-1] = 0
    Ci[nz - 1] = (
        1.0
        / (dzi[-1])
        * (Dzz[nz - 2] / dzi[-1])
        * (ysum[nz - 1] + ysum[nz - 2])
        / 2.0
        / ysum[nz - 2]
        - 1.0
        / (dzi[-1])
        * Dzz[-1]
        / 2.0
        * (
            -1.0 / Hpi[-1]
            + ms * g[-1] / (Navo * kb * Ti[-1])
            + alpha / Ti[-1] * (Tco[-1] - Tco[-2]) / dzi[-1]
        )
        + ((vs[-1] > 0) * vs[-1]) / dzi[-1]
    )

    for j in range(1, nz - 1):
        dz_ave = 0.5 * (dzi[j - 1] + dzi[j])
        A[j] = (
            -1.0
            / dz_ave
            * (
                Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Kzz[j - 1] / dzi[j - 1] * (ysum[j] + ysum[j - 1]) / 2.0
            )
            / ysum[j]
        )
        B[j] = 1.0 / dz_ave * Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0 / ysum[j + 1]
        C[j] = (
            1.0
            / dz_ave
            * Kzz[j - 1]
            / dzi[j - 1]
            * (ysum[j] + ysum[j - 1])
            / 2.0
            / ysum[j - 1]
        )

        # vertical adection
        A[j] += -((vz[j] > 0) * vz[j] - (vz[j - 1] < 0) * vz[j - 1]) / dz_ave
        B[j] += -((vz[j] < 0) * vz[j]) / dz_ave
        C[j] += ((vz[j - 1] > 0) * vz[j - 1]) / dz_ave
        # vertical adection

        # Ai in the shape of nz*ni and Ai[j] in the shape of ni
        # Including the settling velocity of the particles
        Ai[j] = (
            -1.0
            / dz_ave
            * (
                Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Dzz[j - 1] / dzi[j - 1] * (ysum[j] + ysum[j - 1]) / 2.0
            )
            / ysum[j]
            - ((vs[j] > 0) * vs[j] - (vs[j - 1] < 0) * vs[j - 1]) / dz_ave
        )
        Bi[j] = (
            1.0 / dz_ave * Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0 / ysum[j + 1]
            - ((vs[j] < 0) * vs[j]) / dz_ave
        )
        Ci[j] = (
            1.0
            / dz_ave
            * Dzz[j - 1]
            / dzi[j - 1]
            * (ysum[j] + ysum[j - 1])
            / 2.0
            / ysum[j - 1]
            + ((vs[j - 1] > 0) * vs[j - 1]) / dz_ave
        )

        Ai[j] += (
            1.0
            / (2.0 * dz_ave)
            * (
                Dzz[j]
                * (
                    -1.0 / Hpi[j]
                    + ms * g[j] / (Navo * kb * Ti[j])
                    + alpha / Ti[j] * (Tco[j + 1] - Tco[j]) / dzi[j]
                )
                - Dzz[j - 1]
                * (
                    -1.0 / Hpi[j - 1]
                    + ms * g[j] / (Navo * kb * Ti[j - 1])
                    + alpha / Ti[j - 1] * (Tco[j] - Tco[j - 1]) / dzi[j - 1]
                )
            )
        )  # /ysum[j]
        Bi[j] += (
            1.0
            / (2.0 * dz_ave)
            * Dzz[j]
            * (
                -1.0 / Hpi[j]
                + ms * g[j + 1] / (Navo * kb * Ti[j])
                + alpha / Ti[j] * (Tco[j + 1] - Tco[j]) / dzi[j]
            )
        )
        Ci[j] += (
            -1.0
            / (2.0 * dz_ave)
            * Dzz[j - 1]
            * (
                -1.0 / Hpi[j - 1]
                + ms * g[j - 1] / (Navo * kb * Ti[j - 1])
                + alpha / Ti[j - 1] * (Tco[j] - Tco[j - 1]) / dzi[j - 1]
            )
        )

    tmp0 = (A[0] + Ai[0]) * y[0] + (B[0] + Bi[0]) * y[1]  # shape of ni-long 1D array
    tmp1 = np.ndarray.flatten(
        (
            np.vstack(A[1 : nz - 1]) * y[1 : (nz - 1)]
            + np.vstack(B[1 : nz - 1]) * y[1 + 1 : (nz - 1) + 1]
            + np.vstack(C[1 : nz - 1]) * y[1 - 1 : (nz - 1) - 1]
        )
    )
    tmp1 += np.ndarray.flatten(
        Ai[1 : nz - 1] * y[1 : (nz - 1)]
        + Bi[1 : nz - 1] * y[1 + 1 : (nz - 1) + 1]
        + Ci[1 : nz - 1] * y[1 - 1 : (nz - 1) - 1]
    )  # shape of (nz-2,ni)
    tmp2 = (A[nz - 1] + Ai[nz - 1]) * y[nz - 1] + (C[nz - 1] + Ci[nz - 1]) * y[nz - 2]
    diff = np.append(np.append(tmp0, tmp1), tmp2)
    diff = diff.reshape(nz, ni)

    if self.cfg.use_topflux:
        # Don't forget dz!!! -d phi/ dz
        ### the const flux has no contribution to the jacobian ###
        diff[-1] += atm.top_flux / dzi[-1]
    if self.cfg.use_botflux:
        ### the deposition term needs to be included in the jacobian!!!
        diff[0] += (atm.bot_flux - y[0] * atm.bot_vdep) / dzi[0]

    return diff

diffdf_settling_vm(y, atm)

added vm for molecular diffusion function of eddy diffusion including molecular diffusion and the settling velocity for particles, with zero-flux boundary conditions and non-uniform grids (dzi) in the form of Ajy_j + Bj+1y_j+1 + Cj-1*y_j-1

Source code in src/vulcan/op.py
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
def diffdf_settling_vm(self, y, atm):
    """
    added vm for molecular diffusion
    function of eddy diffusion including molecular diffusion and the settling velocity for particles, with zero-flux boundary conditions and non-uniform grids (dzi)
    in the form of Aj*y_j + Bj+1*y_j+1 + Cj-1*y_j-1
    """

    nz = self.cfg.nz
    y = y.copy()

    if self.cfg.non_gas_sp:
        ysum = np.sum(y[:, atm.gas_indx], axis=1)
    else:
        ysum = np.sum(y, axis=1)

    dzi = atm.dzi.copy()
    Kzz = atm.Kzz.copy()
    vz = atm.vz.copy()
    Dzz = atm.Dzz.copy()
    vs = atm.vs.copy()
    alpha = atm.alpha.copy()
    Tco = atm.Tco.copy()
    ms = atm.ms.copy()
    Hp = atm.Hp.copy()
    g = atm.g
    Ti = atm.Ti
    Hpi = atm.Hpi

    vm = atm.vm
    # shape: nz x ni
    # vm defined in build.py
    # vm = - Dzz_cen * ( ms[np.newaxis,:]*g[:,np.newaxis]/(Navo*kb*Tco[:,np.newaxis]) - 1./Hp[:,np.newaxis] +  alpha/Tco[:,np.newaxis]*(delta_T[:,np.newaxis])/dz[:,np.newaxis]  )

    A, B, C = np.zeros(nz), np.zeros(nz), np.zeros(nz)
    Ai, Bi, Ci = [np.zeros((nz, ni)) for i in range(3)]

    A[0] = -1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[0]
    B[0] = 1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[1]
    C[0] = 0
    A[nz - 1] = (
        -1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / 2.0
        / ysum[nz - 1]
    )
    B[nz - 1] = 0
    C[nz - 1] = (
        1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / 2.0
        / ysum[nz - 2]
    )

    # vertical adection (with closed B.C.)
    A[0] += -((vz[0] > 0) * vz[0]) / dzi[0]
    B[0] += -((vz[0] < 0) * vz[0]) / dzi[0]
    A[-1] += ((vz[-1] < 0) * vz[-1]) / dzi[-1]
    C[-1] += ((vz[-1] > 0) * vz[-1]) / dzi[-1]
    # vertical adection

    # shape of ni-long 1D array
    # Including the settling velocity of the particles and the advective component of molecular diffusion
    Ai[0] = (
        -1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[0]
        - ((vs[0] > 0) * vs[0]) / dzi[0]
    )
    Bi[0] = (
        1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / 2.0 / ysum[1]
        - ((vs[0] < 0) * vs[0]) / dzi[0]
    )
    # Ci[0] = 0
    Ai[nz - 1] = (
        -1.0
        / (dzi[-1])
        * (Dzz[nz - 2] / dzi[-1])
        * (ysum[nz - 1] + ysum[nz - 2])
        / 2.0
        / ysum[nz - 1]
        + ((vm[-1] < 0) * vm[-1]) / dzi[-1]
        + ((vs[-1] < 0) * vs[-1]) / dzi[-1]
    )
    # Bi[nz-1] = 0
    Ci[nz - 1] = (
        1.0
        / (dzi[-1])
        * (Dzz[nz - 2] / dzi[-1])
        * (ysum[nz - 1] + ysum[nz - 2])
        / 2.0
        / ysum[nz - 2]
        + ((vm[-1] > 0) * vm[-1]) / dzi[-1]
        + ((vs[-1] > 0) * vs[-1]) / dzi[-1]
    )

    for j in range(1, nz - 1):
        dz_ave = 0.5 * (dzi[j - 1] + dzi[j])
        A[j] = (
            -1.0
            / dz_ave
            * (
                Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Kzz[j - 1] / dzi[j - 1] * (ysum[j] + ysum[j - 1]) / 2.0
            )
            / ysum[j]
        )
        B[j] = 1.0 / dz_ave * Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0 / ysum[j + 1]
        C[j] = (
            1.0
            / dz_ave
            * Kzz[j - 1]
            / dzi[j - 1]
            * (ysum[j] + ysum[j - 1])
            / 2.0
            / ysum[j - 1]
        )

        # vertical adection
        A[j] += -((vz[j] > 0) * vz[j] - (vz[j - 1] < 0) * vz[j - 1]) / dz_ave
        B[j] += -((vz[j] < 0) * vz[j]) / dz_ave
        C[j] += ((vz[j - 1] > 0) * vz[j - 1]) / dz_ave
        # vertical adection

        # Ai in the shape of nz*ni and Ai[j] in the shape of ni
        # Including the settling velocity of the particles

        # diffusion component
        Ai[j] = (
            -1.0
            / dz_ave
            * (
                Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Dzz[j - 1] / dzi[j - 1] * (ysum[j] + ysum[j - 1]) / 2.0
            )
            / ysum[j]
        )
        Bi[j] = 1.0 / dz_ave * Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0 / ysum[j + 1]
        Ci[j] = (
            1.0
            / dz_ave
            * Dzz[j - 1]
            / dzi[j - 1]
            * (ysum[j] + ysum[j - 1])
            / 2.0
            / ysum[j - 1]
        )
        # diffusion component

        # advective component using upwind (inc. from Dzz and from vs)
        Ai[j] += (
            -((vm[j] > 0) * vm[j] - (vm[j - 1] < 0) * vm[j - 1]) / dz_ave
            - ((vs[j] > 0) * vs[j] - (vs[j - 1] < 0) * vs[j - 1]) / dz_ave
        )
        Bi[j] += -((vm[j] < 0) * vm[j]) / dz_ave - ((vs[j] < 0) * vs[j]) / dz_ave
        Ci[j] += (
            +((vm[j - 1] > 0) * vm[j - 1]) / dz_ave + ((vs[j - 1] > 0) * vs[j - 1]) / dz_ave
        )
        # advective component using upwind

    tmp0 = (A[0] + Ai[0]) * y[0] + (B[0] + Bi[0]) * y[1]  # shape of ni-long 1D array
    tmp1 = np.ndarray.flatten(
        (
            np.vstack(A[1 : nz - 1]) * y[1 : (nz - 1)]
            + np.vstack(B[1 : nz - 1]) * y[1 + 1 : (nz - 1) + 1]
            + np.vstack(C[1 : nz - 1]) * y[1 - 1 : (nz - 1) - 1]
        )
    )
    tmp1 += np.ndarray.flatten(
        Ai[1 : nz - 1] * y[1 : (nz - 1)]
        + Bi[1 : nz - 1] * y[1 + 1 : (nz - 1) + 1]
        + Ci[1 : nz - 1] * y[1 - 1 : (nz - 1) - 1]
    )  # shape of (nz-2,ni)
    tmp2 = (A[nz - 1] + Ai[nz - 1]) * y[nz - 1] + (C[nz - 1] + Ci[nz - 1]) * y[nz - 2]
    diff = np.append(np.append(tmp0, tmp1), tmp2)
    diff = diff.reshape(nz, ni)

    if self.cfg.use_topflux:
        # Don't forget dz!!! -d phi/ dz
        ### the const flux has no contribution to the jacobian ###
        diff[-1] += atm.top_flux / dzi[-1]
    if self.cfg.use_botflux:
        ### the deposition term needs to be included in the jacobian!!!
        diff[0] += (atm.bot_flux - y[0] * atm.bot_vdep) / dzi[0]

    return diff

jac_tot(var, atm)

jacobian matrix for dn/dt + dphi/dz = P - L (including molecular diffusion) zero-flux BC: 1st derivitive of y is zero

Source code in src/vulcan/op.py
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
def jac_tot(self, var, atm):
    """
    jacobian matrix for dn/dt + dphi/dz = P - L (including molecular diffusion)
    zero-flux BC:  1st derivitive of y is zero
    """

    nz = self.cfg.nz
    y = var.y.copy()

    # TEST condensation excluding non-gaseous species
    if self.cfg.non_gas_sp:
        ysum = np.sum(y[:, atm.gas_indx], axis=1)
    else:
        ysum = np.sum(y, axis=1)
    # TEST condensation excluding non-gaseous species
    dzi = atm.dzi.copy()
    Kzz = atm.Kzz.copy()
    Dzz = atm.Dzz.copy()
    vz = atm.vz.copy()
    alpha = atm.alpha.copy()
    Tco = atm.Tco
    mu, ms = atm.mu.copy(), atm.ms.copy()
    g = atm.g

    # define T_1/2 for the molecular diffusion
    # Ti = 0.5*(Tco + np.roll(Tco,-1))
    # Ti = Ti[:-1]

    Ti = atm.Ti.copy()
    Hpi = atm.Hpi.copy()

    dfdy = achemjac(y, atm.M, var.k)
    j_indx = []

    for j in range(nz):
        j_indx.append(np.arange(j * ni, j * ni + ni))

    for j in range(1, nz - 1):
        # excluding the buttom and the top cell
        # at j level consists of ni species
        dz_ave = 0.5 * (dzi[j - 1] + dzi[j])
        dfdy[j_indx[j], j_indx[j]] += (
            -1.0
            / dz_ave
            * (
                Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
            )
            / ysum[j]
            - ((vz[j] > 0) * vz[j] - (vz[j - 1] < 0) * vz[j - 1]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j + 1]] += (
            1.0 / dz_ave * (Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1]))
            - ((vz[j] < 0) * vz[j]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j - 1]] += (
            1.0
            / dz_ave
            * (Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1]))
            + ((vz[j - 1] > 0) * vz[j - 1]) / dz_ave
        )

        # [j_indx[j], j_indx[j]] has size ni*ni
        dfdy[j_indx[j], j_indx[j]] += -1.0 / dz_ave * (
            Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
            + Dzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
        ) / ysum[j] + 1.0 / (2.0 * dz_ave) * (
            Dzz[j]
            * (
                -1.0 / Hpi[j]
                + ms * g[j] / (Navo * kb * Ti[j])
                + alpha / Ti[j] * (Tco[j + 1] - Tco[j]) / dzi[j]
            )
            - Dzz[j - 1]
            * (
                -1.0 / Hpi[j - 1]
                + ms * g[j] / (Navo * kb * Ti[j - 1])
                + alpha / Ti[j - 1] * (Tco[j] - Tco[j - 1]) / dzi[j - 1]
            )
        )
        dfdy[j_indx[j], j_indx[j + 1]] += 1.0 / dz_ave * (
            Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1])
        ) + 1.0 / (2.0 * dz_ave) * Dzz[j] * (
            -1.0 / Hpi[j]
            + ms * g[j + 1] / (Navo * kb * Ti[j])
            + alpha / Ti[j] * (Tco[j + 1] - Tco[j]) / dzi[j]
        )
        dfdy[j_indx[j], j_indx[j - 1]] += 1.0 / dz_ave * (
            Dzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1])
        ) - 1.0 / (2.0 * dz_ave) * Dzz[j - 1] * (
            -1.0 / Hpi[j - 1]
            + ms * g[j - 1] / (Navo * kb * Ti[j - 1])
            + alpha / Ti[j - 1] * (Tco[j] - Tco[j - 1]) / dzi[j - 1]
        )

    dfdy[j_indx[0], j_indx[0]] += (
        -1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[0])
        - ((vz[0] > 0) * vz[0]) / dzi[0]
    )
    dfdy[j_indx[0], j_indx[0]] += -1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (
        ysum[1] + ysum[0]
    ) / (2.0 * ysum[0]) + 1.0 / (dzi[0]) * Dzz[0] / 2.0 * (
        -1.0 / Hpi[0]
        + ms * g[0] / (Navo * kb * Ti[0])
        + alpha / Ti[0] * (Tco[1] - Tco[0]) / dzi[0]
    )
    # deposition velocity
    if self.cfg.use_botflux:
        dfdy[j_indx[0], j_indx[0]] += -1.0 * atm.bot_vdep / dzi[0]

    dfdy[j_indx[0], j_indx[1]] += (
        1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[1])
        - ((vz[0] < 0) * vz[0]) / dzi[0]
    )
    dfdy[j_indx[0], j_indx[1]] += 1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (
        ysum[1] + ysum[0]
    ) / (2.0 * ysum[1]) + 1.0 / (dzi[0]) * Dzz[0] / 2.0 * (
        -1.0 / Hpi[0]
        + ms * g[0] / (Navo * kb * Ti[0])
        + alpha / Ti[0] * (Tco[1] - Tco[0]) / dzi[0]
    )

    dfdy[j_indx[nz - 1], j_indx[nz - 1]] += (
        -1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[nz - 1])
        + ((vz[-1] < 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[nz - 1]] += -1.0 / (dzi[nz - 2]) * (
        Dzz[nz - 2] / dzi[nz - 2]
    ) * (ysum[nz - 1] + ysum[nz - 2]) / (2.0 * ysum[nz - 1]) - 1.0 / (dzi[-1]) * Dzz[
        -1
    ] / 2.0 * (
        -1.0 / Hpi[-1]
        + ms * g[-1] / (Navo * kb * Ti[-1])
        + alpha / Ti[-1] * (Tco[-1] - Tco[-2]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] += (
        1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[(nz - 1) - 1])
        + ((vz[-1] > 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] += 1.0 / (dzi[nz - 2]) * (
        Dzz[nz - 2] / dzi[nz - 2]
    ) * (ysum[nz - 1] + ysum[nz - 2]) / (2.0 * ysum[(nz - 1) - 1]) - 1.0 / (dzi[-1]) * Dzz[
        -1
    ] / 2.0 * (
        -1.0 / Hpi[-1]
        + ms * g[-1] / (Navo * kb * Ti[-1])
        + alpha / Ti[-1] * (Tco[-1] - Tco[-2]) / dzi[-1]
    )

    return dfdy

lhs_jac_fix_all_bot(var, atm)

directly constructing lhs = 1./(rh)sparse.identity(ni*nz) - dfdy jacobian matrix for dn/dt + dphi/dz = P - L (including molecular diffusion) Fixed all species BC: all species at bottom (y[0]) remains fixed

Source code in src/vulcan/op.py
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
def lhs_jac_fix_all_bot(self, var, atm):
    """
    directly constructing lhs = 1./(r*h)*sparse.identity(ni*nz) - dfdy
    jacobian matrix for dn/dt + dphi/dz = P - L (including molecular diffusion)
    Fixed all species BC: all species at bottom (y[0]) remains fixed
    """

    nz = self.cfg.nz

    y = var.y.copy()
    # TEST condensation excluding non-gaseous species
    if self.cfg.non_gas_sp:
        ysum = np.sum(y[:, atm.gas_indx], axis=1)
    else:
        ysum = np.sum(y, axis=1)
    # TEST condensation excluding non-gaseous species
    dzi = atm.dzi.copy()
    Kzz = atm.Kzz.copy()
    Dzz = atm.Dzz.copy()
    vz = atm.vz.copy()
    alpha = atm.alpha.copy()
    Tco = atm.Tco
    mu, ms = atm.mu.copy(), atm.ms.copy()
    g = atm.g

    Ti = atm.Ti.copy()
    Hpi = atm.Hpi.copy()

    r = 1.0 + 1.0 / 2.0**0.5
    c0 = 1.0 / (r * var.dt)
    dfdy = neg_achemjac(y, atm.M, var.k, self.cfg.nz)
    np.fill_diagonal(dfdy, c0 + np.diag(dfdy))
    j_indx = []

    for j in range(nz):
        j_indx.append(np.arange(j * ni, j * ni + ni))

    for j in range(1, nz - 1):
        # excluding the buttom and the top cell
        # at j level consists of ni species
        dz_ave = 0.5 * (dzi[j - 1] + dzi[j])
        dfdy[j_indx[j], j_indx[j]] -= (
            -1.0
            / dz_ave
            * (
                Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
            )
            / ysum[j]
            - ((vz[j] > 0) * vz[j] - (vz[j - 1] < 0) * vz[j - 1]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j + 1]] -= (
            1.0 / dz_ave * (Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1]))
            - ((vz[j] < 0) * vz[j]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j - 1]] -= (
            1.0
            / dz_ave
            * (Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1]))
            + ((vz[j - 1] > 0) * vz[j - 1]) / dz_ave
        )

        # [j_indx[j], j_indx[j]] has size ni*ni
        dfdy[j_indx[j], j_indx[j]] -= -1.0 / dz_ave * (
            Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
            + Dzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
        ) / ysum[j] + 1.0 / (2.0 * dz_ave) * (
            Dzz[j]
            * (
                -1.0 / Hpi[j]
                + ms * g[j] / (Navo * kb * Ti[j])
                + alpha / Ti[j] * (Tco[j + 1] - Tco[j]) / dzi[j]
            )
            - Dzz[j - 1]
            * (
                -1.0 / Hpi[j - 1]
                + ms * g[j] / (Navo * kb * Ti[j - 1])
                + alpha / Ti[j - 1] * (Tco[j] - Tco[j - 1]) / dzi[j - 1]
            )
        )
        dfdy[j_indx[j], j_indx[j + 1]] -= 1.0 / dz_ave * (
            Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1])
        ) + 1.0 / (2.0 * dz_ave) * Dzz[j] * (
            -1.0 / Hpi[j]
            + ms * g[j + 1] / (Navo * kb * Ti[j])
            + alpha / Ti[j] * (Tco[j + 1] - Tco[j]) / dzi[j]
        )
        dfdy[j_indx[j], j_indx[j - 1]] -= 1.0 / dz_ave * (
            Dzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1])
        ) - 1.0 / (2.0 * dz_ave) * Dzz[j - 1] * (
            -1.0 / Hpi[j - 1]
            + ms * g[j - 1] / (Navo * kb * Ti[j - 1])
            + alpha / Ti[j - 1] * (Tco[j] - Tco[j - 1]) / dzi[j - 1]
        )

    # deposition velocity (off with fixed all BC)
    # if self.cfg.use_botflux : dfdy[j_indx[0], j_indx[0]] -= -1.*atm.bot_vdep /dzi[0]

    # diffusion-limited escape
    if self.cfg.diff_esc:  # not empty list
        diff_lim = np.zeros(ni)
        for sp in self.cfg.diff_esc:
            if y[-1, species.index(sp)] > 0:
                diff_lim[species.index(sp)] += (
                    atm.top_flux[species.index(sp)] / y[-1, species.index(sp)]
                )
        dfdy[j_indx[-1], j_indx[-1]] -= diff_lim  # negative

    # Fix bottom BC
    dfdy[:, j_indx[0]] = 0.0

    dfdy[j_indx[0], j_indx[1]] -= (
        1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[1])
        - ((vz[0] < 0) * vz[0]) / dzi[0]
    )
    dfdy[j_indx[0], j_indx[1]] -= 1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (
        ysum[1] + ysum[0]
    ) / (2.0 * ysum[1]) + 1.0 / (dzi[0]) * Dzz[0] / 2.0 * (
        -1.0 / Hpi[0]
        + ms * g[0] / (Navo * kb * Ti[0])
        + alpha / Ti[0] * (Tco[1] - Tco[0]) / dzi[0]
    )

    dfdy[j_indx[nz - 1], j_indx[nz - 1]] -= (
        -1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[nz - 1])
        + ((vz[-1] < 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[nz - 1]] -= -1.0 / (dzi[nz - 2]) * (
        Dzz[nz - 2] / dzi[nz - 2]
    ) * (ysum[nz - 1] + ysum[nz - 2]) / (2.0 * ysum[nz - 1]) - 1.0 / (dzi[-1]) * Dzz[
        -1
    ] / 2.0 * (
        -1.0 / Hpi[-1]
        + ms * g[-1] / (Navo * kb * Ti[-1])
        + alpha / Ti[-1] * (Tco[-1] - Tco[-2]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] -= (
        1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[(nz - 1) - 1])
        + ((vz[-1] > 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] -= 1.0 / (dzi[nz - 2]) * (
        Dzz[nz - 2] / dzi[nz - 2]
    ) * (ysum[nz - 1] + ysum[nz - 2]) / (2.0 * ysum[(nz - 1) - 1]) - 1.0 / (dzi[-1]) * Dzz[
        -1
    ] / 2.0 * (
        -1.0 / Hpi[-1]
        + ms * g[-1] / (Navo * kb * Ti[-1])
        + alpha / Ti[-1] * (Tco[-1] - Tco[-2]) / dzi[-1]
    )

    return dfdy

lhs_jac_no_mol(var, atm)

directly constructing lhs = 1./(rh)sparse.identity(ni*nz) - dfdy jacobian matrix for dn/dt + dphi/dz = P - L (WITHOUT molecular diffusion) zero-flux BC: 1st derivitive of y is zero

Source code in src/vulcan/op.py
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
def lhs_jac_no_mol(self, var, atm):
    """
    directly constructing lhs = 1./(r*h)*sparse.identity(ni*nz) - dfdy
    jacobian matrix for dn/dt + dphi/dz = P - L (WITHOUT molecular diffusion)
    zero-flux BC:  1st derivitive of y is zero
    """

    nz = self.cfg.nz

    y = var.y.copy()
    # TEST condensation excluding non-gaseous species
    if self.cfg.non_gas_sp:
        ysum = np.sum(y[:, atm.gas_indx], axis=1)
    else:
        ysum = np.sum(y, axis=1)
    # TEST condensation excluding non-gaseous species
    dzi = atm.dzi.copy()
    Kzz = atm.Kzz.copy()
    vz = atm.vz.copy()
    Tco = atm.Tco
    mu, ms = atm.mu.copy(), atm.ms.copy()

    r = 1.0 + 1.0 / 2.0**0.5
    c0 = 1.0 / (r * var.dt)
    dfdy = neg_achemjac(y, atm.M, var.k, self.cfg.nz)
    np.fill_diagonal(dfdy, c0 + np.diag(dfdy))
    j_indx = []

    for j in range(nz):
        j_indx.append(np.arange(j * ni, j * ni + ni))

    for j in range(1, nz - 1):
        # excluding the buttom and the top cell
        # at j level consists of ni species
        dz_ave = 0.5 * (dzi[j - 1] + dzi[j])
        dfdy[j_indx[j], j_indx[j]] -= (
            -1.0
            / dz_ave
            * (
                Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
            )
            / ysum[j]
            - ((vz[j] > 0) * vz[j] - (vz[j - 1] < 0) * vz[j - 1]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j + 1]] -= (
            1.0 / dz_ave * (Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1]))
            - ((vz[j] < 0) * vz[j]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j - 1]] -= (
            1.0
            / dz_ave
            * (Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1]))
            + ((vz[j - 1] > 0) * vz[j - 1]) / dz_ave
        )

    dfdy[j_indx[0], j_indx[0]] -= (
        -1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[0])
        - ((vz[0] > 0) * vz[0]) / dzi[0]
    )
    # deposition velocity
    if self.cfg.use_botflux:
        dfdy[j_indx[0], j_indx[0]] -= -1.0 * atm.bot_vdep / dzi[0]

    dfdy[j_indx[0], j_indx[1]] -= (
        1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[1])
        - ((vz[0] < 0) * vz[0]) / dzi[0]
    )

    dfdy[j_indx[nz - 1], j_indx[nz - 1]] -= (
        -1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[nz - 1])
        + ((vz[-1] < 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] -= (
        1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[(nz - 1) - 1])
        + ((vz[-1] > 0) * vz[-1]) / dzi[-1]
    )

    return dfdy

lhs_jac_no_mol_fix_all_bot(var, atm)

directly constructing lhs = 1./(rh)sparse.identity(ni*nz) - dfdy jacobian matrix for dn/dt + dphi/dz = P - L (WITHOUT molecular diffusion) Fixed all species BC: all species at bottom (y[0]) remains fixed

Source code in src/vulcan/op.py
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
def lhs_jac_no_mol_fix_all_bot(self, var, atm):
    """
    directly constructing lhs = 1./(r*h)*sparse.identity(ni*nz) - dfdy
    jacobian matrix for dn/dt + dphi/dz = P - L (WITHOUT molecular diffusion)
    Fixed all species BC: all species at bottom (y[0]) remains fixed
    """

    nz = self.cfg.nz

    y = var.y.copy()
    # TEST condensation excluding non-gaseous species
    if self.cfg.non_gas_sp:
        ysum = np.sum(y[:, atm.gas_indx], axis=1)
    else:
        ysum = np.sum(y, axis=1)
    # TEST condensation excluding non-gaseous species
    dzi = atm.dzi.copy()
    Kzz = atm.Kzz.copy()
    vz = atm.vz.copy()
    Tco = atm.Tco
    mu, ms = atm.mu.copy(), atm.ms.copy()

    r = 1.0 + 1.0 / 2.0**0.5
    c0 = 1.0 / (r * var.dt)
    dfdy = neg_achemjac(y, atm.M, var.k, self.cfg.nz)
    np.fill_diagonal(dfdy, c0 + np.diag(dfdy))
    j_indx = []

    for j in range(nz):
        j_indx.append(np.arange(j * ni, j * ni + ni))

    for j in range(1, nz - 1):
        # excluding the buttom and the top cell
        # at j level consists of ni species
        dz_ave = 0.5 * (dzi[j - 1] + dzi[j])
        dfdy[j_indx[j], j_indx[j]] -= (
            -1.0
            / dz_ave
            * (
                Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
            )
            / ysum[j]
            - ((vz[j] > 0) * vz[j] - (vz[j - 1] < 0) * vz[j - 1]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j + 1]] -= (
            1.0 / dz_ave * (Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1]))
            - ((vz[j] < 0) * vz[j]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j - 1]] -= (
            1.0
            / dz_ave
            * (Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1]))
            + ((vz[j - 1] > 0) * vz[j - 1]) / dz_ave
        )

    # dfdy[j_indx[0], j_indx[0]] -= -1./(dzi[0])*(Kzz[0]/dzi[0]) * (ysum[1]+ysum[0])/(2.*ysum[0]) -( (vz[0]>0)*vz[0] )/dzi[0]
    # deposition velocity (off with fixed all BC)
    # if self.cfg.use_botflux : dfdy[j_indx[0], j_indx[0]] -= -1.*atm.bot_vdep /dzi[0]

    # Fix bottom BC
    dfdy[:, j_indx[0]] = 0.0

    dfdy[j_indx[0], j_indx[1]] -= (
        1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[1])
        - ((vz[0] < 0) * vz[0]) / dzi[0]
    )

    dfdy[j_indx[nz - 1], j_indx[nz - 1]] -= (
        -1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[nz - 1])
        + ((vz[-1] < 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] -= (
        1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[(nz - 1) - 1])
        + ((vz[-1] > 0) * vz[-1]) / dzi[-1]
    )

    return dfdy

lhs_jac_settling(var, atm)

directly constructing lhs = 1./(rh)sparse.identity(ni*nz) - dfdy jacobian matrix for dn/dt + dphi/dz = P - L (including molecular diffusion and gravitation settling for particles) zero-flux BC: 1st derivitive of y is zero

Source code in src/vulcan/op.py
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
def lhs_jac_settling(self, var, atm):
    """
    directly constructing lhs = 1./(r*h)*sparse.identity(ni*nz) - dfdy
    jacobian matrix for dn/dt + dphi/dz = P - L (including molecular diffusion and gravitation settling for particles)
    zero-flux BC:  1st derivitive of y is zero
    """

    nz = self.cfg.nz

    y = var.y.copy()
    # TEST condensation excluding non-gaseous species
    if self.cfg.non_gas_sp:
        ysum = np.sum(y[:, atm.gas_indx], axis=1)
    else:
        ysum = np.sum(y, axis=1)
    # TEST condensation excluding non-gaseous species
    dzi = atm.dzi.copy()
    Kzz = atm.Kzz.copy()
    Dzz = atm.Dzz.copy()
    vz = atm.vz.copy()
    vs = atm.vs.copy()
    alpha = atm.alpha.copy()
    Tco = atm.Tco
    mu, ms = atm.mu.copy(), atm.ms.copy()
    g = atm.g

    Ti = atm.Ti.copy()
    Hpi = atm.Hpi.copy()

    # c0 = 1./(r*h) where r = 1. + 1./2.**0.5
    r = 1.0 + 1.0 / 2.0**0.5
    c0 = 1.0 / (r * var.dt)
    dfdy = neg_achemjac(y, atm.M, var.k, self.cfg.nz)
    np.fill_diagonal(dfdy, c0 + np.diag(dfdy))
    j_indx = []

    for j in range(nz):
        j_indx.append(np.arange(j * ni, j * ni + ni))

    for j in range(1, nz - 1):
        # excluding the buttom and the top cell
        # at j level consists of ni species
        dz_ave = 0.5 * (dzi[j - 1] + dzi[j])
        dfdy[j_indx[j], j_indx[j]] -= (
            -1.0
            / dz_ave
            * (
                Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
            )
            / ysum[j]
            - ((vz[j] > 0) * vz[j] - (vz[j - 1] < 0) * vz[j - 1]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j + 1]] -= (
            1.0 / dz_ave * (Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1]))
            - ((vz[j] < 0) * vz[j]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j - 1]] -= (
            1.0
            / dz_ave
            * (Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1]))
            + ((vz[j - 1] > 0) * vz[j - 1]) / dz_ave
        )

        # [j_indx[j], j_indx[j]] has size ni*ni
        dfdy[j_indx[j], j_indx[j]] -= (
            -1.0
            / dz_ave
            * (
                Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Dzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
            )
            / ysum[j]
            + 1.0
            / (2.0 * dz_ave)
            * (
                Dzz[j]
                * (
                    -1.0 / Hpi[j]
                    + ms * g[j] / (Navo * kb * Ti[j])
                    + alpha / Ti[j] * (Tco[j + 1] - Tco[j]) / dzi[j]
                )
                - Dzz[j - 1]
                * (
                    -1.0 / Hpi[j - 1]
                    + ms * g[j] / (Navo * kb * Ti[j - 1])
                    + alpha / Ti[j - 1] * (Tco[j] - Tco[j - 1]) / dzi[j - 1]
                )
            )
            - ((vs[j] > 0) * vs[j] - (vs[j - 1] < 0) * vs[j - 1]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j + 1]] -= (
            1.0 / dz_ave * (Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1]))
            + 1.0
            / (2.0 * dz_ave)
            * Dzz[j]
            * (
                -1.0 / Hpi[j]
                + ms * g[j + 1] / (Navo * kb * Ti[j])
                + alpha / Ti[j] * (Tco[j + 1] - Tco[j]) / dzi[j]
            )
            - ((vs[j] < 0) * vs[j]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j - 1]] -= (
            1.0
            / dz_ave
            * (Dzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1]))
            - 1.0
            / (2.0 * dz_ave)
            * Dzz[j - 1]
            * (
                -1.0 / Hpi[j - 1]
                + ms * g[j - 1] / (Navo * kb * Ti[j - 1])
                + alpha / Ti[j - 1] * (Tco[j] - Tco[j - 1]) / dzi[j - 1]
            )
            + ((vs[j - 1] > 0) * vs[j - 1]) / dz_ave
        )

    dfdy[j_indx[0], j_indx[0]] -= (
        -1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[0])
        - ((vz[0] > 0) * vz[0]) / dzi[0]
    )
    dfdy[j_indx[0], j_indx[0]] -= (
        -1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[0])
        + 1.0
        / (dzi[0])
        * Dzz[0]
        / 2.0
        * (
            -1.0 / Hpi[0]
            + ms * g[0] / (Navo * kb * Ti[0])
            + alpha / Ti[0] * (Tco[1] - Tco[0]) / dzi[0]
        )
        - ((vs[0] > 0) * vs[0]) / dzi[0]
    )
    # deposition velocity
    if self.cfg.use_botflux:
        dfdy[j_indx[0], j_indx[0]] -= -1.0 * atm.bot_vdep / dzi[0]

    dfdy[j_indx[0], j_indx[1]] -= (
        1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[1])
        - ((vz[0] < 0) * vz[0]) / dzi[0]
    )
    dfdy[j_indx[0], j_indx[1]] -= (
        1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[1])
        + 1.0
        / (dzi[0])
        * Dzz[0]
        / 2.0
        * (
            -1.0 / Hpi[0]
            + ms * g[0] / (Navo * kb * Ti[0])
            + alpha / Ti[0] * (Tco[1] - Tco[0]) / dzi[0]
        )
        - ((vs[0] < 0) * vs[0]) / dzi[0]
    )

    dfdy[j_indx[nz - 1], j_indx[nz - 1]] -= (
        -1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[nz - 1])
        + ((vz[-1] < 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[nz - 1]] -= (
        -1.0
        / (dzi[nz - 2])
        * (Dzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / (2.0 * ysum[nz - 1])
        - 1.0
        / (dzi[-1])
        * Dzz[-1]
        / 2.0
        * (
            -1.0 / Hpi[-1]
            + ms * g[-1] / (Navo * kb * Ti[-1])
            + alpha / Ti[-1] * (Tco[-1] - Tco[-2]) / dzi[-1]
        )
        + ((vs[-1] < 0) * vs[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] -= (
        1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[(nz - 1) - 1])
        + ((vz[-1] > 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] -= (
        1.0
        / (dzi[nz - 2])
        * (Dzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / (2.0 * ysum[(nz - 1) - 1])
        - 1.0
        / (dzi[-1])
        * Dzz[-1]
        / 2.0
        * (
            -1.0 / Hpi[-1]
            + ms * g[-1] / (Navo * kb * Ti[-1])
            + alpha / Ti[-1] * (Tco[-1] - Tco[-2]) / dzi[-1]
        )
        + ((vs[-1] > 0) * vs[-1]) / dzi[-1]
    )

    return dfdy

lhs_jac_settling_vm(var, atm)

directly constructing lhs = 1./(rh)sparse.identity(ni*nz) - dfdy jacobian matrix for dn/dt + dphi/dz = P - L (including molecular diffusion and gravitation settling for particles) zero-flux BC: 1st derivitive of y is zero inc. vs from molecular diffusion

Source code in src/vulcan/op.py
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
def lhs_jac_settling_vm(self, var, atm):
    """
    directly constructing lhs = 1./(r*h)*sparse.identity(ni*nz) - dfdy
    jacobian matrix for dn/dt + dphi/dz = P - L (including molecular diffusion and gravitation settling for particles)
    zero-flux BC:  1st derivitive of y is zero
    inc. vs from molecular diffusion
    """
    y = var.y.copy()
    nz = self.cfg.nz

    # TEST condensation excluding non-gaseous species
    if self.cfg.non_gas_sp:
        ysum = np.sum(y[:, atm.gas_indx], axis=1)
    else:
        ysum = np.sum(y, axis=1)
    # TEST condensation excluding non-gaseous species
    dzi = atm.dzi.copy()
    Kzz = atm.Kzz.copy()
    Dzz = atm.Dzz.copy()
    vz = atm.vz.copy()
    vs = atm.vs.copy()
    alpha = atm.alpha.copy()
    Tco = atm.Tco.copy()
    mu, ms = atm.mu.copy(), atm.ms.copy()
    g = atm.g
    vm = atm.vm

    Ti = atm.Ti.copy()
    Hpi = atm.Hpi.copy()

    # c0 = 1./(r*h) where r = 1. + 1./2.**0.5
    r = 1.0 + 1.0 / 2.0**0.5
    c0 = 1.0 / (r * var.dt)
    dfdy = neg_achemjac(y, atm.M, var.k)
    np.fill_diagonal(dfdy, c0 + np.diag(dfdy))
    j_indx = []

    for j in range(nz):
        j_indx.append(np.arange(j * ni, j * ni + ni))

    for j in range(1, nz - 1):
        # excluding the buttom and the top cell
        # at j level consists of ni species
        dz_ave = 0.5 * (dzi[j - 1] + dzi[j])
        dfdy[j_indx[j], j_indx[j]] -= (
            -1.0
            / dz_ave
            * (
                Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
            )
            / ysum[j]
            - ((vz[j] > 0) * vz[j] - (vz[j - 1] < 0) * vz[j - 1]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j + 1]] -= (
            1.0 / dz_ave * (Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1]))
            - ((vz[j] < 0) * vz[j]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j - 1]] -= (
            1.0
            / dz_ave
            * (Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1]))
            + ((vz[j - 1] > 0) * vz[j - 1]) / dz_ave
        )

        # [j_indx[j], j_indx[j]] has size ni*ni
        dfdy[j_indx[j], j_indx[j]] -= (
            -1.0
            / dz_ave
            * (
                Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Dzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
            )
            / ysum[j]
            - ((vs[j] > 0) * vs[j] - (vs[j - 1] < 0) * vs[j - 1]) / dz_ave
            - ((vm[j] > 0) * vm[j] - (vm[j - 1] < 0) * vm[j - 1]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j + 1]] -= (
            1.0 / dz_ave * (Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1]))
            - ((vs[j] < 0) * vs[j]) / dz_ave
            - ((vm[j] < 0) * vm[j]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j - 1]] -= (
            1.0
            / dz_ave
            * (Dzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1]))
            + ((vs[j - 1] > 0) * vs[j - 1]) / dz_ave
            + ((vm[j - 1] > 0) * vm[j - 1]) / dz_ave
        )

    dfdy[j_indx[0], j_indx[0]] -= (
        -1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[0])
        - ((vz[0] > 0) * vz[0]) / dzi[0]
    )
    dfdy[j_indx[0], j_indx[0]] -= (
        -1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[0])
        - ((vs[0] > 0) * vs[0]) / dzi[0]
    )
    # deposition velocity
    if self.cfg.use_botflux:
        dfdy[j_indx[0], j_indx[0]] -= -1.0 * atm.bot_vdep / dzi[0]

    # diffusion-limited escape
    if self.cfg.diff_esc:  # not empty list
        diff_lim = np.zeros(ni)
        for sp in self.cfg.diff_esc:
            if y[-1, species.index(sp)] > 0:
                diff_lim[species.index(sp)] += (
                    atm.top_flux[species.index(sp)] / y[-1, species.index(sp)]
                )
        dfdy[j_indx[-1], j_indx[-1]] -= diff_lim  # negative

    dfdy[j_indx[0], j_indx[1]] -= (
        1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[1])
        - ((vz[0] < 0) * vz[0]) / dzi[0]
    )
    dfdy[j_indx[0], j_indx[1]] -= (
        1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[1])
        - ((vs[0] < 0) * vs[0]) / dzi[0]
    )

    dfdy[j_indx[nz - 1], j_indx[nz - 1]] -= (
        -1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[nz - 1])
        + ((vz[-1] < 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[nz - 1]] -= (
        -1.0
        / (dzi[nz - 2])
        * (Dzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / (2.0 * ysum[nz - 1])
        + ((vs[-1] < 0) * vs[-1]) / dzi[-1]
        + ((vm[-1] < 0) * vm[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] -= (
        1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[(nz - 1) - 1])
        + ((vz[-1] > 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] -= (
        1.0
        / (dzi[nz - 2])
        * (Dzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / (2.0 * ysum[(nz - 1) - 1])
        + ((vs[-1] > 0) * vs[-1]) / dzi[-1]
        + ((vm[-1] > 0) * vm[-1]) / dzi[-1]
    )

    return dfdy

lhs_jac_tot(var, atm)

directly constructing lhs = 1./(rh)sparse.identity(ni*nz) - dfdy jacobian matrix for dn/dt + dphi/dz = P - L (including molecular diffusion) zero-flux BC: 1st derivitive of y is zero

Source code in src/vulcan/op.py
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
def lhs_jac_tot(self, var, atm):
    """
    directly constructing lhs = 1./(r*h)*sparse.identity(ni*nz) - dfdy
    jacobian matrix for dn/dt + dphi/dz = P - L (including molecular diffusion)
    zero-flux BC:  1st derivitive of y is zero
    """

    nz = self.cfg.nz

    y = var.y.copy()
    # TEST condensation excluding non-gaseous species
    if self.cfg.use_condense:
        ysum = np.sum(y[:, atm.gas_indx], axis=1)
        # ysum = np.sum(y, axis=1)
    else:
        ysum = np.sum(y, axis=1)
    # TEST condensation excluding non-gaseous species
    dzi = atm.dzi.copy()
    Kzz = atm.Kzz.copy()
    Dzz = atm.Dzz.copy()
    vz = atm.vz.copy()
    alpha = atm.alpha.copy()
    Tco = atm.Tco
    mu, ms = atm.mu.copy(), atm.ms.copy()
    g = atm.g

    Ti = atm.Ti.copy()
    Hpi = atm.Hpi.copy()

    # c0 = 1./(r*h) where r = 1. + 1./2.**0.5
    r = 1.0 + 1.0 / 2.0**0.5
    c0 = 1.0 / (r * var.dt)
    dfdy = neg_achemjac(y, atm.M, var.k, self.cfg.nz)
    np.fill_diagonal(dfdy, c0 + np.diag(dfdy))
    j_indx = []

    for j in range(nz):
        j_indx.append(np.arange(j * ni, j * ni + ni))

    for j in range(1, nz - 1):
        # excluding the buttom and the top cell
        # at j level consists of ni species
        dz_ave = 0.5 * (dzi[j - 1] + dzi[j])
        dfdy[j_indx[j], j_indx[j]] -= (
            -1.0
            / dz_ave
            * (
                Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
            )
            / ysum[j]
            - ((vz[j] > 0) * vz[j] - (vz[j - 1] < 0) * vz[j - 1]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j + 1]] -= (
            1.0 / dz_ave * (Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1]))
            - ((vz[j] < 0) * vz[j]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j - 1]] -= (
            1.0
            / dz_ave
            * (Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1]))
            + ((vz[j - 1] > 0) * vz[j - 1]) / dz_ave
        )

        # [j_indx[j], j_indx[j]] has size ni*ni
        dfdy[j_indx[j], j_indx[j]] -= -1.0 / dz_ave * (
            Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
            + Dzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
        ) / ysum[j] + 1.0 / (2.0 * dz_ave) * (
            Dzz[j]
            * (
                -1.0 / Hpi[j]
                + ms * g[j] / (Navo * kb * Ti[j])
                + alpha / Ti[j] * (Tco[j + 1] - Tco[j]) / dzi[j]
            )
            - Dzz[j - 1]
            * (
                -1.0 / Hpi[j - 1]
                + ms * g[j] / (Navo * kb * Ti[j - 1])
                + alpha / Ti[j - 1] * (Tco[j] - Tco[j - 1]) / dzi[j - 1]
            )
        )
        dfdy[j_indx[j], j_indx[j + 1]] -= 1.0 / dz_ave * (
            Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1])
        ) + 1.0 / (2.0 * dz_ave) * Dzz[j] * (
            -1.0 / Hpi[j]
            + ms * g[j + 1] / (Navo * kb * Ti[j])
            + alpha / Ti[j] * (Tco[j + 1] - Tco[j]) / dzi[j]
        )
        dfdy[j_indx[j], j_indx[j - 1]] -= 1.0 / dz_ave * (
            Dzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1])
        ) - 1.0 / (2.0 * dz_ave) * Dzz[j - 1] * (
            -1.0 / Hpi[j - 1]
            + ms * g[j - 1] / (Navo * kb * Ti[j - 1])
            + alpha / Ti[j - 1] * (Tco[j] - Tco[j - 1]) / dzi[j - 1]
        )

    dfdy[j_indx[0], j_indx[0]] -= (
        -1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[0])
        - ((vz[0] > 0) * vz[0]) / dzi[0]
    )
    dfdy[j_indx[0], j_indx[0]] -= -1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (
        ysum[1] + ysum[0]
    ) / (2.0 * ysum[0]) + 1.0 / (dzi[0]) * Dzz[0] / 2.0 * (
        -1.0 / Hpi[0]
        + ms * g[0] / (Navo * kb * Ti[0])
        + alpha / Ti[0] * (Tco[1] - Tco[0]) / dzi[0]
    )
    # deposition velocity
    if self.cfg.use_botflux:
        dfdy[j_indx[0], j_indx[0]] -= -1.0 * atm.bot_vdep / dzi[0]

    dfdy[j_indx[0], j_indx[1]] -= (
        1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[1])
        - ((vz[0] < 0) * vz[0]) / dzi[0]
    )
    dfdy[j_indx[0], j_indx[1]] -= 1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (
        ysum[1] + ysum[0]
    ) / (2.0 * ysum[1]) + 1.0 / (dzi[0]) * Dzz[0] / 2.0 * (
        -1.0 / Hpi[0]
        + ms * g[0] / (Navo * kb * Ti[0])
        + alpha / Ti[0] * (Tco[1] - Tco[0]) / dzi[0]
    )

    dfdy[j_indx[nz - 1], j_indx[nz - 1]] -= (
        -1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[nz - 1])
        + ((vz[-1] < 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[nz - 1]] -= -1.0 / (dzi[nz - 2]) * (
        Dzz[nz - 2] / dzi[nz - 2]
    ) * (ysum[nz - 1] + ysum[nz - 2]) / (2.0 * ysum[nz - 1]) - 1.0 / (dzi[-1]) * Dzz[
        -1
    ] / 2.0 * (
        -1.0 / Hpi[-1]
        + ms * g[-1] / (Navo * kb * Ti[-1])
        + alpha / Ti[-1] * (Tco[-1] - Tco[-2]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] -= (
        1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[(nz - 1) - 1])
        + ((vz[-1] > 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] -= 1.0 / (dzi[nz - 2]) * (
        Dzz[nz - 2] / dzi[nz - 2]
    ) * (ysum[nz - 1] + ysum[nz - 2]) / (2.0 * ysum[(nz - 1) - 1]) - 1.0 / (dzi[-1]) * Dzz[
        -1
    ] / 2.0 * (
        -1.0 / Hpi[-1]
        + ms * g[-1] / (Navo * kb * Ti[-1])
        + alpha / Ti[-1] * (Tco[-1] - Tco[-2]) / dzi[-1]
    )

    return dfdy

lhs_jac_tot_vm(var, atm)

directly constructing lhs = 1./(rh)sparse.identity(ni*nz) - dfdy jacobian matrix for dn/dt + dphi/dz = P - L (including molecular diffusion) zero-flux BC: 1st derivitive of y is zero inc. vm from molecular diffusion

Source code in src/vulcan/op.py
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
def lhs_jac_tot_vm(self, var, atm):
    """
    directly constructing lhs = 1./(r*h)*sparse.identity(ni*nz) - dfdy
    jacobian matrix for dn/dt + dphi/dz = P - L (including molecular diffusion)
    zero-flux BC:  1st derivitive of y is zero
    inc. vm from molecular diffusion
    """
    y = var.y.copy()
    nz = self.cfg.nz

    # TEST condensation excluding non-gaseous species
    if self.cfg.use_condense:
        ysum = np.sum(y[:, atm.gas_indx], axis=1)
        # ysum = np.sum(y, axis=1)
    else:
        ysum = np.sum(y, axis=1)
    # TEST condensation excluding non-gaseous species
    dzi = atm.dzi.copy()
    Kzz = atm.Kzz.copy()
    Dzz = atm.Dzz.copy()
    vz = atm.vz.copy()
    alpha = atm.alpha.copy()
    Tco = atm.Tco.copy()
    mu, ms = atm.mu.copy(), atm.ms.copy()
    g = atm.g
    vm = atm.vm

    Ti = atm.Ti.copy()
    Hpi = atm.Hpi.copy()

    # c0 = 1./(r*h) where r = 1. + 1./2.**0.5
    r = 1.0 + 1.0 / 2.0**0.5
    c0 = 1.0 / (r * var.dt)
    dfdy = neg_achemjac(y, atm.M, var.k)
    np.fill_diagonal(dfdy, c0 + np.diag(dfdy))
    j_indx = []

    for j in range(nz):
        j_indx.append(np.arange(j * ni, j * ni + ni))

    for j in range(1, nz - 1):
        # excluding the buttom and the top cell
        # at j level consists of ni species
        dz_ave = 0.5 * (dzi[j - 1] + dzi[j])
        dfdy[j_indx[j], j_indx[j]] -= (
            -1.0
            / dz_ave
            * (
                Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
            )
            / ysum[j]
            - ((vz[j] > 0) * vz[j] - (vz[j - 1] < 0) * vz[j - 1]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j + 1]] -= (
            1.0 / dz_ave * (Kzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1]))
            - ((vz[j] < 0) * vz[j]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j - 1]] -= (
            1.0
            / dz_ave
            * (Kzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1]))
            + ((vz[j - 1] > 0) * vz[j - 1]) / dz_ave
        )

        # [j_indx[j], j_indx[j]] has size ni*ni
        dfdy[j_indx[j], j_indx[j]] -= (
            -1.0
            / dz_ave
            * (
                Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / 2.0
                + Dzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / 2.0
            )
            / ysum[j]
            - ((vm[j] > 0) * vm[j] - (vm[j - 1] < 0) * vm[j - 1]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j + 1]] -= (
            1.0 / dz_ave * (Dzz[j] / dzi[j] * (ysum[j + 1] + ysum[j]) / (2.0 * ysum[j + 1]))
            - ((vm[j] < 0) * vm[j]) / dz_ave
        )
        dfdy[j_indx[j], j_indx[j - 1]] -= (
            1.0
            / dz_ave
            * (Dzz[j - 1] / dzi[j - 1] * (ysum[j - 1] + ysum[j]) / (2.0 * ysum[j - 1]))
            + ((vm[j - 1] > 0) * vm[j - 1]) / dz_ave
        )

    dfdy[j_indx[0], j_indx[0]] -= (
        -1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[0])
        - ((vz[0] > 0) * vz[0]) / dzi[0]
    )
    dfdy[j_indx[0], j_indx[0]] -= (
        -1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[0])
        - ((vm[0] > 0) * vm[0]) / dzi[0]
    )
    # deposition velocity
    if self.cfg.use_botflux:
        dfdy[j_indx[0], j_indx[0]] -= -1.0 * atm.bot_vdep / dzi[0]
    # diffusion-limited escape
    if self.cfg.diff_esc:  # not empty list
        diff_lim = np.zeros(ni)
        for sp in self.cfg.diff_esc:
            if y[-1, species.index(sp)] > 0:
                diff_lim[species.index(sp)] += (
                    atm.top_flux[species.index(sp)] / y[-1, species.index(sp)]
                )
        dfdy[j_indx[-1], j_indx[-1]] -= diff_lim  # negative

    dfdy[j_indx[0], j_indx[1]] -= (
        1.0 / (dzi[0]) * (Kzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[1])
        - ((vz[0] < 0) * vz[0]) / dzi[0]
    )
    dfdy[j_indx[0], j_indx[1]] -= (
        1.0 / (dzi[0]) * (Dzz[0] / dzi[0]) * (ysum[1] + ysum[0]) / (2.0 * ysum[1])
        - ((vm[0] < 0) * vm[0]) / dzi[0]
    )

    dfdy[j_indx[nz - 1], j_indx[nz - 1]] -= (
        -1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[nz - 1])
        + ((vz[-1] < 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[nz - 1]] -= (
        -1.0
        / (dzi[nz - 2])
        * (Dzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / (2.0 * ysum[nz - 1])
        + ((vm[-1] < 0) * vm[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] -= (
        1.0
        / (dzi[nz - 2])
        * (Kzz[nz - 2] / dzi[nz - 2])
        * (ysum[(nz - 1) - 1] + ysum[nz - 1])
        / (2.0 * ysum[(nz - 1) - 1])
        + ((vz[-1] > 0) * vz[-1]) / dzi[-1]
    )
    dfdy[j_indx[nz - 1], j_indx[(nz - 1) - 1]] -= (
        1.0
        / (dzi[nz - 2])
        * (Dzz[nz - 2] / dzi[nz - 2])
        * (ysum[nz - 1] + ysum[nz - 2])
        / (2.0 * ysum[(nz - 1) - 1])
        + ((vm[-1] > 0) * vm[-1]) / dzi[-1]
    )

    return dfdy

loss(data_var)

Source code in src/vulcan/op.py
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
def loss(self, data_var):

    y = data_var.y
    atom_list = self.cfg.atom_list

    # changed atom_tot to dictionary atom_sum
    atom_sum = data_var.atom_sum

    for atom in atom_list:
        # data_var.atom_sum[atom] = np.sum([compo[compo_row.index(species[i])][atom] * data_var.y[:,i] for i in range(ni)])
        # TEST V scaling
        if atom not in getattr(self.cfg, 'loss_ex', []):  # shami added 2024
            data_var.atom_sum[atom] = np.sum(
                [
                    compo[compo_row.index(species[i])][atom] * data_var.y[:, i]
                    for i in range(ni)
                ]
            )  # *data_var.v_ratio
            data_var.atom_loss[atom] = (
                data_var.atom_sum[atom] - data_var.atom_ini[atom]
            ) / data_var.atom_ini[atom]

    return data_var

print_lossBig(para)

Source code in src/vulcan/op.py
3921
3922
3923
3924
3925
def print_lossBig(self, para):

    log.warning('Element conservation is violated too large')
    log.warning('at step: ' + str(para.count))
    log.warning(spacer)

print_nega(data_var, data_para)

Source code in src/vulcan/op.py
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
def print_nega(self, data_var, data_para):

    nega_i = np.where(data_var.y < 0)
    log.warning(
        'Negative y at time '
        + str('{:.2e}'.format(data_var.t))
        + ' and step: '
        + str(data_para.count)
    )
    log.warning('Negative values:' + str(data_var.y[data_var.y < 0]))
    log.warning('from levels: ' + str(nega_i[0]))
    log.warning('species: ' + str([species[s] for s in nega_i[1]]))
    log.warning('dt= ' + str(data_var.dt))
    log.warning('...reset dt to dt*0.2...')
    log.warning(spacer)

reset_y(var, dt_reduc=0.5)

reset y and reduce dt by dt_reduc

Source code in src/vulcan/op.py
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
def reset_y(self, var, dt_reduc=0.5):
    """
    reset y and reduce dt by dt_reduc
    """

    # reset and store y and dt
    var.y = var.y_prev
    var.dt *= dt_reduc
    # var.dt = np.maximum(var.dt, self.cfg.dt_min)

    return var

step_ok(var, para, loss_eps=0.1, rtol=0.6)

Source code in src/vulcan/op.py
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
def step_ok(self, var, para, loss_eps=1e-1, rtol=0.6):
    if (
        np.all(var.y >= 0)
        and np.amax(
            np.abs(
                np.fromiter(var.atom_loss.values(), float)
                - np.fromiter(var.atom_loss_prev.values(), float)
            )
        )
        < loss_eps
        and para.delta <= rtol
    ):
        return True
    else:
        return False

step_reject(var, para, loss_eps=0.1, rtol=0.6)

Source code in src/vulcan/op.py
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
def step_reject(self, var, para, loss_eps=1e-1, rtol=0.6):

    if para.delta > rtol:  # truncation error larger than the tolerence value
        para.delta_count += 1

    elif np.any(var.y < 0):
        para.nega_count += 1
        if self.cfg.use_print_prog:
            self.print_nega(
                var, para
            )  # print the info for the negative solutions (where y < 0)
        # print input: y, t, count, dt

    else:  # meaning np.amax( np.abs( np.abs(y_loss) - np.abs(loss_prev) ) )<loss_eps
        para.loss_count += 1
        if self.cfg.use_print_prog:
            self.print_lossBig(para)

    # reset y and dt to the values at previous step
    var = self.reset_y(var, dt_reduc=self.cfg.dt_var_min)

    if var.dt < self.cfg.dt_min:
        var.dt = self.cfg.dt_min
        var.y[var.y < 0] = 0.0  # clipping of negative values

        log.warning(
            'Keep producing negative values! Clipping negative solutions and moving on!'
        )
        return True

    return False

thomas_vec(a, b, c, d)

Thomas vectorized solver, a b c d refer to http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm d is a matrix not used in this current version

Source code in src/vulcan/op.py
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
def thomas_vec(a, b, c, d):
    """
    Thomas vectorized solver, a b c d refer to http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm
    d is a matrix
    not used in this current version
    """
    # number of equations
    nf = len(a)
    aa, bb, cc, dd = map(np.copy, (a, b, c, d))
    # d needs to reshape
    dd = dd.reshape(nf, -1)
    # C' and D'
    cp = [cc[0] / bb[0]]
    dp = [dd[0] / bb[0]]
    x = np.zeros((nf, np.shape(dd)[1]))

    for i in range(1, nf - 1):
        cp.append(cc[i] / (bb[i] - aa[i] * cp[i - 1]))
        dp.append((dd[i] - aa[i] * dp[i - 1]) / (bb[i] - aa[i] * cp[i - 1]))

    dp.append(
        (dd[(nf - 1)] - aa[(nf - 1)] * dp[(nf - 1) - 1])
        / (bb[(nf - 1)] - aa[(nf - 1)] * cp[(nf - 1) - 1])
    )  # nf-1 is the last element
    x[nf - 1] = dp[nf - 1] / 1
    for i in range(nf - 2, -1, -1):
        x[i] = dp[i] - cp[i] * x[i + 1]

    return x

Ros2(vulcan_cfg)

Bases: ODESolver

class inheritance from ODEsolver for 2nd order Rosenbrock solver

Source code in src/vulcan/op.py
4290
4291
4292
def __init__(self, vulcan_cfg: Config):
    # ODESolver.__init__(self)
    super().__init__(vulcan_cfg)

naming_solver(para)

Source code in src/vulcan/op.py
4562
4563
4564
4565
4566
4567
def naming_solver(self, para):
    if self.cfg.use_moldiff:
        log.info('Include molecular diffusion.')
    else:
        log.info('No molecular diffusion.')
    para.solver_str = 'solver'

one_step(var, atm, para)

Source code in src/vulcan/op.py
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
def one_step(self, var, atm, para):

    while True:
        var, para = getattr(self, para.solver_str)(var, atm, para)

        # clipping small negative values and also calculating atomic loss (atom_loss)
        var, para = self.clip(
            var,
            para,
            atm,
            pos_cut=self.cfg.pos_cut,
            nega_cut=self.cfg.nega_cut,
        )

        if self.step_ok(var, para, loss_eps=self.cfg.loss_eps, rtol=self.cfg.rtol):
            break
        elif self.step_reject(var, para, loss_eps=self.cfg.loss_eps, rtol=self.cfg.rtol):
            break

    return var, para

solver(var, atm, para)

2nd order Rosenbrock [Verwer et al. 1997] with banded-matrix solver with switches to include the molecular diffusion or not

Source code in src/vulcan/op.py
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
def solver(self, var, atm, para):
    """
    2nd order Rosenbrock [Verwer et al. 1997] with banded-matrix solver
    with switches to include the molecular diffusion or not
    """

    nz = self.cfg.nz
    y, ymix, h, k = var.y, var.ymix, var.dt, var.k
    M, dzi, Kzz = atm.M, atm.dzi, atm.Kzz

    if not self.cfg.use_vm_mol:
        if self.cfg.use_moldiff and not self.cfg.use_settling:
            diffdf = self.diffdf
            jac_tot = self.lhs_jac_tot
        elif self.cfg.use_moldiff and self.cfg.use_settling:
            diffdf = self.diffdf_settling
            jac_tot = self.lhs_jac_settling
        else:
            diffdf = self.diffdf_no_mol
            jac_tot = self.lhs_jac_no_mol
    else:  # vulcan_cfg.use_vm_mol :
        if self.cfg.use_moldiff and not self.cfg.use_settling:
            diffdf = self.diffdf_vm
            jac_tot = self.lhs_jac_tot_vm
        elif self.cfg.use_moldiff and self.cfg.use_settling:
            diffdf = self.diffdf_settling_vm
            jac_tot = self.lhs_jac_settling_vm
        else:
            diffdf = self.diffdf_no_mol
            jac_tot = self.lhs_jac_no_mol

    r = 1.0 + 1.0 / 2.0**0.5

    df = chemdf(y, M, k).flatten() + diffdf(y, atm).flatten()
    lhs = jac_tot(var, atm)

    # Fixed species including only below the cold trap # TEST 2022
    if self.cfg.use_condense and para.fix_species_start:
        for sp in self.cfg.fix_species:
            if (
                not self.cfg.fix_species_from_coldtrap_lev
            ):  # if Ptop is not specified, fix the whole column # TEST2022
                pass
            else:
                pfix_indx = atm.conden_min_lev[sp]
                atm.fix_sp_indx[sp] = np.arange(
                    species.index(sp), species.index(sp) + ni * (pfix_indx), ni
                )

            df[atm.fix_sp_indx[sp]] = 0
            lhs[atm.fix_sp_indx[sp], :] = 0
            lhs[atm.fix_sp_indx[sp], atm.fix_sp_indx[sp]] = (
                1.0 / (r * h)
            )  # cuz the jacobian func is directly outputing 1./(r*h)*sparse.identity(ni*nz) - dfdy

    if self.cfg.use_ion:
        df[atm.fix_e_indx] = 0
        lhs[atm.fix_e_indx, :] = 0
        lhs[atm.fix_e_indx, atm.fix_e_indx] = 1.0 / (r * h)

    lhs_b, bw = self.store_bandM(lhs, ni, nz)
    k1_flat = scipy.linalg.solve_banded((bw, bw), lhs_b, df)
    k1 = k1_flat.reshape(y.shape)

    yk2 = y + k1 / r
    df = chemdf(yk2, M, k).flatten() + diffdf(yk2, atm).flatten()

    # TEST condensation
    # Fixed species
    if self.cfg.use_condense and para.fix_species_start:
        for sp in self.cfg.fix_species:
            df[atm.fix_sp_indx[sp]] = 0
    if self.cfg.use_ion:
        df[atm.fix_e_indx] = 0

    rhs = df - 2.0 / (r * h) * k1_flat
    k2 = scipy.linalg.solve_banded((bw, bw), lhs_b, rhs)
    k2 = k2.reshape(y.shape)

    sol = y + 3.0 / (2.0 * r) * k1 + 1 / (2.0 * r) * k2

    ### for Hycean ###
    if (
        getattr(self.cfg, 'use_fix_H2He', False)
        and 'H2' not in self.cfg.use_fix_sp_bot
        and var.t > 1e6
    ):
        self.cfg.use_fix_sp_bot['H2'] = var.ymix[0, species.index('H2')]
        self.cfg.use_fix_sp_bot['He'] = var.ymix[0, species.index('He')]
        print(
            'After 1e6 sec, H2 and He are fixed at '
            + str((var.ymix[0, species.index('H2')], var.ymix[0, species.index('He')]))
        )

        self.fix_sp_bot_index = [species.index(sp) for sp in self.cfg.use_fix_sp_bot.keys()]
        self.fix_sp_bot_mix = np.array(
            [self.cfg.use_fix_sp_bot[sp] for sp in self.cfg.use_fix_sp_bot.keys()]
        )
    ### for Hycean ###

    # setting particles on the surace = 0
    if self.cfg.use_fix_sp_bot:  # if use_fix_sp_bot = {} (empty), it returns false
        sol[0, self.fix_sp_bot_index] = self.fix_sp_bot_mix * atm.n_0[0]

    delta = np.abs(sol - yk2)
    delta[ymix < self.mtol] = 0
    delta[sol < self.atol] = 0

    # neglecting the errors at the surface
    if self.cfg.use_botflux or self.cfg.use_fix_sp_bot:
        delta[0] = 0

    # TEST condensation 2022
    if self.cfg.use_condense:
        delta[:, self.non_gas_sp_index] = 0
        delta[:, self.condense_sp_index] = 0

        if para.fix_species_start:
            for sp in self.cfg.fix_species:
                if (
                    not self.cfg.fix_species_from_coldtrap_lev
                ):  # if Ptop is not specified, fix the whole column # TEST2022
                    sol[:, species.index(sp)] = var.fix_y[sp].copy()
                else:
                    # pfix_indx = min( range(len(atm.pco)), key=lambda i: abs(atm.pco[i]- self.cfg.fix_species_Ptop[0] ))
                    pfix_indx = atm.conden_min_lev[sp]
                    sol[:pfix_indx, species.index(sp)] = var.fix_y[sp].copy()[:pfix_indx]

                delta[:, species.index(sp)] = 0

    if self.cfg.use_print_delta and para.count % self.cfg.print_prog_num == 0:
        max_indx = np.nanargmax(delta / sol, axis=1)
        max_lev_indx = np.nanargmax(delta / sol)
        log.info(
            'Largest delta (truncation error) from nz = ' + str(int(max_lev_indx / ni))
        )
        log.info(np.array(species)[max_indx])
        log.info(
            'Largest delta (truncation error) from '
            + species[max_indx % ni]
            + ' at nz = '
            + str(int(max_indx / ni))
        )

    delta = np.amax(delta[sol > 0] / sol[sol > 0])

    var.y = sol

    # # TEST condensation excluding non-gaseous species
    if self.cfg.non_gas_sp:
        var.ymix = var.y / np.vstack(np.sum(var.y[:, atm.gas_indx], axis=1))
    else:
        var.ymix = var.y / np.vstack(np.sum(var.y, axis=1))
    # TEST condensation excluding non-gaseous species

    para.delta = delta

    # use charge balance to obtain the number density of electrons (such that [ions] = [e])
    if self.cfg.use_ion:
        # clear e
        var.y[:, species.index('e')] = 0
        # set e such that the net chare is zero
        for sp in var.charge_list:
            var.y[:, species.index('e')] -= (
                compo[compo_row.index(sp)]['e'] * var.y[:, species.index(sp)]
            )

    return var, para

solver_fix_all_bot(var, atm, para)

2nd order Rosenbrock [Verwer et al. 1997] with banded-matrix solver with switches to include the molecular diffusion or not

Source code in src/vulcan/op.py
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
def solver_fix_all_bot(self, var, atm, para):
    """
    2nd order Rosenbrock [Verwer et al. 1997] with banded-matrix solver
    with switches to include the molecular diffusion or not
    """

    nz = self.cfg.nz

    y, ymix, h, k = var.y, var.ymix, var.dt, var.k
    M, dzi, Kzz = atm.M, atm.dzi, atm.Kzz

    # store the fixed bottom level
    bottom = np.copy(ymix[0])

    if self.cfg.use_moldiff:
        diffdf = self.diffdf
        jac_tot = self.lhs_jac_fix_all_bot
    else:
        diffdf = self.diffdf_no_mol
        jac_tot = self.lhs_jac_no_mol_fix_all_bot

    r = 1.0 + 1.0 / 2.0**0.5

    df = chemdf(y, M, k).flatten() + diffdf(y, atm).flatten()
    lhs = jac_tot(var, atm)

    lhs_b, bw = self.store_bandM(lhs, ni, nz)
    k1_flat = scipy.linalg.solve_banded((bw, bw), lhs_b, df)

    k1 = k1_flat.reshape(y.shape)

    yk2 = y + k1 / r
    df = chemdf(yk2, M, k).flatten() + diffdf(yk2, atm).flatten()

    rhs = df - 2.0 / (r * h) * k1_flat
    k2 = scipy.linalg.solve_banded((bw, bw), lhs_b, rhs)
    k2 = k2.reshape(y.shape)

    sol = y + 3.0 / (2.0 * r) * k1 + 1 / (2.0 * r) * k2

    # fixed the bottom layer to yini (in chemical EQ)
    sol[0] = bottom * atm.n_0[0]

    delta = np.abs(sol - yk2)
    delta[ymix < self.mtol] = 0
    delta[sol < self.atol] = 0

    delta = np.amax(delta[sol > 0] / sol[sol > 0])

    var.y = sol

    # # TEST condensation excluding non-gaseous species
    if self.cfg.non_gas_sp:
        var.ymix = var.y / np.vstack(np.sum(var.y[:, atm.gas_indx], axis=1))
    else:
        var.ymix = var.y / np.vstack(np.sum(var.y, axis=1))
    # TEST condensation excluding non-gaseous species

    para.delta = delta

    # use charge balance to obtain the number density of electrons (such that [ions] = [e])
    if self.cfg.use_ion:
        # clear e
        var.y[:, species.index('e')] = 0
        # set e such that the net chare is zero
        for sp in var.charge_list:
            var.y[:, species.index('e')] -= (
                compo[compo_row.index(sp)]['e'] * var.y[:, species.index(sp)]
            )

    return var, para

step_size(var, para, dt_var_min=2, dt_var_max=0.5, dt_min=1e-10, dt_max=1e+18)

step-size control by delta(truncation error) for the Rosenbrock method

Source code in src/vulcan/op.py
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
def step_size(self, var, para, dt_var_min=2, dt_var_max=0.5, dt_min=1e-10, dt_max=1e18):
    """
    step-size control by delta(truncation error) for the Rosenbrock method
    """
    h = var.dt
    delta = para.delta
    rtol = self.cfg.rtol

    if delta == 0:
        delta = 0.01 * rtol
    h_factor = 0.9 * (rtol / delta) ** 0.5  # 0.9 is simply a safety factor
    h_factor = np.maximum(h_factor, dt_var_min)
    h_factor = np.minimum(h_factor, dt_var_max)

    h *= h_factor
    h = np.maximum(h, dt_min)
    h = np.minimum(h, dt_max)

    # store the adopted dt
    var.dt = h

    return var

store_bandM(a, nb, nn)

store block-tridiagonal matrix(bandwidth=1) into diagonal ordered form (http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve_banded.html) a : square block-tridiagonal matirx nb: size of the block matrix (number of species) nn: number of the block matrices (number of layers)

Source code in src/vulcan/op.py
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
def store_bandM(self, a, nb, nn):
    """
    store block-tridiagonal matrix(bandwidth=1) into diagonal ordered form
    (http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve_banded.html)
    a : square block-tridiagonal matirx
    nb: size of the block matrix (number of species)
    nn: number of the block matrices (number of layers)
    """

    # band width (treat block-banded as banded matrix)
    bw = 2 * nb - 1
    ab = np.zeros((2 * bw + 1, nb * nn))

    # first 2 columns
    for i in range(0, 2 * nb):
        ab[-(2 * nb + i) :, i] = a[0 : 2 * nb + i, i]

    # middle
    for i in range(2 * nb, nn * nb - 2 * nb):
        ab[:, i] = a[(i - 2 * nb + 1) : (i - 2 * nb + 1) + (2 * bw + 1), i]

    # last 2 columns
    for ne, i in enumerate(range(nn * nb - 2 * nb, nn * nb)):
        ab[: (2 * bw + 1 - ne), i] = a[-(2 * bw + 1 - ne) :, i]

    return (ab, bw)

Output(vulcan_cfg)

Bases: object

Source code in src/vulcan/op.py
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
def __init__(self, vulcan_cfg: Config):

    self.cfg = vulcan_cfg
    output_dir = self.cfg.output_dir + '/'
    out_name = self.cfg.out_name

    if self.cfg.clean_output:
        safe_rm(self.cfg.output_dir)

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    if not os.path.exists(self.cfg.plot_dir):
        os.makedirs(self.cfg.plot_dir)

    outfile = output_dir + out_name
    if os.path.isfile(outfile):
        log.warning('Output file already exists. Removing.')
        safe_rm(outfile)

cfg = vulcan_cfg instance-attribute

plot_TP(atm)

Source code in src/vulcan/op.py
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
def plot_TP(self, atm):
    plot_dir = self.cfg.plot_dir
    # plt.figure('TPK')
    fig, ax1 = plt.subplots()
    ax2 = ax1.twiny()  # ax1 and ax2 share y-axis

    if not self.cfg.plot_height:
        ax1.semilogy(atm.Tco, atm.pco / 1.0e6, c='black')
        ax2.loglog(atm.Kzz, atm.pico[1:-1] / 1.0e6, c='k', ls='--')
        plt.gca().invert_yaxis()
        plt.ylim((self.cfg.P_b / 1.0e6, self.cfg.P_t / 1.0e6))
        ax1.set_ylabel('Pressure (bar)')

    else:  # plotting with height
        ax1.plot(atm.Tco, atm.zmco / 1.0e5, c='black')
        ax2.semilogx(atm.Kzz, atm.zmco[1:] / 1.0e5, c='k', ls='--')
        ax1.set_ylabel('Height (km)')

    # plt.xlabel("Temperature (K)")
    ax1.set_xlabel('Temperature (K)')
    ax2.set_xlabel(r'K$_{zz}$ (cm$^2$s$^{-1}$)')

    fig.savefig(plot_dir + f'TPK_initial.{PLT_FMT}', dpi=self.cfg.plot_dpi)

plot_evo(var, atm, plot_j=-1, plot_ymin=1e-16, dn=1)

Plot the evolution of mixing ratios over time.

Arguments
  • var: variable object containing the time evolution data
  • atm: atmosphere object containing the atmospheric properties
  • plot_j: index of the atmospheric layer to plot (default: -1)
  • plot_ymin: minimum y-axis value for the plot (default: 1e-16)
  • dn: data point interval for plotting (default: 1, meaning plot all points)
Source code in src/vulcan/op.py
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
def plot_evo(self, var, atm, plot_j=-1, plot_ymin=1e-16, dn=1):
    """
    Plot the evolution of mixing ratios over time.

    Arguments
    ------------
    - var: variable object containing the time evolution data
    - atm: atmosphere object containing the atmospheric properties
    - plot_j: index of the atmospheric layer to plot (default: -1)
    - plot_ymin: minimum y-axis value for the plot (default: 1e-16)
    - dn: data point interval for plotting (default: 1, meaning plot all points)
    """

    plot_spec = self.cfg.plot_spec
    plot_dir = self.cfg.plot_dir
    fig, ax = plt.subplots(1, 1, figsize=(8, 6))

    ymix_time = np.array(var.y_time / atm.n_0[:, np.newaxis])

    for i, sp in enumerate(self.cfg.plot_spec):
        col = gas_cols.get(sp, plt.cm.rainbow(float(i) / len(plot_spec)))
        lbl = tex_labels.get(sp, sp)
        ax.plot(
            var.t_time[::dn], ymix_time[::dn, plot_j, species.index(sp)], c=col, label=lbl
        )

    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set_xlabel('Time [s]')
    ax.set_ylabel('Volume mixing ratios')
    ax.set_ylim((plot_ymin, 1.2))
    ax.legend(fontsize=10, labelspacing=0.2, loc='upper left', bbox_to_anchor=(1.0, 1.0))
    fig.savefig(plot_dir + f'evo.{PLT_FMT}', dpi=self.cfg.plot_dpi)
    plt.close('all')

plot_evo_inter(var, atm, plot_j=-1, plot_ymin=1e-16, dn=1)

plot the evolution when the code is interrupted

Source code in src/vulcan/op.py
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
def plot_evo_inter(self, var, atm, plot_j=-1, plot_ymin=1e-16, dn=1):
    """
    plot the evolution when the code is interrupted
    """
    var.t_time = np.array(var.t_time)
    ymix_time = np.array(var.y_time / atm.n_0[:, np.newaxis])

    plot_spec = self.cfg.plot_spec
    plot_dir = self.cfg.plot_dir
    plt.figure('evolution')

    for i, sp in enumerate(self.cfg.plot_spec):
        plt.plot(
            var.t_time[::dn],
            ymix_time[::dn, plot_j, species.index(sp)],
            c=plt.cm.rainbow(float(i) / len(plot_spec)),
            label=sp,
        )

    plt.gca().set_xscale('log')
    plt.gca().set_yscale('log')
    plt.xlabel('time')
    plt.ylabel('mixing ratios')
    plt.ylim((plot_ymin, 1.0))
    plt.legend(frameon=0, prop={'size': 14}, loc='best')
    plt.savefig(plot_dir + f'evo.{PLT_FMT}', dpi=self.cfg.plot_dpi)

plot_flux_update(var, atm, para)

Source code in src/vulcan/op.py
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
def plot_flux_update(self, var, atm, para):

    images = []
    plt.ion()

    # fig.add_subplot(121) fig.add_subplot(122)

    (line1,) = plt.plot(np.sum(var.dflux_u, axis=1), atm.pico / 1.0e6, label='up flux')
    (line2,) = plt.plot(
        np.sum(var.dflux_d, axis=1), atm.pico / 1.0e6, label='down flux', ls='--', lw=1.2
    )
    (line3,) = plt.plot(
        np.sum(var.sflux, axis=1), atm.pico / 1.0e6, label='stellar flux', ls=':', lw=1.5
    )

    images.append((line1, line2))

    plt.title(str(para.count) + ' steps and ' + str('{:.2e}'.format(var.t)) + ' s')
    plt.gca().set_xscale('log')
    plt.gca().set_yscale('log')
    plt.gca().invert_yaxis()
    plt.xlim(xmin=1.0e-8)
    plt.ylim((atm.pico[0] / 1.0e6, atm.pico[-1] / 1.0e6))
    plt.legend(frameon=0, prop={'size': 14}, loc=3)
    plt.xlabel('Diffusive flux')
    plt.ylabel('Pressure (bar)')
    plt.show(block=0)
    plt.pause(0.1)
    if self.cfg.use_flux_movie:
        plt.savefig('plot/movie/flux-' + str(para.count) + '.jpg', dpi=self.cfg.plot_dpi)

    plt.close('all')

plot_update(var, atm, para, fpath=None)

Source code in src/vulcan/op.py
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
def plot_update(self, var, atm, para, fpath=None):

    log.debug('Plotting mixing ratios')

    colors = [
        'b',
        'r',
        'c',
        'm',
        'y',
        'k',
        'orange',
        'pink',
        'grey',
        'darkred',
        'darkblue',
        'salmon',
        'chocolate',
        'mediumspringgreen',
        'steelblue',
        'plum',
        'hotpink',
    ]

    fig, ax = plt.subplots(1, 1, figsize=(8, 6))
    color_index = 0
    for sp in self.cfg.plot_spec:
        if sp in tex_labels:
            sp_lab = tex_labels[sp]
        else:
            sp_lab = sp

        if color_index == len(colors):  # when running out of colors
            colors.append(tuple(np.random.rand(3)))

        if sp in gas_cols.keys():
            color = gas_cols[sp]
        else:
            color = colors[color_index]
            color_index += 1

        if not self.cfg.plot_height:
            (line,) = ax.plot(
                var.ymix[:, species.index(sp)], atm.pco / 1.0e6, color=color, label=sp_lab
            )
            if self.cfg.use_condense and sp in self.cfg.condense_sp:
                ax.plot(
                    atm.sat_mix[sp],
                    atm.pco / 1.0e6,
                    color=color,
                    label=sp_lab + ' sat',
                    ls='--',
                )

            ax.set_yscale('log')
            ax.invert_yaxis()
            ax.set_ylabel('Pressure [bar]')
            ax.set_ylim((self.cfg.P_b / 1.0e6, self.cfg.P_t / 1.0e6))

        else:  # plotting with height
            (line,) = ax.plot(
                var.ymix[:, species.index(sp)], atm.zmco / 1.0e5, color=color, label=sp_lab
            )
            if self.cfg.use_condense and sp in self.cfg.condense_sp:
                ax.plot(
                    atm.sat_mix[sp],
                    atm.zco[1:] / 1.0e5,
                    color=color,
                    label=sp_lab + ' sat',
                    ls='--',
                )

            ax.set_ylim((atm.zco[0] / 1e5, atm.zco[-1] / 1e5))
            ax.set_ylabel('Height [km]')

    title = 'i = %5d steps     t = %.2e seconds' % (para.count, var.t)
    title += '\n dy/dt = %.2e' % (var.longdydt)
    ax.set_title(title)
    ax.set_xscale('log')
    ax.set_xlabel('Volume mixing ratio')
    ax.set_xlim(1e-16, 1.2)
    ax.legend(fontsize=10, labelspacing=0.2, loc='upper left', bbox_to_anchor=(1.0, 1.0))

    # temperature profile
    axt = ax.twiny()
    axt.set_xlabel('Temperature [K]')
    if self.cfg.plot_height:
        axt_yarr = atm.zmco / 1.0e5
    else:
        axt_yarr = atm.pco / 1.0e6
    axt.plot(atm.Tco, axt_yarr, color='k', lw=0.5, ls='dotted')

    if fpath is None:
        save_fpath = os.path.join(self.cfg.plot_dir, f'_recent.{PLT_FMT}')
        copy_fpath = os.path.join(self.cfg.plot_dir, f'{para.pic_count:05d}.{PLT_FMT}')
    else:
        save_fpath = fpath
        copy_fpath = None

    log.debug(f'Plotting to {save_fpath}')
    fig.savefig(save_fpath, dpi=self.cfg.plot_dpi, bbox_inches='tight')

    if copy_fpath:
        shutil.copyfile(save_fpath, copy_fpath)

    para.pic_count += 1

print_end_msg(var, para)

Source code in src/vulcan/op.py
4656
4657
4658
4659
4660
4661
4662
4663
4664
def print_end_msg(self, var, para):
    log.info('Total atom loss:')
    for atom in self.cfg.atom_list:
        log.info(atom + ': ' + str(var.atom_loss[atom]) + ' ')

    log.debug('negative solution counter: ' + str(para.nega_count))
    log.debug('loss rejected counter: ' + str(para.loss_count))
    log.debug('delta rejected counter: ' + str(para.delta_count))
    log.info('------ Live long and prosper \\V/ ------')

print_prog(var, para)

Source code in src/vulcan/op.py
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
def print_prog(self, var, para):
    indx_max = np.nanargmax(para.where_varies_most)
    log.info(
        'Elapsed time: '
        + '{:.2e}'.format(var.t)
        + ' || Step number: '
        + str(para.count)
        + '/'
        + str(self.cfg.count_max)
    )
    log.info(
        'longdy = '
        + '{:.2e}'.format(var.longdy)
        + '      || longdy/dt = '
        + '{:.2e}'.format(var.longdydt)
        + '  || dt = '
        + '{:.2e}'.format(var.dt)
    )
    log.info('from nz = ' + str(int(indx_max / ni)) + ' and ' + species[indx_max % ni])
    log.info(spacer)

save_out(var, atm, para)

Source code in src/vulcan/op.py
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
def save_out(self, var, atm, para):
    output_dir, out_name = self.cfg.output_dir, self.cfg.out_name
    output_file = output_dir + out_name

    if not os.path.exists(output_dir):
        log.debug('The output directory assigned in vulcan_cfg.py does not exist.')
        log.debug(f'Directory {output_dir} created.')
        os.mkdir(output_dir)

    # convert lists into numpy arrays
    for key in var.var_evol_save:
        as_nparray = np.array(getattr(var, key))
        setattr(var, key, as_nparray)

    # plotting
    if self.cfg.use_plot_evo:
        self.plot_evo(var, atm)
    if self.cfg.use_plot_end:
        self.plot_update(
            var, atm, para, fpath=os.path.join(self.cfg.plot_dir, f'mix.{PLT_FMT}')
        )
    plt.close('all')

    # making the save dict
    var_save = {'species': species, 'nr': nr}

    for key in var.var_save:
        var_save[key] = getattr(var, key)
    if self.cfg.save_evolution:
        # slicing time-sequential data to reduce ouput filesize
        fq = self.cfg.save_evo_frq
        for key in var.var_evol_save:
            as_nparray = getattr(var, key)[::fq]
            setattr(var, key, as_nparray)
            var_save[key] = getattr(var, key)

    if self.cfg.output_humanread:
        # human-readable form, less efficient
        with open(output_file + '.var', 'w') as outfile:
            for var in var_save.keys():
                outfile.write(f'# {var} \n')
                outfile.write(str(var_save[var]) + '\n')

        with open(output_file + '.atm', 'w') as outfile:
            for var in vars(atm).keys():
                outfile.write(f'# {var} \n')
                outfile.write(str(vars(atm)[var]) + '\n')

        with open(output_file + '.par', 'w') as outfile:
            for var in vars(para).keys():
                outfile.write(f'# {var} \n')
                outfile.write(str(vars(para)[var]) + '\n')
    else:
        # pickled form, less safe
        from pickle import dump

        with open(output_file, 'wb') as outfile:
            dump(
                {'variable': var_save, 'atm': vars(atm), 'parameter': vars(para)},
                outfile,
                protocol=4,
            )