Пример #1
0
        def calculate_intensities():
            p = request.get_json()
            el_a = Element('', '', p["dA"], '', p["elementAId"])
            el_b = Element('', '', p["dB"], '', p["elementBId"])
            if p["advanced"] == False:
                calc = Calculation('', False, el_a, el_b, p["nA"], p["mB"], p["n"], 0, 0, 1, 1, p["theta2Min"], p["theta2Max"], None, None, None, 1.54, 0)
            else:
                calc = Calculation('', True, el_a, el_b, p["nA"], p["mB"], p["n"], p["wA"], p["wB"], p["gA"], p["gB"], 
                                   p["theta2Min"], p["theta2Max"], None, p["dA"], p["dB"], p["lambda"], p["error"])

            intensities_tuple = self.mathematics.calculate_intensities(calc)
            self.db.save_calculation(calc)
            return jsonify(
                intensities=intensities_tuple[0],
                time=intensities_tuple[1]
            )
Пример #2
0
    def get_answer(self):
        _operations = {
            "addition":"+",
            "subtraction":"-",
            "multiplication":"*",
            "division":"/"
        }
        operationText = self.math_screen.operation_text.text.lower()
        if operationText in _operations.keys():
            self.sign = _operations[operationText]

        question = self.math_screen.question_text.text.split(self.sign)
        for i in question:
            self.items_list.append(int(i))
        math = Calculation(operationText,self.items_list)
        result = math.do_calculation()
        self.math_screen.answer_text.text = result
        self.math_screen.question_text.text = ''
Пример #3
0
 def __init__(self, sp_objects: list, parent=None):
     super().__init__(parent)
     QtWidgets.qApp.installEventFilter(self)
     self.viewMatrix = None
     self.setFocus()
     self.scale_factor = 5.0E6
     self.specific_impulse_of_rocket_engine = 30000
     self.scale_x = 0
     self.scale_y = 0
     self.scale_z = 0
     self.input_pulse = 0
     self.minimum_mass = 40000
     self.current_velocity = 0
     self.current_angle = 0
     self.manual_control_delta_pulse = 2000000
     self.start_modeling = False
     self.is_trajectory_shown = False
     self.calculation_module = Calculation(sp_objects, speed=3000, dt=100)
     self.space_objects = sp_objects
Пример #4
0
    def __init__(self, root, w, h, btn, column_num):
        self.root = root
        self.width = w
        self.height = h
        self.main_colours = ["#c0c0c0", "#1d1d1b", "#2b2b2b", "#343434"]
        self.btn_list = btn
        self.column_num = column_num

        super().__init__(root, width=w, height=h)
        self.pack()
        self.set_main_ui()
        self.set_output_field()
        self.set_input_field()
        self.set_calculation_field()
        self.calc_manage = Calculation()
        root.bind('<Return>', self.result)
        root.bind('<KP_Enter>', self.result)
        root.bind('<BackSpace>', self._d_the_last)
        root.bind("<Key>", self.key)
        root.bind("<Control-q>", self.exit_win)
Пример #5
0
 def __init__(self,
              start_atoms,
              program,
              calculator,
              number,
              folder,
              number_of_relaxation,
              method,
              xc,
              lattice_constant,
              basis_set,
              charge=0,
              reference_cell=None,
              calculation_type='GEOMETRY_OPTIMIZATION',
              ice_structure_calculation=True,
              additional_atoms_calculation=False,
              directory=None,
              filename=None,
              debug=True):
     Calculation.__init__(
         self,
         start_atoms,
         program,
         calculator,
         number,
         folder,
         number_of_relaxation,
         method,
         xc,
         lattice_constant,
         basis_set,
         charge=charge,
         reference_cell=reference_cell,
         calculation_type=calculation_type,
         ice_structure_calculation=ice_structure_calculation,
         additional_atoms_calculation=additional_atoms_calculation,
         directory=directory,
         filename=filename,
         debug=debug)
Пример #6
0
    def calculate(self):
        doors = int(self.param_door.amount_doors.get())
        overlap = int(self.param_door.amount_opening.get())
        res = ''

        if doors - overlap > 1:
            text = "Вы уверены, что мест перекрытий должно быть на столько меньше, чем дверей?"
            res = mbox.askquestion("Warning", text)

        elif overlap - doors > 0:
            text = "Вы уверены, что мест перекрытий должно быть больше, чем дверей?",
            res = mbox.askquestion("Warning", text)

        if res == 'yes' or res == '':
            Calculation(self)
Пример #7
0
def create_selection_function(template, branches, *args):
    '''
    Given a function template, and the branches that are needed to do the calculation in the function, create a calculation class instance and return it.
    '''
    if len(args) > 3:
        raise ValueError(
            "Only up to three variables supported for the template function")
    if len(args) == 0:
        raise ValueError("You need to pass at least one argument")

    if len(args) == 1:
        function = lambda x, y=args[0]: template(x, y)
    if len(args) == 2:
        function = lambda x, y=args[0], z=args[1]: template(x, y, z)
    if len(args) == 3:
        function = lambda x, y=args[0], z=args[1], w=args[2]: template(
            x, y, z, w)

    function.__name__ = template.__name__ + "_".join(
        [str(arg) for arg in args])
    selection_function = Calculation(function, branches)
    return selection_function
Пример #8
0
    def update_calculation(self, id):
        query = """ WITH updated AS (
                        UPDATE calculations SET created_date = %s WHERE id = %s RETURNING *
                    )
                    SELECT updated.*, el_a.*, el_b.*
                    FROM updated
                    LEFT JOIN elements el_a ON updated.element_a_id = el_a.id 
                    LEFT JOIN elements el_b ON updated.element_b_id = el_b.id """
        conn = psycopg2.connect(**self.params)
        cur = conn.cursor()
        cur.execute(query, (datetime.datetime.now(), id))
        r = cur.fetchone()
        cur.close()
        conn.commit()
        conn.close()

        el_a = Element(r[18], r[19], r[20], r[21], r[22])
        el_b = Element(r[23], r[24], r[25], r[26], r[27])
        calc = Calculation(r[0], r[12], el_a, el_b, r[3], r[4], r[5], r[6],
                           r[7], r[8], r[9], r[10], r[11], r[13], r[14], r[15],
                           r[16], r[17])

        return calc
Пример #9
0
def create_inverse_selection_function(list_of_selections, name=None):
    '''
    Given a list of selections, create a selection that is the logical inverse of all of the selections
    '''
    #create the selection function
    branches = []
    for f in list_of_selections:
        for b in f.branches:
            if b not in branches:
                branches.append(b)

    #create the function that does the selection. Also, how slick is this! huh?
    sel_function = lambda trk, list_of_selections=list_of_selections: np.logical_not(
        np.logical_or.reduce([sel.eval(trk) for sel in list_of_selections]))

    if name == None:
        name = "_".join([s.name for s in list_of_selections])
    sel_function.__name__ = name

    #create the calculation
    sel_calculation = Calculation(sel_function, branches)

    return sel_calculation
Пример #10
0
        try:

            print(
                "================ Calculating execution time ================")
            print("** You can insert 0 at any moment to stop")
            elements = int(input("Number of elements: "))
            if elements == 0:
                break
            processing = int(
                input(
                    "Number of instructions executed by the computer per second: "
                ))
            if processing == 0:
                break

            calc = Calculation(elements, processing)

            while True:
                print("What do you want to do?")
                sort = int(
                    input(
                        "1 - Insertion Sort\n2 - Intercalation Sort\n3 - See chart\n0 - Start Over\n"
                    ))

                if sort == 0:
                    break
                elif sort == 1:
                    print("================ Insertion Sort ================")
                    print("Number of elements: {}".format(elements))
                    print(
                        "Number of instructions executed by the computer per second: {}"
Пример #11
0
from calculation import Calculation, CalculationDataMC
from variables import trkEtaPhiECAL
import numpy as np

def NoSelection(trk):
    return np.ones(len(trk)) > 0.0
branches = []
sel_NoSelection = Calculation(NoSelection, branches)

def TightIso(trk):
    return trk["trk_nearest_dR_EM"] > 0.55
sel_TightIso = Calculation(TightIso, ["trk_nearest_dR_EM"])

def HadIso(trk):
    return trk["trk_nearest_dR_HAD"] > 0.4
sel_HadIso = Calculation(HadIso, ["trk_nearest_dR_HAD"])

def pos(trk):
    return trk["trk_charge"] > 0
sel_pos_trk = Calculation(pos, ["trk_charge"])

def neg(trk):
    return np.logical_not(pos(trk))
sel_neg_trk = Calculation(neg, ["trk_charge"])

def pt_sevengev(trk):
    return trk["trk_p"] > 7.0
sel_pt_sevengev = Calculation(pt_sevengev, ["trk_p"])

def hasHADExtrapolation(trk):
    return (trk["trk_phiHEC1"] > -100) | (trk["trk_phiTileBar2"] > -100) | (trk["trk_phiTileExt1"] > -100)
Пример #12
0
    def onCalcButton(self):
        """ Start a calculation when the Calculate button pushed.
        """
        if self.ui.radioButtonGroup.checkedId() == -1:
            QMessageBox.warning(self, tr("Warning"),
                                tr("Select the type of calculation!"))
            return

        # get the selected stations
        stn1 = self.ui.Station1Combo.itemData(
            self.ui.Station1Combo.currentIndex())
        if stn1 is None:
            QMessageBox.warning(self, tr("Warning"),
                                tr("Select station point 1!"))
            self.ui.Station1Combo.setFocus()
            return
        stn2 = self.ui.Station2Combo.itemData(
            self.ui.Station2Combo.currentIndex())
        if stn2 is None and self.ui.IntersectRadio.isChecked():
            QMessageBox.warning(self, tr("Warning"),
                                tr("Select station point 2!"))
            self.ui.Station2Combo.setFocus()
            return
        if self.ui.TargetList.count() == 0:
            QMessageBox.warning(self, tr("Warning"),
                                tr("Add points to Used Points list!"))
            self.ui.TargetList.setFocus()
            return

        if self.ui.OrientRadio.isChecked():
            # orientation
            s = get_station(stn1[0], stn1[1], stn1[2])
            ref_list = []
            for i in range(self.ui.TargetList.count()):
                targetp = self.ui.TargetList.item(i).data(Qt.UserRole)
                to = get_target(targetp[0], targetp[1], targetp[2])
                tp = ScPoint(targetp[0])
                ref_list.append([tp, to])
            z = Calculation.orientation(s, ref_list)
            if z is not None:
                set_orientationangle(stn1[0], stn1[1], stn1[2],
                                     z.get_angle("GON"))
                self.ui.ResultTextBrowser.append("\n" + tr("Orientation") +
                                                 " - %s" % s.p.id)
                self.ui.ResultTextBrowser.append(
                    tr("Point num  Code         Direction    Bearing   Orient ang   Distance   e(cc) E(m)"
                       ))
                self.ui.ResultTextBrowser.append(ResultLog.resultlog_message)
                self.log.write()
                self.log.write_log(tr("Orientation") + " - %s" % s.p.id)
                self.log.write(
                    tr("Point num  Code         Direction    Bearing   Orient ang   Distance   e(cc) E(m)"
                       ))
                self.log.write(ResultLog.resultlog_message)
            else:
                QMessageBox.warning(
                    self, tr("Warning"),
                    tr("Orientation angle cannot be calculated!"))

        elif self.ui.RadialRadio.isChecked():
            # radial surveys (polar point)
            s = get_station(stn1[0], stn1[1], stn1[2])
            log_header = False
            for i in range(self.ui.TargetList.count()):
                targetp = self.ui.TargetList.item(i).data(Qt.UserRole)
                to = get_target(targetp[0], targetp[1], targetp[2])
                tp = ScPoint(targetp[0])
                p = Calculation.polarpoint(s, to)
                if p is not None:
                    # log results
                    if log_header is False:
                        self.ui.ResultTextBrowser.append("\n" +
                                                         tr("Radial Survey"))
                        self.ui.ResultTextBrowser.append(
                            tr("Point num  Code              E            N        Z     Bearing  H.Distance"
                               ))
                        self.log.write()
                        self.log.write_log(tr("Radial Survey"))
                        self.log.write(
                            tr("Point num  Code              E            N        Z     Bearing  H.Distance"
                               ))
                        log_stn = u"%-10s %-10s %12.3f %12.3f %8.3s     <station>" % \
                            (s.p.id, (s.p.pc if s.p.pc is not None else "-"), s.p.e, s.p.n, \
                            ("%8.3f"%s.p.z if s.p.z is not None else "") )
                        self.log.write(log_stn)
                        self.ui.ResultTextBrowser.append(log_stn)
                        log_header = True
                    tp.set_coord(p)
                    if p.z is None:
                        # no z calculated
                        self.ui.ResultTextBrowser.append(
                            ResultLog.resultlog_message)
                        self.log.write(ResultLog.resultlog_message)
                        tp.store_coord(2)
                    else:
                        self.ui.ResultTextBrowser.append(
                            ResultLog.resultlog_message)
                        self.log.write(ResultLog.resultlog_message)
                        tp.store_coord(3)
                else:
                    QMessageBox.warning(
                        self, tr("Warning"),
                        tr("Radial survey on %s cannot be calculated!") %
                        targetp[0])

        elif self.ui.IntersectRadio.isChecked():
            # intersection
            s1 = get_station(stn1[0], stn1[1], stn1[2])
            s2 = get_station(stn2[0], stn2[1], stn2[2])
            if stn1 == stn2:
                QMessageBox.warning(
                    self, tr("Warning"),
                    tr("Station 1 and station 2 are the same!"))
                self.ui.Station1Combo.setFocus()
                return
            log_header = False
            for i in range(self.ui.TargetList.count()):
                itemdata = self.ui.TargetList.item(i).data(Qt.UserRole)
                targetp1 = itemdata[0]
                targetp2 = itemdata[1]
                to1 = get_target(targetp1[0], targetp1[1], targetp1[2])
                tp1 = ScPoint(targetp1[0])
                to2 = get_target(targetp2[0], targetp2[1], targetp2[2])
                #tp2 = ScPoint(targetp2[0])
                p = Calculation.intersection(s1, to1, s2, to2)
                if p is not None:
                    # log results
                    if log_header is False:
                        self.ui.ResultTextBrowser.append("\n" +
                                                         tr("Intersection"))
                        self.ui.ResultTextBrowser.append(
                            tr("Point num  Code              E            N     Bearing1 Bearing2"
                               ))
                        self.log.write()
                        self.log.write_log(tr("Intersection"))
                        self.log.write(
                            tr("Point num  Code              E            N     Bearing1 Bearing2"
                               ))

                        log_stn = u"%-10s %-10s %12.3f %12.3f     <station>\n" % \
                            (s1.p.id, (s1.p.pc if s1.p.pc is not None else "-"), s1.p.e, s1.p.n)
                        log_stn += u"%-10s %-10s %12.3f %12.3f     <station>" % \
                            (s2.p.id, (s2.p.pc if s2.p.pc is not None else "-"), s2.p.e, s2.p.n)
                        self.log.write(log_stn)
                        self.ui.ResultTextBrowser.append(log_stn)
                        log_header = True
                    tp1.set_coord(p)
                    tp1.store_coord(2)
                    self.ui.ResultTextBrowser.append(
                        ResultLog.resultlog_message)
                    self.log.write(ResultLog.resultlog_message)
                else:
                    QMessageBox.warning(
                        self, tr("Warning"),
                        tr("Intersecion on %s cannot be calculated!") %
                        targetp1[0])

        elif self.ui.ResectionRadio.isChecked():
            # resection
            s = get_station(stn1[0], stn1[1], stn1[2])
            if self.ui.TargetList.count() != 3:
                QMessageBox.warning(
                    self, tr("Warning"),
                    tr("Select exactly 3 used points for resection!"))
                self.ui.TargetList.setFocus()
                return
            targetp1 = self.ui.TargetList.item(0).data(Qt.UserRole)
            targetp2 = self.ui.TargetList.item(1).data(Qt.UserRole)
            targetp3 = self.ui.TargetList.item(2).data(Qt.UserRole)
            to1 = get_target(targetp1[0], targetp1[1], targetp1[2])
            to2 = get_target(targetp2[0], targetp2[1], targetp2[2])
            to3 = get_target(targetp3[0], targetp3[1], targetp3[2])
            tp1 = ScPoint(targetp1[0])
            tp2 = ScPoint(targetp2[0])
            tp3 = ScPoint(targetp3[0])
            p = Calculation.resection(s, tp1, tp2, tp3, to1, to2, to3)
            ScPoint(p).store_coord(2)
            # result log
            self.ui.ResultTextBrowser.append("\n" + tr("Resection"))
            self.ui.ResultTextBrowser.append(
                tr("Point num  Code                E            N      Direction  Angle"
                   ))
            self.ui.ResultTextBrowser.append(ResultLog.resultlog_message)
            self.log.write()
            self.log.write_log(tr("Resection"))
            self.log.write(
                tr("Point num  Code                E            N      Direction  Angle"
                   ))
            self.log.write(ResultLog.resultlog_message)
        elif self.ui.FreeRadio.isChecked():
            # free station
            g = GamaInterface()  # default standard deviations are used!
            s = get_station(stn1[0], stn1[1], stn1[2])
            g.add_point(s.p, 'ADJ')
            g.add_observation(s.o)
            for i in range(self.ui.TargetList.count()):
                targetp = self.ui.TargetList.item(i).data(Qt.UserRole)
                p = get_coord(targetp[0])
                g.add_point(p, 'FIX')
                to = get_target(targetp[0], targetp[1], targetp[2])
                g.add_observation(to)
            t = g.adjust()
            if t is None:
                # adjustment failed
                self.ui.ResultTextBrowser.append(
                    tr('gama-local not installed or other runtime error'))
            else:
                self.ui.ResultTextBrowser.append(t)
Пример #13
0
	def __init__(self):
		Calculation.__init__(self)
Пример #14
0
def fill_histograms(hist_filler, outputRootFileName):
    #import thje variables that we want to plot
    from variables import calc_trkNearestNeighbourEM2, calc_trkP, calc_EOP, calc_trkPt, calc_trkAverageMu, calc_trkEtaID, calc_trkEtaECAL, calc_trkNPV2, calc_trkCount, calc_trkNClusters, calc_trkNClusters_EM, calc_trkNClusters_HAD, calc_trkNClusters_emlike, calc_trkNClusters_hadlike, calc_TruthMomentum
    from selections import sel_HadIso
    from reweightings import book_reweighting
    hist_filler.apply_selection_for_channel(
        "LowMuDataTightIso", sel_TightIso)  #Tighter isolation requirement
    hist_filler.apply_selection_for_channel(
        "PythiaJetJetTightIso", sel_TightIso)  #Tighter isolation requirement
    hist_filler.apply_selection_for_channel(
        "PythiaJetJetHardScatter",
        sel_Truth)  #Those tracks truth matched to pions
    hist_filler.apply_selection_for_channel(
        "PythiaJetJetHardScatterTightIso",
        sel_Truth + sel_TightIso)  #Tighter isolation requirement
    book_reweighting(hist_filler, "nominal")
    hist_filler.create_subchannel_for_channel("PythiaJetJetHardScatterPion",
                                              "PythiaJetJetHardScatter",
                                              pion_selections)
    hist_filler.create_subchannel_for_channel("PythiaJetJetHardScatterPionPos",
                                              "PythiaJetJetHardScatter",
                                              pion_pos_selections)
    hist_filler.create_subchannel_for_channel("PythiaJetJetHardScatterPionNeg",
                                              "PythiaJetJetHardScatter",
                                              pion_neg_selections)
    hist_filler.create_subchannel_for_channel("PythiaJetJetHardScatterKaonPos",
                                              "PythiaJetJetHardScatter",
                                              kaon_pos_selections)
    hist_filler.create_subchannel_for_channel("PythiaJetJetHardScatterKaonNeg",
                                              "PythiaJetJetHardScatter",
                                              kaon_neg_selections)
    hist_filler.create_subchannel_for_channel(
        "PythiaJetJetHardScatterProtonPos", "PythiaJetJetHardScatter",
        proton_pos_selections)
    hist_filler.create_subchannel_for_channel(
        "PythiaJetJetHardScatterProtonNeg", "PythiaJetJetHardScatter",
        proton_neg_selections)
    hist_filler.create_subchannel_for_channel("PythiaJetJetHardScatterOther",
                                              "PythiaJetJetHardScatter",
                                              other_selections)
    outFile = ROOT.TFile(outputRootFileName, "RECREATE")

    #count the number of tracks in each channel
    histogram_name = "trkCount"
    selections = []
    trkCountHist = hist_filler.book_histogram_fill(histogram_name,\
                                                         calc_trkCount,\
                                                         selections = selections,\
                                                         bins = 1,\
                                                         range_low = -0.5,\
                                                         range_high = +0.5,\
                                                         xlabel ='Always 0',\
                                                         ylabel = 'Number of Tracks')

    #count the number of events in each channel
    histogram_name = "EventCount"
    selections = [sel_Event]
    trkCountHist = hist_filler.book_histogram_fill(histogram_name,\
                                                         calc_trkCount,\
                                                         selections = selections,\
                                                         bins = 1,\
                                                         range_low = -0.5,\
                                                         range_high = +0.5,\
                                                         xlabel ='Always 0',\
                                                         ylabel = 'Number Events')

    ################################################################################
    #plot the trk avaerage mu histogram
    histogram_name = "trkAverageMu"
    selections = []
    trkAverageMuHist = hist_filler.book_histogram_fill(histogram_name,\
                                                        calc_trkAverageMu,\
                                                        selections = selections,\
                                                        bins = 10,\
                                                        range_low = 0.0,\
                                                        range_high = 10.0,\
                                                        xlabel ='Average #mu of Event',\
                                                        ylabel = 'Number of Tracks')

    ################################################################################
    #plot a histogram of track NPV w/ 2 tracks
    histogram_name = "trkNPV2"
    trkNPV2Hist = hist_filler.book_histogram_fill(histogram_name,\
                                       calc_trkNPV2,\
                                       selections = [],\
                                       bins = 13,\
                                       range_low = -0.5,\
                                       range_high = 12.5,\
                                       xlabel ="NPV with 2 Tracks",\
                                       ylabel = "Number of Tracks")

    #   ################################################################################
    #plot a histogram of the average event NPV
    histogram_name = "eventNPV2Hist"
    eventNPV2Hist = hist_filler.book_histogram_fill(histogram_name,\
                                       calc_trkNPV2,\
                                       selections = [sel_Event],\
                                       bins = 13,\
                                       range_low = -0.5,\
                                       range_high = 12.5,\
                                       xlabel ="NPV with 2 Tracks",\
                                       ylabel = "Number Events")

    #   ################################################################################
    histogram_name = "eventAverageMu"
    selections = [sel_Event]
    eventAverageMuHist = hist_filler.book_histogram_fill(histogram_name,
                                          calc_trkAverageMu,\
                                          selections = selections,\
                                          bins = 10,\
                                          range_low = 0.0,\
                                          range_high = 10.0,\
                                          xlabel ='<#mu>',\
                                          ylabel = 'Number of Events')

    #    ################################################################################
    #plot the pt spectra of the tracks from 0.0 to 30.0 GeV
    #prepare the momentum bins
    binMax = 30.0
    binMin = 0.5
    nBins = 100
    p_bins = get_log_bins(binMin, binMax, nBins)
    p_bins_reference = p_bins
    histogram_name = "trkPtHist"
    hist_filler.book_histogram_fill(histogram_name,\
                                       calc_trkPt,\
                                       selections = [],\
                                       bins = p_bins,\
                                       xlabel ="Track P_{T} [GeV]",\
                                       ylabel = "Number of Tracks")

    hist_filler.book_histogram_fill(histogram_name + "HasExtrapolation",\
                                       calc_trkPt,\
                                       selections = [sel_hasHADExtrapolation],\
                                       bins = p_bins,\
                                       xlabel ="Track P_{T} [GeV]",\
                                       ylabel = "Number of Tracks")

    #    ################################################################################
    binMax = 30.0
    binMin = 0.5
    nBins = 50
    p_bins = get_log_bins(binMin, binMax, nBins)
    p_bins_reference = p_bins
    histogram_name = "LeadingPtTrkHist"
    trkPtHistZoom = hist_filler.book_histogram_fill(histogram_name,\
                                       calc_trkPt,\
                                       selections = [sel_Event],\
                                       bins = p_bins,\
                                       xlabel ="Track P_{T} [GeV]",\
                                       ylabel = "Number of Tracks")

    #    ################################################################################
    #prepare the momentum bins
    binMax = 30.0
    binMin = 0.5
    nBins = 50
    p_bins = get_log_bins(binMin, binMax, nBins)
    p_bins_reference = p_bins
    histogram_name = "SubleadingPtTrkHist"
    trkPtHistZoom = hist_filler.book_histogram_fill(histogram_name,\
                                       calc_trkPt,\
                                       selections = [sel_SubleadingTrack],\
                                       bins = p_bins,\
                                       xlabel ="Track P_{T} [GeV]",\
                                       ylabel = "Number of Tracks")

    from variables import calc_trkEtaECAL, calc_trkPhiECAL
    from selections import PBin, sel_NonZeroEnergy
    p_bin_selection = create_selection_function(PBin, ["trk_p"], 3., 4.)
    histogram_name = "TrkEtaPhiEMCal_MomentumBetween3And4GeV_Denomenator"
    hist_filler.book_2dhistogram_fill(histogram_name,\
                            calc_trkEtaECAL,\
                            calc_trkPhiECAL,\
                            selections=[p_bin_selection],\
                            bins_x = 200,\
                            bins_y = 200,\
                            range_low_y = -3.14,\
                            range_high_y = +3.14,\
                            range_low_x = -2.5,\
                            range_high_x = +2.5,\
                            xlabel = "#eta_{EMCal}",\
                            ylabel = "#phi_{EMCal}",\
                            zlabel = "Number of Tracks")

    histogram_name = "TrkEtaPhiEMCal_MomentumBetween3And4GeV_Numerator"
    hist_filler.book_2dhistogram_fill(histogram_name,\
                            calc_trkEtaECAL,\
                            calc_trkPhiECAL,\
                            selections=[p_bin_selection, sel_NonZeroEnergy],\
                            bins_x = 200,\
                            bins_y = 200,\
                            range_low_y = -3.14,\
                            range_high_y = +3.14,\
                            range_low_x = -2.5,\
                            range_high_x = +2.5,\
                            xlabel = "#eta_{EMCal}",\
                            ylabel = "#phi_{EMCal}",\
                            zlabel = "Number of Tracks")

    #try between 2 and 3 GeV

    p_bin_selection = create_selection_function(PBin, ["trk_p"], 2., 3.)
    histogram_name = "TrkEtaPhiEMCal_MomentumBetween2And3GeV_Denomenator"
    hist_filler.book_2dhistogram_fill(histogram_name,\
                            calc_trkEtaECAL,\
                            calc_trkPhiECAL,\
                            selections=[p_bin_selection],\
                            bins_x = 200,\
                            bins_y = 200,\
                            range_low_y = -3.14,\
                            range_high_y = +3.14,\
                            range_low_x = -2.5,\
                            range_high_x = +2.5,\
                            xlabel = "#eta_{EMCal}",\
                            ylabel = "#phi_{EMCal}",\
                            zlabel = "Number of Tracks")

    histogram_name = "TrkEtaPhiEMCal_MomentumBetween2And3GeV_Numerator"
    hist_filler.book_2dhistogram_fill(histogram_name,\
                            calc_trkEtaECAL,\
                            calc_trkPhiECAL,\
                            selections=[p_bin_selection, sel_NonZeroEnergy],\
                            bins_x = 200,\
                            bins_y = 200,\
                            range_low_y = -3.14,\
                            range_high_y = +3.14,\
                            range_low_x = -2.5,\
                            range_high_x = +2.5,\
                            xlabel = "#eta_{EMCal}",\
                            ylabel = "#phi_{EMCal}",\
                            zlabel = "Number of Tracks")

    ################################################################################
    histogramName = "TrackEtaID"
    hist_filler.book_histogram_fill(histogramName,\
                                       calc_trkEtaID,\
                                       selections = [],\
                                       bins = 100,\
                                       range_low = -5,\
                                       range_high = +5,\
                                       xlabel ="Track #eta ID",\
                                       ylabel = "Number of Tracks")

    #   ################################################################################
    histogramName = "TwoDTrackPvsTrkEtaID"
    max_bin = 2.4
    min_bin = -2.4
    nBins = 48
    eta_bins = get_bins(min_bin, max_bin, nBins)
    hist_filler.book_2dhistogram_fill(histogramName,\
                                             calc_trkEtaID,\
                                             calc_trkP,\
                                             selections=[],\
                                             bins_x=eta_bins,\
                                             xlabel="Track #eta ID",\
                                             bins_y=p_bins,\
                                             ylabel="Track P [GeV]",\
                                             zlabel="Number of Tracks",\
                                             )

    #   ################################################################################
    histogramName = "TwoDTrackPtVsEtaHistogram"
    hist_filler.book_2dhistogram_fill(histogramName,\
                                             calc_trkEtaID,\
                                             calc_trkPt,\
                                             selections=[],\
                                             bins_x=eta_bins,\
                                             xlabel="Track #eta ID",\
                                             bins_y=p_bins,\
                                             ylabel="Track P_{T} [GeV]",\
                                             zlabel="Number of Tracks",\
                                             )

    #   ################################################################################
    histogramName = "TwoDTrackPtVsEtaHistogram_HasExtrapolation"
    hist_filler.book_2dhistogram_fill(histogramName,\
                                             calc_trkEtaID,\
                                             calc_trkPt,\
                                             selections=[sel_hasHADExtrapolation],\
                                             bins_x=eta_bins,\
                                             xlabel="Track #eta ID",\
                                             bins_y=p_bins,\
                                             ylabel="Track P_{T} [GeV]",\
                                             zlabel="Number of Tracks",\
                                             )

    #   ################################################################################
    histogramName = "trkEtaECALHist"
    hist_filler.book_histogram_fill(histogramName,\
                                          calc_trkEtaECAL,
                                          selections = [],
                                          bins = 100,
                                          range_low = -5,
                                          range_high = +5,
                                          xlabel ="Track #eta EM Layer 2",
                                          ylabel = "Number of Tracks",
                                       )

    #   ################################################################################
    histogramName = "TwoDHistTrkPvsPhiInnerToExtrapolEM2"
    dPhi_bins = []
    min_bin = 0.0
    max_bin = pi
    NBins = 100
    dPhi_bins = get_bins(min_bin, max_bin, NBins)

    from variables import calc_trkDPhi
    hist_filler.book_2dhistogram_fill(histogramName,\
                                             calc_trkDPhi,\
                                             calc_trkPt,\
                                             selections=[],\
                                             bins_x=dPhi_bins,\
                                             xlabel="|#phi_{ID} - #phi_{EM2}|",\
                                             bins_y=p_bins,\
                                             ylabel="Track P_{T} [GeV]",\
                                             zlabel="Number of Tracks",\
                                             )

    #   ################################################################################
    histogramName = "lowPTLess07_TwoDHistTrkEtavsDEtaInnerToExtrapolEM2"
    from variables import calc_trkDEta
    from calculation import Calculation

    def lowPT(trk):
        return trk["trk_pt"] < 0.7

    branches = ["trk_pt"]
    sel_lowPT = Calculation(lowPT, branches)
    hist_filler.book_2dhistogram_fill(histogramName,\
                                             calc_trkEtaID,\
                                             calc_trkDEta,\
                                             selections=[sel_lowPT],\
                                             bins_x=50,\
                                             range_low_x=-2.5,\
                                             range_high_x=+2.5,\
                                             xlabel="Track #eta_{ID}",\
                                             bins_y=50,\
                                             range_low_y=0.0,\
                                             range_high_y=1.0,\
                                             ylabel="|#eta_{ID} - #eta_{EM2}|",\
                                             zlabel="Number of Tracks",\
                                             )

    #   ################################################################################
    from calculation import Calculation
    from selections import EtaBin
    sel_Eta00_08 = create_selection_function(EtaBin, ["trk_etaID"], 0.0, 0.8)
    histogramName = "EtaLess08_TwoDHistTrkPvsPhiInnerToExtrapolEM2"
    hist_filler.book_2dhistogram_fill(histogramName,\
                                             calc_trkDPhi,\
                                             calc_trkPt,\
                                             selections=[sel_Eta00_08],\
                                             bins_x=dPhi_bins,\
                                             xlabel="|#phi_{ID} - #phi_{EM2}|",\
                                             bins_y=p_bins,\
                                             ylabel="Track P_{T} [GeV]",\
                                             zlabel="Number of Tracks",\
                                             )

    #    ################################################################################
    histogramName = "NearestDRHist"
    hist_filler.book_histogram_fill(
        histogramName,
        calc_trkNearestNeighbourEM2,
        selections=[],
        bins=25,
        range_low=0.0,
        range_high=5,
        xlabel="dR to Nearest Track",
        ylabel="Number of Tracks",
    )

    from selections import sel_Lar1_1GeV, sel_EHadBetween30And90OfMomentum
    sel_NTRT20 = create_selection_function(NTRTX, ["trk_nTRT"], 20.0, 100000.0)
    MIP_selection = [
        sel_NTRT20, sel_Lar1_1GeV, sel_EHadBetween30And90OfMomentum
    ]

    ################################################################################
    selections = []
    histogramName = "InclusiveEOP"
    hist_filler.book_histogram_fill(histogramName,\
                                     calc_EOP,
                                     selections = selections,
                                     bins = 50,
                                     range_low = -1,
                                     range_high = 5,
                                     xlabel ="E/p",
                                     ylabel = "Number of Tracks",
                                     )

    ################################################################################
    from selections import sel_NonZeroEnergy
    selections = [sel_NonZeroEnergy]
    histogramName = "NonZeroEnergy_InclusiveEOP"
    hist_filler.book_histogram_fill(histogramName,\
                                     calc_EOP,
                                     selections = selections,
                                     bins = 50,
                                     range_low = -1,
                                     range_high = 5,
                                     xlabel ="E/p",
                                     ylabel = "Number of Tracks",
                                     )

    ################################################################################
    # This is figure 3a in the paper:

    selections = []
    binMax = 10.05
    binLow = 0.5
    nBins = 15
    bins = get_log_bins(binLow, binMax, nBins)

    histogramName = "InclusiveZeroFractionVsPDenomenator"
    hist_filler.book_histogram_fill(histogramName,\
                                          calc_trkP,\
                                          selections = selections,\
                                          bins = bins,\
                                          xlabel ="Track P [GeV]",\
                                          ylabel = "Number of Tracks",\
                                          )

    from selections import sel_ELessEqual0
    histogramName = "InclusiveZeroFractionVsPNumerator"
    selections = [sel_ELessEqual0]
    hist_filler.book_histogram_fill(histogramName,\
                                                    calc_trkP,\
                                                    selections = selections,\
                                                    bins = bins,\
                                                    xlabel ="Track P [GeV]",\
                                                    ylabel = "N(E<=0)/N",\
                                                    )

    ################################################################################
    #This is figure 3b of the paper
    bins = [
        -2.3, -1.8, -1.5, -1.4, -1.1, -0.6, 0.0, 0.6, 1.1, 1.4, 1.5, 1.8, 2.3
    ]
    selections = []
    histogramName = "InclusiveZeroFractionVsEtaDenomenator"
    hist_filler.book_histogram_fill(histogramName,\
                                              calc_trkEtaID,\
                                              selections = selections,\
                                              bins = bins,\
                                              xlabel ="Track |#eta|",\
                                              ylabel = "Number of Tracks",\
                                              )
    from selections import sel_ELessEqual0
    histogramName = "InclusiveZeroFractionVsEtaNumerator"
    selections = [sel_ELessEqual0]
    hist_filler.book_histogram_fill(histogramName,\
                                                   calc_trkEtaID,\
                                                   selections = selections,\
                                                   bins = bins,\
                                                   xlabel ="Track |#eta|",\
                                                   ylabel = "N(E<=0)/N",\
                                                   )

    ################################################################################
    bins = [0.0, 0.6, 1.1, 1.4, 1.5, 1.8, 2.3]
    from variables import calc_trkEta_ABS
    selections = []
    histogramName = "InclusiveZeroFractionVsAbsEtaDenomenator"
    hist_filler.book_histogram_fill(histogramName,\
                                              calc_trkEta_ABS,\
                                              selections = selections,\
                                              bins = bins,\
                                              xlabel ="Track |#eta|",\
                                              ylabel = "Number of Tracks",\
                                              )
    from selections import sel_ELessEqual0
    histogramName = "InclusiveZeroFractionVsAbsEtaNumerator"
    selections = [sel_ELessEqual0]
    hist_filler.book_histogram_fill(histogramName,\
                                                   calc_trkEta_ABS,\
                                                   selections = selections,\
                                                   bins = bins,\
                                                   xlabel ="Track |#eta|",\
                                                   ylabel = "N(E<=0)/N",\
                                                   )

    ################################################################################
    from variables import calc_trkEta_ABS
    from selections import EtaBin

    canvases = []
    keep_histograms_alive = []
    for (eta_bin_selection, eta_bin_description,
         eta_bin_edge) in zip(eta_bin_selections, eta_bin_descriptions,
                              eta_bin_tuples):
        center = (eta_bin_edge[0] + eta_bin_edge[1]) / 2.0
        binMax = 30.05
        binLow = get_p(0.5, center)
        nBins = 20
        bins = get_log_bins(binLow, binMax, nBins)

        #do the eta selection and count the inclusive number of tracks in the bin
        selections = [eta_bin_selection]
        histogramName = "ZeroFractionVsP" + eta_bin_description + "Denomenator"
        hist_filler.book_histogram_fill(histogramName,\
                                                  calc_trkP,\
                                                  selections = selections,\
                                                  bins = bins,\
                                                  xlabel ="Track P [GeV]",\
                                                  ylabel = "Number of tracks",\
                                                  )

        #do the eta selections and count the number of tracks with an energy deposity less than or equal to 0.0.
        from selections import sel_ELessEqual0
        selections = [sel_ELessEqual0] + [eta_bin_selection]
        histogramName = "ZeroFractionVsP" + eta_bin_description + "Numerator"
        hist_filler.book_histogram_fill(histogramName,\
                                                       calc_trkP,\
                                                       selections = selections,\
                                                       bins = bins,\
                                                       xlabel ="Track P [GeV]",\
                                                       ylabel = "N(E<=0)/N",\
                                                       )

    ################################################################################
    from variables import calc_trkEta_ABS
    base_description = ["N_{TRT hits} >= 20"]

    for (eta_bin_selection, eta_bin_description,
         eta_bin_edge) in zip(eta_bin_selections, eta_bin_descriptions,
                              eta_bin_tuples):
        center = (eta_bin_edge[0] + eta_bin_edge[1]) / 2.0
        binMax = 30.05
        binLow = get_p(0.5, center)
        nBins = 20
        bins = get_log_bins(binLow, binMax, nBins)

        #do the eta selection and count the inclusive number of tracks in the bin
        selections = [eta_bin_selection] + [sel_NTRT20]
        histogramName = "NTRT20ZeroFractionVsP" + eta_bin_description + "Denomenator"
        hist_filler.book_histogram_fill(histogramName,\
                                                  calc_trkP,\
                                                  selections = selections,\
                                                  bins = bins,\
                                                  xlabel ="Track P [GeV]",\
                                                  ylabel = "Number of tracks",\
                                                  )

        #do the eta selections and count the number of tracks with an energy deposity less than or equal to 0.0.
        from selections import sel_ELessEqual0
        selections = [sel_ELessEqual0] + [eta_bin_selection] + [sel_NTRT20]
        histogramName = "NTRT20ZeroFractionVsP" + eta_bin_description + "Numerator"
        hist_filler.book_histogram_fill(histogramName,\
                                                       calc_trkP,\
                                                       selections = selections,\
                                                       bins = bins,\
                                                       xlabel ="Track P [GeV]",\
                                                       ylabel = "N(E<=0)/N",\
                                                       )

    ################################################################################
    ##Create a set of p and eta bins for the measurement ##########################

    from selections import EtaBin, PBin
    from variables import calc_EOPBkg, calc_EnergyAnulus
    from selections import sel_NonZeroEnergy, sel_HardScatter

    ##select inclusive distributions
    ##Create a set of binned EOP response histograms
    #eta_ranges = eta_bin_tuples
    #base_selection = [sel_NTRT20, sel_Lar1_1GeV, sel_EHadBetween30And90OfMomentum]
    #p_bins_for_eta_range = []
    #for eta_range in eta_bin_tuples:
    #    p_bins_min = get_p(0.5, (eta_range[0] + eta_range[1]) / 2.0)
    #    p_bins = get_log_bins(p_bins_min, 30.05, 15)
    #    p_bins_for_eta_range.append(p_bins)
    #description = "MIPSelectionBetween30and90OfMomentum"
    #put_binning_vectors_in_file(outFile, eta_ranges, p_bins_for_eta_range, description)
    #create_eop_histograms(hist_filler, base_selection, eta_ranges, p_bins_for_eta_range, description)

    from selections import sel_EHadFracAbove70, sel_Lar1_1GeV
    eta_ranges = eta_bin_tuples
    base_selection = [sel_EHadFracAbove70, sel_NTRT20, sel_Lar1_1GeV]
    p_bins_for_eta_range = []
    for eta_range in eta_ranges:
        p_bins_min = get_p(0.5, (eta_range[0] + eta_range[1]) / 2.0)
        p_bins = get_log_bins(p_bins_min, 30.05, 15)
        p_bins_for_eta_range.append(p_bins)
    description = "MIPSelectionHadFracAbove70"
    put_binning_vectors_in_file(outFile, eta_ranges, p_bins_for_eta_range,
                                description)
    create_eop_histograms(hist_filler, base_selection, eta_ranges,
                          p_bins_for_eta_range, description)

    eta_ranges = eta_bin_tuples
    base_selection = [sel_NTRT20, sel_NonZeroEnergy]
    p_bins_for_eta_range = []
    for eta_range in eta_ranges:
        p_bins_min = get_p(0.5, (eta_range[0] + eta_range[1]) / 2.0)
        p_bins = get_log_bins(p_bins_min, 30.05, 15)
        p_bins_for_eta_range.append(p_bins)
    description = "20TRTHitsNonZeroEnergy"
    put_binning_vectors_in_file(outFile, eta_ranges, p_bins_for_eta_range,
                                description)
    create_eop_histograms(hist_filler, base_selection, eta_ranges,
                          p_bins_for_eta_range, description)
    p_bins_for_eta_range = []
    for eta_range in eta_ranges:
        p_bins_min = get_p(0.5, (eta_range[0] + eta_range[1]) / 2.0)
        p_bins = get_log_bins(p_bins_min, 40.05, 300)
        p_bins_for_eta_range.append(p_bins)
    create_spectrum_plots(hist_filler, base_selection, eta_ranges,
                          p_bins_for_eta_range, description)

    eta_ranges = eta_bin_tuples
    base_selection = [sel_NTRT20]
    p_bins_for_eta_range = []
    for eta_range in eta_ranges:
        p_bins_min = get_p(0.5, (eta_range[0] + eta_range[1]) / 2.0)
        p_bins = get_log_bins(p_bins_min, 30.05, 15)
        p_bins_for_eta_range.append(p_bins)
    description = "20TRTHits"
    put_binning_vectors_in_file(outFile, eta_ranges, p_bins_for_eta_range,
                                description)
    create_eop_histograms(hist_filler, base_selection, eta_ranges,
                          p_bins_for_eta_range, description)
    p_bins_for_eta_range = []
    for eta_range in eta_ranges:
        p_bins_min = get_p(0.5, (eta_range[0] + eta_range[1]) / 2.0)
        p_bins = get_log_bins(p_bins_min, 40.05, 300)
        p_bins_for_eta_range.append(p_bins)
    create_spectrum_plots(hist_filler, base_selection, eta_ranges,
                          p_bins_for_eta_range, description)

    eta_ranges = eta_bin_tuples
    base_selection = [sel_NonZeroEnergy]
    p_bins_for_eta_range = []
    for eta_range in eta_ranges:
        p_bins_min = get_p(0.5, (eta_range[0] + eta_range[1]) / 2.0)
        p_bins = get_log_bins(p_bins_min, 30.05, 15)
        p_bins_for_eta_range.append(p_bins)
    description = "NonZeroEnergy"
    put_binning_vectors_in_file(outFile, eta_ranges, p_bins_for_eta_range,
                                description)
    create_eop_histograms(hist_filler, base_selection, eta_ranges,
                          p_bins_for_eta_range, description)
    p_bins_for_eta_range = []
    for eta_range in eta_ranges:
        p_bins_min = get_p(0.5, (eta_range[0] + eta_range[1]) / 2.0)
        p_bins = get_log_bins(p_bins_min, 40.05, 300)
        p_bins_for_eta_range.append(p_bins)
    create_spectrum_plots(hist_filler, base_selection, eta_ranges,
                          p_bins_for_eta_range, description)

    eta_ranges = eta_bin_tuples
    base_selection = []
    p_bins_for_eta_range = []
    for eta_range in eta_ranges:
        p_bins_min = get_p(0.5, (eta_range[0] + eta_range[1]) / 2.0)
        p_bins = get_log_bins(p_bins_min, 30.05, 15)
        p_bins_for_eta_range.append(p_bins)
    description = "Inclusive"
    put_binning_vectors_in_file(outFile, eta_ranges, p_bins_for_eta_range,
                                description)
    create_eop_histograms(hist_filler, base_selection, eta_ranges,
                          p_bins_for_eta_range, description)
    p_bins_for_eta_range = []
    for eta_range in eta_ranges:
        #p_bins_min = get_p(0.5, (eta_range[0] + eta_range[1]) / 2.0)
        p_bins = get_log_bins(0.5, 40.05, 300)
        p_bins_for_eta_range.append(p_bins)
    create_spectrum_plots(hist_filler, base_selection, eta_ranges,
                          p_bins_for_eta_range, description)

    histograms = hist_filler.DumpHistograms()
    for histogram_name in histograms:
        write_histograms(histograms[histogram_name], outFile)

    outFile.Close()

    print("THEJOBFINISHED!")
Пример #15
0
from calculation import Calculation, CalculationDataMC, WeightCalculation
import numpy as np

def weight(vertex, isData):
    if not isData:
        return vertex["mcWeight"]
    return np.ones(len(vertex))
calc_weight = WeightCalculation(weight, ["mcWeight"])

def vertex_mass(vertex):
    return vertex["vertex_mass"]
calc_vertex_mass = Calculation(vertex_mass, ["vertex_mass"])

def vertex_count(vertex):
    return np.ones(len(vertex)) * 0.0
calc_vertex_count = Calculation(vertex_count, [])

def vertex_chiSquared(vertex):
    return vertex["vertex_chiSquared"]
calc_vertex_chiSquared = Calculation(vertex_chiSquared, ["vertex_chiSquared"])

def vertex_Rxy(vertex):
    return vertex["vertex_Rxy"]
calc_vertex_Rxy = Calculation(vertex_Rxy, ["vertex_Rxy"])

def higher_trk_p(vertex):
    trk_p = np.zeros(len(vertex))
    trk_p[vertex["trk1_p"] > vertex["trk2_p"]] = trk1_p[vertex["trk1_p"] > vertex["trk2_p"]]
    trk_p[vertex["trk2_p"] >= vertex["trk1_p"]] = trk2_p[vertex["trk2_p"] >= vertex["trk1_p"]]
    return trk_p
Пример #16
0
def train():
    trains = division()[0]
    print(len(trains))
    cal = Calculation()
    cal.reading_sms_and_calculation(trains)
Пример #17
0
    def onCalcButton(self):
        """
            Start a traverse calculation when the Calculate button pushed.
        """
        if self.ui.buttonGroup.checkedId() == -1:
            QMessageBox.warning(self, tr("Warning"), tr("Select the type of traverse line!"))
            return

        # get the selected stations
        startpoint = self.ui.StartPointComboBox.itemData( self.ui.StartPointComboBox.currentIndex() )
        if startpoint is None:
            QMessageBox.warning(self, tr("Warning"), tr("Select start point!"))
            self.ui.StartPointComboBox.setFocus()
            return
        endpoint = self.ui.EndPointComboBox.itemData( self.ui.EndPointComboBox.currentIndex() )
        if endpoint is None:
            QMessageBox.warning(self, tr("Warning"), tr("Select end point!"))
            self.ui.EndPointComboBox.setFocus()
            return
        if self.ui.OrderList.count()==0:
            QMessageBox.warning(self, tr("Warning"), tr("Add points to point list!"))
            self.ui.OrderList.setFocus()
            return

        # fill stations list
        stations = [startpoint]
        for i in range(self.ui.OrderList.count()):
            station = self.ui.OrderList.item(i).data(Qt.UserRole)
            if i==0 and station == startpoint:
                continue 
            if i==self.ui.OrderList.count()-1 and station == endpoint:
                continue 
            stations.append(station)
        if not self.ui.OpenRadio.isChecked():
            stations.append(endpoint)
            
        # add stations and observations to trav_obs
        trav_obs = []
        for i in range(len(stations)):
            st = get_station(stations[i][0], stations[i][1], stations[i][2])
            targets = get_targets(stations[i][0], stations[i][1], stations[i][2])
            obs1 = None
            obs2 = None
            if targets is not None:
                for target in targets:
                    if i>0 and target[0]==stations[i-1][0]:
                        if obs1 is None:
                            obs1 = get_target(target[0],target[1],target[2])
                        if not self.ui.OpenRadio.isChecked() and (obs2 is not None or i==len(stations)-1):
                            break
                    elif i<len(stations)-1 and target[0]==stations[i+1][0]:
                        if obs2 is None:
                            obs2 = get_target(target[0],target[1],target[2])
                        if obs1 is not None or i==0:
                            break
                    elif self.ui.OpenRadio.isChecked() and i==len(stations)-1 and target[0]==endpoint[0]:
                        if obs2 is None:
                            obs2 = get_target(target[0],target[1],target[2])
                        if obs1 is not None:
                            break
                    
            trav_obs.append([st,obs1,obs2])
            
        # Open Traverse: end point can be selected from end point list
        if self.ui.OpenRadio.isChecked():
            trav_obs.append([Station( Point(endpoint[0]), \
                            PolarObservation(endpoint[0], 'station') ),None,None])
            
            # if end point is a known point -> question
            known_list = get_known()
            if known_list is not None and endpoint[0] in known_list:
                reply = QMessageBox.question(self, tr("Question"), \
                    tr("End point has coordinates.\nAre you sure you want to calculate an open traverse?"), \
                    QMessageBox.Yes, QMessageBox.No)
                if reply == QMessageBox.No:
                    return

        if self.ui.OpenRadio.isChecked():
            plist = Calculation.traverse(trav_obs,True)
        else:
            plist = Calculation.traverse(trav_obs,False)

        if plist is not None:
            #store newly calculated coordinates
            for pt in plist:
                tp = ScPoint(pt.id)
                tp.set_coord(pt)
                tp.store_coord(2)
            traversing_type = self.ui.buttonGroup.checkedButton().text()
            self.ui.ResultTextBrowser.append("\n" + tr("Traversing") + " - %s" % traversing_type)
            self.ui.ResultTextBrowser.append(tr("            bearing    bw dist"))
            self.ui.ResultTextBrowser.append(tr("Point        angle     distance  (dE)     (dN)       dE         dN"))
            self.ui.ResultTextBrowser.append(tr("           correction  fw dist    corrections      Easting    Northing"))
            self.log.write()
            self.log.write_log(tr("Traversing") + " - %s" % traversing_type)
            self.log.write(tr("            bearing    bw dist"))
            self.log.write(tr("Point        angle     distance  (dE)     (dN)       dE         dN"))
            self.log.write(tr("           correction  fw dist    corrections      Easting    Northing"))
            self.ui.ResultTextBrowser.append(ResultLog.resultlog_message)
            self.log.write(ResultLog.resultlog_message)
        else:
            QMessageBox.warning(self, tr("Warning"), tr("Traverse line cannot be calculated!"))
            self.ui.ResultTextBrowser.append(ResultLog.resultlog_message)
            self.log.write(ResultLog.resultlog_message)
Пример #18
0
def create_eop_histograms(hist_filler, base_selection, eta_ranges,p_bins_for_eta_range, description, do_cluster_plots=False, do_calib_hit_plots=False):
    #define a set of eta bins
    eta_count = -1
    for eta_range, p_bins in zip(eta_ranges, p_bins_for_eta_range):
        eta_count += 1
        #get the function that selects tracks in that bin
        eta_bin_selection = create_selection_function(EtaBin, ["trk_etaEMB2","trk_etaEME2","trk_phiEME2", "trk_phiEMB2"], eta_range[0], eta_range[1])

        selections = base_selection + [eta_bin_selection]

        NPtBins = len(p_bins)
        Pt_low = 0.5
        Pt_high = max(p_bins)
        ptbins = get_log_bins(Pt_low, Pt_high, NPtBins)
        eop_bins = get_bins(-1.0, +3.0, 800) # use a super fine binning

        histogram_name = "EOPProfileVsMomentum"
        histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)

        from eop_plotting.variables import calc_EOP
        hist_filler.book_tprofile_fill(histogram_name,
                                                  calc_trkP,\
                                                  calc_EOP,\
                                                  selections = selections,\
                                                  bins = p_bins,\
                                                  xlabel ="P[GeV]",\
                                                  ylabel = "<E/p>",\
                                                  )

        histogram_name = "2DHist_EOPVsMomentum"
        histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
        hist_filler.book_2dhistogram_fill(histogram_name,
                                                  calc_trkP,\
                                                  calc_EOP,\
                                                  selections = selections,\
                                                  bins_x = p_bins,\
                                                  bins_y = eop_bins,\
                                                  xlabel ="P[GeV]",\
                                                  ylabel = "E/p",\
                                                  )
        from variables import cone_strings, total_energy_annulus_template
        from math import pi
        def annulus_area(low,high):
            return pi * ((high ** 2) - (low ** 2))
        for (low, high) in zip(cone_strings[:-1], cone_strings[1:]):
            #this function calculates the energy in a cone from low to high
            func_e = lambda x, y = low, z = high : total_energy_annulus_template(x,y,z)
            func_e.__name__ = "energy_in_cone_{}_{}".format(low, high)
            #this function calculates the energy in a cone from low to high
            func_e_area = lambda x, y = low, z = high, l=low, h=high : total_energy_annulus_template(x,y,z)/(annulus_area(float(l)/1000.0, float(h)/1000.0))
            func_e_area.__name__ = "energy_in_cone_area_{}_{}".format(low, high)
            #this function calculates the eop in a cone from low to high
            func_eop = lambda x, y = low, z = high : total_energy_annulus_template(x,y,z)/x["trk_p"]
            func_eop.__name__ = "eop_in_cone_{}_{}".format(low, high)
            #this function calculates the eop in a cone from low to high
            func_eop_area = lambda x, y = low, z = high, l=low, h=high : (total_energy_annulus_template(x,y,z)/x["trk_p"])/(annulus_area(float(l)/1000.0, float(h)/1000.0))
            func_eop_area.__name__ = "eop_in_cone_area_{}_{}".format(low, high)

            #define the calculation and the branches that we need for this
            branches = ["trk_ClusterEnergy_EM_{}".format(low), "trk_ClusterEnergy_HAD_{}".format(low)]
            branches += ["trk_ClusterEnergy_EM_{}".format(high), "trk_ClusterEnergy_HAD_{}".format(high)]
            clean_branches = []
            for b in branches:
                if "000" not in b:
                    clean_branches.append(b)
            branches = clean_branches
            from calculation import Calculation
            calc_cone_e = Calculation(func_e, branches)
            calc_cone_e_area = Calculation(func_e_area, branches)
            branches = branches + ["trk_p"]
            calc_cone_eop = Calculation(func_eop, branches)
            calc_cone_eop_area = Calculation(func_eop_area, branches)

            #book the histograms
            low_descr = float(low)/10.0
            high_descr = float(high)/10.0
            histogram_name = "EnergyAnnulusProfileVsMomentum_{}_{}".format(low, high)
            histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
            hist_filler.book_tprofile_fill(histogram_name,\
                                                      calc_trkP,\
                                                      calc_cone_e,\
                                                      selections = selections,\
                                                      bins = p_bins,\
                                                      xlabel ="P[GeV]",\
                                                      ylabel = "<E_{r#in[" + "{},{}".format(low_descr, high_descr) + "]}>[GeV]",\
                                                      )

            histogram_name = "EOPProfileVsMomentum_{}_{}".format(low, high)
            histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
            hist_filler.book_tprofile_fill(histogram_name,\
                                                      calc_trkP,\
                                                      calc_cone_eop,\
                                                      selections = selections,\
                                                      bins = p_bins,\
                                                      xlabel ="P[GeV]",\
                                                      ylabel = "<E_{r#in[" + "{},{}".format(low_descr, high_descr) + "]}/p>",\
                                                      )

            #book the histograms
            low_descr = float(low)/10.0
            high_descr = float(high)/10.0
            histogram_name = "EnergyAnnulusProfileVsMomentum_{}_{}_Area".format(low, high)
            histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
            hist_filler.book_tprofile_fill(histogram_name,\
                                                      calc_trkP,\
                                                      calc_cone_e_area,\
                                                      selections = selections,\
                                                      bins = p_bins,\
                                                      xlabel ="P[GeV]",\
                                                      ylabel = "<E_{r#in[" + "{},{}".format(low_descr, high_descr) + "]}>/Area [GeV]",\
                                                      )

            histogram_name = "EOPProfileVsMomentum_{}_{}_Area".format(low, high)
            histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
            hist_filler.book_tprofile_fill(histogram_name,\
                                                      calc_trkP,\
                                                      calc_cone_eop_area,\
                                                      selections = selections,\
                                                      bins = p_bins,\
                                                      xlabel ="P[GeV]",\
                                                      ylabel = "<E_{r#in[" + "{},{}".format(low_descr, high_descr) + "]}/p>/ Area",\
                                                      )

        histogram_name = "EnergyAnulusProfileVsMomentum"
        histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
        from eop_plotting.variables import calc_EnergyAnulus
        hist_filler.book_tprofile_fill(histogram_name,\
                                                  calc_trkP,\
                                                  calc_EnergyAnulus,\
                                                  selections = selections,\
                                                  bins = p_bins,\
                                                  xlabel ="P[GeV]",\
                                                  ylabel = "<E_{EM Anulus}>[GeV]",\
                                                  )

#       from variables import calc_EOTotalEMCalibHitEnergy
#       histogram_name = "EOTotalEMCalibHitEnergyProfileVsMomentum"  + "_" + "_" + description + "_Eta_" + str(eta_count)
#       hist_filler.book_tprofile_fill(histogram_name,\
#                                      calc_trkP,\
#                                      calc_EOTotalEMCalibHitEnergy,\
#                                      selections = selections,\
#                                      bins = p_bins,\
#                                      xlabel = "P[GeV]",\
#                                      ylabel = "<E_{Total Calibration}/P>",\
#                                      )


        histogram_name = "2DHist_EnergyAnulusVsMomentum"
        histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
        hist_filler.book_2dhistogram_fill(histogram_name,\
                                                  calc_trkP,\
                                                  calc_EnergyAnulus,\
                                                  selections = selections,\
                                                  bins_x = p_bins,\
                                                  bins_y = eop_bins,\
                                                  xlabel ="P[GeV]",\
                                                  ylabel = "E_{EM Anulus} [GeV]",\
                                                  )

        histogram_name = "EnergyBkgProfileVsMomentum"
        histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
        from eop_plotting.variables import calc_EOPBkg
        hist_filler.book_tprofile_fill(histogram_name,\
                                                  calc_trkP,\
                                                  calc_EOPBkg,\
                                                  selections = selections,\
                                                  bins = p_bins,\
                                                  xlabel ="P[GeV]",\
                                                  ylabel = "<E/p>_{BKG}",\
                                                  )

        histogram_name = "EnergyBkgUpProfileVsMomentum"
        histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
        from eop_plotting.variables import calc_EOPBkgUp
        hist_filler.book_tprofile_fill(histogram_name,\
                                                  calc_trkP,\
                                                  calc_EOPBkgUp,\
                                                  selections = selections,\
                                                  bins = p_bins,\
                                                  xlabel ="P[GeV]",\
                                                  ylabel = "<E/p>_{BKG}",\
                                                  )

        histogram_name = "EnergyBkgDownProfileVsMomentum"
        histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
        from eop_plotting.variables import calc_EOPBkgDown
        hist_filler.book_tprofile_fill(histogram_name,\
                                                  calc_trkP,\
                                                  calc_EOPBkgDown,\
                                                  selections = selections,\
                                                  bins = p_bins,\
                                                  xlabel ="P[GeV]",\
                                                  ylabel = "<E/p>_{BKG}",\
                                                  )

        histogram_name = "EnergyBigBkgProfileVsMomentum"
        histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
        from eop_plotting.variables import calc_EOPBigBkg
        hist_filler.book_tprofile_fill(histogram_name,\
                                                  calc_trkP,\
                                                  calc_EOPBigBkg,\
                                                  selections = selections,\
                                                  bins = p_bins,\
                                                  xlabel ="P[GeV]",\
                                                  ylabel = "<E/p>_{BKG}",\
                                                  )

        histogram_name = "EnergyBigBkgUpProfileVsMomentum"
        histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
        from eop_plotting.variables import calc_EOPBigBkgUp
        hist_filler.book_tprofile_fill(histogram_name,\
                                                  calc_trkP,\
                                                  calc_EOPBigBkgUp,\
                                                  selections = selections,\
                                                  bins = p_bins,\
                                                  xlabel ="P[GeV]",\
                                                  ylabel = "<E/p>_{BKG}",\
                                                  )

        histogram_name = "EnergyBigBkgDownProfileVsMomentum"
        histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
        from eop_plotting.variables import calc_EOPBigBkgDown
        hist_filler.book_tprofile_fill(histogram_name,\
                                                  calc_trkP,\
                                                  calc_EOPBigBkgDown,\
                                                  selections = selections,\
                                                  bins = p_bins,\
                                                  xlabel ="P[GeV]",\
                                                  ylabel = "<E/p>_{BKG}",\
                                                  )


        histogram_name = "2DHist_EnergyBkgVsMomentum"
        histogram_name = histogram_name + "_" + "_" + description + "_Eta_" + str(eta_count)
        hist_filler.book_2dhistogram_fill(histogram_name,\
                                                  calc_trkP,\
                                                  calc_EOPBkg,\
                                                  selections = selections,\
                                                  bins_x = p_bins,\
                                                  bins_y = eop_bins,\
                                                  xlabel ="P[GeV]",\
                                                  ylabel = "E/p BKG",\
                                                  )

        p_count = -1
        p_ranges = [(p_bins[i],p_bins[i+1]) for i in range(0, len(p_bins)-1)]
        for p_range in p_ranges:
            p_count += 1
            print("The prange is " + str(p_range))
            p_bin_selection = create_selection_function(PBin, ["trk_p"], p_range[0], p_range[1])
            selections = base_selection + [eta_bin_selection] + [p_bin_selection]

            histogram_name = "EOPDistribution" + "_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
            EOPDist  =  hist_filler.book_histogram_fill(histogram_name,
                                                      calc_EOP,\
                                                      selections = selections,\
                                                      bins = eop_bins,\
                                                      xlabel ="E/p",\
                                                      )

            if do_calib_hit_plots:
              from eop_plotting.variables import calc_CalibHitFrac, calc_PhotonCalibHitFrac, calc_HadronCalibHitFrac, sel_HasCalibHit
              from eop_plotting.variables import calc_EMCalibHitFrac, calc_PhotonEMCalibHitFrac, calc_HadronEMCalibHitFrac, sel_HasEMCalibHit
              from eop_plotting.variables import calc_HADCalibHitFrac, calc_PhotonHADCalibHitFrac, calc_HadronHADCalibHitFrac, sel_HasHADCalibHit

              histogram_name = "CalibrationHitTwoDHist_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
              hist_filler.book_2dhistogram_fill(histogram_name,
                                                    calc_EOP,\
                                                    calc_CalibHitFrac,\
                                                    selections = selections + [sel_HasCalibHit],\
                                                    bins_x = [-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],\
                                                    bins_y =list( np.linspace(0.0,1.0,20)),
                                                    range_low_y = 0.0,\
                                                    range_high_y = 1.0,\
                                                    xlabel ="E/p",\
                                                    ylabel = "E^{Calib}_{Track}/E^{Calib}_{Total}",\
                                                    )

              histogram_name = "PhotonCalibrationHitTwoDHist_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
              hist_filler.book_2dhistogram_fill(histogram_name,
                                                    calc_EOP,\
                                                    calc_PhotonCalibHitFrac,\
                                                    selections = selections + [sel_HasCalibHit],\
                                                    bins_x = [-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],\
                                                    bins_y =list( np.linspace(0.0,1.0,20)),
                                                    xlabel ="E/p",\
                                                    ylabel = "E^{Calib}_{Photons}/E^{Calib}_{Total}",\
                                                    )

              histogram_name = "HadronicCalibrationHitTwoDHist_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
              hist_filler.book_2dhistogram_fill(histogram_name,
                                                    calc_EOP,\
                                                    calc_HadronCalibHitFrac,\
                                                    selections = selections + [sel_HasCalibHit],\
                                                    bins_x = [-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],\
                                                    bins_y =list( np.linspace(0.0,1.0,20)),
                                                    xlabel ="E/p",\
                                                    ylabel = "E^{Calib}_{Neutral Hadrons}/E^{Calib}_{Total}",\
                                                    )

              histogram_name = "EMCalibrationHitTwoDHist_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
              hist_filler.book_2dhistogram_fill(histogram_name,
                                                    calc_EOP,\
                                                    calc_EMCalibHitFrac,\
                                                    selections = selections + [sel_HasEMCalibHit],\
                                                    bins_x = [-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],\
                                                    bins_y =list( np.linspace(0.0,1.0,20)),
                                                    xlabel ="E/p",\
                                                    ylabel = "E^{EM Calib}_{Track}/E^{EM Calib}_{Total}",\
                                                    )

              histogram_name = "PhotonEMCalibrationHitTwoDHist_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
              hist_filler.book_2dhistogram_fill(histogram_name,
                                                    calc_EOP,\
                                                    calc_PhotonEMCalibHitFrac,\
                                                    selections = selections + [sel_HasEMCalibHit],\
                                                    bins_x = [-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],\
                                                    bins_y =list( np.linspace(0.0,1.0,20)),
                                                    xlabel ="E/p",\
                                                    ylabel = "E^{EM Calib}_{Photons}/E^{EM Calib}_{Total}",\
                                                    )

              histogram_name = "HadronicEMCalibrationHitTwoDHist_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
              hist_filler.book_2dhistogram_fill(histogram_name,
                                                    calc_EOP,\
                                                    calc_HadronEMCalibHitFrac,\
                                                    selections = selections + [sel_HasEMCalibHit],\
                                                    bins_x = [-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],\
                                                    bins_y =list( np.linspace(0.0,1.0,20)),
                                                    xlabel ="E/p",\
                                                    ylabel = "E^{HAD Calib}_{Neutral Hadrons}/E^{HAD Calib}_{Total}",\
                                                    )

              histogram_name = "HADCalibrationHitTwoDHist_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
              hist_filler.book_2dhistogram_fill(histogram_name,
                                                    calc_EOP,\
                                                    calc_HADCalibHitFrac,\
                                                    selections = selections + [sel_HasHADCalibHit],\
                                                    bins_x = [-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],\
                                                    bins_y =list( np.linspace(0.0,1.0,20)),
                                                    xlabel ="E/p",\
                                                    ylabel = "E^{HAD Calib}_{Track}/E^{HAD Calib}_{Total}",\
                                                    )

              histogram_name = "PhotonHADCalibrationHitTwoDHist_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
              hist_filler.book_2dhistogram_fill(histogram_name,
                                                    calc_EOP,\
                                                    calc_PhotonHADCalibHitFrac,\
                                                    selections = selections + [sel_HasHADCalibHit],\
                                                    bins_x = [-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],\
                                                    bins_y =list( np.linspace(0.0,1.0,20)),
                                                    xlabel ="E/p",\
                                                    ylabel = "E^{HAD Calib}_{Photons}/E^{HAD Calib}_{Total}",\
                                                    )

              histogram_name = "HadronicHADCalibrationHitTwoDHist_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
              hist_filler.book_2dhistogram_fill(histogram_name,
                                                    calc_EOP,\
                                                    calc_HadronHADCalibHitFrac,\
                                                    selections = selections + [sel_HasHADCalibHit],\
                                                    bins_x = [-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],\
                                                    bins_y =list( np.linspace(0.0,1.0,20)),
                                                    xlabel ="E/p",\
                                                    ylabel = "E^{HAD Calib}_{Neutral Hadrons}/E^{HAD Calib}_{Neutral Hadrons}",\
                                                    )

            histogram_name = "EOPBkgDistribution" + "_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
            EOPBkgDist  =  hist_filler.book_histogram_fill(histogram_name,
                                                      calc_EOPBkg,\
                                                      selections = selections,\
                                                      bins = eop_bins,\
                                                      xlabel ="E/p Bkg",\
                                                      )
            histogram_name = "trkTRTHits" + "_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
            from eop_plotting.variables import calc_nTRT
            hist_filler.book_histogram_fill(histogram_name,\
                                   calc_nTRT,\
                                   selections = selections,\
                                   range_low = -0.5,\
                                   range_high = 59.5,\
                                   bins = 60,\
                                   xlabel = "Number of TRT Hits",\
                                   ylabel = "Number of Tracks")

            histogram_name = "trkEMDR100" + "_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
            from eop_plotting.variables import calc_EnergyEMDR100
            hist_filler.book_histogram_fill(histogram_name,\
                                   calc_EnergyEMDR100,\
                                   selections = selections,\
                                   range_low = -2.0,\
                                   range_high = + 10.0,\
                                   bins = 48,\
                                   xlabel = "E_{EM}^{#DeltaR<0.1}[GeV]",\
                                   ylabel = "Number of Tracks")

            histogram_name = "MomentumHadFrac" + "_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
            from eop_plotting.variables import calc_MomentumHadFrac
            hist_filler.book_histogram_fill(histogram_name,\
                                   calc_MomentumHadFrac,\
                                   selections = selections,\
                                   range_low = -1.0,\
                                   range_high = + 5.0,\
                                   bins = 48,\
                                   xlabel = "E^{HAD}/P",\
                                   ylabel = "Number of Tracks")

            histogram_name = "HadFrac" + "_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
            from eop_plotting.variables import calc_HadFrac
            hist_filler.book_histogram_fill(histogram_name,\
                                   calc_HadFrac,\
                                   selections = selections,\
                                   range_low = -1.0,\
                                   range_high = + 2.0,\
                                   bins = 48,\
                                   xlabel = "E^{HAD}/E^{Total}",\
                                   ylabel = "Number of Tracks")

            if do_cluster_plots:

               from eop_plotting.variables import calc_trkNClusters, calc_trkNClusters_EM, calc_trkNClusters_HAD,  calc_trkNClusters_emlike, calc_trkNClusters_hadlike
               histogram_names = ["NClusters","NClusters_EM","NClusters_HAD","NClusters_emlike","NClusters_hadlike"]
               xlabels = ["Number of Clusters","Number of Clusters in EM Calorimeter","Number of Clusters in HAD Calorimeter","Number of Clusters with EM Prob > 0.5","Number of Clusters with EM Prob < 0.5"]
               variables = [calc_trkNClusters, calc_trkNClusters_EM, calc_trkNClusters_HAD, calc_trkNClusters_emlike, calc_trkNClusters_hadlike]

               for histogram_name, variable, xlabel in zip(histogram_names, variables, xlabels):
                   histogram_name = histogram_name + "_" + description + "_Eta_" + str(eta_count) + "_Momentum_" + str(p_count)
                   hist_filler.book_histogram_fill(histogram_name,\
                                          variable,\
                                          selections = selections,\
                                          bins = 10,\
                                          range_low = -0.5,\
                                          range_high = 9.5,\
                                          xlabel=xlabel,\
                                          ylabel="Number of Tracks")
Пример #19
0
            download_object.download()

        else:

            print("Peer Servers found! Distributing download...")

            # get the filesize
            req = Request()
            response = req.makeRequest(url, proxy=peerClientConfig.getProxy())
            filesize = int(response.headers['Content-Length'])
            req.closeConnection(response)
            print("peer-client filesize: {}".format(filesize))

            # get the download ranges to be assigned to each
            parts = client.numPeerServers()
            range_list = Calculation().get_download_ranges_list(
                0, filesize - 1, parts)

            # connect with each server and send them the download details
            client.connectWithPeerServers(range_list, temp_dir)

            # wait for download to complete at each server
            # except main_thread, calling join() for each thread
            # it ensures that merging of parts occur only after each thread has completed downloading
            # print ("Threads: ", len(threading.enumerate()))
            main_thread = threading.current_thread()
            for t in threading.enumerate():
                if t is main_thread:
                    continue
                t.join()

            # servers will send the downloaded part
Пример #20
0
    def onCalcButton(self):
        """
            Start a traverse calculation when the Calculate button pushed.
        """
        if self.ui.buttonGroup.checkedId() == -1:
            QMessageBox.warning(self, tr("Warning"),
                                tr("Select the type of traverse line!"))
            return

        # get the selected stations
        startpoint = self.ui.StartPointComboBox.itemData(
            self.ui.StartPointComboBox.currentIndex())
        if startpoint is None:
            QMessageBox.warning(self, tr("Warning"), tr("Select start point!"))
            self.ui.StartPointComboBox.setFocus()
            return
        endpoint = self.ui.EndPointComboBox.itemData(
            self.ui.EndPointComboBox.currentIndex())
        if endpoint is None:
            QMessageBox.warning(self, tr("Warning"), tr("Select end point!"))
            self.ui.EndPointComboBox.setFocus()
            return
        if self.ui.OrderList.count() == 0:
            QMessageBox.warning(self, tr("Warning"),
                                tr("Add points to point list!"))
            self.ui.OrderList.setFocus()
            return

        # fill stations list
        stations = [startpoint]
        for i in range(self.ui.OrderList.count()):
            station = self.ui.OrderList.item(i).data(Qt.UserRole)
            if i == 0 and station == startpoint:
                continue
            if i == self.ui.OrderList.count() - 1 and station == endpoint:
                continue
            stations.append(station)
        if not self.ui.OpenRadio.isChecked():
            stations.append(endpoint)

        # add stations and observations to trav_obs
        trav_obs = []
        for i in range(len(stations)):
            st = get_station(stations[i][0], stations[i][1], stations[i][2])
            targets = get_targets(stations[i][0], stations[i][1],
                                  stations[i][2])
            obs1 = None
            obs2 = None
            if targets is not None:
                for target in targets:
                    if i > 0 and target[0] == stations[i - 1][0]:
                        if obs1 is None:
                            obs1 = get_target(target[0], target[1], target[2])
                        if not self.ui.OpenRadio.isChecked() and (
                                obs2 is not None or i == len(stations) - 1):
                            break
                    elif i < len(stations) - 1 and target[0] == stations[i +
                                                                         1][0]:
                        if obs2 is None:
                            obs2 = get_target(target[0], target[1], target[2])
                        if obs1 is not None or i == 0:
                            break
                    elif self.ui.OpenRadio.isChecked(
                    ) and i == len(stations) - 1 and target[0] == endpoint[0]:
                        if obs2 is None:
                            obs2 = get_target(target[0], target[1], target[2])
                        if obs1 is not None:
                            break

            trav_obs.append([st, obs1, obs2])

        # Open Traverse: end point can be selected from end point list
        if self.ui.OpenRadio.isChecked():
            trav_obs.append([Station( Point(endpoint[0]), \
                            PolarObservation(endpoint[0], 'station') ),None,None])

            # if end point is a known point -> question
            known_list = get_known()
            if known_list is not None and endpoint[0] in known_list:
                reply = QMessageBox.question(self, tr("Question"), \
                    tr("End point has coordinates.\nAre you sure you want to calculate an open traverse?"), \
                    QMessageBox.Yes, QMessageBox.No)
                if reply == QMessageBox.No:
                    return

        if self.ui.OpenRadio.isChecked():
            plist = Calculation.traverse(trav_obs, True)
        else:
            plist = Calculation.traverse(trav_obs, False)

        if plist is not None:
            #store newly calculated coordinates
            for pt in plist:
                tp = ScPoint(pt.id)
                tp.set_coord(pt)
                tp.store_coord(2)
            traversing_type = self.ui.buttonGroup.checkedButton().text()
            self.ui.ResultTextBrowser.append("\n" + tr("Traversing") +
                                             " - %s" % traversing_type)
            self.ui.ResultTextBrowser.append(
                tr("            bearing    bw dist"))
            self.ui.ResultTextBrowser.append(
                tr("Point        angle     distance  (dE)     (dN)       dE         dN"
                   ))
            self.ui.ResultTextBrowser.append(
                tr("           correction  fw dist    corrections      Easting    Northing"
                   ))
            self.log.write()
            self.log.write_log(tr("Traversing") + " - %s" % traversing_type)
            self.log.write(tr("            bearing    bw dist"))
            self.log.write(
                tr("Point        angle     distance  (dE)     (dN)       dE         dN"
                   ))
            self.log.write(
                tr("           correction  fw dist    corrections      Easting    Northing"
                   ))
            self.ui.ResultTextBrowser.append(ResultLog.resultlog_message)
            self.log.write(ResultLog.resultlog_message)
        else:
            QMessageBox.warning(self, tr("Warning"),
                                tr("Traverse line cannot be calculated!"))
            self.ui.ResultTextBrowser.append(ResultLog.resultlog_message)
            self.log.write(ResultLog.resultlog_message)
from calculation import Calculation

## Take a look here for the run-1 eop selections: https://journals.aps.org/prd/pdf/10.1103/PhysRevD.85.012001


def chi_square_fifteen(vertex):
    return vertex["vertex_chiSquared"] < 15


sel_chi_square_fifteen = Calculation(chi_square_fifteen, ["vertex_chiSquared"])

from variables_identified import calc_cos_theta


def tight_cos_theta_ks(vertex):
    return calc_cos_theta.eval(vertex) > 0.999


sel_tight_cos_theta_ks = Calculation(tight_cos_theta_ks,
                                     calc_cos_theta.branches)


def rxy_ks(vertex):
    return (vertex["vertex_Rxy"] < 450) & (vertex["vertex_Rxy"] > 4.0)


sel_rxy_ks = Calculation(rxy_ks, ["vertex_Rxy"])


def pt_ks(vertex):
    return (vertex["vertex_pt"] > 0.1)
Пример #22
0
    def onCalcButton(self):
        """ Start a calculation when the Calculate button pushed.
        """
        if self.ui.radioButtonGroup.checkedId() == -1:
            QMessageBox.warning(self, tr("Warning"), tr("Select the type of calculation!"))
            return

        # get the selected stations
        stn1 = self.ui.Station1Combo.itemData( self.ui.Station1Combo.currentIndex() )
        if stn1 is None:
            QMessageBox.warning(self, tr("Warning"), tr("Select station point 1!"))
            self.ui.Station1Combo.setFocus()
            return
        stn2 = self.ui.Station2Combo.itemData( self.ui.Station2Combo.currentIndex() )
        if stn2 is None and self.ui.IntersectRadio.isChecked():
            QMessageBox.warning(self, tr("Warning"), tr("Select station point 2!"))
            self.ui.Station2Combo.setFocus()
            return
        if self.ui.TargetList.count()==0:
            QMessageBox.warning(self, tr("Warning"), tr("Add points to Used Points list!"))
            self.ui.TargetList.setFocus()
            return

        if self.ui.OrientRadio.isChecked():
            # orientation
            s = get_station(stn1[0], stn1[1], stn1[2])
            ref_list = []
            for i in range(self.ui.TargetList.count()):
                targetp = self.ui.TargetList.item(i).data(Qt.UserRole)
                to = get_target(targetp[0], targetp[1], targetp[2])
                tp = ScPoint(targetp[0])
                ref_list.append([tp,to])
            z = Calculation.orientation(s, ref_list)
            if z is not None:
                set_orientationangle(stn1[0], stn1[1], stn1[2], z.get_angle("GON"))
                self.ui.ResultTextBrowser.append("\n" + tr("Orientation") + " - %s" % s.p.id)
                self.ui.ResultTextBrowser.append(
                    tr("Point num  Code         Direction    Bearing   Orient ang   Distance   e(cc) E(m)"))
                self.ui.ResultTextBrowser.append(ResultLog.resultlog_message)
                self.log.write()
                self.log.write_log(tr("Orientation") + " - %s" % s.p.id)
                self.log.write(tr("Point num  Code         Direction    Bearing   Orient ang   Distance   e(cc) E(m)"))
                self.log.write(ResultLog.resultlog_message)
            else:
                QMessageBox.warning(self, tr("Warning"), tr("Orientation angle cannot be calculated!"))

        elif self.ui.RadialRadio.isChecked():
            # radial surveys (polar point)
            s = get_station(stn1[0], stn1[1], stn1[2])
            log_header = False
            for i in range(self.ui.TargetList.count()):
                targetp = self.ui.TargetList.item(i).data(Qt.UserRole)
                to = get_target(targetp[0], targetp[1], targetp[2])
                tp = ScPoint(targetp[0])
                p = Calculation.polarpoint(s, to)
                if p is not None:
                    # log results
                    if log_header is False:
                        self.ui.ResultTextBrowser.append("\n" + tr("Radial Survey"))
                        self.ui.ResultTextBrowser.append(tr("Point num  Code              E            N        Z     Bearing  H.Distance"))
                        self.log.write()
                        self.log.write_log(tr("Radial Survey"))
                        self.log.write(tr("Point num  Code              E            N        Z     Bearing  H.Distance"))
                        log_stn = u"%-10s %-10s %12.3f %12.3f %8.3s     <station>" % \
                            (s.p.id, (s.p.pc if s.p.pc is not None else "-"), s.p.e, s.p.n, \
                            ("%8.3f"%s.p.z if s.p.z is not None else "") )
                        self.log.write(log_stn)
                        self.ui.ResultTextBrowser.append(log_stn)
                        log_header = True
                    tp.set_coord(p)
                    if p.z is None:
                        # no z calculated
                        self.ui.ResultTextBrowser.append(ResultLog.resultlog_message)
                        self.log.write(ResultLog.resultlog_message)
                        tp.store_coord(2)
                    else:
                        self.ui.ResultTextBrowser.append(ResultLog.resultlog_message)
                        self.log.write(ResultLog.resultlog_message)
                        tp.store_coord(3)
                else:
                    QMessageBox.warning(self, tr("Warning"), tr("Radial survey on %s cannot be calculated!") % targetp[0])

        elif self.ui.IntersectRadio.isChecked():
            # intersection
            s1 = get_station(stn1[0], stn1[1], stn1[2])
            s2 = get_station(stn2[0], stn2[1], stn2[2])
            if stn1 == stn2:
                QMessageBox.warning(self, tr("Warning"), tr("Station 1 and station 2 are the same!"))
                self.ui.Station1Combo.setFocus()
                return
            log_header = False
            for i in range(self.ui.TargetList.count()):
                itemdata = self.ui.TargetList.item(i).data(Qt.UserRole)
                targetp1 = itemdata[0]
                targetp2 = itemdata[1]
                to1 = get_target(targetp1[0], targetp1[1], targetp1[2])
                tp1 = ScPoint(targetp1[0])
                to2 = get_target(targetp2[0], targetp2[1], targetp2[2])
                #tp2 = ScPoint(targetp2[0])
                p = Calculation.intersection(s1, to1, s2, to2)
                if p is not None:
                    # log results
                    if log_header is False:
                        self.ui.ResultTextBrowser.append("\n" + tr("Intersection"))
                        self.ui.ResultTextBrowser.append(tr("Point num  Code              E            N     Bearing1 Bearing2"))
                        self.log.write()
                        self.log.write_log(tr("Intersection"))
                        self.log.write(tr("Point num  Code              E            N     Bearing1 Bearing2"))

                        log_stn = u"%-10s %-10s %12.3f %12.3f     <station>\n" % \
                            (s1.p.id, (s1.p.pc if s1.p.pc is not None else "-"), s1.p.e, s1.p.n)
                        log_stn += u"%-10s %-10s %12.3f %12.3f     <station>" % \
                            (s2.p.id, (s2.p.pc if s2.p.pc is not None else "-"), s2.p.e, s2.p.n)
                        self.log.write(log_stn)
                        self.ui.ResultTextBrowser.append(log_stn)
                        log_header = True
                    tp1.set_coord(p)
                    tp1.store_coord(2)
                    self.ui.ResultTextBrowser.append(ResultLog.resultlog_message)
                    self.log.write(ResultLog.resultlog_message)
                else:
                    QMessageBox.warning(self, tr("Warning"), tr("Intersecion on %s cannot be calculated!") % targetp1[0])

        elif self.ui.ResectionRadio.isChecked():
            # resection
            s = get_station(stn1[0], stn1[1], stn1[2])
            if self.ui.TargetList.count()!=3:
                QMessageBox.warning(self, tr("Warning"), tr("Select exactly 3 used points for resection!"))
                self.ui.TargetList.setFocus()
                return
            targetp1 = self.ui.TargetList.item(0).data(Qt.UserRole)
            targetp2 = self.ui.TargetList.item(1).data(Qt.UserRole)
            targetp3 = self.ui.TargetList.item(2).data(Qt.UserRole)
            to1 = get_target(targetp1[0], targetp1[1], targetp1[2])
            to2 = get_target(targetp2[0], targetp2[1], targetp2[2])
            to3 = get_target(targetp3[0], targetp3[1], targetp3[2])
            tp1 = ScPoint(targetp1[0])            
            tp2 = ScPoint(targetp2[0])            
            tp3 = ScPoint(targetp3[0])            
            p = Calculation.resection(s, tp1, tp2, tp3, to1, to2, to3)
            ScPoint(p).store_coord(2)
            # result log
            self.ui.ResultTextBrowser.append("\n" + tr("Resection"))
            self.ui.ResultTextBrowser.append(tr("Point num  Code                E            N      Direction  Angle"))
            self.ui.ResultTextBrowser.append(ResultLog.resultlog_message)
            self.log.write()
            self.log.write_log(tr("Resection"))
            self.log.write(tr("Point num  Code                E            N      Direction  Angle"))
            self.log.write(ResultLog.resultlog_message)
        elif self.ui.FreeRadio.isChecked():
            # free station
            g = GamaInterface()  # default standard deviations are used!
            s = get_station(stn1[0], stn1[1], stn1[2])
            g.add_point(s.p, 'ADJ')
            g.add_observation(s.o)
            for i in range(self.ui.TargetList.count()):
                targetp = self.ui.TargetList.item(i).data(Qt.UserRole)
                p = get_coord(targetp[0])
                g.add_point(p, 'FIX')
                to = get_target(targetp[0], targetp[1], targetp[2])
                g.add_observation(to)
            t = g.adjust()
            if t is None:
                # adjustment failed
                self.ui.ResultTextBrowser.append(tr('gama-local not installed or other runtime error'))
            else:
                self.ui.ResultTextBrowser.append(t)
Пример #23
0
from calculation import Calculation, CalculationDataMC, WeightCalculation
import numpy as np
from math import pi


def TruthMomentum(trk):
    return trk["trk_truthP"] * 1000.0  #scale to GeV


calc_TruthMomentum = Calculation(TruthMomentum, ["trk_truthP"])


def TotalCalibHitEnergyEM(trk):
    return trk["trk_TotalPhotonBackgroundCalibHitEnergy_EM_200"] + trk[
        "trk_TotalHadronicBackgroundCalibHitEnergy_EM_200"] + trk[
            "trk_TotalCalibHitEnergy_EM_200"]


def TotalCalibHitEnergyHAD(trk):
    return trk["trk_TotalPhotonBackgroundCalibHitEnergy_HAD_200"] + trk[
        "trk_TotalHadronicBackgroundCalibHitEnergy_HAD_200"] + trk[
            "trk_TotalCalibHitEnergy_HAD_200"]


def TotalCalibHitEnergy(trk):
    return TotalCalibHitEnergyEM(trk) + TotalCalibHitEnergyHAD(trk)


CalibHitBranches = [
    "trk_TotalPhotonBackgroundCalibHitEnergy_EM_200",
    "trk_TotalHadronicBackgroundCalibHitEnergy_EM_200",
Пример #24
0
class PyOpenGL(QOpenGLWidget, QGraphicsView):
    """
    Основной класс  отрисовки космического пространства и обработки полета камеры,
    ручное управление кораблем, отрисовка траектории
    """
    def __init__(self, sp_objects: list, parent=None):
        super().__init__(parent)
        QtWidgets.qApp.installEventFilter(self)
        self.viewMatrix = None
        self.setFocus()
        self.scale_factor = 5.0E6
        self.specific_impulse_of_rocket_engine = 30000
        self.scale_x = 0
        self.scale_y = 0
        self.scale_z = 0
        self.input_pulse = 0
        self.minimum_mass = 40000
        self.current_velocity = 0
        self.current_angle = 0
        self.manual_control_delta_pulse = 2000000
        self.start_modeling = False
        self.is_trajectory_shown = False
        self.calculation_module = Calculation(sp_objects, speed=3000, dt=100)
        self.space_objects = sp_objects

    def initializeGL(self):
        """
        Инициализация основного окна отрисовки, создание матрицы изображения
        """
        OpenGL.GL.glClearColor(0, 0, 0, 1)
        OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST)
        OpenGL.GL.glEnable(OpenGL.GL.GL_LIGHT0)
        OpenGL.GL.glEnable(OpenGL.GL.GL_LIGHTING)
        OpenGL.GL.glColorMaterial(OpenGL.GL.GL_FRONT_AND_BACK,
                                  OpenGL.GL.GL_AMBIENT_AND_DIFFUSE)
        OpenGL.GL.glEnable(OpenGL.GL.GL_COLOR_MATERIAL)

    def resizeGL(self, w: int, h: int):
        """
        Масштабирование экрана, движение камеры, зум камеры
        """
        min_scale = 1.0E7
        max_scale = 1.5E11
        OpenGL.GL.glViewport(0, 0, w, h)
        OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION)
        OpenGL.GL.glLoadIdentity()
        OpenGL.GLU.gluPerspective(90, float(w / h), min_scale, max_scale)
        OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW)
        OpenGL.GL.glLoadIdentity()
        OpenGL.GLU.gluLookAt(0, -1, 0, 0, 0, 0, 0, 0, 10)
        self.viewMatrix = OpenGL.GL.glGetFloatv(OpenGL.GL.GL_MODELVIEW_MATRIX)

    def paintGL(self):
        """
        Вызов функций для отрисовки планеток и траектории
        """
        OpenGL.GL.glClear(OpenGL.GL.GL_COLOR_BUFFER_BIT
                          | OpenGL.GL.GL_DEPTH_BUFFER_BIT)
        OpenGL.GL.glTranslated(self.scale_x, -self.scale_z, -self.scale_y)

        if self.start_modeling:
            self.calculation_module.recalculate_space_objects_positions()
        for obj in self.space_objects:
            if self.is_trajectory_shown and not self.start_modeling:
                obj.draw_trajectory()
            obj.draw()

            if obj.name == 'SpaceShip':
                self.current_velocity = int(math.sqrt(obj.vx**2 + obj.vy**2))
                if not self.start_modeling:
                    obj.set_arrow_angle(self.current_angle, obj.color)
                if obj.vx:
                    plus_pi = int(obj.vx < 0) * 180
                    obj.set_arrow_angle(
                        (math.atan(obj.vy / obj.vx) * 180 / math.pi) + plus_pi,
                        (1, 1, 1))
                else:
                    obj.set_arrow_angle(((180 / abs(obj.vy)) * obj.vy) / 2,
                                        (1, 1, 1))

        self.update()

    def keyPressEvent(self, event):
        """
        Обработка нажатий кнопок на клавиауре
        """
        if event.key() == Qt.Key_W:
            self.scale_y = self.scale_factor
        elif event.key() == Qt.Key_S:
            self.scale_y = -self.scale_factor
        elif event.key() == Qt.Key_D:
            self.scale_x = -self.scale_factor
        elif event.key() == Qt.Key_A:
            self.scale_x = self.scale_factor
        if event.key() == Qt.Key_Down:
            self.scale_z = -self.scale_factor
        if event.key() == Qt.Key_Up:
            self.scale_z = self.scale_factor
        if event.key() == Qt.Key_6:
            if self.space_objects[0].m - self.manual_control_delta_pulse \
                    / self.specific_impulse_of_rocket_engine > self.minimum_mass:
                self.calculation_module.v[0] += self.manual_control_delta_pulse \
                                                / self.space_objects[0].m
                self.space_objects[
                    0].m -= self.manual_control_delta_pulse / self.specific_impulse_of_rocket_engine
        if event.key() == Qt.Key_4:
            if self.space_objects[0].m - self.manual_control_delta_pulse \
                    / self.specific_impulse_of_rocket_engine > self.minimum_mass:
                self.calculation_module.v[0] -= self.manual_control_delta_pulse \
                                                / self.space_objects[0].m
                self.space_objects[
                    0].m -= self.manual_control_delta_pulse / self.specific_impulse_of_rocket_engine
        if event.key() == Qt.Key_8:
            if self.space_objects[0].m - self.manual_control_delta_pulse \
                    / self.specific_impulse_of_rocket_engine > self.minimum_mass:
                self.calculation_module.v[1] += self.manual_control_delta_pulse \
                                                / self.space_objects[0].m
                self.space_objects[
                    0].m -= self.manual_control_delta_pulse / self.specific_impulse_of_rocket_engine
        if event.key() == Qt.Key_2:
            if self.space_objects[0].m - self.manual_control_delta_pulse \
                    / self.specific_impulse_of_rocket_engine > self.minimum_mass:
                self.calculation_module.v[1] -= self.manual_control_delta_pulse \
                                                / self.space_objects[0].m
                self.space_objects[
                    0].m -= self.manual_control_delta_pulse / self.specific_impulse_of_rocket_engine

    def keyReleaseEvent(self, event: QtGui.QKeyEvent):
        """
        Обработка события клавиш на клавиатуре (отпускаем клавишу)
        """
        if event.key() == Qt.Key_W:
            self.scale_y = 0
        elif event.key() == Qt.Key_S:
            self.scale_y = 0
        elif event.key() == Qt.Key_D:
            self.scale_x = 0
        elif event.key() == Qt.Key_A:
            self.scale_x = 0
        if event.key() == Qt.Key_Down:
            self.scale_z = 0
        if event.key() == Qt.Key_Up:
            self.scale_z = 0

    def mousePressEvent(self, event: QtGui.QMouseEvent):
        """
        Обработка нажатия мышкой на экран
        """
        self.setFocus()
Пример #25
0
def calculate(personalData):
    calculation = Calculation()
    result = {
        'years': []
    }
    personalData.sort(key=operator.itemgetter('year'))
    personalData = personalData[-3:]
    for data in personalData:
        age = calculation.calcAge(data['testDate'], data['dateOfBirth'])
        print('\n\n' + data['name'] + ' ' + data['surname'] + ' ' + str(age))
        bmi = calculation.calcBmi(data['weight'], data['height'])
        wtoh = calculation.calcWToH(data['waist'], data['height'])
        ols = calculation.calcOls(data['olsR'], data['olsL'])
        scorePerO = calculation.calcScorePer(data['gender'], age, data['perO'], 'perO')
        scorePerI = calculation.calcScorePer(data['gender'], age, data['perI'], 'perI')
        scoreTable = [
            ('Standweitsprung', str(data['slj']) + ' m', calculation.calcScoreSlj(data['gender'], age, data['slj'])),
            ('Medizinballstoss', str(data['ssp']) + ' m', calculation.calcScoreSsp(data['gender'], age, data['ssp'])),
            ('Einbeinstand', str(ols) + ' s', calculation.calcScoreOls(data['gender'], age, ols)),
            ('Globaler Rumpfkrafttest', data['tms'] + ' s', calculation.calcScoreTms(data['gender'], age, data['tms'])),
            ('Progressiver Ausdauerlauf', data['perO'] + ' min:s', scorePerO) if scorePerI == 0 else ('20m Pendellauf', data['perI'] + ' min:s', scorePerI)
        ]

        #Berechnung Gesamtpunktzahl, Bewertung der Gesamtpunktzahl und Umrechnung der einzelnen Disziplinen für das Spider Diagramm
        totalScore = 0
        spiderScores = []
        spiderScoreLabels = []
        for score in scoreTable:
            totalScore = totalScore + score[2]
            if score[2] < 7:
                spiderScores.append(1)
            elif score[2] < 13:
                spiderScores.append(2)
            elif score[2] < 16:
                spiderScores.append(3)
            elif score[2] < 20:
                spiderScores.append(4)
            else:
                spiderScores.append(5)
            spiderScoreLabels.append(score[0])
        numberToLabel = calculation.numberToLabel(totalScore)

        result['id'] = data['id']
        result['name'] =  data['name'] + ' ' + data['surname']
        result['age'] =  str(age) + ' Jahre'
        result['heigth'] = data['height'] + ' cm'
        result['weight'] = data['weight'] + ' kg'
        result['bmi'] = str(bmi) + ' kg/m^2'
        result['wtoh'] = wtoh
        result['scoreTable'] = scoreTable
        result['totalScore'] = totalScore
        result['numberToLabel'] = numberToLabel
        result['years'].append({
            'year': data['year'],
            'spiderScoreLabels': spiderScoreLabels,
            'spiderScores': spiderScores
        })
    return result
Пример #26
0
class Calc_UI(calc_tk.Canvas):

    def __init__(self, root, w, h, btn, column_num):
        self.root = root
        self.width = w
        self.height = h
        self.main_colours = ["#c0c0c0", "#1d1d1b", "#2b2b2b", "#343434"]
        self.btn_list = btn
        self.column_num = column_num

        super().__init__(root, width=w, height=h)
        self.pack()
        self.set_main_ui()
        self.set_output_field()
        self.set_input_field()
        self.set_calculation_field()
        self.calc_manage = Calculation()
        root.bind('<Return>', self.result)
        root.bind('<KP_Enter>', self.result)
        root.bind('<BackSpace>', self._d_the_last)
        root.bind("<Key>", self.key)
        root.bind("<Control-q>", self.exit_win)

    def set_main_ui(self):
        self.root.title("Duck Calcurator 3.1.0")
        self.frame = calc_tk.Frame(self, bg=self.main_colours[1])
        self.frame.place(relx=0.5, rely=0, relwidth=1, relheight=1, anchor='n')

    def set_output_field(self):
        output = calc_tk.Frame(self.frame, bg=self.main_colours[2])
        output.place(relx=0.5, rely=0, relwidth=1, relheight=0.4, anchor='n')
        self.output_entry = calc_tk.Entry(output, bg=self.main_colours[2], bd=0,
                                          highlightbackground=self.main_colours[2], foreground=self.main_colours[0])
        self.output_entry.place(relx=0.5, rely=0, relwidth=1, relheight=1, anchor='n')

    def set_input_field(self):
        input_field = calc_tk.Frame(self.frame, bg=self.main_colours[3])
        input_field.place(relx=0.5, rely=0.405, relwidth=1, relheight=0.15, anchor='n')
        self.input_entry = calc_tk.Entry(input_field, bg=self.main_colours[3], bd=0,
                                         highlightbackground=self.main_colours[3], foreground=self.main_colours[0])
        self.input_entry.place(relx=0.5, rely=0, relwidth=1, relheight=1, anchor='n')

    def set_calculation_field(self):
        calculate = calc_tk.Frame(self.frame, bg='#3e3e3e')
        calculate.place(relx=0.5, rely=0.56, relwidth=1, relheight=0.45, anchor='n')
        r = 0
        c = 1
        n = 0

        for number in self.btn_list:
            cmd = partial(self.click, number)
            numbers = calc_tk.Button(calculate, text=number, width=3, height=1,
                                     bg="#484848", bd=0.2, highlightbackground="#484847",
                                     foreground=self.main_colours[0],
                                     command=cmd)
            numbers.grid(row=r, column=c, ipadx=8, ipady=2, padx=2, pady=2)
            n += 1
            c += 1
            if c > self.column_num:
                c = 1
                r += 1

    def _d_the_last(self, event):
        self.input_entry.delete(len(self.input_entry.get()) - 1)

    def key(self, event):
        self.input_entry.insert(calc_tk.END, str(event.char))

    def exit_win(self, event):
        self.root.destroy()

    def click(self, btn):
        if btn == "C":
            self.input_entry.delete(0, calc_tk.END)
            self.output_entry.delete(0, calc_tk.END)
        elif btn == "=":
            self.output_entry.delete(0, calc_tk.END)
            self.result('<Return>')
        elif btn == "D":
            self._d_the_last('<BackSpace>')
        elif btn == '\u03C0':
            self.input_entry.insert(calc_tk.END, '3.14')
        else:
            self.input_entry.insert(calc_tk.END, str(btn))

    def result(self, event):
        self.output_entry.delete(0, calc_tk.END)
        check_str = "%+-/*)(.0123456789√^\u221B'sin''cos''tan''rad''deg''abs''lg''ln''fac'"
        input_string = str(self.input_entry.get()).replace(' ', '')
        for item in input_string:
            if item not in check_str or not self.calc_manage.result(input_string):
                msg.showerror("Error!", "Please check your input")
                self.output_entry.insert(0, '0')
                raise ValueError
        self.output_entry.insert(0, self.calc_manage.result(input_string))