coconut_tools.magnetogram.sph_filtering¶
Read, preprocess, filter, write, and plot magnetogram boundary maps.
This module implements the spherical-harmonic preprocessing pipeline used to
turn photospheric magnetograms into COCONUT boundary-condition files. Download
and remote-candidate selection are delegated to
coconut_tools.magnetogram.magnetogram_download; this file handles local map
reading, latitude/longitude normalization, optional temporal interpolation,
optional Carrington-to-Stonyhurst rotation, optional flux balancing, spherical
harmonic projection/reconstruction, diagnostics, and figure generation.
Date handling follows the common magnetogram “effective time” convention: interpolated GONG/ADAPT maps represent the requested target time, HMI small, HMI polar-filled, and WSO use the target time by convention, and non-interpolated GONG/ADAPT/HMI_SYNC maps use the timestamp encoded in the selected filename.
Functions
|
Apply the configured Carrington-to-Stonyhurst longitude rotation. |
|
Build regular colatitude and longitude grids for a processed Br map. |
|
Build 2D meshgrids from 1D theta and phi arrays. |
|
Apply a circular longitude shift to a magnetogram. |
|
Find the longitude column closest to a periodic target angle. |
|
Reduce or remove net magnetic flux from a magnetogram. |
|
Return Br with columns ordered by increasing native longitude. |
|
Extract the GONG longitude offset encoded in a filename. |
|
Interpolate a four-map temporal stencil onto the target time. |
|
Save a two-panel diagnostic figure for input and processed Br maps. |
|
Process all target times described by one sph_filtering configuration. |
|
Process one target time through the spherical-harmonic pipeline. |
|
Return longitude cell centers matching the processed Br column order. |
|
Project Br onto spherical harmonics and reconstruct the filtered map. |
|
Read the first FITS HDU that contains at least a 2D image array. |
|
Read, normalize, and temporally interpolate a four-map stencil. |
|
Read one non-interpolated magnetogram and build its spherical grid. |
|
Read and normalize one FITS magnetogram used in interpolation. |
|
Resize a Br map to the standard 360x720 grid when requested. |
|
Resize a processed longitude axis while preserving its original origin. |
|
Roll an increasing-longitude map into the requested Stonyhurst frame. |
|
Evaluate spherical harmonics across SciPy versions. |
|
Write a COCONUT photospheric boundary-condition file. |
- coconut_tools.magnetogram.sph_filtering.apply_configured_longitude_rotation(Br, Br_linear, local_file, map_type, target_date, use_interpolation, rotate_to_stonyhurst, effective_date=None, resize=False)[source]¶
Apply the configured Carrington-to-Stonyhurst longitude rotation.
The rotation date is the magnetogram effective time. For interpolated GONG/ADAPT products this is the requested target time because the final map is synthesized at that time. For non-interpolated products it is either the timestamp encoded in the selected filename or the product convention returned by
magnetogram_effective_date.- Parameters:
Br (np.ndarray) – Processed radial field map.
Br_linear (np.ndarray | None) – Linear interpolation reference map, when available. It is rotated with the same shift as
Br.local_file (str | list[str]) – Source magnetogram path, or the interpolation stencil paths.
map_type (str) – Magnetogram product type.
target_date (str | datetime) – Requested processing time.
use_interpolation (bool) – Whether temporal interpolation was requested.
rotate_to_stonyhurst (bool) – If false, maps are returned unchanged.
effective_date (str | datetime | None) – Precomputed effective time. If omitted, it is derived from the source file and map type.
resize (bool) – Whether
Brwas resized after reading. When false, the original processed longitude axis is used unchanged.
- Returns:
Rotated
Br, rotatedBr_linearif present, and rotation angle in degrees. The angle isNonewhen rotation is disabled.- Return type:
- coconut_tools.magnetogram.sph_filtering.build_regular_theta_phi(Br, map_type)[source]¶
Build regular colatitude and longitude grids for a processed Br map.
ADAPT maps are represented on a regular colatitude grid. Other supported FITS maps are represented on a regular sine-latitude grid converted to colatitude. Longitudes are endpoint-free in [0, 2*pi).
- Parameters:
Br (np.ndarray) – Magnetic field map.
map_type (str) – Map type.
- Returns:
One-dimensional colatitude
thetaand longitudephivectors in radians.- 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.closest_longitude_column(longitude, target_degrees)[source]¶
Find the longitude column closest to a periodic target angle.
- Parameters:
longitude (np.ndarray) – Longitude cell centers in degrees.
target_degrees (float) – Target longitude in degrees.
- Returns:
Index of the closest column and signed residual in degrees, wrapped into [-180, 180).
- Return type:
tuple[int, float]
- coconut_tools.magnetogram.sph_filtering.correct_net_flux(Br, theta, phi=None, method='surface_mean')[source]¶
Reduce or remove net magnetic flux from a magnetogram.
surface_meansubtracts the surface-weighted mean Br. This is simple and preserves local contrast, but it shifts every pixel by the same offset.polarity_scalingrescales positive and negative polarities by opposite factors so the integrated positive and negative fluxes balance.- Parameters:
Br (np.ndarray) – Radial magnetic field map.
theta (np.ndarray) – 1D colatitude grid in radians.
phi (np.ndarray | None) – 1D longitude grid in radians. Required for exact pixel areas with polarity balancing. If omitted, a regular endpoint-free longitude grid is assumed.
method (str) – Flux correction method.
surface_meansubtracts the surface-weighted mean Br.polarity_scalingrescales positive and negative polarities by opposite multiplicative factors.
- Returns:
Flux-balanced Br map.
- Return type:
np.ndarray
- coconut_tools.magnetogram.sph_filtering.ensure_increasing_longitude(Br, file_path, map_type)[source]¶
Return Br with columns ordered by increasing native longitude.
FITS WCS keywords are used for products whose longitude direction can be read from the header. WSO text maps are left unchanged. HMI maps are kept as read because the current pipeline treats their FITS products as already increasing in longitude.
- Return type:
ndarray- Parameters:
Br (ndarray)
file_path (str)
map_type (str)
- 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.interpolate_br_maps(Br_maps, selection, interpolation_order=2)[source]¶
Interpolate a four-map temporal stencil onto the target time.
interpolation_order=1returns the linear interpolation between the two bracketing maps.interpolation_order=2uses a cubic Hermite estimate based on the before-previous, before, after, and after-next maps. In both cases the second returned array is the linear reference map used for diagnostics.- 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 Br reference.
- Return type:
tuple[np.ndarray, np.ndarray]
- coconut_tools.magnetogram.sph_filtering.plot_maps(Br, Br_mode, theta, phi, map_type, visu_type, output_path='output_map.png', date=None)[source]¶
Save a two-panel diagnostic figure for input and processed Br maps.
The upper panel shows the pre-filtered/pre-projection Br map after all configured preprocessing. The lower panel shows the processed map that is written to the boundary file. The displayed date should be the magnetogram effective time.
- Parameters:
Br (ndarray) – Original radial magnetic field.
Br_mode (ndarray) – Reconstructed radial magnetic field.
theta (ndarray) – 1D colatitude grid in radians.
phi (ndarray) – 1D longitude grid in radians.
map_type (str) – Type of the input map (‘WSO’, ‘GONG’, etc.).
visu_type (str) – Visualization style (‘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 all target times described by one sph_filtering configuration.
With only
dateset, a single target time is processed. Withcadence_hoursandtotal_hours, the function builds a sequence of target times starting atdateand processes each one independently. When no explicitoutput_path_figis provided, each figure is named from the effective magnetogram time.- Config keys:
date: Initial ISO datetime. cadence_hours: Cadence in hours. total_hours: Total duration in hours. interpolation: Use four-map interpolation for temporal GONG variants
and ADAPT.
rotate_to_stonyhurst: Rotate longitude to the Stonyhurst frame. Defaults to True. flux_correct: Remove net magnetic flux if True. flux_correction_method:
surface_meanorpolarity_scaling. output_path_fig: Optional figure file or directory.
- Parameters:
config (dict[str, Any]) – Processing configuration.
method_used (str) – Method label used in output filenames.
- 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 time through the spherical-harmonic pipeline.
The function downloads or reuses the requested magnetogram, optionally builds a temporal interpolation, computes the product effective time, logs the target/effective timing, optionally rotates the map to Stonyhurst, optionally balances net flux, projects/reconstructs the map with spherical harmonics, writes the COCONUT boundary file, and optionally saves a diagnostic figure.
- Parameters:
config (dict[str, Any]) – Processing configuration. Common keys are
map_type,output_dir,download_dir,lmax,amp,r_st,adapt_map,write_map,show_map,visu_type,alpha,interpolation_order,interpolation,rotate_to_stonyhurst,flux_correct,flux_correction_method, anddrms_emailorjsoc_email.target_date (str | datetime) – Requested processing time.
method_used (str) – Method label used in output filenames.
output_path_fig (str | None) – Explicit diagnostic figure path. If omitted, the figure name is built from the effective time.
- Returns:
Processing metadata, including target
date,effective_date,magnetogram_date, output paths, selected local file or interpolation stencil, optionalBr_linear, spherical harmonic coefficients, and rotation angle.- Return type:
dict[str, Any]
- coconut_tools.magnetogram.sph_filtering.processed_longitude_axis(file_path, map_type, temporal=False)[source]¶
Return longitude cell centers matching the processed Br column order.
The returned array follows the same longitude ordering as maps produced by
read_magnetogramorread_temporal_br_map. For interpolated temporal GONG maps, the filename-encoded circular shift is applied so the longitude axis matches the map that was shifted before interpolation.- Return type:
ndarray- Parameters:
file_path (str)
map_type (str)
temporal (bool)
- coconut_tools.magnetogram.sph_filtering.project_and_reconstruct(Br, Theta, Phi, lmax, amp=1, alpha=0)[source]¶
Project Br onto spherical harmonics and reconstruct the filtered map.
Uses complex spherical harmonics with coefficients stored only for m >= 0. For a real field, the missing negative-m modes are recovered during reconstruction by adding 2 * real(a_lm * Y_lm) for m > 0.
- coconut_tools.magnetogram.sph_filtering.read_first_fits_image(file_path)[source]¶
Read the first FITS HDU that contains at least a 2D image array.
- Return type:
ndarray- Parameters:
file_path (str)
- coconut_tools.magnetogram.sph_filtering.read_interpolated_magnetogram(local_files, map_type, selection, adapt_map=0, interpolation_order=2)[source]¶
Read, normalize, and temporally interpolate a four-map stencil.
The source maps are converted into the same latitude/longitude convention before interpolation. The returned
ThetaandPhigrids describe the interpolated map, whileBr_linearis kept as a diagnostic reference for comparing cubic Hermite interpolation against the simpler linear result.- Parameters:
local_files (list[str]) – Local files in stencil order.
map_type (str) – Map type. Supported: temporal GONG variants and 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, resize=False)[source]¶
Read one non-interpolated magnetogram and build its spherical grid.
The map is converted into the pipeline convention: latitude index ordered from north to south after the final Br assignment, longitude columns ordered according to
ensure_increasing_longitude,thetaas colatitude in radians, andphias longitude in radians. WSO text maps are parsed from their native format and converted to Gauss.- Parameters:
file_path (str) – Path to the magnetogram file.
map_type (str) – Map product type, for example
WSO,ADAPT,GONG_mrzqs,GONG_mrbqs,GONG_mrbqj,GONG_mrmqs,GONG_mrnqs,HMI_small,HMI_polfil, orHMI_SYNC.adapt_map (int, optional) – Index for ADAPT map. Defaults to 0.
resize (bool, optional) – Resize FITS maps to
(360, 720)after longitude normalization. Defaults to False.
- Returns:
Br map and 2D
ThetaandPhigrids in radians.- Return type:
tuple[np.ndarray, np.ndarray, np.ndarray]
- coconut_tools.magnetogram.sph_filtering.read_temporal_br_map(file_path, map_type, adapt_map=0)[source]¶
Read and normalize one FITS magnetogram used in interpolation.
The output contains only Br, not the meshgrid. Latitude is flipped into the pipeline convention, longitude is normalized to increasing order, and temporal GONG maps are circularly shifted so column zero corresponds to the Carrington-zero convention before interpolation.
- Parameters:
file_path (str) – Local FITS file.
map_type (str) – Map type. Supported: temporal GONG variants and ADAPT.
adapt_map (int) – ADAPT realization index.
- Returns:
Normalized radial magnetic field map.
- Return type:
np.ndarray
- coconut_tools.magnetogram.sph_filtering.resize_magnetogram_if_requested(Br_data, enabled)[source]¶
Resize a Br map to the standard 360x720 grid when requested.
- Return type:
ndarray- Parameters:
Br_data (ndarray)
enabled (bool)
- coconut_tools.magnetogram.sph_filtering.resize_processed_longitude_axis(longitude_original, nb_phi, has_duplicate_endpoint=False)[source]¶
Resize a processed longitude axis while preserving its original origin.
- Return type:
ndarray- Parameters:
longitude_original (ndarray)
nb_phi (int)
has_duplicate_endpoint (bool)
- coconut_tools.magnetogram.sph_filtering.rotate_longitude_to_stonyhurst(Br, angle_degrees, has_duplicate_endpoint=False, zero_column=None)[source]¶
Roll an increasing-longitude map into the requested Stonyhurst frame.
- Parameters:
Br (np.ndarray) – Map whose longitude columns are already increasing.
angle_degrees (float) – Carrington longitude of the Stonyhurst zero meridian, used only to infer
zero_columnwhen it is omitted.has_duplicate_endpoint (bool) – True when the last longitude column duplicates the first one, as in WSO maps with both 0 and 360 deg.
zero_column (int | None) – Column that should become the first column in the rotated map. If omitted, it is derived from
angle_degrees.
- Returns:
Longitude-rolled map, preserving any duplicate endpoint.
- Return type:
np.ndarray
- 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.write_bc_file(output_name, Br_mode, theta, phi, r_st)[source]¶
Write a COCONUT photospheric boundary-condition file.
The file contains one spherical surface at radius
r_st. Grid points at the two poles are written once, while non-polar cells are written for every longitude column.- Parameters:
output_name (str) – Path to output file.
Br_mode (ndarray) – Reconstructed radial field.
theta (ndarray) – 1D colatitude grid in radians.
phi (ndarray) – 1D longitude grid in radians.
r_st (float) – Spherical radius.