Skip to content

Commit bf6d884

Browse files
committed
mfile cleanup
1 parent d9a939b commit bf6d884

10 files changed

Lines changed: 237 additions & 781 deletions

File tree

process/core/io/mfile/cli.py

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
import json
2+
13
import click
24

5+
from process.core.io.mfile import MFile
36
from process.core.io.mfile.mfile_comparison import compare_mfiles
4-
from process.core.io.mfile.mfile_to_csv import to_csv
5-
from process.core.io.tools import mfile_arg, mfile_opt, save
7+
from process.core.io.tools import mfile_arg, mfile_opt, save, scan_opt
68

79

810
@click.group()
@@ -16,17 +18,27 @@ def mfile():
1618
"-v",
1719
"--variables",
1820
type=str,
19-
help="Optional list of variables or file with list of variables to extract",
21+
help="Optional list of variables or json file with list of variables to extract",
2022
)
2123
@click.option(
2224
"-fmt",
2325
"--format",
2426
"format_",
25-
type=click.Choice(["json", "csv", "toml", "yaml", "pickle"]),
27+
type=click.Choice(["json", "csv", "toml"]),
2628
)
27-
def convert(mfile, variables, format_):
29+
@scan_opt
30+
@click.option("--verbose", is_flag=True)
31+
def convert(mfile, variables, format_, scan, verbose):
2832
"""Convert MFile to other formats."""
29-
to_csv(mfile, variables)
33+
if variables.endswith(".json"):
34+
with open(variables) as f:
35+
variables = json.load(f)["variables"]
36+
else:
37+
variables = list(filter(None, variables.replace(" ", ":").split(":")))
38+
39+
getattr(MFile(mfile), f"to_{format_}")(
40+
keys_to_write=variables, scan=scan, verbose=verbose
41+
)
3042

3143

3244
@mfile.command("compare", no_args_is_help=True)

process/core/io/mfile/mfile.py

Lines changed: 102 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
from collections import OrderedDict
2828
from typing import Any
2929

30+
import numpy as np
31+
3032
logger = logging.getLogger(__name__)
3133

3234

@@ -337,52 +339,118 @@ def add_to_mfile_variable(self, des, name, value, unit, flag, scan=None):
337339
self.data[var_key] = var
338340
self.data[var_key].set_scan(1, value)
339341

340-
def write_to_json(self, keys_to_write=None, scan=-1, verbose=False):
342+
def to_dict(self, keys=None, scan: int | None = -1, verbose=False) -> dict:
343+
"""Convert MFile to dictionary
344+
345+
Parameters
346+
----------
347+
keys :
348+
keys to select
349+
scan :
350+
scan to select
351+
verbose :
352+
verbosity of output
353+
"""
354+
355+
if keys is None:
356+
keys = self.data.keys()
357+
358+
def _get_data(item, dat_key):
359+
data = self.data[item].get_scan(dat_key)
360+
des = self.data[item].var_description.replace("_", " ")
361+
return {"value": data, "description": des} if verbose else data
362+
363+
save_range = (
364+
range(1, self.data["rmajor"].get_number_of_scans() + 1)
365+
if scan is None
366+
else [scan]
367+
)
368+
output = {
369+
f"scan-{i + 1}": {
370+
item: _get_data(
371+
item, -1 if self.data[item].get_number_of_scans() == 1 else i
372+
)
373+
for item in keys
374+
}
375+
for i in save_range
376+
}
377+
return (
378+
output[next(iter(output.keys()))]
379+
if len(output.keys()) == 1 and scan is not None
380+
else output
381+
)
382+
383+
def to_json(self, keys_to_write=None, scan: int | None = -1, verbose=False):
341384
"""Write MFILE object to JSON file
342385
343386
Parameters
344387
----------
345388
keys_to_write :
346-
(Default value = None)
389+
keys to select
347390
scan :
348-
(Default value = -1)
391+
scan to select
349392
verbose :
350-
(Default value = False)
393+
verbosity of output
351394
"""
352395

353-
if keys_to_write is None:
354-
keys_to_write = self.data.keys()
355-
356396
filename = f"{self.filename}.json"
357397

358-
dict_to_write = {}
359-
360-
if scan == 0:
361-
for i in range(self.data["rmajor"].get_number_of_scans()):
362-
sub_dict = {}
363-
for item in keys_to_write:
364-
dat_key = -1 if self.data[item].get_number_of_scans() == 1 else i + 1
365-
data = self.data[item].get_scan(dat_key)
366-
des = self.data[item].var_description.replace("_", " ")
367-
entry = {"value": data, "description": des} if verbose else data
368-
sub_dict[item] = entry
369-
dict_to_write[f"scan-{i + 1}"] = sub_dict
370-
else:
371-
for item in keys_to_write:
372-
# Initialize dat_key properly based on the number of scans
373-
if self.data[item].get_number_of_scans() == 1:
374-
dat_key = -1
375-
else:
376-
dat_key = (
377-
scan if scan > 0 else 1
378-
) # Default to scan 1 if not specified
379-
data = self.data[item].get_scan(dat_key)
380-
des = self.data[item].var_description.replace("_", " ")
381-
entry = {"value": data, "description": des} if verbose else data
382-
dict_to_write[item] = entry
383-
384398
with open(filename, "w") as fp:
385-
json.dump(dict_to_write, fp, indent=4)
399+
json.dump(self.to_dict(keys_to_write, scan, verbose), fp, indent=4)
400+
401+
def to_toml(self, keys_to_write=None, scan: int | None = -1, verbose=False):
402+
"""Write MFILE object to JSON file
403+
404+
Parameters
405+
----------
406+
keys_to_write :
407+
keys to select
408+
scan :
409+
scan to select
410+
verbose :
411+
verbosity of output
412+
"""
413+
import toml
414+
415+
with open(f"{self.filename}.toml", "w") as file:
416+
toml.dump(self.to_dict(keys_to_write, scan, verbose), file)
417+
418+
def to_csv(self, keys_to_write=None, scan=-1, verbose=False):
419+
"""Write to csv file.
420+
421+
Parameters
422+
----------
423+
args : string, list of tuples
424+
input filename, variable data
425+
csv_outfile :
426+
427+
output_data :
428+
(Default value = None)
429+
"""
430+
output_data = []
431+
if scan is None:
432+
for scan_key, vals in self.to_dict(
433+
keys_to_write, scan=scan, verbose=verbose
434+
).items():
435+
output_data.extend((
436+
(scan_key, "", ""),
437+
("Description", "Varname", "Value"),
438+
))
439+
for k, v in vals.items():
440+
output_data.append((v["description"], k, v["value"]))
441+
else:
442+
output_data.append(("Description", "Varname", "Value"))
443+
for k, v in self.to_dict(keys_to_write, scan=scan, verbose=verbose).items():
444+
output_data.append((v["description"], k, v["value"]))
445+
np.savetxt(
446+
f"{self.filename}.csv",
447+
output_data or [],
448+
fmt="%.5e",
449+
delimiter=",",
450+
header="PROCESS MFILE converted to csv",
451+
footer="",
452+
comments="",
453+
)
386454

387455

388456
def sort_value(value_words: list[str]) -> str | float:

0 commit comments

Comments
 (0)