Example #1
0
def main():
    """ """
    input_file = InputTools.get_file_name("Input file? ", 'hepmc').strip()
    new_name = InputTools.get_file_name(
        "Output file? ", Components.EventWise.FILE_EXTENTION).strip()
    dir_name, file_name = os.path.split(input_file)
    new_dir_name, new_file_name = os.path.split(new_name)
    print(f"Reading {file_name}")
    eventWise = Hepmc(dir_name, file_name, 0, 10000)
    eventWise.dir_name = new_dir_name
    eventWise.file_name = new_file_name
    print(f"Writing {eventWise.file_name}")
    eventWise.write()
Example #2
0
def main():
    """ """
    from jet_tools import Components, InputTools, FormJets
    eventWise_path = InputTools.get_file_name("Name the eventWise: ", '.awkd').strip()
    if eventWise_path:
        eventWise = Components.EventWise.from_file(eventWise_path)
        jets = FormJets.get_jet_names(eventWise)
        repeat = True
        barrel_radius2 = np.max((eventWise.Track_OuterX**2 +
                                 eventWise.Track_OuterY**2)))
        barrel_radius = np.sqrt(barrel_radius2)
        half_barrel_length = np.max(np.abs(eventWise.Track_OuterZ.flatten()))
        while repeat:
            eventWise.selected_event = int(input("Event number: "))
            jet_name = InputTools.list_complete("Jet name (empty for none): ", jets).strip()
            if not jet_name:
                outer_pos, tower_pos, barrel_radius, halfbarrel_length\
                        = plot_tracks_towers(eventWise, barrel_radius=barrel_radius,
                                             half_barrel_length=half_barrel_length)
            else:
                jets_here = getattr(eventWise, jet_name + "_Label")
                print(f"Number of jets = {len(jets_here)}")
                source_idx = eventWise.JetInputs_SourceIdx
                n_source = len(source_idx)
                jets_here = [source_idx[jet[jet < n_source]] for jet in jets_here]
                all_jet_particles = set(np.concatenate(jets_here))
                assert all_jet_particles == set(source_idx)
                results = plot_tracks_towers(eventWise, particle_jets=jets_here,
                                             barrel_radius=barrel_radius,
                                             half_barrel_length=half_barrel_length)
                outer_pos, tower_pos, barrel_radius, halfbarrel_length = results
            plot_beamline(halfbarrel_length*3)
            print(f"Barrel_radius = {barrel_radius}, half barrel length = {halfbarrel_length}")
            mlab.show()
            repeat = InputTools.yesNo_question("Repeat? ")
Example #3
0
def get_data_file():
    """ """
    # to start with we know nothing
    root_file = hepmc_file = eventWise_file = False
    start_file = InputTools.get_file_name("Name the data file to start from; ").strip()
    if start_file.endswith('.root'):
        root_file = start_file
        hepmc_file = InputTools.get_file_name("Please give the corripsonding .hepmc file; ", '.hepmc')
    elif start_file.endswith('.hepmc'):
        hepmc_file = start_file
        root_file = InputTools.get_file_name("If desired enter a .root file (blank to skip); ", '.root').strip()
    if hepmc_file and root_file:
        eventWise = JoinHepMCRoot.marry(hepmc_file, root_file)
    elif hepmc_file:
        dir_name, file_name = os.path.split(hepmc_file)
        eventWise = ReadHepmc.Hepmc(dir_name, file_name)
    elif start_file.endswith('.awkd'):
        eventWise = Components.EventWise.from_file(start_file)
    else:
        raise ValueError(f"'{start_file}' not of recognised type,"
                          " please give a '.hepmc' (and optionally a '.root') or an '.awkd' file")
    return eventWise
Example #4
0
def test_get_file_name():
    with TempTestDir("tst") as dir_name:
        file1 = "meow.cat"
        file2 = "maple.syrup"
        new_name1 = os.path.join(dir_name, file1)
        open(new_name1, 'w').close()  # create the file
        new_name2 = os.path.join(dir_name, file2)
        open(new_name2, 'w').close()  # create the file
        # chcek get file name allows arbitary input
        arbitary = "jflsafhdkas ;lasjdf"
        with replace_stdin(io.StringIO(arbitary)):
            found = InputTools.get_file_name("Msg ")
        assert found.strip() == arbitary
        with replace_stdin(io.StringIO(arbitary)):
            found = InputTools.get_file_name("Msg ", "cat")
        assert found.strip() == arbitary
        # tab completing a file that ends in cat should get the first name
        complete = os.path.join(dir_name, 'm') + '\t'
        with replace_stdin(io.StringIO(complete)):
            with unittest.mock.patch('jet_tools.InputTools.tab_complete',
                                     new=fake_tab_complete):
                found = InputTools.get_file_name("Msg ", "cat")
        assert found.strip(
        ) == new_name1, f"Found {found} from {complete}, expected {new_name1}"
"""Plot what changes the number of dimensions in the embedding space"""
from jet_tools import FormJets, InputTools, Components
import matplotlib
from matplotlib import pyplot as plt
from ipdb import set_trace as st
import numpy as np
import warnings
warnings.filterwarnings('ignore')

eventWise_path = InputTools.get_file_name(
    "Where is the eventwise of collection fo eventWise? ", '.awkd').strip()
c_class = FormJets.SpectralFull
spectral_jet_params = dict(
    ExpofPTMultiplier=0,
    ExpofPTPosition='input',
    ExpofPTFormat='Luclus',
    NumEigenvectors=np.inf,
    StoppingCondition='meandistance',
    EigNormFactor=1.4,
    EigenvalueLimit=0.4,
    Laplacien='symmetric',
    DeltaR=np.inf,  # don't stop!
    AffinityType='exponent',
    AffinityExp=2.,
    Sigma=.15,
    CombineSize='sum',
    EigDistance='abscos',
    CutoffKNN=None,
    CutoffDistance=None,
    PhyDistance='angular')
max_particles = 140
Example #6
0
def check_problem():
    """ """
    eventWise = get_data_file()
    BATCH_LENGTH = InputTools.get_literal("How long should the batch be (-1 for all events)? ", int)
    if BATCH_LENGTH == -1:
        BATCH_LENGTH = np.inf
    eventWise = define_inputs(eventWise)
    params = {'DeltaR': 0.4, 'ExponentMultiplier': 0.1, 'NumEigenvectors': 2, 'Laplacien': 'symmetric', "AffinityType": 'linear', "WithLaplacienScaling": False, "CutoffDistance":  5.2, "Invarient": 'normed'}
    jet_name = "ProblemJet"
    params["jet_name"] = jet_name
    FormJets.cluster_multiapply(eventWise, FormJets.Spectral, params, batch_length=BATCH_LENGTH)


if __name__ == '__main__':
    eventWise = get_data_file()
    BATCH_LENGTH = InputTools.get_literal("How long should the batch be (-1 for all events)? ", int)
    if BATCH_LENGTH == -1:
        BATCH_LENGTH = np.inf
    eventWise = define_inputs(eventWise)
    jet_name = get_existing_clusters(eventWise)
    if not jet_name:
        jet_name = make_new_cluster(eventWise)
    # now do tagging
    pretag_jet_pt_cut = get_make_tags(eventWise, jet_name)
    # now calculate shapes and mass peaks
    img_base = InputTools.get_file_name("Give a name to save the plots (empty for no save); ")
    plot_results(eventWise, jet_name, pretag_jet_pt_cut, img_base)



Example #7
0
    try:  # if the user presses ctrl-c we want to go back to the script
        set_trace()
        # now have a play with the objects created :)
        # press c-enter when you're done
    except:
        pass
    print("...")


print("~~ Example of reading a hepmc file ~~")
hepmc_path = "./mini_data/mini.hepmc"
if os.path.exists(hepmc_path):
    print(f"Found a file to read in at {hepmc_path}")
else:
    message = "Please give the location of a hepmc file (can tab complete): "
    hepmc_path = InputTools.get_file_name(message, "hepmc").strip()
    if not os.path.exists(hepmc_path):
        print("Not a vaild file path")
        exit
print("This hepmc file will be read into an awkward array")
input("press enter to continue\n...")
print(" > from jet_tools import ReadHepmc")
from jet_tools import ReadHepmc
print(" > required_size = 10")
required_size = 10
print(
    " > eventWise = ReadHepmc.Hepmc(*os.path.split(hepmc_path), start=0, stop=required_size)"
)
eventWise = ReadHepmc.Hepmc(hepmc_path, start=0, stop=required_size)
print(
    "If the chosen stop point is beyond the end of the hepmc (or equal to np.inf) "
Example #8
0
    eventWise.selected_event = None
    if idealised_jet_clusters is None:
        idealised_jet_clusters = eventWise.Solution
    if jet_name is None:
        jet_name = "SolJet"
    # updated_dict will be replaced in the first batch
    updated_dict = None
    n_events = len(idealised_jet_clusters)
    jet_list = []
    for event_n, jets_gids in enumerate(idealised_jet_clusters):
        if event_n % 100 == 0:
            print(f"{event_n/n_events:.1%}", end='\r', flush=True)
        eventWise.selected_event = event_n
        jet = FormJets.Partitional(eventWise)
        source_idx = eventWise.JetInputs_SourceIdx.tolist()
        for gids in jets_gids:
            if len(gids):
                labels = [source_idx.index(i) for i in gids]
                jet.create_jet(labels)
        jet_list.append(jet)
    updated_dict = FormJets.create_jet_contents(jet_list)
    eventWise.append(**updated_dict)


if __name__ == '__main__':
    path = InputTools.get_file_name("Name eventWise file: ", '.awkd').strip()
    if path:
        eventWise = Components.EventWise.from_file(path)
        append_solution_and_weights(eventWise)
        solution_to_jet(eventWise)
Example #9
0
def main():
    """Launch file, makes and saves a dot graph"""
    repeat = True
    eventWise_path = InputTools.get_file_name("Name the eventWise; ", '.awkd')
    eventWise = Components.EventWise.from_file(eventWise_path)
    while repeat:
        from jet_tools import FormShower
        eventWise.selected_event = int(input("Event number: "))
        showers = FormShower.get_showers(eventWise)
        jet_name = "HomeJet"
        chosen_showers = []
        for i, shower in enumerate(showers):
            shower_roots = [shower.labels[i] for i in shower.root_local_idxs]
            if 'b' not in shower_roots and 'bbar' not in shower_roots:
                continue
            chosen_showers.append(shower)
            print(f"Shower roots {shower.root_idxs}")
            max_children = max([len(d) for d in shower.children])
            end_ids = shower.ends
            print(
                f"Drawing shower {i}, has {max_children} max children. Daughters to particles ratio = {max_children/len(shower.children)}"
            )
            # pick the jet with largest overlap
            largest_overlap = 0
            picked_jet = 0
            for i in range(len(eventWise.HomeJet_Parent)):
                is_external = getattr(eventWise, jet_name + "_Child1")[i] < 0
                input_idx = getattr(eventWise,
                                    jet_name + "_Label")[i][is_external]
                jet_particles = eventWise.JetInputs_SourceIdx[input_idx]
                matches_here = sum([p in end_ids for p in jet_particles])
                if matches_here > largest_overlap:
                    largest_overlap = matches_here
                    picked_jet = i
            print(
                f"A jet contains {largest_overlap} out of {len(end_ids)} end products"
            )
            graph = DotGraph(shower=shower,
                             eventWise=eventWise,
                             jet_name=jet_name,
                             jet_num=picked_jet,
                             use_TracksTowers=True)
            base_name = f"event{eventWise.selected_event}_plot"
            dotName = base_name + str(i) + ".dot"
            legendName = base_name + str(i) + "_ledg.dot"
            with open(dotName, 'w') as dotFile:
                dotFile.write(str(graph))
            with open(legendName, 'w') as dotFile:
                dotFile.write(graph.legend)
        #amalgam_shower = chosen_showers[0]
        #if len(chosen_showers)>1:
        #    for shower in chosen_showers[1:]:
        #        amalgam_shower.amalgamate(shower)
        #print("Drawing the amalgam of all b showers")
        #graph = DotGraph(shower=amalgam_shower, observables=obs)
        #dotName = f"event{eventWise.selected_event}_mixing_plot.dot"
        #legendName ="mixing_ledg.dot"
        #with open(dotName, 'w') as dotFile:
        #    dotFile.write(str(graph))
        #with open(legendName, 'w') as dotFile:
        #    dotFile.write(graph.legend)
        repeat = InputTools.yesNo_question("Again? ")