Skip to content

Commit

Permalink
Make CLI work with uproot 4 (#29)
Browse files Browse the repository at this point in the history
* Make histoprint CLI work with uproot 4.

Fixes #28.

* Catch errors when trying to histogram TTrees rather than branches.

Fixes #27.

* Fix tests for uproot 4.

* Use new Black version.

* Fix TH1 plotting for uproot 4.

* Update URL to example root file.

* Flatten awkward arrays before trying to histogram.
  • Loading branch information
ast0815 authored Feb 5, 2021
1 parent 68039f6 commit 16a43f4
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 34 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/pythontests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ jobs:
python -m pip install -e .[test]
- name: Install optional dependencies for tests
run: |
pip install boost-histogram uproot pandas || true
pip install boost-histogram uproot awkward pandas || true
- name: Run tests
run: |
python -m pytest -s tests/test.py
Expand All @@ -42,7 +42,7 @@ jobs:
histoprint tests/data/3D.txt -s -l A -l B -l C -t "HISTOPRINT"
histoprint tests/data/3D.txt -s -f 0 -l A -f 2 -l C
histoprint tests/data/3D.csv -s -f x -f z
wget http://scikit-hep.org/uproot/examples/Event.root
wget http://scikit-hep.org/uproot3/examples/Event.root
histoprint -s Event.root -f T/event/fTracks.fYfirst -f T/event/fTracks/fTracks.fYlast
histoprint -s Event.root -f htime
Expand Down
57 changes: 44 additions & 13 deletions histoprint/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def histoprint(infile, **kwargs):
_histoprint_root(infile, **kwargs)
exit(0)
except ImportError:
click.echo("Cannot try ROOT file format. Uproot module not found.", err=True)
pass

click.echo("Could not interpret file format.", err=True)
exit(1)
Expand Down Expand Up @@ -223,7 +223,18 @@ def _histoprint_csv(infile, **kwargs):
def _histoprint_root(infile, **kwargs):
"""Interpret file as as ROOT file."""

import uproot as up
# Import uproot
try:
import uproot as up
except ImportError:
click.echo("Cannot try ROOT file format. Uproot module not found.", err=True)
raise
# Import awkward
try:
import awkward as ak
except ImportError:
click.echo("Cannot try ROOT file format. Awkward module not found.", err=True)
raise

# Open root file
F = up.open(infile)
Expand All @@ -243,13 +254,21 @@ def _histoprint_root(infile, **kwargs):
if len(fields) == 1:
# Possible a single histogram
try:
hist = F[fields[0]].numpy()
except (AttributeError, KeyError):
pass
hist = F[fields[0]]
except KeyError:
pass # Deal with key error further down
else:
kwargs.pop("bins", None) # Get rid of useless parameter
print_hist(hist, **kwargs)
return
try:
hist = hist.numpy() # Uproot 3
except AttributeError:
try:
hist = F[fields[0]].to_numpy() # Uproot 4
except AttributeError:
hist = None
if hist is not None:
kwargs.pop("bins", None) # Get rid of useless parameter
print_hist(hist, **kwargs)
return

data = []
for field in fields:
Expand All @@ -264,12 +283,24 @@ def _histoprint_root(infile, **kwargs):
)
exit(1)
try:
d = np.array(branch.array().flatten())
try: # Does the object have values?
d = branch.array()
except (AttributeError, TypeError):
# If not, turn into value error
raise ValueError
try: # Uproot >= 4.0 and Awkward >= 1.0 ?
d = ak.to_numpy(ak.flatten(d))
except AttributeError:
pass
d = np.array(d.flatten())
except ValueError:
click.echo(
"Could not interpret root object '%s'. Possible child branches: %s"
% (key, branch.keys())
)
try:
click.echo(
"Could not interpret root object '%s'. Possible child branches: %s"
% (key, branch.keys())
)
except AttributeError:
click.echo("Could not interpret root object '%s'." % (key))
exit(1)
data.append(d)

Expand Down
Binary file added tests/data/histograms.root
Binary file not shown.
27 changes: 8 additions & 19 deletions tests/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,33 +60,22 @@ def test_boost():


def test_uproot():
"""Test uproot hsitograms if t is available."""
"""Test uproot hsitograms if it is available."""

try:
import uproot
import awkward
except:
return

import uproot_methods.classes.TH1
with uproot.open("tests/data/histograms.root") as F:
hist = F["one"]

class Cls(object):
try:
# Works with uproot 3
hist.show()
except:
pass

class MyTH1(uproot_methods.classes.TH1.Methods, list):
def __init__(self, low, high, values, title=""):
self._fXaxis = Cls()
self._fXaxis._fNbins = len(values)
self._fXaxis._fXmin = low
self._fXaxis._fXmax = high
self.append(0.0) # underflow
for x in values:
self.append(float(x))
self.append(0.0) # overflow
self._fTitle = title
self._classname = "TH1F"

hist = MyTH1(-5, 5, [3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2])
hist.show()
print_hist(hist, title="uproot TH1")


Expand Down

0 comments on commit 16a43f4

Please sign in to comment.