@@ -1679,10 +1679,20 @@ def safe_first_element(obj):
1679
1679
This is a type-independent way of obtaining the first element,
1680
1680
supporting both index access and the iterator protocol.
1681
1681
"""
1682
- return _safe_first_finite (obj , skip_nonfinite = False )
1682
+ if isinstance (obj , collections .abc .Iterator ):
1683
+ # needed to accept `array.flat` as input.
1684
+ # np.flatiter reports as an instance of collections.Iterator but can still be
1685
+ # indexed via []. This has the side effect of re-setting the iterator, but
1686
+ # that is acceptable.
1687
+ try :
1688
+ return obj [0 ]
1689
+ except TypeError :
1690
+ pass
1691
+ raise RuntimeError ("matplotlib does not support generators as input"
8000
)
1692
+ return next (iter (obj ))
1683
1693
1684
1694
1685
- def _safe_first_finite (obj , * , skip_nonfinite = True ):
1695
+ def _safe_first_finite (obj ):
1686
1696
"""
1687
1697
Return the first finite element in *obj* if one is available and skip_nonfinite is
1688
1698
True. Otherwise, return the first element.
@@ -1698,33 +1708,22 @@ def safe_isfinite(val):
1698
1708
try :
1699
1709
return math .isfinite (val )
1700
1710
except (TypeError , ValueError ):
1711
+ # if the outer object is 2d, then val is a 1d array, and
1712
+ # - math.isfinite(numpy.zeros(3)) raises TypeError
1713
+ # - math.isfinite(torch.zeros(3)) raises ValueError
1701
1714
pass
1702
1715
try :
1703
1716
return np .isfinite (val ) if np .isscalar (val ) else True
1704
1717
except TypeError :
1705
1718
# This is something that NumPy cannot make heads or tails of,
1706
1719
# assume "finite"
1707
1720
return True
1708
- if skip_nonfinite is False :
1709
- if isinstance (obj , collections .abc .Iterator ):
1710
- # needed to accept `array.flat` as input.
1711
- # np.flatiter reports as an instance of collections.Iterator
1712
- # but can still be indexed via [].
1713
- # This has the side effect of re-setting the iterator, but
1714
- # that is acceptable.
1715
- try :
1716
- return obj [0 ]
1717
- except TypeError :
1718
- pass
1719
- raise RuntimeError ("matplotlib does not support generators "
1720
- "as input" )
1721
- return next (iter (obj ))
1722
- elif isinstance (obj , np .flatiter ):
1721
+
1722
+ if isinstance (obj , np .flatiter ):
1723
1723
# TODO do the finite filtering on this
1724
1724
return obj [0 ]
1725
1725
elif isinstance (obj , collections .abc .Iterator ):
1726
- raise RuntimeError ("matplotlib does not "
1727
- "support generators as input" )
1726
+ raise RuntimeError ("matplotlib does not support generators as input" )
1728
1727
else :
1729
1728
for val in obj :
1730
1729
if safe_isfinite (val ):
0 commit comments