diff --git a/.github/workflows/format_check.yml b/.github/workflows/format_check.yml index 9225af459..dca19a00f 100644 --- a/.github/workflows/format_check.yml +++ b/.github/workflows/format_check.yml @@ -1,25 +1,10 @@ -name: Format Check - +name: Ruff format on: [push, pull_request] - jobs: - format-check: + ruff: runs-on: ubuntu-latest - steps: - - name: Checkout code - uses: actions/checkout@v2 - - - name: Set up Python - uses: actions/setup-python@v2 - with: - python-version: '3.10' - - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install ruff - - - name: Check code formatting - run: | - ruff check . --diff + - uses: actions/checkout@v4 + - uses: chartboost/ruff-action@v1 + with: + args: 'format --check' diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index c4fd6475b..744b4e642 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -1,25 +1,8 @@ -name: Lint - +name: Ruff check on: [push, pull_request] - jobs: - lint: + ruff: runs-on: ubuntu-latest - steps: - - name: Checkout code - uses: actions/checkout@v2 - - - name: Set up Python - uses: actions/setup-python@v2 - with: - python-version: '3.10' - - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install ruff - - - name: Run linter - run: | - ruff check . + - uses: actions/checkout@v4 + - uses: chartboost/ruff-action@v1 diff --git a/modules/Workflow/CMakeLists.txt b/modules/Workflow/CMakeLists.txt index 97a1b7c19..0397a6208 100644 --- a/modules/Workflow/CMakeLists.txt +++ b/modules/Workflow/CMakeLists.txt @@ -4,6 +4,7 @@ simcenter_add_python_script(SCRIPT changeJSON.py) simcenter_add_python_script(SCRIPT "sWHALE.py") simcenter_add_python_script(SCRIPT "qWHALE.py") simcenter_add_python_script(SCRIPT "rWHALE.py") +simcenter_add_python_script(SCRIPT "createResponseCSV.py") simcenter_add_python_script(SCRIPT "siteResponseWHALE.py") simcenter_add_python_script(SCRIPT "createGM4BIM.py") simcenter_add_python_script(SCRIPT "computeResponseSpectrum.py") @@ -19,4 +20,4 @@ simcenter_add_python_script(SCRIPT R2DTool_workflow.py) simcenter_add_python_script(SCRIPT CreateWorkflowJobs.py) simcenter_add_executable(NAME runMultiModelDriver - FILES runMultiModelDriver.cpp) \ No newline at end of file + FILES runMultiModelDriver.cpp) diff --git a/modules/Workflow/MultiModelDriver.py b/modules/Workflow/MultiModelDriver.py index f976b1c9e..8cce7eb09 100644 --- a/modules/Workflow/MultiModelDriver.py +++ b/modules/Workflow/MultiModelDriver.py @@ -162,14 +162,16 @@ def main(inputFile, driverFile, appKey, registryFile, appDir, runType, osType): 'UTF-8', ) ) - elif osType == 'Windows' and runType == 'runningRemote': + elif runType == 'runningRemote': with open(driverFile, 'wb') as f: # noqa: PTH123 f.write( - appDir - + '/applications/Workflow/' - + exeFileName - + f' {paramsFileName} {driverFile} {multiModelString}', - 'UTF-8', + bytes( + appDir + + '/applications/Workflow/' + + exeFileName + + f' {paramsFileName} {driverFile} {multiModelString}', + 'UTF-8', + ) ) else: with open(driverFile, 'wb') as f: # noqa: PTH123 diff --git a/modules/Workflow/computeResponseSpectrum.py b/modules/Workflow/computeResponseSpectrum.py index d17b52882..bb4ad3f09 100644 --- a/modules/Workflow/computeResponseSpectrum.py +++ b/modules/Workflow/computeResponseSpectrum.py @@ -23,7 +23,7 @@ def convert_accel_units(acceleration, from_, to_='cm/s/s'): # noqa: C901 acceleration = np.asarray(acceleration) if from_ == 'g': if to_ == 'g': - return acceleration + return acceleration # noqa: DOC201, RUF100 if to_ in m_sec_square: return acceleration * g if to_ in cm_sec_square: @@ -70,7 +70,7 @@ def get_velocity_displacement( velocity = time_step * cumtrapz(acceleration, initial=0.0) if displacement is None: displacement = time_step * cumtrapz(velocity, initial=0.0) - return velocity, displacement + return velocity, displacement # noqa: DOC201, RUF100 class NewmarkBeta: @@ -160,7 +160,7 @@ def run(self): 'PGV': np.max(np.fabs(self.velocity)), 'PGD': np.max(np.fabs(self.displacement)), } - return self.response_spectrum, time_series, accel, vel, disp + return self.response_spectrum, time_series, accel, vel, disp # noqa: DOC201, RUF100 def _newmark_beta(self, omega, cval, kval): # noqa: ARG002 """Newmark-beta integral @@ -216,4 +216,4 @@ def _newmark_beta(self, omega, cval, kval): # noqa: ARG002 disp[j, :] = delta_u + disp[j - 1, :] a_t[j, :] = ground_acc[j] + accel[j, :] - return accel, vel, disp, a_t + return accel, vel, disp, a_t # noqa: DOC201, RUF100 diff --git a/modules/Workflow/createGM4BIM.py b/modules/Workflow/createGM4BIM.py index c01d67f69..d2fb8f22d 100644 --- a/modules/Workflow/createGM4BIM.py +++ b/modules/Workflow/createGM4BIM.py @@ -120,7 +120,7 @@ def get_scale_factors(input_units, output_units): # noqa: C901 scale_factors.update({input_name: f_scale}) - return scale_factors + return scale_factors # noqa: DOC201, RUF100 def createFilesForEventGrid(inputDir, outputDir, removeInputDir): # noqa: C901, N802, N803, D103, PLR0915 @@ -410,28 +410,28 @@ def createFilesForEventGrid(inputDir, outputDir, removeInputDir): # noqa: C901, m_pgd_y = 0.0 s_pgd_y = 0.0 # add to dictionary - dict_im[('type', 'loc', 'dir', 'stat')].append(int(siteID)) + dict_im[('type', 'loc', 'dir', 'stat')].append(int(siteID)) # noqa: RUF031, RUF100 # pga - dict_im[('PGA', 0, 1, 'median')].append(m_pga_x) - dict_im[('PGA', 0, 1, 'beta')].append(s_pga_x) - dict_im[('PGA', 0, 2, 'median')].append(m_pga_y) - dict_im[('PGA', 0, 2, 'beta')].append(s_pga_y) + dict_im[('PGA', 0, 1, 'median')].append(m_pga_x) # noqa: RUF031, RUF100 + dict_im[('PGA', 0, 1, 'beta')].append(s_pga_x) # noqa: RUF031, RUF100 + dict_im[('PGA', 0, 2, 'median')].append(m_pga_y) # noqa: RUF031, RUF100 + dict_im[('PGA', 0, 2, 'beta')].append(s_pga_y) # noqa: RUF031, RUF100 # pgv - dict_im[('PGV', 0, 1, 'median')].append(m_pgv_x) - dict_im[('PGV', 0, 1, 'beta')].append(s_pgv_x) - dict_im[('PGV', 0, 2, 'median')].append(m_pgv_y) - dict_im[('PGV', 0, 2, 'beta')].append(s_pgv_y) + dict_im[('PGV', 0, 1, 'median')].append(m_pgv_x) # noqa: RUF031, RUF100 + dict_im[('PGV', 0, 1, 'beta')].append(s_pgv_x) # noqa: RUF031, RUF100 + dict_im[('PGV', 0, 2, 'median')].append(m_pgv_y) # noqa: RUF031, RUF100 + dict_im[('PGV', 0, 2, 'beta')].append(s_pgv_y) # noqa: RUF031, RUF100 # pgd - dict_im[('PGD', 0, 1, 'median')].append(m_pgd_x) - dict_im[('PGD', 0, 1, 'beta')].append(s_pgd_x) - dict_im[('PGD', 0, 2, 'median')].append(m_pgd_y) - dict_im[('PGD', 0, 2, 'beta')].append(s_pgd_y) + dict_im[('PGD', 0, 1, 'median')].append(m_pgd_x) # noqa: RUF031, RUF100 + dict_im[('PGD', 0, 1, 'beta')].append(s_pgd_x) # noqa: RUF031, RUF100 + dict_im[('PGD', 0, 2, 'median')].append(m_pgd_y) # noqa: RUF031, RUF100 + dict_im[('PGD', 0, 2, 'beta')].append(s_pgd_y) # noqa: RUF031, RUF100 for jj, Ti in enumerate(periods): # noqa: N806 cur_sa = f'SA({Ti}s)' - dict_im[(cur_sa, 0, 1, 'median')].append(m_psa_x[jj]) - dict_im[(cur_sa, 0, 1, 'beta')].append(s_psa_x[jj]) - dict_im[(cur_sa, 0, 2, 'median')].append(m_psa_y[jj]) - dict_im[(cur_sa, 0, 2, 'beta')].append(s_psa_y[jj]) + dict_im[(cur_sa, 0, 1, 'median')].append(m_psa_x[jj]) # noqa: RUF031, RUF100 + dict_im[(cur_sa, 0, 1, 'beta')].append(s_psa_x[jj]) # noqa: RUF031, RUF100 + dict_im[(cur_sa, 0, 2, 'median')].append(m_psa_y[jj]) # noqa: RUF031, RUF100 + dict_im[(cur_sa, 0, 2, 'beta')].append(s_psa_y[jj]) # noqa: RUF031, RUF100 # aggregate for cur_key, cur_value in dict_im.items(): diff --git a/modules/Workflow/createResponseCSV.py b/modules/Workflow/createResponseCSV.py new file mode 100644 index 000000000..e553398c3 --- /dev/null +++ b/modules/Workflow/createResponseCSV.py @@ -0,0 +1,89 @@ +# noqa: D100 + +# +# Code to write response.csv file given input and dakotaTab.out files +# + +# Written fmk, important code copied from whale/main.py +# date: 08/24 + +import argparse +import json +import os + +import numpy as np +import pandas as pd + +def main(input_file, dakota_tab_file): # noqa: D103 + + directory_inputs = os.path.dirname(input_file) # noqa: PTH120 + os.chdir(directory_inputs) + + try: + # Attempt to open the file + with open(input_file) as file: # noqa: PTH123 + data = json.load(file) + + except FileNotFoundError: + # Handle the error if the file is not found + print(f"Error createResponseCSV.py: The file '{input_file}' was not found.") # noqa: T201 + return + except OSError: + # Handle other I/O errors + print(f"Error createResponseCSV.py: Error reading the file '{input_file}'.") # noqa: T201 + return + + app_data = data.get('Applications', None) + if app_data is not None: + dl_data = app_data.get('DL', None) + + if dl_data is not None: + dl_app_data = dl_data.get('ApplicationData', None) + + if dl_app_data is not None: + is_coupled = dl_app_data.get('coupled_EDP', None) + + try: + # sy, abs - added try-statement because dakota-reliability does not write DakotaTab.out + dakota_out = pd.read_csv(dakota_tab_file, sep=r'\s+', header=0, index_col=0) + + if is_coupled: + if 'eventID' in dakota_out.columns: + events = dakota_out['eventID'].values # noqa: PD011 + events = [int(e.split('x')[-1]) for e in events] + sorter = np.argsort(events) + dakota_out = dakota_out.iloc[sorter, :] + dakota_out.index = np.arange(dakota_out.shape[0]) + + dakota_out.to_csv('response.csv') + + except FileNotFoundError: + # Handle the error if the file is not found + print(f"Error createResponseCSV.py: The file '{dakota_tab_file}' not found.") # noqa: T201 + return + + except OSError: + # Handle other I/O errors + print(f"Error createResponseCSV.py: Error reading '{dakota_tab_file}'.") # noqa: T201 + return + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + + # Add arguments with default values + parser.add_argument( + '--inputFile', type=str, default='AIM.json', help='Path to the input file)' + ) + parser.add_argument( + '--dakotaTab', + type=str, + default='dakotaTab.out', + help='Path to the dakotaTab file)', + ) + + # Parse the arguments + args = parser.parse_args() + + # Use the arguments + main(args.inputFile, args.dakotaTab) diff --git a/modules/Workflow/whale/main.py b/modules/Workflow/whale/main.py index 5b616b959..759f8af73 100644 --- a/modules/Workflow/whale/main.py +++ b/modules/Workflow/whale/main.py @@ -310,7 +310,7 @@ def create_command(command_list, enforced_python=None): for command_arg in command_list[1:]: command += f'"{command_arg}" ' - return command + return command # noqa: DOC201, RUF100 def run_command(command): @@ -357,7 +357,7 @@ def run_command(command): py_script.main(arg_list) - return '', '' + return '', '' # noqa: DOC201, RUF100 else: # noqa: RET505 # fmk with Shell=True not working on older windows machines, new approach needed for quoted command .. turn into a list @@ -668,7 +668,7 @@ def get_command_list(self, app_path, force_posix=False): # noqa: FBT002, C901 # pp.pprint(arg_list) - return arg_list + return arg_list # noqa: DOC201, RUF100 class Workflow: @@ -1316,7 +1316,7 @@ def create_asset_files(self): log_div() - return assetFilesList + return assetFilesList # noqa: DOC201, RUF100 def augment_asset_files(self): # noqa: C901 """Short description @@ -1504,7 +1504,7 @@ def augment_asset_files(self): # noqa: C901 ) log_div() - return assetFilesList + return assetFilesList # noqa: DOC201, RUF100 def perform_system_performance_assessment(self, asset_type): """For an asset type run the system level performance assessment application @@ -1525,7 +1525,7 @@ def perform_system_performance_assessment(self, asset_type): prepend_timestamp=False, ) log_div() - return False + return False # noqa: DOC201, RUF100 if performance_app.rel_path == None: # noqa: E711 log_msg( @@ -1909,7 +1909,7 @@ def init_simdir(self, asst_id=None, AIM_file_path='AIM.json'): # noqa: C901, N8 prepend_timestamp=False, ) log_div() - return dst + return dst # noqa: DOC201, RUF100 def cleanup_simdir(self, asst_id): """Short description @@ -2734,7 +2734,7 @@ def estimate_losses( # noqa: C901 ], ) if ('PID', '0') in df_res.columns: - del df_res[('PID', '0')] + del df_res[('PID', '0')] # noqa: RUF031, RUF100 # store the EDP statistics in the output DF for col in np.transpose(col_info): diff --git a/modules/common/simcenter_common.py b/modules/common/simcenter_common.py index d1aad42e4..c54977fbe 100644 --- a/modules/common/simcenter_common.py +++ b/modules/common/simcenter_common.py @@ -283,7 +283,7 @@ def get_scale_factors(input_units, output_units): # noqa: C901 scale_factors.update({input_name: f_scale}) - return scale_factors + return scale_factors # noqa: DOC201, RUF100 def get_unit_bases(input_units): @@ -306,4 +306,4 @@ def get_unit_bases(input_units): input_unit_bases = cur_unit_bases break - return input_unit_bases + return input_unit_bases # noqa: DOC201, RUF100 diff --git a/modules/createEVENT/CFDEvent/CFDEvent.py b/modules/createEVENT/CFDEvent/CFDEvent.py index 40062bcf0..884f232eb 100644 --- a/modules/createEVENT/CFDEvent/CFDEvent.py +++ b/modules/createEVENT/CFDEvent/CFDEvent.py @@ -13,7 +13,7 @@ def directionToDof(direction): # noqa: N802 """Converts direction to degree of freedom""" # noqa: D400, D401 directioMap = {'X': 1, 'Y': 2, 'Z': 3} # noqa: N806 - return directioMap[direction] + return directioMap[direction] # noqa: DOC201, RUF100 def addFloorForceToEvent(patternsArray, force, direction, floor): # noqa: ARG001, N802, N803 diff --git a/modules/createEVENT/EmptyDomainCFD/EmptyDomainCFD.py b/modules/createEVENT/EmptyDomainCFD/EmptyDomainCFD.py index ed0c853ea..5d309a10f 100644 --- a/modules/createEVENT/EmptyDomainCFD/EmptyDomainCFD.py +++ b/modules/createEVENT/EmptyDomainCFD/EmptyDomainCFD.py @@ -13,7 +13,7 @@ def directionToDof(direction): # noqa: N802 """Converts direction to degree of freedom""" # noqa: D400, D401 directioMap = {'X': 1, 'Y': 2, 'Z': 3} # noqa: N806 - return directioMap[direction] + return directioMap[direction] # noqa: DOC201, RUF100 def addFloorForceToEvent(patternsArray, force, direction, floor): # noqa: ARG001, N802, N803 diff --git a/modules/createEVENT/EmptyDomainCFD/post_process_output.py b/modules/createEVENT/EmptyDomainCFD/post_process_output.py index 4021a5915..3327b8a1f 100644 --- a/modules/createEVENT/EmptyDomainCFD/post_process_output.py +++ b/modules/createEVENT/EmptyDomainCFD/post_process_output.py @@ -88,7 +88,7 @@ def readPressureProbes(fileName): # noqa: N802, N803 time = np.asarray(time, dtype=np.float32) p = np.asarray(p, dtype=np.float32) - return probes, time, p + return probes, time, p # noqa: DOC201, RUF100 def read_pressure_data(file_names): @@ -291,7 +291,7 @@ def read_openFoam_scalar_field(file_name): # noqa: N802 sField = np.asarray(sField, dtype=np.float32) # noqa: N806 - return sField # noqa: RET504 + return sField # noqa: DOC201, RET504, RUF100 def read_openFoam_vector_field(file_name): # noqa: N802 @@ -312,7 +312,7 @@ def read_openFoam_vector_field(file_name): # noqa: N802 vField = np.asarray(vField, dtype=np.float32) # noqa: N806 - return vField # noqa: RET504 + return vField # noqa: DOC201, RET504, RUF100 def read_openFoam_tensor_field(file_name): # noqa: N802 @@ -340,7 +340,7 @@ def read_openFoam_tensor_field(file_name): # noqa: N802 vField = np.asarray(vField, dtype=np.float32) # noqa: N806 - return vField # noqa: RET504 + return vField # noqa: DOC201, RET504, RUF100 def read_openFoam_symmetric_tensor_field(file_name): # noqa: N802 @@ -367,7 +367,7 @@ def read_openFoam_symmetric_tensor_field(file_name): # noqa: N802 vField = np.asarray(vField, dtype=np.float32) # noqa: N806 - return vField # noqa: RET504 + return vField # noqa: DOC201, RET504, RUF100 def read_velocity_data(path): @@ -462,7 +462,7 @@ def read_velocity_probes(fileName): # noqa: N803 time = np.asarray(time, dtype=np.float32) U = np.asarray(U, dtype=np.float32) # noqa: N806 - return probes, time, U + return probes, time, U # noqa: DOC201, RUF100 def calculate_length_scale(u, uav, dt, min_corr=0.0): @@ -481,7 +481,7 @@ def calculate_length_scale(u, uav, dt, min_corr=0.0): L = uav * np.trapz(corr, dx=dt) # noqa: NPY201, N806 - return L # noqa: RET504 + return L # noqa: DOC201, RET504, RUF100 def psd(x, dt, nseg): # noqa: F811 diff --git a/modules/createEVENT/GeoClawOpenFOAM/AddBuildingForces.py b/modules/createEVENT/GeoClawOpenFOAM/AddBuildingForces.py index 9b69d2e41..95ee701f9 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/AddBuildingForces.py +++ b/modules/createEVENT/GeoClawOpenFOAM/AddBuildingForces.py @@ -9,7 +9,7 @@ def validateCaseDirectoryStructure(caseDir): # noqa: N802, N803 It also checks that system directory contains the controlDict """ # noqa: D205, D400, D401, D404 if not os.path.isdir(caseDir): # noqa: PTH112 - return False + return False # noqa: DOC201, RUF100 caseDirList = os.listdir(caseDir) # noqa: N806 necessaryDirs = ['0', 'constant', 'system'] # noqa: N806 @@ -27,7 +27,7 @@ def findFunctionsDictionary(controlDictLines): # noqa: N802, N803 """This method will find functions dictionary in the controlDict""" # noqa: D400, D401, D404 for line in controlDictLines: if line.startswith('functions'): - return (True, controlDictLines.index(line) + 2) + return (True, controlDictLines.index(line) + 2) # noqa: DOC201, RUF100 return [False, len(controlDictLines)] diff --git a/modules/createEVENT/GeoClawOpenFOAM/GeoClaw.py b/modules/createEVENT/GeoClawOpenFOAM/GeoClaw.py index e661faa8b..890c5549f 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/GeoClaw.py +++ b/modules/createEVENT/GeoClawOpenFOAM/GeoClaw.py @@ -80,4 +80,4 @@ def creategeom(self, data, path): # Points of interest bottompts = self.getbathy(maxvalues, minvalues, data) # noqa: F841 - return 0 + return 0 # noqa: DOC201, RUF100 diff --git a/modules/createEVENT/GeoClawOpenFOAM/GeoClawBathy.py b/modules/createEVENT/GeoClawOpenFOAM/GeoClawBathy.py index 023cc89c3..b4c7961f4 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/GeoClawBathy.py +++ b/modules/createEVENT/GeoClawOpenFOAM/GeoClawBathy.py @@ -61,4 +61,4 @@ def creategeom(self, data, path): # noqa: ARG002 # Create a utilities object hydroutil = hydroUtils() # noqa: F841 - return 0 + return 0 # noqa: DOC201, RUF100 diff --git a/modules/createEVENT/GeoClawOpenFOAM/GetOpenFOAMEvent.py b/modules/createEVENT/GeoClawOpenFOAM/GetOpenFOAMEvent.py index 744b4b743..8a80e4cfc 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/GetOpenFOAMEvent.py +++ b/modules/createEVENT/GeoClawOpenFOAM/GetOpenFOAMEvent.py @@ -16,7 +16,7 @@ def validateCaseDirectoryStructure(caseDir): # noqa: N802, N803 It also checks that system directory contains the controlDict """ # noqa: D205, D400, D401, D404 if not os.path.isdir(caseDir): # noqa: PTH112 - return False + return False # noqa: DOC201, RUF100 caseDirList = os.listdir(caseDir) # noqa: N806 necessaryDirs = ['0', 'constant', 'system', 'postProcessing'] # noqa: N806 @@ -36,7 +36,7 @@ def parseForceComponents(forceArray): # noqa: N802, N803 x = float(components[0]) y = float(components[1]) z = float(components[2]) - return [x, y, z] + return [x, y, z] # noqa: DOC201, RUF100 def ReadOpenFOAMForces(buildingForcesPath, floorsCount, startTime): # noqa: N802, N803 @@ -77,14 +77,14 @@ def ReadOpenFOAMForces(buildingForcesPath, floorsCount, startTime): # noqa: N80 forces[i].Y.append(fpry + fvy + fpoy) forces[i].Z.append(fprz + fvz + fpoz) - return [deltaT, forces] + return [deltaT, forces] # noqa: DOC201, RUF100 def directionToDof(direction): # noqa: N802 """Converts direction to degree of freedom""" # noqa: D400, D401 directioMap = {'X': 1, 'Y': 2, 'Z': 3} # noqa: N806 - return directioMap[direction] + return directioMap[direction] # noqa: DOC201, RUF100 def addFloorForceToEvent( # noqa: N802 diff --git a/modules/createEVENT/GeoClawOpenFOAM/flume.py b/modules/createEVENT/GeoClawOpenFOAM/flume.py index 2fcd048f1..bfba2ea13 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/flume.py +++ b/modules/createEVENT/GeoClawOpenFOAM/flume.py @@ -110,7 +110,7 @@ def generateflume(self, breadth, path): ) # Write bottom STL file # Return extreme values - return extremeval + return extremeval # noqa: DOC201, RUF100 ############################################################# def flumedata(self, IpPTFile): # noqa: N803 @@ -178,7 +178,7 @@ def flumedata(self, IpPTFile): # noqa: N803 self.npt = np.delete(self.npt, noindexes, axis=0) # Return extreme values - return extremeval + return extremeval # noqa: DOC201, RUF100 #################################################################### def right(self): @@ -431,4 +431,4 @@ def extremedata(self, extreme, breadth): ) tempfileID.close # noqa: B018 - return 0 + return 0 # noqa: DOC201, RUF100 diff --git a/modules/createEVENT/GeoClawOpenFOAM/hydroUtils.py b/modules/createEVENT/GeoClawOpenFOAM/hydroUtils.py index 4ff877888..bf32311f5 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/hydroUtils.py +++ b/modules/createEVENT/GeoClawOpenFOAM/hydroUtils.py @@ -90,7 +90,7 @@ def extract(self, obj, path, ind, arr): # noqa: C901 else: arr.append(None) - return arr + return arr # noqa: DOC201, RUF100 ############################################################# def extract_element_from_json(self, obj, path): @@ -106,7 +106,7 @@ def extract_element_from_json(self, obj, path): """ # noqa: D205, D401 if isinstance(obj, dict): # noqa: RET503 - return self.extract(obj, path, 0, []) + return self.extract(obj, path, 0, []) # noqa: DOC201, RUF100 elif isinstance(obj, list): # noqa: RET505 outer_arr = [] for item in obj: @@ -129,7 +129,7 @@ def general_header(self): | | O | \\*---------------------------------------------------------------------------*/ \n\n""" # noqa: W291 - return header # noqa: RET504 + return header # noqa: DOC201, RET504, RUF100 #################################################################### def of7header(self, OFclass, location, filename): # noqa: N803 @@ -156,7 +156,7 @@ class {OFclass}; }} // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //\n\n""" # noqa: W291 - return header # noqa: RET504 + return header # noqa: DOC201, RET504, RUF100 ############################################################# def hydrolog(self, projname, fipath): @@ -210,4 +210,4 @@ def getlist(self, data): data = data.replace(',', ' ') results = [float(n) for n in data.split()] - return results # noqa: RET504 + return results # noqa: DOC201, RET504, RUF100 diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7Alpboundary.py b/modules/createEVENT/GeoClawOpenFOAM/of7Alpboundary.py index 7d01c94ad..4ac1b0b2f 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7Alpboundary.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7Alpboundary.py @@ -89,7 +89,7 @@ def Alptext(self, data, patches): # noqa: N802 Alptext = Alptext + '}\n\n' # noqa: N806 # Return the text for velocity BC - return Alptext # noqa: RET504 + return Alptext # noqa: DOC201, RET504, RUF100 ############################################################# def Alpheader(self): # noqa: N802 @@ -114,7 +114,7 @@ def Alpheader(self): # noqa: N802 header = header + 'internalField\tuniform\t0;\n\n' # Return the header for U file - return header # noqa: RET504 + return header # noqa: DOC201, RET504, RUF100 ############################################################# def Alppatchtext(self, Alptype, patchname): # noqa: ARG002, N802, N803 @@ -140,4 +140,4 @@ def Alppatchtext(self, Alptype, patchname): # noqa: ARG002, N802, N803 Alptext = Alptext + 'type\tzeroGradient;\n\t}\n' # noqa: N806 # Return the header for U file - return Alptext + return Alptext # noqa: DOC201, RUF100 diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7Building.py b/modules/createEVENT/GeoClawOpenFOAM/of7Building.py index 2c586616b..ecb806c7e 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7Building.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7Building.py @@ -100,7 +100,7 @@ def buildcheck(self, data, path): # noqa: C901, PLR0911 data, ['Events', 'BuildingSTLFile'] ) if stlfile == [None]: - return -1 + return -1 # noqa: DOC201, RUF100 else: # noqa: RET505 stlfile = ', '.join( hydroutil.extract_element_from_json( @@ -218,7 +218,7 @@ def createbuilds(self, data, path): elif buildeftype == 'Parameters': self.buildpara(data, path) - return 0 + return 0 # noqa: DOC201, RUF100 ############################################################# def buildmanual(self, data, path): diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7Decomp.py b/modules/createEVENT/GeoClawOpenFOAM/of7Decomp.py index e89b53037..40349fa86 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7Decomp.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7Decomp.py @@ -75,7 +75,7 @@ def decomptext(self, data): decomptext = decomptext + 'method\tscotch;\n\n' - return decomptext # noqa: RET504 + return decomptext # noqa: DOC201, RET504, RUF100 ############################################################# def decompheader(self): @@ -97,7 +97,7 @@ def decompheader(self): // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //\n\n""" # noqa: W291 # Return the header for U file - return header # noqa: RET504 + return header # noqa: DOC201, RET504, RUF100 ############################################################# def scripts(self, data, path): # noqa: ARG002 diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7Geometry.py b/modules/createEVENT/GeoClawOpenFOAM/of7Geometry.py index acbe366c6..1c4b78679 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7Geometry.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7Geometry.py @@ -82,7 +82,7 @@ def geomcheck(self, data, path): # noqa: C901, PLR0911 data, ['Events', 'NumBathymetryFiles'] ) if numbathy == [None]: - return -1 + return -1 # noqa: DOC201, RUF100 else: # noqa: RET505 numbathy = ', '.join( hydroutil.extract_element_from_json( @@ -250,7 +250,7 @@ def createOFSTL(self, data, path): # noqa: C901, N802 # Create geometry (i.e. STL files) and extreme file ecode = finalgeom.creategeom(data, path) if ecode < 0: - return -1 + return -1 # noqa: DOC201, RUF100 # Bathymetry only elif int(simtype) == 2: # noqa: PLR2004 diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7Initial.py b/modules/createEVENT/GeoClawOpenFOAM/of7Initial.py index 82b12159c..16825f65b 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7Initial.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7Initial.py @@ -173,7 +173,7 @@ def alphatext(self, data, fipath): alphatext = alphatext + '\n);' - return alphatext # noqa: RET504 + return alphatext # noqa: DOC201, RET504, RUF100 ############################################################# def alphaheader(self): @@ -195,7 +195,7 @@ def alphaheader(self): // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //\n\n""" # noqa: W291 # Return the header for U file - return header # noqa: RET504 + return header # noqa: DOC201, RET504, RUF100 ############################################################# def alphacheck(self, data, fipath): @@ -220,7 +220,7 @@ def alphacheck(self, data, fipath): fname = 'SWAlpha.txt' swalphafile = os.path.join(fipath, fname) # noqa: PTH118 if not os.path.exists(swalphafile): # noqa: PTH110 - return -1 + return -1 # noqa: DOC201, RUF100 # For all types other than the shallow water else: diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7Materials.py b/modules/createEVENT/GeoClawOpenFOAM/of7Materials.py index b81c87fd9..97c77bec6 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7Materials.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7Materials.py @@ -120,7 +120,7 @@ def mattext(self, data): mattext = mattext + 'sigma\t[1 0 -2 0 0 0 0]\t' + sigma + ';\n' - return mattext # noqa: RET504 + return mattext # noqa: DOC201, RET504, RUF100 ############################################################# def matheader(self): @@ -142,7 +142,7 @@ def matheader(self): // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //\n\n""" # noqa: W291 # Return the header for U file - return header # noqa: RET504 + return header # noqa: DOC201, RET504, RUF100 ############################################################# def matcheck(self, data): @@ -162,7 +162,7 @@ def matcheck(self, data): data, ['Events', 'WaterViscosity'] ) if nuwater == [None]: - return -1 + return -1 # noqa: DOC201, RUF100 # Exponent nuwaterexp = hydroutil.extract_element_from_json( data, ['Events', 'WaterViscosityExp'] diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7Meshing.py b/modules/createEVENT/GeoClawOpenFOAM/of7Meshing.py index 9e6a6298d..dc300767a 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7Meshing.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7Meshing.py @@ -72,7 +72,7 @@ def meshcheck(self, data, fipath): # If hydro mesher - nothing to check if int(mesher[0]) == 0: - return 0 + return 0 # noqa: DOC201, RUF100 # Other mesh software elif int(mesher[0]) == 1: # noqa: RET505 @@ -126,7 +126,7 @@ def meshheader(self, fileobjec): ) # Return the header for meshing file - return header # noqa: RET504 + return header # noqa: DOC201, RET504, RUF100 ############################################################# def bmeshtext(self, data): @@ -284,7 +284,7 @@ def bmeshtext(self, data): # Add merge patch pairs bmeshtext = bmeshtext + 'mergePatchPairs\n(\n);\n' - return bmeshtext # noqa: RET504 + return bmeshtext # noqa: DOC201, RET504, RUF100 ############################################################# def sfetext(self): @@ -320,7 +320,7 @@ def sfetext(self): elif int(data_geoext[6]) == 3: # noqa: PLR2004 sfetext = sfetext + 'OtherBuilding.stl\n' + stlinfo + '\n\n' - return sfetext + return sfetext # noqa: DOC201, RUF100 ############################################################# def shmtext(self, data): @@ -505,7 +505,7 @@ def shmtext(self, data): shmtext = shmtext + 'debug\t0;\n' shmtext = shmtext + 'mergeTolerance\t1E-6;\n' - return shmtext # noqa: RET504 + return shmtext # noqa: DOC201, RET504, RUF100 ############################################################# def scripts(self, data, path): # noqa: C901 diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7Others.py b/modules/createEVENT/GeoClawOpenFOAM/of7Others.py index 37b8f7f31..a2b0b1bdf 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7Others.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7Others.py @@ -78,7 +78,7 @@ def othersheader(self, fileclas, fileloc, fileobjec): ) # Return the header for U file - return header # noqa: RET504 + return header # noqa: DOC201, RET504, RUF100 ############################################################# def gfiletext(self, data): @@ -140,4 +140,4 @@ def gfiletext(self, data): + ');\n' ) - return gfiletext # noqa: RET504 + return gfiletext # noqa: DOC201, RET504, RUF100 diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7Prboundary.py b/modules/createEVENT/GeoClawOpenFOAM/of7Prboundary.py index b34770dff..151d95546 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7Prboundary.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7Prboundary.py @@ -93,7 +93,7 @@ def Prtext(self, data, patches): # noqa: N802 prtext = prtext + '}\n\n' # Return the text for velocity BC - return prtext # noqa: RET504 + return prtext # noqa: DOC201, RET504, RUF100 ############################################################# def Prheader(self): # noqa: N802 @@ -118,7 +118,7 @@ def Prheader(self): # noqa: N802 header = header + 'internalField\tuniform\t0;\n\n' # Return the header for U file - return header # noqa: RET504 + return header # noqa: DOC201, RET504, RUF100 ############################################################# def Prpatchtext(self, data, Prtype, patchname): # noqa: C901, N802, N803 @@ -208,4 +208,4 @@ def Prpatchtext(self, data, Prtype, patchname): # noqa: C901, N802, N803 Prtext = Prtext + 'type\tempty;\n\t}\n' # noqa: N806 # Return the header for U file - return Prtext + return Prtext # noqa: DOC201, RUF100 diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7Process.py b/modules/createEVENT/GeoClawOpenFOAM/of7Process.py index b1979173d..3aa0a8178 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7Process.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7Process.py @@ -132,7 +132,7 @@ def pprocesstext(self, data, path): sampletext = sampletext + ');\n\n' sampletext = sampletext + 'fields\t' + fieldtext + ';\n' - return sampletext # noqa: RET504 + return sampletext # noqa: DOC201, RET504, RUF100 ############################################################# def pprocesscdict(self, data, path): # noqa: C901 @@ -275,7 +275,7 @@ def pprocesscdict(self, data, path): # noqa: C901 cdicttext = cdicttext + '\t\tfields\t' + fieldtext + ';\n' cdicttext = cdicttext + '\t}\n}' - return cdicttext # noqa: RET504 + return cdicttext # noqa: DOC201, RET504, RUF100 ############################################################# def scripts(self, data, path): # noqa: ARG002 @@ -293,7 +293,7 @@ def scripts(self, data, path): # noqa: ARG002 data, ['Events', 'Postprocessing'] ) if pprocess == [None]: - return 0 + return 0 # noqa: DOC201, RUF100 else: # noqa: RET505 pprocess = ', '.join( hydroutil.extract_element_from_json( @@ -350,7 +350,7 @@ def pprocesscheck(self, data, path): ) if pprocess == 'No': - return 0 + return 0 # noqa: DOC201, RUF100 else: # noqa: RET505 pprocessV = ', '.join( # noqa: N806 hydroutil.extract_element_from_json(data, ['Events', 'PPVelocity']) diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7PtDboundary.py b/modules/createEVENT/GeoClawOpenFOAM/of7PtDboundary.py index c432d0bf4..f337d5032 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7PtDboundary.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7PtDboundary.py @@ -115,7 +115,7 @@ def PtDcheck(self, data, patches): # noqa: N802 if (int(Utype) == 103) or (int(Utype) == 104): # noqa: PLR2004 numMovWall += 1 # noqa: N806 if numMovWall > 0: - return 1 + return 1 # noqa: DOC201, RUF100 if numMovWall == 0: return 0 @@ -169,7 +169,7 @@ def PtDtext(self, data, fipath, patches): # noqa: N802 ptdtext = ptdtext + '}\n\n' # Return the text for pointDisplacement - return ptdtext # noqa: RET504 + return ptdtext # noqa: DOC201, RET504, RUF100 ############################################################# def PtDheader(self): # noqa: N802 @@ -194,7 +194,7 @@ def PtDheader(self): # noqa: N802 header = header + 'internalField\tuniform (0 0 0);\n\n' # Return the header for U file - return header # noqa: RET504 + return header # noqa: DOC201, RET504, RUF100 ############################################################# def PtDpatchtext(self, data, Utype, patchname, fipath): # noqa: ARG002, N802, N803 @@ -243,7 +243,7 @@ def PtDpatchtext(self, data, Utype, patchname, fipath): # noqa: ARG002, N802, N PtDtext = PtDtext + 'value\tuniform (0 0 0);\n' # noqa: N806 PtDtext = PtDtext + '\t}\n' # noqa: N806 - return PtDtext + return PtDtext # noqa: DOC201, RUF100 ############################################################# def getNormal(self, patchname): # noqa: N802 @@ -267,4 +267,4 @@ def getNormal(self, patchname): # noqa: N802 elif (patchname == 'Building') or (patchname == 'OtherBuilding'): # noqa: PLR1714 normal = '1 0 0' - return normal + return normal # noqa: DOC201, RUF100 diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7Solve.py b/modules/createEVENT/GeoClawOpenFOAM/of7Solve.py index de0fe5fa5..bbdfa077d 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7Solve.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7Solve.py @@ -73,7 +73,7 @@ def solverheader(self, fileobjec): ) # Return the header for U file - return header # noqa: RET504 + return header # noqa: DOC201, RET504, RUF100 ############################################################# def fvSchemetext(self, data): # noqa: ARG002, N802 @@ -163,7 +163,7 @@ def fvSchemetext(self, data): # noqa: ARG002, N802 fvSchemetext = fvSchemetext + 'alpha.water;\n' # noqa: N806 fvSchemetext = fvSchemetext + '}\n' # noqa: N806 - return fvSchemetext # noqa: RET504 + return fvSchemetext # noqa: DOC201, RET504, RUF100 ############################################################# def fvSolntext(self, data): # noqa: N802 @@ -280,7 +280,7 @@ def fvSolntext(self, data): # noqa: N802 fvSolntext = fvSolntext + 'fields\n\t{\n\t}\n\t' # noqa: N806 fvSolntext = fvSolntext + 'equations\n\t{\n\t\t".*"\t1;\n\t}\n}' # noqa: N806 - return fvSolntext # noqa: RET504 + return fvSolntext # noqa: DOC201, RET504, RUF100 ############################################################# def cdicttext(self, data): @@ -349,7 +349,7 @@ def cdicttext(self, data): cdicttext = cdicttext + 'maxAlphaCo \t 1.0;\n\n' cdicttext = cdicttext + 'maxDeltaT \t 1;\n\n' - return cdicttext # noqa: RET504 + return cdicttext # noqa: DOC201, RET504, RUF100 ############################################################# def cdictcheck(self, data): @@ -366,7 +366,7 @@ def cdictcheck(self, data): # Start time startT = hydroutil.extract_element_from_json(data, ['Events', 'StartTime']) # noqa: N806 if startT == [None]: - return -1 + return -1 # noqa: DOC201, RUF100 # End time endT = hydroutil.extract_element_from_json(data, ['Events', 'EndTime']) # noqa: N806 @@ -489,4 +489,4 @@ def cdictFtext(self, data): # noqa: N802 cdicttext = cdicttext + 'direction\t(1 0 0);\n\t\t\t' cdicttext = cdicttext + 'cumulative\tno;\n\t\t}\n\t}\n}' - return cdicttext # noqa: RET504 + return cdicttext # noqa: DOC201, RET504, RUF100 diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7Turbulence.py b/modules/createEVENT/GeoClawOpenFOAM/of7Turbulence.py index 154e2b209..407ceddf8 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7Turbulence.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7Turbulence.py @@ -84,7 +84,7 @@ def turbtext(self, data): turbtext = turbtext + '\tturbulence\ton;\n' turbtext = turbtext + '\tprintCoeffs\ton;\n}\n' - return turbtext + return turbtext # noqa: DOC201, RUF100 ############################################################# def turbheader(self): @@ -106,4 +106,4 @@ def turbheader(self): // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //\n\n""" # noqa: W291 # Return the header for U file - return header # noqa: RET504 + return header # noqa: DOC201, RET504, RUF100 diff --git a/modules/createEVENT/GeoClawOpenFOAM/of7Uboundary.py b/modules/createEVENT/GeoClawOpenFOAM/of7Uboundary.py index 2686f3c9b..283b2f082 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/of7Uboundary.py +++ b/modules/createEVENT/GeoClawOpenFOAM/of7Uboundary.py @@ -105,7 +105,7 @@ def Utext(self, data, fipath, patches): # noqa: N802 utext = utext + '}\n\n' # Return the text for velocity BC - return utext # noqa: RET504 + return utext # noqa: DOC201, RET504, RUF100 ############################################################# def Uheader(self): # noqa: N802 @@ -130,7 +130,7 @@ def Uheader(self): # noqa: N802 header = header + 'internalField\tuniform (0 0 0);\n\n' # Return the header for U file - return header # noqa: RET504 + return header # noqa: DOC201, RET504, RUF100 ############################################################# def Upatchtext(self, data, Utype, patchname, fipath, numMovWall): # noqa: C901, N802, N803 @@ -345,7 +345,7 @@ def Upatchtext(self, data, Utype, patchname, fipath, numMovWall): # noqa: C901, Utext = Utext + 'type\tempty;\n\t}\n' # noqa: N806 # Return the header for U file - return Utext + return Utext # noqa: DOC201, RUF100 ############################################################# def Uchecks(self, data, fipath, patches): # noqa: C901, N802 @@ -384,7 +384,7 @@ def Uchecks(self, data, fipath, patches): # noqa: C901, N802 # Checking for multiple moving walls numMovWall += 1 # noqa: N806 if numMovWall > 1: - return -1 + return -1 # noqa: DOC201, RUF100 # Check for existing moving wall files dispfilename = hydroutil.extract_element_from_json( diff --git a/modules/createEVENT/GeoClawOpenFOAM/openfoam7.py b/modules/createEVENT/GeoClawOpenFOAM/openfoam7.py index ef3d4e423..d82396707 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/openfoam7.py +++ b/modules/createEVENT/GeoClawOpenFOAM/openfoam7.py @@ -169,7 +169,7 @@ def createfolder(self, data, path, args): scriptfile.close() # Return completion flag - return 0 + return 0 # noqa: DOC201, RUF100 ############################################################# def creategeometry(self, data, path): @@ -192,7 +192,7 @@ def creategeometry(self, data, path): # Create the geometry related files Geometry = of7Geometry() # noqa: N806 if int(mesher[0]) == 1: - return 0 + return 0 # noqa: DOC201, RUF100 elif int(mesher[0]) == 0 or int(mesher[0]) == 2: # noqa: RET505, PLR2004 geomcode = Geometry.geomcheck(data, path) if geomcode == -1: @@ -245,7 +245,7 @@ def createmesh(self, data, path): Meshing = of7Meshing() # noqa: N806 meshcode = Meshing.meshcheck(data, path) if meshcode == -1: - return -1 + return -1 # noqa: DOC201, RUF100 elif int(mesher[0]) == 0: # noqa: RET505 # blockMesh bmeshtext = Meshing.bmeshtext(data) @@ -295,7 +295,7 @@ def materials(self, data, path): Materials = of7Materials() # noqa: N806 matcode = Materials.matcheck(data) if matcode == -1: - return -1 + return -1 # noqa: DOC201, RUF100 else: # noqa: RET505 mattext = Materials.mattext(data) fname = 'transportProperties' @@ -320,7 +320,7 @@ def initial(self, data, path): Inicond = of7Initial() # noqa: N806 initcode = Inicond.alphacheck(data, path) if initcode == -1: - return -1 + return -1 # noqa: DOC201, RUF100 else: # noqa: RET505 alphatext = Inicond.alphatext(data, path) fname = 'setFieldsDict' @@ -355,7 +355,7 @@ def boundary(self, data, path): # Check for boundary conditions here ecode = Uboundary.Uchecks(data, path, patches) if ecode == -1: - return -1 + return -1 # noqa: DOC201, RUF100 else: # noqa: RET505 # Write the U-file if no errors # Path to the file @@ -421,7 +421,7 @@ def turbulence(self, data, path): turbfile.write(turbtext) turbfile.close() - return 0 + return 0 # noqa: DOC201, RUF100 ############################################################# def parallelize(self, data, path): @@ -445,7 +445,7 @@ def parallelize(self, data, path): # Scripts Decomp.scripts(data, path) - return 0 + return 0 # noqa: DOC201, RUF100 ############################################################# def solve(self, data, path): @@ -478,7 +478,7 @@ def solve(self, data, path): # controlDict ecode = Solve.cdictcheck(data) if ecode == -1: - return -1 + return -1 # noqa: DOC201, RUF100 else: # noqa: RET505 cdicttext = Solve.cdicttext(data) fname = 'controlDict' @@ -516,7 +516,7 @@ def others(self, data, path): gfile.write(gfiletext) gfile.close() - return 0 + return 0 # noqa: DOC201, RUF100 ############################################################# def dakota(self, args): @@ -533,7 +533,7 @@ def dakota(self, args): # Dakota Scripts dakota.dakotascripts(args) - return 0 + return 0 # noqa: DOC201, RUF100 ############################################################# def postprocessing(self, data, path): @@ -550,7 +550,7 @@ def postprocessing(self, data, path): # controlDict ecode = pprocess.pprocesscheck(data, path) if ecode == -1: - return -1 + return -1 # noqa: DOC201, RUF100 elif ecode == 0: # noqa: RET505 return 0 else: @@ -589,4 +589,4 @@ def cleaning(self, args, path): # Dakota Scripts cleaner.cleaning(args, path) - return 0 + return 0 # noqa: DOC201, RUF100 diff --git a/modules/createEVENT/GeoClawOpenFOAM/osuFlume.py b/modules/createEVENT/GeoClawOpenFOAM/osuFlume.py index 7c3d584d8..be0cef04d 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/osuFlume.py +++ b/modules/createEVENT/GeoClawOpenFOAM/osuFlume.py @@ -104,4 +104,4 @@ def creategeom(self, data, path): # noqa: ARG002 # Write extreme values and building data to temporary file for later usage flumeobj.extremedata(extreme, breadth) - return 0 + return 0 # noqa: DOC201, RUF100 diff --git a/modules/createEVENT/GeoClawOpenFOAM/userFlume.py b/modules/createEVENT/GeoClawOpenFOAM/userFlume.py index 60ef1373b..66638127c 100644 --- a/modules/createEVENT/GeoClawOpenFOAM/userFlume.py +++ b/modules/createEVENT/GeoClawOpenFOAM/userFlume.py @@ -102,4 +102,4 @@ def creategeom(self, data, path): # Write extreme values and building data to temporary file for later usage flumeobj.extremedata(extreme, breadth) - return 0 + return 0 # noqa: DOC201, RUF100 diff --git a/modules/createEVENT/IsolatedBuildingCFD/IsolatedBuildingCFD.py b/modules/createEVENT/IsolatedBuildingCFD/IsolatedBuildingCFD.py index 7962f92cd..e561d9dbc 100644 --- a/modules/createEVENT/IsolatedBuildingCFD/IsolatedBuildingCFD.py +++ b/modules/createEVENT/IsolatedBuildingCFD/IsolatedBuildingCFD.py @@ -13,7 +13,7 @@ def directionToDof(direction): # noqa: N802 """Converts direction to degree of freedom""" # noqa: D400, D401 directioMap = {'X': 1, 'Y': 2, 'Z': 3} # noqa: N806 - return directioMap[direction] + return directioMap[direction] # noqa: DOC201, RUF100 def addFloorForceToEvent(patternsArray, force, direction, floor): # noqa: ARG001, N802, N803 diff --git a/modules/createEVENT/Istanbul/IstanbulStations.py b/modules/createEVENT/Istanbul/IstanbulStations.py index 3fcd70882..8145e6ee1 100644 --- a/modules/createEVENT/Istanbul/IstanbulStations.py +++ b/modules/createEVENT/Istanbul/IstanbulStations.py @@ -190,7 +190,7 @@ def haversine(lat1, lon1, lat2, lon2): r = 6371 # Radius of the Earth in kilometers distance = r * c - return distance # noqa: RET504 + return distance # noqa: DOC201, RET504, RUF100 if __name__ == '__main__': diff --git a/modules/createEVENT/M9/M9API.py b/modules/createEVENT/M9/M9API.py index 52702a163..ec6a49ea0 100644 --- a/modules/createEVENT/M9/M9API.py +++ b/modules/createEVENT/M9/M9API.py @@ -332,4 +332,4 @@ def haversine(lat1, lon1, lat2, lon2): r = 6371 # Radius of the Earth in kilometers distance = r * c - return distance # noqa: RET504 + return distance # noqa: DOC201, RET504, RUF100 diff --git a/modules/createEVENT/M9/M9Stations.py b/modules/createEVENT/M9/M9Stations.py index 1c5ccf699..f52352c90 100644 --- a/modules/createEVENT/M9/M9Stations.py +++ b/modules/createEVENT/M9/M9Stations.py @@ -229,4 +229,4 @@ def haversine(lat1, lon1, lat2, lon2): r = 6371 # Radius of the Earth in kilometers distance = r * c - return distance # noqa: RET504 + return distance # noqa: DOC201, RET504, RUF100 diff --git a/modules/createEVENT/MPM/MPM.py b/modules/createEVENT/MPM/MPM.py index ea3bbf431..5a2d55a45 100644 --- a/modules/createEVENT/MPM/MPM.py +++ b/modules/createEVENT/MPM/MPM.py @@ -13,7 +13,7 @@ def directionToDof(direction): # noqa: N802 """Converts direction to degree of freedom""" # noqa: D400, D401 directioMap = {'X': 1, 'Y': 2, 'Z': 3} # noqa: N806 - return directioMap[direction] + return directioMap[direction] # noqa: DOC201, RUF100 def addFloorForceToEvent( # noqa: N802 diff --git a/modules/createEVENT/MPM/post_process_output.py b/modules/createEVENT/MPM/post_process_output.py index 4021a5915..3327b8a1f 100644 --- a/modules/createEVENT/MPM/post_process_output.py +++ b/modules/createEVENT/MPM/post_process_output.py @@ -88,7 +88,7 @@ def readPressureProbes(fileName): # noqa: N802, N803 time = np.asarray(time, dtype=np.float32) p = np.asarray(p, dtype=np.float32) - return probes, time, p + return probes, time, p # noqa: DOC201, RUF100 def read_pressure_data(file_names): @@ -291,7 +291,7 @@ def read_openFoam_scalar_field(file_name): # noqa: N802 sField = np.asarray(sField, dtype=np.float32) # noqa: N806 - return sField # noqa: RET504 + return sField # noqa: DOC201, RET504, RUF100 def read_openFoam_vector_field(file_name): # noqa: N802 @@ -312,7 +312,7 @@ def read_openFoam_vector_field(file_name): # noqa: N802 vField = np.asarray(vField, dtype=np.float32) # noqa: N806 - return vField # noqa: RET504 + return vField # noqa: DOC201, RET504, RUF100 def read_openFoam_tensor_field(file_name): # noqa: N802 @@ -340,7 +340,7 @@ def read_openFoam_tensor_field(file_name): # noqa: N802 vField = np.asarray(vField, dtype=np.float32) # noqa: N806 - return vField # noqa: RET504 + return vField # noqa: DOC201, RET504, RUF100 def read_openFoam_symmetric_tensor_field(file_name): # noqa: N802 @@ -367,7 +367,7 @@ def read_openFoam_symmetric_tensor_field(file_name): # noqa: N802 vField = np.asarray(vField, dtype=np.float32) # noqa: N806 - return vField # noqa: RET504 + return vField # noqa: DOC201, RET504, RUF100 def read_velocity_data(path): @@ -462,7 +462,7 @@ def read_velocity_probes(fileName): # noqa: N803 time = np.asarray(time, dtype=np.float32) U = np.asarray(U, dtype=np.float32) # noqa: N806 - return probes, time, U + return probes, time, U # noqa: DOC201, RUF100 def calculate_length_scale(u, uav, dt, min_corr=0.0): @@ -481,7 +481,7 @@ def calculate_length_scale(u, uav, dt, min_corr=0.0): L = uav * np.trapz(corr, dx=dt) # noqa: NPY201, N806 - return L # noqa: RET504 + return L # noqa: DOC201, RET504, RUF100 def psd(x, dt, nseg): # noqa: F811 diff --git a/modules/createEVENT/SurroundedBuildingCFD/SurroundedBuildingCFD.py b/modules/createEVENT/SurroundedBuildingCFD/SurroundedBuildingCFD.py index b331ebbec..e7065e2ff 100644 --- a/modules/createEVENT/SurroundedBuildingCFD/SurroundedBuildingCFD.py +++ b/modules/createEVENT/SurroundedBuildingCFD/SurroundedBuildingCFD.py @@ -13,7 +13,7 @@ def directionToDof(direction): # noqa: N802 """Converts direction to degree of freedom""" # noqa: D400, D401 directioMap = {'X': 1, 'Y': 2, 'Z': 3} # noqa: N806 - return directioMap[direction] + return directioMap[direction] # noqa: DOC201, RUF100 def addFloorForceToEvent(patternsArray, force, direction, floor): # noqa: ARG001, N802, N803 diff --git a/modules/createEVENT/SurroundedBuildingCFD/post_process_output.py b/modules/createEVENT/SurroundedBuildingCFD/post_process_output.py index 4021a5915..3327b8a1f 100644 --- a/modules/createEVENT/SurroundedBuildingCFD/post_process_output.py +++ b/modules/createEVENT/SurroundedBuildingCFD/post_process_output.py @@ -88,7 +88,7 @@ def readPressureProbes(fileName): # noqa: N802, N803 time = np.asarray(time, dtype=np.float32) p = np.asarray(p, dtype=np.float32) - return probes, time, p + return probes, time, p # noqa: DOC201, RUF100 def read_pressure_data(file_names): @@ -291,7 +291,7 @@ def read_openFoam_scalar_field(file_name): # noqa: N802 sField = np.asarray(sField, dtype=np.float32) # noqa: N806 - return sField # noqa: RET504 + return sField # noqa: DOC201, RET504, RUF100 def read_openFoam_vector_field(file_name): # noqa: N802 @@ -312,7 +312,7 @@ def read_openFoam_vector_field(file_name): # noqa: N802 vField = np.asarray(vField, dtype=np.float32) # noqa: N806 - return vField # noqa: RET504 + return vField # noqa: DOC201, RET504, RUF100 def read_openFoam_tensor_field(file_name): # noqa: N802 @@ -340,7 +340,7 @@ def read_openFoam_tensor_field(file_name): # noqa: N802 vField = np.asarray(vField, dtype=np.float32) # noqa: N806 - return vField # noqa: RET504 + return vField # noqa: DOC201, RET504, RUF100 def read_openFoam_symmetric_tensor_field(file_name): # noqa: N802 @@ -367,7 +367,7 @@ def read_openFoam_symmetric_tensor_field(file_name): # noqa: N802 vField = np.asarray(vField, dtype=np.float32) # noqa: N806 - return vField # noqa: RET504 + return vField # noqa: DOC201, RET504, RUF100 def read_velocity_data(path): @@ -462,7 +462,7 @@ def read_velocity_probes(fileName): # noqa: N803 time = np.asarray(time, dtype=np.float32) U = np.asarray(U, dtype=np.float32) # noqa: N806 - return probes, time, U + return probes, time, U # noqa: DOC201, RUF100 def calculate_length_scale(u, uav, dt, min_corr=0.0): @@ -481,7 +481,7 @@ def calculate_length_scale(u, uav, dt, min_corr=0.0): L = uav * np.trapz(corr, dx=dt) # noqa: NPY201, N806 - return L # noqa: RET504 + return L # noqa: DOC201, RET504, RUF100 def psd(x, dt, nseg): # noqa: F811 diff --git a/modules/createEVENT/coupledDigitalTwin/CoupledDigitalTwin.py b/modules/createEVENT/coupledDigitalTwin/CoupledDigitalTwin.py index 28342461c..1caab63cd 100644 --- a/modules/createEVENT/coupledDigitalTwin/CoupledDigitalTwin.py +++ b/modules/createEVENT/coupledDigitalTwin/CoupledDigitalTwin.py @@ -13,7 +13,7 @@ def directionToDof(direction): # noqa: N802 """Converts direction to degree of freedom""" # noqa: D400, D401 directioMap = {'X': 1, 'Y': 2, 'Z': 3} # noqa: N806 - return directioMap[direction] + return directioMap[direction] # noqa: DOC201, RUF100 def addFloorForceToEvent(patternsArray, force, direction, floor): # noqa: ARG001, N802, N803 diff --git a/modules/createEVENT/groundMotionIM/IntensityMeasureComputer.py b/modules/createEVENT/groundMotionIM/IntensityMeasureComputer.py index 96f3359b8..eb60a5fcb 100644 --- a/modules/createEVENT/groundMotionIM/IntensityMeasureComputer.py +++ b/modules/createEVENT/groundMotionIM/IntensityMeasureComputer.py @@ -167,7 +167,7 @@ def convert_accel_units(self, acceleration, from_, to_='cm/sec/sec'): # noqa: C acceleration = np.asarray(acceleration) if from_ == 'g': if to_ == 'g': - return acceleration + return acceleration # noqa: DOC201, RUF100 if to_ in self.km_sec_square: return acceleration * self.g / 1000.0 if to_ in self.m_sec_square: diff --git a/modules/createEVENT/siteResponse/RegionalSiteResponse.py b/modules/createEVENT/siteResponse/RegionalSiteResponse.py index dd4f7179b..edce432d0 100644 --- a/modules/createEVENT/siteResponse/RegionalSiteResponse.py +++ b/modules/createEVENT/siteResponse/RegionalSiteResponse.py @@ -131,7 +131,7 @@ def get_scale_factors(input_units, output_units): # noqa: C901 scale_factors.update({input_name: f_scale}) - return scale_factors + return scale_factors # noqa: DOC201, RUF100 def postProcess(evtName, input_units, f_scale_units): # noqa: N802, N803, D103 diff --git a/modules/createEVENT/stochasticWave/StochasticWave.py b/modules/createEVENT/stochasticWave/StochasticWave.py index 045946a49..98971436f 100644 --- a/modules/createEVENT/stochasticWave/StochasticWave.py +++ b/modules/createEVENT/stochasticWave/StochasticWave.py @@ -100,7 +100,7 @@ def directionToDof(direction): # noqa: N802 """Converts direction to degree of freedom""" # noqa: D400, D401 directioMap = {'X': 1, 'Y': 2, 'Z': 3} # noqa: N806 - return directioMap[direction] + return directioMap[direction] # noqa: DOC201, RUF100 def addFloorForceToEvent(patternsList, timeSeriesList, force, direction, floor): # noqa: N802, N803 diff --git a/modules/createSAM/AutoSDA/Preprocessing/CleanBeamSectionDatabase.ipynb b/modules/createSAM/AutoSDA/Preprocessing/CleanBeamSectionDatabase.ipynb index 5e1cc9ae2..abbe355f2 100644 --- a/modules/createSAM/AutoSDA/Preprocessing/CleanBeamSectionDatabase.ipynb +++ b/modules/createSAM/AutoSDA/Preprocessing/CleanBeamSectionDatabase.ipynb @@ -1,74 +1,75 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Clean Beam Section Database" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "ename": "FileNotFoundError", - "evalue": "[Errno 2] No such file or directory: 'BeamDatabase.csv'", - "output_type": "error", - "traceback": [ - "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[1;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", - "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mpandas\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mpd\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[1;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'BeamDatabase.csv'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'r'\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mfile\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[0mbeam_section_database\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mpd\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread_csv\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfile\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mheader\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n", - "\u001b[1;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'BeamDatabase.csv'" - ] - } - ], - "source": [ - "import pandas as pd\n", - "\n", - "with open('BeamDatabase1.csv', 'r') as file:\n", - " beam_section_database = pd.read_csv(file, header=0)\n", - "\n", - "# Beam section weight shall be less than 300 lb/ft\n", - "# Beam flange thickness shall be less than 1.75 inch.\n", - "target_index = []\n", - "for indx in beam_section_database['index']:\n", - " if (beam_section_database.loc[indx, 'weight'] >= 300):\n", - " target_index.append(indx)\n", - " elif (beam_section_database.loc[indx, 'tf'] >= 1.75):\n", - " target_index.append(indx)\n", - "clean_beam_section = beam_section_database.drop(index=target_index)\n", - "clean_beam_section.to_csv('BeamDatabase2.csv', sep=',', index=False)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.5" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Clean Beam Section Database" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "ename": "FileNotFoundError", + "evalue": "[Errno 2] No such file or directory: 'BeamDatabase.csv'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mpandas\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mpd\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[1;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'BeamDatabase.csv'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'r'\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mfile\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[0mbeam_section_database\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mpd\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread_csv\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfile\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mheader\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'BeamDatabase.csv'" + ] + } + ], + "source": [ + "import pandas as pd\n", + "\n", + "with open('BeamDatabase1.csv') as file: # noqa: PTH123\n", + " beam_section_database = pd.read_csv(file, header=0)\n", + "\n", + "# Beam section weight shall be less than 300 lb/ft\n", + "# Beam flange thickness shall be less than 1.75 inch.\n", + "target_index = []\n", + "for indx in beam_section_database['index']:\n", + " if (\n", + " beam_section_database.loc[indx, 'weight'] >= 300 # noqa: PLR2004\n", + " or beam_section_database.loc[indx, 'tf'] >= 1.75 # noqa: PLR2004\n", + " ):\n", + " target_index.append(indx) # noqa: PERF401\n", + "clean_beam_section = beam_section_database.drop(index=target_index)\n", + "clean_beam_section.to_csv('BeamDatabase2.csv', sep=',', index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/modules/createSAM/AutoSDA/beam_component.py b/modules/createSAM/AutoSDA/beam_component.py index ae245e5d5..ed7b949c7 100644 --- a/modules/createSAM/AutoSDA/beam_component.py +++ b/modules/createSAM/AutoSDA/beam_component.py @@ -181,7 +181,7 @@ def check_flag(self): for key in self.is_feasible.keys(): # noqa: SIM118 if self.is_feasible[key] == False: # noqa: E712 self.flag = False - return self.flag + return self.flag # noqa: DOC201, RUF100 def compute_demand_capacity_ratio(self): """This method is used to compute demand to capacity ratios. diff --git a/modules/createSAM/AutoSDA/column_component.py b/modules/createSAM/AutoSDA/column_component.py index e9d56768f..c17b6b06e 100644 --- a/modules/createSAM/AutoSDA/column_component.py +++ b/modules/createSAM/AutoSDA/column_component.py @@ -264,7 +264,7 @@ def check_flag(self): for key in self.is_feasible.keys(): # noqa: SIM118 if self.is_feasible[key] == False: # noqa: E712 self.flag = False - return self.flag + return self.flag # noqa: DOC201, RUF100 def compute_demand_capacity_ratio(self): """This method is used to calculate the demand to capacity ratios for column components diff --git a/modules/createSAM/AutoSDA/connection_part.py b/modules/createSAM/AutoSDA/connection_part.py index 0483cc614..0b2bd3fa6 100644 --- a/modules/createSAM/AutoSDA/connection_part.py +++ b/modules/createSAM/AutoSDA/connection_part.py @@ -740,4 +740,4 @@ def check_flag(self): for key in self.is_feasible.keys(): # noqa: SIM118 if self.is_feasible[key] == False: # noqa: E712 self.flag = False - return self.flag + return self.flag # noqa: DOC201, RUF100 diff --git a/modules/createSAM/AutoSDA/help_functions.py b/modules/createSAM/AutoSDA/help_functions.py index 1c5f8f8c1..379209b75 100644 --- a/modules/createSAM/AutoSDA/help_functions.py +++ b/modules/createSAM/AutoSDA/help_functions.py @@ -50,7 +50,7 @@ def determine_Fa_coefficient(site_class, Ss): # noqa: C901, N802, N803 Fa = None # noqa: N806 print('Site class is entered with an invalid value') # noqa: T201 - return Fa + return Fa # noqa: DOC201, RUF100 def determine_Fv_coefficient(site_class, S1): # noqa: C901, N802, N803 @@ -94,7 +94,7 @@ def determine_Fv_coefficient(site_class, S1): # noqa: C901, N802, N803 Fv = None # noqa: N806 print('Site class is entered with an invalid value') # noqa: T201 - return Fv + return Fv # noqa: DOC201, RUF100 def calculate_DBE_acceleration(Ss, S1, Fa, Fv): # noqa: N802, N803 @@ -111,7 +111,7 @@ def calculate_DBE_acceleration(Ss, S1, Fa, Fv): # noqa: N802, N803 SM1 = Fv * S1 # noqa: N806 SDS = 2 / 3 * SMS # noqa: N806 SD1 = 2 / 3 * SM1 # noqa: N806 - return SMS, SM1, SDS, SD1 + return SMS, SM1, SDS, SD1 # noqa: DOC201, RUF100 def determine_Cu_coefficient(SD1): # noqa: N802, N803 @@ -133,7 +133,7 @@ def determine_Cu_coefficient(SD1): # noqa: N802, N803 else: Cu = 1.4 # noqa: N806 - return Cu + return Cu # noqa: DOC201, RUF100 def determine_floor_height( @@ -161,7 +161,7 @@ def determine_floor_height( level - 2 ) - return floor_height + return floor_height # noqa: DOC201, RUF100 def calculate_Cs_coefficient(SDS, SD1, S1, T, TL, R, Ie): # noqa: N802, N803 @@ -212,7 +212,7 @@ def calculate_Cs_coefficient(SDS, SD1, S1, T, TL, R, Ie): # noqa: N802, N803 else: pass - return Cs + return Cs # noqa: DOC201, RUF100 def determine_k_coeficient(period): @@ -227,7 +227,7 @@ def determine_k_coeficient(period): else: k = 1 + 0.5 * (period - 0.5) - return k + return k # noqa: DOC201, RUF100 def calculate_seismic_force(base_shear, floor_weight, floor_height, k): @@ -252,7 +252,7 @@ def calculate_seismic_force(base_shear, floor_weight, floor_height, k): for story in range(len(floor_weight) - 1, -1, -1): story_shear[story] = np.sum(seismic_force[story:]) - return seismic_force, story_shear + return seismic_force, story_shear # noqa: DOC201, RUF100 def find_section_candidate(target_depth, section_database): @@ -267,7 +267,7 @@ def find_section_candidate(target_depth, section_database): if match: candidate_index.append(indx) candidates = section_database.loc[candidate_index, 'section size'] - return candidates # noqa: RET504 + return candidates # noqa: DOC201, RET504, RUF100 def search_member_size(target_name, target_quantity, candidate, section_database): @@ -299,7 +299,7 @@ def search_member_size(target_name, target_quantity, candidate, section_database section_size = section_database.loc[ candidate_index[min_index[0][0]], 'section size' ] - return section_size + return section_size # noqa: DOC201, RUF100 def search_section_property(target_size, section_database): @@ -316,7 +316,7 @@ def search_section_property(target_size, section_database): for indx in np.array(section_database['index']): if target_size == section_database.loc[indx, 'section size']: section_info = section_database.loc[indx, :] - return section_info.to_dict() + return section_info.to_dict() # noqa: DOC201, RUF100 except: # noqa: E722 sys.stderr.write( 'Error: wrong size nominated!\nNo such size exists in section database!' @@ -336,7 +336,7 @@ def decrease_member_size(candidate, current_size): # This means the smallest candidate still cannot make design drift close to drift limit, # which further means the smallest section candidate is too large. sys.stderr.write('The lower bound for depth initialization is too large!\n') - return candidate[candidate_pool_index + 1] + return candidate[candidate_pool_index + 1] # noqa: DOC201, RUF100 def extract_depth(size): @@ -346,7 +346,7 @@ def extract_depth(size): """ # noqa: D205, D400, D401, D404 # Use Python regular expression to extract the char between 'W' and 'X', which then become depth output = re.findall(r'.*W(.*)X.*', size) - return int(output[0]) + return int(output[0]) # noqa: DOC201, RUF100 def extract_weight(size): @@ -357,7 +357,7 @@ def extract_weight(size): # Use Python regular expression to extract the char after 'W' to the end of the string, # which then becomes weight output = re.findall(r'.X(.*)', size) - return int(output[0]) + return int(output[0]) # noqa: DOC201, RUF100 def constructability_helper( # noqa: C901 @@ -541,7 +541,7 @@ def constructability_helper( # noqa: C901 variation_story.pop() # Update the ending index for next "identical story block" ending_index = variation_story[-1] - return section_size + return section_size # noqa: DOC201, RUF100 # # Loop over all stories from top to bottom to consider the constructability # starting_story = total_story - 1 @@ -596,4 +596,4 @@ def increase_member_size(candidate, current_size): if candidate_pool_index - 1 < 0: # Make sure the index does not exceed the bound # This means the largest candidate still fails to satisfy the requirement sys.stderr.write('The upper bound for depth initialization is too small!\n') - return candidate[candidate_pool_index - 1] + return candidate[candidate_pool_index - 1] # noqa: DOC201, RUF100 diff --git a/modules/performDL/pelicun3/DL_visuals.py b/modules/performDL/pelicun3/DL_visuals.py index 93cc245cb..43cc80d39 100644 --- a/modules/performDL/pelicun3/DL_visuals.py +++ b/modules/performDL/pelicun3/DL_visuals.py @@ -116,26 +116,26 @@ def plot_fragility(comp_db_path, output_path, create_zip='0'): # noqa: C901, D1 5: cl.scales['5']['seq']['Reds'], } - if comp_data.loc[('Incomplete', '')] != 1: + if comp_data.loc[('Incomplete', '')] != 1: # noqa: RUF031, RUF100 p_min, p_max = 0.01, 0.9 d_min = np.inf d_max = -np.inf LS_count = 0 # noqa: N806 for LS in limit_states: # noqa: N806 - if comp_data.loc[(LS, 'Family')] == 'normal': + if comp_data.loc[(LS, 'Family')] == 'normal': # noqa: RUF031, RUF100 d_min_i, d_max_i = norm.ppf( [p_min, p_max], - loc=comp_data.loc[(LS, 'Theta_0')], - scale=comp_data.loc[(LS, 'Theta_1')] - * comp_data.loc[(LS, 'Theta_0')], + loc=comp_data.loc[(LS, 'Theta_0')], # noqa: RUF031, RUF100 + scale=comp_data.loc[(LS, 'Theta_1')] # noqa: RUF031, RUF100 + * comp_data.loc[(LS, 'Theta_0')], # noqa: RUF031, RUF100 ) - elif comp_data.loc[(LS, 'Family')] == 'lognormal': + elif comp_data.loc[(LS, 'Family')] == 'lognormal': # noqa: RUF031, RUF100 d_min_i, d_max_i = np.exp( norm.ppf( [p_min, p_max], - loc=np.log(comp_data.loc[(LS, 'Theta_0')]), - scale=comp_data.loc[(LS, 'Theta_1')], + loc=np.log(comp_data.loc[(LS, 'Theta_0')]), # noqa: RUF031, RUF100 + scale=comp_data.loc[(LS, 'Theta_1')], # noqa: RUF031, RUF100 ) ) else: @@ -149,18 +149,18 @@ def plot_fragility(comp_db_path, output_path, create_zip='0'): # noqa: C901, D1 demand_vals = np.linspace(d_min, d_max, num=100) for i_ls, LS in enumerate(limit_states): # noqa: N806 - if comp_data.loc[(LS, 'Family')] == 'normal': + if comp_data.loc[(LS, 'Family')] == 'normal': # noqa: RUF031, RUF100 cdf_vals = norm.cdf( demand_vals, - loc=comp_data.loc[(LS, 'Theta_0')], - scale=comp_data.loc[(LS, 'Theta_1')] - * comp_data.loc[(LS, 'Theta_0')], + loc=comp_data.loc[(LS, 'Theta_0')], # noqa: RUF031, RUF100 + scale=comp_data.loc[(LS, 'Theta_1')] # noqa: RUF031, RUF100 + * comp_data.loc[(LS, 'Theta_0')], # noqa: RUF031, RUF100 ) - elif comp_data.loc[(LS, 'Family')] == 'lognormal': + elif comp_data.loc[(LS, 'Family')] == 'lognormal': # noqa: RUF031, RUF100 cdf_vals = norm.cdf( np.log(demand_vals), - loc=np.log(comp_data.loc[(LS, 'Theta_0')]), - scale=comp_data.loc[(LS, 'Theta_1')], + loc=np.log(comp_data.loc[(LS, 'Theta_0')]), # noqa: RUF031, RUF100 + scale=comp_data.loc[(LS, 'Theta_1')], # noqa: RUF031, RUF100 ) else: continue @@ -385,11 +385,11 @@ def plot_fragility(comp_db_path, output_path, create_zip='0'): # noqa: C901, D1 gridcolor='rgb(192,192,192)', ) - demand_unit = comp_data.loc[('Demand', 'Unit')] + demand_unit = comp_data.loc[('Demand', 'Unit')] # noqa: RUF031, RUF100 if demand_unit == 'unitless': demand_unit = '-' fig.update_xaxes( - title_text=f"{comp_data.loc[('Demand', 'Type')]} [{demand_unit}]", + title_text=f"{comp_data.loc[('Demand', 'Type')]} [{demand_unit}]", # noqa: RUF031, RUF100 **shared_ax_props, ) @@ -465,7 +465,7 @@ def plot_repair(comp_db_path, output_path, create_zip='0'): # noqa: C901, D103, # perform plotting for each repair consequence type independently for c_type in repair_df.loc[comp_id].index: # load the component-specific part of the database - comp_data = repair_df.loc[(comp_id, c_type)] + comp_data = repair_df.loc[(comp_id, c_type)] # noqa: RUF031, RUF100 # and the component-specific metadata - if it exists if repair_meta != None: # noqa: E711 @@ -620,7 +620,7 @@ def plot_repair(comp_db_path, output_path, create_zip='0'): # noqa: C901, D103, ), } - if comp_data.loc[('Incomplete', '')] != 1: + if comp_data.loc[('Incomplete', '')] != 1: # noqa: RUF031, RUF100 # set the parameters for displaying uncertainty p_min, p_max = 0.16, 0.84 # +- 1 std # noqa: F841 @@ -929,7 +929,7 @@ def plot_repair(comp_db_path, output_path, create_zip='0'): # noqa: C901, D103, elif quantity_unit.split()[0] == '1': quantity_unit = quantity_unit.split()[1] - dv_unit = comp_data.loc[('DV', 'Unit')] + dv_unit = comp_data.loc[('DV', 'Unit')] # noqa: RUF031, RUF100 if dv_unit == 'unitless': dv_unit = '-' diff --git a/modules/performHUA/pyincore_data/censusutil.py b/modules/performHUA/pyincore_data/censusutil.py index 8b8bc9182..d17253710 100644 --- a/modules/performHUA/pyincore_data/censusutil.py +++ b/modules/performHUA/pyincore_data/censusutil.py @@ -16,7 +16,7 @@ import geopandas as gpd import pandas as pd import requests -from pyincore_data import globals +from pyincore_data import globals # noqa: A004, RUF100 logger = globals.LOGGER @@ -107,7 +107,7 @@ def request_census_api(data_url): api_json = request_json.json() api_df = pd.DataFrame(columns=api_json[0], data=api_json[1:]) - return api_df # noqa: RET504 + return api_df # noqa: DOC201, RET504, RUF100 @staticmethod def get_blockdata_for_demographics( # noqa: C901 @@ -191,7 +191,7 @@ def get_blockdata_for_demographics( # noqa: C901 else: print('Only 2000, 2010, and 2020 decennial census supported') # noqa: T201 - return None + return None # noqa: DOC201, RUF100 # Make directory to save output if not os.path.exists(output_dir): # noqa: PTH110 @@ -860,7 +860,7 @@ def get_blockgroupdata_for_income( # noqa: C901 print('Done creating household income shapefile') # noqa: T201 - return cen_blockgroup[save_columns] + return cen_blockgroup[save_columns] # noqa: DOC201, RUF100 @staticmethod def convert_dislocation_gpd_to_shapefile(in_gpd, programname, savefile): diff --git a/modules/performREC/pyrecodes/run_pyrecodes.py b/modules/performREC/pyrecodes/run_pyrecodes.py index 7998e0aa6..c141ffb8d 100644 --- a/modules/performREC/pyrecodes/run_pyrecodes.py +++ b/modules/performREC/pyrecodes/run_pyrecodes.py @@ -235,7 +235,7 @@ def run_pyrecodes(rec_config, inputRWHALE, parallelType, mpiExec, numPROC): # n ujson.dump(results, f) ind_in_rank += 1 - count = count + 1 + count = count + 1 # noqa: PLR6104, RUF100 # wait for all to finish if doParallel: @@ -504,4 +504,3 @@ def select_realizations_to_run(damage_input, inputRWHALE): # noqa: N803, D103 mpiExec=wfArgs.mpiexec, numPROC=numPROC, ) - diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/CMakeLists.txt b/modules/performRegionalEventSimulation/regionalGroundMotion/CMakeLists.txt index e82a2052c..3d4f51a06 100644 --- a/modules/performRegionalEventSimulation/regionalGroundMotion/CMakeLists.txt +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/CMakeLists.txt @@ -13,4 +13,5 @@ simcenter_add_python_script(SCRIPT HazardOccurrence.py) simcenter_add_python_script(SCRIPT USGS_API.py) simcenter_add_python_script(SCRIPT ScenarioForecast.py) simcenter_add_python_script(SCRIPT liquefaction.py) +simcenter_add_python_script(SCRIPT landslide.py) simcenter_add_python_script(SCRIPT GMSimulators.py) diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/ComputeIntensityMeasure.py b/modules/performRegionalEventSimulation/regionalGroundMotion/ComputeIntensityMeasure.py index 183b4d7ce..f500a4b31 100644 --- a/modules/performRegionalEventSimulation/regionalGroundMotion/ComputeIntensityMeasure.py +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/ComputeIntensityMeasure.py @@ -725,12 +725,15 @@ def compute_im( # noqa: C901, D103 saveInJson = False # noqa: N806 filename = os.path.join(output_dir, filename) # noqa: PTH118 im_list = [] - if 'PGA' in im_info.keys(): # noqa: SIM118 + if 'PGA' in im_info.keys() or im_info.get('Type', None) == 'PGA': # noqa: SIM118 im_list.append('PGA') if 'SA' in im_info.keys(): # noqa: SIM118 for cur_period in im_info['SA']['Periods']: im_list.append(f'SA({cur_period!s})') # noqa: PERF401 - if 'PGV' in im_info.keys(): # noqa: SIM118 + if im_info.get('Type', None) == 'SA': + for cur_period in im_info['Periods']: + im_list.append(f'SA({cur_period!s})') # noqa: PERF401 + if 'PGV' in im_info.keys() or im_info.get('Type', None) == 'PGV': # noqa: SIM118 im_list.append('PGV') # Stations station_list = [ @@ -1110,27 +1113,27 @@ def export_im( # noqa: C901, D103, PLR0912 # Combine PGD from liquefaction, landslide and fault if ( 'liq_PGD_h' in df.columns - or 'ls_PGD_h' in df.columns + or 'lsd_PGD_h' in df.columns or 'fd_PGD_h' in df.columns ): PGD_h = np.zeros(df.shape[0]) # noqa: N806 if 'liq_PGD_h' in df.columns: PGD_h += df['liq_PGD_h'].to_numpy() # noqa: N806 - if 'ls_PGD_h' in df.columns: - PGD_h += df['ls_PGD_h'].to_numpy() # noqa: N806 + if 'lsd_PGD_h' in df.columns: + PGD_h += df['lsd_PGD_h'].to_numpy() # noqa: N806 if 'fd_PGD_h' in df.columns: PGD_h += df['fd_PGD_h'].to_numpy() # noqa: N806 df['PGD_h'] = PGD_h if ( 'liq_PGD_v' in df.columns - or 'ls_PGD_v' in df.columns + or 'lsd_PGD_v' in df.columns or 'fd_PGD_v' in df.columns ): PGD_v = np.zeros(df.shape[0]) # noqa: N806 if 'liq_PGD_v' in df.columns: PGD_v += df['liq_PGD_v'].to_numpy() # noqa: N806 - if 'ls_PGD_v' in df.columns: - PGD_v += df['ls_PGD_v'].to_numpy() # noqa: N806 + if 'lsd_PGD_v' in df.columns: + PGD_v += df['lsd_PGD_v'].to_numpy() # noqa: N806 if 'fd_PGD_v' in df.columns: PGD_v += df['fd_PGD_v'].to_numpy() # noqa: N806 df['PGD_v'] = PGD_v @@ -1173,27 +1176,27 @@ def export_im( # noqa: C901, D103, PLR0912 # Combine PGD from liquefaction, landslide and fault if ( 'liq_PGD_h' in df.columns - or 'ls_PGD_h' in df.columns + or 'lsd_PGD_h' in df.columns or 'fd_PGD_h' in df.columns ): PGD_h = np.zeros(df.shape[0]) # noqa: N806 if 'liq_PGD_h' in df.columns: PGD_h += df['liq_PGD_h'].to_numpy() # noqa: N806 - if 'ls_PGD_h' in df.columns: - PGD_h += df['ls_PGD_h'].to_numpy() # noqa: N806 + if 'lsd_PGD_h' in df.columns: + PGD_h += df['lsd_PGD_h'].to_numpy() # noqa: N806 if 'fd_PGD_h' in df.columns: PGD_h += df['fd_PGD_h'].to_numpy() # noqa: N806 df['PGD_h'] = PGD_h if ( 'liq_PGD_v' in df.columns - or 'ls_PGD_v' in df.columns + or 'lsd_PGD_v' in df.columns or 'fd_PGD_v' in df.columns ): PGD_v = np.zeros(df.shape[0]) # noqa: N806 if 'liq_PGD_v' in df.columns: PGD_v += df['liq_PGD_v'].to_numpy() # noqa: N806 - if 'ls_PGD_v' in df.columns: - PGD_v += df['ls_PGD_v'].to_numpy() # noqa: N806 + if 'lsd_PGD_v' in df.columns: + PGD_v += df['lsd_PGD_v'].to_numpy() # noqa: N806 if 'fd_PGD_v' in df.columns: PGD_v += df['fd_PGD_v'].to_numpy() # noqa: N806 df['PGD_v'] = PGD_v diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/CreateStation.py b/modules/performRegionalEventSimulation/regionalGroundMotion/CreateStation.py index a03932afc..c875cc8c5 100644 --- a/modules/performRegionalEventSimulation/regionalGroundMotion/CreateStation.py +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/CreateStation.py @@ -114,7 +114,7 @@ def create_stations( # noqa: C901, PLR0912, PLR0915 stn_df = pd.read_csv(input_file, header=0, index_col=0) except: # noqa: E722 run_tag = 0 - return run_tag # noqa: RET504 + return run_tag # noqa: DOC201, RET504, RUF100 # Max and Min IDs if len(filterIDs) > 0: stns_requested = [] @@ -543,6 +543,11 @@ def create_stations( # noqa: C901, PLR0912, PLR0915 'distCoast', 'distRiver', 'precipitation', + 'slope', + 'slopeThickness', + 'gammaSoil', + 'phiSoil', + 'cohesionSoil', ]: if stn.get(key, None) is not None: tmp.update({key: stn.get(key)}) @@ -604,7 +609,7 @@ def create_gridded_stations( gstn_df = pd.read_csv(input_file, header=0, index_col=0) except: # noqa: E722 run_tag = 1 - return run_tag # noqa: RET504 + return run_tag # noqa: DOC201, RET504, RUF100 if np.max(gstn_df.index.values) != 2: # noqa: PLR2004 run_tag = 1 return run_tag # noqa: RET504 @@ -657,7 +662,7 @@ def get_vs30_global(lat, lon): ) vs30 = [float(interpFunc(x, y)) for x, y in zip(lon, lat)] # return - return vs30 # noqa: RET504 + return vs30 # noqa: DOC201, RET504, RUF100 def get_vs30_thompson(lat, lon): @@ -689,21 +694,21 @@ def get_vs30_thompson(lat, lon): vs30 = [float(interpFunc(x, y)) for x, y in zip(lon, lat)] # return - return vs30 # noqa: RET504 + return vs30 # noqa: DOC201, RET504, RUF100 def get_z1(vs30): """Compute z1 based on the prediction equation by Chiou and Youngs (2013) (unit of vs30 is meter/second and z1 is meter)""" # noqa: D400 z1 = np.exp(-7.15 / 4.0 * np.log((vs30**4 + 571.0**4) / (1360.0**4 + 571.0**4))) # return - return z1 # noqa: RET504 + return z1 # noqa: DOC201, RET504, RUF100 def get_z25(z1): """Compute z25 based on the prediction equation by Campbell and Bozorgnia (2013)""" # noqa: D400 z25 = 0.748 + 2.218 * z1 # return - return z25 # noqa: RET504 + return z25 # noqa: DOC201, RET504, RUF100 def get_z25fromVs(vs): # noqa: N802 @@ -712,7 +717,7 @@ def get_z25fromVs(vs): # noqa: N802 """ # noqa: D205, D400 z25 = (7.089 - 1.144 * np.log(vs)) * 1000 # return - return z25 # noqa: RET504 + return z25 # noqa: DOC201, RET504, RUF100 def get_zTR_global(lat, lon): # noqa: N802 @@ -738,7 +743,7 @@ def get_zTR_global(lat, lon): # noqa: N802 ) zTR = [float(interpFunc(x, y)) for x, y in zip(lon, lat)] # noqa: N806 # return - return zTR # noqa: RET504 + return zTR # noqa: DOC201, RET504, RUF100 def export_site_prop(stn_file, output_dir, filename): @@ -806,7 +811,7 @@ def get_zTR_ncm(lat, lon): # noqa: N802 # get the top bedrock data zTR.append(abs(cur_res['response']['results'][0]['profiles'][0]['top'])) # return - return zTR + return zTR # noqa: DOC201, RUF100 def get_vsp_ncm(lat, lon, depth): @@ -845,7 +850,7 @@ def get_vsp_ncm(lat, lon, depth): if len(vsp) == 1: vsp = vsp[0] # return - return vsp + return vsp # noqa: DOC201, RUF100 def compute_vs30_from_vsp(depthp, vsp): @@ -863,7 +868,7 @@ def compute_vs30_from_vsp(depthp, vsp): # Computing the Vs30 vs30p = 30.0 / np.sum(delta_t) # return - return vs30p # noqa: RET504 + return vs30p # noqa: DOC201, RET504, RUF100 def get_vs30_ncm(lat, lon): @@ -890,7 +895,7 @@ def get_vs30_ncm(lat, lon): ) vs30.append(760.0) # return - return vs30 + return vs30 # noqa: DOC201, RUF100 def get_soil_model_ba(param=None): @@ -920,7 +925,7 @@ def get_soil_model_ba(param=None): else: res = None - return res + return res # noqa: DOC201, RUF100 def get_soil_model_ei(param=None): @@ -935,7 +940,7 @@ def get_soil_model_ei(param=None): else: res = None - return res + return res # noqa: DOC201, RUF100 def get_soil_model_user(df_stn, model_fun): # noqa: D103 diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/FetchOpenQuake.py b/modules/performRegionalEventSimulation/regionalGroundMotion/FetchOpenQuake.py index daf1d1dba..2a7cf2574 100644 --- a/modules/performRegionalEventSimulation/regionalGroundMotion/FetchOpenQuake.py +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/FetchOpenQuake.py @@ -630,7 +630,7 @@ def oq_run_classical_psha( # noqa: C901 export_realizations('realizations', dstore) except: # noqa: E722 print('FetchOpenQuake: Classical PSHA failed.') # noqa: T201 - return 1 + return 1 # noqa: DOC201, RUF100 elif vtag == 11: # noqa: PLR2004 try: print(f'FetchOpenQuake: running Version {oq_version}.') # noqa: T201 @@ -845,7 +845,7 @@ def oq_read_uhs_classical_psha(scen_info, event_info, dir_info): mag_maf.append([0.0, float(list_IMs[0].split('~')[0]), 0.0]) # return - return ln_psa_mr, mag_maf, im_list + return ln_psa_mr, mag_maf, im_list # noqa: DOC201, RUF100 class OpenQuakeHazardCalc: # noqa: D101 @@ -991,7 +991,7 @@ def run_calc(self): # noqa: C901 oq.ground_motion_fields is False and oq.hazard_curves_from_gmfs is False ): - return {} + return {} # noqa: DOC201, RUF100 elif 'rupture_model' not in oq.inputs: logging.warning( 'There is no rupture_model, the calculator will just ' @@ -1550,7 +1550,7 @@ def eval_calc(self): # noqa: C901, PLR0912, PLR0915 } # return - return res # noqa: RET504 + return res # noqa: DOC201, RET504, RUF100 def calculator_build_events_from_sources(self): # noqa: C901 """Prefilter the composite source model and store the source_info""" # noqa: D400 @@ -1666,7 +1666,7 @@ def __str__(self): # noqa: D105 def to_imt_unit_values(vals, imt): """Exponentiate the values unless the IMT is MMI""" # noqa: D400 if str(imt) == 'MMI': - return vals + return vals # noqa: DOC201, RUF100 return np.exp(vals) diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/HazardOccurrence.py b/modules/performRegionalEventSimulation/regionalGroundMotion/HazardOccurrence.py index 2ca2f8fec..15a748471 100644 --- a/modules/performRegionalEventSimulation/regionalGroundMotion/HazardOccurrence.py +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/HazardOccurrence.py @@ -654,7 +654,7 @@ def _input_check(self): print( # noqa: T201 'OccurrenceModel_ManzourDavidson2016._input_check: no return period is defined.' ) - return False + return False # noqa: DOC201, RUF100 # shape of exceedance probability if len(self.im_exceedance_probs.shape) != 3: # noqa: PLR2004 print( # noqa: T201 @@ -730,8 +730,8 @@ def _opt_initialization(self): itertools.product(range(self.num_sites), range(self.num_return_periods)) ) self.prob += pulp.lpSum( - self.return_periods[j] * self.e_plus[(i, j)] - + self.return_periods[j] * self.e_minus[(i, j)] + self.return_periods[j] * self.e_plus[(i, j)] # noqa: RUF031, RUF100 + + self.return_periods[j] * self.e_minus[(i, j)] # noqa: RUF031, RUF100 for (i, j) in comb_sites_rps ) @@ -757,7 +757,7 @@ def _opt_initialization(self): <= self.num_scenarios ) - return True + return True # noqa: DOC201, RUF100 def solve_opt(self): """target_function: compute the target function to be minimized @@ -853,7 +853,7 @@ def _input_check(self): print( # noqa: T201 'OccurrenceModel_Wangetal2023._input_check: no return period is defined.' ) - return False + return False # noqa: DOC201, RUF100 # shape of exceedance probability if len(self.im_exceedance_probs.shape) != 3: # noqa: PLR2004 print( # noqa: T201 @@ -916,7 +916,7 @@ def _opt_initialization(self): self.X_weighted = np.dot(self.W, self.X) self.y_weighted = np.dot(self.W, self.y) - return True + return True # noqa: DOC201, RUF100 def solve_opt(self): """LASSO regression""" # noqa: D400 diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/HazardSimulationEQ.py b/modules/performRegionalEventSimulation/regionalGroundMotion/HazardSimulationEQ.py index 7d86fccae..3d9eaed21 100644 --- a/modules/performRegionalEventSimulation/regionalGroundMotion/HazardSimulationEQ.py +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/HazardSimulationEQ.py @@ -470,6 +470,18 @@ def hazard_job(hazard_info): # noqa: C901, D103, PLR0915 ln_im_mr, mag_maf, im_list ) gf_im_list += settlement_info['Output'] + if 'Landslide' in ground_failure_info.keys(): # noqa: SIM118 + import landslide # noqa: PLC0415, RUF100 + + if 'Landslide' in ground_failure_info['Landslide'].keys(): # noqa: SIM118 + lsld_info = ground_failure_info['Landslide']['Landslide'] + lsld_model = getattr(landslide, lsld_info['Model'])( + lsld_info['Parameters'], stations + ) + ln_im_mr, mag_maf, im_list = lsld_model.run( + ln_im_mr, mag_maf, im_list + ) + gf_im_list += lsld_info['Output'] if event_info['SaveIM'] and ln_im_mr: print('HazardSimulation: saving simulated intensity measures.') # noqa: T201 @@ -539,6 +551,7 @@ def hazard_job(hazard_info): # noqa: C901, D103, PLR0915 if importlib.util.find_spec('jpype') is None: subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'JPype1']) # noqa: S603 import jpype + from jpype import imports from jpype.types import * # noqa: F403 memory_total = psutil.virtual_memory().total / (1024.0**3) diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/ScenarioForecast.py b/modules/performRegionalEventSimulation/regionalGroundMotion/ScenarioForecast.py index 5083e18fc..67fd6cf1e 100644 --- a/modules/performRegionalEventSimulation/regionalGroundMotion/ScenarioForecast.py +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/ScenarioForecast.py @@ -99,6 +99,9 @@ if importlib.util.find_spec('jpype') is None: subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'JPype1']) # noqa: S603 import jpype + + # from jpype import imports + import jpype.imports from jpype.types import * # noqa: F403 memory_total = psutil.virtual_memory().total / (1024.0**3) diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/database/CMakeLists.txt b/modules/performRegionalEventSimulation/regionalGroundMotion/database/CMakeLists.txt index f79a961e9..0276b2ded 100644 --- a/modules/performRegionalEventSimulation/regionalGroundMotion/database/CMakeLists.txt +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/database/CMakeLists.txt @@ -1,2 +1,2 @@ add_subdirectory(gmdb) - +add_subdirectory(groundfailure) diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/database/groundfailure/CMakeLists.txt b/modules/performRegionalEventSimulation/regionalGroundMotion/database/groundfailure/CMakeLists.txt new file mode 100644 index 000000000..d5da071f5 --- /dev/null +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/database/groundfailure/CMakeLists.txt @@ -0,0 +1,2 @@ +simcenter_add_file(NAME Wills_etal_2015_CA_Geologic_Properties.csv) + diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/database/groundfailure/Wills_etal_2015_CA_Geologic_Properties.csv b/modules/performRegionalEventSimulation/regionalGroundMotion/database/groundfailure/Wills_etal_2015_CA_Geologic_Properties.csv new file mode 100644 index 000000000..1e00416b8 --- /dev/null +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/database/groundfailure/Wills_etal_2015_CA_Geologic_Properties.csv @@ -0,0 +1,19 @@ +Unit Abbreviation,Friction Angle - Mean (degrees),Friction Angle - Median (degrees),Friction Angle - CoV (%),Friction Angle - Min (degrees),Friction Angle - Max (degrees),Cohesion - Mean (kPa),Cohesion - Median (kPa),Cohesion - CoV (%),Cohesion - Min (kPa),Cohesion - Max (kPa) +adf,9999,9999,0,9999,9999,9999,9999,0,9999,9999 +Qi,17,19,52,3,28,15.75,11.97,52,5.99,27.53 +af/Qi,9999,9999,0,9999,9999,9999,9999,0,9999,9999 +Qal1,23,23,46,8,44,32.46,23.94,82,1.96,82.83 +Qal2,23,23,46,8,44,32.46,23.94,82,1.96,82.83 +Qal3,23,23,46,8,44,32.46,23.94,82,1.96,82.83 +Qoa,29,30,37,13,46,33.13,23.94,106,0.05,91.21 +Qs,36,37,13,13,46,10.58,4.79,170,0.05,43.09 +QT,26,26,42,28,42,43.33,35.91,79,0.05,100.55 +Tsh,27,27,40,9,45,40.79,29.93,117,2.35,111.85 +Tss,27,27,40,9,45,40.79,29.93,117,2.35,111.85 +Tv,30,29,46,15,44,25.57,27.53,65,5.46,43.52 +sp,28,26,42,13,48,48.17,35.91,97,2.39,149.63 +Kss,24,24,42,8,40,36.48,28.73,85,1.1,101.6 +KJf,26,25,39,12,43,43.24,29.21,113,2.92,106.77 +crystalline,26,26,35,13,38,18.15,16.76,82,0.05,42.66 +crystalin2,40,40,25,30,50,23.94,23.94,100,0.05,35.91 +water,9999,9999,0,9999,9999,9999,9999,0,9999,9999 diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/gmpe/CorrelationModel.py b/modules/performRegionalEventSimulation/regionalGroundMotion/gmpe/CorrelationModel.py index 8280f3c00..d6e820aac 100644 --- a/modules/performRegionalEventSimulation/regionalGroundMotion/gmpe/CorrelationModel.py +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/gmpe/CorrelationModel.py @@ -65,7 +65,7 @@ def baker_jayaram_correlation_2008(im1, im2, flag_orth=False): # noqa: FBT002, elif im1.startswith('PGA'): T1 = 0.0 # noqa: N806 else: - return 0.0 + return 0.0 # noqa: DOC201, RUF100 if im2.startswith('SA'): T2 = float(im2[3:-1]) # noqa: N806 elif im2.startswith('PGA'): @@ -126,7 +126,7 @@ def bradley_correlation_2011(IM, T=None, flag_Ds=True): # noqa: FBT002, C901, N # PGA if IM == 'PGA': # noqa: RET503 if flag_Ds: - return -0.442 + return -0.442 # noqa: DOC201, RUF100 else: # noqa: RET505 return -0.305 elif IM == 'PGV': @@ -252,7 +252,7 @@ def jayaram_baker_correlation_2009(im, h, flag_clustering=False): # noqa: FBT00 else: b = 40.7 - 15.0 * T rho = np.exp(-3.0 * h / b) - return rho # noqa: RET504 + return rho # noqa: DOC201, RET504, RUF100 def load_loth_baker_correlation_2013(datapath): @@ -270,7 +270,7 @@ def load_loth_baker_correlation_2013(datapath): B2 = pd.read_csv(datapath + 'loth_baker_correlation_2013_B2.csv', header=0) # noqa: N806 B1 = pd.read_csv(datapath + 'loth_baker_correlation_2013_B1.csv', header=0) # noqa: N806 B3 = pd.read_csv(datapath + 'loth_baker_correlation_2013_B3.csv', header=0) # noqa: N806 - return B1, B2, B3 + return B1, B2, B3 # noqa: DOC201, RUF100 def compute_rho_loth_baker_correlation_2013(T1, T2, h, B1, B2, B3): # noqa: N803 @@ -303,7 +303,7 @@ def compute_rho_loth_baker_correlation_2013(T1, T2, h, B1, B2, B3): # noqa: N80 Ch = b1 * np.exp(-3.0 * h / 20.0) + b2 * np.exp(-3.0 * h / 70.0) + b3 * (h == 0) # noqa: N806 # Correlation coefficient rho = Ch - return rho # noqa: RET504 + return rho # noqa: DOC201, RET504, RUF100 def loth_baker_correlation_2013(stations, im_name_list, num_simu): # noqa: C901 @@ -373,7 +373,7 @@ def loth_baker_correlation_2013(stations, im_name_list, num_simu): # noqa: C901 .swapaxes(1, 2) ) # return - return residuals # noqa: RET504 + return residuals # noqa: DOC201, RET504, RUF100 def load_markhvida_ceferino_baker_correlation_2017(datapath): @@ -404,7 +404,7 @@ def load_markhvida_ceferino_baker_correlation_2017(datapath): index_col=None, header=0, ) - return MCB_model, MCB_pca, MCB_var + return MCB_model, MCB_pca, MCB_var # noqa: DOC201, RUF100 def markhvida_ceferino_baker_correlation_2017( # noqa: C901 @@ -521,7 +521,7 @@ def markhvida_ceferino_baker_correlation_2017( # noqa: C901 if tmp_periods > model_Tmax: residuals = np.concatenate((residuals, Tmax_residuals), axis=1) # return - return residuals + return residuals # noqa: DOC201, RUF100 def load_du_ning_correlation_2021(datapath): @@ -548,7 +548,7 @@ def load_du_ning_correlation_2021(datapath): DN_var = pd.read_csv( # noqa: N806 datapath + 'du_ning_correlation_2021_var_scale.csv', index_col=None, header=0 ) - return DN_model, DN_pca, DN_var + return DN_model, DN_pca, DN_var # noqa: DOC201, RUF100 def du_ning_correlation_2021(stations, im_name_list, num_simu, num_pc=23): @@ -657,7 +657,7 @@ def du_ning_correlation_2021(stations, im_name_list, num_simu, num_pc=23): ) # return - return residuals + return residuals # noqa: DOC201, RUF100 def baker_bradley_correlation_2017(im1=None, im2=None): # noqa: C901 @@ -686,7 +686,7 @@ def baker_bradley_correlation_2017(im1=None, im2=None): # noqa: C901 print( # noqa: T201 f'CorrelationModel.baker_bradley_correlation_2017: warning - return 0.0 for unknown {im1}' ) - return 0.0 + return 0.0 # noqa: DOC201, RUF100 im_list.append(tmp_tag) period_list.append(None) if im2.startswith('SA'): diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/gmpe/SignificantDurationModel.py b/modules/performRegionalEventSimulation/regionalGroundMotion/gmpe/SignificantDurationModel.py index 57f02c96b..137adec5d 100644 --- a/modules/performRegionalEventSimulation/regionalGroundMotion/gmpe/SignificantDurationModel.py +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/gmpe/SignificantDurationModel.py @@ -65,7 +65,7 @@ def abrahamson_silva_ds_1999( print( # noqa: T201 "SignificantDurationModel.abrahamson_silva_ds_1999: duration_type='DS575H','DS575V','DS595H','DS595V'?" ) - return None, None + return None, None # noqa: DOC201, RUF100 # modeling coefficients beta = [3.2, 3.2, 3.2, 3.2] b1 = [5.204, 4.610, 5.204, 4.610] @@ -140,7 +140,7 @@ def bommer_stafford_alarcon_ds_2009( print( # noqa: T201 "SignificantDurationModel.bommer_stafford_alarcon_ds_2009: duration_type='DS575H','DS595H'?" ) - return None, None, None, None + return None, None, None, None # noqa: DOC201, RUF100 # modeling coefficients c0 = [-5.6298, -2.2393] @@ -205,7 +205,7 @@ def afshari_stewart_ds_2016( # noqa: C901 print( # noqa: T201 "SignificantDurationModel.afshari_stewart_ds_2016: mechanism='unknown','normal','reverse','strike-slip'?" ) - return None, None, None, None + return None, None, None, None # noqa: DOC201, RUF100 # region map reg_map = {'california': 0, 'japan': 1, 'other': 2} reg_tag = reg_map.get(region.lower(), None) diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/gmpe/openSHAGMPE.py b/modules/performRegionalEventSimulation/regionalGroundMotion/gmpe/openSHAGMPE.py index a2090477b..3a6c527ec 100644 --- a/modules/performRegionalEventSimulation/regionalGroundMotion/gmpe/openSHAGMPE.py +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/gmpe/openSHAGMPE.py @@ -240,7 +240,7 @@ def calc(self, Mw, rJB, rRup, rX, dip, zTop, vs30, vsInf, z1p0, style): # noqa: stdDev = np.sqrt(tauSq + phiSq) # noqa: N806 - return mean, stdDev, np.sqrt(tauSq), np.sqrt(phiSq) + return mean, stdDev, np.sqrt(tauSq), np.sqrt(phiSq) # noqa: DOC201, RUF100 # https://github.com/opensha/opensha/blob/master/src/main/java/org/opensha/sha/imr/attenRelImpl/ngaw2/NGAW2_Wrapper.java#L220 def getFaultFromRake(self, rake): # noqa: N802, D102 diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/landslide.py b/modules/performRegionalEventSimulation/regionalGroundMotion/landslide.py new file mode 100644 index 000000000..d4119aba9 --- /dev/null +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/landslide.py @@ -0,0 +1,638 @@ +import numpy as np # noqa: CPY001, D100, I001, INP001, RUF100 +import rasterio as rio +from scipy.interpolate import interp2d +import sys, warnings, shapely, pandas, os # noqa: ICN001, E401 +from pyproj import Transformer +from pyproj import CRS +from enum import Enum +import geopandas as gpd +from scipy.spatial import ConvexHull +import pandas as pd + + +## Helper functions # noqa: E266, RUF100 +def sampleRaster( # noqa: N802 + raster_file_path, raster_crs, x, y, interp_scheme='nearest', dtype=None +): + """performs 2D interpolation at (x,y) pairs. Accepted interp_scheme = 'nearest', 'linear', 'cubic', and 'quintic'""" # noqa: D400, D401, D403 + print(f'Sampling from the Raster File: {os.path.basename(raster_file_path)}...') # noqa: T201, PTH119 + invalid_value = np.nan + xy_crs = CRS.from_user_input(4326) + raster_crs = CRS.from_user_input(raster_crs) + with rio.open(raster_file_path) as raster_file: + try: + raster_data = raster_file.read() + if raster_data.shape[0] > 1: + warnings.warn( # noqa: B028 + f'More than one band in the file {raster_file_path}, the first band is used.' + ) + except: # noqa: E722 + sys.exit(f'Can not read data from {raster_file_path}') + if xy_crs != raster_crs: + # make transformer for reprojection + transformer_xy_to_data = Transformer.from_crs( + xy_crs, raster_crs, always_xy=True + ) + # reproject and store + x_proj, y_proj = transformer_xy_to_data.transform(x, y) + x = x_proj + y = y_proj + n_sample = len(x) + if interp_scheme == 'nearest': + sample = np.array( + [val[0] for val in raster_file.sample(list(zip(x, y)))] + ) + else: + # create x and y ticks for grid + x_tick = np.linspace( + raster_file.bounds.left, + raster_file.bounds.right, + raster_file.width, + endpoint=False, + ) + y_tick = np.linspace( + raster_file.bounds.bottom, + raster_file.bounds.top, + raster_file.height, + endpoint=False, + ) + # create interp2d function + interp_function = interp2d( + x_tick, + y_tick, + np.flipud(raster_file.read(1)), + kind=interp_scheme, + fill_value=invalid_value, + ) + # get samples + sample = np.transpose( + [interp_function(x[i], y[i]) for i in range(n_sample)] + )[0] + # convert to target datatype + if dtype is not None: + sample = sample.astype(dtype) + # clean up invalid values (returned as 1e38 by NumPy) + sample[abs(sample) > 1e10] = invalid_value # noqa: PLR2004 + return sample # noqa: DOC201, RUF100 + + +## Helper functions # noqa: E266, RUF100 +def sampleVector(vector_file_path, vector_crs, x, y, dtype=None): # noqa: ARG001, N802 + """performs spatial join of vector_file with xy'""" # noqa: D400, D401, D403 + print(f'Sampling from the Vector File: {os.path.basename(vector_file_path)}...') # noqa: T201, PTH119 + invalid_value = np.nan # noqa: F841 + xy_crs = CRS.from_user_input(4326) + vector_gdf = gpd.read_file(vector_file_path) + if vector_gdf.crs != vector_crs: + sys.exit( + f"The CRS of vector file {vector_file_path} is {vector_gdf.crs}, and doesn't match the input CRS ({xy_crs}) defined for liquefaction triggering models" + ) + if xy_crs != vector_crs: + # make transformer for reprojection + transformer_xy_to_data = Transformer.from_crs( + xy_crs, vector_crs, always_xy=True + ) + # reproject and store + x_proj, y_proj = transformer_xy_to_data.transform(x, y) + x = x_proj + y = y_proj + # Create a convex hull containing all sites + sites = np.array([x, y]).transpose() + try: + hull = ConvexHull(sites) + vertices = hull.vertices + vertices = sites[np.append(vertices, vertices[0])] + centroid = np.mean(vertices, axis=0) + vertices = vertices + 0.05 * (vertices - centroid) # noqa: PLR6104, RUF100 + RoI = shapely.geometry.Polygon(vertices) # noqa: N806 + except: # noqa: E722 + centroid = shapely.geometry.Point(np.mean(x), np.mean(y)) + points = [shapely.geometry.Point(x[i], y[i]) for i in range(len(x))] + if len(points) == 1: + distances = [0.1] # Degree + else: + distances = [point.distance(centroid) for point in points] + max_distance = max(distances) * 1.2 + angles = np.linspace(0, 2 * np.pi, 36) + circle_points = [ + ( + centroid.x + max_distance * np.cos(angle), + centroid.y + max_distance * np.sin(angle), + ) + for angle in angles + ] + RoI = shapely.geometry.Polygon(circle_points) # noqa: N806 + data = dict() # noqa: C408 + for col in vector_gdf.columns: + data.update({col: []}) + for row_index in vector_gdf.index: + new_geom = RoI.intersection(vector_gdf.loc[row_index, 'geometry']) + if new_geom.is_empty: + continue + columns = list(vector_gdf.columns) + columns.remove('geometry') + for col in columns: + data[col].append(vector_gdf.loc[row_index, col]) + data['geometry'].append(new_geom) + del vector_gdf + gdf_roi = gpd.GeoDataFrame(data, geometry='geometry', crs=4326) + geometry = [shapely.geometry.Point(lon, lat) for lon, lat in zip(x, y)] # noqa: FURB140, RUF100 + gdf_sites = gpd.GeoDataFrame(geometry=geometry, crs=4326).reset_index() + merged = gpd.GeoDataFrame.sjoin( + gdf_roi, gdf_sites, how='inner', predicate='contains' + ) + merged = merged.set_index('index_right').sort_index().drop(columns=['geometry']) + gdf_sites = pandas.merge(gdf_sites, merged, on='index', how='left') + gdf_sites.drop(columns=['geometry', 'index'], inplace=True) # noqa: PD002 + return gdf_sites # noqa: DOC201, RUF100 + + +def find_additional_output_req(liq_info, current_step): # noqa: D103 + additional_output_keys = [] + if current_step == 'Triggering': + trigging_parameters = liq_info['Triggering']['Parameters'].keys() # noqa: F841 + triger_dist_water = liq_info['Triggering']['Parameters'].get( + 'DistWater', None + ) + if triger_dist_water is None: + return additional_output_keys + lat_dist_water = liq_info['LateralSpreading']['Parameters'].get( + 'DistWater', None + ) + if 'LateralSpreading' in liq_info.keys(): # noqa: SIM118 + lat_dist_water = liq_info['LateralSpreading']['Parameters'].get( + 'DistWater', None + ) + if (liq_info['LateralSpreading']['Model'] == 'Hazus2020') and ( + lat_dist_water == triger_dist_water + ): + additional_output_keys.append('dist_to_water') + return additional_output_keys + + +def infer_from_geologic_map(map_path, map_crs, lon_station, lat_station): # noqa: D103 + gdf_units = sampleVector(map_path, map_crs, lon_station, lat_station, dtype=None) + gdf_units = gdf_units['PTYPE'] + gdf_units = gdf_units.fillna('water') + default_geo_prop_fpath = os.path.join( # noqa: PTH118 + os.path.dirname(os.path.abspath(__file__)), # noqa: PTH100, PTH120 + 'database', + 'groundfailure', + 'Wills_etal_2015_CA_Geologic_Properties.csv', + ) + default_geo_prop = pd.read_csv(default_geo_prop_fpath) + unique_geo_unit = np.unique(gdf_units) + phi_mean = np.empty_like(gdf_units) + coh_mean = np.empty_like(gdf_units) + for each in unique_geo_unit: + rows_with_geo_unit = np.where(gdf_units.values == each)[0] # noqa: PD011 + rows_for_param = np.where( + default_geo_prop['Unit Abbreviation'].values == each # noqa: PD011 + )[0][0] + phi_mean[rows_with_geo_unit] = default_geo_prop[ + 'Friction Angle - Median (degrees)' + ][rows_for_param] + coh_mean[rows_with_geo_unit] = default_geo_prop['Cohesion - Median (kPa)'][ + rows_for_param + ] + return phi_mean, coh_mean + + +def erf2(x): + """modified from https://www.johndcook.com/blog/2009/01/19/stand-alone-error-function-erf""" # noqa: D400, D401, D403 + # constants + a1 = 0.254829592 + a2 = -0.284496736 + a3 = 1.421413741 + a4 = -1.453152027 + a5 = 1.061405429 + p = 0.3275911 + # Save the sign of x + signs = np.sign(x) + x = np.abs(x) + # A & S 7.1.26 + t = 1.0 / (1.0 + p * x) + y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * np.exp(-(x**2)) + return signs * y # noqa: DOC201, RUF100 + + +def norm2_cdf(x, loc, scale): + """ + modified implementation of norm.cdf function from numba_stats, using self-implemented erf function + https://github.com/HDembinski/numba-stats/blob/main/src/numba_stats/norm.py + """ # noqa: D205, D400, D401 + inter = (x - loc) / scale + return 0.5 * (1 + erf2(inter * np.sqrt(0.5))) # noqa: DOC201, RUF100 + + +def erf2_2d(x): + """modified from https://www.johndcook.com/blog/2009/01/19/stand-alone-error-function-erf""" # noqa: D400, D401, D403 + # constants + a1 = 0.254829592 + a2 = -0.284496736 + a3 = 1.421413741 + a4 = -1.453152027 + a5 = 1.061405429 + p = 0.3275911 + # Save the sign of x + signs = np.sign(x) + x = np.abs(x) + # A & S 7.1.26 + t = 1.0 / (1.0 + p * x) + y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * np.exp(-(x**2)) + return signs * y # noqa: DOC201, RUF100 + + +def norm2_cdf_2d(x, loc, scale): + """ + modified implementation of norm.cdf function from numba_stats, using self-implemented erf function + https://github.com/HDembinski/numba-stats/blob/main/src/numba_stats/norm.py + """ # noqa: D205, D400, D401 + inter = (x - loc) / scale + return 0.5 * (1 + erf2_2d(inter * np.sqrt(0.5))) # noqa: DOC201, RUF100 + + +def nb_round(x, decimals): # noqa: D103 + out = np.empty_like(x) + return np.round_(x, decimals, out) # noqa: NPY003, NPY201 + + +def erfinv_coeff(order=20): # noqa: D103 + # initialize + c = np.empty(order + 1) + # starting value + c[0] = 1 + for i in range(1, order + 1): + c[i] = sum([c[j] * c[i - 1 - j] / (j + 1) / (2 * j + 1) for j in range(i)]) # noqa: C419, RUF100 + # return + return c + + +def erfinv(x, order=20): + """returns inverse erf(x)""" # noqa: D400, D401, D403 + # get coefficients + c = erfinv_coeff(order) + # initialize + root_pi_over_2 = np.sqrt(np.pi) / 2 + y = np.zeros(x.shape) + for i in range(order): + y += c[i] / (2 * i + 1) * (root_pi_over_2 * x) ** (2 * i + 1) + # return + return y # noqa: DOC201, RUF100 + + +def norm2_ppf(p, loc, scale): + """ + modified implementation of norm.ppf function from numba_stats, using self-implemented erfinv function + https://github.com/HDembinski/numba-stats/blob/main/src/numba_stats/norm.py + """ # noqa: D205, D400, D401 + inter = np.sqrt(2) * erfinv(2 * p - 1, order=20) + return scale * inter + loc # noqa: DOC201, RUF100 + + +def erfinv_2d(x, order=20): + """returns inverse erf(x)""" # noqa: D400, D401, D403 + # get coefficients + c = erfinv_coeff(order) + # initialize + root_pi_over_2 = np.sqrt(np.pi) / 2 + y = np.zeros(x.shape) + for i in range(order): + y += c[i] / (2 * i + 1) * (root_pi_over_2 * x) ** (2 * i + 1) + # return + return y # noqa: DOC201, RUF100 + + +def norm2_ppf_2d(p, loc, scale): + """ + modified implementation of norm.ppf function from numba_stats, using self-implemented erfinv function + https://github.com/HDembinski/numba-stats/blob/main/src/numba_stats/norm.py + """ # noqa: D205, D400, D401 + inter = np.sqrt(2) * erfinv_2d(2 * p - 1, order=20) + return scale * inter + loc # noqa: DOC201, RUF100 + + +class Landslide: # noqa: D101 + def __init__(self) -> None: + pass + + +# ----------------------------------------------------------- +class BrayMacedo2019(Landslide): + """ + Compute landslide deformation at a given location using the Bray and Macedo (2007) probabilistic model. + Regression models based on three sets of ground motions are provided: + + 1. **Ordinary**: **d** = f(ky, Sa(T), Ts, M) + 2. **Near-fault**: **d** = f(ky, Sa(T), Ts, M, pgv) - unavailable for this version of OpenSRA + 3. **General** (default): **d** = f(ky, Sa(T), Ts, M, pgv) - unavailable for this version of OpenSRA + + The default relationship for **ky** uses **coh_soil**, **phi_soil**, **gamma_soil**, **t_slope**, **slope** + + **PGA** is used in place of **Sa(T)** (i.e., Ts=0) + + Parameters + ---------- + From upstream PBEE: + pga: float, np.ndarray or list + [g] peak ground acceleration + mag: float, np.ndarray or list + moment magnitude + + Geotechnical/geologic: + slope: float, np.ndarray or list + [deg] slope angle + t_slope: float, np.ndarray or list + [m] slope thickness (infinite-slope problem) + gamma_soil: float, np.ndarray or list + [kN/m^3] unit weight of soil + phi_soil: float, np.ndarray or list + [deg] friction angle of soil + coh_soil: float, np.ndarray or list + [kPa] cohesion of soil + + Fixed: + + Returns + ------- + pgdef : float, np.ndarray + [m] permanent ground deformation + sigma_pgdef : float, np.ndarray + aleatory variability for ln(pgdef) + + References + ---------- + .. [1] Bray, J.D., and Macedo, J., 2019, Procedure for Estimating Shear-Induced Seismic Slope Displacement for Shallow Crustal Earthquakes, Journal of Geotechnical and Geoenvironmental Engineering, vol. 145, pp. 12, 04019106. + + """ # noqa: D205, D400 + + def __init__(self, parameters, stations) -> None: + self.stations = stations + self.parameters = parameters + self.slope = None # (km) + self.t_slope = None # (km) + self.gamma_soil = None # (km) + self.phi_soil = None # (m) + self.coh_soil = None # (mm) + self.interpolate_spatial_parameters(parameters) + + def interpolate_spatial_parameters(self, parameters): # noqa: C901, D102 + # site coordinate in CRS 4326 + lat_station = [site['lat'] for site in self.stations] + lon_station = [site['lon'] for site in self.stations] + # slope + if parameters['Slope'] == 'Defined ("slope") in Site File (.csv)': + self.slope = np.array([site['slope'] for site in self.stations]) + else: + self.slope = sampleRaster( + parameters['Slope'], parameters['inputCRS'], lon_station, lat_station + ) + # t_slope + if ( + parameters['SlopeThickness'] + == 'Defined ("slopeThickness") in Site File (.csv)' + ): + self.t_slope = np.array( + [site['slopeThickness'] for site in self.stations] + ) + elif parameters['SlopeThickness'] == 'Use constant value (m)': + self.t_slope = np.array( + [parameters['SlopeThicknessValue']] * len(self.stations) + ) + else: + self.t_slope = sampleRaster( + parameters['SlopeThickness'], + parameters['inputCRS'], + lon_station, + lat_station, + ) + # gamma_soil + if parameters['GammaSoil'] == 'Defined ("gammaSoil") in Site File (.csv)': + self.gamma_soil = np.array([site['gammaSoil'] for site in self.stations]) + elif parameters['GammaSoil'] == 'Use constant value (kN/m^3)': + self.gamma_soil = np.array( + [parameters['GammaSoilValue']] * len(self.stations) + ) + else: + self.gamma_soil = sampleRaster( + parameters['GammaSoil'], + parameters['inputCRS'], + lon_station, + lat_station, + ) + # phi_soil + if parameters['PhiSoil'] == 'Defined ("phiSoil") in Site File (.csv)': + self.phi_soil = np.array([site['phiSoil'] for site in self.stations]) + elif parameters['PhiSoil'] == 'Use constant value (deg)': + self.phi_soil = np.array( + [parameters['PhiSoilValue']] * len(self.stations) + ) + elif parameters['PhiSoil'] == 'Infer from Geologic Map (Bain et al. 2022)': + if ( + parameters['CohesionSoil'] + == 'Infer from Geologic Map (Bain et al. 2022)' + ): + self.phi_soil, self.coh_soil = infer_from_geologic_map( + parameters['GeologicMap'], + parameters['inputCRS'], + lon_station, + lat_station, + ) + else: + self.phi_soil, _ = infer_from_geologic_map( + parameters['GeologicMap'], + parameters['inputCRS'], + lon_station, + lat_station, + ) + else: + self.phi_soil = sampleRaster( + parameters['CohesionSoil'], + parameters['inputCRS'], + lon_station, + lat_station, + ) + # coh_soil + if self.coh_soil is None: + if ( + parameters['CohesionSoil'] + == 'Defined ("cohesionSoil") in Site File (.csv)' + ): + self.coh_soil = np.array( + [site['cohesionSoil'] for site in self.stations] + ) + elif parameters['CohesionSoil'] == 'Use constant value (kPa)': + self.coh_soil = np.array( + [parameters['CohesionSoilValue']] * len(self.stations) + ) + elif ( + parameters['CohesionSoil'] + == 'Infer from Geologic Map (Bain et al. 2022)' + ): + self.coh_soil = infer_from_geologic_map( + parameters['GeologicMap'], + parameters['inputCRS'], + lon_station, + lat_station, + ) + else: + self.coh_soil = sampleRaster( + parameters['CohesionSoil'], + parameters['inputCRS'], + lon_station, + lat_station, + ) + + print('Initiation finished') # noqa: T201 + + def run( # noqa: D102 + self, + ln_im_data, + eq_data, + im_list, + output_keys=['lsd_PGD_h'], # noqa: B006 + additional_output_keys=[], # noqa: B006, ARG002 + ): + if 'PGA' in im_list: + num_stations = len(self.stations) + num_scenarios = len(eq_data) + PGA_col_id = [i for i, x in enumerate(im_list) if x == 'PGA'][0] # noqa: N806, RUF015 + for scenario_id in range(num_scenarios): + num_rlzs = ln_im_data[scenario_id].shape[2] + im_data_scen = np.zeros( + [num_stations, len(im_list) + len(output_keys), num_rlzs] + ) + im_data_scen[:, 0 : len(im_list), :] = ln_im_data[scenario_id] + for rlz_id in range(num_rlzs): + pga = np.exp(ln_im_data[scenario_id][:, PGA_col_id, rlz_id]) + mag = float(eq_data[scenario_id][0]) + model_output = self.model( + pga, + mag, + self.slope, + self.t_slope, + self.gamma_soil, + self.phi_soil, + self.coh_soil, + ) + for i, key in enumerate(output_keys): + im_data_scen[:, len(im_list) + i, rlz_id] = model_output[key] + ln_im_data[scenario_id] = im_data_scen + im_list = im_list + output_keys # noqa: PLR6104, RUF100 + else: + sys.exit( + f"'PGA' is missing in the selected intensity measures and the landslide model 'BrayMacedo2019' can not be computed." # noqa: F541 + ) + # print(f"At least one of 'PGA' and 'PGV' is missing in the selected intensity measures and the liquefaction trigging model 'ZhuEtal2017' can not be computed."\ + # , file=sys.stderr) + # sys.stderr.write("test") + # sys.exit(-1) + return ( + ln_im_data, + eq_data, + im_list, + ) + + def model( # noqa: PLR6301, RUF100 + self, + pga, + mag, # upstream PBEE RV + slope, + t_slope, + gamma_soil, + phi_soil, + coh_soil, # geotechnical/geologic + return_inter_params=False, # to get intermediate params # noqa: FBT002, ARG002 + ): + """Model""" # noqa: D202, D400 + + # get dimensions + ndim = pga.ndim + if ndim == 1: + n_site = len(pga) + n_sample = 1 + shape = n_site + else: + shape = pga.shape + n_site = shape[0] + n_sample = shape[1] + + # initialize + pgdef = np.zeros(shape) + ky = np.zeros(shape) + prob_d_eq_0 = np.zeros(shape) + ln_pgdef_trunc = np.zeros(shape) + nonzero_median_cdf = np.zeros(shape) + + # convert from deg to rad + slope_rad = (slope * np.pi / 180).astype(np.float32) + phi_soil_rad = (phi_soil * np.pi / 180).astype(np.float32) + coh_soil = coh_soil.astype(np.float32) + + # yield acceleration + ky = np.tan(phi_soil_rad - slope_rad) + coh_soil / ( + gamma_soil + * t_slope + * np.cos(slope_rad) ** 2 + * (1 + np.tan(phi_soil_rad) * np.tan(slope_rad)) + ) + ky = np.maximum(ky, 0.01) # to avoid ky = 0 + + # aleatory + sigma_val = 0.72 + + # deformation, eq 3b + ln_pgdef_trunc = ( + -4.684 + + -2.482 * np.log(ky) + + -0.244 * (np.log(ky)) ** 2 + + 0.344 * np.log(ky) * np.log(pga) + + 2.649 * np.log(pga) + + -0.090 * (np.log(pga)) ** 2 + + 0.603 * mag + ) # cm + nonzero_ln_pgdef = ln_pgdef_trunc.copy() + + # probability of zero displacement, eq. 2 with Ts=0 + if ndim == 1: + prob_d_eq_0 = 1 - norm2_cdf( + -2.480 + + -2.970 * np.log(ky) + + -0.120 * (np.log(ky)) ** 2 + + 2.780 * np.log(pga), + 0, + 1, + ) + else: + prob_d_eq_0 = 1 - norm2_cdf_2d( + -2.480 + + -2.970 * np.log(ky) + + -0.120 * (np.log(ky)) ** 2 + + 2.780 * np.log(pga), + 0, + 1, + ) + prob_d_eq_0 = nb_round(prob_d_eq_0, decimals=15) + + # apply non-zero displacement correction/condition, eq 11 + nonzero_median_cdf = 1 - 0.5 / (1 - prob_d_eq_0) + + # loop through numper of samples + if ndim == 1: + nonzero_ln_pgdef[nonzero_median_cdf > 0] = ln_pgdef_trunc[ + nonzero_median_cdf > 0 + ] + sigma_val * norm2_ppf( + nonzero_median_cdf[nonzero_median_cdf > 0], 0.0, 1.0 + ) + else: + for i in range(n_sample): + cond = nonzero_median_cdf[:, i] > 0 + nonzero_ln_pgdef[cond, i] = ln_pgdef_trunc[ + cond, i + ] + sigma_val * norm2_ppf(nonzero_median_cdf[cond, i], 0.0, 1.0) + + # rest of actions + pgdef = np.exp(nonzero_ln_pgdef) / 100 # also convert from cm to m + pgdef = np.maximum(pgdef, 1e-5) # limit to + output = {'lsd_PGD_h': pgdef} + return output # noqa: DOC201, RET504, RUF100 diff --git a/modules/performRegionalEventSimulation/regionalGroundMotion/liquefaction.py b/modules/performRegionalEventSimulation/regionalGroundMotion/liquefaction.py index 82c142387..43bc5d13c 100644 --- a/modules/performRegionalEventSimulation/regionalGroundMotion/liquefaction.py +++ b/modules/performRegionalEventSimulation/regionalGroundMotion/liquefaction.py @@ -82,7 +82,7 @@ def sampleRaster( # noqa: N802 sample = sample.astype(dtype) # clean up invalid values (returned as 1e38 by NumPy) sample[abs(sample) > 1e10] = invalid_value # noqa: PLR2004 - return sample + return sample # noqa: DOC201, RUF100 # Helper functions @@ -163,7 +163,7 @@ def sampleVector(vector_file_path, vector_crs, x, y, dtype=None): # noqa: ARG00 merged = merged.set_index('index_right').sort_index().drop(columns=['geometry']) gdf_sites = pandas.merge(gdf_sites, merged, on='index', how='left') gdf_sites.drop(columns=['geometry', 'index'], inplace=True) # noqa: PD002 - return gdf_sites + return gdf_sites # noqa: DOC201, RUF100 def find_additional_output_req(liq_info, current_step): # noqa: D103 @@ -175,9 +175,6 @@ def find_additional_output_req(liq_info, current_step): # noqa: D103 ) if triger_dist_water is None: return additional_output_keys - lat_dist_water = liq_info['LateralSpreading']['Parameters'].get( - 'DistWater', None - ) if 'LateralSpreading' in liq_info.keys(): # noqa: SIM118 lat_dist_water = liq_info['LateralSpreading']['Parameters'].get( 'DistWater', None @@ -458,7 +455,7 @@ def model(self, pgv, pga, mag): # liq_susc[prob_liq==zero_prob_liq] = 'none' - return {'liq_prob': prob_liq, 'liq_susc': liq_susc} + return {'liq_prob': prob_liq, 'liq_susc': liq_susc} # noqa: DOC201, RUF100 # ----------------------------------------------------------- @@ -549,7 +546,7 @@ def interpolate_spatial_parameters(self, parameters): # noqa: D102 self.liq_susc = np.array(self.liq_susc) # liq_susc = liq_susc_samples[parameters["SusceptibilityKey"]].fillna("NaN") # self.liq_susc = liq_susc.to_numpy() - print('Sampling finished') # noqa: T201 + print('Initiation finished') # noqa: T201 def run(self, ln_im_data, eq_data, im_list, output_keys, additional_output_keys): # noqa: D102 if 'PGA' in im_list: @@ -661,7 +658,7 @@ def model( pga_mag = pga / (10**2.24 / mag**2.56) prob_liq[pga_mag < 0.1] = zero_prob_liq # noqa: PLR2004 - return {'liq_prob': prob_liq, 'liq_susc': liq_susc} + return {'liq_prob': prob_liq, 'liq_susc': liq_susc} # noqa: DOC201, RUF100 # ----------------------------------------------------------- @@ -824,7 +821,7 @@ def model(self, pgv, pga, mag): # for precip > 1700 mm, set prob to "0" prob_liq[self.precip > 1700] = zero_prob_liq # noqa: PLR2004 - return {'liq_prob': prob_liq, 'liq_susc': liq_susc} + return {'liq_prob': prob_liq, 'liq_susc': liq_susc} # noqa: DOC201, RUF100 # Lateral Spreading: @@ -990,7 +987,7 @@ def model( # output['ratio'] = ratio # return - return output # noqa: RET504 + return output # noqa: DOC201, RET504, RUF100 # Settlement: @@ -1063,7 +1060,7 @@ def model( pass # return - return output + return output # noqa: DOC201, RUF100 def run(self, ln_im_data, eq_data, im_list): # noqa: D102 output_keys = ['liq_PGD_v'] diff --git a/modules/performRegionalEventSimulation/regionalWindField/ComputeIntensityMeasure.py b/modules/performRegionalEventSimulation/regionalWindField/ComputeIntensityMeasure.py index 029119094..c32d912f8 100644 --- a/modules/performRegionalEventSimulation/regionalWindField/ComputeIntensityMeasure.py +++ b/modules/performRegionalEventSimulation/regionalWindField/ComputeIntensityMeasure.py @@ -448,7 +448,7 @@ def interp_wind_by_height(pws_ip, height_simu, height_ref): ) # return - return pws_op + return pws_op # noqa: DOC201, RUF100 def gust_factor_ESDU(gd_c, gd_t): # noqa: N802 @@ -475,7 +475,7 @@ def gust_factor_ESDU(gd_c, gd_t): # noqa: N802 gd_c, gd, gf, left=gf[0], right=gf[-1] ) # return - return gf_t # noqa: RET504 + return gf_t # noqa: DOC201, RET504, RUF100 def export_pws(stations, pws, output_dir, filename='EventGrid.csv'): # noqa: D103 diff --git a/modules/performRegionalEventSimulation/regionalWindField/CreateScenario.py b/modules/performRegionalEventSimulation/regionalWindField/CreateScenario.py index c420b6e15..15322c4c6 100644 --- a/modules/performRegionalEventSimulation/regionalWindField/CreateScenario.py +++ b/modules/performRegionalEventSimulation/regionalWindField/CreateScenario.py @@ -156,8 +156,8 @@ def create_wind_scenarios(scenario_info, event_info, stations, data_dir): # noq print('CreateScenario: error - no storm name or year is provided.') # noqa: T201 # Searching the storm try: - df_chs = df_hs[df_hs[('NAME', ' ')] == storm_name] - df_chs = df_chs[df_chs[('SEASON', 'Year')] == storm_year] + df_chs = df_hs[df_hs[('NAME', ' ')] == storm_name] # noqa: RUF031, RUF100 + df_chs = df_chs[df_chs[('SEASON', 'Year')] == storm_year] # noqa: RUF031, RUF100 except: # noqa: E722 print('CreateScenario: error - the storm is not found.') # noqa: T201 if len(df_chs.values) == 0: @@ -166,10 +166,10 @@ def create_wind_scenarios(scenario_info, event_info, stations, data_dir): # noq # Collecting storm properties track_lat = [] track_lon = [] - for x in df_chs[('USA_LAT', 'degrees_north')].values.tolist(): # noqa: PD011 + for x in df_chs[('USA_LAT', 'degrees_north')].values.tolist(): # noqa: PD011, RUF031, RUF100 if x != ' ': track_lat.append(float(x)) # noqa: PERF401 - for x in df_chs[('USA_LON', 'degrees_east')].values.tolist(): # noqa: PD011 + for x in df_chs[('USA_LON', 'degrees_east')].values.tolist(): # noqa: PD011, RUF031, RUF100 if x != ' ': track_lon.append(float(x)) # noqa: PERF401 # If the default option (USA_LAT and USA_LON) is not available, switching to LAT and LON @@ -177,10 +177,10 @@ def create_wind_scenarios(scenario_info, event_info, stations, data_dir): # noq print( # noqa: T201 'CreateScenario: warning - the USA_LAT and USA_LON are not available, switching to LAT and LON.' ) - for x in df_chs[('LAT', 'degrees_north')].values.tolist(): # noqa: PD011 + for x in df_chs[('LAT', 'degrees_north')].values.tolist(): # noqa: PD011, RUF031, RUF100 if x != ' ': track_lat.append(float(x)) # noqa: PERF401 - for x in df_chs[('LON', 'degrees_east')].values.tolist(): # noqa: PD011 + for x in df_chs[('LON', 'degrees_east')].values.tolist(): # noqa: PD011, RUF031, RUF100 if x != ' ': track_lon.append(float(x)) # noqa: PERF401 if len(track_lat) == 0: @@ -197,7 +197,7 @@ def create_wind_scenarios(scenario_info, event_info, stations, data_dir): # noq terrain_data = [] # Storm characteristics at the landfall dist2land = [] - for x in df_chs[('DIST2LAND', 'km')]: + for x in df_chs[('DIST2LAND', 'km')]: # noqa: RUF031, RUF100 if x != ' ': dist2land.append(x) # noqa: PERF401 if len(track_lat) == 0: @@ -237,14 +237,14 @@ def create_wind_scenarios(scenario_info, event_info, stations, data_dir): # noq track_simu = track_lat # Reading data try: - landfall_lat = float(df_chs[('USA_LAT', 'degrees_north')].iloc[tmploc]) - landfall_lon = float(df_chs[('USA_LON', 'degrees_east')].iloc[tmploc]) + landfall_lat = float(df_chs[('USA_LAT', 'degrees_north')].iloc[tmploc]) # noqa: RUF031, RUF100 + landfall_lon = float(df_chs[('USA_LON', 'degrees_east')].iloc[tmploc]) # noqa: RUF031, RUF100 except: # noqa: E722 # If the default option (USA_LAT and USA_LON) is not available, switching to LAT and LON - landfall_lat = float(df_chs[('LAT', 'degrees_north')].iloc[tmploc]) - landfall_lon = float(df_chs[('LON', 'degrees_east')].iloc[tmploc]) + landfall_lat = float(df_chs[('LAT', 'degrees_north')].iloc[tmploc]) # noqa: RUF031, RUF100 + landfall_lon = float(df_chs[('LON', 'degrees_east')].iloc[tmploc]) # noqa: RUF031, RUF100 try: - landfall_ang = float(df_chs[('STORM_DIR', 'degrees')].iloc[tmploc]) + landfall_ang = float(df_chs[('STORM_DIR', 'degrees')].iloc[tmploc]) # noqa: RUF031, RUF100 except: # noqa: E722 print('CreateScenario: error - no landing angle is found.') # noqa: T201 if landfall_ang > 180.0: # noqa: PLR2004 @@ -254,7 +254,7 @@ def create_wind_scenarios(scenario_info, event_info, stations, data_dir): # noq - np.min( [ float(x) - for x in df_chs[('USA_PRES', 'mb')] # noqa: PD011 + for x in df_chs[('USA_PRES', 'mb')] # noqa: PD011, RUF031, RUF100 .iloc[tmploc - 5 :] .values.tolist() if x != ' ' @@ -262,11 +262,11 @@ def create_wind_scenarios(scenario_info, event_info, stations, data_dir): # noq ) ) landfall_spd = ( - float(df_chs[('STORM_SPEED', 'kts')].iloc[tmploc]) * 0.51444 + float(df_chs[('STORM_SPEED', 'kts')].iloc[tmploc]) * 0.51444 # noqa: RUF031, RUF100 ) # convert knots/s to km/s try: landfall_rad = ( - float(df_chs[('USA_RMW', 'nmile')].iloc[tmploc]) * 1.60934 + float(df_chs[('USA_RMW', 'nmile')].iloc[tmploc]) * 1.60934 # noqa: RUF031, RUF100 ) # convert nmile to km except: # noqa: E722 # No available radius of maximum wind is found @@ -274,7 +274,7 @@ def create_wind_scenarios(scenario_info, event_info, stations, data_dir): # noq try: # If the default option (USA_RMW) is not available, switching to REUNION_RMW landfall_rad = ( - float(df_chs[('REUNION_RMW', 'nmile')].iloc[tmploc]) * 1.60934 + float(df_chs[('REUNION_RMW', 'nmile')].iloc[tmploc]) * 1.60934 # noqa: RUF031, RUF100 ) # convert nmile to km except: # noqa: E722 # No available radius of maximum wind is found diff --git a/modules/performRegionalEventSimulation/regionalWindField/CreateStation.py b/modules/performRegionalEventSimulation/regionalWindField/CreateStation.py index 0e14e611b..4eb3ffa04 100644 --- a/modules/performRegionalEventSimulation/regionalWindField/CreateStation.py +++ b/modules/performRegionalEventSimulation/regionalWindField/CreateStation.py @@ -68,7 +68,7 @@ def create_stations(input_file, output_file, min_id, max_id): stn_df = pd.read_csv(input_file, header=0, index_col=0) except: # noqa: E722 run_tag = 0 - return run_tag # noqa: RET504 + return run_tag # noqa: DOC201, RET504, RUF100 # Max and Min IDs stn_ids_min = np.min(stn_df.index.values) stn_ids_max = np.max(stn_df.index.values) diff --git a/modules/performRegionalEventSimulation/regionalWindField/WindFieldSimulation.py b/modules/performRegionalEventSimulation/regionalWindField/WindFieldSimulation.py index c3d5ef3ce..4f5e3c41b 100644 --- a/modules/performRegionalEventSimulation/regionalWindField/WindFieldSimulation.py +++ b/modules/performRegionalEventSimulation/regionalWindField/WindFieldSimulation.py @@ -168,7 +168,7 @@ def __interp_z0(self, lat, lon): if not z0: z0 = 0.01 # return - return z0 + return z0 # noqa: DOC201, RUF100 def add_reference_terrain(self, terrain_info): """add_reference_terrainL specifying reference z0 values for a set of polygons @@ -595,4 +595,4 @@ def compute_wind_field(self): def get_station_data(self): """get_station_data: returning station data""" # noqa: D400 # return station dictionary - return self.station + return self.station # noqa: DOC201, RUF100 diff --git a/modules/performUQ/SimCenterUQ/PLoM/PLoM.py b/modules/performUQ/SimCenterUQ/PLoM/PLoM.py index 76817b505..13973260a 100644 --- a/modules/performUQ/SimCenterUQ/PLoM/PLoM.py +++ b/modules/performUQ/SimCenterUQ/PLoM/PLoM.py @@ -374,7 +374,7 @@ def _load_h5_plom(self, filename): if cur_var in self.dbserver.get_item_adds() and ATTR_MAP[cur_var]: # noqa: F405 # read in cur_data = store[cur_var] - cur_dshape = tuple( + cur_dshape = tuple( # noqa: C409, RUF100 [x[0] for x in store['/DS_' + cur_var[1:]].values.tolist()] # noqa: PD011 ) if cur_dshape == (1,): @@ -416,7 +416,7 @@ def _load_h5_data_X(self, filename): # noqa: N802 item_name='X0', col_name=list(self.X0.columns), item=self.X0 ) - return self.X0.to_numpy() + return self.X0.to_numpy() # noqa: DOC201, RUF100 except: # noqa: E722 return None @@ -491,7 +491,7 @@ def load_h5(self, filename): ) if '/X0' in self.dbserver.get_name_list(): self.X0 = self.dbserver.get_item('X0', table_like=True) - return self.X0.to_numpy() + return self.X0.to_numpy() # noqa: DOC201, RUF100 else: # noqa: RET505 self.logfile.write_msg( msg='PLoM.load_h5: the original X0 data not found in the loaded data.', @@ -598,7 +598,7 @@ def ConfigTasks(self, task_list=FULL_TASK_LIST): # noqa: C901, N802, F405 msg_type='WARNING', msg_level=0, ) - return False + return False # noqa: DOC201, RUF100 map_order = [FULL_TASK_LIST.index(x) for x in self.cur_task_list] # noqa: F405 if map_order != sorted(map_order): self.logfile.write_msg( @@ -961,7 +961,7 @@ def DataNormalization(self, X): # noqa: N802, N803 X_scaled, alpha, x_min = plom.scaling(X) # noqa: N806 x_mean = plom.mean(X_scaled) - return X_scaled, alpha, x_min, x_mean + return X_scaled, alpha, x_min, x_mean # noqa: DOC201, RUF100 def RunPCA(self, X_origin, epsilon_pca): # noqa: N802, N803, D102 # ...PCA... @@ -995,7 +995,7 @@ def RunKDE(self, X, epsilon_kde): # noqa: N802, N803 (s_v, c_v, hat_s_v) = plom.parameters_kde(X) K, b = plom.K(X, epsilon_kde) # noqa: N806 - return s_v, c_v, hat_s_v, K, b + return s_v, c_v, hat_s_v, K, b # noqa: DOC201, RUF100 def DiffMaps(self, H, K, b, tol=0.1): # noqa: N802, N803, D102 # ..diff maps basis... diff --git a/modules/performUQ/SimCenterUQ/PLoM/general.py b/modules/performUQ/SimCenterUQ/PLoM/general.py index 19b6d05d7..039fbf191 100644 --- a/modules/performUQ/SimCenterUQ/PLoM/general.py +++ b/modules/performUQ/SimCenterUQ/PLoM/general.py @@ -149,13 +149,13 @@ def _create_export_dir(self): dir_export = os.path.join(self.db_dir, 'DataOut') # noqa: PTH118 try: os.makedirs(dir_export, exist_ok=True) # noqa: PTH103 - return dir_export # noqa: TRY300 + return dir_export # noqa: DOC201, RUF100, TRY300 except: # noqa: E722 return None def get_item_adds(self): """Returning the full list of data items""" # noqa: D400, D401 - return self._item_adds + return self._item_adds # noqa: DOC201, RUF100 def add_item( self, @@ -190,7 +190,7 @@ def add_item( store.close() # noqa: RET503 else: # Not supported data_type - return False + return False # noqa: DOC201, RUF100 def get_item(self, item_name=None, table_like=False, data_type='Data'): # noqa: FBT002 """Getting a specific data item""" # noqa: D400, D401 @@ -199,7 +199,7 @@ def get_item(self, item_name=None, table_like=False, data_type='Data'): # noqa: store = pd.HDFStore(self.db_path, 'r') try: item = store.get(item_name) - item_shape = tuple( + item_shape = tuple( # noqa: C409, RUF100 [ x[0] for x in self.get_item_shape( # noqa: PD011 @@ -214,7 +214,7 @@ def get_item(self, item_name=None, table_like=False, data_type='Data'): # noqa: finally: store.close() - return item + return item # noqa: DOC201, RUF100 elif data_type == 'ConstraintsFile': store = pd.HDFStore(self.db_path, 'r') try: @@ -247,7 +247,7 @@ def get_item_shape(self, item_name=None): item_shape = None store.close() - return item_shape + return item_shape # noqa: DOC201, RUF100 def get_name_list(self): """Returning the keys of the database""" # noqa: D400, D401 @@ -257,7 +257,7 @@ def get_name_list(self): except: # noqa: E722 name_list = [] store.close() - return name_list + return name_list # noqa: DOC201, RUF100 def export(self, data_name=None, filename=None, file_format='csv'): """Exporting the specific data item @@ -266,7 +266,7 @@ def export(self, data_name=None, filename=None, file_format='csv'): """ # noqa: D205, D400, D401 d = self.get_item(item_name=data_name[1:], table_like=True) if d is None: - return 1 + return 1 # noqa: DOC201, RUF100 if filename is None: filename = os.path.join( # noqa: PTH118 self.dir_export, str(data_name).replace('/', '') + '.' + file_format @@ -311,7 +311,7 @@ def refresh_status(self): # previous task not completed -> this task also needs to rerun self.status = False - return self.status + return self.status # noqa: DOC201, RUF100 # self-check if Counter(self.avail_var_list) == Counter(self.full_var_list) and len( @@ -355,7 +355,7 @@ def refresh_status(self): if not cur_task.status: self.status = False - return self.status + return self.status # noqa: DOC201, RUF100 while cur_task.next_task: cur_task = cur_task.next_task if not cur_task.status: diff --git a/modules/performUQ/SimCenterUQ/runPLoM.py b/modules/performUQ/SimCenterUQ/runPLoM.py index 08f3ac35f..bc3f494a6 100644 --- a/modules/performUQ/SimCenterUQ/runPLoM.py +++ b/modules/performUQ/SimCenterUQ/runPLoM.py @@ -428,7 +428,7 @@ def _create_variables(self, training_data): # check if training data source from simulation if training_data == 'Sampling and Simulation': - return x_dim, y_dim, rv_name, g_name + return x_dim, y_dim, rv_name, g_name # noqa: DOC201, RUF100 # read X and Y variable names for rv in job_config['randomVariables']: @@ -562,7 +562,7 @@ def _parse_plom_parameters(self, surrogateInfo): # noqa: C901, N803 run_flag = 1 # return - return run_flag + return run_flag # noqa: DOC201, RUF100 def _set_up_parallel(self): """_set_up_parallel: set up modules and variables for parallel jobs @@ -592,7 +592,7 @@ def _set_up_parallel(self): run_flag = 1 # return - return run_flag + return run_flag # noqa: DOC201, RUF100 def _load_variables(self, do_sampling, do_simulation): # noqa: C901 """_load_variables: load variables @@ -666,7 +666,7 @@ def _load_variables(self, do_sampling, do_simulation): # noqa: C901 # run_flag = 1 # return - return run_flag + return run_flag # noqa: DOC201, RUF100 # KZ, 07/24: loading user-defined hyper-parameter files def _load_hyperparameter(self): diff --git a/modules/performUQ/UCSD_UQ/defaultLogLikeScript.py b/modules/performUQ/UCSD_UQ/defaultLogLikeScript.py index cd147d466..c0e42c7be 100644 --- a/modules/performUQ/UCSD_UQ/defaultLogLikeScript.py +++ b/modules/performUQ/UCSD_UQ/defaultLogLikeScript.py @@ -142,4 +142,4 @@ def log_likelihood( loglike += ll else: loglike += -np.inf - return loglike + return loglike # noqa: DOC201, RUF100 diff --git a/modules/performUQ/UCSD_UQ/mwg_sampler.py b/modules/performUQ/UCSD_UQ/mwg_sampler.py index 546fb23d2..4bf1e1ea8 100644 --- a/modules/performUQ/UCSD_UQ/mwg_sampler.py +++ b/modules/performUQ/UCSD_UQ/mwg_sampler.py @@ -328,7 +328,7 @@ def tune(scale, acc_rate): >0.95 x 10 """ # noqa: D205, D400 if acc_rate < 0.01: # noqa: PLR2004 - return scale * 0.01 + return scale * 0.01 # noqa: DOC201, RUF100 elif acc_rate < 0.05: # noqa: RET505, PLR2004 return scale * 0.1 elif acc_rate < 0.2: # noqa: PLR2004 diff --git a/modules/performUQ/UCSD_UQ/runFEM.py b/modules/performUQ/UCSD_UQ/runFEM.py index 3e7497448..aa5136105 100644 --- a/modules/performUQ/UCSD_UQ/runFEM.py +++ b/modules/performUQ/UCSD_UQ/runFEM.py @@ -101,4 +101,4 @@ def runFEM( # noqa: N802 preds = np.atleast_2d([-np.inf] * sum(edpLengthsList)).reshape((1, -1)) ll = -np.inf - return (ll, preds) + return (ll, preds) # noqa: DOC201, RUF100 diff --git a/modules/performUQ/UCSD_UQ/runTMCMC.py b/modules/performUQ/UCSD_UQ/runTMCMC.py index 41ab9b66a..6bc59e0bc 100644 --- a/modules/performUQ/UCSD_UQ/runTMCMC.py +++ b/modules/performUQ/UCSD_UQ/runTMCMC.py @@ -561,4 +561,4 @@ def run_TMCMC( # noqa: N802, PLR0913 f'\n\tShutdown mpi4py executor pool for runType: {run_type}' ) - return mytrace, total_log_evidence + return mytrace, total_log_evidence # noqa: DOC201, RUF100 diff --git a/modules/performUQ/common/ERAClasses/ERACond.py b/modules/performUQ/common/ERAClasses/ERACond.py index 1ce36b6a1..cb3dd99fb 100644 --- a/modules/performUQ/common/ERAClasses/ERACond.py +++ b/modules/performUQ/common/ERAClasses/ERACond.py @@ -388,7 +388,7 @@ def equation(param): for i in range(len(Par)): Par[i] = np.squeeze(Par[i]) - return Par + return Par # noqa: DOC201, RUF100 # %% def condCDF(self, x, cond): # noqa: C901, N802 @@ -442,7 +442,7 @@ def condCDF(self, x, cond): # noqa: C901, N802 elif self.Name == 'weibull': CDF = stats.weibull_min.cdf(x, c=par[1], scale=par[0]) # noqa: N806 - return CDF + return CDF # noqa: DOC201, RUF100 # %% def condiCDF(self, y, cond): # noqa: C901, N802 @@ -496,7 +496,7 @@ def condiCDF(self, y, cond): # noqa: C901, N802 elif self.Name == 'weibull': iCDF = stats.weibull_min.ppf(y, c=par[1], scale=par[0]) # noqa: N806 - return iCDF + return iCDF # noqa: DOC201, RUF100 # %% def condPDF(self, x, cond): # noqa: C901, N802 @@ -550,7 +550,7 @@ def condPDF(self, x, cond): # noqa: C901, N802 elif self.Name == 'weibull': PDF = stats.weibull_min.pdf(x, c=par[1], scale=par[0]) # noqa: N806 - return PDF + return PDF # noqa: DOC201, RUF100 # %% def condRandom(self, cond): # noqa: C901, N802 @@ -602,4 +602,4 @@ def condRandom(self, cond): # noqa: C901, N802 elif self.Name == 'weibull': Random = stats.weibull_min.rvs(c=par[1], scale=par[0]) # noqa: N806 - return Random + return Random # noqa: DOC201, RUF100 diff --git a/modules/systemPerformance/REWET/REWET/Damage.py b/modules/systemPerformance/REWET/REWET/Damage.py index 6d6de2112..00e58c304 100644 --- a/modules/systemPerformance/REWET/REWET/Damage.py +++ b/modules/systemPerformance/REWET/REWET/Damage.py @@ -75,7 +75,7 @@ def readDamageFromPickleFile( # noqa: N802 Returns ------- - """ # noqa: D205, D400, D401, D404, D414 + """ # noqa: D205, D400, D401, D404, D414, DOC202, RUF100 with open(pickle_file_name, 'rb') as pckf: # noqa: PTH123 w = pickle.load(pckf) # noqa: S301 @@ -313,7 +313,7 @@ def applyNodalDamage(self, WaterNetwork, current_time): # noqa: C901, N802, N80 ------- None. - """ # noqa: D400 + """ # noqa: D400, DOC202, RUF100 if self.node_damage.empty: print('no node damage at all') # noqa: T201 return @@ -1078,7 +1078,7 @@ def sortEarthquakeListTimely(self): # noqa: N802 ------- None. - """ # noqa: D400, D401, D404 + """ # noqa: D400, D401, D404, DOC202, RUF100 self._earthquake.sort_index() self.is_timely_sorted = True @@ -1097,7 +1097,7 @@ def predictDamage(self, wn, iClear=False): # noqa: FBT002, N802, N803 ------- None. - """ # noqa: D401, D404 + """ # noqa: D401, D404, DOC202, RUF100 if iClear: self.pipe_leak = pd.Series() self.pipe_break = pd.Series() diff --git a/modules/systemPerformance/REWET/REWET/EnhancedWNTR/epanet/io.py b/modules/systemPerformance/REWET/REWET/EnhancedWNTR/epanet/io.py index 9dc65708e..c9fef211c 100644 --- a/modules/systemPerformance/REWET/REWET/EnhancedWNTR/epanet/io.py +++ b/modules/systemPerformance/REWET/REWET/EnhancedWNTR/epanet/io.py @@ -3985,7 +3985,7 @@ def contains_section(self, sec): """ # noqa: D205 try: self.get_section(sec) - return True # noqa: TRY300 + return True # noqa: DOC201, RUF100, TRY300 except NoSectionError: return False @@ -4345,4 +4345,4 @@ def _diff_inp_files( # noqa: C901 g.write(html_diff) g.close() - return n + return n # noqa: DOC201, RUF100 diff --git a/modules/systemPerformance/REWET/REWET/EnhancedWNTR/network/model.py b/modules/systemPerformance/REWET/REWET/EnhancedWNTR/network/model.py index 10d48d8e3..ec54f7220 100644 --- a/modules/systemPerformance/REWET/REWET/EnhancedWNTR/network/model.py +++ b/modules/systemPerformance/REWET/REWET/EnhancedWNTR/network/model.py @@ -75,7 +75,7 @@ def updateWaterNetworkModelWithResult( # noqa: C901, N802 ------- None. - """ # noqa: D205, D401 + """ # noqa: D205, D401, DOC202, RUF100 max_time = result.node['head'].index.max() if latest_simulation_time == None: # noqa: E711 latest_simulation_time = max_time diff --git a/modules/systemPerformance/REWET/REWET/EnhancedWNTR/sim/epanet.py b/modules/systemPerformance/REWET/REWET/EnhancedWNTR/sim/epanet.py index 49008fad1..e9d529c3b 100644 --- a/modules/systemPerformance/REWET/REWET/EnhancedWNTR/sim/epanet.py +++ b/modules/systemPerformance/REWET/REWET/EnhancedWNTR/sim/epanet.py @@ -229,7 +229,7 @@ def run_sim( # noqa: C901 if run_successful: break - return result_data, run_successful + return result_data, run_successful # noqa: DOC201, RUF100 def _updateResultStartTime(self, result_data, start_time): # noqa: N802 for res_type, res in result_data.link.items(): # noqa: B007, PERF102 @@ -379,7 +379,7 @@ def _initialize_internal_graph(self): # noqa: C901 self._node_pairs_with_multiple_links = OrderedDict() for from_node_id, to_node_id in n_links.keys(): # noqa: SIM118 - if n_links[(from_node_id, to_node_id)] > 1: + if n_links[(from_node_id, to_node_id)] > 1: # noqa: RUF031, RUF100 if ( to_node_id, from_node_id, @@ -390,7 +390,7 @@ def _initialize_internal_graph(self): # noqa: C901 from_node_name = self._node_id_to_name[from_node_id] to_node_name = self._node_id_to_name[to_node_id] tmp_list = self._node_pairs_with_multiple_links[ - (from_node_id, to_node_id) + (from_node_id, to_node_id) # noqa: RUF031, RUF100 ] = [] for link_name in self._wn.get_links_for_node(from_node_name): link = self._wn.get_link(link_name) diff --git a/modules/systemPerformance/REWET/REWET/EnhancedWNTR/sim/io.py b/modules/systemPerformance/REWET/REWET/EnhancedWNTR/sim/io.py index d1d29a13a..0422e1318 100644 --- a/modules/systemPerformance/REWET/REWET/EnhancedWNTR/sim/io.py +++ b/modules/systemPerformance/REWET/REWET/EnhancedWNTR/sim/io.py @@ -131,7 +131,7 @@ def _is_number(s): """ # noqa: D400, D401 try: float(s) - return True # noqa: TRY300 + return True # noqa: DOC201, RUF100, TRY300 except ValueError: return False diff --git a/modules/systemPerformance/REWET/REWET/Input/Policy_IO.py b/modules/systemPerformance/REWET/REWET/Input/Policy_IO.py index 36176a055..68935d5a0 100644 --- a/modules/systemPerformance/REWET/REWET/Input/Policy_IO.py +++ b/modules/systemPerformance/REWET/REWET/Input/Policy_IO.py @@ -67,7 +67,7 @@ def __init__(self, definition_file_name): ------- None. - """ # noqa: D400 + """ # noqa: D400, DOC202, RUF100 # some of the following lines have been adopted from WNTR self.rm = restoration_data() @@ -230,7 +230,7 @@ def _read_entities(self): # noqa: C901 ------- None. - """ # noqa: D205, D401 + """ # noqa: D205, D401, DOC202, RUF100 # Entities is kept for legacy compatibility with the first version damage_group_data = self.sections.get( '[ENTITIES]', self.sections.get('[Damage Group]') diff --git a/modules/systemPerformance/REWET/REWET/Output/GUI_Curve_API.py b/modules/systemPerformance/REWET/REWET/Output/GUI_Curve_API.py index 549c86b0c..85c68db92 100644 --- a/modules/systemPerformance/REWET/REWET/Output/GUI_Curve_API.py +++ b/modules/systemPerformance/REWET/REWET/Output/GUI_Curve_API.py @@ -72,7 +72,7 @@ def QNExceedanceCurve(pr, percentage_list, time_type, time_shift=0): # noqa: N8 raise ValueError('Uknown time_type: ' + repr(time_type)) res[percentage] = temp_res - return res + return res # noqa: DOC201, RUF100 def DLExceedanceCurve(pr, percentage_list, time_type, time_shift=0): # noqa: N802 @@ -123,4 +123,4 @@ def DLExceedanceCurve(pr, percentage_list, time_type, time_shift=0): # noqa: N8 raise ValueError('Uknown time_type: ' + repr(time_type)) res[percentage] = temp_res - return res + return res # noqa: DOC201, RUF100 diff --git a/modules/systemPerformance/REWET/REWET/initial.py b/modules/systemPerformance/REWET/REWET/initial.py index 637d4afa1..06af15b3a 100644 --- a/modules/systemPerformance/REWET/REWET/initial.py +++ b/modules/systemPerformance/REWET/REWET/initial.py @@ -46,7 +46,7 @@ def run(self, project_file=None): # noqa: C901 ------- None. - """ # noqa: D205, D401 + """ # noqa: D205, D401, DOC202, RUF100 settings = Settings() if project_file is not None: project_file = str(project_file) diff --git a/modules/systemPerformance/REWET/REWET/restoration/base.py b/modules/systemPerformance/REWET/REWET/restoration/base.py index aeaa77622..c9cac8ac6 100644 --- a/modules/systemPerformance/REWET/REWET/restoration/base.py +++ b/modules/systemPerformance/REWET/REWET/restoration/base.py @@ -232,7 +232,7 @@ def addAgent(self, agent_name, agent_type, definition): # noqa: N802 ------- None. - """ # noqa: D400, D401 + """ # noqa: D400, D401, DOC202, RUF100 # number_of_agents = int(definition['Number']) agent_speed = self.registry.settings['crew_travel_speed'] temp_agent_data = AgentData( @@ -270,7 +270,7 @@ def setActiveAgents(self, active_agent_ID_list): # noqa: N802, N803 ------- None. - """ # noqa: D400 + """ # noqa: D400, DOC202, RUF100 for active_agent_ID in active_agent_ID_list: # noqa: N806 self._agents['active'].loc[active_agent_ID] = True @@ -600,7 +600,7 @@ def addShift(self, name, beginning, ending): # noqa: N802 ------- None. - """ # noqa: D400, D401 + """ # noqa: D400, D401, DOC202, RUF100 if name in self._shift_data: raise ValueError('Shift name already registered') # noqa: EM101, TRY003 if type(beginning) != int and type(beginning) != float: # noqa: E721 @@ -673,7 +673,7 @@ def assignShiftToAgent(self, agent_ID, shift_name): # noqa: N802, N803 ------- None. - """ # noqa: D400, D401 + """ # noqa: D400, D401, DOC202, RUF100 if agent_ID in self._all_agent_shift_data: raise ValueError('The agent ID currently in Agent ALl Shifts') # noqa: EM101, TRY003 if shift_name not in self._shift_data: diff --git a/modules/systemPerformance/REWET/REWET/restoration/io.py b/modules/systemPerformance/REWET/REWET/restoration/io.py index 93ea12387..ce6e932da 100644 --- a/modules/systemPerformance/REWET/REWET/restoration/io.py +++ b/modules/systemPerformance/REWET/REWET/restoration/io.py @@ -44,7 +44,7 @@ def __init__(self, restoration_model, definition_file_name): ------- None. - """ # noqa: D400 + """ # noqa: D400, DOC202, RUF100 # some of the following lines have been adopted from WNTR self.rm = restoration_model self.crew_data = {} @@ -1180,7 +1180,7 @@ def _read_config(self): ------- None. - """ # noqa: D205, D400, D401 + """ # noqa: D205, D400, D401, DOC202, RUF100 edata = OrderedDict() self._crew_file_name = [] self._crew_file_type = [] diff --git a/modules/systemPerformance/REWET/REWET/restoration/model.py b/modules/systemPerformance/REWET/REWET/restoration/model.py index b5d631b19..3f92bf261 100644 --- a/modules/systemPerformance/REWET/REWET/restoration/model.py +++ b/modules/systemPerformance/REWET/REWET/restoration/model.py @@ -907,7 +907,7 @@ def updateShifiting(self, time): # noqa: N802 ------- None. - """ # noqa: D400, D401 + """ # noqa: D400, D401, DOC202, RUF100 if type(time) != int and type(time) != float: # noqa: E721 raise ValueError('Time must be integer not ' + str(type(time))) time = int(time) diff --git a/modules/systemPerformance/REWET/REWET/restoration/registry.py b/modules/systemPerformance/REWET/REWET/restoration/registry.py index 7e0c87119..38037c5b8 100644 --- a/modules/systemPerformance/REWET/REWET/restoration/registry.py +++ b/modules/systemPerformance/REWET/REWET/restoration/registry.py @@ -515,7 +515,7 @@ def addPipeDamageToRegistry(self, node_name, data): # noqa: N802 ------- None. - """ # noqa: D400, D401 + """ # noqa: D400, D401, DOC202, RUF100 # self._pipe_node_damage_status[name] = data leaking_pipe_with_pipeA_orginal_pipe = self._pipe_leak_history[ # noqa: N806 @@ -1280,7 +1280,7 @@ def occupyNode(self, node_name, occupier_name): # noqa: N802 ------- None. - """ # noqa: D400 + """ # noqa: D400, DOC202, RUF100 if occupier_name in self._occupancy: # if not iNodeCoupled(node_name): raise ValueError( # noqa: TRY003 @@ -1307,7 +1307,7 @@ def removeOccupancy(self, occupier_name): # noqa: N802 ------- None. - """ # noqa: D401 + """ # noqa: D401, DOC202, RUF100 temp = self._occupancy[self._occupancy == occupier_name] if len(temp) == 0: @@ -1350,7 +1350,7 @@ def whereIsOccupiedByName(self, occupier_name): # noqa: N802 str or series node(s) ID. - """ # noqa: D400, D401 + """ # noqa: D400, D401, DOC202, RUF100 temp = self._occupancy[self._occupancy == occupier_name] if len(temp) == 0: raise ValueError('there is no occupancy with this name') # noqa: EM101, TRY003 @@ -1387,7 +1387,7 @@ def coupleTwoBreakNodes(self, break_point_1_name, break_point_2_name): # noqa: ------- None. - """ # noqa: D205 + """ # noqa: D205, DOC202, RUF100 self._pipe_break_node_coupling[break_point_1_name] = break_point_2_name self._pipe_break_node_coupling[break_point_2_name] = break_point_1_name self._break_point_attached_to_mainPipe.append(break_point_1_name) diff --git a/modules/systemPerformance/REWET/REWET/timeline.py b/modules/systemPerformance/REWET/REWET/timeline.py index 4e6ff0923..fa1a875ab 100644 --- a/modules/systemPerformance/REWET/REWET/timeline.py +++ b/modules/systemPerformance/REWET/REWET/timeline.py @@ -143,7 +143,7 @@ def addEventTime(self, event_distinct_time, event_type='dmg'): # noqa: N802 ------- None. - """ # noqa: D205, D401, D404 + """ # noqa: D205, D401, D404, DOC202, RUF100 if type(event_distinct_time) != pd.core.series.Series: # noqa: E721 if ( type(event_distinct_time) == numpy.float64 # noqa: E721 @@ -218,7 +218,7 @@ def checkAndAmendTime(self): # noqa: N802 ------- None. - """ # noqa: D205, D401 + """ # noqa: D205, D401, DOC202, RUF100 first_length = len(self._event_time_register.index) self._event_time_register = self._event_time_register[ self._event_time_register.index <= self._simulation_end_time diff --git a/modules/systemPerformance/REWET/preprocessorIO.py b/modules/systemPerformance/REWET/preprocessorIO.py index 3b7d0c9a7..10f291d48 100644 --- a/modules/systemPerformance/REWET/preprocessorIO.py +++ b/modules/systemPerformance/REWET/preprocessorIO.py @@ -187,7 +187,7 @@ def save_scenario_table(scenario_table, scenario_table_file_path): ------- None. - """ # noqa: D205, D400, D401 + """ # noqa: D205, D400, D401, DOC202, RUF100 if isinstance(scenario_table, pd.core.frame.DataFrame): pass elif isinstance(scenario_table, list): diff --git a/pyproject.toml b/pyproject.toml index 43fede178..29ad35b40 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,6 +7,9 @@ select = ["ALL"] ignore = ["ANN", "D211", "D212", "Q000", "Q003", "COM812", "D203", "ISC001", "E501", "ERA001", "PGH003", "FIX002", "TD003", "S101", "N801", "S311", "G004", "SIM102", "SIM108", "NPY002", "F401"] preview = false +[tool.ruff.lint.per-file-ignores] +"path/to/folder/*" = ["ALL"] + [tool.ruff.lint.pydocstyle] convention = "numpy"