forked from mgiulini/pymap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
libio.py
126 lines (105 loc) · 3.76 KB
/
libio.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
"""Library to perform input-output tasks."""
import argparse
import os
from pathlib import Path
def parse_arguments():
"""Parse and check the command-line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--parameters", help="dat input parameter file")
parser.add_argument(
"-v",
"--verbose",
help="increase output verbosity",
action="store_true"
)
args = parser.parse_args()
print(args.__dict__)
# checks
if not args.parameters:
raise Exception("Parameter file is mandatory")
if args.verbose:
print("verbosity turned on")
return args
def check_output_file(cleaned_pars):
"""If the output_filename already exists, block the execution."""
output_fl = cleaned_pars["output_filename"]
output_path = Path(output_fl)
if output_path.is_file():
raise Exception(f"Output file {output_fl} already existing. Aborting")
return
def system_parameters_setup(parfile):
"""Set up the parameters."""
pars = read_parfile(parfile)
check_mandatory_parameters(pars)
cleaned_pars = check_optional_parameters(pars)
print(f"Cleaned Parameters {cleaned_pars}")
check_output_file(cleaned_pars)
return cleaned_pars
def read_parfile(parfile_string):
"""Read parameter file."""
parfile = Path(parfile_string)
print("reading parameters file ", parfile)
if parfile.is_file is False:
raise Exception("Parameter file not existing. Aborting.")
parameters = {}
with open(parfile, "r") as pars:
for ln in pars:
if ln.startswith("#") is False:
split_list = ln.split()
if len(split_list) != 2:
raise Exception(f"badly formatted parameter line\n{ln}")
else:
par_name = split_list[0]
par_value = split_list[1]
parameters[par_name] = par_value
print("parameter ", par_name, " = ", par_value)
return parameters
def check_mandatory_parameters(parameters):
"""Check the existence of mandatory parameters."""
mandatory_keys = [
"input_filename",
"output_filename"
]
observed_pars = parameters.keys()
for par in mandatory_keys:
if par not in observed_pars:
raise Exception(f"missing parameter {par}")
return
def check_optional_parameters(parameters):
"""Check the existence of optional parameters. Set to default if absent."""
optional_keys = {
"max_binom": ["integer", 100000],
}
observed_pars = parameters.keys()
for optk in optional_keys.keys():
if optk not in observed_pars:
parameters[optk] = optional_keys[optk][1]
else:
if optional_keys[optk][0] == "integer":
parameters[optk] = int(parameters[optk])
if optional_keys[optk][0] == "float":
parameters[optk] = float(parameters[optk])
return parameters
def output_mappings(mapping_dict, mapping_order, output_filename):
"""
Functions that outputs the mappings to a file.
Parameters
----------
mapping_dict : dict
dictionary of mappings
mapping_order : list
list of ordered mappings
output_filename : str
"""
header = "N\tmapping\ttrans_mapping\ths\thk\tsmap\tsmap_inf" + os.linesep
with open(output_filename, "w") as wfile:
# write header
wfile.write(header)
for ord_map in mapping_order:
output_str = []
for elem in mapping_dict[ord_map]:
if isinstance(elem, float):
output_str.append(f"{elem:.6f}")
else:
output_str.append(f"{elem}")
wfile.write("\t".join(output_str) + os.linesep)