id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
16,400
janpipek/physt
physt/plotting/matplotlib.py
bar3d
def bar3d(h2: Histogram2D, ax: Axes3D, **kwargs): """Plot of 2D histograms as 3D boxes.""" density = kwargs.pop("density", False) data = get_data(h2, cumulative=False, flatten=True, density=density) if "cmap" in kwargs: cmap = _get_cmap(kwargs) _, cmap_data = _get_cmap_data(data, kwargs) colors = cmap(cmap_data) else: colors = kwargs.pop("color", "blue") xpos, ypos = (arr.flatten() for arr in h2.get_bin_centers()) zpos = np.zeros_like(ypos) dx, dy = (arr.flatten() for arr in h2.get_bin_widths()) _add_labels(ax, h2, kwargs) ax.bar3d(xpos, ypos, zpos, dx, dy, data, color=colors, **kwargs) ax.set_zlabel("density" if density else "frequency")
python
def bar3d(h2: Histogram2D, ax: Axes3D, **kwargs): """Plot of 2D histograms as 3D boxes.""" density = kwargs.pop("density", False) data = get_data(h2, cumulative=False, flatten=True, density=density) if "cmap" in kwargs: cmap = _get_cmap(kwargs) _, cmap_data = _get_cmap_data(data, kwargs) colors = cmap(cmap_data) else: colors = kwargs.pop("color", "blue") xpos, ypos = (arr.flatten() for arr in h2.get_bin_centers()) zpos = np.zeros_like(ypos) dx, dy = (arr.flatten() for arr in h2.get_bin_widths()) _add_labels(ax, h2, kwargs) ax.bar3d(xpos, ypos, zpos, dx, dy, data, color=colors, **kwargs) ax.set_zlabel("density" if density else "frequency")
[ "def", "bar3d", "(", "h2", ":", "Histogram2D", ",", "ax", ":", "Axes3D", ",", "*", "*", "kwargs", ")", ":", "density", "=", "kwargs", ".", "pop", "(", "\"density\"", ",", "False", ")", "data", "=", "get_data", "(", "h2", ",", "cumulative", "=", "False", ",", "flatten", "=", "True", ",", "density", "=", "density", ")", "if", "\"cmap\"", "in", "kwargs", ":", "cmap", "=", "_get_cmap", "(", "kwargs", ")", "_", ",", "cmap_data", "=", "_get_cmap_data", "(", "data", ",", "kwargs", ")", "colors", "=", "cmap", "(", "cmap_data", ")", "else", ":", "colors", "=", "kwargs", ".", "pop", "(", "\"color\"", ",", "\"blue\"", ")", "xpos", ",", "ypos", "=", "(", "arr", ".", "flatten", "(", ")", "for", "arr", "in", "h2", ".", "get_bin_centers", "(", ")", ")", "zpos", "=", "np", ".", "zeros_like", "(", "ypos", ")", "dx", ",", "dy", "=", "(", "arr", ".", "flatten", "(", ")", "for", "arr", "in", "h2", ".", "get_bin_widths", "(", ")", ")", "_add_labels", "(", "ax", ",", "h2", ",", "kwargs", ")", "ax", ".", "bar3d", "(", "xpos", ",", "ypos", ",", "zpos", ",", "dx", ",", "dy", ",", "data", ",", "color", "=", "colors", ",", "*", "*", "kwargs", ")", "ax", ".", "set_zlabel", "(", "\"density\"", "if", "density", "else", "\"frequency\"", ")" ]
Plot of 2D histograms as 3D boxes.
[ "Plot", "of", "2D", "histograms", "as", "3D", "boxes", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L393-L411
16,401
janpipek/physt
physt/plotting/matplotlib.py
image
def image(h2: Histogram2D, ax: Axes, *, show_colorbar: bool = True, interpolation: str = "nearest", **kwargs): """Plot of 2D histograms based on pixmaps. Similar to map, but it: - has fewer options - is much more effective (enables thousands) - does not support irregular bins Parameters ---------- interpolation: interpolation parameter passed to imshow, default: "nearest" (creates rectangles) """ cmap = _get_cmap(kwargs) # h2 as well? data = get_data(h2, cumulative=False, density=kwargs.pop("density", False)) norm, cmap_data = _get_cmap_data(data, kwargs) # zorder = kwargs.pop("zorder", None) for binning in h2._binnings: if not binning.is_regular(): raise RuntimeError( "Histograms with irregular bins cannot be plotted using image method.") kwargs["interpolation"] = interpolation if kwargs.get("xscale") == "log" or kwargs.get("yscale") == "log": raise RuntimeError("Cannot use logarithmic axes with image plots.") _apply_xy_lims(ax, h2, data=data, kwargs=kwargs) _add_labels(ax, h2, kwargs) ax.imshow(data.T[::-1, :], cmap=cmap, norm=norm, extent=(h2.bins[0][0, 0], h2.bins[0][-1, 1], h2.bins[1][0, 0], h2.bins[1][-1, 1]), aspect="auto", **kwargs) if show_colorbar: _add_colorbar(ax, cmap, cmap_data, norm)
python
def image(h2: Histogram2D, ax: Axes, *, show_colorbar: bool = True, interpolation: str = "nearest", **kwargs): """Plot of 2D histograms based on pixmaps. Similar to map, but it: - has fewer options - is much more effective (enables thousands) - does not support irregular bins Parameters ---------- interpolation: interpolation parameter passed to imshow, default: "nearest" (creates rectangles) """ cmap = _get_cmap(kwargs) # h2 as well? data = get_data(h2, cumulative=False, density=kwargs.pop("density", False)) norm, cmap_data = _get_cmap_data(data, kwargs) # zorder = kwargs.pop("zorder", None) for binning in h2._binnings: if not binning.is_regular(): raise RuntimeError( "Histograms with irregular bins cannot be plotted using image method.") kwargs["interpolation"] = interpolation if kwargs.get("xscale") == "log" or kwargs.get("yscale") == "log": raise RuntimeError("Cannot use logarithmic axes with image plots.") _apply_xy_lims(ax, h2, data=data, kwargs=kwargs) _add_labels(ax, h2, kwargs) ax.imshow(data.T[::-1, :], cmap=cmap, norm=norm, extent=(h2.bins[0][0, 0], h2.bins[0][-1, 1], h2.bins[1][0, 0], h2.bins[1][-1, 1]), aspect="auto", **kwargs) if show_colorbar: _add_colorbar(ax, cmap, cmap_data, norm)
[ "def", "image", "(", "h2", ":", "Histogram2D", ",", "ax", ":", "Axes", ",", "*", ",", "show_colorbar", ":", "bool", "=", "True", ",", "interpolation", ":", "str", "=", "\"nearest\"", ",", "*", "*", "kwargs", ")", ":", "cmap", "=", "_get_cmap", "(", "kwargs", ")", "# h2 as well?", "data", "=", "get_data", "(", "h2", ",", "cumulative", "=", "False", ",", "density", "=", "kwargs", ".", "pop", "(", "\"density\"", ",", "False", ")", ")", "norm", ",", "cmap_data", "=", "_get_cmap_data", "(", "data", ",", "kwargs", ")", "# zorder = kwargs.pop(\"zorder\", None)", "for", "binning", "in", "h2", ".", "_binnings", ":", "if", "not", "binning", ".", "is_regular", "(", ")", ":", "raise", "RuntimeError", "(", "\"Histograms with irregular bins cannot be plotted using image method.\"", ")", "kwargs", "[", "\"interpolation\"", "]", "=", "interpolation", "if", "kwargs", ".", "get", "(", "\"xscale\"", ")", "==", "\"log\"", "or", "kwargs", ".", "get", "(", "\"yscale\"", ")", "==", "\"log\"", ":", "raise", "RuntimeError", "(", "\"Cannot use logarithmic axes with image plots.\"", ")", "_apply_xy_lims", "(", "ax", ",", "h2", ",", "data", "=", "data", ",", "kwargs", "=", "kwargs", ")", "_add_labels", "(", "ax", ",", "h2", ",", "kwargs", ")", "ax", ".", "imshow", "(", "data", ".", "T", "[", ":", ":", "-", "1", ",", ":", "]", ",", "cmap", "=", "cmap", ",", "norm", "=", "norm", ",", "extent", "=", "(", "h2", ".", "bins", "[", "0", "]", "[", "0", ",", "0", "]", ",", "h2", ".", "bins", "[", "0", "]", "[", "-", "1", ",", "1", "]", ",", "h2", ".", "bins", "[", "1", "]", "[", "0", ",", "0", "]", ",", "h2", ".", "bins", "[", "1", "]", "[", "-", "1", ",", "1", "]", ")", ",", "aspect", "=", "\"auto\"", ",", "*", "*", "kwargs", ")", "if", "show_colorbar", ":", "_add_colorbar", "(", "ax", ",", "cmap", ",", "cmap_data", ",", "norm", ")" ]
Plot of 2D histograms based on pixmaps. Similar to map, but it: - has fewer options - is much more effective (enables thousands) - does not support irregular bins Parameters ---------- interpolation: interpolation parameter passed to imshow, default: "nearest" (creates rectangles)
[ "Plot", "of", "2D", "histograms", "based", "on", "pixmaps", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L415-L450
16,402
janpipek/physt
physt/plotting/matplotlib.py
polar_map
def polar_map(hist: Histogram2D, ax: Axes, *, show_zero: bool = True, show_colorbar: bool = True, **kwargs): """Polar map of polar histograms. Similar to map, but supports less parameters.""" data = get_data(hist, cumulative=False, flatten=True, density=kwargs.pop("density", False)) cmap = _get_cmap(kwargs) norm, cmap_data = _get_cmap_data(data, kwargs) colors = cmap(cmap_data) rpos, phipos = (arr.flatten() for arr in hist.get_bin_left_edges()) dr, dphi = (arr.flatten() for arr in hist.get_bin_widths()) rmax, _ = (arr.flatten() for arr in hist.get_bin_right_edges()) bar_args = {} if "zorder" in kwargs: bar_args["zorder"] = kwargs.pop("zorder") alphas = _get_alpha_data(cmap_data, kwargs) if np.isscalar(alphas): alphas = np.ones_like(data) * alphas for i in range(len(rpos)): if data[i] > 0 or show_zero: bin_color = colors[i] # TODO: align = "edge" bars = ax.bar(phipos[i], dr[i], width=dphi[i], bottom=rpos[i], align='edge', color=bin_color, edgecolor=kwargs.get("grid_color", cmap(0.5)), lw=kwargs.get("lw", 0.5), alpha=alphas[i], **bar_args) ax.set_rmax(rmax.max()) if show_colorbar: _add_colorbar(ax, cmap, cmap_data, norm)
python
def polar_map(hist: Histogram2D, ax: Axes, *, show_zero: bool = True, show_colorbar: bool = True, **kwargs): """Polar map of polar histograms. Similar to map, but supports less parameters.""" data = get_data(hist, cumulative=False, flatten=True, density=kwargs.pop("density", False)) cmap = _get_cmap(kwargs) norm, cmap_data = _get_cmap_data(data, kwargs) colors = cmap(cmap_data) rpos, phipos = (arr.flatten() for arr in hist.get_bin_left_edges()) dr, dphi = (arr.flatten() for arr in hist.get_bin_widths()) rmax, _ = (arr.flatten() for arr in hist.get_bin_right_edges()) bar_args = {} if "zorder" in kwargs: bar_args["zorder"] = kwargs.pop("zorder") alphas = _get_alpha_data(cmap_data, kwargs) if np.isscalar(alphas): alphas = np.ones_like(data) * alphas for i in range(len(rpos)): if data[i] > 0 or show_zero: bin_color = colors[i] # TODO: align = "edge" bars = ax.bar(phipos[i], dr[i], width=dphi[i], bottom=rpos[i], align='edge', color=bin_color, edgecolor=kwargs.get("grid_color", cmap(0.5)), lw=kwargs.get("lw", 0.5), alpha=alphas[i], **bar_args) ax.set_rmax(rmax.max()) if show_colorbar: _add_colorbar(ax, cmap, cmap_data, norm)
[ "def", "polar_map", "(", "hist", ":", "Histogram2D", ",", "ax", ":", "Axes", ",", "*", ",", "show_zero", ":", "bool", "=", "True", ",", "show_colorbar", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ")", ":", "data", "=", "get_data", "(", "hist", ",", "cumulative", "=", "False", ",", "flatten", "=", "True", ",", "density", "=", "kwargs", ".", "pop", "(", "\"density\"", ",", "False", ")", ")", "cmap", "=", "_get_cmap", "(", "kwargs", ")", "norm", ",", "cmap_data", "=", "_get_cmap_data", "(", "data", ",", "kwargs", ")", "colors", "=", "cmap", "(", "cmap_data", ")", "rpos", ",", "phipos", "=", "(", "arr", ".", "flatten", "(", ")", "for", "arr", "in", "hist", ".", "get_bin_left_edges", "(", ")", ")", "dr", ",", "dphi", "=", "(", "arr", ".", "flatten", "(", ")", "for", "arr", "in", "hist", ".", "get_bin_widths", "(", ")", ")", "rmax", ",", "_", "=", "(", "arr", ".", "flatten", "(", ")", "for", "arr", "in", "hist", ".", "get_bin_right_edges", "(", ")", ")", "bar_args", "=", "{", "}", "if", "\"zorder\"", "in", "kwargs", ":", "bar_args", "[", "\"zorder\"", "]", "=", "kwargs", ".", "pop", "(", "\"zorder\"", ")", "alphas", "=", "_get_alpha_data", "(", "cmap_data", ",", "kwargs", ")", "if", "np", ".", "isscalar", "(", "alphas", ")", ":", "alphas", "=", "np", ".", "ones_like", "(", "data", ")", "*", "alphas", "for", "i", "in", "range", "(", "len", "(", "rpos", ")", ")", ":", "if", "data", "[", "i", "]", ">", "0", "or", "show_zero", ":", "bin_color", "=", "colors", "[", "i", "]", "# TODO: align = \"edge\"", "bars", "=", "ax", ".", "bar", "(", "phipos", "[", "i", "]", ",", "dr", "[", "i", "]", ",", "width", "=", "dphi", "[", "i", "]", ",", "bottom", "=", "rpos", "[", "i", "]", ",", "align", "=", "'edge'", ",", "color", "=", "bin_color", ",", "edgecolor", "=", "kwargs", ".", "get", "(", "\"grid_color\"", ",", "cmap", "(", "0.5", ")", ")", ",", "lw", "=", "kwargs", ".", "get", "(", "\"lw\"", ",", "0.5", ")", ",", "alpha", "=", "alphas", "[", "i", "]", ",", "*", "*", "bar_args", ")", "ax", ".", "set_rmax", "(", "rmax", ".", "max", "(", ")", ")", "if", "show_colorbar", ":", "_add_colorbar", "(", "ax", ",", "cmap", ",", "cmap_data", ",", "norm", ")" ]
Polar map of polar histograms. Similar to map, but supports less parameters.
[ "Polar", "map", "of", "polar", "histograms", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L454-L487
16,403
janpipek/physt
physt/plotting/matplotlib.py
globe_map
def globe_map(hist: Union[Histogram2D, DirectionalHistogram], ax: Axes3D, *, show_zero: bool = True, **kwargs): """Heat map plotted on the surface of a sphere.""" data = get_data(hist, cumulative=False, flatten=False, density=kwargs.pop("density", False)) cmap = _get_cmap(kwargs) norm, cmap_data = _get_cmap_data(data, kwargs) colors = cmap(cmap_data) lw = kwargs.pop("lw", 1) r = 1 xs = r * np.outer(np.sin(hist.numpy_bins[0]), np.cos(hist.numpy_bins[1])) ys = r * np.outer(np.sin(hist.numpy_bins[0]), np.sin(hist.numpy_bins[1])) zs = r * np.outer(np.cos(hist.numpy_bins[0]), np.ones(hist.shape[1] + 1)) for i in range(hist.shape[0]): for j in range(hist.shape[1]): if not show_zero and not data[i, j]: continue x = xs[i, j], xs[i, j + 1], xs[i + 1, j + 1], xs[i + 1, j] y = ys[i, j], ys[i, j + 1], ys[i + 1, j + 1], ys[i + 1, j] z = zs[i, j], zs[i, j + 1], zs[i + 1, j + 1], zs[i + 1, j] verts = [list(zip(x, y, z))] col = Poly3DCollection(verts) col.set_facecolor(colors[i, j]) col.set_edgecolor("black") col.set_linewidth(lw) ax.add_collection3d(col) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") if matplotlib.__version__ < "2": ax.plot_surface([], [], [], color="b") ax.set_xlim(-1.1, 1.1) ax.set_ylim(-1.1, 1.1) ax.set_zlim(-1.1, 1.1) return ax
python
def globe_map(hist: Union[Histogram2D, DirectionalHistogram], ax: Axes3D, *, show_zero: bool = True, **kwargs): """Heat map plotted on the surface of a sphere.""" data = get_data(hist, cumulative=False, flatten=False, density=kwargs.pop("density", False)) cmap = _get_cmap(kwargs) norm, cmap_data = _get_cmap_data(data, kwargs) colors = cmap(cmap_data) lw = kwargs.pop("lw", 1) r = 1 xs = r * np.outer(np.sin(hist.numpy_bins[0]), np.cos(hist.numpy_bins[1])) ys = r * np.outer(np.sin(hist.numpy_bins[0]), np.sin(hist.numpy_bins[1])) zs = r * np.outer(np.cos(hist.numpy_bins[0]), np.ones(hist.shape[1] + 1)) for i in range(hist.shape[0]): for j in range(hist.shape[1]): if not show_zero and not data[i, j]: continue x = xs[i, j], xs[i, j + 1], xs[i + 1, j + 1], xs[i + 1, j] y = ys[i, j], ys[i, j + 1], ys[i + 1, j + 1], ys[i + 1, j] z = zs[i, j], zs[i, j + 1], zs[i + 1, j + 1], zs[i + 1, j] verts = [list(zip(x, y, z))] col = Poly3DCollection(verts) col.set_facecolor(colors[i, j]) col.set_edgecolor("black") col.set_linewidth(lw) ax.add_collection3d(col) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") if matplotlib.__version__ < "2": ax.plot_surface([], [], [], color="b") ax.set_xlim(-1.1, 1.1) ax.set_ylim(-1.1, 1.1) ax.set_zlim(-1.1, 1.1) return ax
[ "def", "globe_map", "(", "hist", ":", "Union", "[", "Histogram2D", ",", "DirectionalHistogram", "]", ",", "ax", ":", "Axes3D", ",", "*", ",", "show_zero", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ")", ":", "data", "=", "get_data", "(", "hist", ",", "cumulative", "=", "False", ",", "flatten", "=", "False", ",", "density", "=", "kwargs", ".", "pop", "(", "\"density\"", ",", "False", ")", ")", "cmap", "=", "_get_cmap", "(", "kwargs", ")", "norm", ",", "cmap_data", "=", "_get_cmap_data", "(", "data", ",", "kwargs", ")", "colors", "=", "cmap", "(", "cmap_data", ")", "lw", "=", "kwargs", ".", "pop", "(", "\"lw\"", ",", "1", ")", "r", "=", "1", "xs", "=", "r", "*", "np", ".", "outer", "(", "np", ".", "sin", "(", "hist", ".", "numpy_bins", "[", "0", "]", ")", ",", "np", ".", "cos", "(", "hist", ".", "numpy_bins", "[", "1", "]", ")", ")", "ys", "=", "r", "*", "np", ".", "outer", "(", "np", ".", "sin", "(", "hist", ".", "numpy_bins", "[", "0", "]", ")", ",", "np", ".", "sin", "(", "hist", ".", "numpy_bins", "[", "1", "]", ")", ")", "zs", "=", "r", "*", "np", ".", "outer", "(", "np", ".", "cos", "(", "hist", ".", "numpy_bins", "[", "0", "]", ")", ",", "np", ".", "ones", "(", "hist", ".", "shape", "[", "1", "]", "+", "1", ")", ")", "for", "i", "in", "range", "(", "hist", ".", "shape", "[", "0", "]", ")", ":", "for", "j", "in", "range", "(", "hist", ".", "shape", "[", "1", "]", ")", ":", "if", "not", "show_zero", "and", "not", "data", "[", "i", ",", "j", "]", ":", "continue", "x", "=", "xs", "[", "i", ",", "j", "]", ",", "xs", "[", "i", ",", "j", "+", "1", "]", ",", "xs", "[", "i", "+", "1", ",", "j", "+", "1", "]", ",", "xs", "[", "i", "+", "1", ",", "j", "]", "y", "=", "ys", "[", "i", ",", "j", "]", ",", "ys", "[", "i", ",", "j", "+", "1", "]", ",", "ys", "[", "i", "+", "1", ",", "j", "+", "1", "]", ",", "ys", "[", "i", "+", "1", ",", "j", "]", "z", "=", "zs", "[", "i", ",", "j", "]", ",", "zs", "[", "i", ",", "j", "+", "1", "]", ",", "zs", "[", "i", "+", "1", ",", "j", "+", "1", "]", ",", "zs", "[", "i", "+", "1", ",", "j", "]", "verts", "=", "[", "list", "(", "zip", "(", "x", ",", "y", ",", "z", ")", ")", "]", "col", "=", "Poly3DCollection", "(", "verts", ")", "col", ".", "set_facecolor", "(", "colors", "[", "i", ",", "j", "]", ")", "col", ".", "set_edgecolor", "(", "\"black\"", ")", "col", ".", "set_linewidth", "(", "lw", ")", "ax", ".", "add_collection3d", "(", "col", ")", "ax", ".", "set_xlabel", "(", "\"x\"", ")", "ax", ".", "set_ylabel", "(", "\"y\"", ")", "ax", ".", "set_zlabel", "(", "\"z\"", ")", "if", "matplotlib", ".", "__version__", "<", "\"2\"", ":", "ax", ".", "plot_surface", "(", "[", "]", ",", "[", "]", ",", "[", "]", ",", "color", "=", "\"b\"", ")", "ax", ".", "set_xlim", "(", "-", "1.1", ",", "1.1", ")", "ax", ".", "set_ylim", "(", "-", "1.1", ",", "1.1", ")", "ax", ".", "set_zlim", "(", "-", "1.1", ",", "1.1", ")", "return", "ax" ]
Heat map plotted on the surface of a sphere.
[ "Heat", "map", "plotted", "on", "the", "surface", "of", "a", "sphere", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L491-L529
16,404
janpipek/physt
physt/plotting/matplotlib.py
pair_bars
def pair_bars(first: Histogram1D, second: Histogram2D, *, orientation: str = "vertical", kind: str = "bar", **kwargs): """Draw two different histograms mirrored in one figure. Parameters ---------- first: Histogram1D second: Histogram1D color1: color2: orientation: str Returns ------- plt.Axes """ # TODO: enable vertical as well as horizontal _, ax = _get_axes(kwargs) color1 = kwargs.pop("color1", "red") color2 = kwargs.pop("color2", "blue") title = kwargs.pop("title", "{0} - {1}".format(first.name, second.name)) xlim = kwargs.pop("xlim", (min(first.bin_left_edges[0], first.bin_left_edges[ 0]), max(first.bin_right_edges[-1], second.bin_right_edges[-1]))) bar(first * (-1), color=color1, ax=ax, ylim="keep", **kwargs) bar(second, color=color2, ax=ax, ylim="keep", **kwargs) ax.set_title(title) ticks = np.abs(ax.get_yticks()) if np.allclose(np.rint(ticks), ticks): ax.set_yticklabels(ticks.astype(int)) else: ax.set_yticklabels(ticks) ax.set_xlim(xlim) ax.legend() return ax
python
def pair_bars(first: Histogram1D, second: Histogram2D, *, orientation: str = "vertical", kind: str = "bar", **kwargs): """Draw two different histograms mirrored in one figure. Parameters ---------- first: Histogram1D second: Histogram1D color1: color2: orientation: str Returns ------- plt.Axes """ # TODO: enable vertical as well as horizontal _, ax = _get_axes(kwargs) color1 = kwargs.pop("color1", "red") color2 = kwargs.pop("color2", "blue") title = kwargs.pop("title", "{0} - {1}".format(first.name, second.name)) xlim = kwargs.pop("xlim", (min(first.bin_left_edges[0], first.bin_left_edges[ 0]), max(first.bin_right_edges[-1], second.bin_right_edges[-1]))) bar(first * (-1), color=color1, ax=ax, ylim="keep", **kwargs) bar(second, color=color2, ax=ax, ylim="keep", **kwargs) ax.set_title(title) ticks = np.abs(ax.get_yticks()) if np.allclose(np.rint(ticks), ticks): ax.set_yticklabels(ticks.astype(int)) else: ax.set_yticklabels(ticks) ax.set_xlim(xlim) ax.legend() return ax
[ "def", "pair_bars", "(", "first", ":", "Histogram1D", ",", "second", ":", "Histogram2D", ",", "*", ",", "orientation", ":", "str", "=", "\"vertical\"", ",", "kind", ":", "str", "=", "\"bar\"", ",", "*", "*", "kwargs", ")", ":", "# TODO: enable vertical as well as horizontal", "_", ",", "ax", "=", "_get_axes", "(", "kwargs", ")", "color1", "=", "kwargs", ".", "pop", "(", "\"color1\"", ",", "\"red\"", ")", "color2", "=", "kwargs", ".", "pop", "(", "\"color2\"", ",", "\"blue\"", ")", "title", "=", "kwargs", ".", "pop", "(", "\"title\"", ",", "\"{0} - {1}\"", ".", "format", "(", "first", ".", "name", ",", "second", ".", "name", ")", ")", "xlim", "=", "kwargs", ".", "pop", "(", "\"xlim\"", ",", "(", "min", "(", "first", ".", "bin_left_edges", "[", "0", "]", ",", "first", ".", "bin_left_edges", "[", "0", "]", ")", ",", "max", "(", "first", ".", "bin_right_edges", "[", "-", "1", "]", ",", "second", ".", "bin_right_edges", "[", "-", "1", "]", ")", ")", ")", "bar", "(", "first", "*", "(", "-", "1", ")", ",", "color", "=", "color1", ",", "ax", "=", "ax", ",", "ylim", "=", "\"keep\"", ",", "*", "*", "kwargs", ")", "bar", "(", "second", ",", "color", "=", "color2", ",", "ax", "=", "ax", ",", "ylim", "=", "\"keep\"", ",", "*", "*", "kwargs", ")", "ax", ".", "set_title", "(", "title", ")", "ticks", "=", "np", ".", "abs", "(", "ax", ".", "get_yticks", "(", ")", ")", "if", "np", ".", "allclose", "(", "np", ".", "rint", "(", "ticks", ")", ",", "ticks", ")", ":", "ax", ".", "set_yticklabels", "(", "ticks", ".", "astype", "(", "int", ")", ")", "else", ":", "ax", ".", "set_yticklabels", "(", "ticks", ")", "ax", ".", "set_xlim", "(", "xlim", ")", "ax", ".", "legend", "(", ")", "return", "ax" ]
Draw two different histograms mirrored in one figure. Parameters ---------- first: Histogram1D second: Histogram1D color1: color2: orientation: str Returns ------- plt.Axes
[ "Draw", "two", "different", "histograms", "mirrored", "in", "one", "figure", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L648-L681
16,405
janpipek/physt
physt/plotting/matplotlib.py
_get_axes
def _get_axes(kwargs: Dict[str, Any], *, use_3d: bool = False, use_polar: bool = False) -> Tuple[Figure, Union[Axes, Axes3D]]: """Prepare the axis to draw into. Parameters ---------- use_3d: If True, an axis with 3D projection is created. use_polar: If True, the plot will have polar coordinates. Kwargs ------ ax: Optional[plt.Axes] An already existing axis to be used. figsize: Optional[tuple] Size of the new figure (if no axis is given). Returns ------ fig : plt.Figure ax : plt.Axes | Axes3D """ figsize = kwargs.pop("figsize", default_figsize) if "ax" in kwargs: ax = kwargs.pop("ax") fig = ax.get_figure() elif use_3d: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111, projection='3d') elif use_polar: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111, projection='polar') else: fig, ax = plt.subplots(figsize=figsize) return fig, ax
python
def _get_axes(kwargs: Dict[str, Any], *, use_3d: bool = False, use_polar: bool = False) -> Tuple[Figure, Union[Axes, Axes3D]]: """Prepare the axis to draw into. Parameters ---------- use_3d: If True, an axis with 3D projection is created. use_polar: If True, the plot will have polar coordinates. Kwargs ------ ax: Optional[plt.Axes] An already existing axis to be used. figsize: Optional[tuple] Size of the new figure (if no axis is given). Returns ------ fig : plt.Figure ax : plt.Axes | Axes3D """ figsize = kwargs.pop("figsize", default_figsize) if "ax" in kwargs: ax = kwargs.pop("ax") fig = ax.get_figure() elif use_3d: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111, projection='3d') elif use_polar: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111, projection='polar') else: fig, ax = plt.subplots(figsize=figsize) return fig, ax
[ "def", "_get_axes", "(", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", ",", "*", ",", "use_3d", ":", "bool", "=", "False", ",", "use_polar", ":", "bool", "=", "False", ")", "->", "Tuple", "[", "Figure", ",", "Union", "[", "Axes", ",", "Axes3D", "]", "]", ":", "figsize", "=", "kwargs", ".", "pop", "(", "\"figsize\"", ",", "default_figsize", ")", "if", "\"ax\"", "in", "kwargs", ":", "ax", "=", "kwargs", ".", "pop", "(", "\"ax\"", ")", "fig", "=", "ax", ".", "get_figure", "(", ")", "elif", "use_3d", ":", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "figsize", ")", "ax", "=", "fig", ".", "add_subplot", "(", "111", ",", "projection", "=", "'3d'", ")", "elif", "use_polar", ":", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "figsize", ")", "ax", "=", "fig", ".", "add_subplot", "(", "111", ",", "projection", "=", "'polar'", ")", "else", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "figsize", ")", "return", "fig", ",", "ax" ]
Prepare the axis to draw into. Parameters ---------- use_3d: If True, an axis with 3D projection is created. use_polar: If True, the plot will have polar coordinates. Kwargs ------ ax: Optional[plt.Axes] An already existing axis to be used. figsize: Optional[tuple] Size of the new figure (if no axis is given). Returns ------ fig : plt.Figure ax : plt.Axes | Axes3D
[ "Prepare", "the", "axis", "to", "draw", "into", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L684-L716
16,406
janpipek/physt
physt/plotting/matplotlib.py
_get_cmap
def _get_cmap(kwargs: dict) -> colors.Colormap: """Get the colour map for plots that support it. Parameters ---------- cmap : str or colors.Colormap or list of colors A map or an instance of cmap. This can also be a seaborn palette (if seaborn is installed). """ from matplotlib.colors import ListedColormap cmap = kwargs.pop("cmap", default_cmap) if isinstance(cmap, list): return ListedColormap(cmap) if isinstance(cmap, str): try: cmap = plt.get_cmap(cmap) except BaseException as exc: try: # Try to use seaborn palette import seaborn as sns sns_palette = sns.color_palette(cmap, n_colors=256) cmap = ListedColormap(sns_palette, name=cmap) except ImportError: raise exc return cmap
python
def _get_cmap(kwargs: dict) -> colors.Colormap: """Get the colour map for plots that support it. Parameters ---------- cmap : str or colors.Colormap or list of colors A map or an instance of cmap. This can also be a seaborn palette (if seaborn is installed). """ from matplotlib.colors import ListedColormap cmap = kwargs.pop("cmap", default_cmap) if isinstance(cmap, list): return ListedColormap(cmap) if isinstance(cmap, str): try: cmap = plt.get_cmap(cmap) except BaseException as exc: try: # Try to use seaborn palette import seaborn as sns sns_palette = sns.color_palette(cmap, n_colors=256) cmap = ListedColormap(sns_palette, name=cmap) except ImportError: raise exc return cmap
[ "def", "_get_cmap", "(", "kwargs", ":", "dict", ")", "->", "colors", ".", "Colormap", ":", "from", "matplotlib", ".", "colors", "import", "ListedColormap", "cmap", "=", "kwargs", ".", "pop", "(", "\"cmap\"", ",", "default_cmap", ")", "if", "isinstance", "(", "cmap", ",", "list", ")", ":", "return", "ListedColormap", "(", "cmap", ")", "if", "isinstance", "(", "cmap", ",", "str", ")", ":", "try", ":", "cmap", "=", "plt", ".", "get_cmap", "(", "cmap", ")", "except", "BaseException", "as", "exc", ":", "try", ":", "# Try to use seaborn palette", "import", "seaborn", "as", "sns", "sns_palette", "=", "sns", ".", "color_palette", "(", "cmap", ",", "n_colors", "=", "256", ")", "cmap", "=", "ListedColormap", "(", "sns_palette", ",", "name", "=", "cmap", ")", "except", "ImportError", ":", "raise", "exc", "return", "cmap" ]
Get the colour map for plots that support it. Parameters ---------- cmap : str or colors.Colormap or list of colors A map or an instance of cmap. This can also be a seaborn palette (if seaborn is installed).
[ "Get", "the", "colour", "map", "for", "plots", "that", "support", "it", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L719-L744
16,407
janpipek/physt
physt/plotting/matplotlib.py
_get_cmap_data
def _get_cmap_data(data, kwargs) -> Tuple[colors.Normalize, np.ndarray]: """Get normalized values to be used with a colormap. Parameters ---------- data : array_like cmap_min : Optional[float] or "min" By default 0. If "min", minimum value of the data. cmap_max : Optional[float] By default, maximum value of the data cmap_normalize : str or colors.Normalize Returns ------- normalizer : colors.Normalize normalized_data : array_like """ norm = kwargs.pop("cmap_normalize", None) if norm == "log": cmap_max = kwargs.pop("cmap_max", data.max()) cmap_min = kwargs.pop("cmap_min", data[data > 0].min()) norm = colors.LogNorm(cmap_min, cmap_max) elif not norm: cmap_max = kwargs.pop("cmap_max", data.max()) cmap_min = kwargs.pop("cmap_min", 0) if cmap_min == "min": cmap_min = data.min() norm = colors.Normalize(cmap_min, cmap_max, clip=True) return norm, norm(data)
python
def _get_cmap_data(data, kwargs) -> Tuple[colors.Normalize, np.ndarray]: """Get normalized values to be used with a colormap. Parameters ---------- data : array_like cmap_min : Optional[float] or "min" By default 0. If "min", minimum value of the data. cmap_max : Optional[float] By default, maximum value of the data cmap_normalize : str or colors.Normalize Returns ------- normalizer : colors.Normalize normalized_data : array_like """ norm = kwargs.pop("cmap_normalize", None) if norm == "log": cmap_max = kwargs.pop("cmap_max", data.max()) cmap_min = kwargs.pop("cmap_min", data[data > 0].min()) norm = colors.LogNorm(cmap_min, cmap_max) elif not norm: cmap_max = kwargs.pop("cmap_max", data.max()) cmap_min = kwargs.pop("cmap_min", 0) if cmap_min == "min": cmap_min = data.min() norm = colors.Normalize(cmap_min, cmap_max, clip=True) return norm, norm(data)
[ "def", "_get_cmap_data", "(", "data", ",", "kwargs", ")", "->", "Tuple", "[", "colors", ".", "Normalize", ",", "np", ".", "ndarray", "]", ":", "norm", "=", "kwargs", ".", "pop", "(", "\"cmap_normalize\"", ",", "None", ")", "if", "norm", "==", "\"log\"", ":", "cmap_max", "=", "kwargs", ".", "pop", "(", "\"cmap_max\"", ",", "data", ".", "max", "(", ")", ")", "cmap_min", "=", "kwargs", ".", "pop", "(", "\"cmap_min\"", ",", "data", "[", "data", ">", "0", "]", ".", "min", "(", ")", ")", "norm", "=", "colors", ".", "LogNorm", "(", "cmap_min", ",", "cmap_max", ")", "elif", "not", "norm", ":", "cmap_max", "=", "kwargs", ".", "pop", "(", "\"cmap_max\"", ",", "data", ".", "max", "(", ")", ")", "cmap_min", "=", "kwargs", ".", "pop", "(", "\"cmap_min\"", ",", "0", ")", "if", "cmap_min", "==", "\"min\"", ":", "cmap_min", "=", "data", ".", "min", "(", ")", "norm", "=", "colors", ".", "Normalize", "(", "cmap_min", ",", "cmap_max", ",", "clip", "=", "True", ")", "return", "norm", ",", "norm", "(", "data", ")" ]
Get normalized values to be used with a colormap. Parameters ---------- data : array_like cmap_min : Optional[float] or "min" By default 0. If "min", minimum value of the data. cmap_max : Optional[float] By default, maximum value of the data cmap_normalize : str or colors.Normalize Returns ------- normalizer : colors.Normalize normalized_data : array_like
[ "Get", "normalized", "values", "to", "be", "used", "with", "a", "colormap", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L747-L775
16,408
janpipek/physt
physt/plotting/matplotlib.py
_get_alpha_data
def _get_alpha_data(data: np.ndarray, kwargs) -> Union[float, np.ndarray]: """Get alpha values for all data points. Parameters ---------- alpha: Callable or float This can be a fixed value or a function of the data. """ alpha = kwargs.pop("alpha", 1) if hasattr(alpha, "__call__"): return np.vectorize(alpha)(data) return alpha
python
def _get_alpha_data(data: np.ndarray, kwargs) -> Union[float, np.ndarray]: """Get alpha values for all data points. Parameters ---------- alpha: Callable or float This can be a fixed value or a function of the data. """ alpha = kwargs.pop("alpha", 1) if hasattr(alpha, "__call__"): return np.vectorize(alpha)(data) return alpha
[ "def", "_get_alpha_data", "(", "data", ":", "np", ".", "ndarray", ",", "kwargs", ")", "->", "Union", "[", "float", ",", "np", ".", "ndarray", "]", ":", "alpha", "=", "kwargs", ".", "pop", "(", "\"alpha\"", ",", "1", ")", "if", "hasattr", "(", "alpha", ",", "\"__call__\"", ")", ":", "return", "np", ".", "vectorize", "(", "alpha", ")", "(", "data", ")", "return", "alpha" ]
Get alpha values for all data points. Parameters ---------- alpha: Callable or float This can be a fixed value or a function of the data.
[ "Get", "alpha", "values", "for", "all", "data", "points", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L778-L789
16,409
janpipek/physt
physt/plotting/matplotlib.py
_add_values
def _add_values(ax: Axes, h1: Histogram1D, data, *, value_format=lambda x: x, **kwargs): """Show values next to each bin in a 1D plot. Parameters ---------- ax : plt.Axes h1 : physt.histogram1d.Histogram1D data : array_like The values to be displayed kwargs : dict Parameters to be passed to matplotlib to override standard text params. """ from .common import get_value_format value_format = get_value_format(value_format) text_kwargs = {"ha": "center", "va": "bottom", "clip_on" : True} text_kwargs.update(kwargs) for x, y in zip(h1.bin_centers, data): ax.text(x, y, str(value_format(y)), **text_kwargs)
python
def _add_values(ax: Axes, h1: Histogram1D, data, *, value_format=lambda x: x, **kwargs): """Show values next to each bin in a 1D plot. Parameters ---------- ax : plt.Axes h1 : physt.histogram1d.Histogram1D data : array_like The values to be displayed kwargs : dict Parameters to be passed to matplotlib to override standard text params. """ from .common import get_value_format value_format = get_value_format(value_format) text_kwargs = {"ha": "center", "va": "bottom", "clip_on" : True} text_kwargs.update(kwargs) for x, y in zip(h1.bin_centers, data): ax.text(x, y, str(value_format(y)), **text_kwargs)
[ "def", "_add_values", "(", "ax", ":", "Axes", ",", "h1", ":", "Histogram1D", ",", "data", ",", "*", ",", "value_format", "=", "lambda", "x", ":", "x", ",", "*", "*", "kwargs", ")", ":", "from", ".", "common", "import", "get_value_format", "value_format", "=", "get_value_format", "(", "value_format", ")", "text_kwargs", "=", "{", "\"ha\"", ":", "\"center\"", ",", "\"va\"", ":", "\"bottom\"", ",", "\"clip_on\"", ":", "True", "}", "text_kwargs", ".", "update", "(", "kwargs", ")", "for", "x", ",", "y", "in", "zip", "(", "h1", ".", "bin_centers", ",", "data", ")", ":", "ax", ".", "text", "(", "x", ",", "y", ",", "str", "(", "value_format", "(", "y", ")", ")", ",", "*", "*", "text_kwargs", ")" ]
Show values next to each bin in a 1D plot. Parameters ---------- ax : plt.Axes h1 : physt.histogram1d.Histogram1D data : array_like The values to be displayed kwargs : dict Parameters to be passed to matplotlib to override standard text params.
[ "Show", "values", "next", "to", "each", "bin", "in", "a", "1D", "plot", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L810-L828
16,410
janpipek/physt
physt/plotting/matplotlib.py
_add_colorbar
def _add_colorbar(ax: Axes, cmap: colors.Colormap, cmap_data: np.ndarray, norm: colors.Normalize): """Show a colorbar right of the plot.""" fig = ax.get_figure() mappable = cm.ScalarMappable(cmap=cmap, norm=norm) mappable.set_array(cmap_data) # TODO: Or what??? fig.colorbar(mappable, ax=ax)
python
def _add_colorbar(ax: Axes, cmap: colors.Colormap, cmap_data: np.ndarray, norm: colors.Normalize): """Show a colorbar right of the plot.""" fig = ax.get_figure() mappable = cm.ScalarMappable(cmap=cmap, norm=norm) mappable.set_array(cmap_data) # TODO: Or what??? fig.colorbar(mappable, ax=ax)
[ "def", "_add_colorbar", "(", "ax", ":", "Axes", ",", "cmap", ":", "colors", ".", "Colormap", ",", "cmap_data", ":", "np", ".", "ndarray", ",", "norm", ":", "colors", ".", "Normalize", ")", ":", "fig", "=", "ax", ".", "get_figure", "(", ")", "mappable", "=", "cm", ".", "ScalarMappable", "(", "cmap", "=", "cmap", ",", "norm", "=", "norm", ")", "mappable", ".", "set_array", "(", "cmap_data", ")", "# TODO: Or what???", "fig", ".", "colorbar", "(", "mappable", ",", "ax", "=", "ax", ")" ]
Show a colorbar right of the plot.
[ "Show", "a", "colorbar", "right", "of", "the", "plot", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L831-L836
16,411
janpipek/physt
physt/plotting/matplotlib.py
_add_stats_box
def _add_stats_box(h1: Histogram1D, ax: Axes, stats: Union[str, bool] = "all"): """Insert a small legend-like box with statistical information. Parameters ---------- stats : "all" | "total" | True What info to display Note ---- Very basic implementation. """ # place a text box in upper left in axes coords if stats in ["all", True]: text = "Total: {0}\nMean: {1:.2f}\nStd.dev: {2:.2f}".format( h1.total, h1.mean(), h1.std()) elif stats == "total": text = "Total: {0}".format(h1.total) else: raise ValueError("Invalid stats specification") ax.text(0.05, 0.95, text, transform=ax.transAxes, verticalalignment='top', horizontalalignment='left')
python
def _add_stats_box(h1: Histogram1D, ax: Axes, stats: Union[str, bool] = "all"): """Insert a small legend-like box with statistical information. Parameters ---------- stats : "all" | "total" | True What info to display Note ---- Very basic implementation. """ # place a text box in upper left in axes coords if stats in ["all", True]: text = "Total: {0}\nMean: {1:.2f}\nStd.dev: {2:.2f}".format( h1.total, h1.mean(), h1.std()) elif stats == "total": text = "Total: {0}".format(h1.total) else: raise ValueError("Invalid stats specification") ax.text(0.05, 0.95, text, transform=ax.transAxes, verticalalignment='top', horizontalalignment='left')
[ "def", "_add_stats_box", "(", "h1", ":", "Histogram1D", ",", "ax", ":", "Axes", ",", "stats", ":", "Union", "[", "str", ",", "bool", "]", "=", "\"all\"", ")", ":", "# place a text box in upper left in axes coords", "if", "stats", "in", "[", "\"all\"", ",", "True", "]", ":", "text", "=", "\"Total: {0}\\nMean: {1:.2f}\\nStd.dev: {2:.2f}\"", ".", "format", "(", "h1", ".", "total", ",", "h1", ".", "mean", "(", ")", ",", "h1", ".", "std", "(", ")", ")", "elif", "stats", "==", "\"total\"", ":", "text", "=", "\"Total: {0}\"", ".", "format", "(", "h1", ".", "total", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid stats specification\"", ")", "ax", ".", "text", "(", "0.05", ",", "0.95", ",", "text", ",", "transform", "=", "ax", ".", "transAxes", ",", "verticalalignment", "=", "'top'", ",", "horizontalalignment", "=", "'left'", ")" ]
Insert a small legend-like box with statistical information. Parameters ---------- stats : "all" | "total" | True What info to display Note ---- Very basic implementation.
[ "Insert", "a", "small", "legend", "-", "like", "box", "with", "statistical", "information", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L839-L862
16,412
janpipek/physt
physt/examples/__init__.py
normal_h1
def normal_h1(size: int = 10000, mean: float = 0, sigma: float = 1) -> Histogram1D: """A simple 1D histogram with normal distribution. Parameters ---------- size : Number of points mean : Mean of the distribution sigma : Sigma of the distribution """ data = np.random.normal(mean, sigma, (size,)) return h1(data, name="normal", axis_name="x", title="1D normal distribution")
python
def normal_h1(size: int = 10000, mean: float = 0, sigma: float = 1) -> Histogram1D: """A simple 1D histogram with normal distribution. Parameters ---------- size : Number of points mean : Mean of the distribution sigma : Sigma of the distribution """ data = np.random.normal(mean, sigma, (size,)) return h1(data, name="normal", axis_name="x", title="1D normal distribution")
[ "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. Parameters ---------- size : Number of points mean : Mean of the distribution sigma : Sigma of the distribution
[ "A", "simple", "1D", "histogram", "with", "normal", "distribution", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/examples/__init__.py#L12-L22
16,413
janpipek/physt
physt/examples/__init__.py
normal_h2
def normal_h2(size: int = 10000) -> Histogram2D: """A simple 2D histogram with normal distribution. Parameters ---------- size : Number of points """ 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")
python
def normal_h2(size: int = 10000) -> Histogram2D: """A simple 2D histogram with normal distribution. Parameters ---------- size : Number of points """ 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")
[ "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. Parameters ---------- size : Number of points
[ "A", "simple", "2D", "histogram", "with", "normal", "distribution", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/examples/__init__.py#L25-L34
16,414
janpipek/physt
physt/examples/__init__.py
normal_h3
def normal_h3(size: int = 10000) -> HistogramND: """A simple 3D histogram with normal distribution. Parameters ---------- size : Number of points """ 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 normal distribution")
python
def normal_h3(size: int = 10000) -> HistogramND: """A simple 3D histogram with normal distribution. Parameters ---------- size : Number of points """ 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 normal distribution")
[ "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 normal distribution\"", ")" ]
A simple 3D histogram with normal distribution. Parameters ---------- size : Number of points
[ "A", "simple", "3D", "histogram", "with", "normal", "distribution", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/examples/__init__.py#L37-L47
16,415
janpipek/physt
physt/examples/__init__.py
fist
def fist() -> Histogram1D: """A simple histogram in the shape of a fist.""" 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(edges, heights, axis_name="Is this a fist?", title="Physt \"logo\"")
python
def fist() -> Histogram1D: """A simple histogram in the shape of a fist.""" 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(edges, heights, axis_name="Is this a fist?", title="Physt \"logo\"")
[ "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", "(", "edges", ",", "heights", ",", "axis_name", "=", "\"Is this a fist?\"", ",", "title", "=", "\"Physt \\\"logo\\\"\"", ")" ]
A simple histogram in the shape of a fist.
[ "A", "simple", "histogram", "in", "the", "shape", "of", "a", "fist", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/examples/__init__.py#L50-L57
16,416
janpipek/physt
physt/io/__init__.py
require_compatible_version
def require_compatible_version(compatible_version, word="File"): """Check that compatible version of input data is not too new.""" if isinstance(compatible_version, str): compatible_version = parse_version(compatible_version) elif not isinstance(compatible_version, Version): raise ValueError("Type of `compatible_version` not understood.") current_version = parse_version(CURRENT_VERSION) if current_version < compatible_version: raise VersionError("{0} written for version >= {1}, this is {2}.".format( word, str(compatible_version), CURRENT_VERSION ))
python
def require_compatible_version(compatible_version, word="File"): """Check that compatible version of input data is not too new.""" if isinstance(compatible_version, str): compatible_version = parse_version(compatible_version) elif not isinstance(compatible_version, Version): raise ValueError("Type of `compatible_version` not understood.") current_version = parse_version(CURRENT_VERSION) if current_version < compatible_version: raise VersionError("{0} written for version >= {1}, this is {2}.".format( word, str(compatible_version), CURRENT_VERSION ))
[ "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 `compatible_version` not understood.\"", ")", "current_version", "=", "parse_version", "(", "CURRENT_VERSION", ")", "if", "current_version", "<", "compatible_version", ":", "raise", "VersionError", "(", "\"{0} written for version >= {1}, this is {2}.\"", ".", "format", "(", "word", ",", "str", "(", "compatible_version", ")", ",", "CURRENT_VERSION", ")", ")" ]
Check that compatible version of input data is not too new.
[ "Check", "that", "compatible", "version", "of", "input", "data", "is", "not", "too", "new", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/__init__.py#L52-L63
16,417
janpipek/physt
physt/io/json.py
save_json
def save_json(histogram: Union[HistogramBase, HistogramCollection], path: Optional[str] = None, **kwargs) -> str: """Save histogram to JSON format. Parameters ---------- histogram : Any histogram path : If set, also writes to the path. Returns ------- json : The JSON representation of the histogram """ # TODO: Implement multiple histograms in one file? data = histogram.to_dict() data["physt_version"] = CURRENT_VERSION if isinstance(histogram, HistogramBase): data["physt_compatible"] = COMPATIBLE_VERSION elif isinstance(histogram, HistogramCollection): data["physt_compatible"] = COLLECTION_COMPATIBLE_VERSION else: raise TypeError("Cannot save unknown type: {0}".format(type(histogram))) text = json.dumps(data, **kwargs) if path: with open(path, "w", encoding="utf-8") as f: f.write(text) return text
python
def save_json(histogram: Union[HistogramBase, HistogramCollection], path: Optional[str] = None, **kwargs) -> str: """Save histogram to JSON format. Parameters ---------- histogram : Any histogram path : If set, also writes to the path. Returns ------- json : The JSON representation of the histogram """ # TODO: Implement multiple histograms in one file? data = histogram.to_dict() data["physt_version"] = CURRENT_VERSION if isinstance(histogram, HistogramBase): data["physt_compatible"] = COMPATIBLE_VERSION elif isinstance(histogram, HistogramCollection): data["physt_compatible"] = COLLECTION_COMPATIBLE_VERSION else: raise TypeError("Cannot save unknown type: {0}".format(type(histogram))) text = json.dumps(data, **kwargs) if path: with open(path, "w", encoding="utf-8") as f: f.write(text) return text
[ "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", "(", "histogram", ",", "HistogramBase", ")", ":", "data", "[", "\"physt_compatible\"", "]", "=", "COMPATIBLE_VERSION", "elif", "isinstance", "(", "histogram", ",", "HistogramCollection", ")", ":", "data", "[", "\"physt_compatible\"", "]", "=", "COLLECTION_COMPATIBLE_VERSION", "else", ":", "raise", "TypeError", "(", "\"Cannot save unknown type: {0}\"", ".", "format", "(", "type", "(", "histogram", ")", ")", ")", "text", "=", "json", ".", "dumps", "(", "data", ",", "*", "*", "kwargs", ")", "if", "path", ":", "with", "open", "(", "path", ",", "\"w\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "f", ".", "write", "(", "text", ")", "return", "text" ]
Save histogram to JSON format. Parameters ---------- histogram : Any histogram path : If set, also writes to the path. Returns ------- json : The JSON representation of the histogram
[ "Save", "histogram", "to", "JSON", "format", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/json.py#L13-L40
16,418
janpipek/physt
physt/io/json.py
load_json
def load_json(path: str, encoding: str = "utf-8") -> HistogramBase: """Load histogram from a JSON file.""" with open(path, "r", encoding=encoding) as f: text = f.read() return parse_json(text)
python
def load_json(path: str, encoding: str = "utf-8") -> HistogramBase: """Load histogram from a JSON file.""" with open(path, "r", encoding=encoding) as f: text = f.read() return parse_json(text)
[ "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.
[ "Load", "histogram", "from", "a", "JSON", "file", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/json.py#L43-L47
16,419
janpipek/physt
physt/io/json.py
parse_json
def parse_json(text: str, encoding: str = "utf-8") -> HistogramBase: """Create histogram from a JSON string.""" data = json.loads(text, encoding=encoding) return create_from_dict(data, format_name="JSON")
python
def parse_json(text: str, encoding: str = "utf-8") -> HistogramBase: """Create histogram from a JSON string.""" data = json.loads(text, encoding=encoding) return create_from_dict(data, format_name="JSON")
[ "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.
[ "Create", "histogram", "from", "a", "JSON", "string", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/json.py#L50-L53
16,420
janpipek/physt
physt/__init__.py
histogram
def histogram(data, bins=None, *args, **kwargs): """Facade function to create 1D histograms. This proceeds in three steps: 1) Based on magical parameter bins, construct bins for the histogram 2) Calculate frequencies for the bins 3) Construct the histogram object itself *Guiding principle:* parameters understood by numpy.histogram should be understood also by physt.histogram as well and should result in a Histogram1D object with (h.numpy_bins, h.frequencies) same as the numpy.histogram output. Additional functionality is a bonus. This function is also aliased as "h1". Parameters ---------- data : array_like, optional Container of all the values (tuple, list, np.ndarray, pd.Series) bins: int or sequence of scalars or callable or str, optional If iterable => the bins themselves If int => number of bins for default binning If callable => use binning method (+ args, kwargs) If string => use named binning method (+ args, kwargs) weights: array_like, optional (as numpy.histogram) keep_missed: Optional[bool] store statistics about how many values were lower than limits and how many higher than limits (default: True) dropna: bool whether to clear data from nan's before histogramming name: str name of the histogram axis_name: str name of the variable on x axis adaptive: bool whether we want the bins to be modifiable (useful for continuous filling of a priori unknown data) dtype: type customize underlying data type: default int64 (without weight) or float (with weights) Other numpy.histogram parameters are excluded, see the methods of the Histogram1D class itself. Returns ------- physt.histogram1d.Histogram1D See Also -------- numpy.histogram """ 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 isinstance(data, tuple) and isinstance(data[0], str): # Works for groupby DataSeries return histogram(data[1], bins, *args, name=data[0], **kwargs) elif type(data).__name__ == "DataFrame": raise RuntimeError("Cannot create histogram from a pandas DataFrame. Use Series.") # Collect arguments (not to send them to binning algorithms) dropna = kwargs.pop("dropna", True) weights = kwargs.pop("weights", None) keep_missed = kwargs.pop("keep_missed", True) name = kwargs.pop("name", None) axis_name = kwargs.pop("axis_name", None) title = kwargs.pop("title", None) # Convert to array if data is not None: array = np.asarray(data) #.flatten() if dropna: array = array[~np.isnan(array)] else: array = None # Get binning binning = calculate_bins(array, bins, *args, check_nan=not dropna and array is not None, adaptive=adaptive, **kwargs) # bins = binning.bins # Get frequencies if array is not None: (frequencies, errors2, underflow, overflow, stats) =\ calculate_frequencies(array, binning=binning, weights=weights, dtype=dtype) else: frequencies = None errors2 = None underflow = 0 overflow = 0 stats = {"sum": 0.0, "sum2": 0.0} # Construct the object if not keep_missed: underflow = 0 overflow = 0 if not axis_name: if hasattr(data, "name"): axis_name = data.name elif hasattr(data, "fields") and len(data.fields) == 1 and isinstance(data.fields[0], str): # Case of dask fields (examples) axis_name = data.fields[0] return Histogram1D(binning=binning, frequencies=frequencies, errors2=errors2, overflow=overflow, underflow=underflow, stats=stats, dtype=dtype, keep_missed=keep_missed, name=name, axis_name=axis_name, title=title)
python
def histogram(data, bins=None, *args, **kwargs): """Facade function to create 1D histograms. This proceeds in three steps: 1) Based on magical parameter bins, construct bins for the histogram 2) Calculate frequencies for the bins 3) Construct the histogram object itself *Guiding principle:* parameters understood by numpy.histogram should be understood also by physt.histogram as well and should result in a Histogram1D object with (h.numpy_bins, h.frequencies) same as the numpy.histogram output. Additional functionality is a bonus. This function is also aliased as "h1". Parameters ---------- data : array_like, optional Container of all the values (tuple, list, np.ndarray, pd.Series) bins: int or sequence of scalars or callable or str, optional If iterable => the bins themselves If int => number of bins for default binning If callable => use binning method (+ args, kwargs) If string => use named binning method (+ args, kwargs) weights: array_like, optional (as numpy.histogram) keep_missed: Optional[bool] store statistics about how many values were lower than limits and how many higher than limits (default: True) dropna: bool whether to clear data from nan's before histogramming name: str name of the histogram axis_name: str name of the variable on x axis adaptive: bool whether we want the bins to be modifiable (useful for continuous filling of a priori unknown data) dtype: type customize underlying data type: default int64 (without weight) or float (with weights) Other numpy.histogram parameters are excluded, see the methods of the Histogram1D class itself. Returns ------- physt.histogram1d.Histogram1D See Also -------- numpy.histogram """ 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 isinstance(data, tuple) and isinstance(data[0], str): # Works for groupby DataSeries return histogram(data[1], bins, *args, name=data[0], **kwargs) elif type(data).__name__ == "DataFrame": raise RuntimeError("Cannot create histogram from a pandas DataFrame. Use Series.") # Collect arguments (not to send them to binning algorithms) dropna = kwargs.pop("dropna", True) weights = kwargs.pop("weights", None) keep_missed = kwargs.pop("keep_missed", True) name = kwargs.pop("name", None) axis_name = kwargs.pop("axis_name", None) title = kwargs.pop("title", None) # Convert to array if data is not None: array = np.asarray(data) #.flatten() if dropna: array = array[~np.isnan(array)] else: array = None # Get binning binning = calculate_bins(array, bins, *args, check_nan=not dropna and array is not None, adaptive=adaptive, **kwargs) # bins = binning.bins # Get frequencies if array is not None: (frequencies, errors2, underflow, overflow, stats) =\ calculate_frequencies(array, binning=binning, weights=weights, dtype=dtype) else: frequencies = None errors2 = None underflow = 0 overflow = 0 stats = {"sum": 0.0, "sum2": 0.0} # Construct the object if not keep_missed: underflow = 0 overflow = 0 if not axis_name: if hasattr(data, "name"): axis_name = data.name elif hasattr(data, "fields") and len(data.fields) == 1 and isinstance(data.fields[0], str): # Case of dask fields (examples) axis_name = data.fields[0] return Histogram1D(binning=binning, frequencies=frequencies, errors2=errors2, overflow=overflow, underflow=underflow, stats=stats, dtype=dtype, keep_missed=keep_missed, name=name, axis_name=axis_name, title=title)
[ "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", "isinstance", "(", "data", ",", "tuple", ")", "and", "isinstance", "(", "data", "[", "0", "]", ",", "str", ")", ":", "# Works for groupby DataSeries", "return", "histogram", "(", "data", "[", "1", "]", ",", "bins", ",", "*", "args", ",", "name", "=", "data", "[", "0", "]", ",", "*", "*", "kwargs", ")", "elif", "type", "(", "data", ")", ".", "__name__", "==", "\"DataFrame\"", ":", "raise", "RuntimeError", "(", "\"Cannot create histogram from a pandas DataFrame. Use Series.\"", ")", "# Collect arguments (not to send them to binning algorithms)", "dropna", "=", "kwargs", ".", "pop", "(", "\"dropna\"", ",", "True", ")", "weights", "=", "kwargs", ".", "pop", "(", "\"weights\"", ",", "None", ")", "keep_missed", "=", "kwargs", ".", "pop", "(", "\"keep_missed\"", ",", "True", ")", "name", "=", "kwargs", ".", "pop", "(", "\"name\"", ",", "None", ")", "axis_name", "=", "kwargs", ".", "pop", "(", "\"axis_name\"", ",", "None", ")", "title", "=", "kwargs", ".", "pop", "(", "\"title\"", ",", "None", ")", "# Convert to array", "if", "data", "is", "not", "None", ":", "array", "=", "np", ".", "asarray", "(", "data", ")", "#.flatten()", "if", "dropna", ":", "array", "=", "array", "[", "~", "np", ".", "isnan", "(", "array", ")", "]", "else", ":", "array", "=", "None", "# Get binning", "binning", "=", "calculate_bins", "(", "array", ",", "bins", ",", "*", "args", ",", "check_nan", "=", "not", "dropna", "and", "array", "is", "not", "None", ",", "adaptive", "=", "adaptive", ",", "*", "*", "kwargs", ")", "# bins = binning.bins", "# Get frequencies", "if", "array", "is", "not", "None", ":", "(", "frequencies", ",", "errors2", ",", "underflow", ",", "overflow", ",", "stats", ")", "=", "calculate_frequencies", "(", "array", ",", "binning", "=", "binning", ",", "weights", "=", "weights", ",", "dtype", "=", "dtype", ")", "else", ":", "frequencies", "=", "None", "errors2", "=", "None", "underflow", "=", "0", "overflow", "=", "0", "stats", "=", "{", "\"sum\"", ":", "0.0", ",", "\"sum2\"", ":", "0.0", "}", "# Construct the object", "if", "not", "keep_missed", ":", "underflow", "=", "0", "overflow", "=", "0", "if", "not", "axis_name", ":", "if", "hasattr", "(", "data", ",", "\"name\"", ")", ":", "axis_name", "=", "data", ".", "name", "elif", "hasattr", "(", "data", ",", "\"fields\"", ")", "and", "len", "(", "data", ".", "fields", ")", "==", "1", "and", "isinstance", "(", "data", ".", "fields", "[", "0", "]", ",", "str", ")", ":", "# Case of dask fields (examples)", "axis_name", "=", "data", ".", "fields", "[", "0", "]", "return", "Histogram1D", "(", "binning", "=", "binning", ",", "frequencies", "=", "frequencies", ",", "errors2", "=", "errors2", ",", "overflow", "=", "overflow", ",", "underflow", "=", "underflow", ",", "stats", "=", "stats", ",", "dtype", "=", "dtype", ",", "keep_missed", "=", "keep_missed", ",", "name", "=", "name", ",", "axis_name", "=", "axis_name", ",", "title", "=", "title", ")" ]
Facade function to create 1D histograms. This proceeds in three steps: 1) Based on magical parameter bins, construct bins for the histogram 2) Calculate frequencies for the bins 3) Construct the histogram object itself *Guiding principle:* parameters understood by numpy.histogram should be understood also by physt.histogram as well and should result in a Histogram1D object with (h.numpy_bins, h.frequencies) same as the numpy.histogram output. Additional functionality is a bonus. This function is also aliased as "h1". Parameters ---------- data : array_like, optional Container of all the values (tuple, list, np.ndarray, pd.Series) bins: int or sequence of scalars or callable or str, optional If iterable => the bins themselves If int => number of bins for default binning If callable => use binning method (+ args, kwargs) If string => use named binning method (+ args, kwargs) weights: array_like, optional (as numpy.histogram) keep_missed: Optional[bool] store statistics about how many values were lower than limits and how many higher than limits (default: True) dropna: bool whether to clear data from nan's before histogramming name: str name of the histogram axis_name: str name of the variable on x axis adaptive: bool whether we want the bins to be modifiable (useful for continuous filling of a priori unknown data) dtype: type customize underlying data type: default int64 (without weight) or float (with weights) Other numpy.histogram parameters are excluded, see the methods of the Histogram1D class itself. Returns ------- physt.histogram1d.Histogram1D See Also -------- numpy.histogram
[ "Facade", "function", "to", "create", "1D", "histograms", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/__init__.py#L16-L127
16,421
janpipek/physt
physt/__init__.py
histogram2d
def histogram2d(data1, data2, bins=10, *args, **kwargs): """Facade function to create 2D histograms. For implementation and parameters, see histogramdd. This function is also aliased as "h2". Returns ------- physt.histogram_nd.Histogram2D See Also -------- numpy.histogram2d histogramdd """ 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 data1 is not None and data2 is not None: data1 = np.asarray(data1) data2 = np.asarray(data2) data = np.concatenate([data1[:, np.newaxis], data2[:, np.newaxis]], axis=1) else: data = None return histogramdd(data, bins, *args, dim=2, **kwargs)
python
def histogram2d(data1, data2, bins=10, *args, **kwargs): """Facade function to create 2D histograms. For implementation and parameters, see histogramdd. This function is also aliased as "h2". Returns ------- physt.histogram_nd.Histogram2D See Also -------- numpy.histogram2d histogramdd """ 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 data1 is not None and data2 is not None: data1 = np.asarray(data1) data2 = np.asarray(data2) data = np.concatenate([data1[:, np.newaxis], data2[:, np.newaxis]], axis=1) else: data = None return histogramdd(data, bins, *args, dim=2, **kwargs)
[ "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", "data1", "is", "not", "None", "and", "data2", "is", "not", "None", ":", "data1", "=", "np", ".", "asarray", "(", "data1", ")", "data2", "=", "np", ".", "asarray", "(", "data2", ")", "data", "=", "np", ".", "concatenate", "(", "[", "data1", "[", ":", ",", "np", ".", "newaxis", "]", ",", "data2", "[", ":", ",", "np", ".", "newaxis", "]", "]", ",", "axis", "=", "1", ")", "else", ":", "data", "=", "None", "return", "histogramdd", "(", "data", ",", "bins", ",", "*", "args", ",", "dim", "=", "2", ",", "*", "*", "kwargs", ")" ]
Facade function to create 2D histograms. For implementation and parameters, see histogramdd. This function is also aliased as "h2". Returns ------- physt.histogram_nd.Histogram2D See Also -------- numpy.histogram2d histogramdd
[ "Facade", "function", "to", "create", "2D", "histograms", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/__init__.py#L130-L159
16,422
janpipek/physt
physt/__init__.py
histogramdd
def histogramdd(data, bins=10, *args, **kwargs): """Facade function to create n-dimensional histograms. 3D variant of this function is also aliased as "h3". Parameters ---------- data : array_like Container of all the values bins: Any weights: array_like, optional (as numpy.histogram) dropna: bool whether to clear data from nan's before histogramming name: str name of the histogram axis_names: Iterable[str] names of the variable on x axis adaptive: whether the bins should be updated when new non-fitting value are filled dtype: Optional[type] Underlying type for the histogram. If weights are specified, default is float. Otherwise int64 dim: int Dimension - necessary if you are creating an empty adaptive histogram Returns ------- physt.histogram_nd.HistogramND See Also -------- numpy.histogramdd """ 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) title = kwargs.pop("title", None) dim = kwargs.pop("dim", None) axis_names = kwargs.pop("axis_names", None) # pandas - guess axis names if not "axis_names" in kwargs: if hasattr(data, "columns"): try: kwargs["axis_names"] = tuple(data.columns) except: pass # Perhaps columns has different meaning here. # Prepare and check data # Convert to array if data is not None: data = np.asarray(data) if data.ndim != 2: raise RuntimeError("Array must have shape (n, d)") if dim is not None and dim != data.shape[1]: raise RuntimeError("Dimension mismatch: {0}!={1}".format(dim, data.shape[1])) _, dim = data.shape if dropna: data = data[~np.isnan(data).any(axis=1)] check_nan = not dropna else: if dim is None: raise RuntimeError("You have to specify either data or its dimension.") data = np.zeros((0, dim)) check_nan = False # Prepare bins bin_schemas = calculate_bins_nd(data, bins, *args, check_nan=check_nan, adaptive=adaptive, **kwargs) #bins = [binning.bins for binning in bin_schemas] # Prepare remaining data weights = kwargs.pop("weights", None) frequencies, errors2, missed = histogram_nd.calculate_frequencies(data, ndim=dim, binnings=bin_schemas, weights=weights) kwargs["name"] = name if title: kwargs["title"] = title if axis_names: kwargs["axis_names"] = axis_names if dim == 2: return histogram_nd.Histogram2D(binnings=bin_schemas, frequencies=frequencies, errors2=errors2, **kwargs) else: return histogram_nd.HistogramND(dimension=dim, binnings=bin_schemas, frequencies=frequencies, errors2=errors2, **kwargs)
python
def histogramdd(data, bins=10, *args, **kwargs): """Facade function to create n-dimensional histograms. 3D variant of this function is also aliased as "h3". Parameters ---------- data : array_like Container of all the values bins: Any weights: array_like, optional (as numpy.histogram) dropna: bool whether to clear data from nan's before histogramming name: str name of the histogram axis_names: Iterable[str] names of the variable on x axis adaptive: whether the bins should be updated when new non-fitting value are filled dtype: Optional[type] Underlying type for the histogram. If weights are specified, default is float. Otherwise int64 dim: int Dimension - necessary if you are creating an empty adaptive histogram Returns ------- physt.histogram_nd.HistogramND See Also -------- numpy.histogramdd """ 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) title = kwargs.pop("title", None) dim = kwargs.pop("dim", None) axis_names = kwargs.pop("axis_names", None) # pandas - guess axis names if not "axis_names" in kwargs: if hasattr(data, "columns"): try: kwargs["axis_names"] = tuple(data.columns) except: pass # Perhaps columns has different meaning here. # Prepare and check data # Convert to array if data is not None: data = np.asarray(data) if data.ndim != 2: raise RuntimeError("Array must have shape (n, d)") if dim is not None and dim != data.shape[1]: raise RuntimeError("Dimension mismatch: {0}!={1}".format(dim, data.shape[1])) _, dim = data.shape if dropna: data = data[~np.isnan(data).any(axis=1)] check_nan = not dropna else: if dim is None: raise RuntimeError("You have to specify either data or its dimension.") data = np.zeros((0, dim)) check_nan = False # Prepare bins bin_schemas = calculate_bins_nd(data, bins, *args, check_nan=check_nan, adaptive=adaptive, **kwargs) #bins = [binning.bins for binning in bin_schemas] # Prepare remaining data weights = kwargs.pop("weights", None) frequencies, errors2, missed = histogram_nd.calculate_frequencies(data, ndim=dim, binnings=bin_schemas, weights=weights) kwargs["name"] = name if title: kwargs["title"] = title if axis_names: kwargs["axis_names"] = axis_names if dim == 2: return histogram_nd.Histogram2D(binnings=bin_schemas, frequencies=frequencies, errors2=errors2, **kwargs) else: return histogram_nd.HistogramND(dimension=dim, binnings=bin_schemas, frequencies=frequencies, errors2=errors2, **kwargs)
[ "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", ")", "title", "=", "kwargs", ".", "pop", "(", "\"title\"", ",", "None", ")", "dim", "=", "kwargs", ".", "pop", "(", "\"dim\"", ",", "None", ")", "axis_names", "=", "kwargs", ".", "pop", "(", "\"axis_names\"", ",", "None", ")", "# pandas - guess axis names", "if", "not", "\"axis_names\"", "in", "kwargs", ":", "if", "hasattr", "(", "data", ",", "\"columns\"", ")", ":", "try", ":", "kwargs", "[", "\"axis_names\"", "]", "=", "tuple", "(", "data", ".", "columns", ")", "except", ":", "pass", "# Perhaps columns has different meaning here.", "# Prepare and check data", "# Convert to array", "if", "data", "is", "not", "None", ":", "data", "=", "np", ".", "asarray", "(", "data", ")", "if", "data", ".", "ndim", "!=", "2", ":", "raise", "RuntimeError", "(", "\"Array must have shape (n, d)\"", ")", "if", "dim", "is", "not", "None", "and", "dim", "!=", "data", ".", "shape", "[", "1", "]", ":", "raise", "RuntimeError", "(", "\"Dimension mismatch: {0}!={1}\"", ".", "format", "(", "dim", ",", "data", ".", "shape", "[", "1", "]", ")", ")", "_", ",", "dim", "=", "data", ".", "shape", "if", "dropna", ":", "data", "=", "data", "[", "~", "np", ".", "isnan", "(", "data", ")", ".", "any", "(", "axis", "=", "1", ")", "]", "check_nan", "=", "not", "dropna", "else", ":", "if", "dim", "is", "None", ":", "raise", "RuntimeError", "(", "\"You have to specify either data or its dimension.\"", ")", "data", "=", "np", ".", "zeros", "(", "(", "0", ",", "dim", ")", ")", "check_nan", "=", "False", "# Prepare bins", "bin_schemas", "=", "calculate_bins_nd", "(", "data", ",", "bins", ",", "*", "args", ",", "check_nan", "=", "check_nan", ",", "adaptive", "=", "adaptive", ",", "*", "*", "kwargs", ")", "#bins = [binning.bins for binning in bin_schemas]", "# Prepare remaining data", "weights", "=", "kwargs", ".", "pop", "(", "\"weights\"", ",", "None", ")", "frequencies", ",", "errors2", ",", "missed", "=", "histogram_nd", ".", "calculate_frequencies", "(", "data", ",", "ndim", "=", "dim", ",", "binnings", "=", "bin_schemas", ",", "weights", "=", "weights", ")", "kwargs", "[", "\"name\"", "]", "=", "name", "if", "title", ":", "kwargs", "[", "\"title\"", "]", "=", "title", "if", "axis_names", ":", "kwargs", "[", "\"axis_names\"", "]", "=", "axis_names", "if", "dim", "==", "2", ":", "return", "histogram_nd", ".", "Histogram2D", "(", "binnings", "=", "bin_schemas", ",", "frequencies", "=", "frequencies", ",", "errors2", "=", "errors2", ",", "*", "*", "kwargs", ")", "else", ":", "return", "histogram_nd", ".", "HistogramND", "(", "dimension", "=", "dim", ",", "binnings", "=", "bin_schemas", ",", "frequencies", "=", "frequencies", ",", "errors2", "=", "errors2", ",", "*", "*", "kwargs", ")" ]
Facade function to create n-dimensional histograms. 3D variant of this function is also aliased as "h3". Parameters ---------- data : array_like Container of all the values bins: Any weights: array_like, optional (as numpy.histogram) dropna: bool whether to clear data from nan's before histogramming name: str name of the histogram axis_names: Iterable[str] names of the variable on x axis adaptive: whether the bins should be updated when new non-fitting value are filled dtype: Optional[type] Underlying type for the histogram. If weights are specified, default is float. Otherwise int64 dim: int Dimension - necessary if you are creating an empty adaptive histogram Returns ------- physt.histogram_nd.HistogramND See Also -------- numpy.histogramdd
[ "Facade", "function", "to", "create", "n", "-", "dimensional", "histograms", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/__init__.py#L162-L254
16,423
janpipek/physt
physt/__init__.py
h3
def h3(data, *args, **kwargs): """Facade function to create 3D histograms. Parameters ---------- data : array_like or list[array_like] or tuple[array_like] Can be a single array (with three columns) or three different arrays (for each component) Returns ------- physt.histogram_nd.HistogramND """ 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) for column in data] data = np.concatenate([item[:, np.newaxis] for item in data], axis=1) else: kwargs["dim"] = 3 return histogramdd(data, *args, **kwargs)
python
def h3(data, *args, **kwargs): """Facade function to create 3D histograms. Parameters ---------- data : array_like or list[array_like] or tuple[array_like] Can be a single array (with three columns) or three different arrays (for each component) Returns ------- physt.histogram_nd.HistogramND """ 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) for column in data] data = np.concatenate([item[:, np.newaxis] for item in data], axis=1) else: kwargs["dim"] = 3 return histogramdd(data, *args, **kwargs)
[ "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", ")", "for", "column", "in", "data", "]", "data", "=", "np", ".", "concatenate", "(", "[", "item", "[", ":", ",", "np", ".", "newaxis", "]", "for", "item", "in", "data", "]", ",", "axis", "=", "1", ")", "else", ":", "kwargs", "[", "\"dim\"", "]", "=", "3", "return", "histogramdd", "(", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Facade function to create 3D histograms. Parameters ---------- data : array_like or list[array_like] or tuple[array_like] Can be a single array (with three columns) or three different arrays (for each component) Returns ------- physt.histogram_nd.HistogramND
[ "Facade", "function", "to", "create", "3D", "histograms", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/__init__.py#L263-L284
16,424
janpipek/physt
physt/__init__.py
collection
def collection(data, bins=10, *args, **kwargs): """Create histogram collection with shared binnning.""" 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)
python
def collection(data, bins=10, *args, **kwargs): """Create histogram collection with shared binnning.""" 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)
[ "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.
[ "Create", "histogram", "collection", "with", "shared", "binnning", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/__init__.py#L287-L292
16,425
janpipek/physt
physt/io/root.py
write_root
def write_root(histogram: HistogramBase, hfile: uproot.write.TFile.TFileUpdate, name: str): """Write histogram to an open ROOT file. Parameters ---------- histogram : Any histogram hfile : Updateable uproot file object name : The name of the histogram inside the file """ hfile[name] = histogram
python
def write_root(histogram: HistogramBase, hfile: uproot.write.TFile.TFileUpdate, name: str): """Write histogram to an open ROOT file. Parameters ---------- histogram : Any histogram hfile : Updateable uproot file object name : The name of the histogram inside the file """ hfile[name] = histogram
[ "def", "write_root", "(", "histogram", ":", "HistogramBase", ",", "hfile", ":", "uproot", ".", "write", ".", "TFile", ".", "TFileUpdate", ",", "name", ":", "str", ")", ":", "hfile", "[", "name", "]", "=", "histogram" ]
Write histogram to an open ROOT file. Parameters ---------- histogram : Any histogram hfile : Updateable uproot file object name : The name of the histogram inside the file
[ "Write", "histogram", "to", "an", "open", "ROOT", "file", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/root.py#L16-L25
16,426
janpipek/physt
physt/io/protobuf/__init__.py
write
def write(histogram): """Convert a histogram to a protobuf message. Note: Currently, all binnings are converted to static form. When you load the histogram again, you will lose any related behaviour. Note: A histogram collection is also planned. Parameters ---------- histogram : HistogramBase | list | dict Any histogram Returns ------- message : google.protobuf.message.Message A protocol buffer message """ 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(histogram.frequencies.flatten()) message.errors2.extend(histogram.errors2.flatten()) # Binnings for binning in histogram._binnings: binning_message = message.binnings.add() for edges in binning.bins: limits = binning_message.bins.add() limits.lower = edges[0] limits.upper = edges[1] # All meta data meta_message = message.meta # user_defined = {} # for key, value in histogram.meta_data.items(): # if key not in PREDEFINED: # user_defined[str(key)] = str(value) for key in SIMPLE_META_KEYS: if key in histogram.meta_data: setattr(meta_message, key, str(histogram.meta_data[key])) if "axis_names" in histogram.meta_data: meta_message.axis_names.extend(histogram.meta_data["axis_names"]) message.physt_version = CURRENT_VERSION message.physt_compatible = COMPATIBLE_VERSION return message
python
def write(histogram): """Convert a histogram to a protobuf message. Note: Currently, all binnings are converted to static form. When you load the histogram again, you will lose any related behaviour. Note: A histogram collection is also planned. Parameters ---------- histogram : HistogramBase | list | dict Any histogram Returns ------- message : google.protobuf.message.Message A protocol buffer message """ 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(histogram.frequencies.flatten()) message.errors2.extend(histogram.errors2.flatten()) # Binnings for binning in histogram._binnings: binning_message = message.binnings.add() for edges in binning.bins: limits = binning_message.bins.add() limits.lower = edges[0] limits.upper = edges[1] # All meta data meta_message = message.meta # user_defined = {} # for key, value in histogram.meta_data.items(): # if key not in PREDEFINED: # user_defined[str(key)] = str(value) for key in SIMPLE_META_KEYS: if key in histogram.meta_data: setattr(meta_message, key, str(histogram.meta_data[key])) if "axis_names" in histogram.meta_data: meta_message.axis_names.extend(histogram.meta_data["axis_names"]) message.physt_version = CURRENT_VERSION message.physt_compatible = COMPATIBLE_VERSION return message
[ "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", "(", "histogram", ".", "frequencies", ".", "flatten", "(", ")", ")", "message", ".", "errors2", ".", "extend", "(", "histogram", ".", "errors2", ".", "flatten", "(", ")", ")", "# Binnings", "for", "binning", "in", "histogram", ".", "_binnings", ":", "binning_message", "=", "message", ".", "binnings", ".", "add", "(", ")", "for", "edges", "in", "binning", ".", "bins", ":", "limits", "=", "binning_message", ".", "bins", ".", "add", "(", ")", "limits", ".", "lower", "=", "edges", "[", "0", "]", "limits", ".", "upper", "=", "edges", "[", "1", "]", "# All meta data", "meta_message", "=", "message", ".", "meta", "# user_defined = {}", "# for key, value in histogram.meta_data.items():", "# if key not in PREDEFINED:", "# user_defined[str(key)] = str(value)", "for", "key", "in", "SIMPLE_META_KEYS", ":", "if", "key", "in", "histogram", ".", "meta_data", ":", "setattr", "(", "meta_message", ",", "key", ",", "str", "(", "histogram", ".", "meta_data", "[", "key", "]", ")", ")", "if", "\"axis_names\"", "in", "histogram", ".", "meta_data", ":", "meta_message", ".", "axis_names", ".", "extend", "(", "histogram", ".", "meta_data", "[", "\"axis_names\"", "]", ")", "message", ".", "physt_version", "=", "CURRENT_VERSION", "message", ".", "physt_compatible", "=", "COMPATIBLE_VERSION", "return", "message" ]
Convert a histogram to a protobuf message. Note: Currently, all binnings are converted to static form. When you load the histogram again, you will lose any related behaviour. Note: A histogram collection is also planned. Parameters ---------- histogram : HistogramBase | list | dict Any histogram Returns ------- message : google.protobuf.message.Message A protocol buffer message
[ "Convert", "a", "histogram", "to", "a", "protobuf", "message", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/protobuf/__init__.py#L24-L76
16,427
janpipek/physt
physt/io/protobuf/__init__.py
read
def read(message): """Convert a parsed protobuf message into a histogram.""" require_compatible_version(message.physt_compatible) # Currently the only implementation a_dict = _dict_from_v0342(message) return create_from_dict(a_dict, "Message")
python
def read(message): """Convert a parsed protobuf message into a histogram.""" require_compatible_version(message.physt_compatible) # Currently the only implementation a_dict = _dict_from_v0342(message) return create_from_dict(a_dict, "Message")
[ "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.
[ "Convert", "a", "parsed", "protobuf", "message", "into", "a", "histogram", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/protobuf/__init__.py#L79-L85
16,428
janpipek/physt
physt/bin_utils.py
make_bin_array
def make_bin_array(bins) -> np.ndarray: """Turn bin data into array understood by HistogramXX classes. Parameters ---------- bins: array_like Array of edges or array of edge tuples Examples -------- >>> make_bin_array([0, 1, 2]) array([[0, 1], [1, 2]]) >>> make_bin_array([[0, 1], [2, 3]]) array([[0, 1], [2, 3]]) """ 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.ndim == 2: if bins.shape[1] != 2: raise RuntimeError("Binning schema with ndim==2 must have 2 columns") # if bins.shape[0] == 0: # raise RuntimeError("Needs at least one bin") return bins # Already correct, just pass else: raise RuntimeError("Binning schema must have ndim==1 or ndim==2")
python
def make_bin_array(bins) -> np.ndarray: """Turn bin data into array understood by HistogramXX classes. Parameters ---------- bins: array_like Array of edges or array of edge tuples Examples -------- >>> make_bin_array([0, 1, 2]) array([[0, 1], [1, 2]]) >>> make_bin_array([[0, 1], [2, 3]]) array([[0, 1], [2, 3]]) """ 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.ndim == 2: if bins.shape[1] != 2: raise RuntimeError("Binning schema with ndim==2 must have 2 columns") # if bins.shape[0] == 0: # raise RuntimeError("Needs at least one bin") return bins # Already correct, just pass else: raise RuntimeError("Binning schema must have ndim==1 or ndim==2")
[ "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", ".", "ndim", "==", "2", ":", "if", "bins", ".", "shape", "[", "1", "]", "!=", "2", ":", "raise", "RuntimeError", "(", "\"Binning schema with ndim==2 must have 2 columns\"", ")", "# if bins.shape[0] == 0:", "# raise RuntimeError(\"Needs at least one bin\")", "return", "bins", "# Already correct, just pass", "else", ":", "raise", "RuntimeError", "(", "\"Binning schema must have ndim==1 or ndim==2\"", ")" ]
Turn bin data into array understood by HistogramXX classes. Parameters ---------- bins: array_like Array of edges or array of edge tuples Examples -------- >>> make_bin_array([0, 1, 2]) array([[0, 1], [1, 2]]) >>> make_bin_array([[0, 1], [2, 3]]) array([[0, 1], [2, 3]])
[ "Turn", "bin", "data", "into", "array", "understood", "by", "HistogramXX", "classes", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/bin_utils.py#L7-L36
16,429
janpipek/physt
physt/bin_utils.py
to_numpy_bins
def to_numpy_bins(bins) -> np.ndarray: """Convert physt bin format to numpy edges. Parameters ---------- bins: array_like 1-D (n) or 2-D (n, 2) array of edges Returns ------- edges: all edges """ 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 np.concatenate([bins[:1, 0], bins[:, 1]])
python
def to_numpy_bins(bins) -> np.ndarray: """Convert physt bin format to numpy edges. Parameters ---------- bins: array_like 1-D (n) or 2-D (n, 2) array of edges Returns ------- edges: all edges """ 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 np.concatenate([bins[:1, 0], bins[:, 1]])
[ "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", "np", ".", "concatenate", "(", "[", "bins", "[", ":", "1", ",", "0", "]", ",", "bins", "[", ":", ",", "1", "]", "]", ")" ]
Convert physt bin format to numpy edges. Parameters ---------- bins: array_like 1-D (n) or 2-D (n, 2) array of edges Returns ------- edges: all edges
[ "Convert", "physt", "bin", "format", "to", "numpy", "edges", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/bin_utils.py#L39-L56
16,430
janpipek/physt
physt/bin_utils.py
to_numpy_bins_with_mask
def to_numpy_bins_with_mask(bins) -> Tuple[np.ndarray, np.ndarray]: """Numpy binning edges including gaps. Parameters ---------- bins: array_like 1-D (n) or 2-D (n, 2) array of edges Returns ------- edges: np.ndarray all edges mask: np.ndarray List of indices that correspond to bins that have to be included Examples -------- >>> to_numpy_bins_with_mask([0, 1, 2]) (array([0., 1., 2.]), array([0, 1])) >>> to_numpy_bins_with_mask([[0, 1], [2, 3]]) (array([0, 1, 2, 3]), array([0, 2]) """ 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.ndim == 2: edges = [] mask = [] j = 0 if bins.shape[0] > 0: edges.append(bins[0, 0]) for i in range(bins.shape[0] - 1): mask.append(j) edges.append(bins[i, 1]) if bins[i, 1] != bins[i+1, 0]: edges.append(bins[i+1, 0]) j += 1 j += 1 mask.append(j) edges.append(bins[-1, 1]) else: raise RuntimeError("to_numpy_bins_with_mask: array with dim=1 or 2 expected") if not np.all(np.diff(edges) > 0): raise RuntimeError("to_numpy_bins_with_mask: edges array not monotone.") return edges, mask
python
def to_numpy_bins_with_mask(bins) -> Tuple[np.ndarray, np.ndarray]: """Numpy binning edges including gaps. Parameters ---------- bins: array_like 1-D (n) or 2-D (n, 2) array of edges Returns ------- edges: np.ndarray all edges mask: np.ndarray List of indices that correspond to bins that have to be included Examples -------- >>> to_numpy_bins_with_mask([0, 1, 2]) (array([0., 1., 2.]), array([0, 1])) >>> to_numpy_bins_with_mask([[0, 1], [2, 3]]) (array([0, 1, 2, 3]), array([0, 2]) """ 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.ndim == 2: edges = [] mask = [] j = 0 if bins.shape[0] > 0: edges.append(bins[0, 0]) for i in range(bins.shape[0] - 1): mask.append(j) edges.append(bins[i, 1]) if bins[i, 1] != bins[i+1, 0]: edges.append(bins[i+1, 0]) j += 1 j += 1 mask.append(j) edges.append(bins[-1, 1]) else: raise RuntimeError("to_numpy_bins_with_mask: array with dim=1 or 2 expected") if not np.all(np.diff(edges) > 0): raise RuntimeError("to_numpy_bins_with_mask: edges array not monotone.") return edges, mask
[ "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", ".", "ndim", "==", "2", ":", "edges", "=", "[", "]", "mask", "=", "[", "]", "j", "=", "0", "if", "bins", ".", "shape", "[", "0", "]", ">", "0", ":", "edges", ".", "append", "(", "bins", "[", "0", ",", "0", "]", ")", "for", "i", "in", "range", "(", "bins", ".", "shape", "[", "0", "]", "-", "1", ")", ":", "mask", ".", "append", "(", "j", ")", "edges", ".", "append", "(", "bins", "[", "i", ",", "1", "]", ")", "if", "bins", "[", "i", ",", "1", "]", "!=", "bins", "[", "i", "+", "1", ",", "0", "]", ":", "edges", ".", "append", "(", "bins", "[", "i", "+", "1", ",", "0", "]", ")", "j", "+=", "1", "j", "+=", "1", "mask", ".", "append", "(", "j", ")", "edges", ".", "append", "(", "bins", "[", "-", "1", ",", "1", "]", ")", "else", ":", "raise", "RuntimeError", "(", "\"to_numpy_bins_with_mask: array with dim=1 or 2 expected\"", ")", "if", "not", "np", ".", "all", "(", "np", ".", "diff", "(", "edges", ")", ">", "0", ")", ":", "raise", "RuntimeError", "(", "\"to_numpy_bins_with_mask: edges array not monotone.\"", ")", "return", "edges", ",", "mask" ]
Numpy binning edges including gaps. Parameters ---------- bins: array_like 1-D (n) or 2-D (n, 2) array of edges Returns ------- edges: np.ndarray all edges mask: np.ndarray List of indices that correspond to bins that have to be included Examples -------- >>> to_numpy_bins_with_mask([0, 1, 2]) (array([0., 1., 2.]), array([0, 1])) >>> to_numpy_bins_with_mask([[0, 1], [2, 3]]) (array([0, 1, 2, 3]), array([0, 2])
[ "Numpy", "binning", "edges", "including", "gaps", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/bin_utils.py#L59-L108
16,431
janpipek/physt
physt/bin_utils.py
is_rising
def is_rising(bins) -> bool: """Check whether the bins are in raising order. Does not check if the bins are consecutive. Parameters ---------- bins: array_like """ # 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
python
def is_rising(bins) -> bool: """Check whether the bins are in raising order. Does not check if the bins are consecutive. Parameters ---------- bins: array_like """ # 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
[ "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. Does not check if the bins are consecutive. Parameters ---------- bins: array_like
[ "Check", "whether", "the", "bins", "are", "in", "raising", "order", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/bin_utils.py#L111-L126
16,432
janpipek/physt
physt/plotting/common.py
get_data
def get_data(histogram: HistogramBase, density: bool = False, cumulative: bool = False, flatten: bool = False) -> np.ndarray: """Get histogram data based on plotting parameters. Parameters ---------- density : Whether to divide bin contents by bin size cumulative : Whether to return cumulative sums instead of individual flatten : Whether to flatten multidimensional bins """ if density: if cumulative: data = (histogram / histogram.total).cumulative_frequencies else: data = histogram.densities else: if cumulative: data = histogram.cumulative_frequencies else: data = histogram.frequencies if flatten: data = data.flatten() return data
python
def get_data(histogram: HistogramBase, density: bool = False, cumulative: bool = False, flatten: bool = False) -> np.ndarray: """Get histogram data based on plotting parameters. Parameters ---------- density : Whether to divide bin contents by bin size cumulative : Whether to return cumulative sums instead of individual flatten : Whether to flatten multidimensional bins """ if density: if cumulative: data = (histogram / histogram.total).cumulative_frequencies else: data = histogram.densities else: if cumulative: data = histogram.cumulative_frequencies else: data = histogram.frequencies if flatten: data = data.flatten() return data
[ "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", "=", "histogram", ".", "densities", "else", ":", "if", "cumulative", ":", "data", "=", "histogram", ".", "cumulative_frequencies", "else", ":", "data", "=", "histogram", ".", "frequencies", "if", "flatten", ":", "data", "=", "data", ".", "flatten", "(", ")", "return", "data" ]
Get histogram data based on plotting parameters. Parameters ---------- density : Whether to divide bin contents by bin size cumulative : Whether to return cumulative sums instead of individual flatten : Whether to flatten multidimensional bins
[ "Get", "histogram", "data", "based", "on", "plotting", "parameters", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/common.py#L15-L37
16,433
janpipek/physt
physt/plotting/common.py
get_err_data
def get_err_data(histogram: HistogramBase, density: bool = False, cumulative: bool = False, flatten: bool = False) -> np.ndarray: """Get histogram error data based on plotting parameters. Parameters ---------- density : Whether to divide bin contents by bin size cumulative : Whether to return cumulative sums instead of individual flatten : Whether to flatten multidimensional bins """ if cumulative: raise RuntimeError("Error bars not supported for cumulative plots.") if density: data = histogram.errors / histogram.bin_sizes else: data = histogram.errors if flatten: data = data.flatten() return data
python
def get_err_data(histogram: HistogramBase, density: bool = False, cumulative: bool = False, flatten: bool = False) -> np.ndarray: """Get histogram error data based on plotting parameters. Parameters ---------- density : Whether to divide bin contents by bin size cumulative : Whether to return cumulative sums instead of individual flatten : Whether to flatten multidimensional bins """ if cumulative: raise RuntimeError("Error bars not supported for cumulative plots.") if density: data = histogram.errors / histogram.bin_sizes else: data = histogram.errors if flatten: data = data.flatten() return data
[ "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", ".", "errors", "/", "histogram", ".", "bin_sizes", "else", ":", "data", "=", "histogram", ".", "errors", "if", "flatten", ":", "data", "=", "data", ".", "flatten", "(", ")", "return", "data" ]
Get histogram error data based on plotting parameters. Parameters ---------- density : Whether to divide bin contents by bin size cumulative : Whether to return cumulative sums instead of individual flatten : Whether to flatten multidimensional bins
[ "Get", "histogram", "error", "data", "based", "on", "plotting", "parameters", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/common.py#L40-L57
16,434
janpipek/physt
physt/plotting/common.py
get_value_format
def get_value_format(value_format: Union[Callable, str] = str) -> Callable[[float], str]: """Create a formatting function from a generic value_format argument. """ if value_format is None: value_format = "" if isinstance(value_format, str): format_str = "{0:" + value_format + "}" def value_format(x): return format_str.format(x) return value_format
python
def get_value_format(value_format: Union[Callable, str] = str) -> Callable[[float], str]: """Create a formatting function from a generic value_format argument. """ if value_format is None: value_format = "" if isinstance(value_format, str): format_str = "{0:" + value_format + "}" def value_format(x): return format_str.format(x) return value_format
[ "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", "format_str", ".", "format", "(", "x", ")", "return", "value_format" ]
Create a formatting function from a generic value_format argument.
[ "Create", "a", "formatting", "function", "from", "a", "generic", "value_format", "argument", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/common.py#L60-L70
16,435
janpipek/physt
physt/plotting/common.py
pop_kwargs_with_prefix
def pop_kwargs_with_prefix(prefix: str, kwargs: dict) -> dict: """Pop all items from a dictionary that have keys beginning with a prefix. Parameters ---------- prefix : str kwargs : dict Returns ------- kwargs : dict Items popped from the original directory, with prefix removed. """ keys = [key for key in kwargs if key.startswith(prefix)] return {key[len(prefix):]: kwargs.pop(key) for key in keys}
python
def pop_kwargs_with_prefix(prefix: str, kwargs: dict) -> dict: """Pop all items from a dictionary that have keys beginning with a prefix. Parameters ---------- prefix : str kwargs : dict Returns ------- kwargs : dict Items popped from the original directory, with prefix removed. """ keys = [key for key in kwargs if key.startswith(prefix)] return {key[len(prefix):]: kwargs.pop(key) for key in keys}
[ "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. Parameters ---------- prefix : str kwargs : dict Returns ------- kwargs : dict Items popped from the original directory, with prefix removed.
[ "Pop", "all", "items", "from", "a", "dictionary", "that", "have", "keys", "beginning", "with", "a", "prefix", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/common.py#L73-L87
16,436
janpipek/physt
physt/histogram_nd.py
HistogramND.bins
def bins(self) -> List[np.ndarray]: """List of bin matrices.""" return [binning.bins for binning in self._binnings]
python
def bins(self) -> List[np.ndarray]: """List of bin matrices.""" return [binning.bins for binning in self._binnings]
[ "def", "bins", "(", "self", ")", "->", "List", "[", "np", ".", "ndarray", "]", ":", "return", "[", "binning", ".", "bins", "for", "binning", "in", "self", ".", "_binnings", "]" ]
List of bin matrices.
[ "List", "of", "bin", "matrices", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_nd.py#L54-L56
16,437
janpipek/physt
physt/histogram_nd.py
HistogramND.select
def select(self, axis: AxisIdentifier, index, force_copy: bool = False) -> HistogramBase: """Select in an axis. Parameters ---------- axis: int or str Axis, in which we select. index: int or slice Index of bin (as in numpy). force_copy: bool If True, identity slice force a copy to be made. """ 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 range(self.ndim)] array_index[axis_id] = index frequencies = self._frequencies[tuple(array_index)].copy() errors2 = self._errors2[tuple(array_index)].copy() if isinstance(index, int): return self._reduce_dimension([ax for ax in range(self.ndim) if ax != axis_id], frequencies, errors2) elif isinstance(index, slice): if index.step is not None and index.step < 0: raise IndexError("Cannot change the order of bins") copy = self.copy() copy._frequencies = frequencies copy._errors2 = errors2 copy._binnings[axis_id] = self._binnings[axis_id][index] return copy else: raise ValueError("Invalid index.")
python
def select(self, axis: AxisIdentifier, index, force_copy: bool = False) -> HistogramBase: """Select in an axis. Parameters ---------- axis: int or str Axis, in which we select. index: int or slice Index of bin (as in numpy). force_copy: bool If True, identity slice force a copy to be made. """ 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 range(self.ndim)] array_index[axis_id] = index frequencies = self._frequencies[tuple(array_index)].copy() errors2 = self._errors2[tuple(array_index)].copy() if isinstance(index, int): return self._reduce_dimension([ax for ax in range(self.ndim) if ax != axis_id], frequencies, errors2) elif isinstance(index, slice): if index.step is not None and index.step < 0: raise IndexError("Cannot change the order of bins") copy = self.copy() copy._frequencies = frequencies copy._errors2 = errors2 copy._binnings[axis_id] = self._binnings[axis_id][index] return copy else: raise ValueError("Invalid index.")
[ "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", "range", "(", "self", ".", "ndim", ")", "]", "array_index", "[", "axis_id", "]", "=", "index", "frequencies", "=", "self", ".", "_frequencies", "[", "tuple", "(", "array_index", ")", "]", ".", "copy", "(", ")", "errors2", "=", "self", ".", "_errors2", "[", "tuple", "(", "array_index", ")", "]", ".", "copy", "(", ")", "if", "isinstance", "(", "index", ",", "int", ")", ":", "return", "self", ".", "_reduce_dimension", "(", "[", "ax", "for", "ax", "in", "range", "(", "self", ".", "ndim", ")", "if", "ax", "!=", "axis_id", "]", ",", "frequencies", ",", "errors2", ")", "elif", "isinstance", "(", "index", ",", "slice", ")", ":", "if", "index", ".", "step", "is", "not", "None", "and", "index", ".", "step", "<", "0", ":", "raise", "IndexError", "(", "\"Cannot change the order of bins\"", ")", "copy", "=", "self", ".", "copy", "(", ")", "copy", ".", "_frequencies", "=", "frequencies", "copy", ".", "_errors2", "=", "errors2", "copy", ".", "_binnings", "[", "axis_id", "]", "=", "self", ".", "_binnings", "[", "axis_id", "]", "[", "index", "]", "return", "copy", "else", ":", "raise", "ValueError", "(", "\"Invalid index.\"", ")" ]
Select in an axis. Parameters ---------- axis: int or str Axis, in which we select. index: int or slice Index of bin (as in numpy). force_copy: bool If True, identity slice force a copy to be made.
[ "Select", "in", "an", "axis", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_nd.py#L71-L104
16,438
janpipek/physt
physt/histogram_nd.py
HistogramND.accumulate
def accumulate(self, axis: AxisIdentifier) -> HistogramBase: """Calculate cumulative frequencies along a certain axis. Returns ------- new_hist: Histogram of the same type & size """ # 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) new_one._frequencies = np.cumsum(new_one.frequencies, axis_id[0]) return new_one
python
def accumulate(self, axis: AxisIdentifier) -> HistogramBase: """Calculate cumulative frequencies along a certain axis. Returns ------- new_hist: Histogram of the same type & size """ # 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) new_one._frequencies = np.cumsum(new_one.frequencies, axis_id[0]) return new_one
[ "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", ")", "new_one", ".", "_frequencies", "=", "np", ".", "cumsum", "(", "new_one", ".", "frequencies", ",", "axis_id", "[", "0", "]", ")", "return", "new_one" ]
Calculate cumulative frequencies along a certain axis. Returns ------- new_hist: Histogram of the same type & size
[ "Calculate", "cumulative", "frequencies", "along", "a", "certain", "axis", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_nd.py#L338-L351
16,439
janpipek/physt
physt/histogram_nd.py
Histogram2D.T
def T(self) -> "Histogram2D": """Histogram with swapped axes. Returns ------- Histogram2D - a copy with swapped axes """ 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._errors2.T return a_copy
python
def T(self) -> "Histogram2D": """Histogram with swapped axes. Returns ------- Histogram2D - a copy with swapped axes """ 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._errors2.T return a_copy
[ "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", ".", "_errors2", ".", "T", "return", "a_copy" ]
Histogram with swapped axes. Returns ------- Histogram2D - a copy with swapped axes
[ "Histogram", "with", "swapped", "axes", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_nd.py#L414-L426
16,440
janpipek/physt
physt/histogram_nd.py
Histogram2D.partial_normalize
def partial_normalize(self, axis: AxisIdentifier = 0, inplace: bool = False): """Normalize in rows or columns. Parameters ---------- axis: int or str Along which axis to sum (numpy-sense) inplace: bool Update the object itself Returns ------- hist : Histogram2D """ # TODO: Is this applicable for HistogramND? axis = self._get_axis(axis) if not inplace: copy = self.copy() copy.partial_normalize(axis, inplace=True) return copy else: self._coerce_dtype(float) if axis == 0: divisor = self._frequencies.sum(axis=0) else: divisor = self._frequencies.sum(axis=1)[:, np.newaxis] divisor[divisor == 0] = 1 # Prevent division errors self._frequencies /= divisor self._errors2 /= (divisor * divisor) # Has its limitations return self
python
def partial_normalize(self, axis: AxisIdentifier = 0, inplace: bool = False): """Normalize in rows or columns. Parameters ---------- axis: int or str Along which axis to sum (numpy-sense) inplace: bool Update the object itself Returns ------- hist : Histogram2D """ # TODO: Is this applicable for HistogramND? axis = self._get_axis(axis) if not inplace: copy = self.copy() copy.partial_normalize(axis, inplace=True) return copy else: self._coerce_dtype(float) if axis == 0: divisor = self._frequencies.sum(axis=0) else: divisor = self._frequencies.sum(axis=1)[:, np.newaxis] divisor[divisor == 0] = 1 # Prevent division errors self._frequencies /= divisor self._errors2 /= (divisor * divisor) # Has its limitations return self
[ "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", ",", "inplace", "=", "True", ")", "return", "copy", "else", ":", "self", ".", "_coerce_dtype", "(", "float", ")", "if", "axis", "==", "0", ":", "divisor", "=", "self", ".", "_frequencies", ".", "sum", "(", "axis", "=", "0", ")", "else", ":", "divisor", "=", "self", ".", "_frequencies", ".", "sum", "(", "axis", "=", "1", ")", "[", ":", ",", "np", ".", "newaxis", "]", "divisor", "[", "divisor", "==", "0", "]", "=", "1", "# Prevent division errors", "self", ".", "_frequencies", "/=", "divisor", "self", ".", "_errors2", "/=", "(", "divisor", "*", "divisor", ")", "# Has its limitations", "return", "self" ]
Normalize in rows or columns. Parameters ---------- axis: int or str Along which axis to sum (numpy-sense) inplace: bool Update the object itself Returns ------- hist : Histogram2D
[ "Normalize", "in", "rows", "or", "columns", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_nd.py#L428-L457
16,441
janpipek/physt
physt/binnings.py
numpy_binning
def numpy_binning(data, bins=10, range=None, *args, **kwargs) -> NumpyBinning: """Construct binning schema compatible with numpy.histogram Parameters ---------- data: array_like, optional This is optional if both bins and range are set bins: int or array_like range: Optional[tuple] (min, max) includes_right_edge: Optional[bool] default: True See Also -------- numpy.histogram """ if isinstance(bins, int): if range: bins = np.linspace(range[0], range[1], bins + 1) else: start = data.min() stop = data.max() bins = np.linspace(start, stop, bins + 1) elif np.iterable(bins): bins = np.asarray(bins) else: # Some numpy edge case _, bins = np.histogram(data, bins, **kwargs) return NumpyBinning(bins)
python
def numpy_binning(data, bins=10, range=None, *args, **kwargs) -> NumpyBinning: """Construct binning schema compatible with numpy.histogram Parameters ---------- data: array_like, optional This is optional if both bins and range are set bins: int or array_like range: Optional[tuple] (min, max) includes_right_edge: Optional[bool] default: True See Also -------- numpy.histogram """ if isinstance(bins, int): if range: bins = np.linspace(range[0], range[1], bins + 1) else: start = data.min() stop = data.max() bins = np.linspace(start, stop, bins + 1) elif np.iterable(bins): bins = np.asarray(bins) else: # Some numpy edge case _, bins = np.histogram(data, bins, **kwargs) return NumpyBinning(bins)
[ "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", "(", ")", "bins", "=", "np", ".", "linspace", "(", "start", ",", "stop", ",", "bins", "+", "1", ")", "elif", "np", ".", "iterable", "(", "bins", ")", ":", "bins", "=", "np", ".", "asarray", "(", "bins", ")", "else", ":", "# Some numpy edge case", "_", ",", "bins", "=", "np", ".", "histogram", "(", "data", ",", "bins", ",", "*", "*", "kwargs", ")", "return", "NumpyBinning", "(", "bins", ")" ]
Construct binning schema compatible with numpy.histogram Parameters ---------- data: array_like, optional This is optional if both bins and range are set bins: int or array_like range: Optional[tuple] (min, max) includes_right_edge: Optional[bool] default: True See Also -------- numpy.histogram
[ "Construct", "binning", "schema", "compatible", "with", "numpy", ".", "histogram" ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L596-L625
16,442
janpipek/physt
physt/binnings.py
human_binning
def human_binning(data=None, bin_count: Optional[int] = None, *, range=None, **kwargs) -> FixedWidthBinning: """Construct fixed-width ninning schema with bins automatically optimized to human-friendly widths. Typical widths are: 1.0, 25,0, 0.02, 500, 2.5e-7, ... Parameters ---------- bin_count: Number of bins range: Optional[tuple] (min, max) """ 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 guess optimum bin width without data.") if bin_count is None: bin_count = ideal_bin_count(data) min_ = range[0] if range else data.min() max_ = range[1] if range else data.max() bw = (max_ - min_) / bin_count power = np.floor(np.log10(bw)).astype(int) best_index = np.argmin(np.abs(np.log(subscales * (10.0 ** power) / bw))) bin_width = (10.0 ** power) * subscales[best_index] return fixed_width_binning(bin_width=bin_width, data=data, range=range, **kwargs)
python
def human_binning(data=None, bin_count: Optional[int] = None, *, range=None, **kwargs) -> FixedWidthBinning: """Construct fixed-width ninning schema with bins automatically optimized to human-friendly widths. Typical widths are: 1.0, 25,0, 0.02, 500, 2.5e-7, ... Parameters ---------- bin_count: Number of bins range: Optional[tuple] (min, max) """ 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 guess optimum bin width without data.") if bin_count is None: bin_count = ideal_bin_count(data) min_ = range[0] if range else data.min() max_ = range[1] if range else data.max() bw = (max_ - min_) / bin_count power = np.floor(np.log10(bw)).astype(int) best_index = np.argmin(np.abs(np.log(subscales * (10.0 ** power) / bw))) bin_width = (10.0 ** power) * subscales[best_index] return fixed_width_binning(bin_width=bin_width, data=data, range=range, **kwargs)
[ "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 guess optimum bin width without data.\"", ")", "if", "bin_count", "is", "None", ":", "bin_count", "=", "ideal_bin_count", "(", "data", ")", "min_", "=", "range", "[", "0", "]", "if", "range", "else", "data", ".", "min", "(", ")", "max_", "=", "range", "[", "1", "]", "if", "range", "else", "data", ".", "max", "(", ")", "bw", "=", "(", "max_", "-", "min_", ")", "/", "bin_count", "power", "=", "np", ".", "floor", "(", "np", ".", "log10", "(", "bw", ")", ")", ".", "astype", "(", "int", ")", "best_index", "=", "np", ".", "argmin", "(", "np", ".", "abs", "(", "np", ".", "log", "(", "subscales", "*", "(", "10.0", "**", "power", ")", "/", "bw", ")", ")", ")", "bin_width", "=", "(", "10.0", "**", "power", ")", "*", "subscales", "[", "best_index", "]", "return", "fixed_width_binning", "(", "bin_width", "=", "bin_width", ",", "data", "=", "data", ",", "range", "=", "range", ",", "*", "*", "kwargs", ")" ]
Construct fixed-width ninning schema with bins automatically optimized to human-friendly widths. Typical widths are: 1.0, 25,0, 0.02, 500, 2.5e-7, ... Parameters ---------- bin_count: Number of bins range: Optional[tuple] (min, max)
[ "Construct", "fixed", "-", "width", "ninning", "schema", "with", "bins", "automatically", "optimized", "to", "human", "-", "friendly", "widths", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L628-L653
16,443
janpipek/physt
physt/binnings.py
quantile_binning
def quantile_binning(data=None, bins=10, *, qrange=(0.0, 1.0), **kwargs) -> StaticBinning: """Binning schema based on quantile ranges. This binning finds equally spaced quantiles. This should lead to all bins having roughly the same frequencies. Note: weights are not (yet) take into account for calculating quantiles. Parameters ---------- bins: sequence or Optional[int] Number of bins qrange: Optional[tuple] Two floats as minimum and maximum quantile (default: 0.0, 1.0) Returns ------- 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_array(bins), includes_right_edge=True)
python
def quantile_binning(data=None, bins=10, *, qrange=(0.0, 1.0), **kwargs) -> StaticBinning: """Binning schema based on quantile ranges. This binning finds equally spaced quantiles. This should lead to all bins having roughly the same frequencies. Note: weights are not (yet) take into account for calculating quantiles. Parameters ---------- bins: sequence or Optional[int] Number of bins qrange: Optional[tuple] Two floats as minimum and maximum quantile (default: 0.0, 1.0) Returns ------- 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_array(bins), includes_right_edge=True)
[ "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_array", "(", "bins", ")", ",", "includes_right_edge", "=", "True", ")" ]
Binning schema based on quantile ranges. This binning finds equally spaced quantiles. This should lead to all bins having roughly the same frequencies. Note: weights are not (yet) take into account for calculating quantiles. Parameters ---------- bins: sequence or Optional[int] Number of bins qrange: Optional[tuple] Two floats as minimum and maximum quantile (default: 0.0, 1.0) Returns ------- StaticBinning
[ "Binning", "schema", "based", "on", "quantile", "ranges", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L656-L680
16,444
janpipek/physt
physt/binnings.py
static_binning
def static_binning(data=None, bins=None, **kwargs) -> StaticBinning: """Construct static binning with whatever bins.""" return StaticBinning(bins=make_bin_array(bins), **kwargs)
python
def static_binning(data=None, bins=None, **kwargs) -> StaticBinning: """Construct static binning with whatever bins.""" return StaticBinning(bins=make_bin_array(bins), **kwargs)
[ "def", "static_binning", "(", "data", "=", "None", ",", "bins", "=", "None", ",", "*", "*", "kwargs", ")", "->", "StaticBinning", ":", "return", "StaticBinning", "(", "bins", "=", "make_bin_array", "(", "bins", ")", ",", "*", "*", "kwargs", ")" ]
Construct static binning with whatever bins.
[ "Construct", "static", "binning", "with", "whatever", "bins", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L683-L685
16,445
janpipek/physt
physt/binnings.py
integer_binning
def integer_binning(data=None, **kwargs) -> StaticBinning: """Construct fixed-width binning schema with bins centered around integers. Parameters ---------- range: Optional[Tuple[int]] min (included) and max integer (excluded) bin bin_width: Optional[int] group "bin_width" integers into one bin (not recommended) """ 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=True, bin_shift=0.5, **kwargs)
python
def integer_binning(data=None, **kwargs) -> StaticBinning: """Construct fixed-width binning schema with bins centered around integers. Parameters ---------- range: Optional[Tuple[int]] min (included) and max integer (excluded) bin bin_width: Optional[int] group "bin_width" integers into one bin (not recommended) """ 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=True, bin_shift=0.5, **kwargs)
[ "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", "=", "True", ",", "bin_shift", "=", "0.5", ",", "*", "*", "kwargs", ")" ]
Construct fixed-width binning schema with bins centered around integers. Parameters ---------- range: Optional[Tuple[int]] min (included) and max integer (excluded) bin bin_width: Optional[int] group "bin_width" integers into one bin (not recommended)
[ "Construct", "fixed", "-", "width", "binning", "schema", "with", "bins", "centered", "around", "integers", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L688-L701
16,446
janpipek/physt
physt/binnings.py
fixed_width_binning
def fixed_width_binning(data=None, bin_width: Union[float, int] = 1, *, range=None, includes_right_edge=False, **kwargs) -> FixedWidthBinning: """Construct fixed-width binning schema. Parameters ---------- bin_width: float range: Optional[tuple] (min, max) align: Optional[float] Must be multiple of bin_width """ result = FixedWidthBinning(bin_width=bin_width, includes_right_edge=includes_right_edge, **kwargs) if range: result._force_bin_existence(range[0]) result._force_bin_existence(range[1], includes_right_edge=True) if not kwargs.get("adaptive"): return result # Otherwise we want to adapt to data if data is not None and data.shape[0]: # print("Jo, tady") result._force_bin_existence([np.min(data), np.max(data)], includes_right_edge=includes_right_edge) return result
python
def fixed_width_binning(data=None, bin_width: Union[float, int] = 1, *, range=None, includes_right_edge=False, **kwargs) -> FixedWidthBinning: """Construct fixed-width binning schema. Parameters ---------- bin_width: float range: Optional[tuple] (min, max) align: Optional[float] Must be multiple of bin_width """ result = FixedWidthBinning(bin_width=bin_width, includes_right_edge=includes_right_edge, **kwargs) if range: result._force_bin_existence(range[0]) result._force_bin_existence(range[1], includes_right_edge=True) if not kwargs.get("adaptive"): return result # Otherwise we want to adapt to data if data is not None and data.shape[0]: # print("Jo, tady") result._force_bin_existence([np.min(data), np.max(data)], includes_right_edge=includes_right_edge) return result
[ "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", ",", "*", "*", "kwargs", ")", "if", "range", ":", "result", ".", "_force_bin_existence", "(", "range", "[", "0", "]", ")", "result", ".", "_force_bin_existence", "(", "range", "[", "1", "]", ",", "includes_right_edge", "=", "True", ")", "if", "not", "kwargs", ".", "get", "(", "\"adaptive\"", ")", ":", "return", "result", "# Otherwise we want to adapt to data", "if", "data", "is", "not", "None", "and", "data", ".", "shape", "[", "0", "]", ":", "# print(\"Jo, tady\")", "result", ".", "_force_bin_existence", "(", "[", "np", ".", "min", "(", "data", ")", ",", "np", ".", "max", "(", "data", ")", "]", ",", "includes_right_edge", "=", "includes_right_edge", ")", "return", "result" ]
Construct fixed-width binning schema. Parameters ---------- bin_width: float range: Optional[tuple] (min, max) align: Optional[float] Must be multiple of bin_width
[ "Construct", "fixed", "-", "width", "binning", "schema", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L704-L726
16,447
janpipek/physt
physt/binnings.py
exponential_binning
def exponential_binning(data=None, bin_count: Optional[int] = None, *, range=None, **kwargs) -> ExponentialBinning: """Construct exponential binning schema. Parameters ---------- bin_count: Optional[int] Number of bins range: Optional[tuple] (min, max) See also -------- numpy.logspace - note that our range semantics is different """ if bin_count is None: bin_count = ideal_bin_count(data) if range: range = (np.log10(range[0]), np.log10(range[1])) else: range = (np.log10(data.min()), np.log10(data.max())) log_width = (range[1] - range[0]) / bin_count return ExponentialBinning(log_min=range[0], log_width=log_width, bin_count=bin_count, **kwargs)
python
def exponential_binning(data=None, bin_count: Optional[int] = None, *, range=None, **kwargs) -> ExponentialBinning: """Construct exponential binning schema. Parameters ---------- bin_count: Optional[int] Number of bins range: Optional[tuple] (min, max) See also -------- numpy.logspace - note that our range semantics is different """ if bin_count is None: bin_count = ideal_bin_count(data) if range: range = (np.log10(range[0]), np.log10(range[1])) else: range = (np.log10(data.min()), np.log10(data.max())) log_width = (range[1] - range[0]) / bin_count return ExponentialBinning(log_min=range[0], log_width=log_width, bin_count=bin_count, **kwargs)
[ "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", ":", "range", "=", "(", "np", ".", "log10", "(", "data", ".", "min", "(", ")", ")", ",", "np", ".", "log10", "(", "data", ".", "max", "(", ")", ")", ")", "log_width", "=", "(", "range", "[", "1", "]", "-", "range", "[", "0", "]", ")", "/", "bin_count", "return", "ExponentialBinning", "(", "log_min", "=", "range", "[", "0", "]", ",", "log_width", "=", "log_width", ",", "bin_count", "=", "bin_count", ",", "*", "*", "kwargs", ")" ]
Construct exponential binning schema. Parameters ---------- bin_count: Optional[int] Number of bins range: Optional[tuple] (min, max) See also -------- numpy.logspace - note that our range semantics is different
[ "Construct", "exponential", "binning", "schema", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L729-L751
16,448
janpipek/physt
physt/binnings.py
calculate_bins
def calculate_bins(array, _=None, *args, **kwargs) -> BinningBase: """Find optimal binning from arguments. Parameters ---------- array: arraylike Data from which the bins should be decided (sometimes used, sometimes not) _: int or str or Callable or arraylike or Iterable or BinningBase To-be-guessed parameter that specifies what kind of binning should be done check_nan: bool Check for the presence of nan's in array? Default: True range: tuple Limit values to a range. Some of the binning methods also (subsequently) use this parameter for the bin shape. Returns ------- BinningBase A two-dimensional array with pairs of bin edges (not necessarily consecutive). """ 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 kwargs.get("range", None): # TODO: re-consider the usage of this parameter array = array[(array >= kwargs["range"][0]) & (array <= kwargs["range"][1])] if _ is None: bin_count = 10 # kwargs.pop("bins", ideal_bin_count(data=array)) - same as numpy binning = numpy_binning(array, bin_count, *args, **kwargs) elif isinstance(_, BinningBase): binning = _ elif isinstance(_, int): binning = numpy_binning(array, _, *args, **kwargs) elif isinstance(_, str): # What about the ranges??? if _ in bincount_methods: bin_count = ideal_bin_count(array, method=_) binning = numpy_binning(array, bin_count, *args, **kwargs) elif _ in binning_methods: method = binning_methods[_] binning = method(array, *args, **kwargs) else: raise RuntimeError("No binning method {0} available.".format(_)) elif callable(_): binning = _(array, *args, **kwargs) elif np.iterable(_): binning = static_binning(array, _, *args, **kwargs) else: raise RuntimeError("Binning {0} not understood.".format(_)) return binning
python
def calculate_bins(array, _=None, *args, **kwargs) -> BinningBase: """Find optimal binning from arguments. Parameters ---------- array: arraylike Data from which the bins should be decided (sometimes used, sometimes not) _: int or str or Callable or arraylike or Iterable or BinningBase To-be-guessed parameter that specifies what kind of binning should be done check_nan: bool Check for the presence of nan's in array? Default: True range: tuple Limit values to a range. Some of the binning methods also (subsequently) use this parameter for the bin shape. Returns ------- BinningBase A two-dimensional array with pairs of bin edges (not necessarily consecutive). """ 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 kwargs.get("range", None): # TODO: re-consider the usage of this parameter array = array[(array >= kwargs["range"][0]) & (array <= kwargs["range"][1])] if _ is None: bin_count = 10 # kwargs.pop("bins", ideal_bin_count(data=array)) - same as numpy binning = numpy_binning(array, bin_count, *args, **kwargs) elif isinstance(_, BinningBase): binning = _ elif isinstance(_, int): binning = numpy_binning(array, _, *args, **kwargs) elif isinstance(_, str): # What about the ranges??? if _ in bincount_methods: bin_count = ideal_bin_count(array, method=_) binning = numpy_binning(array, bin_count, *args, **kwargs) elif _ in binning_methods: method = binning_methods[_] binning = method(array, *args, **kwargs) else: raise RuntimeError("No binning method {0} available.".format(_)) elif callable(_): binning = _(array, *args, **kwargs) elif np.iterable(_): binning = static_binning(array, _, *args, **kwargs) else: raise RuntimeError("Binning {0} not understood.".format(_)) return binning
[ "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", "kwargs", ".", "get", "(", "\"range\"", ",", "None", ")", ":", "# TODO: re-consider the usage of this parameter", "array", "=", "array", "[", "(", "array", ">=", "kwargs", "[", "\"range\"", "]", "[", "0", "]", ")", "&", "(", "array", "<=", "kwargs", "[", "\"range\"", "]", "[", "1", "]", ")", "]", "if", "_", "is", "None", ":", "bin_count", "=", "10", "# kwargs.pop(\"bins\", ideal_bin_count(data=array)) - same as numpy", "binning", "=", "numpy_binning", "(", "array", ",", "bin_count", ",", "*", "args", ",", "*", "*", "kwargs", ")", "elif", "isinstance", "(", "_", ",", "BinningBase", ")", ":", "binning", "=", "_", "elif", "isinstance", "(", "_", ",", "int", ")", ":", "binning", "=", "numpy_binning", "(", "array", ",", "_", ",", "*", "args", ",", "*", "*", "kwargs", ")", "elif", "isinstance", "(", "_", ",", "str", ")", ":", "# What about the ranges???", "if", "_", "in", "bincount_methods", ":", "bin_count", "=", "ideal_bin_count", "(", "array", ",", "method", "=", "_", ")", "binning", "=", "numpy_binning", "(", "array", ",", "bin_count", ",", "*", "args", ",", "*", "*", "kwargs", ")", "elif", "_", "in", "binning_methods", ":", "method", "=", "binning_methods", "[", "_", "]", "binning", "=", "method", "(", "array", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "raise", "RuntimeError", "(", "\"No binning method {0} available.\"", ".", "format", "(", "_", ")", ")", "elif", "callable", "(", "_", ")", ":", "binning", "=", "_", "(", "array", ",", "*", "args", ",", "*", "*", "kwargs", ")", "elif", "np", ".", "iterable", "(", "_", ")", ":", "binning", "=", "static_binning", "(", "array", ",", "_", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "raise", "RuntimeError", "(", "\"Binning {0} not understood.\"", ".", "format", "(", "_", ")", ")", "return", "binning" ]
Find optimal binning from arguments. Parameters ---------- array: arraylike Data from which the bins should be decided (sometimes used, sometimes not) _: int or str or Callable or arraylike or Iterable or BinningBase To-be-guessed parameter that specifies what kind of binning should be done check_nan: bool Check for the presence of nan's in array? Default: True range: tuple Limit values to a range. Some of the binning methods also (subsequently) use this parameter for the bin shape. Returns ------- BinningBase A two-dimensional array with pairs of bin edges (not necessarily consecutive).
[ "Find", "optimal", "binning", "from", "arguments", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L754-L804
16,449
janpipek/physt
physt/binnings.py
ideal_bin_count
def ideal_bin_count(data, method: str = "default") -> int: """A theoretically ideal bin count. Parameters ---------- data: array_likes Data to work on. Most methods don't use this. method: str Name of the method to apply, available values: - default (~sturges) - sqrt - sturges - doane - rice See https://en.wikipedia.org/wiki/Histogram for the description """ 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": return int(np.ceil(np.sqrt(n))) elif method == "sturges": return int(np.ceil(np.log2(n)) + 1) elif method == "doane": if n < 3: return 1 from scipy.stats import skew sigma = np.sqrt(6 * (n-2) / (n + 1) * (n + 3)) return int(np.ceil(1 + np.log2(n) + np.log2(1 + np.abs(skew(data)) / sigma))) elif method == "rice": return int(np.ceil(2 * np.power(n, 1 / 3)))
python
def ideal_bin_count(data, method: str = "default") -> int: """A theoretically ideal bin count. Parameters ---------- data: array_likes Data to work on. Most methods don't use this. method: str Name of the method to apply, available values: - default (~sturges) - sqrt - sturges - doane - rice See https://en.wikipedia.org/wiki/Histogram for the description """ 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": return int(np.ceil(np.sqrt(n))) elif method == "sturges": return int(np.ceil(np.log2(n)) + 1) elif method == "doane": if n < 3: return 1 from scipy.stats import skew sigma = np.sqrt(6 * (n-2) / (n + 1) * (n + 3)) return int(np.ceil(1 + np.log2(n) + np.log2(1 + np.abs(skew(data)) / sigma))) elif method == "rice": return int(np.ceil(2 * np.power(n, 1 / 3)))
[ "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\"", ":", "return", "int", "(", "np", ".", "ceil", "(", "np", ".", "sqrt", "(", "n", ")", ")", ")", "elif", "method", "==", "\"sturges\"", ":", "return", "int", "(", "np", ".", "ceil", "(", "np", ".", "log2", "(", "n", ")", ")", "+", "1", ")", "elif", "method", "==", "\"doane\"", ":", "if", "n", "<", "3", ":", "return", "1", "from", "scipy", ".", "stats", "import", "skew", "sigma", "=", "np", ".", "sqrt", "(", "6", "*", "(", "n", "-", "2", ")", "/", "(", "n", "+", "1", ")", "*", "(", "n", "+", "3", ")", ")", "return", "int", "(", "np", ".", "ceil", "(", "1", "+", "np", ".", "log2", "(", "n", ")", "+", "np", ".", "log2", "(", "1", "+", "np", ".", "abs", "(", "skew", "(", "data", ")", ")", "/", "sigma", ")", ")", ")", "elif", "method", "==", "\"rice\"", ":", "return", "int", "(", "np", ".", "ceil", "(", "2", "*", "np", ".", "power", "(", "n", ",", "1", "/", "3", ")", ")", ")" ]
A theoretically ideal bin count. Parameters ---------- data: array_likes Data to work on. Most methods don't use this. method: str Name of the method to apply, available values: - default (~sturges) - sqrt - sturges - doane - rice See https://en.wikipedia.org/wiki/Histogram for the description
[ "A", "theoretically", "ideal", "bin", "count", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L972-L1007
16,450
janpipek/physt
physt/binnings.py
as_binning
def as_binning(obj, copy: bool = False) -> BinningBase: """Ensure that an object is a binning Parameters --------- obj : BinningBase or array_like Can be a binning, numpy-like bins or full physt bins copy : If true, ensure that the returned object is independent """ if isinstance(obj, BinningBase): if copy: return obj.copy() else: return obj else: bins = make_bin_array(obj) return StaticBinning(bins)
python
def as_binning(obj, copy: bool = False) -> BinningBase: """Ensure that an object is a binning Parameters --------- obj : BinningBase or array_like Can be a binning, numpy-like bins or full physt bins copy : If true, ensure that the returned object is independent """ if isinstance(obj, BinningBase): if copy: return obj.copy() else: return obj else: bins = make_bin_array(obj) return StaticBinning(bins)
[ "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 Parameters --------- obj : BinningBase or array_like Can be a binning, numpy-like bins or full physt bins copy : If true, ensure that the returned object is independent
[ "Ensure", "that", "an", "object", "is", "a", "binning" ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L1013-L1029
16,451
janpipek/physt
physt/binnings.py
BinningBase.to_dict
def to_dict(self) -> OrderedDict: """Dictionary representation of the binning schema. This serves as template method, please implement _update_dict """ result = OrderedDict() result["adaptive"] = self._adaptive result["binning_type"] = type(self).__name__ self._update_dict(result) return result
python
def to_dict(self) -> OrderedDict: """Dictionary representation of the binning schema. This serves as template method, please implement _update_dict """ result = OrderedDict() result["adaptive"] = self._adaptive result["binning_type"] = type(self).__name__ self._update_dict(result) return result
[ "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. This serves as template method, please implement _update_dict
[ "Dictionary", "representation", "of", "the", "binning", "schema", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L77-L86
16,452
janpipek/physt
physt/binnings.py
BinningBase.is_regular
def is_regular(self, rtol: float = 1.e-5, atol: float = 1.e-8) -> bool: """Whether all bins have the same width. Parameters ---------- rtol, atol : numpy tolerance parameters """ return np.allclose(np.diff(self.bins[1] - self.bins[0]), 0.0, rtol=rtol, atol=atol)
python
def is_regular(self, rtol: float = 1.e-5, atol: float = 1.e-8) -> bool: """Whether all bins have the same width. Parameters ---------- rtol, atol : numpy tolerance parameters """ return np.allclose(np.diff(self.bins[1] - self.bins[0]), 0.0, rtol=rtol, atol=atol)
[ "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. Parameters ---------- rtol, atol : numpy tolerance parameters
[ "Whether", "all", "bins", "have", "the", "same", "width", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L97-L104
16,453
janpipek/physt
physt/binnings.py
BinningBase.is_consecutive
def is_consecutive(self, rtol: float = 1.e-5, atol: float = 1.e-8) -> bool: """Whether all bins are in a growing order. Parameters ---------- rtol, atol : numpy tolerance parameters """ if self.inconsecutive_allowed: if self._consecutive is None: if self._numpy_bins is not None: self._consecutive = True self._consecutive = is_consecutive(self.bins, rtol, atol) return self._consecutive else: return True
python
def is_consecutive(self, rtol: float = 1.e-5, atol: float = 1.e-8) -> bool: """Whether all bins are in a growing order. Parameters ---------- rtol, atol : numpy tolerance parameters """ if self.inconsecutive_allowed: if self._consecutive is None: if self._numpy_bins is not None: self._consecutive = True self._consecutive = is_consecutive(self.bins, rtol, atol) return self._consecutive else: return True
[ "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", "self", ".", "_consecutive", "=", "is_consecutive", "(", "self", ".", "bins", ",", "rtol", ",", "atol", ")", "return", "self", ".", "_consecutive", "else", ":", "return", "True" ]
Whether all bins are in a growing order. Parameters ---------- rtol, atol : numpy tolerance parameters
[ "Whether", "all", "bins", "are", "in", "a", "growing", "order", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L106-L120
16,454
janpipek/physt
physt/binnings.py
BinningBase.adapt
def adapt(self, other: 'BinningBase'): """Adapt this binning so that it contains all bins of another binning. Parameters ---------- 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: return self._adapt(other)
python
def adapt(self, other: 'BinningBase'): """Adapt this binning so that it contains all bins of another binning. Parameters ---------- 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: return self._adapt(other)
[ "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", ":", "return", "self", ".", "_adapt", "(", "other", ")" ]
Adapt this binning so that it contains all bins of another binning. Parameters ---------- other: BinningBase
[ "Adapt", "this", "binning", "so", "that", "it", "contains", "all", "bins", "of", "another", "binning", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L154-L167
16,455
janpipek/physt
physt/binnings.py
BinningBase.numpy_bins
def numpy_bins(self) -> np.ndarray: """Bins in the numpy format This might not be available for inconsecutive binnings. Returns ------- edges: np.ndarray shape=(bin_count+1,) """ if self._numpy_bins is None: self._numpy_bins = to_numpy_bins(self.bins) return self._numpy_bins
python
def numpy_bins(self) -> np.ndarray: """Bins in the numpy format This might not be available for inconsecutive binnings. Returns ------- edges: np.ndarray shape=(bin_count+1,) """ if self._numpy_bins is None: self._numpy_bins = to_numpy_bins(self.bins) return self._numpy_bins
[ "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 This might not be available for inconsecutive binnings. Returns ------- edges: np.ndarray shape=(bin_count+1,)
[ "Bins", "in", "the", "numpy", "format" ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L200-L212
16,456
janpipek/physt
physt/binnings.py
BinningBase.numpy_bins_with_mask
def numpy_bins_with_mask(self) -> Tuple[np.ndarray, np.ndarray]: """Bins in the numpy format, including the gaps in inconsecutive binnings. Returns ------- edges, mask: np.ndarray See Also -------- bin_utils.to_numpy_bins_with_mask """ bwm = to_numpy_bins_with_mask(self.bins) if not self.includes_right_edge: bwm[0].append(np.inf) return bwm
python
def numpy_bins_with_mask(self) -> Tuple[np.ndarray, np.ndarray]: """Bins in the numpy format, including the gaps in inconsecutive binnings. Returns ------- edges, mask: np.ndarray See Also -------- bin_utils.to_numpy_bins_with_mask """ bwm = to_numpy_bins_with_mask(self.bins) if not self.includes_right_edge: bwm[0].append(np.inf) return bwm
[ "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. Returns ------- edges, mask: np.ndarray See Also -------- bin_utils.to_numpy_bins_with_mask
[ "Bins", "in", "the", "numpy", "format", "including", "the", "gaps", "in", "inconsecutive", "binnings", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L215-L229
16,457
janpipek/physt
physt/binnings.py
StaticBinning.as_static
def as_static(self, copy: bool = True) -> 'StaticBinning': """Convert binning to a static form. Returns ------- StaticBinning A new static binning with a copy of bins. Parameters ---------- copy : if True, returns itself (already satisfying conditions). """ if copy: return StaticBinning(bins=self.bins.copy(), includes_right_edge=self.includes_right_edge) else: return self
python
def as_static(self, copy: bool = True) -> 'StaticBinning': """Convert binning to a static form. Returns ------- StaticBinning A new static binning with a copy of bins. Parameters ---------- copy : if True, returns itself (already satisfying conditions). """ if copy: return StaticBinning(bins=self.bins.copy(), includes_right_edge=self.includes_right_edge) else: return self
[ "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. Returns ------- StaticBinning A new static binning with a copy of bins. Parameters ---------- copy : if True, returns itself (already satisfying conditions).
[ "Convert", "binning", "to", "a", "static", "form", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L319-L335
16,458
janpipek/physt
physt/compat/dask.py
histogram1d
def histogram1d(data, bins=None, *args, **kwargs): """Facade function to create one-dimensional histogram using dask. Parameters ---------- data: dask.DaskArray or array-like See also -------- physt.histogram """ 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 adaptive histograms supported for dask (currently).") kwargs["adaptive"] = True def block_hist(array): return original_h1(array, bins, *args, **kwargs) return _run_dask( name="dask_adaptive1d", data=data, compute=kwargs.pop("compute", True), method=kwargs.pop("dask_method", "threaded"), func=block_hist)
python
def histogram1d(data, bins=None, *args, **kwargs): """Facade function to create one-dimensional histogram using dask. Parameters ---------- data: dask.DaskArray or array-like See also -------- physt.histogram """ 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 adaptive histograms supported for dask (currently).") kwargs["adaptive"] = True def block_hist(array): return original_h1(array, bins, *args, **kwargs) return _run_dask( name="dask_adaptive1d", data=data, compute=kwargs.pop("compute", True), method=kwargs.pop("dask_method", "threaded"), func=block_hist)
[ "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 adaptive histograms supported for dask (currently).\"", ")", "kwargs", "[", "\"adaptive\"", "]", "=", "True", "def", "block_hist", "(", "array", ")", ":", "return", "original_h1", "(", "array", ",", "bins", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_run_dask", "(", "name", "=", "\"dask_adaptive1d\"", ",", "data", "=", "data", ",", "compute", "=", "kwargs", ".", "pop", "(", "\"compute\"", ",", "True", ")", ",", "method", "=", "kwargs", ".", "pop", "(", "\"dask_method\"", ",", "\"threaded\"", ")", ",", "func", "=", "block_hist", ")" ]
Facade function to create one-dimensional histogram using dask. Parameters ---------- data: dask.DaskArray or array-like See also -------- physt.histogram
[ "Facade", "function", "to", "create", "one", "-", "dimensional", "histogram", "using", "dask", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/compat/dask.py#L30-L57
16,459
janpipek/physt
physt/compat/dask.py
histogram2d
def histogram2d(data1, data2, bins=None, *args, **kwargs): """Facade function to create 2D histogram using dask.""" # 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.name, data2.name] if not hasattr(data1, "dask"): data1 = dask.array.from_array(data1, chunks=data1.size() / 100) if not hasattr(data2, "dask"): data2 = dask.array.from_array(data2, chunks=data2.size() / 100) data = dask.array.stack([data1, data2], axis=1) kwargs["dim"] = 2 return histogramdd(data, bins, *args, **kwargs)
python
def histogram2d(data1, data2, bins=None, *args, **kwargs): """Facade function to create 2D histogram using dask.""" # 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.name, data2.name] if not hasattr(data1, "dask"): data1 = dask.array.from_array(data1, chunks=data1.size() / 100) if not hasattr(data2, "dask"): data2 = dask.array.from_array(data2, chunks=data2.size() / 100) data = dask.array.stack([data1, data2], axis=1) kwargs["dim"] = 2 return histogramdd(data, bins, *args, **kwargs)
[ "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", ".", "name", ",", "data2", ".", "name", "]", "if", "not", "hasattr", "(", "data1", ",", "\"dask\"", ")", ":", "data1", "=", "dask", ".", "array", ".", "from_array", "(", "data1", ",", "chunks", "=", "data1", ".", "size", "(", ")", "/", "100", ")", "if", "not", "hasattr", "(", "data2", ",", "\"dask\"", ")", ":", "data2", "=", "dask", ".", "array", ".", "from_array", "(", "data2", ",", "chunks", "=", "data2", ".", "size", "(", ")", "/", "100", ")", "data", "=", "dask", ".", "array", ".", "stack", "(", "[", "data1", ",", "data2", "]", ",", "axis", "=", "1", ")", "kwargs", "[", "\"dim\"", "]", "=", "2", "return", "histogramdd", "(", "data", ",", "bins", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Facade function to create 2D histogram using dask.
[ "Facade", "function", "to", "create", "2D", "histogram", "using", "dask", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/compat/dask.py#L88-L102
16,460
janpipek/physt
physt/util.py
all_subclasses
def all_subclasses(cls: type) -> Tuple[type, ...]: """All subclasses of a class. From: http://stackoverflow.com/a/17246726/2692780 """ subclasses = [] for subclass in cls.__subclasses__(): subclasses.append(subclass) subclasses.extend(all_subclasses(subclass)) return tuple(subclasses)
python
def all_subclasses(cls: type) -> Tuple[type, ...]: """All subclasses of a class. From: http://stackoverflow.com/a/17246726/2692780 """ subclasses = [] for subclass in cls.__subclasses__(): subclasses.append(subclass) subclasses.extend(all_subclasses(subclass)) return tuple(subclasses)
[ "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. From: http://stackoverflow.com/a/17246726/2692780
[ "All", "subclasses", "of", "a", "class", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/util.py#L9-L18
16,461
janpipek/physt
physt/util.py
find_subclass
def find_subclass(base: type, name: str) -> type: """Find a named subclass of a base class. Uses only the class name without namespace. """ class_candidates = [klass for klass in all_subclasses(base) if klass.__name__ == name ] if len(class_candidates) == 0: raise RuntimeError("No \"{0}\" subclass of \"{1}\".".format(base.__name__, name)) elif len(class_candidates) > 1: raise RuntimeError("Multiple \"{0}\" subclasses of \"{1}\".".format(base.__name__, name)) return class_candidates[0]
python
def find_subclass(base: type, name: str) -> type: """Find a named subclass of a base class. Uses only the class name without namespace. """ class_candidates = [klass for klass in all_subclasses(base) if klass.__name__ == name ] if len(class_candidates) == 0: raise RuntimeError("No \"{0}\" subclass of \"{1}\".".format(base.__name__, name)) elif len(class_candidates) > 1: raise RuntimeError("Multiple \"{0}\" subclasses of \"{1}\".".format(base.__name__, name)) return class_candidates[0]
[ "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", "RuntimeError", "(", "\"No \\\"{0}\\\" subclass of \\\"{1}\\\".\"", ".", "format", "(", "base", ".", "__name__", ",", "name", ")", ")", "elif", "len", "(", "class_candidates", ")", ">", "1", ":", "raise", "RuntimeError", "(", "\"Multiple \\\"{0}\\\" subclasses of \\\"{1}\\\".\"", ".", "format", "(", "base", ".", "__name__", ",", "name", ")", ")", "return", "class_candidates", "[", "0", "]" ]
Find a named subclass of a base class. Uses only the class name without namespace.
[ "Find", "a", "named", "subclass", "of", "a", "base", "class", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/util.py#L21-L34
16,462
janpipek/physt
physt/histogram_collection.py
HistogramCollection.add
def add(self, histogram: Histogram1D): """Add a histogram to the collection.""" if self.binning and not self.binning == histogram.binning: raise ValueError("Cannot add histogram with different binning.") self.histograms.append(histogram)
python
def add(self, histogram: Histogram1D): """Add a histogram to the collection.""" if self.binning and not self.binning == histogram.binning: raise ValueError("Cannot add histogram with different binning.") self.histograms.append(histogram)
[ "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.
[ "Add", "a", "histogram", "to", "the", "collection", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_collection.py#L80-L84
16,463
janpipek/physt
physt/histogram_collection.py
HistogramCollection.normalize_bins
def normalize_bins(self, inplace: bool = False) -> "HistogramCollection": """Normalize each bin in the collection so that the sum is 1.0 for each bin. Note: If a bin is zero in all collections, the result will be inf. """ col = self if inplace else self.copy() sums = self.sum().frequencies for h in col.histograms: h.set_dtype(float) h._frequencies /= sums h._errors2 /= sums ** 2 # TODO: Does this make sense? return col
python
def normalize_bins(self, inplace: bool = False) -> "HistogramCollection": """Normalize each bin in the collection so that the sum is 1.0 for each bin. Note: If a bin is zero in all collections, the result will be inf. """ col = self if inplace else self.copy() sums = self.sum().frequencies for h in col.histograms: h.set_dtype(float) h._frequencies /= sums h._errors2 /= sums ** 2 # TODO: Does this make sense? return col
[ "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", "h", ".", "_errors2", "/=", "sums", "**", "2", "# TODO: Does this make sense?", "return", "col" ]
Normalize each bin in the collection so that the sum is 1.0 for each bin. Note: If a bin is zero in all collections, the result will be inf.
[ "Normalize", "each", "bin", "in", "the", "collection", "so", "that", "the", "sum", "is", "1", ".", "0", "for", "each", "bin", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_collection.py#L113-L124
16,464
janpipek/physt
physt/histogram_collection.py
HistogramCollection.multi_h1
def multi_h1(cls, a_dict: Dict[str, Any], bins=None, **kwargs) -> "HistogramCollection": """Create a collection from multiple datasets.""" from physt.binnings import calculate_bins mega_values = np.concatenate(list(a_dict.values())) binning = calculate_bins(mega_values, bins, **kwargs) title = kwargs.pop("title", None) name = kwargs.pop("name", None) collection = HistogramCollection(binning=binning, title=title, name=name) for key, value in a_dict.items(): collection.create(key, value) return collection
python
def multi_h1(cls, a_dict: Dict[str, Any], bins=None, **kwargs) -> "HistogramCollection": """Create a collection from multiple datasets.""" from physt.binnings import calculate_bins mega_values = np.concatenate(list(a_dict.values())) binning = calculate_bins(mega_values, bins, **kwargs) title = kwargs.pop("title", None) name = kwargs.pop("name", None) collection = HistogramCollection(binning=binning, title=title, name=name) for key, value in a_dict.items(): collection.create(key, value) return collection
[ "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", ")", "title", "=", "kwargs", ".", "pop", "(", "\"title\"", ",", "None", ")", "name", "=", "kwargs", ".", "pop", "(", "\"name\"", ",", "None", ")", "collection", "=", "HistogramCollection", "(", "binning", "=", "binning", ",", "title", "=", "title", ",", "name", "=", "name", ")", "for", "key", ",", "value", "in", "a_dict", ".", "items", "(", ")", ":", "collection", ".", "create", "(", "key", ",", "value", ")", "return", "collection" ]
Create a collection from multiple datasets.
[ "Create", "a", "collection", "from", "multiple", "datasets", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_collection.py#L142-L154
16,465
janpipek/physt
physt/histogram_collection.py
HistogramCollection.to_json
def to_json(self, path: Optional[str] = None, **kwargs) -> str: """Convert to JSON representation. Parameters ---------- path: Where to write the JSON. Returns ------- The JSON representation. """ from .io import save_json return save_json(self, path, **kwargs)
python
def to_json(self, path: Optional[str] = None, **kwargs) -> str: """Convert to JSON representation. Parameters ---------- path: Where to write the JSON. Returns ------- The JSON representation. """ from .io import save_json return save_json(self, path, **kwargs)
[ "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. Parameters ---------- path: Where to write the JSON. Returns ------- The JSON representation.
[ "Convert", "to", "JSON", "representation", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_collection.py#L171-L183
16,466
janpipek/physt
physt/histogram_base.py
HistogramBase._get_axis
def _get_axis(self, name_or_index: AxisIdentifier) -> int: """Get a zero-based index of an axis and check its existence.""" # 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}".format(self.ndim-1)) return name_or_index elif isinstance(name_or_index, str): if name_or_index not in self.axis_names: named_axes = [name for name in self.axis_names if name] raise ValueError("No axis with such name: {0}, available names: {1}. In most places, you can also use numbers." .format(name_or_index, ", ".join(named_axes))) return self.axis_names.index(name_or_index) else: raise TypeError("Argument of type {0} not understood, int or str expected.".format(type(name_or_index)))
python
def _get_axis(self, name_or_index: AxisIdentifier) -> int: """Get a zero-based index of an axis and check its existence.""" # 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}".format(self.ndim-1)) return name_or_index elif isinstance(name_or_index, str): if name_or_index not in self.axis_names: named_axes = [name for name in self.axis_names if name] raise ValueError("No axis with such name: {0}, available names: {1}. In most places, you can also use numbers." .format(name_or_index, ", ".join(named_axes))) return self.axis_names.index(name_or_index) else: raise TypeError("Argument of type {0} not understood, int or str expected.".format(type(name_or_index)))
[ "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}\"", ".", "format", "(", "self", ".", "ndim", "-", "1", ")", ")", "return", "name_or_index", "elif", "isinstance", "(", "name_or_index", ",", "str", ")", ":", "if", "name_or_index", "not", "in", "self", ".", "axis_names", ":", "named_axes", "=", "[", "name", "for", "name", "in", "self", ".", "axis_names", "if", "name", "]", "raise", "ValueError", "(", "\"No axis with such name: {0}, available names: {1}. In most places, you can also use numbers.\"", ".", "format", "(", "name_or_index", ",", "\", \"", ".", "join", "(", "named_axes", ")", ")", ")", "return", "self", ".", "axis_names", ".", "index", "(", "name_or_index", ")", "else", ":", "raise", "TypeError", "(", "\"Argument of type {0} not understood, int or str expected.\"", ".", "format", "(", "type", "(", "name_or_index", ")", ")", ")" ]
Get a zero-based index of an axis and check its existence.
[ "Get", "a", "zero", "-", "based", "index", "of", "an", "axis", "and", "check", "its", "existence", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_base.py#L177-L191
16,467
janpipek/physt
physt/histogram_base.py
HistogramBase.shape
def shape(self) -> Tuple[int, ...]: """Shape of histogram's data. Returns ------- One-element tuple with the number of bins along each axis. """ return tuple(bins.bin_count for bins in self._binnings)
python
def shape(self) -> Tuple[int, ...]: """Shape of histogram's data. Returns ------- One-element tuple with the number of bins along each axis. """ return tuple(bins.bin_count for bins in self._binnings)
[ "def", "shape", "(", "self", ")", "->", "Tuple", "[", "int", ",", "...", "]", ":", "return", "tuple", "(", "bins", ".", "bin_count", "for", "bins", "in", "self", ".", "_binnings", ")" ]
Shape of histogram's data. Returns ------- One-element tuple with the number of bins along each axis.
[ "Shape", "of", "histogram", "s", "data", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_base.py#L194-L201
16,468
janpipek/physt
physt/histogram_base.py
HistogramBase.set_dtype
def set_dtype(self, value, check: bool = True): """Change data type of the bin contents. Allowed conversions: - from integral to float types - between the same category of type (float/integer) - from float types to integer if weights are trivial Parameters ---------- value: np.dtype or something convertible to it. check: bool If True (default), all values are checked against the limits """ # 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): pass # Ok elif check: if np.issubdtype(value, np.integer): if self.dtype.kind == "f": for array in (self._frequencies, self._errors2): if np.any(array % 1.0): raise RuntimeError("Data contain non-integer values.") for array in (self._frequencies, self._errors2): if np.any((array > type_info.max) | (array < type_info.min)): raise RuntimeError("Data contain values outside the specified range.") self._dtype = value self._frequencies = self._frequencies.astype(value) self._errors2 = self._errors2.astype(value) self._missed = self._missed.astype(value)
python
def set_dtype(self, value, check: bool = True): """Change data type of the bin contents. Allowed conversions: - from integral to float types - between the same category of type (float/integer) - from float types to integer if weights are trivial Parameters ---------- value: np.dtype or something convertible to it. check: bool If True (default), all values are checked against the limits """ # 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): pass # Ok elif check: if np.issubdtype(value, np.integer): if self.dtype.kind == "f": for array in (self._frequencies, self._errors2): if np.any(array % 1.0): raise RuntimeError("Data contain non-integer values.") for array in (self._frequencies, self._errors2): if np.any((array > type_info.max) | (array < type_info.min)): raise RuntimeError("Data contain values outside the specified range.") self._dtype = value self._frequencies = self._frequencies.astype(value) self._errors2 = self._errors2.astype(value) self._missed = self._missed.astype(value)
[ "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", ")", ":", "pass", "# Ok", "elif", "check", ":", "if", "np", ".", "issubdtype", "(", "value", ",", "np", ".", "integer", ")", ":", "if", "self", ".", "dtype", ".", "kind", "==", "\"f\"", ":", "for", "array", "in", "(", "self", ".", "_frequencies", ",", "self", ".", "_errors2", ")", ":", "if", "np", ".", "any", "(", "array", "%", "1.0", ")", ":", "raise", "RuntimeError", "(", "\"Data contain non-integer values.\"", ")", "for", "array", "in", "(", "self", ".", "_frequencies", ",", "self", ".", "_errors2", ")", ":", "if", "np", ".", "any", "(", "(", "array", ">", "type_info", ".", "max", ")", "|", "(", "array", "<", "type_info", ".", "min", ")", ")", ":", "raise", "RuntimeError", "(", "\"Data contain values outside the specified range.\"", ")", "self", ".", "_dtype", "=", "value", "self", ".", "_frequencies", "=", "self", ".", "_frequencies", ".", "astype", "(", "value", ")", "self", ".", "_errors2", "=", "self", ".", "_errors2", ".", "astype", "(", "value", ")", "self", ".", "_missed", "=", "self", ".", "_missed", ".", "astype", "(", "value", ")" ]
Change data type of the bin contents. Allowed conversions: - from integral to float types - between the same category of type (float/integer) - from float types to integer if weights are trivial Parameters ---------- value: np.dtype or something convertible to it. check: bool If True (default), all values are checked against the limits
[ "Change", "data", "type", "of", "the", "bin", "contents", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_base.py#L244-L278
16,469
janpipek/physt
physt/histogram_base.py
HistogramBase._coerce_dtype
def _coerce_dtype(self, other_dtype): """Possibly change the bin content type to allow correct operations with other operand. Parameters ---------- other_dtype : np.dtype or type """ 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: self.set_dtype(new_dtype)
python
def _coerce_dtype(self, other_dtype): """Possibly change the bin content type to allow correct operations with other operand. Parameters ---------- other_dtype : np.dtype or type """ 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: self.set_dtype(new_dtype)
[ "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", ":", "self", ".", "set_dtype", "(", "new_dtype", ")" ]
Possibly change the bin content type to allow correct operations with other operand. Parameters ---------- other_dtype : np.dtype or type
[ "Possibly", "change", "the", "bin", "content", "type", "to", "allow", "correct", "operations", "with", "other", "operand", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_base.py#L282-L294
16,470
janpipek/physt
physt/histogram_base.py
HistogramBase.normalize
def normalize(self, inplace: bool = False, percent: bool = False) -> "HistogramBase": """Normalize the histogram, so that the total weight is equal to 1. Parameters ---------- inplace: If True, updates itself. If False (default), returns copy percent: If True, normalizes to percent instead of 1. Default: False Returns ------- HistogramBase : either modified copy or self See also -------- densities HistogramND.partial_normalize """ if inplace: self /= self.total * (.01 if percent else 1) return self else: return self / self.total * (100 if percent else 1)
python
def normalize(self, inplace: bool = False, percent: bool = False) -> "HistogramBase": """Normalize the histogram, so that the total weight is equal to 1. Parameters ---------- inplace: If True, updates itself. If False (default), returns copy percent: If True, normalizes to percent instead of 1. Default: False Returns ------- HistogramBase : either modified copy or self See also -------- densities HistogramND.partial_normalize """ if inplace: self /= self.total * (.01 if percent else 1) return self else: return self / self.total * (100 if percent else 1)
[ "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. Parameters ---------- inplace: If True, updates itself. If False (default), returns copy percent: If True, normalizes to percent instead of 1. Default: False Returns ------- HistogramBase : either modified copy or self See also -------- densities HistogramND.partial_normalize
[ "Normalize", "the", "histogram", "so", "that", "the", "total", "weight", "is", "equal", "to", "1", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_base.py#L314-L335
16,471
janpipek/physt
physt/histogram_base.py
HistogramBase._change_binning
def _change_binning(self, new_binning, bin_map: Iterable[Tuple[int, int]], axis: int = 0): """Set new binnning and update the bin contents according to a map. Fills frequencies and errors with 0. It's the caller's responsibility to provide correct binning and map. Parameters ---------- new_binning: physt.binnings.BinningBase bin_map: Iterable[tuple] tuples contain bin indices (old, new) axis: int What axis does the binning describe(0..ndim-1) """ 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.bin_count, bin_map, axis) self._binnings[axis] = new_binning
python
def _change_binning(self, new_binning, bin_map: Iterable[Tuple[int, int]], axis: int = 0): """Set new binnning and update the bin contents according to a map. Fills frequencies and errors with 0. It's the caller's responsibility to provide correct binning and map. Parameters ---------- new_binning: physt.binnings.BinningBase bin_map: Iterable[tuple] tuples contain bin indices (old, new) axis: int What axis does the binning describe(0..ndim-1) """ 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.bin_count, bin_map, axis) self._binnings[axis] = new_binning
[ "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", ".", "bin_count", ",", "bin_map", ",", "axis", ")", "self", ".", "_binnings", "[", "axis", "]", "=", "new_binning" ]
Set new binnning and update the bin contents according to a map. Fills frequencies and errors with 0. It's the caller's responsibility to provide correct binning and map. Parameters ---------- new_binning: physt.binnings.BinningBase bin_map: Iterable[tuple] tuples contain bin indices (old, new) axis: int What axis does the binning describe(0..ndim-1)
[ "Set", "new", "binnning", "and", "update", "the", "bin", "contents", "according", "to", "a", "map", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_base.py#L386-L404
16,472
janpipek/physt
physt/histogram_base.py
HistogramBase._reshape_data
def _reshape_data(self, new_size, bin_map, axis=0): """Reshape data to match new binning schema. Fills frequencies and errors with 0. Parameters ---------- new_size: int bin_map: Iterable[(old, new)] or int or None If None, we can keep the data unchanged. If int, it is offset by which to shift the data (can be 0) If iterable, pairs specify which old bin should go into which new bin axis: int On which axis to apply """ 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.dtype) new_errors2 = np.zeros(new_shape, dtype=self._frequencies.dtype) self._apply_bin_map( old_frequencies=self._frequencies, new_frequencies=new_frequencies, old_errors2=self._errors2, new_errors2=new_errors2, bin_map=bin_map, axis=axis) self._frequencies = new_frequencies self._errors2 = new_errors2
python
def _reshape_data(self, new_size, bin_map, axis=0): """Reshape data to match new binning schema. Fills frequencies and errors with 0. Parameters ---------- new_size: int bin_map: Iterable[(old, new)] or int or None If None, we can keep the data unchanged. If int, it is offset by which to shift the data (can be 0) If iterable, pairs specify which old bin should go into which new bin axis: int On which axis to apply """ 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.dtype) new_errors2 = np.zeros(new_shape, dtype=self._frequencies.dtype) self._apply_bin_map( old_frequencies=self._frequencies, new_frequencies=new_frequencies, old_errors2=self._errors2, new_errors2=new_errors2, bin_map=bin_map, axis=axis) self._frequencies = new_frequencies self._errors2 = new_errors2
[ "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", ".", "dtype", ")", "new_errors2", "=", "np", ".", "zeros", "(", "new_shape", ",", "dtype", "=", "self", ".", "_frequencies", ".", "dtype", ")", "self", ".", "_apply_bin_map", "(", "old_frequencies", "=", "self", ".", "_frequencies", ",", "new_frequencies", "=", "new_frequencies", ",", "old_errors2", "=", "self", ".", "_errors2", ",", "new_errors2", "=", "new_errors2", ",", "bin_map", "=", "bin_map", ",", "axis", "=", "axis", ")", "self", ".", "_frequencies", "=", "new_frequencies", "self", ".", "_errors2", "=", "new_errors2" ]
Reshape data to match new binning schema. Fills frequencies and errors with 0. Parameters ---------- new_size: int bin_map: Iterable[(old, new)] or int or None If None, we can keep the data unchanged. If int, it is offset by which to shift the data (can be 0) If iterable, pairs specify which old bin should go into which new bin axis: int On which axis to apply
[ "Reshape", "data", "to", "match", "new", "binning", "schema", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_base.py#L455-L482
16,473
janpipek/physt
physt/histogram_base.py
HistogramBase._apply_bin_map
def _apply_bin_map(self, old_frequencies, new_frequencies, old_errors2, new_errors2, bin_map, axis=0): """Fill new data arrays using a map. Parameters ---------- old_frequencies : np.ndarray Source of frequencies data new_frequencies : np.ndarray Target of frequencies data old_errors2 : np.ndarray Source of errors data new_errors2 : np.ndarray Target of errors data bin_map: Iterable[(old, new)] or int or None As in _reshape_data axis: int On which axis to apply See also -------- HistogramBase._reshape_data """ if old_frequencies is not None and old_frequencies.shape[axis] > 0: if isinstance(bin_map, int): new_index = [slice(None) for i in range(self.ndim)] new_index[axis] = slice(bin_map, bin_map + old_frequencies.shape[axis]) new_frequencies[tuple(new_index)] += old_frequencies new_errors2[tuple(new_index)] += old_errors2 else: for (old, new) in bin_map: # Generic enough new_index = [slice(None) for i in range(self.ndim)] new_index[axis] = new old_index = [slice(None) for i in range(self.ndim)] old_index[axis] = old new_frequencies[tuple(new_index)] += old_frequencies[tuple(old_index)] new_errors2[tuple(new_index)] += old_errors2[tuple(old_index)]
python
def _apply_bin_map(self, old_frequencies, new_frequencies, old_errors2, new_errors2, bin_map, axis=0): """Fill new data arrays using a map. Parameters ---------- old_frequencies : np.ndarray Source of frequencies data new_frequencies : np.ndarray Target of frequencies data old_errors2 : np.ndarray Source of errors data new_errors2 : np.ndarray Target of errors data bin_map: Iterable[(old, new)] or int or None As in _reshape_data axis: int On which axis to apply See also -------- HistogramBase._reshape_data """ if old_frequencies is not None and old_frequencies.shape[axis] > 0: if isinstance(bin_map, int): new_index = [slice(None) for i in range(self.ndim)] new_index[axis] = slice(bin_map, bin_map + old_frequencies.shape[axis]) new_frequencies[tuple(new_index)] += old_frequencies new_errors2[tuple(new_index)] += old_errors2 else: for (old, new) in bin_map: # Generic enough new_index = [slice(None) for i in range(self.ndim)] new_index[axis] = new old_index = [slice(None) for i in range(self.ndim)] old_index[axis] = old new_frequencies[tuple(new_index)] += old_frequencies[tuple(old_index)] new_errors2[tuple(new_index)] += old_errors2[tuple(old_index)]
[ "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_index", "=", "[", "slice", "(", "None", ")", "for", "i", "in", "range", "(", "self", ".", "ndim", ")", "]", "new_index", "[", "axis", "]", "=", "slice", "(", "bin_map", ",", "bin_map", "+", "old_frequencies", ".", "shape", "[", "axis", "]", ")", "new_frequencies", "[", "tuple", "(", "new_index", ")", "]", "+=", "old_frequencies", "new_errors2", "[", "tuple", "(", "new_index", ")", "]", "+=", "old_errors2", "else", ":", "for", "(", "old", ",", "new", ")", "in", "bin_map", ":", "# Generic enough", "new_index", "=", "[", "slice", "(", "None", ")", "for", "i", "in", "range", "(", "self", ".", "ndim", ")", "]", "new_index", "[", "axis", "]", "=", "new", "old_index", "=", "[", "slice", "(", "None", ")", "for", "i", "in", "range", "(", "self", ".", "ndim", ")", "]", "old_index", "[", "axis", "]", "=", "old", "new_frequencies", "[", "tuple", "(", "new_index", ")", "]", "+=", "old_frequencies", "[", "tuple", "(", "old_index", ")", "]", "new_errors2", "[", "tuple", "(", "new_index", ")", "]", "+=", "old_errors2", "[", "tuple", "(", "old_index", ")", "]" ]
Fill new data arrays using a map. Parameters ---------- old_frequencies : np.ndarray Source of frequencies data new_frequencies : np.ndarray Target of frequencies data old_errors2 : np.ndarray Source of errors data new_errors2 : np.ndarray Target of errors data bin_map: Iterable[(old, new)] or int or None As in _reshape_data axis: int On which axis to apply See also -------- HistogramBase._reshape_data
[ "Fill", "new", "data", "arrays", "using", "a", "map", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_base.py#L484-L520
16,474
janpipek/physt
physt/histogram_base.py
HistogramBase.has_same_bins
def has_same_bins(self, other: "HistogramBase") -> bool: """Whether two histograms share the same binning.""" 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.ndim): if not np.allclose(self.bins[i], other.bins[i]): return False return True
python
def has_same_bins(self, other: "HistogramBase") -> bool: """Whether two histograms share the same binning.""" 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.ndim): if not np.allclose(self.bins[i], other.bins[i]): return False return True
[ "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", ".", "ndim", ")", ":", "if", "not", "np", ".", "allclose", "(", "self", ".", "bins", "[", "i", "]", ",", "other", ".", "bins", "[", "i", "]", ")", ":", "return", "False", "return", "True" ]
Whether two histograms share the same binning.
[ "Whether", "two", "histograms", "share", "the", "same", "binning", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_base.py#L522-L532
16,475
janpipek/physt
physt/histogram_base.py
HistogramBase.copy
def copy(self, include_frequencies: bool = True) -> "HistogramBase": """Copy the histogram. Parameters ---------- include_frequencies : If false, all frequencies are set to zero. """ if include_frequencies: frequencies = np.copy(self.frequencies) missed = self._missed.copy() errors2 = np.copy(self.errors2) stats = self._stats or None else: frequencies = np.zeros_like(self._frequencies) errors2 = np.zeros_like(self._errors2) missed = np.zeros_like(self._missed) stats = None a_copy = self.__class__.__new__(self.__class__) a_copy._binnings = [binning.copy() for binning in self._binnings] a_copy._dtype = self.dtype a_copy._frequencies = frequencies a_copy._errors2 = errors2 a_copy._meta_data = self._meta_data.copy() a_copy.keep_missed = self.keep_missed a_copy._missed = missed a_copy._stats = stats return a_copy
python
def copy(self, include_frequencies: bool = True) -> "HistogramBase": """Copy the histogram. Parameters ---------- include_frequencies : If false, all frequencies are set to zero. """ if include_frequencies: frequencies = np.copy(self.frequencies) missed = self._missed.copy() errors2 = np.copy(self.errors2) stats = self._stats or None else: frequencies = np.zeros_like(self._frequencies) errors2 = np.zeros_like(self._errors2) missed = np.zeros_like(self._missed) stats = None a_copy = self.__class__.__new__(self.__class__) a_copy._binnings = [binning.copy() for binning in self._binnings] a_copy._dtype = self.dtype a_copy._frequencies = frequencies a_copy._errors2 = errors2 a_copy._meta_data = self._meta_data.copy() a_copy.keep_missed = self.keep_missed a_copy._missed = missed a_copy._stats = stats return a_copy
[ "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", ".", "_stats", "or", "None", "else", ":", "frequencies", "=", "np", ".", "zeros_like", "(", "self", ".", "_frequencies", ")", "errors2", "=", "np", ".", "zeros_like", "(", "self", ".", "_errors2", ")", "missed", "=", "np", ".", "zeros_like", "(", "self", ".", "_missed", ")", "stats", "=", "None", "a_copy", "=", "self", ".", "__class__", ".", "__new__", "(", "self", ".", "__class__", ")", "a_copy", ".", "_binnings", "=", "[", "binning", ".", "copy", "(", ")", "for", "binning", "in", "self", ".", "_binnings", "]", "a_copy", ".", "_dtype", "=", "self", ".", "dtype", "a_copy", ".", "_frequencies", "=", "frequencies", "a_copy", ".", "_errors2", "=", "errors2", "a_copy", ".", "_meta_data", "=", "self", ".", "_meta_data", ".", "copy", "(", ")", "a_copy", ".", "keep_missed", "=", "self", ".", "keep_missed", "a_copy", ".", "_missed", "=", "missed", "a_copy", ".", "_stats", "=", "stats", "return", "a_copy" ]
Copy the histogram. Parameters ---------- include_frequencies : If false, all frequencies are set to zero.
[ "Copy", "the", "histogram", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_base.py#L534-L560
16,476
janpipek/physt
physt/histogram_base.py
HistogramBase.to_dict
def to_dict(self) -> OrderedDict: """Dictionary with all data in the histogram. This is used for export into various formats (e.g. JSON) If a descendant class needs to update the dictionary in some way (put some more information), override the _update_dict method. """ result = OrderedDict() result["histogram_type"] = type(self).__name__ result["binnings"] = [binning.to_dict() for binning in self._binnings] result["frequencies"] = self.frequencies.tolist() result["dtype"] = str(np.dtype(self.dtype)) # TODO: Optimize for _errors == _frequencies result["errors2"] = self.errors2.tolist() result["meta_data"] = self._meta_data result["missed"] = self._missed.tolist() result["missed_keep"] = self.keep_missed self._update_dict(result) return result
python
def to_dict(self) -> OrderedDict: """Dictionary with all data in the histogram. This is used for export into various formats (e.g. JSON) If a descendant class needs to update the dictionary in some way (put some more information), override the _update_dict method. """ result = OrderedDict() result["histogram_type"] = type(self).__name__ result["binnings"] = [binning.to_dict() for binning in self._binnings] result["frequencies"] = self.frequencies.tolist() result["dtype"] = str(np.dtype(self.dtype)) # TODO: Optimize for _errors == _frequencies result["errors2"] = self.errors2.tolist() result["meta_data"] = self._meta_data result["missed"] = self._missed.tolist() result["missed_keep"] = self.keep_missed self._update_dict(result) return result
[ "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", "(", ")", "result", "[", "\"dtype\"", "]", "=", "str", "(", "np", ".", "dtype", "(", "self", ".", "dtype", ")", ")", "# TODO: Optimize for _errors == _frequencies", "result", "[", "\"errors2\"", "]", "=", "self", ".", "errors2", ".", "tolist", "(", ")", "result", "[", "\"meta_data\"", "]", "=", "self", ".", "_meta_data", "result", "[", "\"missed\"", "]", "=", "self", ".", "_missed", ".", "tolist", "(", ")", "result", "[", "\"missed_keep\"", "]", "=", "self", ".", "keep_missed", "self", ".", "_update_dict", "(", "result", ")", "return", "result" ]
Dictionary with all data in the histogram. This is used for export into various formats (e.g. JSON) If a descendant class needs to update the dictionary in some way (put some more information), override the _update_dict method.
[ "Dictionary", "with", "all", "data", "in", "the", "histogram", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_base.py#L619-L638
16,477
janpipek/physt
physt/histogram_base.py
HistogramBase._merge_meta_data
def _merge_meta_data(cls, first: "HistogramBase", second: "HistogramBase") -> dict: """Merge meta data of two histograms leaving only the equal values. (Used in addition and subtraction) """ keys = set(first._meta_data.keys()) keys = keys.union(set(second._meta_data.keys())) return {key: (first._meta_data.get(key, None) if first._meta_data.get(key, None) == second._meta_data.get(key, None) else None) for key in keys}
python
def _merge_meta_data(cls, first: "HistogramBase", second: "HistogramBase") -> dict: """Merge meta data of two histograms leaving only the equal values. (Used in addition and subtraction) """ keys = set(first._meta_data.keys()) keys = keys.union(set(second._meta_data.keys())) return {key: (first._meta_data.get(key, None) if first._meta_data.get(key, None) == second._meta_data.get(key, None) else None) for key in keys}
[ "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", ".", "_meta_data", ".", "get", "(", "key", ",", "None", ")", "==", "second", ".", "_meta_data", ".", "get", "(", "key", ",", "None", ")", "else", "None", ")", "for", "key", "in", "keys", "}" ]
Merge meta data of two histograms leaving only the equal values. (Used in addition and subtraction)
[ "Merge", "meta", "data", "of", "two", "histograms", "leaving", "only", "the", "equal", "values", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_base.py#L816-L825
16,478
janpipek/physt
physt/histogram1d.py
Histogram1D.mean
def mean(self) -> Optional[float]: """Statistical mean of all values entered into histogram. This number is precise, because we keep the necessary data separate from bin contents. """ 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
python
def mean(self) -> Optional[float]: """Statistical mean of all values entered into histogram. This number is precise, because we keep the necessary data separate from bin contents. """ 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
[ "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. This number is precise, because we keep the necessary data separate from bin contents.
[ "Statistical", "mean", "of", "all", "values", "entered", "into", "histogram", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram1d.py#L208-L220
16,479
janpipek/physt
physt/histogram1d.py
Histogram1D.std
def std(self) -> Optional[float]: #, ddof=0): """Standard deviation of all values entered into histogram. This number is precise, because we keep the necessary data separate from bin contents. Returns ------- float """ # TODO: Add DOF if self._stats: return np.sqrt(self.variance()) else: return None
python
def std(self) -> Optional[float]: #, ddof=0): """Standard deviation of all values entered into histogram. This number is precise, because we keep the necessary data separate from bin contents. Returns ------- float """ # TODO: Add DOF if self._stats: return np.sqrt(self.variance()) else: return None
[ "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. This number is precise, because we keep the necessary data separate from bin contents. Returns ------- float
[ "Standard", "deviation", "of", "all", "values", "entered", "into", "histogram", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram1d.py#L222-L236
16,480
janpipek/physt
physt/histogram1d.py
Histogram1D.variance
def variance(self) -> Optional[float]: #, ddof: int = 0) -> float: """Statistical variance of all values entered into histogram. This number is precise, because we keep the necessary data separate from bin contents. Returns ------- 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: return (self._stats["sum2"] - self._stats["sum"] ** 2 / self.total) / self.total else: return np.nan else: return None
python
def variance(self) -> Optional[float]: #, ddof: int = 0) -> float: """Statistical variance of all values entered into histogram. This number is precise, because we keep the necessary data separate from bin contents. Returns ------- 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: return (self._stats["sum2"] - self._stats["sum"] ** 2 / self.total) / self.total else: return np.nan else: return None
[ "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", ":", "return", "(", "self", ".", "_stats", "[", "\"sum2\"", "]", "-", "self", ".", "_stats", "[", "\"sum\"", "]", "**", "2", "/", "self", ".", "total", ")", "/", "self", ".", "total", "else", ":", "return", "np", ".", "nan", "else", ":", "return", "None" ]
Statistical variance of all values entered into histogram. This number is precise, because we keep the necessary data separate from bin contents. Returns ------- float
[ "Statistical", "variance", "of", "all", "values", "entered", "into", "histogram", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram1d.py#L238-L256
16,481
janpipek/physt
physt/histogram1d.py
Histogram1D.find_bin
def find_bin(self, value): """Index of bin corresponding to a value. Parameters ---------- value: float Value to be searched for. Returns ------- int index of bin to which value belongs (-1=underflow, N=overflow, None=not found - inconsecutive) """ 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 else: return self.bin_count elif value < self.bin_right_edges[ixbin - 1]: return ixbin - 1 elif ixbin == self.bin_count: return self.bin_count else: return None
python
def find_bin(self, value): """Index of bin corresponding to a value. Parameters ---------- value: float Value to be searched for. Returns ------- int index of bin to which value belongs (-1=underflow, N=overflow, None=not found - inconsecutive) """ 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 else: return self.bin_count elif value < self.bin_right_edges[ixbin - 1]: return ixbin - 1 elif ixbin == self.bin_count: return self.bin_count else: return None
[ "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", "else", ":", "return", "self", ".", "bin_count", "elif", "value", "<", "self", ".", "bin_right_edges", "[", "ixbin", "-", "1", "]", ":", "return", "ixbin", "-", "1", "elif", "ixbin", "==", "self", ".", "bin_count", ":", "return", "self", ".", "bin_count", "else", ":", "return", "None" ]
Index of bin corresponding to a value. Parameters ---------- value: float Value to be searched for. Returns ------- int index of bin to which value belongs (-1=underflow, N=overflow, None=not found - inconsecutive)
[ "Index", "of", "bin", "corresponding", "to", "a", "value", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram1d.py#L342-L369
16,482
janpipek/physt
physt/histogram1d.py
Histogram1D.fill
def fill(self, value, weight=1): """Update histogram with a new value. Parameters ---------- value: float Value to be added. weight: float, optional Weight assigned to the value. Returns ------- int index of bin which was incremented (-1=underflow, N=overflow, None=not found) Note: If a gap in unconsecutive bins is matched, underflow & overflow are not valid anymore. Note: Name was selected because of the eponymous method in ROOT """ 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(value) if ixbin is None: self.overflow = np.nan self.underflow = np.nan elif ixbin == -1 and self.keep_missed: self.underflow += weight elif ixbin == self.bin_count and self.keep_missed: self.overflow += weight else: self._frequencies[ixbin] += weight self._errors2[ixbin] += weight ** 2 if self._stats: self._stats["sum"] += weight * value self._stats["sum2"] += weight * value ** 2 return ixbin
python
def fill(self, value, weight=1): """Update histogram with a new value. Parameters ---------- value: float Value to be added. weight: float, optional Weight assigned to the value. Returns ------- int index of bin which was incremented (-1=underflow, N=overflow, None=not found) Note: If a gap in unconsecutive bins is matched, underflow & overflow are not valid anymore. Note: Name was selected because of the eponymous method in ROOT """ 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(value) if ixbin is None: self.overflow = np.nan self.underflow = np.nan elif ixbin == -1 and self.keep_missed: self.underflow += weight elif ixbin == self.bin_count and self.keep_missed: self.overflow += weight else: self._frequencies[ixbin] += weight self._errors2[ixbin] += weight ** 2 if self._stats: self._stats["sum"] += weight * value self._stats["sum2"] += weight * value ** 2 return ixbin
[ "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", "(", "value", ")", "if", "ixbin", "is", "None", ":", "self", ".", "overflow", "=", "np", ".", "nan", "self", ".", "underflow", "=", "np", ".", "nan", "elif", "ixbin", "==", "-", "1", "and", "self", ".", "keep_missed", ":", "self", ".", "underflow", "+=", "weight", "elif", "ixbin", "==", "self", ".", "bin_count", "and", "self", ".", "keep_missed", ":", "self", ".", "overflow", "+=", "weight", "else", ":", "self", ".", "_frequencies", "[", "ixbin", "]", "+=", "weight", "self", ".", "_errors2", "[", "ixbin", "]", "+=", "weight", "**", "2", "if", "self", ".", "_stats", ":", "self", ".", "_stats", "[", "\"sum\"", "]", "+=", "weight", "*", "value", "self", ".", "_stats", "[", "\"sum2\"", "]", "+=", "weight", "*", "value", "**", "2", "return", "ixbin" ]
Update histogram with a new value. Parameters ---------- value: float Value to be added. weight: float, optional Weight assigned to the value. Returns ------- int index of bin which was incremented (-1=underflow, N=overflow, None=not found) Note: If a gap in unconsecutive bins is matched, underflow & overflow are not valid anymore. Note: Name was selected because of the eponymous method in ROOT
[ "Update", "histogram", "with", "a", "new", "value", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram1d.py#L371-L408
16,483
janpipek/physt
physt/histogram1d.py
Histogram1D.fill_n
def fill_n(self, values, weights=None, dropna: bool = True): """Update histograms with a set of values. Parameters ---------- values: array_like weights: Optional[array_like] drop_na: Optional[bool] If true (default), all nan's are skipped. """ # TODO: Unify with HistogramBase values = np.asarray(values) if dropna: values = values[~np.isnan(values)] if self._binning.is_adaptive(): map = self._binning.force_bin_existence(values) self._reshape_data(self._binning.bin_count, map) if weights: weights = np.asarray(weights) self._coerce_dtype(weights.dtype) (frequencies, errors2, underflow, overflow, stats) = \ calculate_frequencies(values, self._binning, dtype=self.dtype, weights=weights, validate_bins=False) self._frequencies += frequencies self._errors2 += errors2 # TODO: check that adaptive does not produce under-/over-flows? if self.keep_missed: self.underflow += underflow self.overflow += overflow if self._stats: for key in self._stats: self._stats[key] += stats.get(key, 0.0)
python
def fill_n(self, values, weights=None, dropna: bool = True): """Update histograms with a set of values. Parameters ---------- values: array_like weights: Optional[array_like] drop_na: Optional[bool] If true (default), all nan's are skipped. """ # TODO: Unify with HistogramBase values = np.asarray(values) if dropna: values = values[~np.isnan(values)] if self._binning.is_adaptive(): map = self._binning.force_bin_existence(values) self._reshape_data(self._binning.bin_count, map) if weights: weights = np.asarray(weights) self._coerce_dtype(weights.dtype) (frequencies, errors2, underflow, overflow, stats) = \ calculate_frequencies(values, self._binning, dtype=self.dtype, weights=weights, validate_bins=False) self._frequencies += frequencies self._errors2 += errors2 # TODO: check that adaptive does not produce under-/over-flows? if self.keep_missed: self.underflow += underflow self.overflow += overflow if self._stats: for key in self._stats: self._stats[key] += stats.get(key, 0.0)
[ "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", ".", "_binning", ".", "force_bin_existence", "(", "values", ")", "self", ".", "_reshape_data", "(", "self", ".", "_binning", ".", "bin_count", ",", "map", ")", "if", "weights", ":", "weights", "=", "np", ".", "asarray", "(", "weights", ")", "self", ".", "_coerce_dtype", "(", "weights", ".", "dtype", ")", "(", "frequencies", ",", "errors2", ",", "underflow", ",", "overflow", ",", "stats", ")", "=", "calculate_frequencies", "(", "values", ",", "self", ".", "_binning", ",", "dtype", "=", "self", ".", "dtype", ",", "weights", "=", "weights", ",", "validate_bins", "=", "False", ")", "self", ".", "_frequencies", "+=", "frequencies", "self", ".", "_errors2", "+=", "errors2", "# TODO: check that adaptive does not produce under-/over-flows?", "if", "self", ".", "keep_missed", ":", "self", ".", "underflow", "+=", "underflow", "self", ".", "overflow", "+=", "overflow", "if", "self", ".", "_stats", ":", "for", "key", "in", "self", ".", "_stats", ":", "self", ".", "_stats", "[", "key", "]", "+=", "stats", ".", "get", "(", "key", ",", "0.0", ")" ]
Update histograms with a set of values. Parameters ---------- values: array_like weights: Optional[array_like] drop_na: Optional[bool] If true (default), all nan's are skipped.
[ "Update", "histograms", "with", "a", "set", "of", "values", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram1d.py#L410-L441
16,484
janpipek/physt
physt/histogram1d.py
Histogram1D.to_xarray
def to_xarray(self) -> "xarray.Dataset": """Convert to 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.bins, dims=("bin", "x01")) } coords = {} attrs = { "underflow": self.underflow, "overflow": self.overflow, "inner_missed": self.inner_missed, "keep_missed": self.keep_missed } attrs.update(self._meta_data) # TODO: Add stats return xr.Dataset(data_vars, coords, attrs)
python
def to_xarray(self) -> "xarray.Dataset": """Convert to 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.bins, dims=("bin", "x01")) } coords = {} attrs = { "underflow": self.underflow, "overflow": self.overflow, "inner_missed": self.inner_missed, "keep_missed": self.keep_missed } attrs.update(self._meta_data) # TODO: Add stats return xr.Dataset(data_vars, coords, attrs)
[ "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", ".", "bins", ",", "dims", "=", "(", "\"bin\"", ",", "\"x01\"", ")", ")", "}", "coords", "=", "{", "}", "attrs", "=", "{", "\"underflow\"", ":", "self", ".", "underflow", ",", "\"overflow\"", ":", "self", ".", "overflow", ",", "\"inner_missed\"", ":", "self", ".", "inner_missed", ",", "\"keep_missed\"", ":", "self", ".", "keep_missed", "}", "attrs", ".", "update", "(", "self", ".", "_meta_data", ")", "# TODO: Add stats", "return", "xr", ".", "Dataset", "(", "data_vars", ",", "coords", ",", "attrs", ")" ]
Convert to xarray.Dataset
[ "Convert", "to", "xarray", ".", "Dataset" ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram1d.py#L487-L504
16,485
janpipek/physt
physt/histogram1d.py
Histogram1D.from_xarray
def from_xarray(cls, arr: "xarray.Dataset") -> "Histogram1D": """Convert form xarray.Dataset Parameters ---------- arr: The data in xarray representation """ kwargs = {'frequencies': arr["frequencies"], 'binning': arr["bins"], 'errors2': arr["errors2"], 'overflow': arr.attrs["overflow"], 'underflow': arr.attrs["underflow"], 'keep_missed': arr.attrs["keep_missed"]} # TODO: Add stats return cls(**kwargs)
python
def from_xarray(cls, arr: "xarray.Dataset") -> "Histogram1D": """Convert form xarray.Dataset Parameters ---------- arr: The data in xarray representation """ kwargs = {'frequencies': arr["frequencies"], 'binning': arr["bins"], 'errors2': arr["errors2"], 'overflow': arr.attrs["overflow"], 'underflow': arr.attrs["underflow"], 'keep_missed': arr.attrs["keep_missed"]} # TODO: Add stats return cls(**kwargs)
[ "def", "from_xarray", "(", "cls", ",", "arr", ":", "\"xarray.Dataset\"", ")", "->", "\"Histogram1D\"", ":", "kwargs", "=", "{", "'frequencies'", ":", "arr", "[", "\"frequencies\"", "]", ",", "'binning'", ":", "arr", "[", "\"bins\"", "]", ",", "'errors2'", ":", "arr", "[", "\"errors2\"", "]", ",", "'overflow'", ":", "arr", ".", "attrs", "[", "\"overflow\"", "]", ",", "'underflow'", ":", "arr", ".", "attrs", "[", "\"underflow\"", "]", ",", "'keep_missed'", ":", "arr", ".", "attrs", "[", "\"keep_missed\"", "]", "}", "# TODO: Add stats", "return", "cls", "(", "*", "*", "kwargs", ")" ]
Convert form xarray.Dataset Parameters ---------- arr: The data in xarray representation
[ "Convert", "form", "xarray", ".", "Dataset" ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram1d.py#L507-L521
16,486
janpipek/physt
physt/plotting/__init__.py
set_default_backend
def set_default_backend(name: str): """Choose a default backend.""" global _default_backend if name == "bokeh": raise RuntimeError("Support for bokeh has been discontinued. At some point, we may return to support holoviews.") if not name in backends: raise RuntimeError("Backend {0} is not supported and cannot be set as default.".format(name)) _default_backend = name
python
def set_default_backend(name: str): """Choose a default backend.""" global _default_backend if name == "bokeh": raise RuntimeError("Support for bokeh has been discontinued. At some point, we may return to support holoviews.") if not name in backends: raise RuntimeError("Backend {0} is not supported and cannot be set as default.".format(name)) _default_backend = name
[ "def", "set_default_backend", "(", "name", ":", "str", ")", ":", "global", "_default_backend", "if", "name", "==", "\"bokeh\"", ":", "raise", "RuntimeError", "(", "\"Support for bokeh has been discontinued. At some point, we may return to support holoviews.\"", ")", "if", "not", "name", "in", "backends", ":", "raise", "RuntimeError", "(", "\"Backend {0} is not supported and cannot be set as default.\"", ".", "format", "(", "name", ")", ")", "_default_backend", "=", "name" ]
Choose a default backend.
[ "Choose", "a", "default", "backend", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/__init__.py#L139-L146
16,487
janpipek/physt
physt/plotting/__init__.py
_get_backend
def _get_backend(name: str = None): """Get a plotting backend. Tries to get it using the name - or the default one. """ if not backends: raise RuntimeError("No plotting backend available. Please, install matplotlib (preferred) or bokeh (limited).") if not name: name = _default_backend if name == "bokeh": raise RuntimeError("Support for bokeh has been discontinued. At some point, we may return to support holoviews.") backend = backends.get(name) if not backend: raise RuntimeError("Backend {0} does not exist. Use one of the following: {1}".format(name, ", ".join(backends.keys()))) return name, backends[name]
python
def _get_backend(name: str = None): """Get a plotting backend. Tries to get it using the name - or the default one. """ if not backends: raise RuntimeError("No plotting backend available. Please, install matplotlib (preferred) or bokeh (limited).") if not name: name = _default_backend if name == "bokeh": raise RuntimeError("Support for bokeh has been discontinued. At some point, we may return to support holoviews.") backend = backends.get(name) if not backend: raise RuntimeError("Backend {0} does not exist. Use one of the following: {1}".format(name, ", ".join(backends.keys()))) return name, backends[name]
[ "def", "_get_backend", "(", "name", ":", "str", "=", "None", ")", ":", "if", "not", "backends", ":", "raise", "RuntimeError", "(", "\"No plotting backend available. Please, install matplotlib (preferred) or bokeh (limited).\"", ")", "if", "not", "name", ":", "name", "=", "_default_backend", "if", "name", "==", "\"bokeh\"", ":", "raise", "RuntimeError", "(", "\"Support for bokeh has been discontinued. At some point, we may return to support holoviews.\"", ")", "backend", "=", "backends", ".", "get", "(", "name", ")", "if", "not", "backend", ":", "raise", "RuntimeError", "(", "\"Backend {0} does not exist. Use one of the following: {1}\"", ".", "format", "(", "name", ",", "\", \"", ".", "join", "(", "backends", ".", "keys", "(", ")", ")", ")", ")", "return", "name", ",", "backends", "[", "name", "]" ]
Get a plotting backend. Tries to get it using the name - or the default one.
[ "Get", "a", "plotting", "backend", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/__init__.py#L149-L163
16,488
janpipek/physt
physt/plotting/__init__.py
plot
def plot(histogram: HistogramBase, kind: Optional[str] = None, backend: Optional[str] = None, **kwargs): """Universal plotting function. All keyword arguments are passed to the plotting methods. Parameters ---------- kind: Type of the plot (like "scatter", "line", ...), similar to pandas """ backend_name, backend = _get_backend(backend) if kind is None: kinds = [t for t in backend.types if histogram.ndim in backend.dims[t]] if not kinds: raise RuntimeError("No plot type is supported for {0}" .format(histogram.__class__.__name__)) kind = kinds[0] if kind in backend.types: method = getattr(backend, kind) return method(histogram, **kwargs) else: raise RuntimeError("Histogram type error: {0} missing in backend {1}" .format(kind, backend_name))
python
def plot(histogram: HistogramBase, kind: Optional[str] = None, backend: Optional[str] = None, **kwargs): """Universal plotting function. All keyword arguments are passed to the plotting methods. Parameters ---------- kind: Type of the plot (like "scatter", "line", ...), similar to pandas """ backend_name, backend = _get_backend(backend) if kind is None: kinds = [t for t in backend.types if histogram.ndim in backend.dims[t]] if not kinds: raise RuntimeError("No plot type is supported for {0}" .format(histogram.__class__.__name__)) kind = kinds[0] if kind in backend.types: method = getattr(backend, kind) return method(histogram, **kwargs) else: raise RuntimeError("Histogram type error: {0} missing in backend {1}" .format(kind, backend_name))
[ "def", "plot", "(", "histogram", ":", "HistogramBase", ",", "kind", ":", "Optional", "[", "str", "]", "=", "None", ",", "backend", ":", "Optional", "[", "str", "]", "=", "None", ",", "*", "*", "kwargs", ")", ":", "backend_name", ",", "backend", "=", "_get_backend", "(", "backend", ")", "if", "kind", "is", "None", ":", "kinds", "=", "[", "t", "for", "t", "in", "backend", ".", "types", "if", "histogram", ".", "ndim", "in", "backend", ".", "dims", "[", "t", "]", "]", "if", "not", "kinds", ":", "raise", "RuntimeError", "(", "\"No plot type is supported for {0}\"", ".", "format", "(", "histogram", ".", "__class__", ".", "__name__", ")", ")", "kind", "=", "kinds", "[", "0", "]", "if", "kind", "in", "backend", ".", "types", ":", "method", "=", "getattr", "(", "backend", ",", "kind", ")", "return", "method", "(", "histogram", ",", "*", "*", "kwargs", ")", "else", ":", "raise", "RuntimeError", "(", "\"Histogram type error: {0} missing in backend {1}\"", ".", "format", "(", "kind", ",", "backend_name", ")", ")" ]
Universal plotting function. All keyword arguments are passed to the plotting methods. Parameters ---------- kind: Type of the plot (like "scatter", "line", ...), similar to pandas
[ "Universal", "plotting", "function", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/__init__.py#L166-L187
16,489
janpipek/physt
physt/plotting/vega.py
enable_inline_view
def enable_inline_view(f): """Decorator to enable in-line viewing in Python and saving to external file. It adds several parameters to each decorated plotted function: Parameters ---------- write_to: str (optional) Path to write vega JSON/HTML to. write_format: "auto" | "json" | "html" Whether to create a JSON data file or a full-fledged HTML page. display: "auto" | True | False Whether to try in-line display in IPython indent: int Indentation of JSON """ @wraps(f) def wrapper(hist, write_to=None, write_format="auto", display="auto", indent=2, **kwargs): vega_data = f(hist, **kwargs) if display is True and not VEGA_IPYTHON_PLUGIN_ENABLED: raise RuntimeError("Cannot display vega plot: {0}".format(VEGA_ERROR)) if display == "auto": display = write_to is None if write_to: write_vega(vega_data, hist.title, write_to, write_format, indent) return display_vega(vega_data, display) return wrapper
python
def enable_inline_view(f): """Decorator to enable in-line viewing in Python and saving to external file. It adds several parameters to each decorated plotted function: Parameters ---------- write_to: str (optional) Path to write vega JSON/HTML to. write_format: "auto" | "json" | "html" Whether to create a JSON data file or a full-fledged HTML page. display: "auto" | True | False Whether to try in-line display in IPython indent: int Indentation of JSON """ @wraps(f) def wrapper(hist, write_to=None, write_format="auto", display="auto", indent=2, **kwargs): vega_data = f(hist, **kwargs) if display is True and not VEGA_IPYTHON_PLUGIN_ENABLED: raise RuntimeError("Cannot display vega plot: {0}".format(VEGA_ERROR)) if display == "auto": display = write_to is None if write_to: write_vega(vega_data, hist.title, write_to, write_format, indent) return display_vega(vega_data, display) return wrapper
[ "def", "enable_inline_view", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "hist", ",", "write_to", "=", "None", ",", "write_format", "=", "\"auto\"", ",", "display", "=", "\"auto\"", ",", "indent", "=", "2", ",", "*", "*", "kwargs", ")", ":", "vega_data", "=", "f", "(", "hist", ",", "*", "*", "kwargs", ")", "if", "display", "is", "True", "and", "not", "VEGA_IPYTHON_PLUGIN_ENABLED", ":", "raise", "RuntimeError", "(", "\"Cannot display vega plot: {0}\"", ".", "format", "(", "VEGA_ERROR", ")", ")", "if", "display", "==", "\"auto\"", ":", "display", "=", "write_to", "is", "None", "if", "write_to", ":", "write_vega", "(", "vega_data", ",", "hist", ".", "title", ",", "write_to", ",", "write_format", ",", "indent", ")", "return", "display_vega", "(", "vega_data", ",", "display", ")", "return", "wrapper" ]
Decorator to enable in-line viewing in Python and saving to external file. It adds several parameters to each decorated plotted function: Parameters ---------- write_to: str (optional) Path to write vega JSON/HTML to. write_format: "auto" | "json" | "html" Whether to create a JSON data file or a full-fledged HTML page. display: "auto" | True | False Whether to try in-line display in IPython indent: int Indentation of JSON
[ "Decorator", "to", "enable", "in", "-", "line", "viewing", "in", "Python", "and", "saving", "to", "external", "file", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/vega.py#L102-L134
16,490
janpipek/physt
physt/plotting/vega.py
write_vega
def write_vega(vega_data, *, title: Optional[str], write_to: str, write_format: str = "auto", indent: int = 2): """Write vega dictionary to an external file. Parameters ---------- vega_data : Valid vega data as dictionary write_to: Path to write vega JSON/HTML to. write_format: "auto" | "json" | "html" Whether to create a JSON data file or a full-fledged HTML page. indent: Indentation of JSON """ spec = json.dumps(vega_data, indent=indent) if write_format == "html" or write_format is "auto" and write_to.endswith(".html"): output = HTML_TEMPLATE.replace("{{ title }}", title or "Histogram").replace("{{ spec }}", spec) elif write_format == "json" or write_format is "auto" and write_to.endswith(".json"): output = spec else: raise RuntimeError("Format not understood.") with codecs.open(write_to, "w", encoding="utf-8") as out: out.write(output)
python
def write_vega(vega_data, *, title: Optional[str], write_to: str, write_format: str = "auto", indent: int = 2): """Write vega dictionary to an external file. Parameters ---------- vega_data : Valid vega data as dictionary write_to: Path to write vega JSON/HTML to. write_format: "auto" | "json" | "html" Whether to create a JSON data file or a full-fledged HTML page. indent: Indentation of JSON """ spec = json.dumps(vega_data, indent=indent) if write_format == "html" or write_format is "auto" and write_to.endswith(".html"): output = HTML_TEMPLATE.replace("{{ title }}", title or "Histogram").replace("{{ spec }}", spec) elif write_format == "json" or write_format is "auto" and write_to.endswith(".json"): output = spec else: raise RuntimeError("Format not understood.") with codecs.open(write_to, "w", encoding="utf-8") as out: out.write(output)
[ "def", "write_vega", "(", "vega_data", ",", "*", ",", "title", ":", "Optional", "[", "str", "]", ",", "write_to", ":", "str", ",", "write_format", ":", "str", "=", "\"auto\"", ",", "indent", ":", "int", "=", "2", ")", ":", "spec", "=", "json", ".", "dumps", "(", "vega_data", ",", "indent", "=", "indent", ")", "if", "write_format", "==", "\"html\"", "or", "write_format", "is", "\"auto\"", "and", "write_to", ".", "endswith", "(", "\".html\"", ")", ":", "output", "=", "HTML_TEMPLATE", ".", "replace", "(", "\"{{ title }}\"", ",", "title", "or", "\"Histogram\"", ")", ".", "replace", "(", "\"{{ spec }}\"", ",", "spec", ")", "elif", "write_format", "==", "\"json\"", "or", "write_format", "is", "\"auto\"", "and", "write_to", ".", "endswith", "(", "\".json\"", ")", ":", "output", "=", "spec", "else", ":", "raise", "RuntimeError", "(", "\"Format not understood.\"", ")", "with", "codecs", ".", "open", "(", "write_to", ",", "\"w\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "out", ":", "out", ".", "write", "(", "output", ")" ]
Write vega dictionary to an external file. Parameters ---------- vega_data : Valid vega data as dictionary write_to: Path to write vega JSON/HTML to. write_format: "auto" | "json" | "html" Whether to create a JSON data file or a full-fledged HTML page. indent: Indentation of JSON
[ "Write", "vega", "dictionary", "to", "an", "external", "file", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/vega.py#L137-L156
16,491
janpipek/physt
physt/plotting/vega.py
display_vega
def display_vega(vega_data: dict, display: bool = True) -> Union['Vega', dict]: """Optionally display vega dictionary. Parameters ---------- vega_data : Valid vega data as dictionary display: Whether to try in-line display in IPython """ if VEGA_IPYTHON_PLUGIN_ENABLED and display: from vega3 import Vega return Vega(vega_data) else: return vega_data
python
def display_vega(vega_data: dict, display: bool = True) -> Union['Vega', dict]: """Optionally display vega dictionary. Parameters ---------- vega_data : Valid vega data as dictionary display: Whether to try in-line display in IPython """ if VEGA_IPYTHON_PLUGIN_ENABLED and display: from vega3 import Vega return Vega(vega_data) else: return vega_data
[ "def", "display_vega", "(", "vega_data", ":", "dict", ",", "display", ":", "bool", "=", "True", ")", "->", "Union", "[", "'Vega'", ",", "dict", "]", ":", "if", "VEGA_IPYTHON_PLUGIN_ENABLED", "and", "display", ":", "from", "vega3", "import", "Vega", "return", "Vega", "(", "vega_data", ")", "else", ":", "return", "vega_data" ]
Optionally display vega dictionary. Parameters ---------- vega_data : Valid vega data as dictionary display: Whether to try in-line display in IPython
[ "Optionally", "display", "vega", "dictionary", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/vega.py#L159-L171
16,492
janpipek/physt
physt/plotting/vega.py
bar
def bar(h1: Histogram1D, **kwargs) -> dict: """Bar plot of 1D histogram. Parameters ---------- lw : float Width of the line between bars alpha : float Opacity of the bars hover_alpha: float Opacity of the bars when hover on """ # TODO: Enable collections # TODO: Enable legend vega = _create_figure(kwargs) _add_title(h1, vega, kwargs) _create_scales(h1, vega, kwargs) _create_axes(h1, vega, kwargs) data = get_data(h1, kwargs.pop("density", None), kwargs.pop("cumulative", None)).tolist() lefts = h1.bin_left_edges.astype(float).tolist() rights = h1.bin_right_edges.astype(float).tolist() vega["data"] = [{ "name": "table", "values": [{ "x": lefts[i], "x2": rights[i], "y": data[i], } for i in range(h1.bin_count) ] }] alpha = kwargs.pop("alpha", 1) # hover_alpha = kwargs.pop("hover_alpha", alpha) vega["marks"] = [ { "type": "rect", "from": {"data": "table"}, "encode": { "enter": { "x": {"scale": "xscale", "field": "x"}, "x2": {"scale": "xscale", "field": "x2"}, "y": {"scale": "yscale", "value": 0}, "y2": {"scale": "yscale", "field": "y"}, # "stroke": {"scale": "color", "field": "c"}, "strokeWidth": {"value": kwargs.pop("lw", 2)} }, "update": { "fillOpacity": [ # {"test": "datum === tooltip", "value": hover_alpha}, {"value": alpha} ] }, } } ] _create_tooltips(h1, vega, kwargs) return vega
python
def bar(h1: Histogram1D, **kwargs) -> dict: """Bar plot of 1D histogram. Parameters ---------- lw : float Width of the line between bars alpha : float Opacity of the bars hover_alpha: float Opacity of the bars when hover on """ # TODO: Enable collections # TODO: Enable legend vega = _create_figure(kwargs) _add_title(h1, vega, kwargs) _create_scales(h1, vega, kwargs) _create_axes(h1, vega, kwargs) data = get_data(h1, kwargs.pop("density", None), kwargs.pop("cumulative", None)).tolist() lefts = h1.bin_left_edges.astype(float).tolist() rights = h1.bin_right_edges.astype(float).tolist() vega["data"] = [{ "name": "table", "values": [{ "x": lefts[i], "x2": rights[i], "y": data[i], } for i in range(h1.bin_count) ] }] alpha = kwargs.pop("alpha", 1) # hover_alpha = kwargs.pop("hover_alpha", alpha) vega["marks"] = [ { "type": "rect", "from": {"data": "table"}, "encode": { "enter": { "x": {"scale": "xscale", "field": "x"}, "x2": {"scale": "xscale", "field": "x2"}, "y": {"scale": "yscale", "value": 0}, "y2": {"scale": "yscale", "field": "y"}, # "stroke": {"scale": "color", "field": "c"}, "strokeWidth": {"value": kwargs.pop("lw", 2)} }, "update": { "fillOpacity": [ # {"test": "datum === tooltip", "value": hover_alpha}, {"value": alpha} ] }, } } ] _create_tooltips(h1, vega, kwargs) return vega
[ "def", "bar", "(", "h1", ":", "Histogram1D", ",", "*", "*", "kwargs", ")", "->", "dict", ":", "# TODO: Enable collections", "# TODO: Enable legend", "vega", "=", "_create_figure", "(", "kwargs", ")", "_add_title", "(", "h1", ",", "vega", ",", "kwargs", ")", "_create_scales", "(", "h1", ",", "vega", ",", "kwargs", ")", "_create_axes", "(", "h1", ",", "vega", ",", "kwargs", ")", "data", "=", "get_data", "(", "h1", ",", "kwargs", ".", "pop", "(", "\"density\"", ",", "None", ")", ",", "kwargs", ".", "pop", "(", "\"cumulative\"", ",", "None", ")", ")", ".", "tolist", "(", ")", "lefts", "=", "h1", ".", "bin_left_edges", ".", "astype", "(", "float", ")", ".", "tolist", "(", ")", "rights", "=", "h1", ".", "bin_right_edges", ".", "astype", "(", "float", ")", ".", "tolist", "(", ")", "vega", "[", "\"data\"", "]", "=", "[", "{", "\"name\"", ":", "\"table\"", ",", "\"values\"", ":", "[", "{", "\"x\"", ":", "lefts", "[", "i", "]", ",", "\"x2\"", ":", "rights", "[", "i", "]", ",", "\"y\"", ":", "data", "[", "i", "]", ",", "}", "for", "i", "in", "range", "(", "h1", ".", "bin_count", ")", "]", "}", "]", "alpha", "=", "kwargs", ".", "pop", "(", "\"alpha\"", ",", "1", ")", "# hover_alpha = kwargs.pop(\"hover_alpha\", alpha)", "vega", "[", "\"marks\"", "]", "=", "[", "{", "\"type\"", ":", "\"rect\"", ",", "\"from\"", ":", "{", "\"data\"", ":", "\"table\"", "}", ",", "\"encode\"", ":", "{", "\"enter\"", ":", "{", "\"x\"", ":", "{", "\"scale\"", ":", "\"xscale\"", ",", "\"field\"", ":", "\"x\"", "}", ",", "\"x2\"", ":", "{", "\"scale\"", ":", "\"xscale\"", ",", "\"field\"", ":", "\"x2\"", "}", ",", "\"y\"", ":", "{", "\"scale\"", ":", "\"yscale\"", ",", "\"value\"", ":", "0", "}", ",", "\"y2\"", ":", "{", "\"scale\"", ":", "\"yscale\"", ",", "\"field\"", ":", "\"y\"", "}", ",", "# \"stroke\": {\"scale\": \"color\", \"field\": \"c\"},", "\"strokeWidth\"", ":", "{", "\"value\"", ":", "kwargs", ".", "pop", "(", "\"lw\"", ",", "2", ")", "}", "}", ",", "\"update\"", ":", "{", "\"fillOpacity\"", ":", "[", "# {\"test\": \"datum === tooltip\", \"value\": hover_alpha},", "{", "\"value\"", ":", "alpha", "}", "]", "}", ",", "}", "}", "]", "_create_tooltips", "(", "h1", ",", "vega", ",", "kwargs", ")", "return", "vega" ]
Bar plot of 1D histogram. Parameters ---------- lw : float Width of the line between bars alpha : float Opacity of the bars hover_alpha: float Opacity of the bars when hover on
[ "Bar", "plot", "of", "1D", "histogram", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/vega.py#L175-L237
16,493
janpipek/physt
physt/plotting/vega.py
scatter
def scatter(h1: Histogram1D, **kwargs) -> dict: """Scatter plot of 1D histogram values. Points are horizontally placed in bin centers. Parameters ---------- shape : str """ shape = kwargs.pop("shape", DEFAULT_SCATTER_SHAPE) # size = kwargs.pop("size", DEFAULT_SCATTER_SIZE) mark_template = [{ "type": "symbol", "from": {"data": "series"}, "encode": { "enter": { "x": {"scale": "xscale", "field": "x"}, "y": {"scale": "yscale", "field": "y"}, "shape": {"value": shape}, # "size": {"value": size}, "fill": {"scale": "series", "field": "c"}, }, } }] vega = _scatter_or_line(h1, mark_template=mark_template, kwargs=kwargs) return vega
python
def scatter(h1: Histogram1D, **kwargs) -> dict: """Scatter plot of 1D histogram values. Points are horizontally placed in bin centers. Parameters ---------- shape : str """ shape = kwargs.pop("shape", DEFAULT_SCATTER_SHAPE) # size = kwargs.pop("size", DEFAULT_SCATTER_SIZE) mark_template = [{ "type": "symbol", "from": {"data": "series"}, "encode": { "enter": { "x": {"scale": "xscale", "field": "x"}, "y": {"scale": "yscale", "field": "y"}, "shape": {"value": shape}, # "size": {"value": size}, "fill": {"scale": "series", "field": "c"}, }, } }] vega = _scatter_or_line(h1, mark_template=mark_template, kwargs=kwargs) return vega
[ "def", "scatter", "(", "h1", ":", "Histogram1D", ",", "*", "*", "kwargs", ")", "->", "dict", ":", "shape", "=", "kwargs", ".", "pop", "(", "\"shape\"", ",", "DEFAULT_SCATTER_SHAPE", ")", "# size = kwargs.pop(\"size\", DEFAULT_SCATTER_SIZE)", "mark_template", "=", "[", "{", "\"type\"", ":", "\"symbol\"", ",", "\"from\"", ":", "{", "\"data\"", ":", "\"series\"", "}", ",", "\"encode\"", ":", "{", "\"enter\"", ":", "{", "\"x\"", ":", "{", "\"scale\"", ":", "\"xscale\"", ",", "\"field\"", ":", "\"x\"", "}", ",", "\"y\"", ":", "{", "\"scale\"", ":", "\"yscale\"", ",", "\"field\"", ":", "\"y\"", "}", ",", "\"shape\"", ":", "{", "\"value\"", ":", "shape", "}", ",", "# \"size\": {\"value\": size},", "\"fill\"", ":", "{", "\"scale\"", ":", "\"series\"", ",", "\"field\"", ":", "\"c\"", "}", ",", "}", ",", "}", "}", "]", "vega", "=", "_scatter_or_line", "(", "h1", ",", "mark_template", "=", "mark_template", ",", "kwargs", "=", "kwargs", ")", "return", "vega" ]
Scatter plot of 1D histogram values. Points are horizontally placed in bin centers. Parameters ---------- shape : str
[ "Scatter", "plot", "of", "1D", "histogram", "values", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/vega.py#L244-L270
16,494
janpipek/physt
physt/plotting/vega.py
line
def line(h1: Histogram1D, **kwargs) -> dict: """Line plot of 1D histogram values. Points are horizontally placed in bin centers. Parameters ---------- h1 : physt.histogram1d.Histogram1D Dimensionality of histogram for which it is applicable """ lw = kwargs.pop("lw", DEFAULT_STROKE_WIDTH) mark_template = [{ "type": "line", "encode": { "enter": { "x": {"scale": "xscale", "field": "x"}, "y": {"scale": "yscale", "field": "y"}, "stroke": {"scale": "series", "field": "c"}, "strokeWidth": {"value": lw} } }, "from": {"data": "series"}, }] vega = _scatter_or_line(h1, mark_template=mark_template, kwargs=kwargs) return vega
python
def line(h1: Histogram1D, **kwargs) -> dict: """Line plot of 1D histogram values. Points are horizontally placed in bin centers. Parameters ---------- h1 : physt.histogram1d.Histogram1D Dimensionality of histogram for which it is applicable """ lw = kwargs.pop("lw", DEFAULT_STROKE_WIDTH) mark_template = [{ "type": "line", "encode": { "enter": { "x": {"scale": "xscale", "field": "x"}, "y": {"scale": "yscale", "field": "y"}, "stroke": {"scale": "series", "field": "c"}, "strokeWidth": {"value": lw} } }, "from": {"data": "series"}, }] vega = _scatter_or_line(h1, mark_template=mark_template, kwargs=kwargs) return vega
[ "def", "line", "(", "h1", ":", "Histogram1D", ",", "*", "*", "kwargs", ")", "->", "dict", ":", "lw", "=", "kwargs", ".", "pop", "(", "\"lw\"", ",", "DEFAULT_STROKE_WIDTH", ")", "mark_template", "=", "[", "{", "\"type\"", ":", "\"line\"", ",", "\"encode\"", ":", "{", "\"enter\"", ":", "{", "\"x\"", ":", "{", "\"scale\"", ":", "\"xscale\"", ",", "\"field\"", ":", "\"x\"", "}", ",", "\"y\"", ":", "{", "\"scale\"", ":", "\"yscale\"", ",", "\"field\"", ":", "\"y\"", "}", ",", "\"stroke\"", ":", "{", "\"scale\"", ":", "\"series\"", ",", "\"field\"", ":", "\"c\"", "}", ",", "\"strokeWidth\"", ":", "{", "\"value\"", ":", "lw", "}", "}", "}", ",", "\"from\"", ":", "{", "\"data\"", ":", "\"series\"", "}", ",", "}", "]", "vega", "=", "_scatter_or_line", "(", "h1", ",", "mark_template", "=", "mark_template", ",", "kwargs", "=", "kwargs", ")", "return", "vega" ]
Line plot of 1D histogram values. Points are horizontally placed in bin centers. Parameters ---------- h1 : physt.histogram1d.Histogram1D Dimensionality of histogram for which it is applicable
[ "Line", "plot", "of", "1D", "histogram", "values", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/vega.py#L276-L302
16,495
janpipek/physt
physt/plotting/vega.py
_create_figure
def _create_figure(kwargs: Mapping[str, Any]) -> dict: """Create basic dictionary object with figure properties.""" return { "$schema": "https://vega.github.io/schema/vega/v3.json", "width": kwargs.pop("width", DEFAULT_WIDTH), "height": kwargs.pop("height", DEFAULT_HEIGHT), "padding": kwargs.pop("padding", DEFAULT_PADDING) }
python
def _create_figure(kwargs: Mapping[str, Any]) -> dict: """Create basic dictionary object with figure properties.""" return { "$schema": "https://vega.github.io/schema/vega/v3.json", "width": kwargs.pop("width", DEFAULT_WIDTH), "height": kwargs.pop("height", DEFAULT_HEIGHT), "padding": kwargs.pop("padding", DEFAULT_PADDING) }
[ "def", "_create_figure", "(", "kwargs", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "dict", ":", "return", "{", "\"$schema\"", ":", "\"https://vega.github.io/schema/vega/v3.json\"", ",", "\"width\"", ":", "kwargs", ".", "pop", "(", "\"width\"", ",", "DEFAULT_WIDTH", ")", ",", "\"height\"", ":", "kwargs", ".", "pop", "(", "\"height\"", ",", "DEFAULT_HEIGHT", ")", ",", "\"padding\"", ":", "kwargs", ".", "pop", "(", "\"padding\"", ",", "DEFAULT_PADDING", ")", "}" ]
Create basic dictionary object with figure properties.
[ "Create", "basic", "dictionary", "object", "with", "figure", "properties", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/vega.py#L551-L558
16,496
janpipek/physt
physt/plotting/vega.py
_create_scales
def _create_scales(hist: HistogramBase, vega: dict, kwargs: dict): """Find proper scales for axes.""" if hist.ndim == 1: bins0 = hist.bins.astype(float) else: bins0 = hist.bins[0].astype(float) xlim = kwargs.pop("xlim", "auto") ylim = kwargs.pop("ylim", "auto") if xlim is "auto": nice_x = True else: nice_x = False if ylim is "auto": nice_y = True else: nice_y = False # TODO: Unify xlim & ylim parameters with matplotlib # TODO: Apply xscale & yscale parameters vega["scales"] = [ { "name": "xscale", "type": "linear", "range": "width", "nice": nice_x, "zero": None, "domain": [bins0[0, 0], bins0[-1, 1]] if xlim == "auto" else [float(xlim[0]), float(xlim[1])], # "domain": {"data": "table", "field": "x"} }, { "name": "yscale", "type": "linear", "range": "height", "nice": nice_y, "zero": True if hist.ndim == 1 else None, "domain": {"data": "table", "field": "y"} if ylim == "auto" else [float(ylim[0]), float(ylim[1])] } ] if hist.ndim >= 2: bins1 = hist.bins[1].astype(float) vega["scales"][1]["domain"] = [bins1[0, 0], bins1[-1, 1]]
python
def _create_scales(hist: HistogramBase, vega: dict, kwargs: dict): """Find proper scales for axes.""" if hist.ndim == 1: bins0 = hist.bins.astype(float) else: bins0 = hist.bins[0].astype(float) xlim = kwargs.pop("xlim", "auto") ylim = kwargs.pop("ylim", "auto") if xlim is "auto": nice_x = True else: nice_x = False if ylim is "auto": nice_y = True else: nice_y = False # TODO: Unify xlim & ylim parameters with matplotlib # TODO: Apply xscale & yscale parameters vega["scales"] = [ { "name": "xscale", "type": "linear", "range": "width", "nice": nice_x, "zero": None, "domain": [bins0[0, 0], bins0[-1, 1]] if xlim == "auto" else [float(xlim[0]), float(xlim[1])], # "domain": {"data": "table", "field": "x"} }, { "name": "yscale", "type": "linear", "range": "height", "nice": nice_y, "zero": True if hist.ndim == 1 else None, "domain": {"data": "table", "field": "y"} if ylim == "auto" else [float(ylim[0]), float(ylim[1])] } ] if hist.ndim >= 2: bins1 = hist.bins[1].astype(float) vega["scales"][1]["domain"] = [bins1[0, 0], bins1[-1, 1]]
[ "def", "_create_scales", "(", "hist", ":", "HistogramBase", ",", "vega", ":", "dict", ",", "kwargs", ":", "dict", ")", ":", "if", "hist", ".", "ndim", "==", "1", ":", "bins0", "=", "hist", ".", "bins", ".", "astype", "(", "float", ")", "else", ":", "bins0", "=", "hist", ".", "bins", "[", "0", "]", ".", "astype", "(", "float", ")", "xlim", "=", "kwargs", ".", "pop", "(", "\"xlim\"", ",", "\"auto\"", ")", "ylim", "=", "kwargs", ".", "pop", "(", "\"ylim\"", ",", "\"auto\"", ")", "if", "xlim", "is", "\"auto\"", ":", "nice_x", "=", "True", "else", ":", "nice_x", "=", "False", "if", "ylim", "is", "\"auto\"", ":", "nice_y", "=", "True", "else", ":", "nice_y", "=", "False", "# TODO: Unify xlim & ylim parameters with matplotlib", "# TODO: Apply xscale & yscale parameters", "vega", "[", "\"scales\"", "]", "=", "[", "{", "\"name\"", ":", "\"xscale\"", ",", "\"type\"", ":", "\"linear\"", ",", "\"range\"", ":", "\"width\"", ",", "\"nice\"", ":", "nice_x", ",", "\"zero\"", ":", "None", ",", "\"domain\"", ":", "[", "bins0", "[", "0", ",", "0", "]", ",", "bins0", "[", "-", "1", ",", "1", "]", "]", "if", "xlim", "==", "\"auto\"", "else", "[", "float", "(", "xlim", "[", "0", "]", ")", ",", "float", "(", "xlim", "[", "1", "]", ")", "]", ",", "# \"domain\": {\"data\": \"table\", \"field\": \"x\"}", "}", ",", "{", "\"name\"", ":", "\"yscale\"", ",", "\"type\"", ":", "\"linear\"", ",", "\"range\"", ":", "\"height\"", ",", "\"nice\"", ":", "nice_y", ",", "\"zero\"", ":", "True", "if", "hist", ".", "ndim", "==", "1", "else", "None", ",", "\"domain\"", ":", "{", "\"data\"", ":", "\"table\"", ",", "\"field\"", ":", "\"y\"", "}", "if", "ylim", "==", "\"auto\"", "else", "[", "float", "(", "ylim", "[", "0", "]", ")", ",", "float", "(", "ylim", "[", "1", "]", ")", "]", "}", "]", "if", "hist", ".", "ndim", ">=", "2", ":", "bins1", "=", "hist", ".", "bins", "[", "1", "]", ".", "astype", "(", "float", ")", "vega", "[", "\"scales\"", "]", "[", "1", "]", "[", "\"domain\"", "]", "=", "[", "bins1", "[", "0", ",", "0", "]", ",", "bins1", "[", "-", "1", ",", "1", "]", "]" ]
Find proper scales for axes.
[ "Find", "proper", "scales", "for", "axes", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/vega.py#L568-L613
16,497
janpipek/physt
physt/plotting/vega.py
_create_axes
def _create_axes(hist: HistogramBase, vega: dict, kwargs: dict): """Create axes in the figure.""" xlabel = kwargs.pop("xlabel", hist.axis_names[0]) ylabel = kwargs.pop("ylabel", hist.axis_names[1] if len(hist.axis_names) >= 2 else None) vega["axes"] = [ {"orient": "bottom", "scale": "xscale", "title": xlabel}, {"orient": "left", "scale": "yscale", "title": ylabel} ]
python
def _create_axes(hist: HistogramBase, vega: dict, kwargs: dict): """Create axes in the figure.""" xlabel = kwargs.pop("xlabel", hist.axis_names[0]) ylabel = kwargs.pop("ylabel", hist.axis_names[1] if len(hist.axis_names) >= 2 else None) vega["axes"] = [ {"orient": "bottom", "scale": "xscale", "title": xlabel}, {"orient": "left", "scale": "yscale", "title": ylabel} ]
[ "def", "_create_axes", "(", "hist", ":", "HistogramBase", ",", "vega", ":", "dict", ",", "kwargs", ":", "dict", ")", ":", "xlabel", "=", "kwargs", ".", "pop", "(", "\"xlabel\"", ",", "hist", ".", "axis_names", "[", "0", "]", ")", "ylabel", "=", "kwargs", ".", "pop", "(", "\"ylabel\"", ",", "hist", ".", "axis_names", "[", "1", "]", "if", "len", "(", "hist", ".", "axis_names", ")", ">=", "2", "else", "None", ")", "vega", "[", "\"axes\"", "]", "=", "[", "{", "\"orient\"", ":", "\"bottom\"", ",", "\"scale\"", ":", "\"xscale\"", ",", "\"title\"", ":", "xlabel", "}", ",", "{", "\"orient\"", ":", "\"left\"", ",", "\"scale\"", ":", "\"yscale\"", ",", "\"title\"", ":", "ylabel", "}", "]" ]
Create axes in the figure.
[ "Create", "axes", "in", "the", "figure", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/vega.py#L673-L680
16,498
janpipek/physt
physt/plotting/vega.py
_create_tooltips
def _create_tooltips(hist: Histogram1D, vega: dict, kwargs: dict): """In one-dimensional plots, show values above the value on hover.""" if kwargs.pop("tooltips", False): vega["signals"] = vega.get("signals", []) vega["signals"].append({ "name": "tooltip", "value": {}, "on": [ {"events": "rect:mouseover", "update": "datum"}, {"events": "rect:mouseout", "update": "{}"} ] }) font_size = kwargs.get("fontsize", DEFAULT_FONTSIZE) vega["marks"] = vega.get("marks", []) vega["marks"].append({ "type": "text", "encode": { "enter": { "align": {"value": "center"}, "baseline": {"value": "bottom"}, "fill": {"value": "#333"}, "fontSize": {"value": font_size} }, "update": { "x": {"scale": "xscale", "signal": "(tooltip.x + tooltip.x2) / 2", "band": 0.5}, "y": {"scale": "yscale", "signal": "tooltip.y", "offset": -2}, "text": {"signal": "tooltip.y"}, "fillOpacity": [ {"test": "datum === tooltip", "value": 0}, {"value": 1} ] } } })
python
def _create_tooltips(hist: Histogram1D, vega: dict, kwargs: dict): """In one-dimensional plots, show values above the value on hover.""" if kwargs.pop("tooltips", False): vega["signals"] = vega.get("signals", []) vega["signals"].append({ "name": "tooltip", "value": {}, "on": [ {"events": "rect:mouseover", "update": "datum"}, {"events": "rect:mouseout", "update": "{}"} ] }) font_size = kwargs.get("fontsize", DEFAULT_FONTSIZE) vega["marks"] = vega.get("marks", []) vega["marks"].append({ "type": "text", "encode": { "enter": { "align": {"value": "center"}, "baseline": {"value": "bottom"}, "fill": {"value": "#333"}, "fontSize": {"value": font_size} }, "update": { "x": {"scale": "xscale", "signal": "(tooltip.x + tooltip.x2) / 2", "band": 0.5}, "y": {"scale": "yscale", "signal": "tooltip.y", "offset": -2}, "text": {"signal": "tooltip.y"}, "fillOpacity": [ {"test": "datum === tooltip", "value": 0}, {"value": 1} ] } } })
[ "def", "_create_tooltips", "(", "hist", ":", "Histogram1D", ",", "vega", ":", "dict", ",", "kwargs", ":", "dict", ")", ":", "if", "kwargs", ".", "pop", "(", "\"tooltips\"", ",", "False", ")", ":", "vega", "[", "\"signals\"", "]", "=", "vega", ".", "get", "(", "\"signals\"", ",", "[", "]", ")", "vega", "[", "\"signals\"", "]", ".", "append", "(", "{", "\"name\"", ":", "\"tooltip\"", ",", "\"value\"", ":", "{", "}", ",", "\"on\"", ":", "[", "{", "\"events\"", ":", "\"rect:mouseover\"", ",", "\"update\"", ":", "\"datum\"", "}", ",", "{", "\"events\"", ":", "\"rect:mouseout\"", ",", "\"update\"", ":", "\"{}\"", "}", "]", "}", ")", "font_size", "=", "kwargs", ".", "get", "(", "\"fontsize\"", ",", "DEFAULT_FONTSIZE", ")", "vega", "[", "\"marks\"", "]", "=", "vega", ".", "get", "(", "\"marks\"", ",", "[", "]", ")", "vega", "[", "\"marks\"", "]", ".", "append", "(", "{", "\"type\"", ":", "\"text\"", ",", "\"encode\"", ":", "{", "\"enter\"", ":", "{", "\"align\"", ":", "{", "\"value\"", ":", "\"center\"", "}", ",", "\"baseline\"", ":", "{", "\"value\"", ":", "\"bottom\"", "}", ",", "\"fill\"", ":", "{", "\"value\"", ":", "\"#333\"", "}", ",", "\"fontSize\"", ":", "{", "\"value\"", ":", "font_size", "}", "}", ",", "\"update\"", ":", "{", "\"x\"", ":", "{", "\"scale\"", ":", "\"xscale\"", ",", "\"signal\"", ":", "\"(tooltip.x + tooltip.x2) / 2\"", ",", "\"band\"", ":", "0.5", "}", ",", "\"y\"", ":", "{", "\"scale\"", ":", "\"yscale\"", ",", "\"signal\"", ":", "\"tooltip.y\"", ",", "\"offset\"", ":", "-", "2", "}", ",", "\"text\"", ":", "{", "\"signal\"", ":", "\"tooltip.y\"", "}", ",", "\"fillOpacity\"", ":", "[", "{", "\"test\"", ":", "\"datum === tooltip\"", ",", "\"value\"", ":", "0", "}", ",", "{", "\"value\"", ":", "1", "}", "]", "}", "}", "}", ")" ]
In one-dimensional plots, show values above the value on hover.
[ "In", "one", "-", "dimensional", "plots", "show", "values", "above", "the", "value", "on", "hover", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/vega.py#L683-L718
16,499
janpipek/physt
physt/plotting/vega.py
_add_title
def _add_title(hist: HistogramBase, vega: dict, kwargs: dict): """Display plot title if available.""" title = kwargs.pop("title", hist.title) if title: vega["title"] = { "text": title }
python
def _add_title(hist: HistogramBase, vega: dict, kwargs: dict): """Display plot title if available.""" title = kwargs.pop("title", hist.title) if title: vega["title"] = { "text": title }
[ "def", "_add_title", "(", "hist", ":", "HistogramBase", ",", "vega", ":", "dict", ",", "kwargs", ":", "dict", ")", ":", "title", "=", "kwargs", ".", "pop", "(", "\"title\"", ",", "hist", ".", "title", ")", "if", "title", ":", "vega", "[", "\"title\"", "]", "=", "{", "\"text\"", ":", "title", "}" ]
Display plot title if available.
[ "Display", "plot", "title", "if", "available", "." ]
6dd441b073514e7728235f50b2352d56aacf38d4
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/vega.py#L721-L727