-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcli.py
More file actions
237 lines (205 loc) · 7.91 KB
/
cli.py
File metadata and controls
237 lines (205 loc) · 7.91 KB
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
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
155
156
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
import json
import logging
import os
from pathlib import Path
import click
import orhelper
from ._helpers import extract_ork_from_zip, parse_ork_file
from .nb_builder import NotebookBuilder
from .ork_extractor import ork_extractor
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y.%b.%d %H:%M:%S",
filename="serializer.log",
filemode="w",
)
logger = logging.getLogger(__name__)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
console.setFormatter(formatter)
logger.addHandler(console)
@click.group()
@click.version_option()
def cli():
"""RocketSerializer.
This library has as objective to convert .ork files into parameters.json, so
that they can be used in rocketpy simulations. It also provides the option
to convert the parameters.json file into a .ipynb file, so that the user can
run the simulation using Jupyter Notebooks.
Examples
--------
To easily use the library, you can use the command line interface. For
example, to generate a .json file from a .ork file, you can use the
following command on your terminal:
>>> ork2json("rocket.ork", "rocket", "motor.eng")
If you want to use the library with Python, you can import the library and
use the functions directly. For example, to generate a .json file from a
.ork file, you can use the following code:
>>> from rocketserializer import ork2json
>>> ork2json([ "--filepath", "rocket.ork", "--eng", "motor.eng"])
If you want to convert a .ork file to a Jupyter Notebook, you can use the
following command on your terminal:
>>> ork2notebook("rocket.ork", "rocket", "motor.eng")
"""
@cli.command("ork2json")
@click.option(
"--filepath", type=click.Path(), required=True, help="The path to the .ork file."
)
@click.option(
"--output", type=click.Path(), required=False, help="The path to the output folder."
)
@click.option(
"--ork_jar",
type=click.Path(),
default=None,
required=False,
help="The path to the OpenRocket .jar file.",
)
@click.option("--encoding", type=str, default="utf-8", required=False)
@click.option("--verbose", type=bool, default=False, required=False)
def ork2json(filepath, output=None, ork_jar=None, encoding="utf-8", verbose=False):
"""Generates a .json file from the .ork file.
The .json file will be generated in the output folder using the information
of the .ork file. It is possible to specify the .eng file to extract the
thrust curve from it. If the .eng file is not specified, the thrust curve
will be extracted from the .ork file.
Parameters
----------
filepath : str
The path to the .ork file.
output : str
The path to the output folder.
ork_jar : str, optional
The path to the OpenRocket .jar file. If unspecified, the .jar file
will be searched in the current directory.
encoding : str, optional
The encoding of the .json file. Default is 'utf-8'.
verbose : bool, optional
If True, the log level will be set to DEBUG. Default is False.
Raises
------
ValueError
In case the .ork file does not contain the simulation data.
ValueError
In case the .ork file is not in English.
"""
log_level = logging.DEBUG if verbose else logging.WARNING
logger.setLevel(log_level)
filepath = Path(filepath)
if not filepath.exists():
error = (
"[ork2json] The .ork file or zip archive does not exist. "
"Please specify a valid path."
)
logger.error(error)
raise FileNotFoundError(error)
if filepath.suffix.lower() == ".ork":
extract_dir = filepath.parent
filepath = extract_ork_from_zip(filepath, extract_dir)
logger.info("[ork2json] Extracted .ork file to: %s", filepath.as_posix())
bs, datapoints = parse_ork_file(filepath)
if len(datapoints) == 0:
error_msg = (
"[ork2json] The file must contain the simulation data.\n"
+ "Open the .ork file and run the simulation first."
)
logger.error(error_msg)
raise ValueError(error_msg)
data_labels = bs.find("databranch").attrs["types"].split(",")
if "CG location" not in data_labels:
message = (
"[ork2json] The file must contain the simulation data.\n"
+ "Open the .ork file and run the simulation first."
)
logger.error(message)
raise ValueError(message)
if not ork_jar:
# get any .jar file in the current directory that starts with "OpenRocket"
ork_jar = [
f for f in os.listdir() if f.startswith("OpenRocket") and f.endswith(".jar")
]
if len(ork_jar) == 0:
raise ValueError(
"[ork2json] It was not possible to find the OpenRocket .jar file in "
"the current directory. Please specify the path to the .jar file."
)
ork_jar = ork_jar[0]
logger.info(
"[ork2json] Found OpenRocket .jar file: '%s'", Path(ork_jar).as_posix()
)
if not output:
# get the same folder as the .ork file
output = os.path.dirname(filepath)
logger.warning(
"[ork2json] Output folder not specified. Using '%s' instead.",
Path(output).as_posix(),
)
# orhelper options are: OFF, ERROR, WARN, INFO, DEBUG, TRACE and ALL
# log_level = "OFF" if verbose else "OFF"
# TODO: even if the log level is set to OFF, the orhelper still prints msgs
with orhelper.OpenRocketInstance(ork_jar, log_level="OFF") as instance:
# create the output folder if it does not exist
if os.path.exists(output) is False:
os.mkdir(output)
orh = orhelper.Helper(instance)
ork = orh.load_doc(str(filepath))
settings = ork_extractor(
bs=bs,
filepath=str(filepath),
output_folder=output,
ork=ork,
)
with open(
os.path.join(output, "parameters.json"), "w", encoding=encoding
) as convert_file:
convert_file.write(
json.dumps(settings, indent=4, sort_keys=True, ensure_ascii=False)
)
logger.info(
"[ork2json] The file 'parameters.json' was saved to: '%s'",
Path(output).as_posix(),
)
logger.info(
"[ork2json] Operation completed successfully. You can now use "
"the 'parameters.json' file to run a simulation."
)
@cli.command("ork2notebook")
@click.option("--filepath", type=str, required=True)
@click.option("--output", type=str, required=False)
@click.option("--ork_jar", type=str, default=None, required=False)
@click.option("--encoding", type=str, default="utf-8", required=False)
@click.option("--verbose", type=bool, default=False, required=False)
def ork2notebook(filepath, output, ork_jar=None, encoding="utf-8", verbose=False):
"""Generates a .ipynb file from the .ork file.
Notes
-----
Under the hood, this function uses the `ork2json` function to generate the
parameters.json file and then uses the `NotebookBuilder` class to generate
the .ipynb file.
"""
if not output:
filepath = Path(filepath)
output = filepath.parent
logger.warning(
"[ork2notebook] Output folder not specified. Using '%s' instead.",
Path(output).as_posix(),
)
ork2json(
[
"--filepath",
filepath,
"--output",
output,
"--ork_jar",
ork_jar,
"--encoding",
encoding,
"--verbose",
verbose,
],
standalone_mode=False,
)
instance = NotebookBuilder(parameters_json=os.path.join(output, "parameters.json"))
instance.build(destination=output)