Skip to content

vulcan.op

op


Numerical core of VULCAN: rate coefficients, time integration, solver and output.

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

  • ReadRate reads the chemical network and computes the rate coefficients on the T-P profile, and builds the wavelength grid and cross sections for photochemistry.
  • Integration advances the model step by step until steady state or a limit.
  • ODESolver holds the transport terms, the Jacobians, the radiative transfer and the photolysis rates; Ros2 adds the second-order Rosenbrock step.
  • Output prints progress and writes the results.

Units are cgs: number densities in cm-3, time in s, heights in cm, wavelengths in nm. Index 0 of the vertical axis is the bottom layer.

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, the elemental composition table of all species.
  • vulcan.phy_const: Physical constants used in VULCAN.
  • vulcan.chem_funs: the generated chemistry functions (chemdf, the Jacobians, Gibbs) and the network sizes ni and nr.

ReadRate(vulcan_cfg)

Bases: object

Read the chemical network and compute the rate coefficients on the T-P profile.

Each reaction in the network file gets an odd internal number and its reverse the next even number. The methods are called in this order by vulcan.run_vulcan: read_rate, optionally lim_lowT_rates, rev_rate, remove_rate, and with photochemistry make_bins_read_cross and remove_rate again after the first photolysis rates.

vulcan_cfg : Config Run configuration.

Source code in src/vulcan/op.py
123
124
125
126
127
128
129
130
131
132
133
134
135
def __init__(self, vulcan_cfg: Config):
    """
    Parameters
    ----------
    vulcan_cfg : Config
        Run configuration.
    """

    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)

Replace three hydrocarbon rate coefficients with their low-temperature limits.

Used with Config.use_lowT_limit_rates. The limits, from Moses et al. (2005) as noted in the code, apply to H + CH3 + M -> CH4 + M (T <= 277.5 K), H + C2H4 + M -> C2H5 + M (T <= 300 K) and H + C2H5 + M -> C2H6 + M (T <= 200 K).

Parameters:

Name Type Description Default
var Variables

k is updated in place [cm6 s-1 for these reactions].

required
atm AtmData

Reads Tco [K] and M [cm-3].

required

Returns:

Type Description
Variables

var.

Source code in src/vulcan/op.py
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
def lim_lowT_rates(self, var, atm):
    """
    Replace three hydrocarbon rate coefficients with their low-temperature limits.

    Used with `Config.use_lowT_limit_rates`. The limits, from Moses et al. (2005) as noted
    in the code, apply to H + CH3 + M -> CH4 + M (T <= 277.5 K), H + C2H4 + M -> C2H5 + M
    (T <= 300 K) and H + C2H5 + M -> C2H6 + M (T <= 200 K).

    Parameters
    ----------
    var : store.Variables
        `k` is updated in place [cm6 s-1 for these reactions].
    atm : store.AtmData
        Reads `Tco` [K] and `M` [cm-3].

    Returns
    -------
    store.Variables
        `var`.
    """
    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)

Build the wavelength grid and put the cross sections on it.

The grid covers the wavelengths absorbed by the photolysed species, within var.def_bin_min to var.def_bin_max and up to the longest dissociation threshold. The spacing is Config.dbin1 below Config.dbin_12trans and Config.dbin2 above it, if dbin_12trans lies inside the grid; otherwise dbin1 throughout. Cross sections are interpolated linearly, with zero outside the data. For the species in Config.T_cross_sp, they are also interpolated in temperature in each layer.

Parameters:

Name Type Description Default
var Variables

Reads the photolysed species and their branches; sets the grid bins [nm], the cross sections cross* [cm2] and the empty flux arrays.

required
atm AtmData

Reads Tco [K].

required

Raises:

Type Description
RuntimeError

If a cross-section or branching-ratio file is missing, or a species is not in thresholds.txt.

IOError

If a cross-section file starts or ends with a zero.

Source code in src/vulcan/op.py
 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
1028
1029
1030
1031
1032
1033
1034
1035
1036
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
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
def make_bins_read_cross(self, var, atm):
    """
    Build the wavelength grid and put the cross sections on it.

    The grid covers the wavelengths absorbed by the photolysed species, within
    `var.def_bin_min` to `var.def_bin_max` and up to the longest dissociation threshold.
    The spacing is `Config.dbin1` below `Config.dbin_12trans` and `Config.dbin2` above
    it, if `dbin_12trans` lies inside the grid; otherwise `dbin1` throughout. Cross
    sections are interpolated linearly, with zero outside the data. For the species in
    `Config.T_cross_sp`, they are also interpolated in temperature in each layer.

    Parameters
    ----------
    var : store.Variables
        Reads the photolysed species and their branches; sets the grid `bins` [nm], the
        cross sections `cross*` [cm2] and the empty flux arrays.
    atm : store.AtmData
        Reads `Tco` [K].

    Raises
    ------
    RuntimeError
        If a cross-section or branching-ratio file is missing, or a species is not in
        `thresholds.txt`.
    IOError
        If a cross-section file starts or ends with a zero.
    """
    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)

Read the network file Config.network and compute the forward rate coefficients.

The sections are recognised by their header lines. Two-body and radiative reactions use the Arrhenius form k = a T^n exp(-E/T). After # 3-body, reactions with high-pressure parameters use k = k_0 / (1 + k_0 M / k_inf); those after # 3-body reactions without high-pressure rates use k_0 alone. Reactions after # special have hard-coded forms (currently OH + CH3 + M -> CH3OH + M). Condensation, photodissociation and photoionisation rates are set to zero here and computed later by Integration.conden, ODESolver.compute_J and ODESolver.compute_Jion.

Parameters:

Name Type Description Default
var Variables

Updates the rate coefficients k and k_fun, the reaction lists, the photolysis and ionisation indices, and the first reaction number of each section.

required
atm AtmData

Reads Tco [K] and M [cm-3].

required

Returns:

Type Description
Variables

var.

Source code in src/vulcan/op.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
def read_rate(self, var, atm):
    """
    Read the network file `Config.network` and compute the forward rate coefficients.

    The sections are recognised by their header lines. Two-body and radiative reactions use
    the Arrhenius form k = a T^n exp(-E/T). After `# 3-body`, reactions with high-pressure
    parameters use k = k_0 / (1 + k_0 M / k_inf); those after `# 3-body reactions without
    high-pressure rates` use k_0 alone. Reactions after `# special` have hard-coded forms
    (currently OH + CH3 + M -> CH3OH + M). Condensation, photodissociation and
    photoionisation rates are set to zero here and computed later by
    `Integration.conden`, `ODESolver.compute_J` and `ODESolver.compute_Jion`.

    Parameters
    ----------
    var : store.Variables
        Updates the rate coefficients `k` and `k_fun`, the reaction lists, the photolysis
        and ionisation indices, and the first reaction number of each section.
    atm : store.AtmData
        Reads `Tco` [K] and `M` [cm-3].

    Returns
    -------
    store.Variables
        `var`.
    """

    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)

Set the rate coefficients of the reactions in Config.remove_list to zero.

Parameters:

Name Type Description Default
var Variables

k and k_fun are updated in place.

required

Returns:

Type Description
Variables

var.

Source code in src/vulcan/op.py
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
def remove_rate(self, var):
    """
    Set the rate coefficients of the reactions in `Config.remove_list` to zero.

    Parameters
    ----------
    var : store.Variables
        `k` and `k_fun` are updated in place.

    Returns
    -------
    store.Variables
        `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)

Compute the reverse rate coefficients from the equilibrium constants.

For every reaction before the # reverse stops header, k_rev = k_fwd / K_eq with K_eq from the Gibbs free energies (chem_funs.Gibbs); k_fun gets the same relation. The reverse coefficients of the later reactions, and of reverse reactions listed in Config.remove_list, are zero.

Parameters:

Name Type Description Default
var Variables

Reads and updates k and k_fun.

required
atm AtmData

Reads Tco [K].

required

Returns:

Type Description
Variables

var.

Source code in src/vulcan/op.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
def rev_rate(self, var, atm):
    """
    Compute the reverse rate coefficients from the equilibrium constants.

    For every reaction before the `# reverse stops` header, k_rev = k_fwd / K_eq with K_eq
    from the Gibbs free energies (`chem_funs.Gibbs`); `k_fun` gets the same relation. The
    reverse coefficients of the later reactions, and of reverse reactions listed in
    `Config.remove_list`, are zero.

    Parameters
    ----------
    var : store.Variables
        Reads and updates `k` and `k_fun`.
    atm : store.AtmData
        Reads `Tco` [K].

    Returns
    -------
    store.Variables
        `var`.
    """

    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

Advance the model in time until it reaches steady state or a limit.

Each step updates the photolysis rates when due, takes one solver step, updates the condensation rates, the height grid and the escape fluxes, restores hydrostatic balance, adapts the step size, calls the climate hook every Config.agni_call_frq steps (update_climate), and checks convergence (stop).

odesolver : Ros2 The solver that takes the steps. output : Output Used for the progress messages. vulcan_cfg : Config Run configuration.

Raises:

Type Description
RuntimeError

If Config.use_vm_mol is set; that scheme is in development.

Source code in src/vulcan/op.py
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
def __init__(self, odesolver, output, vulcan_cfg: Config):
    """
    Parameters
    ----------
    odesolver : Ros2
        The solver that takes the steps.
    output : Output
        Used for the progress messages.
    vulcan_cfg : Config
        Run configuration.

    Raises
    ------
    RuntimeError
        If `Config.use_vm_mol` is set; that scheme is in development.
    """

    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`'
        )

    # climate hook and atmosphere builder, set by __call__
    self.climate = None
    self.make_atm = None

    # 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

climate = None instance-attribute

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

make_atm = None 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

update_photo_frq = self.cfg.ini_update_photo_frq instance-attribute

use_settling = self.cfg.use_settling instance-attribute

backup(var)

Store y, dy and atom_loss as the previous-step values, so a step can be undone.

Parameters:

Name Type Description Default
var Variables

Sets y_prev [cm-3], dy_prev and atom_loss_prev.

required

Returns:

Type Description
Variables

var.

Source code in src/vulcan/op.py
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
def backup(self, var):
    """
    Store `y`, `dy` and `atom_loss` as the previous-step values, so a step can be undone.

    Parameters
    ----------
    var : store.Variables
        Sets `y_prev` [cm-3], `dy_prev` and `atom_loss_prev`.

    Returns
    -------
    store.Variables
        `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)

Update the rate coefficients of the condensation reactions.

For a reaction 'X -> X_condensate' the rate is D m / (rho_p r_p^2) (n_X - n_sat), the growth rate of a particle in the continuum regime, with D the molecular diffusion coefficient of X, m its molecular mass, and rho_p and r_p the particle density and radius. The positive part is the condensation coefficient and the magnitude of the negative part the evaporation coefficient of the reverse reaction [s-1]. Handles H2O (with Config.humidity), NH3, H2SO4, S2, S4, S8 and C. The H2O and NH3 rates are set to zero whenever Config.use_relax is non-empty, whichever species it lists.

Parameters:

Name Type Description Default
var Variables

Reads y [cm-3]; updates k for the reactions in conden_re_list.

required
atm AtmData

Reads sat_p [dyn cm-2], Tco [K], Dzz [cm2 s-1], r_p [cm] and rho_p [g cm-3].

required

Returns:

Type Description
Variables

var.

Source code in src/vulcan/op.py
1845
1846
1847
1848
1849
1850
1851
1852
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
1958
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
def conden(self, var, atm):
    """
    Update the rate coefficients of the condensation reactions.

    For a reaction 'X -> X_condensate' the rate is D m / (rho_p r_p^2) (n_X - n_sat), the
    growth rate of a particle in the continuum regime, with D the molecular diffusion
    coefficient of X, m its molecular mass, and rho_p and r_p the particle density and
    radius. The positive part is the condensation coefficient and the magnitude of the
    negative part the evaporation coefficient of the reverse reaction [s-1]. Handles
    H2O (with `Config.humidity`), NH3, H2SO4, S2, S4, S8 and C. The H2O and NH3 rates are
    set to zero whenever `Config.use_relax` is non-empty, whichever species it lists.

    Parameters
    ----------
    var : store.Variables
        Reads `y` [cm-3]; updates `k` for the reactions in `conden_re_list`.
    atm : store.AtmData
        Reads `sat_p` [dyn cm-2], `Tco` [K], `Dzz` [cm2 s-1], `r_p` [cm] and
        `rho_p` [g cm-3].

    Returns
    -------
    store.Variables
        `var`.
    """

    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)

Check whether the model has reached steady state.

longdy is the largest relative change of the mixing ratios since the step at about Config.st_factor times the current time, and longdydt that change per second. Trace species (below mtol_conv or atol), conver_ignore and condensates are left out. Converged means longdy < yconv_cri and longdydt < slope_cri, or longdy < yconv_min and longdydt below a mixing rate Kzz / (0.1 H_p)^2; in both cases the actinic flux change must be below flux_cri. Steps before the latest climate update are not compared.

Parameters:

Name Type Description Default
var Variables

Reads y, ymix, y_time, t_time and aflux_change; sets longdy and longdydt [s-1].

required
para Parameters

Reads count, climate_dT and climate_count; sets where_varies_most.

required
atm AtmData

Reads n_0 [cm-3], Kzz [cm2 s-1] and Hp [cm].

required
out

Not used.

False
print_freq

Not used.

False

Returns:

Type Description
bool

True when converged.

Source code in src/vulcan/op.py
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
1696
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
def conv(self, var, para, atm, out=False, print_freq=100):
    """
    Check whether the model has reached steady state.

    `longdy` is the largest relative change of the mixing ratios since the step at about
    `Config.st_factor` times the current time, and `longdydt` that change per second.
    Trace species (below `mtol_conv` or `atol`), `conver_ignore` and condensates are
    left out. Converged means `longdy < yconv_cri` and `longdydt < slope_cri`, or
    `longdy < yconv_min` and `longdydt` below a mixing rate Kzz / (0.1 H_p)^2; in both
    cases the actinic flux change must be below `flux_cri`. Steps before the latest
    climate update are not compared.

    Parameters
    ----------
    var : store.Variables
        Reads `y`, `ymix`, `y_time`, `t_time` and `aflux_change`; sets `longdy` and
        `longdydt` [s-1].
    para : store.Parameters
        Reads `count`, `climate_dT` and `climate_count`; sets `where_varies_most`.
    atm : store.AtmData
        Reads `n_0` [cm-3], `Kzz` [cm2 s-1] and `Hp` [cm].
    out, print_freq
        Not used.

    Returns
    -------
    bool
        True when converged.
    """
    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)

    # Nor before the latest climate update, whose new densities are no chemical change
    if para.climate_dT:
        indx = max(para.climate_count, indx)
        if indx >= count - 1 or t_time[-1] <= t_time[indx]:
            return False

    # 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)

Set the largest relative change of y over the last step.

Species with mixing ratio below Config.mtol or number density below Config.atol are ignored. On the first step both values are 1.

Parameters:

Name Type Description Default
var Variables

Reads y, y_prev and ymix; sets dy [dimensionless] and dydt [s-1].

required
para Parameters

Reads count.

required

Returns:

Type Description
Variables

var.

Source code in src/vulcan/op.py
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
def f_dy(self, var, para):
    """
    Set the largest relative change of y over the last step.

    Species with mixing ratio below `Config.mtol` or number density below `Config.atol`
    are ignored. On the first step both values are 1.

    Parameters
    ----------
    var : store.Variables
        Reads `y`, `y_prev` and `ymix`; sets `dy` [dimensionless] and `dydt` [s-1].
    para : store.Parameters
        Reads `count`.

    Returns
    -------
    store.Variables
        `var`.
    """
    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)

Relax H2O towards saturation by condensation and evaporation.

Where H2O is supersaturated, an implicit Euler step with the timescale 1 / (D m / (rho_p r_p^2) (n - n_sat)) moves the excess to H2O_l_s; where it is undersaturated, H2O_l_s evaporates at the same rate, limited to the amount present. Used when 'H2O' is in Config.use_relax.

Parameters:

Name Type Description Default
var Variables

Updates ymix and y [cm-3].

required
atm AtmData

Reads sat_p [dyn cm-2], Tco [K], n_0 [cm-3], Dzz [cm2 s-1], r_p [cm] and rho_p [g cm-3].

required

Returns:

Type Description
Variables

var.

Source code in src/vulcan/op.py
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
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
def h2o_conden_evap_relax(self, var, atm):
    """
    Relax H2O towards saturation by condensation and evaporation.

    Where H2O is supersaturated, an implicit Euler step with the timescale
    1 / (D m / (rho_p r_p^2) (n - n_sat)) moves the excess to H2O_l_s; where it is
    undersaturated, H2O_l_s evaporates at the same rate, limited to the amount present.
    Used when 'H2O' is in `Config.use_relax`.

    Parameters
    ----------
    var : store.Variables
        Updates `ymix` and `y` [cm-3].
    atm : store.AtmData
        Reads `sat_p` [dyn cm-2], `Tco` [K], `n_0` [cm-3], `Dzz` [cm2 s-1], `r_p` [cm] and
        `rho_p` [g cm-3].

    Returns
    -------
    store.Variables
        `var`.
    """
    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)

Relax supersaturated H2O towards saturation and move the excess to H2O_l_s.

Not called by the current code; h2o_conden_evap_relax is used instead.

An implicit Euler step with the timescale 1 / |D m / (rho_p r_p^2) (n - n_sat)|, with a fixed particle density of 0.95 g cm-3.

Parameters:

Name Type Description Default
var Variables

Updates ymix and y [cm-3].

required
atm AtmData

Reads sat_p [dyn cm-2], Tco [K], n_0 [cm-3], Dzz [cm2 s-1] and r_p [cm].

required

Returns:

Type Description
Variables

var.

Source code in src/vulcan/op.py
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
def h2o_conden_relax(self, var, atm):
    """
    Relax supersaturated H2O towards saturation and move the excess to H2O_l_s.

    Not called by the current code; `h2o_conden_evap_relax` is used instead.

    An implicit Euler step with the timescale 1 / |D m / (rho_p r_p^2) (n - n_sat)|, with
    a fixed particle density of 0.95 g cm-3.

    Parameters
    ----------
    var : store.Variables
        Updates `ymix` and `y` [cm-3].
    atm : store.AtmData
        Reads `sat_p` [dyn cm-2], `Tco` [K], `n_0` [cm-3], `Dzz` [cm2 s-1] and `r_p` [cm].

    Returns
    -------
    store.Variables
        `var`.
    """
    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)

Relax NH3 towards saturation by condensation and evaporation.

As h2o_conden_evap_relax, for NH3 and NH3_l_s, with no condensation above the level of the lowest saturation mixing ratio (the cold trap). Used when 'NH3' is in Config.use_relax.

Parameters:

Name Type Description Default
var Variables

Updates ymix and y [cm-3].

required
atm AtmData

Reads sat_p [dyn cm-2], Tco [K], n_0 [cm-3], Dzz [cm2 s-1], r_p [cm] and rho_p [g cm-3].

required

Returns:

Type Description
Variables

var.

Source code in src/vulcan/op.py
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
def nh3_conden_evap_relax(self, var, atm):
    """
    Relax NH3 towards saturation by condensation and evaporation.

    As `h2o_conden_evap_relax`, for NH3 and NH3_l_s, with no condensation above the level of
    the lowest saturation mixing ratio (the cold trap). Used when 'NH3' is in
    `Config.use_relax`.

    Parameters
    ----------
    var : store.Variables
        Updates `ymix` and `y` [cm-3].
    atm : store.AtmData
        Reads `sat_p` [dyn cm-2], `Tco` [K], `n_0` [cm-3], `Dzz` [cm2 s-1], `r_p` [cm] and
        `rho_p` [g cm-3].

    Returns
    -------
    store.Variables
        `var`.
    """
    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)

Advance the time by dt, count the step, and append to the time series.

Parameters:

Name Type Description Default
var Variables

Updates t [s] and appends to y_time, t_time and atom_loss_time.

required
para Parameters

Increments count.

required

Returns:

Type Description
tuple

(var, para).

Source code in src/vulcan/op.py
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
def save_step(self, var, para):
    """
    Advance the time by `dt`, count the step, and append to the time series.

    Parameters
    ----------
    var : store.Variables
        Updates `t` [s] and appends to `y_time`, `t_time` and `atom_loss_time`.
    para : store.Parameters
        Increments `count`.

    Returns
    -------
    tuple
        `(var, para)`.
    """
    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)

Decide whether to stop the integration and record why in para.end_case.

Stops when converged (conv, after Config.trun_min and Config.count_min), when the time exceeds Config.runtime [s], or when the step count exceeds Config.count_max. After a climate update, count_min steps must pass again before convergence is tested. With a climate hook, convergence also needs a settled climate (_climate_settled).

Parameters:

Name Type Description Default
var Variables

Reads t [s].

required
para Parameters

Reads count, climate_dT and climate_count; sets end_case.

required
atm AtmData

Passed to conv.

required

Returns:

Type Description
bool or None

True to stop; False or None to continue.

Source code in src/vulcan/op.py
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
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
def stop(self, var, para, atm):
    """
    Decide whether to stop the integration and record why in `para.end_case`.

    Stops when converged (`conv`, after `Config.trun_min` and `Config.count_min`), when the
    time exceeds `Config.runtime` [s], or when the step count exceeds `Config.count_max`.
    After a climate update, `count_min` steps must pass again before convergence is
    tested. With a climate hook, convergence also needs a settled climate
    (`_climate_settled`).

    Parameters
    ----------
    var : store.Variables
        Reads `t` [s].
    para : store.Parameters
        Reads `count`, `climate_dT` and `climate_count`; sets `end_case`.
    atm : store.AtmData
        Passed to `conv`.

    Returns
    -------
    bool or None
        True to stop; False or None to continue.
    """
    if (
        var.t > self.cfg.trun_min
        and para.count > self.cfg.count_min
        and (not para.climate_dT or para.count - para.climate_count > self.cfg.count_min)
        and self.conv(var, para, atm)
    ):
        if self.climate is not None and not self._climate_settled(var, atm, para):
            return para.end_case == 4
        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_climate(climate, var, atm, para, make_atm)

Call the climate hook and recompute every quantity that depends on temperature.

The new temperature (and, with Config.Kzz_prof = 'climate' and use_Kzz, the new Kzz) replaces VULCAN's on its own grid. The mixing ratios are kept, so the number densities follow the new temperature at fixed pressure. Every temperature-dependent quantity is then recomputed as at the start of a run. A change larger than agni_T_rtol also restarts the step size from dttry and the steady-state test in conv; a smaller one does not, so a settled climate does not delay convergence.

Parameters:

Name Type Description Default
climate callable

Climate hook, called as climate(pco, Tco, species, ymix) with copies of the present state; returns a vulcan.climate.ClimateUpdate.

required
var Variables

Reads ymix; updates y [cm-3], the rate coefficients and the atom budgets, and dt [s] after a large change.

required
atm AtmData

Updates Tco [K], Kzz [cm2 s-1] and every quantity derived from them.

required
para Parameters

Appends to climate_dT; sets climate_count after a large change.

required
make_atm Atm

Recomputes molecular diffusion, saturation pressures and settling velocities.

required

Returns:

Type Description
float

Largest relative temperature change over the layers, max |dT| / T [dimensionless].

Source code in src/vulcan/op.py
1393
1394
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
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
def update_climate(self, climate, var, atm, para, make_atm) -> float:
    """
    Call the climate hook and recompute every quantity that depends on temperature.

    The new temperature (and, with `Config.Kzz_prof = 'climate'` and `use_Kzz`, the new
    Kzz) replaces VULCAN's on its own grid. The mixing ratios are kept, so the number
    densities follow the new temperature at fixed pressure. Every temperature-dependent
    quantity is then recomputed as at the start of a run. A change larger than
    `agni_T_rtol` also restarts the step size from `dttry` and the steady-state test in
    `conv`; a smaller one does not, so a settled climate does not delay convergence.

    Parameters
    ----------
    climate : callable
        Climate hook, called as `climate(pco, Tco, species, ymix)` with copies of the
        present state; returns a `vulcan.climate.ClimateUpdate`.
    var : store.Variables
        Reads `ymix`; updates `y` [cm-3], the rate coefficients and the atom budgets, and
        `dt` [s] after a large change.
    atm : store.AtmData
        Updates `Tco` [K], `Kzz` [cm2 s-1] and every quantity derived from them.
    para : store.Parameters
        Appends to `climate_dT`; sets `climate_count` after a large change.
    make_atm : build_atm.Atm
        Recomputes molecular diffusion, saturation pressures and settling velocities.

    Returns
    -------
    float
        Largest relative temperature change over the layers, max |dT| / T
        [dimensionless].
    """
    update = climate(atm.pco.copy(), atm.Tco.copy(), list(species), var.ymix.copy())
    t_new = regrid_temperature(update, atm.pco)
    kzz_new = None
    if self.cfg.Kzz_prof == 'climate' and self.cfg.use_Kzz:
        kzz_new = regrid_kzz(update, atm.pico[1:-1])
    d_tmp = max_relative_change(atm.Tco, t_new)
    atm.Tco = t_new
    if kzz_new is not None:
        atm.Kzz = kzz_new

    self._refresh_densities(var, atm)
    self._refresh_rates(var, atm)
    self._refresh_transport(var, atm, make_atm)
    if self.cfg.use_photo:
        self.odesolver.compute_tau(var, atm)
        self.odesolver.compute_flux(var, atm)
        self.odesolver.compute_J(var, atm)
        if self.cfg.use_ion:
            self.odesolver.compute_Jion(var, atm)
        ReadRate(self.cfg).remove_rate(var)

    # a real change starts a fast transient that the large steady-state step overshoots
    if d_tmp > self.cfg.agni_T_rtol:
        var.dt = self.cfg.dttry
        para.climate_count = para.count
    para.climate_dT.append(d_tmp)
    log.info(
        'Climate update %d at step %d: max |dT|/T = %.3e, T from %.1f to %.1f K'
        % (len(para.climate_dT), para.count, d_tmp, np.min(atm.Tco), np.max(atm.Tco))
    )
    return d_tmp

update_mu_dz(var, atm, make_atm)

Update the mean molar mass, gravity, scale height and the height grid.

Repeats the hydrostatic integration of build_atm.Atm.f_mu_dz for the current composition, keeping the reference level atm.pref_indx; called every Config.update_frq steps and after each climate update.

Parameters:

Name Type Description Default
var Variables

Reads ymix.

required
atm AtmData

Updates mu [g mol-1], g [cm s-2], Hp, dz, dzi, zco, zmco [cm], and with use_moldiff Ti [K] and Hpi [cm].

required
make_atm Atm

Provides mean_mass.

required

Returns:

Type Description
AtmData

atm.

Source code in src/vulcan/op.py
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
def update_mu_dz(self, var, atm, make_atm):
    """
    Update the mean molar mass, gravity, scale height and the height grid.

    Repeats the hydrostatic integration of `build_atm.Atm.f_mu_dz` for the current
    composition, keeping the reference level `atm.pref_indx`; called every
    `Config.update_frq` steps and after each climate update.

    Parameters
    ----------
    var : store.Variables
        Reads `ymix`.
    atm : store.AtmData
        Updates `mu` [g mol-1], `g` [cm s-2], `Hp`, `dz`, `dzi`, `zco`, `zmco` [cm], and
        with `use_moldiff` `Ti` [K] and `Hpi` [cm].
    make_atm : build_atm.Atm
        Provides `mean_mass`.

    Returns
    -------
    store.AtmData
        `atm`.
    """

    # 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)

Set the diffusion-limited escape flux at the top for the species in Config.diff_esc.

phi = -D n (1/H - 1/H_i) in the top layer, with H the pressure scale height and H_i = N_A k_B T / (m g) that of the species with molar mass m. Escape is limited to Config.max_flux: the flux is not allowed below -max_flux, and a positive (inflowing) value is not limited.

Parameters:

Name Type Description Default
var Variables

Reads y [cm-3].

required
atm AtmData

Updates top_flux [cm-2 s-1]; negative is escape.

required

Returns:

Type Description
AtmData

atm.

Source code in src/vulcan/op.py
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
def update_phi_esc(self, var, atm):
    """
    Set the diffusion-limited escape flux at the top for the species in `Config.diff_esc`.

    phi = -D n (1/H - 1/H_i) in the top layer, with H the pressure scale height and
    H_i = N_A k_B T / (m g) that of the species with molar mass m. Escape is limited to
    `Config.max_flux`: the flux is not allowed below -max_flux, and a positive (inflowing)
    value is not limited.

    Parameters
    ----------
    var : store.Variables
        Reads `y` [cm-3].
    atm : store.AtmData
        Updates `top_flux` [cm-2 s-1]; negative is escape.

    Returns
    -------
    store.AtmData
        `atm`.
    """

    # 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

Terms of the continuity equation dn/dt = P - L - dphi/dz and their Jacobians.

Also holds the step acceptance tests, the radiative transfer and the photolysis rates. The lhs_jac_* methods return the matrix 1/(r h) I - J of the Rosenbrock step for the state flattened layer by layer (index j * ni + i), shape (nz ni, nz ni), with r = 1 + 1/sqrt(2) and h the time step [s] (except the *_fix_all_bot variants, whose bottom-layer columns are zero). Transport uses zero-flux boundaries except for the fluxes set with use_topflux and use_botflux.

vulcan_cfg : Config Run configuration; the species fixed at the bottom by use_fix_sp_bot are indexed here.

Source code in src/vulcan/op.py
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
def __init__(self, vulcan_cfg: Config):
    """
    Parameters
    ----------
    vulcan_cfg : Config
        Run configuration; the species fixed at the bottom by `use_fix_sp_bot` are indexed
        here.
    """

    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)

Set small and slightly negative densities to zero and update the element totals.

Values in [nega_cut, pos_cut) become zero, as do negative values with mixing ratio below Config.mtol. Then calls loss and recomputes ymix.

Parameters:

Name Type Description Default
var Variables

Updates y [cm-3], ymix, atom_sum and atom_loss.

required
para Parameters

Adds the clipped amounts to small_y and nega_y [cm-3].

required
atm AtmData

Reads gas_indx.

required
pos_cut float

Upper limit of the values set to zero [cm-3].

0
nega_cut float

Lower limit of the values set to zero [cm-3].

-1

Returns:

Type Description
tuple

(var, para).

Source code in src/vulcan/op.py
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
def clip(self, var, para, atm, pos_cut=0, nega_cut=-1):
    """
    Set small and slightly negative densities to zero and update the element totals.

    Values in [nega_cut, pos_cut) become zero, as do negative values with mixing ratio below
    `Config.mtol`. Then calls `loss` and recomputes `ymix`.

    Parameters
    ----------
    var : store.Variables
        Updates `y` [cm-3], `ymix`, `atom_sum` and `atom_loss`.
    para : store.Parameters
        Adds the clipped amounts to `small_y` and `nega_y` [cm-3].
    atm : store.AtmData
        Reads `gas_indx`.
    pos_cut : float
        Upper limit of the values set to zero [cm-3].
    nega_cut : float
        Lower limit of the values set to zero [cm-3].

    Returns
    -------
    tuple
        `(var, para)`.
    """
    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)

Compute the photodissociation rates and put them into the rate coefficients.

J is the integral over wavelength of the actinic flux times the cross section of each branch. Times Config.f_diurnal, it becomes the rate coefficient of the reaction, unless the reaction is in Config.remove_list.

Parameters:

Name Type Description Default
var Variables

Reads aflux [photons cm-2 s-1 nm-1] and the cross sections [cm2]. Sets J_sp[(sp, branch)], shape (nz,) [s-1], with branch 0 the sum over branches, and updates k.

required
atm AtmData

Not used.

required
Source code in src/vulcan/op.py
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
def compute_J(self, var, atm):
    """
    Compute the photodissociation rates and put them into the rate coefficients.

    J is the integral over wavelength of the actinic flux times the cross section of each
    branch. Times `Config.f_diurnal`, it becomes the rate coefficient of the reaction,
    unless the reaction is in `Config.remove_list`.

    Parameters
    ----------
    var : store.Variables
        Reads `aflux` [photons cm-2 s-1 nm-1] and the cross sections [cm2]. Sets
        `J_sp[(sp, branch)]`, shape (nz,) [s-1], with branch 0 the sum over branches,
        and updates `k`.
    atm : store.AtmData
        Not used.
    """
    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 photoionisation rates and put them into the rate coefficients.

As compute_J, with cross_Jion and no temperature dependence.

Parameters:

Name Type Description Default
var Variables

Reads aflux [photons cm-2 s-1 nm-1] and cross_Jion [cm2]. Sets Jion_sp[(sp, branch)], shape (nz,) [s-1], and updates k.

required
atm AtmData

Not used.

required
Source code in src/vulcan/op.py
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
def compute_Jion(self, var, atm):
    """
    Compute the photoionisation rates and put them into the rate coefficients.

    As `compute_J`, with `cross_Jion` and no temperature dependence.

    Parameters
    ----------
    var : store.Variables
        Reads `aflux` [photons cm-2 s-1 nm-1] and `cross_Jion` [cm2]. Sets
        `Jion_sp[(sp, branch)]`, shape (nz,) [s-1], and updates `k`.
    atm : store.AtmData
        Not used.
    """
    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)

Compute the direct and diffuse stellar flux and the actinic flux in each layer.

The direct beam follows Beer's law along the zenith angle Config.sl_angle; the diffuse flux comes from a two-stream solution with isotropic Rayleigh scattering and no upward diffuse flux at the bottom.

Parameters:

Name Type Description Default
var Variables

Reads tau, sflux_top [erg cm-2 s-1 nm-1] and the cross sections [cm2]. Sets the direct and diffuse fluxes sflux, dflux_u and dflux_d at the interfaces [erg cm-2 s-1 nm-1], the actinic flux aflux at the layer centres [photons cm-2 s-1 nm-1], and its relative change aflux_change.

required
atm AtmData

Not used.

required
Source code in src/vulcan/op.py
4831
4832
4833
4834
4835
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
4868
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
4903
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
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
def compute_flux(self, var, atm):
    """
    Compute the direct and diffuse stellar flux and the actinic flux in each layer.

    The direct beam follows Beer's law along the zenith angle `Config.sl_angle`; the
    diffuse flux comes from a two-stream solution with isotropic Rayleigh scattering and
    no upward diffuse flux at the bottom.

    Parameters
    ----------
    var : store.Variables
        Reads `tau`, `sflux_top` [erg cm-2 s-1 nm-1] and the cross sections [cm2]. Sets
        the direct and diffuse fluxes `sflux`, `dflux_u` and `dflux_d` at the interfaces
        [erg cm-2 s-1 nm-1], the actinic flux `aflux` at the layer centres
        [photons cm-2 s-1 nm-1], and its relative change `aflux_change`.
    atm : store.AtmData
        Not used.
    """
    # 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 vertical optical depth at the interfaces.

tau[j] sums n sigma dz over the layers from j to the top, for absorption by the photodissociating and photoionising species (temperature-dependent cross sections where available) and Rayleigh scattering by Config.scat_sp; tau is zero at the top.

Parameters:

Name Type Description Default
var Variables

Reads y [cm-3] and the cross sections [cm2]; sets tau, shape (nz + 1, nbin) [dimensionless].

required
atm AtmData

Reads dz [cm].

required
Source code in src/vulcan/op.py
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
def compute_tau(self, var, atm):
    """
    Compute the vertical optical depth at the interfaces.

    tau[j] sums n sigma dz over the layers from j to the top, for absorption by the
    photodissociating and photoionising species (temperature-dependent cross sections where
    available) and Rayleigh scattering by `Config.scat_sp`; tau is zero at the top.

    Parameters
    ----------
    var : store.Variables
        Reads `y` [cm-3] and the cross sections [cm2]; sets `tau`, shape (nz + 1, nbin)
        [dimensionless].
    atm : store.AtmData
        Reads `dz` [cm].
    """

    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)

Transport tendency from eddy diffusion, advection and molecular diffusion.

As diffdf_no_mol, plus the molecular flux phi_i = -D_i [n d(n_i/n)/dz + n_i (m_i g / (N_A k_B T) - 1/H_p + alpha_i / T dT/dz)], with m_i the molar mass and alpha_i the thermal diffusion factor, evaluated on the interfaces.

Parameters:

Name Type Description Default
y ndarray

Number densities, shape (nz, ni) [cm-3].

required
atm AtmData

Atmospheric structure.

required

Returns:

Type Description
ndarray

Transport tendency -dphi/dz, shape (nz, ni) [cm-3 s-1].

Source code in src/vulcan/op.py
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
2619
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
def diffdf(self, y, atm):
    """
    Transport tendency from eddy diffusion, advection and molecular diffusion.

    As `diffdf_no_mol`, plus the molecular flux
    phi_i = -D_i [n d(n_i/n)/dz + n_i (m_i g / (N_A k_B T) - 1/H_p + alpha_i / T dT/dz)],
    with m_i the molar mass and alpha_i the thermal diffusion factor, evaluated on the
    interfaces.

    Parameters
    ----------
    y : np.ndarray
        Number densities, shape (nz, ni) [cm-3].
    atm : store.AtmData
        Atmospheric structure.

    Returns
    -------
    np.ndarray
        Transport tendency -dphi/dz, shape (nz, ni) [cm-3 s-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]
    )

    # interior layers j = 1..nz-2 at once; suffix _m: j-1, _p: j+1
    j, j_m, j_p = slice(1, nz - 1), slice(0, nz - 2), slice(2, nz)
    dz_ave = 0.5 * (dzi[j_m] + dzi[j])
    A[j] = (
        -1.0
        / dz_ave
        * (
            Kzz[j] / dzi[j] * (ysum[j_p] + ysum[j]) / 2.0
            + Kzz[j_m] / dzi[j_m] * (ysum[j] + ysum[j_m]) / 2.0
        )
        / ysum[j]
    )
    B[j] = 1.0 / dz_ave * Kzz[j] / dzi[j] * (ysum[j_p] + ysum[j]) / 2.0 / ysum[j_p]
    C[j] = 1.0 / dz_ave * Kzz[j_m] / dzi[j_m] * (ysum[j] + ysum[j_m]) / 2.0 / ysum[j_m]

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

    # per-layer quantities as columns, broadcasting over species
    dz_c, dzi_c, ysum_c = dz_ave[:, None], dzi[:, None], ysum[:, None]
    Hpi_c, Ti_c, g_c, Tco_c = Hpi[:, None], Ti[:, None], g[:, None], Tco[:, None]

    # Ai in the shape of nz*ni and Ai[j] in the shape of (nz-2)*ni
    Ai[j] = (
        -1.0
        / dz_c
        * (
            Dzz[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / 2.0
            + Dzz[j_m] / dzi_c[j_m] * (ysum_c[j] + ysum_c[j_m]) / 2.0
        )
        / ysum_c[j]
    )
    Bi[j] = 1.0 / dz_c * Dzz[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / 2.0 / ysum_c[j_p]
    Ci[j] = (
        1.0 / dz_c * Dzz[j_m] / dzi_c[j_m] * (ysum_c[j] + ysum_c[j_m]) / 2.0 / ysum_c[j_m]
    )

    Ai[j] += (
        1.0
        / (2.0 * dz_c)
        * (
            Dzz[j]
            * (
                -1.0 / Hpi_c[j]
                + ms * g_c[j] / (Navo * kb * Ti_c[j])
                + alpha / Ti_c[j] * (Tco_c[j_p] - Tco_c[j]) / dzi_c[j]
            )
            - Dzz[j_m]
            * (
                -1.0 / Hpi_c[j_m]
                + ms * g_c[j] / (Navo * kb * Ti_c[j_m])
                + alpha / Ti_c[j_m] * (Tco_c[j] - Tco_c[j_m]) / dzi_c[j_m]
            )
        )
    )  # /ysum[j]
    Bi[j] += (
        1.0
        / (2.0 * dz_c)
        * Dzz[j]
        * (
            -1.0 / Hpi_c[j]
            + ms * g_c[j_p] / (Navo * kb * Ti_c[j])
            + alpha / Ti_c[j] * (Tco_c[j_p] - Tco_c[j]) / dzi_c[j]
        )
    )
    Ci[j] += (
        -1.0
        / (2.0 * dz_c)
        * Dzz[j_m]
        * (
            -1.0 / Hpi_c[j_m]
            + ms * g_c[j_m] / (Navo * kb * Ti_c[j_m])
            + alpha / Ti_c[j_m] * (Tco_c[j] - Tco_c[j_m]) / dzi_c[j_m]
        )
    )

    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)

Transport tendency from eddy diffusion and advection, without molecular diffusion.

The eddy flux is phi = -K_zz n d(n_i/n)/dz, with n the total gas density, on the non-uniform grid dzi; advection by vz is upwind. With use_topflux and use_botflux the prescribed fluxes and the deposition loss bot_vdep y[0] are added.

Parameters:

Name Type Description Default
y ndarray

Number densities, shape (nz, ni) [cm-3].

required
atm AtmData

Atmospheric structure.

required

Returns:

Type Description
ndarray

Transport tendency -dphi/dz, shape (nz, ni) [cm-3 s-1].

Source code in src/vulcan/op.py
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
2431
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
def diffdf_no_mol(self, y, atm):
    """
    Transport tendency from eddy diffusion and advection, without molecular diffusion.

    The eddy flux is phi = -K_zz n d(n_i/n)/dz, with n the total gas density, on the
    non-uniform grid `dzi`; advection by `vz` is upwind. With `use_topflux` and
    `use_botflux` the prescribed fluxes and the deposition loss `bot_vdep y[0]` are added.

    Parameters
    ----------
    y : np.ndarray
        Number densities, shape (nz, ni) [cm-3].
    atm : store.AtmData
        Atmospheric structure.

    Returns
    -------
    np.ndarray
        Transport tendency -dphi/dz, shape (nz, ni) [cm-3 s-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

    # interior layers j = 1..nz-2 at once; suffix _m: j-1, _p: j+1
    j, j_m, j_p = slice(1, nz - 1), slice(0, nz - 2), slice(2, nz)
    dz_ave = 0.5 * (dzi[j_m] + dzi[j])
    A[j] = (
        -2.0
        / (dzi[j_m] + dzi[j])
        * (
            Kzz[j] / dzi[j] * (ysum[j_p] + ysum[j]) / 2.0
            + Kzz[j_m] / dzi[j_m] * (ysum[j] + ysum[j_m]) / 2.0
        )
        / ysum[j]
    )
    B[j] = (
        2.0
        / (dzi[j_m] + dzi[j])
        * Kzz[j]
        / dzi[j]
        * (ysum[j_p] + ysum[j])
        / 2.0
        / ysum[j_p]
    )
    C[j] = (
        2.0
        / (dzi[j_m] + dzi[j])
        * Kzz[j_m]
        / dzi[j_m]
        * (ysum[j] + ysum[j_m])
        / 2.0
        / ysum[j_m]
    )

    # vertical adection
    A[j] += -((vz[j] > 0) * vz[j] - (vz[j_m] < 0) * vz[j_m]) / dz_ave
    B[j] += -((vz[j] < 0) * vz[j]) / dz_ave
    C[j] += ((vz[j_m] > 0) * vz[j_m]) / 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)

Transport tendency as diffdf, plus gravitational settling of particles.

The non-gaseous species are advected with the settling velocity atm.vs (upwind).

Parameters:

Name Type Description Default
y ndarray

Number densities, shape (nz, ni) [cm-3].

required
atm AtmData

Atmospheric structure.

required

Returns:

Type Description
ndarray

Transport tendency -dphi/dz, shape (nz, ni) [cm-3 s-1].

Source code in src/vulcan/op.py
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
2778
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
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
def diffdf_settling(self, y, atm):
    """
    Transport tendency as `diffdf`, plus gravitational settling of particles.

    The non-gaseous species are advected with the settling velocity `atm.vs` (upwind).

    Parameters
    ----------
    y : np.ndarray
        Number densities, shape (nz, ni) [cm-3].
    atm : store.AtmData
        Atmospheric structure.

    Returns
    -------
    np.ndarray
        Transport tendency -dphi/dz, shape (nz, ni) [cm-3 s-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]
    )

    # interior layers j = 1..nz-2 at once; suffix _m: j-1, _p: j+1
    j, j_m, j_p = slice(1, nz - 1), slice(0, nz - 2), slice(2, nz)
    dz_ave = 0.5 * (dzi[j_m] + dzi[j])
    A[j] = (
        -1.0
        / dz_ave
        * (
            Kzz[j] / dzi[j] * (ysum[j_p] + ysum[j]) / 2.0
            + Kzz[j_m] / dzi[j_m] * (ysum[j] + ysum[j_m]) / 2.0
        )
        / ysum[j]
    )
    B[j] = 1.0 / dz_ave * Kzz[j] / dzi[j] * (ysum[j_p] + ysum[j]) / 2.0 / ysum[j_p]
    C[j] = 1.0 / dz_ave * Kzz[j_m] / dzi[j_m] * (ysum[j] + ysum[j_m]) / 2.0 / ysum[j_m]

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

    # per-layer quantities as columns, broadcasting over species
    dz_c, dzi_c, ysum_c = dz_ave[:, None], dzi[:, None], ysum[:, None]
    Hpi_c, Ti_c, g_c, Tco_c = Hpi[:, None], Ti[:, None], g[:, None], Tco[:, None]

    # Ai in the shape of nz*ni and Ai[j] in the shape of (nz-2)*ni
    # Including the settling velocity of the particles
    Ai[j] = (
        -1.0
        / dz_c
        * (
            Dzz[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / 2.0
            + Dzz[j_m] / dzi_c[j_m] * (ysum_c[j] + ysum_c[j_m]) / 2.0
        )
        / ysum_c[j]
        - ((vs[j] > 0) * vs[j] - (vs[j_m] < 0) * vs[j_m]) / dz_c
    )
    Bi[j] = (
        1.0 / dz_c * Dzz[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / 2.0 / ysum_c[j_p]
        - ((vs[j] < 0) * vs[j]) / dz_c
    )
    Ci[j] = (
        1.0 / dz_c * Dzz[j_m] / dzi_c[j_m] * (ysum_c[j] + ysum_c[j_m]) / 2.0 / ysum_c[j_m]
        + ((vs[j_m] > 0) * vs[j_m]) / dz_c
    )

    Ai[j] += (
        1.0
        / (2.0 * dz_c)
        * (
            Dzz[j]
            * (
                -1.0 / Hpi_c[j]
                + ms * g_c[j] / (Navo * kb * Ti_c[j])
                + alpha / Ti_c[j] * (Tco_c[j_p] - Tco_c[j]) / dzi_c[j]
            )
            - Dzz[j_m]
            * (
                -1.0 / Hpi_c[j_m]
                + ms * g_c[j] / (Navo * kb * Ti_c[j_m])
                + alpha / Ti_c[j_m] * (Tco_c[j] - Tco_c[j_m]) / dzi_c[j_m]
            )
        )
    )  # /ysum[j]
    Bi[j] += (
        1.0
        / (2.0 * dz_c)
        * Dzz[j]
        * (
            -1.0 / Hpi_c[j]
            + ms * g_c[j_p] / (Navo * kb * Ti_c[j])
            + alpha / Ti_c[j] * (Tco_c[j_p] - Tco_c[j]) / dzi_c[j]
        )
    )
    Ci[j] += (
        -1.0
        / (2.0 * dz_c)
        * Dzz[j_m]
        * (
            -1.0 / Hpi_c[j_m]
            + ms * g_c[j_m] / (Navo * kb * Ti_c[j_m])
            + alpha / Ti_c[j_m] * (Tco_c[j] - Tco_c[j_m]) / dzi_c[j_m]
        )
    )

    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)

Transport tendency with settling and the advective part of molecular diffusion as vm.

As diffdf_settling, but the non-gradient part of the molecular flux is an upwind advection with the velocity atm.vm. Selected only with Config.use_vm_mol, which Integration rejects.

Parameters:

Name Type Description Default
y ndarray

Number densities, shape (nz, ni) [cm-3].

required
atm AtmData

Atmospheric structure.

required

Returns:

Type Description
ndarray

Transport tendency -dphi/dz, shape (nz, ni) [cm-3 s-1].

Source code in src/vulcan/op.py
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
3091
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
def diffdf_settling_vm(self, y, atm):
    """
    Transport tendency with settling and the advective part of molecular diffusion as `vm`.

    As `diffdf_settling`, but the non-gradient part of the molecular flux is an upwind
    advection with the velocity `atm.vm`. Selected only with `Config.use_vm_mol`, which
    `Integration` rejects.

    Parameters
    ----------
    y : np.ndarray
        Number densities, shape (nz, ni) [cm-3].
    atm : store.AtmData
        Atmospheric structure.

    Returns
    -------
    np.ndarray
        Transport tendency -dphi/dz, shape (nz, ni) [cm-3 s-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 J of chemistry plus transport, with molecular diffusion.

Not called by the current code; the solver builds 1/(r h) I - J directly with lhs_jac_tot. It no longer runs: it calls the generated symjac without nz, which raises TypeError.

Parameters:

Name Type Description Default
var Variables

Reads y [cm-3] and k.

required
atm AtmData

Atmospheric structure.

required

Returns:

Type Description
ndarray

Shape (nz ni, nz ni).

Source code in src/vulcan/op.py
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
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
def jac_tot(self, var, atm):
    """
    Jacobian J of chemistry plus transport, with molecular diffusion.

    Not called by the current code; the solver builds 1/(r h) I - J directly with
    `lhs_jac_tot`. It no longer runs: it calls the generated `symjac` without `nz`, which
    raises TypeError.

    Parameters
    ----------
    var : store.Variables
        Reads `y` [cm-3] and `k`.
    atm : store.AtmData
        Atmospheric structure.

    Returns
    -------
    np.ndarray
        Shape (nz ni, nz ni).
    """

    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)

Rosenbrock matrix like lhs_jac_tot, with no dependence on the bottom layer.

Not called by the current code: its only caller, Ros2.solver_fix_all_bot, is unused. The columns of the bottom layer, its 1/(r h) diagonal included, are zero, so the matrix is singular and band_lu raises LinAlgError.

Unlike lhs_jac_tot, it adds the diffusion-limited escape term for Config.diff_esc on the top-layer diagonal and omits the bot_vdep deposition term.

Parameters:

Name Type Description Default
var Variables

Reads y [cm-3], k and dt [s].

required
atm AtmData

Atmospheric structure.

required

Returns:

Type Description
ndarray

Shape (nz ni, nz ni).

Source code in src/vulcan/op.py
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
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
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
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
3956
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
3983
3984
3985
3986
3987
3988
3989
3990
3991
def lhs_jac_fix_all_bot(self, var, atm):
    """
    Rosenbrock matrix like `lhs_jac_tot`, with no dependence on the bottom layer.

    Not called by the current code: its only caller, `Ros2.solver_fix_all_bot`, is
    unused. The columns of the bottom layer, its 1/(r h) diagonal included, are zero, so
    the matrix is singular and `band_lu` raises LinAlgError.

    Unlike `lhs_jac_tot`, it adds the diffusion-limited escape term for `Config.diff_esc`
    on the top-layer diagonal and omits the `bot_vdep` deposition term.

    Parameters
    ----------
    var : store.Variables
        Reads `y` [cm-3], `k` and `dt` [s].
    atm : store.AtmData
        Atmospheric structure.

    Returns
    -------
    np.ndarray
        Shape (nz ni, nz ni).
    """

    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)

Rosenbrock matrix 1/(r h) I - J for chemistry and eddy diffusion only.

Matches diffdf_no_mol.

Parameters:

Name Type Description Default
var Variables

Reads y [cm-3], k and dt [s].

required
atm AtmData

Atmospheric structure.

required

Returns:

Type Description
ndarray

Shape (nz ni, nz ni).

Source code in src/vulcan/op.py
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
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
def lhs_jac_no_mol(self, var, atm):
    """
    Rosenbrock matrix 1/(r h) I - J for chemistry and eddy diffusion only.

    Matches `diffdf_no_mol`.

    Parameters
    ----------
    var : store.Variables
        Reads `y` [cm-3], `k` and `dt` [s].
    atm : store.AtmData
        Atmospheric structure.

    Returns
    -------
    np.ndarray
        Shape (nz ni, nz ni).
    """

    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))

    # interior layers j = 1..nz-2 at once; suffix _m: j-1, _p: j+1. Per-layer
    # quantities are columns that broadcast over species
    j, j_m, j_p = slice(1, nz - 1), slice(0, nz - 2), slice(2, nz)
    dz_c = (0.5 * (dzi[j_m] + dzi[j]))[:, None]
    dzi_c, ysum_c, Kzz_c, vz_c = dzi[:, None], ysum[:, None], Kzz[:, None], vz[:, None]

    self.sub_interior(
        dfdy,
        0,
        -1.0
        / dz_c
        * (
            Kzz_c[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / 2.0
            + Kzz_c[j_m] / dzi_c[j_m] * (ysum_c[j_m] + ysum_c[j]) / 2.0
        )
        / ysum_c[j]
        - ((vz_c[j] > 0) * vz_c[j] - (vz_c[j_m] < 0) * vz_c[j_m]) / dz_c,
    )
    self.sub_interior(
        dfdy,
        ni,
        1.0 / dz_c * (Kzz_c[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / (2.0 * ysum_c[j_p]))
        - ((vz_c[j] < 0) * vz_c[j]) / dz_c,
    )
    self.sub_interior(
        dfdy,
        -ni,
        1.0
        / dz_c
        * (Kzz_c[j_m] / dzi_c[j_m] * (ysum_c[j_m] + ysum_c[j]) / (2.0 * ysum_c[j_m]))
        + ((vz_c[j_m] > 0) * vz_c[j_m]) / dz_c,
    )

    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)

Rosenbrock matrix as lhs_jac_no_mol, with no dependence on the bottom layer.

Not called by the current code: its only caller, Ros2.solver_fix_all_bot, is unused. The columns of the bottom layer, its 1/(r h) diagonal included, are zero, so the matrix is singular and band_lu raises LinAlgError.

Parameters:

Name Type Description Default
var Variables

Reads y [cm-3], k and dt [s].

required
atm AtmData

Atmospheric structure.

required

Returns:

Type Description
ndarray

Shape (nz ni, nz ni).

Source code in src/vulcan/op.py
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
def lhs_jac_no_mol_fix_all_bot(self, var, atm):
    """
    Rosenbrock matrix as `lhs_jac_no_mol`, with no dependence on the bottom layer.

    Not called by the current code: its only caller, `Ros2.solver_fix_all_bot`, is
    unused. The columns of the bottom layer, its 1/(r h) diagonal included, are zero, so
    the matrix is singular and `band_lu` raises LinAlgError.

    Parameters
    ----------
    var : store.Variables
        Reads `y` [cm-3], `k` and `dt` [s].
    atm : store.AtmData
        Atmospheric structure.

    Returns
    -------
    np.ndarray
        Shape (nz ni, nz ni).
    """

    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)

Rosenbrock matrix as lhs_jac_tot, plus gravitational settling of particles.

Matches diffdf_settling.

Parameters:

Name Type Description Default
var Variables

Reads y [cm-3], k and dt [s].

required
atm AtmData

Atmospheric structure.

required

Returns:

Type Description
ndarray

Shape (nz ni, nz ni).

Source code in src/vulcan/op.py
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
4124
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
4218
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
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
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
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
def lhs_jac_settling(self, var, atm):
    """
    Rosenbrock matrix as `lhs_jac_tot`, plus gravitational settling of particles.

    Matches `diffdf_settling`.

    Parameters
    ----------
    var : store.Variables
        Reads `y` [cm-3], `k` and `dt` [s].
    atm : store.AtmData
        Atmospheric structure.

    Returns
    -------
    np.ndarray
        Shape (nz ni, nz ni).
    """

    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))

    # interior layers j = 1..nz-2 at once; suffix _m: j-1, _p: j+1. Per-layer
    # quantities are columns that broadcast over species
    j, j_m, j_p = slice(1, nz - 1), slice(0, nz - 2), slice(2, nz)
    dz_c = (0.5 * (dzi[j_m] + dzi[j]))[:, None]
    dzi_c, ysum_c, Kzz_c, vz_c = dzi[:, None], ysum[:, None], Kzz[:, None], vz[:, None]
    Hpi_c, Ti_c, g_c, Tco_c = Hpi[:, None], Ti[:, None], g[:, None], Tco[:, None]

    self.sub_interior(
        dfdy,
        0,
        -1.0
        / dz_c
        * (
            Kzz_c[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / 2.0
            + Kzz_c[j_m] / dzi_c[j_m] * (ysum_c[j_m] + ysum_c[j]) / 2.0
        )
        / ysum_c[j]
        - ((vz_c[j] > 0) * vz_c[j] - (vz_c[j_m] < 0) * vz_c[j_m]) / dz_c,
    )
    self.sub_interior(
        dfdy,
        ni,
        1.0 / dz_c * (Kzz_c[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / (2.0 * ysum_c[j_p]))
        - ((vz_c[j] < 0) * vz_c[j]) / dz_c,
    )
    self.sub_interior(
        dfdy,
        -ni,
        1.0
        / dz_c
        * (Kzz_c[j_m] / dzi_c[j_m] * (ysum_c[j_m] + ysum_c[j]) / (2.0 * ysum_c[j_m]))
        + ((vz_c[j_m] > 0) * vz_c[j_m]) / dz_c,
    )

    # [j_indx[j], j_indx[j]] has size ni*ni
    self.sub_interior(
        dfdy,
        0,
        -1.0
        / dz_c
        * (
            Dzz[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / 2.0
            + Dzz[j_m] / dzi_c[j_m] * (ysum_c[j_m] + ysum_c[j]) / 2.0
        )
        / ysum_c[j]
        + 1.0
        / (2.0 * dz_c)
        * (
            Dzz[j]
            * (
                -1.0 / Hpi_c[j]
                + ms * g_c[j] / (Navo * kb * Ti_c[j])
                + alpha / Ti_c[j] * (Tco_c[j_p] - Tco_c[j]) / dzi_c[j]
            )
            - Dzz[j_m]
            * (
                -1.0 / Hpi_c[j_m]
                + ms * g_c[j] / (Navo * kb * Ti_c[j_m])
                + alpha / Ti_c[j_m] * (Tco_c[j] - Tco_c[j_m]) / dzi_c[j_m]
            )
        )
        - ((vs[j] > 0) * vs[j] - (vs[j_m] < 0) * vs[j_m]) / dz_c,
    )
    self.sub_interior(
        dfdy,
        ni,
        1.0 / dz_c * (Dzz[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / (2.0 * ysum_c[j_p]))
        + 1.0
        / (2.0 * dz_c)
        * Dzz[j]
        * (
            -1.0 / Hpi_c[j]
            + ms * g_c[j_p] / (Navo * kb * Ti_c[j])
            + alpha / Ti_c[j] * (Tco_c[j_p] - Tco_c[j]) / dzi_c[j]
        )
        - ((vs[j] < 0) * vs[j]) / dz_c,
    )
    self.sub_interior(
        dfdy,
        -ni,
        1.0
        / dz_c
        * (Dzz[j_m] / dzi_c[j_m] * (ysum_c[j_m] + ysum_c[j]) / (2.0 * ysum_c[j_m]))
        - 1.0
        / (2.0 * dz_c)
        * Dzz[j_m]
        * (
            -1.0 / Hpi_c[j_m]
            + ms * g_c[j_m] / (Navo * kb * Ti_c[j_m])
            + alpha / Ti_c[j_m] * (Tco_c[j] - Tco_c[j_m]) / dzi_c[j_m]
        )
        + ((vs[j_m] > 0) * vs[j_m]) / dz_c,
    )

    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)

Rosenbrock matrix as lhs_jac_settling, with the molecular advection velocity atm.vm.

Not called by the current code: only Config.use_vm_mol selects it, and Integration rejects that setting. It no longer runs: it calls the generated neg_symjac without nz, which raises TypeError. Matches diffdf_settling_vm.

Parameters:

Name Type Description Default
var Variables

Reads y [cm-3], k and dt [s].

required
atm AtmData

Atmospheric structure.

required

Returns:

Type Description
ndarray

Shape (nz ni, nz ni).

Source code in src/vulcan/op.py
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
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
def lhs_jac_settling_vm(self, var, atm):
    """
    Rosenbrock matrix as `lhs_jac_settling`, with the molecular advection velocity `atm.vm`.

    Not called by the current code: only `Config.use_vm_mol` selects it, and
    `Integration` rejects that setting. It no longer runs: it calls the generated
    `neg_symjac` without `nz`, which raises TypeError. Matches `diffdf_settling_vm`.

    Parameters
    ----------
    var : store.Variables
        Reads `y` [cm-3], `k` and `dt` [s].
    atm : store.AtmData
        Atmospheric structure.

    Returns
    -------
    np.ndarray
        Shape (nz ni, nz ni).
    """
    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)

Rosenbrock matrix 1/(r h) I - J for chemistry, eddy and molecular diffusion.

Matches diffdf, including the deposition term bot_vdep.

Parameters:

Name Type Description Default
var Variables

Reads y [cm-3], k and dt [s].

required
atm AtmData

Atmospheric structure.

required

Returns:

Type Description
ndarray

Shape (nz ni, nz ni).

Source code in src/vulcan/op.py
3337
3338
3339
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
3426
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
def lhs_jac_tot(self, var, atm):
    """
    Rosenbrock matrix 1/(r h) I - J for chemistry, eddy and molecular diffusion.

    Matches `diffdf`, including the deposition term `bot_vdep`.

    Parameters
    ----------
    var : store.Variables
        Reads `y` [cm-3], `k` and `dt` [s].
    atm : store.AtmData
        Atmospheric structure.

    Returns
    -------
    np.ndarray
        Shape (nz ni, nz ni).
    """

    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))

    # interior layers j = 1..nz-2 at once; suffix _m: j-1, _p: j+1. Per-layer
    # quantities are columns that broadcast over species
    j, j_m, j_p = slice(1, nz - 1), slice(0, nz - 2), slice(2, nz)
    dz_c = (0.5 * (dzi[j_m] + dzi[j]))[:, None]
    dzi_c, ysum_c, Kzz_c, vz_c = dzi[:, None], ysum[:, None], Kzz[:, None], vz[:, None]
    Hpi_c, Ti_c, g_c, Tco_c = Hpi[:, None], Ti[:, None], g[:, None], Tco[:, None]

    self.sub_interior(
        dfdy,
        0,
        -1.0
        / dz_c
        * (
            Kzz_c[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / 2.0
            + Kzz_c[j_m] / dzi_c[j_m] * (ysum_c[j_m] + ysum_c[j]) / 2.0
        )
        / ysum_c[j]
        - ((vz_c[j] > 0) * vz_c[j] - (vz_c[j_m] < 0) * vz_c[j_m]) / dz_c,
    )
    self.sub_interior(
        dfdy,
        ni,
        1.0 / dz_c * (Kzz_c[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / (2.0 * ysum_c[j_p]))
        - ((vz_c[j] < 0) * vz_c[j]) / dz_c,
    )
    self.sub_interior(
        dfdy,
        -ni,
        1.0
        / dz_c
        * (Kzz_c[j_m] / dzi_c[j_m] * (ysum_c[j_m] + ysum_c[j]) / (2.0 * ysum_c[j_m]))
        + ((vz_c[j_m] > 0) * vz_c[j_m]) / dz_c,
    )

    # [j_indx[j], j_indx[j]] has size ni*ni
    self.sub_interior(
        dfdy,
        0,
        -1.0
        / dz_c
        * (
            Dzz[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / 2.0
            + Dzz[j_m] / dzi_c[j_m] * (ysum_c[j_m] + ysum_c[j]) / 2.0
        )
        / ysum_c[j]
        + 1.0
        / (2.0 * dz_c)
        * (
            Dzz[j]
            * (
                -1.0 / Hpi_c[j]
                + ms * g_c[j] / (Navo * kb * Ti_c[j])
                + alpha / Ti_c[j] * (Tco_c[j_p] - Tco_c[j]) / dzi_c[j]
            )
            - Dzz[j_m]
            * (
                -1.0 / Hpi_c[j_m]
                + ms * g_c[j] / (Navo * kb * Ti_c[j_m])
                + alpha / Ti_c[j_m] * (Tco_c[j] - Tco_c[j_m]) / dzi_c[j_m]
            )
        ),
    )
    self.sub_interior(
        dfdy,
        ni,
        1.0 / dz_c * (Dzz[j] / dzi_c[j] * (ysum_c[j_p] + ysum_c[j]) / (2.0 * ysum_c[j_p]))
        + 1.0
        / (2.0 * dz_c)
        * Dzz[j]
        * (
            -1.0 / Hpi_c[j]
            + ms * g_c[j_p] / (Navo * kb * Ti_c[j])
            + alpha / Ti_c[j] * (Tco_c[j_p] - Tco_c[j]) / dzi_c[j]
        ),
    )
    self.sub_interior(
        dfdy,
        -ni,
        1.0
        / dz_c
        * (Dzz[j_m] / dzi_c[j_m] * (ysum_c[j_m] + ysum_c[j]) / (2.0 * ysum_c[j_m]))
        - 1.0
        / (2.0 * dz_c)
        * Dzz[j_m]
        * (
            -1.0 / Hpi_c[j_m]
            + ms * g_c[j_m] / (Navo * kb * Ti_c[j_m])
            + alpha / Ti_c[j_m] * (Tco_c[j] - Tco_c[j_m]) / dzi_c[j_m]
        ),
    )

    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)

Rosenbrock matrix as lhs_jac_tot, with the molecular advection velocity atm.vm.

Not called by the current code: only Config.use_vm_mol selects it, and Integration rejects that setting. It no longer runs: it calls the generated neg_symjac without nz, which raises TypeError.

Parameters:

Name Type Description Default
var Variables

Reads y [cm-3], k and dt [s].

required
atm AtmData

Atmospheric structure.

required

Returns:

Type Description
ndarray

Shape (nz ni, nz ni).

Source code in src/vulcan/op.py
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
3636
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
def lhs_jac_tot_vm(self, var, atm):
    """
    Rosenbrock matrix as `lhs_jac_tot`, with the molecular advection velocity `atm.vm`.

    Not called by the current code: only `Config.use_vm_mol` selects it, and
    `Integration` rejects that setting. It no longer runs: it calls the generated
    `neg_symjac` without `nz`, which raises TypeError.

    Parameters
    ----------
    var : store.Variables
        Reads `y` [cm-3], `k` and `dt` [s].
    atm : store.AtmData
        Atmospheric structure.

    Returns
    -------
    np.ndarray
        Shape (nz ni, nz ni).
    """
    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)

Update the element totals and their relative change since the start.

Elements in Config.loss_ex are skipped.

Parameters:

Name Type Description Default
data_var Variables

Reads y and atom_ini; sets atom_sum [cm-3, summed over all layers] and atom_loss [dimensionless].

required

Returns:

Type Description
Variables

data_var.

Source code in src/vulcan/op.py
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
def loss(self, data_var):
    """
    Update the element totals and their relative change since the start.

    Elements in `Config.loss_ex` are skipped.

    Parameters
    ----------
    data_var : store.Variables
        Reads `y` and `atom_ini`; sets `atom_sum` [cm-3, summed over all layers] and
        `atom_loss` [dimensionless].

    Returns
    -------
    store.Variables
        `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)

Log that a step was rejected because the element conservation changed too much.

Parameters:

Name Type Description Default
para Parameters

Reads count.

required
Source code in src/vulcan/op.py
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
def print_lossBig(self, para):
    """
    Log that a step was rejected because the element conservation changed too much.

    Parameters
    ----------
    para : store.Parameters
        Reads `count`.
    """

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

print_nega(data_var, data_para)

Log where and in which species the solution went negative.

Parameters:

Name Type Description Default
data_var Variables

Reads y, t and dt.

required
data_para Parameters

Reads count.

required
Source code in src/vulcan/op.py
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
def print_nega(self, data_var, data_para):
    """
    Log where and in which species the solution went negative.

    Parameters
    ----------
    data_var : store.Variables
        Reads `y`, `t` and `dt`.
    data_para : store.Parameters
        Reads `count`.
    """

    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)

Restore y to the previous step and multiply the time step by dt_reduc.

Parameters:

Name Type Description Default
var Variables

Updates y [cm-3] and dt [s].

required
dt_reduc float

Factor applied to dt.

0.5

Returns:

Type Description
Variables

var.

Source code in src/vulcan/op.py
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
def reset_y(self, var, dt_reduc=0.5):
    """
    Restore y to the previous step and multiply the time step by `dt_reduc`.

    Parameters
    ----------
    var : store.Variables
        Updates `y` [cm-3] and `dt` [s].
    dt_reduc : float
        Factor applied to `dt`.

    Returns
    -------
    store.Variables
        `var`.
    """

    # 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)

Check whether the last step can be accepted.

It can if y >= 0, the truncation error is within rtol, and the relative element loss changed by less than loss_eps over the step.

Parameters:

Name Type Description Default
var Variables

Reads y, atom_loss and atom_loss_prev.

required
para Parameters

Reads delta.

required
loss_eps float

Largest allowed change of atom_loss per step [dimensionless].

0.1
rtol float

Largest allowed relative truncation error [dimensionless].

0.6

Returns:

Type Description
bool
Source code in src/vulcan/op.py
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
def step_ok(self, var, para, loss_eps=1e-1, rtol=0.6):
    """
    Check whether the last step can be accepted.

    It can if y >= 0, the truncation error is within `rtol`, and the relative element
    loss changed by less than `loss_eps` over the step.

    Parameters
    ----------
    var : store.Variables
        Reads `y`, `atom_loss` and `atom_loss_prev`.
    para : store.Parameters
        Reads `delta`.
    loss_eps : float
        Largest allowed change of `atom_loss` per step [dimensionless].
    rtol : float
        Largest allowed relative truncation error [dimensionless].

    Returns
    -------
    bool
    """
    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)

Reject the step: count the reason, restore y and reduce the time step.

The time step is multiplied by Config.dt_var_min. If it falls below Config.dt_min, it is set to dt_min, negative densities are set to zero, and the integration moves on from the restored state.

Parameters:

Name Type Description Default
var Variables

Updates y [cm-3] and dt [s].

required
para Parameters

Increments delta_count, nega_count or loss_count.

required
loss_eps float

Not used.

0.1
rtol float

Largest allowed relative truncation error [dimensionless].

0.6

Returns:

Type Description
bool

True if the time step reached dt_min and the integration should move on, otherwise False.

Source code in src/vulcan/op.py
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
def step_reject(self, var, para, loss_eps=1e-1, rtol=0.6):
    """
    Reject the step: count the reason, restore y and reduce the time step.

    The time step is multiplied by `Config.dt_var_min`. If it falls below `Config.dt_min`,
    it is set to `dt_min`, negative densities are set to zero, and the integration moves on
    from the restored state.

    Parameters
    ----------
    var : store.Variables
        Updates `y` [cm-3] and `dt` [s].
    para : store.Parameters
        Increments `delta_count`, `nega_count` or `loss_count`.
    loss_eps : float
        Not used.
    rtol : float
        Largest allowed relative truncation error [dimensionless].

    Returns
    -------
    bool
        True if the time step reached `dt_min` and the integration should move on,
        otherwise False.
    """

    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

sub_interior(dfdy, offset, val) staticmethod

Subtract a transport term from one diagonal of the Jacobian in the interior layers.

Sets dfdy[r, r + offset] -= val for every row r of the layers 1 to nz - 2; val has shape (nz - 2, 1), the same for every species, or (nz - 2, ni).

Source code in src/vulcan/op.py
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
@staticmethod
def sub_interior(dfdy, offset, val):
    """
    Subtract a transport term from one diagonal of the Jacobian in the interior layers.

    Sets dfdy[r, r + offset] -= val for every row r of the layers 1 to nz - 2; `val` has
    shape (nz - 2, 1), the same for every species, or (nz - 2, ni).
    """
    nlev = val.shape[0]
    rows = np.arange(ni, (nlev + 1) * ni)
    dfdy[rows, rows + offset] -= np.broadcast_to(val, (nlev, ni)).ravel()

thomas_vec(a, b, c, d)

Solve a tridiagonal system for several right-hand sides with the Thomas algorithm.

Not called by the current code. It has no self argument, so it only works when called through the class.

Parameters:

Name Type Description Default
a ndarray

Sub-, main and super-diagonal, length nf.

required
b ndarray

Sub-, main and super-diagonal, length nf.

required
c ndarray

Sub-, main and super-diagonal, length nf.

required
d ndarray

Right-hand sides, nf rows.

required

Returns:

Type Description
ndarray

Solution, shape (nf, number of right-hand sides).

Source code in src/vulcan/op.py
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
def thomas_vec(a, b, c, d):
    """
    Solve a tridiagonal system for several right-hand sides with the Thomas algorithm.

    Not called by the current code. It has no `self` argument, so it only works when
    called through the class.

    Parameters
    ----------
    a, b, c : np.ndarray
        Sub-, main and super-diagonal, length nf.
    d : np.ndarray
        Right-hand sides, nf rows.

    Returns
    -------
    np.ndarray
        Solution, shape (nf, number of right-hand sides).
    """
    # 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

Second-order Rosenbrock solver (Verwer et al. 1997) with a banded linear solver.

With r = 1 + 1/sqrt(2) and the matrix A = 1/(r h) I - J, one step solves A k1 = f(y) and A k2 = f(y + k1/r) - 2 k1 / (r h), and sets y_new = y + 3/(2r) k1 + 1/(2r) k2. The truncation error is estimated from |y_new - (y + k1/r)|.

vulcan_cfg : Config Run configuration.

Source code in src/vulcan/op.py
5179
5180
5181
5182
5183
5184
5185
5186
5187
def __init__(self, vulcan_cfg: Config):
    """
    Parameters
    ----------
    vulcan_cfg : Config
        Run configuration.
    """
    # ODESolver.__init__(self)
    super().__init__(vulcan_cfg)

band_lu(a, nb) staticmethod

LU-factorise the block-tridiagonal matrix a in LAPACK band storage.

Chemistry couples the nb species within a layer (|row - col| <= nb - 1), and transport couples each species only to itself in the adjacent layers (|row - col| = nb), so both the lower and the upper bandwidth are exactly nb. The factors are computed once and reused for both Rosenbrock stages.

Parameters:

Name Type Description Default
a ndarray

Square block-tridiagonal matrix of nb x nb blocks.

required
nb int

Block size, the number of species.

required

Returns:

Type Description
tuple

(lub, piv, nb), the input of band_solve.

Raises:

Type Description
ValueError

If a contains infs or NaNs.

LinAlgError

If a is singular.

Source code in src/vulcan/op.py
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
@staticmethod
def band_lu(a, nb):
    """
    LU-factorise the block-tridiagonal matrix a in LAPACK band storage.

    Chemistry couples the nb species within a layer (|row - col| <= nb - 1), and
    transport couples each species only to itself in the adjacent layers
    (|row - col| = nb), so both the lower and the upper bandwidth are exactly nb.
    The factors are computed once and reused for both Rosenbrock stages.

    Parameters
    ----------
    a : np.ndarray
        Square block-tridiagonal matrix of nb x nb blocks.
    nb : int
        Block size, the number of species.

    Returns
    -------
    tuple
        `(lub, piv, nb)`, the input of `band_solve`.

    Raises
    ------
    ValueError
        If a contains infs or NaNs.
    np.linalg.LinAlgError
        If a is singular.
    """
    n = a.shape[0]
    # dgbtrf stores a[i, j] at ab[2*nb + i - j, j]; the top nb rows hold the fill-in
    # from row interchanges
    ab = np.zeros((3 * nb + 1, n))
    for d in range(-nb, nb + 1):  # d = column - row
        if d >= 0:
            ab[2 * nb - d, d:] = np.diagonal(a, d)
        else:
            ab[2 * nb - d, : n + d] = np.diagonal(a, d)
    if not np.all(np.isfinite(ab)):
        raise ValueError('array must not contain infs or NaNs')

    lub, piv, info = scipy.linalg.lapack.dgbtrf(ab, nb, nb, overwrite_ab=1)
    if info > 0:
        raise np.linalg.LinAlgError('singular matrix')
    if info < 0:
        raise ValueError('illegal value in %d-th argument of internal gbtrf' % -info)
    return lub, piv, nb

band_solve(lu, b) staticmethod

Solve a x = b with the factors returned by band_lu.

Parameters:

Name Type Description Default
lu tuple

Output of band_lu.

required
b ndarray

Right-hand side.

required

Returns:

Type Description
ndarray

Solution x.

Source code in src/vulcan/op.py
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
@staticmethod
def band_solve(lu, b):
    """
    Solve a x = b with the factors returned by `band_lu`.

    Parameters
    ----------
    lu : tuple
        Output of `band_lu`.
    b : np.ndarray
        Right-hand side.

    Returns
    -------
    np.ndarray
        Solution x.
    """
    lub, piv, nb = lu
    b = np.asarray_chkfinite(b)
    x, info = scipy.linalg.lapack.dgbtrs(lub, nb, nb, b, piv)
    if info < 0:
        raise ValueError('illegal value in %d-th argument of internal gbtrs' % -info)
    return x

naming_solver(para)

Set para.solver_str to the solver method used by one_step (always 'solver').

Parameters:

Name Type Description Default
para Parameters

Sets solver_str.

required
Source code in src/vulcan/op.py
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
def naming_solver(self, para):
    """
    Set `para.solver_str` to the solver method used by `one_step` (always 'solver').

    Parameters
    ----------
    para : store.Parameters
        Sets `solver_str`.
    """
    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)

Take solver steps until one is accepted.

After each step, clip cleans the densities. The loop ends when step_ok accepts the step, or when step_reject reaches Config.dt_min; otherwise the step is repeated with a smaller time step.

Parameters:

Name Type Description Default
var Variables

State, updated in place.

required
atm AtmData

Atmospheric structure.

required
para Parameters

Counters, updated in place.

required

Returns:

Type Description
tuple

(var, para).

Source code in src/vulcan/op.py
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
def one_step(self, var, atm, para):
    """
    Take solver steps until one is accepted.

    After each step, `clip` cleans the densities. The loop ends when `step_ok` accepts the
    step, or when `step_reject` reaches `Config.dt_min`; otherwise the step is repeated
    with a smaller time step.

    Parameters
    ----------
    var : store.Variables
        State, updated in place.
    atm : store.AtmData
        Atmospheric structure.
    para : store.Parameters
        Counters, updated in place.

    Returns
    -------
    tuple
        `(var, 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)

Take one Rosenbrock step of chemistry and transport.

The transport terms and matrix depend on Config.use_moldiff and use_settling. Species in fix_species and, with use_ion, the electron are kept out of the update; the species in use_fix_sp_bot are reset to their bottom mixing ratios. With use_ion, the electron density is then set by charge balance.

With use_fix_H2He, once t > 1e6 s, it adds H2 and He to Config.use_fix_sp_bot, which changes the shared Config for the rest of the run.

Parameters:

Name Type Description Default
var Variables

Reads y, ymix, dt [s] and k; sets y [cm-3] and ymix.

required
atm AtmData

Atmospheric structure.

required
para Parameters

Sets delta [dimensionless].

required

Returns:

Type Description
tuple

(var, para).

Source code in src/vulcan/op.py
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
def solver(self, var, atm, para):
    """
    Take one Rosenbrock step of chemistry and transport.

    The transport terms and matrix depend on `Config.use_moldiff` and `use_settling`.
    Species in `fix_species` and, with `use_ion`, the electron are kept out of the
    update; the species in `use_fix_sp_bot` are reset to their bottom mixing ratios.
    With `use_ion`, the electron density is then set by charge balance.

    With `use_fix_H2He`, once t > 1e6 s, it adds H2 and He to `Config.use_fix_sp_bot`,
    which changes the shared Config for the rest of the run.

    Parameters
    ----------
    var : store.Variables
        Reads `y`, `ymix`, `dt` [s] and `k`; sets `y` [cm-3] and `ymix`.
    atm : store.AtmData
        Atmospheric structure.
    para : store.Parameters
        Sets `delta` [dimensionless].

    Returns
    -------
    tuple
        `(var, para)`.
    """

    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_lu = self.band_lu(lhs, ni)
    k1_flat = self.band_solve(lhs_lu, 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 = self.band_solve(lhs_lu, 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)

Take one Rosenbrock step with the bottom-layer composition held fixed.

Not called by the current code: naming_solver always selects solver. It would fail anyway, because the matrix from lhs_jac_*_fix_all_bot is singular and band_lu raises LinAlgError.

Like solver, with the bottom mixing ratios reset after the step, but without fix_species, use_fix_sp_bot or settling.

Parameters:

Name Type Description Default
var Variables

Reads y, ymix, dt [s] and k; sets y [cm-3] and ymix.

required
atm AtmData

Atmospheric structure.

required
para Parameters

Sets delta [dimensionless].

required

Returns:

Type Description
tuple

(var, para).

Source code in src/vulcan/op.py
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
def solver_fix_all_bot(self, var, atm, para):
    """
    Take one Rosenbrock step with the bottom-layer composition held fixed.

    Not called by the current code: `naming_solver` always selects `solver`. It would
    fail anyway, because the matrix from `lhs_jac_*_fix_all_bot` is singular and
    `band_lu` raises LinAlgError.

    Like `solver`, with the bottom mixing ratios reset after the step, but without
    `fix_species`, `use_fix_sp_bot` or settling.

    Parameters
    ----------
    var : store.Variables
        Reads `y`, `ymix`, `dt` [s] and `k`; sets `y` [cm-3] and `ymix`.
    atm : store.AtmData
        Atmospheric structure.
    para : store.Parameters
        Sets `delta` [dimensionless].

    Returns
    -------
    tuple
        `(var, para)`.
    """

    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_lu = self.band_lu(lhs, ni)
    k1_flat = self.band_solve(lhs_lu, 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 = self.band_solve(lhs_lu, 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)

Set the next time step from the truncation error of the last step.

h_new = h * 0.9 (rtol / delta)^(1/2), with the factor limited to [dt_var_min, dt_var_max] and h_new to [dt_min, dt_max]; a zero delta counts as 0.01 rtol.

Parameters:

Name Type Description Default
var Variables

Updates dt [s].

required
para Parameters

Reads delta [dimensionless].

required
dt_var_min float

Smallest and largest factor applied to the time step.

2
dt_var_max float

Smallest and largest factor applied to the time step.

2
dt_min float

Smallest and largest time step [s].

1e-10
dt_max float

Smallest and largest time step [s].

1e-10

Returns:

Type Description
Variables

var.

Source code in src/vulcan/op.py
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
def step_size(self, var, para, dt_var_min=2, dt_var_max=0.5, dt_min=1e-10, dt_max=1e18):
    """
    Set the next time step from the truncation error of the last step.

    h_new = h * 0.9 (rtol / delta)^(1/2), with the factor limited to
    [`dt_var_min`, `dt_var_max`] and h_new to [`dt_min`, `dt_max`]; a zero delta counts as
    0.01 rtol.

    Parameters
    ----------
    var : store.Variables
        Updates `dt` [s].
    para : store.Parameters
        Reads `delta` [dimensionless].
    dt_var_min, dt_var_max : float
        Smallest and largest factor applied to the time step.
    dt_min, dt_max : float
        Smallest and largest time step [s].

    Returns
    -------
    store.Variables
        `var`.
    """
    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

Output(vulcan_cfg)

Bases: object

Progress messages and output files of a run.

The formats in Config.save_type are 'netcdf' (.nc), 'pickle' (.pkl) and 'plain' (.var, .atm and .par text files), named from Config.out_name in Config.output_dir.

With Config.clean_output, deletes output_dir first (see safe_rm). Creates output_dir and plot_dir, and removes existing output files of the requested formats.

Parameters:

Name Type Description Default
vulcan_cfg Config

Run configuration.

required

Raises:

Type Description
ValueError

If save_type names an unknown format.

Source code in src/vulcan/op.py
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
def __init__(self, vulcan_cfg: Config):
    """
    Prepare the output folders.

    With `Config.clean_output`, deletes `output_dir` first (see `safe_rm`). Creates
    `output_dir` and `plot_dir`, and removes existing output files of the requested formats.

    Parameters
    ----------
    vulcan_cfg : Config
        Run configuration.

    Raises
    ------
    ValueError
        If `save_type` names an unknown format.
    """

    self.cfg = vulcan_cfg
    self.save_types = self._save_types()

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

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

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

    for save_type in self.save_types:
        for ext in self.EXTENSIONS[save_type]:
            outfile = self._out_path(ext)
            if os.path.isfile(outfile):
                log.warning(f'Output file {outfile} already exists. Removing.')
                safe_rm(outfile)

EXTENSIONS = {'netcdf': ['.nc'], 'pickle': ['.pkl'], 'plain': ['.var', '.atm', '.par']} class-attribute instance-attribute

SAVE_TYPES = ('netcdf', 'pickle', 'plain') class-attribute instance-attribute

cfg = vulcan_cfg instance-attribute

save_types = self._save_types() instance-attribute

print_end_msg(var, para)

Log the final element loss and the counts of rejected steps.

Parameters:

Name Type Description Default
var Variables

Reads atom_loss.

required
para Parameters

Reads nega_count, loss_count and delta_count.

required
Source code in src/vulcan/op.py
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
def print_end_msg(self, var, para):
    """
    Log the final element loss and the counts of rejected steps.

    Parameters
    ----------
    var : store.Variables
        Reads `atom_loss`.
    para : store.Parameters
        Reads `nega_count`, `loss_count` and `delta_count`.
    """
    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)

Log the progress of the integration.

Logs the time, the step number, longdy, longdydt, dt, and the species and layer where the composition changes most.

Parameters:

Name Type Description Default
var Variables

Reads t, longdy, longdydt and dt.

required
para Parameters

Reads count and where_varies_most.

required
Source code in src/vulcan/op.py
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
def print_prog(self, var, para):
    """
    Log the progress of the integration.

    Logs the time, the step number, `longdy`, `longdydt`, `dt`, and the species and
    layer where the composition changes most.

    Parameters
    ----------
    var : store.Variables
        Reads `t`, `longdy`, `longdydt` and `dt`.
    para : store.Parameters
        Reads `count` and `where_varies_most`.
    """
    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)

Make the final plots and write the output files.

Plots the evolution (Config.use_plot_evo) and the final mixing ratios (use_plot_end), then writes the formats in save_type to output_dir. With save_evolution, the time series are kept every save_evo_frq steps.

Parameters:

Name Type Description Default
var Variables

Final state; its time series are converted to arrays in place and, with save_evolution, thinned in place to every save_evo_frq-th entry.

required
atm AtmData

Atmospheric structure.

required
para Parameters

Counters.

required
Source code in src/vulcan/op.py
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
def save_out(self, var, atm, para):
    """
    Make the final plots and write the output files.

    Plots the evolution (`Config.use_plot_evo`) and the final mixing ratios
    (`use_plot_end`), then writes the formats in `save_type` to `output_dir`. With
    `save_evolution`, the time series are kept every `save_evo_frq` steps.

    Parameters
    ----------
    var : store.Variables
        Final state; its time series are converted to arrays in place and, with
        `save_evolution`, thinned in place to every `save_evo_frq`-th entry.
    atm : store.AtmData
        Atmospheric structure.
    para : store.Parameters
        Counters.
    """
    output_dir = self.cfg.output_dir

    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.makedirs(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:
        plot.plot_evo(self.cfg, species, var, atm)
    if self.cfg.use_plot_end:
        plot.plot_update(
            self.cfg,
            species,
            var,
            atm,
            para,
            fpath=os.path.join(self.cfg.plot_dir, f'mix.{self.cfg.plot_fmt}'),
        )
    plt.close('all')

    # making the save dict (for pickle and plain)
    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 'netcdf' in self.save_types:
        # self-describing NetCDF4 file
        from vulcan.netcdf import write_netcdf

        write_netcdf(
            self._out_path('.nc'),
            var,
            atm,
            para,
            self.cfg,
            species=species,
            nr=nr,
            re_wM_dict=re_wM_dict,
        )

    if 'plain' in self.save_types:
        # human-readable form, less efficient
        for ext, data in (('.var', var_save), ('.atm', vars(atm)), ('.par', vars(para))):
            fpath = self._out_path(ext)
            log.info(f'Writing plain output to {fpath}')
            with open(fpath, 'w') as outfile:
                for key in data.keys():
                    outfile.write(f'# {key} \n')
                    outfile.write(str(data[key]) + '\n')

    if 'pickle' in self.save_types:
        # pickled form, less safe
        from pickle import dump

        fpath = self._out_path('.pkl')
        log.info(f'Writing pickle output to {fpath}')

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