<commit_before>"""Writes mechanism header and output testing files
"""

# Python 2 compatibility
from __future__ import division
from __future__ import print_function

# Standard libraries
import os
import sys
import itertools

# Local imports
from .. import utils
from . import chem_utilities as chem

def write_mechanism_initializers(path, lang, specs, reacs,
                                 fwd_spec_mapping, back_spec_mapping,
                                 initial_conditions='', cache_optimized=False,
                                 last_spec=None, auto_diff=False):
    """Writes mechanism-specific files.

    Parameters
    ----------
    path : str
        Path where files are being written.
    lang : {'c', 'cuda', 'fortran', 'matlab'}
        Language type.
    specs : list of `SpecInfo`
        List of species in the mechanism.
    reacs : list of `ReacInfo`
        List of reactions in the mechanism.
    fwd_spec_mapping : list of int
        A mapping of the original mechanism to the new species order
    back_spec_mapping : list of int
        A mapping of the new species order to the original mechanism
    initial_conditions : Optional[str]
        A comma separated list of the initial conditions to use in form
        T,P,X (e.g. '800,1,H2=1.0,O2=0.5'). Temperature in K, P in atm.
    cache_optimized : Optional[bool]
        If ``True``, use the greedy optimizer to attempt to improve cache hit rates
    last_spec : Optional[str]
        If specified, the species to assign to the last index.
        Typically should be N2, Ar, He or another inert bath gas
    auto_diff : Optional[bool]
        If ``True``, generate files for Adept auto_differention library.

    Returns
    -------
    None

    """
    if lang in ['matlab', 'fortran']:
        raise NotImplementedError

    if auto_diff:
        with open(os.path.join(path, 'ad_jac.c'), 'w') as file:
            #need to write the auto_diff jacobian
            file.write("""
#include <vector>
#include "adept.h"
#include "header.h"
#include "ad_dydt.h"
void eval_jacob(const double t, const double p, const double* y,
                         double* jac) {
    using adept::adouble; // Import Stack and adouble from adept
    adept::Stack stack; // Where the derivative information is stored
    std::vector<adouble> in(NSP); // Vector of active input variables
    adept::set_values(&in[0], NSP, y); // Initialize adouble inputs
    adouble pres = p;
    stack.new_recording(); // Start recording
    std::vector<adouble> out(NSP); // Create vector of active output variables
    dydt(t, pres, &in[0], &out[0]); // Run algorithm
    stack.independent(&in[0], NSP); // Identify independent variables
    stack.dependent(&out[0], NSP); // Identify dependent variables
    stack.jacobian(jac); // Compute & store Jacobian in jac
}
            """
            )

    # some information variables
    have_rev_rxns = any(reac.rev for reac in reacs)
    have_pdep_rxns = any(reac.thd_body or reac.pdep for reac in reacs)

    gpu_memory = {'y' : 'NSP',
                  'dy' : 'NSP',
                  'conc' : 'NSP',
                  'fwd_rates' : 'FWD_RATES',
                  'rev_rates' : 'REV_RATES',
                  'spec_rates' : 'NSP',
                  'cp' : 'NSP',
                  'h' : 'NSP',
                  'dBdT' : 'NSP',
                  'jac' : 'NSP * NSP',
                  'var' : '1'
                  }
    if any(len(specs) - 1 in reac.reac + reac.prod and
           utils.get_nu(len(specs) - 1, reac) for reac in reacs
           ):
        gpu_memory['J_nplusjplus'] = 'NSP'
    if any(r.pdep or r.thd_body for r in reacs):
        gpu_memory['pres_mod'] = 'PRES_MOD_RATES'
    if any(r.cheb for r in reacs):
        dim = max(rxn.cheb_n_temp for rxn in reacs if rxn.cheb)
        gpu_memory['dot_prod'] = str(dim)

    # the mechanism header defines a number of useful preprocessor defines, as
    # well as defining method stubs for setting initial conditions
    with open(os.path.join(path, 'mechanism{}'.format(utils.header_ext[lang])),
              'w'
              ) as file:

        file.write('#ifndef MECHANISM_{}\n'.format(utils.header_ext[lang][1:]) +
                   '#define MECHANISM_{}\n\n'.format(utils.header_ext[lang][1:])
                   )

        if lang == 'cuda':
            file.write('#include <cuda.h>\n'
                       '#include <cuda_runtime.h>\n'
                       '#include <helper_cuda.h>\n'
                       '#include "launch_bounds.cuh"\n'
                       '#include "gpu_macros.cuh"\n'
                       )
            file.write('\nstruct mechanism_memory {\n')
            for array in gpu_memory:
                file.write('  double * {};\n'.format(array))
            file.write('};\n\n')
        if lang == 'c':
            file.write('#include <string.h>\n') # for memset

        # make cache optimized easy to recognize
        if cache_optimized:
            file.write('//Cache Optimized\n')
        file.write('//last_spec {}\n'.format(last_spec))

        # convience: write species indexes
        file.write('/* Species Indexes\n')
        file.write('\n'.join('{}  {}'.format(i, spec.name)
                             for i, spec in enumerate(specs)
                             )
                   )
        file.write('*/\n\n')
<commit_msg>add a newline in order to make parsing the species names easier<commit_after>"""Writes mechanism header and output testing files
"""

# Python 2 compatibility
from __future__ import division
from __future__ import print_function

# Standard libraries
import os
import sys
import itertools

# Local imports
from .. import utils
from . import chem_utilities as chem

def write_mechanism_initializers(path, lang, specs, reacs,
                                 fwd_spec_mapping, back_spec_mapping,
                                 initial_conditions='', cache_optimized=False,
                                 last_spec=None, auto_diff=False):
    """Writes mechanism-specific files.

    Parameters
    ----------
    path : str
        Path where files are being written.
    lang : {'c', 'cuda', 'fortran', 'matlab'}
        Language type.
    specs : list of `SpecInfo`
        List of species in the mechanism.
    reacs : list of `ReacInfo`
        List of reactions in the mechanism.
    fwd_spec_mapping : list of int
        A mapping of the original mechanism to the new species order
    back_spec_mapping : list of int
        A mapping of the new species order to the original mechanism
    initial_conditions : Optional[str]
        A comma separated list of the initial conditions to use in form
        T,P,X (e.g. '800,1,H2=1.0,O2=0.5'). Temperature in K, P in atm.
    cache_optimized : Optional[bool]
        If ``True``, use the greedy optimizer to attempt to improve cache hit rates
    last_spec : Optional[str]
        If specified, the species to assign to the last index.
        Typically should be N2, Ar, He or another inert bath gas
    auto_diff : Optional[bool]
        If ``True``, generate files for Adept auto_differention library.

    Returns
    -------
    None

    """
    if lang in ['matlab', 'fortran']:
        raise NotImplementedError

    if auto_diff:
        with open(os.path.join(path, 'ad_jac.c'), 'w') as file:
            #need to write the auto_diff jacobian
            file.write("""
#include <vector>
#include "adept.h"
#include "header.h"
#include "ad_dydt.h"
void eval_jacob(const double t, const double p, const double* y,
                         double* jac) {
    using adept::adouble; // Import Stack and adouble from adept
    adept::Stack stack; // Where the derivative information is stored
    std::vector<adouble> in(NSP); // Vector of active input variables
    adept::set_values(&in[0], NSP, y); // Initialize adouble inputs
    adouble pres = p;
    stack.new_recording(); // Start recording
    std::vector<adouble> out(NSP); // Create vector of active output variables
    dydt(t, pres, &in[0], &out[0]); // Run algorithm
    stack.independent(&in[0], NSP); // Identify independent variables
    stack.dependent(&out[0], NSP); // Identify dependent variables
    stack.jacobian(jac); // Compute & store Jacobian in jac
}
            """
            )

    # some information variables
    have_rev_rxns = any(reac.rev for reac in reacs)
    have_pdep_rxns = any(reac.thd_body or reac.pdep for reac in reacs)

    gpu_memory = {'y' : 'NSP',
                  'dy' : 'NSP',
                  'conc' : 'NSP',
                  'fwd_rates' : 'FWD_RATES',
                  'rev_rates' : 'REV_RATES',
                  'spec_rates' : 'NSP',
                  'cp' : 'NSP',
                  'h' : 'NSP',
                  'dBdT' : 'NSP',
                  'jac' : 'NSP * NSP',
                  'var' : '1'
                  }
    if any(len(specs) - 1 in reac.reac + reac.prod and
           utils.get_nu(len(specs) - 1, reac) for reac in reacs
           ):
        gpu_memory['J_nplusjplus'] = 'NSP'
    if any(r.pdep or r.thd_body for r in reacs):
        gpu_memory['pres_mod'] = 'PRES_MOD_RATES'
    if any(r.cheb for r in reacs):
        dim = max(rxn.cheb_n_temp for rxn in reacs if rxn.cheb)
        gpu_memory['dot_prod'] = str(dim)

    # the mechanism header defines a number of useful preprocessor defines, as
    # well as defining method stubs for setting initial conditions
    with open(os.path.join(path, 'mechanism{}'.format(utils.header_ext[lang])),
              'w'
              ) as file:

        file.write('#ifndef MECHANISM_{}\n'.format(utils.header_ext[lang][1:]) +
                   '#define MECHANISM_{}\n\n'.format(utils.header_ext[lang][1:])
                   )

        if lang == 'cuda':
            file.write('#include <cuda.h>\n'
                       '#include <cuda_runtime.h>\n'
                       '#include <helper_cuda.h>\n'
                       '#include "launch_bounds.cuh"\n'
                       '#include "gpu_macros.cuh"\n'
                       )
            file.write('\nstruct mechanism_memory {\n')
            for array in gpu_memory:
                file.write('  double * {};\n'.format(array))
            file.write('};\n\n')
        if lang == 'c':
            file.write('#include <string.h>\n') # for memset

        # make cache optimized easy to recognize
        if cache_optimized:
            file.write('//Cache Optimized\n')
        file.write('//last_spec {}\n'.format(last_spec))

        # convience: write species indexes
        file.write('/* Species Indexes\n')
        file.write('\n'.join('{}  {}'.format(i, spec.name)
                             for i, spec in enumerate(specs)
                             )
                   )
        file.write('\n*/\n\n')

{'fraction_non_alphanumeric': 0.11507789317507418, 'fraction_numerical': 0.004080118694362018, 'mean_word_length': 1.9604721383475159, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4124115', 'n_tokens_mistral': 3321, 'n_tokens_neox': 3196, 'n_words': 947}