Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Combining complex line shape and fake data generator" #67

Merged
merged 179 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
179 commits
Select commit Hold shift + click to select a range
0b00553
fixed gas_scatter_proportion tested
casesyh Jun 26, 2020
9bf9ca2
add chi2 calculation
casesyh Jul 8, 2020
bb0bc61
fix the checking of scatter spectra file
casesyh Jul 11, 2020
fab92a7
fix the checking of scatter spectra file
casesyh Jul 11, 2020
c173168
internal config error
casesyh Jul 11, 2020
fa62da5
fix magnetic field mismatch between notebook and mermithid result
casesyh Aug 20, 2020
96f1259
add radiation loss
casesyh Sep 3, 2020
a27dc40
check in before adding file for composite trap fitting
casesyh Sep 9, 2020
021156b
composite gaussian resolution function implemented
casesyh Sep 10, 2020
6727ea2
add poisson chi2
casesyh Sep 15, 2020
5a8fae7
update KrComplexLineShape to use simulated resolution for fake data g…
casesyh Sep 16, 2020
69617b9
add convolve_ins_resolution
casesyh Sep 17, 2020
6ac5ac1
resolve probabilities containing NaN
casesyh Sep 23, 2020
d5d090a
testing stan analysis test scripts in termite
casesyh Sep 27, 2020
a582ef7
use termite script for testing
casesyh Sep 27, 2020
e04a4f3
update the files
casesyh Sep 28, 2020
be09e5a
delete configuration for magnetic field
casesyh Sep 28, 2020
5825a96
make path_to_ins_resolution_data_txt configurable in fake_data_stan_a…
casesyh Oct 1, 2020
352c672
test resolution function configurable
casesyh Oct 5, 2020
d5ddea3
Loading/using simulated resolution file
taliaweiss Oct 9, 2020
1494fd0
Adopting YuHao's simulated res file naming
taliaweiss Oct 9, 2020
186ee0f
Sample simulated resolution counts rates to account for errors
taliaweiss Oct 9, 2020
10c08f3
add MultiGAsComplexLineShape.py
casesyh Oct 18, 2020
7c013dc
np.random in convolve_ins_resolution
casesyh Oct 18, 2020
cc4f411
update convolve_ins_resolution_combining_four_trap
casesyh Oct 19, 2020
bd27aaa
update convolve_ins_resolution_combining_four_trap
casesyh Oct 20, 2020
acf830a
started adding new options re ins resolution
taliaweiss Oct 20, 2020
5fd5dde
Merge branch 'simulated_ins_resolution_in_fake_data_generator' of htt…
taliaweiss Oct 20, 2020
3231065
add dirac peak option to every make_spectrum
casesyh Oct 20, 2020
0d6cd30
change fix_ftc to use_simulated_inst_reso
casesyh Oct 20, 2020
33dece6
add configuration use_combined_four_trap_inst_reso
casesyh Oct 20, 2020
5474e89
add configuration use_combined_four_trap_inst_reso in FakeDataGenerat…
casesyh Oct 20, 2020
a9b1ac7
Continued YuHao's work adding trap combining/error sampling
taliaweiss Oct 20, 2020
ab5ecc1
Made my naming consistent with YuHao's
taliaweiss Oct 20, 2020
d3496c9
Set radiation loss to True by default
taliaweiss Oct 20, 2020
673bd51
add base_shape configuration to multi gas line shape processor
casesyh Oct 20, 2020
c03617e
Make B-field fixed input for fake data gen
taliaweiss Oct 20, 2020
e0693de
Merge branch 'simulated_ins_resolution_in_fake_data_generator' of htt…
taliaweiss Oct 20, 2020
726b88d
Added missing commas
taliaweiss Oct 20, 2020
fd5eead
put emitted_peak = self.base_shape inside make_spectrum functions
casesyh Oct 20, 2020
684ca43
fixed various small errors in implementation of new features
taliaweiss Oct 21, 2020
ab86d1d
prepare to add smeared triangle resolutio and gaussian+lorentzian res…
casesyh Oct 21, 2020
2871962
Fixed errors; added temporary diagnoistic plots
taliaweiss Oct 21, 2020
7801316
Changed default inst res files
taliaweiss Oct 21, 2020
3fc6772
Fixed temporary diagnostic plots
taliaweiss Oct 21, 2020
f884b91
add smeared triangle and gaussian + lorentzian reoslution
casesyh Oct 22, 2020
d0bf786
Enabled FakeDataGenerator to use complex ls as func of K
taliaweiss Oct 22, 2020
6d99c11
Fixed scatter peak bug; removed temporary plots/printing
taliaweiss Oct 22, 2020
dc418e7
Set bin width of std_eV_array manually
taliaweiss Oct 24, 2020
aed8ddc
Changed default simulated res to T2 version
taliaweiss Oct 24, 2020
6cf5179
push the changes in there
casesyh Oct 25, 2020
2cd91fa
add fitting with composite gaussian lorentzian resolution
casesyh Nov 2, 2020
350f496
fix survival probability
casesyh Nov 3, 2020
8227397
fixed survival probability free scatter proportion
casesyh Nov 4, 2020
d70e4c0
add fitting with partially fixed scatter proportion
casesyh Nov 5, 2020
a94dfc5
update fitting with fixed survival probability partially fixed scatte…
casesyh Nov 6, 2020
2229336
add mass 28 gases
casesyh Nov 16, 2020
5fbb06f
make gases and scatter proportion configurable
casesyh Nov 17, 2020
2323155
make gases and scatter_proportion configurable
casesyh Nov 17, 2020
6325498
add elevated, composite, composite with pedestal factor gaussian reso…
casesyh Nov 17, 2020
bb46e17
composite gaussian resolution scaled and simulated resolution scaled
casesyh Nov 24, 2020
86dee6e
add fitting with simulated resolution scaled and fit reconstruction e…
casesyh Dec 5, 2020
033937d
test git it's been a while
casesyh Jan 24, 2021
514305d
make recon eff param configurable
casesyh Jan 25, 2021
fbb7b49
Merge branch 'multi_gas_scattering' into combining_multi_gas_scatteri…
casesyh Jan 26, 2021
4bc4e14
fix typo in variable name recon_eff_param_c
casesyh Jan 28, 2021
bf8f2a1
Fixed the interface between the fake data generator and the complex l…
huyanxy Jan 28, 2021
b376b79
Merge branch 'combining_multi_gas_scattering_with_simulated_ins_resol…
huyanxy Jan 28, 2021
cac1723
Testing merge of simulated_ins... and multigas... branches
taliaweiss Jan 28, 2021
50089b1
Merge branch 'combining_multi_gas_scattering_with_simulated_ins_resol…
taliaweiss Jan 28, 2021
b32b50b
Testing changes
taliaweiss Jan 28, 2021
a160e85
added more configurables in the fake data generator. Changed variabl…
huyanxy Jan 29, 2021
1249f6a
organized configs
huyanxy Jan 29, 2021
26b7b1d
Testing recon eff in Stan
taliaweiss Jan 29, 2021
3d94d86
Fixed bug in recon eff implementation in complex lineshape
taliaweiss Jan 29, 2021
b830e9c
Removed double-definition of self.scatter_proportion in FakeDataGener…
taliaweiss Jan 29, 2021
2fc7e17
move self.shakeSpectrumClassInstance into InternalConfigure
casesyh Feb 5, 2021
7d29504
Commenting changes
taliaweiss Feb 8, 2021
c7ff7a3
Merge branch 'combining_multi_gas_scattering_with_simulated_ins_resol…
taliaweiss Feb 8, 2021
236a737
add a few comments above the make spectrum's
casesyh Feb 8, 2021
97386cf
Merge branch 'combining_multi_gas_scattering_with_simulated_ins_resol…
taliaweiss Feb 8, 2021
ff744ef
Merged in develop; added comments to FakeDataGenerator's InternalConf…
taliaweiss Feb 8, 2021
0283d97
added shake json file path in the fake data generator; fixed bug (ext…
huyanxy Feb 9, 2021
7719ce2
fixed result dictionary keys for the fitted survival probability. No…
huyanxy Feb 9, 2021
fc3a164
changed comments about the options for the resolution function config
huyanxy Feb 9, 2021
bf49a03
Removed unnecessary path config from FakeDataGenerator
taliaweiss Feb 9, 2021
4f37578
Pulling Xueying's changes
taliaweiss Feb 9, 2021
f16a5e6
fix bug (incorrect function name)
huyanxy Feb 10, 2021
6a2dd07
fix bug (incorrect function name in multi gas lineshape)
huyanxy Feb 10, 2021
a0f279e
removed self.path_to_quad_trap_eff_interp variable (no longer needed)
huyanxy Feb 10, 2021
fbacdb7
fix make spectrum function call bug in method spectrum_func_composite…
casesyh Feb 10, 2021
021ddca
make self.shakeSpectrumClassInstance configuration only happen when s…
casesyh Feb 10, 2021
5be7d8a
fixed function call in complex lineshape
huyanxy Feb 10, 2021
9d6ca2c
included Yu-Hao's change to the shape spectrum input option
huyanxy Feb 10, 2021
a482415
fixed function call
huyanxy Feb 10, 2021
41bbe00
fixed function call
huyanxy Feb 10, 2021
297eb80
Cleaned up code per Christine's recommendations on pull request
taliaweiss Feb 12, 2021
250d3e7
fit with modified exponential scatter peak amplitude ratios
casesyh Mar 15, 2021
2f6f6ed
Added function to compute frac events in ROI for count rate predictions
taliaweiss Mar 16, 2021
7900b6d
Merge branch 'combining_multi_gas_scattering_with_simulated_ins_resol…
taliaweiss Mar 16, 2021
aa3a1c3
add survival probability in parameters
casesyh Mar 16, 2021
79909fd
Updated FakeDataGenerator to use correct recon eff model
taliaweiss Mar 31, 2021
0c3398c
Added Dirac delta option to new complex lineshape function, fixed errors
taliaweiss Apr 1, 2021
69bcf34
add fitting with gaussian resolution
casesyh Jun 23, 2021
5ba3280
add 'gaussian_resolution_fit_scatter_peak_ratio' to resolution functi…
casesyh Jun 24, 2021
76c1d9d
minor modifications in Complex_line_shape_fitter.py
casesyh Jun 24, 2021
c7c89da
copy the MultiGasComplexLineShape.py from combining_branch_temp_for_u…
casesyh Jun 25, 2021
00a65f7
missed adding f_radiation_loss = self.radiation_loss_f() around line 348
casesyh Jun 25, 2021
273522e
upload Complex_line_shape_fitter.py
casesyh Jun 25, 2021
347fb49
Made gaussian res an option in FakeDataGenerator
taliaweiss Jun 28, 2021
29eb20b
Fixed background function for FakeDataGenerator
taliaweiss Jun 30, 2021
703e8bc
Temporarily added diagnostic plotting functions
taliaweiss Jul 1, 2021
36d1d81
Fixed bug in Gaussian response fn option
taliaweiss Jul 20, 2021
42d3926
Merge branch 'develop' into combining_ComplexLineShape_and_FakeDataGe…
taliaweiss Jul 22, 2021
83d6106
add configuration use_quad_eff_interp
casesyh Jul 28, 2021
5f32964
Changed survival_prob default to 1
taliaweiss Jul 28, 2021
e5d160e
Merge branch 'combining_ComplexLineShape_and_FakeDataGenerator' of ht…
taliaweiss Jul 28, 2021
ed96284
Updated len(std_eV_array) for Phase II
taliaweiss Jul 28, 2021
92750ea
Added scale factor to fake data generator
taliaweiss Aug 1, 2021
5cb8e15
Allow energy res to vary with K in data gen
taliaweiss Aug 2, 2021
58400bd
Cleaning - ins res variation with K in data gen
taliaweiss Aug 2, 2021
63efaf0
Changed ins res width defaults; fixed error
taliaweiss Aug 2, 2021
c56ea19
Removed temporary plotting and printing
taliaweiss Aug 2, 2021
481ec91
Added comments re new input parameters in generator
taliaweiss Aug 4, 2021
0c25da8
fixing gaussian resolution with detailed lineshape combo
cclaessens Aug 6, 2021
f0959e2
Re-introduced trap weight and resolution bin sampling
taliaweiss Aug 7, 2021
0d2809b
Merge branch 'combining_ComplexLineShape_and_FakeDataGenerator' of ht…
taliaweiss Aug 7, 2021
0d3350f
fixed molecular final states file and added extended
Aug 11, 2021
28ec76c
fixed molecular final states file and added extended
Juliana-S Aug 11, 2021
62b242c
fixed molecular final states file and added extended
Juliana-S Aug 11, 2021
54a0516
Avoid flipping lineshape for simplified model
taliaweiss Aug 15, 2021
c606dae
rearrange the configurations in complex line shape fitter test
casesyh Aug 23, 2021
ba8410b
rearrange the configurations in complex line shape fitter test
casesyh Aug 23, 2021
10f24d5
Testing channel runtime correction
taliaweiss Oct 7, 2021
9caafcd
Merge branch 'combining_ComplexLineShape_and_FakeDataGenerator' of ht…
taliaweiss Oct 7, 2021
e373596
Fix livetime correction
taliaweiss Oct 17, 2021
10a124a
Fixed normalization process
taliaweiss Oct 19, 2021
f090948
update MultiGasComplexLineShape.py
casesyh Oct 20, 2021
1009485
update MultiGasComplexLineShape.py
casesyh Oct 20, 2021
c23ce65
notes for update: added fit_data_simulated_resolution_scaled_fit_scat…
casesyh Oct 20, 2021
01dbb34
update MultiGasComplexLineShape.py
casesyh Oct 20, 2021
869bc03
update internal run
casesyh Oct 20, 2021
f43e4b6
update fit_data_simulated_resolution_scaled_fit_scatter_peak_ratio
casesyh Oct 20, 2021
57f45e9
update fit_data_simulated_resolution_scaled_fit_scatter_peak_ratio
casesyh Oct 20, 2021
8011208
update fit_data_simulated_resolution_scaled_fit_scatter_peak_ratio
casesyh Oct 20, 2021
c6ebe4f
modify test_analysis/Complex_line_shape_fitter.py
casesyh Oct 20, 2021
209372e
update mermithid/processors/misc/MultiGasComplexLineShape.py
casesyh Oct 20, 2021
7fa0461
Scatter peak ratio re-parameterization in fake data gen
taliaweiss Oct 21, 2021
23bd22a
Merge branch 'combining_ComplexLineShape_and_FakeDataGenerator' of ht…
taliaweiss Oct 21, 2021
1109f4f
add configurable detection eff
casesyh Oct 22, 2021
11b6075
Merge branch 'combining_ComplexLineShape_and_FakeDataGenerator' of ht…
casesyh Oct 22, 2021
55663e5
update test_analysis/Complex_line_shape_fitter.py
casesyh Oct 22, 2021
7915c22
change factor to 0.4626
casesyh Oct 23, 2021
701b949
Fixed freq var approach; added p and q var
taliaweiss Feb 1, 2022
36934ab
Updated molecular endpoint value
taliaweiss Jun 27, 2022
0611b4e
Update fake track tritium data functions
taliaweiss Nov 14, 2022
09c8ad1
adding frequency variation with gaussian resolution. Also adding effi…
cclaessens Nov 24, 2022
a91751e
Sampling simulated resolution once during configuration.
cclaessens Nov 24, 2022
de870bd
Response energy stepzise can be modified. Efficiency is sampled first…
cclaessens Nov 24, 2022
0c19a4b
Fixed merge conflict
taliaweiss Dec 1, 2022
c6e7ca5
Small spacing change
taliaweiss Jun 12, 2023
4e20f71
Added comments describing detector response model options
taliaweiss Jul 10, 2024
08f4bc4
Address several comments from Christine on PR #67
taliaweiss Jul 10, 2024
d3bd951
Add comments to show the two functions called in the tritium fake dat…
Jul 11, 2024
5c47dac
add description to the spectrum_func_composite_gaussian_lorentzian_fi…
Jul 11, 2024
7b7003b
add description for the components of the fit parameter array p0 in t…
Jul 11, 2024
58ce628
Added script descriptions, including relevant to P8 Phase II analysis…
taliaweiss Jul 11, 2024
058d59f
Merge branch 'combining_ComplexLineShape_and_FakeDataGenerator' of ht…
taliaweiss Jul 11, 2024
79a326d
add a list of resolutions to the processor description
Jul 11, 2024
17fccc1
Adding comments to MultiGasComplexLineShape processor to explain func…
taliaweiss Jul 11, 2024
9ed5f9b
Merge fix
taliaweiss Jul 11, 2024
37d4d06
add more descriptions to some functions
Jul 12, 2024
c03c9e5
improve the wording of the comments around line 1235
Jul 12, 2024
7e4e727
add description of spectrum_func_ftc2()
Jul 12, 2024
20d1675
add more to the description of spectrum_func_1 about the function use…
Jul 12, 2024
a3d2c04
add in the discription of spectrum_func() about the amplitude is scal…
Jul 12, 2024
2e54e59
Finished comment defining p0 in spectrum_func
taliaweiss Jul 29, 2024
f6e9fda
Merge fix
taliaweiss Jul 29, 2024
e9e8bd8
delete the functions containing the smeared triangle
Oct 31, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,6 @@ RUN mkdir -p $MERMITHID_BUILD_PREFIX &&\
echo 'export PYTHONPATH=$MERMITHID_BUILD_PREFIX/$(python3 -m site --user-site | sed "s%$(python3 -m site --user-base)%%"):$PYTHONPATH' >> setup.sh &&\
/bin/true

RUN source $COMMON_BUILD_PREFIX/setup.sh &&\
pip install iminuit &&\
/bin/true

########################
FROM mermithid_common as mermithid_done

Expand All @@ -45,6 +41,7 @@ COPY tests $MERMITHID_BUILD_PREFIX/tests

# repeat the cmake command to get the change of install prefix to set correctly (a package_builder known issue)
RUN source $MERMITHID_BUILD_PREFIX/setup.sh &&\
pip3 install --upgrade pip &&\
cd /tmp_source &&\
mkdir -p build &&\
cd build &&\
Expand All @@ -58,6 +55,7 @@ RUN source $MERMITHID_BUILD_PREFIX/setup.sh &&\
cd /tmp_source &&\
# ls -altrh morpho &&\
pip3 install . ./morpho --prefix $MERMITHID_BUILD_PREFIX &&\
pip3 install iminuit &&\
/bin/true

########################
Expand Down
27 changes: 18 additions & 9 deletions mermithid/misc/ComplexLineShapeUtilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,12 @@ def read_oscillator_str_file(filename):

for line in lines:
if line != "" and line[0]!="#":
raw_data = [float(i) for i in line.split("\t")]
energyOsc[0].append(raw_data[0])
energyOsc[1].append(raw_data[1])
try:
raw_data = [float(i) for i in line.split("\t")]
energyOsc[0].append(raw_data[0])
energyOsc[1].append(raw_data[1])
except:
continue
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is not good practice. something should happen during the exception that tells about the error. why is this exception necessary?


energyOsc = np.array(energyOsc)
### take data and sort by energy
Expand All @@ -62,14 +65,21 @@ def aseev_func_tail(energy_loss_array, gas_type):
A2, omeg2, eps2 = 0.1187, 33.40, 10.43
elif gas_type=="Ar":
A2, omeg2, eps2 = 0.3344, 21.91, 21.14
elif gas_type=="N2":
A2, omeg2, eps2 = 0.21754816, 44.99897054, 20.43916114
elif gas_type=="CO":
A2, omeg2, eps2 = 0.19583454, 55.21888452, 16.44972596
elif gas_type=="C2H4":
A2, omeg2, eps2 = 0.57492182, 23.77501391, 14.33107345
return A2*omeg2**2./(omeg2**2.+4*(energy_loss_array-eps2)**2.)

#convert oscillator strength into energy loss spectrum
def get_eloss_spec(e_loss, oscillator_strength, kr_17keV_line): #energies in eV
kinetic_en = kr_17keV_line * 1000
kinetic_en = kr_17keV_line
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are the units correct here? it seems to me like kinetic_en is in keV but the rest of the function is in eV.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks that way to me, too. @casesyh , this is your code – are we missing something?

e_rydberg = 13.605693009 #rydberg energy (eV)
a0 = 5.291772e-11 #bohr radius
return np.where(e_loss>0 , 4.*np.pi*a0**2 * e_rydberg / (kinetic_en * e_loss) * oscillator_strength * np.log(4. * kinetic_en * e_loss / (e_rydberg**3.) ), 0)
argument_of_log = np.where(e_loss > 0, 4. * kinetic_en * e_rydberg / (e_loss**2.) , 1e-5)
return np.where(e_loss>0 , 1./(e_loss) * oscillator_strength* np.log(argument_of_log), 0)

# Takes only the nonzero bins of a histogram
def get_only_nonzero_bins(bins,hist):
Expand Down Expand Up @@ -108,12 +118,11 @@ def energy_guess_to_frequency(energy_guess, energy_guess_err, B_field_guess):
frequency_err = const/(1+energy_guess/mass_energy_electron)**2*energy_guess_err/mass_energy_electron
return frequency , frequency_err

# Given a frequency and error, converts those to B field values assuming the line is the 17.8 keV line
def central_frequency_to_B_field(central_freq,central_freq_err):
# Given a frequency, converts it to a B field value assuming the line is the 17.8 keV line
def central_frequency_to_B_field(central_freq):
const = (2.*np.pi*m_e)*(1+kr_17keV_line/mass_energy_electron)/e_charge
B_field = const*central_freq
B_field_err = const*central_freq_err
return B_field , B_field_err
return B_field

# given a FWHM for the lorentian component and the FWHM for the gaussian component,
# this function estimates the FWHM of the resulting voigt distribution
Expand Down
4 changes: 2 additions & 2 deletions mermithid/misc/Constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ def GF(): return 1.1663787*10**(-23) #Gf/(hc)^3, in eV^(-2)
def Vud(): return 0.97425 #CKM element

#Beta decay-specific physical constants
def QT(): return 18563.251 #For atomic tritium (eV), from Bodine et al. (2015)
def QT2(): return 18573.24 #For molecular tritium (eV), Bodine et al. (2015)
def QT(): return 18563.251 #SHOULD BE DOUBLE-CHECKED. For atomic tritium (eV), from Bodine et al. (2015)
def QT2(): return 18574.01 #For molecular tritium (eV). Calculation here: https://projecteight.slack.com/archives/CG5TY2UE7/p1649963449399179, based on Bodine et al. (2015).
def Rn(): return 2.8840*10**(-3) #Helium-3 nuclear radius in units of me, from Kleesiek et al. (2018): https://arxiv.org/pdf/1806.00369.pdf
def M_3He_in_me(): return 5497.885 #Helium-3 mass in units of me, Kleesiek et al. (2018)
def atomic_num(): return 2. #For helium-3
Expand Down
127 changes: 102 additions & 25 deletions mermithid/misc/FakeTritiumDataFunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
from mermithid.misc.Constants import *
from mermithid.misc.ConversionFunctions import *

import matplotlib.pyplot as plt

"""
Constants and functions used by processors/TritiumSpectrum/FakeDataGenerator.py
"""
Expand Down Expand Up @@ -272,15 +274,30 @@ def convolved_bkgd_rate(K, Kmin, Kmax, lineshape, ls_params, min_energy, max_ene
return 0.



#Convolution of signal and lineshape using scipy.signal.convolve
def convolved_spectral_rate_arrays(K, Q, mnu, Kmin,
lineshape, ls_params, min_energy, max_energy,
complexLineShape, final_state_array):
lineshape, ls_params, scatter_peak_ratio_p, scatter_peak_ratio_q, scatter_fraction, min_energy, max_energy,
complexLineShape, final_state_array, resolution_function, ins_res_width_bounds, ins_res_width_factors, p_factors, q_factors):
"""K is an array-like object
"""
logger.info('Using scipy convolve')
logger.info('Lineshape is {} with {}'.format(lineshape, resolution_function))
energy_half_range = max(max_energy, abs(min_energy))

#logger.info('Using {} frequency regions. Mean and std of p are {} and {}. For q its {} and {}'.format(len(ins_res_width_bounds)-1,
# np.mean(p_factors), np.std(p_factors),
# np.mean(q_factors), np.std(q_factors)))

if ins_res_width_bounds != None:
Kbounds = [np.min(K)] + ins_res_width_bounds + [np.max(K)]
else:
Kbounds = [np.min(K), np.max(K)]

K_segments = []
for i in range(len(Kbounds)-1):
K_segments.append(K[np.logical_and(Kbounds[i]<=K, K<=Kbounds[i+1])])

dE = K[1] - K[0]
n_dE_pos = round(energy_half_range/dE) #Number of steps for the lineshape for energies > 0
n_dE_neg = round(energy_half_range/dE) #Same, for energies < 0
Expand All @@ -293,23 +310,53 @@ def convolved_spectral_rate_arrays(K, Q, mnu, Kmin,
elif lineshape=='simplified_scattering' or lineshape=='simplified':
lineshape_rates = simplified_ls(K_lineshape, 0, ls_params[0], ls_params[1], ls_params[2], ls_params[3], ls_params[4], ls_params[5])
elif lineshape=='detailed_scattering' or lineshape=='detailed':
if resolution_function == 'simulated_resolution' or resolution_function == 'simulated':
lineshape_rates = []
scale_factors = [ls_params[0]*f for f in ins_res_width_factors]
for i in range(len(scale_factors)):
lineshape_rates.append(np.flipud(complexLineShape.make_spectrum_simulated_resolution_scaled_fit_scatter_peak_ratio(scale_factors[i], ls_params[1], scatter_peak_ratio_p*p_factors[i], scatter_peak_ratio_q*q_factors[i], scatter_fraction, emitted_peak='dirac')))
elif resolution_function == 'gaussian_resolution' or resolution_function == 'gaussian':
logger.warn("Scatter peak ratio function for lineshape with Gaussian resolution may not be up-to-date!")
gaussian_widths = [ls_params[0]*f for f in ins_res_width_factors]
lineshape_rates = [np.flipud(complexLineShape.make_spectrum_gaussian_resolution_fit_scatter_peak_ratio(gaussian_widths[i], ls_params[1], scatter_peak_ratio_p*p_factors[i], scatter_peak_ratio_q*q_factors[i], scatter_fraction, emitted_peak='dirac')) for i in range(len(gaussian_widths))]
else:
logger.warn('{} is not a resolution function that has been implemented in the FakeDataGenerator'.format(resolution_function))

lineshape_rates = complexLineShape.spectrum_func_1(K_lineshape/1000., ls_params[0], 0, 1, ls_params[1])

beta_rates = spectral_rate(K, Q, mnu, final_state_array) #np.zeros(len(K))
#for i,ke in enumerate(K):
# beta_rates[i] = spectral_rate(ke, Q, mnu, final_state_array)
below_Kmin = np.where(K < Kmin)

#Convolving
convolved = convolve(beta_rates, lineshape_rates, mode='same')
below_Kmin = np.where(K < Kmin)
np.put(convolved, below_Kmin, np.zeros(len(below_Kmin)))
if (lineshape=='detailed_scattering' or lineshape=='detailed'):# and (resolution_function == 'simulated_resolution' or resolution_function == 'simulated'):
convolved_segments = []
beta_rates = spectral_rate(K, Q, mnu, final_state_array)
plt.figure(figsize=(7,5))
for j in range(len(lineshape_rates)):
plt.plot(lineshape_rates[j])
#beta_rates = spectral_rate(K_segments[j], Q, mnu, final_state_array)
plt.plot(lineshape_rates[j])
convolved_j = convolve(beta_rates, lineshape_rates[j], mode='same')
np.put(convolved_j, below_Kmin, np.zeros(len(below_Kmin)))
#Only including the part of convolved_j that corresponds to the right values of K
convolved_segments.append(convolved_j[np.logical_and(Kbounds[j]<=K, K<=Kbounds[j+1])])
#convolved.append(convolved_j)
convolved = np.concatenate(convolved_segments, axis=None)
plt.savefig('varied_lineshapes.png', dpi=200)
taliaweiss marked this conversation as resolved.
Show resolved Hide resolved
"""elif resolution_function=='gaussian':
lineshape_rates = np.flipud(lineshape_rates)
beta_rates = spectral_rate(K, Q, mnu, final_state_array)
convolved = convolve(beta_rates, lineshape_rates, mode='same')
np.put(convolved, below_Kmin, np.zeros(len(below_Kmin)))"""

if (lineshape=='gaussian' or lineshape=='simplified_scattering' or lineshape=='simplified'):
beta_rates = spectral_rate(K, Q, mnu, final_state_array)
convolved = convolve(beta_rates, lineshape_rates, mode='same')
np.put(convolved, below_Kmin, np.zeros(len(below_Kmin)))

return convolved



#Convolution of background and lineshape using scipy.signal.convolve
def convolved_bkgd_rate_arrays(K, Kmin, Kmax, lineshape, ls_params, min_energy, max_energy, complexLineShape):
def convolved_bkgd_rate_arrays(K, Kmin, Kmax, lineshape, ls_params, scatter_peak_ratio_p, scatter_peak_ratio_q, scatter_fraction, min_energy, max_energy, complexLineShape, resolution_function):
"""K is an array-like object
"""
energy_half_range = max(max_energy, abs(min_energy))
Expand All @@ -325,7 +372,13 @@ def convolved_bkgd_rate_arrays(K, Kmin, Kmax, lineshape, ls_params, min_energy,
elif lineshape=='simplified_scattering' or lineshape=='simplified':
lineshape_rates = simplified_ls(K_lineshape, 0, ls_params[0], ls_params[1], ls_params[2], ls_params[3], ls_params[4], ls_params[5])
elif lineshape=='detailed_scattering' or lineshape=='detailed':
lineshape_rates = complexLineShape.spectrum_func_1(K_lineshape/1000., ls_params[0], 0, 1, ls_params[1])
if resolution_function == 'simulated_resolution' or resolution_function == 'simulated':
lineshape_rates = complexLineShape.make_spectrum_simulated_resolution_scaled_fit_scatter_peak_ratio(ls_params[0], ls_params[1], scatter_peak_ratio_p, scatter_peak_ratio_p, scatter_fraction, emitted_peak='dirac')
elif resolution_function == 'gaussian_resolution' or resolution_function == 'gaussian':
lineshape_rates = complexLineShape.make_spectrum_gaussian_resolution_fit_scatter_peak_ratio(ls_params[0], ls_params[1], scatter_peak_ratio_p, scatter_peak_ratio_q, scatter_fraction, emitted_peak='dirac')
else:
logger.warn('{} is not a resolution function that has been implemented in the FakeDataGenerator'.format(resolution_function))
lineshape_rates = np.flipud(lineshape_rates)

bkgd_rates = np.full(len(K), bkgd_rate())
if len(K) < len(K_lineshape):
Expand All @@ -335,30 +388,40 @@ def convolved_bkgd_rate_arrays(K, Kmin, Kmax, lineshape, ls_params, min_energy,
convolved = convolve(bkgd_rates, lineshape_rates, mode='same')
below_Kmin = np.where(K < Kmin)
np.put(convolved, below_Kmin, np.zeros(len(below_Kmin)))

return convolved



##Fraction of events near the endpoint
##Currently, this only holds for the last 13.6 eV of the spectrum
#def frac_near_endpt(Kmin, Q, mass, atom_or_mol='atom'):
# A = integrate.quad(spectral_rate, Kmin, Q-mass, args=(Q,mass))
# B = integrate.quad(spectral_rate, V0, Q-mass, args=(Q,mass)) #Minimum at V0 because electrons with energy below screening barrier do not escape
# f = (A[0])/(B[0])
# if atom_or_mol=='atom':
# return 0.7006*f
# elif atom_or_mol=='mol' or atom_or_mol=='molecule':
# return 0.57412*f
# else:
# print("Choose 'atom' or 'mol'.")
#Fraction of events near the endpoint
def frac_near_endpt(Kmin, Q, mass, final_state_array, atom_or_mol='mol', range='wide'):
"""
Options for range:
- 'narrow': Only extends ~18 eV (or less) below the endpoint, so that all decays are to the ground state
- 'wide': Wide enough that the probability of decay to a 3He electronic energy level that would shift Q below the ROI is very low
"""
A = integrate.quad(spectral_rate, Kmin, Q-mass, args=(Q, mass, final_state_array))
B = integrate.quad(spectral_rate, V0, Q-mass, args=(Q, mass, final_state_array)) #Minimum at V0 because electrons with energy below screening barrier do not escape
f = (A[0])/(B[0])
if range=='narrow':
if atom_or_mol=='atom':
return 0.7006*f
elif atom_or_mol=='mol' or atom_or_mol=='molecule':
return 0.57412*f
else:
logger.warn("Choose 'atom' or 'mol'.")
elif range=='wide':
return f
else:
logger.warn("Choose range 'narrow' or 'wide'")


#Convert [number of particles]=(density*volume*efficiency) to a signal activity A_s, measured in events/second.
def find_signal_activity(Nparticles, m, Q, Kmin, atom_or_mol='atom', nTperMolecule=2):
taliaweiss marked this conversation as resolved.
Show resolved Hide resolved
"""
Functions to calculate number of events to generate
"""
br = frac_near_endpt(Kmin, Q, m, atom_or_mol)
br = frac_near_endpt(Kmin, Q, m, final_state_array, atom_or_mol)
Thalflife = 3.8789*10**8
A_s = Nparticles*np.log(2)/(Thalflife)*br
if atom_or_mol=='atom':
Expand All @@ -383,3 +446,17 @@ def efficiency_from_interpolation(x, efficiency_dict, B=0.9578186017836624):



def random_efficiency_from_interpolation(x, efficiency_dict, B=0.9578186017836624):
"""
Function to calculate efficiency
"""
logger.info('Sampling efficiencies before interpolation')
f = Frequency(x, B)

efficiency_mean = efficiency_dict['eff interp with slope correction']
efficiency_error = np.mean(efficiency_dict['error interp with slope correction'], axis=0)
random_efficiencies = np.random.normal(efficiency_mean, efficiency_error)
random_efficiencies[random_efficiencies<0] = 0.
interp_efficiency = interp1d(efficiency_dict['frequencies'], random_efficiencies, fill_value='0', bounds_error=False)

return interp_efficiency(f)
Loading