Source code for viiapackage.general.file_handling.viia_get_latest_model_folder

### ===================================================================================================================
###   Get most recent model from analysis folder
### ===================================================================================================================
# Copyright ©VIIA 2024

### ===================================================================================================================
###   1. Import modules
### ===================================================================================================================

# General imports
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING, Optional, Union, Dict

# References for functions and classes in the viiaPackage
if TYPE_CHECKING:
    from viiapackage.viiaStatus import ViiaProject


### ===================================================================================================================
###    2. Function to get latest model folder
### ===================================================================================================================

[docs]def viia_get_latest_model_folder( project: ViiaProject, version: Optional[Union[int, str]] = None, folder: Optional[Path] = None, analysis_nr: Optional[str] = None, signal: Optional[str] = None) -> Optional[Path]: """ This function selects the latest model from the default analysis sub-folders. The path is based on the latest version and time an in the name of the folder. The version number determines the required model step. For BSC, the version is always 1. For TVA, the specific step must be provided. Within this selection the latest timestamp in the folder name is used to find the folder. Input: - project (obj): VIIA project object containing collections of fem objects and project variables. - version (int): The version number as indicated at start of the project. By VIIA convention version number 1 indicates the BSC and higher numbers the strengthening steps. To get the latest model folder with the highest version number, provide input 'highest'. Default value is None, using the version specified in the project. - folder (path): The path of the folder containing the folders from which the latest result folder must be obtained. - analysis_nr (str): The name of the analysis referencing the numbers in the viiaStatus. For example 'A1'. - signal (str): The signal number specified as a string. The available signals are S1, S2, S3, S4, S5, S6, S7, S8, S9, S10 and S11. Required if analysis_name is 'A4', 'A12' or 'A15' or if the folder provided corresponds to one of these three analyses. Output: - The latest result folder for the specified version number is returned as path reference. """ # Check input for version if version is None: version = project.version # Check if the working folder is provided. In that case only the analysis folders with default names are checked. folders = {} # Get the folder based on the requested analysis if not folder: # If signal is provided, find the corresponding signal sub-folder if signal: if not analysis_nr: raise ValueError(f"Error: Signal {signal} is provided but not analysis_name or folder. Please provide " f"one of the two.") else: folders = viia_get_latest_model_folder_signal( project=project, analysis_nr=analysis_nr, signal=signal) else: folder = project.workfolder_location analysis_folders = [] for item in folder.iterdir(): if item.is_dir(): for analysis_int in [1, 2, 3, 4, 7, 10, 12, 13, 15]: if f'A{analysis_int} - ' in item.stem: analysis_folders.append(item) # Filter for a specific analysis, if user requested if analysis_nr: analysis_folders = [fold for fold in analysis_folders if analysis_nr + ' - ' in fold.stem] # Create a dictionary with all the folders of the correct version, key is the timestamp folders = {} for item in folder.iterdir(): if item.is_dir() and item in analysis_folders: folders.update(viia_get_latest_folder(version=version, folder=item)) # When a specific folder is provided else: if not isinstance(folder, Path): folder = Path(folder) if not folder.exists(): return None # if signal is provided, find the corresponding signal sub-folder if signal: if not analysis_nr: if 'A4' in str(folder): analysis_nr = 'A4' elif 'A12' in str(folder): analysis_nr = 'A12' elif 'A15' in str(folder): analysis_nr = 'A15' else: raise ValueError(f"Error: If a signal is provided, the folder provided should correspond to a " f"time-history analysis. The provided folder is {folder}") folders = viia_get_latest_model_folder_signal( project=project, analysis_nr=analysis_nr, signal=signal, version=version) else: folders = viia_get_latest_folder(version=version, folder=folder) # Select the maximum value of the timestamp, this is the latest folder if folders: if isinstance(folders, dict): return project.workfolder_location / folders[max(folders.keys())] elif isinstance(folders, Path): return folders else: return None else: return None
[docs]def viia_get_latest_model_folder_signal( project: ViiaProject, analysis_nr: str, signal: str, version: Optional[int] = None) -> Optional[Path]: """ This function selects the latest model from the default A4/A12/A15 analysis sub-folders for a given signal. The path is based on the latest version and timestamp in the name of the folder that contains the given signal. Input: - project (obj): VIIA project object containing collections of fem objects and project variables. - analysis_nr (str): The number of the time history analysis. Choose from "A4", "A12" or "A15". - signal (str): The signal number specified as a string. The available signals are S1, S2, S3, S4, S5, S6, S7, S8, S9, S10 and S11. - version (int): The version number as indicated at start of the project. By VIIA convention version number 1 indicates the BSC and higher numbers the strengthening steps. To get the latest model folder with the highest version number, provide input 'highest'. Default value is None, using the version specified in the project. Output: - The latest result folder for the specified analysis and signal is returned as path reference. """ # Check input for version if version is None: version = project.version path = None if analysis_nr == 'A4': path = project.workfolder_location / 'A4 - LTH fixed base' elif analysis_nr == 'A12': path = project.workfolder_location / 'A12 - NLTH flex base' elif analysis_nr == 'A15': path = project.workfolder_location / 'A15 - NLTH flex base strengthening' if project.version == 1: project.write_log( f"WARNING: The project version number for A15 analysis should be greater than 1. Please check.") else: raise ValueError(f"ERROR: The analysis_nr should be one of 'A4', 'A12', 'A15'. You specified {analysis_nr}.") if not path or not path.exists(): project.write_log( f"WARNING: {analysis_nr} analysis folder cannot be found. Results can not be generated.") seismic_result_folder = None timestamp_folders = viia_get_latest_folder(version=version, folder=path) for _key in reversed(sorted(timestamp_folders)): seismic_result_folder = Path(timestamp_folders[_key] / signal) if seismic_result_folder.exists() and seismic_result_folder.is_dir(): break seismic_result_folder = None if not seismic_result_folder: project.write_log( f"WARNING: Signal {signal} in {analysis_nr} analysis folder cannot be found. Results can not be " f"generated.") else: project.write_log( f"NLTH results for signal {signal} for {analysis_nr} analysis will be taken from {seismic_result_folder}" f".") return seismic_result_folder
### =================================================================================================================== ### 3. Function to get the most recent folder based on VIIA naming convention ### ===================================================================================================================
[docs]def viia_get_latest_folder(version: Union[str, int], folder: Path) -> Dict[int, Path]: """ Function to collect the sub-folders within the requested folder that comply to the requested version. The timestamp is used as key in dictionary with these sub-folders, for easy selecting latest folder. Input: - version (int): The version number as indicated at start of the project. By VIIA convention version number 1 indicates the BSC and higher numbers the strengthening steps. To get the latest model folder with the highest version number, provide input 'highest'. - folder (path): Path of the folder for which the sub-folders are retrieved. Output: - Returns dictionary with (keys) the timestamp of the sub-folder and values the path to the folder. Note that if version doesn't match any of the sub-folders, the dictionary returned will be empty. """ # Create folder list list_folders = [] for item in folder.iterdir(): if item.is_dir(): if item.stem[:14].isdigit(): list_folders.append(item) else: for sub_item in item.iterdir(): if sub_item.is_dir(): if sub_item.stem[:14].isdigit(): list_folders.append(sub_item) # Create a dictionary with the required version number folders_dict = {} # Expected format folder (VIIA convention) A12 - NLTH flex base\S1\202209281200000-v001 if isinstance(version, str) and version.lower() == 'highest': max_version = 0 for item in list_folders: version_nr = int(item.stem.split('-v')[-1]) if version_nr > max_version: max_version = version_nr version = max_version if isinstance(version, int) and version == 0: return {} if isinstance(version, int) and version > 0: # Remove the version part for the keys to be the timestamp version_check = '-v' + str(version).zfill(3) for item in list_folders: if version_check in item.stem: folders_dict[int(item.stem.replace(version_check, ''))] = item return folders_dict raise TypeError( f"ERROR: The version {version} is not recognised, please provide a positive integer or string ('highest').")
### =================================================================================================================== ### 4. End of script ### ===================================================================================================================