def get_n_cut(energy, angle, two_events, cut_type):
    assert cut_type in ["min", "max", "diff"]
    if two_events is False:
        erg_str = "neutrons.coinc_hits[].erg"
        theta_str = "neutrons.coinc_hits[].coinc_theta*180/3.14"
        theta_abs_str = "180/3.14*neutrons.coinc_hits[].theta_abs"
    else:
        erg_str = "erg"
        theta_str = "theta_nn"
        theta_abs_str = "180/3.14*abs_theta"

    if cut_type in ["min", "max"]:
        final_cut = "{erg_str}[0]{gtlt}{0} && {erg_str}[1]{gtlt}{0}".\
            format(energy, gtlt=">" if cut_type == "min" else "<", erg_str=erg_str)
    else:
        final_cut = "abs({erg_str}[0] - {erg_str}[1])>{0}".format(energy, erg_str=erg_str)

    if perp_cut_angle is not None:
        perp_cut = mt.cut_rangeOR([90-perp_cut_angle, 90+perp_cut_angle], "{0}[0]".format(theta_abs_str),"{0}[1]".format(theta_abs_str))
        final_cut = "{0} && ({1})".format(final_cut, perp_cut)

    if hasattr(angle,  "__iter__"):
        assert len(angle) == 2
        theta_nn_cut = mt.cut_rangeAND(angle, theta_str)
    else:
        theta_nn_cut = "{0}>{1}".format(theta_str, angle)

    final_cut = "{0} && {1}".format(final_cut, theta_nn_cut)

    return final_cut
def get_draw(tree, theta_cut):
    if hasattr(tree, "neutrons"):
        E1 = "neutrons.coinc_hits[].erg[0]"
        E2 = "neutrons.coinc_hits[].erg[1]"
        theta = "neutrons.coinc_hits[].coinc_theta*180/3.14"
        print tree

    else:
        E1 = "erg[0]"
        E2 = "erg[1]"
        theta = "theta_nn"
        print tree

    if draw_type == "lowest":
        result = "{E1}*({E1}<{E2}) + {E2}*({E2}<{E1})".format(E1=E1, E2=E2)
    elif draw_type == "highest":
        result = "{E1}*({E1}>{E2}) + {E2}*({E2}>{E1})".format(E1=E1, E2=E2)
    elif draw_type == "divide":
        result = "{E1}/{E2}*({E1}<{E2}) + {E2}/{E1}*({E2}<{E1})".format(E1=E1,
                                                                        E2=E2)
    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
def get_cut(eneries, DP_coinc=False):
    _s_ = "" if DP_coinc else "neutrons.coinc_hits[0]."
    if cut_type == 1:
        E1, E2 = tuple(eneries)
        return mt.cut_rangeAND([E1,E2],"0.5*({0}erg[0] + {0}erg[1])".format(_s_))

    elif cut_type == 0:
        assert isinstance(eneries, (float, int)), eneries
        eneries = round(eneries, 4)
        return "{1}erg[0]>{0} && {1}erg[1]>{0}".format(eneries,_s_)

    elif cut_type == 2:
        E1, E2 = tuple(map(lambda x:round(x,4),eneries))
        return mt.cut_rangeAND([E1, E2], "{0}erg[0]".format(_s_),"{0}erg[1]".format(_s_))
    elif cut_type == 3:
        E = eneries
        # return mt.cut_rangeAND([E1, E2],"abs({0}erg[0]-{0}erg[1])".format(_s_))
        return "abs({0}erg[0]-{0}erg[1])>{1}".format(_s_,E)
    else:
        assert False, "Invalid cut type! must be '1' for avg neutron energy cut or 0 for threshold cut"
Пример #4
0
Smooth = [0.6, 0.73, 0.68, 0.5]
method = 'pad'
#################################

data_dict['theta_bin_width'] = np.mean(Smooth) * bin_width

for i, (e0, e1) in enumerate(zip(erg_bins[0:-1], erg_bins[1:])):
    if isinstance(Smooth, list):
        smooth = Smooth[i]
    else:
        smooth = Smooth
    c1.cd(i + 1)
    histSP = TH1F(24, 180, binwidths=bin_width / courseness)
    histDP = TH1F(24, 180, binwidths=bin_width / courseness)
    erg_cut = '0.5*(neutrons.coinc_hits[0].erg[0] + neutrons.coinc_hits[0].erg[1])'
    erg_cut = mt.cut_rangeAND(
        [e0, e1], erg_cut) + '&& neutrons.coinc_hits.ForwardTopBot == 0'

    if not forward:
        erg_cut += ' && ' + _cut_

    drw = '180/3.1415*neutrons.coinc_hits.coinc_theta'
    n_coinc = histSP.Project(treeSP, drw, erg_cut, weight=1.0 / n_pulses_SP)
    n_accidentals = histDP.Project(treeDP,
                                   drw,
                                   erg_cut,
                                   weight=1.0 / n_pulses_DP)
    n_accidentals = int(0.5 * n_accidentals / n_pulses_DP * n_pulses_SP)

    if smooth:
        histSP.MySmooth(courseness * smooth / 2, edge_method=method)
        histDP.MySmooth(courseness * smooth / 2, edge_method=method)
Пример #5
0
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)
cuts_n = "||".join(cuts_n)

n_coince = histSP.Project(treeSP, "0", "neutrons.ncoinc == 1")
n_coince += 3 * histSP.Project(treeSP, "0", "neutrons.ncoinc == 3")
# n_coince -= 0.5*n_pulsesSP/n_pulsesDP*( histSP.Project(treeDP, "0", "neutrons.ncoinc == 1") + 2*histDP.Project(treeSP, "0", "neutrons.ncoinc == 2"))
print(n_coince)

histSP.Project(treeSP, "neutrons.coinc_hits[0].tof[0]", cuts)
histSP /= n_pulsesSP
histSP_n.Project(treeSP_n, "noise.coinc_hits[0].tof[0]", cuts_n)
histSP_n /= n_pulsesSP_n
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)
#

theta_abs_bins = []
for angle in mt.angles:
    theta_abs_bins.extend([angle - 10, angle + 10])
    if angle == 150:
        break

#  ===============
theta_range = [150, 180]
# =============

histSP = TH2F(binarrays=theta_abs_bins)
histDP = TH2F(binarrays=theta_abs_bins)

cut = mt.cut_rangeAND(theta_range,
                      'neutrons.coinc_hits[].coinc_theta*180/3.1415')

histSP.Project(
    tree_SP,
    '180/3.141*neutrons.coinc_hits[0].theta_abs[0]:180/3.141*neutrons.coinc_hits[0].theta_abs[1]',
    cut=cut,
    weight=1.0 / n_pulses_SP)
histDP.Project(
    tree_DP,
    '180/3.141*neutrons.coinc_hits[0].theta_abs[0]:180/3.141*neutrons.coinc_hits[0].theta_abs[1]',
    cut=cut,
    weight=1.0 / n_pulses_DP)

c1 = ROOT.TCanvas('c1', 'c1', 700, 700)

histSP -= 0.5 * histSP
                                 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

histDP.SetStats(0)
histSP.SetStats(0)
# ROOT.gStyle.SetOptStat('mn')

histSP.Draw()
histDP.Draw('sames')
    _hist = hist.__copy__()
    hist.transpose()
    hist += _hist
    hist.Multiply(0.5)
    for i in range(len(hist.binvalues)):
        hist.binvalues[i][i + 1:] = 0
    return hist


histos = []
n_erg_bins = 2
max_erg = 6

for i, thetas in enumerate(theta_cuts):

    cut = mt.cut_rangeAND(thetas,
                          '180/3.1415*neutrons.coinc_hits[0].coinc_theta')
    if not forward:
        cut += '&& (neutrons.coinc_hits[0].ForwardDet[0]==0 && neutrons.coinc_hits[0].ForwardDet[1]==0)'
    histSP = TH2F(0, max_erg, n_erg_bins)
    histDP = TH2F(0, max_erg, n_erg_bins)
    drw = 'neutrons.coinc_hits[0].erg[0]:neutrons.coinc_hits[0].erg[1]'

    print('SP, {0}: {1} events'.format(
        thetas, histSP.Project(tree_SP, drw, cut, weight=1.0 / n_pulses_SP)))
    print('DP, {0}: {1} events\n'.format(
        thetas, histDP.Project(tree_DP, drw, cut, weight=1.0 / n_pulses_DP)))

    transpose(histSP)
    transpose(histDP)

    histSP -= 0.5 * histDP