Esempio n. 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
Esempio n. 2
0
import ROOT
import numpy as np
import mytools as mt

import mytools2 as mt2

from TH1Wrapper import TH1F
import os

from collections import OrderedDict

tree_neutrons_singles, n_pulses_neutrons_singles = mt2.NCorrRun(
    'SP', "DU").neutrons_singles_tree
tree_neutrons_doubles, n_pulses_neutrons_doubles = mt2.NCorrRun(
    'SP', "DU").neutrons_doubles_tree
tree_photons_singles, n_pulses_photons_singles = mt2.NCorrRun(
    'SP', "DU").photons_singles_tree
tree_photons_doubles, n_pulses_photons_doubles = mt2.NCorrRun(
    'SP', "DU").photons_doubles_tree
print(tree_neutrons_singles.Draw("", "neutrons.ncoinc==1"), "dmfkf")
tb = ROOT.TBrowser()
singles_neutrons = OrderedDict({})
for det in mt.angles:
    topbots = [0] if det not in [30, 330] else [-1, 1]
    for topbot in topbots:
        cut = "neutrons.hits.det == {0}{1}".format(
            det, "" if topbot == 0 else
            "&& neutrons.hits.ForwardDet == {}".format(topbot))
        cut_ph = "photons.hits.det == {0}{1}".format(
            det, "" if topbot == 0 else
            "&& photons.hits.ForwardDet == {}".format(topbot))
import ROOT
import numpy as np
import mytools2 as mt2
import itertools
import mytools as mt

# =-------------------
target = "DU"
max_events = None
sliding_window_width = 40
# =-------------------
np.random.seed(1)

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

old_tree, _ = mt2.NCorrRun("SP", target).neutrons_doubles_tree


class Pulse:
    def __init__(self):
        self.ergs = [
            old_tree.neutrons.coinc_hits[0].erg[0],
            old_tree.neutrons.coinc_hits[0].erg[1]
        ]
        self.xs = [
            old_tree.neutrons.coinc_hits[0].x[0],
            old_tree.neutrons.coinc_hits[0].x[1]
        ]
        self.ys = [
            old_tree.neutrons.coinc_hits[0].y[0],
            old_tree.neutrons.coinc_hits[0].y[1]
Esempio n. 4
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)
Esempio n. 5
0
     -   (Pi**2*(1 - (x1*x2 + y1*y2 + z1*z2)**2/
     -        ((x1**2 + y1**2 + z1**2)*(x2**2 + y2**2 + z2**2)))) + 
     -  (32400*ez2**2*(-(((x1**2 + y1**2 + z1**2)*z2*(x1*x2 + y1*y2 + z1*z2))/
     -           ((x1**2 + y1**2 + z1**2)*(x2**2 + y2**2 + z2**2))**1.5) + 
     -        z1/Sqrt((x1**2 + y1**2 + z1**2)*(x2**2 + y2**2 + z2**2)))**2)/
     -   (Pi**2*(1 - (x1*x2 + y1*y2 + z1*z2)**2/
     -        ((x1**2 + y1**2 + z1**2)*(x2**2 + y2**2 + z2**2)))) + 
     -  (32400*ez1**2*(-((z1*(x1*x2 + y1*y2 + z1*z2)*(x2**2 + y2**2 + z2**2))/
     -           ((x1**2 + y1**2 + z1**2)*(x2**2 + y2**2 + z2**2))**1.5) + 
     -        z2/Sqrt((x1**2 + y1**2 + z1**2)*(x2**2 + y2**2 + z2**2)))**2)/
     -   (Pi**2*(1 - (x1*x2 + y1*y2 + z1*z2)**2/
     -        ((x1**2 + y1**2 + z1**2)*(x2**2 + y2**2 + z2**2))))"""

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

treeSP, _ = mt2.NCorrRun("SP", "DU", generate_dictionary=0,
                         Forward=True).neutrons_doubles_tree


def get_error(x1, y1, z1, x2, y2, z2, ex1, ey1, ez1, ex2, ey2, ez2):
    result = (
        32400 * ex2**2 *
        (-((x2 * (x1**2 + y1**2 + z1**2) * (x1 * x2 + y1 * y2 + z1 * z2)) /
           ((x1**2 + y1**2 + z1**2) *
            (x2**2 + y2**2 + z2**2))**1.5) + x1 / np.sqrt(
                (x1**2 + y1**2 + z1**2) * (x2**2 + y2**2 + z2**2)))**2
    ) / (np.pi**2 * (1 - (x1 * x2 + y1 * y2 + z1 * z2)**2 / (
        (x1**2 + y1**2 + z1**2) *
        (x2**2 + y2**2 + z2**2)))) + (32400 * ex1**2 * (-(
            (x1 * (x1 * x2 + y1 * y2 + z1 * z2) * (x2**2 + y2**2 + z2**2)) /
            ((x1**2 + y1**2 + z1**2) *
             (x2**2 + y2**2 + z2**2))**1.5) + x2 / np.sqrt(
Esempio n. 6
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))])
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)
Esempio n. 8
0
from TH1Wrapper import TH1F
import os
from matplotlib import pyplot as plt

import matplotlib as mpl

font = {'family': 'DejaVu Sans', 'size': 17.5}
mpl.rc('font', **font)
mpl.rc('text', usetex=True)
mpl.rc("savefig", dpi=300)

nbins = 5
max_events = None
n_plots = 2, 2

treeSP, n_pulsesSP = mt2.NCorrRun('SP', "Cf252").neutrons_doubles_tree


class Det:
    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
import ROOT
import mytools as mt
import mytools2 as mt2
import numpy as np
from TH1Wrapper import TH1F

import matplotlib as mpl

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(
Esempio n. 10
0
import ROOT
import numpy as np
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)
    "lowest": 0.75,
    "highest": 0.75,
    "divide": 0.15,
    "asym": 0.15
}[draw_type]
min_erg = {"lowest": 0.35, "highest": 0.35, "divide": 0, "asym": 0}[draw_type]
max_erg = {"lowest": 5, "highest": 8, "divide": 1, "asym": 0.9}[draw_type]
theta_bins = [100, 150, 170, 180]
plot_p_value = True
#  ===================

theta_bins = list(zip(theta_bins[:-1], theta_bins[1:]))  # + [(30, 180)]

draw_type = draw_type.lower()
tree_Acc, n_pulses_Acc = mt2.NCorrRun(
    "DP",
    "DU",
).neutrons_doubles_tree
tree_SP, n_pulsesSP = mt2.NCorrRun(
    "SP",
    "DU",
).neutrons_doubles_tree

if target == "DU":
    _f = ROOT.TFile(
        "/Users/jeffreyburggraf/PycharmProjects/TwoNeutronCorrelations/Analysis/new_trees/DU.root"
    )
    tree_DP = _f.Get("tree")
else:
    assert target == "Cf252"
    tree_DP = tree_Acc
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)

treeDU_a.GetEntry(int(1E6))
Esempio n. 13
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')
rc('text', usetex=True)


#   ====================================
erg_bin_width = 0.5
theta_bins = [150,170, 170]
make_theta_bins_distinct = True
subtract_accidentals = True
two_event_uncorr = True
perp_cut_angle = 35  # None is not using
plot_p_value = False
save_fig = True
font_size = 10
#   ====================================

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

# fig, ax = plt.subplots(1,1)
# axs = axs.flatten()

if make_theta_bins_distinct:
    if theta_bins[-1] != 180:
        theta_bins += [180]
    theta_bins = list(zip(theta_bins[:-1], theta_bins[1:]))


theta_bins = [theta_bins[0]] + [theta_bins[-1]]

def jitter(arr, p=0.04, max_n=4):
    if not hasattr(jitter, "n"):
Esempio n. 16
0
import mytools2 as mt2
import mytools as mt

from scipy.stats import gaussian_kde

import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt

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:]))
Esempio n. 17
0
import ROOT
import numpy as np
from TH1Wrapper import TH1F
import mytools2 as mt2
import mytools as mt

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

target = "D2O"
max_events = None
double_only = False

treeCf, n_pulses_Cf = mt2.NCorrRun("SP", "Cf252").neutrons_doubles_tree
treeCf_noise, _ = mt2.NCorrRun("SP", "Cf252").neutrons_doubles_tree

if double_only:
    tree_target, pulses_target = mt2.NCorrRun("SP",
                                              target).neutrons_doubles_tree
    tree_Al, pulses_Al = mt2.NCorrRun("SP", "Al").neutrons_doubles_tree
    tree_target_noise, pulses_target_noise = mt2.NCorrRun(
        "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(
Esempio n. 18
0
from TH1Wrapper import TH1F
from matplotlib import pyplot as plt
from matplotlib import pyplot as plt

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)
Esempio n. 19
0
import ROOT
import numpy as np
import matplotlib as mpl
import mytools as mt

mpl.use('TkAgg')

import mytools2 as mt2

from TH1Wrapper import TH1F

neutron_target = 'DU'
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')
from TH1Wrapper import TH1F
import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt

font = {'family': 'sans-serif', 'sans-serif': ['Helvetica'], 'size': 18}
## for Palatino and other serif fonts use:

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)
import matplotlib.pyplot as plt

# ====================
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
import ROOT
import numpy as np
import mytools as mt

import mytools2 as mt2

from TH1Wrapper import TH1F
import os

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
_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
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)
Esempio n. 24
0
import numpy as np
import mytools as mt
from collections import OrderedDict

import mytools2 as mt2

from TH1Wrapper import TH1F

from scipy.optimize import curve_fit
from numpy.polynomial.legendre import legfit
import pickle

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_,
import mytools as mt
import mytools2 as mt2
from TH1Wrapper import TH1F
import matplotlib as mpl
from matplotlib import pyplot as plt
font = {'family': 'DejaVu Sans', 'size': 16}
## for Palatino and other serif fonts use:

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

target = "Al"

Al_treeDP_doubles, Al_pulses_DP_doubles = mt2.NCorrRun(
    "DP", target, generate_dictionary=False,
    Forward=True).neutrons_doubles_tree

DU_treeDP_doubles, DU_pulses_DP_doubles = mt2.NCorrRun(
    "DP", 'DU', generate_dictionary=False, Forward=True).neutrons_doubles_tree

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