Skip to content

Refactor/csvbuilder #98

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Mar 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 6 additions & 16 deletions pythonfmu/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
from .osutil import get_lib_extension, get_platform
from ._version import __version__
from .fmi2slave import FMI2_MODEL_OPTIONS, Fmi2Slave
from .csvslave import create_csv_slave

FilePath = Union[str, Path]
HERE = Path(__file__).parent
Expand Down Expand Up @@ -73,11 +72,8 @@ def build_FMU(
script_file = Path(script_file)
if not script_file.exists():
raise ValueError(f"No such file {script_file!s}")
if not script_file.suffix.endswith(".py") and not script_file.suffix.endswith(".csv"):
raise ValueError(f"File {script_file!s} must have extension '.py' or '.csv'!")

if script_file.suffix.endswith(".csv"):
project_files = {script_file}
if not script_file.suffix.endswith(".py"):
raise ValueError(f"File {script_file!s} must have extension '.py'!")

dest = Path(dest)
if not dest.exists():
Expand All @@ -95,13 +91,7 @@ def build_FMU(

with tempfile.TemporaryDirectory(prefix="pythonfmu_") as tempd:
temp_dir = Path(tempd)
if script_file.suffix.endswith(".csv"):
py_file = temp_dir / (script_file.stem + ".py")
with open(py_file, "+w") as f:
f.write(create_csv_slave(script_file))
script_file = py_file
else:
shutil.copy2(script_file, temp_dir)
shutil.copy2(script_file, temp_dir)

# Embed pythonfmu in the FMU so it does not need to be included
dep_folder = temp_dir / "pythonfmu"
Expand Down Expand Up @@ -210,7 +200,7 @@ def has_binary() -> bool:

def main():
parser = argparse.ArgumentParser(
prog="pythonfmu-builder", description="Build an FMU from a Python script or CSV file."
prog="pythonfmu-builder", description="Build an FMU from a Python script."
)

parser.add_argument(
Expand All @@ -224,7 +214,7 @@ def main():
"-f",
"--file",
dest="script_file",
help="Path to the Python script or CSV file.",
help="Path to the Python script.",
required=True,
)

Expand Down Expand Up @@ -252,7 +242,7 @@ def main():
"project_files",
metavar="Project files",
nargs="*",
help="Additional project files required by the Python script. Ignored when using CSV input.",
help="Additional project files required by the Python script.",
default=set(),
)

Expand Down
79 changes: 78 additions & 1 deletion pythonfmu/csvslave.py → pythonfmu/csvbuilder.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import argparse
import tempfile
from pathlib import Path
from typing import Union
from typing import Union, Optional
from ._version import __version__
from .fmi2slave import FMI2_MODEL_OPTIONS
from .builder import FmuBuilder

FilePath = Union[str, Path]


def create_csv_slave(csvfile: FilePath):
classname = csvfile.stem
filename = csvfile.name
Expand Down Expand Up @@ -94,3 +101,73 @@ def do_step(self, current_time: float, step_size: float) -> bool:
self.find_indices(current_time, step_size)
return True
"""


class CsvFmuBuilder:

@staticmethod
def build_FMU(
csv_file: FilePath,
dest: FilePath = ".",
documentation_folder: Optional[FilePath] = None,
**options,
) -> Path:

if not csv_file.exists():
raise ValueError(f"No such file {csv_file!s}")
if not csv_file.suffix.endswith(".csv"):
raise ValueError(f"File {csv_file!s} must have extension '.csv'!")

options["project_files"] = {csv_file}

with tempfile.TemporaryDirectory(prefix="pythonfmu_") as tempd:
temp_dir = Path(tempd)
script_file = temp_dir / (csv_file.stem + ".py")
with open(script_file, "+w") as f:
f.write(create_csv_slave(csv_file))
options["script_file"] = script_file
return FmuBuilder.build_FMU(**options)


def main():
parser = argparse.ArgumentParser(
prog="pythonfmu-csvbuilder", description="Build an FMU from a Python script or CSV file."
)

parser.add_argument(
"-v",
"--version",
action="version",
version=__version__
)

parser.add_argument(
"-f",
"--file",
dest="script_file",
help="Path to the CSV file.",
required=True,
)

parser.add_argument(
"-d", "--dest", dest="dest", help="Where to save the FMU.", default="."
)

parser.add_argument(
"--doc",
dest="documentation_folder",
help="Documentation folder to include in the FMU.",
default=None,
)

for option in FMI2_MODEL_OPTIONS:
action = "store_false" if option.value else "store_true"
parser.add_argument(
f"--{option.cli}",
dest=option.name,
help=f"If given, {option.name}={action[6:]}",
action=action
)

options = vars(parser.parse_args())
CsvFmuBuilder.build_FMU(**options)
4 changes: 2 additions & 2 deletions pythonfmu/tests/test_csvslave.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pytest
from pathlib import Path

from pythonfmu.builder import FmuBuilder
from pythonfmu.csvbuilder import CsvFmuBuilder

EPS = 1e-7
DEMO = "csvdemo.csv"
Expand All @@ -13,7 +13,7 @@ def test_csvslave(tmp_path):

csv_file = Path(__file__).parent / DEMO

fmu = FmuBuilder.build_FMU(csv_file, dest=tmp_path)
fmu = CsvFmuBuilder.build_FMU(csv_file, dest=tmp_path)
assert fmu.exists()

model_description = fmpy.read_model_description(fmu)
Expand Down
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ pythonfmu =
console_scripts =
pythonfmu-builder = pythonfmu.builder:main
pythonfmu-deploy = pythonfmu.deploy:main
pythonfmu-csvbuilder = pythonfmu.csvbuilder:main

[options.extras_require]
tests =
Expand Down