API 参考 - 工具函数 (Utilities)¶
工具函数 (Utilities)
工具函数 (Utilities) 提供了一系列用于配置处理、文件操作、日志记录和数据库交互的辅助函数。 请在下方的标签页中选择您感兴趣的特定模块。
Configuration utility functions for tricys.
analysis_prepare_config(config_path)
¶
Loads, validates, and prepares the configuration from the given path.
Source code in tricys/utils/config_utils.py
analysis_setup_analysis_cases_workspaces(config)
¶
Set up independent working directories and configuration files for multiple analysis_cases
This function will: 1. Create independent working directories for each analysis_case in the current working directory 2. Convert relative paths in the original configuration to absolute paths 3. Convert analysis_cases format to standard analysis_case format 4. Generate independent config.json files for each case
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Dict[str, Any]
|
Original configuration dictionary containing analysis_cases |
required |
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List containing information for each case, each element contains: |
List[Dict[str, Any]]
|
|
List[Dict[str, Any]]
|
|
List[Dict[str, Any]]
|
|
List[Dict[str, Any]]
|
|
List[Dict[str, Any]]
|
|
Source code in tricys/utils/config_utils.py
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 | |
analysis_validate_analysis_cases_config(config)
¶
Validates analysis_cases configuration format supporting both list and single object.
This function validates: 1. Basic structure and required fields of analysis_cases 2. Simulation parameters compatibility (single job requirement) 3. Required_TBR configuration completeness if used in dependent_variables
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Dict[str, Any]
|
Configuration dictionary to validate. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if configuration is valid, False otherwise. |
Note
Supports both single analysis_case dict or list of cases. Required fields per case: name, independent_variable, independent_variable_sampling. Validates simulation_parameters contain only single job (no sweep). Checks Required_TBR completeness in metrics_definition.
Source code in tricys/utils/config_utils.py
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 | |
analysis_validate_config(config, required_keys=ANALYSIS_REQUIRED_CONFIG_KEYS, parent_key='')
¶
Recursively validates the configuration's structure and values.
Source code in tricys/utils/config_utils.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 | |
basic_prepare_config(config_path)
¶
Loads and prepares the configuration from the given path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
str
|
Path to the JSON configuration file. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Dict[str, Any], Dict[str, Any]]
|
A tuple of (runtime_config, original_config). |
Raises:
| Type | Description |
|---|---|
SystemExit
|
If config file loading/parsing fails or validation fails. |
Note
Converts relative paths to absolute, validates config structure, adds run_timestamp, creates workspace directories, and processes variableFilter for regex escaping. Sets up log_dir, temp_dir, and results_dir within run workspace.
Source code in tricys/utils/config_utils.py
basic_validate_config(config, required_keys=BASIC_REQUIRED_CONFIG_KEYS, parent_key='')
¶
Recursively validates the configuration against required structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Dict[str, Any]
|
Configuration dictionary to validate. |
required |
required_keys
|
Dict
|
Dictionary defining required keys and their expected types. |
BASIC_REQUIRED_CONFIG_KEYS
|
parent_key
|
str
|
Parent key path for nested validation (used internally). |
''
|
Raises:
| Type | Description |
|---|---|
SystemExit
|
If validation fails (exits with code 1). |
Note
Performs structural validation (required keys and types) and value validation (path existence, variableFilter format). Uses regex to validate variableFilter against Modelica identifier patterns. Only validates values on top-level call.
Source code in tricys/utils/config_utils.py
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 | |
check_ai_config(config)
¶
Checks for AI-related environment variables if 'ai: true' is found in the config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Dict[str, Any]
|
The configuration dictionary. |
required |
Raises:
| Type | Description |
|---|---|
SystemExit
|
If AI is enabled in the config but required environment variables are missing. |
Note
If any part of the configuration contains "ai": true, this function verifies
that API_KEY, BASE_URL, and either AI_MODEL or AI_MODELS are set as
environment variables.
Source code in tricys/utils/config_utils.py
convert_relative_paths_to_absolute(config, base_dir)
¶
Recursively converts relative paths to absolute paths in configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Dict[str, Any]
|
Configuration dictionary to process. |
required |
base_dir
|
str
|
Base directory path for resolving relative paths. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Configuration dictionary with converted absolute paths. |
Note
Processes path keys including package_path, db_path, results_dir, temp_dir, log_dir, glossary_path, and any key ending with '_path'. Converts relative paths to absolute using base_dir. Handles nested dictionaries and lists recursively.
Source code in tricys/utils/config_utils.py
Utility functions for file and directory management.
This module provides helper functions for creating unique filenames and managing log file rotation.
archive_run(timestamp)
¶
Archives a run (simulation or analysis) based on its configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timestamp
|
str
|
The timestamp directory name of the run to archive. |
required |
Note
Determines run type (analysis vs simulation) from configuration. Delegates to _archive_run() with appropriate run_type. Extracts configuration from log files using restore_configs_from_log().
Source code in tricys/utils/file_utils.py
get_unique_filename(base_path, filename)
¶
Generates a unique filename by appending a counter if the file already exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_path
|
str
|
The directory path where the file will be saved. |
required |
filename
|
str
|
The desired filename, including the extension. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A unique, non-existing file path. |
Note
Appends _1, _2, etc. before the extension until a non-existing filename is found. Example: if "data.csv" exists, returns "data_1.csv", then "data_2.csv", etc.
Source code in tricys/utils/file_utils.py
unarchive_run(zip_file)
¶
Unarchives a simulation run from a zip file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zip_file
|
str
|
Path to the zip file to extract. |
required |
Raises:
| Type | Description |
|---|---|
SystemExit
|
If zip file not found or extraction fails. |
Note
Extracts to current directory if empty, otherwise creates new directory named after the zip file. Sets up basic logging for the unarchive process. Handles BadZipFile exceptions gracefully.
Source code in tricys/utils/file_utils.py
delete_old_logs(log_path, max_files)
¶
Deletes the oldest log files in a directory to meet a specified limit.
Checks the number of .log files in the given directory and removes the
oldest ones based on modification time until the file count matches the
max_files limit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_path
|
str
|
The path to the directory containing log files. |
required |
max_files
|
int
|
The maximum number of |
required |
Note
Only processes files with .log extension. Sorts by modification time (oldest first) before deletion. Does nothing if current count <= max_files.
Source code in tricys/utils/log_utils.py
log_execution_time(func)
¶
A decorator to log the execution time of a function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
The function to be decorated. |
required |
Returns:
| Type | Description |
|---|---|
Callable
|
The wrapped function that logs execution time. |
Note
Measures execution time using time.perf_counter(). Logs function name, module, and duration in milliseconds. Uses structured logging with extra fields.
Source code in tricys/utils/log_utils.py
restore_configs_from_log(timestamp)
¶
Finds the log file for a given timestamp and restores configurations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timestamp
|
str
|
The timestamp directory name to search for log files. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Dict[str, Any] | None, Dict[str, Any] | None]
|
A tuple of (runtime_config, original_config) or (None, None) if not found. |
Note
Searches in timestamp/simulation_{timestamp}.log and timestamp/log/ directory. Parses JSON log entries to find "Runtime Configuration" and "Original Configuration" messages. Returns parsed configurations as dictionaries.
Source code in tricys/utils/log_utils.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |
setup_logging(config, original_config=None)
¶
Configures the logging module based on the application configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Dict[str, Any]
|
The main configuration dictionary containing logging settings. |
required |
original_config
|
Dict[str, Any]
|
Optional original configuration for additional logging. |
None
|
Note
Sets up JSON formatted logging to console and/or file. Manages log file rotation via delete_old_logs(). Supports main_log_path for analysis cases. Logs both runtime and original configurations in compact JSON format. Clears existing handlers to prevent duplicates.
Source code in tricys/utils/log_utils.py
Utilities for interacting with the simulation parameter SQLite database.
This module provides functions to create, store, update, and retrieve simulation parameter data from a SQLite database file.
create_parameters_table(db_path)
¶
Creates the parameters table in the database if it does not exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
The path to the SQLite database file. |
required |
Raises:
| Type | Description |
|---|---|
Error
|
If a database error occurs during table creation. |
Note
Creates parent directories if they don't exist. Table schema includes: name (TEXT PRIMARY KEY), type, default_value, sweep_values, description, dimensions. Uses CREATE TABLE IF NOT EXISTS for safe repeated calls.
Source code in tricys/utils/sqlite_utils.py
get_parameters_from_db(db_path)
¶
Retrieves parameter details from the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
The path to the SQLite database file. |
required |
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
A list of parameter dictionaries, each containing the name, default_value, |
List[Dict[str, Any]]
|
description, and sweep_values. |
Note
JSON-decodes stored values. Returns empty string for sweep_values if None. Result dict keys: name, default_value, description, sweep_values.
Source code in tricys/utils/sqlite_utils.py
store_parameters_in_db(db_path, params_data)
¶
Stores or replaces a list of parameter details in the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
The path to the SQLite database file. |
required |
params_data
|
List[Dict[str, Any]]
|
A list of dictionaries, where each dictionary contains details for a single parameter. |
required |
Raises:
| Type | Description |
|---|---|
Error
|
If a database error occurs during insertion. |
Note
Uses INSERT OR REPLACE for upsert behavior. JSON-encodes defaultValue and stores dimensions with '()' default. Skips parameters without names. Expected param dict keys: name, type, defaultValue, comment, dimensions.
Source code in tricys/utils/sqlite_utils.py
update_sweep_values_in_db(db_path, param_sweep)
¶
Updates the 'sweep_values' for specified parameters in the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
The path to the SQLite database file. |
required |
param_sweep
|
Dict[str, Any]
|
A dictionary where keys are parameter names and values are the corresponding sweep values (e.g., a list). |
required |
Raises:
| Type | Description |
|---|---|
Error
|
If a database error occurs during the update. |
Note
Converts numpy arrays to lists before JSON encoding. Warns if parameter not found in database. Uses UPDATE statement so parameters must exist before calling this function.