Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 8 additions & 0 deletions src/uproot/_dask.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,11 @@ def _branch_or_field_numpy_dtype(branch):
else:
raise KeyError(f"field {p!r} not found in form {form!r}")
return _form_to_numpy_dtype(form, initial_sizes=sizes)
elif isinstance(branch.interpretation, uproot.interpretation.grouped.AsGrouped):
raise NotImplementedError(
f"uproot.dask with library='np' cannot read the grouped TBranch "
f"{branch.name!r}: select its sub-branches or use library='ak'"
)
else:
return branch.interpretation.numpy_dtype

Expand Down Expand Up @@ -782,6 +787,8 @@ def _get_dask_array(
total_entries = sum(ttree.num_entries for ttree in ttrees)
step_size = max(1, math.ceil(total_entries / (total_files * steps_per_file)))

common_keys = _normalize_grouped_keys(ttrees[0], common_keys, full_paths)

dask_dict = {}

step_sum = 0
Expand Down Expand Up @@ -891,6 +898,7 @@ def _get_dask_array_delay_open(
)
if isinstance(obj, HasFields):
common_keys = _with_subfield_keys(obj, common_keys)
common_keys = _normalize_grouped_keys(obj, common_keys, full_paths)

dask_dict = {}

Expand Down
7 changes: 6 additions & 1 deletion src/uproot/behaviors/TBranch.py
Original file line number Diff line number Diff line change
Expand Up @@ -3633,6 +3633,9 @@ def _regularize_expressions(
None,
)

else:
raise TypeError(f"cut must be None or a string, not {cut!r}")

return arrays, expression_context, branchid_interpretation


Expand Down Expand Up @@ -3783,7 +3786,9 @@ def basket_to_array(basket):
return

# Request all chunks and then poll notifications queue until we have all the arrays we expect
hasbranches._file.source.chunks(ranges, notifications=notifications)
# (a step within baskets that have already been read has nothing to request)
if len(ranges) != 0:
hasbranches._file.source.chunks(ranges, notifications=notifications)

while len(arrays) < len(branchid_interpretation):
obj = notifications.get()
Expand Down
2 changes: 1 addition & 1 deletion src/uproot/compression.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def decompress(self, data: bytes, uncompressed_bytes=None) -> bytes:

elif self.library == "deflate":
deflate = uproot.extras.deflate()
return deflate.zlib_decompress(data, bufsize=uncompressed_bytes)
return deflate.zlib_decompress(data, uncompressed_bytes)

else:
raise ValueError(
Expand Down
11 changes: 9 additions & 2 deletions src/uproot/reading.py
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,7 @@ def streamers(self):
if self._streamers is None:
if self._fSeekInfo == 0:
self._streamers = {}
self._streamer_rules = []

else:
key_cursor = uproot.source.cursor.Cursor(self._fSeekInfo)
Expand Down Expand Up @@ -1034,7 +1035,7 @@ def streamer_dependencies(self, classname, version="max"):
if x not in out:
for i in range(-1, -len(out) - 1, -1):
if out[i][0] == x[0]:
out.insert(i + 1, x)
out.insert(len(out) + i + 1, x)
break
else:
out.append(x)
Expand Down Expand Up @@ -2111,7 +2112,13 @@ def __getitem__(self, where):
head, tail = item[:index], item[index + 1 :]
last = step
step = step[head]
if isinstance(step, uproot.behaviors.TBranch.HasBranches):
if isinstance(
step,
(
uproot.behaviors.TBranch.HasBranches,
uproot.behaviors.RNTuple.HasFields,
),
):
return step["/".join([tail, *items[i + 1 :]])]
else:
raise uproot.KeyInFileError(
Expand Down
7 changes: 7 additions & 0 deletions src/uproot/source/futures.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,13 @@ def close(self):
"""
self.__exit__(None, None, None)

@property
def num_workers(self) -> int:
"""
Always 0: tasks run in the thread that submits them.
"""
return 0

@property
def closed(self) -> bool:
"""
Expand Down
22 changes: 21 additions & 1 deletion src/uproot/source/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ def get_num_bytes(file_path: str, parsed_url: urllib.parse.ParseResult, timeout)
response = connection.getresponse()

while 300 <= response.status < 400:
response.close()
connection.close()
for k, x in response.getheaders():
if k.lower() == "location":
Expand All @@ -117,10 +118,12 @@ def get_num_bytes(file_path: str, parsed_url: urllib.parse.ParseResult, timeout)
)

if response.status == 404:
response.close()
connection.close()
raise uproot._util._file_not_found(file_path, "HTTP(S) returned 404")

if response.status != 200:
response.close()
connection.close()
raise http.client.HTTPException(
f"""HTTP response was {response.status}, rather than 200, in attempt to get file size
Expand All @@ -129,9 +132,11 @@ def get_num_bytes(file_path: str, parsed_url: urllib.parse.ParseResult, timeout)

for k, x in response.getheaders():
if k.lower() == "content-length" and x.strip() != "0":
response.close()
connection.close()
return int(x)
else:
response.close()
connection.close()
raise http.client.HTTPException(
f"""response headers did not include content-length: {dict(response.getheaders())}
Expand Down Expand Up @@ -197,10 +202,12 @@ def get(self, connection, start: int, stop: int) -> bytes:
response = connection.getresponse()

if response.status == 404:
response.close()
connection.close()
raise uproot._util._file_not_found(self.file_path, "HTTP(S) returned 404")

if 300 <= response.status < 400:
response.close()
connection.close()
for k, x in response.getheaders():
if k.lower() == "location":
Expand All @@ -221,6 +228,7 @@ def get(self, connection, start: int, stop: int) -> bytes:
)

if response.status != 206:
response.close()
connection.close()
raise http.client.HTTPException(
f"""remote server responded with status {response.status}, rather than 206 (range requests)
Expand Down Expand Up @@ -324,6 +332,7 @@ def task(resource):

def task(resource):
nonlocal connection
response = None
try:
response = connection.getresponse()

Expand Down Expand Up @@ -364,6 +373,8 @@ def task(resource):
future._set_excinfo(err)

finally:
if response is not None:
response.close()
connection.close()

return uproot.source.futures.ResourceFuture(task)
Expand Down Expand Up @@ -565,7 +576,13 @@ def readline(self) -> bytes:
try:
index = self.already_read.index(b"\n")
except ValueError:
self.already_read = self.already_read + self.stream.read(self.CHUNK)
data = self.stream.read(self.CHUNK)
if len(data) == 0:
# End of stream: there's no newline to wait for.
out = self.already_read
self.already_read = b""
return out
self.already_read = self.already_read + data
else:
out = self.already_read[: index + 1]
self.already_read = self.already_read[index + 1 :]
Expand Down Expand Up @@ -662,6 +679,9 @@ def chunks(
ranges: list[tuple[int, int]],
notifications: queue.Queue,
) -> list[uproot.source.chunk.Chunk]:
if len(ranges) == 0:
# nothing to request (and a Range header needs at least one range)
return []
if self._fallback is None:
self._num_requests += 1
self._num_requested_chunks += len(ranges)
Expand Down
3 changes: 3 additions & 0 deletions src/uproot/source/xrootd.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,9 @@ def chunk(self, start: int, stop: int) -> uproot.source.chunk.Chunk:
def chunks(
self, ranges: list[tuple[int, int]], notifications: queue.Queue
) -> list[uproot.source.chunk.Chunk]:
if len(ranges) == 0:
# nothing to request: don't send an empty vector read
return []
self._num_requests += 1
self._num_requested_chunks += len(ranges)
self._num_requested_bytes += sum(stop - start for start, stop in ranges)
Expand Down
43 changes: 29 additions & 14 deletions tests/test_1189_dask_failing_on_duplicate_keys.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE

import awkward as ak
import pytest
import skhep_testdata

Expand All @@ -9,17 +10,31 @@
pytest.importorskip("dask_awkward")


def test_dask_duplicated_keys():

lazy = uproot.dask(
skhep_testdata.data_path("uproot-metadata-performance.root") + ":Events"
)
materialized = lazy.FatJet_btagDDBvLV2.compute()

lazy = uproot.dask(skhep_testdata.data_path("uproot-issue513.root") + ":Delphes")
materialized = lazy.Particle.compute()

lazy = uproot.dask(
skhep_testdata.data_path("uproot-issue443.root") + ":muonDataTree"
)
materialized = lazy.hitEnd.compute()
# uproot.dask only tokenizes the open TTrees of open_files=True, which is too slow with the
# 1833 TBranches of the first file, and it's the same code as for the last one
@pytest.mark.parametrize(
("file", "tree", "branch", "open_files"),
[
("uproot-metadata-performance.root", "Events", "FatJet_btagDDBvLV2", False),
("uproot-issue513.root", "Delphes", "Particle", False),
("uproot-issue443.root", "muonDataTree", "hitEnd", False),
("uproot-issue443.root", "muonDataTree", "hitEnd", True),
],
)
def test_dask_duplicated_keys(file, tree, branch, open_files):
path = skhep_testdata.data_path(file)
with uproot.open(path) as f:
assert f[tree].keys(filter_name=branch) == [branch, branch]
expected = f[tree][branch].array()

lazy = uproot.dask(f"{path}:{tree}", filter_name=branch, open_files=open_files)
assert lazy.fields == [branch]
materialized = lazy[branch].compute(scheduler="synchronous")
assert ak.array_equal(materialized, expected)


@pytest.mark.parametrize("library", ["ak", "np"])
def test_dask_duplicated_keys_all_branches(library):
path = skhep_testdata.data_path("uproot-issue443.root") + ":muonDataTree"
lazy = uproot.dask(path, library=library)
assert lazy["hitEnd"].compute(scheduler="synchronous").tolist() == []
29 changes: 29 additions & 0 deletions tests/test_1642_read_AsGrouped_with_dask_or_virtual_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,34 @@ def test_read_AsGrouped_with_dask_or_virtual_array():

assert awkward.array_equal(arr, awkward.materialize(virtual_arr))

assert arr.value.tolist() == list(range(10))

dask_arr = uproot.dask(path).compute()
assert awkward.array_equal(arr, dask_arr)


@pytest.mark.parametrize("open_files", [True, False])
@pytest.mark.parametrize(
("full_paths", "value"), [(False, "value"), (True, "branch/value")]
)
def test_read_AsGrouped_with_dask_numpy(open_files, full_paths, value):
"""
As in an eager read of all of a TTree, a group of TBranches that are also
selected is left out: it has no NumPy dtype.
"""
path = skhep_testdata.data_path("uproot-issue-1502.root")
lazy = uproot.dask(path, library="np", open_files=open_files, full_paths=full_paths)
assert len(lazy) == 3
assert value in lazy
computed = dask.compute(lazy, scheduler="synchronous")[0]
assert computed[value].tolist() == list(range(10))


@pytest.mark.parametrize("open_files", [True, False])
@pytest.mark.parametrize("names", ["branch", ["branch", "value"]])
def test_AsGrouped_alone_cannot_be_a_dask_array(open_files, names):
path = skhep_testdata.data_path("uproot-issue-1502.root")
with pytest.raises(
NotImplementedError, match="cannot read the grouped TBranch 'branch'"
):
uproot.dask(path, filter_name=names, library="np", open_files=open_files)
Loading
Loading