diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..443fadd9f9b0a62723c4cfd816cb651365b2eb13
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/basevalidators.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/basevalidators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9554a9c61d93dc1252e5f24e4c209f9e5f262c67
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/basevalidators.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/data_utils.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/data_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4aeca785cb5ebccc871577cb82591cb2ed69dd64
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/data_utils.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/exceptions.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/exceptions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..43e667af8522087896821dd308a2f927590c8f90
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/exceptions.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/files.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/files.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f75d7c5ea64bde91b822821816e7f7072adfce7b
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/files.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/importers.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/importers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1975cdbe4fc2b2d3065aaf5c1c15cc05b4cf611e
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/importers.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/optional_imports.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/optional_imports.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad5aa9f88e133d9915427dc25cd7d9be65d95f55
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/optional_imports.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/png.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/png.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d07ee4e322dff18ea6e0ede4801c070cf05954f1
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/png.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/utils.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce333273f61190d590330288d427fb8b8bf30053
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__pycache__/utils.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__init__.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..78abe774f49393a346c1b98af7d1c14ec6edc1ea
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__init__.py
@@ -0,0 +1,883 @@
+"""
+colors
+=====
+
+Functions that manipulate colors and arrays of colors.
+
+-----
+There are three basic types of color types: rgb, hex and tuple:
+
+rgb - An rgb color is a string of the form 'rgb(a,b,c)' where a, b and c are
+integers between 0 and 255 inclusive.
+
+hex - A hex color is a string of the form '#xxxxxx' where each x is a
+character that belongs to the set [0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f]. This is
+just the set of characters used in the hexadecimal numeric system.
+
+tuple - A tuple color is a 3-tuple of the form (a,b,c) where a, b and c are
+floats between 0 and 1 inclusive.
+
+-----
+Colormaps and Colorscales:
+A colormap or a colorscale is a correspondence between values - Pythonic
+objects such as strings and floats - to colors.
+
+There are typically two main types of colormaps that exist: numerical and
+categorical colormaps.
+
+Numerical:
+----------
+Numerical colormaps are used when the coloring column being used takes a
+spectrum of values or numbers.
+
+A classic example from the Plotly library:
+```
+rainbow_colorscale = [
+ [0, 'rgb(150,0,90)'], [0.125, 'rgb(0,0,200)'],
+ [0.25, 'rgb(0,25,255)'], [0.375, 'rgb(0,152,255)'],
+ [0.5, 'rgb(44,255,150)'], [0.625, 'rgb(151,255,0)'],
+ [0.75, 'rgb(255,234,0)'], [0.875, 'rgb(255,111,0)'],
+ [1, 'rgb(255,0,0)']
+]
+```
+
+Notice that this colorscale is a list of lists with each inner list containing
+a number and a color. These left hand numbers in the nested lists go from 0 to
+1, and they are like pointers tell you when a number is mapped to a specific
+color.
+
+If you have a column of numbers `col_num` that you want to plot, and you know
+
+```
+min(col_num) = 0
+max(col_num) = 100
+```
+
+then if you pull out the number `12.5` in the list and want to figure out what
+color the corresponding chart element (bar, scatter plot, etc) is going to be,
+you'll figure out that proportionally 12.5 to 100 is the same as 0.125 to 1.
+So, the point will be mapped to 'rgb(0,0,200)'.
+
+All other colors between the pinned values in a colorscale are linearly
+interpolated.
+
+Categorical:
+------------
+Alternatively, a categorical colormap is used to assign a specific value in a
+color column to a specific color everytime it appears in the dataset.
+
+A column of strings in a panadas.dataframe that is chosen to serve as the
+color index would naturally use a categorical colormap. However, you can
+choose to use a categorical colormap with a column of numbers.
+
+Be careful! If you have a lot of unique numbers in your color column you will
+end up with a colormap that is massive and may slow down graphing performance.
+"""
+
+import decimal
+from numbers import Number
+
+from _plotly_utils import exceptions
+
+
+# Built-in qualitative color sequences and sequential,
+# diverging and cyclical color scales.
+#
+# Initially ported over from plotly_express
+from . import ( # noqa: F401
+ qualitative,
+ sequential,
+ diverging,
+ cyclical,
+ cmocean,
+ colorbrewer,
+ carto,
+ plotlyjs,
+)
+
+DEFAULT_PLOTLY_COLORS = [
+ "rgb(31, 119, 180)",
+ "rgb(255, 127, 14)",
+ "rgb(44, 160, 44)",
+ "rgb(214, 39, 40)",
+ "rgb(148, 103, 189)",
+ "rgb(140, 86, 75)",
+ "rgb(227, 119, 194)",
+ "rgb(127, 127, 127)",
+ "rgb(188, 189, 34)",
+ "rgb(23, 190, 207)",
+]
+
+PLOTLY_SCALES = {
+ "Greys": [[0, "rgb(0,0,0)"], [1, "rgb(255,255,255)"]],
+ "YlGnBu": [
+ [0, "rgb(8,29,88)"],
+ [0.125, "rgb(37,52,148)"],
+ [0.25, "rgb(34,94,168)"],
+ [0.375, "rgb(29,145,192)"],
+ [0.5, "rgb(65,182,196)"],
+ [0.625, "rgb(127,205,187)"],
+ [0.75, "rgb(199,233,180)"],
+ [0.875, "rgb(237,248,217)"],
+ [1, "rgb(255,255,217)"],
+ ],
+ "Greens": [
+ [0, "rgb(0,68,27)"],
+ [0.125, "rgb(0,109,44)"],
+ [0.25, "rgb(35,139,69)"],
+ [0.375, "rgb(65,171,93)"],
+ [0.5, "rgb(116,196,118)"],
+ [0.625, "rgb(161,217,155)"],
+ [0.75, "rgb(199,233,192)"],
+ [0.875, "rgb(229,245,224)"],
+ [1, "rgb(247,252,245)"],
+ ],
+ "YlOrRd": [
+ [0, "rgb(128,0,38)"],
+ [0.125, "rgb(189,0,38)"],
+ [0.25, "rgb(227,26,28)"],
+ [0.375, "rgb(252,78,42)"],
+ [0.5, "rgb(253,141,60)"],
+ [0.625, "rgb(254,178,76)"],
+ [0.75, "rgb(254,217,118)"],
+ [0.875, "rgb(255,237,160)"],
+ [1, "rgb(255,255,204)"],
+ ],
+ "Bluered": [[0, "rgb(0,0,255)"], [1, "rgb(255,0,0)"]],
+ # modified RdBu based on
+ # www.sandia.gov/~kmorel/documents/ColorMaps/ColorMapsExpanded.pdf
+ "RdBu": [
+ [0, "rgb(5,10,172)"],
+ [0.35, "rgb(106,137,247)"],
+ [0.5, "rgb(190,190,190)"],
+ [0.6, "rgb(220,170,132)"],
+ [0.7, "rgb(230,145,90)"],
+ [1, "rgb(178,10,28)"],
+ ],
+ # Scale for non-negative numeric values
+ "Reds": [
+ [0, "rgb(220,220,220)"],
+ [0.2, "rgb(245,195,157)"],
+ [0.4, "rgb(245,160,105)"],
+ [1, "rgb(178,10,28)"],
+ ],
+ # Scale for non-positive numeric values
+ "Blues": [
+ [0, "rgb(5,10,172)"],
+ [0.35, "rgb(40,60,190)"],
+ [0.5, "rgb(70,100,245)"],
+ [0.6, "rgb(90,120,245)"],
+ [0.7, "rgb(106,137,247)"],
+ [1, "rgb(220,220,220)"],
+ ],
+ "Picnic": [
+ [0, "rgb(0,0,255)"],
+ [0.1, "rgb(51,153,255)"],
+ [0.2, "rgb(102,204,255)"],
+ [0.3, "rgb(153,204,255)"],
+ [0.4, "rgb(204,204,255)"],
+ [0.5, "rgb(255,255,255)"],
+ [0.6, "rgb(255,204,255)"],
+ [0.7, "rgb(255,153,255)"],
+ [0.8, "rgb(255,102,204)"],
+ [0.9, "rgb(255,102,102)"],
+ [1, "rgb(255,0,0)"],
+ ],
+ "Rainbow": [
+ [0, "rgb(150,0,90)"],
+ [0.125, "rgb(0,0,200)"],
+ [0.25, "rgb(0,25,255)"],
+ [0.375, "rgb(0,152,255)"],
+ [0.5, "rgb(44,255,150)"],
+ [0.625, "rgb(151,255,0)"],
+ [0.75, "rgb(255,234,0)"],
+ [0.875, "rgb(255,111,0)"],
+ [1, "rgb(255,0,0)"],
+ ],
+ "Portland": [
+ [0, "rgb(12,51,131)"],
+ [0.25, "rgb(10,136,186)"],
+ [0.5, "rgb(242,211,56)"],
+ [0.75, "rgb(242,143,56)"],
+ [1, "rgb(217,30,30)"],
+ ],
+ "Jet": [
+ [0, "rgb(0,0,131)"],
+ [0.125, "rgb(0,60,170)"],
+ [0.375, "rgb(5,255,255)"],
+ [0.625, "rgb(255,255,0)"],
+ [0.875, "rgb(250,0,0)"],
+ [1, "rgb(128,0,0)"],
+ ],
+ "Hot": [
+ [0, "rgb(0,0,0)"],
+ [0.3, "rgb(230,0,0)"],
+ [0.6, "rgb(255,210,0)"],
+ [1, "rgb(255,255,255)"],
+ ],
+ "Blackbody": [
+ [0, "rgb(0,0,0)"],
+ [0.2, "rgb(230,0,0)"],
+ [0.4, "rgb(230,210,0)"],
+ [0.7, "rgb(255,255,255)"],
+ [1, "rgb(160,200,255)"],
+ ],
+ "Earth": [
+ [0, "rgb(0,0,130)"],
+ [0.1, "rgb(0,180,180)"],
+ [0.2, "rgb(40,210,40)"],
+ [0.4, "rgb(230,230,50)"],
+ [0.6, "rgb(120,70,20)"],
+ [1, "rgb(255,255,255)"],
+ ],
+ "Electric": [
+ [0, "rgb(0,0,0)"],
+ [0.15, "rgb(30,0,100)"],
+ [0.4, "rgb(120,0,100)"],
+ [0.6, "rgb(160,90,0)"],
+ [0.8, "rgb(230,200,0)"],
+ [1, "rgb(255,250,220)"],
+ ],
+ "Viridis": [
+ [0, "#440154"],
+ [0.06274509803921569, "#48186a"],
+ [0.12549019607843137, "#472d7b"],
+ [0.18823529411764706, "#424086"],
+ [0.25098039215686274, "#3b528b"],
+ [0.3137254901960784, "#33638d"],
+ [0.3764705882352941, "#2c728e"],
+ [0.4392156862745098, "#26828e"],
+ [0.5019607843137255, "#21918c"],
+ [0.5647058823529412, "#1fa088"],
+ [0.6274509803921569, "#28ae80"],
+ [0.6901960784313725, "#3fbc73"],
+ [0.7529411764705882, "#5ec962"],
+ [0.8156862745098039, "#84d44b"],
+ [0.8784313725490196, "#addc30"],
+ [0.9411764705882353, "#d8e219"],
+ [1, "#fde725"],
+ ],
+ "Cividis": [
+ [0.000000, "rgb(0,32,76)"],
+ [0.058824, "rgb(0,42,102)"],
+ [0.117647, "rgb(0,52,110)"],
+ [0.176471, "rgb(39,63,108)"],
+ [0.235294, "rgb(60,74,107)"],
+ [0.294118, "rgb(76,85,107)"],
+ [0.352941, "rgb(91,95,109)"],
+ [0.411765, "rgb(104,106,112)"],
+ [0.470588, "rgb(117,117,117)"],
+ [0.529412, "rgb(131,129,120)"],
+ [0.588235, "rgb(146,140,120)"],
+ [0.647059, "rgb(161,152,118)"],
+ [0.705882, "rgb(176,165,114)"],
+ [0.764706, "rgb(192,177,109)"],
+ [0.823529, "rgb(209,191,102)"],
+ [0.882353, "rgb(225,204,92)"],
+ [0.941176, "rgb(243,219,79)"],
+ [1.000000, "rgb(255,233,69)"],
+ ],
+}
+
+
+def color_parser(colors, function):
+ """
+ Takes color(s) and a function and applies the function on the color(s)
+
+ In particular, this function identifies whether the given color object
+ is an iterable or not and applies the given color-parsing function to
+ the color or iterable of colors. If given an iterable, it will only be
+ able to work with it if all items in the iterable are of the same type
+ - rgb string, hex string or tuple
+ """
+ if isinstance(colors, str):
+ return function(colors)
+
+ if isinstance(colors, tuple) and isinstance(colors[0], Number):
+ return function(colors)
+
+ if hasattr(colors, "__iter__"):
+ if isinstance(colors, tuple):
+ new_color_tuple = tuple(function(item) for item in colors)
+ return new_color_tuple
+
+ else:
+ new_color_list = [function(item) for item in colors]
+ return new_color_list
+
+
+def validate_colors(colors, colortype="tuple"):
+ """
+ Validates color(s) and returns a list of color(s) of a specified type
+ """
+ from numbers import Number
+
+ if colors is None:
+ colors = DEFAULT_PLOTLY_COLORS
+
+ if isinstance(colors, str):
+ if colors in PLOTLY_SCALES:
+ colors_list = colorscale_to_colors(PLOTLY_SCALES[colors])
+ # TODO: fix _gantt.py/_scatter.py so that they can accept the
+ # actual colorscale and not just a list of the first and last
+ # color in the plotly colorscale. In resolving this issue we
+ # will be removing the immediate line below
+ colors = [colors_list[0]] + [colors_list[-1]]
+ elif "rgb" in colors or "#" in colors:
+ colors = [colors]
+ else:
+ raise exceptions.PlotlyError(
+ "If your colors variable is a string, it must be a "
+ "Plotly scale, an rgb color or a hex color."
+ )
+
+ elif isinstance(colors, tuple):
+ if isinstance(colors[0], Number):
+ colors = [colors]
+ else:
+ colors = list(colors)
+
+ # convert color elements in list to tuple color
+ for j, each_color in enumerate(colors):
+ if "rgb" in each_color:
+ each_color = color_parser(each_color, unlabel_rgb)
+ for value in each_color:
+ if value > 255.0:
+ raise exceptions.PlotlyError(
+ "Whoops! The elements in your rgb colors "
+ "tuples cannot exceed 255.0."
+ )
+ each_color = color_parser(each_color, unconvert_from_RGB_255)
+ colors[j] = each_color
+
+ if "#" in each_color:
+ each_color = color_parser(each_color, hex_to_rgb)
+ each_color = color_parser(each_color, unconvert_from_RGB_255)
+
+ colors[j] = each_color
+
+ if isinstance(each_color, tuple):
+ for value in each_color:
+ if value > 1.0:
+ raise exceptions.PlotlyError(
+ "Whoops! The elements in your colors tuples cannot exceed 1.0."
+ )
+ colors[j] = each_color
+
+ if colortype == "rgb" and not isinstance(colors, str):
+ for j, each_color in enumerate(colors):
+ rgb_color = color_parser(each_color, convert_to_RGB_255)
+ colors[j] = color_parser(rgb_color, label_rgb)
+
+ return colors
+
+
+def validate_colors_dict(colors, colortype="tuple"):
+ """
+ Validates dictionary of color(s)
+ """
+ # validate each color element in the dictionary
+ for key in colors:
+ if "rgb" in colors[key]:
+ colors[key] = color_parser(colors[key], unlabel_rgb)
+ for value in colors[key]:
+ if value > 255.0:
+ raise exceptions.PlotlyError(
+ "Whoops! The elements in your rgb colors "
+ "tuples cannot exceed 255.0."
+ )
+ colors[key] = color_parser(colors[key], unconvert_from_RGB_255)
+
+ if "#" in colors[key]:
+ colors[key] = color_parser(colors[key], hex_to_rgb)
+ colors[key] = color_parser(colors[key], unconvert_from_RGB_255)
+
+ if isinstance(colors[key], tuple):
+ for value in colors[key]:
+ if value > 1.0:
+ raise exceptions.PlotlyError(
+ "Whoops! The elements in your colors tuples cannot exceed 1.0."
+ )
+
+ if colortype == "rgb":
+ for key in colors:
+ colors[key] = color_parser(colors[key], convert_to_RGB_255)
+ colors[key] = color_parser(colors[key], label_rgb)
+
+ return colors
+
+
+def convert_colors_to_same_type(
+ colors,
+ colortype="rgb",
+ scale=None,
+ return_default_colors=False,
+ num_of_defualt_colors=2,
+):
+ """
+ Converts color(s) to the specified color type
+
+ Takes a single color or an iterable of colors, as well as a list of scale
+ values, and outputs a 2-pair of the list of color(s) converted all to an
+ rgb or tuple color type, aswell as the scale as the second element. If
+ colors is a Plotly Scale name, then 'scale' will be forced to the scale
+ from the respective colorscale and the colors in that colorscale will also
+ be coverted to the selected colortype. If colors is None, then there is an
+ option to return portion of the DEFAULT_PLOTLY_COLORS
+
+ :param (str|tuple|list) colors: either a plotly scale name, an rgb or hex
+ color, a color tuple or a list/tuple of colors
+ :param (list) scale: see docs for validate_scale_values()
+
+ :rtype (tuple) (colors_list, scale) if scale is None in the function call,
+ then scale will remain None in the returned tuple
+ """
+ colors_list = []
+
+ if colors is None and return_default_colors is True:
+ colors_list = DEFAULT_PLOTLY_COLORS[0:num_of_defualt_colors]
+
+ if isinstance(colors, str):
+ if colors in PLOTLY_SCALES:
+ colors_list = colorscale_to_colors(PLOTLY_SCALES[colors])
+ if scale is None:
+ scale = colorscale_to_scale(PLOTLY_SCALES[colors])
+
+ elif "rgb" in colors or "#" in colors:
+ colors_list = [colors]
+
+ elif isinstance(colors, tuple):
+ if isinstance(colors[0], Number):
+ colors_list = [colors]
+ else:
+ colors_list = list(colors)
+
+ elif isinstance(colors, list):
+ colors_list = colors
+
+ # validate scale
+ if scale is not None:
+ validate_scale_values(scale)
+
+ if len(colors_list) != len(scale):
+ raise exceptions.PlotlyError(
+ "Make sure that the length of your scale matches the length "
+ "of your list of colors which is {}.".format(len(colors_list))
+ )
+
+ # convert all colors to rgb
+ for j, each_color in enumerate(colors_list):
+ if "#" in each_color:
+ each_color = color_parser(each_color, hex_to_rgb)
+ each_color = color_parser(each_color, label_rgb)
+ colors_list[j] = each_color
+
+ elif isinstance(each_color, tuple):
+ each_color = color_parser(each_color, convert_to_RGB_255)
+ each_color = color_parser(each_color, label_rgb)
+ colors_list[j] = each_color
+
+ if colortype == "rgb":
+ return (colors_list, scale)
+ elif colortype == "tuple":
+ for j, each_color in enumerate(colors_list):
+ each_color = color_parser(each_color, unlabel_rgb)
+ each_color = color_parser(each_color, unconvert_from_RGB_255)
+ colors_list[j] = each_color
+ return (colors_list, scale)
+ else:
+ raise exceptions.PlotlyError(
+ "You must select either rgb or tuple for your colortype variable."
+ )
+
+
+def convert_dict_colors_to_same_type(colors_dict, colortype="rgb"):
+ """
+ Converts a colors in a dictionary of colors to the specified color type
+
+ :param (dict) colors_dict: a dictionary whose values are single colors
+ """
+ for key in colors_dict:
+ if "#" in colors_dict[key]:
+ colors_dict[key] = color_parser(colors_dict[key], hex_to_rgb)
+ colors_dict[key] = color_parser(colors_dict[key], label_rgb)
+
+ elif isinstance(colors_dict[key], tuple):
+ colors_dict[key] = color_parser(colors_dict[key], convert_to_RGB_255)
+ colors_dict[key] = color_parser(colors_dict[key], label_rgb)
+
+ if colortype == "rgb":
+ return colors_dict
+ elif colortype == "tuple":
+ for key in colors_dict:
+ colors_dict[key] = color_parser(colors_dict[key], unlabel_rgb)
+ colors_dict[key] = color_parser(colors_dict[key], unconvert_from_RGB_255)
+ return colors_dict
+ else:
+ raise exceptions.PlotlyError(
+ "You must select either rgb or tuple for your colortype variable."
+ )
+
+
+def validate_scale_values(scale):
+ """
+ Validates scale values from a colorscale
+
+ :param (list) scale: a strictly increasing list of floats that begins
+ with 0 and ends with 1. Its usage derives from a colorscale which is
+ a list of two-lists (a list with two elements) of the form
+ [value, color] which are used to determine how interpolation weighting
+ works between the colors in the colorscale. Therefore scale is just
+ the extraction of these values from the two-lists in order
+ """
+ if len(scale) < 2:
+ raise exceptions.PlotlyError(
+ "You must input a list of scale values that has at least two values."
+ )
+
+ if (scale[0] != 0) or (scale[-1] != 1):
+ raise exceptions.PlotlyError(
+ "The first and last number in your scale must be 0.0 and 1.0 respectively."
+ )
+
+ if not all(x < y for x, y in zip(scale, scale[1:])):
+ raise exceptions.PlotlyError(
+ "'scale' must be a list that contains a strictly increasing "
+ "sequence of numbers."
+ )
+
+
+def validate_colorscale(colorscale):
+ """Validate the structure, scale values and colors of colorscale."""
+ if not isinstance(colorscale, list):
+ # TODO Write tests for these exceptions
+ raise exceptions.PlotlyError("A valid colorscale must be a list.")
+ if not all(isinstance(innerlist, list) for innerlist in colorscale):
+ raise exceptions.PlotlyError("A valid colorscale must be a list of lists.")
+ colorscale_colors = colorscale_to_colors(colorscale)
+ scale_values = colorscale_to_scale(colorscale)
+
+ validate_scale_values(scale_values)
+ validate_colors(colorscale_colors)
+
+
+def make_colorscale(colors, scale=None):
+ """
+ Makes a colorscale from a list of colors and a scale
+
+ Takes a list of colors and scales and constructs a colorscale based
+ on the colors in sequential order. If 'scale' is left empty, a linear-
+ interpolated colorscale will be generated. If 'scale' is a specificed
+ list, it must be the same legnth as colors and must contain all floats
+ For documentation regarding to the form of the output, see
+ https://plot.ly/python/reference/#mesh3d-colorscale
+
+ :param (list) colors: a list of single colors
+ """
+ colorscale = []
+
+ # validate minimum colors length of 2
+ if len(colors) < 2:
+ raise exceptions.PlotlyError(
+ "You must input a list of colors that has at least two colors."
+ )
+
+ if scale is None:
+ scale_incr = 1.0 / (len(colors) - 1)
+ return [[i * scale_incr, color] for i, color in enumerate(colors)]
+
+ else:
+ if len(colors) != len(scale):
+ raise exceptions.PlotlyError(
+ "The length of colors and scale must be the same."
+ )
+
+ validate_scale_values(scale)
+
+ colorscale = [list(tup) for tup in zip(scale, colors)]
+ return colorscale
+
+
+def find_intermediate_color(lowcolor, highcolor, intermed, colortype="tuple"):
+ """
+ Returns the color at a given distance between two colors
+
+ This function takes two color tuples, where each element is between 0
+ and 1, along with a value 0 < intermed < 1 and returns a color that is
+ intermed-percent from lowcolor to highcolor. If colortype is set to 'rgb',
+ the function will automatically convert the rgb type to a tuple, find the
+ intermediate color and return it as an rgb color.
+ """
+ if colortype == "rgb":
+ # convert to tuple color, eg. (1, 0.45, 0.7)
+ lowcolor = unlabel_rgb(lowcolor)
+ highcolor = unlabel_rgb(highcolor)
+
+ diff_0 = float(highcolor[0] - lowcolor[0])
+ diff_1 = float(highcolor[1] - lowcolor[1])
+ diff_2 = float(highcolor[2] - lowcolor[2])
+
+ inter_med_tuple = (
+ lowcolor[0] + intermed * diff_0,
+ lowcolor[1] + intermed * diff_1,
+ lowcolor[2] + intermed * diff_2,
+ )
+
+ if colortype == "rgb":
+ # back to an rgb string, e.g. rgb(30, 20, 10)
+ inter_med_rgb = label_rgb(inter_med_tuple)
+ return inter_med_rgb
+
+ return inter_med_tuple
+
+
+def unconvert_from_RGB_255(colors):
+ """
+ Return a tuple where each element gets divided by 255
+
+ Takes a (list of) color tuple(s) where each element is between 0 and
+ 255. Returns the same tuples where each tuple element is normalized to
+ a value between 0 and 1
+ """
+ return (colors[0] / (255.0), colors[1] / (255.0), colors[2] / (255.0))
+
+
+def convert_to_RGB_255(colors):
+ """
+ Multiplies each element of a triplet by 255
+
+ Each coordinate of the color tuple is rounded to the nearest float and
+ then is turned into an integer. If a number is of the form x.5, then
+ if x is odd, the number rounds up to (x+1). Otherwise, it rounds down
+ to just x. This is the way rounding works in Python 3 and in current
+ statistical analysis to avoid rounding bias
+
+ :param (list) rgb_components: grabs the three R, G and B values to be
+ returned as computed in the function
+ """
+ rgb_components = []
+
+ for component in colors:
+ rounded_num = decimal.Decimal(str(component * 255.0)).quantize(
+ decimal.Decimal("1"), rounding=decimal.ROUND_HALF_EVEN
+ )
+ # convert rounded number to an integer from 'Decimal' form
+ rounded_num = int(rounded_num)
+ rgb_components.append(rounded_num)
+
+ return (rgb_components[0], rgb_components[1], rgb_components[2])
+
+
+def n_colors(lowcolor, highcolor, n_colors, colortype="tuple"):
+ """
+ Splits a low and high color into a list of n_colors colors in it
+
+ Accepts two color tuples and returns a list of n_colors colors
+ which form the intermediate colors between lowcolor and highcolor
+ from linearly interpolating through RGB space. If colortype is 'rgb'
+ the function will return a list of colors in the same form.
+ """
+ if colortype == "rgb":
+ # convert to tuple
+ lowcolor = unlabel_rgb(lowcolor)
+ highcolor = unlabel_rgb(highcolor)
+
+ diff_0 = float(highcolor[0] - lowcolor[0])
+ incr_0 = diff_0 / (n_colors - 1)
+ diff_1 = float(highcolor[1] - lowcolor[1])
+ incr_1 = diff_1 / (n_colors - 1)
+ diff_2 = float(highcolor[2] - lowcolor[2])
+ incr_2 = diff_2 / (n_colors - 1)
+ list_of_colors = []
+
+ def _constrain_color(c):
+ if c > 255.0:
+ return 255.0
+ elif c < 0.0:
+ return 0.0
+ else:
+ return c
+
+ for index in range(n_colors):
+ new_tuple = (
+ _constrain_color(lowcolor[0] + (index * incr_0)),
+ _constrain_color(lowcolor[1] + (index * incr_1)),
+ _constrain_color(lowcolor[2] + (index * incr_2)),
+ )
+ list_of_colors.append(new_tuple)
+
+ if colortype == "rgb":
+ # back to an rgb string
+ list_of_colors = color_parser(list_of_colors, label_rgb)
+
+ return list_of_colors
+
+
+def label_rgb(colors):
+ """
+ Takes tuple (a, b, c) and returns an rgb color 'rgb(a, b, c)'
+ """
+ return "rgb(%s, %s, %s)" % (colors[0], colors[1], colors[2])
+
+
+def unlabel_rgb(colors):
+ """
+ Takes rgb color(s) 'rgb(a, b, c)' and returns tuple(s) (a, b, c)
+
+ This function takes either an 'rgb(a, b, c)' color or a list of
+ such colors and returns the color tuples in tuple(s) (a, b, c)
+ """
+ str_vals = ""
+ for index in range(len(colors)):
+ try:
+ float(colors[index])
+ str_vals = str_vals + colors[index]
+ except ValueError:
+ if colors[index] == "," or colors[index] == ".":
+ str_vals = str_vals + colors[index]
+
+ str_vals = str_vals + ","
+ numbers = []
+ str_num = ""
+ for char in str_vals:
+ if char != ",":
+ str_num = str_num + char
+ else:
+ numbers.append(float(str_num))
+ str_num = ""
+ return (numbers[0], numbers[1], numbers[2])
+
+
+def hex_to_rgb(value):
+ """
+ Calculates rgb values from a hex color code.
+
+ :param (string) value: Hex color string
+
+ :rtype (tuple) (r_value, g_value, b_value): tuple of rgb values
+ """
+ value = value.lstrip("#")
+ hex_total_length = len(value)
+ rgb_section_length = hex_total_length // 3
+ return tuple(
+ int(value[i : i + rgb_section_length], 16)
+ for i in range(0, hex_total_length, rgb_section_length)
+ )
+
+
+def colorscale_to_colors(colorscale):
+ """
+ Extracts the colors from colorscale as a list
+ """
+ color_list = []
+ for item in colorscale:
+ color_list.append(item[1])
+ return color_list
+
+
+def colorscale_to_scale(colorscale):
+ """
+ Extracts the interpolation scale values from colorscale as a list
+ """
+ scale_list = []
+ for item in colorscale:
+ scale_list.append(item[0])
+ return scale_list
+
+
+def convert_colorscale_to_rgb(colorscale):
+ """
+ Converts the colors in a colorscale to rgb colors
+
+ A colorscale is an array of arrays, each with a numeric value as the
+ first item and a color as the second. This function specifically is
+ converting a colorscale with tuple colors (each coordinate between 0
+ and 1) into a colorscale with the colors transformed into rgb colors
+ """
+ for color in colorscale:
+ color[1] = convert_to_RGB_255(color[1])
+
+ for color in colorscale:
+ color[1] = label_rgb(color[1])
+ return colorscale
+
+
+def named_colorscales():
+ """
+ Returns lowercased names of built-in continuous colorscales.
+ """
+ from _plotly_utils.basevalidators import ColorscaleValidator
+
+ return [c for c in ColorscaleValidator("", "").named_colorscales]
+
+
+def get_colorscale(name):
+ """
+ Returns the colorscale for a given name. See `named_colorscales` for the
+ built-in colorscales.
+ """
+ from _plotly_utils.basevalidators import ColorscaleValidator
+
+ if not isinstance(name, str):
+ raise exceptions.PlotlyError("Name argument have to be a string.")
+
+ name = name.lower()
+ if name[-2:] == "_r":
+ should_reverse = True
+ name = name[:-2]
+ else:
+ should_reverse = False
+
+ if name in ColorscaleValidator("", "").named_colorscales:
+ colorscale = ColorscaleValidator("", "").named_colorscales[name]
+ else:
+ raise exceptions.PlotlyError(f"Colorscale {name} is not a built-in scale.")
+
+ if should_reverse:
+ colorscale = colorscale[::-1]
+ return make_colorscale(colorscale)
+
+
+def sample_colorscale(colorscale, samplepoints, low=0.0, high=1.0, colortype="rgb"):
+ """
+ Samples a colorscale at specific points.
+
+ Interpolates between colors in a colorscale to find the specific colors
+ corresponding to the specified sample values. The colorscale can be specified
+ as a list of `[scale, color]` pairs, as a list of colors, or as a named
+ plotly colorscale. The samplepoints can be specefied as an iterable of specific
+ points in the range [0.0, 1.0], or as an integer number of points which will
+ be spaced equally between the low value (default 0.0) and the high value
+ (default 1.0). The output is a list of colors, formatted according to the
+ specified colortype.
+ """
+ from bisect import bisect_left
+
+ try:
+ validate_colorscale(colorscale)
+ except exceptions.PlotlyError:
+ if isinstance(colorscale, str):
+ colorscale = get_colorscale(colorscale)
+ else:
+ colorscale = make_colorscale(colorscale)
+
+ scale = colorscale_to_scale(colorscale)
+ validate_scale_values(scale)
+ colors = colorscale_to_colors(colorscale)
+ colors = validate_colors(colors, colortype="tuple")
+
+ if isinstance(samplepoints, int):
+ samplepoints = [
+ low + idx / (samplepoints - 1) * (high - low) for idx in range(samplepoints)
+ ]
+ elif isinstance(samplepoints, float):
+ samplepoints = [samplepoints]
+
+ sampled_colors = []
+ for point in samplepoints:
+ high = bisect_left(scale, point)
+ low = high - 1
+ interpolant = (point - scale[low]) / (scale[high] - scale[low])
+ sampled_color = find_intermediate_color(colors[low], colors[high], interpolant)
+ sampled_colors.append(sampled_color)
+ return validate_colors(sampled_colors, colortype=colortype)
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ce6e7542b1cca23bf930317cd131f62639891b5
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/_swatches.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/_swatches.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..574ace6c781f8a8dd869a0a8f72ede8e145d33ed
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/_swatches.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/carto.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/carto.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7a2581c92247ecd671dafc1bcecddc25a475b1d0
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/carto.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/cmocean.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/cmocean.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..22465dbaccd74cd35923cb3c677084a696e5e662
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/cmocean.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/colorbrewer.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/colorbrewer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b1ed02b38f95feedb432bca26d8b5ef62da87f0d
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/colorbrewer.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/cyclical.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/cyclical.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1aec154d2f6ec357a6cdbbfb27397e8ced1ee96
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/cyclical.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/diverging.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/diverging.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7c7d72b31439a28505b7407a9dd856fcd483b349
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/diverging.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/plotlyjs.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/plotlyjs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..205d2a2f8b274c7ef00fa66caa53f0945814730b
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/plotlyjs.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/qualitative.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/qualitative.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..11aebd6086557201a01316621d73039f8307a8fc
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/qualitative.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/sequential.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/sequential.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16f9e37d22b6662dbb0aee2f3c3febcbc48f123a
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/__pycache__/sequential.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/_swatches.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/_swatches.py
new file mode 100644
index 0000000000000000000000000000000000000000..f93b651011a832df130d42510f8767e7b123ac1d
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/_swatches.py
@@ -0,0 +1,161 @@
+def _swatches(module_names, module_contents, template=None):
+ """
+ Parameters
+ ----------
+ template : str or dict or plotly.graph_objects.layout.Template instance
+ The figure template name or definition.
+
+ Returns
+ -------
+ fig : graph_objects.Figure containing the displayed image
+ A `Figure` object. This figure demonstrates the color scales and
+ sequences in this module, as stacked bar charts.
+ """
+ import plotly.graph_objs as go
+ from plotly.express._core import apply_default_cascade
+
+ args = dict(template=template)
+ apply_default_cascade(args, constructor=None)
+
+ sequences = [
+ (k, v)
+ for k, v in module_contents.items()
+ if not (k.startswith("_") or k.startswith("swatches") or k.endswith("_r"))
+ ]
+
+ return go.Figure(
+ data=[
+ go.Bar(
+ orientation="h",
+ y=[name] * len(colors),
+ x=[1] * len(colors),
+ customdata=list(range(len(colors))),
+ marker=dict(color=colors),
+ hovertemplate="%{y}[%{customdata}] = %{marker.color}",
+ )
+ for name, colors in reversed(sequences)
+ ],
+ layout=dict(
+ title="plotly.colors." + module_names.split(".")[-1],
+ barmode="stack",
+ barnorm="fraction",
+ bargap=0.5,
+ showlegend=False,
+ xaxis=dict(range=[-0.02, 1.02], showticklabels=False, showgrid=False),
+ height=max(600, 40 * len(sequences)),
+ template=args["template"],
+ margin=dict(b=10),
+ ),
+ )
+
+
+def _swatches_continuous(module_names, module_contents, template=None):
+ """
+ Parameters
+ ----------
+ template : str or dict or plotly.graph_objects.layout.Template instance
+ The figure template name or definition.
+
+ Returns
+ -------
+ fig : graph_objects.Figure containing the displayed image
+ A `Figure` object. This figure demonstrates the color scales and
+ sequences in this module, as stacked bar charts.
+ """
+ import plotly.graph_objs as go
+ from plotly.express._core import apply_default_cascade
+
+ args = dict(template=template)
+ apply_default_cascade(args, constructor=None)
+
+ sequences = [
+ (k, v)
+ for k, v in module_contents.items()
+ if not (k.startswith("_") or k.startswith("swatches") or k.endswith("_r"))
+ ]
+
+ n = 100
+
+ return go.Figure(
+ data=[
+ go.Bar(
+ orientation="h",
+ y=[name] * n,
+ x=[1] * n,
+ customdata=[(x + 1) / n for x in range(n)],
+ marker=dict(color=list(range(n)), colorscale=name, line_width=0),
+ hovertemplate="%{customdata}",
+ name=name,
+ )
+ for name, colors in reversed(sequences)
+ ],
+ layout=dict(
+ title="plotly.colors." + module_names.split(".")[-1],
+ barmode="stack",
+ barnorm="fraction",
+ bargap=0.3,
+ showlegend=False,
+ xaxis=dict(range=[-0.02, 1.02], showticklabels=False, showgrid=False),
+ height=max(600, 40 * len(sequences)),
+ width=500,
+ template=args["template"],
+ margin=dict(b=10),
+ ),
+ )
+
+
+def _swatches_cyclical(module_names, module_contents, template=None):
+ """
+ Parameters
+ ----------
+ template : str or dict or plotly.graph_objects.layout.Template instance
+ The figure template name or definition.
+
+ Returns
+ -------
+ fig : graph_objects.Figure containing the displayed image
+ A `Figure` object. This figure demonstrates the color scales and
+ sequences in this module, as polar bar charts.
+ """
+ import plotly.graph_objects as go
+ from plotly.subplots import make_subplots
+ from plotly.express._core import apply_default_cascade
+
+ args = dict(template=template)
+ apply_default_cascade(args, constructor=None)
+
+ rows = 2
+ cols = 4
+ scales = [
+ (k, v)
+ for k, v in module_contents.items()
+ if not (k.startswith("_") or k.startswith("swatches") or k.endswith("_r"))
+ ]
+ names = [name for name, colors in scales]
+ fig = make_subplots(
+ rows=rows,
+ cols=cols,
+ subplot_titles=names,
+ specs=[[{"type": "polar"}] * cols] * rows,
+ )
+
+ for i, (name, scale) in enumerate(scales):
+ fig.add_trace(
+ go.Barpolar(
+ r=[1] * int(360 / 5),
+ theta=list(range(0, 360, 5)),
+ marker_color=list(range(0, 360, 5)),
+ marker_cmin=0,
+ marker_cmax=360,
+ marker_colorscale=name,
+ name=name,
+ ),
+ row=int(i / cols) + 1,
+ col=i % cols + 1,
+ )
+ fig.update_traces(width=5.2, marker_line_width=0, base=0.5, showlegend=False)
+ fig.update_polars(angularaxis_visible=False, radialaxis_visible=False)
+ fig.update_layout(
+ title="plotly.colors." + module_names.split(".")[-1], template=args["template"]
+ )
+ return fig
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/carto.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/carto.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5c503f32519e5a7341c2aeaf6cfa15260881963
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/carto.py
@@ -0,0 +1,419 @@
+"""
+Color sequences and scales from CARTO's CartoColors
+
+Learn more at https://github.com/CartoDB/CartoColor
+
+CARTOColors are made available under a Creative Commons Attribution license: https://creativecommons.org/licenses/by/3.0/us/
+"""
+
+from ._swatches import _swatches
+
+
+def swatches(template=None):
+ return _swatches(__name__, globals(), template)
+
+
+swatches.__doc__ = _swatches.__doc__
+
+Burg = [
+ "rgb(255, 198, 196)",
+ "rgb(244, 163, 168)",
+ "rgb(227, 129, 145)",
+ "rgb(204, 96, 125)",
+ "rgb(173, 70, 108)",
+ "rgb(139, 48, 88)",
+ "rgb(103, 32, 68)",
+]
+
+Burgyl = [
+ "rgb(251, 230, 197)",
+ "rgb(245, 186, 152)",
+ "rgb(238, 138, 130)",
+ "rgb(220, 113, 118)",
+ "rgb(200, 88, 108)",
+ "rgb(156, 63, 93)",
+ "rgb(112, 40, 74)",
+]
+
+Redor = [
+ "rgb(246, 210, 169)",
+ "rgb(245, 183, 142)",
+ "rgb(241, 156, 124)",
+ "rgb(234, 129, 113)",
+ "rgb(221, 104, 108)",
+ "rgb(202, 82, 104)",
+ "rgb(177, 63, 100)",
+]
+
+Oryel = [
+ "rgb(236, 218, 154)",
+ "rgb(239, 196, 126)",
+ "rgb(243, 173, 106)",
+ "rgb(247, 148, 93)",
+ "rgb(249, 123, 87)",
+ "rgb(246, 99, 86)",
+ "rgb(238, 77, 90)",
+]
+
+Peach = [
+ "rgb(253, 224, 197)",
+ "rgb(250, 203, 166)",
+ "rgb(248, 181, 139)",
+ "rgb(245, 158, 114)",
+ "rgb(242, 133, 93)",
+ "rgb(239, 106, 76)",
+ "rgb(235, 74, 64)",
+]
+
+Pinkyl = [
+ "rgb(254, 246, 181)",
+ "rgb(255, 221, 154)",
+ "rgb(255, 194, 133)",
+ "rgb(255, 166, 121)",
+ "rgb(250, 138, 118)",
+ "rgb(241, 109, 122)",
+ "rgb(225, 83, 131)",
+]
+
+Mint = [
+ "rgb(228, 241, 225)",
+ "rgb(180, 217, 204)",
+ "rgb(137, 192, 182)",
+ "rgb(99, 166, 160)",
+ "rgb(68, 140, 138)",
+ "rgb(40, 114, 116)",
+ "rgb(13, 88, 95)",
+]
+
+Blugrn = [
+ "rgb(196, 230, 195)",
+ "rgb(150, 210, 164)",
+ "rgb(109, 188, 144)",
+ "rgb(77, 162, 132)",
+ "rgb(54, 135, 122)",
+ "rgb(38, 107, 110)",
+ "rgb(29, 79, 96)",
+]
+
+Darkmint = [
+ "rgb(210, 251, 212)",
+ "rgb(165, 219, 194)",
+ "rgb(123, 188, 176)",
+ "rgb(85, 156, 158)",
+ "rgb(58, 124, 137)",
+ "rgb(35, 93, 114)",
+ "rgb(18, 63, 90)",
+]
+
+Emrld = [
+ "rgb(211, 242, 163)",
+ "rgb(151, 225, 150)",
+ "rgb(108, 192, 139)",
+ "rgb(76, 155, 130)",
+ "rgb(33, 122, 121)",
+ "rgb(16, 89, 101)",
+ "rgb(7, 64, 80)",
+]
+
+Aggrnyl = [
+ "rgb(36, 86, 104)",
+ "rgb(15, 114, 121)",
+ "rgb(13, 143, 129)",
+ "rgb(57, 171, 126)",
+ "rgb(110, 197, 116)",
+ "rgb(169, 220, 103)",
+ "rgb(237, 239, 93)",
+]
+
+Bluyl = [
+ "rgb(247, 254, 174)",
+ "rgb(183, 230, 165)",
+ "rgb(124, 203, 162)",
+ "rgb(70, 174, 160)",
+ "rgb(8, 144, 153)",
+ "rgb(0, 113, 139)",
+ "rgb(4, 82, 117)",
+]
+
+Teal = [
+ "rgb(209, 238, 234)",
+ "rgb(168, 219, 217)",
+ "rgb(133, 196, 201)",
+ "rgb(104, 171, 184)",
+ "rgb(79, 144, 166)",
+ "rgb(59, 115, 143)",
+ "rgb(42, 86, 116)",
+]
+
+Tealgrn = [
+ "rgb(176, 242, 188)",
+ "rgb(137, 232, 172)",
+ "rgb(103, 219, 165)",
+ "rgb(76, 200, 163)",
+ "rgb(56, 178, 163)",
+ "rgb(44, 152, 160)",
+ "rgb(37, 125, 152)",
+]
+
+Purp = [
+ "rgb(243, 224, 247)",
+ "rgb(228, 199, 241)",
+ "rgb(209, 175, 232)",
+ "rgb(185, 152, 221)",
+ "rgb(159, 130, 206)",
+ "rgb(130, 109, 186)",
+ "rgb(99, 88, 159)",
+]
+
+Purpor = [
+ "rgb(249, 221, 218)",
+ "rgb(242, 185, 196)",
+ "rgb(229, 151, 185)",
+ "rgb(206, 120, 179)",
+ "rgb(173, 95, 173)",
+ "rgb(131, 75, 160)",
+ "rgb(87, 59, 136)",
+]
+
+Sunset = [
+ "rgb(243, 231, 155)",
+ "rgb(250, 196, 132)",
+ "rgb(248, 160, 126)",
+ "rgb(235, 127, 134)",
+ "rgb(206, 102, 147)",
+ "rgb(160, 89, 160)",
+ "rgb(92, 83, 165)",
+]
+
+Magenta = [
+ "rgb(243, 203, 211)",
+ "rgb(234, 169, 189)",
+ "rgb(221, 136, 172)",
+ "rgb(202, 105, 157)",
+ "rgb(177, 77, 142)",
+ "rgb(145, 53, 125)",
+ "rgb(108, 33, 103)",
+]
+
+Sunsetdark = [
+ "rgb(252, 222, 156)",
+ "rgb(250, 164, 118)",
+ "rgb(240, 116, 110)",
+ "rgb(227, 79, 111)",
+ "rgb(220, 57, 119)",
+ "rgb(185, 37, 122)",
+ "rgb(124, 29, 111)",
+]
+
+Agsunset = [
+ "rgb(75, 41, 145)",
+ "rgb(135, 44, 162)",
+ "rgb(192, 54, 157)",
+ "rgb(234, 79, 136)",
+ "rgb(250, 120, 118)",
+ "rgb(246, 169, 122)",
+ "rgb(237, 217, 163)",
+]
+
+Brwnyl = [
+ "rgb(237, 229, 207)",
+ "rgb(224, 194, 162)",
+ "rgb(211, 156, 131)",
+ "rgb(193, 118, 111)",
+ "rgb(166, 84, 97)",
+ "rgb(129, 55, 83)",
+ "rgb(84, 31, 63)",
+]
+
+# Diverging schemes
+
+Armyrose = [
+ "rgb(121, 130, 52)",
+ "rgb(163, 173, 98)",
+ "rgb(208, 211, 162)",
+ "rgb(253, 251, 228)",
+ "rgb(240, 198, 195)",
+ "rgb(223, 145, 163)",
+ "rgb(212, 103, 128)",
+]
+
+Fall = [
+ "rgb(61, 89, 65)",
+ "rgb(119, 136, 104)",
+ "rgb(181, 185, 145)",
+ "rgb(246, 237, 189)",
+ "rgb(237, 187, 138)",
+ "rgb(222, 138, 90)",
+ "rgb(202, 86, 44)",
+]
+
+Geyser = [
+ "rgb(0, 128, 128)",
+ "rgb(112, 164, 148)",
+ "rgb(180, 200, 168)",
+ "rgb(246, 237, 189)",
+ "rgb(237, 187, 138)",
+ "rgb(222, 138, 90)",
+ "rgb(202, 86, 44)",
+]
+
+Temps = [
+ "rgb(0, 147, 146)",
+ "rgb(57, 177, 133)",
+ "rgb(156, 203, 134)",
+ "rgb(233, 226, 156)",
+ "rgb(238, 180, 121)",
+ "rgb(232, 132, 113)",
+ "rgb(207, 89, 126)",
+]
+
+Tealrose = [
+ "rgb(0, 147, 146)",
+ "rgb(114, 170, 161)",
+ "rgb(177, 199, 179)",
+ "rgb(241, 234, 200)",
+ "rgb(229, 185, 173)",
+ "rgb(217, 137, 148)",
+ "rgb(208, 88, 126)",
+]
+
+Tropic = [
+ "rgb(0, 155, 158)",
+ "rgb(66, 183, 185)",
+ "rgb(167, 211, 212)",
+ "rgb(241, 241, 241)",
+ "rgb(228, 193, 217)",
+ "rgb(214, 145, 193)",
+ "rgb(199, 93, 171)",
+]
+
+Earth = [
+ "rgb(161, 105, 40)",
+ "rgb(189, 146, 90)",
+ "rgb(214, 189, 141)",
+ "rgb(237, 234, 194)",
+ "rgb(181, 200, 184)",
+ "rgb(121, 167, 172)",
+ "rgb(40, 135, 161)",
+]
+
+# Qualitative palettes
+
+Antique = [
+ "rgb(133, 92, 117)",
+ "rgb(217, 175, 107)",
+ "rgb(175, 100, 88)",
+ "rgb(115, 111, 76)",
+ "rgb(82, 106, 131)",
+ "rgb(98, 83, 119)",
+ "rgb(104, 133, 92)",
+ "rgb(156, 156, 94)",
+ "rgb(160, 97, 119)",
+ "rgb(140, 120, 93)",
+ "rgb(124, 124, 124)",
+]
+
+Bold = [
+ "rgb(127, 60, 141)",
+ "rgb(17, 165, 121)",
+ "rgb(57, 105, 172)",
+ "rgb(242, 183, 1)",
+ "rgb(231, 63, 116)",
+ "rgb(128, 186, 90)",
+ "rgb(230, 131, 16)",
+ "rgb(0, 134, 149)",
+ "rgb(207, 28, 144)",
+ "rgb(249, 123, 114)",
+ "rgb(165, 170, 153)",
+]
+
+Pastel = [
+ "rgb(102, 197, 204)",
+ "rgb(246, 207, 113)",
+ "rgb(248, 156, 116)",
+ "rgb(220, 176, 242)",
+ "rgb(135, 197, 95)",
+ "rgb(158, 185, 243)",
+ "rgb(254, 136, 177)",
+ "rgb(201, 219, 116)",
+ "rgb(139, 224, 164)",
+ "rgb(180, 151, 231)",
+ "rgb(179, 179, 179)",
+]
+
+Prism = [
+ "rgb(95, 70, 144)",
+ "rgb(29, 105, 150)",
+ "rgb(56, 166, 165)",
+ "rgb(15, 133, 84)",
+ "rgb(115, 175, 72)",
+ "rgb(237, 173, 8)",
+ "rgb(225, 124, 5)",
+ "rgb(204, 80, 62)",
+ "rgb(148, 52, 110)",
+ "rgb(111, 64, 112)",
+ "rgb(102, 102, 102)",
+]
+
+Safe = [
+ "rgb(136, 204, 238)",
+ "rgb(204, 102, 119)",
+ "rgb(221, 204, 119)",
+ "rgb(17, 119, 51)",
+ "rgb(51, 34, 136)",
+ "rgb(170, 68, 153)",
+ "rgb(68, 170, 153)",
+ "rgb(153, 153, 51)",
+ "rgb(136, 34, 85)",
+ "rgb(102, 17, 0)",
+ "rgb(136, 136, 136)",
+]
+
+Vivid = [
+ "rgb(229, 134, 6)",
+ "rgb(93, 105, 177)",
+ "rgb(82, 188, 163)",
+ "rgb(153, 201, 69)",
+ "rgb(204, 97, 176)",
+ "rgb(36, 121, 108)",
+ "rgb(218, 165, 27)",
+ "rgb(47, 138, 196)",
+ "rgb(118, 78, 159)",
+ "rgb(237, 100, 90)",
+ "rgb(165, 170, 153)",
+]
+
+Aggrnyl_r = Aggrnyl[::-1]
+Agsunset_r = Agsunset[::-1]
+Antique_r = Antique[::-1]
+Armyrose_r = Armyrose[::-1]
+Blugrn_r = Blugrn[::-1]
+Bluyl_r = Bluyl[::-1]
+Bold_r = Bold[::-1]
+Brwnyl_r = Brwnyl[::-1]
+Burg_r = Burg[::-1]
+Burgyl_r = Burgyl[::-1]
+Darkmint_r = Darkmint[::-1]
+Earth_r = Earth[::-1]
+Emrld_r = Emrld[::-1]
+Fall_r = Fall[::-1]
+Geyser_r = Geyser[::-1]
+Magenta_r = Magenta[::-1]
+Mint_r = Mint[::-1]
+Oryel_r = Oryel[::-1]
+Pastel_r = Pastel[::-1]
+Peach_r = Peach[::-1]
+Pinkyl_r = Pinkyl[::-1]
+Prism_r = Prism[::-1]
+Purp_r = Purp[::-1]
+Purpor_r = Purpor[::-1]
+Redor_r = Redor[::-1]
+Safe_r = Safe[::-1]
+Sunset_r = Sunset[::-1]
+Sunsetdark_r = Sunsetdark[::-1]
+Teal_r = Teal[::-1]
+Tealgrn_r = Tealgrn[::-1]
+Tealrose_r = Tealrose[::-1]
+Temps_r = Temps[::-1]
+Tropic_r = Tropic[::-1]
+Vivid_r = Vivid[::-1]
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/cmocean.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/cmocean.py
new file mode 100644
index 0000000000000000000000000000000000000000..18944b59361865b9dd192ea453dfdf2c13024279
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/cmocean.py
@@ -0,0 +1,296 @@
+"""
+Color scales from the cmocean project
+
+Learn more at https://matplotlib.org/cmocean/
+
+cmocean is made available under an MIT license: https://github.com/matplotlib/cmocean/blob/master/LICENSE.txt
+"""
+
+from ._swatches import _swatches, _swatches_continuous
+
+
+def swatches(template=None):
+ return _swatches(__name__, globals(), template)
+
+
+swatches.__doc__ = _swatches.__doc__
+
+
+def swatches_continuous(template=None):
+ return _swatches_continuous(__name__, globals(), template)
+
+
+swatches_continuous.__doc__ = _swatches_continuous.__doc__
+
+
+turbid = [
+ "rgb(232, 245, 171)",
+ "rgb(220, 219, 137)",
+ "rgb(209, 193, 107)",
+ "rgb(199, 168, 83)",
+ "rgb(186, 143, 66)",
+ "rgb(170, 121, 60)",
+ "rgb(151, 103, 58)",
+ "rgb(129, 87, 56)",
+ "rgb(104, 72, 53)",
+ "rgb(80, 59, 46)",
+ "rgb(57, 45, 37)",
+ "rgb(34, 30, 27)",
+]
+thermal = [
+ "rgb(3, 35, 51)",
+ "rgb(13, 48, 100)",
+ "rgb(53, 50, 155)",
+ "rgb(93, 62, 153)",
+ "rgb(126, 77, 143)",
+ "rgb(158, 89, 135)",
+ "rgb(193, 100, 121)",
+ "rgb(225, 113, 97)",
+ "rgb(246, 139, 69)",
+ "rgb(251, 173, 60)",
+ "rgb(246, 211, 70)",
+ "rgb(231, 250, 90)",
+]
+haline = [
+ "rgb(41, 24, 107)",
+ "rgb(42, 35, 160)",
+ "rgb(15, 71, 153)",
+ "rgb(18, 95, 142)",
+ "rgb(38, 116, 137)",
+ "rgb(53, 136, 136)",
+ "rgb(65, 157, 133)",
+ "rgb(81, 178, 124)",
+ "rgb(111, 198, 107)",
+ "rgb(160, 214, 91)",
+ "rgb(212, 225, 112)",
+ "rgb(253, 238, 153)",
+]
+solar = [
+ "rgb(51, 19, 23)",
+ "rgb(79, 28, 33)",
+ "rgb(108, 36, 36)",
+ "rgb(135, 47, 32)",
+ "rgb(157, 66, 25)",
+ "rgb(174, 88, 20)",
+ "rgb(188, 111, 19)",
+ "rgb(199, 137, 22)",
+ "rgb(209, 164, 32)",
+ "rgb(217, 192, 44)",
+ "rgb(222, 222, 59)",
+ "rgb(224, 253, 74)",
+]
+ice = [
+ "rgb(3, 5, 18)",
+ "rgb(25, 25, 51)",
+ "rgb(44, 42, 87)",
+ "rgb(58, 60, 125)",
+ "rgb(62, 83, 160)",
+ "rgb(62, 109, 178)",
+ "rgb(72, 134, 187)",
+ "rgb(89, 159, 196)",
+ "rgb(114, 184, 205)",
+ "rgb(149, 207, 216)",
+ "rgb(192, 229, 232)",
+ "rgb(234, 252, 253)",
+]
+gray = [
+ "rgb(0, 0, 0)",
+ "rgb(16, 16, 16)",
+ "rgb(38, 38, 38)",
+ "rgb(59, 59, 59)",
+ "rgb(81, 80, 80)",
+ "rgb(102, 101, 101)",
+ "rgb(124, 123, 122)",
+ "rgb(146, 146, 145)",
+ "rgb(171, 171, 170)",
+ "rgb(197, 197, 195)",
+ "rgb(224, 224, 223)",
+ "rgb(254, 254, 253)",
+]
+oxy = [
+ "rgb(63, 5, 5)",
+ "rgb(101, 6, 13)",
+ "rgb(138, 17, 9)",
+ "rgb(96, 95, 95)",
+ "rgb(119, 118, 118)",
+ "rgb(142, 141, 141)",
+ "rgb(166, 166, 165)",
+ "rgb(193, 192, 191)",
+ "rgb(222, 222, 220)",
+ "rgb(239, 248, 90)",
+ "rgb(230, 210, 41)",
+ "rgb(220, 174, 25)",
+]
+deep = [
+ "rgb(253, 253, 204)",
+ "rgb(206, 236, 179)",
+ "rgb(156, 219, 165)",
+ "rgb(111, 201, 163)",
+ "rgb(86, 177, 163)",
+ "rgb(76, 153, 160)",
+ "rgb(68, 130, 155)",
+ "rgb(62, 108, 150)",
+ "rgb(62, 82, 143)",
+ "rgb(64, 60, 115)",
+ "rgb(54, 43, 77)",
+ "rgb(39, 26, 44)",
+]
+dense = [
+ "rgb(230, 240, 240)",
+ "rgb(191, 221, 229)",
+ "rgb(156, 201, 226)",
+ "rgb(129, 180, 227)",
+ "rgb(115, 154, 228)",
+ "rgb(117, 127, 221)",
+ "rgb(120, 100, 202)",
+ "rgb(119, 74, 175)",
+ "rgb(113, 50, 141)",
+ "rgb(100, 31, 104)",
+ "rgb(80, 20, 66)",
+ "rgb(54, 14, 36)",
+]
+algae = [
+ "rgb(214, 249, 207)",
+ "rgb(186, 228, 174)",
+ "rgb(156, 209, 143)",
+ "rgb(124, 191, 115)",
+ "rgb(85, 174, 91)",
+ "rgb(37, 157, 81)",
+ "rgb(7, 138, 78)",
+ "rgb(13, 117, 71)",
+ "rgb(23, 95, 61)",
+ "rgb(25, 75, 49)",
+ "rgb(23, 55, 35)",
+ "rgb(17, 36, 20)",
+]
+matter = [
+ "rgb(253, 237, 176)",
+ "rgb(250, 205, 145)",
+ "rgb(246, 173, 119)",
+ "rgb(240, 142, 98)",
+ "rgb(231, 109, 84)",
+ "rgb(216, 80, 83)",
+ "rgb(195, 56, 90)",
+ "rgb(168, 40, 96)",
+ "rgb(138, 29, 99)",
+ "rgb(107, 24, 93)",
+ "rgb(76, 21, 80)",
+ "rgb(47, 15, 61)",
+]
+speed = [
+ "rgb(254, 252, 205)",
+ "rgb(239, 225, 156)",
+ "rgb(221, 201, 106)",
+ "rgb(194, 182, 59)",
+ "rgb(157, 167, 21)",
+ "rgb(116, 153, 5)",
+ "rgb(75, 138, 20)",
+ "rgb(35, 121, 36)",
+ "rgb(11, 100, 44)",
+ "rgb(18, 78, 43)",
+ "rgb(25, 56, 34)",
+ "rgb(23, 35, 18)",
+]
+amp = [
+ "rgb(241, 236, 236)",
+ "rgb(230, 209, 203)",
+ "rgb(221, 182, 170)",
+ "rgb(213, 156, 137)",
+ "rgb(205, 129, 103)",
+ "rgb(196, 102, 73)",
+ "rgb(186, 74, 47)",
+ "rgb(172, 44, 36)",
+ "rgb(149, 19, 39)",
+ "rgb(120, 14, 40)",
+ "rgb(89, 13, 31)",
+ "rgb(60, 9, 17)",
+]
+tempo = [
+ "rgb(254, 245, 244)",
+ "rgb(222, 224, 210)",
+ "rgb(189, 206, 181)",
+ "rgb(153, 189, 156)",
+ "rgb(110, 173, 138)",
+ "rgb(65, 157, 129)",
+ "rgb(25, 137, 125)",
+ "rgb(18, 116, 117)",
+ "rgb(25, 94, 106)",
+ "rgb(28, 72, 93)",
+ "rgb(25, 51, 80)",
+ "rgb(20, 29, 67)",
+]
+phase = [
+ "rgb(167, 119, 12)",
+ "rgb(197, 96, 51)",
+ "rgb(217, 67, 96)",
+ "rgb(221, 38, 163)",
+ "rgb(196, 59, 224)",
+ "rgb(153, 97, 244)",
+ "rgb(95, 127, 228)",
+ "rgb(40, 144, 183)",
+ "rgb(15, 151, 136)",
+ "rgb(39, 153, 79)",
+ "rgb(119, 141, 17)",
+ "rgb(167, 119, 12)",
+]
+balance = [
+ "rgb(23, 28, 66)",
+ "rgb(41, 58, 143)",
+ "rgb(11, 102, 189)",
+ "rgb(69, 144, 185)",
+ "rgb(142, 181, 194)",
+ "rgb(210, 216, 219)",
+ "rgb(230, 210, 204)",
+ "rgb(213, 157, 137)",
+ "rgb(196, 101, 72)",
+ "rgb(172, 43, 36)",
+ "rgb(120, 14, 40)",
+ "rgb(60, 9, 17)",
+]
+delta = [
+ "rgb(16, 31, 63)",
+ "rgb(38, 62, 144)",
+ "rgb(30, 110, 161)",
+ "rgb(60, 154, 171)",
+ "rgb(140, 193, 186)",
+ "rgb(217, 229, 218)",
+ "rgb(239, 226, 156)",
+ "rgb(195, 182, 59)",
+ "rgb(115, 152, 5)",
+ "rgb(34, 120, 36)",
+ "rgb(18, 78, 43)",
+ "rgb(23, 35, 18)",
+]
+curl = [
+ "rgb(20, 29, 67)",
+ "rgb(28, 72, 93)",
+ "rgb(18, 115, 117)",
+ "rgb(63, 156, 129)",
+ "rgb(153, 189, 156)",
+ "rgb(223, 225, 211)",
+ "rgb(241, 218, 206)",
+ "rgb(224, 160, 137)",
+ "rgb(203, 101, 99)",
+ "rgb(164, 54, 96)",
+ "rgb(111, 23, 91)",
+ "rgb(51, 13, 53)",
+]
+
+algae_r = algae[::-1]
+amp_r = amp[::-1]
+balance_r = balance[::-1]
+curl_r = curl[::-1]
+deep_r = deep[::-1]
+delta_r = delta[::-1]
+dense_r = dense[::-1]
+gray_r = gray[::-1]
+haline_r = haline[::-1]
+ice_r = ice[::-1]
+matter_r = matter[::-1]
+oxy_r = oxy[::-1]
+phase_r = phase[::-1]
+solar_r = solar[::-1]
+speed_r = speed[::-1]
+tempo_r = tempo[::-1]
+thermal_r = thermal[::-1]
+turbid_r = turbid[::-1]
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/colorbrewer.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/colorbrewer.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbb286e43e0e90944f7b76d70d3bee80708461e5
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/colorbrewer.py
@@ -0,0 +1,494 @@
+"""
+Color scales and sequences from the colorbrewer 2 project
+
+Learn more at http://colorbrewer2.org
+
+colorbrewer is made available under an Apache license: http://colorbrewer2.org/export/LICENSE.txt
+"""
+
+from ._swatches import _swatches
+
+
+def swatches(template=None):
+ return _swatches(__name__, globals(), template)
+
+
+swatches.__doc__ = _swatches.__doc__
+
+BrBG = [
+ "rgb(84,48,5)",
+ "rgb(140,81,10)",
+ "rgb(191,129,45)",
+ "rgb(223,194,125)",
+ "rgb(246,232,195)",
+ "rgb(245,245,245)",
+ "rgb(199,234,229)",
+ "rgb(128,205,193)",
+ "rgb(53,151,143)",
+ "rgb(1,102,94)",
+ "rgb(0,60,48)",
+]
+
+PRGn = [
+ "rgb(64,0,75)",
+ "rgb(118,42,131)",
+ "rgb(153,112,171)",
+ "rgb(194,165,207)",
+ "rgb(231,212,232)",
+ "rgb(247,247,247)",
+ "rgb(217,240,211)",
+ "rgb(166,219,160)",
+ "rgb(90,174,97)",
+ "rgb(27,120,55)",
+ "rgb(0,68,27)",
+]
+
+PiYG = [
+ "rgb(142,1,82)",
+ "rgb(197,27,125)",
+ "rgb(222,119,174)",
+ "rgb(241,182,218)",
+ "rgb(253,224,239)",
+ "rgb(247,247,247)",
+ "rgb(230,245,208)",
+ "rgb(184,225,134)",
+ "rgb(127,188,65)",
+ "rgb(77,146,33)",
+ "rgb(39,100,25)",
+]
+
+PuOr = [
+ "rgb(127,59,8)",
+ "rgb(179,88,6)",
+ "rgb(224,130,20)",
+ "rgb(253,184,99)",
+ "rgb(254,224,182)",
+ "rgb(247,247,247)",
+ "rgb(216,218,235)",
+ "rgb(178,171,210)",
+ "rgb(128,115,172)",
+ "rgb(84,39,136)",
+ "rgb(45,0,75)",
+]
+
+RdBu = [
+ "rgb(103,0,31)",
+ "rgb(178,24,43)",
+ "rgb(214,96,77)",
+ "rgb(244,165,130)",
+ "rgb(253,219,199)",
+ "rgb(247,247,247)",
+ "rgb(209,229,240)",
+ "rgb(146,197,222)",
+ "rgb(67,147,195)",
+ "rgb(33,102,172)",
+ "rgb(5,48,97)",
+]
+
+RdGy = [
+ "rgb(103,0,31)",
+ "rgb(178,24,43)",
+ "rgb(214,96,77)",
+ "rgb(244,165,130)",
+ "rgb(253,219,199)",
+ "rgb(255,255,255)",
+ "rgb(224,224,224)",
+ "rgb(186,186,186)",
+ "rgb(135,135,135)",
+ "rgb(77,77,77)",
+ "rgb(26,26,26)",
+]
+
+RdYlBu = [
+ "rgb(165,0,38)",
+ "rgb(215,48,39)",
+ "rgb(244,109,67)",
+ "rgb(253,174,97)",
+ "rgb(254,224,144)",
+ "rgb(255,255,191)",
+ "rgb(224,243,248)",
+ "rgb(171,217,233)",
+ "rgb(116,173,209)",
+ "rgb(69,117,180)",
+ "rgb(49,54,149)",
+]
+
+RdYlGn = [
+ "rgb(165,0,38)",
+ "rgb(215,48,39)",
+ "rgb(244,109,67)",
+ "rgb(253,174,97)",
+ "rgb(254,224,139)",
+ "rgb(255,255,191)",
+ "rgb(217,239,139)",
+ "rgb(166,217,106)",
+ "rgb(102,189,99)",
+ "rgb(26,152,80)",
+ "rgb(0,104,55)",
+]
+
+Spectral = [
+ "rgb(158,1,66)",
+ "rgb(213,62,79)",
+ "rgb(244,109,67)",
+ "rgb(253,174,97)",
+ "rgb(254,224,139)",
+ "rgb(255,255,191)",
+ "rgb(230,245,152)",
+ "rgb(171,221,164)",
+ "rgb(102,194,165)",
+ "rgb(50,136,189)",
+ "rgb(94,79,162)",
+]
+
+Set1 = [
+ "rgb(228,26,28)",
+ "rgb(55,126,184)",
+ "rgb(77,175,74)",
+ "rgb(152,78,163)",
+ "rgb(255,127,0)",
+ "rgb(255,255,51)",
+ "rgb(166,86,40)",
+ "rgb(247,129,191)",
+ "rgb(153,153,153)",
+]
+
+
+Pastel1 = [
+ "rgb(251,180,174)",
+ "rgb(179,205,227)",
+ "rgb(204,235,197)",
+ "rgb(222,203,228)",
+ "rgb(254,217,166)",
+ "rgb(255,255,204)",
+ "rgb(229,216,189)",
+ "rgb(253,218,236)",
+ "rgb(242,242,242)",
+]
+Dark2 = [
+ "rgb(27,158,119)",
+ "rgb(217,95,2)",
+ "rgb(117,112,179)",
+ "rgb(231,41,138)",
+ "rgb(102,166,30)",
+ "rgb(230,171,2)",
+ "rgb(166,118,29)",
+ "rgb(102,102,102)",
+]
+Set2 = [
+ "rgb(102,194,165)",
+ "rgb(252,141,98)",
+ "rgb(141,160,203)",
+ "rgb(231,138,195)",
+ "rgb(166,216,84)",
+ "rgb(255,217,47)",
+ "rgb(229,196,148)",
+ "rgb(179,179,179)",
+]
+
+
+Pastel2 = [
+ "rgb(179,226,205)",
+ "rgb(253,205,172)",
+ "rgb(203,213,232)",
+ "rgb(244,202,228)",
+ "rgb(230,245,201)",
+ "rgb(255,242,174)",
+ "rgb(241,226,204)",
+ "rgb(204,204,204)",
+]
+
+Set3 = [
+ "rgb(141,211,199)",
+ "rgb(255,255,179)",
+ "rgb(190,186,218)",
+ "rgb(251,128,114)",
+ "rgb(128,177,211)",
+ "rgb(253,180,98)",
+ "rgb(179,222,105)",
+ "rgb(252,205,229)",
+ "rgb(217,217,217)",
+ "rgb(188,128,189)",
+ "rgb(204,235,197)",
+ "rgb(255,237,111)",
+]
+
+Accent = [
+ "rgb(127,201,127)",
+ "rgb(190,174,212)",
+ "rgb(253,192,134)",
+ "rgb(255,255,153)",
+ "rgb(56,108,176)",
+ "rgb(240,2,127)",
+ "rgb(191,91,23)",
+ "rgb(102,102,102)",
+]
+
+
+Paired = [
+ "rgb(166,206,227)",
+ "rgb(31,120,180)",
+ "rgb(178,223,138)",
+ "rgb(51,160,44)",
+ "rgb(251,154,153)",
+ "rgb(227,26,28)",
+ "rgb(253,191,111)",
+ "rgb(255,127,0)",
+ "rgb(202,178,214)",
+ "rgb(106,61,154)",
+ "rgb(255,255,153)",
+ "rgb(177,89,40)",
+]
+
+
+Blues = [
+ "rgb(247,251,255)",
+ "rgb(222,235,247)",
+ "rgb(198,219,239)",
+ "rgb(158,202,225)",
+ "rgb(107,174,214)",
+ "rgb(66,146,198)",
+ "rgb(33,113,181)",
+ "rgb(8,81,156)",
+ "rgb(8,48,107)",
+]
+
+BuGn = [
+ "rgb(247,252,253)",
+ "rgb(229,245,249)",
+ "rgb(204,236,230)",
+ "rgb(153,216,201)",
+ "rgb(102,194,164)",
+ "rgb(65,174,118)",
+ "rgb(35,139,69)",
+ "rgb(0,109,44)",
+ "rgb(0,68,27)",
+]
+
+BuPu = [
+ "rgb(247,252,253)",
+ "rgb(224,236,244)",
+ "rgb(191,211,230)",
+ "rgb(158,188,218)",
+ "rgb(140,150,198)",
+ "rgb(140,107,177)",
+ "rgb(136,65,157)",
+ "rgb(129,15,124)",
+ "rgb(77,0,75)",
+]
+
+GnBu = [
+ "rgb(247,252,240)",
+ "rgb(224,243,219)",
+ "rgb(204,235,197)",
+ "rgb(168,221,181)",
+ "rgb(123,204,196)",
+ "rgb(78,179,211)",
+ "rgb(43,140,190)",
+ "rgb(8,104,172)",
+ "rgb(8,64,129)",
+]
+
+Greens = [
+ "rgb(247,252,245)",
+ "rgb(229,245,224)",
+ "rgb(199,233,192)",
+ "rgb(161,217,155)",
+ "rgb(116,196,118)",
+ "rgb(65,171,93)",
+ "rgb(35,139,69)",
+ "rgb(0,109,44)",
+ "rgb(0,68,27)",
+]
+
+Greys = [
+ "rgb(255,255,255)",
+ "rgb(240,240,240)",
+ "rgb(217,217,217)",
+ "rgb(189,189,189)",
+ "rgb(150,150,150)",
+ "rgb(115,115,115)",
+ "rgb(82,82,82)",
+ "rgb(37,37,37)",
+ "rgb(0,0,0)",
+]
+
+OrRd = [
+ "rgb(255,247,236)",
+ "rgb(254,232,200)",
+ "rgb(253,212,158)",
+ "rgb(253,187,132)",
+ "rgb(252,141,89)",
+ "rgb(239,101,72)",
+ "rgb(215,48,31)",
+ "rgb(179,0,0)",
+ "rgb(127,0,0)",
+]
+
+Oranges = [
+ "rgb(255,245,235)",
+ "rgb(254,230,206)",
+ "rgb(253,208,162)",
+ "rgb(253,174,107)",
+ "rgb(253,141,60)",
+ "rgb(241,105,19)",
+ "rgb(217,72,1)",
+ "rgb(166,54,3)",
+ "rgb(127,39,4)",
+]
+
+PuBu = [
+ "rgb(255,247,251)",
+ "rgb(236,231,242)",
+ "rgb(208,209,230)",
+ "rgb(166,189,219)",
+ "rgb(116,169,207)",
+ "rgb(54,144,192)",
+ "rgb(5,112,176)",
+ "rgb(4,90,141)",
+ "rgb(2,56,88)",
+]
+
+PuBuGn = [
+ "rgb(255,247,251)",
+ "rgb(236,226,240)",
+ "rgb(208,209,230)",
+ "rgb(166,189,219)",
+ "rgb(103,169,207)",
+ "rgb(54,144,192)",
+ "rgb(2,129,138)",
+ "rgb(1,108,89)",
+ "rgb(1,70,54)",
+]
+
+PuRd = [
+ "rgb(247,244,249)",
+ "rgb(231,225,239)",
+ "rgb(212,185,218)",
+ "rgb(201,148,199)",
+ "rgb(223,101,176)",
+ "rgb(231,41,138)",
+ "rgb(206,18,86)",
+ "rgb(152,0,67)",
+ "rgb(103,0,31)",
+]
+
+Purples = [
+ "rgb(252,251,253)",
+ "rgb(239,237,245)",
+ "rgb(218,218,235)",
+ "rgb(188,189,220)",
+ "rgb(158,154,200)",
+ "rgb(128,125,186)",
+ "rgb(106,81,163)",
+ "rgb(84,39,143)",
+ "rgb(63,0,125)",
+]
+
+RdPu = [
+ "rgb(255,247,243)",
+ "rgb(253,224,221)",
+ "rgb(252,197,192)",
+ "rgb(250,159,181)",
+ "rgb(247,104,161)",
+ "rgb(221,52,151)",
+ "rgb(174,1,126)",
+ "rgb(122,1,119)",
+ "rgb(73,0,106)",
+]
+
+Reds = [
+ "rgb(255,245,240)",
+ "rgb(254,224,210)",
+ "rgb(252,187,161)",
+ "rgb(252,146,114)",
+ "rgb(251,106,74)",
+ "rgb(239,59,44)",
+ "rgb(203,24,29)",
+ "rgb(165,15,21)",
+ "rgb(103,0,13)",
+]
+
+YlGn = [
+ "rgb(255,255,229)",
+ "rgb(247,252,185)",
+ "rgb(217,240,163)",
+ "rgb(173,221,142)",
+ "rgb(120,198,121)",
+ "rgb(65,171,93)",
+ "rgb(35,132,67)",
+ "rgb(0,104,55)",
+ "rgb(0,69,41)",
+]
+
+YlGnBu = [
+ "rgb(255,255,217)",
+ "rgb(237,248,177)",
+ "rgb(199,233,180)",
+ "rgb(127,205,187)",
+ "rgb(65,182,196)",
+ "rgb(29,145,192)",
+ "rgb(34,94,168)",
+ "rgb(37,52,148)",
+ "rgb(8,29,88)",
+]
+
+YlOrBr = [
+ "rgb(255,255,229)",
+ "rgb(255,247,188)",
+ "rgb(254,227,145)",
+ "rgb(254,196,79)",
+ "rgb(254,153,41)",
+ "rgb(236,112,20)",
+ "rgb(204,76,2)",
+ "rgb(153,52,4)",
+ "rgb(102,37,6)",
+]
+
+YlOrRd = [
+ "rgb(255,255,204)",
+ "rgb(255,237,160)",
+ "rgb(254,217,118)",
+ "rgb(254,178,76)",
+ "rgb(253,141,60)",
+ "rgb(252,78,42)",
+ "rgb(227,26,28)",
+ "rgb(189,0,38)",
+ "rgb(128,0,38)",
+]
+
+Accent_r = Accent[::-1]
+Blues_r = Blues[::-1]
+BrBG_r = BrBG[::-1]
+BuGn_r = BuGn[::-1]
+BuPu_r = BuPu[::-1]
+Dark2_r = Dark2[::-1]
+GnBu_r = GnBu[::-1]
+Greens_r = Greens[::-1]
+Greys_r = Greys[::-1]
+OrRd_r = OrRd[::-1]
+Oranges_r = Oranges[::-1]
+PRGn_r = PRGn[::-1]
+Paired_r = Paired[::-1]
+Pastel1_r = Pastel1[::-1]
+Pastel2_r = Pastel2[::-1]
+PiYG_r = PiYG[::-1]
+PuBu_r = PuBu[::-1]
+PuBuGn_r = PuBuGn[::-1]
+PuOr_r = PuOr[::-1]
+PuRd_r = PuRd[::-1]
+Purples_r = Purples[::-1]
+RdBu_r = RdBu[::-1]
+RdGy_r = RdGy[::-1]
+RdPu_r = RdPu[::-1]
+RdYlBu_r = RdYlBu[::-1]
+RdYlGn_r = RdYlGn[::-1]
+Reds_r = Reds[::-1]
+Set1_r = Set1[::-1]
+Set2_r = Set2[::-1]
+Set3_r = Set3[::-1]
+Spectral_r = Spectral[::-1]
+YlGn_r = YlGn[::-1]
+YlGnBu_r = YlGnBu[::-1]
+YlOrBr_r = YlOrBr[::-1]
+YlOrRd_r = YlOrRd[::-1]
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/cyclical.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/cyclical.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcb7d07e2e3cda931db4014e5a9095448540377e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/cyclical.py
@@ -0,0 +1,157 @@
+"""
+Cyclical color scales are appropriate for continuous data that has a natural cyclical \
+structure, such as temporal data (hour of day, day of week, day of year, seasons) or
+complex numbers or other phase data.
+"""
+
+from ._swatches import _swatches, _swatches_continuous, _swatches_cyclical
+
+
+def swatches(template=None):
+ return _swatches(__name__, globals(), template)
+
+
+swatches.__doc__ = _swatches.__doc__
+
+
+def swatches_continuous(template=None):
+ return _swatches_continuous(__name__, globals(), template)
+
+
+swatches_continuous.__doc__ = _swatches_continuous.__doc__
+
+
+def swatches_cyclical(template=None):
+ return _swatches_cyclical(__name__, globals(), template)
+
+
+swatches_cyclical.__doc__ = _swatches_cyclical.__doc__
+
+
+Twilight = [
+ "#e2d9e2",
+ "#9ebbc9",
+ "#6785be",
+ "#5e43a5",
+ "#421257",
+ "#471340",
+ "#8e2c50",
+ "#ba6657",
+ "#ceac94",
+ "#e2d9e2",
+]
+IceFire = [
+ "#000000",
+ "#001f4d",
+ "#003786",
+ "#0e58a8",
+ "#217eb8",
+ "#30a4ca",
+ "#54c8df",
+ "#9be4ef",
+ "#e1e9d1",
+ "#f3d573",
+ "#e7b000",
+ "#da8200",
+ "#c65400",
+ "#ac2301",
+ "#820000",
+ "#4c0000",
+ "#000000",
+]
+Edge = [
+ "#313131",
+ "#3d019d",
+ "#3810dc",
+ "#2d47f9",
+ "#2593ff",
+ "#2adef6",
+ "#60fdfa",
+ "#aefdff",
+ "#f3f3f1",
+ "#fffda9",
+ "#fafd5b",
+ "#f7da29",
+ "#ff8e25",
+ "#f8432d",
+ "#d90d39",
+ "#97023d",
+ "#313131",
+]
+Phase = [
+ "rgb(167, 119, 12)",
+ "rgb(197, 96, 51)",
+ "rgb(217, 67, 96)",
+ "rgb(221, 38, 163)",
+ "rgb(196, 59, 224)",
+ "rgb(153, 97, 244)",
+ "rgb(95, 127, 228)",
+ "rgb(40, 144, 183)",
+ "rgb(15, 151, 136)",
+ "rgb(39, 153, 79)",
+ "rgb(119, 141, 17)",
+ "rgb(167, 119, 12)",
+]
+HSV = [
+ "#ff0000",
+ "#ffa700",
+ "#afff00",
+ "#08ff00",
+ "#00ff9f",
+ "#00b7ff",
+ "#0010ff",
+ "#9700ff",
+ "#ff00bf",
+ "#ff0000",
+]
+mrybm = [
+ "#f884f7",
+ "#f968c4",
+ "#ea4388",
+ "#cf244b",
+ "#b51a15",
+ "#bd4304",
+ "#cc6904",
+ "#d58f04",
+ "#cfaa27",
+ "#a19f62",
+ "#588a93",
+ "#2269c4",
+ "#3e3ef0",
+ "#6b4ef9",
+ "#956bfa",
+ "#cd7dfe",
+ "#f884f7",
+]
+mygbm = [
+ "#ef55f1",
+ "#fb84ce",
+ "#fbafa1",
+ "#fcd471",
+ "#f0ed35",
+ "#c6e516",
+ "#96d310",
+ "#61c10b",
+ "#31ac28",
+ "#439064",
+ "#3d719a",
+ "#284ec8",
+ "#2e21ea",
+ "#6324f5",
+ "#9139fa",
+ "#c543fa",
+ "#ef55f1",
+]
+
+Edge_r = Edge[::-1]
+HSV_r = HSV[::-1]
+IceFire_r = IceFire[::-1]
+Phase_r = Phase[::-1]
+Twilight_r = Twilight[::-1]
+mrybm_r = mrybm[::-1]
+mygbm_r = mygbm[::-1]
+
+__all__ = [
+ "swatches",
+ "swatches_cyclical",
+]
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/diverging.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/diverging.py
new file mode 100644
index 0000000000000000000000000000000000000000..53170df9c097f81c225b0bc014868393523a1f72
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/diverging.py
@@ -0,0 +1,75 @@
+"""
+Diverging color scales are appropriate for continuous data that has a natural midpoint \
+other otherwise informative special value, such as 0 altitude, or the boiling point
+of a liquid. The color scales in this module are \
+mostly meant to be passed in as the `color_continuous_scale` argument to various \
+functions, and to be used with the `color_continuous_midpoint` argument.
+"""
+
+from .colorbrewer import ( # noqa: F401
+ BrBG,
+ PRGn,
+ PiYG,
+ PuOr,
+ RdBu,
+ RdGy,
+ RdYlBu,
+ RdYlGn,
+ Spectral,
+ BrBG_r,
+ PRGn_r,
+ PiYG_r,
+ PuOr_r,
+ RdBu_r,
+ RdGy_r,
+ RdYlBu_r,
+ RdYlGn_r,
+ Spectral_r,
+)
+from .cmocean import ( # noqa: F401
+ balance,
+ delta,
+ curl,
+ oxy,
+ balance_r,
+ delta_r,
+ curl_r,
+ oxy_r,
+)
+from .carto import ( # noqa: F401
+ Armyrose,
+ Fall,
+ Geyser,
+ Temps,
+ Tealrose,
+ Tropic,
+ Earth,
+ Armyrose_r,
+ Fall_r,
+ Geyser_r,
+ Temps_r,
+ Tealrose_r,
+ Tropic_r,
+ Earth_r,
+)
+
+from .plotlyjs import Picnic, Portland, Picnic_r, Portland_r # noqa: F401
+
+from ._swatches import _swatches, _swatches_continuous
+
+
+def swatches(template=None):
+ return _swatches(__name__, globals(), template)
+
+
+swatches.__doc__ = _swatches.__doc__
+
+
+def swatches_continuous(template=None):
+ return _swatches_continuous(__name__, globals(), template)
+
+
+swatches_continuous.__doc__ = _swatches_continuous.__doc__
+
+
+__all__ = ["swatches"]
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/plotlyjs.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/plotlyjs.py
new file mode 100644
index 0000000000000000000000000000000000000000..a49ae023e5c82d490bf6cd97a8d8d473d8f30c61
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/plotlyjs.py
@@ -0,0 +1,180 @@
+# Copied from
+# https://github.com/plotly/plotly.js/blob/master/src/components/colorscale/scales.js
+
+# NOTE: these differ slightly from plotly.colors.PLOTLY_SCALES from Plotly.js because
+# those ones don't have perfectly evenly spaced steps ...
+# not sure when this skew was introduced, possibly as early as Plotly.py v4.0
+
+Blackbody = [
+ "rgb(0,0,0)",
+ "rgb(230,0,0)",
+ "rgb(230,210,0)",
+ "rgb(255,255,255)",
+ "rgb(160,200,255)",
+]
+Bluered = ["rgb(0,0,255)", "rgb(255,0,0)"]
+Blues = [
+ "rgb(5,10,172)",
+ "rgb(40,60,190)",
+ "rgb(70,100,245)",
+ "rgb(90,120,245)",
+ "rgb(106,137,247)",
+ "rgb(220,220,220)",
+]
+Cividis = [
+ "rgb(0,32,76)",
+ "rgb(0,42,102)",
+ "rgb(0,52,110)",
+ "rgb(39,63,108)",
+ "rgb(60,74,107)",
+ "rgb(76,85,107)",
+ "rgb(91,95,109)",
+ "rgb(104,106,112)",
+ "rgb(117,117,117)",
+ "rgb(131,129,120)",
+ "rgb(146,140,120)",
+ "rgb(161,152,118)",
+ "rgb(176,165,114)",
+ "rgb(192,177,109)",
+ "rgb(209,191,102)",
+ "rgb(225,204,92)",
+ "rgb(243,219,79)",
+ "rgb(255,233,69)",
+]
+Earth = [
+ "rgb(0,0,130)",
+ "rgb(0,180,180)",
+ "rgb(40,210,40)",
+ "rgb(230,230,50)",
+ "rgb(120,70,20)",
+ "rgb(255,255,255)",
+]
+Electric = [
+ "rgb(0,0,0)",
+ "rgb(30,0,100)",
+ "rgb(120,0,100)",
+ "rgb(160,90,0)",
+ "rgb(230,200,0)",
+ "rgb(255,250,220)",
+]
+Greens = [
+ "rgb(0,68,27)",
+ "rgb(0,109,44)",
+ "rgb(35,139,69)",
+ "rgb(65,171,93)",
+ "rgb(116,196,118)",
+ "rgb(161,217,155)",
+ "rgb(199,233,192)",
+ "rgb(229,245,224)",
+ "rgb(247,252,245)",
+]
+Greys = ["rgb(0,0,0)", "rgb(255,255,255)"]
+Hot = ["rgb(0,0,0)", "rgb(230,0,0)", "rgb(255,210,0)", "rgb(255,255,255)"]
+Jet = [
+ "rgb(0,0,131)",
+ "rgb(0,60,170)",
+ "rgb(5,255,255)",
+ "rgb(255,255,0)",
+ "rgb(250,0,0)",
+ "rgb(128,0,0)",
+]
+Picnic = [
+ "rgb(0,0,255)",
+ "rgb(51,153,255)",
+ "rgb(102,204,255)",
+ "rgb(153,204,255)",
+ "rgb(204,204,255)",
+ "rgb(255,255,255)",
+ "rgb(255,204,255)",
+ "rgb(255,153,255)",
+ "rgb(255,102,204)",
+ "rgb(255,102,102)",
+ "rgb(255,0,0)",
+]
+Portland = [
+ "rgb(12,51,131)",
+ "rgb(10,136,186)",
+ "rgb(242,211,56)",
+ "rgb(242,143,56)",
+ "rgb(217,30,30)",
+]
+Rainbow = [
+ "rgb(150,0,90)",
+ "rgb(0,0,200)",
+ "rgb(0,25,255)",
+ "rgb(0,152,255)",
+ "rgb(44,255,150)",
+ "rgb(151,255,0)",
+ "rgb(255,234,0)",
+ "rgb(255,111,0)",
+ "rgb(255,0,0)",
+]
+RdBu = [
+ "rgb(5,10,172)",
+ "rgb(106,137,247)",
+ "rgb(190,190,190)",
+ "rgb(220,170,132)",
+ "rgb(230,145,90)",
+ "rgb(178,10,28)",
+]
+Reds = ["rgb(220,220,220)", "rgb(245,195,157)", "rgb(245,160,105)", "rgb(178,10,28)"]
+Viridis = [
+ "#440154",
+ "#48186a",
+ "#472d7b",
+ "#424086",
+ "#3b528b",
+ "#33638d",
+ "#2c728e",
+ "#26828e",
+ "#21918c",
+ "#1fa088",
+ "#28ae80",
+ "#3fbc73",
+ "#5ec962",
+ "#84d44b",
+ "#addc30",
+ "#d8e219",
+ "#fde725",
+]
+YlGnBu = [
+ "rgb(8,29,88)",
+ "rgb(37,52,148)",
+ "rgb(34,94,168)",
+ "rgb(29,145,192)",
+ "rgb(65,182,196)",
+ "rgb(127,205,187)",
+ "rgb(199,233,180)",
+ "rgb(237,248,217)",
+ "rgb(255,255,217)",
+]
+YlOrRd = [
+ "rgb(128,0,38)",
+ "rgb(189,0,38)",
+ "rgb(227,26,28)",
+ "rgb(252,78,42)",
+ "rgb(253,141,60)",
+ "rgb(254,178,76)",
+ "rgb(254,217,118)",
+ "rgb(255,237,160)",
+ "rgb(255,255,204)",
+]
+
+Blackbody_r = Blackbody[::-1]
+Bluered_r = Bluered[::-1]
+Blues_r = Blues[::-1]
+Cividis_r = Cividis[::-1]
+Earth_r = Earth[::-1]
+Electric_r = Electric[::-1]
+Greens_r = Greens[::-1]
+Greys_r = Greys[::-1]
+Hot_r = Hot[::-1]
+Jet_r = Jet[::-1]
+Picnic_r = Picnic[::-1]
+Portland_r = Portland[::-1]
+Rainbow_r = Rainbow[::-1]
+RdBu_r = RdBu[::-1]
+Reds_r = Reds[::-1]
+Viridis_r = Viridis[::-1]
+YlGnBu_r = YlGnBu[::-1]
+YlOrRd_r = YlOrRd[::-1]
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/qualitative.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/qualitative.py
new file mode 100644
index 0000000000000000000000000000000000000000..c26a55783a790bd9c9f4a2fe32c0fe54a09d04c4
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/qualitative.py
@@ -0,0 +1,184 @@
+"""
+Qualitative color sequences are appropriate for data that has no natural ordering, such \
+as categories, colors, names, countries etc. The color sequences in this module are \
+mostly meant to be passed in as the `color_discrete_sequence` argument to various functions.
+"""
+
+from ._swatches import _swatches
+
+
+def swatches(template=None):
+ return _swatches(__name__, globals(), template)
+
+
+swatches.__doc__ = _swatches.__doc__
+
+Plotly = [
+ "#636EFA",
+ "#EF553B",
+ "#00CC96",
+ "#AB63FA",
+ "#FFA15A",
+ "#19D3F3",
+ "#FF6692",
+ "#B6E880",
+ "#FF97FF",
+ "#FECB52",
+]
+
+D3 = [
+ "#1F77B4",
+ "#FF7F0E",
+ "#2CA02C",
+ "#D62728",
+ "#9467BD",
+ "#8C564B",
+ "#E377C2",
+ "#7F7F7F",
+ "#BCBD22",
+ "#17BECF",
+]
+G10 = [
+ "#3366CC",
+ "#DC3912",
+ "#FF9900",
+ "#109618",
+ "#990099",
+ "#0099C6",
+ "#DD4477",
+ "#66AA00",
+ "#B82E2E",
+ "#316395",
+]
+T10 = [
+ "#4C78A8",
+ "#F58518",
+ "#E45756",
+ "#72B7B2",
+ "#54A24B",
+ "#EECA3B",
+ "#B279A2",
+ "#FF9DA6",
+ "#9D755D",
+ "#BAB0AC",
+]
+Alphabet = [
+ "#AA0DFE",
+ "#3283FE",
+ "#85660D",
+ "#782AB6",
+ "#565656",
+ "#1C8356",
+ "#16FF32",
+ "#F7E1A0",
+ "#E2E2E2",
+ "#1CBE4F",
+ "#C4451C",
+ "#DEA0FD",
+ "#FE00FA",
+ "#325A9B",
+ "#FEAF16",
+ "#F8A19F",
+ "#90AD1C",
+ "#F6222E",
+ "#1CFFCE",
+ "#2ED9FF",
+ "#B10DA1",
+ "#C075A6",
+ "#FC1CBF",
+ "#B00068",
+ "#FBE426",
+ "#FA0087",
+]
+Dark24 = [
+ "#2E91E5",
+ "#E15F99",
+ "#1CA71C",
+ "#FB0D0D",
+ "#DA16FF",
+ "#222A2A",
+ "#B68100",
+ "#750D86",
+ "#EB663B",
+ "#511CFB",
+ "#00A08B",
+ "#FB00D1",
+ "#FC0080",
+ "#B2828D",
+ "#6C7C32",
+ "#778AAE",
+ "#862A16",
+ "#A777F1",
+ "#620042",
+ "#1616A7",
+ "#DA60CA",
+ "#6C4516",
+ "#0D2A63",
+ "#AF0038",
+]
+Light24 = [
+ "#FD3216",
+ "#00FE35",
+ "#6A76FC",
+ "#FED4C4",
+ "#FE00CE",
+ "#0DF9FF",
+ "#F6F926",
+ "#FF9616",
+ "#479B55",
+ "#EEA6FB",
+ "#DC587D",
+ "#D626FF",
+ "#6E899C",
+ "#00B5F7",
+ "#B68E00",
+ "#C9FBE5",
+ "#FF0092",
+ "#22FFA7",
+ "#E3EE9E",
+ "#86CE00",
+ "#BC7196",
+ "#7E7DCD",
+ "#FC6955",
+ "#E48F72",
+]
+
+Alphabet_r = Alphabet[::-1]
+D3_r = D3[::-1]
+Dark24_r = Dark24[::-1]
+G10_r = G10[::-1]
+Light24_r = Light24[::-1]
+Plotly_r = Plotly[::-1]
+T10_r = T10[::-1]
+
+from .colorbrewer import ( # noqa: E402 F401
+ Set1,
+ Pastel1,
+ Dark2,
+ Set2,
+ Pastel2,
+ Set3,
+ Set1_r,
+ Pastel1_r,
+ Dark2_r,
+ Set2_r,
+ Pastel2_r,
+ Set3_r,
+)
+from .carto import ( # noqa: E402 F401
+ Antique,
+ Bold,
+ Pastel,
+ Prism,
+ Safe,
+ Vivid,
+ Antique_r,
+ Bold_r,
+ Pastel_r,
+ Prism_r,
+ Safe_r,
+ Vivid_r,
+)
+
+
+__all__ = ["swatches"]
diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/sequential.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/sequential.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e9ccf6b6fb2465677b031305ad307d4dd2ebae5
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/colors/sequential.py
@@ -0,0 +1,257 @@
+"""
+Sequential color scales are appropriate for most continuous data, but in some cases it \
+can be helpful to use a `plotly.colors.diverging` or \
+`plotly.colors.cyclical` scale instead. The color scales in this module are \
+mostly meant to be passed in as the `color_continuous_scale` argument to various functions.
+"""
+
+from ._swatches import _swatches, _swatches_continuous
+
+
+def swatches(template=None):
+ return _swatches(__name__, globals(), template)
+
+
+swatches.__doc__ = _swatches.__doc__
+
+
+def swatches_continuous(template=None):
+ return _swatches_continuous(__name__, globals(), template)
+
+
+swatches_continuous.__doc__ = _swatches_continuous.__doc__
+
+Plotly3 = [
+ "#0508b8",
+ "#1910d8",
+ "#3c19f0",
+ "#6b1cfb",
+ "#981cfd",
+ "#bf1cfd",
+ "#dd2bfd",
+ "#f246fe",
+ "#fc67fd",
+ "#fe88fc",
+ "#fea5fd",
+ "#febefe",
+ "#fec3fe",
+]
+
+Viridis = [
+ "#440154",
+ "#482878",
+ "#3e4989",
+ "#31688e",
+ "#26828e",
+ "#1f9e89",
+ "#35b779",
+ "#6ece58",
+ "#b5de2b",
+ "#fde725",
+]
+Cividis = [
+ "#00224e",
+ "#123570",
+ "#3b496c",
+ "#575d6d",
+ "#707173",
+ "#8a8678",
+ "#a59c74",
+ "#c3b369",
+ "#e1cc55",
+ "#fee838",
+]
+
+Inferno = [
+ "#000004",
+ "#1b0c41",
+ "#4a0c6b",
+ "#781c6d",
+ "#a52c60",
+ "#cf4446",
+ "#ed6925",
+ "#fb9b06",
+ "#f7d13d",
+ "#fcffa4",
+]
+Magma = [
+ "#000004",
+ "#180f3d",
+ "#440f76",
+ "#721f81",
+ "#9e2f7f",
+ "#cd4071",
+ "#f1605d",
+ "#fd9668",
+ "#feca8d",
+ "#fcfdbf",
+]
+Plasma = [
+ "#0d0887",
+ "#46039f",
+ "#7201a8",
+ "#9c179e",
+ "#bd3786",
+ "#d8576b",
+ "#ed7953",
+ "#fb9f3a",
+ "#fdca26",
+ "#f0f921",
+]
+Turbo = [
+ "#30123b",
+ "#4145ab",
+ "#4675ed",
+ "#39a2fc",
+ "#1bcfd4",
+ "#24eca6",
+ "#61fc6c",
+ "#a4fc3b",
+ "#d1e834",
+ "#f3c63a",
+ "#fe9b2d",
+ "#f36315",
+ "#d93806",
+ "#b11901",
+ "#7a0402",
+]
+
+Cividis_r = Cividis[::-1]
+Inferno_r = Inferno[::-1]
+Magma_r = Magma[::-1]
+Plasma_r = Plasma[::-1]
+Plotly3_r = Plotly3[::-1]
+Turbo_r = Turbo[::-1]
+Viridis_r = Viridis[::-1]
+
+from .plotlyjs import ( # noqa: E402 F401
+ Blackbody,
+ Bluered,
+ Electric,
+ Hot,
+ Jet,
+ Rainbow,
+ Blackbody_r,
+ Bluered_r,
+ Electric_r,
+ Hot_r,
+ Jet_r,
+ Rainbow_r,
+)
+
+from .colorbrewer import ( # noqa: E402 F401
+ Blues,
+ BuGn,
+ BuPu,
+ GnBu,
+ Greens,
+ Greys,
+ OrRd,
+ Oranges,
+ PuBu,
+ PuBuGn,
+ PuRd,
+ Purples,
+ RdBu,
+ RdPu,
+ Reds,
+ YlGn,
+ YlGnBu,
+ YlOrBr,
+ YlOrRd,
+ Blues_r,
+ BuGn_r,
+ BuPu_r,
+ GnBu_r,
+ Greens_r,
+ Greys_r,
+ OrRd_r,
+ Oranges_r,
+ PuBu_r,
+ PuBuGn_r,
+ PuRd_r,
+ Purples_r,
+ RdBu_r,
+ RdPu_r,
+ Reds_r,
+ YlGn_r,
+ YlGnBu_r,
+ YlOrBr_r,
+ YlOrRd_r,
+)
+
+from .cmocean import ( # noqa: E402 F401
+ turbid,
+ thermal,
+ haline,
+ solar,
+ ice,
+ gray,
+ deep,
+ dense,
+ algae,
+ matter,
+ speed,
+ amp,
+ tempo,
+ turbid_r,
+ thermal_r,
+ haline_r,
+ solar_r,
+ ice_r,
+ gray_r,
+ deep_r,
+ dense_r,
+ algae_r,
+ matter_r,
+ speed_r,
+ amp_r,
+ tempo_r,
+)
+
+from .carto import ( # noqa: E402 F401
+ Burg,
+ Burgyl,
+ Redor,
+ Oryel,
+ Peach,
+ Pinkyl,
+ Mint,
+ Blugrn,
+ Darkmint,
+ Emrld,
+ Aggrnyl,
+ Bluyl,
+ Teal,
+ Tealgrn,
+ Purp,
+ Purpor,
+ Sunset,
+ Magenta,
+ Sunsetdark,
+ Agsunset,
+ Brwnyl,
+ Burg_r,
+ Burgyl_r,
+ Redor_r,
+ Oryel_r,
+ Peach_r,
+ Pinkyl_r,
+ Mint_r,
+ Blugrn_r,
+ Darkmint_r,
+ Emrld_r,
+ Aggrnyl_r,
+ Bluyl_r,
+ Teal_r,
+ Tealgrn_r,
+ Purp_r,
+ Purpor_r,
+ Sunset_r,
+ Magenta_r,
+ Sunsetdark_r,
+ Agsunset_r,
+ Brwnyl_r,
+)
+
+__all__ = ["swatches"]
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/__config__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/__config__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b07bdeb21604b8ea66ae49252917c05b6090b710
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/__config__.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8bdbbec1c5204292d5fe4f39014cffb9dd2b9ec6
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_array_api_info.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_array_api_info.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21ecb3f15c0959114b5bc60a6302adfe4f5583e0
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_array_api_info.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_configtool.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_configtool.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3a7f2ab2611b4586bdabc19efc2cbe3e7512158
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_configtool.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_distributor_init.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_distributor_init.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4477420b96824ad0d7545a1d8f89a1b069993499
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_distributor_init.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_expired_attrs_2_0.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_expired_attrs_2_0.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..88c7d962083f8a4b3fd808210c67a398002a2adf
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_expired_attrs_2_0.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_globals.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_globals.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26bd37d741e766b1da73e471cc4cc18acd873b07
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_globals.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_pytesttester.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_pytesttester.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..51af4d5c642594fdd7d2aa5043fc5b002f59e7e2
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/_pytesttester.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/conftest.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/conftest.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ba88c5ce2a58a5009dda3dee3df114e07bda7824
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/conftest.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/dtypes.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/dtypes.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f8f8fecaee85e5dadae3620a28be3720a4756c27
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/dtypes.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/exceptions.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/exceptions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e29a81381efcb954ba7566c8fe44d35a88f0669
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/exceptions.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/matlib.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/matlib.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1dc3c7aefb0d63827f725d426bae923b633fcd88
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/matlib.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/version.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/version.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ea24833f0dec6d0aa637410e12359c193c35c625
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/__pycache__/version.cpython-312.pyc differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/__init__.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ede50aaeefc3f595ed7e5993eadfba6d044fd94c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/__init__.py
@@ -0,0 +1,203 @@
+"""
+Contains the core of NumPy: ndarray, ufuncs, dtypes, etc.
+
+Please note that this module is private. All functions and objects
+are available in the main ``numpy`` namespace - use that instead.
+
+"""
+
+import os
+
+from numpy.version import version as __version__
+
+# disables OpenBLAS affinity setting of the main thread that limits
+# python threads or processes to one core
+env_added = []
+for envkey in ['OPENBLAS_MAIN_FREE']:
+ if envkey not in os.environ:
+ # Note: using `putenv` (and `unsetenv` further down) instead of updating
+ # `os.environ` on purpose to avoid a race condition, see gh-30627.
+ os.putenv(envkey, '1')
+ env_added.append(envkey)
+
+try:
+ from . import multiarray
+except ImportError as exc:
+ import sys
+
+ # Bypass for the module re-initialization opt-out
+ if exc.msg == "cannot load module more than once per process":
+ raise
+
+ # Basically always, the problem should be that the C module is wrong/missing...
+ if (
+ isinstance(exc, ModuleNotFoundError)
+ and exc.name == "numpy._core._multiarray_umath"
+ ):
+ import sys
+ candidates = []
+ for path in __path__:
+ candidates.extend(
+ f for f in os.listdir(path) if f.startswith("_multiarray_umath"))
+ if len(candidates) == 0:
+ bad_c_module_info = (
+ "We found no compiled module, did NumPy build successfully?\n")
+ else:
+ candidate_str = '\n * '.join(candidates)
+ # cache_tag is documented to be possibly None, so just use name if it is
+ # this guesses at cache_tag being the same as the extension module scheme
+ tag = sys.implementation.cache_tag or sys.implementation.name
+ bad_c_module_info = (
+ f"The following compiled module files exist, but seem incompatible\n"
+ f"with with either python '{tag}' or the "
+ f"platform '{sys.platform}':\n\n * {candidate_str}\n"
+ )
+ else:
+ bad_c_module_info = ""
+
+ major, minor, *_ = sys.version_info
+ msg = f"""
+
+IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
+
+Importing the numpy C-extensions failed. This error can happen for
+many reasons, often due to issues with your setup or how NumPy was
+installed.
+{bad_c_module_info}
+We have compiled some common reasons and troubleshooting tips at:
+
+ https://numpy.org/devdocs/user/troubleshooting-importerror.html
+
+Please note and check the following:
+
+ * The Python version is: Python {major}.{minor} from "{sys.executable}"
+ * The NumPy version is: "{__version__}"
+
+and make sure that they are the versions you expect.
+
+Please carefully study the information and documentation linked above.
+This is unlikely to be a NumPy issue but will be caused by a bad install
+or environment on your machine.
+
+Original error was: {exc}
+"""
+
+ raise ImportError(msg) from exc
+finally:
+ for envkey in env_added:
+ os.unsetenv(envkey)
+del envkey
+del env_added
+del os
+
+from . import umath
+
+# Check that multiarray,umath are pure python modules wrapping
+# _multiarray_umath and not either of the old c-extension modules
+if not (hasattr(multiarray, '_multiarray_umath') and
+ hasattr(umath, '_multiarray_umath')):
+ import sys
+ path = sys.modules['numpy'].__path__
+ msg = ("Something is wrong with the numpy installation. "
+ "While importing we detected an older version of "
+ "numpy in {}. One method of fixing this is to repeatedly uninstall "
+ "numpy until none is found, then reinstall this version.")
+ raise ImportError(msg.format(path))
+
+from . import numerictypes as nt
+from .numerictypes import sctypeDict, sctypes
+
+multiarray.set_typeDict(nt.sctypeDict)
+from . import einsumfunc, fromnumeric, function_base, getlimits, numeric, shape_base
+from .einsumfunc import *
+from .fromnumeric import *
+from .function_base import *
+from .getlimits import *
+
+# Note: module name memmap is overwritten by a class with same name
+from .memmap import *
+from .numeric import *
+from .records import recarray, record
+from .shape_base import *
+
+del nt
+
+# do this after everything else, to minimize the chance of this misleadingly
+# appearing in an import-time traceback
+# add these for module-freeze analysis (like PyInstaller)
+from . import (
+ _add_newdocs,
+ _add_newdocs_scalars,
+ _dtype,
+ _dtype_ctypes,
+ _internal,
+ _methods,
+)
+from .numeric import absolute as abs
+
+acos = numeric.arccos
+acosh = numeric.arccosh
+asin = numeric.arcsin
+asinh = numeric.arcsinh
+atan = numeric.arctan
+atanh = numeric.arctanh
+atan2 = numeric.arctan2
+concat = numeric.concatenate
+bitwise_left_shift = numeric.left_shift
+bitwise_invert = numeric.invert
+bitwise_right_shift = numeric.right_shift
+permute_dims = numeric.transpose
+pow = numeric.power
+
+__all__ = [
+ "abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "atan2",
+ "bitwise_invert", "bitwise_left_shift", "bitwise_right_shift", "concat",
+ "pow", "permute_dims", "memmap", "sctypeDict", "record", "recarray"
+]
+__all__ += numeric.__all__
+__all__ += function_base.__all__
+__all__ += getlimits.__all__
+__all__ += shape_base.__all__
+__all__ += einsumfunc.__all__
+
+
+def _ufunc_reduce(func):
+ # Report the `__name__`. pickle will try to find the module. Note that
+ # pickle supports for this `__name__` to be a `__qualname__`. It may
+ # make sense to add a `__qualname__` to ufuncs, to allow this more
+ # explicitly (Numba has ufuncs as attributes).
+ # See also: https://github.com/dask/distributed/issues/3450
+ return func.__name__
+
+
+def _DType_reconstruct(scalar_type):
+ # This is a work-around to pickle type(np.dtype(np.float64)), etc.
+ # and it should eventually be replaced with a better solution, e.g. when
+ # DTypes become HeapTypes.
+ return type(dtype(scalar_type))
+
+
+def _DType_reduce(DType):
+ # As types/classes, most DTypes can simply be pickled by their name:
+ if not DType._legacy or DType.__module__ == "numpy.dtypes":
+ return DType.__name__
+
+ # However, user defined legacy dtypes (like rational) do not end up in
+ # `numpy.dtypes` as module and do not have a public class at all.
+ # For these, we pickle them by reconstructing them from the scalar type:
+ scalar_type = DType.type
+ return _DType_reconstruct, (scalar_type,)
+
+
+import copyreg
+
+copyreg.pickle(ufunc, _ufunc_reduce)
+copyreg.pickle(type(dtype), _DType_reduce, _DType_reconstruct)
+
+# Unclutter namespace (must keep _*_reconstruct for unpickling)
+del copyreg, _ufunc_reduce, _DType_reduce
+
+from numpy._pytesttester import PytestTester
+
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/__init__.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..ce5427bbfcd97a93ae04c9d3a48177f3ae258ca2
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/__init__.pyi
@@ -0,0 +1,666 @@
+# keep in sync with https://github.com/numpy/numtype/blob/main/src/numpy-stubs/_core/__init__.pyi
+
+from ._asarray import require
+from ._ufunc_config import (
+ errstate,
+ getbufsize,
+ geterr,
+ geterrcall,
+ setbufsize,
+ seterr,
+ seterrcall,
+)
+from .arrayprint import (
+ array2string,
+ array_repr,
+ array_str,
+ format_float_positional,
+ format_float_scientific,
+ get_printoptions,
+ printoptions,
+ set_printoptions,
+)
+from .einsumfunc import einsum, einsum_path
+from .fromnumeric import (
+ all,
+ amax,
+ amin,
+ any,
+ argmax,
+ argmin,
+ argpartition,
+ argsort,
+ around,
+ choose,
+ clip,
+ compress,
+ cumprod,
+ cumsum,
+ cumulative_prod,
+ cumulative_sum,
+ diagonal,
+ matrix_transpose,
+ max,
+ mean,
+ min,
+ ndim,
+ nonzero,
+ partition,
+ prod,
+ ptp,
+ put,
+ ravel,
+ repeat,
+ reshape,
+ resize,
+ round,
+ searchsorted,
+ shape,
+ size,
+ sort,
+ squeeze,
+ std,
+ sum,
+ swapaxes,
+ take,
+ trace,
+ transpose,
+ transpose as permute_dims,
+ var,
+)
+from .function_base import geomspace, linspace, logspace
+from .getlimits import finfo, iinfo
+from .memmap import memmap
+from .numeric import (
+ False_,
+ True_,
+ allclose,
+ arange,
+ argwhere,
+ array,
+ array_equal,
+ array_equiv,
+ asanyarray,
+ asarray,
+ ascontiguousarray,
+ asfortranarray,
+ astype,
+ base_repr,
+ binary_repr,
+ bitwise_not,
+ broadcast,
+ can_cast,
+ concatenate,
+ concatenate as concat,
+ convolve,
+ copyto,
+ correlate,
+ count_nonzero,
+ cross,
+ dot,
+ dtype,
+ empty,
+ empty_like,
+ flatiter,
+ flatnonzero,
+ from_dlpack,
+ frombuffer,
+ fromfile,
+ fromfunction,
+ fromiter,
+ fromstring,
+ full,
+ full_like,
+ identity,
+ indices,
+ inf,
+ inner,
+ isclose,
+ isfortran,
+ isscalar,
+ lexsort,
+ little_endian,
+ matmul,
+ may_share_memory,
+ min_scalar_type,
+ moveaxis,
+ nan,
+ ndarray,
+ nditer,
+ nested_iters,
+ newaxis,
+ ones,
+ ones_like,
+ outer,
+ promote_types,
+ putmask,
+ result_type,
+ roll,
+ rollaxis,
+ shares_memory,
+ tensordot,
+ ufunc,
+ vdot,
+ vecdot,
+ where,
+ zeros,
+ zeros_like,
+)
+from .numerictypes import (
+ ScalarType,
+ bool,
+ bool_,
+ busday_count,
+ busday_offset,
+ busdaycalendar,
+ byte,
+ bytes_,
+ cdouble,
+ character,
+ clongdouble,
+ complex64,
+ complex128,
+ complex192,
+ complex256,
+ complexfloating,
+ csingle,
+ datetime64,
+ datetime_as_string,
+ datetime_data,
+ double,
+ flexible,
+ float16,
+ float32,
+ float64,
+ float96,
+ float128,
+ floating,
+ generic,
+ half,
+ inexact,
+ int8,
+ int16,
+ int32,
+ int64,
+ int_,
+ intc,
+ integer,
+ intp,
+ is_busday,
+ isdtype,
+ issubdtype,
+ long,
+ longdouble,
+ longlong,
+ number,
+ object_,
+ sctypeDict,
+ short,
+ signedinteger,
+ single,
+ str_,
+ timedelta64,
+ typecodes,
+ ubyte,
+ uint,
+ uint8,
+ uint16,
+ uint32,
+ uint64,
+ uintc,
+ uintp,
+ ulong,
+ ulonglong,
+ unsignedinteger,
+ ushort,
+ void,
+)
+from .records import recarray, record
+from .shape_base import (
+ atleast_1d,
+ atleast_2d,
+ atleast_3d,
+ block,
+ hstack,
+ stack,
+ unstack,
+ vstack,
+)
+from .umath import (
+ absolute,
+ absolute as abs,
+ add,
+ arccos,
+ arccos as acos,
+ arccosh,
+ arccosh as acosh,
+ arcsin,
+ arcsin as asin,
+ arcsinh,
+ arcsinh as asinh,
+ arctan,
+ arctan as atan,
+ arctan2,
+ arctan2 as atan2,
+ arctanh,
+ arctanh as atanh,
+ bitwise_and,
+ bitwise_count,
+ bitwise_or,
+ bitwise_xor,
+ cbrt,
+ ceil,
+ conj,
+ conjugate,
+ copysign,
+ cos,
+ cosh,
+ deg2rad,
+ degrees,
+ divide,
+ divmod,
+ e,
+ equal,
+ euler_gamma,
+ exp,
+ exp2,
+ expm1,
+ fabs,
+ float_power,
+ floor,
+ floor_divide,
+ fmax,
+ fmin,
+ fmod,
+ frexp,
+ frompyfunc,
+ gcd,
+ greater,
+ greater_equal,
+ heaviside,
+ hypot,
+ invert,
+ invert as bitwise_invert,
+ isfinite,
+ isinf,
+ isnan,
+ isnat,
+ lcm,
+ ldexp,
+ left_shift,
+ left_shift as bitwise_left_shift,
+ less,
+ less_equal,
+ log,
+ log1p,
+ log2,
+ log10,
+ logaddexp,
+ logaddexp2,
+ logical_and,
+ logical_not,
+ logical_or,
+ logical_xor,
+ matvec,
+ maximum,
+ minimum,
+ mod,
+ modf,
+ multiply,
+ negative,
+ nextafter,
+ not_equal,
+ pi,
+ positive,
+ power,
+ power as pow,
+ rad2deg,
+ radians,
+ reciprocal,
+ remainder,
+ right_shift,
+ right_shift as bitwise_right_shift,
+ rint,
+ sign,
+ signbit,
+ sin,
+ sinh,
+ spacing,
+ sqrt,
+ square,
+ subtract,
+ tan,
+ tanh,
+ true_divide,
+ trunc,
+ vecmat,
+)
+
+__all__ = [
+ "False_",
+ "ScalarType",
+ "True_",
+ "abs",
+ "absolute",
+ "acos",
+ "acosh",
+ "add",
+ "all",
+ "allclose",
+ "amax",
+ "amin",
+ "any",
+ "arange",
+ "arccos",
+ "arccosh",
+ "arcsin",
+ "arcsinh",
+ "arctan",
+ "arctan2",
+ "arctanh",
+ "argmax",
+ "argmin",
+ "argpartition",
+ "argsort",
+ "argwhere",
+ "around",
+ "array",
+ "array2string",
+ "array_equal",
+ "array_equiv",
+ "array_repr",
+ "array_str",
+ "asanyarray",
+ "asarray",
+ "ascontiguousarray",
+ "asfortranarray",
+ "asin",
+ "asinh",
+ "astype",
+ "atan",
+ "atan2",
+ "atanh",
+ "atleast_1d",
+ "atleast_2d",
+ "atleast_3d",
+ "base_repr",
+ "binary_repr",
+ "bitwise_and",
+ "bitwise_count",
+ "bitwise_invert",
+ "bitwise_left_shift",
+ "bitwise_not",
+ "bitwise_or",
+ "bitwise_right_shift",
+ "bitwise_xor",
+ "block",
+ "bool",
+ "bool_",
+ "broadcast",
+ "busday_count",
+ "busday_offset",
+ "busdaycalendar",
+ "byte",
+ "bytes_",
+ "can_cast",
+ "cbrt",
+ "cdouble",
+ "ceil",
+ "character",
+ "choose",
+ "clip",
+ "clongdouble",
+ "complex64",
+ "complex128",
+ "complex192",
+ "complex256",
+ "complexfloating",
+ "compress",
+ "concat",
+ "concatenate",
+ "conj",
+ "conjugate",
+ "convolve",
+ "copysign",
+ "copyto",
+ "correlate",
+ "cos",
+ "cosh",
+ "count_nonzero",
+ "cross",
+ "csingle",
+ "cumprod",
+ "cumsum",
+ "cumulative_prod",
+ "cumulative_sum",
+ "datetime64",
+ "datetime_as_string",
+ "datetime_data",
+ "deg2rad",
+ "degrees",
+ "diagonal",
+ "divide",
+ "divmod",
+ "dot",
+ "double",
+ "dtype",
+ "e",
+ "einsum",
+ "einsum_path",
+ "empty",
+ "empty_like",
+ "equal",
+ "errstate",
+ "euler_gamma",
+ "exp",
+ "exp2",
+ "expm1",
+ "fabs",
+ "finfo",
+ "flatiter",
+ "flatnonzero",
+ "flexible",
+ "float16",
+ "float32",
+ "float64",
+ "float96",
+ "float128",
+ "float_power",
+ "floating",
+ "floor",
+ "floor_divide",
+ "fmax",
+ "fmin",
+ "fmod",
+ "format_float_positional",
+ "format_float_scientific",
+ "frexp",
+ "from_dlpack",
+ "frombuffer",
+ "fromfile",
+ "fromfunction",
+ "fromiter",
+ "frompyfunc",
+ "fromstring",
+ "full",
+ "full_like",
+ "gcd",
+ "generic",
+ "geomspace",
+ "get_printoptions",
+ "getbufsize",
+ "geterr",
+ "geterrcall",
+ "greater",
+ "greater_equal",
+ "half",
+ "heaviside",
+ "hstack",
+ "hypot",
+ "identity",
+ "iinfo",
+ "indices",
+ "inexact",
+ "inf",
+ "inner",
+ "int8",
+ "int16",
+ "int32",
+ "int64",
+ "int_",
+ "intc",
+ "integer",
+ "intp",
+ "invert",
+ "is_busday",
+ "isclose",
+ "isdtype",
+ "isfinite",
+ "isfortran",
+ "isinf",
+ "isnan",
+ "isnat",
+ "isscalar",
+ "issubdtype",
+ "lcm",
+ "ldexp",
+ "left_shift",
+ "less",
+ "less_equal",
+ "lexsort",
+ "linspace",
+ "little_endian",
+ "log",
+ "log1p",
+ "log2",
+ "log10",
+ "logaddexp",
+ "logaddexp2",
+ "logical_and",
+ "logical_not",
+ "logical_or",
+ "logical_xor",
+ "logspace",
+ "long",
+ "longdouble",
+ "longlong",
+ "matmul",
+ "matrix_transpose",
+ "matvec",
+ "max",
+ "maximum",
+ "may_share_memory",
+ "mean",
+ "memmap",
+ "min",
+ "min_scalar_type",
+ "minimum",
+ "mod",
+ "modf",
+ "moveaxis",
+ "multiply",
+ "nan",
+ "ndarray",
+ "ndim",
+ "nditer",
+ "negative",
+ "nested_iters",
+ "newaxis",
+ "nextafter",
+ "nonzero",
+ "not_equal",
+ "number",
+ "object_",
+ "ones",
+ "ones_like",
+ "outer",
+ "partition",
+ "permute_dims",
+ "pi",
+ "positive",
+ "pow",
+ "power",
+ "printoptions",
+ "prod",
+ "promote_types",
+ "ptp",
+ "put",
+ "putmask",
+ "rad2deg",
+ "radians",
+ "ravel",
+ "recarray",
+ "reciprocal",
+ "record",
+ "remainder",
+ "repeat",
+ "require",
+ "reshape",
+ "resize",
+ "result_type",
+ "right_shift",
+ "rint",
+ "roll",
+ "rollaxis",
+ "round",
+ "sctypeDict",
+ "searchsorted",
+ "set_printoptions",
+ "setbufsize",
+ "seterr",
+ "seterrcall",
+ "shape",
+ "shares_memory",
+ "short",
+ "sign",
+ "signbit",
+ "signedinteger",
+ "sin",
+ "single",
+ "sinh",
+ "size",
+ "sort",
+ "spacing",
+ "sqrt",
+ "square",
+ "squeeze",
+ "stack",
+ "std",
+ "str_",
+ "subtract",
+ "sum",
+ "swapaxes",
+ "take",
+ "tan",
+ "tanh",
+ "tensordot",
+ "timedelta64",
+ "trace",
+ "transpose",
+ "true_divide",
+ "trunc",
+ "typecodes",
+ "ubyte",
+ "ufunc",
+ "uint",
+ "uint8",
+ "uint16",
+ "uint32",
+ "uint64",
+ "uintc",
+ "uintp",
+ "ulong",
+ "ulonglong",
+ "unsignedinteger",
+ "unstack",
+ "ushort",
+ "var",
+ "vdot",
+ "vecdot",
+ "vecmat",
+ "void",
+ "vstack",
+ "where",
+ "zeros",
+ "zeros_like",
+]
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_add_newdocs.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..178bcc9f813dc0293cdae94cf3a4b5ea5199ff2e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_add_newdocs.py
@@ -0,0 +1,7161 @@
+"""
+This is only meant to add docs to objects defined in C-extension modules.
+The purpose is to allow easier editing of the docstrings without
+requiring a re-compile.
+
+NOTE: Many of the methods of ndarray have corresponding functions.
+ If you update these docstrings, please keep also the ones in
+ _core/fromnumeric.py, matrixlib/defmatrix.py up-to-date.
+
+"""
+
+import textwrap
+
+from numpy._core.function_base import add_newdoc
+from numpy._core.overrides import get_array_function_like_doc # noqa: F401
+
+###############################################################################
+#
+# flatiter
+#
+# flatiter needs a toplevel description
+#
+###############################################################################
+
+add_newdoc('numpy._core', 'flatiter',
+ """
+ Flat iterator object to iterate over arrays.
+
+ A `flatiter` iterator is returned by ``x.flat`` for any array `x`.
+ It allows iterating over the array as if it were a 1-D array,
+ either in a for-loop or by calling its `next` method.
+
+ Iteration is done in row-major, C-style order (the last
+ index varying the fastest). The iterator can also be indexed using
+ basic slicing or advanced indexing.
+
+ See Also
+ --------
+ ndarray.flat : Return a flat iterator over an array.
+ ndarray.flatten : Returns a flattened copy of an array.
+
+ Notes
+ -----
+ A `flatiter` iterator can not be constructed directly from Python code
+ by calling the `flatiter` constructor.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2, 3)
+ >>> fl = x.flat
+ >>> type(fl)
+
+ >>> for item in fl:
+ ... print(item)
+ ...
+ 0
+ 1
+ 2
+ 3
+ 4
+ 5
+
+ >>> fl[2:4]
+ array([2, 3])
+
+ """)
+
+# flatiter attributes
+
+add_newdoc('numpy._core', 'flatiter', ('base',
+ """
+ A reference to the array that is iterated over.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(5)
+ >>> fl = x.flat
+ >>> fl.base is x
+ True
+
+ """))
+
+add_newdoc('numpy._core', 'flatiter', ('coords',
+ """
+ An N-dimensional tuple of current coordinates.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2, 3)
+ >>> fl = x.flat
+ >>> fl.coords
+ (0, 0)
+ >>> next(fl)
+ 0
+ >>> fl.coords
+ (0, 1)
+
+ """))
+
+add_newdoc('numpy._core', 'flatiter', ('index',
+ """
+ Current flat index into the array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2, 3)
+ >>> fl = x.flat
+ >>> fl.index
+ 0
+ >>> next(fl)
+ 0
+ >>> fl.index
+ 1
+
+ """))
+
+# flatiter methods
+
+add_newdoc('numpy._core', 'flatiter', ('__array__',
+ """
+ __array__($self, dtype=None, /, *, copy=None)
+ --
+
+ flat.__array__([dtype], *, copy=None)
+
+ Get array from iterator
+
+ """))
+
+add_newdoc('numpy._core', 'flatiter', ('copy',
+ """
+ copy($self, /)
+ --
+
+ flat.copy()
+
+ Get a copy of the iterator as a 1-D array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2, 3)
+ >>> x
+ array([[0, 1, 2],
+ [3, 4, 5]])
+ >>> fl = x.flat
+ >>> fl.copy()
+ array([0, 1, 2, 3, 4, 5])
+
+ """))
+
+
+###############################################################################
+#
+# nditer
+#
+###############################################################################
+
+add_newdoc('numpy._core', 'nditer',
+ """
+ nditer(
+ op,
+ flags=None,
+ op_flags=None,
+ op_dtypes=None,
+ order='K',
+ casting='safe',
+ op_axes=None,
+ itershape=None,
+ buffersize=0,
+ )
+ --
+
+ nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K',
+ casting='safe', op_axes=None, itershape=None, buffersize=0)
+
+ Efficient multi-dimensional iterator object to iterate over arrays.
+ To get started using this object, see the
+ :ref:`introductory guide to array iteration `.
+
+ Parameters
+ ----------
+ op : ndarray or sequence of array_like
+ The array(s) to iterate over.
+ flags : sequence of str, optional
+ Flags to control the behavior of the iterator.
+
+ * ``buffered`` enables buffering when required.
+ * ``c_index`` causes a C-order index to be tracked.
+ * ``f_index`` causes a Fortran-order index to be tracked.
+ * ``multi_index`` causes a multi-index, or a tuple of indices
+ with one per iteration dimension, to be tracked.
+ * ``common_dtype`` causes all the operands to be converted to
+ a common data type, with copying or buffering as necessary.
+ * ``copy_if_overlap`` causes the iterator to determine if read
+ operands have overlap with write operands, and make temporary
+ copies as necessary to avoid overlap. False positives (needless
+ copying) are possible in some cases.
+ * ``delay_bufalloc`` delays allocation of the buffers until
+ a reset() call is made. Allows ``allocate`` operands to
+ be initialized before their values are copied into the buffers.
+ * ``external_loop`` causes the ``values`` given to be
+ one-dimensional arrays with multiple values instead of
+ zero-dimensional arrays.
+ * ``grow_inner`` allows the ``value`` array sizes to be made
+ larger than the buffer size when both ``buffered`` and
+ ``external_loop`` is used.
+ * ``ranged`` allows the iterator to be restricted to a sub-range
+ of the iterindex values.
+ * ``refs_ok`` enables iteration of reference types, such as
+ object arrays.
+ * ``reduce_ok`` enables iteration of ``readwrite`` operands
+ which are broadcasted, also known as reduction operands.
+ * ``zerosize_ok`` allows `itersize` to be zero.
+ op_flags : list of list of str, optional
+ This is a list of flags for each operand. At minimum, one of
+ ``readonly``, ``readwrite``, or ``writeonly`` must be specified.
+
+ * ``readonly`` indicates the operand will only be read from.
+ * ``readwrite`` indicates the operand will be read from and written to.
+ * ``writeonly`` indicates the operand will only be written to.
+ * ``no_broadcast`` prevents the operand from being broadcasted.
+ * ``contig`` forces the operand data to be contiguous.
+ * ``aligned`` forces the operand data to be aligned.
+ * ``nbo`` forces the operand data to be in native byte order.
+ * ``copy`` allows a temporary read-only copy if required.
+ * ``updateifcopy`` allows a temporary read-write copy if required.
+ * ``allocate`` causes the array to be allocated if it is None
+ in the ``op`` parameter.
+ * ``no_subtype`` prevents an ``allocate`` operand from using a subtype.
+ * ``arraymask`` indicates that this operand is the mask to use
+ for selecting elements when writing to operands with the
+ 'writemasked' flag set. The iterator does not enforce this,
+ but when writing from a buffer back to the array, it only
+ copies those elements indicated by this mask.
+ * ``writemasked`` indicates that only elements where the chosen
+ ``arraymask`` operand is True will be written to.
+ * ``overlap_assume_elementwise`` can be used to mark operands that are
+ accessed only in the iterator order, to allow less conservative
+ copying when ``copy_if_overlap`` is present.
+ op_dtypes : dtype or tuple of dtype(s), optional
+ The required data type(s) of the operands. If copying or buffering
+ is enabled, the data will be converted to/from their original types.
+ order : {'C', 'F', 'A', 'K'}, optional
+ Controls the iteration order. 'C' means C order, 'F' means
+ Fortran order, 'A' means 'F' order if all the arrays are Fortran
+ contiguous, 'C' order otherwise, and 'K' means as close to the
+ order the array elements appear in memory as possible. This also
+ affects the element memory order of ``allocate`` operands, as they
+ are allocated to be compatible with iteration order.
+ Default is 'K'.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur when making a copy
+ or buffering. Setting this to 'unsafe' is not recommended,
+ as it can adversely affect accumulations.
+
+ * 'no' means the data types should not be cast at all.
+ * 'equiv' means only byte-order changes are allowed.
+ * 'safe' means only casts which can preserve values are allowed.
+ * 'same_kind' means only safe casts or casts within a kind,
+ like float64 to float32, are allowed.
+ * 'unsafe' means any data conversions may be done.
+ op_axes : list of list of ints, optional
+ If provided, is a list of ints or None for each operands.
+ The list of axes for an operand is a mapping from the dimensions
+ of the iterator to the dimensions of the operand. A value of
+ -1 can be placed for entries, causing that dimension to be
+ treated as `newaxis`.
+ itershape : tuple of ints, optional
+ The desired shape of the iterator. This allows ``allocate`` operands
+ with a dimension mapped by op_axes not corresponding to a dimension
+ of a different operand to get a value not equal to 1 for that
+ dimension.
+ buffersize : int, optional
+ When buffering is enabled, controls the size of the temporary
+ buffers. Set to 0 for the default value.
+
+ Attributes
+ ----------
+ dtypes : tuple of dtype(s)
+ The data types of the values provided in `value`. This may be
+ different from the operand data types if buffering is enabled.
+ Valid only before the iterator is closed.
+ finished : bool
+ Whether the iteration over the operands is finished or not.
+ has_delayed_bufalloc : bool
+ If True, the iterator was created with the ``delay_bufalloc`` flag,
+ and no reset() function was called on it yet.
+ has_index : bool
+ If True, the iterator was created with either the ``c_index`` or
+ the ``f_index`` flag, and the property `index` can be used to
+ retrieve it.
+ has_multi_index : bool
+ If True, the iterator was created with the ``multi_index`` flag,
+ and the property `multi_index` can be used to retrieve it.
+ index
+ When the ``c_index`` or ``f_index`` flag was used, this property
+ provides access to the index. Raises a ValueError if accessed
+ and ``has_index`` is False.
+ iterationneedsapi : bool
+ Whether iteration requires access to the Python API, for example
+ if one of the operands is an object array.
+ iterindex : int
+ An index which matches the order of iteration.
+ itersize : int
+ Size of the iterator.
+ itviews
+ Structured view(s) of `operands` in memory, matching the reordered
+ and optimized iterator access pattern. Valid only before the iterator
+ is closed.
+ multi_index
+ When the ``multi_index`` flag was used, this property
+ provides access to the index. Raises a ValueError if accessed
+ accessed and ``has_multi_index`` is False.
+ ndim : int
+ The dimensions of the iterator.
+ nop : int
+ The number of iterator operands.
+ operands : tuple of operand(s)
+ The array(s) to be iterated over. Valid only before the iterator is
+ closed.
+ shape : tuple of ints
+ Shape tuple, the shape of the iterator.
+ value
+ Value of ``operands`` at current iteration. Normally, this is a
+ tuple of array scalars, but if the flag ``external_loop`` is used,
+ it is a tuple of one dimensional arrays.
+
+ Notes
+ -----
+ `nditer` supersedes `flatiter`. The iterator implementation behind
+ `nditer` is also exposed by the NumPy C API.
+
+ The Python exposure supplies two iteration interfaces, one which follows
+ the Python iterator protocol, and another which mirrors the C-style
+ do-while pattern. The native Python approach is better in most cases, but
+ if you need the coordinates or index of an iterator, use the C-style pattern.
+
+ Examples
+ --------
+ Here is how we might write an ``iter_add`` function, using the
+ Python iterator protocol:
+
+ >>> import numpy as np
+
+ >>> def iter_add_py(x, y, out=None):
+ ... addop = np.add
+ ... it = np.nditer([x, y, out], [],
+ ... [['readonly'], ['readonly'], ['writeonly','allocate']])
+ ... with it:
+ ... for (a, b, c) in it:
+ ... addop(a, b, out=c)
+ ... return it.operands[2]
+
+ Here is the same function, but following the C-style pattern:
+
+ >>> def iter_add(x, y, out=None):
+ ... addop = np.add
+ ... it = np.nditer([x, y, out], [],
+ ... [['readonly'], ['readonly'], ['writeonly','allocate']])
+ ... with it:
+ ... while not it.finished:
+ ... addop(it[0], it[1], out=it[2])
+ ... it.iternext()
+ ... return it.operands[2]
+
+ Here is an example outer product function:
+
+ >>> def outer_it(x, y, out=None):
+ ... mulop = np.multiply
+ ... it = np.nditer([x, y, out], ['external_loop'],
+ ... [['readonly'], ['readonly'], ['writeonly', 'allocate']],
+ ... op_axes=[list(range(x.ndim)) + [-1] * y.ndim,
+ ... [-1] * x.ndim + list(range(y.ndim)),
+ ... None])
+ ... with it:
+ ... for (a, b, c) in it:
+ ... mulop(a, b, out=c)
+ ... return it.operands[2]
+
+ >>> a = np.arange(2)+1
+ >>> b = np.arange(3)+1
+ >>> outer_it(a,b)
+ array([[1, 2, 3],
+ [2, 4, 6]])
+
+ Here is an example function which operates like a "lambda" ufunc:
+
+ >>> def luf(lamdaexpr, *args, **kwargs):
+ ... '''luf(lambdaexpr, op1, ..., opn, out=None, order='K', casting='safe', buffersize=0)'''
+ ... nargs = len(args)
+ ... op = (kwargs.get('out',None),) + args
+ ... it = np.nditer(op, ['buffered','external_loop'],
+ ... [['writeonly','allocate','no_broadcast']] +
+ ... [['readonly','nbo','aligned']]*nargs,
+ ... order=kwargs.get('order','K'),
+ ... casting=kwargs.get('casting','safe'),
+ ... buffersize=kwargs.get('buffersize',0))
+ ... while not it.finished:
+ ... it[0] = lamdaexpr(*it[1:])
+ ... it.iternext()
+ ... return it.operands[0]
+
+ >>> a = np.arange(5)
+ >>> b = np.ones(5)
+ >>> luf(lambda i,j:i*i + j/2, a, b)
+ array([ 0.5, 1.5, 4.5, 9.5, 16.5])
+
+ If operand flags ``"writeonly"`` or ``"readwrite"`` are used the
+ operands may be views into the original data with the
+ `WRITEBACKIFCOPY` flag. In this case `nditer` must be used as a
+ context manager or the `nditer.close` method must be called before
+ using the result. The temporary data will be written back to the
+ original data when the :meth:`~object.__exit__` function is called
+ but not before:
+
+ >>> a = np.arange(6, dtype='i4')[::-2]
+ >>> with np.nditer(a, [],
+ ... [['writeonly', 'updateifcopy']],
+ ... casting='unsafe',
+ ... op_dtypes=[np.dtype('f4')]) as i:
+ ... x = i.operands[0]
+ ... x[:] = [-1, -2, -3]
+ ... # a still unchanged here
+ >>> a, x
+ (array([-1, -2, -3], dtype=int32), array([-1., -2., -3.], dtype=float32))
+
+ It is important to note that once the iterator is exited, dangling
+ references (like `x` in the example) may or may not share data with
+ the original data `a`. If writeback semantics were active, i.e. if
+ `x.base.flags.writebackifcopy` is `True`, then exiting the iterator
+ will sever the connection between `x` and `a`, writing to `x` will
+ no longer write to `a`. If writeback semantics are not active, then
+ `x.data` will still point at some part of `a.data`, and writing to
+ one will affect the other.
+
+ Context management and the `close` method appeared in version 1.15.0.
+
+ """)
+
+# nditer attributes
+
+add_newdoc('numpy._core', 'nditer', ('operands',
+ """
+ operands[`Slice`]
+
+ The array(s) to be iterated over. Valid only before the iterator is closed.
+ """))
+
+# nditer methods
+
+add_newdoc('numpy._core', 'nditer', ('copy',
+ """
+ copy($self, /)
+ --
+
+ copy()
+
+ Get a copy of the iterator in its current state.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(10)
+ >>> y = x + 1
+ >>> it = np.nditer([x, y])
+ >>> next(it)
+ (array(0), array(1))
+ >>> it2 = it.copy()
+ >>> next(it2)
+ (array(1), array(2))
+
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('debug_print',
+ """
+ debug_print($self, /)
+ --
+
+ debug_print()
+
+ Print the current state of the `nditer` instance and debug info to stdout.
+
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('enable_external_loop',
+ """
+ enable_external_loop($self, /)
+ --
+
+ enable_external_loop()
+
+ When the "external_loop" was not used during construction, but
+ is desired, this modifies the iterator to behave as if the flag
+ was specified.
+
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('iternext',
+ """
+ iternext($self, /)
+ --
+
+ iternext()
+
+ Check whether iterations are left, and perform a single internal iteration
+ without returning the result. Used in the C-style pattern do-while
+ pattern. For an example, see `nditer`.
+
+ Returns
+ -------
+ iternext : bool
+ Whether or not there are iterations left.
+
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('remove_axis',
+ """
+ remove_axis($self, i, /)
+ --
+
+ remove_axis(i, /)
+
+ Removes axis `i` from the iterator. Requires that the flag "multi_index"
+ be enabled.
+
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('remove_multi_index',
+ """
+ remove_multi_index($self, /)
+ --
+
+ remove_multi_index()
+
+ When the "multi_index" flag was specified, this removes it, allowing
+ the internal iteration structure to be optimized further.
+
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('reset',
+ """
+ reset($self, /)
+ --
+
+ reset()
+
+ Reset the iterator to its initial state.
+
+ """))
+
+add_newdoc('numpy._core', 'nditer', ('close',
+ """
+ close($self, /)
+ --
+
+ close()
+
+ Resolve all writeback semantics in writeable operands.
+
+ See Also
+ --------
+ :ref:`nditer-context-manager`
+
+ """))
+
+# nested_iters
+
+add_newdoc('numpy._core', 'nested_iters',
+ """
+ nested_iters(
+ op,
+ axes,
+ flags=None,
+ op_flags=None,
+ op_dtypes=None,
+ order='K',
+ casting='safe',
+ buffersize=0,
+ )
+ --
+
+ nested_iters(op, axes, flags=None, op_flags=None, op_dtypes=None,
+ order='K', casting='safe', buffersize=0)
+
+ Create nditers for use in nested loops
+
+ Create a tuple of `nditer` objects which iterate in nested loops over
+ different axes of the op argument. The first iterator is used in the
+ outermost loop, the last in the innermost loop. Advancing one will
+ change the subsequent iterators to point at its new element.
+
+ Parameters
+ ----------
+ op : ndarray or sequence of array_like
+ The array(s) to iterate over.
+ axes : list of list of int
+ Each item is used as an "op_axes" argument to an nditer
+ flags, op_flags, op_dtypes, order, casting, buffersize (optional)
+ See `nditer` parameters of the same name
+
+ Returns
+ -------
+ iters : tuple of nditer
+ An nditer for each item in `axes`, outermost first
+
+ See Also
+ --------
+ nditer
+
+ Examples
+ --------
+
+ Basic usage. Note how y is the "flattened" version of
+ [a[:, 0, :], a[:, 1, 0], a[:, 2, :]] since we specified
+ the first iter's axes as [1]
+
+ >>> import numpy as np
+ >>> a = np.arange(12).reshape(2, 3, 2)
+ >>> i, j = np.nested_iters(a, [[1], [0, 2]], flags=["multi_index"])
+ >>> for x in i:
+ ... print(i.multi_index)
+ ... for y in j:
+ ... print('', j.multi_index, y)
+ (0,)
+ (0, 0) 0
+ (0, 1) 1
+ (1, 0) 6
+ (1, 1) 7
+ (1,)
+ (0, 0) 2
+ (0, 1) 3
+ (1, 0) 8
+ (1, 1) 9
+ (2,)
+ (0, 0) 4
+ (0, 1) 5
+ (1, 0) 10
+ (1, 1) 11
+
+ """)
+
+###############################################################################
+#
+# broadcast
+#
+###############################################################################
+
+add_newdoc('numpy._core', 'broadcast',
+ """
+ broadcast(*arrays)
+ --
+
+ Produce an object that mimics broadcasting.
+
+ Parameters
+ ----------
+ in1, in2, ... : array_like
+ Input parameters.
+
+ Returns
+ -------
+ b : broadcast object
+ Broadcast the input parameters against one another, and
+ return an object that encapsulates the result.
+ Amongst others, it has ``shape`` and ``nd`` properties, and
+ may be used as an iterator.
+
+ See Also
+ --------
+ broadcast_arrays
+ broadcast_to
+ broadcast_shapes
+
+ Examples
+ --------
+
+ Manually adding two vectors, using broadcasting:
+
+ >>> import numpy as np
+ >>> x = np.array([[1], [2], [3]])
+ >>> y = np.array([4, 5, 6])
+ >>> b = np.broadcast(x, y)
+
+ >>> out = np.empty(b.shape)
+ >>> out.flat = [u+v for (u,v) in b]
+ >>> out
+ array([[5., 6., 7.],
+ [6., 7., 8.],
+ [7., 8., 9.]])
+
+ Compare against built-in broadcasting:
+
+ >>> x + y
+ array([[5, 6, 7],
+ [6, 7, 8],
+ [7, 8, 9]])
+
+ """)
+
+# attributes
+
+add_newdoc('numpy._core', 'broadcast', ('index',
+ """
+ current index in broadcasted result
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> x = np.array([[1], [2], [3]])
+ >>> y = np.array([4, 5, 6])
+ >>> b = np.broadcast(x, y)
+ >>> b.index
+ 0
+ >>> next(b), next(b), next(b)
+ ((1, 4), (1, 5), (1, 6))
+ >>> b.index
+ 3
+
+ """))
+
+add_newdoc('numpy._core', 'broadcast', ('iters',
+ """
+ tuple of iterators along ``self``'s "components."
+
+ Returns a tuple of `numpy.flatiter` objects, one for each "component"
+ of ``self``.
+
+ See Also
+ --------
+ numpy.flatiter
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> row, col = b.iters
+ >>> next(row), next(col)
+ (1, 4)
+
+ """))
+
+add_newdoc('numpy._core', 'broadcast', ('ndim',
+ """
+ Number of dimensions of broadcasted result. Alias for `nd`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> b.ndim
+ 2
+
+ """))
+
+add_newdoc('numpy._core', 'broadcast', ('nd',
+ """
+ Number of dimensions of broadcasted result. For code intended for NumPy
+ 1.12.0 and later the more consistent `ndim` is preferred.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> b.nd
+ 2
+
+ """))
+
+add_newdoc('numpy._core', 'broadcast', ('numiter',
+ """
+ Number of iterators possessed by the broadcasted result.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> b.numiter
+ 2
+
+ """))
+
+add_newdoc('numpy._core', 'broadcast', ('shape',
+ """
+ Shape of broadcasted result.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> b.shape
+ (3, 3)
+
+ """))
+
+add_newdoc('numpy._core', 'broadcast', ('size',
+ """
+ Total size of broadcasted result.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> b.size
+ 9
+
+ """))
+
+# methods
+
+add_newdoc('numpy._core', 'broadcast', ('reset',
+ """
+ reset($self, /)
+ --
+
+ reset()
+
+ Reset the broadcasted result's iterator(s).
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ None
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> y = np.array([[4], [5], [6]])
+ >>> b = np.broadcast(x, y)
+ >>> b.index
+ 0
+ >>> next(b), next(b), next(b)
+ ((1, 4), (2, 4), (3, 4))
+ >>> b.index
+ 3
+ >>> b.reset()
+ >>> b.index
+ 0
+
+ """))
+
+###############################################################################
+#
+# numpy functions
+#
+###############################################################################
+
+add_newdoc('numpy._core.multiarray', 'array',
+ """
+ array(
+ object,
+ dtype=None,
+ *,
+ copy=True,
+ order='K',
+ subok=False,
+ ndmin=0,
+ ndmax=0,
+ like=None,
+ )
+ --
+
+ array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0,
+ ndmax=0, like=None)
+
+ Create an array.
+
+ Parameters
+ ----------
+ object : array_like
+ An array, any object exposing the array interface, an object whose
+ ``__array__`` method returns an array, or any (nested) sequence.
+ If object is a scalar, a 0-dimensional array containing object is
+ returned.
+ dtype : data-type, optional
+ The desired data-type for the array. If not given, NumPy will try to use
+ a default ``dtype`` that can represent the values (by applying promotion
+ rules when necessary.)
+ copy : bool, optional
+ If ``True`` (default), then the array data is copied. If ``None``,
+ a copy will only be made if ``__array__`` returns a copy, if obj is
+ a nested sequence, or if a copy is needed to satisfy any of the other
+ requirements (``dtype``, ``order``, etc.). Note that any copy of
+ the data is shallow, i.e., for arrays with object dtype, the new
+ array will point to the same objects. See Examples for `ndarray.copy`.
+ For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
+ Default: ``True``.
+ order : {'K', 'A', 'C', 'F'}, optional
+ Specify the memory layout of the array. If object is not an array, the
+ newly created array will be in C order (row major) unless 'F' is
+ specified, in which case it will be in Fortran order (column major).
+ If object is an array the following holds.
+
+ ===== ========= ===================================================
+ order no copy copy=True
+ ===== ========= ===================================================
+ 'K' unchanged F & C order preserved, otherwise most similar order
+ 'A' unchanged F order if input is F and not C, otherwise C order
+ 'C' C order C order
+ 'F' F order F order
+ ===== ========= ===================================================
+
+ When ``copy=None`` and a copy is made for other reasons, the result is
+ the same as if ``copy=True``, with some exceptions for 'A', see the
+ Notes section. The default order is 'K'.
+ subok : bool, optional
+ If True, then sub-classes will be passed-through, otherwise
+ the returned array will be forced to be a base-class array (default).
+ ndmin : int, optional
+ Specifies the minimum number of dimensions that the resulting
+ array should have. Ones will be prepended to the shape as
+ needed to meet this requirement.
+ ndmax : int, optional
+ Specifies the maximum number of dimensions to create when inferring
+ shape from nested sequences. By default (ndmax=0), NumPy recurses
+ through all nesting levels (up to the compile-time constant
+ ``NPY_MAXDIMS``).
+ Setting ``ndmax`` stops recursion at the specified depth, preserving
+ deeper nested structures as objects instead of promoting them to
+ higher-dimensional arrays. In this case, ``dtype=object`` is required.
+
+ .. versionadded:: 2.4.0
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ An array object satisfying the specified requirements.
+
+ See Also
+ --------
+ empty_like : Return an empty array with shape and type of input.
+ ones_like : Return an array of ones with shape and type of input.
+ zeros_like : Return an array of zeros with shape and type of input.
+ full_like : Return a new array with shape of input filled with value.
+ empty : Return a new uninitialized array.
+ ones : Return a new array setting values to one.
+ zeros : Return a new array setting values to zero.
+ full : Return a new array of given shape filled with value.
+ copy : Return an array copy of the given object.
+
+
+ Notes
+ -----
+ When order is 'A' and ``object`` is an array in neither 'C' nor 'F' order,
+ and a copy is forced by a change in dtype, then the order of the result is
+ not necessarily 'C' as expected. This is likely a bug.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.array([1, 2, 3])
+ array([1, 2, 3])
+
+ Upcasting:
+
+ >>> np.array([1, 2, 3.0])
+ array([ 1., 2., 3.])
+
+ More than one dimension:
+
+ >>> np.array([[1, 2], [3, 4]])
+ array([[1, 2],
+ [3, 4]])
+
+ Minimum dimensions 2:
+
+ >>> np.array([1, 2, 3], ndmin=2)
+ array([[1, 2, 3]])
+
+ Type provided:
+
+ >>> np.array([1, 2, 3], dtype=complex)
+ array([ 1.+0.j, 2.+0.j, 3.+0.j])
+
+ Data-type consisting of more than one element:
+
+ >>> x = np.array([(1,2),(3,4)],dtype=[('a','>> x['a']
+ array([1, 3], dtype=int32)
+
+ Creating an array from sub-classes:
+
+ >>> np.array(np.asmatrix('1 2; 3 4'))
+ array([[1, 2],
+ [3, 4]])
+
+ >>> np.array(np.asmatrix('1 2; 3 4'), subok=True)
+ matrix([[1, 2],
+ [3, 4]])
+
+ Limiting the maximum dimensions with ``ndmax``:
+
+ >>> a = np.array([[1, 2], [3, 4]], dtype=object, ndmax=2)
+ >>> a
+ array([[1, 2],
+ [3, 4]], dtype=object)
+ >>> a.shape
+ (2, 2)
+
+ >>> b = np.array([[1, 2], [3, 4]], dtype=object, ndmax=1)
+ >>> b
+ array([list([1, 2]), list([3, 4])], dtype=object)
+ >>> b.shape
+ (2,)
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'asarray',
+ """
+ asarray(a, dtype=None, order=None, *, device=None, copy=None, like=None)
+ --
+
+ asarray(a, dtype=None, order=None, *, device=None, copy=None, like=None)
+
+ Convert the input to an array.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data, in any form that can be converted to an array. This
+ includes lists, lists of tuples, tuples, tuples of tuples, tuples
+ of lists and ndarrays.
+ dtype : data-type, optional
+ By default, the data-type is inferred from the input data.
+ order : {'C', 'F', 'A', 'K'}, optional
+ The memory layout of the output.
+ 'C' gives a row-major layout (C-style),
+ 'F' gives a column-major layout (Fortran-style).
+ 'C' and 'F' will copy if needed to ensure the output format.
+ 'A' (any) is equivalent to 'F' if input a is non-contiguous or Fortran-contiguous, otherwise, it is equivalent to 'C'.
+ Unlike 'C' or 'F', 'A' does not ensure that the result is contiguous.
+ 'K' (keep) is the default and preserves the input order for the output.
+ device : str, optional
+ The device on which to place the created array. Default: ``None``.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+ copy : bool, optional
+ If ``True``, then the object is copied. If ``None`` then the object is
+ copied only if needed, i.e. if ``__array__`` returns a copy, if obj
+ is a nested sequence, or if a copy is needed to satisfy any of
+ the other requirements (``dtype``, ``order``, etc.).
+ For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
+ Default: ``None``.
+
+ .. versionadded:: 2.0.0
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Array interpretation of ``a``. No copy is performed if the input
+ is already an ndarray with matching dtype and order. If ``a`` is a
+ subclass of ndarray, a base class ndarray is returned.
+
+ See Also
+ --------
+ asanyarray : Similar function which passes through subclasses.
+ ascontiguousarray : Convert input to a contiguous array.
+ asfortranarray : Convert input to an ndarray with column-major memory order.
+ asarray_chkfinite : Similar function which checks input for NaNs and Infs.
+ fromiter : Create an array from an iterator.
+ fromfunction : Construct an array by executing a function on grid positions.
+
+ Examples
+ --------
+ Convert a list into an array:
+
+ >>> a = [1, 2]
+ >>> import numpy as np
+ >>> np.asarray(a)
+ array([1, 2])
+
+ Existing arrays are not copied:
+
+ >>> a = np.array([1, 2])
+ >>> np.asarray(a) is a
+ True
+
+ If `dtype` is set, array is copied only if dtype does not match:
+
+ >>> a = np.array([1, 2], dtype=np.float32)
+ >>> np.shares_memory(np.asarray(a, dtype=np.float32), a)
+ True
+ >>> np.shares_memory(np.asarray(a, dtype=np.float64), a)
+ False
+
+ Contrary to `asanyarray`, ndarray subclasses are not passed through:
+
+ >>> issubclass(np.recarray, np.ndarray)
+ True
+ >>> a = np.array([(1., 2), (3., 4)], dtype='f4,i4').view(np.recarray)
+ >>> np.asarray(a) is a
+ False
+ >>> np.asanyarray(a) is a
+ True
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'asanyarray',
+ """
+ asanyarray(a, dtype=None, order=None, *, device=None, copy=None, like=None)
+ --
+
+ asanyarray(a, dtype=None, order=None, *, device=None, copy=None, like=None)
+
+ Convert the input to an ndarray, but pass ndarray subclasses through.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data, in any form that can be converted to an array. This
+ includes scalars, lists, lists of tuples, tuples, tuples of tuples,
+ tuples of lists, and ndarrays.
+ dtype : data-type, optional
+ By default, the data-type is inferred from the input data.
+ order : {'C', 'F', 'A', 'K'}, optional
+ The memory layout of the output.
+ 'C' gives a row-major layout (C-style),
+ 'F' gives a column-major layout (Fortran-style).
+ 'C' and 'F' will copy if needed to ensure the output format.
+ 'A' (any) is equivalent to 'F' if input a is non-contiguous or Fortran-contiguous, otherwise, it is equivalent to 'C'.
+ Unlike 'C' or 'F', 'A' does not ensure that the result is contiguous.
+ 'K' (keep) preserves the input order for the output.
+ 'C' is the default.
+ device : str, optional
+ The device on which to place the created array. Default: ``None``.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.1.0
+
+ copy : bool, optional
+ If ``True``, then the object is copied. If ``None`` then the object is
+ copied only if needed, i.e. if ``__array__`` returns a copy, if obj
+ is a nested sequence, or if a copy is needed to satisfy any of
+ the other requirements (``dtype``, ``order``, etc.).
+ For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
+ Default: ``None``.
+
+ .. versionadded:: 2.1.0
+
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray or an ndarray subclass
+ Array interpretation of `a`. If `a` is an ndarray or a subclass
+ of ndarray, it is returned as-is and no copy is performed.
+
+ See Also
+ --------
+ asarray : Similar function which always returns ndarrays.
+ ascontiguousarray : Convert input to a contiguous array.
+ asfortranarray : Convert input to an ndarray with column-major memory order.
+ asarray_chkfinite : Similar function which checks input for NaNs and Infs.
+ fromiter : Create an array from an iterator.
+ fromfunction : Construct an array by executing a function on grid positions.
+
+ Examples
+ --------
+ Convert a list into an array:
+
+ >>> a = [1, 2]
+ >>> import numpy as np
+ >>> np.asanyarray(a)
+ array([1, 2])
+
+ Instances of `ndarray` subclasses are passed through as-is:
+
+ >>> a = np.array([(1., 2), (3., 4)], dtype='f4,i4').view(np.recarray)
+ >>> np.asanyarray(a) is a
+ True
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'ascontiguousarray',
+ """
+ ascontiguousarray(a, dtype=None, *, like=None)
+ --
+
+ ascontiguousarray(a, dtype=None, *, like=None)
+
+ Return a contiguous array (ndim >= 1) in memory (C order).
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ dtype : str or dtype object, optional
+ Data-type of returned array.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Contiguous array of same shape and content as `a`, with type `dtype`
+ if specified.
+
+ See Also
+ --------
+ asfortranarray : Convert input to an ndarray with column-major memory order.
+ require : Return an ndarray that satisfies requirements.
+ ndarray.flags : Information about the memory layout of the array.
+
+ Examples
+ --------
+ Starting with a Fortran-contiguous array:
+
+ >>> import numpy as np
+ >>> x = np.ones((2, 3), order='F')
+ >>> x.flags['F_CONTIGUOUS']
+ True
+
+ Calling ``ascontiguousarray`` makes a C-contiguous copy:
+
+ >>> y = np.ascontiguousarray(x)
+ >>> y.flags['C_CONTIGUOUS']
+ True
+ >>> np.may_share_memory(x, y)
+ False
+
+ Now, starting with a C-contiguous array:
+
+ >>> x = np.ones((2, 3), order='C')
+ >>> x.flags['C_CONTIGUOUS']
+ True
+
+ Then, calling ``ascontiguousarray`` returns the same object:
+
+ >>> y = np.ascontiguousarray(x)
+ >>> x is y
+ True
+
+ Note: This function returns an array with at least one-dimension (1-d)
+ so it will not preserve 0-d arrays.
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'asfortranarray',
+ """
+ asfortranarray(a, dtype=None, *, like=None)
+ --
+
+ asfortranarray(a, dtype=None, *, like=None)
+
+ Return an array (ndim >= 1) laid out in Fortran order in memory.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ dtype : str or dtype object, optional
+ By default, the data-type is inferred from the input data.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ The input `a` in Fortran, or column-major, order.
+
+ See Also
+ --------
+ ascontiguousarray : Convert input to a contiguous (C order) array.
+ asanyarray : Convert input to an ndarray with either row or
+ column-major memory order.
+ require : Return an ndarray that satisfies requirements.
+ ndarray.flags : Information about the memory layout of the array.
+
+ Examples
+ --------
+ Starting with a C-contiguous array:
+
+ >>> import numpy as np
+ >>> x = np.ones((2, 3), order='C')
+ >>> x.flags['C_CONTIGUOUS']
+ True
+
+ Calling ``asfortranarray`` makes a Fortran-contiguous copy:
+
+ >>> y = np.asfortranarray(x)
+ >>> y.flags['F_CONTIGUOUS']
+ True
+ >>> np.may_share_memory(x, y)
+ False
+
+ Now, starting with a Fortran-contiguous array:
+
+ >>> x = np.ones((2, 3), order='F')
+ >>> x.flags['F_CONTIGUOUS']
+ True
+
+ Then, calling ``asfortranarray`` returns the same object:
+
+ >>> y = np.asfortranarray(x)
+ >>> x is y
+ True
+
+ Note: This function returns an array with at least one-dimension (1-d)
+ so it will not preserve 0-d arrays.
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'empty',
+ """
+ empty(shape, dtype=None, order='C', *, device=None, like=None)
+ --
+
+ empty(shape, dtype=None, order='C', *, device=None, like=None)
+
+ Return a new array of given shape and type, without initializing entries.
+
+ Parameters
+ ----------
+ shape : int or tuple of int
+ Shape of the empty array, e.g., ``(2, 3)`` or ``2``.
+ dtype : data-type, optional
+ Desired output data-type for the array, e.g, `numpy.int8`. Default is
+ `numpy.float64`.
+ order : {'C', 'F'}, optional, default: 'C'
+ Whether to store multi-dimensional data in row-major
+ (C-style) or column-major (Fortran-style) order in memory.
+ device : str, optional
+ The device on which to place the created array. Default: ``None``.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of uninitialized (arbitrary) data of the given shape, dtype, and
+ order. Object arrays will be initialized to None.
+
+ See Also
+ --------
+ empty_like : Return an empty array with shape and type of input.
+ ones : Return a new array setting values to one.
+ zeros : Return a new array setting values to zero.
+ full : Return a new array of given shape filled with value.
+
+ Notes
+ -----
+ Unlike other array creation functions (e.g. `zeros`, `ones`, `full`),
+ `empty` does not initialize the values of the array, and may therefore be
+ marginally faster. However, the values stored in the newly allocated array
+ are arbitrary. For reproducible behavior, be sure to set each element of
+ the array before reading.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.empty([2, 2])
+ array([[ -9.74499359e+001, 6.69583040e-309],
+ [ 2.13182611e-314, 3.06959433e-309]]) #uninitialized
+
+ >>> np.empty([2, 2], dtype=int)
+ array([[-1073741821, -1067949133],
+ [ 496041986, 19249760]]) #uninitialized
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'scalar',
+ """
+ scalar(dtype, obj)
+
+ Return a new scalar array of the given type initialized with obj.
+
+ This function is meant mainly for pickle support. `dtype` must be a
+ valid data-type descriptor. If `dtype` corresponds to an object
+ descriptor, then `obj` can be any object, otherwise `obj` must be a
+ string. If `obj` is not given, it will be interpreted as None for object
+ type and as zeros for all other types.
+
+ """) # sufficient null bytes for all number dtypes
+
+add_newdoc('numpy._core.multiarray', 'zeros',
+ """
+ zeros(shape, dtype=None, order='C', *, device=None, like=None)
+ --
+
+ zeros(shape, dtype=None, order='C', *, device=None, like=None)
+
+ Return a new array of given shape and type, filled with zeros.
+
+ Parameters
+ ----------
+ shape : int or tuple of ints
+ Shape of the new array, e.g., ``(2, 3)`` or ``2``.
+ dtype : data-type, optional
+ The desired data-type for the array, e.g., `numpy.int8`. Default is
+ `numpy.float64`.
+ order : {'C', 'F'}, optional, default: 'C'
+ Whether to store multi-dimensional data in row-major
+ (C-style) or column-major (Fortran-style) order in memory.
+ device : str, optional
+ The device on which to place the created array. Default: ``None``.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of zeros with the given shape, dtype, and order.
+
+ See Also
+ --------
+ zeros_like : Return an array of zeros with shape and type of input.
+ empty : Return a new uninitialized array.
+ ones : Return a new array setting values to one.
+ full : Return a new array of given shape filled with value.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.zeros(5)
+ array([ 0., 0., 0., 0., 0.])
+
+ >>> np.zeros((5,), dtype=int)
+ array([0, 0, 0, 0, 0])
+
+ >>> np.zeros((2, 1))
+ array([[ 0.],
+ [ 0.]])
+
+ >>> s = (2,2)
+ >>> np.zeros(s)
+ array([[ 0., 0.],
+ [ 0., 0.]])
+
+ >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
+ array([(0, 0), (0, 0)],
+ dtype=[('x', '>> import numpy as np
+ >>> np.fromstring('1 2', dtype=int, sep=' ')
+ array([1, 2])
+ >>> np.fromstring('1, 2', dtype=int, sep=',')
+ array([1, 2])
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'compare_chararrays',
+ """
+ compare_chararrays(a1, a2, cmp, rstrip)
+ --
+
+ compare_chararrays(a1, a2, cmp, rstrip)
+
+ Performs element-wise comparison of two string arrays using the
+ comparison operator specified by `cmp`.
+
+ Parameters
+ ----------
+ a1, a2 : array_like
+ Arrays to be compared.
+ cmp : {"<", "<=", "==", ">=", ">", "!="}
+ Type of comparison.
+ rstrip : bool
+ If True, the spaces at the end of strings are removed before the comparison.
+
+ Returns
+ -------
+ out : ndarray
+ The output array of type `numpy.bool` with the same shape as `a1` and `a2`.
+
+ Raises
+ ------
+ ValueError
+ If `cmp` is not valid.
+ TypeError
+ If at least one of `a1` or `a2` is a non-string array
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["a", "b", "cde"])
+ >>> b = np.array(["a", "a", "dec"])
+ >>> np.char.compare_chararrays(a, b, ">", True)
+ array([False, True, False])
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'fromiter',
+ """
+ fromiter(iter, dtype, count=-1, *, like=None)
+ --
+
+ fromiter(iter, dtype, count=-1, *, like=None)
+
+ Create a new 1-dimensional array from an iterable object.
+
+ Parameters
+ ----------
+ iter : iterable object
+ An iterable object providing data for the array.
+ dtype : data-type
+ The data-type of the returned array.
+
+ .. versionchanged:: 1.23
+ Object and subarray dtypes are now supported (note that the final
+ result is not 1-D for a subarray dtype).
+
+ count : int, optional
+ The number of items to read from *iterable*. The default is -1,
+ which means all data is read.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ The output array.
+
+ Notes
+ -----
+ Specify `count` to improve performance. It allows ``fromiter`` to
+ pre-allocate the output array, instead of resizing it on demand.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> iterable = (x*x for x in range(5))
+ >>> np.fromiter(iterable, float)
+ array([ 0., 1., 4., 9., 16.])
+
+ A carefully constructed subarray dtype will lead to higher dimensional
+ results:
+
+ >>> iterable = ((x+1, x+2) for x in range(5))
+ >>> np.fromiter(iterable, dtype=np.dtype((int, 2)))
+ array([[1, 2],
+ [2, 3],
+ [3, 4],
+ [4, 5],
+ [5, 6]])
+
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'fromfile',
+ """
+ fromfile(file, dtype=None, count=-1, sep='', offset=0, *, like=None)
+ --
+
+ fromfile(file, dtype=float, count=-1, sep='', offset=0, *, like=None)
+
+ Construct an array from data in a text or binary file.
+
+ A highly efficient way of reading binary data with a known data-type,
+ as well as parsing simply formatted text files. Data written using the
+ `tofile` method can be read using this function.
+
+ Parameters
+ ----------
+ file : file or str or Path
+ An open file object, a string containing the filename, or a Path object.
+ When reading from a file object it must support random access
+ (i.e. it must have tell and seek methods).
+ dtype : data-type
+ Data type of the returned array.
+ For binary files, it is used to determine the size and byte-order
+ of the items in the file.
+ Most builtin numeric types are supported and extension types may be supported.
+ count : int
+ Number of items to read. ``-1`` means all items (i.e., the complete
+ file).
+ sep : str
+ Separator between items if file is a text file.
+ Empty ("") separator means the file should be treated as binary.
+ Spaces (" ") in the separator match zero or more whitespace characters.
+ A separator consisting only of spaces must match at least one
+ whitespace.
+ offset : int
+ The offset (in bytes) from the file's current position. Defaults to 0.
+ Only permitted for binary files.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ See also
+ --------
+ load, save
+ ndarray.tofile
+ loadtxt : More flexible way of loading data from a text file.
+
+ Notes
+ -----
+ Do not rely on the combination of `tofile` and `fromfile` for
+ data storage, as the binary files generated are not platform
+ independent. In particular, no byte-order or data-type information is
+ saved. Data can be stored in the platform independent ``.npy`` format
+ using `save` and `load` instead.
+
+ Examples
+ --------
+ Construct an ndarray:
+
+ >>> import numpy as np
+ >>> dt = np.dtype([('time', [('min', np.int64), ('sec', np.int64)]),
+ ... ('temp', float)])
+ >>> x = np.zeros((1,), dtype=dt)
+ >>> x['time']['min'] = 10; x['temp'] = 98.25
+ >>> x
+ array([((10, 0), 98.25)],
+ dtype=[('time', [('min', '>> import tempfile
+ >>> fname = tempfile.mkstemp()[1]
+ >>> x.tofile(fname)
+
+ Read the raw data from disk:
+
+ >>> np.fromfile(fname, dtype=dt)
+ array([((10, 0), 98.25)],
+ dtype=[('time', [('min', '>> np.save(fname, x)
+ >>> np.load(fname + '.npy')
+ array([((10, 0), 98.25)],
+ dtype=[('time', [('min', '>> dt = np.dtype(int)
+ >>> dt = dt.newbyteorder('>')
+ >>> np.frombuffer(buf, dtype=dt) # doctest: +SKIP
+
+ The data of the resulting array will not be byteswapped, but will be
+ interpreted correctly.
+
+ This function creates a view into the original object. This should be safe
+ in general, but it may make sense to copy the result when the original
+ object is mutable or untrusted.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> s = b'hello world'
+ >>> np.frombuffer(s, dtype='S1', count=5, offset=6)
+ array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')
+
+ >>> np.frombuffer(b'\\x01\\x02', dtype=np.uint8)
+ array([1, 2], dtype=uint8)
+ >>> np.frombuffer(b'\\x01\\x02\\x03\\x04\\x05', dtype=np.uint8, count=3)
+ array([1, 2, 3], dtype=uint8)
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'from_dlpack',
+ """
+ from_dlpack(x, /, *, device=None, copy=None)
+ --
+
+ from_dlpack(x, /, *, device=None, copy=None)
+
+ Create a NumPy array from an object implementing the ``__dlpack__``
+ protocol. Generally, the returned NumPy array is a view of the input
+ object. See [1]_ and [2]_ for more details.
+
+ Parameters
+ ----------
+ x : object
+ A Python object that implements the ``__dlpack__`` and
+ ``__dlpack_device__`` methods.
+ device : device, optional
+ Device on which to place the created array. Default: ``None``.
+ Must be ``"cpu"`` if passed which may allow importing an array
+ that is not already CPU available.
+ copy : bool, optional
+ Boolean indicating whether or not to copy the input. If ``True``,
+ the copy will be made. If ``False``, the function will never copy,
+ and will raise ``BufferError`` in case a copy is deemed necessary.
+ Passing it requests a copy from the exporter who may or may not
+ implement the capability.
+ If ``None``, the function will reuse the existing memory buffer if
+ possible and copy otherwise. Default: ``None``.
+
+
+ Returns
+ -------
+ out : ndarray
+
+ References
+ ----------
+ .. [1] Array API documentation,
+ https://data-apis.org/array-api/latest/design_topics/data_interchange.html#syntax-for-data-interchange-with-dlpack
+
+ .. [2] Python specification for DLPack,
+ https://dmlc.github.io/dlpack/latest/python_spec.html
+
+ Examples
+ --------
+ >>> import torch # doctest: +SKIP
+ >>> x = torch.arange(10) # doctest: +SKIP
+ >>> # create a view of the torch tensor "x" in NumPy
+ >>> y = np.from_dlpack(x) # doctest: +SKIP
+ """)
+
+add_newdoc('numpy._core.multiarray', 'correlate',
+ """cross_correlate(a,v, mode=0)""")
+
+add_newdoc('numpy._core.multiarray', 'arange',
+ """
+ arange(start_or_stop, /, stop=None, step=1, *, dtype=None, device=None, like=None)
+ --
+
+ arange([start,] stop[, step,], dtype=None, *, device=None, like=None)
+
+ Return evenly spaced values within a given interval.
+
+ ``arange`` can be called with a varying number of positional arguments:
+
+ * ``arange(stop)``: Values are generated within the half-open interval
+ ``[0, stop)`` (in other words, the interval including `start` but
+ excluding `stop`).
+ * ``arange(start, stop)``: Values are generated within the half-open
+ interval ``[start, stop)``.
+ * ``arange(start, stop, step)`` Values are generated within the half-open
+ interval ``[start, stop)``, with spacing between values given by
+ ``step``.
+
+ For integer arguments the function is roughly equivalent to the Python
+ built-in :py:class:`range`, but returns an ndarray rather than a ``range``
+ instance.
+
+ When using a non-integer step, such as 0.1, it is often better to use
+ `numpy.linspace`.
+
+ See the Warning sections below for more information.
+
+ Parameters
+ ----------
+ start : integer or real, optional
+ Start of interval. The interval includes this value. The default
+ start value is 0.
+ stop : integer or real
+ End of interval. The interval does not include this value, except
+ in some cases where `step` is not an integer and floating point
+ round-off affects the length of `out`.
+ step : integer or real, optional
+ Spacing between values. For any output `out`, this is the distance
+ between two adjacent values, ``out[i+1] - out[i]``. The default
+ step size is 1. If `step` is specified as a position argument,
+ `start` must also be given.
+ dtype : dtype, optional
+ The type of the output array. If `dtype` is not given, infer the data
+ type from the other input arguments.
+ device : str, optional
+ The device on which to place the created array. Default: ``None``.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ arange : ndarray
+ Array of evenly spaced values.
+
+ For floating point arguments, the length of the result is
+ ``ceil((stop - start)/step)``. Because of floating point overflow,
+ this rule may result in the last element of `out` being greater
+ than `stop`.
+
+ Warnings
+ --------
+ The length of the output might not be numerically stable.
+
+ Another stability issue is due to the internal implementation of
+ `numpy.arange`.
+ The actual step value used to populate the array is
+ ``dtype(start + step) - dtype(start)`` and not `step`. Precision loss
+ can occur here, due to casting or due to using floating points when
+ `start` is much larger than `step`. This can lead to unexpected
+ behaviour. For example::
+
+ >>> np.arange(0, 5, 0.5, dtype=int)
+ array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
+ >>> np.arange(-3, 3, 0.5, dtype=int)
+ array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8])
+
+ In such cases, the use of `numpy.linspace` should be preferred.
+
+ The built-in :py:class:`range` generates :std:doc:`Python built-in integers
+ that have arbitrary size `, while `numpy.arange`
+ produces `numpy.int32` or `numpy.int64` numbers. This may result in
+ incorrect results for large integer values::
+
+ >>> power = 40
+ >>> modulo = 10000
+ >>> x1 = [(n ** power) % modulo for n in range(8)]
+ >>> x2 = [(n ** power) % modulo for n in np.arange(8)]
+ >>> print(x1)
+ [0, 1, 7776, 8801, 6176, 625, 6576, 4001] # correct
+ >>> print(x2)
+ [0, 1, 7776, 7185, 0, 5969, 4816, 3361] # incorrect
+
+ See Also
+ --------
+ numpy.linspace : Evenly spaced numbers with careful handling of endpoints.
+ numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.
+ numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.
+ :ref:`how-to-partition`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.arange(3)
+ array([0, 1, 2])
+ >>> np.arange(3.0)
+ array([ 0., 1., 2.])
+ >>> np.arange(3,7)
+ array([3, 4, 5, 6])
+ >>> np.arange(3,7,2)
+ array([3, 5])
+
+ """)
+
+add_newdoc('numpy._core.multiarray', '_get_ndarray_c_version',
+ """_get_ndarray_c_version()
+
+ Return the compile time NPY_VERSION (formerly called NDARRAY_VERSION) number.
+
+ """)
+
+add_newdoc('numpy._core.multiarray', '_reconstruct',
+ """_reconstruct(subtype, shape, dtype)
+
+ Construct an empty array. Used by Pickle.
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'promote_types',
+ """
+ promote_types(type1, type2, /)
+ --
+
+ promote_types(type1, type2, /)
+
+ Returns the data type with the smallest size and smallest scalar
+ kind to which both ``type1`` and ``type2`` may be safely cast.
+ The returned data type is always considered "canonical", this mainly
+ means that the promoted dtype will always be in native byte order.
+
+ This function is symmetric, but rarely associative.
+
+ Parameters
+ ----------
+ type1 : dtype or dtype specifier
+ First data type.
+ type2 : dtype or dtype specifier
+ Second data type.
+
+ Returns
+ -------
+ out : dtype
+ The promoted data type.
+
+ Notes
+ -----
+ Please see `numpy.result_type` for additional information about promotion.
+
+ Starting in NumPy 1.9, promote_types function now returns a valid string
+ length when given an integer or float dtype as one argument and a string
+ dtype as another argument. Previously it always returned the input string
+ dtype, even if it wasn't long enough to store the max integer/float value
+ converted to a string.
+
+ .. versionchanged:: 1.23.0
+
+ NumPy now supports promotion for more structured dtypes. It will now
+ remove unnecessary padding from a structure dtype and promote included
+ fields individually.
+
+ See Also
+ --------
+ result_type, dtype, can_cast
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.promote_types('f4', 'f8')
+ dtype('float64')
+
+ >>> np.promote_types('i8', 'f4')
+ dtype('float64')
+
+ >>> np.promote_types('>i8', '>> np.promote_types('i4', 'S8')
+ dtype('S11')
+
+ An example of a non-associative case:
+
+ >>> p = np.promote_types
+ >>> p('S', p('i1', 'u1'))
+ dtype('S6')
+ >>> p(p('S', 'i1'), 'u1')
+ dtype('S4')
+
+ """)
+
+add_newdoc('numpy._core.multiarray', 'c_einsum',
+ """
+ c_einsum(subscripts, *operands, out=None, dtype=None, order='K',
+ casting='safe')
+
+ *This documentation shadows that of the native python implementation of the `einsum` function,
+ except all references and examples related to the `optimize` argument (v 0.12.0) have been removed.*
+
+ Evaluates the Einstein summation convention on the operands.
+
+ Using the Einstein summation convention, many common multi-dimensional,
+ linear algebraic array operations can be represented in a simple fashion.
+ In *implicit* mode `einsum` computes these values.
+
+ In *explicit* mode, `einsum` provides further flexibility to compute
+ other array operations that might not be considered classical Einstein
+ summation operations, by disabling, or forcing summation over specified
+ subscript labels.
+
+ See the notes and examples for clarification.
+
+ Parameters
+ ----------
+ subscripts : str
+ Specifies the subscripts for summation as comma separated list of
+ subscript labels. An implicit (classical Einstein summation)
+ calculation is performed unless the explicit indicator '->' is
+ included as well as subscript labels of the precise output form.
+ operands : list of array_like
+ These are the arrays for the operation.
+ out : ndarray, optional
+ If provided, the calculation is done into this array.
+ dtype : {data-type, None}, optional
+ If provided, forces the calculation to use the data type specified.
+ Note that you may have to also give a more liberal `casting`
+ parameter to allow the conversions. Default is None.
+ order : {'C', 'F', 'A', 'K'}, optional
+ Controls the memory layout of the output. 'C' means it should
+ be C contiguous. 'F' means it should be Fortran contiguous,
+ 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise.
+ 'K' means it should be as close to the layout of the inputs as
+ is possible, including arbitrarily permuted axes.
+ Default is 'K'.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Setting this to
+ 'unsafe' is not recommended, as it can adversely affect accumulations.
+
+ * 'no' means the data types should not be cast at all.
+ * 'equiv' means only byte-order changes are allowed.
+ * 'safe' means only casts which can preserve values are allowed.
+ * 'same_kind' means only safe casts or casts within a kind,
+ like float64 to float32, are allowed.
+ * 'unsafe' means any data conversions may be done.
+
+ Default is 'safe'.
+ optimize : {False, True, 'greedy', 'optimal'}, optional
+ Controls if intermediate optimization should occur. No optimization
+ will occur if False and True will default to the 'greedy' algorithm.
+ Also accepts an explicit contraction list from the ``np.einsum_path``
+ function. See ``np.einsum_path`` for more details. Defaults to False.
+
+ Returns
+ -------
+ output : ndarray
+ The calculation based on the Einstein summation convention.
+
+ See Also
+ --------
+ einsum_path, dot, inner, outer, tensordot, linalg.multi_dot
+
+ Notes
+ -----
+ The Einstein summation convention can be used to compute
+ many multi-dimensional, linear algebraic array operations. `einsum`
+ provides a succinct way of representing these.
+
+ A non-exhaustive list of these operations,
+ which can be computed by `einsum`, is shown below along with examples:
+
+ * Trace of an array, :py:func:`numpy.trace`.
+ * Return a diagonal, :py:func:`numpy.diag`.
+ * Array axis summations, :py:func:`numpy.sum`.
+ * Transpositions and permutations, :py:func:`numpy.transpose`.
+ * Matrix multiplication and dot product, :py:func:`numpy.matmul` :py:func:`numpy.dot`.
+ * Vector inner and outer products, :py:func:`numpy.inner` :py:func:`numpy.outer`.
+ * Broadcasting, element-wise and scalar multiplication, :py:func:`numpy.multiply`.
+ * Tensor contractions, :py:func:`numpy.tensordot`.
+ * Chained array operations, in efficient calculation order, :py:func:`numpy.einsum_path`.
+
+ The subscripts string is a comma-separated list of subscript labels,
+ where each label refers to a dimension of the corresponding operand.
+ Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
+ is equivalent to :py:func:`np.inner(a,b) `. If a label
+ appears only once, it is not summed, so ``np.einsum('i', a)`` produces a
+ view of ``a`` with no changes. A further example ``np.einsum('ij,jk', a, b)``
+ describes traditional matrix multiplication and is equivalent to
+ :py:func:`np.matmul(a,b) `. Repeated subscript labels in one
+ operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent
+ to :py:func:`np.trace(a) `.
+
+ In *implicit mode*, the chosen subscripts are important
+ since the axes of the output are reordered alphabetically. This
+ means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
+ ``np.einsum('ji', a)`` takes its transpose. Additionally,
+ ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
+ ``np.einsum('ij,jh', a, b)`` returns the transpose of the
+ multiplication since subscript 'h' precedes subscript 'i'.
+
+ In *explicit mode* the output can be directly controlled by
+ specifying output subscript labels. This requires the
+ identifier '->' as well as the list of output subscript labels.
+ This feature increases the flexibility of the function since
+ summing can be disabled or forced when required. The call
+ ``np.einsum('i->', a)`` is like :py:func:`np.sum(a) `
+ if ``a`` is a 1-D array, and ``np.einsum('ii->i', a)``
+ is like :py:func:`np.diag(a) ` if ``a`` is a square 2-D array.
+ The difference is that `einsum` does not allow broadcasting by default.
+ Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
+ order of the output subscript labels and therefore returns matrix
+ multiplication, unlike the example above in implicit mode.
+
+ To enable and control broadcasting, use an ellipsis. Default
+ NumPy-style broadcasting is done by adding an ellipsis
+ to the left of each term, like ``np.einsum('...ii->...i', a)``.
+ ``np.einsum('...i->...', a)`` is like
+ :py:func:`np.sum(a, axis=-1) ` for array ``a`` of any shape.
+ To take the trace along the first and last axes,
+ you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
+ product with the left-most indices instead of rightmost, one can do
+ ``np.einsum('ij...,jk...->ik...', a, b)``.
+
+ When there is only one operand, no axes are summed, and no output
+ parameter is provided, a view into the operand is returned instead
+ of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``
+ produces a view (changed in version 1.10.0).
+
+ `einsum` also provides an alternative way to provide the subscripts
+ and operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``.
+ If the output shape is not provided in this format `einsum` will be
+ calculated in implicit mode, otherwise it will be performed explicitly.
+ The examples below have corresponding `einsum` calls with the two
+ parameter methods.
+
+ Views returned from einsum are now writeable whenever the input array
+ is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now
+ have the same effect as :py:func:`np.swapaxes(a, 0, 2) `
+ and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal
+ of a 2D array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(25).reshape(5,5)
+ >>> b = np.arange(5)
+ >>> c = np.arange(6).reshape(2,3)
+
+ Trace of a matrix:
+
+ >>> np.einsum('ii', a)
+ 60
+ >>> np.einsum(a, [0,0])
+ 60
+ >>> np.trace(a)
+ 60
+
+ Extract the diagonal (requires explicit form):
+
+ >>> np.einsum('ii->i', a)
+ array([ 0, 6, 12, 18, 24])
+ >>> np.einsum(a, [0,0], [0])
+ array([ 0, 6, 12, 18, 24])
+ >>> np.diag(a)
+ array([ 0, 6, 12, 18, 24])
+
+ Sum over an axis (requires explicit form):
+
+ >>> np.einsum('ij->i', a)
+ array([ 10, 35, 60, 85, 110])
+ >>> np.einsum(a, [0,1], [0])
+ array([ 10, 35, 60, 85, 110])
+ >>> np.sum(a, axis=1)
+ array([ 10, 35, 60, 85, 110])
+
+ For higher dimensional arrays summing a single axis can be done with ellipsis:
+
+ >>> np.einsum('...j->...', a)
+ array([ 10, 35, 60, 85, 110])
+ >>> np.einsum(a, [Ellipsis,1], [Ellipsis])
+ array([ 10, 35, 60, 85, 110])
+
+ Compute a matrix transpose, or reorder any number of axes:
+
+ >>> np.einsum('ji', c)
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+ >>> np.einsum('ij->ji', c)
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+ >>> np.einsum(c, [1,0])
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+ >>> np.transpose(c)
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+
+ Vector inner products:
+
+ >>> np.einsum('i,i', b, b)
+ 30
+ >>> np.einsum(b, [0], b, [0])
+ 30
+ >>> np.inner(b,b)
+ 30
+
+ Matrix vector multiplication:
+
+ >>> np.einsum('ij,j', a, b)
+ array([ 30, 80, 130, 180, 230])
+ >>> np.einsum(a, [0,1], b, [1])
+ array([ 30, 80, 130, 180, 230])
+ >>> np.dot(a, b)
+ array([ 30, 80, 130, 180, 230])
+ >>> np.einsum('...j,j', a, b)
+ array([ 30, 80, 130, 180, 230])
+
+ Broadcasting and scalar multiplication:
+
+ >>> np.einsum('..., ...', 3, c)
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+ >>> np.einsum(',ij', 3, c)
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+ >>> np.einsum(3, [Ellipsis], c, [Ellipsis])
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+ >>> np.multiply(3, c)
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+
+ Vector outer product:
+
+ >>> np.einsum('i,j', np.arange(2)+1, b)
+ array([[0, 1, 2, 3, 4],
+ [0, 2, 4, 6, 8]])
+ >>> np.einsum(np.arange(2)+1, [0], b, [1])
+ array([[0, 1, 2, 3, 4],
+ [0, 2, 4, 6, 8]])
+ >>> np.outer(np.arange(2)+1, b)
+ array([[0, 1, 2, 3, 4],
+ [0, 2, 4, 6, 8]])
+
+ Tensor contraction:
+
+ >>> a = np.arange(60.).reshape(3,4,5)
+ >>> b = np.arange(24.).reshape(4,3,2)
+ >>> np.einsum('ijk,jil->kl', a, b)
+ array([[ 4400., 4730.],
+ [ 4532., 4874.],
+ [ 4664., 5018.],
+ [ 4796., 5162.],
+ [ 4928., 5306.]])
+ >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])
+ array([[ 4400., 4730.],
+ [ 4532., 4874.],
+ [ 4664., 5018.],
+ [ 4796., 5162.],
+ [ 4928., 5306.]])
+ >>> np.tensordot(a,b, axes=([1,0],[0,1]))
+ array([[ 4400., 4730.],
+ [ 4532., 4874.],
+ [ 4664., 5018.],
+ [ 4796., 5162.],
+ [ 4928., 5306.]])
+
+ Writeable returned arrays (since version 1.10.0):
+
+ >>> a = np.zeros((3, 3))
+ >>> np.einsum('ii->i', a)[:] = 1
+ >>> a
+ array([[ 1., 0., 0.],
+ [ 0., 1., 0.],
+ [ 0., 0., 1.]])
+
+ Example of ellipsis use:
+
+ >>> a = np.arange(6).reshape((3,2))
+ >>> b = np.arange(12).reshape((4,3))
+ >>> np.einsum('ki,jk->ij', a, b)
+ array([[10, 28, 46, 64],
+ [13, 40, 67, 94]])
+ >>> np.einsum('ki,...k->i...', a, b)
+ array([[10, 28, 46, 64],
+ [13, 40, 67, 94]])
+ >>> np.einsum('k...,jk', a, b)
+ array([[10, 28, 46, 64],
+ [13, 40, 67, 94]])
+
+ """)
+
+
+##############################################################################
+#
+# Documentation for ndarray attributes and methods
+#
+##############################################################################
+
+
+##############################################################################
+#
+# ndarray object
+#
+##############################################################################
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray',
+ """
+ ndarray(shape, dtype=None, buffer=None, offset=0, strides=None, order=None)
+ --
+
+ ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)
+
+ An array object represents a multidimensional, homogeneous array
+ of fixed-size items. An associated data-type object describes the
+ format of each element in the array (its byte-order, how many bytes it
+ occupies in memory, whether it is an integer, a floating point number,
+ or something else, etc.)
+
+ Arrays should be constructed using `array`, `zeros` or `empty` (refer
+ to the See Also section below). The parameters given here refer to
+ a low-level method (`ndarray(...)`) for instantiating an array.
+
+ For more information, refer to the `numpy` module and examine the
+ methods and attributes of an array.
+
+ Parameters
+ ----------
+ (for the __new__ method; see Notes below)
+
+ shape : tuple of ints
+ Shape of created array.
+ dtype : data-type, optional
+ Any object that can be interpreted as a numpy data type.
+ Default is `numpy.float64`.
+ buffer : object exposing buffer interface, optional
+ Used to fill the array with data.
+ offset : int, optional
+ Offset of array data in buffer.
+ strides : tuple of ints, optional
+ Strides of data in memory.
+ order : {'C', 'F'}, optional
+ Row-major (C-style) or column-major (Fortran-style) order.
+
+ Attributes
+ ----------
+ T : ndarray
+ Transpose of the array.
+ data : buffer
+ The array's elements, in memory.
+ dtype : dtype object
+ Describes the format of the elements in the array.
+ flags : dict
+ Dictionary containing information related to memory use, e.g.,
+ 'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc.
+ flat : numpy.flatiter object
+ Flattened version of the array as an iterator. The iterator
+ allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for
+ assignment examples; TODO).
+ imag : ndarray
+ Imaginary part of the array.
+ real : ndarray
+ Real part of the array.
+ size : int
+ Number of elements in the array.
+ itemsize : int
+ The memory use of each array element in bytes.
+ nbytes : int
+ The total number of bytes required to store the array data,
+ i.e., ``itemsize * size``.
+ ndim : int
+ The array's number of dimensions.
+ shape : tuple of ints
+ Shape of the array.
+ strides : tuple of ints
+ The step-size required to move from one element to the next in
+ memory. For example, a contiguous ``(3, 4)`` array of type
+ ``int16`` in C-order has strides ``(8, 2)``. This implies that
+ to move from element to element in memory requires jumps of 2 bytes.
+ To move from row-to-row, one needs to jump 8 bytes at a time
+ (``2 * 4``).
+ ctypes : ctypes object
+ Class containing properties of the array needed for interaction
+ with ctypes.
+ base : ndarray
+ If the array is a view into another array, that array is its `base`
+ (unless that array is also a view). The `base` array is where the
+ array data is actually stored.
+
+ See Also
+ --------
+ array : Construct an array.
+ zeros : Create an array, each element of which is zero.
+ empty : Create an array, but leave its allocated memory unchanged (i.e.,
+ it contains "garbage").
+ dtype : Create a data-type.
+ numpy.typing.NDArray : An ndarray alias :term:`generic `
+ w.r.t. its `dtype.type `.
+
+ Notes
+ -----
+ There are two modes of creating an array using ``__new__``:
+
+ 1. If `buffer` is None, then only `shape`, `dtype`, and `order`
+ are used.
+ 2. If `buffer` is an object exposing the buffer interface, then
+ all keywords are interpreted.
+
+ No ``__init__`` method is needed because the array is fully initialized
+ after the ``__new__`` method.
+
+ Examples
+ --------
+ These examples illustrate the low-level `ndarray` constructor. Refer
+ to the `See Also` section above for easier ways of constructing an
+ ndarray.
+
+ First mode, `buffer` is None:
+
+ >>> import numpy as np
+ >>> np.ndarray(shape=(2,2), dtype=float, order='F')
+ array([[0.0e+000, 0.0e+000], # random
+ [ nan, 2.5e-323]])
+
+ Second mode:
+
+ >>> np.ndarray((2,), buffer=np.array([1,2,3]),
+ ... offset=np.int_().itemsize,
+ ... dtype=int) # offset = 1*itemsize, i.e. skip first element
+ array([2, 3])
+
+ """)
+
+
+##############################################################################
+#
+# ndarray attributes
+#
+##############################################################################
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_interface__',
+ """Array protocol: Python side."""))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_priority__',
+ """Array priority."""))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_struct__',
+ """Array protocol: C-struct side."""))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('base',
+ """
+ Base object if memory is from some other object.
+
+ Examples
+ --------
+ The base of an array that owns its memory is None:
+
+ >>> import numpy as np
+ >>> x = np.array([1,2,3,4])
+ >>> x.base is None
+ True
+
+ Slicing creates a view, whose memory is shared with x:
+
+ >>> y = x[2:]
+ >>> y.base is x
+ True
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('ctypes',
+ """
+ An object to simplify the interaction of the array with the ctypes
+ module.
+
+ This attribute creates an object that makes it easier to use arrays
+ when calling shared libraries with the ctypes module. The returned
+ object has, among others, data, shape, and strides attributes (see
+ Notes below) which themselves return ctypes objects that can be used
+ as arguments to a shared library.
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ c : Python object
+ Possessing attributes data, shape, strides, etc.
+
+ See Also
+ --------
+ numpy.ctypeslib
+
+ Notes
+ -----
+ Below are the public attributes of this object which were documented
+ in "Guide to NumPy" (we have omitted undocumented public attributes,
+ as well as documented private attributes):
+
+ .. autoattribute:: numpy._core._internal._ctypes.data
+ :noindex:
+
+ .. autoattribute:: numpy._core._internal._ctypes.shape
+ :noindex:
+
+ .. autoattribute:: numpy._core._internal._ctypes.strides
+ :noindex:
+
+ .. automethod:: numpy._core._internal._ctypes.data_as
+ :noindex:
+
+ .. automethod:: numpy._core._internal._ctypes.shape_as
+ :noindex:
+
+ .. automethod:: numpy._core._internal._ctypes.strides_as
+ :noindex:
+
+ If the ctypes module is not available, then the ctypes attribute
+ of array objects still returns something useful, but ctypes objects
+ are not returned and errors may be raised instead. In particular,
+ the object will still have the ``as_parameter`` attribute which will
+ return an integer equal to the data attribute.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import ctypes
+ >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
+ >>> x
+ array([[0, 1],
+ [2, 3]], dtype=int32)
+ >>> x.ctypes.data
+ 31962608 # may vary
+ >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
+ <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
+ >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
+ c_uint(0)
+ >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
+ c_ulong(4294967296)
+ >>> x.ctypes.shape
+ # may vary
+ >>> x.ctypes.strides
+ # may vary
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('data',
+ """Python buffer object pointing to the start of the array's data."""))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('dtype',
+ """
+ Data-type of the array's elements.
+
+ .. warning::
+
+ Setting ``arr.dtype`` is discouraged and may be deprecated in the
+ future. Setting will replace the ``dtype`` without modifying the
+ memory (see also `ndarray.view` and `ndarray.astype`).
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ d : numpy dtype object
+
+ See Also
+ --------
+ ndarray.astype : Cast the values contained in the array to a new data-type.
+ ndarray.view : Create a view of the same data but a different data-type.
+ numpy.dtype
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(4).reshape((2, 2))
+ >>> x
+ array([[0, 1],
+ [2, 3]])
+ >>> x.dtype
+ dtype('int64') # may vary (OS, bitness)
+ >>> isinstance(x.dtype, np.dtype)
+ True
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('imag',
+ """
+ The imaginary part of the array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.sqrt([1+0j, 0+1j])
+ >>> x.imag
+ array([ 0. , 0.70710678])
+ >>> x.imag.dtype
+ dtype('float64')
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('itemsize',
+ """
+ Length of one array element in bytes.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1,2,3], dtype=np.float64)
+ >>> x.itemsize
+ 8
+ >>> x = np.array([1,2,3], dtype=np.complex128)
+ >>> x.itemsize
+ 16
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('flags',
+ """
+ Information about the memory layout of the array.
+
+ Attributes
+ ----------
+ C_CONTIGUOUS (C)
+ The data is in a single, C-style contiguous segment.
+ F_CONTIGUOUS (F)
+ The data is in a single, Fortran-style contiguous segment.
+ OWNDATA (O)
+ The array owns the memory it uses or borrows it from another object.
+ WRITEABLE (W)
+ The data area can be written to. Setting this to False locks
+ the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
+ from its base array at creation time, but a view of a writeable
+ array may be subsequently locked while the base array remains writeable.
+ (The opposite is not true, in that a view of a locked array may not
+ be made writeable. However, currently, locking a base object does not
+ lock any views that already reference it, so under that circumstance it
+ is possible to alter the contents of a locked array via a previously
+ created writeable view onto it.) Attempting to change a non-writeable
+ array raises a RuntimeError exception.
+ ALIGNED (A)
+ The data and all elements are aligned appropriately for the hardware.
+ WRITEBACKIFCOPY (X)
+ This array is a copy of some other array. The C-API function
+ PyArray_ResolveWritebackIfCopy must be called before deallocating
+ to the base array will be updated with the contents of this array.
+ FNC
+ F_CONTIGUOUS and not C_CONTIGUOUS.
+ FORC
+ F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
+ BEHAVED (B)
+ ALIGNED and WRITEABLE.
+ CARRAY (CA)
+ BEHAVED and C_CONTIGUOUS.
+ FARRAY (FA)
+ BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
+
+ Notes
+ -----
+ The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
+ or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
+ names are only supported in dictionary access.
+
+ Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
+ changed by the user, via direct assignment to the attribute or dictionary
+ entry, or by calling `ndarray.setflags`.
+
+ The array flags cannot be set arbitrarily:
+
+ - WRITEBACKIFCOPY can only be set ``False``.
+ - ALIGNED can only be set ``True`` if the data is truly aligned.
+ - WRITEABLE can only be set ``True`` if the array owns its own memory
+ or the ultimate owner of the memory exposes a writeable buffer
+ interface or is a string.
+
+ Arrays can be both C-style and Fortran-style contiguous simultaneously.
+ This is clear for 1-dimensional arrays, but can also be true for higher
+ dimensional arrays.
+
+ Even for contiguous arrays a stride for a given dimension
+ ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
+ or the array has no elements.
+ It does *not* generally hold that ``self.strides[-1] == self.itemsize``
+ for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
+ Fortran-style contiguous arrays is true.
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('flat',
+ """
+ A 1-D iterator over the array.
+
+ This is a `numpy.flatiter` instance, which acts similarly to, but is not
+ a subclass of, Python's built-in iterator object.
+
+ See Also
+ --------
+ flatten : Return a copy of the array collapsed into one dimension.
+
+ flatiter
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(1, 7).reshape(2, 3)
+ >>> x
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> x.flat[3]
+ 4
+ >>> x.T
+ array([[1, 4],
+ [2, 5],
+ [3, 6]])
+ >>> x.T.flat[3]
+ 5
+ >>> type(x.flat)
+
+
+ An assignment example:
+
+ >>> x.flat = 3; x
+ array([[3, 3, 3],
+ [3, 3, 3]])
+ >>> x.flat[[1,4]] = 1; x
+ array([[3, 1, 3],
+ [3, 1, 3]])
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('nbytes',
+ """
+ Total bytes consumed by the elements of the array.
+
+ Notes
+ -----
+ Does not include memory consumed by non-element attributes of the
+ array object.
+
+ See Also
+ --------
+ sys.getsizeof
+ Memory consumed by the object itself without parents in case view.
+ This does include memory consumed by non-element attributes.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.zeros((3,5,2), dtype=np.complex128)
+ >>> x.nbytes
+ 480
+ >>> np.prod(x.shape) * x.itemsize
+ 480
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('ndim',
+ """
+ Number of array dimensions.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3])
+ >>> x.ndim
+ 1
+ >>> y = np.zeros((2, 3, 4))
+ >>> y.ndim
+ 3
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('real',
+ """
+ The real part of the array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.sqrt([1+0j, 0+1j])
+ >>> x.real
+ array([ 1. , 0.70710678])
+ >>> x.real.dtype
+ dtype('float64')
+
+ See Also
+ --------
+ numpy.real : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('shape',
+ """
+ Tuple of array dimensions.
+
+ The shape property is usually used to get the current shape of an array,
+ but may also be used to reshape the array in-place by assigning a tuple of
+ array dimensions to it. As with `numpy.reshape`, one of the new shape
+ dimensions can be -1, in which case its value is inferred from the size of
+ the array and the remaining dimensions. Reshaping an array in-place will
+ fail if a copy is required.
+
+ .. warning::
+
+ Setting ``arr.shape`` is discouraged and may be deprecated in the
+ future. Using `ndarray.reshape` is the preferred approach.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3, 4])
+ >>> x.shape
+ (4,)
+ >>> y = np.zeros((2, 3, 4))
+ >>> y.shape
+ (2, 3, 4)
+ >>> y.shape = (3, 8)
+ >>> y
+ array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0., 0., 0., 0.]])
+ >>> y.shape = (3, 6)
+ Traceback (most recent call last):
+ File "", line 1, in
+ ValueError: cannot reshape array of size 24 into shape (3,6)
+ >>> np.zeros((4,2))[::2].shape = (-1,)
+ Traceback (most recent call last):
+ File "", line 1, in
+ AttributeError: Incompatible shape for in-place modification. Use
+ `.reshape()` to make a copy with the desired shape.
+
+ See Also
+ --------
+ numpy.shape : Equivalent getter function.
+ numpy.reshape : Function similar to setting ``shape``.
+ ndarray.reshape : Method similar to setting ``shape``.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('size',
+ """
+ Number of elements in the array.
+
+ Equal to ``np.prod(a.shape)``, i.e., the product of the array's
+ dimensions.
+
+ Notes
+ -----
+ `a.size` returns a standard arbitrary precision Python integer. This
+ may not be the case with other methods of obtaining the same value
+ (like the suggested ``np.prod(a.shape)``, which returns an instance
+ of ``np.int_``), and may be relevant if the value is used further in
+ calculations that may overflow a fixed size integer type.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
+ >>> x.size
+ 30
+ >>> np.prod(x.shape)
+ 30
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('strides',
+ """
+ Tuple of bytes to step in each dimension when traversing an array.
+
+ The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
+ is::
+
+ offset = sum(np.array(i) * a.strides)
+
+ A more detailed explanation of strides can be found in
+ :ref:`arrays.ndarray`.
+
+ .. warning::
+
+ Setting ``arr.strides`` is discouraged and may be deprecated in the
+ future. `numpy.lib.stride_tricks.as_strided` should be preferred
+ to create a new view of the same data in a safer way.
+
+ Notes
+ -----
+ Imagine an array of 32-bit integers (each 4 bytes)::
+
+ x = np.array([[0, 1, 2, 3, 4],
+ [5, 6, 7, 8, 9]], dtype=np.int32)
+
+ This array is stored in memory as 40 bytes, one after the other
+ (known as a contiguous block of memory). The strides of an array tell
+ us how many bytes we have to skip in memory to move to the next position
+ along a certain axis. For example, we have to skip 4 bytes (1 value) to
+ move to the next column, but 20 bytes (5 values) to get to the same
+ position in the next row. As such, the strides for the array `x` will be
+ ``(20, 4)``.
+
+ See Also
+ --------
+ numpy.lib.stride_tricks.as_strided
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> y = np.reshape(np.arange(2 * 3 * 4, dtype=np.int32), (2, 3, 4))
+ >>> y
+ array([[[ 0, 1, 2, 3],
+ [ 4, 5, 6, 7],
+ [ 8, 9, 10, 11]],
+ [[12, 13, 14, 15],
+ [16, 17, 18, 19],
+ [20, 21, 22, 23]]], dtype=np.int32)
+ >>> y.strides
+ (48, 16, 4)
+ >>> y[1, 1, 1]
+ np.int32(17)
+ >>> offset = sum(y.strides * np.array((1, 1, 1)))
+ >>> offset // y.itemsize
+ np.int64(17)
+
+ >>> x = np.reshape(np.arange(5*6*7*8, dtype=np.int32), (5, 6, 7, 8))
+ >>> x = x.transpose(2, 3, 1, 0)
+ >>> x.strides
+ (32, 4, 224, 1344)
+ >>> i = np.array([3, 5, 2, 2], dtype=np.int32)
+ >>> offset = sum(i * x.strides)
+ >>> x[3, 5, 2, 2]
+ np.int32(813)
+ >>> offset // x.itemsize
+ np.int64(813)
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('T',
+ """
+ View of the transposed array.
+
+ Same as ``self.transpose()``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> a
+ array([[1, 2],
+ [3, 4]])
+ >>> a.T
+ array([[1, 3],
+ [2, 4]])
+
+ >>> a = np.array([1, 2, 3, 4])
+ >>> a
+ array([1, 2, 3, 4])
+ >>> a.T
+ array([1, 2, 3, 4])
+
+ See Also
+ --------
+ transpose
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('mT',
+ """
+ View of the matrix transposed array.
+
+ The matrix transpose is the transpose of the last two dimensions, even
+ if the array is of higher dimension.
+
+ .. versionadded:: 2.0
+
+ Raises
+ ------
+ ValueError
+ If the array is of dimension less than 2.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> a
+ array([[1, 2],
+ [3, 4]])
+ >>> a.mT
+ array([[1, 3],
+ [2, 4]])
+
+ >>> a = np.arange(8).reshape((2, 2, 2))
+ >>> a
+ array([[[0, 1],
+ [2, 3]],
+
+ [[4, 5],
+ [6, 7]]])
+ >>> a.mT
+ array([[[0, 2],
+ [1, 3]],
+
+ [[4, 6],
+ [5, 7]]])
+
+ """))
+
+##############################################################################
+#
+# ndarray methods
+#
+##############################################################################
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array__',
+ """
+ __array__($self, dtype=None, /, *, copy=None)
+ --
+
+ a.__array__([dtype], *, copy=None)
+
+ For ``dtype`` parameter it returns a new reference to self if
+ ``dtype`` is not given or it matches array's data type.
+ A new array of provided data type is returned if ``dtype``
+ is different from the current data type of the array.
+ For ``copy`` parameter it returns a new reference to self if
+ ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
+ parameter. The method returns a new array for ``copy=True``, regardless of
+ ``dtype`` parameter.
+
+ A more detailed explanation of the ``__array__`` interface
+ can be found in :ref:`dunder_array.interface`.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_finalize__',
+ """
+ __array_finalize__($self, obj, /)
+ --
+
+ a.__array_finalize__(obj, /)
+
+ Present so subclasses can call super. Does nothing.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_function__',
+ """
+ __array_function__($self, /, func, types, args, kwargs)
+ --
+
+ a.__array_function__(func, types, args, kwargs)
+
+ See :ref:`NEP 18 ` and :ref:`NEP 35 ` for details.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_ufunc__',
+ """
+ __array_ufunc__($self, ufunc, method, /, *inputs, **kwargs)
+ --
+
+ a.__array_ufunc__(ufunc, method, /, *inputs, **kwargs)
+
+ See :ref:`NEP 13 ` for details.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_wrap__',
+ """
+ __array_wrap__($self, array, context=None, return_scalar=True, /)
+ --
+
+ a.__array_wrap__(array[, context[, return_scalar]], /)
+
+ Returns a view of `array` with the same type as self.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__class_getitem__',
+ """
+ __class_getitem__($cls, item, /)
+ --
+
+ ndarray[shape, dtype]
+
+ Return a parametrized wrapper around the `~numpy.ndarray` type.
+
+ .. versionadded:: 1.22
+
+ Returns
+ -------
+ alias : types.GenericAlias
+ A parametrized `~numpy.ndarray` type.
+
+ Examples
+ --------
+ >>> import numpy as np
+
+ >>> np.ndarray[tuple[int], np.dtype[np.uint8]]
+ numpy.ndarray[tuple[int], numpy.dtype[numpy.uint8]]
+
+ See Also
+ --------
+ :pep:`585` : Type hinting generics in standard collections.
+ numpy.typing.NDArray : An ndarray alias :term:`generic `
+ w.r.t. its `dtype.type `.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__dlpack__',
+ """
+ __dlpack__($self, /, *, stream=None, max_version=None, dl_device=None, copy=None)
+ --
+
+ a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
+
+ Exports the array for consumption by ``from_dlpack()`` as a DLPack capsule.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__dlpack_device__',
+ """
+ __dlpack_device__($self, /)
+ --
+
+ a.__dlpack_device__()
+
+ Returns device type (``1``) and device ID (``0``) in DLPack format.
+ Meant for use within ``from_dlpack()``.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__reduce__',
+ """
+ __reduce__($self, /)
+ --
+
+ a.__reduce__()
+
+ For pickling.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__reduce_ex__',
+ """
+ __reduce_ex__($self, protocol, /)
+ --
+
+ a.__reduce_ex__(protocol, /)
+
+ For pickling.
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('__setstate__',
+ """
+ __setstate__($self, state, /)
+ --
+
+ a.__setstate__(state, /)
+
+ For unpickling.
+
+ The `state` argument must be a sequence that contains the following
+ elements:
+
+ Parameters
+ ----------
+ version : int
+ optional pickle version. If omitted defaults to 0.
+ shape : tuple
+ dtype : data-type
+ isFortran : bool
+ rawdata : string or list
+ a binary string with the data (or a list if 'a' is an object array)
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('dot',
+ """
+ dot($self, other, /, out=None)
+ --
+
+ a.dot(other, /, out=None)
+
+ Refer to :func:`numpy.dot` for full documentation.
+
+ See Also
+ --------
+ numpy.dot : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('argpartition',
+ """
+ argpartition($self, kth, /, axis=-1, kind='introselect', order=None)
+ --
+
+ a.argpartition(kth, axis=-1, kind='introselect', order=None)
+
+ Returns the indices that would partition this array.
+
+ Refer to `numpy.argpartition` for full documentation.
+
+ See Also
+ --------
+ numpy.argpartition : equivalent function
+
+ """))
+
+
+add_newdoc('numpy._core.multiarray', 'ndarray', ('partition',
+ """
+ partition($self, kth, /, axis=-1, kind='introselect', order=None)
+ --
+
+ a.partition(kth, axis=-1, kind='introselect', order=None)
+
+ Partially sorts the elements in the array in such a way that the value of
+ the element in k-th position is in the position it would be in a sorted
+ array. In the output array, all elements smaller than the k-th element
+ are located to the left of this element and all equal or greater are
+ located to its right. The ordering of the elements in the two partitions
+ on the either side of the k-th element in the output array is undefined.
+
+ Parameters
+ ----------
+ kth : int or sequence of ints
+ Element index to partition by. The kth element value will be in its
+ final sorted position and all smaller elements will be moved before it
+ and all equal or greater elements behind it.
+ The order of all elements in the partitions is undefined.
+ If provided with a sequence of kth it will partition all elements
+ indexed by kth of them into their sorted position at once.
+
+ .. deprecated:: 1.22.0
+ Passing booleans as index is deprecated.
+ axis : int, optional
+ Axis along which to sort. Default is -1, which means sort along the
+ last axis.
+ kind : {'introselect'}, optional
+ Selection algorithm. Default is 'introselect'.
+ order : str or list of str, optional
+ When `a` is an array with fields defined, this argument specifies
+ which fields to compare first, second, etc. A single field can
+ be specified as a string, and not all fields need to be specified,
+ but unspecified fields will still be used, in the order in which
+ they come up in the dtype, to break ties.
+
+ See Also
+ --------
+ numpy.partition : Return a partitioned copy of an array.
+ argpartition : Indirect partition.
+ sort : Full sort.
+
+ Notes
+ -----
+ See ``np.partition`` for notes on the different algorithms.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([3, 4, 2, 1])
+ >>> a.partition(3)
+ >>> a
+ array([2, 1, 3, 4]) # may vary
+
+ >>> a.partition((1, 3))
+ >>> a
+ array([1, 2, 3, 4])
+
+ """))
+
+
+##############################################################################
+#
+# methods from both `ndarray` and `generic`
+#
+##############################################################################
+
+_METHOD_DOC_TEMPLATE = """{name}({params})
+--
+
+{doc}"""
+
+def _array_method_doc(name: str, params: str, doc: str) -> None:
+ """
+ Interenal helper function for adding docstrings to a common method of
+ `numpy.ndarray` and `numpy.generic`.
+
+ The provided docstring will be added to the given `numpy.ndarray` method.
+ For the `numpy.generic` method, a shorter docstring indicating that it is
+ identical to the `ndarray` method will be created.
+ Both methods will have a proper and identical `__text_signature__`.
+
+ Parameters
+ ----------
+ name : str
+ Name of the method.
+ params : str
+ Parameter signature for the method without parentheses, for example,
+ ``"a, /, dtype=None, *, copy=False"``.
+ Parameter defaults must be understood by `ast.literal_eval`, i.e. strings,
+ bytes, numbers, tuples, lists, dicts, sets, booleans, or None.
+ doc : str
+ The full docstring for the `ndarray` method.
+ """
+
+ # prepend the pos-only `$self` parameter to the method signature
+ if "/" not in params:
+ params = f"/, {params}" if params else "/"
+ params = f"$self, {params}"
+
+ # add docstring to `np.ndarray.{name}`
+ doc = textwrap.dedent(doc).strip()
+ doc_array = _METHOD_DOC_TEMPLATE.format(name=name, params=params, doc=doc)
+ add_newdoc("numpy._core.multiarray", "ndarray", (name, doc_array))
+
+ # add docstring to `np.generic.{name}`
+ doc_scalar = f"Scalar method identical to `ndarray.{name}`."
+ doc_scalar = _METHOD_DOC_TEMPLATE.format(name=name, params=params, doc=doc_scalar)
+ add_newdoc("numpy._core.numerictypes", "generic", (name, doc_scalar))
+
+
+_array_method_doc('__array_namespace__', "*, api_version=None",
+ """
+ a.__array_namespace__(*, api_version=None)
+
+ For Array API compatibility.
+ """)
+
+_array_method_doc('__copy__', "",
+ """
+ a.__copy__()
+
+ Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
+
+ Equivalent to ``a.copy(order='K')``.
+ """)
+
+_array_method_doc('__deepcopy__', "memo, /",
+ """
+ a.__deepcopy__(memo, /)
+
+ Used if :func:`copy.deepcopy` is called on an array.
+ """)
+
+_array_method_doc('all', "axis=None, out=None, keepdims=False, *, where=True",
+ """
+ a.all(axis=None, out=None, *, keepdims=, where=)
+
+ Returns True if all elements evaluate to True.
+
+ Refer to `numpy.all` for full documentation.
+
+ See Also
+ --------
+ numpy.all : equivalent function
+ """)
+
+_array_method_doc('any', "axis=None, out=None, keepdims=False, *, where=True",
+ """
+ a.any(axis=None, out=None, *, keepdims=, where=)
+
+ Returns True if any of the elements of `a` evaluate to True.
+
+ Refer to `numpy.any` for full documentation.
+
+ See Also
+ --------
+ numpy.any : equivalent function
+ """)
+
+_array_method_doc('argmax', "axis=None, out=None, *, keepdims=False",
+ """
+ a.argmax(axis=None, out=None, *, keepdims=False)
+
+ Return indices of the maximum values along the given axis.
+
+ Refer to `numpy.argmax` for full documentation.
+
+ See Also
+ --------
+ numpy.argmax : equivalent function
+ """)
+
+_array_method_doc('argmin', "axis=None, out=None, *, keepdims=False",
+ """
+ a.argmin(axis=None, out=None, *, keepdims=False)
+
+ Return indices of the minimum values along the given axis.
+
+ Refer to `numpy.argmin` for detailed documentation.
+
+ See Also
+ --------
+ numpy.argmin : equivalent function
+ """)
+
+_array_method_doc('argsort', "axis=-1, kind=None, order=None, *, stable=None",
+ """
+ a.argsort(axis=-1, kind=None, order=None, *, stable=None)
+
+ Returns the indices that would sort this array.
+
+ Refer to `numpy.argsort` for full documentation.
+
+ See Also
+ --------
+ numpy.argsort : equivalent function
+ """)
+
+_array_method_doc('astype', "dtype, order='K', casting='unsafe', subok=True, copy=True",
+ """
+ a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
+
+ Copy of the array, cast to a specified type.
+
+ Parameters
+ ----------
+ dtype : str or dtype
+ Typecode or data-type to which the array is cast.
+ order : {'C', 'F', 'A', 'K'}, optional
+ Controls the memory layout order of the result.
+ 'C' means C order, 'F' means Fortran order, 'A'
+ means 'F' order if all the arrays are Fortran contiguous,
+ 'C' order otherwise, and 'K' means as close to the
+ order the array elements appear in memory as possible.
+ Default is 'K'.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'same_value', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Defaults to 'unsafe'
+ for backwards compatibility.
+
+ * 'no' means the data types should not be cast at all.
+ * 'equiv' means only byte-order changes are allowed.
+ * 'safe' means only casts which can preserve values are allowed.
+ * 'same_kind' means only safe casts or casts within a kind,
+ like float64 to float32, are allowed.
+ * 'unsafe' means any data conversions may be done.
+ * 'same_value' means any data conversions may be done, but the values
+ must not change, including rounding of floats or overflow of ints
+
+ .. versionadded:: 2.4
+ Support for ``'same_value'`` was added.
+
+ subok : bool, optional
+ If True, then sub-classes will be passed-through (default), otherwise
+ the returned array will be forced to be a base-class array.
+ copy : bool, optional
+ By default, astype always returns a newly allocated array. If this
+ is set to false, and the `dtype`, `order`, and `subok`
+ requirements are satisfied, the input array is returned instead
+ of a copy.
+
+ Returns
+ -------
+ arr_t : ndarray
+ Unless `copy` is False and the other conditions for returning the input
+ array are satisfied (see description for `copy` input parameter), `arr_t`
+ is a new array of the same shape as the input array, with dtype, order
+ given by `dtype`, `order`.
+
+ Raises
+ ------
+ ComplexWarning
+ When casting from complex to float or int. To avoid this,
+ one should use ``a.real.astype(t)``.
+ ValueError
+ When casting using ``'same_value'`` and the values change or would
+ overflow
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 2.5])
+ >>> x
+ array([1. , 2. , 2.5])
+
+ >>> x.astype(int)
+ array([1, 2, 2])
+
+ >>> x.astype(int, casting="same_value")
+ Traceback (most recent call last):
+ ...
+ ValueError: could not cast 'same_value' double to long
+
+ >>> x[:2].astype(int, casting="same_value")
+ array([1, 2])
+ """)
+
+_array_method_doc('byteswap', "inplace=False",
+ """
+ a.byteswap(inplace=False)
+
+ Swap the bytes of the array elements
+
+ Toggle between low-endian and big-endian data representation by
+ returning a byteswapped array, optionally swapped in-place.
+ Arrays of byte-strings are not swapped. The real and imaginary
+ parts of a complex number are swapped individually.
+
+ Parameters
+ ----------
+ inplace : bool, optional
+ If ``True``, swap bytes in-place, default is ``False``.
+
+ Returns
+ -------
+ out : ndarray
+ The byteswapped array. If `inplace` is ``True``, this is
+ a view to self.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> A = np.array([1, 256, 8755], dtype=np.int16)
+ >>> list(map(hex, A))
+ ['0x1', '0x100', '0x2233']
+ >>> A.byteswap(inplace=True)
+ array([ 256, 1, 13090], dtype=int16)
+ >>> list(map(hex, A))
+ ['0x100', '0x1', '0x3322']
+
+ Arrays of byte-strings are not swapped
+
+ >>> A = np.array([b'ceg', b'fac'])
+ >>> A.byteswap()
+ array([b'ceg', b'fac'], dtype='|S3')
+
+ ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
+ the same values but different representation in memory
+
+ >>> A = np.array([1, 2, 3],dtype=np.int64)
+ >>> A.view(np.uint8)
+ array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
+ 0, 0], dtype=uint8)
+ >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
+ array([1, 2, 3], dtype='>i8')
+ >>> A.view(np.uint8)
+ array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
+ 0, 3], dtype=uint8)
+ """)
+
+_array_method_doc('choose', "choices, out=None, mode='raise'",
+ """
+ a.choose(choices, out=None, mode='raise')
+
+ Use an index array to construct a new array from a set of choices.
+
+ Refer to `numpy.choose` for full documentation.
+
+ See Also
+ --------
+ numpy.choose : equivalent function
+ """)
+
+_array_method_doc('clip', "min=None, max=None, out=None, **kwargs",
+ """
+ a.clip(min=, max=, out=None, **kwargs)
+
+ Return an array whose values are limited to ``[min, max]``.
+ One of max or min must be given.
+
+ Refer to `numpy.clip` for full documentation.
+
+ See Also
+ --------
+ numpy.clip : equivalent function
+ """)
+
+_array_method_doc('compress', "condition, axis=None, out=None",
+ """
+ a.compress(condition, axis=None, out=None)
+
+ Return selected slices of this array along given axis.
+
+ Refer to `numpy.compress` for full documentation.
+
+ See Also
+ --------
+ numpy.compress : equivalent function
+ """)
+
+_array_method_doc('conj', "",
+ """
+ a.conj()
+
+ Complex-conjugate all elements.
+
+ Refer to `numpy.conjugate` for full documentation.
+
+ See Also
+ --------
+ numpy.conjugate : equivalent function
+ """)
+
+_array_method_doc('conjugate', "",
+ """
+ a.conjugate()
+
+ Return the complex conjugate, element-wise.
+
+ Refer to `numpy.conjugate` for full documentation.
+
+ See Also
+ --------
+ numpy.conjugate : equivalent function
+ """)
+
+_array_method_doc('copy', "order='C'",
+ """
+ a.copy(order='C')
+
+ Return a copy of the array.
+
+ Parameters
+ ----------
+ order : {'C', 'F', 'A', 'K'}, optional
+ Controls the memory layout of the copy. 'C' means C-order,
+ 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
+ 'C' otherwise. 'K' means match the layout of `a` as closely
+ as possible. (Note that this function and :func:`numpy.copy` are very
+ similar but have different default values for their order=
+ arguments, and this function always passes sub-classes through.)
+
+ See also
+ --------
+ numpy.copy : Similar function with different default behavior
+ numpy.copyto
+
+ Notes
+ -----
+ This function is the preferred method for creating an array copy. The
+ function :func:`numpy.copy` is similar, but it defaults to using order 'K',
+ and will not pass sub-classes through by default.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([[1,2,3],[4,5,6]], order='F')
+
+ >>> y = x.copy()
+
+ >>> x.fill(0)
+
+ >>> x
+ array([[0, 0, 0],
+ [0, 0, 0]])
+
+ >>> y
+ array([[1, 2, 3],
+ [4, 5, 6]])
+
+ >>> y.flags['C_CONTIGUOUS']
+ True
+
+ For arrays containing Python objects (e.g. dtype=object),
+ the copy is a shallow one. The new array will contain the
+ same object which may lead to surprises if that object can
+ be modified (is mutable):
+
+ >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
+ >>> b = a.copy()
+ >>> b[2][0] = 10
+ >>> a
+ array([1, 'm', list([10, 3, 4])], dtype=object)
+
+ To ensure all elements within an ``object`` array are copied,
+ use `copy.deepcopy`:
+
+ >>> import copy
+ >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
+ >>> c = copy.deepcopy(a)
+ >>> c[2][0] = 10
+ >>> c
+ array([1, 'm', list([10, 3, 4])], dtype=object)
+ >>> a
+ array([1, 'm', list([2, 3, 4])], dtype=object)
+ """)
+
+_array_method_doc('cumprod', "axis=None, dtype=None, out=None",
+ """
+ a.cumprod(axis=None, dtype=None, out=None)
+
+ Return the cumulative product of the elements along the given axis.
+
+ Refer to `numpy.cumprod` for full documentation.
+
+ See Also
+ --------
+ numpy.cumprod : equivalent function
+ """)
+
+_array_method_doc('cumsum', "axis=None, dtype=None, out=None",
+ """
+ a.cumsum(axis=None, dtype=None, out=None)
+
+ Return the cumulative sum of the elements along the given axis.
+
+ Refer to `numpy.cumsum` for full documentation.
+
+ See Also
+ --------
+ numpy.cumsum : equivalent function
+ """)
+
+_array_method_doc('diagonal', "offset=0, axis1=0, axis2=1",
+ """
+ a.diagonal(offset=0, axis1=0, axis2=1)
+
+ Return specified diagonals. In NumPy 1.9 the returned array is a
+ read-only view instead of a copy as in previous NumPy versions. In
+ a future version the read-only restriction will be removed.
+
+ Refer to :func:`numpy.diagonal` for full documentation.
+
+ See Also
+ --------
+ numpy.diagonal : equivalent function
+ """)
+
+_array_method_doc('dump', "file",
+ """
+ a.dump(file)
+
+ Dump a pickle of the array to the specified file.
+ The array can be read back with pickle.load or numpy.load.
+
+ Parameters
+ ----------
+ file : str or Path
+ A string naming the dump file.
+ """)
+
+_array_method_doc('dumps', "",
+ """
+ a.dumps()
+
+ Returns the pickle of the array as a string.
+ ``pickle.loads`` will convert the string back to an array.
+
+ Parameters
+ ----------
+ None
+ """)
+
+_array_method_doc('fill', "value",
+ """
+ a.fill(value)
+
+ Fill the array with a scalar value.
+
+ Parameters
+ ----------
+ value : scalar
+ All elements of `a` will be assigned this value.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([1, 2])
+ >>> a.fill(0)
+ >>> a
+ array([0, 0])
+ >>> a = np.empty(2)
+ >>> a.fill(1)
+ >>> a
+ array([1., 1.])
+
+ Fill expects a scalar value and always behaves the same as assigning
+ to a single array element. The following is a rare example where this
+ distinction is important:
+
+ >>> a = np.array([None, None], dtype=object)
+ >>> a[0] = np.array(3)
+ >>> a
+ array([array(3), None], dtype=object)
+ >>> a.fill(np.array(3))
+ >>> a
+ array([array(3), array(3)], dtype=object)
+
+ Where other forms of assignments will unpack the array being assigned:
+
+ >>> a[...] = np.array(3)
+ >>> a
+ array([3, 3], dtype=object)
+ """)
+
+_array_method_doc('flatten', "order='C'",
+ """
+ a.flatten(order='C')
+
+ Return a copy of the array collapsed into one dimension.
+
+ Parameters
+ ----------
+ order : {'C', 'F', 'A', 'K'}, optional
+ 'C' means to flatten in row-major (C-style) order.
+ 'F' means to flatten in column-major (Fortran-
+ style) order. 'A' means to flatten in column-major
+ order if `a` is Fortran *contiguous* in memory,
+ row-major order otherwise. 'K' means to flatten
+ `a` in the order the elements occur in memory.
+ The default is 'C'.
+
+ Returns
+ -------
+ y : ndarray
+ A copy of the input array, flattened to one dimension.
+
+ See Also
+ --------
+ ravel : Return a flattened array.
+ flat : A 1-D flat iterator over the array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1,2], [3,4]])
+ >>> a.flatten()
+ array([1, 2, 3, 4])
+ >>> a.flatten('F')
+ array([1, 3, 2, 4])
+ """)
+
+_array_method_doc('getfield', "dtype, offset=0",
+ """
+ a.getfield(dtype, offset=0)
+
+ Returns a field of the given array as a certain type.
+
+ A field is a view of the array data with a given data-type. The values in
+ the view are determined by the given type and the offset into the current
+ array in bytes. The offset needs to be such that the view dtype fits in the
+ array dtype; for example an array of dtype complex128 has 16-byte elements.
+ If taking a view with a 32-bit integer (4 bytes), the offset needs to be
+ between 0 and 12 bytes.
+
+ Parameters
+ ----------
+ dtype : str or dtype
+ The data type of the view. The dtype size of the view can not be larger
+ than that of the array itself.
+ offset : int
+ Number of bytes to skip before beginning the element view.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.diag([1.+1.j]*2)
+ >>> x[1, 1] = 2 + 4.j
+ >>> x
+ array([[1.+1.j, 0.+0.j],
+ [0.+0.j, 2.+4.j]])
+ >>> x.getfield(np.float64)
+ array([[1., 0.],
+ [0., 2.]])
+
+ By choosing an offset of 8 bytes we can select the complex part of the
+ array for our view:
+
+ >>> x.getfield(np.float64, offset=8)
+ array([[1., 0.],
+ [0., 4.]])
+ """)
+
+_array_method_doc('item', "*args",
+ """
+ a.item(*args)
+
+ Copy an element of an array to a standard Python scalar and return it.
+
+ Parameters
+ ----------
+ \\*args : Arguments (variable number and type)
+
+ * none: in this case, the method only works for arrays
+ with one element (`a.size == 1`), which element is
+ copied into a standard Python scalar object and returned.
+
+ * int_type: this argument is interpreted as a flat index into
+ the array, specifying which element to copy and return.
+
+ * tuple of int_types: functions as does a single int_type argument,
+ except that the argument is interpreted as an nd-index into the
+ array.
+
+ Returns
+ -------
+ z : Standard Python scalar object
+ A copy of the specified element of the array as a suitable
+ Python scalar
+
+ Notes
+ -----
+ When the data type of `a` is longdouble or clongdouble, item() returns
+ a scalar array object because there is no available Python scalar that
+ would not lose information. Void arrays return a buffer object for item(),
+ unless fields are defined, in which case a tuple is returned.
+
+ `item` is very similar to a[args], except, instead of an array scalar,
+ a standard Python scalar is returned. This can be useful for speeding up
+ access to elements of the array and doing arithmetic on elements of the
+ array using Python's optimized math.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.random.seed(123)
+ >>> x = np.random.randint(9, size=(3, 3))
+ >>> x
+ array([[2, 2, 6],
+ [1, 3, 6],
+ [1, 0, 1]])
+ >>> x.item(3)
+ 1
+ >>> x.item(7)
+ 0
+ >>> x.item((0, 1))
+ 2
+ >>> x.item((2, 2))
+ 1
+
+ For an array with object dtype, elements are returned as-is.
+
+ >>> a = np.array([np.int64(1)], dtype=object)
+ >>> a.item() #return np.int64
+ np.int64(1)
+ """)
+
+_KWARGS_REDUCE = "keepdims=, initial=, where="
+
+_array_method_doc('max', "axis=None, out=None, **kwargs",
+ f"""
+ a.max(axis=None, out=None, *, {_KWARGS_REDUCE})
+
+ Return the maximum along a given axis.
+
+ Refer to `numpy.amax` for full documentation.
+
+ See Also
+ --------
+ numpy.amax : equivalent function
+ """)
+
+_array_method_doc('min', "axis=None, out=None, **kwargs",
+ f"""
+ a.min(axis=None, out=None, *, {_KWARGS_REDUCE})
+
+ Return the minimum along a given axis.
+
+ Refer to `numpy.amin` for full documentation.
+
+ See Also
+ --------
+ numpy.amin : equivalent function
+ """)
+
+_array_method_doc('prod', "axis=None, dtype=None, out=None, **kwargs",
+ f"""
+ a.prod(axis=None, dtype=None, out=None, *, {_KWARGS_REDUCE})
+
+ Return the product of the array elements over the given axis
+
+ Refer to `numpy.prod` for full documentation.
+
+ See Also
+ --------
+ numpy.prod : equivalent function
+ """)
+
+_array_method_doc('sum', "axis=None, dtype=None, out=None, **kwargs",
+ f"""
+ a.sum(axis=None, dtype=None, out=None, *, {_KWARGS_REDUCE})
+
+ Return the sum of the array elements over the given axis.
+
+ Refer to `numpy.sum` for full documentation.
+
+ See Also
+ --------
+ numpy.sum : equivalent function
+ """)
+
+_array_method_doc('mean', "axis=None, dtype=None, out=None, **kwargs",
+ """
+ a.mean(axis=None, dtype=None, out=None, *, keepdims=, where=)
+
+ Returns the average of the array elements along given axis.
+
+ Refer to `numpy.mean` for full documentation.
+
+ See Also
+ --------
+ numpy.mean : equivalent function
+ """)
+
+_array_method_doc('nonzero', "",
+ """
+ a.nonzero()
+
+ Return the indices of the elements that are non-zero.
+
+ Refer to `numpy.nonzero` for full documentation.
+
+ See Also
+ --------
+ numpy.nonzero : equivalent function
+ """)
+
+_array_method_doc('put', "indices, values, /, mode='raise'",
+ """
+ a.put(indices, values, mode='raise')
+
+ Set ``a.flat[n] = values[n]`` for all ``n`` in indices.
+
+ Refer to `numpy.put` for full documentation.
+
+ See Also
+ --------
+ numpy.put : equivalent function
+ """)
+
+_array_method_doc('ravel', "order='C'",
+ """
+ a.ravel(order='C')
+
+ Return a flattened array.
+
+ Refer to `numpy.ravel` for full documentation.
+
+ See Also
+ --------
+ numpy.ravel : equivalent function
+ ndarray.flat : a flat iterator on the array.
+ """)
+
+_array_method_doc('repeat', "repeats, /, axis=None",
+ """
+ a.repeat(repeats, axis=None)
+
+ Repeat elements of an array.
+
+ Refer to `numpy.repeat` for full documentation.
+
+ See Also
+ --------
+ numpy.repeat : equivalent function
+ """)
+
+_array_method_doc('reshape', "*shape, order='C', copy=None",
+ """
+ a.reshape(shape, /, *, order='C', copy=None)
+ a.reshape(*shape, order='C', copy=None)
+
+ Returns an array containing the same data with a new shape.
+
+ Refer to `numpy.reshape` for full documentation.
+
+ See Also
+ --------
+ numpy.reshape : equivalent function
+
+ Notes
+ -----
+ Unlike the free function `numpy.reshape`, this method on `ndarray` allows
+ the elements of the shape parameter to be passed in as separate arguments.
+ For example, ``a.reshape(4, 2)`` is equivalent to ``a.reshape((4, 2))``.
+ """)
+
+_array_method_doc('resize', "*new_shape, refcheck=True",
+ """
+ a.resize(new_shape, /, *, refcheck=True)
+ a.resize(*new_shape, refcheck=True)
+
+ Change shape and size of array in-place.
+
+ Parameters
+ ----------
+ new_shape : tuple of ints, or `n` ints
+ Shape of resized array.
+ refcheck : bool, optional
+ If False, reference count will not be checked. Default is True.
+ See Notes below for more explanation.
+
+ Returns
+ -------
+ None
+
+ Raises
+ ------
+ ValueError
+ If `a` does not own its own data or references or views to may exist.
+
+ See Also
+ --------
+ resize : Return a new array with the specified shape.
+
+ Notes
+ -----
+ This reallocates space for the data area if necessary.
+
+ Only contiguous arrays (data elements consecutive in memory) can be
+ resized.
+
+ Reallocating arrays in-place can often lead to memory fragmentation and
+ should be avoided. If the goal is to reclaim over-allocated memory,
+ alternatives are to create a view or a copy of just the desired data, or
+ using two passes to build the array: one to cheaply determine the shape and
+ another to allocate and fill. Benchmark your use case to determine what is
+ optimum. You may be surprised to find ``resize`` actually slows down or
+ bloats your application.
+
+ The purpose of the reference count check is to make sure you
+ do not use this array as a buffer for another Python object and then
+ reallocate the memory.
+
+ On Python 3.13 and older, the check allows objects with exactly one
+ reference to be reallocated in-place. On Python 3.14 and newer, the array
+ must be uniquely referenced. See [1]_ for more details.
+
+ If you are sure that you have not shared the memory for this array with
+ another Python object, then you may safely set `refcheck` to False.
+
+
+ References
+ ----------
+ .. [1] Python 3.14 What's New, https://docs.python.org/3/whatsnew/3.14.html#whatsnew314-refcount
+
+ Examples
+ --------
+ Shrinking an array: array is flattened (in the order that the data are
+ stored in memory), resized, and reshaped:
+
+ >>> import numpy as np
+
+ >>> a = np.array([[0, 1], [2, 3]], order='C')
+ >>> a.resize((2, 1))
+ >>> a
+ array([[0],
+ [1]])
+
+ >>> a = np.array([[0, 1], [2, 3]], order='F')
+ >>> a.resize((2, 1))
+ >>> a
+ array([[0],
+ [2]])
+
+ Enlarging an array: as above, but missing entries are filled with zeros:
+
+ >>> b = np.array([[0, 1], [2, 3]])
+ >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
+ >>> b
+ array([[0, 1, 2],
+ [3, 0, 0]])
+
+ Referencing an array prevents resizing...
+
+ >>> c = a
+ >>> a.resize((1, 1))
+ Traceback (most recent call last):
+ ...
+ ValueError: cannot resize an array that references or is referenced ...
+
+ Unless `refcheck` is False:
+
+ >>> a.resize((1, 1), refcheck=False)
+ >>> a
+ array([[0]])
+ >>> c
+ array([[0]])
+ """)
+
+_array_method_doc('round', "decimals=0, out=None",
+ """
+ a.round(decimals=0, out=None)
+
+ Return `a` with each element rounded to the given number of decimals.
+
+ Refer to `numpy.around` for full documentation.
+
+ See Also
+ --------
+ numpy.around : equivalent function
+ """)
+
+_array_method_doc('searchsorted', "v, /, side='left', sorter=None",
+ """
+ a.searchsorted(v, side='left', sorter=None)
+
+ Find indices where elements of `v` should be inserted in `a` to maintain order.
+
+ For full documentation, see `numpy.searchsorted`.
+
+ See Also
+ --------
+ numpy.searchsorted : equivalent function
+ """)
+
+_array_method_doc('setfield', "val, /, dtype, offset=0",
+ """
+ a.setfield(val, dtype, offset=0)
+
+ Put a value into a specified place in a field defined by a data-type.
+
+ Place `val` into `a`'s field defined by `dtype` and beginning `offset`
+ bytes into the field.
+
+ Parameters
+ ----------
+ val : object
+ Value to be placed in field.
+ dtype : dtype object
+ Data-type of the field in which to place `val`.
+ offset : int, optional
+ The number of bytes into the field at which to place `val`.
+
+ Returns
+ -------
+ None
+
+ See Also
+ --------
+ getfield
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.eye(3)
+ >>> x.getfield(np.float64)
+ array([[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]])
+ >>> x.setfield(3, np.int32)
+ >>> x.getfield(np.int32)
+ array([[3, 3, 3],
+ [3, 3, 3],
+ [3, 3, 3]], dtype=int32)
+ >>> x
+ array([[1.0e+000, 1.5e-323, 1.5e-323],
+ [1.5e-323, 1.0e+000, 1.5e-323],
+ [1.5e-323, 1.5e-323, 1.0e+000]])
+ >>> x.setfield(np.eye(3), np.int32)
+ >>> x
+ array([[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]])
+ """)
+
+_array_method_doc('setflags', "*, write=None, align=None, uic=None",
+ """
+ a.setflags(write=None, align=None, uic=None)
+
+ Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
+ respectively.
+
+ These Boolean-valued flags affect how numpy interprets the memory
+ area used by `a` (see Notes below). The ALIGNED flag can only
+ be set to True if the data is actually aligned according to the type.
+ The WRITEBACKIFCOPY flag can never be set
+ to True. The flag WRITEABLE can only be set to True if the array owns its
+ own memory, or the ultimate owner of the memory exposes a writeable buffer
+ interface, or is a string. (The exception for string is made so that
+ unpickling can be done without copying memory.)
+
+ Parameters
+ ----------
+ write : bool, optional
+ Describes whether or not `a` can be written to.
+ align : bool, optional
+ Describes whether or not `a` is aligned properly for its type.
+ uic : bool, optional
+ Describes whether or not `a` is a copy of another "base" array.
+
+ Notes
+ -----
+ Array flags provide information about how the memory area used
+ for the array is to be interpreted. There are 7 Boolean flags
+ in use, only three of which can be changed by the user:
+ WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
+
+ WRITEABLE (W) the data area can be written to;
+
+ ALIGNED (A) the data and strides are aligned appropriately for the hardware
+ (as determined by the compiler);
+
+ WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
+ by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
+ called, the base array will be updated with the contents of this array.
+
+ All flags can be accessed using the single (upper case) letter as well
+ as the full name.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> y = np.array([[3, 1, 7],
+ ... [2, 0, 0],
+ ... [8, 5, 9]])
+ >>> y
+ array([[3, 1, 7],
+ [2, 0, 0],
+ [8, 5, 9]])
+ >>> y.flags
+ C_CONTIGUOUS : True
+ F_CONTIGUOUS : False
+ OWNDATA : True
+ WRITEABLE : True
+ ALIGNED : True
+ WRITEBACKIFCOPY : False
+ >>> y.setflags(write=0, align=0)
+ >>> y.flags
+ C_CONTIGUOUS : True
+ F_CONTIGUOUS : False
+ OWNDATA : True
+ WRITEABLE : False
+ ALIGNED : False
+ WRITEBACKIFCOPY : False
+ >>> y.setflags(uic=1)
+ Traceback (most recent call last):
+ File "", line 1, in
+ ValueError: cannot set WRITEBACKIFCOPY flag to True
+ """)
+
+_array_method_doc('sort', "axis=-1, kind=None, order=None, *, stable=None",
+ """
+ a.sort(axis=-1, kind=None, order=None, *, stable=None)
+
+ Sort an array in-place. Refer to `numpy.sort` for full documentation.
+
+ Parameters
+ ----------
+ axis : int, optional
+ Axis along which to sort. Default is -1, which means sort along the
+ last axis.
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
+ Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
+ and 'mergesort' use timsort under the covers and, in general, the
+ actual implementation will vary with datatype. The 'mergesort' option
+ is retained for backwards compatibility.
+ order : str or list of str, optional
+ When `a` is an array with fields defined, this argument specifies
+ which fields to compare first, second, etc. A single field can
+ be specified as a string, and not all fields need be specified,
+ but unspecified fields will still be used, in the order in which
+ they come up in the dtype, to break ties.
+ stable : bool, optional
+ Sort stability. If ``True``, the returned array will maintain
+ the relative order of ``a`` values which compare as equal.
+ If ``False`` or ``None``, this is not guaranteed. Internally,
+ this option selects ``kind='stable'``. Default: ``None``.
+
+ .. versionadded:: 2.0.0
+
+ See Also
+ --------
+ numpy.sort : Return a sorted copy of an array.
+ numpy.argsort : Indirect sort.
+ numpy.lexsort : Indirect stable sort on multiple keys.
+ numpy.searchsorted : Find elements in sorted array.
+ numpy.partition: Partial sort.
+
+ Notes
+ -----
+ See `numpy.sort` for notes on the different sorting algorithms.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1,4], [3,1]])
+ >>> a.sort(axis=1)
+ >>> a
+ array([[1, 4],
+ [1, 3]])
+ >>> a.sort(axis=0)
+ >>> a
+ array([[1, 3],
+ [1, 4]])
+
+ Use the `order` keyword to specify a field to use when sorting a
+ structured array:
+
+ >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
+ >>> a.sort(order='y')
+ >>> a
+ array([(b'c', 1), (b'a', 2)],
+ dtype=[('x', 'S1'), ('y', ', where=, mean="
+
+_array_method_doc('std', "axis=None, dtype=None, out=None, ddof=0, **kwargs",
+ f"""
+ a.std(axis=None, dtype=None, out=None, ddof=0, {_KWARGS_STD})
+
+ Returns the standard deviation of the array elements along given axis.
+
+ Refer to `numpy.std` for full documentation.
+
+ See Also
+ --------
+ numpy.std : equivalent function
+ """)
+
+_array_method_doc('var', "axis=None, dtype=None, out=None, ddof=0, **kwargs",
+ f"""
+ a.var(axis=None, dtype=None, out=None, ddof=0, {_KWARGS_STD})
+
+ Returns the variance of the array elements, along given axis.
+
+ Refer to `numpy.var` for full documentation.
+
+ See Also
+ --------
+ numpy.var : equivalent function
+ """)
+
+_array_method_doc('swapaxes', "axis1, axis2, /",
+ """
+ a.swapaxes(axis1, axis2, /)
+
+ Return a view of the array with `axis1` and `axis2` interchanged.
+
+ Refer to `numpy.swapaxes` for full documentation.
+
+ See Also
+ --------
+ numpy.swapaxes : equivalent function
+ """)
+
+_array_method_doc('take', "indices, /, axis=None, out=None, mode='raise'",
+ """
+ a.take(indices, axis=None, out=None, mode='raise')
+
+ Return an array formed from the elements of `a` at the given indices.
+
+ Refer to `numpy.take` for full documentation.
+
+ See Also
+ --------
+ numpy.take : equivalent function
+ """)
+
+_array_method_doc('to_device', "device, /, *, stream=None",
+ """
+ a.to_device(device, /, *, stream=None)
+
+ For Array API compatibility. Since NumPy only supports CPU arrays, this
+ method is a no-op that returns the same array.
+
+ Parameters
+ ----------
+ device : "cpu"
+ Must be ``"cpu"``.
+ stream : None, optional
+ Currently unsupported.
+
+ Returns
+ -------
+ out : Self
+ Returns the same array.
+ """)
+
+_array_method_doc('tofile', "fid, /, sep='', format='%s'",
+ """
+ a.tofile(fid, /, sep='', format='%s')
+
+ Write array to a file as text or binary (default).
+
+ Data is always written in 'C' order, independent of the order of `a`.
+ The data produced by this method can be recovered using the function
+ fromfile().
+
+ Parameters
+ ----------
+ fid : file or str or Path
+ An open file object, or a string containing a filename.
+ sep : str
+ Separator between array items for text output.
+ If "" (empty), a binary file is written, equivalent to
+ ``file.write(a.tobytes())``.
+ format : str
+ Format string for text file output.
+ Each entry in the array is formatted to text by first converting
+ it to the closest Python type, and then using "format" % item.
+
+ Notes
+ -----
+ This is a convenience function for quick storage of array data.
+ Information on endianness and precision is lost, so this method is not a
+ good choice for files intended to archive data or transport data between
+ machines with different endianness. Some of these problems can be overcome
+ by outputting the data as text files, at the expense of speed and file
+ size.
+
+ When fid is a file object, array contents are directly written to the
+ file, bypassing the file object's ``write`` method. As a result, tofile
+ cannot be used with files objects supporting compression (e.g., GzipFile)
+ or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
+ """)
+
+_array_method_doc('tolist', "",
+ """
+ a.tolist()
+
+ Return the array as an ``a.ndim``-levels deep nested list of Python scalars.
+
+ Return a copy of the array data as a (nested) Python list.
+ Data items are converted to the nearest compatible builtin Python type, via
+ the `~numpy.ndarray.item` method.
+
+ If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will
+ not be a list at all, but a simple Python scalar.
+
+ Parameters
+ ----------
+ none
+
+ Returns
+ -------
+ y : object, or list of object, or list of list of object, or ...
+ The possibly nested list of array elements.
+
+ Notes
+ -----
+ The array may be recreated via ``a = np.array(a.tolist())``, although this
+ may sometimes lose precision.
+
+ Examples
+ --------
+ For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,
+ except that ``tolist`` changes numpy scalars to Python scalars:
+
+ >>> import numpy as np
+ >>> a = np.uint32([1, 2])
+ >>> a_list = list(a)
+ >>> a_list
+ [np.uint32(1), np.uint32(2)]
+ >>> type(a_list[0])
+
+ >>> a_tolist = a.tolist()
+ >>> a_tolist
+ [1, 2]
+ >>> type(a_tolist[0])
+
+
+ Additionally, for a 2D array, ``tolist`` applies recursively:
+
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> list(a)
+ [array([1, 2]), array([3, 4])]
+ >>> a.tolist()
+ [[1, 2], [3, 4]]
+
+ The base case for this recursion is a 0D array:
+
+ >>> a = np.array(1)
+ >>> list(a)
+ Traceback (most recent call last):
+ ...
+ TypeError: iteration over a 0-d array
+ >>> a.tolist()
+ 1
+ """)
+
+_array_method_doc('tobytes', "order='C'",
+ """
+ a.tobytes(order='C')
+
+ Construct Python bytes containing the raw data bytes in the array.
+
+ Constructs Python bytes showing a copy of the raw contents of
+ data memory. The bytes object is produced in C-order by default.
+ This behavior is controlled by the ``order`` parameter.
+
+ Parameters
+ ----------
+ order : {'C', 'F', 'A'}, optional
+ Controls the memory layout of the bytes object. 'C' means C-order,
+ 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is
+ Fortran contiguous, 'C' otherwise. Default is 'C'.
+
+ Returns
+ -------
+ s : bytes
+ Python bytes exhibiting a copy of `a`'s raw data.
+
+ See also
+ --------
+ frombuffer
+ Inverse of this operation, construct a 1-dimensional array from Python
+ bytes.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([[0, 1], [2, 3]], dtype='>> x.tobytes()
+ b'\\x00\\x00\\x01\\x00\\x02\\x00\\x03\\x00'
+ >>> x.tobytes('C') == x.tobytes()
+ True
+ >>> x.tobytes('F')
+ b'\\x00\\x00\\x02\\x00\\x01\\x00\\x03\\x00'
+ """)
+
+_array_method_doc('trace', "offset=0, axis1=0, axis2=1, dtype=None, out=None",
+ """
+ a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
+
+ Return the sum along diagonals of the array.
+
+ Refer to `numpy.trace` for full documentation.
+
+ See Also
+ --------
+ numpy.trace : equivalent function
+ """)
+
+_array_method_doc('transpose', "*axes",
+ """
+ a.transpose(*axes)
+
+ Returns a view of the array with axes transposed.
+
+ Refer to `numpy.transpose` for full documentation.
+
+ Parameters
+ ----------
+ axes : None, tuple of ints, or `n` ints
+
+ * None or no argument: reverses the order of the axes.
+
+ * tuple of ints: `i` in the `j`-th place in the tuple means that the
+ array's `i`-th axis becomes the transposed array's `j`-th axis.
+
+ * `n` ints: same as an n-tuple of the same ints (this form is
+ intended simply as a "convenience" alternative to the tuple form).
+
+ Returns
+ -------
+ p : ndarray
+ View of the array with its axes suitably permuted.
+
+ See Also
+ --------
+ transpose : Equivalent function.
+ ndarray.T : Array property returning the array transposed.
+ ndarray.reshape : Give a new shape to an array without changing its data.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> a
+ array([[1, 2],
+ [3, 4]])
+ >>> a.transpose()
+ array([[1, 3],
+ [2, 4]])
+ >>> a.transpose((1, 0))
+ array([[1, 3],
+ [2, 4]])
+ >>> a.transpose(1, 0)
+ array([[1, 3],
+ [2, 4]])
+
+ >>> a = np.array([1, 2, 3, 4])
+ >>> a
+ array([1, 2, 3, 4])
+ >>> a.transpose()
+ array([1, 2, 3, 4])
+ """)
+
+_array_method_doc('view', "*args, **kwargs",
+ """
+ a.view([dtype][, type])
+
+ New view of array with the same data.
+
+ .. note::
+ Passing None for ``dtype`` is different from omitting the parameter,
+ since the former invokes ``dtype(None)`` which is an alias for
+ ``dtype('float64')``.
+
+ Parameters
+ ----------
+ dtype : data-type or ndarray sub-class, optional
+ Data-type descriptor of the returned view, e.g., float32 or int16.
+ Omitting it results in the view having the same data-type as `a`.
+ This argument can also be specified as an ndarray sub-class, which
+ then specifies the type of the returned object (this is equivalent to
+ setting the ``type`` parameter).
+ type : Python type, optional
+ Type of the returned view, e.g., ndarray or matrix. Again, omission
+ of the parameter results in type preservation.
+
+ Notes
+ -----
+ ``a.view()`` is used two different ways:
+
+ ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
+ of the array's memory with a different data-type. This can cause a
+ reinterpretation of the bytes of memory.
+
+ ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
+ returns an instance of `ndarray_subclass` that looks at the same array
+ (same shape, dtype, etc.) This does not cause a reinterpretation of the
+ memory.
+
+ For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
+ bytes per entry than the previous dtype (for example, converting a regular
+ array to a structured array), then the last axis of ``a`` must be
+ contiguous. This axis will be resized in the result.
+
+ .. versionchanged:: 1.23.0
+ Only the last axis needs to be contiguous. Previously, the entire array
+ had to be C-contiguous.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
+
+ Viewing array data using a different type and dtype:
+
+ >>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])
+ >>> y = x.view(dtype=nonneg, type=np.recarray)
+ >>> x["a"]
+ array([-1], dtype=int8)
+ >>> y.a
+ array([255], dtype=uint8)
+
+ Creating a view on a structured array so it can be used in calculations
+
+ >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
+ >>> xv = x.view(dtype=np.int8).reshape(-1,2)
+ >>> xv
+ array([[1, 2],
+ [3, 4]], dtype=int8)
+ >>> xv.mean(0)
+ array([2., 3.])
+
+ Making changes to the view changes the underlying array
+
+ >>> xv[0,1] = 20
+ >>> x
+ array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
+
+ Using a view to convert an array to a recarray:
+
+ >>> z = x.view(np.recarray)
+ >>> z.a
+ array([1, 3], dtype=int8)
+
+ Views share data:
+
+ >>> x[0] = (9, 10)
+ >>> z[0]
+ np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
+
+ Views that change the dtype size (bytes per entry) should normally be
+ avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
+
+ >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)
+ >>> y = x[:, ::2]
+ >>> y
+ array([[1, 3],
+ [4, 6]], dtype=int16)
+ >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
+ Traceback (most recent call last):
+ ...
+ ValueError: To change to a dtype of a different size, the last axis must be contiguous
+ >>> z = y.copy()
+ >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
+ array([[(1, 3)],
+ [(4, 6)]], dtype=[('width', '>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)
+ >>> x.transpose(1, 0, 2).view(np.int16)
+ array([[[ 256, 770],
+ [3340, 3854]],
+
+ [[1284, 1798],
+ [4368, 4882]],
+
+ [[2312, 2826],
+ [5396, 5910]]], dtype=int16)
+ """)
+
+
+##############################################################################
+#
+# umath functions
+#
+##############################################################################
+
+add_newdoc('numpy._core.umath', 'frompyfunc',
+ """
+ frompyfunc(func, /, nin, nout, **kwargs)
+ --
+
+ frompyfunc(func, /, nin, nout, *[, identity])
+
+ Takes an arbitrary Python function and returns a NumPy ufunc.
+
+ Can be used, for example, to add broadcasting to a built-in Python
+ function (see Examples section).
+
+ Parameters
+ ----------
+ func : Python function object
+ An arbitrary Python function.
+ nin : int
+ The number of input arguments.
+ nout : int
+ The number of objects returned by `func`.
+ identity : object, optional
+ The value to use for the `~numpy.ufunc.identity` attribute of the resulting
+ object. If specified, this is equivalent to setting the underlying
+ C ``identity`` field to ``PyUFunc_IdentityValue``.
+ If omitted, the identity is set to ``PyUFunc_None``. Note that this is
+ _not_ equivalent to setting the identity to ``None``, which implies the
+ operation is reorderable.
+
+ Returns
+ -------
+ out : ufunc
+ Returns a NumPy universal function (``ufunc``) object.
+
+ See Also
+ --------
+ vectorize : Evaluates pyfunc over input arrays using broadcasting rules of numpy.
+
+ Notes
+ -----
+ The returned ufunc always returns PyObject arrays.
+
+ Examples
+ --------
+ Use frompyfunc to add broadcasting to the Python function ``oct``:
+
+ >>> import numpy as np
+ >>> oct_array = np.frompyfunc(oct, 1, 1)
+ >>> oct_array(np.array((10, 30, 100)))
+ array(['0o12', '0o36', '0o144'], dtype=object)
+ >>> np.array((oct(10), oct(30), oct(100))) # for comparison
+ array(['0o12', '0o36', '0o144'], dtype='doc is NULL.)
+
+ Parameters
+ ----------
+ ufunc : numpy.ufunc
+ A ufunc whose current doc is NULL.
+ new_docstring : string
+ The new docstring for the ufunc.
+
+ Notes
+ -----
+ This method allocates memory for new_docstring on
+ the heap. Technically this creates a memory leak, since this
+ memory will not be reclaimed until the end of the program
+ even if the ufunc itself is removed. However this will only
+ be a problem if the user is repeatedly creating ufuncs with
+ no documentation, adding documentation via add_newdoc_ufunc,
+ and then throwing away the ufunc.
+ """)
+
+add_newdoc('numpy._core.multiarray', 'get_handler_name',
+ """
+ get_handler_name(a: ndarray) -> str | None
+
+ Return the name of the memory handler used by `a`. If not provided, return
+ the name of the memory handler that will be used to allocate data for the
+ next `ndarray` in this context. May return None if `a` does not own its
+ memory, in which case you can traverse ``a.base`` for a memory handler.
+ """)
+
+add_newdoc('numpy._core.multiarray', 'get_handler_version',
+ """
+ get_handler_version(a: ndarray) -> int,None
+
+ Return the version of the memory handler used by `a`. If not provided,
+ return the version of the memory handler that will be used to allocate data
+ for the next `ndarray` in this context. May return None if `a` does not own
+ its memory, in which case you can traverse ``a.base`` for a memory handler.
+ """)
+
+add_newdoc('numpy._core._multiarray_umath', '_array_converter',
+ """
+ _array_converter(*array_likes)
+
+ Helper to convert one or more objects to arrays. Integrates machinery
+ to deal with the ``result_type`` and ``__array_wrap__``.
+
+ The reason for this is that e.g. ``result_type`` needs to convert to arrays
+ to find the ``dtype``. But converting to an array before calling
+ ``result_type`` would incorrectly "forget" whether it was a Python int,
+ float, or complex.
+ """)
+
+add_newdoc(
+ 'numpy._core._multiarray_umath', '_array_converter', ('scalar_input',
+ """
+ A tuple which indicates for each input whether it was a scalar that
+ was coerced to a 0-D array (and was not already an array or something
+ converted via a protocol like ``__array__()``).
+ """))
+
+add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('as_arrays',
+ """
+ as_arrays(/, subok=True, pyscalars="convert_if_no_array")
+
+ Return the inputs as arrays or scalars.
+
+ Parameters
+ ----------
+ subok : True or False, optional
+ Whether array subclasses are preserved.
+ pyscalars : {"convert", "preserve", "convert_if_no_array"}, optional
+ To allow NEP 50 weak promotion later, it may be desirable to preserve
+ Python scalars. As default, these are preserved unless all inputs
+ are Python scalars. "convert" enforces an array return.
+ """))
+
+add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('result_type',
+ """result_type(/, extra_dtype=None, ensure_inexact=False)
+
+ Find the ``result_type`` just as ``np.result_type`` would, but taking
+ into account that the original inputs (before converting to an array) may
+ have been Python scalars with weak promotion.
+
+ Parameters
+ ----------
+ extra_dtype : dtype instance or class
+ An additional DType or dtype instance to promote (e.g. could be used
+ to ensure the result precision is at least float32).
+ ensure_inexact : True or False
+ When ``True``, ensures a floating point (or complex) result replacing
+ the ``arr * 1.`` or ``result_type(..., 0.0)`` pattern.
+ """))
+
+add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('wrap',
+ """
+ wrap(arr, /, to_scalar=None)
+
+ Call ``__array_wrap__`` on ``arr`` if ``arr`` is not the same subclass
+ as the input the ``__array_wrap__`` method was retrieved from.
+
+ Parameters
+ ----------
+ arr : ndarray
+ The object to be wrapped. Normally an ndarray or subclass,
+ although for backward compatibility NumPy scalars are also accepted
+ (these will be converted to a NumPy array before being passed on to
+ the ``__array_wrap__`` method).
+ to_scalar : {True, False, None}, optional
+ When ``True`` will convert a 0-d array to a scalar via ``result[()]``
+ (with a fast-path for non-subclasses). If ``False`` the result should
+ be an array-like (as ``__array_wrap__`` is free to return a non-array).
+ By default (``None``), a scalar is returned if all inputs were scalar.
+ """))
+
+
+add_newdoc('numpy._core.multiarray', '_get_madvise_hugepage',
+ """
+ _get_madvise_hugepage() -> bool
+
+ Get use of ``madvise (2)`` MADV_HUGEPAGE support when
+ allocating the array data. Returns the currently set value.
+ See `global_state` for more information.
+ """)
+
+add_newdoc('numpy._core.multiarray', '_set_madvise_hugepage',
+ """
+ _set_madvise_hugepage(enabled: bool) -> bool
+
+ Set or unset use of ``madvise (2)`` MADV_HUGEPAGE support when
+ allocating the array data. Returns the previously set value.
+ See `global_state` for more information.
+ """)
+
+
+##############################################################################
+#
+# Documentation for ufunc attributes and methods
+#
+##############################################################################
+
+
+##############################################################################
+#
+# ufunc object
+#
+##############################################################################
+
+add_newdoc('numpy._core', 'ufunc',
+ """
+ Functions that operate element by element on whole arrays.
+
+ To see the documentation for a specific ufunc, use `info`. For
+ example, ``np.info(np.sin)``. Because ufuncs are written in C
+ (for speed) and linked into Python with NumPy's ufunc facility,
+ Python's help() function finds this page whenever help() is called
+ on a ufunc.
+
+ A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.
+
+ **Calling ufuncs:** ``op(*x[, out], where=True, **kwargs)``
+
+ Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.
+
+ The broadcasting rules are:
+
+ * Dimensions of length 1 may be prepended to either array.
+ * Arrays may be repeated along dimensions of length 1.
+
+ Parameters
+ ----------
+ *x : array_like
+ Input arrays.
+ out : ndarray, None, ..., or tuple of ndarray and None, optional
+ Location(s) into which the result(s) are stored.
+ If not provided or None, new array(s) are created by the ufunc.
+ If passed as a keyword argument, can be Ellipses (``out=...``) to
+ ensure an array is returned even if the result is 0-dimensional,
+ or a tuple with length equal to the number of outputs (where None
+ can be used for allocation by the ufunc).
+
+ .. versionadded:: 2.3
+ Support for ``out=...`` was added.
+
+ where : array_like, optional
+ This condition is broadcast over the input. At locations where the
+ condition is True, the `out` array will be set to the ufunc result.
+ Elsewhere, the `out` array will retain its original value.
+ Note that if an uninitialized `out` array is created via the default
+ ``out=None``, locations within it where the condition is False will
+ remain uninitialized.
+ **kwargs
+ For other keyword-only arguments, see the :ref:`ufunc docs `.
+
+ Returns
+ -------
+ r : ndarray or tuple of ndarray
+ `r` will have the shape that the arrays in `x` broadcast to; if `out` is
+ provided, it will be returned. If not, `r` will be allocated and
+ may contain uninitialized values. If the function has more than one
+ output, then the result will be a tuple of arrays.
+
+ """)
+
+
+##############################################################################
+#
+# ufunc attributes
+#
+##############################################################################
+
+add_newdoc('numpy._core', 'ufunc', ('identity',
+ """
+ The identity value.
+
+ Data attribute containing the identity element for the ufunc,
+ if it has one. If it does not, the attribute value is None.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.add.identity
+ 0
+ >>> np.multiply.identity
+ 1
+ >>> print(np.power.identity)
+ None
+ >>> print(np.exp.identity)
+ None
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('nargs',
+ """
+ The number of arguments.
+
+ Data attribute containing the number of arguments the ufunc takes, including
+ optional ones.
+
+ Notes
+ -----
+ Typically this value will be one more than what you might expect
+ because all ufuncs take the optional "out" argument.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.add.nargs
+ 3
+ >>> np.multiply.nargs
+ 3
+ >>> np.power.nargs
+ 3
+ >>> np.exp.nargs
+ 2
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('nin',
+ """
+ The number of inputs.
+
+ Data attribute containing the number of arguments the ufunc treats as input.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.add.nin
+ 2
+ >>> np.multiply.nin
+ 2
+ >>> np.power.nin
+ 2
+ >>> np.exp.nin
+ 1
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('nout',
+ """
+ The number of outputs.
+
+ Data attribute containing the number of arguments the ufunc treats as output.
+
+ Notes
+ -----
+ Since all ufuncs can take output arguments, this will always be at least 1.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.add.nout
+ 1
+ >>> np.multiply.nout
+ 1
+ >>> np.power.nout
+ 1
+ >>> np.exp.nout
+ 1
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('ntypes',
+ """
+ The number of types.
+
+ The number of numerical NumPy types - of which there are 18 total - on which
+ the ufunc can operate.
+
+ See Also
+ --------
+ numpy.ufunc.types
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.add.ntypes
+ 22
+ >>> np.multiply.ntypes
+ 23
+ >>> np.power.ntypes
+ 21
+ >>> np.exp.ntypes
+ 10
+ >>> np.remainder.ntypes
+ 16
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('types',
+ """
+ Returns a list with types grouped input->output.
+
+ Data attribute listing the data-type "Domain-Range" groupings the ufunc can
+ deliver. The data-types are given using the character codes.
+
+ See Also
+ --------
+ numpy.ufunc.ntypes
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.add.types
+ ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', ...
+
+ >>> np.power.types
+ ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', ...
+
+ >>> np.exp.types
+ ['e->e', 'f->f', 'd->d', 'f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O']
+
+ >>> np.remainder.types
+ ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', ...
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('signature',
+ """
+ Definition of the core elements a generalized ufunc operates on.
+
+ The signature determines how the dimensions of each input/output array
+ are split into core and loop dimensions:
+
+ 1. Each dimension in the signature is matched to a dimension of the
+ corresponding passed-in array, starting from the end of the shape tuple.
+ 2. Core dimensions assigned to the same label in the signature must have
+ exactly matching sizes, no broadcasting is performed.
+ 3. The core dimensions are removed from all inputs and the remaining
+ dimensions are broadcast together, defining the loop dimensions.
+
+ Notes
+ -----
+ Generalized ufuncs are used internally in many linalg functions, and in
+ the testing suite; the examples below are taken from these.
+ For ufuncs that operate on scalars, the signature is None, which is
+ equivalent to '()' for every argument.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.linalg._umath_linalg.det.signature
+ '(m,m)->()'
+ >>> np.matmul.signature
+ '(n?,k),(k,m?)->(n?,m?)'
+ >>> np.add.signature is None
+ True # equivalent to '(),()->()'
+ """))
+
+##############################################################################
+#
+# ufunc methods
+#
+##############################################################################
+
+add_newdoc('numpy._core', 'ufunc', ('reduce',
+ """
+ reduce($self, array, /, axis=0, dtype=None, out=None, **kwargs)
+ --
+
+ reduce(array, axis=0, dtype=None, out=None, keepdims=False, initial=, where=True)
+
+ Reduces `array`'s dimension by one, by applying ufunc along one axis.
+
+ Let :math:`array.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then
+ :math:`ufunc.reduce(array, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` =
+ the result of iterating `j` over :math:`range(N_i)`, cumulatively applying
+ ufunc to each :math:`array[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`.
+ For a one-dimensional array, reduce produces results equivalent to:
+ ::
+
+ r = op.identity # op = ufunc
+ for i in range(len(A)):
+ r = op(r, A[i])
+ return r
+
+ For example, add.reduce() is equivalent to sum().
+
+ Parameters
+ ----------
+ array : array_like
+ The array to act on.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which a reduction is performed.
+ The default (`axis` = 0) is perform a reduction over the first
+ dimension of the input array. `axis` may be negative, in
+ which case it counts from the last to the first axis.
+
+ If this is None, a reduction is performed over all the axes.
+ If this is a tuple of ints, a reduction is performed on multiple
+ axes, instead of a single axis or all the axes as before.
+
+ For operations which are either not commutative or not associative,
+ doing a reduction over multiple axes is not well-defined. The
+ ufuncs do not currently raise an exception in this case, but will
+ likely do so in the future.
+ dtype : data-type code, optional
+ The data type used to perform the operation. Defaults to that of
+ ``out`` if given, and the data type of ``array`` otherwise (though
+ upcast to conserve precision for some cases, such as
+ ``numpy.add.reduce`` for integer or boolean input).
+ out : ndarray, None, ..., or tuple of ndarray and None, optional
+ Location into which the result is stored.
+ If not provided or None, a freshly-allocated array is returned.
+ If passed as a keyword argument, can be Ellipses (``out=...``) to
+ ensure an array is returned even if the result is 0-dimensional
+ (which is useful especially for object dtype), or a 1-element tuple
+ (latter for consistency with ``ufunc.__call__``).
+
+ .. versionadded:: 2.3
+ Support for ``out=...`` was added.
+
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the original `array`.
+ initial : scalar, optional
+ The value with which to start the reduction.
+ If the ufunc has no identity or the dtype is object, this defaults
+ to None - otherwise it defaults to ufunc.identity.
+ If ``None`` is given, the first element of the reduction is used,
+ and an error is thrown if the reduction is empty.
+ where : array_like of bool, optional
+ A boolean array which is broadcasted to match the dimensions
+ of `array`, and selects elements to include in the reduction. Note
+ that for ufuncs like ``minimum`` that do not have an identity
+ defined, one has to pass in also ``initial``.
+
+ Returns
+ -------
+ r : ndarray
+ The reduced array. If `out` was supplied, `r` is a reference to it.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.multiply.reduce([2,3,5])
+ 30
+
+ A multi-dimensional array example:
+
+ >>> X = np.arange(8).reshape((2,2,2))
+ >>> X
+ array([[[0, 1],
+ [2, 3]],
+ [[4, 5],
+ [6, 7]]])
+ >>> np.add.reduce(X, 0)
+ array([[ 4, 6],
+ [ 8, 10]])
+ >>> np.add.reduce(X) # confirm: default axis value is 0
+ array([[ 4, 6],
+ [ 8, 10]])
+ >>> np.add.reduce(X, 1)
+ array([[ 2, 4],
+ [10, 12]])
+ >>> np.add.reduce(X, 2)
+ array([[ 1, 5],
+ [ 9, 13]])
+
+ You can use the ``initial`` keyword argument to initialize the reduction
+ with a different value, and ``where`` to select specific elements to include:
+
+ >>> np.add.reduce([10], initial=5)
+ 15
+ >>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10)
+ array([14., 14.])
+ >>> a = np.array([10., np.nan, 10])
+ >>> np.add.reduce(a, where=~np.isnan(a))
+ 20.0
+
+ Allows reductions of empty arrays where they would normally fail, i.e.
+ for ufuncs without an identity.
+
+ >>> np.minimum.reduce([], initial=np.inf)
+ inf
+ >>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False])
+ array([ 1., 10.])
+ >>> np.minimum.reduce([])
+ Traceback (most recent call last):
+ ...
+ ValueError: zero-size array to reduction operation minimum which has no identity
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('accumulate',
+ """
+ accumulate($self, array, /, axis=0, dtype=None, out=None)
+ --
+
+ accumulate(array, axis=0, dtype=None, out=None)
+
+ Accumulate the result of applying the operator to all elements.
+
+ For a one-dimensional array, accumulate produces results equivalent to::
+
+ r = np.empty(len(A))
+ t = op.identity # op = the ufunc being applied to A's elements
+ for i in range(len(A)):
+ t = op(t, A[i])
+ r[i] = t
+ return r
+
+ For example, add.accumulate() is equivalent to np.cumsum().
+
+ For a multi-dimensional array, accumulate is applied along only one
+ axis (axis zero by default; see Examples below) so repeated use is
+ necessary if one wants to accumulate over multiple axes.
+
+ Parameters
+ ----------
+ array : array_like
+ The array to act on.
+ axis : int, optional
+ The axis along which to apply the accumulation; default is zero.
+ dtype : data-type code, optional
+ The data-type used to represent the intermediate results. Defaults
+ to the data-type of the output array if such is provided, or the
+ data-type of the input array if no output array is provided.
+ out : ndarray, None, or tuple of ndarray and None, optional
+ Location into which the result is stored.
+ If not provided or None, a freshly-allocated array is returned.
+ For consistency with ``ufunc.__call__``, if passed as a keyword
+ argument, can be Ellipses (``out=...``, which has the same effect
+ as None as an array is always returned), or a 1-element tuple.
+
+ Returns
+ -------
+ r : ndarray
+ The accumulated values. If `out` was supplied, `r` is a reference to
+ `out`.
+
+ Examples
+ --------
+ 1-D array examples:
+
+ >>> import numpy as np
+ >>> np.add.accumulate([2, 3, 5])
+ array([ 2, 5, 10])
+ >>> np.multiply.accumulate([2, 3, 5])
+ array([ 2, 6, 30])
+
+ 2-D array examples:
+
+ >>> I = np.eye(2)
+ >>> I
+ array([[1., 0.],
+ [0., 1.]])
+
+ Accumulate along axis 0 (rows), down columns:
+
+ >>> np.add.accumulate(I, 0)
+ array([[1., 0.],
+ [1., 1.]])
+ >>> np.add.accumulate(I) # no axis specified = axis zero
+ array([[1., 0.],
+ [1., 1.]])
+
+ Accumulate along axis 1 (columns), through rows:
+
+ >>> np.add.accumulate(I, 1)
+ array([[1., 1.],
+ [0., 1.]])
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('reduceat',
+ """
+ reduceat($self, array, /, indices, axis=0, dtype=None, out=None)
+ --
+
+ reduceat(array, indices, axis=0, dtype=None, out=None)
+
+ Performs a (local) reduce with specified slices over a single axis.
+
+ For i in ``range(len(indices))``, `reduceat` computes
+ ``ufunc.reduce(array[indices[i]:indices[i+1]])``, which becomes the i-th
+ generalized "row" parallel to `axis` in the final result (i.e., in a
+ 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if
+ `axis = 1`, it becomes the i-th column). There are three exceptions to this:
+
+ * when ``i = len(indices) - 1`` (so for the last index),
+ ``indices[i+1] = array.shape[axis]``.
+ * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is
+ simply ``array[indices[i]]``.
+ * if ``indices[i] >= len(array)`` or ``indices[i] < 0``, an error is raised.
+
+ The shape of the output depends on the size of `indices`, and may be
+ larger than `array` (this happens if ``len(indices) > array.shape[axis]``).
+
+ Parameters
+ ----------
+ array : array_like
+ The array to act on.
+ indices : array_like
+ Paired indices, comma separated (not colon), specifying slices to
+ reduce.
+ axis : int, optional
+ The axis along which to apply the reduceat.
+ dtype : data-type code, optional
+ The data type used to perform the operation. Defaults to that of
+ ``out`` if given, and the data type of ``array`` otherwise (though
+ upcast to conserve precision for some cases, such as
+ ``numpy.add.reduce`` for integer or boolean input).
+ out : ndarray, None, or tuple of ndarray and None, optional
+ Location into which the result is stored.
+ If not provided or None, a freshly-allocated array is returned.
+ For consistency with ``ufunc.__call__``, if passed as a keyword
+ argument, can be Ellipses (``out=...``, which has the same effect
+ as None as an array is always returned), or a 1-element tuple.
+
+ Returns
+ -------
+ r : ndarray
+ The reduced values. If `out` was supplied, `r` is a reference to
+ `out`.
+
+ Notes
+ -----
+ A descriptive example:
+
+ If `array` is 1-D, the function `ufunc.accumulate(array)` is the same as
+ ``ufunc.reduceat(array, indices)[::2]`` where `indices` is
+ ``range(len(array) - 1)`` with a zero placed
+ in every other element:
+ ``indices = zeros(2 * len(array) - 1)``,
+ ``indices[1::2] = range(1, len(array))``.
+
+ Don't be fooled by this attribute's name: `reduceat(array)` is not
+ necessarily smaller than `array`.
+
+ Examples
+ --------
+ To take the running sum of four successive values:
+
+ >>> import numpy as np
+ >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2]
+ array([ 6, 10, 14, 18])
+
+ A 2-D example:
+
+ >>> x = np.linspace(0, 15, 16).reshape(4,4)
+ >>> x
+ array([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.],
+ [12., 13., 14., 15.]])
+
+ ::
+
+ # reduce such that the result has the following five rows:
+ # [row1 + row2 + row3]
+ # [row4]
+ # [row2]
+ # [row3]
+ # [row1 + row2 + row3 + row4]
+
+ >>> np.add.reduceat(x, [0, 3, 1, 2, 0])
+ array([[12., 15., 18., 21.],
+ [12., 13., 14., 15.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.],
+ [24., 28., 32., 36.]])
+
+ ::
+
+ # reduce such that result has the following two columns:
+ # [col1 * col2 * col3, col4]
+
+ >>> np.multiply.reduceat(x, [0, 3], 1)
+ array([[ 0., 3.],
+ [ 120., 7.],
+ [ 720., 11.],
+ [2184., 15.]])
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('outer',
+ r"""
+ outer($self, A, B, /, **kwargs)
+ --
+
+ outer(A, B, /, **kwargs)
+
+ Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`.
+
+ Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of
+ ``op.outer(A, B)`` is an array of dimension M + N such that:
+
+ .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] =
+ op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}])
+
+ For `A` and `B` one-dimensional, this is equivalent to::
+
+ r = empty(len(A),len(B))
+ for i in range(len(A)):
+ for j in range(len(B)):
+ r[i,j] = op(A[i], B[j]) # op = ufunc in question
+
+ Parameters
+ ----------
+ A : array_like
+ First array
+ B : array_like
+ Second array
+ kwargs : any
+ Arguments to pass on to the ufunc. Typically `dtype` or `out`.
+ See `ufunc` for a comprehensive overview of all available arguments.
+
+ Returns
+ -------
+ r : ndarray
+ Output array
+
+ See Also
+ --------
+ numpy.outer : A less powerful version of ``np.multiply.outer``
+ that `ravel`\ s all inputs to 1D. This exists
+ primarily for compatibility with old code.
+
+ tensordot : ``np.tensordot(a, b, axes=((), ()))`` and
+ ``np.multiply.outer(a, b)`` behave same for all
+ dimensions of a and b.
+
+ Examples
+ --------
+ >>> np.multiply.outer([1, 2, 3], [4, 5, 6])
+ array([[ 4, 5, 6],
+ [ 8, 10, 12],
+ [12, 15, 18]])
+
+ A multi-dimensional example:
+
+ >>> A = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> A.shape
+ (2, 3)
+ >>> B = np.array([[1, 2, 3, 4]])
+ >>> B.shape
+ (1, 4)
+ >>> C = np.multiply.outer(A, B)
+ >>> C.shape; C
+ (2, 3, 1, 4)
+ array([[[[ 1, 2, 3, 4]],
+ [[ 2, 4, 6, 8]],
+ [[ 3, 6, 9, 12]]],
+ [[[ 4, 8, 12, 16]],
+ [[ 5, 10, 15, 20]],
+ [[ 6, 12, 18, 24]]]])
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('at',
+ """
+ at($self, a, indices, b=None, /)
+ --
+
+ at(a, indices, b=None, /)
+
+ Performs unbuffered in place operation on operand 'a' for elements
+ specified by 'indices'. For addition ufunc, this method is equivalent to
+ ``a[indices] += b``, except that results are accumulated for elements that
+ are indexed more than once. For example, ``a[[0,0]] += 1`` will only
+ increment the first element once because of buffering, whereas
+ ``add.at(a, [0,0], 1)`` will increment the first element twice.
+
+ Parameters
+ ----------
+ a : array_like
+ The array to perform in place operation on.
+ indices : array_like or tuple
+ Array like index object or slice object for indexing into first
+ operand. If first operand has multiple dimensions, indices can be a
+ tuple of array like index objects or slice objects.
+ b : array_like
+ Second operand for ufuncs requiring two operands. Operand must be
+ broadcastable over first operand after indexing or slicing.
+
+ Examples
+ --------
+ Set items 0 and 1 to their negative values:
+
+ >>> import numpy as np
+ >>> a = np.array([1, 2, 3, 4])
+ >>> np.negative.at(a, [0, 1])
+ >>> a
+ array([-1, -2, 3, 4])
+
+ Increment items 0 and 1, and increment item 2 twice:
+
+ >>> a = np.array([1, 2, 3, 4])
+ >>> np.add.at(a, [0, 1, 2, 2], 1)
+ >>> a
+ array([2, 3, 5, 4])
+
+ Add items 0 and 1 in first array to second array,
+ and store results in first array:
+
+ >>> a = np.array([1, 2, 3, 4])
+ >>> b = np.array([1, 2])
+ >>> np.add.at(a, [0, 1], b)
+ >>> a
+ array([2, 4, 3, 4])
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('resolve_dtypes',
+ """
+ resolve_dtypes($self, dtypes, *, signature=None, casting=None, reduction=False)
+ --
+
+ resolve_dtypes(dtypes, *, signature=None, casting=None, reduction=False)
+
+ Find the dtypes NumPy will use for the operation. Both input and
+ output dtypes are returned and may differ from those provided.
+
+ .. note::
+
+ This function always applies NEP 50 rules since it is not provided
+ any actual values. The Python types ``int``, ``float``, and
+ ``complex`` thus behave weak and should be passed for "untyped"
+ Python input.
+
+ Parameters
+ ----------
+ dtypes : tuple of dtypes, None, or literal int, float, complex
+ The input dtypes for each operand. Output operands can be
+ None, indicating that the dtype must be found.
+ signature : tuple of DTypes or None, optional
+ If given, enforces exact DType (classes) of the specific operand.
+ The ufunc ``dtype`` argument is equivalent to passing a tuple with
+ only output dtypes set.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ The casting mode when casting is necessary. This is identical to
+ the ufunc call casting modes.
+ reduction : boolean
+ If given, the resolution assumes a reduce operation is happening
+ which slightly changes the promotion and type resolution rules.
+ `dtypes` is usually something like ``(None, np.dtype("i2"), None)``
+ for reductions (first input is also the output).
+
+ .. note::
+
+ The default casting mode is "same_kind", however, as of
+ NumPy 1.24, NumPy uses "unsafe" for reductions.
+
+ Returns
+ -------
+ dtypes : tuple of dtypes
+ The dtypes which NumPy would use for the calculation. Note that
+ dtypes may not match the passed in ones (casting is necessary).
+
+
+ Examples
+ --------
+ This API requires passing dtypes, define them for convenience:
+
+ >>> import numpy as np
+ >>> int32 = np.dtype("int32")
+ >>> float32 = np.dtype("float32")
+
+ The typical ufunc call does not pass an output dtype. `numpy.add` has two
+ inputs and one output, so leave the output as ``None`` (not provided):
+
+ >>> np.add.resolve_dtypes((int32, float32, None))
+ (dtype('float64'), dtype('float64'), dtype('float64'))
+
+ The loop found uses "float64" for all operands (including the output), the
+ first input would be cast.
+
+ ``resolve_dtypes`` supports "weak" handling for Python scalars by passing
+ ``int``, ``float``, or ``complex``:
+
+ >>> np.add.resolve_dtypes((float32, float, None))
+ (dtype('float32'), dtype('float32'), dtype('float32'))
+
+ Where the Python ``float`` behaves similar to a Python value ``0.0``
+ in a ufunc call. (See :ref:`NEP 50 ` for details.)
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('_resolve_dtypes_and_context',
+ """
+ _resolve_dtypes_and_context($self, dtypes, *, signature=None, casting=None, reduction=False)
+ --
+
+ _resolve_dtypes_and_context(dtypes, *, signature=None, casting=None, reduction=False)
+
+ See `numpy.ufunc.resolve_dtypes` for parameter information. This
+ function is considered *unstable*. You may use it, but the returned
+ information is NumPy version specific and expected to change.
+ Large API/ABI changes are not expected, but a new NumPy version is
+ expected to require updating code using this functionality.
+
+ This function is designed to be used in conjunction with
+ `numpy.ufunc._get_strided_loop`. The calls are split to mirror the C API
+ and allow future improvements.
+
+ Returns
+ -------
+ dtypes : tuple of dtypes
+ call_info :
+ PyCapsule with all necessary information to get access to low level
+ C calls. See `numpy.ufunc._get_strided_loop` for more information.
+
+ """))
+
+add_newdoc('numpy._core', 'ufunc', ('_get_strided_loop',
+ """
+ _get_strided_loop($self, call_info, /, *, fixed_strides=None)
+ --
+
+ _get_strided_loop(call_info, /, *, fixed_strides=None)
+
+ This function fills in the ``call_info`` capsule to include all
+ information necessary to call the low-level strided loop from NumPy.
+
+ See notes for more information.
+
+ Parameters
+ ----------
+ call_info : PyCapsule
+ The PyCapsule returned by `numpy.ufunc._resolve_dtypes_and_context`.
+ fixed_strides : tuple of int or None, optional
+ A tuple with fixed byte strides of all input arrays. NumPy may use
+ this information to find specialized loops, so any call must follow
+ the given stride. Use ``None`` to indicate that the stride is not
+ known (or not fixed) for all calls.
+
+ Notes
+ -----
+ Together with `numpy.ufunc._resolve_dtypes_and_context` this function
+ gives low-level access to the NumPy ufunc loops.
+ The first function does general preparation and returns the required
+ information. It returns this as a C capsule with the version specific
+ name ``numpy_1.24_ufunc_call_info``.
+ The NumPy 1.24 ufunc call info capsule has the following layout::
+
+ typedef struct {
+ PyArrayMethod_StridedLoop *strided_loop;
+ PyArrayMethod_Context *context;
+ NpyAuxData *auxdata;
+
+ /* Flag information (expected to change) */
+ npy_bool requires_pyapi; /* GIL is required by loop */
+
+ /* Loop doesn't set FPE flags; if not set check FPE flags */
+ npy_bool no_floatingpoint_errors;
+ } ufunc_call_info;
+
+ Note that the first call only fills in the ``context``. The call to
+ ``_get_strided_loop`` fills in all other data. The main thing to note is
+ that the new-style loops return 0 on success, -1 on failure. They are
+ passed context as new first input and ``auxdata`` as (replaced) last.
+
+ Only the ``strided_loop``signature is considered guaranteed stable
+ for NumPy bug-fix releases. All other API is tied to the experimental
+ API versioning.
+
+ The reason for the split call is that cast information is required to
+ decide what the fixed-strides will be.
+
+ NumPy ties the lifetime of the ``auxdata`` information to the capsule.
+
+ """))
+
+
+##############################################################################
+#
+# Documentation for dtype attributes and methods
+#
+##############################################################################
+
+##############################################################################
+#
+# dtype object
+#
+##############################################################################
+
+add_newdoc('numpy._core.multiarray', 'dtype',
+ """
+ dtype(dtype, align=False, copy=False, **kwargs)
+ --
+
+ dtype(dtype, align=False, copy=False, [metadata])
+
+ Create a data type object.
+
+ A numpy array is homogeneous, and contains elements described by a
+ dtype object. A dtype object can be constructed from different
+ combinations of fundamental numeric types.
+
+ Parameters
+ ----------
+ dtype
+ Object to be converted to a data type object.
+ align : bool, optional
+ Add padding to the fields to match what a C compiler would output
+ for a similar C-struct. Can be ``True`` only if `obj` is a dictionary
+ or a comma-separated string. If a struct dtype is being created,
+ this also sets a sticky alignment flag ``isalignedstruct``.
+ copy : bool, optional
+ Make a new copy of the data-type object. If ``False``, the result
+ may just be a reference to a built-in data-type object.
+ metadata : dict, optional
+ An optional dictionary with dtype metadata.
+
+ See also
+ --------
+ result_type
+
+ Examples
+ --------
+ Using array-scalar type:
+
+ >>> import numpy as np
+ >>> np.dtype(np.int16)
+ dtype('int16')
+
+ Structured type, one field name 'f1', containing int16:
+
+ >>> np.dtype([('f1', np.int16)])
+ dtype([('f1', '>> np.dtype([('f1', [('f1', np.int16)])])
+ dtype([('f1', [('f1', '>> np.dtype([('f1', np.uint64), ('f2', np.int32)])
+ dtype([('f1', '>> np.dtype([('a','f8'),('b','S10')])
+ dtype([('a', '>> np.dtype("i4, (2,3)f8")
+ dtype([('f0', '>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)])
+ dtype([('hello', '>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))
+ dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')]))
+
+ Using dictionaries. Two fields named 'gender' and 'age':
+
+ >>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})
+ dtype([('gender', 'S1'), ('age', 'u1')])
+
+ Offsets in bytes, here 0 and 25:
+
+ >>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)})
+ dtype([('surname', 'S25'), ('age', 'u1')])
+
+ """)
+
+##############################################################################
+#
+# dtype attributes
+#
+##############################################################################
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('alignment',
+ """
+ The required alignment (bytes) of this data-type according to the compiler.
+
+ More information is available in the C-API section of the manual.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> x = np.dtype('i4')
+ >>> x.alignment
+ 4
+
+ >>> x = np.dtype(float)
+ >>> x.alignment
+ 8
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('byteorder',
+ """
+ A character indicating the byte-order of this data-type object.
+
+ One of:
+
+ === ==============
+ '=' native
+ '<' little-endian
+ '>' big-endian
+ '|' not applicable
+ === ==============
+
+ All built-in data-type objects have byteorder either '=' or '|'.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> dt = np.dtype('i2')
+ >>> dt.byteorder
+ '='
+ >>> # endian is not relevant for 8 bit numbers
+ >>> np.dtype('i1').byteorder
+ '|'
+ >>> # or ASCII strings
+ >>> np.dtype('S2').byteorder
+ '|'
+ >>> # Even if specific code is given, and it is native
+ >>> # '=' is the byteorder
+ >>> import sys
+ >>> sys_is_le = sys.byteorder == 'little'
+ >>> native_code = '<' if sys_is_le else '>'
+ >>> swapped_code = '>' if sys_is_le else '<'
+ >>> dt = np.dtype(native_code + 'i2')
+ >>> dt.byteorder
+ '='
+ >>> # Swapped code shows up as itself
+ >>> dt = np.dtype(swapped_code + 'i2')
+ >>> dt.byteorder == swapped_code
+ True
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('char',
+ """A unique character code for each of the 21 different built-in types.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> x = np.dtype(float)
+ >>> x.char
+ 'd'
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('descr',
+ """
+ `__array_interface__` description of the data-type.
+
+ The format is that required by the 'descr' key in the
+ `__array_interface__` attribute.
+
+ Warning: This attribute exists specifically for `__array_interface__`,
+ and passing it directly to `numpy.dtype` will not accurately reconstruct
+ some dtypes (e.g., scalar and subarray dtypes).
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> x = np.dtype(float)
+ >>> x.descr
+ [('', '>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
+ >>> dt.descr
+ [('name', '>> import numpy as np
+ >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
+ >>> print(dt.fields)
+ {'name': (dtype('>> import numpy as np
+ >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
+ >>> x.flags
+ 16
+ >>> np._core.multiarray.NEEDS_PYAPI
+ 16
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('hasobject',
+ """
+ Boolean indicating whether this dtype contains any reference-counted
+ objects in any fields or sub-dtypes.
+
+ Recall that what is actually in the ndarray memory representing
+ the Python object is the memory address of that object (a pointer).
+ Special handling may be required, and this attribute is useful for
+ distinguishing data types that may contain arbitrary Python objects
+ and data-types that won't.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('isbuiltin',
+ """
+ Integer indicating how this dtype relates to the built-in dtypes.
+
+ Read-only.
+
+ = ========================================================================
+ 0 if this is a structured array type, with fields
+ 1 if this is a dtype compiled into numpy (such as ints, floats etc)
+ 2 if the dtype is for a user-defined numpy type
+ A user-defined type uses the numpy C-API machinery to extend
+ numpy to handle a new array type. See
+ :ref:`user.user-defined-data-types` in the NumPy manual.
+ = ========================================================================
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> dt = np.dtype('i2')
+ >>> dt.isbuiltin
+ 1
+ >>> dt = np.dtype('f8')
+ >>> dt.isbuiltin
+ 1
+ >>> dt = np.dtype([('field1', 'f8')])
+ >>> dt.isbuiltin
+ 0
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('isnative',
+ """
+ Boolean indicating whether the byte order of this dtype is native
+ to the platform.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('isalignedstruct',
+ """
+ Boolean indicating whether the dtype is a struct which maintains
+ field alignment. This flag is sticky, so when combining multiple
+ structs together, it is preserved and produces new dtypes which
+ are also aligned.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('itemsize',
+ """
+ The element size of this data-type object.
+
+ For 18 of the 21 types this number is fixed by the data-type.
+ For the flexible data-types, this number can be anything.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> arr = np.array([[1, 2], [3, 4]])
+ >>> arr.dtype
+ dtype('int64')
+ >>> arr.itemsize
+ 8
+
+ >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
+ >>> dt.itemsize
+ 80
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('kind',
+ """
+ A character code (one of 'biufcmMOSTUV') identifying the general kind of data.
+
+ = ======================
+ b boolean
+ i signed integer
+ u unsigned integer
+ f floating-point
+ c complex floating-point
+ m timedelta
+ M datetime
+ O object
+ S (byte-)string
+ T string (StringDType)
+ U Unicode
+ V void
+ = ======================
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> dt = np.dtype('i4')
+ >>> dt.kind
+ 'i'
+ >>> dt = np.dtype('f8')
+ >>> dt.kind
+ 'f'
+ >>> dt = np.dtype([('field1', 'f8')])
+ >>> dt.kind
+ 'V'
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('metadata',
+ """
+ Either ``None`` or a readonly dictionary of metadata (mappingproxy).
+
+ The metadata field can be set using any dictionary at data-type
+ creation. NumPy currently has no uniform approach to propagating
+ metadata; although some array operations preserve it, there is no
+ guarantee that others will.
+
+ .. warning::
+
+ Although used in certain projects, this feature was long undocumented
+ and is not well supported. Some aspects of metadata propagation
+ are expected to change in the future.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> dt = np.dtype(float, metadata={"key": "value"})
+ >>> dt.metadata["key"]
+ 'value'
+ >>> arr = np.array([1, 2, 3], dtype=dt)
+ >>> arr.dtype.metadata
+ mappingproxy({'key': 'value'})
+
+ Adding arrays with identical datatypes currently preserves the metadata:
+
+ >>> (arr + arr).dtype.metadata
+ mappingproxy({'key': 'value'})
+
+ If the arrays have different dtype metadata, the first one wins:
+
+ >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
+ >>> arr2 = np.array([3, 2, 1], dtype=dt2)
+ >>> print((arr + arr2).dtype.metadata)
+ {'key': 'value'}
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('name',
+ """
+ A bit-width name for this data-type.
+
+ Un-sized flexible data-type objects do not have this attribute.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> x = np.dtype(float)
+ >>> x.name
+ 'float64'
+ >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
+ >>> x.name
+ 'void640'
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('names',
+ """
+ Ordered list of field names, or ``None`` if there are no fields.
+
+ The names are ordered according to increasing byte offset. This can be
+ used, for example, to walk through all of the named fields in offset order.
+
+ Examples
+ --------
+ >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
+ >>> dt.names
+ ('name', 'grades')
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('num',
+ """
+ A unique number for each of the 21 different built-in types.
+
+ These are roughly ordered from least-to-most precision.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> dt = np.dtype(str)
+ >>> dt.num
+ 19
+
+ >>> dt = np.dtype(float)
+ >>> dt.num
+ 12
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('shape',
+ """
+ Shape tuple of the sub-array if this data type describes a sub-array,
+ and ``()`` otherwise.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> dt = np.dtype(('i4', 4))
+ >>> dt.shape
+ (4,)
+
+ >>> dt = np.dtype(('i4', (2, 3)))
+ >>> dt.shape
+ (2, 3)
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('ndim',
+ """
+ Number of dimensions of the sub-array if this data type describes a
+ sub-array, and ``0`` otherwise.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.dtype(float)
+ >>> x.ndim
+ 0
+
+ >>> x = np.dtype((float, 8))
+ >>> x.ndim
+ 1
+
+ >>> x = np.dtype(('i4', (3, 4)))
+ >>> x.ndim
+ 2
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('str',
+ """The array-protocol typestring of this data-type object."""))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('subdtype',
+ """
+ Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
+ None otherwise.
+
+ The *shape* is the fixed shape of the sub-array described by this
+ data type, and *item_dtype* the data type of the array.
+
+ If a field whose dtype object has this attribute is retrieved,
+ then the extra dimensions implied by *shape* are tacked on to
+ the end of the retrieved array.
+
+ See Also
+ --------
+ dtype.base
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.dtype('8f')
+ >>> x.subdtype
+ (dtype('float32'), (8,))
+
+ >>> x = np.dtype('i2')
+ >>> x.subdtype
+ >>>
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('base',
+ """
+ Returns dtype for the base element of the subarrays,
+ regardless of their dimension or shape.
+
+ See Also
+ --------
+ dtype.subdtype
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.dtype('8f')
+ >>> x.base
+ dtype('float32')
+
+ >>> x = np.dtype('i2')
+ >>> x.base
+ dtype('int16')
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('type',
+ """The type object used to instantiate a scalar of this data-type."""))
+
+##############################################################################
+#
+# dtype methods
+#
+##############################################################################
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('newbyteorder',
+ """
+ newbyteorder($self, new_order='S', /)
+ --
+
+ newbyteorder(new_order='S', /)
+
+ Return a new dtype with a different byte order.
+
+ Changes are also made in all fields and sub-arrays of the data type.
+
+ Parameters
+ ----------
+ new_order : string, optional
+ Byte order to force; a value from the byte order specifications
+ below. The default value ('S') results in swapping the current
+ byte order. `new_order` codes can be any of:
+
+ * 'S' - swap dtype from current to opposite endian
+ * {'<', 'little'} - little endian
+ * {'>', 'big'} - big endian
+ * {'=', 'native'} - native order
+ * {'|', 'I'} - ignore (no change to byte order)
+
+ Returns
+ -------
+ new_dtype : dtype
+ New dtype object with the given change to the byte order.
+
+ Notes
+ -----
+ Changes are also made in all fields and sub-arrays of the data type.
+
+ Examples
+ --------
+ >>> import sys
+ >>> sys_is_le = sys.byteorder == 'little'
+ >>> native_code = '<' if sys_is_le else '>'
+ >>> swapped_code = '>' if sys_is_le else '<'
+ >>> import numpy as np
+ >>> native_dt = np.dtype(native_code+'i2')
+ >>> swapped_dt = np.dtype(swapped_code+'i2')
+ >>> native_dt.newbyteorder('S') == swapped_dt
+ True
+ >>> native_dt.newbyteorder() == swapped_dt
+ True
+ >>> native_dt == swapped_dt.newbyteorder('S')
+ True
+ >>> native_dt == swapped_dt.newbyteorder('=')
+ True
+ >>> native_dt == swapped_dt.newbyteorder('N')
+ True
+ >>> native_dt == native_dt.newbyteorder('|')
+ True
+ >>> np.dtype('>> np.dtype('>> np.dtype('>i2') == native_dt.newbyteorder('>')
+ True
+ >>> np.dtype('>i2') == native_dt.newbyteorder('B')
+ True
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('__class_getitem__',
+ """
+ __class_getitem__(item, /)
+
+ Return a parametrized wrapper around the `~numpy.dtype` type.
+
+ .. versionadded:: 1.22
+
+ Returns
+ -------
+ alias : types.GenericAlias
+ A parametrized `~numpy.dtype` type.
+
+ Examples
+ --------
+ >>> import numpy as np
+
+ >>> np.dtype[np.int64]
+ numpy.dtype[numpy.int64]
+
+ See Also
+ --------
+ :pep:`585` : Type hinting generics in standard collections.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('__ge__',
+ """
+ __ge__(value, /)
+
+ Return ``self >= value``.
+
+ Equivalent to ``np.can_cast(value, self, casting="safe")``.
+
+ See Also
+ --------
+ can_cast : Returns True if cast between data types can occur according to
+ the casting rule.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('__le__',
+ """
+ __le__(value, /)
+
+ Return ``self <= value``.
+
+ Equivalent to ``np.can_cast(self, value, casting="safe")``.
+
+ See Also
+ --------
+ can_cast : Returns True if cast between data types can occur according to
+ the casting rule.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('__gt__',
+ """
+ __gt__(value, /)
+
+ Return ``self > value``.
+
+ Equivalent to
+ ``self != value and np.can_cast(value, self, casting="safe")``.
+
+ See Also
+ --------
+ can_cast : Returns True if cast between data types can occur according to
+ the casting rule.
+
+ """))
+
+add_newdoc('numpy._core.multiarray', 'dtype', ('__lt__',
+ """
+ __lt__(value, /)
+
+ Return ``self < value``.
+
+ Equivalent to
+ ``self != value and np.can_cast(self, value, casting="safe")``.
+
+ See Also
+ --------
+ can_cast : Returns True if cast between data types can occur according to
+ the casting rule.
+
+ """))
+
+##############################################################################
+#
+# Datetime-related Methods
+#
+##############################################################################
+
+add_newdoc('numpy._core.multiarray', 'busdaycalendar',
+ """
+ busdaycalendar(weekmask='1111100', holidays=None)
+ --
+
+ busdaycalendar(weekmask='1111100', holidays=None)
+
+ A business day calendar object that efficiently stores information
+ defining valid days for the busday family of functions.
+
+ The default valid days are Monday through Friday ("business days").
+ A busdaycalendar object can be specified with any set of weekly
+ valid days, plus an optional "holiday" dates that always will be invalid.
+
+ Once a busdaycalendar object is created, the weekmask and holidays
+ cannot be modified.
+
+ Parameters
+ ----------
+ weekmask : str or array_like of bool, optional
+ A seven-element array indicating which of Monday through Sunday are
+ valid days. May be specified as a length-seven list or array, like
+ [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
+ like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
+ weekdays, optionally separated by white space. Valid abbreviations
+ are: Mon Tue Wed Thu Fri Sat Sun
+ holidays : array_like of datetime64[D], optional
+ An array of dates to consider as invalid dates, no matter which
+ weekday they fall upon. Holiday dates may be specified in any
+ order, and NaT (not-a-time) dates are ignored. This list is
+ saved in a normalized form that is suited for fast calculations
+ of valid days.
+
+ Returns
+ -------
+ out : busdaycalendar
+ A business day calendar object containing the specified
+ weekmask and holidays values.
+
+ See Also
+ --------
+ is_busday : Returns a boolean array indicating valid days.
+ busday_offset : Applies an offset counted in valid days.
+ busday_count : Counts how many valid days are in a half-open date range.
+
+ Attributes
+ ----------
+ weekmask : (copy) seven-element array of bool
+ holidays : (copy) sorted array of datetime64[D]
+
+ Notes
+ -----
+ Once a busdaycalendar object is created, you cannot modify the
+ weekmask or holidays. The attributes return copies of internal data.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> # Some important days in July
+ ... bdd = np.busdaycalendar(
+ ... holidays=['2011-07-01', '2011-07-04', '2011-07-17'])
+ >>> # Default is Monday to Friday weekdays
+ ... bdd.weekmask
+ array([ True, True, True, True, True, False, False])
+ >>> # Any holidays already on the weekend are removed
+ ... bdd.holidays
+ array(['2011-07-01', '2011-07-04'], dtype='datetime64[D]')
+ """)
+
+add_newdoc('numpy._core.multiarray', 'busdaycalendar', ('weekmask',
+ """A copy of the seven-element boolean mask indicating valid days."""))
+
+add_newdoc('numpy._core.multiarray', 'busdaycalendar', ('holidays',
+ """A copy of the holiday array indicating additional invalid days."""))
+
+add_newdoc('numpy._core.multiarray', 'normalize_axis_index',
+ """
+ normalize_axis_index(axis, ndim, msg_prefix=None)
+
+ Normalizes an axis index, `axis`, such that is a valid positive index into
+ the shape of array with `ndim` dimensions. Raises an AxisError with an
+ appropriate message if this is not possible.
+
+ Used internally by all axis-checking logic.
+
+ Parameters
+ ----------
+ axis : int
+ The un-normalized index of the axis. Can be negative
+ ndim : int
+ The number of dimensions of the array that `axis` should be normalized
+ against
+ msg_prefix : str
+ A prefix to put before the message, typically the name of the argument
+
+ Returns
+ -------
+ normalized_axis : int
+ The normalized axis index, such that `0 <= normalized_axis < ndim`
+
+ Raises
+ ------
+ AxisError
+ If the axis index is invalid, when `-ndim <= axis < ndim` is false.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from numpy.lib.array_utils import normalize_axis_index
+ >>> normalize_axis_index(0, ndim=3)
+ 0
+ >>> normalize_axis_index(1, ndim=3)
+ 1
+ >>> normalize_axis_index(-1, ndim=3)
+ 2
+
+ >>> normalize_axis_index(3, ndim=3)
+ Traceback (most recent call last):
+ ...
+ numpy.exceptions.AxisError: axis 3 is out of bounds for array ...
+ >>> normalize_axis_index(-4, ndim=3, msg_prefix='axes_arg')
+ Traceback (most recent call last):
+ ...
+ numpy.exceptions.AxisError: axes_arg: axis -4 is out of bounds ...
+ """)
+
+add_newdoc('numpy._core.multiarray', 'datetime_data',
+ """
+ datetime_data(dtype, /)
+ --
+
+ datetime_data(dtype, /)
+
+ Get information about the step size of a date or time type.
+
+ The returned tuple can be passed as the second argument of `numpy.datetime64` and
+ `numpy.timedelta64`.
+
+ Parameters
+ ----------
+ dtype : dtype
+ The dtype object, which must be a `datetime64` or `timedelta64` type.
+
+ Returns
+ -------
+ unit : str
+ The :ref:`datetime unit ` on which this dtype
+ is based.
+ count : int
+ The number of base units in a step.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> dt_25s = np.dtype('timedelta64[25s]')
+ >>> np.datetime_data(dt_25s)
+ ('s', 25)
+ >>> np.array(10, dt_25s).astype('timedelta64[s]')
+ array(250, dtype='timedelta64[s]')
+
+ The result can be used to construct a datetime that uses the same units
+ as a timedelta
+
+ >>> np.datetime64('2010', np.datetime_data(dt_25s))
+ np.datetime64('2010-01-01T00:00:00','25s')
+ """)
+
+
+##############################################################################
+#
+# Documentation for `generic` attributes and methods
+#
+##############################################################################
+
+add_newdoc('numpy._core.numerictypes', 'generic',
+ """
+ Base class for numpy scalar types.
+
+ Class from which most (all?) numpy scalar types are derived. For
+ consistency, exposes the same API as `ndarray`, despite many
+ consequent attributes being either "get-only," or completely irrelevant.
+ This is the class from which it is strongly suggested users should derive
+ custom scalar types.
+
+ """)
+
+# Attributes
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('T',
+ """Scalar attribute identical to `ndarray.T`."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('base',
+ """Scalar attribute identical to `ndarray.base`."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('data',
+ """Pointer to start of data."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('dtype',
+ """Get array data-descriptor."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('flags',
+ """The integer value of flags."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('flat',
+ """A 1-D view of the scalar."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('imag',
+ """The imaginary part of the scalar."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('itemsize',
+ """The length of one element in bytes."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('ndim',
+ """The number of array dimensions."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('real',
+ """The real part of the scalar."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('shape',
+ """Tuple of array dimensions."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('size',
+ """The number of elements in the gentype."""))
+
+add_newdoc('numpy._core.numerictypes', 'generic', ('strides',
+ """Tuple of bytes steps in each dimension."""))
+
+# Methods
+
+add_newdoc('numpy._core.numerictypes', 'number', ('__class_getitem__',
+ """
+ __class_getitem__($cls, item, /)
+ --
+
+ number.__class_getitem__(item, /)
+
+ Return a parametrized wrapper around the `~numpy.number` type.
+
+ .. versionadded:: 1.22
+
+ Returns
+ -------
+ alias : types.GenericAlias
+ A parametrized `~numpy.number` type.
+
+ Examples
+ --------
+ >>> from typing import Any
+ >>> import numpy as np
+
+ >>> np.signedinteger[Any]
+ numpy.signedinteger[typing.Any]
+
+ See Also
+ --------
+ :pep:`585` : Type hinting generics in standard collections.
+
+ """))
+
+##############################################################################
+#
+# Documentation for scalar type abstract base classes in type hierarchy
+#
+##############################################################################
+
+
+add_newdoc('numpy._core.numerictypes', 'number',
+ """
+ Abstract base class of all numeric scalar types.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'integer',
+ """
+ Abstract base class of all integer scalar types.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'signedinteger',
+ """
+ Abstract base class of all signed integer scalar types.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'unsignedinteger',
+ """
+ Abstract base class of all unsigned integer scalar types.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'inexact',
+ """
+ Abstract base class of all numeric scalar types with a (potentially)
+ inexact representation of the values in its range, such as
+ floating-point numbers.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'floating',
+ """
+ Abstract base class of all floating-point scalar types.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'complexfloating',
+ """
+ Abstract base class of all complex number scalar types that are made up of
+ floating-point numbers.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'flexible',
+ """
+ Abstract base class of all scalar types without predefined length.
+ The actual size of these types depends on the specific `numpy.dtype`
+ instantiation.
+
+ """)
+
+add_newdoc('numpy._core.numerictypes', 'character',
+ """
+ Abstract base class of all character string scalar types.
+
+ """)
+
+##############################################################################
+#
+# Documentation for `dtypes.*` classes
+#
+##############################################################################
+
+for _dtype_name, _signature, _sctype_name in (
+ ("BoolDType", "()", "bool"),
+ ("Int8DType", "()", "int8"),
+ ("UInt8DType", "()", "uint8"),
+ ("Int16DType", "()", "int16"),
+ ("UInt16DType", "()", "uint16"),
+ ("Int32DType", "()", "int32"),
+ ("IntDType", "()", "intc"),
+ ("UInt32DType", "()", "uint32"),
+ ("UIntDType", "()", "uintc"),
+ ("Int64DType", "()", "int64"),
+ ("UInt64DType", "()", "uint64"),
+ ("LongLongDType", "()", "longlong"),
+ ("ULongLongDType", "()", "ulonglong"),
+ ("Float16DType", "()", "float16"),
+ ("Float32DType", "()", "float32"),
+ ("Float64DType", "()", "float64"),
+ ("LongDoubleDType", "()", "longdouble"),
+ ("Complex64DType", "()", "complex64"),
+ ("Complex128DType", "()", "complex128"),
+ ("CLongDoubleDType", "()", "clongdouble"),
+ ("ObjectDType", "()", "object"),
+ ("BytesDType", "(size, /)", "bytes_"),
+ ("StrDType", "(size, /)", "str_"),
+ ("VoidDType", "(length, /)", "void"),
+ ("DateTime64DType", "(unit, /)", "datetime64"),
+ ("TimeDelta64DType", "(unit, /)", "timedelta64"),
+):
+ _extra_docs = ""
+ if _dtype_name in {"VoidDType", "DateTime64DType", "TimeDelta64DType"}:
+ _extra_docs = f"""
+ .. warning::
+ ``np.dtypes.{_dtype_name}`` cannot be instantiated directly.
+ Use ``np.dtype("{_sctype_name}[{{unit}}]")`` instead.
+ """
+
+ add_newdoc('numpy.dtypes', _dtype_name,
+ f"""
+ {_dtype_name}{_signature}
+ --
+
+ DType class corresponding to the `numpy.{_sctype_name}` scalar type.
+ {_extra_docs}
+ See `numpy.dtype` for the typical way to create dtype instances
+ and :ref:`arrays.dtypes` for additional information.
+ """)
+
+ del _dtype_name, _signature, _sctype_name, _extra_docs # avoid namespace pollution
+
+
+add_newdoc('numpy._core.multiarray', 'StringDType',
+ """
+ StringDType(*, coerce=True, **kwargs)
+ --
+
+ StringDType(*, na_object=np._NoValue, coerce=True)
+
+ Create a StringDType instance.
+
+ StringDType can be used to store UTF-8 encoded variable-width strings in
+ a NumPy array.
+
+ Parameters
+ ----------
+ na_object : object, optional
+ Object used to represent missing data. If unset, the array will not
+ use a missing data sentinel.
+ coerce : bool, optional
+ Whether or not items in an array-like passed to an array creation
+ function that are neither a str or str subtype should be coerced to
+ str. Defaults to True. If set to False, creating a StringDType
+ array from an array-like containing entries that are not already
+ strings will raise an error.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+
+ >>> from numpy.dtypes import StringDType
+ >>> np.array(["hello", "world"], dtype=StringDType())
+ array(["hello", "world"], dtype=StringDType())
+
+ >>> arr = np.array(["hello", None, "world"],
+ ... dtype=StringDType(na_object=None))
+ >>> arr
+ array(["hello", None, "world"], dtype=StringDType(na_object=None))
+ >>> arr[1] is None
+ True
+
+ >>> arr = np.array(["hello", np.nan, "world"],
+ ... dtype=StringDType(na_object=np.nan))
+ >>> np.isnan(arr)
+ array([False, True, False])
+
+ >>> np.array([1.2, object(), "hello world"],
+ ... dtype=StringDType(coerce=False))
+ Traceback (most recent call last):
+ ...
+ ValueError: StringDType only allows string data when string coercion is disabled.
+
+ >>> np.array(["hello", "world"], dtype=StringDType(coerce=True))
+ array(["hello", "world"], dtype=StringDType(coerce=True))
+ """)
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_add_newdocs.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_add_newdocs.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..2d004814fdcf9a9c31bbea794d715a9b330ca161
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_add_newdocs.pyi
@@ -0,0 +1,2 @@
+from .function_base import add_newdoc as add_newdoc
+from .overrides import get_array_function_like_doc as get_array_function_like_doc
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_add_newdocs_scalars.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_add_newdocs_scalars.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f9eca5e47f375e55a66e3c547b5a811de5eb22f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_add_newdocs_scalars.py
@@ -0,0 +1,381 @@
+"""
+This file is separate from ``_add_newdocs.py`` so that it can be mocked out by
+our sphinx ``conf.py`` during doc builds, where we want to avoid showing
+platform-dependent information.
+"""
+import os
+import sys
+
+from numpy._core import dtype, numerictypes as _numerictypes
+from numpy._core.function_base import add_newdoc
+
+##############################################################################
+#
+# Documentation for concrete scalar classes
+#
+##############################################################################
+
+def numeric_type_aliases(aliases):
+ def type_aliases_gen():
+ for alias, doc in aliases:
+ try:
+ alias_type = getattr(_numerictypes, alias)
+ except AttributeError:
+ # The set of aliases that actually exist varies between platforms
+ pass
+ else:
+ yield (alias_type, alias, doc)
+ return list(type_aliases_gen())
+
+
+possible_aliases = numeric_type_aliases([
+ ('int8', '8-bit signed integer (``-128`` to ``127``)'),
+ ('int16', '16-bit signed integer (``-32_768`` to ``32_767``)'),
+ ('int32', '32-bit signed integer (``-2_147_483_648`` to ``2_147_483_647``)'),
+ ('int64', '64-bit signed integer (``-9_223_372_036_854_775_808`` to ``9_223_372_036_854_775_807``)'),
+ ('intp', 'Signed integer large enough to fit pointer, compatible with C ``intptr_t``'),
+ ('uint8', '8-bit unsigned integer (``0`` to ``255``)'),
+ ('uint16', '16-bit unsigned integer (``0`` to ``65_535``)'),
+ ('uint32', '32-bit unsigned integer (``0`` to ``4_294_967_295``)'),
+ ('uint64', '64-bit unsigned integer (``0`` to ``18_446_744_073_709_551_615``)'),
+ ('uintp', 'Unsigned integer large enough to fit pointer, compatible with C ``uintptr_t``'),
+ ('float16', '16-bit-precision floating-point number type: sign bit, 5 bits exponent, 10 bits mantissa'),
+ ('float32', '32-bit-precision floating-point number type: sign bit, 8 bits exponent, 23 bits mantissa'),
+ ('float64', '64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa'),
+ ('float96', '96-bit extended-precision floating-point number type'),
+ ('float128', '128-bit extended-precision floating-point number type'),
+ ('complex64', 'Complex number type composed of 2 32-bit-precision floating-point numbers'),
+ ('complex128', 'Complex number type composed of 2 64-bit-precision floating-point numbers'),
+ ('complex192', 'Complex number type composed of 2 96-bit extended-precision floating-point numbers'),
+ ('complex256', 'Complex number type composed of 2 128-bit extended-precision floating-point numbers'),
+])
+
+
+def _get_platform_and_machine():
+ try:
+ system, _, _, _, machine = os.uname()
+ except AttributeError:
+ system = sys.platform
+ if system == 'win32':
+ machine = os.environ.get('PROCESSOR_ARCHITEW6432', '') \
+ or os.environ.get('PROCESSOR_ARCHITECTURE', '')
+ else:
+ machine = 'unknown'
+ return system, machine
+
+
+_system, _machine = _get_platform_and_machine()
+_doc_alias_string = f":Alias on this platform ({_system} {_machine}):"
+
+# docstring prefix that cpython uses to populate `__text_signature__`
+_ARGUMENT_CLINIC_TEMPLATE = """{name}{signature}
+--
+
+{docstring}"""
+
+def add_newdoc_for_scalar_type(name: str, text_signature: str, doc: str) -> None:
+ # note: `:field: value` is rST syntax which renders as field lists.
+ cls = getattr(_numerictypes, name)
+ module = cls.__module__
+
+ lines_extra = [
+ "", # blank line after main doc
+ f":Character code: ``{dtype(cls).char!r}``",
+ ]
+
+ if name != cls.__name__:
+ lines_extra.append(f":Canonical name: `{module}.{name}`")
+
+ lines_extra.extend(
+ f"{_doc_alias_string} `{module}.{alias}`: {doc}."
+ for alias_type, alias, doc in possible_aliases
+ if alias_type is cls
+ )
+
+ docstring = _ARGUMENT_CLINIC_TEMPLATE.format(
+ name=cls.__name__, # must match the class name
+ signature=text_signature,
+ docstring="\n".join([doc.strip(), *lines_extra]),
+ )
+ add_newdoc('numpy._core.numerictypes', name, docstring)
+
+
+for bool_name in ('bool', 'bool_'):
+ add_newdoc_for_scalar_type(bool_name, '(value=False, /)', """
+Boolean type (True or False), stored as a byte.
+
+.. warning::
+
+ The :class:`bool` type is not a subclass of the :class:`int_` type
+ (the :class:`bool` is not even a number type). This is different
+ than Python's default implementation of :class:`bool` as a
+ sub-class of :class:`int`.
+""")
+
+add_newdoc_for_scalar_type('byte', '(value=0, /)', """
+Signed integer type, compatible with C ``char``.
+""")
+
+add_newdoc_for_scalar_type('short', '(value=0, /)', """
+Signed integer type, compatible with C ``short``.
+""")
+
+add_newdoc_for_scalar_type('intc', '(value=0, /)', """
+Signed integer type, compatible with C ``int``.
+""")
+
+add_newdoc_for_scalar_type('long', '(value=0, /)', """
+Signed integer type, compatible with C ``long``.
+""")
+
+# TODO: These docs probably need an if to highlight the default rather than
+# the C-types (and be correct).
+add_newdoc_for_scalar_type('int_', '(value=0, /)', """
+Default signed integer type, 64bit on 64bit systems and 32bit on 32bit systems.
+""")
+
+add_newdoc_for_scalar_type('longlong', '(value=0, /)', """
+Signed integer type, compatible with C ``long long``.
+""")
+
+add_newdoc_for_scalar_type('ubyte', '(value=0, /)', """
+Unsigned integer type, compatible with C ``unsigned char``.
+""")
+
+add_newdoc_for_scalar_type('ushort', '(value=0, /)', """
+Unsigned integer type, compatible with C ``unsigned short``.
+""")
+
+add_newdoc_for_scalar_type('uintc', '(value=0, /)', """
+Unsigned integer type, compatible with C ``unsigned int``.
+""")
+
+add_newdoc_for_scalar_type('uint', '(value=0, /)', """
+Unsigned signed integer type, 64bit on 64bit systems and 32bit on 32bit systems.
+""")
+
+add_newdoc_for_scalar_type('ulong', '(value=0, /)', """
+Unsigned integer type, compatible with C ``unsigned long``.
+""")
+
+add_newdoc_for_scalar_type('ulonglong', '(value=0, /)', """
+Unsigned integer type, compatible with C ``unsigned long long``.
+""")
+
+add_newdoc_for_scalar_type('half', '(value=0, /)', """
+Half-precision floating-point number type.
+""")
+
+add_newdoc_for_scalar_type('single', '(value=0, /)', """
+Single-precision floating-point number type, compatible with C ``float``.
+""")
+
+add_newdoc_for_scalar_type('double', '(value=0, /)', """
+Double-precision floating-point number type, compatible with Python :class:`float` and C ``double``.
+""")
+
+add_newdoc_for_scalar_type('longdouble', '(value=0, /)', """
+Extended-precision floating-point number type, compatible with C ``long double``
+but not necessarily with IEEE 754 quadruple-precision.
+""")
+
+add_newdoc_for_scalar_type('csingle', '(real=0, imag=0, /)', """
+Complex number type composed of two single-precision floating-point numbers.
+""")
+
+add_newdoc_for_scalar_type('cdouble', '(real=0, imag=0, /)', """
+Complex number type composed of two double-precision floating-point numbers,
+compatible with Python :class:`complex`.
+""")
+
+add_newdoc_for_scalar_type('clongdouble', '(real=0, imag=0, /)', """
+Complex number type composed of two extended-precision floating-point numbers.
+""")
+
+add_newdoc_for_scalar_type('object_', '(value=None, /)', """
+Any Python object.
+""")
+
+add_newdoc_for_scalar_type('str_', '(value="", /, *args, **kwargs)', r"""
+A unicode string.
+
+This type strips trailing null codepoints.
+
+>>> s = np.str_("abc\x00")
+>>> s
+'abc'
+
+Unlike the builtin :class:`str`, this supports the
+:ref:`python:bufferobjects`, exposing its contents as UCS4:
+
+>>> m = memoryview(np.str_("abc"))
+>>> m.format
+'3w'
+>>> m.tobytes()
+b'a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00'
+""")
+
+add_newdoc_for_scalar_type('bytes_', '(value="", /, *args, **kwargs)', r"""
+A byte string.
+
+When used in arrays, this type strips trailing null bytes.
+""")
+
+add_newdoc_for_scalar_type('void', '(length_or_data, /, dtype=None)', r"""
+np.void(length_or_data, /, dtype=None)
+
+Create a new structured or unstructured void scalar.
+
+Parameters
+----------
+length_or_data : int, array-like, bytes-like, object
+ One of multiple meanings (see notes). The length or
+ bytes data of an unstructured void. Or alternatively,
+ the data to be stored in the new scalar when `dtype`
+ is provided.
+ This can be an array-like, in which case an array may
+ be returned.
+dtype : dtype, optional
+ If provided the dtype of the new scalar. This dtype must
+ be "void" dtype (i.e. a structured or unstructured void,
+ see also :ref:`defining-structured-types`).
+
+ .. versionadded:: 1.24
+
+Notes
+-----
+For historical reasons and because void scalars can represent both
+arbitrary byte data and structured dtypes, the void constructor
+has three calling conventions:
+
+1. ``np.void(5)`` creates a ``dtype="V5"`` scalar filled with five
+ ``\0`` bytes. The 5 can be a Python or NumPy integer.
+2. ``np.void(b"bytes-like")`` creates a void scalar from the byte string.
+ The dtype itemsize will match the byte string length, here ``"V10"``.
+3. When a ``dtype=`` is passed the call is roughly the same as an
+ array creation. However, a void scalar rather than array is returned.
+
+Please see the examples which show all three different conventions.
+
+Examples
+--------
+>>> np.void(5)
+np.void(b'\x00\x00\x00\x00\x00')
+>>> np.void(b'abcd')
+np.void(b'\x61\x62\x63\x64')
+>>> np.void((3.2, b'eggs'), dtype="d,S5")
+np.void((3.2, b'eggs'), dtype=[('f0', '>> np.void(3, dtype=[('x', np.int8), ('y', np.int8)])
+np.void((3, 3), dtype=[('x', 'i1'), ('y', 'i1')])
+""")
+
+add_newdoc_for_scalar_type('datetime64', '(value=None, /, *args)', """
+If created from a 64-bit integer, it represents an offset from ``1970-01-01T00:00:00``.
+If created from string, the string can be in ISO 8601 date or datetime format.
+
+When parsing a string to create a datetime object, if the string contains
+a trailing timezone (A 'Z' or a timezone offset), the timezone will be
+dropped and a User Warning is given.
+
+Datetime64 objects should be considered to be UTC and therefore have an
+offset of +0000.
+
+>>> np.datetime64(10, 'Y')
+np.datetime64('1980')
+>>> np.datetime64('1980', 'Y')
+np.datetime64('1980')
+>>> np.datetime64(10, 'D')
+np.datetime64('1970-01-11')
+
+See :ref:`arrays.datetime` for more information.
+""")
+
+add_newdoc_for_scalar_type('timedelta64', '(value=0, /, *args)', """
+A timedelta stored as a 64-bit integer.
+
+See :ref:`arrays.datetime` for more information.
+""")
+
+add_newdoc('numpy._core.numerictypes', "integer", ('is_integer',
+ """
+ is_integer($self, /)
+ --
+
+ integer.is_integer() -> bool
+
+ Return ``True`` if the number is finite with integral value.
+
+ .. versionadded:: 1.22
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.int64(-2).is_integer()
+ True
+ >>> np.uint32(5).is_integer()
+ True
+ """))
+
+# TODO: work out how to put this on the base class, np.floating
+for float_name in ('half', 'single', 'double', 'longdouble'):
+ add_newdoc('numpy._core.numerictypes', float_name, ('as_integer_ratio',
+ f"""
+ as_integer_ratio($self, /)
+ --
+
+ {float_name}.as_integer_ratio() -> (int, int)
+
+ Return a pair of integers, whose ratio is exactly equal to the original
+ floating point number, and with a positive denominator.
+ Raise `OverflowError` on infinities and a `ValueError` on NaNs.
+
+ >>> np.{float_name}(10.0).as_integer_ratio()
+ (10, 1)
+ >>> np.{float_name}(0.0).as_integer_ratio()
+ (0, 1)
+ >>> np.{float_name}(-.25).as_integer_ratio()
+ (-1, 4)
+ """))
+
+ add_newdoc('numpy._core.numerictypes', float_name, ('is_integer',
+ f"""
+ is_integer($self, /)
+ --
+
+ {float_name}.is_integer() -> bool
+
+ Return ``True`` if the floating point number is finite with integral
+ value, and ``False`` otherwise.
+
+ .. versionadded:: 1.22
+
+ Examples
+ --------
+ >>> np.{float_name}(-2.0).is_integer()
+ True
+ >>> np.{float_name}(3.2).is_integer()
+ False
+ """))
+
+for int_name in ('int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32',
+ 'int64', 'uint64', 'int64', 'uint64', 'int64', 'uint64',
+ 'longlong', 'ulonglong'):
+ # Add negative examples for signed cases by checking typecode
+ add_newdoc('numpy._core.numerictypes', int_name, ('bit_count',
+ f"""
+ bit_count($self, /)
+ --
+
+ {int_name}.bit_count() -> int
+
+ Computes the number of 1-bits in the absolute value of the input.
+ Analogous to the builtin `int.bit_count` or ``popcount`` in C++.
+
+ Examples
+ --------
+ >>> np.{int_name}(127).bit_count()
+ 7""" +
+ (f"""
+ >>> np.{int_name}(-127).bit_count()
+ 7
+ """ if dtype(int_name).char.islower() else "")))
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_add_newdocs_scalars.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_add_newdocs_scalars.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..241f4a00bd45ac0dd201a77b545a2d98fa124ebd
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_add_newdocs_scalars.pyi
@@ -0,0 +1,16 @@
+from typing import Final
+
+import numpy as np
+
+possible_aliases: Final[list[tuple[type[np.number], str, str]]] = ...
+_system: Final[str] = ...
+_machine: Final[str] = ...
+_doc_alias_string: Final[str] = ...
+_bool_docstring: Final[str] = ...
+bool_name: str = ...
+int_name: str = ...
+float_name: str = ...
+
+def numeric_type_aliases(aliases: list[tuple[str, str]]) -> list[tuple[type[np.number], str, str]]: ...
+def add_newdoc_for_scalar_type(name: str, text_signature: str, doc: str) -> None: ...
+def _get_platform_and_machine() -> tuple[str, str]: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_asarray.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_asarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..edaff5222f6936779ddb6704087ececc46480a2b
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_asarray.py
@@ -0,0 +1,130 @@
+"""
+Functions in the ``as*array`` family that promote array-likes into arrays.
+
+`require` fits this category despite its name not matching this pattern.
+"""
+from .multiarray import array, asanyarray
+from .overrides import array_function_dispatch, finalize_array_function_like, set_module
+
+__all__ = ["require"]
+
+
+POSSIBLE_FLAGS = {
+ 'C': 'C', 'C_CONTIGUOUS': 'C', 'CONTIGUOUS': 'C',
+ 'F': 'F', 'F_CONTIGUOUS': 'F', 'FORTRAN': 'F',
+ 'A': 'A', 'ALIGNED': 'A',
+ 'W': 'W', 'WRITEABLE': 'W',
+ 'O': 'O', 'OWNDATA': 'O',
+ 'E': 'E', 'ENSUREARRAY': 'E'
+}
+
+
+@finalize_array_function_like
+@set_module('numpy')
+def require(a, dtype=None, requirements=None, *, like=None):
+ """
+ Return an ndarray of the provided type that satisfies requirements.
+
+ This function is useful to be sure that an array with the correct flags
+ is returned for passing to compiled code (perhaps through ctypes).
+
+ Parameters
+ ----------
+ a : array_like
+ The object to be converted to a type-and-requirement-satisfying array.
+ dtype : data-type
+ The required data-type. If None preserve the current dtype. If your
+ application requires the data to be in native byteorder, include
+ a byteorder specification as a part of the dtype specification.
+ requirements : str or sequence of str
+ The requirements list can be any of the following
+
+ * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
+ * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
+ * 'ALIGNED' ('A') - ensure a data-type aligned array
+ * 'WRITEABLE' ('W') - ensure a writable array
+ * 'OWNDATA' ('O') - ensure an array that owns its own data
+ * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Array with specified requirements and type if given.
+
+ See Also
+ --------
+ asarray : Convert input to an ndarray.
+ asanyarray : Convert to an ndarray, but pass through ndarray subclasses.
+ ascontiguousarray : Convert input to a contiguous array.
+ asfortranarray : Convert input to an ndarray with column-major
+ memory order.
+ ndarray.flags : Information about the memory layout of the array.
+
+ Notes
+ -----
+ The returned array will be guaranteed to have the listed requirements
+ by making a copy if needed.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2,3)
+ >>> x.flags
+ C_CONTIGUOUS : True
+ F_CONTIGUOUS : False
+ OWNDATA : False
+ WRITEABLE : True
+ ALIGNED : True
+ WRITEBACKIFCOPY : False
+
+ >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F'])
+ >>> y.flags
+ C_CONTIGUOUS : False
+ F_CONTIGUOUS : True
+ OWNDATA : True
+ WRITEABLE : True
+ ALIGNED : True
+ WRITEBACKIFCOPY : False
+
+ """
+ if like is not None:
+ return _require_with_like(
+ like,
+ a,
+ dtype=dtype,
+ requirements=requirements,
+ )
+
+ if not requirements:
+ return asanyarray(a, dtype=dtype)
+
+ requirements = {POSSIBLE_FLAGS[x.upper()] for x in requirements}
+
+ if 'E' in requirements:
+ requirements.remove('E')
+ subok = False
+ else:
+ subok = True
+
+ order = 'A'
+ if requirements >= {'C', 'F'}:
+ raise ValueError('Cannot specify both "C" and "F" order')
+ elif 'F' in requirements:
+ order = 'F'
+ requirements.remove('F')
+ elif 'C' in requirements:
+ order = 'C'
+ requirements.remove('C')
+
+ arr = array(a, dtype=dtype, order=order, copy=None, subok=subok)
+
+ for prop in requirements:
+ if not arr.flags[prop]:
+ return arr.copy(order)
+ return arr
+
+
+_require_with_like = array_function_dispatch()(require)
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_asarray.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_asarray.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..6bef69d8e4eabd7e1318324cd731cb4492b0771f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_asarray.pyi
@@ -0,0 +1,43 @@
+from collections.abc import Iterable
+from typing import Any, Literal, TypeAlias, TypeVar, overload
+
+from numpy._typing import DTypeLike, NDArray, _SupportsArrayFunc
+
+__all__ = ["require"]
+
+_ArrayT = TypeVar("_ArrayT", bound=NDArray[Any])
+
+_Requirements: TypeAlias = Literal[
+ "C", "C_CONTIGUOUS", "CONTIGUOUS",
+ "F", "F_CONTIGUOUS", "FORTRAN",
+ "A", "ALIGNED",
+ "W", "WRITEABLE",
+ "O", "OWNDATA"
+]
+_E: TypeAlias = Literal["E", "ENSUREARRAY"]
+_RequirementsWithE: TypeAlias = _Requirements | _E
+
+@overload
+def require(
+ a: _ArrayT,
+ dtype: None = None,
+ requirements: _Requirements | Iterable[_Requirements] | None = None,
+ *,
+ like: _SupportsArrayFunc | None = None
+) -> _ArrayT: ...
+@overload
+def require(
+ a: object,
+ dtype: DTypeLike | None = None,
+ requirements: _E | Iterable[_RequirementsWithE] | None = None,
+ *,
+ like: _SupportsArrayFunc | None = None
+) -> NDArray[Any]: ...
+@overload
+def require(
+ a: object,
+ dtype: DTypeLike | None = None,
+ requirements: _Requirements | Iterable[_Requirements] | None = None,
+ *,
+ like: _SupportsArrayFunc | None = None
+) -> NDArray[Any]: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_dtype.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_dtype.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a8a091b269c2f0acd37e3844e4f09a35b71e098
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_dtype.py
@@ -0,0 +1,366 @@
+"""
+A place for code to be called from the implementation of np.dtype
+
+String handling is much easier to do correctly in python.
+"""
+import numpy as np
+
+_kind_to_stem = {
+ 'u': 'uint',
+ 'i': 'int',
+ 'c': 'complex',
+ 'f': 'float',
+ 'b': 'bool',
+ 'V': 'void',
+ 'O': 'object',
+ 'M': 'datetime',
+ 'm': 'timedelta',
+ 'S': 'bytes',
+ 'U': 'str',
+}
+
+
+def _kind_name(dtype):
+ try:
+ return _kind_to_stem[dtype.kind]
+ except KeyError as e:
+ raise RuntimeError(
+ f"internal dtype error, unknown kind {dtype.kind!r}"
+ ) from None
+
+
+def __str__(dtype):
+ if dtype.fields is not None:
+ return _struct_str(dtype, include_align=True)
+ elif dtype.subdtype:
+ return _subarray_str(dtype)
+ elif issubclass(dtype.type, np.flexible) or not dtype.isnative:
+ return dtype.str
+ else:
+ return dtype.name
+
+
+def __repr__(dtype):
+ arg_str = _construction_repr(dtype, include_align=False)
+ if dtype.isalignedstruct:
+ arg_str = arg_str + ", align=True"
+ return f"dtype({arg_str})"
+
+
+def _unpack_field(dtype, offset, title=None):
+ """
+ Helper function to normalize the items in dtype.fields.
+
+ Call as:
+
+ dtype, offset, title = _unpack_field(*dtype.fields[name])
+ """
+ return dtype, offset, title
+
+
+def _isunsized(dtype):
+ # PyDataType_ISUNSIZED
+ return dtype.itemsize == 0
+
+
+def _construction_repr(dtype, include_align=False, short=False):
+ """
+ Creates a string repr of the dtype, excluding the 'dtype()' part
+ surrounding the object. This object may be a string, a list, or
+ a dict depending on the nature of the dtype. This
+ is the object passed as the first parameter to the dtype
+ constructor, and if no additional constructor parameters are
+ given, will reproduce the exact memory layout.
+
+ Parameters
+ ----------
+ short : bool
+ If true, this creates a shorter repr using 'kind' and 'itemsize',
+ instead of the longer type name.
+
+ include_align : bool
+ If true, this includes the 'align=True' parameter
+ inside the struct dtype construction dict when needed. Use this flag
+ if you want a proper repr string without the 'dtype()' part around it.
+
+ If false, this does not preserve the
+ 'align=True' parameter or sticky NPY_ALIGNED_STRUCT flag for
+ struct arrays like the regular repr does, because the 'align'
+ flag is not part of first dtype constructor parameter. This
+ mode is intended for a full 'repr', where the 'align=True' is
+ provided as the second parameter.
+ """
+ if dtype.fields is not None:
+ return _struct_str(dtype, include_align=include_align)
+ elif dtype.subdtype:
+ return _subarray_str(dtype)
+ else:
+ return _scalar_str(dtype, short=short)
+
+
+def _scalar_str(dtype, short):
+ byteorder = _byte_order_str(dtype)
+
+ if dtype.type == np.bool:
+ if short:
+ return "'?'"
+ else:
+ return "'bool'"
+
+ elif dtype.type == np.object_:
+ # The object reference may be different sizes on different
+ # platforms, so it should never include the itemsize here.
+ return "'O'"
+
+ elif dtype.type == np.bytes_:
+ if _isunsized(dtype):
+ return "'S'"
+ else:
+ return "'S%d'" % dtype.itemsize
+
+ elif dtype.type == np.str_:
+ if _isunsized(dtype):
+ return f"'{byteorder}U'"
+ else:
+ return "'%sU%d'" % (byteorder, dtype.itemsize / 4)
+
+ elif dtype.type == str:
+ return "'T'"
+
+ elif not type(dtype)._legacy:
+ return f"'{byteorder}{type(dtype).__name__}{dtype.itemsize * 8}'"
+
+ # unlike the other types, subclasses of void are preserved - but
+ # historically the repr does not actually reveal the subclass
+ elif issubclass(dtype.type, np.void):
+ if _isunsized(dtype):
+ return "'V'"
+ else:
+ return "'V%d'" % dtype.itemsize
+
+ elif dtype.type == np.datetime64:
+ return f"'{byteorder}M8{_datetime_metadata_str(dtype)}'"
+
+ elif dtype.type == np.timedelta64:
+ return f"'{byteorder}m8{_datetime_metadata_str(dtype)}'"
+
+ elif dtype.isbuiltin == 2:
+ return dtype.type.__name__
+
+ elif np.issubdtype(dtype, np.number):
+ # Short repr with endianness, like '' """
+ # hack to obtain the native and swapped byte order characters
+ swapped = np.dtype(int).newbyteorder('S')
+ native = swapped.newbyteorder('S')
+
+ byteorder = dtype.byteorder
+ if byteorder == '=':
+ return native.byteorder
+ if byteorder == 'S':
+ # TODO: this path can never be reached
+ return swapped.byteorder
+ elif byteorder == '|':
+ return ''
+ else:
+ return byteorder
+
+
+def _datetime_metadata_str(dtype):
+ # TODO: this duplicates the C metastr_to_unicode functionality
+ unit, count = np.datetime_data(dtype)
+ if unit == 'generic':
+ return ''
+ elif count == 1:
+ return f'[{unit}]'
+ else:
+ return f'[{count}{unit}]'
+
+
+def _struct_dict_str(dtype, includealignedflag):
+ # unpack the fields dictionary into ls
+ names = dtype.names
+ fld_dtypes = []
+ offsets = []
+ titles = []
+ for name in names:
+ fld_dtype, offset, title = _unpack_field(*dtype.fields[name])
+ fld_dtypes.append(fld_dtype)
+ offsets.append(offset)
+ titles.append(title)
+
+ # Build up a string to make the dictionary
+
+ if np._core.arrayprint._get_legacy_print_mode() <= 121:
+ colon = ":"
+ fieldsep = ","
+ else:
+ colon = ": "
+ fieldsep = ", "
+
+ # First, the names
+ ret = "{'names'%s[" % colon
+ ret += fieldsep.join(repr(name) for name in names)
+
+ # Second, the formats
+ ret += f"], 'formats'{colon}["
+ ret += fieldsep.join(
+ _construction_repr(fld_dtype, short=True) for fld_dtype in fld_dtypes)
+
+ # Third, the offsets
+ ret += f"], 'offsets'{colon}["
+ ret += fieldsep.join("%d" % offset for offset in offsets)
+
+ # Fourth, the titles
+ if any(title is not None for title in titles):
+ ret += f"], 'titles'{colon}["
+ ret += fieldsep.join(repr(title) for title in titles)
+
+ # Fifth, the itemsize
+ ret += "], 'itemsize'%s%d" % (colon, dtype.itemsize)
+
+ if (includealignedflag and dtype.isalignedstruct):
+ # Finally, the aligned flag
+ ret += ", 'aligned'%sTrue}" % colon
+ else:
+ ret += "}"
+
+ return ret
+
+
+def _aligned_offset(offset, alignment):
+ # round up offset:
+ return - (-offset // alignment) * alignment
+
+
+def _is_packed(dtype):
+ """
+ Checks whether the structured data type in 'dtype'
+ has a simple layout, where all the fields are in order,
+ and follow each other with no alignment padding.
+
+ When this returns true, the dtype can be reconstructed
+ from a list of the field names and dtypes with no additional
+ dtype parameters.
+
+ Duplicates the C `is_dtype_struct_simple_unaligned_layout` function.
+ """
+ align = dtype.isalignedstruct
+ max_alignment = 1
+ total_offset = 0
+ for name in dtype.names:
+ fld_dtype, fld_offset, title = _unpack_field(*dtype.fields[name])
+
+ if align:
+ total_offset = _aligned_offset(total_offset, fld_dtype.alignment)
+ max_alignment = max(max_alignment, fld_dtype.alignment)
+
+ if fld_offset != total_offset:
+ return False
+ total_offset += fld_dtype.itemsize
+
+ if align:
+ total_offset = _aligned_offset(total_offset, max_alignment)
+
+ return total_offset == dtype.itemsize
+
+
+def _struct_list_str(dtype):
+ items = []
+ for name in dtype.names:
+ fld_dtype, fld_offset, title = _unpack_field(*dtype.fields[name])
+
+ item = "("
+ if title is not None:
+ item += f"({title!r}, {name!r}), "
+ else:
+ item += f"{name!r}, "
+ # Special case subarray handling here
+ if fld_dtype.subdtype is not None:
+ base, shape = fld_dtype.subdtype
+ item += f"{_construction_repr(base, short=True)}, {shape}"
+ else:
+ item += _construction_repr(fld_dtype, short=True)
+
+ item += ")"
+ items.append(item)
+
+ return "[" + ", ".join(items) + "]"
+
+
+def _struct_str(dtype, include_align):
+ # The list str representation can't include the 'align=' flag,
+ # so if it is requested and the struct has the aligned flag set,
+ # we must use the dict str instead.
+ if not (include_align and dtype.isalignedstruct) and _is_packed(dtype):
+ sub = _struct_list_str(dtype)
+
+ else:
+ sub = _struct_dict_str(dtype, include_align)
+
+ # If the data type isn't the default, void, show it
+ if dtype.type != np.void:
+ return f"({dtype.type.__module__}.{dtype.type.__name__}, {sub})"
+ else:
+ return sub
+
+
+def _subarray_str(dtype):
+ base, shape = dtype.subdtype
+ return f"({_construction_repr(base, short=True)}, {shape})"
+
+
+def _name_includes_bit_suffix(dtype):
+ if dtype.type == np.object_:
+ # pointer size varies by system, best to omit it
+ return False
+ elif dtype.type == np.bool:
+ # implied
+ return False
+ elif dtype.type is None:
+ return True
+ elif np.issubdtype(dtype, np.flexible) and _isunsized(dtype):
+ # unspecified
+ return False
+ else:
+ return True
+
+
+def _name_get(dtype):
+ # provides dtype.name.__get__, documented as returning a "bit name"
+
+ if dtype.isbuiltin == 2:
+ # user dtypes don't promise to do anything special
+ return dtype.type.__name__
+
+ if not type(dtype)._legacy:
+ name = type(dtype).__name__
+
+ elif issubclass(dtype.type, np.void):
+ # historically, void subclasses preserve their name, eg `record64`
+ name = dtype.type.__name__
+ else:
+ name = _kind_name(dtype)
+
+ # append bit counts
+ if _name_includes_bit_suffix(dtype):
+ name += f"{dtype.itemsize * 8}"
+
+ # append metadata to datetimes
+ if dtype.type in (np.datetime64, np.timedelta64):
+ name += _datetime_metadata_str(dtype)
+
+ return name
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_dtype.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_dtype.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..28adecf4ad2f24b139f55676750548ee7e8c5cd6
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_dtype.pyi
@@ -0,0 +1,56 @@
+from typing import Final, Literal as L, TypeAlias, TypedDict, overload, type_check_only
+from typing_extensions import ReadOnly, TypeVar
+
+import numpy as np
+
+###
+
+_T = TypeVar("_T")
+
+_Name: TypeAlias = L["uint", "int", "complex", "float", "bool", "void", "object", "datetime", "timedelta", "bytes", "str"]
+
+@type_check_only
+class _KindToStemType(TypedDict):
+ u: ReadOnly[L["uint"]]
+ i: ReadOnly[L["int"]]
+ c: ReadOnly[L["complex"]]
+ f: ReadOnly[L["float"]]
+ b: ReadOnly[L["bool"]]
+ V: ReadOnly[L["void"]]
+ O: ReadOnly[L["object"]]
+ M: ReadOnly[L["datetime"]]
+ m: ReadOnly[L["timedelta"]]
+ S: ReadOnly[L["bytes"]]
+ U: ReadOnly[L["str"]]
+
+###
+
+_kind_to_stem: Final[_KindToStemType] = ...
+
+#
+def _kind_name(dtype: np.dtype) -> _Name: ...
+def __str__(dtype: np.dtype) -> str: ...
+def __repr__(dtype: np.dtype) -> str: ...
+
+#
+def _isunsized(dtype: np.dtype) -> bool: ...
+def _is_packed(dtype: np.dtype) -> bool: ...
+def _name_includes_bit_suffix(dtype: np.dtype) -> bool: ...
+
+#
+def _construction_repr(dtype: np.dtype, include_align: bool = False, short: bool = False) -> str: ...
+def _scalar_str(dtype: np.dtype, short: bool) -> str: ...
+def _byte_order_str(dtype: np.dtype) -> str: ...
+def _datetime_metadata_str(dtype: np.dtype) -> str: ...
+def _struct_dict_str(dtype: np.dtype, includealignedflag: bool) -> str: ...
+def _struct_list_str(dtype: np.dtype) -> str: ...
+def _struct_str(dtype: np.dtype, include_align: bool) -> str: ...
+def _subarray_str(dtype: np.dtype) -> str: ...
+def _name_get(dtype: np.dtype) -> str: ...
+
+#
+@overload
+def _unpack_field(dtype: np.dtype, offset: int, title: _T) -> tuple[np.dtype, int, _T]: ...
+@overload
+def _unpack_field(dtype: np.dtype, offset: int, title: None = None) -> tuple[np.dtype, int, None]: ...
+def _aligned_offset(offset: int, alignment: int) -> int: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_dtype_ctypes.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_dtype_ctypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..4de6df6dbd37d63ecb259584c71a5c5d91f45a0c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_dtype_ctypes.py
@@ -0,0 +1,120 @@
+"""
+Conversion from ctypes to dtype.
+
+In an ideal world, we could achieve this through the PEP3118 buffer protocol,
+something like::
+
+ def dtype_from_ctypes_type(t):
+ # needed to ensure that the shape of `t` is within memoryview.format
+ class DummyStruct(ctypes.Structure):
+ _fields_ = [('a', t)]
+
+ # empty to avoid memory allocation
+ ctype_0 = (DummyStruct * 0)()
+ mv = memoryview(ctype_0)
+
+ # convert the struct, and slice back out the field
+ return _dtype_from_pep3118(mv.format)['a']
+
+Unfortunately, this fails because:
+
+* ctypes cannot handle length-0 arrays with PEP3118 (bpo-32782)
+* PEP3118 cannot represent unions, but both numpy and ctypes can
+* ctypes cannot handle big-endian structs with PEP3118 (bpo-32780)
+"""
+
+# We delay-import ctypes for distributions that do not include it.
+# While this module is not used unless the user passes in ctypes
+# members, it is eagerly imported from numpy/_core/__init__.py.
+import numpy as np
+
+
+def _from_ctypes_array(t):
+ return np.dtype((dtype_from_ctypes_type(t._type_), (t._length_,)))
+
+
+def _from_ctypes_structure(t):
+ for item in t._fields_:
+ if len(item) > 2:
+ raise TypeError(
+ "ctypes bitfields have no dtype equivalent")
+
+ if hasattr(t, "_pack_"):
+ import ctypes
+ formats = []
+ offsets = []
+ names = []
+ current_offset = 0
+ for fname, ftyp in t._fields_:
+ names.append(fname)
+ formats.append(dtype_from_ctypes_type(ftyp))
+ # Each type has a default offset, this is platform dependent
+ # for some types.
+ effective_pack = min(t._pack_, ctypes.alignment(ftyp))
+ current_offset = (
+ (current_offset + effective_pack - 1) // effective_pack
+ ) * effective_pack
+ offsets.append(current_offset)
+ current_offset += ctypes.sizeof(ftyp)
+
+ return np.dtype({
+ "formats": formats,
+ "offsets": offsets,
+ "names": names,
+ "itemsize": ctypes.sizeof(t)})
+ else:
+ fields = []
+ for fname, ftyp in t._fields_:
+ fields.append((fname, dtype_from_ctypes_type(ftyp)))
+
+ # by default, ctypes structs are aligned
+ return np.dtype(fields, align=True)
+
+
+def _from_ctypes_scalar(t):
+ """
+ Return the dtype type with endianness included if it's the case
+ """
+ if getattr(t, '__ctype_be__', None) is t:
+ return np.dtype('>' + t._type_)
+ elif getattr(t, '__ctype_le__', None) is t:
+ return np.dtype('<' + t._type_)
+ else:
+ return np.dtype(t._type_)
+
+
+def _from_ctypes_union(t):
+ import ctypes
+ formats = []
+ offsets = []
+ names = []
+ for fname, ftyp in t._fields_:
+ names.append(fname)
+ formats.append(dtype_from_ctypes_type(ftyp))
+ offsets.append(0) # Union fields are offset to 0
+
+ return np.dtype({
+ "formats": formats,
+ "offsets": offsets,
+ "names": names,
+ "itemsize": ctypes.sizeof(t)})
+
+
+def dtype_from_ctypes_type(t):
+ """
+ Construct a dtype object from a ctypes type
+ """
+ import _ctypes
+ if issubclass(t, _ctypes.Array):
+ return _from_ctypes_array(t)
+ elif issubclass(t, _ctypes._Pointer):
+ raise TypeError("ctypes pointers have no dtype equivalent")
+ elif issubclass(t, _ctypes.Structure):
+ return _from_ctypes_structure(t)
+ elif issubclass(t, _ctypes.Union):
+ return _from_ctypes_union(t)
+ elif isinstance(getattr(t, '_type_', None), str):
+ return _from_ctypes_scalar(t)
+ else:
+ raise NotImplementedError(
+ f"Unknown ctypes type {t.__name__}")
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_dtype_ctypes.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_dtype_ctypes.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..69438a2c1b4c98cda8b36d45440fd459f118ebb9
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_dtype_ctypes.pyi
@@ -0,0 +1,83 @@
+import _ctypes
+import ctypes as ct
+from typing import Any, overload
+
+import numpy as np
+
+#
+@overload
+def dtype_from_ctypes_type(t: type[_ctypes.Array[Any] | _ctypes.Structure]) -> np.dtype[np.void]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_bool]) -> np.dtype[np.bool]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_int8 | ct.c_byte]) -> np.dtype[np.int8]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_uint8 | ct.c_ubyte]) -> np.dtype[np.uint8]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_int16 | ct.c_short]) -> np.dtype[np.int16]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_uint16 | ct.c_ushort]) -> np.dtype[np.uint16]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_int32 | ct.c_int]) -> np.dtype[np.int32]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_uint32 | ct.c_uint]) -> np.dtype[np.uint32]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_ssize_t | ct.c_long]) -> np.dtype[np.int32 | np.int64]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_size_t | ct.c_ulong]) -> np.dtype[np.uint32 | np.uint64]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_int64 | ct.c_longlong]) -> np.dtype[np.int64]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_uint64 | ct.c_ulonglong]) -> np.dtype[np.uint64]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_float]) -> np.dtype[np.float32]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_double]) -> np.dtype[np.float64]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_longdouble]) -> np.dtype[np.longdouble]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.c_char]) -> np.dtype[np.bytes_]: ...
+@overload
+def dtype_from_ctypes_type(t: type[ct.py_object[Any]]) -> np.dtype[np.object_]: ...
+
+# NOTE: the complex ctypes on python>=3.14 are not yet supported at runtim, see
+# https://github.com/numpy/numpy/issues/28360
+
+#
+def _from_ctypes_array(t: type[_ctypes.Array[Any]]) -> np.dtype[np.void]: ...
+def _from_ctypes_structure(t: type[_ctypes.Structure]) -> np.dtype[np.void]: ...
+def _from_ctypes_union(t: type[_ctypes.Union]) -> np.dtype[np.void]: ...
+
+# keep in sync with `dtype_from_ctypes_type` (minus the first overload)
+@overload
+def _from_ctypes_scalar(t: type[ct.c_bool]) -> np.dtype[np.bool]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_int8 | ct.c_byte]) -> np.dtype[np.int8]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_uint8 | ct.c_ubyte]) -> np.dtype[np.uint8]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_int16 | ct.c_short]) -> np.dtype[np.int16]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_uint16 | ct.c_ushort]) -> np.dtype[np.uint16]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_int32 | ct.c_int]) -> np.dtype[np.int32]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_uint32 | ct.c_uint]) -> np.dtype[np.uint32]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_ssize_t | ct.c_long]) -> np.dtype[np.int32 | np.int64]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_size_t | ct.c_ulong]) -> np.dtype[np.uint32 | np.uint64]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_int64 | ct.c_longlong]) -> np.dtype[np.int64]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_uint64 | ct.c_ulonglong]) -> np.dtype[np.uint64]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_float]) -> np.dtype[np.float32]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_double]) -> np.dtype[np.float64]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_longdouble]) -> np.dtype[np.longdouble]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.c_char]) -> np.dtype[np.bytes_]: ...
+@overload
+def _from_ctypes_scalar(t: type[ct.py_object[Any]]) -> np.dtype[np.object_]: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_exceptions.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..73b07d25ef1f2b4b7a3c81ead115a3b8382b0730
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_exceptions.py
@@ -0,0 +1,162 @@
+"""
+Various richly-typed exceptions, that also help us deal with string formatting
+in python where it's easier.
+
+By putting the formatting in `__str__`, we also avoid paying the cost for
+users who silence the exceptions.
+"""
+
+def _unpack_tuple(tup):
+ if len(tup) == 1:
+ return tup[0]
+ else:
+ return tup
+
+
+def _display_as_base(cls):
+ """
+ A decorator that makes an exception class look like its base.
+
+ We use this to hide subclasses that are implementation details - the user
+ should catch the base type, which is what the traceback will show them.
+
+ Classes decorated with this decorator are subject to removal without a
+ deprecation warning.
+ """
+ assert issubclass(cls, Exception)
+ cls.__name__ = cls.__base__.__name__
+ return cls
+
+
+class UFuncTypeError(TypeError):
+ """ Base class for all ufunc exceptions """
+ def __init__(self, ufunc):
+ self.ufunc = ufunc
+
+
+@_display_as_base
+class _UFuncNoLoopError(UFuncTypeError):
+ """ Thrown when a ufunc loop cannot be found """
+ def __init__(self, ufunc, dtypes):
+ super().__init__(ufunc)
+ self.dtypes = tuple(dtypes)
+
+ def __str__(self):
+ return (
+ f"ufunc {self.ufunc.__name__!r} did not contain a loop with signature "
+ f"matching types {_unpack_tuple(self.dtypes[:self.ufunc.nin])!r} "
+ f"-> {_unpack_tuple(self.dtypes[self.ufunc.nin:])!r}"
+ )
+
+
+@_display_as_base
+class _UFuncBinaryResolutionError(_UFuncNoLoopError):
+ """ Thrown when a binary resolution fails """
+ def __init__(self, ufunc, dtypes):
+ super().__init__(ufunc, dtypes)
+ assert len(self.dtypes) == 2
+
+ def __str__(self):
+ return (
+ "ufunc {!r} cannot use operands with types {!r} and {!r}"
+ ).format(
+ self.ufunc.__name__, *self.dtypes
+ )
+
+
+@_display_as_base
+class _UFuncCastingError(UFuncTypeError):
+ def __init__(self, ufunc, casting, from_, to):
+ super().__init__(ufunc)
+ self.casting = casting
+ self.from_ = from_
+ self.to = to
+
+
+@_display_as_base
+class _UFuncInputCastingError(_UFuncCastingError):
+ """ Thrown when a ufunc input cannot be casted """
+ def __init__(self, ufunc, casting, from_, to, i):
+ super().__init__(ufunc, casting, from_, to)
+ self.in_i = i
+
+ def __str__(self):
+ # only show the number if more than one input exists
+ i_str = f"{self.in_i} " if self.ufunc.nin != 1 else ""
+ return (
+ f"Cannot cast ufunc {self.ufunc.__name__!r} input {i_str}from "
+ f"{self.from_!r} to {self.to!r} with casting rule {self.casting!r}"
+ )
+
+
+@_display_as_base
+class _UFuncOutputCastingError(_UFuncCastingError):
+ """ Thrown when a ufunc output cannot be casted """
+ def __init__(self, ufunc, casting, from_, to, i):
+ super().__init__(ufunc, casting, from_, to)
+ self.out_i = i
+
+ def __str__(self):
+ # only show the number if more than one output exists
+ i_str = f"{self.out_i} " if self.ufunc.nout != 1 else ""
+ return (
+ f"Cannot cast ufunc {self.ufunc.__name__!r} output {i_str}from "
+ f"{self.from_!r} to {self.to!r} with casting rule {self.casting!r}"
+ )
+
+
+@_display_as_base
+class _ArrayMemoryError(MemoryError):
+ """ Thrown when an array cannot be allocated"""
+ def __init__(self, shape, dtype):
+ self.shape = shape
+ self.dtype = dtype
+
+ @property
+ def _total_size(self):
+ num_bytes = self.dtype.itemsize
+ for dim in self.shape:
+ num_bytes *= dim
+ return num_bytes
+
+ @staticmethod
+ def _size_to_string(num_bytes):
+ """ Convert a number of bytes into a binary size string """
+
+ # https://en.wikipedia.org/wiki/Binary_prefix
+ LOG2_STEP = 10
+ STEP = 1024
+ units = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']
+
+ unit_i = max(num_bytes.bit_length() - 1, 1) // LOG2_STEP
+ unit_val = 1 << (unit_i * LOG2_STEP)
+ n_units = num_bytes / unit_val
+ del unit_val
+
+ # ensure we pick a unit that is correct after rounding
+ if round(n_units) == STEP:
+ unit_i += 1
+ n_units /= STEP
+
+ # deal with sizes so large that we don't have units for them
+ if unit_i >= len(units):
+ new_unit_i = len(units) - 1
+ n_units *= 1 << ((unit_i - new_unit_i) * LOG2_STEP)
+ unit_i = new_unit_i
+
+ unit_name = units[unit_i]
+ # format with a sensible number of digits
+ if unit_i == 0:
+ # no decimal point on bytes
+ return f'{n_units:.0f} {unit_name}'
+ elif round(n_units) < 1000:
+ # 3 significant figures, if none are dropped to the left of the .
+ return f'{n_units:#.3g} {unit_name}'
+ else:
+ # just give all the digits otherwise
+ return f'{n_units:#.0f} {unit_name}'
+
+ def __str__(self):
+ size_str = self._size_to_string(self._total_size)
+ return (f"Unable to allocate {size_str} for an array with shape "
+ f"{self.shape} and data type {self.dtype}")
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_exceptions.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_exceptions.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..b340fde3e46331e9f4ef2fa8ab8920a5dd1e45df
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_exceptions.pyi
@@ -0,0 +1,54 @@
+from collections.abc import Iterable
+from typing import Any, Final, TypeVar, overload
+
+import numpy as np
+from numpy import _CastingKind
+
+###
+
+_T = TypeVar("_T")
+_TupleT = TypeVar("_TupleT", bound=tuple[()] | tuple[Any, Any, *tuple[Any, ...]])
+_ExceptionT = TypeVar("_ExceptionT", bound=Exception)
+
+###
+
+class UFuncTypeError(TypeError):
+ ufunc: Final[np.ufunc]
+ def __init__(self, /, ufunc: np.ufunc) -> None: ...
+
+class _UFuncNoLoopError(UFuncTypeError):
+ dtypes: tuple[np.dtype, ...]
+ def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype]) -> None: ...
+
+class _UFuncBinaryResolutionError(_UFuncNoLoopError):
+ dtypes: tuple[np.dtype, np.dtype]
+ def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype]) -> None: ...
+
+class _UFuncCastingError(UFuncTypeError):
+ casting: Final[_CastingKind]
+ from_: Final[np.dtype]
+ to: Final[np.dtype]
+ def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype, to: np.dtype) -> None: ...
+
+class _UFuncInputCastingError(_UFuncCastingError):
+ in_i: Final[int]
+ def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype, to: np.dtype, i: int) -> None: ...
+
+class _UFuncOutputCastingError(_UFuncCastingError):
+ out_i: Final[int]
+ def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype, to: np.dtype, i: int) -> None: ...
+
+class _ArrayMemoryError(MemoryError):
+ shape: tuple[int, ...]
+ dtype: np.dtype
+ def __init__(self, /, shape: tuple[int, ...], dtype: np.dtype) -> None: ...
+ @property
+ def _total_size(self) -> int: ...
+ @staticmethod
+ def _size_to_string(num_bytes: int) -> str: ...
+
+@overload
+def _unpack_tuple(tup: tuple[_T]) -> _T: ...
+@overload
+def _unpack_tuple(tup: _TupleT) -> _TupleT: ...
+def _display_as_base(cls: type[_ExceptionT]) -> type[_ExceptionT]: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_internal.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c64daf30dbd660bf289d24219e2831897bb42d5
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_internal.py
@@ -0,0 +1,968 @@
+"""
+A place for internal code
+
+Some things are more easily handled Python.
+
+"""
+import ast
+import math
+import re
+import sys
+import warnings
+
+from numpy import _NoValue
+from numpy.exceptions import DTypePromotionError
+
+from .multiarray import StringDType, array, dtype, promote_types
+
+try:
+ import ctypes
+except ImportError:
+ ctypes = None
+
+IS_PYPY = sys.implementation.name == 'pypy'
+
+if sys.byteorder == 'little':
+ _nbo = '<'
+else:
+ _nbo = '>'
+
+def _makenames_list(adict, align):
+ allfields = []
+
+ for fname, obj in adict.items():
+ n = len(obj)
+ if not isinstance(obj, tuple) or n not in (2, 3):
+ raise ValueError("entry not a 2- or 3- tuple")
+ if n > 2 and obj[2] == fname:
+ continue
+ num = int(obj[1])
+ if num < 0:
+ raise ValueError("invalid offset.")
+ format = dtype(obj[0], align=align)
+ if n > 2:
+ title = obj[2]
+ else:
+ title = None
+ allfields.append((fname, format, num, title))
+ # sort by offsets
+ allfields.sort(key=lambda x: x[2])
+ names = [x[0] for x in allfields]
+ formats = [x[1] for x in allfields]
+ offsets = [x[2] for x in allfields]
+ titles = [x[3] for x in allfields]
+
+ return names, formats, offsets, titles
+
+# Called in PyArray_DescrConverter function when
+# a dictionary without "names" and "formats"
+# fields is used as a data-type descriptor.
+def _usefields(adict, align):
+ try:
+ names = adict[-1]
+ except KeyError:
+ names = None
+ if names is None:
+ names, formats, offsets, titles = _makenames_list(adict, align)
+ else:
+ formats = []
+ offsets = []
+ titles = []
+ for name in names:
+ res = adict[name]
+ formats.append(res[0])
+ offsets.append(res[1])
+ if len(res) > 2:
+ titles.append(res[2])
+ else:
+ titles.append(None)
+
+ return dtype({"names": names,
+ "formats": formats,
+ "offsets": offsets,
+ "titles": titles}, align)
+
+
+# construct an array_protocol descriptor list
+# from the fields attribute of a descriptor
+# This calls itself recursively but should eventually hit
+# a descriptor that has no fields and then return
+# a simple typestring
+
+def _array_descr(descriptor):
+ fields = descriptor.fields
+ if fields is None:
+ subdtype = descriptor.subdtype
+ if subdtype is None:
+ if descriptor.metadata is None:
+ return descriptor.str
+ else:
+ new = descriptor.metadata.copy()
+ if new:
+ return (descriptor.str, new)
+ else:
+ return descriptor.str
+ else:
+ return (_array_descr(subdtype[0]), subdtype[1])
+
+ names = descriptor.names
+ ordered_fields = [fields[x] + (x,) for x in names]
+ result = []
+ offset = 0
+ for field in ordered_fields:
+ if field[1] > offset:
+ num = field[1] - offset
+ result.append(('', f'|V{num}'))
+ offset += num
+ elif field[1] < offset:
+ raise ValueError(
+ "dtype.descr is not defined for types with overlapping or "
+ "out-of-order fields")
+ if len(field) > 3:
+ name = (field[2], field[3])
+ else:
+ name = field[2]
+ if field[0].subdtype:
+ tup = (name, _array_descr(field[0].subdtype[0]),
+ field[0].subdtype[1])
+ else:
+ tup = (name, _array_descr(field[0]))
+ offset += field[0].itemsize
+ result.append(tup)
+
+ if descriptor.itemsize > offset:
+ num = descriptor.itemsize - offset
+ result.append(('', f'|V{num}'))
+
+ return result
+
+
+# format_re was originally from numarray by J. Todd Miller
+
+format_re = re.compile(r'(?P[<>|=]?)'
+ r'(?P *[(]?[ ,0-9]*[)]? *)'
+ r'(?P[<>|=]?)'
+ r'(?P[A-Za-z0-9.?]*(?:\[[a-zA-Z0-9,.]+\])?)')
+sep_re = re.compile(r'\s*,\s*')
+space_re = re.compile(r'\s+$')
+
+# astr is a string (perhaps comma separated)
+
+_convorder = {'=': _nbo}
+
+def _commastring(astr):
+ startindex = 0
+ result = []
+ islist = False
+ while startindex < len(astr):
+ mo = format_re.match(astr, pos=startindex)
+ try:
+ (order1, repeats, order2, dtype) = mo.groups()
+ except (TypeError, AttributeError):
+ raise ValueError(
+ f'format number {len(result) + 1} of "{astr}" is not recognized'
+ ) from None
+ startindex = mo.end()
+ # Separator or ending padding
+ if startindex < len(astr):
+ if space_re.match(astr, pos=startindex):
+ startindex = len(astr)
+ else:
+ mo = sep_re.match(astr, pos=startindex)
+ if not mo:
+ raise ValueError(
+ 'format number %d of "%s" is not recognized' %
+ (len(result) + 1, astr))
+ startindex = mo.end()
+ islist = True
+
+ if order2 == '':
+ order = order1
+ elif order1 == '':
+ order = order2
+ else:
+ order1 = _convorder.get(order1, order1)
+ order2 = _convorder.get(order2, order2)
+ if (order1 != order2):
+ raise ValueError(
+ f'inconsistent byte-order specification {order1} and {order2}')
+ order = order1
+
+ if order in ('|', '=', _nbo):
+ order = ''
+ dtype = order + dtype
+ if repeats == '':
+ newitem = dtype
+ else:
+ if (repeats[0] == "(" and repeats[-1] == ")"
+ and repeats[1:-1].strip() != ""
+ and "," not in repeats):
+ warnings.warn(
+ 'Passing in a parenthesized single number for repeats '
+ 'is deprecated; pass either a single number or indicate '
+ 'a tuple with a comma, like "(2,)".', DeprecationWarning,
+ stacklevel=2)
+ newitem = (dtype, ast.literal_eval(repeats))
+
+ result.append(newitem)
+
+ return result if islist else result[0]
+
+class dummy_ctype:
+
+ def __init__(self, cls):
+ self._cls = cls
+
+ def __mul__(self, other):
+ return self
+
+ def __call__(self, *other):
+ return self._cls(other)
+
+ def __eq__(self, other):
+ return self._cls == other._cls
+
+ def __ne__(self, other):
+ return self._cls != other._cls
+
+def _getintp_ctype():
+ val = _getintp_ctype.cache
+ if val is not None:
+ return val
+ if ctypes is None:
+ import numpy as np
+ val = dummy_ctype(np.intp)
+ else:
+ char = dtype('n').char
+ if char == 'i':
+ val = ctypes.c_int
+ elif char == 'l':
+ val = ctypes.c_long
+ elif char == 'q':
+ val = ctypes.c_longlong
+ else:
+ val = ctypes.c_long
+ _getintp_ctype.cache = val
+ return val
+
+
+_getintp_ctype.cache = None
+
+# Used for .ctypes attribute of ndarray
+
+class _missing_ctypes:
+ def cast(self, num, obj):
+ return num.value
+
+ class c_void_p:
+ def __init__(self, ptr):
+ self.value = ptr
+
+
+class _ctypes:
+ def __init__(self, array, ptr=None):
+ self._arr = array
+
+ if ctypes:
+ self._ctypes = ctypes
+ self._data = self._ctypes.c_void_p(ptr)
+ else:
+ # fake a pointer-like object that holds onto the reference
+ self._ctypes = _missing_ctypes()
+ self._data = self._ctypes.c_void_p(ptr)
+ self._data._objects = array
+
+ if self._arr.ndim == 0:
+ self._zerod = True
+ else:
+ self._zerod = False
+
+ def data_as(self, obj):
+ """
+ Return the data pointer cast to a particular c-types object.
+ For example, calling ``self._as_parameter_`` is equivalent to
+ ``self.data_as(ctypes.c_void_p)``. Perhaps you want to use
+ the data as a pointer to a ctypes array of floating-point data:
+ ``self.data_as(ctypes.POINTER(ctypes.c_double))``.
+
+ The returned pointer will keep a reference to the array.
+ """
+ # _ctypes.cast function causes a circular reference of self._data in
+ # self._data._objects. Attributes of self._data cannot be released
+ # until gc.collect is called. Make a copy of the pointer first then
+ # let it hold the array reference. This is a workaround to circumvent
+ # the CPython bug https://bugs.python.org/issue12836.
+ ptr = self._ctypes.cast(self._data, obj)
+ ptr._arr = self._arr
+ return ptr
+
+ def shape_as(self, obj):
+ """
+ Return the shape tuple as an array of some other c-types
+ type. For example: ``self.shape_as(ctypes.c_short)``.
+ """
+ if self._zerod:
+ return None
+ return (obj * self._arr.ndim)(*self._arr.shape)
+
+ def strides_as(self, obj):
+ """
+ Return the strides tuple as an array of some other
+ c-types type. For example: ``self.strides_as(ctypes.c_longlong)``.
+ """
+ if self._zerod:
+ return None
+ return (obj * self._arr.ndim)(*self._arr.strides)
+
+ @property
+ def data(self):
+ """
+ A pointer to the memory area of the array as a Python integer.
+ This memory area may contain data that is not aligned, or not in
+ correct byte-order. The memory area may not even be writeable.
+ The array flags and data-type of this array should be respected
+ when passing this attribute to arbitrary C-code to avoid trouble
+ that can include Python crashing. User Beware! The value of this
+ attribute is exactly the same as:
+ ``self._array_interface_['data'][0]``.
+
+ Note that unlike ``data_as``, a reference won't be kept to the array:
+ code like ``ctypes.c_void_p((a + b).ctypes.data)`` will result in a
+ pointer to a deallocated array, and should be spelt
+ ``(a + b).ctypes.data_as(ctypes.c_void_p)``
+ """
+ return self._data.value
+
+ @property
+ def shape(self):
+ """
+ (c_intp*self.ndim): A ctypes array of length self.ndim where
+ the basetype is the C-integer corresponding to ``dtype('p')`` on this
+ platform (see `~numpy.ctypeslib.c_intp`). This base-type could be
+ `ctypes.c_int`, `ctypes.c_long`, or `ctypes.c_longlong` depending on
+ the platform. The ctypes array contains the shape of
+ the underlying array.
+ """
+ return self.shape_as(_getintp_ctype())
+
+ @property
+ def strides(self):
+ """
+ (c_intp*self.ndim): A ctypes array of length self.ndim where
+ the basetype is the same as for the shape attribute. This ctypes
+ array contains the strides information from the underlying array.
+ This strides information is important for showing how many bytes
+ must be jumped to get to the next element in the array.
+ """
+ return self.strides_as(_getintp_ctype())
+
+ @property
+ def _as_parameter_(self):
+ """
+ Overrides the ctypes semi-magic method
+
+ Enables `c_func(some_array.ctypes)`
+ """
+ return self.data_as(ctypes.c_void_p)
+
+
+def _newnames(datatype, order):
+ """
+ Given a datatype and an order object, return a new names tuple, with the
+ order indicated
+ """
+ oldnames = datatype.names
+ nameslist = list(oldnames)
+ if isinstance(order, str):
+ order = [order]
+ seen = set()
+ if isinstance(order, (list, tuple)):
+ for name in order:
+ try:
+ nameslist.remove(name)
+ except ValueError:
+ if name in seen:
+ raise ValueError(f"duplicate field name: {name}") from None
+ else:
+ raise ValueError(f"unknown field name: {name}") from None
+ seen.add(name)
+ return tuple(list(order) + nameslist)
+ raise ValueError(f"unsupported order value: {order}")
+
+def _copy_fields(ary):
+ """Return copy of structured array with padding between fields removed.
+
+ Parameters
+ ----------
+ ary : ndarray
+ Structured array from which to remove padding bytes
+
+ Returns
+ -------
+ ary_copy : ndarray
+ Copy of ary with padding bytes removed
+ """
+ dt = ary.dtype
+ copy_dtype = {'names': dt.names,
+ 'formats': [dt.fields[name][0] for name in dt.names]}
+ return array(ary, dtype=copy_dtype, copy=True)
+
+def _promote_fields(dt1, dt2):
+ """ Perform type promotion for two structured dtypes.
+
+ Parameters
+ ----------
+ dt1 : structured dtype
+ First dtype.
+ dt2 : structured dtype
+ Second dtype.
+
+ Returns
+ -------
+ out : dtype
+ The promoted dtype
+
+ Notes
+ -----
+ If one of the inputs is aligned, the result will be. The titles of
+ both descriptors must match (point to the same field).
+ """
+ # Both must be structured and have the same names in the same order
+ if (dt1.names is None or dt2.names is None) or dt1.names != dt2.names:
+ raise DTypePromotionError(
+ f"field names `{dt1.names}` and `{dt2.names}` mismatch.")
+
+ # if both are identical, we can (maybe!) just return the same dtype.
+ identical = dt1 is dt2
+ new_fields = []
+ for name in dt1.names:
+ field1 = dt1.fields[name]
+ field2 = dt2.fields[name]
+ new_descr = promote_types(field1[0], field2[0])
+ identical = identical and new_descr is field1[0]
+
+ # Check that the titles match (if given):
+ if field1[2:] != field2[2:]:
+ raise DTypePromotionError(
+ f"field titles of field '{name}' mismatch")
+ if len(field1) == 2:
+ new_fields.append((name, new_descr))
+ else:
+ new_fields.append(((field1[2], name), new_descr))
+
+ res = dtype(new_fields, align=dt1.isalignedstruct or dt2.isalignedstruct)
+
+ # Might as well preserve identity (and metadata) if the dtype is identical
+ # and the itemsize, offsets are also unmodified. This could probably be
+ # sped up, but also probably just be removed entirely.
+ if identical and res.itemsize == dt1.itemsize:
+ for name in dt1.names:
+ if dt1.fields[name][1] != res.fields[name][1]:
+ return res # the dtype changed.
+ return dt1
+
+ return res
+
+
+def _getfield_is_safe(oldtype, newtype, offset):
+ """ Checks safety of getfield for object arrays.
+
+ As in _view_is_safe, we need to check that memory containing objects is not
+ reinterpreted as a non-object datatype and vice versa.
+
+ Parameters
+ ----------
+ oldtype : data-type
+ Data type of the original ndarray.
+ newtype : data-type
+ Data type of the field being accessed by ndarray.getfield
+ offset : int
+ Offset of the field being accessed by ndarray.getfield
+
+ Raises
+ ------
+ TypeError
+ If the field access is invalid
+
+ """
+ if newtype.hasobject or oldtype.hasobject:
+ if offset == 0 and newtype == oldtype:
+ return
+ if oldtype.names is not None:
+ for name in oldtype.names:
+ if (oldtype.fields[name][1] == offset and
+ oldtype.fields[name][0] == newtype):
+ return
+ raise TypeError("Cannot get/set field of an object array")
+ return
+
+def _view_is_safe(oldtype, newtype):
+ """ Checks safety of a view involving object arrays, for example when
+ doing::
+
+ np.zeros(10, dtype=oldtype).view(newtype)
+
+ Parameters
+ ----------
+ oldtype : data-type
+ Data type of original ndarray
+ newtype : data-type
+ Data type of the view
+
+ Raises
+ ------
+ TypeError
+ If the new type is incompatible with the old type.
+
+ """
+
+ # if the types are equivalent, there is no problem.
+ # for example: dtype((np.record, 'i4,i4')) == dtype((np.void, 'i4,i4'))
+ if oldtype == newtype:
+ return
+
+ if newtype.hasobject or oldtype.hasobject:
+ raise TypeError("Cannot change data-type for array of references.")
+ return
+
+
+# Given a string containing a PEP 3118 format specifier,
+# construct a NumPy dtype
+
+_pep3118_native_map = {
+ '?': '?',
+ 'c': 'S1',
+ 'b': 'b',
+ 'B': 'B',
+ 'h': 'h',
+ 'H': 'H',
+ 'i': 'i',
+ 'I': 'I',
+ 'l': 'l',
+ 'L': 'L',
+ 'q': 'q',
+ 'Q': 'Q',
+ 'e': 'e',
+ 'f': 'f',
+ 'd': 'd',
+ 'g': 'g',
+ 'Zf': 'F',
+ 'Zd': 'D',
+ 'Zg': 'G',
+ 's': 'S',
+ 'w': 'U',
+ 'O': 'O',
+ 'x': 'V', # padding
+}
+_pep3118_native_typechars = ''.join(_pep3118_native_map.keys())
+
+_pep3118_standard_map = {
+ '?': '?',
+ 'c': 'S1',
+ 'b': 'b',
+ 'B': 'B',
+ 'h': 'i2',
+ 'H': 'u2',
+ 'i': 'i4',
+ 'I': 'u4',
+ 'l': 'i4',
+ 'L': 'u4',
+ 'q': 'i8',
+ 'Q': 'u8',
+ 'e': 'f2',
+ 'f': 'f',
+ 'd': 'd',
+ 'Zf': 'F',
+ 'Zd': 'D',
+ 's': 'S',
+ 'w': 'U',
+ 'O': 'O',
+ 'x': 'V', # padding
+}
+_pep3118_standard_typechars = ''.join(_pep3118_standard_map.keys())
+
+_pep3118_unsupported_map = {
+ 'u': 'UCS-2 strings',
+ '&': 'pointers',
+ 't': 'bitfields',
+ 'X': 'function pointers',
+}
+
+class _Stream:
+ def __init__(self, s):
+ self.s = s
+ self.byteorder = '@'
+
+ def advance(self, n):
+ res = self.s[:n]
+ self.s = self.s[n:]
+ return res
+
+ def consume(self, c):
+ if self.s[:len(c)] == c:
+ self.advance(len(c))
+ return True
+ return False
+
+ def consume_until(self, c):
+ if callable(c):
+ i = 0
+ while i < len(self.s) and not c(self.s[i]):
+ i = i + 1
+ return self.advance(i)
+ else:
+ i = self.s.index(c)
+ res = self.advance(i)
+ self.advance(len(c))
+ return res
+
+ @property
+ def next(self):
+ return self.s[0]
+
+ def __bool__(self):
+ return bool(self.s)
+
+
+def _dtype_from_pep3118(spec):
+ stream = _Stream(spec)
+ dtype, align = __dtype_from_pep3118(stream, is_subdtype=False)
+ return dtype
+
+def __dtype_from_pep3118(stream, is_subdtype):
+ field_spec = {
+ 'names': [],
+ 'formats': [],
+ 'offsets': [],
+ 'itemsize': 0
+ }
+ offset = 0
+ common_alignment = 1
+ is_padding = False
+
+ # Parse spec
+ while stream:
+ value = None
+
+ # End of structure, bail out to upper level
+ if stream.consume('}'):
+ break
+
+ # Sub-arrays (1)
+ shape = None
+ if stream.consume('('):
+ shape = stream.consume_until(')')
+ shape = tuple(map(int, shape.split(',')))
+
+ # Byte order
+ if stream.next in ('@', '=', '<', '>', '^', '!'):
+ byteorder = stream.advance(1)
+ if byteorder == '!':
+ byteorder = '>'
+ stream.byteorder = byteorder
+
+ # Byte order characters also control native vs. standard type sizes
+ if stream.byteorder in ('@', '^'):
+ type_map = _pep3118_native_map
+ type_map_chars = _pep3118_native_typechars
+ else:
+ type_map = _pep3118_standard_map
+ type_map_chars = _pep3118_standard_typechars
+
+ # Item sizes
+ itemsize_str = stream.consume_until(lambda c: not c.isdigit())
+ if itemsize_str:
+ itemsize = int(itemsize_str)
+ else:
+ itemsize = 1
+
+ # Data types
+ is_padding = False
+
+ if stream.consume('T{'):
+ value, align = __dtype_from_pep3118(
+ stream, is_subdtype=True)
+ elif stream.next in type_map_chars:
+ if stream.next == 'Z':
+ typechar = stream.advance(2)
+ else:
+ typechar = stream.advance(1)
+
+ is_padding = (typechar == 'x')
+ dtypechar = type_map[typechar]
+ if dtypechar in 'USV':
+ dtypechar += '%d' % itemsize
+ itemsize = 1
+ numpy_byteorder = {'@': '=', '^': '='}.get(
+ stream.byteorder, stream.byteorder)
+ value = dtype(numpy_byteorder + dtypechar)
+ align = value.alignment
+ elif stream.next in _pep3118_unsupported_map:
+ desc = _pep3118_unsupported_map[stream.next]
+ raise NotImplementedError(
+ f"Unrepresentable PEP 3118 data type {stream.next!r} ({desc})")
+ else:
+ raise ValueError(
+ f"Unknown PEP 3118 data type specifier {stream.s!r}"
+ )
+
+ #
+ # Native alignment may require padding
+ #
+ # Here we assume that the presence of a '@' character implicitly
+ # implies that the start of the array is *already* aligned.
+ #
+ extra_offset = 0
+ if stream.byteorder == '@':
+ start_padding = (-offset) % align
+ intra_padding = (-value.itemsize) % align
+
+ offset += start_padding
+
+ if intra_padding != 0:
+ if itemsize > 1 or (shape is not None and _prod(shape) > 1):
+ # Inject internal padding to the end of the sub-item
+ value = _add_trailing_padding(value, intra_padding)
+ else:
+ # We can postpone the injection of internal padding,
+ # as the item appears at most once
+ extra_offset += intra_padding
+
+ # Update common alignment
+ common_alignment = _lcm(align, common_alignment)
+
+ # Convert itemsize to sub-array
+ if itemsize != 1:
+ value = dtype((value, (itemsize,)))
+
+ # Sub-arrays (2)
+ if shape is not None:
+ value = dtype((value, shape))
+
+ # Field name
+ if stream.consume(':'):
+ name = stream.consume_until(':')
+ else:
+ name = None
+
+ if not (is_padding and name is None):
+ if name is not None and name in field_spec['names']:
+ raise RuntimeError(
+ f"Duplicate field name '{name}' in PEP3118 format"
+ )
+ field_spec['names'].append(name)
+ field_spec['formats'].append(value)
+ field_spec['offsets'].append(offset)
+
+ offset += value.itemsize
+ offset += extra_offset
+
+ field_spec['itemsize'] = offset
+
+ # extra final padding for aligned types
+ if stream.byteorder == '@':
+ field_spec['itemsize'] += (-offset) % common_alignment
+
+ # Check if this was a simple 1-item type, and unwrap it
+ if (field_spec['names'] == [None]
+ and field_spec['offsets'][0] == 0
+ and field_spec['itemsize'] == field_spec['formats'][0].itemsize
+ and not is_subdtype):
+ ret = field_spec['formats'][0]
+ else:
+ _fix_names(field_spec)
+ ret = dtype(field_spec)
+
+ # Finished
+ return ret, common_alignment
+
+def _fix_names(field_spec):
+ """ Replace names which are None with the next unused f%d name """
+ names = field_spec['names']
+ for i, name in enumerate(names):
+ if name is not None:
+ continue
+
+ j = 0
+ while True:
+ name = f'f{j}'
+ if name not in names:
+ break
+ j = j + 1
+ names[i] = name
+
+def _add_trailing_padding(value, padding):
+ """Inject the specified number of padding bytes at the end of a dtype"""
+ if value.fields is None:
+ field_spec = {
+ 'names': ['f0'],
+ 'formats': [value],
+ 'offsets': [0],
+ 'itemsize': value.itemsize
+ }
+ else:
+ fields = value.fields
+ names = value.names
+ field_spec = {
+ 'names': names,
+ 'formats': [fields[name][0] for name in names],
+ 'offsets': [fields[name][1] for name in names],
+ 'itemsize': value.itemsize
+ }
+
+ field_spec['itemsize'] += padding
+ return dtype(field_spec)
+
+def _prod(a):
+ p = 1
+ for x in a:
+ p *= x
+ return p
+
+def _gcd(a, b):
+ """Calculate the greatest common divisor of a and b"""
+ if not (math.isfinite(a) and math.isfinite(b)):
+ raise ValueError('Can only find greatest common divisor of '
+ f'finite arguments, found "{a}" and "{b}"')
+ while b:
+ a, b = b, a % b
+ return a
+
+def _lcm(a, b):
+ return a // _gcd(a, b) * b
+
+def array_ufunc_errmsg_formatter(dummy, ufunc, method, *inputs, **kwargs):
+ """ Format the error message for when __array_ufunc__ gives up. """
+ args_string = ', '.join([f'{arg!r}' for arg in inputs] +
+ [f'{k}={v!r}'
+ for k, v in kwargs.items()])
+ args = inputs + kwargs.get('out', ())
+ types_string = ', '.join(repr(type(arg).__name__) for arg in args)
+ return ('operand type(s) all returned NotImplemented from '
+ f'__array_ufunc__({ufunc!r}, {method!r}, {args_string}): {types_string}'
+ )
+
+
+def array_function_errmsg_formatter(public_api, types):
+ """ Format the error message for when __array_ufunc__ gives up. """
+ func_name = f'{public_api.__module__}.{public_api.__name__}'
+ return (f"no implementation found for '{func_name}' on types that implement "
+ f'__array_function__: {list(types)}')
+
+
+def _ufunc_doc_signature_formatter(ufunc):
+ """
+ Builds a signature string which resembles PEP 457
+
+ This is used to construct the first line of the docstring
+
+ Keep in sync with `_ufunc_inspect_signature_builder`.
+ """
+
+ # input arguments are simple
+ if ufunc.nin == 1:
+ in_args = 'x'
+ else:
+ in_args = ', '.join(f'x{i + 1}' for i in range(ufunc.nin))
+
+ # output arguments are both keyword or positional
+ if ufunc.nout == 0:
+ out_args = ', /, out=()'
+ elif ufunc.nout == 1:
+ out_args = ', /, out=None'
+ else:
+ out_args = '[, {positional}], / [, out={default}]'.format(
+ positional=', '.join(
+ f'out{i + 1}' for i in range(ufunc.nout)),
+ default=repr((None,) * ufunc.nout)
+ )
+
+ # keyword only args depend on whether this is a gufunc
+ kwargs = (
+ ", casting='same_kind'"
+ ", order='K'"
+ ", dtype=None"
+ ", subok=True"
+ )
+
+ # NOTE: gufuncs may or may not support the `axis` parameter
+ if ufunc.signature is None:
+ kwargs = f", where=True{kwargs}[, signature]"
+ else:
+ kwargs += "[, signature, axes, axis]"
+
+ # join all the parts together
+ return f'{ufunc.__name__}({in_args}{out_args}, *{kwargs})'
+
+
+def _ufunc_inspect_signature_builder(ufunc):
+ """
+ Builds a ``__signature__`` string.
+
+ Should be kept in sync with `_ufunc_doc_signature_formatter`.
+ """
+
+ from inspect import Parameter, Signature
+
+ params = []
+
+ # positional-only input parameters
+ if ufunc.nin == 1:
+ params.append(Parameter("x", Parameter.POSITIONAL_ONLY))
+ else:
+ params.extend(
+ Parameter(f"x{i}", Parameter.POSITIONAL_ONLY)
+ for i in range(1, ufunc.nin + 1)
+ )
+
+ # for the sake of simplicity, we only consider a single output parameter
+ if ufunc.nout == 1:
+ out_default = None
+ else:
+ out_default = (None,) * ufunc.nout
+ params.append(
+ Parameter("out", Parameter.POSITIONAL_OR_KEYWORD, default=out_default),
+ )
+
+ if ufunc.signature is None:
+ params.append(Parameter("where", Parameter.KEYWORD_ONLY, default=True))
+ else:
+ # NOTE: not all gufuncs support the `axis` parameters
+ params.append(Parameter("axes", Parameter.KEYWORD_ONLY, default=_NoValue))
+ params.append(Parameter("axis", Parameter.KEYWORD_ONLY, default=_NoValue))
+ params.append(Parameter("keepdims", Parameter.KEYWORD_ONLY, default=False))
+
+ params.extend((
+ Parameter("casting", Parameter.KEYWORD_ONLY, default='same_kind'),
+ Parameter("order", Parameter.KEYWORD_ONLY, default='K'),
+ Parameter("dtype", Parameter.KEYWORD_ONLY, default=None),
+ Parameter("subok", Parameter.KEYWORD_ONLY, default=True),
+ Parameter("signature", Parameter.KEYWORD_ONLY, default=None),
+ ))
+
+ return Signature(params)
+
+
+def npy_ctypes_check(cls):
+ # determine if a class comes from ctypes, in order to work around
+ # a bug in the buffer protocol for those objects, bpo-10746
+ try:
+ # ctypes class are new-style, so have an __mro__. This probably fails
+ # for ctypes classes with multiple inheritance.
+ if IS_PYPY:
+ # (..., _ctypes.basics._CData, Bufferable, object)
+ ctype_base = cls.__mro__[-3]
+ else:
+ # # (..., _ctypes._CData, object)
+ ctype_base = cls.__mro__[-2]
+ # right now, they're part of the _ctypes module
+ return '_ctypes' in ctype_base.__module__
+ except Exception:
+ return False
+
+# used to handle the _NoValue default argument for na_object
+# in the C implementation of the __reduce__ method for stringdtype
+def _convert_to_stringdtype_kwargs(coerce, na_object=_NoValue):
+ if na_object is _NoValue:
+ return StringDType(coerce=coerce)
+ return StringDType(coerce=coerce, na_object=na_object)
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_internal.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_internal.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..6e37022ffd56401e2b50595a476c56740cfa1a57
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_internal.pyi
@@ -0,0 +1,61 @@
+import ctypes as ct
+import re
+from collections.abc import Callable, Iterable
+from typing import Any, Final, Generic, Self, overload
+from typing_extensions import TypeVar
+
+import numpy as np
+import numpy.typing as npt
+from numpy.ctypeslib import c_intp
+
+_CastT = TypeVar("_CastT", bound=ct._CanCastTo)
+_T_co = TypeVar("_T_co", covariant=True)
+_CT = TypeVar("_CT", bound=ct._CData)
+_PT_co = TypeVar("_PT_co", bound=int | None, default=None, covariant=True)
+
+###
+
+IS_PYPY: Final[bool] = ...
+
+format_re: Final[re.Pattern[str]] = ...
+sep_re: Final[re.Pattern[str]] = ...
+space_re: Final[re.Pattern[str]] = ...
+
+###
+
+# TODO: Let the likes of `shape_as` and `strides_as` return `None`
+# for 0D arrays once we've got shape-support
+
+class _ctypes(Generic[_PT_co]):
+ @overload
+ def __init__(self: _ctypes[None], /, array: npt.NDArray[Any], ptr: None = None) -> None: ...
+ @overload
+ def __init__(self, /, array: npt.NDArray[Any], ptr: _PT_co) -> None: ...
+
+ #
+ @property
+ def data(self) -> _PT_co: ...
+ @property
+ def shape(self) -> ct.Array[c_intp]: ...
+ @property
+ def strides(self) -> ct.Array[c_intp]: ...
+ @property
+ def _as_parameter_(self) -> ct.c_void_p: ...
+
+ #
+ def data_as(self, /, obj: type[_CastT]) -> _CastT: ...
+ def shape_as(self, /, obj: type[_CT]) -> ct.Array[_CT]: ...
+ def strides_as(self, /, obj: type[_CT]) -> ct.Array[_CT]: ...
+
+class dummy_ctype(Generic[_T_co]):
+ _cls: type[_T_co]
+
+ def __init__(self, /, cls: type[_T_co]) -> None: ...
+ def __eq__(self, other: Self, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
+ def __ne__(self, other: Self, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
+ def __mul__(self, other: object, /) -> Self: ...
+ def __call__(self, /, *other: object) -> _T_co: ...
+
+def array_ufunc_errmsg_formatter(dummy: object, ufunc: np.ufunc, method: str, *inputs: object, **kwargs: object) -> str: ...
+def array_function_errmsg_formatter(public_api: Callable[..., object], types: Iterable[str]) -> str: ...
+def npy_ctypes_check(cls: type) -> bool: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_methods.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_methods.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c29831bca209e63dc7e06a2d0f83fa986fc3f98
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_methods.py
@@ -0,0 +1,252 @@
+"""
+Array methods which are called by both the C-code for the method
+and the Python code for the NumPy-namespace function
+
+"""
+import os
+import pickle
+import warnings
+from contextlib import nullcontext
+
+import numpy as np
+from numpy._core import multiarray as mu, numerictypes as nt, umath as um
+from numpy._core.multiarray import asanyarray
+from numpy._globals import _NoValue
+
+# save those O(100) nanoseconds!
+bool_dt = mu.dtype("bool")
+umr_maximum = um.maximum.reduce
+umr_minimum = um.minimum.reduce
+umr_sum = um.add.reduce
+umr_prod = um.multiply.reduce
+umr_bitwise_count = um.bitwise_count
+umr_any = um.logical_or.reduce
+umr_all = um.logical_and.reduce
+
+# Complex types to -> (2,)float view for fast-path computation in _var()
+_complex_to_float = {
+ nt.dtype(nt.csingle): nt.dtype(nt.single),
+ nt.dtype(nt.cdouble): nt.dtype(nt.double),
+}
+# Special case for windows: ensure double takes precedence
+if nt.dtype(nt.longdouble) != nt.dtype(nt.double):
+ _complex_to_float.update({
+ nt.dtype(nt.clongdouble): nt.dtype(nt.longdouble),
+ })
+
+# avoid keyword arguments to speed up parsing, saves about 15%-20% for very
+# small reductions
+def _amax(a, axis=None, out=None, keepdims=False,
+ initial=_NoValue, where=True):
+ return umr_maximum(a, axis, None, out, keepdims, initial, where)
+
+def _amin(a, axis=None, out=None, keepdims=False,
+ initial=_NoValue, where=True):
+ return umr_minimum(a, axis, None, out, keepdims, initial, where)
+
+def _sum(a, axis=None, dtype=None, out=None, keepdims=False,
+ initial=_NoValue, where=True):
+ return umr_sum(a, axis, dtype, out, keepdims, initial, where)
+
+def _prod(a, axis=None, dtype=None, out=None, keepdims=False,
+ initial=_NoValue, where=True):
+ return umr_prod(a, axis, dtype, out, keepdims, initial, where)
+
+def _any(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
+ # By default, return a boolean for any and all
+ if dtype is None:
+ dtype = bool_dt
+ # Parsing keyword arguments is currently fairly slow, so avoid it for now
+ if where is True:
+ return umr_any(a, axis, dtype, out, keepdims)
+ return umr_any(a, axis, dtype, out, keepdims, where=where)
+
+def _all(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
+ # By default, return a boolean for any and all
+ if dtype is None:
+ dtype = bool_dt
+ # Parsing keyword arguments is currently fairly slow, so avoid it for now
+ if where is True:
+ return umr_all(a, axis, dtype, out, keepdims)
+ return umr_all(a, axis, dtype, out, keepdims, where=where)
+
+def _count_reduce_items(arr, axis, keepdims=False, where=True):
+ # fast-path for the default case
+ if where is True:
+ # no boolean mask given, calculate items according to axis
+ if axis is None:
+ axis = tuple(range(arr.ndim))
+ elif not isinstance(axis, tuple):
+ axis = (axis,)
+ items = 1
+ for ax in axis:
+ items *= arr.shape[mu.normalize_axis_index(ax, arr.ndim)]
+ items = nt.intp(items)
+ else:
+ # TODO: Optimize case when `where` is broadcast along a non-reduction
+ # axis and full sum is more excessive than needed.
+
+ # guarded to protect circular imports
+ from numpy.lib._stride_tricks_impl import broadcast_to
+ # count True values in (potentially broadcasted) boolean mask
+ items = umr_sum(broadcast_to(where, arr.shape), axis, nt.intp, None,
+ keepdims)
+ return items
+
+def _clip(a, min=None, max=None, out=None, **kwargs):
+ if a.dtype.kind in "iu":
+ # If min/max is a Python integer, deal with out-of-bound values here.
+ # (This enforces NEP 50 rules as no value based promotion is done.)
+ if type(min) is int and min <= np.iinfo(a.dtype).min:
+ min = None
+ if type(max) is int and max >= np.iinfo(a.dtype).max:
+ max = None
+
+ if min is None and max is None:
+ # return identity
+ return um.positive(a, out=out, **kwargs)
+ elif min is None:
+ return um.minimum(a, max, out=out, **kwargs)
+ elif max is None:
+ return um.maximum(a, min, out=out, **kwargs)
+ else:
+ return um.clip(a, min, max, out=out, **kwargs)
+
+def _mean(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
+ arr = asanyarray(a)
+
+ is_float16_result = False
+
+ rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
+ if rcount == 0 if where is True else umr_any(rcount == 0, axis=None):
+ warnings.warn("Mean of empty slice", RuntimeWarning, stacklevel=2)
+
+ # Cast bool, unsigned int, and int to float64 by default
+ if dtype is None:
+ if issubclass(arr.dtype.type, (nt.integer, nt.bool)):
+ dtype = mu.dtype('f8')
+ elif issubclass(arr.dtype.type, nt.float16):
+ dtype = mu.dtype('f4')
+ is_float16_result = True
+
+ ret = umr_sum(arr, axis, dtype, out, keepdims, where=where)
+ if isinstance(ret, mu.ndarray):
+ ret = um.true_divide(
+ ret, rcount, out=ret, casting='unsafe', subok=False)
+ if is_float16_result and out is None:
+ ret = arr.dtype.type(ret)
+ elif hasattr(ret, 'dtype'):
+ if is_float16_result:
+ ret = arr.dtype.type(ret / rcount)
+ else:
+ ret = ret.dtype.type(ret / rcount)
+ else:
+ ret = ret / rcount
+
+ return ret
+
+def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
+ where=True, mean=None):
+ arr = asanyarray(a)
+
+ rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
+ # Make this warning show up on top.
+ if ddof >= rcount if where is True else umr_any(ddof >= rcount, axis=None):
+ warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning,
+ stacklevel=2)
+
+ # Cast bool, unsigned int, and int to float64 by default
+ if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool)):
+ dtype = mu.dtype('f8')
+
+ if mean is not None:
+ arrmean = mean
+ else:
+ # Compute the mean.
+ # Note that if dtype is not of inexact type then arraymean will
+ # not be either.
+ arrmean = umr_sum(arr, axis, dtype, keepdims=True, where=where)
+ # The shape of rcount has to match arrmean to not change the shape of
+ # out in broadcasting. Otherwise, it cannot be stored back to arrmean.
+ if rcount.ndim == 0:
+ # fast-path for default case when where is True
+ div = rcount
+ else:
+ # matching rcount to arrmean when where is specified as array
+ div = rcount.reshape(arrmean.shape)
+ if isinstance(arrmean, mu.ndarray):
+ arrmean = um.true_divide(arrmean, div, out=arrmean,
+ casting='unsafe', subok=False)
+ elif hasattr(arrmean, "dtype"):
+ arrmean = arrmean.dtype.type(arrmean / rcount)
+ else:
+ arrmean = arrmean / rcount
+
+ # Compute sum of squared deviations from mean
+ # Note that x may not be inexact and that we need it to be an array,
+ # not a scalar.
+ x = um.subtract(arr, arrmean, out=...)
+ if issubclass(arr.dtype.type, (nt.floating, nt.integer)):
+ x = um.square(x, out=x)
+ # Fast-paths for built-in complex types
+ elif (_float_dtype := _complex_to_float.get(x.dtype)) is not None:
+ xv = x.view(dtype=(_float_dtype, (2,)))
+ um.square(xv, out=xv)
+ x = um.add(xv[..., 0], xv[..., 1], out=x.real)
+ # Most general case; includes handling object arrays containing imaginary
+ # numbers and complex types with non-native byteorder
+ else:
+ x = um.multiply(x, um.conjugate(x), out=x).real
+
+ ret = umr_sum(x, axis, dtype, out, keepdims=keepdims, where=where)
+
+ # Compute degrees of freedom and make sure it is not negative.
+ rcount = um.maximum(rcount - ddof, 0)
+
+ # divide by degrees of freedom
+ if isinstance(ret, mu.ndarray):
+ ret = um.true_divide(
+ ret, rcount, out=ret, casting='unsafe', subok=False)
+ elif hasattr(ret, 'dtype'):
+ ret = ret.dtype.type(ret / rcount)
+ else:
+ ret = ret / rcount
+
+ return ret
+
+def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
+ where=True, mean=None):
+ ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
+ keepdims=keepdims, where=where, mean=mean)
+
+ if isinstance(ret, mu.ndarray):
+ ret = um.sqrt(ret, out=ret)
+ elif hasattr(ret, 'dtype'):
+ ret = ret.dtype.type(um.sqrt(ret))
+ else:
+ ret = um.sqrt(ret)
+
+ return ret
+
+def _ptp(a, axis=None, out=None, keepdims=False):
+ return um.subtract(
+ umr_maximum(a, axis, None, out, keepdims),
+ umr_minimum(a, axis, None, None, keepdims),
+ out
+ )
+
+def _dump(self, file, protocol=2):
+ if hasattr(file, 'write'):
+ ctx = nullcontext(file)
+ else:
+ ctx = open(os.fspath(file), "wb")
+ with ctx as f:
+ pickle.dump(self, f, protocol=protocol)
+
+def _dumps(self, protocol=2):
+ return pickle.dumps(self, protocol=protocol)
+
+def _bitwise_count(a, out=None, *, where=True, casting='same_kind',
+ order='K', dtype=None, subok=True):
+ return umr_bitwise_count(a, out, where=where, casting=casting,
+ order=order, dtype=dtype, subok=subok)
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_methods.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_methods.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..3c80683f003b8e63040804bbcadcce3c4e3a9444
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_methods.pyi
@@ -0,0 +1,22 @@
+from collections.abc import Callable
+from typing import Any, Concatenate, TypeAlias
+
+import numpy as np
+
+from . import _exceptions as _exceptions
+
+###
+
+_Reduce2: TypeAlias = Callable[Concatenate[object, ...], Any]
+
+###
+
+bool_dt: np.dtype[np.bool] = ...
+umr_maximum: _Reduce2 = ...
+umr_minimum: _Reduce2 = ...
+umr_sum: _Reduce2 = ...
+umr_prod: _Reduce2 = ...
+umr_bitwise_count = np.bitwise_count
+umr_any: _Reduce2 = ...
+umr_all: _Reduce2 = ...
+_complex_to_float: dict[np.dtype[np.complexfloating], np.dtype[np.floating]] = ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_operand_flag_tests.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_operand_flag_tests.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ae9df607bc25e04b1fc2d05967246e348de35c09
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_operand_flag_tests.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_rational_tests.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_rational_tests.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..6bb5030127954882796dad222472d9747890feaa
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_rational_tests.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_simd.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_simd.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..0ba7d78eeb87509322a0971f7d3eeeec8c8f3b6d
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_simd.pyi
@@ -0,0 +1,35 @@
+from types import ModuleType
+from typing import TypedDict, type_check_only
+
+# NOTE: these 5 are only defined on systems with an intel processor
+SSE42: ModuleType | None = ...
+FMA3: ModuleType | None = ...
+AVX2: ModuleType | None = ...
+AVX512F: ModuleType | None = ...
+AVX512_SKX: ModuleType | None = ...
+
+# NOTE: these 2 are only defined on systems with an arm processor
+ASIMD: ModuleType | None = ...
+NEON: ModuleType | None = ...
+
+# NOTE: This is only defined on systems with an riscv64 processor.
+RVV: ModuleType | None = ...
+
+baseline: ModuleType | None = ...
+
+@type_check_only
+class SimdTargets(TypedDict):
+ SSE42: ModuleType | None
+ AVX2: ModuleType | None
+ FMA3: ModuleType | None
+ AVX512F: ModuleType | None
+ AVX512_SKX: ModuleType | None
+ ASIMD: ModuleType | None
+ NEON: ModuleType | None
+ RVV: ModuleType | None
+ baseline: ModuleType | None
+
+targets: SimdTargets = ...
+
+def clear_floatstatus() -> None: ...
+def get_floatstatus() -> int: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_string_helpers.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_string_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..87085d4119dd56981f835dd97cc303fc04284da4
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_string_helpers.py
@@ -0,0 +1,100 @@
+"""
+String-handling utilities to avoid locale-dependence.
+
+Used primarily to generate type name aliases.
+"""
+# "import string" is costly to import!
+# Construct the translation tables directly
+# "A" = chr(65), "a" = chr(97)
+_all_chars = tuple(map(chr, range(256)))
+_ascii_upper = _all_chars[65:65 + 26]
+_ascii_lower = _all_chars[97:97 + 26]
+LOWER_TABLE = _all_chars[:65] + _ascii_lower + _all_chars[65 + 26:]
+UPPER_TABLE = _all_chars[:97] + _ascii_upper + _all_chars[97 + 26:]
+
+
+def english_lower(s):
+ """ Apply English case rules to convert ASCII strings to all lower case.
+
+ This is an internal utility function to replace calls to str.lower() such
+ that we can avoid changing behavior with changing locales. In particular,
+ Turkish has distinct dotted and dotless variants of the Latin letter "I" in
+ both lowercase and uppercase. Thus, "I".lower() != "i" in a "tr" locale.
+
+ Parameters
+ ----------
+ s : str
+
+ Returns
+ -------
+ lowered : str
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import english_lower
+ >>> english_lower('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_')
+ 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789_'
+ >>> english_lower('')
+ ''
+ """
+ lowered = s.translate(LOWER_TABLE)
+ return lowered
+
+
+def english_upper(s):
+ """ Apply English case rules to convert ASCII strings to all upper case.
+
+ This is an internal utility function to replace calls to str.upper() such
+ that we can avoid changing behavior with changing locales. In particular,
+ Turkish has distinct dotted and dotless variants of the Latin letter "I" in
+ both lowercase and uppercase. Thus, "i".upper() != "I" in a "tr" locale.
+
+ Parameters
+ ----------
+ s : str
+
+ Returns
+ -------
+ uppered : str
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import english_upper
+ >>> english_upper('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_')
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
+ >>> english_upper('')
+ ''
+ """
+ uppered = s.translate(UPPER_TABLE)
+ return uppered
+
+
+def english_capitalize(s):
+ """ Apply English case rules to convert the first character of an ASCII
+ string to upper case.
+
+ This is an internal utility function to replace calls to str.capitalize()
+ such that we can avoid changing behavior with changing locales.
+
+ Parameters
+ ----------
+ s : str
+
+ Returns
+ -------
+ capitalized : str
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import english_capitalize
+ >>> english_capitalize('int8')
+ 'Int8'
+ >>> english_capitalize('Int8')
+ 'Int8'
+ >>> english_capitalize('')
+ ''
+ """
+ if s:
+ return english_upper(s[0]) + s[1:]
+ else:
+ return s
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_string_helpers.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_string_helpers.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..6a85832b7a930edf28cf414e1f7801e6a3d94605
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_string_helpers.pyi
@@ -0,0 +1,12 @@
+from typing import Final
+
+_all_chars: Final[tuple[str, ...]] = ...
+_ascii_upper: Final[tuple[str, ...]] = ...
+_ascii_lower: Final[tuple[str, ...]] = ...
+
+LOWER_TABLE: Final[tuple[str, ...]] = ...
+UPPER_TABLE: Final[tuple[str, ...]] = ...
+
+def english_lower(s: str) -> str: ...
+def english_upper(s: str) -> str: ...
+def english_capitalize(s: str) -> str: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_struct_ufunc_tests.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_struct_ufunc_tests.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..3dcc56829864332aad38113eb1b74bcfaf454372
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_struct_ufunc_tests.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_type_aliases.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_type_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..51c8e6ca26779706ad414c5f78071e67c22a55a5
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_type_aliases.py
@@ -0,0 +1,131 @@
+"""
+Due to compatibility, numpy has a very large number of different naming
+conventions for the scalar types (those subclassing from `numpy.generic`).
+This file produces a convoluted set of dictionaries mapping names to types,
+and sometimes other mappings too.
+
+.. data:: allTypes
+ A dictionary of names to types that will be exposed as attributes through
+ ``np._core.numerictypes.*``
+
+.. data:: sctypeDict
+ Similar to `allTypes`, but maps a broader set of aliases to their types.
+
+.. data:: sctypes
+ A dictionary keyed by a "type group" string, providing a list of types
+ under that group.
+
+"""
+
+import numpy._core.multiarray as ma
+from numpy._core.multiarray import dtype, typeinfo
+
+######################################
+# Building `sctypeDict` and `allTypes`
+######################################
+
+sctypeDict = {}
+allTypes = {}
+c_names_dict = {}
+
+_abstract_type_names = {
+ "generic", "integer", "inexact", "floating", "number",
+ "flexible", "character", "complexfloating", "unsignedinteger",
+ "signedinteger"
+}
+
+for _abstract_type_name in _abstract_type_names:
+ allTypes[_abstract_type_name] = getattr(ma, _abstract_type_name)
+ del _abstract_type_name
+
+for k, v in typeinfo.items():
+ if k.startswith("NPY_") and v not in c_names_dict:
+ c_names_dict[k[4:]] = v
+ else:
+ concrete_type = v.type
+ allTypes[k] = concrete_type
+ sctypeDict[k] = concrete_type
+ del concrete_type
+ del k, v
+
+_aliases = {
+ "double": "float64",
+ "cdouble": "complex128",
+ "single": "float32",
+ "csingle": "complex64",
+ "half": "float16",
+ "bool_": "bool",
+ # Default integer:
+ "int_": "intp",
+ "uint": "uintp",
+}
+
+for k, v in _aliases.items():
+ sctypeDict[k] = allTypes[v]
+ allTypes[k] = allTypes[v]
+ del k, v
+
+# extra aliases are added only to `sctypeDict`
+# to support dtype name access, such as`np.dtype("float")`
+_extra_aliases = {
+ "float": "float64",
+ "complex": "complex128",
+ "object": "object_",
+ "bytes": "bytes_",
+ "a": "bytes_",
+ "int": "int_",
+ "str": "str_",
+ "unicode": "str_",
+}
+
+for k, v in _extra_aliases.items():
+ sctypeDict[k] = allTypes[v]
+ del k, v
+
+# include extended precision sized aliases
+for is_complex, full_name in [(False, "longdouble"), (True, "clongdouble")]:
+ longdouble_type = allTypes[full_name]
+
+ bits = dtype(longdouble_type).itemsize * 8
+ base_name = "complex" if is_complex else "float"
+ extended_prec_name = f"{base_name}{bits}"
+ if extended_prec_name not in allTypes:
+ sctypeDict[extended_prec_name] = longdouble_type
+ allTypes[extended_prec_name] = longdouble_type
+
+ del is_complex, full_name, longdouble_type, bits, base_name, extended_prec_name
+
+
+####################
+# Building `sctypes`
+####################
+
+sctypes = {"int": set(), "uint": set(), "float": set(),
+ "complex": set(), "others": set()}
+
+for type_info in typeinfo.values():
+ if type_info.kind in ["M", "m"]: # exclude timedelta and datetime
+ continue
+
+ concrete_type = type_info.type
+
+ # find proper group for each concrete type
+ for type_group, abstract_type in [
+ ("int", ma.signedinteger), ("uint", ma.unsignedinteger),
+ ("float", ma.floating), ("complex", ma.complexfloating),
+ ("others", ma.generic)
+ ]:
+ if issubclass(concrete_type, abstract_type):
+ sctypes[type_group].add(concrete_type)
+ del type_group, abstract_type
+ break
+
+ del type_info, concrete_type
+
+# sort sctype groups by bitsize
+for sctype_key in sctypes.keys():
+ sctype_list = list(sctypes[sctype_key])
+ sctype_list.sort(key=lambda x: dtype(x).itemsize)
+ sctypes[sctype_key] = sctype_list
+
+ del sctype_key, sctype_list
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_type_aliases.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_type_aliases.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e28541cc89875dc46294a6e6eb4df4c0f7dd8d63
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_type_aliases.pyi
@@ -0,0 +1,86 @@
+from collections.abc import Collection
+from typing import Final, Literal as L, TypeAlias, TypedDict, type_check_only
+
+import numpy as np
+
+sctypeDict: Final[dict[str, type[np.generic]]]
+allTypes: Final[dict[str, type[np.generic]]]
+
+@type_check_only
+class _CNamesDict(TypedDict):
+ BOOL: np.dtype[np.bool]
+ HALF: np.dtype[np.half]
+ FLOAT: np.dtype[np.single]
+ DOUBLE: np.dtype[np.double]
+ LONGDOUBLE: np.dtype[np.longdouble]
+ CFLOAT: np.dtype[np.csingle]
+ CDOUBLE: np.dtype[np.cdouble]
+ CLONGDOUBLE: np.dtype[np.clongdouble]
+ STRING: np.dtype[np.bytes_]
+ UNICODE: np.dtype[np.str_]
+ VOID: np.dtype[np.void]
+ OBJECT: np.dtype[np.object_]
+ DATETIME: np.dtype[np.datetime64]
+ TIMEDELTA: np.dtype[np.timedelta64]
+ BYTE: np.dtype[np.byte]
+ UBYTE: np.dtype[np.ubyte]
+ SHORT: np.dtype[np.short]
+ USHORT: np.dtype[np.ushort]
+ INT: np.dtype[np.intc]
+ UINT: np.dtype[np.uintc]
+ LONG: np.dtype[np.long]
+ ULONG: np.dtype[np.ulong]
+ LONGLONG: np.dtype[np.longlong]
+ ULONGLONG: np.dtype[np.ulonglong]
+
+c_names_dict: Final[_CNamesDict]
+
+_AbstractTypeName: TypeAlias = L[
+ "generic",
+ "flexible",
+ "character",
+ "number",
+ "integer",
+ "inexact",
+ "unsignedinteger",
+ "signedinteger",
+ "floating",
+ "complexfloating",
+]
+_abstract_type_names: Final[set[_AbstractTypeName]]
+
+@type_check_only
+class _AliasesType(TypedDict):
+ double: L["float64"]
+ cdouble: L["complex128"]
+ single: L["float32"]
+ csingle: L["complex64"]
+ half: L["float16"]
+ bool_: L["bool"]
+ int_: L["intp"]
+ uint: L["intp"]
+
+_aliases: Final[_AliasesType]
+
+@type_check_only
+class _ExtraAliasesType(TypedDict):
+ float: L["float64"]
+ complex: L["complex128"]
+ object: L["object_"]
+ bytes: L["bytes_"]
+ a: L["bytes_"]
+ int: L["int_"]
+ str: L["str_"]
+ unicode: L["str_"]
+
+_extra_aliases: Final[_ExtraAliasesType]
+
+@type_check_only
+class _SCTypes(TypedDict):
+ int: Collection[type[np.signedinteger]]
+ uint: Collection[type[np.unsignedinteger]]
+ float: Collection[type[np.floating]]
+ complex: Collection[type[np.complexfloating]]
+ others: Collection[type[np.flexible | np.bool | np.object_]]
+
+sctypes: Final[_SCTypes]
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_ufunc_config.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_ufunc_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a7476670d9511e0dbf0c9304b378f1064dfbbb0
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_ufunc_config.py
@@ -0,0 +1,515 @@
+"""
+Functions for changing global ufunc configuration
+
+This provides helpers which wrap `_get_extobj_dict` and `_make_extobj`, and
+`_extobj_contextvar` from umath.
+"""
+import functools
+
+from numpy._utils import set_module
+
+from .umath import _extobj_contextvar, _get_extobj_dict, _make_extobj
+
+__all__ = [
+ "seterr", "geterr", "setbufsize", "getbufsize", "seterrcall", "geterrcall",
+ "errstate"
+]
+
+
+@set_module('numpy')
+def seterr(all=None, divide=None, over=None, under=None, invalid=None):
+ """
+ Set how floating-point errors are handled.
+
+ Note that operations on integer scalar types (such as `int16`) are
+ handled like floating point, and are affected by these settings.
+
+ Parameters
+ ----------
+ all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
+ Set treatment for all types of floating-point errors at once:
+
+ - ignore: Take no action when the exception occurs.
+ - warn: Print a :exc:`RuntimeWarning` (via the Python `warnings`
+ module).
+ - raise: Raise a :exc:`FloatingPointError`.
+ - call: Call a function specified using the `seterrcall` function.
+ - print: Print a warning directly to ``stdout``.
+ - log: Record error in a Log object specified by `seterrcall`.
+
+ The default is not to change the current behavior.
+ divide : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
+ Treatment for division by zero.
+ over : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
+ Treatment for floating-point overflow.
+ under : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
+ Treatment for floating-point underflow.
+ invalid : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
+ Treatment for invalid floating-point operation.
+
+ Returns
+ -------
+ old_settings : dict
+ Dictionary containing the old settings.
+
+ See also
+ --------
+ seterrcall : Set a callback function for the 'call' mode.
+ geterr, geterrcall, errstate
+
+
+ Notes
+ -----
+ The floating-point exceptions are defined in the IEEE 754 standard [1]_:
+
+ - Division by zero: infinite result obtained from finite numbers.
+ - Overflow: result too large to be expressed.
+ - Underflow: result so close to zero that some precision
+ was lost.
+ - Invalid operation: result is not an expressible number, typically
+ indicates that a NaN was produced.
+
+ **Concurrency note:** see :ref:`fp_error_handling`
+
+ .. [1] https://en.wikipedia.org/wiki/IEEE_754
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> orig_settings = np.seterr(all='ignore') # seterr to known value
+ >>> np.int16(32000) * np.int16(3)
+ np.int16(30464)
+ >>> np.seterr(over='raise')
+ {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
+ >>> old_settings = np.seterr(all='warn', over='raise')
+ >>> np.int16(32000) * np.int16(3)
+ Traceback (most recent call last):
+ File "", line 1, in
+ FloatingPointError: overflow encountered in scalar multiply
+
+ >>> old_settings = np.seterr(all='print')
+ >>> np.geterr()
+ {'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'}
+ >>> np.int16(32000) * np.int16(3)
+ np.int16(30464)
+ >>> np.seterr(**orig_settings) # restore original
+ {'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'}
+
+ """
+
+ old = _get_extobj_dict()
+ # The errstate doesn't include call and bufsize, so pop them:
+ old.pop("call", None)
+ old.pop("bufsize", None)
+
+ extobj = _make_extobj(
+ all=all, divide=divide, over=over, under=under, invalid=invalid)
+ _extobj_contextvar.set(extobj)
+ return old
+
+
+@set_module('numpy')
+def geterr():
+ """
+ Get the current way of handling floating-point errors.
+
+ Returns
+ -------
+ res : dict
+ A dictionary with keys "divide", "over", "under", and "invalid",
+ whose values are from the strings "ignore", "print", "log", "warn",
+ "raise", and "call". The keys represent possible floating-point
+ exceptions, and the values define how these exceptions are handled.
+
+ See Also
+ --------
+ geterrcall, seterr, seterrcall
+
+ Notes
+ -----
+ For complete documentation of the types of floating-point exceptions and
+ treatment options, see `seterr`.
+
+ **Concurrency note:** see :doc:`/reference/routines.err`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.geterr()
+ {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
+ >>> np.arange(3.) / np.arange(3.) # doctest: +SKIP
+ array([nan, 1., 1.])
+ RuntimeWarning: invalid value encountered in divide
+
+ >>> oldsettings = np.seterr(all='warn', invalid='raise')
+ >>> np.geterr()
+ {'divide': 'warn', 'over': 'warn', 'under': 'warn', 'invalid': 'raise'}
+ >>> np.arange(3.) / np.arange(3.)
+ Traceback (most recent call last):
+ ...
+ FloatingPointError: invalid value encountered in divide
+ >>> oldsettings = np.seterr(**oldsettings) # restore original
+
+ """
+ res = _get_extobj_dict()
+ # The "geterr" doesn't include call and bufsize,:
+ res.pop("call", None)
+ res.pop("bufsize", None)
+ return res
+
+
+@set_module('numpy')
+def setbufsize(size):
+ """
+ Set the size of the buffer used in ufuncs.
+
+ .. versionchanged:: 2.0
+ The scope of setting the buffer is tied to the `numpy.errstate`
+ context. Exiting a ``with errstate():`` will also restore the bufsize.
+
+ Parameters
+ ----------
+ size : int
+ Size of buffer.
+
+ Returns
+ -------
+ bufsize : int
+ Previous size of ufunc buffer in bytes.
+
+ Notes
+ -----
+ **Concurrency note:** see :doc:`/reference/routines.err`
+
+ Examples
+ --------
+ When exiting a `numpy.errstate` context manager the bufsize is restored:
+
+ >>> import numpy as np
+ >>> with np.errstate():
+ ... np.setbufsize(4096)
+ ... print(np.getbufsize())
+ ...
+ 8192
+ 4096
+ >>> np.getbufsize()
+ 8192
+
+ """
+ if size < 0:
+ raise ValueError("buffer size must be non-negative")
+ old = _get_extobj_dict()["bufsize"]
+ extobj = _make_extobj(bufsize=size)
+ _extobj_contextvar.set(extobj)
+ return old
+
+
+@set_module('numpy')
+def getbufsize():
+ """
+ Return the size of the buffer used in ufuncs.
+
+ Returns
+ -------
+ getbufsize : int
+ Size of ufunc buffer in bytes.
+
+ Notes
+ -----
+
+ **Concurrency note:** see :doc:`/reference/routines.err`
+
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.getbufsize()
+ 8192
+
+ """
+ return _get_extobj_dict()["bufsize"]
+
+
+@set_module('numpy')
+def seterrcall(func):
+ """
+ Set the floating-point error callback function or log object.
+
+ There are two ways to capture floating-point error messages. The first
+ is to set the error-handler to 'call', using `seterr`. Then, set
+ the function to call using this function.
+
+ The second is to set the error-handler to 'log', using `seterr`.
+ Floating-point errors then trigger a call to the 'write' method of
+ the provided object.
+
+ Parameters
+ ----------
+ func : callable f(err, flag) or object with write method
+ Function to call upon floating-point errors ('call'-mode) or
+ object whose 'write' method is used to log such message ('log'-mode).
+
+ The call function takes two arguments. The first is a string describing
+ the type of error (such as "divide by zero", "overflow", "underflow",
+ or "invalid value"), and the second is the status flag. The flag is a
+ byte, whose four least-significant bits indicate the type of error, one
+ of "divide", "over", "under", "invalid"::
+
+ [0 0 0 0 divide over under invalid]
+
+ In other words, ``flags = divide + 2*over + 4*under + 8*invalid``.
+
+ If an object is provided, its write method should take one argument,
+ a string.
+
+ Returns
+ -------
+ h : callable, log instance or None
+ The old error handler.
+
+ See Also
+ --------
+ seterr, geterr, geterrcall
+
+ Notes
+ -----
+
+ **Concurrency note:** see :doc:`/reference/routines.err`
+
+ Examples
+ --------
+ Callback upon error:
+
+ >>> def err_handler(type, flag):
+ ... print("Floating point error (%s), with flag %s" % (type, flag))
+ ...
+
+ >>> import numpy as np
+
+ >>> orig_handler = np.seterrcall(err_handler)
+ >>> orig_err = np.seterr(all='call')
+
+ >>> np.array([1, 2, 3]) / 0.0
+ Floating point error (divide by zero), with flag 1
+ array([inf, inf, inf])
+
+ >>> np.seterrcall(orig_handler)
+
+ >>> np.seterr(**orig_err)
+ {'divide': 'call', 'over': 'call', 'under': 'call', 'invalid': 'call'}
+
+ Log error message:
+
+ >>> class Log:
+ ... def write(self, msg):
+ ... print("LOG: %s" % msg)
+ ...
+
+ >>> log = Log()
+ >>> saved_handler = np.seterrcall(log)
+ >>> save_err = np.seterr(all='log')
+
+ >>> np.array([1, 2, 3]) / 0.0
+ LOG: Warning: divide by zero encountered in divide
+ array([inf, inf, inf])
+
+ >>> np.seterrcall(orig_handler)
+
+ >>> np.seterr(**orig_err)
+ {'divide': 'log', 'over': 'log', 'under': 'log', 'invalid': 'log'}
+
+ """
+ old = _get_extobj_dict()["call"]
+ extobj = _make_extobj(call=func)
+ _extobj_contextvar.set(extobj)
+ return old
+
+
+@set_module('numpy')
+def geterrcall():
+ """
+ Return the current callback function used on floating-point errors.
+
+ When the error handling for a floating-point error (one of "divide",
+ "over", "under", or "invalid") is set to 'call' or 'log', the function
+ that is called or the log instance that is written to is returned by
+ `geterrcall`. This function or log instance has been set with
+ `seterrcall`.
+
+ Returns
+ -------
+ errobj : callable, log instance or None
+ The current error handler. If no handler was set through `seterrcall`,
+ ``None`` is returned.
+
+ See Also
+ --------
+ seterrcall, seterr, geterr
+
+ Notes
+ -----
+ For complete documentation of the types of floating-point exceptions and
+ treatment options, see `seterr`.
+
+ **Concurrency note:** see :ref:`fp_error_handling`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.geterrcall() # we did not yet set a handler, returns None
+
+ >>> orig_settings = np.seterr(all='call')
+ >>> def err_handler(type, flag):
+ ... print("Floating point error (%s), with flag %s" % (type, flag))
+ >>> old_handler = np.seterrcall(err_handler)
+ >>> np.array([1, 2, 3]) / 0.0
+ Floating point error (divide by zero), with flag 1
+ array([inf, inf, inf])
+
+ >>> cur_handler = np.geterrcall()
+ >>> cur_handler is err_handler
+ True
+ >>> old_settings = np.seterr(**orig_settings) # restore original
+ >>> old_handler = np.seterrcall(None) # restore original
+
+ """
+ return _get_extobj_dict()["call"]
+
+
+class _unspecified:
+ pass
+
+
+_Unspecified = _unspecified()
+
+
+@set_module('numpy')
+class errstate:
+ """
+ errstate(**kwargs)
+
+ Context manager for floating-point error handling.
+
+ Using an instance of `errstate` as a context manager allows statements in
+ that context to execute with a known error handling behavior. Upon entering
+ the context the error handling is set with `seterr` and `seterrcall`, and
+ upon exiting it is reset to what it was before.
+
+ .. versionchanged:: 1.17.0
+ `errstate` is also usable as a function decorator, saving
+ a level of indentation if an entire function is wrapped.
+
+ .. versionchanged:: 2.0
+ `errstate` is now fully thread and asyncio safe, but may not be
+ entered more than once.
+ It is not safe to decorate async functions using ``errstate``.
+
+ Parameters
+ ----------
+ kwargs : {divide, over, under, invalid}
+ Keyword arguments. The valid keywords are the possible floating-point
+ exceptions. Each keyword should have a string value that defines the
+ treatment for the particular error. Possible values are
+ {'ignore', 'warn', 'raise', 'call', 'print', 'log'}.
+
+ See Also
+ --------
+ seterr, geterr, seterrcall, geterrcall
+
+ Notes
+ -----
+ For complete documentation of the types of floating-point exceptions and
+ treatment options, see `seterr`.
+
+ **Concurrency note:** see :ref:`fp_error_handling`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> olderr = np.seterr(all='ignore') # Set error handling to known state.
+
+ >>> np.arange(3) / 0.
+ array([nan, inf, inf])
+ >>> with np.errstate(divide='ignore'):
+ ... np.arange(3) / 0.
+ array([nan, inf, inf])
+
+ >>> np.sqrt(-1)
+ np.float64(nan)
+ >>> with np.errstate(invalid='raise'):
+ ... np.sqrt(-1)
+ Traceback (most recent call last):
+ File "", line 2, in
+ FloatingPointError: invalid value encountered in sqrt
+
+ Outside the context the error handling behavior has not changed:
+
+ >>> np.geterr()
+ {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
+ >>> olderr = np.seterr(**olderr) # restore original state
+
+ """
+ __slots__ = (
+ "_all",
+ "_call",
+ "_divide",
+ "_invalid",
+ "_over",
+ "_token",
+ "_under",
+ )
+
+ def __init__(self, *, call=_Unspecified,
+ all=None, divide=None, over=None, under=None, invalid=None):
+ self._token = None
+ self._call = call
+ self._all = all
+ self._divide = divide
+ self._over = over
+ self._under = under
+ self._invalid = invalid
+
+ def __enter__(self):
+ # Note that __call__ duplicates much of this logic
+ if self._token is not None:
+ raise TypeError("Cannot enter `np.errstate` twice.")
+ if self._call is _Unspecified:
+ extobj = _make_extobj(
+ all=self._all, divide=self._divide, over=self._over,
+ under=self._under, invalid=self._invalid)
+ else:
+ extobj = _make_extobj(
+ call=self._call,
+ all=self._all, divide=self._divide, over=self._over,
+ under=self._under, invalid=self._invalid)
+
+ self._token = _extobj_contextvar.set(extobj)
+
+ def __exit__(self, *exc_info):
+ _extobj_contextvar.reset(self._token)
+
+ def __call__(self, func):
+ # We need to customize `__call__` compared to `ContextDecorator`
+ # because we must store the token per-thread so cannot store it on
+ # the instance (we could create a new instance for this).
+ # This duplicates the code from `__enter__`.
+ @functools.wraps(func)
+ def inner(*args, **kwargs):
+ if self._call is _Unspecified:
+ extobj = _make_extobj(
+ all=self._all, divide=self._divide, over=self._over,
+ under=self._under, invalid=self._invalid)
+ else:
+ extobj = _make_extobj(
+ call=self._call,
+ all=self._all, divide=self._divide, over=self._over,
+ under=self._under, invalid=self._invalid)
+
+ _token = _extobj_contextvar.set(extobj)
+ try:
+ # Call the original, decorated, function:
+ return func(*args, **kwargs)
+ finally:
+ _extobj_contextvar.reset(_token)
+
+ return inner
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_ufunc_config.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_ufunc_config.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..f1f0d88fe1658a232660cd268226894d333f8786
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_ufunc_config.pyi
@@ -0,0 +1,69 @@
+from _typeshed import SupportsWrite
+from collections.abc import Callable
+from types import TracebackType
+from typing import Any, Final, Literal, TypeAlias, TypedDict, TypeVar, type_check_only
+
+__all__ = [
+ "seterr",
+ "geterr",
+ "setbufsize",
+ "getbufsize",
+ "seterrcall",
+ "geterrcall",
+ "errstate",
+]
+
+_ErrKind: TypeAlias = Literal["ignore", "warn", "raise", "call", "print", "log"]
+_ErrCall: TypeAlias = Callable[[str, int], Any] | SupportsWrite[str]
+
+_CallableT = TypeVar("_CallableT", bound=Callable[..., object])
+
+@type_check_only
+class _ErrDict(TypedDict):
+ divide: _ErrKind
+ over: _ErrKind
+ under: _ErrKind
+ invalid: _ErrKind
+
+###
+
+class _unspecified: ...
+
+_Unspecified: Final[_unspecified]
+
+class errstate:
+ __slots__ = "_all", "_call", "_divide", "_invalid", "_over", "_token", "_under"
+
+ def __init__(
+ self,
+ /,
+ *,
+ call: _ErrCall | _unspecified = ..., # = _Unspecified
+ all: _ErrKind | None = None,
+ divide: _ErrKind | None = None,
+ over: _ErrKind | None = None,
+ under: _ErrKind | None = None,
+ invalid: _ErrKind | None = None,
+ ) -> None: ...
+ def __call__(self, /, func: _CallableT) -> _CallableT: ...
+ def __enter__(self) -> None: ...
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ /,
+ ) -> None: ...
+
+def seterr(
+ all: _ErrKind | None = None,
+ divide: _ErrKind | None = None,
+ over: _ErrKind | None = None,
+ under: _ErrKind | None = None,
+ invalid: _ErrKind | None = None,
+) -> _ErrDict: ...
+def geterr() -> _ErrDict: ...
+def setbufsize(size: int) -> int: ...
+def getbufsize() -> int: ...
+def seterrcall(func: _ErrCall | None) -> _ErrCall | None: ...
+def geterrcall() -> _ErrCall | None: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_umath_tests.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_umath_tests.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..f97440bf41a024d45c703e8b6c8bedb39c30e8ce
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_umath_tests.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_umath_tests.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_umath_tests.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..696cec3b755e03bfac98fb55db8e223bfbd9f390
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/_umath_tests.pyi
@@ -0,0 +1,47 @@
+# undocumented internal testing module for ufunc features, defined in
+# numpy/_core/src/umath/_umath_tests.c.src
+
+from typing import Final, Literal as L, TypedDict, type_check_only
+
+import numpy as np
+from numpy._typing import _GUFunc_Nin2_Nout1, _UFunc_Nin1_Nout1, _UFunc_Nin2_Nout1
+
+@type_check_only
+class _TestDispatchResult(TypedDict):
+ func: str # e.g. 'func_AVX2'
+ var: str # e.g. 'var_AVX2'
+ func_xb: str # e.g. 'func_AVX2'
+ var_xb: str # e.g. 'var_AVX2'
+ all: list[str] # e.g. ['func_AVX2', 'func_SSE41', 'func']
+
+###
+
+# undocumented
+def test_signature(
+ nin: int, nout: int, signature: str, /
+) -> tuple[
+ L[0, 1], # core_enabled (0 for scalar ufunc; 1 for generalized ufunc)
+ tuple[int, ...] | None, # core_num_dims
+ tuple[int, ...] | None, # core_dim_ixs
+ tuple[int, ...] | None, # core_dim_flags
+ tuple[int, ...] | None, # core_dim_sizes
+]: ...
+
+# undocumented
+def test_dispatch() -> _TestDispatchResult: ...
+
+# undocumented ufuncs and gufuncs
+always_error: Final[_UFunc_Nin2_Nout1[L["always_error"], L[1], None]] = ...
+always_error_unary: Final[_UFunc_Nin1_Nout1[L["always_error_unary"], L[1], None]] = ...
+always_error_gufunc: Final[_GUFunc_Nin2_Nout1[L["always_error_gufunc"], L[1], None, L["(i),()->()"]]] = ...
+inner1d: Final[_GUFunc_Nin2_Nout1[L["inner1d"], L[2], None, L["(i),(i)->()"]]] = ...
+innerwt: Final[np.ufunc] = ... # we have no specialized type for 3->1 gufuncs
+matrix_multiply: Final[_GUFunc_Nin2_Nout1[L["matrix_multiply"], L[3], None, L["(m,n),(n,p)->(m,p)"]]] = ...
+matmul: Final[_GUFunc_Nin2_Nout1[L["matmul"], L[3], None, L["(m?,n),(n,p?)->(m?,p?)"]]] = ...
+euclidean_pdist: Final[_GUFunc_Nin2_Nout1[L["euclidean_pdist"], L[2], None, L["(n,d)->(p)"]]] = ...
+cumsum: Final[np.ufunc] = ... # we have no specialized type for 1->1 gufuncs
+inner1d_no_doc: Final[_GUFunc_Nin2_Nout1[L["inner1d_no_doc"], L[2], None, L["(i),(i)->()"]]] = ...
+cross1d: Final[_GUFunc_Nin2_Nout1[L["cross1d"], L[2], None, L["(3),(3)->(3)"]]] = ...
+_pickleable_module_global_ufunc: Final[np.ufunc] = ... # 0->0 ufunc; segfaults if called
+indexed_negative: Final[_UFunc_Nin1_Nout1[L["indexed_negative"], L[0], L[0]]] = ... # ntypes=0; can't be called
+conv1d_full: Final[_GUFunc_Nin2_Nout1[L["conv1d_full"], L[1], None, L["(m),(n)->(p)"]]] = ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/arrayprint.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/arrayprint.py
new file mode 100644
index 0000000000000000000000000000000000000000..96c17285bb3d7f7658689116c66293c954281498
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/arrayprint.py
@@ -0,0 +1,1779 @@
+"""Array printing function
+
+$Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $
+
+"""
+__all__ = ["array2string", "array_str", "array_repr",
+ "set_printoptions", "get_printoptions", "printoptions",
+ "format_float_positional", "format_float_scientific"]
+__docformat__ = 'restructuredtext'
+
+#
+# Written by Konrad Hinsen
+# last revision: 1996-3-13
+# modified by Jim Hugunin 1997-3-3 for repr's and str's (and other details)
+# and by Perry Greenfield 2000-4-1 for numarray
+# and by Travis Oliphant 2005-8-22 for numpy
+
+
+# Note: Both scalartypes.c.src and arrayprint.py implement strs for numpy
+# scalars but for different purposes. scalartypes.c.src has str/reprs for when
+# the scalar is printed on its own, while arrayprint.py has strs for when
+# scalars are printed inside an ndarray. Only the latter strs are currently
+# user-customizable.
+
+import functools
+import numbers
+import sys
+
+try:
+ from _thread import get_ident
+except ImportError:
+ from _dummy_thread import get_ident
+
+import contextlib
+import operator
+import warnings
+
+import numpy as np
+
+from . import numerictypes as _nt
+from .fromnumeric import any
+from .multiarray import (
+ array,
+ datetime_as_string,
+ datetime_data,
+ dragon4_positional,
+ dragon4_scientific,
+ ndarray,
+)
+from .numeric import asarray, concatenate, errstate
+from .numerictypes import complex128, flexible, float64, int_
+from .overrides import array_function_dispatch, set_module
+from .printoptions import format_options
+from .umath import absolute, isfinite, isinf, isnat
+
+
+def _make_options_dict(precision=None, threshold=None, edgeitems=None,
+ linewidth=None, suppress=None, nanstr=None, infstr=None,
+ sign=None, formatter=None, floatmode=None, legacy=None,
+ override_repr=None):
+ """
+ Make a dictionary out of the non-None arguments, plus conversion of
+ *legacy* and sanity checks.
+ """
+
+ options = {k: v for k, v in list(locals().items()) if v is not None}
+
+ if suppress is not None:
+ options['suppress'] = bool(suppress)
+
+ modes = ['fixed', 'unique', 'maxprec', 'maxprec_equal']
+ if floatmode not in modes + [None]:
+ raise ValueError("floatmode option must be one of " +
+ ", ".join(f'"{m}"' for m in modes))
+
+ if sign not in [None, '-', '+', ' ']:
+ raise ValueError("sign option must be one of ' ', '+', or '-'")
+
+ if legacy is False:
+ options['legacy'] = sys.maxsize
+ elif legacy == False: # noqa: E712
+ warnings.warn(
+ f"Passing `legacy={legacy!r}` is deprecated.",
+ FutureWarning, stacklevel=3
+ )
+ options['legacy'] = sys.maxsize
+ elif legacy == '1.13':
+ options['legacy'] = 113
+ elif legacy == '1.21':
+ options['legacy'] = 121
+ elif legacy == '1.25':
+ options['legacy'] = 125
+ elif legacy == '2.1':
+ options['legacy'] = 201
+ elif legacy == '2.2':
+ options['legacy'] = 202
+ elif legacy is None:
+ pass # OK, do nothing.
+ else:
+ warnings.warn(
+ "legacy printing option can currently only be '1.13', '1.21', "
+ "'1.25', '2.1', '2.2' or `False`", stacklevel=3)
+
+ if threshold is not None:
+ # forbid the bad threshold arg suggested by stack overflow, gh-12351
+ if not isinstance(threshold, numbers.Number):
+ raise TypeError("threshold must be numeric")
+ if np.isnan(threshold):
+ raise ValueError("threshold must be non-NAN, try "
+ "sys.maxsize for untruncated representation")
+
+ if precision is not None:
+ # forbid the bad precision arg as suggested by issue #18254
+ try:
+ options['precision'] = operator.index(precision)
+ except TypeError as e:
+ raise TypeError('precision must be an integer') from e
+
+ return options
+
+
+@set_module('numpy')
+def set_printoptions(precision=None, threshold=None, edgeitems=None,
+ linewidth=None, suppress=None, nanstr=None,
+ infstr=None, formatter=None, sign=None, floatmode=None,
+ *, legacy=None, override_repr=None):
+ """
+ Set printing options.
+
+ These options determine the way floating point numbers, arrays and
+ other NumPy objects are displayed.
+
+ Parameters
+ ----------
+ precision : int or None, optional
+ Number of digits of precision for floating point output (default 8).
+ May be None if `floatmode` is not `fixed`, to print as many digits as
+ necessary to uniquely specify the value.
+ threshold : int, optional
+ Total number of array elements which trigger summarization
+ rather than full repr (default 1000).
+ To always use the full repr without summarization, pass `sys.maxsize`.
+ edgeitems : int, optional
+ Number of array items in summary at beginning and end of
+ each dimension (default 3).
+ linewidth : int, optional
+ The number of characters per line for the purpose of inserting
+ line breaks (default 75).
+ suppress : bool, optional
+ If True, always print floating point numbers using fixed point
+ notation, in which case numbers equal to zero in the current precision
+ will print as zero. If False, then scientific notation is used when
+ absolute value of the smallest number is < 1e-4 or the ratio of the
+ maximum absolute value to the minimum is > 1e3. The default is False.
+ nanstr : str, optional
+ String representation of floating point not-a-number (default nan).
+ infstr : str, optional
+ String representation of floating point infinity (default inf).
+ sign : string, either '-', '+', or ' ', optional
+ Controls printing of the sign of floating-point types. If '+', always
+ print the sign of positive values. If ' ', always prints a space
+ (whitespace character) in the sign position of positive values. If
+ '-', omit the sign character of positive values. (default '-')
+
+ .. versionchanged:: 2.0
+ The sign parameter can now be an integer type, previously
+ types were floating-point types.
+
+ formatter : dict of callables, optional
+ If not None, the keys should indicate the type(s) that the respective
+ formatting function applies to. Callables should return a string.
+ Types that are not specified (by their corresponding keys) are handled
+ by the default formatters. Individual types for which a formatter
+ can be set are:
+
+ - 'bool'
+ - 'int'
+ - 'timedelta' : a `numpy.timedelta64`
+ - 'datetime' : a `numpy.datetime64`
+ - 'float'
+ - 'longfloat' : 128-bit floats
+ - 'complexfloat'
+ - 'longcomplexfloat' : composed of two 128-bit floats
+ - 'numpystr' : types `numpy.bytes_` and `numpy.str_`
+ - 'object' : `np.object_` arrays
+
+ Other keys that can be used to set a group of types at once are:
+
+ - 'all' : sets all types
+ - 'int_kind' : sets 'int'
+ - 'float_kind' : sets 'float' and 'longfloat'
+ - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
+ - 'str_kind' : sets 'numpystr'
+ floatmode : str, optional
+ Controls the interpretation of the `precision` option for
+ floating-point types. Can take the following values
+ (default maxprec_equal):
+
+ * 'fixed': Always print exactly `precision` fractional digits,
+ even if this would print more or fewer digits than
+ necessary to specify the value uniquely.
+ * 'unique': Print the minimum number of fractional digits necessary
+ to represent each value uniquely. Different elements may
+ have a different number of digits. The value of the
+ `precision` option is ignored.
+ * 'maxprec': Print at most `precision` fractional digits, but if
+ an element can be uniquely represented with fewer digits
+ only print it with that many.
+ * 'maxprec_equal': Print at most `precision` fractional digits,
+ but if every element in the array can be uniquely
+ represented with an equal number of fewer digits, use that
+ many digits for all elements.
+ legacy : string or `False`, optional
+ If set to the string ``'1.13'`` enables 1.13 legacy printing mode. This
+ approximates numpy 1.13 print output by including a space in the sign
+ position of floats and different behavior for 0d arrays. This also
+ enables 1.21 legacy printing mode (described below).
+
+ If set to the string ``'1.21'`` enables 1.21 legacy printing mode. This
+ approximates numpy 1.21 print output of complex structured dtypes
+ by not inserting spaces after commas that separate fields and after
+ colons.
+
+ If set to ``'1.25'`` approximates printing of 1.25 which mainly means
+ that numeric scalars are printed without their type information, e.g.
+ as ``3.0`` rather than ``np.float64(3.0)``.
+
+ If set to ``'2.1'``, shape information is not given when arrays are
+ summarized (i.e., multiple elements replaced with ``...``).
+
+ If set to ``'2.2'``, the transition to use scientific notation for
+ printing ``np.float16`` and ``np.float32`` types may happen later or
+ not at all for larger values.
+
+ If set to `False`, disables legacy mode.
+
+ Unrecognized strings will be ignored with a warning for forward
+ compatibility.
+
+ .. versionchanged:: 1.22.0
+ .. versionchanged:: 2.2
+
+ override_repr: callable, optional
+ If set a passed function will be used for generating arrays' repr.
+ Other options will be ignored.
+
+ See Also
+ --------
+ get_printoptions, printoptions, array2string
+
+
+ Notes
+ -----
+
+ * ``formatter`` is always reset with a call to `set_printoptions`.
+ * Use `printoptions` as a context manager to set the values temporarily.
+ * These print options apply only to NumPy ndarrays, not to scalars.
+
+ **Concurrency note:** see :ref:`text_formatting_options`
+
+ Examples
+ --------
+ Floating point precision can be set:
+
+ >>> import numpy as np
+ >>> np.set_printoptions(precision=4)
+ >>> np.array([1.123456789])
+ [1.1235]
+
+ Long arrays can be summarised:
+
+ >>> np.set_printoptions(threshold=5)
+ >>> np.arange(10)
+ array([0, 1, 2, ..., 7, 8, 9], shape=(10,))
+
+ Small results can be suppressed:
+
+ >>> eps = np.finfo(float).eps
+ >>> x = np.arange(4.)
+ >>> x**2 - (x + eps)**2
+ array([-4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00])
+ >>> np.set_printoptions(suppress=True)
+ >>> x**2 - (x + eps)**2
+ array([-0., -0., 0., 0.])
+
+ A custom formatter can be used to display array elements as desired:
+
+ >>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)})
+ >>> x = np.arange(3)
+ >>> x
+ array([int: 0, int: -1, int: -2])
+ >>> np.set_printoptions() # formatter gets reset
+ >>> x
+ array([0, 1, 2])
+
+ To put back the default options, you can use:
+
+ >>> np.set_printoptions(edgeitems=3, infstr='inf',
+ ... linewidth=75, nanstr='nan', precision=8,
+ ... suppress=False, threshold=1000, formatter=None)
+
+ Also to temporarily override options, use `printoptions`
+ as a context manager:
+
+ >>> with np.printoptions(precision=2, suppress=True, threshold=5):
+ ... np.linspace(0, 10, 10)
+ array([ 0. , 1.11, 2.22, ..., 7.78, 8.89, 10. ], shape=(10,))
+
+ """
+ _set_printoptions(precision, threshold, edgeitems, linewidth, suppress,
+ nanstr, infstr, formatter, sign, floatmode,
+ legacy=legacy, override_repr=override_repr)
+
+
+def _set_printoptions(precision=None, threshold=None, edgeitems=None,
+ linewidth=None, suppress=None, nanstr=None,
+ infstr=None, formatter=None, sign=None, floatmode=None,
+ *, legacy=None, override_repr=None):
+ new_opt = _make_options_dict(precision, threshold, edgeitems, linewidth,
+ suppress, nanstr, infstr, sign, formatter,
+ floatmode, legacy)
+ # formatter and override_repr are always reset
+ new_opt['formatter'] = formatter
+ new_opt['override_repr'] = override_repr
+
+ updated_opt = format_options.get() | new_opt
+ updated_opt.update(new_opt)
+
+ if updated_opt['legacy'] == 113:
+ updated_opt['sign'] = '-'
+
+ return format_options.set(updated_opt)
+
+
+@set_module('numpy')
+def get_printoptions():
+ """
+ Return the current print options.
+
+ Returns
+ -------
+ print_opts : dict
+ Dictionary of current print options with keys
+
+ - precision : int
+ - threshold : int
+ - edgeitems : int
+ - linewidth : int
+ - suppress : bool
+ - nanstr : str
+ - infstr : str
+ - sign : str
+ - formatter : dict of callables
+ - floatmode : str
+ - legacy : str or False
+
+ For a full description of these options, see `set_printoptions`.
+
+ Notes
+ -----
+ These print options apply only to NumPy ndarrays, not to scalars.
+
+ **Concurrency note:** see :ref:`text_formatting_options`
+
+ See Also
+ --------
+ set_printoptions, printoptions
+
+ Examples
+ --------
+ >>> import numpy as np
+
+ >>> np.get_printoptions()
+ {'edgeitems': 3, 'threshold': 1000, ..., 'override_repr': None}
+
+ >>> np.get_printoptions()['linewidth']
+ 75
+ >>> np.set_printoptions(linewidth=100)
+ >>> np.get_printoptions()['linewidth']
+ 100
+
+ """
+ opts = format_options.get().copy()
+ opts['legacy'] = {
+ 113: '1.13', 121: '1.21', 125: '1.25', 201: '2.1',
+ 202: '2.2', sys.maxsize: False,
+ }[opts['legacy']]
+ return opts
+
+
+def _get_legacy_print_mode():
+ """Return the legacy print mode as an int."""
+ return format_options.get()['legacy']
+
+
+@set_module('numpy')
+@contextlib.contextmanager
+def printoptions(*args, **kwargs):
+ """Context manager for setting print options.
+
+ Set print options for the scope of the `with` block, and restore the old
+ options at the end. See `set_printoptions` for the full description of
+ available options.
+
+ Examples
+ --------
+ >>> import numpy as np
+
+ >>> from numpy.testing import assert_equal
+ >>> with np.printoptions(precision=2):
+ ... np.array([2.0]) / 3
+ array([0.67])
+
+ The `as`-clause of the `with`-statement gives the current print options:
+
+ >>> with np.printoptions(precision=2) as opts:
+ ... assert_equal(opts, np.get_printoptions())
+
+ See Also
+ --------
+ set_printoptions, get_printoptions
+
+ Notes
+ -----
+ These print options apply only to NumPy ndarrays, not to scalars.
+
+ **Concurrency note:** see :ref:`text_formatting_options`
+
+ """
+ token = _set_printoptions(*args, **kwargs)
+
+ try:
+ yield get_printoptions()
+ finally:
+ format_options.reset(token)
+
+
+def _leading_trailing(a, edgeitems, index=()):
+ """
+ Keep only the N-D corners (leading and trailing edges) of an array.
+
+ Should be passed a base-class ndarray, since it makes no guarantees about
+ preserving subclasses.
+ """
+ axis = len(index)
+ if axis == a.ndim:
+ return a[index]
+
+ if a.shape[axis] > 2 * edgeitems:
+ return concatenate((
+ _leading_trailing(a, edgeitems, index + np.index_exp[:edgeitems]),
+ _leading_trailing(a, edgeitems, index + np.index_exp[-edgeitems:])
+ ), axis=axis)
+ else:
+ return _leading_trailing(a, edgeitems, index + np.index_exp[:])
+
+
+def _object_format(o):
+ """ Object arrays containing lists should be printed unambiguously """
+ if type(o) is list:
+ fmt = 'list({!r})'
+ else:
+ fmt = '{!r}'
+ return fmt.format(o)
+
+def repr_format(x):
+ if isinstance(x, (np.str_, np.bytes_)):
+ return repr(x.item())
+ return repr(x)
+
+def str_format(x):
+ if isinstance(x, (np.str_, np.bytes_)):
+ return str(x.item())
+ return str(x)
+
+def _get_formatdict(data, *, precision, floatmode, suppress, sign, legacy,
+ formatter, **kwargs):
+ # note: extra arguments in kwargs are ignored
+
+ # wrapped in lambdas to avoid taking a code path
+ # with the wrong type of data
+ formatdict = {
+ 'bool': lambda: BoolFormat(data),
+ 'int': lambda: IntegerFormat(data, sign),
+ 'float': lambda: FloatingFormat(
+ data, precision, floatmode, suppress, sign, legacy=legacy),
+ 'longfloat': lambda: FloatingFormat(
+ data, precision, floatmode, suppress, sign, legacy=legacy),
+ 'complexfloat': lambda: ComplexFloatingFormat(
+ data, precision, floatmode, suppress, sign, legacy=legacy),
+ 'longcomplexfloat': lambda: ComplexFloatingFormat(
+ data, precision, floatmode, suppress, sign, legacy=legacy),
+ 'datetime': lambda: DatetimeFormat(data, legacy=legacy),
+ 'timedelta': lambda: TimedeltaFormat(data),
+ 'object': lambda: _object_format,
+ 'void': lambda: str_format,
+ 'numpystr': lambda: repr_format}
+
+ # we need to wrap values in `formatter` in a lambda, so that the interface
+ # is the same as the above values.
+ def indirect(x):
+ return lambda: x
+
+ if formatter is not None:
+ fkeys = [k for k in formatter.keys() if formatter[k] is not None]
+ if 'all' in fkeys:
+ for key in formatdict.keys():
+ formatdict[key] = indirect(formatter['all'])
+ if 'int_kind' in fkeys:
+ for key in ['int']:
+ formatdict[key] = indirect(formatter['int_kind'])
+ if 'float_kind' in fkeys:
+ for key in ['float', 'longfloat']:
+ formatdict[key] = indirect(formatter['float_kind'])
+ if 'complex_kind' in fkeys:
+ for key in ['complexfloat', 'longcomplexfloat']:
+ formatdict[key] = indirect(formatter['complex_kind'])
+ if 'str_kind' in fkeys:
+ formatdict['numpystr'] = indirect(formatter['str_kind'])
+ for key in formatdict.keys():
+ if key in fkeys:
+ formatdict[key] = indirect(formatter[key])
+
+ return formatdict
+
+def _get_format_function(data, **options):
+ """
+ find the right formatting function for the dtype_
+ """
+ dtype_ = data.dtype
+ dtypeobj = dtype_.type
+ formatdict = _get_formatdict(data, **options)
+ if dtypeobj is None:
+ return formatdict["numpystr"]()
+ elif issubclass(dtypeobj, _nt.bool):
+ return formatdict['bool']()
+ elif issubclass(dtypeobj, _nt.integer):
+ if issubclass(dtypeobj, _nt.timedelta64):
+ return formatdict['timedelta']()
+ else:
+ return formatdict['int']()
+ elif issubclass(dtypeobj, _nt.floating):
+ if issubclass(dtypeobj, _nt.longdouble):
+ return formatdict['longfloat']()
+ else:
+ return formatdict['float']()
+ elif issubclass(dtypeobj, _nt.complexfloating):
+ if issubclass(dtypeobj, _nt.clongdouble):
+ return formatdict['longcomplexfloat']()
+ else:
+ return formatdict['complexfloat']()
+ elif issubclass(dtypeobj, (_nt.str_, _nt.bytes_)):
+ return formatdict['numpystr']()
+ elif issubclass(dtypeobj, _nt.datetime64):
+ return formatdict['datetime']()
+ elif issubclass(dtypeobj, _nt.object_):
+ return formatdict['object']()
+ elif issubclass(dtypeobj, _nt.void):
+ if dtype_.names is not None:
+ return StructuredVoidFormat.from_data(data, **options)
+ else:
+ return formatdict['void']()
+ else:
+ return formatdict['numpystr']()
+
+
+def _recursive_guard(fillvalue='...'):
+ """
+ Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs
+
+ Decorates a function such that if it calls itself with the same first
+ argument, it returns `fillvalue` instead of recursing.
+
+ Largely copied from reprlib.recursive_repr
+ """
+
+ def decorating_function(f):
+ repr_running = set()
+
+ @functools.wraps(f)
+ def wrapper(self, *args, **kwargs):
+ key = id(self), get_ident()
+ if key in repr_running:
+ return fillvalue
+ repr_running.add(key)
+ try:
+ return f(self, *args, **kwargs)
+ finally:
+ repr_running.discard(key)
+
+ return wrapper
+
+ return decorating_function
+
+
+# gracefully handle recursive calls, when object arrays contain themselves
+@_recursive_guard()
+def _array2string(a, options, separator=' ', prefix=""):
+ # The formatter __init__s in _get_format_function cannot deal with
+ # subclasses yet, and we also need to avoid recursion issues in
+ # _formatArray with subclasses which return 0d arrays in place of scalars
+ data = asarray(a)
+ if a.shape == ():
+ a = data
+
+ if a.size > options['threshold']:
+ summary_insert = "..."
+ data = _leading_trailing(data, options['edgeitems'])
+ else:
+ summary_insert = ""
+
+ # find the right formatting function for the array
+ format_function = _get_format_function(data, **options)
+
+ # skip over "["
+ next_line_prefix = " "
+ # skip over array(
+ next_line_prefix += " " * len(prefix)
+
+ lst = _formatArray(a, format_function, options['linewidth'],
+ next_line_prefix, separator, options['edgeitems'],
+ summary_insert, options['legacy'])
+ return lst
+
+
+def _array2string_dispatcher(
+ a, max_line_width=None, precision=None,
+ suppress_small=None, separator=None, prefix=None,
+ *, formatter=None, threshold=None,
+ edgeitems=None, sign=None, floatmode=None, suffix=None,
+ legacy=None):
+ return (a,)
+
+
+@array_function_dispatch(_array2string_dispatcher, module='numpy')
+def array2string(a, max_line_width=None, precision=None,
+ suppress_small=None, separator=' ', prefix="",
+ *, formatter=None, threshold=None,
+ edgeitems=None, sign=None, floatmode=None, suffix="",
+ legacy=None):
+ """
+ Return a string representation of an array.
+
+ Parameters
+ ----------
+ a : ndarray
+ Input array.
+ max_line_width : int, optional
+ Inserts newlines if text is longer than `max_line_width`.
+ Defaults to ``numpy.get_printoptions()['linewidth']``.
+ precision : int or None, optional
+ Floating point precision.
+ Defaults to ``numpy.get_printoptions()['precision']``.
+ suppress_small : bool, optional
+ Represent numbers "very close" to zero as zero; default is False.
+ Very close is defined by precision: if the precision is 8, e.g.,
+ numbers smaller (in absolute value) than 5e-9 are represented as
+ zero.
+ Defaults to ``numpy.get_printoptions()['suppress']``.
+ separator : str, optional
+ Inserted between elements.
+ prefix : str, optional
+ suffix : str, optional
+ The length of the prefix and suffix strings are used to respectively
+ align and wrap the output. An array is typically printed as::
+
+ prefix + array2string(a) + suffix
+
+ The output is left-padded by the length of the prefix string, and
+ wrapping is forced at the column ``max_line_width - len(suffix)``.
+ It should be noted that the content of prefix and suffix strings are
+ not included in the output.
+ formatter : dict of callables, optional
+ If not None, the keys should indicate the type(s) that the respective
+ formatting function applies to. Callables should return a string.
+ Types that are not specified (by their corresponding keys) are handled
+ by the default formatters. Individual types for which a formatter
+ can be set are:
+
+ - 'bool'
+ - 'int'
+ - 'timedelta' : a `numpy.timedelta64`
+ - 'datetime' : a `numpy.datetime64`
+ - 'float'
+ - 'longfloat' : 128-bit floats
+ - 'complexfloat'
+ - 'longcomplexfloat' : composed of two 128-bit floats
+ - 'void' : type `numpy.void`
+ - 'numpystr' : types `numpy.bytes_` and `numpy.str_`
+
+ Other keys that can be used to set a group of types at once are:
+
+ - 'all' : sets all types
+ - 'int_kind' : sets 'int'
+ - 'float_kind' : sets 'float' and 'longfloat'
+ - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
+ - 'str_kind' : sets 'numpystr'
+ threshold : int, optional
+ Total number of array elements which trigger summarization
+ rather than full repr.
+ Defaults to ``numpy.get_printoptions()['threshold']``.
+ edgeitems : int, optional
+ Number of array items in summary at beginning and end of
+ each dimension.
+ Defaults to ``numpy.get_printoptions()['edgeitems']``.
+ sign : string, either '-', '+', or ' ', optional
+ Controls printing of the sign of floating-point types. If '+', always
+ print the sign of positive values. If ' ', always prints a space
+ (whitespace character) in the sign position of positive values. If
+ '-', omit the sign character of positive values.
+ Defaults to ``numpy.get_printoptions()['sign']``.
+
+ .. versionchanged:: 2.0
+ The sign parameter can now be an integer type, previously
+ types were floating-point types.
+
+ floatmode : str, optional
+ Controls the interpretation of the `precision` option for
+ floating-point types.
+ Defaults to ``numpy.get_printoptions()['floatmode']``.
+ Can take the following values:
+
+ - 'fixed': Always print exactly `precision` fractional digits,
+ even if this would print more or fewer digits than
+ necessary to specify the value uniquely.
+ - 'unique': Print the minimum number of fractional digits necessary
+ to represent each value uniquely. Different elements may
+ have a different number of digits. The value of the
+ `precision` option is ignored.
+ - 'maxprec': Print at most `precision` fractional digits, but if
+ an element can be uniquely represented with fewer digits
+ only print it with that many.
+ - 'maxprec_equal': Print at most `precision` fractional digits,
+ but if every element in the array can be uniquely
+ represented with an equal number of fewer digits, use that
+ many digits for all elements.
+ legacy : string or `False`, optional
+ If set to the string ``'1.13'`` enables 1.13 legacy printing mode. This
+ approximates numpy 1.13 print output by including a space in the sign
+ position of floats and different behavior for 0d arrays. If set to
+ `False`, disables legacy mode. Unrecognized strings will be ignored
+ with a warning for forward compatibility.
+
+ Returns
+ -------
+ array_str : str
+ String representation of the array.
+
+ Raises
+ ------
+ TypeError
+ if a callable in `formatter` does not return a string.
+
+ See Also
+ --------
+ array_str, array_repr, set_printoptions, get_printoptions
+
+ Notes
+ -----
+ If a formatter is specified for a certain type, the `precision` keyword is
+ ignored for that type.
+
+ This is a very flexible function; `array_repr` and `array_str` are using
+ `array2string` internally so keywords with the same name should work
+ identically in all three functions.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1e-16,1,2,3])
+ >>> np.array2string(x, precision=2, separator=',',
+ ... suppress_small=True)
+ '[0.,1.,2.,3.]'
+
+ >>> x = np.arange(3.)
+ >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x})
+ '[0.00 1.00 2.00]'
+
+ >>> x = np.arange(3)
+ >>> np.array2string(x, formatter={'int':lambda x: hex(x)})
+ '[0x0 0x1 0x2]'
+
+ """
+
+ overrides = _make_options_dict(precision, threshold, edgeitems,
+ max_line_width, suppress_small, None, None,
+ sign, formatter, floatmode, legacy)
+ options = format_options.get().copy()
+ options.update(overrides)
+
+ if options['legacy'] <= 113:
+ if a.shape == () and a.dtype.names is None:
+ return repr(a.item())
+
+ if options['legacy'] > 113:
+ options['linewidth'] -= len(suffix)
+
+ # treat as a null array if any of shape elements == 0
+ if a.size == 0:
+ return "[]"
+
+ return _array2string(a, options, separator, prefix)
+
+
+def _extendLine(s, line, word, line_width, next_line_prefix, legacy):
+ needs_wrap = len(line) + len(word) > line_width
+ if legacy > 113:
+ # don't wrap lines if it won't help
+ if len(line) <= len(next_line_prefix):
+ needs_wrap = False
+
+ if needs_wrap:
+ s += line.rstrip() + "\n"
+ line = next_line_prefix
+ line += word
+ return s, line
+
+
+def _extendLine_pretty(s, line, word, line_width, next_line_prefix, legacy):
+ """
+ Extends line with nicely formatted (possibly multi-line) string ``word``.
+ """
+ words = word.splitlines()
+ if len(words) == 1 or legacy <= 113:
+ return _extendLine(s, line, word, line_width, next_line_prefix, legacy)
+
+ max_word_length = max(len(word) for word in words)
+ if (len(line) + max_word_length > line_width and
+ len(line) > len(next_line_prefix)):
+ s += line.rstrip() + '\n'
+ line = next_line_prefix + words[0]
+ indent = next_line_prefix
+ else:
+ indent = len(line) * ' '
+ line += words[0]
+
+ for word in words[1::]:
+ s += line.rstrip() + '\n'
+ line = indent + word
+
+ suffix_length = max_word_length - len(words[-1])
+ line += suffix_length * ' '
+
+ return s, line
+
+def _formatArray(a, format_function, line_width, next_line_prefix,
+ separator, edge_items, summary_insert, legacy):
+ """formatArray is designed for two modes of operation:
+
+ 1. Full output
+
+ 2. Summarized output
+
+ """
+ def recurser(index, hanging_indent, curr_width):
+ """
+ By using this local function, we don't need to recurse with all the
+ arguments. Since this function is not created recursively, the cost is
+ not significant
+ """
+ axis = len(index)
+ axes_left = a.ndim - axis
+
+ if axes_left == 0:
+ return format_function(a[index])
+
+ # when recursing, add a space to align with the [ added, and reduce the
+ # length of the line by 1
+ next_hanging_indent = hanging_indent + ' '
+ if legacy <= 113:
+ next_width = curr_width
+ else:
+ next_width = curr_width - len(']')
+
+ a_len = a.shape[axis]
+ show_summary = summary_insert and 2 * edge_items < a_len
+ if show_summary:
+ leading_items = edge_items
+ trailing_items = edge_items
+ else:
+ leading_items = 0
+ trailing_items = a_len
+
+ # stringify the array with the hanging indent on the first line too
+ s = ''
+
+ # last axis (rows) - wrap elements if they would not fit on one line
+ if axes_left == 1:
+ # the length up until the beginning of the separator / bracket
+ if legacy <= 113:
+ elem_width = curr_width - len(separator.rstrip())
+ else:
+ elem_width = curr_width - max(
+ len(separator.rstrip()), len(']')
+ )
+
+ line = hanging_indent
+ for i in range(leading_items):
+ word = recurser(index + (i,), next_hanging_indent, next_width)
+ s, line = _extendLine_pretty(
+ s, line, word, elem_width, hanging_indent, legacy)
+ line += separator
+
+ if show_summary:
+ s, line = _extendLine(
+ s, line, summary_insert, elem_width, hanging_indent, legacy
+ )
+ if legacy <= 113:
+ line += ", "
+ else:
+ line += separator
+
+ for i in range(trailing_items, 1, -1):
+ word = recurser(index + (-i,), next_hanging_indent, next_width)
+ s, line = _extendLine_pretty(
+ s, line, word, elem_width, hanging_indent, legacy)
+ line += separator
+
+ if legacy <= 113:
+ # width of the separator is not considered on 1.13
+ elem_width = curr_width
+ word = recurser(index + (-1,), next_hanging_indent, next_width)
+ s, line = _extendLine_pretty(
+ s, line, word, elem_width, hanging_indent, legacy)
+
+ s += line
+
+ # other axes - insert newlines between rows
+ else:
+ s = ''
+ line_sep = separator.rstrip() + '\n' * (axes_left - 1)
+
+ for i in range(leading_items):
+ nested = recurser(
+ index + (i,), next_hanging_indent, next_width
+ )
+ s += hanging_indent + nested + line_sep
+
+ if show_summary:
+ if legacy <= 113:
+ # trailing space, fixed nbr of newlines,
+ # and fixed separator
+ s += hanging_indent + summary_insert + ", \n"
+ else:
+ s += hanging_indent + summary_insert + line_sep
+
+ for i in range(trailing_items, 1, -1):
+ nested = recurser(index + (-i,), next_hanging_indent,
+ next_width)
+ s += hanging_indent + nested + line_sep
+
+ nested = recurser(index + (-1,), next_hanging_indent, next_width)
+ s += hanging_indent + nested
+
+ # remove the hanging indent, and wrap in []
+ s = '[' + s[len(hanging_indent):] + ']'
+ return s
+
+ try:
+ # invoke the recursive part with an initial index and prefix
+ return recurser(index=(),
+ hanging_indent=next_line_prefix,
+ curr_width=line_width)
+ finally:
+ # recursive closures have a cyclic reference to themselves, which
+ # requires gc to collect (gh-10620). To avoid this problem, for
+ # performance and PyPy friendliness, we break the cycle:
+ recurser = None
+
+def _none_or_positive_arg(x, name):
+ if x is None:
+ return -1
+ if x < 0:
+ raise ValueError(f"{name} must be >= 0")
+ return x
+
+class FloatingFormat:
+ """ Formatter for subtypes of np.floating """
+ def __init__(self, data, precision, floatmode, suppress_small, sign=False,
+ *, legacy=None):
+ # for backcompatibility, accept bools
+ if isinstance(sign, bool):
+ sign = '+' if sign else '-'
+
+ self._legacy = legacy
+ if self._legacy <= 113:
+ # when not 0d, legacy does not support '-'
+ if data.shape != () and sign == '-':
+ sign = ' '
+
+ self.floatmode = floatmode
+ if floatmode == 'unique':
+ self.precision = None
+ else:
+ self.precision = precision
+
+ self.precision = _none_or_positive_arg(self.precision, 'precision')
+
+ self.suppress_small = suppress_small
+ self.sign = sign
+ self.exp_format = False
+ self.large_exponent = False
+ self.fillFormat(data)
+
+ def fillFormat(self, data):
+ # only the finite values are used to compute the number of digits
+ finite_vals = data[isfinite(data)]
+
+ # choose exponential mode based on the non-zero finite values:
+ abs_non_zero = absolute(finite_vals[finite_vals != 0])
+ if len(abs_non_zero) != 0:
+ max_val = np.max(abs_non_zero)
+ min_val = np.min(abs_non_zero)
+ if self._legacy <= 202:
+ exp_cutoff_max = 1.e8
+ else:
+ # consider data type while deciding the max cutoff for exp format
+ exp_cutoff_max = 10.**min(8, np.finfo(data.dtype).precision)
+ with errstate(over='ignore'): # division can overflow
+ if max_val >= exp_cutoff_max or (not self.suppress_small and
+ (min_val < 0.0001 or max_val / min_val > 1000.)):
+ self.exp_format = True
+
+ # do a first pass of printing all the numbers, to determine sizes
+ if len(finite_vals) == 0:
+ self.pad_left = 0
+ self.pad_right = 0
+ self.trim = '.'
+ self.exp_size = -1
+ self.unique = True
+ self.min_digits = None
+ elif self.exp_format:
+ trim, unique = '.', True
+ if self.floatmode == 'fixed' or self._legacy <= 113:
+ trim, unique = 'k', False
+ strs = (dragon4_scientific(x, precision=self.precision,
+ unique=unique, trim=trim, sign=self.sign == '+')
+ for x in finite_vals)
+ frac_strs, _, exp_strs = zip(*(s.partition('e') for s in strs))
+ int_part, frac_part = zip(*(s.split('.') for s in frac_strs))
+ self.exp_size = max(len(s) for s in exp_strs) - 1
+
+ self.trim = 'k'
+ self.precision = max(len(s) for s in frac_part)
+ self.min_digits = self.precision
+ self.unique = unique
+
+ # for back-compat with np 1.13, use 2 spaces & sign and full prec
+ if self._legacy <= 113:
+ self.pad_left = 3
+ else:
+ # this should be only 1 or 2. Can be calculated from sign.
+ self.pad_left = max(len(s) for s in int_part)
+ # pad_right is only needed for nan length calculation
+ self.pad_right = self.exp_size + 2 + self.precision
+ else:
+ trim, unique = '.', True
+ if self.floatmode == 'fixed':
+ trim, unique = 'k', False
+ strs = (dragon4_positional(x, precision=self.precision,
+ fractional=True,
+ unique=unique, trim=trim,
+ sign=self.sign == '+')
+ for x in finite_vals)
+ int_part, frac_part = zip(*(s.split('.') for s in strs))
+ if self._legacy <= 113:
+ self.pad_left = 1 + max(len(s.lstrip('-+')) for s in int_part)
+ else:
+ self.pad_left = max(len(s) for s in int_part)
+ self.pad_right = max(len(s) for s in frac_part)
+ self.exp_size = -1
+ self.unique = unique
+
+ if self.floatmode in ['fixed', 'maxprec_equal']:
+ self.precision = self.min_digits = self.pad_right
+ self.trim = 'k'
+ else:
+ self.trim = '.'
+ self.min_digits = 0
+
+ if self._legacy > 113:
+ # account for sign = ' ' by adding one to pad_left
+ if self.sign == ' ' and not any(np.signbit(finite_vals)):
+ self.pad_left += 1
+
+ # if there are non-finite values, may need to increase pad_left
+ if data.size != finite_vals.size:
+ neginf = self.sign != '-' or any(data[isinf(data)] < 0)
+ offset = self.pad_right + 1 # +1 for decimal pt
+ current_options = format_options.get()
+ self.pad_left = max(
+ self.pad_left, len(current_options['nanstr']) - offset,
+ len(current_options['infstr']) + neginf - offset
+ )
+
+ def __call__(self, x):
+ if not np.isfinite(x):
+ with errstate(invalid='ignore'):
+ current_options = format_options.get()
+ if np.isnan(x):
+ sign = '+' if self.sign == '+' else ''
+ ret = sign + current_options['nanstr']
+ else: # isinf
+ sign = '-' if x < 0 else '+' if self.sign == '+' else ''
+ ret = sign + current_options['infstr']
+ return ' ' * (
+ self.pad_left + self.pad_right + 1 - len(ret)
+ ) + ret
+
+ if self.exp_format:
+ return dragon4_scientific(x,
+ precision=self.precision,
+ min_digits=self.min_digits,
+ unique=self.unique,
+ trim=self.trim,
+ sign=self.sign == '+',
+ pad_left=self.pad_left,
+ exp_digits=self.exp_size)
+ else:
+ return dragon4_positional(x,
+ precision=self.precision,
+ min_digits=self.min_digits,
+ unique=self.unique,
+ fractional=True,
+ trim=self.trim,
+ sign=self.sign == '+',
+ pad_left=self.pad_left,
+ pad_right=self.pad_right)
+
+
+@set_module('numpy')
+def format_float_scientific(x, precision=None, unique=True, trim='k',
+ sign=False, pad_left=None, exp_digits=None,
+ min_digits=None):
+ """
+ Format a floating-point scalar as a decimal string in scientific notation.
+
+ Provides control over rounding, trimming and padding. Uses and assumes
+ IEEE unbiased rounding. Uses the "Dragon4" algorithm.
+
+ Parameters
+ ----------
+ x : python float or numpy floating scalar
+ Value to format.
+ precision : non-negative integer or None, optional
+ Maximum number of digits to print. May be None if `unique` is
+ `True`, but must be an integer if unique is `False`.
+ unique : boolean, optional
+ If `True`, use a digit-generation strategy which gives the shortest
+ representation which uniquely identifies the floating-point number from
+ other values of the same type, by judicious rounding. If `precision`
+ is given fewer digits than necessary can be printed. If `min_digits`
+ is given more can be printed, in which cases the last digit is rounded
+ with unbiased rounding.
+ If `False`, digits are generated as if printing an infinite-precision
+ value and stopping after `precision` digits, rounding the remaining
+ value with unbiased rounding
+ trim : one of 'k', '.', '0', '-', optional
+ Controls post-processing trimming of trailing digits, as follows:
+
+ * 'k' : keep trailing zeros, keep decimal point (no trimming)
+ * '.' : trim all trailing zeros, leave decimal point
+ * '0' : trim all but the zero before the decimal point. Insert the
+ zero if it is missing.
+ * '-' : trim trailing zeros and any trailing decimal point
+ sign : boolean, optional
+ Whether to show the sign for positive values.
+ pad_left : non-negative integer, optional
+ Pad the left side of the string with whitespace until at least that
+ many characters are to the left of the decimal point.
+ exp_digits : non-negative integer, optional
+ Pad the exponent with zeros until it contains at least this
+ many digits. If omitted, the exponent will be at least 2 digits.
+ min_digits : non-negative integer or None, optional
+ Minimum number of digits to print. This only has an effect for
+ `unique=True`. In that case more digits than necessary to uniquely
+ identify the value may be printed and rounded unbiased.
+
+ .. versionadded:: 1.21.0
+
+ Returns
+ -------
+ rep : string
+ The string representation of the floating point value
+
+ See Also
+ --------
+ format_float_positional
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.format_float_scientific(np.float32(np.pi))
+ '3.1415927e+00'
+ >>> s = np.float32(1.23e24)
+ >>> np.format_float_scientific(s, unique=False, precision=15)
+ '1.230000071797338e+24'
+ >>> np.format_float_scientific(s, exp_digits=4)
+ '1.23e+0024'
+ """
+ precision = _none_or_positive_arg(precision, 'precision')
+ pad_left = _none_or_positive_arg(pad_left, 'pad_left')
+ exp_digits = _none_or_positive_arg(exp_digits, 'exp_digits')
+ min_digits = _none_or_positive_arg(min_digits, 'min_digits')
+ if min_digits > 0 and precision > 0 and min_digits > precision:
+ raise ValueError("min_digits must be less than or equal to precision")
+ return dragon4_scientific(x, precision=precision, unique=unique,
+ trim=trim, sign=sign, pad_left=pad_left,
+ exp_digits=exp_digits, min_digits=min_digits)
+
+
+@set_module('numpy')
+def format_float_positional(x, precision=None, unique=True,
+ fractional=True, trim='k', sign=False,
+ pad_left=None, pad_right=None, min_digits=None):
+ """
+ Format a floating-point scalar as a decimal string in positional notation.
+
+ Provides control over rounding, trimming and padding. Uses and assumes
+ IEEE unbiased rounding. Uses the "Dragon4" algorithm.
+
+ Parameters
+ ----------
+ x : python float or numpy floating scalar
+ Value to format.
+ precision : non-negative integer or None, optional
+ Maximum number of digits to print. May be None if `unique` is
+ `True`, but must be an integer if unique is `False`.
+ unique : boolean, optional
+ If `True`, use a digit-generation strategy which gives the shortest
+ representation which uniquely identifies the floating-point number from
+ other values of the same type, by judicious rounding. If `precision`
+ is given fewer digits than necessary can be printed, or if `min_digits`
+ is given more can be printed, in which cases the last digit is rounded
+ with unbiased rounding.
+ If `False`, digits are generated as if printing an infinite-precision
+ value and stopping after `precision` digits, rounding the remaining
+ value with unbiased rounding
+ fractional : boolean, optional
+ If `True`, the cutoffs of `precision` and `min_digits` refer to the
+ total number of digits after the decimal point, including leading
+ zeros.
+ If `False`, `precision` and `min_digits` refer to the total number of
+ significant digits, before or after the decimal point, ignoring leading
+ zeros.
+ trim : one of 'k', '.', '0', '-', optional
+ Controls post-processing trimming of trailing digits, as follows:
+
+ * 'k' : keep trailing zeros, keep decimal point (no trimming)
+ * '.' : trim all trailing zeros, leave decimal point
+ * '0' : trim all but the zero before the decimal point. Insert the
+ zero if it is missing.
+ * '-' : trim trailing zeros and any trailing decimal point
+ sign : boolean, optional
+ Whether to show the sign for positive values.
+ pad_left : non-negative integer, optional
+ Pad the left side of the string with whitespace until at least that
+ many characters are to the left of the decimal point.
+ pad_right : non-negative integer, optional
+ Pad the right side of the string with whitespace until at least that
+ many characters are to the right of the decimal point.
+ min_digits : non-negative integer or None, optional
+ Minimum number of digits to print. Only has an effect if `unique=True`
+ in which case additional digits past those necessary to uniquely
+ identify the value may be printed, rounding the last additional digit.
+
+ .. versionadded:: 1.21.0
+
+ Returns
+ -------
+ rep : string
+ The string representation of the floating point value
+
+ See Also
+ --------
+ format_float_scientific
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.format_float_positional(np.float32(np.pi))
+ '3.1415927'
+ >>> np.format_float_positional(np.float16(np.pi))
+ '3.14'
+ >>> np.format_float_positional(np.float16(0.3))
+ '0.3'
+ >>> np.format_float_positional(np.float16(0.3), unique=False, precision=10)
+ '0.3000488281'
+ """
+ precision = _none_or_positive_arg(precision, 'precision')
+ pad_left = _none_or_positive_arg(pad_left, 'pad_left')
+ pad_right = _none_or_positive_arg(pad_right, 'pad_right')
+ min_digits = _none_or_positive_arg(min_digits, 'min_digits')
+ if not fractional and precision == 0:
+ raise ValueError("precision must be greater than 0 if "
+ "fractional=False")
+ if min_digits > 0 and precision > 0 and min_digits > precision:
+ raise ValueError("min_digits must be less than or equal to precision")
+ return dragon4_positional(x, precision=precision, unique=unique,
+ fractional=fractional, trim=trim,
+ sign=sign, pad_left=pad_left,
+ pad_right=pad_right, min_digits=min_digits)
+
+class IntegerFormat:
+ def __init__(self, data, sign='-'):
+ if data.size > 0:
+ data_max = np.max(data)
+ data_min = np.min(data)
+ data_max_str_len = len(str(data_max))
+ if sign == ' ' and data_min < 0:
+ sign = '-'
+ if data_max >= 0 and sign in "+ ":
+ data_max_str_len += 1
+ max_str_len = max(data_max_str_len,
+ len(str(data_min)))
+ else:
+ max_str_len = 0
+ self.format = f'{{:{sign}{max_str_len}d}}'
+
+ def __call__(self, x):
+ return self.format.format(x)
+
+class BoolFormat:
+ def __init__(self, data, **kwargs):
+ # add an extra space so " True" and "False" have the same length and
+ # array elements align nicely when printed, except in 0d arrays
+ self.truestr = ' True' if data.shape != () else 'True'
+
+ def __call__(self, x):
+ return self.truestr if x else "False"
+
+
+class ComplexFloatingFormat:
+ """ Formatter for subtypes of np.complexfloating """
+ def __init__(self, x, precision, floatmode, suppress_small,
+ sign=False, *, legacy=None):
+ # for backcompatibility, accept bools
+ if isinstance(sign, bool):
+ sign = '+' if sign else '-'
+
+ floatmode_real = floatmode_imag = floatmode
+ if legacy <= 113:
+ floatmode_real = 'maxprec_equal'
+ floatmode_imag = 'maxprec'
+
+ self.real_format = FloatingFormat(
+ x.real, precision, floatmode_real, suppress_small,
+ sign=sign, legacy=legacy
+ )
+ self.imag_format = FloatingFormat(
+ x.imag, precision, floatmode_imag, suppress_small,
+ sign='+', legacy=legacy
+ )
+
+ def __call__(self, x):
+ r = self.real_format(x.real)
+ i = self.imag_format(x.imag)
+
+ # add the 'j' before the terminal whitespace in i
+ sp = len(i.rstrip())
+ i = i[:sp] + 'j' + i[sp:]
+
+ return r + i
+
+
+class _TimelikeFormat:
+ def __init__(self, data):
+ non_nat = data[~isnat(data)]
+ if len(non_nat) > 0:
+ # Max str length of non-NaT elements
+ max_str_len = max(len(self._format_non_nat(np.max(non_nat))),
+ len(self._format_non_nat(np.min(non_nat))))
+ else:
+ max_str_len = 0
+ if len(non_nat) < data.size:
+ # data contains a NaT
+ max_str_len = max(max_str_len, 5)
+ self._format = f'%{max_str_len}s'
+ self._nat = "'NaT'".rjust(max_str_len)
+
+ def _format_non_nat(self, x):
+ # override in subclass
+ raise NotImplementedError
+
+ def __call__(self, x):
+ if isnat(x):
+ return self._nat
+ else:
+ return self._format % self._format_non_nat(x)
+
+
+class DatetimeFormat(_TimelikeFormat):
+ def __init__(self, x, unit=None, timezone=None, casting='same_kind',
+ legacy=False):
+ # Get the unit from the dtype
+ if unit is None:
+ if x.dtype.kind == 'M':
+ unit = datetime_data(x.dtype)[0]
+ else:
+ unit = 's'
+
+ if timezone is None:
+ timezone = 'naive'
+ self.timezone = timezone
+ self.unit = unit
+ self.casting = casting
+ self.legacy = legacy
+
+ # must be called after the above are configured
+ super().__init__(x)
+
+ def __call__(self, x):
+ if self.legacy <= 113:
+ return self._format_non_nat(x)
+ return super().__call__(x)
+
+ def _format_non_nat(self, x):
+ return "'%s'" % datetime_as_string(x,
+ unit=self.unit,
+ timezone=self.timezone,
+ casting=self.casting)
+
+
+class TimedeltaFormat(_TimelikeFormat):
+ def _format_non_nat(self, x):
+ return str(x.astype('i8'))
+
+
+class SubArrayFormat:
+ def __init__(self, format_function, **options):
+ self.format_function = format_function
+ self.threshold = options['threshold']
+ self.edge_items = options['edgeitems']
+
+ def __call__(self, a):
+ self.summary_insert = "..." if a.size > self.threshold else ""
+ return self.format_array(a)
+
+ def format_array(self, a):
+ if np.ndim(a) == 0:
+ return self.format_function(a)
+
+ if self.summary_insert and a.shape[0] > 2 * self.edge_items:
+ formatted = (
+ [self.format_array(a_) for a_ in a[:self.edge_items]]
+ + [self.summary_insert]
+ + [self.format_array(a_) for a_ in a[-self.edge_items:]]
+ )
+ else:
+ formatted = [self.format_array(a_) for a_ in a]
+
+ return "[" + ", ".join(formatted) + "]"
+
+
+class StructuredVoidFormat:
+ """
+ Formatter for structured np.void objects.
+
+ This does not work on structured alias types like
+ np.dtype(('i4', 'i2,i2')), as alias scalars lose their field information,
+ and the implementation relies upon np.void.__getitem__.
+ """
+ def __init__(self, format_functions):
+ self.format_functions = format_functions
+
+ @classmethod
+ def from_data(cls, data, **options):
+ """
+ This is a second way to initialize StructuredVoidFormat,
+ using the raw data as input. Added to avoid changing
+ the signature of __init__.
+ """
+ format_functions = []
+ for field_name in data.dtype.names:
+ format_function = _get_format_function(data[field_name], **options)
+ if data.dtype[field_name].shape != ():
+ format_function = SubArrayFormat(format_function, **options)
+ format_functions.append(format_function)
+ return cls(format_functions)
+
+ def __call__(self, x):
+ str_fields = [
+ format_function(field)
+ for field, format_function in zip(x, self.format_functions)
+ ]
+ if len(str_fields) == 1:
+ return f"({str_fields[0]},)"
+ else:
+ return f"({', '.join(str_fields)})"
+
+
+def _void_scalar_to_string(x, is_repr=True):
+ """
+ Implements the repr for structured-void scalars. It is called from the
+ scalartypes.c.src code, and is placed here because it uses the elementwise
+ formatters defined above.
+ """
+ options = format_options.get().copy()
+
+ if options["legacy"] <= 125:
+ return StructuredVoidFormat.from_data(array(x), **options)(x)
+
+ if options.get('formatter') is None:
+ options['formatter'] = {}
+ options['formatter'].setdefault('float_kind', str)
+ val_repr = StructuredVoidFormat.from_data(array(x), **options)(x)
+ if not is_repr:
+ return val_repr
+ cls = type(x)
+ cls_fqn = cls.__module__.replace("numpy", "np") + "." + cls.__name__
+ void_dtype = np.dtype((np.void, x.dtype))
+ return f"{cls_fqn}({val_repr}, dtype={void_dtype!s})"
+
+
+_typelessdata = [int_, float64, complex128, _nt.bool]
+
+
+def dtype_is_implied(dtype):
+ """
+ Determine if the given dtype is implied by the representation
+ of its values.
+
+ Parameters
+ ----------
+ dtype : dtype
+ Data type
+
+ Returns
+ -------
+ implied : bool
+ True if the dtype is implied by the representation of its values.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np._core.arrayprint.dtype_is_implied(int)
+ True
+ >>> np.array([1, 2, 3], int)
+ array([1, 2, 3])
+ >>> np._core.arrayprint.dtype_is_implied(np.int8)
+ False
+ >>> np.array([1, 2, 3], np.int8)
+ array([1, 2, 3], dtype=int8)
+ """
+ dtype = np.dtype(dtype)
+ if format_options.get()['legacy'] <= 113 and dtype.type == np.bool:
+ return False
+
+ # not just void types can be structured, and names are not part of the repr
+ if dtype.names is not None:
+ return False
+
+ # should care about endianness *unless size is 1* (e.g., int8, bool)
+ if not dtype.isnative:
+ return False
+
+ return dtype.type in _typelessdata
+
+
+def dtype_short_repr(dtype):
+ """
+ Convert a dtype to a short form which evaluates to the same dtype.
+
+ The intent is roughly that the following holds
+
+ >>> from numpy import *
+ >>> dt = np.int64([1, 2]).dtype
+ >>> assert eval(dtype_short_repr(dt)) == dt
+ """
+ if type(dtype).__repr__ != np.dtype.__repr__:
+ # TODO: Custom repr for user DTypes, logic should likely move.
+ return repr(dtype)
+ if dtype.names is not None:
+ # structured dtypes give a list or tuple repr
+ return str(dtype)
+ elif issubclass(dtype.type, flexible):
+ # handle these separately so they don't give garbage like str256
+ return f"'{str(dtype)}'"
+
+ typename = dtype.name
+ if not dtype.isnative:
+ # deal with cases like dtype(' 210
+ and arr.size > current_options['threshold'])):
+ extras.append(f"shape={arr.shape}")
+ if not dtype_is_implied(arr.dtype) or arr.size == 0:
+ extras.append(f"dtype={dtype_short_repr(arr.dtype)}")
+
+ if not extras:
+ return prefix + lst + ")"
+
+ arr_str = prefix + lst + ","
+ extra_str = ", ".join(extras) + ")"
+ # compute whether we should put extras on a new line: Do so if adding the
+ # extras would extend the last line past max_line_width.
+ # Note: This line gives the correct result even when rfind returns -1.
+ last_line_len = len(arr_str) - (arr_str.rfind('\n') + 1)
+ spacer = " "
+ if current_options['legacy'] <= 113:
+ if issubclass(arr.dtype.type, flexible):
+ spacer = '\n' + ' ' * len(prefix)
+ elif last_line_len + len(extra_str) + 1 > max_line_width:
+ spacer = '\n' + ' ' * len(prefix)
+
+ return arr_str + spacer + extra_str
+
+
+def _array_repr_dispatcher(
+ arr, max_line_width=None, precision=None, suppress_small=None):
+ return (arr,)
+
+
+@array_function_dispatch(_array_repr_dispatcher, module='numpy')
+def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
+ """
+ Return the string representation of an array.
+
+ Parameters
+ ----------
+ arr : ndarray
+ Input array.
+ max_line_width : int, optional
+ Inserts newlines if text is longer than `max_line_width`.
+ Defaults to ``numpy.get_printoptions()['linewidth']``.
+ precision : int, optional
+ Floating point precision.
+ Defaults to ``numpy.get_printoptions()['precision']``.
+ suppress_small : bool, optional
+ Represent numbers "very close" to zero as zero; default is False.
+ Very close is defined by precision: if the precision is 8, e.g.,
+ numbers smaller (in absolute value) than 5e-9 are represented as
+ zero.
+ Defaults to ``numpy.get_printoptions()['suppress']``.
+
+ Returns
+ -------
+ string : str
+ The string representation of an array.
+
+ See Also
+ --------
+ array_str, array2string, set_printoptions
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.array_repr(np.array([1,2]))
+ 'array([1, 2])'
+ >>> np.array_repr(np.ma.array([0.]))
+ 'MaskedArray([0.])'
+ >>> np.array_repr(np.array([], np.int32))
+ 'array([], dtype=int32)'
+
+ >>> x = np.array([1e-6, 4e-7, 2, 3])
+ >>> np.array_repr(x, precision=6, suppress_small=True)
+ 'array([0.000001, 0. , 2. , 3. ])'
+
+ """
+ return _array_repr_implementation(
+ arr, max_line_width, precision, suppress_small)
+
+
+@_recursive_guard()
+def _guarded_repr_or_str(v):
+ if isinstance(v, bytes):
+ return repr(v)
+ return str(v)
+
+
+def _array_str_implementation(
+ a, max_line_width=None, precision=None, suppress_small=None,
+ array2string=array2string):
+ """Internal version of array_str() that allows overriding array2string."""
+ if (format_options.get()['legacy'] <= 113 and
+ a.shape == () and not a.dtype.names):
+ return str(a.item())
+
+ # the str of 0d arrays is a special case: It should appear like a scalar,
+ # so floats are not truncated by `precision`, and strings are not wrapped
+ # in quotes. So we return the str of the scalar value.
+ if a.shape == ():
+ # obtain a scalar and call str on it, avoiding problems for subclasses
+ # for which indexing with () returns a 0d instead of a scalar by using
+ # ndarray's getindex. Also guard against recursive 0d object arrays.
+ return _guarded_repr_or_str(np.ndarray.__getitem__(a, ()))
+
+ return array2string(a, max_line_width, precision, suppress_small, ' ', "")
+
+
+def _array_str_dispatcher(
+ a, max_line_width=None, precision=None, suppress_small=None):
+ return (a,)
+
+
+@array_function_dispatch(_array_str_dispatcher, module='numpy')
+def array_str(a, max_line_width=None, precision=None, suppress_small=None):
+ """
+ Return a string representation of the data in an array.
+
+ The data in the array is returned as a single string. This function is
+ similar to `array_repr`, the difference being that `array_repr` also
+ returns information on the kind of array and its data type.
+
+ Parameters
+ ----------
+ a : ndarray
+ Input array.
+ max_line_width : int, optional
+ Inserts newlines if text is longer than `max_line_width`.
+ Defaults to ``numpy.get_printoptions()['linewidth']``.
+ precision : int, optional
+ Floating point precision.
+ Defaults to ``numpy.get_printoptions()['precision']``.
+ suppress_small : bool, optional
+ Represent numbers "very close" to zero as zero; default is False.
+ Very close is defined by precision: if the precision is 8, e.g.,
+ numbers smaller (in absolute value) than 5e-9 are represented as
+ zero.
+ Defaults to ``numpy.get_printoptions()['suppress']``.
+
+ See Also
+ --------
+ array2string, array_repr, set_printoptions
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.array_str(np.arange(3))
+ '[0 1 2]'
+
+ """
+ return _array_str_implementation(
+ a, max_line_width, precision, suppress_small)
+
+
+# needed if __array_function__ is disabled
+_array2string_impl = getattr(array2string, '__wrapped__', array2string)
+_default_array_str = functools.partial(_array_str_implementation,
+ array2string=_array2string_impl)
+_default_array_repr = functools.partial(_array_repr_implementation,
+ array2string=_array2string_impl)
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/arrayprint.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/arrayprint.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..307f844634ca02b3ee17f426f8f17d38024fd444
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/arrayprint.pyi
@@ -0,0 +1,158 @@
+from collections.abc import Callable
+
+# Using a private class is by no means ideal, but it is simply a consequence
+# of a `contextlib.context` returning an instance of aforementioned class
+from contextlib import _GeneratorContextManager
+from typing import (
+ Any,
+ Final,
+ Literal,
+ SupportsIndex,
+ TypeAlias,
+ TypedDict,
+ type_check_only,
+)
+
+import numpy as np
+from numpy._typing import NDArray, _CharLike_co, _FloatLike_co
+
+__all__ = [
+ "array2string",
+ "array_repr",
+ "array_str",
+ "format_float_positional",
+ "format_float_scientific",
+ "get_printoptions",
+ "printoptions",
+ "set_printoptions",
+]
+
+###
+
+_FloatMode: TypeAlias = Literal["fixed", "unique", "maxprec", "maxprec_equal"]
+_LegacyNoStyle: TypeAlias = Literal["1.21", "1.25", "2.1", False]
+_Legacy: TypeAlias = Literal["1.13", _LegacyNoStyle]
+_Sign: TypeAlias = Literal["-", "+", " "]
+_Trim: TypeAlias = Literal["k", ".", "0", "-"]
+_ReprFunc: TypeAlias = Callable[[NDArray[Any]], str]
+
+@type_check_only
+class _FormatDict(TypedDict, total=False):
+ bool: Callable[[np.bool], str]
+ int: Callable[[np.integer], str]
+ timedelta: Callable[[np.timedelta64], str]
+ datetime: Callable[[np.datetime64], str]
+ float: Callable[[np.floating], str]
+ longfloat: Callable[[np.longdouble], str]
+ complexfloat: Callable[[np.complexfloating], str]
+ longcomplexfloat: Callable[[np.clongdouble], str]
+ void: Callable[[np.void], str]
+ numpystr: Callable[[_CharLike_co], str]
+ object: Callable[[object], str]
+ all: Callable[[object], str]
+ int_kind: Callable[[np.integer], str]
+ float_kind: Callable[[np.floating], str]
+ complex_kind: Callable[[np.complexfloating], str]
+ str_kind: Callable[[_CharLike_co], str]
+
+@type_check_only
+class _FormatOptions(TypedDict):
+ precision: int
+ threshold: int
+ edgeitems: int
+ linewidth: int
+ suppress: bool
+ nanstr: str
+ infstr: str
+ formatter: _FormatDict | None
+ sign: _Sign
+ floatmode: _FloatMode
+ legacy: _Legacy
+
+###
+
+__docformat__: Final = "restructuredtext" # undocumented
+
+def set_printoptions(
+ precision: SupportsIndex | None = None,
+ threshold: int | None = None,
+ edgeitems: int | None = None,
+ linewidth: int | None = None,
+ suppress: bool | None = None,
+ nanstr: str | None = None,
+ infstr: str | None = None,
+ formatter: _FormatDict | None = None,
+ sign: _Sign | None = None,
+ floatmode: _FloatMode | None = None,
+ *,
+ legacy: _Legacy | None = None,
+ override_repr: _ReprFunc | None = None,
+) -> None: ...
+def get_printoptions() -> _FormatOptions: ...
+
+# public numpy export
+def array2string(
+ a: NDArray[Any],
+ max_line_width: int | None = None,
+ precision: SupportsIndex | None = None,
+ suppress_small: bool | None = None,
+ separator: str = " ",
+ prefix: str = "",
+ *,
+ formatter: _FormatDict | None = None,
+ threshold: int | None = None,
+ edgeitems: int | None = None,
+ sign: _Sign | None = None,
+ floatmode: _FloatMode | None = None,
+ suffix: str = "",
+ legacy: _Legacy | None = None,
+) -> str: ...
+
+def format_float_scientific(
+ x: _FloatLike_co,
+ precision: int | None = None,
+ unique: bool = True,
+ trim: _Trim = "k",
+ sign: bool = False,
+ pad_left: int | None = None,
+ exp_digits: int | None = None,
+ min_digits: int | None = None,
+) -> str: ...
+def format_float_positional(
+ x: _FloatLike_co,
+ precision: int | None = None,
+ unique: bool = True,
+ fractional: bool = True,
+ trim: _Trim = "k",
+ sign: bool = False,
+ pad_left: int | None = None,
+ pad_right: int | None = None,
+ min_digits: int | None = None,
+) -> str: ...
+def array_repr(
+ arr: NDArray[Any],
+ max_line_width: int | None = None,
+ precision: SupportsIndex | None = None,
+ suppress_small: bool | None = None,
+) -> str: ...
+def array_str(
+ a: NDArray[Any],
+ max_line_width: int | None = None,
+ precision: SupportsIndex | None = None,
+ suppress_small: bool | None = None,
+) -> str: ...
+def printoptions(
+ precision: SupportsIndex | None = ...,
+ threshold: int | None = ...,
+ edgeitems: int | None = ...,
+ linewidth: int | None = ...,
+ suppress: bool | None = ...,
+ nanstr: str | None = ...,
+ infstr: str | None = ...,
+ formatter: _FormatDict | None = ...,
+ sign: _Sign | None = None,
+ floatmode: _FloatMode | None = None,
+ *,
+ legacy: _Legacy | None = None,
+ override_repr: _ReprFunc | None = None,
+) -> _GeneratorContextManager[_FormatOptions]: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/cversions.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/cversions.py
new file mode 100644
index 0000000000000000000000000000000000000000..00159c3a8031d8ccd44b226db42090f97014cd9f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/cversions.py
@@ -0,0 +1,13 @@
+"""Simple script to compute the api hash of the current API.
+
+The API has is defined by numpy_api_order and ufunc_api_order.
+
+"""
+from os.path import dirname
+
+from code_generators.genapi import fullapi_hash
+from code_generators.numpy_api import full_api
+
+if __name__ == '__main__':
+ curdir = dirname(__file__)
+ print(fullapi_hash(full_api))
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/defchararray.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/defchararray.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a8750507f419738bfcaed4263090c4f3a7bc591
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/defchararray.py
@@ -0,0 +1,1414 @@
+"""
+This module contains a set of functions for vectorized string
+operations and methods.
+
+.. note::
+ The `chararray` class exists for backwards compatibility with
+ Numarray, it is not recommended for new development. Starting from numpy
+ 1.4, if one needs arrays of strings, it is recommended to use arrays of
+ `dtype` `object_`, `bytes_` or `str_`, and use the free functions
+ in the `numpy.char` module for fast vectorized string operations.
+
+Some methods will only be available if the corresponding string method is
+available in your version of Python.
+
+The preferred alias for `defchararray` is `numpy.char`.
+
+"""
+import functools
+
+import numpy as np
+from numpy._core import overrides
+from numpy._core.multiarray import compare_chararrays
+from numpy._core.strings import (
+ _join as join,
+ _rsplit as rsplit,
+ _split as split,
+ _splitlines as splitlines,
+)
+from numpy._utils import set_module
+from numpy.strings import *
+from numpy.strings import (
+ multiply as strings_multiply,
+ partition as strings_partition,
+ rpartition as strings_rpartition,
+)
+
+from .numeric import array as narray, asarray as asnarray, ndarray
+from .numerictypes import bytes_, character, str_
+
+__all__ = [
+ 'equal', 'not_equal', 'greater_equal', 'less_equal',
+ 'greater', 'less', 'str_len', 'add', 'multiply', 'mod', 'capitalize',
+ 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
+ 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
+ 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
+ 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
+ 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
+ 'title', 'translate', 'upper', 'zfill', 'isnumeric', 'isdecimal',
+ 'array', 'asarray', 'compare_chararrays', 'chararray'
+ ]
+
+
+array_function_dispatch = functools.partial(
+ overrides.array_function_dispatch, module='numpy.char')
+
+
+def _binary_op_dispatcher(x1, x2):
+ return (x1, x2)
+
+
+@array_function_dispatch(_binary_op_dispatcher)
+def equal(x1, x2):
+ """
+ Return (x1 == x2) element-wise.
+
+ Unlike `numpy.equal`, this comparison is performed by first
+ stripping whitespace characters from the end of the string. This
+ behavior is provided for backward-compatibility with numarray.
+
+ Parameters
+ ----------
+ x1, x2 : array_like of str or unicode
+ Input arrays of the same shape.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> y = "aa "
+ >>> x = "aa"
+ >>> np.char.equal(x, y)
+ array(True)
+
+ See Also
+ --------
+ not_equal, greater_equal, less_equal, greater, less
+ """
+ return compare_chararrays(x1, x2, '==', True)
+
+
+@array_function_dispatch(_binary_op_dispatcher)
+def not_equal(x1, x2):
+ """
+ Return (x1 != x2) element-wise.
+
+ Unlike `numpy.not_equal`, this comparison is performed by first
+ stripping whitespace characters from the end of the string. This
+ behavior is provided for backward-compatibility with numarray.
+
+ Parameters
+ ----------
+ x1, x2 : array_like of str or unicode
+ Input arrays of the same shape.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools.
+
+ See Also
+ --------
+ equal, greater_equal, less_equal, greater, less
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x1 = np.array(['a', 'b', 'c'])
+ >>> np.char.not_equal(x1, 'b')
+ array([ True, False, True])
+
+ """
+ return compare_chararrays(x1, x2, '!=', True)
+
+
+@array_function_dispatch(_binary_op_dispatcher)
+def greater_equal(x1, x2):
+ """
+ Return (x1 >= x2) element-wise.
+
+ Unlike `numpy.greater_equal`, this comparison is performed by
+ first stripping whitespace characters from the end of the string.
+ This behavior is provided for backward-compatibility with
+ numarray.
+
+ Parameters
+ ----------
+ x1, x2 : array_like of str or unicode
+ Input arrays of the same shape.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools.
+
+ See Also
+ --------
+ equal, not_equal, less_equal, greater, less
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x1 = np.array(['a', 'b', 'c'])
+ >>> np.char.greater_equal(x1, 'b')
+ array([False, True, True])
+
+ """
+ return compare_chararrays(x1, x2, '>=', True)
+
+
+@array_function_dispatch(_binary_op_dispatcher)
+def less_equal(x1, x2):
+ """
+ Return (x1 <= x2) element-wise.
+
+ Unlike `numpy.less_equal`, this comparison is performed by first
+ stripping whitespace characters from the end of the string. This
+ behavior is provided for backward-compatibility with numarray.
+
+ Parameters
+ ----------
+ x1, x2 : array_like of str or unicode
+ Input arrays of the same shape.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools.
+
+ See Also
+ --------
+ equal, not_equal, greater_equal, greater, less
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x1 = np.array(['a', 'b', 'c'])
+ >>> np.char.less_equal(x1, 'b')
+ array([ True, True, False])
+
+ """
+ return compare_chararrays(x1, x2, '<=', True)
+
+
+@array_function_dispatch(_binary_op_dispatcher)
+def greater(x1, x2):
+ """
+ Return (x1 > x2) element-wise.
+
+ Unlike `numpy.greater`, this comparison is performed by first
+ stripping whitespace characters from the end of the string. This
+ behavior is provided for backward-compatibility with numarray.
+
+ Parameters
+ ----------
+ x1, x2 : array_like of str or unicode
+ Input arrays of the same shape.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools.
+
+ See Also
+ --------
+ equal, not_equal, greater_equal, less_equal, less
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x1 = np.array(['a', 'b', 'c'])
+ >>> np.char.greater(x1, 'b')
+ array([False, False, True])
+
+ """
+ return compare_chararrays(x1, x2, '>', True)
+
+
+@array_function_dispatch(_binary_op_dispatcher)
+def less(x1, x2):
+ """
+ Return (x1 < x2) element-wise.
+
+ Unlike `numpy.greater`, this comparison is performed by first
+ stripping whitespace characters from the end of the string. This
+ behavior is provided for backward-compatibility with numarray.
+
+ Parameters
+ ----------
+ x1, x2 : array_like of str or unicode
+ Input arrays of the same shape.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools.
+
+ See Also
+ --------
+ equal, not_equal, greater_equal, less_equal, greater
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x1 = np.array(['a', 'b', 'c'])
+ >>> np.char.less(x1, 'b')
+ array([True, False, False])
+
+ """
+ return compare_chararrays(x1, x2, '<', True)
+
+
+@set_module("numpy.char")
+def multiply(a, i):
+ """
+ Return (a * i), that is string multiple concatenation,
+ element-wise.
+
+ Values in ``i`` of less than 0 are treated as 0 (which yields an
+ empty string).
+
+ Parameters
+ ----------
+ a : array_like, with `np.bytes_` or `np.str_` dtype
+
+ i : array_like, with any integer dtype
+
+ Returns
+ -------
+ out : ndarray
+ Output array of str or unicode, depending on input types
+
+ Notes
+ -----
+ This is a thin wrapper around np.strings.multiply that raises
+ `ValueError` when ``i`` is not an integer. It only
+ exists for backwards-compatibility.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["a", "b", "c"])
+ >>> np.strings.multiply(a, 3)
+ array(['aaa', 'bbb', 'ccc'], dtype='>> i = np.array([1, 2, 3])
+ >>> np.strings.multiply(a, i)
+ array(['a', 'bb', 'ccc'], dtype='>> np.strings.multiply(np.array(['a']), i)
+ array(['a', 'aa', 'aaa'], dtype='>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3))
+ >>> np.strings.multiply(a, 3)
+ array([['aaa', 'bbb', 'ccc'],
+ ['ddd', 'eee', 'fff']], dtype='>> np.strings.multiply(a, i)
+ array([['a', 'bb', 'ccc'],
+ ['d', 'ee', 'fff']], dtype='>> import numpy as np
+ >>> x = np.array(["Numpy is nice!"])
+ >>> np.char.partition(x, " ")
+ array([['Numpy', ' ', 'is nice!']], dtype='>> import numpy as np
+ >>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
+ >>> np.char.rpartition(a, 'A')
+ array([['aAaAa', 'A', ''],
+ [' a', 'A', ' '],
+ ['abB', 'A', 'Bba']], dtype='= 2`` and ``order='F'``, in which case `strides`
+ is in "Fortran order".
+
+ Methods
+ -------
+ astype
+ argsort
+ copy
+ count
+ decode
+ dump
+ dumps
+ encode
+ endswith
+ expandtabs
+ fill
+ find
+ flatten
+ getfield
+ index
+ isalnum
+ isalpha
+ isdecimal
+ isdigit
+ islower
+ isnumeric
+ isspace
+ istitle
+ isupper
+ item
+ join
+ ljust
+ lower
+ lstrip
+ nonzero
+ put
+ ravel
+ repeat
+ replace
+ reshape
+ resize
+ rfind
+ rindex
+ rjust
+ rsplit
+ rstrip
+ searchsorted
+ setfield
+ setflags
+ sort
+ split
+ splitlines
+ squeeze
+ startswith
+ strip
+ swapaxes
+ swapcase
+ take
+ title
+ tofile
+ tolist
+ translate
+ transpose
+ upper
+ view
+ zfill
+
+ Parameters
+ ----------
+ shape : tuple
+ Shape of the array.
+ itemsize : int, optional
+ Length of each array element, in number of characters. Default is 1.
+ unicode : bool, optional
+ Are the array elements of type unicode (True) or string (False).
+ Default is False.
+ buffer : object exposing the buffer interface or str, optional
+ Memory address of the start of the array data. Default is None,
+ in which case a new array is created.
+ offset : int, optional
+ Fixed stride displacement from the beginning of an axis?
+ Default is 0. Needs to be >=0.
+ strides : array_like of ints, optional
+ Strides for the array (see `~numpy.ndarray.strides` for
+ full description). Default is None.
+ order : {'C', 'F'}, optional
+ The order in which the array data is stored in memory: 'C' ->
+ "row major" order (the default), 'F' -> "column major"
+ (Fortran) order.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> charar = np.char.chararray((3, 3))
+ >>> charar[:] = 'a'
+ >>> charar
+ chararray([[b'a', b'a', b'a'],
+ [b'a', b'a', b'a'],
+ [b'a', b'a', b'a']], dtype='|S1')
+
+ >>> charar = np.char.chararray(charar.shape, itemsize=5)
+ >>> charar[:] = 'abc'
+ >>> charar
+ chararray([[b'abc', b'abc', b'abc'],
+ [b'abc', b'abc', b'abc'],
+ [b'abc', b'abc', b'abc']], dtype='|S5')
+
+ """
+ def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None,
+ offset=0, strides=None, order='C'):
+ if unicode:
+ dtype = str_
+ else:
+ dtype = bytes_
+
+ # force itemsize to be a Python int, since using NumPy integer
+ # types results in itemsize.itemsize being used as the size of
+ # strings in the new array.
+ itemsize = int(itemsize)
+
+ if isinstance(buffer, str):
+ # unicode objects do not have the buffer interface
+ filler = buffer
+ buffer = None
+ else:
+ filler = None
+
+ if buffer is None:
+ self = ndarray.__new__(subtype, shape, (dtype, itemsize),
+ order=order)
+ else:
+ self = ndarray.__new__(subtype, shape, (dtype, itemsize),
+ buffer=buffer,
+ offset=offset, strides=strides,
+ order=order)
+ if filler is not None:
+ self[...] = filler
+
+ return self
+
+ def __array_wrap__(self, arr, context=None, return_scalar=False):
+ # When calling a ufunc (and some other functions), we return a
+ # chararray if the ufunc output is a string-like array,
+ # or an ndarray otherwise
+ if arr.dtype.char in "SUbc":
+ return arr.view(type(self))
+ return arr
+
+ def __array_finalize__(self, obj):
+ # The b is a special case because it is used for reconstructing.
+ if self.dtype.char not in 'VSUbc':
+ raise ValueError("Can only create a chararray from string data.")
+
+ def __getitem__(self, obj):
+ val = ndarray.__getitem__(self, obj)
+ if isinstance(val, character):
+ return val.rstrip()
+ return val
+
+ # IMPLEMENTATION NOTE: Most of the methods of this class are
+ # direct delegations to the free functions in this module.
+ # However, those that return an array of strings should instead
+ # return a chararray, so some extra wrapping is required.
+
+ def __eq__(self, other):
+ """
+ Return (self == other) element-wise.
+
+ See Also
+ --------
+ equal
+ """
+ return equal(self, other)
+
+ def __ne__(self, other):
+ """
+ Return (self != other) element-wise.
+
+ See Also
+ --------
+ not_equal
+ """
+ return not_equal(self, other)
+
+ def __ge__(self, other):
+ """
+ Return (self >= other) element-wise.
+
+ See Also
+ --------
+ greater_equal
+ """
+ return greater_equal(self, other)
+
+ def __le__(self, other):
+ """
+ Return (self <= other) element-wise.
+
+ See Also
+ --------
+ less_equal
+ """
+ return less_equal(self, other)
+
+ def __gt__(self, other):
+ """
+ Return (self > other) element-wise.
+
+ See Also
+ --------
+ greater
+ """
+ return greater(self, other)
+
+ def __lt__(self, other):
+ """
+ Return (self < other) element-wise.
+
+ See Also
+ --------
+ less
+ """
+ return less(self, other)
+
+ def __add__(self, other):
+ """
+ Return (self + other), that is string concatenation,
+ element-wise for a pair of array_likes of str or unicode.
+
+ See Also
+ --------
+ add
+ """
+ return add(self, other)
+
+ def __radd__(self, other):
+ """
+ Return (other + self), that is string concatenation,
+ element-wise for a pair of array_likes of `bytes_` or `str_`.
+
+ See Also
+ --------
+ add
+ """
+ return add(other, self)
+
+ def __mul__(self, i):
+ """
+ Return (self * i), that is string multiple concatenation,
+ element-wise.
+
+ See Also
+ --------
+ multiply
+ """
+ return asarray(multiply(self, i))
+
+ def __rmul__(self, i):
+ """
+ Return (self * i), that is string multiple concatenation,
+ element-wise.
+
+ See Also
+ --------
+ multiply
+ """
+ return asarray(multiply(self, i))
+
+ def __mod__(self, i):
+ """
+ Return (self % i), that is pre-Python 2.6 string formatting
+ (interpolation), element-wise for a pair of array_likes of `bytes_`
+ or `str_`.
+
+ See Also
+ --------
+ mod
+ """
+ return asarray(mod(self, i))
+
+ def __rmod__(self, other):
+ return NotImplemented
+
+ def argsort(self, axis=-1, kind=None, order=None, *, stable=None):
+ """
+ Return the indices that sort the array lexicographically.
+
+ For full documentation see `numpy.argsort`, for which this method is
+ in fact merely a "thin wrapper."
+
+ Examples
+ --------
+ >>> c = np.array(['a1b c', '1b ca', 'b ca1', 'Ca1b'], 'S5')
+ >>> c = c.view(np.char.chararray); c
+ chararray(['a1b c', '1b ca', 'b ca1', 'Ca1b'],
+ dtype='|S5')
+ >>> c[c.argsort()]
+ chararray(['1b ca', 'Ca1b', 'a1b c', 'b ca1'],
+ dtype='|S5')
+
+ """
+ return self.__array__().argsort(axis, kind, order, stable=stable)
+ argsort.__doc__ = ndarray.argsort.__doc__
+
+ def capitalize(self):
+ """
+ Return a copy of `self` with only the first character of each element
+ capitalized.
+
+ See Also
+ --------
+ char.capitalize
+
+ """
+ return asarray(capitalize(self))
+
+ def center(self, width, fillchar=' '):
+ """
+ Return a copy of `self` with its elements centered in a
+ string of length `width`.
+
+ See Also
+ --------
+ center
+ """
+ return asarray(center(self, width, fillchar))
+
+ def count(self, sub, start=0, end=None):
+ """
+ Returns an array with the number of non-overlapping occurrences of
+ substring `sub` in the range [`start`, `end`].
+
+ See Also
+ --------
+ char.count
+
+ """
+ return count(self, sub, start, end)
+
+ def decode(self, encoding=None, errors=None):
+ """
+ Calls ``bytes.decode`` element-wise.
+
+ See Also
+ --------
+ char.decode
+
+ """
+ return decode(self, encoding, errors)
+
+ def encode(self, encoding=None, errors=None):
+ """
+ Calls :meth:`str.encode` element-wise.
+
+ See Also
+ --------
+ char.encode
+
+ """
+ return encode(self, encoding, errors)
+
+ def endswith(self, suffix, start=0, end=None):
+ """
+ Returns a boolean array which is `True` where the string element
+ in `self` ends with `suffix`, otherwise `False`.
+
+ See Also
+ --------
+ char.endswith
+
+ """
+ return endswith(self, suffix, start, end)
+
+ def expandtabs(self, tabsize=8):
+ """
+ Return a copy of each string element where all tab characters are
+ replaced by one or more spaces.
+
+ See Also
+ --------
+ char.expandtabs
+
+ """
+ return asarray(expandtabs(self, tabsize))
+
+ def find(self, sub, start=0, end=None):
+ """
+ For each element, return the lowest index in the string where
+ substring `sub` is found.
+
+ See Also
+ --------
+ char.find
+
+ """
+ return find(self, sub, start, end)
+
+ def index(self, sub, start=0, end=None):
+ """
+ Like `find`, but raises :exc:`ValueError` when the substring is not
+ found.
+
+ See Also
+ --------
+ char.index
+
+ """
+ return index(self, sub, start, end)
+
+ def isalnum(self):
+ """
+ Returns true for each element if all characters in the string
+ are alphanumeric and there is at least one character, false
+ otherwise.
+
+ See Also
+ --------
+ char.isalnum
+
+ """
+ return isalnum(self)
+
+ def isalpha(self):
+ """
+ Returns true for each element if all characters in the string
+ are alphabetic and there is at least one character, false
+ otherwise.
+
+ See Also
+ --------
+ char.isalpha
+
+ """
+ return isalpha(self)
+
+ def isdigit(self):
+ """
+ Returns true for each element if all characters in the string are
+ digits and there is at least one character, false otherwise.
+
+ See Also
+ --------
+ char.isdigit
+
+ """
+ return isdigit(self)
+
+ def islower(self):
+ """
+ Returns true for each element if all cased characters in the
+ string are lowercase and there is at least one cased character,
+ false otherwise.
+
+ See Also
+ --------
+ char.islower
+
+ """
+ return islower(self)
+
+ def isspace(self):
+ """
+ Returns true for each element if there are only whitespace
+ characters in the string and there is at least one character,
+ false otherwise.
+
+ See Also
+ --------
+ char.isspace
+
+ """
+ return isspace(self)
+
+ def istitle(self):
+ """
+ Returns true for each element if the element is a titlecased
+ string and there is at least one character, false otherwise.
+
+ See Also
+ --------
+ char.istitle
+
+ """
+ return istitle(self)
+
+ def isupper(self):
+ """
+ Returns true for each element if all cased characters in the
+ string are uppercase and there is at least one character, false
+ otherwise.
+
+ See Also
+ --------
+ char.isupper
+
+ """
+ return isupper(self)
+
+ def join(self, seq):
+ """
+ Return a string which is the concatenation of the strings in the
+ sequence `seq`.
+
+ See Also
+ --------
+ char.join
+
+ """
+ return join(self, seq)
+
+ def ljust(self, width, fillchar=' '):
+ """
+ Return an array with the elements of `self` left-justified in a
+ string of length `width`.
+
+ See Also
+ --------
+ char.ljust
+
+ """
+ return asarray(ljust(self, width, fillchar))
+
+ def lower(self):
+ """
+ Return an array with the elements of `self` converted to
+ lowercase.
+
+ See Also
+ --------
+ char.lower
+
+ """
+ return asarray(lower(self))
+
+ def lstrip(self, chars=None):
+ """
+ For each element in `self`, return a copy with the leading characters
+ removed.
+
+ See Also
+ --------
+ char.lstrip
+
+ """
+ return lstrip(self, chars)
+
+ def partition(self, sep):
+ """
+ Partition each element in `self` around `sep`.
+
+ See Also
+ --------
+ partition
+ """
+ return asarray(partition(self, sep))
+
+ def replace(self, old, new, count=None):
+ """
+ For each element in `self`, return a copy of the string with all
+ occurrences of substring `old` replaced by `new`.
+
+ See Also
+ --------
+ char.replace
+
+ """
+ return replace(self, old, new, count if count is not None else -1)
+
+ def rfind(self, sub, start=0, end=None):
+ """
+ For each element in `self`, return the highest index in the string
+ where substring `sub` is found, such that `sub` is contained
+ within [`start`, `end`].
+
+ See Also
+ --------
+ char.rfind
+
+ """
+ return rfind(self, sub, start, end)
+
+ def rindex(self, sub, start=0, end=None):
+ """
+ Like `rfind`, but raises :exc:`ValueError` when the substring `sub` is
+ not found.
+
+ See Also
+ --------
+ char.rindex
+
+ """
+ return rindex(self, sub, start, end)
+
+ def rjust(self, width, fillchar=' '):
+ """
+ Return an array with the elements of `self`
+ right-justified in a string of length `width`.
+
+ See Also
+ --------
+ char.rjust
+
+ """
+ return asarray(rjust(self, width, fillchar))
+
+ def rpartition(self, sep):
+ """
+ Partition each element in `self` around `sep`.
+
+ See Also
+ --------
+ rpartition
+ """
+ return asarray(rpartition(self, sep))
+
+ def rsplit(self, sep=None, maxsplit=None):
+ """
+ For each element in `self`, return a list of the words in
+ the string, using `sep` as the delimiter string.
+
+ See Also
+ --------
+ char.rsplit
+
+ """
+ return rsplit(self, sep, maxsplit)
+
+ def rstrip(self, chars=None):
+ """
+ For each element in `self`, return a copy with the trailing
+ characters removed.
+
+ See Also
+ --------
+ char.rstrip
+
+ """
+ return rstrip(self, chars)
+
+ def split(self, sep=None, maxsplit=None):
+ """
+ For each element in `self`, return a list of the words in the
+ string, using `sep` as the delimiter string.
+
+ See Also
+ --------
+ char.split
+
+ """
+ return split(self, sep, maxsplit)
+
+ def splitlines(self, keepends=None):
+ """
+ For each element in `self`, return a list of the lines in the
+ element, breaking at line boundaries.
+
+ See Also
+ --------
+ char.splitlines
+
+ """
+ return splitlines(self, keepends)
+
+ def startswith(self, prefix, start=0, end=None):
+ """
+ Returns a boolean array which is `True` where the string element
+ in `self` starts with `prefix`, otherwise `False`.
+
+ See Also
+ --------
+ char.startswith
+
+ """
+ return startswith(self, prefix, start, end)
+
+ def strip(self, chars=None):
+ """
+ For each element in `self`, return a copy with the leading and
+ trailing characters removed.
+
+ See Also
+ --------
+ char.strip
+
+ """
+ return strip(self, chars)
+
+ def swapcase(self):
+ """
+ For each element in `self`, return a copy of the string with
+ uppercase characters converted to lowercase and vice versa.
+
+ See Also
+ --------
+ char.swapcase
+
+ """
+ return asarray(swapcase(self))
+
+ def title(self):
+ """
+ For each element in `self`, return a titlecased version of the
+ string: words start with uppercase characters, all remaining cased
+ characters are lowercase.
+
+ See Also
+ --------
+ char.title
+
+ """
+ return asarray(title(self))
+
+ def translate(self, table, deletechars=None):
+ """
+ For each element in `self`, return a copy of the string where
+ all characters occurring in the optional argument
+ `deletechars` are removed, and the remaining characters have
+ been mapped through the given translation table.
+
+ See Also
+ --------
+ char.translate
+
+ """
+ return asarray(translate(self, table, deletechars))
+
+ def upper(self):
+ """
+ Return an array with the elements of `self` converted to
+ uppercase.
+
+ See Also
+ --------
+ char.upper
+
+ """
+ return asarray(upper(self))
+
+ def zfill(self, width):
+ """
+ Return the numeric string left-filled with zeros in a string of
+ length `width`.
+
+ See Also
+ --------
+ char.zfill
+
+ """
+ return asarray(zfill(self, width))
+
+ def isnumeric(self):
+ """
+ For each element in `self`, return True if there are only
+ numeric characters in the element.
+
+ See Also
+ --------
+ char.isnumeric
+
+ """
+ return isnumeric(self)
+
+ def isdecimal(self):
+ """
+ For each element in `self`, return True if there are only
+ decimal characters in the element.
+
+ See Also
+ --------
+ char.isdecimal
+
+ """
+ return isdecimal(self)
+
+
+@set_module("numpy.char")
+def array(obj, itemsize=None, copy=True, unicode=None, order=None):
+ """
+ Create a `~numpy.char.chararray`.
+
+ .. note::
+ This class is provided for numarray backward-compatibility.
+ New code (not concerned with numarray compatibility) should use
+ arrays of type `bytes_` or `str_` and use the free functions
+ in :mod:`numpy.char` for fast vectorized string operations instead.
+
+ Versus a NumPy array of dtype `bytes_` or `str_`, this
+ class adds the following functionality:
+
+ 1) values automatically have whitespace removed from the end
+ when indexed
+
+ 2) comparison operators automatically remove whitespace from the
+ end when comparing values
+
+ 3) vectorized string operations are provided as methods
+ (e.g. `chararray.endswith `)
+ and infix operators (e.g. ``+, *, %``)
+
+ Parameters
+ ----------
+ obj : array of str or unicode-like
+
+ itemsize : int, optional
+ `itemsize` is the number of characters per scalar in the
+ resulting array. If `itemsize` is None, and `obj` is an
+ object array or a Python list, the `itemsize` will be
+ automatically determined. If `itemsize` is provided and `obj`
+ is of type str or unicode, then the `obj` string will be
+ chunked into `itemsize` pieces.
+
+ copy : bool, optional
+ If true (default), then the object is copied. Otherwise, a copy
+ will only be made if ``__array__`` returns a copy, if obj is a
+ nested sequence, or if a copy is needed to satisfy any of the other
+ requirements (`itemsize`, unicode, `order`, etc.).
+
+ unicode : bool, optional
+ When true, the resulting `~numpy.char.chararray` can contain Unicode
+ characters, when false only 8-bit characters. If unicode is
+ None and `obj` is one of the following:
+
+ - a `~numpy.char.chararray`,
+ - an ndarray of type :class:`str_` or :class:`bytes_`
+ - a Python :class:`str` or :class:`bytes` object,
+
+ then the unicode setting of the output array will be
+ automatically determined.
+
+ order : {'C', 'F', 'A'}, optional
+ Specify the order of the array. If order is 'C' (default), then the
+ array will be in C-contiguous order (last-index varies the
+ fastest). If order is 'F', then the returned array
+ will be in Fortran-contiguous order (first-index varies the
+ fastest). If order is 'A', then the returned array may
+ be in any order (either C-, Fortran-contiguous, or even
+ discontiguous).
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> char_array = np.char.array(['hello', 'world', 'numpy','array'])
+ >>> char_array
+ chararray(['hello', 'world', 'numpy', 'array'], dtype='`)
+ and infix operators (e.g. ``+``, ``*``, ``%``)
+
+ Parameters
+ ----------
+ obj : array of str or unicode-like
+
+ itemsize : int, optional
+ `itemsize` is the number of characters per scalar in the
+ resulting array. If `itemsize` is None, and `obj` is an
+ object array or a Python list, the `itemsize` will be
+ automatically determined. If `itemsize` is provided and `obj`
+ is of type str or unicode, then the `obj` string will be
+ chunked into `itemsize` pieces.
+
+ unicode : bool, optional
+ When true, the resulting `~numpy.char.chararray` can contain Unicode
+ characters, when false only 8-bit characters. If unicode is
+ None and `obj` is one of the following:
+
+ - a `~numpy.char.chararray`,
+ - an ndarray of type `str_` or `unicode_`
+ - a Python str or unicode object,
+
+ then the unicode setting of the output array will be
+ automatically determined.
+
+ order : {'C', 'F'}, optional
+ Specify the order of the array. If order is 'C' (default), then the
+ array will be in C-contiguous order (last-index varies the
+ fastest). If order is 'F', then the returned array
+ will be in Fortran-contiguous order (first-index varies the
+ fastest).
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.char.asarray(['hello', 'world'])
+ chararray(['hello', 'world'], dtype=' _CharArray[bytes_]: ...
+ @overload
+ def __new__(
+ subtype,
+ shape: _ShapeLike,
+ itemsize: SupportsIndex | SupportsInt,
+ unicode: L[True],
+ buffer: Buffer | np.ndarray | None = None,
+ offset: SupportsIndex = 0,
+ strides: _ShapeLike | None = None,
+ order: _OrderKACF = "C",
+ ) -> _CharArray[str_]: ...
+ @overload
+ def __new__(
+ subtype,
+ shape: _ShapeLike,
+ itemsize: SupportsIndex | SupportsInt = 1,
+ *,
+ unicode: L[True],
+ buffer: Buffer | np.ndarray | None = None,
+ offset: SupportsIndex = 0,
+ strides: _ShapeLike | None = None,
+ order: _OrderKACF = "C",
+ ) -> _CharArray[str_]: ...
+
+ def __array_finalize__(self, obj: object) -> None: ...
+ def __mul__(self, other: i_co) -> chararray[_AnyShape, _CharDTypeT_co]: ... # type: ignore[override]
+ def __rmul__(self, other: i_co) -> chararray[_AnyShape, _CharDTypeT_co]: ... # type: ignore[override]
+ def __mod__(self, i: Any) -> chararray[_AnyShape, _CharDTypeT_co]: ... # type: ignore[override]
+
+ @overload # type: ignore[override]
+ def __eq__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def __eq__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> NDArray[np.bool]: ...
+
+ @overload # type: ignore[override]
+ def __ne__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def __ne__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> NDArray[np.bool]: ...
+
+ @overload # type: ignore[override]
+ def __ge__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def __ge__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> NDArray[np.bool]: ...
+
+ @overload # type: ignore[override]
+ def __le__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def __le__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> NDArray[np.bool]: ...
+
+ @overload # type: ignore[override]
+ def __gt__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def __gt__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> NDArray[np.bool]: ...
+
+ @overload # type: ignore[override]
+ def __lt__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def __lt__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> NDArray[np.bool]: ...
+
+ @overload # type: ignore[override]
+ def __add__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def __add__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload # type: ignore[override]
+ def __radd__(
+ self: _CharArray[str_],
+ other: U_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def __radd__(
+ self: _CharArray[bytes_],
+ other: S_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def center(
+ self: _CharArray[str_],
+ width: i_co,
+ fillchar: U_co = " ",
+ ) -> _CharArray[str_]: ...
+ @overload
+ def center(
+ self: _CharArray[bytes_],
+ width: i_co,
+ fillchar: str | S_co = " ",
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def count(
+ self: _CharArray[str_],
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[int_]: ...
+ @overload
+ def count(
+ self: _CharArray[bytes_],
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[int_]: ...
+
+ def decode(
+ self: _CharArray[bytes_],
+ encoding: str | None = None,
+ errors: str | None = None,
+ ) -> _CharArray[str_]: ...
+
+ def encode(
+ self: _CharArray[str_],
+ encoding: str | None = None,
+ errors: str | None = None,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def endswith(
+ self: _CharArray[str_],
+ suffix: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def endswith(
+ self: _CharArray[bytes_],
+ suffix: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[np.bool]: ...
+
+ def expandtabs(
+ self,
+ tabsize: i_co = 8,
+ ) -> Self: ...
+
+ @overload
+ def find(
+ self: _CharArray[str_],
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[int_]: ...
+ @overload
+ def find(
+ self: _CharArray[bytes_],
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[int_]: ...
+
+ @overload
+ def index(
+ self: _CharArray[str_],
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[int_]: ...
+ @overload
+ def index(
+ self: _CharArray[bytes_],
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[int_]: ...
+
+ @overload
+ def join(
+ self: _CharArray[str_],
+ seq: U_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def join(
+ self: _CharArray[bytes_],
+ seq: S_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def ljust(
+ self: _CharArray[str_],
+ width: i_co,
+ fillchar: U_co = " ",
+ ) -> _CharArray[str_]: ...
+ @overload
+ def ljust(
+ self: _CharArray[bytes_],
+ width: i_co,
+ fillchar: str | S_co = " ",
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def lstrip(
+ self: _CharArray[str_],
+ chars: U_co | None = None,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def lstrip(
+ self: _CharArray[bytes_],
+ chars: S_co | None = None,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload # type: ignore[override]
+ def partition(
+ self: _CharArray[str_],
+ sep: U_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def partition(
+ self: _CharArray[bytes_],
+ sep: S_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def replace(
+ self: _CharArray[str_],
+ old: U_co,
+ new: U_co,
+ count: i_co | None = None,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def replace(
+ self: _CharArray[bytes_],
+ old: S_co,
+ new: S_co,
+ count: i_co | None = None,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def rfind(
+ self: _CharArray[str_],
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[int_]: ...
+ @overload
+ def rfind(
+ self: _CharArray[bytes_],
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[int_]: ...
+
+ @overload
+ def rindex(
+ self: _CharArray[str_],
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[int_]: ...
+ @overload
+ def rindex(
+ self: _CharArray[bytes_],
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[int_]: ...
+
+ @overload
+ def rjust(
+ self: _CharArray[str_],
+ width: i_co,
+ fillchar: U_co = " ",
+ ) -> _CharArray[str_]: ...
+ @overload
+ def rjust(
+ self: _CharArray[bytes_],
+ width: i_co,
+ fillchar: str | S_co = " ",
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def rpartition(
+ self: _CharArray[str_],
+ sep: U_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def rpartition(
+ self: _CharArray[bytes_],
+ sep: S_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def rsplit(
+ self: _CharArray[str_],
+ sep: U_co | None = None,
+ maxsplit: i_co | None = None,
+ ) -> NDArray[object_]: ...
+ @overload
+ def rsplit(
+ self: _CharArray[bytes_],
+ sep: S_co | None = None,
+ maxsplit: i_co | None = None,
+ ) -> NDArray[object_]: ...
+
+ @overload
+ def rstrip(
+ self: _CharArray[str_],
+ chars: U_co | None = None,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def rstrip(
+ self: _CharArray[bytes_],
+ chars: S_co | None = None,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def split(
+ self: _CharArray[str_],
+ sep: U_co | None = None,
+ maxsplit: i_co | None = None,
+ ) -> NDArray[object_]: ...
+ @overload
+ def split(
+ self: _CharArray[bytes_],
+ sep: S_co | None = None,
+ maxsplit: i_co | None = None,
+ ) -> NDArray[object_]: ...
+
+ def splitlines(self, keepends: b_co | None = None) -> NDArray[object_]: ...
+
+ @overload
+ def startswith(
+ self: _CharArray[str_],
+ prefix: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[np.bool]: ...
+ @overload
+ def startswith(
+ self: _CharArray[bytes_],
+ prefix: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+ ) -> NDArray[np.bool]: ...
+
+ @overload
+ def strip(
+ self: _CharArray[str_],
+ chars: U_co | None = None,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def strip(
+ self: _CharArray[bytes_],
+ chars: S_co | None = None,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def translate(
+ self: _CharArray[str_],
+ table: U_co,
+ deletechars: U_co | None = None,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def translate(
+ self: _CharArray[bytes_],
+ table: S_co,
+ deletechars: S_co | None = None,
+ ) -> _CharArray[bytes_]: ...
+
+ def zfill(self, width: i_co) -> Self: ...
+ def capitalize(self) -> Self: ...
+ def title(self) -> Self: ...
+ def swapcase(self) -> Self: ...
+ def lower(self) -> Self: ...
+ def upper(self) -> Self: ...
+ def isalnum(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def isalpha(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def isdigit(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def islower(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def isspace(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def istitle(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def isupper(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def isnumeric(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+ def isdecimal(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
+
+# Comparison
+@overload
+def equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def not_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def not_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def not_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def greater_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def greater_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def greater_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def less_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def less_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def less_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def greater(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def greater(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def greater(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def less(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def less(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def less(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def add(x1: U_co, x2: U_co) -> NDArray[np.str_]: ...
+@overload
+def add(x1: S_co, x2: S_co) -> NDArray[np.bytes_]: ...
+@overload
+def add(x1: _StringDTypeSupportsArray, x2: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def add(x1: T_co, x2: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def multiply(a: U_co, i: i_co) -> NDArray[np.str_]: ...
+@overload
+def multiply(a: S_co, i: i_co) -> NDArray[np.bytes_]: ...
+@overload
+def multiply(a: _StringDTypeSupportsArray, i: i_co) -> _StringDTypeArray: ...
+@overload
+def multiply(a: T_co, i: i_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def mod(a: U_co, value: Any) -> NDArray[np.str_]: ...
+@overload
+def mod(a: S_co, value: Any) -> NDArray[np.bytes_]: ...
+@overload
+def mod(a: _StringDTypeSupportsArray, value: Any) -> _StringDTypeArray: ...
+@overload
+def mod(a: T_co, value: Any) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def capitalize(a: U_co) -> NDArray[str_]: ...
+@overload
+def capitalize(a: S_co) -> NDArray[bytes_]: ...
+@overload
+def capitalize(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def capitalize(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def center(a: U_co, width: i_co, fillchar: U_co = " ") -> NDArray[str_]: ...
+@overload
+def center(a: S_co, width: i_co, fillchar: str | S_co = " ") -> NDArray[bytes_]: ...
+@overload
+def center(a: _StringDTypeSupportsArray, width: i_co, fillchar: str | _StringDTypeSupportsArray = " ") -> _StringDTypeArray: ...
+@overload
+def center(a: T_co, width: i_co, fillchar: T_co = " ") -> _StringDTypeOrUnicodeArray: ...
+
+def decode(
+ a: S_co,
+ encoding: str | None = None,
+ errors: str | None = None,
+) -> NDArray[str_]: ...
+def encode(
+ a: U_co | T_co,
+ encoding: str | None = None,
+ errors: str | None = None,
+) -> NDArray[bytes_]: ...
+
+@overload
+def expandtabs(a: U_co, tabsize: i_co = 8) -> NDArray[str_]: ...
+@overload
+def expandtabs(a: S_co, tabsize: i_co = 8) -> NDArray[bytes_]: ...
+@overload
+def expandtabs(a: _StringDTypeSupportsArray, tabsize: i_co = 8) -> _StringDTypeArray: ...
+@overload
+def expandtabs(a: T_co, tabsize: i_co = 8) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def join(sep: U_co, seq: U_co) -> NDArray[str_]: ...
+@overload
+def join(sep: S_co, seq: S_co) -> NDArray[bytes_]: ...
+@overload
+def join(sep: _StringDTypeSupportsArray, seq: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def join(sep: T_co, seq: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def ljust(a: U_co, width: i_co, fillchar: U_co = " ") -> NDArray[str_]: ...
+@overload
+def ljust(a: S_co, width: i_co, fillchar: str | S_co = " ") -> NDArray[bytes_]: ...
+@overload
+def ljust(a: _StringDTypeSupportsArray, width: i_co, fillchar: str | _StringDTypeSupportsArray = " ") -> _StringDTypeArray: ...
+@overload
+def ljust(a: T_co, width: i_co, fillchar: T_co = " ") -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def lower(a: U_co) -> NDArray[str_]: ...
+@overload
+def lower(a: S_co) -> NDArray[bytes_]: ...
+@overload
+def lower(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def lower(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def lstrip(a: U_co, chars: U_co | None = None) -> NDArray[str_]: ...
+@overload
+def lstrip(a: S_co, chars: S_co | None = None) -> NDArray[bytes_]: ...
+@overload
+def lstrip(a: _StringDTypeSupportsArray, chars: _StringDTypeSupportsArray | None = None) -> _StringDTypeArray: ...
+@overload
+def lstrip(a: T_co, chars: T_co | None = None) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def partition(a: U_co, sep: U_co) -> NDArray[str_]: ...
+@overload
+def partition(a: S_co, sep: S_co) -> NDArray[bytes_]: ...
+@overload
+def partition(a: _StringDTypeSupportsArray, sep: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def partition(a: T_co, sep: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def replace(
+ a: U_co,
+ old: U_co,
+ new: U_co,
+ count: i_co | None = -1,
+) -> NDArray[str_]: ...
+@overload
+def replace(
+ a: S_co,
+ old: S_co,
+ new: S_co,
+ count: i_co | None = -1,
+) -> NDArray[bytes_]: ...
+@overload
+def replace(
+ a: _StringDTypeSupportsArray,
+ old: _StringDTypeSupportsArray,
+ new: _StringDTypeSupportsArray,
+ count: i_co = -1,
+) -> _StringDTypeArray: ...
+@overload
+def replace(
+ a: T_co,
+ old: T_co,
+ new: T_co,
+ count: i_co = -1,
+) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def rjust(
+ a: U_co,
+ width: i_co,
+ fillchar: U_co = " ",
+) -> NDArray[str_]: ...
+@overload
+def rjust(
+ a: S_co,
+ width: i_co,
+ fillchar: str | S_co = " ",
+) -> NDArray[bytes_]: ...
+@overload
+def rjust(
+ a: _StringDTypeSupportsArray,
+ width: i_co,
+ fillchar: str | _StringDTypeSupportsArray = " ",
+) -> _StringDTypeArray: ...
+@overload
+def rjust(
+ a: T_co,
+ width: i_co,
+ fillchar: T_co = " ",
+) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def rpartition(a: U_co, sep: U_co) -> NDArray[str_]: ...
+@overload
+def rpartition(a: S_co, sep: S_co) -> NDArray[bytes_]: ...
+@overload
+def rpartition(a: _StringDTypeSupportsArray, sep: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def rpartition(a: T_co, sep: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def rsplit(
+ a: U_co,
+ sep: U_co | None = None,
+ maxsplit: i_co | None = None,
+) -> NDArray[object_]: ...
+@overload
+def rsplit(
+ a: S_co,
+ sep: S_co | None = None,
+ maxsplit: i_co | None = None,
+) -> NDArray[object_]: ...
+@overload
+def rsplit(
+ a: _StringDTypeSupportsArray,
+ sep: _StringDTypeSupportsArray | None = None,
+ maxsplit: i_co | None = None,
+) -> NDArray[object_]: ...
+@overload
+def rsplit(
+ a: T_co,
+ sep: T_co | None = None,
+ maxsplit: i_co | None = None,
+) -> NDArray[object_]: ...
+
+@overload
+def rstrip(a: U_co, chars: U_co | None = None) -> NDArray[str_]: ...
+@overload
+def rstrip(a: S_co, chars: S_co | None = None) -> NDArray[bytes_]: ...
+@overload
+def rstrip(a: _StringDTypeSupportsArray, chars: _StringDTypeSupportsArray | None = None) -> _StringDTypeArray: ...
+@overload
+def rstrip(a: T_co, chars: T_co | None = None) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def split(
+ a: U_co,
+ sep: U_co | None = None,
+ maxsplit: i_co | None = None,
+) -> NDArray[object_]: ...
+@overload
+def split(
+ a: S_co,
+ sep: S_co | None = None,
+ maxsplit: i_co | None = None,
+) -> NDArray[object_]: ...
+@overload
+def split(
+ a: _StringDTypeSupportsArray,
+ sep: _StringDTypeSupportsArray | None = None,
+ maxsplit: i_co | None = None,
+) -> NDArray[object_]: ...
+@overload
+def split(
+ a: T_co,
+ sep: T_co | None = None,
+ maxsplit: i_co | None = None,
+) -> NDArray[object_]: ...
+
+def splitlines(a: UST_co, keepends: b_co | None = None) -> NDArray[np.object_]: ...
+
+@overload
+def strip(a: U_co, chars: U_co | None = None) -> NDArray[str_]: ...
+@overload
+def strip(a: S_co, chars: S_co | None = None) -> NDArray[bytes_]: ...
+@overload
+def strip(a: _StringDTypeSupportsArray, chars: _StringDTypeSupportsArray | None = None) -> _StringDTypeArray: ...
+@overload
+def strip(a: T_co, chars: T_co | None = None) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def swapcase(a: U_co) -> NDArray[str_]: ...
+@overload
+def swapcase(a: S_co) -> NDArray[bytes_]: ...
+@overload
+def swapcase(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def swapcase(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def title(a: U_co) -> NDArray[str_]: ...
+@overload
+def title(a: S_co) -> NDArray[bytes_]: ...
+@overload
+def title(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def title(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def translate(
+ a: U_co,
+ table: str,
+ deletechars: str | None = None,
+) -> NDArray[str_]: ...
+@overload
+def translate(
+ a: S_co,
+ table: str,
+ deletechars: str | None = None,
+) -> NDArray[bytes_]: ...
+@overload
+def translate(
+ a: _StringDTypeSupportsArray,
+ table: str,
+ deletechars: str | None = None,
+) -> _StringDTypeArray: ...
+@overload
+def translate(
+ a: T_co,
+ table: str,
+ deletechars: str | None = None,
+) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def upper(a: U_co) -> NDArray[str_]: ...
+@overload
+def upper(a: S_co) -> NDArray[bytes_]: ...
+@overload
+def upper(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def upper(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def zfill(a: U_co, width: i_co) -> NDArray[str_]: ...
+@overload
+def zfill(a: S_co, width: i_co) -> NDArray[bytes_]: ...
+@overload
+def zfill(a: _StringDTypeSupportsArray, width: i_co) -> _StringDTypeArray: ...
+@overload
+def zfill(a: T_co, width: i_co) -> _StringDTypeOrUnicodeArray: ...
+
+# String information
+@overload
+def count(
+ a: U_co,
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[int_]: ...
+@overload
+def count(
+ a: S_co,
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[int_]: ...
+@overload
+def count(
+ a: T_co,
+ sub: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+
+@overload
+def endswith(
+ a: U_co,
+ suffix: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.bool]: ...
+@overload
+def endswith(
+ a: S_co,
+ suffix: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.bool]: ...
+@overload
+def endswith(
+ a: T_co,
+ suffix: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.bool]: ...
+
+@overload
+def find(
+ a: U_co,
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[int_]: ...
+@overload
+def find(
+ a: S_co,
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[int_]: ...
+@overload
+def find(
+ a: T_co,
+ sub: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+
+@overload
+def index(
+ a: U_co,
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[int_]: ...
+@overload
+def index(
+ a: S_co,
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[int_]: ...
+@overload
+def index(
+ a: T_co,
+ sub: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+
+def isalpha(a: UST_co) -> NDArray[np.bool]: ...
+def isalnum(a: UST_co) -> NDArray[np.bool]: ...
+def isdecimal(a: U_co | T_co) -> NDArray[np.bool]: ...
+def isdigit(a: UST_co) -> NDArray[np.bool]: ...
+def islower(a: UST_co) -> NDArray[np.bool]: ...
+def isnumeric(a: U_co | T_co) -> NDArray[np.bool]: ...
+def isspace(a: UST_co) -> NDArray[np.bool]: ...
+def istitle(a: UST_co) -> NDArray[np.bool]: ...
+def isupper(a: UST_co) -> NDArray[np.bool]: ...
+
+@overload
+def rfind(
+ a: U_co,
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[int_]: ...
+@overload
+def rfind(
+ a: S_co,
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[int_]: ...
+@overload
+def rfind(
+ a: T_co,
+ sub: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+
+@overload
+def rindex(
+ a: U_co,
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[int_]: ...
+@overload
+def rindex(
+ a: S_co,
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[int_]: ...
+@overload
+def rindex(
+ a: T_co,
+ sub: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+
+@overload
+def startswith(
+ a: U_co,
+ prefix: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.bool]: ...
+@overload
+def startswith(
+ a: S_co,
+ prefix: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.bool]: ...
+@overload
+def startswith(
+ a: T_co,
+ prefix: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.bool]: ...
+
+def str_len(A: UST_co) -> NDArray[int_]: ...
+
+# Overload 1 and 2: str- or bytes-based array-likes
+# overload 3 and 4: arbitrary object with unicode=False (-> bytes_)
+# overload 5 and 6: arbitrary object with unicode=True (-> str_)
+# overload 7: arbitrary object with unicode=None (default) (-> str_ | bytes_)
+@overload
+def array(
+ obj: U_co,
+ itemsize: int | None = None,
+ copy: bool = True,
+ unicode: L[True] | None = None,
+ order: _OrderKACF = None,
+) -> _CharArray[str_]: ...
+@overload
+def array(
+ obj: S_co,
+ itemsize: int | None = None,
+ copy: bool = True,
+ unicode: L[False] | None = None,
+ order: _OrderKACF = None,
+) -> _CharArray[bytes_]: ...
+@overload
+def array(
+ obj: object,
+ itemsize: int | None,
+ copy: bool,
+ unicode: L[False],
+ order: _OrderKACF = None,
+) -> _CharArray[bytes_]: ...
+@overload
+def array(
+ obj: object,
+ itemsize: int | None = None,
+ copy: bool = True,
+ *,
+ unicode: L[False],
+ order: _OrderKACF = None,
+) -> _CharArray[bytes_]: ...
+@overload
+def array(
+ obj: object,
+ itemsize: int | None,
+ copy: bool,
+ unicode: L[True],
+ order: _OrderKACF = None,
+) -> _CharArray[str_]: ...
+@overload
+def array(
+ obj: object,
+ itemsize: int | None = None,
+ copy: bool = True,
+ *,
+ unicode: L[True],
+ order: _OrderKACF = None,
+) -> _CharArray[str_]: ...
+@overload
+def array(
+ obj: object,
+ itemsize: int | None = None,
+ copy: bool = True,
+ unicode: bool | None = None,
+ order: _OrderKACF = None,
+) -> _CharArray[str_] | _CharArray[bytes_]: ...
+
+@overload
+def asarray(
+ obj: U_co,
+ itemsize: int | None = None,
+ unicode: L[True] | None = None,
+ order: _OrderKACF = None,
+) -> _CharArray[str_]: ...
+@overload
+def asarray(
+ obj: S_co,
+ itemsize: int | None = None,
+ unicode: L[False] | None = None,
+ order: _OrderKACF = None,
+) -> _CharArray[bytes_]: ...
+@overload
+def asarray(
+ obj: object,
+ itemsize: int | None,
+ unicode: L[False],
+ order: _OrderKACF = None,
+) -> _CharArray[bytes_]: ...
+@overload
+def asarray(
+ obj: object,
+ itemsize: int | None = None,
+ *,
+ unicode: L[False],
+ order: _OrderKACF = None,
+) -> _CharArray[bytes_]: ...
+@overload
+def asarray(
+ obj: object,
+ itemsize: int | None,
+ unicode: L[True],
+ order: _OrderKACF = None,
+) -> _CharArray[str_]: ...
+@overload
+def asarray(
+ obj: object,
+ itemsize: int | None = None,
+ *,
+ unicode: L[True],
+ order: _OrderKACF = None,
+) -> _CharArray[str_]: ...
+@overload
+def asarray(
+ obj: object,
+ itemsize: int | None = None,
+ unicode: bool | None = None,
+ order: _OrderKACF = None,
+) -> _CharArray[str_] | _CharArray[bytes_]: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/einsumfunc.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/einsumfunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..9461994f579592f2ca47bb375e15ad6adb74303c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/einsumfunc.py
@@ -0,0 +1,1650 @@
+"""
+Implementation of optimized einsum.
+
+"""
+import functools
+import itertools
+import operator
+
+from numpy._core.multiarray import c_einsum, matmul
+from numpy._core.numeric import asanyarray, reshape
+from numpy._core.overrides import array_function_dispatch
+from numpy._core.umath import multiply
+
+__all__ = ['einsum', 'einsum_path']
+
+# importing string for string.ascii_letters would be too slow
+# the first import before caching has been measured to take 800 µs (#23777)
+# imports begin with uppercase to mimic ASCII values to avoid sorting issues
+einsum_symbols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
+einsum_symbols_set = set(einsum_symbols)
+
+
+def _flop_count(idx_contraction, inner, num_terms, size_dictionary):
+ """
+ Computes the number of FLOPS in the contraction.
+
+ Parameters
+ ----------
+ idx_contraction : iterable
+ The indices involved in the contraction
+ inner : bool
+ Does this contraction require an inner product?
+ num_terms : int
+ The number of terms in a contraction
+ size_dictionary : dict
+ The size of each of the indices in idx_contraction
+
+ Returns
+ -------
+ flop_count : int
+ The total number of FLOPS required for the contraction.
+
+ Examples
+ --------
+
+ >>> _flop_count('abc', False, 1, {'a': 2, 'b':3, 'c':5})
+ 30
+
+ >>> _flop_count('abc', True, 2, {'a': 2, 'b':3, 'c':5})
+ 60
+
+ """
+
+ overall_size = _compute_size_by_dict(idx_contraction, size_dictionary)
+ op_factor = max(1, num_terms - 1)
+ if inner:
+ op_factor += 1
+
+ return overall_size * op_factor
+
+def _compute_size_by_dict(indices, idx_dict):
+ """
+ Computes the product of the elements in indices based on the dictionary
+ idx_dict.
+
+ Parameters
+ ----------
+ indices : iterable
+ Indices to base the product on.
+ idx_dict : dictionary
+ Dictionary of index sizes
+
+ Returns
+ -------
+ ret : int
+ The resulting product.
+
+ Examples
+ --------
+ >>> _compute_size_by_dict('abbc', {'a': 2, 'b':3, 'c':5})
+ 90
+
+ """
+ ret = 1
+ for i in indices:
+ ret *= idx_dict[i]
+ return ret
+
+
+def _find_contraction(positions, input_sets, output_set):
+ """
+ Finds the contraction for a given set of input and output sets.
+
+ Parameters
+ ----------
+ positions : iterable
+ Integer positions of terms used in the contraction.
+ input_sets : list
+ List of sets that represent the lhs side of the einsum subscript
+ output_set : set
+ Set that represents the rhs side of the overall einsum subscript
+
+ Returns
+ -------
+ new_result : set
+ The indices of the resulting contraction
+ remaining : list
+ List of sets that have not been contracted, the new set is appended to
+ the end of this list
+ idx_removed : set
+ Indices removed from the entire contraction
+ idx_contraction : set
+ The indices used in the current contraction
+
+ Examples
+ --------
+
+ # A simple dot product test case
+ >>> pos = (0, 1)
+ >>> isets = [set('ab'), set('bc')]
+ >>> oset = set('ac')
+ >>> _find_contraction(pos, isets, oset)
+ ({'a', 'c'}, [{'a', 'c'}], {'b'}, {'a', 'b', 'c'})
+
+ # A more complex case with additional terms in the contraction
+ >>> pos = (0, 2)
+ >>> isets = [set('abd'), set('ac'), set('bdc')]
+ >>> oset = set('ac')
+ >>> _find_contraction(pos, isets, oset)
+ ({'a', 'c'}, [{'a', 'c'}, {'a', 'c'}], {'b', 'd'}, {'a', 'b', 'c', 'd'})
+ """
+
+ idx_contract = set()
+ idx_remain = output_set.copy()
+ remaining = []
+ for ind, value in enumerate(input_sets):
+ if ind in positions:
+ idx_contract |= value
+ else:
+ remaining.append(value)
+ idx_remain |= value
+
+ new_result = idx_remain & idx_contract
+ idx_removed = (idx_contract - new_result)
+ remaining.append(new_result)
+
+ return (new_result, remaining, idx_removed, idx_contract)
+
+
+def _optimal_path(input_sets, output_set, idx_dict, memory_limit):
+ """
+ Computes all possible pair contractions, sieves the results based
+ on ``memory_limit`` and returns the lowest cost path. This algorithm
+ scales factorial with respect to the elements in the list ``input_sets``.
+
+ Parameters
+ ----------
+ input_sets : list
+ List of sets that represent the lhs side of the einsum subscript
+ output_set : set
+ Set that represents the rhs side of the overall einsum subscript
+ idx_dict : dictionary
+ Dictionary of index sizes
+ memory_limit : int
+ The maximum number of elements in a temporary array
+
+ Returns
+ -------
+ path : list
+ The optimal contraction order within the memory limit constraint.
+
+ Examples
+ --------
+ >>> isets = [set('abd'), set('ac'), set('bdc')]
+ >>> oset = set()
+ >>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
+ >>> _optimal_path(isets, oset, idx_sizes, 5000)
+ [(0, 2), (0, 1)]
+ """
+
+ full_results = [(0, [], input_sets)]
+ for iteration in range(len(input_sets) - 1):
+ iter_results = []
+
+ # Compute all unique pairs
+ for curr in full_results:
+ cost, positions, remaining = curr
+ for con in itertools.combinations(
+ range(len(input_sets) - iteration), 2
+ ):
+
+ # Find the contraction
+ cont = _find_contraction(con, remaining, output_set)
+ new_result, new_input_sets, idx_removed, idx_contract = cont
+
+ # Sieve the results based on memory_limit
+ new_size = _compute_size_by_dict(new_result, idx_dict)
+ if new_size > memory_limit:
+ continue
+
+ # Build (total_cost, positions, indices_remaining)
+ total_cost = cost + _flop_count(
+ idx_contract, idx_removed, len(con), idx_dict
+ )
+ new_pos = positions + [con]
+ iter_results.append((total_cost, new_pos, new_input_sets))
+
+ # Update combinatorial list, if we did not find anything return best
+ # path + remaining contractions
+ if iter_results:
+ full_results = iter_results
+ else:
+ path = min(full_results, key=lambda x: x[0])[1]
+ path += [tuple(range(len(input_sets) - iteration))]
+ return path
+
+ # If we have not found anything return single einsum contraction
+ if len(full_results) == 0:
+ return [tuple(range(len(input_sets)))]
+
+ path = min(full_results, key=lambda x: x[0])[1]
+ return path
+
+def _parse_possible_contraction(
+ positions, input_sets, output_set, idx_dict,
+ memory_limit, path_cost, naive_cost
+ ):
+ """Compute the cost (removed size + flops) and resultant indices for
+ performing the contraction specified by ``positions``.
+
+ Parameters
+ ----------
+ positions : tuple of int
+ The locations of the proposed tensors to contract.
+ input_sets : list of sets
+ The indices found on each tensors.
+ output_set : set
+ The output indices of the expression.
+ idx_dict : dict
+ Mapping of each index to its size.
+ memory_limit : int
+ The total allowed size for an intermediary tensor.
+ path_cost : int
+ The contraction cost so far.
+ naive_cost : int
+ The cost of the unoptimized expression.
+
+ Returns
+ -------
+ cost : (int, int)
+ A tuple containing the size of any indices removed, and the flop cost.
+ positions : tuple of int
+ The locations of the proposed tensors to contract.
+ new_input_sets : list of sets
+ The resulting new list of indices if this proposed contraction
+ is performed.
+
+ """
+
+ # Find the contraction
+ contract = _find_contraction(positions, input_sets, output_set)
+ idx_result, new_input_sets, idx_removed, idx_contract = contract
+
+ # Sieve the results based on memory_limit
+ new_size = _compute_size_by_dict(idx_result, idx_dict)
+ if new_size > memory_limit:
+ return None
+
+ # Build sort tuple
+ old_sizes = (
+ _compute_size_by_dict(input_sets[p], idx_dict) for p in positions
+ )
+ removed_size = sum(old_sizes) - new_size
+
+ # NB: removed_size used to be just the size of any removed indices i.e.:
+ # helpers.compute_size_by_dict(idx_removed, idx_dict)
+ cost = _flop_count(idx_contract, idx_removed, len(positions), idx_dict)
+ sort = (-removed_size, cost)
+
+ # Sieve based on total cost as well
+ if (path_cost + cost) > naive_cost:
+ return None
+
+ # Add contraction to possible choices
+ return [sort, positions, new_input_sets]
+
+
+def _update_other_results(results, best):
+ """Update the positions and provisional input_sets of ``results``
+ based on performing the contraction result ``best``. Remove any
+ involving the tensors contracted.
+
+ Parameters
+ ----------
+ results : list
+ List of contraction results produced by
+ ``_parse_possible_contraction``.
+ best : list
+ The best contraction of ``results`` i.e. the one that
+ will be performed.
+
+ Returns
+ -------
+ mod_results : list
+ The list of modified results, updated with outcome of
+ ``best`` contraction.
+ """
+
+ best_con = best[1]
+ bx, by = best_con
+ mod_results = []
+
+ for cost, (x, y), con_sets in results:
+
+ # Ignore results involving tensors just contracted
+ if x in best_con or y in best_con:
+ continue
+
+ # Update the input_sets
+ del con_sets[by - int(by > x) - int(by > y)]
+ del con_sets[bx - int(bx > x) - int(bx > y)]
+ con_sets.insert(-1, best[2][-1])
+
+ # Update the position indices
+ mod_con = x - int(x > bx) - int(x > by), y - int(y > bx) - int(y > by)
+ mod_results.append((cost, mod_con, con_sets))
+
+ return mod_results
+
+def _greedy_path(input_sets, output_set, idx_dict, memory_limit):
+ """
+ Finds the path by contracting the best pair until the input list is
+ exhausted. The best pair is found by minimizing the tuple
+ ``(-prod(indices_removed), cost)``. What this amounts to is prioritizing
+ matrix multiplication or inner product operations, then Hadamard like
+ operations, and finally outer operations. Outer products are limited by
+ ``memory_limit``. This algorithm scales cubically with respect to the
+ number of elements in the list ``input_sets``.
+
+ Parameters
+ ----------
+ input_sets : list
+ List of sets that represent the lhs side of the einsum subscript
+ output_set : set
+ Set that represents the rhs side of the overall einsum subscript
+ idx_dict : dictionary
+ Dictionary of index sizes
+ memory_limit : int
+ The maximum number of elements in a temporary array
+
+ Returns
+ -------
+ path : list
+ The greedy contraction order within the memory limit constraint.
+
+ Examples
+ --------
+ >>> isets = [set('abd'), set('ac'), set('bdc')]
+ >>> oset = set()
+ >>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
+ >>> _greedy_path(isets, oset, idx_sizes, 5000)
+ [(0, 2), (0, 1)]
+ """
+
+ # Handle trivial cases that leaked through
+ if len(input_sets) == 1:
+ return [(0,)]
+ elif len(input_sets) == 2:
+ return [(0, 1)]
+
+ # Build up a naive cost
+ contract = _find_contraction(
+ range(len(input_sets)), input_sets, output_set
+ )
+ idx_result, new_input_sets, idx_removed, idx_contract = contract
+ naive_cost = _flop_count(
+ idx_contract, idx_removed, len(input_sets), idx_dict
+ )
+
+ # Initially iterate over all pairs
+ comb_iter = itertools.combinations(range(len(input_sets)), 2)
+ known_contractions = []
+
+ path_cost = 0
+ path = []
+
+ for iteration in range(len(input_sets) - 1):
+
+ # Iterate over all pairs on the first step, only previously
+ # found pairs on subsequent steps
+ for positions in comb_iter:
+
+ # Always initially ignore outer products
+ if input_sets[positions[0]].isdisjoint(input_sets[positions[1]]):
+ continue
+
+ result = _parse_possible_contraction(
+ positions, input_sets, output_set, idx_dict,
+ memory_limit, path_cost, naive_cost
+ )
+ if result is not None:
+ known_contractions.append(result)
+
+ # If we do not have a inner contraction, rescan pairs
+ # including outer products
+ if len(known_contractions) == 0:
+
+ # Then check the outer products
+ for positions in itertools.combinations(
+ range(len(input_sets)), 2
+ ):
+ result = _parse_possible_contraction(
+ positions, input_sets, output_set, idx_dict,
+ memory_limit, path_cost, naive_cost
+ )
+ if result is not None:
+ known_contractions.append(result)
+
+ # If we still did not find any remaining contractions,
+ # default back to einsum like behavior
+ if len(known_contractions) == 0:
+ path.append(tuple(range(len(input_sets))))
+ break
+
+ # Sort based on first index
+ best = min(known_contractions, key=lambda x: x[0])
+
+ # Now propagate as many unused contractions as possible
+ # to the next iteration
+ known_contractions = _update_other_results(known_contractions, best)
+
+ # Next iteration only compute contractions with the new tensor
+ # All other contractions have been accounted for
+ input_sets = best[2]
+ new_tensor_pos = len(input_sets) - 1
+ comb_iter = ((i, new_tensor_pos) for i in range(new_tensor_pos))
+
+ # Update path and total cost
+ path.append(best[1])
+ path_cost += best[0][1]
+
+ return path
+
+
+def _parse_einsum_input(operands):
+ """
+ A reproduction of einsum c side einsum parsing in python.
+
+ Returns
+ -------
+ input_strings : str
+ Parsed input strings
+ output_string : str
+ Parsed output string
+ operands : list of array_like
+ The operands to use in the numpy contraction
+
+ Examples
+ --------
+ The operand list is simplified to reduce printing:
+
+ >>> np.random.seed(123)
+ >>> a = np.random.rand(4, 4)
+ >>> b = np.random.rand(4, 4, 4)
+ >>> _parse_einsum_input(('...a,...a->...', a, b))
+ ('za,xza', 'xz', [a, b]) # may vary
+
+ >>> _parse_einsum_input((a, [Ellipsis, 0], b, [Ellipsis, 0]))
+ ('za,xza', 'xz', [a, b]) # may vary
+ """
+
+ if len(operands) == 0:
+ raise ValueError("No input operands")
+
+ if isinstance(operands[0], str):
+ subscripts = operands[0].replace(" ", "")
+ operands = [asanyarray(v) for v in operands[1:]]
+
+ # Ensure all characters are valid
+ for s in subscripts:
+ if s in '.,->':
+ continue
+ if s not in einsum_symbols:
+ raise ValueError(f"Character {s} is not a valid symbol.")
+
+ else:
+ tmp_operands = list(operands)
+ operand_list = []
+ subscript_list = []
+ for p in range(len(operands) // 2):
+ operand_list.append(tmp_operands.pop(0))
+ subscript_list.append(tmp_operands.pop(0))
+
+ output_list = tmp_operands[-1] if len(tmp_operands) else None
+ operands = [asanyarray(v) for v in operand_list]
+ subscripts = ""
+ last = len(subscript_list) - 1
+ for num, sub in enumerate(subscript_list):
+ for s in sub:
+ if s is Ellipsis:
+ subscripts += "..."
+ else:
+ try:
+ s = operator.index(s)
+ except TypeError as e:
+ raise TypeError(
+ "For this input type lists must contain "
+ "either int or Ellipsis"
+ ) from e
+ subscripts += einsum_symbols[s]
+ if num != last:
+ subscripts += ","
+
+ if output_list is not None:
+ subscripts += "->"
+ for s in output_list:
+ if s is Ellipsis:
+ subscripts += "..."
+ else:
+ try:
+ s = operator.index(s)
+ except TypeError as e:
+ raise TypeError(
+ "For this input type lists must contain "
+ "either int or Ellipsis"
+ ) from e
+ subscripts += einsum_symbols[s]
+ # Check for proper "->"
+ if ("-" in subscripts) or (">" in subscripts):
+ invalid = (subscripts.count("-") > 1) or (subscripts.count(">") > 1)
+ if invalid or (subscripts.count("->") != 1):
+ raise ValueError("Subscripts can only contain one '->'.")
+
+ # Parse ellipses
+ if "." in subscripts:
+ used = subscripts.replace(".", "").replace(",", "").replace("->", "")
+ unused = list(einsum_symbols_set - set(used))
+ ellipse_inds = "".join(unused)
+ longest = 0
+
+ if "->" in subscripts:
+ input_tmp, output_sub = subscripts.split("->")
+ split_subscripts = input_tmp.split(",")
+ out_sub = True
+ else:
+ split_subscripts = subscripts.split(',')
+ out_sub = False
+
+ for num, sub in enumerate(split_subscripts):
+ if "." in sub:
+ if (sub.count(".") != 3) or (sub.count("...") != 1):
+ raise ValueError("Invalid Ellipses.")
+
+ # Take into account numerical values
+ if operands[num].shape == ():
+ ellipse_count = 0
+ else:
+ ellipse_count = max(operands[num].ndim, 1)
+ ellipse_count -= (len(sub) - 3)
+
+ if ellipse_count > longest:
+ longest = ellipse_count
+
+ if ellipse_count < 0:
+ raise ValueError("Ellipses lengths do not match.")
+ elif ellipse_count == 0:
+ split_subscripts[num] = sub.replace('...', '')
+ else:
+ rep_inds = ellipse_inds[-ellipse_count:]
+ split_subscripts[num] = sub.replace('...', rep_inds)
+
+ subscripts = ",".join(split_subscripts)
+ if longest == 0:
+ out_ellipse = ""
+ else:
+ out_ellipse = ellipse_inds[-longest:]
+
+ if out_sub:
+ subscripts += "->" + output_sub.replace("...", out_ellipse)
+ else:
+ # Special care for outputless ellipses
+ output_subscript = ""
+ tmp_subscripts = subscripts.replace(",", "")
+ for s in sorted(set(tmp_subscripts)):
+ if s not in (einsum_symbols):
+ raise ValueError(f"Character {s} is not a valid symbol.")
+ if tmp_subscripts.count(s) == 1:
+ output_subscript += s
+ normal_inds = ''.join(sorted(set(output_subscript) -
+ set(out_ellipse)))
+
+ subscripts += "->" + out_ellipse + normal_inds
+
+ # Build output string if does not exist
+ if "->" in subscripts:
+ input_subscripts, output_subscript = subscripts.split("->")
+ else:
+ input_subscripts = subscripts
+ # Build output subscripts
+ tmp_subscripts = subscripts.replace(",", "")
+ output_subscript = ""
+ for s in sorted(set(tmp_subscripts)):
+ if s not in einsum_symbols:
+ raise ValueError(f"Character {s} is not a valid symbol.")
+ if tmp_subscripts.count(s) == 1:
+ output_subscript += s
+
+ # Make sure output subscripts are in the input
+ for char in output_subscript:
+ if output_subscript.count(char) != 1:
+ raise ValueError("Output character %s appeared more than once in "
+ "the output." % char)
+ if char not in input_subscripts:
+ raise ValueError(f"Output character {char} did not appear in the input")
+
+ # Make sure number operands is equivalent to the number of terms
+ if len(input_subscripts.split(',')) != len(operands):
+ raise ValueError("Number of einsum subscripts must be equal to the "
+ "number of operands.")
+
+ return (input_subscripts, output_subscript, operands)
+
+
+def _einsum_path_dispatcher(*operands, optimize=None, einsum_call=None):
+ # NOTE: technically, we should only dispatch on array-like arguments, not
+ # subscripts (given as strings). But separating operands into
+ # arrays/subscripts is a little tricky/slow (given einsum's two supported
+ # signatures), so as a practical shortcut we dispatch on everything.
+ # Strings will be ignored for dispatching since they don't define
+ # __array_function__.
+ return operands
+
+
+@array_function_dispatch(_einsum_path_dispatcher, module='numpy')
+def einsum_path(*operands, optimize='greedy', einsum_call=False):
+ """
+ einsum_path(subscripts, *operands, optimize='greedy')
+
+ Evaluates the lowest cost contraction order for an einsum expression by
+ considering the creation of intermediate arrays.
+
+ Parameters
+ ----------
+ subscripts : str
+ Specifies the subscripts for summation.
+ *operands : list of array_like
+ These are the arrays for the operation.
+ optimize : {bool, list, tuple, 'greedy', 'optimal'}
+ Choose the type of path. If a tuple is provided, the second argument is
+ assumed to be the maximum intermediate size created. If only a single
+ argument is provided the largest input or output array size is used
+ as a maximum intermediate size.
+
+ * if a list is given that starts with ``einsum_path``, uses this as the
+ contraction path
+ * if False no optimization is taken
+ * if True defaults to the 'greedy' algorithm
+ * 'optimal' An algorithm that combinatorially explores all possible
+ ways of contracting the listed tensors and chooses the least costly
+ path. Scales exponentially with the number of terms in the
+ contraction.
+ * 'greedy' An algorithm that chooses the best pair contraction
+ at each step. Effectively, this algorithm searches the largest inner,
+ Hadamard, and then outer products at each step. Scales cubically with
+ the number of terms in the contraction. Equivalent to the 'optimal'
+ path for most contractions.
+
+ Default is 'greedy'.
+
+ Returns
+ -------
+ path : list of tuples
+ A list representation of the einsum path.
+ string_repr : str
+ A printable representation of the einsum path.
+
+ Notes
+ -----
+ The resulting path indicates which terms of the input contraction should be
+ contracted first, the result of this contraction is then appended to the
+ end of the contraction list. This list can then be iterated over until all
+ intermediate contractions are complete.
+
+ See Also
+ --------
+ einsum, linalg.multi_dot
+
+ Examples
+ --------
+
+ We can begin with a chain dot example. In this case, it is optimal to
+ contract the ``b`` and ``c`` tensors first as represented by the first
+ element of the path ``(1, 2)``. The resulting tensor is added to the end
+ of the contraction and the remaining contraction ``(0, 1)`` is then
+ completed.
+
+ >>> np.random.seed(123)
+ >>> a = np.random.rand(2, 2)
+ >>> b = np.random.rand(2, 5)
+ >>> c = np.random.rand(5, 2)
+ >>> path_info = np.einsum_path('ij,jk,kl->il', a, b, c, optimize='greedy')
+ >>> print(path_info[0])
+ ['einsum_path', (1, 2), (0, 1)]
+ >>> print(path_info[1])
+ Complete contraction: ij,jk,kl->il # may vary
+ Naive scaling: 4
+ Optimized scaling: 3
+ Naive FLOP count: 1.600e+02
+ Optimized FLOP count: 5.600e+01
+ Theoretical speedup: 2.857
+ Largest intermediate: 4.000e+00 elements
+ -------------------------------------------------------------------------
+ scaling current remaining
+ -------------------------------------------------------------------------
+ 3 kl,jk->jl ij,jl->il
+ 3 jl,ij->il il->il
+
+
+ A more complex index transformation example.
+
+ >>> I = np.random.rand(10, 10, 10, 10)
+ >>> C = np.random.rand(10, 10)
+ >>> path_info = np.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C,
+ ... optimize='greedy')
+
+ >>> print(path_info[0])
+ ['einsum_path', (0, 2), (0, 3), (0, 2), (0, 1)]
+ >>> print(path_info[1])
+ Complete contraction: ea,fb,abcd,gc,hd->efgh # may vary
+ Naive scaling: 8
+ Optimized scaling: 5
+ Naive FLOP count: 8.000e+08
+ Optimized FLOP count: 8.000e+05
+ Theoretical speedup: 1000.000
+ Largest intermediate: 1.000e+04 elements
+ --------------------------------------------------------------------------
+ scaling current remaining
+ --------------------------------------------------------------------------
+ 5 abcd,ea->bcde fb,gc,hd,bcde->efgh
+ 5 bcde,fb->cdef gc,hd,cdef->efgh
+ 5 cdef,gc->defg hd,defg->efgh
+ 5 defg,hd->efgh efgh->efgh
+ """
+
+ # Figure out what the path really is
+ path_type = optimize
+ if path_type is True:
+ path_type = 'greedy'
+ if path_type is None:
+ path_type = False
+
+ explicit_einsum_path = False
+ memory_limit = None
+
+ # No optimization or a named path algorithm
+ if (path_type is False) or isinstance(path_type, str):
+ pass
+
+ # Given an explicit path
+ elif len(path_type) and (path_type[0] == 'einsum_path'):
+ explicit_einsum_path = True
+
+ # Path tuple with memory limit
+ elif ((len(path_type) == 2) and isinstance(path_type[0], str) and
+ isinstance(path_type[1], (int, float))):
+ memory_limit = int(path_type[1])
+ path_type = path_type[0]
+
+ else:
+ raise TypeError(f"Did not understand the path: {str(path_type)}")
+
+ # Hidden option, only einsum should call this
+ einsum_call_arg = einsum_call
+
+ # Python side parsing
+ input_subscripts, output_subscript, operands = (
+ _parse_einsum_input(operands)
+ )
+
+ # Build a few useful list and sets
+ input_list = input_subscripts.split(',')
+ num_inputs = len(input_list)
+ input_sets = [set(x) for x in input_list]
+ output_set = set(output_subscript)
+ indices = set(input_subscripts.replace(',', ''))
+ num_indices = len(indices)
+
+ # Get length of each unique dimension and ensure all dimensions are correct
+ dimension_dict = {}
+ for tnum, term in enumerate(input_list):
+ sh = operands[tnum].shape
+ if len(sh) != len(term):
+ raise ValueError("Einstein sum subscript %s does not contain the "
+ "correct number of indices for operand %d."
+ % (input_subscripts[tnum], tnum))
+ for cnum, char in enumerate(term):
+ dim = sh[cnum]
+
+ if char in dimension_dict.keys():
+ # For broadcasting cases we always want the largest dim size
+ if dimension_dict[char] == 1:
+ dimension_dict[char] = dim
+ elif dim not in (1, dimension_dict[char]):
+ raise ValueError("Size of label '%s' for operand %d (%d) "
+ "does not match previous terms (%d)."
+ % (char, tnum, dimension_dict[char], dim))
+ else:
+ dimension_dict[char] = dim
+
+ # Compute size of each input array plus the output array
+ size_list = [_compute_size_by_dict(term, dimension_dict)
+ for term in input_list + [output_subscript]]
+ max_size = max(size_list)
+
+ if memory_limit is None:
+ memory_arg = max_size
+ else:
+ memory_arg = memory_limit
+
+ # Compute the path
+ if explicit_einsum_path:
+ path = path_type[1:]
+ elif (
+ (path_type is False)
+ or (num_inputs in [1, 2])
+ or (indices == output_set)
+ ):
+ # Nothing to be optimized, leave it to einsum
+ path = [tuple(range(num_inputs))]
+ elif path_type == "greedy":
+ path = _greedy_path(
+ input_sets, output_set, dimension_dict, memory_arg
+ )
+ elif path_type == "optimal":
+ path = _optimal_path(
+ input_sets, output_set, dimension_dict, memory_arg
+ )
+ else:
+ raise KeyError("Path name %s not found", path_type)
+
+ cost_list, scale_list, size_list, contraction_list = [], [], [], []
+
+ # Build contraction tuple (positions, gemm, einsum_str, remaining)
+ for cnum, contract_inds in enumerate(path):
+ # Make sure we remove inds from right to left
+ contract_inds = tuple(sorted(contract_inds, reverse=True))
+
+ contract = _find_contraction(contract_inds, input_sets, output_set)
+ out_inds, input_sets, idx_removed, idx_contract = contract
+
+ if not einsum_call_arg:
+ # these are only needed for printing info
+ cost = _flop_count(
+ idx_contract, idx_removed, len(contract_inds), dimension_dict
+ )
+ cost_list.append(cost)
+ scale_list.append(len(idx_contract))
+ size_list.append(_compute_size_by_dict(out_inds, dimension_dict))
+
+ tmp_inputs = []
+ for x in contract_inds:
+ tmp_inputs.append(input_list.pop(x))
+
+ # Last contraction
+ if (cnum - len(path)) == -1:
+ idx_result = output_subscript
+ else:
+ sort_result = [(dimension_dict[ind], ind) for ind in out_inds]
+ idx_result = "".join([x[1] for x in sorted(sort_result)])
+
+ input_list.append(idx_result)
+ einsum_str = ",".join(tmp_inputs) + "->" + idx_result
+
+ contraction = (contract_inds, einsum_str, input_list[:])
+ contraction_list.append(contraction)
+
+ if len(input_list) != 1:
+ # Explicit "einsum_path" is usually trusted, but we detect this kind of
+ # mistake in order to prevent from returning an intermediate value.
+ raise RuntimeError(
+ f"Invalid einsum_path is specified: {len(input_list) - 1} more "
+ "operands has to be contracted.")
+
+ if einsum_call_arg:
+ return (operands, contraction_list)
+
+ # Return the path along with a nice string representation
+ overall_contraction = input_subscripts + "->" + output_subscript
+ header = ("scaling", "current", "remaining")
+
+ # Compute naive cost
+ # This isn't quite right, need to look into exactly how einsum does this
+ inner_product = (
+ sum(len(set(x)) for x in input_subscripts.split(',')) - num_indices
+ ) > 0
+ naive_cost = _flop_count(
+ indices, inner_product, num_inputs, dimension_dict
+ )
+
+ opt_cost = sum(cost_list) + 1
+ speedup = naive_cost / opt_cost
+ max_i = max(size_list)
+
+ path_print = f" Complete contraction: {overall_contraction}\n"
+ path_print += f" Naive scaling: {num_indices}\n"
+ path_print += " Optimized scaling: %d\n" % max(scale_list)
+ path_print += f" Naive FLOP count: {naive_cost:.3e}\n"
+ path_print += f" Optimized FLOP count: {opt_cost:.3e}\n"
+ path_print += f" Theoretical speedup: {speedup:3.3f}\n"
+ path_print += f" Largest intermediate: {max_i:.3e} elements\n"
+ path_print += "-" * 74 + "\n"
+ path_print += "%6s %24s %40s\n" % header
+ path_print += "-" * 74
+
+ for n, contraction in enumerate(contraction_list):
+ _, einsum_str, remaining = contraction
+ remaining_str = ",".join(remaining) + "->" + output_subscript
+ path_run = (scale_list[n], einsum_str, remaining_str)
+ path_print += "\n%4d %24s %40s" % path_run
+
+ path = ['einsum_path'] + path
+ return (path, path_print)
+
+
+def _parse_eq_to_pure_multiplication(a_term, shape_a, b_term, shape_b, out):
+ """If there are no contracted indices, then we can directly transpose and
+ insert singleton dimensions into ``a`` and ``b`` such that (broadcast)
+ elementwise multiplication performs the einsum.
+
+ No need to cache this as it is within the cached
+ ``_parse_eq_to_batch_matmul``.
+
+ """
+ desired_a = ""
+ desired_b = ""
+ new_shape_a = []
+ new_shape_b = []
+ for ix in out:
+ if ix in a_term:
+ desired_a += ix
+ new_shape_a.append(shape_a[a_term.index(ix)])
+ else:
+ new_shape_a.append(1)
+ if ix in b_term:
+ desired_b += ix
+ new_shape_b.append(shape_b[b_term.index(ix)])
+ else:
+ new_shape_b.append(1)
+
+ if desired_a != a_term:
+ eq_a = f"{a_term}->{desired_a}"
+ else:
+ eq_a = None
+ if desired_b != b_term:
+ eq_b = f"{b_term}->{desired_b}"
+ else:
+ eq_b = None
+
+ return (
+ eq_a,
+ eq_b,
+ new_shape_a,
+ new_shape_b,
+ None, # new_shape_ab, not needed since not fusing
+ None, # perm_ab, not needed as we transpose a and b first
+ True, # pure_multiplication=True
+ )
+
+
+@functools.lru_cache(2**12)
+def _parse_eq_to_batch_matmul(eq, shape_a, shape_b):
+ """Cached parsing of a two term einsum equation into the necessary
+ sequence of arguments for contracttion via batched matrix multiplication.
+ The steps we need to specify are:
+
+ 1. Remove repeated and trivial indices from the left and right terms,
+ and transpose them, done as a single einsum.
+ 2. Fuse the remaining indices so we have two 3D tensors.
+ 3. Perform the batched matrix multiplication.
+ 4. Unfuse the output to get the desired final index order.
+
+ """
+ lhs, out = eq.split("->")
+ a_term, b_term = lhs.split(",")
+
+ if len(a_term) != len(shape_a):
+ raise ValueError(f"Term '{a_term}' does not match shape {shape_a}.")
+ if len(b_term) != len(shape_b):
+ raise ValueError(f"Term '{b_term}' does not match shape {shape_b}.")
+
+ sizes = {}
+ singletons = set()
+
+ # parse left term to unique indices with size > 1
+ left = {}
+ for ix, d in zip(a_term, shape_a):
+ if d == 1:
+ # everything (including broadcasting) works nicely if simply ignore
+ # such dimensions, but we do need to track if they appear in output
+ # and thus should be reintroduced later
+ singletons.add(ix)
+ continue
+ if sizes.setdefault(ix, d) != d:
+ # set and check size
+ raise ValueError(
+ f"Index {ix} has mismatched sizes {sizes[ix]} and {d}."
+ )
+ left[ix] = True
+
+ # parse right term to unique indices with size > 1
+ right = {}
+ for ix, d in zip(b_term, shape_b):
+ # broadcast indices (size 1 on one input and size != 1
+ # on the other) should not be treated as singletons
+ if d == 1:
+ if ix not in left:
+ singletons.add(ix)
+ continue
+ singletons.discard(ix)
+
+ if sizes.setdefault(ix, d) != d:
+ # set and check size
+ raise ValueError(
+ f"Index {ix} has mismatched sizes {sizes[ix]} and {d}."
+ )
+ right[ix] = True
+
+ # now we classify the unique size > 1 indices only
+ bat_inds = [] # appears on A, B, O
+ con_inds = [] # appears on A, B, .
+ a_keep = [] # appears on A, ., O
+ b_keep = [] # appears on ., B, O
+ # other indices (appearing on A or B only) will
+ # be summed or traced out prior to the matmul
+ for ix in left:
+ if right.pop(ix, False):
+ if ix in out:
+ bat_inds.append(ix)
+ else:
+ con_inds.append(ix)
+ elif ix in out:
+ a_keep.append(ix)
+ # now only indices unique to right remain
+ for ix in right:
+ if ix in out:
+ b_keep.append(ix)
+
+ if not con_inds:
+ # contraction is pure multiplication, prepare inputs differently
+ return _parse_eq_to_pure_multiplication(
+ a_term, shape_a, b_term, shape_b, out
+ )
+
+ # only need the size one indices that appear in the output
+ singletons = [ix for ix in out if ix in singletons]
+
+ # take diagonal, remove any trivial axes and transpose left
+ desired_a = "".join((*bat_inds, *a_keep, *con_inds))
+ if a_term != desired_a:
+ eq_a = f"{a_term}->{desired_a}"
+ else:
+ eq_a = None
+
+ # take diagonal, remove any trivial axes and transpose right
+ desired_b = "".join((*bat_inds, *con_inds, *b_keep))
+ if b_term != desired_b:
+ eq_b = f"{b_term}->{desired_b}"
+ else:
+ eq_b = None
+
+ # then we want to reshape
+ if bat_inds:
+ lgroups = (bat_inds, a_keep, con_inds)
+ rgroups = (bat_inds, con_inds, b_keep)
+ ogroups = (bat_inds, a_keep, b_keep)
+ else:
+ # avoid size 1 batch dimension if no batch indices
+ lgroups = (a_keep, con_inds)
+ rgroups = (con_inds, b_keep)
+ ogroups = (a_keep, b_keep)
+
+ if any(len(group) != 1 for group in lgroups):
+ # need to fuse 'kept' and contracted indices
+ # (though could allow batch indices to be broadcast)
+ new_shape_a = tuple(
+ functools.reduce(operator.mul, (sizes[ix] for ix in ix_group), 1)
+ for ix_group in lgroups
+ )
+ else:
+ new_shape_a = None
+
+ if any(len(group) != 1 for group in rgroups):
+ # need to fuse 'kept' and contracted indices
+ # (though could allow batch indices to be broadcast)
+ new_shape_b = tuple(
+ functools.reduce(operator.mul, (sizes[ix] for ix in ix_group), 1)
+ for ix_group in rgroups
+ )
+ else:
+ new_shape_b = None
+
+ if any(len(group) != 1 for group in ogroups) or singletons:
+ new_shape_ab = (1,) * len(singletons) + tuple(
+ sizes[ix] for ix_group in ogroups for ix in ix_group
+ )
+ else:
+ new_shape_ab = None
+
+ # then we might need to permute the matmul produced output:
+ out_produced = "".join((*singletons, *bat_inds, *a_keep, *b_keep))
+ if out_produced != out:
+ perm_ab = tuple(out_produced.index(ix) for ix in out)
+ else:
+ perm_ab = None
+
+ return (
+ eq_a,
+ eq_b,
+ new_shape_a,
+ new_shape_b,
+ new_shape_ab,
+ perm_ab,
+ False, # pure_multiplication=False
+ )
+
+
+@functools.lru_cache(maxsize=64)
+def _parse_output_order(order, a_is_fcontig, b_is_fcontig):
+ order = order.upper()
+ if order == "K":
+ return None
+ elif order in "CF":
+ return order
+ elif order == "A":
+ if a_is_fcontig and b_is_fcontig:
+ return "F"
+ else:
+ return "C"
+ else:
+ raise ValueError(
+ "ValueError: order must be one of "
+ f"'C', 'F', 'A', or 'K' (got '{order}')"
+ )
+
+
+def bmm_einsum(eq, a, b, out=None, **kwargs):
+ """Perform arbitrary pairwise einsums using only ``matmul``, or
+ ``multiply`` if no contracted indices are involved (plus maybe single term
+ ``einsum`` to prepare the terms individually). The logic for each is cached
+ based on the equation and array shape, and each step is only performed if
+ necessary.
+
+ Parameters
+ ----------
+ eq : str
+ The einsum equation.
+ a : array_like
+ The first array to contract.
+ b : array_like
+ The second array to contract.
+
+ Returns
+ -------
+ array_like
+
+ Notes
+ -----
+ A fuller description of this algorithm, and original source for this
+ implementation, can be found at https://github.com/jcmgray/einsum_bmm.
+ """
+ (
+ eq_a,
+ eq_b,
+ new_shape_a,
+ new_shape_b,
+ new_shape_ab,
+ perm_ab,
+ pure_multiplication,
+ ) = _parse_eq_to_batch_matmul(eq, a.shape, b.shape)
+
+ # n.b. one could special case various cases to call c_einsum directly here
+
+ # need to handle `order` a little manually, since we do transpose
+ # operations before and potentially after the ufunc calls
+ output_order = _parse_output_order(
+ kwargs.pop("order", "K"), a.flags.f_contiguous, b.flags.f_contiguous
+ )
+
+ # prepare left
+ if eq_a is not None:
+ # diagonals, sums, and tranpose
+ a = c_einsum(eq_a, a)
+ if new_shape_a is not None:
+ a = reshape(a, new_shape_a)
+
+ # prepare right
+ if eq_b is not None:
+ # diagonals, sums, and tranpose
+ b = c_einsum(eq_b, b)
+ if new_shape_b is not None:
+ b = reshape(b, new_shape_b)
+
+ if pure_multiplication:
+ # no contracted indices
+ if output_order is not None:
+ kwargs["order"] = output_order
+
+ # do the 'contraction' via multiplication!
+ return multiply(a, b, out=out, **kwargs)
+
+ # can only supply out here if no other reshaping / transposing
+ matmul_out_compatible = (new_shape_ab is None) and (perm_ab is None)
+ if matmul_out_compatible:
+ kwargs["out"] = out
+
+ # do the contraction!
+ ab = matmul(a, b, **kwargs)
+
+ # prepare the output
+ if new_shape_ab is not None:
+ ab = reshape(ab, new_shape_ab)
+ if perm_ab is not None:
+ ab = ab.transpose(perm_ab)
+
+ if (out is not None) and (not matmul_out_compatible):
+ # handle case where out is specified, but we also needed
+ # to reshape / transpose ``ab`` after the matmul
+ out[:] = ab
+ ab = out
+ elif output_order is not None:
+ ab = asanyarray(ab, order=output_order)
+
+ return ab
+
+
+def _einsum_dispatcher(*operands, out=None, optimize=None, **kwargs):
+ # Arguably we dispatch on more arguments than we really should; see note in
+ # _einsum_path_dispatcher for why.
+ yield from operands
+ yield out
+
+
+# Rewrite einsum to handle different cases
+@array_function_dispatch(_einsum_dispatcher, module='numpy')
+def einsum(*operands, out=None, optimize=False, **kwargs):
+ """
+ einsum(subscripts, *operands, out=None, dtype=None, order='K',
+ casting='safe', optimize=False)
+
+ Evaluates the Einstein summation convention on the operands.
+
+ Using the Einstein summation convention, many common multi-dimensional,
+ linear algebraic array operations can be represented in a simple fashion.
+ In *implicit* mode `einsum` computes these values.
+
+ In *explicit* mode, `einsum` provides further flexibility to compute
+ other array operations that might not be considered classical Einstein
+ summation operations, by disabling, or forcing summation over specified
+ subscript labels.
+
+ See the notes and examples for clarification.
+
+ Parameters
+ ----------
+ subscripts : str
+ Specifies the subscripts for summation as comma separated list of
+ subscript labels. An implicit (classical Einstein summation)
+ calculation is performed unless the explicit indicator '->' is
+ included as well as subscript labels of the precise output form.
+ operands : list of array_like
+ These are the arrays for the operation.
+ out : ndarray, optional
+ If provided, the calculation is done into this array.
+ dtype : {data-type, None}, optional
+ If provided, forces the calculation to use the data type specified.
+ Note that you may have to also give a more liberal `casting`
+ parameter to allow the conversions. Default is None.
+ order : {'C', 'F', 'A', 'K'}, optional
+ Controls the memory layout of the output. 'C' means it should
+ be C contiguous. 'F' means it should be Fortran contiguous,
+ 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise.
+ 'K' means it should be as close to the layout as the inputs as
+ is possible, including arbitrarily permuted axes.
+ Default is 'K'.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Setting this to
+ 'unsafe' is not recommended, as it can adversely affect accumulations.
+
+ * 'no' means the data types should not be cast at all.
+ * 'equiv' means only byte-order changes are allowed.
+ * 'safe' means only casts which can preserve values are allowed.
+ * 'same_kind' means only safe casts or casts within a kind,
+ like float64 to float32, are allowed.
+ * 'unsafe' means any data conversions may be done.
+
+ Default is 'safe'.
+ optimize : {False, True, 'greedy', 'optimal'}, optional
+ Controls if intermediate optimization should occur. No optimization
+ will occur if False and True will default to the 'greedy' algorithm.
+ Also accepts an explicit contraction list from the ``np.einsum_path``
+ function. See ``np.einsum_path`` for more details. Defaults to False.
+
+ Returns
+ -------
+ output : ndarray
+ The calculation based on the Einstein summation convention.
+
+ See Also
+ --------
+ einsum_path, dot, inner, outer, tensordot, linalg.multi_dot
+ einsum:
+ Similar verbose interface is provided by the
+ `einops `_ package to cover
+ additional operations: transpose, reshape/flatten, repeat/tile,
+ squeeze/unsqueeze and reductions.
+ The `opt_einsum `_
+ optimizes contraction order for einsum-like expressions
+ in backend-agnostic manner.
+
+ Notes
+ -----
+ The Einstein summation convention can be used to compute
+ many multi-dimensional, linear algebraic array operations. `einsum`
+ provides a succinct way of representing these.
+
+ A non-exhaustive list of these operations,
+ which can be computed by `einsum`, is shown below along with examples:
+
+ * Trace of an array, :py:func:`numpy.trace`.
+ * Return a diagonal, :py:func:`numpy.diag`.
+ * Array axis summations, :py:func:`numpy.sum`.
+ * Transpositions and permutations, :py:func:`numpy.transpose`.
+ * Matrix multiplication and dot product, :py:func:`numpy.matmul`
+ :py:func:`numpy.dot`.
+ * Vector inner and outer products, :py:func:`numpy.inner`
+ :py:func:`numpy.outer`.
+ * Broadcasting, element-wise and scalar multiplication,
+ :py:func:`numpy.multiply`.
+ * Tensor contractions, :py:func:`numpy.tensordot`.
+ * Chained array operations, in efficient calculation order,
+ :py:func:`numpy.einsum_path`.
+
+ The subscripts string is a comma-separated list of subscript labels,
+ where each label refers to a dimension of the corresponding operand.
+ Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
+ is equivalent to :py:func:`np.inner(a,b) `. If a label
+ appears only once, it is not summed, so ``np.einsum('i', a)``
+ produces a view of ``a`` with no changes. A further example
+ ``np.einsum('ij,jk', a, b)`` describes traditional matrix multiplication
+ and is equivalent to :py:func:`np.matmul(a,b) `.
+ Repeated subscript labels in one operand take the diagonal.
+ For example, ``np.einsum('ii', a)`` is equivalent to
+ :py:func:`np.trace(a) `.
+
+ In *implicit mode*, the chosen subscripts are important
+ since the axes of the output are reordered alphabetically. This
+ means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
+ ``np.einsum('ji', a)`` takes its transpose. Additionally,
+ ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
+ ``np.einsum('ij,jh', a, b)`` returns the transpose of the
+ multiplication since subscript 'h' precedes subscript 'i'.
+
+ In *explicit mode* the output can be directly controlled by
+ specifying output subscript labels. This requires the
+ identifier '->' as well as the list of output subscript labels.
+ This feature increases the flexibility of the function since
+ summing can be disabled or forced when required. The call
+ ``np.einsum('i->', a)`` is like :py:func:`np.sum(a) `
+ if ``a`` is a 1-D array, and ``np.einsum('ii->i', a)``
+ is like :py:func:`np.diag(a) ` if ``a`` is a square 2-D array.
+ The difference is that `einsum` does not allow broadcasting by default.
+ Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
+ order of the output subscript labels and therefore returns matrix
+ multiplication, unlike the example above in implicit mode.
+
+ To enable and control broadcasting, use an ellipsis. Default
+ NumPy-style broadcasting is done by adding an ellipsis
+ to the left of each term, like ``np.einsum('...ii->...i', a)``.
+ ``np.einsum('...i->...', a)`` is like
+ :py:func:`np.sum(a, axis=-1) ` for array ``a`` of any shape.
+ To take the trace along the first and last axes,
+ you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
+ product with the left-most indices instead of rightmost, one can do
+ ``np.einsum('ij...,jk...->ik...', a, b)``.
+
+ When there is only one operand, no axes are summed, and no output
+ parameter is provided, a view into the operand is returned instead
+ of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``
+ produces a view (changed in version 1.10.0).
+
+ `einsum` also provides an alternative way to provide the subscripts and
+ operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``.
+ If the output shape is not provided in this format `einsum` will be
+ calculated in implicit mode, otherwise it will be performed explicitly.
+ The examples below have corresponding `einsum` calls with the two
+ parameter methods.
+
+ Views returned from einsum are now writeable whenever the input array
+ is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now
+ have the same effect as :py:func:`np.swapaxes(a, 0, 2) `
+ and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal
+ of a 2D array.
+
+ Added the ``optimize`` argument which will optimize the contraction order
+ of an einsum expression. For a contraction with three or more operands
+ this can greatly increase the computational efficiency at the cost of
+ a larger memory footprint during computation.
+
+ Typically a 'greedy' algorithm is applied which empirical tests have shown
+ returns the optimal path in the majority of cases. In some cases 'optimal'
+ will return the superlative path through a more expensive, exhaustive
+ search. For iterative calculations it may be advisable to calculate
+ the optimal path once and reuse that path by supplying it as an argument.
+ An example is given below.
+
+ See :py:func:`numpy.einsum_path` for more details.
+
+ Examples
+ --------
+ >>> a = np.arange(25).reshape(5,5)
+ >>> b = np.arange(5)
+ >>> c = np.arange(6).reshape(2,3)
+
+ Trace of a matrix:
+
+ >>> np.einsum('ii', a)
+ 60
+ >>> np.einsum(a, [0,0])
+ 60
+ >>> np.trace(a)
+ 60
+
+ Extract the diagonal (requires explicit form):
+
+ >>> np.einsum('ii->i', a)
+ array([ 0, 6, 12, 18, 24])
+ >>> np.einsum(a, [0,0], [0])
+ array([ 0, 6, 12, 18, 24])
+ >>> np.diag(a)
+ array([ 0, 6, 12, 18, 24])
+
+ Sum over an axis (requires explicit form):
+
+ >>> np.einsum('ij->i', a)
+ array([ 10, 35, 60, 85, 110])
+ >>> np.einsum(a, [0,1], [0])
+ array([ 10, 35, 60, 85, 110])
+ >>> np.sum(a, axis=1)
+ array([ 10, 35, 60, 85, 110])
+
+ For higher dimensional arrays summing a single axis can be done
+ with ellipsis:
+
+ >>> np.einsum('...j->...', a)
+ array([ 10, 35, 60, 85, 110])
+ >>> np.einsum(a, [Ellipsis,1], [Ellipsis])
+ array([ 10, 35, 60, 85, 110])
+
+ Compute a matrix transpose, or reorder any number of axes:
+
+ >>> np.einsum('ji', c)
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+ >>> np.einsum('ij->ji', c)
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+ >>> np.einsum(c, [1,0])
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+ >>> np.transpose(c)
+ array([[0, 3],
+ [1, 4],
+ [2, 5]])
+
+ Vector inner products:
+
+ >>> np.einsum('i,i', b, b)
+ 30
+ >>> np.einsum(b, [0], b, [0])
+ 30
+ >>> np.inner(b,b)
+ 30
+
+ Matrix vector multiplication:
+
+ >>> np.einsum('ij,j', a, b)
+ array([ 30, 80, 130, 180, 230])
+ >>> np.einsum(a, [0,1], b, [1])
+ array([ 30, 80, 130, 180, 230])
+ >>> np.dot(a, b)
+ array([ 30, 80, 130, 180, 230])
+ >>> np.einsum('...j,j', a, b)
+ array([ 30, 80, 130, 180, 230])
+
+ Broadcasting and scalar multiplication:
+
+ >>> np.einsum('..., ...', 3, c)
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+ >>> np.einsum(',ij', 3, c)
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+ >>> np.einsum(3, [Ellipsis], c, [Ellipsis])
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+ >>> np.multiply(3, c)
+ array([[ 0, 3, 6],
+ [ 9, 12, 15]])
+
+ Vector outer product:
+
+ >>> np.einsum('i,j', np.arange(2)+1, b)
+ array([[0, 1, 2, 3, 4],
+ [0, 2, 4, 6, 8]])
+ >>> np.einsum(np.arange(2)+1, [0], b, [1])
+ array([[0, 1, 2, 3, 4],
+ [0, 2, 4, 6, 8]])
+ >>> np.outer(np.arange(2)+1, b)
+ array([[0, 1, 2, 3, 4],
+ [0, 2, 4, 6, 8]])
+
+ Tensor contraction:
+
+ >>> a = np.arange(60.).reshape(3,4,5)
+ >>> b = np.arange(24.).reshape(4,3,2)
+ >>> np.einsum('ijk,jil->kl', a, b)
+ array([[4400., 4730.],
+ [4532., 4874.],
+ [4664., 5018.],
+ [4796., 5162.],
+ [4928., 5306.]])
+ >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])
+ array([[4400., 4730.],
+ [4532., 4874.],
+ [4664., 5018.],
+ [4796., 5162.],
+ [4928., 5306.]])
+ >>> np.tensordot(a,b, axes=([1,0],[0,1]))
+ array([[4400., 4730.],
+ [4532., 4874.],
+ [4664., 5018.],
+ [4796., 5162.],
+ [4928., 5306.]])
+
+ Writeable returned arrays (since version 1.10.0):
+
+ >>> a = np.zeros((3, 3))
+ >>> np.einsum('ii->i', a)[:] = 1
+ >>> a
+ array([[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]])
+
+ Example of ellipsis use:
+
+ >>> a = np.arange(6).reshape((3,2))
+ >>> b = np.arange(12).reshape((4,3))
+ >>> np.einsum('ki,jk->ij', a, b)
+ array([[10, 28, 46, 64],
+ [13, 40, 67, 94]])
+ >>> np.einsum('ki,...k->i...', a, b)
+ array([[10, 28, 46, 64],
+ [13, 40, 67, 94]])
+ >>> np.einsum('k...,jk', a, b)
+ array([[10, 28, 46, 64],
+ [13, 40, 67, 94]])
+
+ Chained array operations. For more complicated contractions, speed ups
+ might be achieved by repeatedly computing a 'greedy' path or pre-computing
+ the 'optimal' path and repeatedly applying it, using an `einsum_path`
+ insertion (since version 1.12.0). Performance improvements can be
+ particularly significant with larger arrays:
+
+ >>> a = np.ones(64).reshape(2,4,8)
+
+ Basic `einsum`: ~1520ms (benchmarked on 3.1GHz Intel i5.)
+
+ >>> for iteration in range(500):
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)
+
+ Sub-optimal `einsum` (due to repeated path calculation time): ~330ms
+
+ >>> for iteration in range(500):
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a,
+ ... optimize='optimal')
+
+ Greedy `einsum` (faster optimal path approximation): ~160ms
+
+ >>> for iteration in range(500):
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='greedy')
+
+ Optimal `einsum` (best usage pattern in some use cases): ~110ms
+
+ >>> path = np.einsum_path('ijk,ilm,njm,nlk,abc->',a,a,a,a,a,
+ ... optimize='optimal')[0]
+ >>> for iteration in range(500):
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=path)
+
+ """
+ # Special handling if out is specified
+ specified_out = out is not None
+
+ # If no optimization, run pure einsum
+ if optimize is False:
+ if specified_out:
+ kwargs['out'] = out
+ return c_einsum(*operands, **kwargs)
+
+ # Check the kwargs to avoid a more cryptic error later, without having to
+ # repeat default values here
+ valid_einsum_kwargs = ['dtype', 'order', 'casting']
+ unknown_kwargs = [k for (k, v) in kwargs.items() if
+ k not in valid_einsum_kwargs]
+ if len(unknown_kwargs):
+ raise TypeError(f"Did not understand the following kwargs: {unknown_kwargs}")
+
+ # Build the contraction list and operand
+ operands, contraction_list = einsum_path(*operands, optimize=optimize,
+ einsum_call=True)
+
+ # Start contraction loop
+ for num, contraction in enumerate(contraction_list):
+ inds, einsum_str, _ = contraction
+ tmp_operands = [operands.pop(x) for x in inds]
+
+ # Do we need to deal with the output?
+ handle_out = specified_out and ((num + 1) == len(contraction_list))
+
+ # If out was specified
+ if handle_out:
+ kwargs["out"] = out
+
+ if len(tmp_operands) == 2:
+ # Call (batched) matrix multiplication if possible
+ new_view = bmm_einsum(einsum_str, *tmp_operands, **kwargs)
+ else:
+ # Call einsum
+ new_view = c_einsum(einsum_str, *tmp_operands, **kwargs)
+
+ # Append new items and dereference what we can
+ operands.append(new_view)
+ del tmp_operands, new_view
+
+ if specified_out:
+ return out
+ else:
+ return operands[0]
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/einsumfunc.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/einsumfunc.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..6d34883e66256d0dfe51661caa5218997dd53e9b
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/einsumfunc.pyi
@@ -0,0 +1,184 @@
+from collections.abc import Sequence
+from typing import Any, Literal, TypeAlias, TypeVar, overload
+
+import numpy as np
+from numpy import _OrderKACF, number
+from numpy._typing import (
+ NDArray,
+ _ArrayLikeBool_co,
+ _ArrayLikeComplex_co,
+ _ArrayLikeFloat_co,
+ _ArrayLikeInt_co,
+ _ArrayLikeObject_co,
+ _ArrayLikeUInt_co,
+ _DTypeLikeBool,
+ _DTypeLikeComplex,
+ _DTypeLikeComplex_co,
+ _DTypeLikeFloat,
+ _DTypeLikeInt,
+ _DTypeLikeObject,
+ _DTypeLikeUInt,
+)
+
+__all__ = ["einsum", "einsum_path"]
+
+_ArrayT = TypeVar(
+ "_ArrayT",
+ bound=NDArray[np.bool | number],
+)
+
+_OptimizeKind: TypeAlias = bool | Literal["greedy", "optimal"] | Sequence[Any] | None
+_CastingSafe: TypeAlias = Literal["no", "equiv", "safe", "same_kind"]
+_CastingUnsafe: TypeAlias = Literal["unsafe"]
+
+# TODO: Properly handle the `casting`-based combinatorics
+# TODO: We need to evaluate the content `__subscripts` in order
+# to identify whether or an array or scalar is returned. At a cursory
+# glance this seems like something that can quite easily be done with
+# a mypy plugin.
+# Something like `is_scalar = bool(__subscripts.partition("->")[-1])`
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeBool_co,
+ out: None = None,
+ dtype: _DTypeLikeBool | None = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = False,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeUInt_co,
+ out: None = None,
+ dtype: _DTypeLikeUInt | None = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = False,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeInt_co,
+ out: None = None,
+ dtype: _DTypeLikeInt | None = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = False,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeFloat_co,
+ out: None = None,
+ dtype: _DTypeLikeFloat | None = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = False,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeComplex_co,
+ out: None = None,
+ dtype: _DTypeLikeComplex | None = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = False,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: Any,
+ casting: _CastingUnsafe,
+ dtype: _DTypeLikeComplex_co | None = ...,
+ out: None = None,
+ order: _OrderKACF = ...,
+ optimize: _OptimizeKind = False,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeComplex_co,
+ out: _ArrayT,
+ dtype: _DTypeLikeComplex_co | None = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = False,
+) -> _ArrayT: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: Any,
+ out: _ArrayT,
+ casting: _CastingUnsafe,
+ dtype: _DTypeLikeComplex_co | None = ...,
+ order: _OrderKACF = ...,
+ optimize: _OptimizeKind = False,
+) -> _ArrayT: ...
+
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeObject_co,
+ out: None = None,
+ dtype: _DTypeLikeObject | None = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = False,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: Any,
+ casting: _CastingUnsafe,
+ dtype: _DTypeLikeObject | None = ...,
+ out: None = None,
+ order: _OrderKACF = ...,
+ optimize: _OptimizeKind = False,
+) -> Any: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeObject_co,
+ out: _ArrayT,
+ dtype: _DTypeLikeObject | None = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingSafe = ...,
+ optimize: _OptimizeKind = False,
+) -> _ArrayT: ...
+@overload
+def einsum(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: Any,
+ out: _ArrayT,
+ casting: _CastingUnsafe,
+ dtype: _DTypeLikeObject | None = ...,
+ order: _OrderKACF = ...,
+ optimize: _OptimizeKind = False,
+) -> _ArrayT: ...
+
+# NOTE: `einsum_call` is a hidden kwarg unavailable for public use.
+# It is therefore excluded from the signatures below.
+# NOTE: In practice the list consists of a `str` (first element)
+# and a variable number of integer tuples.
+def einsum_path(
+ subscripts: str | _ArrayLikeInt_co,
+ /,
+ *operands: _ArrayLikeComplex_co | _DTypeLikeObject,
+ optimize: _OptimizeKind = "greedy",
+ einsum_call: Literal[False] = False,
+) -> tuple[list[Any], str]: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/fromnumeric.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/fromnumeric.py
new file mode 100644
index 0000000000000000000000000000000000000000..33fb9ec4b39fc2ce6e1737ad432a365d8305b694
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/fromnumeric.py
@@ -0,0 +1,4233 @@
+"""Module containing non-deprecated functions borrowed from Numeric.
+
+"""
+import functools
+import math
+import types
+
+import numpy as np
+from numpy._utils import set_module
+
+from . import _methods, multiarray as mu, numerictypes as nt, overrides, umath as um
+from ._multiarray_umath import _array_converter
+from .multiarray import asanyarray, asarray, concatenate
+
+_dt_ = nt.sctype2char
+
+# functions that are methods
+__all__ = [
+ 'all', 'amax', 'amin', 'any', 'argmax',
+ 'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip',
+ 'compress', 'cumprod', 'cumsum', 'cumulative_prod', 'cumulative_sum',
+ 'diagonal', 'mean', 'max', 'min', 'matrix_transpose',
+ 'ndim', 'nonzero', 'partition', 'prod', 'ptp', 'put',
+ 'ravel', 'repeat', 'reshape', 'resize', 'round',
+ 'searchsorted', 'shape', 'size', 'sort', 'squeeze',
+ 'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var',
+]
+
+_gentype = types.GeneratorType
+# save away Python sum
+_sum_ = sum
+
+array_function_dispatch = functools.partial(
+ overrides.array_function_dispatch, module='numpy')
+
+
+# functions that are now methods
+def _wrapit(obj, method, *args, **kwds):
+ conv = _array_converter(obj)
+ # As this already tried the method, subok is maybe quite reasonable here
+ # but this follows what was done before. TODO: revisit this.
+ arr, = conv.as_arrays(subok=False)
+ result = getattr(arr, method)(*args, **kwds)
+
+ return conv.wrap(result, to_scalar=False)
+
+
+def _wrapfunc(obj, method, *args, **kwds):
+ bound = getattr(obj, method, None)
+ if bound is None:
+ return _wrapit(obj, method, *args, **kwds)
+
+ try:
+ return bound(*args, **kwds)
+ except TypeError:
+ # A TypeError occurs if the object does have such a method in its
+ # class, but its signature is not identical to that of NumPy's. This
+ # situation has occurred in the case of a downstream library like
+ # 'pandas'.
+ #
+ # Call _wrapit from within the except clause to ensure a potential
+ # exception has a traceback chain.
+ return _wrapit(obj, method, *args, **kwds)
+
+
+def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs):
+ passkwargs = {k: v for k, v in kwargs.items()
+ if v is not np._NoValue}
+
+ if type(obj) is not mu.ndarray:
+ try:
+ reduction = getattr(obj, method)
+ except AttributeError:
+ pass
+ else:
+ # This branch is needed for reductions like any which don't
+ # support a dtype.
+ if dtype is not None:
+ return reduction(axis=axis, dtype=dtype, out=out, **passkwargs)
+ else:
+ return reduction(axis=axis, out=out, **passkwargs)
+
+ return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
+
+
+def _wrapreduction_any_all(obj, ufunc, method, axis, out, **kwargs):
+ # Same as above function, but dtype is always bool (but never passed on)
+ passkwargs = {k: v for k, v in kwargs.items()
+ if v is not np._NoValue}
+
+ if type(obj) is not mu.ndarray:
+ try:
+ reduction = getattr(obj, method)
+ except AttributeError:
+ pass
+ else:
+ return reduction(axis=axis, out=out, **passkwargs)
+
+ return ufunc.reduce(obj, axis, bool, out, **passkwargs)
+
+
+def _take_dispatcher(a, indices, axis=None, out=None, mode=None):
+ return (a, out)
+
+
+@array_function_dispatch(_take_dispatcher)
+def take(a, indices, axis=None, out=None, mode='raise'):
+ """
+ Take elements from an array along an axis.
+
+ When axis is not None, this function does the same thing as "fancy"
+ indexing (indexing arrays using arrays); however, it can be easier to use
+ if you need elements along a given axis. A call such as
+ ``np.take(arr, indices, axis=3)`` is equivalent to
+ ``arr[:,:,:,indices,...]``.
+
+ Explained without fancy indexing, this is equivalent to the following use
+ of `ndindex`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of
+ indices::
+
+ Ni, Nk = a.shape[:axis], a.shape[axis+1:]
+ Nj = indices.shape
+ for ii in ndindex(Ni):
+ for jj in ndindex(Nj):
+ for kk in ndindex(Nk):
+ out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
+
+ Parameters
+ ----------
+ a : array_like (Ni..., M, Nk...)
+ The source array.
+ indices : array_like (Nj...)
+ The indices of the values to extract.
+ Also allow scalars for indices.
+ axis : int, optional
+ The axis over which to select values. By default, the flattened
+ input array is used.
+ out : ndarray, optional (Ni..., Nj..., Nk...)
+ If provided, the result will be placed in this array. It should
+ be of the appropriate shape and dtype. Note that `out` is always
+ buffered if `mode='raise'`; use other modes for better performance.
+ mode : {'raise', 'wrap', 'clip'}, optional
+ Specifies how out-of-bounds indices will behave.
+
+ * 'raise' -- raise an error (default)
+ * 'wrap' -- wrap around
+ * 'clip' -- clip to the range
+
+ 'clip' mode means that all indices that are too large are replaced
+ by the index that addresses the last element along that axis. Note
+ that this disables indexing with negative numbers.
+
+ Returns
+ -------
+ out : ndarray (Ni..., Nj..., Nk...)
+ The returned array has the same type as `a`.
+
+ See Also
+ --------
+ compress : Take elements using a boolean mask
+ ndarray.take : equivalent method
+ take_along_axis : Take elements by matching the array and the index arrays
+
+ Notes
+ -----
+ By eliminating the inner loop in the description above, and using `s_` to
+ build simple slice objects, `take` can be expressed in terms of applying
+ fancy indexing to each 1-d slice::
+
+ Ni, Nk = a.shape[:axis], a.shape[axis+1:]
+ for ii in ndindex(Ni):
+ for kk in ndindex(Nk):
+ out[ii + s_[...,] + kk] = a[ii + s_[:,] + kk][indices]
+
+ For this reason, it is equivalent to (but faster than) the following use
+ of `apply_along_axis`::
+
+ out = np.apply_along_axis(lambda a_1d: a_1d[indices], axis, a)
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = [4, 3, 5, 7, 6, 8]
+ >>> indices = [0, 1, 4]
+ >>> np.take(a, indices)
+ array([4, 3, 6])
+
+ In this example if `a` is an ndarray, "fancy" indexing can be used.
+
+ >>> a = np.array(a)
+ >>> a[indices]
+ array([4, 3, 6])
+
+ If `indices` is not one dimensional, the output also has these dimensions.
+
+ >>> np.take(a, [[0, 1], [2, 3]])
+ array([[4, 3],
+ [5, 7]])
+ """
+ return _wrapfunc(a, 'take', indices, axis=axis, out=out, mode=mode)
+
+
+def _reshape_dispatcher(a, /, shape, order=None, *, copy=None):
+ return (a,)
+
+
+@array_function_dispatch(_reshape_dispatcher)
+def reshape(a, /, shape, order='C', *, copy=None):
+ """
+ Gives a new shape to an array without changing its data.
+
+ Parameters
+ ----------
+ a : array_like
+ Array to be reshaped.
+ shape : int or tuple of ints
+ The new shape should be compatible with the original shape. If
+ an integer, then the result will be a 1-D array of that length.
+ One shape dimension can be -1. In this case, the value is
+ inferred from the length of the array and remaining dimensions.
+ order : {'C', 'F', 'A'}, optional
+ Read the elements of ``a`` using this index order, and place the
+ elements into the reshaped array using this index order. 'C'
+ means to read / write the elements using C-like index order,
+ with the last axis index changing fastest, back to the first
+ axis index changing slowest. 'F' means to read / write the
+ elements using Fortran-like index order, with the first index
+ changing fastest, and the last index changing slowest. Note that
+ the 'C' and 'F' options take no account of the memory layout of
+ the underlying array, and only refer to the order of indexing.
+ 'A' means to read / write the elements in Fortran-like index
+ order if ``a`` is Fortran *contiguous* in memory, C-like order
+ otherwise.
+ copy : bool, optional
+ If ``True``, then the array data is copied. If ``None``, a copy will
+ only be made if it's required by ``order``. For ``False`` it raises
+ a ``ValueError`` if a copy cannot be avoided. Default: ``None``.
+
+ Returns
+ -------
+ reshaped_array : ndarray
+ This will be a new view object if possible; otherwise, it will
+ be a copy. Note there is no guarantee of the *memory layout* (C- or
+ Fortran- contiguous) of the returned array.
+
+ See Also
+ --------
+ ndarray.reshape : Equivalent method.
+
+ Notes
+ -----
+ It is not always possible to change the shape of an array without copying
+ the data.
+
+ The ``order`` keyword gives the index ordering both for *fetching*
+ the values from ``a``, and then *placing* the values into the output
+ array. For example, let's say you have an array:
+
+ >>> a = np.arange(6).reshape((3, 2))
+ >>> a
+ array([[0, 1],
+ [2, 3],
+ [4, 5]])
+
+ You can think of reshaping as first raveling the array (using the given
+ index order), then inserting the elements from the raveled array into the
+ new array using the same kind of index ordering as was used for the
+ raveling.
+
+ >>> np.reshape(a, (2, 3)) # C-like index ordering
+ array([[0, 1, 2],
+ [3, 4, 5]])
+ >>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
+ array([[0, 1, 2],
+ [3, 4, 5]])
+ >>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
+ array([[0, 4, 3],
+ [2, 1, 5]])
+ >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
+ array([[0, 4, 3],
+ [2, 1, 5]])
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1,2,3], [4,5,6]])
+ >>> np.reshape(a, 6)
+ array([1, 2, 3, 4, 5, 6])
+ >>> np.reshape(a, 6, order='F')
+ array([1, 4, 2, 5, 3, 6])
+
+ >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
+ array([[1, 2],
+ [3, 4],
+ [5, 6]])
+ """
+ if copy is not None:
+ return _wrapfunc(a, 'reshape', shape, order=order, copy=copy)
+ return _wrapfunc(a, 'reshape', shape, order=order)
+
+
+def _choose_dispatcher(a, choices, out=None, mode=None):
+ yield a
+ yield from choices
+ yield out
+
+
+@array_function_dispatch(_choose_dispatcher)
+def choose(a, choices, out=None, mode='raise'):
+ """
+ Construct an array from an index array and a list of arrays to choose from.
+
+ First of all, if confused or uncertain, definitely look at the Examples -
+ in its full generality, this function is less simple than it might
+ seem from the following code description::
+
+ np.choose(a,c) == np.array([c[a[I]][I] for I in np.ndindex(a.shape)])
+
+ But this omits some subtleties. Here is a fully general summary:
+
+ Given an "index" array (`a`) of integers and a sequence of ``n`` arrays
+ (`choices`), `a` and each choice array are first broadcast, as necessary,
+ to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
+ 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
+ for each ``i``. Then, a new array with shape ``Ba.shape`` is created as
+ follows:
+
+ * if ``mode='raise'`` (the default), then, first of all, each element of
+ ``a`` (and thus ``Ba``) must be in the range ``[0, n-1]``; now, suppose
+ that ``i`` (in that range) is the value at the ``(j0, j1, ..., jm)``
+ position in ``Ba`` - then the value at the same position in the new array
+ is the value in ``Bchoices[i]`` at that same position;
+
+ * if ``mode='wrap'``, values in `a` (and thus `Ba`) may be any (signed)
+ integer; modular arithmetic is used to map integers outside the range
+ `[0, n-1]` back into that range; and then the new array is constructed
+ as above;
+
+ * if ``mode='clip'``, values in `a` (and thus ``Ba``) may be any (signed)
+ integer; negative integers are mapped to 0; values greater than ``n-1``
+ are mapped to ``n-1``; and then the new array is constructed as above.
+
+ Parameters
+ ----------
+ a : int array
+ This array must contain integers in ``[0, n-1]``, where ``n`` is the
+ number of choices, unless ``mode=wrap`` or ``mode=clip``, in which
+ cases any integers are permissible.
+ choices : sequence of arrays
+ Choice arrays. `a` and all of the choices must be broadcastable to the
+ same shape. If `choices` is itself an array (not recommended), then
+ its outermost dimension (i.e., the one corresponding to
+ ``choices.shape[0]``) is taken as defining the "sequence".
+ out : array, optional
+ If provided, the result will be inserted into this array. It should
+ be of the appropriate shape and dtype. Note that `out` is always
+ buffered if ``mode='raise'``; use other modes for better performance.
+ mode : {'raise' (default), 'wrap', 'clip'}, optional
+ Specifies how indices outside ``[0, n-1]`` will be treated:
+
+ * 'raise' : an exception is raised
+ * 'wrap' : value becomes value mod ``n``
+ * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1
+
+ Returns
+ -------
+ merged_array : array
+ The merged result.
+
+ Raises
+ ------
+ ValueError: shape mismatch
+ If `a` and each choice array are not all broadcastable to the same
+ shape.
+
+ See Also
+ --------
+ ndarray.choose : equivalent method
+ numpy.take_along_axis : Preferable if `choices` is an array
+
+ Notes
+ -----
+ To reduce the chance of misinterpretation, even though the following
+ "abuse" is nominally supported, `choices` should neither be, nor be
+ thought of as, a single array, i.e., the outermost sequence-like container
+ should be either a list or a tuple.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
+ ... [20, 21, 22, 23], [30, 31, 32, 33]]
+ >>> np.choose([2, 3, 1, 0], choices
+ ... # the first element of the result will be the first element of the
+ ... # third (2+1) "array" in choices, namely, 20; the second element
+ ... # will be the second element of the fourth (3+1) choice array, i.e.,
+ ... # 31, etc.
+ ... )
+ array([20, 31, 12, 3])
+ >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
+ array([20, 31, 12, 3])
+ >>> # because there are 4 choice arrays
+ >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
+ array([20, 1, 12, 3])
+ >>> # i.e., 0
+
+ A couple examples illustrating how choose broadcasts:
+
+ >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
+ >>> choices = [-10, 10]
+ >>> np.choose(a, choices)
+ array([[ 10, -10, 10],
+ [-10, 10, -10],
+ [ 10, -10, 10]])
+
+ >>> # With thanks to Anne Archibald
+ >>> a = np.array([0, 1]).reshape((2,1,1))
+ >>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
+ >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
+ >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
+ array([[[ 1, 1, 1, 1, 1],
+ [ 2, 2, 2, 2, 2],
+ [ 3, 3, 3, 3, 3]],
+ [[-1, -2, -3, -4, -5],
+ [-1, -2, -3, -4, -5],
+ [-1, -2, -3, -4, -5]]])
+
+ """
+ return _wrapfunc(a, 'choose', choices, out=out, mode=mode)
+
+
+def _repeat_dispatcher(a, repeats, axis=None):
+ return (a,)
+
+
+@array_function_dispatch(_repeat_dispatcher)
+def repeat(a, repeats, axis=None):
+ """
+ Repeat each element of an array after themselves
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ repeats : int or array of ints
+ The number of repetitions for each element. `repeats` is broadcasted
+ to fit the shape of the given axis.
+ axis : int, optional
+ The axis along which to repeat values. By default, use the
+ flattened input array, and return a flat output array.
+
+ Returns
+ -------
+ repeated_array : ndarray
+ Output array which has the same shape as `a`, except along
+ the given axis.
+
+ See Also
+ --------
+ tile : Tile an array.
+ unique : Find the unique elements of an array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.repeat(3, 4)
+ array([3, 3, 3, 3])
+ >>> x = np.array([[1,2],[3,4]])
+ >>> np.repeat(x, 2)
+ array([1, 1, 2, 2, 3, 3, 4, 4])
+ >>> np.repeat(x, 3, axis=1)
+ array([[1, 1, 1, 2, 2, 2],
+ [3, 3, 3, 4, 4, 4]])
+ >>> np.repeat(x, [1, 2], axis=0)
+ array([[1, 2],
+ [3, 4],
+ [3, 4]])
+
+ """
+ return _wrapfunc(a, 'repeat', repeats, axis=axis)
+
+
+def _put_dispatcher(a, ind, v, mode=None):
+ return (a, ind, v)
+
+
+@array_function_dispatch(_put_dispatcher)
+def put(a, ind, v, mode='raise'):
+ """
+ Replaces specified elements of an array with given values.
+
+ The indexing works on the flattened target array. `put` is roughly
+ equivalent to:
+
+ ::
+
+ a.flat[ind] = v
+
+ Parameters
+ ----------
+ a : ndarray
+ Target array.
+ ind : array_like
+ Target indices, interpreted as integers.
+ v : array_like
+ Values to place in `a` at target indices. If `v` is shorter than
+ `ind` it will be repeated as necessary.
+ mode : {'raise', 'wrap', 'clip'}, optional
+ Specifies how out-of-bounds indices will behave.
+
+ * 'raise' -- raise an error (default)
+ * 'wrap' -- wrap around
+ * 'clip' -- clip to the range
+
+ 'clip' mode means that all indices that are too large are replaced
+ by the index that addresses the last element along that axis. Note
+ that this disables indexing with negative numbers. In 'raise' mode,
+ if an exception occurs the target array may still be modified.
+
+ See Also
+ --------
+ putmask, place
+ put_along_axis : Put elements by matching the array and the index arrays
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(5)
+ >>> np.put(a, [0, 2], [-44, -55])
+ >>> a
+ array([-44, 1, -55, 3, 4])
+
+ >>> a = np.arange(5)
+ >>> np.put(a, 22, -5, mode='clip')
+ >>> a
+ array([ 0, 1, 2, 3, -5])
+
+ """
+ try:
+ put = a.put
+ except AttributeError as e:
+ raise TypeError(f"argument 1 must be numpy.ndarray, not {type(a)}") from e
+
+ return put(ind, v, mode=mode)
+
+
+def _swapaxes_dispatcher(a, axis1, axis2):
+ return (a,)
+
+
+@array_function_dispatch(_swapaxes_dispatcher)
+def swapaxes(a, axis1, axis2):
+ """
+ Interchange two axes of an array.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ axis1 : int
+ First axis.
+ axis2 : int
+ Second axis.
+
+ Returns
+ -------
+ a_swapped : ndarray
+ For NumPy >= 1.10.0, if `a` is an ndarray, then a view of `a` is
+ returned; otherwise a new array is created. For earlier NumPy
+ versions a view of `a` is returned only if the order of the
+ axes is changed, otherwise the input array is returned.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([[1,2,3]])
+ >>> np.swapaxes(x,0,1)
+ array([[1],
+ [2],
+ [3]])
+
+ >>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
+ >>> x
+ array([[[0, 1],
+ [2, 3]],
+ [[4, 5],
+ [6, 7]]])
+
+ >>> np.swapaxes(x,0,2)
+ array([[[0, 4],
+ [2, 6]],
+ [[1, 5],
+ [3, 7]]])
+
+ """
+ return _wrapfunc(a, 'swapaxes', axis1, axis2)
+
+
+def _transpose_dispatcher(a, axes=None):
+ return (a,)
+
+
+@array_function_dispatch(_transpose_dispatcher)
+def transpose(a, axes=None):
+ """
+ Returns an array with axes transposed.
+
+ For a 1-D array, this returns an unchanged view of the original array, as a
+ transposed vector is simply the same vector.
+ To convert a 1-D array into a 2-D column vector, an additional dimension
+ must be added, e.g., ``np.atleast_2d(a).T`` achieves this, as does
+ ``a[:, np.newaxis]``.
+ For a 2-D array, this is the standard matrix transpose.
+ For an n-D array, if axes are given, their order indicates how the
+ axes are permuted (see Examples). If axes are not provided, then
+ ``transpose(a).shape == a.shape[::-1]``.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ axes : tuple or list of ints, optional
+ If specified, it must be a tuple or list which contains a permutation
+ of [0, 1, ..., N-1] where N is the number of axes of `a`. Negative
+ indices can also be used to specify axes. The i-th axis of the returned
+ array will correspond to the axis numbered ``axes[i]`` of the input.
+ If not specified, defaults to ``range(a.ndim)[::-1]``, which reverses
+ the order of the axes.
+
+ Returns
+ -------
+ p : ndarray
+ `a` with its axes permuted. A view is returned whenever possible.
+
+ See Also
+ --------
+ ndarray.transpose : Equivalent method.
+ moveaxis : Move axes of an array to new positions.
+ argsort : Return the indices that would sort an array.
+
+ Notes
+ -----
+ Use ``transpose(a, argsort(axes))`` to invert the transposition of tensors
+ when using the `axes` keyword argument.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> a
+ array([[1, 2],
+ [3, 4]])
+ >>> np.transpose(a)
+ array([[1, 3],
+ [2, 4]])
+
+ >>> a = np.array([1, 2, 3, 4])
+ >>> a
+ array([1, 2, 3, 4])
+ >>> np.transpose(a)
+ array([1, 2, 3, 4])
+
+ >>> a = np.ones((1, 2, 3))
+ >>> np.transpose(a, (1, 0, 2)).shape
+ (2, 1, 3)
+
+ >>> a = np.ones((2, 3, 4, 5))
+ >>> np.transpose(a).shape
+ (5, 4, 3, 2)
+
+ >>> a = np.arange(3*4*5).reshape((3, 4, 5))
+ >>> np.transpose(a, (-1, 0, -2)).shape
+ (5, 3, 4)
+
+ """
+ return _wrapfunc(a, 'transpose', axes)
+
+
+def _matrix_transpose_dispatcher(x):
+ return (x,)
+
+@array_function_dispatch(_matrix_transpose_dispatcher)
+def matrix_transpose(x, /):
+ """
+ Transposes a matrix (or a stack of matrices) ``x``.
+
+ This function is Array API compatible.
+
+ Parameters
+ ----------
+ x : array_like
+ Input array having shape (..., M, N) and whose two innermost
+ dimensions form ``MxN`` matrices.
+
+ Returns
+ -------
+ out : ndarray
+ An array containing the transpose for each matrix and having shape
+ (..., N, M).
+
+ See Also
+ --------
+ transpose : Generic transpose method.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.matrix_transpose([[1, 2], [3, 4]])
+ array([[1, 3],
+ [2, 4]])
+
+ >>> np.matrix_transpose([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
+ array([[[1, 3],
+ [2, 4]],
+ [[5, 7],
+ [6, 8]]])
+
+ """
+ x = asanyarray(x)
+ if x.ndim < 2:
+ raise ValueError(
+ f"Input array must be at least 2-dimensional, but it is {x.ndim}"
+ )
+ return swapaxes(x, -1, -2)
+
+
+def _partition_dispatcher(a, kth, axis=None, kind=None, order=None):
+ return (a,)
+
+
+@array_function_dispatch(_partition_dispatcher)
+def partition(a, kth, axis=-1, kind='introselect', order=None):
+ """
+ Return a partitioned copy of an array.
+
+ Creates a copy of the array and partially sorts it in such a way that
+ the value of the element in k-th position is in the position it would be
+ in a sorted array. In the output array, all elements smaller than the k-th
+ element are located to the left of this element and all equal or greater
+ are located to its right. The ordering of the elements in the two
+ partitions on the either side of the k-th element in the output array is
+ undefined.
+
+ Parameters
+ ----------
+ a : array_like
+ Array to be sorted.
+ kth : int or sequence of ints
+ Element index to partition by. The k-th value of the element
+ will be in its final sorted position and all smaller elements
+ will be moved before it and all equal or greater elements behind
+ it. The order of all elements in the partitions is undefined. If
+ provided with a sequence of k-th it will partition all elements
+ indexed by k-th of them into their sorted position at once.
+
+ axis : int or None, optional
+ Axis along which to sort. If None, the array is flattened before
+ sorting. The default is -1, which sorts along the last axis.
+ kind : {'introselect'}, optional
+ Selection algorithm. Default is 'introselect'.
+ order : str or list of str, optional
+ When `a` is an array with fields defined, this argument
+ specifies which fields to compare first, second, etc. A single
+ field can be specified as a string. Not all fields need be
+ specified, but unspecified fields will still be used, in the
+ order in which they come up in the dtype, to break ties.
+
+ Returns
+ -------
+ partitioned_array : ndarray
+ Array of the same type and shape as `a`.
+
+ See Also
+ --------
+ ndarray.partition : Method to sort an array in-place.
+ argpartition : Indirect partition.
+ sort : Full sorting
+
+ Notes
+ -----
+ The various selection algorithms are characterized by their average
+ speed, worst case performance, work space size, and whether they are
+ stable. A stable sort keeps items with the same key in the same
+ relative order. The available algorithms have the following
+ properties:
+
+ ================= ======= ============= ============ =======
+ kind speed worst case work space stable
+ ================= ======= ============= ============ =======
+ 'introselect' 1 O(n) 0 no
+ ================= ======= ============= ============ =======
+
+ All the partition algorithms make temporary copies of the data when
+ partitioning along any but the last axis. Consequently,
+ partitioning along the last axis is faster and uses less space than
+ partitioning along any other axis.
+
+ The sort order for complex numbers is lexicographic. If both the
+ real and imaginary parts are non-nan then the order is determined by
+ the real parts except when they are equal, in which case the order
+ is determined by the imaginary parts.
+
+ The sort order of ``np.nan`` is bigger than ``np.inf``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([7, 1, 7, 7, 1, 5, 7, 2, 3, 2, 6, 2, 3, 0])
+ >>> p = np.partition(a, 4)
+ >>> p
+ array([0, 1, 2, 1, 2, 5, 2, 3, 3, 6, 7, 7, 7, 7]) # may vary
+
+ ``p[4]`` is 2; all elements in ``p[:4]`` are less than or equal
+ to ``p[4]``, and all elements in ``p[5:]`` are greater than or
+ equal to ``p[4]``. The partition is::
+
+ [0, 1, 2, 1], [2], [5, 2, 3, 3, 6, 7, 7, 7, 7]
+
+ The next example shows the use of multiple values passed to `kth`.
+
+ >>> p2 = np.partition(a, (4, 8))
+ >>> p2
+ array([0, 1, 2, 1, 2, 3, 3, 2, 5, 6, 7, 7, 7, 7])
+
+ ``p2[4]`` is 2 and ``p2[8]`` is 5. All elements in ``p2[:4]``
+ are less than or equal to ``p2[4]``, all elements in ``p2[5:8]``
+ are greater than or equal to ``p2[4]`` and less than or equal to
+ ``p2[8]``, and all elements in ``p2[9:]`` are greater than or
+ equal to ``p2[8]``. The partition is::
+
+ [0, 1, 2, 1], [2], [3, 3, 2], [5], [6, 7, 7, 7, 7]
+ """
+ if axis is None:
+ # flatten returns (1, N) for np.matrix, so always use the last axis
+ a = asanyarray(a).flatten()
+ axis = -1
+ else:
+ a = asanyarray(a).copy(order="K")
+ a.partition(kth, axis=axis, kind=kind, order=order)
+ return a
+
+
+def _argpartition_dispatcher(a, kth, axis=None, kind=None, order=None):
+ return (a,)
+
+
+@array_function_dispatch(_argpartition_dispatcher)
+def argpartition(a, kth, axis=-1, kind='introselect', order=None):
+ """
+ Perform an indirect partition along the given axis using the
+ algorithm specified by the `kind` keyword. It returns an array of
+ indices of the same shape as `a` that index data along the given
+ axis in partitioned order.
+
+ Parameters
+ ----------
+ a : array_like
+ Array to sort.
+ kth : int or sequence of ints
+ Element index to partition by. The k-th element will be in its
+ final sorted position and all smaller elements will be moved
+ before it and all larger elements behind it. The order of all
+ elements in the partitions is undefined. If provided with a
+ sequence of k-th it will partition all of them into their sorted
+ position at once.
+
+ axis : int or None, optional
+ Axis along which to sort. The default is -1 (the last axis). If
+ None, the flattened array is used.
+ kind : {'introselect'}, optional
+ Selection algorithm. Default is 'introselect'
+ order : str or list of str, optional
+ When `a` is an array with fields defined, this argument
+ specifies which fields to compare first, second, etc. A single
+ field can be specified as a string, and not all fields need be
+ specified, but unspecified fields will still be used, in the
+ order in which they come up in the dtype, to break ties.
+
+ Returns
+ -------
+ index_array : ndarray, int
+ Array of indices that partition `a` along the specified axis.
+ If `a` is one-dimensional, ``a[index_array]`` yields a partitioned `a`.
+ More generally, ``np.take_along_axis(a, index_array, axis=axis)``
+ always yields the partitioned `a`, irrespective of dimensionality.
+
+ See Also
+ --------
+ partition : Describes partition algorithms used.
+ ndarray.partition : Inplace partition.
+ argsort : Full indirect sort.
+ take_along_axis : Apply ``index_array`` from argpartition
+ to an array as if by calling partition.
+
+ Notes
+ -----
+ The returned indices are not guaranteed to be sorted according to
+ the values. Furthermore, the default selection algorithm ``introselect``
+ is unstable, and hence the returned indices are not guaranteed
+ to be the earliest/latest occurrence of the element.
+
+ `argpartition` works for real/complex inputs with nan values,
+ see `partition` for notes on the enhanced sort order and
+ different selection algorithms.
+
+ Examples
+ --------
+ One dimensional array:
+
+ >>> import numpy as np
+ >>> x = np.array([3, 4, 2, 1])
+ >>> x[np.argpartition(x, 3)]
+ array([2, 1, 3, 4]) # may vary
+ >>> x[np.argpartition(x, (1, 3))]
+ array([1, 2, 3, 4]) # may vary
+
+ >>> x = [3, 4, 2, 1]
+ >>> np.array(x)[np.argpartition(x, 3)]
+ array([2, 1, 3, 4]) # may vary
+
+ Multi-dimensional array:
+
+ >>> x = np.array([[3, 4, 2], [1, 3, 1]])
+ >>> index_array = np.argpartition(x, kth=1, axis=-1)
+ >>> # below is the same as np.partition(x, kth=1)
+ >>> np.take_along_axis(x, index_array, axis=-1)
+ array([[2, 3, 4],
+ [1, 1, 3]])
+
+ """
+ return _wrapfunc(a, 'argpartition', kth, axis=axis, kind=kind, order=order)
+
+
+def _sort_dispatcher(a, axis=None, kind=None, order=None, *, stable=None):
+ return (a,)
+
+
+@array_function_dispatch(_sort_dispatcher)
+def sort(a, axis=-1, kind=None, order=None, *, stable=None):
+ """
+ Return a sorted copy of an array.
+
+ Parameters
+ ----------
+ a : array_like
+ Array to be sorted.
+ axis : int or None, optional
+ Axis along which to sort. If None, the array is flattened before
+ sorting. The default is -1, which sorts along the last axis.
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
+ Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
+ and 'mergesort' use timsort or radix sort under the covers and,
+ in general, the actual implementation will vary with data type.
+ The 'mergesort' option is retained for backwards compatibility.
+ order : str or list of str, optional
+ When `a` is an array with fields defined, this argument specifies
+ which fields to compare first, second, etc. A single field can
+ be specified as a string, and not all fields need be specified,
+ but unspecified fields will still be used, in the order in which
+ they come up in the dtype, to break ties.
+ stable : bool, optional
+ Sort stability. If ``True``, the returned array will maintain
+ the relative order of ``a`` values which compare as equal.
+ If ``False`` or ``None``, this is not guaranteed. Internally,
+ this option selects ``kind='stable'``. Default: ``None``.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ sorted_array : ndarray
+ Array of the same type and shape as `a`.
+
+ See Also
+ --------
+ ndarray.sort : Method to sort an array in-place.
+ argsort : Indirect sort.
+ lexsort : Indirect stable sort on multiple keys.
+ searchsorted : Find elements in a sorted array.
+ partition : Partial sort.
+
+ Notes
+ -----
+ The various sorting algorithms are characterized by their average speed,
+ worst case performance, work space size, and whether they are stable. A
+ stable sort keeps items with the same key in the same relative
+ order. The four algorithms implemented in NumPy have the following
+ properties:
+
+ =========== ======= ============= ============ ========
+ kind speed worst case work space stable
+ =========== ======= ============= ============ ========
+ 'quicksort' 1 O(n^2) 0 no
+ 'heapsort' 3 O(n*log(n)) 0 no
+ 'mergesort' 2 O(n*log(n)) ~n/2 yes
+ 'timsort' 2 O(n*log(n)) ~n/2 yes
+ =========== ======= ============= ============ ========
+
+ .. note:: The datatype determines which of 'mergesort' or 'timsort'
+ is actually used, even if 'mergesort' is specified. User selection
+ at a finer scale is not currently available.
+
+ For performance, ``sort`` makes a temporary copy if needed to make the data
+ `contiguous `_
+ in memory along the sort axis. For even better performance and reduced
+ memory consumption, ensure that the array is already contiguous along the
+ sort axis.
+
+ The sort order for complex numbers is lexicographic. If both the real
+ and imaginary parts are non-nan then the order is determined by the
+ real parts except when they are equal, in which case the order is
+ determined by the imaginary parts.
+
+ Previous to numpy 1.4.0 sorting real and complex arrays containing nan
+ values led to undefined behaviour. In numpy versions >= 1.4.0 nan
+ values are sorted to the end. The extended sort order is:
+
+ * Real: [R, nan]
+ * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
+
+ where R is a non-nan real value. Complex values with the same nan
+ placements are sorted according to the non-nan part if it exists.
+ Non-nan values are sorted as before.
+
+ quicksort has been changed to:
+ `introsort `_.
+ When sorting does not make enough progress it switches to
+ `heapsort `_.
+ This implementation makes quicksort O(n*log(n)) in the worst case.
+
+ 'stable' automatically chooses the best stable sorting algorithm
+ for the data type being sorted.
+ It, along with 'mergesort' is currently mapped to
+ `timsort `_
+ or `radix sort `_
+ depending on the data type.
+ API forward compatibility currently limits the
+ ability to select the implementation and it is hardwired for the different
+ data types.
+
+ Timsort is added for better performance on already or nearly
+ sorted data. On random data timsort is almost identical to
+ mergesort. It is now used for stable sort while quicksort is still the
+ default sort if none is chosen. For timsort details, refer to
+ `CPython listsort.txt
+ `_
+ 'mergesort' and 'stable' are mapped to radix sort for integer data types.
+ Radix sort is an O(n) sort instead of O(n log n).
+
+ NaT now sorts to the end of arrays for consistency with NaN.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1,4],[3,1]])
+ >>> np.sort(a) # sort along the last axis
+ array([[1, 4],
+ [1, 3]])
+ >>> np.sort(a, axis=None) # sort the flattened array
+ array([1, 1, 3, 4])
+ >>> np.sort(a, axis=0) # sort along the first axis
+ array([[1, 1],
+ [3, 4]])
+
+ Use the `order` keyword to specify a field to use when sorting a
+ structured array:
+
+ >>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
+ >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
+ ... ('Galahad', 1.7, 38)]
+ >>> a = np.array(values, dtype=dtype) # create a structured array
+ >>> np.sort(a, order='height') # doctest: +SKIP
+ array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
+ ('Lancelot', 1.8999999999999999, 38)],
+ dtype=[('name', '|S10'), ('height', '>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
+ array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
+ ('Arthur', 1.8, 41)],
+ dtype=[('name', '|S10'), ('height', '>> import numpy as np
+ >>> x = np.array([3, 1, 2])
+ >>> np.argsort(x)
+ array([1, 2, 0])
+
+ Two-dimensional array:
+
+ >>> x = np.array([[0, 3], [2, 2]])
+ >>> x
+ array([[0, 3],
+ [2, 2]])
+
+ >>> ind = np.argsort(x, axis=0) # sorts along first axis (down)
+ >>> ind
+ array([[0, 1],
+ [1, 0]])
+ >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0)
+ array([[0, 2],
+ [2, 3]])
+
+ >>> ind = np.argsort(x, axis=1) # sorts along last axis (across)
+ >>> ind
+ array([[0, 1],
+ [0, 1]])
+ >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1)
+ array([[0, 3],
+ [2, 2]])
+
+ Indices of the sorted elements of a N-dimensional array:
+
+ >>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
+ >>> ind
+ (array([0, 1, 1, 0]), array([0, 0, 1, 1]))
+ >>> x[ind] # same as np.sort(x, axis=None)
+ array([0, 2, 2, 3])
+
+ Sorting with keys:
+
+ >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '>> x
+ array([(1, 0), (0, 1)],
+ dtype=[('x', '>> np.argsort(x, order=('x','y'))
+ array([1, 0])
+
+ >>> np.argsort(x, order=('y','x'))
+ array([0, 1])
+
+ """
+ return _wrapfunc(
+ a, 'argsort', axis=axis, kind=kind, order=order, stable=stable
+ )
+
+def _argmax_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
+ return (a, out)
+
+
+@array_function_dispatch(_argmax_dispatcher)
+def argmax(a, axis=None, out=None, *, keepdims=np._NoValue):
+ """
+ Returns the indices of the maximum values along an axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ axis : int, optional
+ By default, the index is into the flattened array, otherwise
+ along the specified axis.
+ out : array, optional
+ If provided, the result will be inserted into this array. It should
+ be of the appropriate shape and dtype.
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the array.
+
+ .. versionadded:: 1.22.0
+
+ Returns
+ -------
+ index_array : ndarray of ints
+ Array of indices into the array. It has the same shape as ``a.shape``
+ with the dimension along `axis` removed. If `keepdims` is set to True,
+ then the size of `axis` will be 1 with the resulting array having same
+ shape as ``a.shape``.
+
+ See Also
+ --------
+ ndarray.argmax, argmin
+ amax : The maximum value along a given axis.
+ unravel_index : Convert a flat index into an index tuple.
+ take_along_axis : Apply ``np.expand_dims(index_array, axis)``
+ from argmax to an array as if by calling max.
+
+ Notes
+ -----
+ In case of multiple occurrences of the maximum values, the indices
+ corresponding to the first occurrence are returned.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(6).reshape(2,3) + 10
+ >>> a
+ array([[10, 11, 12],
+ [13, 14, 15]])
+ >>> np.argmax(a)
+ 5
+ >>> np.argmax(a, axis=0)
+ array([1, 1, 1])
+ >>> np.argmax(a, axis=1)
+ array([2, 2])
+
+ Indexes of the maximal elements of a N-dimensional array:
+
+ >>> a.flat[np.argmax(a)]
+ 15
+ >>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
+ >>> ind
+ (1, 2)
+ >>> a[ind]
+ 15
+
+ >>> b = np.arange(6)
+ >>> b[1] = 5
+ >>> b
+ array([0, 5, 2, 3, 4, 5])
+ >>> np.argmax(b) # Only the first occurrence is returned.
+ 1
+
+ >>> x = np.array([[4,2,3], [1,0,3]])
+ >>> index_array = np.argmax(x, axis=-1)
+ >>> # Same as np.amax(x, axis=-1, keepdims=True)
+ >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
+ array([[4],
+ [3]])
+ >>> # Same as np.amax(x, axis=-1)
+ >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1),
+ ... axis=-1).squeeze(axis=-1)
+ array([4, 3])
+
+ Setting `keepdims` to `True`,
+
+ >>> x = np.arange(24).reshape((2, 3, 4))
+ >>> res = np.argmax(x, axis=1, keepdims=True)
+ >>> res.shape
+ (2, 1, 4)
+ """
+ kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
+ return _wrapfunc(a, 'argmax', axis=axis, out=out, **kwds)
+
+
+def _argmin_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
+ return (a, out)
+
+
+@array_function_dispatch(_argmin_dispatcher)
+def argmin(a, axis=None, out=None, *, keepdims=np._NoValue):
+ """
+ Returns the indices of the minimum values along an axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ axis : int, optional
+ By default, the index is into the flattened array, otherwise
+ along the specified axis.
+ out : array, optional
+ If provided, the result will be inserted into this array. It should
+ be of the appropriate shape and dtype.
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the array.
+
+ .. versionadded:: 1.22.0
+
+ Returns
+ -------
+ index_array : ndarray of ints
+ Array of indices into the array. It has the same shape as `a.shape`
+ with the dimension along `axis` removed. If `keepdims` is set to True,
+ then the size of `axis` will be 1 with the resulting array having same
+ shape as `a.shape`.
+
+ See Also
+ --------
+ ndarray.argmin, argmax
+ amin : The minimum value along a given axis.
+ unravel_index : Convert a flat index into an index tuple.
+ take_along_axis : Apply ``np.expand_dims(index_array, axis)``
+ from argmin to an array as if by calling min.
+
+ Notes
+ -----
+ In case of multiple occurrences of the minimum values, the indices
+ corresponding to the first occurrence are returned.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(6).reshape(2,3) + 10
+ >>> a
+ array([[10, 11, 12],
+ [13, 14, 15]])
+ >>> np.argmin(a)
+ 0
+ >>> np.argmin(a, axis=0)
+ array([0, 0, 0])
+ >>> np.argmin(a, axis=1)
+ array([0, 0])
+
+ Indices of the minimum elements of a N-dimensional array:
+
+ >>> a.flat[np.argmin(a)]
+ 10
+ >>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
+ >>> ind
+ (0, 0)
+ >>> a[ind]
+ 10
+
+ >>> b = np.arange(6) + 10
+ >>> b[4] = 10
+ >>> b
+ array([10, 11, 12, 13, 10, 15])
+ >>> np.argmin(b) # Only the first occurrence is returned.
+ 0
+
+ >>> x = np.array([[4,2,3], [1,0,3]])
+ >>> index_array = np.argmin(x, axis=-1)
+ >>> # Same as np.amin(x, axis=-1, keepdims=True)
+ >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
+ array([[2],
+ [0]])
+ >>> # Same as np.amax(x, axis=-1)
+ >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1),
+ ... axis=-1).squeeze(axis=-1)
+ array([2, 0])
+
+ Setting `keepdims` to `True`,
+
+ >>> x = np.arange(24).reshape((2, 3, 4))
+ >>> res = np.argmin(x, axis=1, keepdims=True)
+ >>> res.shape
+ (2, 1, 4)
+ """
+ kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
+ return _wrapfunc(a, 'argmin', axis=axis, out=out, **kwds)
+
+
+def _searchsorted_dispatcher(a, v, side=None, sorter=None):
+ return (a, v, sorter)
+
+
+@array_function_dispatch(_searchsorted_dispatcher)
+def searchsorted(a, v, side='left', sorter=None):
+ """
+ Find indices where elements should be inserted to maintain order.
+
+ Find the indices into a sorted array `a` such that, if the
+ corresponding elements in `v` were inserted before the indices, the
+ order of `a` would be preserved.
+
+ Assuming that `a` is sorted:
+
+ ====== ============================
+ `side` returned index `i` satisfies
+ ====== ============================
+ left ``a[i-1] < v <= a[i]``
+ right ``a[i-1] <= v < a[i]``
+ ====== ============================
+
+ Parameters
+ ----------
+ a : 1-D array_like
+ Input array. If `sorter` is None, then it must be sorted in
+ ascending order, otherwise `sorter` must be an array of indices
+ that sort it.
+ v : array_like
+ Values to insert into `a`.
+ side : {'left', 'right'}, optional
+ If 'left', the index of the first suitable location found is given.
+ If 'right', return the last such index. If there is no suitable
+ index, return either 0 or N (where N is the length of `a`).
+ sorter : 1-D array_like, optional
+ Optional array of integer indices that sort array a into ascending
+ order. They are typically the result of argsort.
+
+ Returns
+ -------
+ indices : int or array of ints
+ Array of insertion points with the same shape as `v`,
+ or an integer if `v` is a scalar.
+
+ See Also
+ --------
+ sort : Return a sorted copy of an array.
+ histogram : Produce histogram from 1-D data.
+
+ Notes
+ -----
+ Binary search is used to find the required insertion points.
+
+ As of NumPy 1.4.0 `searchsorted` works with real/complex arrays containing
+ `nan` values. The enhanced sort order is documented in `sort`.
+
+ This function uses the same algorithm as the builtin python
+ `bisect.bisect_left` (``side='left'``) and `bisect.bisect_right`
+ (``side='right'``) functions, which is also vectorized
+ in the `v` argument.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.searchsorted([11,12,13,14,15], 13)
+ 2
+ >>> np.searchsorted([11,12,13,14,15], 13, side='right')
+ 3
+ >>> np.searchsorted([11,12,13,14,15], [-10, 20, 12, 13])
+ array([0, 5, 1, 2])
+
+ When `sorter` is used, the returned indices refer to the sorted
+ array of `a` and not `a` itself:
+
+ >>> a = np.array([40, 10, 20, 30])
+ >>> sorter = np.argsort(a)
+ >>> sorter
+ array([1, 2, 3, 0]) # Indices that would sort the array 'a'
+ >>> result = np.searchsorted(a, 25, sorter=sorter)
+ >>> result
+ 2
+ >>> a[sorter[result]]
+ 30 # The element at index 2 of the sorted array is 30.
+ """
+ return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
+
+
+def _resize_dispatcher(a, new_shape):
+ return (a,)
+
+
+@array_function_dispatch(_resize_dispatcher)
+def resize(a, new_shape):
+ """
+ Return a new array with the specified shape.
+
+ If the new array is larger than the original array, then the new
+ array is filled with repeated copies of `a`. Note that this behavior
+ is different from a.resize(new_shape) which fills with zeros instead
+ of repeated copies of `a`.
+
+ Parameters
+ ----------
+ a : array_like
+ Array to be resized.
+
+ new_shape : int or tuple of int
+ Shape of resized array.
+
+ Returns
+ -------
+ reshaped_array : ndarray
+ The new array is formed from the data in the old array, repeated
+ if necessary to fill out the required number of elements. The
+ data are repeated iterating over the array in C-order.
+
+ See Also
+ --------
+ numpy.reshape : Reshape an array without changing the total size.
+ numpy.pad : Enlarge and pad an array.
+ numpy.repeat : Repeat elements of an array.
+ ndarray.resize : resize an array in-place.
+
+ Notes
+ -----
+ When the total size of the array does not change `~numpy.reshape` should
+ be used. In most other cases either indexing (to reduce the size)
+ or padding (to increase the size) may be a more appropriate solution.
+
+ Warning: This functionality does **not** consider axes separately,
+ i.e. it does not apply interpolation/extrapolation.
+ It fills the return array with the required number of elements, iterating
+ over `a` in C-order, disregarding axes (and cycling back from the start if
+ the new shape is larger). This functionality is therefore not suitable to
+ resize images, or data where each axis represents a separate and distinct
+ entity.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[0,1],[2,3]])
+ >>> np.resize(a,(2,3))
+ array([[0, 1, 2],
+ [3, 0, 1]])
+ >>> np.resize(a,(1,4))
+ array([[0, 1, 2, 3]])
+ >>> np.resize(a,(2,4))
+ array([[0, 1, 2, 3],
+ [0, 1, 2, 3]])
+
+ """
+ if isinstance(new_shape, (int, nt.integer)):
+ new_shape = (new_shape,)
+
+ a = ravel(a)
+
+ new_size = 1
+ for dim_length in new_shape:
+ new_size *= dim_length
+ if dim_length < 0:
+ raise ValueError(
+ 'all elements of `new_shape` must be non-negative'
+ )
+
+ if a.size == 0 or new_size == 0:
+ # First case must zero fill. The second would have repeats == 0.
+ return np.zeros_like(a, shape=new_shape)
+
+ # ceiling division without negating new_size
+ repeats = (new_size + a.size - 1) // a.size
+ a = concatenate((a,) * repeats)[:new_size]
+
+ return reshape(a, new_shape)
+
+
+def _squeeze_dispatcher(a, axis=None):
+ return (a,)
+
+
+@array_function_dispatch(_squeeze_dispatcher)
+def squeeze(a, axis=None):
+ """
+ Remove axes of length one from `a`.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+ axis : None or int or tuple of ints, optional
+ Selects a subset of the entries of length one in the
+ shape. If an axis is selected with shape entry greater than
+ one, an error is raised.
+
+ Returns
+ -------
+ squeezed : ndarray
+ The input array, but with all or a subset of the
+ dimensions of length 1 removed. This is always `a` itself
+ or a view into `a`. Note that if all axes are squeezed,
+ the result is a 0d array and not a scalar.
+
+ Raises
+ ------
+ ValueError
+ If `axis` is not None, and an axis being squeezed is not of length 1
+
+ See Also
+ --------
+ expand_dims : The inverse operation, adding entries of length one
+ reshape : Insert, remove, and combine dimensions, and resize existing ones
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([[[0], [1], [2]]])
+ >>> x.shape
+ (1, 3, 1)
+ >>> np.squeeze(x).shape
+ (3,)
+ >>> np.squeeze(x, axis=0).shape
+ (3, 1)
+ >>> np.squeeze(x, axis=1).shape
+ Traceback (most recent call last):
+ ...
+ ValueError: cannot select an axis to squeeze out which has size
+ not equal to one
+ >>> np.squeeze(x, axis=2).shape
+ (1, 3)
+ >>> x = np.array([[1234]])
+ >>> x.shape
+ (1, 1)
+ >>> np.squeeze(x)
+ array(1234) # 0d array
+ >>> np.squeeze(x).shape
+ ()
+ >>> np.squeeze(x)[()]
+ 1234
+
+ """
+ try:
+ squeeze = a.squeeze
+ except AttributeError:
+ return _wrapit(a, 'squeeze', axis=axis)
+ if axis is None:
+ return squeeze()
+ else:
+ return squeeze(axis=axis)
+
+
+def _diagonal_dispatcher(a, offset=None, axis1=None, axis2=None):
+ return (a,)
+
+
+@array_function_dispatch(_diagonal_dispatcher)
+def diagonal(a, offset=0, axis1=0, axis2=1):
+ """
+ Return specified diagonals.
+
+ If `a` is 2-D, returns the diagonal of `a` with the given offset,
+ i.e., the collection of elements of the form ``a[i, i+offset]``. If
+ `a` has more than two dimensions, then the axes specified by `axis1`
+ and `axis2` are used to determine the 2-D sub-array whose diagonal is
+ returned. The shape of the resulting array can be determined by
+ removing `axis1` and `axis2` and appending an index to the right equal
+ to the size of the resulting diagonals.
+
+ In versions of NumPy prior to 1.7, this function always returned a new,
+ independent array containing a copy of the values in the diagonal.
+
+ In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,
+ but depending on this fact is deprecated. Writing to the resulting
+ array continues to work as it used to, but a FutureWarning is issued.
+
+ Starting in NumPy 1.9 it returns a read-only view on the original array.
+ Attempting to write to the resulting array will produce an error.
+
+ In some future release, it will return a read/write view and writing to
+ the returned array will alter your original array. The returned array
+ will have the same type as the input array.
+
+ If you don't write to the array returned by this function, then you can
+ just ignore all of the above.
+
+ If you depend on the current behavior, then we suggest copying the
+ returned array explicitly, i.e., use ``np.diagonal(a).copy()`` instead
+ of just ``np.diagonal(a)``. This will work with both past and future
+ versions of NumPy.
+
+ Parameters
+ ----------
+ a : array_like
+ Array from which the diagonals are taken.
+ offset : int, optional
+ Offset of the diagonal from the main diagonal. Can be positive or
+ negative. Defaults to main diagonal (0).
+ axis1 : int, optional
+ Axis to be used as the first axis of the 2-D sub-arrays from which
+ the diagonals should be taken. Defaults to first axis (0).
+ axis2 : int, optional
+ Axis to be used as the second axis of the 2-D sub-arrays from
+ which the diagonals should be taken. Defaults to second axis (1).
+
+ Returns
+ -------
+ array_of_diagonals : ndarray
+ If `a` is 2-D, then a 1-D array containing the diagonal and of the
+ same type as `a` is returned unless `a` is a `matrix`, in which case
+ a 1-D array rather than a (2-D) `matrix` is returned in order to
+ maintain backward compatibility.
+
+ If ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2`
+ are removed, and a new axis inserted at the end corresponding to the
+ diagonal.
+
+ Raises
+ ------
+ ValueError
+ If the dimension of `a` is less than 2.
+
+ See Also
+ --------
+ diag : MATLAB work-a-like for 1-D and 2-D arrays.
+ diagflat : Create diagonal arrays.
+ trace : Sum along diagonals.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(4).reshape(2,2)
+ >>> a
+ array([[0, 1],
+ [2, 3]])
+ >>> a.diagonal()
+ array([0, 3])
+ >>> a.diagonal(1)
+ array([1])
+
+ A 3-D example:
+
+ >>> a = np.arange(8).reshape(2,2,2); a
+ array([[[0, 1],
+ [2, 3]],
+ [[4, 5],
+ [6, 7]]])
+ >>> a.diagonal(0, # Main diagonals of two arrays created by skipping
+ ... 0, # across the outer(left)-most axis last and
+ ... 1) # the "middle" (row) axis first.
+ array([[0, 6],
+ [1, 7]])
+
+ The sub-arrays whose main diagonals we just obtained; note that each
+ corresponds to fixing the right-most (column) axis, and that the
+ diagonals are "packed" in rows.
+
+ >>> a[:,:,0] # main diagonal is [0 6]
+ array([[0, 2],
+ [4, 6]])
+ >>> a[:,:,1] # main diagonal is [1 7]
+ array([[1, 3],
+ [5, 7]])
+
+ The anti-diagonal can be obtained by reversing the order of elements
+ using either `numpy.flipud` or `numpy.fliplr`.
+
+ >>> a = np.arange(9).reshape(3, 3)
+ >>> a
+ array([[0, 1, 2],
+ [3, 4, 5],
+ [6, 7, 8]])
+ >>> np.fliplr(a).diagonal() # Horizontal flip
+ array([2, 4, 6])
+ >>> np.flipud(a).diagonal() # Vertical flip
+ array([6, 4, 2])
+
+ Note that the order in which the diagonal is retrieved varies depending
+ on the flip function.
+ """
+ if isinstance(a, np.matrix):
+ # Make diagonal of matrix 1-D to preserve backward compatibility.
+ return asarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
+ else:
+ return asanyarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
+
+
+def _trace_dispatcher(
+ a, offset=None, axis1=None, axis2=None, dtype=None, out=None):
+ return (a, out)
+
+
+@array_function_dispatch(_trace_dispatcher)
+def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
+ """
+ Return the sum along diagonals of the array.
+
+ If `a` is 2-D, the sum along its diagonal with the given offset
+ is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
+
+ If `a` has more than two dimensions, then the axes specified by axis1 and
+ axis2 are used to determine the 2-D sub-arrays whose traces are returned.
+ The shape of the resulting array is the same as that of `a` with `axis1`
+ and `axis2` removed.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array, from which the diagonals are taken.
+ offset : int, optional
+ Offset of the diagonal from the main diagonal. Can be both positive
+ and negative. Defaults to 0.
+ axis1, axis2 : int, optional
+ Axes to be used as the first and second axis of the 2-D sub-arrays
+ from which the diagonals should be taken. Defaults are the first two
+ axes of `a`.
+ dtype : dtype, optional
+ Determines the data-type of the returned array and of the accumulator
+ where the elements are summed. If dtype has the value None and `a` is
+ of integer type of precision less than the default integer
+ precision, then the default integer precision is used. Otherwise,
+ the precision is the same as that of `a`.
+ out : ndarray, optional
+ Array into which the output is placed. Its type is preserved and
+ it must be of the right shape to hold the output.
+
+ Returns
+ -------
+ sum_along_diagonals : ndarray
+ If `a` is 2-D, the sum along the diagonal is returned. If `a` has
+ larger dimensions, then an array of sums along diagonals is returned.
+
+ See Also
+ --------
+ diag, diagonal, diagflat
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.trace(np.eye(3))
+ 3.0
+ >>> a = np.arange(8).reshape((2,2,2))
+ >>> np.trace(a)
+ array([6, 8])
+
+ >>> a = np.arange(24).reshape((2,2,2,3))
+ >>> np.trace(a).shape
+ (2, 3)
+
+ """
+ if isinstance(a, np.matrix):
+ # Get trace of matrix via an array to preserve backward compatibility.
+ return asarray(a).trace(
+ offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out
+ )
+ else:
+ return asanyarray(a).trace(
+ offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out
+ )
+
+
+def _ravel_dispatcher(a, order=None):
+ return (a,)
+
+
+@array_function_dispatch(_ravel_dispatcher)
+def ravel(a, order='C'):
+ """Return a contiguous flattened array.
+
+ A 1-D array, containing the elements of the input, is returned. A copy is
+ made only if needed.
+
+ As of NumPy 1.10, the returned array will have the same type as the input
+ array. (for example, a masked array will be returned for a masked array
+ input)
+
+ Parameters
+ ----------
+ a : array_like
+ Input array. The elements in `a` are read in the order specified by
+ `order`, and packed as a 1-D array.
+ order : {'C','F', 'A', 'K'}, optional
+
+ The elements of `a` are read using this index order. 'C' means
+ to index the elements in row-major, C-style order,
+ with the last axis index changing fastest, back to the first
+ axis index changing slowest. 'F' means to index the elements
+ in column-major, Fortran-style order, with the
+ first index changing fastest, and the last index changing
+ slowest. Note that the 'C' and 'F' options take no account of
+ the memory layout of the underlying array, and only refer to
+ the order of axis indexing. 'A' means to read the elements in
+ Fortran-like index order if `a` is Fortran *contiguous* in
+ memory, C-like order otherwise. 'K' means to read the
+ elements in the order they occur in memory, except for
+ reversing the data when strides are negative. By default, 'C'
+ index order is used.
+
+ Returns
+ -------
+ y : array_like
+ y is a contiguous 1-D array of the same subtype as `a`,
+ with shape ``(a.size,)``.
+ Note that matrices are special cased for backward compatibility,
+ if `a` is a matrix, then y is a 1-D ndarray.
+
+ See Also
+ --------
+ ndarray.flat : 1-D iterator over an array.
+ ndarray.flatten : 1-D array copy of the elements of an array
+ in row-major order.
+ ndarray.reshape : Change the shape of an array without changing its data.
+
+ Notes
+ -----
+ In row-major, C-style order, in two dimensions, the row index
+ varies the slowest, and the column index the quickest. This can
+ be generalized to multiple dimensions, where row-major order
+ implies that the index along the first axis varies slowest, and
+ the index along the last quickest. The opposite holds for
+ column-major, Fortran-style index ordering.
+
+ When a view is desired in as many cases as possible, ``arr.reshape(-1)``
+ may be preferable. However, ``ravel`` supports ``K`` in the optional
+ ``order`` argument while ``reshape`` does not.
+
+ Examples
+ --------
+ It is equivalent to ``reshape(-1, order=order)``.
+
+ >>> import numpy as np
+ >>> x = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> np.ravel(x)
+ array([1, 2, 3, 4, 5, 6])
+
+ >>> x.reshape(-1)
+ array([1, 2, 3, 4, 5, 6])
+
+ >>> np.ravel(x, order='F')
+ array([1, 4, 2, 5, 3, 6])
+
+ When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:
+
+ >>> np.ravel(x.T)
+ array([1, 4, 2, 5, 3, 6])
+ >>> np.ravel(x.T, order='A')
+ array([1, 2, 3, 4, 5, 6])
+
+ When ``order`` is 'K', it will preserve orderings that are neither 'C'
+ nor 'F', but won't reverse axes:
+
+ >>> a = np.arange(3)[::-1]; a
+ array([2, 1, 0])
+ >>> a.ravel(order='C')
+ array([2, 1, 0])
+ >>> a.ravel(order='K')
+ array([2, 1, 0])
+
+ >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
+ array([[[ 0, 2, 4],
+ [ 1, 3, 5]],
+ [[ 6, 8, 10],
+ [ 7, 9, 11]]])
+ >>> a.ravel(order='C')
+ array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
+ >>> a.ravel(order='K')
+ array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
+
+ """
+ if isinstance(a, np.matrix):
+ return asarray(a).ravel(order=order)
+ else:
+ return asanyarray(a).ravel(order=order)
+
+
+def _nonzero_dispatcher(a):
+ return (a,)
+
+
+@array_function_dispatch(_nonzero_dispatcher)
+def nonzero(a):
+ """
+ Return the indices of the elements that are non-zero.
+
+ Returns a tuple of arrays, one for each dimension of `a`,
+ containing the indices of the non-zero elements in that
+ dimension. The values in `a` are always tested and returned in
+ row-major, C-style order.
+
+ To group the indices by element, rather than dimension, use `argwhere`,
+ which returns a row for each non-zero element.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+
+ Returns
+ -------
+ tuple_of_arrays : tuple
+ Indices of elements that are non-zero.
+
+ See Also
+ --------
+ flatnonzero :
+ Return indices that are non-zero in the flattened version of the input
+ array.
+ ndarray.nonzero :
+ Equivalent ndarray method.
+ count_nonzero :
+ Counts the number of non-zero elements in the input array.
+
+ Notes
+ -----
+ While the nonzero values can be obtained with ``a[nonzero(a)]``, it is
+ recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which
+ will correctly handle 0-d arrays.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
+ >>> x
+ array([[3, 0, 0],
+ [0, 4, 0],
+ [5, 6, 0]])
+ >>> np.nonzero(x)
+ (array([0, 1, 2, 2]), array([0, 1, 0, 1]))
+
+ >>> x[np.nonzero(x)]
+ array([3, 4, 5, 6])
+ >>> np.transpose(np.nonzero(x))
+ array([[0, 0],
+ [1, 1],
+ [2, 0],
+ [2, 1]])
+
+ A common use for ``nonzero`` is to find the indices of an array, where
+ a condition is True. Given an array `a`, the condition `a` > 3 is a
+ boolean array and since False is interpreted as 0, np.nonzero(a > 3)
+ yields the indices of the `a` where the condition is true.
+
+ >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+ >>> a > 3
+ array([[False, False, False],
+ [ True, True, True],
+ [ True, True, True]])
+ >>> np.nonzero(a > 3)
+ (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
+
+ Using this result to index `a` is equivalent to using the mask directly:
+
+ >>> a[np.nonzero(a > 3)]
+ array([4, 5, 6, 7, 8, 9])
+ >>> a[a > 3] # prefer this spelling
+ array([4, 5, 6, 7, 8, 9])
+
+ ``nonzero`` can also be called as a method of the array.
+
+ >>> (a > 3).nonzero()
+ (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
+
+ """
+ return _wrapfunc(a, 'nonzero')
+
+
+def _shape_dispatcher(a):
+ return (a,)
+
+
+@array_function_dispatch(_shape_dispatcher)
+def shape(a):
+ """
+ Return the shape of an array.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+
+ Returns
+ -------
+ shape : tuple of ints
+ The elements of the shape tuple give the lengths of the
+ corresponding array dimensions.
+
+ See Also
+ --------
+ len : ``len(a)`` is equivalent to ``np.shape(a)[0]`` for N-D arrays with
+ ``N>=1``.
+ ndarray.shape : Equivalent array method.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.shape(np.eye(3))
+ (3, 3)
+ >>> np.shape([[1, 3]])
+ (1, 2)
+ >>> np.shape([0])
+ (1,)
+ >>> np.shape(0)
+ ()
+
+ >>> a = np.array([(1, 2), (3, 4), (5, 6)],
+ ... dtype=[('x', 'i4'), ('y', 'i4')])
+ >>> np.shape(a)
+ (3,)
+ >>> a.shape
+ (3,)
+
+ """
+ try:
+ result = a.shape
+ except AttributeError:
+ result = asarray(a).shape
+ return result
+
+
+def _compress_dispatcher(condition, a, axis=None, out=None):
+ return (condition, a, out)
+
+
+@array_function_dispatch(_compress_dispatcher)
+def compress(condition, a, axis=None, out=None):
+ """
+ Return selected slices of an array along given axis.
+
+ When working along a given axis, a slice along that axis is returned in
+ `output` for each index where `condition` evaluates to True. When
+ working on a 1-D array, `compress` is equivalent to `extract`.
+
+ Parameters
+ ----------
+ condition : 1-D array of bools
+ Array that selects which entries to return. If len(condition)
+ is less than the size of `a` along the given axis, then output is
+ truncated to the length of the condition array.
+ a : array_like
+ Array from which to extract a part.
+ axis : int, optional
+ Axis along which to take slices. If None (default), work on the
+ flattened array.
+ out : ndarray, optional
+ Output array. Its type is preserved and it must be of the right
+ shape to hold the output.
+
+ Returns
+ -------
+ compressed_array : ndarray
+ A copy of `a` without the slices along axis for which `condition`
+ is false.
+
+ See Also
+ --------
+ take, choose, diag, diagonal, select
+ ndarray.compress : Equivalent method in ndarray
+ extract : Equivalent method when working on 1-D arrays
+ :ref:`ufuncs-output-type`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4], [5, 6]])
+ >>> a
+ array([[1, 2],
+ [3, 4],
+ [5, 6]])
+ >>> np.compress([0, 1], a, axis=0)
+ array([[3, 4]])
+ >>> np.compress([False, True, True], a, axis=0)
+ array([[3, 4],
+ [5, 6]])
+ >>> np.compress([False, True], a, axis=1)
+ array([[2],
+ [4],
+ [6]])
+
+ Working on the flattened array does not return slices along an axis but
+ selects elements.
+
+ >>> np.compress([False, True], a)
+ array([2])
+
+ """
+ return _wrapfunc(a, 'compress', condition, axis=axis, out=out)
+
+
+def _clip_dispatcher(a, a_min=None, a_max=None, out=None, *, min=None,
+ max=None, **kwargs):
+ return (a, a_min, a_max, out, min, max)
+
+
+@array_function_dispatch(_clip_dispatcher)
+def clip(a, a_min=np._NoValue, a_max=np._NoValue, out=None, *,
+ min=np._NoValue, max=np._NoValue, **kwargs):
+ """
+ Clip (limit) the values in an array.
+
+ Given an interval, values outside the interval are clipped to
+ the interval edges. For example, if an interval of ``[0, 1]``
+ is specified, values smaller than 0 become 0, and values larger
+ than 1 become 1.
+
+ Equivalent to but faster than ``np.minimum(a_max, np.maximum(a, a_min))``.
+
+ No check is performed to ensure ``a_min < a_max``.
+
+ Parameters
+ ----------
+ a : array_like
+ Array containing elements to clip.
+ a_min, a_max : array_like or None
+ Minimum and maximum value. If ``None``, clipping is not performed on
+ the corresponding edge. If both ``a_min`` and ``a_max`` are ``None``,
+ the elements of the returned array stay the same. Both are broadcasted
+ against ``a``.
+ out : ndarray, optional
+ The results will be placed in this array. It may be the input
+ array for in-place clipping. `out` must be of the right shape
+ to hold the output. Its type is preserved.
+ min, max : array_like or None
+ Array API compatible alternatives for ``a_min`` and ``a_max``
+ arguments. Either ``a_min`` and ``a_max`` or ``min`` and ``max``
+ can be passed at the same time. Default: ``None``.
+
+ .. versionadded:: 2.1.0
+ **kwargs
+ For other keyword-only arguments, see the
+ :ref:`ufunc docs `.
+
+ Returns
+ -------
+ clipped_array : ndarray
+ An array with the elements of `a`, but where values
+ < `a_min` are replaced with `a_min`, and those > `a_max`
+ with `a_max`.
+
+ See Also
+ --------
+ :ref:`ufuncs-output-type`
+
+ Notes
+ -----
+ When `a_min` is greater than `a_max`, `clip` returns an
+ array in which all values are equal to `a_max`,
+ as shown in the second example.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(10)
+ >>> a
+ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
+ >>> np.clip(a, 1, 8)
+ array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
+ >>> np.clip(a, 8, 1)
+ array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
+ >>> np.clip(a, 3, 6, out=a)
+ array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
+ >>> a
+ array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
+ >>> a = np.arange(10)
+ >>> a
+ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
+ >>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
+ array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
+
+ """
+ if a_min is np._NoValue and a_max is np._NoValue:
+ a_min = None if min is np._NoValue else min
+ a_max = None if max is np._NoValue else max
+ elif a_min is np._NoValue:
+ raise TypeError("clip() missing 1 required positional "
+ "argument: 'a_min'")
+ elif a_max is np._NoValue:
+ raise TypeError("clip() missing 1 required positional "
+ "argument: 'a_max'")
+ elif min is not np._NoValue or max is not np._NoValue:
+ raise ValueError("Passing `min` or `max` keyword argument when "
+ "`a_min` and `a_max` are provided is forbidden.")
+
+ return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs)
+
+
+def _sum_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
+ initial=None, where=None):
+ return (a, out)
+
+
+@array_function_dispatch(_sum_dispatcher)
+def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
+ initial=np._NoValue, where=np._NoValue):
+ """
+ Sum of array elements over a given axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Elements to sum.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which a sum is performed. The default,
+ axis=None, will sum all of the elements of the input array. If
+ axis is negative it counts from the last to the first axis. If
+ axis is a tuple of ints, a sum is performed on all of the axes
+ specified in the tuple instead of a single axis or all the axes as
+ before.
+ dtype : dtype, optional
+ The type of the returned array and of the accumulator in which the
+ elements are summed. The dtype of `a` is used by default unless `a`
+ has an integer dtype of less precision than the default platform
+ integer. In that case, if `a` is signed then the platform integer
+ is used while if `a` is unsigned then an unsigned integer of the
+ same precision as the platform integer is used.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must have
+ the same shape as the expected output, but the type of the output
+ values will be cast if necessary.
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `sum` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+ initial : scalar, optional
+ Starting value for the sum. See `~numpy.ufunc.reduce` for details.
+ where : array_like of bool, optional
+ Elements to include in the sum. See `~numpy.ufunc.reduce` for details.
+
+ Returns
+ -------
+ sum_along_axis : ndarray
+ An array with the same shape as `a`, with the specified
+ axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
+ is returned. If an output array is specified, a reference to
+ `out` is returned.
+
+ See Also
+ --------
+ ndarray.sum : Equivalent method.
+ add: ``numpy.add.reduce`` equivalent function.
+ cumsum : Cumulative sum of array elements.
+ trapezoid : Integration of array values using composite trapezoidal rule.
+
+ mean, average
+
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow.
+
+ The sum of an empty array is the neutral element 0:
+
+ >>> np.sum([])
+ 0.0
+
+ For floating point numbers the numerical precision of sum (and
+ ``np.add.reduce``) is in general limited by directly adding each number
+ individually to the result causing rounding errors in every step.
+ However, often numpy will use a numerically better approach (partial
+ pairwise summation) leading to improved precision in many use-cases.
+ This improved precision is always provided when no ``axis`` is given.
+ When ``axis`` is given, it will depend on which axis is summed.
+ Technically, to provide the best speed possible, the improved precision
+ is only used when the summation is along the fast axis in memory.
+ Note that the exact precision may vary depending on other parameters.
+ In contrast to NumPy, Python's ``math.fsum`` function uses a slower but
+ more precise approach to summation.
+ Especially when summing a large number of lower precision floating point
+ numbers, such as ``float32``, numerical errors can become significant.
+ In such cases it can be advisable to use `dtype="float64"` to use a higher
+ precision for the output.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.sum([0.5, 1.5])
+ 2.0
+ >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
+ np.int32(1)
+ >>> np.sum([[0, 1], [0, 5]])
+ 6
+ >>> np.sum([[0, 1], [0, 5]], axis=0)
+ array([0, 6])
+ >>> np.sum([[0, 1], [0, 5]], axis=1)
+ array([1, 5])
+ >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
+ array([1., 5.])
+
+ If the accumulator is too small, overflow occurs:
+
+ >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
+ np.int8(-128)
+
+ You can also start the sum with a value other than zero:
+
+ >>> np.sum([10], initial=5)
+ 15
+ """
+ if isinstance(a, _gentype):
+ # 2018-02-25, 1.15.0
+ raise TypeError(
+ "Calling np.sum(generator) is deprecated."
+ "Use np.sum(np.fromiter(generator)) or "
+ "the python sum builtin instead.",
+ )
+
+ return _wrapreduction(
+ a, np.add, 'sum', axis, dtype, out,
+ keepdims=keepdims, initial=initial, where=where
+ )
+
+
+def _any_dispatcher(a, axis=None, out=None, keepdims=None, *,
+ where=np._NoValue):
+ return (a, where, out)
+
+
+@array_function_dispatch(_any_dispatcher)
+def any(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
+ """
+ Test whether any array element along a given axis evaluates to True.
+
+ Returns single boolean if `axis` is ``None``
+
+ Parameters
+ ----------
+ a : array_like
+ Input array or object that can be converted to an array.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which a logical OR reduction is performed.
+ The default (``axis=None``) is to perform a logical OR over all
+ the dimensions of the input array. `axis` may be negative, in
+ which case it counts from the last to the first axis. If this
+ is a tuple of ints, a reduction is performed on multiple
+ axes, instead of a single axis or all the axes as before.
+ out : ndarray, optional
+ Alternate output array in which to place the result. It must have
+ the same shape as the expected output and its type is preserved
+ (e.g., if it is of type float, then it will remain so, returning
+ 1.0 for True and 0.0 for False, regardless of the type of `a`).
+ See :ref:`ufuncs-output-type` for more details.
+
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `any` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+
+ where : array_like of bool, optional
+ Elements to include in checking for any `True` values.
+ See `~numpy.ufunc.reduce` for details.
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ any : bool or ndarray
+ A new boolean or `ndarray` is returned unless `out` is specified,
+ in which case a reference to `out` is returned.
+
+ See Also
+ --------
+ ndarray.any : equivalent method
+
+ all : Test whether all elements along a given axis evaluate to True.
+
+ Notes
+ -----
+ Not a Number (NaN), positive infinity and negative infinity evaluate
+ to `True` because these are not equal to zero.
+
+ .. versionchanged:: 2.0
+ Before NumPy 2.0, ``any`` did not return booleans for object dtype
+ input arrays.
+ This behavior is still available via ``np.logical_or.reduce``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.any([[True, False], [True, True]])
+ True
+
+ >>> np.any([[True, False, True ],
+ ... [False, False, False]], axis=0)
+ array([ True, False, True])
+
+ >>> np.any([-1, 0, 5])
+ True
+
+ >>> np.any([[np.nan], [np.inf]], axis=1, keepdims=True)
+ array([[ True],
+ [ True]])
+
+ >>> np.any([[True, False], [False, False]], where=[[False], [True]])
+ False
+
+ >>> a = np.array([[1, 0, 0],
+ ... [0, 0, 1],
+ ... [0, 0, 0]])
+ >>> np.any(a, axis=0)
+ array([ True, False, True])
+ >>> np.any(a, axis=1)
+ array([ True, True, False])
+
+ >>> o=np.array(False)
+ >>> z=np.any([-1, 4, 5], out=o)
+ >>> z, o
+ (array(True), array(True))
+ >>> # Check now that z is a reference to o
+ >>> z is o
+ True
+ >>> id(z), id(o) # identity of z and o # doctest: +SKIP
+ (191614240, 191614240)
+
+ """
+ return _wrapreduction_any_all(a, np.logical_or, 'any', axis, out,
+ keepdims=keepdims, where=where)
+
+
+def _all_dispatcher(a, axis=None, out=None, keepdims=None, *,
+ where=None):
+ return (a, where, out)
+
+
+@array_function_dispatch(_all_dispatcher)
+def all(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
+ """
+ Test whether all array elements along a given axis evaluate to True.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array or object that can be converted to an array.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which a logical AND reduction is performed.
+ The default (``axis=None``) is to perform a logical AND over all
+ the dimensions of the input array. `axis` may be negative, in
+ which case it counts from the last to the first axis. If this
+ is a tuple of ints, a reduction is performed on multiple
+ axes, instead of a single axis or all the axes as before.
+ out : ndarray, optional
+ Alternate output array in which to place the result.
+ It must have the same shape as the expected output and its
+ type is preserved (e.g., if ``dtype(out)`` is float, the result
+ will consist of 0.0's and 1.0's). See :ref:`ufuncs-output-type`
+ for more details.
+
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `all` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+
+ where : array_like of bool, optional
+ Elements to include in checking for all `True` values.
+ See `~numpy.ufunc.reduce` for details.
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ all : ndarray, bool
+ A new boolean or array is returned unless `out` is specified,
+ in which case a reference to `out` is returned.
+
+ See Also
+ --------
+ ndarray.all : equivalent method
+
+ any : Test whether any element along a given axis evaluates to True.
+
+ Notes
+ -----
+ Not a Number (NaN), positive infinity and negative infinity
+ evaluate to `True` because these are not equal to zero.
+
+ .. versionchanged:: 2.0
+ Before NumPy 2.0, ``all`` did not return booleans for object dtype
+ input arrays.
+ This behavior is still available via ``np.logical_and.reduce``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.all([[True,False],[True,True]])
+ False
+
+ >>> np.all([[True,False],[True,True]], axis=0)
+ array([ True, False])
+
+ >>> np.all([-1, 4, 5])
+ True
+
+ >>> np.all([1.0, np.nan])
+ True
+
+ >>> np.all([[True, True], [False, True]], where=[[True], [False]])
+ True
+
+ >>> o=np.array(False)
+ >>> z=np.all([-1, 4, 5], out=o)
+ >>> id(z), id(o), z
+ (28293632, 28293632, array(True)) # may vary
+
+ """
+ return _wrapreduction_any_all(a, np.logical_and, 'all', axis, out,
+ keepdims=keepdims, where=where)
+
+
+def _cumulative_func(x, func, axis, dtype, out, include_initial):
+ x = np.atleast_1d(x)
+ x_ndim = x.ndim
+ if axis is None:
+ if x_ndim >= 2:
+ raise ValueError("For arrays which have more than one dimension "
+ "``axis`` argument is required.")
+ axis = 0
+
+ if out is not None and include_initial:
+ item = [slice(None)] * x_ndim
+ item[axis] = slice(1, None)
+ func.accumulate(x, axis=axis, dtype=dtype, out=out[tuple(item)])
+ item[axis] = 0
+ out[tuple(item)] = func.identity
+ return out
+
+ res = func.accumulate(x, axis=axis, dtype=dtype, out=out)
+ if include_initial:
+ initial_shape = list(x.shape)
+ initial_shape[axis] = 1
+ res = np.concat(
+ [np.full_like(res, func.identity, shape=initial_shape), res],
+ axis=axis,
+ )
+
+ return res
+
+
+def _cumulative_prod_dispatcher(x, /, *, axis=None, dtype=None, out=None,
+ include_initial=None):
+ return (x, out)
+
+
+@array_function_dispatch(_cumulative_prod_dispatcher)
+def cumulative_prod(x, /, *, axis=None, dtype=None, out=None,
+ include_initial=False):
+ """
+ Return the cumulative product of elements along a given axis.
+
+ This function is an Array API compatible alternative to `numpy.cumprod`.
+
+ Parameters
+ ----------
+ x : array_like
+ Input array.
+ axis : int, optional
+ Axis along which the cumulative product is computed. The default
+ (None) is only allowed for one-dimensional arrays. For arrays
+ with more than one dimension ``axis`` is required.
+ dtype : dtype, optional
+ Type of the returned array, as well as of the accumulator in which
+ the elements are multiplied. If ``dtype`` is not specified, it
+ defaults to the dtype of ``x``, unless ``x`` has an integer dtype
+ with a precision less than that of the default platform integer.
+ In that case, the default platform integer is used instead.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must
+ have the same shape and buffer length as the expected output
+ but the type of the resulting values will be cast if necessary.
+ See :ref:`ufuncs-output-type` for more details.
+ include_initial : bool, optional
+ Boolean indicating whether to include the initial value (ones) as
+ the first value in the output. With ``include_initial=True``
+ the shape of the output is different than the shape of the input.
+ Default: ``False``.
+
+ Returns
+ -------
+ cumulative_prod_along_axis : ndarray
+ A new array holding the result is returned unless ``out`` is
+ specified, in which case a reference to ``out`` is returned. The
+ result has the same shape as ``x`` if ``include_initial=False``.
+
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow.
+
+ Examples
+ --------
+ >>> a = np.array([1, 2, 3])
+ >>> np.cumulative_prod(a) # intermediate results 1, 1*2
+ ... # total product 1*2*3 = 6
+ array([1, 2, 6])
+ >>> a = np.array([1, 2, 3, 4, 5, 6])
+ >>> np.cumulative_prod(a, dtype=float) # specify type of output
+ array([ 1., 2., 6., 24., 120., 720.])
+
+ The cumulative product for each column (i.e., over the rows) of ``b``:
+
+ >>> b = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> np.cumulative_prod(b, axis=0)
+ array([[ 1, 2, 3],
+ [ 4, 10, 18]])
+
+ The cumulative product for each row (i.e. over the columns) of ``b``:
+
+ >>> np.cumulative_prod(b, axis=1)
+ array([[ 1, 2, 6],
+ [ 4, 20, 120]])
+
+ """
+ return _cumulative_func(x, um.multiply, axis, dtype, out, include_initial)
+
+
+def _cumulative_sum_dispatcher(x, /, *, axis=None, dtype=None, out=None,
+ include_initial=None):
+ return (x, out)
+
+
+@array_function_dispatch(_cumulative_sum_dispatcher)
+def cumulative_sum(x, /, *, axis=None, dtype=None, out=None,
+ include_initial=False):
+ """
+ Return the cumulative sum of the elements along a given axis.
+
+ This function is an Array API compatible alternative to `numpy.cumsum`.
+
+ Parameters
+ ----------
+ x : array_like
+ Input array.
+ axis : int, optional
+ Axis along which the cumulative sum is computed. The default
+ (None) is only allowed for one-dimensional arrays. For arrays
+ with more than one dimension ``axis`` is required.
+ dtype : dtype, optional
+ Type of the returned array and of the accumulator in which the
+ elements are summed. If ``dtype`` is not specified, it defaults
+ to the dtype of ``x``, unless ``x`` has an integer dtype with
+ a precision less than that of the default platform integer.
+ In that case, the default platform integer is used.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must
+ have the same shape and buffer length as the expected output
+ but the type will be cast if necessary. See :ref:`ufuncs-output-type`
+ for more details.
+ include_initial : bool, optional
+ Boolean indicating whether to include the initial value (zeros) as
+ the first value in the output. With ``include_initial=True``
+ the shape of the output is different than the shape of the input.
+ Default: ``False``.
+
+ Returns
+ -------
+ cumulative_sum_along_axis : ndarray
+ A new array holding the result is returned unless ``out`` is
+ specified, in which case a reference to ``out`` is returned. The
+ result has the same shape as ``x`` if ``include_initial=False``.
+
+ See Also
+ --------
+ sum : Sum array elements.
+ trapezoid : Integration of array values using composite trapezoidal rule.
+ diff : Calculate the n-th discrete difference along given axis.
+
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow.
+
+ ``cumulative_sum(a)[-1]`` may not be equal to ``sum(a)`` for
+ floating-point values since ``sum`` may use a pairwise summation routine,
+ reducing the roundoff-error. See `sum` for more information.
+
+ Examples
+ --------
+ >>> a = np.array([1, 2, 3, 4, 5, 6])
+ >>> a
+ array([1, 2, 3, 4, 5, 6])
+ >>> np.cumulative_sum(a)
+ array([ 1, 3, 6, 10, 15, 21])
+ >>> np.cumulative_sum(a, dtype=float) # specifies type of output value(s)
+ array([ 1., 3., 6., 10., 15., 21.])
+
+ >>> b = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> np.cumulative_sum(b,axis=0) # sum over rows for each of the 3 columns
+ array([[1, 2, 3],
+ [5, 7, 9]])
+ >>> np.cumulative_sum(b,axis=1) # sum over columns for each of the 2 rows
+ array([[ 1, 3, 6],
+ [ 4, 9, 15]])
+
+ ``cumulative_sum(c)[-1]`` may not be equal to ``sum(c)``
+
+ >>> c = np.array([1, 2e-9, 3e-9] * 1000000)
+ >>> np.cumulative_sum(c)[-1]
+ 1000000.0050045159
+ >>> c.sum()
+ 1000000.0050000029
+
+ """
+ return _cumulative_func(x, um.add, axis, dtype, out, include_initial)
+
+
+def _cumsum_dispatcher(a, axis=None, dtype=None, out=None):
+ return (a, out)
+
+
+@array_function_dispatch(_cumsum_dispatcher)
+def cumsum(a, axis=None, dtype=None, out=None):
+ """
+ Return the cumulative sum of the elements along a given axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ axis : int, optional
+ Axis along which the cumulative sum is computed. The default
+ (None) is to compute the cumsum over the flattened array.
+ dtype : dtype, optional
+ Type of the returned array and of the accumulator in which the
+ elements are summed. If `dtype` is not specified, it defaults
+ to the dtype of `a`, unless `a` has an integer dtype with a
+ precision less than that of the default platform integer. In
+ that case, the default platform integer is used.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must
+ have the same shape and buffer length as the expected output
+ but the type will be cast if necessary. See :ref:`ufuncs-output-type`
+ for more details.
+
+ Returns
+ -------
+ cumsum_along_axis : ndarray.
+ A new array holding the result is returned unless `out` is
+ specified, in which case a reference to `out` is returned. The
+ result has the same size as `a`, and the same shape as `a` if
+ `axis` is not None or `a` is a 1-d array.
+
+ See Also
+ --------
+ cumulative_sum : Array API compatible alternative for ``cumsum``.
+ sum : Sum array elements.
+ trapezoid : Integration of array values using composite trapezoidal rule.
+ diff : Calculate the n-th discrete difference along given axis.
+
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow.
+
+ ``cumsum(a)[-1]`` may not be equal to ``sum(a)`` for floating-point
+ values since ``sum`` may use a pairwise summation routine, reducing
+ the roundoff-error. See `sum` for more information.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1,2,3], [4,5,6]])
+ >>> a
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> np.cumsum(a)
+ array([ 1, 3, 6, 10, 15, 21])
+ >>> np.cumsum(a, dtype=float) # specifies type of output value(s)
+ array([ 1., 3., 6., 10., 15., 21.])
+
+ >>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
+ array([[1, 2, 3],
+ [5, 7, 9]])
+ >>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
+ array([[ 1, 3, 6],
+ [ 4, 9, 15]])
+
+ ``cumsum(b)[-1]`` may not be equal to ``sum(b)``
+
+ >>> b = np.array([1, 2e-9, 3e-9] * 1000000)
+ >>> b.cumsum()[-1]
+ 1000000.0050045159
+ >>> b.sum()
+ 1000000.0050000029
+
+ """
+ return _wrapfunc(a, 'cumsum', axis=axis, dtype=dtype, out=out)
+
+
+def _ptp_dispatcher(a, axis=None, out=None, keepdims=None):
+ return (a, out)
+
+
+@array_function_dispatch(_ptp_dispatcher)
+def ptp(a, axis=None, out=None, keepdims=np._NoValue):
+ """
+ Range of values (maximum - minimum) along an axis.
+
+ The name of the function comes from the acronym for 'peak to peak'.
+
+ .. warning::
+ `ptp` preserves the data type of the array. This means the
+ return value for an input of signed integers with n bits
+ (e.g. `numpy.int8`, `numpy.int16`, etc) is also a signed integer
+ with n bits. In that case, peak-to-peak values greater than
+ ``2**(n-1)-1`` will be returned as negative values. An example
+ with a work-around is shown below.
+
+ Parameters
+ ----------
+ a : array_like
+ Input values.
+ axis : None or int or tuple of ints, optional
+ Axis along which to find the peaks. By default, flatten the
+ array. `axis` may be negative, in
+ which case it counts from the last to the first axis.
+ If this is a tuple of ints, a reduction is performed on multiple
+ axes, instead of a single axis or all the axes as before.
+ out : array_like
+ Alternative output array in which to place the result. It must
+ have the same shape and buffer length as the expected output,
+ but the type of the output values will be cast if necessary.
+
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `ptp` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+
+ Returns
+ -------
+ ptp : ndarray or scalar
+ The range of a given array - `scalar` if array is one-dimensional
+ or a new array holding the result along the given axis
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([[4, 9, 2, 10],
+ ... [6, 9, 7, 12]])
+
+ >>> np.ptp(x, axis=1)
+ array([8, 6])
+
+ >>> np.ptp(x, axis=0)
+ array([2, 0, 5, 2])
+
+ >>> np.ptp(x)
+ 10
+
+ This example shows that a negative value can be returned when
+ the input is an array of signed integers.
+
+ >>> y = np.array([[1, 127],
+ ... [0, 127],
+ ... [-1, 127],
+ ... [-2, 127]], dtype=np.int8)
+ >>> np.ptp(y, axis=1)
+ array([ 126, 127, -128, -127], dtype=int8)
+
+ A work-around is to use the `view()` method to view the result as
+ unsigned integers with the same bit width:
+
+ >>> np.ptp(y, axis=1).view(np.uint8)
+ array([126, 127, 128, 129], dtype=uint8)
+
+ """
+ kwargs = {}
+ if keepdims is not np._NoValue:
+ kwargs['keepdims'] = keepdims
+ return _methods._ptp(a, axis=axis, out=out, **kwargs)
+
+
+def _max_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
+ where=None):
+ return (a, out)
+
+
+@array_function_dispatch(_max_dispatcher)
+@set_module('numpy')
+def max(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
+ where=np._NoValue):
+ """
+ Return the maximum of an array or maximum along an axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which to operate. By default, flattened input is
+ used. If this is a tuple of ints, the maximum is selected over
+ multiple axes, instead of a single axis or all the axes as before.
+
+ out : ndarray, optional
+ Alternative output array in which to place the result. Must
+ be of the same shape and buffer length as the expected output.
+ See :ref:`ufuncs-output-type` for more details.
+
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the ``max`` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+
+ initial : scalar, optional
+ The minimum value of an output element. Must be present to allow
+ computation on empty slice. See `~numpy.ufunc.reduce` for details.
+
+ where : array_like of bool, optional
+ Elements to compare for the maximum. See `~numpy.ufunc.reduce`
+ for details.
+
+ Returns
+ -------
+ max : ndarray or scalar
+ Maximum of `a`. If `axis` is None, the result is a scalar value.
+ If `axis` is an int, the result is an array of dimension
+ ``a.ndim - 1``. If `axis` is a tuple, the result is an array of
+ dimension ``a.ndim - len(axis)``.
+
+ See Also
+ --------
+ amin :
+ The minimum value of an array along a given axis, propagating any NaNs.
+ nanmax :
+ The maximum value of an array along a given axis, ignoring any NaNs.
+ maximum :
+ Element-wise maximum of two arrays, propagating any NaNs.
+ fmax :
+ Element-wise maximum of two arrays, ignoring any NaNs.
+ argmax :
+ Return the indices of the maximum values.
+
+ nanmin, minimum, fmin
+
+ Notes
+ -----
+ NaN values are propagated, that is if at least one item is NaN, the
+ corresponding max value will be NaN as well. To ignore NaN values
+ (MATLAB behavior), please use nanmax.
+
+ Don't use `~numpy.max` for element-wise comparison of 2 arrays; when
+ ``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than
+ ``max(a, axis=0)``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(4).reshape((2,2))
+ >>> a
+ array([[0, 1],
+ [2, 3]])
+ >>> np.max(a) # Maximum of the flattened array
+ 3
+ >>> np.max(a, axis=0) # Maxima along the first axis
+ array([2, 3])
+ >>> np.max(a, axis=1) # Maxima along the second axis
+ array([1, 3])
+ >>> np.max(a, where=[False, True], initial=-1, axis=0)
+ array([-1, 3])
+ >>> b = np.arange(5, dtype=float)
+ >>> b[2] = np.nan
+ >>> np.max(b)
+ np.float64(nan)
+ >>> np.max(b, where=~np.isnan(b), initial=-1)
+ 4.0
+ >>> np.nanmax(b)
+ 4.0
+
+ You can use an initial value to compute the maximum of an empty slice, or
+ to initialize it to a different value:
+
+ >>> np.max([[-50], [10]], axis=-1, initial=0)
+ array([ 0, 10])
+
+ Notice that the initial value is used as one of the elements for which the
+ maximum is determined, unlike for the default argument Python's max
+ function, which is only used for empty iterables.
+
+ >>> np.max([5], initial=6)
+ 6
+ >>> max([5], default=6)
+ 5
+ """
+ return _wrapreduction(a, np.maximum, 'max', axis, None, out,
+ keepdims=keepdims, initial=initial, where=where)
+
+
+@array_function_dispatch(_max_dispatcher)
+def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
+ where=np._NoValue):
+ """
+ Return the maximum of an array or maximum along an axis.
+
+ `amax` is an alias of `~numpy.max`.
+
+ See Also
+ --------
+ max : alias of this function
+ ndarray.max : equivalent method
+ """
+ return _wrapreduction(a, np.maximum, 'max', axis, None, out,
+ keepdims=keepdims, initial=initial, where=where)
+
+
+def _min_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
+ where=None):
+ return (a, out)
+
+
+@array_function_dispatch(_min_dispatcher)
+def min(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
+ where=np._NoValue):
+ """
+ Return the minimum of an array or minimum along an axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which to operate. By default, flattened input is
+ used.
+
+ If this is a tuple of ints, the minimum is selected over multiple axes,
+ instead of a single axis or all the axes as before.
+ out : ndarray, optional
+ Alternative output array in which to place the result. Must
+ be of the same shape and buffer length as the expected output.
+ See :ref:`ufuncs-output-type` for more details.
+
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the ``min`` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+
+ initial : scalar, optional
+ The maximum value of an output element. Must be present to allow
+ computation on empty slice. See `~numpy.ufunc.reduce` for details.
+
+ where : array_like of bool, optional
+ Elements to compare for the minimum. See `~numpy.ufunc.reduce`
+ for details.
+
+ Returns
+ -------
+ min : ndarray or scalar
+ Minimum of `a`. If `axis` is None, the result is a scalar value.
+ If `axis` is an int, the result is an array of dimension
+ ``a.ndim - 1``. If `axis` is a tuple, the result is an array of
+ dimension ``a.ndim - len(axis)``.
+
+ See Also
+ --------
+ amax :
+ The maximum value of an array along a given axis, propagating any NaNs.
+ nanmin :
+ The minimum value of an array along a given axis, ignoring any NaNs.
+ minimum :
+ Element-wise minimum of two arrays, propagating any NaNs.
+ fmin :
+ Element-wise minimum of two arrays, ignoring any NaNs.
+ argmin :
+ Return the indices of the minimum values.
+
+ nanmax, maximum, fmax
+
+ Notes
+ -----
+ NaN values are propagated, that is if at least one item is NaN, the
+ corresponding min value will be NaN as well. To ignore NaN values
+ (MATLAB behavior), please use nanmin.
+
+ Don't use `~numpy.min` for element-wise comparison of 2 arrays; when
+ ``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than
+ ``min(a, axis=0)``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(4).reshape((2,2))
+ >>> a
+ array([[0, 1],
+ [2, 3]])
+ >>> np.min(a) # Minimum of the flattened array
+ 0
+ >>> np.min(a, axis=0) # Minima along the first axis
+ array([0, 1])
+ >>> np.min(a, axis=1) # Minima along the second axis
+ array([0, 2])
+ >>> np.min(a, where=[False, True], initial=10, axis=0)
+ array([10, 1])
+
+ >>> b = np.arange(5, dtype=float)
+ >>> b[2] = np.nan
+ >>> np.min(b)
+ np.float64(nan)
+ >>> np.min(b, where=~np.isnan(b), initial=10)
+ 0.0
+ >>> np.nanmin(b)
+ 0.0
+
+ >>> np.min([[-50], [10]], axis=-1, initial=0)
+ array([-50, 0])
+
+ Notice that the initial value is used as one of the elements for which the
+ minimum is determined, unlike for the default argument Python's max
+ function, which is only used for empty iterables.
+
+ Notice that this isn't the same as Python's ``default`` argument.
+
+ >>> np.min([6], initial=5)
+ 5
+ >>> min([6], default=5)
+ 6
+ """
+ return _wrapreduction(a, np.minimum, 'min', axis, None, out,
+ keepdims=keepdims, initial=initial, where=where)
+
+
+@array_function_dispatch(_min_dispatcher)
+def amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
+ where=np._NoValue):
+ """
+ Return the minimum of an array or minimum along an axis.
+
+ `amin` is an alias of `~numpy.min`.
+
+ See Also
+ --------
+ min : alias of this function
+ ndarray.min : equivalent method
+ """
+ return _wrapreduction(a, np.minimum, 'min', axis, None, out,
+ keepdims=keepdims, initial=initial, where=where)
+
+
+def _prod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
+ initial=None, where=None):
+ return (a, out)
+
+
+@array_function_dispatch(_prod_dispatcher)
+def prod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
+ initial=np._NoValue, where=np._NoValue):
+ """
+ Return the product of array elements over a given axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which a product is performed. The default,
+ axis=None, will calculate the product of all the elements in the
+ input array. If axis is negative it counts from the last to the
+ first axis.
+
+ If axis is a tuple of ints, a product is performed on all of the
+ axes specified in the tuple instead of a single axis or all the
+ axes as before.
+ dtype : dtype, optional
+ The type of the returned array, as well as of the accumulator in
+ which the elements are multiplied. The dtype of `a` is used by
+ default unless `a` has an integer dtype of less precision than the
+ default platform integer. In that case, if `a` is signed then the
+ platform integer is used while if `a` is unsigned then an unsigned
+ integer of the same precision as the platform integer is used.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must have
+ the same shape as the expected output, but the type of the output
+ values will be cast if necessary.
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left in the
+ result as dimensions with size one. With this option, the result
+ will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `prod` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+ initial : scalar, optional
+ The starting value for this product. See `~numpy.ufunc.reduce`
+ for details.
+ where : array_like of bool, optional
+ Elements to include in the product. See `~numpy.ufunc.reduce`
+ for details.
+
+ Returns
+ -------
+ product_along_axis : ndarray, see `dtype` parameter above.
+ An array shaped as `a` but with the specified axis removed.
+ Returns a reference to `out` if specified.
+
+ See Also
+ --------
+ ndarray.prod : equivalent method
+ :ref:`ufuncs-output-type`
+
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow. That means that, on a 32-bit platform:
+
+ >>> x = np.array([536870910, 536870910, 536870910, 536870910])
+ >>> np.prod(x)
+ 16 # may vary
+
+ The product of an empty array is the neutral element 1:
+
+ >>> np.prod([])
+ 1.0
+
+ Examples
+ --------
+ By default, calculate the product of all elements:
+
+ >>> import numpy as np
+ >>> np.prod([1.,2.])
+ 2.0
+
+ Even when the input array is two-dimensional:
+
+ >>> a = np.array([[1., 2.], [3., 4.]])
+ >>> np.prod(a)
+ 24.0
+
+ But we can also specify the axis over which to multiply:
+
+ >>> np.prod(a, axis=1)
+ array([ 2., 12.])
+ >>> np.prod(a, axis=0)
+ array([3., 8.])
+
+ Or select specific elements to include:
+
+ >>> np.prod([1., np.nan, 3.], where=[True, False, True])
+ 3.0
+
+ If the type of `x` is unsigned, then the output type is
+ the unsigned platform integer:
+
+ >>> x = np.array([1, 2, 3], dtype=np.uint8)
+ >>> np.prod(x).dtype == np.uint
+ True
+
+ If `x` is of a signed integer type, then the output type
+ is the default platform integer:
+
+ >>> x = np.array([1, 2, 3], dtype=np.int8)
+ >>> np.prod(x).dtype == int
+ True
+
+ You can also start the product with a value other than one:
+
+ >>> np.prod([1, 2], initial=5)
+ 10
+ """
+ return _wrapreduction(a, np.multiply, 'prod', axis, dtype, out,
+ keepdims=keepdims, initial=initial, where=where)
+
+
+def _cumprod_dispatcher(a, axis=None, dtype=None, out=None):
+ return (a, out)
+
+
+@array_function_dispatch(_cumprod_dispatcher)
+def cumprod(a, axis=None, dtype=None, out=None):
+ """
+ Return the cumulative product of elements along a given axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ axis : int, optional
+ Axis along which the cumulative product is computed. By default
+ the input is flattened.
+ dtype : dtype, optional
+ Type of the returned array, as well as of the accumulator in which
+ the elements are multiplied. If *dtype* is not specified, it
+ defaults to the dtype of `a`, unless `a` has an integer dtype with
+ a precision less than that of the default platform integer. In
+ that case, the default platform integer is used instead.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must
+ have the same shape and buffer length as the expected output
+ but the type of the resulting values will be cast if necessary.
+
+ Returns
+ -------
+ cumprod : ndarray
+ A new array holding the result is returned unless `out` is
+ specified, in which case a reference to out is returned.
+
+ See Also
+ --------
+ cumulative_prod : Array API compatible alternative for ``cumprod``.
+ :ref:`ufuncs-output-type`
+
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([1,2,3])
+ >>> np.cumprod(a) # intermediate results 1, 1*2
+ ... # total product 1*2*3 = 6
+ array([1, 2, 6])
+ >>> a = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> np.cumprod(a, dtype=float) # specify type of output
+ array([ 1., 2., 6., 24., 120., 720.])
+
+ The cumulative product for each column (i.e., over the rows) of `a`:
+
+ >>> np.cumprod(a, axis=0)
+ array([[ 1, 2, 3],
+ [ 4, 10, 18]])
+
+ The cumulative product for each row (i.e. over the columns) of `a`:
+
+ >>> np.cumprod(a,axis=1)
+ array([[ 1, 2, 6],
+ [ 4, 20, 120]])
+
+ """
+ return _wrapfunc(a, 'cumprod', axis=axis, dtype=dtype, out=out)
+
+
+def _ndim_dispatcher(a):
+ return (a,)
+
+
+@array_function_dispatch(_ndim_dispatcher)
+def ndim(a):
+ """
+ Return the number of dimensions of an array.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array. If it is not already an ndarray, a conversion is
+ attempted.
+
+ Returns
+ -------
+ number_of_dimensions : int
+ The number of dimensions in `a`. Scalars are zero-dimensional.
+
+ See Also
+ --------
+ ndarray.ndim : equivalent method
+ shape : dimensions of array
+ ndarray.shape : dimensions of array
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.ndim([[1,2,3],[4,5,6]])
+ 2
+ >>> np.ndim(np.array([[1,2,3],[4,5,6]]))
+ 2
+ >>> np.ndim(1)
+ 0
+
+ """
+ try:
+ return a.ndim
+ except AttributeError:
+ return asarray(a).ndim
+
+
+def _size_dispatcher(a, axis=None):
+ return (a,)
+
+
+@array_function_dispatch(_size_dispatcher)
+def size(a, axis=None):
+ """
+ Return the number of elements along a given axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which the elements are counted. By default, give
+ the total number of elements.
+
+ .. versionchanged:: 2.4
+ Extended to accept multiple axes.
+
+ Returns
+ -------
+ element_count : int
+ Number of elements along the specified axis.
+
+ See Also
+ --------
+ shape : dimensions of array
+ ndarray.shape : dimensions of array
+ ndarray.size : number of elements in array
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1,2,3],[4,5,6]])
+ >>> np.size(a)
+ 6
+ >>> np.size(a,axis=1)
+ 3
+ >>> np.size(a,axis=0)
+ 2
+ >>> np.size(a,axis=(0,1))
+ 6
+
+ """
+ if axis is None:
+ try:
+ return a.size
+ except AttributeError:
+ return asarray(a).size
+ else:
+ _shape = shape(a)
+ from .numeric import normalize_axis_tuple
+ axis = normalize_axis_tuple(axis, len(_shape), allow_duplicate=False)
+ return math.prod(_shape[ax] for ax in axis)
+
+
+def _round_dispatcher(a, decimals=None, out=None):
+ return (a, out)
+
+
+@array_function_dispatch(_round_dispatcher)
+def round(a, decimals=0, out=None):
+ """
+ Evenly round to the given number of decimals.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+ decimals : int, optional
+ Number of decimal places to round to (default: 0). If
+ decimals is negative, it specifies the number of positions to
+ the left of the decimal point.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must have
+ the same shape as the expected output, but the type of the output
+ values will be cast if necessary. See :ref:`ufuncs-output-type`
+ for more details.
+
+ Returns
+ -------
+ rounded_array : ndarray
+ An array of the same type as `a`, containing the rounded values.
+ Unless `out` was specified, a new array is created. A reference to
+ the result is returned.
+
+ The real and imaginary parts of complex numbers are rounded
+ separately. The result of rounding a float is a float.
+
+ See Also
+ --------
+ ndarray.round : equivalent method
+ around : an alias for this function
+ ceil, fix, floor, rint, trunc
+
+
+ Notes
+ -----
+ For values exactly halfway between rounded decimal values, NumPy
+ rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
+ -0.5 and 0.5 round to 0.0, etc.
+
+ ``np.round`` uses a fast but sometimes inexact algorithm to round
+ floating-point datatypes. For positive `decimals` it is equivalent to
+ ``np.true_divide(np.rint(a * 10**decimals), 10**decimals)``, which has
+ error due to the inexact representation of decimal fractions in the IEEE
+ floating point standard [1]_ and errors introduced when scaling by powers
+ of ten. For instance, note the extra "1" in the following:
+
+ >>> np.round(56294995342131.5, 3)
+ 56294995342131.51
+
+ If your goal is to print such values with a fixed number of decimals, it is
+ preferable to use numpy's float printing routines to limit the number of
+ printed decimals:
+
+ >>> np.format_float_positional(56294995342131.5, precision=3)
+ '56294995342131.5'
+
+ The float printing routines use an accurate but much more computationally
+ demanding algorithm to compute the number of digits after the decimal
+ point.
+
+ Alternatively, Python's builtin `round` function uses a more accurate
+ but slower algorithm for 64-bit floating point values:
+
+ >>> round(56294995342131.5, 3)
+ 56294995342131.5
+ >>> np.round(16.055, 2), round(16.055, 2) # equals 16.0549999999999997
+ (16.06, 16.05)
+
+
+ References
+ ----------
+ .. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
+ https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.round([0.37, 1.64])
+ array([0., 2.])
+ >>> np.round([0.37, 1.64], decimals=1)
+ array([0.4, 1.6])
+ >>> np.round([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
+ array([0., 2., 2., 4., 4.])
+ >>> np.round([1,2,3,11], decimals=1) # ndarray of ints is returned
+ array([ 1, 2, 3, 11])
+ >>> np.round([1,2,3,11], decimals=-1)
+ array([ 0, 0, 0, 10])
+
+ """
+ return _wrapfunc(a, 'round', decimals=decimals, out=out)
+
+
+@array_function_dispatch(_round_dispatcher)
+def around(a, decimals=0, out=None):
+ """
+ Round an array to the given number of decimals.
+
+ `around` is an alias of `~numpy.round`.
+
+ See Also
+ --------
+ ndarray.round : equivalent method
+ round : alias for this function
+ ceil, fix, floor, rint, trunc
+
+ """
+ return _wrapfunc(a, 'round', decimals=decimals, out=out)
+
+
+def _mean_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, *,
+ where=None):
+ return (a, where, out)
+
+
+@array_function_dispatch(_mean_dispatcher)
+def mean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, *,
+ where=np._NoValue):
+ """
+ Compute the arithmetic mean along the specified axis.
+
+ Returns the average of the array elements. The average is taken over
+ the flattened array by default, otherwise over the specified axis.
+ `float64` intermediate and return values are used for integer inputs.
+
+ Parameters
+ ----------
+ a : array_like
+ Array containing numbers whose mean is desired. If `a` is not an
+ array, a conversion is attempted.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which the means are computed. The default is to
+ compute the mean of the flattened array.
+
+ If this is a tuple of ints, a mean is performed over multiple axes,
+ instead of a single axis or all the axes as before.
+ dtype : data-type, optional
+ Type to use in computing the mean. For integer inputs, the default
+ is `float64`; for floating point inputs, it is the same as the
+ input dtype.
+ out : ndarray, optional
+ Alternate output array in which to place the result. The default
+ is ``None``; if provided, it must have the same shape as the
+ expected output, but the type will be cast if necessary.
+ See :ref:`ufuncs-output-type` for more details.
+ See :ref:`ufuncs-output-type` for more details.
+
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `mean` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+
+ where : array_like of bool, optional
+ Elements to include in the mean. See `~numpy.ufunc.reduce` for details.
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ m : ndarray, see dtype parameter above
+ If `out=None`, returns a new array containing the mean values,
+ otherwise a reference to the output array is returned.
+
+ See Also
+ --------
+ average : Weighted average
+ std, var, nanmean, nanstd, nanvar
+
+ Notes
+ -----
+ The arithmetic mean is the sum of the elements along the axis divided
+ by the number of elements.
+
+ Note that for floating-point input, the mean is computed using the
+ same precision the input has. Depending on the input data, this can
+ cause the results to be inaccurate, especially for `float32` (see
+ example below). Specifying a higher-precision accumulator using the
+ `dtype` keyword can alleviate this issue.
+
+ By default, `float16` results are computed using `float32` intermediates
+ for extra precision.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> np.mean(a)
+ 2.5
+ >>> np.mean(a, axis=0)
+ array([2., 3.])
+ >>> np.mean(a, axis=1)
+ array([1.5, 3.5])
+
+ In single precision, `mean` can be inaccurate:
+
+ >>> a = np.zeros((2, 512*512), dtype=np.float32)
+ >>> a[0, :] = 1.0
+ >>> a[1, :] = 0.1
+ >>> np.mean(a)
+ np.float32(0.54999924)
+
+ Computing the mean in float64 is more accurate:
+
+ >>> np.mean(a, dtype=np.float64)
+ 0.55000000074505806 # may vary
+
+ Computing the mean in timedelta64 is available:
+
+ >>> b = np.array([1, 3], dtype="timedelta64[D]")
+ >>> np.mean(b)
+ np.timedelta64(2,'D')
+
+ Specifying a where argument:
+
+ >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])
+ >>> np.mean(a)
+ 12.0
+ >>> np.mean(a, where=[[True], [False], [False]])
+ 9.0
+
+ """
+ kwargs = {}
+ if keepdims is not np._NoValue:
+ kwargs['keepdims'] = keepdims
+ if where is not np._NoValue:
+ kwargs['where'] = where
+ if type(a) is not mu.ndarray:
+ try:
+ mean = a.mean
+ except AttributeError:
+ pass
+ else:
+ return mean(axis=axis, dtype=dtype, out=out, **kwargs)
+
+ return _methods._mean(a, axis=axis, dtype=dtype,
+ out=out, **kwargs)
+
+
+def _std_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
+ keepdims=None, *, where=None, mean=None, correction=None):
+ return (a, where, out, mean)
+
+
+@array_function_dispatch(_std_dispatcher)
+def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
+ where=np._NoValue, mean=np._NoValue, correction=np._NoValue):
+ r"""
+ Compute the standard deviation along the specified axis.
+
+ Returns the standard deviation, a measure of the spread of a distribution,
+ of the array elements. The standard deviation is computed for the
+ flattened array by default, otherwise over the specified axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Calculate the standard deviation of these values.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which the standard deviation is computed. The
+ default is to compute the standard deviation of the flattened array.
+ If this is a tuple of ints, a standard deviation is performed over
+ multiple axes, instead of a single axis or all the axes as before.
+ dtype : dtype, optional
+ Type to use in computing the standard deviation. For arrays of
+ integer type the default is float64, for arrays of float types it is
+ the same as the array type.
+ out : ndarray, optional
+ Alternative output array in which to place the result. It must have
+ the same shape as the expected output but the type (of the calculated
+ values) will be cast if necessary.
+ See :ref:`ufuncs-output-type` for more details.
+ ddof : {int, float}, optional
+ Means Delta Degrees of Freedom. The divisor used in calculations
+ is ``N - ddof``, where ``N`` represents the number of elements.
+ By default `ddof` is zero. See Notes for details about use of `ddof`.
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `std` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+ where : array_like of bool, optional
+ Elements to include in the standard deviation.
+ See `~numpy.ufunc.reduce` for details.
+
+ .. versionadded:: 1.20.0
+
+ mean : array_like, optional
+ Provide the mean to prevent its recalculation. The mean should have
+ a shape as if it was calculated with ``keepdims=True``.
+ The axis for the calculation of the mean should be the same as used in
+ the call to this std function.
+
+ .. versionadded:: 2.0.0
+
+ correction : {int, float}, optional
+ Array API compatible name for the ``ddof`` parameter. Only one of them
+ can be provided at the same time.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ standard_deviation : ndarray, see dtype parameter above.
+ If `out` is None, return a new array containing the standard deviation,
+ otherwise return a reference to the output array.
+
+ See Also
+ --------
+ var, mean, nanmean, nanstd, nanvar
+ :ref:`ufuncs-output-type`
+
+ Notes
+ -----
+ There are several common variants of the array standard deviation
+ calculation. Assuming the input `a` is a one-dimensional NumPy array
+ and ``mean`` is either provided as an argument or computed as
+ ``a.mean()``, NumPy computes the standard deviation of an array as::
+
+ N = len(a)
+ d2 = abs(a - mean)**2 # abs is for complex `a`
+ var = d2.sum() / (N - ddof) # note use of `ddof`
+ std = var**0.5
+
+ Different values of the argument `ddof` are useful in different
+ contexts. NumPy's default ``ddof=0`` corresponds with the expression:
+
+ .. math::
+
+ \sqrt{\frac{\sum_i{|a_i - \bar{a}|^2 }}{N}}
+
+ which is sometimes called the "population standard deviation" in the field
+ of statistics because it applies the definition of standard deviation to
+ `a` as if `a` were a complete population of possible observations.
+
+ Many other libraries define the standard deviation of an array
+ differently, e.g.:
+
+ .. math::
+
+ \sqrt{\frac{\sum_i{|a_i - \bar{a}|^2 }}{N - 1}}
+
+ In statistics, the resulting quantity is sometimes called the "sample
+ standard deviation" because if `a` is a random sample from a larger
+ population, this calculation provides the square root of an unbiased
+ estimate of the variance of the population. The use of :math:`N-1` in the
+ denominator is often called "Bessel's correction" because it corrects for
+ bias (toward lower values) in the variance estimate introduced when the
+ sample mean of `a` is used in place of the true mean of the population.
+ The resulting estimate of the standard deviation is still biased, but less
+ than it would have been without the correction. For this quantity, use
+ ``ddof=1``.
+
+ Note that, for complex numbers, `std` takes the absolute
+ value before squaring, so that the result is always real and nonnegative.
+
+ For floating-point input, the standard deviation is computed using the same
+ precision the input has. Depending on the input data, this can cause
+ the results to be inaccurate, especially for float32 (see example below).
+ Specifying a higher-accuracy accumulator using the `dtype` keyword can
+ alleviate this issue.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> np.std(a)
+ 1.1180339887498949 # may vary
+ >>> np.std(a, axis=0)
+ array([1., 1.])
+ >>> np.std(a, axis=1)
+ array([0.5, 0.5])
+
+ In single precision, std() can be inaccurate:
+
+ >>> a = np.zeros((2, 512*512), dtype=np.float32)
+ >>> a[0, :] = 1.0
+ >>> a[1, :] = 0.1
+ >>> np.std(a)
+ np.float32(0.45000005)
+
+ Computing the standard deviation in float64 is more accurate:
+
+ >>> np.std(a, dtype=np.float64)
+ 0.44999999925494177 # may vary
+
+ Specifying a where argument:
+
+ >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
+ >>> np.std(a)
+ 2.614064523559687 # may vary
+ >>> np.std(a, where=[[True], [True], [False]])
+ 2.0
+
+ Using the mean keyword to save computation time:
+
+ >>> import numpy as np
+ >>> from timeit import timeit
+ >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
+ >>> mean = np.mean(a, axis=1, keepdims=True)
+ >>>
+ >>> g = globals()
+ >>> n = 10000
+ >>> t1 = timeit("std = np.std(a, axis=1, mean=mean)", globals=g, number=n)
+ >>> t2 = timeit("std = np.std(a, axis=1)", globals=g, number=n)
+ >>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
+ #doctest: +SKIP
+ Percentage execution time saved 30%
+
+ """
+ kwargs = {}
+ if keepdims is not np._NoValue:
+ kwargs['keepdims'] = keepdims
+ if where is not np._NoValue:
+ kwargs['where'] = where
+ if mean is not np._NoValue:
+ kwargs['mean'] = mean
+
+ if correction != np._NoValue:
+ if ddof != 0:
+ raise ValueError(
+ "ddof and correction can't be provided simultaneously."
+ )
+ else:
+ ddof = correction
+
+ if type(a) is not mu.ndarray:
+ try:
+ std = a.std
+ except AttributeError:
+ pass
+ else:
+ return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
+
+ return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
+ **kwargs)
+
+
+def _var_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
+ keepdims=None, *, where=None, mean=None, correction=None):
+ return (a, where, out, mean)
+
+
+@array_function_dispatch(_var_dispatcher)
+def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
+ where=np._NoValue, mean=np._NoValue, correction=np._NoValue):
+ r"""
+ Compute the variance along the specified axis.
+
+ Returns the variance of the array elements, a measure of the spread of a
+ distribution. The variance is computed for the flattened array by
+ default, otherwise over the specified axis.
+
+ Parameters
+ ----------
+ a : array_like
+ Array containing numbers whose variance is desired. If `a` is not an
+ array, a conversion is attempted.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which the variance is computed. The default is to
+ compute the variance of the flattened array.
+ If this is a tuple of ints, a variance is performed over multiple axes,
+ instead of a single axis or all the axes as before.
+ dtype : data-type, optional
+ Type to use in computing the variance. For arrays of integer type
+ the default is `float64`; for arrays of float types it is the same as
+ the array type.
+ out : ndarray, optional
+ Alternate output array in which to place the result. It must have
+ the same shape as the expected output, but the type is cast if
+ necessary.
+ ddof : {int, float}, optional
+ "Delta Degrees of Freedom": the divisor used in the calculation is
+ ``N - ddof``, where ``N`` represents the number of elements. By
+ default `ddof` is zero. See notes for details about use of `ddof`.
+ keepdims : bool, optional
+ If this is set to True, the axes which are reduced are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ If the default value is passed, then `keepdims` will not be
+ passed through to the `var` method of sub-classes of
+ `ndarray`, however any non-default value will be. If the
+ sub-class' method does not implement `keepdims` any
+ exceptions will be raised.
+ where : array_like of bool, optional
+ Elements to include in the variance. See `~numpy.ufunc.reduce` for
+ details.
+
+ .. versionadded:: 1.20.0
+
+ mean : array like, optional
+ Provide the mean to prevent its recalculation. The mean should have
+ a shape as if it was calculated with ``keepdims=True``.
+ The axis for the calculation of the mean should be the same as used in
+ the call to this var function.
+
+ .. versionadded:: 2.0.0
+
+ correction : {int, float}, optional
+ Array API compatible name for the ``ddof`` parameter. Only one of them
+ can be provided at the same time.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ variance : ndarray, see dtype parameter above
+ If ``out=None``, returns a new array containing the variance;
+ otherwise, a reference to the output array is returned.
+
+ See Also
+ --------
+ std, mean, nanmean, nanstd, nanvar
+ :ref:`ufuncs-output-type`
+
+ Notes
+ -----
+ There are several common variants of the array variance calculation.
+ Assuming the input `a` is a one-dimensional NumPy array and ``mean`` is
+ either provided as an argument or computed as ``a.mean()``, NumPy
+ computes the variance of an array as::
+
+ N = len(a)
+ d2 = abs(a - mean)**2 # abs is for complex `a`
+ var = d2.sum() / (N - ddof) # note use of `ddof`
+
+ Different values of the argument `ddof` are useful in different
+ contexts. NumPy's default ``ddof=0`` corresponds with the expression:
+
+ .. math::
+
+ \frac{\sum_i{|a_i - \bar{a}|^2 }}{N}
+
+ which is sometimes called the "population variance" in the field of
+ statistics because it applies the definition of variance to `a` as if `a`
+ were a complete population of possible observations.
+
+ Many other libraries define the variance of an array differently, e.g.:
+
+ .. math::
+
+ \frac{\sum_i{|a_i - \bar{a}|^2}}{N - 1}
+
+ In statistics, the resulting quantity is sometimes called the "sample
+ variance" because if `a` is a random sample from a larger population,
+ this calculation provides an unbiased estimate of the variance of the
+ population. The use of :math:`N-1` in the denominator is often called
+ "Bessel's correction" because it corrects for bias (toward lower values)
+ in the variance estimate introduced when the sample mean of `a` is used
+ in place of the true mean of the population. For this quantity, use
+ ``ddof=1``.
+
+ Note that for complex numbers, the absolute value is taken before
+ squaring, so that the result is always real and nonnegative.
+
+ For floating-point input, the variance is computed using the same
+ precision the input has. Depending on the input data, this can cause
+ the results to be inaccurate, especially for `float32` (see example
+ below). Specifying a higher-accuracy accumulator using the ``dtype``
+ keyword can alleviate this issue.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> np.var(a)
+ 1.25
+ >>> np.var(a, axis=0)
+ array([1., 1.])
+ >>> np.var(a, axis=1)
+ array([0.25, 0.25])
+
+ In single precision, var() can be inaccurate:
+
+ >>> a = np.zeros((2, 512*512), dtype=np.float32)
+ >>> a[0, :] = 1.0
+ >>> a[1, :] = 0.1
+ >>> np.var(a)
+ np.float32(0.20250003)
+
+ Computing the variance in float64 is more accurate:
+
+ >>> np.var(a, dtype=np.float64)
+ 0.20249999932944759 # may vary
+ >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
+ 0.2025
+
+ Specifying a where argument:
+
+ >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
+ >>> np.var(a)
+ 6.833333333333333 # may vary
+ >>> np.var(a, where=[[True], [True], [False]])
+ 4.0
+
+ Using the mean keyword to save computation time:
+
+ >>> import numpy as np
+ >>> from timeit import timeit
+ >>>
+ >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
+ >>> mean = np.mean(a, axis=1, keepdims=True)
+ >>>
+ >>> g = globals()
+ >>> n = 10000
+ >>> t1 = timeit("var = np.var(a, axis=1, mean=mean)", globals=g, number=n)
+ >>> t2 = timeit("var = np.var(a, axis=1)", globals=g, number=n)
+ >>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
+ #doctest: +SKIP
+ Percentage execution time saved 32%
+
+ """
+ kwargs = {}
+ if keepdims is not np._NoValue:
+ kwargs['keepdims'] = keepdims
+ if where is not np._NoValue:
+ kwargs['where'] = where
+ if mean is not np._NoValue:
+ kwargs['mean'] = mean
+
+ if correction != np._NoValue:
+ if ddof != 0:
+ raise ValueError(
+ "ddof and correction can't be provided simultaneously."
+ )
+ else:
+ ddof = correction
+
+ if type(a) is not mu.ndarray:
+ try:
+ var = a.var
+
+ except AttributeError:
+ pass
+ else:
+ return var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
+
+ return _methods._var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
+ **kwargs)
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/fromnumeric.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/fromnumeric.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..2a9762240e3d55afe2b506464a47575e50a66731
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/fromnumeric.pyi
@@ -0,0 +1,1735 @@
+# ruff: noqa: ANN401
+from _typeshed import Incomplete
+from collections.abc import Sequence
+from typing import (
+ Any,
+ Literal,
+ Never,
+ Protocol,
+ SupportsIndex,
+ TypeAlias,
+ TypedDict,
+ TypeVar,
+ Unpack,
+ overload,
+ type_check_only,
+)
+
+import numpy as np
+from numpy import (
+ _AnyShapeT,
+ _CastingKind,
+ _ModeKind,
+ _OrderACF,
+ _OrderKACF,
+ _PartitionKind,
+ _SortKind,
+ _SortSide,
+ complexfloating,
+ float16,
+ floating,
+ generic,
+ int64,
+ int_,
+ intp,
+ object_,
+ timedelta64,
+ uint64,
+)
+from numpy._globals import _NoValueType
+from numpy._typing import (
+ ArrayLike,
+ DTypeLike,
+ NDArray,
+ _AnyShape,
+ _ArrayLike,
+ _ArrayLikeBool_co,
+ _ArrayLikeComplex_co,
+ _ArrayLikeFloat_co,
+ _ArrayLikeInt,
+ _ArrayLikeInt_co,
+ _ArrayLikeObject_co,
+ _ArrayLikeUInt_co,
+ _BoolLike_co,
+ _ComplexLike_co,
+ _DTypeLike,
+ _IntLike_co,
+ _NestedSequence,
+ _NumberLike_co,
+ _ScalarLike_co,
+ _ShapeLike,
+)
+
+__all__ = [
+ "all",
+ "amax",
+ "amin",
+ "any",
+ "argmax",
+ "argmin",
+ "argpartition",
+ "argsort",
+ "around",
+ "choose",
+ "clip",
+ "compress",
+ "cumprod",
+ "cumsum",
+ "cumulative_prod",
+ "cumulative_sum",
+ "diagonal",
+ "mean",
+ "max",
+ "min",
+ "matrix_transpose",
+ "ndim",
+ "nonzero",
+ "partition",
+ "prod",
+ "ptp",
+ "put",
+ "ravel",
+ "repeat",
+ "reshape",
+ "resize",
+ "round",
+ "searchsorted",
+ "shape",
+ "size",
+ "sort",
+ "squeeze",
+ "std",
+ "sum",
+ "swapaxes",
+ "take",
+ "trace",
+ "transpose",
+ "var",
+]
+
+_ScalarT = TypeVar("_ScalarT", bound=generic)
+_NumberOrObjectT = TypeVar("_NumberOrObjectT", bound=np.number | np.object_)
+_ArrayT = TypeVar("_ArrayT", bound=np.ndarray[Any, Any])
+_ShapeT = TypeVar("_ShapeT", bound=tuple[int, ...])
+_ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], covariant=True)
+_BoolOrIntArrayT = TypeVar("_BoolOrIntArrayT", bound=NDArray[np.integer | np.bool])
+
+@type_check_only
+class _SupportsShape(Protocol[_ShapeT_co]):
+ # NOTE: it matters that `self` is positional only
+ @property
+ def shape(self, /) -> _ShapeT_co: ...
+
+@type_check_only
+class _UFuncKwargs(TypedDict, total=False):
+ where: _ArrayLikeBool_co | None
+ order: _OrderKACF
+ subok: bool
+ signature: str | tuple[str | None, ...]
+ casting: _CastingKind
+
+# a "sequence" that isn't a string, bytes, bytearray, or memoryview
+_T = TypeVar("_T")
+_PyArray: TypeAlias = list[_T] | tuple[_T, ...]
+# `int` also covers `bool`
+_PyScalar: TypeAlias = complex | bytes | str
+
+# TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
+@overload
+def take(
+ a: _ArrayLike[_ScalarT],
+ indices: _IntLike_co,
+ axis: None = None,
+ out: None = None,
+ mode: _ModeKind = "raise",
+) -> _ScalarT: ...
+@overload
+def take(
+ a: ArrayLike,
+ indices: _IntLike_co,
+ axis: SupportsIndex | None = None,
+ out: None = None,
+ mode: _ModeKind = "raise",
+) -> Any: ...
+@overload
+def take(
+ a: _ArrayLike[_ScalarT],
+ indices: _ArrayLikeInt_co,
+ axis: SupportsIndex | None = None,
+ out: None = None,
+ mode: _ModeKind = "raise",
+) -> NDArray[_ScalarT]: ...
+@overload
+def take(
+ a: ArrayLike,
+ indices: _ArrayLikeInt_co,
+ axis: SupportsIndex | None = None,
+ out: None = None,
+ mode: _ModeKind = "raise",
+) -> NDArray[Any]: ...
+@overload
+def take(
+ a: ArrayLike,
+ indices: _ArrayLikeInt_co,
+ axis: SupportsIndex | None,
+ out: _ArrayT,
+ mode: _ModeKind = "raise",
+) -> _ArrayT: ...
+@overload
+def take(
+ a: ArrayLike,
+ indices: _ArrayLikeInt_co,
+ axis: SupportsIndex | None = None,
+ *,
+ out: _ArrayT,
+ mode: _ModeKind = "raise",
+) -> _ArrayT: ...
+
+@overload
+def reshape( # shape: index
+ a: _ArrayLike[_ScalarT],
+ /,
+ shape: SupportsIndex,
+ order: _OrderACF = "C",
+ *,
+ copy: bool | None = None,
+) -> np.ndarray[tuple[int], np.dtype[_ScalarT]]: ...
+@overload
+def reshape( # shape: (int, ...) @ _AnyShapeT
+ a: _ArrayLike[_ScalarT],
+ /,
+ shape: _AnyShapeT,
+ order: _OrderACF = "C",
+ *,
+ copy: bool | None = None,
+) -> np.ndarray[_AnyShapeT, np.dtype[_ScalarT]]: ...
+@overload # shape: Sequence[index]
+def reshape(
+ a: _ArrayLike[_ScalarT],
+ /,
+ shape: Sequence[SupportsIndex],
+ order: _OrderACF = "C",
+ *,
+ copy: bool | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload # shape: index
+def reshape(
+ a: ArrayLike,
+ /,
+ shape: SupportsIndex,
+ order: _OrderACF = "C",
+ *,
+ copy: bool | None = None,
+) -> np.ndarray[tuple[int], np.dtype]: ...
+@overload
+def reshape( # shape: (int, ...) @ _AnyShapeT
+ a: ArrayLike,
+ /,
+ shape: _AnyShapeT,
+ order: _OrderACF = "C",
+ *,
+ copy: bool | None = None,
+) -> np.ndarray[_AnyShapeT, np.dtype]: ...
+@overload # shape: Sequence[index]
+def reshape(
+ a: ArrayLike,
+ /,
+ shape: Sequence[SupportsIndex],
+ order: _OrderACF = "C",
+ *,
+ copy: bool | None = None,
+) -> NDArray[Any]: ...
+
+@overload
+def choose(
+ a: _IntLike_co,
+ choices: ArrayLike,
+ out: None = None,
+ mode: _ModeKind = "raise",
+) -> Any: ...
+@overload
+def choose(
+ a: _ArrayLikeInt_co,
+ choices: _ArrayLike[_ScalarT],
+ out: None = None,
+ mode: _ModeKind = "raise",
+) -> NDArray[_ScalarT]: ...
+@overload
+def choose(
+ a: _ArrayLikeInt_co,
+ choices: ArrayLike,
+ out: None = None,
+ mode: _ModeKind = "raise",
+) -> NDArray[Any]: ...
+@overload
+def choose(
+ a: _ArrayLikeInt_co,
+ choices: ArrayLike,
+ out: _ArrayT,
+ mode: _ModeKind = "raise",
+) -> _ArrayT: ...
+
+# keep in sync with `ma.core.repeat`
+@overload
+def repeat(
+ a: _ArrayLike[_ScalarT],
+ repeats: _ArrayLikeInt_co,
+ axis: None = None,
+) -> np.ndarray[tuple[int], np.dtype[_ScalarT]]: ...
+@overload
+def repeat(
+ a: _ArrayLike[_ScalarT],
+ repeats: _ArrayLikeInt_co,
+ axis: SupportsIndex,
+) -> NDArray[_ScalarT]: ...
+@overload
+def repeat(
+ a: ArrayLike,
+ repeats: _ArrayLikeInt_co,
+ axis: None = None,
+) -> np.ndarray[tuple[int], np.dtype[Any]]: ...
+@overload
+def repeat(
+ a: ArrayLike,
+ repeats: _ArrayLikeInt_co,
+ axis: SupportsIndex,
+) -> NDArray[Any]: ...
+
+#
+def put(
+ a: NDArray[Any],
+ ind: _ArrayLikeInt_co,
+ v: ArrayLike,
+ mode: _ModeKind = "raise",
+) -> None: ...
+
+# keep in sync with `ndarray.swapaxes` and `ma.core.swapaxes`
+@overload
+def swapaxes(a: _ArrayT, axis1: SupportsIndex, axis2: SupportsIndex) -> _ArrayT: ...
+@overload
+def swapaxes(a: _ArrayLike[_ScalarT], axis1: SupportsIndex, axis2: SupportsIndex) -> NDArray[_ScalarT]: ...
+@overload
+def swapaxes(a: ArrayLike, axis1: SupportsIndex, axis2: SupportsIndex) -> NDArray[Any]: ...
+
+@overload
+def transpose(
+ a: _ArrayLike[_ScalarT],
+ axes: _ShapeLike | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def transpose(
+ a: ArrayLike,
+ axes: _ShapeLike | None = None,
+) -> NDArray[Any]: ...
+
+@overload
+def matrix_transpose(x: _ArrayLike[_ScalarT], /) -> NDArray[_ScalarT]: ...
+@overload
+def matrix_transpose(x: ArrayLike, /) -> NDArray[Any]: ...
+
+#
+@overload
+def partition(
+ a: _ArrayLike[_ScalarT],
+ kth: _ArrayLikeInt,
+ axis: SupportsIndex | None = -1,
+ kind: _PartitionKind = "introselect",
+ order: None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def partition(
+ a: _ArrayLike[np.void],
+ kth: _ArrayLikeInt,
+ axis: SupportsIndex | None = -1,
+ kind: _PartitionKind = "introselect",
+ order: str | Sequence[str] | None = None,
+) -> NDArray[np.void]: ...
+@overload
+def partition(
+ a: ArrayLike,
+ kth: _ArrayLikeInt,
+ axis: SupportsIndex | None = -1,
+ kind: _PartitionKind = "introselect",
+ order: str | Sequence[str] | None = None,
+) -> NDArray[Any]: ...
+
+#
+def argpartition(
+ a: ArrayLike,
+ kth: _ArrayLikeInt,
+ axis: SupportsIndex | None = -1,
+ kind: _PartitionKind = "introselect",
+ order: str | Sequence[str] | None = None,
+) -> NDArray[intp]: ...
+
+#
+@overload
+def sort(
+ a: _ArrayLike[_ScalarT],
+ axis: SupportsIndex | None = -1,
+ kind: _SortKind | None = None,
+ order: str | Sequence[str] | None = None,
+ *,
+ stable: bool | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def sort(
+ a: ArrayLike,
+ axis: SupportsIndex | None = -1,
+ kind: _SortKind | None = None,
+ order: str | Sequence[str] | None = None,
+ *,
+ stable: bool | None = None,
+) -> NDArray[Any]: ...
+
+def argsort(
+ a: ArrayLike,
+ axis: SupportsIndex | None = -1,
+ kind: _SortKind | None = None,
+ order: str | Sequence[str] | None = None,
+ *,
+ stable: bool | None = None,
+) -> NDArray[intp]: ...
+
+@overload
+def argmax(
+ a: ArrayLike,
+ axis: None = None,
+ out: None = None,
+ *,
+ keepdims: Literal[False] | _NoValueType = ...,
+) -> intp: ...
+@overload
+def argmax(
+ a: ArrayLike,
+ axis: SupportsIndex | None = None,
+ out: None = None,
+ *,
+ keepdims: bool | _NoValueType = ...,
+) -> Any: ...
+@overload
+def argmax(
+ a: ArrayLike,
+ axis: SupportsIndex | None,
+ out: _BoolOrIntArrayT,
+ *,
+ keepdims: bool | _NoValueType = ...,
+) -> _BoolOrIntArrayT: ...
+@overload
+def argmax(
+ a: ArrayLike,
+ axis: SupportsIndex | None = None,
+ *,
+ out: _BoolOrIntArrayT,
+ keepdims: bool | _NoValueType = ...,
+) -> _BoolOrIntArrayT: ...
+
+@overload
+def argmin(
+ a: ArrayLike,
+ axis: None = None,
+ out: None = None,
+ *,
+ keepdims: Literal[False] | _NoValueType = ...,
+) -> intp: ...
+@overload
+def argmin(
+ a: ArrayLike,
+ axis: SupportsIndex | None = None,
+ out: None = None,
+ *,
+ keepdims: bool | _NoValueType = ...,
+) -> Any: ...
+@overload
+def argmin(
+ a: ArrayLike,
+ axis: SupportsIndex | None,
+ out: _BoolOrIntArrayT,
+ *,
+ keepdims: bool | _NoValueType = ...,
+) -> _BoolOrIntArrayT: ...
+@overload
+def argmin(
+ a: ArrayLike,
+ axis: SupportsIndex | None = None,
+ *,
+ out: _BoolOrIntArrayT,
+ keepdims: bool | _NoValueType = ...,
+) -> _BoolOrIntArrayT: ...
+
+# TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
+@overload
+def searchsorted(
+ a: ArrayLike,
+ v: _ScalarLike_co,
+ side: _SortSide = "left",
+ sorter: _ArrayLikeInt_co | None = None, # 1D int array
+) -> intp: ...
+@overload
+def searchsorted(
+ a: ArrayLike,
+ v: ArrayLike,
+ side: _SortSide = "left",
+ sorter: _ArrayLikeInt_co | None = None, # 1D int array
+) -> NDArray[intp]: ...
+
+# TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
+@overload
+def resize(a: _ArrayLike[_ScalarT], new_shape: SupportsIndex | tuple[SupportsIndex]) -> np.ndarray[tuple[int], np.dtype[_ScalarT]]: ...
+@overload
+def resize(a: _ArrayLike[_ScalarT], new_shape: _AnyShapeT) -> np.ndarray[_AnyShapeT, np.dtype[_ScalarT]]: ...
+@overload
+def resize(a: _ArrayLike[_ScalarT], new_shape: _ShapeLike) -> NDArray[_ScalarT]: ...
+@overload
+def resize(a: ArrayLike, new_shape: SupportsIndex | tuple[SupportsIndex]) -> np.ndarray[tuple[int], np.dtype]: ...
+@overload
+def resize(a: ArrayLike, new_shape: _AnyShapeT) -> np.ndarray[_AnyShapeT, np.dtype]: ...
+@overload
+def resize(a: ArrayLike, new_shape: _ShapeLike) -> NDArray[Any]: ...
+
+# TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
+@overload
+def squeeze(
+ a: _ScalarT,
+ axis: _ShapeLike | None = None,
+) -> _ScalarT: ...
+@overload
+def squeeze(
+ a: _ArrayLike[_ScalarT],
+ axis: _ShapeLike | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def squeeze(
+ a: ArrayLike,
+ axis: _ShapeLike | None = None,
+) -> NDArray[Any]: ...
+
+# keep in sync with `ma.core.diagonal`
+@overload
+def diagonal(
+ a: _ArrayLike[_ScalarT],
+ offset: SupportsIndex = 0,
+ axis1: SupportsIndex = 0,
+ axis2: SupportsIndex = 1, # >= 2D array
+) -> NDArray[_ScalarT]: ...
+@overload
+def diagonal(
+ a: ArrayLike,
+ offset: SupportsIndex = 0,
+ axis1: SupportsIndex = 0,
+ axis2: SupportsIndex = 1, # >= 2D array
+) -> NDArray[Any]: ...
+
+# keep in sync with `ma.core.trace`
+@overload
+def trace(
+ a: ArrayLike, # >= 2D array
+ offset: SupportsIndex = 0,
+ axis1: SupportsIndex = 0,
+ axis2: SupportsIndex = 1,
+ dtype: DTypeLike | None = None,
+ out: None = None,
+) -> Any: ...
+@overload
+def trace(
+ a: ArrayLike, # >= 2D array
+ offset: SupportsIndex,
+ axis1: SupportsIndex,
+ axis2: SupportsIndex,
+ dtype: DTypeLike | None,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def trace(
+ a: ArrayLike, # >= 2D array
+ offset: SupportsIndex = 0,
+ axis1: SupportsIndex = 0,
+ axis2: SupportsIndex = 1,
+ dtype: DTypeLike | None = None,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+
+_Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarT]]
+
+@overload
+def ravel(a: _ArrayLike[_ScalarT], order: _OrderKACF = "C") -> _Array1D[_ScalarT]: ...
+@overload
+def ravel(a: bytes | _NestedSequence[bytes], order: _OrderKACF = "C") -> _Array1D[np.bytes_]: ...
+@overload
+def ravel(a: str | _NestedSequence[str], order: _OrderKACF = "C") -> _Array1D[np.str_]: ...
+@overload
+def ravel(a: bool | _NestedSequence[bool], order: _OrderKACF = "C") -> _Array1D[np.bool]: ...
+@overload
+def ravel(a: int | _NestedSequence[int], order: _OrderKACF = "C") -> _Array1D[np.int_ | Any]: ...
+@overload
+def ravel(a: float | _NestedSequence[float], order: _OrderKACF = "C") -> _Array1D[np.float64 | Any]: ...
+@overload
+def ravel(a: complex | _NestedSequence[complex], order: _OrderKACF = "C") -> _Array1D[np.complex128 | Any]: ...
+@overload
+def ravel(a: ArrayLike, order: _OrderKACF = "C") -> np.ndarray[tuple[int], np.dtype]: ...
+
+def nonzero(a: _ArrayLike[Any]) -> tuple[np.ndarray[tuple[int], np.dtype[intp]], ...]: ...
+
+# this prevents `Any` from being returned with Pyright
+@overload
+def shape(a: _SupportsShape[Never]) -> _AnyShape: ...
+@overload
+def shape(a: _SupportsShape[_ShapeT]) -> _ShapeT: ...
+@overload
+def shape(a: _PyScalar) -> tuple[()]: ...
+# `collections.abc.Sequence` can't be used hesre, since `bytes` and `str` are
+# subtypes of it, which would make the return types incompatible.
+@overload
+def shape(a: _PyArray[_PyScalar]) -> tuple[int]: ...
+@overload
+def shape(a: _PyArray[_PyArray[_PyScalar]]) -> tuple[int, int]: ...
+# this overload will be skipped by typecheckers that don't support PEP 688
+@overload
+def shape(a: memoryview | bytearray) -> tuple[int]: ...
+@overload
+def shape(a: ArrayLike) -> _AnyShape: ...
+
+@overload
+def compress(
+ condition: _ArrayLikeBool_co, # 1D bool array
+ a: _ArrayLike[_ScalarT],
+ axis: SupportsIndex | None = None,
+ out: None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def compress(
+ condition: _ArrayLikeBool_co, # 1D bool array
+ a: ArrayLike,
+ axis: SupportsIndex | None = None,
+ out: None = None,
+) -> NDArray[Any]: ...
+@overload
+def compress(
+ condition: _ArrayLikeBool_co, # 1D bool array
+ a: ArrayLike,
+ axis: SupportsIndex | None,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def compress(
+ condition: _ArrayLikeBool_co, # 1D bool array
+ a: ArrayLike,
+ axis: SupportsIndex | None = None,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+
+# TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
+@overload
+def clip(
+ a: _ScalarT,
+ a_min: ArrayLike | _NoValueType | None = ...,
+ a_max: ArrayLike | _NoValueType | None = ...,
+ out: None = None,
+ *,
+ min: ArrayLike | _NoValueType | None = ...,
+ max: ArrayLike | _NoValueType | None = ...,
+ dtype: None = None,
+ **kwargs: Unpack[_UFuncKwargs],
+) -> _ScalarT: ...
+@overload
+def clip(
+ a: _ScalarLike_co,
+ a_min: ArrayLike | _NoValueType | None = ...,
+ a_max: ArrayLike | _NoValueType | None = ...,
+ out: None = None,
+ *,
+ min: ArrayLike | _NoValueType | None = ...,
+ max: ArrayLike | _NoValueType | None = ...,
+ dtype: None = None,
+ **kwargs: Unpack[_UFuncKwargs],
+) -> Any: ...
+@overload
+def clip(
+ a: _ArrayLike[_ScalarT],
+ a_min: ArrayLike | _NoValueType | None = ...,
+ a_max: ArrayLike | _NoValueType | None = ...,
+ out: None = None,
+ *,
+ min: ArrayLike | _NoValueType | None = ...,
+ max: ArrayLike | _NoValueType | None = ...,
+ dtype: None = None,
+ **kwargs: Unpack[_UFuncKwargs],
+) -> NDArray[_ScalarT]: ...
+@overload
+def clip(
+ a: ArrayLike,
+ a_min: ArrayLike | _NoValueType | None = ...,
+ a_max: ArrayLike | _NoValueType | None = ...,
+ out: None = None,
+ *,
+ min: ArrayLike | _NoValueType | None = ...,
+ max: ArrayLike | _NoValueType | None = ...,
+ dtype: None = None,
+ **kwargs: Unpack[_UFuncKwargs],
+) -> NDArray[Any]: ...
+@overload
+def clip(
+ a: ArrayLike,
+ a_min: ArrayLike | None,
+ a_max: ArrayLike | None,
+ out: _ArrayT,
+ *,
+ min: ArrayLike | _NoValueType | None = ...,
+ max: ArrayLike | _NoValueType | None = ...,
+ dtype: DTypeLike | None = None,
+ **kwargs: Unpack[_UFuncKwargs],
+) -> _ArrayT: ...
+@overload
+def clip(
+ a: ArrayLike,
+ a_min: ArrayLike | _NoValueType | None = ...,
+ a_max: ArrayLike | _NoValueType | None = ...,
+ *,
+ out: _ArrayT,
+ min: ArrayLike | _NoValueType | None = ...,
+ max: ArrayLike | _NoValueType | None = ...,
+ dtype: DTypeLike | None = None,
+ **kwargs: Unpack[_UFuncKwargs],
+) -> _ArrayT: ...
+@overload
+def clip(
+ a: ArrayLike,
+ a_min: ArrayLike | _NoValueType | None = ...,
+ a_max: ArrayLike | _NoValueType | None = ...,
+ out: None = None,
+ *,
+ min: ArrayLike | _NoValueType | None = ...,
+ max: ArrayLike | _NoValueType | None = ...,
+ dtype: DTypeLike | None = None,
+ **kwargs: Unpack[_UFuncKwargs],
+) -> Any: ...
+
+@overload
+def sum(
+ a: _ArrayLike[_ScalarT],
+ axis: None = None,
+ dtype: None = None,
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def sum(
+ a: _ArrayLike[_ScalarT],
+ axis: None = None,
+ dtype: None = None,
+ out: None = None,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT | NDArray[_ScalarT]: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: None,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: None = None,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: _ShapeLike | None,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT | NDArray[_ScalarT]: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: _ShapeLike | None = None,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT | NDArray[_ScalarT]: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: _ShapeLike | None = None,
+ dtype: DTypeLike | None = None,
+ out: None = None,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> Any: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: _ShapeLike | None,
+ dtype: DTypeLike | None,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def sum(
+ a: ArrayLike,
+ axis: _ShapeLike | None = None,
+ dtype: DTypeLike | None = None,
+ *,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+
+# keep in sync with `any`
+@overload
+def all(
+ a: ArrayLike | None,
+ axis: None = None,
+ out: None = None,
+ keepdims: Literal[False, 0] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> np.bool: ...
+@overload
+def all(
+ a: ArrayLike | None,
+ axis: int | tuple[int, ...] | None = None,
+ out: None = None,
+ keepdims: _BoolLike_co | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> Incomplete: ...
+@overload
+def all(
+ a: ArrayLike | None,
+ axis: int | tuple[int, ...] | None,
+ out: _ArrayT,
+ keepdims: _BoolLike_co | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def all(
+ a: ArrayLike | None,
+ axis: int | tuple[int, ...] | None = None,
+ *,
+ out: _ArrayT,
+ keepdims: _BoolLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+
+# keep in sync with `all`
+@overload
+def any(
+ a: ArrayLike | None,
+ axis: None = None,
+ out: None = None,
+ keepdims: Literal[False, 0] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> np.bool: ...
+@overload
+def any(
+ a: ArrayLike | None,
+ axis: int | tuple[int, ...] | None = None,
+ out: None = None,
+ keepdims: _BoolLike_co | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> Incomplete: ...
+@overload
+def any(
+ a: ArrayLike | None,
+ axis: int | tuple[int, ...] | None,
+ out: _ArrayT,
+ keepdims: _BoolLike_co | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def any(
+ a: ArrayLike | None,
+ axis: int | tuple[int, ...] | None = None,
+ *,
+ out: _ArrayT,
+ keepdims: _BoolLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+
+#
+@overload
+def cumsum(
+ a: _ArrayLike[_ScalarT],
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def cumsum(
+ a: ArrayLike,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+) -> NDArray[Any]: ...
+@overload
+def cumsum(
+ a: ArrayLike,
+ axis: SupportsIndex | None,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def cumsum(
+ a: ArrayLike,
+ axis: SupportsIndex | None = None,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def cumsum(
+ a: ArrayLike,
+ axis: SupportsIndex | None = None,
+ dtype: DTypeLike | None = None,
+ out: None = None,
+) -> NDArray[Any]: ...
+@overload
+def cumsum(
+ a: ArrayLike,
+ axis: SupportsIndex | None,
+ dtype: DTypeLike | None,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def cumsum(
+ a: ArrayLike,
+ axis: SupportsIndex | None = None,
+ dtype: DTypeLike | None = None,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+
+@overload
+def cumulative_sum(
+ x: _ArrayLike[_ScalarT],
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+ include_initial: bool = False,
+) -> NDArray[_ScalarT]: ...
+@overload
+def cumulative_sum(
+ x: ArrayLike,
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+ include_initial: bool = False,
+) -> NDArray[Any]: ...
+@overload
+def cumulative_sum(
+ x: ArrayLike,
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ include_initial: bool = False,
+) -> NDArray[_ScalarT]: ...
+@overload
+def cumulative_sum(
+ x: ArrayLike,
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: DTypeLike | None = None,
+ out: None = None,
+ include_initial: bool = False,
+) -> NDArray[Any]: ...
+@overload
+def cumulative_sum(
+ x: ArrayLike,
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: DTypeLike | None = None,
+ out: _ArrayT,
+ include_initial: bool = False,
+) -> _ArrayT: ...
+
+@overload
+def ptp(
+ a: _ArrayLike[_ScalarT],
+ axis: None = None,
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def ptp(
+ a: ArrayLike,
+ axis: _ShapeLike | None = None,
+ out: None = None,
+ keepdims: bool | _NoValueType = ...,
+) -> Any: ...
+@overload
+def ptp(
+ a: ArrayLike,
+ axis: _ShapeLike | None,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def ptp(
+ a: ArrayLike,
+ axis: _ShapeLike | None = None,
+ *,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+) -> _ArrayT: ...
+
+@overload
+def amax(
+ a: _ArrayLike[_ScalarT],
+ axis: None = None,
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def amax(
+ a: ArrayLike,
+ axis: _ShapeLike | None = None,
+ out: None = None,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> Any: ...
+@overload
+def amax(
+ a: ArrayLike,
+ axis: _ShapeLike | None,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def amax(
+ a: ArrayLike,
+ axis: _ShapeLike | None = None,
+ *,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+
+@overload
+def amin(
+ a: _ArrayLike[_ScalarT],
+ axis: None = None,
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def amin(
+ a: ArrayLike,
+ axis: _ShapeLike | None = None,
+ out: None = None,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> Any: ...
+@overload
+def amin(
+ a: ArrayLike,
+ axis: _ShapeLike | None,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def amin(
+ a: ArrayLike,
+ axis: _ShapeLike | None = None,
+ *,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+
+# TODO: `np.prod()``: For object arrays `initial` does not necessarily
+# have to be a numerical scalar.
+# The only requirement is that it is compatible
+# with the `.__mul__()` method(s) of the passed array's elements.
+# Note that the same situation holds for all wrappers around
+# `np.ufunc.reduce`, e.g. `np.sum()` (`.__add__()`).
+# TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
+@overload
+def prod(
+ a: _ArrayLikeBool_co,
+ axis: None = None,
+ dtype: None = None,
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> int_: ...
+@overload
+def prod(
+ a: _ArrayLikeUInt_co,
+ axis: None = None,
+ dtype: None = None,
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> uint64: ...
+@overload
+def prod(
+ a: _ArrayLikeInt_co,
+ axis: None = None,
+ dtype: None = None,
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> int64: ...
+@overload
+def prod(
+ a: _ArrayLikeFloat_co,
+ axis: None = None,
+ dtype: None = None,
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> floating: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co,
+ axis: None = None,
+ dtype: None = None,
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> complexfloating: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = None,
+ dtype: None = None,
+ out: None = None,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> Any: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None = None,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = None,
+ dtype: DTypeLike | None = None,
+ out: None = None,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> Any: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None,
+ dtype: DTypeLike | None,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def prod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = None,
+ dtype: DTypeLike | None = None,
+ *,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+ initial: _NumberLike_co | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+
+# TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
+@overload
+def cumprod(
+ a: _ArrayLikeBool_co,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+) -> NDArray[int_]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeUInt_co,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+) -> NDArray[uint64]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeInt_co,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+) -> NDArray[int64]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeFloat_co,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+) -> NDArray[floating]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeComplex_co,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+) -> NDArray[complexfloating]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeObject_co,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+) -> NDArray[object_]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: SupportsIndex | None,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: SupportsIndex | None = None,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: SupportsIndex | None = None,
+ dtype: DTypeLike | None = None,
+ out: None = None,
+) -> NDArray[Any]: ...
+@overload
+def cumprod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: SupportsIndex | None,
+ dtype: DTypeLike | None,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def cumprod(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: SupportsIndex | None = None,
+ dtype: DTypeLike | None = None,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+
+# TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
+@overload
+def cumulative_prod(
+ x: _ArrayLikeBool_co,
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+ include_initial: bool = False,
+) -> NDArray[int_]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeUInt_co,
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+ include_initial: bool = False,
+) -> NDArray[uint64]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeInt_co,
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+ include_initial: bool = False,
+) -> NDArray[int64]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeFloat_co,
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+ include_initial: bool = False,
+) -> NDArray[floating]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeComplex_co,
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+ include_initial: bool = False,
+) -> NDArray[complexfloating]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeObject_co,
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: None = None,
+ out: None = None,
+ include_initial: bool = False,
+) -> NDArray[object_]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ include_initial: bool = False,
+) -> NDArray[_ScalarT]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: DTypeLike | None = None,
+ out: None = None,
+ include_initial: bool = False,
+) -> NDArray[Any]: ...
+@overload
+def cumulative_prod(
+ x: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ /,
+ *,
+ axis: SupportsIndex | None = None,
+ dtype: DTypeLike | None = None,
+ out: _ArrayT,
+ include_initial: bool = False,
+) -> _ArrayT: ...
+
+def ndim(a: ArrayLike) -> int: ...
+
+def size(a: ArrayLike, axis: int | tuple[int, ...] | None = None) -> int: ...
+
+# TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
+@overload
+def around(
+ a: _BoolLike_co,
+ decimals: SupportsIndex = 0,
+ out: None = None,
+) -> float16: ...
+@overload
+def around(
+ a: _NumberOrObjectT,
+ decimals: SupportsIndex = 0,
+ out: None = None,
+) -> _NumberOrObjectT: ...
+@overload
+def around(
+ a: _ComplexLike_co | object_,
+ decimals: SupportsIndex = 0,
+ out: None = None,
+) -> Any: ...
+@overload
+def around(
+ a: _ArrayLikeBool_co,
+ decimals: SupportsIndex = 0,
+ out: None = None,
+) -> NDArray[float16]: ...
+@overload
+def around(
+ a: _ArrayLike[_NumberOrObjectT],
+ decimals: SupportsIndex = 0,
+ out: None = None,
+) -> NDArray[_NumberOrObjectT]: ...
+@overload
+def around(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ decimals: SupportsIndex = 0,
+ out: None = None,
+) -> NDArray[Any]: ...
+@overload
+def around(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ decimals: SupportsIndex,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def around(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ decimals: SupportsIndex = 0,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+
+# TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
+@overload
+def mean(
+ a: _ArrayLikeFloat_co,
+ axis: None = None,
+ dtype: None = None,
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> floating: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co,
+ axis: None = None,
+ dtype: None = None,
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> complexfloating: ...
+@overload
+def mean(
+ a: _ArrayLike[np.timedelta64],
+ axis: None = None,
+ dtype: None = None,
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> timedelta64: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None,
+ dtype: DTypeLike | None,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = None,
+ dtype: DTypeLike | None = None,
+ *,
+ out: _ArrayT,
+ keepdims: bool | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None = None,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ keepdims: Literal[False] | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None,
+ dtype: _DTypeLike[_ScalarT],
+ out: None,
+ keepdims: Literal[True, 1],
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> NDArray[_ScalarT]: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ *,
+ keepdims: bool | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT | NDArray[_ScalarT]: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = None,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ keepdims: bool | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> _ScalarT | NDArray[_ScalarT]: ...
+@overload
+def mean(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = None,
+ dtype: DTypeLike | None = None,
+ out: None = None,
+ keepdims: bool | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+) -> Incomplete: ...
+
+@overload
+def std(
+ a: _ArrayLikeComplex_co,
+ axis: None = None,
+ dtype: None = None,
+ out: None = None,
+ ddof: float = 0,
+ keepdims: Literal[False] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> floating: ...
+@overload
+def std(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = None,
+ dtype: None = None,
+ out: None = None,
+ ddof: float = 0,
+ keepdims: bool | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> Any: ...
+@overload
+def std(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ ddof: float = 0,
+ keepdims: Literal[False] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def std(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None = None,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ ddof: float = 0,
+ keepdims: Literal[False] | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def std(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = None,
+ dtype: DTypeLike | None = None,
+ out: None = None,
+ ddof: float = 0,
+ keepdims: bool | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> Any: ...
+@overload
+def std(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None,
+ dtype: DTypeLike | None,
+ out: _ArrayT,
+ ddof: float = 0,
+ keepdims: bool | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def std(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = None,
+ dtype: DTypeLike | None = None,
+ *,
+ out: _ArrayT,
+ ddof: float = 0,
+ keepdims: bool | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _ArrayT: ...
+
+@overload
+def var(
+ a: _ArrayLikeComplex_co,
+ axis: None = None,
+ dtype: None = None,
+ out: None = None,
+ ddof: float = 0,
+ keepdims: Literal[False] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> floating: ...
+@overload
+def var(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = None,
+ dtype: None = None,
+ out: None = None,
+ ddof: float = 0,
+ keepdims: bool | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> Any: ...
+@overload
+def var(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ ddof: float = 0,
+ keepdims: Literal[False] | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def var(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: None = None,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ out: None = None,
+ ddof: float = 0,
+ keepdims: Literal[False] | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _ScalarT: ...
+@overload
+def var(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = None,
+ dtype: DTypeLike | None = None,
+ out: None = None,
+ ddof: float = 0,
+ keepdims: bool | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> Any: ...
+@overload
+def var(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None,
+ dtype: DTypeLike | None,
+ out: _ArrayT,
+ ddof: float = 0,
+ keepdims: bool | _NoValueType = ...,
+ *,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _ArrayT: ...
+@overload
+def var(
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+ axis: _ShapeLike | None = None,
+ dtype: DTypeLike | None = None,
+ *,
+ out: _ArrayT,
+ ddof: float = 0,
+ keepdims: bool | _NoValueType = ...,
+ where: _ArrayLikeBool_co | _NoValueType = ...,
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
+ correction: float | _NoValueType = ...,
+) -> _ArrayT: ...
+
+max = amax
+min = amin
+round = around
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/function_base.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/function_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fcc6b4f770a82e8f8127377d33017376533c45c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/function_base.py
@@ -0,0 +1,547 @@
+import functools
+import inspect
+import operator
+import types
+import warnings
+
+import numpy as np
+from numpy._core import overrides
+from numpy._core._multiarray_umath import _array_converter
+from numpy._core.multiarray import add_docstring
+
+from . import numeric as _nx
+from .numeric import asanyarray, nan, ndim, result_type
+
+__all__ = ['logspace', 'linspace', 'geomspace']
+
+
+array_function_dispatch = functools.partial(
+ overrides.array_function_dispatch, module='numpy')
+
+
+def _linspace_dispatcher(start, stop, num=None, endpoint=None, retstep=None,
+ dtype=None, axis=None, *, device=None):
+ return (start, stop)
+
+
+@array_function_dispatch(_linspace_dispatcher)
+def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,
+ axis=0, *, device=None):
+ """
+ Return evenly spaced numbers over a specified interval.
+
+ Returns `num` evenly spaced samples, calculated over the
+ interval [`start`, `stop`].
+
+ The endpoint of the interval can optionally be excluded.
+
+ .. versionchanged:: 1.20.0
+ Values are rounded towards ``-inf`` instead of ``0`` when an
+ integer ``dtype`` is specified. The old behavior can
+ still be obtained with ``np.linspace(start, stop, num).astype(int)``
+
+ Parameters
+ ----------
+ start : array_like
+ The starting value of the sequence.
+ stop : array_like
+ The end value of the sequence, unless `endpoint` is set to False.
+ In that case, the sequence consists of all but the last of ``num + 1``
+ evenly spaced samples, so that `stop` is excluded. Note that the step
+ size changes when `endpoint` is False.
+ num : int, optional
+ Number of samples to generate. Default is 50. Must be non-negative.
+ endpoint : bool, optional
+ If True, `stop` is the last sample. Otherwise, it is not included.
+ Default is True.
+ retstep : bool, optional
+ If True, return (`samples`, `step`), where `step` is the spacing
+ between samples.
+ dtype : dtype, optional
+ The type of the output array. If `dtype` is not given, the data type
+ is inferred from `start` and `stop`. The inferred dtype will never be
+ an integer; `float` is chosen even if the arguments would produce an
+ array of integers.
+ axis : int, optional
+ The axis in the result to store the samples. Relevant only if start
+ or stop are array-like. By default (0), the samples will be along a
+ new axis inserted at the beginning. Use -1 to get an axis at the end.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ samples : ndarray
+ There are `num` equally spaced samples in the closed interval
+ ``[start, stop]`` or the half-open interval ``[start, stop)``
+ (depending on whether `endpoint` is True or False).
+ step : float, optional
+ Only returned if `retstep` is True
+
+ Size of spacing between samples.
+
+
+ See Also
+ --------
+ arange : Similar to `linspace`, but uses a step size (instead of the
+ number of samples).
+ geomspace : Similar to `linspace`, but with numbers spaced evenly on a log
+ scale (a geometric progression).
+ logspace : Similar to `geomspace`, but with the end points specified as
+ logarithms.
+ :ref:`how-to-partition`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.linspace(2.0, 3.0, num=5)
+ array([2. , 2.25, 2.5 , 2.75, 3. ])
+ >>> np.linspace(2.0, 3.0, num=5, endpoint=False)
+ array([2. , 2.2, 2.4, 2.6, 2.8])
+ >>> np.linspace(2.0, 3.0, num=5, retstep=True)
+ (array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
+
+ Graphical illustration:
+
+ >>> import matplotlib.pyplot as plt
+ >>> N = 8
+ >>> y = np.zeros(N)
+ >>> x1 = np.linspace(0, 10, N, endpoint=True)
+ >>> x2 = np.linspace(0, 10, N, endpoint=False)
+ >>> plt.plot(x1, y, 'o')
+ []
+ >>> plt.plot(x2, y + 0.5, 'o')
+ []
+ >>> plt.ylim([-0.5, 1])
+ (-0.5, 1)
+ >>> plt.show()
+
+ """
+ num = operator.index(num)
+ if num < 0:
+ raise ValueError(
+ f"Number of samples, {num}, must be non-negative."
+ )
+ div = (num - 1) if endpoint else num
+
+ conv = _array_converter(start, stop)
+ start, stop = conv.as_arrays()
+ dt = conv.result_type(ensure_inexact=True)
+
+ if dtype is None:
+ dtype = dt
+ integer_dtype = False
+ else:
+ integer_dtype = _nx.issubdtype(dtype, _nx.integer)
+
+ # Use `dtype=type(dt)` to enforce a floating point evaluation:
+ delta = np.subtract(stop, start, dtype=type(dt))
+ y = _nx.arange(
+ 0, num, dtype=dt, device=device
+ ).reshape((-1,) + (1,) * ndim(delta))
+
+ # In-place multiplication y *= delta/div is faster, but prevents
+ # the multiplicant from overriding what class is produced, and thus
+ # prevents, e.g. use of Quantities, see gh-7142. Hence, we multiply
+ # in place only for standard scalar types.
+ if div > 0:
+ _mult_inplace = _nx.isscalar(delta)
+ step = delta / div
+ any_step_zero = (
+ step == 0 if _mult_inplace else _nx.asanyarray(step == 0).any())
+ if any_step_zero:
+ # Special handling for denormal numbers, gh-5437
+ y /= div
+ if _mult_inplace:
+ y *= delta
+ else:
+ y = y * delta
+ elif _mult_inplace:
+ y *= step
+ else:
+ y = y * step
+ else:
+ # sequences with 0 items or 1 item with endpoint=True (i.e. div <= 0)
+ # have an undefined step
+ step = nan
+ # Multiply with delta to allow possible override of output class.
+ y = y * delta
+
+ y += start
+
+ if endpoint and num > 1:
+ y[-1, ...] = stop
+
+ if axis != 0:
+ y = _nx.moveaxis(y, 0, axis)
+
+ if integer_dtype:
+ _nx.floor(y, out=y)
+
+ y = conv.wrap(y.astype(dtype, copy=False))
+ if retstep:
+ return y, step
+ else:
+ return y
+
+
+def _logspace_dispatcher(start, stop, num=None, endpoint=None, base=None,
+ dtype=None, axis=None):
+ return (start, stop, base)
+
+
+@array_function_dispatch(_logspace_dispatcher)
+def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None,
+ axis=0):
+ """
+ Return numbers spaced evenly on a log scale.
+
+ In linear space, the sequence starts at ``base ** start``
+ (`base` to the power of `start`) and ends with ``base ** stop``
+ (see `endpoint` below).
+
+ .. versionchanged:: 1.25.0
+ Non-scalar 'base` is now supported
+
+ Parameters
+ ----------
+ start : array_like
+ ``base ** start`` is the starting value of the sequence.
+ stop : array_like
+ ``base ** stop`` is the final value of the sequence, unless `endpoint`
+ is False. In that case, ``num + 1`` values are spaced over the
+ interval in log-space, of which all but the last (a sequence of
+ length `num`) are returned.
+ num : integer, optional
+ Number of samples to generate. Default is 50.
+ endpoint : boolean, optional
+ If true, `stop` is the last sample. Otherwise, it is not included.
+ Default is True.
+ base : array_like, optional
+ The base of the log space. The step size between the elements in
+ ``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
+ Default is 10.0.
+ dtype : dtype
+ The type of the output array. If `dtype` is not given, the data type
+ is inferred from `start` and `stop`. The inferred type will never be
+ an integer; `float` is chosen even if the arguments would produce an
+ array of integers.
+ axis : int, optional
+ The axis in the result to store the samples. Relevant only if start,
+ stop, or base are array-like. By default (0), the samples will be
+ along a new axis inserted at the beginning. Use -1 to get an axis at
+ the end.
+
+ Returns
+ -------
+ samples : ndarray
+ `num` samples, equally spaced on a log scale.
+
+ See Also
+ --------
+ arange : Similar to linspace, with the step size specified instead of the
+ number of samples. Note that, when used with a float endpoint, the
+ endpoint may or may not be included.
+ linspace : Similar to logspace, but with the samples uniformly distributed
+ in linear space, instead of log space.
+ geomspace : Similar to logspace, but with endpoints specified directly.
+ :ref:`how-to-partition`
+
+ Notes
+ -----
+ If base is a scalar, logspace is equivalent to the code
+
+ >>> y = np.linspace(start, stop, num=num, endpoint=endpoint)
+ ... # doctest: +SKIP
+ >>> power(base, y).astype(dtype)
+ ... # doctest: +SKIP
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.logspace(2.0, 3.0, num=4)
+ array([ 100. , 215.443469 , 464.15888336, 1000. ])
+ >>> np.logspace(2.0, 3.0, num=4, endpoint=False)
+ array([100. , 177.827941 , 316.22776602, 562.34132519])
+ >>> np.logspace(2.0, 3.0, num=4, base=2.0)
+ array([4. , 5.0396842 , 6.34960421, 8. ])
+ >>> np.logspace(2.0, 3.0, num=4, base=[2.0, 3.0], axis=-1)
+ array([[ 4. , 5.0396842 , 6.34960421, 8. ],
+ [ 9. , 12.98024613, 18.72075441, 27. ]])
+
+ Graphical illustration:
+
+ >>> import matplotlib.pyplot as plt
+ >>> N = 10
+ >>> x1 = np.logspace(0.1, 1, N, endpoint=True)
+ >>> x2 = np.logspace(0.1, 1, N, endpoint=False)
+ >>> y = np.zeros(N)
+ >>> plt.plot(x1, y, 'o')
+ []
+ >>> plt.plot(x2, y + 0.5, 'o')
+ []
+ >>> plt.ylim([-0.5, 1])
+ (-0.5, 1)
+ >>> plt.show()
+
+ """
+ if not isinstance(base, (float, int)) and np.ndim(base):
+ # If base is non-scalar, broadcast it with the others, since it
+ # may influence how axis is interpreted.
+ ndmax = np.broadcast(start, stop, base).ndim
+ start, stop, base = (
+ np.array(a, copy=None, subok=True, ndmin=ndmax)
+ for a in (start, stop, base)
+ )
+ base = np.expand_dims(base, axis=axis)
+ y = linspace(start, stop, num=num, endpoint=endpoint, axis=axis)
+ if dtype is None:
+ return _nx.power(base, y)
+ return _nx.power(base, y).astype(dtype, copy=False)
+
+
+def _geomspace_dispatcher(start, stop, num=None, endpoint=None, dtype=None,
+ axis=None):
+ return (start, stop)
+
+
+@array_function_dispatch(_geomspace_dispatcher)
+def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):
+ """
+ Return numbers spaced evenly on a log scale (a geometric progression).
+
+ This is similar to `logspace`, but with endpoints specified directly.
+ Each output sample is a constant multiple of the previous.
+
+ Parameters
+ ----------
+ start : array_like
+ The starting value of the sequence.
+ stop : array_like
+ The final value of the sequence, unless `endpoint` is False.
+ In that case, ``num + 1`` values are spaced over the
+ interval in log-space, of which all but the last (a sequence of
+ length `num`) are returned.
+ num : integer, optional
+ Number of samples to generate. Default is 50.
+ endpoint : boolean, optional
+ If true, `stop` is the last sample. Otherwise, it is not included.
+ Default is True.
+ dtype : dtype
+ The type of the output array. If `dtype` is not given, the data type
+ is inferred from `start` and `stop`. The inferred dtype will never be
+ an integer; `float` is chosen even if the arguments would produce an
+ array of integers.
+ axis : int, optional
+ The axis in the result to store the samples. Relevant only if start
+ or stop are array-like. By default (0), the samples will be along a
+ new axis inserted at the beginning. Use -1 to get an axis at the end.
+
+ Returns
+ -------
+ samples : ndarray
+ `num` samples, equally spaced on a log scale.
+
+ See Also
+ --------
+ logspace : Similar to geomspace, but with endpoints specified using log
+ and base.
+ linspace : Similar to geomspace, but with arithmetic instead of geometric
+ progression.
+ arange : Similar to linspace, with the step size specified instead of the
+ number of samples.
+ :ref:`how-to-partition`
+
+ Notes
+ -----
+ If the inputs or dtype are complex, the output will follow a logarithmic
+ spiral in the complex plane. (There are an infinite number of spirals
+ passing through two points; the output will follow the shortest such path.)
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.geomspace(1, 1000, num=4)
+ array([ 1., 10., 100., 1000.])
+ >>> np.geomspace(1, 1000, num=3, endpoint=False)
+ array([ 1., 10., 100.])
+ >>> np.geomspace(1, 1000, num=4, endpoint=False)
+ array([ 1. , 5.62341325, 31.6227766 , 177.827941 ])
+ >>> np.geomspace(1, 256, num=9)
+ array([ 1., 2., 4., 8., 16., 32., 64., 128., 256.])
+
+ Note that the above may not produce exact integers:
+
+ >>> np.geomspace(1, 256, num=9, dtype=int)
+ array([ 1, 2, 4, 7, 16, 32, 63, 127, 256])
+ >>> np.around(np.geomspace(1, 256, num=9)).astype(int)
+ array([ 1, 2, 4, 8, 16, 32, 64, 128, 256])
+
+ Negative, decreasing, and complex inputs are allowed:
+
+ >>> np.geomspace(1000, 1, num=4)
+ array([1000., 100., 10., 1.])
+ >>> np.geomspace(-1000, -1, num=4)
+ array([-1000., -100., -10., -1.])
+ >>> np.geomspace(1j, 1000j, num=4) # Straight line
+ array([0. +1.j, 0. +10.j, 0. +100.j, 0.+1000.j])
+ >>> np.geomspace(-1+0j, 1+0j, num=5) # Circle
+ array([-1.00000000e+00+1.22464680e-16j, -7.07106781e-01+7.07106781e-01j,
+ 6.12323400e-17+1.00000000e+00j, 7.07106781e-01+7.07106781e-01j,
+ 1.00000000e+00+0.00000000e+00j])
+
+ Graphical illustration of `endpoint` parameter:
+
+ >>> import matplotlib.pyplot as plt
+ >>> N = 10
+ >>> y = np.zeros(N)
+ >>> plt.semilogx(np.geomspace(1, 1000, N, endpoint=True), y + 1, 'o')
+ []
+ >>> plt.semilogx(np.geomspace(1, 1000, N, endpoint=False), y + 2, 'o')
+ []
+ >>> plt.axis([0.5, 2000, 0, 3])
+ [0.5, 2000, 0, 3]
+ >>> plt.grid(True, color='0.7', linestyle='-', which='both', axis='both')
+ >>> plt.show()
+
+ """
+ start = asanyarray(start)
+ stop = asanyarray(stop)
+ if _nx.any(start == 0) or _nx.any(stop == 0):
+ raise ValueError('Geometric sequence cannot include zero')
+
+ dt = result_type(start, stop, float(num), _nx.zeros((), dtype))
+ if dtype is None:
+ dtype = dt
+ else:
+ # complex to dtype('complex128'), for instance
+ dtype = _nx.dtype(dtype)
+
+ # Promote both arguments to the same dtype in case, for instance, one is
+ # complex and another is negative and log would produce NaN otherwise.
+ # Copy since we may change things in-place further down.
+ start = start.astype(dt, copy=True)
+ stop = stop.astype(dt, copy=True)
+
+ # Allow negative real values and ensure a consistent result for complex
+ # (including avoiding negligible real or imaginary parts in output) by
+ # rotating start to positive real, calculating, then undoing rotation.
+ out_sign = _nx.sign(start)
+ start /= out_sign
+ stop = stop / out_sign
+
+ log_start = _nx.log10(start)
+ log_stop = _nx.log10(stop)
+ result = logspace(log_start, log_stop, num=num,
+ endpoint=endpoint, base=10.0, dtype=dt)
+
+ # Make sure the endpoints match the start and stop arguments. This is
+ # necessary because np.exp(np.log(x)) is not necessarily equal to x.
+ if num > 0:
+ result[0] = start
+ if num > 1 and endpoint:
+ result[-1] = stop
+
+ result *= out_sign
+
+ if axis != 0:
+ result = _nx.moveaxis(result, 0, axis)
+
+ return result.astype(dtype, copy=False)
+
+
+def _needs_add_docstring(obj):
+ """
+ Returns true if the only way to set the docstring of `obj` from python is
+ via add_docstring.
+
+ This function errs on the side of being overly conservative.
+ """
+ Py_TPFLAGS_HEAPTYPE = 1 << 9
+
+ if isinstance(obj, (types.FunctionType, types.MethodType, property)):
+ return False
+
+ if isinstance(obj, type) and obj.__flags__ & Py_TPFLAGS_HEAPTYPE:
+ return False
+
+ return True
+
+
+def _add_docstring(obj, doc, warn_on_python):
+ if warn_on_python and not _needs_add_docstring(obj):
+ warnings.warn(
+ f"add_newdoc was used on a pure-python object {obj}. "
+ "Prefer to attach it directly to the source.",
+ UserWarning,
+ stacklevel=3)
+
+ doc = inspect.cleandoc(doc)
+
+ try:
+ add_docstring(obj, doc)
+ except Exception:
+ pass
+
+
+def add_newdoc(place, obj, doc, warn_on_python=True):
+ """
+ Add documentation to an existing object, typically one defined in C
+
+ The purpose is to allow easier editing of the docstrings without requiring
+ a re-compile. This exists primarily for internal use within numpy itself.
+
+ Parameters
+ ----------
+ place : str
+ The absolute name of the module to import from
+ obj : str | None
+ The name of the object to add documentation to, typically a class or
+ function name.
+ doc : str | tuple[str, str] | list[tuple[str, str]]
+ If a string, the documentation to apply to `obj`
+
+ If a tuple, then the first element is interpreted as an attribute
+ of `obj` and the second as the docstring to apply -
+ ``(method, docstring)``
+
+ If a list, then each element of the list should be a tuple of length
+ two - ``[(method1, docstring1), (method2, docstring2), ...]``
+ warn_on_python : bool
+ If True, the default, emit `UserWarning` if this is used to attach
+ documentation to a pure-python object.
+
+ Notes
+ -----
+ This routine never raises an error if the docstring can't be written, but
+ will raise an error if the object being documented does not exist.
+
+ This routine cannot modify read-only docstrings, as appear
+ in new-style classes or built-in functions. Because this
+ routine never raises an error the caller must check manually
+ that the docstrings were changed.
+
+ Since this function grabs the ``char *`` from a c-level str object and puts
+ it into the ``tp_doc`` slot of the type of `obj`, it violates a number of
+ C-API best-practices, by:
+
+ - modifying a `PyTypeObject` after calling `PyType_Ready`
+ - calling `Py_INCREF` on the str and losing the reference, so the str
+ will never be released
+
+ If possible it should be avoided.
+ """
+ new = getattr(__import__(place, globals(), {}, [obj]), obj)
+ if isinstance(doc, str):
+ if "${ARRAY_FUNCTION_LIKE}" in doc:
+ doc = overrides.get_array_function_like_doc(new, doc)
+ _add_docstring(new, doc, warn_on_python)
+ elif isinstance(doc, tuple):
+ attr, docstring = doc
+ _add_docstring(getattr(new, attr), docstring, warn_on_python)
+ elif isinstance(doc, list):
+ for attr, docstring in doc:
+ _add_docstring(getattr(new, attr), docstring, warn_on_python)
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/function_base.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/function_base.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..19e1238c4e1538cfa97cad9b32839b04ef705c72
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/function_base.pyi
@@ -0,0 +1,276 @@
+from _typeshed import Incomplete
+from typing import Literal as L, SupportsIndex, TypeAlias, TypeVar, overload
+
+import numpy as np
+from numpy._typing import (
+ DTypeLike,
+ NDArray,
+ _ArrayLikeComplex_co,
+ _ArrayLikeFloat_co,
+ _DTypeLike,
+)
+from numpy._typing._array_like import _DualArrayLike
+
+__all__ = ["geomspace", "linspace", "logspace"]
+
+_ScalarT = TypeVar("_ScalarT", bound=np.generic)
+
+_ToArrayFloat64: TypeAlias = _DualArrayLike[np.dtype[np.float64 | np.integer | np.bool], float]
+
+@overload
+def linspace(
+ start: _ToArrayFloat64,
+ stop: _ToArrayFloat64,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ retstep: L[False] = False,
+ dtype: None = None,
+ axis: SupportsIndex = 0,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[np.float64]: ...
+@overload
+def linspace(
+ start: _ArrayLikeFloat_co,
+ stop: _ArrayLikeFloat_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ retstep: L[False] = False,
+ dtype: None = None,
+ axis: SupportsIndex = 0,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[np.floating]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ retstep: L[False] = False,
+ dtype: None = None,
+ axis: SupportsIndex = 0,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[np.complexfloating]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex,
+ endpoint: bool,
+ retstep: L[False],
+ dtype: _DTypeLike[_ScalarT],
+ axis: SupportsIndex = 0,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ retstep: L[False] = False,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ axis: SupportsIndex = 0,
+ device: L["cpu"] | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ retstep: L[False] = False,
+ dtype: DTypeLike | None = None,
+ axis: SupportsIndex = 0,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[Incomplete]: ...
+@overload
+def linspace(
+ start: _ToArrayFloat64,
+ stop: _ToArrayFloat64,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ *,
+ retstep: L[True],
+ dtype: None = None,
+ axis: SupportsIndex = 0,
+ device: L["cpu"] | None = None,
+) -> tuple[NDArray[np.float64], np.float64]: ...
+@overload
+def linspace(
+ start: _ArrayLikeFloat_co,
+ stop: _ArrayLikeFloat_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ *,
+ retstep: L[True],
+ dtype: None = None,
+ axis: SupportsIndex = 0,
+ device: L["cpu"] | None = None,
+) -> tuple[NDArray[np.floating], np.floating]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ *,
+ retstep: L[True],
+ dtype: None = None,
+ axis: SupportsIndex = 0,
+ device: L["cpu"] | None = None,
+) -> tuple[NDArray[np.complexfloating], np.complexfloating]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ *,
+ retstep: L[True],
+ dtype: _DTypeLike[_ScalarT],
+ axis: SupportsIndex = 0,
+ device: L["cpu"] | None = None,
+) -> tuple[NDArray[_ScalarT], _ScalarT]: ...
+@overload
+def linspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ *,
+ retstep: L[True],
+ dtype: DTypeLike | None = None,
+ axis: SupportsIndex = 0,
+ device: L["cpu"] | None = None,
+) -> tuple[NDArray[Incomplete], Incomplete]: ...
+
+@overload
+def logspace(
+ start: _ToArrayFloat64,
+ stop: _ToArrayFloat64,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ base: _ToArrayFloat64 = 10.0,
+ dtype: None = None,
+ axis: SupportsIndex = 0,
+) -> NDArray[np.float64]: ...
+@overload
+def logspace(
+ start: _ArrayLikeFloat_co,
+ stop: _ArrayLikeFloat_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ base: _ArrayLikeFloat_co = 10.0,
+ dtype: None = None,
+ axis: SupportsIndex = 0,
+) -> NDArray[np.floating]: ...
+@overload
+def logspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ base: _ArrayLikeComplex_co = 10.0,
+ dtype: None = None,
+ axis: SupportsIndex = 0,
+) -> NDArray[np.complexfloating]: ...
+@overload
+def logspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex,
+ endpoint: bool,
+ base: _ArrayLikeComplex_co,
+ dtype: _DTypeLike[_ScalarT],
+ axis: SupportsIndex = 0,
+) -> NDArray[_ScalarT]: ...
+@overload
+def logspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ base: _ArrayLikeComplex_co = 10.0,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ axis: SupportsIndex = 0,
+) -> NDArray[_ScalarT]: ...
+@overload
+def logspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ base: _ArrayLikeComplex_co = 10.0,
+ dtype: DTypeLike | None = None,
+ axis: SupportsIndex = 0,
+) -> NDArray[Incomplete]: ...
+
+@overload
+def geomspace(
+ start: _ToArrayFloat64,
+ stop: _ToArrayFloat64,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ dtype: None = None,
+ axis: SupportsIndex = 0,
+) -> NDArray[np.float64]: ...
+@overload
+def geomspace(
+ start: _ArrayLikeFloat_co,
+ stop: _ArrayLikeFloat_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ dtype: None = None,
+ axis: SupportsIndex = 0,
+) -> NDArray[np.floating]: ...
+@overload
+def geomspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ dtype: None = None,
+ axis: SupportsIndex = 0,
+) -> NDArray[np.complexfloating]: ...
+@overload
+def geomspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex,
+ endpoint: bool,
+ dtype: _DTypeLike[_ScalarT],
+ axis: SupportsIndex = 0,
+) -> NDArray[_ScalarT]: ...
+@overload
+def geomspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ axis: SupportsIndex = 0,
+) -> NDArray[_ScalarT]: ...
+@overload
+def geomspace(
+ start: _ArrayLikeComplex_co,
+ stop: _ArrayLikeComplex_co,
+ num: SupportsIndex = 50,
+ endpoint: bool = True,
+ dtype: DTypeLike | None = None,
+ axis: SupportsIndex = 0,
+) -> NDArray[Incomplete]: ...
+
+def add_newdoc(
+ place: str,
+ obj: str,
+ doc: str | tuple[str, str] | list[tuple[str, str]],
+ warn_on_python: bool = True,
+) -> None: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/getlimits.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/getlimits.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c03d81165fb175ad1e8603e399eea62a8bf5114
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/getlimits.py
@@ -0,0 +1,462 @@
+"""Machine limits for Float32 and Float64 and (long double) if available...
+
+"""
+__all__ = ['finfo', 'iinfo']
+
+import math
+import types
+import warnings
+from functools import cached_property
+
+from numpy._utils import set_module
+
+from . import numeric, numerictypes as ntypes
+from ._multiarray_umath import _populate_finfo_constants
+
+
+def _fr0(a):
+ """fix rank-0 --> rank-1"""
+ if a.ndim == 0:
+ a = a.copy()
+ a.shape = (1,)
+ return a
+
+
+def _fr1(a):
+ """fix rank > 0 --> rank-0"""
+ if a.size == 1:
+ a = a.copy()
+ a.shape = ()
+ return a
+
+
+_convert_to_float = {
+ ntypes.csingle: ntypes.single,
+ ntypes.complex128: ntypes.float64,
+ ntypes.clongdouble: ntypes.longdouble
+ }
+
+# Parameters for creating MachAr / MachAr-like objects
+_title_fmt = 'numpy {} precision floating point number'
+_MACHAR_PARAMS = {
+ ntypes.double: {
+ 'itype': ntypes.int64,
+ 'fmt': '%24.16e',
+ 'title': _title_fmt.format('double')},
+ ntypes.single: {
+ 'itype': ntypes.int32,
+ 'fmt': '%15.7e',
+ 'title': _title_fmt.format('single')},
+ ntypes.longdouble: {
+ 'itype': ntypes.longlong,
+ 'fmt': '%s',
+ 'title': _title_fmt.format('long double')},
+ ntypes.half: {
+ 'itype': ntypes.int16,
+ 'fmt': '%12.5e',
+ 'title': _title_fmt.format('half')}}
+
+
+@set_module('numpy')
+class finfo:
+ """
+ finfo(dtype)
+
+ Machine limits for floating point types.
+
+ Attributes
+ ----------
+ bits : int
+ The number of bits occupied by the type.
+ dtype : dtype
+ Returns the dtype for which `finfo` returns information. For complex
+ input, the returned dtype is the associated ``float*`` dtype for its
+ real and complex components.
+ eps : float
+ The difference between 1.0 and the next smallest representable float
+ larger than 1.0. For example, for 64-bit binary floats in the IEEE-754
+ standard, ``eps = 2**-52``, approximately 2.22e-16.
+ epsneg : float
+ The difference between 1.0 and the next smallest representable float
+ less than 1.0. For example, for 64-bit binary floats in the IEEE-754
+ standard, ``epsneg = 2**-53``, approximately 1.11e-16.
+ iexp : int
+ The number of bits in the exponent portion of the floating point
+ representation.
+ machep : int
+ The exponent that yields `eps`.
+ max : floating point number of the appropriate type
+ The largest representable number.
+ maxexp : int
+ The smallest positive power of the base (2) that causes overflow.
+ Corresponds to the C standard MAX_EXP.
+ min : floating point number of the appropriate type
+ The smallest representable number, typically ``-max``.
+ minexp : int
+ The most negative power of the base (2) consistent with there
+ being no leading 0's in the mantissa. Corresponds to the C
+ standard MIN_EXP - 1.
+ negep : int
+ The exponent that yields `epsneg`.
+ nexp : int
+ The number of bits in the exponent including its sign and bias.
+ nmant : int
+ The number of explicit bits in the mantissa (excluding the implicit
+ leading bit for normalized numbers).
+ precision : int
+ The approximate number of decimal digits to which this kind of
+ float is precise.
+ resolution : floating point number of the appropriate type
+ The approximate decimal resolution of this type, i.e.,
+ ``10**-precision``.
+ tiny : float
+ An alias for `smallest_normal`, kept for backwards compatibility.
+ smallest_normal : float
+ The smallest positive floating point number with 1 as leading bit in
+ the mantissa following IEEE-754 (see Notes).
+ smallest_subnormal : float
+ The smallest positive floating point number with 0 as leading bit in
+ the mantissa following IEEE-754.
+
+ Parameters
+ ----------
+ dtype : float, dtype, or instance
+ Kind of floating point or complex floating point
+ data-type about which to get information.
+
+ See Also
+ --------
+ iinfo : The equivalent for integer data types.
+ spacing : The distance between a value and the nearest adjacent number
+ nextafter : The next floating point value after x1 towards x2
+
+ Notes
+ -----
+ For developers of NumPy: do not instantiate this at the module level.
+ The initial calculation of these parameters is expensive and negatively
+ impacts import times. These objects are cached, so calling ``finfo()``
+ repeatedly inside your functions is not a problem.
+
+ Note that ``smallest_normal`` is not actually the smallest positive
+ representable value in a NumPy floating point type. As in the IEEE-754
+ standard [1]_, NumPy floating point types make use of subnormal numbers to
+ fill the gap between 0 and ``smallest_normal``. However, subnormal numbers
+ may have significantly reduced precision [2]_.
+
+ For ``longdouble``, the representation varies across platforms. On most
+ platforms it is IEEE 754 binary128 (quad precision) or binary64-extended
+ (80-bit extended precision). On PowerPC systems, it may use the IBM
+ double-double format (a pair of float64 values), which has special
+ characteristics for precision and range.
+
+ This function can also be used for complex data types as well. If used,
+ the output will be the same as the corresponding real float type
+ (e.g. numpy.finfo(numpy.csingle) is the same as numpy.finfo(numpy.single)).
+ However, the output is true for the real and imaginary components.
+
+ References
+ ----------
+ .. [1] IEEE Standard for Floating-Point Arithmetic, IEEE Std 754-2008,
+ pp.1-70, 2008, https://doi.org/10.1109/IEEESTD.2008.4610935
+ .. [2] Wikipedia, "Denormal Numbers",
+ https://en.wikipedia.org/wiki/Denormal_number
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.finfo(np.float64).dtype
+ dtype('float64')
+ >>> np.finfo(np.complex64).dtype
+ dtype('float32')
+
+ """
+
+ _finfo_cache = {}
+
+ __class_getitem__ = classmethod(types.GenericAlias)
+
+ def __new__(cls, dtype):
+ try:
+ obj = cls._finfo_cache.get(dtype) # most common path
+ if obj is not None:
+ return obj
+ except TypeError:
+ pass
+
+ if dtype is None:
+ # Deprecated in NumPy 1.25, 2023-01-16
+ warnings.warn(
+ "finfo() dtype cannot be None. This behavior will "
+ "raise an error in the future. (Deprecated in NumPy 1.25)",
+ DeprecationWarning,
+ stacklevel=2
+ )
+
+ try:
+ dtype = numeric.dtype(dtype)
+ except TypeError:
+ # In case a float instance was given
+ dtype = numeric.dtype(type(dtype))
+
+ obj = cls._finfo_cache.get(dtype)
+ if obj is not None:
+ return obj
+ dtypes = [dtype]
+ newdtype = ntypes.obj2sctype(dtype)
+ if newdtype is not dtype:
+ dtypes.append(newdtype)
+ dtype = newdtype
+ if not issubclass(dtype, numeric.inexact):
+ raise ValueError(f"data type {dtype!r} not inexact")
+ obj = cls._finfo_cache.get(dtype)
+ if obj is not None:
+ return obj
+ if not issubclass(dtype, numeric.floating):
+ newdtype = _convert_to_float[dtype]
+ if newdtype is not dtype:
+ # dtype changed, for example from complex128 to float64
+ dtypes.append(newdtype)
+ dtype = newdtype
+
+ obj = cls._finfo_cache.get(dtype, None)
+ if obj is not None:
+ # the original dtype was not in the cache, but the new
+ # dtype is in the cache. we add the original dtypes to
+ # the cache and return the result
+ for dt in dtypes:
+ cls._finfo_cache[dt] = obj
+ return obj
+ obj = object.__new__(cls)._init(dtype)
+ for dt in dtypes:
+ cls._finfo_cache[dt] = obj
+ return obj
+
+ def _init(self, dtype):
+ self.dtype = numeric.dtype(dtype)
+ self.bits = self.dtype.itemsize * 8
+ self._fmt = None
+ self._repr = None
+ _populate_finfo_constants(self, self.dtype)
+ return self
+
+ @cached_property
+ def epsneg(self):
+ # Assume typical floating point logic. Could also use nextafter.
+ return self.eps / self._radix
+
+ @cached_property
+ def resolution(self):
+ return self.dtype.type(10)**-self.precision
+
+ @cached_property
+ def machep(self):
+ return int(math.log2(self.eps))
+
+ @cached_property
+ def negep(self):
+ return int(math.log2(self.epsneg))
+
+ @cached_property
+ def nexp(self):
+ # considering all ones (inf/nan) and all zeros (subnormal/zero)
+ return math.ceil(math.log2(self.maxexp - self.minexp + 2))
+
+ @cached_property
+ def iexp(self):
+ # Calculate exponent bits from it's range:
+ return math.ceil(math.log2(self.maxexp - self.minexp))
+
+ def __str__(self):
+ if (fmt := getattr(self, "_fmt", None)) is not None:
+ return fmt
+
+ def get_str(name, pad=None):
+ if (val := getattr(self, name, None)) is None:
+ return ""
+ if pad is not None:
+ s = str(val).ljust(pad)
+ return str(val)
+
+ precision = get_str("precision", 3)
+ machep = get_str("machep", 6)
+ negep = get_str("negep", 6)
+ minexp = get_str("minexp", 6)
+ maxexp = get_str("maxexp", 6)
+ resolution = get_str("resolution")
+ eps = get_str("eps")
+ epsneg = get_str("epsneg")
+ tiny = get_str("tiny")
+ smallest_normal = get_str("smallest_normal")
+ smallest_subnormal = get_str("smallest_subnormal")
+ nexp = get_str("nexp", 6)
+ max_ = get_str("max")
+ if hasattr(self, "min") and hasattr(self, "max") and -self.min == self.max:
+ min_ = "-max"
+ else:
+ min_ = get_str("min")
+
+ fmt = (
+ f'Machine parameters for {self.dtype}\n'
+ f'---------------------------------------------------------------\n'
+ f'precision = {precision} resolution = {resolution}\n'
+ f'machep = {machep} eps = {eps}\n'
+ f'negep = {negep} epsneg = {epsneg}\n'
+ f'minexp = {minexp} tiny = {tiny}\n'
+ f'maxexp = {maxexp} max = {max_}\n'
+ f'nexp = {nexp} min = {min_}\n'
+ f'smallest_normal = {smallest_normal} '
+ f'smallest_subnormal = {smallest_subnormal}\n'
+ f'---------------------------------------------------------------\n'
+ )
+ self._fmt = fmt
+ return fmt
+
+ def __repr__(self):
+ if (repr_str := getattr(self, "_repr", None)) is not None:
+ return repr_str
+
+ c = self.__class__.__name__
+
+ # Use precision+1 digits in exponential notation
+ fmt_str = _MACHAR_PARAMS.get(self.dtype.type, {}).get('fmt', '%s')
+ if fmt_str != '%s' and hasattr(self, 'max') and hasattr(self, 'min'):
+ max_str = (fmt_str % self.max).strip()
+ min_str = (fmt_str % self.min).strip()
+ else:
+ max_str = str(self.max)
+ min_str = str(self.min)
+
+ resolution_str = str(self.resolution)
+
+ repr_str = (f"{c}(resolution={resolution_str}, min={min_str},"
+ f" max={max_str}, dtype={self.dtype})")
+ self._repr = repr_str
+ return repr_str
+
+ @cached_property
+ def tiny(self):
+ """Return the value for tiny, alias of smallest_normal.
+
+ Returns
+ -------
+ tiny : float
+ Value for the smallest normal, alias of smallest_normal.
+
+ Warns
+ -----
+ UserWarning
+ If the calculated value for the smallest normal is requested for
+ double-double.
+ """
+ return self.smallest_normal
+
+
+@set_module('numpy')
+class iinfo:
+ """
+ iinfo(type)
+
+ Machine limits for integer types.
+
+ Attributes
+ ----------
+ bits : int
+ The number of bits occupied by the type.
+ dtype : dtype
+ Returns the dtype for which `iinfo` returns information.
+ min : int
+ The smallest integer expressible by the type.
+ max : int
+ The largest integer expressible by the type.
+
+ Parameters
+ ----------
+ int_type : integer type, dtype, or instance
+ The kind of integer data type to get information about.
+
+ See Also
+ --------
+ finfo : The equivalent for floating point data types.
+
+ Examples
+ --------
+ With types:
+
+ >>> import numpy as np
+ >>> ii16 = np.iinfo(np.int16)
+ >>> ii16.min
+ -32768
+ >>> ii16.max
+ 32767
+ >>> ii32 = np.iinfo(np.int32)
+ >>> ii32.min
+ -2147483648
+ >>> ii32.max
+ 2147483647
+
+ With instances:
+
+ >>> ii32 = np.iinfo(np.int32(10))
+ >>> ii32.min
+ -2147483648
+ >>> ii32.max
+ 2147483647
+
+ """
+
+ _min_vals = {}
+ _max_vals = {}
+
+ __class_getitem__ = classmethod(types.GenericAlias)
+
+ def __init__(self, int_type):
+ try:
+ self.dtype = numeric.dtype(int_type)
+ except TypeError:
+ self.dtype = numeric.dtype(type(int_type))
+ self.kind = self.dtype.kind
+ self.bits = self.dtype.itemsize * 8
+ self.key = "%s%d" % (self.kind, self.bits)
+ if self.kind not in 'iu':
+ raise ValueError(f"Invalid integer data type {self.kind!r}.")
+
+ @property
+ def min(self):
+ """Minimum value of given dtype."""
+ if self.kind == 'u':
+ return 0
+ else:
+ try:
+ val = iinfo._min_vals[self.key]
+ except KeyError:
+ val = int(-(1 << (self.bits - 1)))
+ iinfo._min_vals[self.key] = val
+ return val
+
+ @property
+ def max(self):
+ """Maximum value of given dtype."""
+ try:
+ val = iinfo._max_vals[self.key]
+ except KeyError:
+ if self.kind == 'u':
+ val = int((1 << self.bits) - 1)
+ else:
+ val = int((1 << (self.bits - 1)) - 1)
+ iinfo._max_vals[self.key] = val
+ return val
+
+ def __str__(self):
+ """String representation."""
+ fmt = (
+ 'Machine parameters for %(dtype)s\n'
+ '---------------------------------------------------------------\n'
+ 'min = %(min)s\n'
+ 'max = %(max)s\n'
+ '---------------------------------------------------------------\n'
+ )
+ return fmt % {'dtype': self.dtype, 'min': self.min, 'max': self.max}
+
+ def __repr__(self):
+ return "%s(min=%s, max=%s, dtype=%s)" % (self.__class__.__name__,
+ self.min, self.max, self.dtype)
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/getlimits.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/getlimits.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..a22149ceb5c672145e2f3c2bd7ad3c20f7503185
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/getlimits.pyi
@@ -0,0 +1,124 @@
+from functools import cached_property
+from types import GenericAlias
+from typing import Final, Generic, Self, overload
+from typing_extensions import TypeVar
+
+import numpy as np
+from numpy._typing import (
+ _CLongDoubleCodes,
+ _Complex64Codes,
+ _Complex128Codes,
+ _DTypeLike,
+ _Float16Codes,
+ _Float32Codes,
+ _Float64Codes,
+ _Int8Codes,
+ _Int16Codes,
+ _Int32Codes,
+ _Int64Codes,
+ _IntPCodes,
+ _LongDoubleCodes,
+ _UInt8Codes,
+ _UInt16Codes,
+ _UInt32Codes,
+ _UInt64Codes,
+)
+
+__all__ = ["finfo", "iinfo"]
+
+###
+
+_IntegerT_co = TypeVar("_IntegerT_co", bound=np.integer, default=np.integer, covariant=True)
+_FloatingT_co = TypeVar("_FloatingT_co", bound=np.floating, default=np.floating, covariant=True)
+
+###
+
+class iinfo(Generic[_IntegerT_co]):
+ dtype: np.dtype[_IntegerT_co]
+ bits: Final[int]
+ kind: Final[str]
+ key: Final[str]
+
+ @property
+ def min(self, /) -> int: ...
+ @property
+ def max(self, /) -> int: ...
+
+ #
+ @overload
+ def __init__(self, /, int_type: _IntegerT_co | _DTypeLike[_IntegerT_co]) -> None: ...
+ @overload
+ def __init__(self: iinfo[np.int_], /, int_type: _IntPCodes | type[int] | int) -> None: ...
+ @overload
+ def __init__(self: iinfo[np.int8], /, int_type: _Int8Codes) -> None: ...
+ @overload
+ def __init__(self: iinfo[np.uint8], /, int_type: _UInt8Codes) -> None: ...
+ @overload
+ def __init__(self: iinfo[np.int16], /, int_type: _Int16Codes) -> None: ...
+ @overload
+ def __init__(self: iinfo[np.uint16], /, int_type: _UInt16Codes) -> None: ...
+ @overload
+ def __init__(self: iinfo[np.int32], /, int_type: _Int32Codes) -> None: ...
+ @overload
+ def __init__(self: iinfo[np.uint32], /, int_type: _UInt32Codes) -> None: ...
+ @overload
+ def __init__(self: iinfo[np.int64], /, int_type: _Int64Codes) -> None: ...
+ @overload
+ def __init__(self: iinfo[np.uint64], /, int_type: _UInt64Codes) -> None: ...
+ @overload
+ def __init__(self, /, int_type: str) -> None: ...
+
+ #
+ @classmethod
+ def __class_getitem__(cls, item: object, /) -> GenericAlias: ...
+
+class finfo(Generic[_FloatingT_co]):
+ dtype: np.dtype[_FloatingT_co] # readonly
+ eps: _FloatingT_co # readonly
+ _radix: _FloatingT_co # readonly
+ smallest_normal: _FloatingT_co # readonly
+ smallest_subnormal: _FloatingT_co # readonly
+ max: _FloatingT_co # readonly
+ min: _FloatingT_co # readonly
+
+ _fmt: str | None # `__str__` cache
+ _repr: str | None # `__repr__` cache
+
+ bits: Final[int]
+ maxexp: Final[int]
+ minexp: Final[int]
+ nmant: Final[int]
+ precision: Final[int]
+
+ @classmethod
+ def __class_getitem__(cls, item: object, /) -> GenericAlias: ...
+
+ #
+ @overload
+ def __new__(cls, dtype: _FloatingT_co | _DTypeLike[_FloatingT_co]) -> Self: ...
+ @overload
+ def __new__(cls, dtype: _Float16Codes) -> finfo[np.float16]: ...
+ @overload
+ def __new__(cls, dtype: _Float32Codes | _Complex64Codes | _DTypeLike[np.complex64]) -> finfo[np.float32]: ...
+ @overload
+ def __new__(cls, dtype: _Float64Codes | _Complex128Codes | type[complex] | complex) -> finfo[np.float64]: ...
+ @overload
+ def __new__(cls, dtype: _LongDoubleCodes | _CLongDoubleCodes | _DTypeLike[np.clongdouble]) -> finfo[np.longdouble]: ...
+ @overload
+ def __new__(cls, dtype: str) -> finfo: ...
+
+ #
+ @cached_property
+ def epsneg(self, /) -> _FloatingT_co: ...
+ @cached_property
+ def resolution(self, /) -> _FloatingT_co: ...
+ @cached_property
+ def machep(self, /) -> int: ...
+ @cached_property
+ def negep(self, /) -> int: ...
+ @cached_property
+ def nexp(self, /) -> int: ...
+ @cached_property
+ def iexp(self, /) -> int: ...
+ @cached_property
+ def tiny(self, /) -> _FloatingT_co: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/memmap.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/memmap.py
new file mode 100644
index 0000000000000000000000000000000000000000..8cfa7f94a8da4318cae87ae895a8eec1435add70
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/memmap.py
@@ -0,0 +1,363 @@
+import operator
+from contextlib import nullcontext
+
+import numpy as np
+from numpy._utils import set_module
+
+from .numeric import dtype, ndarray, uint8
+
+__all__ = ['memmap']
+
+dtypedescr = dtype
+valid_filemodes = ["r", "c", "r+", "w+"]
+writeable_filemodes = ["r+", "w+"]
+
+mode_equivalents = {
+ "readonly": "r",
+ "copyonwrite": "c",
+ "readwrite": "r+",
+ "write": "w+"
+ }
+
+
+@set_module('numpy')
+class memmap(ndarray):
+ """Create a memory-map to an array stored in a *binary* file on disk.
+
+ Memory-mapped files are used for accessing small segments of large files
+ on disk, without reading the entire file into memory. NumPy's
+ memmap's are array-like objects. This differs from Python's ``mmap``
+ module, which uses file-like objects.
+
+ This subclass of ndarray has some unpleasant interactions with
+ some operations, because it doesn't quite fit properly as a subclass.
+ An alternative to using this subclass is to create the ``mmap``
+ object yourself, then create an ndarray with ndarray.__new__ directly,
+ passing the object created in its 'buffer=' parameter.
+
+ This class may at some point be turned into a factory function
+ which returns a view into an mmap buffer.
+
+ Flush the memmap instance to write the changes to the file. Currently there
+ is no API to close the underlying ``mmap``. It is tricky to ensure the
+ resource is actually closed, since it may be shared between different
+ memmap instances.
+
+
+ Parameters
+ ----------
+ filename : str, file-like object, or pathlib.Path instance
+ The file name or file object to be used as the array data buffer.
+ dtype : data-type, optional
+ The data-type used to interpret the file contents.
+ Default is `uint8`.
+ mode : {'r+', 'r', 'w+', 'c'}, optional
+ The file is opened in this mode:
+
+ +------+-------------------------------------------------------------+
+ | 'r' | Open existing file for reading only. |
+ +------+-------------------------------------------------------------+
+ | 'r+' | Open existing file for reading and writing. |
+ +------+-------------------------------------------------------------+
+ | 'w+' | Create or overwrite existing file for reading and writing. |
+ | | If ``mode == 'w+'`` then `shape` must also be specified. |
+ +------+-------------------------------------------------------------+
+ | 'c' | Copy-on-write: assignments affect data in memory, but |
+ | | changes are not saved to disk. The file on disk is |
+ | | read-only. |
+ +------+-------------------------------------------------------------+
+
+ Default is 'r+'.
+ offset : int, optional
+ In the file, array data starts at this offset. Since `offset` is
+ measured in bytes, it should normally be a multiple of the byte-size
+ of `dtype`. When ``mode != 'r'``, even positive offsets beyond end of
+ file are valid; The file will be extended to accommodate the
+ additional data. By default, ``memmap`` will start at the beginning of
+ the file, even if ``filename`` is a file pointer ``fp`` and
+ ``fp.tell() != 0``.
+ shape : int or sequence of ints, optional
+ The desired shape of the array. If ``mode == 'r'`` and the number
+ of remaining bytes after `offset` is not a multiple of the byte-size
+ of `dtype`, you must specify `shape`. By default, the returned array
+ will be 1-D with the number of elements determined by file size
+ and data-type.
+
+ .. versionchanged:: 2.0
+ The shape parameter can now be any integer sequence type, previously
+ types were limited to tuple and int.
+
+ order : {'C', 'F'}, optional
+ Specify the order of the ndarray memory layout:
+ :term:`row-major`, C-style or :term:`column-major`,
+ Fortran-style. This only has an effect if the shape is
+ greater than 1-D. The default order is 'C'.
+
+ Attributes
+ ----------
+ filename : str or pathlib.Path instance
+ Path to the mapped file.
+ offset : int
+ Offset position in the file.
+ mode : str
+ File mode.
+
+ Methods
+ -------
+ flush
+ Flush any changes in memory to file on disk.
+ When you delete a memmap object, flush is called first to write
+ changes to disk.
+
+
+ See also
+ --------
+ lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file.
+
+ Notes
+ -----
+ The memmap object can be used anywhere an ndarray is accepted.
+ Given a memmap ``fp``, ``isinstance(fp, numpy.ndarray)`` returns
+ ``True``.
+
+ Memory-mapped files cannot be larger than 2GB on 32-bit systems.
+
+ When a memmap causes a file to be created or extended beyond its
+ current size in the filesystem, the contents of the new part are
+ unspecified. On systems with POSIX filesystem semantics, the extended
+ part will be filled with zero bytes.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> data = np.arange(12, dtype='float32')
+ >>> data.resize((3,4))
+
+ This example uses a temporary file so that doctest doesn't write
+ files to your directory. You would use a 'normal' filename.
+
+ >>> from tempfile import mkdtemp
+ >>> import os.path as path
+ >>> filename = path.join(mkdtemp(), 'newfile.dat')
+
+ Create a memmap with dtype and shape that matches our data:
+
+ >>> fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4))
+ >>> fp
+ memmap([[0., 0., 0., 0.],
+ [0., 0., 0., 0.],
+ [0., 0., 0., 0.]], dtype=float32)
+
+ Write data to memmap array:
+
+ >>> fp[:] = data[:]
+ >>> fp
+ memmap([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+
+ >>> fp.filename == path.abspath(filename)
+ True
+
+ Flushes memory changes to disk in order to read them back
+
+ >>> fp.flush()
+
+ Load the memmap and verify data was stored:
+
+ >>> newfp = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
+ >>> newfp
+ memmap([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+
+ Read-only memmap:
+
+ >>> fpr = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
+ >>> fpr.flags.writeable
+ False
+
+ Copy-on-write memmap:
+
+ >>> fpc = np.memmap(filename, dtype='float32', mode='c', shape=(3,4))
+ >>> fpc.flags.writeable
+ True
+
+ It's possible to assign to copy-on-write array, but values are only
+ written into the memory copy of the array, and not written to disk:
+
+ >>> fpc
+ memmap([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+ >>> fpc[0,:] = 0
+ >>> fpc
+ memmap([[ 0., 0., 0., 0.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+
+ File on disk is unchanged:
+
+ >>> fpr
+ memmap([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+
+ Offset into a memmap:
+
+ >>> fpo = np.memmap(filename, dtype='float32', mode='r', offset=16)
+ >>> fpo
+ memmap([ 4., 5., 6., 7., 8., 9., 10., 11.], dtype=float32)
+
+ """
+
+ __array_priority__ = -100.0
+
+ def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0,
+ shape=None, order='C'):
+ # Import here to minimize 'import numpy' overhead
+ import mmap
+ import os.path
+ try:
+ mode = mode_equivalents[mode]
+ except KeyError as e:
+ if mode not in valid_filemodes:
+ all_modes = valid_filemodes + list(mode_equivalents.keys())
+ raise ValueError(
+ f"mode must be one of {all_modes!r} (got {mode!r})"
+ ) from None
+
+ if mode == 'w+' and shape is None:
+ raise ValueError("shape must be given if mode == 'w+'")
+
+ if hasattr(filename, 'read'):
+ f_ctx = nullcontext(filename)
+ else:
+ f_ctx = open(
+ os.fspath(filename),
+ ('r' if mode == 'c' else mode) + 'b'
+ )
+
+ with f_ctx as fid:
+ fid.seek(0, 2)
+ flen = fid.tell()
+ descr = dtypedescr(dtype)
+ _dbytes = descr.itemsize
+
+ if shape is None:
+ bytes = flen - offset
+ if bytes % _dbytes:
+ raise ValueError("Size of available data is not a "
+ "multiple of the data-type size.")
+ size = bytes // _dbytes
+ shape = (size,)
+ else:
+ if not isinstance(shape, (tuple, list)):
+ try:
+ shape = [operator.index(shape)]
+ except TypeError:
+ pass
+ shape = tuple(shape)
+ size = np.intp(1) # avoid overflows
+ for k in shape:
+ size *= k
+
+ bytes = int(offset + size * _dbytes)
+
+ if mode in ('w+', 'r+'):
+ # gh-27723
+ # if bytes == 0, we write out 1 byte to allow empty memmap.
+ bytes = max(bytes, 1)
+ if flen < bytes:
+ fid.seek(bytes - 1, 0)
+ fid.write(b'\0')
+ fid.flush()
+
+ if mode == 'c':
+ acc = mmap.ACCESS_COPY
+ elif mode == 'r':
+ acc = mmap.ACCESS_READ
+ else:
+ acc = mmap.ACCESS_WRITE
+
+ start = offset - offset % mmap.ALLOCATIONGRANULARITY
+ bytes -= start
+ # bytes == 0 is problematic as in mmap length=0 maps the full file.
+ # See PR gh-27723 for a more detailed explanation.
+ if bytes == 0 and start > 0:
+ bytes += mmap.ALLOCATIONGRANULARITY
+ start -= mmap.ALLOCATIONGRANULARITY
+ array_offset = offset - start
+ mm = mmap.mmap(fid.fileno(), bytes, access=acc, offset=start)
+
+ self = ndarray.__new__(subtype, shape, dtype=descr, buffer=mm,
+ offset=array_offset, order=order)
+ self._mmap = mm
+ self.offset = offset
+ self.mode = mode
+
+ if isinstance(filename, os.PathLike):
+ # special case - if we were constructed with a pathlib.path,
+ # then filename is a path object, not a string
+ self.filename = filename.resolve()
+ elif hasattr(fid, "name") and isinstance(fid.name, str):
+ # py3 returns int for TemporaryFile().name
+ self.filename = os.path.abspath(fid.name)
+ # same as memmap copies (e.g. memmap + 1)
+ else:
+ self.filename = None
+
+ return self
+
+ def __array_finalize__(self, obj):
+ if hasattr(obj, '_mmap') and np.may_share_memory(self, obj):
+ self._mmap = obj._mmap
+ self.filename = obj.filename
+ self.offset = obj.offset
+ self.mode = obj.mode
+ else:
+ self._mmap = None
+ self.filename = None
+ self.offset = None
+ self.mode = None
+
+ def flush(self):
+ """
+ Write any changes in the array to the file on disk.
+
+ For further information, see `memmap`.
+
+ Parameters
+ ----------
+ None
+
+ See Also
+ --------
+ memmap
+
+ """
+ if self.base is not None and hasattr(self.base, 'flush'):
+ self.base.flush()
+
+ def __array_wrap__(self, arr, context=None, return_scalar=False):
+ arr = super().__array_wrap__(arr, context)
+
+ # Return a memmap if a memmap was given as the output of the
+ # ufunc. Leave the arr class unchanged if self is not a memmap
+ # to keep original memmap subclasses behavior
+ if self is arr or type(self) is not memmap:
+ return arr
+
+ # Return scalar instead of 0d memmap, e.g. for np.sum with
+ # axis=None (note that subclasses will not reach here)
+ if return_scalar:
+ return arr[()]
+
+ # Return ndarray otherwise
+ return arr.view(np.ndarray)
+
+ def __getitem__(self, index):
+ res = super().__getitem__(index)
+ if type(res) is memmap and res._mmap is None:
+ return res.view(type=ndarray)
+ return res
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/memmap.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/memmap.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..0b31328404fb397614bd03832af9282ce251c4f4
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/memmap.pyi
@@ -0,0 +1,3 @@
+from numpy import memmap
+
+__all__ = ["memmap"]
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/multiarray.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/multiarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd5a66a8785ffe7e04774da190eaa4427b491b79
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/multiarray.py
@@ -0,0 +1,1740 @@
+"""
+Create the numpy._core.multiarray namespace for backward compatibility.
+In v1.16 the multiarray and umath c-extension modules were merged into
+a single _multiarray_umath extension module. So we replicate the old
+namespace by importing from the extension module.
+
+"""
+
+import functools
+
+from . import _multiarray_umath, overrides
+from ._multiarray_umath import * # noqa: F403
+
+# These imports are needed for backward compatibility,
+# do not change them. issue gh-15518
+# _get_ndarray_c_version is semi-public, on purpose not added to __all__
+from ._multiarray_umath import ( # noqa: F401
+ _ARRAY_API,
+ _flagdict,
+ _get_madvise_hugepage,
+ _get_ndarray_c_version,
+ _monotonicity,
+ _place,
+ _reconstruct,
+ _set_madvise_hugepage,
+ _vec_string,
+ from_dlpack,
+)
+
+__all__ = [
+ '_ARRAY_API', 'ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DATETIMEUNITS',
+ 'ITEM_HASOBJECT', 'ITEM_IS_POINTER', 'LIST_PICKLE', 'MAXDIMS',
+ 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'NEEDS_INIT', 'NEEDS_PYAPI',
+ 'RAISE', 'USE_GETITEM', 'USE_SETITEM', 'WRAP',
+ '_flagdict', 'from_dlpack', '_place', '_reconstruct', '_vec_string',
+ '_monotonicity', 'add_docstring', 'arange', 'array', 'asarray',
+ 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'bincount',
+ 'broadcast', 'busday_count', 'busday_offset', 'busdaycalendar', 'can_cast',
+ 'compare_chararrays', 'concatenate', 'copyto', 'correlate', 'correlate2',
+ 'count_nonzero', 'c_einsum', 'datetime_as_string', 'datetime_data',
+ 'dot', 'dragon4_positional', 'dragon4_scientific', 'dtype',
+ 'empty', 'empty_like', 'error', 'flagsobj', 'flatiter', 'format_longfloat',
+ 'frombuffer', 'fromfile', 'fromiter', 'fromstring',
+ 'get_handler_name', 'get_handler_version', 'inner', 'interp',
+ 'interp_complex', 'is_busday', 'lexsort', 'matmul', 'vecdot',
+ 'may_share_memory', 'min_scalar_type', 'ndarray', 'nditer', 'nested_iters',
+ 'normalize_axis_index', 'packbits', 'promote_types', 'putmask',
+ 'ravel_multi_index', 'result_type', 'scalar', 'set_datetimeparse_function',
+ 'set_typeDict', 'shares_memory', 'typeinfo',
+ 'unpackbits', 'unravel_index', 'vdot', 'where', 'zeros']
+
+# For backward compatibility, make sure pickle imports
+# these functions from here
+_reconstruct.__module__ = 'numpy._core.multiarray'
+scalar.__module__ = 'numpy._core.multiarray'
+
+
+from_dlpack.__module__ = 'numpy'
+arange.__module__ = 'numpy'
+array.__module__ = 'numpy'
+asarray.__module__ = 'numpy'
+asanyarray.__module__ = 'numpy'
+ascontiguousarray.__module__ = 'numpy'
+asfortranarray.__module__ = 'numpy'
+datetime_data.__module__ = 'numpy'
+empty.__module__ = 'numpy'
+frombuffer.__module__ = 'numpy'
+fromfile.__module__ = 'numpy'
+fromiter.__module__ = 'numpy'
+frompyfunc.__module__ = 'numpy'
+fromstring.__module__ = 'numpy'
+may_share_memory.__module__ = 'numpy'
+nested_iters.__module__ = 'numpy'
+promote_types.__module__ = 'numpy'
+zeros.__module__ = 'numpy'
+normalize_axis_index.__module__ = 'numpy.lib.array_utils'
+add_docstring.__module__ = 'numpy.lib'
+compare_chararrays.__module__ = 'numpy.char'
+
+
+def _override___module__():
+ namespace_names = globals()
+ for ufunc_name in [
+ 'absolute', 'arccos', 'arccosh', 'add', 'arcsin', 'arcsinh', 'arctan',
+ 'arctan2', 'arctanh', 'bitwise_and', 'bitwise_count', 'invert',
+ 'left_shift', 'bitwise_or', 'right_shift', 'bitwise_xor', 'cbrt',
+ 'ceil', 'conjugate', 'copysign', 'cos', 'cosh', 'deg2rad', 'degrees',
+ 'divide', 'divmod', 'equal', 'exp', 'exp2', 'expm1', 'fabs',
+ 'float_power', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod',
+ 'frexp', 'gcd', 'greater', 'greater_equal', 'heaviside', 'hypot',
+ 'isfinite', 'isinf', 'isnan', 'isnat', 'lcm', 'ldexp', 'less',
+ 'less_equal', 'log', 'log10', 'log1p', 'log2', 'logaddexp',
+ 'logaddexp2', 'logical_and', 'logical_not', 'logical_or',
+ 'logical_xor', 'matmul', 'matvec', 'maximum', 'minimum', 'remainder',
+ 'modf', 'multiply', 'negative', 'nextafter', 'not_equal', 'positive',
+ 'power', 'rad2deg', 'radians', 'reciprocal', 'rint', 'sign', 'signbit',
+ 'sin', 'sinh', 'spacing', 'sqrt', 'square', 'subtract', 'tan', 'tanh',
+ 'trunc', 'vecdot', 'vecmat',
+ ]:
+ ufunc = namespace_names[ufunc_name]
+ ufunc.__module__ = "numpy"
+ ufunc.__qualname__ = ufunc_name
+
+
+_override___module__()
+
+
+# We can't verify dispatcher signatures because NumPy's C functions don't
+# support introspection.
+array_function_from_c_func_and_dispatcher = functools.partial(
+ overrides.array_function_from_dispatcher,
+ module='numpy', docs_from_dispatcher=True, verify=False)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.empty_like)
+def empty_like(
+ prototype, dtype=None, order="K", subok=True, shape=None, *, device=None
+):
+ """
+ empty_like(
+ prototype,
+ /,
+ dtype=None,
+ order='K',
+ subok=True,
+ shape=None,
+ *,
+ device=None,
+ )
+ --
+
+ Return a new array with the same shape and type as a given array.
+
+ Parameters
+ ----------
+ prototype : array_like
+ The shape and data-type of `prototype` define these same attributes
+ of the returned array.
+ dtype : data-type, optional
+ Overrides the data type of the result.
+ order : {'C', 'F', 'A', or 'K'}, optional
+ Overrides the memory layout of the result. 'C' means C-order,
+ 'F' means F-order, 'A' means 'F' if `prototype` is Fortran
+ contiguous, 'C' otherwise. 'K' means match the layout of `prototype`
+ as closely as possible.
+ subok : bool, optional.
+ If True, then the newly created array will use the sub-class
+ type of `prototype`, otherwise it will be a base-class array. Defaults
+ to True.
+ shape : int or sequence of ints, optional.
+ Overrides the shape of the result. If order='K' and the number of
+ dimensions is unchanged, will try to keep order, otherwise,
+ order='C' is implied.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of uninitialized (arbitrary) data with the same
+ shape and type as `prototype`.
+
+ See Also
+ --------
+ ones_like : Return an array of ones with shape and type of input.
+ zeros_like : Return an array of zeros with shape and type of input.
+ full_like : Return a new array with shape of input filled with value.
+ empty : Return a new uninitialized array.
+
+ Notes
+ -----
+ Unlike other array creation functions (e.g. `zeros_like`, `ones_like`,
+ `full_like`), `empty_like` does not initialize the values of the array,
+ and may therefore be marginally faster. However, the values stored in the
+ newly allocated array are arbitrary. For reproducible behavior, be sure
+ to set each element of the array before reading.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = ([1,2,3], [4,5,6]) # a is array-like
+ >>> np.empty_like(a)
+ array([[-1073741821, -1073741821, 3], # uninitialized
+ [ 0, 0, -1073741821]])
+ >>> a = np.array([[1., 2., 3.],[4.,5.,6.]])
+ >>> np.empty_like(a)
+ array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], # uninitialized
+ [ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]])
+
+ """
+ return (prototype,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.concatenate)
+def concatenate(arrays, axis=0, out=None, *, dtype=None, casting="same_kind"):
+ """
+ concatenate(
+ arrays,
+ /,
+ axis=0,
+ out=None,
+ *,
+ dtype=None,
+ casting="same_kind",
+ )
+ --
+
+ Join a sequence of arrays along an existing axis.
+
+ Parameters
+ ----------
+ a1, a2, ... : sequence of array_like
+ The arrays must have the same shape, except in the dimension
+ corresponding to `axis` (the first, by default).
+ axis : int, optional
+ The axis along which the arrays will be joined. If axis is None,
+ arrays are flattened before use. Default is 0.
+ out : ndarray, optional
+ If provided, the destination to place the result. The shape must be
+ correct, matching that of what concatenate would have returned if no
+ out argument were specified.
+ dtype : str or dtype
+ If provided, the destination array will have this dtype. Cannot be
+ provided together with `out`.
+
+ .. versionadded:: 1.20.0
+
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Defaults to 'same_kind'.
+ For a description of the options, please see :term:`casting`.
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ res : ndarray
+ The concatenated array.
+
+ See Also
+ --------
+ ma.concatenate : Concatenate function that preserves input masks.
+ array_split : Split an array into multiple sub-arrays of equal or
+ near-equal size.
+ split : Split array into a list of multiple sub-arrays of equal size.
+ hsplit : Split array into multiple sub-arrays horizontally (column wise).
+ vsplit : Split array into multiple sub-arrays vertically (row wise).
+ dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
+ stack : Stack a sequence of arrays along a new axis.
+ block : Assemble arrays from blocks.
+ hstack : Stack arrays in sequence horizontally (column wise).
+ vstack : Stack arrays in sequence vertically (row wise).
+ dstack : Stack arrays in sequence depth wise (along third dimension).
+ column_stack : Stack 1-D arrays as columns into a 2-D array.
+
+ Notes
+ -----
+ When one or more of the arrays to be concatenated is a MaskedArray,
+ this function will return a MaskedArray object instead of an ndarray,
+ but the input masks are *not* preserved. In cases where a MaskedArray
+ is expected as input, use the ma.concatenate function from the masked
+ array module instead.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2], [3, 4]])
+ >>> b = np.array([[5, 6]])
+ >>> np.concatenate((a, b), axis=0)
+ array([[1, 2],
+ [3, 4],
+ [5, 6]])
+ >>> np.concatenate((a, b.T), axis=1)
+ array([[1, 2, 5],
+ [3, 4, 6]])
+ >>> np.concatenate((a, b), axis=None)
+ array([1, 2, 3, 4, 5, 6])
+
+ This function will not preserve masking of MaskedArray inputs.
+
+ >>> a = np.ma.arange(3)
+ >>> a[1] = np.ma.masked
+ >>> b = np.arange(2, 5)
+ >>> a
+ masked_array(data=[0, --, 2],
+ mask=[False, True, False],
+ fill_value=999999)
+ >>> b
+ array([2, 3, 4])
+ >>> np.concatenate([a, b])
+ masked_array(data=[0, 1, 2, 2, 3, 4],
+ mask=False,
+ fill_value=999999)
+ >>> np.ma.concatenate([a, b])
+ masked_array(data=[0, --, 2, 2, 3, 4],
+ mask=[False, True, False, False, False, False],
+ fill_value=999999)
+
+ """
+ if out is not None:
+ # optimize for the typical case where only arrays is provided
+ arrays = list(arrays)
+ arrays.append(out)
+ return arrays
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.inner)
+def inner(a, b, /):
+ """
+ inner(a, b, /)
+
+ Inner product of two arrays.
+
+ Ordinary inner product of vectors for 1-D arrays (without complex
+ conjugation), in higher dimensions a sum product over the last axes.
+
+ Parameters
+ ----------
+ a, b : array_like
+ If `a` and `b` are nonscalar, their last dimensions must match.
+
+ Returns
+ -------
+ out : ndarray
+ If `a` and `b` are both
+ scalars or both 1-D arrays then a scalar is returned; otherwise
+ an array is returned.
+ ``out.shape = (*a.shape[:-1], *b.shape[:-1])``
+
+ Raises
+ ------
+ ValueError
+ If both `a` and `b` are nonscalar and their last dimensions have
+ different sizes.
+
+ See Also
+ --------
+ tensordot : Sum products over arbitrary axes.
+ dot : Generalised matrix product, using second last dimension of `b`.
+ vecdot : Vector dot product of two arrays.
+ einsum : Einstein summation convention.
+
+ Notes
+ -----
+ For vectors (1-D arrays) it computes the ordinary inner-product::
+
+ np.inner(a, b) = sum(a[:]*b[:])
+
+ More generally, if ``ndim(a) = r > 0`` and ``ndim(b) = s > 0``::
+
+ np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1))
+
+ or explicitly::
+
+ np.inner(a, b)[i0,...,ir-2,j0,...,js-2]
+ = sum(a[i0,...,ir-2,:]*b[j0,...,js-2,:])
+
+ In addition `a` or `b` may be scalars, in which case::
+
+ np.inner(a,b) = a*b
+
+ Examples
+ --------
+ Ordinary inner product for vectors:
+
+ >>> import numpy as np
+ >>> a = np.array([1,2,3])
+ >>> b = np.array([0,1,0])
+ >>> np.inner(a, b)
+ 2
+
+ Some multidimensional examples:
+
+ >>> a = np.arange(24).reshape((2,3,4))
+ >>> b = np.arange(4)
+ >>> c = np.inner(a, b)
+ >>> c.shape
+ (2, 3)
+ >>> c
+ array([[ 14, 38, 62],
+ [ 86, 110, 134]])
+
+ >>> a = np.arange(2).reshape((1,1,2))
+ >>> b = np.arange(6).reshape((3,2))
+ >>> c = np.inner(a, b)
+ >>> c.shape
+ (1, 1, 3)
+ >>> c
+ array([[[1, 3, 5]]])
+
+ An example where `b` is a scalar:
+
+ >>> np.inner(np.eye(2), 7)
+ array([[7., 0.],
+ [0., 7.]])
+
+ """
+ return (a, b)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.where)
+def where(condition, x=None, y=None, /):
+ """
+ where(condition, [x, y], /)
+
+ Return elements chosen from `x` or `y` depending on `condition`.
+
+ .. note::
+ When only `condition` is provided, this function is a shorthand for
+ ``np.asarray(condition).nonzero()``. Using `nonzero` directly should be
+ preferred, as it behaves correctly for subclasses. The rest of this
+ documentation covers only the case where all three arguments are
+ provided.
+
+ Parameters
+ ----------
+ condition : array_like, bool
+ Where True, yield `x`, otherwise yield `y`.
+ x, y : array_like
+ Values from which to choose. `x`, `y` and `condition` need to be
+ broadcastable to some shape.
+
+ Returns
+ -------
+ out : ndarray
+ An array with elements from `x` where `condition` is True, and elements
+ from `y` elsewhere.
+
+ See Also
+ --------
+ choose
+ nonzero : The function that is called when x and y are omitted
+
+ Notes
+ -----
+ If all the arrays are 1-D, `where` is equivalent to::
+
+ [xv if c else yv
+ for c, xv, yv in zip(condition, x, y)]
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(10)
+ >>> a
+ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
+ >>> np.where(a < 5, a, 10*a)
+ array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
+
+ This can be used on multidimensional arrays too:
+
+ >>> np.where([[True, False], [True, True]],
+ ... [[1, 2], [3, 4]],
+ ... [[9, 8], [7, 6]])
+ array([[1, 8],
+ [3, 4]])
+
+ The shapes of x, y, and the condition are broadcast together:
+
+ >>> x, y = np.ogrid[:3, :4]
+ >>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast
+ array([[10, 0, 0, 0],
+ [10, 11, 1, 1],
+ [10, 11, 12, 2]])
+
+ >>> a = np.array([[0, 1, 2],
+ ... [0, 2, 4],
+ ... [0, 3, 6]])
+ >>> np.where(a < 4, a, -1) # -1 is broadcast
+ array([[ 0, 1, 2],
+ [ 0, 2, -1],
+ [ 0, 3, -1]])
+ """
+ return (condition, x, y)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.lexsort)
+def lexsort(keys, axis=-1):
+ """
+ lexsort(keys, axis=-1)
+
+ Perform an indirect stable sort using a sequence of keys.
+
+ Given multiple sorting keys, lexsort returns an array of integer indices
+ that describes the sort order by multiple keys. The last key in the
+ sequence is used for the primary sort order, ties are broken by the
+ second-to-last key, and so on.
+
+ Parameters
+ ----------
+ keys : (k, m, n, ...) array-like
+ The `k` keys to be sorted. The *last* key (e.g, the last
+ row if `keys` is a 2D array) is the primary sort key.
+ Each element of `keys` along the zeroth axis must be
+ an array-like object of the same shape.
+ axis : int, optional
+ Axis to be indirectly sorted. By default, sort over the last axis
+ of each sequence. Separate slices along `axis` sorted over
+ independently; see last example.
+
+ Returns
+ -------
+ indices : (m, n, ...) ndarray of ints
+ Array of indices that sort the keys along the specified axis.
+
+ See Also
+ --------
+ argsort : Indirect sort.
+ ndarray.sort : In-place sort.
+ sort : Return a sorted copy of an array.
+
+ Examples
+ --------
+ Sort names: first by surname, then by name.
+
+ >>> import numpy as np
+ >>> surnames = ('Hertz', 'Galilei', 'Hertz')
+ >>> first_names = ('Heinrich', 'Galileo', 'Gustav')
+ >>> ind = np.lexsort((first_names, surnames))
+ >>> ind
+ array([1, 2, 0])
+
+ >>> [surnames[i] + ", " + first_names[i] for i in ind]
+ ['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich']
+
+ Sort according to two numerical keys, first by elements
+ of ``a``, then breaking ties according to elements of ``b``:
+
+ >>> a = [1, 5, 1, 4, 3, 4, 4] # First sequence
+ >>> b = [9, 4, 0, 4, 0, 2, 1] # Second sequence
+ >>> ind = np.lexsort((b, a)) # Sort by `a`, then by `b`
+ >>> ind
+ array([2, 0, 4, 6, 5, 3, 1])
+ >>> [(a[i], b[i]) for i in ind]
+ [(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)]
+
+ Compare against `argsort`, which would sort each key independently.
+
+ >>> np.argsort((b, a), kind='stable')
+ array([[2, 4, 6, 5, 1, 3, 0],
+ [0, 2, 4, 3, 5, 6, 1]])
+
+ To sort lexicographically with `argsort`, we would need to provide a
+ structured array.
+
+ >>> x = np.array([(ai, bi) for ai, bi in zip(a, b)],
+ ... dtype = np.dtype([('x', int), ('y', int)]))
+ >>> np.argsort(x) # or np.argsort(x, order=('x', 'y'))
+ array([2, 0, 4, 6, 5, 3, 1])
+
+ The zeroth axis of `keys` always corresponds with the sequence of keys,
+ so 2D arrays are treated just like other sequences of keys.
+
+ >>> arr = np.asarray([b, a])
+ >>> ind2 = np.lexsort(arr)
+ >>> np.testing.assert_equal(ind2, ind)
+
+ Accordingly, the `axis` parameter refers to an axis of *each* key, not of
+ the `keys` argument itself. For instance, the array ``arr`` is treated as
+ a sequence of two 1-D keys, so specifying ``axis=0`` is equivalent to
+ using the default axis, ``axis=-1``.
+
+ >>> np.testing.assert_equal(np.lexsort(arr, axis=0),
+ ... np.lexsort(arr, axis=-1))
+
+ For higher-dimensional arrays, the axis parameter begins to matter. The
+ resulting array has the same shape as each key, and the values are what
+ we would expect if `lexsort` were performed on corresponding slices
+ of the keys independently. For instance,
+
+ >>> x = [[1, 2, 3, 4],
+ ... [4, 3, 2, 1],
+ ... [2, 1, 4, 3]]
+ >>> y = [[2, 2, 1, 1],
+ ... [1, 2, 1, 2],
+ ... [1, 1, 2, 1]]
+ >>> np.lexsort((x, y), axis=1)
+ array([[2, 3, 0, 1],
+ [2, 0, 3, 1],
+ [1, 0, 3, 2]])
+
+ Each row of the result is what we would expect if we were to perform
+ `lexsort` on the corresponding row of the keys:
+
+ >>> for i in range(3):
+ ... print(np.lexsort((x[i], y[i])))
+ [2 3 0 1]
+ [2 0 3 1]
+ [1 0 3 2]
+
+ """
+ if isinstance(keys, tuple):
+ return keys
+ else:
+ return (keys,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.can_cast)
+def can_cast(from_, to, casting="safe"):
+ """
+ can_cast(from_, to, casting='safe')
+
+ Returns True if cast between data types can occur according to the
+ casting rule.
+
+ Parameters
+ ----------
+ from_ : dtype, dtype specifier, NumPy scalar, or array
+ Data type, NumPy scalar, or array to cast from.
+ to : dtype or dtype specifier
+ Data type to cast to.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur.
+
+ * 'no' means the data types should not be cast at all.
+ * 'equiv' means only byte-order changes are allowed.
+ * 'safe' means only casts which can preserve values are allowed.
+ * 'same_kind' means only safe casts or casts within a kind,
+ like float64 to float32, are allowed.
+ * 'unsafe' means any data conversions may be done.
+
+ Returns
+ -------
+ out : bool
+ True if cast can occur according to the casting rule.
+
+ Notes
+ -----
+ .. versionchanged:: 2.0
+ This function does not support Python scalars anymore and does not
+ apply any value-based logic for 0-D arrays and NumPy scalars.
+
+ See also
+ --------
+ dtype, result_type
+
+ Examples
+ --------
+ Basic examples
+
+ >>> import numpy as np
+ >>> np.can_cast(np.int32, np.int64)
+ True
+ >>> np.can_cast(np.float64, complex)
+ True
+ >>> np.can_cast(complex, float)
+ False
+
+ >>> np.can_cast('i8', 'f8')
+ True
+ >>> np.can_cast('i8', 'f4')
+ False
+ >>> np.can_cast('i4', 'S4')
+ False
+
+ """
+ return (from_,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.min_scalar_type)
+def min_scalar_type(a, /):
+ """
+ min_scalar_type(a, /)
+
+ For scalar ``a``, returns the data type with the smallest size
+ and smallest scalar kind which can hold its value. For non-scalar
+ array ``a``, returns the vector's dtype unmodified.
+
+ Floating point values are not demoted to integers,
+ and complex values are not demoted to floats.
+
+ Parameters
+ ----------
+ a : scalar or array_like
+ The value whose minimal data type is to be found.
+
+ Returns
+ -------
+ out : dtype
+ The minimal data type.
+
+ See Also
+ --------
+ result_type, promote_types, dtype, can_cast
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.min_scalar_type(10)
+ dtype('uint8')
+
+ >>> np.min_scalar_type(-260)
+ dtype('int16')
+
+ >>> np.min_scalar_type(3.1)
+ dtype('float16')
+
+ >>> np.min_scalar_type(1e50)
+ dtype('float64')
+
+ >>> np.min_scalar_type(np.arange(4,dtype='f8'))
+ dtype('float64')
+
+ """
+ return (a,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.result_type)
+def result_type(*arrays_and_dtypes):
+ """
+ result_type(*arrays_and_dtypes)
+
+ Returns the type that results from applying the NumPy
+ :ref:`type promotion ` rules to the arguments.
+
+ Parameters
+ ----------
+ arrays_and_dtypes : list of arrays and dtypes
+ The operands of some operation whose result type is needed.
+
+ Returns
+ -------
+ out : dtype
+ The result type.
+
+ See also
+ --------
+ dtype, promote_types, min_scalar_type, can_cast
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.result_type(3, np.arange(7, dtype='i1'))
+ dtype('int8')
+
+ >>> np.result_type('i4', 'c8')
+ dtype('complex128')
+
+ >>> np.result_type(3.0, -2)
+ dtype('float64')
+
+ """
+ return arrays_and_dtypes
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.dot)
+def dot(a, b, out=None):
+ """
+ dot(a, b, out=None)
+
+ Dot product of two arrays. Specifically,
+
+ - If both `a` and `b` are 1-D arrays, it is inner product of vectors
+ (without complex conjugation).
+
+ - If both `a` and `b` are 2-D arrays, it is matrix multiplication,
+ but using :func:`matmul` or ``a @ b`` is preferred.
+
+ - If either `a` or `b` is 0-D (scalar), it is equivalent to
+ :func:`multiply` and using ``numpy.multiply(a, b)`` or ``a * b`` is
+ preferred.
+
+ - If `a` is an N-D array and `b` is a 1-D array, it is a sum product over
+ the last axis of `a` and `b`.
+
+ - If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a
+ sum product over the last axis of `a` and the second-to-last axis of
+ `b`::
+
+ dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
+
+ It uses an optimized BLAS library when possible (see `numpy.linalg`).
+
+ Parameters
+ ----------
+ a : array_like
+ First argument.
+ b : array_like
+ Second argument.
+ out : ndarray, optional
+ Output argument. This must have the exact kind that would be returned
+ if it was not used. In particular, it must have the right type, must be
+ C-contiguous, and its dtype must be the dtype that would be returned
+ for `dot(a,b)`. This is a performance feature. Therefore, if these
+ conditions are not met, an exception is raised, instead of attempting
+ to be flexible.
+
+ Returns
+ -------
+ output : ndarray
+ Returns the dot product of `a` and `b`. If `a` and `b` are both
+ scalars or both 1-D arrays then a scalar is returned; otherwise
+ an array is returned.
+ If `out` is given, then it is returned.
+
+ Raises
+ ------
+ ValueError
+ If the last dimension of `a` is not the same size as
+ the second-to-last dimension of `b`.
+
+ See Also
+ --------
+ vdot : Complex-conjugating dot product.
+ vecdot : Vector dot product of two arrays.
+ tensordot : Sum products over arbitrary axes.
+ einsum : Einstein summation convention.
+ matmul : '@' operator as method with out parameter.
+ linalg.multi_dot : Chained dot product.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.dot(3, 4)
+ 12
+
+ Neither argument is complex-conjugated:
+
+ >>> np.dot([2j, 3j], [2j, 3j])
+ (-13+0j)
+
+ For 2-D arrays it is the matrix product:
+
+ >>> a = [[1, 0], [0, 1]]
+ >>> b = [[4, 1], [2, 2]]
+ >>> np.dot(a, b)
+ array([[4, 1],
+ [2, 2]])
+
+ >>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
+ >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
+ >>> np.dot(a, b)[2,3,2,1,2,2]
+ 499128
+ >>> sum(a[2,3,2,:] * b[1,2,:,2])
+ 499128
+
+ """
+ return (a, b, out)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.vdot)
+def vdot(a, b, /):
+ r"""
+ vdot(a, b, /)
+
+ Return the dot product of two vectors.
+
+ The `vdot` function handles complex numbers differently than `dot`:
+ if the first argument is complex, it is replaced by its complex conjugate
+ in the dot product calculation. `vdot` also handles multidimensional
+ arrays differently than `dot`: it does not perform a matrix product, but
+ flattens the arguments to 1-D arrays before taking a vector dot product.
+
+ Consequently, when the arguments are 2-D arrays of the same shape, this
+ function effectively returns their
+ `Frobenius inner product `_
+ (also known as the *trace inner product* or the *standard inner product*
+ on a vector space of matrices).
+
+ Parameters
+ ----------
+ a : array_like
+ If `a` is complex the complex conjugate is taken before calculation
+ of the dot product.
+ b : array_like
+ Second argument to the dot product.
+
+ Returns
+ -------
+ output : ndarray
+ Dot product of `a` and `b`. Can be an int, float, or
+ complex depending on the types of `a` and `b`.
+
+ See Also
+ --------
+ dot : Return the dot product without using the complex conjugate of the
+ first argument.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([1+2j,3+4j])
+ >>> b = np.array([5+6j,7+8j])
+ >>> np.vdot(a, b)
+ (70-8j)
+ >>> np.vdot(b, a)
+ (70+8j)
+
+ Note that higher-dimensional arrays are flattened!
+
+ >>> a = np.array([[1, 4], [5, 6]])
+ >>> b = np.array([[4, 1], [2, 2]])
+ >>> np.vdot(a, b)
+ 30
+ >>> np.vdot(b, a)
+ 30
+ >>> 1*4 + 4*1 + 5*2 + 6*2
+ 30
+
+ """ # noqa: E501
+ return (a, b)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.bincount)
+def bincount(x, /, weights=None, minlength=0):
+ """
+ bincount(x, /, weights=None, minlength=0)
+
+ Count number of occurrences of each value in array of non-negative ints.
+
+ The number of bins (of size 1) is one larger than the largest value in
+ `x`. If `minlength` is specified, there will be at least this number
+ of bins in the output array (though it will be longer if necessary,
+ depending on the contents of `x`).
+ Each bin gives the number of occurrences of its index value in `x`.
+ If `weights` is specified the input array is weighted by it, i.e. if a
+ value ``n`` is found at position ``i``, ``out[n] += weight[i]`` instead
+ of ``out[n] += 1``.
+
+ Parameters
+ ----------
+ x : array_like, 1 dimension, nonnegative ints
+ Input array.
+ weights : array_like, optional
+ Weights, array of the same shape as `x`.
+ minlength : int, optional
+ A minimum number of bins for the output array.
+
+ Returns
+ -------
+ out : ndarray of ints
+ The result of binning the input array.
+ The length of `out` is equal to ``np.amax(x)+1``.
+
+ Raises
+ ------
+ ValueError
+ If the input is not 1-dimensional, or contains elements with negative
+ values, or if `minlength` is negative.
+ TypeError
+ If the type of the input is float or complex.
+
+ See Also
+ --------
+ histogram, digitize, unique
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.bincount(np.arange(5))
+ array([1, 1, 1, 1, 1])
+ >>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
+ array([1, 3, 1, 1, 0, 0, 0, 1])
+
+ >>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
+ >>> np.bincount(x).size == np.amax(x)+1
+ True
+
+ The input array needs to be of integer dtype, otherwise a
+ TypeError is raised:
+
+ >>> np.bincount(np.arange(5, dtype=float))
+ Traceback (most recent call last):
+ ...
+ TypeError: Cannot cast array data from dtype('float64') to dtype('int64')
+ according to the rule 'safe'
+
+ A possible use of ``bincount`` is to perform sums over
+ variable-size chunks of an array, using the ``weights`` keyword.
+
+ >>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights
+ >>> x = np.array([0, 1, 1, 2, 2, 2])
+ >>> np.bincount(x, weights=w)
+ array([ 0.3, 0.7, 1.1])
+
+ """
+ return (x, weights)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.ravel_multi_index)
+def ravel_multi_index(multi_index, dims, mode="raise", order="C"):
+ """
+ ravel_multi_index(multi_index, dims, mode='raise', order='C')
+
+ Converts a tuple of index arrays into an array of flat
+ indices, applying boundary modes to the multi-index.
+
+ Parameters
+ ----------
+ multi_index : tuple of array_like
+ A tuple of integer arrays, one array for each dimension.
+ dims : tuple of ints
+ The shape of array into which the indices from ``multi_index`` apply.
+ mode : {'raise', 'wrap', 'clip'}, optional
+ Specifies how out-of-bounds indices are handled. Can specify
+ either one mode or a tuple of modes, one mode per index.
+
+ * 'raise' -- raise an error (default)
+ * 'wrap' -- wrap around
+ * 'clip' -- clip to the range
+
+ In 'clip' mode, a negative index which would normally
+ wrap will clip to 0 instead.
+ order : {'C', 'F'}, optional
+ Determines whether the multi-index should be viewed as
+ indexing in row-major (C-style) or column-major
+ (Fortran-style) order.
+
+ Returns
+ -------
+ raveled_indices : ndarray
+ An array of indices into the flattened version of an array
+ of dimensions ``dims``.
+
+ See Also
+ --------
+ unravel_index
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> arr = np.array([[3,6,6],[4,5,1]])
+ >>> np.ravel_multi_index(arr, (7,6))
+ array([22, 41, 37])
+ >>> np.ravel_multi_index(arr, (7,6), order='F')
+ array([31, 41, 13])
+ >>> np.ravel_multi_index(arr, (4,6), mode='clip')
+ array([22, 23, 19])
+ >>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap'))
+ array([12, 13, 13])
+
+ >>> np.ravel_multi_index((3,1,4,1), (6,7,8,9))
+ 1621
+ """
+ return multi_index
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.unravel_index)
+def unravel_index(indices, shape, order="C"):
+ """
+ unravel_index(indices, shape, order='C')
+
+ Converts a flat index or array of flat indices into a tuple
+ of coordinate arrays.
+
+ Parameters
+ ----------
+ indices : array_like
+ An integer array whose elements are indices into the flattened
+ version of an array of dimensions ``shape``. Before version 1.6.0,
+ this function accepted just one index value.
+ shape : tuple of ints
+ The shape of the array to use for unraveling ``indices``.
+ order : {'C', 'F'}, optional
+ Determines whether the indices should be viewed as indexing in
+ row-major (C-style) or column-major (Fortran-style) order.
+
+ Returns
+ -------
+ unraveled_coords : tuple of ndarray
+ Each array in the tuple has the same shape as the ``indices``
+ array.
+
+ See Also
+ --------
+ ravel_multi_index
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.unravel_index([22, 41, 37], (7,6))
+ (array([3, 6, 6]), array([4, 5, 1]))
+ >>> np.unravel_index([31, 41, 13], (7,6), order='F')
+ (array([3, 6, 6]), array([4, 5, 1]))
+
+ >>> np.unravel_index(1621, (6,7,8,9))
+ (3, 1, 4, 1)
+
+ """
+ return (indices,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.copyto)
+def copyto(dst, src, casting="same_kind", where=True):
+ """
+ copyto(dst, src, casting='same_kind', where=True)
+
+ Copies values from one array to another, broadcasting as necessary.
+
+ Raises a TypeError if the `casting` rule is violated, and if
+ `where` is provided, it selects which elements to copy.
+
+ Parameters
+ ----------
+ dst : ndarray
+ The array into which values are copied.
+ src : array_like
+ The array from which values are copied.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur when copying.
+
+ * 'no' means the data types should not be cast at all.
+ * 'equiv' means only byte-order changes are allowed.
+ * 'safe' means only casts which can preserve values are allowed.
+ * 'same_kind' means only safe casts or casts within a kind,
+ like float64 to float32, are allowed.
+ * 'unsafe' means any data conversions may be done.
+ where : array_like of bool, optional
+ A boolean array which is broadcasted to match the dimensions
+ of `dst`, and selects elements to copy from `src` to `dst`
+ wherever it contains the value True.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> A = np.array([4, 5, 6])
+ >>> B = [1, 2, 3]
+ >>> np.copyto(A, B)
+ >>> A
+ array([1, 2, 3])
+
+ >>> A = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> B = [[4, 5, 6], [7, 8, 9]]
+ >>> np.copyto(A, B)
+ >>> A
+ array([[4, 5, 6],
+ [7, 8, 9]])
+
+ """
+ return (dst, src, where)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.putmask)
+def putmask(a, /, mask, values):
+ """
+ putmask(a, /, mask, values)
+
+ Changes elements of an array based on conditional and input values.
+
+ Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``.
+
+ If `values` is not the same size as `a` and `mask` then it will repeat.
+ This gives behavior different from ``a[mask] = values``.
+
+ Parameters
+ ----------
+ a : ndarray
+ Target array.
+ mask : array_like
+ Boolean mask array. It has to be the same shape as `a`.
+ values : array_like
+ Values to put into `a` where `mask` is True. If `values` is smaller
+ than `a` it will be repeated.
+
+ See Also
+ --------
+ place, put, take, copyto
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2, 3)
+ >>> np.putmask(x, x>2, x**2)
+ >>> x
+ array([[ 0, 1, 2],
+ [ 9, 16, 25]])
+
+ If `values` is smaller than `a` it is repeated:
+
+ >>> x = np.arange(5)
+ >>> np.putmask(x, x>1, [-33, -44])
+ >>> x
+ array([ 0, 1, -33, -44, -33])
+
+ """
+ return (a, mask, values)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.packbits)
+def packbits(a, /, axis=None, bitorder="big"):
+ """
+ packbits(a, /, axis=None, bitorder='big')
+
+ Packs the elements of a binary-valued array into bits in a uint8 array.
+
+ The result is padded to full bytes by inserting zero bits at the end.
+
+ Parameters
+ ----------
+ a : array_like
+ An array of integers or booleans whose elements should be packed to
+ bits.
+ axis : int, optional
+ The dimension over which bit-packing is done.
+ ``None`` implies packing the flattened array.
+ bitorder : {'big', 'little'}, optional
+ The order of the input bits. 'big' will mimic bin(val),
+ ``[0, 0, 0, 0, 0, 0, 1, 1] => 3 = 0b00000011``, 'little' will
+ reverse the order so ``[1, 1, 0, 0, 0, 0, 0, 0] => 3``.
+ Defaults to 'big'.
+
+ Returns
+ -------
+ packed : ndarray
+ Array of type uint8 whose elements represent bits corresponding to the
+ logical (0 or nonzero) value of the input elements. The shape of
+ `packed` has the same number of dimensions as the input (unless `axis`
+ is None, in which case the output is 1-D).
+
+ See Also
+ --------
+ unpackbits: Unpacks elements of a uint8 array into a binary-valued output
+ array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[[1,0,1],
+ ... [0,1,0]],
+ ... [[1,1,0],
+ ... [0,0,1]]])
+ >>> b = np.packbits(a, axis=-1)
+ >>> b
+ array([[[160],
+ [ 64]],
+ [[192],
+ [ 32]]], dtype=uint8)
+
+ Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000,
+ and 32 = 0010 0000.
+
+ """
+ return (a,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits)
+def unpackbits(a, /, axis=None, count=None, bitorder="big"):
+ """
+ unpackbits(a, /, axis=None, count=None, bitorder='big')
+
+ Unpacks elements of a uint8 array into a binary-valued output array.
+
+ Each element of `a` represents a bit-field that should be unpacked
+ into a binary-valued output array. The shape of the output array is
+ either 1-D (if `axis` is ``None``) or the same shape as the input
+ array with unpacking done along the axis specified.
+
+ Parameters
+ ----------
+ a : ndarray, uint8 type
+ Input array.
+ axis : int, optional
+ The dimension over which bit-unpacking is done.
+ ``None`` implies unpacking the flattened array.
+ count : int or None, optional
+ The number of elements to unpack along `axis`, provided as a way
+ of undoing the effect of packing a size that is not a multiple
+ of eight. A non-negative number means to only unpack `count`
+ bits. A negative number means to trim off that many bits from
+ the end. ``None`` means to unpack the entire array (the
+ default). Counts larger than the available number of bits will
+ add zero padding to the output. Negative counts must not
+ exceed the available number of bits.
+ bitorder : {'big', 'little'}, optional
+ The order of the returned bits. 'big' will mimic bin(val),
+ ``3 = 0b00000011 => [0, 0, 0, 0, 0, 0, 1, 1]``, 'little' will reverse
+ the order to ``[1, 1, 0, 0, 0, 0, 0, 0]``.
+ Defaults to 'big'.
+
+ Returns
+ -------
+ unpacked : ndarray, uint8 type
+ The elements are binary-valued (0 or 1).
+
+ See Also
+ --------
+ packbits : Packs the elements of a binary-valued array into bits in
+ a uint8 array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[2], [7], [23]], dtype=np.uint8)
+ >>> a
+ array([[ 2],
+ [ 7],
+ [23]], dtype=uint8)
+ >>> b = np.unpackbits(a, axis=1)
+ >>> b
+ array([[0, 0, 0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
+ >>> c = np.unpackbits(a, axis=1, count=-3)
+ >>> c
+ array([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0]], dtype=uint8)
+
+ >>> p = np.packbits(b, axis=0)
+ >>> np.unpackbits(p, axis=0)
+ array([[0, 0, 0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 0, 1, 0, 1, 1, 1],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
+ >>> np.array_equal(b, np.unpackbits(p, axis=0, count=b.shape[0]))
+ True
+
+ """
+ return (a,)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.shares_memory)
+def shares_memory(a, b, /, max_work=-1):
+ """
+ shares_memory(a, b, /, max_work=-1)
+
+ Determine if two arrays share memory.
+
+ .. warning::
+
+ This function can be exponentially slow for some inputs, unless
+ `max_work` is set to zero or a positive integer.
+ If in doubt, use `numpy.may_share_memory` instead.
+
+ Parameters
+ ----------
+ a, b : ndarray
+ Input arrays
+ max_work : int, optional
+ Effort to spend on solving the overlap problem (maximum number
+ of candidate solutions to consider). The following special
+ values are recognized:
+
+ max_work=-1 (default)
+ The problem is solved exactly. In this case, the function returns
+ True only if there is an element shared between the arrays. Finding
+ the exact solution may take extremely long in some cases.
+ max_work=0
+ Only the memory bounds of a and b are checked.
+ This is equivalent to using ``may_share_memory()``.
+
+ Raises
+ ------
+ numpy.exceptions.TooHardError
+ Exceeded max_work.
+
+ Returns
+ -------
+ out : bool
+
+ See Also
+ --------
+ may_share_memory
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array([1, 2, 3, 4])
+ >>> np.shares_memory(x, np.array([5, 6, 7]))
+ False
+ >>> np.shares_memory(x[::2], x)
+ True
+ >>> np.shares_memory(x[::2], x[1::2])
+ False
+
+ Checking whether two arrays share memory is NP-complete, and
+ runtime may increase exponentially in the number of
+ dimensions. Hence, `max_work` should generally be set to a finite
+ number, as it is possible to construct examples that take
+ extremely long to run:
+
+ >>> from numpy.lib.stride_tricks import as_strided
+ >>> x = np.zeros([192163377], dtype=np.int8)
+ >>> x1 = as_strided(
+ ... x, strides=(36674, 61119, 85569), shape=(1049, 1049, 1049))
+ >>> x2 = as_strided(
+ ... x[64023025:], strides=(12223, 12224, 1), shape=(1049, 1049, 1))
+ >>> np.shares_memory(x1, x2, max_work=1000)
+ Traceback (most recent call last):
+ ...
+ numpy.exceptions.TooHardError: Exceeded max_work
+
+ Running ``np.shares_memory(x1, x2)`` without `max_work` set takes
+ around 1 minute for this case. It is possible to find problems
+ that take still significantly longer.
+
+ """
+ return (a, b)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.may_share_memory)
+def may_share_memory(a, b, /, max_work=0):
+ """
+ may_share_memory(a, b, /, max_work=0)
+
+ Determine if two arrays might share memory
+
+ A return of True does not necessarily mean that the two arrays
+ share any element. It just means that they *might*.
+
+ Only the memory bounds of a and b are checked by default.
+
+ Parameters
+ ----------
+ a, b : ndarray
+ Input arrays
+ max_work : int, optional
+ Effort to spend on solving the overlap problem. See
+ `shares_memory` for details. Default for ``may_share_memory``
+ is to do a bounds check.
+
+ Returns
+ -------
+ out : bool
+
+ See Also
+ --------
+ shares_memory
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.may_share_memory(np.array([1,2]), np.array([5,8,9]))
+ False
+ >>> x = np.zeros([3, 4])
+ >>> np.may_share_memory(x[:,0], x[:,1])
+ True
+
+ """
+ return (a, b)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.is_busday)
+def is_busday(dates, weekmask="1111100", holidays=None, busdaycal=None, out=None):
+ """
+ is_busday(
+ dates,
+ weekmask='1111100',
+ holidays=None,
+ busdaycal=None,
+ out=None,
+ )
+
+ Calculates which of the given dates are valid days, and which are not.
+
+ Parameters
+ ----------
+ dates : array_like of datetime64[D]
+ The array of dates to process.
+ weekmask : str or array_like of bool, optional
+ A seven-element array indicating which of Monday through Sunday are
+ valid days. May be specified as a length-seven list or array, like
+ [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
+ like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
+ weekdays, optionally separated by white space. Valid abbreviations
+ are: Mon Tue Wed Thu Fri Sat Sun
+ holidays : array_like of datetime64[D], optional
+ An array of dates to consider as invalid dates. They may be
+ specified in any order, and NaT (not-a-time) dates are ignored.
+ This list is saved in a normalized form that is suited for
+ fast calculations of valid days.
+ busdaycal : busdaycalendar, optional
+ A `busdaycalendar` object which specifies the valid days. If this
+ parameter is provided, neither weekmask nor holidays may be
+ provided.
+ out : array of bool, optional
+ If provided, this array is filled with the result.
+
+ Returns
+ -------
+ out : array of bool
+ An array with the same shape as ``dates``, containing True for
+ each valid day, and False for each invalid day.
+
+ See Also
+ --------
+ busdaycalendar : An object that specifies a custom set of valid days.
+ busday_offset : Applies an offset counted in valid days.
+ busday_count : Counts how many valid days are in a half-open date range.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> # The weekdays are Friday, Saturday, and Monday
+ ... np.is_busday(['2011-07-01', '2011-07-02', '2011-07-18'],
+ ... holidays=['2011-07-01', '2011-07-04', '2011-07-17'])
+ array([False, False, True])
+ """
+ return (dates, weekmask, holidays, out)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_offset)
+def busday_offset(dates, offsets, roll="raise", weekmask="1111100", holidays=None,
+ busdaycal=None, out=None):
+ """
+ busday_offset(
+ dates,
+ offsets,
+ roll='raise',
+ weekmask='1111100',
+ holidays=None,
+ busdaycal=None,
+ out=None,
+ )
+
+ First adjusts the date to fall on a valid day according to
+ the ``roll`` rule, then applies offsets to the given dates
+ counted in valid days.
+
+ Parameters
+ ----------
+ dates : array_like of datetime64[D]
+ The array of dates to process.
+ offsets : array_like of int
+ The array of offsets, which is broadcast with ``dates``.
+ roll : {'raise', 'nat', 'forward', 'following', 'backward', 'preceding', \
+ 'modifiedfollowing', 'modifiedpreceding'}, optional
+ How to treat dates that do not fall on a valid day. The default
+ is 'raise'.
+
+ * 'raise' means to raise an exception for an invalid day.
+ * 'nat' means to return a NaT (not-a-time) for an invalid day.
+ * 'forward' and 'following' mean to take the first valid day
+ later in time.
+ * 'backward' and 'preceding' mean to take the first valid day
+ earlier in time.
+ * 'modifiedfollowing' means to take the first valid day
+ later in time unless it is across a Month boundary, in which
+ case to take the first valid day earlier in time.
+ * 'modifiedpreceding' means to take the first valid day
+ earlier in time unless it is across a Month boundary, in which
+ case to take the first valid day later in time.
+ weekmask : str or array_like of bool, optional
+ A seven-element array indicating which of Monday through Sunday are
+ valid days. May be specified as a length-seven list or array, like
+ [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
+ like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
+ weekdays, optionally separated by white space. Valid abbreviations
+ are: Mon Tue Wed Thu Fri Sat Sun
+ holidays : array_like of datetime64[D], optional
+ An array of dates to consider as invalid dates. They may be
+ specified in any order, and NaT (not-a-time) dates are ignored.
+ This list is saved in a normalized form that is suited for
+ fast calculations of valid days.
+ busdaycal : busdaycalendar, optional
+ A `busdaycalendar` object which specifies the valid days. If this
+ parameter is provided, neither weekmask nor holidays may be
+ provided.
+ out : array of datetime64[D], optional
+ If provided, this array is filled with the result.
+
+ Returns
+ -------
+ out : array of datetime64[D]
+ An array with a shape from broadcasting ``dates`` and ``offsets``
+ together, containing the dates with offsets applied.
+
+ See Also
+ --------
+ busdaycalendar : An object that specifies a custom set of valid days.
+ is_busday : Returns a boolean array indicating valid days.
+ busday_count : Counts how many valid days are in a half-open date range.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> # First business day in October 2011 (not accounting for holidays)
+ ... np.busday_offset('2011-10', 0, roll='forward')
+ np.datetime64('2011-10-03')
+ >>> # Last business day in February 2012 (not accounting for holidays)
+ ... np.busday_offset('2012-03', -1, roll='forward')
+ np.datetime64('2012-02-29')
+ >>> # Third Wednesday in January 2011
+ ... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed')
+ np.datetime64('2011-01-19')
+ >>> # 2012 Mother's Day in Canada and the U.S.
+ ... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun')
+ np.datetime64('2012-05-13')
+
+ >>> # First business day on or after a date
+ ... np.busday_offset('2011-03-20', 0, roll='forward')
+ np.datetime64('2011-03-21')
+ >>> np.busday_offset('2011-03-22', 0, roll='forward')
+ np.datetime64('2011-03-22')
+ >>> # First business day after a date
+ ... np.busday_offset('2011-03-20', 1, roll='backward')
+ np.datetime64('2011-03-21')
+ >>> np.busday_offset('2011-03-22', 1, roll='backward')
+ np.datetime64('2011-03-23')
+ """
+ return (dates, offsets, weekmask, holidays, out)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_count)
+def busday_count(begindates, enddates, weekmask="1111100", holidays=(),
+ busdaycal=None, out=None):
+ """
+ busday_count(
+ begindates,
+ enddates,
+ weekmask='1111100',
+ holidays=[],
+ busdaycal=None,
+ out=None
+ )
+
+ Counts the number of valid days between `begindates` and
+ `enddates`, not including the day of `enddates`.
+
+ If ``enddates`` specifies a date value that is earlier than the
+ corresponding ``begindates`` date value, the count will be negative.
+
+ Parameters
+ ----------
+ begindates : array_like of datetime64[D]
+ The array of the first dates for counting.
+ enddates : array_like of datetime64[D]
+ The array of the end dates for counting, which are excluded
+ from the count themselves.
+ weekmask : str or array_like of bool, optional
+ A seven-element array indicating which of Monday through Sunday are
+ valid days. May be specified as a length-seven list or array, like
+ [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
+ like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
+ weekdays, optionally separated by white space. Valid abbreviations
+ are: Mon Tue Wed Thu Fri Sat Sun
+ holidays : array_like of datetime64[D], optional
+ An array of dates to consider as invalid dates. They may be
+ specified in any order, and NaT (not-a-time) dates are ignored.
+ This list is saved in a normalized form that is suited for
+ fast calculations of valid days.
+ busdaycal : busdaycalendar, optional
+ A `busdaycalendar` object which specifies the valid days. If this
+ parameter is provided, neither weekmask nor holidays may be
+ provided.
+ out : array of int, optional
+ If provided, this array is filled with the result.
+
+ Returns
+ -------
+ out : array of int
+ An array with a shape from broadcasting ``begindates`` and ``enddates``
+ together, containing the number of valid days between
+ the begin and end dates.
+
+ See Also
+ --------
+ busdaycalendar : An object that specifies a custom set of valid days.
+ is_busday : Returns a boolean array indicating valid days.
+ busday_offset : Applies an offset counted in valid days.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> # Number of weekdays in January 2011
+ ... np.busday_count('2011-01', '2011-02')
+ 21
+ >>> # Number of weekdays in 2011
+ >>> np.busday_count('2011', '2012')
+ 260
+ >>> # Number of Saturdays in 2011
+ ... np.busday_count('2011', '2012', weekmask='Sat')
+ 53
+ """
+ return (begindates, enddates, weekmask, holidays, out)
+
+
+@array_function_from_c_func_and_dispatcher(_multiarray_umath.datetime_as_string)
+def datetime_as_string(arr, unit=None, timezone="naive", casting="same_kind"):
+ """
+ datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')
+
+ Convert an array of datetimes into an array of strings.
+
+ Parameters
+ ----------
+ arr : array_like of datetime64
+ The array of UTC timestamps to format.
+ unit : str
+ One of None, 'auto', or
+ a :ref:`datetime unit `.
+ timezone : {'naive', 'UTC', 'local'} or tzinfo
+ Timezone information to use when displaying the datetime. If 'UTC',
+ end with a Z to indicate UTC time. If 'local', convert to the local
+ timezone first, and suffix with a +-#### timezone offset. If a tzinfo
+ object, then do as with 'local', but use the specified timezone.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}
+ Casting to allow when changing between datetime units.
+
+ Returns
+ -------
+ str_arr : ndarray
+ An array of strings the same shape as `arr`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from zoneinfo import ZoneInfo
+ >>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]')
+ >>> d
+ array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30',
+ '2002-10-27T07:30'], dtype='datetime64[m]')
+
+ Setting the timezone to UTC shows the same information, but with a Z suffix
+
+ >>> np.datetime_as_string(d, timezone='UTC')
+ array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z',
+ '2002-10-27T07:30Z'], dtype='>> np.datetime_as_string(d, timezone=ZoneInfo('US/Eastern'))
+ array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400',
+ '2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='>> np.datetime_as_string(d, unit='h')
+ array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'],
+ dtype='>> np.datetime_as_string(d, unit='s')
+ array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00',
+ '2002-10-27T07:30:00'], dtype='>> np.datetime_as_string(d, unit='h', casting='safe')
+ Traceback (most recent call last):
+ ...
+ TypeError: Cannot create a datetime string as units 'h' from a NumPy
+ datetime with units 'm' according to the rule 'safe'
+ """
+ return (arr,)
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/multiarray.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/multiarray.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..279ba5a81b81ae68a0ecaa9aa03cf2678aedc26a
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/multiarray.pyi
@@ -0,0 +1,1328 @@
+# TODO: Sort out any and all missing functions in this namespace
+import datetime as dt
+from _typeshed import Incomplete, StrOrBytesPath, SupportsLenAndGetItem
+from collections.abc import Callable, Iterable, Sequence
+from typing import (
+ Any,
+ ClassVar,
+ Final,
+ Literal as L,
+ Protocol,
+ SupportsIndex,
+ TypeAlias,
+ TypeVar,
+ final,
+ overload,
+ type_check_only,
+)
+from typing_extensions import CapsuleType
+
+import numpy as np
+from numpy import ( # type: ignore[attr-defined] # Python >=3.12
+ _AnyShapeT,
+ _CastingKind,
+ _CopyMode,
+ _ModeKind,
+ _NDIterFlagsKind,
+ _NDIterFlagsOp,
+ _OrderCF,
+ _OrderKACF,
+ _SupportsBuffer,
+ _SupportsFileMethods,
+ broadcast,
+ busdaycalendar,
+ complexfloating,
+ correlate,
+ count_nonzero,
+ datetime64,
+ dtype,
+ einsum as c_einsum,
+ flatiter,
+ float64,
+ floating,
+ from_dlpack,
+ generic,
+ int_,
+ interp,
+ intp,
+ matmul,
+ ndarray,
+ nditer,
+ signedinteger,
+ str_,
+ timedelta64,
+ ufunc,
+ uint8,
+ unsignedinteger,
+ vecdot,
+)
+from numpy._typing import (
+ ArrayLike,
+ DTypeLike,
+ NDArray,
+ _AnyShape,
+ _ArrayLike,
+ _ArrayLikeBool_co,
+ _ArrayLikeBytes_co,
+ _ArrayLikeComplex_co,
+ _ArrayLikeDT64_co,
+ _ArrayLikeFloat_co,
+ _ArrayLikeInt_co,
+ _ArrayLikeObject_co,
+ _ArrayLikeStr_co,
+ _ArrayLikeTD64_co,
+ _ArrayLikeUInt_co,
+ _DT64Codes,
+ _DTypeLike,
+ _FloatLike_co,
+ _IntLike_co,
+ _NestedSequence,
+ _ScalarLike_co,
+ _Shape,
+ _ShapeLike,
+ _SupportsArrayFunc,
+ _SupportsDType,
+ _TD64Like_co,
+)
+from numpy._typing._ufunc import (
+ _2PTuple,
+ _PyFunc_Nin1_Nout1,
+ _PyFunc_Nin1P_Nout2P,
+ _PyFunc_Nin2_Nout1,
+ _PyFunc_Nin3P_Nout1,
+)
+
+__all__ = [
+ "_ARRAY_API",
+ "ALLOW_THREADS",
+ "BUFSIZE",
+ "CLIP",
+ "DATETIMEUNITS",
+ "ITEM_HASOBJECT",
+ "ITEM_IS_POINTER",
+ "LIST_PICKLE",
+ "MAXDIMS",
+ "MAY_SHARE_BOUNDS",
+ "MAY_SHARE_EXACT",
+ "NEEDS_INIT",
+ "NEEDS_PYAPI",
+ "RAISE",
+ "USE_GETITEM",
+ "USE_SETITEM",
+ "WRAP",
+ "_flagdict",
+ "from_dlpack",
+ "_place",
+ "_reconstruct",
+ "_vec_string",
+ "_monotonicity",
+ "add_docstring",
+ "arange",
+ "array",
+ "asarray",
+ "asanyarray",
+ "ascontiguousarray",
+ "asfortranarray",
+ "bincount",
+ "broadcast",
+ "busday_count",
+ "busday_offset",
+ "busdaycalendar",
+ "can_cast",
+ "compare_chararrays",
+ "concatenate",
+ "copyto",
+ "correlate",
+ "correlate2",
+ "count_nonzero",
+ "c_einsum",
+ "datetime_as_string",
+ "datetime_data",
+ "dot",
+ "dragon4_positional",
+ "dragon4_scientific",
+ "dtype",
+ "empty",
+ "empty_like",
+ "error",
+ "flagsobj",
+ "flatiter",
+ "format_longfloat",
+ "frombuffer",
+ "fromfile",
+ "fromiter",
+ "fromstring",
+ "get_handler_name",
+ "get_handler_version",
+ "inner",
+ "interp",
+ "interp_complex",
+ "is_busday",
+ "lexsort",
+ "matmul",
+ "vecdot",
+ "may_share_memory",
+ "min_scalar_type",
+ "ndarray",
+ "nditer",
+ "nested_iters",
+ "normalize_axis_index",
+ "packbits",
+ "promote_types",
+ "putmask",
+ "ravel_multi_index",
+ "result_type",
+ "scalar",
+ "set_datetimeparse_function",
+ "set_typeDict",
+ "shares_memory",
+ "typeinfo",
+ "unpackbits",
+ "unravel_index",
+ "vdot",
+ "where",
+ "zeros",
+]
+
+_ScalarT = TypeVar("_ScalarT", bound=generic)
+_DTypeT = TypeVar("_DTypeT", bound=np.dtype)
+_ArrayT = TypeVar("_ArrayT", bound=ndarray)
+_ArrayT_co = TypeVar("_ArrayT_co", bound=ndarray, covariant=True)
+_ShapeT = TypeVar("_ShapeT", bound=_Shape)
+# TODO: fix the names of these typevars
+_ReturnType = TypeVar("_ReturnType")
+_IDType = TypeVar("_IDType")
+_Nin = TypeVar("_Nin", bound=int)
+_Nout = TypeVar("_Nout", bound=int)
+
+_Array: TypeAlias = ndarray[_ShapeT, dtype[_ScalarT]]
+_Array1D: TypeAlias = ndarray[tuple[int], dtype[_ScalarT]]
+
+# Valid time units
+_UnitKind: TypeAlias = L[
+ "Y",
+ "M",
+ "D",
+ "h",
+ "m",
+ "s",
+ "ms",
+ "us", "μs",
+ "ns",
+ "ps",
+ "fs",
+ "as",
+]
+_RollKind: TypeAlias = L[ # `raise` is deliberately excluded
+ "nat",
+ "forward",
+ "following",
+ "backward",
+ "preceding",
+ "modifiedfollowing",
+ "modifiedpreceding",
+]
+
+@type_check_only
+class _SupportsArray(Protocol[_ArrayT_co]):
+ def __array__(self, /) -> _ArrayT_co: ...
+
+@type_check_only
+class _ConstructorEmpty(Protocol):
+ # 1-D shape
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: SupportsIndex,
+ dtype: None = None,
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+ ) -> _Array1D[float64]: ...
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: SupportsIndex,
+ dtype: _DTypeT | _SupportsDType[_DTypeT],
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+ ) -> ndarray[tuple[int], _DTypeT]: ...
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: SupportsIndex,
+ dtype: type[_ScalarT],
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+ ) -> _Array1D[_ScalarT]: ...
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: SupportsIndex,
+ dtype: DTypeLike | None = None,
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+ ) -> _Array1D[Incomplete]: ...
+
+ # known shape
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: _AnyShapeT,
+ dtype: None = None,
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+ ) -> _Array[_AnyShapeT, float64]: ...
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: _AnyShapeT,
+ dtype: _DTypeT | _SupportsDType[_DTypeT],
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+ ) -> ndarray[_AnyShapeT, _DTypeT]: ...
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: _AnyShapeT,
+ dtype: type[_ScalarT],
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+ ) -> _Array[_AnyShapeT, _ScalarT]: ...
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: _AnyShapeT,
+ dtype: DTypeLike | None = None,
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+ ) -> _Array[_AnyShapeT, Incomplete]: ...
+
+ # unknown shape
+ @overload
+ def __call__(
+ self, /,
+ shape: _ShapeLike,
+ dtype: None = None,
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+ ) -> NDArray[float64]: ...
+ @overload
+ def __call__(
+ self, /,
+ shape: _ShapeLike,
+ dtype: _DTypeT | _SupportsDType[_DTypeT],
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+ ) -> ndarray[_AnyShape, _DTypeT]: ...
+ @overload
+ def __call__(
+ self, /,
+ shape: _ShapeLike,
+ dtype: type[_ScalarT],
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+ ) -> NDArray[_ScalarT]: ...
+ @overload
+ def __call__(
+ self,
+ /,
+ shape: _ShapeLike,
+ dtype: DTypeLike | None = None,
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+ ) -> NDArray[Incomplete]: ...
+
+# using `Final` or `TypeAlias` will break stubtest
+error = Exception
+
+# from ._multiarray_umath
+ITEM_HASOBJECT: Final = 1
+LIST_PICKLE: Final = 2
+ITEM_IS_POINTER: Final = 4
+NEEDS_INIT: Final = 8
+NEEDS_PYAPI: Final = 16
+USE_GETITEM: Final = 32
+USE_SETITEM: Final = 64
+DATETIMEUNITS: Final[CapsuleType] = ...
+_ARRAY_API: Final[CapsuleType] = ...
+
+_flagdict: Final[dict[str, int]] = ...
+_monotonicity: Final[Callable[..., object]] = ...
+_place: Final[Callable[..., object]] = ...
+_reconstruct: Final[Callable[..., object]] = ...
+_vec_string: Final[Callable[..., object]] = ...
+correlate2: Final[Callable[..., object]] = ...
+dragon4_positional: Final[Callable[..., object]] = ...
+dragon4_scientific: Final[Callable[..., object]] = ...
+interp_complex: Final[Callable[..., object]] = ...
+set_datetimeparse_function: Final[Callable[..., object]] = ...
+
+def get_handler_name(a: NDArray[Any] = ..., /) -> str | None: ...
+def get_handler_version(a: NDArray[Any] = ..., /) -> int | None: ...
+def format_longfloat(x: np.longdouble, precision: int) -> str: ...
+def scalar(dtype: _DTypeT, object: bytes | object = ...) -> ndarray[tuple[()], _DTypeT]: ...
+def set_typeDict(dict_: dict[str, np.dtype], /) -> None: ...
+
+typeinfo: Final[dict[str, np.dtype[np.generic]]] = ...
+
+ALLOW_THREADS: Final[int] # 0 or 1 (system-specific)
+BUFSIZE: Final = 8_192
+CLIP: Final = 0
+WRAP: Final = 1
+RAISE: Final = 2
+MAXDIMS: Final = 64
+MAY_SHARE_BOUNDS: Final = 0
+MAY_SHARE_EXACT: Final = -1
+tracemalloc_domain: Final = 389_047
+
+zeros: Final[_ConstructorEmpty] = ...
+empty: Final[_ConstructorEmpty] = ...
+
+@overload
+def empty_like(
+ prototype: _ArrayT,
+ /,
+ dtype: None = None,
+ order: _OrderKACF = "K",
+ subok: bool = True,
+ shape: _ShapeLike | None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> _ArrayT: ...
+@overload
+def empty_like(
+ prototype: _ArrayLike[_ScalarT],
+ /,
+ dtype: None = None,
+ order: _OrderKACF = "K",
+ subok: bool = True,
+ shape: _ShapeLike | None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def empty_like(
+ prototype: Incomplete,
+ /,
+ dtype: _DTypeLike[_ScalarT],
+ order: _OrderKACF = "K",
+ subok: bool = True,
+ shape: _ShapeLike | None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def empty_like(
+ prototype: Incomplete,
+ /,
+ dtype: DTypeLike | None = None,
+ order: _OrderKACF = "K",
+ subok: bool = True,
+ shape: _ShapeLike | None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[Incomplete]: ...
+
+@overload
+def array(
+ object: _ArrayT,
+ dtype: None = None,
+ *,
+ copy: bool | _CopyMode | None = True,
+ order: _OrderKACF = "K",
+ subok: L[True],
+ ndmin: int = 0,
+ ndmax: int = 0,
+ like: _SupportsArrayFunc | None = None,
+) -> _ArrayT: ...
+@overload
+def array(
+ object: _SupportsArray[_ArrayT],
+ dtype: None = None,
+ *,
+ copy: bool | _CopyMode | None = True,
+ order: _OrderKACF = "K",
+ subok: L[True],
+ ndmin: L[0] = 0,
+ ndmax: int = 0,
+ like: _SupportsArrayFunc | None = None,
+) -> _ArrayT: ...
+@overload
+def array(
+ object: _ArrayLike[_ScalarT],
+ dtype: None = None,
+ *,
+ copy: bool | _CopyMode | None = True,
+ order: _OrderKACF = "K",
+ subok: bool = False,
+ ndmin: int = 0,
+ ndmax: int = 0,
+ like: _SupportsArrayFunc | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def array(
+ object: Any,
+ dtype: _DTypeLike[_ScalarT],
+ *,
+ copy: bool | _CopyMode | None = True,
+ order: _OrderKACF = "K",
+ subok: bool = False,
+ ndmin: int = 0,
+ ndmax: int = 0,
+ like: _SupportsArrayFunc | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def array(
+ object: Any,
+ dtype: DTypeLike | None = None,
+ *,
+ copy: bool | _CopyMode | None = True,
+ order: _OrderKACF = "K",
+ subok: bool = False,
+ ndmin: int = 0,
+ ndmax: int = 0,
+ like: _SupportsArrayFunc | None = None,
+) -> NDArray[Any]: ...
+
+#
+@overload
+def ravel_multi_index(
+ multi_index: SupportsLenAndGetItem[_IntLike_co],
+ dims: _ShapeLike,
+ mode: _ModeKind | tuple[_ModeKind, ...] = "raise",
+ order: _OrderCF = "C",
+) -> intp: ...
+@overload
+def ravel_multi_index(
+ multi_index: SupportsLenAndGetItem[_ArrayLikeInt_co],
+ dims: _ShapeLike,
+ mode: _ModeKind | tuple[_ModeKind, ...] = "raise",
+ order: _OrderCF = "C",
+) -> NDArray[intp]: ...
+
+#
+@overload
+def unravel_index(indices: _IntLike_co, shape: _ShapeLike, order: _OrderCF = "C") -> tuple[intp, ...]: ...
+@overload
+def unravel_index(indices: _ArrayLikeInt_co, shape: _ShapeLike, order: _OrderCF = "C") -> tuple[NDArray[intp], ...]: ...
+
+#
+def normalize_axis_index(axis: int, ndim: int, msg_prefix: str | None = None) -> int: ...
+
+# NOTE: Allow any sequence of array-like objects
+@overload
+def concatenate(
+ arrays: _ArrayLike[_ScalarT],
+ /,
+ axis: SupportsIndex | None = 0,
+ out: None = None,
+ *,
+ dtype: None = None,
+ casting: _CastingKind | None = "same_kind",
+) -> NDArray[_ScalarT]: ...
+@overload
+def concatenate(
+ arrays: SupportsLenAndGetItem[ArrayLike],
+ /,
+ axis: SupportsIndex | None = 0,
+ out: None = None,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ casting: _CastingKind | None = "same_kind",
+) -> NDArray[_ScalarT]: ...
+@overload
+def concatenate(
+ arrays: SupportsLenAndGetItem[ArrayLike],
+ /,
+ axis: SupportsIndex | None = 0,
+ out: None = None,
+ *,
+ dtype: DTypeLike | None = None,
+ casting: _CastingKind | None = "same_kind",
+) -> NDArray[Incomplete]: ...
+@overload
+def concatenate(
+ arrays: SupportsLenAndGetItem[ArrayLike],
+ /,
+ axis: SupportsIndex | None = 0,
+ *,
+ out: _ArrayT,
+ dtype: DTypeLike | None = None,
+ casting: _CastingKind | None = "same_kind",
+) -> _ArrayT: ...
+@overload
+def concatenate(
+ arrays: SupportsLenAndGetItem[ArrayLike],
+ /,
+ axis: SupportsIndex | None,
+ out: _ArrayT,
+ *,
+ dtype: DTypeLike | None = None,
+ casting: _CastingKind | None = "same_kind",
+) -> _ArrayT: ...
+
+def inner(a: ArrayLike, b: ArrayLike, /) -> Incomplete: ...
+
+@overload
+def where(condition: ArrayLike, x: None = None, y: None = None, /) -> tuple[NDArray[intp], ...]: ...
+@overload
+def where(condition: ArrayLike, x: ArrayLike, y: ArrayLike, /) -> NDArray[Incomplete]: ...
+
+def lexsort(keys: ArrayLike, axis: SupportsIndex = -1) -> NDArray[intp]: ...
+
+def can_cast(from_: ArrayLike | DTypeLike, to: DTypeLike, casting: _CastingKind = "safe") -> bool: ...
+
+def min_scalar_type(a: ArrayLike, /) -> dtype: ...
+def result_type(*arrays_and_dtypes: ArrayLike | DTypeLike | None) -> dtype: ...
+
+@overload
+def dot(a: ArrayLike, b: ArrayLike, out: None = None) -> Incomplete: ...
+@overload
+def dot(a: ArrayLike, b: ArrayLike, out: _ArrayT) -> _ArrayT: ...
+
+@overload
+def vdot(a: _ArrayLikeBool_co, b: _ArrayLikeBool_co, /) -> np.bool: ...
+@overload
+def vdot(a: _ArrayLikeUInt_co, b: _ArrayLikeUInt_co, /) -> unsignedinteger: ...
+@overload
+def vdot(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, /) -> signedinteger: ...
+@overload
+def vdot(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, /) -> floating: ...
+@overload
+def vdot(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, /) -> complexfloating: ...
+@overload
+def vdot(a: _ArrayLikeTD64_co, b: _ArrayLikeTD64_co, /) -> timedelta64: ...
+@overload
+def vdot(a: _ArrayLikeObject_co, b: object, /) -> Any: ...
+@overload
+def vdot(a: object, b: _ArrayLikeObject_co, /) -> Any: ...
+
+def bincount(x: ArrayLike, /, weights: ArrayLike | None = None, minlength: SupportsIndex = 0) -> NDArray[intp]: ...
+
+def copyto(dst: ndarray, src: ArrayLike, casting: _CastingKind = "same_kind", where: object = True) -> None: ...
+def putmask(a: ndarray, /, mask: _ArrayLikeBool_co, values: ArrayLike) -> None: ...
+
+_BitOrder: TypeAlias = L["big", "little"]
+
+@overload
+def packbits(a: _ArrayLikeInt_co, /, axis: None = None, bitorder: _BitOrder = "big") -> ndarray[tuple[int], dtype[uint8]]: ...
+@overload
+def packbits(a: _ArrayLikeInt_co, /, axis: SupportsIndex, bitorder: _BitOrder = "big") -> NDArray[uint8]: ...
+
+@overload
+def unpackbits(
+ a: _ArrayLike[uint8],
+ /,
+ axis: None = None,
+ count: SupportsIndex | None = None,
+ bitorder: _BitOrder = "big",
+) -> ndarray[tuple[int], dtype[uint8]]: ...
+@overload
+def unpackbits(
+ a: _ArrayLike[uint8],
+ /,
+ axis: SupportsIndex,
+ count: SupportsIndex | None = None,
+ bitorder: _BitOrder = "big",
+) -> NDArray[uint8]: ...
+
+_MaxWork: TypeAlias = L[-1, 0]
+
+# any two python objects will be accepted, not just `ndarray`s
+def shares_memory(a: object, b: object, /, max_work: _MaxWork = -1) -> bool: ...
+def may_share_memory(a: object, b: object, /, max_work: _MaxWork = 0) -> bool: ...
+
+@overload
+def asarray(
+ a: _ArrayLike[_ScalarT],
+ dtype: None = None,
+ order: _OrderKACF = ...,
+ *,
+ device: L["cpu"] | None = ...,
+ copy: bool | None = ...,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[_ScalarT]: ...
+@overload
+def asarray(
+ a: Any,
+ dtype: _DTypeLike[_ScalarT],
+ order: _OrderKACF = ...,
+ *,
+ device: L["cpu"] | None = ...,
+ copy: bool | None = ...,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[_ScalarT]: ...
+@overload
+def asarray(
+ a: Any,
+ dtype: DTypeLike | None = ...,
+ order: _OrderKACF = ...,
+ *,
+ device: L["cpu"] | None = ...,
+ copy: bool | None = ...,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def asanyarray(
+ a: _ArrayT, # Preserve subclass-information
+ dtype: None = None,
+ order: _OrderKACF = ...,
+ *,
+ device: L["cpu"] | None = ...,
+ copy: bool | None = ...,
+ like: _SupportsArrayFunc | None = ...,
+) -> _ArrayT: ...
+@overload
+def asanyarray(
+ a: _ArrayLike[_ScalarT],
+ dtype: None = None,
+ order: _OrderKACF = ...,
+ *,
+ device: L["cpu"] | None = ...,
+ copy: bool | None = ...,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[_ScalarT]: ...
+@overload
+def asanyarray(
+ a: Any,
+ dtype: _DTypeLike[_ScalarT],
+ order: _OrderKACF = ...,
+ *,
+ device: L["cpu"] | None = ...,
+ copy: bool | None = ...,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[_ScalarT]: ...
+@overload
+def asanyarray(
+ a: Any,
+ dtype: DTypeLike | None = ...,
+ order: _OrderKACF = ...,
+ *,
+ device: L["cpu"] | None = ...,
+ copy: bool | None = ...,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def ascontiguousarray(
+ a: _ArrayLike[_ScalarT],
+ dtype: None = None,
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[_ScalarT]: ...
+@overload
+def ascontiguousarray(
+ a: Any,
+ dtype: _DTypeLike[_ScalarT],
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[_ScalarT]: ...
+@overload
+def ascontiguousarray(
+ a: Any,
+ dtype: DTypeLike | None = ...,
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def asfortranarray(
+ a: _ArrayLike[_ScalarT],
+ dtype: None = None,
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[_ScalarT]: ...
+@overload
+def asfortranarray(
+ a: Any,
+ dtype: _DTypeLike[_ScalarT],
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[_ScalarT]: ...
+@overload
+def asfortranarray(
+ a: Any,
+ dtype: DTypeLike | None = ...,
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[Any]: ...
+
+def promote_types(__type1: DTypeLike, __type2: DTypeLike) -> dtype: ...
+
+# `sep` is a de facto mandatory argument, as its default value is deprecated
+@overload
+def fromstring(
+ string: str | bytes,
+ dtype: None = None,
+ count: SupportsIndex = ...,
+ *,
+ sep: str,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[float64]: ...
+@overload
+def fromstring(
+ string: str | bytes,
+ dtype: _DTypeLike[_ScalarT],
+ count: SupportsIndex = ...,
+ *,
+ sep: str,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[_ScalarT]: ...
+@overload
+def fromstring(
+ string: str | bytes,
+ dtype: DTypeLike | None = ...,
+ count: SupportsIndex = ...,
+ *,
+ sep: str,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def frompyfunc( # type: ignore[overload-overlap]
+ func: Callable[[Any], _ReturnType], /,
+ nin: L[1],
+ nout: L[1],
+ *,
+ identity: None = None,
+) -> _PyFunc_Nin1_Nout1[_ReturnType, None]: ...
+@overload
+def frompyfunc( # type: ignore[overload-overlap]
+ func: Callable[[Any], _ReturnType], /,
+ nin: L[1],
+ nout: L[1],
+ *,
+ identity: _IDType,
+) -> _PyFunc_Nin1_Nout1[_ReturnType, _IDType]: ...
+@overload
+def frompyfunc( # type: ignore[overload-overlap]
+ func: Callable[[Any, Any], _ReturnType], /,
+ nin: L[2],
+ nout: L[1],
+ *,
+ identity: None = None,
+) -> _PyFunc_Nin2_Nout1[_ReturnType, None]: ...
+@overload
+def frompyfunc( # type: ignore[overload-overlap]
+ func: Callable[[Any, Any], _ReturnType], /,
+ nin: L[2],
+ nout: L[1],
+ *,
+ identity: _IDType,
+) -> _PyFunc_Nin2_Nout1[_ReturnType, _IDType]: ...
+@overload
+def frompyfunc( # type: ignore[overload-overlap]
+ func: Callable[..., _ReturnType], /,
+ nin: _Nin,
+ nout: L[1],
+ *,
+ identity: None = None,
+) -> _PyFunc_Nin3P_Nout1[_ReturnType, None, _Nin]: ...
+@overload
+def frompyfunc( # type: ignore[overload-overlap]
+ func: Callable[..., _ReturnType], /,
+ nin: _Nin,
+ nout: L[1],
+ *,
+ identity: _IDType,
+) -> _PyFunc_Nin3P_Nout1[_ReturnType, _IDType, _Nin]: ...
+@overload
+def frompyfunc(
+ func: Callable[..., _2PTuple[_ReturnType]], /,
+ nin: _Nin,
+ nout: _Nout,
+ *,
+ identity: None = None,
+) -> _PyFunc_Nin1P_Nout2P[_ReturnType, None, _Nin, _Nout]: ...
+@overload
+def frompyfunc(
+ func: Callable[..., _2PTuple[_ReturnType]], /,
+ nin: _Nin,
+ nout: _Nout,
+ *,
+ identity: _IDType,
+) -> _PyFunc_Nin1P_Nout2P[_ReturnType, _IDType, _Nin, _Nout]: ...
+@overload
+def frompyfunc(
+ func: Callable[..., Any], /,
+ nin: SupportsIndex,
+ nout: SupportsIndex,
+ *,
+ identity: object | None = ...,
+) -> ufunc: ...
+
+@overload
+def fromfile(
+ file: StrOrBytesPath | _SupportsFileMethods,
+ dtype: None = None,
+ count: SupportsIndex = ...,
+ sep: str = ...,
+ offset: SupportsIndex = ...,
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[float64]: ...
+@overload
+def fromfile(
+ file: StrOrBytesPath | _SupportsFileMethods,
+ dtype: _DTypeLike[_ScalarT],
+ count: SupportsIndex = ...,
+ sep: str = ...,
+ offset: SupportsIndex = ...,
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[_ScalarT]: ...
+@overload
+def fromfile(
+ file: StrOrBytesPath | _SupportsFileMethods,
+ dtype: DTypeLike | None = ...,
+ count: SupportsIndex = ...,
+ sep: str = ...,
+ offset: SupportsIndex = ...,
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def fromiter(
+ iter: Iterable[Any],
+ dtype: _DTypeLike[_ScalarT],
+ count: SupportsIndex = ...,
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[_ScalarT]: ...
+@overload
+def fromiter(
+ iter: Iterable[Any],
+ dtype: DTypeLike | None,
+ count: SupportsIndex = ...,
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[Any]: ...
+
+@overload
+def frombuffer(
+ buffer: _SupportsBuffer,
+ dtype: None = None,
+ count: SupportsIndex = ...,
+ offset: SupportsIndex = ...,
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[float64]: ...
+@overload
+def frombuffer(
+ buffer: _SupportsBuffer,
+ dtype: _DTypeLike[_ScalarT],
+ count: SupportsIndex = ...,
+ offset: SupportsIndex = ...,
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[_ScalarT]: ...
+@overload
+def frombuffer(
+ buffer: _SupportsBuffer,
+ dtype: DTypeLike | None = ...,
+ count: SupportsIndex = ...,
+ offset: SupportsIndex = ...,
+ *,
+ like: _SupportsArrayFunc | None = ...,
+) -> NDArray[Any]: ...
+
+_ArangeScalar: TypeAlias = np.integer | np.floating | np.datetime64 | np.timedelta64
+_ArangeScalarT = TypeVar("_ArangeScalarT", bound=_ArangeScalar)
+
+# keep in sync with ma.core.arange
+# NOTE: The `float64 | Any` return types needed to avoid incompatible overlapping overloads
+@overload # dtype=
+def arange(
+ start_or_stop: _ArangeScalar | float,
+ /,
+ stop: _ArangeScalar | float | None = None,
+ step: _ArangeScalar | float | None = 1,
+ *,
+ dtype: _DTypeLike[_ArangeScalarT],
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array1D[_ArangeScalarT]: ...
+@overload # (int-like, int-like?, int-like?)
+def arange(
+ start_or_stop: _IntLike_co,
+ /,
+ stop: _IntLike_co | None = None,
+ step: _IntLike_co | None = 1,
+ *,
+ dtype: type[int] | _DTypeLike[np.int_] | None = None,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array1D[np.int_]: ...
+@overload # (float, float-like?, float-like?)
+def arange(
+ start_or_stop: float | floating,
+ /,
+ stop: _FloatLike_co | None = None,
+ step: _FloatLike_co | None = 1,
+ *,
+ dtype: type[float] | _DTypeLike[np.float64] | None = None,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array1D[np.float64 | Any]: ...
+@overload # (float-like, float, float-like?)
+def arange(
+ start_or_stop: _FloatLike_co,
+ /,
+ stop: float | floating,
+ step: _FloatLike_co | None = 1,
+ *,
+ dtype: type[float] | _DTypeLike[np.float64] | None = None,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array1D[np.float64 | Any]: ...
+@overload # (timedelta, timedelta-like?, timedelta-like?)
+def arange(
+ start_or_stop: np.timedelta64,
+ /,
+ stop: _TD64Like_co | None = None,
+ step: _TD64Like_co | None = 1,
+ *,
+ dtype: _DTypeLike[np.timedelta64] | None = None,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array1D[np.timedelta64[Incomplete]]: ...
+@overload # (timedelta-like, timedelta, timedelta-like?)
+def arange(
+ start_or_stop: _TD64Like_co,
+ /,
+ stop: np.timedelta64,
+ step: _TD64Like_co | None = 1,
+ *,
+ dtype: _DTypeLike[np.timedelta64] | None = None,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array1D[np.timedelta64[Incomplete]]: ...
+@overload # (datetime, datetime, timedelta-like) (requires both start and stop)
+def arange(
+ start_or_stop: np.datetime64,
+ /,
+ stop: np.datetime64,
+ step: _TD64Like_co | None = 1,
+ *,
+ dtype: _DTypeLike[np.datetime64] | None = None,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array1D[np.datetime64[Incomplete]]: ...
+@overload # (str, str, timedelta-like, dtype=dt64-like) (requires both start and stop)
+def arange(
+ start_or_stop: str,
+ /,
+ stop: str,
+ step: _TD64Like_co | None = 1,
+ *,
+ dtype: _DTypeLike[np.datetime64] | _DT64Codes,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array1D[np.datetime64[Incomplete]]: ...
+@overload # dtype=
+def arange(
+ start_or_stop: _ArangeScalar | float | str,
+ /,
+ stop: _ArangeScalar | float | str | None = None,
+ step: _ArangeScalar | float | None = 1,
+ *,
+ dtype: DTypeLike | None = None,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array1D[Incomplete]: ...
+
+#
+def datetime_data(dtype: str | _DTypeLike[datetime64 | timedelta64], /) -> tuple[str, int]: ...
+
+# The datetime functions perform unsafe casts to `datetime64[D]`,
+# so a lot of different argument types are allowed here
+
+_ToDates: TypeAlias = dt.date | _NestedSequence[dt.date]
+_ToDeltas: TypeAlias = dt.timedelta | _NestedSequence[dt.timedelta]
+
+@overload
+def busday_count(
+ begindates: _ScalarLike_co | dt.date,
+ enddates: _ScalarLike_co | dt.date,
+ weekmask: ArrayLike = "1111100",
+ holidays: ArrayLike | _ToDates = (),
+ busdaycal: busdaycalendar | None = None,
+ out: None = None,
+) -> int_: ...
+@overload
+def busday_count(
+ begindates: ArrayLike | _ToDates,
+ enddates: ArrayLike | _ToDates,
+ weekmask: ArrayLike = "1111100",
+ holidays: ArrayLike | _ToDates = (),
+ busdaycal: busdaycalendar | None = None,
+ out: None = None,
+) -> NDArray[int_]: ...
+@overload
+def busday_count(
+ begindates: ArrayLike | _ToDates,
+ enddates: ArrayLike | _ToDates,
+ weekmask: ArrayLike = "1111100",
+ holidays: ArrayLike | _ToDates = (),
+ busdaycal: busdaycalendar | None = None,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def busday_count(
+ begindates: ArrayLike | _ToDates,
+ enddates: ArrayLike | _ToDates,
+ weekmask: ArrayLike,
+ holidays: ArrayLike | _ToDates,
+ busdaycal: busdaycalendar | None,
+ out: _ArrayT,
+) -> _ArrayT: ...
+
+# `roll="raise"` is (more or less?) equivalent to `casting="safe"`
+@overload
+def busday_offset(
+ dates: datetime64 | dt.date,
+ offsets: _TD64Like_co | dt.timedelta,
+ roll: L["raise"] = "raise",
+ weekmask: ArrayLike = "1111100",
+ holidays: ArrayLike | _ToDates | None = None,
+ busdaycal: busdaycalendar | None = None,
+ out: None = None,
+) -> datetime64: ...
+@overload
+def busday_offset(
+ dates: _ArrayLike[datetime64] | _NestedSequence[dt.date],
+ offsets: _ArrayLikeTD64_co | _ToDeltas,
+ roll: L["raise"] = "raise",
+ weekmask: ArrayLike = "1111100",
+ holidays: ArrayLike | _ToDates | None = None,
+ busdaycal: busdaycalendar | None = None,
+ out: None = None,
+) -> NDArray[datetime64]: ...
+@overload
+def busday_offset(
+ dates: _ArrayLike[datetime64] | _ToDates,
+ offsets: _ArrayLikeTD64_co | _ToDeltas,
+ roll: L["raise"] = "raise",
+ weekmask: ArrayLike = "1111100",
+ holidays: ArrayLike | _ToDates | None = None,
+ busdaycal: busdaycalendar | None = None,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def busday_offset(
+ dates: _ArrayLike[datetime64] | _ToDates,
+ offsets: _ArrayLikeTD64_co | _ToDeltas,
+ roll: L["raise"],
+ weekmask: ArrayLike,
+ holidays: ArrayLike | _ToDates | None,
+ busdaycal: busdaycalendar | None,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def busday_offset(
+ dates: _ScalarLike_co | dt.date,
+ offsets: _ScalarLike_co | dt.timedelta,
+ roll: _RollKind,
+ weekmask: ArrayLike = "1111100",
+ holidays: ArrayLike | _ToDates | None = None,
+ busdaycal: busdaycalendar | None = None,
+ out: None = None,
+) -> datetime64: ...
+@overload
+def busday_offset(
+ dates: ArrayLike | _NestedSequence[dt.date],
+ offsets: ArrayLike | _ToDeltas,
+ roll: _RollKind,
+ weekmask: ArrayLike = "1111100",
+ holidays: ArrayLike | _ToDates | None = None,
+ busdaycal: busdaycalendar | None = None,
+ out: None = None,
+) -> NDArray[datetime64]: ...
+@overload
+def busday_offset(
+ dates: ArrayLike | _ToDates,
+ offsets: ArrayLike | _ToDeltas,
+ roll: _RollKind,
+ weekmask: ArrayLike = "1111100",
+ holidays: ArrayLike | _ToDates | None = None,
+ busdaycal: busdaycalendar | None = None,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def busday_offset(
+ dates: ArrayLike | _ToDates,
+ offsets: ArrayLike | _ToDeltas,
+ roll: _RollKind,
+ weekmask: ArrayLike,
+ holidays: ArrayLike | _ToDates | None,
+ busdaycal: busdaycalendar | None,
+ out: _ArrayT,
+) -> _ArrayT: ...
+
+@overload
+def is_busday(
+ dates: _ScalarLike_co | dt.date,
+ weekmask: ArrayLike = "1111100",
+ holidays: ArrayLike | _ToDates | None = None,
+ busdaycal: busdaycalendar | None = None,
+ out: None = None,
+) -> np.bool: ...
+@overload
+def is_busday(
+ dates: ArrayLike | _NestedSequence[dt.date],
+ weekmask: ArrayLike = "1111100",
+ holidays: ArrayLike | _ToDates | None = None,
+ busdaycal: busdaycalendar | None = None,
+ out: None = None,
+) -> NDArray[np.bool]: ...
+@overload
+def is_busday(
+ dates: ArrayLike | _ToDates,
+ weekmask: ArrayLike = "1111100",
+ holidays: ArrayLike | _ToDates | None = None,
+ busdaycal: busdaycalendar | None = None,
+ *,
+ out: _ArrayT,
+) -> _ArrayT: ...
+@overload
+def is_busday(
+ dates: ArrayLike | _ToDates,
+ weekmask: ArrayLike,
+ holidays: ArrayLike | _ToDates | None,
+ busdaycal: busdaycalendar | None,
+ out: _ArrayT,
+) -> _ArrayT: ...
+
+_TimezoneContext: TypeAlias = L["naive", "UTC", "local"] | dt.tzinfo
+
+@overload
+def datetime_as_string(
+ arr: datetime64 | dt.date,
+ unit: L["auto"] | _UnitKind | None = None,
+ timezone: _TimezoneContext = "naive",
+ casting: _CastingKind = "same_kind",
+) -> str_: ...
+@overload
+def datetime_as_string(
+ arr: _ArrayLikeDT64_co | _NestedSequence[dt.date],
+ unit: L["auto"] | _UnitKind | None = None,
+ timezone: _TimezoneContext = "naive",
+ casting: _CastingKind = "same_kind",
+) -> NDArray[str_]: ...
+
+@overload
+def compare_chararrays(
+ a1: _ArrayLikeStr_co,
+ a2: _ArrayLikeStr_co,
+ cmp: L["<", "<=", "==", ">=", ">", "!="],
+ rstrip: bool,
+) -> NDArray[np.bool]: ...
+@overload
+def compare_chararrays(
+ a1: _ArrayLikeBytes_co,
+ a2: _ArrayLikeBytes_co,
+ cmp: L["<", "<=", "==", ">=", ">", "!="],
+ rstrip: bool,
+) -> NDArray[np.bool]: ...
+
+def add_docstring(obj: Callable[..., Any], docstring: str, /) -> None: ...
+
+_GetItemKeys: TypeAlias = L[
+ "C", "CONTIGUOUS", "C_CONTIGUOUS",
+ "F", "FORTRAN", "F_CONTIGUOUS",
+ "W", "WRITEABLE",
+ "B", "BEHAVED",
+ "O", "OWNDATA",
+ "A", "ALIGNED",
+ "X", "WRITEBACKIFCOPY",
+ "CA", "CARRAY",
+ "FA", "FARRAY",
+ "FNC",
+ "FORC",
+]
+_SetItemKeys: TypeAlias = L[
+ "A", "ALIGNED",
+ "W", "WRITEABLE",
+ "X", "WRITEBACKIFCOPY",
+]
+
+@final
+class flagsobj:
+ __hash__: ClassVar[None] # type: ignore[assignment]
+ aligned: bool
+ # NOTE: deprecated
+ # updateifcopy: bool
+ writeable: bool
+ writebackifcopy: bool
+ @property
+ def behaved(self) -> bool: ...
+ @property
+ def c_contiguous(self) -> bool: ...
+ @property
+ def carray(self) -> bool: ...
+ @property
+ def contiguous(self) -> bool: ...
+ @property
+ def f_contiguous(self) -> bool: ...
+ @property
+ def farray(self) -> bool: ...
+ @property
+ def fnc(self) -> bool: ...
+ @property
+ def forc(self) -> bool: ...
+ @property
+ def fortran(self) -> bool: ...
+ @property
+ def num(self) -> int: ...
+ @property
+ def owndata(self) -> bool: ...
+ def __getitem__(self, key: _GetItemKeys) -> bool: ...
+ def __setitem__(self, key: _SetItemKeys, value: bool) -> None: ...
+
+def nested_iters(
+ op: ArrayLike | Sequence[ArrayLike],
+ axes: Sequence[Sequence[SupportsIndex]],
+ flags: Sequence[_NDIterFlagsKind] | None = ...,
+ op_flags: Sequence[Sequence[_NDIterFlagsOp]] | None = ...,
+ op_dtypes: DTypeLike | Sequence[DTypeLike | None] | None = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingKind = ...,
+ buffersize: SupportsIndex = ...,
+) -> tuple[nditer, ...]: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/numeric.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/numeric.py
new file mode 100644
index 0000000000000000000000000000000000000000..da382b4e8bd2893443eecf77654af3d8b4792b7f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/numeric.py
@@ -0,0 +1,2771 @@
+import builtins
+import functools
+import itertools
+import math
+import numbers
+import operator
+import sys
+import warnings
+
+import numpy as np
+from numpy.exceptions import AxisError
+
+from . import multiarray, numerictypes, numerictypes as nt, overrides, shape_base, umath
+from ._ufunc_config import errstate
+from .multiarray import ( # noqa: F401
+ ALLOW_THREADS,
+ BUFSIZE,
+ CLIP,
+ MAXDIMS,
+ MAY_SHARE_BOUNDS,
+ MAY_SHARE_EXACT,
+ RAISE,
+ WRAP,
+ arange,
+ array,
+ asanyarray,
+ asarray,
+ ascontiguousarray,
+ asfortranarray,
+ broadcast,
+ can_cast,
+ concatenate,
+ copyto,
+ dot,
+ dtype,
+ empty,
+ empty_like,
+ flatiter,
+ from_dlpack,
+ frombuffer,
+ fromfile,
+ fromiter,
+ fromstring,
+ inner,
+ lexsort,
+ matmul,
+ may_share_memory,
+ min_scalar_type,
+ ndarray,
+ nditer,
+ nested_iters,
+ normalize_axis_index,
+ promote_types,
+ putmask,
+ result_type,
+ shares_memory,
+ vdot,
+ vecdot,
+ where,
+ zeros,
+)
+from .overrides import finalize_array_function_like, set_module
+from .umath import NAN, PINF, invert, multiply, sin
+
+bitwise_not = invert
+ufunc = type(sin)
+newaxis = None
+
+array_function_dispatch = functools.partial(
+ overrides.array_function_dispatch, module='numpy')
+
+
+__all__ = [
+ 'newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc',
+ 'arange', 'array', 'asarray', 'asanyarray', 'ascontiguousarray',
+ 'asfortranarray', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype',
+ 'fromstring', 'fromfile', 'frombuffer', 'from_dlpack', 'where',
+ 'argwhere', 'copyto', 'concatenate', 'lexsort', 'astype',
+ 'can_cast', 'promote_types', 'min_scalar_type',
+ 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like',
+ 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll',
+ 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian',
+ 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction',
+ 'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones',
+ 'identity', 'allclose', 'putmask',
+ 'flatnonzero', 'inf', 'nan', 'False_', 'True_', 'bitwise_not',
+ 'full', 'full_like', 'matmul', 'vecdot', 'shares_memory',
+ 'may_share_memory']
+
+
+def _zeros_like_dispatcher(
+ a, dtype=None, order=None, subok=None, shape=None, *, device=None
+):
+ return (a,)
+
+
+@array_function_dispatch(_zeros_like_dispatcher)
+def zeros_like(
+ a, dtype=None, order='K', subok=True, shape=None, *, device=None
+):
+ """
+ Return an array of zeros with the same shape and type as a given array.
+
+ Parameters
+ ----------
+ a : array_like
+ The shape and data-type of `a` define these same attributes of
+ the returned array.
+ dtype : data-type, optional
+ Overrides the data type of the result.
+ order : {'C', 'F', 'A', or 'K'}, optional
+ Overrides the memory layout of the result. 'C' means C-order,
+ 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
+ 'C' otherwise. 'K' means match the layout of `a` as closely
+ as possible.
+ subok : bool, optional.
+ If True, then the newly created array will use the sub-class
+ type of `a`, otherwise it will be a base-class array. Defaults
+ to True.
+ shape : int or sequence of ints, optional.
+ Overrides the shape of the result. If order='K' and the number of
+ dimensions is unchanged, will try to keep order, otherwise,
+ order='C' is implied.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of zeros with the same shape and type as `a`.
+
+ See Also
+ --------
+ empty_like : Return an empty array with shape and type of input.
+ ones_like : Return an array of ones with shape and type of input.
+ full_like : Return a new array with shape of input filled with value.
+ zeros : Return a new array setting values to zero.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6)
+ >>> x = x.reshape((2, 3))
+ >>> x
+ array([[0, 1, 2],
+ [3, 4, 5]])
+ >>> np.zeros_like(x)
+ array([[0, 0, 0],
+ [0, 0, 0]])
+
+ >>> y = np.arange(3, dtype=float)
+ >>> y
+ array([0., 1., 2.])
+ >>> np.zeros_like(y)
+ array([0., 0., 0.])
+
+ """
+ res = empty_like(
+ a, dtype=dtype, order=order, subok=subok, shape=shape, device=device
+ )
+ # needed instead of a 0 to get same result as zeros for string dtypes
+ z = zeros(1, dtype=res.dtype)
+ multiarray.copyto(res, z, casting='unsafe')
+ return res
+
+
+@finalize_array_function_like
+@set_module('numpy')
+def ones(shape, dtype=None, order='C', *, device=None, like=None):
+ """
+ Return a new array of given shape and type, filled with ones.
+
+ Parameters
+ ----------
+ shape : int or sequence of ints
+ Shape of the new array, e.g., ``(2, 3)`` or ``2``.
+ dtype : data-type, optional
+ The desired data-type for the array, e.g., `numpy.int8`. Default is
+ `numpy.float64`.
+ order : {'C', 'F'}, optional, default: C
+ Whether to store multi-dimensional data in row-major
+ (C-style) or column-major (Fortran-style) order in
+ memory.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of ones with the given shape, dtype, and order.
+
+ See Also
+ --------
+ ones_like : Return an array of ones with shape and type of input.
+ empty : Return a new uninitialized array.
+ zeros : Return a new array setting values to zero.
+ full : Return a new array of given shape filled with value.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.ones(5)
+ array([1., 1., 1., 1., 1.])
+
+ >>> np.ones((5,), dtype=int)
+ array([1, 1, 1, 1, 1])
+
+ >>> np.ones((2, 1))
+ array([[1.],
+ [1.]])
+
+ >>> s = (2,2)
+ >>> np.ones(s)
+ array([[1., 1.],
+ [1., 1.]])
+
+ """
+ if like is not None:
+ return _ones_with_like(
+ like, shape, dtype=dtype, order=order, device=device
+ )
+
+ a = empty(shape, dtype, order, device=device)
+ multiarray.copyto(a, 1, casting='unsafe')
+ return a
+
+
+_ones_with_like = array_function_dispatch()(ones)
+
+
+def _ones_like_dispatcher(
+ a, dtype=None, order=None, subok=None, shape=None, *, device=None
+):
+ return (a,)
+
+
+@array_function_dispatch(_ones_like_dispatcher)
+def ones_like(
+ a, dtype=None, order='K', subok=True, shape=None, *, device=None
+):
+ """
+ Return an array of ones with the same shape and type as a given array.
+
+ Parameters
+ ----------
+ a : array_like
+ The shape and data-type of `a` define these same attributes of
+ the returned array.
+ dtype : data-type, optional
+ Overrides the data type of the result.
+ order : {'C', 'F', 'A', or 'K'}, optional
+ Overrides the memory layout of the result. 'C' means C-order,
+ 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
+ 'C' otherwise. 'K' means match the layout of `a` as closely
+ as possible.
+ subok : bool, optional.
+ If True, then the newly created array will use the sub-class
+ type of `a`, otherwise it will be a base-class array. Defaults
+ to True.
+ shape : int or sequence of ints, optional.
+ Overrides the shape of the result. If order='K' and the number of
+ dimensions is unchanged, will try to keep order, otherwise,
+ order='C' is implied.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of ones with the same shape and type as `a`.
+
+ See Also
+ --------
+ empty_like : Return an empty array with shape and type of input.
+ zeros_like : Return an array of zeros with shape and type of input.
+ full_like : Return a new array with shape of input filled with value.
+ ones : Return a new array setting values to one.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6)
+ >>> x = x.reshape((2, 3))
+ >>> x
+ array([[0, 1, 2],
+ [3, 4, 5]])
+ >>> np.ones_like(x)
+ array([[1, 1, 1],
+ [1, 1, 1]])
+
+ >>> y = np.arange(3, dtype=float)
+ >>> y
+ array([0., 1., 2.])
+ >>> np.ones_like(y)
+ array([1., 1., 1.])
+
+ """
+ res = empty_like(
+ a, dtype=dtype, order=order, subok=subok, shape=shape, device=device
+ )
+ multiarray.copyto(res, 1, casting='unsafe')
+ return res
+
+
+def _full_dispatcher(
+ shape, fill_value, dtype=None, order=None, *, device=None, like=None
+):
+ return (like,)
+
+
+@finalize_array_function_like
+@set_module('numpy')
+def full(shape, fill_value, dtype=None, order='C', *, device=None, like=None):
+ """
+ Return a new array of given shape and type, filled with `fill_value`.
+
+ Parameters
+ ----------
+ shape : int or sequence of ints
+ Shape of the new array, e.g., ``(2, 3)`` or ``2``.
+ fill_value : scalar or array_like
+ Fill value.
+ dtype : data-type, optional
+ The desired data-type for the array The default, None, means
+ ``np.array(fill_value).dtype``.
+ order : {'C', 'F'}, optional
+ Whether to store multidimensional data in C- or Fortran-contiguous
+ (row- or column-wise) order in memory.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of `fill_value` with the given shape, dtype, and order.
+
+ See Also
+ --------
+ full_like : Return a new array with shape of input filled with value.
+ empty : Return a new uninitialized array.
+ ones : Return a new array setting values to one.
+ zeros : Return a new array setting values to zero.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.full((2, 2), np.inf)
+ array([[inf, inf],
+ [inf, inf]])
+ >>> np.full((2, 2), 10)
+ array([[10, 10],
+ [10, 10]])
+
+ >>> np.full((2, 2), [1, 2])
+ array([[1, 2],
+ [1, 2]])
+
+ """
+ if like is not None:
+ return _full_with_like(
+ like, shape, fill_value, dtype=dtype, order=order, device=device
+ )
+
+ if dtype is None:
+ fill_value = asarray(fill_value)
+ dtype = fill_value.dtype
+ a = empty(shape, dtype, order, device=device)
+ multiarray.copyto(a, fill_value, casting='unsafe')
+ return a
+
+
+_full_with_like = array_function_dispatch()(full)
+
+
+def _full_like_dispatcher(
+ a, fill_value, dtype=None, order=None, subok=None, shape=None,
+ *, device=None
+):
+ return (a,)
+
+
+@array_function_dispatch(_full_like_dispatcher)
+def full_like(
+ a, fill_value, dtype=None, order='K', subok=True, shape=None,
+ *, device=None
+):
+ """
+ Return a full array with the same shape and type as a given array.
+
+ Parameters
+ ----------
+ a : array_like
+ The shape and data-type of `a` define these same attributes of
+ the returned array.
+ fill_value : array_like
+ Fill value.
+ dtype : data-type, optional
+ Overrides the data type of the result.
+ order : {'C', 'F', 'A', or 'K'}, optional
+ Overrides the memory layout of the result. 'C' means C-order,
+ 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
+ 'C' otherwise. 'K' means match the layout of `a` as closely
+ as possible.
+ subok : bool, optional.
+ If True, then the newly created array will use the sub-class
+ type of `a`, otherwise it will be a base-class array. Defaults
+ to True.
+ shape : int or sequence of ints, optional.
+ Overrides the shape of the result. If order='K' and the number of
+ dimensions is unchanged, will try to keep order, otherwise,
+ order='C' is implied.
+ device : str, optional
+ The device on which to place the created array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.0.0
+
+ Returns
+ -------
+ out : ndarray
+ Array of `fill_value` with the same shape and type as `a`.
+
+ See Also
+ --------
+ empty_like : Return an empty array with shape and type of input.
+ ones_like : Return an array of ones with shape and type of input.
+ zeros_like : Return an array of zeros with shape and type of input.
+ full : Return a new array of given shape filled with value.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6, dtype=int)
+ >>> np.full_like(x, 1)
+ array([1, 1, 1, 1, 1, 1])
+ >>> np.full_like(x, 0.1)
+ array([0, 0, 0, 0, 0, 0])
+ >>> np.full_like(x, 0.1, dtype=np.double)
+ array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
+ >>> np.full_like(x, np.nan, dtype=np.double)
+ array([nan, nan, nan, nan, nan, nan])
+
+ >>> y = np.arange(6, dtype=np.double)
+ >>> np.full_like(y, 0.1)
+ array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
+
+ >>> y = np.zeros([2, 2, 3], dtype=int)
+ >>> np.full_like(y, [0, 0, 255])
+ array([[[ 0, 0, 255],
+ [ 0, 0, 255]],
+ [[ 0, 0, 255],
+ [ 0, 0, 255]]])
+ """
+ res = empty_like(
+ a, dtype=dtype, order=order, subok=subok, shape=shape, device=device
+ )
+ multiarray.copyto(res, fill_value, casting='unsafe')
+ return res
+
+
+def _count_nonzero_dispatcher(a, axis=None, *, keepdims=None):
+ return (a,)
+
+
+@array_function_dispatch(_count_nonzero_dispatcher)
+def count_nonzero(a, axis=None, *, keepdims=False):
+ """
+ Counts the number of non-zero values in the array ``a``.
+
+ The word "non-zero" is in reference to the Python 2.x
+ built-in method ``__nonzero__()`` (renamed ``__bool__()``
+ in Python 3.x) of Python objects that tests an object's
+ "truthfulness". For example, any number is considered
+ truthful if it is nonzero, whereas any string is considered
+ truthful if it is not the empty string. Thus, this function
+ (recursively) counts how many elements in ``a`` (and in
+ sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()``
+ method evaluated to ``True``.
+
+ Parameters
+ ----------
+ a : array_like
+ The array for which to count non-zeros.
+ axis : int or tuple, optional
+ Axis or tuple of axes along which to count non-zeros.
+ Default is None, meaning that non-zeros will be counted
+ along a flattened version of ``a``.
+ keepdims : bool, optional
+ If this is set to True, the axes that are counted are left
+ in the result as dimensions with size one. With this option,
+ the result will broadcast correctly against the input array.
+
+ Returns
+ -------
+ count : int or array of int
+ Number of non-zero values in the array along a given axis.
+ Otherwise, the total number of non-zero values in the array
+ is returned.
+
+ See Also
+ --------
+ nonzero : Return the coordinates of all the non-zero values.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.count_nonzero(np.eye(4))
+ np.int64(4)
+ >>> a = np.array([[0, 1, 7, 0],
+ ... [3, 0, 2, 19]])
+ >>> np.count_nonzero(a)
+ np.int64(5)
+ >>> np.count_nonzero(a, axis=0)
+ array([1, 1, 2, 1])
+ >>> np.count_nonzero(a, axis=1)
+ array([2, 3])
+ >>> np.count_nonzero(a, axis=1, keepdims=True)
+ array([[2],
+ [3]])
+ """
+ if axis is None and not keepdims:
+ return multiarray.count_nonzero(a)
+
+ a = asanyarray(a)
+
+ # TODO: this works around .astype(bool) not working properly (gh-9847)
+ if np.issubdtype(a.dtype, np.character):
+ a_bool = a != a.dtype.type()
+ else:
+ a_bool = a.astype(np.bool, copy=False)
+
+ return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims)
+
+
+@set_module('numpy')
+def isfortran(a):
+ """
+ Check if the array is Fortran contiguous but *not* C contiguous.
+
+ This function is obsolete. If you only want to check if an array is Fortran
+ contiguous use ``a.flags.f_contiguous`` instead.
+
+ Parameters
+ ----------
+ a : ndarray
+ Input array.
+
+ Returns
+ -------
+ isfortran : bool
+ Returns True if the array is Fortran contiguous but *not* C contiguous.
+
+
+ Examples
+ --------
+
+ np.array allows to specify whether the array is written in C-contiguous
+ order (last index varies the fastest), or FORTRAN-contiguous order in
+ memory (first index varies the fastest).
+
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
+ >>> a
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> np.isfortran(a)
+ False
+
+ >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F')
+ >>> b
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> np.isfortran(b)
+ True
+
+
+ The transpose of a C-ordered array is a FORTRAN-ordered array.
+
+ >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
+ >>> a
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> np.isfortran(a)
+ False
+ >>> b = a.T
+ >>> b
+ array([[1, 4],
+ [2, 5],
+ [3, 6]])
+ >>> np.isfortran(b)
+ True
+
+ C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
+
+ >>> np.isfortran(np.array([1, 2], order='F'))
+ False
+
+ """
+ return a.flags.fnc
+
+
+def _argwhere_dispatcher(a):
+ return (a,)
+
+
+@array_function_dispatch(_argwhere_dispatcher)
+def argwhere(a):
+ """
+ Find the indices of array elements that are non-zero, grouped by element.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+
+ Returns
+ -------
+ index_array : (N, a.ndim) ndarray
+ Indices of elements that are non-zero. Indices are grouped by element.
+ This array will have shape ``(N, a.ndim)`` where ``N`` is the number of
+ non-zero items.
+
+ See Also
+ --------
+ where, nonzero
+
+ Notes
+ -----
+ ``np.argwhere(a)`` is almost the same as ``np.transpose(np.nonzero(a))``,
+ but produces a result of the correct shape for a 0D array.
+
+ The output of ``argwhere`` is not suitable for indexing arrays.
+ For this purpose use ``nonzero(a)`` instead.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(6).reshape(2,3)
+ >>> x
+ array([[0, 1, 2],
+ [3, 4, 5]])
+ >>> np.argwhere(x>1)
+ array([[0, 2],
+ [1, 0],
+ [1, 1],
+ [1, 2]])
+
+ """
+ # nonzero does not behave well on 0d, so promote to 1d
+ if np.ndim(a) == 0:
+ a = shape_base.atleast_1d(a)
+ # then remove the added dimension
+ return argwhere(a)[:, :0]
+ return transpose(nonzero(a))
+
+
+def _flatnonzero_dispatcher(a):
+ return (a,)
+
+
+@array_function_dispatch(_flatnonzero_dispatcher)
+def flatnonzero(a):
+ """
+ Return indices that are non-zero in the flattened version of a.
+
+ This is equivalent to ``np.nonzero(np.ravel(a))[0]``.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data.
+
+ Returns
+ -------
+ res : ndarray
+ Output array, containing the indices of the elements of ``a.ravel()``
+ that are non-zero.
+
+ See Also
+ --------
+ nonzero : Return the indices of the non-zero elements of the input array.
+ ravel : Return a 1-D array containing the elements of the input array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(-2, 3)
+ >>> x
+ array([-2, -1, 0, 1, 2])
+ >>> np.flatnonzero(x)
+ array([0, 1, 3, 4])
+
+ Use the indices of the non-zero elements as an index array to extract
+ these elements:
+
+ >>> x.ravel()[np.flatnonzero(x)]
+ array([-2, -1, 1, 2])
+
+ """
+ return np.nonzero(np.ravel(a))[0]
+
+
+def _correlate_dispatcher(a, v, mode=None):
+ return (a, v)
+
+
+@array_function_dispatch(_correlate_dispatcher)
+def correlate(a, v, mode='valid'):
+ r"""
+ Cross-correlation of two 1-dimensional sequences.
+
+ This function computes the correlation as generally defined in signal
+ processing texts [1]_:
+
+ .. math:: c_k = \sum_n a_{n+k} \cdot \overline{v}_n
+
+ with a and v sequences being zero-padded where necessary and
+ :math:`\overline v` denoting complex conjugation.
+
+ Parameters
+ ----------
+ a, v : array_like
+ Input sequences.
+ mode : {'valid', 'same', 'full'}, optional
+ Refer to the `convolve` docstring. Note that the default
+ is 'valid', unlike `convolve`, which uses 'full'.
+
+ Returns
+ -------
+ out : ndarray
+ Discrete cross-correlation of `a` and `v`.
+
+ See Also
+ --------
+ convolve : Discrete, linear convolution of two one-dimensional sequences.
+ scipy.signal.correlate : uses FFT which has superior performance
+ on large arrays.
+
+ Notes
+ -----
+ The definition of correlation above is not unique and sometimes
+ correlation may be defined differently. Another common definition is [1]_:
+
+ .. math:: c'_k = \sum_n a_{n} \cdot \overline{v_{n+k}}
+
+ which is related to :math:`c_k` by :math:`c'_k = c_{-k}`.
+
+ `numpy.correlate` may perform slowly in large arrays (i.e. n = 1e5)
+ because it does not use the FFT to compute the convolution; in that case,
+ `scipy.signal.correlate` might be preferable.
+
+ References
+ ----------
+ .. [1] Wikipedia, "Cross-correlation",
+ https://en.wikipedia.org/wiki/Cross-correlation
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.correlate([1, 2, 3], [0, 1, 0.5])
+ array([3.5])
+ >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
+ array([2. , 3.5, 3. ])
+ >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
+ array([0.5, 2. , 3.5, 3. , 0. ])
+
+ Using complex sequences:
+
+ >>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
+ array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ])
+
+ Note that you get the time reversed, complex conjugated result
+ (:math:`\overline{c_{-k}}`) when the two input sequences a and v change
+ places:
+
+ >>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
+ array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j])
+
+ """
+ return multiarray.correlate2(a, v, mode)
+
+
+def _convolve_dispatcher(a, v, mode=None):
+ return (a, v)
+
+
+@array_function_dispatch(_convolve_dispatcher)
+def convolve(a, v, mode='full'):
+ """
+ Returns the discrete, linear convolution of two one-dimensional sequences.
+
+ The convolution operator is often seen in signal processing, where it
+ models the effect of a linear time-invariant system on a signal [1]_. In
+ probability theory, the sum of two independent random variables is
+ distributed according to the convolution of their individual
+ distributions.
+
+ If `v` is longer than `a`, the arrays are swapped before computation.
+
+ Parameters
+ ----------
+ a : (N,) array_like
+ First one-dimensional input array.
+ v : (M,) array_like
+ Second one-dimensional input array.
+ mode : {'full', 'valid', 'same'}, optional
+ 'full':
+ By default, mode is 'full'. This returns the convolution
+ at each point of overlap, with an output shape of (N+M-1,). At
+ the end-points of the convolution, the signals do not overlap
+ completely, and boundary effects may be seen.
+
+ 'same':
+ Mode 'same' returns output of length ``max(M, N)``. Boundary
+ effects are still visible.
+
+ 'valid':
+ Mode 'valid' returns output of length
+ ``max(M, N) - min(M, N) + 1``. The convolution product is only given
+ for points where the signals overlap completely. Values outside
+ the signal boundary have no effect.
+
+ Returns
+ -------
+ out : ndarray
+ Discrete, linear convolution of `a` and `v`.
+
+ See Also
+ --------
+ scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier
+ Transform.
+ scipy.linalg.toeplitz : Used to construct the convolution operator.
+ polymul : Polynomial multiplication. Same output as convolve, but also
+ accepts poly1d objects as input.
+
+ Notes
+ -----
+ The discrete convolution operation is defined as
+
+ .. math:: (a * v)_n = \\sum_{m = -\\infty}^{\\infty} a_m v_{n - m}
+
+ It can be shown that a convolution :math:`x(t) * y(t)` in time/space
+ is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier
+ domain, after appropriate padding (padding is necessary to prevent
+ circular convolution). Since multiplication is more efficient (faster)
+ than convolution, the function `scipy.signal.fftconvolve` exploits the
+ FFT to calculate the convolution of large data-sets.
+
+ References
+ ----------
+ .. [1] Wikipedia, "Convolution",
+ https://en.wikipedia.org/wiki/Convolution
+
+ Examples
+ --------
+ Note how the convolution operator flips the second array
+ before "sliding" the two across one another:
+
+ >>> import numpy as np
+ >>> np.convolve([1, 2, 3], [0, 1, 0.5])
+ array([0. , 1. , 2.5, 4. , 1.5])
+
+ Only return the middle values of the convolution.
+ Contains boundary effects, where zeros are taken
+ into account:
+
+ >>> np.convolve([1,2,3],[0,1,0.5], 'same')
+ array([1. , 2.5, 4. ])
+
+ The two arrays are of the same length, so there
+ is only one position where they completely overlap:
+
+ >>> np.convolve([1,2,3],[0,1,0.5], 'valid')
+ array([2.5])
+
+ """
+ a, v = array(a, copy=None, ndmin=1), array(v, copy=None, ndmin=1)
+ if len(a) == 0:
+ raise ValueError('a cannot be empty')
+ if len(v) == 0:
+ raise ValueError('v cannot be empty')
+ if len(v) > len(a):
+ a, v = v, a
+ return multiarray.correlate(a, v[::-1], mode)
+
+
+def _outer_dispatcher(a, b, out=None):
+ return (a, b, out)
+
+
+@array_function_dispatch(_outer_dispatcher)
+def outer(a, b, out=None):
+ """
+ Compute the outer product of two vectors.
+
+ Given two vectors `a` and `b` of length ``M`` and ``N``, respectively,
+ the outer product [1]_ is::
+
+ [[a_0*b_0 a_0*b_1 ... a_0*b_{N-1} ]
+ [a_1*b_0 .
+ [ ... .
+ [a_{M-1}*b_0 a_{M-1}*b_{N-1} ]]
+
+ Parameters
+ ----------
+ a : (M,) array_like
+ First input vector. Input is flattened if
+ not already 1-dimensional.
+ b : (N,) array_like
+ Second input vector. Input is flattened if
+ not already 1-dimensional.
+ out : (M, N) ndarray, optional
+ A location where the result is stored
+
+ Returns
+ -------
+ out : (M, N) ndarray
+ ``out[i, j] = a[i] * b[j]``
+
+ See also
+ --------
+ inner
+ einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent.
+ ufunc.outer : A generalization to dimensions other than 1D and other
+ operations. ``np.multiply.outer(a.ravel(), b.ravel())``
+ is the equivalent.
+ linalg.outer : An Array API compatible variation of ``np.outer``,
+ which accepts 1-dimensional inputs only.
+ tensordot : ``np.tensordot(a.ravel(), b.ravel(), axes=((), ()))``
+ is the equivalent.
+
+ References
+ ----------
+ .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd
+ ed., Baltimore, MD, Johns Hopkins University Press, 1996,
+ pg. 8.
+
+ Examples
+ --------
+ Make a (*very* coarse) grid for computing a Mandelbrot set:
+
+ >>> import numpy as np
+ >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
+ >>> rl
+ array([[-2., -1., 0., 1., 2.],
+ [-2., -1., 0., 1., 2.],
+ [-2., -1., 0., 1., 2.],
+ [-2., -1., 0., 1., 2.],
+ [-2., -1., 0., 1., 2.]])
+ >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
+ >>> im
+ array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
+ [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
+ [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
+ [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
+ [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
+ >>> grid = rl + im
+ >>> grid
+ array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],
+ [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],
+ [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],
+ [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],
+ [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])
+
+ An example using a "vector" of letters:
+
+ >>> x = np.array(['a', 'b', 'c'], dtype=object)
+ >>> np.outer(x, [1, 2, 3])
+ array([['a', 'aa', 'aaa'],
+ ['b', 'bb', 'bbb'],
+ ['c', 'cc', 'ccc']], dtype=object)
+
+ """
+ a = asarray(a)
+ b = asarray(b)
+ return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out)
+
+
+def _tensordot_dispatcher(a, b, axes=None):
+ return (a, b)
+
+
+@array_function_dispatch(_tensordot_dispatcher)
+def tensordot(a, b, axes=2):
+ """
+ Compute tensor dot product along specified axes.
+
+ Given two tensors, `a` and `b`, and an array_like object containing
+ two array_like objects, ``(a_axes, b_axes)``, sum the products of
+ `a`'s and `b`'s elements (components) over the axes specified by
+ ``a_axes`` and ``b_axes``. The third argument can be a single non-negative
+ integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions
+ of `a` and the first ``N`` dimensions of `b` are summed over.
+
+ Parameters
+ ----------
+ a, b : array_like
+ Tensors to "dot".
+
+ axes : int or (2,) array_like
+ * integer_like
+ If an int N, sum over the last N axes of `a` and the first N axes
+ of `b` in order. The sizes of the corresponding axes must match.
+ * (2,) array_like
+ Or, a list of axes to be summed over, first sequence applying to `a`,
+ second to `b`. Both elements array_like must be of the same length.
+ Each axis may appear at most once; repeated axes are not allowed.
+ For example, ``axes=([1, 1], [0, 0])`` is invalid.
+ Returns
+ -------
+ output : ndarray
+ The tensor dot product of the input.
+
+ See Also
+ --------
+ dot, einsum
+
+ Notes
+ -----
+ Three common use cases are:
+ * ``axes = 0`` : tensor product :math:`a\\otimes b`
+ * ``axes = 1`` : tensor dot product :math:`a\\cdot b`
+ * ``axes = 2`` : (default) tensor double contraction :math:`a:b`
+
+ When `axes` is integer_like, the sequence of axes for evaluation
+ will be: from the -Nth axis to the -1th axis in `a`,
+ and from the 0th axis to (N-1)th axis in `b`.
+ For example, ``axes = 2`` is the equal to
+ ``axes = [[-2, -1], [0, 1]]``.
+ When N-1 is smaller than 0, or when -N is larger than -1,
+ the element of `a` and `b` are defined as the `axes`.
+
+ When there is more than one axis to sum over - and they are not the last
+ (first) axes of `a` (`b`) - the argument `axes` should consist of
+ two sequences of the same length, with the first axis to sum over given
+ first in both sequences, the second axis second, and so forth.
+ The calculation can be referred to ``numpy.einsum``.
+
+ For example, if ``a.shape == (2, 3, 4)`` and ``b.shape == (3, 4, 5)``,
+ then ``axes=([1, 2], [0, 1])`` sums over the ``(3, 4)`` dimensions of
+ both arrays and produces an output of shape ``(2, 5)``.
+
+ Each summation axis corresponds to a distinct contraction index; repeating
+ an axis (for example ``axes=([1, 1], [0, 0])``) is invalid.
+
+ The shape of the result consists of the non-contracted axes of the
+ first tensor, followed by the non-contracted axes of the second.
+
+ Examples
+ --------
+ An example on integer_like:
+
+ >>> a_0 = np.array([[1, 2], [3, 4]])
+ >>> b_0 = np.array([[5, 6], [7, 8]])
+ >>> c_0 = np.tensordot(a_0, b_0, axes=0)
+ >>> c_0.shape
+ (2, 2, 2, 2)
+ >>> c_0
+ array([[[[ 5, 6],
+ [ 7, 8]],
+ [[10, 12],
+ [14, 16]]],
+ [[[15, 18],
+ [21, 24]],
+ [[20, 24],
+ [28, 32]]]])
+
+ An example on array_like:
+
+ >>> a = np.arange(60.).reshape(3,4,5)
+ >>> b = np.arange(24.).reshape(4,3,2)
+ >>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
+ >>> c.shape
+ (5, 2)
+ >>> c
+ array([[4400., 4730.],
+ [4532., 4874.],
+ [4664., 5018.],
+ [4796., 5162.],
+ [4928., 5306.]])
+
+ A slower but equivalent way of computing the same...
+
+ >>> d = np.zeros((5,2))
+ >>> for i in range(5):
+ ... for j in range(2):
+ ... for k in range(3):
+ ... for n in range(4):
+ ... d[i,j] += a[k,n,i] * b[n,k,j]
+ >>> c == d
+ array([[ True, True],
+ [ True, True],
+ [ True, True],
+ [ True, True],
+ [ True, True]])
+
+ An extended example taking advantage of the overloading of + and \\*:
+
+ >>> a = np.array(range(1, 9)).reshape((2, 2, 2))
+ >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
+ >>> A = A.reshape((2, 2))
+ >>> a; A
+ array([[[1, 2],
+ [3, 4]],
+ [[5, 6],
+ [7, 8]]])
+ array([['a', 'b'],
+ ['c', 'd']], dtype=object)
+
+ >>> np.tensordot(a, A) # third argument default is 2 for double-contraction
+ array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
+
+ >>> np.tensordot(a, A, 1)
+ array([[['acc', 'bdd'],
+ ['aaacccc', 'bbbdddd']],
+ [['aaaaacccccc', 'bbbbbdddddd'],
+ ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
+
+ >>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
+ array([[[[['a', 'b'],
+ ['c', 'd']],
+ ...
+
+ >>> np.tensordot(a, A, (0, 1))
+ array([[['abbbbb', 'cddddd'],
+ ['aabbbbbb', 'ccdddddd']],
+ [['aaabbbbbbb', 'cccddddddd'],
+ ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
+
+ >>> np.tensordot(a, A, (2, 1))
+ array([[['abb', 'cdd'],
+ ['aaabbbb', 'cccdddd']],
+ [['aaaaabbbbbb', 'cccccdddddd'],
+ ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
+
+ >>> np.tensordot(a, A, ((0, 1), (0, 1)))
+ array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
+
+ >>> np.tensordot(a, A, ((2, 1), (1, 0)))
+ array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
+
+ """
+ try:
+ iter(axes)
+ except Exception:
+ axes_a = list(range(-axes, 0))
+ axes_b = list(range(axes))
+ else:
+ axes_a, axes_b = axes
+ try:
+ na = len(axes_a)
+ axes_a = list(axes_a)
+ except TypeError:
+ axes_a = [axes_a]
+ na = 1
+ try:
+ nb = len(axes_b)
+ axes_b = list(axes_b)
+ except TypeError:
+ axes_b = [axes_b]
+ nb = 1
+
+ if len(set(axes_a)) != len(axes_a):
+ raise ValueError("duplicate axes are not allowed in tensordot")
+ if len(set(axes_b)) != len(axes_b):
+ raise ValueError("duplicate axes are not allowed in tensordot")
+
+ a, b = asarray(a), asarray(b)
+ as_ = a.shape
+ nda = a.ndim
+ bs = b.shape
+ ndb = b.ndim
+ equal = True
+ if na != nb:
+ equal = False
+ else:
+ for k in range(na):
+ if as_[axes_a[k]] != bs[axes_b[k]]:
+ equal = False
+ break
+ if axes_a[k] < 0:
+ axes_a[k] += nda
+ if axes_b[k] < 0:
+ axes_b[k] += ndb
+ if not equal:
+ raise ValueError("shape-mismatch for sum")
+
+ # Move the axes to sum over to the end of "a"
+ # and to the front of "b"
+ notin = [k for k in range(nda) if k not in axes_a]
+ newaxes_a = notin + axes_a
+ N2 = math.prod(as_[axis] for axis in axes_a)
+ newshape_a = (math.prod(as_[ax] for ax in notin), N2)
+ olda = [as_[axis] for axis in notin]
+
+ notin = [k for k in range(ndb) if k not in axes_b]
+ newaxes_b = axes_b + notin
+ N2 = math.prod(bs[axis] for axis in axes_b)
+ newshape_b = (N2, math.prod(bs[ax] for ax in notin))
+ oldb = [bs[axis] for axis in notin]
+
+ at = a.transpose(newaxes_a).reshape(newshape_a)
+ bt = b.transpose(newaxes_b).reshape(newshape_b)
+ res = dot(at, bt)
+ return res.reshape(olda + oldb)
+
+
+def _roll_dispatcher(a, shift, axis=None):
+ return (a,)
+
+
+@array_function_dispatch(_roll_dispatcher)
+def roll(a, shift, axis=None):
+ """
+ Roll array elements along a given axis.
+
+ Elements that roll beyond the last position are re-introduced at
+ the first.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ shift : int or tuple of ints
+ The number of places by which elements are shifted. If a tuple,
+ then `axis` must be a tuple of the same size, and each of the
+ given axes is shifted by the corresponding number. If an int
+ while `axis` is a tuple of ints, then the same value is used for
+ all given axes.
+ axis : int or tuple of ints, optional
+ Axis or axes along which elements are shifted. By default, the
+ array is flattened before shifting, after which the original
+ shape is restored.
+
+ Returns
+ -------
+ res : ndarray
+ Output array, with the same shape as `a`.
+
+ See Also
+ --------
+ rollaxis : Roll the specified axis backwards, until it lies in a
+ given position.
+
+ Notes
+ -----
+ Supports rolling over multiple dimensions simultaneously.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.arange(10)
+ >>> np.roll(x, 2)
+ array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
+ >>> np.roll(x, -2)
+ array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
+
+ >>> x2 = np.reshape(x, (2, 5))
+ >>> x2
+ array([[0, 1, 2, 3, 4],
+ [5, 6, 7, 8, 9]])
+ >>> np.roll(x2, 1)
+ array([[9, 0, 1, 2, 3],
+ [4, 5, 6, 7, 8]])
+ >>> np.roll(x2, -1)
+ array([[1, 2, 3, 4, 5],
+ [6, 7, 8, 9, 0]])
+ >>> np.roll(x2, 1, axis=0)
+ array([[5, 6, 7, 8, 9],
+ [0, 1, 2, 3, 4]])
+ >>> np.roll(x2, -1, axis=0)
+ array([[5, 6, 7, 8, 9],
+ [0, 1, 2, 3, 4]])
+ >>> np.roll(x2, 1, axis=1)
+ array([[4, 0, 1, 2, 3],
+ [9, 5, 6, 7, 8]])
+ >>> np.roll(x2, -1, axis=1)
+ array([[1, 2, 3, 4, 0],
+ [6, 7, 8, 9, 5]])
+ >>> np.roll(x2, (1, 1), axis=(1, 0))
+ array([[9, 5, 6, 7, 8],
+ [4, 0, 1, 2, 3]])
+ >>> np.roll(x2, (2, 1), axis=(1, 0))
+ array([[8, 9, 5, 6, 7],
+ [3, 4, 0, 1, 2]])
+
+ """
+ a = asanyarray(a)
+ if axis is None:
+ return roll(a.ravel(), shift, 0).reshape(a.shape)
+
+ else:
+ axis = normalize_axis_tuple(axis, a.ndim, allow_duplicate=True)
+ broadcasted = broadcast(shift, axis)
+ if broadcasted.ndim > 1:
+ raise ValueError(
+ "'shift' and 'axis' should be scalars or 1D sequences")
+ shifts = dict.fromkeys(range(a.ndim), 0)
+ for sh, ax in broadcasted:
+ shifts[ax] += int(sh)
+
+ rolls = [((slice(None), slice(None)),)] * a.ndim
+ for ax, offset in shifts.items():
+ offset %= a.shape[ax] or 1 # If `a` is empty, nothing matters.
+ if offset:
+ # (original, result), (original, result)
+ rolls[ax] = ((slice(None, -offset), slice(offset, None)),
+ (slice(-offset, None), slice(None, offset)))
+
+ result = empty_like(a)
+ for indices in itertools.product(*rolls):
+ arr_index, res_index = zip(*indices)
+ result[res_index] = a[arr_index]
+
+ return result
+
+
+def _rollaxis_dispatcher(a, axis, start=None):
+ return (a,)
+
+
+@array_function_dispatch(_rollaxis_dispatcher)
+def rollaxis(a, axis, start=0):
+ """
+ Roll the specified axis backwards, until it lies in a given position.
+
+ This function continues to be supported for backward compatibility, but you
+ should prefer `moveaxis`. The `moveaxis` function was added in NumPy
+ 1.11.
+
+ Parameters
+ ----------
+ a : ndarray
+ Input array.
+ axis : int
+ The axis to be rolled. The positions of the other axes do not
+ change relative to one another.
+ start : int, optional
+ When ``start <= axis``, the axis is rolled back until it lies in
+ this position. When ``start > axis``, the axis is rolled until it
+ lies before this position. The default, 0, results in a "complete"
+ roll. The following table describes how negative values of ``start``
+ are interpreted:
+
+ .. table::
+ :align: left
+
+ +-------------------+----------------------+
+ | ``start`` | Normalized ``start`` |
+ +===================+======================+
+ | ``-(arr.ndim+1)`` | raise ``AxisError`` |
+ +-------------------+----------------------+
+ | ``-arr.ndim`` | 0 |
+ +-------------------+----------------------+
+ | |vdots| | |vdots| |
+ +-------------------+----------------------+
+ | ``-1`` | ``arr.ndim-1`` |
+ +-------------------+----------------------+
+ | ``0`` | ``0`` |
+ +-------------------+----------------------+
+ | |vdots| | |vdots| |
+ +-------------------+----------------------+
+ | ``arr.ndim`` | ``arr.ndim`` |
+ +-------------------+----------------------+
+ | ``arr.ndim + 1`` | raise ``AxisError`` |
+ +-------------------+----------------------+
+
+ .. |vdots| unicode:: U+22EE .. Vertical Ellipsis
+
+ Returns
+ -------
+ res : ndarray
+ For NumPy >= 1.10.0 a view of `a` is always returned. For earlier
+ NumPy versions a view of `a` is returned only if the order of the
+ axes is changed, otherwise the input array is returned.
+
+ See Also
+ --------
+ moveaxis : Move array axes to new positions.
+ roll : Roll the elements of an array by a number of positions along a
+ given axis.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.ones((3,4,5,6))
+ >>> np.rollaxis(a, 3, 1).shape
+ (3, 6, 4, 5)
+ >>> np.rollaxis(a, 2).shape
+ (5, 3, 4, 6)
+ >>> np.rollaxis(a, 1, 4).shape
+ (3, 5, 6, 4)
+
+ """
+ n = a.ndim
+ axis = normalize_axis_index(axis, n)
+ if start < 0:
+ start += n
+ msg = "'%s' arg requires %d <= %s < %d, but %d was passed in"
+ if not (0 <= start < n + 1):
+ raise AxisError(msg % ('start', -n, 'start', n + 1, start))
+ if axis < start:
+ # it's been removed
+ start -= 1
+ if axis == start:
+ return a[...]
+ axes = list(range(n))
+ axes.remove(axis)
+ axes.insert(start, axis)
+ return a.transpose(axes)
+
+
+@set_module("numpy.lib.array_utils")
+def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False):
+ """
+ Normalizes an axis argument into a tuple of non-negative integer axes.
+
+ This handles shorthands such as ``1`` and converts them to ``(1,)``,
+ as well as performing the handling of negative indices covered by
+ `normalize_axis_index`.
+
+ By default, this forbids axes from being specified multiple times.
+
+ Used internally by multi-axis-checking logic.
+
+ Parameters
+ ----------
+ axis : int, iterable of int
+ The un-normalized index or indices of the axis.
+ ndim : int
+ The number of dimensions of the array that `axis` should be normalized
+ against.
+ argname : str, optional
+ A prefix to put before the error message, typically the name of the
+ argument.
+ allow_duplicate : bool, optional
+ If False, the default, disallow an axis from being specified twice.
+
+ Returns
+ -------
+ normalized_axes : tuple of int
+ The normalized axis index, such that `0 <= normalized_axis < ndim`
+
+ Raises
+ ------
+ AxisError
+ If any axis provided is out of range
+ ValueError
+ If an axis is repeated
+
+ See also
+ --------
+ normalize_axis_index : normalizing a single scalar axis
+ """
+ # Optimization to speed-up the most common cases.
+ if not isinstance(axis, (tuple, list)):
+ try:
+ axis = [operator.index(axis)]
+ except TypeError:
+ pass
+ # Going via an iterator directly is slower than via list comprehension.
+ axis = tuple(normalize_axis_index(ax, ndim, argname) for ax in axis)
+ if not allow_duplicate and len(set(axis)) != len(axis):
+ if argname:
+ raise ValueError(f'repeated axis in `{argname}` argument')
+ else:
+ raise ValueError('repeated axis')
+ return axis
+
+
+def _moveaxis_dispatcher(a, source, destination):
+ return (a,)
+
+
+@array_function_dispatch(_moveaxis_dispatcher)
+def moveaxis(a, source, destination):
+ """
+ Move axes of an array to new positions.
+
+ Other axes remain in their original order.
+
+ Parameters
+ ----------
+ a : np.ndarray
+ The array whose axes should be reordered.
+ source : int or sequence of int
+ Original positions of the axes to move. These must be unique.
+ destination : int or sequence of int
+ Destination positions for each of the original axes. These must also be
+ unique.
+
+ Returns
+ -------
+ result : np.ndarray
+ Array with moved axes. This array is a view of the input array.
+
+ See Also
+ --------
+ transpose : Permute the dimensions of an array.
+ swapaxes : Interchange two axes of an array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.zeros((3, 4, 5))
+ >>> np.moveaxis(x, 0, -1).shape
+ (4, 5, 3)
+ >>> np.moveaxis(x, -1, 0).shape
+ (5, 3, 4)
+
+ These all achieve the same result:
+
+ >>> np.transpose(x).shape
+ (5, 4, 3)
+ >>> np.swapaxes(x, 0, -1).shape
+ (5, 4, 3)
+ >>> np.moveaxis(x, [0, 1], [-1, -2]).shape
+ (5, 4, 3)
+ >>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape
+ (5, 4, 3)
+
+ """
+ try:
+ # allow duck-array types if they define transpose
+ transpose = a.transpose
+ except AttributeError:
+ a = asarray(a)
+ transpose = a.transpose
+
+ source = normalize_axis_tuple(source, a.ndim, 'source')
+ destination = normalize_axis_tuple(destination, a.ndim, 'destination')
+ if len(source) != len(destination):
+ raise ValueError('`source` and `destination` arguments must have '
+ 'the same number of elements')
+
+ order = [n for n in range(a.ndim) if n not in source]
+
+ for dest, src in sorted(zip(destination, source)):
+ order.insert(dest, src)
+
+ result = transpose(order)
+ return result
+
+
+def _cross_dispatcher(a, b, axisa=None, axisb=None, axisc=None, axis=None):
+ return (a, b)
+
+
+@array_function_dispatch(_cross_dispatcher)
+def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
+ """
+ Return the cross product of two (arrays of) vectors.
+
+ The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular
+ to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors
+ are defined by the last axis of `a` and `b` by default, and these axes
+ can have dimensions 2 or 3. Where the dimension of either `a` or `b` is
+ 2, the third component of the input vector is assumed to be zero and the
+ cross product calculated accordingly. In cases where both input vectors
+ have dimension 2, the z-component of the cross product is returned.
+
+ Parameters
+ ----------
+ a : array_like
+ Components of the first vector(s).
+ b : array_like
+ Components of the second vector(s).
+ axisa : int, optional
+ Axis of `a` that defines the vector(s). By default, the last axis.
+ axisb : int, optional
+ Axis of `b` that defines the vector(s). By default, the last axis.
+ axisc : int, optional
+ Axis of `c` containing the cross product vector(s). Ignored if
+ both input vectors have dimension 2, as the return is scalar.
+ By default, the last axis.
+ axis : int, optional
+ If defined, the axis of `a`, `b` and `c` that defines the vector(s)
+ and cross product(s). Overrides `axisa`, `axisb` and `axisc`.
+
+ Returns
+ -------
+ c : ndarray
+ Vector cross product(s).
+
+ Raises
+ ------
+ ValueError
+ When the dimension of the vector(s) in `a` and/or `b` does not
+ equal 2 or 3.
+
+ See Also
+ --------
+ inner : Inner product
+ outer : Outer product.
+ linalg.cross : An Array API compatible variation of ``np.cross``,
+ which accepts (arrays of) 3-element vectors only.
+ ix_ : Construct index arrays.
+
+ Notes
+ -----
+ Supports full broadcasting of the inputs.
+
+ Dimension-2 input arrays were deprecated in 2.0.0. If you do need this
+ functionality, you can use::
+
+ def cross2d(x, y):
+ return x[..., 0] * y[..., 1] - x[..., 1] * y[..., 0]
+
+ Examples
+ --------
+ Vector cross-product.
+
+ >>> import numpy as np
+ >>> x = [1, 2, 3]
+ >>> y = [4, 5, 6]
+ >>> np.cross(x, y)
+ array([-3, 6, -3])
+
+ One vector with dimension 2.
+
+ >>> x = [1, 2]
+ >>> y = [4, 5, 6]
+ >>> np.cross(x, y)
+ array([12, -6, -3])
+
+ Equivalently:
+
+ >>> x = [1, 2, 0]
+ >>> y = [4, 5, 6]
+ >>> np.cross(x, y)
+ array([12, -6, -3])
+
+ Both vectors with dimension 2.
+
+ >>> x = [1,2]
+ >>> y = [4,5]
+ >>> np.cross(x, y)
+ array(-3)
+
+ Multiple vector cross-products. Note that the direction of the cross
+ product vector is defined by the *right-hand rule*.
+
+ >>> x = np.array([[1,2,3], [4,5,6]])
+ >>> y = np.array([[4,5,6], [1,2,3]])
+ >>> np.cross(x, y)
+ array([[-3, 6, -3],
+ [ 3, -6, 3]])
+
+ The orientation of `c` can be changed using the `axisc` keyword.
+
+ >>> np.cross(x, y, axisc=0)
+ array([[-3, 3],
+ [ 6, -6],
+ [-3, 3]])
+
+ Change the vector definition of `x` and `y` using `axisa` and `axisb`.
+
+ >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]])
+ >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]])
+ >>> np.cross(x, y)
+ array([[ -6, 12, -6],
+ [ 0, 0, 0],
+ [ 6, -12, 6]])
+ >>> np.cross(x, y, axisa=0, axisb=0)
+ array([[-24, 48, -24],
+ [-30, 60, -30],
+ [-36, 72, -36]])
+
+ """
+ if axis is not None:
+ axisa, axisb, axisc = (axis,) * 3
+ a = asarray(a)
+ b = asarray(b)
+
+ if (a.ndim < 1) or (b.ndim < 1):
+ raise ValueError("At least one array has zero dimension")
+
+ # Check axisa and axisb are within bounds
+ axisa = normalize_axis_index(axisa, a.ndim, msg_prefix='axisa')
+ axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb')
+
+ # Move working axis to the end of the shape
+ a = moveaxis(a, axisa, -1)
+ b = moveaxis(b, axisb, -1)
+ msg = ("incompatible dimensions for cross product\n"
+ "(dimension must be 2 or 3)")
+ if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):
+ raise ValueError(msg)
+ if a.shape[-1] == 2 or b.shape[-1] == 2:
+ # Deprecated in NumPy 2.0, 2023-09-26
+ warnings.warn(
+ "Arrays of 2-dimensional vectors are deprecated. Use arrays of "
+ "3-dimensional vectors instead. (deprecated in NumPy 2.0)",
+ DeprecationWarning, stacklevel=2
+ )
+
+ # Create the output array
+ shape = broadcast(a[..., 0], b[..., 0]).shape
+ if a.shape[-1] == 3 or b.shape[-1] == 3:
+ shape += (3,)
+ # Check axisc is within bounds
+ axisc = normalize_axis_index(axisc, len(shape), msg_prefix='axisc')
+ dtype = promote_types(a.dtype, b.dtype)
+ cp = empty(shape, dtype)
+
+ # recast arrays as dtype
+ a = a.astype(dtype)
+ b = b.astype(dtype)
+
+ # create local aliases for readability
+ a0 = a[..., 0]
+ a1 = a[..., 1]
+ if a.shape[-1] == 3:
+ a2 = a[..., 2]
+ b0 = b[..., 0]
+ b1 = b[..., 1]
+ if b.shape[-1] == 3:
+ b2 = b[..., 2]
+ if cp.ndim != 0 and cp.shape[-1] == 3:
+ cp0 = cp[..., 0]
+ cp1 = cp[..., 1]
+ cp2 = cp[..., 2]
+
+ if a.shape[-1] == 2:
+ if b.shape[-1] == 2:
+ # a0 * b1 - a1 * b0
+ multiply(a0, b1, out=cp)
+ cp -= a1 * b0
+ return cp
+ else:
+ assert b.shape[-1] == 3
+ # cp0 = a1 * b2 - 0 (a2 = 0)
+ # cp1 = 0 - a0 * b2 (a2 = 0)
+ # cp2 = a0 * b1 - a1 * b0
+ multiply(a1, b2, out=cp0)
+ multiply(a0, b2, out=cp1)
+ negative(cp1, out=cp1)
+ multiply(a0, b1, out=cp2)
+ cp2 -= a1 * b0
+ else:
+ assert a.shape[-1] == 3
+ if b.shape[-1] == 3:
+ # cp0 = a1 * b2 - a2 * b1
+ # cp1 = a2 * b0 - a0 * b2
+ # cp2 = a0 * b1 - a1 * b0
+ multiply(a1, b2, out=cp0)
+ tmp = np.multiply(a2, b1, out=...)
+ cp0 -= tmp
+ multiply(a2, b0, out=cp1)
+ multiply(a0, b2, out=tmp)
+ cp1 -= tmp
+ multiply(a0, b1, out=cp2)
+ multiply(a1, b0, out=tmp)
+ cp2 -= tmp
+ else:
+ assert b.shape[-1] == 2
+ # cp0 = 0 - a2 * b1 (b2 = 0)
+ # cp1 = a2 * b0 - 0 (b2 = 0)
+ # cp2 = a0 * b1 - a1 * b0
+ multiply(a2, b1, out=cp0)
+ negative(cp0, out=cp0)
+ multiply(a2, b0, out=cp1)
+ multiply(a0, b1, out=cp2)
+ cp2 -= a1 * b0
+
+ return moveaxis(cp, -1, axisc)
+
+
+little_endian = (sys.byteorder == 'little')
+
+
+@set_module('numpy')
+def indices(dimensions, dtype=int, sparse=False):
+ """
+ Return an array representing the indices of a grid.
+
+ Compute an array where the subarrays contain index values 0, 1, ...
+ varying only along the corresponding axis.
+
+ Parameters
+ ----------
+ dimensions : sequence of ints
+ The shape of the grid.
+ dtype : dtype, optional
+ Data type of the result.
+ sparse : boolean, optional
+ Return a sparse representation of the grid instead of a dense
+ representation. Default is False.
+
+ Returns
+ -------
+ grid : one ndarray or tuple of ndarrays
+ If sparse is False:
+ Returns one array of grid indices,
+ ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
+ If sparse is True:
+ Returns a tuple of arrays, with
+ ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
+ dimensions[i] in the ith place
+
+ See Also
+ --------
+ mgrid, ogrid, meshgrid
+
+ Notes
+ -----
+ The output shape in the dense case is obtained by prepending the number
+ of dimensions in front of the tuple of dimensions, i.e. if `dimensions`
+ is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is
+ ``(N, r0, ..., rN-1)``.
+
+ The subarrays ``grid[k]`` contains the N-D array of indices along the
+ ``k-th`` axis. Explicitly::
+
+ grid[k, i0, i1, ..., iN-1] = ik
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> grid = np.indices((2, 3))
+ >>> grid.shape
+ (2, 2, 3)
+ >>> grid[0] # row indices
+ array([[0, 0, 0],
+ [1, 1, 1]])
+ >>> grid[1] # column indices
+ array([[0, 1, 2],
+ [0, 1, 2]])
+
+ The indices can be used as an index into an array.
+
+ >>> x = np.arange(20).reshape(5, 4)
+ >>> row, col = np.indices((2, 3))
+ >>> x[row, col]
+ array([[0, 1, 2],
+ [4, 5, 6]])
+
+ Note that it would be more straightforward in the above example to
+ extract the required elements directly with ``x[:2, :3]``.
+
+ If sparse is set to true, the grid will be returned in a sparse
+ representation.
+
+ >>> i, j = np.indices((2, 3), sparse=True)
+ >>> i.shape
+ (2, 1)
+ >>> j.shape
+ (1, 3)
+ >>> i # row indices
+ array([[0],
+ [1]])
+ >>> j # column indices
+ array([[0, 1, 2]])
+
+ """
+ dimensions = tuple(dimensions)
+ N = len(dimensions)
+ shape = (1,) * N
+ if sparse:
+ res = ()
+ else:
+ res = empty((N,) + dimensions, dtype=dtype)
+ for i, dim in enumerate(dimensions):
+ idx = arange(dim, dtype=dtype).reshape(
+ shape[:i] + (dim,) + shape[i + 1:]
+ )
+ if sparse:
+ res = res + (idx,)
+ else:
+ res[i] = idx
+ return res
+
+
+@finalize_array_function_like
+@set_module('numpy')
+def fromfunction(function, shape, *, dtype=float, like=None, **kwargs):
+ """
+ Construct an array by executing a function over each coordinate.
+
+ The resulting array therefore has a value ``fn(x, y, z)`` at
+ coordinate ``(x, y, z)``.
+
+ Parameters
+ ----------
+ function : callable
+ The function is called with N parameters, where N is the rank of
+ `shape`. Each parameter represents the coordinates of the array
+ varying along a specific axis. For example, if `shape`
+ were ``(2, 2)``, then the parameters would be
+ ``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])``
+ shape : (N,) tuple of ints
+ Shape of the output array, which also determines the shape of
+ the coordinate arrays passed to `function`.
+ dtype : data-type, optional
+ Data-type of the coordinate arrays passed to `function`.
+ By default, `dtype` is float.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ fromfunction : any
+ The result of the call to `function` is passed back directly.
+ Therefore the shape of `fromfunction` is completely determined by
+ `function`. If `function` returns a scalar value, the shape of
+ `fromfunction` would not match the `shape` parameter.
+
+ See Also
+ --------
+ indices, meshgrid
+
+ Notes
+ -----
+ Keywords other than `dtype` and `like` are passed to `function`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.fromfunction(lambda i, j: i, (2, 2), dtype=float)
+ array([[0., 0.],
+ [1., 1.]])
+
+ >>> np.fromfunction(lambda i, j: j, (2, 2), dtype=float)
+ array([[0., 1.],
+ [0., 1.]])
+
+ >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
+ array([[ True, False, False],
+ [False, True, False],
+ [False, False, True]])
+
+ >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
+ array([[0, 1, 2],
+ [1, 2, 3],
+ [2, 3, 4]])
+
+ """
+ if like is not None:
+ return _fromfunction_with_like(
+ like, function, shape, dtype=dtype, **kwargs)
+
+ args = indices(shape, dtype=dtype)
+ return function(*args, **kwargs)
+
+
+_fromfunction_with_like = array_function_dispatch()(fromfunction)
+
+
+def _frombuffer(buf, dtype, shape, order, axis_order=None):
+ array = frombuffer(buf, dtype=dtype)
+ if order == 'K' and axis_order is not None:
+ return array.reshape(shape, order='C').transpose(axis_order)
+ return array.reshape(shape, order=order)
+
+
+@set_module('numpy')
+def isscalar(element):
+ """
+ Returns True if the type of `element` is a scalar type.
+
+ Parameters
+ ----------
+ element : any
+ Input argument, can be of any type and shape.
+
+ Returns
+ -------
+ val : bool
+ True if `element` is a scalar type, False if it is not.
+
+ See Also
+ --------
+ ndim : Get the number of dimensions of an array
+
+ Notes
+ -----
+ If you need a stricter way to identify a *numerical* scalar, use
+ ``isinstance(x, numbers.Number)``, as that returns ``False`` for most
+ non-numerical elements such as strings.
+
+ In most cases ``np.ndim(x) == 0`` should be used instead of this function,
+ as that will also return true for 0d arrays. This is how numpy overloads
+ functions in the style of the ``dx`` arguments to `gradient` and
+ the ``bins`` argument to `histogram`. Some key differences:
+
+ +------------------------------------+---------------+-------------------+
+ | x |``isscalar(x)``|``np.ndim(x) == 0``|
+ +====================================+===============+===================+
+ | PEP 3141 numeric objects | ``True`` | ``True`` |
+ | (including builtins) | | |
+ +------------------------------------+---------------+-------------------+
+ | builtin string and buffer objects | ``True`` | ``True`` |
+ +------------------------------------+---------------+-------------------+
+ | other builtin objects, like | ``False`` | ``True`` |
+ | `pathlib.Path`, `Exception`, | | |
+ | the result of `re.compile` | | |
+ +------------------------------------+---------------+-------------------+
+ | third-party objects like | ``False`` | ``True`` |
+ | `matplotlib.figure.Figure` | | |
+ +------------------------------------+---------------+-------------------+
+ | zero-dimensional numpy arrays | ``False`` | ``True`` |
+ +------------------------------------+---------------+-------------------+
+ | other numpy arrays | ``False`` | ``False`` |
+ +------------------------------------+---------------+-------------------+
+ | `list`, `tuple`, and other | ``False`` | ``False`` |
+ | sequence objects | | |
+ +------------------------------------+---------------+-------------------+
+
+ Examples
+ --------
+ >>> import numpy as np
+
+ >>> np.isscalar(3.1)
+ True
+
+ >>> np.isscalar(np.array(3.1))
+ False
+
+ >>> np.isscalar([3.1])
+ False
+
+ >>> np.isscalar(False)
+ True
+
+ >>> np.isscalar('numpy')
+ True
+
+ NumPy supports PEP 3141 numbers:
+
+ >>> from fractions import Fraction
+ >>> np.isscalar(Fraction(5, 17))
+ True
+ >>> from numbers import Number
+ >>> np.isscalar(Number())
+ True
+
+ """
+ return (isinstance(element, generic)
+ or type(element) in ScalarType
+ or isinstance(element, numbers.Number))
+
+
+@set_module('numpy')
+def binary_repr(num, width=None):
+ """
+ Return the binary representation of the input number as a string.
+
+ For negative numbers, if width is not given, a minus sign is added to the
+ front. If width is given, the two's complement of the number is
+ returned, with respect to that width.
+
+ In a two's-complement system negative numbers are represented by the two's
+ complement of the absolute value. This is the most common method of
+ representing signed integers on computers [1]_. A N-bit two's-complement
+ system can represent every integer in the range
+ :math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
+
+ Parameters
+ ----------
+ num : int
+ Only an integer decimal number can be used.
+ width : int, optional
+ The length of the returned string if `num` is positive, or the length
+ of the two's complement if `num` is negative, provided that `width` is
+ at least a sufficient number of bits for `num` to be represented in
+ the designated form. If the `width` value is insufficient, an error is
+ raised.
+
+ Returns
+ -------
+ bin : str
+ Binary representation of `num` or two's complement of `num`.
+
+ See Also
+ --------
+ base_repr: Return a string representation of a number in the given base
+ system.
+ bin: Python's built-in binary representation generator of an integer.
+
+ Notes
+ -----
+ `binary_repr` is equivalent to using `base_repr` with base 2, but about 25x
+ faster.
+
+ References
+ ----------
+ .. [1] Wikipedia, "Two's complement",
+ https://en.wikipedia.org/wiki/Two's_complement
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.binary_repr(3)
+ '11'
+ >>> np.binary_repr(-3)
+ '-11'
+ >>> np.binary_repr(3, width=4)
+ '0011'
+
+ The two's complement is returned when the input number is negative and
+ width is specified:
+
+ >>> np.binary_repr(-3, width=3)
+ '101'
+ >>> np.binary_repr(-3, width=5)
+ '11101'
+
+ """
+ def err_if_insufficient(width, binwidth):
+ if width is not None and width < binwidth:
+ raise ValueError(
+ f"Insufficient bit {width=} provided for {binwidth=}"
+ )
+
+ # Ensure that num is a Python integer to avoid overflow or unwanted
+ # casts to floating point.
+ num = operator.index(num)
+
+ if num == 0:
+ return '0' * (width or 1)
+
+ elif num > 0:
+ binary = f'{num:b}'
+ binwidth = len(binary)
+ outwidth = (binwidth if width is None
+ else builtins.max(binwidth, width))
+ err_if_insufficient(width, binwidth)
+ return binary.zfill(outwidth)
+
+ elif width is None:
+ return f'-{-num:b}'
+
+ else:
+ poswidth = len(f'{-num:b}')
+
+ # See gh-8679: remove extra digit
+ # for numbers at boundaries.
+ if 2**(poswidth - 1) == -num:
+ poswidth -= 1
+
+ twocomp = 2**(poswidth + 1) + num
+ binary = f'{twocomp:b}'
+ binwidth = len(binary)
+
+ outwidth = builtins.max(binwidth, width)
+ err_if_insufficient(width, binwidth)
+ return '1' * (outwidth - binwidth) + binary
+
+
+@set_module('numpy')
+def base_repr(number, base=2, padding=0):
+ """
+ Return a string representation of a number in the given base system.
+
+ Parameters
+ ----------
+ number : int
+ The value to convert. Positive and negative values are handled.
+ base : int, optional
+ Convert `number` to the `base` number system. The valid range is 2-36,
+ the default value is 2.
+ padding : int, optional
+ Number of zeros padded on the left. Default is 0 (no padding).
+
+ Returns
+ -------
+ out : str
+ String representation of `number` in `base` system.
+
+ See Also
+ --------
+ binary_repr : Faster version of `base_repr` for base 2.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.base_repr(5)
+ '101'
+ >>> np.base_repr(6, 5)
+ '11'
+ >>> np.base_repr(7, base=5, padding=3)
+ '00012'
+
+ >>> np.base_repr(10, base=16)
+ 'A'
+ >>> np.base_repr(32, base=16)
+ '20'
+
+ """
+ digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+ if base > len(digits):
+ raise ValueError("Bases greater than 36 not handled in base_repr.")
+ elif base < 2:
+ raise ValueError("Bases less than 2 not handled in base_repr.")
+
+ num = abs(int(number))
+ res = []
+ while num:
+ res.append(digits[num % base])
+ num //= base
+ if padding:
+ res.append('0' * padding)
+ if number < 0:
+ res.append('-')
+ return ''.join(reversed(res or '0'))
+
+
+# These are all essentially abbreviations
+# These might wind up in a special abbreviations module
+
+
+def _maketup(descr, val):
+ dt = dtype(descr)
+ # Place val in all scalar tuples:
+ fields = dt.fields
+ if fields is None:
+ return val
+ else:
+ res = [_maketup(fields[name][0], val) for name in dt.names]
+ return tuple(res)
+
+
+@finalize_array_function_like
+@set_module('numpy')
+def identity(n, dtype=None, *, like=None):
+ """
+ Return the identity array.
+
+ The identity array is a square array with ones on
+ the main diagonal.
+
+ Parameters
+ ----------
+ n : int
+ Number of rows (and columns) in `n` x `n` output.
+ dtype : data-type, optional
+ Data-type of the output. Defaults to ``float``.
+ ${ARRAY_FUNCTION_LIKE}
+
+ .. versionadded:: 1.20.0
+
+ Returns
+ -------
+ out : ndarray
+ `n` x `n` array with its main diagonal set to one,
+ and all other elements 0.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.identity(3)
+ array([[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]])
+
+ """
+ if like is not None:
+ return _identity_with_like(like, n, dtype=dtype)
+
+ from numpy import eye
+ return eye(n, dtype=dtype, like=like)
+
+
+_identity_with_like = array_function_dispatch()(identity)
+
+
+def _allclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
+ return (a, b, rtol, atol)
+
+
+@array_function_dispatch(_allclose_dispatcher)
+def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
+ """
+ Returns True if two arrays are element-wise equal within a tolerance.
+
+ The tolerance values are positive, typically very small numbers. The
+ relative difference (`rtol` * abs(`b`)) and the absolute difference
+ `atol` are added together to compare against the absolute difference
+ between `a` and `b`.
+
+ .. warning:: The default `atol` is not appropriate for comparing numbers
+ with magnitudes much smaller than one (see Notes).
+
+ NaNs are treated as equal if they are in the same place and if
+ ``equal_nan=True``. Infs are treated as equal if they are in the same
+ place and of the same sign in both arrays.
+
+ Parameters
+ ----------
+ a, b : array_like
+ Input arrays to compare.
+ rtol : array_like
+ The relative tolerance parameter (see Notes).
+ atol : array_like
+ The absolute tolerance parameter (see Notes).
+ equal_nan : bool
+ Whether to compare NaN's as equal. If True, NaN's in `a` will be
+ considered equal to NaN's in `b` in the output array.
+
+ Returns
+ -------
+ allclose : bool
+ Returns True if the two arrays are equal within the given
+ tolerance; False otherwise.
+
+ See Also
+ --------
+ isclose, all, any, equal
+
+ Notes
+ -----
+ If the following equation is element-wise True, then allclose returns
+ True.::
+
+ absolute(a - b) <= (atol + rtol * absolute(b))
+
+ The above equation is not symmetric in `a` and `b`, so that
+ ``allclose(a, b)`` might be different from ``allclose(b, a)`` in
+ some rare cases.
+
+ The default value of `atol` is not appropriate when the reference value
+ `b` has magnitude smaller than one. For example, it is unlikely that
+ ``a = 1e-9`` and ``b = 2e-9`` should be considered "close", yet
+ ``allclose(1e-9, 2e-9)`` is ``True`` with default settings. Be sure
+ to select `atol` for the use case at hand, especially for defining the
+ threshold below which a non-zero value in `a` will be considered "close"
+ to a very small or zero value in `b`.
+
+ The comparison of `a` and `b` uses standard broadcasting, which
+ means that `a` and `b` need not have the same shape in order for
+ ``allclose(a, b)`` to evaluate to True. The same is true for
+ `equal` but not `array_equal`.
+
+ `allclose` is not defined for non-numeric data types.
+ `bool` is considered a numeric data-type for this purpose.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
+ False
+
+ >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
+ True
+
+ >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
+ False
+
+ >>> np.allclose([1.0, np.nan], [1.0, np.nan])
+ False
+
+ >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
+ True
+
+
+ """
+ res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
+ return builtins.bool(res)
+
+
+def _isclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
+ return (a, b, rtol, atol)
+
+
+@array_function_dispatch(_isclose_dispatcher)
+def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
+ """
+ Returns a boolean array where two arrays are element-wise equal within a
+ tolerance.
+
+ The tolerance values are positive, typically very small numbers. The
+ relative difference (`rtol` * abs(`b`)) and the absolute difference
+ `atol` are added together to compare against the absolute difference
+ between `a` and `b`.
+
+ .. warning:: The default `atol` is not appropriate for comparing numbers
+ with magnitudes much smaller than one (see Notes).
+
+ Parameters
+ ----------
+ a, b : array_like
+ Input arrays to compare.
+ rtol : array_like
+ The relative tolerance parameter (see Notes).
+ atol : array_like
+ The absolute tolerance parameter (see Notes).
+ equal_nan : bool
+ Whether to compare NaN's as equal. If True, NaN's in `a` will be
+ considered equal to NaN's in `b` in the output array.
+
+ Returns
+ -------
+ y : array_like
+ Returns a boolean array of where `a` and `b` are equal within the
+ given tolerance. If both `a` and `b` are scalars, returns a single
+ boolean value.
+
+ See Also
+ --------
+ allclose
+ math.isclose
+
+ Notes
+ -----
+ For finite values, isclose uses the following equation to test whether
+ two floating point values are equivalent.::
+
+ absolute(a - b) <= (atol + rtol * absolute(b))
+
+ Unlike the built-in `math.isclose`, the above equation is not symmetric
+ in `a` and `b` -- it assumes `b` is the reference value -- so that
+ `isclose(a, b)` might be different from `isclose(b, a)`.
+
+ The default value of `atol` is not appropriate when the reference value
+ `b` has magnitude smaller than one. For example, it is unlikely that
+ ``a = 1e-9`` and ``b = 2e-9`` should be considered "close", yet
+ ``isclose(1e-9, 2e-9)`` is ``True`` with default settings. Be sure
+ to select `atol` for the use case at hand, especially for defining the
+ threshold below which a non-zero value in `a` will be considered "close"
+ to a very small or zero value in `b`.
+
+ `isclose` is not defined for non-numeric data types.
+ :class:`bool` is considered a numeric data-type for this purpose.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
+ array([ True, False])
+
+ >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])
+ array([ True, True])
+
+ >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])
+ array([False, True])
+
+ >>> np.isclose([1.0, np.nan], [1.0, np.nan])
+ array([ True, False])
+
+ >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
+ array([ True, True])
+
+ >>> np.isclose([1e-8, 1e-7], [0.0, 0.0])
+ array([ True, False])
+
+ >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0)
+ array([False, False])
+
+ >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0])
+ array([ True, True])
+
+ >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0)
+ array([False, True])
+
+ """
+ # Turn all but python scalars into arrays.
+ x, y, atol, rtol = (
+ a if isinstance(a, (int, float, complex)) else asanyarray(a)
+ for a in (a, b, atol, rtol))
+
+ # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT).
+ # This will cause casting of x later. Also, make sure to allow subclasses
+ # (e.g., for numpy.ma).
+ # NOTE: We explicitly allow timedelta, which used to work. This could
+ # possibly be deprecated. See also gh-18286.
+ # timedelta works if `atol` is an integer or also a timedelta.
+ # Although, the default tolerances are unlikely to be useful
+ if (dtype := getattr(y, "dtype", None)) is not None and dtype.kind != "m":
+ dt = multiarray.result_type(y, 1.)
+ y = asanyarray(y, dtype=dt)
+ elif isinstance(y, int):
+ y = float(y)
+
+ # atol and rtol can be arrays
+ if not (np.all(np.isfinite(atol)) and np.all(np.isfinite(rtol))):
+ err_s = np.geterr()["invalid"]
+ err_msg = f"One of rtol or atol is not valid, atol: {atol}, rtol: {rtol}"
+
+ if err_s == "warn":
+ warnings.warn(err_msg, RuntimeWarning, stacklevel=2)
+ elif err_s == "raise":
+ raise FloatingPointError(err_msg)
+ elif err_s == "print":
+ print(err_msg)
+
+ with errstate(invalid='ignore'):
+
+ result = (less_equal(abs(x - y), atol + rtol * abs(y))
+ & isfinite(y)
+ | (x == y))
+ if equal_nan:
+ result |= isnan(x) & isnan(y)
+
+ return result[()] # Flatten 0d arrays to scalars
+
+
+def _array_equal_dispatcher(a1, a2, equal_nan=None):
+ return (a1, a2)
+
+
+_no_nan_types = {
+ # should use np.dtype.BoolDType, but as of writing
+ # that fails the reloading test.
+ type(dtype(nt.bool)),
+ type(dtype(nt.int8)),
+ type(dtype(nt.int16)),
+ type(dtype(nt.int32)),
+ type(dtype(nt.int64)),
+}
+
+
+def _dtype_cannot_hold_nan(dtype):
+ return type(dtype) in _no_nan_types
+
+
+@array_function_dispatch(_array_equal_dispatcher)
+def array_equal(a1, a2, equal_nan=False):
+ """
+ True if two arrays have the same shape and elements, False otherwise.
+
+ Parameters
+ ----------
+ a1, a2 : array_like
+ Input arrays.
+ equal_nan : bool
+ Whether to compare NaN's as equal. If the dtype of a1 and a2 is
+ complex, values will be considered equal if either the real or the
+ imaginary component of a given value is ``nan``.
+
+ Returns
+ -------
+ b : bool
+ Returns True if the arrays are equal.
+
+ See Also
+ --------
+ allclose: Returns True if two arrays are element-wise equal within a
+ tolerance.
+ array_equiv: Returns True if input arrays are shape consistent and all
+ elements equal.
+
+ Examples
+ --------
+ >>> import numpy as np
+
+ >>> np.array_equal([1, 2], [1, 2])
+ True
+
+ >>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
+ True
+
+ >>> np.array_equal([1, 2], [1, 2, 3])
+ False
+
+ >>> np.array_equal([1, 2], [1, 4])
+ False
+
+ >>> a = np.array([1, np.nan])
+ >>> np.array_equal(a, a)
+ False
+
+ >>> np.array_equal(a, a, equal_nan=True)
+ True
+
+ When ``equal_nan`` is True, complex values with nan components are
+ considered equal if either the real *or* the imaginary components are nan.
+
+ >>> a = np.array([1 + 1j])
+ >>> b = a.copy()
+ >>> a.real = np.nan
+ >>> b.imag = np.nan
+ >>> np.array_equal(a, b, equal_nan=True)
+ True
+ """
+ try:
+ a1, a2 = asarray(a1), asarray(a2)
+ except Exception:
+ return False
+ if a1.shape != a2.shape:
+ return False
+ if not equal_nan:
+ return builtins.bool((asanyarray(a1 == a2)).all())
+
+ if a1 is a2:
+ # nan will compare equal so an array will compare equal to itself.
+ return True
+
+ cannot_have_nan = (_dtype_cannot_hold_nan(a1.dtype)
+ and _dtype_cannot_hold_nan(a2.dtype))
+ if cannot_have_nan:
+ return builtins.bool(asarray(a1 == a2).all())
+
+ # Handling NaN values if equal_nan is True
+ a1nan, a2nan = isnan(a1), isnan(a2)
+ # NaN's occur at different locations
+ if not (a1nan == a2nan).all():
+ return False
+ # Shapes of a1, a2 and masks are guaranteed to be consistent by this point
+ return builtins.bool((a1[~a1nan] == a2[~a1nan]).all())
+
+
+def _array_equiv_dispatcher(a1, a2):
+ return (a1, a2)
+
+
+@array_function_dispatch(_array_equiv_dispatcher)
+def array_equiv(a1, a2):
+ """
+ Returns True if input arrays are shape consistent and all elements equal.
+
+ Shape consistent means they are either the same shape, or one input array
+ can be broadcasted to create the same shape as the other one.
+
+ Parameters
+ ----------
+ a1, a2 : array_like
+ Input arrays.
+
+ Returns
+ -------
+ out : bool
+ True if equivalent, False otherwise.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.array_equiv([1, 2], [1, 2])
+ True
+ >>> np.array_equiv([1, 2], [1, 3])
+ False
+
+ Showing the shape equivalence:
+
+ >>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
+ True
+ >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
+ False
+
+ >>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
+ False
+
+ """
+ try:
+ a1, a2 = asarray(a1), asarray(a2)
+ except Exception:
+ return False
+ try:
+ multiarray.broadcast(a1, a2)
+ except Exception:
+ return False
+
+ return builtins.bool(asanyarray(a1 == a2).all())
+
+
+def _astype_dispatcher(x, dtype, /, *, copy=None, device=None):
+ return (x, dtype)
+
+
+@array_function_dispatch(_astype_dispatcher)
+def astype(x, dtype, /, *, copy=True, device=None):
+ """
+ Copies an array to a specified data type.
+
+ This function is an Array API compatible alternative to
+ `numpy.ndarray.astype`.
+
+ Parameters
+ ----------
+ x : ndarray
+ Input NumPy array to cast. ``array_likes`` are explicitly not
+ supported here.
+ dtype : dtype
+ Data type of the result.
+ copy : bool, optional
+ Specifies whether to copy an array when the specified dtype matches
+ the data type of the input array ``x``. If ``True``, a newly allocated
+ array must always be returned. If ``False`` and the specified dtype
+ matches the data type of the input array, the input array must be
+ returned; otherwise, a newly allocated array must be returned.
+ Defaults to ``True``.
+ device : str, optional
+ The device on which to place the returned array. Default: None.
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
+
+ .. versionadded:: 2.1.0
+
+ Returns
+ -------
+ out : ndarray
+ An array having the specified data type.
+
+ See Also
+ --------
+ ndarray.astype
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> arr = np.array([1, 2, 3]); arr
+ array([1, 2, 3])
+ >>> np.astype(arr, np.float64)
+ array([1., 2., 3.])
+
+ Non-copy case:
+
+ >>> arr = np.array([1, 2, 3])
+ >>> arr_noncpy = np.astype(arr, arr.dtype, copy=False)
+ >>> np.shares_memory(arr, arr_noncpy)
+ True
+
+ """
+ if not (isinstance(x, np.ndarray) or isscalar(x)):
+ raise TypeError(
+ "Input should be a NumPy array or scalar. "
+ f"It is a {type(x)} instead."
+ )
+ if device is not None and device != "cpu":
+ raise ValueError(
+ 'Device not understood. Only "cpu" is allowed, but received:'
+ f' {device}'
+ )
+ return x.astype(dtype, copy=copy)
+
+
+inf = PINF
+nan = NAN
+False_ = nt.bool(False)
+True_ = nt.bool(True)
+
+
+def extend_all(module):
+ existing = set(__all__)
+ mall = module.__all__
+ for a in mall:
+ if a not in existing:
+ __all__.append(a)
+
+
+from . import _asarray, _ufunc_config, arrayprint, fromnumeric
+from ._asarray import *
+from ._ufunc_config import *
+from .arrayprint import *
+from .fromnumeric import *
+from .numerictypes import *
+from .umath import *
+
+extend_all(fromnumeric)
+extend_all(umath)
+extend_all(numerictypes)
+extend_all(arrayprint)
+extend_all(_asarray)
+extend_all(_ufunc_config)
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/numeric.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/numeric.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..4ad2881cf17e4ef88c1d1d4023c42720c1319068
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/numeric.pyi
@@ -0,0 +1,1276 @@
+from _typeshed import Incomplete
+from builtins import bool as py_bool
+from collections.abc import Callable, Iterable, Sequence
+from typing import (
+ Any,
+ Final,
+ Literal as L,
+ SupportsAbs,
+ SupportsIndex,
+ TypeAlias,
+ TypeGuard,
+ TypeVar,
+ overload,
+)
+
+import numpy as np
+from numpy import (
+ False_,
+ True_,
+ _OrderCF,
+ _OrderKACF,
+ bitwise_not,
+ inf,
+ little_endian,
+ nan,
+ newaxis,
+ ufunc,
+)
+from numpy._typing import (
+ ArrayLike,
+ DTypeLike,
+ NDArray,
+ _ArrayLike,
+ _ArrayLikeBool_co,
+ _ArrayLikeComplex_co,
+ _ArrayLikeFloat_co,
+ _ArrayLikeInt_co,
+ _ArrayLikeNumber_co,
+ _ArrayLikeTD64_co,
+ _CDoubleCodes,
+ _Complex128Codes,
+ _DoubleCodes,
+ _DTypeLike,
+ _DTypeLikeBool,
+ _Float64Codes,
+ _IntCodes,
+ _NestedSequence,
+ _NumberLike_co,
+ _ScalarLike_co,
+ _Shape,
+ _ShapeLike,
+ _SupportsArray,
+ _SupportsArrayFunc,
+ _SupportsDType,
+)
+
+from ._asarray import require
+from ._ufunc_config import (
+ errstate,
+ getbufsize,
+ geterr,
+ geterrcall,
+ setbufsize,
+ seterr,
+ seterrcall,
+)
+from .arrayprint import (
+ array2string,
+ array_repr,
+ array_str,
+ format_float_positional,
+ format_float_scientific,
+ get_printoptions,
+ printoptions,
+ set_printoptions,
+)
+from .fromnumeric import (
+ all,
+ amax,
+ amin,
+ any,
+ argmax,
+ argmin,
+ argpartition,
+ argsort,
+ around,
+ choose,
+ clip,
+ compress,
+ cumprod,
+ cumsum,
+ cumulative_prod,
+ cumulative_sum,
+ diagonal,
+ matrix_transpose,
+ max,
+ mean,
+ min,
+ ndim,
+ nonzero,
+ partition,
+ prod,
+ ptp,
+ put,
+ ravel,
+ repeat,
+ reshape,
+ resize,
+ round,
+ searchsorted,
+ shape,
+ size,
+ sort,
+ squeeze,
+ std,
+ sum,
+ swapaxes,
+ take,
+ trace,
+ transpose,
+ var,
+)
+from .multiarray import (
+ ALLOW_THREADS as ALLOW_THREADS,
+ BUFSIZE as BUFSIZE,
+ CLIP as CLIP,
+ MAXDIMS as MAXDIMS,
+ MAY_SHARE_BOUNDS as MAY_SHARE_BOUNDS,
+ MAY_SHARE_EXACT as MAY_SHARE_EXACT,
+ RAISE as RAISE,
+ WRAP as WRAP,
+ _Array,
+ _ConstructorEmpty,
+ arange,
+ array,
+ asanyarray,
+ asarray,
+ ascontiguousarray,
+ asfortranarray,
+ broadcast,
+ can_cast,
+ concatenate,
+ copyto,
+ dot,
+ dtype,
+ empty,
+ empty_like,
+ flatiter,
+ from_dlpack,
+ frombuffer,
+ fromfile,
+ fromiter,
+ fromstring,
+ inner,
+ lexsort,
+ matmul,
+ may_share_memory,
+ min_scalar_type,
+ ndarray,
+ nditer,
+ nested_iters,
+ normalize_axis_index as normalize_axis_index,
+ promote_types,
+ putmask,
+ result_type,
+ shares_memory,
+ vdot,
+ where,
+ zeros,
+)
+from .numerictypes import (
+ ScalarType,
+ bool,
+ bool_,
+ busday_count,
+ busday_offset,
+ busdaycalendar,
+ byte,
+ bytes_,
+ cdouble,
+ character,
+ clongdouble,
+ complex64,
+ complex128,
+ complex192,
+ complex256,
+ complexfloating,
+ csingle,
+ datetime64,
+ datetime_as_string,
+ datetime_data,
+ double,
+ flexible,
+ float16,
+ float32,
+ float64,
+ float96,
+ float128,
+ floating,
+ generic,
+ half,
+ inexact,
+ int8,
+ int16,
+ int32,
+ int64,
+ int_,
+ intc,
+ integer,
+ intp,
+ is_busday,
+ isdtype,
+ issubdtype,
+ long,
+ longdouble,
+ longlong,
+ number,
+ object_,
+ short,
+ signedinteger,
+ single,
+ str_,
+ timedelta64,
+ typecodes,
+ ubyte,
+ uint,
+ uint8,
+ uint16,
+ uint32,
+ uint64,
+ uintc,
+ uintp,
+ ulong,
+ ulonglong,
+ unsignedinteger,
+ ushort,
+ void,
+)
+from .umath import (
+ absolute,
+ add,
+ arccos,
+ arccosh,
+ arcsin,
+ arcsinh,
+ arctan,
+ arctan2,
+ arctanh,
+ bitwise_and,
+ bitwise_count,
+ bitwise_or,
+ bitwise_xor,
+ cbrt,
+ ceil,
+ conj,
+ conjugate,
+ copysign,
+ cos,
+ cosh,
+ deg2rad,
+ degrees,
+ divide,
+ divmod,
+ e,
+ equal,
+ euler_gamma,
+ exp,
+ exp2,
+ expm1,
+ fabs,
+ float_power,
+ floor,
+ floor_divide,
+ fmax,
+ fmin,
+ fmod,
+ frexp,
+ frompyfunc,
+ gcd,
+ greater,
+ greater_equal,
+ heaviside,
+ hypot,
+ invert,
+ isfinite,
+ isinf,
+ isnan,
+ isnat,
+ lcm,
+ ldexp,
+ left_shift,
+ less,
+ less_equal,
+ log,
+ log1p,
+ log2,
+ log10,
+ logaddexp,
+ logaddexp2,
+ logical_and,
+ logical_not,
+ logical_or,
+ logical_xor,
+ matvec,
+ maximum,
+ minimum,
+ mod,
+ modf,
+ multiply,
+ negative,
+ nextafter,
+ not_equal,
+ pi,
+ positive,
+ power,
+ rad2deg,
+ radians,
+ reciprocal,
+ remainder,
+ right_shift,
+ rint,
+ sign,
+ signbit,
+ sin,
+ sinh,
+ spacing,
+ sqrt,
+ square,
+ subtract,
+ tan,
+ tanh,
+ true_divide,
+ trunc,
+ vecdot,
+ vecmat,
+)
+
+__all__ = [
+ "False_",
+ "ScalarType",
+ "True_",
+ "absolute",
+ "add",
+ "all",
+ "allclose",
+ "amax",
+ "amin",
+ "any",
+ "arange",
+ "arccos",
+ "arccosh",
+ "arcsin",
+ "arcsinh",
+ "arctan",
+ "arctan2",
+ "arctanh",
+ "argmax",
+ "argmin",
+ "argpartition",
+ "argsort",
+ "argwhere",
+ "around",
+ "array",
+ "array2string",
+ "array_equal",
+ "array_equiv",
+ "array_repr",
+ "array_str",
+ "asanyarray",
+ "asarray",
+ "ascontiguousarray",
+ "asfortranarray",
+ "astype",
+ "base_repr",
+ "binary_repr",
+ "bitwise_and",
+ "bitwise_count",
+ "bitwise_not",
+ "bitwise_or",
+ "bitwise_xor",
+ "bool",
+ "bool_",
+ "broadcast",
+ "busday_count",
+ "busday_offset",
+ "busdaycalendar",
+ "byte",
+ "bytes_",
+ "can_cast",
+ "cbrt",
+ "cdouble",
+ "ceil",
+ "character",
+ "choose",
+ "clip",
+ "clongdouble",
+ "complex64",
+ "complex128",
+ "complex192",
+ "complex256",
+ "complexfloating",
+ "compress",
+ "concatenate",
+ "conj",
+ "conjugate",
+ "convolve",
+ "copysign",
+ "copyto",
+ "correlate",
+ "cos",
+ "cosh",
+ "count_nonzero",
+ "cross",
+ "csingle",
+ "cumprod",
+ "cumsum",
+ "cumulative_prod",
+ "cumulative_sum",
+ "datetime64",
+ "datetime_as_string",
+ "datetime_data",
+ "deg2rad",
+ "degrees",
+ "diagonal",
+ "divide",
+ "divmod",
+ "dot",
+ "double",
+ "dtype",
+ "e",
+ "empty",
+ "empty_like",
+ "equal",
+ "errstate",
+ "euler_gamma",
+ "exp",
+ "exp2",
+ "expm1",
+ "fabs",
+ "flatiter",
+ "flatnonzero",
+ "flexible",
+ "float16",
+ "float32",
+ "float64",
+ "float96",
+ "float128",
+ "float_power",
+ "floating",
+ "floor",
+ "floor_divide",
+ "fmax",
+ "fmin",
+ "fmod",
+ "format_float_positional",
+ "format_float_scientific",
+ "frexp",
+ "from_dlpack",
+ "frombuffer",
+ "fromfile",
+ "fromfunction",
+ "fromiter",
+ "frompyfunc",
+ "fromstring",
+ "full",
+ "full_like",
+ "gcd",
+ "generic",
+ "get_printoptions",
+ "getbufsize",
+ "geterr",
+ "geterrcall",
+ "greater",
+ "greater_equal",
+ "half",
+ "heaviside",
+ "hypot",
+ "identity",
+ "indices",
+ "inexact",
+ "inf",
+ "inner",
+ "int8",
+ "int16",
+ "int32",
+ "int64",
+ "int_",
+ "intc",
+ "integer",
+ "intp",
+ "invert",
+ "is_busday",
+ "isclose",
+ "isdtype",
+ "isfinite",
+ "isfortran",
+ "isinf",
+ "isnan",
+ "isnat",
+ "isscalar",
+ "issubdtype",
+ "lcm",
+ "ldexp",
+ "left_shift",
+ "less",
+ "less_equal",
+ "lexsort",
+ "little_endian",
+ "log",
+ "log1p",
+ "log2",
+ "log10",
+ "logaddexp",
+ "logaddexp2",
+ "logical_and",
+ "logical_not",
+ "logical_or",
+ "logical_xor",
+ "long",
+ "longdouble",
+ "longlong",
+ "matmul",
+ "matrix_transpose",
+ "matvec",
+ "max",
+ "maximum",
+ "may_share_memory",
+ "mean",
+ "min",
+ "min_scalar_type",
+ "minimum",
+ "mod",
+ "modf",
+ "moveaxis",
+ "multiply",
+ "nan",
+ "ndarray",
+ "ndim",
+ "nditer",
+ "negative",
+ "nested_iters",
+ "newaxis",
+ "nextafter",
+ "nonzero",
+ "not_equal",
+ "number",
+ "object_",
+ "ones",
+ "ones_like",
+ "outer",
+ "partition",
+ "pi",
+ "positive",
+ "power",
+ "printoptions",
+ "prod",
+ "promote_types",
+ "ptp",
+ "put",
+ "putmask",
+ "rad2deg",
+ "radians",
+ "ravel",
+ "reciprocal",
+ "remainder",
+ "repeat",
+ "require",
+ "reshape",
+ "resize",
+ "result_type",
+ "right_shift",
+ "rint",
+ "roll",
+ "rollaxis",
+ "round",
+ "searchsorted",
+ "set_printoptions",
+ "setbufsize",
+ "seterr",
+ "seterrcall",
+ "shape",
+ "shares_memory",
+ "short",
+ "sign",
+ "signbit",
+ "signedinteger",
+ "sin",
+ "single",
+ "sinh",
+ "size",
+ "sort",
+ "spacing",
+ "sqrt",
+ "square",
+ "squeeze",
+ "std",
+ "str_",
+ "subtract",
+ "sum",
+ "swapaxes",
+ "take",
+ "tan",
+ "tanh",
+ "tensordot",
+ "timedelta64",
+ "trace",
+ "transpose",
+ "true_divide",
+ "trunc",
+ "typecodes",
+ "ubyte",
+ "ufunc",
+ "uint",
+ "uint8",
+ "uint16",
+ "uint32",
+ "uint64",
+ "uintc",
+ "uintp",
+ "ulong",
+ "ulonglong",
+ "unsignedinteger",
+ "ushort",
+ "var",
+ "vdot",
+ "vecdot",
+ "vecmat",
+ "void",
+ "where",
+ "zeros",
+ "zeros_like",
+]
+
+_T = TypeVar("_T")
+_ScalarT = TypeVar("_ScalarT", bound=generic)
+_NumberObjectT = TypeVar("_NumberObjectT", bound=number | object_)
+_NumericScalarT = TypeVar("_NumericScalarT", bound=number | timedelta64 | object_)
+_DTypeT = TypeVar("_DTypeT", bound=dtype)
+_ArrayT = TypeVar("_ArrayT", bound=np.ndarray[Any, Any])
+_ShapeT = TypeVar("_ShapeT", bound=_Shape)
+
+_AnyShapeT = TypeVar(
+ "_AnyShapeT",
+ tuple[()],
+ tuple[int],
+ tuple[int, int],
+ tuple[int, int, int],
+ tuple[int, int, int, int],
+ tuple[int, ...],
+)
+_AnyNumericScalarT = TypeVar(
+ "_AnyNumericScalarT",
+ np.int8, np.int16, np.int32, np.int64,
+ np.uint8, np.uint16, np.uint32, np.uint64,
+ np.float16, np.float32, np.float64, np.longdouble,
+ np.complex64, np.complex128, np.clongdouble,
+ np.timedelta64,
+ np.object_,
+)
+
+_CorrelateMode: TypeAlias = L["valid", "same", "full"]
+
+_Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarT]]
+_Array2D: TypeAlias = np.ndarray[tuple[int, int], np.dtype[_ScalarT]]
+_Array3D: TypeAlias = np.ndarray[tuple[int, int, int], np.dtype[_ScalarT]]
+_Array4D: TypeAlias = np.ndarray[tuple[int, int, int, int], np.dtype[_ScalarT]]
+
+_Int_co: TypeAlias = np.integer | np.bool
+_Float_co: TypeAlias = np.floating | _Int_co
+_Number_co: TypeAlias = np.number | np.bool
+_TD64_co: TypeAlias = np.timedelta64 | _Int_co
+
+_ArrayLike1D: TypeAlias = _SupportsArray[np.dtype[_ScalarT]] | Sequence[_ScalarT]
+_ArrayLike1DBool_co: TypeAlias = _SupportsArray[np.dtype[np.bool]] | Sequence[py_bool | np.bool]
+_ArrayLike1DInt_co: TypeAlias = _SupportsArray[np.dtype[_Int_co]] | Sequence[int | _Int_co]
+_ArrayLike1DFloat_co: TypeAlias = _SupportsArray[np.dtype[_Float_co]] | Sequence[float | _Float_co]
+_ArrayLike1DNumber_co: TypeAlias = _SupportsArray[np.dtype[_Number_co]] | Sequence[complex | _Number_co]
+_ArrayLike1DTD64_co: TypeAlias = _ArrayLike1D[_TD64_co]
+_ArrayLike1DObject_co: TypeAlias = _ArrayLike1D[np.object_]
+
+_DTypeLikeInt: TypeAlias = type[int] | _IntCodes
+_DTypeLikeFloat64: TypeAlias = type[float] | _Float64Codes | _DoubleCodes
+_DTypeLikeComplex128: TypeAlias = type[complex] | _Complex128Codes | _CDoubleCodes
+
+###
+
+# keep in sync with `ones_like`
+@overload
+def zeros_like(
+ a: _ArrayT,
+ dtype: None = None,
+ order: _OrderKACF = "K",
+ subok: L[True] = True,
+ shape: None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> _ArrayT: ...
+@overload
+def zeros_like(
+ a: _ArrayLike[_ScalarT],
+ dtype: None = None,
+ order: _OrderKACF = "K",
+ subok: py_bool = True,
+ shape: _ShapeLike | None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def zeros_like(
+ a: object,
+ dtype: _DTypeLike[_ScalarT],
+ order: _OrderKACF = "K",
+ subok: py_bool = True,
+ shape: _ShapeLike | None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def zeros_like(
+ a: object,
+ dtype: DTypeLike | None = None,
+ order: _OrderKACF = "K",
+ subok: py_bool = True,
+ shape: _ShapeLike | None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[Any]: ...
+
+ones: Final[_ConstructorEmpty]
+
+# keep in sync with `zeros_like`
+@overload
+def ones_like(
+ a: _ArrayT,
+ dtype: None = None,
+ order: _OrderKACF = "K",
+ subok: L[True] = True,
+ shape: None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> _ArrayT: ...
+@overload
+def ones_like(
+ a: _ArrayLike[_ScalarT],
+ dtype: None = None,
+ order: _OrderKACF = "K",
+ subok: py_bool = True,
+ shape: _ShapeLike | None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def ones_like(
+ a: object,
+ dtype: _DTypeLike[_ScalarT],
+ order: _OrderKACF = "K",
+ subok: py_bool = True,
+ shape: _ShapeLike | None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def ones_like(
+ a: object,
+ dtype: DTypeLike | None = None,
+ order: _OrderKACF = "K",
+ subok: py_bool = True,
+ shape: _ShapeLike | None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[Any]: ...
+
+# TODO: Add overloads for bool, int, float, complex, str, bytes, and memoryview
+# 1-D shape
+@overload
+def full(
+ shape: SupportsIndex,
+ fill_value: _ScalarT,
+ dtype: None = None,
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array[tuple[int], _ScalarT]: ...
+@overload
+def full(
+ shape: SupportsIndex,
+ fill_value: Any,
+ dtype: _DTypeT | _SupportsDType[_DTypeT],
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> np.ndarray[tuple[int], _DTypeT]: ...
+@overload
+def full(
+ shape: SupportsIndex,
+ fill_value: Any,
+ dtype: type[_ScalarT],
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array[tuple[int], _ScalarT]: ...
+@overload
+def full(
+ shape: SupportsIndex,
+ fill_value: Any,
+ dtype: DTypeLike | None = None,
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array[tuple[int], Any]: ...
+# known shape
+@overload
+def full(
+ shape: _AnyShapeT,
+ fill_value: _ScalarT,
+ dtype: None = None,
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array[_AnyShapeT, _ScalarT]: ...
+@overload
+def full(
+ shape: _AnyShapeT,
+ fill_value: Any,
+ dtype: _DTypeT | _SupportsDType[_DTypeT],
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> np.ndarray[_AnyShapeT, _DTypeT]: ...
+@overload
+def full(
+ shape: _AnyShapeT,
+ fill_value: Any,
+ dtype: type[_ScalarT],
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array[_AnyShapeT, _ScalarT]: ...
+@overload
+def full(
+ shape: _AnyShapeT,
+ fill_value: Any,
+ dtype: DTypeLike | None = None,
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> _Array[_AnyShapeT, Any]: ...
+# unknown shape
+@overload
+def full(
+ shape: _ShapeLike,
+ fill_value: _ScalarT,
+ dtype: None = None,
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def full(
+ shape: _ShapeLike,
+ fill_value: Any,
+ dtype: _DTypeT | _SupportsDType[_DTypeT],
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> np.ndarray[Any, _DTypeT]: ...
+@overload
+def full(
+ shape: _ShapeLike,
+ fill_value: Any,
+ dtype: type[_ScalarT],
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def full(
+ shape: _ShapeLike,
+ fill_value: Any,
+ dtype: DTypeLike | None = None,
+ order: _OrderCF = "C",
+ *,
+ device: L["cpu"] | None = None,
+ like: _SupportsArrayFunc | None = None,
+) -> NDArray[Any]: ...
+
+@overload
+def full_like(
+ a: _ArrayT,
+ fill_value: object,
+ dtype: None = None,
+ order: _OrderKACF = "K",
+ subok: L[True] = True,
+ shape: None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> _ArrayT: ...
+@overload
+def full_like(
+ a: _ArrayLike[_ScalarT],
+ fill_value: object,
+ dtype: None = None,
+ order: _OrderKACF = "K",
+ subok: py_bool = True,
+ shape: _ShapeLike | None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def full_like(
+ a: object,
+ fill_value: object,
+ dtype: _DTypeLike[_ScalarT],
+ order: _OrderKACF = "K",
+ subok: py_bool = True,
+ shape: _ShapeLike | None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[_ScalarT]: ...
+@overload
+def full_like(
+ a: object,
+ fill_value: object,
+ dtype: DTypeLike | None = None,
+ order: _OrderKACF = "K",
+ subok: py_bool = True,
+ shape: _ShapeLike | None = None,
+ *,
+ device: L["cpu"] | None = None,
+) -> NDArray[Any]: ...
+
+#
+@overload
+def count_nonzero(a: ArrayLike, axis: None = None, *, keepdims: L[False] = False) -> np.intp: ...
+@overload
+def count_nonzero(a: _ScalarLike_co, axis: _ShapeLike | None = None, *, keepdims: L[True]) -> np.intp: ...
+@overload
+def count_nonzero(
+ a: NDArray[Any] | _NestedSequence[ArrayLike], axis: _ShapeLike | None = None, *, keepdims: L[True]
+) -> NDArray[np.intp]: ...
+@overload
+def count_nonzero(a: ArrayLike, axis: _ShapeLike | None = None, *, keepdims: py_bool = False) -> Any: ...
+
+#
+def isfortran(a: ndarray | generic) -> py_bool: ...
+
+#
+def argwhere(a: ArrayLike) -> _Array2D[np.intp]: ...
+def flatnonzero(a: ArrayLike) -> _Array1D[np.intp]: ...
+
+# keep in sync with `convolve`
+@overload
+def correlate(
+ a: _ArrayLike1D[_AnyNumericScalarT], v: _ArrayLike1D[_AnyNumericScalarT], mode: _CorrelateMode = "valid"
+) -> _Array1D[_AnyNumericScalarT]: ...
+@overload
+def correlate(a: _ArrayLike1DBool_co, v: _ArrayLike1DBool_co, mode: _CorrelateMode = "valid") -> _Array1D[np.bool]: ...
+@overload
+def correlate(a: _ArrayLike1DInt_co, v: _ArrayLike1DInt_co, mode: _CorrelateMode = "valid") -> _Array1D[np.int_ | Any]: ...
+@overload
+def correlate(a: _ArrayLike1DFloat_co, v: _ArrayLike1DFloat_co, mode: _CorrelateMode = "valid") -> _Array1D[np.float64 | Any]: ...
+@overload
+def correlate(
+ a: _ArrayLike1DNumber_co, v: _ArrayLike1DNumber_co, mode: _CorrelateMode = "valid"
+) -> _Array1D[np.complex128 | Any]: ...
+@overload
+def correlate(
+ a: _ArrayLike1DTD64_co, v: _ArrayLike1DTD64_co, mode: _CorrelateMode = "valid"
+) -> _Array1D[np.timedelta64 | Any]: ...
+
+# keep in sync with `correlate`
+@overload
+def convolve(
+ a: _ArrayLike1D[_AnyNumericScalarT], v: _ArrayLike1D[_AnyNumericScalarT], mode: _CorrelateMode = "valid"
+) -> _Array1D[_AnyNumericScalarT]: ...
+@overload
+def convolve(a: _ArrayLike1DBool_co, v: _ArrayLike1DBool_co, mode: _CorrelateMode = "valid") -> _Array1D[np.bool]: ...
+@overload
+def convolve(a: _ArrayLike1DInt_co, v: _ArrayLike1DInt_co, mode: _CorrelateMode = "valid") -> _Array1D[np.int_ | Any]: ...
+@overload
+def convolve(a: _ArrayLike1DFloat_co, v: _ArrayLike1DFloat_co, mode: _CorrelateMode = "valid") -> _Array1D[np.float64 | Any]: ...
+@overload
+def convolve(
+ a: _ArrayLike1DNumber_co, v: _ArrayLike1DNumber_co, mode: _CorrelateMode = "valid"
+) -> _Array1D[np.complex128 | Any]: ...
+@overload
+def convolve(
+ a: _ArrayLike1DTD64_co, v: _ArrayLike1DTD64_co, mode: _CorrelateMode = "valid"
+) -> _Array1D[np.timedelta64 | Any]: ...
+
+# keep roughly in sync with `convolve` and `correlate`, but for 2-D output and an additional `out` overload
+@overload
+def outer(
+ a: _ArrayLike[_AnyNumericScalarT], b: _ArrayLike[_AnyNumericScalarT], out: None = None
+) -> _Array2D[_AnyNumericScalarT]: ...
+@overload
+def outer(a: _ArrayLikeBool_co, b: _ArrayLikeBool_co, out: None = None) -> _Array2D[np.bool]: ...
+@overload
+def outer(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, out: None = None) -> _Array2D[np.int_ | Any]: ...
+@overload
+def outer(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, out: None = None) -> _Array2D[np.float64 | Any]: ...
+@overload
+def outer(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, out: None = None) -> _Array2D[np.complex128 | Any]: ...
+@overload
+def outer(a: _ArrayLikeTD64_co, b: _ArrayLikeTD64_co, out: None = None) -> _Array2D[np.timedelta64 | Any]: ...
+@overload
+def outer(a: _ArrayLikeNumber_co | _ArrayLikeTD64_co, b: _ArrayLikeNumber_co | _ArrayLikeTD64_co, out: _ArrayT) -> _ArrayT: ...
+
+# keep in sync with numpy.linalg._linalg.tensordot (ignoring `/, *`)
+@overload
+def tensordot(
+ a: _ArrayLike[_AnyNumericScalarT], b: _ArrayLike[_AnyNumericScalarT], axes: int | tuple[_ShapeLike, _ShapeLike] = 2
+) -> NDArray[_AnyNumericScalarT]: ...
+@overload
+def tensordot(a: _ArrayLikeBool_co, b: _ArrayLikeBool_co, axes: int | tuple[_ShapeLike, _ShapeLike] = 2) -> NDArray[np.bool]: ...
+@overload
+def tensordot(
+ a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, axes: int | tuple[_ShapeLike, _ShapeLike] = 2
+) -> NDArray[np.int_ | Any]: ...
+@overload
+def tensordot(
+ a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, axes: int | tuple[_ShapeLike, _ShapeLike] = 2
+) -> NDArray[np.float64 | Any]: ...
+@overload
+def tensordot(
+ a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, axes: int | tuple[_ShapeLike, _ShapeLike] = 2
+) -> NDArray[np.complex128 | Any]: ...
+
+#
+@overload
+def cross(
+ a: _ArrayLike[_AnyNumericScalarT],
+ b: _ArrayLike[_AnyNumericScalarT],
+ axisa: int = -1,
+ axisb: int = -1,
+ axisc: int = -1,
+ axis: int | None = None,
+) -> NDArray[_AnyNumericScalarT]: ...
+@overload
+def cross(
+ a: _ArrayLikeInt_co,
+ b: _ArrayLikeInt_co,
+ axisa: int = -1,
+ axisb: int = -1,
+ axisc: int = -1,
+ axis: int | None = None,
+) -> NDArray[np.int_ | Any]: ...
+@overload
+def cross(
+ a: _ArrayLikeFloat_co,
+ b: _ArrayLikeFloat_co,
+ axisa: int = -1,
+ axisb: int = -1,
+ axisc: int = -1,
+ axis: int | None = None,
+) -> NDArray[np.float64 | Any]: ...
+@overload
+def cross(
+ a: _ArrayLikeComplex_co,
+ b: _ArrayLikeComplex_co,
+ axisa: int = -1,
+ axisb: int = -1,
+ axisc: int = -1,
+ axis: int | None = None,
+) -> NDArray[np.complex128 | Any]: ...
+
+#
+@overload
+def roll(a: _ArrayT, shift: _ShapeLike, axis: _ShapeLike | None = None) -> _ArrayT: ...
+@overload
+def roll(a: _ArrayLike[_ScalarT], shift: _ShapeLike, axis: _ShapeLike | None = None) -> NDArray[_ScalarT]: ...
+@overload
+def roll(a: ArrayLike, shift: _ShapeLike, axis: _ShapeLike | None = None) -> NDArray[Any]: ...
+
+#
+def rollaxis(a: _ArrayT, axis: int, start: int = 0) -> _ArrayT: ...
+def moveaxis(a: _ArrayT, source: _ShapeLike, destination: _ShapeLike) -> _ArrayT: ...
+def normalize_axis_tuple(
+ axis: int | Iterable[int],
+ ndim: int,
+ argname: str | None = None,
+ allow_duplicate: py_bool | None = False,
+) -> tuple[int, ...]: ...
+
+#
+@overload # 0d, dtype=int (default), sparse=False (default)
+def indices(dimensions: tuple[()], dtype: type[int] = int, sparse: L[False] = False) -> _Array1D[np.intp]: ...
+@overload # 0d, dtype=, sparse=True
+def indices(dimensions: tuple[()], dtype: DTypeLike | None = int, *, sparse: L[True]) -> tuple[()]: ...
+@overload # 0d, dtype=, sparse=False (default)
+def indices(dimensions: tuple[()], dtype: _DTypeLike[_ScalarT], sparse: L[False] = False) -> _Array1D[_ScalarT]: ...
+@overload # 0d, dtype=, sparse=False (default)
+def indices(dimensions: tuple[()], dtype: DTypeLike, sparse: L[False] = False) -> _Array1D[Any]: ...
+@overload # 1d, dtype=int (default), sparse=False (default)
+def indices(dimensions: tuple[int], dtype: type[int] = int, sparse: L[False] = False) -> _Array2D[np.intp]: ...
+@overload # 1d, dtype=int (default), sparse=True
+def indices(dimensions: tuple[int], dtype: type[int] = int, *, sparse: L[True]) -> tuple[_Array1D[np.intp]]: ...
+@overload # 1d, dtype=, sparse=False (default)
+def indices(dimensions: tuple[int], dtype: _DTypeLike[_ScalarT], sparse: L[False] = False) -> _Array2D[_ScalarT]: ...
+@overload # 1d, dtype=, sparse=True
+def indices(dimensions: tuple[int], dtype: _DTypeLike[_ScalarT], sparse: L[True]) -> tuple[_Array1D[_ScalarT]]: ...
+@overload # 1d, dtype=, sparse=False (default)
+def indices(dimensions: tuple[int], dtype: DTypeLike, sparse: L[False] = False) -> _Array2D[Any]: ...
+@overload # 1d, dtype=, sparse=True
+def indices(dimensions: tuple[int], dtype: DTypeLike, sparse: L[True]) -> tuple[_Array1D[Any]]: ...
+@overload # 2d, dtype=int (default), sparse=False (default)
+def indices(dimensions: tuple[int, int], dtype: type[int] = int, sparse: L[False] = False) -> _Array3D[np.intp]: ...
+@overload # 2d, dtype=int (default), sparse=True
+def indices(
+ dimensions: tuple[int, int], dtype: type[int] = int, *, sparse: L[True]
+) -> tuple[_Array2D[np.intp], _Array2D[np.intp]]: ...
+@overload # 2d, dtype=, sparse=False (default)
+def indices(dimensions: tuple[int, int], dtype: _DTypeLike[_ScalarT], sparse: L[False] = False) -> _Array3D[_ScalarT]: ...
+@overload # 2d, dtype=, sparse=True
+def indices(
+ dimensions: tuple[int, int], dtype: _DTypeLike[_ScalarT], sparse: L[True]
+) -> tuple[_Array2D[_ScalarT], _Array2D[_ScalarT]]: ...
+@overload # 2d, dtype=, sparse=False (default)
+def indices(dimensions: tuple[int, int], dtype: DTypeLike, sparse: L[False] = False) -> _Array3D[Any]: ...
+@overload # 2d, dtype=, sparse=True
+def indices(dimensions: tuple[int, int], dtype: DTypeLike, sparse: L[True]) -> tuple[_Array2D[Any], _Array2D[Any]]: ...
+@overload # ?d, dtype=int (default), sparse=False (default)
+def indices(dimensions: Sequence[int], dtype: type[int] = int, sparse: L[False] = False) -> NDArray[np.intp]: ...
+@overload # ?d, dtype=int (default), sparse=True
+def indices(dimensions: Sequence[int], dtype: type[int] = int, *, sparse: L[True]) -> tuple[NDArray[np.intp], ...]: ...
+@overload # ?d, dtype=, sparse=False (default)
+def indices(dimensions: Sequence[int], dtype: _DTypeLike[_ScalarT], sparse: L[False] = False) -> NDArray[_ScalarT]: ...
+@overload # ?d, dtype=, sparse=True
+def indices(dimensions: Sequence[int], dtype: _DTypeLike[_ScalarT], sparse: L[True]) -> tuple[NDArray[_ScalarT], ...]: ...
+@overload # ?d, dtype=, sparse=False (default)
+def indices(dimensions: Sequence[int], dtype: DTypeLike, sparse: L[False] = False) -> ndarray: ...
+@overload # ?d, dtype=, sparse=True
+def indices(dimensions: Sequence[int], dtype: DTypeLike, sparse: L[True]) -> tuple[ndarray, ...]: ...
+
+#
+def fromfunction(
+ function: Callable[..., _T],
+ shape: Sequence[int],
+ *,
+ dtype: DTypeLike | None = float,
+ like: _SupportsArrayFunc | None = None,
+ **kwargs: object,
+) -> _T: ...
+
+#
+def isscalar(element: object) -> TypeGuard[generic | complex | str | bytes | memoryview]: ...
+
+#
+def binary_repr(num: SupportsIndex, width: int | None = None) -> str: ...
+def base_repr(number: SupportsAbs[float], base: float = 2, padding: SupportsIndex | None = 0) -> str: ...
+
+#
+@overload # dtype: None (default)
+def identity(n: int, dtype: None = None, *, like: _SupportsArrayFunc | None = None) -> _Array2D[np.float64]: ...
+@overload # dtype: known scalar type
+def identity(n: int, dtype: _DTypeLike[_ScalarT], *, like: _SupportsArrayFunc | None = None) -> _Array2D[_ScalarT]: ...
+@overload # dtype: like bool
+def identity(n: int, dtype: _DTypeLikeBool, *, like: _SupportsArrayFunc | None = None) -> _Array2D[np.bool]: ...
+@overload # dtype: like int_
+def identity(n: int, dtype: _DTypeLikeInt, *, like: _SupportsArrayFunc | None = None) -> _Array2D[np.int_ | Any]: ...
+@overload # dtype: like float64
+def identity(n: int, dtype: _DTypeLikeFloat64, *, like: _SupportsArrayFunc | None = None) -> _Array2D[np.float64 | Any]: ...
+@overload # dtype: like complex128
+def identity(n: int, dtype: _DTypeLikeComplex128, *, like: _SupportsArrayFunc | None = None) -> _Array2D[np.complex128 | Any]: ...
+@overload # dtype: unknown
+def identity(n: int, dtype: DTypeLike, *, like: _SupportsArrayFunc | None = None) -> _Array2D[Incomplete]: ...
+
+#
+def allclose(
+ a: ArrayLike,
+ b: ArrayLike,
+ rtol: ArrayLike = 1e-5,
+ atol: ArrayLike = 1e-8,
+ equal_nan: py_bool = False,
+) -> py_bool: ...
+
+#
+@overload # scalar, scalar
+def isclose(
+ a: _NumberLike_co,
+ b: _NumberLike_co,
+ rtol: ArrayLike = 1e-5,
+ atol: ArrayLike = 1e-8,
+ equal_nan: py_bool = False,
+) -> np.bool: ...
+@overload # known shape, same shape or scalar
+def isclose(
+ a: np.ndarray[_ShapeT],
+ b: np.ndarray[_ShapeT] | _NumberLike_co,
+ rtol: ArrayLike = 1e-5,
+ atol: ArrayLike = 1e-8,
+ equal_nan: py_bool = False,
+) -> np.ndarray[_ShapeT, np.dtype[np.bool]]: ...
+@overload # same shape or scalar, known shape
+def isclose(
+ a: np.ndarray[_ShapeT] | _NumberLike_co,
+ b: np.ndarray[_ShapeT],
+ rtol: ArrayLike = 1e-5,
+ atol: ArrayLike = 1e-8,
+ equal_nan: py_bool = False,
+) -> np.ndarray[_ShapeT, np.dtype[np.bool]]: ...
+@overload # 1d sequence, <=1d array-like
+def isclose(
+ a: Sequence[_NumberLike_co],
+ b: Sequence[_NumberLike_co] | _NumberLike_co | np.ndarray[tuple[int]],
+ rtol: ArrayLike = 1e-5,
+ atol: ArrayLike = 1e-8,
+ equal_nan: py_bool = False,
+) -> np.ndarray[tuple[int], np.dtype[np.bool]]: ...
+@overload # <=1d array-like, 1d sequence
+def isclose(
+ a: Sequence[_NumberLike_co] | _NumberLike_co | np.ndarray[tuple[int]],
+ b: Sequence[_NumberLike_co],
+ rtol: ArrayLike = 1e-5,
+ atol: ArrayLike = 1e-8,
+ equal_nan: py_bool = False,
+) -> np.ndarray[tuple[int], np.dtype[np.bool]]: ...
+@overload # 2d sequence, <=2d array-like
+def isclose(
+ a: Sequence[Sequence[_NumberLike_co]],
+ b: Sequence[Sequence[_NumberLike_co]] | Sequence[_NumberLike_co] | _NumberLike_co | np.ndarray[tuple[int] | tuple[int, int]],
+ rtol: ArrayLike = 1e-5,
+ atol: ArrayLike = 1e-8,
+ equal_nan: py_bool = False,
+) -> np.ndarray[tuple[int], np.dtype[np.bool]]: ...
+@overload # <=2d array-like, 2d sequence
+def isclose(
+ b: Sequence[Sequence[_NumberLike_co]] | Sequence[_NumberLike_co] | _NumberLike_co | np.ndarray[tuple[int] | tuple[int, int]],
+ a: Sequence[Sequence[_NumberLike_co]],
+ rtol: ArrayLike = 1e-5,
+ atol: ArrayLike = 1e-8,
+ equal_nan: py_bool = False,
+) -> np.ndarray[tuple[int], np.dtype[np.bool]]: ...
+@overload # unknown shape, unknown shape
+def isclose(
+ a: ArrayLike,
+ b: ArrayLike,
+ rtol: ArrayLike = 1e-5,
+ atol: ArrayLike = 1e-8,
+ equal_nan: py_bool = False,
+) -> NDArray[np.bool] | Any: ...
+
+#
+def array_equal(a1: ArrayLike, a2: ArrayLike, equal_nan: py_bool = False) -> py_bool: ...
+def array_equiv(a1: ArrayLike, a2: ArrayLike) -> py_bool: ...
+
+#
+@overload
+def astype(
+ x: ndarray[_ShapeT],
+ dtype: _DTypeLike[_ScalarT],
+ /,
+ *,
+ copy: py_bool = True,
+ device: L["cpu"] | None = None,
+) -> ndarray[_ShapeT, dtype[_ScalarT]]: ...
+@overload
+def astype(
+ x: ndarray[_ShapeT],
+ dtype: DTypeLike | None,
+ /,
+ *,
+ copy: py_bool = True,
+ device: L["cpu"] | None = None,
+) -> ndarray[_ShapeT]: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/numerictypes.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/numerictypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..265ad4f8eb1f578e53625b5c832a866bb4a5ed5c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/numerictypes.py
@@ -0,0 +1,633 @@
+"""
+numerictypes: Define the numeric type objects
+
+This module is designed so "from numerictypes import \\*" is safe.
+Exported symbols include:
+
+ Dictionary with all registered number types (including aliases):
+ sctypeDict
+
+ Type objects (not all will be available, depends on platform):
+ see variable sctypes for which ones you have
+
+ Bit-width names
+
+ int8 int16 int32 int64
+ uint8 uint16 uint32 uint64
+ float16 float32 float64 float96 float128
+ complex64 complex128 complex192 complex256
+ datetime64 timedelta64
+
+ c-based names
+
+ bool
+
+ object_
+
+ void, str_
+
+ byte, ubyte,
+ short, ushort
+ intc, uintc,
+ intp, uintp,
+ int_, uint,
+ longlong, ulonglong,
+
+ single, csingle,
+ double, cdouble,
+ longdouble, clongdouble,
+
+ As part of the type-hierarchy: xx -- is bit-width
+
+ generic
+ +-> bool (kind=b)
+ +-> number
+ | +-> integer
+ | | +-> signedinteger (intxx) (kind=i)
+ | | | byte
+ | | | short
+ | | | intc
+ | | | intp
+ | | | int_
+ | | | longlong
+ | | \\-> unsignedinteger (uintxx) (kind=u)
+ | | ubyte
+ | | ushort
+ | | uintc
+ | | uintp
+ | | uint
+ | | ulonglong
+ | +-> inexact
+ | +-> floating (floatxx) (kind=f)
+ | | half
+ | | single
+ | | double
+ | | longdouble
+ | \\-> complexfloating (complexxx) (kind=c)
+ | csingle
+ | cdouble
+ | clongdouble
+ +-> flexible
+ | +-> character
+ | | bytes_ (kind=S)
+ | | str_ (kind=U)
+ | |
+ | \\-> void (kind=V)
+ \\-> object_ (not used much) (kind=O)
+
+"""
+import numbers
+import warnings
+
+from numpy._utils import set_module
+
+from . import multiarray as ma
+from .multiarray import (
+ busday_count,
+ busday_offset,
+ busdaycalendar,
+ datetime_as_string,
+ datetime_data,
+ dtype,
+ is_busday,
+ ndarray,
+)
+
+# we add more at the bottom
+__all__ = [
+ 'ScalarType', 'typecodes', 'issubdtype', 'datetime_data',
+ 'datetime_as_string', 'busday_offset', 'busday_count',
+ 'is_busday', 'busdaycalendar', 'isdtype'
+]
+
+# we don't need all these imports, but we need to keep them for compatibility
+# for users using np._core.numerictypes.UPPER_TABLE
+# we don't export these for import *, but we do want them accessible
+# as numerictypes.bool, etc.
+from builtins import bool, bytes, complex, float, int, object, str # noqa: F401, UP029
+
+from ._dtype import _kind_name
+from ._string_helpers import ( # noqa: F401
+ LOWER_TABLE,
+ UPPER_TABLE,
+ english_capitalize,
+ english_lower,
+ english_upper,
+)
+from ._type_aliases import allTypes, sctypeDict, sctypes
+
+# We use this later
+generic = allTypes['generic']
+
+genericTypeRank = ['bool', 'int8', 'uint8', 'int16', 'uint16',
+ 'int32', 'uint32', 'int64', 'uint64',
+ 'float16', 'float32', 'float64', 'float96', 'float128',
+ 'complex64', 'complex128', 'complex192', 'complex256',
+ 'object']
+
+@set_module('numpy')
+def maximum_sctype(t):
+ """
+ Return the scalar type of highest precision of the same kind as the input.
+
+ .. deprecated:: 2.0
+ Use an explicit dtype like int64 or float64 instead.
+
+ Parameters
+ ----------
+ t : dtype or dtype specifier
+ The input data type. This can be a `dtype` object or an object that
+ is convertible to a `dtype`.
+
+ Returns
+ -------
+ out : dtype
+ The highest precision data type of the same kind (`dtype.kind`) as `t`.
+
+ See Also
+ --------
+ obj2sctype, mintypecode, sctype2char
+ dtype
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import maximum_sctype
+ >>> maximum_sctype(int)
+
+ >>> maximum_sctype(np.uint8)
+
+ >>> maximum_sctype(complex)
+ # may vary
+
+ >>> maximum_sctype(str)
+
+
+ >>> maximum_sctype('i2')
+
+ >>> maximum_sctype('f4')
+ # may vary
+
+ """
+
+ # Deprecated in NumPy 2.0, 2023-07-11
+ warnings.warn(
+ "`maximum_sctype` is deprecated. Use an explicit dtype like int64 "
+ "or float64 instead. (deprecated in NumPy 2.0)",
+ DeprecationWarning,
+ stacklevel=2
+ )
+
+ g = obj2sctype(t)
+ if g is None:
+ return t
+ t = g
+ base = _kind_name(dtype(t))
+ if base in sctypes:
+ return sctypes[base][-1]
+ else:
+ return t
+
+
+@set_module('numpy')
+def issctype(rep):
+ """
+ Determines whether the given object represents a scalar data-type.
+
+ Parameters
+ ----------
+ rep : any
+ If `rep` is an instance of a scalar dtype, True is returned. If not,
+ False is returned.
+
+ Returns
+ -------
+ out : bool
+ Boolean result of check whether `rep` is a scalar dtype.
+
+ See Also
+ --------
+ issubsctype, issubdtype, obj2sctype, sctype2char
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import issctype
+ >>> issctype(np.int32)
+ True
+ >>> issctype(list)
+ False
+ >>> issctype(1.1)
+ False
+
+ Strings are also a scalar type:
+
+ >>> issctype(np.dtype('str'))
+ True
+
+ """
+ if not isinstance(rep, (type, dtype)):
+ return False
+ try:
+ res = obj2sctype(rep)
+ if res and res != object_:
+ return True
+ else:
+ return False
+ except Exception:
+ return False
+
+
+def obj2sctype(rep, default=None):
+ """
+ Return the scalar dtype or NumPy equivalent of Python type of an object.
+
+ Parameters
+ ----------
+ rep : any
+ The object of which the type is returned.
+ default : any, optional
+ If given, this is returned for objects whose types can not be
+ determined. If not given, None is returned for those objects.
+
+ Returns
+ -------
+ dtype : dtype or Python type
+ The data type of `rep`.
+
+ See Also
+ --------
+ sctype2char, issctype, issubsctype, issubdtype
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import obj2sctype
+ >>> obj2sctype(np.int32)
+
+ >>> obj2sctype(np.array([1., 2.]))
+
+ >>> obj2sctype(np.array([1.j]))
+
+
+ >>> obj2sctype(dict)
+
+ >>> obj2sctype('string')
+
+ >>> obj2sctype(1, default=list)
+
+
+ """
+ # prevent abstract classes being upcast
+ if isinstance(rep, type) and issubclass(rep, generic):
+ return rep
+ # extract dtype from arrays
+ if isinstance(rep, ndarray):
+ return rep.dtype.type
+ # fall back on dtype to convert
+ try:
+ res = dtype(rep)
+ except Exception:
+ return default
+ else:
+ return res.type
+
+
+@set_module('numpy')
+def issubclass_(arg1, arg2):
+ """
+ Determine if a class is a subclass of a second class.
+
+ `issubclass_` is equivalent to the Python built-in ``issubclass``,
+ except that it returns False instead of raising a TypeError if one
+ of the arguments is not a class.
+
+ Parameters
+ ----------
+ arg1 : class
+ Input class. True is returned if `arg1` is a subclass of `arg2`.
+ arg2 : class or tuple of classes.
+ Input class. If a tuple of classes, True is returned if `arg1` is a
+ subclass of any of the tuple elements.
+
+ Returns
+ -------
+ out : bool
+ Whether `arg1` is a subclass of `arg2` or not.
+
+ See Also
+ --------
+ issubsctype, issubdtype, issctype
+
+ Examples
+ --------
+ >>> np.issubclass_(np.int32, int)
+ False
+ >>> np.issubclass_(np.int32, float)
+ False
+ >>> np.issubclass_(np.float64, float)
+ True
+
+ """
+ try:
+ return issubclass(arg1, arg2)
+ except TypeError:
+ return False
+
+
+@set_module('numpy')
+def issubsctype(arg1, arg2):
+ """
+ Determine if the first argument is a subclass of the second argument.
+
+ Parameters
+ ----------
+ arg1, arg2 : dtype or dtype specifier
+ Data-types.
+
+ Returns
+ -------
+ out : bool
+ The result.
+
+ See Also
+ --------
+ issctype, issubdtype, obj2sctype
+
+ Examples
+ --------
+ >>> from numpy._core import issubsctype
+ >>> issubsctype('S8', str)
+ False
+ >>> issubsctype(np.array([1]), int)
+ True
+ >>> issubsctype(np.array([1]), float)
+ False
+
+ """
+ return issubclass(obj2sctype(arg1), obj2sctype(arg2))
+
+
+class _PreprocessDTypeError(Exception):
+ pass
+
+
+def _preprocess_dtype(dtype):
+ """
+ Preprocess dtype argument by:
+ 1. fetching type from a data type
+ 2. verifying that types are built-in NumPy dtypes
+ """
+ if isinstance(dtype, ma.dtype):
+ dtype = dtype.type
+ if isinstance(dtype, ndarray) or dtype not in allTypes.values():
+ raise _PreprocessDTypeError
+ return dtype
+
+
+@set_module('numpy')
+def isdtype(dtype, kind):
+ """
+ Determine if a provided dtype is of a specified data type ``kind``.
+
+ This function only supports built-in NumPy's data types.
+ Third-party dtypes are not yet supported.
+
+ Parameters
+ ----------
+ dtype : dtype
+ The input dtype.
+ kind : dtype or str or tuple of dtypes/strs.
+ dtype or dtype kind. Allowed dtype kinds are:
+ * ``'bool'`` : boolean kind
+ * ``'signed integer'`` : signed integer data types
+ * ``'unsigned integer'`` : unsigned integer data types
+ * ``'integral'`` : integer data types
+ * ``'real floating'`` : real-valued floating-point data types
+ * ``'complex floating'`` : complex floating-point data types
+ * ``'numeric'`` : numeric data types
+
+ Returns
+ -------
+ out : bool
+
+ See Also
+ --------
+ issubdtype
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.isdtype(np.float32, np.float64)
+ False
+ >>> np.isdtype(np.float32, "real floating")
+ True
+ >>> np.isdtype(np.complex128, ("real floating", "complex floating"))
+ True
+
+ """
+ try:
+ dtype = _preprocess_dtype(dtype)
+ except _PreprocessDTypeError:
+ raise TypeError(
+ "dtype argument must be a NumPy dtype, "
+ f"but it is a {type(dtype)}."
+ ) from None
+
+ input_kinds = kind if isinstance(kind, tuple) else (kind,)
+
+ processed_kinds = set()
+
+ for kind in input_kinds:
+ if kind == "bool":
+ processed_kinds.add(allTypes["bool"])
+ elif kind == "signed integer":
+ processed_kinds.update(sctypes["int"])
+ elif kind == "unsigned integer":
+ processed_kinds.update(sctypes["uint"])
+ elif kind == "integral":
+ processed_kinds.update(sctypes["int"] + sctypes["uint"])
+ elif kind == "real floating":
+ processed_kinds.update(sctypes["float"])
+ elif kind == "complex floating":
+ processed_kinds.update(sctypes["complex"])
+ elif kind == "numeric":
+ processed_kinds.update(
+ sctypes["int"] + sctypes["uint"] +
+ sctypes["float"] + sctypes["complex"]
+ )
+ elif isinstance(kind, str):
+ raise ValueError(
+ "kind argument is a string, but"
+ f" {kind!r} is not a known kind name."
+ )
+ else:
+ try:
+ kind = _preprocess_dtype(kind)
+ except _PreprocessDTypeError:
+ raise TypeError(
+ "kind argument must be comprised of "
+ "NumPy dtypes or strings only, "
+ f"but is a {type(kind)}."
+ ) from None
+ processed_kinds.add(kind)
+
+ return dtype in processed_kinds
+
+
+@set_module('numpy')
+def issubdtype(arg1, arg2):
+ r"""
+ Returns True if first argument is a typecode lower/equal in type hierarchy.
+
+ This is like the builtin :func:`issubclass`, but for `dtype`\ s.
+
+ Parameters
+ ----------
+ arg1, arg2 : dtype_like
+ `dtype` or object coercible to one
+
+ Returns
+ -------
+ out : bool
+
+ See Also
+ --------
+ :ref:`arrays.scalars` : Overview of the numpy type hierarchy.
+
+ Examples
+ --------
+ `issubdtype` can be used to check the type of arrays:
+
+ >>> ints = np.array([1, 2, 3], dtype=np.int32)
+ >>> np.issubdtype(ints.dtype, np.integer)
+ True
+ >>> np.issubdtype(ints.dtype, np.floating)
+ False
+
+ >>> floats = np.array([1, 2, 3], dtype=np.float32)
+ >>> np.issubdtype(floats.dtype, np.integer)
+ False
+ >>> np.issubdtype(floats.dtype, np.floating)
+ True
+
+ Similar types of different sizes are not subdtypes of each other:
+
+ >>> np.issubdtype(np.float64, np.float32)
+ False
+ >>> np.issubdtype(np.float32, np.float64)
+ False
+
+ but both are subtypes of `floating`:
+
+ >>> np.issubdtype(np.float64, np.floating)
+ True
+ >>> np.issubdtype(np.float32, np.floating)
+ True
+
+ For convenience, dtype-like objects are allowed too:
+
+ >>> np.issubdtype('S1', np.bytes_)
+ True
+ >>> np.issubdtype('i4', np.signedinteger)
+ True
+
+ """
+ if not issubclass_(arg1, generic):
+ arg1 = dtype(arg1).type
+ if not issubclass_(arg2, generic):
+ arg2 = dtype(arg2).type
+
+ return issubclass(arg1, arg2)
+
+
+@set_module('numpy')
+def sctype2char(sctype):
+ """
+ Return the string representation of a scalar dtype.
+
+ Parameters
+ ----------
+ sctype : scalar dtype or object
+ If a scalar dtype, the corresponding string character is
+ returned. If an object, `sctype2char` tries to infer its scalar type
+ and then return the corresponding string character.
+
+ Returns
+ -------
+ typechar : str
+ The string character corresponding to the scalar type.
+
+ Raises
+ ------
+ ValueError
+ If `sctype` is an object for which the type can not be inferred.
+
+ See Also
+ --------
+ obj2sctype, issctype, issubsctype, mintypecode
+
+ Examples
+ --------
+ >>> from numpy._core.numerictypes import sctype2char
+ >>> for sctype in [np.int32, np.double, np.cdouble, np.bytes_, np.ndarray]:
+ ... print(sctype2char(sctype))
+ l # may vary
+ d
+ D
+ S
+ O
+
+ >>> x = np.array([1., 2-1.j])
+ >>> sctype2char(x)
+ 'D'
+ >>> sctype2char(list)
+ 'O'
+
+ """
+ sctype = obj2sctype(sctype)
+ if sctype is None:
+ raise ValueError("unrecognized type")
+ if sctype not in sctypeDict.values():
+ # for compatibility
+ raise KeyError(sctype)
+ return dtype(sctype).char
+
+
+def _scalar_type_key(typ):
+ """A ``key`` function for `sorted`."""
+ dt = dtype(typ)
+ return (dt.kind.lower(), dt.itemsize)
+
+
+ScalarType = [int, float, complex, bool, bytes, str, memoryview]
+ScalarType += sorted(dict.fromkeys(sctypeDict.values()), key=_scalar_type_key)
+ScalarType = tuple(ScalarType)
+
+
+# Now add the types we've determined to this module
+for key in allTypes:
+ globals()[key] = allTypes[key]
+ __all__.append(key)
+
+del key
+
+typecodes = {'Character': 'c',
+ 'Integer': 'bhilqnp',
+ 'UnsignedInteger': 'BHILQNP',
+ 'Float': 'efdg',
+ 'Complex': 'FDG',
+ 'AllInteger': 'bBhHiIlLqQnNpP',
+ 'AllFloat': 'efdgFDG',
+ 'Datetime': 'Mm',
+ 'All': '?bhilqnpBHILQNPefdgFDGSUVOMm'}
+
+# backwards compatibility --- deprecated name
+# Formal deprecation: Numpy 1.20.0, 2020-10-19 (see numpy/__init__.py)
+typeDict = sctypeDict
+
+def _register_types():
+ numbers.Integral.register(integer)
+ numbers.Complex.register(inexact)
+ numbers.Real.register(floating)
+ numbers.Number.register(number)
+
+
+_register_types()
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/numerictypes.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/numerictypes.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..46bb6a379861b3db8008e9e6415d714ae9684e36
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/numerictypes.pyi
@@ -0,0 +1,196 @@
+from builtins import bool as py_bool
+from typing import Any, Final, Literal as L, TypedDict, type_check_only
+
+import numpy as np
+from numpy import (
+ bool,
+ bool_,
+ byte,
+ bytes_,
+ cdouble,
+ character,
+ clongdouble,
+ complex64,
+ complex128,
+ complex192,
+ complex256,
+ complexfloating,
+ csingle,
+ datetime64,
+ double,
+ dtype,
+ flexible,
+ float16,
+ float32,
+ float64,
+ float96,
+ float128,
+ floating,
+ generic,
+ half,
+ inexact,
+ int8,
+ int16,
+ int32,
+ int64,
+ int_,
+ intc,
+ integer,
+ intp,
+ long,
+ longdouble,
+ longlong,
+ number,
+ object_,
+ short,
+ signedinteger,
+ single,
+ str_,
+ timedelta64,
+ ubyte,
+ uint,
+ uint8,
+ uint16,
+ uint32,
+ uint64,
+ uintc,
+ uintp,
+ ulong,
+ ulonglong,
+ unsignedinteger,
+ ushort,
+ void,
+)
+from numpy._typing import DTypeLike
+
+from ._type_aliases import sctypeDict as sctypeDict
+from .multiarray import (
+ busday_count,
+ busday_offset,
+ busdaycalendar,
+ datetime_as_string,
+ datetime_data,
+ is_busday,
+)
+
+__all__ = [
+ "ScalarType",
+ "typecodes",
+ "issubdtype",
+ "datetime_data",
+ "datetime_as_string",
+ "busday_offset",
+ "busday_count",
+ "is_busday",
+ "busdaycalendar",
+ "isdtype",
+ "generic",
+ "unsignedinteger",
+ "character",
+ "inexact",
+ "number",
+ "integer",
+ "flexible",
+ "complexfloating",
+ "signedinteger",
+ "floating",
+ "bool",
+ "float16",
+ "float32",
+ "float64",
+ "longdouble",
+ "complex64",
+ "complex128",
+ "clongdouble",
+ "bytes_",
+ "str_",
+ "void",
+ "object_",
+ "datetime64",
+ "timedelta64",
+ "int8",
+ "byte",
+ "uint8",
+ "ubyte",
+ "int16",
+ "short",
+ "uint16",
+ "ushort",
+ "int32",
+ "intc",
+ "uint32",
+ "uintc",
+ "int64",
+ "long",
+ "uint64",
+ "ulong",
+ "longlong",
+ "ulonglong",
+ "intp",
+ "uintp",
+ "double",
+ "cdouble",
+ "single",
+ "csingle",
+ "half",
+ "bool_",
+ "int_",
+ "uint",
+ "float96",
+ "float128",
+ "complex192",
+ "complex256",
+]
+
+@type_check_only
+class _TypeCodes(TypedDict):
+ Character: L["c"]
+ Integer: L["bhilqnp"]
+ UnsignedInteger: L["BHILQNP"]
+ Float: L["efdg"]
+ Complex: L["FDG"]
+ AllInteger: L["bBhHiIlLqQnNpP"]
+ AllFloat: L["efdgFDG"]
+ Datetime: L["Mm"]
+ All: L["?bhilqnpBHILQNPefdgFDGSUVOMm"]
+
+def isdtype(dtype: dtype | type, kind: DTypeLike | tuple[DTypeLike, ...]) -> py_bool: ...
+def issubdtype(arg1: DTypeLike | None, arg2: DTypeLike | None) -> py_bool: ...
+
+typecodes: Final[_TypeCodes] = ...
+ScalarType: Final[
+ tuple[
+ type[int],
+ type[float],
+ type[complex],
+ type[py_bool],
+ type[bytes],
+ type[str],
+ type[memoryview[Any]],
+ type[np.bool],
+ type[complex64],
+ type[complex128],
+ type[complex128 | complex192 | complex256],
+ type[float16],
+ type[float32],
+ type[float64],
+ type[float64 | float96 | float128],
+ type[int8],
+ type[int16],
+ type[int32],
+ type[int32 | int64],
+ type[int64],
+ type[datetime64],
+ type[timedelta64],
+ type[object_],
+ type[bytes_],
+ type[str_],
+ type[uint8],
+ type[uint16],
+ type[uint32],
+ type[uint32 | uint64],
+ type[uint64],
+ type[void],
+ ]
+] = ...
+typeDict: Final = sctypeDict
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/overrides.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/overrides.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d5e7750b09bf3539916aa2a97f88cb29ded6acc
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/overrides.py
@@ -0,0 +1,188 @@
+"""Implementation of __array_function__ overrides from NEP-18."""
+import collections
+import functools
+import inspect
+
+from numpy._core._multiarray_umath import (
+ _ArrayFunctionDispatcher,
+ _get_implementing_args,
+ add_docstring,
+)
+from numpy._utils import set_module # noqa: F401
+from numpy._utils._inspect import getargspec
+
+ARRAY_FUNCTIONS = set()
+
+array_function_like_doc = (
+ """like : array_like, optional
+ Reference object to allow the creation of arrays which are not
+ NumPy arrays. If an array-like passed in as ``like`` supports
+ the ``__array_function__`` protocol, the result will be defined
+ by it. In this case, it ensures the creation of an array object
+ compatible with that passed in via this argument."""
+)
+
+def get_array_function_like_doc(public_api, docstring_template=""):
+ ARRAY_FUNCTIONS.add(public_api)
+ docstring = public_api.__doc__ or docstring_template
+ return docstring.replace("${ARRAY_FUNCTION_LIKE}", array_function_like_doc)
+
+def finalize_array_function_like(public_api):
+ public_api.__doc__ = get_array_function_like_doc(public_api)
+ return public_api
+
+
+add_docstring(
+ _ArrayFunctionDispatcher,
+ """
+ Class to wrap functions with checks for __array_function__ overrides.
+
+ All arguments are required, and can only be passed by position.
+
+ Parameters
+ ----------
+ dispatcher : function or None
+ The dispatcher function that returns a single sequence-like object
+ of all arguments relevant. It must have the same signature (except
+ the default values) as the actual implementation.
+ If ``None``, this is a ``like=`` dispatcher and the
+ ``_ArrayFunctionDispatcher`` must be called with ``like`` as the
+ first (additional and positional) argument.
+ implementation : function
+ Function that implements the operation on NumPy arrays without
+ overrides. Arguments passed calling the ``_ArrayFunctionDispatcher``
+ will be forwarded to this (and the ``dispatcher``) as if using
+ ``*args, **kwargs``.
+
+ Attributes
+ ----------
+ _implementation : function
+ The original implementation passed in.
+ """)
+
+
+# exposed for testing purposes; used internally by _ArrayFunctionDispatcher
+add_docstring(
+ _get_implementing_args,
+ """
+ Collect arguments on which to call __array_function__.
+
+ Parameters
+ ----------
+ relevant_args : iterable of array-like
+ Iterable of possibly array-like arguments to check for
+ __array_function__ methods.
+
+ Returns
+ -------
+ Sequence of arguments with __array_function__ methods, in the order in
+ which they should be called.
+ """)
+
+
+ArgSpec = collections.namedtuple('ArgSpec', 'args varargs keywords defaults')
+
+
+def verify_matching_signatures(implementation, dispatcher):
+ """Verify that a dispatcher function has the right signature."""
+ implementation_spec = ArgSpec(*getargspec(implementation))
+ dispatcher_spec = ArgSpec(*getargspec(dispatcher))
+
+ if (implementation_spec.args != dispatcher_spec.args or
+ implementation_spec.varargs != dispatcher_spec.varargs or
+ implementation_spec.keywords != dispatcher_spec.keywords or
+ (bool(implementation_spec.defaults) !=
+ bool(dispatcher_spec.defaults)) or
+ (implementation_spec.defaults is not None and
+ len(implementation_spec.defaults) !=
+ len(dispatcher_spec.defaults))):
+ raise RuntimeError('implementation and dispatcher for %s have '
+ 'different function signatures' % implementation)
+
+ if implementation_spec.defaults is not None:
+ if dispatcher_spec.defaults != (None,) * len(dispatcher_spec.defaults):
+ raise RuntimeError('dispatcher functions can only use None for '
+ 'default argument values')
+
+
+def array_function_dispatch(dispatcher=None, module=None, verify=True,
+ docs_from_dispatcher=False):
+ """Decorator for adding dispatch with the __array_function__ protocol.
+
+ See NEP-18 for example usage.
+
+ Parameters
+ ----------
+ dispatcher : callable or None
+ Function that when called like ``dispatcher(*args, **kwargs)`` with
+ arguments from the NumPy function call returns an iterable of
+ array-like arguments to check for ``__array_function__``.
+
+ If `None`, the first argument is used as the single `like=` argument
+ and not passed on. A function implementing `like=` must call its
+ dispatcher with `like` as the first non-keyword argument.
+ module : str, optional
+ __module__ attribute to set on new function, e.g., ``module='numpy'``.
+ By default, module is copied from the decorated function.
+ verify : bool, optional
+ If True, verify the that the signature of the dispatcher and decorated
+ function signatures match exactly: all required and optional arguments
+ should appear in order with the same names, but the default values for
+ all optional arguments should be ``None``. Only disable verification
+ if the dispatcher's signature needs to deviate for some particular
+ reason, e.g., because the function has a signature like
+ ``func(*args, **kwargs)``.
+ docs_from_dispatcher : bool, optional
+ If True, copy docs from the dispatcher function onto the dispatched
+ function, rather than from the implementation. This is useful for
+ functions defined in C, which otherwise don't have docstrings.
+
+ Returns
+ -------
+ Function suitable for decorating the implementation of a NumPy function.
+
+ """
+ def decorator(implementation):
+ if verify:
+ if dispatcher is not None:
+ verify_matching_signatures(implementation, dispatcher)
+ else:
+ # Using __code__ directly similar to verify_matching_signature
+ co = implementation.__code__
+ last_arg = co.co_argcount + co.co_kwonlyargcount - 1
+ last_arg = co.co_varnames[last_arg]
+ if last_arg != "like" or co.co_kwonlyargcount == 0:
+ raise RuntimeError(
+ "__array_function__ expects `like=` to be the last "
+ "argument and a keyword-only argument. "
+ f"{implementation} does not seem to comply.")
+
+ if docs_from_dispatcher and dispatcher.__doc__ is not None:
+ doc = inspect.cleandoc(dispatcher.__doc__)
+ add_docstring(implementation, doc)
+
+ public_api = _ArrayFunctionDispatcher(dispatcher, implementation)
+ functools.update_wrapper(public_api, implementation)
+
+ if not verify and not getattr(implementation, "__text_signature__", None):
+ public_api.__signature__ = inspect.signature(dispatcher)
+
+ if module is not None:
+ public_api.__module__ = module
+
+ ARRAY_FUNCTIONS.add(public_api)
+
+ return public_api
+
+ return decorator
+
+
+def array_function_from_dispatcher(
+ implementation, module=None, verify=True, docs_from_dispatcher=True):
+ """Like array_function_dispatcher, but with function arguments flipped."""
+
+ def decorator(dispatcher):
+ return array_function_dispatch(
+ dispatcher, module, verify=verify,
+ docs_from_dispatcher=docs_from_dispatcher)(implementation)
+ return decorator
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/overrides.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/overrides.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..6ef52566d7823560635f02b9579cf43c66144e47
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/overrides.pyi
@@ -0,0 +1,47 @@
+from collections.abc import Callable, Iterable
+from typing import Any, Final, NamedTuple, ParamSpec, TypeAlias, TypeVar
+
+from numpy._utils import set_module as set_module
+
+_T = TypeVar("_T")
+_Tss = ParamSpec("_Tss")
+_FuncLikeT = TypeVar("_FuncLikeT", bound=type | Callable[..., object])
+
+_Dispatcher: TypeAlias = Callable[_Tss, Iterable[object]]
+
+###
+
+ARRAY_FUNCTIONS: set[Callable[..., Any]] = ...
+array_function_like_doc: Final[str] = ...
+
+class ArgSpec(NamedTuple):
+ args: list[str]
+ varargs: str | None
+ keywords: str | None
+ defaults: tuple[Any, ...]
+
+def get_array_function_like_doc(public_api: Callable[..., object], docstring_template: str = "") -> str: ...
+def finalize_array_function_like(public_api: _FuncLikeT) -> _FuncLikeT: ...
+
+#
+def verify_matching_signatures(implementation: Callable[_Tss, object], dispatcher: _Dispatcher[_Tss]) -> None: ...
+
+# NOTE: This actually returns a `_ArrayFunctionDispatcher` callable wrapper object, with
+# the original wrapped callable stored in the `._implementation` attribute. It checks
+# for any `__array_function__` of the values of specific arguments that the dispatcher
+# specifies. Since the dispatcher only returns an iterable of passed array-like args,
+# this overridable behaviour is impossible to annotate.
+def array_function_dispatch(
+ dispatcher: _Dispatcher[_Tss] | None = None,
+ module: str | None = None,
+ verify: bool = True,
+ docs_from_dispatcher: bool = False,
+) -> Callable[[_FuncLikeT], _FuncLikeT]: ...
+
+#
+def array_function_from_dispatcher(
+ implementation: Callable[_Tss, _T],
+ module: str | None = None,
+ verify: bool = True,
+ docs_from_dispatcher: bool = True,
+) -> Callable[[_Dispatcher[_Tss]], Callable[_Tss, _T]]: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/printoptions.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/printoptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d6f9635cd3c17eab501fcda6edef20bfddbdc34
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/printoptions.py
@@ -0,0 +1,32 @@
+"""
+Stores and defines the low-level format_options context variable.
+
+This is defined in its own file outside of the arrayprint module
+so we can import it from C while initializing the multiarray
+C module during import without introducing circular dependencies.
+"""
+
+import sys
+from contextvars import ContextVar
+
+__all__ = ["format_options"]
+
+default_format_options_dict = {
+ "edgeitems": 3, # repr N leading and trailing items of each dimension
+ "threshold": 1000, # total items > triggers array summarization
+ "floatmode": "maxprec",
+ "precision": 8, # precision of floating point representations
+ "suppress": False, # suppress printing small floating values in exp format
+ "linewidth": 75,
+ "nanstr": "nan",
+ "infstr": "inf",
+ "sign": "-",
+ "formatter": None,
+ # Internally stored as an int to simplify comparisons; converted from/to
+ # str/False on the way in/out.
+ 'legacy': sys.maxsize,
+ 'override_repr': None,
+}
+
+format_options = ContextVar(
+ "format_options", default=default_format_options_dict)
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/printoptions.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/printoptions.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..bd7c7b40692d4afb0cb2ab6a8f48b0065cc9c127
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/printoptions.pyi
@@ -0,0 +1,28 @@
+from collections.abc import Callable
+from contextvars import ContextVar
+from typing import Any, Final, TypedDict
+
+from .arrayprint import _FormatDict
+
+__all__ = ["format_options"]
+
+###
+
+class _FormatOptionsDict(TypedDict):
+ edgeitems: int
+ threshold: int
+ floatmode: str
+ precision: int
+ suppress: bool
+ linewidth: int
+ nanstr: str
+ infstr: str
+ sign: str
+ formatter: _FormatDict | None
+ legacy: int
+ override_repr: Callable[[Any], str] | None
+
+###
+
+default_format_options_dict: Final[_FormatOptionsDict] = ...
+format_options: ContextVar[_FormatOptionsDict]
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/records.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/records.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a6af16e3b23f5e3909892b54a329c26495a2e84
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/records.py
@@ -0,0 +1,1088 @@
+"""
+This module contains a set of functions for record arrays.
+"""
+import os
+import warnings
+from collections import Counter
+from contextlib import nullcontext
+
+from numpy._utils import set_module
+
+from . import numeric as sb, numerictypes as nt
+from .arrayprint import _get_legacy_print_mode
+
+# All of the functions allow formats to be a dtype
+__all__ = [
+ 'record', 'recarray', 'format_parser', 'fromarrays', 'fromrecords',
+ 'fromstring', 'fromfile', 'array', 'find_duplicate',
+]
+
+
+ndarray = sb.ndarray
+
+_byteorderconv = {'b': '>',
+ 'l': '<',
+ 'n': '=',
+ 'B': '>',
+ 'L': '<',
+ 'N': '=',
+ 'S': 's',
+ 's': 's',
+ '>': '>',
+ '<': '<',
+ '=': '=',
+ '|': '|',
+ 'I': '|',
+ 'i': '|'}
+
+# formats regular expression
+# allows multidimensional spec with a tuple syntax in front
+# of the letter code '(2,3)f4' and ' ( 2 , 3 ) f4 '
+# are equally allowed
+
+numfmt = nt.sctypeDict
+
+
+@set_module('numpy.rec')
+def find_duplicate(list):
+ """Find duplication in a list, return a list of duplicated elements"""
+ return [
+ item
+ for item, counts in Counter(list).items()
+ if counts > 1
+ ]
+
+
+@set_module('numpy.rec')
+class format_parser:
+ """
+ Class to convert formats, names, titles description to a dtype.
+
+ After constructing the format_parser object, the dtype attribute is
+ the converted data-type:
+ ``dtype = format_parser(formats, names, titles).dtype``
+
+ Attributes
+ ----------
+ dtype : dtype
+ The converted data-type.
+
+ Parameters
+ ----------
+ formats : str or list of str
+ The format description, either specified as a string with
+ comma-separated format descriptions in the form ``'f8, i4, S5'``, or
+ a list of format description strings in the form
+ ``['f8', 'i4', 'S5']``.
+ names : str or list/tuple of str
+ The field names, either specified as a comma-separated string in the
+ form ``'col1, col2, col3'``, or as a list or tuple of strings in the
+ form ``['col1', 'col2', 'col3']``.
+ An empty list can be used, in that case default field names
+ ('f0', 'f1', ...) are used.
+ titles : sequence
+ Sequence of title strings. An empty list can be used to leave titles
+ out.
+ aligned : bool, optional
+ If True, align the fields by padding as the C-compiler would.
+ Default is False.
+ byteorder : str, optional
+ If specified, all the fields will be changed to the
+ provided byte-order. Otherwise, the default byte-order is
+ used. For all available string specifiers, see `dtype.newbyteorder`.
+
+ See Also
+ --------
+ numpy.dtype, numpy.typename
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.rec.format_parser(['>> np.rec.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'],
+ ... []).dtype
+ dtype([('col1', '>> np.rec.format_parser([' len(titles):
+ self._titles += [None] * (self._nfields - len(titles))
+
+ def _createdtype(self, byteorder):
+ dtype = sb.dtype({
+ 'names': self._names,
+ 'formats': self._f_formats,
+ 'offsets': self._offsets,
+ 'titles': self._titles,
+ })
+ if byteorder is not None:
+ byteorder = _byteorderconv[byteorder[0]]
+ dtype = dtype.newbyteorder(byteorder)
+
+ self.dtype = dtype
+
+
+class record(nt.void):
+ """A data-type scalar that allows field access as attribute lookup.
+ """
+
+ # manually set name and module so that this class's type shows up
+ # as numpy.record when printed
+ __name__ = 'record'
+ __module__ = 'numpy'
+
+ def __repr__(self):
+ if _get_legacy_print_mode() <= 113:
+ return self.__str__()
+ return super().__repr__()
+
+ def __str__(self):
+ if _get_legacy_print_mode() <= 113:
+ return str(self.item())
+ return super().__str__()
+
+ def __getattribute__(self, attr):
+ if attr in ('setfield', 'getfield', 'dtype'):
+ return nt.void.__getattribute__(self, attr)
+ try:
+ return nt.void.__getattribute__(self, attr)
+ except AttributeError:
+ pass
+ fielddict = nt.void.__getattribute__(self, 'dtype').fields
+ res = fielddict.get(attr, None)
+ if res:
+ obj = self.getfield(*res[:2])
+ # if it has fields return a record,
+ # otherwise return the object
+ try:
+ dt = obj.dtype
+ except AttributeError:
+ # happens if field is Object type
+ return obj
+ if dt.names is not None:
+ return obj.view((self.__class__, obj.dtype))
+ return obj
+ else:
+ raise AttributeError(f"'record' object has no attribute '{attr}'")
+
+ def __setattr__(self, attr, val):
+ if attr in ('setfield', 'getfield', 'dtype'):
+ raise AttributeError(f"Cannot set '{attr}' attribute")
+ fielddict = nt.void.__getattribute__(self, 'dtype').fields
+ res = fielddict.get(attr, None)
+ if res:
+ return self.setfield(val, *res[:2])
+ elif getattr(self, attr, None):
+ return nt.void.__setattr__(self, attr, val)
+ else:
+ raise AttributeError(f"'record' object has no attribute '{attr}'")
+
+ def __getitem__(self, indx):
+ obj = nt.void.__getitem__(self, indx)
+
+ # copy behavior of record.__getattribute__,
+ if isinstance(obj, nt.void) and obj.dtype.names is not None:
+ return obj.view((self.__class__, obj.dtype))
+ else:
+ # return a single element
+ return obj
+
+ def pprint(self):
+ """Pretty-print all fields."""
+ # pretty-print all fields
+ names = self.dtype.names
+ maxlen = max(len(name) for name in names)
+ fmt = '%% %ds: %%s' % maxlen
+ rows = [fmt % (name, getattr(self, name)) for name in names]
+ return "\n".join(rows)
+
+# The recarray is almost identical to a standard array (which supports
+# named fields already) The biggest difference is that it can use
+# attribute-lookup to find the fields and it is constructed using
+# a record.
+
+# If byteorder is given it forces a particular byteorder on all
+# the fields (and any subfields)
+
+
+@set_module("numpy.rec")
+class recarray(ndarray):
+ """Construct an ndarray that allows field access using attributes.
+
+ Arrays may have a data-types containing fields, analogous
+ to columns in a spread sheet. An example is ``[(x, int), (y, float)]``,
+ where each entry in the array is a pair of ``(int, float)``. Normally,
+ these attributes are accessed using dictionary lookups such as ``arr['x']``
+ and ``arr['y']``. Record arrays allow the fields to be accessed as members
+ of the array, using ``arr.x`` and ``arr.y``.
+
+ Parameters
+ ----------
+ shape : tuple
+ Shape of output array.
+ dtype : data-type, optional
+ The desired data-type. By default, the data-type is determined
+ from `formats`, `names`, `titles`, `aligned` and `byteorder`.
+ formats : list of data-types, optional
+ A list containing the data-types for the different columns, e.g.
+ ``['i4', 'f8', 'i4']``. `formats` does *not* support the new
+ convention of using types directly, i.e. ``(int, float, int)``.
+ Note that `formats` must be a list, not a tuple.
+ Given that `formats` is somewhat limited, we recommend specifying
+ `dtype` instead.
+ names : tuple of str, optional
+ The name of each column, e.g. ``('x', 'y', 'z')``.
+ buf : buffer, optional
+ By default, a new array is created of the given shape and data-type.
+ If `buf` is specified and is an object exposing the buffer interface,
+ the array will use the memory from the existing buffer. In this case,
+ the `offset` and `strides` keywords are available.
+
+ Other Parameters
+ ----------------
+ titles : tuple of str, optional
+ Aliases for column names. For example, if `names` were
+ ``('x', 'y', 'z')`` and `titles` is
+ ``('x_coordinate', 'y_coordinate', 'z_coordinate')``, then
+ ``arr['x']`` is equivalent to both ``arr.x`` and ``arr.x_coordinate``.
+ byteorder : {'<', '>', '='}, optional
+ Byte-order for all fields.
+ aligned : bool, optional
+ Align the fields in memory as the C-compiler would.
+ strides : tuple of ints, optional
+ Buffer (`buf`) is interpreted according to these strides (strides
+ define how many bytes each array element, row, column, etc.
+ occupy in memory).
+ offset : int, optional
+ Start reading buffer (`buf`) from this offset onwards.
+ order : {'C', 'F'}, optional
+ Row-major (C-style) or column-major (Fortran-style) order.
+
+ Returns
+ -------
+ rec : recarray
+ Empty array of the given shape and type.
+
+ See Also
+ --------
+ numpy.rec.fromrecords : Construct a record array from data.
+ numpy.record : fundamental data-type for `recarray`.
+ numpy.rec.format_parser : determine data-type from formats, names, titles.
+
+ Notes
+ -----
+ This constructor can be compared to ``empty``: it creates a new record
+ array but does not fill it with data. To create a record array from data,
+ use one of the following methods:
+
+ 1. Create a standard ndarray and convert it to a record array,
+ using ``arr.view(np.recarray)``
+ 2. Use the `buf` keyword.
+ 3. Use `np.rec.fromrecords`.
+
+ Examples
+ --------
+ Create an array with two fields, ``x`` and ``y``:
+
+ >>> import numpy as np
+ >>> x = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', '>> x
+ array([(1., 2), (3., 4)], dtype=[('x', '>> x['x']
+ array([1., 3.])
+
+ View the array as a record array:
+
+ >>> x = x.view(np.recarray)
+
+ >>> x.x
+ array([1., 3.])
+
+ >>> x.y
+ array([2, 4])
+
+ Create a new, empty record array:
+
+ >>> np.recarray((2,),
+ ... dtype=[('x', int), ('y', float), ('z', int)]) #doctest: +SKIP
+ rec.array([(-1073741821, 1.2249118382103472e-301, 24547520),
+ (3471280, 1.2134086255804012e-316, 0)],
+ dtype=[('x', ' 0 or self.shape == (0,):
+ lst = sb.array2string(
+ self, separator=', ', prefix=prefix, suffix=',')
+ else:
+ # show zero-length shape unless it is (0,)
+ lst = f"[], shape={repr(self.shape)}"
+
+ lf = '\n' + ' ' * len(prefix)
+ if _get_legacy_print_mode() <= 113:
+ lf = ' ' + lf # trailing space
+ return fmt % (lst, lf, repr_dtype)
+
+ def field(self, attr, val=None):
+ if isinstance(attr, int):
+ names = ndarray.__getattribute__(self, 'dtype').names
+ attr = names[attr]
+
+ fielddict = ndarray.__getattribute__(self, 'dtype').fields
+
+ res = fielddict[attr][:2]
+
+ if val is None:
+ obj = self.getfield(*res)
+ if obj.dtype.names is not None:
+ return obj
+ return obj.view(ndarray)
+ else:
+ return self.setfield(val, *res)
+
+
+def _deprecate_shape_0_as_None(shape):
+ if shape == 0:
+ warnings.warn(
+ "Passing `shape=0` to have the shape be inferred is deprecated, "
+ "and in future will be equivalent to `shape=(0,)`. To infer "
+ "the shape and suppress this warning, pass `shape=None` instead.",
+ FutureWarning, stacklevel=3)
+ return None
+ else:
+ return shape
+
+
+@set_module("numpy.rec")
+def fromarrays(arrayList, dtype=None, shape=None, formats=None,
+ names=None, titles=None, aligned=False, byteorder=None):
+ """Create a record array from a (flat) list of arrays
+
+ Parameters
+ ----------
+ arrayList : list or tuple
+ List of array-like objects (such as lists, tuples,
+ and ndarrays).
+ dtype : data-type, optional
+ valid dtype for all arrays
+ shape : int or tuple of ints, optional
+ Shape of the resulting array. If not provided, inferred from
+ ``arrayList[0]``.
+ formats, names, titles, aligned, byteorder :
+ If `dtype` is ``None``, these arguments are passed to
+ `numpy.rec.format_parser` to construct a dtype. See that function for
+ detailed documentation.
+
+ Returns
+ -------
+ np.recarray
+ Record array consisting of given arrayList columns.
+
+ Examples
+ --------
+ >>> x1=np.array([1,2,3,4])
+ >>> x2=np.array(['a','dd','xyz','12'])
+ >>> x3=np.array([1.1,2,3,4])
+ >>> r = np.rec.fromarrays([x1,x2,x3],names='a,b,c')
+ >>> print(r[1])
+ (2, 'dd', 2.0) # may vary
+ >>> x1[1]=34
+ >>> r.a
+ array([1, 2, 3, 4])
+
+ >>> x1 = np.array([1, 2, 3, 4])
+ >>> x2 = np.array(['a', 'dd', 'xyz', '12'])
+ >>> x3 = np.array([1.1, 2, 3,4])
+ >>> r = np.rec.fromarrays(
+ ... [x1, x2, x3],
+ ... dtype=np.dtype([('a', np.int32), ('b', 'S3'), ('c', np.float32)]))
+ >>> r
+ rec.array([(1, b'a', 1.1), (2, b'dd', 2. ), (3, b'xyz', 3. ),
+ (4, b'12', 4. )],
+ dtype=[('a', ' 0:
+ shape = shape[:-nn]
+
+ _array = recarray(shape, descr)
+
+ # populate the record array (makes a copy)
+ for k, obj in enumerate(arrayList):
+ nn = descr[k].ndim
+ testshape = obj.shape[:obj.ndim - nn]
+ name = _names[k]
+ if testshape != shape:
+ raise ValueError(f'array-shape mismatch in array {k} ("{name}")')
+
+ _array[name] = obj
+
+ return _array
+
+
+@set_module("numpy.rec")
+def fromrecords(recList, dtype=None, shape=None, formats=None, names=None,
+ titles=None, aligned=False, byteorder=None):
+ """Create a recarray from a list of records in text form.
+
+ Parameters
+ ----------
+ recList : sequence
+ data in the same field may be heterogeneous - they will be promoted
+ to the highest data type.
+ dtype : data-type, optional
+ valid dtype for all arrays
+ shape : int or tuple of ints, optional
+ shape of each array.
+ formats, names, titles, aligned, byteorder :
+ If `dtype` is ``None``, these arguments are passed to
+ `numpy.format_parser` to construct a dtype. See that function for
+ detailed documentation.
+
+ If both `formats` and `dtype` are None, then this will auto-detect
+ formats. Use list of tuples rather than list of lists for faster
+ processing.
+
+ Returns
+ -------
+ np.recarray
+ record array consisting of given recList rows.
+
+ Examples
+ --------
+ >>> r=np.rec.fromrecords([(456,'dbe',1.2),(2,'de',1.3)],
+ ... names='col1,col2,col3')
+ >>> print(r[0])
+ (456, 'dbe', 1.2)
+ >>> r.col1
+ array([456, 2])
+ >>> r.col2
+ array(['dbe', 'de'], dtype='>> import pickle
+ >>> pickle.loads(pickle.dumps(r))
+ rec.array([(456, 'dbe', 1.2), ( 2, 'de', 1.3)],
+ dtype=[('col1', ' 1:
+ raise ValueError("Can only deal with 1-d array.")
+ _array = recarray(shape, descr)
+ for k in range(_array.size):
+ _array[k] = tuple(recList[k])
+ # list of lists instead of list of tuples ?
+ # 2018-02-07, 1.14.1
+ warnings.warn(
+ "fromrecords expected a list of tuples, may have received a list "
+ "of lists instead. In the future that will raise an error",
+ FutureWarning, stacklevel=2)
+ return _array
+ else:
+ if shape is not None and retval.shape != shape:
+ retval.shape = shape
+
+ res = retval.view(recarray)
+
+ return res
+
+
+@set_module("numpy.rec")
+def fromstring(datastring, dtype=None, shape=None, offset=0, formats=None,
+ names=None, titles=None, aligned=False, byteorder=None):
+ r"""Create a record array from binary data
+
+ Note that despite the name of this function it does not accept `str`
+ instances.
+
+ Parameters
+ ----------
+ datastring : bytes-like
+ Buffer of binary data
+ dtype : data-type, optional
+ Valid dtype for all arrays
+ shape : int or tuple of ints, optional
+ Shape of each array.
+ offset : int, optional
+ Position in the buffer to start reading from.
+ formats, names, titles, aligned, byteorder :
+ If `dtype` is ``None``, these arguments are passed to
+ `numpy.format_parser` to construct a dtype. See that function for
+ detailed documentation.
+
+
+ Returns
+ -------
+ np.recarray
+ Record array view into the data in datastring. This will be readonly
+ if `datastring` is readonly.
+
+ See Also
+ --------
+ numpy.frombuffer
+
+ Examples
+ --------
+ >>> a = b'\x01\x02\x03abc'
+ >>> np.rec.fromstring(a, dtype='u1,u1,u1,S3')
+ rec.array([(1, 2, 3, b'abc')],
+ dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1'), ('f3', 'S3')])
+
+ >>> grades_dtype = [('Name', (np.str_, 10)), ('Marks', np.float64),
+ ... ('GradeLevel', np.int32)]
+ >>> grades_array = np.array([('Sam', 33.3, 3), ('Mike', 44.4, 5),
+ ... ('Aadi', 66.6, 6)], dtype=grades_dtype)
+ >>> np.rec.fromstring(grades_array.tobytes(), dtype=grades_dtype)
+ rec.array([('Sam', 33.3, 3), ('Mike', 44.4, 5), ('Aadi', 66.6, 6)],
+ dtype=[('Name', '>> s = '\x01\x02\x03abc'
+ >>> np.rec.fromstring(s, dtype='u1,u1,u1,S3')
+ Traceback (most recent call last):
+ ...
+ TypeError: a bytes-like object is required, not 'str'
+ """
+
+ if dtype is None and formats is None:
+ raise TypeError("fromstring() needs a 'dtype' or 'formats' argument")
+
+ if dtype is not None:
+ descr = sb.dtype(dtype)
+ else:
+ descr = format_parser(formats, names, titles, aligned, byteorder).dtype
+
+ itemsize = descr.itemsize
+
+ # NumPy 1.19.0, 2020-01-01
+ shape = _deprecate_shape_0_as_None(shape)
+
+ if shape in (None, -1):
+ shape = (len(datastring) - offset) // itemsize
+
+ _array = recarray(shape, descr, buf=datastring, offset=offset)
+ return _array
+
+def get_remaining_size(fd):
+ pos = fd.tell()
+ try:
+ fd.seek(0, 2)
+ return fd.tell() - pos
+ finally:
+ fd.seek(pos, 0)
+
+
+@set_module("numpy.rec")
+def fromfile(fd, dtype=None, shape=None, offset=0, formats=None,
+ names=None, titles=None, aligned=False, byteorder=None):
+ """Create an array from binary file data
+
+ Parameters
+ ----------
+ fd : str or file type
+ If file is a string or a path-like object then that file is opened,
+ else it is assumed to be a file object. The file object must
+ support random access (i.e. it must have tell and seek methods).
+ dtype : data-type, optional
+ valid dtype for all arrays
+ shape : int or tuple of ints, optional
+ shape of each array.
+ offset : int, optional
+ Position in the file to start reading from.
+ formats, names, titles, aligned, byteorder :
+ If `dtype` is ``None``, these arguments are passed to
+ `numpy.format_parser` to construct a dtype. See that function for
+ detailed documentation
+
+ Returns
+ -------
+ np.recarray
+ record array consisting of data enclosed in file.
+
+ Examples
+ --------
+ >>> from tempfile import TemporaryFile
+ >>> a = np.empty(10,dtype='f8,i4,a5')
+ >>> a[5] = (0.5,10,'abcde')
+ >>>
+ >>> fd=TemporaryFile()
+ >>> a = a.view(a.dtype.newbyteorder('<'))
+ >>> a.tofile(fd)
+ >>>
+ >>> _ = fd.seek(0)
+ >>> r=np.rec.fromfile(fd, formats='f8,i4,a5', shape=10,
+ ... byteorder='<')
+ >>> print(r[5])
+ (0.5, 10, b'abcde')
+ >>> r.shape
+ (10,)
+ """
+
+ if dtype is None and formats is None:
+ raise TypeError("fromfile() needs a 'dtype' or 'formats' argument")
+
+ # NumPy 1.19.0, 2020-01-01
+ shape = _deprecate_shape_0_as_None(shape)
+
+ if shape is None:
+ shape = (-1,)
+ elif isinstance(shape, int):
+ shape = (shape,)
+
+ if hasattr(fd, 'readinto'):
+ # GH issue 2504. fd supports io.RawIOBase or io.BufferedIOBase
+ # interface. Example of fd: gzip, BytesIO, BufferedReader
+ # file already opened
+ ctx = nullcontext(fd)
+ else:
+ # open file
+ ctx = open(os.fspath(fd), 'rb')
+
+ with ctx as fd:
+ if offset > 0:
+ fd.seek(offset, 1)
+ size = get_remaining_size(fd)
+
+ if dtype is not None:
+ descr = sb.dtype(dtype)
+ else:
+ descr = format_parser(
+ formats, names, titles, aligned, byteorder
+ ).dtype
+
+ itemsize = descr.itemsize
+
+ shapeprod = sb.array(shape).prod(dtype=nt.intp)
+ shapesize = shapeprod * itemsize
+ if shapesize < 0:
+ shape = list(shape)
+ shape[shape.index(-1)] = size // -shapesize
+ shape = tuple(shape)
+ shapeprod = sb.array(shape).prod(dtype=nt.intp)
+
+ nbytes = shapeprod * itemsize
+
+ if nbytes > size:
+ raise ValueError(
+ "Not enough bytes left in file for specified "
+ "shape and type."
+ )
+
+ # create the array
+ _array = recarray(shape, descr)
+ nbytesread = fd.readinto(_array.data)
+ if nbytesread != nbytes:
+ raise OSError("Didn't read as many bytes as expected")
+
+ return _array
+
+
+@set_module("numpy.rec")
+def array(obj, dtype=None, shape=None, offset=0, strides=None, formats=None,
+ names=None, titles=None, aligned=False, byteorder=None, copy=True):
+ """
+ Construct a record array from a wide-variety of objects.
+
+ A general-purpose record array constructor that dispatches to the
+ appropriate `recarray` creation function based on the inputs (see Notes).
+
+ Parameters
+ ----------
+ obj : any
+ Input object. See Notes for details on how various input types are
+ treated.
+ dtype : data-type, optional
+ Valid dtype for array.
+ shape : int or tuple of ints, optional
+ Shape of each array.
+ offset : int, optional
+ Position in the file or buffer to start reading from.
+ strides : tuple of ints, optional
+ Buffer (`buf`) is interpreted according to these strides (strides
+ define how many bytes each array element, row, column, etc.
+ occupy in memory).
+ formats, names, titles, aligned, byteorder :
+ If `dtype` is ``None``, these arguments are passed to
+ `numpy.format_parser` to construct a dtype. See that function for
+ detailed documentation.
+ copy : bool, optional
+ Whether to copy the input object (True), or to use a reference instead.
+ This option only applies when the input is an ndarray or recarray.
+ Defaults to True.
+
+ Returns
+ -------
+ np.recarray
+ Record array created from the specified object.
+
+ Notes
+ -----
+ If `obj` is ``None``, then call the `~numpy.recarray` constructor. If
+ `obj` is a string, then call the `fromstring` constructor. If `obj` is a
+ list or a tuple, then if the first object is an `~numpy.ndarray`, call
+ `fromarrays`, otherwise call `fromrecords`. If `obj` is a
+ `~numpy.recarray`, then make a copy of the data in the recarray
+ (if ``copy=True``) and use the new formats, names, and titles. If `obj`
+ is a file, then call `fromfile`. Finally, if obj is an `ndarray`, then
+ return ``obj.view(recarray)``, making a copy of the data if ``copy=True``.
+
+ Examples
+ --------
+ >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+ >>> a
+ array([[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]])
+
+ >>> np.rec.array(a)
+ rec.array([[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]],
+ dtype=int64)
+
+ >>> b = [(1, 1), (2, 4), (3, 9)]
+ >>> c = np.rec.array(b, formats = ['i2', 'f2'], names = ('x', 'y'))
+ >>> c
+ rec.array([(1, 1.), (2, 4.), (3, 9.)],
+ dtype=[('x', '>> c.x
+ array([1, 2, 3], dtype=int16)
+
+ >>> c.y
+ array([1., 4., 9.], dtype=float16)
+
+ >>> r = np.rec.array(['abc','def'], names=['col1','col2'])
+ >>> print(r.col1)
+ abc
+
+ >>> r.col1
+ array('abc', dtype='>> r.col2
+ array('def', dtype=' object: ...
+ def tell(self, /) -> int: ...
+ def readinto(self, buffer: memoryview, /) -> int: ...
+
+###
+
+# exported in `numpy.rec`
+class record(np.void): # type: ignore[misc]
+ __name__: ClassVar[Literal["record"]] = "record"
+ __module__: Literal["numpy"] = "numpy"
+
+ def pprint(self) -> str: ...
+
+ def __getattribute__(self, attr: str, /) -> Any: ...
+ def __setattr__(self, attr: str, val: ArrayLike, /) -> None: ...
+
+ @overload
+ def __getitem__(self, key: str | SupportsIndex, /) -> Incomplete: ...
+ @overload
+ def __getitem__(self, key: list[str], /) -> record: ...
+
+# exported in `numpy.rec`
+class recarray(np.ndarray[_ShapeT_co, _DTypeT_co]):
+ __name__: ClassVar[Literal["recarray"]] = "recarray"
+ __module__: Literal["numpy.rec"] = "numpy.rec"
+
+ @overload
+ def __new__(
+ subtype,
+ shape: _ShapeLike,
+ dtype: None = None,
+ buf: Buffer | None = None,
+ offset: SupportsIndex = 0,
+ strides: _ShapeLike | None = None,
+ *,
+ formats: DTypeLike | None,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ byteorder: _ByteOrder | None = None,
+ aligned: bool = False,
+ order: _OrderKACF = "C",
+ ) -> _RecArray[record]: ...
+ @overload
+ def __new__(
+ subtype,
+ shape: _ShapeLike,
+ dtype: DTypeLike | None,
+ buf: Buffer | None = None,
+ offset: SupportsIndex = 0,
+ strides: _ShapeLike | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ byteorder: None = None,
+ aligned: Literal[False] = False,
+ order: _OrderKACF = "C",
+ ) -> _RecArray[Incomplete]: ...
+
+ def __getattribute__(self, attr: str, /) -> Any: ...
+ def __setattr__(self, attr: str, val: ArrayLike, /) -> None: ...
+
+ def __array_finalize__(self, /, obj: object) -> None: ...
+
+ #
+ @overload
+ def field(self, /, attr: int | str, val: ArrayLike) -> None: ...
+ @overload
+ def field(self, /, attr: int | str, val: None = None) -> Incomplete: ...
+
+# exported in `numpy.rec`
+class format_parser:
+ dtype: np.dtype[np.void]
+ def __init__(
+ self,
+ /,
+ formats: DTypeLike | None,
+ names: str | Sequence[str] | None,
+ titles: str | Sequence[str] | None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+ ) -> None: ...
+
+# exported in `numpy.rec`
+@overload
+def fromarrays(
+ arrayList: Iterable[ArrayLike],
+ dtype: DTypeLike | None = None,
+ shape: _ShapeLike | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+) -> _RecArray[Any]: ...
+@overload
+def fromarrays(
+ arrayList: Iterable[ArrayLike],
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ *,
+ formats: DTypeLike | None,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+) -> _RecArray[record]: ...
+
+@overload
+def fromrecords(
+ recList: _ArrayLikeVoid_co | tuple[object, ...] | _NestedSequence[tuple[object, ...]],
+ dtype: DTypeLike | None = None,
+ shape: _ShapeLike | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+) -> _RecArray[record]: ...
+@overload
+def fromrecords(
+ recList: _ArrayLikeVoid_co | tuple[object, ...] | _NestedSequence[tuple[object, ...]],
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ *,
+ formats: DTypeLike | None,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+) -> _RecArray[record]: ...
+
+# exported in `numpy.rec`
+@overload
+def fromstring(
+ datastring: Buffer,
+ dtype: DTypeLike | None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+) -> _RecArray[record]: ...
+@overload
+def fromstring(
+ datastring: Buffer,
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ *,
+ formats: DTypeLike | None,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+) -> _RecArray[record]: ...
+
+# exported in `numpy.rec`
+@overload
+def fromfile(
+ fd: StrOrBytesPath | _SupportsReadInto,
+ dtype: DTypeLike | None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+) -> _RecArray[Any]: ...
+@overload
+def fromfile(
+ fd: StrOrBytesPath | _SupportsReadInto,
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ *,
+ formats: DTypeLike | None,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+) -> _RecArray[record]: ...
+
+# exported in `numpy.rec`
+@overload
+def array(
+ obj: _ScalarT | NDArray[_ScalarT],
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+ copy: bool = True,
+) -> _RecArray[_ScalarT]: ...
+@overload
+def array(
+ obj: ArrayLike,
+ dtype: DTypeLike | None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+ copy: bool = True,
+) -> _RecArray[Any]: ...
+@overload
+def array(
+ obj: ArrayLike,
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ *,
+ formats: DTypeLike | None,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+ copy: bool = True,
+) -> _RecArray[record]: ...
+@overload
+def array(
+ obj: None,
+ dtype: DTypeLike | None,
+ shape: _ShapeLike,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+ copy: bool = True,
+) -> _RecArray[Any]: ...
+@overload
+def array(
+ obj: None,
+ dtype: None = None,
+ *,
+ shape: _ShapeLike,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ formats: DTypeLike | None,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+ copy: bool = True,
+) -> _RecArray[record]: ...
+@overload
+def array(
+ obj: _SupportsReadInto,
+ dtype: DTypeLike | None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ formats: None = None,
+ names: None = None,
+ titles: None = None,
+ aligned: bool = False,
+ byteorder: None = None,
+ copy: bool = True,
+) -> _RecArray[Any]: ...
+@overload
+def array(
+ obj: _SupportsReadInto,
+ dtype: None = None,
+ shape: _ShapeLike | None = None,
+ offset: int = 0,
+ strides: tuple[int, ...] | None = None,
+ *,
+ formats: DTypeLike | None,
+ names: str | Sequence[str] | None = None,
+ titles: str | Sequence[str] | None = None,
+ aligned: bool = False,
+ byteorder: _ByteOrder | None = None,
+ copy: bool = True,
+) -> _RecArray[record]: ...
+
+# exported in `numpy.rec`
+def find_duplicate(list: Iterable[_T]) -> list[_T]: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/shape_base.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/shape_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..39de8739db0eef8f1cd740467538a807d6d58e87
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/shape_base.py
@@ -0,0 +1,996 @@
+__all__ = ['atleast_1d', 'atleast_2d', 'atleast_3d', 'block', 'hstack',
+ 'stack', 'unstack', 'vstack']
+
+import functools
+import itertools
+import operator
+
+from . import fromnumeric as _from_nx, numeric as _nx, overrides
+from .multiarray import array, asanyarray, normalize_axis_index
+
+array_function_dispatch = functools.partial(
+ overrides.array_function_dispatch, module='numpy')
+
+
+def _atleast_1d_dispatcher(*arys):
+ return arys
+
+
+@array_function_dispatch(_atleast_1d_dispatcher)
+def atleast_1d(*arys):
+ """
+ Convert inputs to arrays with at least one dimension.
+
+ Scalar inputs are converted to 1-dimensional arrays, whilst
+ higher-dimensional inputs are preserved.
+
+ Parameters
+ ----------
+ arys1, arys2, ... : array_like
+ One or more input arrays.
+
+ Returns
+ -------
+ ret : ndarray
+ An array, or tuple of arrays, each with ``a.ndim >= 1``.
+ Copies are made only if necessary.
+
+ See Also
+ --------
+ atleast_2d, atleast_3d
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.atleast_1d(1.0)
+ array([1.])
+
+ >>> x = np.arange(9.0).reshape(3,3)
+ >>> np.atleast_1d(x)
+ array([[0., 1., 2.],
+ [3., 4., 5.],
+ [6., 7., 8.]])
+ >>> np.atleast_1d(x) is x
+ True
+
+ >>> np.atleast_1d(1, [3, 4])
+ (array([1]), array([3, 4]))
+
+ """
+ if len(arys) == 1:
+ result = asanyarray(arys[0])
+ if result.ndim == 0:
+ result = result.reshape(1)
+ return result
+ res = []
+ for ary in arys:
+ result = asanyarray(ary)
+ if result.ndim == 0:
+ result = result.reshape(1)
+ res.append(result)
+ return tuple(res)
+
+
+def _atleast_2d_dispatcher(*arys):
+ return arys
+
+
+@array_function_dispatch(_atleast_2d_dispatcher)
+def atleast_2d(*arys):
+ """
+ View inputs as arrays with at least two dimensions.
+
+ Parameters
+ ----------
+ arys1, arys2, ... : array_like
+ One or more array-like sequences. Non-array inputs are converted
+ to arrays. Arrays that already have two or more dimensions are
+ preserved.
+
+ Returns
+ -------
+ res, res2, ... : ndarray
+ An array, or tuple of arrays, each with ``a.ndim >= 2``.
+ Copies are avoided where possible, and views with two or more
+ dimensions are returned.
+
+ See Also
+ --------
+ atleast_1d, atleast_3d
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.atleast_2d(3.0)
+ array([[3.]])
+
+ >>> x = np.arange(3.0)
+ >>> np.atleast_2d(x)
+ array([[0., 1., 2.]])
+ >>> np.atleast_2d(x).base is x
+ True
+
+ >>> np.atleast_2d(1, [1, 2], [[1, 2]])
+ (array([[1]]), array([[1, 2]]), array([[1, 2]]))
+
+ """
+ res = []
+ for ary in arys:
+ ary = asanyarray(ary)
+ if ary.ndim == 0:
+ result = ary.reshape(1, 1)
+ elif ary.ndim == 1:
+ result = ary[_nx.newaxis, :]
+ else:
+ result = ary
+ res.append(result)
+ if len(res) == 1:
+ return res[0]
+ else:
+ return tuple(res)
+
+
+def _atleast_3d_dispatcher(*arys):
+ return arys
+
+
+@array_function_dispatch(_atleast_3d_dispatcher)
+def atleast_3d(*arys):
+ """
+ View inputs as arrays with at least three dimensions.
+
+ Parameters
+ ----------
+ arys1, arys2, ... : array_like
+ One or more array-like sequences. Non-array inputs are converted to
+ arrays. Arrays that already have three or more dimensions are
+ preserved.
+
+ Returns
+ -------
+ res1, res2, ... : ndarray
+ An array, or tuple of arrays, each with ``a.ndim >= 3``. Copies are
+ avoided where possible, and views with three or more dimensions are
+ returned. For example, a 1-D array of shape ``(N,)`` becomes a view
+ of shape ``(1, N, 1)``, and a 2-D array of shape ``(M, N)`` becomes a
+ view of shape ``(M, N, 1)``.
+
+ See Also
+ --------
+ atleast_1d, atleast_2d
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.atleast_3d(3.0)
+ array([[[3.]]])
+
+ >>> x = np.arange(3.0)
+ >>> np.atleast_3d(x).shape
+ (1, 3, 1)
+
+ >>> x = np.arange(12.0).reshape(4,3)
+ >>> np.atleast_3d(x).shape
+ (4, 3, 1)
+ >>> np.atleast_3d(x).base is x.base # x is a reshape, so not base itself
+ True
+
+ >>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]):
+ ... print(arr, arr.shape) # doctest: +SKIP
+ ...
+ [[[1]
+ [2]]] (1, 2, 1)
+ [[[1]
+ [2]]] (1, 2, 1)
+ [[[1 2]]] (1, 1, 2)
+
+ """
+ res = []
+ for ary in arys:
+ ary = asanyarray(ary)
+ if ary.ndim == 0:
+ result = ary.reshape(1, 1, 1)
+ elif ary.ndim == 1:
+ result = ary[_nx.newaxis, :, _nx.newaxis]
+ elif ary.ndim == 2:
+ result = ary[:, :, _nx.newaxis]
+ else:
+ result = ary
+ res.append(result)
+ if len(res) == 1:
+ return res[0]
+ else:
+ return tuple(res)
+
+
+def _arrays_for_stack_dispatcher(arrays):
+ if not hasattr(arrays, "__getitem__"):
+ raise TypeError('arrays to stack must be passed as a "sequence" type '
+ 'such as list or tuple.')
+
+ return tuple(arrays)
+
+
+def _vhstack_dispatcher(tup, *, dtype=None, casting=None):
+ return _arrays_for_stack_dispatcher(tup)
+
+
+@array_function_dispatch(_vhstack_dispatcher)
+def vstack(tup, *, dtype=None, casting="same_kind"):
+ """
+ Stack arrays in sequence vertically (row wise).
+
+ This is equivalent to concatenation along the first axis after 1-D arrays
+ of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by
+ `vsplit`.
+
+ This function makes most sense for arrays with up to 3 dimensions. For
+ instance, for pixel-data with a height (first axis), width (second axis),
+ and r/g/b channels (third axis). The functions `concatenate`, `stack` and
+ `block` provide more general stacking and concatenation operations.
+
+ Parameters
+ ----------
+ tup : sequence of ndarrays
+ The arrays must have the same shape along all but the first axis.
+ 1-D arrays must have the same length. In the case of a single
+ array_like input, it will be treated as a sequence of arrays; i.e.,
+ each element along the zeroth axis is treated as a separate array.
+
+ dtype : str or dtype
+ If provided, the destination array will have this dtype. Cannot be
+ provided together with `out`.
+
+ .. versionadded:: 1.24
+
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Defaults to 'same_kind'.
+
+ .. versionadded:: 1.24
+
+ Returns
+ -------
+ stacked : ndarray
+ The array formed by stacking the given arrays, will be at least 2-D.
+
+ See Also
+ --------
+ concatenate : Join a sequence of arrays along an existing axis.
+ stack : Join a sequence of arrays along a new axis.
+ block : Assemble an nd-array from nested lists of blocks.
+ hstack : Stack arrays in sequence horizontally (column wise).
+ dstack : Stack arrays in sequence depth wise (along third axis).
+ column_stack : Stack 1-D arrays as columns into a 2-D array.
+ vsplit : Split an array into multiple sub-arrays vertically (row-wise).
+ unstack : Split an array into a tuple of sub-arrays along an axis.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([1, 2, 3])
+ >>> b = np.array([4, 5, 6])
+ >>> np.vstack((a,b))
+ array([[1, 2, 3],
+ [4, 5, 6]])
+
+ >>> a = np.array([[1], [2], [3]])
+ >>> b = np.array([[4], [5], [6]])
+ >>> np.vstack((a,b))
+ array([[1],
+ [2],
+ [3],
+ [4],
+ [5],
+ [6]])
+
+ """
+ arrs = atleast_2d(*tup)
+ if not isinstance(arrs, tuple):
+ arrs = (arrs,)
+ return _nx.concatenate(arrs, 0, dtype=dtype, casting=casting)
+
+
+@array_function_dispatch(_vhstack_dispatcher)
+def hstack(tup, *, dtype=None, casting="same_kind"):
+ """
+ Stack arrays in sequence horizontally (column wise).
+
+ This is equivalent to concatenation along the second axis, except for 1-D
+ arrays where it concatenates along the first axis. Rebuilds arrays divided
+ by `hsplit`.
+
+ This function makes most sense for arrays with up to 3 dimensions. For
+ instance, for pixel-data with a height (first axis), width (second axis),
+ and r/g/b channels (third axis). The functions `concatenate`, `stack` and
+ `block` provide more general stacking and concatenation operations.
+
+ Parameters
+ ----------
+ tup : sequence of ndarrays
+ The arrays must have the same shape along all but the second axis,
+ except 1-D arrays which can be any length. In the case of a single
+ array_like input, it will be treated as a sequence of arrays; i.e.,
+ each element along the zeroth axis is treated as a separate array.
+
+ dtype : str or dtype
+ If provided, the destination array will have this dtype. Cannot be
+ provided together with `out`.
+
+ .. versionadded:: 1.24
+
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Defaults to 'same_kind'.
+
+ .. versionadded:: 1.24
+
+ Returns
+ -------
+ stacked : ndarray
+ The array formed by stacking the given arrays.
+
+ See Also
+ --------
+ concatenate : Join a sequence of arrays along an existing axis.
+ stack : Join a sequence of arrays along a new axis.
+ block : Assemble an nd-array from nested lists of blocks.
+ vstack : Stack arrays in sequence vertically (row wise).
+ dstack : Stack arrays in sequence depth wise (along third axis).
+ column_stack : Stack 1-D arrays as columns into a 2-D array.
+ hsplit : Split an array into multiple sub-arrays
+ horizontally (column-wise).
+ unstack : Split an array into a tuple of sub-arrays along an axis.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array((1,2,3))
+ >>> b = np.array((4,5,6))
+ >>> np.hstack((a,b))
+ array([1, 2, 3, 4, 5, 6])
+ >>> a = np.array([[1],[2],[3]])
+ >>> b = np.array([[4],[5],[6]])
+ >>> np.hstack((a,b))
+ array([[1, 4],
+ [2, 5],
+ [3, 6]])
+
+ """
+ arrs = atleast_1d(*tup)
+ if not isinstance(arrs, tuple):
+ arrs = (arrs,)
+ # As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
+ if arrs and arrs[0].ndim == 1:
+ return _nx.concatenate(arrs, 0, dtype=dtype, casting=casting)
+ else:
+ return _nx.concatenate(arrs, 1, dtype=dtype, casting=casting)
+
+
+def _stack_dispatcher(arrays, axis=None, out=None, *,
+ dtype=None, casting=None):
+ arrays = _arrays_for_stack_dispatcher(arrays)
+ if out is not None:
+ # optimize for the typical case where only arrays is provided
+ arrays = list(arrays)
+ arrays.append(out)
+ return arrays
+
+
+@array_function_dispatch(_stack_dispatcher)
+def stack(arrays, axis=0, out=None, *, dtype=None, casting="same_kind"):
+ """
+ Join a sequence of arrays along a new axis.
+
+ The ``axis`` parameter specifies the index of the new axis in the
+ dimensions of the result. For example, if ``axis=0`` it will be the first
+ dimension and if ``axis=-1`` it will be the last dimension.
+
+ Parameters
+ ----------
+ arrays : sequence of ndarrays
+ Each array must have the same shape. In the case of a single ndarray
+ array_like input, it will be treated as a sequence of arrays; i.e.,
+ each element along the zeroth axis is treated as a separate array.
+
+ axis : int, optional
+ The axis in the result array along which the input arrays are stacked.
+
+ out : ndarray, optional
+ If provided, the destination to place the result. The shape must be
+ correct, matching that of what stack would have returned if no
+ out argument were specified.
+
+ dtype : str or dtype
+ If provided, the destination array will have this dtype. Cannot be
+ provided together with `out`.
+
+ .. versionadded:: 1.24
+
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur. Defaults to 'same_kind'.
+
+ .. versionadded:: 1.24
+
+
+ Returns
+ -------
+ stacked : ndarray
+ The stacked array has one more dimension than the input arrays.
+
+ See Also
+ --------
+ concatenate : Join a sequence of arrays along an existing axis.
+ block : Assemble an nd-array from nested lists of blocks.
+ split : Split array into a list of multiple sub-arrays of equal size.
+ unstack : Split an array into a tuple of sub-arrays along an axis.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> rng = np.random.default_rng()
+ >>> arrays = [rng.normal(size=(3,4)) for _ in range(10)]
+ >>> np.stack(arrays, axis=0).shape
+ (10, 3, 4)
+
+ >>> np.stack(arrays, axis=1).shape
+ (3, 10, 4)
+
+ >>> np.stack(arrays, axis=2).shape
+ (3, 4, 10)
+
+ >>> a = np.array([1, 2, 3])
+ >>> b = np.array([4, 5, 6])
+ >>> np.stack((a, b))
+ array([[1, 2, 3],
+ [4, 5, 6]])
+
+ >>> np.stack((a, b), axis=-1)
+ array([[1, 4],
+ [2, 5],
+ [3, 6]])
+
+ """
+ arrays = [asanyarray(arr) for arr in arrays]
+ if not arrays:
+ raise ValueError('need at least one array to stack')
+
+ shapes = {arr.shape for arr in arrays}
+ if len(shapes) != 1:
+ raise ValueError('all input arrays must have the same shape')
+
+ result_ndim = arrays[0].ndim + 1
+ axis = normalize_axis_index(axis, result_ndim)
+
+ sl = (slice(None),) * axis + (_nx.newaxis,)
+ expanded_arrays = [arr[sl] for arr in arrays]
+ return _nx.concatenate(expanded_arrays, axis=axis, out=out,
+ dtype=dtype, casting=casting)
+
+def _unstack_dispatcher(x, /, *, axis=None):
+ return (x,)
+
+@array_function_dispatch(_unstack_dispatcher)
+def unstack(x, /, *, axis=0):
+ """
+ Split an array into a sequence of arrays along the given axis.
+
+ The ``axis`` parameter specifies the dimension along which the array will
+ be split. For example, if ``axis=0`` (the default) it will be the first
+ dimension and if ``axis=-1`` it will be the last dimension.
+
+ The result is a tuple of arrays split along ``axis``.
+
+ .. versionadded:: 2.1.0
+
+ Parameters
+ ----------
+ x : ndarray
+ The array to be unstacked.
+ axis : int, optional
+ Axis along which the array will be split. Default: ``0``.
+
+ Returns
+ -------
+ unstacked : tuple of ndarrays
+ The unstacked arrays.
+
+ See Also
+ --------
+ stack : Join a sequence of arrays along a new axis.
+ concatenate : Join a sequence of arrays along an existing axis.
+ block : Assemble an nd-array from nested lists of blocks.
+ split : Split array into a list of multiple sub-arrays of equal size.
+
+ Notes
+ -----
+ ``unstack`` serves as the reverse operation of :py:func:`stack`, i.e.,
+ ``stack(unstack(x, axis=axis), axis=axis) == x``.
+
+ This function is equivalent to ``tuple(np.moveaxis(x, axis, 0))``, since
+ iterating on an array iterates along the first axis.
+
+ Examples
+ --------
+ >>> arr = np.arange(24).reshape((2, 3, 4))
+ >>> np.unstack(arr)
+ (array([[ 0, 1, 2, 3],
+ [ 4, 5, 6, 7],
+ [ 8, 9, 10, 11]]),
+ array([[12, 13, 14, 15],
+ [16, 17, 18, 19],
+ [20, 21, 22, 23]]))
+ >>> np.unstack(arr, axis=1)
+ (array([[ 0, 1, 2, 3],
+ [12, 13, 14, 15]]),
+ array([[ 4, 5, 6, 7],
+ [16, 17, 18, 19]]),
+ array([[ 8, 9, 10, 11],
+ [20, 21, 22, 23]]))
+ >>> arr2 = np.stack(np.unstack(arr, axis=1), axis=1)
+ >>> arr2.shape
+ (2, 3, 4)
+ >>> np.all(arr == arr2)
+ np.True_
+
+ """
+ if x.ndim == 0:
+ raise ValueError("Input array must be at least 1-d.")
+ return tuple(_nx.moveaxis(x, axis, 0))
+
+
+# Internal functions to eliminate the overhead of repeated dispatch in one of
+# the two possible paths inside np.block.
+# Use getattr to protect against __array_function__ being disabled.
+_size = getattr(_from_nx.size, '__wrapped__', _from_nx.size)
+_ndim = getattr(_from_nx.ndim, '__wrapped__', _from_nx.ndim)
+_concatenate = getattr(_from_nx.concatenate,
+ '__wrapped__', _from_nx.concatenate)
+
+
+def _block_format_index(index):
+ """
+ Convert a list of indices ``[0, 1, 2]`` into ``"arrays[0][1][2]"``.
+ """
+ idx_str = ''.join(f'[{i}]' for i in index if i is not None)
+ return 'arrays' + idx_str
+
+
+def _block_check_depths_match(arrays, parent_index=[]):
+ """
+ Recursive function checking that the depths of nested lists in `arrays`
+ all match. Mismatch raises a ValueError as described in the block
+ docstring below.
+
+ The entire index (rather than just the depth) needs to be calculated
+ for each innermost list, in case an error needs to be raised, so that
+ the index of the offending list can be printed as part of the error.
+
+ Parameters
+ ----------
+ arrays : nested list of arrays
+ The arrays to check
+ parent_index : list of int
+ The full index of `arrays` within the nested lists passed to
+ `_block_check_depths_match` at the top of the recursion.
+
+ Returns
+ -------
+ first_index : list of int
+ The full index of an element from the bottom of the nesting in
+ `arrays`. If any element at the bottom is an empty list, this will
+ refer to it, and the last index along the empty axis will be None.
+ max_arr_ndim : int
+ The maximum of the ndims of the arrays nested in `arrays`.
+ final_size: int
+ The number of elements in the final array. This is used the motivate
+ the choice of algorithm used using benchmarking wisdom.
+
+ """
+ if isinstance(arrays, tuple):
+ # not strictly necessary, but saves us from:
+ # - more than one way to do things - no point treating tuples like
+ # lists
+ # - horribly confusing behaviour that results when tuples are
+ # treated like ndarray
+ raise TypeError(
+ f'{_block_format_index(parent_index)} is a tuple. '
+ 'Only lists can be used to arrange blocks, and np.block does '
+ 'not allow implicit conversion from tuple to ndarray.'
+ )
+ elif isinstance(arrays, list) and len(arrays) > 0:
+ idxs_ndims = (_block_check_depths_match(arr, parent_index + [i])
+ for i, arr in enumerate(arrays))
+
+ first_index, max_arr_ndim, final_size = next(idxs_ndims)
+ for index, ndim, size in idxs_ndims:
+ final_size += size
+ if ndim > max_arr_ndim:
+ max_arr_ndim = ndim
+ if len(index) != len(first_index):
+ raise ValueError(
+ "List depths are mismatched. First element was at "
+ f"depth {len(first_index)}, but there is an element at "
+ f"depth {len(index)} ({_block_format_index(index)})"
+ )
+ # propagate our flag that indicates an empty list at the bottom
+ if index[-1] is None:
+ first_index = index
+
+ return first_index, max_arr_ndim, final_size
+ elif isinstance(arrays, list) and len(arrays) == 0:
+ # We've 'bottomed out' on an empty list
+ return parent_index + [None], 0, 0
+ else:
+ # We've 'bottomed out' - arrays is either a scalar or an array
+ size = _size(arrays)
+ return parent_index, _ndim(arrays), size
+
+
+def _atleast_nd(a, ndim):
+ # Ensures `a` has at least `ndim` dimensions by prepending
+ # ones to `a.shape` as necessary
+ return array(a, ndmin=ndim, copy=None, subok=True)
+
+
+def _accumulate(values):
+ return list(itertools.accumulate(values))
+
+
+def _concatenate_shapes(shapes, axis):
+ """Given array shapes, return the resulting shape and slices prefixes.
+
+ These help in nested concatenation.
+
+ Returns
+ -------
+ shape: tuple of int
+ This tuple satisfies::
+
+ shape, _ = _concatenate_shapes([arr.shape for shape in arrs], axis)
+ shape == concatenate(arrs, axis).shape
+
+ slice_prefixes: tuple of (slice(start, end), )
+ For a list of arrays being concatenated, this returns the slice
+ in the larger array at axis that needs to be sliced into.
+
+ For example, the following holds::
+
+ ret = concatenate([a, b, c], axis)
+ _, (sl_a, sl_b, sl_c) = concatenate_slices([a, b, c], axis)
+
+ ret[(slice(None),) * axis + sl_a] == a
+ ret[(slice(None),) * axis + sl_b] == b
+ ret[(slice(None),) * axis + sl_c] == c
+
+ These are called slice prefixes since they are used in the recursive
+ blocking algorithm to compute the left-most slices during the
+ recursion. Therefore, they must be prepended to rest of the slice
+ that was computed deeper in the recursion.
+
+ These are returned as tuples to ensure that they can quickly be added
+ to existing slice tuple without creating a new tuple every time.
+
+ """
+ # Cache a result that will be reused.
+ shape_at_axis = [shape[axis] for shape in shapes]
+
+ # Take a shape, any shape
+ first_shape = shapes[0]
+ first_shape_pre = first_shape[:axis]
+ first_shape_post = first_shape[axis + 1:]
+
+ if any(shape[:axis] != first_shape_pre or
+ shape[axis + 1:] != first_shape_post for shape in shapes):
+ raise ValueError(
+ f'Mismatched array shapes in block along axis {axis}.')
+
+ shape = (first_shape_pre + (sum(shape_at_axis),) + first_shape[axis + 1:])
+
+ offsets_at_axis = _accumulate(shape_at_axis)
+ slice_prefixes = [(slice(start, end),)
+ for start, end in zip([0] + offsets_at_axis,
+ offsets_at_axis)]
+ return shape, slice_prefixes
+
+
+def _block_info_recursion(arrays, max_depth, result_ndim, depth=0):
+ """
+ Returns the shape of the final array, along with a list
+ of slices and a list of arrays that can be used for assignment inside the
+ new array
+
+ Parameters
+ ----------
+ arrays : nested list of arrays
+ The arrays to check
+ max_depth : list of int
+ The number of nested lists
+ result_ndim : int
+ The number of dimensions in thefinal array.
+
+ Returns
+ -------
+ shape : tuple of int
+ The shape that the final array will take on.
+ slices: list of tuple of slices
+ The slices into the full array required for assignment. These are
+ required to be prepended with ``(Ellipsis, )`` to obtain to correct
+ final index.
+ arrays: list of ndarray
+ The data to assign to each slice of the full array
+
+ """
+ if depth < max_depth:
+ shapes, slices, arrays = zip(
+ *[_block_info_recursion(arr, max_depth, result_ndim, depth + 1)
+ for arr in arrays])
+
+ axis = result_ndim - max_depth + depth
+ shape, slice_prefixes = _concatenate_shapes(shapes, axis)
+
+ # Prepend the slice prefix and flatten the slices
+ slices = [slice_prefix + the_slice
+ for slice_prefix, inner_slices in zip(slice_prefixes, slices)
+ for the_slice in inner_slices]
+
+ # Flatten the array list
+ arrays = functools.reduce(operator.add, arrays)
+
+ return shape, slices, arrays
+ else:
+ # We've 'bottomed out' - arrays is either a scalar or an array
+ # type(arrays) is not list
+ # Return the slice and the array inside a list to be consistent with
+ # the recursive case.
+ arr = _atleast_nd(arrays, result_ndim)
+ return arr.shape, [()], [arr]
+
+
+def _block(arrays, max_depth, result_ndim, depth=0):
+ """
+ Internal implementation of block based on repeated concatenation.
+ `arrays` is the argument passed to
+ block. `max_depth` is the depth of nested lists within `arrays` and
+ `result_ndim` is the greatest of the dimensions of the arrays in
+ `arrays` and the depth of the lists in `arrays` (see block docstring
+ for details).
+ """
+ if depth < max_depth:
+ arrs = [_block(arr, max_depth, result_ndim, depth + 1)
+ for arr in arrays]
+ return _concatenate(arrs, axis=-(max_depth - depth))
+ else:
+ # We've 'bottomed out' - arrays is either a scalar or an array
+ # type(arrays) is not list
+ return _atleast_nd(arrays, result_ndim)
+
+
+def _block_dispatcher(arrays):
+ # Use type(...) is list to match the behavior of np.block(), which special
+ # cases list specifically rather than allowing for generic iterables or
+ # tuple. Also, we know that list.__array_function__ will never exist.
+ if isinstance(arrays, list):
+ for subarrays in arrays:
+ yield from _block_dispatcher(subarrays)
+ else:
+ yield arrays
+
+
+@array_function_dispatch(_block_dispatcher)
+def block(arrays):
+ """
+ Assemble an nd-array from nested lists of blocks.
+
+ Blocks in the innermost lists are concatenated (see `concatenate`) along
+ the last dimension (-1), then these are concatenated along the
+ second-last dimension (-2), and so on until the outermost list is reached.
+
+ Blocks can be of any dimension, but will not be broadcasted using
+ the normal rules. Instead, leading axes of size 1 are inserted,
+ to make ``block.ndim`` the same for all blocks. This is primarily useful
+ for working with scalars, and means that code like ``np.block([v, 1])``
+ is valid, where ``v.ndim == 1``.
+
+ When the nested list is two levels deep, this allows block matrices to be
+ constructed from their components.
+
+ Parameters
+ ----------
+ arrays : nested list of array_like or scalars (but not tuples)
+ If passed a single ndarray or scalar (a nested list of depth 0), this
+ is returned unmodified (and not copied).
+
+ Elements shapes must match along the appropriate axes (without
+ broadcasting), but leading 1s will be prepended to the shape as
+ necessary to make the dimensions match.
+
+ Returns
+ -------
+ block_array : ndarray
+ The array assembled from the given blocks.
+
+ The dimensionality of the output is equal to the greatest of:
+
+ * the dimensionality of all the inputs
+ * the depth to which the input list is nested
+
+ Raises
+ ------
+ ValueError
+ * If list depths are mismatched - for instance, ``[[a, b], c]`` is
+ illegal, and should be spelt ``[[a, b], [c]]``
+ * If lists are empty - for instance, ``[[a, b], []]``
+
+ See Also
+ --------
+ concatenate : Join a sequence of arrays along an existing axis.
+ stack : Join a sequence of arrays along a new axis.
+ vstack : Stack arrays in sequence vertically (row wise).
+ hstack : Stack arrays in sequence horizontally (column wise).
+ dstack : Stack arrays in sequence depth wise (along third axis).
+ column_stack : Stack 1-D arrays as columns into a 2-D array.
+ vsplit : Split an array into multiple sub-arrays vertically (row-wise).
+ unstack : Split an array into a tuple of sub-arrays along an axis.
+
+ Notes
+ -----
+ When called with only scalars, ``np.block`` is equivalent to an ndarray
+ call. So ``np.block([[1, 2], [3, 4]])`` is equivalent to
+ ``np.array([[1, 2], [3, 4]])``.
+
+ This function does not enforce that the blocks lie on a fixed grid.
+ ``np.block([[a, b], [c, d]])`` is not restricted to arrays of the form::
+
+ AAAbb
+ AAAbb
+ cccDD
+
+ But is also allowed to produce, for some ``a, b, c, d``::
+
+ AAAbb
+ AAAbb
+ cDDDD
+
+ Since concatenation happens along the last axis first, `block` is *not*
+ capable of producing the following directly::
+
+ AAAbb
+ cccbb
+ cccDD
+
+ Matlab's "square bracket stacking", ``[A, B, ...; p, q, ...]``, is
+ equivalent to ``np.block([[A, B, ...], [p, q, ...]])``.
+
+ Examples
+ --------
+ The most common use of this function is to build a block matrix:
+
+ >>> import numpy as np
+ >>> A = np.eye(2) * 2
+ >>> B = np.eye(3) * 3
+ >>> np.block([
+ ... [A, np.zeros((2, 3))],
+ ... [np.ones((3, 2)), B ]
+ ... ])
+ array([[2., 0., 0., 0., 0.],
+ [0., 2., 0., 0., 0.],
+ [1., 1., 3., 0., 0.],
+ [1., 1., 0., 3., 0.],
+ [1., 1., 0., 0., 3.]])
+
+ With a list of depth 1, `block` can be used as `hstack`:
+
+ >>> np.block([1, 2, 3]) # hstack([1, 2, 3])
+ array([1, 2, 3])
+
+ >>> a = np.array([1, 2, 3])
+ >>> b = np.array([4, 5, 6])
+ >>> np.block([a, b, 10]) # hstack([a, b, 10])
+ array([ 1, 2, 3, 4, 5, 6, 10])
+
+ >>> A = np.ones((2, 2), int)
+ >>> B = 2 * A
+ >>> np.block([A, B]) # hstack([A, B])
+ array([[1, 1, 2, 2],
+ [1, 1, 2, 2]])
+
+ With a list of depth 2, `block` can be used in place of `vstack`:
+
+ >>> a = np.array([1, 2, 3])
+ >>> b = np.array([4, 5, 6])
+ >>> np.block([[a], [b]]) # vstack([a, b])
+ array([[1, 2, 3],
+ [4, 5, 6]])
+
+ >>> A = np.ones((2, 2), int)
+ >>> B = 2 * A
+ >>> np.block([[A], [B]]) # vstack([A, B])
+ array([[1, 1],
+ [1, 1],
+ [2, 2],
+ [2, 2]])
+
+ It can also be used in place of `atleast_1d` and `atleast_2d`:
+
+ >>> a = np.array(0)
+ >>> b = np.array([1])
+ >>> np.block([a]) # atleast_1d(a)
+ array([0])
+ >>> np.block([b]) # atleast_1d(b)
+ array([1])
+
+ >>> np.block([[a]]) # atleast_2d(a)
+ array([[0]])
+ >>> np.block([[b]]) # atleast_2d(b)
+ array([[1]])
+
+
+ """
+ arrays, list_ndim, result_ndim, final_size = _block_setup(arrays)
+
+ # It was found through benchmarking that making an array of final size
+ # around 256x256 was faster by straight concatenation on a
+ # i7-7700HQ processor and dual channel ram 2400MHz.
+ # It didn't seem to matter heavily on the dtype used.
+ #
+ # A 2D array using repeated concatenation requires 2 copies of the array.
+ #
+ # The fastest algorithm will depend on the ratio of CPU power to memory
+ # speed.
+ # One can monitor the results of the benchmark
+ # https://pv.github.io/numpy-bench/#bench_shape_base.Block2D.time_block2d
+ # to tune this parameter until a C version of the `_block_info_recursion`
+ # algorithm is implemented which would likely be faster than the python
+ # version.
+ if list_ndim * final_size > (2 * 512 * 512):
+ return _block_slicing(arrays, list_ndim, result_ndim)
+ else:
+ return _block_concatenate(arrays, list_ndim, result_ndim)
+
+
+# These helper functions are mostly used for testing.
+# They allow us to write tests that directly call `_block_slicing`
+# or `_block_concatenate` without blocking large arrays to force the wisdom
+# to trigger the desired path.
+def _block_setup(arrays):
+ """
+ Returns
+ (`arrays`, list_ndim, result_ndim, final_size)
+ """
+ bottom_index, arr_ndim, final_size = _block_check_depths_match(arrays)
+ list_ndim = len(bottom_index)
+ if bottom_index and bottom_index[-1] is None:
+ raise ValueError(
+ f'List at {_block_format_index(bottom_index)} cannot be empty'
+ )
+ result_ndim = max(arr_ndim, list_ndim)
+ return arrays, list_ndim, result_ndim, final_size
+
+
+def _block_slicing(arrays, list_ndim, result_ndim):
+ shape, slices, arrays = _block_info_recursion(
+ arrays, list_ndim, result_ndim)
+ dtype = _nx.result_type(*[arr.dtype for arr in arrays])
+
+ # Test preferring F only in the case that all input arrays are F
+ F_order = all(arr.flags['F_CONTIGUOUS'] for arr in arrays)
+ C_order = all(arr.flags['C_CONTIGUOUS'] for arr in arrays)
+ order = 'F' if F_order and not C_order else 'C'
+ result = _nx.empty(shape=shape, dtype=dtype, order=order)
+ # Note: In a c implementation, the function
+ # PyArray_CreateMultiSortedStridePerm could be used for more advanced
+ # guessing of the desired order.
+
+ for the_slice, arr in zip(slices, arrays):
+ result[(Ellipsis,) + the_slice] = arr
+ return result
+
+
+def _block_concatenate(arrays, list_ndim, result_ndim):
+ result = _block(arrays, list_ndim, result_ndim)
+ if list_ndim == 0:
+ # Catch an edge case where _block returns a view because
+ # `arrays` is a single numpy array and not a list of numpy arrays.
+ # This might copy scalars or lists twice, but this isn't a likely
+ # usecase for those interested in performance
+ result = result.copy()
+ return result
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/shape_base.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/shape_base.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..b87cae8a5f0fdd479f4ef978f1fa251c5a152bb0
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/shape_base.pyi
@@ -0,0 +1,182 @@
+from collections.abc import Sequence
+from typing import Any, SupportsIndex, TypeVar, overload
+
+from numpy import _CastingKind, generic
+from numpy._typing import ArrayLike, DTypeLike, NDArray, _ArrayLike, _DTypeLike
+
+__all__ = [
+ "atleast_1d",
+ "atleast_2d",
+ "atleast_3d",
+ "block",
+ "hstack",
+ "stack",
+ "unstack",
+ "vstack",
+]
+
+_T = TypeVar("_T")
+_ScalarT = TypeVar("_ScalarT", bound=generic)
+_ScalarT1 = TypeVar("_ScalarT1", bound=generic)
+_ScalarT2 = TypeVar("_ScalarT2", bound=generic)
+_ArrayT = TypeVar("_ArrayT", bound=NDArray[Any])
+
+###
+
+# keep in sync with `numpy.ma.extras.atleast_1d`
+@overload
+def atleast_1d(a0: _ArrayLike[_ScalarT], /) -> NDArray[_ScalarT]: ...
+@overload
+def atleast_1d(a0: _ArrayLike[_ScalarT1], a1: _ArrayLike[_ScalarT2], /) -> tuple[NDArray[_ScalarT1], NDArray[_ScalarT2]]: ...
+@overload
+def atleast_1d(a0: _ArrayLike[_ScalarT], a1: _ArrayLike[_ScalarT], /, *arys: _ArrayLike[_ScalarT]) -> tuple[NDArray[_ScalarT], ...]: ...
+@overload
+def atleast_1d(a0: ArrayLike, /) -> NDArray[Any]: ...
+@overload
+def atleast_1d(a0: ArrayLike, a1: ArrayLike, /) -> tuple[NDArray[Any], NDArray[Any]]: ...
+@overload
+def atleast_1d(a0: ArrayLike, a1: ArrayLike, /, *ai: ArrayLike) -> tuple[NDArray[Any], ...]: ...
+
+# keep in sync with `numpy.ma.extras.atleast_2d`
+@overload
+def atleast_2d(a0: _ArrayLike[_ScalarT], /) -> NDArray[_ScalarT]: ...
+@overload
+def atleast_2d(a0: _ArrayLike[_ScalarT1], a1: _ArrayLike[_ScalarT2], /) -> tuple[NDArray[_ScalarT1], NDArray[_ScalarT2]]: ...
+@overload
+def atleast_2d(a0: _ArrayLike[_ScalarT], a1: _ArrayLike[_ScalarT], /, *arys: _ArrayLike[_ScalarT]) -> tuple[NDArray[_ScalarT], ...]: ...
+@overload
+def atleast_2d(a0: ArrayLike, /) -> NDArray[Any]: ...
+@overload
+def atleast_2d(a0: ArrayLike, a1: ArrayLike, /) -> tuple[NDArray[Any], NDArray[Any]]: ...
+@overload
+def atleast_2d(a0: ArrayLike, a1: ArrayLike, /, *ai: ArrayLike) -> tuple[NDArray[Any], ...]: ...
+
+# keep in sync with `numpy.ma.extras.atleast_3d`
+@overload
+def atleast_3d(a0: _ArrayLike[_ScalarT], /) -> NDArray[_ScalarT]: ...
+@overload
+def atleast_3d(a0: _ArrayLike[_ScalarT1], a1: _ArrayLike[_ScalarT2], /) -> tuple[NDArray[_ScalarT1], NDArray[_ScalarT2]]: ...
+@overload
+def atleast_3d(a0: _ArrayLike[_ScalarT], a1: _ArrayLike[_ScalarT], /, *arys: _ArrayLike[_ScalarT]) -> tuple[NDArray[_ScalarT], ...]: ...
+@overload
+def atleast_3d(a0: ArrayLike, /) -> NDArray[Any]: ...
+@overload
+def atleast_3d(a0: ArrayLike, a1: ArrayLike, /) -> tuple[NDArray[Any], NDArray[Any]]: ...
+@overload
+def atleast_3d(a0: ArrayLike, a1: ArrayLike, /, *ai: ArrayLike) -> tuple[NDArray[Any], ...]: ...
+
+# used by numpy.lib._shape_base_impl
+def _arrays_for_stack_dispatcher(arrays: Sequence[_T]) -> tuple[_T, ...]: ...
+
+# keep in sync with `numpy.ma.extras.vstack`
+@overload
+def vstack(
+ tup: Sequence[_ArrayLike[_ScalarT]],
+ *,
+ dtype: None = None,
+ casting: _CastingKind = "same_kind"
+) -> NDArray[_ScalarT]: ...
+@overload
+def vstack(
+ tup: Sequence[ArrayLike],
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ casting: _CastingKind = "same_kind"
+) -> NDArray[_ScalarT]: ...
+@overload
+def vstack(
+ tup: Sequence[ArrayLike],
+ *,
+ dtype: DTypeLike | None = None,
+ casting: _CastingKind = "same_kind"
+) -> NDArray[Any]: ...
+
+# keep in sync with `numpy.ma.extras.hstack`
+@overload
+def hstack(
+ tup: Sequence[_ArrayLike[_ScalarT]],
+ *,
+ dtype: None = None,
+ casting: _CastingKind = "same_kind"
+) -> NDArray[_ScalarT]: ...
+@overload
+def hstack(
+ tup: Sequence[ArrayLike],
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ casting: _CastingKind = "same_kind"
+) -> NDArray[_ScalarT]: ...
+@overload
+def hstack(
+ tup: Sequence[ArrayLike],
+ *,
+ dtype: DTypeLike | None = None,
+ casting: _CastingKind = "same_kind"
+) -> NDArray[Any]: ...
+
+# keep in sync with `numpy.ma.extras.stack`
+@overload
+def stack(
+ arrays: Sequence[_ArrayLike[_ScalarT]],
+ axis: SupportsIndex = 0,
+ out: None = None,
+ *,
+ dtype: None = None,
+ casting: _CastingKind = "same_kind"
+) -> NDArray[_ScalarT]: ...
+@overload
+def stack(
+ arrays: Sequence[ArrayLike],
+ axis: SupportsIndex = 0,
+ out: None = None,
+ *,
+ dtype: _DTypeLike[_ScalarT],
+ casting: _CastingKind = "same_kind"
+) -> NDArray[_ScalarT]: ...
+@overload
+def stack(
+ arrays: Sequence[ArrayLike],
+ axis: SupportsIndex = 0,
+ out: None = None,
+ *,
+ dtype: DTypeLike | None = None,
+ casting: _CastingKind = "same_kind"
+) -> NDArray[Any]: ...
+@overload
+def stack(
+ arrays: Sequence[ArrayLike],
+ axis: SupportsIndex,
+ out: _ArrayT,
+ *,
+ dtype: DTypeLike | None = None,
+ casting: _CastingKind = "same_kind",
+) -> _ArrayT: ...
+@overload
+def stack(
+ arrays: Sequence[ArrayLike],
+ axis: SupportsIndex = 0,
+ *,
+ out: _ArrayT,
+ dtype: DTypeLike | None = None,
+ casting: _CastingKind = "same_kind",
+) -> _ArrayT: ...
+
+@overload
+def unstack(
+ array: _ArrayLike[_ScalarT],
+ /,
+ *,
+ axis: int = 0,
+) -> tuple[NDArray[_ScalarT], ...]: ...
+@overload
+def unstack(
+ array: ArrayLike,
+ /,
+ *,
+ axis: int = 0,
+) -> tuple[NDArray[Any], ...]: ...
+
+@overload
+def block(arrays: _ArrayLike[_ScalarT]) -> NDArray[_ScalarT]: ...
+@overload
+def block(arrays: ArrayLike) -> NDArray[Any]: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/strings.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/strings.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9fa7f58e3ea5c50182038e0644e96f5c73f9c63
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/strings.py
@@ -0,0 +1,1813 @@
+"""
+This module contains a set of functions for vectorized string
+operations.
+"""
+
+import functools
+import sys
+
+import numpy as np
+from numpy import (
+ add,
+ equal,
+ greater,
+ greater_equal,
+ less,
+ less_equal,
+ multiply as _multiply_ufunc,
+ not_equal,
+)
+from numpy._core.multiarray import _vec_string
+from numpy._core.overrides import array_function_dispatch, set_module
+from numpy._core.umath import (
+ _center,
+ _expandtabs,
+ _expandtabs_length,
+ _ljust,
+ _lstrip_chars,
+ _lstrip_whitespace,
+ _partition,
+ _partition_index,
+ _replace,
+ _rjust,
+ _rpartition,
+ _rpartition_index,
+ _rstrip_chars,
+ _rstrip_whitespace,
+ _slice,
+ _strip_chars,
+ _strip_whitespace,
+ _zfill,
+ count as _count_ufunc,
+ endswith as _endswith_ufunc,
+ find as _find_ufunc,
+ index as _index_ufunc,
+ isalnum,
+ isalpha,
+ isdecimal,
+ isdigit,
+ islower,
+ isnumeric,
+ isspace,
+ istitle,
+ isupper,
+ rfind as _rfind_ufunc,
+ rindex as _rindex_ufunc,
+ startswith as _startswith_ufunc,
+ str_len,
+)
+
+
+def _override___module__():
+ for ufunc in [
+ isalnum, isalpha, isdecimal, isdigit, islower, isnumeric, isspace,
+ istitle, isupper, str_len,
+ ]:
+ ufunc.__module__ = "numpy.strings"
+ ufunc.__qualname__ = ufunc.__name__
+
+
+_override___module__()
+
+
+__all__ = [
+ # UFuncs
+ "equal", "not_equal", "less", "less_equal", "greater", "greater_equal",
+ "add", "multiply", "isalpha", "isdigit", "isspace", "isalnum", "islower",
+ "isupper", "istitle", "isdecimal", "isnumeric", "str_len", "find",
+ "rfind", "index", "rindex", "count", "startswith", "endswith", "lstrip",
+ "rstrip", "strip", "replace", "expandtabs", "center", "ljust", "rjust",
+ "zfill", "partition", "rpartition", "slice",
+
+ # _vec_string - Will gradually become ufuncs as well
+ "upper", "lower", "swapcase", "capitalize", "title",
+
+ # _vec_string - Will probably not become ufuncs
+ "mod", "decode", "encode", "translate",
+
+ # Removed from namespace until behavior has been crystallized
+ # "join", "split", "rsplit", "splitlines",
+]
+
+
+MAX = np.iinfo(np.int64).max
+
+array_function_dispatch = functools.partial(
+ array_function_dispatch, module='numpy.strings')
+
+
+def _get_num_chars(a):
+ """
+ Helper function that returns the number of characters per field in
+ a string or unicode array. This is to abstract out the fact that
+ for a unicode array this is itemsize / 4.
+ """
+ if issubclass(a.dtype.type, np.str_):
+ return a.itemsize // 4
+ return a.itemsize
+
+
+def _to_bytes_or_str_array(result, output_dtype_like):
+ """
+ Helper function to cast a result back into an array
+ with the appropriate dtype if an object array must be used
+ as an intermediary.
+ """
+ output_dtype_like = np.asarray(output_dtype_like)
+ if result.size == 0:
+ # Calling asarray & tolist in an empty array would result
+ # in losing shape information
+ return result.astype(output_dtype_like.dtype)
+ ret = np.asarray(result.tolist())
+ if isinstance(output_dtype_like.dtype, np.dtypes.StringDType):
+ return ret.astype(type(output_dtype_like.dtype))
+ return ret.astype(type(output_dtype_like.dtype)(_get_num_chars(ret)))
+
+
+def _clean_args(*args):
+ """
+ Helper function for delegating arguments to Python string
+ functions.
+
+ Many of the Python string operations that have optional arguments
+ do not use 'None' to indicate a default value. In these cases,
+ we need to remove all None arguments, and those following them.
+ """
+ newargs = []
+ for chk in args:
+ if chk is None:
+ break
+ newargs.append(chk)
+ return newargs
+
+
+def _multiply_dispatcher(a, i):
+ return (a,)
+
+
+@set_module("numpy.strings")
+@array_function_dispatch(_multiply_dispatcher)
+def multiply(a, i):
+ """
+ Return (a * i), that is string multiple concatenation,
+ element-wise.
+
+ Values in ``i`` of less than 0 are treated as 0 (which yields an
+ empty string).
+
+ Parameters
+ ----------
+ a : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
+
+ i : array_like, with any integer dtype
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
+ depending on input types
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["a", "b", "c"])
+ >>> np.strings.multiply(a, 3)
+ array(['aaa', 'bbb', 'ccc'], dtype='>> i = np.array([1, 2, 3])
+ >>> np.strings.multiply(a, i)
+ array(['a', 'bb', 'ccc'], dtype='>> np.strings.multiply(np.array(['a']), i)
+ array(['a', 'aa', 'aaa'], dtype='>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3))
+ >>> np.strings.multiply(a, 3)
+ array([['aaa', 'bbb', 'ccc'],
+ ['ddd', 'eee', 'fff']], dtype='>> np.strings.multiply(a, i)
+ array([['a', 'bb', 'ccc'],
+ ['d', 'ee', 'fff']], dtype=' sys.maxsize / np.maximum(i, 1)):
+ raise OverflowError("Overflow encountered in string multiply")
+
+ buffersizes = a_len * i
+ out_dtype = f"{a.dtype.char}{buffersizes.max()}"
+ out = np.empty_like(a, shape=buffersizes.shape, dtype=out_dtype)
+ return _multiply_ufunc(a, i, out=out)
+
+
+def _mod_dispatcher(a, values):
+ return (a, values)
+
+
+@set_module("numpy.strings")
+@array_function_dispatch(_mod_dispatcher)
+def mod(a, values):
+ """
+ Return (a % i), that is pre-Python 2.6 string formatting
+ (interpolation), element-wise for a pair of array_likes of str
+ or unicode.
+
+ Parameters
+ ----------
+ a : array_like, with `np.bytes_` or `np.str_` dtype
+
+ values : array_like of values
+ These values will be element-wise interpolated into the string.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
+ depending on input types
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["NumPy is a %s library"])
+ >>> np.strings.mod(a, values=["Python"])
+ array(['NumPy is a Python library'], dtype='>> a = np.array([b'%d bytes', b'%d bits'])
+ >>> values = np.array([8, 64])
+ >>> np.strings.mod(a, values)
+ array([b'8 bytes', b'64 bits'], dtype='|S7')
+
+ """
+ return _to_bytes_or_str_array(
+ _vec_string(a, np.object_, '__mod__', (values,)), a)
+
+
+@set_module("numpy.strings")
+def find(a, sub, start=0, end=None):
+ """
+ For each element, return the lowest index in the string where
+ substring ``sub`` is found, such that ``sub`` is contained in the
+ range [``start``, ``end``).
+
+ Parameters
+ ----------
+ a : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
+
+ sub : array_like, with `np.bytes_` or `np.str_` dtype
+ The substring to search for.
+
+ start, end : array_like, with any integer dtype
+ The range to look in, interpreted as in slice notation.
+
+ Returns
+ -------
+ y : ndarray
+ Output array of ints
+
+ See Also
+ --------
+ str.find
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["NumPy is a Python library"])
+ >>> np.strings.find(a, "Python")
+ array([11])
+
+ """
+ end = end if end is not None else MAX
+ return _find_ufunc(a, sub, start, end)
+
+
+@set_module("numpy.strings")
+def rfind(a, sub, start=0, end=None):
+ """
+ For each element, return the highest index in the string where
+ substring ``sub`` is found, such that ``sub`` is contained in the
+ range [``start``, ``end``).
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+ The substring to search for.
+
+ start, end : array_like, with any integer dtype
+ The range to look in, interpreted as in slice notation.
+
+ Returns
+ -------
+ y : ndarray
+ Output array of ints
+
+ See Also
+ --------
+ str.rfind
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["Computer Science"])
+ >>> np.strings.rfind(a, "Science", start=0, end=None)
+ array([9])
+ >>> np.strings.rfind(a, "Science", start=0, end=8)
+ array([-1])
+ >>> b = np.array(["Computer Science", "Science"])
+ >>> np.strings.rfind(b, "Science", start=0, end=None)
+ array([9, 0])
+
+ """
+ end = end if end is not None else MAX
+ return _rfind_ufunc(a, sub, start, end)
+
+
+@set_module("numpy.strings")
+def index(a, sub, start=0, end=None):
+ """
+ Like `find`, but raises :exc:`ValueError` when the substring is not found.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ start, end : array_like, with any integer dtype, optional
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ints.
+
+ See Also
+ --------
+ find, str.index
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["Computer Science"])
+ >>> np.strings.index(a, "Science", start=0, end=None)
+ array([9])
+
+ """
+ end = end if end is not None else MAX
+ return _index_ufunc(a, sub, start, end)
+
+
+@set_module("numpy.strings")
+def rindex(a, sub, start=0, end=None):
+ """
+ Like `rfind`, but raises :exc:`ValueError` when the substring `sub` is
+ not found.
+
+ Parameters
+ ----------
+ a : array-like, with `np.bytes_` or `np.str_` dtype
+
+ sub : array-like, with `np.bytes_` or `np.str_` dtype
+
+ start, end : array-like, with any integer dtype, optional
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ints.
+
+ See Also
+ --------
+ rfind, str.rindex
+
+ Examples
+ --------
+ >>> a = np.array(["Computer Science"])
+ >>> np.strings.rindex(a, "Science", start=0, end=None)
+ array([9])
+
+ """
+ end = end if end is not None else MAX
+ return _rindex_ufunc(a, sub, start, end)
+
+
+@set_module("numpy.strings")
+def count(a, sub, start=0, end=None):
+ """
+ Returns an array with the number of non-overlapping occurrences of
+ substring ``sub`` in the range [``start``, ``end``).
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+ The substring to search for.
+
+ start, end : array_like, with any integer dtype
+ The range to look in, interpreted as in slice notation.
+
+ Returns
+ -------
+ y : ndarray
+ Output array of ints
+
+ See Also
+ --------
+ str.count
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
+ >>> c
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> np.strings.count(c, 'A')
+ array([3, 1, 1])
+ >>> np.strings.count(c, 'aA')
+ array([3, 1, 0])
+ >>> np.strings.count(c, 'A', start=1, end=4)
+ array([2, 1, 1])
+ >>> np.strings.count(c, 'A', start=1, end=3)
+ array([1, 0, 0])
+
+ """
+ end = end if end is not None else MAX
+ return _count_ufunc(a, sub, start, end)
+
+
+@set_module("numpy.strings")
+def startswith(a, prefix, start=0, end=None):
+ """
+ Returns a boolean array which is `True` where the string element
+ in ``a`` starts with ``prefix``, otherwise `False`.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ prefix : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ start, end : array_like, with any integer dtype
+ With ``start``, test beginning at that position. With ``end``,
+ stop comparing at that position.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools
+
+ See Also
+ --------
+ str.startswith
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> s = np.array(['foo', 'bar'])
+ >>> s
+ array(['foo', 'bar'], dtype='>> np.strings.startswith(s, 'fo')
+ array([True, False])
+ >>> np.strings.startswith(s, 'o', start=1, end=2)
+ array([True, False])
+
+ """
+ end = end if end is not None else MAX
+ return _startswith_ufunc(a, prefix, start, end)
+
+
+@set_module("numpy.strings")
+def endswith(a, suffix, start=0, end=None):
+ """
+ Returns a boolean array which is `True` where the string element
+ in ``a`` ends with ``suffix``, otherwise `False`.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ suffix : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ start, end : array_like, with any integer dtype
+ With ``start``, test beginning at that position. With ``end``,
+ stop comparing at that position.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of bools
+
+ See Also
+ --------
+ str.endswith
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> s = np.array(['foo', 'bar'])
+ >>> s
+ array(['foo', 'bar'], dtype='>> np.strings.endswith(s, 'ar')
+ array([False, True])
+ >>> np.strings.endswith(s, 'a', start=1, end=2)
+ array([False, True])
+
+ """
+ end = end if end is not None else MAX
+ return _endswith_ufunc(a, suffix, start, end)
+
+
+def _code_dispatcher(a, encoding=None, errors=None):
+ return (a,)
+
+
+@set_module("numpy.strings")
+@array_function_dispatch(_code_dispatcher)
+def decode(a, encoding=None, errors=None):
+ r"""
+ Calls :meth:`bytes.decode` element-wise.
+
+ The set of available codecs comes from the Python standard library,
+ and may be extended at runtime. For more information, see the
+ :mod:`codecs` module.
+
+ Parameters
+ ----------
+ a : array_like, with ``bytes_`` dtype
+
+ encoding : str, optional
+ The name of an encoding
+
+ errors : str, optional
+ Specifies how to handle encoding errors
+
+ Returns
+ -------
+ out : ndarray
+
+ See Also
+ --------
+ :py:meth:`bytes.decode`
+
+ Notes
+ -----
+ The type of the result will depend on the encoding specified.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> c = np.array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
+ ... b'\x81\x82\xc2\xc1\xc2\x82\x81'])
+ >>> c
+ array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
+ b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7')
+ >>> np.strings.decode(c, encoding='cp037')
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> import numpy as np
+ >>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
+ >>> np.strings.encode(a, encoding='cp037')
+ array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
+ b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7')
+
+ """
+ return _to_bytes_or_str_array(
+ _vec_string(a, np.object_, 'encode', _clean_args(encoding, errors)),
+ np.bytes_(b''))
+
+
+def _expandtabs_dispatcher(a, tabsize=None):
+ return (a,)
+
+
+@set_module("numpy.strings")
+@array_function_dispatch(_expandtabs_dispatcher)
+def expandtabs(a, tabsize=8):
+ """
+ Return a copy of each string element where all tab characters are
+ replaced by one or more spaces.
+
+ Calls :meth:`str.expandtabs` element-wise.
+
+ Return a copy of each string element where all tab characters are
+ replaced by one or more spaces, depending on the current column
+ and the given `tabsize`. The column number is reset to zero after
+ each newline occurring in the string. This doesn't understand other
+ non-printing characters or escape sequences.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+ Input array
+ tabsize : int, optional
+ Replace tabs with `tabsize` number of spaces. If not given defaults
+ to 8 spaces.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
+ depending on input type
+
+ See Also
+ --------
+ str.expandtabs
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(['\t\tHello\tworld'])
+ >>> np.strings.expandtabs(a, tabsize=4) # doctest: +SKIP
+ array([' Hello world'], dtype='>> import numpy as np
+ >>> c = np.array(['a1b2','1b2a','b2a1','2a1b']); c
+ array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='>> np.strings.center(c, width=9)
+ array([' a1b2 ', ' 1b2a ', ' b2a1 ', ' 2a1b '], dtype='>> np.strings.center(c, width=9, fillchar='*')
+ array(['***a1b2**', '***1b2a**', '***b2a1**', '***2a1b**'], dtype='>> np.strings.center(c, width=1)
+ array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='>> import numpy as np
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
+ >>> np.strings.ljust(c, width=3)
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> np.strings.ljust(c, width=9)
+ array(['aAaAaA ', ' aA ', 'abBABba '], dtype='>> import numpy as np
+ >>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
+ >>> np.strings.rjust(a, width=3)
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> np.strings.rjust(a, width=9)
+ array([' aAaAaA', ' aA ', ' abBABba'], dtype='>> import numpy as np
+ >>> np.strings.zfill(['1', '-1', '+1'], 3)
+ array(['001', '-01', '+01'], dtype='>> import numpy as np
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
+ >>> c
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> np.strings.lstrip(c, 'a')
+ array(['AaAaA', ' aA ', 'bBABba'], dtype='>> np.strings.lstrip(c, 'A') # leaves c unchanged
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> (np.strings.lstrip(c, ' ') == np.strings.lstrip(c, '')).all()
+ np.False_
+ >>> (np.strings.lstrip(c, ' ') == np.strings.lstrip(c)).all()
+ np.True_
+
+ """
+ if chars is None:
+ return _lstrip_whitespace(a)
+ return _lstrip_chars(a, chars)
+
+
+@set_module("numpy.strings")
+def rstrip(a, chars=None):
+ """
+ For each element in `a`, return a copy with the trailing characters
+ removed.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+ chars : scalar with the same dtype as ``a``, optional
+ The ``chars`` argument is a string specifying the set of
+ characters to be removed. If ``None``, the ``chars``
+ argument defaults to removing whitespace. The ``chars`` argument
+ is not a prefix or suffix; rather, all combinations of its
+ values are stripped.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
+ depending on input types
+
+ See Also
+ --------
+ str.rstrip
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> c = np.array(['aAaAaA', 'abBABba'])
+ >>> c
+ array(['aAaAaA', 'abBABba'], dtype='>> np.strings.rstrip(c, 'a')
+ array(['aAaAaA', 'abBABb'], dtype='>> np.strings.rstrip(c, 'A')
+ array(['aAaAa', 'abBABba'], dtype='>> import numpy as np
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
+ >>> c
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> np.strings.strip(c)
+ array(['aAaAaA', 'aA', 'abBABba'], dtype='>> np.strings.strip(c, 'a')
+ array(['AaAaA', ' aA ', 'bBABb'], dtype='>> np.strings.strip(c, 'A')
+ array(['aAaAa', ' aA ', 'abBABba'], dtype='>> import numpy as np
+ >>> c = np.array(['a1b c', '1bca', 'bca1']); c
+ array(['a1b c', '1bca', 'bca1'], dtype='>> np.strings.upper(c)
+ array(['A1B C', '1BCA', 'BCA1'], dtype='>> import numpy as np
+ >>> c = np.array(['A1B C', '1BCA', 'BCA1']); c
+ array(['A1B C', '1BCA', 'BCA1'], dtype='>> np.strings.lower(c)
+ array(['a1b c', '1bca', 'bca1'], dtype='>> import numpy as np
+ >>> c=np.array(['a1B c','1b Ca','b Ca1','cA1b'],'S5'); c
+ array(['a1B c', '1b Ca', 'b Ca1', 'cA1b'],
+ dtype='|S5')
+ >>> np.strings.swapcase(c)
+ array(['A1b C', '1B cA', 'B cA1', 'Ca1B'],
+ dtype='|S5')
+
+ """
+ a_arr = np.asarray(a)
+ return _vec_string(a_arr, a_arr.dtype, 'swapcase')
+
+
+@set_module("numpy.strings")
+@array_function_dispatch(_unary_op_dispatcher)
+def capitalize(a):
+ """
+ Return a copy of ``a`` with only the first character of each element
+ capitalized.
+
+ Calls :meth:`str.capitalize` element-wise.
+
+ For byte strings, this method is locale-dependent.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+ Input array of strings to capitalize.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
+ depending on input types
+
+ See Also
+ --------
+ str.capitalize
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> c = np.array(['a1b2','1b2a','b2a1','2a1b'],'S4'); c
+ array(['a1b2', '1b2a', 'b2a1', '2a1b'],
+ dtype='|S4')
+ >>> np.strings.capitalize(c)
+ array(['A1b2', '1b2a', 'B2a1', '2a1b'],
+ dtype='|S4')
+
+ """
+ a_arr = np.asarray(a)
+ return _vec_string(a_arr, a_arr.dtype, 'capitalize')
+
+
+@set_module("numpy.strings")
+@array_function_dispatch(_unary_op_dispatcher)
+def title(a):
+ """
+ Return element-wise title cased version of string or unicode.
+
+ Title case words start with uppercase characters, all remaining cased
+ characters are lowercase.
+
+ Calls :meth:`str.title` element-wise.
+
+ For 8-bit strings, this method is locale-dependent.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+ Input array.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
+ depending on input types
+
+ See Also
+ --------
+ str.title
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c
+ array(['a1b c', '1b ca', 'b ca1', 'ca1b'],
+ dtype='|S5')
+ >>> np.strings.title(c)
+ array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'],
+ dtype='|S5')
+
+ """
+ a_arr = np.asarray(a)
+ return _vec_string(a_arr, a_arr.dtype, 'title')
+
+
+def _replace_dispatcher(a, old, new, count=None):
+ return (a,)
+
+
+@set_module("numpy.strings")
+@array_function_dispatch(_replace_dispatcher)
+def replace(a, old, new, count=-1):
+ """
+ For each element in ``a``, return a copy of the string with
+ occurrences of substring ``old`` replaced by ``new``.
+
+ Parameters
+ ----------
+ a : array_like, with ``bytes_`` or ``str_`` dtype
+
+ old, new : array_like, with ``bytes_`` or ``str_`` dtype
+
+ count : array_like, with ``int_`` dtype
+ If the optional argument ``count`` is given, only the first
+ ``count`` occurrences are replaced.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
+ depending on input types
+
+ See Also
+ --------
+ str.replace
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(["That is a mango", "Monkeys eat mangos"])
+ >>> np.strings.replace(a, 'mango', 'banana')
+ array(['That is a banana', 'Monkeys eat bananas'], dtype='>> a = np.array(["The dish is fresh", "This is it"])
+ >>> np.strings.replace(a, 'is', 'was')
+ array(['The dwash was fresh', 'Thwas was it'], dtype='>> import numpy as np
+ >>> np.strings.join('-', 'osd') # doctest: +SKIP
+ array('o-s-d', dtype='>> np.strings.join(['-', '.'], ['ghc', 'osd']) # doctest: +SKIP
+ array(['g-h-c', 'o.s.d'], dtype='>> import numpy as np
+ >>> x = np.array("Numpy is nice!")
+ >>> np.strings.split(x, " ") # doctest: +SKIP
+ array(list(['Numpy', 'is', 'nice!']), dtype=object) # doctest: +SKIP
+
+ >>> np.strings.split(x, " ", 1) # doctest: +SKIP
+ array(list(['Numpy', 'is nice!']), dtype=object) # doctest: +SKIP
+
+ See Also
+ --------
+ str.split, rsplit
+
+ """
+ # This will return an array of lists of different sizes, so we
+ # leave it as an object array
+ return _vec_string(
+ a, np.object_, 'split', [sep] + _clean_args(maxsplit))
+
+
+@array_function_dispatch(_split_dispatcher)
+def _rsplit(a, sep=None, maxsplit=None):
+ """
+ For each element in `a`, return a list of the words in the
+ string, using `sep` as the delimiter string.
+
+ Calls :meth:`str.rsplit` element-wise.
+
+ Except for splitting from the right, `rsplit`
+ behaves like `split`.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ sep : str or unicode, optional
+ If `sep` is not specified or None, any whitespace string
+ is a separator.
+ maxsplit : int, optional
+ If `maxsplit` is given, at most `maxsplit` splits are done,
+ the rightmost ones.
+
+ Returns
+ -------
+ out : ndarray
+ Array of list objects
+
+ See Also
+ --------
+ str.rsplit, split
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(['aAaAaA', 'abBABba'])
+ >>> np.strings.rsplit(a, 'A') # doctest: +SKIP
+ array([list(['a', 'a', 'a', '']), # doctest: +SKIP
+ list(['abB', 'Bba'])], dtype=object) # doctest: +SKIP
+
+ """
+ # This will return an array of lists of different sizes, so we
+ # leave it as an object array
+ return _vec_string(
+ a, np.object_, 'rsplit', [sep] + _clean_args(maxsplit))
+
+
+def _splitlines_dispatcher(a, keepends=None):
+ return (a,)
+
+
+@array_function_dispatch(_splitlines_dispatcher)
+def _splitlines(a, keepends=None):
+ """
+ For each element in `a`, return a list of the lines in the
+ element, breaking at line boundaries.
+
+ Calls :meth:`str.splitlines` element-wise.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+
+ keepends : bool, optional
+ Line breaks are not included in the resulting list unless
+ keepends is given and true.
+
+ Returns
+ -------
+ out : ndarray
+ Array of list objects
+
+ See Also
+ --------
+ str.splitlines
+
+ Examples
+ --------
+ >>> np.char.splitlines("first line\\nsecond line")
+ array(list(['first line', 'second line']), dtype=object)
+ >>> a = np.array(["first\\nsecond", "third\\nfourth"])
+ >>> np.char.splitlines(a)
+ array([list(['first', 'second']), list(['third', 'fourth'])], dtype=object)
+
+ """
+ return _vec_string(
+ a, np.object_, 'splitlines', _clean_args(keepends))
+
+
+def _partition_dispatcher(a, sep):
+ return (a,)
+
+
+@set_module("numpy.strings")
+@array_function_dispatch(_partition_dispatcher)
+def partition(a, sep):
+ """
+ Partition each element in ``a`` around ``sep``.
+
+ For each element in ``a``, split the element at the first
+ occurrence of ``sep``, and return a 3-tuple containing the part
+ before the separator, the separator itself, and the part after
+ the separator. If the separator is not found, the first item of
+ the tuple will contain the whole string, and the second and third
+ ones will be the empty string.
+
+ Parameters
+ ----------
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+ Input array
+ sep : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
+ Separator to split each string element in ``a``.
+
+ Returns
+ -------
+ out : 3-tuple:
+ - array with ``StringDType``, ``bytes_`` or ``str_`` dtype with the
+ part before the separator
+ - array with ``StringDType``, ``bytes_`` or ``str_`` dtype with the
+ separator
+ - array with ``StringDType``, ``bytes_`` or ``str_`` dtype with the
+ part after the separator
+
+ See Also
+ --------
+ str.partition
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> x = np.array(["Numpy is nice!"])
+ >>> np.strings.partition(x, " ")
+ (array(['Numpy'], dtype='>> import numpy as np
+ >>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
+ >>> np.strings.rpartition(a, 'A')
+ (array(['aAaAa', ' a', 'abB'], dtype='>> import numpy as np
+ >>> a = np.array(['a1b c', '1bca', 'bca1'])
+ >>> table = a[0].maketrans('abc', '123')
+ >>> deletechars = ' '
+ >>> np.char.translate(a, table, deletechars)
+ array(['112 3', '1231', '2311'], dtype='>> import numpy as np
+ >>> a = np.array(['hello', 'world'])
+ >>> np.strings.slice(a, 2)
+ array(['he', 'wo'], dtype='>> np.strings.slice(a, 2, None)
+ array(['llo', 'rld'], dtype='>> np.strings.slice(a, 1, 5, 2)
+ array(['el', 'ol'], dtype='>> np.strings.slice(a, np.array([1, 2]), np.array([4, 5]))
+ array(['ell', 'rld'], dtype='>> b = np.array(['hello world', 'γεια σου κόσμε', '你好世界', '👋 🌍'],
+ ... dtype=np.dtypes.StringDType())
+ >>> np.strings.slice(b, -2)
+ array(['hello wor', 'γεια σου κόσ', '你好', '👋'], dtype=StringDType())
+
+ >>> np.strings.slice(b, -2, None)
+ array(['ld', 'με', '世界', ' 🌍'], dtype=StringDType())
+
+ >>> np.strings.slice(b, [3, -10, 2, -3], [-1, -2, -1, 3])
+ array(['lo worl', ' σου κόσ', '世', '👋 🌍'], dtype=StringDType())
+
+ >>> np.strings.slice(b, None, None, -1)
+ array(['dlrow olleh', 'εμσόκ υοσ αιεγ', '界世好你', '🌍 👋'],
+ dtype=StringDType())
+
+ """
+ # Just like in the construction of a regular slice object, if only start
+ # is specified then start will become stop, see logic in slice_new.
+ if stop is np._NoValue:
+ stop = start
+ start = None
+
+ # adjust start, stop, step to be integers, see logic in PySlice_Unpack
+ if step is None:
+ step = 1
+ step = np.asanyarray(step)
+ if not np.issubdtype(step.dtype, np.integer):
+ raise TypeError(f"unsupported type {step.dtype} for operand 'step'")
+ if np.any(step == 0):
+ raise ValueError("slice step cannot be zero")
+
+ if start is None:
+ start = np.where(step < 0, np.iinfo(np.intp).max, 0)
+
+ if stop is None:
+ stop = np.where(step < 0, np.iinfo(np.intp).min, np.iinfo(np.intp).max)
+
+ return _slice(a, start, stop, step)
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/strings.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/strings.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..270760412670a2a96c1a959f2ddcbb0675764be0
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/strings.pyi
@@ -0,0 +1,536 @@
+from typing import TypeAlias, overload
+
+import numpy as np
+from numpy._globals import _NoValueType
+from numpy._typing import (
+ NDArray,
+ _AnyShape,
+ _ArrayLikeAnyString_co as UST_co,
+ _ArrayLikeBytes_co as S_co,
+ _ArrayLikeInt_co as i_co,
+ _ArrayLikeStr_co as U_co,
+ _ArrayLikeString_co as T_co,
+ _SupportsArray,
+)
+
+__all__ = [
+ "add",
+ "capitalize",
+ "center",
+ "count",
+ "decode",
+ "encode",
+ "endswith",
+ "equal",
+ "expandtabs",
+ "find",
+ "greater",
+ "greater_equal",
+ "index",
+ "isalnum",
+ "isalpha",
+ "isdecimal",
+ "isdigit",
+ "islower",
+ "isnumeric",
+ "isspace",
+ "istitle",
+ "isupper",
+ "less",
+ "less_equal",
+ "ljust",
+ "lower",
+ "lstrip",
+ "mod",
+ "multiply",
+ "not_equal",
+ "partition",
+ "replace",
+ "rfind",
+ "rindex",
+ "rjust",
+ "rpartition",
+ "rstrip",
+ "startswith",
+ "str_len",
+ "strip",
+ "swapcase",
+ "title",
+ "translate",
+ "upper",
+ "zfill",
+ "slice",
+]
+
+_StringDTypeArray: TypeAlias = np.ndarray[_AnyShape, np.dtypes.StringDType]
+_StringDTypeSupportsArray: TypeAlias = _SupportsArray[np.dtypes.StringDType]
+_StringDTypeOrUnicodeArray: TypeAlias = np.ndarray[_AnyShape, np.dtype[np.str_]] | _StringDTypeArray
+
+@overload
+def equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def not_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def not_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def not_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def greater_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def greater_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def greater_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def less_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def less_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def less_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def greater(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def greater(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def greater(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def less(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
+@overload
+def less(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
+@overload
+def less(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
+
+@overload
+def add(x1: U_co, x2: U_co) -> NDArray[np.str_]: ...
+@overload
+def add(x1: S_co, x2: S_co) -> NDArray[np.bytes_]: ...
+@overload
+def add(x1: _StringDTypeSupportsArray, x2: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def add(x1: T_co, x2: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def multiply(a: U_co, i: i_co) -> NDArray[np.str_]: ...
+@overload
+def multiply(a: S_co, i: i_co) -> NDArray[np.bytes_]: ...
+@overload
+def multiply(a: _StringDTypeSupportsArray, i: i_co) -> _StringDTypeArray: ...
+@overload
+def multiply(a: T_co, i: i_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def mod(a: U_co, value: object) -> NDArray[np.str_]: ...
+@overload
+def mod(a: S_co, value: object) -> NDArray[np.bytes_]: ...
+@overload
+def mod(a: _StringDTypeSupportsArray, value: object) -> _StringDTypeArray: ...
+@overload
+def mod(a: T_co, value: object) -> _StringDTypeOrUnicodeArray: ...
+
+def isalpha(x: UST_co) -> NDArray[np.bool]: ...
+def isalnum(a: UST_co) -> NDArray[np.bool]: ...
+def isdigit(x: UST_co) -> NDArray[np.bool]: ...
+def isspace(x: UST_co) -> NDArray[np.bool]: ...
+def isdecimal(x: U_co | T_co) -> NDArray[np.bool]: ...
+def isnumeric(x: U_co | T_co) -> NDArray[np.bool]: ...
+def islower(a: UST_co) -> NDArray[np.bool]: ...
+def istitle(a: UST_co) -> NDArray[np.bool]: ...
+def isupper(a: UST_co) -> NDArray[np.bool]: ...
+
+def str_len(x: UST_co) -> NDArray[np.int_]: ...
+
+@overload
+def find(
+ a: U_co,
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+@overload
+def find(
+ a: S_co,
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+@overload
+def find(
+ a: T_co,
+ sub: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+
+@overload
+def rfind(
+ a: U_co,
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+@overload
+def rfind(
+ a: S_co,
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+@overload
+def rfind(
+ a: T_co,
+ sub: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+
+@overload
+def index(
+ a: U_co,
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+@overload
+def index(
+ a: S_co,
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+@overload
+def index(
+ a: T_co,
+ sub: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+
+@overload
+def rindex(
+ a: U_co,
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+@overload
+def rindex(
+ a: S_co,
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+@overload
+def rindex(
+ a: T_co,
+ sub: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+
+@overload
+def count(
+ a: U_co,
+ sub: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+@overload
+def count(
+ a: S_co,
+ sub: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+@overload
+def count(
+ a: T_co,
+ sub: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.int_]: ...
+
+@overload
+def startswith(
+ a: U_co,
+ prefix: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.bool]: ...
+@overload
+def startswith(
+ a: S_co,
+ prefix: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.bool]: ...
+@overload
+def startswith(
+ a: T_co,
+ prefix: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.bool]: ...
+
+@overload
+def endswith(
+ a: U_co,
+ suffix: U_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.bool]: ...
+@overload
+def endswith(
+ a: S_co,
+ suffix: S_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.bool]: ...
+@overload
+def endswith(
+ a: T_co,
+ suffix: T_co,
+ start: i_co = 0,
+ end: i_co | None = None,
+) -> NDArray[np.bool]: ...
+
+def decode(
+ a: S_co,
+ encoding: str | None = None,
+ errors: str | None = None,
+) -> NDArray[np.str_]: ...
+def encode(
+ a: U_co | T_co,
+ encoding: str | None = None,
+ errors: str | None = None,
+) -> NDArray[np.bytes_]: ...
+
+@overload
+def expandtabs(a: U_co, tabsize: i_co = 8) -> NDArray[np.str_]: ...
+@overload
+def expandtabs(a: S_co, tabsize: i_co = 8) -> NDArray[np.bytes_]: ...
+@overload
+def expandtabs(a: _StringDTypeSupportsArray, tabsize: i_co = 8) -> _StringDTypeArray: ...
+@overload
+def expandtabs(a: T_co, tabsize: i_co = 8) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def center(a: U_co, width: i_co, fillchar: UST_co = " ") -> NDArray[np.str_]: ...
+@overload
+def center(a: S_co, width: i_co, fillchar: UST_co = " ") -> NDArray[np.bytes_]: ...
+@overload
+def center(a: _StringDTypeSupportsArray, width: i_co, fillchar: UST_co = " ") -> _StringDTypeArray: ...
+@overload
+def center(a: T_co, width: i_co, fillchar: UST_co = " ") -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def ljust(a: U_co, width: i_co, fillchar: UST_co = " ") -> NDArray[np.str_]: ...
+@overload
+def ljust(a: S_co, width: i_co, fillchar: UST_co = " ") -> NDArray[np.bytes_]: ...
+@overload
+def ljust(a: _StringDTypeSupportsArray, width: i_co, fillchar: UST_co = " ") -> _StringDTypeArray: ...
+@overload
+def ljust(a: T_co, width: i_co, fillchar: UST_co = " ") -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def rjust(a: U_co, width: i_co, fillchar: UST_co = " ") -> NDArray[np.str_]: ...
+@overload
+def rjust(a: S_co, width: i_co, fillchar: UST_co = " ") -> NDArray[np.bytes_]: ...
+@overload
+def rjust(a: _StringDTypeSupportsArray, width: i_co, fillchar: UST_co = " ") -> _StringDTypeArray: ...
+@overload
+def rjust(a: T_co, width: i_co, fillchar: UST_co = " ") -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def lstrip(a: U_co, chars: U_co | None = None) -> NDArray[np.str_]: ...
+@overload
+def lstrip(a: S_co, chars: S_co | None = None) -> NDArray[np.bytes_]: ...
+@overload
+def lstrip(a: _StringDTypeSupportsArray, chars: T_co | None = None) -> _StringDTypeArray: ...
+@overload
+def lstrip(a: T_co, chars: T_co | None = None) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def rstrip(a: U_co, chars: U_co | None = None) -> NDArray[np.str_]: ...
+@overload
+def rstrip(a: S_co, chars: S_co | None = None) -> NDArray[np.bytes_]: ...
+@overload
+def rstrip(a: _StringDTypeSupportsArray, chars: T_co | None = None) -> _StringDTypeArray: ...
+@overload
+def rstrip(a: T_co, chars: T_co | None = None) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def strip(a: U_co, chars: U_co | None = None) -> NDArray[np.str_]: ...
+@overload
+def strip(a: S_co, chars: S_co | None = None) -> NDArray[np.bytes_]: ...
+@overload
+def strip(a: _StringDTypeSupportsArray, chars: T_co | None = None) -> _StringDTypeArray: ...
+@overload
+def strip(a: T_co, chars: T_co | None = None) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def zfill(a: U_co, width: i_co) -> NDArray[np.str_]: ...
+@overload
+def zfill(a: S_co, width: i_co) -> NDArray[np.bytes_]: ...
+@overload
+def zfill(a: _StringDTypeSupportsArray, width: i_co) -> _StringDTypeArray: ...
+@overload
+def zfill(a: T_co, width: i_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def upper(a: U_co) -> NDArray[np.str_]: ...
+@overload
+def upper(a: S_co) -> NDArray[np.bytes_]: ...
+@overload
+def upper(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def upper(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def lower(a: U_co) -> NDArray[np.str_]: ...
+@overload
+def lower(a: S_co) -> NDArray[np.bytes_]: ...
+@overload
+def lower(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def lower(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def swapcase(a: U_co) -> NDArray[np.str_]: ...
+@overload
+def swapcase(a: S_co) -> NDArray[np.bytes_]: ...
+@overload
+def swapcase(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def swapcase(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def capitalize(a: U_co) -> NDArray[np.str_]: ...
+@overload
+def capitalize(a: S_co) -> NDArray[np.bytes_]: ...
+@overload
+def capitalize(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def capitalize(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def title(a: U_co) -> NDArray[np.str_]: ...
+@overload
+def title(a: S_co) -> NDArray[np.bytes_]: ...
+@overload
+def title(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def title(a: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def replace(
+ a: U_co,
+ old: U_co,
+ new: U_co,
+ count: i_co = -1,
+) -> NDArray[np.str_]: ...
+@overload
+def replace(
+ a: S_co,
+ old: S_co,
+ new: S_co,
+ count: i_co = -1,
+) -> NDArray[np.bytes_]: ...
+@overload
+def replace(
+ a: _StringDTypeSupportsArray,
+ old: _StringDTypeSupportsArray,
+ new: _StringDTypeSupportsArray,
+ count: i_co = -1,
+) -> _StringDTypeArray: ...
+@overload
+def replace(
+ a: T_co,
+ old: T_co,
+ new: T_co,
+ count: i_co = -1,
+) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def partition(a: U_co, sep: U_co) -> NDArray[np.str_]: ...
+@overload
+def partition(a: S_co, sep: S_co) -> NDArray[np.bytes_]: ...
+@overload
+def partition(a: _StringDTypeSupportsArray, sep: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def partition(a: T_co, sep: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def rpartition(a: U_co, sep: U_co) -> NDArray[np.str_]: ...
+@overload
+def rpartition(a: S_co, sep: S_co) -> NDArray[np.bytes_]: ...
+@overload
+def rpartition(a: _StringDTypeSupportsArray, sep: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
+@overload
+def rpartition(a: T_co, sep: T_co) -> _StringDTypeOrUnicodeArray: ...
+
+@overload
+def translate(
+ a: U_co,
+ table: str,
+ deletechars: str | None = None,
+) -> NDArray[np.str_]: ...
+@overload
+def translate(
+ a: S_co,
+ table: str,
+ deletechars: str | None = None,
+) -> NDArray[np.bytes_]: ...
+@overload
+def translate(
+ a: _StringDTypeSupportsArray,
+ table: str,
+ deletechars: str | None = None,
+) -> _StringDTypeArray: ...
+@overload
+def translate(
+ a: T_co,
+ table: str,
+ deletechars: str | None = None,
+) -> _StringDTypeOrUnicodeArray: ...
+
+#
+@overload
+def slice(
+ a: U_co,
+ start: i_co | None = None,
+ stop: i_co | _NoValueType | None = ..., # = np._NoValue
+ step: i_co | None = None,
+ /,
+) -> NDArray[np.str_]: ...
+@overload
+def slice(
+ a: S_co,
+ start: i_co | None = None,
+ stop: i_co | _NoValueType | None = ..., # = np._NoValue
+ step: i_co | None = None,
+ /,
+) -> NDArray[np.bytes_]: ...
+@overload
+def slice(
+ a: _StringDTypeSupportsArray,
+ start: i_co | None = None,
+ stop: i_co | _NoValueType | None = ..., # = np._NoValue
+ step: i_co | None = None,
+ /,
+) -> _StringDTypeArray: ...
+@overload
+def slice(
+ a: T_co,
+ start: i_co | None = None,
+ stop: i_co | _NoValueType | None = ..., # = np._NoValue
+ step: i_co | None = None,
+ /,
+) -> _StringDTypeOrUnicodeArray: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/umath.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/umath.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc4b8a1238f01dc77aa65fad740cdbb96322f8f6
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/umath.py
@@ -0,0 +1,60 @@
+"""
+Create the numpy._core.umath namespace for backward compatibility. In v1.16
+the multiarray and umath c-extension modules were merged into a single
+_multiarray_umath extension module. So we replicate the old namespace
+by importing from the extension module.
+
+"""
+
+import numpy
+
+from . import _multiarray_umath
+from ._multiarray_umath import *
+
+# These imports are needed for backward compatibility,
+# do not change them. issue gh-11862
+# _ones_like is semi-public, on purpose not added to __all__
+# These imports are needed for the strip & replace implementations
+from ._multiarray_umath import (
+ _UFUNC_API,
+ _add_newdoc_ufunc,
+ _center,
+ _expandtabs,
+ _expandtabs_length,
+ _extobj_contextvar,
+ _get_extobj_dict,
+ _ljust,
+ _lstrip_chars,
+ _lstrip_whitespace,
+ _make_extobj,
+ _ones_like,
+ _partition,
+ _partition_index,
+ _replace,
+ _rjust,
+ _rpartition,
+ _rpartition_index,
+ _rstrip_chars,
+ _rstrip_whitespace,
+ _slice,
+ _strip_chars,
+ _strip_whitespace,
+ _zfill,
+)
+
+__all__ = [
+ 'absolute', 'add',
+ 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh',
+ 'bitwise_and', 'bitwise_or', 'bitwise_xor', 'cbrt', 'ceil', 'conj',
+ 'conjugate', 'copysign', 'cos', 'cosh', 'bitwise_count', 'deg2rad',
+ 'degrees', 'divide', 'divmod', 'e', 'equal', 'euler_gamma', 'exp', 'exp2',
+ 'expm1', 'fabs', 'floor', 'floor_divide', 'float_power', 'fmax', 'fmin',
+ 'fmod', 'frexp', 'frompyfunc', 'gcd', 'greater', 'greater_equal',
+ 'heaviside', 'hypot', 'invert', 'isfinite', 'isinf', 'isnan', 'isnat',
+ 'lcm', 'ldexp', 'left_shift', 'less', 'less_equal', 'log', 'log10',
+ 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and', 'logical_not',
+ 'logical_or', 'logical_xor', 'matmul', 'matvec', 'maximum', 'minimum', 'mod',
+ 'modf', 'multiply', 'negative', 'nextafter', 'not_equal', 'pi', 'positive',
+ 'power', 'rad2deg', 'radians', 'reciprocal', 'remainder', 'right_shift',
+ 'rint', 'sign', 'signbit', 'sin', 'sinh', 'spacing', 'sqrt', 'square',
+ 'subtract', 'tan', 'tanh', 'true_divide', 'trunc', 'vecdot', 'vecmat']
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_core/umath.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/umath.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..faf6fb545d5f2d97f80a0149ca59761185ac2124
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_core/umath.pyi
@@ -0,0 +1,232 @@
+import contextvars
+from _typeshed import SupportsWrite
+from collections.abc import Callable
+from typing import Any, Final, Literal, TypeAlias, TypedDict, Unpack, type_check_only
+from typing_extensions import CapsuleType
+
+from numpy import (
+ absolute,
+ add,
+ arccos,
+ arccosh,
+ arcsin,
+ arcsinh,
+ arctan,
+ arctan2,
+ arctanh,
+ bitwise_and,
+ bitwise_count,
+ bitwise_or,
+ bitwise_xor,
+ cbrt,
+ ceil,
+ conj,
+ conjugate,
+ copysign,
+ cos,
+ cosh,
+ deg2rad,
+ degrees,
+ divide,
+ divmod,
+ e,
+ equal,
+ euler_gamma,
+ exp,
+ exp2,
+ expm1,
+ fabs,
+ float_power,
+ floor,
+ floor_divide,
+ fmax,
+ fmin,
+ fmod,
+ frexp,
+ frompyfunc,
+ gcd,
+ greater,
+ greater_equal,
+ heaviside,
+ hypot,
+ invert,
+ isfinite,
+ isinf,
+ isnan,
+ isnat,
+ lcm,
+ ldexp,
+ left_shift,
+ less,
+ less_equal,
+ log,
+ log1p,
+ log2,
+ log10,
+ logaddexp,
+ logaddexp2,
+ logical_and,
+ logical_not,
+ logical_or,
+ logical_xor,
+ matmul,
+ matvec,
+ maximum,
+ minimum,
+ mod,
+ modf,
+ multiply,
+ negative,
+ nextafter,
+ not_equal,
+ pi,
+ positive,
+ power,
+ rad2deg,
+ radians,
+ reciprocal,
+ remainder,
+ right_shift,
+ rint,
+ sign,
+ signbit,
+ sin,
+ sinh,
+ spacing,
+ sqrt,
+ square,
+ subtract,
+ tan,
+ tanh,
+ true_divide,
+ trunc,
+ vecdot,
+ vecmat,
+)
+
+__all__ = [
+ "absolute",
+ "add",
+ "arccos",
+ "arccosh",
+ "arcsin",
+ "arcsinh",
+ "arctan",
+ "arctan2",
+ "arctanh",
+ "bitwise_and",
+ "bitwise_count",
+ "bitwise_or",
+ "bitwise_xor",
+ "cbrt",
+ "ceil",
+ "conj",
+ "conjugate",
+ "copysign",
+ "cos",
+ "cosh",
+ "deg2rad",
+ "degrees",
+ "divide",
+ "divmod",
+ "e",
+ "equal",
+ "euler_gamma",
+ "exp",
+ "exp2",
+ "expm1",
+ "fabs",
+ "float_power",
+ "floor",
+ "floor_divide",
+ "fmax",
+ "fmin",
+ "fmod",
+ "frexp",
+ "frompyfunc",
+ "gcd",
+ "greater",
+ "greater_equal",
+ "heaviside",
+ "hypot",
+ "invert",
+ "isfinite",
+ "isinf",
+ "isnan",
+ "isnat",
+ "lcm",
+ "ldexp",
+ "left_shift",
+ "less",
+ "less_equal",
+ "log",
+ "log1p",
+ "log2",
+ "log10",
+ "logaddexp",
+ "logaddexp2",
+ "logical_and",
+ "logical_not",
+ "logical_or",
+ "logical_xor",
+ "matmul",
+ "matvec",
+ "maximum",
+ "minimum",
+ "mod",
+ "modf",
+ "multiply",
+ "negative",
+ "nextafter",
+ "not_equal",
+ "pi",
+ "positive",
+ "power",
+ "rad2deg",
+ "radians",
+ "reciprocal",
+ "remainder",
+ "right_shift",
+ "rint",
+ "sign",
+ "signbit",
+ "sin",
+ "sinh",
+ "spacing",
+ "sqrt",
+ "square",
+ "subtract",
+ "tan",
+ "tanh",
+ "true_divide",
+ "trunc",
+ "vecdot",
+ "vecmat",
+]
+
+###
+
+_ErrKind: TypeAlias = Literal["ignore", "warn", "raise", "call", "print", "log"]
+_ErrCall: TypeAlias = Callable[[str, int], Any] | SupportsWrite[str]
+
+@type_check_only
+class _ExtOjbDict(TypedDict, total=False):
+ divide: _ErrKind
+ over: _ErrKind
+ under: _ErrKind
+ invalid: _ErrKind
+ call: _ErrCall | None
+ bufsize: int
+
+# re-exports from `_core._multiarray_umath` that are used by `_core._ufunc_config`
+
+NAN: Final[float] = float("nan")
+PINF: Final[float] = float("+inf")
+NINF: Final[float] = float("-inf")
+PZERO: Final[float] = +0.0
+NZERO: Final[float] = -0.0
+_UFUNC_API: Final[CapsuleType] = ...
+_extobj_contextvar: Final[contextvars.ContextVar[CapsuleType]] = ...
+
+def _get_extobj_dict() -> _ExtOjbDict: ...
+def _make_extobj(*, all: _ErrKind = ..., **kwargs: Unpack[_ExtOjbDict]) -> CapsuleType: ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_pyinstaller/__init__.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_pyinstaller/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_pyinstaller/__init__.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_pyinstaller/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_pyinstaller/hook-numpy.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_pyinstaller/hook-numpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..61c224b338104d47e6d1b888d0face3b874f5e34
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_pyinstaller/hook-numpy.py
@@ -0,0 +1,36 @@
+"""This hook should collect all binary files and any hidden modules that numpy
+needs.
+
+Our (some-what inadequate) docs for writing PyInstaller hooks are kept here:
+https://pyinstaller.readthedocs.io/en/stable/hooks.html
+
+"""
+from PyInstaller.compat import is_pure_conda
+from PyInstaller.utils.hooks import collect_dynamic_libs
+
+# Collect all DLLs inside numpy's installation folder, dump them into built
+# app's root.
+binaries = collect_dynamic_libs("numpy", ".")
+
+# If using Conda without any non-conda virtual environment manager:
+if is_pure_conda:
+ # Assume running the NumPy from Conda-forge and collect it's DLLs from the
+ # communal Conda bin directory. DLLs from NumPy's dependencies must also be
+ # collected to capture MKL, OpenBlas, OpenMP, etc.
+ from PyInstaller.utils.hooks import conda_support
+ datas = conda_support.collect_dynamic_libs("numpy", dependencies=True)
+
+# Submodules PyInstaller cannot detect. `_dtype_ctypes` is only imported
+# from C and `_multiarray_tests` is used in tests (which are not packed).
+hiddenimports = ['numpy._core._dtype_ctypes', 'numpy._core._multiarray_tests']
+
+# Remove testing and building code and packages that are referenced throughout
+# NumPy but are not really dependencies.
+excludedimports = [
+ "scipy",
+ "pytest",
+ "f2py",
+ "setuptools",
+ "distutils",
+ "numpy.distutils",
+]
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_pyinstaller/hook-numpy.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_pyinstaller/hook-numpy.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..6da4914d7e5adf4fbd0c90500b8b14fc9f1e908c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_pyinstaller/hook-numpy.pyi
@@ -0,0 +1,6 @@
+from typing import Final
+
+binaries: Final[list[tuple[str, str]]] = ...
+
+hiddenimports: Final[list[str]] = ...
+excludedimports: Final[list[str]] = ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_typing/__init__.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_typing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..22eb6e3f30bb98948782cc88f6ebae7c2092a968
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_typing/__init__.py
@@ -0,0 +1,173 @@
+"""Private counterpart of ``numpy.typing``."""
+
+import sys
+
+from ._array_like import (
+ NDArray as NDArray,
+ _ArrayLike as _ArrayLike,
+ _ArrayLikeAnyString_co as _ArrayLikeAnyString_co,
+ _ArrayLikeBool_co as _ArrayLikeBool_co,
+ _ArrayLikeBytes_co as _ArrayLikeBytes_co,
+ _ArrayLikeComplex128_co as _ArrayLikeComplex128_co,
+ _ArrayLikeComplex_co as _ArrayLikeComplex_co,
+ _ArrayLikeDT64_co as _ArrayLikeDT64_co,
+ _ArrayLikeFloat64_co as _ArrayLikeFloat64_co,
+ _ArrayLikeFloat_co as _ArrayLikeFloat_co,
+ _ArrayLikeInt as _ArrayLikeInt,
+ _ArrayLikeInt_co as _ArrayLikeInt_co,
+ _ArrayLikeNumber_co as _ArrayLikeNumber_co,
+ _ArrayLikeObject_co as _ArrayLikeObject_co,
+ _ArrayLikeStr_co as _ArrayLikeStr_co,
+ _ArrayLikeString_co as _ArrayLikeString_co,
+ _ArrayLikeTD64_co as _ArrayLikeTD64_co,
+ _ArrayLikeUInt_co as _ArrayLikeUInt_co,
+ _ArrayLikeVoid_co as _ArrayLikeVoid_co,
+ _FiniteNestedSequence as _FiniteNestedSequence,
+ _SupportsArray as _SupportsArray,
+ _SupportsArrayFunc as _SupportsArrayFunc,
+)
+
+#
+from ._char_codes import (
+ _BoolCodes as _BoolCodes,
+ _ByteCodes as _ByteCodes,
+ _BytesCodes as _BytesCodes,
+ _CDoubleCodes as _CDoubleCodes,
+ _CharacterCodes as _CharacterCodes,
+ _CLongDoubleCodes as _CLongDoubleCodes,
+ _Complex64Codes as _Complex64Codes,
+ _Complex128Codes as _Complex128Codes,
+ _ComplexFloatingCodes as _ComplexFloatingCodes,
+ _CSingleCodes as _CSingleCodes,
+ _DoubleCodes as _DoubleCodes,
+ _DT64Codes as _DT64Codes,
+ _FlexibleCodes as _FlexibleCodes,
+ _Float16Codes as _Float16Codes,
+ _Float32Codes as _Float32Codes,
+ _Float64Codes as _Float64Codes,
+ _FloatingCodes as _FloatingCodes,
+ _GenericCodes as _GenericCodes,
+ _HalfCodes as _HalfCodes,
+ _InexactCodes as _InexactCodes,
+ _Int8Codes as _Int8Codes,
+ _Int16Codes as _Int16Codes,
+ _Int32Codes as _Int32Codes,
+ _Int64Codes as _Int64Codes,
+ _IntCCodes as _IntCCodes,
+ _IntCodes as _IntCodes,
+ _IntegerCodes as _IntegerCodes,
+ _IntPCodes as _IntPCodes,
+ _LongCodes as _LongCodes,
+ _LongDoubleCodes as _LongDoubleCodes,
+ _LongLongCodes as _LongLongCodes,
+ _NumberCodes as _NumberCodes,
+ _ObjectCodes as _ObjectCodes,
+ _ShortCodes as _ShortCodes,
+ _SignedIntegerCodes as _SignedIntegerCodes,
+ _SingleCodes as _SingleCodes,
+ _StrCodes as _StrCodes,
+ _StringCodes as _StringCodes,
+ _TD64Codes as _TD64Codes,
+ _UByteCodes as _UByteCodes,
+ _UInt8Codes as _UInt8Codes,
+ _UInt16Codes as _UInt16Codes,
+ _UInt32Codes as _UInt32Codes,
+ _UInt64Codes as _UInt64Codes,
+ _UIntCCodes as _UIntCCodes,
+ _UIntCodes as _UIntCodes,
+ _UIntPCodes as _UIntPCodes,
+ _ULongCodes as _ULongCodes,
+ _ULongLongCodes as _ULongLongCodes,
+ _UnsignedIntegerCodes as _UnsignedIntegerCodes,
+ _UShortCodes as _UShortCodes,
+ _VoidCodes as _VoidCodes,
+)
+
+#
+from ._dtype_like import (
+ _DTypeLike as _DTypeLike,
+ _DTypeLikeBool as _DTypeLikeBool,
+ _DTypeLikeBytes as _DTypeLikeBytes,
+ _DTypeLikeComplex as _DTypeLikeComplex,
+ _DTypeLikeComplex_co as _DTypeLikeComplex_co,
+ _DTypeLikeDT64 as _DTypeLikeDT64,
+ _DTypeLikeFloat as _DTypeLikeFloat,
+ _DTypeLikeInt as _DTypeLikeInt,
+ _DTypeLikeObject as _DTypeLikeObject,
+ _DTypeLikeStr as _DTypeLikeStr,
+ _DTypeLikeTD64 as _DTypeLikeTD64,
+ _DTypeLikeUInt as _DTypeLikeUInt,
+ _DTypeLikeVoid as _DTypeLikeVoid,
+ _HasDType as _HasDType,
+ _SupportsDType as _SupportsDType,
+ _VoidDTypeLike as _VoidDTypeLike,
+)
+
+#
+from ._nbit import (
+ _NBitByte as _NBitByte,
+ _NBitDouble as _NBitDouble,
+ _NBitHalf as _NBitHalf,
+ _NBitInt as _NBitInt,
+ _NBitIntC as _NBitIntC,
+ _NBitIntP as _NBitIntP,
+ _NBitLong as _NBitLong,
+ _NBitLongDouble as _NBitLongDouble,
+ _NBitLongLong as _NBitLongLong,
+ _NBitShort as _NBitShort,
+ _NBitSingle as _NBitSingle,
+)
+
+#
+from ._nbit_base import ( # type: ignore[deprecated]
+ NBitBase as NBitBase, # pyright: ignore[reportDeprecated]
+ _8Bit as _8Bit,
+ _16Bit as _16Bit,
+ _32Bit as _32Bit,
+ _64Bit as _64Bit,
+ _96Bit as _96Bit,
+ _128Bit as _128Bit,
+)
+
+#
+from ._nested_sequence import _NestedSequence as _NestedSequence
+
+#
+from ._scalars import (
+ _BoolLike_co as _BoolLike_co,
+ _CharLike_co as _CharLike_co,
+ _ComplexLike_co as _ComplexLike_co,
+ _FloatLike_co as _FloatLike_co,
+ _IntLike_co as _IntLike_co,
+ _NumberLike_co as _NumberLike_co,
+ _ScalarLike_co as _ScalarLike_co,
+ _TD64Like_co as _TD64Like_co,
+ _UIntLike_co as _UIntLike_co,
+ _VoidLike_co as _VoidLike_co,
+)
+
+#
+from ._shape import _AnyShape as _AnyShape, _Shape as _Shape, _ShapeLike as _ShapeLike
+
+#
+from ._ufunc import (
+ _GUFunc_Nin2_Nout1 as _GUFunc_Nin2_Nout1,
+ _UFunc_Nin1_Nout1 as _UFunc_Nin1_Nout1,
+ _UFunc_Nin1_Nout2 as _UFunc_Nin1_Nout2,
+ _UFunc_Nin2_Nout1 as _UFunc_Nin2_Nout1,
+ _UFunc_Nin2_Nout2 as _UFunc_Nin2_Nout2,
+)
+
+# wrapping the public aliases in `TypeAliasType` helps with introspection readability
+if sys.version_info >= (3, 12):
+ from typing import TypeAliasType
+
+ from ._array_like import ArrayLike as _ArrayLikeAlias
+ from ._dtype_like import DTypeLike as _DTypeLikeAlias
+
+ ArrayLike = TypeAliasType("ArrayLike", _ArrayLikeAlias)
+ DTypeLike = TypeAliasType("DTypeLike", _DTypeLikeAlias)
+
+else:
+ from ._array_like import ArrayLike as ArrayLike
+ from ._dtype_like import DTypeLike as DTypeLike
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_typing/_add_docstring.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_typing/_add_docstring.py
new file mode 100644
index 0000000000000000000000000000000000000000..5330a6b3b7159ba528602a624702975b6827feab
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_typing/_add_docstring.py
@@ -0,0 +1,153 @@
+"""A module for creating docstrings for sphinx ``data`` domains."""
+
+import re
+import textwrap
+
+from ._array_like import NDArray
+
+_docstrings_list = []
+
+
+def add_newdoc(name: str, value: str, doc: str) -> None:
+ """Append ``_docstrings_list`` with a docstring for `name`.
+
+ Parameters
+ ----------
+ name : str
+ The name of the object.
+ value : str
+ A string-representation of the object.
+ doc : str
+ The docstring of the object.
+
+ """
+ _docstrings_list.append((name, value, doc))
+
+
+def _parse_docstrings() -> str:
+ """Convert all docstrings in ``_docstrings_list`` into a single
+ sphinx-legible text block.
+
+ """
+ type_list_ret = []
+ for name, value, doc in _docstrings_list:
+ s = textwrap.dedent(doc).replace("\n", "\n ")
+
+ # Replace sections by rubrics
+ lines = s.split("\n")
+ new_lines = []
+ indent = ""
+ for line in lines:
+ m = re.match(r'^(\s+)[-=]+\s*$', line)
+ if m and new_lines:
+ prev = textwrap.dedent(new_lines.pop())
+ if prev == "Examples":
+ indent = ""
+ new_lines.append(f'{m.group(1)}.. rubric:: {prev}')
+ else:
+ indent = 4 * " "
+ new_lines.append(f'{m.group(1)}.. admonition:: {prev}')
+ new_lines.append("")
+ else:
+ new_lines.append(f"{indent}{line}")
+
+ s = "\n".join(new_lines)
+ s_block = f""".. data:: {name}\n :value: {value}\n {s}"""
+ type_list_ret.append(s_block)
+ return "\n".join(type_list_ret)
+
+
+add_newdoc('ArrayLike', 'typing.Union[...]',
+ """
+ A `~typing.Union` representing objects that can be coerced
+ into an `~numpy.ndarray`.
+
+ Among others this includes the likes of:
+
+ * Scalars.
+ * (Nested) sequences.
+ * Objects implementing the `~class.__array__` protocol.
+
+ .. versionadded:: 1.20
+
+ See Also
+ --------
+ :term:`array_like`:
+ Any scalar or sequence that can be interpreted as an ndarray.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ >>> import numpy as np
+ >>> import numpy.typing as npt
+
+ >>> def as_array(a: npt.ArrayLike) -> np.ndarray:
+ ... return np.array(a)
+
+ """)
+
+add_newdoc('DTypeLike', 'typing.Union[...]',
+ """
+ A `~typing.Union` representing objects that can be coerced
+ into a `~numpy.dtype`.
+
+ Among others this includes the likes of:
+
+ * :class:`type` objects.
+ * Character codes or the names of :class:`type` objects.
+ * Objects with the ``.dtype`` attribute.
+
+ .. versionadded:: 1.20
+
+ See Also
+ --------
+ :ref:`Specifying and constructing data types `
+ A comprehensive overview of all objects that can be coerced
+ into data types.
+
+ Examples
+ --------
+ .. code-block:: python
+
+ >>> import numpy as np
+ >>> import numpy.typing as npt
+
+ >>> def as_dtype(d: npt.DTypeLike) -> np.dtype:
+ ... return np.dtype(d)
+
+ """)
+
+add_newdoc('NDArray', repr(NDArray),
+ """
+ A `np.ndarray[tuple[Any, ...], np.dtype[ScalarT]] `
+ type alias :term:`generic ` w.r.t. its
+ `dtype.type `.
+
+ Can be used during runtime for typing arrays with a given dtype
+ and unspecified shape.
+
+ .. versionadded:: 1.21
+
+ Examples
+ --------
+ .. code-block:: python
+
+ >>> import numpy as np
+ >>> import numpy.typing as npt
+
+ >>> print(npt.NDArray)
+ numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[~_ScalarT]]
+
+ >>> print(npt.NDArray[np.float64])
+ numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[numpy.float64]]
+
+ >>> NDArrayInt = npt.NDArray[np.int_]
+ >>> a: NDArrayInt = np.arange(10)
+
+ >>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]:
+ ... return np.array(a)
+
+ """)
+
+_docstrings = _parse_docstrings()
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_typing/_array_like.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_typing/_array_like.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b071f4a031999c6a61edc9a35e082ad8be2ff76
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_typing/_array_like.py
@@ -0,0 +1,106 @@
+import sys
+from collections.abc import Callable, Collection, Sequence
+from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, TypeVar, runtime_checkable
+
+import numpy as np
+from numpy import dtype
+
+from ._nbit_base import _32Bit, _64Bit
+from ._nested_sequence import _NestedSequence
+from ._shape import _AnyShape
+
+if TYPE_CHECKING:
+ StringDType = np.dtypes.StringDType
+else:
+ # at runtime outside of type checking importing this from numpy.dtypes
+ # would lead to a circular import
+ from numpy._core.multiarray import StringDType
+
+_T = TypeVar("_T")
+_ScalarT = TypeVar("_ScalarT", bound=np.generic)
+_DTypeT = TypeVar("_DTypeT", bound=dtype[Any])
+_DTypeT_co = TypeVar("_DTypeT_co", covariant=True, bound=dtype[Any])
+
+NDArray: TypeAlias = np.ndarray[_AnyShape, dtype[_ScalarT]]
+
+# The `_SupportsArray` protocol only cares about the default dtype
+# (i.e. `dtype=None` or no `dtype` parameter at all) of the to-be returned
+# array.
+# Concrete implementations of the protocol are responsible for adding
+# any and all remaining overloads
+@runtime_checkable
+class _SupportsArray(Protocol[_DTypeT_co]):
+ def __array__(self) -> np.ndarray[Any, _DTypeT_co]: ...
+
+
+@runtime_checkable
+class _SupportsArrayFunc(Protocol):
+ """A protocol class representing `~class.__array_function__`."""
+ def __array_function__(
+ self,
+ func: Callable[..., Any],
+ types: Collection[type[Any]],
+ args: tuple[Any, ...],
+ kwargs: dict[str, Any],
+ ) -> object: ...
+
+
+# TODO: Wait until mypy supports recursive objects in combination with typevars
+_FiniteNestedSequence: TypeAlias = (
+ _T
+ | Sequence[_T]
+ | Sequence[Sequence[_T]]
+ | Sequence[Sequence[Sequence[_T]]]
+ | Sequence[Sequence[Sequence[Sequence[_T]]]]
+)
+
+# A subset of `npt.ArrayLike` that can be parametrized w.r.t. `np.generic`
+_ArrayLike: TypeAlias = (
+ _SupportsArray[dtype[_ScalarT]]
+ | _NestedSequence[_SupportsArray[dtype[_ScalarT]]]
+)
+
+# A union representing array-like objects; consists of two typevars:
+# One representing types that can be parametrized w.r.t. `np.dtype`
+# and another one for the rest
+_DualArrayLike: TypeAlias = (
+ _SupportsArray[_DTypeT]
+ | _NestedSequence[_SupportsArray[_DTypeT]]
+ | _T
+ | _NestedSequence[_T]
+)
+
+if sys.version_info >= (3, 12):
+ from collections.abc import Buffer as _Buffer
+else:
+ @runtime_checkable
+ class _Buffer(Protocol):
+ def __buffer__(self, flags: int, /) -> memoryview: ...
+
+ArrayLike: TypeAlias = _Buffer | _DualArrayLike[dtype[Any], complex | bytes | str]
+
+# `ArrayLike_co`: array-like objects that can be coerced into `X`
+# given the casting rules `same_kind`
+_ArrayLikeBool_co: TypeAlias = _DualArrayLike[dtype[np.bool], bool]
+_ArrayLikeUInt_co: TypeAlias = _DualArrayLike[dtype[np.bool | np.unsignedinteger], bool]
+_ArrayLikeInt_co: TypeAlias = _DualArrayLike[dtype[np.bool | np.integer], int]
+_ArrayLikeFloat_co: TypeAlias = _DualArrayLike[dtype[np.bool | np.integer | np.floating], float]
+_ArrayLikeComplex_co: TypeAlias = _DualArrayLike[dtype[np.bool | np.number], complex]
+_ArrayLikeNumber_co: TypeAlias = _ArrayLikeComplex_co
+_ArrayLikeTD64_co: TypeAlias = _DualArrayLike[dtype[np.bool | np.integer | np.timedelta64], int]
+_ArrayLikeDT64_co: TypeAlias = _ArrayLike[np.datetime64]
+_ArrayLikeObject_co: TypeAlias = _ArrayLike[np.object_]
+
+_ArrayLikeVoid_co: TypeAlias = _ArrayLike[np.void]
+_ArrayLikeBytes_co: TypeAlias = _DualArrayLike[dtype[np.bytes_], bytes]
+_ArrayLikeStr_co: TypeAlias = _DualArrayLike[dtype[np.str_], str]
+_ArrayLikeString_co: TypeAlias = _DualArrayLike[StringDType, str]
+_ArrayLikeAnyString_co: TypeAlias = _DualArrayLike[dtype[np.character] | StringDType, bytes | str]
+
+__Float64_co: TypeAlias = np.floating[_64Bit] | np.float32 | np.float16 | np.integer | np.bool
+__Complex128_co: TypeAlias = np.number[_64Bit] | np.number[_32Bit] | np.float16 | np.integer | np.bool
+_ArrayLikeFloat64_co: TypeAlias = _DualArrayLike[dtype[__Float64_co], float]
+_ArrayLikeComplex128_co: TypeAlias = _DualArrayLike[dtype[__Complex128_co], complex]
+
+# NOTE: This includes `builtins.bool`, but not `numpy.bool`.
+_ArrayLikeInt: TypeAlias = _DualArrayLike[dtype[np.integer], int]
diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_typing/_char_codes.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_typing/_char_codes.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b6fad228d56400556fc13371ace114c056b3ed8
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_typing/_char_codes.py
@@ -0,0 +1,213 @@
+from typing import Literal
+
+_BoolCodes = Literal[
+ "bool", "bool_",
+ "?", "|?", "=?", "", ">?",
+ "b1", "|b1", "=b1", "b1",
+] # fmt: skip
+
+_UInt8Codes = Literal["uint8", "u1", "|u1", "=u1", "u1"]
+_UInt16Codes = Literal["uint16", "u2", "|u2", "=u2", "u2"]
+_UInt32Codes = Literal["uint32", "u4", "|u4", "=u4", "u4"]
+_UInt64Codes = Literal["uint64", "u8", "|u8", "=u8", "u8"]
+
+_Int8Codes = Literal["int8", "i1", "|i1", "=i1", "i1"]
+_Int16Codes = Literal["int16", "i2", "|i2", "=i2", "i2"]
+_Int32Codes = Literal["int32", "i4", "|i4", "=i4", "i4"]
+_Int64Codes = Literal["int64", "i8", "|i8", "=i8", "i8"]
+
+_Float16Codes = Literal["float16", "f2", "|f2", "=f2", "f2"]
+_Float32Codes = Literal["float32", "f4", "|f4", "=f4", "f4"]
+_Float64Codes = Literal["float64", "f8", "|f8", "=f8", "f8"]
+
+_Complex64Codes = Literal["complex64", "c8", "|c8", "=c8", "c8"]
+_Complex128Codes = Literal["complex128", "c16", "|c16", "=c16", "c16"]
+
+_ByteCodes = Literal["byte", "b", "|b", "=b", "b"]
+_ShortCodes = Literal["short", "h", "|h", "=h", "h"]
+_IntCCodes = Literal["intc", "i", "|i", "=i", "i"]
+_IntPCodes = Literal["intp", "int", "int_", "n", "|n", "=n", "n"]
+_LongCodes = Literal["long", "l", "|l", "=l", "l"]
+_IntCodes = _IntPCodes
+_LongLongCodes = Literal["longlong", "q", "|q", "=q", "q"]
+
+_UByteCodes = Literal["ubyte", "B", "|B", "=B", "B"]
+_UShortCodes = Literal["ushort", "H", "|H", "=H", "H"]
+_UIntCCodes = Literal["uintc", "I", "|I", "=I", "I"]
+_UIntPCodes = Literal["uintp", "uint", "N", "|N", "=N", "N"]
+_ULongCodes = Literal["ulong", "L", "|L", "=L", "L"]
+_UIntCodes = _UIntPCodes
+_ULongLongCodes = Literal["ulonglong", "Q", "|Q", "=Q", "Q"]
+
+_HalfCodes = Literal["half", "e", "|e", "=e", "e"]
+_SingleCodes = Literal["single", "f", "|f", "=f", "f"]
+_DoubleCodes = Literal["double", "float", "d", "|d", "=d", "d"]
+_LongDoubleCodes = Literal["longdouble", "g", "|g", "=g", "g"]
+
+_CSingleCodes = Literal["csingle", "F", "|F", "=F", "F"]
+_CDoubleCodes = Literal["cdouble", "complex", "D", "|D", "=D", "D"]
+_CLongDoubleCodes = Literal["clongdouble", "G", "|G", "=G", "G"]
+
+_StrCodes = Literal["str", "str_", "unicode", "U", "|U", "=U", "U"]
+_BytesCodes = Literal["bytes", "bytes_", "S", "|S", "=S", "S"]
+_VoidCodes = Literal["void", "V", "|V", "=V", "V"]
+_ObjectCodes = Literal["object", "object_", "O", "|O", "=O", "