From 3105d383d315cfe4de06159a3a60ce7a2111debb Mon Sep 17 00:00:00 2001 From: Hendrik van der Stok Date: Fri, 12 Apr 2024 12:27:37 +0200 Subject: [PATCH 1/3] fix errors due to new version of ebcpy=0.3.14 --- aixcalibuha/sensitivity_analysis/sensitivity_analyzer.py | 2 +- aixcalibuha/utils/visualizer.py | 2 +- examples/__init__.py | 2 +- setup.py | 2 +- tests/test_modelica_cal_sen.py | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/aixcalibuha/sensitivity_analysis/sensitivity_analyzer.py b/aixcalibuha/sensitivity_analysis/sensitivity_analyzer.py index 6b4d288b..180c840c 100644 --- a/aixcalibuha/sensitivity_analysis/sensitivity_analyzer.py +++ b/aixcalibuha/sensitivity_analysis/sensitivity_analyzer.py @@ -146,7 +146,7 @@ def __init__(self, self.savepath_sim = pathlib.Path(self.savepath_sim) # Setup the logger - self.logger = setup_logger(cd=self.cd, name=self.__class__.__name__) + self.logger = setup_logger(working_directory=self.cd, name=self.__class__.__name__) # Setup default values self.problem: dict = None diff --git a/aixcalibuha/utils/visualizer.py b/aixcalibuha/utils/visualizer.py index 552f9bcb..38dc2c0b 100644 --- a/aixcalibuha/utils/visualizer.py +++ b/aixcalibuha/utils/visualizer.py @@ -67,7 +67,7 @@ def __init__(self, cd, name, calibration_class, logger=None): self._tuner_paras = None self._goals = None if logger is None: - self.logger = setup_logger(cd=cd, name=name) + self.logger = setup_logger(working_directory=cd, name=name) else: if not isinstance(logger, logging.Logger): raise TypeError(f"Given logger is of type {type(logger)} " diff --git a/examples/__init__.py b/examples/__init__.py index 8a921fa4..006ec741 100644 --- a/examples/__init__.py +++ b/examples/__init__.py @@ -32,7 +32,7 @@ def setup_fmu(examples_dir, example="B", n_cpu=1): else: raise ValueError("Only example 'A' and 'B' are available") - return FMU_API(cd=examples_dir.joinpath("testzone"), + return FMU_API(working_directory=examples_dir.joinpath("testzone"), model_name=model_name, log_fmu=False, n_cpu=n_cpu) diff --git a/setup.py b/setup.py index 4bfff100..c3358ec6 100644 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ 'matplotlib>=3.3.4', 'pandas>=1.3.5', 'SALib>=1.4.6', - 'ebcpy>=0.3.0', + 'ebcpy>=0.3.14', 'toml>=0.10.2' ] diff --git a/tests/test_modelica_cal_sen.py b/tests/test_modelica_cal_sen.py index 943104f8..8cc8acee 100644 --- a/tests/test_modelica_cal_sen.py +++ b/tests/test_modelica_cal_sen.py @@ -67,7 +67,7 @@ def setUp(self): else: model_name = aixcalibuha_dir.joinpath("examples", "model", "PumpAndValve_linux.fmu") - self.sim_api = FMU_API(cd=self.example_cal_dir, + self.sim_api = FMU_API(working_directory=self.example_cal_dir, model_name=model_name) def test_modelica_calibrator(self): @@ -133,7 +133,7 @@ def setUp(self): else: model_name = aixcalibuha_dir.joinpath("examples", "model", "PumpAndValve_linux.fmu") - self.sim_api = FMU_API(cd=self.result_dir, + self.sim_api = FMU_API(working_directory=self.result_dir, model_name=model_name) def test_sa_morris(self): From 309a0ea02883eb194e56bdbe86691e7fabfd44fc Mon Sep 17 00:00:00 2001 From: Hendrik van der Stok Date: Fri, 12 Apr 2024 15:00:39 +0200 Subject: [PATCH 2/3] chore: rename cd to working_directory --- aixcalibuha/calibration/calibrator.py | 23 ++++---- .../calibration/multi_class_calibrator.py | 32 ++++++----- .../sensitivity_analyzer.py | 57 ++++++++++++------- aixcalibuha/sensitivity_analysis/sobol.py | 4 +- aixcalibuha/utils/configuration.py | 4 +- aixcalibuha/utils/visualizer.py | 50 ++++++++-------- examples/__init__.py | 10 ++-- examples/docs/e1_A_energy_system_analysis.md | 12 ++-- examples/docs/e1_B_energy_system_analysis.md | 8 +-- .../e2_A_optimization_problem_definition.md | 6 +- .../e2_B_optimization_problem_definition.md | 6 +- ..._1_verbose_sensitivity_analysis_example.md | 6 +- ...ose_dymola_sensitivity_analysis_example.md | 8 +-- .../docs/e3_sensitivity_analysis_example.md | 11 ++-- ...ose_dymola_sensitivity_analysis_example.md | 8 +-- ...e3_verbose_sensitivity_analysis_example.md | 6 +- examples/docs/e4_calibration_example.md | 6 +- examples/docs/e5_automated_process.md | 2 +- examples/e1_A_energy_system_analysis.py | 20 +++---- examples/e1_B_energy_system_analysis.py | 10 ++-- .../e2_A_optimization_problem_definition.py | 8 +-- .../e2_B_optimization_problem_definition.py | 8 +-- ..._1_verbose_sensitivity_analysis_example.py | 10 ++-- ...ose_dymola_sensitivity_analysis_example.py | 12 ++-- examples/e3_sensitivity_analysis_example.py | 8 +-- examples/e4_calibration_example.py | 10 ++-- examples/e5_automated_process.py | 6 +- .../e6_multiprocessing_calibration_example.py | 4 +- .../e1_A_energy_system_analysis.ipynb | 6 +- .../e1_B_energy_system_analysis.ipynb | 6 +- ...e2_A_optimization_problem_definition.ipynb | 6 +- ...e2_B_optimization_problem_definition.ipynb | 6 +- ...verbose_sensitivity_analysis_example.ipynb | 6 +- ..._dymola_sensitivity_analysis_example.ipynb | 6 +- .../e3_sensitivity_analysis_example.ipynb | 2 +- ..._dymola_sensitivity_analysis_example.ipynb | 6 +- ...verbose_sensitivity_analysis_example.ipynb | 6 +- .../e4_calibration_example.ipynb | 2 +- .../e5_automated_process.ipynb | 2 +- tests/test_config.py | 4 +- tests/test_data_types.py | 4 +- tests/test_modelica_cal_sen.py | 8 +-- tutorial/tutorial.ipynb | 10 ++-- 43 files changed, 227 insertions(+), 208 deletions(-) diff --git a/aixcalibuha/calibration/calibrator.py b/aixcalibuha/calibration/calibrator.py index 69bad510..1d86a77e 100644 --- a/aixcalibuha/calibration/calibrator.py +++ b/aixcalibuha/calibration/calibrator.py @@ -5,9 +5,10 @@ import os import json +from pathlib import Path import time import logging -from typing import Dict +from typing import Dict, Union from copy import copy import numpy as np import pandas as pd @@ -22,7 +23,7 @@ class Calibrator(Optimizer): This class can Calibrator be used for single time-intervals of calibration. - :param str,os.path.normpath cd: + :param str,Path working_directory: Working directory :param ebcpy.simulationapi.SimulationAPI sim_api: Simulation-API for running the models @@ -91,7 +92,7 @@ class Calibrator(Optimizer): """ def __init__(self, - cd: str, + working_directory: Union[Path, str], sim_api: SimulationAPI, calibration_class: CalibrationClass, **kwargs): @@ -133,7 +134,7 @@ def __init__(self, f"{type(keyword_value).__name__} but should be type bool") # %% Initialize all public parameters - super().__init__(cd, **kwargs) + super().__init__(working_directory, **kwargs) # Set sim_api self.sim_api = sim_api @@ -158,7 +159,7 @@ def __init__(self, # De-register the logger setup in the optimization class: if self.verbose_logging: self.logger = visualizer.CalibrationVisualizer( - cd=cd, + working_directory=working_directory, name=self.__class__.__name__, calibration_class=self.calibration_class, logger=self.logger, @@ -166,13 +167,13 @@ def __init__(self, ) else: self.logger = visualizer.CalibrationLogger( - cd=cd, + working_directory=working_directory, name=self.__class__.__name__, calibration_class=self.calibration_class, logger=self.logger ) - self.cd_of_class = cd # Single class does not need an extra folder + self.working_directory_of_class = working_directory # Single class does not need an extra folder # Set the output interval according the the given Goals mean_freq = self.goals.get_meas_frequency() @@ -217,7 +218,7 @@ def obj(self, xk, *args): try: # Generate the folder name for the calibration if self.save_files: - savepath_files = os.path.join(self.sim_api.cd, + savepath_files = os.path.join(self.sim_api.working_directory, f"simulation_{self._counter}") _filepath = self.sim_api.simulate( parameters=parameters, @@ -280,7 +281,7 @@ def mp_obj(self, x, *args): _filepaths = self.sim_api.simulate( parameters=parameter_list, return_option="savepath", - savepath=self.sim_api.cd, + savepath=self.sim_api.working_directory, result_file_name=result_file_names, fail_on_error=self.fail_on_error, inputs=self.calibration_class.inputs, @@ -394,7 +395,7 @@ def calibrate(self, framework, method=None, **kwargs) -> dict: # Setup the visualizer for plotting and logging: self.logger.calibrate_new_class(self.calibration_class, - cd=self.cd_of_class, + working_directory=self.working_directory_of_class, for_validation=False) self.logger.log_initial_names() @@ -521,7 +522,7 @@ def validate(self, validation_class: CalibrationClass, calibration_result: Dict, self.sim_api.sim_setup.start_time = start_time self.logger.calibrate_new_class(self.calibration_class, - cd=self.cd_of_class, + working_directory=self.working_directory_of_class, for_validation=True) # Use the results parameter vector to simulate again. diff --git a/aixcalibuha/calibration/multi_class_calibrator.py b/aixcalibuha/calibration/multi_class_calibrator.py index 8ff888ab..12317b35 100644 --- a/aixcalibuha/calibration/multi_class_calibrator.py +++ b/aixcalibuha/calibration/multi_class_calibrator.py @@ -4,8 +4,11 @@ """ import os -from typing import List +from pathlib import Path +from typing import List, Union import numpy as np +from ebcpy.simulationapi import SimulationAPI + from aixcalibuha import CalibrationClass, data_types from aixcalibuha.calibration import Calibrator @@ -51,8 +54,8 @@ class MultipleClassCalibrator(Calibrator): merge_multiple_classes = True def __init__(self, - cd: str, - sim_api, + working_directory: Union[Path, str], + sim_api: SimulationAPI, calibration_classes: List[CalibrationClass], start_time_method: str = 'fixstart', calibration_strategy: str = 'parallel', @@ -85,7 +88,7 @@ def __init__(self, self.calibration_strategy = calibration_strategy.lower() # Instantiate parent-class - super().__init__(cd, sim_api, calibration_classes[0], **kwargs) + super().__init__(working_directory, sim_api, calibration_classes[0], **kwargs) # Merge the multiple calibration_classes if self.merge_multiple_classes: self.calibration_classes = data_types.merge_calibration_classes(calibration_classes) @@ -114,15 +117,15 @@ def calibrate(self, framework, method=None, **kwargs) -> dict: # Iterate over the different existing classes for cal_class in self.calibration_classes: - #%% Working-Directory: + # %% Working-Directory: # Alter the working directory for saving the simulations-results - self.cd_of_class = os.path.join(self.cd, - f"{cal_class.name}_" - f"{cal_class.start_time}_" - f"{cal_class.stop_time}") - self.sim_api.set_cd(self.cd_of_class) + self.working_directory_of_class = os.path.join(self.working_directory, + f"{cal_class.name}_" + f"{cal_class.start_time}_" + f"{cal_class.stop_time}") + self.sim_api.set_working_directory(self.working_directory_of_class) - #%% Calibration-Setup + # %% Calibration-Setup # Reset counter for new calibration self._counter = 0 # Retrieve already calibrated parameters (i.e. calibrated in the previous classes) @@ -160,11 +163,11 @@ def calibrate(self, framework, method=None, **kwargs) -> dict: else: self.bounds = [(0, 1) for i in range(len(self.x0))] - #%% Execution + # %% Execution # Run the single ModelicaCalibration super().calibrate(framework=framework, method=method, **kwargs) - #%% Post-processing + # %% Post-processing # Append result to list for future perturbation based on older results. self._cal_history.append({"res": self._current_best_iterate, "cal_class": cal_class}) @@ -261,7 +264,8 @@ def check_intersection_of_tuner_parameters(self): self.logger.log("The tuner parameters used for evaluation " "are averaged as follows:\n " "{}".format(' ,'.join([f"{tuner}={value}" - for tuner, value in average_tuner_parameter.items()]))) + for tuner, value in + average_tuner_parameter.items()]))) # Create result-dictionary res_tuner = average_tuner_parameter diff --git a/aixcalibuha/sensitivity_analysis/sensitivity_analyzer.py b/aixcalibuha/sensitivity_analysis/sensitivity_analyzer.py index 180c840c..8f0dc745 100644 --- a/aixcalibuha/sensitivity_analysis/sensitivity_analyzer.py +++ b/aixcalibuha/sensitivity_analysis/sensitivity_analyzer.py @@ -3,8 +3,9 @@ import abc import copy import os -import pathlib +from pathlib import Path import multiprocessing as mp +import warnings from typing import List from collections import Counter import numpy as np @@ -94,7 +95,7 @@ class SenAnalyzer(abc.ABC): number of samples produced, but relates to the total number of samples produced in a manner dependent on the sampler method used. See the documentation of the specific method in the SALib for more information. - :keyword str,os.path.normpath cd: + :keyword str,Path working_directory: The path for the current working directory. Logger and results will be stored here. :keyword boolean fail_on_error: @@ -115,8 +116,8 @@ class SenAnalyzer(abc.ABC): Supported options can be extracted from the ebcpy.TimeSeriesData.save() function. Default is 'pyarrow'. - :keyword str,os.path.normpath savepath_sim: - Default is cd. Own directory for the time series data sets of all simulations + :keyword str,Path savepath_sim: + Default is working_directory. Own directory for the time series data sets of all simulations during the sensitivity analysis. The own dir can be necessary for large data sets, because they can crash IDE during indexing when they are in the project folder. @@ -137,16 +138,25 @@ def __init__(self, self.suffix_files = kwargs.pop('suffix_files', 'csv') self.parquet_engine = kwargs.pop('parquet_engine', 'pyarrow') self.ret_val_on_error = kwargs.pop("ret_val_on_error", np.NAN) - self.cd = kwargs.pop("cd", os.getcwd()) - self.savepath_sim = kwargs.pop('savepath_sim', self.cd) + self.working_directory = kwargs.pop("working_directory", os.getcwd()) - if isinstance(self.cd, str): - self.cd = pathlib.Path(self.cd) + if "cd" in kwargs: + warnings.warn( + "cd was renamed to working_directory in all classes. " + "Use working_directory instead.", + category=DeprecationWarning) + self.working_directory = kwargs.pop("cd") + + self.savepath_sim = kwargs.pop('savepath_sim', self.working_directory) + + if isinstance(self.working_directory, str): + self.working_directory = Path(self.working_directory) if isinstance(self.savepath_sim, str): - self.savepath_sim = pathlib.Path(self.savepath_sim) + self.savepath_sim = Path(self.savepath_sim) # Setup the logger - self.logger = setup_logger(working_directory=self.cd, name=self.__class__.__name__) + self.logger = setup_logger(working_directory=self.working_directory, + name=self.__class__.__name__) # Setup default values self.problem: dict = None @@ -236,7 +246,7 @@ def simulate_samples(self, cal_class, **kwargs): # creat df of samples with the result_file_names as the index result_file_names = [f"simulation_{idx}" for idx in range(len(samples))] samples_df = pd.DataFrame(samples, columns=initial_names, index=result_file_names) - samples_df.to_csv(self.cd.joinpath(f'samples_{cal_class.name}.csv')) + samples_df.to_csv(self.working_directory.joinpath(f'samples_{cal_class.name}.csv')) # Simulate the current values parameters = [] @@ -410,7 +420,7 @@ def run(self, calibration_classes, merge_multiple_classes=True, **kwargs): The usage of the same simulations for different calibration classes is not supported yet. :keyword bool save_results: - Default True. If True, all results are saved as a csv in cd. + Default True. If True, all results are saved as a csv in working_directory. (samples, statistical measures and analysis variables). :keyword bool plot_result: Default True. If True, the results will be plotted. @@ -513,17 +523,17 @@ def run(self, calibration_classes, merge_multiple_classes=True, **kwargs): if len(output_verbose) > 1 and verbose: stat_mea.update(output_verbose) - # save statistical measure and corresponding samples for each cal_class in cd + # save statistical measure and corresponding samples for each cal_class in working_directory if save_results: result_file_names = [f"simulation_{idx}" for idx in range(len(output_array))] stat_mea_df = pd.DataFrame(stat_mea, index=result_file_names) - savepath_stat_mea = self.cd.joinpath( + savepath_stat_mea = self.working_directory.joinpath( f'{cal_class.goals.statistical_measure}_{cal_class.name}.csv') stat_mea_df.to_csv(savepath_stat_mea) self.reproduction_files.append(savepath_stat_mea) samples_df = pd.DataFrame(samples, columns=cal_class.tuner_paras.get_names(), index=result_file_names) - savepath_samples = self.cd.joinpath(f'samples_{cal_class.name}.csv') + savepath_samples = self.working_directory.joinpath(f'samples_{cal_class.name}.csv') samples_df.to_csv(savepath_samples) self.reproduction_files.append(savepath_samples) @@ -552,9 +562,11 @@ def _save(self, result: pd.DataFrame, time_dependent: bool = False): Needs to be overwritten for Sobol results. """ if time_dependent: - savepath_result = self.cd.joinpath(f'{self.__class__.__name__}_results_time.csv') + savepath_result = self.working_directory.joinpath( + f'{self.__class__.__name__}_results_time.csv') else: - savepath_result = self.cd.joinpath(f'{self.__class__.__name__}_results.csv') + savepath_result = self.working_directory.joinpath( + f'{self.__class__.__name__}_results.csv') result.to_csv(savepath_result) self.reproduction_files.append(savepath_result) @@ -677,7 +689,7 @@ def run_time_dependent(self, cal_class: CalibrationClass, **kwargs): they were saved from self.save_files. Currently, the name of the sim folder must be "simulations_CAL_CLASS_NAME" and for the samples "samples_CAL_CLASS_NAME". :keyword bool save_results: - Default True. If True, all results are saved as a csv in cd. + Default True. If True, all results are saved as a csv in working_directory. (samples and analysis variables). :keyword int n_steps: Default is all time steps. If the problem is large, the evaluation of all time steps @@ -865,7 +877,7 @@ def load_from_csv(path): def save_for_reproduction(self, title: str, - path: pathlib.Path = None, + path: Path = None, files: list = None, exclude_sim_files: bool = False, remove_saved_files: bool = False, @@ -878,8 +890,8 @@ def save_for_reproduction(self, :param str title: Title of the study - :param pathlib.Path path: - Where to store the .zip file. If not given, self.cd is used. + :param Path path: + Where to store the .zip file. If not given, self.working_directory is used. :param list files: List of files to save along the standard ones. Examples would be plots, tables etc. @@ -901,7 +913,8 @@ def save_for_reproduction(self, if exclude_sim_files: if 'simulation' in str(file_path): continue - filename = "SenAnalyzer" + str(file_path).rsplit(self.cd.name, maxsplit=1)[-1] + filename = "SenAnalyzer" + \ + str(file_path).rsplit(self.working_directory.name, maxsplit=1)[-1] files.append(CopyFile( sourcepath=file_path, filename=filename, diff --git a/aixcalibuha/sensitivity_analysis/sobol.py b/aixcalibuha/sensitivity_analysis/sobol.py index beb2cc2b..9136ae8d 100644 --- a/aixcalibuha/sensitivity_analysis/sobol.py +++ b/aixcalibuha/sensitivity_analysis/sobol.py @@ -93,10 +93,10 @@ def _save(self, result: tuple, time_dependent: bool = False): if not result[0].empty: super()._save(result=result[0], time_dependent=time_dependent) if time_dependent: - savepath_result_2 = self.cd.joinpath( + savepath_result_2 = self.working_directory.joinpath( f'{self.__class__.__name__}_results_second_order_time.csv') else: - savepath_result_2 = self.cd.joinpath( + savepath_result_2 = self.working_directory.joinpath( f'{self.__class__.__name__}_results_second_order.csv') if not result[1].empty: result[1].to_csv(savepath_result_2) diff --git a/aixcalibuha/utils/configuration.py b/aixcalibuha/utils/configuration.py index 8cc76e43..d7d80a96 100644 --- a/aixcalibuha/utils/configuration.py +++ b/aixcalibuha/utils/configuration.py @@ -175,7 +175,7 @@ def write_config(filepath, config): If the file already exists, the data is recursively updated. - :param str,os.path.normpath filepath: + :param str,Path filepath: Filepath with the config. :param: dict config: Config to be saved @@ -195,7 +195,7 @@ def read_config(filepath): """ Read the given file and return the toml-config - :param str,os.path.normpath filepath: + :param str,Path filepath: Filepath with the config. :return: dict config: Loaded config diff --git a/aixcalibuha/utils/visualizer.py b/aixcalibuha/utils/visualizer.py index 38dc2c0b..06f47896 100644 --- a/aixcalibuha/utils/visualizer.py +++ b/aixcalibuha/utils/visualizer.py @@ -42,7 +42,7 @@ class CalibrationLogger: this Framework with print-statements and saving everything relevant as a log-file. - :param str,os.path.normpath cd: + :param str,Path working_directory: Directory where to store the output of the Logger and possible child-classes. If the given directory can not be created, an error will be raised. @@ -62,18 +62,18 @@ class CalibrationLogger: _prec = decimal_prec _width = integer_prec + decimal_prec + 1 # Calculate the actual width - def __init__(self, cd, name, calibration_class, logger=None): + def __init__(self, working_directory, name, calibration_class, logger=None): """Instantiate class parameters""" self._tuner_paras = None self._goals = None if logger is None: - self.logger = setup_logger(working_directory=cd, name=name) + self.logger = setup_logger(working_directory=working_directory, name=name) else: if not isinstance(logger, logging.Logger): raise TypeError(f"Given logger is of type {type(logger)} " f"but should be type logging.Logger") self.logger = logger - self.cd = cd + self.working_directory = working_directory self.calibration_class = calibration_class def log(self, msg, level=logging.INFO): @@ -157,7 +157,7 @@ def save_calibration_result(self, best_iterate, model_name, **kwargs): self.logger.info(result_log) self._counter_calibration = 0 - def calibrate_new_class(self, calibration_class, cd=None, for_validation=False): + def calibrate_new_class(self, calibration_class, working_directory=None, for_validation=False): """Function to setup the figures for a new class of calibration. This function is called when instantiating this Class. If you uses continuuos calibration classes, call this function before @@ -166,26 +166,26 @@ def calibrate_new_class(self, calibration_class, cd=None, for_validation=False): :param aixcalibuha.CalibrationClass calibration_class: Class holding information on names, tuner_paras, goals and time-intervals of calibration. - :param str,os.path.normpath cd: + :param str,Path working_directory: Optional change in working directory to store files :param bool for_validation: If it's only for validation, only plot the goals """ - if cd is not None: - self.cd = cd + if working_directory is not None: + self.working_directory = working_directory self.calibration_class = calibration_class @property - def cd(self) -> str: + def working_directory(self) -> str: """Get the current working directory for storing plots.""" - return self._cd + return self._working_directory - @cd.setter - def cd(self, cd: str): + @working_directory.setter + def working_directory(self, working_directory: str): """Set the current working directory for storing plots.""" - if not os.path.exists(cd): - os.makedirs(cd) - self._cd = cd + if not os.path.exists(working_directory): + os.makedirs(working_directory) + self._working_directory = working_directory @property def tuner_paras(self) -> aixcalibuha.TunerParas: @@ -354,7 +354,7 @@ class CalibrationVisualizer(CalibrationLogger): yields plot which disappear to fast. Default is 1-e3 s. """ - def __init__(self, cd, + def __init__(self, working_directory, name, calibration_class, logger=None, @@ -362,7 +362,7 @@ def __init__(self, cd, """Instantiate class parameters""" # Instantiate the logger: - super().__init__(cd=cd, + super().__init__(working_directory=working_directory, name=name, calibration_class=calibration_class, logger=logger) @@ -388,7 +388,7 @@ def __init__(self, cd, f"be float or int but is {type(self.show_plot_pause_time)}." ) - def calibrate_new_class(self, calibration_class, cd=None, for_validation=False): + def calibrate_new_class(self, calibration_class, working_directory=None, for_validation=False): """Function to setup the figures for a new class of calibration. This function is called when instantiating this Class. If you uses continuuos calibration classes, call this function before @@ -397,12 +397,12 @@ def calibrate_new_class(self, calibration_class, cd=None, for_validation=False): :param aixcalibuha.CalibrationClass calibration_class: Class holding information on names, tuner_paras, goals and time-intervals of calibration. - :param str,os.path.normpath cd: + :param str,Path working_directory: Optional change in working directory to store files :param bool for_validation: If it's only for validation, only plot the goals """ - super().calibrate_new_class(calibration_class, cd) + super().calibrate_new_class(calibration_class, working_directory) name = calibration_class.name @@ -514,14 +514,14 @@ def save_calibration_result(self, best_iterate, model_name, **kwargs): duration = kwargs["duration"] # Extract filepathes - iterpath = os.path.join(self.cd, f'Iteration_{itercount}') + iterpath = os.path.join(self.working_directory, f'Iteration_{itercount}') if not os.path.exists(iterpath): os.mkdir(iterpath) filepath_tuner = os.path.join(iterpath, "tuner_parameter_plot.%s" % self.file_type) filepath_obj = os.path.join(iterpath, "objective_plot.%s" % self.file_type) if self.save_tsd_plot: - bestgoal = os.path.join(self.cd, + bestgoal = os.path.join(self.working_directory, self.goals_dir, str(best_iterate["Iterate"]) + f"_goals.{self.file_type}") # Copy best goals figure @@ -531,7 +531,7 @@ def save_calibration_result(self, best_iterate, model_name, **kwargs): res_dict = dict(best_iterate['Parameters']) res_dict['Objective'] = best_iterate["Objective"] res_dict['Duration'] = duration - res_csv = f'{self.cd}\\Iteration_{itercount}\\RESUL' \ + res_csv = f'{self.working_directory}\\Iteration_{itercount}\\RESUL' \ f'TS_{self.calibration_class.name}_iteration{itercount}.csv' with open(res_csv, 'w') as rescsv: writer = csv.DictWriter(rescsv, res_dict.keys()) @@ -584,7 +584,7 @@ def log_intersection_of_tuners(self, intersected_tuner_parameters, **kwargs): # Always store in the parent diretory as this info is relevant for all classes # fig_intersection.suptitle("Intersection of Tuner Parameters") fig_intersection.suptitle("Intersection of Tuner Parameters") - path_intersections = os.path.join(os.path.dirname(self.cd), "tunerintersections") + path_intersections = os.path.join(os.path.dirname(self.working_directory), "tunerintersections") if not os.path.exists(path_intersections): os.makedirs(path_intersections) if "itercount" in kwargs: @@ -692,7 +692,7 @@ def _plot_goals(self, at_validation=False): name_id = self._counter_calibration if self.save_tsd_plot: - _savedir = os.path.join(self.cd, self.goals_dir) + _savedir = os.path.join(self.working_directory, self.goals_dir) if not os.path.exists(_savedir): os.makedirs(_savedir) self.fig_goal.savefig( diff --git a/examples/__init__.py b/examples/__init__.py index 006ec741..7cc78ffd 100644 --- a/examples/__init__.py +++ b/examples/__init__.py @@ -1,7 +1,7 @@ """ Module containing examples on how to use AixCaliBuHA """ -import pathlib +from pathlib import Path import sys from ebcpy import FMU_API, DymolaAPI from examples import e2_A_optimization_problem_definition, e2_B_optimization_problem_definition @@ -11,14 +11,14 @@ def setup_fmu(examples_dir, example="B", n_cpu=1): """ Setup the FMU used in all examples and tests. - :param [pathlib.Path, str] examples_dir: + :param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param str example: Which example to run, "A" or "B" :param int n_cpu: Number of cores to use """ - examples_dir = pathlib.Path(examples_dir) + examples_dir = Path(examples_dir) if example == "A": if "win" not in sys.platform: raise OSError("Can only run the example type B on windows. " @@ -39,7 +39,7 @@ def setup_fmu(examples_dir, example="B", n_cpu=1): def setup_dym_api(examples_dir, aixlib_mo, example="A", n_cpu=1, dymola_version='Dymola 2023'): - examples_dir = pathlib.Path(examples_dir) + examples_dir = Path(examples_dir) packages = [] if example == "A": packages.append(examples_dir.joinpath('model', 'AixCaliBuHAExamples.mo')) @@ -50,7 +50,7 @@ def setup_dym_api(examples_dir, aixlib_mo, example="A", n_cpu=1, dymola_version= else: raise ValueError("Only example 'A' and 'B' are available") - return DymolaAPI(cd=examples_dir.joinpath("testzone"), + return DymolaAPI(working_directory=examples_dir.joinpath("testzone"), model_name=model_name, packages=packages, n_cpu=n_cpu, diff --git a/examples/docs/e1_A_energy_system_analysis.md b/examples/docs/e1_A_energy_system_analysis.md index 6669913d..d36a8a89 100644 --- a/examples/docs/e1_A_energy_system_analysis.md +++ b/examples/docs/e1_A_energy_system_analysis.md @@ -9,7 +9,7 @@ Goals of this part of the examples: Start by importing all relevant packages ```python -import pathlib +from pathlib import Path import matplotlib.pyplot as plt ``` @@ -25,12 +25,12 @@ Please define the missing TODOs in the section below according to the docstrings """ Arguments of this example: -:param [pathlib.Path, str] examples_dir: +:param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param str aixlib_mo: Path to the package.mo of the AixLib. This example was tested for AixLib version 1.0.0. -:param str cd: +:param str working_directory: Path in which to store the output. Default is the examples\results folder :param bool with_plot: @@ -46,10 +46,10 @@ General settings ```python if cd is None: - cd = pathlib.Path(examples_dir).joinpath("results") + cd = Path(examples_dir).joinpath("results") else: - cd = pathlib.Path(cd) -examples_dir = pathlib.Path(examples_dir) + cd = Path(cd) +examples_dir = Path(examples_dir) aixcalibuha_mo = examples_dir.joinpath("model", "AixCaliBuHAExamples.mo") ``` diff --git a/examples/docs/e1_B_energy_system_analysis.md b/examples/docs/e1_B_energy_system_analysis.md index a65eeb7d..04d82abc 100644 --- a/examples/docs/e1_B_energy_system_analysis.md +++ b/examples/docs/e1_B_energy_system_analysis.md @@ -9,7 +9,7 @@ Goals of this part of the examples: Start by importing all relevant packages ```python -import pathlib +from pathlib import Path import matplotlib.pyplot as plt ``` @@ -19,7 +19,7 @@ Please define the missing TODOs in the section below according to the docstrings """ Arguments of this example: -:param [pathlib.Path, str] examples_dir: +:param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param bool with_plot: Show the plot at the end of the script. Default is True. @@ -136,6 +136,6 @@ let's change some names and time index to ensure a realistic scenario: ```python tsd = tsd.rename(columns={"pipe.T": "TPipe", "heatCapacitor.T": "TCapacity"}) tsd.to_datetime_index() -tsd.save(pathlib.Path(examples_dir).joinpath("data", "PumpAndValve.hdf"), key="examples") -print("Saved data under", pathlib.Path(examples_dir).joinpath("data")) +tsd.save(Path(examples_dir).joinpath("data", "PumpAndValve.hdf"), key="examples") +print("Saved data under", Path(examples_dir).joinpath("data")) ``` diff --git a/examples/docs/e2_A_optimization_problem_definition.md b/examples/docs/e2_A_optimization_problem_definition.md index a069194f..81ed7ab2 100644 --- a/examples/docs/e2_A_optimization_problem_definition.md +++ b/examples/docs/e2_A_optimization_problem_definition.md @@ -11,7 +11,7 @@ Goals of this part of the examples: Start by importing all relevant packages ```python -import pathlib +from pathlib import Path ``` Imports from ebcpy @@ -34,7 +34,7 @@ Please define the missing TODOs in the section below according to the docstrings """ Arguments of this example: -:param [pathlib.Path, str] examples_dir: +:param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param str statistical_measure: Measure to calculate the scalar of the objective, @@ -103,7 +103,7 @@ Thus, you need to specify both measured and simulated data. Start by loading the measured data generated in 1_A_energy_system_analysis.py: ```python -data_dir = pathlib.Path(examples_dir).joinpath("data") +data_dir = Path(examples_dir).joinpath("data") meas_target_data = TimeSeriesData(data_dir.joinpath("measured_target_data.hdf"), key="example") ``` diff --git a/examples/docs/e2_B_optimization_problem_definition.md b/examples/docs/e2_B_optimization_problem_definition.md index e8512779..5ec4fe1a 100644 --- a/examples/docs/e2_B_optimization_problem_definition.md +++ b/examples/docs/e2_B_optimization_problem_definition.md @@ -11,7 +11,7 @@ Goals of this part of the examples: Start by importing all relevant packages ```python -import pathlib +from pathlib import Path ``` Imports from ebcpy @@ -34,7 +34,7 @@ Please define the missing TODOs in the section below according to the docstrings """ Arguments of this example: -:param [pathlib.Path, str] examples_dir: +:param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param str statistical_measure: Measure to calculate the scalar of the objective, @@ -94,7 +94,7 @@ As the examples should work, and the cal_class example uses the other examples, we will test it here: ```python -data_dir = pathlib.Path(examples_dir).joinpath("data") +data_dir = Path(examples_dir).joinpath("data") meas_target_data = TimeSeriesData(data_dir.joinpath("PumpAndValve.hdf"), key="examples") ``` diff --git a/examples/docs/e3_1_verbose_sensitivity_analysis_example.md b/examples/docs/e3_1_verbose_sensitivity_analysis_example.md index 97f623fd..b38bdec4 100644 --- a/examples/docs/e3_1_verbose_sensitivity_analysis_example.md +++ b/examples/docs/e3_1_verbose_sensitivity_analysis_example.md @@ -14,7 +14,7 @@ Start by importing all relevant packages ```python import warnings -import pathlib +from pathlib import Path import matplotlib.pyplot as plt from aixcalibuha import SobolAnalyzer, FASTAnalyzer, MorrisAnalyzer from aixcalibuha.data_types import merge_calibration_classes @@ -36,7 +36,7 @@ and tuner-parameters are selected with these results. A comparison between different methods is shown. At the end the option to save a reproduction archive is shown. -:param [pathlib.Path, str] examples_dir: +:param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA e.g. r"LOCAL_PATH_TO\AixCaliBuHA\examples" :param str example: @@ -59,7 +59,7 @@ some further settings for the analysis. Let's first load the necessary simulation api: ```python -examples_dir = pathlib.Path(examples_dir) +examples_dir = Path(examples_dir) sim_api = setup_fmu(examples_dir=examples_dir, example=example, n_cpu=n_cpu) ``` diff --git a/examples/docs/e3_2_verbose_dymola_sensitivity_analysis_example.md b/examples/docs/e3_2_verbose_dymola_sensitivity_analysis_example.md index f909b0fe..5c1d8db2 100644 --- a/examples/docs/e3_2_verbose_dymola_sensitivity_analysis_example.md +++ b/examples/docs/e3_2_verbose_dymola_sensitivity_analysis_example.md @@ -7,7 +7,7 @@ Goals of this part of the examples: ```python import os -import pathlib +from pathlib import Path from examples import setup_dym_api, setup_calibration_classes ``` @@ -25,9 +25,9 @@ Please define the missing TODOs in the section below according to the docstrings """ Example process of a verbose sensitivity analysis with the dymola_api. -:param [pathlib.Path, str] examples_dir: +:param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA -:param [pathlib.Path, str] aixlib_mo: +:param [Path, str] aixlib_mo: Path to the AixLib package.mo file. :param str example: Which example to run, "A" or "B" @@ -47,7 +47,7 @@ n_cpu: int = 1 Using a dymola api instead of the fmu api ```python -examples_dir = pathlib.Path(examples_dir) +examples_dir = Path(examples_dir) sim_api = setup_dym_api(examples_dir=examples_dir, aixlib_mo=aixlib_mo, example=example, diff --git a/examples/docs/e3_sensitivity_analysis_example.md b/examples/docs/e3_sensitivity_analysis_example.md index 6278a1ab..c2d049f8 100644 --- a/examples/docs/e3_sensitivity_analysis_example.md +++ b/examples/docs/e3_sensitivity_analysis_example.md @@ -24,7 +24,7 @@ The result of this analysis is then printed to the user. The automatic_select function is presented as-well, using a threshold of 1 and the default `mu_star` criterion. -:param [pathlib.Path, str] examples_dir: +:param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param str example: Which example to run, "A" or "B" @@ -47,13 +47,14 @@ Let's thus first load the necessary simulation api: ```python from examples import setup_fmu, setup_calibration_classes + sim_api = setup_fmu(examples_dir=examples_dir, example=example, n_cpu=n_cpu) sen_analyzer = SobolAnalyzer( - sim_api=sim_api, - num_samples=10, - cd=sim_api.cd - ) + sim_api=sim_api, + num_samples=10, + cd=sim_api.working_directory +) ``` Now perform the analysis for the one of the given calibration classes. diff --git a/examples/docs/e3_verbose_dymola_sensitivity_analysis_example.md b/examples/docs/e3_verbose_dymola_sensitivity_analysis_example.md index f909b0fe..5c1d8db2 100644 --- a/examples/docs/e3_verbose_dymola_sensitivity_analysis_example.md +++ b/examples/docs/e3_verbose_dymola_sensitivity_analysis_example.md @@ -7,7 +7,7 @@ Goals of this part of the examples: ```python import os -import pathlib +from pathlib import Path from examples import setup_dym_api, setup_calibration_classes ``` @@ -25,9 +25,9 @@ Please define the missing TODOs in the section below according to the docstrings """ Example process of a verbose sensitivity analysis with the dymola_api. -:param [pathlib.Path, str] examples_dir: +:param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA -:param [pathlib.Path, str] aixlib_mo: +:param [Path, str] aixlib_mo: Path to the AixLib package.mo file. :param str example: Which example to run, "A" or "B" @@ -47,7 +47,7 @@ n_cpu: int = 1 Using a dymola api instead of the fmu api ```python -examples_dir = pathlib.Path(examples_dir) +examples_dir = Path(examples_dir) sim_api = setup_dym_api(examples_dir=examples_dir, aixlib_mo=aixlib_mo, example=example, diff --git a/examples/docs/e3_verbose_sensitivity_analysis_example.md b/examples/docs/e3_verbose_sensitivity_analysis_example.md index 97f623fd..b38bdec4 100644 --- a/examples/docs/e3_verbose_sensitivity_analysis_example.md +++ b/examples/docs/e3_verbose_sensitivity_analysis_example.md @@ -14,7 +14,7 @@ Start by importing all relevant packages ```python import warnings -import pathlib +from pathlib import Path import matplotlib.pyplot as plt from aixcalibuha import SobolAnalyzer, FASTAnalyzer, MorrisAnalyzer from aixcalibuha.data_types import merge_calibration_classes @@ -36,7 +36,7 @@ and tuner-parameters are selected with these results. A comparison between different methods is shown. At the end the option to save a reproduction archive is shown. -:param [pathlib.Path, str] examples_dir: +:param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA e.g. r"LOCAL_PATH_TO\AixCaliBuHA\examples" :param str example: @@ -59,7 +59,7 @@ some further settings for the analysis. Let's first load the necessary simulation api: ```python -examples_dir = pathlib.Path(examples_dir) +examples_dir = Path(examples_dir) sim_api = setup_fmu(examples_dir=examples_dir, example=example, n_cpu=n_cpu) ``` diff --git a/examples/docs/e4_calibration_example.md b/examples/docs/e4_calibration_example.md index e2f5b74e..1b3951ce 100644 --- a/examples/docs/e4_calibration_example.md +++ b/examples/docs/e4_calibration_example.md @@ -22,7 +22,7 @@ to better understand what is happening in the calibration. If you want, you can switch the methods to other supported methods or change the framework and try the global optimizer of dlib. -:param [pathlib.Path, str] examples_dir: +:param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param str example: Which example to run, "A" or "B" @@ -152,7 +152,7 @@ Select between single or multiple class calibration ```python if isinstance(cal_classes, CalibrationClass): modelica_calibrator = Calibrator( - cd=sim_api.cd, + cd=sim_api.working_directory, sim_api=sim_api, calibration_class=cal_classes, **kwargs_calibrator) @@ -160,7 +160,7 @@ else: kwargs_calibrator.update(kwargs_multiple_classes) # Setup the class modelica_calibrator = MultipleClassCalibrator( - cd=sim_api.cd, + cd=sim_api.working_directory, sim_api=sim_api, calibration_classes=cal_classes, start_time_method="fixstart", diff --git a/examples/docs/e5_automated_process.md b/examples/docs/e5_automated_process.md index 12e7ee37..44f6a702 100644 --- a/examples/docs/e5_automated_process.md +++ b/examples/docs/e5_automated_process.md @@ -17,7 +17,7 @@ Please define the missing TODOs in the section below according to the docstrings """ Arguments of this example: -:param [pathlib.Path, str] examples_dir: +:param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param str example: Whether to use example A (requires windows) or B. diff --git a/examples/e1_A_energy_system_analysis.py b/examples/e1_A_energy_system_analysis.py index f6393750..26db4bf9 100644 --- a/examples/e1_A_energy_system_analysis.py +++ b/examples/e1_A_energy_system_analysis.py @@ -6,7 +6,7 @@ # 4. Generate some measured data to later use in a calibration # Start by importing all relevant packages -import pathlib +from pathlib import Path import matplotlib.pyplot as plt # Imports from ebcpy from ebcpy import DymolaAPI, TimeSeriesData @@ -15,29 +15,29 @@ def main( examples_dir, aixlib_mo, - cd=None, + working_directory=None, with_plot=True ): """ Arguments of this example: - :param [pathlib.Path, str] examples_dir: + :param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param str aixlib_mo: Path to the package.mo of the AixLib. This example was tested for AixLib version 1.0.0. - :param str cd: + :param str working_directory: Path in which to store the output. Default is the examples\results folder :param bool with_plot: Show the plot at the end of the script. Default is True. """ # General settings - if cd is None: - cd = pathlib.Path(examples_dir).joinpath("results") + if working_directory is None: + working_directory = Path(examples_dir).joinpath("results") else: - cd = pathlib.Path(cd) - examples_dir = pathlib.Path(examples_dir) + working_directory = Path(working_directory) + examples_dir = Path(examples_dir) aixcalibuha_mo = examples_dir.joinpath("model", "AixCaliBuHAExamples.mo") # ## System analysis @@ -54,7 +54,7 @@ def main( # Start by setting up the Dymola-API. For more info, see the examples in ebcpy. dym_api = DymolaAPI( model_name="AixCaliBuHAExamples.HeatPumpSystemCalibration", - cd=cd, + working_directory=working_directory, packages=[ aixlib_mo, aixcalibuha_mo @@ -167,5 +167,5 @@ def main( # TODO-User: Change the AixLib path! main( aixlib_mo=r"D:\02_workshop\AixLib\AixLib\package.mo", - examples_dir=pathlib.Path(__file__).parent + examples_dir=Path(__file__).parent ) diff --git a/examples/e1_B_energy_system_analysis.py b/examples/e1_B_energy_system_analysis.py index 4086f503..27598a73 100644 --- a/examples/e1_B_energy_system_analysis.py +++ b/examples/e1_B_energy_system_analysis.py @@ -6,7 +6,7 @@ # 4. Generate some measured data to later use in a calibration # # Start by importing all relevant packages -import pathlib +from pathlib import Path import matplotlib.pyplot as plt @@ -17,7 +17,7 @@ def main( """ Arguments of this example: - :param [pathlib.Path, str] examples_dir: + :param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param bool with_plot: Show the plot at the end of the script. Default is True. @@ -100,11 +100,11 @@ def main( # let's change some names and time index to ensure a realistic scenario: tsd = tsd.rename(columns={"pipe.T": "TPipe", "heatCapacitor.T": "TCapacity"}) tsd.to_datetime_index() - tsd.save(pathlib.Path(examples_dir).joinpath("data", "PumpAndValve.hdf"), key="examples") - print("Saved data under", pathlib.Path(examples_dir).joinpath("data")) + tsd.save(Path(examples_dir).joinpath("data", "PumpAndValve.hdf"), key="examples") + print("Saved data under", Path(examples_dir).joinpath("data")) if __name__ == '__main__': main( - examples_dir=pathlib.Path(__file__).parent + examples_dir=Path(__file__).parent ) diff --git a/examples/e2_A_optimization_problem_definition.py b/examples/e2_A_optimization_problem_definition.py index 04983f31..e07e4502 100644 --- a/examples/e2_A_optimization_problem_definition.py +++ b/examples/e2_A_optimization_problem_definition.py @@ -8,7 +8,7 @@ # 5. Learn how to merge multiple classes # # Start by importing all relevant packages -import pathlib +from pathlib import Path # Imports from ebcpy from ebcpy import TimeSeriesData # Imports from aixcalibuha @@ -25,7 +25,7 @@ def main( """ Arguments of this example: - :param [pathlib.Path, str] examples_dir: + :param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param str statistical_measure: Measure to calculate the scalar of the objective, @@ -81,7 +81,7 @@ def main( # Thus, you need to specify both measured and simulated data. # # Start by loading the measured data generated in 1_A_energy_system_analysis.py: - data_dir = pathlib.Path(examples_dir).joinpath("data") + data_dir = Path(examples_dir).joinpath("data") meas_target_data = TimeSeriesData(data_dir.joinpath("measured_target_data.hdf"), key="example") # Map the measured keys to the names inside your simulation variable_names = { @@ -217,6 +217,6 @@ def main( if __name__ == '__main__': main( - examples_dir=pathlib.Path(__file__).parent, + examples_dir=Path(__file__).parent, multiple_classes=True ) diff --git a/examples/e2_B_optimization_problem_definition.py b/examples/e2_B_optimization_problem_definition.py index 0d13ca31..42ced1f9 100644 --- a/examples/e2_B_optimization_problem_definition.py +++ b/examples/e2_B_optimization_problem_definition.py @@ -8,7 +8,7 @@ # 5. Learn how to merge multiple classes # # Start by importing all relevant packages -import pathlib +from pathlib import Path # Imports from ebcpy from ebcpy import TimeSeriesData # Imports from AixCaliBUhA @@ -25,7 +25,7 @@ def main( """ Arguments of this example: - :param [pathlib.Path, str] examples_dir: + :param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param str statistical_measure: Measure to calculate the scalar of the objective, @@ -70,7 +70,7 @@ def main( # # As the examples should work, and the cal_class example uses the other examples, # we will test it here: - data_dir = pathlib.Path(examples_dir).joinpath("data") + data_dir = Path(examples_dir).joinpath("data") meas_target_data = TimeSeriesData(data_dir.joinpath("PumpAndValve.hdf"), key="examples") # Setup three variables for different format of setup @@ -192,6 +192,6 @@ def main( if __name__ == '__main__': main( - examples_dir=pathlib.Path(__file__).parent, + examples_dir=Path(__file__).parent, multiple_classes=True ) diff --git a/examples/e3_1_verbose_sensitivity_analysis_example.py b/examples/e3_1_verbose_sensitivity_analysis_example.py index c93795f7..7607515a 100644 --- a/examples/e3_1_verbose_sensitivity_analysis_example.py +++ b/examples/e3_1_verbose_sensitivity_analysis_example.py @@ -11,7 +11,7 @@ # Start by importing all relevant packages import warnings -import pathlib +from pathlib import Path import matplotlib.pyplot as plt from aixcalibuha import SobolAnalyzer, FASTAnalyzer, MorrisAnalyzer from aixcalibuha.data_types import merge_calibration_classes @@ -35,7 +35,7 @@ def run_sensitivity_analysis( A comparison between different methods is shown. At the end the option to save a reproduction archive is shown. - :param [pathlib.Path, str] examples_dir: + :param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA e.g. r"LOCAL_PATH_TO\AixCaliBuHA\examples" :param str example: @@ -51,7 +51,7 @@ def run_sensitivity_analysis( # You just have to pass a valid simulation api and # some further settings for the analysis. # Let's first load the necessary simulation api: - examples_dir = pathlib.Path(examples_dir) + examples_dir = Path(examples_dir) sim_api = setup_fmu(examples_dir=examples_dir, example=example, n_cpu=n_cpu) # To conduct a sensitivity analysis, we need to define calibration classes that # encompass the objectives (goals) for which sensitivity is to be assessed. In this @@ -113,7 +113,7 @@ def run_sensitivity_analysis( sim_api=sim_api, num_samples=8, calc_second_order=True, - cd=examples_dir.joinpath('testzone', f'verbose_sen_{example}'), + working_directory=examples_dir.joinpath('testzone', f'verbose_sen_{example}'), save_files=True, savepath_sim=examples_dir.joinpath('testzone', f'verbose_sen_{example}', 'files'), suffix_files='csv' @@ -464,7 +464,7 @@ def run_sensitivity_analysis( # Sensitivity analysis: run_sensitivity_analysis( - examples_dir=pathlib.Path(__file__).parent, + examples_dir=Path(__file__).parent, example=EXAMPLE, n_cpu=N_CPU ) diff --git a/examples/e3_2_verbose_dymola_sensitivity_analysis_example.py b/examples/e3_2_verbose_dymola_sensitivity_analysis_example.py index 87e8b3f2..b7a2f451 100644 --- a/examples/e3_2_verbose_dymola_sensitivity_analysis_example.py +++ b/examples/e3_2_verbose_dymola_sensitivity_analysis_example.py @@ -4,7 +4,7 @@ # 1. Learn how to execute a sensitivity analysis with the dymola api # import os -import pathlib +from pathlib import Path from examples import setup_dym_api, setup_calibration_classes # Import a valid analyzer, e.g. `SobolAnalyzer` from aixcalibuha import SobolAnalyzer @@ -21,9 +21,9 @@ def run_sensitivity_analysis( """ Example process of a verbose sensitivity analysis with the dymola_api. - :param [pathlib.Path, str] examples_dir: + :param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA - :param [pathlib.Path, str] aixlib_mo: + :param [Path, str] aixlib_mo: Path to the AixLib package.mo file. :param str example: Which example to run, "A" or "B" @@ -35,7 +35,7 @@ def run_sensitivity_analysis( """ # ## Setup # Using a dymola api instead of the fmu api - examples_dir = pathlib.Path(examples_dir) + examples_dir = Path(examples_dir) sim_api = setup_dym_api(examples_dir=examples_dir, aixlib_mo=aixlib_mo, example=example, @@ -59,7 +59,7 @@ def run_sensitivity_analysis( sim_api=sim_api, num_samples=2, calc_second_order=True, - cd=examples_dir.joinpath('testzone', f'verbose_sen_dymola_{example}'), + working_directory=examples_dir.joinpath('testzone', f'verbose_sen_dymola_{example}'), save_files=True, load_files=False, savepath_sim=examples_dir.joinpath('testzone', f'verbose_sen_dymola_{example}', 'files'), @@ -112,7 +112,7 @@ def run_sensitivity_analysis( # Sensitivity analysis: run_sensitivity_analysis( - examples_dir=pathlib.Path(__file__).parent, + examples_dir=Path(__file__).parent, aixlib_mo=r"D:\sbg-hst\Repos\AixLib\AixLib\package.mo", example=EXAMPLE, n_cpu=N_CPU diff --git a/examples/e3_sensitivity_analysis_example.py b/examples/e3_sensitivity_analysis_example.py index ebd72925..be03d1f9 100644 --- a/examples/e3_sensitivity_analysis_example.py +++ b/examples/e3_sensitivity_analysis_example.py @@ -23,7 +23,7 @@ def run_sensitivity_analysis( The automatic_select function is presented as-well, using a threshold of 1 and the default `mu_star` criterion. - :param [pathlib.Path, str] examples_dir: + :param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param str example: Which example to run, "A" or "B" @@ -44,7 +44,7 @@ def run_sensitivity_analysis( sen_analyzer = SobolAnalyzer( sim_api=sim_api, num_samples=10, - cd=sim_api.cd + working_directory=sim_api.working_directory ) # Now perform the analysis for the one of the given calibration classes. calibration_classes = setup_calibration_classes( @@ -72,7 +72,7 @@ def run_sensitivity_analysis( if __name__ == "__main__": - import pathlib + from pathlib import Path from examples import setup_fmu, setup_calibration_classes # Parameters for sen-analysis: EXAMPLE = "B" # Or choose A @@ -80,7 +80,7 @@ def run_sensitivity_analysis( # Sensitivity analysis: run_sensitivity_analysis( - examples_dir=pathlib.Path(__file__).parent, + examples_dir=Path(__file__).parent, example=EXAMPLE, n_cpu=N_CPU ) diff --git a/examples/e4_calibration_example.py b/examples/e4_calibration_example.py index 28505e74..b1755752 100644 --- a/examples/e4_calibration_example.py +++ b/examples/e4_calibration_example.py @@ -25,7 +25,7 @@ def run_calibration( can switch the methods to other supported methods or change the framework and try the global optimizer of dlib. - :param [pathlib.Path, str] examples_dir: + :param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param str example: Which example to run, "A" or "B" @@ -124,7 +124,7 @@ def run_calibration( # Select between single or multiple class calibration if isinstance(cal_classes, CalibrationClass): modelica_calibrator = Calibrator( - cd=sim_api.cd, + working_directory=sim_api.working_directory, sim_api=sim_api, calibration_class=cal_classes, **kwargs_calibrator) @@ -132,7 +132,7 @@ def run_calibration( kwargs_calibrator.update(kwargs_multiple_classes) # Setup the class modelica_calibrator = MultipleClassCalibrator( - cd=sim_api.cd, + working_directory=sim_api.working_directory, sim_api=sim_api, calibration_classes=cal_classes, start_time_method="fixstart", @@ -155,11 +155,11 @@ def run_calibration( if __name__ == "__main__": - import pathlib + from pathlib import Path # Parameters for sen-analysis: EXAMPLE = "B" # Or choose A # Sensitivity analysis: run_calibration( - examples_dir=pathlib.Path(__file__).parent, + examples_dir=Path(__file__).parent, example=EXAMPLE ) diff --git a/examples/e5_automated_process.py b/examples/e5_automated_process.py index d0ea490f..ab2e79a9 100644 --- a/examples/e5_automated_process.py +++ b/examples/e5_automated_process.py @@ -16,7 +16,7 @@ def main( """ Arguments of this example: - :param [pathlib.Path, str] examples_dir: + :param [Path, str] examples_dir: Path to the examples folder of AixCaliBuHA :param str example: Whether to use example A (requires windows) or B. @@ -39,6 +39,6 @@ def main( if __name__ == '__main__': - import pathlib + from pathlib import Path EXAMPLE = "B" - main(examples_dir=pathlib.Path(__file__).parent, example=EXAMPLE) + main(examples_dir=Path(__file__).parent, example=EXAMPLE) diff --git a/examples/e6_multiprocessing_calibration_example.py b/examples/e6_multiprocessing_calibration_example.py index 83a48e3c..2d1b072a 100644 --- a/examples/e6_multiprocessing_calibration_example.py +++ b/examples/e6_multiprocessing_calibration_example.py @@ -5,7 +5,7 @@ if __name__ == "__main__": - import pathlib + from pathlib import Path from examples.e4_calibration_example import run_calibration # Number of logical Processors to run calibration on: N_CPU = 5 @@ -14,7 +14,7 @@ # Sensitivity analysis: run_calibration( - examples_dir=pathlib.Path(__file__).parent, + examples_dir=Path(__file__).parent, example=EXAMPLE, n_cpu=N_CPU, framework="pymoo", diff --git a/examples/jupyter_notebooks/e1_A_energy_system_analysis.ipynb b/examples/jupyter_notebooks/e1_A_energy_system_analysis.ipynb index c0879569..41659aa9 100644 --- a/examples/jupyter_notebooks/e1_A_energy_system_analysis.ipynb +++ b/examples/jupyter_notebooks/e1_A_energy_system_analysis.ipynb @@ -15,7 +15,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "import pathlib\nimport matplotlib.pyplot as plt\n" + "source": "from pathlib import Path\nimport matplotlib.pyplot as plt\n" }, { "cell_type": "markdown", @@ -39,7 +39,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "\"\"\"\nArguments of this example:\n\n:param [pathlib.Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param str aixlib_mo:\n Path to the package.mo of the AixLib.\n This example was tested for AixLib version 1.0.0.\n:param str cd:\n Path in which to store the output.\n Default is the examples\\results folder\n:param bool with_plot:\n Show the plot at the end of the script. Default is True.\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\naixlib_mo = \"TODO: Add a valid input according to the docstring above\"\ncd = None\nwith_plot = True\n" + "source": "\"\"\"\nArguments of this example:\n\n:param [Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param str aixlib_mo:\n Path to the package.mo of the AixLib.\n This example was tested for AixLib version 1.0.0.\n:param str cd:\n Path in which to store the output.\n Default is the examples\\results folder\n:param bool with_plot:\n Show the plot at the end of the script. Default is True.\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\naixlib_mo = \"TODO: Add a valid input according to the docstring above\"\ncd = None\nwith_plot = True\n" }, { "cell_type": "markdown", @@ -51,7 +51,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "if cd is None:\n cd = pathlib.Path(examples_dir).joinpath(\"results\")\nelse:\n cd = pathlib.Path(cd)\nexamples_dir = pathlib.Path(examples_dir)\naixcalibuha_mo = examples_dir.joinpath(\"model\", \"AixCaliBuHAExamples.mo\")\n" + "source": "if cd is None:\n cd = Path(examples_dir).joinpath(\"results\")\nelse:\n cd = Path(cd)\nexamples_dir = Path(examples_dir)\naixcalibuha_mo = examples_dir.joinpath(\"model\", \"AixCaliBuHAExamples.mo\")\n" }, { "cell_type": "markdown", diff --git a/examples/jupyter_notebooks/e1_B_energy_system_analysis.ipynb b/examples/jupyter_notebooks/e1_B_energy_system_analysis.ipynb index 1569e166..3c8f9ad0 100644 --- a/examples/jupyter_notebooks/e1_B_energy_system_analysis.ipynb +++ b/examples/jupyter_notebooks/e1_B_energy_system_analysis.ipynb @@ -10,7 +10,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "import pathlib\nimport matplotlib.pyplot as plt\n" + "source": "from pathlib import Path\nimport matplotlib.pyplot as plt\n" }, { "cell_type": "markdown", @@ -22,7 +22,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "\"\"\"\nArguments of this example:\n\n:param [pathlib.Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param bool with_plot:\n Show the plot at the end of the script. Default is True.\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nwith_plot = True\n" + "source": "\"\"\"\nArguments of this example:\n\n:param [Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param bool with_plot:\n Show the plot at the end of the script. Default is True.\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nwith_plot = True\n" }, { "cell_type": "markdown", @@ -123,7 +123,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "tsd = tsd.rename(columns={\"pipe.T\": \"TPipe\", \"heatCapacitor.T\": \"TCapacity\"})\ntsd.to_datetime_index()\ntsd.save(pathlib.Path(examples_dir).joinpath(\"data\", \"PumpAndValve.hdf\"), key=\"examples\")\nprint(\"Saved data under\", pathlib.Path(examples_dir).joinpath(\"data\"))\n" + "source": "tsd = tsd.rename(columns={\"pipe.T\": \"TPipe\", \"heatCapacitor.T\": \"TCapacity\"})\ntsd.to_datetime_index()\ntsd.save(Path(examples_dir).joinpath(\"data\", \"PumpAndValve.hdf\"), key=\"examples\")\nprint(\"Saved data under\", Path(examples_dir).joinpath(\"data\"))\n" } ], "metadata": { diff --git a/examples/jupyter_notebooks/e2_A_optimization_problem_definition.ipynb b/examples/jupyter_notebooks/e2_A_optimization_problem_definition.ipynb index 907aaca9..a4bd6e6e 100644 --- a/examples/jupyter_notebooks/e2_A_optimization_problem_definition.ipynb +++ b/examples/jupyter_notebooks/e2_A_optimization_problem_definition.ipynb @@ -15,7 +15,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "import pathlib\n" + "source": "from pathlib import Path\n" }, { "cell_type": "markdown", @@ -51,7 +51,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "\"\"\"\nArguments of this example:\n\n:param [pathlib.Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param str statistical_measure:\n Measure to calculate the scalar of the objective,\n One of the supported methods in\n ebcpy.utils.statistics_analyzer.StatisticsAnalyzer\n e.g. RMSE, MAE, NRMSE\n:param bool multiple_classes:\n If False, all CalibrationClasses will have the\n same name\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nstatistical_measure = \"NRMSE\"\nmultiple_classes = True\n" + "source": "\"\"\"\nArguments of this example:\n\n:param [Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param str statistical_measure:\n Measure to calculate the scalar of the objective,\n One of the supported methods in\n ebcpy.utils.statistics_analyzer.StatisticsAnalyzer\n e.g. RMSE, MAE, NRMSE\n:param bool multiple_classes:\n If False, all CalibrationClasses will have the\n same name\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nstatistical_measure = \"NRMSE\"\nmultiple_classes = True\n" }, { "cell_type": "markdown", @@ -87,7 +87,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "data_dir = pathlib.Path(examples_dir).joinpath(\"data\")\nmeas_target_data = TimeSeriesData(data_dir.joinpath(\"measured_target_data.hdf\"), key=\"example\")\n" + "source": "data_dir = Path(examples_dir).joinpath(\"data\")\nmeas_target_data = TimeSeriesData(data_dir.joinpath(\"measured_target_data.hdf\"), key=\"example\")\n" }, { "cell_type": "markdown", diff --git a/examples/jupyter_notebooks/e2_B_optimization_problem_definition.ipynb b/examples/jupyter_notebooks/e2_B_optimization_problem_definition.ipynb index c523e409..8c55aafd 100644 --- a/examples/jupyter_notebooks/e2_B_optimization_problem_definition.ipynb +++ b/examples/jupyter_notebooks/e2_B_optimization_problem_definition.ipynb @@ -15,7 +15,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "import pathlib\n" + "source": "from pathlib import Path\n" }, { "cell_type": "markdown", @@ -51,7 +51,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "\"\"\"\nArguments of this example:\n\n:param [pathlib.Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param str statistical_measure:\n Measure to calculate the scalar of the objective,\n One of the supported methods in\n ebcpy.utils.statistics_analyzer.StatisticsAnalyzer\n e.g. RMSE, MAE, NRMSE\n:param bool multiple_classes:\n If False, all CalibrationClasses will have the\n same name\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nstatistical_measure = \"NRMSE\"\nmultiple_classes = True\n" + "source": "\"\"\"\nArguments of this example:\n\n:param [Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param str statistical_measure:\n Measure to calculate the scalar of the objective,\n One of the supported methods in\n ebcpy.utils.statistics_analyzer.StatisticsAnalyzer\n e.g. RMSE, MAE, NRMSE\n:param bool multiple_classes:\n If False, all CalibrationClasses will have the\n same name\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nstatistical_measure = \"NRMSE\"\nmultiple_classes = True\n" }, { "cell_type": "markdown", @@ -87,7 +87,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "data_dir = pathlib.Path(examples_dir).joinpath(\"data\")\nmeas_target_data = TimeSeriesData(data_dir.joinpath(\"PumpAndValve.hdf\"),\n key=\"examples\")\n" + "source": "data_dir = Path(examples_dir).joinpath(\"data\")\nmeas_target_data = TimeSeriesData(data_dir.joinpath(\"PumpAndValve.hdf\"),\n key=\"examples\")\n" }, { "cell_type": "markdown", diff --git a/examples/jupyter_notebooks/e3_1_verbose_sensitivity_analysis_example.ipynb b/examples/jupyter_notebooks/e3_1_verbose_sensitivity_analysis_example.ipynb index 218bdd7b..731b2aff 100644 --- a/examples/jupyter_notebooks/e3_1_verbose_sensitivity_analysis_example.ipynb +++ b/examples/jupyter_notebooks/e3_1_verbose_sensitivity_analysis_example.ipynb @@ -20,7 +20,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "import warnings\nimport pathlib\nimport matplotlib.pyplot as plt\nfrom aixcalibuha import SobolAnalyzer, FASTAnalyzer, MorrisAnalyzer\nfrom aixcalibuha.data_types import merge_calibration_classes\nfrom examples import setup_fmu, setup_calibration_classes\nfrom aixcalibuha import plotting\n" + "source": "import warnings\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nfrom aixcalibuha import SobolAnalyzer, FASTAnalyzer, MorrisAnalyzer\nfrom aixcalibuha.data_types import merge_calibration_classes\nfrom examples import setup_fmu, setup_calibration_classes\nfrom aixcalibuha import plotting\n" }, { "cell_type": "markdown", @@ -32,7 +32,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "\"\"\"\nExample process of a verbose sensitivity analysis for calibration and analysis porpoises.\nFirst, the sensitivity problem is constructed, in this example\nthe `sobol` method is chosen.\nAfterward, the SenAnalyzer class is instantiated to run the\nsensitivity analysis in the next step.\nThe result of this analysis is then printed to the user.\nand tuner-parameters are selected with these results.\nA comparison between different methods is shown.\nAt the end the option to save a reproduction archive is shown.\n\n:param [pathlib.Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n e.g. r\"LOCAL_PATH_TO\\AixCaliBuHA\\examples\"\n:param str example:\n Which example to run, \"A\" or \"B\"\n:param int n_cpu:\n Number of cores to use\n\n:return: A list of calibration classes\n:rtype: list\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nexample: str = \"B\"\nn_cpu: int = 1\n" + "source": "\"\"\"\nExample process of a verbose sensitivity analysis for calibration and analysis porpoises.\nFirst, the sensitivity problem is constructed, in this example\nthe `sobol` method is chosen.\nAfterward, the SenAnalyzer class is instantiated to run the\nsensitivity analysis in the next step.\nThe result of this analysis is then printed to the user.\nand tuner-parameters are selected with these results.\nA comparison between different methods is shown.\nAt the end the option to save a reproduction archive is shown.\n\n:param [Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n e.g. r\"LOCAL_PATH_TO\\AixCaliBuHA\\examples\"\n:param str example:\n Which example to run, \"A\" or \"B\"\n:param int n_cpu:\n Number of cores to use\n\n:return: A list of calibration classes\n:rtype: list\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nexample: str = \"B\"\nn_cpu: int = 1\n" }, { "cell_type": "markdown", @@ -44,7 +44,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "examples_dir = pathlib.Path(examples_dir)\nsim_api = setup_fmu(examples_dir=examples_dir, example=example, n_cpu=n_cpu)\n" + "source": "examples_dir = Path(examples_dir)\nsim_api = setup_fmu(examples_dir=examples_dir, example=example, n_cpu=n_cpu)\n" }, { "cell_type": "markdown", diff --git a/examples/jupyter_notebooks/e3_2_verbose_dymola_sensitivity_analysis_example.ipynb b/examples/jupyter_notebooks/e3_2_verbose_dymola_sensitivity_analysis_example.ipynb index ef7ac32a..2c3e152e 100644 --- a/examples/jupyter_notebooks/e3_2_verbose_dymola_sensitivity_analysis_example.ipynb +++ b/examples/jupyter_notebooks/e3_2_verbose_dymola_sensitivity_analysis_example.ipynb @@ -15,7 +15,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "import os\nimport pathlib\nfrom examples import setup_dym_api, setup_calibration_classes\n" + "source": "import os\nfrom pathlib import Path\nfrom examples import setup_dym_api, setup_calibration_classes\n" }, { "cell_type": "markdown", @@ -39,7 +39,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "\"\"\"\nExample process of a verbose sensitivity analysis with the dymola_api.\n\n:param [pathlib.Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param [pathlib.Path, str] aixlib_mo:\n Path to the AixLib package.mo file.\n:param str example:\n Which example to run, \"A\" or \"B\"\n:param int n_cpu:\n Number of cores to use\n\n:return: A list of calibration classes\n:rtype: list\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\naixlib_mo = \"TODO: Add a valid input according to the docstring above\"\nexample: str = \"B\"\nn_cpu: int = 1\n" + "source": "\"\"\"\nExample process of a verbose sensitivity analysis with the dymola_api.\n\n:param [Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param [Path, str] aixlib_mo:\n Path to the AixLib package.mo file.\n:param str example:\n Which example to run, \"A\" or \"B\"\n:param int n_cpu:\n Number of cores to use\n\n:return: A list of calibration classes\n:rtype: list\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\naixlib_mo = \"TODO: Add a valid input according to the docstring above\"\nexample: str = \"B\"\nn_cpu: int = 1\n" }, { "cell_type": "markdown", @@ -51,7 +51,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "examples_dir = pathlib.Path(examples_dir)\nsim_api = setup_dym_api(examples_dir=examples_dir,\n aixlib_mo=aixlib_mo,\n example=example,\n n_cpu=n_cpu)\ncalibration_classes = setup_calibration_classes(\n examples_dir=examples_dir, example=example, multiple_classes=False\n)[0]\nmerged_calibration_classes = merge_calibration_classes(calibration_classes)\nmerged_calibration_classes[0].name = 'global'\ncalibration_classes = setup_calibration_classes(\n examples_dir=examples_dir, example=example, multiple_classes=True\n)[0]\nmerged_calibration_classes.extend(merge_calibration_classes(calibration_classes))\n\nif example == 'B':\n merged_calibration_classes[-1].tuner_paras = merged_calibration_classes[0].tuner_paras\n" + "source": "examples_dir = Path(examples_dir)\nsim_api = setup_dym_api(examples_dir=examples_dir,\n aixlib_mo=aixlib_mo,\n example=example,\n n_cpu=n_cpu)\ncalibration_classes = setup_calibration_classes(\n examples_dir=examples_dir, example=example, multiple_classes=False\n)[0]\nmerged_calibration_classes = merge_calibration_classes(calibration_classes)\nmerged_calibration_classes[0].name = 'global'\ncalibration_classes = setup_calibration_classes(\n examples_dir=examples_dir, example=example, multiple_classes=True\n)[0]\nmerged_calibration_classes.extend(merge_calibration_classes(calibration_classes))\n\nif example == 'B':\n merged_calibration_classes[-1].tuner_paras = merged_calibration_classes[0].tuner_paras\n" }, { "cell_type": "markdown", diff --git a/examples/jupyter_notebooks/e3_sensitivity_analysis_example.ipynb b/examples/jupyter_notebooks/e3_sensitivity_analysis_example.ipynb index 6b79020d..b4d248eb 100644 --- a/examples/jupyter_notebooks/e3_sensitivity_analysis_example.ipynb +++ b/examples/jupyter_notebooks/e3_sensitivity_analysis_example.ipynb @@ -27,7 +27,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "\"\"\"\nExample process of a sensitivity analysis.\nFirst, the sensitivity problem is constructed, in this example\nthe `morris` method is chosen.\nAfterward, the sen_analyzer class is instantiated to run the\nsensitivity analysis in the next step.\nThe result of this analysis is then printed to the user.\nThe automatic_select function is presented as-well, using a threshold of 1\nand the default `mu_star` criterion.\n\n:param [pathlib.Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param str example:\n Which example to run, \"A\" or \"B\"\n:param int n_cpu:\n Number of cores to use\n\n:return: A list of calibration classes\n:rtype: list\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nexample: str = \"B\"\nn_cpu: int = 1\n" + "source": "\"\"\"\nExample process of a sensitivity analysis.\nFirst, the sensitivity problem is constructed, in this example\nthe `morris` method is chosen.\nAfterward, the sen_analyzer class is instantiated to run the\nsensitivity analysis in the next step.\nThe result of this analysis is then printed to the user.\nThe automatic_select function is presented as-well, using a threshold of 1\nand the default `mu_star` criterion.\n\n:param [Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param str example:\n Which example to run, \"A\" or \"B\"\n:param int n_cpu:\n Number of cores to use\n\n:return: A list of calibration classes\n:rtype: list\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nexample: str = \"B\"\nn_cpu: int = 1\n" }, { "cell_type": "markdown", diff --git a/examples/jupyter_notebooks/e3_verbose_dymola_sensitivity_analysis_example.ipynb b/examples/jupyter_notebooks/e3_verbose_dymola_sensitivity_analysis_example.ipynb index ef7ac32a..2c3e152e 100644 --- a/examples/jupyter_notebooks/e3_verbose_dymola_sensitivity_analysis_example.ipynb +++ b/examples/jupyter_notebooks/e3_verbose_dymola_sensitivity_analysis_example.ipynb @@ -15,7 +15,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "import os\nimport pathlib\nfrom examples import setup_dym_api, setup_calibration_classes\n" + "source": "import os\nfrom pathlib import Path\nfrom examples import setup_dym_api, setup_calibration_classes\n" }, { "cell_type": "markdown", @@ -39,7 +39,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "\"\"\"\nExample process of a verbose sensitivity analysis with the dymola_api.\n\n:param [pathlib.Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param [pathlib.Path, str] aixlib_mo:\n Path to the AixLib package.mo file.\n:param str example:\n Which example to run, \"A\" or \"B\"\n:param int n_cpu:\n Number of cores to use\n\n:return: A list of calibration classes\n:rtype: list\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\naixlib_mo = \"TODO: Add a valid input according to the docstring above\"\nexample: str = \"B\"\nn_cpu: int = 1\n" + "source": "\"\"\"\nExample process of a verbose sensitivity analysis with the dymola_api.\n\n:param [Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param [Path, str] aixlib_mo:\n Path to the AixLib package.mo file.\n:param str example:\n Which example to run, \"A\" or \"B\"\n:param int n_cpu:\n Number of cores to use\n\n:return: A list of calibration classes\n:rtype: list\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\naixlib_mo = \"TODO: Add a valid input according to the docstring above\"\nexample: str = \"B\"\nn_cpu: int = 1\n" }, { "cell_type": "markdown", @@ -51,7 +51,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "examples_dir = pathlib.Path(examples_dir)\nsim_api = setup_dym_api(examples_dir=examples_dir,\n aixlib_mo=aixlib_mo,\n example=example,\n n_cpu=n_cpu)\ncalibration_classes = setup_calibration_classes(\n examples_dir=examples_dir, example=example, multiple_classes=False\n)[0]\nmerged_calibration_classes = merge_calibration_classes(calibration_classes)\nmerged_calibration_classes[0].name = 'global'\ncalibration_classes = setup_calibration_classes(\n examples_dir=examples_dir, example=example, multiple_classes=True\n)[0]\nmerged_calibration_classes.extend(merge_calibration_classes(calibration_classes))\n\nif example == 'B':\n merged_calibration_classes[-1].tuner_paras = merged_calibration_classes[0].tuner_paras\n" + "source": "examples_dir = Path(examples_dir)\nsim_api = setup_dym_api(examples_dir=examples_dir,\n aixlib_mo=aixlib_mo,\n example=example,\n n_cpu=n_cpu)\ncalibration_classes = setup_calibration_classes(\n examples_dir=examples_dir, example=example, multiple_classes=False\n)[0]\nmerged_calibration_classes = merge_calibration_classes(calibration_classes)\nmerged_calibration_classes[0].name = 'global'\ncalibration_classes = setup_calibration_classes(\n examples_dir=examples_dir, example=example, multiple_classes=True\n)[0]\nmerged_calibration_classes.extend(merge_calibration_classes(calibration_classes))\n\nif example == 'B':\n merged_calibration_classes[-1].tuner_paras = merged_calibration_classes[0].tuner_paras\n" }, { "cell_type": "markdown", diff --git a/examples/jupyter_notebooks/e3_verbose_sensitivity_analysis_example.ipynb b/examples/jupyter_notebooks/e3_verbose_sensitivity_analysis_example.ipynb index 218bdd7b..731b2aff 100644 --- a/examples/jupyter_notebooks/e3_verbose_sensitivity_analysis_example.ipynb +++ b/examples/jupyter_notebooks/e3_verbose_sensitivity_analysis_example.ipynb @@ -20,7 +20,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "import warnings\nimport pathlib\nimport matplotlib.pyplot as plt\nfrom aixcalibuha import SobolAnalyzer, FASTAnalyzer, MorrisAnalyzer\nfrom aixcalibuha.data_types import merge_calibration_classes\nfrom examples import setup_fmu, setup_calibration_classes\nfrom aixcalibuha import plotting\n" + "source": "import warnings\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nfrom aixcalibuha import SobolAnalyzer, FASTAnalyzer, MorrisAnalyzer\nfrom aixcalibuha.data_types import merge_calibration_classes\nfrom examples import setup_fmu, setup_calibration_classes\nfrom aixcalibuha import plotting\n" }, { "cell_type": "markdown", @@ -32,7 +32,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "\"\"\"\nExample process of a verbose sensitivity analysis for calibration and analysis porpoises.\nFirst, the sensitivity problem is constructed, in this example\nthe `sobol` method is chosen.\nAfterward, the SenAnalyzer class is instantiated to run the\nsensitivity analysis in the next step.\nThe result of this analysis is then printed to the user.\nand tuner-parameters are selected with these results.\nA comparison between different methods is shown.\nAt the end the option to save a reproduction archive is shown.\n\n:param [pathlib.Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n e.g. r\"LOCAL_PATH_TO\\AixCaliBuHA\\examples\"\n:param str example:\n Which example to run, \"A\" or \"B\"\n:param int n_cpu:\n Number of cores to use\n\n:return: A list of calibration classes\n:rtype: list\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nexample: str = \"B\"\nn_cpu: int = 1\n" + "source": "\"\"\"\nExample process of a verbose sensitivity analysis for calibration and analysis porpoises.\nFirst, the sensitivity problem is constructed, in this example\nthe `sobol` method is chosen.\nAfterward, the SenAnalyzer class is instantiated to run the\nsensitivity analysis in the next step.\nThe result of this analysis is then printed to the user.\nand tuner-parameters are selected with these results.\nA comparison between different methods is shown.\nAt the end the option to save a reproduction archive is shown.\n\n:param [Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n e.g. r\"LOCAL_PATH_TO\\AixCaliBuHA\\examples\"\n:param str example:\n Which example to run, \"A\" or \"B\"\n:param int n_cpu:\n Number of cores to use\n\n:return: A list of calibration classes\n:rtype: list\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nexample: str = \"B\"\nn_cpu: int = 1\n" }, { "cell_type": "markdown", @@ -44,7 +44,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "examples_dir = pathlib.Path(examples_dir)\nsim_api = setup_fmu(examples_dir=examples_dir, example=example, n_cpu=n_cpu)\n" + "source": "examples_dir = Path(examples_dir)\nsim_api = setup_fmu(examples_dir=examples_dir, example=example, n_cpu=n_cpu)\n" }, { "cell_type": "markdown", diff --git a/examples/jupyter_notebooks/e4_calibration_example.ipynb b/examples/jupyter_notebooks/e4_calibration_example.ipynb index ae692fd9..e3d9433a 100644 --- a/examples/jupyter_notebooks/e4_calibration_example.ipynb +++ b/examples/jupyter_notebooks/e4_calibration_example.ipynb @@ -27,7 +27,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "\"\"\"\nRun an example for a calibration. Make sure you have Dymola installed\non your device and a working licence. All output data will be stored in\nthe current working directory of python. Look at the logs and plots\nto better understand what is happening in the calibration. If you want, you\ncan switch the methods to other supported methods or change the framework and\ntry the global optimizer of dlib.\n\n:param [pathlib.Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param str example:\n Which example to run, \"A\" or \"B\"\n:param int n_cpu:\n Number of cores to use\n\nOptional, for the fully automated process\n:param ebcpy.simulationapi.SimulationAPI sim_api:\n Simulation API to simulate the models\n:param list[CalibrationClass] cal_classes:\n List with multiple CalibrationClass objects for calibration. Goals and\n TunerParameters have to be set. If only one class is provided (either\n a list with one entry or a CalibrationClass object) the single-class\n Calibrator is used.\n:param CalibrationClass framework:\n See Documentation of ebcpy on available optimization frameworks\n:param str method:\n See Documentation of ebcpy on available optimization framework methods\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nexample = \"B\"\nn_cpu: int = 1\nsim_api = None\ncal_classes = None\nframework: str = \"scipy_differential_evolution\"\nmethod: str = \"best1bin\"\n" + "source": "\"\"\"\nRun an example for a calibration. Make sure you have Dymola installed\non your device and a working licence. All output data will be stored in\nthe current working directory of python. Look at the logs and plots\nto better understand what is happening in the calibration. If you want, you\ncan switch the methods to other supported methods or change the framework and\ntry the global optimizer of dlib.\n\n:param [Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param str example:\n Which example to run, \"A\" or \"B\"\n:param int n_cpu:\n Number of cores to use\n\nOptional, for the fully automated process\n:param ebcpy.simulationapi.SimulationAPI sim_api:\n Simulation API to simulate the models\n:param list[CalibrationClass] cal_classes:\n List with multiple CalibrationClass objects for calibration. Goals and\n TunerParameters have to be set. If only one class is provided (either\n a list with one entry or a CalibrationClass object) the single-class\n Calibrator is used.\n:param CalibrationClass framework:\n See Documentation of ebcpy on available optimization frameworks\n:param str method:\n See Documentation of ebcpy on available optimization framework methods\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nexample = \"B\"\nn_cpu: int = 1\nsim_api = None\ncal_classes = None\nframework: str = \"scipy_differential_evolution\"\nmethod: str = \"best1bin\"\n" }, { "cell_type": "markdown", diff --git a/examples/jupyter_notebooks/e5_automated_process.ipynb b/examples/jupyter_notebooks/e5_automated_process.ipynb index 17130d51..a30e6f03 100644 --- a/examples/jupyter_notebooks/e5_automated_process.ipynb +++ b/examples/jupyter_notebooks/e5_automated_process.ipynb @@ -27,7 +27,7 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": "\"\"\"\nArguments of this example:\n\n:param [pathlib.Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param str example:\n Whether to use example A (requires windows) or B.\n Default is \"A\"\n:param int n_cpu:\n Number of cores to use\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nexample: str = \"A\"\nn_cpu: int = 1\n" + "source": "\"\"\"\nArguments of this example:\n\n:param [Path, str] examples_dir:\n Path to the examples folder of AixCaliBuHA\n:param str example:\n Whether to use example A (requires windows) or B.\n Default is \"A\"\n:param int n_cpu:\n Number of cores to use\n\"\"\"\nexamples_dir = \"TODO: Add a valid input according to the docstring above\"\nexample: str = \"A\"\nn_cpu: int = 1\n" }, { "cell_type": "markdown", diff --git a/tests/test_config.py b/tests/test_config.py index 0537002d..5e4f8cf7 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,7 +1,7 @@ """Test-module for all classes inside aixcalibuha.calibration""" import unittest -import pathlib +from pathlib import Path import aixcalibuha from aixcalibuha.utils import configuration @@ -15,7 +15,7 @@ def test_import(self): def test_funcs(self): """Test functions""" - example_hdf = pathlib.Path(__file__).parents[1].joinpath("examples", + example_hdf = Path(__file__).parents[1].joinpath("examples", "data", "PumpAndValve.hdf") var_names = {"TCap": ["TCapacity", "heatCapacitor.T"], diff --git a/tests/test_data_types.py b/tests/test_data_types.py index 9bdc67fb..80ba430f 100644 --- a/tests/test_data_types.py +++ b/tests/test_data_types.py @@ -1,6 +1,6 @@ """Test-module for all classes inside aixcalibuha.__init__.py""" -import pathlib +from pathlib import Path import unittest import numpy as np from ebcpy import data_types @@ -14,7 +14,7 @@ def setUp(self): """Called before every test. Define example paths and parameters used in all test-functions. """ - self.framework_dir = pathlib.Path(__file__).parents[1] + self.framework_dir = Path(__file__).parents[1] self.example_dir = self.framework_dir.joinpath("examples", "data") def test_calibration_class(self): diff --git a/tests/test_modelica_cal_sen.py b/tests/test_modelica_cal_sen.py index 8cc8acee..7e84dbee 100644 --- a/tests/test_modelica_cal_sen.py +++ b/tests/test_modelica_cal_sen.py @@ -5,7 +5,7 @@ import unittest import sys import os -import pathlib +from pathlib import Path import shutil import matplotlib.pyplot as plt @@ -17,7 +17,7 @@ def _set_up(): - aixcalibuha_dir = pathlib.Path(__file__).parents[1] + aixcalibuha_dir = Path(__file__).parents[1] data_dir = aixcalibuha_dir.joinpath("examples", "data") testzone_dir = aixcalibuha_dir.joinpath("tests", "testzone") @@ -73,7 +73,7 @@ def setUp(self): def test_modelica_calibrator(self): """Function for testing of class calibration.Calibrator.""" calibrator = Calibrator( - cd=self.sim_api.cd, + working_directory=self.sim_api.cd, sim_api=self.sim_api, calibration_class=self.calibration_classes[0], show_plot=False, @@ -85,7 +85,7 @@ def test_modelica_calibrator(self): def test_mutliple_class_calibration(self): """Function for testing of class calibration.FixStartContModelicaCal.""" calibrator = MultipleClassCalibrator( - cd=self.example_cal_dir, + working_directory=self.example_cal_dir, sim_api=self.sim_api, calibration_classes=self.calibration_classes, start_time_method='fixstart', diff --git a/tutorial/tutorial.ipynb b/tutorial/tutorial.ipynb index 09c9d996..14a482af 100644 --- a/tutorial/tutorial.ipynb +++ b/tutorial/tutorial.ipynb @@ -106,8 +106,8 @@ "source": [ "from ebcpy import data_types, preprocessing\n", "from aixcalibuha import Goals\n", - "import pathlib, os\n", - "basepath = pathlib.Path(os.getcwd()).parent\n", + "from pathlib import Path, os\n", + "basepath = Path(os.getcwd()).parent\n", "# First we load our measurement data as time series data from the examples folder\n", "path = basepath.joinpath(\"examples\", \"data\", \"PumpAndValve.hdf\")\n", "mtd = data_types.TimeSeriesData(path, key=\"examples\")\n", @@ -308,7 +308,7 @@ "\n", "def setup_fmu():\n", " \"\"\"Setup the FMU used in all examples and tests.\"\"\"\n", - " example_dir = pathlib.Path(os.getcwd()).parent\n", + " example_dir = Path(os.getcwd()).parent\n", "\n", " if \"win\" in sys.platform:\n", " model_name = example_dir.joinpath(\"examples\", \"model\", \"PumpAndValve_windows.fmu\")\n", @@ -330,7 +330,7 @@ "\n", "# %% Parameters for sen-analysis:\n", "# Check out the ebcpy tutorial for an introduction to the simulation API.\n", - "cd = os.path.normpath(os.path.join(os.getcwd(), \"testzone\"))\n", + "cd = Path(os.path.join(os.getcwd(), \"testzone\"))\n", "sim_api = setup_fmu()\n", "\n", "# Pick out a calibration class\n", @@ -465,7 +465,7 @@ "\n", "# Equivalent to the setup of the single-class-calibration:\n", "statistical_measure = \"RMSE\"\n", - "cd = os.path.normpath(os.path.join(os.getcwd(), \"testzone\"))\n", + "cd = Path(os.path.join(os.getcwd(), \"testzone\"))\n", "framework=\"scipy_differential_evolution\"\n", "method=\"best1bin\"\n", "# Choose options for multiple-class-calibration:\n", From 693f032368976ed85b8b07a802a98e1551c645d9 Mon Sep 17 00:00:00 2001 From: Hendrik van der Stok Date: Fri, 12 Apr 2024 15:17:58 +0200 Subject: [PATCH 3/3] chore: update changelog and increas version --- CHANGELOG.md | 3 +++ aixcalibuha/__init__.py | 2 +- setup.py | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 83414bde..0a6a2516 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,3 +60,6 @@ - Sensitivity analysis is now usable for large models and data - Add time dependent sensitivity analysis - Ends support for python 3.7 + +- **v1.0.1** + - refactor cd to working_directory #57 diff --git a/aixcalibuha/__init__.py b/aixcalibuha/__init__.py index db00633f..314fda7b 100644 --- a/aixcalibuha/__init__.py +++ b/aixcalibuha/__init__.py @@ -7,4 +7,4 @@ from .sensitivity_analysis import SobolAnalyzer, MorrisAnalyzer, FASTAnalyzer, PAWNAnalyzer, \ plotting -__version__ = "1.0.0" +__version__ = "1.0.1" diff --git a/setup.py b/setup.py index c3358ec6..5c4eb530 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ 'toml>=0.10.2' ] -__version__ = "1.0.0" +__version__ = "1.0.1" setuptools.setup( name='aixcalibuha',