Skip to content
lutteguPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

radspec

A pure Python, zero-external-dependency library designed for nuclear physicists and radiation metrologists to read, inspect, and convert raw binary and ASCII gamma and alpha spectrometry files:

  • Canberra / Mirion Genie 2000 CAM (.cnf)
  • EG&G ORTEC Maestro binary (.chn)
  • IAEA / ORTEC standard ASCII (.spe)
  • ORTEC Gamma-Vision / Maestro binary records (.spc)

Includes a standalone PySide6 (Qt) Desktop Studio (matching the visual style and ergonomics of GLysis2) and a powerful CLI to directly inspect, edit, and sum-merge Genie 2000 .CNF spectra with rigorous nuclear metrological fidelity.


Key Metrology & Editing Capabilities

  • Interactive Qt GUI Studio (radspec gui or Start_RadSpec_GUI.bat):

    • High-contrast, dark-theme Matplotlib canvas with crosshair cursor displaying instantaneous Channel, Energy (keV), Gross Counts, and Count Rate (cps).
    • Logarithmic / Linear scale and Energy (keV) / Channel x-axis toggle buttons.
    • Interactive Region of Interest (ROI) display with boundary bands and centroid markers.
    • Dedicated CNF Spectrum Editor and Genie 2000 Spectrum Merger tabs.
  • Direct Genie 2000 CAM In-Place Binary Editing (edit_cnf_file / radspec edit):

    • Directly alters OpenVMS 64-bit 100 ns acquisition start timestamps (calendar date & time).
    • Modifies Live Time ($LT$) and Real Time ($RT$) with real-time Dead Time ($DT = RT - LT$) calculation and status validation.
    • Updates detector identification string and sample metadata (title, sample ID, matrix type, mass/volume quantity, measurement units, geometry).
    • Updates active polynomial energy calibration ($a_0, a_1, a_2, a_3$) and FWHM resolution parameters ($c_0, c_1$).
    • In-place spectrum channel arithmetic: scaling factor ($\times k$), constant offset ($+c$), zeroing noise regions, or single channel editing.
    • Automatic .bak backup creation when overwriting files.
    • Preserves 100% of existing proprietary CAM sections (efficiency curves, geometry, hardware settings, peak tables).
  • Multi-File Genie 2000 Spectrum Merger (merge_cnfs / radspec merge):

    • Combines multiple .CNF runs (e.g. repeated sample counts or long environmental monitoring).
    • Strictly validates channel count match across all files.
    • Evaluates energy calibration shifts ($\Delta E_{\max}$) across the energy range to warn against artificial peak broadening.
    • Calculates exact metrological sums: $$C_{\text{sum}}[k] = \sum_{m} C_m[k] \quad \text{with} \quad \sigma(C_{\text{sum}}[k]) = \sqrt{C_{\text{sum}}[k]}$$ $$LT_{\text{sum}} = \sum_{m} LT_m, \quad RT_{\text{sum}} = \sum_{m} RT_m, \quad DT_{\text{sum}} = RT_{\text{sum}} - LT_{\text{sum}}$$
    • Sets combined acquisition start date to earliest acquisition run.
    • Emits a fully compliant binary .CNF file loadable in Genie 2000, GammaVision, GLysis2, and radspec.
  • Vendor-Independent & DLL-Free: Directly parses low-level VAX F-floating words, OpenVMS 64-bit 100 ns ticks, 50 Hz hardware clock counters, and tagged binary sections without requiring Genie 2000, Maestro, CAMBIO, or Windows DLLs.

  • Robust CAM Section Directory Parsing: Accurately parses Canberra CAM 48-byte directory entries (id, offset, sec_len). Channels are strictly bounded to their declared section length (e.g., 8192 channels / 33,280 bytes), guaranteeing seamless handling of merged dual-spectra and re-analyzed files without channel overruns, corrupted calibrations, or phantom high-energy bursts.

  • Embedded Peak Analysis Extraction: Arbitrates multiple 0x12006 peak analysis sections to populate spec.peaks with Genie 2000 centroid channels, energies (keV), net areas, and uncertainties.

  • Strict Metrological Timing: Preserves exact live time, real time, and calculated dead time fraction ($DT% = \frac{RT - LT}{RT} \times 100$) down to hardware resolution.

  • Traceable Calibration: Computes channel energies on the fly using active polynomial calibration coefficients ($E(ch) = a_0 + a_1 ch + a_2 ch^2 + \dots$) and extracts FWHM resolution parameters.

  • Complete Information Access:

    • Sample metadata: title, sample ID, sample type, geometry, mass/quantity, and measurement units.
    • Hardware & Detector: detector name, MCA model (Lynx, DSA, etc.), acquisition mode (PHA, PHA+).
    • Regions of Interest (ROIs): boundary channels, centroid channels, and peak energies.
    • Forensic Raw Access: Every parsed and unparsed byte section / record is available via spec.raw_metadata and spec.raw_sections.
  • Zero Heavy Dependencies: Core library requires only standard library Python 3.8+ (struct, datetime, math, pathlib). Optional NumPy and Pandas integrations activate automatically if installed.


Installation

Install in editable mode in any Python virtual environment:

pip install -e C:\PGM\0_Database\radspec

Or append to your Python script's search path:

import sys
sys.path.append(r"C:\PGM\0_Database\radspec")

Python Usage

1. Universal Spectrum Loading (Auto-Detect Format)

radspec.read_spectrum() automatically identifies the format using file signatures and extensions:

import radspec

# Load any supported format (.cnf, .chn, .spe, .spc)
spec = radspec.read_spectrum("samples/1100471.CNF")

print(f"Format:       {spec.format}")
print(f"Sample:       {spec.sample_title} (ID: {spec.sample_id})")
print(f"Detector:     {spec.detector_name} (MCA: {spec.mca_type})")
print(f"Start Time:   {spec.start_time}")
print(f"Live Time:    {spec.live_time_s:,.2f} s")
print(f"Real Time:    {spec.real_time_s:,.2f} s")
print(f"Dead Time:    {spec.dead_time_percent:.2f}%")
print(f"Channels:     {spec.channel_count}")
print(f"Total Counts: {spec.total_counts:,}")
print(f"Count Rate:   {spec.total_counts / spec.live_time_s:,.2f} cps")

2. Calibrated Energy & Channel Counts

Access calibrated energies in keV and raw counts directly:

# Array of calibrated energies (keV)
energies = spec.energies
counts = spec.counts

# Inspect specific channels
for ch in range(5):
    print(f"Ch {ch:4d} | {energies[ch]:8.3f} keV | {counts[ch]:6d} counts")

# Energy at any arbitrary channel (including fractional centroids):
e_peak = spec.energy_at_channel(1973.5)
print(f"Centroid at ch 1973.5 = {e_peak:.2f} keV")

3. Regions of Interest (ROIs)

Inspect preset or detected ROIs:

for idx, roi in enumerate(spec.rois):
    print(f"ROI #{idx+1}: Ch {roi.start_channel} - {roi.stop_channel} ({roi.energy_keV:.2f} keV)")

4. Forensic Raw Access

Every vendor section, record, and header is accessible for in-depth inspection:

# Raw metadata dictionary:
print(spec.raw_metadata.keys())

# For CNF files: raw byte sections indexed by CAM section ID:
# (e.g. 0x00012000 = Acq/Cal, 0x00012001 = Sample Info, 0x00012004 = ROI, 0x00012005 = Counts)
raw_bytes = spec.raw_sections[0x00012000]

5. Numerical & Data Science Integrations (NumPy / Pandas)

If NumPy or Pandas are installed in your environment:

# NumPy: returns 3 1D ndarrays: (channels, energies_keV, counts)
chs, energies, counts = spec.to_numpy()

# Pandas DataFrame: columns ['channel', 'energy_keV', 'counts']
df = spec.to_dataframe()

6. Direct In-Place Editing of Genie 2000 (.CNF) Files

import datetime
import radspec

# Modify any parameter directly in a .CNF file:
radspec.edit_cnf_file(
    "measurement.cnf",
    output_path="modified_measurement.cnf",  # or None to overwrite with .bak
    start_time=datetime.datetime(2026, 11, 18, 14, 30, 0),
    live_time_s=7200.0,
    real_time_s=7245.5,
    detector_name="HPGe_Det_1",
    sample_title="Soil Standard 250.0g",
    sample_id="SAMPLE-2026-001",
    sample_quantity=250.0,
    sample_units="g",
    energy_cal=[0.125, 0.4998, 0.0, 0.0],
    scale_counts=1.0,                       # multiply counts
    zero_channels=(0, 40),                  # zero out low-energy electronic noise
)

7. Merging Multiple Spectra into a Sum Spectrum

import radspec

# Sum multiple Genie 2000 files with strict metrological adjustment:
merged_spec = radspec.merge_cnfs(
    ["run1.cnf", "run2.cnf", "run3.cnf"],
    output_path="sum_spectrum.cnf",
    detector_name="HPGe_Det_1",
    sample_title="Composite Run (3 files)",
    force=False  # checks calibration compatibility
)

print(f"Total Summed Counts: {merged_spec.total_counts:,}")
print(f"Combined Live Time:  {merged_spec.live_time_s:,.2f} s")
print(f"Combined Real Time:  {merged_spec.real_time_s:,.2f} s")
print(f"Combined Dead Time:  {merged_spec.dead_time_percent:.2f}%")

8. Format Conversions

from radspec import convert_to_txt, convert_to_csv, convert_to_spe, batch_convert_to_txt

# Convert any spectrum to CAMBIO / RawData2DB compatible enriched TXT:
convert_to_txt("measurement.cnf", "output.txt")

# Convert to standard CSV:
convert_to_csv("measurement.chn", "output.csv")

# Convert binary spectra (.cnf, .chn, .spc) into portable IAEA/ORTEC ASCII SPE:
convert_to_spe("measurement.spc", "output.spe")

# Batch convert a whole folder of spectra:
batch_convert_to_txt("C:/path/to/spectra_folder", recursive=True)

Command Line Interface (CLI)

radspec provides dedicated CLI tools for inspecting, editing, merging, and launching the GUI:

# 1. Launch the Qt Desktop GUI Studio:
python run_gui.py
# or double-click Start_RadSpec_GUI.bat
# or:
radspec gui
radspec gui "samples/1100471.CNF"

# 2. Inspect spectrum metrology summary:
radspec info "samples/1100471.CNF"

# 3. Edit Genie 2000 .CNF directly from CLI:
radspec edit "samples/25_0030.CNF" -o "samples/edited.CNF" \
    --start-time "2026-11-18 10:00:00" \
    --live-time 7200.0 --real-time 7250.0 \
    --detector "HPGe_Coaxial_1" \
    --title "Modified Sample 250g" \
    --scale-counts 1.5 \
    --zero-channels 0 35 \
    -i

# 4. Merge multiple Genie 2000 files into a sum spectrum:
radspec merge "samples/run1.cnf" "samples/run2.cnf" -o "samples/sum.cnf" \
    --detector "HPGe_Coaxial_1" \
    --title "Summed Run 1+2" \
    -i

# 5. Format conversion and batch processing:
radspec "samples/scenario_1_point.cnf" --to csv
radspec "samples/scenario_1_point.spc" --to spe
radspec "C:/path/to/spectra" --batch -r

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages