Files
JFCalibration2/jfcal/utils.py
T
2026-07-22 16:46:36 +02:00

66 lines
1.9 KiB
Python

import glob
from pathlib import Path
import boost_histogram as bh
import numpy as np
def get_first_file(path : Path, file_prefix : str):
"""
Get the first file with lowest index in directory that matches the given prefix.
"""
first_file = min(path.glob(f'{file_prefix}*'), default=None)
if first_file is None:
raise ValueError(f"No files found in {path} with prefix {file_prefix}")
return first_file
def save_fit_parameters(fit_params : dict, output_file : Path):
"""
Save the fit parameters to a text file.
Parameters
----------
fit_params : dict
The fit parameters to save.
output_file : Path
The path to the output file.
"""
with open(output_file, 'w') as f:
for key, value in fit_params.items():
f.write(f"{key}: {value}\n")
def create_histogram_from_data(data : np.ndarray, bin_range : tuple[float, float] = None, bin_width : float = None) -> bh.Histogram:
"""
Create a histogram from the given data.
Parameters
----------
data : np.ndarray
The data to create the histogram from.
bin_range : tuple[float, float], optional
The range of the bins. Default is None, which means the range is determined from the data.
bin_width : float, optional
The width of each bin. Default is None, which means the number of bins is determined automatically.
Returns
-------
bh.Histogram
The created boost histogram.
"""
if bin_range is None:
min = np.min(data)
max = np.max(data)
bin_range = (min - 0.05*(max - min), max + 0.05*(max - min)) # add 5% margin to the range
if bin_width is None:
bins = 200 # 0.5 %
else:
bins = int((bin_range[1] - bin_range[0]) / bin_width)
hist = bh.Histogram(bh.axis.Regular(bins, bin_range[0], bin_range[1]))
hist.fill(data)
return hist