Skip to content

vulcan.make_chem_funs

make_chem_funs


Generate chem_funs.py, the chemistry functions of the network, from the network file and the thermodynamic data.

make_all renumbers the reactions in the network file, writes the net reaction rates and the chemical tendency chemdf, the equilibrium constants Gibbs for the reverse rates and the analytical Jacobians symjac and neg_symjac into chem_funs.py, and checks the network for element conservation and duplicate reactions. chem_funs.py is generated: edit the network or the thermodynamic input instead, and run without -n.

Imports
  • vulcan.config: Config class for handling configuration settings.
  • vulcan.paths: Paths to various files and directories used in VULCAN.

check_conserv(nr)

Check that every forward reaction conserves each element.

The atoms of the reactants and of the products (without M) are counted from the element columns of thermo/all_compose.txt; each reaction that does not balance is logged as a warning.

Parameters:

Name Type Description Default
nr int

Number of reactions, forward and reverse.

required

Raises:

Type Description
RuntimeError

If any reaction does not conserve the elements.

ValueError

If a species is missing from all_compose.txt.

Source code in src/vulcan/make_chem_funs.py
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
def check_conserv(nr):
    """
    Check that every forward reaction conserves each element.

    The atoms of the reactants and of the products (without M) are counted from the
    element columns of `thermo/all_compose.txt`; each reaction that does not balance is
    logged as a warning.

    Parameters
    ----------
    nr : int
        Number of reactions, forward and reverse.

    Raises
    ------
    RuntimeError
        If any reaction does not conserve the elements.
    ValueError
        If a species is missing from `all_compose.txt`.
    """
    from .chem_funs import re_dict

    conserv_check = True
    compo = np.genfromtxt(COM_FILE, names=True, dtype=None)
    compo_row_raw = list(compo['species'])

    # Convert bytes to strings
    # Behaviour differs between Python and SciPy versions. Uses Try/Catch to mitigate.
    compo_row = []
    for sp in compo_row_raw:
        try:
            sp = sp.decode()
        except (UnicodeDecodeError, AttributeError):
            pass
        compo_row.append(str(sp))
    log.debug('compo_row: ' + str(compo_row)[1:60] + '...')

    # dtype.names returns the column names and -2 is for 'species' and 'mass'
    num_atoms = len(compo.dtype.names) - 2

    for re in range(1, nr + 1, 2):
        reac_atoms, prod_atoms = np.zeros(num_atoms), np.zeros(num_atoms)

        for sp in re_dict[re][0]:
            # 1:7 for all the atoms (H	O	C	He	N	S)
            reac_atoms += np.array(list(compo[compo_row.index(sp)])[1 : num_atoms + 1])

        for sp in re_dict[re][1]:
            prod_atoms += np.array(list(compo[compo_row.index(sp)])[1 : num_atoms + 1])

        if not np.all(reac_atoms == prod_atoms):
            log.warning('Re ' + str(re) + ' not conserving element!')
            conserv_check = False

    if conserv_check:
        log.info('Elements conserved in the network.')
    else:
        raise RuntimeError('Elements are not conserved in the reaction. Check the network!')

check_duplicate(nr, photo_re_indx)

Warn about forward reactions that repeat another one.

Two reactions count as duplicates when they have the same reactant and product species, in either direction; stoichiometric coefficients are not compared. Only the reactions before the first photolysis reaction are checked.

Parameters:

Name Type Description Default
nr int

Number of reactions, forward and reverse.

required
photo_re_indx int

Number of the first photolysis reaction, or 0 to check all reactions.

required
Source code in src/vulcan/make_chem_funs.py
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
def check_duplicate(nr, photo_re_indx):
    """
    Warn about forward reactions that repeat another one.

    Two reactions count as duplicates when they have the same reactant and product
    species, in either direction; stoichiometric coefficients are not compared. Only the
    reactions before the first photolysis reaction are checked.

    Parameters
    ----------
    nr : int
        Number of reactions, forward and reverse.
    photo_re_indx : int
        Number of the first photolysis reaction, or 0 to check all reactions.
    """
    from .chem_funs import re_wM_dict

    if photo_re_indx > 0:
        re_end = photo_re_indx - 1
    else:
        re_end = nr

    dup_list = []
    for re in range(1, re_end, 2):
        for re_oth in range(1, re_end, 2):
            if re != re_oth:
                if (
                    set(re_wM_dict[re][0]) == set(re_wM_dict[re_oth][0])
                    and set(re_wM_dict[re][1]) == set(re_wM_dict[re_oth][1])
                    or set(re_wM_dict[re][0]) == set(re_wM_dict[re_oth][1])
                    and set(re_wM_dict[re][1]) == set(re_wM_dict[re_oth][0])
                ):
                    # if prod of R_re == prod of R_re' and reac of R_re == react of R_re' or reac of R_re == prod of R_re' and prod of R_re == react
                    dup_check = True
                    if {re, re_oth} not in dup_list:
                        dup_list.append({re, re_oth})
                        log.warning(
                            'Re' + str(re) + ' and ' + 'Re' + str(re_oth) + ' are duplicates!'
                        )

    if not dup_list:
        log.info('No duplicates in the network.')

make_Gibbs(re_table, gibbs_text, ofname)

Append the equilibrium constants of the reactions to chem_funs.py.

Writes Gibbs(j, T), the equilibrium constant of forward reaction j in number-density units, K_j = exp(-sum(nu g / RT)) (k_B T / P_0)^(n_reac - n_prod) [(cm3)^(n_reac - n_prod)], with g / RT from the NASA 9-coefficient polynomials (valid for 200 to 6000 K), P_0 = 1 bar, and n_reac and n_prod the numbers of reactant and product molecules without M. op.ReadRate.rev_rate sets the reverse rate k[j+1] = k[j] / K_j.

Parameters:

Name Type Description Default
re_table str

Reaction table from read_network.

required
gibbs_text str

Not used; the functions are always read from paths.GIBBS_FILE.

required
ofname str

File to append to.

required
Source code in src/vulcan/make_chem_funs.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
def make_Gibbs(re_table, gibbs_text, ofname):
    """
    Append the equilibrium constants of the reactions to `chem_funs.py`.

    Writes `Gibbs(j, T)`, the equilibrium constant of forward reaction j in number-density
    units, K_j = exp(-sum(nu g / RT)) (k_B T / P_0)^(n_reac - n_prod) [(cm3)^(n_reac -
    n_prod)], with g / RT from the NASA 9-coefficient polynomials (valid for 200 to 6000 K),
    P_0 = 1 bar, and n_reac and n_prod the numbers of reactant and product molecules
    without M. `op.ReadRate.rev_rate` sets the reverse rate k[j+1] = k[j] / K_j.

    Parameters
    ----------
    re_table : str
        Reaction table from `read_network`.
    gibbs_text : str
        Not used; the functions are always read from `paths.GIBBS_FILE`.
    ofname : str
        File to append to.
    """
    chem_dict = {}
    reac_dict = {}  # reaction dict. packed with v_i
    exp_reac_dict = {}  # explicit reaction dict.
    i = -1
    j = -1  # index of forward reaction(odd number:1,3,5,...)
    count = 0  # count for even/odd term in v_exp
    reac_list = []
    rate_dict = {}

    reac_list, rate_dict, gibbs_dict = [], {}, {}
    gstr = ''

    for line in re_table.splitlines():
        if line == '':
            continue
        elif line[0] == '#':
            continue
        else:
            reac = []
            mol_reac = []
            mol_prod = []
            prod = []
            rate_exp = ''
            rate_str = ''
            v_str = ''
            v_exp = ''  # to store the explicit expression of v_i (for jacobian)
            gibbs = 'np.exp( -('
            R = True
            N = False
            reac_num, prod_num = 0, 0

            # Need to take car of M!!!
            for term in line.split():
                # print 'term' + term
                if term == '+':
                    continue
                elif term == '->':
                    # R=True:reactants R=False:products
                    R = False
                    continue

                # mol_list = [stoi-number, species name]
                mol_list = term.split('*')
                if len(mol_list) == 1:
                    mol_list = [1] + mol_list
                else:
                    mol_list = [int(mol_list[0])] + mol_list[1:]
                mol = mol_list[1]
                stoi = int(mol_list[0])

                # check if the species is already included
                if mol not in chem_dict and not term == 'M':
                    i += 1
                    chem_dict.update({mol: i})
                    reac_dict.update({chem_dict[mol]: ''})
                    exp_reac_dict.update({chem_dict[mol]: ''})
                # if R is true, it's the reactants
                if R:
                    reac.append(mol_list)
                    mol_reac.append(mol)
                else:
                    prod.append(mol_list)
                    mol_prod.append(mol)

            j += 2

            reac_args = list(set(mol_reac + mol_prod))  # Remove repeating elements
            # because set exclude duplicates

            # v_i() is the rate equation function for i
            rate_str = 'v_' + str(j) + '('

            reac_noM = [ele for ele in reac if not ele[1] == 'M']
            prod_noM = [ele for ele in prod if not ele[1] == 'M']
            reac_args_noM = [ele for ele in reac_args if not ele == 'M']

            for term in [ele for ele in reac_args if not ele == 'M']:
                rate_str += 'y[' + str(chem_dict[term]) + '], '
            rate_str = rate_str[0:-2] + ')'

            v_exp += 'k[' + str(j) + ']*'
            for term in reac:
                if term[0] != 1:
                    if term[1] == 'M':
                        v_exp += term[1] + '**' + str(term[0]) + '*'
                    else:
                        v_exp += (
                            'y[' + str(chem_dict[term[1]]) + ']' + '**' + str(term[0]) + '*'
                        )
                else:
                    if term[1] == 'M':
                        v_exp += term[1] + '*'
                    else:
                        v_exp += 'y[' + str(chem_dict[term[1]]) + ']*'
            v_exp = v_exp[0:-1]  # Delete the last '*'

            v_exp += ' - k[' + str(j + 1) + ']*'
            for term in prod:
                if term[0] != 1:
                    if term[1] == 'M':
                        v_exp += term[1] + '**' + str(term[0]) + '*'
                    else:
                        v_exp += (
                            'y[' + str(chem_dict[term[1]]) + ']' + '**' + str(term[0]) + '*'
                        )
                else:
                    if term[1] == 'M':
                        v_exp += term[1] + '*'
                    else:
                        v_exp += 'y[' + str(chem_dict[term[1]]) + ']*'
            v_exp = v_exp[0:-1]  # Delete the last '*'

            for term in reac_noM:
                # term[0] is the stoi-number of the species
                reac_dict[chem_dict[term[1]]] += ' -' + str(term[0]) + '*' + rate_str
                if term[0] == 1:
                    exp_reac_dict[chem_dict[term[1]]] += ' -' + '(' + v_exp + ')'
                    count += 1
                else:
                    exp_reac_dict[chem_dict[term[1]]] += (
                        ' -' + str(term[0]) + '*(' + v_exp + ')'
                    )
                    count += 1

            for term in prod_noM:
                reac_dict[chem_dict[term[1]]] += ' +' + str(term[0]) + '*' + rate_str
                if term[0] == 1:
                    exp_reac_dict[chem_dict[term[1]]] += ' +' + '(' + v_exp + ')'
                    count += 1
                else:
                    exp_reac_dict[chem_dict[term[1]]] += (
                        ' +' + str(term[0]) + '*(' + v_exp + ')'
                    )
                    count += 1

            ######################## for constructing Gibbs free energy ########################
            for term in reac_noM:
                gibbs += '-' + str(term[0]) + '*' + "gibbs_sp('" + str(term[1]) + "',T)"
                reac_num += term[0]

            for term in prod_noM:
                gibbs += '+' + str(term[0]) + '*' + "gibbs_sp('" + str(term[1]) + "',T)"
                prod_num += term[0]

            gibbs += ' ) )'
            if prod_num - reac_num != 0:
                gibbs += '*(corr*T)**' + str(reac_num - prod_num)
            gibbs_dict[j] = gibbs
            ######################## for constructing Gibbs free energy ########################

            v_str = '#' + line + '\n'
            v_str += 'v_' + str(j) + ' = lambda '

            for term in reac_args_noM:
                v_str += term + ', '
            v_str = v_str[0:-2] + ' : '
            # j: ->
            # j+1: <-
            v_str += 'k[' + str(j) + ']*'
            for term in reac:
                if term[0] != 1:
                    v_str += term[1] + '**' + str(term[0]) + '*'
                else:
                    v_str += term[1] + '*'
            v_str = v_str[0:-1]  # Delete the last '*'

            v_str += ' - k[' + str(j + 1) + ']*'
            for term in prod:
                if term[0] != 1:
                    v_str += term[1] + '**' + str(term[0]) + '*'
                else:
                    v_str += term[1] + '*'
            v_str = v_str[0:-1]

            reac_list.append(v_str)

            # ouput of each single rate from k1...
            rate_exp += 'k[' + str(j) + ']*'
            for term in reac:
                if term[1] == 'M':
                    rate_exp += 'M*'
                else:
                    if term[0] == 1:
                        rate_exp += 'y[' + str(chem_dict[term[1]]) + ']*'
                    else:
                        rate_exp += 'y[' + str(chem_dict[term[1]]) + ']**' + str(term[0]) + '*'

            rate_exp = rate_exp[0:-1]  # Delete the last '*'
            rate_dict[j] = rate_exp
            rate_exp = ''
            rate_exp += 'k[' + str(j + 1) + ']*'  # j+1 even number for reverse index
            for term in prod:
                if term[1] == 'M':
                    rate_exp += 'M*'
                else:
                    if term[0] == 1:
                        rate_exp += 'y[' + str(chem_dict[term[1]]) + ']*'
                    else:
                        rate_exp += 'y[' + str(chem_dict[term[1]]) + ']**' + str(term[0]) + '*'
            rate_exp = rate_exp[0:-1]  # Delete the last '*'
            rate_dict[j + 1] = rate_exp

    with open(GIBBS_FILE, 'r') as g:
        for line in g:
            gstr += line

    # the data of 'H2CO' is from Brucat's 2015
    # C2H NASA 9 new from Brucat
    gstr += '\n\n'
    gstr += 'nasa9 = {} \n'
    gstr += 'for i in [ _ for _ in spec_list]: \n'
    gstr += f"    nasa9[i] = np.loadtxt('{THERMO_DIR}/NASA9/' + str(i) + '.txt') \n"
    gstr += '    nasa9[i] = nasa9[i].flatten() \n'
    gstr += "    nasa9[i,'low'] = nasa9[i][0:10] \n"
    gstr += "    nasa9[i,'high'] = nasa9[i][10:20] \n"

    gstr += '\n\n'
    gstr += '# Gibbs free energy:\n'
    gstr += 'def Gibbs(i,T):\n'
    gstr += '\t G={}\n'.expandtabs(3)
    for _ in gibbs_dict:
        gstr += '\t G['.expandtabs(3) + str(_) + '] = lambda T: ' + str(gibbs_dict[_]) + '\n'

    gstr += '\t return G[i](T)\n\n'.expandtabs(3)

    with open(ofname, 'a+') as f:
        f.write(gstr)

make_all(vulcan_cfg)

Generate chem_funs.py from the network and check the network.

Runs the make_* functions in turn, then check_conserv and check_duplicate. It must run before anything imports chem_funs, as vulcan.run_vulcan does: an already imported chem_funs is not reloaded before make_jac reads it.

Parameters:

Name Type Description Default
vulcan_cfg Config

Run configuration; reads network and use_photo.

required

Raises:

Type Description
RuntimeError

If a reaction does not conserve the elements (check_conserv).

Source code in src/vulcan/make_chem_funs.py
 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
def make_all(vulcan_cfg: Config):
    """
    Generate `chem_funs.py` from the network and check the network.

    Runs the `make_*` functions in turn, then `check_conserv` and `check_duplicate`.
    It must run before anything imports `chem_funs`, as `vulcan.run_vulcan` does: an
    already imported `chem_funs` is not reloaded before `make_jac` reads it.

    Parameters
    ----------
    vulcan_cfg : Config
        Run configuration; reads `network` and `use_photo`.

    Raises
    ------
    RuntimeError
        If a reaction does not conserve the elements (`check_conserv`).
    """

    re_table, photo_table, photo_re_indx = read_network(vulcan_cfg)
    ni, nr, species = make_chemdf(re_table, CHEM_FUNS_FILE)
    make_Gibbs(re_table, GIBBS_FILE, CHEM_FUNS_FILE)

    # import the "ofname" module as chemistry for make_jac to read df
    chem_funs = importlib.import_module('.chem_funs', package=__package__)

    # the last function that writes into chem_funs.py
    make_jac(ni, nr, CHEM_FUNS_FILE, chem_funs)
    make_neg_jac(ni, nr, CHEM_FUNS_FILE, chem_funs)

    # reload
    importlib.reload(chem_funs)

    # check network
    check_conserv(nr)
    check_duplicate(nr, photo_re_indx)

make_chemdf(re_table, ofname)

Write the species, the reaction lists and the chemical tendency into chem_funs.py.

The species are numbered in order of first appearance in re_table. For each reaction j with stoichiometric coefficients nu, the net rate is v_j = k[j] prod(y_reac^nu) - k[j+1] prod(y_prod^nu). The main function written is chemdf(y, M, k), the production minus loss dn/dt of every species [cm-3 s-1] for y of shape (nz, ni); df writes the same terms out for the Jacobian.

Parameters:

Name Type Description Default
re_table str

Reaction table from read_network.

required
ofname str

File to write; overwritten.

required

Returns:

Name Type Description
ni int

Number of species.

nr int

Number of reactions, forward and reverse.

species dict_keys

Species names in index order.

Source code in src/vulcan/make_chem_funs.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
def make_chemdf(re_table, ofname):
    """
    Write the species, the reaction lists and the chemical tendency into `chem_funs.py`.

    The species are numbered in order of first appearance in `re_table`. For each
    reaction j with stoichiometric coefficients nu, the net rate is
    v_j = k[j] prod(y_reac^nu) - k[j+1] prod(y_prod^nu). The main function written is
    `chemdf(y, M, k)`, the production minus loss dn/dt of every species [cm-3 s-1] for y of
    shape (nz, ni); `df` writes the same terms out for the Jacobian.

    Parameters
    ----------
    re_table : str
        Reaction table from `read_network`.
    ofname : str
        File to write; overwritten.

    Returns
    -------
    ni : int
        Number of species.
    nr : int
        Number of reactions, forward and reverse.
    species : dict_keys
        Species names in index order.
    """

    chem_dict = {}
    reac_dict = {}  # reaction dict. packed with v_i
    exp_reac_dict = {}  # explicit reaction dict.
    i = -1
    j = -1  # index of forward reaction(odd number:1,3,5,...)
    count = 0  # count for even/odd term in v_exp

    reac_list = []
    rate_dict = {}
    sp_rate = {}  # to store each term of prod and loss individually
    re_sp_dic = {}
    re_reac_prod = {}  # store the products and the reactants for reaction j (without M)
    re_reac_prod_wM = {}  # same as re_reac_prod but including M
    re_dict_str = 're_dict = {'
    re_wM_dict_str = 're_wM_dict = {'  # including M

    for line in re_table.splitlines():
        """
        reac : e.g. [[1, 'H'], [1, 'H'], [1, 'M']]
        reac_args: e.g. ['H2', 'H', 'M']
        """
        # skip the space and #
        if line == '':
            continue
        elif line[0] == '#':
            continue
        else:
            reac = []
            mol_reac = []
            mol_prod = []
            prod = []
            rate_exp = ''
            rate_str = ''
            v_str = ''
            v_exp = ''  # to store the explicit expression of v_i (for jacobian)
            # sp_rate = [] # to store species
            # R = True:reactants  R = False:products
            R = True  # if reads '->'
            N = False

            # Need to take car of M!!!
            for term in line.split():
                if term == '+':
                    continue
                elif term == '->':
                    # R=True:reactants R=False:products
                    R = False
                    continue

                # mol_list = [stoi-number, species name]
                mol_list = term.split('*')
                if len(mol_list) == 1:
                    mol_list = [1] + mol_list
                else:
                    mol_list = [int(mol_list[0])] + mol_list[1:]
                mol = mol_list[1]
                stoi = int(mol_list[0])

                # check if the species is already included
                if mol not in chem_dict and not term == 'M':
                    i += 1
                    chem_dict.update({mol: i})
                    reac_dict.update({chem_dict[mol]: ''})
                    exp_reac_dict.update({chem_dict[mol]: ''})

                    # creating a new list for new species
                    sp_rate[mol] = []

                # if R is true, it's the reactants
                if R:
                    reac.append(mol_list)
                    mol_reac.append(mol)
                else:
                    prod.append(mol_list)
                    mol_prod.append(mol)

            j += 2

            reac_args = list(set(mol_reac + mol_prod))  # Remove repeating elements
            # because set exclude duplicates

            # v_i() is the rate equation function for i
            rate_str = 'v_' + str(j) + '(k, M, '

            reac_noM = [ele for ele in reac if not ele[1] == 'M']
            prod_noM = [ele for ele in prod if not ele[1] == 'M']
            reac_args_noM = [ele for ele in reac_args if not ele == 'M']

            # store the products and the reactants in the 1st and 2nd element for reaction j (without M)
            re_reac_prod[j] = [
                [ele[1] for ele in reac if not ele[1] == 'M'],
                [ele[1] for ele in prod if not ele[1] == 'M'],
            ]
            # store the products and the reactants in the 1st and 2nd element for reaction j (with M)
            re_reac_prod_wM[j] = [[ele[1] for ele in reac], [ele[1] for ele in prod]]
            # skip line
            if j % 51 == 0:
                re_dict_str += '\n'
                re_wM_dict_str += '\n'

            re_dict_str += str(j) + ':' + str(re_reac_prod[j]) + ', '
            # reverse the list "re_reac_prod[j]" for the reverse reaction
            re_dict_str += str(j + 1) + ':' + str(re_reac_prod[j][::-1]) + ', '
            # with M
            re_wM_dict_str += str(j) + ':' + str(re_reac_prod_wM[j]) + ', '
            # reverse
            re_wM_dict_str += str(j + 1) + ':' + str(re_reac_prod_wM[j][::-1]) + ', '

            for term in [ele for ele in reac_args if not ele == 'M']:
                rate_str += 'y[' + str(chem_dict[term]) + '], '
            rate_str = rate_str[0:-2] + ')'

            v_exp += 'k[' + str(j) + ']*'
            for term in reac:
                if term[0] != 1:
                    if term[1] == 'M':
                        v_exp += term[1] + '**' + str(term[0]) + '*'
                    else:
                        v_exp += (
                            'y[' + str(chem_dict[term[1]]) + ']' + '**' + str(term[0]) + '*'
                        )
                else:
                    if term[1] == 'M':
                        v_exp += term[1] + '*'
                    else:
                        v_exp += 'y[' + str(chem_dict[term[1]]) + ']*'
            v_exp = v_exp[0:-1]  # Delete the last '*'
            fv_exp = v_exp

            v_exp += ' - k[' + str(j + 1) + ']*'
            b_exp = ' k[' + str(j + 1) + ']*'

            for term in prod:
                if term[0] != 1:
                    if term[1] == 'M':
                        v_exp += term[1] + '**' + str(term[0]) + '*'
                        b_exp += term[1] + '**' + str(term[0]) + '*'
                    else:
                        v_exp += (
                            'y[' + str(chem_dict[term[1]]) + ']' + '**' + str(term[0]) + '*'
                        )
                        b_exp += (
                            'y[' + str(chem_dict[term[1]]) + ']' + '**' + str(term[0]) + '*'
                        )
                else:
                    if term[1] == 'M':
                        v_exp += term[1] + '*'
                        b_exp += term[1] + '*'
                    else:
                        v_exp += 'y[' + str(chem_dict[term[1]]) + ']*'
                        b_exp += 'y[' + str(chem_dict[term[1]]) + ']*'
            v_exp = v_exp[0:-1]  # Delete the last '*'
            rv_exp = b_exp[0:-1]

            for term in reac_noM:
                # term[0] os the stoi-number of the species
                reac_dict[chem_dict[term[1]]] += ' -' + str(term[0]) + '*' + rate_str

                # for each term of prod and loss individually
                sp_rate[term[1]].append(' -' + str(term[0]) + '*' + fv_exp)
                sp_rate[term[1]].append(' +' + str(term[0]) + '*' + rv_exp)

                if term[0] == 1:
                    exp_reac_dict[chem_dict[term[1]]] += ' -' + '(' + v_exp + ')'
                    count += 1
                else:
                    exp_reac_dict[chem_dict[term[1]]] += (
                        ' -' + str(term[0]) + '*(' + v_exp + ')'
                    )
                    count += 1

            for term in prod_noM:
                reac_dict[chem_dict[term[1]]] += ' +' + str(term[0]) + '*' + rate_str
                sp_rate[term[1]].append(' +' + str(term[0]) + '*' + fv_exp)
                sp_rate[term[1]].append(' -' + str(term[0]) + '*' + rv_exp)

                if term[0] == 1:
                    exp_reac_dict[chem_dict[term[1]]] += ' +' + '(' + v_exp + ')'
                    count += 1
                else:
                    exp_reac_dict[chem_dict[term[1]]] += (
                        ' +' + str(term[0]) + '*(' + v_exp + ')'
                    )
                    count += 1

            v_str = '#' + line + '\n'
            v_str += 'v_' + str(j) + ' = lambda k, M, '

            for term in reac_args_noM:
                v_str += term + ', '
            v_str = v_str[0:-2] + ' : '
            v_str += 'k[' + str(j) + ']*'
            for term in reac:
                if term[0] != 1:
                    v_str += term[1] + '**' + str(term[0]) + '*'
                else:
                    v_str += term[1] + '*'
            v_str = v_str[0:-1]  # Delete the last '*'

            v_str += ' - k[' + str(j + 1) + ']*'
            for term in prod:
                if term[0] != 1:
                    v_str += term[1] + '**' + str(term[0]) + '*'
                else:
                    v_str += term[1] + '*'
            v_str = v_str[0:-1]

            reac_list.append(v_str)

            # ouput of each single rate from k1...
            rate_exp += 'k[' + str(j) + ']*'
            for term in reac:
                if term[1] == 'M':
                    rate_exp += 'M*'
                else:
                    if term[0] == 1:
                        rate_exp += 'y[' + str(chem_dict[term[1]]) + ']*'
                    else:
                        rate_exp += 'y[' + str(chem_dict[term[1]]) + ']**' + str(term[0]) + '*'

            rate_exp = rate_exp[0:-1]  # Delete the last '*'
            rate_dict[j] = rate_exp
            rate_exp = ''
            rate_exp += 'k[' + str(j + 1) + ']*'  # j+1 even number for reverse index
            for term in prod:
                if term[1] == 'M':
                    rate_exp += 'M*'
                else:
                    if term[0] == 1:
                        rate_exp += 'y[' + str(chem_dict[term[1]]) + ']*'
                    else:
                        rate_exp += 'y[' + str(chem_dict[term[1]]) + ']**' + str(term[0]) + '*'
            rate_exp = rate_exp[0:-1]  # Delete the last '*'
            rate_dict[j + 1] = rate_exp

    re_dict_str = re_dict_str[:-2]  # delet the last ','
    re_dict_str += '}\n'
    re_wM_dict_str = re_wM_dict_str[:-2]
    re_wM_dict_str += '}\n'
    # print re_dict_str
    # save output
    chem_dict_r = {}
    spec_list = []

    ofstr = '#!/usr/bin/env python3 \n\n'
    ofstr += '# This file was generated by VULCAN \n\n'
    ofstr += 'import numpy as np \n'
    ofstr += 'from .phy_const import kb, Navo\n\n'

    ofstr += "'''\n## Reaction ##\n\n"
    ofstr += re_table + '\n\n'

    ofstr += '## Mapping ##\n\n'
    for term in chem_dict:
        chem_dict_r.update({chem_dict[term]: term})
    for term in reac_dict:
        ofstr += chem_dict_r[term] + ': y[' + str(term) + '], '
    ofstr += '\n\n'
    for term in reac_dict:
        ofstr += chem_dict_r[term] + '\t' + str(term) + '\t' + reac_dict[term] + '\n'
    for i in chem_dict_r:
        spec_list.append(chem_dict_r[i])

    ofstr += "'''\n\n"

    ofstr += '#species list\n'
    ofstr += 'spec_list = ' + str(spec_list)
    ofstr += '\n# the total number of species'
    ofstr += '\nni = ' + str(len(chem_dict.keys()))
    ofstr += '\n# the total number of reactions (forward and reverse)'
    ofstr += '\nnr = ' + str(len(rate_dict.keys()))

    ofstr += (
        '\n\n# store the products and the reactants in the 1st and the 2nd element for reaction j (without M)\n'
        + re_dict_str
    )
    ofstr += (
        '\n\n# store the products and the reactants in the 1st and the 2nd element for reaction j (with M)\n'
        + re_wM_dict_str
    )

    ost = '\n\ndef chemdf(y, M, k): \n'  # Note: making M as input!!!
    ost += '\t y = np.transpose(y) \n'.expandtabs(3)
    ost += '\t dydt = np.zeros(shape=y.shape) \n'.expandtabs(3)

    # Evaluate each net reaction rate v_i once into a local vi, since a rate enters the
    # tendency of every species it involves
    rate_calls = {}
    chemdf_terms = {}
    for num in reac_dict:
        for call, re_num in findall(r'(v_(\d+)\([^)]*\))', reac_dict[num]):
            rate_calls[int(re_num)] = call
        chemdf_terms[num] = sub(r'v_(\d+)\([^)]*\)', r'v\1', reac_dict[num])
    for re_num in sorted(rate_calls):
        ost += '\t v'.expandtabs(3) + str(re_num) + ' = ' + rate_calls[re_num] + '\n'

    for num in chemdf_terms:
        ost += '\t dydt['.expandtabs(3) + str(num) + '] = ' + chemdf_terms[num] + '\n'

    ost += '\t dydt = np.transpose(dydt) \n'.expandtabs(3)
    ost += '\t return dydt \n\n'.expandtabs(3)

    ost += 'def df(y, M, k):\n'
    ost += '\t df_list = [] \n'.expandtabs(3)
    for num in exp_reac_dict:
        ost += '\t df_list.append( '.expandtabs(3) + exp_reac_dict[num] + ' )\n'
    ost += '\t return df_list \n\n'.expandtabs(3)

    ofstr += ost

    for term in reac_list:
        ofstr += term + '\n\n\n'

    # for rate analysis
    ost = 'def rate_ans(sp): \n'
    ost += '\t rate_str = {}\n'.expandtabs(3)
    ost += '\t re_sp_dic = {}\n'.expandtabs(3)
    for sp in sp_rate:
        ost += '    rate_str["' + sp + '"] = ['
        re_sp_dic[sp] = []
        for i in sp_rate[sp]:
            ost += i
            ost += ','
            start, end = False, False
            for n, letter in enumerate(i):
                if letter == 'k' and not start:
                    k_start = n + 2
                    start = True
                elif letter == ']' and start and not end:
                    k_end = n
                    end = True
                    re_sp_dic[sp].append(int(i[k_start:k_end]))

        ost = ost[0:-1]
        ost += ']'
        ost += '\n'
    ost += '\t return np.array(rate_str[sp]) \n\n'.expandtabs(3)
    ofstr += ost

    log.debug(f'Writing ofstr to {ofname}')
    with open(ofname, 'w') as of:
        of.write(ofstr)

    # return (ni, nr, the list of species)
    return (len(chem_dict.keys()), len(rate_dict.keys()), chem_dict.keys())

make_jac(ni, nr, ofname, chemistry)

Append symjac(y, M, k, nz), the analytical Jacobian of the chemistry, to chem_funs.py.

The Jacobian d(df)/dy is derived symbolically with SymPy from chemistry.df. The generated function returns a dense array of shape (nz ni, nz ni) for the state flattened layer by layer (index layer * ni + species); only the blocks within each layer are filled, since chemistry does not couple layers.

Parameters:

Name Type Description Default
ni int

Number of species.

required
nr int

Number of reactions, forward and reverse.

required
ofname str

File to append to.

required
chemistry module

The chem_funs module written so far, which provides df.

required
Source code in src/vulcan/make_chem_funs.py
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
def make_jac(ni, nr, ofname, chemistry):
    """
    Append `symjac(y, M, k, nz)`, the analytical Jacobian of the chemistry, to `chem_funs.py`.

    The Jacobian d(df)/dy is derived symbolically with SymPy from `chemistry.df`. The
    generated function returns a dense array of shape (nz ni, nz ni) for the state
    flattened layer by layer (index layer * ni + species); only the blocks within each
    layer are filled, since chemistry does not couple layers.

    Parameters
    ----------
    ni : int
        Number of species.
    nr : int
        Number of reactions, forward and reverse.
    ofname : str
        File to append to.
    chemistry : module
        The `chem_funs` module written so far, which provides `df`.
    """
    M = Symbol('M')
    y, k = [], []

    for i in range(ni):
        y.append(Symbol('y[:,' + str(i) + ']'))
    for i in range(nr + 1):
        k.append(Symbol('k[' + str(i) + ']'))

    # chemistry is the "ofname" module
    dy = Matrix(chemistry.df(y, M, k))
    x = Matrix(y)
    jac = dy.jacobian(x)

    jstr = '\ndef symjac(y, M, k, nz): \n'
    jstr += '\t dfdy = np.zeros(shape=[ni*nz, ni*nz])   \n'.expandtabs(3)
    jstr += '\t indx = [] \n'.expandtabs(3)
    jstr += '\t for j in range(ni): \n'.expandtabs(3)
    jstr += '\t indx.append( np.arange(j,j+ni*nz,ni) ) \n'.expandtabs(7)

    for i in range(ni):
        for j in range(ni):
            jstr += (
                '\t dfdy[indx['.expandtabs(3)
                + str(i)
                + '], indx['
                + str(j)
                + ']] = '
                + str(jac[i, j])
                + '\n'
            )

    jstr += '\t return dfdy \n\n'.expandtabs(3)

    # save the output function
    with open(ofname, 'a+') as f:
        f.write(jstr)

make_neg_jac(ni, nr, ofname, chemistry)

Append neg_symjac(y, M, k, nz), the negative of symjac, to chem_funs.py.

The Rosenbrock solver (op.ODESolver.lhs_jac_*) starts from -J, so this saves a sign change of the full matrix at each step. Same layout and arguments as make_jac.

Parameters:

Name Type Description Default
ni int

Number of species.

required
nr int

Number of reactions, forward and reverse.

required
ofname str

File to append to.

required
chemistry module

The chem_funs module written so far, which provides df.

required
Source code in src/vulcan/make_chem_funs.py
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
def make_neg_jac(ni, nr, ofname, chemistry):
    """
    Append `neg_symjac(y, M, k, nz)`, the negative of `symjac`, to `chem_funs.py`.

    The Rosenbrock solver (`op.ODESolver.lhs_jac_*`) starts from -J, so this saves a
    sign change of the full matrix at each step. Same layout and arguments as
    `make_jac`.

    Parameters
    ----------
    ni : int
        Number of species.
    nr : int
        Number of reactions, forward and reverse.
    ofname : str
        File to append to.
    chemistry : module
        The `chem_funs` module written so far, which provides `df`.
    """
    M = Symbol('M')
    y, k = [], []

    for i in range(ni):
        y.append(Symbol('y[:,' + str(i) + ']'))
    for i in range(nr + 1):
        k.append(Symbol('k[' + str(i) + ']'))

    # chemistry is the "ofname" module
    dy = Matrix(chemistry.df(y, M, k))
    x = Matrix(y)
    jac = dy.jacobian(x)

    jstr = '\ndef neg_symjac(y, M, k, nz): \n'
    jstr += '\t dfdy = np.zeros(shape=[ni*nz, ni*nz])   \n'.expandtabs(3)
    jstr += '\t indx = [] \n'.expandtabs(3)
    jstr += '\t for j in range(ni): \n'.expandtabs(3)
    jstr += '\t indx.append( np.arange(j,j+ni*nz,ni) ) \n'.expandtabs(7)

    for i in range(ni):
        for j in range(ni):
            jstr += (
                '\t dfdy[indx['.expandtabs(3)
                + str(i)
                + '], indx['
                + str(j)
                + ']] = -('
                + str(jac[i, j])
                + ')\n'
            )

    jstr += '\t return dfdy \n\n'.expandtabs(3)

    # save the output function
    with open(ofname, 'a+') as f:
        f.write(jstr)

read_network(vulcan_cfg)

Renumber the reactions of the network file and collect them as a reaction table.

The forward reactions get the odd numbers 1, 3, 5, ... in file order (the reverse reaction of n is n + 1), and the network file is overwritten with the new numbers. The section headers set the label of each entry ('#M' for three-body, '#P' for photolysis, and so on). Without use_photo, the photochemical reactions go to a separate table.

Parameters:

Name Type Description Default
vulcan_cfg Config

Run configuration; reads network and use_photo.

required

Returns:

Name Type Description
re_table str

Reaction table for make_chemdf: a header line, then for each reaction a label line such as '#M5' and the reaction such as 'H + H + M -> H2 + M'.

photo_table str

The photolysis, radiative and ionisation reactions left out without use_photo.

photo_re_indx int

Number of the first photolysis reaction, or 0 if the network has none.

Source code in src/vulcan/make_chem_funs.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def read_network(vulcan_cfg: Config):
    """
    Renumber the reactions of the network file and collect them as a reaction table.

    The forward reactions get the odd numbers 1, 3, 5, ... in file order (the reverse
    reaction of n is n + 1), and the network file is overwritten with the new numbers.
    The section headers set the label of each entry ('#M' for three-body, '#P' for
    photolysis, and so on). Without `use_photo`, the photochemical reactions go to a
    separate table.

    Parameters
    ----------
    vulcan_cfg : Config
        Run configuration; reads `network` and `use_photo`.

    Returns
    -------
    re_table : str
        Reaction table for `make_chemdf`: a header line, then for each reaction a label
        line such as '#M5' and the reaction such as 'H + H + M -> H2 + M'.
    photo_table : str
        The photolysis, radiative and ionisation reactions left out without `use_photo`.
    photo_re_indx : int
        Number of the first photolysis reaction, or 0 if the network has none.
    """

    Rf, Rindx = {}, {}
    i = 1
    special_re, photo_re = False, False
    re_end = False

    if vulcan_cfg.use_photo:
        header = 'Chemical Network and Photolysis Reactions'
    else:
        header = 'Chemical Network without Photochemistry'
    ofstr = f'# {header} \n\n'

    photo_str = '# photochemistry \n\n'
    ion_str = '# ionchemistry \n\n'
    re_label = '#R'
    new_network = ''
    photo_re_indx = 0  # The index of first photodissoication reaction

    with open(vulcan_cfg.network, 'r') as f:
        for line in f.readlines():
            # switch to 3-body and dissociation reations
            if line.startswith('# 3-body'):
                re_label = '#M'

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

            elif line.startswith('# condensation'):
                log.debug('Including condensation reactions.')
                special_re = False  # switch to reactions with special forms (hard coded)
                re_label = '#C'

            elif line.startswith('# radiative'):
                re_label = '#R'

            elif line.startswith('# photo'):
                special_re = False  # switch to photo-disscoiation reactions
                photo_re = True
                photo_re_indx = i
                re_label = '#P'

            elif line.startswith('# ionisation'):
                re_label = '#I'

            # skip common lines and blank lines
            # ========================================================================================
            if (
                not line.startswith('#') and line.strip() and not special_re and not re_end
            ):  # if not starts
                Rf[i] = line.partition('[')[-1].rpartition(']')[0].strip()
                li = line.partition(']')[-1].strip()
                columns = li.split()

                # updating the numerical index in the network (1, 3, ...)
                line = '{:<4d} {:s}'.format(i, ''.join(line.partition('[')[1:]))

                if not (not vulcan_cfg.use_photo and photo_re):
                    ofstr += re_label + str(i) + '\n'
                    ofstr += Rf[i] + '\n'

                # storing only the photochemical reactions
                elif re_label == '#P':
                    photo_str += re_label + str(i) + '\n'
                    photo_str += Rf[i] + '\n'

                # storing only the condensation reactions
                elif re_label == '#C':
                    ofstr += re_label + str(i) + '\n'
                    ofstr += Rf[i] + '\n'

                elif re_label == '#R':
                    photo_str += re_label + str(i) + '\n'
                    photo_str += Rf[i] + '\n'

                elif re_label == '#I':
                    photo_str += re_label + str(i) + '\n'
                    photo_str += Rf[i] + '\n'

                i += 2
            # ========================================================================================
            elif special_re and line.strip() and not line.startswith('#') and not re_end:
                # Rindx[i] = int(line.partition('[')[0].strip())
                Rf[i] = line.partition('[')[-1].rpartition(']')[0].strip()
                line = '{:<4d} {:s}'.format(i, ''.join(line.partition('[')[1:]))
                ofstr += re_label + str(i) + '\n'
                ofstr += Rf[i] + '\n'

                i += 2
            new_network += line

    with open(vulcan_cfg.network, 'w+') as f:
        f.write(new_network)
    return ofstr, photo_str, photo_re_indx