Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
124 commits
Select commit Hold shift + click to select a range
3cb7b20
abs - refactoring
bsaakash Nov 25, 2024
324f31b
abs - refactoring one stage of tmcmc to allow other strategies
bsaakash Nov 25, 2024
7d43802
abs - removing redundant print statement
bsaakash Jan 6, 2025
041afc1
Merge remote-tracking branch 'upstream/master'
bsaakash Jan 6, 2025
340f19e
abs - pythonic improvements to UCSD_UQ engine script
bsaakash Jan 29, 2025
b2dcb26
abs - updating mainscript to support surrogate-aided Bayesian calibra…
bsaakash Jan 29, 2025
deb4cfa
abs - updating datamodels to expect the same keys as TMCMC without ap…
bsaakash Jan 29, 2025
c310483
abs - updates to support python3.9
bsaakash Jan 29, 2025
632b2af
abs - updates to GP-AB mainscript to fit into the simcenter workflow
bsaakash Jan 29, 2025
51a88ae
Merge pull request #7 from NHERI-SimCenter/master
bsaakash Jan 29, 2025
8b602fe
Merge pull request #8 from NHERI-SimCenter/master
bsaakash Jan 30, 2025
26ec828
Merge remote-tracking branch 'upstream/master'
bsaakash Jan 30, 2025
1eac3d3
Merge remote-tracking branch 'refs/remotes/origin/master'
bsaakash Jan 30, 2025
ed45cc7
Merge remote-tracking branch 'upstream/master'
bsaakash Mar 11, 2025
91ecf33
abs - using full path to input json file
bsaakash Mar 17, 2025
d647a22
abs - assessing convergence after first iteration
bsaakash Mar 17, 2025
6bac51e
abs - renaming function for running one stage of original tmcmc
bsaakash Mar 17, 2025
1769404
abs - fixing call to attributes of gp and pca objects
bsaakash Apr 1, 2025
7972c80
abs - fixing calculation of imse
bsaakash Apr 1, 2025
d0e6d62
abs - using tmcmc resutls dict keys explicitly
bsaakash Apr 1, 2025
c642b4c
abs - updating calls to other objects used in the algorithm
bsaakash Apr 1, 2025
9493e02
abs - updating the function signatures
bsaakash Apr 1, 2025
d5d175d
Merge remote-tracking branch 'upstream/master'
bsaakash Apr 1, 2025
9aa7fb2
abs - adding an argument to gp fit method to handle cases when gp rec…
bsaakash Apr 1, 2025
5b9d772
abs - using marginal log-likelihood of the model parameters only
bsaakash Apr 7, 2025
ee980a6
abs - using stage_num consistently when warm-starting is possible. Us…
bsaakash Apr 7, 2025
08d987a
abs - using constant and linear terms in the basis function for the m…
bsaakash Apr 7, 2025
c6ef494
abs - fixing warm start stage calculation return value
bsaakash Apr 7, 2025
88e24c2
abs - setting num_samples_per_stage, fixing log_like and log_prior
bsaakash Apr 7, 2025
42289b9
abs - using prior_log_pdf
bsaakash Apr 7, 2025
1b08cc5
abs - serializing results to json file
bsaakash Apr 7, 2025
07c371d
abs - using pdf values instead of logpdf
bsaakash Apr 8, 2025
5199c8f
abs - explicitly defining current and previous log likelihood approxi…
bsaakash Apr 8, 2025
829af49
abs - writing results to file, creating new workdirs per simulation o…
bsaakash Apr 8, 2025
950529b
abs - tracking the model parameters and the normalized samples in tmcmc
bsaakash Apr 9, 2025
2447c31
abs - updating pca class, separating the fit and project methods, sca…
bsaakash Apr 11, 2025
1de66ee
abs - renaming the gp fit method
bsaakash Apr 11, 2025
ae18ab1
abs - fixing the gkl calculation code
bsaakash Apr 11, 2025
c56cf8b
abs - writing more outputs to file, using scaling of outputs in pca
bsaakash Apr 11, 2025
c6af097
Merge remote-tracking branch 'upstream/master'
bsaakash Apr 11, 2025
01cfb5e
abs - fixing loocv nrmse calculation
bsaakash Apr 11, 2025
d0ee247
abs - getting prior variances, changing loocv to gcv
bsaakash Apr 11, 2025
63314dc
abs - updating the gmap calculation
bsaakash Apr 11, 2025
674a53d
abs - getting the prior variances from the join distribution object
bsaakash Apr 11, 2025
c60623f
abs - saving outputs optionally
bsaakash Apr 11, 2025
bd9162a
abs - reorganizing the code
bsaakash Apr 11, 2025
57d64d6
abs - saving number of tmcmc stages
bsaakash Apr 11, 2025
6531bc1
abs - support for edge case with one data point
bsaakash Apr 12, 2025
bf8d312
abs - fixing the weighted hyperparameter calculation, supporting mse …
bsaakash Apr 12, 2025
5717b4f
abs - updates for adaptive doe
bsaakash Apr 12, 2025
8f38bef
abs - safer calculation of cholesky decomposition for use in tmcmc
bsaakash Apr 12, 2025
3dcad08
abs - safer cholesky decomposition calculation
bsaakash Apr 12, 2025
afb2fe8
abs - using precomputed values from gpy in the woodbury formula for l…
bsaakash Apr 14, 2025
66ea0b2
abs - faster log-likelihood calculation
bsaakash Apr 14, 2025
4503e9d
abs - writing tabular data files
bsaakash Apr 15, 2025
ef47b4a
abs - updating space filling doe
bsaakash Apr 15, 2025
0aefab8
abs - removing the redundant domain variable
bsaakash Apr 15, 2025
bd1ec77
abs - adding kde calculation
bsaakash Apr 15, 2025
58f0464
abs - using mse_w and providing weights in function call
bsaakash Apr 18, 2025
da35456
abs - calculating target density inside the tmcmc
bsaakash Apr 18, 2025
2d49622
abs - renaming variables for clarity
bsaakash Apr 18, 2025
aeac5b0
abs - updating convergence metric calculations
bsaakash Apr 18, 2025
1f8348d
abs - renaming updated function
bsaakash Apr 18, 2025
1045e4b
abs - adapting the exploitation proportion
bsaakash Apr 22, 2025
85da02e
abs -safer proposal covariance calculation
bsaakash Apr 22, 2025
c8572f9
abs - fixing kl divergence calculation in log space, starting with ex…
bsaakash Apr 22, 2025
fa192aa
abs - initializing new training points as empty arrays
bsaakash Apr 22, 2025
8c02146
abs - using samples from intermediate stages, calculating weights usi…
bsaakash Apr 22, 2025
e538da3
abs - normalizing weights, recording number of candidate training poi…
bsaakash Apr 22, 2025
8401b0e
abs - normalizing weights
bsaakash Apr 22, 2025
d15f609
abs - fixing max calculation
bsaakash Apr 22, 2025
d3ac6a9
abs - parallelizing tmcmc
bsaakash Apr 23, 2025
d726e3e
abs - saving number of model evaluations in tmcmc
bsaakash Apr 23, 2025
9c0d566
abs - disabling logging
bsaakash Apr 23, 2025
aeb48ee
abs - improving logging, parallelization
bsaakash Apr 23, 2025
afd9ef1
abs - refactoring loglikelihood
bsaakash Apr 23, 2025
79fc2ea
abs - logging acceptance rates
bsaakash Apr 24, 2025
6ae6d91
abs - logging improvements in tmcmc, iterative refinement of gp
bsaakash Apr 29, 2025
4138cfa
abs - normalizing weights
bsaakash Apr 30, 2025
7450253
abs - adding functionality for configuring inputs
bsaakash May 8, 2025
db5b0dd
abs - adding common functionality for logging
bsaakash May 8, 2025
54fdcf3
abs - improving gp model creation, adding more options to gp model
bsaakash May 8, 2025
4744147
abs - unifying logging
bsaakash May 8, 2025
e8c799b
abs - logging improvements
bsaakash May 12, 2025
88c218b
abs - handling nugget options
bsaakash May 12, 2025
dbab464
abs - trying new logging
bsaakash May 12, 2025
b0a39ff
abs - incorporating logging
bsaakash May 12, 2025
04ca093
abs - incorporating logging
bsaakash May 12, 2025
a91bca9
abs - using empty arrays
bsaakash May 12, 2025
68bd7a9
abs - adding more logging helpers
bsaakash May 12, 2025
5975315
abs - refactoring the main algorithm body into smaller methods
bsaakash May 12, 2025
08222b9
abs - decorator for uniform logging
bsaakash May 12, 2025
1811139
abs - adding loglikehood functions script
bsaakash May 15, 2025
9711698
abs - adding methods to log simple messages
bsaakash May 15, 2025
1a672bc
abs - propagating logging
bsaakash May 15, 2025
8c2ff33
abs- trying a new NamedAdditive class to overcome copy() error in gpy
bsaakash May 15, 2025
a66c61e
abs - always using spawn method instead of fork in multiprocessing fo…
bsaakash May 15, 2025
c09826a
abs - logging improvements in tmcmc
bsaakash May 18, 2025
03eacee
abs - logging improvements
bsaakash May 18, 2025
6ea6524
abs - logging refinement, using sklearn to handle mean instead of gpy…
bsaakash May 18, 2025
079e0a5
abs - updates
bsaakash May 18, 2025
79cff5d
abs - minor logging improvements
bsaakash May 18, 2025
dc8a629
abs - using no symbol in logfile
bsaakash May 21, 2025
97ddfbc
abs - adapting proposal scale
bsaakash May 21, 2025
f52685a
abs - using scale factor
bsaakash May 21, 2025
1a0ea32
abs - removing unused code
bsaakash May 22, 2025
dee7c25
Merge remote-tracking branch 'upstream/master'
bsaakash May 22, 2025
ec8e583
abs - refactoring to have pca inside gp
bsaakash May 22, 2025
259bf6e
abs - refactoring run method
bsaakash May 26, 2025
1b5cfd1
abs - aborting mpi run quickly when error
bsaakash Jun 17, 2025
8a193f9
abs - cleaning up
bsaakash Jun 17, 2025
91215ec
abs - updating gp model
bsaakash Jun 17, 2025
7478a5a
abs - minor fixes to comments
bsaakash Jun 17, 2025
0bdc28a
abs - improvements to parallel runner
bsaakash Jun 17, 2025
070a279
abs - propagating run type for remote run
bsaakash Jun 17, 2025
adfe2cd
abs - ending mpi jobs after run
bsaakash Jun 17, 2025
2541aec
abs - writing error message to .err file
bsaakash Jun 17, 2025
db0942d
abs - improved processing of calibration data files
bsaakash Jun 26, 2025
85fb478
abs - better error message propagation
bsaakash Jun 27, 2025
e2db1aa
abs - alternative opensees build
bsaakash Jun 27, 2025
b17f4ee
abs - commenting out nataf for now
bsaakash Jul 2, 2025
a7dfb35
Merge remote-tracking branch 'upstream/master'
bsaakash Jul 2, 2025
a633c9f
abs - more consistent reshaping of inputs and outputs
bsaakash Jul 3, 2025
a636aff
abs - reverting change
bsaakash Jul 7, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions modules/performFEM/OpenSees/createOpenSeesDriver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@ int main(int argc, const char **argv) {

dpreproCommand = remoteDir + std::string("/applications/performUQ/templateSub/simCenterSub");
openSeesCommand = std::string("/home1/00477/tg457427/bin/OpenSees");
// openSeesCommand = std::string("/opt/apps/intel24/impi21/opensees/3.7.1/bin/OpenSees");
pythonCommand = std::string("python3");

}
Expand Down
19 changes: 10 additions & 9 deletions modules/performUQ/UCSD_UQ/UCSD_UQ.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,27 +30,28 @@ def main(args): # noqa: D103
else:
pythonCommand = 'python3' # noqa: N806

mainScriptDir = os.path.dirname(os.path.realpath(__file__)) # noqa: PTH120, N806
mainScript = os.path.join(mainScriptDir, 'mainscript.py') # noqa: PTH118, N806
templateDir = os.getcwd() # noqa: PTH109, N806
tmpSimCenterDir = str(Path(templateDir).parents[0]) # noqa: N806

# Change permission of driver file
os.chmod(driverFile, stat.S_IXUSR | stat.S_IRUSR | stat.S_IXOTH) # noqa: PTH101
st = os.stat(driverFile) # noqa: PTH116
os.chmod(driverFile, st.st_mode | stat.S_IEXEC) # noqa: PTH101
driverFile = './' + driverFile # noqa: N806
print('WORKFLOW: ' + driverFile) # noqa: T201

template_dir = Path.cwd()
tmp_simcenter_dir = template_dir.parent

main_script_dir = Path(__file__).parent
main_script = main_script_dir / 'mainscript.py'

command = (
f'"{pythonCommand}" "{mainScript}" "{tmpSimCenterDir}"'
f' "{templateDir}" {runType} {driverFile} {workflowInput}'
f'"{pythonCommand}" "{main_script!s}" "{tmp_simcenter_dir!s}"'
f' "{template_dir!s}" {runType} {driverFile} {workflowInput}'
)

print(command) # noqa: T201

command_list = shlex.split(command)

err_file = Path(tmpSimCenterDir) / 'UCSD_UQ.err'
err_file = tmp_simcenter_dir / 'UCSD_UQ.err'
err_file.touch()

try:
Expand Down
172 changes: 115 additions & 57 deletions modules/performUQ/UCSD_UQ/mainscript.py
Original file line number Diff line number Diff line change
@@ -1,81 +1,139 @@
"""authors: Mukesh Kumar Ramancha, Maitreya Manoj Kurumbhati, Prof. J.P. Conte, Aakash Bangalore Satish*
affiliation: University of California, San Diego, *SimCenter, University of California, Berkeley

""" # noqa: INP001, D205, D400

# ======================================================================================================================
"""
module: mainscript.py.

This script executes an uncertainty quantification (UQ) analysis based on an input JSON file.
It dynamically selects the appropriate UQ method in the UCSD_UQ engine and executes the corresponding script.

### Functionality:
- Adds the `common` directory to `sys.path` to allow importing necessary modules.
- Parses command-line arguments for necessary paths and parameters.
- Reads and validates the JSON input file.
- Determines the appropriate UQ script to run based on `uqType` and `useApproximation` flags.
- Constructs the command and executes the selected script.
- Captures errors and logs them to `UCSD_UQ.err`.

### Usage:
```sh
python script.py /path/to/working /path/to/template runningLocal driver input.json
```

### Arguments:
1. `working_dir` (Path): Path to the working directory where computations are performed.
2. `template_dir` (Path): Path to the template directory containing the input JSON file.
3. `run_type` (str): Execution mode (`runningLocal` or `runningRemote`).
4. `driver_file` (str): Name of the driver file.
5. `input_file` (Path): Name of the JSON input file.

### Error Handling:
- If an invalid JSON file is provided, the script exits with an error.
- If an unknown UQ type is encountered, the script exits with an error.
- If an exception occurs during execution, the error is logged in `UCSD_UQ.err`.

"""

import argparse
import json
import shlex
import sys
import traceback
from pathlib import Path

path_to_common_uq = Path(__file__).parent.parent / 'common'
sys.path.append(str(path_to_common_uq))
# Dynamically add 'common' directory to sys.path
path_to_common_uq = Path(__file__).resolve().parent.parent / 'common'
if path_to_common_uq not in sys.path:
sys.path.insert(0, str(path_to_common_uq))


# ======================================================================================================================
def main(input_args): # noqa: D103
# # Initialize analysis
# path_to_UCSD_UQ_directory = Path(input_args[2]).resolve().parent
# path_to_working_directory = Path(input_args[3]).resolve()
# path_to_template_directory = Path(input_args[4]).resolve()
# run_type = input_args[5] # either "runningLocal" or "runningRemote"
# driver_file_name = input_args[6]
# input_file_name = input_args[7]
def parse_args():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(description='Run UQ analysis.')
parser.add_argument('working_dir', type=Path, help='Path to working directory')
parser.add_argument('template_dir', type=Path, help='Path to template directory')
parser.add_argument(
'run_type', choices=['runningLocal', 'runningRemote'], help='Run type'
)
parser.add_argument('driver_file', help='Driver file name')
parser.add_argument('input_file', type=Path, help='Input JSON file')
return parser.parse_args()


# Initialize analysis
path_to_UCSD_UQ_directory = Path(input_args[0]).resolve().parent # noqa: N806, F841
path_to_working_directory = Path(input_args[1]).resolve()
path_to_template_directory = Path(input_args[2]).resolve()
run_type = input_args[3] # either "runningLocal" or "runningRemote"
driver_file_name = input_args[4]
input_file_name = input_args[5]
def load_json(file_path):
"""Load and validate JSON input."""
try:
with file_path.open(encoding='utf-8') as f:
data = json.load(f)
except json.JSONDecodeError as e:
sys.stderr.write(f'ERROR: Invalid JSON format in {file_path}:\n{e}\n')
sys.exit(1)

Path('dakotaTab.out').unlink(missing_ok=True)
Path('dakotaTabPrior.out').unlink(missing_ok=True)
if 'UQ' not in data:
sys.stderr.write(f"ERROR: Missing 'UQ' key in input JSON: {file_path}\n")
sys.exit(1)

input_file_full_path = path_to_template_directory / input_file_name
return data

with open(input_file_full_path, encoding='utf-8') as f: # noqa: PTH123
inputs = json.load(f)

uq_inputs = inputs['UQ']
if uq_inputs['uqType'] == 'Metropolis Within Gibbs Sampler':
import mainscript_hierarchical_bayesian
def select_uq_script(uq_inputs):
"""Determine which UQ script to run."""
uq_methods = {
'Metropolis Within Gibbs Sampler': 'mainscript_hierarchical_bayesian',
}

main_function = mainscript_hierarchical_bayesian.main
else:
import mainscript_tmcmc
module_name = uq_methods.get(uq_inputs['uqType'], 'mainscript_tmcmc')
if uq_inputs.get('useApproximation'):
module_name = 'gp_ab_algorithm'

main_function = mainscript_tmcmc.main
try:
module = __import__(module_name)
except ImportError:
sys.stderr.write(
f'ERROR: Could not import {module_name}. Ensure the script exists.\n'
)
sys.exit(1)

command = (
f'"{path_to_working_directory}" "{path_to_template_directory}" '
f'{run_type} "{driver_file_name}" "{input_file_full_path}"'
)
command_list = shlex.split(command)
return module.main

# Check if 'UCSD_UQ.err' exists, and create it if not
err_file = path_to_working_directory / 'UCSD_UQ.err'

if not err_file.exists():
err_file.touch() # Create the file
def main():
"""Run UQ analysis."""
args = parse_args()

# Ensure output error file exists
err_file = args.working_dir / 'UCSD_UQ.err'
err_file.touch(exist_ok=True)

# Remove any previous output files
(args.working_dir / 'dakotaTab.out').unlink(missing_ok=True)
(args.working_dir / 'dakotaTabPrior.out').unlink(missing_ok=True)

# Load JSON input file
inputs = load_json(args.template_dir / args.input_file)
uq_inputs = inputs['UQ']

# Select the appropriate UQ script
main_function = select_uq_script(uq_inputs)

# Construct the command
command = [
str(args.working_dir),
str(args.template_dir),
args.run_type,
args.driver_file,
str(args.template_dir / args.input_file),
]

# Try running the main_function and catch any exceptions
try:
main_function(command_list)
except Exception: # noqa: BLE001
# Write the exception message to the .err file
main_function(command)
except Exception:
err_msg = f'ERROR: An exception occurred:\n{traceback.format_exc()}\n'
with err_file.open('a') as f:
f.write('ERROR: An exception occurred:\n')
f.write(f'{traceback.format_exc()}\n')
f.write(err_msg)
sys.stderr.write(err_msg)

if args.run_type == 'runningRemote':
from mpi4py import MPI

# ======================================================================================================================
MPI.COMM_WORLD.Abort(1)

if __name__ == '__main__':
input_args = sys.argv
main(input_args)

# ======================================================================================================================
if __name__ == '__main__':
main()
7 changes: 6 additions & 1 deletion modules/performUQ/common/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,9 @@ simcenter_add_python_script(SCRIPT gp_ab_algorithm.py)
simcenter_add_python_script(SCRIPT gp_model.py)
simcenter_add_python_script(SCRIPT principal_component_analysis.py)
simcenter_add_python_script(SCRIPT space_filling_doe.py)
simcenter_add_python_script(SCRIPT tmcmc.py)
simcenter_add_python_script(SCRIPT tmcmc.py)
simcenter_add_python_script(SCRIPT safer_cholesky.py)
simcenter_add_python_script(SCRIPT kernel_density_estimation.py)
simcenter_add_python_script(SCRIPT config_utilities.py)
simcenter_add_python_script(SCRIPT logging_utilities.py)
simcenter_add_python_script(SCRIPT log_likelihood_functions.py)
Loading
Loading