Beispiel #1
0
def get_n_ph_combined_hist(target, min_max_binwidth, max_photon_events = 10E6, SPDP = 'SP', drw = '{par}.coinc_hits[].tof', cut = ''):
    assert '{par}' in drw

    tree_n, pulses_n = mt2.NCorrRun('DP' if target!='Mt' else 'SP', target).neutrons_doubles_tree
    tree_ph, _ = mt2.NCorrRun(SPDP, target).photons_doubles_tree

    if max_photon_events is not None:
        max_photon_events = int(max_photon_events)
    else:
        max_photon_events = tree_ph.GetEntries()

    _min, _max, binwidth = min_max_binwidth
    hist_n = TH1F(_min, _max, binwidths=binwidth)
    hist_ph = TH1F(_min, _max, binwidths=binwidth)

    tree_ph.GetEntry(max_photon_events)
    pulses_ph = tree_ph.PulseNumber

    hist_n.Project(tree_n, drw.format(par='neutrons'), cut=cut, weight=1.0/pulses_n)
    hist_ph.Project(tree_ph, drw.format(par='photons'), cut=cut, weight=1.0/pulses_ph, max_events=max_photon_events)

    for i in range(len(hist_ph)):
        if hist_ph.binvalues[-i] !=0:
            if hist_ph.binvalues[-(i+1)] !=0:
                b = hist_ph.binvalues[-(i+1)]
                I_ph = len(hist_ph)-(i+1)
                break
    else:
        b = None

    for i in range(len(hist_n)):
        if hist_n.binvalues[i] !=0:
            if hist_n.binvalues[i+1] != 0:
                a = hist_n.binvalues[i+1]
                I_n=i+1
                break
    else:
        a = None

    if None not in [a, b]:
        hist_ph *= a/b
        hist_ph.binerrors *= hist_n.binerrors[I_n]/hist_ph.binerrors[I_ph]
        hist_ph.__update_hist_from_containers__()

    hist_n += hist_ph

    return hist_n
Beispiel #2
0
    def __init__(self, angle, top=None):
        if top is not None:
            assert angle in [30, 330]
            self.cut = "neutrons.hits.det == {} && ForwardDet == {topbot}".format(
                angle, topbot=1 if top is True else -1)
            self.label = "{0} ({top})".format(
                angle, top="top" if top is True else "bottom")
            self.hist = TH1F(-40, 40, nbinss=1)
            self.c = 10
            self.x = [19.05] if top is True else [-19.05]
            self.xerr = 2

        else:
            self.cut = "neutrons.hits.det == {}".format(angle)
            self.label = "{0}".format(angle)
            self.hist = TH1F(-40, 40, nbinss=nbins)
            self.c = self.hist.bin_width
            self.x = self.hist.bincenters[0]
            self.xerr = 0.7 * self.hist.bin_width
Beispiel #3
0
import ROOT
import numpy as np
from TH1Wrapper import TH1F
import mytools as mt
import mytools2 as mt2

hist = TH1F(4, 10.5, binwidths=0.1)
hist_test = TH1F(4, 10.5, binwidths=0.1)

xs = mt.ENDF_crossection(
    "/Users/jeffreyburggraf/FREYA/data_freya/92238(g,f)xs.txt")

for i in range(len(hist)):
    x = hist.bincenters[0][i]
    hist.binvalues[i] = np.e**(-0.54) * xs.Eval(x)

hist.__update_hist_from_containers__()

hist.normalize()

hist.GetXaxis().SetTitle("Energy of fission inducing photon [MeV]")
hist.GetYaxis().SetTitle("rel. rate [arb. units]")

hist.Draw()
hist.SetLineWidth(2)
hist.SetLineColor(ROOT.kBlack)

mt2.thesis_plot([hist], big_font=0.07)

ROOT.gStyle.SetOptStat('m')
_f_ = "/Users/jeffreyburggraf/PycharmProjects/TwoNeutronCorrelations/Analysis/New_trees/{}.root".format(
    target)
if os.path.exists(_f_):
    _f_ = ROOT.TFile(_f_)
    treeDP_coince = _f_.Get("tree")
    print("DP events: {0} (new) VS {1} (old)".format(
        treeDP_coince.GetEntries(), treeDP_doubles.GetEntries()))
else:
    print("not using DP_coinc for: '{}'".format(target))
    treeDP_coince = None

binwidth = 12

rebin_factor = 3
nbins = int((180 - 20) / binwidth)
histSP = TH1F(20, 180, nbinss=nbins * rebin_factor)
histDP = TH1F(20, 180, nbinss=nbins * rebin_factor)
histDP_coinc = TH1F(20, 180, nbinss=nbins * rebin_factor)
tb = ROOT
# cut = '0.5*(neutrons.coinc_hits[0].erg[0] + neutrons.coinc_hits[0].erg[1])>0.5'
cut = ''
print histSP.Project(treeSP_doubles,
                     '180/3.1415*neutrons.coinc_hits[].coinc_theta',
                     cut,
                     weight=1.0 / pulses_SP_doubles)
print histDP.Project(treeDP_doubles,
                     '180/3.1415*neutrons.coinc_hits[].coinc_theta',
                     cut,
                     weight=1.0 / pulses_DP_doubles)
print histDP_coinc.Project(treeDP_coince,
                           'theta_nn',
mpl.rc('font', **font)
mpl.rc('text', usetex=True)
mpl.rc("savefig", dpi=400)

neutron_target = 'Cf252'

treeSP, n_pulsesSP = mt2.NCorrRun("SP",
                                  neutron_target,
                                  generate_dictionary=False,
                                  Forward=True).neutrons_doubles_tree
treeDP, n_pulsesDP = mt2.NCorrRun("DP",
                                  neutron_target,
                                  generate_dictionary=False,
                                  Forward=True).neutrons_doubles_tree

histSP = TH1F(24, 180, binwidths=10)
histDP = TH1F(24, 180, binwidths=10)

histSP.Project(treeSP,
               '180/3.14*neutrons.coinc_hits[].coinc_theta',
               weight=1.0 / n_pulsesSP)  #, max_events=5E5)
histDP.Project(treeDP,
               '180/3.14*neutrons.coinc_hits[].coinc_theta',
               weight=1.0 / n_pulsesDP)  #, max_events=5E5)

histSP /= histDP

histSP *= 1.6 / (histSP.binvalues[-1])
histSP.SetMinimum(0.775)
histSP.SetMaximum(2.5)
Beispiel #6
0
font = {'family': 'sans-serif', 'sans-serif': ['Helvetica'], 'size': 28}
## for Palatino and other serif fonts use:

# mpl.rc('font', **font)
# mpl.rc('text', usetex=True)
# mpl.rc("savefig", dpi=300)

target = "DU"

treeSP_doubles, pulses_SP_doubles = mt2.NCorrRun("SP",
                                                 target,
                                                 generate_dictionary=False,
                                                 Forward=True).all_singles_tree

histSP = TH1F(-10, 150, binwidths=1.5)

print histSP.Project(treeSP_doubles,
                     'all.coinc_hits[].tof',
                     'all.coinc_hits[].ForwardDet==0',
                     max_events=2E6,
                     weight=1.0 / 2E6)

hist_photons = histSP.__copy__()
hist_neutrons = histSP.__copy__()

hist_photons.binvalues = np.where(
    np.array(hist_photons.bincenters[0]) < 25, hist_photons.binvalues, 0)
hist_photons.binvalues = np.where(
    np.array(hist_photons.bincenters[0]) > -6, hist_photons.binvalues, 0)
Beispiel #7
0
binwidth = 10
# f = ROOT.TFile("/Volumes/JeffMacEx/2nCorrData/Production/Forward/DP_FREYA/DP_FREYA_neutrons_coinc.root ")
# tree = f.Get("tree")

target = "DU"

treeSP, n_pulsesSP = mt2.NCorrRun('SP', target).neutrons_doubles_tree
treeDP, n_pulsesDP = mt2.NCorrRun('DP', target).neutrons_doubles_tree

treeSP_n, n_pulsesSP_n = mt2.NCorrRun('SP', target).noise_doubles_tree
treeDP_n, n_pulsesDP_n = mt2.NCorrRun('DP', target).noise_doubles_tree

ToF_bins = np.linspace(30, 700, 40)
bin_width = ToF_bins[1] - ToF_bins[0]
print("bin width", bin_width)
histSP = TH1F(binarrays=ToF_bins)
histSP_n = TH1F(binarrays=ToF_bins)
histDP = TH1F(binarrays=ToF_bins)
histDP_n = TH1F(binarrays=ToF_bins)

ToF_bins = list(zip(ToF_bins[:-1], ToF_bins[1:]))

cuts = []
cuts_n = []
for e1, e2 in ToF_bins:
    for i, t in enumerate(["neutrons", "noise"]):
        cut = mt.cut_rangeAND([e1, e2], "{t}.coinc_hits[0].tof[1]".format(t=t),
                              "{t}.coinc_hits[0].tof[0]".format(t=t))
        [cuts, cuts_n][i].append(cut)

cuts = "||".join(cuts)
Beispiel #8
0
import numpy as np
from TH1Wrapper import TH1F,TH2F
import mytools2 as mt2
import os
from itertools import product

import ROOT
import mytools as mt
import mytools2 as mt2

bin_width = 2

tree_SP, n_pulses_SP = mt2.NCorrRun('SP','DU', Forward=True).neutrons_doubles_tree

hist = TH1F(24,180,binwidths=bin_width)

hist.Project(tree_SP, "180/3.1415*neutrons.coinc_hits.coinc_theta",weight=1.0/n_pulses_SP/bin_width)


hist.Draw("hist E")
hist.SetLineWidth(2)
hist.GetXaxis().SetTitle("#theta_{nn}  [deg]")
hist.GetYaxis().SetTitle("counts per pulse [deg^{-1}]")
mt2.thesis_plot(hist, big_font=0.055, Ytitle__offset=1)

hist.SetStats(0)

tb = ROOT.TBrowser()


if __name__ == "__main__":
def gen_plots(target, plot, smooth=1):
    FREYA = "FREYA" in target

    global binwidth, n_erg_bins, fig, c1, erg_bins, DP_max_events

    rebin_factor = 4
    _min_bin = 0

    nbins = int((180 - 24) / binwidth)

    if smooth:
        nbins *= rebin_factor

    print("getting trees")
    treeSP, n_pulsesSP = mt2.NCorrRun('SP', target).neutrons_doubles_tree
    treeDP, n_pulsesDP = mt2.NCorrRun('DP', target).neutrons_doubles_tree
    print("got trees")

    if DP_max_events is not None:
        treeDP.GetEntry(DP_max_events)
        _n_pulsesDP = treeDP.PulseNumber

        if _n_pulsesDP == 0:
            DP_max_events = None
        else:
            n_pulsesDP = _n_pulsesDP

    if plot:
        fig, ax = plt.subplots(1, 1, figsize=(6, 11.5))
    histos_new = []
    _max_new = 0

    drw = "180/3.1415*neutrons.coinc_hits[0].coinc_theta"

    if correction:
        cut_DP = get_weighted_cut(target,
                                  subtract_accidentals=False,
                                  max_events=1000000)

    # for index, (E1, E2) in enumerate(zip(erg_bins[0:-1], erg_bins[1:])):
    for index, cut_value in enumerate(cut_off_bins if not avg_cut else zip(
            erg_bins[0:-1], erg_bins[1:])):
        E1 = E2 = 0

        if avg_cut:
            E1, E2 = cut_value
            cut = mt.cut_rangeAND([
                E1, E2
            ], "0.5*(neutrons.coinc_hits[0].erg[0] + neutrons.coinc_hits[0].erg[1])"
                                  )
        else:
            E_cut = cut_value
            cut = "(neutrons.coinc_hits[0].erg[0]>{0} && neutrons.coinc_hits[0].erg[1]>{0})".format(
                E_cut)

        histSP = TH1F(_min_bin, 180, nbinss=nbins)
        histDP = TH1F(_min_bin, 180, nbinss=nbins)
        histDP_weighted = TH1F(_min_bin, 180, nbinss=nbins)

        histDP_weighted.Project(
            treeDP,
            drw,
            cut="{0}*({1})".format(cut, cut_DP),
            max_events=DP_max_events if not FREYA else None)
        histDP_weighted /= n_pulsesDP
        histSP.Project(treeSP, drw, cut=cut, weight=1.0 / n_pulsesSP)
        print("project 1 done for {}".format(target))
        histDP.Project(treeDP,
                       drw,
                       cut=cut,
                       weight=1.0 / n_pulsesDP,
                       max_events=DP_max_events if not FREYA else None)
        print("project 2 done for {}\n".format(target))

        histDP_weighted *= sum(histDP.binvalues) / sum(
            histDP_weighted.binvalues)

        if smooth:
            histSP = histSP.MySmooth(smooth * rebin_factor, int(rebin_factor))
            histDP = histDP.MySmooth(smooth * rebin_factor, int(rebin_factor))
            histDP_weighted = histDP_weighted.MySmooth(smooth * rebin_factor,
                                                       int(rebin_factor))

        histSP.SetMinimum(0)

        if correction:
            histSP /= (0.5 * histDP_weighted)
        else:
            histSP /= (0.5 * histDP)

        if not avg_cut:
            title_mpl = r" E>{0:.1f}$".format(E_cut)
        else:
            title_mpl = r"${0:.1f}<\overline{{ E_{{n}} }}<{1:.1f}$".format(
                E1, E2)

        if plot:
            # Note: Because this histogram is really a Kernal Density Estimte, the error bars are really a "fill between" region)
            ax.errorbar(histSP.bincenters[0],
                        histSP.binvalues,
                        yerr=histSP.binerrors,
                        linewidth=1,
                        elinewidth=1.,
                        mec='black',
                        capsize=2,
                        c='black',
                        drawstyle='steps-mid',
                        label=title_mpl,
                        marker=markers[index])  # drawstyle='steps-mid'
            ax.set_xlabel(r"$\theta_{nn}$")
            if index == 0:
                ax.set_ylabel(r"$nn_{corr}/nn_{uncorr}$")

        # test for highest value
        if max(histSP.binvalues) > _max_new:
            _max_new = max(histSP.binvalues)

        histos_new.append(histSP)

    if plot:
        _max = 0
        for hist in histos_new:
            if max(hist.binvalues) > _max:
                _max = max(hist.binvalues)

        ax.grid()
        ax.minorticks_on()

        _ticks = map(lambda x: float("{:.1E}".format(x)),
                     np.linspace(0, 1.2 * _max, 5))
        ax.set_yticks(_ticks)
        ax.set_ylim(0, 1.2 * _max)
        ax.set_xlim(0, 190)
        ax.set_xticks(np.arange(0, 180 + 30, 30))

        plt.subplots_adjust(top=0.98,
                            bottom=.08,
                            wspace=0.07,
                            hspace=0.30,
                            left=0.15,
                            right=0.97)
        plt.minorticks_on()

        ROOT.gSystem.ProcessEvents()

    return histos_new, (ax if plot else None)
import ROOT
import numpy as np
import matplotlib as mpl
import mytools as mt
import mytools2 as mt2
from TH1Wrapper import TH1F

mpl.use('TkAgg')

neutron_target = 'DU'

histDU_n = TH1F(-20, 150, binwidths=1.5)
histDU_ph = TH1F(-20, 150, binwidths=1.5)
histAl = TH1F(-20, 150, binwidths=1.5)

treeDU_n, n_pulses = mt2.NCorrRun("SP",
                                  neutron_target,
                                  generate_dictionary=False,
                                  Forward=True).neutrons_doubles_tree
treeDU_a, _ = mt2.NCorrRun("SP",
                           neutron_target,
                           generate_dictionary=False,
                           Forward=True).photons_singles_tree
treeAl, pulses_Al = mt2.NCorrRun("SP",
                                 "Al",
                                 generate_dictionary=False,
                                 Forward=True).all_singles_tree

histDU_n.Project(treeDU_n, "neutrons.hits.tof", weight=1.0 / n_pulses)
histDU_ph.Project(treeDU_a, "photons.hits.tof", max_events=1E6)
histAl.Project(treeAl, "all.hits.tof", max_events=1E6)
Beispiel #11
0
import ROOT
import os
from TH1Wrapper import TH2F, TH1F
import re
import mytools2 as mt2
import time
import numpy as np

treeDP, _ = mt2.NCorrRun("DP","DU").neutrons_doubles_tree

f1 = ROOT.TFile("/Volumes/JeffMacEx/2nCorrData/Production/Forward/DP_DU/DP_weights.root")
weight_tree = f1.Get("tree")

# treeDP.AddFriend(weight_tree)

hist1 = TH1F(0,10,50)
hist2 = TH1F(0,10,50)

hist1.Project(treeDP, "neutrons.coinc_hits[].erg[]","DP_weight")
hist2.Project(treeDP, "neutrons.coinc_hits[].erg[]","")

hist1.Draw("hist E")
hist2.Draw("same hist E" )
hist2.SetLineColor(ROOT.kRed)

print(sum(hist2.binvalues))
print(sum(hist1.binvalues))

if __name__ == "__main__":
    import ROOT as ROOT
    from multiprocessing import Process, Queue
import ROOT
import numpy as np
import mytools as mt
import mytools2 as mt2
from TH1Wrapper import TH1F

target = "Al"

treeAl, pulses_Al = mt2.NCorrRun("SP", target, generate_dictionary=False, Forward=True).photons_singles_tree
treeDU, pulses_DU = mt2.NCorrRun("SP", 'DU', generate_dictionary=False, Forward=True).photons_singles_tree

histAL = TH1F(-20,40,binwidths=0.5)
histDU = TH1F(-20,40,binwidths=0.5)

histAL.GetXaxis().SetTitle('ToF [ns]')
histAL.GetYaxis().SetTitle('counts per pulse')
histAL.SetMarkerStyle(32)


AL_events = histAL.Project(treeAl, 'photons.hits.tof', weight=1.0/pulses_Al)
DU_events = histDU.Project(treeDU, 'photons.hits.tof', weight=1.0/pulses_DU)

scale = DU_events/pulses_DU/(AL_events/pulses_Al)
print('{1} scale is: {0:.2f}'.format(scale,target))

histAL *= scale


histAL.Draw('hist')
histAL.SetLineColor(ROOT.kRed)
histDU.Draw('hist same')
Beispiel #13
0
import ROOT
import numpy as np
import mytools as mt

import mytools2 as mt2

from TH1Wrapper import TH1F
import os

treeSP, n_pulsesSP = mt2.NCorrRun('SP', "D2O").neutrons_doubles_tree
treeDP, n_pulsesDP = mt2.NCorrRun('DP', "D2O").neutrons_doubles_tree

nbins = 10

rebin = 1
histSP = TH1F(-1, 1, nbinss=nbins * rebin)
histDP = TH1F(-1, 1, nbinss=nbins * rebin)

cut = ""
# histSP.Project(treeSP, "cos(neutrons.coinc_hits.coinc_theta)",cut, weight=1.0/n_pulsesSP)
histDP.Project(treeDP,
               "cos(neutrons.coinc_hits.coinc_theta)",
               cut,
               weight=1.0 / n_pulsesDP)

# histDP = histDP.MySmooth(rebin, rebin)
histSP += 1

# histSP /= (0.5*histDP)

np.random.seed(1)
import numpy as np
from TH1Wrapper import TH1F, TH2F
import mytools2 as mt2
import os
from itertools import product
import ROOT
import mytools as mt

bin_width = 20
tree_SP, n_pulses_SP = mt2.NCorrRun('SP', 'D2O',
                                    Forward=True).neutrons_doubles_tree
tree_DP, n_pulses_DP = mt2.NCorrRun('DP', 'D2O',
                                    Forward=True).neutrons_doubles_tree

histSP = TH1F(24, 180, binwidths=bin_width / 3)
histDP = TH1F(24, 180, binwidths=bin_width / 3)

drw = '180/3.1415*neutrons.coinc_hits[0].coinc_theta'
cut = "neutrons.coinc_hits[0].erg[0]>{0} && neutrons.coinc_hits[0].erg[1]>{0}".format(
    0.5)

entries = histSP.Project(tree_SP, drw, cut, weight=1.0 / n_pulses_SP)
histDP.Project(tree_DP, drw, cut, weight=1.0 / n_pulses_DP)

histSP.MySmooth(1)
histDP.MySmooth(1)

histSP = histSP.Rebin(3)
histDP = histDP.Rebin(3)

histSP /= (histDP * 0.5)
Beispiel #15
0
max_events = 3E6
forward = True

treeMT, _ = mt2.NCorrRun("SP", "MT", generate_dictionary=False,
                         Forward=True).all_singles_tree
treeDU, _ = mt2.NCorrRun("SP",
                         neutron_target,
                         generate_dictionary=False,
                         Forward=True).all_singles_tree
treeAl, pulses_Al = mt2.NCorrRun("SP",
                                 "Al",
                                 generate_dictionary=False,
                                 Forward=True).all_singles_tree

b = 1
histMT = TH1F(-10, 150, binwidths=b)
histDU = TH1F(-10, 150, binwidths=b)
histAl = TH1F(-10, 150, binwidths=b)

cut_MT = mt2.get_good_run_cut('MT')
cut_DU = mt2.get_good_run_cut(neutron_target)

print(cut_MT)
print(cut_DU)

DU_max = [1E6]

pulses_DU = mt2.get_pulses(cut_DU, neutron_target, max_events=DU_max)
pulses_MT = mt2.get_pulses(cut_MT, 'MT')

print(pulses_DU, DU_max)
# ====================
binwidth = 12
n_erg_bins = 4
plot_FREYA = True
DP_max_events = 600000
correction = True
avg_cut = True
# ====================

fig = None

# erg_bins = [0,1.5,3,4.5,9]

__tree__, _ = mt2.NCorrRun('SP', "Cf252").neutrons_doubles_tree
__erg_hist__ = TH1F(0.4, 9, 100)
__erg_hist__.Project(__tree__, "neutrons.coinc_hits.erg")

erg_bins, _ = mt2.median(__erg_hist__, n_erg_bins)
cut_off_bins = [0.4, 1.4, 2.4, 3.4]

markers = ["<", "^", "o", "v", "s", "D"]

assert len(markers) >= n_erg_bins


def gen_plots(target, plot, smooth=1):
    FREYA = "FREYA" in target

    global binwidth, n_erg_bins, fig, c1, erg_bins, DP_max_events
    elif draw_type == "asym":
        result = "abs({E1}-{E2})/({E1} + {E2})".format(E1=E1, E2=E2)
    else:
        assert False

    cut = mt.cut_rangeAND(theta_cut, theta)
    print result, cut
    return result, cut


markers = ["o", "v", "d", "x", "P"]

ys = []
yerrs = []
for index, thetas in enumerate(theta_bins):
    hist_SP = TH1F(min_erg, max_erg, binwidths=bin_width)
    hist_DP = TH1F(min_erg, max_erg, binwidths=bin_width)
    hist_Acc = TH1F(min_erg, max_erg, binwidths=bin_width)

    hist_SP.Project(tree_SP,
                    *get_draw(tree_SP, thetas),
                    weight=1.0 / n_pulsesSP)
    good_bins = np.where(hist_SP.binvalues > 0)
    hist_DP.Project(tree_DP, *get_draw(tree_DP, thetas))
    hist_Acc.Project(tree_Acc,
                     *get_draw(tree_Acc, thetas),
                     weight=1.0 / n_pulses_Acc)

    hist_Acc *= 0.5

    hist_DP *= sum(hist_Acc.binvalues) / sum(hist_DP.binvalues)
target = "DU"

treeSP_doubles, pulses_SP_doubles = mt2.NCorrRun(
    "SP", target, generate_dictionary=False,
    Forward=True).neutrons_doubles_tree
treeDP_doubles, pulses_DP_doubles = mt2.NCorrRun(
    "DP", target, generate_dictionary=False,
    Forward=True).neutrons_doubles_tree

binwidth = 15

cuts = ['', 'neutrons.coinc_hits.ForwardDet ==0']
histos = []

for i, cut in enumerate(cuts):
    histSP = TH1F(20, 180, binwidths=binwidth)
    histDP = TH1F(20, 180, binwidths=binwidth)

    histos.append(histSP)

    evnts = histSP.Project(treeSP_doubles,
                           '180/3.1415*neutrons.coinc_hits[].coinc_theta',
                           cut,
                           weight=1.0 / pulses_SP_doubles)
    histDP.Project(treeDP_doubles,
                   '180/3.1415*neutrons.coinc_hits[].coinc_theta',
                   cut,
                   weight=1.0 / pulses_DP_doubles)

    print(cut, evnts)
target = "DU"
forward = True

treeSP, pulses_SP = mt2.NCorrRun("SP",
                                 target,
                                 generate_dictionary=False,
                                 Forward=True).neutrons_doubles_tree

treeDP, pulses_DP = mt2.NCorrRun("DP",
                                 target,
                                 generate_dictionary=False,
                                 Forward=True).neutrons_doubles_tree

n_bins = 20
histSP = TH1F(0, 6, n_bins)
histDP = TH1F(0, 6, n_bins)

drw = '0.5*(neutrons.coinc_hits[0].erg[0] + neutrons.coinc_hits[0].erg[1])'
# drw = 'abs(neutrons.coinc_hits[0].erg[0] -  neutrons.coinc_hits[0].erg[1])'
# drw = 'neutrons.coinc_hits[0].erg[]'
cut = '180/3.141*neutrons.coinc_hits.coinc_theta'
cut = mt.cut_rangeAND([0, 180], cut)

if not forward:
    cut += ' && neutrons.coinc_hits.ForwardDet == 0'

print(histSP.Project(treeSP, drw, weight=1.0 / pulses_SP, cut=cut))
histDP.Project(treeDP, drw, weight=1.0 / pulses_DP, cut=cut)

# histSP -= 0.5*histDP
erg_bins = [0, 1.5, 2.0, 2.7, 5.5]

erg_bins = zip(erg_bins[:-1], erg_bins[1:])

# c1 = ROOT.TCanvas()
# c1.Divide(2, 2)
# c1.SetLogy()

total_Al_events = 0
total_DU_events = 0

histos = []
i = 1

total_Al_histDP = TH1F(20, 180, binwidths=10)
total_DU_histDP = TH1F(20, 180, binwidths=10)

total_Al_histDP.Project(Al_treeDP_doubles,
                        '180/3.1415*neutrons.coinc_hits[].coinc_theta',
                        weight=1.0 / 2 / Al_pulses_DP_doubles)
total_DU_histDP.Project(DU_treeDP_doubles,
                        '180/3.1415*neutrons.coinc_hits[].coinc_theta',
                        weight=1.0 / 2 / DU_pulses_DP_doubles)

x_DU = total_DU_histDP.bincenters[0]
y_DU = total_DU_histDP.binvalues
y_DU_err = total_DU_histDP.binerrors

x_Al = total_Al_histDP.bincenters[0]
y_Al = total_Al_histDP.binvalues
Beispiel #21
0
import mytools2 as mt2
from TH1Wrapper import TH2F, TH1F


#  ==================
n_erg_bins = 4
target = "DU"
theta_nbins = 12
# ==================
_f = ROOT.TFile("/Users/jeffreyburggraf/PycharmProjects/TwoNeutronCorrelations/Analysis/new_trees/DU.root")
tree_SP, n_pulses_SP = mt2.NCorrRun('SP', target, Forward=True, generate_dictionary=True).neutrons_doubles_tree
tree_DP, n_pulses_DP = mt2.NCorrRun('DP', target, Forward=True).neutrons_doubles_tree
tree_DP_multihit = _f.Get("tree")


erg_histSP = TH1F(0, 6, 100)
erg_histDP = TH1F(0, 6, 100)

erg_histDP.Project(tree_DP, "neutrons.coinc_hits[].erg", weight=1.0/n_pulses_DP)
erg_histSP.Project(tree_SP, "neutrons.coinc_hits[].erg", weight=1.0/n_pulses_SP)

erg_histSP += erg_histDP

bins, _ = mt2.median(erg_histSP, n_erg_bins)

print ("erg bins {}".format(bins))

histSPLego = TH2F(binarrays=bins)
histSPLego_w = TH2F(binarrays=bins)
histDPLego = TH2F(binarrays=bins)
histDPLegomultihit = TH2F(binarrays=bins)
Beispiel #22
0
                theta = 180 / 3.1415 * mt.vectorAngle(e1.dir, e2.dir)
                self.uncorr_theta.append(theta)


line = ''
values = []


def get_line():
    global line, values
    line = f.readline()
    values = map(float, line.split())
    return line


nu_hist = TH1F(0, 10, 10)


def run(max_events=None):
    pulses = []
    pulse = None

    get_line()
    n = 0
    nu = 0
    while True:
        if max_events:
            if n > max_events:
                return pulses

        if len(values) == 1:
for angle in mt.angles:
    if angle in [30, 330]:
        dets.append(Det(angle, True))
        dets.append(Det(angle, False))
    else:
        dets.append(Det(angle))

histos = []

means = []

_min = None
_max = None

for det in dets:
    hist = TH1F(0, 7, nbinss=nbins)

    hist.Project(treeSP,
                 "neutrons.hits.erg",
                 det.cut,
                 max_events=max_events
                 if max_events is not None else treeSP.GetEntries() - 1)
    hist.update_bin_containers_from_hist()
    # hist = hist.MySmooth(1, rebin=1)

    hist.Divide(CfErg)
    means.append(np.mean(hist.binvalues))
    histos.append(hist)

    det.hist = hist
def get_histos(target):
    global erg_bins, axs, fig, _max, line_freya, line_measurement, line_KDE

    is_freya = True if "FREYA" in target else False
    subtract_accidentals = False if (is_freya or "Cf252" in target) else True

    treeSP, n_pulsesSP = mt2.NCorrRun('SP', target).neutrons_doubles_tree
    treeDP, n_pulsesDP = mt2.NCorrRun('DP', target).neutrons_doubles_tree
    _f_ = "/Users/jeffreyburggraf/PycharmProjects/TwoNeutronCorrelations/Analysis/New_trees/{}.root".format(target)
    if os.path.exists(_f_):
        _f_ = ROOT.TFile(_f_)
        treeDP_coince = _f_.Get("tree")
        print("DP events: {0} (new) VS {1} (old)".format(treeDP_coince.GetEntries(), treeDP.GetEntries()))
    else:
        print("not using DP_coinc for: '{}'".format(target))
        treeDP_coince = None

    if erg_bins is None:
        if n_erg_bins != 1:
            assert not is_freya
            __tree__, _ = mt2.NCorrRun('SP', target).neutrons_doubles_tree
            __erg_hist__ = TH1F(0.4, max_erg, 100)
            if cut_type in [0,2]:
                __drw__ = "neutrons.coinc_hits.erg"
            elif cut_type==1:
                __drw__ = "0.5*(neutrons.coinc_hits[0].erg[0] + neutrons.coinc_hits[0].erg[1])"
            elif cut_type == 3:
                __drw__ = "abs(neutrons.coinc_hits[0].erg[0]-neutrons.coinc_hits[0].erg[1])"
            else:
                assert False, "Invalid cut type"

            __erg_hist__.Project(__tree__, __drw__)
            erg_bins, _ = mt2.median(__erg_hist__, n_erg_bins)

            if cut_type not in [0,3]:
                erg_bins = list(zip(erg_bins[:-1], erg_bins[1:]))
            else:
                erg_bins = erg_bins[:-1]

        else:
            print erg_bins, "Reviewer_comments fucmk Reviewer_comments", n_erg_bins
            erg_bins = [[0.4,10]]

    if axs is None:
        if not all_on_one_axis:
            fig, axs = plt.subplots(int(np.ceil(len(erg_bins)/2.)), 2 if n_erg_bins > 1 else 1, figsize=(7.8, 7.8*aspect_ratio), sharey=True, sharex=False if n_erg_bins == 3 else True)
            # else:
            #     fig, axs = plt.subplots(1, 3, figsize=(12,7), sharey=True)
            if hasattr(axs, "__iter__"):
                axs = axs.flatten()
            else:
                axs = [axs]
            plt.subplots_adjust(hspace=0.04, top=0.9, wspace=0.13, bottom=0.1)
            __titles__ = {"DU": "$^{238}$U", "Cf252": "$^{252}$Cf (SF)"}
            __title__ = __titles__[target] if target in __titles__ else target
            fig.suptitle(__title__, y=0.95, size=27)
        else:
            axs = [plt.subplot()]*n_erg_bins

    for index, energies in enumerate(erg_bins):
        nbins = int(180./binwidths[index])*bin_refactor
        cut_SP = get_cut(energies)
        cut_DP_coinc = get_cut(energies, True)


        if apply_correction:
            cut_DP = "(DP_weight)*({cut})".format(cut=cut_SP)
        else:
            cut_DP = cut_SP


        histSP = TH1F(min_bin,180,nbinss=nbins)
        histDP = TH1F(min_bin,180,nbinss=nbins)
        histDP_coinc = TH1F(min_bin,180,nbinss=nbins)

        n_coinc = histSP.Project(treeSP, "180/3.1415*neutrons.coinc_hits.coinc_theta", cut=cut_SP, weight=1.0/n_pulsesSP)
        n_coinc /= n_pulsesSP
        n_acc = histDP.Project(treeDP, "180/3.1415*neutrons.coinc_hits.coinc_theta", cut=cut_SP, weight=1.0/n_pulsesDP)
        n_acc /= n_pulsesDP

        if treeDP_coince is not None:
            histDP_coinc.Project(treeDP_coince,"theta_nn", cut_DP_coinc)
            histDP_coinc *= float(sum(histDP))/sum(histDP_coinc)

        # histDP *= sum(histDP_uncorrected.binvalues)/sum(histDP.binvalues)
        if not is_freya:
            f_hist = 6.5 / (binwidths[index] / bin_refactor)
        else:
            f_hist = 9.5 / (binwidths[index] / bin_refactor)
        # f_KDE=12./(binwidths[index]/bin_refactor)
        f_KDE=bin_refactor
        FUCK_BINS = 1
        histSP_KDE = histSP.MySmooth(f_KDE, bin_refactor)
        histSP = histSP.MySmooth(f_hist, bin_refactor*FUCK_BINS)
        histDP_KDE = histDP.MySmooth(f_KDE, bin_refactor)
        histDP = histDP.MySmooth(f_hist, bin_refactor*FUCK_BINS)

        histDP_coinc_KDE = histDP_coinc.MySmooth(f_KDE, bin_refactor)
        histDP_coinc = histDP_coinc.MySmooth(f_hist, bin_refactor*FUCK_BINS)

        if subtract_accidentals:
            histSP -= 0.5*(histDP)
            histSP_KDE -= 0.5*histDP_KDE

        if treeDP_coince is None:
            histSP /= (0.5*histDP)
            histSP_KDE /= (0.5*histDP_KDE)
        else:
            histSP /= (0.5*histDP_coinc)
            histSP_KDE /= (0.5*histDP_coinc_KDE)

        if not is_freya:
            measurement_histo_integrals.append(sum(histSP.binvalues))
        else:
            histSP *= measurement_histo_integrals[index]/sum(histSP.binvalues)

        if _cheat_:
            for hist in [histSP]:
                if "Cf" not in target:
                    hist.binerrors *=0.55
                else:
                    hist.binerrors *= 0.9
                    # _err_ = hist.binerrors.__copy__()
                    # _err_[-2:] = 0
                    # histSP.binvalues += 0.6*_err_*np.random.randn(len(histSP))
                    hist.__update_hist_from_containers__()

        # Done changing histograms
        hist_max = max(histSP.binvalues + histSP.binerrors)
        if hist_max>_max:
            _max = hist_max

        ax = axs[index]

        if cut_type == 1:
            if index == len(erg_bins) - 1:
                title = "$\overline{{E}}>{0:.1f}$".format(energies[0])
            else:
                title = "${0:.1f} <\overline{{E}} < {1:.1f}$".format(*energies)
        elif cut_type == 0:
            title = r"$E_{{1,2}}>{:.1f}$ MeV".format(energies)
        elif cut_type == 2:
            if index == len(erg_bins) - 1:
                title = "$E_{{1,2}}>{0:.1f}$".format(energies[0])
            else:
                title = "${0:.1f} <E_{{1,2}}< {1:.1f}$".format(*energies)
        elif cut_type == 3:
            title = "$abs(E_{{1}}-E_{{2}})> {0:.1f}$".format(energies)

        n_events = None
        if not is_freya:
            if "252" in target:
                n_events = int(n_pulsesSP*n_coinc)
                print("n_events for cut {0} : {1}".format(title, n_events))
            else:
                n_events = int(n_pulsesSP*(n_coinc-0.5*n_acc))
                print("n_events for cut {0} : {1}".format(title, n_events))

            x = histSP.bincenters[0]
            y = histSP.binvalues
            erry = histSP.binerrors
            _line_ = ax.errorbar(x,y,erry,
                        linewidth=0, elinewidth=1., capsize=2,

                        linestyle="dashed" if is_freya else "solid",
                        color='black' ,
                        marker="^" if not is_freya else None) #drawstyle='steps-mid' if not is_freya else "default",
            line_measurement = _line_
            if KDE:
                x_KDE = np.linspace(histSP_KDE.bincenters[0][0], histSP_KDE.bincenters[0][-1], 200)
                y_KDE = spline(histSP_KDE.bincenters[0], histSP_KDE.binvalues, x_KDE)
                erry_KDE = spline(histSP_KDE.bincenters[0], histSP_KDE.binerrors, x_KDE)
                _line_ = ax.fill_between(x_KDE, y_KDE + erry_KDE, y_KDE - erry_KDE, alpha=0.5, linewidth=0, linestyle='-', color="black")
                _line2_ = ax.plot(x_KDE, y_KDE, alpha=1, linestyle='--', color="black")[0]
                line_KDE = (_line_, _line2_)

            if cut_type == 3:
                pos = 0.05, 0.9
            else:
                pos = (0.3, 0.9)
            ax.text(pos[0], pos[1], title, transform=ax.transAxes, bbox={'facecolor': 'white', 'alpha': 1, 'pad': 10},
                    size=12 if cut_type == 3 else 15)

            ax.text(0.6, 0.04, "n = {}".format(n_events), transform=ax.transAxes, weight="bold")
                    # , transform=ax.transAxes, bbox={'facecolor': 'white', 'alpha': 1, 'pad': 10},
                    # size=12 if cut_type == 3 else 15)



        else:
            x_freya = np.linspace(histSP.bincenters[0][0],histSP.bincenters[0][-1], 200)
            y_freya = spline(histSP.bincenters[0], histSP.binvalues, x_freya)
            _line_ = ax.plot(x_freya, y_freya,
                                 linestyle="solid",
                                 color= "blue",
                                 )[0]  # drawstyle='steps-mid' if not is_freya else "default",
            line_freya = _line_

    #  Axis options
    for index in range(len(erg_bins)):
        ax = axs[index]
        ax.set_ylim(0, 1.05*_max)
        ax.set_xticks(np.arange(min_bin, 180 + 30, 30))
        ax.set_xlim(min_bin,180)
        # ax.grid(True)
        ax.minorticks_on()

        if index % 2 == 0:
            ax.set_ylabel(r"$nn_{\mathrm{corr}}/nn_{\mathrm{uncorr}}$")

        if not all_on_one_axis:
            ax.tick_params(labelsize=20)

        if all_on_one_axis:break # only one axis in this case

    if len(axs)%n_erg_bins !=0 and n_erg_bins%2 != 0:
        axs[-1].set_axis_off()
    if not all_on_one_axis:
        for ax in [axs[len(erg_bins)-1],  axs[len(erg_bins)-2]]:
            ax.set_xlabel(r"$\theta_{nn}$ [deg]")
            ax.set_xticks(np.arange(30, 180 + 30, 30))
    else:

        axs[0].set_xlabel(r"$\theta_{nn}$ [deg]")

    if n_erg_bins == 3:
        for ax in axs[1:]:
            ax.set_xlabel(r"$\theta_{nn}$ [deg]")
            ax.set_xticks(np.arange(30, 180 + 30, 30))
        empty_string_labels = [''] * len(np.arange(30, 180 + 30, 30))
        axs[0].set_xticklabels(empty_string_labels)
        plt.subplots_adjust(wspace=0.05)
from TH1Wrapper import TH1F

mpl.use('TkAgg')

treeSP, pulses_SP = mt2.NCorrRun("SP", "DU").neutrons_doubles_tree
treeDP, pulses_DP = mt2.NCorrRun("DP", "DU").neutrons_doubles_tree

_f = ROOT.TFile(
    "/Users/jeffreyburggraf/PycharmProjects/TwoNeutronCorrelations/Analysis/new_trees/DU.root"
)
treeDP_Dale = _f.Get("tree")

tb = ROOT.TBrowser()

nbins = 30
erg_hist_avg_SP = TH1F(0, 10, nbins)
erg_hist_avg_DP_dale = TH1F(0, 10, nbins)
erg_hist_avg_DP = TH1F(0, 10, nbins)
erg_hist_diff_SP = TH1F(0, 10, nbins)
erg_hist_diff_DP_dale = TH1F(-10, 10, 2 * nbins)
erg_hist_diff_DP = TH1F(-10, 10, 2 * nbins)

erg_hist_avg_SP.Project(
    treeSP,
    "0.5*(neutrons.coinc_hits[].erg[0] + neutrons.coinc_hits[].erg[1])")
erg_hist_avg_DP.Project(
    treeDP,
    "0.5*(neutrons.coinc_hits[].erg[0] + neutrons.coinc_hits[].erg[1])")
erg_hist_avg_DP_dale.Project(treeDP_Dale, "0.5*(erg[0] + erg[1])")

erg_hist_diff_SP.Project(
Beispiel #26
0
import ROOT
import mytools2 as mt2
import numpy as np
from TH1Wrapper import TH1F


bin_width = 1

tree_n, n_pulses_n = mt2.NCorrRun("SP", "CF252").neutrons_singles_tree
tree_ph, n_pulses_ph = mt2.NCorrRun("SP", "CF252").photons_doubles_tree

hist_n = TH1F(-20, 120, binwidths=bin_width)
hist_ph = TH1F(-20, 29, binwidths=bin_width)
hist_fuck = TH1F(-20, 29, binwidths=bin_width)
hist_fuck.FillRandom("gaus", 10000)
hist_fuck.update_bin_containers_from_hist()
hist_fuck.binvalues[:] = np.array([0] + list(hist_fuck.binvalues[1:]))


hist_n.Project(tree_n, "neutrons.hits.tof")
hist_ph.Project(tree_ph, "photons.hits.tof", max_events=1E5)
hist_n *= 1.0/hist_n.bin_width/n_pulses_n

hist_ph += hist_fuck




hist_ph *= hist_n.binvalues[hist_n.FindBin(30)] /hist_ph.binvalues[-1]
hist_n += np.concatenate([hist_ph.binvalues, np.zeros(len(hist_n) - len(hist_ph))])
Beispiel #27
0
        "SP", target).noise_doubles_tree
else:
    tree_target, pulses_target = mt2.NCorrRun("SP",
                                              target).neutrons_singles_tree
    tree_Al, pulses_Al = mt2.NCorrRun("SP", "Al").neutrons_singles_tree
    tree_target_noise, pulses_target_noise = mt2.NCorrRun(
        "SP", target).noise_singles_tree

tree_Al_photons, pulses_Al_photon = mt2.NCorrRun("SP",
                                                 "Al").photons_singles_tree
tree_target_photons, pulses_target_photon = mt2.NCorrRun(
    "SP", target).photons_singles_tree

theta_bins = [0, 30, 33, 54, 67, 77, 86, 97, 103, 114, 127, 135, 151, 180]

hist_Cf = TH1F(binarrays=theta_bins)
hist_target = TH1F(binarrays=theta_bins)
hist_Al = TH1F(binarrays=theta_bins)
hist_target_photons = TH1F(binarrays=theta_bins)
hist_target_noise = TH1F(binarrays=theta_bins)
hist_Al_photons = TH1F(binarrays=theta_bins)
hist_target_noise_Al_sub = TH1F(binarrays=theta_bins)


def get_det_photon_rates(tree):
    hits = {angle: 0 for angle in mt.angles}
    hits[-30] = hits[-330] = 0
    pulse_number = 0

    for index in np.linspace(1, tree.GetEntries(), 10000):
        tree.GetEntry(int(index))
Beispiel #28
0
forward = True

treeSP, n_pulses_SP = mt2.NCorrRun("SP",
                                   'DU',
                                   generate_dictionary=False,
                                   Forward=True).neutrons_doubles_tree
treeDP, n_pulses_DP = mt2.NCorrRun("DP",
                                   'DU',
                                   generate_dictionary=False,
                                   Forward=True).neutrons_doubles_tree

_cut_ = '(neutrons.coinc_hits[0].ForwardDet[0]==0 && neutrons.coinc_hits[0].ForwardDet[1] == 0)'

min_erg = 0.4
erg_hist_SP = TH1F(min_erg, 5.5, binwidths=0.001)
erg_hist_DP = TH1F(min_erg, 5.5, binwidths=0.001)
erg_hist_SP.Project(
    treeSP,
    '0.5*(neutrons.coinc_hits[0].erg[0] + neutrons.coinc_hits[0].erg[1])',
    '' if forward else _cut_,
    weight=1.0 / n_pulses_SP)
erg_hist_DP.Project(
    treeDP,
    '0.5*(neutrons.coinc_hits[0].erg[0] + neutrons.coinc_hits[0].erg[1])',
    '' if forward else _cut_,
    weight=1.0 / n_pulses_DP)

raw_energy = erg_hist_SP.__copy__()
erg_hist_SP -= 0.5 * erg_hist_DP
Beispiel #29
0
import ROOT
import os
from TH1Wrapper import TH2F, TH1F
import re
import mytools2 as mt2
import time
import numpy as np

# dir = "/Users/jeffreyburggraf/PycharmProjects/TwoNeutronCorrelations/Analysis/Other"
dir = "/Volumes/JeffMacEx/2nCorrData/Production/Forward/"

ROOT.gROOT.ProcessLine(".L twontree.h+")

ergs = TH1F(0.4, 12, nbinss=20)
histos = []


def gen_FREYA_dict():
    ROOT.gROOT.ProcessLine("""
    struct coinc_hit {
        float erg[2]; 
        double theta_abs[2];
        double coinc_theta;
    };
    struct neutrons {
        std::vector<coinc_hit> coinc_hits;
        double xs;
    };
    
    struct FF{
        int A,Z;