Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: setting keep branches with a list wasn't working correctly #100

Merged
merged 5 commits into from
Jul 2, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Small fixes for the linter and drop_branches
zbilodea committed Jul 2, 2024
commit 159acbbaee7b638242ea28a1bb96014f94155b0d
47 changes: 21 additions & 26 deletions src/hepconvert/_utils.py
Original file line number Diff line number Diff line change
@@ -54,38 +54,33 @@ def filter_branches(tree, keep_branches, drop_branches, count_branches):
if drop_branches and keep_branches:
msg = "Can specify either drop_branches or keep_branches, not both."
raise ValueError(msg) from None

if drop_branches:
if isinstance(drop_branches, dict): # noqa: SIM102
branches = drop_branches if drop_branches else keep_branches
keys = []
if branches:
if isinstance(branches, dict): # noqa: SIM102
if (
len(drop_branches) > 1
and tree.name in drop_branches
or tree.name == next(iter(drop_branches.keys()))
len(branches) > 1
and tree.name in branches
or tree.name == next(iter(branches.keys()))
):
drop_branches = drop_branches.get(tree.name)
if isinstance(drop_branches, str) or len(drop_branches) == 1:
drop_branches = tree.keys(filter_name=drop_branches)
return [
b.name
for b in tree.branches
if b.name not in count_branches and b.name not in drop_branches
]
if keep_branches:
if isinstance(keep_branches, dict): # noqa: SIM102
if (
len(keep_branches) > 1
and tree.name in keep_branches
or tree.name == next(iter(keep_branches.keys()))
):
keep_branches = keep_branches.get(tree.name)
if isinstance(keep_branches, str) or len(keep_branches) == 1:
keep_branches = tree.keys(filter_name=keep_branches)
keys = branches.get(tree.name)
if isinstance(branches, str) or len(branches) == 1:
keys = tree.keys(filter_name=branches)
else:
for i in branches:
keys = np.union1d(keys, tree.keys(filter_name=i))
if drop_branches:
return [
b.name
for b in tree.branches
if b.name not in count_branches and b.name in keep_branches
if b.name not in count_branches and b.name not in keys
]
return [b.name for b in tree.branches if b.name not in count_branches]
return [
b.name
for b in tree.branches
if b.name not in count_branches and b.name in keys
]
return [b.name for b in tree.branches]


def check_tqdm():
9 changes: 4 additions & 5 deletions src/hepconvert/copy_root.py
Original file line number Diff line number Diff line change
@@ -18,7 +18,6 @@ def copy_root(
*,
keep_branches=None,
drop_branches=None,
# add_branches=None, #TODO: add functionality for this, just specify about the counter issue?
keep_trees=None,
drop_trees=None,
cut=None,
@@ -32,7 +31,7 @@ def copy_root(
initial_basket_capacity=10,
resize_factor=10.0,
counter_name=lambda counted: "n" + counted,
step_size=100,
step_size="100 MB",
compression="ZLIB",
compression_level=1,
):
@@ -216,12 +215,12 @@ def copy_root(
)
raise ValueError(msg)

if len(trees) > 1 and progress_bar is not False:
if len(trees) > 1 and progress_bar is not False and progress_bar is not None:
number_of_items = len(trees)
if progress_bar is True:
tqdm = _utils.check_tqdm()
progress_bar = tqdm.tqdm(desc="Trees copied")
progress_bar.reset(total=number_of_items)
progress_bar.reset(total=number_of_items)
for t in trees:
tree = f[t]
count_branches = get_counter_branches(tree)
@@ -280,6 +279,6 @@ def copy_root(
out_file[tree.name].extend(chunk)
except AssertionError:
msg = "Are the branch-names correct?"
if len(trees) > 1 and progress_bar is not False:
if len(trees) > 1 and progress_bar is not False and progress_bar is not None:
progress_bar.update(n=1)
f.close()
6 changes: 3 additions & 3 deletions src/hepconvert/histogram_adding.py
Original file line number Diff line number Diff line change
@@ -418,11 +418,11 @@ def add_histograms(
if not force and not append:
raise FileExistsError
if force and append:
msg = "Cannot append to a new file. Either force or append can be true."
msg = "Cannot append to a new file. Either force or append can be true, not both."
raise ValueError(msg)
if append:
out_file = uproot.update(destination)
elif force:
else:
out_file = uproot.recreate(
destination,
compression=uproot.compression.Compression.from_code_pair(
@@ -490,7 +490,7 @@ def add_histograms(
msg = f"File: {input_file} does not exist or is corrupt."
raise FileNotFoundError(msg) from None
if same_names:
if progress_bar:
if progress_bar and hist_bar:
hist_bar.reset(len(keys))
for key in keys:
try:
3 changes: 1 addition & 2 deletions src/hepconvert/merge.py
Original file line number Diff line number Diff line change
@@ -246,10 +246,9 @@ def merge_root(
)
raise ValueError(msg)
if progress_bar is not False:
number_of_items = len(files)
if progress_bar is True:
tqdm = _utils.check_tqdm()
number_of_items = len(files)

progress_bar = tqdm.tqdm(desc="Files added")
progress_bar.reset(number_of_items)
for t in trees:
45 changes: 20 additions & 25 deletions tests/test_copy_root.py
Original file line number Diff line number Diff line change
@@ -62,33 +62,25 @@ def test_keep_branch(tmp_path):
assert key not in file["events"].keys()


def test_add_branch(tmp_path):
def test_keep_branches(tmp_path):
hepconvert.copy_root(
Path(tmp_path) / "drop_branches.root",
skhep_testdata.data_path("uproot-HZZ.root"),
drop_branches=["MClepton_py", "Jet_Px"],
drop_branches=["Jet_*", "MClepton_*"],
counter_name=lambda counted: "N" + counted,
force=True,
)
arrays = file["events"].arrays()
branch_types = {
name: array.type
for name, array in zip(ak.fields(arrays), ak.unzip(arrays))
if not name.startswith("n") and not name.startswith("N")
}

branches = {
file["events"]["MClepton_py"].name: file["events"]["MClepton_py"].arrays(),
file["events"]["Jet_Px"].name: file["events"]["Jet_Px"].arrays(),
}
jet_px = {file["events"]["Jet_Px"].name: file["events"]["Jet_Px"].arrays()}
hepconvert.copy_root(
Path(tmp_path) / "add_branches.root",
Path(tmp_path) / "drop_branches.root",
force=True,
)
original = uproot.open(skhep_testdata.data_path("uproot-HZZ.root"))

file = uproot.open(Path(tmp_path) / "add_branches.root")
file = uproot.open(Path(tmp_path) / "drop_branches.root")
for key in original["events"].keys():
if key.startswith("MClepton_"):
assert key in file["events"].keys()
assert ak.all(
file["events"][key].array() == original["events"][key].array()
)
else:
assert key not in file["events"].keys()


def test_hepdata_example(tmp_path):
@@ -100,7 +92,6 @@ def test_hepdata_example(tmp_path):
)
hepconvert_file = uproot.open(Path(tmp_path) / "copy_hepdata.root")
file = uproot.open(skhep_testdata.data_path("uproot-hepdata-example.root"))

for key in hepconvert_file.keys(cycle=False):
assert key in file.keys(cycle=False)

@@ -203,7 +194,7 @@ def test_drop_tree(tmp_path):

with pytest.raises(
ValueError,
match="Key 'tree5' does not match any TTree in ROOT file/Users/zobil/Desktop/directory/two_trees.root",
match=f"Key 'tree5' does not match any TTree in ROOT {tmp_path}/two_trees.root",
):
hepconvert.copy_root(
Path(tmp_path) / "copied.root",
@@ -244,7 +235,11 @@ def test_keep_tree_and_branch(tmp_path):
import numpy as np

with uproot.recreate(Path(tmp_path) / "two_trees.root") as file:
file["tree"] = {"x": np.array([1, 2, 3, 4, 5]), "y": np.array([4, 5, 6, 7, 8])}
file["tree"] = {
"x": np.array([1, 2, 3, 4, 5]),
"y": np.array([4, 5, 6, 7, 8]),
"z": np.array([4, 5, 6, 7, 8]),
}
file["tree1"] = {
"x": np.array([1, 2, 3, 4, 5]),
"y": np.array([4, 5, 6, 7, 8]),
@@ -254,14 +249,14 @@ def test_keep_tree_and_branch(tmp_path):
hepconvert.copy_root(
Path(tmp_path) / "copied.root",
Path(tmp_path) / "two_trees.root",
keep_branches={"tree": "x", "tree1": "y"},
keep_branches={"tree": ["x", "z"], "tree1": "y"},
force=True,
)

with uproot.open(Path(tmp_path) / "copied.root") as copy:
assert copy.keys(cycle=False) == ["tree", "tree1"]
assert copy["tree1"].keys() == ["y"]
assert copy["tree"].keys() == ["x"]
assert copy["tree"].keys() == ["x", "z"]
for tree in copy.keys(cycle=False):
for key in copy[tree].keys():
assert ak.all(copy[tree][key].array() == file[tree][key].array())