coconut_tools.magnetogram.sph_filtering

Utilities for generating and downloading magnetogram input files for COCONUT simulations.

This module supports the generation of COCONUT-compatible magnetic boundary files based on real solar data from various sources (e.g., WSO, GONG, ADAPT, HMI).

Main capabilities: - Construct output filenames and download magnetogram data using Sunpy or custom rules, - Build single-date or cadence-based time series configurations, - Download four-map stencils and temporally interpolate GONG/ADAPT magnetograms, - Handle spherical harmonic resolution (lmax), - Provide helper functions to parse timestamps and build mesh grids.

Used to prepare magnetic input for running COCONUT coronal MHD simulations.

Functions

append_timestamp_to_path(path, date)

Append a compact timestamp before a path extension.

build_gong_remote_dir(date[, file_id])

Build a GONG QR magnetogram directory URL for one day.

build_output_name(date, map_type, ...[, ...])

Build the COCONUT boundary filename for a target date.

build_processing_dates(start_date[, ...])

Build target dates from a start date, cadence, and total duration.

build_regular_theta_phi(Br, map_type)

Build the 1D theta/phi grids used by sph_filtering.

build_theta_phi(theta, phi)

Build 2D meshgrids from 1D theta and phi arrays.

circular_shift_longitude(Br, shift)

Apply a circular longitude shift to a magnetogram.

correct_net_flux(Br, theta)

Remove the surface-weighted mean Br from a magnetogram.

default_figure_path(output_dir, map_type, date)

Build a default diagnostic figure path for one target date.

download_candidate(candidate, output_dir)

Download one candidate if it is missing locally.

download_interpolation_magnetograms(date, ...)

Download the four magnetograms needed for temporal interpolation.

extract_gong_longitude_shift(file_path)

Extract the GONG longitude offset encoded in a filename.

fetch_remote_names(remote_dir, file_id)

List remote filenames from a GONG-style directory page.

format_timestamp(date)

Format a datetime as YYYYMMDDHHMMSS for output filenames.

generate_output_and_interpolation_map_names(...)

Generate output name and download four maps for temporal interpolation.

generate_output_and_map_names(date, ...[, ...])

Generate output filename and download magnetogram file based on map type.

interpolate_br_maps(Br_maps, selection[, ...])

Interpolate four Br maps in time.

list_adapt_candidates(date)

List ADAPT candidates around a target date.

list_gong_candidates(date)

List GONG candidates around a target date.

list_remote_candidates(date, map_type)

List remote temporal candidates for a map type.

parse_date_from_filename(name, fmt, split_token)

Parse date from filename using a given format and delimiter.

parse_iso_datetime(date)

Parse a date value into a datetime.

plot_maps(Br, Br_mode, theta, phi, map_type, ...)

Plot original and reconstructed Br maps.

process_config(config[, method_used])

Process one sph_filtering configuration.

process_magnetogram_date(config, target_date)

Process one target date from a sph_filtering configuration.

project_and_reconstruct(Br, Theta, Phi, lmax)

Project Br on spherical harmonics and reconstruct Br_mode.

read_interpolated_magnetogram(local_files, ...)

Read and temporally interpolate a four-map magnetogram stencil.

read_magnetogram(file_path, map_type[, ...])

Read magnetic field map file and extract Br, Theta, Phi grids.

read_temporal_br_map(file_path, map_type[, ...])

Read one FITS magnetogram for temporal interpolation.

select_interpolation_stencil(candidates, ...)

Select four magnetograms around a target date for Hermite interpolation.

select_nearest_candidate(candidates, target_date)

Select the candidate closest to a target date.

spherical_harmonic(m, l, Phi, Theta)

Evaluate spherical harmonics across SciPy versions.

unique_sorted_candidates(candidates)

Sort candidates and keep one entry per timestamp.

write_bc_file(output_name, Br_mode, theta, ...)

Write boundary condition file.

Classes

InterpolationSelection(before_previous, ...)

Four-map temporal interpolation stencil and its time weights.

MagnetogramCandidate(name, date, remote_url)

Remote magnetogram candidate with an observation timestamp.

class coconut_tools.magnetogram.sph_filtering.InterpolationSelection(before_previous, before, after, after_next, coef_before, coef_after, interval_seconds, previous_interval_seconds, next_interval_seconds, target_date)[source]

Bases: object

Four-map temporal interpolation stencil and its time weights.

Parameters:
after: MagnetogramCandidate
after_next: MagnetogramCandidate
before: MagnetogramCandidate
before_previous: MagnetogramCandidate
coef_after: float
coef_before: float
interval_seconds: float
next_interval_seconds: float
previous_interval_seconds: float
target_date: datetime
class coconut_tools.magnetogram.sph_filtering.MagnetogramCandidate(name, date, remote_url)[source]

Bases: object

Remote magnetogram candidate with an observation timestamp.

Parameters:
  • name (str)

  • date (datetime)

  • remote_url (str)

date: datetime
name: str
remote_url: str
coconut_tools.magnetogram.sph_filtering.append_timestamp_to_path(path, date)[source]

Append a compact timestamp before a path extension.

Return type:

str

Parameters:
  • path (str)

  • date (str | datetime)

coconut_tools.magnetogram.sph_filtering.build_gong_remote_dir(date, file_id='mrzqs')[source]

Build a GONG QR magnetogram directory URL for one day.

Parameters:
  • date (datetime) – Day to list.

  • file_id (str) – GONG file identifier.

Returns:

Remote directory URL.

Return type:

str

coconut_tools.magnetogram.sph_filtering.build_output_name(date, map_type, output_dir, lmax, method_used='sph')[source]

Build the COCONUT boundary filename for a target date.

Parameters:
  • date (str | datetime) – Target date.

  • map_type (str) – Map type.

  • output_dir (str) – Directory for the boundary file.

  • lmax (int | None) – Maximum spherical harmonic degree.

  • method_used (str) – Method label included in the output stem.

Returns:

Output filename ending with _YYYYMMDDHHMMSS.dat.

Return type:

str

coconut_tools.magnetogram.sph_filtering.build_processing_dates(start_date, cadence_hours=None, total_hours=None)[source]

Build target dates from a start date, cadence, and total duration.

Parameters:
  • start_date (str | datetime) – First target date.

  • cadence_hours (float | None) – Cadence in hours.

  • total_hours (float | None) – Total duration in hours. If None, one date is returned.

Returns:

Target dates to process.

Return type:

list[datetime]

coconut_tools.magnetogram.sph_filtering.build_regular_theta_phi(Br, map_type)[source]

Build the 1D theta/phi grids used by sph_filtering.

Parameters:
  • Br (np.ndarray) – Magnetic field map.

  • map_type (str) – Map type.

Returns:

Theta and phi vectors.

Return type:

tuple[np.ndarray, np.ndarray]

coconut_tools.magnetogram.sph_filtering.build_theta_phi(theta, phi)[source]

Build 2D meshgrids from 1D theta and phi arrays.

Parameters:
  • theta (ndarray) – 1D array of theta values (colatitude).

  • phi (ndarray) – 1D array of phi values (longitude).

Returns:

(Theta, Phi) meshgrids.

Return type:

tuple

coconut_tools.magnetogram.sph_filtering.circular_shift_longitude(Br, shift)[source]

Apply a circular longitude shift to a magnetogram.

Parameters:
  • Br (np.ndarray) – Magnetic field map.

  • shift (int) – Number of longitude cells to shift right.

Returns:

Shifted magnetic field map.

Return type:

np.ndarray

coconut_tools.magnetogram.sph_filtering.correct_net_flux(Br, theta)[source]

Remove the surface-weighted mean Br from a magnetogram.

Parameters:
  • Br (np.ndarray) – Radial magnetic field map.

  • theta (np.ndarray) – 1D colatitude grid in radians.

Returns:

Flux-balanced Br map.

Return type:

np.ndarray

coconut_tools.magnetogram.sph_filtering.default_figure_path(output_dir, map_type, date)[source]

Build a default diagnostic figure path for one target date.

Return type:

str

Parameters:
  • output_dir (str)

  • map_type (str)

  • date (str | datetime)

coconut_tools.magnetogram.sph_filtering.download_candidate(candidate, output_dir)[source]

Download one candidate if it is missing locally.

Parameters:
  • candidate (MagnetogramCandidate) – Remote candidate.

  • output_dir (str) – Local download directory.

Returns:

Local file path.

Return type:

str

coconut_tools.magnetogram.sph_filtering.download_interpolation_magnetograms(date, map_type, output_dir)[source]

Download the four magnetograms needed for temporal interpolation.

Parameters:
  • date (str | datetime) – Target interpolation date.

  • map_type (str) – Map type. Supported: GONG, ADAPT.

  • output_dir (str) – Local download directory.

Returns:

Local files in stencil order and selection.

Return type:

tuple[list[str], InterpolationSelection]

coconut_tools.magnetogram.sph_filtering.extract_gong_longitude_shift(file_path)[source]

Extract the GONG longitude offset encoded in a filename.

Parameters:

file_path (str) – Local GONG filename or path.

Returns:

Number of longitude cells used for circular shifting.

Return type:

int

coconut_tools.magnetogram.sph_filtering.fetch_remote_names(remote_dir, file_id)[source]

List remote filenames from a GONG-style directory page.

Parameters:
  • remote_dir (str) – Remote directory URL.

  • file_id (str) – Filename token to keep.

Returns:

Matching filenames.

Return type:

list[str]

coconut_tools.magnetogram.sph_filtering.format_timestamp(date)[source]

Format a datetime as YYYYMMDDHHMMSS for output filenames.

Parameters:

date (str | datetime) – Date to format.

Returns:

Compact timestamp.

Return type:

str

coconut_tools.magnetogram.sph_filtering.generate_output_and_interpolation_map_names(date, map_type, output_dir, lmax, method_used='sph', download_dir=None)[source]

Generate output name and download four maps for temporal interpolation.

Parameters:
  • date (str | datetime) – Target date.

  • map_type (str) – Map type. Supported: GONG, ADAPT.

  • output_dir (str) – Directory for the boundary file.

  • lmax (int | None) – Maximum spherical harmonic degree.

  • method_used (str) – Method label kept for compatibility.

  • download_dir (str | None) – Directory for downloaded FITS files.

Returns:

Output name, files, selection.

Return type:

tuple[str, list[str], InterpolationSelection]

coconut_tools.magnetogram.sph_filtering.generate_output_and_map_names(date, map_type, output_dir, lmax, method_used='sph')[source]

Generate output filename and download magnetogram file based on map type.

Parameters:
  • date (str) – Date string in ISO format (e.g., ‘2020-12-07T15:00:00’).

  • map_type (str) – Map type (‘WSO’, ‘GONG’, ‘ADAPT’, ‘HMI’).

  • output_dir (str) – Directory to store output file.

  • lmax (int) – Spherical harmonic maximum degree.

  • method_used (str) – method used for filtering ( e.g NLD )

Returns:

(output_name (str), local_file (str))

Return type:

tuple

coconut_tools.magnetogram.sph_filtering.interpolate_br_maps(Br_maps, selection, interpolation_order=2)[source]

Interpolate four Br maps in time.

Parameters:
  • Br_maps (list[np.ndarray]) – Maps ordered as before-previous, before, after, after-next.

  • selection (InterpolationSelection) – Time stencil and weights.

  • interpolation_order (int) – 1 for linear, 2 for cubic Hermite.

Returns:

Interpolated Br and linear interpolation.

Return type:

tuple[np.ndarray, np.ndarray]

coconut_tools.magnetogram.sph_filtering.list_adapt_candidates(date)[source]

List ADAPT candidates around a target date.

Parameters:

date (str | datetime) – Target date.

Returns:

Sorted unique candidates.

Return type:

list[MagnetogramCandidate]

coconut_tools.magnetogram.sph_filtering.list_gong_candidates(date)[source]

List GONG candidates around a target date.

The previous, current, and next UTC days are queried so a four-map stencil can cross midnight.

Parameters:

date (str | datetime) – Target date.

Returns:

Sorted unique candidates.

Return type:

list[MagnetogramCandidate]

coconut_tools.magnetogram.sph_filtering.list_remote_candidates(date, map_type)[source]

List remote temporal candidates for a map type.

Parameters:
  • date (str | datetime) – Target date.

  • map_type (str) – Map type.

Returns:

Sorted candidates.

Return type:

list[MagnetogramCandidate]

coconut_tools.magnetogram.sph_filtering.parse_date_from_filename(name, fmt, split_token)[source]

Parse date from filename using a given format and delimiter.

Parameters:
  • name (str) – Filename.

  • fmt (str) – Format string to parse the date.

  • split_token (str) – Token to split the filename before parsing.

Returns:

Parsed datetime object.

Return type:

datetime

coconut_tools.magnetogram.sph_filtering.parse_iso_datetime(date)[source]

Parse a date value into a datetime.

Parameters:

date (str | datetime) – ISO datetime string or datetime object.

Returns:

Parsed datetime.

Return type:

datetime

coconut_tools.magnetogram.sph_filtering.plot_maps(Br, Br_mode, theta, phi, map_type, visu_type, output_path='output_map.png', date=None)[source]

Plot original and reconstructed Br maps.

Parameters:
  • Br (ndarray) – Original radial magnetic field.

  • Br_mode (ndarray) – Reconstructed radial magnetic field.

  • theta (ndarray) – 1D theta grid.

  • phi (ndarray) – 1D phi grid.

  • map_type (str) – Type of the input map (‘WSO’, ‘GONG’, etc.).

  • visu_type (str) – Visualization style (‘lat’ or ‘sinlat’).

  • lat_type (str, optional) – Latitude type for WSO (‘lat’ or ‘sinlat’).

  • output_path (str) – Path where the figure will be saved.

  • date (str | datetime, optional) – Processed date to display on the figure.

coconut_tools.magnetogram.sph_filtering.process_config(config, method_used='sph')[source]

Process one sph_filtering configuration.

The configuration keeps the existing keys and adds optional multi-date processing.

Config keys:

date: Initial ISO datetime. cadence_hours: Cadence in hours. total_hours: Total duration in hours. interpolation: Use four-map interpolation for GONG/ADAPT. flux_correct: Remove net magnetic flux if True.

Parameters:
  • config (dict[str, Any]) – Processing configuration.

  • method_used (str) – Method label kept for compatibility.

Returns:

Per-date processing results.

Return type:

list[dict[str, Any]]

coconut_tools.magnetogram.sph_filtering.process_magnetogram_date(config, target_date, method_used='sph', output_path_fig=None)[source]

Process one target date from a sph_filtering configuration.

Parameters:
  • config (dict[str, Any]) – Processing configuration.

  • target_date (str | datetime) – Date to process.

  • method_used (str) – Method label kept for compatibility.

  • output_path_fig (str | None) – Diagnostic figure path.

Returns:

Paths and processing metadata.

Return type:

dict[str, Any]

coconut_tools.magnetogram.sph_filtering.project_and_reconstruct(Br, Theta, Phi, lmax, amp=1, alpha=0)[source]

Project Br on spherical harmonics and reconstruct Br_mode.

Parameters:
  • Br (ndarray) – Original radial field.

  • Theta (ndarray) – Colatitude grid.

  • Phi (ndarray) – Longitude grid.

  • lmax (int) – Maximum spherical harmonic degree.

  • amp (float) – Amplitude factor for reconstruction.

  • alpha (float) – Enhances the filtering for higher frequencies.

Returns:

(Br_mode, coefbr)

Return type:

tuple

coconut_tools.magnetogram.sph_filtering.read_interpolated_magnetogram(local_files, map_type, selection, adapt_map=0, interpolation_order=2)[source]

Read and temporally interpolate a four-map magnetogram stencil.

Parameters:
  • local_files (list[str]) – Local files in stencil order.

  • map_type (str) – Map type. Supported: GONG, ADAPT.

  • selection (InterpolationSelection) – Time interpolation metadata.

  • adapt_map (int) – ADAPT realization index.

  • interpolation_order (int) – 1 for linear, 2 for cubic Hermite.

Returns:

Br, Theta, Phi, Br_linear.

Return type:

tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]

coconut_tools.magnetogram.sph_filtering.read_magnetogram(file_path, map_type, adapt_map=0)[source]

Read magnetic field map file and extract Br, Theta, Phi grids.

Parameters:
  • file_path (str) – Path to the magnetogram file.

  • map_type (str) – Type of the map (‘WSO’, ‘GONG’, ‘ADAPT’, ‘HMI_small’, ‘HMI_pofil’).

  • adapt_map (int, optional) – Index for ADAPT map. Defaults to 0.

Returns:

(Br_map, Theta, Phi) arrays.

Return type:

tuple

coconut_tools.magnetogram.sph_filtering.read_temporal_br_map(file_path, map_type, adapt_map=0)[source]

Read one FITS magnetogram for temporal interpolation.

Parameters:
  • file_path (str) – Local FITS file.

  • map_type (str) – Map type. Supported: GONG, ADAPT.

  • adapt_map (int) – ADAPT realization index.

Returns:

Radial magnetic field map.

Return type:

np.ndarray

coconut_tools.magnetogram.sph_filtering.select_interpolation_stencil(candidates, target_date)[source]

Select four magnetograms around a target date for Hermite interpolation.

Parameters:
  • candidates (list[MagnetogramCandidate]) – Sorted remote candidates.

  • target_date (str | datetime) – Target interpolation date.

Returns:

Four-map stencil and coefficients.

Return type:

InterpolationSelection

coconut_tools.magnetogram.sph_filtering.select_nearest_candidate(candidates, target_date)[source]

Select the candidate closest to a target date.

Return type:

MagnetogramCandidate

Parameters:
coconut_tools.magnetogram.sph_filtering.spherical_harmonic(m, l, Phi, Theta)[source]

Evaluate spherical harmonics across SciPy versions.

Parameters:
  • m (int) – Harmonic order.

  • l (int) – Harmonic degree.

  • Phi (ndarray) – Longitude grid.

  • Theta (ndarray) – Colatitude grid.

Returns:

Complex spherical harmonic values.

Return type:

ndarray

coconut_tools.magnetogram.sph_filtering.unique_sorted_candidates(candidates)[source]

Sort candidates and keep one entry per timestamp.

Return type:

list[MagnetogramCandidate]

Parameters:

candidates (list[MagnetogramCandidate])

coconut_tools.magnetogram.sph_filtering.write_bc_file(output_name, Br_mode, theta, phi, r_st)[source]

Write boundary condition file.

Parameters:
  • output_name (str) – Path to output file.

  • Br_mode (ndarray) – Reconstructed radial field.

  • theta (ndarray) – 1D theta grid.

  • phi (ndarray) – 1D phi grid.

  • r_st (float) – Spherical radius.