コード例 #1
0
 def __init__(self, in_fname, interv, offset=None):
     self.path = in_fname
     self.__data_obj = ReadHepmc.Hepmc(in_fname,
                                       start=interv[0],
                                       stop=interv[1])
     if (offset is not None):
         self.__evt_offset = offset
     else:
         self.__evt_offset = interv[0]
     self.num_evts = self.__data_obj.n_events
     self.clustered = False
コード例 #2
0
def test_ReadHepmc():
    check_lines()
    hepmc_file = os.path.join(data_dir, "mini.hepmc")
    n_events = 4
    # try starting from 0
    hepmc1 = ReadHepmc.Hepmc(hepmc_file, 0, n_events)
    # try startng from 1
    start2 = 1
    hepmc2 = ReadHepmc.Hepmc(hepmc_file, start=start2, stop=n_events)
    idents = PDGNames.Identities()
    all_ids = set(idents.particle_data[:, idents.columns["id"]])
    for event_n in range(n_events):  # loop over out selection of events
        hepmc1.selected_event = event_n
        # sanity checks on the components
        assert hepmc1.Event_n == event_n
        # again for the other one
        check_event_consistancy(hepmc1, all_ids)
        try:
            hepmc2.selected_event = event_n
            assert hepmc2.Event_n == event_n + 1
        except (IndexError, ValueError):
            assert event_n + start2 == n_events
            continue  # reach the end of 1
        check_event_consistancy(hepmc2, all_ids)
コード例 #3
0
def test_marry():
    # get a root file
    root_file = os.path.join(data_dir, "mini.root")
    components = ["Particle", "Track", "Tower"]
    rootreadout = Components.RootReadout(root_file, components)
    # decide how many events
    n_events = min(len(rootreadout.Energy), 4)

    with TempTestDir("marry") as dir_name:
        # create a cut down verson of the root file
        contents = {
            name: getattr(rootreadout, name)[:n_events]
            for name in rootreadout.columns
        }
        columns = list(contents.keys())
        restricted = Components.EventWise(os.path.join(dir_name,
                                                       "restricted.parquet"),
                                          columns=columns,
                                          contents=contents)
        hepmc_file = os.path.join(data_dir, "mini.hepmc")
        hepmc = ReadHepmc.Hepmc(hepmc_file, 0, n_events)
        JoinHepMCRoot.marry(hepmc, restricted)
        married_name = 'restricted_particles.parquet'
        married = Components.EventWise.from_file(
            os.path.join(dir_name, married_name))
        # check that the married file contains the columns of the components
        for column in married.columns:
            values = getattr(married, column)
            assert len(values) == n_events
        # check that the number of particles in each event is consistent across all columns
        per_particle_cols = married._column_contents['per_particle'][0]
        values0 = getattr(married, str(per_particle_cols[0]))
        nparticles_col0 = np.array([len(event) for event in values0])
        for column in per_particle_cols[1:]:
            if column.split('_',
                            1)[0] in ("Tower", "Track", "Vertex", "Weight"):
                continue  #  these do have diferent frequencies
            if column == 'Random_state_ints':
                continue
            values = getattr(married, str(column))
            nparticles_here = [len(event) for event in values]
            tst.assert_allclose(
                nparticles_col0,
                nparticles_here,
                err_msg=
                f"{per_particle_cols[0]} and {column} cound diferent particles"
            )
コード例 #4
0
def get_data_file(input_file):
    hepmc_extention = ".hepmc"
    if input_file.endswith("hepmc"):
        read_file = input_file.replace(hepmc_extention,
                                       Components.EventWise.FILE_EXTENTION)
    else:
        read_file = input_file
    if os.path.exists(read_file):
        input_file = read_file
        data = Components.EventWise.from_file(input_file)
        Components.add_all(data)
        return data
    else:
        data = ReadHepmc.Hepmc(input_file)
        data.file_name = data.file_name.replace(
            hepmc_extention, Components.EventWise.FILE_EXTENTION)
        data.write()
        del data
        return get_data_file(input_file)
コード例 #5
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
コード例 #6
0
def check_lines():
    particles = []
    particles.append({'barcode': 3, 'Start_vertex_barcode': -1, 'End_vertex_barcode': -3, 'PID': 2, 'Px': 0., 'Py': 0., 'Pz': 7.3759823919779751e+02, 'Energy': 7.3759823919779751e+02})
    particles.append({'barcode': 9, 'Start_vertex_barcode': -1, 'End_vertex_barcode': -7, 'PID': 21, 'Px': -1.4386555718774256e+01, 'Py': -1.6927530140503261e+01, 'Pz': 4.6864615737194424e+02, 'Energy': 4.6917239377610036e+02})
    particles.append({'barcode': 4, 'Start_vertex_barcode': -2, 'Pz':58.104791987011104, 'End_vertex_barcode': -3, 'PID': -2, 'Px': 0, 'Py': 0, 'Pz': -5.1893763547975027e+00, 'Energy': 5.1893763547975027e+00})
    particles.append({'barcode': 5, 'Start_vertex_barcode': -3, 'End_vertex_barcode': -6, 'PID': 35, 'Px': 0, 'Py': 7.1054273576000000e-15, 'Pz': 7.3240886284999999e+02, 'Energy': 7.4278761555910899e+02})
    particles.append({'barcode': 6, 'Start_vertex_barcode': -4, 'End_vertex_barcode': -1, 'PID': 2, 'Px': -3.5527136788005009e-15, 'Py': -3.5527136788005009e-15, 'Pz': 1.2709487353166983e+03, 'Energy': 1.2709487353166983e+03})
    particles.append({'barcode': 7, 'Start_vertex_barcode': -5, 'End_vertex_barcode': -2, 'PID': -2, 'Px': -3.5527136788005009e-15, 'Py': -3.5527136788005009e-15, 'Pz': -5.1893763547976164e+00, 'Energy': 5.1893763547975027e+00})
    particles.append({'barcode': 8, 'Start_vertex_barcode': -6, 'End_vertex_barcode': -13, 'PID': 35, 'Px': 1.4386555718906120e+01, 'Py': 1.6927530140658423e+01, 'Pz': 7.9711320159753188e+02, 'Energy': 8.0696571790253006e+02})
    # for h1bBatch2.hepmc
    #particles.append({'barcode': 3, 'Start_vertex_barcode': -1, 'End_vertex_barcode': -3,
    #    'PID': 1, 'Px': 0., 'Py': 0., 'Pz':58.104791987011104, 'Energy':58.104791987011104})
    #particles.append({'barcode': 4, 'Start_vertex_barcode': -2, 'End_vertex_barcode': -3,
    #    'PID': -1, 'Px': 0., 'Py': 0., 'Pz':-59.434584436371104, 'Energy':59.434584436371104})
    #particles.append({'barcode': 9, 'Start_vertex_barcode': -2, 'End_vertex_barcode': -10,
    #    'PID': 1, 'Px': -105.03226729224349, 'Py': -58.130810879967129, 'Pz':-739.62417574317283, 'Energy':749.30300852851167})
    #particles.append({'barcode': 5, 'Start_vertex_barcode': -3, 'End_vertex_barcode': -6,
    #    'PID': 35, 'Px': 0., 'Py': 0., 'Pz':-1.3297924496000000, 'Energy':117.53937642477460})
    #particles.append({'barcode': 6, 'Start_vertex_barcode': -4, 'End_vertex_barcode': -1,
    #    'PID': 1, 'Px': -1.2789769243681803*10**(-13), 'Py': -5.6843418860808015*10**(-14), 'Pz':58.104791987011055, 'Energy':58.104791987011112})
    #particles.append({'barcode': 14, 'Start_vertex_barcode': -4, 'End_vertex_barcode': -15,
    #    'PID': -1, 'Px': -5.7820152482327529, 'Py': -94.171736449210982, 'Pz': 362.01370390194961, 'Energy': 374.10664035673017})
    #particles.append({'barcode': 7, 'Start_vertex_barcode': -5, 'End_vertex_barcode': -2,
    #    'PID': 21, 'Px': 8.7041485130612273*10**(-14), 'Py': 6.5725203057809267*10**(-14), 'Pz': -876.93569382111320, 'Energy': 876.93569382111275})
    #particles.append({'barcode': 8, 'Start_vertex_barcode': -6, 'End_vertex_barcode': -9,
    #    'PID': 35, 'Px': 105.03226729368578, 'Py': 58.130810880765388, 'Pz':-79.206726092116511, 'Energy':185.73747728206331})
    hepmc_file = os.path.join(data_dir, "mini.hepmc")
    n_events = 1
    hepmc = ReadHepmc.Hepmc(hepmc_file, 0, n_events)
    hepmc.selected_event = 0
    for particle in particles:
        index = np.where(hepmc.Particle_barcode == particle['barcode'])[0][0]
        assert particle['Start_vertex_barcode'] == hepmc.Start_vertex_barcode[index]
        assert particle['End_vertex_barcode'] == hepmc.End_vertex_barcode[index]
        assert particle['PID'] == hepmc.MCPID[index]
        tst.assert_allclose([particle['Px'], particle['Py'], particle['Pz'], particle['Energy']],
                            [hepmc.Px[index], hepmc.Py[index], hepmc.Pz[index], hepmc.Energy[index]])
コード例 #7
0
"""Processing events in version 1 of the paper"""
#hepmc_dir = "/scratch/hadh1g17/MG5_aMC_v2_6_7/ttsemileptonic/Events/run_02/tag_1_pythia8_events.hepmc"
#hepmc_dir = "../megaIgnore/ttsemileptonic_pt4.hepmc"
hepmc_dir = "/home/henry/Programs/MG5_aMC_v2_9_2/ttsemileptonic3/Events/run_03/tag_1_pythia8_events.hepmc"
from jet_tools import ReadHepmc, Components, FormJets, TrueTag, MassPeaks, FormJetInputs
import numpy as np

hepmc = ReadHepmc.Hepmc(hepmc_dir, 0, np.inf)
hepmc.file_name = "ttsemileptonic_pt7.awkd"
#hepmc.dir_name = "/home/hadh1g17/jets/megaIgnore"
hepmc.dir_name = "../megaIgnore"
hepmc.write()
print()
print("Adding components")
print()
Components.add_all(hepmc)
print()
print("Creating jet inputs")
print()
FormJetInputs.create_jetInputs(hepmc)
jet_names = []
jet_name = "AntiKTp8Jet"
jet_names.append(jet_name)
jet_class = FormJets.Traditional
jet_params = {
    'DeltaR': 0.8,
    'ExpofPTFormat': 'min',
    'ExpofPTMultiplier': 0,
    'PhyDistance': 'angular'
}
print()
コード例 #8
0
    new_particle_barcode = inserted_eventWise.Particle_barcode + free_particle_barcode
    inserted_eventWise.append(Vertex_barcode=new_vertex_barcode,
                              End_vertex_barcode=new_end_barcode,
                              Start_vertex_barcode=new_start_barcode,
                              Particle_barcode=new_particle_barcode)
    # for ram reasons go throught the columns in small sets
    columns = set(main_eventWise.columns).intersection(
        inserted_eventWise.columns)
    new_content = {}
    for i, column in enumerate(columns):
        main = getattr(main_eventWise, column)
        insert = getattr(inserted_eventWise, column)
        new_column = [a.tolist() + b.tolist() for a, b in zip(main, insert)]
        new_content[column] = ak.from_iter(new_column)
    main_eventWise.append(**new_content)


def merge_Hepmc(path1,
                path2,
                out_path=None,
                same_beamparticles=False,
                batch_len=None):
    pass


if __name__ == '__main__':
    path = "megaIgnore/join/tag_1_pythia8_events_pileup.hepmc"
    hepmc = ReadHepmc.Hepmc(*os.path.split(path), 0, 10)
    new_path = path + ".copy"
    write_Hepmc(hepmc, new_path)
コード例 #9
0
def void_test_ReadHepmc2():
    hepmc_file = os.path.join(data_dir, "billy_tag_2_pythia8_events.hepmc")
    n_events = 4
    hepmc = ReadHepmc.Hepmc(hepmc_file, 0, n_events)
    idents = PDGNames.Identities()
    mom_diff = []
    all_ids = set(idents.particle_data[:, idents.columns["id"]])
    for event_n in range(n_events):  # loop over out selection of events
        hepmc.selected_event = event_n
        # sanity checks on the components
        assert hepmc.Event_n == event_n
        # check the beam particles
        beam_idx1 = np.where(hepmc.Particle_barcode == hepmc.Barcode_beam_particle1)[0][0]
        beam_idx2 = np.where(hepmc.Particle_barcode == hepmc.Barcode_beam_particle2)[0][0]
        assert hepmc.Is_root[beam_idx1]
        assert hepmc.Is_root[beam_idx2]
        assert len(hepmc.Parents[beam_idx1]) == 0
        assert len(hepmc.Parents[beam_idx2]) == 0
        # valid PID
        assert set(np.abs(hepmc.MCPID)).issubset(all_ids)
        # conservation of momentum at the vertices
        parent_p4 = np.zeros(4)
        child_p4 = np.zeros(4)
        issues = 0
        relations = 0
        conserved_multiplicity = []
        unconserved_multiplicity = []
        for v_barcode in hepmc.Vertex_barcode:
            parent_p4[:] = 0
            child_p4[:] = 0
            parents_idx = np.where(hepmc.End_vertex_barcode == v_barcode)[0]
            children_idx = np.where(hepmc.Start_vertex_barcode == v_barcode)[0]
            if len(parents_idx) == 0:
                for cidx in children_idx:
                    assert hepmc.Is_root[cidx]
            elif len(children_idx) == 0:
                for pidx in parents_idx:
                    assert hepmc.Is_leaf[pidx]
            else:
                for pidx in parents_idx:
                    parent_p4 += (hepmc.Energy[pidx], hepmc.Px[pidx], hepmc.Py[pidx], hepmc.Pz[pidx])
                for cidx in children_idx:
                    child_p4 += (hepmc.Energy[cidx], hepmc.Px[cidx], hepmc.Py[cidx], hepmc.Pz[cidx])
                relations += 1
                mom_diff.append(parent_p4 - child_p4)
                try:
                    tst.assert_allclose(parent_p4[1:], child_p4[1:], rtol=0.05, atol=0.001)
                    conserved_multiplicity.append(len(children_idx) + len(parents_idx))
                except AssertionError as e:
                    if issues < 1 and event_n==0:
                        parent_barcodes = hepmc.Particle_barcode[parents_idx]
                        children_barcodes = hepmc.Particle_barcode[children_idx]
                        print(f"Vertex {v_barcode} has incoming particles with barcodes {parent_barcodes} and outgoing particles with barcodes {children_barcodes}")
                        print(f"The incoming total momentum is {parent_p4}")
                        print(f"The outgoing total momentum is {child_p4}")
                    issues += 1
                    unconserved_multiplicity.append(len(children_idx) + len(parents_idx))
        print(f"Event {event_n}")
        print(f"non-conservation {issues}; {100*issues/relations:.1f}%")
        print(f"multipicity, conserved {np.mean(conserved_multiplicity):.2f}, unconserved {np.mean(unconserved_multiplicity):.2f}")
    return np.array(mom_diff)
コード例 #10
0
def void_test_ReadHepmc():
    hepmc_file = os.path.join(data_dir, "mini.hepmc")
    n_events = 1
    hepmc = ReadHepmc.Hepmc(hepmc_file, 0, n_events)
    idents = PDGNames.Identities()
    all_ids = set(idents.particle_data[:, idents.columns["id"]])
    for event_n in range(n_events):  # loop over out selection of events
        hepmc.selected_event = event_n
        # sanity checks on the components
        assert hepmc.Event_n == event_n
        # check the beam particles
        beam_idx1 = np.where(hepmc.Particle_barcode == hepmc.Barcode_beam_particle1)[0][0]
        beam_idx2 = np.where(hepmc.Particle_barcode == hepmc.Barcode_beam_particle2)[0][0]
        assert hepmc.Is_root[beam_idx1]
        assert hepmc.Is_root[beam_idx2]
        assert len(hepmc.Parents[beam_idx1]) == 0
        assert len(hepmc.Parents[beam_idx2]) == 0
        # valid PID
        assert set(np.abs(hepmc.MCPID)).issubset(all_ids)
        # conservation of momentum and parent child reflection
        num_particles = len(hepmc.MCPID)
        parent_p4 = np.zeros(4)
        child_p4 = np.zeros(4)
        self_p4 = np.zeros(4)
        children_issues = 0
        children_relations = 0
        parent_issues = 0
        parent_relations = 0
        conserved_parent_multiplicity = []
        conserved_children_multiplicity = []
        unconserved_parent_multiplicity = []
        unconserved_children_multiplicity = []
        for idx in range(num_particles):  # loop over particles in event
            parent_p4[:] = 0
            child_p4[:] = 0
            self_p4[:] = (hepmc.Energy[idx], hepmc.Px[idx], hepmc.Py[idx], hepmc.Pz[idx])
            if not hepmc.Is_root[idx]:
                parent_relations += 1
                # we have already checked the parents of roots
                parent_idx = hepmc.Parents[idx]
                assert len(parent_idx) > 0
                for pidx in parent_idx:
                    assert idx in hepmc.Children[pidx]
                    parent_p4 += (hepmc.Energy[pidx], hepmc.Px[pidx], hepmc.Py[pidx], hepmc.Pz[pidx])
                    # if these parents have children besides this child
                    # subtract their momentum out
                    for cidx in hepmc.Children[pidx]:
                        if cidx == idx:
                            continue
                        else:
                            parent_p4 -= (hepmc.Energy[cidx], hepmc.Px[cidx], hepmc.Py[cidx], hepmc.Pz[cidx])
                try:
                    tst.assert_allclose(parent_p4[1:], self_p4[1:], rtol=0.05, atol=0.001)
                    conserved_parent_multiplicity.append(len(parent_idx))
                except AssertionError as e:
                    #print(f"Event {event_n}, particle {idx}, parents; {e}")
                    parent_issues += 1
                    unconserved_parent_multiplicity.append(len(parent_idx))
            if hepmc.Is_leaf[idx]:
                assert len(hepmc.Children[idx]) == 0
            else:
                children_relations += 1
                children_idx = hepmc.Children[idx]
                assert len(children_idx) > 0
                for cidx in children_idx:
                    assert idx in hepmc.Parents[cidx]
                    child_p4 += (hepmc.Energy[cidx], hepmc.Px[cidx], hepmc.Py[cidx], hepmc.Pz[cidx])
                    # if these children have parents besides this one
                    # subtract their momentum out
                    for pidx in hepmc.Parents[cidx]:
                        if pidx == idx:
                            continue
                        else:
                            child_p4 -= (hepmc.Energy[pidx], hepmc.Px[pidx], hepmc.Py[pidx], hepmc.Pz[pidx])
                try:
                    tst.assert_allclose(child_p4[1:], self_p4[1:], rtol=0.05, atol = 0.001)
                    conserved_children_multiplicity.append(len(children_idx))
                except AssertionError as e:
                    #print(f"Event {event_n}, particle {idx}, children; {e}")
                    children_issues += 1
                    unconserved_children_multiplicity.append(len(children_idx))
        print(f"Event {event_n}")
        print(f"Children non-conservation {children_issues}; {100*children_issues/children_relations:.1f}%")
        print(f"Parent non-conservation {parent_issues}; {100*parent_issues/parent_relations:.1f}%")
        print(f"Any non-conservation {100*(parent_issues+children_issues)/(children_relations+parent_relations):.1f}%")
        print(f"Children multipicity, conserved {np.mean(conserved_children_multiplicity):.2f}, unconserved {np.mean(unconserved_children_multiplicity):.2f}")
        print(f"Parent multipicity, conserved {np.mean(conserved_parent_multiplicity):.2f}, unconserved {np.mean(unconserved_parent_multiplicity):.2f}")
コード例 #11
0
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) "
    "then the whole file is read. "
    "The awkward array is wrapped in a cutsom object called an EventWise. "
    "If the hepmc file is very large it may be necessary to read it in chunks. "
    "The chunks can be combined using eventWise.combine (see the doc string for combine)."
)
print(" > from jet_tools.Components import EventWise")
from jet_tools.Components import EventWise
print(
    "This class is structured around the format of event by event particle data."
)
print(
    "(for direct access to the awkward array use EventWise._column_contents)")
input("press enter to continue\n...")
コード例 #12
0
hepmc_name = sys.argv[1]
pileup_name = sys.argv[2]

# don't be too stiff about the name of the file
file_num = int('0' +
               ''.join((c
                        for c in os.path.split(hepmc_name)[1] if c.isdigit())))
# but try to find a number in it

higgs_weight = hepmc_name.split('/')[-2]
print(f"Working on a {higgs_weight} event")
hepmc_save_dir = os.path.join(os.path.split(pileup_name)[0], higgs_weight)
print(f"Will be saving in {hepmc_save_dir}")

print("Reading hepmc")
ew = ReadHepmc.Hepmc(hepmc_name)
ew.selected_event = None
num_events = len(ew.X)
print(f"Contains {num_events} events")
ew.dir_name = hepmc_save_dir
i = 0
while True:
    ew.file_name = f"{i:02}_{file_num:02}_signal.parquet"
    try:
        # will throw an error if the fiel exists
        open(ew.path_name, 'x').close()
        # otherwise, works like touch
        break
    except FileExistsError:
        i += 1
ew.write()
コード例 #13
0
def marry(hepmc, root_particles):
    """
    Combine the information in a hepmc file and a root file
    in one eventWise, to have richer information about the particles

    Parameters
    ----------
    hepmc : str or EventWise
        if a str should be the path to the hepmc file on disk
        if an EventWise should be a dataset with the
        hepmc event data
    root_particles : str or EventWise
        if a str should be the path to the root file on disk
        if an EventWise should be a dataset with the
        root event data

    Returns
    -------
    new_eventWise : EventWise
        dataset containing matched data from teh root file and
        the hepmc file.
    
    """
    if isinstance(root_particles, str):
        root_particles = Components.RootReadout(root_particles,
                                                ['Particle', 'Track', 'Tower'])
    if isinstance(hepmc, str):
        if Components.EventWise.pottential_file(hepmc):
            hepmc = ReadHepmc.Hepmc.from_file(hepmc)
        else:
            hepmc = ReadHepmc.Hepmc(hepmc)
    # first we assert that they both contain the same number of events
    n_events = len(root_particles.PID)
    assert n_events == len(
        hepmc.MCPID), "Files cotain doferent number of events"
    # this being extablished we compare them eventwise
    #  (hepmc name, root name)
    precicely_equivalent = [('MCPID', 'PID'), ('Status_code', 'Status')]
    close_equivalent = [('Px', 'Px'), ('Py', 'Py'), ('Pz', 'Pz'),
                        ('Energy', 'Energy'), ('Generated_mass', 'Mass')]
    for event_n in range(n_events):
        hepmc.selected_event = event_n
        root_particles.selected_event = event_n
        # the particles are expected to have the same order in both files
        for hepmc_name, root_name in precicely_equivalent:
            assert np.all(root_particles.__getattr__(root_name)
                          == hepmc.__getattr__(hepmc_name)), \
                                  f"{root_name} in root file not equal to {hepmc_name}"+\
                                  " in hepmc file"
        for hepmc_name, root_name in close_equivalent:
            np.testing.assert_allclose(
                root_particles.__getattr__(root_name),
                hepmc.__getattr__(hepmc_name),
                err_msg=f"{root_name} in root file not close" +
                "to {hepmc_name} in hepmc file")
    # remove all selected indices
    hepmc.selected_event = None
    root_particles.selected_event = None
    # we will keep all of the root columns, but only a selection of the hepmc columns
    # ensure a copy is made
    columns = [name for name in root_particles.columns]
    # forcefully read in here
    contents = {key: getattr(root_particles, key) for key in columns}
    per_event_hepmc_cols = hepmc.event_information_cols + hepmc.weight_cols + \
                           hepmc.units_cols + hepmc.cross_section_cols
    columns += sorted(per_event_hepmc_cols)
    for name in per_event_hepmc_cols:
        contents[name] = getattr(hepmc, name)
    # some get renamed
    per_vertex_hepmc_cols = {
        'Vertex_barcode': 'Vertex_barcode',
        'X': 'Vertex_X',
        'Y': 'Vertex_Y',
        'Z': 'Vertex_Z',
        'Ctau': 'Vertex_Ctau'
    }
    columns += sorted(per_vertex_hepmc_cols.values())
    for name, new_name in per_vertex_hepmc_cols.items():
        contents[new_name] = getattr(hepmc, name)
    per_particle_hepmc_cols = [
        'End_vertex_barcode', 'Start_vertex_barcode', 'Parents', 'Children',
        'Is_root', 'Is_leaf'
    ]
    columns += sorted(per_particle_hepmc_cols)
    for name in per_particle_hepmc_cols:
        contents[name] = hepmc.__getattr__(name)
    # firgure out which of the root columns are per particle and which are per event
    per_particle_root_cols = []
    per_event_root_cols = []
    for name in root_particles.columns:
        values = getattr(root_particles, name)
        _, depth = Components.detect_depth(values[:])
        if depth == 0:
            per_event_root_cols.append(name)
        else:
            per_particle_root_cols.append(name)
    # record what has what level of granularity
    contents['per_event'] = ak.from_iter(per_event_root_cols +
                                         per_event_hepmc_cols)
    contents['per_vertex'] = ak.from_iter(per_vertex_hepmc_cols.values())
    contents['per_particle'] = ak.from_iter(per_particle_root_cols +
                                            per_particle_hepmc_cols)
    # make the new object and save it
    file_name = (root_particles.file_name.split('.', 1)[0] + '_particles' +
                 Components.EventWise.FILE_EXTENTION)
    dir_name = root_particles.dir_name
    path_name = os.path.join(dir_name, file_name)
    new_eventWise = Components.EventWise(path_name, columns, contents)
    new_eventWise.write()
    return new_eventWise