Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def normal_h1(size: int = 10000, mean: float = 0, sigma: float = 1) -> Histogram1D:
data = np.random.normal(mean, sigma, (size,))
return h1(data, name="normal", axis_name="x", title="1D normal distribution") | [
"A simple 1D histogram with normal distribution.\n\n Parameters\n ----------\n size : Number of points\n mean : Mean of the distribution\n sigma : Sigma of the distribution\n "
] |
Please provide a description of the function:def normal_h2(size: int = 10000) -> Histogram2D:
data1 = np.random.normal(0, 1, (size,))
data2 = np.random.normal(0, 1, (size,))
return h2(data1, data2, name="normal", axis_names=tuple("xy"), title="2D normal distribution") | [
"A simple 2D histogram with normal distribution.\n\n Parameters\n ----------\n size : Number of points\n "
] |
Please provide a description of the function:def normal_h3(size: int = 10000) -> HistogramND:
data1 = np.random.normal(0, 1, (size,))
data2 = np.random.normal(0, 1, (size,))
data3 = np.random.normal(0, 1, (size,))
return h3([data1, data2, data3], name="normal", axis_names=tuple("xyz"), title="3D no... | [
"A simple 3D histogram with normal distribution.\n\n Parameters\n ----------\n size : Number of points\n "
] |
Please provide a description of the function:def fist() -> Histogram1D:
import numpy as np
from ..histogram1d import Histogram1D
widths = [0, 1.2, 0.2, 1, 0.1, 1, 0.1, 0.9, 0.1, 0.8]
edges = np.cumsum(widths)
heights = np.asarray([4, 1, 7.5, 6, 7.6, 6, 7.5, 6, 7.2]) + 5
return Histogram1D(e... | [
"A simple histogram in the shape of a fist."
] |
Please provide a description of the function:def create_from_dict(data: dict, format_name: str, check_version: bool = True) -> Union[HistogramBase, HistogramCollection]:
# Version
if check_version:
compatible_version = data["physt_compatible"]
require_compatible_version(compatible_version, ... | [
"Once dict from source data is created, turn this into histogram.\n \n Parameters\n ----------\n data : dict\n Parsed JSON-like tree.\n\n Returns\n -------\n histogram : HistogramBase\n A histogram (of any dimensionality)\n "
] |
Please provide a description of the function:def require_compatible_version(compatible_version, word="File"):
if isinstance(compatible_version, str):
compatible_version = parse_version(compatible_version)
elif not isinstance(compatible_version, Version):
raise ValueError("Type of `compatibl... | [
"Check that compatible version of input data is not too new."
] |
Please provide a description of the function:def save_json(histogram: Union[HistogramBase, HistogramCollection], path: Optional[str] = None, **kwargs) -> str:
# TODO: Implement multiple histograms in one file?
data = histogram.to_dict()
data["physt_version"] = CURRENT_VERSION
if isinstance(histogr... | [
"Save histogram to JSON format.\n\n Parameters\n ----------\n histogram : Any histogram\n path : If set, also writes to the path.\n\n Returns\n -------\n json : The JSON representation of the histogram\n "
] |
Please provide a description of the function:def load_json(path: str, encoding: str = "utf-8") -> HistogramBase:
with open(path, "r", encoding=encoding) as f:
text = f.read()
return parse_json(text) | [
"Load histogram from a JSON file."
] |
Please provide a description of the function:def parse_json(text: str, encoding: str = "utf-8") -> HistogramBase:
data = json.loads(text, encoding=encoding)
return create_from_dict(data, format_name="JSON") | [
"Create histogram from a JSON string."
] |
Please provide a description of the function:def histogram(data, bins=None, *args, **kwargs):
import numpy as np
from .histogram1d import Histogram1D, calculate_frequencies
from .binnings import calculate_bins
adaptive = kwargs.pop("adaptive", False)
dtype = kwargs.pop("dtype", None)
if i... | [
"Facade function to create 1D histograms.\n\n This proceeds in three steps:\n 1) Based on magical parameter bins, construct bins for the histogram\n 2) Calculate frequencies for the bins\n 3) Construct the histogram object itself\n\n *Guiding principle:* parameters understood by numpy.histogram shoul... |
Please provide a description of the function:def histogram2d(data1, data2, bins=10, *args, **kwargs):
import numpy as np
# guess axis names
if "axis_names" not in kwargs:
if hasattr(data1, "name") and hasattr(data2, "name"):
kwargs["axis_names"] = [data1.name, data2.name]
if da... | [
"Facade function to create 2D histograms.\n\n For implementation and parameters, see histogramdd.\n\n This function is also aliased as \"h2\".\n\n Returns\n -------\n physt.histogram_nd.Histogram2D\n\n See Also\n --------\n numpy.histogram2d\n histogramdd\n "
] |
Please provide a description of the function:def histogramdd(data, bins=10, *args, **kwargs):
import numpy as np
from . import histogram_nd
from .binnings import calculate_bins_nd
adaptive = kwargs.pop("adaptive", False)
dropna = kwargs.pop("dropna", True)
name = kwargs.pop("name", None)
... | [
"Facade function to create n-dimensional histograms.\n\n 3D variant of this function is also aliased as \"h3\".\n\n Parameters\n ----------\n data : array_like\n Container of all the values\n bins: Any\n weights: array_like, optional\n (as numpy.histogram)\n dropna: bool\n ... |
Please provide a description of the function:def h3(data, *args, **kwargs):
import numpy as np
if data is not None and isinstance(data, (list, tuple)) and not np.isscalar(data[0]):
if "axis_names" not in kwargs:
kwargs["axis_names"] = [(column.name if hasattr(column, "name") else None)... | [
"Facade function to create 3D histograms.\n\n Parameters\n ----------\n data : array_like or list[array_like] or tuple[array_like]\n Can be a single array (with three columns) or three different arrays\n (for each component)\n\n Returns\n -------\n physt.histogram_nd.HistogramND\n ... |
Please provide a description of the function:def collection(data, bins=10, *args, **kwargs):
from physt.histogram_collection import HistogramCollection
if hasattr(data, "columns"):
data = {column: data[column] for column in data.columns}
return HistogramCollection.multi_h1(data, bins, **kwargs) | [
"Create histogram collection with shared binnning."
] |
Please provide a description of the function:def write_root(histogram: HistogramBase, hfile: uproot.write.TFile.TFileUpdate, name: str):
hfile[name] = histogram | [
"Write histogram to an open ROOT file.\n\n Parameters\n ----------\n histogram : Any histogram\n hfile : Updateable uproot file object\n name : The name of the histogram inside the file\n "
] |
Please provide a description of the function:def save_root(histogram: HistogramBase, path: str, name: Optional[str] = None):
if name is None:
name = histogram.name
if os.path.isfile(path):
# TODO: Not supported currently
hfile = uproot.write.TFile.TFileUpdate(path)
else:
... | [
"Write histogram to a (new) ROOT file.\n\n Parameters\n ----------\n histogram : Any histogram\n path: path for the output file (perhaps should not exist?)\n name : The name of the histogram inside the file\n "
] |
Please provide a description of the function:def write(histogram):
histogram_dict = histogram.to_dict()
message = Histogram()
for field in SIMPLE_CONVERSION_FIELDS:
setattr(message, field, histogram_dict[field])
# Main numerical data - TODO: Optimize!
message.frequencies.extend(h... | [
"Convert a histogram to a protobuf message.\n\n Note: Currently, all binnings are converted to\n static form. When you load the histogram again,\n you will lose any related behaviour.\n\n Note: A histogram collection is also planned.\n \n Parameters\n ----------\n histogram : HistogramBa... |
Please provide a description of the function:def read(message):
require_compatible_version(message.physt_compatible)
# Currently the only implementation
a_dict = _dict_from_v0342(message)
return create_from_dict(a_dict, "Message") | [
"Convert a parsed protobuf message into a histogram."
] |
Please provide a description of the function:def make_bin_array(bins) -> np.ndarray:
bins = np.asarray(bins)
if bins.ndim == 1:
# if bins.shape[0] == 0:
# raise RuntimeError("Needs at least one bin")
return np.hstack((bins[:-1, np.newaxis], bins[1:, np.newaxis]))
elif bins.n... | [
"Turn bin data into array understood by HistogramXX classes.\n\n Parameters\n ----------\n bins: array_like\n Array of edges or array of edge tuples\n\n Examples\n --------\n >>> make_bin_array([0, 1, 2])\n array([[0, 1],\n [1, 2]])\n >>> make_bin_array([[0, 1], [2, 3]])\n ... |
Please provide a description of the function:def to_numpy_bins(bins) -> np.ndarray:
bins = np.asarray(bins)
if bins.ndim == 1: # Already in the proper format
return bins
if not is_consecutive(bins):
raise RuntimeError("Cannot create numpy bins from inconsecutive edges")
return n... | [
"Convert physt bin format to numpy edges.\n\n Parameters\n ----------\n bins: array_like\n 1-D (n) or 2-D (n, 2) array of edges\n\n Returns\n -------\n edges: all edges\n "
] |
Please provide a description of the function:def to_numpy_bins_with_mask(bins) -> Tuple[np.ndarray, np.ndarray]:
bins = np.asarray(bins)
if bins.ndim == 1:
edges = bins
if bins.shape[0] > 1:
mask = np.arange(bins.shape[0] - 1)
else:
mask = []
elif bins.nd... | [
"Numpy binning edges including gaps.\n\n Parameters\n ----------\n bins: array_like\n 1-D (n) or 2-D (n, 2) array of edges\n\n Returns\n -------\n edges: np.ndarray\n all edges\n mask: np.ndarray\n List of indices that correspond to bins that have to be included\n\n Exam... |
Please provide a description of the function:def is_rising(bins) -> bool:
# TODO: Optimize for numpy bins
bins = make_bin_array(bins)
if np.any(bins[:, 0] >= bins[:, 1]):
return False
if np.any(bins[1:, 0] < bins[:-1, 1]):
return False
return True | [
"Check whether the bins are in raising order.\n\n Does not check if the bins are consecutive.\n\n Parameters\n ----------\n bins: array_like\n "
] |
Please provide a description of the function:def is_consecutive(bins, rtol: float = 1.e-5, atol: float = 1.e-8) -> bool:
bins = np.asarray(bins)
if bins.ndim == 1:
return True
else:
bins = make_bin_array(bins)
return np.allclose(bins[1:, 0], bins[:-1, 1], rtol, atol) | [
"Check whether the bins are consecutive (edges match).\n\n Does not check if the bins are in rising order.\n "
] |
Please provide a description of the function:def is_bin_subset(sub, sup) -> bool:
sub = make_bin_array(sub)
sup = make_bin_array(sup)
for row in sub:
if not (row == sup).all(axis=1).any():
# TODO: Enable also approximate equality
return False
return True | [
"Check whether all bins in one binning are present also in another:\n\n Parameters\n ----------\n sub: array_like\n Candidate for the bin subset\n sup: array_like\n Candidate for the bin superset\n "
] |
Please provide a description of the function:def get_data(histogram: HistogramBase, density: bool = False, cumulative: bool = False, flatten: bool = False) -> np.ndarray:
if density:
if cumulative:
data = (histogram / histogram.total).cumulative_frequencies
else:
data = ... | [
"Get histogram data based on plotting parameters.\n\n Parameters\n ----------\n density : Whether to divide bin contents by bin size\n cumulative : Whether to return cumulative sums instead of individual\n flatten : Whether to flatten multidimensional bins\n "
] |
Please provide a description of the function:def get_err_data(histogram: HistogramBase, density: bool = False, cumulative: bool = False, flatten: bool = False) -> np.ndarray:
if cumulative:
raise RuntimeError("Error bars not supported for cumulative plots.")
if density:
data = histogram.err... | [
"Get histogram error data based on plotting parameters.\n\n Parameters\n ----------\n density : Whether to divide bin contents by bin size\n cumulative : Whether to return cumulative sums instead of individual\n flatten : Whether to flatten multidimensional bins\n "
] |
Please provide a description of the function:def get_value_format(value_format: Union[Callable, str] = str) -> Callable[[float], str]:
if value_format is None:
value_format = ""
if isinstance(value_format, str):
format_str = "{0:" + value_format + "}"
def value_format(x): return fo... | [
"Create a formatting function from a generic value_format argument.\n "
] |
Please provide a description of the function:def pop_kwargs_with_prefix(prefix: str, kwargs: dict) -> dict:
keys = [key for key in kwargs if key.startswith(prefix)]
return {key[len(prefix):]: kwargs.pop(key) for key in keys} | [
"Pop all items from a dictionary that have keys beginning with a prefix.\n\n Parameters\n ----------\n prefix : str\n kwargs : dict\n\n Returns\n -------\n kwargs : dict\n Items popped from the original directory, with prefix removed.\n "
] |
Please provide a description of the function:def calculate_frequencies(data, ndim: int, binnings, weights=None, dtype=None) -> Tuple[np.ndarray, np.ndarray, float]:
# TODO: Remove ndim
# TODO: What if data is None
# Prepare numpy array of data
if data is not None:
data = np.asarray(data)
... | [
"\"Get frequencies and bin errors from the data (n-dimensional variant).\n\n Parameters\n ----------\n data : array_like\n 2D array with ndim columns and row for each entry.\n ndim : int\n Dimensionality od the data.\n binnings:\n Binnings to apply in all axes.\n weights : Opt... |
Please provide a description of the function:def bins(self) -> List[np.ndarray]:
return [binning.bins for binning in self._binnings] | [
"List of bin matrices."
] |
Please provide a description of the function:def numpy_bins(self) -> List[np.ndarray]:
return [binning.numpy_bins for binning in self._binnings] | [
"Numpy-like bins (if available)."
] |
Please provide a description of the function:def select(self, axis: AxisIdentifier, index, force_copy: bool = False) -> HistogramBase:
if index == slice(None) and not force_copy:
return self
axis_id = self._get_axis(axis)
array_index = [slice(None, None, None) for i in rang... | [
"Select in an axis.\n\n Parameters\n ----------\n axis: int or str\n Axis, in which we select.\n index: int or slice\n Index of bin (as in numpy).\n force_copy: bool\n If True, identity slice force a copy to be made.\n "
] |
Please provide a description of the function:def find_bin(self, value, axis: Optional[AxisIdentifier] = None):
if axis is not None:
axis = self._get_axis(axis)
ixbin = np.searchsorted(self.get_bin_left_edges(axis), value, side="right")
if ixbin == 0:
... | [
"Index(indices) of bin corresponding to a value.\n\n Parameters\n ----------\n value: array_like\n Value with dimensionality equal to histogram\n axis: Optional[int]\n If set, find axis along an axis. Otherwise, find bins along all axes.\n None = outside ... |
Please provide a description of the function:def fill_n(self, values, weights=None, dropna: bool = True, columns: bool = False):
values = np.asarray(values)
if values.ndim != 2:
raise RuntimeError("Expecting 2D array of values.")
if columns:
values = values.T
... | [
"Add more values at once.\n\n Parameters\n ----------\n values: array_like\n Values to add. Can be array of shape (count, ndim) or\n array of shape (ndim, count) [use columns=True] or something\n convertible to it\n weights: array_like\n Weight... |
Please provide a description of the function:def _get_projection_axes(self, *axes: AxisIdentifier) -> Tuple[Tuple[int, ...], Tuple[int, ...]]:
axes = [self._get_axis(ax) for ax in axes]
if not axes:
raise ValueError("No axis selected for projection")
if len(axes) != len(set(... | [
"Find axis identifiers for projection and all the remaining ones.\n \n Returns\n -------\n axes: axes to include in the projection\n invert: axes along which to reduce\n "
] |
Please provide a description of the function:def accumulate(self, axis: AxisIdentifier) -> HistogramBase:
# TODO: Merge with Histogram1D.cumulative_frequencies
# TODO: Deal with errors and totals etc.
# TODO: inplace
new_one = self.copy()
axis_id = self._get_axis(axis)
... | [
"Calculate cumulative frequencies along a certain axis.\n\n Returns\n -------\n new_hist: Histogram of the same type & size\n "
] |
Please provide a description of the function:def projection(self, *axes: AxisIdentifier, **kwargs) -> HistogramBase:
# TODO: rename to project in 0.5
axes, invert = self._get_projection_axes(*axes)
frequencies = self.frequencies.sum(axis=invert)
errors2 = self.errors2.sum(axis=i... | [
"Reduce dimensionality by summing along axis/axes.\n\n Parameters\n ----------\n axes: Iterable[int or str]\n List of axes for the new histogram. Could be either\n numbers or names. Must contain at least one axis.\n name: Optional[str] # TODO: Check\n Nam... |
Please provide a description of the function:def T(self) -> "Histogram2D":
a_copy = self.copy()
a_copy._binnings = list(reversed(a_copy._binnings))
a_copy.axis_names = list(reversed(a_copy.axis_names))
a_copy._frequencies = a_copy._frequencies.T
a_copy._errors2 = a_copy.... | [
"Histogram with swapped axes.\n\n Returns\n -------\n Histogram2D - a copy with swapped axes\n "
] |
Please provide a description of the function:def partial_normalize(self, axis: AxisIdentifier = 0, inplace: bool = False):
# TODO: Is this applicable for HistogramND?
axis = self._get_axis(axis)
if not inplace:
copy = self.copy()
copy.partial_normalize(axis, inpl... | [
"Normalize in rows or columns.\n\n Parameters\n ----------\n axis: int or str\n Along which axis to sum (numpy-sense)\n inplace: bool\n Update the object itself\n\n Returns\n -------\n hist : Histogram2D\n "
] |
Please provide a description of the function:def numpy_binning(data, bins=10, range=None, *args, **kwargs) -> NumpyBinning:
if isinstance(bins, int):
if range:
bins = np.linspace(range[0], range[1], bins + 1)
else:
start = data.min()
stop = data.max()
... | [
"Construct binning schema compatible with numpy.histogram\n\n Parameters\n ----------\n data: array_like, optional\n This is optional if both bins and range are set\n bins: int or array_like\n range: Optional[tuple]\n (min, max)\n includes_right_edge: Optional[bool]\n default:... |
Please provide a description of the function:def human_binning(data=None, bin_count: Optional[int] = None, *, range=None, **kwargs) -> FixedWidthBinning:
subscales = np.array([0.5, 1, 2, 2.5, 5, 10])
# TODO: remove colliding kwargs
if data is None and range is None:
raise RuntimeError("Cannot ... | [
"Construct fixed-width ninning schema with bins automatically optimized to human-friendly widths.\n\n Typical widths are: 1.0, 25,0, 0.02, 500, 2.5e-7, ...\n\n Parameters\n ----------\n bin_count: Number of bins\n range: Optional[tuple]\n (min, max)\n "
] |
Please provide a description of the function:def quantile_binning(data=None, bins=10, *, qrange=(0.0, 1.0), **kwargs) -> StaticBinning:
if np.isscalar(bins):
bins = np.linspace(qrange[0] * 100, qrange[1] * 100, bins + 1)
bins = np.percentile(data, bins)
return static_binning(bins=make_bin_arra... | [
"Binning schema based on quantile ranges.\n\n This binning finds equally spaced quantiles. This should lead to\n all bins having roughly the same frequencies.\n\n Note: weights are not (yet) take into account for calculating\n quantiles.\n\n Parameters\n ----------\n bins: sequence or Optional[... |
Please provide a description of the function:def static_binning(data=None, bins=None, **kwargs) -> StaticBinning:
return StaticBinning(bins=make_bin_array(bins), **kwargs) | [
"Construct static binning with whatever bins."
] |
Please provide a description of the function:def integer_binning(data=None, **kwargs) -> StaticBinning:
if "range" in kwargs:
kwargs["range"] = tuple(r - 0.5 for r in kwargs["range"])
return fixed_width_binning(data=data, bin_width=kwargs.pop("bin_width", 1),
align=Tr... | [
"Construct fixed-width binning schema with bins centered around integers.\n\n Parameters\n ----------\n range: Optional[Tuple[int]]\n min (included) and max integer (excluded) bin\n bin_width: Optional[int]\n group \"bin_width\" integers into one bin (not recommended)\n "
] |
Please provide a description of the function:def fixed_width_binning(data=None, bin_width: Union[float, int] = 1, *, range=None, includes_right_edge=False, **kwargs) -> FixedWidthBinning:
result = FixedWidthBinning(bin_width=bin_width, includes_right_edge=includes_right_edge,
**k... | [
"Construct fixed-width binning schema.\n\n Parameters\n ----------\n bin_width: float\n range: Optional[tuple]\n (min, max)\n align: Optional[float]\n Must be multiple of bin_width\n "
] |
Please provide a description of the function:def exponential_binning(data=None, bin_count: Optional[int] = None, *, range=None, **kwargs) -> ExponentialBinning:
if bin_count is None:
bin_count = ideal_bin_count(data)
if range:
range = (np.log10(range[0]), np.log10(range[1]))
else:
... | [
"Construct exponential binning schema.\n\n Parameters\n ----------\n bin_count: Optional[int]\n Number of bins\n range: Optional[tuple]\n (min, max)\n\n See also\n --------\n numpy.logspace - note that our range semantics is different\n "
] |
Please provide a description of the function:def calculate_bins(array, _=None, *args, **kwargs) -> BinningBase:
if array is not None:
if kwargs.pop("check_nan", True):
if np.any(np.isnan(array)):
raise RuntimeError("Cannot calculate bins in presence of NaN's.")
if kw... | [
"Find optimal binning from arguments.\n\n Parameters\n ----------\n array: arraylike\n Data from which the bins should be decided (sometimes used, sometimes not)\n _: int or str or Callable or arraylike or Iterable or BinningBase\n To-be-guessed parameter that specifies what kind of binnin... |
Please provide a description of the function:def calculate_bins_nd(array, bins=None, *args, **kwargs):
if kwargs.pop("check_nan", True):
if np.any(np.isnan(array)):
raise RuntimeError("Cannot calculate bins in presence of NaN's.")
if array is not None:
_, dim = array.shape
... | [
"Find optimal binning from arguments (n-dimensional variant)\n\n Usage similar to `calculate_bins`.\n\n Returns\n -------\n List[BinningBase]\n "
] |
Please provide a description of the function:def ideal_bin_count(data, method: str = "default") -> int:
n = data.size
if n < 1:
return 1
if method == "default":
if n <= 32:
return 7
else:
return ideal_bin_count(data, "sturges")
elif method == "sqrt":
... | [
"A theoretically ideal bin count.\n\n Parameters\n ----------\n data: array_likes\n Data to work on. Most methods don't use this.\n method: str\n Name of the method to apply, available values:\n - default (~sturges)\n - sqrt\n - sturges\n - doane\n ... |
Please provide a description of the function:def as_binning(obj, copy: bool = False) -> BinningBase:
if isinstance(obj, BinningBase):
if copy:
return obj.copy()
else:
return obj
else:
bins = make_bin_array(obj)
return StaticBinning(bins) | [
"Ensure that an object is a binning\n\n Parameters\n ---------\n obj : BinningBase or array_like\n Can be a binning, numpy-like bins or full physt bins\n copy : If true, ensure that the returned object is independent\n "
] |
Please provide a description of the function:def to_dict(self) -> OrderedDict:
result = OrderedDict()
result["adaptive"] = self._adaptive
result["binning_type"] = type(self).__name__
self._update_dict(result)
return result | [
"Dictionary representation of the binning schema.\n\n This serves as template method, please implement _update_dict\n "
] |
Please provide a description of the function:def is_regular(self, rtol: float = 1.e-5, atol: float = 1.e-8) -> bool:
return np.allclose(np.diff(self.bins[1] - self.bins[0]), 0.0, rtol=rtol, atol=atol) | [
"Whether all bins have the same width.\n\n Parameters\n ----------\n rtol, atol : numpy tolerance parameters\n "
] |
Please provide a description of the function:def is_consecutive(self, rtol: float = 1.e-5, atol: float = 1.e-8) -> bool:
if self.inconsecutive_allowed:
if self._consecutive is None:
if self._numpy_bins is not None:
self._consecutive = True
... | [
"Whether all bins are in a growing order.\n\n Parameters\n ----------\n rtol, atol : numpy tolerance parameters\n "
] |
Please provide a description of the function:def adapt(self, other: 'BinningBase'):
# TODO: in-place arg
if np.array_equal(self.bins, other.bins):
return None, None
elif not self.is_adaptive():
raise RuntimeError("Cannot adapt non-adaptive binning.")
else... | [
"Adapt this binning so that it contains all bins of another binning.\n\n Parameters\n ----------\n other: BinningBase\n "
] |
Please provide a description of the function:def set_adaptive(self, value: bool = True):
if value and not self.adaptive_allowed:
raise RuntimeError("Cannot change binning to adaptive.")
self._adaptive = value | [
"Set/unset the adaptive property of the binning.\n\n This is available only for some of the binning types.\n "
] |
Please provide a description of the function:def bins(self):
if self._bins is None:
self._bins = make_bin_array(self.numpy_bins)
return self._bins | [
"Bins in the wider format (as edge pairs)\n\n Returns\n -------\n bins: np.ndarray\n shape=(bin_count, 2)\n "
] |
Please provide a description of the function:def numpy_bins(self) -> np.ndarray:
if self._numpy_bins is None:
self._numpy_bins = to_numpy_bins(self.bins)
return self._numpy_bins | [
"Bins in the numpy format\n\n This might not be available for inconsecutive binnings.\n\n Returns\n -------\n edges: np.ndarray\n shape=(bin_count+1,)\n "
] |
Please provide a description of the function:def numpy_bins_with_mask(self) -> Tuple[np.ndarray, np.ndarray]:
bwm = to_numpy_bins_with_mask(self.bins)
if not self.includes_right_edge:
bwm[0].append(np.inf)
return bwm | [
"Bins in the numpy format, including the gaps in inconsecutive binnings.\n\n Returns\n -------\n edges, mask: np.ndarray\n\n See Also\n --------\n bin_utils.to_numpy_bins_with_mask\n "
] |
Please provide a description of the function:def as_fixed_width(self, copy=True):
if self.bin_count == 0:
raise RuntimeError("Cannot guess binning width with zero bins")
elif self.bin_count == 1 or self.is_consecutive() and self.is_regular():
return FixedWidthBinning(min... | [
"Convert binning to recipe with fixed width (if possible.)\n\n Parameters\n ----------\n copy: bool\n Ensure that we receive another object\n\n Returns\n -------\n FixedWidthBinning\n "
] |
Please provide a description of the function:def as_static(self, copy: bool = True) -> 'StaticBinning':
if copy:
return StaticBinning(bins=self.bins.copy(),
includes_right_edge=self.includes_right_edge)
else:
return self | [
"Convert binning to a static form.\n\n Returns\n -------\n StaticBinning\n A new static binning with a copy of bins.\n\n Parameters\n ----------\n copy : if True, returns itself (already satisfying conditions).\n "
] |
Please provide a description of the function:def histogram1d(data, bins=None, *args, **kwargs):
import dask
if not hasattr(data, "dask"):
data = dask.array.from_array(data, chunks=int(data.shape[0] / options["chunk_split"]))
if not kwargs.get("adaptive", True):
raise RuntimeError("Only... | [
"Facade function to create one-dimensional histogram using dask.\n\n Parameters\n ----------\n data: dask.DaskArray or array-like\n\n See also\n --------\n physt.histogram\n "
] |
Please provide a description of the function:def histogram2d(data1, data2, bins=None, *args, **kwargs):
# TODO: currently very unoptimized! for non-dasks
import dask
if "axis_names" not in kwargs:
if hasattr(data1, "name") and hasattr(data2, "name"):
kwargs["axis_names"] = [data1.na... | [
"Facade function to create 2D histogram using dask."
] |
Please provide a description of the function:def all_subclasses(cls: type) -> Tuple[type, ...]:
subclasses = []
for subclass in cls.__subclasses__():
subclasses.append(subclass)
subclasses.extend(all_subclasses(subclass))
return tuple(subclasses) | [
"All subclasses of a class.\n\n From: http://stackoverflow.com/a/17246726/2692780\n "
] |
Please provide a description of the function:def find_subclass(base: type, name: str) -> type:
class_candidates = [klass
for klass in all_subclasses(base)
if klass.__name__ == name
]
if len(class_candidates) == 0:
raise Runtime... | [
"Find a named subclass of a base class.\n\n Uses only the class name without namespace.\n "
] |
Please provide a description of the function:def pop_many(a_dict: Dict[str, Any], *args: str, **kwargs) -> Dict[str, Any]:
result = {}
for arg in args:
if arg in a_dict:
result[arg] = a_dict.pop(arg)
for key, value in kwargs.items():
result[key] = a_dict.pop(key, value)
... | [
"Pop multiple items from a dictionary.\n \n Parameters\n ----------\n a_dict : Dictionary from which the items will popped\n args: Keys which will be popped (and not included if not present)\n kwargs: Keys + default value pairs (if key not found, this default is included)\n\n Returns\n -----... |
Please provide a description of the function:def add(self, histogram: Histogram1D):
if self.binning and not self.binning == histogram.binning:
raise ValueError("Cannot add histogram with different binning.")
self.histograms.append(histogram) | [
"Add a histogram to the collection."
] |
Please provide a description of the function:def normalize_bins(self, inplace: bool = False) -> "HistogramCollection":
col = self if inplace else self.copy()
sums = self.sum().frequencies
for h in col.histograms:
h.set_dtype(float)
h._frequencies /= sums
... | [
"Normalize each bin in the collection so that the sum is 1.0 for each bin.\n\n Note: If a bin is zero in all collections, the result will be inf.\n "
] |
Please provide a description of the function:def multi_h1(cls, a_dict: Dict[str, Any], bins=None, **kwargs) -> "HistogramCollection":
from physt.binnings import calculate_bins
mega_values = np.concatenate(list(a_dict.values()))
binning = calculate_bins(mega_values, bins, **kwargs)
... | [
"Create a collection from multiple datasets."
] |
Please provide a description of the function:def to_json(self, path: Optional[str] = None, **kwargs) -> str:
from .io import save_json
return save_json(self, path, **kwargs) | [
"Convert to JSON representation.\n\n Parameters\n ----------\n path: Where to write the JSON.\n\n Returns\n -------\n The JSON representation.\n "
] |
Please provide a description of the function:def axis_names(self) -> Tuple[str, ...]:
default = ["axis{0}".format(i) for i in range(self.ndim)]
return tuple(self._meta_data.get("axis_names", None) or default) | [
"Names of axes (stored in meta-data)."
] |
Please provide a description of the function:def _get_axis(self, name_or_index: AxisIdentifier) -> int:
# TODO: Add unit test
if isinstance(name_or_index, int):
if name_or_index < 0 or name_or_index >= self.ndim:
raise ValueError("No such axis, must be from 0 to {0}"... | [
"Get a zero-based index of an axis and check its existence."
] |
Please provide a description of the function:def shape(self) -> Tuple[int, ...]:
return tuple(bins.bin_count for bins in self._binnings) | [
"Shape of histogram's data.\n\n Returns\n -------\n One-element tuple with the number of bins along each axis.\n "
] |
Please provide a description of the function:def _eval_dtype(cls, value):
value = np.dtype(value)
if value.kind in "iu":
type_info = np.iinfo(value)
elif value.kind == "f":
type_info = np.finfo(value)
else:
raise RuntimeError("Unsupported dtyp... | [
"Convert dtype into canonical form, check its applicability and return info.\n \n Parameters\n ----------\n value: np.dtype or something convertible to it.\n\n Returns\n -------\n value: np.dtype\n type_info: \n Information about the dtype\n ... |
Please provide a description of the function:def set_dtype(self, value, check: bool = True):
# TODO? Deal with unsigned types
value, type_info = self._eval_dtype(value)
if value == self._dtype:
return
if self.dtype is None or np.can_cast(self.dtype, value):
... | [
"Change data type of the bin contents.\n\n Allowed conversions:\n - from integral to float types\n - between the same category of type (float/integer)\n - from float types to integer if weights are trivial\n\n Parameters\n ----------\n value: np.dtype or something co... |
Please provide a description of the function:def _coerce_dtype(self, other_dtype):
if self._dtype is None:
new_dtype = np.dtype(other_dtype)
else:
new_dtype = np.find_common_type([self._dtype, np.dtype(other_dtype)], [])
if new_dtype != self.dtype:
se... | [
"Possibly change the bin content type to allow correct operations with other operand.\n\n Parameters\n ----------\n other_dtype : np.dtype or type\n "
] |
Please provide a description of the function:def normalize(self, inplace: bool = False, percent: bool = False) -> "HistogramBase":
if inplace:
self /= self.total * (.01 if percent else 1)
return self
else:
return self / self.total * (100 if percent else 1) | [
"Normalize the histogram, so that the total weight is equal to 1.\n\n Parameters\n ----------\n inplace: If True, updates itself. If False (default), returns copy\n percent: If True, normalizes to percent instead of 1. Default: False\n\n Returns\n -------\n Histogram... |
Please provide a description of the function:def set_adaptive(self, value: bool = True):
# TODO: remove in favour of adaptive property
if not all(b.adaptive_allowed for b in self._binnings):
raise RuntimeError("All binnings must allow adaptive behaviour.")
for binning in sel... | [
"Change the histogram binning to (non)adaptive.\n\n This requires binning in all dimensions to allow this.\n "
] |
Please provide a description of the function:def _change_binning(self, new_binning, bin_map: Iterable[Tuple[int, int]], axis: int = 0):
axis = int(axis)
if axis < 0 or axis >= self.ndim:
raise RuntimeError("Axis must be in range 0..(ndim-1)")
self._reshape_data(new_binning.b... | [
"Set new binnning and update the bin contents according to a map.\n\n Fills frequencies and errors with 0.\n It's the caller's responsibility to provide correct binning and map.\n\n Parameters\n ----------\n new_binning: physt.binnings.BinningBase\n bin_map: Iterable[tuple]... |
Please provide a description of the function:def merge_bins(self, amount: Optional[int] = None, *, min_frequency: Optional[float] = None,
axis: Optional[AxisIdentifier] = None, inplace: bool = False) -> 'HistogramBase':
if not inplace:
histogram = self.copy()
... | [
"Reduce the number of bins and add their content:\n\n Parameters\n ----------\n amount: How many adjacent bins to join together.\n min_frequency: Try to have at least this value in each bin\n (this is not enforce e.g. for minima between high bins)\n axis: int or None\n ... |
Please provide a description of the function:def _reshape_data(self, new_size, bin_map, axis=0):
if bin_map is None:
return
else:
new_shape = list(self.shape)
new_shape[axis] = new_size
new_frequencies = np.zeros(new_shape, dtype=self._frequencies... | [
"Reshape data to match new binning schema.\n\n Fills frequencies and errors with 0.\n\n Parameters\n ----------\n new_size: int\n bin_map: Iterable[(old, new)] or int or None\n If None, we can keep the data unchanged.\n If int, it is offset by which to shift ... |
Please provide a description of the function:def _apply_bin_map(self, old_frequencies, new_frequencies, old_errors2,
new_errors2, bin_map, axis=0):
if old_frequencies is not None and old_frequencies.shape[axis] > 0:
if isinstance(bin_map, int):
new_ind... | [
"Fill new data arrays using a map.\n\n Parameters\n ----------\n old_frequencies : np.ndarray\n Source of frequencies data\n new_frequencies : np.ndarray\n Target of frequencies data\n old_errors2 : np.ndarray\n Source of errors data\n new_e... |
Please provide a description of the function:def has_same_bins(self, other: "HistogramBase") -> bool:
if self.shape != other.shape:
return False
elif self.ndim == 1:
return np.allclose(self.bins, other.bins)
elif self.ndim > 1:
for i in range(self.ndi... | [
"Whether two histograms share the same binning."
] |
Please provide a description of the function:def copy(self, include_frequencies: bool = True) -> "HistogramBase":
if include_frequencies:
frequencies = np.copy(self.frequencies)
missed = self._missed.copy()
errors2 = np.copy(self.errors2)
stats = self._st... | [
"Copy the histogram.\n\n Parameters\n ----------\n include_frequencies : If false, all frequencies are set to zero.\n "
] |
Please provide a description of the function:def fill_n(self, values, weights=None, **kwargs):
if weights is not None:
if weights.shape != values.shape[0]:
raise RuntimeError("Wrong shape of weights")
for i, value in enumerate(values):
if weights is not N... | [
"Add more values at once.\n\n This (default) implementation uses a simple loop to add values using `fill` method.\n Actually, it is not used in neither Histogram1D, nor HistogramND.\n\n Parameters\n ----------\n values: Iterable\n Values to add\n weights: Optiona... |
Please provide a description of the function:def to_dict(self) -> OrderedDict:
result = OrderedDict()
result["histogram_type"] = type(self).__name__
result["binnings"] = [binning.to_dict() for binning in self._binnings]
result["frequencies"] = self.frequencies.tolist()
r... | [
"Dictionary with all data in the histogram.\n\n This is used for export into various formats (e.g. JSON)\n If a descendant class needs to update the dictionary in some way\n (put some more information), override the _update_dict method.\n "
] |
Please provide a description of the function:def _kwargs_from_dict(cls, a_dict: dict) -> dict:
from .binnings import BinningBase
kwargs = {
"binnings": [BinningBase.from_dict(binning_data) for binning_data in a_dict["binnings"]],
"dtype": np.dtype(a_dict["dtype"]),
... | [
"Modify __init__ arguments from an external dictionary.\n\n Template method for from dict.\n Override if necessary (like it's done in Histogram1D).\n "
] |
Please provide a description of the function:def from_dict(cls, a_dict: Mapping[str, Any]) -> "HistogramBase":
kwargs = cls._kwargs_from_dict(a_dict)
return cls(**kwargs) | [
"Create an instance from a dictionary.\n\n If customization is necessary, override the _from_dict_kwargs\n template method, not this one.\n "
] |
Please provide a description of the function:def _merge_meta_data(cls, first: "HistogramBase", second: "HistogramBase") -> dict:
keys = set(first._meta_data.keys())
keys = keys.union(set(second._meta_data.keys()))
return {key:
(first._meta_data.get(key, None) if first._m... | [
"Merge meta data of two histograms leaving only the equal values.\n\n (Used in addition and subtraction)\n "
] |
Please provide a description of the function:def calculate_frequencies(data, binning, weights=None, validate_bins=True,
already_sorted=False, dtype=None):
# TODO: Is it possible to merge with histogram_nd.calculate_frequencies?
# TODO: What if data is None
# TODO: Change stat... | [
"Get frequencies and bin errors from the data.\n\n Parameters\n ----------\n data : array_like\n Data items to work on.\n binning : physt.binnings.BinningBase\n A set of bins.\n weights : array_like, optional\n Weights of the items.\n validate_bins : bool, optional\n If... |
Please provide a description of the function:def select(self, axis, index, force_copy: bool = False):
if axis == 0:
if index == slice(None) and not force_copy:
return self
return self[index]
else:
raise ValueError("In Histogram1D.select(), axi... | [
"Alias for [] to be compatible with HistogramND."
] |
Please provide a description of the function:def numpy_like(self) -> Tuple[np.ndarray, np.ndarray]:
return self.frequencies, self.numpy_bins | [
"Return "
] |
Please provide a description of the function:def mean(self) -> Optional[float]:
if self._stats: # TODO: should be true always?
if self.total > 0:
return self._stats["sum"] / self.total
else:
return np.nan
else:
return None | [
"Statistical mean of all values entered into histogram.\n\n This number is precise, because we keep the necessary data\n separate from bin contents.\n "
] |
Please provide a description of the function:def std(self) -> Optional[float]: #, ddof=0):
# TODO: Add DOF
if self._stats:
return np.sqrt(self.variance())
else:
return None | [
"Standard deviation of all values entered into histogram.\n\n This number is precise, because we keep the necessary data\n separate from bin contents.\n\n Returns\n -------\n float\n "
] |
Please provide a description of the function:def variance(self) -> Optional[float]: #, ddof: int = 0) -> float:
# TODO: Add DOF
# http://stats.stackexchange.com/questions/6534/how-do-i-calculate-a-weighted-standard-deviation-in-excel
if self._stats:
if self.total > 0:
... | [
"Statistical variance of all values entered into histogram.\n\n This number is precise, because we keep the necessary data\n separate from bin contents.\n\n Returns\n -------\n float\n "
] |
Please provide a description of the function:def find_bin(self, value):
ixbin = np.searchsorted(self.bin_left_edges, value, side="right")
if ixbin == 0:
return -1
elif ixbin == self.bin_count:
if value <= self.bin_right_edges[-1]:
return ixbin - 1... | [
"Index of bin corresponding to a value.\n\n Parameters\n ----------\n value: float\n Value to be searched for.\n\n Returns\n -------\n int\n index of bin to which value belongs\n (-1=underflow, N=overflow, None=not found - inconsecutive)\n ... |
Please provide a description of the function:def fill(self, value, weight=1):
self._coerce_dtype(type(weight))
if self._binning.is_adaptive():
map = self._binning.force_bin_existence(value)
self._reshape_data(self._binning.bin_count, map)
ixbin = self.find_bin(v... | [
"Update histogram with a new value.\n\n Parameters\n ----------\n value: float\n Value to be added.\n weight: float, optional\n Weight assigned to the value.\n\n Returns\n -------\n int\n index of bin which was incremented (-1=underfl... |
Please provide a description of the function:def fill_n(self, values, weights=None, dropna: bool = True):
# TODO: Unify with HistogramBase
values = np.asarray(values)
if dropna:
values = values[~np.isnan(values)]
if self._binning.is_adaptive():
map = self... | [
"Update histograms with a set of values.\n\n Parameters\n ----------\n values: array_like\n weights: Optional[array_like]\n drop_na: Optional[bool]\n If true (default), all nan's are skipped.\n "
] |
Please provide a description of the function:def to_dataframe(self) -> "pandas.DataFrame":
import pandas as pd
df = pd.DataFrame(
{
"left": self.bin_left_edges,
"right": self.bin_right_edges,
"frequency": self.frequencies,
... | [
"Convert to pandas DataFrame.\n\n This is not a lossless conversion - (under/over)flow info is lost.\n "
] |
Please provide a description of the function:def to_xarray(self) -> "xarray.Dataset":
import xarray as xr
data_vars = {
"frequencies": xr.DataArray(self.frequencies, dims="bin"),
"errors2": xr.DataArray(self.errors2, dims="bin"),
"bins": xr.DataArray(self.bin... | [
"Convert to xarray.Dataset"
] |
Please provide a description of the function:def from_xarray(cls, arr: "xarray.Dataset") -> "Histogram1D":
kwargs = {'frequencies': arr["frequencies"],
'binning': arr["bins"],
'errors2': arr["errors2"],
'overflow': arr.attrs["overflow"],
... | [
"Convert form xarray.Dataset\n\n Parameters\n ----------\n arr: The data in xarray representation\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.