API Reference¶
Complete API documentation for GOLIAT, organized by module category.
Core Modules¶
Core functionality for configuration, logging, and utilities.
Antenna¶
goliat.antenna.Antenna ¶
Manages antenna-specific properties and configurations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Config | The configuration object containing antenna settings. | required |
frequency_mhz | int | The operating frequency in MHz. | required |
Source code in goliat/antenna.py
Functions¶
get_config_for_frequency ¶
Gets the antenna configuration for the current frequency.
Raises:
| Type | Description |
|---|---|
ValueError | If no configuration is defined for the frequency. |
Returns:
| Type | Description |
|---|---|
dict | The antenna configuration dictionary. |
Source code in goliat/antenna.py
get_model_type ¶
get_source_entity_name ¶
get_centered_antenna_path ¶
Constructs the path to the centered .sab antenna file.
If the exact frequency file doesn't exist, finds the nearest available frequency and shows a warning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
centered_antennas_dir | str | The directory for centered antenna files. | required |
Returns:
| Type | Description |
|---|---|
str | The absolute path to the centered antenna model file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError | If no antenna files are found in the directory. |
Source code in goliat/antenna.py
Colors¶
goliat.colors ¶
Functions¶
init_colorama ¶
Initialize colorama with appropriate settings for the current environment.
Preserves ANSI codes when stdout is piped (e.g., in Jupyter notebooks) by checking for JUPYTER_NOTEBOOK or COLORAMA_STRIP environment variables.
Source code in goliat/colors.py
get_color ¶
Returns the colorama color code for a log type, or white if not found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_type | str | Log type key (e.g., 'info', 'warning', 'error'). | required |
Returns:
| Type | Description |
|---|---|
str | Colorama color code string. |
Source code in goliat/colors.py
Data Management¶
goliat.data_extractor ¶
Functions¶
get_parameter_from_json ¶
Extracts a nested value from a JSON file using dot notation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path | str | Path to the JSON file. | required |
json_path | str | Dot-separated path like 'section.subsection.key'. | required |
Returns:
| Type | Description |
|---|---|
Any | The value at the path, or None if not found. |
Source code in goliat/data_extractor.py
get_parameter ¶
Retrieves a parameter from a data source using a config-driven approach.
Supports JSON sources currently. The source_config defines where to look, and context provides values for formatting paths (e.g., project_root).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_config | Dict[str, Any] | Dict with 'source_type', 'file_path_template', 'json_path'. | required |
context | Dict[str, Any] | Values for formatting file paths. | required |
Returns:
| Type | Description |
|---|---|
Any | The retrieved value, or None on error. |
Source code in goliat/data_extractor.py
Logging¶
goliat.logging_manager ¶
Classes¶
ColorFormatter ¶
Bases: Formatter
Custom formatter that colorizes log messages based on log_type.
Applies colorama color codes to messages and caller info based on the log_type attribute (info, warning, error, success, etc.).
Functions¶
format ¶
Adds color codes to log messages based on log_type.
Source code in goliat/logging_manager.py
CustomFormatter ¶
LoggingMixin ¶
A mixin class that provides a standardized logging interface.
Provides a _log method that directs messages to the appropriate logger ('progress' or 'verbose') and, if available, to the GUI.
Functions¶
setup_loggers ¶
Sets up dual logging system with rotation.
Creates 'progress' and 'verbose' loggers with file and console handlers. Rotates old logs when more than 30 exist. Uses lock file for thread-safe rotation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
process_id | Optional[str] | Optional ID to make log filenames unique for parallel runs. | None |
Returns:
| Type | Description |
|---|---|
tuple[Logger, Logger, str] | Tuple of (progress_logger, verbose_logger, session_timestamp). |
Source code in goliat/logging_manager.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | |
shutdown_loggers ¶
Safely shuts down all logging handlers to release file locks.
Source code in goliat/logging_manager.py
add_simulation_log_handlers ¶
Adds file handlers for progress and verbose logs to a simulation-specific directory.
Creates log files in the simulation directory while keeping the main logs/ directory handlers intact. Both progress and verbose logs are written to the simulation directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulation_dir | str | Directory path where simulation-specific logs should be written. | required |
Returns:
| Type | Description |
|---|---|
list[Handler] | List of handlers that were added (for later removal via remove_simulation_log_handlers). |
Source code in goliat/logging_manager.py
remove_simulation_log_handlers ¶
Removes simulation-specific log handlers and closes their files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handlers | list[Handler] | List of handlers to remove (typically returned from add_simulation_log_handlers). | required |
Source code in goliat/logging_manager.py
Profiling¶
goliat.profiler.Profiler ¶
Manages execution time tracking, ETA estimation, and study phase management.
This class divides a study into phases (setup, run, extract), calculates weighted progress, and estimates the time remaining. It also saves updated time estimates to a configuration file after each run, making it self-improving.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
execution_control | dict | Dict indicating which phases are enabled. | required |
profiling_config | dict | Historical timing data for estimates. | required |
study_type | str | Study type ('near_field' or 'far_field'). | required |
config_path | str | Path where profiling config is saved. | required |
Source code in goliat/profiler.py
Functions¶
set_total_simulations ¶
set_project_scope ¶
set_current_project ¶
simulation_completed ¶
start_stage ¶
Starts tracking a new phase (setup/run/extract).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phase_name | str | Phase name like 'setup', 'run', or 'extract'. | required |
total_stages | int | Number of stages within this phase. | 1 |
Source code in goliat/profiler.py
end_stage ¶
Ends current phase and records its duration for future estimates.
Source code in goliat/profiler.py
complete_run_phase ¶
get_weighted_progress ¶
Calculates overall study progress using phase weights and simulation count.
This method handles the complexity that different phases (setup, run, extract) take different amounts of time. For example, if setup takes 10 minutes, run takes 2 hours, and extract takes 5 minutes, then the run phase should account for roughly 85% of the progress bar, not 33%.
The calculation works in two parts: 1. Progress within current simulation: Sums weights of completed phases, plus partial weight for the current phase based on its progress ratio. 2. Overall progress: Divides (completed_simulations + current_sim_progress) by total_simulations to get the overall percentage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phase_name | str | The name of the current phase ('setup', 'run', or 'extract'). | required |
phase_progress_ratio | float | Progress within current phase (0.0 = not started, 1.0 = fully complete). | required |
Returns:
| Type | Description |
|---|---|
float | Overall progress percentage (0.0 to 100.0). |
Source code in goliat/profiler.py
get_subtask_estimate ¶
Retrieves the estimated time for a specific subtask. Args: task_name: The name of the subtask. Returns: The estimated duration in seconds.
Source code in goliat/profiler.py
get_phase_subtasks ¶
Gets a list of subtasks for a given phase. Args: phase_name: The name of the phase. Returns: A list of subtask names.
Source code in goliat/profiler.py
get_time_remaining ¶
Estimates total time remaining for the entire study.
Uses historical timing data to predict how long each phase will take, then calculates remaining time by subtracting elapsed time from total estimated time. This gives a realistic ETA that accounts for the fact that different phases take different amounts of time.
The calculation considers: - Time already spent on fully completed simulations - Time spent on phases within the current simulation that are done - Estimated time remaining in the current phase (based on progress ratio) - Estimated time for all future simulations
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_stage_progress | float | Progress within current stage (0.0 to 1.0). | 0.0 |
Returns:
| Type | Description |
|---|---|
float | Estimated time remaining in seconds. |
Source code in goliat/profiler.py
subtask ¶
A context manager to time a subtask.
Source code in goliat/profiler.py
update_and_save_estimates ¶
Updates the profiling configuration with the latest average times and saves it.
This makes the profiler's estimates self-improving over time.
Source code in goliat/profiler.py
Project Management¶
goliat.project_manager ¶
Attributes¶
Classes¶
ProjectCorruptionError ¶
Bases: Exception
Raised when a project file is corrupted, locked, or inaccessible.
ProjectManager ¶
ProjectManager(config: Config, verbose_logger: Logger, progress_logger: Logger, gui: Optional[QueueGUI] = None, no_cache: bool = False)
Bases: LoggingMixin
Manages the lifecycle of Sim4Life (.smash) project files.
Handles creation, opening, saving, and validation of project files, ensuring robustness against file corruption and locks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Config | The main configuration object. | required |
verbose_logger | Logger | Logger for detailed output. | required |
progress_logger | Logger | Logger for high-level progress updates. | required |
gui | Optional[QueueGUI] | The GUI proxy for inter-process communication. | None |
no_cache | bool | If True, bypasses metadata verification. | False |
Source code in goliat/project_manager.py
Functions¶
write_simulation_metadata ¶
write_simulation_metadata(meta_path: str, surgical_config: dict, update_setup_timestamp: bool = False)
Writes config metadata and hash to disk for verification/resume.
Creates a metadata file that tracks the config hash and completion status of each phase (setup/run/extract). Used by the verify-and-resume feature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
meta_path | str | Full path where metadata should be saved. | required |
surgical_config | dict | The minimal config snapshot for this simulation. | required |
update_setup_timestamp | bool | If True, updates setup_timestamp to now (use when setup was done). If False, preserves existing timestamp if metadata exists. | False |
Source code in goliat/project_manager.py
update_simulation_metadata ¶
update_simulation_metadata(meta_path: str, run_done: Optional[bool] = None, extract_done: Optional[bool] = None)
Updates phase completion flags in the metadata file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
meta_path | str | Path to the metadata file. | required |
run_done | Optional[bool] | New run phase status. | None |
extract_done | Optional[bool] | New extract phase status. | None |
Source code in goliat/project_manager.py
verify_simulation_metadata ¶
verify_simulation_metadata(meta_path: str, surgical_config: dict, smash_path: Optional[str] = None) -> dict
Verifies if an existing simulation can be reused to skip completed phases.
This method implements a three-step verification process to determine if a previously run simulation can be reused:
-
Config hash check: Compares the stored config hash with the current config. If they don't match, the simulation is outdated and must be rerun.
-
Project file validation: Checks if the .smash file exists, is not locked, and has valid HDF5 structure. If invalid, setup must be rerun.
-
Deliverable freshness check: Verifies that output files (H5 results) and extracted files (JSON/PKL/HTML) exist and are newer than the setup timestamp. This ensures we don't skip phases if files are missing or outdated.
The method returns a dict indicating which phases are complete, allowing the study to skip setup/run/extract as appropriate. Note that extract completion always requires run completion - if extract is done but run isn't, both are marked incomplete to prevent inconsistent states.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
meta_path | str | Path to the metadata file containing config hash and timestamps. | required |
surgical_config | dict | Current config snapshot to compare against stored hash. | required |
smash_path | Optional[str] | Optional override for project file path (used for verification). | None |
Returns:
| Type | Description |
|---|---|
dict | Dict with boolean flags: 'setup_done', 'run_done', 'extract_done'. |
dict | All False if verification fails at any step. |
Source code in goliat/project_manager.py
get_setup_timestamp_from_metadata ¶
Retrieves the setup timestamp from the metadata file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
meta_path | str | Path to the metadata file. | required |
Returns:
| Type | Description |
|---|---|
Optional[float] | Setup timestamp as a float (seconds since epoch), or None if not found or file doesn't exist. |
Source code in goliat/project_manager.py
create_or_open_project ¶
create_or_open_project(phantom_name: str, frequency_mhz: int, scenario_name: Optional[str] = None, position_name: Optional[str] = None, orientation_name: Optional[str] = None, **kwargs) -> dict
Creates a new project or opens an existing one based on the 'do_setup' flag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phantom_name | str | The name of the phantom model. | required |
frequency_mhz | int | The simulation frequency in MHz. | required |
scenario_name | Optional[str] | The base name of the placement scenario. | None |
position_name | Optional[str] | The name of the position within the scenario. | None |
orientation_name | Optional[str] | The name of the orientation within the scenario. | None |
Raises:
| Type | Description |
|---|---|
ValueError | If required parameters are missing or |
FileNotFoundError | If |
ProjectCorruptionError | If the project file is corrupted. |
Source code in goliat/project_manager.py
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 | |
create_new ¶
Creates a new empty project in memory.
Closes any open document, deletes existing project file and cache files, then creates a fresh unsaved project. Also initializes the model by creating/deleting a dummy block to ensure Sim4Life is ready.
Source code in goliat/project_manager.py
open ¶
Opens an existing project after validation checks.
Raises:
| Type | Description |
|---|---|
ProjectCorruptionError | If project file is invalid, locked, or Sim4Life can't open it. |
Source code in goliat/project_manager.py
save ¶
Saves the current project to its file path.
Retries the save operation up to N times (configurable via save_retry_count) if Sim4Life randomly errors out. Logs warnings for each retry attempt.
Raises:
| Type | Description |
|---|---|
ValueError | If project_path hasn't been set. |
Exception | If all retry attempts fail, the last exception is raised. |
Source code in goliat/project_manager.py
close ¶
cleanup ¶
reload_project ¶
Saves, closes, and reopens the project to load simulation results.
Needed because Sim4Life sometimes requires a reload to see new results files. This ensures results are available for extraction.
Source code in goliat/project_manager.py
Functions¶
Study Orchestration¶
Study classes that orchestrate simulation workflows.
Base Study¶
goliat.studies.base_study ¶
Classes¶
BaseStudy ¶
BaseStudy(study_type: str, config_filename: Optional[str] = None, gui: Optional[QueueGUI] = None, profiler=None, no_cache: bool = False)
Bases: LoggingMixin
Base class for simulation studies.
Handles common setup like config loading, profiling, project management, and GUI coordination. Subclasses implement _run_study() for specific logic.
Source code in goliat/studies/base_study.py
Functions¶
subtask ¶
A context manager for a 'subtask' within a phase.
Source code in goliat/studies/base_study.py
start_stage_animation ¶
Starts progress bar animation for the current stage.
end_stage_animation ¶
run ¶
Main entry point to run the study.
Ensures Sim4Life is running, calls _run_study(), and handles cleanup and error reporting. Catches StudyCancelledError for graceful shutdown.
Source code in goliat/studies/base_study.py
Functions¶
Far-Field Study¶
goliat.studies.far_field_study ¶
Classes¶
FarFieldStudy ¶
FarFieldStudy(study_type: str, config_filename: Optional[str] = None, gui: Optional[QueueGUI] = None, profiler=None, no_cache: bool = False)
Bases: BaseStudy
Manages far-field simulation campaigns.
Runs plane wave simulations across phantoms, frequencies, directions, and polarizations. Handles setup, run, and extraction phases with progress tracking.
Source code in goliat/studies/base_study.py
Functions¶
Near-Field Study¶
goliat.studies.near_field_study ¶
Classes¶
NearFieldStudy ¶
NearFieldStudy(study_type: str, config_filename: Optional[str] = None, gui: Optional[QueueGUI] = None, profiler=None, no_cache: bool = False)
Bases: BaseStudy
Manages near-field simulation campaigns.
Runs simulations across phantoms, frequencies, placements, positions, and orientations. Handles setup, run, and extraction phases with progress tracking and metadata verification.
Source code in goliat/studies/base_study.py
Functions¶
Setup Modules¶
Classes responsible for building the Sim4Life simulation scene.
Base Setup¶
goliat.setups.base_setup ¶
Classes¶
BaseSetup ¶
BaseSetup(config: Config, verbose_logger: Logger, progress_logger: Logger, gui: Optional[QueueGUI] = None)
Bases: LoggingMixin
Base class for simulation setup modules.
Provides common functionality like solver configuration, time/termination setup, point sensor creation, and final voxelization. Subclasses implement run_full_setup() for specific setup logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Config | Configuration object. | required |
verbose_logger | Logger | Logger for detailed output. | required |
progress_logger | Logger | Logger for progress updates. | required |
gui | Optional[QueueGUI] | Optional GUI instance for forwarding progress messages. | None |
Source code in goliat/setups/base_setup.py
Functions¶
run_full_setup ¶
Prepares the simulation scene. Must be implemented by subclasses.
Returns:
| Type | Description |
|---|---|
| The configured simulation object. |
Raises:
| Type | Description |
|---|---|
NotImplementedError | If not overridden by subclass. |
Source code in goliat/setups/base_setup.py
Boundary Setup¶
goliat.setups.boundary_setup ¶
Classes¶
BoundarySetup ¶
BoundarySetup(config: Config, simulation: Simulation, verbose_logger: Logger, progress_logger: Logger)
Bases: BaseSetup
Configures the boundary conditions for the simulation.
Source code in goliat/setups/boundary_setup.py
Functions¶
setup_boundary_conditions ¶
Configures PML boundary conditions from the solver settings.
Sets the global boundary type (e.g., UPML/CPML) and PML strength (Low/Medium/High) based on the config.
Source code in goliat/setups/boundary_setup.py
Far-Field Setup¶
goliat.setups.far_field_setup ¶
Classes¶
FarFieldSetup ¶
FarFieldSetup(config: Config, phantom_name: str, frequency_mhz: int, direction_name: str, polarization_name: str, project_manager: ProjectManager, verbose_logger: Logger, progress_logger: Logger, profiler: Profiler, gui=None)
Bases: BaseSetup
Configures a far-field simulation for a specific direction and polarization.
Source code in goliat/setups/far_field_setup.py
Functions¶
run_full_setup ¶
Executes the full setup sequence for a single far-field simulation with granular timing.
Source code in goliat/setups/far_field_setup.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |
Gridding Setup¶
goliat.setups.gridding_setup ¶
Classes¶
GriddingSetup ¶
GriddingSetup(config: Config, simulation: Simulation, placement_name: str, antenna: Antenna, verbose_logger: Logger, progress_logger: Logger, frequency_mhz: int | None = None)
Bases: BaseSetup
Configures simulation grid resolution and subgridding.
Sets up main grid (automatic or manual) with padding, and optional antenna-specific subgrids for fine details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Config | Configuration object. | required |
simulation | Simulation | The simulation object to configure gridding for. | required |
placement_name | str | Name of the placement scenario. | required |
antenna | Antenna | Antenna object. | required |
verbose_logger | Logger | Logger for detailed output. | required |
progress_logger | Logger | Logger for progress updates. | required |
frequency_mhz | int | None | Simulation frequency in MHz (optional). | None |
Source code in goliat/setups/gridding_setup.py
Functions¶
setup_gridding ¶
Sets up main grid and optional antenna subgrids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
antenna_components | dict | None | Dict mapping component names to entities. | None |
Source code in goliat/setups/gridding_setup.py
Material Setup¶
goliat.setups.material_setup ¶
Classes¶
MaterialSetup ¶
MaterialSetup(config: Config, simulation: Simulation, antenna: Antenna, phantom_name: str, verbose_logger: Logger, progress_logger: Logger, free_space: bool = False)
Bases: BaseSetup
Assigns materials to phantom tissues and antenna components.
Maps tissue names to IT'IS database materials and assigns antenna materials from config. Uses file locking for thread-safe database access.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Config | Configuration object. | required |
simulation | Simulation | The simulation object to assign materials to. | required |
antenna | Antenna | Antenna object. | required |
phantom_name | str | Name of the phantom model. | required |
verbose_logger | Logger | Logger for detailed output. | required |
progress_logger | Logger | Logger for progress updates. | required |
free_space | bool | Whether this is a free-space simulation. | False |
Source code in goliat/setups/material_setup.py
Functions¶
assign_materials ¶
Assigns materials to simulation entities.
Sets background to Air, then assigns phantom materials if not free-space, and antenna materials if not phantom_only mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
antenna_components | dict | None | Dict mapping component names to entities. | None |
phantom_only | bool | If True, skips antenna material assignment. | False |
Source code in goliat/setups/material_setup.py
Near-Field Setup¶
goliat.setups.near_field_setup ¶
Classes¶
NearFieldSetup ¶
NearFieldSetup(config: Config, phantom_name: str, frequency_mhz: int, scenario_name: str, position_name: str, orientation_name: str, antenna: Antenna, verbose_logger: Logger, progress_logger: Logger, profiler: Profiler, gui=None, free_space: bool = False)
Bases: BaseSetup
Configures the simulation environment by coordinating setup modules.
Source code in goliat/setups/near_field_setup.py
Functions¶
run_full_setup ¶
Executes complete setup sequence with detailed timing.
Orchestrates the entire simulation setup process in 6 major subtasks:
-
Load phantom: Imports phantom model from disk or downloads if missing. Creates head/trunk bounding boxes if needed.
-
Configure scene: Imports antenna, places it relative to phantom, creates simulation bounding box, sets up simulation entity, adds point sensors. Handles special cases like phantom rotation and phone alignment.
-
Assign materials: Maps tissue names to IT'IS database materials, assigns antenna component materials from config. Uses file locking for thread safety.
-
Configure solver: Sets up gridding (automatic or manual with subgrids), configures boundary conditions (PML), and sets up excitation sources.
-
Voxelize: Runs automatic voxelization on all simulation entities, updates materials and grid, optionally exports material properties.
-
Save project: Saves the .smash file to disk.
Each subtask is profiled individually for accurate timing estimates. The method returns a fully configured simulation object ready to run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
project_manager | ProjectManager | Project manager for saving operations. | required |
lock | Optional lock (currently unused, reserved for future use). | None |
Returns:
| Type | Description |
|---|---|
Simulation | Fully configured simulation object ready for execution. |
Source code in goliat/setups/near_field_setup.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 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 | |
Phantom Setup¶
goliat.setups.phantom_setup ¶
Classes¶
PhantomSetup ¶
Bases: BaseSetup
Handles loading and importing phantom models into Sim4Life.
Source code in goliat/setups/phantom_setup.py
Functions¶
ensure_phantom_is_loaded ¶
Checks if phantom is loaded, imports from disk if available, or downloads if missing.
Returns:
| Type | Description |
|---|---|
bool | True if phantom is now loaded, False if download was initiated (requires re-run). |
Source code in goliat/setups/phantom_setup.py
Placement Setup¶
goliat.setups.placement_setup ¶
Classes¶
PlacementSetup ¶
PlacementSetup(config: Config, phantom_name: str, frequency_mhz: int, base_placement_name: str, position_name: str, orientation_name: str, antenna: Antenna, verbose_logger: Logger, progress_logger: Logger, free_space: bool = False)
Bases: BaseSetup
Handles antenna placement and orientation relative to phantom.
Imports antenna model, calculates target position based on placement scenario, and applies composed transformation (stand-up rotation, translation, orientation twists) to position antenna correctly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Config | Configuration object. | required |
phantom_name | str | Name of the phantom model. | required |
frequency_mhz | int | Simulation frequency in MHz. | required |
base_placement_name | str | Base name of the placement scenario. | required |
position_name | str | Name of the position within the scenario. | required |
orientation_name | str | Name of the orientation within the scenario. | required |
antenna | Antenna | Antenna object to place. | required |
verbose_logger | Logger | Logger for detailed output. | required |
progress_logger | Logger | Logger for progress updates. | required |
free_space | bool | Whether this is a free-space simulation. | False |
Source code in goliat/setups/placement_setup.py
Functions¶
place_antenna ¶
Places and orients antenna using a single composed transformation.
This method implements a key optimization: instead of applying multiple transforms sequentially (which causes precision loss and can accumulate errors), it composes all transformations into a single matrix and applies it once.
The transformation sequence is: 1. Stand-up rotation: Rotates antenna 90° around X-axis to make it upright 2. Base translation: Moves antenna to a reference point (speaker location) 3. Special rotation: For 'by_cheek', applies -90° Z-rotation to align with YZ plane 4. Orientation twists: Applies any rotations specified in orientation config 5. Final translation: Moves antenna to its target position relative to phantom
The order matters because matrix multiplication is not commutative. Each step builds on the previous transform, so the antenna ends up correctly positioned and oriented relative to the phantom regardless of how many rotations are needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
None (uses instance attributes | antenna, placement_name, etc.) | required |
Raises:
| Type | Description |
|---|---|
RuntimeError | If antenna import fails or required entities aren't found. |
Source code in goliat/setups/placement_setup.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
Source Setup¶
goliat.setups.source_setup ¶
Classes¶
SourceSetup ¶
SourceSetup(config: Config, simulation: Simulation, frequency_mhz: int, antenna: Antenna, verbose_logger: Logger, progress_logger: Logger, free_space: bool = False, phantom_name: Optional[str] = None, placement_name: Optional[str] = None)
Bases: BaseSetup
Configures excitation sources and sensors for the simulation.
Source code in goliat/setups/source_setup.py
Functions¶
setup_source_and_sensors ¶
Sets up the edge source and sensors based on excitation type.
Uses excitation_type from config to determine Harmonic or Gaussian excitation. For free-space simulations, also adds far-field sensors for Gaussian sources.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
antenna_components | dict | Dict mapping component names to entities. | required |
Source code in goliat/setups/source_setup.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
Simulation Execution¶
goliat.simulation_runner.SimulationRunner ¶
SimulationRunner(config: Config, project_path: str, simulation: Simulation, profiler: Profiler, verbose_logger: Logger, progress_logger: Logger, project_manager: ProjectManager, gui: Optional[QueueGUI] = None)
Bases: LoggingMixin
Manages simulation execution via the Sim4Life API or iSolve.exe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Config | Configuration object. | required |
project_path | str | Path to the Sim4Life project file. | required |
simulation | Simulation | The simulation object to run. | required |
profiler | Profiler | Profiler for timing subtasks. | required |
verbose_logger | Logger | Logger for detailed output. | required |
progress_logger | Logger | Logger for high-level updates. | required |
gui | Optional[QueueGUI] | Optional GUI proxy for updates. | None |
project_manager | ProjectManager | ProjectManager instance. Uses its save() method. | required |
Source code in goliat/simulation_runner.py
Functions¶
run ¶
Runs the simulation using the configured execution method.
Writes input file first, then runs via Sim4Life API, manual iSolve, or oSPARC depending on config. Handles errors and provides helpful messages for common issues.
Source code in goliat/simulation_runner.py
Execution Strategies¶
Strategy pattern implementations for different simulation execution methods.
Base Strategy¶
goliat.runners.execution_strategy ¶
Abstract base class for simulation execution strategies.
Classes¶
ExecutionStrategy ¶
ExecutionStrategy(config: Config, project_path: str, simulation: Simulation, profiler: Profiler, verbose_logger: LoggingMixin, progress_logger: LoggingMixin, project_manager: ProjectManager, gui: QueueGUI | None = None)
Bases: ABC
Abstract base class for simulation execution strategies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Config | Configuration object. | required |
project_path | str | Path to the Sim4Life project file. | required |
simulation | Simulation | The simulation object to run. | required |
profiler | Profiler | Profiler for timing subtasks. | required |
verbose_logger | LoggingMixin | Logger for detailed output. | required |
progress_logger | LoggingMixin | Logger for high-level updates. | required |
project_manager | ProjectManager | ProjectManager instance. | required |
gui | QueueGUI | None | Optional GUI proxy for updates. | None |
Source code in goliat/runners/execution_strategy.py
iSolve Manual Strategy¶
goliat.runners.isolve_manual_strategy ¶
Execution strategy for manual iSolve subprocess execution.
Classes¶
ISolveManualStrategy ¶
Bases: ExecutionStrategy, LoggingMixin
Execution strategy for running iSolve.exe directly via subprocess.
Source code in goliat/runners/isolve_manual_strategy.py
Functions¶
run ¶
Runs iSolve.exe directly with real-time output logging.
This method bypasses Sim4Life's API and runs the solver executable directly. This is useful when you need more control over the execution environment or when the API has issues. The key challenge is capturing output in real-time without blocking the main thread.
The solution uses a background thread with a queue: - A daemon thread reads stdout line-by-line and puts lines into a queue - The main thread polls the queue non-blockingly and logs output - After process completion, remaining output is drained from the queue
This approach allows the GUI to remain responsive and users to see progress updates as they happen. Without threading, reading stdout would block until the process finishes, making it impossible to show real-time progress.
Steps: 1. Locate iSolve.exe relative to Python executable 2. Spawn subprocess with stdout/stderr pipes 3. Start background thread to read stdout into queue 4. Poll process and queue, logging output without blocking 5. After completion, reload project to load results into Sim4Life
Raises:
| Type | Description |
|---|---|
FileNotFoundError | If iSolve.exe or input file not found. |
RuntimeError | If iSolve exits with non-zero code or simulation can't be found after reload. |
Source code in goliat/runners/isolve_manual_strategy.py
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 419 420 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 | |
Functions¶
oSPARC Direct Strategy¶
goliat.runners.osparc_direct_strategy ¶
Execution strategy for oSPARC cloud platform execution.
Classes¶
OSPARCDirectStrategy ¶
Bases: ExecutionStrategy, LoggingMixin
Execution strategy for submitting simulations to oSPARC cloud platform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_name | str | oSPARC resource name to use (e.g., 'local', 'osparc-1'). | required |
*args | Passed to parent class. | () | |
**kwargs | Passed to parent class. | {} |
Source code in goliat/runners/osparc_direct_strategy.py
Functions¶
run ¶
Submits simulation directly to oSPARC cloud platform.
This method handles cloud-based simulation execution through the oSPARC platform. Instead of running locally, it uploads the solver input file to oSPARC, submits a job, and polls for completion.
The process: 1. Initializes oSPARC API client using credentials from config 2. Creates a job submission with input file path and resource name 3. Submits job and waits for completion (polls status periodically) 4. Downloads results when job completes successfully 5. Reloads project to load results into Sim4Life
This requires Sim4Life 8.2.0 for the XOsparcApiClient module. The method handles authentication, job lifecycle, and error reporting.
Raises:
| Type | Description |
|---|---|
RuntimeError | If API client unavailable, job creation fails, job completes with non-success status, or simulation can't be found after reload. |
FileNotFoundError | If solver input file not found. |
ValueError | If oSPARC credentials are missing from config. |
Source code in goliat/runners/osparc_direct_strategy.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | |
Sim4Life API Strategy¶
goliat.runners.sim4life_api_strategy ¶
Execution strategy for Sim4Life API execution.
Classes¶
Sim4LifeAPIStrategy ¶
Bases: ExecutionStrategy, LoggingMixin
Execution strategy for running simulations via Sim4Life API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | None | Server ID to use (None for localhost). | required |
*args | Passed to parent class. | () | |
**kwargs | Passed to parent class. | {} |
Source code in goliat/runners/sim4life_api_strategy.py
Functions¶
run ¶
Run simulation using Sim4Life API.
Raises:
| Type | Description |
|---|---|
RuntimeError | If simulation execution fails. |
Source code in goliat/runners/sim4life_api_strategy.py
Results Extraction¶
Classes for extracting and processing simulation results.
Cleanup¶
goliat.extraction.cleaner.Cleaner ¶
Manages deletion of simulation files to free disk space.
Deletes output files, input files, and/or project files based on config. Useful for long-running studies where disk space is limited.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent | ResultsExtractor | Parent ResultsExtractor instance. | required |
Source code in goliat/extraction/cleaner.py
Functions¶
cleanup_simulation_files ¶
Deletes simulation files based on auto_cleanup config.
Removes files matching specified patterns (output/input H5 files, project files). Only runs if cleanup is enabled in config.
Source code in goliat/extraction/cleaner.py
JSON Encoding¶
goliat.extraction.json_encoder ¶
Classes¶
Power Extraction¶
goliat.extraction.power_extractor ¶
Classes¶
PowerExtractor ¶
Bases: LoggingMixin
Extracts input power and power balance from simulation results.
For near-field, reads power from port sensors. For far-field, calculates theoretical power from plane wave parameters. Also extracts power balance to verify energy conservation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent | ResultsExtractor | Parent ResultsExtractor instance. | required |
results_data | dict | Dict to store extracted power data. | required |
Source code in goliat/extraction/power_extractor.py
Functions¶
extract_input_power ¶
Extracts input power, delegating to study-type specific methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulation_extractor | Extractor | Results extractor from the simulation. | required |
Source code in goliat/extraction/power_extractor.py
extract_power_balance ¶
Extracts power balance to verify energy conservation.
Power balance is a sanity check: the power going into the simulation should equal the power coming out (as losses and radiation). This helps catch numerical errors or convergence issues.
The balance is calculated as: balance = (P_out / P_in) × 100%
Where P_out includes: - Dielectric losses (power absorbed by materials) - Radiated power (power escaping the simulation volume)
For far-field studies, uses the theoretical input power (from plane wave calculation) rather than extracted power, since plane waves don't have a traditional "input port" sensor.
A balance close to 100% indicates good energy conservation. Values significantly different suggest convergence issues or numerical errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulation_extractor | Extractor | Results extractor from the simulation. | required |
Source code in goliat/extraction/power_extractor.py
Reporting¶
goliat.extraction.reporter.Reporter ¶
Generates and saves detailed reports from extraction results.
Creates Pickle files for programmatic access and HTML files for human readability. Includes SAR statistics, tissue groups, and peak SAR details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent | ResultsExtractor | Parent ResultsExtractor instance. | required |
Source code in goliat/extraction/reporter.py
Functions¶
save_reports ¶
Saves Pickle and HTML reports to the results directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df | DataFrame | DataFrame with detailed SAR statistics per tissue. | required |
tissue_groups | dict | Dict mapping group names to tissue lists. | required |
group_sar_stats | dict | Dict with aggregated SAR stats per group. | required |
results_data | dict | Dict with summary results and metadata. | required |
Source code in goliat/extraction/reporter.py
SAR Extraction¶
goliat.extraction.sar_extractor ¶
Classes¶
SarExtractor ¶
Bases: LoggingMixin
Extracts SAR statistics from simulation results.
Uses Sim4Life's SarStatisticsEvaluator to compute mass-averaged SAR, peak spatial-average SAR (10g), and tissue-specific metrics. Groups tissues into logical groups (eyes, skin, brain) for analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent | ResultsExtractor | Parent ResultsExtractor instance. | required |
results_data | dict | Dict to store extracted SAR data. | required |
Source code in goliat/extraction/sar_extractor.py
Functions¶
extract_sar_statistics ¶
Extracts comprehensive SAR statistics for all tissues.
This is the main SAR extraction method that orchestrates the entire process. It uses Sim4Life's SarStatisticsEvaluator to compute standardized SAR metrics according to IEEE/IEC standards.
The process: 1. Extracts the 'Overall Field' E-field data from simulation results 2. Creates a SarStatisticsEvaluator configured for 10g peak spatial-average SAR 3. Processes the evaluator output into a pandas DataFrame 4. Groups tissues into logical categories (eyes, skin, brain) 5. Calculates weighted-average SAR for each group (mass-weighted) 6. Extracts peak SAR details (location, coordinates, etc.) 7. Stores both per-tissue and group-level results
The results include mass-averaged SAR, peak spatial-average SAR (10g), and tissue-specific metrics. For near-field studies, also extracts head/trunk SAR based on placement scenario. For far-field, extracts whole-body SAR.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulation_extractor | Extractor | Results extractor from the simulation object. | required |
Source code in goliat/extraction/sar_extractor.py
extract_peak_sar_details ¶
Extracts detailed metadata about the peak spatial-average SAR location.
While the main SAR extraction gives per-tissue statistics, this method provides detailed information about where the absolute peak SAR occurs. This includes 3D coordinates, the tissue/organ containing the peak, mass of the 10g averaging volume, and other metadata.
This information is useful for: - Understanding which anatomical region has the highest exposure - Verifying that peak SAR is in an expected location - Debugging unexpected SAR hotspots - Reporting peak exposure location in compliance documentation
Uses Sim4Life's AverageSarFieldEvaluator configured for 10g spatial averaging to find the peak location according to IEEE/IEC 62704-1 standards.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
em_sensor_extractor | Extractor | The 'Overall Field' results extractor containing the SAR field data. | required |
Source code in goliat/extraction/sar_extractor.py
Sensor Extraction¶
goliat.extraction.sensor_extractor ¶
Point sensor data extraction.
Classes¶
SensorExtractor ¶
Extracts time-domain E-field data from point sensors.
Reads E-field measurements from sensors placed at simulation bbox corners, creates plots showing magnitude over time, and stores raw data in results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent | ResultsExtractor | Parent ResultsExtractor instance. | required |
results_data | dict | Dict to store extracted data. | required |
Source code in goliat/extraction/sensor_extractor.py
Functions¶
extract_point_sensor_data ¶
Extracts E-field data from all point sensors and generates plots.
Iterates through configured sensors, extracts time-domain E-field components (Ex, Ey, Ez), calculates magnitude, and saves both plot and raw data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulation_extractor | Extractor | Results extractor from the simulation object. | required |
Source code in goliat/extraction/sensor_extractor.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
Analysis¶
Classes for analyzing and visualizing simulation results.
Analyzer¶
goliat.analysis.analyzer.Analyzer ¶
Analyzer(config: Config, phantom_name: str, strategy: BaseAnalysisStrategy, plot_format: str = 'pdf')
Analyzes simulation results using a strategy pattern.
Delegates to strategy-specific implementations for loading results and generating plots. Handles unit conversion, caching, and report export.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Config | Configuration object. | required |
phantom_name | str | Phantom model name being analyzed. | required |
strategy | BaseAnalysisStrategy | Strategy implementation for analysis logic. | required |
plot_format | str | Output format for plots ('pdf' or 'png'), default 'pdf'. | 'pdf' |
Source code in goliat/analysis/analyzer.py
Functions¶
run_analysis ¶
Runs complete analysis pipeline using the selected strategy.
Loads results, converts units, exports reports, and generates plots. Delegates strategy-specific logic to the strategy instance.
Source code in goliat/analysis/analyzer.py
Analysis Strategies¶
goliat.analysis.base_strategy ¶
Classes¶
BaseAnalysisStrategy ¶
Bases: ABC
Base class for analysis strategies.
Defines interface for loading results, calculating normalization factors, and generating plots. Subclasses implement study-type specific logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Config | Configuration object. | required |
phantom_name | str | Phantom model name being analyzed. | required |
analysis_config | dict | None | Optional dictionary with plot names as keys and boolean values. | None |
Source code in goliat/analysis/base_strategy.py
Functions¶
should_generate_plot ¶
Checks if a plot should be generated based on the analysis config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plot_name | str | Name of the plot to check. | required |
Returns:
| Type | Description |
|---|---|
bool | True if the plot should be generated (default if not in config), False otherwise. |
Source code in goliat/analysis/base_strategy.py
get_results_base_dir ¶
get_plots_dir ¶
load_and_process_results abstractmethod ¶
Loads and processes all simulation results.
Iterates through configured scenarios and calls analyzer._process_single_result() for each one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
analyzer | Analyzer | Analyzer instance to process results with. | required |
Source code in goliat/analysis/base_strategy.py
get_normalization_factor abstractmethod ¶
Calculates SAR normalization factor from simulated power.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frequency_mhz | int | Simulation frequency in MHz. | required |
simulated_power_w | float | Input power from simulation in Watts. | required |
Returns:
| Type | Description |
|---|---|
float | Normalization factor to multiply SAR values by. |
Source code in goliat/analysis/base_strategy.py
extract_data abstractmethod ¶
extract_data(pickle_data: dict, frequency_mhz: int, placement_name: str, scenario_name: str, sim_power: float, norm_factor: float, sar_results: dict | None = None) -> tuple[dict, list]
Extracts and structures data from a single simulation's result files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pickle_data | dict | Data loaded from the .pkl result file. | required |
frequency_mhz | int | Simulation frequency. | required |
placement_name | str | Detailed placement name. | required |
scenario_name | str | General scenario name. | required |
sim_power | float | Simulated input power in Watts. | required |
norm_factor | float | Normalization factor to apply. | required |
sar_results | dict | None | Optional JSON results dict containing additional data like power balance. | None |
Returns:
| Type | Description |
|---|---|
tuple[dict, list] | Tuple of (main result entry dict, list of organ-specific entries). |
Source code in goliat/analysis/base_strategy.py
apply_bug_fixes abstractmethod ¶
Applies workarounds for known data inconsistencies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result_entry | dict | Data entry for a single simulation result. | required |
Returns:
| Type | Description |
|---|---|
dict | Corrected result entry. |
Source code in goliat/analysis/base_strategy.py
calculate_summary_stats abstractmethod ¶
Calculates summary statistics from aggregated results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results_df | DataFrame | DataFrame with all aggregated simulation results. | required |
Returns:
| Type | Description |
|---|---|
DataFrame | DataFrame with summary statistics. |
Source code in goliat/analysis/base_strategy.py
generate_plots abstractmethod ¶
generate_plots(analyzer: Analyzer, plotter: Plotter, results_df: DataFrame, all_organ_results_df: DataFrame)
Generates study-type specific plots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
analyzer | Analyzer | Analyzer instance with aggregated data. | required |
plotter | Plotter | Plotter instance for creating figures. | required |
results_df | DataFrame | DataFrame with summary results. | required |
all_organ_results_df | DataFrame | DataFrame with organ-level details. | required |
Source code in goliat/analysis/base_strategy.py
Far-Field Strategy¶
goliat.analysis.far_field_strategy ¶
Classes¶
FarFieldAnalysisStrategy ¶
Bases: BaseAnalysisStrategy
Analysis strategy for far-field simulations.
Handles result loading, normalization, and plot generation for far-field studies with incident directions and polarizations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Config | Configuration object. | required |
phantom_name | str | Phantom model name being analyzed. | required |
analysis_config | dict | None | Optional dictionary with plot names as keys and boolean values. | None |
Source code in goliat/analysis/far_field_strategy.py
Functions¶
get_results_base_dir ¶
get_plots_dir ¶
load_and_process_results ¶
Iterates through far-field results and processes each one.
Source code in goliat/analysis/far_field_strategy.py
get_normalization_factor ¶
Returns normalization factor for far-field (always 1.0).
Far-field simulations are normalized to 1 W/m^2 in the simulation itself, so no additional normalization is needed.
Source code in goliat/analysis/far_field_strategy.py
apply_bug_fixes ¶
calculate_summary_stats ¶
Calculates summary statistics for far-field results.
Source code in goliat/analysis/far_field_strategy.py
Near-Field Strategy¶
goliat.analysis.near_field_strategy ¶
Classes¶
NearFieldAnalysisStrategy ¶
Bases: BaseAnalysisStrategy
Analysis strategy for near-field simulations.
Handles result loading, normalization, and plot generation for near-field studies with placement scenarios, positions, and orientations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Config | Configuration object. | required |
phantom_name | str | Phantom model name being analyzed. | required |
analysis_config | dict | None | Optional dictionary with plot names as keys and boolean values. | None |
Source code in goliat/analysis/near_field_strategy.py
Functions¶
get_results_base_dir ¶
get_plots_dir ¶
load_and_process_results ¶
Iterates through near-field results and processes each one.
Source code in goliat/analysis/near_field_strategy.py
get_normalization_factor ¶
Calculates the normalization factor based on the target power.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frequency_mhz | int | The simulation frequency in MHz. | required |
simulated_power_w | float | The input power from the simulation in Watts. | required |
Returns:
| Type | Description |
|---|---|
float | The calculated normalization factor, or 1.0 if not possible. |
Source code in goliat/analysis/near_field_strategy.py
extract_data ¶
extract_data(pickle_data: dict, frequency_mhz: int, placement_name: str, scenario_name: str, sim_power: float, norm_factor: float, sar_results: dict | None = None) -> tuple[dict, list]
Extracts and normalizes SAR data from a single near-field result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pickle_data | dict | Data loaded from the .pkl result file. | required |
frequency_mhz | int | The simulation frequency. | required |
placement_name | str | The detailed name of the placement. | required |
scenario_name | str | The general scenario name (e.g., 'by_cheek'). | required |
sim_power | float | The simulated input power in Watts. | required |
norm_factor | float | The normalization factor to apply to SAR values. | required |
sar_results | dict | None | Optional JSON results dict containing power balance data. | None |
Returns:
| Type | Description |
|---|---|
tuple[dict, list] | A tuple containing the main result entry and a list of organ-specific entries. |
Source code in goliat/analysis/near_field_strategy.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 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 | |
apply_bug_fixes ¶
Applies a workaround for Head SAR being miscategorized as Trunk SAR.
NOTE: This method is deprecated for whole_body bounding box scenarios. For whole_body scenarios, SAR_head and SAR_trunk should remain NA.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result_entry | dict | The data entry for a single simulation result. | required |
Returns:
| Type | Description |
|---|---|
dict | The corrected result entry. |
Source code in goliat/analysis/near_field_strategy.py
calculate_summary_stats ¶
Calculates summary statistics, including completion progress.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results_df | DataFrame | DataFrame with all aggregated simulation results. | required |
Returns:
| Type | Description |
|---|---|
DataFrame | A DataFrame with mean SAR values and a 'progress' column. |
Source code in goliat/analysis/near_field_strategy.py
generate_plots ¶
generate_plots(analyzer: Analyzer, plotter: Plotter, results_df: DataFrame, all_organ_results_df: DataFrame)
Generates all plots for the near-field analysis.
Includes bar charts for average SAR, line plots for psSAR, and boxplots for SAR distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
analyzer | Analyzer | The main analyzer instance. | required |
plotter | Plotter | The plotter instance for generating plots. | required |
results_df | DataFrame | DataFrame with main aggregated results. | required |
all_organ_results_df | DataFrame | DataFrame with detailed organ-level results. | required |
Source code in goliat/analysis/near_field_strategy.py
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 419 420 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 515 516 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 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 | |
Plotting¶
goliat.analysis.plotter.Plotter ¶
Bases: BasePlotter
Generates publication-ready plots from simulation results.
Creates bar charts, line plots, boxplots, and heatmaps for SAR analysis. All plots are saved to the configured plots directory.
Uses composition to delegate to specialized plot modules for better organization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plots_dir | str | Directory where all plots will be saved. | required |
phantom_name | str | None | Optional phantom model name for titles. | None |
plot_format | str | Output format for plots ('pdf' or 'png'), default 'pdf'. | 'pdf' |
Source code in goliat/analysis/plotter.py
Functions¶
plot_average_sar_bar ¶
plot_average_pssar_bar ¶
plot_whole_body_sar_bar ¶
plot_peak_sar_line ¶
plot_pssar_line ¶
plot_sar_line ¶
plot_pssar_line_individual_variations ¶
Plots individual variation lines for each placement variation.
plot_sar_line_individual_variations ¶
plot_sar_distribution_boxplots ¶
Creates boxplots showing SAR value distributions across placements.
plot_far_field_distribution_boxplot ¶
Creates a boxplot showing distribution of a metric across directions/polarizations.
plot_sar_heatmap ¶
Creates a combined heatmap showing Min/Avg/Max SAR per tissue and frequency.
plot_peak_sar_heatmap ¶
Creates a heatmap for peak SAR values across tissues and frequencies.
plot_peak_location_3d_interactive ¶
plot_peak_location_2d_projections ¶
Creates 2D scatter plots showing peak locations projected onto XY, XZ, YZ planes.
plot_correlation_head_vs_eye_sar ¶
Creates scatter plot showing correlation between Head SAR and Eye psSAR10g.
plot_tissue_group_correlation_matrix ¶
Creates heatmap showing correlation coefficients between tissue group SAR values.
plot_bubble_mass_vs_sar ¶
plot_bubble_mass_vs_sar_interactive ¶
Creates an interactive bubble plot with common axis limits across frequencies.
plot_top20_tissues_ranking ¶
Creates horizontal bar chart showing top 20 tissues ranked by various metrics.
plot_power_efficiency_trends ¶
Creates line plot showing antenna efficiency and power component percentages.
plot_power_absorption_distribution ¶
Creates pie chart or stacked bar chart showing power distribution across tissue groups.
plot_power_balance_overview ¶
plot_penetration_depth_ratio ¶
Creates line plot showing SAR penetration depth ratio (Brain/Skin) vs frequency.
plot_max_local_vs_pssar10g_scatter ¶
Creates scatter plot showing relationship between Max Local SAR and psSAR10g.
plot_tissue_frequency_response ¶
Creates line plot showing how a specific tissue responds across frequencies.
plot_tissue_mass_volume_distribution ¶
Creates histograms and scatter plot showing tissue mass and volume distributions.
plot_cdf ¶
Creates CDF plot for a metric with optional aggregation by independent variables.
identify_outliers ¶
GUI Components¶
Graphical user interface for monitoring simulation progress.
Main GUI¶
goliat.gui.progress_gui ¶
ProgressGUI main window component.
Classes¶
ProgressGUI ¶
Bases: QWidget
Main GUI window for monitoring simulation progress.
Provides real-time progress tracking via progress bars, ETA estimation, and status logs. Runs in the main process and communicates with worker process through a multiprocessing queue.
The GUI architecture: - Main window runs in main process, worker runs in separate process - Communication via multiprocessing.Queue for thread-safe message passing - QueueHandler polls queue every 100ms and updates UI accordingly - Multiple timers handle different update frequencies (queue, clock, graphs)
Features: - Overall progress bar (weighted across all simulations) - Stage progress bar (current phase: setup/run/extract) - Real-time ETA calculation based on profiler estimates - Status log with color-coded messages - Timings table showing execution statistics - Pie charts showing phase/subtask breakdowns - Time series plots for progress and ETA trends - System tray integration for background operation
Initializes data manager, status manager, UI builder, timers, and queue handler. Sets up Qt timers for periodic updates (queue polling, clock updates, graph refreshes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
queue | Queue | Queue for receiving messages from worker process. | required |
stop_event | Event | Event to signal termination to worker process. | required |
process | Process | Worker process running the study. | required |
init_window_title | str | Initial window title. | '' |
Source code in goliat/gui/progress_gui.py
Functions¶
update_overall_progress ¶
Updates overall progress bar across all simulations.
update_stage_progress ¶
update_stage_progress(stage_name: str, current_step: int, total_steps: int, sub_stage: str = '') -> None
Updates stage-specific progress bar and label.
Source code in goliat/gui/progress_gui.py
start_stage_animation ¶
Starts smooth animated progress bar for a stage.
Instead of jumping to discrete progress values, animates smoothly over the estimated duration. This provides visual feedback during long-running tasks where progress updates are infrequent.
The animation uses linear interpolation between current value and target (always 100% = 1000). Updates every 50ms via Qt timer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimated_duration | float | Estimated task duration in seconds (from profiler). | required |
end_step | int | Target step value (unused, always animates to 100%). | required |
Source code in goliat/gui/progress_gui.py
end_stage_animation ¶
update_animation ¶
Updates progress bar animation frame and syncs overall progress.
Called every 50ms by Qt timer when animation is active. Calculates current progress based on elapsed time and estimated duration, then updates stage progress bar. Also syncs overall progress bar using weighted progress calculation from profiler.
Source code in goliat/gui/progress_gui.py
update_simulation_details ¶
Updates simulation counter and details labels.
update_status ¶
Appends message to status log with color formatting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message | str | Message text. | required |
log_type | str | Log type for color coding. | 'default' |
Source code in goliat/gui/progress_gui.py
update_utilization ¶
update_utilization_plot ¶
update_clock ¶
update_graphs ¶
hide_to_tray ¶
show_from_tray ¶
stop_study ¶
Sends stop signal to worker process.
Source code in goliat/gui/progress_gui.py
study_finished ¶
Handles study completion, stopping timers and updating UI.
Called when worker process signals completion. Stops all timers, updates final progress to 100%, sets stage label, and schedules window auto-close after 3 seconds (if no errors).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error | bool | Whether study finished with errors (affects UI styling). | False |
Source code in goliat/gui/progress_gui.py
closeEvent ¶
Handles window close event, ensuring worker process termination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event | Any | Close event. | required |
Source code in goliat/gui/progress_gui.py
Functions¶
GUI Communication¶
goliat.gui.queue_gui ¶
QueueGUI proxy for worker process communication.
Classes¶
QueueGUI ¶
QueueGUI(queue: Queue, stop_event: Event, profiler: Profiler, progress_logger: Logger, verbose_logger: Logger)
Bases: LoggingMixin
Proxy for ProgressGUI that operates in a separate process.
Mimics the ProgressGUI interface but routes all calls through a multiprocessing queue, enabling thread-safe communication between worker and GUI processes. All methods serialize their arguments and send them via queue for the GUI process to handle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
queue | Queue | Multiprocessing queue for IPC. | required |
stop_event | Event | Event flagging user cancellation. | required |
profiler | Profiler | Profiler for ETA calculations. | required |
progress_logger | Logger | Logger for progress-level messages. | required |
verbose_logger | Logger | Logger for detailed messages. | required |
Source code in goliat/gui/queue_gui.py
Functions¶
log ¶
Sends a log message to the GUI via queue.
Only 'progress' level messages are forwarded to reduce queue traffic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message | str | Log message text. | required |
level | str | Log level (only 'progress' forwarded). | 'verbose' |
log_type | str | Type for color coding in GUI. | 'default' |
Source code in goliat/gui/queue_gui.py
update_simulation_details ¶
Sends current simulation case details to GUI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sim_count | int | Current simulation number (1-indexed). | required |
total_sims | int | Total simulations in study. | required |
details | str | Human-readable description of current case. | required |
Source code in goliat/gui/queue_gui.py
update_overall_progress ¶
Updates overall study progress bar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_step | float | Current step number or percentage (0-100). | required |
total_steps | int | Total steps in study. | required |
Source code in goliat/gui/queue_gui.py
update_stage_progress ¶
update_stage_progress(stage_name: str, current_step: int, total_steps: int, sub_stage: str = '') -> None
Updates progress for a specific stage (setup/run/extract).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stage_name | str | Stage name like 'Setup' or 'Running Simulation'. | required |
current_step | int | Current step within stage. | required |
total_steps | int | Total steps for stage. | required |
sub_stage | str | Optional sub-stage description. | '' |
Source code in goliat/gui/queue_gui.py
start_stage_animation ¶
Starts animated progress bar for a stage.
Looks up time estimate from profiler and starts animation that progresses toward end_value over that duration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_name | str | Task name ('setup', 'run', 'extract', or subtask name). | required |
end_value | int | Target progress value (typically 100). | required |
Source code in goliat/gui/queue_gui.py
end_stage_animation ¶
update_profiler ¶
process_events ¶
GUI Components¶
goliat.gui.components.clock_manager ¶
Clock and ETA management component.
Classes¶
ClockManager ¶
Manages elapsed time, ETA, and window title updates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gui | ProgressGUI | ProgressGUI instance. | required |
Source code in goliat/gui/components/clock_manager.py
Functions¶
update ¶
Updates elapsed time, ETA labels, and window title.
Called every second by Qt timer. Calculates elapsed time from start, gets ETA from profiler (if available), and updates window title with current status and progress percentage.
The window title shows: [progress%] GOLIAT | Sim X/Y | Status where Status is 'Booting...', 'Running...', or 'Finished'.
Source code in goliat/gui/components/clock_manager.py
Functions¶
goliat.gui.components.data_manager ¶
Data management for GUI: CSV file handling and cleanup.
Classes¶
DataManager ¶
Manages CSV data files for time remaining and overall progress tracking.
Writes timestamped data points to CSV files for plotting and analysis. Automatically cleans up old files (keeps last 50) to prevent disk bloat. Creates unique session files using timestamp and process hash.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_dir | str | Directory where data files will be stored. | required |
verbose_logger | Logger | Logger for verbose messages. | required |
Source code in goliat/gui/components/data_manager.py
Functions¶
write_time_remaining ¶
Appends a time remaining data point to CSV.
Writes timestamp and hours remaining to session-specific CSV file. Used for plotting ETA trends over time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hours_remaining | float | Estimated hours remaining as float. | required |
Source code in goliat/gui/components/data_manager.py
write_overall_progress ¶
Appends an overall progress data point to CSV.
Writes timestamp and progress percentage to session-specific CSV file. Used for plotting progress trends over time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
progress_percent | float | Overall progress percentage (0-100). | required |
Source code in goliat/gui/components/data_manager.py
write_system_utilization ¶
write_system_utilization(cpu_percent: float, ram_percent: float, gpu_percent: Optional[float] = None, gpu_vram_percent: Optional[float] = None) -> None
Appends a system utilization data point to CSV.
Writes timestamp and CPU, RAM, GPU utilization, and GPU VRAM percentages to session-specific CSV file. Used for plotting utilization trends over time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cpu_percent | float | CPU utilization percentage (0-100). | required |
ram_percent | float | RAM utilization percentage (0-100). | required |
gpu_percent | Optional[float] | GPU utilization percentage (0-100), or None if unavailable. | None |
gpu_vram_percent | Optional[float] | GPU VRAM utilization percentage (0-100), or None if unavailable. | None |
Source code in goliat/gui/components/data_manager.py
Functions¶
goliat.gui.components.graph_manager ¶
Graph update management component.
Classes¶
GraphManager ¶
Manages time remaining and overall progress graph updates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gui | ProgressGUI | ProgressGUI instance. | required |
Source code in goliat/gui/components/graph_manager.py
Functions¶
update ¶
Updates time remaining, overall progress, and system utilization graphs (called every 5 seconds).
Gets current ETA and progress values, writes them to CSV files (via DataManager), and adds data points to matplotlib plots. The plots show trends over time, helping users see if ETA is converging or progress is steady.
This runs less frequently than clock updates (5s vs 1s) because plotting is more expensive and the trends don't need millisecond precision.
Source code in goliat/gui/components/graph_manager.py
Functions¶
goliat.gui.components.machine_id_detector ¶
Machine ID detection utility.
Classes¶
MachineIdDetector ¶
Detects machine ID (public IP or local IP) for web monitoring.
Tries external service first with retries, then falls back to local IP. Matches the logic in run_worker.py to ensure consistency.
Functions¶
detect staticmethod ¶
Auto-detects machine ID (public IP or local IP).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verbose_logger | Logger | Logger for verbose messages. | required |
Returns:
| Type | Description |
|---|---|
Optional[str] | Machine ID string, or None if detection failed. |
Source code in goliat/gui/components/machine_id_detector.py
goliat.gui.components.plots._matplotlib_imports ¶
Matplotlib imports with fallback handling for plotting components.
goliat.gui.components.plots.overall_progress_plot ¶
Overall progress plot component for GUI.
Classes¶
OverallProgressPlot ¶
Manages overall progress plot with real-time updates.
Creates a matplotlib line plot showing progress percentage trends over time. Updates dynamically as new data points arrive. Uses green color scheme to distinguish from time remaining plot. Y-axis fixed at 0-100%.
Source code in goliat/gui/components/plots/overall_progress_plot.py
Functions¶
add_data_point ¶
Adds data point and refreshes plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timestamp | datetime | Timestamp for the data point. | required |
progress_percent | float | Progress percentage as float. | required |
Source code in goliat/gui/components/plots/overall_progress_plot.py
Functions¶
goliat.gui.components.plots.pie_charts_manager ¶
Pie charts manager component for GUI.
Classes¶
PieChartsManager ¶
Manages four pie charts displaying timing breakdowns by phase and subtask.
Shows visual breakdown of execution time: - Top-left: Phase weights (setup/run/extract relative durations) - Top-right: Setup subtasks breakdown - Bottom-left: Run subtasks breakdown - Bottom-right: Extract subtasks breakdown
Updates automatically when profiler state changes. Filters out fake aggregated entries. Uses color palette for visual distinction.
Source code in goliat/gui/components/plots/pie_charts_manager.py
Functions¶
update ¶
Updates pie charts with timing data from profiler.
Collects phase weights and subtask timing data, filters out fake aggregated entries, and renders pie charts with percentages. Charts show relative time spent in each phase/subtask, helping identify bottlenecks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profiler | Profiler | Profiler instance containing timing data. | required |
Source code in goliat/gui/components/plots/pie_charts_manager.py
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 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 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | |
goliat.gui.components.plots.system_utilization_plot ¶
System utilization plot component for GUI.
Classes¶
SystemUtilizationPlot ¶
Manages system utilization plot with real-time updates.
Creates a matplotlib line plot showing CPU, RAM, GPU utilization, and GPU VRAM utilization percentages over time. Updates dynamically as new data points arrive. Y-axis extends to 105% (with ticks at 0, 20, 40, 60, 80, 100) to prevent clipping of lines at 100%. GPU lines only shown if GPU is available.
Source code in goliat/gui/components/plots/system_utilization_plot.py
Functions¶
add_data_point ¶
add_data_point(timestamp: datetime, cpu_percent: float, ram_percent: float, gpu_percent: Optional[float] = None, gpu_vram_percent: Optional[float] = None, cpu_cores: int = 0, total_ram_gb: float = 0.0, gpu_name: Optional[str] = None, total_gpu_vram_gb: float = 0.0) -> None
Adds data point and refreshes plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timestamp | datetime | Timestamp for the data point. | required |
cpu_percent | float | CPU utilization percentage (0-100). | required |
ram_percent | float | RAM utilization percentage (0-100). | required |
gpu_percent | Optional[float] | GPU utilization percentage (0-100), or None if unavailable. | None |
gpu_vram_percent | Optional[float] | GPU VRAM utilization percentage (0-100), or None if unavailable. | None |
cpu_cores | int | Number of CPU cores (for legend). | 0 |
total_ram_gb | float | Total RAM in GB (for legend). | 0.0 |
gpu_name | Optional[str] | GPU model name (for legend). | None |
total_gpu_vram_gb | float | Total GPU VRAM in GB (for legend). | 0.0 |
Source code in goliat/gui/components/plots/system_utilization_plot.py
Functions¶
goliat.gui.components.plots.time_remaining_plot ¶
Time remaining plot component for GUI.
Attributes¶
Classes¶
TimeRemainingPlot ¶
Manages time remaining plot with real-time updates.
Creates a matplotlib line plot showing ETA trends over time. Updates dynamically as new data points arrive, maintaining dark theme styling consistent with GUI. Tracks maximum time seen to set appropriate Y-axis limits.
Source code in goliat/gui/components/plots/time_remaining_plot.py
Functions¶
add_data_point ¶
Adds data point and refreshes plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timestamp | datetime | Timestamp for the data point. | required |
hours_remaining | float | Hours remaining as float. | required |
Source code in goliat/gui/components/plots/time_remaining_plot.py
Functions¶
goliat.gui.components.plots.utils ¶
Common utilities for plotting components.
Functions¶
get_ntp_utc_time ¶
Get current UTC time from NTP server (bypasses system clock).
Uses NTP to get accurate time independent of system clock issues. Caches the result for 30 seconds to minimize performance impact. Falls back to system time if NTP query fails.
Returns:
| Type | Description |
|---|---|
datetime | Current UTC time as timezone-aware datetime. |
Source code in goliat/gui/components/plots/utils.py
convert_to_utc_plus_one ¶
Convert a datetime to UTC+1 timezone.
Handles both naive (assumed UTC) and timezone-aware datetimes. Works reliably across VMs worldwide by always normalizing to UTC first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timestamp | datetime | Datetime to convert (can be naive or timezone-aware). If naive, assumes it's already in UTC (recommended usage). | required |
Returns:
| Type | Description |
|---|---|
datetime | Datetime in UTC+1 timezone (timezone-aware). |
Source code in goliat/gui/components/plots/utils.py
goliat.gui.components.progress_animation ¶
Progress bar animation logic.
Classes¶
ProgressAnimation ¶
Manages smooth progress bar animations based on estimated durations.
Provides linear interpolation animation for progress bars when explicit progress updates aren't available. Animates from current value to target (100%) over estimated duration, giving visual feedback during long tasks.
Updates every 50ms via Qt timer, calculating progress ratio from elapsed time and duration. Stops automatically when target is reached or stopped explicitly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
progress_bar | QProgressBar | Progress bar widget to animate (0-1000 range). | required |
timer | QTimer | QTimer instance for animation updates (50ms interval). | required |
debug | bool | Enable debug logging (currently unused). | False |
Source code in goliat/gui/components/progress_animation.py
Functions¶
start ¶
Starts smooth animation for progress bar.
Begins linear interpolation from current value to 100% over estimated duration. If already at 100%, skips animation. Starts Qt timer if not already active.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimated_duration | float | Estimated task duration in seconds (from profiler). | required |
end_step | int | Target step value (unused, always animates to 100%). | required |
Source code in goliat/gui/components/progress_animation.py
stop ¶
Stops the progress bar animation.
update ¶
Updates progress bar animation frame by frame.
Calculates current progress ratio based on elapsed time and duration, then interpolates between start and end values. Updates progress bar value and format string. Called every 50ms by Qt timer when active.
Source code in goliat/gui/components/progress_animation.py
goliat.gui.components.progress_manager ¶
Progress bar management component.
Classes¶
ProgressManager ¶
Manages progress bar updates for overall and stage progress.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gui | ProgressGUI | ProgressGUI instance. | required |
Source code in goliat/gui/components/progress_manager.py
Functions¶
update_overall ¶
Updates overall progress bar across all simulations.
The progress bar uses a 0-10000 range internally (for finer granularity), but displays as percentage. Overall progress accounts for completed simulations plus progress within current simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_step | float | Current step number (0-100 range) or percentage (0-100). | required |
total_steps | int | Total number of steps (typically 100). | required |
Source code in goliat/gui/components/progress_manager.py
update_stage ¶
Updates stage-specific progress bar and label.
Shows progress within current phase (setup/run/extract). Stops any active animation when explicit progress is set. Uses 0-1000 range internally for finer granularity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stage_name | str | Name of current stage (e.g., 'Setup', 'Running Simulation'). | required |
current_step | int | Current step within stage. | required |
total_steps | int | Total steps for the stage. | required |
sub_stage | str | Optional sub-stage description (currently unused). | '' |
Source code in goliat/gui/components/progress_manager.py
update_simulation_details ¶
Updates simulation counter and details labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sim_count | int | Current simulation number. | required |
total_sims | int | Total number of simulations. | required |
details | str | Description of current simulation case. | required |
Source code in goliat/gui/components/progress_manager.py
goliat.gui.components.queue_handler ¶
Queue message handler for processing messages from worker process.
Classes¶
QueueHandler ¶
Handles processing of messages from the worker process queue.
Polls the multiprocessing queue and dispatches messages to appropriate GUI update methods. This decouples message handling from queue polling, making the code cleaner and easier to test.
Message types: - 'status': Log message with color coding - 'overall_progress': Update overall progress bar - 'stage_progress': Update stage progress bar - 'start_animation': Start animated progress bar - 'end_animation': Stop animation - 'profiler_update': Update profiler state and refresh timing displays - 'sim_details': Update simulation counter and details - 'finished': Study completed successfully - 'fatal_error': Study failed with fatal error
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gui_instance | ProgressGUI | ProgressGUI instance to update with messages. | required |
Source code in goliat/gui/components/queue_handler.py
Functions¶
process_queue ¶
Processes messages from worker process queue and updates UI accordingly.
Polls queue non-blockingly and processes all available messages in one call. Handles different message types by calling appropriate GUI methods. Catches and logs exceptions to prevent one bad message from crashing GUI.
This method is called every 100ms by Qt timer to keep UI responsive.
After processing each message for the GUI, forwards a copy to WebGUIBridge if it exists (for web dashboard monitoring).
Source code in goliat/gui/components/queue_handler.py
goliat.gui.components.screenshot_capture ¶
Screenshot capture component for GUI tabs.
Classes¶
ScreenshotCapture ¶
Captures screenshots of GUI tabs for web monitoring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gui | ProgressGUI | ProgressGUI instance with tabs to capture. | required |
Source code in goliat/gui/components/screenshot_capture.py
Functions¶
capture_all_tabs ¶
Capture all GUI tabs as JPEG bytes.
Captures each tab widget individually without switching tabs, so it doesn't interfere with the user's current view.
Returns:
| Type | Description |
|---|---|
Dict[str, bytes] | Dictionary mapping tab names to JPEG bytes. |
Dict[str, bytes] | Empty dict if capture fails or PySide6 not available. |
Source code in goliat/gui/components/screenshot_capture.py
goliat.gui.components.status_manager ¶
Status management for GUI: colors, counting, and formatting.
Classes¶
StatusManager ¶
Manages status colors, counting, and message formatting for GUI.
Handles color mapping for different log types (info, warning, error, etc.), counts warnings and errors for display in error summary, and formats messages with HTML color styling for the QTextEdit widget.
Note: Uses white for 'progress' messages in GUI (unlike terminal colors) because all messages shown here are progress updates. This improves readability in the dark-themed GUI.
Source code in goliat/gui/components/status_manager.py
Functions¶
get_color ¶
Gets HTML color code for a log type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_type | str | Type of log message. | required |
Returns:
| Type | Description |
|---|---|
str | HTML color code (hex). |
format_message ¶
Formats message with HTML color styling.
Preserves leading spaces by converting them to entities, then wraps message in a tag with appropriate color style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message | str | Message text to format. | required |
log_type | str | Log type for color selection. | 'default' |
Returns:
| Type | Description |
|---|---|
str | HTML-formatted message string ready for QTextEdit. |
Source code in goliat/gui/components/status_manager.py
record_log ¶
Records log entry and updates warning/error counters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_type | str | Type of log message. | required |
Source code in goliat/gui/components/status_manager.py
get_error_summary ¶
Gets formatted summary of warnings and errors with optional web status.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
web_connected | bool | Whether web dashboard is connected (optional). | False |
Returns:
| Type | Description |
|---|---|
str | Formatted string with emoji indicators and counts. |
Source code in goliat/gui/components/status_manager.py
goliat.gui.components.system_monitor ¶
System resource monitoring component for GUI.
Classes¶
SystemMonitor ¶
Monitors system resource utilization (CPU, RAM, GPU).
Provides methods to get current CPU usage percentage, RAM usage in GB, and GPU utilization percentage (via nvidia-smi). Gracefully handles missing dependencies (psutil) and unavailable GPU.
Functions¶
get_cpu_utilization staticmethod ¶
Gets current CPU utilization percentage.
Uses non-blocking approach by calling cpu_percent() without interval, which returns utilization since last call. For accurate measurement, ensure this is called at consistent intervals (e.g., every 1 second).
Returns:
| Type | Description |
|---|---|
float | CPU usage percentage (0-100), or 0.0 if psutil unavailable. |
Source code in goliat/gui/components/system_monitor.py
get_ram_utilization staticmethod ¶
Gets current RAM usage and total RAM.
Returns:
| Type | Description |
|---|---|
Tuple[float, float] | Tuple of (used_GB, total_GB), or (0.0, 0.0) if psutil unavailable. |
Source code in goliat/gui/components/system_monitor.py
get_ram_utilization_detailed staticmethod ¶
Gets RAM utilization with and without cacheable memory.
Returns:
| Type | Description |
|---|---|
float | Tuple of (percent_with_cache, percent_without_cache, total_GB), or (0.0, 0.0, 0.0) if psutil unavailable. |
float |
|
float |
|
Tuple[float, float, float] |
|
Source code in goliat/gui/components/system_monitor.py
get_gpu_vram_utilization staticmethod ¶
Gets current GPU VRAM usage and total VRAM.
Returns:
| Type | Description |
|---|---|
Optional[Tuple[float, float]] | Tuple of (used_GB, total_GB), or None if nvidia-smi unavailable. |
Source code in goliat/gui/components/system_monitor.py
get_gpu_utilization staticmethod ¶
Gets current GPU utilization percentage via nvidia-smi.
Returns:
| Type | Description |
|---|---|
Optional[float] | GPU usage percentage (0-100), or None if nvidia-smi unavailable. |
Source code in goliat/gui/components/system_monitor.py
get_gpu_name staticmethod ¶
Gets GPU name via nvidia-smi.
Returns:
| Type | Description |
|---|---|
Optional[str] | GPU name (e.g., "RTX 4090"), or None if nvidia-smi unavailable. |
Source code in goliat/gui/components/system_monitor.py
get_cpu_cores staticmethod ¶
Gets number of CPU cores.
Returns:
| Type | Description |
|---|---|
int | Number of CPU cores, or 0 if psutil unavailable. |
Source code in goliat/gui/components/system_monitor.py
get_total_ram_gb staticmethod ¶
Gets total RAM in GB.
Returns:
| Type | Description |
|---|---|
float | Total RAM in GB, or 0.0 if psutil unavailable. |
Source code in goliat/gui/components/system_monitor.py
is_gpu_available staticmethod ¶
Checks if GPU is available via nvidia-smi.
Returns:
| Type | Description |
|---|---|
bool | True if nvidia-smi is available and returns successfully, False otherwise. |
Source code in goliat/gui/components/system_monitor.py
goliat.gui.components.timings_table ¶
Timings table component for displaying profiling statistics.
Classes¶
TimingsTable ¶
Manages timings table displaying profiling statistics.
Shows execution time statistics (mean, median, min, max, percentiles) for all phases and subtasks. Filters out fake aggregated entries and organizes data by phase for easy inspection. Updates automatically when profiler state changes via queue messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table_widget | QTableWidget | QTableWidget instance to populate with timing data. | required |
Source code in goliat/gui/components/timings_table.py
Functions¶
update ¶
Populates table with timing statistics from profiler.
Collects all phase and subtask timing data, computes statistics (mean, median, percentiles), and displays in table. Filters out fake aggregated entries that shouldn't be shown.
Statistics computed: - Mean, median, min, max - 10th, 25th, 75th, 90th percentiles
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profiler | Profiler | Profiler instance containing timing data. | required |
Source code in goliat/gui/components/timings_table.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | |
goliat.gui.components.tray_manager ¶
Tray icon management component.
Classes¶
TrayManager ¶
TrayManager(parent_widget: QWidget, show_callback: Callable[[], None], close_callback: Callable[[], None])
Manages system tray icon and menu.
Handles system tray integration for background operation. Shows tray icon with favicon, provides context menu (Show/Exit), and handles click events to restore window. Allows users to minimize GUI to tray and continue monitoring via icon.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent_widget | QWidget | Parent widget (ProgressGUI window). | required |
show_callback | Callable[[], None] | Function to call when restoring window. | required |
close_callback | Callable[[], None] | Function to call when exiting application. | required |
Source code in goliat/gui/components/tray_manager.py
goliat.gui.components.ui_builder ¶
UI builder component for constructing the ProgressGUI interface.
Classes¶
UIBuilder ¶
Builds UI components for ProgressGUI.
Provides static methods to construct the complete GUI layout, including tabs, progress bars, plots, tables, and buttons. Handles styling via Qt stylesheets for dark theme appearance.
Functions¶
get_icon_path staticmethod ¶
Gets path to window icon.
Returns:
| Type | Description |
|---|---|
str | Absolute path to favicon.svg. |
Source code in goliat/gui/components/ui_builder.py
build staticmethod ¶
Builds complete UI for the GUI instance.
Sets up window properties, applies stylesheet, creates tabs (Progress, Timings, Piecharts, Time Remaining, Overall Progress), and adds control buttons. Attaches components to gui_instance for later access.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gui_instance | ProgressGUI | ProgressGUI instance to build UI for. | required |
status_manager | StatusManager | StatusManager instance for error summary display. | required |
Source code in goliat/gui/components/ui_builder.py
goliat.gui.components.utilization_manager ¶
System utilization management component.
Classes¶
UtilizationManager ¶
Manages CPU, RAM, and GPU utilization displays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gui | ProgressGUI | ProgressGUI instance. | required |
Source code in goliat/gui/components/utilization_manager.py
Functions¶
update ¶
Updates CPU, RAM, and GPU utilization displays.
Called every second by Qt timer. Gets current utilization values from SystemMonitor and updates the progress bars and labels.
Source code in goliat/gui/components/utilization_manager.py
update_plot ¶
Updates the system utilization plot with current values.
Called less frequently (every 2 seconds) to avoid excessive plot updates. Writes to CSV and adds data point to plot.
Source code in goliat/gui/components/utilization_manager.py
Functions¶
goliat.gui.components.web_bridge_manager ¶
Web bridge manager component for remote monitoring.
Classes¶
WebBridgeManager ¶
Manages web GUI bridge initialization and status updates.
Handles connection to web dashboard, collects system info, and manages bridge lifecycle. Keeps web bridge code exactly as is per requirements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gui | ProgressGUI | ProgressGUI instance. | required |
server_url | str | Web dashboard server URL. | required |
machine_id | Optional[str] | Machine ID for identification. | required |
Source code in goliat/gui/components/web_bridge_manager.py
Functions¶
initialize ¶
Initializes web GUI bridge for remote monitoring.
Sets up connection to web dashboard, collects system info, and starts the bridge. Handles errors gracefully to allow GUI to continue without web monitoring.
Source code in goliat/gui/components/web_bridge_manager.py
sync_progress ¶
Periodically sync actual GUI progress bar values to web dashboard.
Sends the current progress bar values to the web bridge so the dashboard always shows the actual progress, even if progress messages aren't sent.
Source code in goliat/gui/components/web_bridge_manager.py
stop ¶
Stops the web bridge and screenshot capture.
Source code in goliat/gui/components/web_bridge_manager.py
send_finished ¶
Sends final status update to web before stopping bridge.
Sends multiple 100% progress updates with delays to ensure the cloud receives them even if it's lagging behind. This prevents tasks from appearing stuck at 99% on the web interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error | bool | Whether study finished with errors. | False |
Source code in goliat/gui/components/web_bridge_manager.py
Scripts¶
Entry point scripts for running studies and analysis.
Scripts
These are top-level scripts for running studies. They are not part of the core API but are included for reference.
goliat study- Main entry point for running studiesgoliat analyze- Entry point for post-processing analysisgoliat parallel- Script for running parallel study batchesgoliat free-space- Script for free-space validation runsgoliat init- Initialize GOLIAT environment (install dependencies, setup)goliat status- Show setup status and environment informationgoliat validate- Validate configuration filesgoliat version- Show GOLIAT version information