Commit 38f14166 authored by Antoine Berchet's avatar Antoine Berchet
Browse files

Applying flake8 rules

parent 915e36d4
......@@ -7,7 +7,4 @@ import glob
modules = glob.glob(dirname(__file__) + "/*")
__all__ = [basename(f) for f in modules
if isdir(f) and not f.endswith('.py')]
__all__ = [basename(f) for f in modules if isdir(f) and not f.endswith(".py")]
......@@ -8,22 +8,23 @@ def main():
The only required argument is the defintion Yaml file
"""
# Parses the arguments given to the script
# Use the following command to see the script helper:
# $python -m pycif -h
cmd_parser = argparse.ArgumentParser(
description='Runs pyCIF from a given Yaml file')
cmd_parser.add_argument('def_file', type=str,
help="path to the Yaml configuration file")
cmd_parser.add_argument("--debug", help="debug mode",
action="store_true")
description="Runs pyCIF from a given Yaml file"
)
cmd_parser.add_argument(
"def_file", type=str, help="path to the Yaml configuration file"
)
cmd_parser.add_argument("--debug", help="debug mode", action="store_true")
args = vars(cmd_parser.parse_args())
# Run pyCIF
Setup.run_simu(args)
if __name__ == '__main__':
if __name__ == "__main__":
main()
......@@ -6,5 +6,8 @@ import glob
modules = glob.glob(dirname(__file__) + "/*")
__all__ = [basename(f) for f in modules
if isdir(f) and not f.endswith('.py') and 'pycache' not in f]
__all__ = [
basename(f)
for f in modules
if isdir(f) and not f.endswith(".py") and "pycache" not in f
]
......@@ -9,7 +9,6 @@ import glob
modules = glob.glob(dirname(__file__) + "/*")
__all__ = [basename(f) for f in modules
if isdir(f) and not f.endswith('.py')]
__all__ = [basename(f) for f in modules if isdir(f) and not f.endswith(".py")]
from . import register
......@@ -9,17 +9,17 @@ from pycif.utils.path import init_dir
default_values = {
# Max number of reactants/reaction
'nreactamax': 4,
"nreactamax": 4,
# Number of tabul. temperatures for stoichio.
'ntemps': 4,
"ntemps": 4,
# Max number of rate constants
'ntabmax': 22,
"ntabmax": 22,
# Max number of tabulated photolysis levels
'nlevphotmax': 50,
"nlevphotmax": 50,
# Max number of tabulated zenith angles
'ntabuzenmax': 20,
"ntabuzenmax": 20,
# Max number of photolysis reactions
'nphotmax': 50,
"nphotmax": 50,
}
......@@ -34,24 +34,25 @@ def ini_data(self, **kwargs):
Updates on the fly the chemistry
"""
info('Initializing the Chemistry')
info("Initializing the Chemistry")
# Copying the chemical scheme to the working directory
workdir = self.workdir
dirchem_ref = '{}/chemical_scheme/{}/'.format(workdir, self.schemeid)
dirchem_ref = "{}/chemical_scheme/{}/".format(workdir, self.schemeid)
self.dirchem_ref = dirchem_ref
shutil.rmtree(dirchem_ref, ignore_errors=True)
init_dir(dirchem_ref)
# If pre-computed scheme is specified
if hasattr(self, 'dir_precomp'):
copy_tree('{}/{}/'.format(self.dir_precomp, self.schemeid),
dirchem_ref)
if hasattr(self, "dir_precomp"):
copy_tree(
"{}/{}/".format(self.dir_precomp, self.schemeid), dirchem_ref
)
# Read chemistry
self.read_chemicalscheme(**kwargs)
# Otherwise, initialize files from the yaml
else:
self.create_chemicalscheme()
......@@ -4,7 +4,7 @@ import pandas as pd
import numpy as np
import re
from pycif.utils.path import init_dir
from.utils import create_mandchem, create_optchem
from .utils import create_mandchem, create_optchem
def create_chemicalscheme(self):
......@@ -13,76 +13,85 @@ def create_chemicalscheme(self):
species attributes
consistently with the data retrieved
"""
# Common variables
workdir = self.workdir
mecachim = self.schemeid
dirchem_ref = self.dirchem_ref
# Initializes number of species and reactions
self.nacspecies = len(self.acspecies.attributes) \
if hasattr(self, 'acspecies') else 0
self.nemisspec = len(self.emis_species.attributes) \
if hasattr(self, 'emis_species') else 0
self.nemisspec_interp = len(self.emis_species_interp.attributes) \
if hasattr(self, 'emis_species_interp') else 0
self.nprspecies = len(self.prescrconcs.attributes) \
if hasattr(self, 'prescrconcs') else 0
self.nprodspecies = len(self.prodloss3d.attributes) \
if hasattr(self, 'prodloss3d') else 0
self.ndepspecies = len(self.deposition.attributes) \
if hasattr(self, 'deposition') else 0
self.nreacs = len(self.reactions.attributes) \
if hasattr(self, 'reactions') else 0
self.nfamilies = len(self.families.attributes) \
if hasattr(self, 'families') else 0
self.nacspecies = (
len(self.acspecies.attributes) if hasattr(self, "acspecies") else 0
)
self.nemisspec = (
len(self.emis_species.attributes)
if hasattr(self, "emis_species")
else 0
)
self.nemisspec_interp = (
len(self.emis_species_interp.attributes)
if hasattr(self, "emis_species_interp")
else 0
)
self.nprspecies = (
len(self.prescrconcs.attributes) if hasattr(self, "prescrconcs") else 0
)
self.nprodspecies = (
len(self.prodloss3d.attributes) if hasattr(self, "prodloss3d") else 0
)
self.ndepspecies = (
len(self.deposition.attributes) if hasattr(self, "deposition") else 0
)
self.nreacs = (
len(self.reactions.attributes) if hasattr(self, "reactions") else 0
)
self.nfamilies = (
len(self.families.attributes) if hasattr(self, "families") else 0
)
# Cleaning the target directory
os.system('rm -rf {}'.format(dirchem_ref))
os.system("rm -rf {}".format(dirchem_ref))
init_dir(dirchem_ref)
# List of files
finf = '{}/chemical_scheme.nml'.format(dirchem_ref)
filer = '{}/REACTIONS.{}'.format(dirchem_ref, mecachim)
fileps = '{}/PRESCRIBED_SPECIES.{}'.format(dirchem_ref, mecachim)
filepl = '{}/PRODLOSS_SPECIES.{}'.format(dirchem_ref, mecachim)
filedp = '{}/DEPO_SPECIES.{}'.format(dirchem_ref, mecachim)
filea = '{}/ANTHROPIC.{}'.format(dirchem_ref, mecachim)
fileb = '{}/BIOGENIC.{}'.format(dirchem_ref, mecachim)
finf = "{}/chemical_scheme.nml".format(dirchem_ref)
filer = "{}/REACTIONS.{}".format(dirchem_ref, mecachim)
fileps = "{}/PRESCRIBED_SPECIES.{}".format(dirchem_ref, mecachim)
filepl = "{}/PRODLOSS_SPECIES.{}".format(dirchem_ref, mecachim)
filedp = "{}/DEPO_SPECIES.{}".format(dirchem_ref, mecachim)
filea = "{}/ANTHROPIC.{}".format(dirchem_ref, mecachim)
fileb = "{}/BIOGENIC.{}".format(dirchem_ref, mecachim)
mandatory_files = [filer, fileps, filepl, filedp]
create_mandchem(self, mandatory_files)
files = '{}/STOICHIOMETRY.{}'.format(dirchem_ref, mecachim)
filec = '{}/CHEMISTRY.{}'.format(dirchem_ref, mecachim)
filerr = '{}/REACTION_RATES.{}'.format(dirchem_ref, mecachim)
filej = '{}/PHOTO_RATES.{}'.format(dirchem_ref, mecachim)
filef = '{}/FAMILIES.{}'.format(dirchem_ref, mecachim)
fileals = '{}/ALL_SPECIES.{}'.format(dirchem_ref, mecachim)
fileas = '{}/ACTIVE_SPECIES.{}'.format(dirchem_ref, mecachim)
files = "{}/STOICHIOMETRY.{}".format(dirchem_ref, mecachim)
filec = "{}/CHEMISTRY.{}".format(dirchem_ref, mecachim)
filerr = "{}/REACTION_RATES.{}".format(dirchem_ref, mecachim)
filej = "{}/PHOTO_RATES.{}".format(dirchem_ref, mecachim)
filef = "{}/FAMILIES.{}".format(dirchem_ref, mecachim)
fileals = "{}/ALL_SPECIES.{}".format(dirchem_ref, mecachim)
fileas = "{}/ACTIVE_SPECIES.{}".format(dirchem_ref, mecachim)
nallqmax, nphoto_rates = create_optchem(self, filer, fileps)
# Create chemical_scheme.nml namelist
os.system('echo "&args" > {}'.format(finf))
os.system('echo "fnacspec = \'{}\'" >> {}'.format(fileas, finf))
os.system('echo "fnallspec = \'{}\'" >> {}'.format(fileals, finf))
os.system('echo "fnprescr = \'{}\'" >> {}'.format(fileps, finf))
os.system('echo "fnprodl = \'{}\'" >> {}'.format(filepl, finf))
os.system('echo "fndep = \'{}\'" >> {}'.format(filedp, finf))
os.system('echo "fnchem = \'{}\'" >> {}'.format(filec, finf))
os.system('echo "fnstoi = \'{}\'" >> {}'.format(files, finf))
os.system('echo "fnrates = \'{}\'" >> {}'.format(filerr, finf))
os.system('echo "fnjrates = \'{}\'" >> {}'.format(filej, finf))
os.system('echo "fnfamilies = \'{}\'" >> {}'.format(filef, finf))
os.system("echo \"fnacspec = '{}'\" >> {}".format(fileas, finf))
os.system("echo \"fnallspec = '{}'\" >> {}".format(fileals, finf))
os.system("echo \"fnprescr = '{}'\" >> {}".format(fileps, finf))
os.system("echo \"fnprodl = '{}'\" >> {}".format(filepl, finf))
os.system("echo \"fndep = '{}'\" >> {}".format(filedp, finf))
os.system("echo \"fnchem = '{}'\" >> {}".format(filec, finf))
os.system("echo \"fnstoi = '{}'\" >> {}".format(files, finf))
os.system("echo \"fnrates = '{}'\" >> {}".format(filerr, finf))
os.system("echo \"fnjrates = '{}'\" >> {}".format(filej, finf))
os.system("echo \"fnfamilies = '{}'\" >> {}".format(filef, finf))
os.system('echo "iqmax = {}" >> {}'.format(self.nspecies, finf))
os.system('echo "iallqmax = {}" >> {}'.format(nallqmax, finf))
os.system(
'echo "iprescrmax = {}" >> {}'.format(self.nprspecies, finf))
os.system(
'echo "iprodmax = {}" >> {}'.format(self.nprodspecies, finf))
os.system(
'echo "idepmax = {}" >> {}'.format(self.ndepspecies, finf))
os.system('echo "iprescrmax = {}" >> {}'.format(self.nprspecies, finf))
os.system('echo "iprodmax = {}" >> {}'.format(self.nprodspecies, finf))
os.system('echo "idepmax = {}" >> {}'.format(self.ndepspecies, finf))
os.system('echo "nreac = {}" >> {}'.format(self.nreacs, finf))
os.system('echo "ijratesmax = {}" >> {}'.format(nphoto_rates, finf))
os.system('echo "/" >> {}'.format(finf))
......@@ -6,8 +6,7 @@ import pandas as pd
import os
def read_chemicalscheme(chemistry,
**kwargs):
def read_chemicalscheme(chemistry, **kwargs):
"""Reads a chemical scheme from existing files
Args:
......@@ -20,55 +19,59 @@ def read_chemicalscheme(chemistry,
Notes:
"""
info('Reading Chemistry')
info("Reading Chemistry")
workdir = chemistry.workdir
dirchem_ref = '{}/chemical_scheme/{}/'.format(workdir, chemistry.schemeid)
dirchem_ref = "{}/chemical_scheme/{}/".format(workdir, chemistry.schemeid)
# ACTIVE SPECIES
file_chem = '{}/ACTIVE_SPECIES.{}'.format(dirchem_ref,
chemistry.schemeid)
acspecies = pd.read_csv(file_chem, header=None, sep=' ',
usecols=[0, 1], names=['ID', 'name'])
chemistry.acspecies = \
chemistry.from_dict({s: None for s in acspecies['name']})
file_chem = "{}/ACTIVE_SPECIES.{}".format(dirchem_ref, chemistry.schemeid)
acspecies = pd.read_csv(
file_chem, header=None, sep=" ", usecols=[0, 1], names=["ID", "name"]
)
chemistry.acspecies = chemistry.from_dict(
{s: None for s in acspecies["name"]}
)
chemistry.nacspecies = len(acspecies)
# ANTHROPIC
file_chem = '{}/ANTHROPIC.{}'.format(dirchem_ref,
chemistry.schemeid)
emis_species = pd.read_csv(file_chem, header=None, sep=' ',
usecols=[0, 1], names=['ID', 'name'])
chemistry.emis_species = \
chemistry.from_dict({s: None for s in emis_species['name']})
file_chem = "{}/ANTHROPIC.{}".format(dirchem_ref, chemistry.schemeid)
emis_species = pd.read_csv(
file_chem, header=None, sep=" ", usecols=[0, 1], names=["ID", "name"]
)
chemistry.emis_species = chemistry.from_dict(
{s: None for s in emis_species["name"]}
)
chemistry.nemisspec = len(emis_species)
# BIOGENIC
file_chem = '{}/BIOGENIC.{}'.format(dirchem_ref,
chemistry.schemeid)
bio_species = pd.read_csv(file_chem, header=None, sep=' ',
usecols=[0, 1], names=['ID', 'name'])
chemistry.bio_species = \
chemistry.from_dict({s: None for s in bio_species['name']})
file_chem = "{}/BIOGENIC.{}".format(dirchem_ref, chemistry.schemeid)
bio_species = pd.read_csv(
file_chem, header=None, sep=" ", usecols=[0, 1], names=["ID", "name"]
)
chemistry.bio_species = chemistry.from_dict(
{s: None for s in bio_species["name"]}
)
chemistry.nemisspec_interp = len(bio_species)
# DEPO_SPEC
file_chem = '{}/DEPO_SPEC.{}'.format(dirchem_ref,
chemistry.schemeid)
dep_species = pd.read_csv(file_chem, header=None, sep=' ',
usecols=[0], names=['name'])
chemistry.dep_species = \
chemistry.from_dict({s: None for s in dep_species['name']})
file_chem = "{}/DEPO_SPEC.{}".format(dirchem_ref, chemistry.schemeid)
dep_species = pd.read_csv(
file_chem, header=None, sep=" ", usecols=[0], names=["name"]
)
chemistry.dep_species = chemistry.from_dict(
{s: None for s in dep_species["name"]}
)
chemistry.ndepspecies = len(dep_species)
# CHEMISTRY
with open(dirchem_ref + 'CHEMISTRY.' + chemistry.schemeid, 'r') as fsp:
with open(dirchem_ref + "CHEMISTRY." + chemistry.schemeid, "r") as fsp:
ln = fsp.readlines()
chemistry.nreacs = len(ln)
with open(dirchem_ref + 'FAMILIES.' + chemistry.schemeid, 'r') as fsp:
with open(dirchem_ref + "FAMILIES." + chemistry.schemeid, "r") as fsp:
ln = fsp.readlines()
chemistry.nfamilies = len(ln)
chemistry.nprspecies = 4 ##### en dur pour le moment
......@@ -13,29 +13,29 @@ def create_mandchem(chemistry, mandatory_files):
Create the mandatory chemistry files using the chemistry config yml file
"""
for mfile in mandatory_files:
os.system('touch {}'.format(mfile))
os.system("touch {}".format(mfile))
# Chemical reactions
with open(mandatory_files[0], 'w') as f:
with open(mandatory_files[0], "w") as f:
if chemistry.nreacs > 0:
for attr in chemistry.reactions.attributes:
reac = getattr(chemistry.reactions, attr)
f.write(reac + '\n')
if hasattr(chemistry, 'prescrconcs'):
with open(mandatory_files[1], 'w') as f:
f.write(reac + "\n")
if hasattr(chemistry, "prescrconcs"):
with open(mandatory_files[1], "w") as f:
for attr in chemistry.prescrconcs.attributes:
f.write(attr + '\n')
if hasattr(chemistry, 'prodloss3d'):
with open(mandatory_files[2], 'w') as f:
f.write(attr + "\n")
if hasattr(chemistry, "prodloss3d"):
with open(mandatory_files[2], "w") as f:
for attr in chemistry.prodloss3d.attributes:
f.write(attr + '\n')
if hasattr(chemistry, 'deposition'):
with open(mandatory_files[3], 'w') as f:
f.write(attr + "\n")
if hasattr(chemistry, "deposition"):
with open(mandatory_files[3], "w") as f:
for attr in chemistry.deposition.attributes:
f.write(attr + '\n')
f.write(attr + "\n")
def create_optchem(chemistry, filer, fileps):
......@@ -52,60 +52,79 @@ def create_optchem(chemistry, filer, fileps):
fileps (str): path to the file with prescribed species
"""
workdir = chemistry.workdir
dirchem_ref = chemistry.dirchem_ref
mecachim = chemistry.schemeid
files = '{}/STOICHIOMETRY.{}'.format(dirchem_ref, mecachim)
filec = '{}/CHEMISTRY.{}'.format(dirchem_ref, mecachim)
filerr = '{}/REACTION_RATES.{}'.format(dirchem_ref, mecachim)
filej = '{}/PHOTO_RATES.{}'.format(dirchem_ref, mecachim)
filef = '{}/FAMILIES.{}'.format(dirchem_ref, mecachim)
fileals = '{}/ALL_SPECIES.{}'.format(dirchem_ref, mecachim)
fileas = '{}/ACTIVE_SPECIES.{}'.format(dirchem_ref, mecachim)
fileanth = '{}/ANTHROPIC.{}'.format(dirchem_ref, mecachim)
filebio = '{}/BIOGENIC.{}'.format(dirchem_ref, mecachim)
os.system('rm -f {} {} {} {}'.format(files, filec, filerr, filef))
files = "{}/STOICHIOMETRY.{}".format(dirchem_ref, mecachim)
filec = "{}/CHEMISTRY.{}".format(dirchem_ref, mecachim)
filerr = "{}/REACTION_RATES.{}".format(dirchem_ref, mecachim)
filej = "{}/PHOTO_RATES.{}".format(dirchem_ref, mecachim)
filef = "{}/FAMILIES.{}".format(dirchem_ref, mecachim)
fileals = "{}/ALL_SPECIES.{}".format(dirchem_ref, mecachim)
fileas = "{}/ACTIVE_SPECIES.{}".format(dirchem_ref, mecachim)
fileanth = "{}/ANTHROPIC.{}".format(dirchem_ref, mecachim)
filebio = "{}/BIOGENIC.{}".format(dirchem_ref, mecachim)
os.system("rm -f {} {} {} {}".format(files, filec, filerr, filef))
# Read reactions
df_reac = pd.read_csv(filer, index_col=False, header=None,
comment='#', engine="python", delim_whitespace=True)
df_reac = pd.read_csv(
filer,
index_col=False,
header=None,
comment="#",
engine="python",
delim_whitespace=True,
)
# Read prescribed species
prescribed_species = np.array([])
if exists(fileps) and getsize(fileps) > 0:
df_prescr = pd.read_csv(fileps, index_col=False, header=None,
comment='#', engine="python",
delim_whitespace=True)
df_prescr = pd.read_csv(
fileps,
index_col=False,
header=None,
comment="#",
engine="python",
delim_whitespace=True,
)
prescribed_species = df_prescr[0]
nonactive = np.append(prescribed_species, ['O2', 'X', None])
nonactive = np.append(prescribed_species, ["O2", "X", None])
# Create stoechiometry and chemistry
parts = df_reac[0].str.split('->', n=2, expand=True)
parts = df_reac[0].str.split("->", n=2, expand=True)
left_hand_sides = parts[0]
right_hand_sides = parts[1]
losses = left_hand_sides.str.split('+', expand=True)
nlosses = left_hand_sides.str.split('+').apply(len)
losses = left_hand_sides.str.split("+", expand=True)
nlosses = left_hand_sides.str.split("+").apply(len)
losses.insert(0, -1, nlosses)
prods = right_hand_sides.str.split('+', expand=True)
prods = right_hand_sides.str.split("+", expand=True)
nprods = pd.Series(np.sum(~pd.isnull(prods).values, axis=1))
prods.insert(0, -1, nprods)
prods_spec = np.copy(prods.values)
stoichiometry = np.zeros((1, 6))
for (i, j), value in np.ndenumerate(prods.values[:, 1:]):
try:
prods_list = prods.values[i, j + 1].split('*')
prods_list = prods.values[i, j + 1].split("*")
if len(prods_list) > 1:
arr = np.array(
[prods_list[1], prods_list[0], prods_list[0], prods_list[0],
prods_list[0], i + 1])
stoichiometry = np.append(stoichiometry, arr[np.newaxis, ...],
axis=0)
[
prods_list[1],
prods_list[0],
prods_list[0],
prods_list[0],
prods_list[0],
i + 1,
]
)
stoichiometry = np.append(
stoichiometry, arr[np.newaxis, ...], axis=0
)
if prods_list[-1] not in nonactive:
prods_spec[i, j + 1] = prods_list[-1]
else:
......@@ -117,19 +136,19 @@ def create_optchem(chemistry, filer, fileps):
file_chemistry = np.append(losses.values, prods_spec, axis=1)
file_chemistry = pd.DataFrame(file_chemistry)
stoichiometry = pd.DataFrame(stoichiometry[1:])
# Create reactions
reactions = df_reac[1].values
reactions_rates, nphoto_rates = read_react(reactions, filej)
reactions_rates = pd.DataFrame(reactions_rates)
# Active species
chemistry.nspecies = len(chemistry.acspecies.attributes)
# Create active_species (output_species) and all_species
output_species = np.array(chemistry.acspecies.attributes)
all_species = np.append(output_species, prescribed_species, axis=0)
type_spec = np.array([['type']])
type_spec = np.array([["type"]])
acinfos = np.array([0, 0])
type_spec = np.broadcast_to(type_spec, (all_species.shape[0], 1))
acinfos = np.broadcast_to(acinfos, (output_species.shape[0], 2))
......@@ -137,27 +156,27 @@ def create_optchem(chemistry, filer, fileps):
output_species = np.append(output_species[:, np.newaxis], acinfos, axis=1)
for i in range(output_species.shape[0]):
outspec = getattr(chemistry.acspecies, output_species[i, 0])
output_species[i, 1] = str(getattr(outspec, 'restart_id'))
output_species[i, 2] = str(getattr(outspec, 'mass'))
output_species[i, 1] = str(getattr(outspec, "restart_id"))
output_species[i, 2] = str(getattr(outspec, "mass"))