Skip to content

API Reference

Complete API documentation for GOLIAT, organized by module category.

Core Modules

Core functionality for configuration, logging, and utilities.

Antenna

goliat.antenna.Antenna

Antenna(config: Config, frequency_mhz: int)

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
def __init__(self, config: "Config", frequency_mhz: int):
    """Initializes the Antenna object.

    Args:
        config: The configuration object containing antenna settings.
        frequency_mhz: The operating frequency in MHz.
    """
    self.config = config
    self.frequency_mhz = frequency_mhz
    self.antenna_config = self.config["antenna_config"] or {}

Methods:

get_config_for_frequency

get_config_for_frequency() -> dict

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
def get_config_for_frequency(self) -> dict:
    """Gets the antenna configuration for the current frequency.

    Raises:
        ValueError: If no configuration is defined for the frequency.

    Returns:
        The antenna configuration dictionary.
    """
    freq_str = str(self.frequency_mhz)
    if freq_str not in self.antenna_config:
        raise ValueError(f"Antenna configuration not defined for frequency: {self.frequency_mhz} MHz")
    return self.antenna_config[freq_str]

get_model_type

get_model_type() -> str

Returns the antenna model type string.

Source code in goliat/antenna.py
def get_model_type(self) -> str:
    """Returns the antenna model type string."""
    return str(self.get_config_for_frequency().get("model_type"))

get_source_entity_name

get_source_entity_name() -> str

Returns the source entity name from the antenna config.

Source code in goliat/antenna.py
def get_source_entity_name(self) -> str:
    """Returns the source entity name from the antenna config."""
    return str(self.get_config_for_frequency().get("source_name"))

get_centered_antenna_path

get_centered_antenna_path(centered_antennas_dir: str) -> str

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
def get_centered_antenna_path(self, centered_antennas_dir: str) -> str:
    """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.

    Args:
        centered_antennas_dir: The directory for centered antenna files.

    Returns:
        The absolute path to the centered antenna model file.

    Raises:
        FileNotFoundError: If no antenna files are found in the directory.
    """
    antenna_filename = f"{self.frequency_mhz}MHz_centered.sab"
    antenna_path = os.path.join(centered_antennas_dir, antenna_filename)

    # Check if exact file exists
    if os.path.exists(antenna_path) and os.path.isfile(antenna_path):
        return antenna_path

    # File doesn't exist, try to find nearest frequency
    logger.warning(f"Antenna file for {self.frequency_mhz} MHz not found: {antenna_path}. Searching for nearest available frequency...")

    # Scan directory for available antenna files
    if not os.path.exists(centered_antennas_dir):
        raise FileNotFoundError(f"Antenna directory does not exist: {centered_antennas_dir}")

    available_files = []
    pattern = re.compile(r"(\d+)MHz_centered\.sab$")

    try:
        for filename in os.listdir(centered_antennas_dir):
            match = pattern.match(filename)
            if match:
                freq = int(match.group(1))
                filepath = os.path.join(centered_antennas_dir, filename)
                if os.path.isfile(filepath):
                    available_files.append((freq, filepath))
    except (OSError, PermissionError) as e:
        raise FileNotFoundError(f"Could not read antenna directory {centered_antennas_dir}: {e}") from e

    if not available_files:
        raise FileNotFoundError(f"No antenna files found in directory: {centered_antennas_dir}")

    # Find nearest frequency
    available_files.sort(key=lambda x: x[0])  # Sort by frequency
    nearest_freq, nearest_path = min(available_files, key=lambda x: abs(x[0] - self.frequency_mhz))

    logger.warning(f"Using antenna file for {nearest_freq} MHz instead of {self.frequency_mhz} MHz. File: {nearest_path}")

    return nearest_path

Colors

goliat.colors

Functions:

init_colorama

init_colorama()

Initialize colorama for 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
def init_colorama():
    """Initialize colorama for current environment.

    Preserves ANSI codes when stdout is piped (e.g., in Jupyter notebooks)
    by checking for JUPYTER_NOTEBOOK or COLORAMA_STRIP environment variables.
    """
    # Preserve ANSI codes when stdout is piped (e.g., in Jupyter notebooks)
    strip_codes = os.environ.get("COLORAMA_STRIP", "").lower() == "0" or os.environ.get("JUPYTER_NOTEBOOK", "").lower() == "1"
    init(autoreset=True, strip=not strip_codes, convert=False if strip_codes else True)

get_color

get_color(log_type: str) -> str

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
def get_color(log_type: str) -> str:
    """Returns the colorama color code for a log type, or white if not found.

    Args:
        log_type: Log type key (e.g., 'info', 'warning', 'error').

    Returns:
        Colorama color code string.
    """
    return COLOR_MAP.get(log_type, Fore.WHITE)

Constants

goliat.constants

Constants used throughout the GOLIAT codebase.

This module centralizes magic numbers, thresholds, and hardcoded values to improve maintainability and reduce technical debt.

Attributes

MIN_H5_FILE_SIZE_BYTES module-attribute

MIN_H5_FILE_SIZE_BYTES = 8 * 1024 * 1024

Minimum size in bytes for a valid H5 output file.

iSolve sometimes creates incomplete files that are smaller than this threshold. Files smaller than this are considered invalid.

H5_SIZE_INCREASE_THRESHOLD module-attribute

H5_SIZE_INCREASE_THRESHOLD = 1.1

Minimum size increase ratio for Output.h5 compared to Input.h5.

Output.h5 must be at least 10% bigger than Input.h5 to ensure the simulation completed successfully. This helps detect incomplete or corrupted output files.

PLOT_Y_AXIS_BUFFER_MULTIPLIER module-attribute

PLOT_Y_AXIS_BUFFER_MULTIPLIER = 1.1

Multiplier for y-axis maximum in plots.

Adds 10% buffer above the maximum value for better visualization.

Data Extractor

goliat.data_extractor

Functions:

get_parameter_from_json

get_parameter_from_json(file_path: str, json_path: str) -> Any

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
def get_parameter_from_json(file_path: str, json_path: str) -> Any:
    """Extracts a nested value from a JSON file using dot notation.

    Args:
        file_path: Path to the JSON file.
        json_path: Dot-separated path like 'section.subsection.key'.

    Returns:
        The value at the path, or None if not found.
    """
    if not os.path.exists(file_path):
        return None

    try:
        with open(file_path, "r") as f:
            data = json.load(f)
    except (json.JSONDecodeError, ValueError):
        return None

    keys = json_path.split(".")
    value = data
    for key in keys:
        if isinstance(value, dict) and key in value:
            value = value[key]
        else:
            return None
    return value

get_parameter

get_parameter(source_config: Dict[str, Any], context: Dict[str, Any]) -> Any

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
def get_parameter(source_config: Dict[str, Any], context: Dict[str, Any]) -> Any:
    """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).

    Args:
        source_config: Dict with 'source_type', 'file_path_template', 'json_path'.
        context: Values for formatting file paths.

    Returns:
        The retrieved value, or None on error.
    """
    source_type = source_config.get("source_type")

    if source_type == "json":
        file_path_template = source_config.get("file_path_template")
        if not file_path_template:
            return None

        try:
            file_path = file_path_template.format(**context)
        except KeyError as e:
            import logging

            logging.getLogger("verbose").error(f"Error: Missing context for placeholder in file_path_template: {e}")
            return None

        json_path = source_config.get("json_path")
        if not json_path:
            return None

        project_root = context.get("project_root", "")
        full_path = os.path.join(project_root, file_path)

        return get_parameter_from_json(full_path, json_path)

    # Future extension for other data source types
    # elif source_type == 'simulation':
    #     # ... implementation for extracting from simulation results ...
    #     pass

    else:
        import logging

        logging.getLogger("verbose").error(f"Error: Unsupported source type '{source_type}'")
        return None

Gui Manager

goliat.gui_manager

Main GUI manager module.

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
def __init__(
    self,
    queue: Queue,
    stop_event: Event,
    profiler: "Profiler",
    progress_logger: Logger,
    verbose_logger: Logger,
) -> None:
    """Sets up the queue GUI proxy.

    Args:
        queue: Multiprocessing queue for IPC.
        stop_event: Event flagging user cancellation.
        profiler: Profiler for ETA calculations.
        progress_logger: Logger for progress-level messages.
        verbose_logger: Logger for detailed messages.
    """
    self.queue: Queue = queue
    self.stop_event: Event = stop_event
    self.profiler: "Profiler" = profiler
    self.progress_logger: Logger = progress_logger
    self.verbose_logger: Logger = verbose_logger
Methods:
log
log(message: str, level: str = 'verbose', log_type: str = 'default') -> None

Sends a log message to the GUI via queue.

All messages are forwarded through the queue for terminal output (S4L 9.2 fix). Progress messages update the GUI status box; verbose messages only print to terminal.

Parameters:

Name Type Description Default
message str

Log message text.

required
level str

Log level ('progress' or 'verbose').

'verbose'
log_type str

Type for color coding in GUI.

'default'
Source code in goliat/gui/queue_gui.py
def log(self, message: str, level: str = "verbose", log_type: str = "default") -> None:
    """Sends a log message to the GUI via queue.

    All messages are forwarded through the queue for terminal output (S4L 9.2 fix).
    Progress messages update the GUI status box; verbose messages only print to terminal.

    Args:
        message: Log message text.
        level: Log level ('progress' or 'verbose').
        log_type: Type for color coding in GUI.
    """
    import time

    # Use monotonic time with a small increment to ensure unique timestamps
    # even for messages sent in rapid succession
    if not hasattr(self, "_last_timestamp"):
        self._last_timestamp = 0.0
    current_time = time.time()
    # Ensure timestamp is always increasing, even if system clock jumps backward
    if current_time <= self._last_timestamp:
        self._last_timestamp += 0.000001  # 1 microsecond increment
    else:
        self._last_timestamp = current_time

    # Determine message type based on level
    # 'status' messages update GUI status box AND print to terminal
    # 'terminal_only' messages only print to terminal (for verbose logs)
    msg_type = "status" if level == "progress" else "terminal_only"

    self.queue.put(
        {
            "type": msg_type,
            "message": message,
            "log_type": log_type,
            "timestamp": self._last_timestamp,
        }
    )
update_simulation_details
update_simulation_details(sim_count: int, total_sims: int, details: str) -> None

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
def update_simulation_details(self, sim_count: int, total_sims: int, details: str) -> None:
    """Sends current simulation case details to GUI.

    Args:
        sim_count: Current simulation number (1-indexed).
        total_sims: Total simulations in study.
        details: Human-readable description of current case.
    """
    self.queue.put(
        {
            "type": "sim_details",
            "count": sim_count,
            "total": total_sims,
            "details": details,
        }
    )
update_overall_progress
update_overall_progress(current_step: float, total_steps: int) -> None

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
def update_overall_progress(self, current_step: float, total_steps: int) -> None:
    """Updates overall study progress bar.

    Args:
        current_step: Current step number or percentage (0-100).
        total_steps: Total steps in study.
    """
    self.queue.put({"type": "overall_progress", "current": current_step, "total": total_steps})
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
def update_stage_progress(self, stage_name: str, current_step: int, total_steps: int, sub_stage: str = "") -> None:
    """Updates progress for a specific stage (setup/run/extract).

    Args:
        stage_name: Stage name like 'Setup' or 'Running Simulation'.
        current_step: Current step within stage.
        total_steps: Total steps for stage.
        sub_stage: Optional sub-stage description.
    """
    self.queue.put(
        {
            "type": "stage_progress",
            "name": stage_name,
            "current": current_step,
            "total": total_steps,
            "sub_stage": sub_stage,
        }
    )
start_stage_animation
start_stage_animation(task_name: str, end_value: int) -> None

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
def start_stage_animation(self, task_name: str, end_value: int) -> None:
    """Starts animated progress bar for a stage.

    Looks up time estimate from profiler and starts animation that
    progresses toward end_value over that duration.

    Args:
        task_name: Task name ('setup', 'run', 'extract', or subtask name).
        end_value: Target progress value (typically 100).
    """
    if task_name in ["setup", "run", "extract"]:
        estimate = self.profiler.profiling_config.get(f"avg_{task_name}_time", 60)
    else:
        estimate = self.profiler.get_subtask_estimate(task_name)
    self.queue.put({"type": "start_animation", "estimate": estimate, "end_value": end_value})
end_stage_animation
end_stage_animation() -> None

Stops the current animated progress bar.

Source code in goliat/gui/queue_gui.py
def end_stage_animation(self) -> None:
    """Stops the current animated progress bar."""
    self.queue.put({"type": "end_animation"})
update_profiler
update_profiler() -> None

Sends profiler state to GUI for ETA display.

Source code in goliat/gui/queue_gui.py
def update_profiler(self) -> None:
    """Sends profiler state to GUI for ETA display."""
    self.queue.put({"type": "profiler_update", "profiler": self.profiler})
process_events
process_events() -> None

No-op for interface compatibility with ProgressGUI.

Source code in goliat/gui/queue_gui.py
def process_events(self) -> None:
    """No-op for interface compatibility with ProgressGUI."""
    pass
is_stopped
is_stopped() -> bool

Checks if user requested cancellation via GUI.

Source code in goliat/gui/queue_gui.py
def is_stopped(self) -> bool:
    """Checks if user requested cancellation via GUI."""
    return self.stop_event.is_set()

ProgressGUI

ProgressGUI(queue: Queue, stop_event: Event, process: Process, init_window_title: str = '', use_web: bool = True, auto_close: bool = False)

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 - 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.

''
use_web bool

Whether to enable web bridge for remote monitoring.

True
auto_close bool

Whether to automatically close GUI on successful completion.

False
Source code in goliat/gui/progress_gui.py
def __init__(
    self,
    queue: Queue,
    stop_event: Event,
    process: Process,
    init_window_title: str = "",
    use_web: bool = True,
    auto_close: bool = False,
) -> None:
    """Sets up the GUI window and all components.

    Initializes data manager, status manager, UI builder, timers, and
    queue handler. Sets up Qt timers for periodic updates (queue polling,
    clock updates, graph refreshes).

    Args:
        queue: Queue for receiving messages from worker process.
        stop_event: Event to signal termination to worker process.
        process: Worker process running the study.
        init_window_title: Initial window title.
        use_web: Whether to enable web bridge for remote monitoring.
        auto_close: Whether to automatically close GUI on successful completion.
    """
    super().__init__()
    self.queue: Queue = queue
    self.stop_event: Event = stop_event
    self.process: Process = process
    self.start_time: float = time.monotonic()
    self.progress_logger: logging.Logger = logging.getLogger("progress")
    self.verbose_logger: logging.Logger = logging.getLogger("verbose")
    self.init_window_title: str = init_window_title
    self.auto_close: bool = auto_close
    self.DEBUG: bool = False
    self.study_is_finished: bool = False
    self.study_had_errors: bool = False
    self.child_exit_code: int = 0  # Exit code from child process (42 = memory error)

    self.total_simulations: int = 0
    self.current_simulation_count: int = 0

    # Initialize components
    self._initialize_components()

    # Auto-detect machine ID
    self.machine_id = MachineIdDetector.detect(self.verbose_logger)
    self.server_url = "https://monitor.goliat.waves-ugent.be"

    # Build UI
    UIBuilder.build(self, self.status_manager)

    # Initialize managers
    self.web_bridge_manager = WebBridgeManager(self, self.server_url, self.machine_id, use_web=use_web)
    self.progress_manager = ProgressManager(self)
    self.clock_manager = ClockManager(self)
    self.utilization_manager = UtilizationManager(self)
    self.graph_manager = GraphManager(self)

    # Initialize web GUI bridge after UI is built (so we can set callback)
    self.web_bridge_manager.initialize()

    # Initialize animation and other components
    self._initialize_animation()
    self._initialize_managers()
    self._setup_timers()
    self._initialize_system_monitoring()
Methods:
update_overall_progress
update_overall_progress(current_step: float, total_steps: int) -> None

Updates overall progress bar across all simulations.

Source code in goliat/gui/progress_gui.py
def update_overall_progress(self, current_step: float, total_steps: int) -> None:
    """Updates overall progress bar across all simulations."""
    self.progress_manager.update_overall(current_step, total_steps)
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
def update_stage_progress(self, stage_name: str, current_step: int, total_steps: int, sub_stage: str = "") -> None:
    """Updates stage-specific progress bar and label."""
    self.progress_manager.update_stage(stage_name, current_step, total_steps, sub_stage)
start_stage_animation
start_stage_animation(estimated_duration: float, end_step: int) -> None

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
def start_stage_animation(self, estimated_duration: float, end_step: int) -> None:
    """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.

    Args:
        estimated_duration: Estimated task duration in seconds (from profiler).
        end_step: Target step value (unused, always animates to 100%).
    """
    if self.DEBUG:
        self.update_status(f"DEBUG: start_stage_animation received: duration={estimated_duration:.2f}s, end_step={end_step}")
    self.progress_animation.start(estimated_duration, end_step)
end_stage_animation
end_stage_animation() -> None

Stops stage progress bar animation.

Source code in goliat/gui/progress_gui.py
def end_stage_animation(self) -> None:
    """Stops stage progress bar animation."""
    self.progress_animation.stop()
update_animation
update_animation() -> None

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
def update_animation(self) -> None:
    """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.
    """
    self.progress_animation.update()

    # Sync overall progress based on stage animation
    if self.profiler and self.profiler.current_phase:
        current_value = self.stage_progress_bar.value()
        percent = (current_value / 1000) * 100
        progress = self.profiler.get_weighted_progress(self.profiler.current_phase, percent / 100.0)
        self.progress_manager.update_overall(progress, 100)
update_simulation_details
update_simulation_details(sim_count: int, total_sims: int, details: str) -> None

Updates simulation counter and details labels.

Source code in goliat/gui/progress_gui.py
def update_simulation_details(self, sim_count: int, total_sims: int, details: str) -> None:
    """Updates simulation counter and details labels."""
    self.progress_manager.update_simulation_details(sim_count, total_sims, details)
update_status
update_status(message: str, log_type: str = 'default') -> None

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
def update_status(self, message: str, log_type: str = "default") -> None:
    """Appends message to status log with color formatting.

    Args:
        message: Message text.
        log_type: Log type for color coding.
    """
    self.status_manager.record_log(log_type)
    # Update error counter with current web status
    web_connected = False
    if (
        hasattr(self, "web_bridge_manager")
        and self.web_bridge_manager.web_bridge
        and hasattr(self.web_bridge_manager.web_bridge, "is_connected")
    ):
        web_connected = self.web_bridge_manager.web_bridge.is_connected
    self.error_counter_label.setText(self.status_manager.get_error_summary(web_connected=web_connected))
    formatted_message = self.status_manager.format_message(message, log_type)
    self.status_text.append(formatted_message)
update_utilization
update_utilization() -> None

Updates CPU, RAM, and GPU utilization displays.

Source code in goliat/gui/progress_gui.py
def update_utilization(self) -> None:
    """Updates CPU, RAM, and GPU utilization displays."""
    self.utilization_manager.update()
update_utilization_plot
update_utilization_plot() -> None

Updates the system utilization plot with current values.

Source code in goliat/gui/progress_gui.py
def update_utilization_plot(self) -> None:
    """Updates the system utilization plot with current values."""
    self.utilization_manager.update_plot()
update_clock
update_clock() -> None

Updates elapsed time, ETA labels, and window title.

Source code in goliat/gui/progress_gui.py
def update_clock(self) -> None:
    """Updates elapsed time, ETA labels, and window title."""
    self.clock_manager.update()
update_graphs
update_graphs() -> None

Updates time remaining and overall progress graphs.

Source code in goliat/gui/progress_gui.py
def update_graphs(self) -> None:
    """Updates time remaining and overall progress graphs."""
    self.graph_manager.update()
hide_to_tray
hide_to_tray() -> None

Hides main window and shows system tray icon.

Source code in goliat/gui/progress_gui.py
def hide_to_tray(self) -> None:
    """Hides main window and shows system tray icon."""
    self.hide()
    self.tray_manager.show()
show_from_tray
show_from_tray() -> None

Shows main window from system tray.

Source code in goliat/gui/progress_gui.py
def show_from_tray(self) -> None:
    """Shows main window from system tray."""
    self.show()
    self.tray_manager.hide()
stop_study
stop_study() -> None

Sends stop signal to worker process.

Source code in goliat/gui/progress_gui.py
def stop_study(self) -> None:
    """Sends stop signal to worker process."""
    message = "--- Sending stop signal to study process ---"
    self.progress_logger.info(message, extra={"log_type": "warning"})
    self.verbose_logger.info(message, extra={"log_type": "warning"})
    self.update_status(message, log_type="warning")
    self.stop_button.setEnabled(False)
    self.tray_button.setEnabled(False)
    self.stop_event.set()
study_finished
study_finished(error: bool = False, memory_error: bool = False) -> None

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).

For memory errors (exit code 42), the GUI auto-closes even with errors so the batch worker can retry the assignment.

Parameters:

Name Type Description Default
error bool

Whether study finished with errors (affects UI styling).

False
memory_error bool

Whether this was a memory error (exit code 42). Memory errors auto-close to allow batch retry.

False
Source code in goliat/gui/progress_gui.py
def study_finished(self, error: bool = False, memory_error: bool = False) -> None:
    """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).

    For memory errors (exit code 42), the GUI auto-closes even with errors
    so the batch worker can retry the assignment.

    Args:
        error: Whether study finished with errors (affects UI styling).
        memory_error: Whether this was a memory error (exit code 42).
                     Memory errors auto-close to allow batch retry.
    """
    self.study_is_finished = True
    self.study_had_errors = error
    self.clock_timer.stop()
    self.queue_timer.stop()
    self.graph_timer.stop()
    self.utilization_timer.stop()
    self.utilization_plot_timer.stop()
    self.progress_sync_timer.stop()
    self.progress_animation.stop()
    if not error:
        self.update_status("--- Study Finished ---", log_type="success")
        self.overall_progress_bar.setValue(self.overall_progress_bar.maximum())
        self.stage_label.setText("Finished")
    elif memory_error:
        self.update_status("--- Study Stopped: Memory Error (will retry) ---", log_type="fatal")
        self.stage_label.setText("Memory Error")
    else:
        self.update_status("--- Study Finished with Errors ---", log_type="fatal")
        self.stage_label.setText("Error")

    self.stop_button.setEnabled(False)
    self.tray_button.setEnabled(False)

    # Send final status update to web before stopping bridge
    self.web_bridge_manager.send_finished(error)

    self.update_clock()  # Final title update

    # Instead of auto-closing, show a message that user can close the window
    if not error:
        self.progress_logger.info("All done! You may close this window now.", extra={"log_type": "success"})
        self.update_status("\n✓ All done! You may close this window now.", log_type="success")
        # Auto-close if enabled (used by batch worker mode)
        if self.auto_close:
            self.progress_logger.info("Auto-closing GUI in 2 seconds...", extra={"log_type": "info"})
            from PySide6.QtCore import QTimer as _QTimer

            _QTimer.singleShot(2000, self.close)
    elif memory_error:
        # Memory errors should ALWAYS auto-close so the process can be restarted to free GPU memory.
        # This is required for both batch worker retry logic and persistent mode retry logic.
        # Unlike normal errors, memory errors cannot be resolved without a full process restart.
        self.progress_logger.info("Memory error detected. Auto-closing for retry...", extra={"log_type": "warning"})
        self.update_status("\n⚠ Memory error detected. Auto-closing for retry...", log_type="warning")
        from PySide6.QtCore import QTimer as _QTimer

        _QTimer.singleShot(2000, self.close)
    else:
        self.progress_logger.info("Finished with errors. You may close this window now.", extra={"log_type": "warning"})
        self.update_status("\n✓ Finished with errors. You may close this window now.", log_type="warning")
closeEvent
closeEvent(event: Any) -> None

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
def closeEvent(self, event: Any) -> None:
    """Handles window close event, ensuring worker process termination.

    Args:
        event: Close event.
    """
    if self.tray_manager.is_visible():
        self.tray_manager.hide()

    if self.process.is_alive():
        self.progress_logger.info("Terminating study process...", extra={"log_type": "warning"})
        self.process.terminate()
        self.process.join(timeout=5)

    # Stop web bridge if enabled
    self.web_bridge_manager.stop()

    shutdown_loggers()
    event.accept()

Logging Manager

goliat.logging_manager.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.).

Methods:

format

format(record: LogRecord) -> str

Adds color codes to log messages based on log_type.

Source code in goliat/logging_manager.py
def format(self, record: logging.LogRecord) -> str:
    """Adds color codes to log messages based on log_type."""
    log_type = getattr(record, "log_type", "default")
    message_color = get_color(log_type)
    caller_color = get_color("caller")
    message = record.getMessage()
    caller_info = getattr(record, "caller_info", "")
    return f"{message_color}{message}{Style.RESET_ALL} {caller_color}{caller_info}{Style.RESET_ALL}"

Metadata Exporter

goliat.metadata_exporter.TimingBreakdown dataclass

TimingBreakdown(phase_name: str, avg_time_s: float, total_time_s: float, num_executions: int, subtasks: dict[str, float] = dict())

Breakdown of timing data for a single phase.

Profiler

goliat.profiler.Profiler

Profiler(execution_control: dict, profiling_config: dict, study_type: str, config_path: str)

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
def __init__(
    self,
    execution_control: dict,
    profiling_config: dict,
    study_type: str,
    config_path: str,
):
    """Initialize profiler with phase weights and timing config.

    Args:
        execution_control: Dict indicating which phases are enabled.
        profiling_config: Historical timing data for estimates.
        study_type: Study type ('near_field' or 'far_field').
        config_path: Path where profiling config is saved.
    """
    self.execution_control = execution_control
    self.profiling_config = profiling_config
    self.study_type = study_type
    self.config_path = config_path

    self.phase_weights = self._calculate_phase_weights()
    self.subtask_times = defaultdict(list)
    self.subtask_stack = []

    self.total_simulations = 0
    self.completed_simulations = 0
    self.total_projects = 0
    self.current_project = 0
    self.completed_phases = set()

    self.start_time = time.monotonic()
    self.current_phase = None
    self.phase_start_time = None
    self.phase_skipped = False
    self.run_phase_total_duration = 0

Methods:

set_total_simulations

set_total_simulations(total: int)

Sets total simulation count for progress tracking.

Source code in goliat/profiler.py
def set_total_simulations(self, total: int):
    """Sets total simulation count for progress tracking."""
    self.total_simulations = total

set_project_scope

set_project_scope(total_projects: int)

Sets total project count for progress tracking.

Source code in goliat/profiler.py
def set_project_scope(self, total_projects: int):
    """Sets total project count for progress tracking."""
    self.total_projects = total_projects

set_current_project

set_current_project(project_index: int)

Sets the current project index.

Source code in goliat/profiler.py
def set_current_project(self, project_index: int):
    """Sets the current project index."""
    self.current_project = project_index

simulation_completed

simulation_completed()

Marks one simulation as completed.

Source code in goliat/profiler.py
def simulation_completed(self):
    """Marks one simulation as completed."""
    self.completed_simulations += 1

start_stage

start_stage(phase_name: str, total_stages: int = 1)

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
def start_stage(self, phase_name: str, total_stages: int = 1):
    """Starts tracking a new phase (setup/run/extract).

    Args:
        phase_name: Phase name like 'setup', 'run', or 'extract'.
        total_stages: Number of stages within this phase.
    """
    self.current_phase = phase_name
    self.phase_start_time = time.monotonic()
    self.phase_skipped = False
    self.completed_stages_in_phase = 0
    self.total_stages_in_phase = total_stages

end_stage

end_stage()

Ends current phase and records its duration for future estimates.

Source code in goliat/profiler.py
def end_stage(self):
    """Ends current phase and records its duration for future estimates."""
    if self.phase_start_time:
        elapsed = time.monotonic() - self.phase_start_time

        # For setup phase: if it was cached/skipped, don't add to statistics
        # (cached phases pollute real execution time statistics)
        if self.current_phase == "setup" and self.phase_skipped:
            # Cached setup: don't pollute statistics
            # avg_{phase}_time remains unchanged (uses previous real measurements)
            pass
        else:
            # Real phase: add to statistics and compute simple average for display
            self.subtask_times[self.current_phase].append(elapsed)
            times = self.subtask_times[self.current_phase]
            # Store simple average for pie charts, timings table, etc.
            self.profiling_config[f"avg_{self.current_phase}_time"] = sum(times) / len(times)

    self.current_phase = None
    self.phase_skipped = False  # Reset for next phase

complete_run_phase

complete_run_phase()

Stores the total duration of the 'run' phase from its subtasks.

Source code in goliat/profiler.py
def complete_run_phase(self):
    """Stores the total duration of the 'run' phase from its subtasks."""
    self.run_phase_total_duration = sum(self.subtask_times.get("run_simulation_total", [0]))

get_weighted_progress

get_weighted_progress(phase_name: str, phase_progress_ratio: float) -> float

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
def get_weighted_progress(self, phase_name: str, phase_progress_ratio: float) -> float:
    """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.

    Args:
        phase_name: The name of the current phase ('setup', 'run', or 'extract').
        phase_progress_ratio: Progress within current phase (0.0 = not started,
                             1.0 = fully complete).

    Returns:
        Overall progress percentage (0.0 to 100.0).
    """
    if self.total_simulations == 0:
        return 0.0

    # Progress within the current simulation
    progress_current_sim = 0
    for p, w in self.phase_weights.items():
        if p == phase_name:
            progress_current_sim += w * phase_progress_ratio
            break
        progress_current_sim += w

    # Overall progress
    overall_progress = (self.completed_simulations + progress_current_sim) / self.total_simulations
    # print(f"DEBUG: get_weighted_progress: phase={phase_name}, ratio={phase_progress_ratio:.2f}, completed={self.completed_simulations}, total={self.total_simulations}, progress={overall_progress * 100:.1f}%")
    return overall_progress * 100

get_subtask_estimate

get_subtask_estimate(task_name: str) -> float

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
def get_subtask_estimate(self, task_name: str) -> float:
    """Retrieves the estimated time for a specific subtask.
    Args:
        task_name: The name of the subtask.
    Returns:
        The estimated duration in seconds.
    """
    return self.profiling_config.get(f"avg_{task_name}", 1.0)

get_phase_subtasks

get_phase_subtasks(phase_name: str) -> list

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
def get_phase_subtasks(self, phase_name: str) -> list:
    """Gets a list of subtasks for a given phase.
    Args:
        phase_name: The name of the phase.
    Returns:
        A list of subtask names.
    """
    subtasks = []
    for key in self.profiling_config.keys():
        if key.startswith(f"avg_{phase_name}_"):
            subtasks.append(key.replace("avg_", ""))
    return subtasks

get_time_remaining

get_time_remaining(current_stage_progress: float = 0.0) -> float

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
def get_time_remaining(self, current_stage_progress: float = 0.0) -> float:
    """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

    Args:
        current_stage_progress: Progress within current stage (0.0 to 1.0).

    Returns:
        Estimated time remaining in seconds.
    """
    if not self.current_phase or self.total_simulations == 0:
        return 0.0

    # Calculate the total estimated time for one simulation using smart estimates
    total_time_per_sim = 0
    for phase in ["setup", "run", "extract"]:
        if self.execution_control.get(f"do_{phase}", False):
            total_time_per_sim += self._get_smart_phase_estimate(phase)

    # Calculate estimated time remaining in the current simulation
    ordered_phases = [p for p in ["setup", "run", "extract"] if self.execution_control.get(f"do_{p}", False)]
    try:
        current_phase_index = ordered_phases.index(self.current_phase)
    except ValueError:
        current_phase_index = 0

    # Estimated time remaining in current phase (based on progress)
    # Clamp progress to [0.0, 1.0] to handle edge cases
    progress = max(0.0, min(1.0, current_stage_progress))
    current_phase_time = self._get_smart_phase_estimate(self.current_phase)
    time_remaining_in_current_sim = current_phase_time * (1.0 - progress)

    # Add time for phases not yet started in current simulation
    for i in range(current_phase_index + 1, len(ordered_phases)):
        phase = ordered_phases[i]
        time_remaining_in_current_sim += self._get_smart_phase_estimate(phase)

    # Calculate remaining simulations (excluding current one)
    remaining_simulations = self.total_simulations - self.completed_simulations - 1

    # Estimated time remaining = time left in current sim + time for all remaining sims
    eta = time_remaining_in_current_sim + (remaining_simulations * total_time_per_sim)
    return max(0, eta)

subtask

subtask(task_name: str)

A context manager to time a subtask.

Source code in goliat/profiler.py
@contextlib.contextmanager
def subtask(self, task_name: str):
    """A context manager to time a subtask."""
    self.subtask_stack.append({"name": task_name, "start_time": time.monotonic()})
    try:
        yield
    finally:
        subtask = self.subtask_stack.pop()
        elapsed = time.monotonic() - subtask["start_time"]
        self.subtask_times[subtask["name"]].append(elapsed)
        self.update_and_save_estimates()

update_and_save_estimates

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
def update_and_save_estimates(self):
    """Updates the profiling configuration with the latest average times and saves it.

    This makes the profiler's estimates self-improving over time.
    """
    try:
        with open(self.config_path, "r") as f:
            full_config = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        full_config = {}

    if self.study_type not in full_config:
        full_config[self.study_type] = {}

    for key, value in self.profiling_config.items():
        if key.startswith("avg_"):
            full_config[self.study_type][key] = round(value, 2)

    for task_name, times in self.subtask_times.items():
        if times:
            avg_task_time = sum(times) / len(times)
            avg_key = f"avg_{task_name}"
            full_config[self.study_type][avg_key] = round(avg_task_time, 2)
            # Also update the in-memory profiling_config so it's available when sent to GUI
            self.profiling_config[avg_key] = round(avg_task_time, 2)

    with open(self.config_path, "w") as f:
        json.dump(full_config, f, indent=4)

save_estimates

save_estimates()

Saves the final profiling estimates at the end of the study.

Source code in goliat/profiler.py
def save_estimates(self):
    """Saves the final profiling estimates at the end of the study."""
    self.update_and_save_estimates()

Project Manager

goliat.project_manager.ProjectCorruptionError

Bases: Exception

Raised when a project file is corrupted, locked, or inaccessible.

Results Extractor

goliat.results_extractor.ExtractionContext dataclass

ExtractionContext(config: Config, simulation: Simulation, phantom_name: str, frequency_mhz: int | list[int], scenario_name: str, position_name: str, orientation_name: str, study_type: str, verbose_logger: Logger, progress_logger: Logger, free_space: bool = False, gui: Optional[QueueGUI] = None, study: Optional[BaseStudy] = None)

Context object containing all parameters needed for result extraction.

Groups related parameters together to reduce the parameter count of ResultsExtractor.init.

Simulation Runner

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
def __init__(
    self,
    config: "Config",
    project_path: str,
    simulation: "s4l_v1.simulation.emfdtd.Simulation",
    profiler: "Profiler",
    verbose_logger: "Logger",
    progress_logger: "Logger",
    project_manager: "ProjectManager",
    gui: "Optional[QueueGUI]" = None,
):
    """Sets up the simulation runner.

    Args:
        config: Configuration object.
        project_path: Path to the Sim4Life project file.
        simulation: The simulation object to run.
        profiler: Profiler for timing subtasks.
        verbose_logger: Logger for detailed output.
        progress_logger: Logger for high-level updates.
        gui: Optional GUI proxy for updates.
        project_manager: ProjectManager instance. Uses its save() method.
    """
    self.config = config
    self.project_path = project_path
    self.simulation = simulation
    self.profiler = profiler
    self.verbose_logger = verbose_logger
    self.progress_logger = progress_logger
    self.gui = gui
    self.project_manager = project_manager
    import s4l_v1.document

    self.document = s4l_v1.document
    self.current_strategy: Optional["ExecutionStrategy"] = None  # Track current execution strategy
    _active_runners.add(self)  # Register this instance for global cleanup

Methods:

run

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
def run(self):
    """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.
    """
    if not self.simulation:
        self._log(
            "ERROR: Simulation object not found. Cannot run simulation.",
            level="progress",
            log_type="error",
        )
        return
    self._log(f"Running simulation: {self.simulation.Name}", log_type="verbose")

    server_name = (self.config["solver_settings"] or {}).get("server")

    try:
        if hasattr(self.simulation, "WriteInputFile"):
            self._log(
                "    - Write input file...",
                level="progress",
                log_type="progress",
            )
            with self.profiler.subtask("run_write_input_file"):
                self.simulation.WriteInputFile()
                # Force a save to flush files
                self.project_manager.save()
            elapsed = self.profiler.subtask_times["run_write_input_file"][-1]
            self._log(f"      - Subtask 'run_write_input_file' done in {elapsed:.2f}s", log_type="verbose")
            self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

        # Stop here if we only want to write the input file
        if self.config.get_only_write_input_file():
            self._log(
                "'only_write_input_file' is true, skipping simulation run.",
                level="progress",
                log_type="info",
            )
            return

        # Select and execute strategy
        strategy = self._create_execution_strategy(server_name)
        self.current_strategy = strategy
        try:
            strategy.run()
        finally:
            self.current_strategy = None

    except Exception as e:
        self._log(
            f"An error occurred during simulation run: {e}",
            level="progress",
            log_type="error",
        )
        # Check if a cloud server was intended for the run
        server_name = (self.config["solver_settings"] or {}).get("server")
        if server_name and server_name != "localhost":
            self._log(
                "If you are running on the cloud, please ensure you are logged into Sim4Life "
                "via the GUI and your API credentials are correct.",
                level="progress",
                log_type="warning",
            )
        self.verbose_logger.error(traceback.format_exc())

    return self.simulation

Configuration

Configuration management and settings.

Core

goliat.config.core.Config

Config(base_dir: str, config_filename: str = 'near_field_config.json', no_cache: bool = False)

Manages loading and access of hierarchical JSON configurations.

Parameters:

Name Type Description Default
base_dir str

The base directory of the project.

required
config_filename str

The name of the main configuration file to load.

'near_field_config.json'
no_cache bool

This parameter is accepted but not used directly by the Config class. It's used by other managers to control caching behavior.

False
Source code in goliat/config/core.py
def __init__(self, base_dir: str, config_filename: str = "near_field_config.json", no_cache: bool = False):
    """Load main config, material mapping, and profiling config.

    Args:
        base_dir: The base directory of the project.
        config_filename: The name of the main configuration file to load.
        no_cache: This parameter is accepted but not used directly by the Config class.
                  It's used by other managers to control caching behavior.
    """
    self.base_dir = base_dir
    self.config_path = self._resolve_config_path(config_filename, self.base_dir)
    self.material_mapping_path = os.path.join(self.base_dir, "data", "material_name_mapping.json")

    # Generate session hash for profiling config (similar to GUI session tracking)
    session_hash = hashlib.md5(f"{time.time()}_{os.getpid()}".encode()).hexdigest()[:8]
    data_dir = os.path.join(self.base_dir, "data")
    os.makedirs(data_dir, exist_ok=True)

    # Generate timestamp for filename
    session_timestamp = datetime.now().strftime("%d-%m_%H-%M-%S")

    # Cleanup old JSON files before creating new one
    cleanup_old_data_files(data_dir)

    self.profiling_config_path = os.path.join(data_dir, f"profiling_config_{session_timestamp}_{session_hash}.json")

    self.config = self._load_config_with_inheritance(self.config_path)

    # Load material mapping - provide helpful error if missing
    try:
        self.material_mapping = self._load_json(self.material_mapping_path)
    except FileNotFoundError:
        raise FileNotFoundError(
            f"Material mapping file not found at: {self.material_mapping_path}\nPlease run 'goliat init' to set up the required files."
        )

    # Load or initialize profiling config
    self.profiling_config = load_or_create_profiling_config(self.profiling_config_path)

    # Load detuning config if enabled
    self.detuning_data = None
    self.detuning_enabled = self.config.get("detuning_enabled", "") or False
    self.detuning_write_during_calibration = self.config.get("detuning_write_during_calibration", "") or False

    if self.detuning_enabled:
        # Validate study type
        study_type = self.config["study_type"]
        if study_type == "far_field":
            raise ValueError("Detuning feature is only supported for near_field studies, not far_field")

        detuning_config_path = self.config.get("detuning_config", "")
        if detuning_config_path:
            resolved_path = self._resolve_path_relative_to_config(self.config_path, detuning_config_path)
            self.detuning_data = self._load_detuning_config(resolved_path)
        else:
            import logging

            logging.getLogger("progress").warning(
                "detuning_enabled is true but detuning_config not specified. Detuning will default to 0.", extra={"log_type": "warning"}
            )
    elif self.config.get("detuning_config", ""):
        # Only warn if config provided but both enabled and write are false
        # If write_during_calibration is true, we're in calibration mode (writing), so no warning needed
        if not self.detuning_write_during_calibration:
            import logging

            logging.getLogger("progress").warning(
                "detuning_config provided but detuning_enabled is false, ignoring detuning config", extra={"log_type": "warning"}
            )

Methods:

get_material_mapping

get_material_mapping(phantom_name: str) -> dict

Gets the material name mapping for a specific phantom.

Parameters:

Name Type Description Default
phantom_name str

The name of the phantom.

required

Returns:

Type Description
dict

The material mapping dictionary.

Source code in goliat/config/core.py
def get_material_mapping(self, phantom_name: str) -> dict:
    """Gets the material name mapping for a specific phantom.

    Args:
        phantom_name: The name of the phantom.

    Returns:
        The material mapping dictionary.
    """
    if phantom_name in self.material_mapping:
        return self.material_mapping[phantom_name]
    else:
        return self.material_mapping

get_profiling_config

get_profiling_config(study_type: str) -> dict

Gets the profiling configuration for a given study type.

Parameters:

Name Type Description Default
study_type str

The type of the study (e.g., 'near_field').

required

Returns:

Type Description
dict

The profiling configuration for the study type.

Source code in goliat/config/core.py
def get_profiling_config(self, study_type: str) -> dict:
    """Gets the profiling configuration for a given study type.

    Args:
        study_type: The type of the study (e.g., 'near_field').

    Returns:
        The profiling configuration for the study type.
    """
    return get_profiling_config(self.profiling_config, study_type)

get_download_email

get_download_email() -> str

Returns the download email from environment variables.

Raises:

Type Description
ValueError

If DOWNLOAD_EMAIL is not set in the environment.

Source code in goliat/config/core.py
def get_download_email(self) -> str:
    """Returns the download email from environment variables.

    Raises:
        ValueError: If DOWNLOAD_EMAIL is not set in the environment.
    """
    return get_download_email()

get_osparc_credentials

get_osparc_credentials() -> dict

Gets oSPARC credentials from environment variables.

Raises:

Type Description
ValueError

If required oSPARC credentials are not set.

Returns:

Type Description
dict

A dictionary containing oSPARC API credentials.

Source code in goliat/config/core.py
def get_osparc_credentials(self) -> dict:
    """Gets oSPARC credentials from environment variables.

    Raises:
        ValueError: If required oSPARC credentials are not set.

    Returns:
        A dictionary containing oSPARC API credentials.
    """
    return get_osparc_credentials()

get_only_write_input_file

get_only_write_input_file() -> bool

Returns whether to only write input files without running simulations.

Source code in goliat/config/core.py
def get_only_write_input_file(self) -> bool:
    """Returns whether to only write input files without running simulations."""
    result = self["execution_control.only_write_input_file"]
    if result is None:
        result = False
    assert isinstance(result, bool)
    return result

get_auto_cleanup_previous_results

get_auto_cleanup_previous_results() -> list

Gets the 'auto_cleanup_previous_results' setting from 'execution_control'.

This setting determines which previous simulation files to automatically delete to preserve disk space. It should only be used in serial workflows.

Also checks GOLIAT_AUTO_CLEANUP environment variable for worker scenarios where config is downloaded from cloud. Format: comma-separated values like "output,input".

Returns:

Type Description
list

A list of file types to clean up (e.g., ["output", "input"]).

Source code in goliat/config/core.py
def get_auto_cleanup_previous_results(self) -> list:
    """Gets the 'auto_cleanup_previous_results' setting from 'execution_control'.

    This setting determines which previous simulation files to automatically delete
    to preserve disk space. It should only be used in serial workflows.

    Also checks GOLIAT_AUTO_CLEANUP environment variable for worker scenarios where
    config is downloaded from cloud. Format: comma-separated values like "output,input".

    Returns:
        A list of file types to clean up (e.g., ["output", "input"]).
    """
    # Check environment variable first (for worker scenarios)
    env_cleanup = os.environ.get("GOLIAT_AUTO_CLEANUP", "").strip()
    if env_cleanup:
        # Parse comma-separated values
        env_types = [t.strip().lower() for t in env_cleanup.split(",") if t.strip()]
        valid_types = {"output", "input", "smash"}
        valid_env_types = [t for t in env_types if t in valid_types]
        if valid_env_types:
            return valid_env_types

    cleanup_setting = self["execution_control.auto_cleanup_previous_results"] or []

    # Handle legacy boolean format for backwards compatibility
    if isinstance(cleanup_setting, bool):
        if cleanup_setting:
            # Legacy behavior: only clean output files
            return ["output"]
        else:
            return []

    # Validate that it's a list
    if not isinstance(cleanup_setting, list):
        import logging

        logging.warning(f"'auto_cleanup_previous_results' should be a list, got {type(cleanup_setting)}. Disabling cleanup for safety.")
        return []

    # Validate file types
    valid_types = {"output", "input", "smash"}
    invalid_types = [t for t in cleanup_setting if t not in valid_types]
    if invalid_types:
        import logging

        logging.warning(f"Invalid file types in 'auto_cleanup_previous_results': {invalid_types}. Valid types are: {valid_types}")

    return [t for t in cleanup_setting if t in valid_types]

build_simulation_config

build_simulation_config(phantom_name: str, frequency_mhz: int | list[int], scenario_name: Optional[str] = None, position_name: Optional[str] = None, orientation_name: Optional[str] = None, direction_name: Optional[str] = None, polarization_name: Optional[str] = None) -> dict

Constructs a minimal, simulation-specific configuration dictionary.

This method is the core of the "Verify and Resume" feature. It creates a "surgical" snapshot of the configuration that is unique to a single simulation run. This snapshot is then hashed to determine if a valid, reusable simulation already exists.

The key principle is to only include parameters that directly affect the outcome of the specific simulation. For example, instead of including the entire 'gridding_parameters' block, it surgically extracts only the gridding value for the specific 'frequency_mhz' being used. This ensures that a change to one frequency's gridding in the main config does not invalidate the hashes for other, unaffected frequencies.

Parameters:

Name Type Description Default
phantom_name str

The name of the phantom model.

required
frequency_mhz int | list[int]

The simulation frequency in MHz.

required
scenario_name Optional[str]

(Near-Field) The base name of the placement scenario.

None
position_name Optional[str]

(Near-Field) The name of the position within the scenario.

None
orientation_name Optional[str]

(Near-Field) The name of the orientation.

None
direction_name Optional[str]

(Far-Field) The incident direction of the plane wave.

None
polarization_name Optional[str]

(Far-Field) The polarization of the plane wave.

None

Returns:

Type Description
dict

A dictionary containing the minimal, surgical configuration snapshot.

Source code in goliat/config/core.py
def build_simulation_config(
    self,
    phantom_name: str,
    frequency_mhz: int | list[int],
    scenario_name: Optional[str] = None,
    position_name: Optional[str] = None,
    orientation_name: Optional[str] = None,
    direction_name: Optional[str] = None,
    polarization_name: Optional[str] = None,
) -> dict:
    """Constructs a minimal, simulation-specific configuration dictionary.

    This method is the core of the "Verify and Resume" feature. It creates a
    "surgical" snapshot of the configuration that is unique to a single
    simulation run. This snapshot is then hashed to determine if a valid,
    reusable simulation already exists.

    The key principle is to only include parameters that directly affect the
    outcome of the specific simulation. For example, instead of including the
    entire 'gridding_parameters' block, it surgically extracts only the
    gridding value for the specific 'frequency_mhz' being used. This ensures
    that a change to one frequency's gridding in the main config does not
    invalidate the hashes for other, unaffected frequencies.

    Args:
        phantom_name: The name of the phantom model.
        frequency_mhz: The simulation frequency in MHz.
        scenario_name: (Near-Field) The base name of the placement scenario.
        position_name: (Near-Field) The name of the position within the scenario.
        orientation_name: (Near-Field) The name of the orientation.
        direction_name: (Far-Field) The incident direction of the plane wave.
        polarization_name: (Far-Field) The polarization of the plane wave.

    Returns:
        A dictionary containing the minimal, surgical configuration snapshot.
    """
    surgical_config = {}

    # 1. Copy global parameters
    global_keys = [
        "study_type",
        "simulation_parameters",
        "solver_settings",
        "manual_isolve",
        "export_material_properties",
    ]
    for key in global_keys:
        if key in self.config:
            surgical_config[key] = self[key]

    # 2. Surgically handle gridding parameters
    gridding_params = self["gridding_parameters"] or {}
    surgical_config["gridding_parameters"] = build_surgical_gridding(gridding_params, frequency_mhz)

    # 3. Add simulation-specific identifiers
    surgical_config["phantom"] = phantom_name
    surgical_config["frequency_mhz"] = frequency_mhz

    # 4. Surgically select study-specific parameters
    study_type = self["study_type"]
    if study_type == "near_field":
        build_near_field_simulation_config(
            self, surgical_config, phantom_name, frequency_mhz, scenario_name, position_name, orientation_name
        )
    elif study_type == "far_field":
        build_far_field_simulation_config(self, surgical_config, phantom_name, direction_name, polarization_name)

    return surgical_config

get_detuning_mhz

get_detuning_mhz(phantom_name: str, frequency_mhz: int, placement_name: str) -> float

Gets detuning value in MHz for a specific simulation.

Parameters:

Name Type Description Default
phantom_name str

Name of the phantom (will be normalized to lowercase).

required
frequency_mhz int

Frequency in MHz.

required
placement_name str

Placement name (format: {scenario}{position}).

required

Returns:

Type Description
float

Detuning value in MHz. Returns 0.0 if not found or detuning disabled.

Source code in goliat/config/core.py
def get_detuning_mhz(
    self,
    phantom_name: str,
    frequency_mhz: int,
    placement_name: str,
) -> float:
    """Gets detuning value in MHz for a specific simulation.

    Args:
        phantom_name: Name of the phantom (will be normalized to lowercase).
        frequency_mhz: Frequency in MHz.
        placement_name: Placement name (format: {scenario}_{position}_{orientation}).

    Returns:
        Detuning value in MHz. Returns 0.0 if not found or detuning disabled.
    """
    if not self.detuning_enabled or not self.detuning_data:
        return 0.0

    # Normalize phantom name to lowercase
    phantom_lower = phantom_name.lower()

    # Convert frequency to string format
    freq_str = f"{frequency_mhz}MHz"

    # Lookup in nested structure
    try:
        detuning_value = self.detuning_data.get(phantom_lower, {}).get(freq_str, {}).get(placement_name)
        if detuning_value is None:
            # Missing entry - warn and return 0
            import logging

            logging.getLogger("progress").warning(
                f"No detuning data for {phantom_name}/{freq_str}/{placement_name}, using 0 MHz", extra={"log_type": "warning"}
            )
            return 0.0
        return float(detuning_value)
    except (AttributeError, TypeError):
        # Invalid structure - warn and return 0
        import logging

        logging.getLogger("progress").warning(
            f"Invalid detuning data structure for {phantom_name}/{freq_str}/{placement_name}, using 0 MHz",
            extra={"log_type": "warning"},
        )
        return 0.0

update_detuning_file

update_detuning_file(phantom_name: str, frequency_mhz: int | list[int], placement_name: str, detuning_mhz: float) -> None

Updates detuning file with a new detuning value.

Parameters:

Name Type Description Default
phantom_name str

Name of the phantom (will be normalized to lowercase).

required
frequency_mhz int | list[int]

Frequency in MHz.

required
placement_name str

Placement name (format: {scenario}{position}).

required
detuning_mhz float

Detuning value in MHz to write.

required
Source code in goliat/config/core.py
def update_detuning_file(
    self,
    phantom_name: str,
    frequency_mhz: int | list[int],
    placement_name: str,
    detuning_mhz: float,
) -> None:
    """Updates detuning file with a new detuning value.

    Args:
        phantom_name: Name of the phantom (will be normalized to lowercase).
        frequency_mhz: Frequency in MHz.
        placement_name: Placement name (format: {scenario}_{position}_{orientation}).
        detuning_mhz: Detuning value in MHz to write.
    """
    if not self.detuning_enabled or not self.detuning_write_during_calibration:
        return

    detuning_config_path = self.config.get("detuning_config")
    if not detuning_config_path:
        return

    resolved_path = self._resolve_path_relative_to_config(self.config_path, detuning_config_path)

    # Normalize phantom name to lowercase
    phantom_lower = phantom_name.lower()
    # For multi-sine, format as "700+2450MHz"
    freq_str_val = "+".join(str(f) for f in frequency_mhz) if isinstance(frequency_mhz, list) else str(frequency_mhz)
    freq_str = f"{freq_str_val}MHz"

    # Load existing data or create empty structure
    if os.path.exists(resolved_path):
        try:
            detuning_config = self._load_json(resolved_path)
            detuning_data = detuning_config.get("detuning_data", {})
        except (json.JSONDecodeError, FileNotFoundError):
            detuning_data = {}
    else:
        detuning_data = {}

    # Initialize nested structure if needed
    if phantom_lower not in detuning_data:
        detuning_data[phantom_lower] = {}
    if freq_str not in detuning_data[phantom_lower]:
        detuning_data[phantom_lower][freq_str] = {}

    # Only write if entry doesn't exist (never overwrite)
    if placement_name not in detuning_data[phantom_lower][freq_str]:
        detuning_data[phantom_lower][freq_str][placement_name] = detuning_mhz

        # Save updated file
        detuning_config = {"detuning_data": detuning_data}
        os.makedirs(os.path.dirname(resolved_path), exist_ok=True)
        with open(resolved_path, "w") as f:
            json.dump(detuning_config, f, indent=2)

        # Update in-memory data
        self.detuning_data = detuning_data

initialize_missing_detuning_entries

initialize_missing_detuning_entries() -> None

Initializes missing detuning entries for all simulations in the study.

Called at the end of a calibration run to ensure all simulation entries exist in the detuning file (with value 0) before manual calibration values are added.

Source code in goliat/config/core.py
def initialize_missing_detuning_entries(self) -> None:
    """Initializes missing detuning entries for all simulations in the study.

    Called at the end of a calibration run to ensure all simulation entries exist
    in the detuning file (with value 0) before manual calibration values are added.
    """
    if not self.detuning_enabled or not self.detuning_write_during_calibration:
        return

    detuning_config_path = self.config["detuning_config"]
    if not detuning_config_path:
        return

    resolved_path = self._resolve_path_relative_to_config(self.config_path, detuning_config_path)
    detuning_data = self._load_or_create_detuning_data(resolved_path)

    # Initialize missing entries for all simulation combinations
    for phantom_lower, freq_str, placement_name in self._iter_simulation_combinations():
        if phantom_lower not in detuning_data:
            detuning_data[phantom_lower] = {}
        if freq_str not in detuning_data[phantom_lower]:
            detuning_data[phantom_lower][freq_str] = {}
        if placement_name not in detuning_data[phantom_lower][freq_str]:
            detuning_data[phantom_lower][freq_str][placement_name] = 0.0

    self._save_detuning_data(resolved_path, detuning_data)

Credentials

goliat.config.credentials

Environment variable and credentials management.

Functions:

get_download_email

get_download_email() -> str

Returns the download email from environment variables.

Raises:

Type Description
ValueError

If DOWNLOAD_EMAIL is not set in the environment.

Source code in goliat/config/credentials.py
def get_download_email() -> str:
    """Returns the download email from environment variables.

    Raises:
        ValueError: If DOWNLOAD_EMAIL is not set in the environment.
    """
    email = os.getenv("DOWNLOAD_EMAIL")
    if not email:
        raise ValueError("Missing DOWNLOAD_EMAIL. Please set this in your .env file.")
    return email

get_osparc_credentials

get_osparc_credentials() -> dict

Gets oSPARC credentials from environment variables.

Raises:

Type Description
ValueError

If required oSPARC credentials are not set.

Returns:

Type Description
dict

A dictionary containing oSPARC API credentials.

Source code in goliat/config/credentials.py
def get_osparc_credentials() -> dict:
    """Gets oSPARC credentials from environment variables.

    Raises:
        ValueError: If required oSPARC credentials are not set.

    Returns:
        A dictionary containing oSPARC API credentials.
    """
    credentials = {
        "api_key": os.getenv("OSPARC_API_KEY"),
        "api_secret": os.getenv("OSPARC_API_SECRET"),
        "api_server": "https://api.sim4life.science",
        "api_version": "v0",
    }

    missing = [key for key, value in credentials.items() if value is None and key != "api_version"]
    if missing:
        raise ValueError(
            f"Missing oSPARC credentials: {', '.join(missing)}. "
            "Please create a .env file in the project root with your oSPARC API credentials. "
            "See README.md for setup instructions."
        )

    return credentials

File Management

goliat.config.file_management

File management utilities for configuration.

Functions:

cleanup_old_data_files

cleanup_old_data_files(data_dir: str)

Removes old CSV/JSON files from data/ when there are more than 50.

Only cleans files matching specific patterns (time_remaining_, overall_progress_, profiling_config_). Files are sorted by creation time and oldest are deleted first.

Parameters:

Name Type Description Default
data_dir str

The data directory to clean up.

required
Source code in goliat/config/file_management.py
def cleanup_old_data_files(data_dir: str):
    """Removes old CSV/JSON files from data/ when there are more than 50.

    Only cleans files matching specific patterns (time_remaining_, overall_progress_,
    profiling_config_). Files are sorted by creation time and oldest are deleted first.

    Args:
        data_dir: The data directory to clean up.
    """
    try:
        # Get all CSV and JSON files in the data directory
        data_files = []
        for f in os.listdir(data_dir):
            if f.endswith(".csv") or f.endswith(".json"):
                # Only include files with the expected naming pattern
                if any(prefix in f for prefix in ["time_remaining_", "overall_progress_", "profiling_config_"]):
                    full_path = os.path.join(data_dir, f)
                    data_files.append(full_path)

        # Sort by creation time (oldest first)
        data_files.sort(key=os.path.getctime)

        # Remove oldest files if we have more than 50
        while len(data_files) > 50:
            old_file = None
            try:
                old_file = data_files.pop(0)
                os.remove(old_file)
                logging.getLogger("verbose").debug(f"Removed old data file: {os.path.basename(old_file)}")
            except OSError as e:
                if old_file:
                    logging.getLogger("verbose").warning(f"Failed to remove {os.path.basename(old_file)}: {e}")
                else:
                    logging.getLogger("verbose").warning(f"Failed to remove a file: {e}")
    except Exception as e:
        logging.getLogger("verbose").warning(f"Error during data file cleanup: {e}")

Merge

goliat.config.merge

Dictionary merging utilities.

Functions:

deep_merge

deep_merge(source: dict, destination: dict) -> dict

Recursively merges two dictionaries, overwriting destination with source values.

Parameters:

Name Type Description Default
source dict

The dictionary with values to merge.

required
destination dict

The dictionary to be merged into.

required

Returns:

Type Description
dict

The merged dictionary.

Source code in goliat/config/merge.py
def deep_merge(source: dict, destination: dict) -> dict:
    """Recursively merges two dictionaries, overwriting destination with source values.

    Args:
        source: The dictionary with values to merge.
        destination: The dictionary to be merged into.

    Returns:
        The merged dictionary.
    """
    for key, value in source.items():
        if isinstance(value, dict) and key in destination and isinstance(destination[key], dict):
            deep_merge(value, destination[key])
        else:
            destination[key] = value
    return destination

Profiling

goliat.config.profiling

Profiling configuration management.

Functions:

load_or_create_profiling_config

load_or_create_profiling_config(profiling_config_path: str) -> dict

Loads profiling config from disk, or creates a new one if missing.

Parameters:

Name Type Description Default
profiling_config_path str

Path to the profiling config file.

required

Returns:

Type Description
dict

The profiling config dict, initialized with empty structure if new.

Source code in goliat/config/profiling.py
def load_or_create_profiling_config(profiling_config_path: str) -> dict:
    """Loads profiling config from disk, or creates a new one if missing.

    Args:
        profiling_config_path: Path to the profiling config file.

    Returns:
        The profiling config dict, initialized with empty structure if new.
    """
    if os.path.exists(profiling_config_path):
        try:
            with open(profiling_config_path, "r") as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError):
            # If file is corrupted, start fresh
            pass

    # Create a new profiling config with empty structure
    profiling_config = {}

    # Initialize with empty structure for each study type
    for study_type in ["near_field", "far_field"]:
        profiling_config[study_type] = {}

    # Save the initial config
    try:
        with open(profiling_config_path, "w") as f:
            json.dump(profiling_config, f, indent=4)
    except IOError:
        # If we can't write, just return the empty dict
        pass

    return profiling_config

get_profiling_config

get_profiling_config(profiling_config: dict, study_type: str) -> dict

Gets the profiling configuration for a given study type.

Parameters:

Name Type Description Default
profiling_config dict

The profiling configuration dictionary.

required
study_type str

The type of the study (e.g., 'near_field').

required

Returns:

Type Description
dict

The profiling configuration for the study type.

Source code in goliat/config/profiling.py
def get_profiling_config(profiling_config: dict, study_type: str) -> dict:
    """Gets the profiling configuration for a given study type.

    Args:
        profiling_config: The profiling configuration dictionary.
        study_type: The type of the study (e.g., 'near_field').

    Returns:
        The profiling configuration for the study type.
    """
    if study_type not in profiling_config:
        logging.warning(f"Profiling configuration not defined for study type: {study_type}. Returning empty configuration.")
        return {}
    return profiling_config[study_type]

Simulation Config

goliat.config.simulation_config

Simulation-specific configuration building utilities.

Functions:

build_surgical_gridding

build_surgical_gridding(gridding_params: dict, frequency_mhz: int | list[int]) -> dict

Extracts frequency-specific gridding parameters.

This surgically extracts only the gridding value for the specific frequency, ensuring that changes to other frequencies don't invalidate hashes.

Parameters:

Name Type Description Default
gridding_params dict

The full gridding parameters dictionary.

required
frequency_mhz int | list[int]

The simulation frequency in MHz.

required

Returns:

Type Description
dict

A dictionary containing surgical gridding parameters.

Source code in goliat/config/simulation_config.py
def build_surgical_gridding(gridding_params: dict, frequency_mhz: int | list[int]) -> dict:
    """Extracts frequency-specific gridding parameters.

    This surgically extracts only the gridding value for the specific frequency,
    ensuring that changes to other frequencies don't invalidate hashes.

    Args:
        gridding_params: The full gridding parameters dictionary.
        frequency_mhz: The simulation frequency in MHz.

    Returns:
        A dictionary containing surgical gridding parameters.
    """
    surgical_gridding = {}
    # Copy non-frequency specific gridding params
    for key, value in gridding_params.items():
        if key != "global_gridding_per_frequency":
            surgical_gridding[key] = value

    # Extract only the relevant frequency's gridding value
    if "global_gridding_per_frequency" in gridding_params:
        # For multi-sine, use highest frequency's gridding
        ref_freq = max(frequency_mhz) if isinstance(frequency_mhz, list) else frequency_mhz
        freq_str = str(ref_freq)
        if freq_str in gridding_params["global_gridding_per_frequency"]:
            surgical_gridding["global_gridding_per_frequency"] = {freq_str: gridding_params["global_gridding_per_frequency"][freq_str]}

    return surgical_gridding

build_near_field_simulation_config

build_near_field_simulation_config(config_accessor, surgical_config: dict, phantom_name: str, frequency_mhz: int | list[int], scenario_name: Optional[str], position_name: Optional[str], orientation_name: Optional[str]) -> None

Builds near-field specific configuration components.

Parameters:

Name Type Description Default
config_accessor

Object with getitem method to access config values.

required
surgical_config dict

The configuration dictionary to populate.

required
phantom_name str

The name of the phantom model.

required
frequency_mhz int | list[int]

The simulation frequency in MHz.

required
scenario_name Optional[str]

The base name of the placement scenario.

required
position_name Optional[str]

The name of the position within the scenario.

required
orientation_name Optional[str]

The name of the orientation.

required
Source code in goliat/config/simulation_config.py
def build_near_field_simulation_config(
    config_accessor,
    surgical_config: dict,
    phantom_name: str,
    frequency_mhz: int | list[int],
    scenario_name: Optional[str],
    position_name: Optional[str],
    orientation_name: Optional[str],
) -> None:
    """Builds near-field specific configuration components.

    Args:
        config_accessor: Object with __getitem__ method to access config values.
        surgical_config: The configuration dictionary to populate.
        phantom_name: The name of the phantom model.
        frequency_mhz: The simulation frequency in MHz.
        scenario_name: The base name of the placement scenario.
        position_name: The name of the position within the scenario.
        orientation_name: The name of the orientation.
    """
    # Select the specific antenna config for the given frequency
    # For multi-sine, use highest frequency's antenna config
    ref_freq = max(frequency_mhz) if isinstance(frequency_mhz, list) else frequency_mhz
    surgical_config["antenna_config"] = config_accessor[f"antenna_config.{ref_freq}"]

    # Reconstruct placement_scenarios for the specific placement
    if scenario_name:
        placement_scenarios = config_accessor["placement_scenarios"] or {}
        original_scenario = placement_scenarios.get(scenario_name) if isinstance(placement_scenarios, dict) else None
        if original_scenario and position_name and orientation_name:
            surgical_config["placement_scenarios"] = {
                scenario_name: {
                    "positions": {position_name: original_scenario["positions"][position_name]},
                    "orientations": {orientation_name: original_scenario["orientations"][orientation_name]},
                    "bounding_box": original_scenario.get("bounding_box", "default"),
                }
            }

    # Select the specific phantom definition
    phantom_definitions = config_accessor["phantom_definitions"] or {}
    surgical_config["phantom_definitions"] = {
        phantom_name: phantom_definitions.get(phantom_name, {}) if isinstance(phantom_definitions, dict) else {}
    }

build_far_field_simulation_config

build_far_field_simulation_config(config_accessor, surgical_config: dict, phantom_name: str, direction_name: Optional[str], polarization_name: Optional[str]) -> None

Builds far-field specific configuration components.

Parameters:

Name Type Description Default
config_accessor

Object with getitem method to access config values.

required
surgical_config dict

The configuration dictionary to populate.

required
phantom_name str

The name of the phantom model.

required
direction_name Optional[str]

The incident direction of the plane wave.

required
polarization_name Optional[str]

The polarization of the plane wave.

required
Source code in goliat/config/simulation_config.py
def build_far_field_simulation_config(
    config_accessor,
    surgical_config: dict,
    phantom_name: str,
    direction_name: Optional[str],
    polarization_name: Optional[str],
) -> None:
    """Builds far-field specific configuration components.

    Args:
        config_accessor: Object with __getitem__ method to access config values.
        surgical_config: The configuration dictionary to populate.
        phantom_name: The name of the phantom model.
        direction_name: The incident direction of the plane wave.
        polarization_name: The polarization of the plane wave.
    """
    # Surgically build the far_field_setup to be robust against future changes
    original_ff_setup = config_accessor["far_field_setup"] or {}
    if original_ff_setup:
        surgical_config["far_field_setup"] = {
            "type": original_ff_setup.get("type"),
            "environmental": {
                "incident_directions": [direction_name],
                "polarizations": [polarization_name],
            },
        }
    # Also include the specific phantom definition, if it's not empty
    phantom_definitions = config_accessor["phantom_definitions"] or {}
    phantom_def = phantom_definitions.get(phantom_name, {}) if isinstance(phantom_definitions, dict) else {}
    if phantom_def:
        surgical_config["phantom_definitions"] = {phantom_name: phantom_def}

Study Orchestration

Study classes that orchestrate simulation workflows.

Base Study

goliat.studies.base_study.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
def __init__(
    self,
    study_type: str,
    config_filename: Optional[str] = None,
    gui: Optional["QueueGUI"] = None,
    profiler=None,
    no_cache: bool = False,
):
    """Load config, set up loggers and profiler, determine base directory."""
    self.study_type = study_type
    self.gui = gui
    self.verbose_logger = logging.getLogger("verbose")
    self.progress_logger = logging.getLogger("progress")
    self.no_cache = no_cache

    # Determine base_dir: prefer cwd if it has configs/, otherwise fallback to package location
    cwd = os.getcwd()
    if os.path.isdir(os.path.join(cwd, "configs")):
        self.base_dir = cwd
    else:
        # Fallback: calculate from package location (for backwards compatibility)
        self.base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

    self.config = Config(
        self.base_dir,
        config_filename if config_filename else f"{self.study_type}_config.json",
    )

    # Get study-specific profiling config
    profiling_config = self.config.get_profiling_config(self.study_type)
    execution_control = self.config["execution_control"] or {"do_setup": True, "do_run": True, "do_extract": True}

    self.profiler = Profiler(
        execution_control,  # type: ignore
        profiling_config,
        self.study_type,
        self.config.profiling_config_path,
    )
    self.line_profiler = None

    self.project_manager = ProjectManager(
        self.config,
        self.verbose_logger,
        self.progress_logger,
        self.gui,
        no_cache=self.no_cache,
    )

Methods:

subtask

subtask(task_name: str, instance_to_profile=None)

A context manager for a 'subtask' within a phase.

Source code in goliat/studies/base_study.py
@contextlib.contextmanager
def subtask(self, task_name: str, instance_to_profile=None):
    """A context manager for a 'subtask' within a phase."""
    is_top_level_subtask = not self.profiler.subtask_stack
    sub_stage_display_name = task_name.replace("_", " ").capitalize()

    if is_top_level_subtask:
        self._log(f"  - {sub_stage_display_name}...", level="progress", log_type="progress")
        if self.gui and self.profiler.current_phase:
            self.gui.update_stage_progress(self.profiler.current_phase.capitalize(), 0, 1, sub_stage=sub_stage_display_name)
            self.start_stage_animation(task_name, 100)

    lp, wrapper = self._setup_line_profiler_if_needed(task_name, instance_to_profile)

    try:
        with self.profiler.subtask(task_name):
            if lp and wrapper:
                yield wrapper
            else:
                yield
    finally:
        elapsed = self.profiler.subtask_times[task_name][-1]
        self._log(f"    - Subtask '{task_name}' done in {elapsed:.2f}s", log_type="verbose")

        if is_top_level_subtask:
            self._log(f"    - Done in {elapsed:.2f}s", level="progress", log_type="success")
            if self.gui:
                self.end_stage_animation()
                if self.profiler.current_phase:
                    self.gui.update_stage_progress(self.profiler.current_phase.capitalize(), 1, 1)

        if lp:
            self._log_line_profiler_stats(task_name, lp)

start_stage_animation

start_stage_animation(task_name: str, end_value: int)

Starts progress bar animation for the current stage.

Source code in goliat/studies/base_study.py
def start_stage_animation(self, task_name: str, end_value: int):
    """Starts progress bar animation for the current stage."""
    if self.gui:
        self.gui.start_stage_animation(task_name, end_value)

end_stage_animation

end_stage_animation()

Stops the current stage animation.

Source code in goliat/studies/base_study.py
def end_stage_animation(self):
    """Stops the current stage animation."""
    if self.gui:
        self.gui.end_stage_animation()

run

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
def run(self):
    """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.
    """
    ensure_s4l_running()
    try:
        self._run_study()
    except StudyCancelledError:
        self._log(
            "--- Study execution cancelled by user. ---",
            level="progress",
            log_type="warning",
        )
    except Exception as e:
        self._log(f"--- FATAL ERROR in study: {e} ---", level="progress", log_type="fatal")
        self.verbose_logger.error(traceback.format_exc())
    finally:
        self._log(
            f"\n--- {self.__class__.__name__} Finished ---",
            level="progress",
            log_type="success",
        )
        self.profiler.save_estimates()
        self.project_manager.cleanup()
        if self.gui:
            self.gui.update_profiler()  # Send final profiler state

Far Field Study

goliat.studies.far_field_study.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
def __init__(
    self,
    study_type: str,
    config_filename: Optional[str] = None,
    gui: Optional["QueueGUI"] = None,
    profiler=None,
    no_cache: bool = False,
):
    """Load config, set up loggers and profiler, determine base directory."""
    self.study_type = study_type
    self.gui = gui
    self.verbose_logger = logging.getLogger("verbose")
    self.progress_logger = logging.getLogger("progress")
    self.no_cache = no_cache

    # Determine base_dir: prefer cwd if it has configs/, otherwise fallback to package location
    cwd = os.getcwd()
    if os.path.isdir(os.path.join(cwd, "configs")):
        self.base_dir = cwd
    else:
        # Fallback: calculate from package location (for backwards compatibility)
        self.base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

    self.config = Config(
        self.base_dir,
        config_filename if config_filename else f"{self.study_type}_config.json",
    )

    # Get study-specific profiling config
    profiling_config = self.config.get_profiling_config(self.study_type)
    execution_control = self.config["execution_control"] or {"do_setup": True, "do_run": True, "do_extract": True}

    self.profiler = Profiler(
        execution_control,  # type: ignore
        profiling_config,
        self.study_type,
        self.config.profiling_config_path,
    )
    self.line_profiler = None

    self.project_manager = ProjectManager(
        self.config,
        self.verbose_logger,
        self.progress_logger,
        self.gui,
        no_cache=self.no_cache,
    )

Near Field Study

goliat.studies.near_field_study.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
def __init__(
    self,
    study_type: str,
    config_filename: Optional[str] = None,
    gui: Optional["QueueGUI"] = None,
    profiler=None,
    no_cache: bool = False,
):
    """Load config, set up loggers and profiler, determine base directory."""
    self.study_type = study_type
    self.gui = gui
    self.verbose_logger = logging.getLogger("verbose")
    self.progress_logger = logging.getLogger("progress")
    self.no_cache = no_cache

    # Determine base_dir: prefer cwd if it has configs/, otherwise fallback to package location
    cwd = os.getcwd()
    if os.path.isdir(os.path.join(cwd, "configs")):
        self.base_dir = cwd
    else:
        # Fallback: calculate from package location (for backwards compatibility)
        self.base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

    self.config = Config(
        self.base_dir,
        config_filename if config_filename else f"{self.study_type}_config.json",
    )

    # Get study-specific profiling config
    profiling_config = self.config.get_profiling_config(self.study_type)
    execution_control = self.config["execution_control"] or {"do_setup": True, "do_run": True, "do_extract": True}

    self.profiler = Profiler(
        execution_control,  # type: ignore
        profiling_config,
        self.study_type,
        self.config.profiling_config_path,
    )
    self.line_profiler = None

    self.project_manager = ProjectManager(
        self.config,
        self.verbose_logger,
        self.progress_logger,
        self.gui,
        no_cache=self.no_cache,
    )

Setup Modules

Classes responsible for building the Sim4Life simulation scene.

Base Setup

goliat.setups.base_setup.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
def __init__(self, config: "Config", verbose_logger: "Logger", progress_logger: "Logger", gui: Optional["QueueGUI"] = None):
    """Sets up the base setup.

    Args:
        config: Configuration object.
        verbose_logger: Logger for detailed output.
        progress_logger: Logger for progress updates.
        gui: Optional GUI instance for forwarding progress messages.
    """
    self.config = config
    self.verbose_logger = verbose_logger
    self.progress_logger = progress_logger
    self.gui = gui
    import s4l_v1

    self.s4l_v1 = s4l_v1
    self.emfdtd = self.s4l_v1.simulation.emfdtd
    self.model = self.s4l_v1.model

Methods:

run_full_setup

run_full_setup(project_manager: ProjectManager)

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
def run_full_setup(self, project_manager: "ProjectManager"):
    """Prepares the simulation scene. Must be implemented by subclasses.

    Returns:
        The configured simulation object.

    Raises:
        NotImplementedError: If not overridden by subclass.
    """
    raise NotImplementedError("The 'run_full_setup' method must be implemented by a subclass.")

Boundary Setup

goliat.setups.boundary_setup.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
def __init__(
    self,
    config: "Config",
    simulation: "emfdtd.Simulation",
    verbose_logger: "Logger",
    progress_logger: "Logger",
):
    """Store simulation reference for boundary configuration."""
    super().__init__(config, verbose_logger, progress_logger)
    self.simulation = simulation

Methods:

setup_boundary_conditions

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
def setup_boundary_conditions(self):
    """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.
    """
    self._log("Setting up boundary conditions...", log_type="progress")
    solver_settings = self.config["solver_settings"] or {}
    boundary_config = solver_settings.get("boundary_conditions", {})

    # Set Boundary Type (e.g., UpmlCpml)
    bc_type = boundary_config.get("type", "UpmlCpml")
    self._log(f"  - Setting global boundary conditions to: {bc_type}", log_type="info")

    global_boundaries = self.simulation.GlobalBoundarySettings
    if global_boundaries:
        bc_enum = global_boundaries.GlobalBoundaryType.enum
        if hasattr(bc_enum, bc_type):
            global_boundaries.GlobalBoundaryType = getattr(bc_enum, bc_type)
            self._log(
                f"    - Successfully set GlobalBoundaryType to {bc_type}",
                log_type="verbose",
            )
        else:
            self._log(
                f"    - Warning: Invalid boundary condition type '{bc_type}'. Using default.",
                log_type="warning",
            )
    else:
        self._log(
            "    - Warning: 'GlobalBoundarySettings' not found on simulation object.",
            log_type="warning",
        )

    # Set PML Strength
    strength = boundary_config.get("strength", "Medium").capitalize()
    self._log(f"  - Setting PML strength to: {strength}", log_type="info")

    boundary_settings_list = [x for x in self.simulation.AllSettings if isinstance(x, self.emfdtd.BoundarySettings)]
    if not boundary_settings_list:
        self._log(
            "  - No BoundarySettings found in simulation. Cannot set PML strength.",
            log_type="warning",
        )
        return

    boundary_settings = boundary_settings_list[0]

    strength_enum = boundary_settings.PmlStrength.enum
    if hasattr(strength_enum, strength):
        boundary_settings.PmlStrength = getattr(strength_enum, strength)
        self._log(f"    - Successfully set PmlStrength to {strength}", log_type="verbose")
    else:
        self._log(
            f"    - Warning: Invalid PML strength '{strength}'. Using default (Medium).",
            log_type="warning",
        )
        boundary_settings.PmlStrength = strength_enum.Medium

Far Field Setup

goliat.setups.far_field_setup.FarFieldSetup

FarFieldSetup(config: Config, phantom_name: str, frequency_mhz: int | list[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
def __init__(
    self,
    config: "Config",
    phantom_name: str,
    frequency_mhz: int | list[int],
    direction_name: str,
    polarization_name: str,
    project_manager: "ProjectManager",
    verbose_logger: "Logger",
    progress_logger: "Logger",
    profiler: "Profiler",
    gui=None,
):
    """Store far-field parameters (direction, polarization, frequency)."""
    super().__init__(config, verbose_logger, progress_logger, gui)
    self.phantom_name = phantom_name
    self.frequency_mhz = frequency_mhz
    # For multi-sine, use highest frequency for grid/reference
    self.reference_frequency_mhz = max(frequency_mhz) if isinstance(frequency_mhz, list) else frequency_mhz
    self.is_multisine = isinstance(frequency_mhz, list)
    self.direction_name = direction_name
    self.polarization_name = polarization_name
    self.project_manager = project_manager
    self.profiler = profiler
    self.gui = gui
    self.simulation_type = self.config["far_field_setup.type"]
    if self.simulation_type is None:
        self.simulation_type = "environmental"
    self.document = self.s4l_v1.document

Methods:

run_full_setup

run_full_setup(project_manager: ProjectManager) -> emfdtd.Simulation

Executes the full setup sequence for a single far-field simulation with granular timing.

Source code in goliat/setups/far_field_setup.py
def run_full_setup(self, project_manager: "ProjectManager") -> "emfdtd.Simulation":
    """Executes the full setup sequence for a single far-field simulation with granular timing."""
    self._log("--- Setting up single Far-Field sim ---", log_type="header")

    # Subtask 1: Load phantom
    self._log("    - Load phantom...", level="progress", log_type="progress")
    with self.profiler.subtask("setup_load_phantom"):
        phantom_setup = PhantomSetup(
            self.config,
            self.phantom_name,
            self.verbose_logger,
            self.progress_logger,
        )
        phantom_setup.ensure_phantom_is_loaded()
    elapsed = self.profiler.subtask_times["setup_load_phantom"][-1]
    self._log(f"      - Subtask 'setup_load_phantom' done in {elapsed:.2f}s", log_type="verbose")
    self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    # Subtask 2: Configure scene
    self._log("    - Configure scene (bbox, plane wave)...", level="progress", log_type="progress")
    with self.profiler.subtask("setup_configure_scene"):
        bbox_entity = self._create_or_get_simulation_bbox()
        simulation = self._create_simulation_entity(bbox_entity)
    elapsed = self.profiler.subtask_times["setup_configure_scene"][-1]
    self._log(f"      - Subtask 'setup_configure_scene' done in {elapsed:.2f}s", log_type="verbose")
    self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    # Subtask 3: Assign materials
    self._log("    - Assign materials...", level="progress", log_type="progress")
    with self.profiler.subtask("setup_materials"):
        material_setup = MaterialSetup(
            self.config,
            simulation,
            None,  # type: ignore
            self.phantom_name,
            self.verbose_logger,
            self.progress_logger,
            free_space=False,
            frequencies_mhz=list(self.frequency_mhz) if self.is_multisine else None,  # type: ignore[arg-type]
        )
        material_setup.assign_materials(phantom_only=True)
    elapsed = self.profiler.subtask_times["setup_materials"][-1]
    self._log(f"      - Subtask 'setup_materials' done in {elapsed:.2f}s", log_type="verbose")
    self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    # Subtask 4: Configure solver
    self._log("    - Configure solver (gridding, boundaries, sensors)...", level="progress", log_type="progress")
    with self.profiler.subtask("setup_solver"):
        gridding_setup = GriddingSetup(
            self.config,
            simulation,
            None,  # type: ignore
            None,  # type: ignore
            self.verbose_logger,
            self.progress_logger,
            frequency_mhz=self.reference_frequency_mhz,
        )
        gridding_setup.setup_gridding()

        boundary_setup = BoundarySetup(self.config, simulation, self.verbose_logger, self.progress_logger)
        boundary_setup.setup_boundary_conditions()

        self._add_point_sensors(simulation, "far_field_simulation_bbox")
        self._setup_solver_settings(simulation)
    elapsed = self.profiler.subtask_times["setup_solver"][-1]
    self._log(f"      - Subtask 'setup_solver' done in {elapsed:.2f}s", log_type="verbose")
    self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    # Subtask 5: Voxelize
    self._log("    - Voxelize simulation...", level="progress", log_type="progress")
    with self.profiler.subtask("setup_voxelize"):
        bbox_entity = next(
            (e for e in self.model.AllEntities() if hasattr(e, "Name") and e.Name == "far_field_simulation_bbox"),
            None,
        )
        if not bbox_entity:
            raise RuntimeError("Could not find 'far_field_simulation_bbox' for voxelization.")

        import XCoreModeling

        phantom_entities = [e for e in self.model.AllEntities() if isinstance(e, XCoreModeling.TriangleMesh)]
        point_sensor_entities = [e for e in self.model.AllEntities() if "Point Sensor Entity" in e.Name]

        all_simulation_parts = phantom_entities + [bbox_entity] + point_sensor_entities

        super()._finalize_setup(self.project_manager, simulation, all_simulation_parts, self.reference_frequency_mhz)
    elapsed = self.profiler.subtask_times["setup_voxelize"][-1]
    self._log(f"      - Subtask 'setup_voxelize' done in {elapsed:.2f}s", log_type="verbose")
    self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    # Subtask 6: Save project
    self._log("    - Save project...", level="progress", log_type="progress")
    with self.profiler.subtask("setup_save_project"):
        project_manager.save()
    elapsed = self.profiler.subtask_times["setup_save_project"][-1]
    self._log(f"      - Subtask 'setup_save_project' done in {elapsed:.2f}s", log_type="verbose")
    self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    self._log("Common settings applied.", log_type="success")
    return simulation

Gridding Setup

goliat.setups.gridding_setup.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
def __init__(
    self,
    config: "Config",
    simulation: "emfdtd.Simulation",
    placement_name: str,
    antenna: "Antenna",
    verbose_logger: "Logger",
    progress_logger: "Logger",
    frequency_mhz: int | None = None,
):
    """Initializes the GriddingSetup.

    Args:
        config: Configuration object.
        simulation: The simulation object to configure gridding for.
        placement_name: Name of the placement scenario.
        antenna: Antenna object.
        verbose_logger: Logger for detailed output.
        progress_logger: Logger for progress updates.
        frequency_mhz: Simulation frequency in MHz (optional).
    """
    super().__init__(config, verbose_logger, progress_logger)
    self.simulation = simulation
    self.placement_name = placement_name
    self.antenna = antenna
    self.frequency_mhz = frequency_mhz

    import s4l_v1.units

    self.units = s4l_v1.units

Methods:

setup_gridding

setup_gridding(antenna_components: dict | None = None)

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
def setup_gridding(self, antenna_components: dict | None = None):
    """Sets up main grid and optional antenna subgrids.

    Args:
        antenna_components: Dict mapping component names to entities.
    """
    self._log("Setting up gridding...", log_type="progress")
    self._setup_main_grid()
    if antenna_components:
        self._setup_subgrids(antenna_components)
    else:
        self._log(
            "  - No antenna components provided, skipping subgridding.",
            log_type="info",
        )

Material Setup

goliat.setups.material_setup.MaterialSetup

MaterialSetup(config: Config, simulation: Simulation, antenna: Antenna, phantom_name: str, verbose_logger: Logger, progress_logger: Logger, free_space: bool = False, frequencies_mhz: list[int] | None = None)

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
frequencies_mhz list[int] | None

List of frequencies for multisine dispersion fitting.

None
Source code in goliat/setups/material_setup.py
def __init__(
    self,
    config: "Config",
    simulation: "emfdtd.Simulation",
    antenna: "Antenna",
    phantom_name: str,
    verbose_logger: "Logger",
    progress_logger: "Logger",
    free_space: bool = False,
    frequencies_mhz: list[int] | None = None,
):
    """Initializes the MaterialSetup.

    Args:
        config: Configuration object.
        simulation: The simulation object to assign materials to.
        antenna: Antenna object.
        phantom_name: Name of the phantom model.
        verbose_logger: Logger for detailed output.
        progress_logger: Logger for progress updates.
        free_space: Whether this is a free-space simulation.
        frequencies_mhz: List of frequencies for multisine dispersion fitting.
    """
    super().__init__(config, verbose_logger, progress_logger)
    self.simulation = simulation
    self.antenna = antenna
    self.phantom_name = phantom_name
    self.free_space = free_space
    self.frequencies_mhz = frequencies_mhz
    self.is_multisine = frequencies_mhz is not None and len(frequencies_mhz) > 1

    # Import required modules
    import s4l_v1.materials.database
    import XCoreModeling

    # Access material database - use s4l_v1.materials.database
    self.database = s4l_v1.materials.database
    self.XCoreModeling = XCoreModeling

Methods:

assign_materials

assign_materials(antenna_components: dict | None = None, phantom_only: bool = False)

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
def assign_materials(self, antenna_components: dict | None = None, phantom_only: bool = False):
    """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.

    Args:
        antenna_components: Dict mapping component names to entities.
        phantom_only: If True, skips antenna material assignment.
    """
    self._log("Assigning materials...", log_type="progress")

    # Background material
    background_settings = self.simulation.raw.BackgroundMaterialSettings()  # type: ignore
    air_material = self.database["Generic 1.1"]["Air"]  # type: ignore
    self.simulation.raw.AssignMaterial(background_settings, air_material)  # type: ignore

    # Phantom materials
    if not self.free_space:
        if self.is_multisine:
            self._assign_phantom_materials_multisine()
        else:
            self._assign_phantom_materials()

    # Antenna materials
    if not phantom_only:
        if not antenna_components:
            raise ValueError("antenna_components must be provided when not in phantom_only mode.")
        self._assign_antenna_materials(antenna_components)

Near Field Setup

goliat.setups.near_field_setup.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
def __init__(
    self,
    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,
):
    """Store near-field parameters (scenario, position, orientation, antenna)."""
    super().__init__(config, verbose_logger, progress_logger, gui)
    self.phantom_name = phantom_name
    self.frequency_mhz = frequency_mhz
    self.base_placement_name = scenario_name
    self.position_name = position_name
    self.orientation_name = orientation_name
    self.placement_name = f"{scenario_name}_{position_name}_{orientation_name}"
    self.antenna = antenna
    self.profiler = profiler
    self.gui = gui
    self.free_space = free_space
    # Will be set in _setup_simulation_entity if detuning is enabled
    self.final_frequency_mhz = frequency_mhz

    # S4L modules
    import XCoreModeling

    self.document = self.s4l_v1.document
    self.XCoreModeling = XCoreModeling

Methods:

run_full_setup

run_full_setup(project_manager: ProjectManager, lock=None) -> emfdtd.Simulation

Executes complete setup sequence with detailed timing.

Orchestrates the entire simulation setup process in 6 major subtasks:

  1. Load phantom: Imports phantom model from disk or downloads if missing. Creates head/trunk bounding boxes if needed.

  2. 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.

  3. Assign materials: Maps tissue names to IT'IS database materials, assigns antenna component materials from config. Uses file locking for thread safety.

  4. Configure solver: Sets up gridding (automatic or manual with subgrids), configures boundary conditions (PML), and sets up excitation sources.

  5. Voxelize: Runs automatic voxelization on all simulation entities, updates materials and grid, optionally exports material properties.

  6. 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
def run_full_setup(self, project_manager: "ProjectManager", lock=None) -> "emfdtd.Simulation":
    """Executes complete setup sequence with detailed timing.

    Orchestrates the entire simulation setup process in 6 major subtasks:

    1. Load phantom: Imports phantom model from disk or downloads if missing.
       Creates head/trunk bounding boxes if needed.

    2. 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.

    3. Assign materials: Maps tissue names to IT'IS database materials, assigns
       antenna component materials from config. Uses file locking for thread safety.

    4. Configure solver: Sets up gridding (automatic or manual with subgrids),
       configures boundary conditions (PML), and sets up excitation sources.

    5. Voxelize: Runs automatic voxelization on all simulation entities, updates
       materials and grid, optionally exports material properties.

    6. 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.

    Args:
        project_manager: Project manager for saving operations.
        lock: Optional lock (currently unused, reserved for future use).

    Returns:
        Fully configured simulation object ready for execution.
    """
    self._log("Running full simulation setup...", log_type="progress")

    # Subtask 1: Load phantom
    if not self.free_space:
        self._log("    - Load phantom...", level="progress", log_type="progress")
        with self.profiler.subtask("setup_load_phantom"):
            phantom_setup = PhantomSetup(
                self.config,
                self.phantom_name,
                self.verbose_logger,
                self.progress_logger,
            )
            phantom_setup.ensure_phantom_is_loaded()
        elapsed = self.profiler.subtask_times["setup_load_phantom"][-1]
        self._log(f"      - Subtask 'setup_load_phantom' done in {elapsed:.2f}s", log_type="verbose")
        self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    # Subtask 2: Configure scene
    self._log("    - Configure scene (bboxes, placement, simulation, sensors)...", level="progress", log_type="progress")
    with self.profiler.subtask("setup_configure_scene"):
        if not self.free_space:
            self._setup_bounding_boxes()

        placement_setup = PlacementSetup(
            self.config,
            self.phantom_name,
            self.frequency_mhz,
            self.base_placement_name,
            self.position_name,
            self.orientation_name,
            self.antenna,
            self.verbose_logger,
            self.progress_logger,
            self.free_space,
        )
        placement_setup.place_antenna()

        antenna_components = self._get_antenna_components()
        self._create_simulation_bbox()
        simulation = self._setup_simulation_entity()

        # Configure overall field sensor based on config
        self._configure_overall_field_sensor(simulation, self.frequency_mhz)

        sim_bbox_name = f"{self.placement_name.lower()}_simulation_bbox"
        self._add_point_sensors(simulation, sim_bbox_name)

        self._handle_phantom_rotation(placement_setup)
        self._align_simulation_with_phone()

    elapsed = self.profiler.subtask_times["setup_configure_scene"][-1]
    self._log(f"      - Subtask 'setup_configure_scene' done in {elapsed:.2f}s", log_type="verbose")
    self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    # Subtask 3: Assign materials
    self._log("    - Assign materials...", level="progress", log_type="progress")
    with self.profiler.subtask("setup_materials"):
        material_setup = MaterialSetup(
            self.config,
            simulation,
            self.antenna,
            self.phantom_name,
            self.verbose_logger,
            self.progress_logger,
            self.free_space,
        )
        material_setup.assign_materials(antenna_components)

    elapsed = self.profiler.subtask_times["setup_materials"][-1]
    self._log(f"      - Subtask 'setup_materials' done in {elapsed:.2f}s", log_type="verbose")
    self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    # Subtask 4: Configure solver
    self._log("    - Configure solver (gridding, boundaries, sources)...", level="progress", log_type="progress")
    with self.profiler.subtask("setup_solver"):
        gridding_setup = GriddingSetup(
            self.config,
            simulation,
            self.placement_name,
            self.antenna,
            self.verbose_logger,
            self.progress_logger,
            frequency_mhz=self.frequency_mhz,
        )
        gridding_setup.setup_gridding(antenna_components)

        boundary_setup = BoundarySetup(self.config, simulation, self.verbose_logger, self.progress_logger)
        boundary_setup.setup_boundary_conditions()

        # Use final frequency (with detuning applied) for source setup
        source_frequency = getattr(self, "final_frequency_mhz", self.frequency_mhz)
        source_setup = SourceSetup(
            self.config,
            simulation,
            source_frequency,
            self.antenna,
            self.verbose_logger,
            self.progress_logger,
            self.free_space,
            self.phantom_name,
            self.placement_name,
        )
        source_setup.setup_source_and_sensors(antenna_components)

    elapsed = self.profiler.subtask_times["setup_solver"][-1]
    self._log(f"      - Subtask 'setup_solver' done in {elapsed:.2f}s", log_type="verbose")
    self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    # Subtask 5: Voxelize
    self._log("    - Voxelize simulation...", level="progress", log_type="progress")
    with self.profiler.subtask("setup_voxelize"):
        all_antenna_parts = list(antenna_components.values())
        point_sensor_entities = [e for e in self.model.AllEntities() if "Point Sensor Entity" in e.Name]

        if self.free_space:
            sim_bbox_name = "freespace_simulation_bbox"
        else:
            sim_bbox_name = f"{self.placement_name.lower()}_simulation_bbox"

        sim_bbox_entity = next(
            (e for e in self.model.AllEntities() if hasattr(e, "Name") and e.Name == sim_bbox_name),
            None,
        )
        if not sim_bbox_entity:
            raise RuntimeError(f"Could not find simulation bounding box: '{sim_bbox_name}' for voxelization.")

        phantom_entities = [e for e in self.model.AllEntities() if isinstance(e, self.XCoreModeling.TriangleMesh)]
        all_simulation_parts = phantom_entities + all_antenna_parts + point_sensor_entities + [sim_bbox_entity]

        super()._finalize_setup(project_manager, simulation, all_simulation_parts, self.frequency_mhz)

    elapsed = self.profiler.subtask_times["setup_voxelize"][-1]
    self._log(f"      - Subtask 'setup_voxelize' done in {elapsed:.2f}s", log_type="verbose")
    self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    # Subtask 6: Save project
    self._log("    - Save project...", level="progress", log_type="progress")
    with self.profiler.subtask("setup_save_project"):
        project_manager.save()
    elapsed = self.profiler.subtask_times["setup_save_project"][-1]
    self._log(f"      - Subtask 'setup_save_project' done in {elapsed:.2f}s", log_type="verbose")
    self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    self._log("Full simulation setup complete.", log_type="success")
    return simulation

Phantom Setup

goliat.setups.phantom_setup.PhantomSetup

PhantomSetup(config: Config, phantom_name: str, verbose_logger: Logger, progress_logger: Logger)

Bases: BaseSetup

Handles loading and importing phantom models into Sim4Life.

Source code in goliat/setups/phantom_setup.py
def __init__(
    self,
    config: "Config",
    phantom_name: str,
    verbose_logger: "Logger",
    progress_logger: "Logger",
):
    """Store phantom name and import S4L modules."""
    super().__init__(config, verbose_logger, progress_logger)
    self.phantom_name = phantom_name

    import s4l_v1.data
    import s4l_v1.model
    import XCoreModeling

    self.model = s4l_v1.model
    self.data = s4l_v1.data
    self.XCoreModeling = XCoreModeling

Methods:

ensure_phantom_is_loaded

ensure_phantom_is_loaded() -> bool

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
def ensure_phantom_is_loaded(self) -> bool:
    """Checks if phantom is loaded, imports from disk if available, or downloads if missing.

    Returns:
        True if phantom is now loaded, False if download was initiated (requires re-run).
    """
    self._log("--- Running Phantom Check ---", log_type="header")
    all_entities = self.model.AllEntities()
    self._log(f"Found {len(all_entities)} total entities in the project.", log_type="info")

    is_loaded = False
    for i, entity in enumerate(all_entities):
        if hasattr(entity, "Name"):
            entity_name_lower = entity.Name.lower()
            phantom_name_lower = self.phantom_name.lower()
            if phantom_name_lower in entity_name_lower:
                is_loaded = True
                break
        else:
            self._log(f"  - Entity {i}: (No 'Name' attribute)", log_type="verbose")

    if is_loaded:
        self._log(
            "--- Phantom Check Result: Phantom model is already present. ---",
            log_type="success",
        )
        return True
    else:
        self._log(
            "--- Phantom Check Result: Phantom not found in project. ---",
            log_type="warning",
        )

    study_type = self.config["study_type"]
    if study_type == "near_field" or study_type == "far_field":
        sab_path = os.path.join(self.config.base_dir, "data", "phantoms", f"{self.phantom_name}.sab")
        if os.path.exists(sab_path):
            self._log(
                f"Phantom not found in document. Importing from '{sab_path}'...",
                log_type="info",
            )
            self.XCoreModeling.Import(sab_path)
            self._log("Phantom imported successfully.", log_type="success")
            return True

        self._log(
            f"Local .sab file not found. Attempting to download '{self.phantom_name}'...",
            log_type="info",
        )
        available_downloads = self.data.GetAvailableDownloads()
        phantom_to_download = next(
            (item for item in available_downloads if self.phantom_name.lower() in item.Name.lower()),
            None,
        )

        if not phantom_to_download:
            raise FileNotFoundError(f"Phantom '{self.phantom_name}' not found for download or in local files.")

        self._log(f"Found '{phantom_to_download.Name}'. Downloading...", log_type="info")
        download_email = self.config["download_email"]
        if download_email is None:
            download_email = "example@example.com"
        self.data.DownloadModel(
            phantom_to_download,
            email=download_email,  # type: ignore
            directory=os.path.join(self.config.base_dir, "data", "phantoms"),
        )
        self._log(
            "Phantom downloaded successfully. Please re-run the script to import the new .sab file.",
            log_type="success",
        )
        return False
    else:
        raise ValueError(f"Unknown study type: {study_type}")

Placement Setup

goliat.setups.placement_setup.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
def __init__(
    self,
    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,
):
    """Initializes the PlacementSetup.

    Args:
        config: Configuration object.
        phantom_name: Name of the phantom model.
        frequency_mhz: Simulation frequency in MHz.
        base_placement_name: Base name of the placement scenario.
        position_name: Name of the position within the scenario.
        orientation_name: Name of the orientation within the scenario.
        antenna: Antenna object to place.
        verbose_logger: Logger for detailed output.
        progress_logger: Logger for progress updates.
        free_space: Whether this is a free-space simulation.
    """
    super().__init__(config, verbose_logger, progress_logger)
    self.phantom_name = phantom_name
    self.frequency_mhz = frequency_mhz
    self.base_placement_name = base_placement_name
    self.position_name = position_name
    self.orientation_name = orientation_name
    self.placement_name = f"{base_placement_name}_{position_name}_{orientation_name}"
    self.antenna = antenna
    self.free_space = free_space

    # Import XCoreMath for transformations
    import XCoreMath

    self.XCoreMath = XCoreMath

Methods:

place_antenna

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
def place_antenna(self):
    """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.

    Args:
        None (uses instance attributes: antenna, placement_name, etc.)

    Raises:
        RuntimeError: If antenna import fails or required entities aren't found.
    """
    self._log(
        f"--- Starting Placement: {self.base_placement_name} - {self.position_name} - {self.orientation_name} ---",
        log_type="header",
    )

    phantom_definition = (self.config["phantom_definitions"] or {}).get(self.phantom_name.lower(), {})
    if not self.free_space and not phantom_definition.get("placements", {}).get(f"do_{self.base_placement_name}"):
        self._log(
            f"Placement '{self.base_placement_name}' is disabled in the configuration.",
            log_type="info",
        )
        return

    base_target_point, position_offset = self._get_placement_details()

    # Import antenna model
    antenna_path = self.antenna.get_centered_antenna_path(os.path.join(self.config.base_dir, "data", "antennas", "centered"))
    imported_entities = list(self.model.Import(antenna_path))

    antenna_group = next(
        (e for e in imported_entities if "Antenna" in e.Name and "bounding box" not in e.Name),
        None,
    )
    bbox_entity = next((e for e in imported_entities if "bounding box" in e.Name), None)

    if not antenna_group:
        raise RuntimeError("Could not find imported antenna group.")

    # Find the "Ground" entity/entities ("PCB" of the phone excl. IFA antenna)
    ground_entities = [e for e in antenna_group.Entities if "Ground" in e.Name or "Substrate" in e.Name]  # type: ignore

    # Normalize antenna group name to use requested frequency (in case fallback file was used)
    # Replace any frequency in the name with the requested frequency
    normalized_name = re.sub(r"\d+\s*MHz", f"{self.antenna.frequency_mhz} MHz", antenna_group.Name)

    # Rename the entities to include the placement name for uniqueness
    antenna_group.Name = f"{normalized_name} ({self.placement_name})"
    if bbox_entity:
        # Also normalize bounding box name if it contains frequency
        normalized_bbox_name = re.sub(r"\d+\s*MHz", f"{self.antenna.frequency_mhz} MHz", bbox_entity.Name)
        bbox_entity.Name = f"{normalized_bbox_name} ({self.placement_name})"

    entities_to_transform = [antenna_group, bbox_entity] if bbox_entity else [antenna_group]

    # --- Transformation Composition ---
    self._log("Composing final transformation...", log_type="progress")

    # Start with an identity transform
    final_transform = self.XCoreMath.Transform()

    # 1. Stand-up Rotation
    rot_stand_up = self.XCoreMath.Rotation(self.XCoreMath.Vec3(1, 0, 0), np.deg2rad(90))
    final_transform = rot_stand_up * final_transform

    # 2. Base translation to antenna reference point (speaker output of the mock-up phone)
    reference_target_point = self._get_speaker_reference(ground_entities, upright_transform=final_transform)
    base_translation = self.XCoreMath.Translation(reference_target_point)
    final_transform = base_translation * final_transform

    # Special rotation for 'by_cheek' to align with YZ plane
    if self.base_placement_name.startswith("by_cheek"):
        self._log("Applying 'by_cheek' specific Z-rotation.", log_type="info")
        rot_z_cheek = self.XCoreMath.Rotation(self.XCoreMath.Vec3(0, 0, 1), np.deg2rad(-90))
        final_transform = rot_z_cheek * final_transform

    # 3. Orientation Twist
    if self.orientation_rotations:
        for rot in self.orientation_rotations:
            axis_map = {
                "X": self.XCoreMath.Vec3(1, 0, 0),
                "Y": self.XCoreMath.Vec3(0, 1, 0),
                "Z": self.XCoreMath.Vec3(0, 0, 1),
            }
            rot_twist = self.XCoreMath.Rotation(axis_map[rot["axis"].upper()], np.deg2rad(rot["angle_deg"]))
            final_transform = rot_twist * final_transform

    # 4. Final Translation
    final_target_point = self.model.Vec3(
        base_target_point[0] + position_offset[0],
        base_target_point[1] + position_offset[1],
        base_target_point[2] + position_offset[2],
    )
    translation_transform = self.XCoreMath.Translation(final_target_point)
    final_transform = translation_transform * final_transform

    # --- Apply the single, composed transform ---
    self._log("Applying final composed transform.", log_type="progress")
    for entity in entities_to_transform:
        entity.ApplyTransform(final_transform)

    self._log("--- Transformation Sequence Complete ---", log_type="success")

Source Setup

goliat.setups.source_setup.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
def __init__(
    self,
    config: "Config",
    simulation: "emfdtd.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,
):
    """Store simulation, frequency, and antenna for source configuration."""
    super().__init__(config, verbose_logger, progress_logger)
    self.simulation = simulation
    self.frequency_mhz = frequency_mhz
    self.antenna = antenna
    self.free_space = free_space
    self.phantom_name = phantom_name
    self.placement_name = placement_name

    import s4l_v1.units

    self.units = s4l_v1.units

Methods:

setup_source_and_sensors

setup_source_and_sensors(antenna_components: dict)

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
def setup_source_and_sensors(self, antenna_components: dict):
    """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.

    Args:
        antenna_components: Dict mapping component names to entities.
    """
    self._log("Setting up source and sensors...", log_type="progress")

    source_name = self.antenna.get_source_entity_name()
    if source_name not in antenna_components:
        raise RuntimeError(f"Could not find source entity '{source_name}' in antenna group.")
    source_entity = antenna_components[source_name]

    # Source setup
    edge_source_settings = self.emfdtd.EdgeSourceSettings()

    # Get the enum for ExcitationType
    excitation_enum = edge_source_settings.ExcitationType.enum

    # Read excitation type from config (default to Harmonic for backward compatibility)
    excitation_type = self.config["simulation_parameters.excitation_type"] or "Harmonic"
    excitation_type_lower = excitation_type.lower() if isinstance(excitation_type, str) else "harmonic"

    if excitation_type_lower == "gaussian":
        bandwidth_mhz_val = self.config["simulation_parameters.bandwidth_mhz"] or 50.0
        bandwidth_mhz = float(bandwidth_mhz_val) if not isinstance(bandwidth_mhz_val, dict) else 50.0
        k_val = self.config["simulation_parameters.gaussian_pulse_k"] or 3
        k = int(k_val) if not isinstance(k_val, dict) else 3

        if k == 5:
            # Use Sim4Life built-in Gaussian (forced k=5)
            self._log(f"  - Using Sim4Life built-in Gaussian source (BW: {bandwidth_mhz} MHz, k=5).", log_type="info")
            edge_source_settings.ExcitationType = excitation_enum.Gaussian
            edge_source_settings.CenterFrequency = self.frequency_mhz, self.units.MHz
            edge_source_settings.Bandwidth = bandwidth_mhz, self.units.MHz
        else:
            # Use custom Gaussian waveform with user-defined k (faster pulse)
            self._log(f"  - Using custom Gaussian source (BW: {bandwidth_mhz} MHz, k={k}).", log_type="info")
            edge_source_settings.ExcitationType = excitation_enum.UserDefined

            # Set up user-defined signal from equation
            user_signal_enum = edge_source_settings.UserSignalType.enum
            edge_source_settings.UserSignalType = user_signal_enum.FromEquation

            # Calculate parameters for Gaussian pulse
            # σ = 0.94/(π·BW), t₀ = k·σ (to start near zero)
            bandwidth_hz = bandwidth_mhz * 1e6
            center_freq_hz = self.frequency_mhz * 1e6
            sigma = 0.94 / (np.pi * bandwidth_hz)
            t0 = float(k) * sigma

            # Create Gaussian-modulated pulse expression: A * exp(-(_t-t₀)²/(2σ²)) * cos(2π·f₀·_t)
            # Using Sim4Life expression syntax with '_t' as time variable
            # Note: Using ** for exponentiation (Python-style) instead of ^
            amplitude = 1.0
            expression = f"{amplitude} * exp(-(_t - {t0})**2 / (2 * {sigma}**2)) * cos(2 * pi * {center_freq_hz} * _t)"
            edge_source_settings.UserExpression = expression

            # Set center frequency for reference (used by post-processing)
            edge_source_settings.CenterFrequency = self.frequency_mhz, self.units.MHz
    else:
        self._log("  - Using Harmonic source.", log_type="info")
        # Frequency already has detuning applied in NearFieldSetup if enabled
        edge_source_settings.ExcitationType = excitation_enum.Harmonic
        edge_source_settings.Frequency = self.frequency_mhz, self.units.MHz
        edge_source_settings.CenterFrequency = self.frequency_mhz, self.units.MHz

    self.simulation.Add(edge_source_settings, [source_entity])

    # Sensor setup
    edge_sensor_settings = self.emfdtd.EdgeSensorSettings()
    self.simulation.Add(edge_sensor_settings, [source_entity])

    # Far-field sensors only for free-space simulations (for radiation patterns)
    if self.free_space:
        far_field_sensor_settings = self.simulation.AddFarFieldSensorSettings()

        # Configure extracted frequencies for Gaussian source
        if excitation_type_lower == "gaussian":
            center_freq_hz = self.frequency_mhz * 1e6
            bandwidth_mhz_val = self.config["simulation_parameters.bandwidth_mhz"] or 50.0
            bandwidth_mhz_ff = float(bandwidth_mhz_val) if not isinstance(bandwidth_mhz_val, dict) else 50.0
            bandwidth_hz = bandwidth_mhz_ff * 1e6
            start_freq_hz = center_freq_hz - (bandwidth_hz / 2)
            end_freq_hz = center_freq_hz + (bandwidth_hz / 2)

            # Create a list of 21 frequencies, including the center frequency
            num_samples = 21
            extracted_frequencies_hz = [start_freq_hz + i * (bandwidth_hz / (num_samples - 1)) for i in range(num_samples)]

            far_field_sensor_settings.ExtractedFrequencies = (
                extracted_frequencies_hz,
                self.units.Hz,
            )
            self._log(
                f"  - Set extracted frequencies from {start_freq_hz / 1e6} MHz to {end_freq_hz / 1e6} MHz.",
                log_type="info",
            )

Execution Strategies

Strategy pattern implementations for different simulation execution methods.

Execution Strategy

goliat.runners.execution_strategy.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
def __init__(
    self,
    config: "Config",
    project_path: str,
    simulation: "s4l_v1.simulation.emfdtd.Simulation",
    profiler: "Profiler",
    verbose_logger: "LoggingMixin",
    progress_logger: "LoggingMixin",
    project_manager: "ProjectManager",
    gui: "QueueGUI | None" = None,
):
    """Initialize execution strategy.

    Args:
        config: Configuration object.
        project_path: Path to the Sim4Life project file.
        simulation: The simulation object to run.
        profiler: Profiler for timing subtasks.
        verbose_logger: Logger for detailed output.
        progress_logger: Logger for high-level updates.
        project_manager: ProjectManager instance.
        gui: Optional GUI proxy for updates.
    """
    self.config = config
    self.project_path = project_path
    self.simulation = simulation
    self.profiler = profiler
    self.verbose_logger = verbose_logger
    self.progress_logger = progress_logger
    self.project_manager = project_manager
    self.gui = gui

Methods:

run abstractmethod

run() -> None

Execute the simulation using this strategy.

Raises:

Type Description
StudyCancelledError

If execution is cancelled by user.

RuntimeError

If execution fails.

FileNotFoundError

If required files are missing.

Source code in goliat/runners/execution_strategy.py
@abstractmethod
def run(self) -> None:
    """Execute the simulation using this strategy.

    Raises:
        StudyCancelledError: If execution is cancelled by user.
        RuntimeError: If execution fails.
        FileNotFoundError: If required files are missing.
    """
    pass

Isolve Manual Strategy

goliat.runners.isolve_manual_strategy.ISolveManualStrategy

ISolveManualStrategy(*args, **kwargs)

Bases: ExecutionStrategy, LoggingMixin

Execution strategy for running iSolve.exe directly via subprocess.

Source code in goliat/runners/isolve_manual_strategy.py
def __init__(self, *args, **kwargs):
    """Initialize iSolve manual strategy."""
    super().__init__(*args, **kwargs)
    self.current_isolve_process = None
    self.current_process_manager = None

Methods:

reset_memory_error_count classmethod

reset_memory_error_count() -> None

Reset the memory error counter. Called at start of new session.

Source code in goliat/runners/isolve_manual_strategy.py
@classmethod
def reset_memory_error_count(cls) -> None:
    """Reset the memory error counter. Called at start of new session."""
    cls._memory_error_count = 0

run

run() -> None

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
def run(self) -> None:
    """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:
        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.
    """
    command = self._prepare_isolve_command()

    try:
        self._log("    - Execute iSolve...", level="progress", log_type="progress")
        with self.profiler.subtask("run_isolve_execution"):
            output_parser = ISolveOutputParser(self.verbose_logger, self.progress_logger, self.gui)
            keep_awake_handler = KeepAwakeHandler(self.config)
            retry_handler = RetryHandler(self.progress_logger, self.gui)
            keep_awake_handler.trigger_before_retry()

            while True:
                self._check_for_stop_signal()
                if retry_handler.get_attempt_number() > 0:
                    keep_awake_handler.trigger_before_retry()
                if self._run_single_attempt(command, output_parser, keep_awake_handler, retry_handler) == "done":
                    break

        elapsed = self.profiler.subtask_times["run_isolve_execution"][-1]
        self._log(f"      - Subtask 'run_isolve_execution' done in {elapsed:.2f}s", log_type="verbose")
        self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

        post_handler = PostSimulationHandler(self.project_path, self.profiler, self.verbose_logger, self.progress_logger)
        post_handler.wait_and_reload()

    except StudyCancelledError:
        self._cleanup()
        raise
    except Exception as e:
        self._cleanup()
        self._log(
            f"An unexpected error occurred while running iSolve.exe: {e}",
            level="progress",
            log_type="error",
        )
        self.verbose_logger.error(traceback.format_exc())
        raise
    finally:
        self._cleanup()

Isolve Output Parser

goliat.runners.isolve_output_parser.ProgressInfo dataclass

ProgressInfo(percentage: int, time_remaining: str, mcells_per_sec: str)

Extracted progress information from iSolve output.

Isolve Process Manager

goliat.runners.isolve_process_manager.ISolveProcessManager

ISolveProcessManager(command: List[str], gui: Optional[QueueGUI], verbose_logger: Logger, progress_logger: Logger)

Bases: LoggingMixin

Manages iSolve subprocess lifecycle and non-blocking I/O.

Parameters:

Name Type Description Default
command List[str]

Command to execute (e.g., [isolve_path, "-i", input_file]).

required
gui Optional[QueueGUI]

GUI proxy for stop signal checks.

required
verbose_logger Logger

Logger for verbose output.

required
progress_logger Logger

Logger for progress output.

required
Source code in goliat/runners/isolve_process_manager.py
def __init__(
    self,
    command: List[str],
    gui: Optional["QueueGUI"],
    verbose_logger: "Logger",
    progress_logger: "Logger",
):
    """Initialize process manager.

    Args:
        command: Command to execute (e.g., [isolve_path, "-i", input_file]).
        gui: GUI proxy for stop signal checks.
        verbose_logger: Logger for verbose output.
        progress_logger: Logger for progress output.
    """
    self.command = command
    self.gui = gui
    self.verbose_logger = verbose_logger
    self.progress_logger = progress_logger
    self.process: Optional[subprocess.Popen] = None
    self.output_queue: Optional[Queue] = None
    self.reader_thread: Optional[threading.Thread] = None
    self._is_running = False

Methods:

start

start() -> None

Start the subprocess and begin reading output.

Source code in goliat/runners/isolve_process_manager.py
def start(self) -> None:
    """Start the subprocess and begin reading output."""
    self.process = subprocess.Popen(
        self.command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        creationflags=subprocess.CREATE_NO_WINDOW,
    )
    self.output_queue = Queue()
    self.reader_thread = threading.Thread(target=_reader_thread, args=(self.process.stdout, self.output_queue))
    self.reader_thread.daemon = True
    self.reader_thread.start()
    self._is_running = True

is_running

is_running() -> bool

Check if process is still running.

Source code in goliat/runners/isolve_process_manager.py
def is_running(self) -> bool:
    """Check if process is still running."""
    return self._is_running and self.process is not None and self.process.poll() is None

read_available_lines

read_available_lines() -> List[str]

Read all available lines from output queue (non-blocking).

Returns:

Type Description
List[str]

List of lines read (may be empty if no output available).

Source code in goliat/runners/isolve_process_manager.py
def read_available_lines(self) -> List[str]:
    """Read all available lines from output queue (non-blocking).

    Returns:
        List of lines read (may be empty if no output available).
    """
    if self.output_queue is None:
        return []

    lines = []
    try:
        while True:
            lines.append(self.output_queue.get_nowait())
    except Empty:
        pass
    return lines

read_all_remaining_lines

read_all_remaining_lines() -> List[str]

Read all remaining lines after process completes.

Should be called after is_running() returns False. Ensures reader thread has finished and queue is drained.

Returns:

Type Description
List[str]

List of all remaining lines.

Source code in goliat/runners/isolve_process_manager.py
def read_all_remaining_lines(self) -> List[str]:
    """Read all remaining lines after process completes.

    Should be called after is_running() returns False.
    Ensures reader thread has finished and queue is drained.

    Returns:
        List of all remaining lines.
    """
    if self.reader_thread is not None and self.reader_thread.is_alive():
        self.reader_thread.join()

    lines = []
    if self.output_queue is not None:
        while not self.output_queue.empty():
            try:
                lines.append(self.output_queue.get_nowait())
            except Empty:
                break
    return lines

get_return_code

get_return_code() -> Optional[int]

Get process return code (None if still running).

Source code in goliat/runners/isolve_process_manager.py
def get_return_code(self) -> Optional[int]:
    """Get process return code (None if still running)."""
    return self.process.returncode if self.process else None

read_stderr

read_stderr() -> str

Read stderr output (fallback - most errors are in stdout).

Returns:

Type Description
str

Stripped stderr string or empty string.

Source code in goliat/runners/isolve_process_manager.py
def read_stderr(self) -> str:
    """Read stderr output (fallback - most errors are in stdout).

    Returns:
        Stripped stderr string or empty string.
    """
    if self.process is None or self.process.stderr is None:
        return ""

    try:
        stderr_output = self.process.stderr.read()
        if stderr_output:
            return stderr_output.strip()
    except Exception:
        pass
    return ""

terminate

terminate(timeout: float = 2.0) -> None

Terminate process, force kill if it doesn't stop in time.

Parameters:

Name Type Description Default
timeout float

Seconds to wait before force killing.

2.0
Source code in goliat/runners/isolve_process_manager.py
def terminate(self, timeout: float = 2.0) -> None:
    """Terminate process, force kill if it doesn't stop in time.

    Args:
        timeout: Seconds to wait before force killing.
    """
    if self.process is None:
        return

    if self.process.poll() is None:
        try:
            self.process.terminate()
            self.process.wait(timeout=timeout)
        except subprocess.TimeoutExpired:
            self.process.kill()
            self.process.wait()
        except Exception:
            pass

cleanup

cleanup() -> None

Clean up process and threads.

Source code in goliat/runners/isolve_process_manager.py
def cleanup(self) -> None:
    """Clean up process and threads."""
    if self.process is not None:
        if self.process.poll() is None:
            try:
                self.process.terminate()
                self.process.wait(timeout=2)
            except subprocess.TimeoutExpired:
                self.process.kill()
                self.process.wait()
            except Exception:
                pass
        self.process = None

    if self.reader_thread is not None and self.reader_thread.is_alive():
        self.reader_thread.join()

    self._is_running = False

    # Adaptive delay based on memory usage (more memory = longer wait)
    if psutil is not None:
        try:
            memory = psutil.virtual_memory()
            used_gb = memory.used / (1024**3)
            # Scale delay: 0.5s base + 0.1s per 10GB used (max 3s)
            delay = min(0.5 + (used_gb / 10.0) * 0.1, 3.0)
            time.sleep(delay)
        except Exception:
            time.sleep(0.5)  # Fallback to default
    else:
        time.sleep(0.5)

    # Force garbage collection to free Python-side memory
    gc.collect()

check_stop_signal

check_stop_signal() -> None

Check for stop signal and terminate if requested.

Raises:

Type Description
StudyCancelledError

If stop signal detected.

Source code in goliat/runners/isolve_process_manager.py
def check_stop_signal(self) -> None:
    """Check for stop signal and terminate if requested.

    Raises:
        StudyCancelledError: If stop signal detected.
    """
    if self.gui and self.gui.is_stopped():
        self._log("Stop signal detected, terminating iSolve subprocess...", log_type="warning")
        self.terminate(timeout=2)
        raise StudyCancelledError("Study cancelled by user.")

Keep Awake Handler

goliat.runners.keep_awake_handler.KeepAwakeHandler

KeepAwakeHandler(config: Config)

Handles keep_awake script triggering.

Parameters:

Name Type Description Default
config Config

Configuration object.

required
Source code in goliat/runners/keep_awake_handler.py
def __init__(self, config: "Config"):
    """Initialize keep_awake handler.

    Args:
        config: Configuration object.
    """
    self.config = config
    self.triggered = False

Methods:

trigger_before_retry

trigger_before_retry() -> None

Trigger keep_awake before retry attempt.

Source code in goliat/runners/keep_awake_handler.py
def trigger_before_retry(self) -> None:
    """Trigger keep_awake before retry attempt."""
    if not (self.config["keep_awake"] or False):
        return

    try:
        # Path: goliat/goliat/runners/keep_awake_handler.py -> goliat/goliat/utils/scripts/
        script_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "utils", "scripts")
        if script_dir not in sys.path:
            sys.path.insert(0, script_dir)
        from keep_awake import keep_awake  # type: ignore

        keep_awake()
    except Exception as e:
        print(f"Warning: keep_awake() failed: {e}")
        if sys.stdout is not None:
            sys.stdout.flush()

trigger_on_progress

trigger_on_progress() -> None

Trigger keep_awake script on first progress update.

Source code in goliat/runners/keep_awake_handler.py
def trigger_on_progress(self) -> None:
    """Trigger keep_awake script on first progress update."""
    if not (self.config["keep_awake"] or False):
        return

    if self.triggered:
        return

    script_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "utils", "scripts", "keep_awake.py")
    if os.path.exists(script_path):
        subprocess.Popen([sys.executable, script_path])
    self.triggered = True

reset

reset() -> None

Reset triggered flag (for new simulation).

Source code in goliat/runners/keep_awake_handler.py
def reset(self) -> None:
    """Reset triggered flag (for new simulation)."""
    self.triggered = False

Osparc Direct Strategy

goliat.runners.osparc_direct_strategy.OSPARCDirectStrategy

OSPARCDirectStrategy(server_name: str, *args, **kwargs)

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
def __init__(self, server_name: str, *args, **kwargs):
    """Initialize oSPARC direct strategy.

    Args:
        server_name: oSPARC resource name to use (e.g., 'local', 'osparc-1').
        *args: Passed to parent class.
        **kwargs: Passed to parent class.
    """
    super().__init__(*args, **kwargs)
    self.server_name = server_name

Methods:

run

run() -> None

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 9.2+ 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
def run(self) -> None:
    """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 9.2+ for the XOsparcApiClient module. The method
    handles authentication, job lifecycle, and error reporting.

    Raises:
        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.
    """
    # XOsparcApiClient is only available in Sim4Life 9.2+
    if not is_sim4life_92_or_later():
        detected = get_version_display_string()
        self._log(
            f"XOsparcApiClient requires Sim4Life 9.2+. Detected: {detected}",
            level="progress",
            log_type="error",
        )
        self._log(
            "Use the osparc PyPI package for batch runs on 8.2, or upgrade to 9.2.",
            level="progress",
            log_type="info",
        )
        raise RuntimeError(f"oSPARC direct strategy requires Sim4Life 9.2+, but running on {detected}.")

    import XOsparcApiClient  # type: ignore

    self._log(
        f"--- Running simulation on oSPARC server: {self.server_name} ---",
        level="progress",
        log_type="header",
    )

    # 1. Get Credentials and Initialize Client
    creds = self.config.get_osparc_credentials()
    if not all(k in creds for k in ["api_key", "api_secret", "api_server"]):
        raise ValueError("Missing oSPARC credentials in configuration.")

    client = XOsparcApiClient.OsparcApiClient(
        api_key=creds["api_key"],
        api_secret=creds["api_secret"],
        api_server=creds["api_server"],
        api_version=creds.get("api_version", "v0"),
    )
    self._log("oSPARC client initialized.", log_type="verbose")

    # 2. Prepare Job Submission Data
    input_file_path = os.path.join(os.path.dirname(self.project_path), self.simulation.GetInputFileName())
    if not os.path.exists(input_file_path):
        raise FileNotFoundError(f"Solver input file not found at: {input_file_path}")

    job_data = XOsparcApiClient.JobSubmissionData()
    job_data.InputFilePath = input_file_path
    job_data.ResourceName = self.server_name
    job_data.SolverKey = "sim4life-isolve"
    job_data.SolverVersion = ""  # Let the API choose the default version

    # 3. Create and Start the Job
    self._log(
        f"Creating job for input file: {os.path.basename(input_file_path)}",
        level="progress",
        log_type="info",
    )
    create_response = client.CreateJob(job_data)
    if not create_response.Success:
        raise RuntimeError(f"Failed to create oSPARC job: {create_response.Content}")

    job_id = create_response.Content.get("id")
    if not job_id:
        raise RuntimeError("oSPARC API did not return a job ID after creation.")

    self._log(
        f"Job created with ID: {job_id}. Starting job...",
        level="progress",
        log_type="info",
    )
    start_response = client.StartJob(job_data, job_id)
    if not start_response.Success:
        raise RuntimeError(f"Failed to start oSPARC job {job_id}: {start_response.Content}")

    # 4. Poll for Job Completion
    self._log("Job started. Polling for status...", level="progress", log_type="progress")
    while True:
        self._check_for_stop_signal()

        status_response = client.GetJobStatus(job_data.SolverKey, job_data.SolverVersion, job_id)
        if not status_response.Success:
            self._log(
                f"Warning: Could not get job status for {job_id}.",
                level="progress",
                log_type="warning",
            )
            time.sleep(10)
            continue

        status = status_response.Content.get("state")
        self._log(f"  - Job '{job_id}' status: {status}", log_type="verbose")

        if status in ["SUCCESS", "FAILED", "ABORTED"]:
            log_type = "success" if status == "SUCCESS" else "error"
            self._log(
                f"Job {job_id} finished with status: {status}",
                level="progress",
                log_type=log_type,
            )
            if status != "SUCCESS":
                raise RuntimeError(f"oSPARC job {job_id} failed with status: {status}")
            break

        time.sleep(30)

    # 5. Post-simulation steps
    post_handler = PostSimulationHandler(self.project_path, self.profiler, self.verbose_logger, self.progress_logger)
    post_handler.wait_and_reload()

Post Simulation Handler

goliat.runners.post_simulation_handler.PostSimulationHandler

PostSimulationHandler(project_path: str, profiler: Profiler, verbose_logger: Logger, progress_logger: Logger)

Bases: LoggingMixin

Handles post-simulation tasks: waiting for results and reloading project.

Parameters:

Name Type Description Default
project_path str

Path to project file to reload.

required
profiler Profiler

Profiler for timing subtasks.

required
verbose_logger Logger

Logger for verbose output.

required
progress_logger Logger

Logger for progress output.

required
Source code in goliat/runners/post_simulation_handler.py
def __init__(
    self,
    project_path: str,
    profiler: "Profiler",
    verbose_logger: "Logger",
    progress_logger: "Logger",
):
    """Initialize post-simulation handler.

    Args:
        project_path: Path to project file to reload.
        profiler: Profiler for timing subtasks.
        verbose_logger: Logger for verbose output.
        progress_logger: Logger for progress output.
    """
    self.project_path = project_path
    self.profiler = profiler
    self.verbose_logger = verbose_logger
    self.progress_logger = progress_logger
    import s4l_v1.document

    self.document = s4l_v1.document

Methods:

wait_and_reload

wait_and_reload() -> None

Wait for results and reload project.

Waits 5 seconds for results to be written, then closes and reopens the project to load results into Sim4Life. Only reloads if memory usage is above 60% to free memory.

Source code in goliat/runners/post_simulation_handler.py
def wait_and_reload(self) -> None:
    """Wait for results and reload project.

    Waits 5 seconds for results to be written, then closes and reopens
    the project to load results into Sim4Life. Only reloads if memory
    usage is above 60% to free memory.
    """
    self._log(
        "    - Wait for results...",
        level="progress",
        log_type="progress",
    )
    with self.profiler.subtask("run_wait_for_results"):
        non_blocking_sleep(5)
    elapsed = self.profiler.subtask_times["run_wait_for_results"][-1]
    self._log(f"      - Subtask 'run_wait_for_results' done in {elapsed:.2f}s", log_type="verbose")
    self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    # Check memory usage and reload only if above threshold
    should_reload = False
    if psutil is not None:
        try:
            memory = psutil.virtual_memory()
            memory_percent = memory.percent
            if memory_percent > 60.0:
                should_reload = True
                self._log(
                    f"    - Memory usage at {memory_percent:.1f}%, reloading project to free memory...",
                    level="progress",
                    log_type="progress",
                )
        except Exception:
            # If memory check fails, reload anyway to be safe
            should_reload = True
    else:
        # If psutil not available, reload anyway
        should_reload = True

    if should_reload:
        self._log(
            "    - Reload project...",
            level="progress",
            log_type="progress",
        )
        with self.profiler.subtask("run_reload_project"):
            self.document.Close()
            open_project(self.project_path)
        elapsed = self.profiler.subtask_times["run_reload_project"][-1]
        self._log(f"      - Subtask 'run_reload_project' done in {elapsed:.2f}s", log_type="verbose")
        self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

        # Force garbage collection after reload to free memory
        gc.collect()

        self._log(
            "Project reloaded and results are available.",
            log_type="success",
        )
    else:
        self._log(
            "Memory usage acceptable, skipping reload.",
            log_type="verbose",
        )

Retry Handler

goliat.runners.retry_handler.RetryHandler

RetryHandler(progress_logger: Logger, gui: Optional[QueueGUI] = None)

Bases: LoggingMixin

Manages retry logic and attempt tracking.

Parameters:

Name Type Description Default
progress_logger Logger

Logger for progress-level messages.

required
gui Optional[QueueGUI]

Optional GUI proxy for sending progress messages.

None
Source code in goliat/runners/retry_handler.py
def __init__(self, progress_logger: "Logger", gui: Optional["QueueGUI"] = None):
    """Initialize retry handler.

    Args:
        progress_logger: Logger for progress-level messages.
        gui: Optional GUI proxy for sending progress messages.
    """
    self.progress_logger = progress_logger
    self.gui = gui
    self.attempt_number = 0

Methods:

should_retry

should_retry(return_code: Optional[int], detected_errors: list) -> bool

Determine if retry should occur.

Parameters:

Name Type Description Default
return_code Optional[int]

Process return code (None if exception).

required
detected_errors list

List of errors detected in output.

required

Returns:

Type Description
bool

True if should retry (always True for non-zero return code).

Source code in goliat/runners/retry_handler.py
def should_retry(self, return_code: Optional[int], detected_errors: list) -> bool:
    """Determine if retry should occur.

    Args:
        return_code: Process return code (None if exception).
        detected_errors: List of errors detected in output.

    Returns:
        True if should retry (always True for non-zero return code).
    """
    return return_code != 0

record_attempt

record_attempt() -> None

Record a retry attempt and log it.

Source code in goliat/runners/retry_handler.py
def record_attempt(self) -> None:
    """Record a retry attempt and log it."""
    self.attempt_number += 1
    if self.attempt_number > 0:
        self._log(
            f"    - iSolve failed, retry attempt {self.attempt_number}",
            level="progress",
            log_type="warning",
        )

    # Log error every 50 retries
    if self.attempt_number > 0 and self.attempt_number % 50 == 0:
        self._log(
            f"iSolve failed {self.attempt_number} times",
            level="progress",
            log_type="error",
        )

get_attempt_number

get_attempt_number() -> int

Get current attempt number (0 = first attempt).

Source code in goliat/runners/retry_handler.py
def get_attempt_number(self) -> int:
    """Get current attempt number (0 = first attempt)."""
    return self.attempt_number

reset

reset() -> None

Reset attempt counter (for new simulation).

Source code in goliat/runners/retry_handler.py
def reset(self) -> None:
    """Reset attempt counter (for new simulation)."""
    self.attempt_number = 0

Sim4Life Api Strategy

goliat.runners.sim4life_api_strategy.Sim4LifeAPIStrategy

Sim4LifeAPIStrategy(server_id: str | None, *args, **kwargs)

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
def __init__(self, server_id: str | None, *args, **kwargs):
    """Initialize Sim4Life API strategy.

    Args:
        server_id: Server ID to use (None for localhost).
        *args: Passed to parent class.
        **kwargs: Passed to parent class.
    """
    super().__init__(*args, **kwargs)
    self.server_id = server_id

Methods:

run

run() -> None

Run simulation using Sim4Life API.

Raises:

Type Description
RuntimeError

If simulation execution fails.

Source code in goliat/runners/sim4life_api_strategy.py
def run(self) -> None:
    """Run simulation using Sim4Life API.

    Raises:
        RuntimeError: If simulation execution fails.
    """
    self.simulation.RunSimulation(wait=True, server_id=self.server_id)
    server_name = (self.config["solver_settings"] or {}).get("server", "localhost")
    log_msg = f"Simulation finished on '{server_name}'."
    self._log(log_msg, level="progress", log_type="success")

Results Extraction

Classes for extracting and processing simulation results.

Auto Induced Processor

goliat.extraction.auto_induced_processor.AutoInducedProcessor

AutoInducedProcessor(parent_study: FarFieldStudy, phantom_name: str, freq: int)

Bases: LoggingMixin, _AutoInducedExtractionMixin

Processes auto-induced exposure using existing SAPD extraction infrastructure.

Orchestrates focus search, field combination, and SAPD extraction for a completed set of environmental simulations.

Parameters:

Name Type Description Default
parent_study FarFieldStudy

Parent FarFieldStudy instance (provides loggers, profiler, config).

required
phantom_name str

Name of the phantom (e.g., "thelonious").

required
freq int

Frequency in MHz.

required
Source code in goliat/extraction/auto_induced_processor.py
def __init__(self, parent_study: "FarFieldStudy", phantom_name: str, freq: int):
    """Initialize the processor.

    Args:
        parent_study: Parent FarFieldStudy instance (provides loggers, profiler, config).
        phantom_name: Name of the phantom (e.g., "thelonious").
        freq: Frequency in MHz.
    """
    self.study = parent_study
    self.config = parent_study.config
    self.phantom_name = phantom_name
    self.freq = freq

    # Share loggers from parent study
    self.verbose_logger = parent_study.verbose_logger
    self.progress_logger = parent_study.progress_logger
    self.gui = parent_study.gui

Methods:

process

process(h5_paths: list[Path], input_h5: Path, output_dir: Path) -> dict

Run the auto-induced analysis pipeline.

Parameters:

Name Type Description Default
h5_paths list[Path]

List of _Output.h5 file paths (one per direction/polarization).

required
input_h5 Path

Path to any _Input.h5 file (for skin mask extraction).

required
output_dir Path

Directory to write combined H5 files and results.

required

Returns:

Type Description
dict

Dict with analysis results including candidates, SAPD values, and worst-case.

Source code in goliat/extraction/auto_induced_processor.py
def process(
    self,
    h5_paths: list[Path],
    input_h5: Path,
    output_dir: Path,
) -> dict:
    """Run the auto-induced analysis pipeline.

    Args:
        h5_paths: List of _Output.h5 file paths (one per direction/polarization).
        input_h5: Path to any _Input.h5 file (for skin mask extraction).
        output_dir: Directory to write combined H5 files and results.

    Returns:
        Dict with analysis results including candidates, SAPD values, and worst-case.
    """
    auto_cfg = self.config["auto_induced"] or {}
    top_n = auto_cfg.get("top_n", 10)
    cube_size_mm = auto_cfg.get("cube_size_mm", 100)
    save_intermediate_files = auto_cfg.get("save_intermediate_files", False)
    search_metric = auto_cfg.get("search_metric", "E_magnitude")
    extraction_metric = auto_cfg.get("extraction_metric", "sapd")
    full_volume = auto_cfg.get("full_volume_combination", False)
    combine_chunk_size = auto_cfg.get("combine_chunk_size", 50)
    # For SAR, only E-field is needed; for SAPD, both E and H
    field_types = ("E",) if extraction_metric == "sar" else ("E", "H")

    self._log(
        f"\n--- Auto-Induced Analysis: {self.phantom_name}, {self.freq}MHz ---",
        level="progress",
        log_type="header",
    )
    self._log(
        f"  Combining {len(h5_paths)} simulations, extracting top {top_n} candidates",
        level="progress",
        log_type="info",
    )

    os.makedirs(output_dir, exist_ok=True)

    # Step 1: Focus search
    with self.study.subtask("auto_induced_focus_search"):
        candidates = self._find_focus_candidates(h5_paths, input_h5, top_n, search_metric, output_dir)

    if not candidates:
        self._log("    ERROR: No focus candidates found", log_type="error")
        return {"error": "No focus candidates found", "candidates": []}

    # Step 2: Combine fields for each candidate
    with self.study.subtask("auto_induced_combine_fields"):
        combined_h5_paths = []
        from tqdm import tqdm

        from .field_cache import FieldCache

        # Pre-load all source fields once, shared across all candidates.
        # FieldCache auto-detects available RAM:
        #   - Memory mode (RAM sufficient): loads all files into numpy arrays.
        #     Weighted sum per candidate is then pure numpy — no file I/O.
        #   - Streaming mode (low RAM): uses slab LRU cache, falls back to
        #     the original chunked approach.
        slab_cache_gb = (self.config["auto_induced"] or {}).get("search", {}).get("slab_cache_gb", 2.0)
        low_memory_mode = (self.config["auto_induced"] or {}).get("search", {}).get("low_memory_mode", None)

        # Only pre-load E (SAR) or E+H (SAPD) — same field types we'll combine
        # FieldCache only supports one field_type at a time, so load each separately
        field_caches = {}
        for ft in field_types:
            self._log(f"  Pre-loading {ft}-fields from {len(h5_paths)} files...", level="progress", log_type="info")
            field_caches[ft] = FieldCache(
                h5_paths=[str(p) for p in h5_paths],
                field_type=ft,
                low_memory=low_memory_mode,
                slab_cache_gb=slab_cache_gb,
            )
            mode = "streaming" if field_caches[ft].streaming_mode else "memory"
            self._log(f"    {ft}-field cache ready ({mode} mode)", level="progress", log_type="info")

        # Create outer progress bar for candidates
        candidates_pbar = tqdm(
            enumerate(candidates, start=1),
            total=len(candidates),
            desc="Combining fields",
            unit="candidate",
            leave=False,
        )

        for i, candidate in candidates_pbar:
            candidates_pbar.set_description(f"Combining fields (candidate {i}/{len(candidates)})")

            if full_volume:
                # Full-volume combination — uses pre-loaded cache if in memory mode
                combined_path = self._combine_fields_for_candidate(
                    _CombineRequest(
                        h5_paths=h5_paths,
                        candidate=candidate,
                        output_dir=output_dir,
                        candidate_idx=i,
                        cube_size_mm=cube_size_mm,
                        combine_chunk_size=combine_chunk_size,
                        full_volume=True,
                        field_types=field_types,
                        field_caches=field_caches,
                    )
                )
                combined_h5_paths.append(combined_path)
            else:
                # Sliced combination with component progress bar
                n_components = len(field_types) * 3  # 3 spatial components per field type
                with tqdm(
                    total=n_components,
                    desc=f"  Candidate #{i}",
                    unit="component",
                    leave=False,
                ) as components_pbar:
                    combined_path = self._combine_fields_for_candidate(
                        _CombineRequest(
                            h5_paths=h5_paths,
                            candidate=candidate,
                            output_dir=output_dir,
                            candidate_idx=i,
                            cube_size_mm=cube_size_mm,
                            progress_bar=components_pbar,
                            field_types=field_types,
                        )
                    )
                    combined_h5_paths.append(combined_path)

        candidates_pbar.close()

        # Clean up field caches (closes file handles in streaming mode)
        for fc in field_caches.values():
            fc.close()

    # Step 3: Extract dosimetric metric for each candidate
    metric_key = "peak_sar_10g_W_kg" if extraction_metric == "sar" else "peak_sapd_w_m2"
    metric_unit = "W/kg" if extraction_metric == "sar" else "W/m2"
    subtask_name = "auto_induced_extract_sar" if extraction_metric == "sar" else "auto_induced_extract_sapd"

    with self.study.subtask(subtask_name):
        extraction_results = []
        for i, combined_h5 in enumerate(combined_h5_paths):
            if combined_h5 and combined_h5.exists():
                # Each candidate gets its own output subdirectory
                candidate_output_dir = Path(output_dir) / f"candidate_{i + 1:02d}"
                candidate_output_dir.mkdir(parents=True, exist_ok=True)

                if extraction_metric == "sar":
                    result = self._extract_sar(
                        combined_h5=combined_h5,
                        candidate_idx=i + 1,
                        candidate=candidates[i],
                        input_h5=input_h5,
                        candidate_output_dir=candidate_output_dir,
                        save_intermediate_files=save_intermediate_files,
                    )
                else:
                    result = self._extract_sapd(
                        combined_h5=combined_h5,
                        candidate_idx=i + 1,
                        candidate=candidates[i],
                        cube_size_mm=cube_size_mm,
                        input_h5=input_h5,
                        save_intermediate_files=save_intermediate_files,
                    )
                extraction_results.append(result)

                # Log per-candidate progress
                metric_val = result.get(metric_key)
                metric_str = f"{metric_val:.4e} {metric_unit}" if metric_val else "ERROR"
                self._log(
                    f"    Candidate #{i + 1}/{len(candidates)}: {metric_str}",
                    level="progress",
                    log_type="info",
                )
            else:
                extraction_results.append({"error": f"Combined H5 not found: {combined_h5}"})

    # Find worst case
    worst_case = self._find_worst_case(extraction_results, metric_key=metric_key)

    if worst_case and worst_case.get(metric_key):
        metric_label = "SAR 10g" if extraction_metric == "sar" else "SAPD"
        self._log(
            f"  - Worst-case {metric_label}: {worst_case[metric_key]:.4e} {metric_unit} (candidate #{worst_case.get('candidate_idx')})",
            level="progress",
            log_type="success",
        )

    # Export proxy-metric correlation data
    correlation_data = []
    metric_col = "sar_10g_W_kg" if extraction_metric == "sar" else "sapd_w_m2"
    for i, (candidate, ext_result) in enumerate(zip(candidates, extraction_results)):
        proxy_score = candidate.get("hotspot_score", candidate.get("metric_sum", 0.0))
        metric_value = ext_result.get(metric_key)
        if metric_value is not None:
            entry = {
                "candidate_idx": i + 1,
                "voxel_x": candidate["voxel_idx"][0],
                "voxel_y": candidate["voxel_idx"][1],
                "voxel_z": candidate["voxel_idx"][2],
                "proxy_score": proxy_score,
                metric_col: metric_value,
            }
            # Add distance to skin if available
            if "distance_to_skin_mm" in candidate:
                entry["distance_to_skin_mm"] = candidate["distance_to_skin_mm"]
            correlation_data.append(entry)
    if correlation_data:
        import csv

        corr_filename = f"proxy_{extraction_metric}_correlation.csv"
        corr_path = Path(output_dir) / corr_filename
        with open(corr_path, "w", newline="") as f:
            writer = csv.DictWriter(f, fieldnames=correlation_data[0].keys())
            writer.writeheader()
            writer.writerows(correlation_data)
        self.verbose_logger.info(f"  Exported proxy-{extraction_metric.upper()} correlation to {corr_path.name}")

    return {
        "phantom": self.phantom_name,
        "frequency_mhz": self.freq,
        "extraction_metric": extraction_metric,
        "candidates": candidates,
        "combined_h5_files": [str(p) for p in combined_h5_paths if p],
        "extraction_results": extraction_results,
        "worst_case": worst_case,
    }

Cleaner

goliat.extraction.cleaner.Cleaner

Cleaner(parent: ResultsExtractor)

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
def __init__(self, parent: "ResultsExtractor"):
    """Sets up the cleaner.

    Args:
        parent: Parent ResultsExtractor instance.
    """
    self.parent = parent

Methods:

cleanup_simulation_files

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
def cleanup_simulation_files(self):
    """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.
    """
    cleanup_types = self.parent.config.get_auto_cleanup_previous_results()
    if not cleanup_types:
        return

    if self.parent.study is None:
        self.parent._log("  - WARNING: Study object is not available. Skipping cleanup.", log_type="warning")
        return

    project_path = self.parent.study.project_manager.project_path
    if not project_path:
        self.parent._log("  - WARNING: Project path is not set. Skipping cleanup.", log_type="warning")
        return
    project_dir = os.path.dirname(project_path)
    project_filename = os.path.basename(project_path)
    results_dir = os.path.join(project_dir, project_filename + "_Results")

    # Map cleanup types to file patterns and directories
    file_patterns = {
        "output": (results_dir, "*_Output.h5", "output"),
        "input": (results_dir, "*_Input.h5", "input"),
        "smash": (project_dir, "*.smash", "project"),
    }

    total_deleted = self._delete_files(cleanup_types, file_patterns)

    if total_deleted > 0:
        self.parent._log(
            f"  - Cleaned up {total_deleted} file(s) to save disk space.",
            level="progress",
            log_type="info",
        )

Field Combiner

goliat.extraction.field_combiner.FieldCombineConfig dataclass

FieldCombineConfig(h5_paths: Sequence[Path], weights: ndarray, template_h5_path: Path, output_h5_path: Path, field_types: Sequence[str] = ('E', 'H'))

Configuration for field combination operations.

Field Reader

goliat.extraction.field_reader

Utilities for reading E/H fields from Sim4Life _Output.h5 files.

Supports memory-efficient reading for auto-induced exposure calculations: - Read fields at specific voxel indices (skin-only extraction) - Read fields in z-slab chunks (for full-field combination) - Handle Yee grid staggering (Nx-1, Ny-1, Nz-1 per component)

Functions:

find_overall_field_group

find_overall_field_group(f: File) -> Optional[str]

Find the FieldGroup containing 'Overall Field'.

Parameters:

Name Type Description Default
f File

Open h5py File object.

required

Returns:

Type Description
Optional[str]

Path to the FieldGroup (e.g., 'FieldGroups/0') or None if not found.

Source code in goliat/extraction/field_reader.py
def find_overall_field_group(f: h5py.File) -> Optional[str]:
    """Find the FieldGroup containing 'Overall Field'.

    Args:
        f: Open h5py File object.

    Returns:
        Path to the FieldGroup (e.g., 'FieldGroups/0') or None if not found.
    """
    if "FieldGroups" not in f:
        return None

    for fg_key in f["FieldGroups"].keys():
        obj_path = f"FieldGroups/{fg_key}/_Object"
        if obj_path in f:
            name_attr = f[obj_path].attrs.get("name", b"")
            if isinstance(name_attr, bytes):
                name_attr = name_attr.decode("utf-8")
            if name_attr == "Overall Field":
                return f"FieldGroups/{fg_key}"

    return None

get_field_path

get_field_path(fg_path: str, field_type: str = 'E') -> str

Get the HDF5 path for E or H field data.

Parameters:

Name Type Description Default
fg_path str

Path to the FieldGroup.

required
field_type str

'E' for electric field, 'H' for magnetic field.

'E'

Returns:

Type Description
str

Path to the field's Snapshots/0 group containing comp0/comp1/comp2.

Source code in goliat/extraction/field_reader.py
def get_field_path(fg_path: str, field_type: str = "E") -> str:
    """Get the HDF5 path for E or H field data.

    Args:
        fg_path: Path to the FieldGroup.
        field_type: 'E' for electric field, 'H' for magnetic field.

    Returns:
        Path to the field's Snapshots/0 group containing comp0/comp1/comp2.
    """
    field_name = f"EM {field_type}(x,y,z,f0)"
    return f"{fg_path}/AllFields/{field_name}/_Object/Snapshots/0"

read_field_component

read_field_component(f: File, field_path: str, component: int, z_slice: Optional[slice] = None) -> np.ndarray

Read a single field component as complex array.

Parameters:

Name Type Description Default
f File

Open h5py File object.

required
field_path str

Path to the Snapshots/0 group.

required
component int

0, 1, or 2 for x, y, z component.

required
z_slice Optional[slice]

Optional slice for z-axis (for chunked reading).

None

Returns:

Name Type Description
ndarray

Complex64 array of shape (Nx, Ny, Nz) or (Nx, Ny, Nz_chunk).

Note ndarray

Dimensions vary due to Yee staggering.

Source code in goliat/extraction/field_reader.py
def read_field_component(
    f: h5py.File,
    field_path: str,
    component: int,
    z_slice: Optional[slice] = None,
) -> np.ndarray:
    """Read a single field component as complex array.

    Args:
        f: Open h5py File object.
        field_path: Path to the Snapshots/0 group.
        component: 0, 1, or 2 for x, y, z component.
        z_slice: Optional slice for z-axis (for chunked reading).

    Returns:
        Complex64 array of shape (Nx, Ny, Nz) or (Nx, Ny, Nz_chunk).
        Note: Dimensions vary due to Yee staggering.
    """
    comp_name = f"comp{component}"
    dataset = f[f"{field_path}/{comp_name}"]

    if z_slice is not None:
        # Dataset shape is (Nx, Ny, Nz, 2) where last dim is [real, imag]
        data = dataset[:, :, z_slice, :]
    else:
        data = dataset[:]

    # Convert to complex
    return data[..., 0] + 1j * data[..., 1]

read_field_at_indices

read_field_at_indices(h5_path: Union[str, Path], indices: ndarray, field_type: str = 'E') -> np.ndarray

Read field values at specific voxel indices.

Optimized for reading fields only at skin voxel locations. Uses single-point h5py reads for small N, vectorized reads for large N.

Parameters:

Name Type Description Default
h5_path Union[str, Path]

Path to _Output.h5 file.

required
indices ndarray

Array of shape (N, 3) with [ix, iy, iz] indices.

required
field_type str

'E' or 'H'.

'E'

Returns:

Type Description
ndarray

Complex64 array of shape (N, 3) with [Ex, Ey, Ez] or [Hx, Hy, Hz].

Note

Due to Yee staggering, we use the voxel center approximation. For component i, data shape is (N-1) in dimension i. We clamp indices to valid range.

Source code in goliat/extraction/field_reader.py
def read_field_at_indices(
    h5_path: Union[str, Path],
    indices: np.ndarray,
    field_type: str = "E",
) -> np.ndarray:
    """Read field values at specific voxel indices.

    Optimized for reading fields only at skin voxel locations.
    Uses single-point h5py reads for small N, vectorized reads for large N.

    Args:
        h5_path: Path to _Output.h5 file.
        indices: Array of shape (N, 3) with [ix, iy, iz] indices.
        field_type: 'E' or 'H'.

    Returns:
        Complex64 array of shape (N, 3) with [Ex, Ey, Ez] or [Hx, Hy, Hz].

    Note:
        Due to Yee staggering, we use the voxel center approximation.
        For component i, data shape is (N-1) in dimension i.
        We clamp indices to valid range.
    """
    result = np.zeros((len(indices), 3), dtype=np.complex64)
    n_points = len(indices)

    with h5py.File(h5_path, "r") as f:
        fg_path = find_overall_field_group(f)
        if fg_path is None:
            raise ValueError(f"No 'Overall Field' found in {h5_path}")

        field_path = get_field_path(fg_path, field_type)

        for comp in range(3):
            dataset = f[f"{field_path}/comp{comp}"]
            shape = dataset.shape[:3]  # (Nx, Ny, Nz) for this component

            # Clamp indices to valid range for this component
            # Component 0 (Ex): shape is (Nx-1, Ny, Nz)
            # Component 1 (Ey): shape is (Nx, Ny-1, Nz)
            # Component 2 (Ez): shape is (Nx, Ny, Nz-1)
            ix = np.minimum(indices[:, 0], shape[0] - 1)
            iy = np.minimum(indices[:, 1], shape[1] - 1)
            iz = np.minimum(indices[:, 2], shape[2] - 1)

            if n_points <= 100:
                # For small N: read points directly from disk (avoids loading GB arrays)
                # h5py supports single-point indexing without loading full dataset
                for j in range(n_points):
                    data = dataset[int(ix[j]), int(iy[j]), int(iz[j]), :]
                    result[j, comp] = data[0] + 1j * data[1]
            else:
                # For large N: read full array (vectorized indexing is faster)
                full_data = dataset[:]  # Shape: (Nx, Ny, Nz, 2)
                data = full_data[ix, iy, iz, :]  # Shape: (N, 2)
                result[:, comp] = data[:, 0] + 1j * data[:, 1]

    return result

read_field_chunk

read_field_chunk(h5_path: Union[str, Path], z_start: int, z_end: int, field_type: str = 'E') -> Tuple[np.ndarray, np.ndarray, np.ndarray]

Read a z-slab chunk of the field.

For memory-efficient full-field combination.

Parameters:

Name Type Description Default
h5_path Union[str, Path]

Path to _Output.h5 file.

required
z_start int

Start z-index (inclusive).

required
z_end int

End z-index (exclusive).

required
field_type str

'E' or 'H'.

'E'

Returns:

Type Description
ndarray

Tuple of (comp0, comp1, comp2) complex64 arrays.

ndarray

Shapes vary due to Yee staggering:

ndarray
  • comp0: (Nx-1, Ny, z_end-z_start)
Tuple[ndarray, ndarray, ndarray]
  • comp1: (Nx, Ny-1, z_end-z_start)
Tuple[ndarray, ndarray, ndarray]
  • comp2: (Nx, Ny, z_end-z_start-1) - one less in z!
Source code in goliat/extraction/field_reader.py
def read_field_chunk(
    h5_path: Union[str, Path],
    z_start: int,
    z_end: int,
    field_type: str = "E",
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Read a z-slab chunk of the field.

    For memory-efficient full-field combination.

    Args:
        h5_path: Path to _Output.h5 file.
        z_start: Start z-index (inclusive).
        z_end: End z-index (exclusive).
        field_type: 'E' or 'H'.

    Returns:
        Tuple of (comp0, comp1, comp2) complex64 arrays.
        Shapes vary due to Yee staggering:
        - comp0: (Nx-1, Ny, z_end-z_start)
        - comp1: (Nx, Ny-1, z_end-z_start)
        - comp2: (Nx, Ny, z_end-z_start-1) - one less in z!
    """
    with h5py.File(h5_path, "r") as f:
        fg_path = find_overall_field_group(f)
        if fg_path is None:
            raise ValueError(f"No 'Overall Field' found in {h5_path}")

        field_path = get_field_path(fg_path, field_type)
        z_slice = slice(z_start, z_end)

        components = []
        for comp in range(3):
            # For comp2 (Ez), the z-dimension is Nz-1, so adjust slice
            if comp == 2:
                # Clamp to valid range
                dataset = f[f"{field_path}/comp{comp}"]
                max_z = dataset.shape[2]
                z_slice_adj = slice(z_start, min(z_end, max_z))
                data = read_field_component(f, field_path, comp, z_slice_adj)
            else:
                data = read_field_component(f, field_path, comp, z_slice)
            components.append(data)

    return tuple(components)

read_full_field

read_full_field(h5_path: Union[str, Path], field_type: str = 'E') -> Tuple[np.ndarray, np.ndarray, np.ndarray]

Read the entire E or H field.

Warning: Can be very memory intensive (~2GB for typical phantom).

Parameters:

Name Type Description Default
h5_path Union[str, Path]

Path to _Output.h5 file.

required
field_type str

'E' or 'H'.

'E'

Returns:

Type Description
Tuple[ndarray, ndarray, ndarray]

Tuple of (comp0, comp1, comp2) complex64 arrays.

Source code in goliat/extraction/field_reader.py
def read_full_field(
    h5_path: Union[str, Path],
    field_type: str = "E",
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Read the entire E or H field.

    Warning: Can be very memory intensive (~2GB for typical phantom).

    Args:
        h5_path: Path to _Output.h5 file.
        field_type: 'E' or 'H'.

    Returns:
        Tuple of (comp0, comp1, comp2) complex64 arrays.
    """
    with h5py.File(h5_path, "r") as f:
        fg_path = find_overall_field_group(f)
        if fg_path is None:
            raise ValueError(f"No 'Overall Field' found in {h5_path}")

        field_path = get_field_path(fg_path, field_type)

        components = []
        for comp in range(3):
            data = read_field_component(f, field_path, comp)
            components.append(data)

    return tuple(components)

get_field_shape

get_field_shape(h5_path: Union[str, Path]) -> Tuple[int, int, int]

Get the grid shape from an _Output.h5 file.

Returns the node count (Nx, Ny, Nz), not voxel count. Field components have shapes (Nx-1, Ny, Nz), etc. due to Yee grid.

Parameters:

Name Type Description Default
h5_path Union[str, Path]

Path to _Output.h5 file.

required

Returns:

Type Description
Tuple[int, int, int]

Tuple (Nx, Ny, Nz) - node counts.

Source code in goliat/extraction/field_reader.py
def get_field_shape(h5_path: Union[str, Path]) -> Tuple[int, int, int]:
    """Get the grid shape from an _Output.h5 file.

    Returns the node count (Nx, Ny, Nz), not voxel count.
    Field components have shapes (Nx-1, Ny, Nz), etc. due to Yee grid.

    Args:
        h5_path: Path to _Output.h5 file.

    Returns:
        Tuple (Nx, Ny, Nz) - node counts.
    """
    with h5py.File(h5_path, "r") as f:
        fg_path = find_overall_field_group(f)
        if fg_path is None:
            raise ValueError(f"No 'Overall Field' found in {h5_path}")

        field_path = get_field_path(fg_path, "E")
        # comp0 has shape (Nx-1, Ny, Nz, 2), so Nx = shape[0] + 1
        shape = f[f"{field_path}/comp0"].shape
        return (shape[0] + 1, shape[1], shape[2])

Field Cache

goliat.extraction.field_cache.FieldCache

FieldCache(h5_paths: Sequence[Union[str, Path]], field_type: str = 'E', low_memory: Optional[bool] = None, slab_cache_gb: float = DEFAULT_SLAB_CACHE_GB)

Cache for pre-loaded E-field data from multiple H5 files.

Supports three modes: - Memory mode (default): Load all fields into RAM for fast access. Best when you have enough RAM to hold all field data (~3 min). - Streaming mode (optimized): Uses slab-based LRU cache for efficient disk access. Much faster than naive streaming (~10-30 min vs 42 hours). - Legacy streaming mode: Single-point reads (extremely slow, deprecated).

Mode is automatically selected based on available RAM, or can be forced via the low_memory parameter.

Parameters:

Name Type Description Default
h5_paths Sequence[Union[str, Path]]

Paths to _Output.h5 files.

required
field_type str

'E' or 'H'.

'E'
low_memory Optional[bool]

If True, use streaming mode (no pre-loading). If False, always use memory mode (may cause paging on low-RAM). If None (default), auto-detect based on available RAM.

None
slab_cache_gb float

Size of slab LRU cache in GB (only for streaming mode).

DEFAULT_SLAB_CACHE_GB
Source code in goliat/extraction/field_cache.py
def __init__(
    self,
    h5_paths: Sequence[Union[str, Path]],
    field_type: str = "E",
    low_memory: Optional[bool] = None,
    slab_cache_gb: float = DEFAULT_SLAB_CACHE_GB,
):
    """Initialize the field cache.

    Args:
        h5_paths: Paths to _Output.h5 files.
        field_type: 'E' or 'H'.
        low_memory: If True, use streaming mode (no pre-loading).
            If False, always use memory mode (may cause paging on low-RAM).
            If None (default), auto-detect based on available RAM.
        slab_cache_gb: Size of slab LRU cache in GB (only for streaming mode).
    """
    self.h5_paths = [str(p) for p in h5_paths]
    self.field_type = field_type
    self.fields: Dict[str, List[np.ndarray]] = {}
    self.shapes: Dict[str, Tuple[int, int, int]] = {}
    self.slab_cache_gb = slab_cache_gb

    self._slab_cache: Optional[SlabLRUCache] = None
    self._open_files: Dict[str, h5py.File] = {}
    self._field_paths: Dict[str, str] = {}

    logger = logging.getLogger("progress")

    available_gb = _get_available_memory_gb()
    estimated_gb = _estimate_cache_size_gb(h5_paths)
    has_enough_ram = available_gb < 0 or estimated_gb <= available_gb - self.MIN_HEADROOM_GB

    if low_memory is None:
        self.streaming_mode = not has_enough_ram
    else:
        self.streaming_mode = low_memory

    if available_gb > 0:
        logger.info(f"  Memory check: {estimated_gb:.1f} GB needed, {available_gb:.1f} GB available")

    if self.streaming_mode:
        logger.info(
            f"  Using OPTIMIZED STREAMING mode with {slab_cache_gb:.1f} GB slab cache\n"
            f"  This is ~100x faster than naive streaming. "
            f"For fastest processing, use a machine with >{estimated_gb + self.MIN_HEADROOM_GB:.0f} GB RAM."
        )
        self._init_streaming_mode()
    else:
        if not has_enough_ram:
            warning_msg = (
                f"\n{'=' * 70}\n"
                f"  WARNING: Insufficient RAM for field cache!\n"
                f"  - Cache size: {estimated_gb:.1f} GB\n"
                f"  - Available RAM: {available_gb:.1f} GB\n"
                f"  - Recommended: {estimated_gb + self.MIN_HEADROOM_GB:.1f} GB\n"
                f"\n"
                f"  This may cause severe slowdowns due to disk paging.\n"
                f"  Consider:\n"
                f"    1. Closing other applications to free RAM\n"
                f"    2. Running on a machine with more RAM\n"
                f"    3. Reducing n_samples in config\n"
                f"    4. Setting low_memory_mode=true in config\n"
                f"{'=' * 70}\n"
            )
            logger.warning(warning_msg)
            warnings.warn(
                f"Field cache ({estimated_gb:.1f} GB) exceeds available RAM ({available_gb:.1f} GB). Expect severe slowdowns.",
                ResourceWarning,
                stacklevel=2,
            )

        logger.info(f"  Pre-loading {field_type}-fields from {len(h5_paths)} files...")
        t0 = time.perf_counter()

        for h5_path in tqdm(self.h5_paths, desc=f"Loading {field_type}-fields"):
            self._load_field(h5_path)

        total_mb = sum(sum(c.nbytes for c in comps) for comps in self.fields.values()) / 1e6
        logger.info(f"  [timing] Field cache loaded: {time.perf_counter() - t0:.2f}s, {total_mb:.0f} MB")

Methods:

read_at_indices

read_at_indices(h5_path: str, indices: ndarray) -> np.ndarray

Read field values at specific indices.

In memory mode, reads from pre-loaded cached data. In streaming mode, uses slab-based caching for efficiency.

Parameters:

Name Type Description Default
h5_path str

Which file to read from.

required
indices ndarray

(N, 3) array of [ix, iy, iz] indices.

required

Returns:

Type Description
ndarray

(N, 3) complex array of field values.

Source code in goliat/extraction/field_cache.py
def read_at_indices(self, h5_path: str, indices: np.ndarray) -> np.ndarray:
    """Read field values at specific indices.

    In memory mode, reads from pre-loaded cached data.
    In streaming mode, uses slab-based caching for efficiency.

    Args:
        h5_path: Which file to read from.
        indices: (N, 3) array of [ix, iy, iz] indices.

    Returns:
        (N, 3) complex array of field values.
    """
    if self.streaming_mode:
        return self._read_at_indices_streaming_optimized(h5_path, indices)
    else:
        return self._read_at_indices_memory(h5_path, indices)

get_cache_stats

get_cache_stats() -> Optional[Dict[str, float]]

Get slab cache statistics (streaming mode only).

Source code in goliat/extraction/field_cache.py
def get_cache_stats(self) -> Optional[Dict[str, float]]:
    """Get slab cache statistics (streaming mode only)."""
    if self._slab_cache is not None:
        return self._slab_cache.get_stats()
    return None

close

close()

Close open file handles (streaming mode cleanup).

Source code in goliat/extraction/field_cache.py
def close(self):
    """Close open file handles (streaming mode cleanup)."""
    for f in self._open_files.values():
        try:
            f.close()
        except Exception:
            pass
    self._open_files.clear()

Focus Optimizer

Json Encoder

goliat.extraction.json_encoder.NumpyArrayEncoder

Bases: JSONEncoder

JSON encoder that handles NumPy types.

Converts numpy arrays and numeric types to Python built-ins so they can be serialized to JSON.

Methods:

default

default(o: Any) -> Any

Converts NumPy types to JSON-serializable Python types.

Source code in goliat/extraction/json_encoder.py
def default(self, o: Any) -> Any:
    """Converts NumPy types to JSON-serializable Python types."""
    if isinstance(o, np.ndarray):
        return o.tolist()
    if isinstance(o, np.integer):
        return int(o)
    if isinstance(o, np.floating):
        return float(o)
    return super().default(o)

Power Extractor

goliat.extraction.power_extractor.PowerExtractor

PowerExtractor(parent: ResultsExtractor, results_data: dict)

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
def __init__(self, parent: "ResultsExtractor", results_data: dict):
    """Sets up the power extractor.

    Args:
        parent: Parent ResultsExtractor instance.
        results_data: Dict to store extracted power data.
    """
    self.parent = parent
    self.config = parent.config
    self.simulation = parent.simulation
    self.study_type = parent.study_type
    self.placement_name = parent.placement_name
    self.frequency_mhz = parent.frequency_mhz
    self.verbose_logger = parent.verbose_logger
    self.progress_logger = parent.progress_logger
    self.gui = parent.gui
    self.results_data = results_data

    import s4l_v1.document

    self.document = s4l_v1.document

Methods:

extract_input_power

extract_input_power(simulation_extractor: Extractor)

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
def extract_input_power(self, simulation_extractor: "analysis.Extractor"):  # type: ignore
    """Extracts input power, delegating to study-type specific methods.

    Args:
        simulation_extractor: Results extractor from the simulation.
    """
    self._log("    - Extract input power...", level="progress", log_type="progress")

    try:
        elapsed = 0.0
        if self.parent.study:
            with self.parent.study.profiler.subtask("extract_input_power"):  # type: ignore
                if self.study_type == "far_field":
                    self._extract_far_field_power(simulation_extractor)
                else:
                    self._extract_near_field_power(simulation_extractor)

            elapsed = self.parent.study.profiler.subtask_times["extract_input_power"][-1]

        self._log(f"      - Subtask 'extract_input_power' done in {elapsed:.2f}s", log_type="verbose")
        self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")
    except Exception as e:
        self._log(
            f"  - ERROR: An exception occurred during input power extraction: {e}",
            level="progress",
            log_type="error",
        )
        self.verbose_logger.error(traceback.format_exc())

extract_power_balance

extract_power_balance(simulation_extractor: Extractor)

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
def extract_power_balance(self, simulation_extractor: "analysis.Extractor"):  # type: ignore
    """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.

    Args:
        simulation_extractor: Results extractor from the simulation.
    """
    self._log("    - Extract power balance...", level="progress", log_type="progress")
    try:
        elapsed = 0.0
        if self.parent.study:
            with self.parent.study.profiler.subtask("extract_power_balance"):  # type: ignore
                em_sensor_extractor = simulation_extractor["Overall Field"]
                power_balance_extractor = em_sensor_extractor.Outputs["Power Balance"]
                power_balance_extractor.Update()

                power_balance_data = {
                    key: power_balance_extractor.Data.DataSimpleDataCollection.FieldValue(key, 0)
                    for key in power_balance_extractor.Data.DataSimpleDataCollection.Keys()
                    if key != "Balance"
                }

                if self.parent.study_type == "far_field" and "input_power_W" in self.results_data:
                    power_balance_data["Pin"] = self.results_data["input_power_W"]
                    self._log(
                        f"    - Overwriting Pin with theoretical value: {float(power_balance_data['Pin']):.4e} W",
                        log_type="info",
                    )

                pin = power_balance_data.get("Pin", 0.0)
                p_out = power_balance_data.get("DielLoss", 0.0) + power_balance_data.get("RadPower", 0.0)
                balance = 100 * (p_out / pin) if pin > 1e-9 else float("nan")

                power_balance_data["Balance"] = balance
                self._log(f"    - Final Balance: {balance:.2f}%", log_type="highlight")
                self.results_data["power_balance"] = power_balance_data

            elapsed = self.parent.study.profiler.subtask_times["extract_power_balance"][-1]
        self._log(f"      - Subtask 'extract_power_balance' done in {elapsed:.2f}s", log_type="verbose")
        self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    except Exception as e:
        self._log(f"  - WARNING: Could not extract power balance: {e}", log_type="warning")
        self.verbose_logger.error(traceback.format_exc())

Reporter

goliat.extraction.reporter.Reporter

Reporter(parent: ResultsExtractor)

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
def __init__(self, parent: "ResultsExtractor"):
    """Sets up the reporter.

    Args:
        parent: Parent ResultsExtractor instance.
    """
    self.parent = parent

Methods:

save_reports

save_reports(df: DataFrame, tissue_groups: dict, group_sar_stats: dict, results_data: dict)

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
def save_reports(
    self,
    df: pd.DataFrame,
    tissue_groups: dict,
    group_sar_stats: dict,
    results_data: dict,
):
    """Saves Pickle and HTML reports to the results directory.

    Args:
        df: DataFrame with detailed SAR statistics per tissue.
        tissue_groups: Dict mapping group names to tissue lists.
        group_sar_stats: Dict with aggregated SAR stats per group.
        results_data: Dict with summary results and metadata.
    """
    results_dir = self._get_results_dir()
    os.makedirs(results_dir, exist_ok=True)

    self._save_pickle_report(results_dir, df, tissue_groups, group_sar_stats, results_data)
    self._save_html_report(results_dir, df, tissue_groups, group_sar_stats, results_data)

Resonance Extractor

goliat.extraction.resonance_extractor.ResonanceExtractor

ResonanceExtractor(parent: ResultsExtractor, results_data: dict)

Bases: LoggingMixin

Extracts antenna resonance frequency and detuning from Gaussian pulse results.

Analyzes frequency-dependent accepted power to identify resonance peak and calculates detuning relative to nominal frequency.

Parameters:

Name Type Description Default
parent ResultsExtractor

Parent ResultsExtractor instance.

required
results_data dict

Dict to store extracted resonance data.

required
Source code in goliat/extraction/resonance_extractor.py
def __init__(self, parent: "ResultsExtractor", results_data: dict):
    """Sets up the resonance extractor.

    Args:
        parent: Parent ResultsExtractor instance.
        results_data: Dict to store extracted resonance data.
    """
    self.parent = parent
    self.config = parent.config
    self.frequency_mhz = parent.frequency_mhz
    self.verbose_logger = parent.verbose_logger
    self.progress_logger = parent.progress_logger
    self.results_data = results_data
    self.gui = parent.gui

    import s4l_v1.document

    self.document = s4l_v1.document

Methods:

extract_resonance_frequency

extract_resonance_frequency(simulation_extractor: Extractor)

Extract antenna resonant frequency from Gaussian pulse results.

Analyzes frequency-dependent accepted power to identify resonance peak. Calculates detuning relative to nominal frequency.

Parameters:

Name Type Description Default
simulation_extractor Extractor

Results extractor from the simulation.

required

Returns:

Name Type Description
dict

Contains resonant_freq_mhz, detuning_mhz, max_power_w, freq_resolution_mhz

Source code in goliat/extraction/resonance_extractor.py
def extract_resonance_frequency(self, simulation_extractor: "analysis.Extractor"):  # type: ignore
    """Extract antenna resonant frequency from Gaussian pulse results.

    Analyzes frequency-dependent accepted power to identify resonance peak.
    Calculates detuning relative to nominal frequency.

    Args:
        simulation_extractor: Results extractor from the simulation.

    Returns:
        dict: Contains resonant_freq_mhz, detuning_mhz, max_power_w, freq_resolution_mhz
    """
    try:
        # Extract full frequency spectrum
        input_power_extractor = simulation_extractor["Input Power"]
        self.document.AllAlgorithms.Add(input_power_extractor)
        input_power_extractor.Update()

        input_power_output = input_power_extractor.Outputs["EM Input Power(f)"]
        input_power_output.Update()

        # Get continuous frequency data (automatically from FFT)
        freq_axis_hz = input_power_output.Data.Axis  # Full freq array
        power_data_w = input_power_output.Data.GetComponent(0)  # Power at each freq

        # Convert to MHz
        freq_axis_mhz = freq_axis_hz / 1e6

        # Find resonant frequency (maximum accepted power)
        max_idx = np.argmax(power_data_w)
        resonant_freq_mhz = freq_axis_mhz[max_idx]
        max_power_w = power_data_w[max_idx]

        # Calculate detuning
        freq_mhz = self.frequency_mhz
        nominal_freq_mhz = float(freq_mhz if isinstance(freq_mhz, (int, float)) else np.mean(freq_mhz))
        detuning_mhz = float(resonant_freq_mhz - nominal_freq_mhz)

        # Calculate frequency resolution
        if len(freq_axis_hz) > 1:
            freq_resolution_mhz = (freq_axis_hz[1] - freq_axis_hz[0]) / 1e6
        else:
            freq_resolution_mhz = 0.0

        # Log results
        self._log(f"\n{'=' * 80}", log_type="highlight")
        self._log("  ANTENNA RESONANCE ANALYSIS", log_type="highlight")
        self._log(f"{'=' * 80}", log_type="highlight")
        self._log(f"  Nominal frequency: {nominal_freq_mhz} MHz", log_type="info")
        self._log(f"  Detected resonance: {resonant_freq_mhz:.2f} MHz", log_type="highlight")
        self._log(
            f"  Detuning: {detuning_mhz:+.2f} MHz ({detuning_mhz / nominal_freq_mhz * 100:+.1f}%)",
            log_type="highlight" if abs(detuning_mhz) > 10 else "info",
        )
        self._log(f"  Max power at resonance: {max_power_w * 1000:.2f} mW", log_type="info")
        self._log(f"  Frequency resolution: {freq_resolution_mhz:.2f} MHz", log_type="info")
        self._log(f"  Number of frequency points: {len(freq_axis_hz)}", log_type="info")
        self._log(f"{'=' * 80}\n", log_type="highlight")

        # Warning for severe detuning
        if abs(detuning_mhz) > 50:
            self._log("\n" + "!" * 80, log_type="warning")
            self._log("  WARNING: SIGNIFICANT ANTENNA DETUNING DETECTED!", log_type="warning")
            self._log(
                f"  The antenna has shifted {detuning_mhz:+.1f} MHz from nominal frequency.",
                log_type="warning",
            )
            self._log("  Consider:", log_type="warning")
            self._log(
                f"    1. Re-running simulation at detected resonance ({resonant_freq_mhz:.0f} MHz)",
                log_type="warning",
            )
            self._log("    2. Verifying antenna design for this placement scenario", log_type="warning")
            self._log(
                "    3. Checking if SAR pattern is affected by off-resonance operation",
                log_type="warning",
            )
            self._log("!" * 80 + "\n", log_type="warning")

        # Store results
        resonance_data = {
            "resonant_freq_mhz": float(resonant_freq_mhz),
            "nominal_freq_mhz": float(nominal_freq_mhz),
            "detuning_mhz": float(detuning_mhz),
            "detuning_percent": float(detuning_mhz / nominal_freq_mhz * 100),
            "max_power_w": float(max_power_w),
            "freq_resolution_mhz": float(freq_resolution_mhz),
            "num_freq_points": int(len(freq_axis_hz)),
            "frequency_axis_mhz": freq_axis_mhz.tolist(),  # For plotting
            "power_data_w": power_data_w.tolist(),  # For plotting
        }

        # Clean up
        self.document.AllAlgorithms.Remove(input_power_extractor)

        return resonance_data

    except Exception as e:
        self._log(
            f"  - ERROR: An exception occurred during resonance extraction: {e}",
            log_type="error",
        )
        self.verbose_logger.error(traceback.format_exc())
        return None

Sapd Extractor

goliat.extraction.sapd_extractor.SapdExtractionContext dataclass

SapdExtractionContext(center_m: Optional[List[float]] = None, sliced_h5_path: Optional[str] = None, sliced_extractor: Optional[Any] = None, active_extractor: Optional[Any] = None, em_sensor_extractor: Optional[Any] = None, model_to_grid_filter: Optional[Any] = None, sapd_evaluator: Optional[Any] = None, sapd_field_evaluator: Optional[Any] = None)

Holds state during SAPD extraction to reduce method parameters.

Sar Extractor

goliat.extraction.sar_extractor.SarExtractor

SarExtractor(parent: ResultsExtractor, results_data: dict)

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
def __init__(self, parent: "ResultsExtractor", results_data: dict):
    """Sets up the SAR extractor.

    Args:
        parent: Parent ResultsExtractor instance.
        results_data: Dict to store extracted SAR data.
    """
    self.parent = parent
    self.config = parent.config
    self.simulation = parent.simulation
    self.phantom_name = parent.phantom_name
    self.placement_name = parent.placement_name
    self.verbose_logger = parent.verbose_logger
    self.progress_logger = parent.progress_logger
    self.gui = parent.gui
    self.results_data = results_data

    import s4l_v1.analysis
    import s4l_v1.document
    import s4l_v1.units as units

    self.analysis = s4l_v1.analysis
    self.document = s4l_v1.document
    self.units = units

    self.tissue_grouper = TissueGrouper(self.config, self.phantom_name, self)

Methods:

extract_sar_statistics

extract_sar_statistics(simulation_extractor: Extractor)

Extracts 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
def extract_sar_statistics(self, simulation_extractor: "analysis.Extractor"):  # type: ignore
    """Extracts 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.

    Args:
        simulation_extractor: Results extractor from the simulation object.
    """
    self._log("    - Extract SAR statistics...", level="progress", log_type="progress")
    try:
        elapsed = 0.0
        if self.parent.study:
            with self.parent.study.profiler.subtask("extract_sar_statistics"):  # type: ignore
                em_sensor_extractor = self._setup_em_sensor_extractor(simulation_extractor)
                try:
                    results = self._evaluate_sar_statistics(em_sensor_extractor)

                    if not results:
                        return

                    df = self._create_sar_dataframe(results)
                    tissue_groups = self.tissue_grouper.group_tissues(df["Tissue"].tolist())
                    group_sar_stats = self._calculate_group_sar(df, tissue_groups)

                    self._store_group_sar_results(group_sar_stats)
                    self._store_all_regions_sar(df)
                    self.extract_peak_sar_details(em_sensor_extractor)
                    self._store_temporary_data(df, tissue_groups, group_sar_stats)
                finally:
                    try:
                        self.document.AllAlgorithms.Remove(em_sensor_extractor)
                    except Exception:
                        pass

            elapsed = self.parent.study.profiler.subtask_times["extract_sar_statistics"][-1]
        self._log(f"      - Subtask 'extract_sar_statistics' done in {elapsed:.2f}s", log_type="verbose")
        self._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    except Exception as e:
        self._log(
            f"  - ERROR: An unexpected error during all-tissue SAR statistics extraction: {e}",
            level="progress",
            log_type="error",
        )
        self.verbose_logger.error(traceback.format_exc())

extract_peak_sar_details

extract_peak_sar_details(em_sensor_extractor: Extractor)

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
def extract_peak_sar_details(self, em_sensor_extractor: "analysis.Extractor"):  # type: ignore
    """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.

    Args:
        em_sensor_extractor: The 'Overall Field' results extractor containing
                           the SAR field data.
    """
    self._log("  - Extracting peak SAR details...", log_type="progress")
    average_sar_field_evaluator = None
    try:
        inputs = [em_sensor_extractor.Outputs["SAR(x,y,z,f0)"]]
        average_sar_field_evaluator = self.analysis.em_evaluators.AverageSarFieldEvaluator(inputs=inputs)
        average_sar_field_evaluator.TargetMass = 10.0, self.units.Unit("g")
        average_sar_field_evaluator.UpdateAttributes()
        self.document.AllAlgorithms.Add(average_sar_field_evaluator)
        average_sar_field_evaluator.Update()

        peak_sar_output = average_sar_field_evaluator.Outputs["Peak Spatial SAR (psSAR) Results"]
        peak_sar_output.Update()  # type: ignore

        data_collection = peak_sar_output.Data.DataSimpleDataCollection  # type: ignore

        # data_collection may be a Sim4Life wrapper around a null JSON object.
        # The Python truthiness check passes even for null-wrapped objects, so
        # we must guard the Keys() call with its own try-except.
        if data_collection is not None:
            peak_sar_details = {}
            try:
                keys = list(data_collection.Keys())
            except Exception:
                # Sim4Life returns a null JSON wrapper when SAR is zero
                # everywhere (e.g. combined field has no energy).
                keys = []
                self._log(
                    "  - WARNING: Peak SAR data collection is null (SAR may be zero everywhere).",
                    log_type="warning",
                )

            for key in keys:
                try:
                    value = data_collection.FieldValue(key, 0)
                    if value is not None:
                        peak_sar_details[key] = value
                except Exception:
                    pass  # Skip keys that fail to extract

            if peak_sar_details:
                self.results_data["peak_sar_details"] = peak_sar_details
            else:
                self._log(
                    "  - WARNING: Peak SAR data collection was empty after filtering None values.",
                    log_type="warning",
                )
        else:
            self._log(
                "  - WARNING: Could not extract peak SAR details (data collection is None).",
                log_type="warning",
            )

    except Exception as e:
        self._log(
            f"  - ERROR: An exception occurred during peak SAR detail extraction: {e}",
            log_type="error",
        )
        self.verbose_logger.error(traceback.format_exc())
    finally:
        # Always remove the evaluator to avoid accumulating stale algorithms
        # in AllAlgorithms across candidates (causes cascading state corruption).
        if average_sar_field_evaluator is not None:
            try:
                self.document.AllAlgorithms.Remove(average_sar_field_evaluator)
            except Exception:
                pass

Sensor Extractor

goliat.extraction.sensor_extractor.SensorExtractor

SensorExtractor(parent: ResultsExtractor, results_data: dict)

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
def __init__(self, parent: "ResultsExtractor", results_data: dict):
    """Sets up the sensor extractor.

    Args:
        parent: Parent ResultsExtractor instance.
        results_data: Dict to store extracted data.
    """
    self.parent = parent
    self.results_data = results_data
    self.verbose_logger = parent.verbose_logger
    self.progress_logger = parent.progress_logger

Methods:

extract_point_sensor_data

extract_point_sensor_data(simulation_extractor: Extractor)

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
def extract_point_sensor_data(self, simulation_extractor: "analysis.Extractor"):  # type: ignore
    """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.

    Args:
        simulation_extractor: Results extractor from the simulation object.
    """
    self.parent._log("    - Extract point sensors...", level="progress", log_type="progress")

    try:
        elapsed = 0.0
        if self.parent.study:
            with self.parent.study.profiler.subtask("extract_point_sensor_data"):  # type: ignore
                num_sensors = self.parent.config["simulation_parameters.number_of_point_sensors"] or 0
                if num_sensors == 0:
                    return

                plt.ioff()
                plt.rcParams.update({"text.usetex": False})
                fig, ax = plt.subplots()
                ax.grid(True, which="major", axis="y", linestyle="--")

                point_source_order = self.parent.config["simulation_parameters.point_source_order"] or []
                point_sensor_results = {}

                for i in range(num_sensors):  # type: ignore
                    if i >= len(point_source_order):  # type: ignore
                        self.parent._log(
                            f"    - WARNING: Not enough entries in 'point_source_order' for sensor {i + 1}. Skipping.",
                            log_type="warning",
                        )
                        continue

                    corner_name = point_source_order[i]  # type: ignore
                    full_sensor_name = f"Point Sensor Entity {i + 1} ({corner_name})"

                    try:
                        em_sensor_extractor = simulation_extractor[full_sensor_name]
                        if not em_sensor_extractor:
                            self.parent._log(
                                f"    - WARNING: Could not find sensor extractor for '{full_sensor_name}'",
                                log_type="warning",
                            )
                            continue
                    except Exception as e:
                        self.parent._log(
                            f"    - WARNING: Could not retrieve sensor '{full_sensor_name}'. Error: {e}",
                            log_type="warning",
                        )
                        continue

                    self.parent.document.AllAlgorithms.Add(em_sensor_extractor)

                    if "EM E(t)" not in em_sensor_extractor.Outputs:
                        self.parent._log(
                            f"    - WARNING: 'EM E(t)' output not found for sensor '{full_sensor_name}'",
                            log_type="warning",
                        )
                        self.parent.document.AllAlgorithms.Remove(em_sensor_extractor)
                        continue

                    em_output = em_sensor_extractor.Outputs["EM E(t)"]
                    em_output.Update()

                    time_axis = em_output.Data.Axis
                    ex, ey, ez = (em_output.Data.GetComponent(i) for i in range(3))
                    label = corner_name.replace("_", " ").title()

                    if time_axis is not None and time_axis.size > 0:
                        e_mag = np.sqrt(ex**2 + ey**2 + ez**2)
                        ax.plot(time_axis, e_mag, label=label)
                        point_sensor_results[label] = {
                            "time_s": time_axis.tolist(),
                            "Ex_V_m": ex.tolist(),
                            "Ey_V_m": ey.tolist(),
                            "Ez_V_m": ez.tolist(),
                            "E_mag_V_m": e_mag.tolist(),
                        }
                    else:
                        self.parent._log(
                            f"    - WARNING: No data found for sensor '{full_sensor_name}'",
                            log_type="warning",
                        )

                    self.parent.document.AllAlgorithms.Remove(em_sensor_extractor)

                if point_sensor_results:
                    self.results_data["point_sensor_data"] = point_sensor_results

                self._save_plot(fig, ax)

            elapsed = self.parent.study.profiler.subtask_times["extract_point_sensor_data"][-1]
        self.parent._log(f"      - Subtask 'extract_point_sensor_data' done in {elapsed:.2f}s", log_type="verbose")
        self.parent._log(f"      - Done in {elapsed:.2f}s", level="progress", log_type="success")

    except Exception as e:
        self.parent._log(
            f"  - ERROR: An exception occurred during point sensor data extraction: {e}",
            level="progress",
            log_type="error",
        )
        self.verbose_logger.error(traceback.format_exc())

Tissue Grouping

goliat.extraction.tissue_grouping.TissueGrouper

TissueGrouper(config: Config, phantom_name: str, logger: LoggingMixin)

Handles grouping of tissues into logical categories for SAR analysis.

Parameters:

Name Type Description Default
config Config

Configuration object for accessing material mappings.

required
phantom_name str

Name of the phantom model.

required
logger LoggingMixin

Logger instance for logging messages.

required
Source code in goliat/extraction/tissue_grouping.py
def __init__(self, config: "Config", phantom_name: str, logger: "LoggingMixin"):
    """Load material mapping for the given phantom.

    Args:
        config: Configuration object for accessing material mappings.
        phantom_name: Name of the phantom model.
        logger: Logger instance for logging messages.
    """
    self.config = config
    self.phantom_name = phantom_name
    self.logger = logger

Methods:

group_tissues

group_tissues(available_tissues: list[str]) -> dict[str, list[str]]

Groups tissues according to material_name_mapping.json.

Simple matching: tissue_name -> material_name -> entity_name -> check group.

Parameters:

Name Type Description Default
available_tissues list[str]

List of tissue names found in the simulation results.

required

Returns:

Type Description
dict[str, list[str]]

Dict mapping group names to lists of tissue names that belong to that group.

dict[str, list[str]]

Empty groups are still included but with empty lists.

Source code in goliat/extraction/tissue_grouping.py
def group_tissues(self, available_tissues: list[str]) -> dict[str, list[str]]:
    """Groups tissues according to material_name_mapping.json.

    Simple matching: tissue_name -> material_name -> entity_name -> check group.

    Args:
        available_tissues: List of tissue names found in the simulation results.

    Returns:
        Dict mapping group names to lists of tissue names that belong to that group.
        Empty groups are still included but with empty lists.
    """
    material_mapping = self.config.get_material_mapping(self.phantom_name)

    if "_tissue_groups" not in material_mapping:
        return {}

    return self._group_from_config(material_mapping, available_tissues)

Analysis

Classes for analyzing and visualizing simulation results.

Analyze Simulation Stats

goliat.analysis.analyze_simulation_stats

Analyze Near-Field simulation logs and create professional, client-ready visualizations.

IMPROVEMENTS: - Strict filtering for Near Field simulations only. - Emojis removed to prevent font rendering errors. - "High-End Engineering" aesthetic (professional dark theme). - Dynamic layout scaling for lists with many items. - Robust text placement to avoid overlap.

Functions:

find_all_verbose_logs

find_all_verbose_logs(results_dir: str | Path) -> list[Path]

Find all verbose.log files in the results directory.

Source code in goliat/analysis/analyze_simulation_stats.py
def find_all_verbose_logs(results_dir: str | Path) -> list[Path]:
    """Find all verbose.log files in the results directory."""
    results_dir = Path(results_dir)
    return list(results_dir.rglob("verbose.log"))

parse_all_logs

parse_all_logs(log_files: list[Path], verbose: bool = True) -> list[dict]

Parse all verbose.log files and return list of metrics.

Source code in goliat/analysis/analyze_simulation_stats.py
def parse_all_logs(log_files: list[Path], verbose: bool = True) -> list[dict]:
    """Parse all verbose.log files and return list of metrics."""
    all_metrics = []

    for i, log_file in enumerate(log_files):
        # STRICT FILTER: Only Near Field
        if "near_field" not in log_file.parts:
            continue

        if verbose and i % 50 == 0:
            logging.getLogger("progress").info(f"  Parsing: {i + 1}/{len(log_files)}...", extra={"log_type": "verbose"})

        try:
            metrics = parse_verbose_log(log_file)

            # Robust category extraction
            parts = log_file.parts
            category = {"study_type": "near_field", "phantom": "unknown", "frequency": "unknown", "placement": "unknown"}

            try:
                # Assuming structure: .../near_field/phantom/freq/placement/verbose.log
                nf_index = parts.index("near_field")
                if nf_index + 3 < len(parts):
                    category["phantom"] = parts[nf_index + 1]
                    category["frequency"] = parts[nf_index + 2]
                    category["placement"] = parts[nf_index + 3]
            except ValueError:
                pass

            metrics["category"] = category
            all_metrics.append(metrics)

        except Exception:
            if verbose:
                # print(f"  Error parsing {log_file}: {e}")
                pass

    if verbose:
        logging.getLogger("progress").info(f"  Parsed {len(all_metrics)} Near-Field log files.", extra={"log_type": "progress"})

    return all_metrics

compute_aggregate_stats

compute_aggregate_stats(all_metrics: list[dict]) -> dict

Compute aggregate statistics across all simulations.

Source code in goliat/analysis/analyze_simulation_stats.py
def compute_aggregate_stats(all_metrics: list[dict]) -> dict:
    """Compute aggregate statistics across all simulations."""
    stats = {
        "total_simulations": len(all_metrics),
        "total_cells": 0,
        "total_cells_with_pml": 0,
        "total_edges": 0,
        "total_iterations": 0,
        "total_cell_iterations": 0,
        "total_runtime_s": 0,
        "total_materials": [],  # Changed to list for JSON serialization
        "total_tissues": [],  # Changed to list for JSON serialization
        "by_phantom": defaultdict(lambda: {"count": 0, "cells": 0, "iterations": 0, "cell_iterations": 0, "runtime_s": 0}),
        "by_frequency": defaultdict(lambda: {"count": 0, "cells": 0, "iterations": 0, "cell_iterations": 0, "runtime_s": 0}),
        "by_placement": defaultdict(lambda: {"count": 0, "cells": 0, "iterations": 0, "cell_iterations": 0, "runtime_s": 0}),
        "iterations_list": [],
        "cells_list": [],
        "runtime_list": [],
        "cell_iterations_list": [],
        "peak_speed_list": [],  # Peak MCells/s per simulation
        "avg_speed_list": [],  # Avg MCells/s per simulation
    }

    unique_tissues = set()

    for m in all_metrics:
        # Extract values
        cells = m.get("grid", {}).get("total_cells_with_pml", 0)
        iterations = m.get("solver", {}).get("iterations", 0)
        runtime = m.get("timing", {}).get("total_wall_clock_s", 0)
        edges = m.get("edges", {}).get("total_edges", 0)
        cell_iterations = cells * iterations if cells and iterations else 0

        # Aggregate totals
        stats["total_cells_with_pml"] += cells
        stats["total_cells"] += m.get("grid", {}).get("total_cells", 0)
        stats["total_edges"] += edges
        stats["total_iterations"] += iterations
        stats["total_cell_iterations"] += cell_iterations
        stats["total_runtime_s"] += runtime

        # Track materials/tissues
        for tissue in m.get("materials", {}).get("tissues", []):
            unique_tissues.add(tissue.get("name", ""))

        # Lists for distributions
        stats["iterations_list"].append(iterations)
        stats["cells_list"].append(cells)
        stats["runtime_list"].append(runtime)
        stats["cell_iterations_list"].append(cell_iterations)

        # Speed metrics from summary
        summary = m.get("summary", {})
        if summary.get("peak_mcells_per_s"):
            stats["peak_speed_list"].append(summary["peak_mcells_per_s"])
        if summary.get("avg_mcells_per_s"):
            stats["avg_speed_list"].append(summary["avg_mcells_per_s"])

        # By category
        cat = m.get("category", {})

        if cat.get("phantom"):
            p = stats["by_phantom"][cat["phantom"]]
            p["count"] += 1
            p["cells"] += cells
            p["iterations"] += iterations
            p["cell_iterations"] += cell_iterations
            p["runtime_s"] += runtime

        if cat.get("frequency"):
            freq = cat["frequency"]
            f = stats["by_frequency"][freq]
            f["count"] += 1
            f["cells"] += cells
            f["iterations"] += iterations
            f["cell_iterations"] += cell_iterations
            f["runtime_s"] += runtime

        if cat.get("placement"):
            # Group by placement type more cleanly
            placement = cat["placement"]
            pl = stats["by_placement"][placement]
            pl["count"] += 1
            pl["cells"] += cells
            pl["iterations"] += iterations
            pl["cell_iterations"] += cell_iterations
            pl["runtime_s"] += runtime

    stats["unique_tissue_count"] = len(unique_tissues)
    stats["total_tissues"] = list(unique_tissues)

    # Convert defaultdicts to simple dicts
    stats["by_phantom"] = {k: dict(v) for k, v in stats["by_phantom"].items()}
    stats["by_frequency"] = {k: dict(v) for k, v in stats["by_frequency"].items()}
    stats["by_placement"] = {k: dict(v) for k, v in stats["by_placement"].items()}

    return stats

format_large_number

format_large_number(n: float, precision: int = 1) -> str

Format large numbers with K/M/B suffixes.

Source code in goliat/analysis/analyze_simulation_stats.py
def format_large_number(n: float, precision: int = 1) -> str:
    """Format large numbers with K/M/B suffixes."""
    if n >= 1e15:
        return f"{n / 1e15:.{precision}f} Quadrillion"
    elif n >= 1e12:
        return f"{n / 1e12:.{precision}f} Trillion"
    elif n >= 1e9:
        return f"{n / 1e9:.{precision}f} Billion"
    elif n >= 1e6:
        return f"{n / 1e6:.{precision}f} Million"
    elif n >= 1e3:
        return f"{n / 1e3:.{precision}f} K"
    else:
        return f"{n:.{precision}f}"

set_custom_style

set_custom_style()

Set a professional, high-contrast engineering dark style.

Source code in goliat/analysis/analyze_simulation_stats.py
def set_custom_style():
    """Set a professional, high-contrast engineering dark style."""
    plt.style.use("seaborn-v0_8-darkgrid")

    # Colors suitable for "Engineering/Simulation" look (Deep Blues, Bright Cyans, Warm Accents)
    bg_color = "#0e1117"
    paper_color = "#0e1117"
    text_color = "#e0e0e0"  # Softer white
    grid_color = "#262730"

    # Updated Palette - Less aggressive, more "Scientific"
    primary_blue = "#2E86C1"  # Strong, professional blue
    cyan_bright = "#00BFA5"  # Teal/Cyan for distinction
    alert_orange = "#FF7043"  # Softer than red, for highlights
    soft_purple = "#9b59b6"
    slate_grey = "#607D8B"
    gold_accent = "#F1C40F"

    plt.rcParams.update(
        {
            "figure.facecolor": paper_color,
            "axes.facecolor": bg_color,
            "axes.edgecolor": grid_color,
            "axes.labelcolor": text_color,
            "text.color": text_color,
            "xtick.color": text_color,
            "ytick.color": text_color,
            "grid.color": grid_color,
            "grid.alpha": 0.6,
            "figure.figsize": (12, 7),
            "font.size": 12,
            "axes.labelsize": 13,
            "axes.titlesize": 16,
            "xtick.labelsize": 11,
            "ytick.labelsize": 11,
            "font.family": "sans-serif",  # Ensure standard font
        }
    )

    return [primary_blue, cyan_bright, alert_orange, soft_purple, slate_grey, gold_accent]

create_visualizations

create_visualizations(stats: dict, output_dir: str | Path)

Create all visualizations with rigorous layout checks.

Source code in goliat/analysis/analyze_simulation_stats.py
def create_visualizations(stats: dict, output_dir: str | Path):
    """Create all visualizations with rigorous layout checks."""
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    colors = set_custom_style()

    # 01. COMPUTATIONAL SCALE
    fig, ax = plt.subplots(figsize=(14, 8))

    labels = ["Cells Computed", "Edges Computed", "Grid Cells (PML)", "Time Steps"]
    values = [stats["total_cell_iterations"], stats["total_edges"], stats["total_cells_with_pml"], stats["total_iterations"]]

    y_pos = np.arange(len(labels))
    # Use the blue/teal/purple palette
    bar_colors = [colors[2], colors[0], colors[1], colors[5]]

    ax.barh(y_pos, values, color=bar_colors, height=0.6, alpha=0.9)

    ax.set_yticks(y_pos)
    ax.set_yticklabels(labels, fontweight="bold")
    ax.set_xscale("log")
    ax.set_title(f"Simulation Campaign Scale ({stats['total_simulations']} Runs)", pad=20, fontweight="bold")
    ax.set_xlabel("Count (Log Scale)")
    ax.grid(True, which="both", ls="-", alpha=0.3)

    # Text labels placed strictly outside for readability
    for i, v in enumerate(values):
        ax.text(v * 1.5, i, f" {format_large_number(v, 2)}", va="center", fontweight="bold", color="white")

    ax.set_xlim(right=max(values) * 50)

    plt.tight_layout()
    fig.savefig(output_dir / "01_computational_scale.png", dpi=200, bbox_inches="tight")
    plt.close(fig)

    # 02. DETAILED PLACEMENT ANALYSIS
    placements = sorted(stats["by_placement"].keys())
    # Clean names
    display_names = [p.replace("by_", "").replace("front_of_", "").replace("_", " ").title() for p in placements]
    values = [stats["by_placement"][p]["cell_iterations"] for p in placements]

    # Sort
    if values:
        sorted_pack = sorted(zip(values, display_names), reverse=False)
        values = [x[0] for x in sorted_pack]
        display_names = [x[1] for x in sorted_pack]

    dynamic_height = max(8, len(values) * 0.4)
    fig, ax = plt.subplots(figsize=(14, dynamic_height))

    # Main bars in primary blue
    ax.barh(range(len(values)), values, color=colors[0], alpha=0.85)

    ax.set_yticks(range(len(values)))
    ax.set_yticklabels(display_names)
    ax.set_xlabel("Computational Cost (Cells Computed)")
    ax.set_title("Computational Load by Antenna Placement", pad=20, fontweight="bold")
    ax.grid(True, axis="x", alpha=0.3)

    max_val = max(values) if values else 1
    for i, v in enumerate(values):
        label_text = f"{format_large_number(v)}"
        if v > max_val * 0.2:
            ax.text(v - (max_val * 0.02), i, label_text, va="center", ha="right", color="white", fontweight="bold")
        else:
            ax.text(v + (max_val * 0.01), i, label_text, va="center", ha="left", color="#dddddd", fontweight="bold")

    plt.tight_layout()
    fig.savefig(output_dir / "02_placement_cost.png", dpi=200, bbox_inches="tight")
    plt.close(fig)

    # 03. PHANTOM & FREQUENCY
    phantom_list = sorted(stats["by_phantom"].keys())

    # Filter out Duke if it somehow snuck in with 0 stats, but keep if real
    # Only keep phantoms with > 0 cell iterations to be safe
    phantom_list = [p for p in phantom_list if stats["by_phantom"][p]["cell_iterations"] > 0]

    freq_list = sorted(stats["by_frequency"].keys(), key=lambda x: int(m.group()) if (m := re.search(r"\d+", x)) else 0)

    fig = plt.figure(figsize=(16, 8))
    gs = gridspec.GridSpec(1, 2, width_ratios=[1, 1], wspace=0.3)

    # Phantoms
    ax0 = plt.subplot(gs[0])
    p_values = [stats["by_phantom"][p]["cell_iterations"] for p in phantom_list]

    # Nice bar colors
    ax0.bar(phantom_list, p_values, color=colors[3], alpha=0.9)
    ax0.set_title("Load by Phantom", fontweight="bold")
    ax0.set_ylabel("Cells Computed")
    ax0.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f"{x / 1e12:.0f}T"))
    ax0.grid(True, axis="y", alpha=0.3)

    # Value labels
    for i, v in enumerate(p_values):
        ax0.text(i, v, f"{v / 1e12:.1f}T", ha="center", va="bottom", fontweight="bold", color="white")

    # Frequencies
    ax1 = plt.subplot(gs[1])
    f_values = [stats["by_frequency"][f]["cell_iterations"] for f in freq_list]
    ax1.bar(freq_list, f_values, color=colors[1], alpha=0.9)
    ax1.set_title("Load by Frequency", fontweight="bold")
    ax1.tick_params(axis="x", rotation=45)
    ax1.grid(True, axis="y", alpha=0.3)

    plt.tight_layout()
    fig.savefig(output_dir / "03_phantom_freq_breakdown.png", dpi=200, bbox_inches="tight")
    plt.close(fig)

    # 04. CLIENT INFOGRAPHIC (Enhanced)
    fig = plt.figure(figsize=(18, 10))
    fig.patch.set_facecolor("#0e1117")

    # Compute additional metrics
    peak_speed_gcells_s = max(stats["peak_speed_list"]) / 1000 if stats["peak_speed_list"] else 0
    avg_runtime_min = (stats["total_runtime_s"] / stats["total_simulations"]) / 60 if stats["total_simulations"] > 0 else 0
    num_placements = len(stats["by_placement"])

    # Get frequency range
    freq_list_sorted = sorted(stats["by_frequency"].keys(), key=lambda x: int(m.group()) if (m := re.search(r"\d+", x)) else 0)
    if freq_list_sorted:
        freq_range = f"{freq_list_sorted[0]} - {freq_list_sorted[-1]}"
    else:
        freq_range = "N/A"

    # Title Area
    gs = gridspec.GridSpec(5, 4, height_ratios=[0.15, 0.28, 0.28, 0.28, 0.08], hspace=0.15)
    ax_title = plt.subplot(gs[0, :])
    ax_title.axis("off")
    ax_title.text(0.5, 0.5, "NEAR FIELD COMPUTATIONAL CAMPAIGN", ha="center", va="center", fontsize=30, color=colors[1], fontweight="bold")

    # Row 1: Hero Stats (Large)
    hero_stats = [
        ("TOTAL RUNS", f"{stats['total_simulations']}", colors[0]),
        ("CELLS COMPUTED", f"{stats['total_cell_iterations'] / 1e15:.2f} Quadrillion", colors[2]),
        ("COMPUTE TIME", f"{stats['total_runtime_s'] / 3600:.0f} Hours", colors[1]),
        ("PEAK SPEED", f"{peak_speed_gcells_s:.1f} GCells/s", colors[5]),
    ]

    for i, (k, v, c) in enumerate(hero_stats):
        ax = plt.subplot(gs[1, i])
        ax.axis("off")
        ax.text(0.5, 0.6, v, ha="center", va="center", fontsize=24, fontweight="bold", color=c)
        ax.text(0.5, 0.3, k, ha="center", va="center", fontsize=11, fontweight="bold", color="#aaaaaa")

    # Row 2: Grid & Data Stats
    row2_stats = [
        ("Grid Cells", f"{stats['total_cells_with_pml'] / 1e9:.1f} Billion", "#ffffff"),
        ("Data Edges", f"{stats['total_edges'] / 1e9:.1f} Billion", "#ffffff"),
        ("Time Steps", f"{stats['total_iterations'] / 1e6:.1f} Million", "#ffffff"),
        ("Avg Sim Time", f"{avg_runtime_min:.1f} min", "#ffffff"),
    ]

    for i, (k, v, c) in enumerate(row2_stats):
        ax = plt.subplot(gs[2, i])
        ax.axis("off")
        rect = plt.Rectangle((0.1, 0.15), 0.8, 0.7, transform=ax.transAxes, fill=True, color="#1e222b", zorder=0, alpha=0.8, lw=0)
        ax.add_patch(rect)
        ax.text(0.5, 0.6, v, ha="center", va="center", fontsize=18, fontweight="bold", color=c)
        ax.text(0.5, 0.35, k, ha="center", va="center", fontsize=11, color="#888888")

    # Row 3: Study Configuration
    row3_stats = [
        ("Anatomical Models", f"{len(phantom_list)}", "#ffffff"),
        ("Frequency Range", freq_range, "#ffffff"),
        ("Antenna Placements", f"{num_placements}", "#ffffff"),
        ("Tissues Modeled", f"{stats['unique_tissue_count']}", "#ffffff"),
    ]

    for i, (k, v, c) in enumerate(row3_stats):
        ax = plt.subplot(gs[3, i])
        ax.axis("off")
        rect = plt.Rectangle((0.1, 0.15), 0.8, 0.7, transform=ax.transAxes, fill=True, color="#1e222b", zorder=0, alpha=0.8, lw=0)
        ax.add_patch(rect)
        ax.text(0.5, 0.6, v, ha="center", va="center", fontsize=18, fontweight="bold", color=c)
        ax.text(0.5, 0.35, k, ha="center", va="center", fontsize=11, color="#888888")

    # Footer
    ax_foot = plt.subplot(gs[4, :])
    ax_foot.axis("off")
    ax_foot.text(
        0.5,
        0.5,
        f"Generated: {datetime.now().strftime('%Y-%m-%d')} | GOLIAT Solver Analysis",
        ha="center",
        va="center",
        fontsize=10,
        color="#666666",
    )

    plt.tight_layout()
    fig.savefig(output_dir / "00_summary_infographic.png", dpi=200, bbox_inches="tight")
    plt.close(fig)

    # 04. RUNTIME DISTRIBUTION (Restored)
    if stats["runtime_list"]:
        fig, ax = plt.subplots(figsize=(14, 7))
        # Convert to minutes
        runtimes_min = [r / 60 for r in stats["runtime_list"]]

        ax.hist(runtimes_min, bins=30, color=colors[3], alpha=0.7, edgecolor=colors[3])
        ax.set_title("Simulation Runtime Distribution", pad=20, fontweight="bold")
        ax.set_xlabel("Runtime (Minutes)")
        ax.set_ylabel("Number of Simulations")

        # Add a text box with stats
        avg_runtime = np.mean(runtimes_min)
        total_hours = sum(runtimes_min) / 60
        stats_text = f"Total Time: {total_hours:.1f} Hours\nAvg Runtime: {avg_runtime:.1f} min\nMax Runtime: {max(runtimes_min):.1f} min"

        ax.text(
            0.95,
            0.95,
            stats_text,
            transform=ax.transAxes,
            verticalalignment="top",
            horizontalalignment="right",
            bbox=dict(boxstyle="round", facecolor="#1e222b", alpha=0.8, edgecolor=colors[4]),
            color="white",
            fontsize=12,
        )

        ax.grid(True, axis="y", alpha=0.3)
        plt.tight_layout()
        fig.savefig(output_dir / "04_runtime_distribution.png", dpi=200, bbox_inches="tight")
        plt.close(fig)

    # 05. SCATTER PLOT: GRID SIZE vs RUNTIME
    if stats["cells_list"] and stats["runtime_list"]:
        fig, ax = plt.subplots(figsize=(14, 8))

        cells_m = [c / 1e6 for c in stats["cells_list"]]
        # Convert seconds to minutes
        runtimes_min = [r / 60 for r in stats["runtime_list"]]

        # Scatter with alpha to show density
        ax.scatter(cells_m, runtimes_min, c=colors[1], alpha=0.6, s=80, edgecolors="none")

        ax.set_title("Solver Performance: Grid Size vs Compute Time", pad=20, fontweight="bold")
        ax.set_xlabel("Grid Size (Million Cells)")
        ax.set_ylabel("Compute Time (Minutes)")
        ax.set_xlim(left=0)
        ax.set_ylim(bottom=0)
        ax.grid(True, alpha=0.3)

        # Add correlation text
        if len(cells_m) > 1:
            try:
                corr = np.corrcoef(cells_m, runtimes_min)[0, 1]
                ax.text(
                    0.05,
                    0.95,
                    f"Correlation: {corr:.3f}",
                    transform=ax.transAxes,
                    bbox=dict(boxstyle="round", facecolor="#1e222b", alpha=0.8),
                    color="white",
                )
            except Exception:
                pass

        plt.tight_layout()
        fig.savefig(output_dir / "05_solver_scaling.png", dpi=200, bbox_inches="tight")
        plt.close(fig)

    # 06. SPEED DISTRIBUTION PLOT
    if stats["peak_speed_list"]:
        fig, ax = plt.subplots(figsize=(14, 7))

        # Convert to GCells/s for readability
        peak_speeds_gcells = [s / 1000 for s in stats["peak_speed_list"]]

        # Histogram of Peak Speeds
        ax.hist(peak_speeds_gcells, bins=25, color=colors[2], alpha=0.8, edgecolor=colors[2])
        ax.set_title("Solver Speed Distribution", pad=15, fontweight="bold")
        ax.set_xlabel("Peak Speed (GCells/s)")
        ax.set_ylabel("Number of Simulations")
        ax.grid(True, axis="y", alpha=0.3)

        # Add stats annotation
        max_speed = max(peak_speeds_gcells)
        avg_peak = np.mean(peak_speeds_gcells)
        stats_text = (
            f"Fastest: {max_speed:.2f} GCells/s\nAvg Peak: {avg_peak:.2f} GCells/s\nMin Peak: {min(peak_speeds_gcells):.2f} GCells/s"
        )
        ax.axvline(max_speed, color=colors[5], linestyle="--", linewidth=2, label=f"Fastest: {max_speed:.2f}")
        ax.text(
            0.95,
            0.95,
            stats_text,
            transform=ax.transAxes,
            verticalalignment="top",
            horizontalalignment="right",
            bbox=dict(boxstyle="round", facecolor="#1e222b", alpha=0.9, edgecolor=colors[5]),
            color="white",
            fontsize=11,
        )

        plt.tight_layout()
        fig.savefig(output_dir / "06_speed_distribution.png", dpi=200, bbox_inches="tight")
        plt.close(fig)

main

main()

CLI entry point. Parses logs and generates stats/plots.

Source code in goliat/analysis/analyze_simulation_stats.py
def main():
    """CLI entry point. Parses logs and generates stats/plots."""
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("results_dir", nargs="?", default="results")
    parser.add_argument("-o", "--output", default="paper/simulation_stats")
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()

    log_files = find_all_verbose_logs(args.results_dir)
    all_metrics = parse_all_logs(log_files)

    if not all_metrics:
        logging.getLogger("progress").warning("  No Near-Field logs found.", extra={"log_type": "warning"})
        return

    stats = compute_aggregate_stats(all_metrics)

    logging.getLogger("progress").info(f"  Total Simulations: {stats['total_simulations']}", extra={"log_type": "info"})
    logging.getLogger("progress").info(
        f"  Total Cell-Iterations: {format_large_number(stats['total_cell_iterations'])}", extra={"log_type": "info"}
    )

    create_visualizations(stats, args.output)

    if args.json:
        json_path = Path(args.output) / "nf_stats.json"
        # We need to filter out the large lists before dumping
        json_stats = stats.copy()
        json_stats["iterations_list"] = []
        json_stats["cells_list"] = []
        json_stats["runtime_list"] = []
        json_stats["cell_iterations_list"] = []
        json_stats["peak_speed_list"] = []
        json_stats["avg_speed_list"] = []

        with open(json_path, "w") as f:
            json.dump(json_stats, f, indent=2)

    logging.getLogger("progress").info(f"  Saved visualizations to: {args.output}/", extra={"log_type": "success"})

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
def __init__(self, config: "Config", phantom_name: str, strategy: "BaseAnalysisStrategy", plot_format: str = "pdf"):
    """Sets up the analyzer with a strategy.

    Args:
        config: Configuration object.
        phantom_name: Phantom model name being analyzed.
        strategy: Strategy implementation for analysis logic.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.config = config
    self.base_dir = config.base_dir
    self.phantom_name = phantom_name
    self.strategy = strategy
    self.results_base_dir = self.strategy.get_results_base_dir()
    self.plotter = Plotter(self.strategy.get_plots_dir(), phantom_name=self.phantom_name, plot_format=plot_format)
    self.all_results = []
    self.all_organ_results = []
    # Will be populated from pickle files - contains actual tissue names from extraction
    # This is the authoritative source, computed during extraction using material_name_mapping.json
    self.tissue_group_composition = {}

Methods:

run_analysis

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
def run_analysis(self):
    """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.
    """
    logging.getLogger("progress").info(
        f"--- Starting Results Analysis for Phantom: {self.phantom_name} ---",
        extra={"log_type": "header"},
    )

    # Check if we should load data or use cache instead
    load_data = self.strategy.analysis_config.get("load_data", True)

    if not load_data:
        logging.getLogger("progress").info(
            "--- Skipping data loading phase, loading from cache ---",
            extra={"log_type": "info"},
        )
        results_df, all_organ_results_df = self._load_from_cache()
        if results_df is None:
            logging.getLogger("progress").error(
                "--- Failed to load cached results. Run analysis with load_data=True first. ---",
                extra={"log_type": "error"},
            )
            return
    else:
        self.strategy.load_and_process_results(self)

        if not self.all_results:
            logging.getLogger("progress").info("--- No results found to analyze. ---", extra={"log_type": "warning"})
            return

        results_df = pd.DataFrame(self.all_results)
        all_organ_results_df = pd.DataFrame(self.all_organ_results) if self.all_organ_results else pd.DataFrame()

        results_df = self._convert_units_and_cache(results_df, all_organ_results_df)
        self._export_reports(results_df, all_organ_results_df)

    self.strategy.generate_plots(self, self.plotter, results_df, all_organ_results_df)

    logging.getLogger("progress").info("--- Analysis Finished ---", extra={"log_type": "success"})

Base Strategy

goliat.analysis.base_strategy.BaseAnalysisStrategy

BaseAnalysisStrategy(config: Config, phantom_name: str, analysis_config: dict | None = None)

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
def __init__(self, config: "Config", phantom_name: str, analysis_config: dict | None = None):
    """Sets up the analysis strategy.

    Args:
        config: Configuration object.
        phantom_name: Phantom model name being analyzed.
        analysis_config: Optional dictionary with plot names as keys and boolean values.
    """
    self.config = config
    self.phantom_name = phantom_name
    self.base_dir = config.base_dir
    self.analysis_config = analysis_config or {}

Methods:

should_generate_plot

should_generate_plot(plot_name: str) -> bool

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
def should_generate_plot(self, plot_name: str) -> bool:
    """Checks if a plot should be generated based on the analysis config.

    Args:
        plot_name: Name of the plot to check.

    Returns:
        True if the plot should be generated (default if not in config), False otherwise.
    """
    if not self.analysis_config:
        return True  # Generate all plots if no config provided
    return self.analysis_config.get(plot_name, True)  # Default to True if not specified

get_expected_item_count

get_expected_item_count() -> int

Returns expected number of progress items for this phantom.

This is used by the GUI to set an accurate progress bar maximum. Each item corresponds to one progress log message (Processing, Generating plot, etc.).

Returns:

Type Description
int

Expected number of items that will trigger progress updates.

Source code in goliat/analysis/base_strategy.py
def get_expected_item_count(self) -> int:
    """Returns expected number of progress items for this phantom.

    This is used by the GUI to set an accurate progress bar maximum.
    Each item corresponds to one progress log message (Processing, Generating plot, etc.).

    Returns:
        Expected number of items that will trigger progress updates.
    """
    raise NotImplementedError("Subclasses must implement get_expected_item_count()")

get_results_base_dir

get_results_base_dir() -> str

Returns base directory path for results. Must be implemented by subclasses.

Source code in goliat/analysis/base_strategy.py
def get_results_base_dir(self) -> str:
    """Returns base directory path for results. Must be implemented by subclasses."""
    raise NotImplementedError

get_plots_dir

get_plots_dir() -> str

Returns directory path for saving plots. Must be implemented by subclasses.

Source code in goliat/analysis/base_strategy.py
def get_plots_dir(self) -> str:
    """Returns directory path for saving plots. Must be implemented by subclasses."""
    raise NotImplementedError

load_and_process_results abstractmethod

load_and_process_results(analyzer: Analyzer)

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
@abstractmethod
def load_and_process_results(self, analyzer: "Analyzer"):
    """Loads and processes all simulation results.

    Iterates through configured scenarios and calls analyzer._process_single_result()
    for each one.

    Args:
        analyzer: Analyzer instance to process results with.
    """
    pass

get_normalization_factor abstractmethod

get_normalization_factor(frequency_mhz: int, simulated_power_w: float) -> float

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
@abstractmethod
def get_normalization_factor(self, frequency_mhz: int, simulated_power_w: float) -> float:
    """Calculates SAR normalization factor from simulated power.

    Args:
        frequency_mhz: Simulation frequency in MHz.
        simulated_power_w: Input power from simulation in Watts.

    Returns:
        Normalization factor to multiply SAR values by.
    """
    pass

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, sapd_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
sapd_results dict | None

Optional SAPD JSON results dict (present when sapd=true in config).

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
@abstractmethod
def extract_data(
    self,
    pickle_data: dict,
    frequency_mhz: int,
    placement_name: str,
    scenario_name: str,
    sim_power: float,
    norm_factor: float,
    sar_results: dict | None = None,
    sapd_results: dict | None = None,
) -> tuple[dict, list]:
    """Extracts and structures data from a single simulation's result files.

    Args:
        pickle_data: Data loaded from the .pkl result file.
        frequency_mhz: Simulation frequency.
        placement_name: Detailed placement name.
        scenario_name: General scenario name.
        sim_power: Simulated input power in Watts.
        norm_factor: Normalization factor to apply.
        sar_results: Optional JSON results dict containing additional data like power balance.
        sapd_results: Optional SAPD JSON results dict (present when sapd=true in config).

    Returns:
        Tuple of (main result entry dict, list of organ-specific entries).
    """
    pass

apply_bug_fixes abstractmethod

apply_bug_fixes(result_entry: dict) -> dict

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
@abstractmethod
def apply_bug_fixes(self, result_entry: dict) -> dict:
    """Applies workarounds for known data inconsistencies.

    Args:
        result_entry: Data entry for a single simulation result.

    Returns:
        Corrected result entry.
    """
    return result_entry

calculate_summary_stats abstractmethod

calculate_summary_stats(results_df: DataFrame) -> pd.DataFrame

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
@abstractmethod
def calculate_summary_stats(self, results_df: pd.DataFrame) -> pd.DataFrame:
    """Calculates summary statistics from aggregated results.

    Args:
        results_df: DataFrame with all aggregated simulation results.

    Returns:
        DataFrame with summary statistics.
    """
    pass

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
@abstractmethod
def generate_plots(
    self,
    analyzer: "Analyzer",
    plotter: "Plotter",
    results_df: pd.DataFrame,
    all_organ_results_df: pd.DataFrame,
):
    """Generates study-type specific plots.

    Args:
        analyzer: Analyzer instance with aggregated data.
        plotter: Plotter instance for creating figures.
        results_df: DataFrame with summary results.
        all_organ_results_df: DataFrame with organ-level details.
    """
    pass

Compare

goliat.analysis.compare

Compare UGent and CNR data from Excel files and create comparison plots.

This module provides functionality to compare SAR data between different institutions (UGent and CNR) and create publication-quality comparison plots.

Functions:

load_comparison_data

load_comparison_data(ugent_file: str, cnr_file: str) -> pd.DataFrame

Load all data from both Excel files.

Parameters:

Name Type Description Default
ugent_file str

Path to UGent Excel file

required
cnr_file str

Path to CNR Excel file

required

Returns:

Type Description
DataFrame

Combined DataFrame with all data

Source code in goliat/analysis/compare.py
def load_comparison_data(
    ugent_file: str,
    cnr_file: str,
) -> pd.DataFrame:
    """Load all data from both Excel files.

    Args:
        ugent_file: Path to UGent Excel file
        cnr_file: Path to CNR Excel file

    Returns:
        Combined DataFrame with all data
    """
    all_data = []

    # Load UGent data
    if os.path.exists(ugent_file):
        logging.getLogger("progress").info(
            f"Loading UGent data from: {ugent_file}",
            extra={"log_type": "info"},
        )
        xl_ugent = pd.ExcelFile(ugent_file)
        for sheet_name in xl_ugent.sheet_names:
            df = pd.read_excel(ugent_file, sheet_name=sheet_name)
            parts = sheet_name.split("_")
            phantom = parts[0]
            scenario = "_".join(parts[1:])
            df["phantom"] = phantom
            df["institution"] = "UGent"
            df["scenario"] = scenario
            all_data.append(df)
    else:
        logging.getLogger("progress").warning(
            f"UGent file not found: {ugent_file}",
            extra={"log_type": "warning"},
        )

    # Load CNR data
    if os.path.exists(cnr_file):
        logging.getLogger("progress").info(
            f"Loading CNR data from: {cnr_file}",
            extra={"log_type": "info"},
        )
        xl_cnr = pd.ExcelFile(cnr_file)
        for sheet_name in xl_cnr.sheet_names:
            df = pd.read_excel(cnr_file, sheet_name=sheet_name)
            parts = sheet_name.split("_")
            phantom = parts[0]
            scenario = "_".join(parts[1:])
            df["phantom"] = phantom
            df["institution"] = "CNR"
            df["scenario"] = scenario
            all_data.append(df)
    else:
        logging.getLogger("progress").warning(
            f"CNR file not found: {cnr_file}",
            extra={"log_type": "warning"},
        )

    if not all_data:
        return pd.DataFrame()

    combined_df = pd.concat(all_data, ignore_index=True)
    return combined_df

create_comparison_plots

create_comparison_plots(df: DataFrame, output_dir: Path, plot_format: str = 'pdf')

Create comparison plots for all metrics and scenarios.

Parameters:

Name Type Description Default
df DataFrame

Combined DataFrame with UGent and CNR data

required
output_dir Path

Directory to save plots

required
plot_format str

Output format ('pdf' or 'png')

'pdf'
Source code in goliat/analysis/compare.py
def create_comparison_plots(
    df: pd.DataFrame,
    output_dir: Path,
    plot_format: str = "pdf",
):
    """Create comparison plots for all metrics and scenarios.

    Args:
        df: Combined DataFrame with UGent and CNR data
        output_dir: Directory to save plots
        plot_format: Output format ('pdf' or 'png')
    """
    output_dir.mkdir(exist_ok=True, parents=True)

    for scenario in SCENARIOS:
        scenario_data = df[df["scenario"] == scenario].copy()

        if scenario_data.empty:
            logging.getLogger("progress").info(
                f"No data found for scenario: {scenario}",
                extra={"log_type": "warning"},
            )
            continue

        for metric in METRICS:
            if metric not in scenario_data.columns:
                continue

            metric_data = scenario_data[scenario_data[metric].notna()].copy()

            if metric_data.empty:
                continue

            fig, ax = plt.subplots(figsize=(3.5, 2.5))  # IEEE single-column

            phantoms = metric_data["phantom"].unique()

            for phantom in sorted(phantoms):
                phantom_data = metric_data[metric_data["phantom"] == phantom]
                institution = phantom_data["institution"].iloc[0]

                grouped = phantom_data.groupby("frequency_mhz")[metric].agg(["mean", "std"])

                x = grouped.index.values
                y_mean = grouped["mean"].values
                y_std = grouped["std"].values

                label = f"{phantom} ({institution})"
                color = INSTITUTION_COLORS.get(institution, "gray")
                marker = PHANTOM_MARKERS.get(phantom, "o")

                ax.errorbar(
                    x,
                    y_mean,
                    yerr=y_std,
                    marker=marker,
                    linestyle="-",
                    label=label,
                    color=color,
                    markersize=4,
                    capsize=2,
                    capthick=1,
                    linewidth=1.5,
                )

            ax.set_xlabel("Frequency (MHz)")
            ax.set_ylabel(metric)
            ax.legend(loc="best", fontsize=7)
            ax.grid(True, alpha=0.3)
            ax.set_ylim(bottom=0)

            plt.tight_layout()

            safe_metric = metric.replace(" ", "_").replace("/", "_").replace("(", "").replace(")", "")
            filename = f"compare_{safe_metric}_{scenario}.{plot_format}"
            filepath = output_dir / filename

            if plot_format == "pdf":
                fig.savefig(filepath, bbox_inches="tight", format="pdf")
            else:
                fig.savefig(filepath, dpi=300, bbox_inches="tight")

            plt.close(fig)
            logging.getLogger("progress").info(
                f"  - Generated comparison plot: {filename}",
                extra={"log_type": "success"},
            )

create_summary_comparison_plots

create_summary_comparison_plots(df: DataFrame, output_dir: Path, plot_format: str = 'pdf')

Create summary comparison plots across all scenarios.

Parameters:

Name Type Description Default
df DataFrame

Combined DataFrame with UGent and CNR data

required
output_dir Path

Directory to save plots

required
plot_format str

Output format ('pdf' or 'png')

'pdf'
Source code in goliat/analysis/compare.py
def create_summary_comparison_plots(
    df: pd.DataFrame,
    output_dir: Path,
    plot_format: str = "pdf",
):
    """Create summary comparison plots across all scenarios.

    Args:
        df: Combined DataFrame with UGent and CNR data
        output_dir: Directory to save plots
        plot_format: Output format ('pdf' or 'png')
    """
    output_dir.mkdir(exist_ok=True, parents=True)

    for metric in METRICS:
        if metric not in df.columns:
            continue

        metric_data = df[df[metric].notna()].copy()

        if metric_data.empty:
            continue

        # Create figure with 3 subplots (one per scenario)
        fig, axes = plt.subplots(1, 3, figsize=(7, 2.5))

        for idx, scenario in enumerate(SCENARIOS):
            ax = axes[idx]
            scenario_data = metric_data[metric_data["scenario"] == scenario]

            if scenario_data.empty:
                ax.text(0.5, 0.5, "No data", ha="center", va="center", transform=ax.transAxes)
                ax.set_title(scenario.replace("_", " ").title())
                continue

            phantoms = scenario_data["phantom"].unique()
            for phantom in sorted(phantoms):
                phantom_data = scenario_data[scenario_data["phantom"] == phantom]
                institution = phantom_data["institution"].iloc[0]

                grouped = phantom_data.groupby("frequency_mhz")[metric].agg(["mean", "std"])

                x = grouped.index.values
                y_mean = grouped["mean"].values
                y_std = grouped["std"].values

                label = f"{phantom}"
                color = INSTITUTION_COLORS.get(institution, "gray")
                marker = PHANTOM_MARKERS.get(phantom, "o")
                linestyle = "-" if institution == "UGent" else "--"

                ax.errorbar(
                    x,
                    y_mean,
                    yerr=y_std,
                    marker=marker,
                    linestyle=linestyle,
                    label=label,
                    color=color,
                    markersize=3,
                    capsize=1,
                    capthick=0.5,
                    linewidth=1,
                )

            ax.set_xlabel("Frequency (MHz)")
            if idx == 0:
                ax.set_ylabel(metric.replace("_", " "))
            ax.set_title(scenario.replace("_", " ").title())
            ax.legend(loc="best", fontsize=6)
            ax.grid(True, alpha=0.3)
            ax.set_ylim(bottom=0)

        plt.tight_layout()

        safe_metric = metric.replace(" ", "_").replace("/", "_").replace("(", "").replace(")", "")
        filename = f"compare_summary_{safe_metric}.{plot_format}"
        filepath = output_dir / filename

        if plot_format == "pdf":
            fig.savefig(filepath, bbox_inches="tight", format="pdf")
        else:
            fig.savefig(filepath, dpi=300, bbox_inches="tight")

        plt.close(fig)
        logging.getLogger("progress").info(
            f"  - Generated summary comparison plot: {filename}",
            extra={"log_type": "success"},
        )

run_comparison

run_comparison(ugent_file: str, cnr_file: str, output_dir: str, plot_format: str = 'pdf')

Run the full comparison analysis.

Parameters:

Name Type Description Default
ugent_file str

Path to UGent Excel file

required
cnr_file str

Path to CNR Excel file

required
output_dir str

Directory to save comparison plots

required
plot_format str

Output format ('pdf' or 'png')

'pdf'
Source code in goliat/analysis/compare.py
def run_comparison(
    ugent_file: str,
    cnr_file: str,
    output_dir: str,
    plot_format: str = "pdf",
):
    """Run the full comparison analysis.

    Args:
        ugent_file: Path to UGent Excel file
        cnr_file: Path to CNR Excel file
        output_dir: Directory to save comparison plots
        plot_format: Output format ('pdf' or 'png')
    """
    # Apply white background style (overrides any dark mode from other modules)
    _apply_comparison_style()

    logging.getLogger("progress").info(
        "=" * 60,
        extra={"log_type": "header"},
    )
    logging.getLogger("progress").info(
        "   UGent vs CNR Data Comparison",
        extra={"log_type": "header"},
    )
    logging.getLogger("progress").info(
        "=" * 60,
        extra={"log_type": "header"},
    )

    # Load data
    df = load_comparison_data(ugent_file, cnr_file)

    if df.empty:
        logging.getLogger("progress").error(
            "No data loaded. Please check file paths.",
            extra={"log_type": "error"},
        )
        return

    logging.getLogger("progress").info(
        f"Loaded {len(df)} total data points",
        extra={"log_type": "success"},
    )
    logging.getLogger("progress").info(
        f"Phantoms: {list(df['phantom'].unique())}",
        extra={"log_type": "info"},
    )
    logging.getLogger("progress").info(
        f"Institutions: {list(df['institution'].unique())}",
        extra={"log_type": "info"},
    )
    logging.getLogger("progress").info(
        f"Scenarios: {list(df['scenario'].unique())}",
        extra={"log_type": "info"},
    )

    output_path = Path(output_dir)

    # Create individual comparison plots
    logging.getLogger("progress").info(
        "\nCreating individual comparison plots...",
        extra={"log_type": "info"},
    )
    create_comparison_plots(df, output_path, plot_format)

    # Create summary plots
    logging.getLogger("progress").info(
        "\nCreating summary comparison plots...",
        extra={"log_type": "info"},
    )
    create_summary_comparison_plots(df, output_path, plot_format)

    logging.getLogger("progress").info(
        f"\nAll comparison plots saved to: {output_dir}",
        extra={"log_type": "success"},
    )

main

main()

Main entry point for CLI usage.

Source code in goliat/analysis/compare.py
def main():
    """Main entry point for CLI usage."""
    import argparse

    parser = argparse.ArgumentParser(description="Compare UGent and CNR SAR data from Excel files")
    parser.add_argument(
        "--ugent-file",
        type=str,
        default="results/near_field/Final_Data_UGent.xlsx",
        help="Path to UGent Excel file",
    )
    parser.add_argument(
        "--cnr-file",
        type=str,
        default="results/near_field/Final_Data_CNR.xlsx",
        help="Path to CNR Excel file",
    )
    parser.add_argument(
        "-o",
        "--output",
        type=str,
        default="plots/comparison",
        help="Output directory for comparison plots",
    )
    parser.add_argument(
        "--format",
        type=str,
        choices=["pdf", "png"],
        default="pdf",
        help="Output format for plots",
    )
    args = parser.parse_args()

    # Setup basic logging if not in goliat context
    from goliat.logging_manager import setup_loggers

    setup_loggers()

    run_comparison(
        args.ugent_file,
        args.cnr_file,
        args.output,
        args.format,
    )

Create Excel For Partners

goliat.analysis.create_excel_for_partners

Create Excel file matching CNR's Excel format for Thelonious and Eartha phantoms.

Functions:

get_target_power_mapping

get_target_power_mapping(config_path: str) -> dict[int, int]

Read target power values from config file for each frequency.

Source code in goliat/analysis/create_excel_for_partners.py
def get_target_power_mapping(config_path: str) -> dict[int, int]:
    """Read target power values from config file for each frequency."""
    with open(config_path, "r") as f:
        config = json.load(f)

    antenna_config = config.get("antenna_config", {})
    power_mapping = {}

    for freq_str, freq_config in antenna_config.items():
        if isinstance(freq_config, dict) and "target_power_mW" in freq_config:
            frequency_mhz = int(freq_str)
            power_mapping[frequency_mhz] = freq_config["target_power_mW"]

    return power_mapping

map_placement_name

map_placement_name(placement: str, sheet_type: str) -> str

Map placement names to match CNR's Excel format.

Parameters:

Name Type Description Default
placement str

Original placement name from CSV

required
sheet_type str

One of 'fronteyes', 'belly', or 'cheek'

required

Returns:

Type Description
str

Mapped placement name matching CNR's Excel format

Source code in goliat/analysis/create_excel_for_partners.py
def map_placement_name(placement: str, sheet_type: str) -> str:
    """Map placement names to match CNR's Excel format.

    Args:
        placement: Original placement name from CSV
        sheet_type: One of 'fronteyes', 'belly', or 'cheek'

    Returns:
        Mapped placement name matching CNR's Excel format
    """
    if sheet_type == "fronteyes":
        # front_of_eyes_* placements stay the same
        if placement.startswith("front_of_eyes_"):
            return placement
    elif sheet_type == "belly":
        # by_belly_* -> belly_level_*
        if placement.startswith("by_belly_"):
            return placement.replace("by_belly_", "belly_level_")
    elif sheet_type == "cheek":
        # Map cheek placements to cheek_1, cheek_2, cheek_3, tilt_1, tilt_2, tilt_3
        mapping = {
            "by_cheek_tragus_cheek_base": "cheek_1",
            "by_cheek_tragus_cheek_up": "cheek_2",
            "by_cheek_tragus_cheek_down": "cheek_3",
            "by_cheek_tragus_tilt_base": "tilt_1",
            "by_cheek_tragus_tilt_up": "tilt_2",
            "by_cheek_tragus_tilt_down": "tilt_3",
        }
        return mapping.get(placement, placement)

    return placement

create_sheet_data

create_sheet_data(df: DataFrame, sheet_type: str, power_mapping: dict[int, int]) -> pd.DataFrame

Create data for one sheet matching CNR's Excel format.

Parameters:

Name Type Description Default
df DataFrame

Source DataFrame from CSV

required
sheet_type str

One of 'fronteyes', 'belly', or 'cheek'

required
power_mapping dict[int, int]

Dictionary mapping frequency (MHz) to target power (mW)

required

Returns:

Type Description
DataFrame

DataFrame formatted to match CNR's Excel sheet format

Source code in goliat/analysis/create_excel_for_partners.py
def create_sheet_data(
    df: pd.DataFrame,
    sheet_type: str,
    power_mapping: dict[int, int],
) -> pd.DataFrame:
    """Create data for one sheet matching CNR's Excel format.

    Args:
        df: Source DataFrame from CSV
        sheet_type: One of 'fronteyes', 'belly', or 'cheek'
        power_mapping: Dictionary mapping frequency (MHz) to target power (mW)

    Returns:
        DataFrame formatted to match CNR's Excel sheet format
    """
    # Filter placements based on sheet type
    if sheet_type == "fronteyes":
        filtered_df = df[df["placement"].str.startswith("front_of_eyes_")].copy()
    elif sheet_type == "belly":
        filtered_df = df[df["placement"].str.startswith("by_belly_")].copy()
    elif sheet_type == "cheek":
        filtered_df = df[df["placement"].str.startswith("by_cheek_tragus_")].copy()
    else:
        raise ValueError(f"Unknown sheet_type: {sheet_type}")

    if filtered_df.empty:
        return pd.DataFrame()

    # Map placement names to match CNR's Excel format
    filtered_df["placement"] = filtered_df["placement"].apply(lambda x: map_placement_name(x, sheet_type))

    # Create output DataFrame with column names matching CNR's Excel format
    result_df = pd.DataFrame()
    result_df["frequency_mhz"] = filtered_df["frequency_mhz"]
    result_df["placement"] = filtered_df["placement"]

    # Add Input Power column based on frequency (matching CNR's Excel format)
    result_df["Input Power (mW)"] = result_df["frequency_mhz"].map(power_mapping)
    # Fill in any missing target powers (e.g. for new frequencies not in the power_mapping)
    result_df["Input Power (mW)"] = result_df["Input Power (mW)"].fillna("N/A")

    # Map SAR and SAPD columns to match CNR's Excel format
    sar_mapping = {
        "SAR_wholebody (mW/kg)": "SAR_whole_body",
        "SAR_head (mW/kg)": "SAR_head",
        "SAR_trunk (mW/kg)": "SAR_trunk",
        "Peak SAPD (W/m²)": "peak_sapd_W_m2",
    }

    for excel_col, csv_col in sar_mapping.items():
        if csv_col in filtered_df.columns:
            result_df[excel_col] = filtered_df[csv_col]
        else:
            result_df[excel_col] = pd.NA

    # Sort by frequency and placement
    result_df = result_df.sort_values(by=["frequency_mhz", "placement"]).reset_index(drop=True)

    return result_df

create_cnr_excel

create_cnr_excel(phantom_name: str, csv_path: str, config_path: str, output_path: str)

Create Excel file matching CNR's Excel format for a phantom.

Parameters:

Name Type Description Default
phantom_name str

Name of the phantom (e.g., 'thelonious', 'eartha')

required
csv_path str

Path to normalized_results_detailed.csv

required
config_path str

Path to config JSON file with antenna_config

required
output_path str

Path where Excel file should be saved

required
Source code in goliat/analysis/create_excel_for_partners.py
def create_cnr_excel(
    phantom_name: str,
    csv_path: str,
    config_path: str,
    output_path: str,
):
    """Create Excel file matching CNR's Excel format for a phantom.

    Args:
        phantom_name: Name of the phantom (e.g., 'thelonious', 'eartha')
        csv_path: Path to normalized_results_detailed.csv
        config_path: Path to config JSON file with antenna_config
        output_path: Path where Excel file should be saved
    """
    # Read CSV data
    df = pd.read_csv(csv_path)

    # Get power mapping from config
    power_mapping = get_target_power_mapping(config_path)

    # Create data for each sheet
    sheet_fronteyes = create_sheet_data(df, "fronteyes", power_mapping)
    sheet_belly = create_sheet_data(df, "belly", power_mapping)
    sheet_cheek = create_sheet_data(df, "cheek", power_mapping)

    # Create Excel file with multiple sheets
    sheet_name = f"{phantom_name.capitalize()}_fronteyes"
    belly_name = f"{phantom_name.capitalize()}_belly"
    cheek_name = f"{phantom_name.capitalize()}_cheek"

    with pd.ExcelWriter(output_path, engine="openpyxl") as writer:
        # Write sheets in order: fronteyes (sheet 1), belly (sheet 2), cheek (sheet 3)
        sheet_fronteyes.to_excel(writer, sheet_name=sheet_name, index=False)
        sheet_belly.to_excel(writer, sheet_name=belly_name, index=False)
        sheet_cheek.to_excel(writer, sheet_name=cheek_name, index=False)

    print(f"Created Excel file: {output_path}")
    print(f"  - Sheet 1 ({sheet_name}): {len(sheet_fronteyes)} rows")
    print(f"  - Sheet 2 ({belly_name}): {len(sheet_belly)} rows")
    print(f"  - Sheet 3 ({cheek_name}): {len(sheet_cheek)} rows")

main

main(config_path: str | None = None)

Main function to create a single Excel file matching CNR's Excel format for both phantoms.

Source code in goliat/analysis/create_excel_for_partners.py
def main(config_path: str | None = None):
    """Main function to create a single Excel file matching CNR's Excel format for both phantoms."""
    # Paths
    # __file__ is in goliat/goliat/analysis/, so we need to go up to goliat/
    base_dir = Path(__file__).parent.parent.parent
    results_dir = base_dir / "results" / "near_field"

    if config_path is None:
        # Check for 26GHz config first as it's the current focus
        potential_configs = [base_dir / "configs" / "near_field_config_26ghz.json", base_dir / "configs" / "near_field_config.json"]
        for cp in potential_configs:
            if cp.exists():
                config_path = str(cp)
                break
        if config_path is None:
            config_path = str(base_dir / "configs" / "near_field_config.json")

    # Read phantom names from config instead of hardcoding
    resolved_config_path = Path(config_path)
    if not resolved_config_path.is_absolute():
        resolved_config_path = base_dir / config_path
    # Try common resolution paths (matching Config._resolve_config_path behavior)
    candidates = [
        resolved_config_path,
        base_dir / "configs" / config_path,
        base_dir / "configs" / f"{config_path}.json",
    ]
    try:
        actual_path = next(c for c in candidates if c.exists())
        with open(actual_path, "r") as f:
            config_data = json.load(f)
        phantoms = config_data.get("phantoms", ["thelonious", "eartha"])
    except (StopIteration, Exception):
        phantoms = ["thelonious", "eartha"]

    # Create a single Excel file with all sheets
    output_path = results_dir / "Final_Data_UGent.xlsx"

    # Get power mapping from config
    power_mapping = get_target_power_mapping(str(config_path))

    # Create Excel writer
    with pd.ExcelWriter(output_path, engine="openpyxl") as writer:
        for phantom_name in phantoms:
            csv_path = results_dir / phantom_name / "normalized_results_detailed.csv"

            if not csv_path.exists():
                logging.getLogger("progress").warning(f"CSV file not found: {csv_path}", extra={"log_type": "warning"})
                continue

            logging.getLogger("progress").info(f"  Processing: {phantom_name.capitalize()}...", extra={"log_type": "progress"})

            # Read CSV data
            df = pd.read_csv(csv_path)

            # Create data for each sheet
            sheet_fronteyes = create_sheet_data(df, "fronteyes", power_mapping)
            sheet_belly = create_sheet_data(df, "belly", power_mapping)
            sheet_cheek = create_sheet_data(df, "cheek", power_mapping)

            # Create sheet names (Excel limits sheet names to 31 characters)
            # Strip frequency/resolution suffixes like _26ghz_coarse for clean tab names
            clean_name = phantom_name.split("_")[0].capitalize()
            sheet_name_fronteyes = f"{clean_name}_fronteyes"[:31]
            sheet_name_belly = f"{clean_name}_belly"[:31]
            sheet_name_cheek = f"{clean_name}_cheek"[:31]

            # Write sheets
            sheet_fronteyes.to_excel(writer, sheet_name=sheet_name_fronteyes, index=False)
            sheet_belly.to_excel(writer, sheet_name=sheet_name_belly, index=False)
            sheet_cheek.to_excel(writer, sheet_name=sheet_name_cheek, index=False)

            # Add table formatting to each sheet
            workbook = writer.book

            # Format fronteyes sheet as table
            if not sheet_fronteyes.empty:
                ws_fronteyes = workbook[sheet_name_fronteyes]
                _add_table_formatting(ws_fronteyes, sheet_fronteyes, sheet_name_fronteyes)
                _auto_size_columns(ws_fronteyes, sheet_fronteyes)

            # Format belly sheet as table
            if not sheet_belly.empty:
                ws_belly = workbook[sheet_name_belly]
                _add_table_formatting(ws_belly, sheet_belly, sheet_name_belly)
                _auto_size_columns(ws_belly, sheet_belly)

            # Format cheek sheet as table
            if not sheet_cheek.empty:
                ws_cheek = workbook[sheet_name_cheek]
                _add_table_formatting(ws_cheek, sheet_cheek, sheet_name_cheek)
                _auto_size_columns(ws_cheek, sheet_cheek)

            logging.getLogger("progress").info(f"    - {sheet_name_fronteyes}: {len(sheet_fronteyes)} rows", extra={"log_type": "verbose"})
            logging.getLogger("progress").info(f"    - {sheet_name_belly}: {len(sheet_belly)} rows", extra={"log_type": "verbose"})
            logging.getLogger("progress").info(f"    - {sheet_name_cheek}: {len(sheet_cheek)} rows", extra={"log_type": "verbose"})

    logging.getLogger("progress").info(f"  Created: {output_path.name}", extra={"log_type": "success"})

Far Field Strategy

goliat.analysis.far_field_strategy.FarFieldAnalysisStrategy

FarFieldAnalysisStrategy(config: Config, phantom_name: str, analysis_config: dict | None = None)

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
def __init__(self, config: "Config", phantom_name: str, analysis_config: dict | None = None):
    """Initializes the far-field analysis strategy.

    Args:
        config: Configuration object.
        phantom_name: Phantom model name being analyzed.
        analysis_config: Optional dictionary with plot names as keys and boolean values.
    """
    super().__init__(config, phantom_name, analysis_config)

Methods:

get_results_base_dir

get_results_base_dir() -> str

Returns base directory for far-field results.

Source code in goliat/analysis/far_field_strategy.py
def get_results_base_dir(self) -> str:
    """Returns base directory for far-field results."""
    return os.path.join(self.base_dir, "results", "far_field", self.phantom_name)

get_plots_dir

get_plots_dir() -> str

Returns directory for far-field plots.

Source code in goliat/analysis/far_field_strategy.py
def get_plots_dir(self) -> str:
    """Returns directory for far-field plots."""
    return os.path.join(self.base_dir, "plots", "far_field", self.phantom_name)

get_expected_item_count

get_expected_item_count() -> int

Returns expected number of progress items for this phantom.

Returns the EXACT count of processing items (result files to be processed). If load_data is False (cache mode), returns 0 since no processing occurs. Plot items are not counted - the GUI handles this via dynamic maximum adjustment.

Returns:

Type Description
int

Exact number of result files that will trigger 'Processing:' log messages.

Source code in goliat/analysis/far_field_strategy.py
def get_expected_item_count(self) -> int:
    """Returns expected number of progress items for this phantom.

    Returns the EXACT count of processing items (result files to be processed).
    If load_data is False (cache mode), returns 0 since no processing occurs.
    Plot items are not counted - the GUI handles this via dynamic maximum adjustment.

    Returns:
        Exact number of result files that will trigger 'Processing:' log messages.
    """
    # If loading from cache, no "Processing:" messages are generated
    if not self.analysis_config.get("load_data", True):
        return 0

    frequencies = self.config["frequencies_mhz"] or []
    far_field_params = self.config["far_field_setup.environmental"] or {}
    incident_directions = far_field_params.get("incident_directions", [])
    polarizations = far_field_params.get("polarizations", [])

    num_frequencies = len(frequencies)
    num_placements = len(incident_directions) * len(polarizations)

    # Exact count: one progress item per result file processed
    return num_frequencies * num_placements

load_and_process_results

load_and_process_results(analyzer: Analyzer)

Iterates through far-field results and processes each one.

Source code in goliat/analysis/far_field_strategy.py
def load_and_process_results(self, analyzer: "Analyzer"):
    """Iterates through far-field results and processes each one."""
    frequencies = self.config["frequencies_mhz"]
    far_field_params = self.config["far_field_setup.environmental"]
    if not far_field_params:
        return
    incident_directions = far_field_params.get("incident_directions", [])
    polarizations = far_field_params.get("polarizations", [])

    if not frequencies:
        return

    for freq in frequencies:
        if not incident_directions:
            continue
        for direction_name in incident_directions:
            if not polarizations:
                continue
            for polarization_name in polarizations:
                placement_name = f"environmental_{direction_name}_{polarization_name}"
                analyzer._process_single_result(freq, "environmental", placement_name, "")

get_normalization_factor

get_normalization_factor(frequency_mhz: int, simulated_power_w: float) -> float

Returns normalization factor for far-field.

Far-field simulations run at E = 1 V/m (power density = 1.326 mW/m²). To normalize to 1 W/m² (our "1 W" convention for comparison with near-field), we scale by 754 (since SAR scales as E², and E for 1 W/m² is 27.46 V/m).

The factor is 1 / (1 / (2 * 376.73)) = 753.46, rounded to 754.

Source code in goliat/analysis/far_field_strategy.py
def get_normalization_factor(self, frequency_mhz: int, simulated_power_w: float) -> float:
    """Returns normalization factor for far-field.

    Far-field simulations run at E = 1 V/m (power density = 1.326 mW/m²).
    To normalize to 1 W/m² (our "1 W" convention for comparison with near-field),
    we scale by 754 (since SAR scales as E², and E for 1 W/m² is 27.46 V/m).

    The factor is 1 / (1 / (2 * 376.73)) = 753.46, rounded to 754.
    """
    return 754.0

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, sapd_results: dict | None = None) -> tuple[dict, list]

Extract and normalize SAR data from pickle file for far-field results.

Source code in goliat/analysis/far_field_strategy.py
def extract_data(
    self,
    pickle_data: dict,
    frequency_mhz: int,
    placement_name: str,
    scenario_name: str,
    sim_power: float,
    norm_factor: float,
    sar_results: dict | None = None,
    sapd_results: dict | None = None,
) -> tuple[dict, list]:
    """Extract and normalize SAR data from pickle file for far-field results."""
    summary_results = pickle_data.get("summary_results", {})
    grouped_stats = pickle_data.get("grouped_sar_stats", {})
    detailed_df = pickle_data.get("detailed_sar_stats")

    result_entry = {
        "frequency_mhz": frequency_mhz,
        "placement": placement_name,
        "scenario": scenario_name,
        "input_power_w": sim_power,
        "SAR_whole_body": summary_results.get("whole_body_sar", pd.NA) * norm_factor
        if pd.notna(summary_results.get("whole_body_sar"))
        else pd.NA,
        "peak_sar": summary_results.get("peak_sar_10g_W_kg", pd.NA) * norm_factor
        if pd.notna(summary_results.get("peak_sar_10g_W_kg"))
        else pd.NA,
    }

    # Extract psSAR10g for each tissue group (brain, eyes, skin, genitals)
    # This mirrors the near-field strategy for symmetry
    for group_name, stats in grouped_stats.items():
        if isinstance(stats, dict):
            key = f"psSAR10g_{group_name.replace('_group', '')}"
            peak_sar = stats.get("peak_sar", pd.NA)
            result_entry[key] = peak_sar * norm_factor if pd.notna(peak_sar) else pd.NA

    # Extract power balance data if available
    power_balance = None
    if sar_results and "power_balance" in sar_results:
        power_balance = sar_results["power_balance"]
    elif summary_results and "power_balance" in summary_results:
        power_balance = summary_results["power_balance"]

    if power_balance:
        result_entry["power_balance_pct"] = power_balance.get("Balance", pd.NA)
        result_entry["power_pin_W"] = power_balance.get("Pin", pd.NA)
        result_entry["power_diel_loss_W"] = power_balance.get("DielLoss", pd.NA)
        result_entry["power_rad_W"] = power_balance.get("RadPower", pd.NA)
        result_entry["power_sibc_loss_W"] = power_balance.get("SIBCLoss", pd.NA)

    organ_entries = []
    if detailed_df is not None:
        peak_sar_col = "Peak Spatial-Average SAR[IEEE/IEC62704-1] (10g)"
        for _, row in detailed_df.iterrows():
            organ_entry = {
                "frequency_mhz": frequency_mhz,
                "placement": placement_name,
                "scenario": scenario_name,  # Added for symmetry with near-field
                "tissue": _clean_tissue_name(row["Tissue"]),  # Clean tissue name early
                "mass_avg_sar_mw_kg": row["Mass-Averaged SAR"] * norm_factor * 1000,
                "peak_sar_10g_mw_kg": row.get(peak_sar_col, pd.NA) * norm_factor * 1000 if pd.notna(row.get(peak_sar_col)) else pd.NA,
                "min_local_sar_mw_kg": row.get("Min. local SAR", pd.NA) * norm_factor * 1000
                if pd.notna(row.get("Min. local SAR", pd.NA))
                else pd.NA,
                "max_local_sar_mw_kg": row.get("Max. local SAR", pd.NA) * norm_factor * 1000
                if pd.notna(row.get("Max. local SAR", pd.NA))
                else pd.NA,
            }
            # Add Total Mass, Total Volume, Total Loss, Max Loss Power Density if available
            # (symmetric with near-field strategy)
            if "Total Mass" in row.index:
                organ_entry["Total Mass"] = row["Total Mass"]
            if "Total Volume" in row.index:
                organ_entry["Total Volume"] = row["Total Volume"]
            if "Total Loss" in row.index:
                organ_entry["Total Loss"] = row["Total Loss"]
            if "Max Loss Power Density" in row.index:
                organ_entry["Max Loss Power Density"] = row["Max Loss Power Density"]
            # Add psSAR10g column name for compatibility (symmetric with near-field)
            if peak_sar_col in row.index and pd.notna(row[peak_sar_col]):
                organ_entry["psSAR10g"] = row[peak_sar_col] * norm_factor * 1000
            organ_entries.append(organ_entry)
    return result_entry, organ_entries

apply_bug_fixes

apply_bug_fixes(result_entry: dict) -> dict

No bug fixes needed for far-field data.

Source code in goliat/analysis/far_field_strategy.py
def apply_bug_fixes(self, result_entry: dict) -> dict:
    """No bug fixes needed for far-field data."""
    return result_entry

calculate_summary_stats

calculate_summary_stats(results_df: DataFrame) -> pd.DataFrame

Calculates summary statistics for far-field results.

Source code in goliat/analysis/far_field_strategy.py
def calculate_summary_stats(self, results_df: pd.DataFrame) -> pd.DataFrame:
    """Calculates summary statistics for far-field results."""
    summary = results_df.groupby("frequency_mhz").mean(numeric_only=True)
    return pd.DataFrame(summary)

generate_plots

generate_plots(analyzer: Analyzer, plotter: Plotter, results_df: DataFrame, all_organ_results_df: DataFrame)

Generates all plots for far-field analysis.

Includes bar charts, line plots, boxplots, heatmaps, ranking plots, CDF plots, correlation matrices, bubble plots, and tissue analysis.

Source code in goliat/analysis/far_field_strategy.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
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
def generate_plots(
    self,
    analyzer: "Analyzer",
    plotter: "Plotter",
    results_df: pd.DataFrame,
    all_organ_results_df: pd.DataFrame,
):
    """Generates all plots for far-field analysis.

    Includes bar charts, line plots, boxplots, heatmaps, ranking plots,
    CDF plots, correlation matrices, bubble plots, and tissue analysis.
    """
    logging.getLogger("progress").info(
        "\n--- Generating plots for far-field analysis ---",
        extra={"log_type": "header"},
    )

    # Add tissue group SAR columns to results_df
    results_df = self._add_tissue_group_sar(results_df, all_organ_results_df, analyzer)

    summary_stats = self.calculate_summary_stats(results_df)

    # ============================================================================
    # Basic Bar and Line Plots
    # ============================================================================
    if self.should_generate_plot("plot_whole_body_sar_bar"):
        plotter.plot_whole_body_sar_bar(summary_stats)
    if self.should_generate_plot("plot_peak_sar_line"):
        plotter.plot_peak_sar_line(summary_stats)
    if self.should_generate_plot("plot_far_field_distribution_boxplot"):
        plotter.plot_sar_distribution_boxplot_single(results_df, metric="SAR_whole_body")
        plotter.plot_sar_distribution_boxplot_single(results_df, metric="peak_sar")
        # Also generate boxplots for tissue groups (symmetric with near-field)
        for metric in ["SAR_brain", "SAR_eyes", "SAR_skin", "SAR_genitals"]:
            if metric in results_df.columns and results_df[metric].notna().any():
                plotter.plot_sar_distribution_boxplot_single(results_df, metric=metric)
        # Generate boxplots for psSAR10g metrics (symmetric with near-field)
        pssar_columns = [col for col in results_df.columns if col.startswith("psSAR10g")]
        for metric in pssar_columns:
            if results_df[metric].notna().any():
                plotter.plot_sar_distribution_boxplot_single(results_df, metric=metric)

    # Tissue group bar plots (symmetric with near-field: brain, eyes, skin, genitals)
    if self.should_generate_plot("plot_average_sar_bar"):
        plotter.plot_average_sar_bar("environmental", summary_stats, None, results_df)
    if self.should_generate_plot("plot_average_pssar_bar"):
        plotter.plot_average_pssar_bar("environmental", summary_stats, None, results_df)

    # ============================================================================
    # Far-field Direction vs Polarization Comparison (unique to far-field)
    # ============================================================================
    if self.should_generate_plot("plot_far_field_direction_polarization_summary"):
        logging.getLogger("progress").info(
            "  - Generating direction/polarization comparison heatmaps (frequency-averaged)...",
            extra={"log_type": "info"},
        )
        plotter.plot_far_field_direction_polarization_summary(results_df)

    # Frequency-dependent line plots for direction/polarization comparison
    if self.should_generate_plot("plot_far_field_direction_polarization_comparison"):
        logging.getLogger("progress").info(
            "  - Generating direction/polarization frequency-dependence comparison plots...",
            extra={"log_type": "info"},
        )
        plotter.plot_far_field_direction_polarization_comparison(results_df)

    # ============================================================================
    # Polarization Ratio Analysis (unique to far-field)
    # ============================================================================
    if self.should_generate_plot("plot_polarization_ratio"):
        logging.getLogger("progress").info(
            "  - Generating polarization ratio analysis plots...",
            extra={"log_type": "info"},
        )
        # Line plot: ratio vs frequency per direction (shows frequency evolution)
        plotter.plot_polarization_ratio_lines(results_df)
        # Frequency-averaged heatmap (quick overview)
        plotter.plot_polarization_ratio_heatmap(results_df)
        # Per-frequency heatmaps disabled due to memory concerns (9 figs per phantom)
        # plotter.plot_polarization_ratio_heatmaps_per_frequency(results_df)

    # ============================================================================
    # Individual Variation Line Plots (one line per direction/polarization)
    # ============================================================================
    sar_columns_for_lines = ["SAR_whole_body", "SAR_brain", "SAR_skin", "SAR_eyes", "SAR_genitals"]
    if self.should_generate_plot("plot_sar_line_individual_variations"):
        for metric_col in sar_columns_for_lines:
            if metric_col in results_df.columns and results_df[metric_col].notna().any():
                plotter.plot_sar_line_individual_variations(
                    results_df,
                    scenario_name=None,  # No scenario for far-field
                    metric_column=metric_col,
                )

    # psSAR10g individual variation plots for tissue groups (symmetric with near-field)
    pssar_columns = [col for col in results_df.columns if col.startswith("psSAR10g")]
    if self.should_generate_plot("plot_pssar_line_individual_variations"):
        for metric_col in pssar_columns:
            if metric_col in results_df.columns and results_df[metric_col].notna().any():
                plotter.plot_pssar_line_individual_variations(
                    results_df,
                    scenario_name=None,
                    metric_column=metric_col,
                )

    # ============================================================================
    # Heatmaps
    # ============================================================================
    # Check if required columns exist for full Min/Avg/Max heatmap (symmetric with NF)
    required_cols = ["min_local_sar_mw_kg", "mass_avg_sar_mw_kg", "max_local_sar_mw_kg"]
    missing_cols = [col for col in required_cols if col not in all_organ_results_df.columns]

    if missing_cols:
        logging.getLogger("progress").warning(
            f"  - WARNING: Missing columns for full SAR heatmap: {missing_cols}. Using available columns.",
            extra={"log_type": "warning"},
        )
        # Fallback: only use avg_sar if min/max not available
        organ_sar_df = (
            all_organ_results_df.groupby(["tissue", "frequency_mhz"]).agg(avg_sar=("mass_avg_sar_mw_kg", "mean")).reset_index()
        )
    else:
        # Full aggregation with min/avg/max (symmetric with NF)
        organ_sar_df = (
            all_organ_results_df.groupby(["tissue", "frequency_mhz"])
            .agg(
                min_sar=("min_local_sar_mw_kg", "mean"),
                avg_sar=("mass_avg_sar_mw_kg", "mean"),
                max_sar=("max_local_sar_mw_kg", "mean"),
            )
            .reset_index()
        )
        # Drop rows where all SAR values are NA
        organ_sar_df = organ_sar_df.dropna(subset=["min_sar", "avg_sar", "max_sar"], how="all")

    organ_pssar_df = all_organ_results_df.groupby(["tissue", "frequency_mhz"])["peak_sar_10g_mw_kg"].mean().reset_index()

    group_summary_data = []
    if analyzer.tissue_group_composition:
        tissue_groups = {group_name: list(tissues) for group_name, tissues in analyzer.tissue_group_composition.items()}

        for group_name, tissues in tissue_groups.items():
            if not tissues:
                continue
            group_df = all_organ_results_df[all_organ_results_df["tissue"].isin(tissues)]
            if not group_df.empty:
                summary = (
                    group_df.groupby("frequency_mhz")
                    .agg(
                        avg_sar=("mass_avg_sar_mw_kg", "mean"),
                        peak_sar_10g_mw_kg=("peak_sar_10g_mw_kg", "mean"),
                    )
                    .reset_index()
                )
                summary["group"] = group_name.replace("_group", "").capitalize()
                group_summary_data.append(summary)

        group_summary_df = pd.concat(group_summary_data, ignore_index=True) if group_summary_data else pd.DataFrame()

        if not group_summary_df.empty:
            plotter_tissue_groups = {group_name: list(tissues) for group_name, tissues in analyzer.tissue_group_composition.items()}

            if self.should_generate_plot("plot_peak_sar_heatmap"):
                plotter.plot_peak_sar_heatmap(
                    pd.DataFrame(organ_sar_df),
                    group_summary_df[["group", "frequency_mhz", "avg_sar"]],
                    plotter_tissue_groups,
                    value_col="avg_sar",
                    title="Average SAR",
                )
                plotter.plot_peak_sar_heatmap(
                    pd.DataFrame(organ_pssar_df),
                    group_summary_df[["group", "frequency_mhz", "peak_sar_10g_mw_kg"]],
                    plotter_tissue_groups,
                    value_col="peak_sar_10g_mw_kg",
                    title="Peak SAR 10g",
                )
            # SAR heatmap (symmetric with NF)
            if self.should_generate_plot("plot_sar_heatmap"):
                plotter.plot_sar_heatmap(
                    pd.DataFrame(organ_sar_df),
                    group_summary_df[["group", "frequency_mhz", "avg_sar"]],
                    plotter_tissue_groups,
                )

    # ============================================================================
    # SAR/psSAR Line Plots (symmetric with NF)
    # ============================================================================
    if self.should_generate_plot("plot_sar_line"):
        plotter.plot_sar_line("environmental", summary_stats)
    if self.should_generate_plot("plot_pssar_line"):
        plotter.plot_pssar_line("environmental", summary_stats)

    # ============================================================================
    # SAR Distribution Boxplots (symmetric with NF)
    # ============================================================================
    if self.should_generate_plot("plot_sar_distribution_boxplots"):
        plotter.plot_sar_distribution_boxplots("environmental", results_df)

    # ============================================================================
    # Power Balance Plots
    # ============================================================================
    if self.should_generate_plot("plot_power_balance_overview"):
        plotter.plot_power_balance_overview(results_df)
    if self.should_generate_plot("plot_power_efficiency_trends"):
        plotter.plot_power_efficiency_trends(results_df, scenario_name=None)
    if not all_organ_results_df.empty and self.should_generate_plot("plot_power_absorption_distribution"):
        if "Total Loss" in all_organ_results_df.columns:
            plotter.plot_power_absorption_distribution(all_organ_results_df, scenario_name=None)
        else:
            logging.getLogger("progress").warning(
                "  - WARNING: No 'Total Loss' data available for power absorption plot.",
                extra={"log_type": "warning"},
            )

    # ============================================================================
    # Ranking Plots (Top 20 Tissues)
    # ============================================================================
    if not all_organ_results_df.empty and self.should_generate_plot("plot_top20_tissues_ranking"):
        logging.getLogger("progress").info(
            "  - Generating ranking plots (top 20 tissues)...",
            extra={"log_type": "info"},
        )
        # Top 20 by Max Local SAR (symmetric with near-field - same order as NF)
        if "max_local_sar_mw_kg" in all_organ_results_df.columns:
            plotter.plot_top20_tissues_ranking(all_organ_results_df, metric="max_local_sar_mw_kg", scenario_name=None)
        # Top 20 by Mass-Averaged SAR
        plotter.plot_top20_tissues_ranking(all_organ_results_df, metric="mass_avg_sar_mw_kg", scenario_name=None)
        # Top 20 by Peak SAR 10g (far-field specific - peak_sar is the same as psSAR10g whole body)
        if "peak_sar_10g_mw_kg" in all_organ_results_df.columns:
            plotter.plot_top20_tissues_ranking(all_organ_results_df, metric="peak_sar_10g_mw_kg", scenario_name=None)
        # Top 20 by Total Loss (symmetric with near-field)
        if "Total Loss" in all_organ_results_df.columns:
            plotter.plot_top20_tissues_ranking(all_organ_results_df, metric="Total Loss", scenario_name=None)

    # ============================================================================
    # CDF Plots
    # ============================================================================
    if self.should_generate_plot("plot_cdf"):
        logging.getLogger("progress").info(
            "  - Generating CDF plots...",
            extra={"log_type": "info"},
        )
        # Include both SAR and psSAR10g metrics for symmetry with near-field
        sar_metrics = [col for col in results_df.columns if col.startswith("SAR_")]
        pssar_metrics = [col for col in results_df.columns if col.startswith("psSAR10g")]
        cdf_metrics = sar_metrics + pssar_metrics + (["peak_sar"] if "peak_sar" in results_df.columns else [])
        for metric in cdf_metrics:
            if metric in results_df.columns and results_df[metric].notna().any():
                # CDF grouped by frequency (symmetric with near-field per-scenario CDFs)
                plotter.plot_cdf(results_df, metric, group_by="frequency_mhz", scenario_name=None)

        # Parse direction and polarization from placement for CDF grouping
        # Add direction/polarization columns if not present
        if "direction" not in results_df.columns or "polarization" not in results_df.columns:

            def parse_placement(placement: str) -> tuple:
                direction_labels = {
                    "x_pos": "From left",
                    "x_neg": "From right",
                    "y_pos": "From back",
                    "y_neg": "From front",
                    "z_pos": "From below",
                    "z_neg": "From above",
                }
                parts = placement.replace("environmental_", "").split("_")
                if len(parts) >= 3:
                    dir_key = f"{parts[0]}_{parts[1]}"
                    direction = direction_labels.get(dir_key, f"{parts[0]}{parts[1]}")
                    pol = "Theta" if parts[2] == "theta" else "Phi"
                    return direction, pol
                return placement, "Unknown"

            results_df[["direction", "polarization"]] = results_df["placement"].apply(lambda x: pd.Series(parse_placement(x)))

        # CDF grouped by direction (analogous to near-field per-scenario CDFs)
        for metric in cdf_metrics:
            if metric in results_df.columns and results_df[metric].notna().any():
                plotter.plot_cdf(results_df, metric, group_by="direction", scenario_name=None)

        # CDF grouped by polarization
        for metric in cdf_metrics:
            if metric in results_df.columns and results_df[metric].notna().any():
                plotter.plot_cdf(results_df, metric, group_by="polarization", scenario_name=None)

    # ============================================================================
    # Correlation Plots
    # ============================================================================
    if self.should_generate_plot("plot_tissue_group_correlation_matrix"):
        logging.getLogger("progress").info(
            "  - Generating correlation matrix...",
            extra={"log_type": "info"},
        )
        plotter.plot_tissue_group_correlation_matrix(results_df, scenario_name=None)

    # ============================================================================
    # Bubble Plots (Mass vs SAR)
    # ============================================================================
    if not all_organ_results_df.empty and self.should_generate_plot("plot_bubble_mass_vs_sar"):
        if "Total Mass" in all_organ_results_df.columns:
            logging.getLogger("progress").info(
                "  - Generating bubble plots (mass vs SAR)...",
                extra={"log_type": "info"},
            )
            # Get unique frequencies for frequency-specific plots (symmetric with near-field)
            frequencies = (
                sorted(all_organ_results_df["frequency_mhz"].dropna().unique())
                if "frequency_mhz" in all_organ_results_df.columns
                else []
            )

            # SAR columns to plot
            sar_columns = ["mass_avg_sar_mw_kg"]
            if "peak_sar_10g_mw_kg" in all_organ_results_df.columns:
                sar_columns.append("peak_sar_10g_mw_kg")
            if "max_local_sar_mw_kg" in all_organ_results_df.columns:
                sar_columns.append("max_local_sar_mw_kg")

            for sar_col in sar_columns:
                # All frequencies combined
                plotter.plot_bubble_mass_vs_sar(all_organ_results_df, sar_column=sar_col, scenario_name=None)

                # Per-frequency variants (symmetric with near-field)
                for freq in frequencies:
                    plotter.plot_bubble_mass_vs_sar(
                        all_organ_results_df,
                        sar_column=sar_col,
                        scenario_name=None,
                        frequency_mhz=freq,
                    )

    # Interactive bubble plots (symmetric with NF)
    if not all_organ_results_df.empty and self.should_generate_plot("plot_bubble_mass_vs_sar_interactive"):
        if "Total Mass" in all_organ_results_df.columns:
            plotter.plot_bubble_mass_vs_sar_interactive(all_organ_results_df, sar_column="mass_avg_sar_mw_kg", scenario_name=None)

    # ============================================================================
    # Penetration Depth Ratio (symmetric with NF)
    # ============================================================================
    if self.should_generate_plot("plot_penetration_depth_ratio"):
        # Pre-check columns for psSAR10g penetration ratio (symmetric with near-field)
        if "psSAR10g_brain" in results_df.columns and "psSAR10g_skin" in results_df.columns:
            plotter.plot_penetration_depth_ratio(results_df, scenario_name=None, metric_type="psSAR10g")
        # Pre-check columns for SAR penetration ratio (symmetric with near-field)
        if "SAR_brain" in results_df.columns and "SAR_skin" in results_df.columns:
            plotter.plot_penetration_depth_ratio(results_df, scenario_name=None, metric_type="SAR")

    # ============================================================================
    # Max Local vs psSAR Scatter (symmetric with NF)
    # ============================================================================
    if not all_organ_results_df.empty and self.should_generate_plot("plot_max_local_vs_pssar10g_scatter"):
        if "max_local_sar_mw_kg" in all_organ_results_df.columns:
            plotter.plot_max_local_vs_pssar10g_scatter(all_organ_results_df, scenario_name=None)
        else:
            logging.getLogger("progress").warning(
                "  - WARNING: Missing 'max_local_sar_mw_kg' column for Max Local vs psSAR10g scatter plot.",
                extra={"log_type": "warning"},
            )

    # ============================================================================
    # Tissue Analysis Plots
    # ============================================================================
    if not all_organ_results_df.empty:
        # Tissue frequency response for top tissues
        if self.should_generate_plot("plot_tissue_frequency_response") and "mass_avg_sar_mw_kg" in all_organ_results_df.columns:
            logging.getLogger("progress").info(
                "  - Generating tissue frequency response plots...",
                extra={"log_type": "info"},
            )
            filtered_organs = all_organ_results_df[all_organ_results_df["tissue"] != "All Regions"]
            top_tissues = filtered_organs.groupby("tissue")["mass_avg_sar_mw_kg"].mean().nlargest(10).index.tolist()
            for tissue in top_tissues:
                plotter.plot_tissue_frequency_response(all_organ_results_df, tissue_name=tissue, scenario_name=None)
        # Tissue mass/volume distribution (symmetric with NF)
        if self.should_generate_plot("plot_tissue_mass_volume_distribution"):
            plotter.plot_tissue_mass_volume_distribution(all_organ_results_df, scenario_name=None)

    # ============================================================================
    # Spatial Plots (3D and 2D Peak Locations) - Symmetric with near-field
    # ============================================================================
    # Collect peak location data from all results (same as near-field)
    peak_location_data = []
    for result in analyzer.all_results:
        if "peak_sar_details" in result:
            peak_details = result["peak_sar_details"]
            if peak_details and isinstance(peak_details, dict):
                peak_location_data.append(
                    {
                        "PeakLocation": peak_details.get("PeakLocation", None),
                        "PeakCubeSideLength": peak_details.get("PeakCubeSideLength", None),
                        "PeakValue": peak_details.get("PeakValue", None),
                        "PeakCell": peak_details.get("PeakCell", None),
                        "placement": result.get("placement", ""),
                        "frequency_mhz": result.get("frequency_mhz", None),
                        "scenario": result.get("scenario", "environmental"),
                    }
                )

    peak_location_df = pd.DataFrame(peak_location_data) if peak_location_data else pd.DataFrame()

    if not peak_location_df.empty:
        if self.should_generate_plot("plot_peak_location_3d_interactive") or self.should_generate_plot(
            "plot_peak_location_2d_projections"
        ):
            logging.getLogger("progress").info(
                "  - Generating spatial plots (3D and 2D peak locations)...",
                extra={"log_type": "info"},
            )

            # Calculate consistent axis limits from all data
            axis_limits = plotter.spatial._calculate_axis_limits(peak_location_df)

            if self.should_generate_plot("plot_peak_location_3d_interactive"):
                plotter.plot_peak_location_3d_interactive(peak_location_df, scenario_name=None, axis_limits=axis_limits)

            if self.should_generate_plot("plot_peak_location_2d_projections"):
                plotter.plot_peak_location_2d_projections(peak_location_df, scenario_name=None)

    # ============================================================================
    # Outlier Identification
    # ============================================================================
    if self.should_generate_plot("identify_outliers"):
        logging.getLogger("progress").info(
            "  - Identifying outliers...",
            extra={"log_type": "info"},
        )
        # Include both psSAR10g and SAR metrics for symmetry with near-field (psSAR10g first like NF)
        pssar_outlier_metrics = [
            "psSAR10g_brain",
            "psSAR10g_eyes",
            "psSAR10g_skin",
            "psSAR10g_genitals",
            "psSAR10g_whole_body",  # Added for symmetry with near-field
        ]
        sar_outlier_metrics = [
            "SAR_whole_body",
            "peak_sar",  # Far-field specific
            "SAR_brain",
            "SAR_skin",
            "SAR_eyes",
            "SAR_genitals",
        ]
        outlier_metrics = pssar_outlier_metrics + sar_outlier_metrics  # psSAR10g first like near-field
        for metric in outlier_metrics:
            if metric in results_df.columns and results_df[metric].notna().any():
                outliers = plotter.identify_outliers(results_df, metric, scenario_name=None)
                # Save CSV and log count (symmetric with near-field)
                if outliers is not None and not outliers.empty:
                    subdir = plotter._get_subdir("outliers")
                    filename = f"outliers_{metric}.csv"
                    outliers.to_csv(os.path.join(subdir, filename), index=False)
                    logging.getLogger("progress").info(
                        f"    - Found {len(outliers)} outliers for {metric}",
                        extra={"log_type": "info"},
                    )

Near Field Strategy

goliat.analysis.near_field_strategy.NearFieldAnalysisStrategy

NearFieldAnalysisStrategy(config: Config, phantom_name: str, analysis_config: dict | None = None)

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
def __init__(self, config: "Config", phantom_name: str, analysis_config: dict | None = None):
    """Initializes the near-field analysis strategy.

    Args:
        config: Configuration object.
        phantom_name: Phantom model name being analyzed.
        analysis_config: Optional dictionary with plot names as keys and boolean values.
    """
    super().__init__(config, phantom_name, analysis_config)

Methods:

get_results_base_dir

get_results_base_dir() -> str

Returns base directory for near-field results.

Source code in goliat/analysis/near_field_strategy.py
def get_results_base_dir(self) -> str:
    """Returns base directory for near-field results."""
    return os.path.join(self.base_dir, "results", "near_field", self.phantom_name)

get_plots_dir

get_plots_dir() -> str

Returns directory for near-field plots.

Source code in goliat/analysis/near_field_strategy.py
def get_plots_dir(self) -> str:
    """Returns directory for near-field plots."""
    return os.path.join(self.base_dir, "plots", "near_field", self.phantom_name)

get_expected_item_count

get_expected_item_count() -> int

Returns expected number of progress items for this phantom.

Returns the EXACT count of processing items (result files to be processed). If load_data is False (cache mode), returns 0 since no processing occurs. Plot items are not counted - the GUI handles this via dynamic maximum adjustment.

Returns:

Type Description
int

Exact number of result files that will trigger 'Processing:' log messages.

Source code in goliat/analysis/near_field_strategy.py
def get_expected_item_count(self) -> int:
    """Returns expected number of progress items for this phantom.

    Returns the EXACT count of processing items (result files to be processed).
    If load_data is False (cache mode), returns 0 since no processing occurs.
    Plot items are not counted - the GUI handles this via dynamic maximum adjustment.

    Returns:
        Exact number of result files that will trigger 'Processing:' log messages.
    """
    # If loading from cache, no "Processing:" messages are generated
    if not self.analysis_config.get("load_data", True):
        return 0

    antenna_config = self.config["antenna_config"] or {}
    placement_scenarios = self.config["placement_scenarios"] or {}

    num_frequencies = len(antenna_config)
    num_placements = 0
    for scenario_def in placement_scenarios.values():
        if scenario_def:
            positions = scenario_def.get("positions", {})
            orientations = scenario_def.get("orientations", {})
            num_placements += len(positions) * max(len(orientations), 1)

    # Exact count: one progress item per result file processed
    return num_frequencies * num_placements

load_and_process_results

load_and_process_results(analyzer: Analyzer)

Iterates through near-field results and processes each one.

Source code in goliat/analysis/near_field_strategy.py
def load_and_process_results(self, analyzer: "Analyzer"):
    """Iterates through near-field results and processes each one."""
    antenna_config = self.config["antenna_config"] or {}
    if not antenna_config:
        return
    frequencies = antenna_config.keys()
    placement_scenarios = self.config["placement_scenarios"]
    if not placement_scenarios:
        return

    for freq in frequencies:
        frequency_mhz = int(freq)
        for scenario_name, scenario_def in placement_scenarios.items():
            if not scenario_def:
                continue
            positions = scenario_def.get("positions", {})
            orientations = scenario_def.get("orientations", {})
            if not positions or not orientations:
                continue
            for pos_name in positions.keys():
                for orient_name in orientations.keys():
                    analyzer._process_single_result(frequency_mhz, scenario_name, pos_name, orient_name)

get_normalization_factor

get_normalization_factor(frequency_mhz: int, simulated_power_w: float) -> float

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
def get_normalization_factor(self, frequency_mhz: int, simulated_power_w: float) -> float:
    """Calculates the normalization factor based on the target power.

    Args:
        frequency_mhz: The simulation frequency in MHz.
        simulated_power_w: The input power from the simulation in Watts.

    Returns:
        The calculated normalization factor, or 1.0 if not possible.
    """
    antenna_configs = self.config["antenna_config"] or {}
    freq_config = antenna_configs.get(str(frequency_mhz), {})
    target_power_mw = freq_config.get("target_power_mW")
    if target_power_mw is not None and pd.notna(simulated_power_w) and simulated_power_w > 0:
        target_power_w = target_power_mw / 1000.0
        return target_power_w / simulated_power_w
    return 1.0

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, sapd_results: dict | None = None) -> tuple[dict, list]

Extracts and normalizes SAR and SAPD 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
sapd_results dict | None

Optional SAPD JSON results dict (present when sapd=true in config).

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
def extract_data(
    self,
    pickle_data: dict,
    frequency_mhz: int,
    placement_name: str,
    scenario_name: str,
    sim_power: float,
    norm_factor: float,
    sar_results: dict | None = None,
    sapd_results: dict | None = None,
) -> tuple[dict, list]:
    """Extracts and normalizes SAR and SAPD data from a single near-field result.

    Args:
        pickle_data: Data loaded from the .pkl result file.
        frequency_mhz: The simulation frequency.
        placement_name: The detailed name of the placement.
        scenario_name: The general scenario name (e.g., 'by_cheek').
        sim_power: The simulated input power in Watts.
        norm_factor: The normalization factor to apply to SAR values.
        sar_results: Optional JSON results dict containing power balance data.
        sapd_results: Optional SAPD JSON results dict (present when sapd=true in config).

    Returns:
        A tuple containing the main result entry and a list of organ-specific entries.
    """
    summary_results = pickle_data.get("summary_results", {})
    grouped_stats = pickle_data.get("grouped_sar_stats", {})
    detailed_df = pickle_data.get("detailed_sar_stats")

    # Check bounding_box setting from config to determine which SAR fields are valid
    placement_scenarios = self.config["placement_scenarios"] or {}
    scenario_config = placement_scenarios.get(scenario_name, {}) if isinstance(placement_scenarios, dict) else {}
    bounding_box_setting = scenario_config.get("bounding_box", "default")

    # Extract SAR values - prioritize JSON over pickle, and respect bounding_box setting
    sar_head = pd.NA
    sar_trunk = pd.NA
    sar_whole_body = pd.NA

    # If whole_body bounding box, only use whole_body_sar (ignore head/trunk from old pickle files)
    if bounding_box_setting == "whole_body":
        # Prefer JSON, fallback to pickle
        sar_whole_body = sar_results.get("whole_body_sar", pd.NA) if sar_results else pd.NA
        if pd.isna(sar_whole_body):
            sar_whole_body = summary_results.get("whole_body_sar", pd.NA)
    else:
        # For head/trunk/default bounding boxes, extract head/trunk SAR
        # Prefer JSON, fallback to pickle
        if sar_results:
            sar_head = sar_results.get("head_SAR", pd.NA)
            sar_trunk = sar_results.get("trunk_SAR", pd.NA)
        if pd.isna(sar_head):
            sar_head = summary_results.get("head_SAR", pd.NA)
        if pd.isna(sar_trunk):
            sar_trunk = summary_results.get("trunk_SAR", pd.NA)

        # Also check for whole_body_sar (might exist from old data)
        if sar_results:
            sar_whole_body = sar_results.get("whole_body_sar", pd.NA)
        if pd.isna(sar_whole_body):
            sar_whole_body = summary_results.get("whole_body_sar", pd.NA)

    result_entry = {
        "frequency_mhz": frequency_mhz,
        "placement": placement_name,
        "scenario": scenario_name,
        "input_power_w": sim_power,
        "SAR_head": sar_head * norm_factor if pd.notna(sar_head) else pd.NA,
        "SAR_trunk": sar_trunk * norm_factor if pd.notna(sar_trunk) else pd.NA,
        "SAR_whole_body": sar_whole_body * norm_factor if pd.notna(sar_whole_body) else pd.NA,
    }
    for group_name, stats in grouped_stats.items():
        key = f"psSAR10g_{group_name.replace('_group', '')}"
        result_entry[key] = stats.get("peak_sar", pd.NA) * norm_factor

    # Include SAPD data if available (not scaled by norm_factor — already at target power;
    # however, like SAR we apply norm_factor since SAPD scales linearly with power)
    if sapd_results is not None:
        raw_sapd = sapd_results.get("peak_sapd_W_m2", pd.NA)
        result_entry["peak_sapd_W_m2"] = raw_sapd * norm_factor if pd.notna(raw_sapd) else pd.NA
        result_entry["peak_sapd_location_m"] = sapd_results.get("peak_sapd_location_m", pd.NA)
    else:
        result_entry["peak_sapd_W_m2"] = pd.NA
        result_entry["peak_sapd_location_m"] = pd.NA

    # Extract power balance data if available
    power_balance = None
    if sar_results and "power_balance" in sar_results:
        power_balance = sar_results["power_balance"]
    elif summary_results and "power_balance" in summary_results:
        power_balance = summary_results["power_balance"]

    if power_balance:
        result_entry["power_balance_pct"] = power_balance.get("Balance", pd.NA)
        result_entry["power_pin_W"] = power_balance.get("Pin", pd.NA)
        result_entry["power_diel_loss_W"] = power_balance.get("DielLoss", pd.NA)
        result_entry["power_rad_W"] = power_balance.get("RadPower", pd.NA)
        result_entry["power_sibc_loss_W"] = power_balance.get("SIBCLoss", pd.NA)

    organ_entries = []
    if detailed_df is not None:
        peak_sar_col = "Peak Spatial-Average SAR[IEEE/IEC62704-1] (10g)"
        for _, row in detailed_df.iterrows():
            organ_entry = {
                "frequency_mhz": frequency_mhz,
                "placement": placement_name,
                "scenario": scenario_name,
                "tissue": _clean_tissue_name(row["Tissue"]),  # Clean tissue name early
                "mass_avg_sar_mw_kg": row["Mass-Averaged SAR"] * norm_factor * 1000,
                "peak_sar_10g_mw_kg": row.get(peak_sar_col, pd.NA) * norm_factor * 1000
                if pd.notna(row.get(peak_sar_col, pd.NA))
                else pd.NA,
                "min_local_sar_mw_kg": row.get("Min. local SAR", pd.NA) * norm_factor * 1000
                if pd.notna(row.get("Min. local SAR", pd.NA))
                else pd.NA,
                "max_local_sar_mw_kg": row.get("Max. local SAR", pd.NA) * norm_factor * 1000
                if pd.notna(row.get("Max. local SAR", pd.NA))
                else pd.NA,
            }
            # Add Total Mass, Total Volume, Total Loss, Max Loss Power Density if available
            if "Total Mass" in row.index:
                organ_entry["Total Mass"] = row["Total Mass"]
            if "Total Volume" in row.index:
                organ_entry["Total Volume"] = row["Total Volume"]
            if "Total Loss" in row.index:
                organ_entry["Total Loss"] = row["Total Loss"]
            if "Max Loss Power Density" in row.index:
                organ_entry["Max Loss Power Density"] = row["Max Loss Power Density"]
            # Add psSAR10g column name for compatibility
            if peak_sar_col in row.index and pd.notna(row[peak_sar_col]):
                organ_entry["psSAR10g"] = row[peak_sar_col] * norm_factor * 1000
            organ_entries.append(organ_entry)
    return result_entry, organ_entries

apply_bug_fixes

apply_bug_fixes(result_entry: dict) -> dict

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
def apply_bug_fixes(self, result_entry: dict) -> dict:
    """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.

    Args:
        result_entry: The data entry for a single simulation result.

    Returns:
        The corrected result entry.
    """
    # Skip bug fix if whole_body_sar is present (indicates whole_body bounding box)
    if pd.notna(result_entry.get("SAR_whole_body")):
        # For whole_body scenarios, ensure head/trunk are NA
        result_entry["SAR_head"] = pd.NA
        result_entry["SAR_trunk"] = pd.NA
        return result_entry

    # Original bug fix logic for head/trunk bounding boxes
    placement = result_entry.get("placement", "").lower()
    if placement.startswith("front_of_eyes") or placement.startswith("by_cheek"):
        sar_head = result_entry.get("SAR_head")
        sar_trunk = result_entry.get("SAR_trunk")
        if bool(pd.isna(sar_head)) and bool(pd.notna(sar_trunk)):
            result_entry["SAR_head"] = sar_trunk
            result_entry["SAR_trunk"] = pd.NA
    return result_entry

calculate_summary_stats

calculate_summary_stats(results_df: DataFrame) -> pd.DataFrame

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
def calculate_summary_stats(self, results_df: pd.DataFrame) -> pd.DataFrame:
    """Calculates summary statistics, including completion progress.

    Args:
        results_df: DataFrame with all aggregated simulation results.

    Returns:
        A DataFrame with mean SAR values and a 'progress' column.
    """
    placement_scenarios = self.config["placement_scenarios"]
    placements_per_scenario = {}
    logging.getLogger("progress").info(
        "\n--- Calculating Total Possible Placements per Scenario ---",
        extra={"log_type": "header"},
    )
    if placement_scenarios:
        for name, definition in placement_scenarios.items():
            if not definition:
                continue
            total = len(definition.get("positions", {})) * len(definition.get("orientations", {}))
            placements_per_scenario[name] = total
            logging.getLogger("progress").info(f"- Scenario '{name}': {total} placements", extra={"log_type": "info"})

    summary_stats = results_df.groupby(["scenario", "frequency_mhz"]).mean(numeric_only=True)
    completion_counts = results_df.groupby(["scenario", "frequency_mhz"]).size()

    # Define a mapping function that safely handles potential missing keys
    def get_progress(idx):
        """Return 'completed/total' string for a (scenario, freq) index."""
        # Index is a tuple (scenario, frequency)
        if isinstance(idx, tuple) and len(idx) == 2:
            scenario_name, _ = idx
        else:
            scenario_name = idx
        completed = completion_counts.get(idx, 0)
        total = placements_per_scenario.get(scenario_name, 0)
        return f"{completed}/{total}"

    if not summary_stats.empty:
        summary_stats["progress"] = summary_stats.index.map(get_progress)  # type: ignore
    return pd.DataFrame(summary_stats)

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
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
def generate_plots(
    self,
    analyzer: "Analyzer",
    plotter: "Plotter",
    results_df: pd.DataFrame,
    all_organ_results_df: pd.DataFrame,
):
    """Generates all plots for the near-field analysis.

    Includes bar charts for average SAR, line plots for psSAR, and boxplots
    for SAR distribution.

    Args:
        analyzer: The main analyzer instance.
        plotter: The plotter instance for generating plots.
        results_df: DataFrame with main aggregated results.
        all_organ_results_df: DataFrame with detailed organ-level results.
    """
    # Aggregate organ-level SAR by tissue groups and merge into results_df
    # Uses tissue_group_composition from pickle files if available
    results_df = self._add_tissue_group_sar(results_df, all_organ_results_df, analyzer)

    scenarios_with_results = results_df["scenario"].unique()
    summary_stats = self.calculate_summary_stats(results_df)

    # ============================================================================
    # Aggregated Plots (symmetric with far-field)
    # ============================================================================
    # These plots aggregate data across ALL scenarios for overall trends
    if self.should_generate_plot("plot_whole_body_sar_bar"):
        # Aggregate summary stats across scenarios by frequency
        freq_summary = summary_stats.groupby("frequency_mhz").mean(numeric_only=True)
        if "SAR_whole_body" in freq_summary.columns:
            plotter.plot_whole_body_sar_bar(freq_summary)

    if self.should_generate_plot("plot_peak_sar_line"):
        # Aggregate summary stats across scenarios by frequency
        freq_summary = summary_stats.groupby("frequency_mhz").mean(numeric_only=True)
        if "peak_sar" in freq_summary.columns:
            plotter.plot_peak_sar_line(freq_summary)

    for scenario_name in scenarios_with_results:
        logging.getLogger("progress").info(
            f"\n--- Generating plots for scenario: {scenario_name} ---",
            extra={"log_type": "header"},
        )
        scenario_results_df = results_df[results_df["scenario"] == scenario_name]
        if scenario_name in summary_stats.index:
            scenario_summary_stats = summary_stats.loc[scenario_name]
            avg_results = scenario_summary_stats.drop(columns=["progress"])
            progress_info = scenario_summary_stats["progress"]
            if self.should_generate_plot("plot_average_sar_bar"):
                plotter.plot_average_sar_bar(scenario_name, pd.DataFrame(avg_results), pd.Series(progress_info), scenario_results_df)
            if self.should_generate_plot("plot_average_pssar_bar"):
                plotter.plot_average_pssar_bar(scenario_name, pd.DataFrame(avg_results), pd.Series(progress_info), scenario_results_df)
            if self.should_generate_plot("plot_sar_line"):
                plotter.plot_sar_line(scenario_name, pd.DataFrame(avg_results))
            if self.should_generate_plot("plot_pssar_line"):
                plotter.plot_pssar_line(scenario_name, pd.DataFrame(avg_results))
        if self.should_generate_plot("plot_sar_distribution_boxplots"):
            plotter.plot_sar_distribution_boxplots(scenario_name, pd.DataFrame(scenario_results_df))

        # Individual variation line plots (one line per placement/direction/polarization)
        # Include all SAR and psSAR10g metrics for symmetry
        pssar_columns = [col for col in scenario_results_df.columns if col.startswith("psSAR10g")]
        sar_columns_for_lines = ["SAR_head", "SAR_trunk", "SAR_whole_body", "SAR_brain", "SAR_skin", "SAR_eyes", "SAR_genitals"]
        # Plot SAR metrics using SAR-specific function
        if self.should_generate_plot("plot_sar_line_individual_variations"):
            for metric_col in sar_columns_for_lines:
                if metric_col in scenario_results_df.columns:
                    plotter.plot_sar_line_individual_variations(
                        results_df,
                        scenario_name=scenario_name,
                        metric_column=metric_col,
                    )
        # Plot psSAR10g metrics using psSAR10g-specific function
        if self.should_generate_plot("plot_pssar_line_individual_variations"):
            for metric_col in pssar_columns:
                if metric_col in scenario_results_df.columns:
                    plotter.plot_pssar_line_individual_variations(
                        results_df,
                        scenario_name=scenario_name,
                        metric_column=metric_col,
                    )

    # Generate heatmap with all tissues (Min/Avg/Max SAR)
    if not all_organ_results_df.empty and analyzer.tissue_group_composition:
        # Check if required columns exist
        required_cols = ["min_local_sar_mw_kg", "mass_avg_sar_mw_kg", "max_local_sar_mw_kg"]
        missing_cols = [col for col in required_cols if col not in all_organ_results_df.columns]

        if missing_cols:
            logging.getLogger("progress").warning(
                f"  - WARNING: Missing columns for SAR heatmap: {missing_cols}. Skipping heatmap.",
                extra={"log_type": "warning"},
            )
        else:
            # Prepare organ-level data with min/avg/max SAR
            # Aggregate across all placements to get mean values per tissue and frequency
            organ_sar_df = (
                all_organ_results_df.groupby(["tissue", "frequency_mhz"])
                .agg(
                    min_sar=("min_local_sar_mw_kg", "mean"),
                    avg_sar=("mass_avg_sar_mw_kg", "mean"),
                    max_sar=("max_local_sar_mw_kg", "mean"),
                )
                .reset_index()
            )

            # Drop rows where all SAR values are NA (pandas mean() returns NaN if all values are NaN)
            organ_sar_df = organ_sar_df.dropna(subset=["min_sar", "avg_sar", "max_sar"], how="all")

            # Prepare group-level summary data
            tissue_groups = {group_name: list(tissues) for group_name, tissues in analyzer.tissue_group_composition.items()}

            group_summary_data = []
            for group_name, tissues in tissue_groups.items():
                if not tissues:
                    continue

                # Filter organs belonging to this group
                group_df = all_organ_results_df[all_organ_results_df["tissue"].isin(tissues)]

                if not group_df.empty:
                    summary = group_df.groupby("frequency_mhz").agg(avg_sar=("mass_avg_sar_mw_kg", "mean")).reset_index()
                    summary["group"] = group_name.replace("_group", "").capitalize()
                    group_summary_data.append(summary)

            group_summary_df = pd.concat(group_summary_data, ignore_index=True) if group_summary_data else pd.DataFrame()

            if not organ_sar_df.empty and not group_summary_df.empty:
                # Use tissue_group_composition for plotter (convert sets to lists)
                plotter_tissue_groups = {group_name: list(tissues) for group_name, tissues in analyzer.tissue_group_composition.items()}

                if self.should_generate_plot("plot_sar_heatmap"):
                    logging.getLogger("progress").info(
                        "\n--- Generating SAR heatmap (all tissues) ---",
                        extra={"log_type": "header"},
                    )
                    plotter.plot_sar_heatmap(
                        pd.DataFrame(organ_sar_df),
                        pd.DataFrame(group_summary_df),
                        plotter_tissue_groups,
                    )

                # Also generate psSAR10g heatmap if data is available
                if "peak_sar_10g_mw_kg" in all_organ_results_df.columns and self.should_generate_plot("plot_peak_sar_heatmap"):
                    organ_pssar_df = (
                        all_organ_results_df.groupby(["tissue", "frequency_mhz"])
                        .agg(peak_sar_10g_mw_kg=("peak_sar_10g_mw_kg", "mean"))
                        .reset_index()
                    )
                    organ_pssar_df = plotter._filter_all_regions(organ_pssar_df, tissue_column="tissue")

                    group_pssar_summary_data = []
                    for group_name, tissues in tissue_groups.items():
                        if not tissues:
                            continue
                        group_df = all_organ_results_df[all_organ_results_df["tissue"].isin(tissues)]
                        if not group_df.empty:
                            summary = (
                                group_df.groupby("frequency_mhz").agg(peak_sar_10g_mw_kg=("peak_sar_10g_mw_kg", "mean")).reset_index()
                            )
                            summary["group"] = group_name.replace("_group", "").capitalize()
                            group_pssar_summary_data.append(summary)

                    group_pssar_summary_df = (
                        pd.concat(group_pssar_summary_data, ignore_index=True) if group_pssar_summary_data else pd.DataFrame()
                    )

                    if not organ_pssar_df.empty and not group_pssar_summary_df.empty:
                        if self.should_generate_plot("plot_peak_sar_heatmap"):
                            logging.getLogger("progress").info(
                                "\n--- Generating psSAR10g heatmap (all tissues) ---",
                                extra={"log_type": "header"},
                            )
                            plotter.plot_peak_sar_heatmap(
                                pd.DataFrame(organ_pssar_df),
                                pd.DataFrame(group_pssar_summary_df),
                                plotter_tissue_groups,
                                value_col="peak_sar_10g_mw_kg",
                                title="Peak SAR 10g",
                            )
            else:
                logging.getLogger("progress").warning(
                    "  - WARNING: Insufficient data for SAR heatmap (empty organ or group data).",
                    extra={"log_type": "warning"},
                )

    # Generate power balance plots for all results
    if self.should_generate_plot("plot_power_balance_overview"):
        plotter.plot_power_balance_overview(results_df)

    # ============================================================================
    # Additional Analysis Plots
    # ============================================================================

    logging.getLogger("progress").info(
        "\n--- Generating additional analysis plots ---",
        extra={"log_type": "header"},
    )

    # Collect peak location data from all results
    peak_location_data = []
    for result in analyzer.all_results:
        if "peak_sar_details" in result:
            peak_details = result["peak_sar_details"]
            if peak_details and isinstance(peak_details, dict):
                peak_location_data.append(
                    {
                        "PeakLocation": peak_details.get("PeakLocation", None),
                        "PeakCubeSideLength": peak_details.get("PeakCubeSideLength", None),
                        "PeakValue": peak_details.get("PeakValue", None),
                        "PeakCell": peak_details.get("PeakCell", None),
                        "placement": result.get("placement", ""),
                        "frequency_mhz": result.get("frequency_mhz", None),
                        "scenario": result.get("scenario", ""),
                    }
                )

    peak_location_df = pd.DataFrame(peak_location_data) if peak_location_data else pd.DataFrame()

    # ============================================================================
    # Spatial Plots
    # ============================================================================
    if not peak_location_df.empty:
        if self.should_generate_plot("plot_peak_location_3d_interactive") or self.should_generate_plot(
            "plot_peak_location_2d_projections"
        ):
            logging.getLogger("progress").info(
                "  - Generating spatial plots (3D and 2D peak locations)...",
                extra={"log_type": "info"},
            )
            # First create aggregated plot with all scenarios
            # Calculate axis limits from all data
            axis_limits = plotter.spatial._calculate_axis_limits(peak_location_df)
            # Create aggregated plot
            if self.should_generate_plot("plot_peak_location_3d_interactive"):
                plotter.plot_peak_location_3d_interactive(peak_location_df, scenario_name=None, axis_limits=axis_limits)

            # Per-scenario spatial plots with inherited axis limits
            for scenario in peak_location_df["scenario"].unique():
                scenario_peak_data = peak_location_df[peak_location_df["scenario"] == scenario].copy()
                if not scenario_peak_data.empty and self.should_generate_plot("plot_peak_location_3d_interactive"):
                    plotter.plot_peak_location_3d_interactive(scenario_peak_data, scenario_name=scenario, axis_limits=axis_limits)
                if self.should_generate_plot("plot_peak_location_2d_projections"):
                    plotter.plot_peak_location_2d_projections(peak_location_df, scenario_name=scenario)

    # ============================================================================
    # Correlation Plots
    # ============================================================================
    if self.should_generate_plot("plot_correlation_head_vs_eye_sar") or self.should_generate_plot(
        "plot_tissue_group_correlation_matrix"
    ):
        logging.getLogger("progress").info(
            "  - Generating correlation plots...",
            extra={"log_type": "info"},
        )
        # Head vs Eye SAR correlation (for front_of_eyes scenario)
        if "front_of_eyes" in scenarios_with_results and self.should_generate_plot("plot_correlation_head_vs_eye_sar"):
            plotter.plot_correlation_head_vs_eye_sar(results_df, scenario_name="front_of_eyes")
        # Tissue group correlation matrix (per scenario only - averaging across scenarios doesn't make sense)
        if self.should_generate_plot("plot_tissue_group_correlation_matrix"):
            for scenario in scenarios_with_results:
                plotter.plot_tissue_group_correlation_matrix(results_df, scenario_name=scenario)

    # ============================================================================
    # Bubble Plots (Mass vs SAR)
    # ============================================================================
    if not all_organ_results_df.empty and (
        self.should_generate_plot("plot_bubble_mass_vs_sar") or self.should_generate_plot("plot_bubble_mass_vs_sar_interactive")
    ):
        logging.getLogger("progress").info(
            "  - Generating bubble plots (mass vs SAR)...",
            extra={"log_type": "info"},
        )
        # Note: Total Mass, Total Volume, etc. should be included in organ_entries from extract_data

        # Get unique frequencies for frequency-specific plots
        frequencies = (
            sorted(all_organ_results_df["frequency_mhz"].dropna().unique()) if "frequency_mhz" in all_organ_results_df.columns else []
        )

        # SAR columns to plot
        sar_columns = ["mass_avg_sar_mw_kg"]
        if "psSAR10g" in all_organ_results_df.columns:
            sar_columns.append("psSAR10g")
        elif "peak_sar_10g_mw_kg" in all_organ_results_df.columns:
            all_organ_results_df["psSAR10g"] = all_organ_results_df["peak_sar_10g_mw_kg"]
            sar_columns.append("psSAR10g")
        if "max_local_sar_mw_kg" in all_organ_results_df.columns:
            sar_columns.append("max_local_sar_mw_kg")

        for sar_col in sar_columns:
            # Per-scenario variants only (averaging across scenarios doesn't make sense)
            for scenario in scenarios_with_results:
                # Per-scenario (all frequencies)
                if self.should_generate_plot("plot_bubble_mass_vs_sar"):
                    plotter.plot_bubble_mass_vs_sar(
                        all_organ_results_df,
                        sar_column=sar_col,
                        scenario_name=scenario,
                    )

                    # Per-scenario AND per-frequency variants
                    for freq in frequencies:
                        plotter.plot_bubble_mass_vs_sar(
                            all_organ_results_df,
                            sar_column=sar_col,
                            scenario_name=scenario,
                            frequency_mhz=freq,
                        )

                # Interactive plot per scenario
                if self.should_generate_plot("plot_bubble_mass_vs_sar_interactive"):
                    plotter.plot_bubble_mass_vs_sar_interactive(
                        all_organ_results_df,
                        sar_column=sar_col,
                        scenario_name=scenario,
                    )

    # ============================================================================
    # Ranking Plots
    # ============================================================================
    if not all_organ_results_df.empty and self.should_generate_plot("plot_top20_tissues_ranking"):
        logging.getLogger("progress").info(
            "  - Generating ranking plots (top 20 tissues)...",
            extra={"log_type": "info"},
        )
        # Per-scenario variants only (averaging across scenarios doesn't make sense)
        for scenario in scenarios_with_results:
            if "max_local_sar_mw_kg" in all_organ_results_df.columns:
                plotter.plot_top20_tissues_ranking(
                    all_organ_results_df,
                    metric="max_local_sar_mw_kg",
                    scenario_name=scenario,
                )
            # Top 20 by Mass-Averaged SAR
            plotter.plot_top20_tissues_ranking(
                all_organ_results_df,
                metric="mass_avg_sar_mw_kg",
                scenario_name=scenario,
            )
            # Top 20 by Total Loss (if available)
            if "Total Loss" in all_organ_results_df.columns:
                plotter.plot_top20_tissues_ranking(
                    all_organ_results_df,
                    metric="Total Loss",
                    scenario_name=scenario,
                )

    # ============================================================================
    # Power Plots
    # ============================================================================
    if self.should_generate_plot("plot_power_efficiency_trends") or self.should_generate_plot("plot_power_absorption_distribution"):
        logging.getLogger("progress").info(
            "  - Generating power analysis plots...",
            extra={"log_type": "info"},
        )
        # Power efficiency trends (per scenario only - averaging across scenarios doesn't make sense)
        if self.should_generate_plot("plot_power_efficiency_trends"):
            for scenario in scenarios_with_results:
                plotter.plot_power_efficiency_trends(results_df, scenario_name=scenario)

        # Power absorption distribution (per scenario only - averaging across scenarios doesn't make sense)
        if self.should_generate_plot("plot_power_absorption_distribution") and not all_organ_results_df.empty:
            if "Total Loss" in all_organ_results_df.columns:
                for scenario in scenarios_with_results:
                    plotter.plot_power_absorption_distribution(all_organ_results_df, scenario_name=scenario)
            else:
                logging.getLogger("progress").warning(
                    "  - WARNING: No 'Total Loss' data available for power absorption plot.",
                    extra={"log_type": "warning"},
                )

    # ============================================================================
    # Penetration Depth Plot
    # ============================================================================
    if self.should_generate_plot("plot_penetration_depth_ratio"):
        logging.getLogger("progress").info(
            "  - Generating penetration depth plot...",
            extra={"log_type": "info"},
        )
        # Penetration depth ratio (per scenario only - averaging across scenarios doesn't make sense)
        # Generate both psSAR10g and SAR versions for symmetry
        if "psSAR10g_brain" in results_df.columns and "psSAR10g_skin" in results_df.columns:
            for scenario in scenarios_with_results:
                plotter.plot_penetration_depth_ratio(results_df, scenario_name=scenario, metric_type="psSAR10g")
        if "SAR_brain" in results_df.columns and "SAR_skin" in results_df.columns:
            for scenario in scenarios_with_results:
                plotter.plot_penetration_depth_ratio(results_df, scenario_name=scenario, metric_type="SAR")

    # ============================================================================
    # Tissue Analysis Plots
    # ============================================================================
    if not all_organ_results_df.empty and (
        self.should_generate_plot("plot_max_local_vs_pssar10g_scatter")
        or self.should_generate_plot("plot_tissue_mass_volume_distribution")
        or self.should_generate_plot("plot_tissue_frequency_response")
    ):
        logging.getLogger("progress").info(
            "  - Generating tissue analysis plots...",
            extra={"log_type": "info"},
        )
        # Max Local SAR vs psSAR10g scatter (per scenario only - averaging across scenarios doesn't make sense)
        if self.should_generate_plot("plot_max_local_vs_pssar10g_scatter") and "max_local_sar_mw_kg" in all_organ_results_df.columns:
            for scenario in scenarios_with_results:
                plotter.plot_max_local_vs_pssar10g_scatter(all_organ_results_df, scenario_name=scenario)

        # Tissue mass/volume distribution (per scenario only - averaging across scenarios doesn't make sense)
        if (
            self.should_generate_plot("plot_tissue_mass_volume_distribution")
            and "Total Mass" in all_organ_results_df.columns
            and "Total Volume" in all_organ_results_df.columns
        ):
            for scenario in scenarios_with_results:
                plotter.plot_tissue_mass_volume_distribution(all_organ_results_df, scenario_name=scenario)

        # Tissue frequency response for top tissues (per scenario only - averaging across scenarios doesn't make sense)
        if self.should_generate_plot("plot_tissue_frequency_response") and "mass_avg_sar_mw_kg" in all_organ_results_df.columns:
            # Filter out 'All Regions' before selecting top tissues
            filtered_organs = all_organ_results_df[all_organ_results_df["tissue"] != "All Regions"]
            for scenario in scenarios_with_results:
                # Get top tissues per scenario
                scenario_organs = filtered_organs[filtered_organs["scenario"] == scenario]
                top_tissues = scenario_organs.groupby("tissue")["mass_avg_sar_mw_kg"].mean().nlargest(10).index.tolist()
                for tissue in top_tissues:
                    plotter.plot_tissue_frequency_response(all_organ_results_df, tissue_name=tissue, scenario_name=scenario)

    # ============================================================================
    # CDF Plots
    # ============================================================================
    if self.should_generate_plot("plot_cdf"):
        logging.getLogger("progress").info(
            "  - Generating CDF plots...",
            extra={"log_type": "info"},
        )
        # Get all available metrics for CDF plots
        cdf_metrics = []
        sar_metrics = [col for col in results_df.columns if col.startswith("SAR_")]
        pssar_metrics = [col for col in results_df.columns if col.startswith("psSAR10g_")]
        cdf_metrics.extend(sar_metrics)
        cdf_metrics.extend(pssar_metrics)

        # Generate CDF plots with various grouping options
        for metric in cdf_metrics:
            if metric not in results_df.columns:
                continue

            # CDF grouped by scenario (shows all scenarios together for comparison)
            plotter.plot_cdf(results_df, metric, group_by="scenario")

            # Per-scenario CDFs grouped by frequency
            for scenario in scenarios_with_results:
                plotter.plot_cdf(results_df, metric, group_by="frequency_mhz", scenario_name=scenario)

            # Note: Single CDF (all data) and per-frequency CDFs removed - averaging across scenarios doesn't make sense

    # ============================================================================
    # Outlier Identification
    # ============================================================================
    if self.should_generate_plot("identify_outliers"):
        logging.getLogger("progress").info(
            "  - Identifying outliers...",
            extra={"log_type": "info"},
        )
        # Include all SAR and psSAR10g metrics for symmetry
        outlier_metrics = [
            "psSAR10g_brain",
            "psSAR10g_eyes",
            "psSAR10g_skin",
            "psSAR10g_genitals",
            "psSAR10g_whole_body",
            "SAR_head",
            "SAR_trunk",
            "SAR_whole_body",
            "SAR_brain",
            "SAR_skin",
            "SAR_eyes",
            "SAR_genitals",
        ]
        for metric in outlier_metrics:
            if metric in results_df.columns and results_df[metric].notna().any():
                outliers = plotter.identify_outliers(results_df, metric)
                if outliers is not None and not outliers.empty:
                    # Save outliers to CSV
                    subdir = plotter._get_subdir("outliers")
                    filename = f"outliers_{metric}.csv"
                    outliers.to_csv(os.path.join(subdir, filename), index=False)
                    logging.getLogger("progress").info(
                        f"    - Found {len(outliers)} outliers for {metric}",
                        extra={"log_type": "info"},
                    )

    logging.getLogger("progress").info(
        "\n--- Analysis plots generation complete ---",
        extra={"log_type": "success"},
    )

Parallel Plot Executor

goliat.analysis.parallel_plot_executor.ParallelPlotExecutor

ParallelPlotExecutor(max_workers: int | None = None)

Executes plot generation tasks in parallel using process pool.

Uses ProcessPoolExecutor for plot generation tasks to ensure full isolation of matplotlib state, avoiding thread-safety issues with rcParams and backends.

Parameters:

Name Type Description Default
max_workers int | None

Maximum number of worker processes. If None, uses default (typically os.cpu_count()).

None
Source code in goliat/analysis/parallel_plot_executor.py
def __init__(self, max_workers: int | None = None):
    """Initialize parallel plot executor.

    Args:
        max_workers: Maximum number of worker processes. If None, uses default
                    (typically os.cpu_count()).
    """
    if max_workers is None:
        # Default: use CPU count but ensure at least 1, cap at 16 to avoid excessive memory usage
        # Plotting can be memory intensive with large DataFrames
        max_workers = min(16, (os.cpu_count() or 1))
    self.max_workers = max_workers

Methods:

execute_plots

execute_plots(plot_tasks: list[tuple[Callable, tuple, dict]], task_descriptions: list[str] | None = None)

Execute multiple plot generation tasks in parallel.

Parameters:

Name Type Description Default
plot_tasks list[tuple[Callable, tuple, dict]]

List of (function, args_tuple, kwargs_dict) tuples.

required
task_descriptions list[str] | None

Optional list of task descriptions for logging. If None, uses function names.

None

Returns:

Type Description

List of results (or exceptions) in completion order.

Source code in goliat/analysis/parallel_plot_executor.py
def execute_plots(
    self,
    plot_tasks: list[tuple[Callable, tuple, dict]],
    task_descriptions: list[str] | None = None,
):
    """Execute multiple plot generation tasks in parallel.

    Args:
        plot_tasks: List of (function, args_tuple, kwargs_dict) tuples.
        task_descriptions: Optional list of task descriptions for logging.
                          If None, uses function names.

    Returns:
        List of results (or exceptions) in completion order.
    """
    if not plot_tasks:
        return []

    if task_descriptions is None:
        task_descriptions = [f"{func.__name__}" for func, _, _ in plot_tasks]

    results = []
    completed_count = 0
    total_tasks = len(plot_tasks)

    # Use ProcessPoolExecutor for isolation
    with ProcessPoolExecutor(max_workers=self.max_workers) as executor:
        # Submit all tasks
        future_to_task = {}
        for (func, args, kwargs), desc in zip(plot_tasks, task_descriptions):
            # Submit the top-level wrapper function with the actual function as the first arg
            future = executor.submit(_execute_plot_task, func, *args, **kwargs)
            future_to_task[future] = desc

        # Process completed tasks
        for future in as_completed(future_to_task):
            task_desc = future_to_task[future]
            completed_count += 1
            try:
                result = future.result()
                results.append((task_desc, result, None))
                logging.getLogger("progress").info(
                    f"  - Completed plot ({completed_count}/{total_tasks}): {task_desc}",
                    extra={"log_type": "success"},
                )
            except Exception as e:
                results.append((task_desc, None, e))
                logging.getLogger("progress").error(
                    f"  - ERROR in plot '{task_desc}': {str(e)}",
                    extra={"log_type": "error"},
                )

    return results

Parse Verbose Log

goliat.analysis.parse_verbose_log

Parse verbose.log files to extract simulation metrics into JSON format.

This script extracts all key metrics from GOLIAT/Sim4Life verbose logs for reporting and analysis purposes.

Functions:

parse_verbose_log

parse_verbose_log(log_path: str | Path) -> dict[str, Any]

Parse a verbose.log file and extract all simulation metrics.

Parameters:

Name Type Description Default
log_path str | Path

Path to the verbose.log file

required

Returns:

Type Description
dict[str, Any]

Dictionary containing all extracted metrics

Source code in goliat/analysis/parse_verbose_log.py
def parse_verbose_log(log_path: str | Path) -> dict[str, Any]:
    """
    Parse a verbose.log file and extract all simulation metrics.

    Args:
        log_path: Path to the verbose.log file

    Returns:
        Dictionary containing all extracted metrics
    """
    log_path = Path(log_path)

    if not log_path.exists():
        raise FileNotFoundError(f"Log file not found: {log_path}")

    content = log_path.read_text(encoding="utf-8", errors="replace")

    metrics = {
        "metadata": _extract_metadata(content, log_path),
        "phantom": _extract_phantom_info(content),
        "grid": _extract_grid_info(content),
        "boundaries": _extract_boundary_info(content),
        "materials": _extract_materials_info(content),
        "solver": _extract_solver_info(content),
        "timing": _extract_timing_info(content),
        "hardware": _extract_hardware_info(content),
        "simulation": _extract_simulation_info(content),
        "edges": _extract_edge_statistics(content),
        "sensors": _extract_sensor_info(content),
        "sources": _extract_source_info(content),
        "results": _extract_results_info(content),
        "_content": content,  # Store for speed extraction in _compute_summary
    }

    # Add computed summary statistics
    metrics["summary"] = _compute_summary(metrics)

    # Remove _content to save memory (it's huge)
    del metrics["_content"]

    return metrics

parse_and_save

parse_and_save(log_path: str | Path, output_path: str | Path | None = None) -> Path

Parse a verbose.log file and save metrics to JSON.

Parameters:

Name Type Description Default
log_path str | Path

Path to the verbose.log file

required
output_path str | Path | None

Optional output path for JSON. Defaults to same directory as log.

None

Returns:

Type Description
Path

Path to the saved JSON file

Source code in goliat/analysis/parse_verbose_log.py
def parse_and_save(log_path: str | Path, output_path: str | Path | None = None) -> Path:
    """
    Parse a verbose.log file and save metrics to JSON.

    Args:
        log_path: Path to the verbose.log file
        output_path: Optional output path for JSON. Defaults to same directory as log.

    Returns:
        Path to the saved JSON file
    """
    log_path = Path(log_path)

    if output_path is None:
        output_path = log_path.parent / "simulation_metrics.json"
    else:
        output_path = Path(output_path)

    metrics = parse_verbose_log(log_path)

    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(metrics, f, indent=2, ensure_ascii=False)

    print(f"Metrics saved to: {output_path}")
    return output_path

main

main()

Main entry point for CLI usage.

Source code in goliat/analysis/parse_verbose_log.py
def main():
    """Main entry point for CLI usage."""
    parser = argparse.ArgumentParser(description="Parse verbose.log files to extract simulation metrics")
    parser.add_argument("log_path", type=str, help="Path to the verbose.log file")
    parser.add_argument(
        "-o", "--output", type=str, default=None, help="Output path for JSON file (default: simulation_metrics.json in same directory)"
    )
    parser.add_argument("--pretty", action="store_true", help="Print metrics to console in pretty format")

    args = parser.parse_args()

    output_path = parse_and_save(args.log_path, args.output)

    if args.pretty:
        with open(output_path, "r") as f:
            metrics = json.load(f)
        print("\n" + "=" * 60)
        print("SIMULATION METRICS SUMMARY")
        print("=" * 60)

        if "summary" in metrics:
            for key, value in metrics["summary"].items():
                print(f"  {key}: {value}")

Plotter

goliat.analysis.plotter.Plotter

Plotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

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
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Sets up the plotter and creates output directory.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    super().__init__(plots_dir, phantom_name, plot_format)
    os.makedirs(self.plots_dir, exist_ok=True)

    # Initialize specialized plot modules
    self.bar = BarPlotter(plots_dir, phantom_name, plot_format)
    self.line = LinePlotter(plots_dir, phantom_name, plot_format)
    self.boxplot = BoxplotPlotter(plots_dir, phantom_name, plot_format)
    self.heatmap = HeatmapPlotter(plots_dir, phantom_name, plot_format)
    self.spatial = SpatialPlotter(plots_dir, phantom_name, plot_format)
    self.correlation = CorrelationPlotter(plots_dir, phantom_name, plot_format)
    self.bubble = BubblePlotter(plots_dir, phantom_name, plot_format)
    self.ranking = RankingPlotter(plots_dir, phantom_name, plot_format)
    self.power = PowerPlotter(plots_dir, phantom_name, plot_format)
    self.penetration = PenetrationPlotter(plots_dir, phantom_name, plot_format)
    self.tissue_analysis = TissueAnalysisPlotter(plots_dir, phantom_name, plot_format)
    self.cdf = CdfPlotter(plots_dir, phantom_name, plot_format)
    self.outliers = OutliersPlotter(plots_dir, phantom_name, plot_format)

    logging.getLogger("progress").info(
        f"--- Plots will be saved to '{self.plots_dir}' directory. ---",
        extra={"log_type": "info"},
    )

Methods:

plot_average_sar_bar

plot_average_sar_bar(*args, **kwargs)

Creates a bar chart of average SAR values by frequency.

Source code in goliat/analysis/plotter.py
def plot_average_sar_bar(self, *args, **kwargs):
    """Creates a bar chart of average SAR values by frequency."""
    return self.bar.plot_average_sar_bar(*args, **kwargs)

plot_average_pssar_bar

plot_average_pssar_bar(*args, **kwargs)

Creates a bar chart of average psSAR10g values by frequency.

Source code in goliat/analysis/plotter.py
def plot_average_pssar_bar(self, *args, **kwargs):
    """Creates a bar chart of average psSAR10g values by frequency."""
    return self.bar.plot_average_pssar_bar(*args, **kwargs)

plot_whole_body_sar_bar

plot_whole_body_sar_bar(*args, **kwargs)

Creates a bar chart of average whole-body SAR by frequency.

Source code in goliat/analysis/plotter.py
def plot_whole_body_sar_bar(self, *args, **kwargs):
    """Creates a bar chart of average whole-body SAR by frequency."""
    return self.bar.plot_whole_body_sar_bar(*args, **kwargs)

plot_peak_sar_line

plot_peak_sar_line(*args, **kwargs)

Plots peak SAR trend across frequencies.

Source code in goliat/analysis/plotter.py
def plot_peak_sar_line(self, *args, **kwargs):
    """Plots peak SAR trend across frequencies."""
    return self.line.plot_peak_sar_line(*args, **kwargs)

plot_pssar_line

plot_pssar_line(*args, **kwargs)

Plots average psSAR10g trends for tissue groups by frequency.

Source code in goliat/analysis/plotter.py
def plot_pssar_line(self, *args, **kwargs):
    """Plots average psSAR10g trends for tissue groups by frequency."""
    return self.line.plot_pssar_line(*args, **kwargs)

plot_sar_line

plot_sar_line(*args, **kwargs)

Plots average SAR trends for tissue groups by frequency.

Source code in goliat/analysis/plotter.py
def plot_sar_line(self, *args, **kwargs):
    """Plots average SAR trends for tissue groups by frequency."""
    return self.line.plot_sar_line(*args, **kwargs)

plot_pssar_line_individual_variations

plot_pssar_line_individual_variations(*args, **kwargs)

Plots individual variation lines for each placement variation.

Source code in goliat/analysis/plotter.py
def plot_pssar_line_individual_variations(self, *args, **kwargs):
    """Plots individual variation lines for each placement variation."""
    return self.line.plot_pssar_line_individual_variations(*args, **kwargs)

plot_sar_line_individual_variations

plot_sar_line_individual_variations(*args, **kwargs)

Plots individual variation lines for SAR metrics.

Source code in goliat/analysis/plotter.py
def plot_sar_line_individual_variations(self, *args, **kwargs):
    """Plots individual variation lines for SAR metrics."""
    return self.line.plot_sar_line_individual_variations(*args, **kwargs)

plot_far_field_direction_polarization_lines

plot_far_field_direction_polarization_lines(*args, **kwargs)

Creates line plots showing frequency dependence for far-field direction/polarization.

Source code in goliat/analysis/plotter.py
def plot_far_field_direction_polarization_lines(self, *args, **kwargs):
    """Creates line plots showing frequency dependence for far-field direction/polarization."""
    return self.line.plot_far_field_direction_polarization_lines(*args, **kwargs)

plot_far_field_direction_polarization_comparison

plot_far_field_direction_polarization_comparison(*args, **kwargs)

Generates frequency-dependent comparison plots for all direction/polarization combos.

Source code in goliat/analysis/plotter.py
def plot_far_field_direction_polarization_comparison(self, *args, **kwargs):
    """Generates frequency-dependent comparison plots for all direction/polarization combos."""
    return self.line.plot_far_field_direction_polarization_comparison(*args, **kwargs)

plot_sar_distribution_boxplots

plot_sar_distribution_boxplots(*args, **kwargs)

Creates boxplots showing SAR value distributions across placements.

Source code in goliat/analysis/plotter.py
def plot_sar_distribution_boxplots(self, *args, **kwargs):
    """Creates boxplots showing SAR value distributions across placements."""
    return self.boxplot.plot_sar_distribution_boxplots(*args, **kwargs)

plot_sar_distribution_boxplot_single

plot_sar_distribution_boxplot_single(*args, **kwargs)

Creates a single boxplot showing distribution of one metric across frequencies.

Source code in goliat/analysis/plotter.py
def plot_sar_distribution_boxplot_single(self, *args, **kwargs):
    """Creates a single boxplot showing distribution of one metric across frequencies."""
    return self.boxplot.plot_sar_distribution_boxplot_single(*args, **kwargs)

plot_sar_heatmap

plot_sar_heatmap(*args, **kwargs)

Creates a combined heatmap showing Min/Avg/Max SAR per tissue and frequency.

Source code in goliat/analysis/plotter.py
def plot_sar_heatmap(self, *args, **kwargs):
    """Creates a combined heatmap showing Min/Avg/Max SAR per tissue and frequency."""
    return self.heatmap.plot_sar_heatmap(*args, **kwargs)

plot_peak_sar_heatmap

plot_peak_sar_heatmap(*args, **kwargs)

Creates a heatmap for peak SAR values across tissues and frequencies.

Source code in goliat/analysis/plotter.py
def plot_peak_sar_heatmap(self, *args, **kwargs):
    """Creates a heatmap for peak SAR values across tissues and frequencies."""
    return self.heatmap.plot_peak_sar_heatmap(*args, **kwargs)

plot_far_field_direction_polarization_heatmap

plot_far_field_direction_polarization_heatmap(*args, **kwargs)

Creates a heatmap comparing SAR across incident directions and polarizations.

Source code in goliat/analysis/plotter.py
def plot_far_field_direction_polarization_heatmap(self, *args, **kwargs):
    """Creates a heatmap comparing SAR across incident directions and polarizations."""
    return self.heatmap.plot_far_field_direction_polarization_heatmap(*args, **kwargs)

plot_far_field_direction_polarization_summary

plot_far_field_direction_polarization_summary(*args, **kwargs)

Creates a multi-panel summary of SAR across directions/polarizations.

Source code in goliat/analysis/plotter.py
def plot_far_field_direction_polarization_summary(self, *args, **kwargs):
    """Creates a multi-panel summary of SAR across directions/polarizations."""
    return self.heatmap.plot_far_field_direction_polarization_summary(*args, **kwargs)

plot_peak_location_3d_interactive

plot_peak_location_3d_interactive(*args, **kwargs)

Creates an interactive 3D plot of peak SAR locations.

Source code in goliat/analysis/plotter.py
def plot_peak_location_3d_interactive(self, *args, **kwargs):
    """Creates an interactive 3D plot of peak SAR locations."""
    return self.spatial.plot_peak_location_3d_interactive(*args, **kwargs)

plot_peak_location_2d_projections

plot_peak_location_2d_projections(*args, **kwargs)

Creates 2D scatter plots showing peak locations projected onto XY, XZ, YZ planes.

Source code in goliat/analysis/plotter.py
def plot_peak_location_2d_projections(self, *args, **kwargs):
    """Creates 2D scatter plots showing peak locations projected onto XY, XZ, YZ planes."""
    return self.spatial.plot_peak_location_2d_projections(*args, **kwargs)

plot_correlation_head_vs_eye_sar

plot_correlation_head_vs_eye_sar(*args, **kwargs)

Creates scatter plot showing correlation between Head SAR and Eye psSAR10g.

Source code in goliat/analysis/plotter.py
def plot_correlation_head_vs_eye_sar(self, *args, **kwargs):
    """Creates scatter plot showing correlation between Head SAR and Eye psSAR10g."""
    return self.correlation.plot_correlation_head_vs_eye_sar(*args, **kwargs)

plot_tissue_group_correlation_matrix

plot_tissue_group_correlation_matrix(*args, **kwargs)

Creates heatmap showing correlation coefficients between tissue group SAR values.

Source code in goliat/analysis/plotter.py
def plot_tissue_group_correlation_matrix(self, *args, **kwargs):
    """Creates heatmap showing correlation coefficients between tissue group SAR values."""
    return self.correlation.plot_tissue_group_correlation_matrix(*args, **kwargs)

plot_bubble_mass_vs_sar

plot_bubble_mass_vs_sar(*args, **kwargs)

Creates bubble plot showing how tissue mass affects SAR values.

Source code in goliat/analysis/plotter.py
def plot_bubble_mass_vs_sar(self, *args, **kwargs):
    """Creates bubble plot showing how tissue mass affects SAR values."""
    return self.bubble.plot_bubble_mass_vs_sar(*args, **kwargs)

plot_bubble_mass_vs_sar_interactive

plot_bubble_mass_vs_sar_interactive(*args, **kwargs)

Creates an interactive bubble plot with common axis limits across frequencies.

Source code in goliat/analysis/plotter.py
def plot_bubble_mass_vs_sar_interactive(self, *args, **kwargs):
    """Creates an interactive bubble plot with common axis limits across frequencies."""
    return self.bubble.plot_bubble_mass_vs_sar_interactive(*args, **kwargs)

plot_top20_tissues_ranking

plot_top20_tissues_ranking(*args, **kwargs)

Creates horizontal bar chart showing top 20 tissues ranked by various metrics.

Source code in goliat/analysis/plotter.py
def plot_top20_tissues_ranking(self, *args, **kwargs):
    """Creates horizontal bar chart showing top 20 tissues ranked by various metrics."""
    return self.ranking.plot_top20_tissues_ranking(*args, **kwargs)
plot_power_efficiency_trends(*args, **kwargs)

Creates line plot showing antenna efficiency and power component percentages.

Source code in goliat/analysis/plotter.py
def plot_power_efficiency_trends(self, *args, **kwargs):
    """Creates line plot showing antenna efficiency and power component percentages."""
    return self.power.plot_power_efficiency_trends(*args, **kwargs)

plot_power_absorption_distribution

plot_power_absorption_distribution(*args, **kwargs)

Creates pie chart or stacked bar chart showing power distribution across tissue groups.

Source code in goliat/analysis/plotter.py
def plot_power_absorption_distribution(self, *args, **kwargs):
    """Creates pie chart or stacked bar chart showing power distribution across tissue groups."""
    return self.power.plot_power_absorption_distribution(*args, **kwargs)

plot_power_balance_overview

plot_power_balance_overview(*args, **kwargs)

Creates power balance overview heatmap with all components.

Source code in goliat/analysis/plotter.py
def plot_power_balance_overview(self, *args, **kwargs):
    """Creates power balance overview heatmap with all components."""
    return self.power.plot_power_balance_overview(*args, **kwargs)

plot_penetration_depth_ratio

plot_penetration_depth_ratio(*args, **kwargs)

Creates line plot showing SAR penetration depth ratio (Brain/Skin) vs frequency.

Source code in goliat/analysis/plotter.py
def plot_penetration_depth_ratio(self, *args, **kwargs):
    """Creates line plot showing SAR penetration depth ratio (Brain/Skin) vs frequency."""
    return self.penetration.plot_penetration_depth_ratio(*args, **kwargs)

plot_max_local_vs_pssar10g_scatter

plot_max_local_vs_pssar10g_scatter(*args, **kwargs)

Creates scatter plot showing relationship between Max Local SAR and psSAR10g.

Source code in goliat/analysis/plotter.py
def plot_max_local_vs_pssar10g_scatter(self, *args, **kwargs):
    """Creates scatter plot showing relationship between Max Local SAR and psSAR10g."""
    return self.tissue_analysis.plot_max_local_vs_pssar10g_scatter(*args, **kwargs)

plot_tissue_frequency_response

plot_tissue_frequency_response(*args, **kwargs)

Creates line plot showing how a specific tissue responds across frequencies.

Source code in goliat/analysis/plotter.py
def plot_tissue_frequency_response(self, *args, **kwargs):
    """Creates line plot showing how a specific tissue responds across frequencies."""
    return self.tissue_analysis.plot_tissue_frequency_response(*args, **kwargs)

plot_tissue_mass_volume_distribution

plot_tissue_mass_volume_distribution(*args, **kwargs)

Creates histograms and scatter plot showing tissue mass and volume distributions.

Source code in goliat/analysis/plotter.py
def plot_tissue_mass_volume_distribution(self, *args, **kwargs):
    """Creates histograms and scatter plot showing tissue mass and volume distributions."""
    return self.tissue_analysis.plot_tissue_mass_volume_distribution(*args, **kwargs)

plot_cdf

plot_cdf(*args, **kwargs)

Creates CDF plot for a metric with optional aggregation by independent variables.

Source code in goliat/analysis/plotter.py
def plot_cdf(self, *args, **kwargs):
    """Creates CDF plot for a metric with optional aggregation by independent variables."""
    return self.cdf.plot_cdf(*args, **kwargs)

identify_outliers

identify_outliers(*args, **kwargs)

Identifies and visualizes outliers in SAR metrics.

Source code in goliat/analysis/plotter.py
def identify_outliers(self, *args, **kwargs):
    """Identifies and visualizes outliers in SAR metrics."""
    return self.outliers.identify_outliers(*args, **kwargs)

plot_cross_phantom_comparison

plot_cross_phantom_comparison(*args, **kwargs)

Plots SAR vs frequency comparing different phantoms.

Source code in goliat/analysis/plotter.py
def plot_cross_phantom_comparison(self, *args, **kwargs):
    """Plots SAR vs frequency comparing different phantoms."""
    return self.line.plot_cross_phantom_comparison(*args, **kwargs)

plot_polarization_ratio_lines

plot_polarization_ratio_lines(*args, **kwargs)

Plots theta/phi polarization ratio vs frequency for each direction.

Source code in goliat/analysis/plotter.py
def plot_polarization_ratio_lines(self, *args, **kwargs):
    """Plots theta/phi polarization ratio vs frequency for each direction."""
    return self.line.plot_polarization_ratio_lines(*args, **kwargs)

plot_polarization_ratio_heatmap

plot_polarization_ratio_heatmap(*args, **kwargs)

Plots frequency-averaged polarization ratio heatmap.

Source code in goliat/analysis/plotter.py
def plot_polarization_ratio_heatmap(self, *args, **kwargs):
    """Plots frequency-averaged polarization ratio heatmap."""
    return self.heatmap.plot_polarization_ratio_heatmap(*args, **kwargs)

plot_polarization_ratio_heatmaps_per_frequency

plot_polarization_ratio_heatmaps_per_frequency(*args, **kwargs)

Plots polarization ratio heatmaps for each frequency separately.

Source code in goliat/analysis/plotter.py
def plot_polarization_ratio_heatmaps_per_frequency(self, *args, **kwargs):
    """Plots polarization ratio heatmaps for each frequency separately."""
    return self.heatmap.plot_polarization_ratio_heatmaps_per_frequency(*args, **kwargs)

Plots

goliat.analysis.plots.bar.BarPlotter

BarPlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Bases: BasePlotter

Generates bar chart plots for SAR analysis.

Source code in goliat/analysis/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

plot_average_sar_bar

plot_average_sar_bar(scenario_name: str, avg_results: DataFrame, progress_info: Series, scenario_results_df: DataFrame | None = None)

Creates a bar chart of average Head and Trunk SAR by frequency.

Shows completion progress in x-axis labels. Used for near-field analysis.

Parameters:

Name Type Description Default
scenario_name str

Placement scenario name (e.g., 'by_cheek').

required
avg_results DataFrame

DataFrame with average SAR values, indexed by frequency.

required
progress_info Series

Series with completion counts like '⅚' per frequency.

required
Source code in goliat/analysis/plots/bar.py
def plot_average_sar_bar(
    self, scenario_name: str, avg_results: pd.DataFrame, progress_info: pd.Series, scenario_results_df: pd.DataFrame | None = None
):
    """Creates a bar chart of average Head and Trunk SAR by frequency.

    Shows completion progress in x-axis labels. Used for near-field analysis.

    Args:
        scenario_name: Placement scenario name (e.g., 'by_cheek').
        avg_results: DataFrame with average SAR values, indexed by frequency.
        progress_info: Series with completion counts like '5/6' per frequency.
    """
    fig, ax = plt.subplots(figsize=(3.5, 2.5))  # IEEE single-column width

    # Select available columns - exclude SAR_whole_body (same as psSAR10g excludes whole_body)
    sar_cols = []
    legend_labels = []
    sar_metrics_order = ["SAR_head", "SAR_trunk", "SAR_brain", "SAR_skin", "SAR_eyes", "SAR_genitals"]
    for metric in sar_metrics_order:
        if metric in avg_results.columns:
            sar_cols.append(metric)
            # Use trimmed legend labels (remove "SAR" since y-axis already says "SAR")
            legend_labels.append(LEGEND_LABELS.get(metric, metric.replace("SAR_", "").replace("_", " ").title()))

    if sar_cols:
        # Get frequencies for error bar calculation
        if isinstance(avg_results.index, pd.MultiIndex):
            frequencies = sorted(avg_results.index.get_level_values("frequency_mhz").unique())
        else:
            frequencies = sorted(avg_results.index.unique())

        # Calculate error bars from boxplot data if available, otherwise use std
        error_bars_dict = {}
        use_boxplot_errors = False
        stds = None
        if scenario_results_df is not None:
            # Try to calculate boxplot-style error bars
            for metric in sar_cols:
                if metric in scenario_results_df.columns:
                    lower_errors, upper_errors = self._calculate_boxplot_error_bars(scenario_results_df, metric, frequencies)
                    # Convert to arrays matching avg_results index order
                    lower_arr = []
                    upper_arr = []
                    for freq in frequencies:
                        lower_arr.append(lower_errors.get(freq, 0))
                        upper_arr.append(upper_errors.get(freq, 0))
                    error_bars_dict[metric] = (np.array(lower_arr), np.array(upper_arr))
                    use_boxplot_errors = True

        if not use_boxplot_errors:
            # Fall back to std
            stds = avg_results[sar_cols].std(axis=0) if len(avg_results) > 1 else pd.Series(0, index=sar_cols)
            for metric in sar_cols:
                error_bars_dict[metric] = stds[metric] if metric in stds.index else 0

        # Plot bars
        if use_boxplot_errors:
            # Plot with asymmetric error bars - need to format as list of tuples
            error_bars_list = []
            for col in sar_cols:
                if col in error_bars_dict and isinstance(error_bars_dict[col], tuple):
                    error_bars_list.append(error_bars_dict[col])
                else:
                    error_bars_list.append(None)
            avg_results[sar_cols].plot(
                kind="bar",
                ax=ax,
                color=self._get_academic_colors(len(sar_cols)),
                yerr=error_bars_list if any(e is not None for e in error_bars_list) else None,
                capsize=2,
                error_kw={"elinewidth": 0.8, "capthick": 0.8},
                legend=False,
            )
        elif len(avg_results) > 1 and stds is not None:
            avg_results[sar_cols].plot(
                kind="bar",
                ax=ax,
                color=self._get_academic_colors(len(sar_cols)),
                yerr=stds,
                capsize=2,
                error_kw={"elinewidth": 0.8, "capthick": 0.8},
                legend=False,
            )
        else:
            avg_results[sar_cols].plot(kind="bar", ax=ax, color=self._get_academic_colors(len(sar_cols)), legend=False)

        # Handle both single-level and multi-level index
        if isinstance(avg_results.index, pd.MultiIndex):
            # Multi-level index: extract frequency from second level
            progress_labels = [
                f"{freq}\n({progress_info.get((scenario_name, freq), progress_info.get(freq, '0/0'))})"
                for scenario, freq in avg_results.index
            ]
        else:
            # Single-level index: assume it's frequency
            progress_labels = [str(freq) for freq in avg_results.index]
        ax.set_xticklabels(progress_labels, rotation=0)

        # Create title with phantom name and formatted scenario
        base_title = "Average normalized SAR for scenario"
        title_full = self._get_title_with_phantom(base_title, scenario_name)
        # Don't set title on plot - will be in caption file
        ax.set_xlabel(self._format_axis_label("Frequency", "MHz"))
        ax.set_ylabel(self._format_axis_label("Normalized SAR", r"mW kg$^{-1}$"))

        # Format legend labels to be human readable (e.g., psSAR10g_eyes -> psSAR10g Eyes)
        formatted_legend_labels = []
        for label in legend_labels:
            # Handle psSAR10g_eyes format - preserve psSAR10g capitalization
            if "pssar10g" in label.lower() or "psSAR10g" in label:
                # First fix any incorrect capitalization
                label = label.replace("Pssar10g", "psSAR10g").replace("Pssar", "psSAR")
                formatted_label = label.replace("psSAR10g", "psSAR10g ").replace("_", " ").title()
                # Fix capitalization - ensure psSAR10g stays correct
                formatted_label = formatted_label.replace("Pssar10g", "psSAR10g").replace("Pssar", "psSAR")
            else:
                formatted_label = (
                    self._format_organ_name(label) if hasattr(self, "_format_organ_name") else label.replace("_", " ").title()
                )
            formatted_legend_labels.append(formatted_label)

        # Move legend below plot - create handles manually to ensure we get all of them
        import matplotlib.patches as mpatches

        from .line import LinePlotter

        line_plotter = LinePlotter(self.plots_dir, self.phantom_name, self.plot_format)
        # Always create patches manually to ensure we have the correct number and colors
        # This is more reliable than trying to extract from containers which may be incomplete
        handles = []
        # Get colors from academic color palette
        colors = self._get_academic_colors(len(sar_cols))
        for i, col in enumerate(sar_cols):
            # Create a rectangle patch with the color from the academic palette
            patch = mpatches.Patch(facecolor=colors[i], edgecolor="black", linewidth=0.5)
            handles.append(patch)
        # Ensure handles and labels match exactly
        if len(handles) != len(formatted_legend_labels):
            logging.getLogger("progress").warning(
                f"Mismatch: {len(handles)} handles but {len(formatted_legend_labels)} labels for SAR bar plot. "
                f"Columns: {sar_cols}, Labels: {formatted_legend_labels}",
                extra={"log_type": "warning"},
            )
        # Use 2 columns for legend to ensure balanced layout (2x2 for 4 items)
        n_cols = 2 if len(formatted_legend_labels) >= 4 else min(3, len(formatted_legend_labels))
        line_plotter._place_legend_below(
            fig, ax, len(formatted_legend_labels), n_cols=n_cols, handles=handles, labels=formatted_legend_labels
        )

        # Add sample size annotation showing samples per bar (not number of bars)
        # Calculate samples per frequency from scenario_results_df
        if scenario_results_df is not None and not scenario_results_df.empty:
            samples_per_freq = scenario_results_df.groupby("frequency_mhz").size()
            # Use the most common sample size (mode), or mean if all different
            if len(samples_per_freq.unique()) == 1:
                n_per_bar = samples_per_freq.iloc[0]
            else:
                n_per_bar = int(samples_per_freq.median())
            ax.text(
                0.95,
                0.95,
                f"n = {n_per_bar}/bar",
                transform=ax.transAxes,
                fontsize=8,
                verticalalignment="top",
                horizontalalignment="right",
                bbox=dict(boxstyle="square,pad=0.4", facecolor="white", edgecolor="black", linewidth=0.5, alpha=1.0),
            )

        # Set y-axis - simple 0 to max + 5%
        y_max = ax.get_ylim()[1]
        ax.set_ylim(0, y_max * 1.05)
    else:
        ax.text(0.5, 0.5, "No SAR data available", ha="center", va="center")
        base_title = "Average normalized SAR for scenario"
        title_full = self._get_title_with_phantom(base_title, scenario_name)
        use_boxplot_errors = False

    plt.tight_layout()
    error_bar_note = (
        "Error bars show boxplot whiskers (IQR-based range)"
        if use_boxplot_errors
        else "Error bars indicate standard deviation when multiple data points are available"
    )
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The bar chart shows average normalized SAR values (Head, Trunk, Brain, Skin, Eyes, Genitals) across frequencies for the {self._format_scenario_name(scenario_name)} scenario for {phantom_name_formatted}. {error_bar_note}."
    self._save_figure(fig, "bar", f"average_sar_bar_{scenario_name}", title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = avg_results[sar_cols].copy()
    csv_data.index.name = "frequency_mhz"
    self._save_csv_data(csv_data, "bar", f"average_sar_bar_{scenario_name}")

plot_average_pssar_bar

plot_average_pssar_bar(scenario_name: str, avg_results: DataFrame, progress_info: Series, scenario_results_df: DataFrame | None = None)

Creates a bar chart of average psSAR10g values by frequency for a scenario.

Symmetric counterpart to plot_average_sar_bar.

Parameters:

Name Type Description Default
scenario_name str

Placement scenario name (e.g., 'by_cheek').

required
avg_results DataFrame

DataFrame with average psSAR10g values, indexed by frequency.

required
progress_info Series

Series with completion counts like '⅚' per frequency.

required
Source code in goliat/analysis/plots/bar.py
def plot_average_pssar_bar(
    self, scenario_name: str, avg_results: pd.DataFrame, progress_info: pd.Series, scenario_results_df: pd.DataFrame | None = None
):
    """Creates a bar chart of average psSAR10g values by frequency for a scenario.

    Symmetric counterpart to plot_average_sar_bar.

    Args:
        scenario_name: Placement scenario name (e.g., 'by_cheek').
        avg_results: DataFrame with average psSAR10g values, indexed by frequency.
        progress_info: Series with completion counts like '5/6' per frequency.
    """
    fig, ax = plt.subplots(figsize=(3.5, 2.5))  # IEEE single-column width

    # Select all psSAR10g columns for symmetry
    pssar_cols = [col for col in avg_results.columns if col.startswith("psSAR10g")]
    pssar_cols.sort()  # Consistent ordering

    if pssar_cols:
        # Get frequencies for error bar calculation
        if isinstance(avg_results.index, pd.MultiIndex):
            frequencies = sorted(avg_results.index.get_level_values("frequency_mhz").unique())
        else:
            frequencies = sorted(avg_results.index.unique())

        # Calculate error bars from boxplot data if available, otherwise use std
        error_bars_dict = {}
        use_boxplot_errors = False
        stds = None
        if scenario_results_df is not None:
            # Try to calculate boxplot-style error bars
            for metric in pssar_cols:
                if metric in scenario_results_df.columns:
                    lower_errors, upper_errors = self._calculate_boxplot_error_bars(scenario_results_df, metric, frequencies)
                    # Convert to arrays matching avg_results index order
                    lower_arr = []
                    upper_arr = []
                    for freq in frequencies:
                        lower_arr.append(lower_errors.get(freq, 0))
                        upper_arr.append(upper_errors.get(freq, 0))
                    error_bars_dict[metric] = (np.array(lower_arr), np.array(upper_arr))
                    use_boxplot_errors = True

        if not use_boxplot_errors:
            # Fall back to std
            stds = avg_results[pssar_cols].std(axis=0) if len(avg_results) > 1 else pd.Series(0, index=pssar_cols)
            for metric in pssar_cols:
                error_bars_dict[metric] = stds[metric] if metric in stds.index else 0

        # Plot bars
        if use_boxplot_errors:
            # Plot with asymmetric error bars - need to format as list of tuples
            error_bars_list = []
            for col in pssar_cols:
                if col in error_bars_dict and isinstance(error_bars_dict[col], tuple):
                    error_bars_list.append(error_bars_dict[col])
                else:
                    error_bars_list.append(None)
            avg_results[pssar_cols].plot(
                kind="bar",
                ax=ax,
                color=self._get_academic_colors(len(pssar_cols)),
                yerr=error_bars_list if any(e is not None for e in error_bars_list) else None,
                capsize=2,
                error_kw={"elinewidth": 0.8, "capthick": 0.8},
                legend=False,
            )
        elif len(avg_results) > 1 and stds is not None:
            avg_results[pssar_cols].plot(
                kind="bar",
                ax=ax,
                color=self._get_academic_colors(len(pssar_cols)),
                yerr=stds,
                capsize=2,
                error_kw={"elinewidth": 0.8, "capthick": 0.8},
                legend=False,
            )
        else:
            avg_results[pssar_cols].plot(kind="bar", ax=ax, color=self._get_academic_colors(len(pssar_cols)), legend=False)

        # Handle both single-level and multi-level index
        if isinstance(avg_results.index, pd.MultiIndex):
            # Multi-level index: extract frequency from second level
            progress_labels = [
                f"{freq}\n({progress_info.get((scenario_name, freq), progress_info.get(freq, '0/0'))})"
                for scenario, freq in avg_results.index
            ]
        else:
            # Single-level index: assume it's frequency
            progress_labels = [str(freq) for freq in avg_results.index]
        ax.set_xticklabels(progress_labels, rotation=0)

        # Create title with phantom name and formatted scenario
        base_title = "Average normalized psSAR10g for scenario"
        title_full = self._get_title_with_phantom(base_title, scenario_name)
        # Don't set title on plot - will be in caption file
        ax.set_xlabel(self._format_axis_label("Frequency", "MHz"))
        ax.set_ylabel(self._format_axis_label("Normalized psSAR10g", r"mW kg$^{-1}$"))
        # Use trimmed legend labels (remove "psSAR10g" since y-axis already says "psSAR10g")
        legend_labels = [LEGEND_LABELS.get(col, col.replace("psSAR10g_", "").replace("_", " ").title()) for col in pssar_cols]

        # Format legend labels to be human readable (e.g., eyes -> Eyes, whole_body -> Whole Body)
        formatted_legend_labels = []
        for label in legend_labels:
            if label is None:
                continue
            formatted_label = self._format_organ_name(label) if hasattr(self, "_format_organ_name") else label.replace("_", " ").title()
            formatted_legend_labels.append(formatted_label)

        # Move legend below plot - create handles manually to ensure we get all of them
        import matplotlib.patches as mpatches

        from .line import LinePlotter

        line_plotter = LinePlotter(self.plots_dir, self.phantom_name, self.plot_format)
        # Always create patches manually to ensure we have the correct number and colors
        # This is more reliable than trying to extract from containers which may be incomplete
        handles = []
        # Get colors from academic color palette
        colors = self._get_academic_colors(len(pssar_cols))
        for i, col in enumerate(pssar_cols):
            # Create a rectangle patch with the color from the academic palette
            patch = mpatches.Patch(facecolor=colors[i], edgecolor="black", linewidth=0.5)
            handles.append(patch)
        # Ensure handles and labels match exactly
        if len(handles) != len(formatted_legend_labels):
            logging.getLogger("progress").warning(
                f"Mismatch: {len(handles)} handles but {len(formatted_legend_labels)} labels for psSAR10g bar plot. "
                f"Columns: {pssar_cols}, Labels: {formatted_legend_labels}",
                extra={"log_type": "warning"},
            )
        # Use 2 columns for legend to ensure balanced layout (2x2 for 4 items)
        n_cols = 2 if len(formatted_legend_labels) >= 4 else min(3, len(formatted_legend_labels))
        line_plotter._place_legend_below(
            fig, ax, len(formatted_legend_labels), n_cols=n_cols, handles=handles, labels=formatted_legend_labels
        )

        # Add sample size annotation showing samples per bar (not number of bars)
        # Calculate samples per frequency from scenario_results_df
        if scenario_results_df is not None and not scenario_results_df.empty:
            samples_per_freq = scenario_results_df.groupby("frequency_mhz").size()
            # Use the most common sample size (mode), or mean if all different
            if len(samples_per_freq.unique()) == 1:
                n_per_bar = samples_per_freq.iloc[0]
            else:
                n_per_bar = int(samples_per_freq.median())
            ax.text(
                0.95,
                0.95,
                f"n = {n_per_bar}/bar",
                transform=ax.transAxes,
                fontsize=8,
                verticalalignment="top",
                horizontalalignment="right",
                bbox=dict(boxstyle="square,pad=0.4", facecolor="white", edgecolor="black", linewidth=0.5, alpha=1.0),
            )

        # Set y-axis - simple 0 to max + 5%
        y_max = ax.get_ylim()[1]
        ax.set_ylim(0, y_max * 1.05)
    else:
        ax.text(0.5, 0.5, "No psSAR10g data available", ha="center", va="center")
        base_title = "Average normalized psSAR10g for scenario"
        title_full = self._get_title_with_phantom(base_title, scenario_name)
        use_boxplot_errors = False

    plt.tight_layout()
    error_bar_note = (
        "Error bars show boxplot whiskers (IQR-based range)"
        if use_boxplot_errors
        else "Error bars indicate standard deviation when multiple data points are available"
    )
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The bar chart shows average normalized psSAR10g values (Eyes, Skin, Brain, Genitals, Whole Body) across frequencies for the {self._format_scenario_name(scenario_name)} scenario for {phantom_name_formatted}. {error_bar_note}."
    self._save_figure(fig, "bar", f"average_pssar_bar_{scenario_name}", title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = avg_results[pssar_cols].copy()
    csv_data.index.name = "frequency_mhz"
    self._save_csv_data(csv_data, "bar", f"average_pssar_bar_{scenario_name}")

plot_whole_body_sar_bar

plot_whole_body_sar_bar(avg_results: DataFrame)

Creates a bar chart of average whole-body SAR by frequency.

Source code in goliat/analysis/plots/bar.py
def plot_whole_body_sar_bar(self, avg_results: pd.DataFrame):
    """Creates a bar chart of average whole-body SAR by frequency."""
    fig, ax = plt.subplots(figsize=(3.5, 2.5))  # IEEE single-column width
    avg_results["SAR_whole_body"].plot(kind="bar", ax=ax, color="skyblue")
    ax.set_xticklabels(avg_results.index.get_level_values("frequency_mhz"), rotation=0)
    title_full = self._get_title_with_phantom("Average whole-body SAR")
    # Don't set title on plot - will be in caption file
    ax.set_xlabel(self._format_axis_label("Frequency", "MHz"))
    ax.set_ylabel(self._format_axis_label("Normalized whole-body SAR", r"mW kg$^{-1}$"))
    # Set y-axis to start at 0 and go to max + 5%
    y_max = ax.get_ylim()[1]
    ax.set_ylim(0, y_max * 1.05)
    plt.tight_layout()
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The bar chart shows average normalized whole-body SAR values across frequencies for {phantom_name_formatted}."
    self._save_figure(fig, "bar", "average_whole_body_sar_bar", title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = avg_results[["SAR_whole_body"]].copy()
    csv_data.index.name = "frequency_mhz"
    self._save_csv_data(csv_data, "bar", "average_whole_body_sar_bar")

goliat.analysis.plots.base.BasePlotter

BasePlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Base class for plot modules with shared utilities.

Provides common helper methods for subdirectory management, data filtering, and title generation.

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/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

goliat.analysis.plots.boxplot.BoxplotPlotter

BoxplotPlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Bases: BasePlotter

Generates boxplot plots for SAR analysis.

Source code in goliat/analysis/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

plot_sar_distribution_boxplots

plot_sar_distribution_boxplots(scenario_name: str, scenario_results_df: DataFrame)

Creates boxplots showing SAR value distributions across frequencies.

Generates separate boxplots for each SAR and psSAR10g metric. Shows spread and outliers for each frequency. Used by near-field analysis which generates multiple plots per scenario.

Parameters:

Name Type Description Default
scenario_name str

Placement scenario name.

required
scenario_results_df DataFrame

DataFrame with detailed results for all placements.

required
Source code in goliat/analysis/plots/boxplot.py
def plot_sar_distribution_boxplots(self, scenario_name: str, scenario_results_df: pd.DataFrame):
    """Creates boxplots showing SAR value distributions across frequencies.

    Generates separate boxplots for each SAR and psSAR10g metric.
    Shows spread and outliers for each frequency. Used by near-field analysis
    which generates multiple plots per scenario.

    Args:
        scenario_name: Placement scenario name.
        scenario_results_df: DataFrame with detailed results for all placements.
    """
    pssar_columns = [col for col in scenario_results_df.columns if col.startswith("psSAR10g")]
    # Include all SAR metrics for symmetry with psSAR10g
    sar_metrics_for_boxplot = [
        "SAR_head",
        "SAR_trunk",
        "SAR_whole_body",
        "SAR_brain",
        "SAR_skin",
        "SAR_eyes",
        "SAR_genitals",
    ] + pssar_columns
    for metric in sar_metrics_for_boxplot:
        if metric not in scenario_results_df.columns:
            continue
        if not scenario_results_df[metric].dropna().empty:
            fig, ax = plt.subplots(figsize=(3.5, 2.5))  # IEEE single-column width
            sns.boxplot(data=scenario_results_df, x="frequency_mhz", y=metric, ax=ax, **self._get_boxplot_kwargs())
            metric_label = METRIC_LABELS.get(metric, metric)
            base_title = f"distribution of normalized {metric_label} for scenario"
            title_full = self._get_title_with_phantom(base_title, scenario_name)
            # Don't set title on plot - will be in caption file
            ax.set_xlabel(self._format_axis_label("Frequency", "MHz"))
            ax.set_ylabel(self._format_axis_label("Normalized SAR", r"mW kg$^{-1}$"))

            # Add sample size annotation - use max samples per boxplot

            unique_freqs = sorted(scenario_results_df["frequency_mhz"].unique())
            max_n = 0
            for freq in unique_freqs:
                freq_data = scenario_results_df[scenario_results_df["frequency_mhz"] == freq][metric].dropna()
                n_freq = len(freq_data)
                if n_freq > max_n:
                    max_n = n_freq

            if max_n > 0:
                ax.text(
                    0.95,
                    0.95,
                    f"n = {max_n}",
                    transform=ax.transAxes,
                    fontsize=8,
                    verticalalignment="top",
                    horizontalalignment="right",
                    bbox=dict(boxstyle="square,pad=0.4", facecolor="white", edgecolor="black", linewidth=0.5, alpha=1.0),
                )

            # Set y-axis to start at 0 and go to max + 5%
            y_max = ax.get_ylim()[1]
            ax.set_ylim(0, y_max * 1.05)
            plt.tight_layout()

            phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
            caption = f"The boxplot shows the distribution of normalized {metric_label} values across different frequencies for the {self._format_scenario_name(scenario_name)} scenario for {phantom_name_formatted}. Each box spans from the first quartile (Q1) to the third quartile (Q3), with the median line shown inside the box. The whiskers extend to show the range of the data, and points beyond the whiskers are outliers."
            self._save_figure(fig, "boxplot", f"boxplot_{metric}_{scenario_name}", title=title_full, caption=caption, dpi=300)

            # Save CSV data
            csv_data = scenario_results_df[["frequency_mhz", metric]].copy()
            self._save_csv_data(csv_data, "boxplot", f"boxplot_{metric}_{scenario_name}")

plot_sar_distribution_boxplot_single

plot_sar_distribution_boxplot_single(results_df: DataFrame, metric: str = 'SAR_whole_body', scenario_name: str | None = None)

Creates a single boxplot showing distribution of one metric across frequencies.

Generates one boxplot for a specified metric. Shows spread and outliers for each frequency. Used by far-field analysis which calls this per-metric. Symmetric counterpart to plot_sar_distribution_boxplots.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with detailed results.

required
metric str

Column name of the SAR metric to plot.

'SAR_whole_body'
scenario_name str | None

Optional scenario name for filename (default: None uses 'all').

None
Source code in goliat/analysis/plots/boxplot.py
def plot_sar_distribution_boxplot_single(
    self, results_df: pd.DataFrame, metric: str = "SAR_whole_body", scenario_name: str | None = None
):
    """Creates a single boxplot showing distribution of one metric across frequencies.

    Generates one boxplot for a specified metric. Shows spread and outliers
    for each frequency. Used by far-field analysis which calls this per-metric.
    Symmetric counterpart to plot_sar_distribution_boxplots.

    Args:
        results_df: DataFrame with detailed results.
        metric: Column name of the SAR metric to plot.
        scenario_name: Optional scenario name for filename (default: None uses 'all').
    """
    if metric not in results_df.columns or results_df[metric].dropna().empty:
        logging.getLogger("progress").warning(
            f"  - WARNING: No data for metric '{metric}' to generate boxplot.",
            extra={"log_type": "warning"},
        )
        return

    fig, ax = plt.subplots(figsize=(3.5, 2.5))  # IEEE single-column width
    sns.boxplot(data=results_df, x="frequency_mhz", y=metric, ax=ax, **self._get_boxplot_kwargs())
    metric_label = METRIC_LABELS.get(metric, metric)
    base_title = f"distribution of normalized {metric_label}"
    title_full = self._get_title_with_phantom(base_title, scenario_name)
    # Don't set title on plot - will be in caption file
    ax.set_xlabel(self._format_axis_label("Frequency", "MHz"))
    ax.set_ylabel(self._format_axis_label("Normalized SAR", r"mW kg$^{-1}$"))

    # Add sample size annotation - use max samples per boxplot (symmetric with near-field)
    unique_freqs = sorted(results_df["frequency_mhz"].unique())
    max_n = 0
    for freq in unique_freqs:
        freq_data = results_df[results_df["frequency_mhz"] == freq][metric].dropna()
        n_freq = len(freq_data)
        if n_freq > max_n:
            max_n = n_freq

    if max_n > 0:
        ax.text(
            0.95,
            0.95,
            f"n = {max_n}",
            transform=ax.transAxes,
            fontsize=8,
            verticalalignment="top",
            horizontalalignment="right",
            bbox=dict(boxstyle="square,pad=0.4", facecolor="white", edgecolor="black", linewidth=0.5, alpha=1.0),
        )

    # Set y-axis to start at 0 and go to max + 5%
    y_max = ax.get_ylim()[1]
    ax.set_ylim(0, y_max * 1.05)
    plt.tight_layout()

    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    scenario_str = f" for the {self._format_scenario_name(scenario_name)} scenario" if scenario_name else ""
    caption = f"The boxplot shows the distribution of normalized {metric_label} values across different frequencies{scenario_str} for {phantom_name_formatted}. Each box spans from the first quartile (Q1) to the third quartile (Q3), with the median line shown inside the box. The whiskers extend to show the range of the data, and points beyond the whiskers are outliers."
    filename_base = f"boxplot_{metric}_{scenario_name or 'all'}"
    self._save_figure(fig, "boxplot", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data (symmetric with near-field)
    csv_data = results_df[["frequency_mhz", metric]].copy()
    self._save_csv_data(csv_data, "boxplot", filename_base)

goliat.analysis.plots.bubble.BubblePlotter

BubblePlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Bases: BasePlotter

Generates bubble plots for SAR analysis.

Source code in goliat/analysis/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

plot_bubble_mass_vs_sar

plot_bubble_mass_vs_sar(organ_results_df: DataFrame, sar_column: str = 'mass_avg_sar_mw_kg', scenario_name: str | None = None, frequency_mhz: int | None = None)

Creates bubble plot showing how tissue mass affects SAR values.

Parameters:

Name Type Description Default
organ_results_df DataFrame

DataFrame with columns: ['tissue', 'Total Mass', 'Total Volume', sar_column, 'frequency_mhz']

required
sar_column str

Column name for SAR values (default: 'mass_avg_sar_mw_kg').

'mass_avg_sar_mw_kg'
scenario_name str | None

Optional scenario name for filtering.

None
frequency_mhz int | None

Optional frequency for filtering.

None
Source code in goliat/analysis/plots/bubble.py
def plot_bubble_mass_vs_sar(
    self,
    organ_results_df: pd.DataFrame,
    sar_column: str = "mass_avg_sar_mw_kg",
    scenario_name: str | None = None,
    frequency_mhz: int | None = None,
):
    """Creates bubble plot showing how tissue mass affects SAR values.

    Args:
        organ_results_df: DataFrame with columns: ['tissue', 'Total Mass', 'Total Volume',
                      sar_column, 'frequency_mhz']
        sar_column: Column name for SAR values (default: 'mass_avg_sar_mw_kg').
        scenario_name: Optional scenario name for filtering.
        frequency_mhz: Optional frequency for filtering.
    """
    if organ_results_df.empty:
        return

    plot_df = organ_results_df.copy()
    # Filter out 'All Regions' - it's a whole-body aggregate, not a real tissue
    plot_df = self._filter_all_regions(plot_df, tissue_column="tissue")

    # Filter by frequency if provided
    if frequency_mhz is not None:
        plot_df = plot_df[plot_df["frequency_mhz"] == frequency_mhz].copy()

    # Check required columns
    required_cols = ["tissue", "Total Mass", "Total Volume", sar_column]
    missing_cols = [col for col in required_cols if col not in plot_df.columns]
    if missing_cols:
        logging.getLogger("progress").warning(
            f"Missing columns for bubble plot: {missing_cols}",
            extra={"log_type": "warning"},
        )
        return

    # Remove rows with missing data
    plot_df = plot_df.dropna(subset=required_cols)
    plot_df = plot_df[plot_df["Total Mass"] > 0]
    plot_df = plot_df[plot_df[sar_column] > 0]

    if plot_df.empty:
        return

    # Aggregate by tissue (mean across placements if multiple)
    if "placement" in plot_df.columns:
        plot_df = (
            plot_df.groupby("tissue")
            .agg(
                {
                    "Total Mass": "mean",
                    "Total Volume": "mean",
                    sar_column: "mean",
                    "frequency_mhz": "first",
                }
            )
            .reset_index()
        )

    # Only create log-scale version on x-axis (removed linear version)
    # Use IEEE single-column width (3.5 inches)
    fig_log, ax_log = plt.subplots(figsize=(3.5, 4.8))  # IEEE single-column width, taller for legend

    # Scale bubble size - use power of 0.75 (between sqrt and linear) for moderate scaling
    volumes_log = plot_df["Total Volume"].values
    vol_min_log, vol_max_log = volumes_log.min(), volumes_log.max()
    if vol_max_log > vol_min_log:
        normalized_volumes_log = (volumes_log - vol_min_log) / (vol_max_log - vol_min_log)
        bubble_sizes_log = np.power(normalized_volumes_log, 0.75) * 50 + 10  # Scale to 10-60 range
    else:
        bubble_sizes_log = np.full(len(volumes_log), 30)  # Default size if all same

    # Scatter plot without colorbar (volume shown by bubble size only)
    ax_log.scatter(
        plot_df[sar_column],
        plot_df["Total Mass"],
        s=bubble_sizes_log,
        c="gray",  # Single color - volume shown by size only
        alpha=0.7,
        edgecolors="black",
        linewidth=0.5,
    )

    ax_log.set_xscale("log")
    ax_log.set_yscale("log")
    # Format SAR column name properly (preserve SAR and psSAR10g acronyms)
    sar_display = sar_column.replace("_mw_kg", "").replace("_", " ")
    # Capitalize properly, preserving SAR and psSAR10g acronyms
    sar_words = sar_display.split()
    sar_formatted = []
    for word in sar_words:
        word_lower = word.lower()
        # Check for psSAR10g in any capitalization variation and fix it
        if "pssar10g" in word_lower:
            # Replace any variation (pssar10g, Pssar10g, PSSAR10G, etc.) with psSAR10g
            sar_formatted.append("psSAR10g")
        elif word.upper() == "SAR":
            sar_formatted.append("SAR")
        else:
            sar_formatted.append(word.capitalize())
    sar_display_final = " ".join(sar_formatted)
    # Final safety check: replace any incorrect psSAR10g capitalization in the final string
    sar_display_final = sar_display_final.replace("Pssar10g", "psSAR10g").replace("PSSAR10g", "psSAR10g").replace("Pssar", "psSAR")
    ax_log.set_xlabel(f"{sar_display_final} (mW kg$^{{-1}}$)")
    ax_log.set_ylabel("Total Mass (kg)")

    # Add extra space to x-axis max value for label visibility
    x_min, x_max = ax_log.get_xlim()
    ax_log.set_xlim(x_min, x_max * 1.15)  # Add 15% extra space on right

    ax_log.grid(True, alpha=0.3)

    # Add bubble size legend with updated scaling
    volumes_legend = plot_df["Total Volume"].values
    vol_min_legend, vol_max_legend = volumes_legend.min(), volumes_legend.max()
    if vol_max_legend > vol_min_legend:
        # Use quantiles for legend sizes
        q25 = plot_df["Total Volume"].quantile(0.25)
        q75 = plot_df["Total Volume"].quantile(0.75)
        vol_max_legend_val = plot_df["Total Volume"].max()

        # Normalize and apply power scaling
        def scale_volume(v):
            """Map volume to marker size with power scaling for  better visual spread."""
            normalized = (v - vol_min_legend) / (vol_max_legend - vol_min_legend) if vol_max_legend > vol_min_legend else 0.5
            return np.power(normalized, 0.75) * 50 + 10

        sizes_for_legend = [scale_volume(q25), scale_volume(q75), scale_volume(vol_max_legend_val)]
        labels_for_legend = [f"{q25 * 1e6:.1e} m$^3$", f"{q75 * 1e6:.1e} m$^3$", f"{vol_max_legend_val * 1e6:.1e} m$^3$"]
    else:
        sizes_for_legend = [30]
        labels_for_legend = [f"{vol_min_legend * 1e6:.1e} m$^3$"]

    legend_elements_log = [
        plt.scatter([], [], s=s, c="gray", alpha=0.7, edgecolors="black", linewidth=0.5, label=label)
        for s, label in zip(sizes_for_legend, labels_for_legend)
    ]
    # Place legend below the plot
    legend_log = ax_log.legend(
        handles=legend_elements_log,
        title="Bubble Size (Volume)",
        loc="upper center",
        bbox_to_anchor=(0.5, -0.15),
        ncol=len(legend_elements_log),
        fontsize=8,
        frameon=True,
        fancybox=False,
        shadow=False,
        edgecolor="black",
        facecolor="white",
        framealpha=1.0,
    )
    legend_log.get_frame().set_linewidth(0.5)
    # Adjust figure to accommodate legend
    fig_log.subplots_adjust(bottom=0.2)

    # Label ALL tissues/organ with smaller fontsize
    for _, row in plot_df.iterrows():
        tissue_clean = self._format_organ_name(row["tissue"])
        ax_log.annotate(
            tissue_clean,
            (row[sar_column], row["Total Mass"]),
            fontsize=5,  # Reduced from 6 to 5
            alpha=0.8,
            textcoords="offset points",
            xytext=(3, 3),
            ha="left",
            bbox=dict(boxstyle="square,pad=0.2", facecolor="white", alpha=0.7, edgecolor="gray", linewidth=0.3),  # No rounded corners
        )

    plt.tight_layout()

    # Create safe filename from sar_column
    sar_name_safe = sar_column.replace("_mw_kg", "").replace("_", "_")
    filename_base_log = f"bubble_mass_vs_{sar_name_safe}_{scenario_name or 'all'}_{frequency_mhz or 'all'}MHz_log"

    # Remove title from plot - will be in caption file
    ax_log.set_title("")  # Remove title

    base_title_log = "Tissue Mass vs SAR Bubble Plot (Log Scale)"
    title_full_log = self._get_title_with_phantom(base_title_log, scenario_name)
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption_log = f"The bubble plot shows tissue mass vs {sar_display_final} with bubble size proportional to tissue volume (log scale on both axes) for the {self._format_scenario_name(scenario_name) if scenario_name else 'all scenarios'} scenario{f' at {frequency_mhz} MHz' if frequency_mhz else ''} for {phantom_name_formatted}."

    filename_log = self._save_figure(fig_log, "bubble", filename_base_log, title=title_full_log, caption=caption_log, dpi=300)

    # Save CSV data
    csv_data = plot_df[["tissue", "Total Mass", "Total Volume", sar_column, "frequency_mhz"]].copy()
    self._save_csv_data(csv_data, "bubble", filename_base_log)
    logging.getLogger("progress").info(
        f"  - Generated bubble plot (log scale): {filename_log}",
        extra={"log_type": "success"},
    )

plot_bubble_mass_vs_sar_interactive

plot_bubble_mass_vs_sar_interactive(organ_results_df: DataFrame, sar_column: str = 'mass_avg_sar_mw_kg', scenario_name: str | None = None)

Creates an interactive bubble plot (plotly) with common axis limits across frequencies.

Uses Plotly for interactive visualization (not affected by scienceplots).

Parameters:

Name Type Description Default
organ_results_df DataFrame

DataFrame with columns: ['tissue', 'Total Mass', 'Total Volume', sar_column, 'frequency_mhz', 'placement']

required
sar_column str

Column name for SAR values (default: 'mass_avg_sar_mw_kg').

'mass_avg_sar_mw_kg'
scenario_name str | None

Optional scenario name for filtering.

None
Source code in goliat/analysis/plots/bubble.py
def plot_bubble_mass_vs_sar_interactive(
    self,
    organ_results_df: pd.DataFrame,
    sar_column: str = "mass_avg_sar_mw_kg",
    scenario_name: str | None = None,
):
    """Creates an interactive bubble plot (plotly) with common axis limits across frequencies.

    Uses Plotly for interactive visualization (not affected by scienceplots).

    Args:
        organ_results_df: DataFrame with columns: ['tissue', 'Total Mass', 'Total Volume',
                      sar_column, 'frequency_mhz', 'placement']
        sar_column: Column name for SAR values (default: 'mass_avg_sar_mw_kg').
        scenario_name: Optional scenario name for filtering.
    """
    try:
        import plotly.graph_objects as go
        from plotly.subplots import make_subplots
    except ImportError:
        logging.getLogger("progress").warning(
            "Plotly not available. Skipping interactive bubble plot. Install with: pip install plotly",
            extra={"log_type": "warning"},
        )
        return

    if organ_results_df.empty:
        return

    plot_df = organ_results_df.copy()
    # Filter out 'All Regions'
    plot_df = self._filter_all_regions(plot_df, tissue_column="tissue")

    if scenario_name:
        plot_df = plot_df[plot_df["scenario"] == scenario_name].copy()

    # Check required columns
    required_cols = ["tissue", "Total Mass", "Total Volume", sar_column, "frequency_mhz"]
    missing_cols = [col for col in required_cols if col not in plot_df.columns]
    if missing_cols:
        logging.getLogger("progress").warning(
            f"Missing columns for interactive bubble plot: {missing_cols}",
            extra={"log_type": "warning"},
        )
        return

    # Remove rows with missing data
    plot_df = plot_df.dropna(subset=required_cols)
    plot_df = plot_df[plot_df["Total Mass"] > 0]
    plot_df = plot_df[plot_df[sar_column] > 0]

    if plot_df.empty:
        return

    # Get common axis limits across all frequencies
    x_min = plot_df[sar_column].min()
    x_max = plot_df[sar_column].max()
    y_min = plot_df["Total Mass"].min()
    y_max = plot_df["Total Mass"].max()

    # Format SAR column name properly (preserve SAR and psSAR10g acronyms)
    sar_display = sar_column.replace("_mw_kg", "").replace("_", " ")
    # Capitalize properly, preserving SAR and psSAR10g acronyms
    sar_words = sar_display.split()
    sar_formatted = []
    for word in sar_words:
        word_lower = word.lower()
        # Check for psSAR10g in any capitalization variation and fix it
        if "pssar10g" in word_lower:
            # Replace any variation (pssar10g, Pssar10g, PSSAR10G, etc.) with psSAR10g
            sar_formatted.append("psSAR10g")
        elif word.upper() == "SAR":
            sar_formatted.append("SAR")
        else:
            sar_formatted.append(word.capitalize())
    sar_display_final = " ".join(sar_formatted)
    # Final safety check: replace any incorrect psSAR10g capitalization in the final string
    sar_display_final = sar_display_final.replace("Pssar10g", "psSAR10g").replace("PSSAR10g", "psSAR10g").replace("Pssar", "psSAR")

    # Get unique frequencies
    frequencies = sorted(plot_df["frequency_mhz"].unique())

    # Create subplots - one per frequency
    n_freqs = len(frequencies)
    cols = min(3, n_freqs)
    rows = (n_freqs + cols - 1) // cols

    fig = make_subplots(
        rows=rows,
        cols=cols,
        subplot_titles=[f"{freq} MHz" for freq in frequencies],
        horizontal_spacing=0.1,
        vertical_spacing=0.12,
    )

    # Color scale for frequencies
    colorscale = "Jet"

    for idx, freq in enumerate(frequencies):
        freq_data = plot_df[plot_df["frequency_mhz"] == freq].copy()

        # Aggregate by tissue (mean across placements if multiple)
        if "placement" in freq_data.columns:
            freq_data = (
                freq_data.groupby("tissue")
                .agg(
                    {
                        "Total Mass": "mean",
                        "Total Volume": "mean",
                        sar_column: "mean",
                    }
                )
                .reset_index()
            )

        row = (idx // cols) + 1
        col = (idx % cols) + 1

        # Scale bubble size - use power of 0.75 (between sqrt and linear) for moderate scaling
        volumes = freq_data["Total Volume"].values
        # Normalize volumes to 0-1 range, then apply power scaling
        vol_min, vol_max = volumes.min(), volumes.max()
        if vol_max > vol_min:
            normalized_volumes = (volumes - vol_min) / (vol_max - vol_min)
            bubble_sizes = np.power(normalized_volumes, 0.75) * 50 + 10  # Scale to 10-60 range
        else:
            bubble_sizes = np.full(len(volumes), 30)  # Default size if all same

        fig.add_trace(
            go.Scatter(
                x=freq_data[sar_column],
                y=freq_data["Total Mass"],
                mode="markers",
                marker=dict(
                    size=bubble_sizes,
                    sizemode="diameter",
                    sizeref=1.0,  # Direct size reference
                    sizemin=4,
                    color=freq,
                    colorscale=colorscale,
                    showscale=(idx == 0),
                    colorbar=dict(title="Frequency (MHz)") if idx == 0 else None,
                    line=dict(width=0.5, color="black"),
                ),
                text=[self._format_organ_name(t) for t in freq_data["tissue"]],
                hovertemplate="<b>%{text}</b><br>"
                + f"{sar_display_final}: %{{x:.2f}} mW/kg<br>"
                + "Mass: %{y:.4f} kg<br>"
                + "Volume: %{marker.size:.2e} m³<extra></extra>",
                name=f"{freq} MHz",
                showlegend=False,
            ),
            row=row,
            col=col,
        )

        # Set common axis limits
        fig.update_xaxes(
            type="log",
            range=[np.log10(x_min * 0.9), np.log10(x_max * 1.1)],
            title_text=f"{sar_display_final} (mW/kg)",
            row=row,
            col=col,
        )
        fig.update_yaxes(
            type="log",
            range=[np.log10(y_min * 0.9), np.log10(y_max * 1.1)],
            title_text="Total Mass (kg)",
            row=row,
            col=col,
        )

    # Update layout
    base_title = "Tissue Mass vs SAR Bubble Plot (Interactive)"
    title_with_phantom = self._get_title_with_phantom(base_title, scenario_name)
    # Don't set title on plot - will be in caption file
    fig.update_layout(
        title="",
        height=300 * rows,
        showlegend=False,
    )

    subdir = self._get_subdir("bubble")
    sar_name_safe = sar_column.replace("_mw_kg", "").replace("_", "_")
    filename = f"bubble_mass_vs_{sar_name_safe}_{scenario_name or 'all'}_interactive.html"
    fig.write_html(os.path.join(subdir, filename))

    # Create caption file for HTML plot
    caption_filename = filename.replace(".html", ".txt")
    caption_path = os.path.join(subdir, caption_filename)
    # Format SAR column name properly for caption (preserve SAR and psSAR10g acronyms)
    sar_display_interactive = sar_column.replace("_mw_kg", "").replace("_", " ")
    sar_words_interactive = sar_display_interactive.split()
    sar_formatted_interactive = []
    for word in sar_words_interactive:
        word_lower = word.lower()
        # Check for psSAR10g in any capitalization variation and fix it
        if "pssar10g" in word_lower:
            # Replace any variation (pssar10g, Pssar10g, PSSAR10G, etc.) with psSAR10g
            sar_formatted_interactive.append("psSAR10g")
        elif word.upper() == "SAR":
            sar_formatted_interactive.append("SAR")
        else:
            sar_formatted_interactive.append(word.capitalize())
    sar_display_final_interactive = " ".join(sar_formatted_interactive)
    # Final safety check: replace any incorrect psSAR10g capitalization in the final string
    sar_display_final_interactive = (
        sar_display_final_interactive.replace("Pssar10g", "psSAR10g").replace("PSSAR10g", "psSAR10g").replace("Pssar", "psSAR")
    )
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"Interactive bubble plot showing tissue mass vs {sar_display_final_interactive} with bubble size proportional to tissue volume (log scale on both axes) for the {self._format_scenario_name(scenario_name) if scenario_name else 'all scenarios'} scenario for {phantom_name_formatted}. Each subplot corresponds to a different frequency, with common axis limits for comparison."
    with open(caption_path, "w", encoding="utf-8") as f:
        f.write(f"Title: {title_with_phantom}\n\n")
        f.write(f"Caption: {caption}\n")

    logging.getLogger("progress").info(
        f"  - Generated interactive bubble plot: {filename}",
        extra={"log_type": "success"},
    )

goliat.analysis.plots.cdf.CdfPlotter

CdfPlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Bases: BasePlotter

Generates CDF plots for SAR analysis.

Source code in goliat/analysis/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

plot_cdf

plot_cdf(results_df: DataFrame, metric: str, group_by: str | list[str] | None = None, scenario_name: str | None = None, frequency_mhz: int | None = None)

Creates CDF plot for a metric with optional aggregation by independent variables.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with simulation results.

required
metric str

Column name for the metric to plot.

required
group_by str | list[str] | None

Column name(s) to group by for multiple CDF lines (e.g., 'scenario', 'frequency_mhz', 'placement'). Can be a single string or list of strings. If None, plots single CDF.

None
scenario_name str | None

Optional scenario name for filtering.

None
frequency_mhz int | None

Optional frequency for filtering.

None
Source code in goliat/analysis/plots/cdf.py
def plot_cdf(
    self,
    results_df: pd.DataFrame,
    metric: str,
    group_by: str | list[str] | None = None,
    scenario_name: str | None = None,
    frequency_mhz: int | None = None,
):
    """Creates CDF plot for a metric with optional aggregation by independent variables.

    Args:
        results_df: DataFrame with simulation results.
        metric: Column name for the metric to plot.
        group_by: Column name(s) to group by for multiple CDF lines (e.g., 'scenario', 'frequency_mhz', 'placement').
                 Can be a single string or list of strings. If None, plots single CDF.
        scenario_name: Optional scenario name for filtering.
        frequency_mhz: Optional frequency for filtering.
    """
    if metric not in results_df.columns:
        logging.getLogger("progress").warning(
            f"Metric '{metric}' not found for CDF plot.",
            extra={"log_type": "warning"},
        )
        return

    plot_df = results_df.copy()

    # Filter by scenario if provided
    if scenario_name:
        plot_df = plot_df[plot_df["scenario"] == scenario_name].copy()

    # Filter by frequency if provided
    if frequency_mhz is not None:
        plot_df = plot_df[plot_df["frequency_mhz"] == frequency_mhz].copy()

    # Remove missing values
    plot_df = plot_df.dropna(subset=[metric])
    plot_df = plot_df[plot_df[metric] > 0]  # Only positive values

    if plot_df.empty:
        return

    fig, ax = plt.subplots(figsize=(3.5, 2.5))  # IEEE single-column width

    # If group_by is specified, create multiple CDF lines
    if group_by:
        if isinstance(group_by, str):
            group_by = [group_by]

        # Get unique combinations of grouping variables
        if all(col in plot_df.columns for col in group_by):
            groups = plot_df.groupby(group_by)

            # Generate colors and linestyles for each group using academic palettes
            n_groups = len(groups)
            colors = self._get_academic_colors(n_groups)
            linestyles = self._get_academic_linestyles(n_groups)

            formatted_labels = []
            handles_list = []
            for idx, ((group_vals, group_df), color) in enumerate(zip(groups, colors)):
                if isinstance(group_vals, tuple):
                    # Format each value to be human readable
                    formatted_vals = []
                    for col, val in zip(group_by, group_vals):
                        # Format value based on column type
                        if col == "frequency_mhz":
                            formatted_vals.append(f"{val} MHz")
                        elif col == "scenario":
                            val_formatted = (
                                self._format_organ_name(str(val))
                                if hasattr(self, "_format_organ_name")
                                else str(val).replace("_", " ").title()
                            )
                            formatted_vals.append(val_formatted)
                        else:
                            val_formatted = (
                                self._format_organ_name(str(val))
                                if hasattr(self, "_format_organ_name")
                                else str(val).replace("_", " ").title()
                            )
                            formatted_vals.append(val_formatted)
                    label = " | ".join(formatted_vals)
                else:
                    # Format single value
                    if group_by[0] == "frequency_mhz":
                        label = f"{group_vals} MHz"
                    elif group_by[0] == "scenario":
                        label = (
                            self._format_organ_name(str(group_vals))
                            if hasattr(self, "_format_organ_name")
                            else str(group_vals).replace("_", " ").title()
                        )
                    else:
                        label = (
                            self._format_organ_name(str(group_vals))
                            if hasattr(self, "_format_organ_name")
                            else str(group_vals).replace("_", " ").title()
                        )

                formatted_labels.append(label)

                # Calculate CDF
                sorted_values = np.sort(group_df[metric].values)
                n = len(sorted_values)
                y = np.arange(1, n + 1) / n

                line = ax.plot(sorted_values, y, label=label, linewidth=2, color=color, linestyle=linestyles[idx], alpha=0.8)
                handles_list.append(line[0])

            # Place legend below plot - use 2 columns for frequencies or when there are 4 items
            from .line import LinePlotter

            line_plotter = LinePlotter(self.plots_dir, self.phantom_name, self.plot_format)
            # Use 2 columns for frequencies, or when there are 4 items for balanced layout
            n_cols = (
                2
                if (
                    (isinstance(group_by, list) and "frequency_mhz" in group_by)
                    or (isinstance(group_by, str) and group_by == "frequency_mhz")
                    or len(formatted_labels) == 4
                )
                else min(3, len(formatted_labels))
            )
            line_plotter._place_legend_below(
                fig, ax, len(formatted_labels), n_cols=n_cols, handles=handles_list, labels=formatted_labels
            )

            # Add n= label - use max sample size across groups
            max_n = max(len(group_df) for _, group_df in groups)
            ax.text(
                0.95,
                0.95,
                f"n = {max_n}",
                transform=ax.transAxes,
                fontsize=8,
                verticalalignment="top",
                horizontalalignment="right",
                bbox=dict(boxstyle="square,pad=0.4", facecolor="white", edgecolor="black", linewidth=0.5, alpha=1.0),
            )
        else:
            # Fallback: single CDF
            sorted_values = np.sort(plot_df[metric].values)
            n = len(sorted_values)
            y = np.arange(1, n + 1) / n
            ax.plot(sorted_values, y, linewidth=2)
    else:
        # Single CDF
        sorted_values = np.sort(plot_df[metric].values)
        n = len(sorted_values)
        y = np.arange(1, n + 1) / n
        ax.plot(sorted_values, y, linewidth=2)

    metric_label = METRIC_LABELS.get(metric, metric.replace("_", " ").title())
    ax.set_xlabel(f"{metric_label} (mW kg$^{{-1}}$)")
    ax.set_ylabel("Cumulative Probability")

    # xlim should start at 0
    if ax.get_lines():
        x_max = 0
        for line in ax.get_lines():
            x_data = line.get_xdata()
            if len(x_data) > 0:
                x_max = max(x_max, x_data.max())
        ax.set_xlim(0, x_max * 1.05)

    # For CDF plots, y-axis should start at first y value (not 0) and go to 1.0
    y_min = 0.0  # Default value
    if ax.get_lines():
        # Get all y values from plotted lines
        y_min = 1.0
        for line in ax.get_lines():
            y_data = line.get_ydata()
            if len(y_data) > 0:
                y_min = min(y_min, y_data[0])
        ax.set_ylim(y_min, 1.0)
    else:
        # Fallback if no lines
        ax.set_ylim(0, 1.0)

    # Add inset for "all scenarios, all frequencies" plots to zoom in on non-outliers
    # Detect if this is an "all_allMHz" plot (scenario_name is None and frequency_mhz is None)
    is_all_all_plot = scenario_name is None and frequency_mhz is None and group_by

    if is_all_all_plot and ax.get_lines() and len(ax.get_lines()) > 1:
        from mpl_toolkits.axes_grid1.inset_locator import inset_axes

        # Get max x value for each line to detect outlier
        line_maxes = []
        for line in ax.get_lines():
            x_data = line.get_xdata()
            if len(x_data) > 0:
                line_maxes.append((x_data.max(), line))

        if len(line_maxes) >= 2:
            # Sort by max value
            line_maxes.sort(key=lambda x: x[0], reverse=True)
            max_val = line_maxes[0][0]
            second_max = line_maxes[1][0]

            # Check if there's an outlier (max is > 2x the second highest)
            if max_val > second_max * 2.0:
                # Create inset zoomed to the non-outlier range
                ax_inset = inset_axes(ax, width="40%", height="40%", loc="lower right", borderpad=1.5)

                # Replot all lines in the inset with reduced linewidth
                colors = self._get_academic_colors(len(ax.get_lines()))
                linestyles = self._get_academic_linestyles(len(ax.get_lines()))
                for idx, line in enumerate(ax.get_lines()):
                    x_data = line.get_xdata()
                    y_data = line.get_ydata()
                    ax_inset.plot(x_data, y_data, linewidth=1, color=colors[idx], linestyle=linestyles[idx], alpha=0.8)

                # Set inset limits to zoom on non-outlier data (up to 95th percentile of second highest)
                # Use second_max * 1.1 as max x to include some margin
                inset_x_max = second_max * 1.1
                ax_inset.set_xlim(0, inset_x_max)
                ax_inset.set_ylim(y_min, 1.0)
                ax_inset.tick_params(labelsize=6)
                ax_inset.grid(True, alpha=0.3)
                ax_inset.set_title("Zoomed (excl. outlier)", fontsize=7, pad=2)

    # Add n= label for single CDF
    if not group_by:
        n_samples = len(plot_df)
        ax.text(
            0.95,
            0.95,
            f"n = {n_samples}",
            transform=ax.transAxes,
            fontsize=8,
            verticalalignment="top",
            horizontalalignment="right",
            bbox=dict(boxstyle="square,pad=0.4", facecolor="white", edgecolor="black", linewidth=0.5, alpha=1.0),
        )

    ax.grid(True, alpha=0.3, which="both")

    # Create title with phantom name - format as sentence without colons or underscores
    metric_label = METRIC_LABELS.get(metric, metric.replace("_", " ").title())
    # Format scenario name to remove underscores
    formatted_scenario = self._format_scenario_name(scenario_name) if scenario_name else None
    # Build title parts - no colon, flow as sentence
    if formatted_scenario:
        if frequency_mhz:
            base_title = f"cumulative distribution function for {metric_label} in {formatted_scenario} scenario at {frequency_mhz} MHz"
        else:
            base_title = f"cumulative distribution function for {metric_label} in {formatted_scenario} scenario"
    else:
        if frequency_mhz:
            base_title = f"cumulative distribution function for {metric_label} at {frequency_mhz} MHz"
        else:
            base_title = f"cumulative distribution function for {metric_label}"
    title_full = self._get_title_with_phantom(base_title)
    # Don't set title on plot - will be in caption file

    plt.tight_layout()

    metric_safe = metric.replace("SAR", "").replace("psSAR10g_", "").replace("_", "_")
    group_suffix = "_".join(group_by) if group_by else "all"
    scenario_suffix = scenario_name or "all"
    freq_suffix = f"{frequency_mhz}MHz" if frequency_mhz else "allMHz"
    filename_base = f"cdf_{metric_safe}_{group_suffix}_{scenario_suffix}_{freq_suffix}"
    # Format group_by for caption - replace underscores and format nicely
    if group_by:
        if isinstance(group_by, str):
            group_by_list = [group_by]
        else:
            group_by_list = group_by
        # Format each group_by item - replace frequency_mhz with frequency, format others
        formatted_groups = []
        for gb in group_by_list:
            if gb == "frequency_mhz":
                formatted_groups.append("frequency")
            elif gb == "scenario":
                formatted_groups.append("scenario")
            else:
                # Format other group_by columns nicely
                formatted_groups.append(gb.replace("_", " "))
        group_text = ", ".join(formatted_groups)
        group_suffix_text = f"Grouped by {group_text}."
    else:
        group_suffix_text = ""
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The cumulative distribution function (CDF) plot shows the probability distribution of {metric_label} values for {phantom_name_formatted}. {group_suffix_text}"
    filename = self._save_figure(fig, "cdf", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data - save the raw plot data
    csv_data = plot_df[[metric]].copy()
    if group_by:
        if isinstance(group_by, str):
            group_by = [group_by]
        for col in group_by:
            if col in plot_df.columns:
                csv_data[col] = plot_df[col]
    self._save_csv_data(csv_data, "cdf", filename_base)
    logging.getLogger("progress").info(
        f"  - Generated CDF plot: {filename}",
        extra={"log_type": "success"},
    )

goliat.analysis.plots.correlation.CorrelationPlotter

CorrelationPlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Bases: BasePlotter

Generates correlation plots for SAR analysis.

Source code in goliat/analysis/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

plot_correlation_head_vs_eye_sar

plot_correlation_head_vs_eye_sar(results_df: DataFrame, scenario_name: str = 'front_of_eyes')

Creates scatter plot showing correlation between Head SAR and Eye psSAR10g with linear regression.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with columns: ['SAR_head', 'psSAR10g_eyes', 'frequency_mhz', 'scenario']

required
scenario_name str

Scenario to filter for (default: 'front_of_eyes').

'front_of_eyes'
Source code in goliat/analysis/plots/correlation.py
def plot_correlation_head_vs_eye_sar(
    self,
    results_df: pd.DataFrame,
    scenario_name: str = "front_of_eyes",
):
    """Creates scatter plot showing correlation between Head SAR and Eye psSAR10g with linear regression.

    Args:
        results_df: DataFrame with columns: ['SAR_head', 'psSAR10g_eyes', 'frequency_mhz', 'scenario']
        scenario_name: Scenario to filter for (default: 'front_of_eyes').
    """
    from scipy import stats

    if scenario_name:
        plot_df = results_df[results_df["scenario"] == scenario_name].copy()
    else:
        plot_df = results_df.copy()

    # Check if columns exist
    if "SAR_head" not in plot_df.columns or "psSAR10g_eyes" not in plot_df.columns:
        logging.getLogger("progress").warning(
            f"Missing required columns for head vs eye correlation plot: "
            f"{'SAR_head ' if 'SAR_head' not in plot_df.columns else ''}"
            f"{'psSAR10g_eyes' if 'psSAR10g_eyes' not in plot_df.columns else ''}",
            extra={"log_type": "warning"},
        )
        return

    plot_df["SAR_head"] = pd.to_numeric(plot_df["SAR_head"], errors="coerce")
    plot_df["psSAR10g_eyes"] = pd.to_numeric(plot_df["psSAR10g_eyes"], errors="coerce")
    correlation_df = plot_df.dropna(subset=["SAR_head", "psSAR10g_eyes"])

    if correlation_df.empty:
        logging.getLogger("progress").warning(
            f"No valid data for correlation plot (scenario: {scenario_name})",
            extra={"log_type": "warning"},
        )
        return

    # Perform linear regression
    slope, intercept, r_value, p_value, std_err = stats.linregress(correlation_df["SAR_head"], correlation_df["psSAR10g_eyes"])
    r_squared = r_value**2

    fig, ax = plt.subplots(figsize=(3.5, 2.5))  # IEEE single-column width

    # Scatter plot colored by frequency
    if "frequency_mhz" in correlation_df.columns:
        scatter = ax.scatter(
            correlation_df["SAR_head"],
            correlation_df["psSAR10g_eyes"],
            c=correlation_df["frequency_mhz"],
            cmap="jet",
            s=30,
            alpha=0.7,
        )
        cbar = plt.colorbar(scatter, ax=ax)
        cbar.set_label("Frequency (MHz)")
    else:
        ax.scatter(correlation_df["SAR_head"], correlation_df["psSAR10g_eyes"], s=30, alpha=0.7)

    # Plot regression line
    x_vals = np.array(ax.get_xlim())
    y_vals = intercept + slope * x_vals
    ax.plot(x_vals, y_vals, "--", color="red", linewidth=2, label=f"Linear Fit (R²={r_squared:.4f})")

    formatted_scenario = self._format_scenario_name(scenario_name)
    base_title = "correlation between head SAR and eye psSAR10g"
    title_full = self._get_title_with_phantom(base_title, scenario_name)
    # Don't set title on plot - will be in caption file
    ax.set_xlabel(self._format_axis_label("Normalized head SAR", r"mW kg$^{-1}$"))
    ax.set_ylabel(self._format_axis_label("Normalized psSAR10g eyes", r"mW kg$^{-1}$"))

    # Add R² value annotation
    ax.text(
        0.98,
        0.98,
        f"R² = {r_squared:.4f}\np = {p_value:.4f}",
        transform=ax.transAxes,
        fontsize=8,
        verticalalignment="top",
        horizontalalignment="right",
        bbox=dict(boxstyle="square", facecolor="white", edgecolor="black", linewidth=0.5, pad=0.3),
    )

    ax.legend()
    ax.grid(True, alpha=0.3)

    plt.tight_layout()

    filename_base = f"correlation_head_vs_eye_sar_{scenario_name}"
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The scatter plot shows the correlation between normalized head SAR and normalized eye psSAR10g values for the {formatted_scenario} scenario for {phantom_name_formatted}. Points are colored by frequency. The red dashed line shows the linear fit with R² and p-value annotations."
    filename = self._save_figure(fig, "correlation", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = correlation_df[["SAR_head", "psSAR10g_eyes"]].copy()
    if "frequency_mhz" in correlation_df.columns:
        csv_data["frequency_mhz"] = correlation_df["frequency_mhz"]
    self._save_csv_data(csv_data, "correlation", filename_base)
    logging.getLogger("progress").info(
        f"  - Generated correlation plot: {filename}",
        extra={"log_type": "success"},
    )

plot_tissue_group_correlation_matrix

plot_tissue_group_correlation_matrix(results_df: DataFrame, scenario_name: str | None = None)

Creates heatmap showing correlation coefficients between different tissue group SAR values.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with tissue group SAR columns (SAR_eyes, SAR_brain, etc.)

required
scenario_name str | None

Optional scenario name for filtering.

None
Source code in goliat/analysis/plots/correlation.py
def plot_tissue_group_correlation_matrix(
    self,
    results_df: pd.DataFrame,
    scenario_name: str | None = None,
):
    """Creates heatmap showing correlation coefficients between different tissue group SAR values.

    Args:
        results_df: DataFrame with tissue group SAR columns (SAR_eyes, SAR_brain, etc.)
        scenario_name: Optional scenario name for filtering.
    """
    # Filter by scenario if provided
    if scenario_name:
        plot_df = results_df[results_df["scenario"] == scenario_name].copy()
    else:
        plot_df = results_df.copy()

    # Find all SAR columns
    sar_cols = [col for col in plot_df.columns if col.startswith("SAR_") or col.startswith("psSAR10g_")]
    sar_cols = [col for col in sar_cols if col in plot_df.columns]

    # Exclude columns that are all NaN
    valid_sar_cols = []
    for col in sar_cols:
        if not plot_df[col].isna().all():
            valid_sar_cols.append(col)

    if len(valid_sar_cols) < 2:
        logging.getLogger("progress").warning(
            "Not enough valid SAR columns for correlation matrix.",
            extra={"log_type": "warning"},
        )
        return

    # Convert pd.NA to np.nan and drop rows with all NaN
    sar_data = plot_df[valid_sar_cols].copy()
    sar_data = sar_data.replace(pd.NA, np.nan)
    sar_data = sar_data.dropna(how="all")

    if sar_data.empty or len(sar_data) < 2:
        logging.getLogger("progress").warning(
            "Not enough valid data for correlation matrix.",
            extra={"log_type": "warning"},
        )
        return

    # Calculate correlation matrix (only numeric columns)
    # Use pairwise deletion to handle missing values better
    correlation_matrix = sar_data.corr(method="pearson", min_periods=2)

    # Create human-readable labels for columns
    def get_human_readable_label(col_name):
        """Convert column name to human-readable label."""
        # Try METRIC_LABELS first (full labels)
        if col_name in METRIC_LABELS:
            return METRIC_LABELS[col_name]
        # Try LEGEND_LABELS (trimmed labels)
        if col_name in LEGEND_LABELS:
            label = LEGEND_LABELS[col_name]
            # Add "SAR" or "psSAR10g" prefix if needed for clarity
            if col_name.startswith("SAR_"):
                return f"{label} SAR"
            elif col_name.startswith("psSAR10g_"):
                return f"psSAR10g {label}"
            return label
        # Fallback: format the column name
        return col_name.replace("SAR_", "").replace("psSAR10g_", "psSAR10g ").replace("_", " ").title()

    # Rename columns and index with human-readable labels
    correlation_matrix_labeled = correlation_matrix.copy()
    readable_labels = [get_human_readable_label(col) for col in correlation_matrix.columns]
    correlation_matrix_labeled.columns = readable_labels
    correlation_matrix_labeled.index = readable_labels

    # Create heatmap
    fig, ax = plt.subplots(figsize=(7.16, 5.5))  # IEEE two-column width for correlation matrix
    sns.heatmap(
        correlation_matrix_labeled,
        annot=True,
        fmt=".3f",
        cmap="RdBu_r",
        center=0,
        vmin=-1,
        vmax=1,
        square=True,
        linewidths=0.5,
        cbar_kws={"label": "Correlation Coefficient"},
        ax=ax,
    )

    base_title = "tissue group correlation matrix"
    title_full = self._get_title_with_phantom(base_title, scenario_name)
    # Don't set title on plot - will be in caption file
    plt.tight_layout()

    filename_base = f"correlation_matrix_tissue_groups_{scenario_name}" if scenario_name else "correlation_matrix_tissue_groups"
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The heatmap shows Pearson correlation coefficients between different tissue group SAR values for the {self._format_scenario_name(scenario_name) if scenario_name else 'all scenarios'} scenario for {phantom_name_formatted}. Values range from -1 (perfect negative correlation) to +1 (perfect positive correlation)."
    filename = self._save_figure(fig, "correlation", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data
    self._save_csv_data(correlation_matrix, "correlation", filename_base)
    logging.getLogger("progress").info(
        f"  - Generated correlation matrix: {filename}",
        extra={"log_type": "success"},
    )

goliat.analysis.plots.heatmap.HeatmapPlotter

HeatmapPlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Bases: BasePlotter

Generates heatmap plots for SAR analysis.

Source code in goliat/analysis/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

plot_sar_heatmap

plot_sar_heatmap(organ_df: DataFrame, group_df: DataFrame, tissue_groups: dict)

Creates separate heatmaps for Min, Avg, and Max SAR per tissue and frequency.

Generates three separate heatmaps instead of a combined summary. Each heatmap has two panels: top shows individual tissues, bottom shows group summaries. Uses log-scale colormap for better visibility.

Source code in goliat/analysis/plots/heatmap.py
def plot_sar_heatmap(self, organ_df: pd.DataFrame, group_df: pd.DataFrame, tissue_groups: dict):
    """Creates separate heatmaps for Min, Avg, and Max SAR per tissue and frequency.

    Generates three separate heatmaps instead of a combined summary.
    Each heatmap has two panels: top shows individual tissues, bottom shows group summaries.
    Uses log-scale colormap for better visibility.
    """
    # Generate separate heatmaps for min, avg, and max
    self._plot_sar_heatmap_single(organ_df, group_df, tissue_groups, "min_sar", "Min")
    self._plot_sar_heatmap_single(organ_df, group_df, tissue_groups, "avg_sar", "Avg")
    self._plot_sar_heatmap_single(organ_df, group_df, tissue_groups, "max_sar", "Max")

plot_peak_sar_heatmap

plot_peak_sar_heatmap(organ_df: DataFrame, group_df: DataFrame, tissue_groups: dict, value_col: str = 'peak_sar_10g_mw_kg', title: str = 'Peak SAR')

Creates a heatmap for peak SAR values across tissues and frequencies.

Similar structure to plot_sar_heatmap but focused on peak SAR metrics. Shows individual tissues and group summaries in separate panels. 'All Regions' is excluded as it's a whole-body aggregate, not a real tissue.

Parameters:

Name Type Description Default
organ_df DataFrame

DataFrame with organ-level peak SAR data.

required
group_df DataFrame

DataFrame with group-level summaries.

required
tissue_groups dict

Dict mapping groups to tissue lists.

required
value_col str

Column name containing the peak SAR values.

'peak_sar_10g_mw_kg'
title str

Title for the plot.

'Peak SAR'
Source code in goliat/analysis/plots/heatmap.py
def plot_peak_sar_heatmap(
    self,
    organ_df: pd.DataFrame,
    group_df: pd.DataFrame,
    tissue_groups: dict,
    value_col: str = "peak_sar_10g_mw_kg",
    title: str = "Peak SAR",
):
    """Creates a heatmap for peak SAR values across tissues and frequencies.

    Similar structure to plot_sar_heatmap but focused on peak SAR metrics.
    Shows individual tissues and group summaries in separate panels.
    'All Regions' is excluded as it's a whole-body aggregate, not a real tissue.

    Args:
        organ_df: DataFrame with organ-level peak SAR data.
        group_df: DataFrame with group-level summaries.
        tissue_groups: Dict mapping groups to tissue lists.
        value_col: Column name containing the peak SAR values.
        title: Title for the plot.
    """
    # Filter out 'All Regions' - it's a whole-body aggregate, not a real tissue
    organ_df = self._filter_all_regions(organ_df, tissue_column="tissue")

    # Clean and format tissue names before pivoting (remove phantom identifiers and format for display)
    organ_df_clean = organ_df.copy()
    organ_df_clean["tissue"] = organ_df_clean["tissue"].apply(lambda x: self._format_organ_name(x))

    organ_pivot = organ_df_clean.pivot_table(index="tissue", columns="frequency_mhz", values=value_col)
    organ_pivot = organ_pivot.loc[(organ_pivot > 0.01).any(axis=1)]
    mean_organ_sar = organ_pivot.mean(axis=1).sort_values(ascending=False)
    organ_pivot = organ_pivot.reindex(mean_organ_sar.index)

    group_pivot = group_df.pivot_table(index="group", columns="frequency_mhz", values=value_col)
    if isinstance(group_pivot, pd.DataFrame) and not group_pivot.empty:
        mean_group_sar = group_pivot.mean(axis=1)
        if isinstance(mean_group_sar, pd.Series):
            mean_group_sar = mean_group_sar.sort_values(ascending=False)
            group_pivot = group_pivot.reindex(mean_group_sar.index)

    if organ_pivot.empty:
        return

    # Use two-column width for wide heatmaps, scale height dynamically based on content
    # Calculate height: base height + height per row (with reduced row height for compact cells)
    min_row_height = 0.25  # Reduced from 0.35 - minimum inches per row for readability
    base_height = 2.0  # Base height for titles, spacing, group summary
    organ_height = max(len(organ_pivot) * min_row_height, len(organ_pivot) * 0.08)  # Reduced from 0.12 - dynamic per-row height
    group_height = max(len(group_pivot) * 0.25, 0.8) if not group_pivot.empty else 0  # Reduced from 0.4 and 1.0
    total_height = base_height + organ_height + group_height
    fig = plt.figure(figsize=(7.16, total_height))
    gs = gridspec.GridSpec(
        2,
        2,
        height_ratios=[len(organ_pivot), len(group_pivot) + 1],
        width_ratios=[0.95, 0.05],
        hspace=0.1,
    )
    ax_organ = fig.add_subplot(gs[0, 0])
    ax_group = fig.add_subplot(gs[1, 0])
    cbar_ax = fig.add_subplot(gs[:, 1])

    # Create title with phantom name
    base_title = f"{title} (mW kg$^{{-1}}$) per tissue"
    title_with_phantom = self._get_title_with_phantom(base_title)

    # Plot organ heatmap without title
    sns.heatmap(
        organ_pivot,
        ax=ax_organ,
        annot=True,
        fmt=".2f",
        cmap="jet",
        linewidths=0.5,
        norm=LogNorm(vmin=organ_pivot[organ_pivot > 0].min().min(), vmax=organ_pivot.max().max()),
        cbar=True,
        cbar_ax=cbar_ax,
        xticklabels=False,  # Remove x tickmarks
        yticklabels=True,  # Keep y labels but reduce fontsize
        square=False,  # Allow rectangular cells for more compact vertical layout
    )
    ax_organ.set_xlabel("")
    ax_organ.set_ylabel("Tissue")
    ax_organ.tick_params(labelsize=6, which="minor", length=0)  # Reduced fontsize, no minor ticks

    # Color tissue labels by group
    group_colors_peak = {"eyes": "red", "skin": "green", "brain": "blue", "genitals": "purple"}
    tissue_to_group = {}
    for group, tissues in tissue_groups.items():
        for tissue in tissues:
            tissue_clean = self._format_organ_name(tissue)
            tissue_to_group[tissue_clean] = group.lower().replace("_group", "").replace("group", "")

    for tick_label in ax_organ.get_yticklabels():
        tissue_name = tick_label.get_text()
        group_name = tissue_to_group.get(tissue_name, "")
        if group_name in group_colors_peak:
            tick_label.set_color(group_colors_peak[group_name])
        tick_label.set_fontsize(6)  # Reduced fontsize

    # Plot group summary without title
    sns.heatmap(
        group_pivot,
        ax=ax_group,
        annot=True,
        fmt=".2f",
        cmap="jet",
        linewidths=0.5,
        norm=LogNorm(vmin=group_pivot[group_pivot > 0].min().min(), vmax=group_pivot.max().max()) if not group_pivot.empty else None,
        cbar=False,
        xticklabels=False,  # Remove x tickmarks
        yticklabels=True,  # Keep y labels but reduce fontsize
        square=False,  # Allow rectangular cells for more compact vertical layout
    )
    ax_group.set_xlabel(self._format_axis_label("Frequency", "MHz"))
    ax_group.set_ylabel("")
    ax_group.tick_params(labelsize=6, which="minor", length=0)  # Reduced fontsize, no minor ticks
    # Color group labels
    for tick_label in ax_group.get_yticklabels():
        tick_label.set_rotation(0)
        group_name = tick_label.get_text().lower().replace("_group", "").replace("group", "")
        if group_name in group_colors_peak:
            tick_label.set_color(group_colors_peak[group_name])
        tick_label.set_fontsize(6)  # Reduced fontsize

    plt.tight_layout(rect=(0, 0, 0.95, 0.98))
    filename_base = f"heatmap_{value_col}_summary"
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The heatmap shows {title} values per tissue across frequencies for {phantom_name_formatted}. The top panel shows individual tissues, and the bottom panel shows organ group summaries. Tissues are colored by group (red=eyes, green=skin, blue=brain, purple=genitals)."
    filename = self._save_figure(fig, "heatmap", filename_base, title=title_with_phantom, caption=caption, dpi=300)
    logging.getLogger("progress").info(
        f"  - Generated {title} heatmap: {filename}",
        extra={"log_type": "success"},
    )

    # Also create HTML version
    try:
        import plotly.graph_objects as go
        from plotly.subplots import make_subplots

        # Create HTML version
        fig_html = make_subplots(
            rows=2,
            cols=1,
            subplot_titles=["", ""],  # Remove subplot titles
            vertical_spacing=0.15,
        )

        # Organ heatmap
        z_min_organ = organ_pivot[organ_pivot > 0].min().min() if (organ_pivot > 0).any().any() else 0.01
        z_max_organ = organ_pivot.max().max()
        fig_html.add_trace(
            go.Heatmap(
                z=organ_pivot.values,
                x=organ_pivot.columns.tolist(),
                y=organ_pivot.index.tolist(),
                colorscale="Jet",
                zmin=z_min_organ,
                zmax=z_max_organ,
                colorbar=dict(title=f"{title} (mW/kg)", len=0.5, y=0.75),
                text=organ_pivot.values,
                texttemplate="%{text:.2f}",
                textfont={"size": 8},
            ),
            row=1,
            col=1,
        )

        # Group heatmap
        if not group_pivot.empty:
            z_min_group = group_pivot[group_pivot > 0].min().min() if (group_pivot > 0).any().any() else 0.01
            z_max_group = group_pivot.max().max()
            fig_html.add_trace(
                go.Heatmap(
                    z=group_pivot.values,
                    x=group_pivot.columns.tolist(),
                    y=group_pivot.index.tolist(),
                    colorscale="Jet",
                    zmin=z_min_group,
                    zmax=z_max_group,
                    colorbar=dict(title=f"{title} (mW/kg)", len=0.5, y=0.25),
                    text=group_pivot.values,
                    texttemplate="%{text:.2f}",
                    textfont={"size": 10},
                ),
                row=2,
                col=1,
            )

        fig_html.update_layout(
            title=self._get_title_with_phantom(f"{title} per tissue"),
            height=600 + len(organ_pivot) * 15,
        )

        subdir = self._get_subdir("heatmap")
        html_filename = f"heatmap_{value_col}_summary.html"
        fig_html.write_html(os.path.join(subdir, html_filename))
        logging.getLogger("progress").info(
            f"  - Generated {title} heatmap (HTML): {html_filename}",
            extra={"log_type": "success"},
        )
    except ImportError:
        logging.getLogger("progress").warning(
            "Plotly not available. Skipping HTML heatmap. Install with: pip install plotly",
            extra={"log_type": "warning"},
        )

plot_far_field_direction_polarization_heatmap

plot_far_field_direction_polarization_heatmap(results_df: DataFrame, metric: str = 'SAR_whole_body', frequency_mhz: int | None = None)

Creates a heatmap comparing SAR values across incident directions and polarizations.

This visualization is specific to far-field analysis where simulations are run for different incident wave directions (from left, right, front, back, above, below) and polarizations (theta, phi). The heatmap shows where SAR is highest and lowest.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with 'placement' column containing direction/polarization info.

required
metric str

SAR metric to plot (default: 'SAR_whole_body').

'SAR_whole_body'
frequency_mhz int | None

Optional frequency to filter. If None, averages across all frequencies.

None
Source code in goliat/analysis/plots/heatmap.py
def plot_far_field_direction_polarization_heatmap(
    self,
    results_df: pd.DataFrame,
    metric: str = "SAR_whole_body",
    frequency_mhz: int | None = None,
):
    """Creates a heatmap comparing SAR values across incident directions and polarizations.

    This visualization is specific to far-field analysis where simulations are run
    for different incident wave directions (from left, right, front, back, above, below) and polarizations
    (theta, phi). The heatmap shows where SAR is highest and lowest.

    Args:
        results_df: DataFrame with 'placement' column containing direction/polarization info.
        metric: SAR metric to plot (default: 'SAR_whole_body').
        frequency_mhz: Optional frequency to filter. If None, averages across all frequencies.
    """
    if metric not in results_df.columns or results_df[metric].dropna().empty:
        logging.getLogger("progress").warning(
            f"  - WARNING: No data for metric '{metric}' to generate direction/polarization heatmap.",
            extra={"log_type": "warning"},
        )
        return

    # Parse placement column to extract direction and polarization
    df = results_df.copy()

    def parse_placement(placement: str) -> tuple[str, str]:
        """Parse placement string like 'environmental_x_pos_theta' to ('From left', 'Theta')."""
        # Direction labels describe where the wave is coming FROM (not propagation direction)
        direction_labels = {
            "x_pos": "From left",
            "x_neg": "From right",
            "y_pos": "From back",
            "y_neg": "From front",
            "z_pos": "From below",
            "z_neg": "From above",
        }
        parts = placement.replace("environmental_", "").split("_")
        if len(parts) >= 3:
            dir_key = f"{parts[0]}_{parts[1]}"
            direction = direction_labels.get(dir_key, f"{parts[0].upper()}{'+' if parts[1] == 'pos' else '-'}")
            pol = "Theta" if parts[2] == "theta" else "Phi"
            return direction, pol
        return placement, "Unknown"

    df[["direction", "polarization"]] = df["placement"].apply(lambda x: pd.Series(parse_placement(x)))

    # Filter by frequency if specified
    if frequency_mhz is not None:
        df = df[df["frequency_mhz"] == frequency_mhz]
        freq_suffix = f"_{frequency_mhz}MHz"
    else:
        freq_suffix = "_allMHz"

    if df.empty:
        logging.getLogger("progress").warning(
            f"  - WARNING: No data after filtering for heatmap (metric={metric}, freq={frequency_mhz}).",
            extra={"log_type": "warning"},
        )
        return

    # Create pivot table: direction x polarization
    # If multiple frequencies, take the mean
    pivot = df.pivot_table(
        index="direction",
        columns="polarization",
        values=metric,
        aggfunc="mean",
    )

    # Reorder directions for logical display
    direction_order = ["From left", "From right", "From back", "From front", "From below", "From above"]
    pivot = pivot.reindex([d for d in direction_order if d in pivot.index])

    # Reorder polarizations (Theta, Phi)
    pol_order = ["Theta", "Phi"]
    pivot = pivot[[p for p in pol_order if p in pivot.columns]]

    if pivot.empty:
        logging.getLogger("progress").warning(
            "  - WARNING: Empty pivot table for direction/polarization heatmap.",
            extra={"log_type": "warning"},
        )
        return

    # Create figure - compact size since we only have 6x2 cells
    fig, ax = plt.subplots(figsize=(3.5, 4.0))

    # Use a diverging colormap centered on the mean
    vmin = pivot.min().min()
    vmax = pivot.max().max()

    # Use log scale if values span more than 2 orders of magnitude
    use_log = vmax / vmin > 100 if vmin > 0 else False

    if use_log:
        from matplotlib.colors import LogNorm

        norm = LogNorm(vmin=vmin, vmax=vmax)
    else:
        norm = None

    sns.heatmap(
        pivot,
        ax=ax,
        annot=True,
        fmt=".1f",
        cmap="RdYlGn_r",  # Red=high SAR, Green=low SAR
        linewidths=1.0,
        linecolor="white",
        cbar_kws={"label": f"{self._format_organ_name(metric)} (mW/kg)"},
        norm=norm,
        square=True,
    )

    # Styling
    ax.set_xlabel("Polarization", fontsize=9)
    ax.set_ylabel("Incident Direction", fontsize=9)
    ax.tick_params(labelsize=8)

    # Rotate y-axis labels for better readability
    ax.set_yticklabels(ax.get_yticklabels(), rotation=0)

    plt.tight_layout()

    # Create title and caption
    from .base import METRIC_LABELS

    metric_label = METRIC_LABELS.get(metric, metric)
    freq_text = f"at {frequency_mhz} MHz" if frequency_mhz else "averaged across all frequencies"
    base_title = f"far-field {metric_label} by incident direction and polarization {freq_text}"
    title_full = self._get_title_with_phantom(base_title)

    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = (
        f"The heatmap compares normalized {metric_label} values for {phantom_name_formatted} "
        f"across different far-field incident wave directions (from left, right, front, back, above, below) and polarizations (Theta, Phi) "
        f"{freq_text}. Red indicates higher SAR absorption, green indicates lower SAR absorption. "
        f"This visualization helps identify which exposure configurations result in the highest and lowest SAR values."
    )

    filename_base = f"heatmap_direction_polarization_{metric}{freq_suffix}"
    filename = self._save_figure(fig, "heatmap", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data
    self._save_csv_data(pivot, "heatmap", filename_base)

    logging.getLogger("progress").info(
        f"  - Generated direction/polarization heatmap: {filename}",
        extra={"log_type": "success"},
    )

    return filename

plot_far_field_direction_polarization_summary

plot_far_field_direction_polarization_summary(results_df: DataFrame, metrics: list[str] | None = None)

Creates a multi-panel summary comparing SAR metrics across directions/polarizations.

Generates both individual metric heatmaps and a combined multi-panel figure.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with 'placement' column containing direction/polarization info.

required
metrics list[str] | None

List of metrics to plot. If None, plots common metrics.

None
Source code in goliat/analysis/plots/heatmap.py
def plot_far_field_direction_polarization_summary(
    self,
    results_df: pd.DataFrame,
    metrics: list[str] | None = None,
):
    """Creates a multi-panel summary comparing SAR metrics across directions/polarizations.

    Generates both individual metric heatmaps and a combined multi-panel figure.

    Args:
        results_df: DataFrame with 'placement' column containing direction/polarization info.
        metrics: List of metrics to plot. If None, plots common metrics.
    """
    if metrics is None:
        # Default metrics to plot - includes tissue group SAR and psSAR10g metrics
        possible_metrics = [
            # Whole-body and peak metrics
            "SAR_whole_body",
            "peak_sar",
            # SAR tissue groups (average SAR per tissue group)
            "SAR_brain",
            "SAR_skin",
            "SAR_eyes",
            "SAR_genitals",
            # psSAR10g metrics (peak spatial-average SAR)
            "psSAR10g_brain",
            "psSAR10g_skin",
            "psSAR10g_eyes",
            "psSAR10g_genitals",
        ]
        metrics = [m for m in possible_metrics if m in results_df.columns and results_df[m].notna().any()]

    if not metrics:
        logging.getLogger("progress").warning(
            "  - WARNING: No valid metrics for direction/polarization summary.",
            extra={"log_type": "warning"},
        )
        return

    # Generate individual heatmaps for each metric
    for metric in metrics:
        self.plot_far_field_direction_polarization_heatmap(results_df, metric=metric)

    # Create a multi-panel combined figure
    self._plot_far_field_direction_polarization_combined(results_df, metrics)

plot_polarization_ratio_heatmap

plot_polarization_ratio_heatmap(results_df: DataFrame, metrics: list[str] | None = None)

Plots heatmap of theta/phi polarization ratio for each direction and metric.

Creates a heatmap showing frequency-averaged polarization ratios. Ratios > 1.0 indicate theta dominates; < 1.0 indicates phi dominates.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with placement column containing direction and polarization info.

required
metrics list[str] | None

List of metrics to analyze. If None, uses common metrics.

None
Source code in goliat/analysis/plots/heatmap.py
def plot_polarization_ratio_heatmap(
    self,
    results_df: pd.DataFrame,
    metrics: list[str] | None = None,
):
    """Plots heatmap of theta/phi polarization ratio for each direction and metric.

    Creates a heatmap showing frequency-averaged polarization ratios.
    Ratios > 1.0 indicate theta dominates; < 1.0 indicates phi dominates.

    Args:
        results_df: DataFrame with placement column containing direction and polarization info.
        metrics: List of metrics to analyze. If None, uses common metrics.
    """
    if results_df.empty:
        return

    # Parse placement to extract direction and polarization
    def parse_placement(placement: str) -> tuple[str | None, str | None]:
        parts = placement.split("_")
        if len(parts) >= 4:
            direction = f"{parts[1]}_{parts[2]}"  # e.g., "x_pos"
            pol = parts[3]  # "theta" or "phi"
            return direction, pol
        return None, None

    df = results_df.copy()
    df[["direction", "polarization"]] = df["placement"].apply(lambda x: pd.Series(parse_placement(x)))
    df = df.dropna(subset=["direction", "polarization"])

    if df.empty:
        return

    if metrics is None:
        possible_metrics = ["SAR_whole_body", "psSAR10g_brain", "psSAR10g_eyes", "psSAR10g_skin", "psSAR10g_genitals"]
        metrics = [m for m in possible_metrics if m in df.columns and df[m].notna().any()]

    if not metrics:
        return

    # Direction display names and order (human-readable: describes where wave comes FROM)
    direction_names = {
        "x_pos": "From left",
        "x_neg": "From right",
        "y_pos": "From back",
        "y_neg": "From front",
        "z_pos": "From below",
        "z_neg": "From above",
    }

    direction_order = ["x_pos", "x_neg", "y_pos", "y_neg", "z_pos", "z_neg"]
    available_directions = [d for d in direction_order if d in df["direction"].unique()]

    # Compute ratio for each direction and metric (averaged across frequencies)
    ratio_data = {}
    for direction in available_directions:
        dir_df = df[df["direction"] == direction]
        direction_ratios = {}

        for metric in metrics:
            if metric not in dir_df.columns:
                continue

            pivot = dir_df.pivot_table(values=metric, index="frequency_mhz", columns="polarization", aggfunc="mean")

            if "theta" not in pivot.columns or "phi" not in pivot.columns:
                continue

            # Average ratio across frequencies
            ratios = pivot["theta"] / pivot["phi"]
            avg_ratio = ratios.mean()
            direction_ratios[metric] = avg_ratio

        if direction_ratios:
            ratio_data[direction_names.get(direction, direction)] = direction_ratios

    if not ratio_data:
        return

    # Create DataFrame for heatmap
    ratio_df = pd.DataFrame(ratio_data).T

    # Rename columns for display
    metric_labels = {
        "SAR_whole_body": "Whole Body",
        "SAR_brain": "Brain",
        "SAR_eyes": "Eyes",
        "SAR_skin": "Skin",
        "SAR_genitals": "Genitals",
        "psSAR10g_brain": "Brain",
        "psSAR10g_eyes": "Eyes",
        "psSAR10g_skin": "Skin",
        "psSAR10g_genitals": "Genitals",
    }
    ratio_df = ratio_df.rename(columns=metric_labels)

    # Reorder rows
    row_order = ["From left", "From right", "From back", "From front", "From below", "From above"]
    ratio_df = ratio_df.reindex([r for r in row_order if r in ratio_df.index])

    # Create figure - IEEE single-column width
    fig, ax = plt.subplots(figsize=(3.5, 3.0))

    # Colormap starting from 0, centered at 1.0
    from matplotlib.colors import TwoSlopeNorm

    vmin = 0.0  # Start from 0
    vmax = max(ratio_df.max().max(), 2.0)  # Ensure we show at least up to 2.0
    vcenter = 1.0

    norm = TwoSlopeNorm(vmin=vmin, vcenter=vcenter, vmax=vmax)

    sns.heatmap(
        ratio_df,
        ax=ax,
        annot=True,
        fmt=".2f",
        cmap="RdBu_r",  # Red for theta dominates (>1), Blue for phi dominates (<1)
        norm=norm,
        linewidths=0.5,
        cbar_kws={"label": "Polarization Ratio (Theta/Phi)"},
    )

    ax.set_xlabel("Tissue Group", fontsize=10)
    ax.set_ylabel("Incident Direction", fontsize=10)
    ax.tick_params(axis="both", labelsize=9, which="both")
    ax.minorticks_off()  # Remove minor ticks

    plt.tight_layout()

    # Save
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    title = self._get_title_with_phantom("Polarization Ratio (Theta/Phi) by Direction")
    caption = (
        f"Heatmap showing the theta/phi polarization ratio for {phantom_name_formatted}, "
        f"averaged across all frequencies. "
        f"Ratio > 1.0 (red) indicates theta polarization gives higher SAR. "
        f"Ratio < 1.0 (blue) indicates phi polarization dominates. "
        f"Note: These are frequency-averaged values; significant frequency-dependent variations exist."
    )

    filename = self._save_figure(fig, "heatmap", "heatmap_polarization_ratio", title=title, caption=caption, dpi=200)

    logging.getLogger("progress").info(
        f"  - Generated polarization ratio heatmap: {filename}",
        extra={"log_type": "success"},
    )

plot_polarization_ratio_heatmaps_per_frequency

plot_polarization_ratio_heatmaps_per_frequency(results_df: DataFrame, metrics: list[str] | None = None)

Plots polarization ratio heatmaps for each frequency separately.

Creates individual heatmaps showing theta/phi ratios for each frequency, allowing detailed analysis of frequency-dependent polarization effects.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with placement column containing direction and polarization info.

required
metrics list[str] | None

List of metrics to analyze. If None, uses common metrics.

None
Source code in goliat/analysis/plots/heatmap.py
def plot_polarization_ratio_heatmaps_per_frequency(
    self,
    results_df: pd.DataFrame,
    metrics: list[str] | None = None,
):
    """Plots polarization ratio heatmaps for each frequency separately.

    Creates individual heatmaps showing theta/phi ratios for each frequency,
    allowing detailed analysis of frequency-dependent polarization effects.

    Args:
        results_df: DataFrame with placement column containing direction and polarization info.
        metrics: List of metrics to analyze. If None, uses common metrics.
    """
    if results_df.empty:
        return

    # Parse placement to extract direction and polarization
    def parse_placement(placement: str) -> tuple[str | None, str | None]:
        parts = placement.split("_")
        if len(parts) >= 4:
            direction = f"{parts[1]}_{parts[2]}"
            pol = parts[3]
            return direction, pol
        return None, None

    df = results_df.copy()
    df[["direction", "polarization"]] = df["placement"].apply(lambda x: pd.Series(parse_placement(x)))
    df = df.dropna(subset=["direction", "polarization"])

    if df.empty:
        return

    if metrics is None:
        possible_metrics = ["SAR_whole_body", "psSAR10g_brain", "psSAR10g_eyes", "psSAR10g_skin", "psSAR10g_genitals"]
        metrics = [m for m in possible_metrics if m in df.columns and df[m].notna().any()]

    if not metrics:
        return

    frequencies = sorted(df["frequency_mhz"].unique())

    direction_names = {
        "x_pos": "From left",
        "x_neg": "From right",
        "y_pos": "From back",
        "y_neg": "From front",
        "z_pos": "From below",
        "z_neg": "From above",
    }
    direction_order = ["x_pos", "x_neg", "y_pos", "y_neg", "z_pos", "z_neg"]
    available_directions = [d for d in direction_order if d in df["direction"].unique()]

    metric_labels = {
        "SAR_whole_body": "Whole Body",
        "SAR_brain": "Brain",
        "SAR_eyes": "Eyes",
        "SAR_skin": "Skin",
        "SAR_genitals": "Genitals",
        "psSAR10g_brain": "Brain",
        "psSAR10g_eyes": "Eyes",
        "psSAR10g_skin": "Skin",
        "psSAR10g_genitals": "Genitals",
    }

    from matplotlib.colors import TwoSlopeNorm

    for freq in frequencies:
        freq_df = df[df["frequency_mhz"] == freq]

        # Compute ratio for each direction and metric
        ratio_data = {}
        for direction in available_directions:
            dir_df = freq_df[freq_df["direction"] == direction]
            direction_ratios = {}

            for metric in metrics:
                if metric not in dir_df.columns:
                    continue

                theta_val = dir_df[dir_df["polarization"] == "theta"][metric].mean()
                phi_val = dir_df[dir_df["polarization"] == "phi"][metric].mean()

                if pd.notna(theta_val) and pd.notna(phi_val) and phi_val != 0:
                    direction_ratios[metric] = theta_val / phi_val

            if direction_ratios:
                ratio_data[direction_names.get(direction, direction)] = direction_ratios

        if not ratio_data:
            continue

        ratio_df = pd.DataFrame(ratio_data).T
        ratio_df = ratio_df.rename(columns=metric_labels)
        row_order = ["From left", "From right", "From back", "From front", "From below", "From above"]
        ratio_df = ratio_df.reindex([r for r in row_order if r in ratio_df.index])

        # Create figure - use IEEE single-column width for proper font scaling
        fig, ax = plt.subplots(figsize=(3.5, 3.0))

        # Colormap starting from 0, centered at 1.0
        vmin = 0.0
        vmax = max(ratio_df.max().max(), 2.0)
        vcenter = 1.0

        norm = TwoSlopeNorm(vmin=vmin, vcenter=vcenter, vmax=vmax)

        sns.heatmap(
            ratio_df,
            ax=ax,
            annot=True,
            fmt=".2f",
            cmap="RdBu_r",
            norm=norm,
            linewidths=0.5,
            cbar_kws={"label": "Polarization Ratio (Theta/Phi)"},
            annot_kws={"fontsize": 8},
        )

        ax.set_xlabel("Tissue Group", fontsize=9)
        ax.set_ylabel("Incident Direction", fontsize=9)
        ax.set_title(f"{int(freq)} MHz", fontsize=10, fontweight="bold")
        ax.tick_params(axis="both", labelsize=8, which="both")
        ax.minorticks_off()  # Remove minor ticks

        plt.tight_layout()

        filename = f"heatmap_polarization_ratio_{int(freq)}MHz"
        self._save_figure(fig, "heatmap", filename, dpi=200)

    logging.getLogger("progress").info(
        f"  - Generated {len(frequencies)} per-frequency polarization ratio heatmaps",
        extra={"log_type": "info"},
    )

goliat.analysis.plots.line.LinePlotter

LinePlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Bases: BasePlotter

Generates line plots for SAR analysis.

Source code in goliat/analysis/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

plot_peak_sar_line

plot_peak_sar_line(summary_stats: DataFrame)

Plots peak SAR trend across frequencies for far-field analysis.

Source code in goliat/analysis/plots/line.py
def plot_peak_sar_line(self, summary_stats: pd.DataFrame):
    """Plots peak SAR trend across frequencies for far-field analysis."""
    fig, ax = plt.subplots(figsize=(3.5, 2.5))  # IEEE single-column width
    title_full = self._get_title_with_phantom("average peak SAR (10g) across all tissues")
    if "peak_sar" in summary_stats.columns:
        summary_stats["peak_sar"].plot(kind="line", marker="o", ax=ax, color="purple")
        # Don't set title on plot - will be in caption file
        ax.set_xlabel(self._format_axis_label("Frequency", "MHz"))
        ax.set_ylabel(self._format_axis_label("Normalized peak SAR", r"mW kg$^{-1}$"))
        ax.set_xticks(summary_stats.index)
        # Rotate x-axis labels only for actual simulated frequencies (1450, 2140, 2450, etc.)
        # Check if frequencies are actual simulated values (not auto-generated)
        freq_values = summary_stats.index.tolist()
        simulated_freqs = [1450, 2140, 2450]
        if freq_values and any(isinstance(f, (int, float)) and f in simulated_freqs for f in freq_values):
            plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
            self._adjust_slanted_tick_labels(ax)
        ax.grid(True, which="both", linestyle="--", linewidth=0.5)
        # Set y-axis to start at 0 and go to max + 5%
        y_max = ax.get_ylim()[1]
        ax.set_ylim(0, y_max * 1.05)
    else:
        ax.text(0.5, 0.5, "No Peak SAR data found", ha="center", va="center")
    plt.tight_layout()
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The line plot shows the trend of average peak SAR (10g) values across all tissues as a function of frequency for {phantom_name_formatted}."
    self._save_figure(fig, "line", "line_peak_sar_summary", title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = summary_stats[["peak_sar"]].copy() if "peak_sar" in summary_stats.columns else pd.DataFrame()
    csv_data.index.name = "frequency_mhz"
    if not csv_data.empty:
        self._save_csv_data(csv_data, "line", "line_peak_sar_summary")

plot_pssar_line

plot_pssar_line(scenario_name: str, avg_results: DataFrame)

Plots average psSAR10g trends for tissue groups by frequency.

Shows how peak spatial-average SAR varies with frequency for eyes, skin, and brain groups.

Parameters:

Name Type Description Default
scenario_name str

Placement scenario name.

required
avg_results DataFrame

DataFrame with average psSAR10g values.

required
Source code in goliat/analysis/plots/line.py
def plot_pssar_line(self, scenario_name: str, avg_results: pd.DataFrame):
    """Plots average psSAR10g trends for tissue groups by frequency.

    Shows how peak spatial-average SAR varies with frequency for eyes,
    skin, and brain groups.

    Args:
        scenario_name: Placement scenario name.
        avg_results: DataFrame with average psSAR10g values.
    """
    pssar_columns = [col for col in avg_results.columns if col.startswith("psSAR10g")]
    base_title = "average normalized psSAR10g for scenario"
    title_full = self._get_title_with_phantom(base_title, scenario_name)

    # Calculate dynamic height based on legend size
    n_items = len(pssar_columns) if pssar_columns else 0
    legend_height = self._calculate_legend_height(n_items, n_cols=3) if n_items > 0 else 0
    base_height = 2.5  # Base plot height
    total_height = base_height + legend_height

    fig, ax = plt.subplots(figsize=(3.5, total_height))  # IEEE single-column width, dynamic height
    if pssar_columns:
        colors = self._get_academic_colors(len(pssar_columns))
        linestyles = self._get_academic_linestyles(len(pssar_columns))
        markers = self._get_academic_markers(len(pssar_columns))
        for idx, col in enumerate(pssar_columns):
            avg_results[col].plot(
                kind="line",
                marker=markers[idx],
                linestyle=linestyles[idx],
                ax=ax,
                color=colors[idx],
                label=LEGEND_LABELS.get(col, col),
            )
        # Don't set title on plot - will be in caption file
        ax.set_xlabel(self._format_axis_label("Frequency", "MHz"))
        ax.set_ylabel(self._format_axis_label("Normalized psSAR10g", r"mW kg$^{-1}$"))
        legend_labels = [label for col in pssar_columns if (label := LEGEND_LABELS.get(col, col)) is not None]
        # Use 2 columns for legend when there are 4 items to ensure balanced layout
        n_cols = 2 if len(legend_labels) == 4 else min(3, len(legend_labels))
        # Place legend below in grid format (will get handles/labels from ax)
        self._place_legend_below(fig, ax, len(legend_labels), n_cols=n_cols)
        ax.set_xticks(avg_results.index)
        # Rotate frequency labels (always rotate when x-axis is Frequency)
        plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
        self._adjust_slanted_tick_labels(ax)
        # Set y-axis to start at 0 and go to max + 5%
        y_max = ax.get_ylim()[1]
        ax.set_ylim(0, y_max * 1.05)
    else:
        ax.text(0.5, 0.5, "No psSAR10g data found", ha="center", va="center")
    plt.tight_layout()
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The line plot shows average normalized psSAR10g trends for different tissue groups (Eyes, Skin, Brain, Genitals, Whole Body) across frequencies for the {self._format_scenario_name(scenario_name)} scenario for {phantom_name_formatted}."
    self._save_figure(fig, "line", f"pssar10g_line_{scenario_name}", title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = avg_results[pssar_columns].copy()
    csv_data.index.name = "frequency_mhz"
    self._save_csv_data(csv_data, "line", f"pssar10g_line_{scenario_name}")

plot_sar_line

plot_sar_line(scenario_name: str, avg_results: DataFrame)

Plots average SAR trends for tissue groups by frequency.

Symmetric counterpart to plot_pssar_line.

Parameters:

Name Type Description Default
scenario_name str

Placement scenario name.

required
avg_results DataFrame

DataFrame with average SAR values.

required
Source code in goliat/analysis/plots/line.py
def plot_sar_line(self, scenario_name: str, avg_results: pd.DataFrame):
    """Plots average SAR trends for tissue groups by frequency.

    Symmetric counterpart to plot_pssar_line.

    Args:
        scenario_name: Placement scenario name.
        avg_results: DataFrame with average SAR values.
    """
    sar_columns = [col for col in avg_results.columns if col.startswith("SAR_")]
    base_title = "average normalized SAR for scenario"
    title_full = self._get_title_with_phantom(base_title, scenario_name)

    # Calculate dynamic height based on legend size
    n_items = len(sar_columns) if sar_columns else 0
    legend_height = self._calculate_legend_height(n_items, n_cols=3) if n_items > 0 else 0
    base_height = 2.5  # Base plot height
    total_height = base_height + legend_height

    fig, ax = plt.subplots(figsize=(3.5, total_height))  # IEEE single-column width, dynamic height
    if sar_columns:
        colors = self._get_academic_colors(len(sar_columns))
        linestyles = self._get_academic_linestyles(len(sar_columns))
        markers = self._get_academic_markers(len(sar_columns))
        for idx, col in enumerate(sar_columns):
            avg_results[col].plot(
                kind="line",
                marker=markers[idx],
                linestyle=linestyles[idx],
                ax=ax,
                color=colors[idx],
                label=LEGEND_LABELS.get(col, col),
            )
        # Don't set title on plot - will be in caption file
        ax.set_xlabel(self._format_axis_label("Frequency", "MHz"))
        ax.set_ylabel(self._format_axis_label("Normalized SAR", r"mW kg$^{-1}$"))
        # Use trimmed legend labels (remove "SAR" since y-axis already says "SAR")
        legend_labels = [LEGEND_LABELS.get(col, col.replace("SAR_", "").replace("_", " ").title()) for col in sar_columns]
        # Use 2 columns for legend when there are 4 items to ensure balanced layout
        n_cols = 2 if len(legend_labels) == 4 else min(3, len(legend_labels))
        # Place legend below in grid format (will get handles/labels from ax)
        self._place_legend_below(fig, ax, len(legend_labels), n_cols=n_cols)
        ax.set_xticks(avg_results.index)
        # Rotate frequency labels (always rotate when x-axis is Frequency)
        plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
        self._adjust_slanted_tick_labels(ax)
        # Set y-axis to start at 0 and go to max + 5%
        y_max = ax.get_ylim()[1]
        ax.set_ylim(0, y_max * 1.05)
    else:
        ax.text(0.5, 0.5, "No SAR data found", ha="center", va="center")
    plt.tight_layout()
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The line plot shows average normalized SAR trends for different tissue groups (Head, Trunk, Whole-Body, Brain, Skin, Eyes, Genitals) across frequencies for the {self._format_scenario_name(scenario_name)} scenario for {phantom_name_formatted}."
    self._save_figure(fig, "line", f"sar_line_{scenario_name}", title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = avg_results[sar_columns].copy()
    csv_data.index.name = "frequency_mhz"
    self._save_csv_data(csv_data, "line", f"sar_line_{scenario_name}")

plot_pssar_line_individual_variations

plot_pssar_line_individual_variations(results_df: DataFrame, scenario_name: str, metric_column: str = 'psSAR10g_eyes')

Plots individual variation lines for each placement/direction/polarization.

Similar to boxplots but shows individual lines instead of aggregating variability. Each placement variation gets its own line with a legend entry.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with detailed results including 'placement' column.

required
scenario_name str

Scenario name for filtering.

required
metric_column str

Column name for the metric to plot (e.g., 'psSAR10g_eyes').

'psSAR10g_eyes'
Source code in goliat/analysis/plots/line.py
def plot_pssar_line_individual_variations(
    self,
    results_df: pd.DataFrame,
    scenario_name: str,
    metric_column: str = "psSAR10g_eyes",
):
    """Plots individual variation lines for each placement/direction/polarization.

    Similar to boxplots but shows individual lines instead of aggregating variability.
    Each placement variation gets its own line with a legend entry.

    Args:
        results_df: DataFrame with detailed results including 'placement' column.
        scenario_name: Scenario name for filtering.
        metric_column: Column name for the metric to plot (e.g., 'psSAR10g_eyes').
    """
    if metric_column not in results_df.columns:
        logging.getLogger("progress").warning(
            f"Column '{metric_column}' not found for individual variation plot.",
            extra={"log_type": "warning"},
        )
        return

    # Filter by scenario
    plot_df = results_df[results_df["scenario"] == scenario_name].copy()

    if plot_df.empty:
        return

    # Group by frequency and placement
    if "placement" not in plot_df.columns:
        logging.getLogger("progress").warning(
            "No 'placement' column found for individual variation plot.",
            extra={"log_type": "warning"},
        )
        return

    # Get unique placements
    placements = sorted(plot_df["placement"].unique())

    # Create pivot table: frequency vs placement
    pivot_data = plot_df.pivot_table(
        index="frequency_mhz",
        columns="placement",
        values=metric_column,
        aggfunc="mean",
    )

    if pivot_data.empty:
        return

    # Calculate dynamic height based on legend size
    # Use 2 columns for legend layout
    n_items = len(placements)
    n_cols = 2  # Always use 2 columns for legend
    legend_height = self._calculate_legend_height(n_items, n_cols=n_cols)
    # Use IEEE standard single-column width (3.5 inches) - height will be adjusted dynamically
    # Base height for proper font rendering at IEEE single-column width
    base_height = 2.5
    total_height = base_height + legend_height

    fig, ax = plt.subplots(figsize=(3.5, total_height))  # IEEE single-column width (3.5"), dynamic height

    # Plot each placement as a separate line

    colors = self._get_academic_colors(len(placements))
    linestyles = self._get_academic_linestyles(len(placements))
    markers = self._get_academic_markers(len(placements))
    for idx, placement in enumerate(placements):
        if placement in pivot_data.columns:
            # Format placement name to be human readable
            placement_formatted = (
                self._format_organ_name(placement) if hasattr(self, "_format_organ_name") else placement.replace("_", " ").title()
            )
            ax.plot(
                pivot_data.index,
                pivot_data[placement],
                marker=markers[idx],
                linestyle=linestyles[idx],
                label=placement_formatted,
                linewidth=1.5,
                markersize=4,
                color=colors[idx],
                alpha=0.7,
            )

    ax.set_xlabel(self._format_axis_label("Frequency", "MHz"))
    metric_label = METRIC_LABELS.get(metric_column, metric_column)
    ax.set_ylabel(self._format_axis_label(metric_label, r"mW kg$^{-1}$"))
    formatted_scenario = self._format_scenario_name(scenario_name) if scenario_name else None
    if formatted_scenario:
        base_title = f"individual variations for {metric_label} in {formatted_scenario} scenario"
    else:
        base_title = f"individual variations for {metric_label}"
    title_full = self._get_title_with_phantom(base_title)
    # Don't set title on plot - will be in caption file
    # Place legend below in grid format
    self._place_legend_below(fig, ax, n_items, n_cols=n_cols)

    # Rotate frequency labels (always rotate when x-axis is Frequency)
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
    self._adjust_slanted_tick_labels(ax)

    ax.grid(True, alpha=0.3)
    # Set y-axis to start at 0 and go to max + 5%
    y_max = ax.get_ylim()[1]
    ax.set_ylim(0, y_max * 1.05)

    plt.tight_layout()

    metric_safe = metric_column.replace("SAR_", "").replace("psSAR10g_", "").replace("_", "_")
    prefix = "sar" if metric_column.startswith("SAR_") else "pssar10g"
    filename_base = f"{prefix}_line_individual_{metric_safe}_{scenario_name}"
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The line plot shows individual variation lines for each placement/direction/polarization combination for {metric_label} across frequencies in the {self._format_scenario_name(scenario_name)} scenario for {phantom_name_formatted}. Each line represents a specific placement variation."
    filename = self._save_figure(fig, "line", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = pivot_data.copy()
    csv_data.index.name = "frequency_mhz"
    self._save_csv_data(csv_data, "line", filename_base)
    logging.getLogger("progress").info(
        f"  - Generated individual variation line plot: {filename}",
        extra={"log_type": "success"},
    )

plot_sar_line_individual_variations

plot_sar_line_individual_variations(results_df: DataFrame, scenario_name: str, metric_column: str = 'SAR_head')

Plots individual variation lines for SAR metrics.

Symmetric counterpart to plot_pssar_line_individual_variations for SAR metrics.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with detailed results including 'placement' column.

required
scenario_name str

Scenario name for filtering.

required
metric_column str

Column name for the SAR metric to plot (e.g., 'SAR_head').

'SAR_head'
Source code in goliat/analysis/plots/line.py
def plot_sar_line_individual_variations(
    self,
    results_df: pd.DataFrame,
    scenario_name: str,
    metric_column: str = "SAR_head",
):
    """Plots individual variation lines for SAR metrics.

    Symmetric counterpart to plot_pssar_line_individual_variations for SAR metrics.

    Args:
        results_df: DataFrame with detailed results including 'placement' column.
        scenario_name: Scenario name for filtering.
        metric_column: Column name for the SAR metric to plot (e.g., 'SAR_head').
    """
    # Delegate to the generic function
    self.plot_pssar_line_individual_variations(results_df, scenario_name, metric_column)

plot_far_field_direction_polarization_lines

plot_far_field_direction_polarization_lines(results_df: DataFrame, metric: str = 'SAR_whole_body', group_by: str = 'direction')

Creates line plots showing frequency dependence for far-field direction/polarization.

This visualization shows how SAR varies with frequency for each direction/polarization combination, enabling comparison of frequency-dependent effects.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with 'placement' column containing direction/polarization info.

required
metric str

SAR metric to plot (default: 'SAR_whole_body').

'SAR_whole_body'
group_by str

How to group lines - 'direction' (one line per direction, panels for polarization), 'polarization' (one line per polarization, panels for direction), or 'both' (all combinations on one plot).

'direction'
Source code in goliat/analysis/plots/line.py
def plot_far_field_direction_polarization_lines(
    self,
    results_df: pd.DataFrame,
    metric: str = "SAR_whole_body",
    group_by: str = "direction",  # "direction", "polarization", or "both"
):
    """Creates line plots showing frequency dependence for far-field direction/polarization.

    This visualization shows how SAR varies with frequency for each direction/polarization
    combination, enabling comparison of frequency-dependent effects.

    Args:
        results_df: DataFrame with 'placement' column containing direction/polarization info.
        metric: SAR metric to plot (default: 'SAR_whole_body').
        group_by: How to group lines - 'direction' (one line per direction, panels for polarization),
                  'polarization' (one line per polarization, panels for direction),
                  or 'both' (all combinations on one plot).
    """
    if metric not in results_df.columns or results_df[metric].dropna().empty:
        logging.getLogger("progress").warning(
            f"  - WARNING: No data for metric '{metric}' for direction/polarization line plot.",
            extra={"log_type": "warning"},
        )
        return

    # Parse placement column to extract direction and polarization
    df = results_df.copy()

    def parse_placement(placement: str) -> tuple[str, str]:
        """Parse placement string like 'environmental_x_pos_theta' to ('From left', 'Theta')."""
        # Direction labels describe where the wave is coming FROM (not propagation direction)
        direction_labels = {
            "x_pos": "From left",
            "x_neg": "From right",
            "y_pos": "From back",
            "y_neg": "From front",
            "z_pos": "From below",
            "z_neg": "From above",
        }
        parts = placement.replace("environmental_", "").split("_")
        if len(parts) >= 3:
            dir_key = f"{parts[0]}_{parts[1]}"
            direction = direction_labels.get(dir_key, f"{parts[0].upper()}{'+' if parts[1] == 'pos' else '-'}")
            pol = "Theta" if parts[2] == "theta" else "Phi"
            return direction, pol
        return placement, "Unknown"

    df[["direction", "polarization"]] = df["placement"].apply(lambda x: pd.Series(parse_placement(x)))

    # Get metric label
    metric_label = METRIC_LABELS.get(metric, metric)

    if group_by == "both":
        # All direction/polarization combinations on one plot
        self._plot_far_field_all_combinations(df, metric, metric_label)
    elif group_by == "direction":
        # One panel per polarization, lines for each direction
        self._plot_far_field_by_polarization(df, metric, metric_label)
    else:  # group_by == "polarization"
        # One panel per direction, lines for each polarization
        self._plot_far_field_by_direction(df, metric, metric_label)

plot_far_field_direction_polarization_comparison

plot_far_field_direction_polarization_comparison(results_df: DataFrame, metrics: list[str] | None = None)

Generates frequency-dependent comparison plots for all direction/polarization combos.

Creates multiple line plots showing how SAR varies with frequency for different direction/polarization combinations.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with 'placement' column containing direction/polarization info.

required
metrics list[str] | None

List of metrics to plot. If None, uses common metrics.

None
Source code in goliat/analysis/plots/line.py
def plot_far_field_direction_polarization_comparison(
    self,
    results_df: pd.DataFrame,
    metrics: list[str] | None = None,
):
    """Generates frequency-dependent comparison plots for all direction/polarization combos.

    Creates multiple line plots showing how SAR varies with frequency for different
    direction/polarization combinations.

    Args:
        results_df: DataFrame with 'placement' column containing direction/polarization info.
        metrics: List of metrics to plot. If None, uses common metrics.
    """
    if metrics is None:
        # Include both SAR tissue groups and psSAR10g metrics
        # SAR tissue groups are added during analysis via _add_tissue_group_sar()
        possible_metrics = [
            # Whole-body and peak metrics
            "SAR_whole_body",
            "peak_sar",
            # SAR tissue groups (average SAR per tissue group)
            "SAR_brain",
            "SAR_skin",
            "SAR_eyes",
            "SAR_genitals",
            # psSAR10g metrics (peak spatial-average SAR)
            "psSAR10g_brain",
            "psSAR10g_skin",
            "psSAR10g_eyes",
            "psSAR10g_genitals",
        ]
        metrics = [m for m in possible_metrics if m in results_df.columns and results_df[m].notna().any()]

    if not metrics:
        logging.getLogger("progress").warning(
            "  - WARNING: No valid metrics for direction/polarization comparison.",
            extra={"log_type": "warning"},
        )
        return

    logging.getLogger("progress").info(
        "  - Generating direction/polarization frequency comparison plots...",
        extra={"log_type": "info"},
    )

    for metric in metrics:
        # Generate the "by polarization" view - most useful for comparing directions
        self.plot_far_field_direction_polarization_lines(results_df, metric=metric, group_by="direction")

plot_cross_phantom_comparison

plot_cross_phantom_comparison(all_phantom_data: dict[str, DataFrame], metrics: list[str] | None = None)

Plots SAR vs frequency comparing different phantoms.

Creates line plots showing how SAR varies with frequency for each phantom, revealing age/body-size dependent absorption patterns.

Parameters:

Name Type Description Default
all_phantom_data dict[str, DataFrame]

Dictionary mapping phantom names to their results DataFrames.

required
metrics list[str] | None

List of metrics to plot. If None, uses common metrics.

None
Source code in goliat/analysis/plots/line.py
def plot_cross_phantom_comparison(
    self,
    all_phantom_data: dict[str, pd.DataFrame],
    metrics: list[str] | None = None,
):
    """Plots SAR vs frequency comparing different phantoms.

    Creates line plots showing how SAR varies with frequency for each phantom,
    revealing age/body-size dependent absorption patterns.

    Args:
        all_phantom_data: Dictionary mapping phantom names to their results DataFrames.
        metrics: List of metrics to plot. If None, uses common metrics.
    """
    if not all_phantom_data:
        logging.getLogger("progress").warning(
            "  - WARNING: No phantom data for cross-phantom comparison.",
            extra={"log_type": "warning"},
        )
        return

    if metrics is None:
        # Default metrics - check what's available in first phantom
        first_df = list(all_phantom_data.values())[0]
        possible_metrics = [
            "SAR_whole_body",
            "SAR_brain",
            "SAR_eyes",
            "SAR_skin",
            "SAR_genitals",
        ]
        metrics = [m for m in possible_metrics if m in first_df.columns and first_df[m].notna().any()]

    if not metrics:
        return

    # Phantom display names: simplified (Adult/Child Male/Female)
    phantom_info = {
        "duke": ("Duke", "Adult male"),
        "ella": ("Ella", "Adult female"),
        "eartha": ("Eartha", "Child female"),
        "thelonious": ("Thelonious", "Child male"),
    }

    # Use standard academic colors: black, red, dark blue, purple
    academic_colors = self._get_academic_colors(4)
    phantom_colors = {
        "duke": academic_colors[0],  # black (adult male)
        "ella": academic_colors[2],  # dark blue (adult female)
        "eartha": academic_colors[3],  # purple (child female)
        "thelonious": academic_colors[1],  # red (child male)
    }

    # Use standard academic markers and linestyles
    academic_markers = self._get_academic_markers(4)
    academic_linestyles = self._get_academic_linestyles(4)
    phantom_markers = {
        "duke": academic_markers[0],  # circle
        "ella": academic_markers[1],  # square
        "eartha": academic_markers[2],  # triangle
        "thelonious": academic_markers[3],  # diamond
    }
    phantom_linestyles = {
        "duke": academic_linestyles[0],  # solid
        "ella": academic_linestyles[1],  # dashed
        "eartha": academic_linestyles[2],  # dotted
        "thelonious": academic_linestyles[3],  # dashdot
    }

    for metric in metrics:
        # Create figure - IEEE single-column width
        fig, ax = plt.subplots(figsize=(3.5, 2.5))

        # Combine data from all phantoms
        for phantom_name, df in all_phantom_data.items():
            if metric not in df.columns or df[metric].isna().all():
                continue

            # Compute statistics per frequency: mean, 25th, 75th percentile
            freq_stats = df.groupby("frequency_mhz")[metric].agg(["mean", lambda x: x.quantile(0.25), lambda x: x.quantile(0.75)])
            freq_stats.columns = ["mean", "p25", "p75"]

            display_name, description = phantom_info.get(phantom_name.lower(), (phantom_name.capitalize(), ""))
            label = f"{display_name} ({description})" if description else display_name
            color = phantom_colors.get(phantom_name.lower(), "gray")

            # Plot line with markers and linestyle
            ax.plot(
                freq_stats.index,
                freq_stats["mean"].values,
                marker=phantom_markers.get(phantom_name.lower(), "o"),
                linestyle=phantom_linestyles.get(phantom_name.lower(), "solid"),
                color=color,
                label=label,
                linewidth=1.5,
                markersize=5,
            )

            # Add 25-75th percentile whiskers (simple error bars)
            ax.errorbar(
                freq_stats.index,
                freq_stats["mean"].values,
                yerr=[freq_stats["mean"] - freq_stats["p25"], freq_stats["p75"] - freq_stats["mean"]],
                fmt="none",  # No markers, just error bars
                color=color,
                capsize=3,
                capthick=0.7,
                elinewidth=0.7,
                alpha=0.8,
            )

        # Format axes
        ax.set_xlabel("Frequency (MHz)", fontsize=9)
        metric_label = METRIC_LABELS.get(metric, metric.replace("_", " ").title())
        ax.set_ylabel(f"{metric_label} (mW/kg)", fontsize=9)
        ax.tick_params(axis="both", labelsize=8)

        # Y-axis starts from 0
        ax.set_ylim(bottom=0)

        # Set x-axis to log scale if frequencies span wide range
        frequencies = list(all_phantom_data.values())[0]["frequency_mhz"].unique()
        if max(frequencies) / min(frequencies) > 5:
            ax.set_xscale("log")
            ax.set_xticks(sorted(frequencies))
            ax.set_xticklabels([str(int(f)) for f in sorted(frequencies)], rotation=45, ha="right")

        ax.grid(True, alpha=0.3, linestyle="--")
        ax.legend(fontsize=7, loc="upper right", frameon=True, fancybox=False, edgecolor="black")

        plt.tight_layout()

        # Save
        filename = f"line_cross_phantom_{metric}"
        title = self._get_title_with_phantom(f"Cross-Phantom Comparison: {metric_label}")
        caption = (
            f"Cross-phantom comparison of {metric_label.lower()} as a function of frequency. "
            f"Lines show means across all incident directions and polarizations. "
            f"Whiskers indicate 25th-75th percentile range. "
            f"Children show approximately 1.5-2× higher absorption than adults."
        )
        self._save_figure(fig, "line", filename, title=title, caption=caption, dpi=300)

    logging.getLogger("progress").info(
        f"  - Generated {len(metrics)} cross-phantom comparison plots",
        extra={"log_type": "info"},
    )

plot_polarization_ratio_lines

plot_polarization_ratio_lines(results_df: DataFrame, metrics: list[str] | None = None)

Plots theta/phi polarization ratio vs frequency for each direction.

Shows how the polarization sensitivity changes with frequency for different incident directions. This is unique to far-field analysis.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with placement column containing direction and polarization info.

required
metrics list[str] | None

List of metrics to analyze. If None, uses common metrics.

None
Source code in goliat/analysis/plots/line.py
def plot_polarization_ratio_lines(
    self,
    results_df: pd.DataFrame,
    metrics: list[str] | None = None,
):
    """Plots theta/phi polarization ratio vs frequency for each direction.

    Shows how the polarization sensitivity changes with frequency for different
    incident directions. This is unique to far-field analysis.

    Args:
        results_df: DataFrame with placement column containing direction and polarization info.
        metrics: List of metrics to analyze. If None, uses common metrics.
    """
    if results_df.empty:
        return

    # Parse placement to extract direction and polarization
    def parse_placement(placement: str) -> tuple[str | None, str | None]:
        parts = placement.split("_")
        if len(parts) >= 4:
            direction = f"{parts[1]}_{parts[2]}"  # e.g., "x_pos"
            pol = parts[3]  # "theta" or "phi"
            return direction, pol
        return None, None

    df = results_df.copy()
    df[["direction", "polarization"]] = df["placement"].apply(lambda x: pd.Series(parse_placement(x)))
    df = df.dropna(subset=["direction", "polarization"])

    if df.empty:
        return

    if metrics is None:
        possible_metrics = ["SAR_whole_body", "psSAR10g_brain", "psSAR10g_eyes", "psSAR10g_skin", "psSAR10g_genitals"]
        metrics = [m for m in possible_metrics if m in df.columns and df[m].notna().any()]

    if not metrics:
        return

    # Direction display names (human-readable: describes where wave comes FROM)
    direction_names = {
        "x_pos": "From left",
        "x_neg": "From right",
        "y_pos": "From back",
        "y_neg": "From front",
        "z_pos": "From below",
        "z_neg": "From above",
    }

    direction_order = ["x_pos", "x_neg", "y_pos", "y_neg", "z_pos", "z_neg"]
    available_directions = [d for d in direction_order if d in df["direction"].unique()]

    # Use standard academic colors, markers, and linestyles for metrics
    academic_colors = self._get_academic_colors(5)
    academic_markers = self._get_academic_markers(5)
    academic_linestyles = self._get_academic_linestyles(5)
    metrics_list = ["SAR_whole_body", "psSAR10g_brain", "psSAR10g_eyes", "psSAR10g_skin", "psSAR10g_genitals"]
    metric_colors = {m: academic_colors[i] for i, m in enumerate(metrics_list)}
    metric_markers = {m: academic_markers[i] for i, m in enumerate(metrics_list)}
    metric_linestyles = {m: academic_linestyles[i] for i, m in enumerate(metrics_list)}

    # First pass: compute global max ratio across all panels
    global_max_ratio = 0.0
    all_ratios = {}
    for direction in available_directions[:6]:
        dir_df = df[df["direction"] == direction]
        all_ratios[direction] = {}
        for metric in metrics:
            if metric not in dir_df.columns:
                continue
            pivot = dir_df.pivot_table(values=metric, index="frequency_mhz", columns="polarization", aggfunc="mean")
            if "theta" in pivot.columns and "phi" in pivot.columns:
                ratio = pivot["theta"] / pivot["phi"]
                ratio = ratio.dropna()
                if not ratio.empty:
                    all_ratios[direction][metric] = ratio
                    global_max_ratio = max(global_max_ratio, ratio.max())

    # Add some headroom to max
    y_max = max(global_max_ratio * 1.1, 1.5)

    # Create 2x3 panel figure - IEEE single-column width
    fig = plt.figure(figsize=(3.5, 4.5))
    gs = fig.add_gridspec(2, 3, hspace=0.45, wspace=0.3, bottom=0.18)

    legend_handles = []
    legend_labels = []

    for panel_idx, direction in enumerate(available_directions[:6]):
        row = panel_idx // 3
        col = panel_idx % 3
        ax = fig.add_subplot(gs[row, col])

        for metric in metrics:
            if direction not in all_ratios or metric not in all_ratios[direction]:
                continue

            ratio = all_ratios[direction][metric]
            color = metric_colors.get(metric, "gray")
            marker = metric_markers.get(metric, "o")
            linestyle = metric_linestyles.get(metric, "solid")
            label = metric.replace("SAR_", "").replace("psSAR10g_", "").replace("_", " ").title()

            (line,) = ax.plot(
                ratio.index,
                ratio.values,
                marker=marker,
                linestyle=linestyle,
                color=color,
                linewidth=1.0,
                markersize=3,
            )

            # Collect legend items only once (from first panel)
            if panel_idx == 0:
                legend_handles.append(line)
                legend_labels.append(label)

        # Reference line at ratio=1.0
        ax.axhline(y=1.0, color="gray", linestyle="--", linewidth=0.8, alpha=0.7)

        # Formatting
        ax.set_title(direction_names.get(direction, direction), fontsize=9)
        ax.set_xlabel("Frequency (MHz)", fontsize=8)
        if col == 0:
            ax.set_ylabel("Theta/Phi Ratio", fontsize=8)
        ax.tick_params(axis="both", labelsize=7)

        # Y-axis: start from 0, use global max
        ax.set_ylim(0, y_max)

        # Log scale for x-axis
        frequencies = sorted(df["frequency_mhz"].unique())
        if len(frequencies) > 1 and max(frequencies) / min(frequencies) > 5:
            ax.set_xscale("log")
            ax.set_xticks(frequencies)
            ax.set_xticklabels([str(int(f)) for f in frequencies], rotation=45, ha="right", fontsize=6)

        ax.grid(True, alpha=0.3, linestyle="--")

    # Add shared legend below all subplots
    fig.legend(
        legend_handles,
        legend_labels,
        loc="lower center",
        ncol=len(legend_labels),
        fontsize=8,
        frameon=True,
        fancybox=False,
        edgecolor="black",
        bbox_to_anchor=(0.5, 0.02),
    )

    # Save
    filename = "line_polarization_ratio_by_direction"
    title = self._get_title_with_phantom("Polarization Ratio vs Frequency by Direction")
    caption = (
        "Theta/phi polarization ratio as a function of frequency for each incident direction. "
        "Ratio > 1.0 indicates theta polarization gives higher SAR; ratio < 1.0 indicates phi dominates. "
        "The gray dashed line marks the equal polarization reference (ratio = 1.0). "
        "Significant frequency-dependent variations indicate complex polarization sensitivity."
    )
    self._save_figure(fig, "line", filename, title=title, caption=caption, dpi=300)

    logging.getLogger("progress").info(
        "  - Generated polarization ratio line plot",
        extra={"log_type": "info"},
    )

goliat.analysis.plots.outliers.OutliersPlotter

OutliersPlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Bases: BasePlotter

Generates outlier detection plots for SAR analysis.

Source code in goliat/analysis/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

identify_outliers

identify_outliers(results_df: DataFrame, metrics: str | list[str], scenario_name: str | None = None, method: str = 'iqr', threshold: float = 1.5)

Identifies and visualizes outliers in SAR metrics.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with simulation results.

required
metrics str | list[str]

Single metric column name or list of metric column names to check for outliers.

required
scenario_name str | None

Optional scenario name for filtering.

None
method str

Method for outlier detection ('iqr' for Interquartile Range, 'zscore' for Z-score).

'iqr'
threshold float

Threshold multiplier for IQR method or Z-score threshold.

1.5

Returns:

Type Description

DataFrame containing outlier rows, or None if no outliers found.

Source code in goliat/analysis/plots/outliers.py
def identify_outliers(
    self,
    results_df: pd.DataFrame,
    metrics: str | list[str],
    scenario_name: str | None = None,
    method: str = "iqr",
    threshold: float = 1.5,
):
    """Identifies and visualizes outliers in SAR metrics.

    Args:
        results_df: DataFrame with simulation results.
        metrics: Single metric column name or list of metric column names to check for outliers.
        scenario_name: Optional scenario name for filtering.
        method: Method for outlier detection ('iqr' for Interquartile Range, 'zscore' for Z-score).
        threshold: Threshold multiplier for IQR method or Z-score threshold.

    Returns:
        DataFrame containing outlier rows, or None if no outliers found.
    """
    plot_df = results_df.copy()

    if scenario_name:
        plot_df = plot_df[plot_df["scenario"] == scenario_name].copy()

    if plot_df.empty:
        return pd.DataFrame()  # Return empty DataFrame instead of None

    # Normalize metrics to list
    if isinstance(metrics, str):
        metrics = [metrics]

    outlier_summary = []
    all_outlier_dfs = []  # Collect all outlier DataFrames

    for metric in metrics:
        if metric not in plot_df.columns:
            continue

        metric_data = plot_df[metric].dropna()
        if metric_data.empty:
            continue

        if method == "iqr":
            Q1 = metric_data.quantile(0.25)
            Q3 = metric_data.quantile(0.75)
            IQR = Q3 - Q1
            lower_bound = Q1 - threshold * IQR
            upper_bound = Q3 + threshold * IQR
            outliers = plot_df[(plot_df[metric] < lower_bound) | (plot_df[metric] > upper_bound)]
        elif method == "zscore":
            mean_val = metric_data.mean()
            std_val = metric_data.std()
            if std_val == 0:
                continue
            z_scores = np.abs((plot_df[metric] - mean_val) / std_val)
            outliers = plot_df[z_scores > threshold]
        else:
            continue

        if not outliers.empty:
            outlier_summary.append(
                {
                    "metric": metric,
                    "count": len(outliers),
                    "outliers": outliers,
                }
            )
            all_outlier_dfs.append(outliers)

    if not outlier_summary:
        logging.getLogger("progress").info(
            f"  - No outliers detected for metrics: {', '.join(metrics)}",
            extra={"log_type": "info"},
        )
        return pd.DataFrame()  # Return empty DataFrame instead of None

    # Collect all outlier rows into a single DataFrame
    if all_outlier_dfs:
        all_outliers = pd.concat(all_outlier_dfs, ignore_index=True)
        # Drop duplicates based on hashable columns only (avoid unhashable types like dicts)
        # Get list of columns that are hashable (numeric, string, etc.)
        hashable_cols = []
        for col in all_outliers.columns:
            try:
                # Try to hash a sample value to check if column is hashable
                sample_val = all_outliers[col].dropna().iloc[0] if not all_outliers[col].dropna().empty else None
                if sample_val is not None:
                    hash(sample_val)
                    hashable_cols.append(col)
            except (TypeError, IndexError):
                # Column contains unhashable types, skip it
                continue

        # Drop duplicates using only hashable columns, or all columns if none are hashable
        if hashable_cols:
            try:
                all_outliers = all_outliers.drop_duplicates(subset=hashable_cols)
            except (TypeError, ValueError):
                # If still fails, just return all outliers without deduplication
                pass
        # If no hashable columns, just return all outliers (no deduplication possible)
    else:
        all_outliers = pd.DataFrame()

    # Create visualization
    n_metrics = len(outlier_summary)
    fig, axes = plt.subplots(n_metrics, 1, figsize=(3.5, 2.0 * n_metrics))  # IEEE single-column width
    if n_metrics == 1:
        axes = [axes]

    for idx, summary in enumerate(outlier_summary):
        ax = axes[idx]
        metric = summary["metric"]
        outliers = summary["outliers"]

        # Boxplot with outliers highlighted
        plot_data = plot_df[metric].dropna()
        bp = ax.boxplot([plot_data], vert=True, patch_artist=True, showfliers=True)
        bp["boxes"][0].set_facecolor("lightblue")
        bp["boxes"][0].set_alpha(0.7)

        # Highlight outliers
        outlier_values = outliers[metric].dropna()
        if not outlier_values.empty:
            ax.scatter([1] * len(outlier_values), outlier_values.values, color="red", s=30, alpha=0.7, marker="x", label="Outliers")

        ax.set_ylabel(f"{METRIC_LABELS.get(metric, metric)} (mW kg$^{{-1}}$)")
        # Don't set title on plot - will be in caption file
        ax.grid(True, alpha=0.3, axis="y")
        if not outlier_values.empty:
            ax.legend()
        # Set y-axis to start at 0 and go to max + 5%
        y_max = ax.get_ylim()[1]
        ax.set_ylim(0, y_max * 1.05)

    plt.tight_layout()

    filename_base = f"outliers_{method}_{scenario_name or 'all'}"
    metrics_list = ", ".join(str(METRIC_LABELS.get(s["metric"], s["metric"])) for s in outlier_summary)
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The outlier detection plots show metrics {metrics_list} using {method} method for the {self._format_scenario_name(scenario_name) if scenario_name else 'all scenarios'} scenario for {phantom_name_formatted}. Outliers are marked with red 'x' markers."
    title_full = self._get_title_with_phantom(f"outlier detection ({method} method)")
    filename = self._save_figure(fig, "outliers", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data
    if not all_outliers.empty:
        self._save_csv_data(all_outliers, "outliers", filename_base)
    logging.getLogger("progress").info(
        f"  - Generated outlier detection plot: {filename}",
        extra={"log_type": "success"},
    )

    # Return DataFrame of all outliers
    return all_outliers

goliat.analysis.plots.penetration.PenetrationPlotter

PenetrationPlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Bases: BasePlotter

Generates penetration depth plots for SAR analysis.

Source code in goliat/analysis/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

plot_penetration_depth_ratio

plot_penetration_depth_ratio(results_df: DataFrame, scenario_name: str | None = None, metric_type: str = 'psSAR10g')

Creates line plot showing SAR penetration depth ratio (Brain/Skin) vs frequency.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with psSAR10g_brain/psSAR10g_skin or SAR_brain/SAR_skin columns.

required
scenario_name str | None

Optional scenario name for filtering.

None
metric_type str

Type of SAR metric to use ('psSAR10g' or 'SAR').

'psSAR10g'
Source code in goliat/analysis/plots/penetration.py
def plot_penetration_depth_ratio(
    self,
    results_df: pd.DataFrame,
    scenario_name: str | None = None,
    metric_type: str = "psSAR10g",
):
    """Creates line plot showing SAR penetration depth ratio (Brain/Skin) vs frequency.

    Args:
        results_df: DataFrame with psSAR10g_brain/psSAR10g_skin or SAR_brain/SAR_skin columns.
        scenario_name: Optional scenario name for filtering.
        metric_type: Type of SAR metric to use ('psSAR10g' or 'SAR').
    """
    brain_col = f"{metric_type}_brain"
    skin_col = f"{metric_type}_skin"
    required_cols = ["frequency_mhz", brain_col, skin_col]
    if not all(col in results_df.columns for col in required_cols):
        logging.getLogger("progress").warning(
            f"Missing columns for {metric_type} penetration depth plot: {brain_col}, {skin_col}.",
            extra={"log_type": "warning"},
        )
        return

    if scenario_name:
        plot_df = results_df[results_df["scenario"] == scenario_name].copy()
    else:
        plot_df = results_df.copy()

    # Calculate ratio
    plot_df = plot_df.copy()
    plot_df["penetration_ratio"] = plot_df[brain_col] / plot_df[skin_col]
    plot_df = plot_df.dropna(subset=["penetration_ratio"])
    plot_df = plot_df[plot_df["penetration_ratio"] > 0]  # Remove invalid ratios

    if plot_df.empty:
        return

    # Group by frequency
    avg_ratio = plot_df.groupby("frequency_mhz")["penetration_ratio"].mean().reset_index()

    fig, ax = plt.subplots(figsize=(3.5, 2.5))  # IEEE single-column width

    linestyles = self._get_academic_linestyles(1)
    markers = self._get_academic_markers(1)
    colors = self._get_academic_colors(1)

    ax.plot(
        avg_ratio["frequency_mhz"],
        avg_ratio["penetration_ratio"],
        marker=markers[0],
        linestyle=linestyles[0],
        color=colors[0],
        linewidth=2,
        markersize=4,
    )

    ax.set_xlabel(self._format_axis_label("Frequency", "MHz"))
    ax.set_ylabel(f"Ratio ({metric_type} Brain / {metric_type} Skin)")
    ax.set_yscale("log")
    # Rotate x-axis labels only for actual simulated frequencies
    # Rotate frequency labels (always rotate when x-axis is Frequency)
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
    self._adjust_slanted_tick_labels(ax)
    formatted_scenario = self._format_scenario_name(scenario_name) if scenario_name else None
    if formatted_scenario:
        base_title = f"SAR penetration depth brain to skin {metric_type} ratio versus frequency for {formatted_scenario} scenario"
    else:
        base_title = f"SAR penetration depth brain to skin {metric_type} ratio versus frequency"
    title_full = self._get_title_with_phantom(base_title)
    # Don't set title on plot - will be in caption file
    ax.grid(True, which="both", ls="--", alpha=0.3)

    plt.tight_layout()

    filename_base = f"penetration_ratio_{metric_type}_vs_frequency_{scenario_name or 'all'}"
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The line plot shows the SAR penetration depth ratio (Brain/Skin) for {metric_type} as a function of frequency for the {self._format_scenario_name(scenario_name) if scenario_name else 'all scenarios'} scenario for {phantom_name_formatted}. Higher ratios indicate deeper penetration into brain tissue relative to skin."
    filename = self._save_figure(fig, "penetration", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = avg_ratio[["frequency_mhz", "penetration_ratio"]].copy()
    self._save_csv_data(csv_data, "penetration", filename_base)
    logging.getLogger("progress").info(
        f"  - Generated penetration depth plot: {filename}",
        extra={"log_type": "success"},
    )

goliat.analysis.plots.power.PowerPlotter

PowerPlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Bases: BasePlotter

Generates power balance plots for SAR analysis.

Source code in goliat/analysis/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

plot_power_efficiency_trends(results_df: DataFrame, scenario_name: str | None = None)

Creates line plot showing antenna efficiency and power component percentages across frequencies.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with power balance columns.

required
scenario_name str | None

Optional scenario name for filtering.

None
Source code in goliat/analysis/plots/power.py
def plot_power_efficiency_trends(
    self,
    results_df: pd.DataFrame,
    scenario_name: str | None = None,
):
    """Creates line plot showing antenna efficiency and power component percentages across frequencies.

    Args:
        results_df: DataFrame with power balance columns.
        scenario_name: Optional scenario name for filtering.
    """
    if scenario_name:
        plot_df = results_df[results_df["scenario"] == scenario_name].copy()
    else:
        plot_df = results_df.copy()

    required_cols = ["frequency_mhz", "power_pin_W", "power_rad_W", "power_diel_loss_W", "power_sibc_loss_W"]
    missing_cols = [col for col in required_cols if col not in plot_df.columns]
    if missing_cols:
        logging.getLogger("progress").warning(
            f"Missing columns for power efficiency plot: {missing_cols}",
            extra={"log_type": "warning"},
        )
        return

    # Calculate efficiency and percentages
    plot_df = plot_df.copy()
    plot_df["efficiency"] = (plot_df["power_rad_W"] / plot_df["power_pin_W"]) * 100
    plot_df["diel_loss_pct"] = (plot_df["power_diel_loss_W"] / plot_df["power_pin_W"]) * 100
    plot_df["sibc_loss_pct"] = (plot_df["power_sibc_loss_W"] / plot_df["power_pin_W"]) * 100
    plot_df["rad_pct"] = (plot_df["power_rad_W"] / plot_df["power_pin_W"]) * 100

    # Group by frequency
    freq_summary = (
        plot_df.groupby("frequency_mhz")
        .agg(
            {
                "efficiency": "mean",
                "diel_loss_pct": "mean",
                "sibc_loss_pct": "mean",
                "rad_pct": "mean",
            }
        )
        .reset_index()
    )

    fig, axes = plt.subplots(2, 1, figsize=(3.5, 4.5))  # IEEE single-column width, taller for 2 subplots

    # Top plot: Efficiency
    ax1 = axes[0]
    markers = self._get_academic_markers(1)
    linestyles = self._get_academic_linestyles(1)
    colors = self._get_academic_colors(1)
    ax1.plot(
        freq_summary["frequency_mhz"],
        freq_summary["efficiency"],
        marker=markers[0],
        linestyle=linestyles[0],
        linewidth=2,
        markersize=4,
        label="Antenna Efficiency",
        color=colors[0],
    )
    ax1.set_xlabel(self._format_axis_label("Frequency", "MHz"))
    ax1.set_ylabel(self._format_axis_label("Efficiency", "%"))
    ax1.set_title("Antenna efficiency vs frequency")  # Subplot title - keep it
    # Set explicit x-axis limits fitted to frequencies
    freq_min = freq_summary["frequency_mhz"].min()
    freq_max = freq_summary["frequency_mhz"].max()
    freq_range = freq_max - freq_min
    ax1.set_xlim(freq_min - freq_range * 0.05, freq_max + freq_range * 0.05)
    # Rotate x-axis labels for real number line frequencies
    plt.setp(ax1.get_xticklabels(), rotation=45, ha="right")
    self._adjust_slanted_tick_labels(ax1)
    ax1.grid(True, alpha=0.3)
    ax1.legend()
    # Set y-axis to go up to 100%
    ax1.set_ylim(0, 100)

    # Bottom plot: Grouped bar chart for better visibility
    ax2 = axes[1]
    # Force x-axis to start at first frequency and end at last frequency
    ax2.set_xlim(freq_min, freq_max)

    # Check if SIBC loss is consistently very small (< 2%)
    sibc_max = freq_summary["sibc_loss_pct"].max()
    if sibc_max < 2.0:
        # Plot SIBC as a separate line on secondary y-axis for visibility
        ax2_twin = ax2.twinx()
        ax2.fill_between(
            freq_summary["frequency_mhz"], 0, freq_summary["diel_loss_pct"], label="Dielectric Loss", alpha=0.7, color="#00008B"
        )  # Dark blue
        ax2.fill_between(
            freq_summary["frequency_mhz"],
            freq_summary["diel_loss_pct"],
            100,
            label="Radiated Power",
            alpha=0.7,
            color="purple",  # Purple instead of green
        )
        # Use distinct markers for SIBC line
        markers = self._get_academic_markers(2)  # Get 2 to pick a different one if needed, or just use index 1
        linestyles = self._get_academic_linestyles(2)
        ax2_twin.plot(
            freq_summary["frequency_mhz"],
            freq_summary["sibc_loss_pct"],
            marker=markers[1] if len(markers) > 1 else "s",
            linestyle=linestyles[1] if len(linestyles) > 1 else "--",
            label="SIBC Loss",
            color="orange",
            linewidth=2,
            markersize=4,
        )
        ax2_twin.set_ylabel("SIBC Loss (%)", color="orange", fontsize=10)
        ax2_twin.tick_params(axis="y", labelcolor="orange")
        ax2_twin.set_ylim(0, max(sibc_max * 1.2, 0.5))
        # Combine legends - move to top right
        lines1, labels1 = ax2.get_legend_handles_labels()
        lines2, labels2 = ax2_twin.get_legend_handles_labels()
        ax2.legend(lines1 + lines2, labels1 + labels2, loc="upper right")
    else:
        # Normal stacked area chart
        ax2.fill_between(freq_summary["frequency_mhz"], 0, freq_summary["diel_loss_pct"], label="Dielectric Loss", alpha=0.7)
        ax2.fill_between(
            freq_summary["frequency_mhz"],
            freq_summary["diel_loss_pct"],
            freq_summary["diel_loss_pct"] + freq_summary["sibc_loss_pct"],
            label="SIBC Loss",
            alpha=0.7,
        )
        ax2.fill_between(
            freq_summary["frequency_mhz"],
            freq_summary["diel_loss_pct"] + freq_summary["sibc_loss_pct"],
            100,
            label="Radiated Power",
            alpha=0.7,
        )
        ax2.legend(loc="upper right")

    ax2.set_xlabel(self._format_axis_label("Frequency", "MHz"))
    ax2.set_ylabel(self._format_axis_label("Percentage of input power", "%"))
    ax2.set_title("Power component breakdown vs frequency")  # Subplot title - keep it
    # Rotate x-axis labels for real number line frequencies
    # Rotate x-axis labels only for actual simulated frequencies
    # Rotate frequency labels (always rotate when x-axis is Frequency)
    plt.setp(ax2.get_xticklabels(), rotation=45, ha="right")
    self._adjust_slanted_tick_labels(ax2)
    ax2.set_ylim(0, 100)  # Already starts at 0, max is 100%
    ax2.grid(True, alpha=0.3)

    # Create title with phantom name
    base_title = "power efficiency trends"
    title_full = self._get_title_with_phantom(base_title, scenario_name)
    # Don't set suptitle - will be in caption file
    plt.tight_layout()

    filename_base = f"power_efficiency_{scenario_name or 'all'}"
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The power efficiency analysis shows antenna efficiency and power component breakdown (dielectric loss, SIBC loss, radiated power) as a function of frequency for the {self._format_scenario_name(scenario_name) if scenario_name else 'all scenarios'} scenario for {phantom_name_formatted}."
    filename = self._save_figure(fig, "power", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = pd.DataFrame(
        {
            "frequency_mhz": freq_summary["frequency_mhz"],
            "efficiency": freq_summary["efficiency"],
            "dielectric_loss": freq_summary.get("dielectric_loss", np.nan),
            "sibc_loss": freq_summary.get("sibc_loss", np.nan),
            "radiated_power": freq_summary.get("radiated_power", np.nan),
        }
    )
    self._save_csv_data(csv_data, "power", filename_base)
    logging.getLogger("progress").info(
        f"  - Generated power efficiency plot: {filename}",
        extra={"log_type": "success"},
    )

plot_power_absorption_distribution

plot_power_absorption_distribution(organ_results_df: DataFrame, scenario_name: str | None = None, frequency_mhz: int | None = None)

Creates pie chart or stacked bar chart showing how total power is distributed across tissue groups.

Pie charts are kept as-is (not using scienceplots) as they work well with default matplotlib.

Parameters:

Name Type Description Default
organ_results_df DataFrame

DataFrame with tissue-level data including 'Total Loss' column.

required
scenario_name str | None

Optional scenario name for filtering.

None
frequency_mhz int | None

Optional frequency for filtering.

None
Source code in goliat/analysis/plots/power.py
def plot_power_absorption_distribution(
    self,
    organ_results_df: pd.DataFrame,
    scenario_name: str | None = None,
    frequency_mhz: int | None = None,
):
    """Creates pie chart or stacked bar chart showing how total power is distributed across tissue groups.

    Pie charts are kept as-is (not using scienceplots) as they work well with default matplotlib.

    Args:
        organ_results_df: DataFrame with tissue-level data including 'Total Loss' column.
        scenario_name: Optional scenario name for filtering.
        frequency_mhz: Optional frequency for filtering.
    """
    if organ_results_df.empty or "Total Loss" not in organ_results_df.columns:
        logging.getLogger("progress").warning(
            "No 'Total Loss' data available for power absorption plot.",
            extra={"log_type": "warning"},
        )
        return

    plot_df = organ_results_df.copy()
    # Filter out 'All Regions' - it's a whole-body aggregate and would double-count in pie charts
    plot_df = self._filter_all_regions(plot_df, tissue_column="tissue")

    # Filter by frequency if provided
    if frequency_mhz is not None:
        plot_df = plot_df[plot_df["frequency_mhz"] == frequency_mhz].copy()

    # Aggregate by tissue group if available, otherwise by tissue
    if "tissue_group" in plot_df.columns:
        group_loss = plot_df.groupby("tissue_group")["Total Loss"].sum().reset_index()
        group_loss = group_loss[group_loss["Total Loss"] > 0]
    else:
        # Use individual tissues
        group_loss = plot_df.groupby("tissue")["Total Loss"].sum().reset_index()
        group_loss = group_loss[group_loss["Total Loss"] > 0]
        group_loss = group_loss.nlargest(10, "Total Loss")  # Top 10 tissues

    if group_loss.empty:
        return

    # Vertical arrangement: 2 rows, 1 column, variable height
    subplot_height = 2.5  # Height per subplot
    total_height = 2 * subplot_height
    fig, axes = plt.subplots(2, 1, figsize=(3.5, total_height))  # IEEE single-column width, vertical arrangement

    # Pie chart - group tissues <5% into "Others"
    ax1 = axes[0]
    group_loss_copy = group_loss.copy()
    group_loss_copy = group_loss_copy.sort_values("Total Loss", ascending=False)
    total_loss_sum = group_loss_copy["Total Loss"].sum()
    threshold = total_loss_sum * 0.05  # 5% threshold

    # Separate into main groups and others
    main_groups = group_loss_copy[group_loss_copy["Total Loss"] >= threshold]
    others_group = group_loss_copy[group_loss_copy["Total Loss"] < threshold]

    # Combine others if any exist
    if not others_group.empty and len(others_group) > 0:
        others_sum = others_group["Total Loss"].sum()
        others_row = pd.DataFrame({group_loss_copy.columns[0]: ["Others"], "Total Loss": [others_sum]})
        pie_data = pd.concat([main_groups, others_row], ignore_index=True)
    else:
        pie_data = main_groups

    # Generate colors - use Set3 colormap
    n_colors = len(pie_data)
    colors = plt.cm.Set3(np.linspace(0, 1, n_colors))

    wedges, texts, autotexts = ax1.pie(
        pie_data["Total Loss"],
        labels=pie_data.iloc[:, 0],
        autopct="%1.1f%%",
        colors=colors,
        startangle=90,
    )
    ax1.set_title("Power Absorption Distribution (Pie Chart)")

    # Stacked bar chart by frequency
    ax2 = axes[1]
    if frequency_mhz is None and "frequency_mhz" in plot_df.columns:
        # Aggregate across frequencies
        if "tissue_group" in plot_df.columns:
            freq_group_loss = plot_df.groupby(["frequency_mhz", "tissue_group"])["Total Loss"].sum().reset_index()
            freq_group_loss = freq_group_loss.pivot(index="frequency_mhz", columns="tissue_group", values="Total Loss").fillna(0)
        else:
            # Use top tissues
            top_tissues = plot_df.groupby("tissue")["Total Loss"].sum().nlargest(5).index
            plot_df_top = plot_df[plot_df["tissue"].isin(top_tissues)]
            freq_group_loss = plot_df_top.groupby(["frequency_mhz", "tissue"])["Total Loss"].sum().reset_index()
            freq_group_loss = freq_group_loss.pivot(index="frequency_mhz", columns="tissue", values="Total Loss").fillna(0)

        # Use same colors as pie chart - create color mapping
        # Get column order from pie chart (main groups + Others if exists)
        pie_cols = pie_data.iloc[:, 0].tolist()
        color_map = dict(zip(pie_cols, colors[: len(pie_cols)]))

        # Reorder freq_group_loss columns to match pie chart order
        freq_cols = freq_group_loss.columns.tolist()
        # Put pie chart columns first, then others
        ordered_cols = [col for col in pie_cols if col in freq_cols] + [col for col in freq_cols if col not in pie_cols]
        freq_group_loss_ordered = freq_group_loss[ordered_cols]

        # Create color list matching column order
        bar_colors = [color_map.get(col, plt.cm.Set3(0.5)) for col in ordered_cols]

        freq_group_loss_ordered.plot(kind="bar", stacked=True, ax=ax2, color=bar_colors)
        ax2.set_xlabel("Frequency (MHz)")
        ax2.set_ylabel("Total Loss (W)")
        ax2.set_title("Power Absorption Distribution by Frequency (Stacked)")
        # Format legend labels to be human readable and place below subfigure
        legend = ax2.get_legend()
        if legend:
            # Get current labels and format them
            current_labels = [t.get_text() for t in legend.get_texts()]
            formatted_labels = []
            for label in current_labels:
                # Format tissue group names
                formatted_label = (
                    self._format_organ_name(label) if hasattr(self, "_format_organ_name") else label.replace("_", " ").title()
                )
                formatted_labels.append(formatted_label)
            # Remove old legend and create new one below
            legend.remove()
            legend_new = ax2.legend(
                title="Tissue Group",
                labels=formatted_labels,
                loc="upper center",
                bbox_to_anchor=(0.5, -0.25),
                ncol=min(3, len(formatted_labels)),
                fontsize=8,
            )
            legend_new.get_frame().set_linewidth(0.5)
            legend_new.get_frame().set_edgecolor("black")
            # Adjust subplot to accommodate legend
            fig.subplots_adjust(bottom=0.3)
        else:
            legend_new = ax2.legend(title="Tissue Group", loc="upper center", bbox_to_anchor=(0.5, -0.25))
            legend_new.get_frame().set_linewidth(0.5)
            legend_new.get_frame().set_edgecolor("black")
            fig.subplots_adjust(bottom=0.3)
        # Rotate frequency labels (always rotate when x-axis is Frequency)
        plt.setp(ax2.get_xticklabels(), rotation=45, ha="right")
        self._adjust_slanted_tick_labels(ax2)
    else:
        ax2.text(0.5, 0.5, "Single frequency - use pie chart", ha="center", va="center", transform=ax2.transAxes)
        ax2.set_title("Power Absorption Distribution")

    base_title = "power absorption distribution"
    title_full = self._get_title_with_phantom(base_title, scenario_name)
    plt.tight_layout()

    filename_base = f"power_absorption_{scenario_name or 'all'}_{frequency_mhz or 'all'}MHz"
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The power absorption distribution analysis shows pie chart of total power loss by tissue group and stacked bar chart by frequency for the {self._format_scenario_name(scenario_name) if scenario_name else 'all scenarios'} scenario{f' at {frequency_mhz} MHz' if frequency_mhz else ''} for {phantom_name_formatted}."
    filename = self._save_figure(fig, "power", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = (
        plot_df[["tissue_group", "Total Loss", "frequency_mhz"]].copy()
        if "tissue_group" in plot_df.columns
        else plot_df[["tissue", "Total Loss", "frequency_mhz"]].copy()
    )
    self._save_csv_data(csv_data, "power", filename_base)
    logging.getLogger("progress").info(
        f"  - Generated power absorption plot: {filename}",
        extra={"log_type": "success"},
    )

plot_power_balance_overview

plot_power_balance_overview(results_df: DataFrame)

Creates power balance overview heatmap with all components.

Parameters:

Name Type Description Default
results_df DataFrame

DataFrame with power balance columns.

required
Source code in goliat/analysis/plots/power.py
def plot_power_balance_overview(self, results_df: pd.DataFrame):
    """Creates power balance overview heatmap with all components.

    Args:
        results_df: DataFrame with power balance columns.
    """
    power_df = self._prepare_power_data(results_df)
    if power_df is None:
        return

    # Group by frequency and scenario
    balance_summary = (
        power_df.groupby(["frequency_mhz", "scenario"])
        .agg(
            {
                "power_balance_pct": ["mean", "std", "min", "max"],
                "power_pin_W": "mean",
                "power_rad_W": "mean",
                "power_diel_loss_W": "mean",
                "power_sibc_loss_W": "mean",
            }
        )
        .reset_index()
    )

    # Flatten column names
    balance_summary.columns = ["_".join(col).strip("_") if col[1] else col[0] for col in balance_summary.columns.values]

    # Vertical arrangement: 3 rows, 1 column for heatmaps only
    subplot_height = 2.5  # Height per subplot
    total_height = 3 * subplot_height
    fig, axes = plt.subplots(3, 1, figsize=(3.5, total_height))  # IEEE single-column width, vertical arrangement

    # Balance percentage heatmap - round to one decimal, start at 0, red to green colormap
    balance_pivot = balance_summary.pivot(index="scenario", columns="frequency_mhz", values="power_balance_pct_mean")
    sns.heatmap(balance_pivot, annot=True, fmt=".1f", cmap="RdYlGn", center=100, vmin=0, ax=axes[0], cbar_kws={"label": "Balance (%)"})
    axes[0].set_title("Power Balance Percentage")
    axes[0].set_ylabel("Scenario")
    axes[0].tick_params(which="minor", length=0)  # No minor ticks

    # Input power heatmap - convert to mW, start at 0
    pin_pivot = balance_summary.pivot(index="scenario", columns="frequency_mhz", values="power_pin_W_mean")
    pin_pivot_mW = pin_pivot * 1000  # Convert W to mW
    sns.heatmap(pin_pivot_mW, annot=True, fmt=".1f", cmap="jet", vmin=0, ax=axes[1], cbar_kws={"label": "Power (mW)"})
    axes[1].set_title("Input Power")
    axes[1].set_ylabel("Scenario")
    axes[1].tick_params(which="minor", length=0)  # No minor ticks

    # Radiated power heatmap - convert to mW, start at 0
    rad_pivot = balance_summary.pivot(index="scenario", columns="frequency_mhz", values="power_rad_W_mean")
    rad_pivot_mW = rad_pivot * 1000  # Convert W to mW
    sns.heatmap(rad_pivot_mW, annot=True, fmt=".1f", cmap="jet", vmin=0, ax=axes[2], cbar_kws={"label": "Power (mW)"})
    axes[2].set_title("Radiated Power")
    axes[2].set_xlabel(self._format_axis_label("Frequency", "MHz"))
    axes[2].set_ylabel("Scenario")
    axes[2].tick_params(which="minor", length=0)  # No minor ticks

    base_title = "power balance overview"
    title_full = self._get_title_with_phantom(base_title)
    # Don't set suptitle - will be in caption file
    plt.tight_layout()

    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The power balance overview shows heatmaps of power balance percentage, input power, and radiated power across scenarios and frequencies for {phantom_name_formatted}."
    filename = self._save_figure(fig, "power", "power_balance_overview", title=title_full, caption=caption, dpi=300)

    # Now create separate figure for Power Loss Breakdown
    loss_diel_pivot = (
        balance_summary.pivot(index="scenario", columns="frequency_mhz", values="power_diel_loss_W_mean") * 1000
    )  # Convert to mW
    loss_sibc_pivot = (
        balance_summary.pivot(index="scenario", columns="frequency_mhz", values="power_sibc_loss_W_mean") * 1000
    )  # Convert to mW

    if not loss_diel_pivot.empty:
        # Sum across frequencies for each scenario
        loss_diel_sum = loss_diel_pivot.sum(axis=1)
        loss_sibc_sum = loss_sibc_pivot.sum(axis=1)

        # Create DataFrame for stacked bar chart
        loss_combined = pd.DataFrame({"Dielectric": loss_diel_sum, "SIBC": loss_sibc_sum})

        # Create separate figure for Power Loss Breakdown
        fig_loss, ax_loss = plt.subplots(figsize=(3.5, 2.5))  # IEEE single-column width
        loss_combined.plot(kind="bar", stacked=True, ax=ax_loss, color=["#00008B", "orange"])  # Dark blue instead of blue
        ax_loss.set_title("Power Loss Breakdown")
        ax_loss.set_xlabel("Scenario")
        ax_loss.set_ylabel("Power Loss (mW)")
        ax_loss.legend(title="Loss Type", labels=["Dielectric", "SIBC"])
        ax_loss.set_ylim(bottom=0)  # Start at 0
        plt.setp(ax_loss.get_xticklabels(), rotation=45, ha="right")
        self._adjust_slanted_tick_labels(ax_loss)

        base_title_loss = "power loss breakdown"
        title_full_loss = self._get_title_with_phantom(base_title_loss)
        plt.tight_layout()

        phantom_name_formatted_loss = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
        caption_loss = f"The power loss breakdown shows stacked bar chart of dielectric and SIBC power losses summed across frequencies for each scenario for {phantom_name_formatted_loss}."
        filename_loss = self._save_figure(
            fig_loss, "power", "power_loss_breakdown", title=title_full_loss, caption=caption_loss, dpi=300
        )
        logging.getLogger("progress").info(
            "  - Generated power loss breakdown",
            extra={"log_type": "success"},
        )

    # Save CSV data - save the power balance data
    csv_data = power_df.copy() if "power_df" in locals() else pd.DataFrame()
    if not csv_data.empty:
        self._save_csv_data(csv_data, "power", "power_balance_overview")
    logging.getLogger("progress").info(
        "  - Generated power balance overview",
        extra={"log_type": "success"},
    )

goliat.analysis.plots.ranking.RankingPlotter

RankingPlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Bases: BasePlotter

Generates ranking plots for SAR analysis.

Source code in goliat/analysis/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

plot_top20_tissues_ranking

plot_top20_tissues_ranking(organ_results_df: DataFrame, metric: str = 'max_local_sar_mw_kg', scenario_name: str | None = None, frequency_mhz: int | None = None)

Creates horizontal bar chart showing top 20 tissues ranked by various metrics.

Parameters:

Name Type Description Default
organ_results_df DataFrame

DataFrame with tissue-level data.

required
metric str

Metric to rank by (e.g., 'max_local_sar_mw_kg', 'mass_avg_sar_mw_kg', 'Total Loss').

'max_local_sar_mw_kg'
scenario_name str | None

Optional scenario name for filtering.

None
frequency_mhz int | None

Optional frequency for filtering.

None
Source code in goliat/analysis/plots/ranking.py
def plot_top20_tissues_ranking(
    self,
    organ_results_df: pd.DataFrame,
    metric: str = "max_local_sar_mw_kg",
    scenario_name: str | None = None,
    frequency_mhz: int | None = None,
):
    """Creates horizontal bar chart showing top 20 tissues ranked by various metrics.

    Args:
        organ_results_df: DataFrame with tissue-level data.
        metric: Metric to rank by (e.g., 'max_local_sar_mw_kg', 'mass_avg_sar_mw_kg', 'Total Loss').
        scenario_name: Optional scenario name for filtering.
        frequency_mhz: Optional frequency for filtering.
    """
    if organ_results_df.empty:
        return

    plot_df = organ_results_df.copy()
    # Filter out 'All Regions' - it's a whole-body aggregate, not a real tissue
    plot_df = self._filter_all_regions(plot_df, tissue_column="tissue")

    # Filter by frequency if provided
    if frequency_mhz is not None:
        plot_df = plot_df[plot_df["frequency_mhz"] == frequency_mhz].copy()

    if metric not in plot_df.columns:
        logging.getLogger("progress").warning(
            f"Metric '{metric}' not found in data.",
            extra={"log_type": "warning"},
        )
        return

    # Aggregate by tissue
    if "placement" in plot_df.columns:
        plot_df = (
            plot_df.groupby("tissue")
            .agg(
                {
                    metric: "mean",
                }
            )
            .reset_index()
        )

    # Get top 20
    top20 = plot_df.nlargest(20, metric).sort_values(metric, ascending=True)

    if top20.empty:
        return

    fig, ax = plt.subplots(figsize=(3.5, 4.0))  # IEEE single-column width, taller for ranking

    # Auto-detect unit family based on max value
    max_val_raw = top20[metric].max()
    unit_multiplier = 1.0
    unit_label = r"mW kg$^{-1}$"

    if max_val_raw < 1e-6:
        unit_multiplier = 1e9
        unit_label = r"nW kg$^{-1}$"
    elif max_val_raw < 1e-3:
        unit_multiplier = 1e6
        unit_label = r"$\mu$W kg$^{{-1}}$"
    elif max_val_raw < 1.0:
        unit_multiplier = 1e3
        unit_label = r"mW kg$^{-1}$"
    # else: keep as mW/kg (default)

    # Scale values for display
    top20_scaled = top20.copy()
    top20_scaled[metric] = top20_scaled[metric] * unit_multiplier

    # Detect outliers: if ratio between #1 and #2 > 2.5, cap the display
    outlier_threshold = 2.5
    values_sorted = top20_scaled[metric].sort_values(ascending=False)
    has_outlier = False
    outlier_cap_value = None

    if len(values_sorted) >= 2:
        first_val = values_sorted.iloc[0]
        second_val = values_sorted.iloc[1]
        if second_val > 0 and first_val / second_val > outlier_threshold:
            has_outlier = True
            # Cap at 1.5x the second value for display
            outlier_cap_value = second_val * 1.5

    # Color by tissue group using academic color palette
    colors = self._get_academic_colors(len(top20_scaled))

    # Clean and format tissue names (remove redundant phantom identifiers and format for display)
    top20_clean = top20_scaled.copy()
    top20_clean["tissue_clean"] = top20_clean["tissue"].apply(lambda x: self._format_organ_name(x))

    # Create display values - cap outliers if needed
    display_values = top20_clean[metric].copy()
    outlier_mask = pd.Series([False] * len(display_values), index=display_values.index)

    if has_outlier and outlier_cap_value is not None:
        # Mark the outlier(s) - values that are significantly higher than the cap
        outlier_mask = display_values > outlier_cap_value
        display_values = display_values.clip(upper=outlier_cap_value)

    # Draw bars
    bar_positions = range(len(top20_clean))
    bars = ax.barh(bar_positions, display_values, color=colors, alpha=0.7, edgecolor="black", linewidth=0.5)

    # Add broken bar pattern for outliers
    if has_outlier:
        for i, (bar, is_outlier) in enumerate(zip(bars, outlier_mask.values)):
            if is_outlier:
                # Add diagonal lines to indicate broken/capped bar
                bar_height = bar.get_height()
                bar_y = bar.get_y()
                bar_width = bar.get_width()

                # Add break marks at the end of the bar
                break_x = bar_width * 0.95
                ax.plot([break_x, break_x], [bar_y + 0.1, bar_y + bar_height - 0.1], color="white", linewidth=2, zorder=3)
                ax.plot(
                    [break_x - bar_width * 0.02, break_x + bar_width * 0.02],
                    [bar_y + bar_height * 0.3, bar_y + bar_height * 0.7],
                    color="white",
                    linewidth=2,
                    zorder=3,
                )
                ax.plot(
                    [break_x - bar_width * 0.02, break_x + bar_width * 0.02],
                    [bar_y + bar_height * 0.7, bar_y + bar_height * 0.3],
                    color="white",
                    linewidth=2,
                    zorder=3,
                )

    ax.set_yticks(bar_positions)
    ax.set_yticklabels(top20_clean["tissue_clean"], fontsize=9)
    ax.tick_params(axis="y", which="major", length=0)  # Remove y-axis tick marks
    # Reduce top and bottom margins
    ax.margins(y=0.01)  # Minimal top/bottom margins

    # Format x-axis label properly
    metric_display = metric.replace("_mw_kg", "").replace("_", " ")
    # Capitalize properly, preserving SAR and psSAR10g acronyms
    metric_words = metric_display.split()
    metric_formatted = []
    for word in metric_words:
        word_lower = word.lower()
        # Check for psSAR10g in any capitalization variation and fix it
        if "pssar10g" in word_lower:
            # Replace any variation (pssar10g, Pssar10g, PSSAR10G, etc.) with psSAR10g
            metric_formatted.append("psSAR10g")
        elif word.upper() == "SAR":
            metric_formatted.append("SAR")
        else:
            metric_formatted.append(word.capitalize())
    metric_display = " ".join(metric_formatted)
    # Final safety check: replace any incorrect psSAR10g capitalization
    metric_display = metric_display.replace("Pssar10g", "psSAR10g").replace("PSSAR10g", "psSAR10g").replace("Pssar", "psSAR")
    ax.set_xlabel(f"{metric_display} ({unit_label})")
    ax.set_ylabel("Tissue")

    # Create title with phantom name
    base_title = f"top 20 tissues by {metric_display}"
    title_full = self._get_title_with_phantom(base_title, scenario_name)
    # Don't set title on plot - will be in caption file
    ax.grid(True, alpha=0.3, axis="x")

    # Set x-axis range - use capped value if outliers exist
    if has_outlier and outlier_cap_value is not None:
        ax.set_xlim(0, outlier_cap_value * 1.15)  # Extra space for label
    else:
        max_val = top20_clean[metric].max()
        ax.set_xlim(0, max_val * 1.05)

    # Add value labels on bars
    # For the highest bar (last one in sorted order), put label IN the bar, others to the right
    # Find the index position of the max value (it's the last bar since sorted ascending=True)
    max_bar_idx = len(top20_clean) - 1

    for i, (idx, row) in enumerate(top20_clean.iterrows()):
        actual_value = row[metric]
        display_value = display_values.loc[idx]
        is_outlier_bar = outlier_mask.loc[idx] if has_outlier else False

        if is_outlier_bar:
            # Outlier bar: show actual value with asterisk indicator
            # Position label left of break marks (which are at 0.95), use black for readability
            label_text = f"{actual_value:.3f}*"
            ax.text(display_value * 0.85, i, label_text, va="center", ha="right", fontsize=8, color="black", weight="bold")
        elif i == max_bar_idx:  # Highest bar (last position) - only if not outlier
            # Highest bar: label inside, right-aligned, black text
            ax.text(actual_value * 0.95, i, f"{actual_value:.3f}", va="center", ha="right", fontsize=8, color="black", weight="bold")
        else:
            # Other bars: label to the right
            ax.text(actual_value, i, f" {actual_value:.3f}", va="center", fontsize=8)

    plt.tight_layout()

    metric_name = metric.replace("_mw_kg", "").replace("_", "_")
    filename_base = f"ranking_top20_{metric_name}_{scenario_name or 'all'}_{frequency_mhz or 'all'}MHz"
    # Use the properly formatted metric_display and unit_label for caption
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    outlier_note = (
        " Note: values marked with * are outliers that exceed the display scale; the actual value is shown." if has_outlier else ""
    )
    caption = f"The horizontal bar chart ranks the top 20 tissues by {metric_display} ({unit_label}) for the {self._format_scenario_name(scenario_name) if scenario_name else 'all scenarios'} scenario{f' at {frequency_mhz} MHz' if frequency_mhz else ''} for {phantom_name_formatted}.{outlier_note}"
    filename = self._save_figure(fig, "ranking", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = top20_clean[["tissue_clean", metric]].copy()
    csv_data.columns = ["tissue", metric]
    csv_data = csv_data.sort_values(metric, ascending=True)
    self._save_csv_data(csv_data, "ranking", filename_base)
    logging.getLogger("progress").info(
        f"  - Generated ranking plot: {filename}",
        extra={"log_type": "success"},
    )

goliat.analysis.plots.spatial.SpatialPlotter

SpatialPlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Bases: BasePlotter

Generates spatial/3D plots for SAR analysis.

Source code in goliat/analysis/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

plot_peak_location_3d_interactive

plot_peak_location_3d_interactive(peak_data: DataFrame, scenario_name: str | None = None, axis_limits: dict | None = None)

Creates an interactive 3D plot of peak SAR locations as wireframe boxes.

Each box represents the spatial averaging cube (10g) centered at the peak location. Uses Plotly for interactive visualization (not affected by scienceplots).

Parameters:

Name Type Description Default
peak_data DataFrame

DataFrame with columns: ['PeakLocation', 'PeakCubeSideLength', 'PeakValue', 'placement', 'frequency_mhz', 'scenario']

required
scenario_name str | None

Optional scenario name for filtering and filename.

None
axis_limits dict | None

Optional dict with 'x', 'y', 'z' keys containing (min, max) tuples. If None, calculates from filtered data.

None
Source code in goliat/analysis/plots/spatial.py
def plot_peak_location_3d_interactive(
    self,
    peak_data: pd.DataFrame,
    scenario_name: str | None = None,
    axis_limits: dict | None = None,
):
    """Creates an interactive 3D plot of peak SAR locations as wireframe boxes.

    Each box represents the spatial averaging cube (10g) centered at the peak location.
    Uses Plotly for interactive visualization (not affected by scienceplots).

    Args:
        peak_data: DataFrame with columns: ['PeakLocation', 'PeakCubeSideLength',
                  'PeakValue', 'placement', 'frequency_mhz', 'scenario']
        scenario_name: Optional scenario name for filtering and filename.
        axis_limits: Optional dict with 'x', 'y', 'z' keys containing (min, max) tuples.
                    If None, calculates from filtered data.
    """
    try:
        import plotly.graph_objects as go
    except ImportError:
        logging.getLogger("progress").warning(
            "Plotly not available. Skipping 3D interactive plot. Install with: pip install plotly",
            extra={"log_type": "warning"},
        )
        return

    if peak_data.empty:
        logging.getLogger("progress").warning(
            "No peak location data available for 3D plot.",
            extra={"log_type": "warning"},
        )
        return

    # Filter by scenario if provided
    plot_data = peak_data.copy()
    if scenario_name:
        plot_data = plot_data[plot_data["scenario"] == scenario_name].copy()

    if plot_data.empty:
        return

    # Calculate axis limits if not provided
    if axis_limits is None:
        axis_limits = self._calculate_axis_limits(plot_data)

    fig = go.Figure()
    colorscale = "jet"

    # Normalize PeakValue for color mapping
    if "PeakValue" in plot_data.columns:
        peak_values = plot_data["PeakValue"].values
        vmin, vmax = peak_values.min(), peak_values.max()
    else:
        vmin, vmax = 0, 1
        peak_values = np.zeros(len(plot_data))

    # Get unique scenarios for color coding
    if "scenario" in plot_data.columns:
        unique_scenarios = sorted(plot_data["scenario"].unique())
        scenario_colors = plt.cm.tab10(np.linspace(0, 1, len(unique_scenarios)))
        scenario_color_map = {scenario: tuple(scenario_colors[i][:3]) for i, scenario in enumerate(unique_scenarios)}
    else:
        scenario_color_map = {}

    for idx, row in plot_data.iterrows():
        loc = row.get("PeakLocation")
        side = row.get("PeakCubeSideLength")
        if loc is None or side is None or (np.isscalar(loc) and pd.isna(loc)) or (np.isscalar(side) and pd.isna(side)):
            continue

        location = row["PeakLocation"]
        if isinstance(location, str):
            try:
                import ast

                location = ast.literal_eval(location)
            except Exception:
                continue

        if not isinstance(location, (list, tuple)) or len(location) != 3:
            continue

        x, y, z = location
        side_length = float(row.get("PeakCubeSideLength", 0.01))
        peak_val = float(row.get("PeakValue", 0))

        # Convert to millimeters
        x_mm, y_mm, z_mm = x * 1000, y * 1000, z * 1000
        side_length_mm = side_length * 1000

        # Create wireframe box vertices (in mm)
        half = side_length_mm / 2
        vertices = [
            [x_mm - half, y_mm - half, z_mm - half],
            [x_mm + half, y_mm - half, z_mm - half],
            [x_mm + half, y_mm + half, z_mm - half],
            [x_mm - half, y_mm + half, z_mm - half],
            [x_mm - half, y_mm - half, z_mm + half],
            [x_mm + half, y_mm - half, z_mm + half],
            [x_mm + half, y_mm + half, z_mm + half],
            [x_mm - half, y_mm + half, z_mm + half],
        ]

        # Define box edges
        edges = [
            [0, 1],
            [1, 2],
            [2, 3],
            [3, 0],  # bottom face
            [4, 5],
            [5, 6],
            [6, 7],
            [7, 4],  # top face
            [0, 4],
            [1, 5],
            [2, 6],
            [3, 7],  # vertical edges
        ]

        scenario = row.get("scenario", "unknown")
        placement = row.get("placement", "unknown")
        freq = row.get("frequency_mhz", "unknown")
        label = f"{scenario} | {placement} | {freq} MHz"

        # For aggregated plot: use scenario colors and show legend grouped by scenario
        # For individual scenario plot: use peak value colors, no legend
        if scenario_name is None and scenario in scenario_color_map:
            box_color = scenario_color_map[scenario]
            legend_name = scenario  # Group by scenario in aggregated plot
            show_legend = True
        else:
            normalized_val = (peak_val - vmin) / (vmax - vmin) if vmax > vmin else 0.5
            box_color = plt.cm.get_cmap(colorscale)(normalized_val)[:3]
            legend_name = label
            show_legend = False

        # Create a trace for this box (all edges together for legend)
        edge_x, edge_y, edge_z = [], [], []
        for edge in edges:
            v0, v1 = vertices[edge[0]], vertices[edge[1]]
            edge_x.extend([v0[0], v1[0], None])
            edge_y.extend([v0[1], v1[1], None])
            edge_z.extend([v0[2], v1[2], None])

        fig.add_trace(
            go.Scatter3d(
                x=edge_x,
                y=edge_y,
                z=edge_z,
                mode="lines",
                line=dict(color=f"rgb({int(box_color[0] * 255)}, {int(box_color[1] * 255)}, {int(box_color[2] * 255)})", width=3),
                name=legend_name,
                showlegend=show_legend,
                legendgroup=scenario if scenario_name is None else None,
                hovertemplate=f"{label}<br>Peak SAR: {peak_val:.2f} mW/kg<br>Location: ({x_mm:.2f}, {y_mm:.2f}, {z_mm:.2f}) mm<extra></extra>",
            )
        )

    # Add colorbar for peak values (only if not using scenario colors)
    if scenario_name is not None or not scenario_color_map:
        fig.add_trace(
            go.Scatter3d(
                x=[None],
                y=[None],
                z=[None],
                mode="markers",
                marker=dict(
                    colorscale=colorscale,
                    showscale=True,
                    cmin=vmin,
                    cmax=vmax,
                    colorbar=dict(title="Peak SAR (mW/kg)", len=0.5, y=0.5),
                ),
                showlegend=False,
            )
        )

    base_title = "3D peak SAR location visualization"
    title_with_phantom = self._get_title_with_phantom(base_title, scenario_name)
    # Title will be in caption file, not on plot
    fig.update_layout(
        title=title_with_phantom,
        scene=dict(
            xaxis_title="X (mm)",
            yaxis_title="Y (mm)",
            zaxis_title="Z (mm)",
            xaxis=dict(range=axis_limits["x"]),
            yaxis=dict(range=axis_limits["y"]),
            zaxis=dict(range=axis_limits["z"]),
            aspectmode="cube",
        ),
        width=1000,
        height=800,
    )

    subdir = self._get_subdir("spatial")
    filename = f"peak_location_3d_interactive_{scenario_name}.html" if scenario_name else "peak_location_3d_interactive_all.html"
    fig.write_html(os.path.join(subdir, filename))

    # Create caption file for HTML plot
    caption_filename = filename.replace(".html", ".txt")
    caption_path = os.path.join(subdir, caption_filename)
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The interactive 3D visualization shows peak SAR locations as wireframe boxes representing the spatial averaging cube (10g) centered at each peak location for the {self._format_scenario_name(scenario_name) if scenario_name else 'all scenarios'} scenario for {phantom_name_formatted}."
    with open(caption_path, "w", encoding="utf-8") as f:
        f.write(f"Title: {title_with_phantom}\n\n")
        f.write(f"Caption: {caption}\n")

    logging.getLogger("progress").info(
        f"  - Generated 3D interactive plot: {filename}",
        extra={"log_type": "success"},
    )

plot_peak_location_2d_projections

plot_peak_location_2d_projections(peak_data: DataFrame, scenario_name: str | None = None)

Creates 2D scatter plots showing peak locations projected onto XY, XZ, YZ planes.

Parameters:

Name Type Description Default
peak_data DataFrame

DataFrame with columns: ['PeakLocation', 'PeakValue', 'placement', 'frequency_mhz', 'scenario']

required
scenario_name str | None

Optional scenario name for filtering and filename.

None
Source code in goliat/analysis/plots/spatial.py
def plot_peak_location_2d_projections(
    self,
    peak_data: pd.DataFrame,
    scenario_name: str | None = None,
):
    """Creates 2D scatter plots showing peak locations projected onto XY, XZ, YZ planes.

    Args:
        peak_data: DataFrame with columns: ['PeakLocation', 'PeakValue', 'placement',
                  'frequency_mhz', 'scenario']
        scenario_name: Optional scenario name for filtering and filename.
    """
    if peak_data.empty:
        return

    if scenario_name:
        peak_data = peak_data[peak_data["scenario"] == scenario_name].copy()

    if peak_data.empty:
        return

    # Extract coordinates
    locations = []
    peak_values = []
    for idx, row in peak_data.iterrows():
        loc = row.get("PeakLocation")
        if loc is None or (np.isscalar(loc) and pd.isna(loc)):
            continue
        location = row["PeakLocation"]
        if isinstance(location, str):
            try:
                import ast

                location = ast.literal_eval(location)
            except Exception:
                continue
        if isinstance(location, (list, tuple)) and len(location) == 3:
            locations.append(location)
            peak_values.append(float(row.get("PeakValue", 0)))

    if not locations:
        return

    locations = np.array(locations)
    peak_values = np.array(peak_values)

    # Convert from meters to millimeters
    locations_mm = locations * 1000

    # Vertical arrangement: 3 rows, 1 column, variable height
    subplot_height = 2.5  # Height per subplot
    total_height = 3 * subplot_height
    fig, axes = plt.subplots(3, 1, figsize=(3.5, total_height))  # IEEE single-column width, vertical arrangement

    # Auto-detect unit family based on max peak value
    max_val_raw = peak_values.max()
    unit_multiplier = 1.0
    unit_label = r"mW kg$^{-1}$"

    if max_val_raw < 1e-6:
        unit_multiplier = 1e9
        unit_label = r"nW kg$^{-1}$"
    elif max_val_raw < 1e-3:
        unit_multiplier = 1e6
        unit_label = r"$\mu$W kg$^{{-1}}$"
    elif max_val_raw < 1.0:
        unit_multiplier = 1e3
        unit_label = r"mW kg$^{-1}$"

    peak_values_scaled = peak_values * unit_multiplier
    vmin = 0.0 * unit_multiplier  # Start colormap at 0
    vmax = peak_values_scaled.max()

    # Transverse-XY plane (subplot title - keep it)
    scatter1 = axes[0].scatter(
        locations_mm[:, 0], locations_mm[:, 1], c=peak_values_scaled, cmap="jet", alpha=0.7, s=30, vmin=vmin, vmax=vmax
    )
    axes[0].set_xlabel(self._format_axis_label("X", "mm"))
    axes[0].set_ylabel(self._format_axis_label("Y", "mm"))
    axes[0].set_title("Transverse-XY plane")
    axes[0].grid(True, alpha=0.3)
    cbar1 = plt.colorbar(scatter1, ax=axes[0])
    cbar1.set_label(self._format_axis_label("Peak SAR", unit_label))

    # Sagittal-XZ plane (subplot title - keep it)
    scatter2 = axes[1].scatter(
        locations_mm[:, 0], locations_mm[:, 2], c=peak_values_scaled, cmap="jet", alpha=0.7, s=30, vmin=vmin, vmax=vmax
    )
    axes[1].set_xlabel(self._format_axis_label("X", "mm"))
    axes[1].set_ylabel(self._format_axis_label("Z", "mm"))
    axes[1].set_title("Sagittal-XZ plane")
    axes[1].grid(True, alpha=0.3)
    cbar2 = plt.colorbar(scatter2, ax=axes[1])
    cbar2.set_label(self._format_axis_label("Peak SAR", unit_label))

    # Coronal-YZ plane (subplot title - keep it)
    scatter3 = axes[2].scatter(
        locations_mm[:, 1], locations_mm[:, 2], c=peak_values_scaled, cmap="jet", alpha=0.7, s=30, vmin=vmin, vmax=vmax
    )
    axes[2].set_xlabel(self._format_axis_label("Y", "mm"))
    axes[2].set_ylabel(self._format_axis_label("Z", "mm"))
    axes[2].set_title("Coronal-YZ plane")
    axes[2].grid(True, alpha=0.3)
    cbar3 = plt.colorbar(scatter3, ax=axes[2])
    cbar3.set_label(self._format_axis_label("Peak SAR", unit_label))

    base_title = "peak SAR location 2D projections"
    title_full = self._get_title_with_phantom(base_title, scenario_name)
    # Don't set suptitle - will be in caption file

    # Add sample size annotation - top-right, simple box, black border
    n_samples = len(locations_mm)
    fig.text(
        0.95,
        0.95,
        f"n = {n_samples}",
        fontsize=8,
        transform=fig.transFigure,
        verticalalignment="top",
        horizontalalignment="right",
        bbox=dict(boxstyle="square,pad=0.4", facecolor="white", edgecolor="black", linewidth=0.5, alpha=1.0),
    )
    plt.tight_layout()

    filename_base = f"peak_location_2d_{scenario_name}" if scenario_name else "peak_location_2d"
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The 2D projections show peak SAR locations onto Transverse-XY, Sagittal-XZ, and Coronal-YZ planes for the {self._format_scenario_name(scenario_name) if scenario_name else 'all scenarios'} scenario for {phantom_name_formatted}. Each point represents a peak location, colored by peak SAR value."
    filename = self._save_figure(fig, "spatial", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = pd.DataFrame(
        {"x_mm": locations_mm[:, 0], "y_mm": locations_mm[:, 1], "z_mm": locations_mm[:, 2], "peak_sar_mw_kg": peak_values}
    )
    self._save_csv_data(csv_data, "spatial", filename_base)
    logging.getLogger("progress").info(
        f"  - Generated 2D projection plots: {filename}",
        extra={"log_type": "success"},
    )

goliat.analysis.plots.tissue_analysis.TissueAnalysisPlotter

TissueAnalysisPlotter(plots_dir: str, phantom_name: str | None = None, plot_format: str = 'pdf')

Bases: BasePlotter

Generates tissue analysis plots for SAR analysis.

Source code in goliat/analysis/plots/base.py
def __init__(self, plots_dir: str, phantom_name: str | None = None, plot_format: str = "pdf"):
    """Initialize base plotter.

    Args:
        plots_dir: Directory where all plots will be saved.
        phantom_name: Optional phantom model name for titles.
        plot_format: Output format for plots ('pdf' or 'png'), default 'pdf'.
    """
    self.plots_dir = plots_dir
    self.phantom_name = phantom_name
    self.plot_format = plot_format

Methods:

plot_max_local_vs_pssar10g_scatter

plot_max_local_vs_pssar10g_scatter(organ_results_df: DataFrame, scenario_name: str | None = None, frequency_mhz: int | None = None)

Creates scatter plot showing relationship between Max Local SAR and psSAR10g.

Parameters:

Name Type Description Default
organ_results_df DataFrame

DataFrame with max_local_sar_mw_kg and psSAR10g columns.

required
scenario_name str | None

Optional scenario name for filtering.

None
frequency_mhz int | None

Optional frequency for filtering.

None
Source code in goliat/analysis/plots/tissue_analysis.py
def plot_max_local_vs_pssar10g_scatter(
    self,
    organ_results_df: pd.DataFrame,
    scenario_name: str | None = None,
    frequency_mhz: int | None = None,
):
    """Creates scatter plot showing relationship between Max Local SAR and psSAR10g.

    Args:
        organ_results_df: DataFrame with max_local_sar_mw_kg and psSAR10g columns.
        scenario_name: Optional scenario name for filtering.
        frequency_mhz: Optional frequency for filtering.
    """
    # Check for required columns, try alternative names
    if "max_local_sar_mw_kg" not in organ_results_df.columns:
        if "Max. local SAR" in organ_results_df.columns:
            organ_results_df = organ_results_df.rename(columns={"Max. local SAR": "max_local_sar_mw_kg"})

    if "psSAR10g" not in organ_results_df.columns:
        if "peak_sar_10g_mw_kg" in organ_results_df.columns:
            organ_results_df["psSAR10g"] = organ_results_df["peak_sar_10g_mw_kg"]
        elif "Peak Spatial-Average SAR[IEEE/IEC62704-1] (10g)" in organ_results_df.columns:
            organ_results_df["psSAR10g"] = organ_results_df["Peak Spatial-Average SAR[IEEE/IEC62704-1] (10g)"]

    required_cols = ["max_local_sar_mw_kg", "psSAR10g"]
    if not all(col in organ_results_df.columns for col in required_cols):
        logging.getLogger("progress").warning(
            "Missing columns for Max Local SAR vs psSAR10g scatter plot.",
            extra={"log_type": "warning"},
        )
        return

    plot_df = organ_results_df.copy()

    if frequency_mhz is not None:
        plot_df = plot_df[plot_df["frequency_mhz"] == frequency_mhz].copy()

    plot_df = plot_df.dropna(subset=required_cols)
    plot_df = plot_df[(plot_df["max_local_sar_mw_kg"] > 0) & (plot_df["psSAR10g"] > 0)]

    if plot_df.empty:
        return

    # Filter out extreme outliers in Max Local SAR (using iterative ratio method)
    # This removes points where the max value is > 2x the average of the next 30 points
    if len(plot_df) >= 6:
        iteration = 0
        original_count = len(plot_df)

        while len(plot_df) >= 6:
            iteration += 1
            # Sort by Max Local SAR descending
            plot_df = plot_df.sort_values("max_local_sar_mw_kg", ascending=False)

            # Get the top value and the next 30
            top_row = plot_df.iloc[0]
            top_val = top_row["max_local_sar_mw_kg"]

            next_n = plot_df.iloc[1:31]
            avg_next_n = next_n["max_local_sar_mw_kg"].mean()

            if avg_next_n <= 0:
                break

            ratio = top_val / avg_next_n

            if ratio > 2.0:
                # Found an outlier - remove the top row
                plot_df = plot_df.iloc[1:].copy()
            else:
                # Ratio is acceptable, stop checking
                break

        new_count = len(plot_df)
        if new_count < original_count:
            logging.getLogger("progress").info(
                f"  - Filtered {original_count - new_count} extreme outlier(s) using iterative ratio method (>2.0x avg of next 30).",
                extra={"log_type": "info"},
            )

    if plot_df.empty:
        return

    # Check for outliers and dense clusters
    max_x = plot_df["max_local_sar_mw_kg"].max()
    max_y = plot_df["psSAR10g"].max()

    # Identify dense region (95th percentile)
    x_p95 = plot_df["max_local_sar_mw_kg"].quantile(0.95)
    y_p95 = plot_df["psSAR10g"].quantile(0.95)

    # Set minimum axis values to avoid overplotting at origin
    x_min_val = plot_df["max_local_sar_mw_kg"].quantile(0.01)

    # Create main plot with inset for dense region
    fig = plt.figure(figsize=(3.5, 3.0))  # IEEE single-column width
    ax = fig.add_subplot(111)

    # Color by frequency if available
    if "frequency_mhz" in plot_df.columns and len(plot_df["frequency_mhz"].unique()) > 1:
        scatter_plot = ax.scatter(
            plot_df["max_local_sar_mw_kg"],
            plot_df["psSAR10g"],
            c=plot_df["frequency_mhz"],
            cmap="jet",
            alpha=0.6,
            s=30,
        )
        # Create colorbar with proper positioning to avoid extra subplot
        cbar = plt.colorbar(scatter_plot, ax=ax, pad=0.02)
        cbar.set_label("Frequency (MHz)")
    else:
        ax.scatter(plot_df["max_local_sar_mw_kg"], plot_df["psSAR10g"], alpha=0.6, s=30)

    # Add diagonal reference line (y=x) - limit to reasonable range
    max_val = max(x_p95, y_p95)
    ax.plot([x_min_val, max_val], [x_min_val, max_val], "r--", linewidth=2, label="y=x (No Spatial Averaging)")

    # Set axis limits: start at 0 for SAR values, go to max + 5%
    ax.set_xlim(0, max_x * 1.05)
    ax.set_ylim(0, max_y * 1.05)

    ax.set_xlabel(r"Max Local SAR (mW kg$^{-1}$)")
    ax.set_ylabel(r"psSAR10g (mW kg$^{-1}$)")

    # Create title with phantom name
    base_title = "max local SAR vs psSAR10g"
    title_full = self._get_title_with_phantom(base_title, scenario_name)
    # Don't set title on plot - will be in caption file
    ax.legend()
    ax.grid(True, alpha=0.3)

    # Add inset for dense region if there's significant clustering
    if x_p95 < max_x * 0.5 or y_p95 < max_y * 0.5:
        ax_inset = inset_axes(ax, width="40%", height="40%", loc="upper right", borderpad=2)

        # Filter data for inset (include a bit more than p95)
        inset_limit_x = x_p95 * 1.1
        inset_limit_y = y_p95 * 1.1

        inset_df = plot_df[(plot_df["max_local_sar_mw_kg"] <= inset_limit_x) & (plot_df["psSAR10g"] <= inset_limit_y)]

        if not inset_df.empty:
            if "frequency_mhz" in inset_df.columns and len(inset_df["frequency_mhz"].unique()) > 1:
                ax_inset.scatter(
                    inset_df["max_local_sar_mw_kg"],
                    inset_df["psSAR10g"],
                    c=inset_df["frequency_mhz"],
                    cmap="jet",
                    alpha=0.6,
                    s=20,
                )
            else:
                ax_inset.scatter(inset_df["max_local_sar_mw_kg"], inset_df["psSAR10g"], alpha=0.6, s=20)

        # Reference line in inset
        min_val = 0
        inset_max_ref = min(inset_limit_x, inset_limit_y)
        ax_inset.plot([min_val, inset_max_ref], [min_val, inset_max_ref], "r--", linewidth=1, alpha=0.5)

        # Set limits
        ax_inset.set_xlim(0, inset_limit_x)
        ax_inset.set_ylim(0, inset_limit_y)

        # Ensure 0 is shown as a tick if possible, but rely mainly on limits
        # Manual checking of tick labels can be fragile with tight layouts

        ax_inset.set_xlabel("Max Local SAR", fontsize=8)
        ax_inset.set_ylabel("psSAR10g", fontsize=8)
        ax_inset.tick_params(labelsize=7)
        ax_inset.grid(True, alpha=0.3)
        ax_inset.set_title("Zoomed View\n(95th percentile)", fontsize=8)

    plt.tight_layout()

    filename_base = f"scatter_MaxLocal_vs_psSAR10g_{scenario_name or 'all'}_{frequency_mhz or 'all'}MHz"
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The scatter plot compares Max Local SAR and psSAR10g values for tissues in the {self._format_scenario_name(scenario_name) if scenario_name else 'all scenarios'} scenario{f' at {frequency_mhz} MHz' if frequency_mhz else ''} for {phantom_name_formatted}. The red dashed line represents y=x (no spatial averaging). Points are colored by frequency when multiple frequencies are present."
    filename = self._save_figure(fig, "tissue_analysis", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data - use actual columns that exist
    csv_cols = ["max_local_sar_mw_kg", "psSAR10g"]
    if "frequency_mhz" in plot_df.columns:
        csv_cols.append("frequency_mhz")
    csv_data = plot_df[csv_cols].copy()
    self._save_csv_data(csv_data, "tissue_analysis", filename_base)
    logging.getLogger("progress").info(
        f"  - Generated scatter plot: {filename}",
        extra={"log_type": "success"},
    )

plot_tissue_frequency_response

plot_tissue_frequency_response(organ_results_df: DataFrame, tissue_name: str, scenario_name: str | None = None)

Creates line plot showing how a specific tissue responds across frequencies.

Parameters:

Name Type Description Default
organ_results_df DataFrame

DataFrame with tissue-level data.

required
tissue_name str

Name of the tissue to plot.

required
scenario_name str | None

Optional scenario name for filtering.

None
Source code in goliat/analysis/plots/tissue_analysis.py
def plot_tissue_frequency_response(
    self,
    organ_results_df: pd.DataFrame,
    tissue_name: str,
    scenario_name: str | None = None,
):
    """Creates line plot showing how a specific tissue responds across frequencies.

    Args:
        organ_results_df: DataFrame with tissue-level data.
        tissue_name: Name of the tissue to plot.
        scenario_name: Optional scenario name for filtering.
    """
    # Skip if trying to plot 'All Regions' - it's not a real tissue
    if tissue_name == "All Regions":
        return

    plot_df = organ_results_df[organ_results_df["tissue"] == tissue_name].copy()

    if plot_df.empty:
        return

    if scenario_name:
        plot_df = plot_df[plot_df["scenario"] == scenario_name].copy()

    if plot_df.empty:
        return

    # Aggregate by frequency
    sar_cols = ["min_local_sar_mw_kg", "mass_avg_sar_mw_kg", "max_local_sar_mw_kg"]
    available_cols = [col for col in sar_cols if col in plot_df.columns]

    if not available_cols:
        # Try alternative column names
        if "Min. local SAR" in plot_df.columns:
            plot_df["min_local_sar_mw_kg"] = plot_df["Min. local SAR"]
            available_cols.append("min_local_sar_mw_kg")
        if "Mass-Averaged SAR" in plot_df.columns:
            plot_df["mass_avg_sar_mw_kg"] = plot_df["Mass-Averaged SAR"]
            available_cols.append("mass_avg_sar_mw_kg")
        if "Max. local SAR" in plot_df.columns:
            plot_df["max_local_sar_mw_kg"] = plot_df["Max. local SAR"]
            available_cols.append("max_local_sar_mw_kg")

    if not available_cols:
        return

    freq_summary = plot_df.groupby("frequency_mhz")[available_cols].mean().reset_index()

    fig, ax = plt.subplots(figsize=(3.5, 2.5))  # IEEE single-column width

    colors = self._get_academic_colors(len(available_cols))
    linestyles = self._get_academic_linestyles(len(available_cols))
    markers = self._get_academic_markers(len(available_cols))

    for idx, col in enumerate(available_cols):
        # Format label properly: remove "_mw_kg", preserve SAR acronym
        label_base = col.replace("_mw_kg", "").replace("_", " ")
        # Capitalize properly, preserving SAR acronym
        label_words = label_base.split()
        label_formatted = []
        for word in label_words:
            if word.upper() == "SAR":
                label_formatted.append("SAR")
            else:
                label_formatted.append(word.capitalize())
        label = " ".join(label_formatted)
        ax.plot(
            freq_summary["frequency_mhz"],
            freq_summary[col],
            marker=markers[idx],
            linestyle=linestyles[idx],
            color=colors[idx],
            label=label,
            linewidth=2,
            markersize=4,
        )

    ax.set_xlabel(self._format_axis_label("Frequency", "MHz"))
    ax.set_ylabel(self._format_axis_label("SAR", r"mW kg$^{-1}$"))
    # Rotate x-axis labels for real number line frequencies
    # Rotate x-axis labels only for actual simulated frequencies
    # Rotate frequency labels (always rotate when x-axis is Frequency)
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
    self._adjust_slanted_tick_labels(ax)

    # Clean tissue name and create title with phantom name
    tissue_clean = self._clean_tissue_name(tissue_name)
    formatted_scenario = self._format_scenario_name(scenario_name) if scenario_name else None
    if formatted_scenario:
        base_title = f"frequency response for {tissue_clean} in {formatted_scenario} scenario"
    else:
        base_title = f"frequency response for {tissue_clean}"
    title_full = self._get_title_with_phantom(base_title)
    # Don't set title on plot - will be in caption file
    ax.legend()
    ax.grid(True, alpha=0.3)
    # Set y-axis to start at 0 and go to max + 5%
    y_max = ax.get_ylim()[1]
    ax.set_ylim(0, y_max * 1.05)

    plt.tight_layout()

    safe_tissue_name = tissue_name.replace("/", "_").replace(" ", "_")
    filename_base = f"tissue_frequency_response_{safe_tissue_name}_{scenario_name or 'all'}"
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The line plot shows the frequency response of SAR metrics (Min Local SAR, Mass-Averaged SAR, Max Local SAR) for {tissue_clean} in the {self._format_scenario_name(scenario_name) if scenario_name else 'all scenarios'} scenario for {phantom_name_formatted}."
    filename = self._save_figure(fig, "tissue_analysis", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = freq_summary.copy()
    csv_data.index.name = "frequency_mhz"
    self._save_csv_data(csv_data, "tissue_analysis", filename_base)
    logging.getLogger("progress").info(
        f"  - Generated tissue frequency response: {filename}",
        extra={"log_type": "success"},
    )

plot_tissue_mass_volume_distribution

plot_tissue_mass_volume_distribution(organ_results_df: DataFrame, scenario_name: str | None = None)

Creates histograms and scatter plot showing tissue mass and volume distributions.

Parameters:

Name Type Description Default
organ_results_df DataFrame

DataFrame with 'Total Mass' and 'Total Volume' columns.

required
scenario_name str | None

Optional scenario name for filtering.

None
Source code in goliat/analysis/plots/tissue_analysis.py
def plot_tissue_mass_volume_distribution(
    self,
    organ_results_df: pd.DataFrame,
    scenario_name: str | None = None,
):
    """Creates histograms and scatter plot showing tissue mass and volume distributions.

    Args:
        organ_results_df: DataFrame with 'Total Mass' and 'Total Volume' columns.
        scenario_name: Optional scenario name for filtering.
    """
    required_cols = ["Total Mass", "Total Volume"]
    if not all(col in organ_results_df.columns for col in required_cols):
        logging.getLogger("progress").warning(
            "Missing columns for mass/volume distribution plot.",
            extra={"log_type": "warning"},
        )
        return

    plot_df = organ_results_df.copy()
    # Filter out 'All Regions' - it's a whole-body aggregate, not a real tissue
    plot_df = self._filter_all_regions(plot_df, tissue_column="tissue")
    plot_df = plot_df.dropna(subset=required_cols)
    plot_df = plot_df[(plot_df["Total Mass"] > 0) & (plot_df["Total Volume"] > 0)]

    if plot_df.empty:
        return

    # Aggregate by tissue if multiple placements
    if "placement" in plot_df.columns:
        plot_df = (
            plot_df.groupby("tissue")
            .agg(
                {
                    "Total Mass": "mean",
                    "Total Volume": "mean",
                }
            )
            .reset_index()
        )

    # Vertical arrangement: 3 rows, 1 column, variable height
    subplot_height = 2.5  # Height per subplot
    total_height = 3 * subplot_height
    fig, axes = plt.subplots(3, 1, figsize=(3.5, total_height))  # IEEE single-column width, vertical arrangement

    # Histogram of Total Mass - use log-spaced bins for constant bin size on log scale
    mass_min = plot_df["Total Mass"].min()
    mass_max = plot_df["Total Mass"].max()
    # Create logarithmically spaced bins
    mass_bins = np.logspace(np.log10(mass_min), np.log10(mass_max), 31)  # 31 edges = 30 bins
    axes[0].hist(plot_df["Total Mass"], bins=mass_bins, edgecolor="black", alpha=0.7)
    axes[0].set_xscale("log")
    axes[0].set_xlabel("Total Mass (kg)")
    axes[0].set_ylabel("Frequency")
    axes[0].set_title("Distribution of Total Mass")  # Subplot title - keep it
    axes[0].grid(True, alpha=0.3)

    # Histogram of Total Volume - use log-spaced bins for constant bin size on log scale
    vol_min = plot_df["Total Volume"].min()
    vol_max = plot_df["Total Volume"].max()
    # Create logarithmically spaced bins
    vol_bins = np.logspace(np.log10(vol_min), np.log10(vol_max), 31)  # 31 edges = 30 bins
    axes[1].hist(plot_df["Total Volume"], bins=vol_bins, edgecolor="black", alpha=0.7)
    axes[1].set_xscale("log")
    axes[1].set_xlabel("Total Volume (m$^3$)")
    axes[1].set_ylabel("Frequency")
    axes[1].set_title("Distribution of Total Volume")  # Subplot title - keep it
    axes[1].grid(True, alpha=0.3)

    # Scatter: Volume vs Mass
    axes[2].scatter(plot_df["Total Volume"], plot_df["Total Mass"], alpha=0.6, s=30, edgecolors="black", linewidth=0.5)
    axes[2].set_xscale("log")
    axes[2].set_yscale("log")
    axes[2].set_xlabel("Total Volume (m$^3$)")
    axes[2].set_ylabel("Total Mass (kg)")
    axes[2].set_title("Volume vs Mass (Density Analysis)")  # Subplot title - keep it

    # Add reference line for water density (1000 kg m$^{-3}$)
    vol_range = [plot_df["Total Volume"].min(), plot_df["Total Volume"].max()]
    mass_water = [v * 1000 for v in vol_range]
    axes[2].plot(vol_range, mass_water, "r--", linewidth=2, label="Water Density (1000 kg m$^{-3}$)")
    axes[2].legend()
    axes[2].grid(True, alpha=0.3)

    base_title = "tissue mass/volume distribution"
    title_full = self._get_title_with_phantom(base_title, scenario_name)
    # Don't set suptitle - will be in caption file
    plt.tight_layout()

    filename_base = f"distribution_mass_volume_{scenario_name or 'all'}"
    phantom_name_formatted = self.phantom_name.capitalize() if self.phantom_name else "the phantom"
    caption = f"The distribution analysis shows histograms of tissue total mass and total volume (log scale), and a scatter plot of volume vs mass with water density reference line for the {self._format_scenario_name(scenario_name) if scenario_name else 'all scenarios'} scenario for {phantom_name_formatted}."
    filename = self._save_figure(fig, "tissue_analysis", filename_base, title=title_full, caption=caption, dpi=300)

    # Save CSV data
    csv_data = plot_df[["tissue", "Total Mass", "Total Volume"]].copy()
    self._save_csv_data(csv_data, "tissue_analysis", filename_base)
    logging.getLogger("progress").info(
        f"  - Generated mass/volume distribution: {filename}",
        extra={"log_type": "success"},
    )

GUI Components

Graphical user interface for monitoring simulation progress.

Analysis Gui

goliat.gui.analysis_gui.SignalingLogHandler

SignalingLogHandler()

Bases: Handler, QObject

Log handler that emits Qt signals for log records.

Source code in goliat/gui/analysis_gui.py
def __init__(self):
    """Dual init for Handler and QObject."""
    logging.Handler.__init__(self)
    QObject.__init__(self)

Methods:

emit

emit(record)

Format record and emit as Qt signal.

Source code in goliat/gui/analysis_gui.py
def emit(self, record):
    """Format record and emit as Qt signal."""
    try:
        msg = self.format(record)
        # Extract log_type for coloring (defaults to 'default')
        log_type = getattr(record, "log_type", "default")
        self.log_signal.emit(msg, record.levelname, log_type)
    except Exception:
        self.handleError(record)

Progress Gui

goliat.gui.progress_gui.ProgressGUI

ProgressGUI(queue: Queue, stop_event: Event, process: Process, init_window_title: str = '', use_web: bool = True, auto_close: bool = False)

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 - 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.

''
use_web bool

Whether to enable web bridge for remote monitoring.

True
auto_close bool

Whether to automatically close GUI on successful completion.

False
Source code in goliat/gui/progress_gui.py
def __init__(
    self,
    queue: Queue,
    stop_event: Event,
    process: Process,
    init_window_title: str = "",
    use_web: bool = True,
    auto_close: bool = False,
) -> None:
    """Sets up the GUI window and all components.

    Initializes data manager, status manager, UI builder, timers, and
    queue handler. Sets up Qt timers for periodic updates (queue polling,
    clock updates, graph refreshes).

    Args:
        queue: Queue for receiving messages from worker process.
        stop_event: Event to signal termination to worker process.
        process: Worker process running the study.
        init_window_title: Initial window title.
        use_web: Whether to enable web bridge for remote monitoring.
        auto_close: Whether to automatically close GUI on successful completion.
    """
    super().__init__()
    self.queue: Queue = queue
    self.stop_event: Event = stop_event
    self.process: Process = process
    self.start_time: float = time.monotonic()
    self.progress_logger: logging.Logger = logging.getLogger("progress")
    self.verbose_logger: logging.Logger = logging.getLogger("verbose")
    self.init_window_title: str = init_window_title
    self.auto_close: bool = auto_close
    self.DEBUG: bool = False
    self.study_is_finished: bool = False
    self.study_had_errors: bool = False
    self.child_exit_code: int = 0  # Exit code from child process (42 = memory error)

    self.total_simulations: int = 0
    self.current_simulation_count: int = 0

    # Initialize components
    self._initialize_components()

    # Auto-detect machine ID
    self.machine_id = MachineIdDetector.detect(self.verbose_logger)
    self.server_url = "https://monitor.goliat.waves-ugent.be"

    # Build UI
    UIBuilder.build(self, self.status_manager)

    # Initialize managers
    self.web_bridge_manager = WebBridgeManager(self, self.server_url, self.machine_id, use_web=use_web)
    self.progress_manager = ProgressManager(self)
    self.clock_manager = ClockManager(self)
    self.utilization_manager = UtilizationManager(self)
    self.graph_manager = GraphManager(self)

    # Initialize web GUI bridge after UI is built (so we can set callback)
    self.web_bridge_manager.initialize()

    # Initialize animation and other components
    self._initialize_animation()
    self._initialize_managers()
    self._setup_timers()
    self._initialize_system_monitoring()

Methods:

update_overall_progress

update_overall_progress(current_step: float, total_steps: int) -> None

Updates overall progress bar across all simulations.

Source code in goliat/gui/progress_gui.py
def update_overall_progress(self, current_step: float, total_steps: int) -> None:
    """Updates overall progress bar across all simulations."""
    self.progress_manager.update_overall(current_step, total_steps)

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
def update_stage_progress(self, stage_name: str, current_step: int, total_steps: int, sub_stage: str = "") -> None:
    """Updates stage-specific progress bar and label."""
    self.progress_manager.update_stage(stage_name, current_step, total_steps, sub_stage)

start_stage_animation

start_stage_animation(estimated_duration: float, end_step: int) -> None

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
def start_stage_animation(self, estimated_duration: float, end_step: int) -> None:
    """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.

    Args:
        estimated_duration: Estimated task duration in seconds (from profiler).
        end_step: Target step value (unused, always animates to 100%).
    """
    if self.DEBUG:
        self.update_status(f"DEBUG: start_stage_animation received: duration={estimated_duration:.2f}s, end_step={end_step}")
    self.progress_animation.start(estimated_duration, end_step)

end_stage_animation

end_stage_animation() -> None

Stops stage progress bar animation.

Source code in goliat/gui/progress_gui.py
def end_stage_animation(self) -> None:
    """Stops stage progress bar animation."""
    self.progress_animation.stop()

update_animation

update_animation() -> None

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
def update_animation(self) -> None:
    """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.
    """
    self.progress_animation.update()

    # Sync overall progress based on stage animation
    if self.profiler and self.profiler.current_phase:
        current_value = self.stage_progress_bar.value()
        percent = (current_value / 1000) * 100
        progress = self.profiler.get_weighted_progress(self.profiler.current_phase, percent / 100.0)
        self.progress_manager.update_overall(progress, 100)

update_simulation_details

update_simulation_details(sim_count: int, total_sims: int, details: str) -> None

Updates simulation counter and details labels.

Source code in goliat/gui/progress_gui.py
def update_simulation_details(self, sim_count: int, total_sims: int, details: str) -> None:
    """Updates simulation counter and details labels."""
    self.progress_manager.update_simulation_details(sim_count, total_sims, details)

update_status

update_status(message: str, log_type: str = 'default') -> None

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
def update_status(self, message: str, log_type: str = "default") -> None:
    """Appends message to status log with color formatting.

    Args:
        message: Message text.
        log_type: Log type for color coding.
    """
    self.status_manager.record_log(log_type)
    # Update error counter with current web status
    web_connected = False
    if (
        hasattr(self, "web_bridge_manager")
        and self.web_bridge_manager.web_bridge
        and hasattr(self.web_bridge_manager.web_bridge, "is_connected")
    ):
        web_connected = self.web_bridge_manager.web_bridge.is_connected
    self.error_counter_label.setText(self.status_manager.get_error_summary(web_connected=web_connected))
    formatted_message = self.status_manager.format_message(message, log_type)
    self.status_text.append(formatted_message)

update_utilization

update_utilization() -> None

Updates CPU, RAM, and GPU utilization displays.

Source code in goliat/gui/progress_gui.py
def update_utilization(self) -> None:
    """Updates CPU, RAM, and GPU utilization displays."""
    self.utilization_manager.update()

update_utilization_plot

update_utilization_plot() -> None

Updates the system utilization plot with current values.

Source code in goliat/gui/progress_gui.py
def update_utilization_plot(self) -> None:
    """Updates the system utilization plot with current values."""
    self.utilization_manager.update_plot()

update_clock

update_clock() -> None

Updates elapsed time, ETA labels, and window title.

Source code in goliat/gui/progress_gui.py
def update_clock(self) -> None:
    """Updates elapsed time, ETA labels, and window title."""
    self.clock_manager.update()

update_graphs

update_graphs() -> None

Updates time remaining and overall progress graphs.

Source code in goliat/gui/progress_gui.py
def update_graphs(self) -> None:
    """Updates time remaining and overall progress graphs."""
    self.graph_manager.update()

hide_to_tray

hide_to_tray() -> None

Hides main window and shows system tray icon.

Source code in goliat/gui/progress_gui.py
def hide_to_tray(self) -> None:
    """Hides main window and shows system tray icon."""
    self.hide()
    self.tray_manager.show()

show_from_tray

show_from_tray() -> None

Shows main window from system tray.

Source code in goliat/gui/progress_gui.py
def show_from_tray(self) -> None:
    """Shows main window from system tray."""
    self.show()
    self.tray_manager.hide()

stop_study

stop_study() -> None

Sends stop signal to worker process.

Source code in goliat/gui/progress_gui.py
def stop_study(self) -> None:
    """Sends stop signal to worker process."""
    message = "--- Sending stop signal to study process ---"
    self.progress_logger.info(message, extra={"log_type": "warning"})
    self.verbose_logger.info(message, extra={"log_type": "warning"})
    self.update_status(message, log_type="warning")
    self.stop_button.setEnabled(False)
    self.tray_button.setEnabled(False)
    self.stop_event.set()

study_finished

study_finished(error: bool = False, memory_error: bool = False) -> None

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).

For memory errors (exit code 42), the GUI auto-closes even with errors so the batch worker can retry the assignment.

Parameters:

Name Type Description Default
error bool

Whether study finished with errors (affects UI styling).

False
memory_error bool

Whether this was a memory error (exit code 42). Memory errors auto-close to allow batch retry.

False
Source code in goliat/gui/progress_gui.py
def study_finished(self, error: bool = False, memory_error: bool = False) -> None:
    """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).

    For memory errors (exit code 42), the GUI auto-closes even with errors
    so the batch worker can retry the assignment.

    Args:
        error: Whether study finished with errors (affects UI styling).
        memory_error: Whether this was a memory error (exit code 42).
                     Memory errors auto-close to allow batch retry.
    """
    self.study_is_finished = True
    self.study_had_errors = error
    self.clock_timer.stop()
    self.queue_timer.stop()
    self.graph_timer.stop()
    self.utilization_timer.stop()
    self.utilization_plot_timer.stop()
    self.progress_sync_timer.stop()
    self.progress_animation.stop()
    if not error:
        self.update_status("--- Study Finished ---", log_type="success")
        self.overall_progress_bar.setValue(self.overall_progress_bar.maximum())
        self.stage_label.setText("Finished")
    elif memory_error:
        self.update_status("--- Study Stopped: Memory Error (will retry) ---", log_type="fatal")
        self.stage_label.setText("Memory Error")
    else:
        self.update_status("--- Study Finished with Errors ---", log_type="fatal")
        self.stage_label.setText("Error")

    self.stop_button.setEnabled(False)
    self.tray_button.setEnabled(False)

    # Send final status update to web before stopping bridge
    self.web_bridge_manager.send_finished(error)

    self.update_clock()  # Final title update

    # Instead of auto-closing, show a message that user can close the window
    if not error:
        self.progress_logger.info("All done! You may close this window now.", extra={"log_type": "success"})
        self.update_status("\n✓ All done! You may close this window now.", log_type="success")
        # Auto-close if enabled (used by batch worker mode)
        if self.auto_close:
            self.progress_logger.info("Auto-closing GUI in 2 seconds...", extra={"log_type": "info"})
            from PySide6.QtCore import QTimer as _QTimer

            _QTimer.singleShot(2000, self.close)
    elif memory_error:
        # Memory errors should ALWAYS auto-close so the process can be restarted to free GPU memory.
        # This is required for both batch worker retry logic and persistent mode retry logic.
        # Unlike normal errors, memory errors cannot be resolved without a full process restart.
        self.progress_logger.info("Memory error detected. Auto-closing for retry...", extra={"log_type": "warning"})
        self.update_status("\n⚠ Memory error detected. Auto-closing for retry...", log_type="warning")
        from PySide6.QtCore import QTimer as _QTimer

        _QTimer.singleShot(2000, self.close)
    else:
        self.progress_logger.info("Finished with errors. You may close this window now.", extra={"log_type": "warning"})
        self.update_status("\n✓ Finished with errors. You may close this window now.", log_type="warning")

closeEvent

closeEvent(event: Any) -> None

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
def closeEvent(self, event: Any) -> None:
    """Handles window close event, ensuring worker process termination.

    Args:
        event: Close event.
    """
    if self.tray_manager.is_visible():
        self.tray_manager.hide()

    if self.process.is_alive():
        self.progress_logger.info("Terminating study process...", extra={"log_type": "warning"})
        self.process.terminate()
        self.process.join(timeout=5)

    # Stop web bridge if enabled
    self.web_bridge_manager.stop()

    shutdown_loggers()
    event.accept()

Queue Gui

goliat.gui.queue_gui.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
def __init__(
    self,
    queue: Queue,
    stop_event: Event,
    profiler: "Profiler",
    progress_logger: Logger,
    verbose_logger: Logger,
) -> None:
    """Sets up the queue GUI proxy.

    Args:
        queue: Multiprocessing queue for IPC.
        stop_event: Event flagging user cancellation.
        profiler: Profiler for ETA calculations.
        progress_logger: Logger for progress-level messages.
        verbose_logger: Logger for detailed messages.
    """
    self.queue: Queue = queue
    self.stop_event: Event = stop_event
    self.profiler: "Profiler" = profiler
    self.progress_logger: Logger = progress_logger
    self.verbose_logger: Logger = verbose_logger

Methods:

log

log(message: str, level: str = 'verbose', log_type: str = 'default') -> None

Sends a log message to the GUI via queue.

All messages are forwarded through the queue for terminal output (S4L 9.2 fix). Progress messages update the GUI status box; verbose messages only print to terminal.

Parameters:

Name Type Description Default
message str

Log message text.

required
level str

Log level ('progress' or 'verbose').

'verbose'
log_type str

Type for color coding in GUI.

'default'
Source code in goliat/gui/queue_gui.py
def log(self, message: str, level: str = "verbose", log_type: str = "default") -> None:
    """Sends a log message to the GUI via queue.

    All messages are forwarded through the queue for terminal output (S4L 9.2 fix).
    Progress messages update the GUI status box; verbose messages only print to terminal.

    Args:
        message: Log message text.
        level: Log level ('progress' or 'verbose').
        log_type: Type for color coding in GUI.
    """
    import time

    # Use monotonic time with a small increment to ensure unique timestamps
    # even for messages sent in rapid succession
    if not hasattr(self, "_last_timestamp"):
        self._last_timestamp = 0.0
    current_time = time.time()
    # Ensure timestamp is always increasing, even if system clock jumps backward
    if current_time <= self._last_timestamp:
        self._last_timestamp += 0.000001  # 1 microsecond increment
    else:
        self._last_timestamp = current_time

    # Determine message type based on level
    # 'status' messages update GUI status box AND print to terminal
    # 'terminal_only' messages only print to terminal (for verbose logs)
    msg_type = "status" if level == "progress" else "terminal_only"

    self.queue.put(
        {
            "type": msg_type,
            "message": message,
            "log_type": log_type,
            "timestamp": self._last_timestamp,
        }
    )

update_simulation_details

update_simulation_details(sim_count: int, total_sims: int, details: str) -> None

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
def update_simulation_details(self, sim_count: int, total_sims: int, details: str) -> None:
    """Sends current simulation case details to GUI.

    Args:
        sim_count: Current simulation number (1-indexed).
        total_sims: Total simulations in study.
        details: Human-readable description of current case.
    """
    self.queue.put(
        {
            "type": "sim_details",
            "count": sim_count,
            "total": total_sims,
            "details": details,
        }
    )

update_overall_progress

update_overall_progress(current_step: float, total_steps: int) -> None

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
def update_overall_progress(self, current_step: float, total_steps: int) -> None:
    """Updates overall study progress bar.

    Args:
        current_step: Current step number or percentage (0-100).
        total_steps: Total steps in study.
    """
    self.queue.put({"type": "overall_progress", "current": current_step, "total": total_steps})

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
def update_stage_progress(self, stage_name: str, current_step: int, total_steps: int, sub_stage: str = "") -> None:
    """Updates progress for a specific stage (setup/run/extract).

    Args:
        stage_name: Stage name like 'Setup' or 'Running Simulation'.
        current_step: Current step within stage.
        total_steps: Total steps for stage.
        sub_stage: Optional sub-stage description.
    """
    self.queue.put(
        {
            "type": "stage_progress",
            "name": stage_name,
            "current": current_step,
            "total": total_steps,
            "sub_stage": sub_stage,
        }
    )

start_stage_animation

start_stage_animation(task_name: str, end_value: int) -> None

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
def start_stage_animation(self, task_name: str, end_value: int) -> None:
    """Starts animated progress bar for a stage.

    Looks up time estimate from profiler and starts animation that
    progresses toward end_value over that duration.

    Args:
        task_name: Task name ('setup', 'run', 'extract', or subtask name).
        end_value: Target progress value (typically 100).
    """
    if task_name in ["setup", "run", "extract"]:
        estimate = self.profiler.profiling_config.get(f"avg_{task_name}_time", 60)
    else:
        estimate = self.profiler.get_subtask_estimate(task_name)
    self.queue.put({"type": "start_animation", "estimate": estimate, "end_value": end_value})

end_stage_animation

end_stage_animation() -> None

Stops the current animated progress bar.

Source code in goliat/gui/queue_gui.py
def end_stage_animation(self) -> None:
    """Stops the current animated progress bar."""
    self.queue.put({"type": "end_animation"})

update_profiler

update_profiler() -> None

Sends profiler state to GUI for ETA display.

Source code in goliat/gui/queue_gui.py
def update_profiler(self) -> None:
    """Sends profiler state to GUI for ETA display."""
    self.queue.put({"type": "profiler_update", "profiler": self.profiler})

process_events

process_events() -> None

No-op for interface compatibility with ProgressGUI.

Source code in goliat/gui/queue_gui.py
def process_events(self) -> None:
    """No-op for interface compatibility with ProgressGUI."""
    pass

is_stopped

is_stopped() -> bool

Checks if user requested cancellation via GUI.

Source code in goliat/gui/queue_gui.py
def is_stopped(self) -> bool:
    """Checks if user requested cancellation via GUI."""
    return self.stop_event.is_set()

Components

goliat.gui.components.clock_manager.ClockManager

ClockManager(gui: ProgressGUI)

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
def __init__(self, gui: "ProgressGUI") -> None:
    """Store GUI reference for timer updates.

    Args:
        gui: ProgressGUI instance.
    """
    self.gui = gui

Methods:

update

update() -> None

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
def update(self) -> None:
    """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'.
    """
    elapsed_sec = time.monotonic() - self.gui.start_time
    self.gui.elapsed_label.setText(f"Elapsed: {format_time(elapsed_sec)}")

    eta_sec: Optional[float] = None
    if self.gui.profiler and self.gui.profiler.current_phase:
        current_stage_progress_ratio = self.gui.stage_progress_bar.value() / 1000.0
        eta_sec = self.gui.profiler.get_time_remaining(current_stage_progress=current_stage_progress_ratio)

        if eta_sec is not None:
            time_remaining_str = format_time(eta_sec)
            self.gui.eta_label.setText(f"Time Remaining: {time_remaining_str}")
        else:
            self.gui.eta_label.setText("Time Remaining: N/A")
    else:
        self.gui.eta_label.setText("Time Remaining: N/A")

    # Update window title with status
    progress_percent = max(0, self.gui.overall_progress_bar.value() / 100.0)
    title = self.gui.init_window_title
    if title:
        title += " | "
    title += f"[{progress_percent:.2f}%] GOLIAT"
    if self.gui.total_simulations > 0:
        title += f" | Sim {self.gui.current_simulation_count}/{self.gui.total_simulations}"

    # Determine status based on actual activity
    if self.gui.study_is_finished:
        status = "Finished" if not self.gui.study_had_errors else "Finished with Errors"
    elif progress_percent > 0 or self.gui.current_simulation_count > 0:
        status = "Running..."
    else:
        status = "Booting..."

    title += f" | {status}"
    self.gui.setWindowTitle(title)

    # Update web connection status indicator periodically
    if hasattr(self.gui, "web_bridge_manager") and self.gui.web_bridge_manager and self.gui.web_bridge_manager.web_bridge:
        if hasattr(self.gui.web_bridge_manager.web_bridge, "is_connected"):
            if hasattr(self.gui, "error_counter_label") and hasattr(self.gui, "status_manager"):
                self.gui._update_web_status(self.gui.web_bridge_manager.web_bridge.is_connected)

goliat.gui.components.data_manager.DataManager

DataManager(data_dir: str, verbose_logger: Logger)

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
def __init__(self, data_dir: str, verbose_logger: Logger) -> None:
    """Create session-specific CSV files for progress tracking.

    Args:
        data_dir: Directory where data files will be stored.
        verbose_logger: Logger for verbose messages.
    """
    self.data_dir: str = data_dir
    self.verbose_logger: Logger = verbose_logger
    self.session_hash: str = hashlib.md5(f"{time.time()}_{os.getpid()}".encode()).hexdigest()[:8]
    session_timestamp = datetime.now().strftime("%d-%m_%H-%M-%S")

    # Cleanup old CSV files before creating new ones
    self._cleanup_old_data_files()

    self.time_remaining_file: str = os.path.join(self.data_dir, f"time_remaining_{session_timestamp}_{self.session_hash}.csv")
    self.overall_progress_file: str = os.path.join(self.data_dir, f"overall_progress_{session_timestamp}_{self.session_hash}.csv")
    self.system_utilization_file: str = os.path.join(self.data_dir, f"system_utilization_{session_timestamp}_{self.session_hash}.csv")

    # Initialize data files
    self._initialize_files()

Methods:

write_time_remaining

write_time_remaining(hours_remaining: float) -> None

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
def write_time_remaining(self, hours_remaining: float) -> None:
    """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.

    Args:
        hours_remaining: Estimated hours remaining as float.
    """
    self._write_csv_row(self.time_remaining_file, hours_remaining, "time remaining")

write_overall_progress

write_overall_progress(progress_percent: float) -> None

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
def write_overall_progress(self, progress_percent: float) -> None:
    """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.

    Args:
        progress_percent: Overall progress percentage (0-100).
    """
    self._write_csv_row(self.overall_progress_file, progress_percent, "overall progress")

write_system_utilization

write_system_utilization(cpu_percent: float, ram_percent: float, gpu_percent: Optional[float] = None, gpu_vram_percent: Optional[float] = None, disk_read_mbps: Optional[float] = None, disk_write_mbps: Optional[float] = None) -> None

Appends a system utilization data point to CSV.

Writes timestamp and CPU, RAM, GPU utilization, GPU VRAM, and disk I/O throughput 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
disk_read_mbps Optional[float]

Disk read throughput in MB/s, or None if unavailable.

None
disk_write_mbps Optional[float]

Disk write throughput in MB/s, or None if unavailable.

None
Source code in goliat/gui/components/data_manager.py
def write_system_utilization(
    self,
    cpu_percent: float,
    ram_percent: float,
    gpu_percent: Optional[float] = None,
    gpu_vram_percent: Optional[float] = None,
    disk_read_mbps: Optional[float] = None,
    disk_write_mbps: Optional[float] = None,
) -> None:
    """Appends a system utilization data point to CSV.

    Writes timestamp and CPU, RAM, GPU utilization, GPU VRAM, and disk I/O
    throughput to session-specific CSV file. Used for plotting utilization trends over time.

    Args:
        cpu_percent: CPU utilization percentage (0-100).
        ram_percent: RAM utilization percentage (0-100).
        gpu_percent: GPU utilization percentage (0-100), or None if unavailable.
        gpu_vram_percent: GPU VRAM utilization percentage (0-100), or None if unavailable.
        disk_read_mbps: Disk read throughput in MB/s, or None if unavailable.
        disk_write_mbps: Disk write throughput in MB/s, or None if unavailable.
    """
    try:
        current_time = get_ntp_utc_time()  # Use NTP time (bypasses system clock issues)
        with open(self.system_utilization_file, "a", newline="") as f:
            writer = csv.writer(f)
            writer.writerow(
                [
                    current_time.isoformat(),
                    cpu_percent,
                    ram_percent,
                    gpu_percent if gpu_percent is not None else "",
                    gpu_vram_percent if gpu_vram_percent is not None else "",
                    f"{disk_read_mbps:.2f}" if disk_read_mbps is not None else "",
                    f"{disk_write_mbps:.2f}" if disk_write_mbps is not None else "",
                ]
            )
    except Exception as e:
        self.verbose_logger.error(f"Failed to write system utilization data: {e}")

goliat.gui.components.graph_manager.GraphManager

GraphManager(gui: ProgressGUI)

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
def __init__(self, gui: "ProgressGUI") -> None:
    """Initializes graph manager.

    Args:
        gui: ProgressGUI instance.
    """
    self.gui = gui

Methods:

update

update() -> None

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
def update(self) -> None:
    """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.
    """
    # Get current ETA
    eta_sec: Optional[float] = None
    if self.gui.profiler and self.gui.profiler.current_phase:
        current_stage_progress_ratio = self.gui.stage_progress_bar.value() / 1000.0
        eta_sec = self.gui.profiler.get_time_remaining(current_stage_progress=current_stage_progress_ratio)

    # Get current progress
    progress_percent = max(0, self.gui.overall_progress_bar.value() / 100.0)

    # Update time remaining data
    if eta_sec is not None:
        current_time = get_ntp_utc_time()  # Use NTP time (bypasses system clock issues)
        hours_remaining = eta_sec / 3600.0
        self.gui.data_manager.write_time_remaining(hours_remaining)
        self.gui.time_remaining_plot.add_data_point(current_time, hours_remaining)

    # Update overall progress data
    current_time = get_ntp_utc_time()  # Use NTP time (bypasses system clock issues)
    self.gui.data_manager.write_overall_progress(progress_percent)
    self.gui.overall_progress_plot.add_data_point(current_time, progress_percent)

goliat.gui.components.machine_id_detector.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.

Methods:

detect staticmethod

detect(verbose_logger: Logger) -> Optional[str]

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
@staticmethod
def detect(verbose_logger: Logger) -> Optional[str]:
    """Auto-detects machine ID (public IP or local IP).

    Args:
        verbose_logger: Logger for verbose messages.

    Returns:
        Machine ID string, or None if detection failed.
    """
    try:
        import requests

        # Try external service first with retries (matches run_worker.py)
        public_ip = None
        for attempt in range(3):  # Try up to 3 times
            try:
                response = requests.get("https://api.ipify.org", timeout=10)
                if response.status_code == 200:
                    public_ip = response.text.strip()
                    if public_ip:
                        break
            except Exception:
                if attempt < 2:  # Not the last attempt
                    continue
                # Last attempt failed, will fall through to local IP

        if public_ip:
            verbose_logger.info(f"Auto-detected public IP: {public_ip}")
            return public_ip
        else:
            # Fallback to local IP
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            local_ip = s.getsockname()[0]
            s.close()
            verbose_logger.info(f"Auto-detected local IP: {local_ip}")
            return local_ip
    except Exception as e:
        verbose_logger.warning(f"Could not auto-detect machine ID: {e}")
        return None

goliat.gui.components.progress_animation.ProgressAnimation

ProgressAnimation(progress_bar: QProgressBar, timer: QTimer, debug: bool = False)

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
def __init__(self, progress_bar: "QProgressBar", timer: "QTimer", debug: bool = False) -> None:
    """Sets up the animation handler.

    Args:
        progress_bar: Progress bar widget to animate (0-1000 range).
        timer: QTimer instance for animation updates (50ms interval).
        debug: Enable debug logging (currently unused).
    """
    from PySide6.QtCore import QTimer as _QTimer
    from PySide6.QtWidgets import QProgressBar as _QProgressBar

    self.progress_bar: _QProgressBar = progress_bar
    self.timer: _QTimer = timer
    self.debug: bool = debug
    self.active: bool = False
    self.start_time: float = 0.0
    self.duration: float = 0.0
    self.start_value: int = 0
    self.end_value: int = 0

Methods:

start

start(estimated_duration: float, end_step: int) -> None

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
def start(self, estimated_duration: float, end_step: int) -> None:
    """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.

    Args:
        estimated_duration: Estimated task duration in seconds (from profiler).
        end_step: Target step value (unused, always animates to 100%).
    """
    if self.debug:
        self._log(f"start_animation received: duration={estimated_duration:.2f}s, end_step={end_step}")

    self.start_time = time.monotonic()
    self.duration = estimated_duration
    self.start_value = self.progress_bar.value()
    self.end_value = 1000  # Progress bar range is 0-1000

    if self.start_value >= self.end_value:
        if self.debug:
            self._log("Animation skipped, start_value >= end_value.")
        return

    self.active = True
    if not self.timer.isActive():
        self.timer.start(50)
    if self.debug:
        self._log("Animation started.")

stop

stop() -> None

Stops the progress bar animation.

Source code in goliat/gui/components/progress_animation.py
def stop(self) -> None:
    """Stops the progress bar animation."""
    if self.active and self.debug:
        self._log("end_animation called.")
    self.active = False
    if self.timer.isActive():
        self.timer.stop()

update

update() -> None

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
def update(self) -> None:
    """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.
    """
    if not self.active:
        return

    elapsed = time.monotonic() - self.start_time

    if self.duration > 0:
        progress_ratio = min(elapsed / self.duration, 1.0)
    else:
        progress_ratio = 1.0

    value_range = self.end_value - self.start_value
    current_value = self.start_value + int(value_range * progress_ratio)
    current_value = min(current_value, self.end_value)

    self.progress_bar.setValue(current_value)
    percent = (current_value / 1000) * 100
    self.progress_bar.setFormat(f"{percent:.0f}%")

goliat.gui.components.progress_manager.ProgressManager

ProgressManager(gui: ProgressGUI)

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
def __init__(self, gui: "ProgressGUI") -> None:
    """Initializes progress manager.

    Args:
        gui: ProgressGUI instance.
    """
    self.gui = gui

Methods:

update_overall

update_overall(current_step: float, total_steps: int) -> None

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
def update_overall(self, current_step: float, total_steps: int) -> None:
    """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.

    Args:
        current_step: Current step number (0-100 range) or percentage (0-100).
        total_steps: Total number of steps (typically 100).
    """
    if self.gui.DEBUG:
        self.gui.update_status(f"DEBUG: update_overall_progress received: current={current_step}, total={total_steps}")
    if total_steps > 0:
        progress_percent = (current_step / total_steps) * 100
        self.gui.overall_progress_bar.setValue(int(progress_percent * 100))
        self.gui.overall_progress_bar.setFormat(f"{progress_percent:.2f}%")
        if self.gui.DEBUG:
            self.gui.update_status(f"DEBUG: Overall progress set to: {progress_percent:.2f}%")

update_stage

update_stage(stage_name: str, current_step: int, total_steps: int, sub_stage: str = '') -> None

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
def update_stage(self, stage_name: str, current_step: int, total_steps: int, sub_stage: str = "") -> None:
    """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.

    Args:
        stage_name: Name of current stage (e.g., 'Setup', 'Running Simulation').
        current_step: Current step within stage.
        total_steps: Total steps for the stage.
        sub_stage: Optional sub-stage description (currently unused).
    """
    if self.gui.DEBUG:
        self.gui.update_status(
            f"DEBUG: update_stage_progress received: name='{stage_name}', current={current_step}, total={total_steps}, sub_stage='{sub_stage}'"
        )

    self.gui.stage_label.setText(f"Current Stage: {stage_name}")
    self.gui.total_steps_for_stage = total_steps
    self.gui.progress_animation.stop()

    progress_percent = (current_step / total_steps) if total_steps > 0 else 0
    final_value = int(progress_percent * 1000)

    self.gui.stage_progress_bar.setValue(final_value)
    self.gui.stage_progress_bar.setFormat(f"{progress_percent * 100:.0f}%")
    if self.gui.DEBUG:
        self.gui.update_status(f"DEBUG: Stage '{stage_name}' progress set to: {progress_percent * 100:.0f}%")

update_simulation_details

update_simulation_details(sim_count: int, total_sims: int, details: str) -> None

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
def update_simulation_details(self, sim_count: int, total_sims: int, details: str) -> None:
    """Updates simulation counter and details labels.

    Args:
        sim_count: Current simulation number.
        total_sims: Total number of simulations.
        details: Description of current simulation case.
    """
    self.gui.current_simulation_count = sim_count
    self.gui.total_simulations = total_sims
    self.gui.sim_counter_label.setText(f"Simulation: {sim_count} / {total_sims}")
    self.gui.sim_details_label.setText(f"Current Case: {details}")

    # Send simulation details to web dashboard
    if hasattr(self.gui, "web_bridge_manager") and self.gui.web_bridge_manager is not None:
        if self.gui.web_bridge_manager.web_bridge is not None:
            self.gui.web_bridge_manager.web_bridge.enqueue(
                {"type": "simulation_details", "simulation_count": sim_count, "total_simulations": total_sims, "current_case": details}
            )

goliat.gui.components.queue_handler.QueueHandler

QueueHandler(gui_instance: ProgressGUI)

Handles processing of messages from the worker process queue.

Polls the multiprocessing queue and dispatches messages to the matching 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
def __init__(self, gui_instance: "ProgressGUI") -> None:
    """Wire up message handlers to GUI instance.

    Args:
        gui_instance: ProgressGUI instance to update with messages.
    """
    self.gui: "ProgressGUI" = gui_instance
    self._MESSAGE_HANDLERS = {
        "status": self._handle_status,
        "terminal_only": self._handle_terminal_only,  # Verbose logs - terminal only, no GUI update
        "print": self._handle_print,  # stdout/stderr from child process
        "overall_progress": self._handle_overall_progress,
        "stage_progress": self._handle_stage_progress,
        "start_animation": self._handle_start_animation,
        "end_animation": self._handle_end_animation,
        "profiler_update": self._handle_profiler_update,
        "sim_details": self._handle_sim_details,
        "finished": self._handle_finished,
        "fatal_error": self._handle_fatal_error,
        "memory_error": self._handle_memory_error,
    }

Methods:

process_queue

process_queue() -> None

Processes messages from worker process queue and updates UI.

Polls queue non-blockingly and processes all available messages in one call. Routes each message type to its handler method. 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
def process_queue(self) -> None:
    """Processes messages from worker process queue and updates UI.

    Polls queue non-blockingly and processes all available messages in one
    call. Routes each message type to its handler method.
    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).
    """
    while not self.gui.queue.empty():
        try:
            msg: Dict[str, Any] = self.gui.queue.get_nowait()
            msg_type: Optional[str] = msg.get("type")

            # Dispatch message to its handler
            if msg_type:
                handler = self._MESSAGE_HANDLERS.get(msg_type)
                if handler:
                    handler(msg)

            # Forward message to web bridge if enabled
            if hasattr(self.gui, "web_bridge_manager") and self.gui.web_bridge_manager.web_bridge is not None:
                try:
                    # Sanitize profiler_update messages before forwarding
                    if msg_type == "profiler_update" and "profiler" in msg:
                        profiler = msg.get("profiler")
                        # Extract only serializable data from profiler
                        # Calculate eta_seconds using get_time_remaining() method
                        eta_seconds = None
                        if profiler and hasattr(profiler, "get_time_remaining"):
                            try:
                                # Get current stage progress ratio from GUI if available
                                current_stage_progress = 0.0
                                if hasattr(self.gui, "stage_progress_bar"):
                                    stage_value = self.gui.stage_progress_bar.value()
                                    stage_max = self.gui.stage_progress_bar.maximum()
                                    if stage_max > 0:
                                        current_stage_progress = stage_value / stage_max
                                # Call get_time_remaining() to get ETA in seconds
                                eta_seconds = profiler.get_time_remaining(current_stage_progress=current_stage_progress)
                            except Exception as e:
                                # If calculation fails, log but don't crash
                                if hasattr(self.gui, "verbose_logger"):
                                    self.gui.verbose_logger.debug(f"Failed to calculate ETA: {e}")
                        sanitized_msg = {
                            "type": "profiler_update",
                            "eta_seconds": eta_seconds,
                        }
                        self.gui.web_bridge_manager.web_bridge.enqueue(sanitized_msg)
                    else:
                        self.gui.web_bridge_manager.web_bridge.enqueue(msg)
                except Exception as e:
                    # Don't let web bridge errors crash the GUI
                    self.gui.verbose_logger.warning(f"Failed to forward message to web bridge: {e}")

        except Empty:
            break
        except Exception as e:
            self.gui.verbose_logger.error(f"Error processing GUI queue: {e}\n{traceback.format_exc()}")

goliat.gui.components.screenshot_capture.ScreenshotCapture

ScreenshotCapture(gui: ProgressGUI)

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
def __init__(self, gui: "ProgressGUI") -> None:
    """Initialize screenshot capture component.

    Args:
        gui: ProgressGUI instance with tabs to capture.
    """
    self.gui = gui
    self.verbose_logger = logging.getLogger("screenshot_capture")

Methods:

capture_all_tabs

capture_all_tabs() -> Dict[str, bytes]

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
def capture_all_tabs(self) -> Dict[str, bytes]:
    """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:
        Dictionary mapping tab names to JPEG bytes.
        Empty dict if capture fails or PySide6 not available.
    """
    if QBuffer is None or QWidget is None or QPixmap is None:
        return {}

    screenshots: Dict[str, bytes] = {}

    try:
        if not hasattr(self.gui, "tabs"):
            self.verbose_logger.warning("GUI has no tabs attribute")
            return {}

        tabs = self.gui.tabs
        tab_count = tabs.count()

        for i in range(tab_count):
            try:
                tab_widget = tabs.widget(i)
                tab_name = tabs.tabText(i)

                if tab_widget is None:
                    self.verbose_logger.warning(f"Tab {i} ({tab_name}) has no widget")
                    continue

                # Skip the main "Progress" tab - its data is already sent via other mechanisms
                if tab_name == "Progress":
                    continue

                # Get the size of the tab widget's parent (QTabWidget) to know the proper size
                # Non-visible tabs might have zero size, so we use parent size as reference
                parent_size = tabs.size()
                widget_width = tab_widget.width() if tab_widget.width() > 0 else parent_size.width()
                widget_height = tab_widget.height() if tab_widget.height() > 0 else parent_size.height()

                # Fallback to reasonable defaults if sizes are still zero
                if widget_width == 0:
                    widget_width = 800
                if widget_height == 0:
                    widget_height = 600

                # Process events to ensure all widgets are painted
                if QApplication is not None:
                    QApplication.processEvents()

                pixmap = QPixmap(widget_width, widget_height)
                pixmap.fill()
                tab_widget.render(pixmap)

                # Process events after rendering
                if QApplication is not None:
                    QApplication.processEvents()

                if pixmap.isNull():
                    self.verbose_logger.warning(f"Failed to grab pixmap for tab {tab_name}")
                    continue

                # Verify pixmap has content (not just empty/white)
                if pixmap.width() == 0 or pixmap.height() == 0:
                    self.verbose_logger.warning(f"Pixmap for tab {tab_name} has zero size")
                    continue

                # Convert to JPEG bytes
                jpeg_bytes = self._compress_to_jpeg(pixmap)

                if jpeg_bytes:
                    screenshots[tab_name] = jpeg_bytes
                    self.verbose_logger.debug(f"Captured screenshot for tab '{tab_name}' ({len(jpeg_bytes)} bytes)")

            except Exception as e:
                # Log error but continue capturing other tabs
                self.verbose_logger.warning(f"Failed to capture tab {i}: {e}", exc_info=True)
                continue

    except Exception as e:
        self.verbose_logger.error(f"Failed to capture screenshots: {e}", exc_info=True)

    return screenshots

goliat.gui.components.status_manager.StatusManager

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
def __init__(self) -> None:
    """Initializes status manager with default counters and color map."""
    self.warning_count: int = 0
    self.error_count: int = 0

    # Color mapping - NOTE: Intentionally using white for "progress" in GUI
    # since all messages shown here are progress updates. This deviates from
    # the terminal color scheme defined in goliat/colors.py for better readability.
    self.color_map: dict[str, str] = {
        "default": "#f0f0f0",  # WHITE
        "progress": "#f0f0f0",  # WHITE (GUI-specific override)
        "info": "#17a2b8",  # CYAN
        "verbose": "#007acc",  # BLUE
        "warning": "#ffc107",  # YELLOW
        "error": "#dc3545",  # RED
        "fatal": "#d63384",  # MAGENTA
        "success": "#5cb85c",  # BRIGHT GREEN
        "header": "#e83e8c",  # BRIGHT MAGENTA
        "highlight": "#ffd700",  # BRIGHT YELLOW
        "caller": "#6c757d",  # DIM (gray)
    }

Methods:

get_color

get_color(log_type: str) -> str

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).

Source code in goliat/gui/components/status_manager.py
def get_color(self, log_type: str) -> str:
    """Gets HTML color code for a log type.

    Args:
        log_type: Type of log message.

    Returns:
        HTML color code (hex).
    """
    return self.color_map.get(log_type, "#f0f0f0")

format_message

format_message(message: str, log_type: str = 'default') -> str

Formats message with HTML color styling.

Strips any ANSI escape codes (from terminal formatters), preserves leading spaces by converting them to   entities, then wraps message in a tag with the matching color.

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
def format_message(self, message: str, log_type: str = "default") -> str:
    """Formats message with HTML color styling.

    Strips any ANSI escape codes (from terminal formatters), preserves
    leading spaces by converting them to &nbsp; entities, then wraps
    message in a <span> tag with the matching color.

    Args:
        message: Message text to format.
        log_type: Log type for color selection.

    Returns:
        HTML-formatted message string ready for QTextEdit.
    """
    import re

    # Strip ANSI escape codes (e.g., \x1b[35m, \x1b[0m)
    ansi_pattern = re.compile(r"\x1b\[[0-9;]*m")
    clean_message = ansi_pattern.sub("", message)

    # Preserve leading spaces by converting them to &nbsp;
    preserved_message = clean_message.replace(" ", "&nbsp;")
    color = self.get_color(log_type)
    return f'<span style="color:{color};">{preserved_message}</span>'

record_log

record_log(log_type: str) -> None

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
def record_log(self, log_type: str) -> None:
    """Records log entry and updates warning/error counters.

    Args:
        log_type: Type of log message.
    """
    if log_type == "warning":
        self.warning_count += 1
    elif log_type in ["error", "fatal"]:
        self.error_count += 1

get_error_summary

get_error_summary(web_connected: bool = False) -> str

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
def get_error_summary(self, web_connected: bool = False) -> str:
    """Gets formatted summary of warnings and errors with optional web status.

    Args:
        web_connected: Whether web dashboard is connected (optional).

    Returns:
        Formatted string with emoji indicators and counts.
    """
    web_status = "🟢" if web_connected else "🔴"
    return f"⚠️ Warnings: {self.warning_count} | ❌ Errors: {self.error_count} | {web_status} Web"

goliat.gui.components.system_monitor.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.

Methods:

get_cpu_utilization staticmethod

get_cpu_utilization() -> float

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
@staticmethod
def get_cpu_utilization() -> float:
    """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:
        CPU usage percentage (0-100), or 0.0 if psutil unavailable.
    """
    if not PSUTIL_AVAILABLE:
        return 0.0
    try:
        # Non-blocking call - returns utilization since last call
        # psutil is guaranteed to be available here due to PSUTIL_AVAILABLE check
        cpu_percent = psutil.cpu_percent(interval=None)  # type: ignore[possibly-unbound]
        # Clamp to valid range (psutil can sometimes return slightly negative or >100)
        return max(0.0, min(100.0, cpu_percent))
    except Exception:
        return 0.0

get_ram_utilization staticmethod

get_ram_utilization() -> Tuple[float, float]

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
@staticmethod
def get_ram_utilization() -> Tuple[float, float]:
    """Gets current RAM usage and total RAM.

    Returns:
        Tuple of (used_GB, total_GB), or (0.0, 0.0) if psutil unavailable.
    """
    if not PSUTIL_AVAILABLE:
        return (0.0, 0.0)
    try:
        # psutil is guaranteed to be available here due to PSUTIL_AVAILABLE check
        memory = psutil.virtual_memory()  # type: ignore[possibly-unbound]
        used_gb = memory.used / (1024**3)
        total_gb = memory.total / (1024**3)
        return (used_gb, total_gb)
    except Exception:
        return (0.0, 0.0)

get_ram_utilization_detailed staticmethod

get_ram_utilization_detailed() -> Tuple[float, float, float]

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
  • percent_with_cache: (used / total) * 100 (includes cacheable memory)
float
  • percent_without_cache: ((total - available) / total) * 100 (excludes cacheable memory)
Tuple[float, float, float]
  • total_GB: Total RAM in GB
Source code in goliat/gui/components/system_monitor.py
@staticmethod
def get_ram_utilization_detailed() -> Tuple[float, float, float]:
    """Gets RAM utilization with and without cacheable memory.

    Returns:
        Tuple of (percent_with_cache, percent_without_cache, total_GB), or (0.0, 0.0, 0.0) if psutil unavailable.
        - percent_with_cache: (used / total) * 100 (includes cacheable memory)
        - percent_without_cache: ((total - available) / total) * 100 (excludes cacheable memory)
        - total_GB: Total RAM in GB
    """
    if not PSUTIL_AVAILABLE:
        return (0.0, 0.0, 0.0)
    try:
        # psutil is guaranteed to be available here due to PSUTIL_AVAILABLE check
        memory = psutil.virtual_memory()  # type: ignore[possibly-unbound]
        total_gb = memory.total / (1024**3)

        # With cache: used / total
        percent_with_cache = memory.percent

        # Without cache: (total - available) / total
        # This excludes cacheable memory that can be freed
        percent_without_cache = ((memory.total - memory.available) / memory.total) * 100

        return (percent_with_cache, percent_without_cache, total_gb)
    except Exception:
        return (0.0, 0.0, 0.0)

get_gpu_vram_utilization staticmethod

get_gpu_vram_utilization() -> Optional[Tuple[float, float]]

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
@staticmethod
def get_gpu_vram_utilization() -> Optional[Tuple[float, float]]:
    """Gets current GPU VRAM usage and total VRAM.

    Returns:
        Tuple of (used_GB, total_GB), or None if nvidia-smi unavailable.
    """
    try:
        result = subprocess.run(
            ["nvidia-smi", "--query-gpu=memory.used,memory.total", "--format=csv,noheader,nounits"],
            capture_output=True,
            text=True,
            timeout=2,
            check=False,
        )
        if result.returncode == 0 and result.stdout.strip():
            # Get first GPU's memory usage
            memory_str = result.stdout.strip().split("\n")[0].strip()
            parts = memory_str.split(", ")
            if len(parts) == 2:
                used_mb = float(parts[0].strip())
                total_mb = float(parts[1].strip())
                used_gb = used_mb / 1024.0
                total_gb = total_mb / 1024.0
                return (used_gb, total_gb)
        return None
    except (subprocess.TimeoutExpired, subprocess.CalledProcessError, FileNotFoundError, ValueError, IndexError):
        return None

get_gpu_utilization staticmethod

get_gpu_utilization() -> Optional[float]

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
@staticmethod
def get_gpu_utilization() -> Optional[float]:
    """Gets current GPU utilization percentage via nvidia-smi.

    Returns:
        GPU usage percentage (0-100), or None if nvidia-smi unavailable.
    """
    try:
        result = subprocess.run(
            ["nvidia-smi", "--query-gpu=utilization.gpu", "--format=csv,noheader,nounits"],
            capture_output=True,
            text=True,
            timeout=2,
            check=False,
        )
        if result.returncode == 0 and result.stdout.strip():
            # Get first GPU's utilization
            utilization_str = result.stdout.strip().split("\n")[0].strip()
            return float(utilization_str)
        return None
    except (subprocess.TimeoutExpired, subprocess.CalledProcessError, FileNotFoundError, ValueError):
        return None

get_gpu_name staticmethod

get_gpu_name() -> Optional[str]

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
@staticmethod
def get_gpu_name() -> Optional[str]:
    """Gets GPU name via nvidia-smi.

    Returns:
        GPU name (e.g., "RTX 4090"), or None if nvidia-smi unavailable.
    """
    try:
        result = subprocess.run(
            ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
            capture_output=True,
            text=True,
            timeout=2,
            check=False,
        )
        if result.returncode == 0 and result.stdout.strip():
            # Get first GPU's name and clean it up
            gpu_name = result.stdout.strip().split("\n")[0].strip()
            # Remove common prefixes like "NVIDIA " and clean up
            gpu_name = gpu_name.replace("NVIDIA ", "").strip()
            return gpu_name
        return None
    except (subprocess.TimeoutExpired, subprocess.CalledProcessError, FileNotFoundError):
        return None

get_cpu_cores staticmethod

get_cpu_cores() -> int

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
@staticmethod
def get_cpu_cores() -> int:
    """Gets number of CPU cores.

    Returns:
        Number of CPU cores, or 0 if psutil unavailable.
    """
    if not PSUTIL_AVAILABLE:
        return 0
    try:
        return psutil.cpu_count(logical=True) or 0  # type: ignore[possibly-unbound]
    except Exception:
        return 0

get_total_ram_gb staticmethod

get_total_ram_gb() -> float

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
@staticmethod
def get_total_ram_gb() -> float:
    """Gets total RAM in GB.

    Returns:
        Total RAM in GB, or 0.0 if psutil unavailable.
    """
    if not PSUTIL_AVAILABLE:
        return 0.0
    try:
        memory = psutil.virtual_memory()  # type: ignore[possibly-unbound]
        return memory.total / (1024**3)
    except Exception:
        return 0.0

get_disk_io_throughput staticmethod

get_disk_io_throughput() -> Optional[Tuple[float, float]]

Gets current disk I/O throughput in MB/s.

Calculates read and write speeds by comparing current I/O counters with values from the previous call. First call returns None as there's no baseline for comparison.

Returns:

Type Description
Optional[Tuple[float, float]]

Tuple of (read_MB_per_sec, write_MB_per_sec), or None if unavailable.

Source code in goliat/gui/components/system_monitor.py
@staticmethod
def get_disk_io_throughput() -> Optional[Tuple[float, float]]:
    """Gets current disk I/O throughput in MB/s.

    Calculates read and write speeds by comparing current I/O counters
    with values from the previous call. First call returns None as there's
    no baseline for comparison.

    Returns:
        Tuple of (read_MB_per_sec, write_MB_per_sec), or None if unavailable.
    """
    if not PSUTIL_AVAILABLE:
        return None
    try:
        import time

        current_time = time.time()
        # psutil is guaranteed to be available here due to PSUTIL_AVAILABLE check
        io_counters = psutil.disk_io_counters()  # type: ignore[possibly-unbound]
        if io_counters is None:
            return None

        current_read = io_counters.read_bytes
        current_write = io_counters.write_bytes

        if SystemMonitor._last_disk_io is None:
            # First call - store baseline and return None
            SystemMonitor._last_disk_io = (current_read, current_write, current_time)
            return None

        last_read, last_write, last_time = SystemMonitor._last_disk_io
        time_delta = current_time - last_time

        if time_delta <= 0:
            return None

        # Calculate throughput in MB/s
        read_speed = (current_read - last_read) / (1024 * 1024) / time_delta
        write_speed = (current_write - last_write) / (1024 * 1024) / time_delta

        # Update stored values for next call
        SystemMonitor._last_disk_io = (current_read, current_write, current_time)

        # Clamp to non-negative (counters can wrap on some systems)
        return (max(0.0, read_speed), max(0.0, write_speed))
    except Exception:
        return None

is_gpu_available staticmethod

is_gpu_available() -> bool

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
@staticmethod
def is_gpu_available() -> bool:
    """Checks if GPU is available via nvidia-smi.

    Returns:
        True if nvidia-smi is available and returns successfully, False otherwise.
    """
    return SystemMonitor.get_gpu_utilization() is not None

get_page_faults_per_second staticmethod

get_page_faults_per_second() -> Optional[float]

Gets current hard page faults per second.

Hard page faults (major faults) occur when the system needs to read data from disk because it's not in RAM. High rates indicate memory pressure and can significantly impact performance.

Calculates the rate by comparing current page fault count with the previous call. First call returns None as there's no baseline.

Returns:

Type Description
Optional[float]

Page faults per second, or None if unavailable.

Source code in goliat/gui/components/system_monitor.py
@staticmethod
def get_page_faults_per_second() -> Optional[float]:
    """Gets current hard page faults per second.

    Hard page faults (major faults) occur when the system needs to read data
    from disk because it's not in RAM. High rates indicate memory pressure
    and can significantly impact performance.

    Calculates the rate by comparing current page fault count with the
    previous call. First call returns None as there's no baseline.

    Returns:
        Page faults per second, or None if unavailable.
    """
    if not PSUTIL_AVAILABLE:
        return None
    try:
        import time

        current_time = time.time()
        # psutil is guaranteed to be available here due to PSUTIL_AVAILABLE check
        swap_info = psutil.swap_memory()  # type: ignore[possibly-unbound]

        # On Windows, swap_memory().sin and .sout track page-ins and page-outs
        # We use sin (swap in) as it represents data being read from disk to RAM
        # which is the hard fault scenario
        # Note: On Linux, we could also use /proc/vmstat for more detailed stats
        current_faults = swap_info.sin  # Bytes swapped in from disk

        if SystemMonitor._last_page_faults is None:
            # First call - store baseline and return None
            SystemMonitor._last_page_faults = (current_faults, current_time)
            return None

        last_faults, last_time = SystemMonitor._last_page_faults
        time_delta = current_time - last_time

        if time_delta <= 0:
            return None

        # Calculate faults per second (convert bytes to pages, assuming 4KB pages)
        page_size = 4096  # Standard page size in bytes
        faults_delta = current_faults - last_faults
        pages_swapped = faults_delta / page_size
        faults_per_second = pages_swapped / time_delta

        # Update stored values for next call
        SystemMonitor._last_page_faults = (current_faults, current_time)

        # Clamp to non-negative (counters can wrap on some systems)
        return max(0.0, faults_per_second)
    except Exception:
        return None

goliat.gui.components.timings_table.TimingsTable

TimingsTable(table_widget: QTableWidget)

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
def __init__(self, table_widget: QTableWidget) -> None:
    """Sets up the timings table widget.

    Args:
        table_widget: QTableWidget instance to populate with timing data.
    """
    self.table: QTableWidget = table_widget
    self._setup_table()

Methods:

update

update(profiler: Profiler) -> None

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
def update(self, profiler: "Profiler") -> None:
    """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

    Args:
        profiler: Profiler instance containing timing data.
    """
    if not profiler:
        return

    self.table.setRowCount(0)

    # Collect all tasks with their raw timing data
    all_tasks: Dict[str, Dict[str, Any]] = {}
    for phase in ["setup", "run", "extract"]:
        avg_time = profiler.profiling_config.get(f"avg_{phase}_time")
        if avg_time is not None:
            raw_times = profiler.subtask_times.get(phase, [])
            all_tasks[f"{phase}_total"] = {
                "phase": phase,
                "subtask": "---",
                "raw_times": raw_times if raw_times else [avg_time],
            }

    # Filter out fake aggregated entries that shouldn't be displayed
    fake_entries = ["setup_simulation", "run_simulation_total", "extract_results_total"]

    for key, value in profiler.profiling_config.items():
        if key.startswith("avg_") and "_time" not in key:
            task_name = key.replace("avg_", "")

            # Skip fake aggregated entries
            if task_name in fake_entries:
                continue

            parts = task_name.split("_", 1)
            phase = parts[0]
            subtask_name = parts[1] if len(parts) > 1 else phase
            raw_times = profiler.subtask_times.get(task_name, [])
            all_tasks[key] = {
                "phase": phase,
                "subtask": subtask_name,
                "raw_times": raw_times if raw_times else [value],
            }

    # Populate table with statistics
    for task_info in all_tasks.values():
        row_position = self.table.rowCount()
        self.table.insertRow(row_position)

        times: List[float] = task_info.get("raw_times", [])
        if times:
            times_array = np.array(times)
            mean_val = float(np.mean(times_array))
            median_val = float(np.median(times_array))
            min_val = float(np.min(times_array))
            max_val = float(np.max(times_array))
            p10 = float(np.percentile(times_array, 10))
            p25 = float(np.percentile(times_array, 25))
            p75 = float(np.percentile(times_array, 75))
            p90 = float(np.percentile(times_array, 90))
        else:
            mean_val = median_val = min_val = max_val = p10 = p25 = p75 = p90 = 0.0

        # Create items and set text color to ensure visibility in both light and dark modes
        light_text_color = QColor("#f0f0f0")
        items = [
            QTableWidgetItem(task_info.get("phase", "N/A")),
            QTableWidgetItem(task_info.get("subtask", "---")),
            QTableWidgetItem(f"{mean_val:.2f}"),
            QTableWidgetItem(f"{median_val:.2f}"),
            QTableWidgetItem(f"{min_val:.2f}"),
            QTableWidgetItem(f"{max_val:.2f}"),
            QTableWidgetItem(f"{p10:.2f}"),
            QTableWidgetItem(f"{p25:.2f}"),
            QTableWidgetItem(f"{p75:.2f}"),
            QTableWidgetItem(f"{p90:.2f}"),
        ]
        for item in items:
            item.setForeground(light_text_color)

        self.table.setItem(row_position, 0, items[0])
        self.table.setItem(row_position, 1, items[1])
        self.table.setItem(row_position, 2, items[2])
        self.table.setItem(row_position, 3, items[3])
        self.table.setItem(row_position, 4, items[4])
        self.table.setItem(row_position, 5, items[5])
        self.table.setItem(row_position, 6, items[6])
        self.table.setItem(row_position, 7, items[7])
        self.table.setItem(row_position, 8, items[8])
        self.table.setItem(row_position, 9, items[9])

goliat.gui.components.tray_manager.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
def __init__(self, parent_widget: QWidget, show_callback: Callable[[], None], close_callback: Callable[[], None]) -> None:
    """Sets up tray icon with menu.

    Args:
        parent_widget: Parent widget (ProgressGUI window).
        show_callback: Function to call when restoring window.
        close_callback: Function to call when exiting application.
    """
    self.parent: QWidget = parent_widget
    self.tray_icon: QSystemTrayIcon = QSystemTrayIcon(parent_widget)

    # Set icon
    icon_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets", "favicon.svg")
    if os.path.exists(icon_path):
        self.tray_icon.setIcon(QIcon(icon_path))
    else:
        style = parent_widget.style()
        icon = style.standardIcon(style.StandardPixmap.SP_ComputerIcon)
        self.tray_icon.setIcon(icon)
    self.tray_icon.setToolTip("Simulation is running...")

    # Create menu
    tray_menu = QMenu(parent_widget)
    show_action = QAction("Show", parent_widget)
    show_action.triggered.connect(show_callback)
    tray_menu.addAction(show_action)

    exit_action = QAction("Exit", parent_widget)
    exit_action.triggered.connect(close_callback)
    tray_menu.addAction(exit_action)

    self.tray_icon.setContextMenu(tray_menu)
    self.tray_icon.activated.connect(lambda reason: self._tray_icon_activated(reason, show_callback))

Methods:

show

show() -> None

Shows the tray icon.

Source code in goliat/gui/components/tray_manager.py
def show(self) -> None:
    """Shows the tray icon."""
    self.tray_icon.show()

hide

hide() -> None

Hides the tray icon.

Source code in goliat/gui/components/tray_manager.py
def hide(self) -> None:
    """Hides the tray icon."""
    self.tray_icon.hide()

is_visible

is_visible() -> bool

Checks if tray icon is visible.

Returns:

Type Description
bool

True if visible, False otherwise.

Source code in goliat/gui/components/tray_manager.py
def is_visible(self) -> bool:
    """Checks if tray icon is visible.

    Returns:
        True if visible, False otherwise.
    """
    return self.tray_icon.isVisible()

goliat.gui.components.ui_builder.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.

Methods:

get_icon_path staticmethod

get_icon_path() -> str

Gets path to window icon.

Returns:

Type Description
str

Absolute path to favicon.svg.

Source code in goliat/gui/components/ui_builder.py
@staticmethod
def get_icon_path() -> str:
    """Gets path to window icon.

    Returns:
        Absolute path to favicon.svg.
    """
    return os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets", "favicon.svg")

build staticmethod

build(gui_instance: ProgressGUI, status_manager: StatusManager) -> None

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
@staticmethod
def build(gui_instance: "ProgressGUI", status_manager: "StatusManager") -> None:
    """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.

    Args:
        gui_instance: ProgressGUI instance to build UI for.
        status_manager: StatusManager instance for error summary display.
    """
    gui_instance.setWindowTitle(gui_instance.init_window_title)
    gui_instance.resize(800, 900)

    # Set window icon
    icon_path = UIBuilder.get_icon_path()
    if os.path.exists(icon_path):
        gui_instance.setWindowIcon(QIcon(icon_path))

    gui_instance.setStyleSheet(UIBuilder.STYLESHEET)

    main_layout = QVBoxLayout(gui_instance)
    gui_instance.tabs = QTabWidget()
    main_layout.addWidget(gui_instance.tabs)

    # Build tabs
    UIBuilder._build_progress_tab(gui_instance, status_manager)
    UIBuilder._build_timings_tab(gui_instance)
    UIBuilder._build_piecharts_tab(gui_instance)
    UIBuilder._build_time_remaining_tab(gui_instance)
    UIBuilder._build_overall_progress_tab(gui_instance)
    UIBuilder._build_system_utilization_tab(gui_instance)
    UIBuilder._build_disk_io_tab(gui_instance)

    # Build buttons
    UIBuilder._build_buttons(gui_instance, main_layout)

goliat.gui.components.utilization_manager.UtilizationManager

UtilizationManager(gui: ProgressGUI)

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
def __init__(self, gui: "ProgressGUI") -> None:
    """Initializes utilization manager.

    Args:
        gui: ProgressGUI instance.
    """
    self.gui = gui
    # Initialize last values to avoid issues before first update
    self._last_cpu_percent: float = 0.0
    self._last_ram_percent: float = 0.0
    self._last_gpu_percent: Optional[float] = None
    self._last_gpu_vram_percent: Optional[float] = None
    self._last_disk_read_mbps: Optional[float] = None
    self._last_disk_write_mbps: Optional[float] = None
    self._last_page_faults_per_sec: Optional[float] = None

Methods:

update

update() -> None

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
def update(self) -> None:
    """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.
    """
    # Update CPU utilization
    cpu_percent = SystemMonitor.get_cpu_utilization()
    self.gui.cpu_bar.setValue(int(cpu_percent))
    self.gui.cpu_bar.setFormat(f"{cpu_percent:.0f}%")

    # Update RAM utilization
    ram_percent_with_cache, _, total_gb = SystemMonitor.get_ram_utilization_detailed()
    used_gb, _ = SystemMonitor.get_ram_utilization()

    if total_gb > 0:
        ram_percent = ram_percent_with_cache
        self.gui.ram_bar.setValue(int(ram_percent))
        self.gui.ram_bar.setFormat(f"{used_gb:.1f}/{total_gb:.1f} GB")
    else:
        ram_percent = 0.0
        self.gui.ram_bar.setValue(0)
        self.gui.ram_bar.setFormat("N/A")

    # Update GPU utilization
    # Always try to get GPU data, not just when gpu_available is True
    # This allows recovery after temporary failures
    gpu_percent: Optional[float] = None
    gpu_percent = SystemMonitor.get_gpu_utilization()
    if gpu_percent is not None:
        self.gui.gpu_bar.setValue(int(gpu_percent))
        self.gui.gpu_bar.setFormat(f"{gpu_percent:.0f}%")
        self.gui.gpu_available = True  # Reset to True if we get data
    else:
        self.gui.gpu_bar.setValue(0)
        self.gui.gpu_bar.setFormat("N/A")
        # Don't set gpu_available to False here - allow recovery

    # Store current values for plot update (updated less frequently via graph_manager)
    self._last_cpu_percent = cpu_percent
    self._last_ram_percent = ram_percent
    self._last_gpu_percent = gpu_percent

    # Get GPU VRAM utilization for plot (not shown in main tab)
    # Always try to get VRAM data, not just when gpu_available is True
    # This allows recovery after temporary failures
    vram_info = SystemMonitor.get_gpu_vram_utilization()
    if vram_info is not None:
        used_vram_gb, total_vram_gb = vram_info
        if total_vram_gb > 0:
            self._last_gpu_vram_percent = (used_vram_gb / total_vram_gb) * 100
            self.gui.gpu_available = True  # Reset to True if we get VRAM data
        else:
            self._last_gpu_vram_percent = None
    else:
        self._last_gpu_vram_percent = None

    # Get disk I/O throughput for plot (not shown in main tab)
    disk_io = SystemMonitor.get_disk_io_throughput()
    if disk_io is not None:
        self._last_disk_read_mbps, self._last_disk_write_mbps = disk_io
    else:
        self._last_disk_read_mbps = None
        self._last_disk_write_mbps = None

    # Get page faults per second for plot (indicates memory pressure)
    self._last_page_faults_per_sec = SystemMonitor.get_page_faults_per_second()

update_plot

update_plot() -> None

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
def update_plot(self) -> None:
    """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.
    """
    current_time = get_ntp_utc_time()  # Use NTP time (bypasses system clock issues)

    # Write to CSV (includes RAM, GPU VRAM, and disk I/O)
    try:
        self.gui.data_manager.write_system_utilization(
            self._last_cpu_percent,
            self._last_ram_percent,
            self._last_gpu_percent,
            self._last_gpu_vram_percent,
            self._last_disk_read_mbps,
            self._last_disk_write_mbps,
        )
    except Exception as e:
        self.gui.verbose_logger.error(f"[UtilizationPlot] CSV write failed: {e}")

    # Add to system utilization plot (CPU, RAM, GPU, VRAM)
    if hasattr(self.gui, "system_utilization_plot"):
        # Get system info for legend
        from goliat.gui.components.system_monitor import SystemMonitor

        cpu_cores = SystemMonitor.get_cpu_cores()
        total_ram_gb = SystemMonitor.get_total_ram_gb()
        gpu_name = SystemMonitor.get_gpu_name()

        # Get GPU VRAM total for legend
        # Always try to get VRAM info, not just when gpu_available is True
        total_gpu_vram_gb = 0.0
        vram_info = SystemMonitor.get_gpu_vram_utilization()
        if vram_info is not None:
            _, total_gpu_vram_gb = vram_info

        try:
            self.gui.system_utilization_plot.add_data_point(
                timestamp=current_time,
                cpu_percent=self._last_cpu_percent,
                ram_percent=self._last_ram_percent,
                gpu_percent=self._last_gpu_percent,
                gpu_vram_percent=self._last_gpu_vram_percent,
                cpu_cores=cpu_cores,
                total_ram_gb=total_ram_gb,
                gpu_name=gpu_name,
                total_gpu_vram_gb=total_gpu_vram_gb,
            )
        except Exception as e:
            self.gui.verbose_logger.error(f"[UtilizationPlot] Failed to add plot data point: {e}")
    else:
        self.gui.verbose_logger.warning("[UtilizationPlot] system_utilization_plot attribute not found on GUI")

    # Add to disk I/O plot (includes page faults on secondary axis)
    if hasattr(self.gui, "disk_io_plot"):
        try:
            self.gui.disk_io_plot.add_data_point(
                timestamp=current_time,
                disk_read_mbps=self._last_disk_read_mbps,
                disk_write_mbps=self._last_disk_write_mbps,
                page_faults_per_sec=self._last_page_faults_per_sec,
            )
        except Exception as e:
            self.gui.verbose_logger.error(f"[DiskIOPlot] Failed to add plot data point: {e}")

goliat.gui.components.web_bridge_manager.WebBridgeManager

WebBridgeManager(gui: ProgressGUI, server_url: str, machine_id: Optional[str], use_web: bool = True)

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
use_web bool

Whether to enable web bridge (default: True).

True
Source code in goliat/gui/components/web_bridge_manager.py
def __init__(self, gui: "ProgressGUI", server_url: str, machine_id: Optional[str], use_web: bool = True) -> None:
    """Initializes web bridge manager.

    Args:
        gui: ProgressGUI instance.
        server_url: Web dashboard server URL.
        machine_id: Machine ID for identification.
        use_web: Whether to enable web bridge (default: True).
    """
    self.gui = gui
    self.server_url = server_url
    self.machine_id = machine_id
    self.use_web = use_web
    self.web_bridge: Optional[Any] = None
    self.screenshot_timer: Optional[Any] = None
    self.screenshot_capture: Optional[Any] = None

Methods:

initialize

initialize() -> None

Initializes web GUI bridge for remote monitoring.

Sets up connection to web dashboard, collects system info, and starts the bridge. Errors are caught so GUI can continue without web monitoring.

Source code in goliat/gui/components/web_bridge_manager.py
def initialize(self) -> None:
    """Initializes web GUI bridge for remote monitoring.

    Sets up connection to web dashboard, collects system info, and starts
    the bridge. Errors are caught so GUI can continue without web monitoring.
    """
    if not self.use_web:
        # Web bridge disabled via config
        if hasattr(self.gui, "error_counter_label") and hasattr(self.gui, "status_manager"):
            self.gui._update_web_status(False)
        return

    if self.machine_id:
        try:
            from goliat.gui.components.system_monitor import SystemMonitor
            from goliat.utils.gui_bridge import WebGUIBridge

            self.web_bridge = WebGUIBridge(self.server_url, self.machine_id)

            # Collect system info
            gpu_name = SystemMonitor.get_gpu_name()
            cpu_cores = SystemMonitor.get_cpu_cores()
            total_ram_gb = SystemMonitor.get_total_ram_gb()
            hostname = socket.gethostname()

            system_info = {"gpuName": gpu_name or "N/A", "cpuCores": cpu_cores, "totalRamGB": total_ram_gb, "hostname": hostname}
            self.web_bridge.set_system_info(system_info)

            # Set callback to update GUI indicator BEFORE starting
            self.web_bridge.set_connection_callback(self.gui._update_web_status)
            # start() already sends initial heartbeat, no need to send again
            self.web_bridge.start()

            # Initialize screenshot capture
            self._initialize_screenshot_capture()

            self.gui.verbose_logger.info(f"Web GUI bridge enabled: {self.server_url}, machine_id={self.machine_id}")
            self.gui.verbose_logger.info(
                f"System info: GPU={gpu_name or 'N/A'}, CPU={cpu_cores} cores, RAM={total_ram_gb:.1f} GB, Hostname={hostname}"
            )
        except Exception as e:
            self.gui.verbose_logger.warning(f"Failed to initialize web GUI bridge: {e}. Continuing without web monitoring.")
            if hasattr(self.gui, "error_counter_label") and hasattr(self.gui, "status_manager"):
                self.gui._update_web_status(False)
    else:
        if hasattr(self.gui, "error_counter_label") and hasattr(self.gui, "status_manager"):
            self.gui._update_web_status(False)

sync_progress

sync_progress() -> None

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
def sync_progress(self) -> None:
    """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.
    """
    if self.web_bridge is None:
        return

    try:
        # Get actual progress bar values
        overall_value = self.gui.overall_progress_bar.value()
        overall_max = self.gui.overall_progress_bar.maximum()
        overall_progress = (overall_value / overall_max * 100) if overall_max > 0 else 0

        stage_value = self.gui.stage_progress_bar.value()
        stage_max = self.gui.stage_progress_bar.maximum()
        stage_progress = (stage_value / stage_max * 100) if stage_max > 0 else 0

        # Send overall progress
        if overall_progress > 0:
            self.web_bridge.enqueue({"type": "overall_progress", "current": overall_progress, "total": 100})

        # Send stage progress if we have a stage name
        if stage_progress > 0 and hasattr(self.gui, "stage_label"):
            stage_name = self.gui.stage_label.text().replace("Current Stage: ", "")
            if stage_name and stage_name != "Current Stage:":
                self.web_bridge.enqueue({"type": "stage_progress", "name": stage_name, "current": stage_progress, "total": 100})
    except Exception as e:
        # Don't let progress sync errors break the GUI
        if hasattr(self.gui, "verbose_logger"):
            self.gui.verbose_logger.debug(f"Failed to sync progress to web: {e}")

stop

stop() -> None

Stops the web bridge and screenshot capture.

Source code in goliat/gui/components/web_bridge_manager.py
def stop(self) -> None:
    """Stops the web bridge and screenshot capture."""
    # Stop screenshot timer
    if self.screenshot_timer is not None:
        try:
            self.screenshot_timer.stop()
        except Exception as e:
            if hasattr(self.gui, "verbose_logger"):
                self.gui.verbose_logger.warning(f"Error stopping screenshot timer: {e}")

    # Stop web bridge
    if self.web_bridge is not None:
        try:
            self.web_bridge.stop()
        except Exception as e:
            if hasattr(self.gui, "verbose_logger"):
                self.gui.verbose_logger.warning(f"Error stopping web bridge: {e}")

send_finished

send_finished(error: bool = False) -> None

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
def send_finished(self, error: bool = False) -> None:
    """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.

    Args:
        error: Whether study finished with errors.
    """
    # Stop screenshot timer first to prevent new screenshots from being queued
    if self.screenshot_timer is not None:
        try:
            self.screenshot_timer.stop()
        except Exception as e:
            if hasattr(self.gui, "verbose_logger"):
                self.gui.verbose_logger.warning(f"Error stopping screenshot timer: {e}")

    if self.web_bridge is not None:
        try:
            import time

            # Check if bridge is still running before sending messages
            if not self.web_bridge.running:
                # Bridge already stopped, just ensure screenshot timer is stopped
                return

            # Send multiple 100% progress updates with delays to ensure cloud receives them
            # Cloud is often lagging behind, so we send updates multiple times
            for i in range(5):  # Send 5 times to ensure at least one gets through
                # Check if bridge is still running before each enqueue
                if not self.web_bridge.running:
                    break
                self.web_bridge.enqueue({"type": "overall_progress", "current": 100, "total": 100})
                # Also send stage progress at 100% if we have a stage name
                if hasattr(self.gui, "stage_label"):
                    stage_name = self.gui.stage_label.text().replace("Current Stage: ", "")
                    if stage_name and stage_name != "Current Stage:":
                        self.web_bridge.enqueue({"type": "stage_progress", "name": stage_name, "current": 100, "total": 100})
                if i < 4:  # Don't sleep after the last iteration
                    time.sleep(0.5)  # 500ms delay between updates

            # Send finished message only if bridge is still running
            if self.web_bridge.running:
                self.web_bridge.enqueue(
                    {"type": "finished", "message": "Study finished successfully" if not error else "Study finished with errors"}
                )

                # Wait longer for final messages to send (cloud might be processing previous updates)
                time.sleep(3)  # Increased from 1s to 3s to give cloud more time

            # Stop the bridge (safe to call even if already stopped)
            self.web_bridge.stop()
        except Exception as e:
            if hasattr(self.gui, "verbose_logger"):
                self.gui.verbose_logger.warning(f"Error stopping web bridge: {e}")

Components / Plots

goliat.gui.components.plots._matplotlib_imports

Matplotlib imports with fallback handling for plotting components.

goliat.gui.components.plots.overall_progress_plot.OverallProgressPlot

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
def __init__(self) -> None:
    """Sets up matplotlib figure and axes with dark theme."""
    if Figure is None or FigureCanvas is None:
        raise ImportError("matplotlib is required for plotting")
    from matplotlib.axes import Axes as _Axes
    from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as _FigureCanvas
    from matplotlib.figure import Figure as _Figure

    self.figure: _Figure = _Figure(figsize=(10, 6), facecolor="#2b2b2b")
    self.canvas: _FigureCanvas = _FigureCanvas(self.figure)
    self.ax: _Axes = self.figure.add_subplot(111)
    self.data: List[Tuple[datetime, float]] = []
    self.max_progress_seen: float = 0.0
    self._setup()

Methods:

add_data_point

add_data_point(timestamp: datetime, progress_percent: float) -> None

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
def add_data_point(self, timestamp: datetime, progress_percent: float) -> None:
    """Adds data point and refreshes plot.

    Args:
        timestamp: Timestamp for the data point.
        progress_percent: Progress percentage as float.
    """
    if progress_percent > self.max_progress_seen:
        self.max_progress_seen = progress_percent
    # Convert timestamp to UTC+1
    utc_plus_one_timestamp = convert_to_utc_plus_one(timestamp)

    # Validate timestamp: reject if it's anomalously far from the last timestamp
    # This prevents spikes from corrupted timestamps (e.g., from NTP cache issues)
    if self.data and not validate_timestamp(utc_plus_one_timestamp, self.data[-1][0]):
        # Skip this data point - timestamp is anomalous
        return

    self.data.append((utc_plus_one_timestamp, progress_percent))
    self._refresh()

goliat.gui.components.plots.pie_charts_manager.PieChartsManager

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
def __init__(self) -> None:
    """Sets up matplotlib figure with 2x2 subplot grid."""
    if Figure is None or FigureCanvas is None:
        raise ImportError("matplotlib is required for plotting")
    from matplotlib.axes import Axes as _Axes
    from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as _FigureCanvas
    from matplotlib.figure import Figure as _Figure

    self.figure: _Figure = _Figure(figsize=(12, 10), facecolor="#2b2b2b")
    self.canvas: _FigureCanvas = _FigureCanvas(self.figure)
    self.axes: List[_Axes] = [
        self.figure.add_subplot(221),  # Top-left: Phase weights
        self.figure.add_subplot(222),  # Top-right: Setup subtasks
        self.figure.add_subplot(223),  # Bottom-left: Run subtasks
        self.figure.add_subplot(224),  # Bottom-right: Extract subtasks
    ]
    self._setup()

Methods:

update

update(profiler: Profiler