Utilities¶
Internal helpers used by runners, timing export, and logging. Most users interact
with these indirectly via run_* and preset dicts; the entries below are for
custom workflows and debugging.
Parameter resolution¶
Helper functions for running SCGO campaigns.
This module provides utility functions used by the high-level API in scgo.runner_api to eliminate code duplication and improve maintainability.
- scgo.utils.run_helpers.initialize_params(params)[source]¶
Initialize and merge params with defaults.
Handles None check and deep merge with default parameters.
- scgo.utils.run_helpers.initialize_ts_params(ts_params, *, system_type, surface_config=None, go_params=None)[source]¶
Initialize and merge TS params with
get_ts_search_params()defaults.When
go_paramsis provided, calculator settings are aligned with the merged GO dict unless overridden ints_params.
- scgo.utils.run_helpers.diff_param_overrides(base, merged, *, prefix='')[source]¶
Return flat
path -> valueentries wheremergeddiffers frombase.
- scgo.utils.run_helpers.log_params_resolution(context, *, source_label, user_params, merged, base, verbosity)[source]¶
Log how user params were merged onto preset defaults.
- Return type:
- scgo.utils.run_helpers.get_calculator_class(calculator_name)[source]¶
Get calculator class by name.
- Parameters:
calculator_name (
str) – Name of the calculator (e.g., “MACE”, “EMT”).- Return type:
- Returns:
Calculator class.
- Raises:
ValueError – If calculator name is unknown or not available.
- scgo.utils.run_helpers.validate_algorithm_params(algo_params, chosen_go, verbosity)[source]¶
Validate algorithm-specific parameters.
- scgo.utils.run_helpers.resolve_auto_params(algo_params, composition, chosen_go)[source]¶
Resolve ‘auto’ parameter values.
- scgo.utils.run_helpers.resolve_diversity_params(algo_params, params, chosen_go)[source]¶
Resolve diversity parameters for fitness strategy.
Extracts diversity parameters from algorithm-specific params or top-level params, with algorithm-specific taking precedence. Raises ValueError if required diversity_reference_db is missing.
- Parameters:
- Returns:
diversity_reference_db (required)
diversity_max_references (default: 100)
diversity_update_interval (default: 5)
- Return type:
- Raises:
ValueError – If diversity_reference_db is not provided.
- scgo.utils.run_helpers.prepare_algorithm_kwargs(algo_params, params, composition, chosen_go, *, system_type)[source]¶
Unified parameter preparation for algorithm execution.
Resolves “auto” parameter values, converts optimizer string names to classes, resolves fitness strategy, and filters out top-level keys that shouldn’t be passed to algorithms.
- Parameters:
- Return type:
- Returns:
Dictionary ready for direct algorithm execution.
- scgo.utils.run_helpers.log_ts_configuration(ts_params, coerced_kwargs, *, verbosity, user_params=None, base=None)[source]¶
Log resolved transition-state search configuration.
- Return type:
- scgo.utils.run_helpers.log_configuration(params, chosen_go, cluster_formula, n_atoms, global_optimizer_kwargs, verbosity, *, user_params=None, params_base=None)[source]¶
Log final configuration.
- Parameters:
chosen_go (
str) – Name of chosen algorithm.cluster_formula (
str) – Chemical formula string.n_atoms (
int) – Number of atoms.global_optimizer_kwargs (
dict[str,Any]) – Resolved algorithm parameters.verbosity (
int) – Logging verbosity level.user_params (
dict[str,Any] |None) – Original user dict before merge (for provenance logging).params_base (
dict[str,Any] |None) – Base defaults used for merge (defaults toget_default_params()).
- Return type:
Config aliases¶
Helpers for aliased dataclass construction kwargs.
Combine atoms¶
Shared Atoms combine / surface-geometry helpers.
- scgo.utils.combine_atoms.concatenate_inherit_cell_pbc(base, mobile)[source]¶
Concatenate
basethenmobile; inherit cell and PBC frombase.- Return type:
Atoms
- scgo.utils.combine_atoms.random_rotation_matrix(rng)[source]¶
Uniform random rotation (Haar on SO(3)) via random quaternion.
- Return type:
ndarray
Logging¶
Root logging setup, verbosity levels, and TRACE support for SCGO.
- scgo.utils.logging.get_logger(name)[source]¶
Return a logger for
name(typically__name__).- Return type:
- scgo.utils.logging.configure_logging(verbosity=1, format_string=None, hpc_mode=None)[source]¶
Configure the root logger for the SCGO package.
SCGO targets HPC batch jobs: by default third-party loggers are suppressed aggressively. Set environment variable
SCGO_LOCAL_DEV=1to use milder suppression whenhpc_modeis omitted, or passhpc_mode=Falseexplicitly.- Parameters:
verbosity (
int) – Verbosity level (0=quiet, 1=normal, 2=debug, 3=trace).format_string (
str|None) – Custom format string. If None, uses default format.hpc_mode (
bool|None) – If True, suppresses more third-party logs (default when None, unlessSCGO_LOCAL_DEV=1). If False, only WARNING+ for most libs.
- Return type:
- scgo.utils.logging.should_show_progress(verbosity)[source]¶
True when verbosity >= 1 (progress bars enabled for normal+).
- Return type:
- scgo.utils.logging.log_debug_v(logger, message, *args, verbosity=1, min_verbosity=2)[source]¶
Log debug message if verbosity >= min_verbosity (default 2).
Uses lazy %-style formatting. Message is only formatted if it will be logged.
- scgo.utils.logging.log_info_v(logger, message, *args, verbosity=1, min_verbosity=1)[source]¶
Log info message if verbosity >= min_verbosity (default 1).
Uses lazy %-style formatting. Message is only formatted if it will be logged.
- scgo.utils.logging.log_warning_v(logger, message, *args, verbosity=1, min_verbosity=1)[source]¶
Log warning message if verbosity >= min_verbosity (default 1).
Warnings are typically always shown, but this allows conditional suppression.
- scgo.utils.logging.log_error_v(logger, message, *args, verbosity=0, min_verbosity=0)[source]¶
Log error message if verbosity >= min_verbosity (default 0).
Errors are typically always shown, but this allows conditional suppression.
- scgo.utils.logging.log_exception_v(logger, message, *args, verbosity=1, min_verbosity=1, min_verbosity_for_traceback=2)[source]¶
Log exception with traceback if verbosity >= min_verbosity_for_traceback.
For unexpected errors, use logger.exception() directly instead. This helper is for handled exceptions where you want conditional traceback.
- Parameters:
logger (
Logger) – The logger instance.message (
str) – Format string for the message.*args (
object) – Arguments for the format string.verbosity (
int) – Current verbosity level (0-3).min_verbosity (
int) – Minimum verbosity to log error (default 1).min_verbosity_for_traceback (
int) – Minimum verbosity for traceback (default 2).
- Return type:
Phase logging¶
Phase-oriented logging helpers for SCGO runs (headers, summaries, collectors).
- scgo.utils.phase_logging.infer_verbosity(logger, explicit=None)[source]¶
Map an explicit verbosity or infer from the configured logger level.
- Return type:
- scgo.utils.phase_logging.log_phase_header(logger, title, *, verbosity, level=1)[source]¶
Emit a visible phase banner when
verbosity >= level.- Return type:
- scgo.utils.phase_logging.log_phase_subheader(logger, title, *, verbosity, level=1)[source]¶
Emit a lighter sub-phase banner (e.g. per generation).
- Return type:
- scgo.utils.phase_logging.format_count_summary(counts)[source]¶
Format outcome counts as
label×N, ....- Return type:
- class scgo.utils.phase_logging.InitDiagnosticsCollector[source]¶
Bases:
objectThread-safe accumulator for initialization fallbacks and placement failures.
Run directories and metadata¶
Run tracking and metadata management for SCGO campaigns.
This module provides functions for generating run IDs, saving and loading run metadata, and managing run-specific directory structures.
- class scgo.utils.run_tracking.RunMetadataJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]¶
Bases:
JSONEncoderJSON encoder:
typeobjects become their__name__(for params snapshots).- default(obj)[source]¶
Implement this method in a subclass such that it returns a serializable object for
o, or calls the base implementation (to raise aTypeError).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return super().default(o)
- Return type:
- class scgo.utils.run_tracking.RunMetadata(run_id, timestamp, composition=None, formula=None, params=None)[source]¶
Bases:
objectMetadata for a single run.
- scgo.utils.run_tracking.generate_run_id()[source]¶
Generate timestamp-based run ID with microsecond granularity.
- Returns:
run_YYYYMMDD_HHMMSS_ffffff Example: “run_20250124_143022_123456”
- Return type:
- scgo.utils.run_tracking.ensure_run_id(run_id, verbosity=0, logger=None)[source]¶
Ensure a run_id exists, generating one if needed and logging if appropriate.
This helper consolidates the common pattern of generating a run_id if None and logging it when verbosity is sufficient.
- scgo.utils.run_tracking.save_run_metadata(run_dir, run_id, metadata=None)[source]¶
Save run metadata to metadata.json file.
- scgo.utils.run_tracking.load_run_metadata(run_dir)[source]¶
Load run metadata from metadata.json file.
- Parameters:
run_dir (
str) – Directory containing metadata.json file.- Return type:
- Returns:
RunMetadata object if metadata file exists and is valid, None otherwise.
- scgo.utils.run_tracking.get_run_directories(base_output_dir)[source]¶
Get list of all run directories in base output directory.
Timing JSON¶
Timing summary logging and timing.json for GO, basin hopping, NEB/TS, and GO+TS.
GA/BH: set write_timing_json and detailed_timing in
optimizer_params['ga'] (or bh) inside params/go_params.
TS: set write_timing_json in ts_params.
GO timing is written at run level: {run_dir}/timing.json (alongside
metadata.json and the optimizer database).
GO+TS pipeline rollup timing is written at the campaign root as
go_ts_timing.json when write_timing_json=True in go_params and/or
ts_params.
- scgo.utils.timing_report.ga_relax_seconds_from_timings(timings)[source]¶
Total MLIP relax wall time for TorchSim GA (initial + offspring batches).
- Return type:
- scgo.utils.timing_report.relax_seconds_from_timings(timings)[source]¶
Return total relax/NEB wall time inferred from a timing payload.
- Return type:
- scgo.utils.timing_report.cpu_non_relax_seconds_from_timings(timings)[source]¶
Return non-relax CPU wall time (precomputed or total minus relax).
- Return type:
- scgo.utils.timing_report.log_timing_summary(logger, backend, timings_s, *, verbosity)[source]¶
Log a one-line timing summary when
verbosity >= 1.- Return type:
- scgo.utils.timing_report.write_timing_file(output_dir, payload, *, filename=None)[source]¶
- Return type:
- scgo.utils.timing_report.read_timing_file(path)[source]¶
Load a timing JSON file; return
Noneif missing or unreadable.
- scgo.utils.timing_report.load_run_timing_payload(run_dir)[source]¶
Load
timing.jsonfrom a run directory.
- scgo.utils.timing_report.flatten_run_timing_payload(payload)[source]¶
Return a flat timing payload (legacy multi-trial documents are rejected).
- scgo.utils.timing_report.build_timing_payload(*, backend, timings_s, run_id=None, extra=None)[source]¶
Build a structured timing document with provenance header and schema version.
- scgo.utils.timing_report.build_run_timing_document(*, run_id, payload)[source]¶
Attach run_id to a single-run timing payload.
Output path helpers¶
Campaign output directory layout for global optimization and TS search.
- scgo.utils.output_paths.formula_searches_dir(root, formula)[source]¶
Return
{root}/{formula}_searches.- Return type:
- scgo.utils.output_paths.formula_ts_results_dir(root, formula)[source]¶
Return
{root}/{formula}_ts_results.- Return type:
- scgo.utils.output_paths.resolve_campaign_root(output_dir)[source]¶
Resolve campaign root from
output_dir.When
output_dirisNone, use the current working directory. Whenoutput_dirends with_searches, use its parent as the campaign root. Otherwise treatoutput_diras the campaign root.- Return type:
- scgo.utils.output_paths.resolve_minima_dir(campaign_root, formula, *, searches_dir=None)[source]¶
Return the directory containing GO
run_*/minima databases.When
searches_diris provided, minima are read from that path.- Return type:
- scgo.utils.output_paths.resolve_ts_campaign_paths(output_dir, path_key_formula, *, searches_dir=None)[source]¶
Return
(campaign_root, minima_dir, ts_results_root)for TS search.path_key_formulais the cluster/mobile formula used for sibling{formula}_searchesand{formula}_ts_resultsdirectory names (without slab symbols for surface runs).
- scgo.utils.output_paths.resolve_go_searches_dir(output_dir, formula)[source]¶
Return the GO
{formula}_searches/directory forrun_go.When
output_diris provided, it is the searches directory itself. Whenoutput_dirisNone, use{formula}_searchesunder CWD.- Return type: