text
stringlengths
17
362k
id
stringlengths
13
115
metadata
dict
__index_level_0__
int64
0
75
<component name="ProjectCodeStyleConfiguration"> <state> <option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" /> </state> </component>
ivy/.idea/codeStyles/codeStyleConfig.xml/0
{ "file_path": "ivy/.idea/codeStyles/codeStyleConfig.xml", "repo_id": "ivy", "token_count": 51 }
0
# How to Contribute You can pick an open issue to contribute from our [ToDo list issues](https://github.com/unifyai/ivy/issues?q=is%3Aopen+is%3Aissue+label%3AToDo), which is the placeholder of our subtasks. Please, follow the next process when you work on your subtask: ## Steps 1. **Choosing a Task:** - Choose a task to work on which: - is not marked as completed with a tick. - does not have an issue created. - is not mentioned in the comments. Currently, there are three open tasks: - [Function Reformatting](https://unify.ai/docs/ivy/overview/contributing/open_tasks.html#function-formatting) - [Frontend APIs](https://unify.ai/docs/ivy/overview/contributing/open_tasks.html#frontend-apis) - [Ivy Experimental API](https://unify.ai/docs/ivy/overview/contributing/open_tasks.html#ivy-experimental-api) 2. **Create Issue:** - Create a new issue with the title being just the name of the sub-task you would like to work on. 3. **Comment on the ToDo List:** - Comment on the ToDo list issue with a reference to your new issue like so: `- [ ] #Issue_number`. For example, if your issue number is 12345, then the text of your comment should be `- [ ] #12345`. You could also use just the issue number (`#12345`), or a link to the issue itself (`https://github.com/unifyai/ivy/issues/12345`). - At some point after your comment is made, your issue will automatically be added to the ToDo list and the comment will be deleted. No need to wait for this to happen before progressing to the next stage. Don’t comment anything else on these ToDo issues. 4. **Start Working:** - When you have finished PR or need help open the PR make sure to follow our PR template. 5. **Review Process:** - Wait for us to review your PR. Please be patient, our engineers will look into your PR based on the queue we have, no need to ping them. - Every time you respond to our requested changes you must re-request a review in order for us to re-engage with the PR. - Once the PR is in good shape, we will merge into main, and then you become an Ivy contributor! ### Important Notes - If your PR is not created within 7 days of creating the issue, then a warning message will appear on the issue, we do this in order to keep our ToDo lists moving quickly, - Please don't take it personally if your issue or PR gets closed because of this 7-day inactivity time limit. - Finally, we limit the maximum number of open and incomplete sub-task issues to three per person. Feel free to watch the next video: [![Video](https://img.youtube.com/vi/wBKTOGmwfbo/0.jpg)](https://www.youtube.com/embed/wBKTOGmwfbo) For questions, please reach out on [discord](https://discord.gg/MDK979Ga) in the [todo list issues thread](https://discord.com/channels/799879767196958751/1189903501011202128)!
ivy/CONTRIBUTING.md/0
{ "file_path": "ivy/CONTRIBUTING.md", "repo_id": "ivy", "token_count": 849 }
1
#!/bin/bash docker build --progress=plain -t unifyai/multiversion:base -f MultiversionDockerFile ..
ivy/docker/build_multiversiondockerfile.sh/0
{ "file_path": "ivy/docker/build_multiversiondockerfile.sh", "repo_id": "ivy", "token_count": 39 }
2
.. title:: Home .. include:: ../README.md :parser: myst_parser.sphinx_ .. toctree:: :hidden: :maxdepth: -1 Home <self> .. toctree:: :hidden: :maxdepth: -1 :caption: The Basics overview/get_started.rst demos/quickstart.ipynb .. toctree:: :hidden: :maxdepth: -1 :caption: Demos demos/learn_the_basics.rst demos/guides.rst demos/examples_and_demos.rst .. toctree:: :hidden: :maxdepth: -1 :caption: Background overview/motivation.rst overview/related_work.rst .. toctree:: :hidden: :maxdepth: -1 :caption: Contributors overview/design.rst overview/contributing.rst overview/volunteer_ranks.rst overview/deep_dive.rst overview/glossary.rst overview/faq.rst .. toctree:: :hidden: :maxdepth: -1 :caption: API Reference overview/one_liners.rst .. autosummary:: :toctree: docs/functional :template: top_functional_toc.rst :recursive: :hide-table: ivy.functional.ivy .. autosummary:: :toctree: docs/data_classes :template: top_data_toc.rst :recursive: :hide-table: ivy.data_classes .. autosummary:: :toctree: docs :template: top_ivy_toc.rst :recursive: :hide-table: ivy.stateful ivy.utils ivy_tests.test_ivy.helpers
ivy/docs/index.rst/0
{ "file_path": "ivy/docs/index.rst", "repo_id": "ivy", "token_count": 514 }
3
Containers ========== .. _`ivy.Container`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/container.py#L52 .. _`dict`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L51 .. _`ivy.Container.cont_map`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L3070 .. _`ivy.Container.cont_all_true`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L1592 .. _`ivy.Container.cont_to_iterator`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L2043 .. _`ContainerBase`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L51 .. _`ivy.Container.cont_multi_map`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L623 .. _`ivy.Container.cont_diff`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L427 .. _`ivy.Container.cont_common_key_chains`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L741 .. _`ivy.Container.cont_multi_map_in_function`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L162 .. _`ivy.Container.tan`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/elementwise.py#L7347 .. _`ivy.Container.roll`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/manipulation.py#L927 .. _`instance method is added`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/__init__.py#L683 .. _`inherits`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/container.py#L52 .. _`ContainerWithElementwise`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/elementwise.py#L9 .. _`__repr__`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L3629 .. _`__getattr__`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L3860 .. _`__setattr__`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L3882 .. _`__getitem__`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L3934 .. _`__setitem__`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L3976 .. _`__contains__`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L3996 .. _`__getstate__`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L4004 .. _`__setstate__`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/base.py#L4019 .. _`implemented`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/container.py#L133 .. _`__add__`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/container.py#L191 .. _`__sub__`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/container.py#L290 .. _`__mul__`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/container.py#L389 .. _`__truediv__`: https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/container/container.py#L399 .. _`repo`: https://github.com/unifyai/ivy .. _`discord`: https://discord.gg/sXyFF8tDtm .. _`containers thread`: https://discord.com/channels/799879767196958751/1189906066549506048 The `ivy.Container`_ inherits from `dict`_, and is useful for storing nested data. For example, the container is equally suitable for storing batches of training data, or for storing the weights of a network. The methods of the :class:`ivy.Container` class are more varied than those of the :class:`ivy.Array`. All methods of the :class:`ivy.Array` are instance methods, and almost all of them directly wrap a function in the functional API. For the :class:`ivy.Container`, there are also methods which are specific to the container itself, for performing nested operations on the leaves of the container for example. Overall, this results in the following three mutually exclusive groups of :class:`ivy.Container` methods. Each of these are explained in the following sub-sections. #. Container instance methods #. API instance methods #. API special methods Container Instance Methods -------------------------- Container instance methods are methods which are specific to the container itself. A few examples include `ivy.Container.cont_map`_ which is used for mapping a function to all leaves of the container, `ivy.Container.cont_all_true`_ which determines if all container leaves evaluate to boolean `True`, and `ivy.Container.cont_to_iterator`_ which returns an iterator for traversing the leaves of the container. There are many more examples, check out the abstract `ContainerBase`_ class to see some more! API Instance Methods -------------------- The *API* instance methods serve a similar purpose to the instance methods of the :class:`ivy.Array` class. They enable functions in Ivy's functional API to be called as instance methods on the :class:`ivy.Container` class. The difference is that with the :class:`ivy.Container`, the API function is applied recursively to all the leaves of the container. The :class:`ivy.Container` instance methods should **exactly match** the instance methods of the :class:`ivy.Array`, both in terms of the methods implemented and the argument which :code:`self` replaces in the function being called. This means :code:`self` should always replace the first array argument in the function. `ivy.Container.add <https://github.com/unifyai/ivy/blob/1dba30aae5c087cd8b9ffe7c4b42db1904160873/ivy/container/elementwise.py#L158>`_ is a good example. However, as with the :class:`ivy.Array` class, it's important to bear in mind that this is *not necessarily the first argument*, although in most cases it will be. We also **do not** set the :code:`out` argument to :code:`self` for instance methods. If the only array argument is the :code:`out` argument, then we do not implement this instance method. For example, we do not implement an instance method for `ivy.zeros <https://github.com/unifyai/ivy/blob/1dba30aae5c087cd8b9ffe7c4b42db1904160873/ivy/functional/ivy/creation.py#L116>`_. As is the case for :class:`ivy.Array`, the organization of these instance methods follows the same organizational structure as the files in the functional API. The :class:`ivy.Container` class `inherits`_ from many category-specific array classes, such as `ContainerWithElementwise`_, each of which implements the category-specific instance methods. As with :class:`ivy.Array`, given the simple set of rules which underpin how these instance methods should all be implemented, if a source-code implementation is not found, then this `instance method is added`_ programmatically. This serves as a helpful backup in cases where some instance methods are accidentally missed out. Again, the benefit of the source code implementations is that this makes the code much more readable, with important methods not being entirely absent from the code. It also enables other helpful perks, such as auto-completions in the IDE etc. API Special Methods -------------------- All non-operator special methods are implemented in `ContainerBase`_, which is the abstract base class for all containers. These special methods include `__repr__`_ which controls how the container is printed in the terminal, `__getattr__`_ that primarily enables keys in the underlying :code:`dict` to be queried as attributes, whereas if no attribute, item or method is found which matches the name provided on the container itself, then the leaves will also be recursively traversed, searching for the attribute. If it turns out to be a callable function on the leaves, then it will call the function on each leaf and update the leaves with the returned results, for a more detailed explanation with examples, see the code block below. `__setattr__`_ that enables attribute setting to update the underlying :code:`dict`, `__getitem__`_ that enables the underlying :code:`dict` to be queried via a chain of keys, `__setitem__`_ that enables the underlying :code:`dict` to be set via a chain of keys, `__contains__`_ that enables us to check for chains of keys in the underlying :code:`dict`, and `__getstate__`_ and `__setstate__`_ which combined enable the container to be pickled and unpickled. .. code-block:: python x = ivy.Container(a=ivy.array([0.]), b=ivy.Container(a=ivy.array([[0.]]), b=ivy.array([1., 2., 3.]))) print(x.shape) { a: [ 1 ], b: { a: [ 1, 1 ], b: [ 3 ] } } print(x.ndim) { a: 1, b: { a: 2, b: 1 } } num_dims = x.shape.__len__() print(num_dims) { a: 1, b: { a: 2, b: 1 } } print(len(x.shape)) # doesn't work because Python in low-level C has a restriction on the return type of `len` to be `int` print(num_dims.real) { a: 1, b: { a: 2, b: 1 } } print(bin(num_dims)) # doesn't work because some Python built-in functions have enforcement on input argument types # external method flexibility enables positional and keyword arguments to be passed into the attribute y = ivy.Container(l1=[1, 2, 3], c1=ivy.Container(l1=[3, 2, 1], l2=[4, 5, 6])) print(y.__getattr__("count", 1)) { c1: { l1: 1, l2: 0 }, l1: 1 } print(y.count(1)) # doesn't work since essentially the argument 1 won't be passed to `__getattr__` print(y.__getattr__("__add__", [10])) { c1: { l1: [ 3, 2, 1, 10 ], l2: [ 4, 5, 6, 10 ] }, l1: [ 1, 2, 3, 10 ] } As for the special methods which are `implemented`_ in the main :class:`ivy.Container` class, they all make calls to the corresponding standard operator functions. As a result, the operator functions will make use of the special methods of the lefthand passed input objects if available, otherwise it will make use of the reverse special method of the righthand operand. For instance, if the lefthand operand at any given leaf of the container in an :class:`ivy.Array`, then the operator function will make calls to the special methods of this array object. As explained in the `Arrays <arrays.rst>`_ section of the Deep Dive, these special methods will in turn call the corresponding functions from the ivy functional API. Examples include `__add__`_, `__sub__`_, `__mul__`_ and `__truediv__`_ which will make calls to :func:`ivy.add`, :func:`ivy.subtract`, :func:`ivy.multiply` and :func:`ivy.divide` respectively if the lefthand operand is an :class:`ivy.Array` object. Otherwise, these special methods will be called on whatever objects are at the leaves of the container, such as int, float, :class:`ivy.NativeArray` etc. Nestable Functions ------------------ As introduced in the `Function Types <function_types.rst>`_ section, most functions in Ivy are *nestable*, which means that they can accept :class:`ivy.Container` instances in place of **any** of the arguments. Here, we expand on this explanation. Please check out the explanation in the `Function Types <function_types.rst>`_ section first. **Explicitly Nestable Functions** The *nestable* behaviour is added to any function which is decorated with the `handle_nestable <https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/ivy/func_wrapper.py#L429>`_ wrapper. This wrapper causes the function to be applied at each leaf of any containers passed in the input. More information on this can be found in the `Function Wrapping <https://github.com/unifyai/ivy/blob/b725ed10bca15f6f10a0e5154af10231ca842da2/docs/partial_source/deep_dive/function_wrapping.rst>`_ section of the Deep Dive. Additionally, any nestable function which returns multiple arrays, will return the same number of containers for its container counterpart. This property makes the function symmetric with regards to the input-output behavior, irrespective of whether :class:`ivy.Array` or :class:`ivy.Container` instances are used. Any argument in the input can be replaced with a container without changing the number of inputs, and the presence or absence of ivy.Container instances in the input should not change the number of return values of the function. In other words, if containers are detected in the input, then we should return a separate container for each array that the function would otherwise return. The current implementation checks if the leaves of the container have a list of arrays. If they do, this container is then unstacked to multiple containers(as many as the number of arrays), which are then returned inside a list. **Implicitly Nestable Functions** *Compositional* functions are composed of other nestable functions, and hence are already **implicitly nestable**. So, we do not need to explicitly wrap it at all. Let's take the function :func:`ivy.cross_entropy` as an example. The internally called functions are: :func:`ivy.clip`, :func:`ivy.log`, :func:`ivy.sum` and :func:`ivy.negative`, each of which are themselves *nestable*. .. code-block:: python def cross_entropy( true: Union[ivy.Array, ivy.NativeArray], pred: Union[ivy.Array, ivy.NativeArray], /, *, axis: Optional[int] = -1, epsilon: float =1e-7, out: Optional[ivy.Array] = None ) -> ivy.Array: pred = ivy.clip(pred, epsilon, 1 - epsilon) log_pred = ivy.log(pred) return ivy.negative(ivy.sum(log_pred * true, axis, out=out), out=out) Therefore, when passing an :class:`ivy.Container` instance in the input, each internal function will, in turn, correctly handle the container, and return a new container with the correct operations having been performed. This makes it very easy and intuitive to debug the code, as the code is stepped through chronologically. In effect, all leaves of the input container are being processed concurrently, during the computation steps of the :func:`ivy.cross_entropy` function. However, what if we had added the `handle_nestable <https://github.com/unifyai/ivy/blob/5f58c087906a797b5cb5603714d5e5a532fc4cd4/ivy/func_wrapper.py#L407>`_ wrapping as a decorator directly to the function :func:`ivy.cross_entropy`? In this case, the :func:`ivy.cross_entropy` function would itself be called multiple times, on each of the leaves of the container. The functions :func:`ivy.clip`, :func:`ivy.log`, :func:`ivy.sum` and :func:`ivy.negative` would each only consume and return arrays, and debugging the :func:`ivy.cross_entropy` function would then become less intuitively chronological, with each leaf of the input container now processed sequentially, rather than concurrently. Therefore, our approach is to **not** wrap any compositional functions which are already *implicitly nestable* as a result of the *nestable* functions called internally. **Explicitly Nestable Compositional Functions** There may be some compositional functions which are not implicitly nestable for some reason, and in such cases adding the explicit `handle_nestable <https://github.com/unifyai/ivy/blob/5f58c087906a797b5cb5603714d5e5a532fc4cd4/ivy/func_wrapper.py#L407>`_ wrapping may be necessary. One such example is the :func:`ivy.linear` function which is not implicitly nestable despite being compositional. This is because of the use of special functions like :func:`__len__` and :func:`__list__` which, among other functions, are not nestable and can't be made nestable. But we should try to avoid this, in order to make the flow of computation as intuitive to the user as possible. When tracing the code, the computation graph is **identical** in either case, and there will be no implications on performance whatsoever. The implicit nestable solution may be slightly less efficient in eager mode, as the leaves of the container are traversed multiple times rather than once, but if performance is of concern then the code should always be traced in any case. The distinction is only really relevant when stepping through and debugging with eager mode execution, and for the reasons outlined above, the preference is to keep compositional functions implicitly nestable where possible. **Shared Nested Structure** When the nested structures of the multiple containers are *shared* but not *identical*, then the behaviour of the nestable function is a bit different. Containers have *shared* nested structures if all unique leaves in any of the containers are children of a nested structure which is shared by all other containers. Take the example below, the nested structures of containers :code:`x` and :code:`y` are shared but not identical. .. code-block:: python x = ivy.Container(a={'b': 2, 'c': 4}, d={'e': 6, 'f': 9}) y = ivy.Container(a=2, d=3) The shared key chains (chains of keys, used for indexing the container) are :code:`a` and :code:`d`. The key chains unique to :code:`x` are :code:`a/b`, :code:`a/c`, :code:`d/e` and :code:`d/f`. The unique key chains all share the same base structure as all other containers (in this case only one other container, :code:`y`). Therefore, the containers :code:`x` and :code:`y` have a shared nested structure. When calling *nestable* functions on containers with non-identical structure, then the shared leaves of the shallowest container are broadcast to the leaves of the deepest container. It's helpful to look at an example: .. code-block:: python print(x / y) { a: { b: 1.0, c: 2.0 }, d: { e: 2.0, f: 3.0 } } In this case, the integer at :code:`y.a` is broadcast to the leaves :code:`x.a.b` and :code:`x.a.c`, and the integer at :code:`y.d` is broadcast to the leaves :code:`x.d.e` and :code:`x.d.f`. Another example of containers with shared nested structure is given below: .. code-block:: python x = ivy.Container(a={'b': 2, 'c': 4}, d={'e': 6, 'f': 8}) y = ivy.Container(a=2, d=3) z = ivy.Container(a={'b': 10, 'c': {'g': 11, 'h': 12}}, d={'e': 13, 'f': 14}) Adding these containers together would result in the following: .. code-block:: python print(x + y + z) { a: { b: 14, c: { g: 17, h: 18, } }, d: { e: 22, f: 25 } } An example of containers which **do not** have a shared nested structure is given below: .. code-block:: python x = ivy.Container(a={'b': 2, 'c': 4}, d={'e': 6, 'f': 8}) y = ivy.Container(a=2, d=3, g=4) z = ivy.Container(a={'b': 10, 'c': {'g': 11, 'h': 12}}, d={'e': 13, 'g': 14}) This is for three reasons, (a) the key chain :code:`g` is not shared by any container other than :code:`y`, (b) the key chain :code:`d/f` for :code:`x` is not present in :code:`z` despite :code:`d` not being a non-leaf node in :code:`z`, and likewise the key chain :code:`d/g` for :code:`z` is not present in :code:`x` despite :code:`d` not being a non-leaf node in :code:`x`. **Round Up** This should have hopefully given you a good feel for containers, and how these are handled in Ivy. If you have any questions, please feel free to reach out on `discord`_ in the `containers thread`_! **Video** .. raw:: html <iframe width="420" height="315" allow="fullscreen;" src="https://www.youtube.com/embed/oHcoYFi2rvI" class="video"> </iframe>
ivy/docs/overview/deep_dive/containers.rst/0
{ "file_path": "ivy/docs/overview/deep_dive/containers.rst", "repo_id": "ivy", "token_count": 7349 }
4
Ivy-Lint: Ivy's Custom Code Formatters ====================================== Overview -------- ``ivy-lint`` is a specialized suite of formatters crafted for the Ivy codebase. It addresses unique formatting requirements not catered to by standard Python formatters. While the suite currently highlights the ``FunctionOrderingFormatter``, we're continually expanding to include more formatters tailored to Ivy's needs. Existing Formatters ------------------- FunctionOrderingFormatter ~~~~~~~~~~~~~~~~~~~~~~~~~ This formatter ensures a standardized order of declarations within Python files, organizing functions, classes, and assignments based on a hierarchy designed for the Ivy codebase. **Purpose**: To bring a sense of uniformity and structure to the code files by sorting various Python declarations. **Target Files**: Specifically designed for frontends and tests. How the Formatter Works: ~~~~~~~~~~~~~~~~~~~~~~~~ 1. **Header Management**: - Removes pre-existing headers in the source code based on specific patterns. 2. **Comments Handling**: - Extracts code components along with their leading comments, ensuring that relevant comments are retained during the reordering process. 3. **Dependency Handling**: - Constructs dependency graphs to understand and maintain the relationships between classes and assignments. 4. **Sorting Logic**: - Prioritizes imports, followed by assignments based on certain dependencies, then classes, and finally functions. - Preserves module-level docstrings at the top of the file. - Organizes helper functions and primary functions into separate sections for clarity. 5. **File Processing**: - Processes files that align with certain patterns, rearranging their content as needed. Integration and Usage --------------------- To get the best out of ``ivy-lint``, integrate it within a pre-commit hook. This ensures that whenever code changes are about to be committed, the suite checks and, if needed, formats the files to align with Ivy's standards. For comprehensive details on weaving ``ivy-lint`` into your development practices, kindly refer to our `formatting guide <formatting.rst>`_. Contribution ------------ We’re always thrilled to welcome contributions to ``ivy-lint``. If you're brimming with ideas for a new formatter or can enhance our existing ones, please connect with us either on our GitHub repository or our `discord <https://discord.gg/Y3prZYHS>`_ channel. Round Up -------- ``ivy-lint`` stands as a testament to Ivy's commitment to code clarity and uniformity. As the landscape of our needs shifts, we foresee further refining and expanding our suite of formatters. For all discussions or inquiries, you're always welcome on `discord <https://discord.gg/Y3prZYHS>`_ in the `formatting thread <https://discord.com/channels/799879767196958751/1190247322626572408>`_.
ivy/docs/overview/deep_dive/ivy_lint.rst/0
{ "file_path": "ivy/docs/overview/deep_dive/ivy_lint.rst", "repo_id": "ivy", "token_count": 681 }
5
Motivation ========== | (a) `ML Explosion <motivation/ml_explosion.rst>`_ | A huge number of ML tools have exploded onto the scene! | | (b) `Why Unify? <motivation/why_unify.rst>`_ | Why should we try to unify them? | | (c) `Standardization <motivation/standardization.rst>`_ | We’re collaborating with The `Consortium for Python Data API Standards <https://data-apis.org>`_ .. toctree:: :hidden: :maxdepth: -1 :caption: Background motivation/ml_explosion.rst motivation/why_unify.rst motivation/standardization.rst
ivy/docs/overview/motivation.rst/0
{ "file_path": "ivy/docs/overview/motivation.rst", "repo_id": "ivy", "token_count": 195 }
6
.. _`RWorks Vendor-Specific APIs`: Vendor-Specific APIs ==================== .. _`CUDA`: https://developer.nvidia.com/cuda-toolkit .. _`TensorRT`: https://developer.nvidia.com/tensorrt .. _`NVIDIA`: https://www.nvidia.com/ .. _`PyTorch`: https://pytorch.org/ .. _`TensorFlow`: https://www.tensorflow.org/ .. _`Compute Unified Device Architecture (CUDA)`: https://developer.nvidia.com/cuda-toolkit .. _`discord`: https://discord.gg/sXyFF8tDtm .. |tensorrt| image:: https://raw.githubusercontent.com/unifyai/unifyai.github.io/main/img/externally_linked/related_work/vendor_specific_apis/tensorrt.png :height: 15pt :class: dark-light .. |cuda| image:: https://raw.githubusercontent.com/unifyai/unifyai.github.io/main/img/externally_linked/related_work/vendor_specific_apis/cuda.png :height: 20pt :class: dark-light Vendor-specific APIs provide an interface to define customized operations for hardware from specific vendors. The libraries are written exclusively for hardware from this vendor, and so the code is clearly not generalized nor is it intended to be. These APIs are often used by higher level multi-vendor compilers and frameworks, and most machine learning practitioners will not interface with these low level vendor-specific APIs directly. TensorRT |tensorrt| ------------------- Built on top of `CUDA`_, `TensorRT`_ is a C++ library for high performance inference on `NVIDIA`_ GPUs and deep learning accelerators. It is integrated with `PyTorch`_ and TensorFlow. When conducting deep learning training in a proprietary or custom framework, then the TensorRT C++ API can be used to import and accelerate models. Several optimizations contribute to the high performance: reduced mixed precision maximizes throughput, layer and tensor fusion optimizes device memory, kernel autotuning selects the best data layers and algorithms, time fusion optimizes recurrent neural networks, multi-stream execution manages input streams, and dynamic tensor memory optimizes memory consumption. CUDA |cuda| ----------- `Compute Unified Device Architecture (CUDA)`_ is a parallel computing platform and application programming interface (API) that allows software to use certain types of graphics processing units (GPUs) for general purpose processing, an approach called general-purpose computing on GPUs (GPGPU). It is a software layer that gives direct access to the GPU's virtual instruction set and parallel computational elements, for the execution of compute kernels. It is designed to work with programming languages such as C, C++, and Fortran.
ivy/docs/overview/related_work/vendor_specific_apis.rst/0
{ "file_path": "ivy/docs/overview/related_work/vendor_specific_apis.rst", "repo_id": "ivy", "token_count": 684 }
7
# flake8: noqa # global import copy import functools import numpy as np from operator import mul from typing import Optional # local import ivy from .conversions import args_to_native, to_ivy from .activations import _ArrayWithActivations from .creation import _ArrayWithCreation from .data_type import _ArrayWithDataTypes from .device import _ArrayWithDevice from .elementwise import _ArrayWithElementwise from .general import _ArrayWithGeneral from .gradients import _ArrayWithGradients from .image import _ArrayWithImage from .layers import _ArrayWithLayers from .linear_algebra import _ArrayWithLinearAlgebra from .losses import _ArrayWithLosses from .manipulation import _ArrayWithManipulation from .norms import _ArrayWithNorms from .random import _ArrayWithRandom from .searching import _ArrayWithSearching from .set import _ArrayWithSet from .sorting import _ArrayWithSorting from .statistical import _ArrayWithStatistical from .utility import _ArrayWithUtility from ivy.func_wrapper import handle_view_indexing from .experimental import ( _ArrayWithSearchingExperimental, _ArrayWithActivationsExperimental, _ArrayWithConversionsExperimental, _ArrayWithCreationExperimental, _ArrayWithData_typeExperimental, _ArrayWithDeviceExperimental, _ArrayWithElementWiseExperimental, _ArrayWithGeneralExperimental, _ArrayWithGradientsExperimental, _ArrayWithImageExperimental, _ArrayWithLayersExperimental, _ArrayWithLinearAlgebraExperimental, _ArrayWithLossesExperimental, _ArrayWithManipulationExperimental, _ArrayWithNormsExperimental, _ArrayWithRandomExperimental, _ArrayWithSetExperimental, _ArrayWithSortingExperimental, _ArrayWithStatisticalExperimental, _ArrayWithUtilityExperimental, ) class Array( _ArrayWithActivations, _ArrayWithCreation, _ArrayWithDataTypes, _ArrayWithDevice, _ArrayWithElementwise, _ArrayWithGeneral, _ArrayWithGradients, _ArrayWithImage, _ArrayWithLayers, _ArrayWithLinearAlgebra, _ArrayWithLosses, _ArrayWithManipulation, _ArrayWithNorms, _ArrayWithRandom, _ArrayWithSearching, _ArrayWithSet, _ArrayWithSorting, _ArrayWithStatistical, _ArrayWithUtility, _ArrayWithActivationsExperimental, _ArrayWithConversionsExperimental, _ArrayWithCreationExperimental, _ArrayWithData_typeExperimental, _ArrayWithDeviceExperimental, _ArrayWithElementWiseExperimental, _ArrayWithGeneralExperimental, _ArrayWithGradientsExperimental, _ArrayWithImageExperimental, _ArrayWithLayersExperimental, _ArrayWithLinearAlgebraExperimental, _ArrayWithLossesExperimental, _ArrayWithManipulationExperimental, _ArrayWithNormsExperimental, _ArrayWithRandomExperimental, _ArrayWithSearchingExperimental, _ArrayWithSetExperimental, _ArrayWithSortingExperimental, _ArrayWithStatisticalExperimental, _ArrayWithUtilityExperimental, ): def __init__(self, data, dynamic_backend=None): _ArrayWithActivations.__init__(self) _ArrayWithCreation.__init__(self) _ArrayWithDataTypes.__init__(self) _ArrayWithDevice.__init__(self) _ArrayWithElementwise.__init__(self) _ArrayWithGeneral.__init__(self) _ArrayWithGradients.__init__(self) _ArrayWithImage.__init__(self) _ArrayWithLayers.__init__(self) _ArrayWithLinearAlgebra.__init__(self) _ArrayWithLosses.__init__(self) _ArrayWithManipulation.__init__(self) _ArrayWithNorms.__init__(self) _ArrayWithRandom.__init__(self) _ArrayWithSearching.__init__(self) _ArrayWithSet.__init__(self) _ArrayWithSorting.__init__(self) _ArrayWithStatistical.__init__(self) _ArrayWithUtility.__init__(self) _ArrayWithActivationsExperimental.__init__(self), _ArrayWithConversionsExperimental.__init__(self), _ArrayWithCreationExperimental.__init__(self), _ArrayWithData_typeExperimental.__init__(self), _ArrayWithDeviceExperimental.__init__(self), _ArrayWithElementWiseExperimental.__init__(self), _ArrayWithGeneralExperimental.__init__(self), _ArrayWithGradientsExperimental.__init__(self), _ArrayWithImageExperimental.__init__(self), _ArrayWithLayersExperimental.__init__(self), _ArrayWithLinearAlgebraExperimental.__init__(self), _ArrayWithLossesExperimental.__init__(self), _ArrayWithManipulationExperimental.__init__(self), _ArrayWithNormsExperimental.__init__(self), _ArrayWithRandomExperimental.__init__(self), _ArrayWithSearchingExperimental.__init__(self), _ArrayWithSetExperimental.__init__(self), _ArrayWithSortingExperimental.__init__(self), _ArrayWithStatisticalExperimental.__init__(self), _ArrayWithUtilityExperimental.__init__(self), self._init(data, dynamic_backend) self._view_attributes(data) def _init(self, data, dynamic_backend=None): if ivy.is_ivy_array(data): self._data = data.data elif ivy.is_native_array(data): self._data = data elif isinstance(data, np.ndarray): self._data = ivy.asarray(data)._data elif isinstance(data, (list, tuple)): self._data = ivy.asarray(data)._data elif ivy.is_ivy_sparse_array(data): self._data = data._data elif ivy.is_native_sparse_array(data): self._data = data._data else: raise ivy.utils.exceptions.IvyException( "data must be ivy array, native array or ndarray" ) self._size = None self._strides = None self._itemsize = None self._dtype = None self._device = None self._dev_str = None self._pre_repr = None self._post_repr = None self._backend = ivy.current_backend(self._data).backend if dynamic_backend is not None: self._dynamic_backend = dynamic_backend else: self._dynamic_backend = ivy.dynamic_backend self.weak_type = False # to handle 0-D jax front weak typed arrays def _view_attributes(self, data): self._base = None self._view_refs = [] self._manipulation_stack = [] self._torch_base = None self._torch_view_refs = [] self._torch_manipulation = None # Properties # # ---------- # @property def backend(self): return self._backend @property def dynamic_backend(self): return self._dynamic_backend @dynamic_backend.setter def dynamic_backend(self, value): from ivy.functional.ivy.gradients import _variable from ivy.utils.backend.handler import _data_to_new_backend, _get_backend_for_arg if value: ivy_backend = ivy.with_backend(self._backend) if ivy_backend.gradients._is_variable(self.data): native_var = ivy_backend.gradients._variable_data( self, ) data = _data_to_new_backend(native_var, ivy_backend).data self._data = _variable(data).data else: self._data = _data_to_new_backend(self, ivy_backend).data self._backend = ivy.backend else: self._backend = _get_backend_for_arg(self.data.__class__.__module__).backend self._dynamic_backend = value @property def data(self) -> ivy.NativeArray: """The native array being wrapped in self.""" return self._data @property def dtype(self) -> ivy.Dtype: """Data type of the array elements.""" if self._dtype is None: self._dtype = ivy.dtype(self._data) return self._dtype @property def device(self) -> ivy.Device: """Hardware device the array data resides on.""" if self._device is None: self._device = ivy.dev(self._data) return self._device @property def mT(self) -> ivy.Array: """Transpose of a matrix (or a stack of matrices). Returns ------- ret array whose last two dimensions (axes) are permuted in reverse order relative to original array (i.e., for an array instance having shape ``(..., M, N)``, the returned array must have shape ``(..., N, M)``). The returned array must have the same data type as the original array. """ ivy.utils.assertions.check_greater( len(self._data.shape), 2, allow_equal=True, as_array=False ) return ivy.matrix_transpose(self._data) @property def ndim(self) -> int: """Number of array dimensions (axes).""" return len(tuple(self._data.shape)) @property def shape(self) -> ivy.Shape: """Array dimensions.""" return ivy.Shape(self._data.shape) @property def size(self) -> Optional[int]: """Number of elements in the array.""" if self._size is None: if ivy.current_backend_str() in ["numpy", "jax"]: self._size = self._data.size return self._size self._size = ( functools.reduce(mul, self._data.shape) if len(self._data.shape) > 0 else 1 ) return self._size @property def itemsize(self) -> Optional[int]: """Size of array elements in bytes.""" if self._itemsize is None: self._itemsize = ivy.itemsize(self._data) return self._itemsize @property def strides(self) -> Optional[int]: """Get strides across each dimension.""" if self._strides is None: # for this to work consistently for non-contiguous arrays # we must pass self to ivy.strides, not self.data self._strides = ivy.strides(self) return self._strides @property def T(self) -> ivy.Array: """Transpose of the array. Returns ------- ret two-dimensional array whose first and last dimensions (axes) are permuted in reverse order relative to original array. """ ivy.utils.assertions.check_equal(len(self._data.shape), 2, as_array=False) return ivy.matrix_transpose(self._data) @property def base(self) -> ivy.Array: """Original array referenced by view.""" return self._base @property def real(self) -> ivy.Array: """Real part of the array. Returns ------- ret array containing the real part of each element in the array. The returned array must have the same shape and data type as the original array. """ return ivy.real(self._data) @property def imag(self) -> ivy.Array: """Imaginary part of the array. Returns ------- ret array containing the imaginary part of each element in the array. The returned array must have the same shape and data type as the original array. """ return ivy.imag(self._data) # Setters # # --------# @data.setter def data(self, data): ivy.utils.assertions.check_true( ivy.is_native_array(data), "data must be native array" ) self._init(data) # Built-ins # # ----------# @classmethod def __torch_function__(cls, func, types, args=(), kwargs={}): args, kwargs = args_to_native(*args, **kwargs) return func(*args, **kwargs) def __ivy_array_function__(self, func, types, args, kwargs): # Cannot handle items that have __ivy_array_function__ other than those of # ivy arrays or native arrays. for t in types: if ( hasattr(t, "__ivy_array_function__") and (t.__ivy_array_function__ is not ivy.Array.__ivy_array_function__) or ( hasattr(ivy.NativeArray, "__ivy_array_function__") and ( t.__ivy_array_function__ is not ivy.NativeArray.__ivy_array_function__ ) ) ): return NotImplemented # Arguments contain no overrides, so we can safely call the # overloaded function again. return func(*args, **kwargs) def __array__(self, *args, **kwargs): args, kwargs = args_to_native(*args, **kwargs) return self._data.__array__(*args, dtype=self.dtype, **kwargs) def __array_prepare__(self, *args, **kwargs): args, kwargs = args_to_native(*args, **kwargs) return self._data.__array_prepare__(*args, **kwargs) def __array_ufunc__(self, *args, **kwargs): args, kwargs = args_to_native(*args, **kwargs) return self._data.__array_ufunc__(*args, **kwargs) def __array_wrap__(self, *args, **kwargs): args, kwargs = args_to_native(*args, **kwargs) return self._data.__array_wrap__(*args, **kwargs) def __array_namespace__(self, api_version=None): return ivy def __repr__(self): if self._dev_str is None: self._dev_str = ivy.as_ivy_dev(self.device) self._pre_repr = "ivy.array" if "gpu" in self._dev_str: self._post_repr = f", dev={self._dev_str})" else: self._post_repr = ")" sig_fig = ivy.array_significant_figures dec_vals = ivy.array_decimal_values if self.backend == "" or ivy.is_local(): # If the array was constructed using implicit backend backend = ivy.current_backend() else: # Requirerd in the case that backend is different # from the currently set backend backend = ivy.with_backend(self.backend) arr_np = backend.to_numpy(self._data) rep = ( np.array(ivy.vec_sig_fig(arr_np, sig_fig)) if self.size > 0 else np.array(arr_np) ) with np.printoptions(precision=dec_vals): repr = rep.__repr__()[:-1].partition(", dtype")[0].partition(", dev")[0] return ( self._pre_repr + repr[repr.find("(") :] + self._post_repr.format(ivy.current_backend_str()) ) def __dir__(self): return self._data.__dir__() def __getattribute__(self, item): return super().__getattribute__(item) def __getattr__(self, item): try: attr = self._data.__getattribute__(item) except AttributeError: attr = self._data.__getattr__(item) return to_ivy(attr) @handle_view_indexing def __getitem__(self, query): return ivy.get_item(self._data, query) def __setitem__(self, query, val): self._data = ivy.set_item(self._data, query, val)._data def __contains__(self, key): return self._data.__contains__(key) def __getstate__(self): data_dict = {} # only pickle the native array data_dict["data"] = self.data # also store the local ivy framework that created this array data_dict["backend"] = self.backend data_dict["device_str"] = ivy.as_ivy_dev(self.device) return data_dict def __setstate__(self, state): # we can construct other details of ivy.Array # just by re-creating the ivy.Array using the native array # get the required backend ( ivy.set_backend(state["backend"]) if state["backend"] is not None and len(state["backend"]) > 0 else ivy.current_backend(state["data"]) ) ivy_array = ivy.array(state["data"]) ivy.previous_backend() self.__dict__ = ivy_array.__dict__ # TODO: what about placement of the array on the right device ? # device = backend.as_native_dev(state["device_str"]) # backend.to_device(self, device) def __pos__(self): return ivy.positive(self._data) def __neg__(self): return ivy.negative(self._data) def __pow__(self, power): """ivy.Array special method variant of ivy.pow. This method simply wraps the function, and so the docstring for ivy.pow also applies to this method with minimal changes. Parameters ---------- self Input array or float. power Array or float power. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- ret an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. Examples -------- With :class:`ivy.Array` input: >>> x = ivy.array([1, 2, 3]) >>> y = x ** 2 >>> print(y) ivy.array([1, 4, 9]) >>> x = ivy.array([1.2, 2.1, 3.5]) >>> y = x ** 2.9 >>> print(y) ivy.array([ 1.69678056, 8.59876156, 37.82660675]) """ return ivy.pow(self._data, power) def __rpow__(self, power): return ivy.pow(power, self._data) def __ipow__(self, power): return ivy.pow(self._data, power) def __add__(self, other): """ivy.Array special method variant of ivy.add. This method simply wraps the function, and so the docstring for ivy.add also applies to this method with minimal changes. Parameters ---------- self first input array. Should have a numeric data type. other second input array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- ret an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. Examples -------- >>> x = ivy.array([1, 2, 3]) >>> y = ivy.array([4, 5, 6]) >>> z = x + y >>> print(z) ivy.array([5, 7, 9]) """ return ivy.add(self._data, other) def __radd__(self, other): """ivy.Array reverse special method variant of ivy.add. This method simply wraps the function, and so the docstring for ivy.add also applies to this method with minimal changes. Parameters ---------- self first input array. Should have a numeric data type. other second input array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- ret an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. Examples -------- >>> x = 1 >>> y = ivy.array([4, 5, 6]) >>> z = x + y >>> print(z) ivy.array([5, 6, 7]) """ return ivy.add(other, self._data) def __iadd__(self, other): return ivy.add(self._data, other) def __sub__(self, other): """ivy.Array special method variant of ivy.subtract. This method simply wraps the function, and so the docstring for ivy.subtract also applies to this method with minimal changes. Parameters ---------- self first input array. Should have a numeric data type. other second input array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- ret an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. Examples -------- With :class:`ivy.Array` instances only: >>> x = ivy.array([1, 2, 3]) >>> y = ivy.array([4, 5, 6]) >>> z = x - y >>> print(z) ivy.array([-3, -3, -3]) """ return ivy.subtract(self._data, other) def __rsub__(self, other): """ivy.Array reverse special method variant of ivy.subtract. This method simply wraps the function, and so the docstring for ivy.subtract also applies to this method with minimal changes. Parameters ---------- self first input array. Should have a numeric data type. other second input array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- ret an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. Examples -------- >>> x = 1 >>> y = ivy.array([4, 5, 6]) >>> z = x - y >>> print(z) ivy.array([-3, -4, -5]) """ return ivy.subtract(other, self._data) def __isub__(self, other): return ivy.subtract(self._data, other) def __mul__(self, other): return ivy.multiply(self._data, other) def __rmul__(self, other): return ivy.multiply(other, self._data) def __imul__(self, other): return ivy.multiply(self._data, other) def __mod__(self, other): return ivy.remainder(self._data, other) def __rmod__(self, other): return ivy.remainder(other, self._data) def __imod__(self, other): return ivy.remainder(self._data, other) def __divmod__(self, other): return ivy.divide(self._data, other), ivy.remainder(self._data, other) def __rdivmod__(self, other): return ivy.divide(other, self._data), ivy.remainder(other, self._data) def __truediv__(self, other): """ivy.Array reverse special method variant of ivy.divide. This method simply wraps the function, and so the docstring for ivy.divide also applies to this method with minimal changes. Parameters ---------- self first input array. Should have a numeric data type. other second input array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- ret an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Examples -------- >>> x = ivy.array([1, 2, 3]) >>> y = ivy.array([4, 5, 6]) >>> z = x / y >>> print(z) ivy.array([0.25 , 0.40000001, 0.5 ]) """ return ivy.divide(self._data, other) def __rtruediv__(self, other): return ivy.divide(other, self._data) def __itruediv__(self, other): return ivy.divide(self._data, other) def __floordiv__(self, other): return ivy.floor_divide(self._data, other) def __rfloordiv__(self, other): return ivy.floor_divide(other, self._data) def __ifloordiv__(self, other): return ivy.floor_divide(self._data, other) def __matmul__(self, other): return ivy.matmul(self._data, other) def __rmatmul__(self, other): return ivy.matmul(other, self._data) def __imatmul__(self, other): return ivy.matmul(self._data, other) def __abs__(self): """ivy.Array special method variant of ivy.abs. This method simply wraps the function, and so the docstring for ivy.abs also applies to this method with minimal changes. Parameters ---------- self input array. Should have a numeric data type. Returns ------- ret an array containing the absolute value of each element in ``self``. The returned array must have the same data type as ``self``. Examples -------- With :class:`ivy.Array` input: >>> x = ivy.array([6, -2, 0, -1]) >>> print(abs(x)) ivy.array([6, 2, 0, 1]) >>> x = ivy.array([-1.2, 1.2]) >>> print(abs(x)) ivy.array([1.2, 1.2]) """ return ivy.abs(self._data) def __float__(self): if hasattr(self._data, "__float__"): if "complex" in self.dtype: res = float(self.real) else: res = self._data.__float__() else: res = float(ivy.to_scalar(self._data)) if res is NotImplemented: return res return to_ivy(res) def __int__(self): if hasattr(self._data, "__int__"): if "complex" in self.dtype: res = int(self.real) else: res = self._data.__int__() else: res = int(ivy.to_scalar(self._data)) if res is NotImplemented: return res return to_ivy(res) def __complex__(self): res = complex(ivy.to_scalar(self._data)) if res is NotImplemented: return res return to_ivy(res) def __bool__(self): return self._data.__bool__() def __dlpack__(self, stream=None): # Not completely supported yet as paddle and tf # doesn't support __dlpack__ and __dlpack_device__ dunders right now # created issues # paddle https://github.com/PaddlePaddle/Paddle/issues/56891 # tf https://github.com/tensorflow/tensorflow/issues/61769 return ivy.to_dlpack(self) def __dlpack_device__(self): return self._data.__dlpack_device__() def __lt__(self, other): """ivy.Array special method variant of ivy.less. This method simply wraps the function, and so the docstring for ivy.less also applies to this method with minimal changes. Parameters ---------- self first input array. May have any data type. other second input array. Must be compatible with x1 (with Broadcasting). May have any data type. Returns ------- ret an array containing the element-wise results. The returned array must have a data type of bool. Examples -------- >>> x = ivy.array([6, 2, 3]) >>> y = ivy.array([4, 5, 3]) >>> z = x < y >>> print(z) ivy.array([ False, True, False]) """ return ivy.less(self._data, other) def __le__(self, other): """ivy.Array special method variant of ivy.less_equal. This method simply wraps the function, and so the docstring for ivy.less_equal also applies to this method with minimal changes. Parameters ---------- self first input array. May have any data type. other second input array. Must be compatible with x1 (with Broadcasting). May have any data type. Returns ------- ret an array containing the element-wise results. The returned array must have a data type of bool. Examples -------- >>> x = ivy.array([6, 2, 3]) >>> y = ivy.array([4, 5, 3]) >>> z = x <= y >>> print(z) ivy.array([ False, True, True]) """ return ivy.less_equal(self._data, other) def __eq__(self, other): """ivy.Array special method variant of ivy.equal. This method simply wraps the function, and so the docstring for ivy.equal also applies to this method with minimal changes. Parameters ---------- self first input array. May have any data type. other second input array. Must be compatible with x1 (with Broadcasting). May have any data type. Returns ------- ret an array containing the element-wise results. The returned array must have a data type of bool. Examples -------- With :class:`ivy.Array` instances: >>> x1 = ivy.array([1, 0, 1, 1]) >>> x2 = ivy.array([1, 0, 0, -1]) >>> y = x1 == x2 >>> print(y) ivy.array([True, True, False, False]) >>> x1 = ivy.array([1, 0, 1, 0]) >>> x2 = ivy.array([0, 1, 0, 1]) >>> y = x1 == x2 >>> print(y) ivy.array([False, False, False, False]) """ return ivy.equal(self._data, other) def __ne__(self, other): """ivy.Array special method variant of ivy.not_equal. This method simply wraps the function, and so the docstring for ivy.not_equal also applies to this method with minimal changes. Parameters ---------- self first input array. May have any data type. other second input array. Must be compatible with x1 (with Broadcasting). May have any data type. Returns ------- ret an array containing the element-wise results. The returned array must have a data type of bool. Examples -------- With :class:`ivy.Array` instances: >>> x1 = ivy.array([1, 0, 1, 1]) >>> x2 = ivy.array([1, 0, 0, -1]) >>> y = x1 != x2 >>> print(y) ivy.array([False, False, True, True]) >>> x1 = ivy.array([1, 0, 1, 0]) >>> x2 = ivy.array([0, 1, 0, 1]) >>> y = x1 != x2 >>> print(y) ivy.array([True, True, True, True]) """ return ivy.not_equal(self._data, other) def __gt__(self, other): """ivy.Array special method variant of ivy.greater. This method simply wraps the function, and so the docstring for ivy.greater also applies to this method with minimal changes. Parameters ---------- self first input array. May have any data type. other second input array. Must be compatible with x1 (with Broadcasting). May have any data type. Returns ------- ret an array containing the element-wise results. The returned array must have a data type of bool. Examples -------- With :class:`ivy.Array` instances: >>> x = ivy.array([6, 2, 3]) >>> y = ivy.array([4, 5, 3]) >>> z = x > y >>> print(z) ivy.array([True,False,False]) With mix of :class:`ivy.Array` and :class:`ivy.Container` instances: >>> x = ivy.array([[5.1, 2.3, -3.6]]) >>> y = ivy.Container(a=ivy.array([[4.], [5.1], [6.]]),b=ivy.array([[-3.6], [6.], [7.]])) >>> z = x > y >>> print(z) { a: ivy.array([[True, False, False], [False, False, False], [False, False, False]]), b: ivy.array([[True, True, False], [False, False, False], [False, False, False]]) } """ return ivy.greater(self._data, other) def __ge__(self, other): """ivy.Array special method variant of ivy.greater_equal. This method simply wraps the function, and so the docstring for ivy.bitwise_xor also applies to this method with minimal changes. Parameters ---------- self first input array. May have any data type. other second input array. Must be compatible with x1 (with Broadcasting). May have any data type. Returns ------- ret an array containing the element-wise results. The returned array must have a data type of bool. Examples -------- With :class:`ivy.Array` instances: >>> x = ivy.array([6, 2, 3]) >>> y = ivy.array([4, 5, 6]) >>> z = x >= y >>> print(z) ivy.array([True,False,False]) With mix of :class:`ivy.Array` and :class:`ivy.Container` instances: >>> x = ivy.array([[5.1, 2.3, -3.6]]) >>> y = ivy.Container(a=ivy.array([[4.], [5.1], [6.]]),b=ivy.array([[5.], [6.], [7.]])) >>> z = x >= y >>> print(z) { a: ivy.array([[True, False, False], [True, False, False], [False, False, False]]), b: ivy.array([[True, False, False], [False, False, False], [False, False, False]]) } """ return ivy.greater_equal(self._data, other) def __and__(self, other): return ivy.bitwise_and(self._data, other) def __rand__(self, other): return ivy.bitwise_and(other, self._data) def __iand__(self, other): return ivy.bitwise_and(self._data, other) def __or__(self, other): return ivy.bitwise_or(self._data, other) def __ror__(self, other): return ivy.bitwise_or(other, self._data) def __ior__(self, other): return ivy.bitwise_or(self._data, other) def __invert__(self): return ivy.bitwise_invert(self._data) def __xor__(self, other): """ivy.Array special method variant of ivy.bitwise_xor. This method simply wraps the function, and so the docstring for ivy.bitwise_xor also applies to this method with minimal changes. Parameters ---------- self first input array. Should have an integer or boolean data type. other second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. out optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Examples -------- With :class:`ivy.Array` instances: >>> a = ivy.array([1, 2, 3]) >>> b = ivy.array([3, 2, 1]) >>> y = a ^ b >>> print(y) ivy.array([2,0,2]) With mix of :class:`ivy.Array` and :class:`ivy.Container` instances: >>> x = ivy.Container(a = ivy.array([-67, 21])) >>> y = ivy.array([12, 13]) >>> z = x ^ y >>> print(z) {a: ivy.array([-79, 24])} """ return ivy.bitwise_xor(self._data, other) def __rxor__(self, other): return ivy.bitwise_xor(other, self._data) def __ixor__(self, other): return ivy.bitwise_xor(self._data, other) def __lshift__(self, other): return ivy.bitwise_left_shift(self._data, other) def __rlshift__(self, other): return ivy.bitwise_left_shift(other, self._data) def __ilshift__(self, other): return ivy.bitwise_left_shift(self._data, other) def __rshift__(self, other): """ivy.Array special method variant of ivy.bitwise_right_shift. This method simply wraps the function, and so the docstring for ivy.bitwise_right_shift also applies to this method with minimal changes. Parameters ---------- self first input array. Should have an integer data type. other second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- ret an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Examples -------- With :class:`ivy.Array` instances only: >>> a = ivy.array([2, 3, 4]) >>> b = ivy.array([0, 1, 2]) >>> y = a >> b >>> print(y) ivy.array([2, 1, 1]) """ return ivy.bitwise_right_shift(self._data, other) def __rrshift__(self, other): """ivy.Array reverse special method variant of ivy.bitwise_right_shift. This method simply wraps the function, and so the docstring for ivy.bitwise_right_shift also applies to this method with minimal changes. Parameters ---------- self first input array. Should have an integer data type. other second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- ret an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Examples -------- >>> a = 32 >>> b = ivy.array([0, 1, 2]) >>> y = a >> b >>> print(y) ivy.array([32, 16, 8]) """ return ivy.bitwise_right_shift(other, self._data) def __irshift__(self, other): return ivy.bitwise_right_shift(self._data, other) def __deepcopy__(self, memodict={}): try: return to_ivy(self._data.__deepcopy__(memodict)) except AttributeError: # ToDo: try and find more elegant solution to jax inability to # deepcopy device arrays if ivy.current_backend_str() == "jax": np_array = copy.deepcopy(self._data) jax_array = ivy.array(np_array) return to_ivy(jax_array) return to_ivy(copy.deepcopy(self._data)) except RuntimeError: from ivy.functional.ivy.gradients import _is_variable # paddle and torch don't support the deepcopy protocol on non-leaf tensors if _is_variable(self): return to_ivy(copy.deepcopy(ivy.stop_gradient(self)._data)) return to_ivy(copy.deepcopy(self._data)) def __len__(self): if not len(self._data.shape): return 0 try: return len(self._data) except TypeError: return self._data.shape[0] def __iter__(self): if self.ndim == 0: raise TypeError("iteration over a 0-d ivy.Array not supported") if ivy.current_backend_str() == "paddle": if self.dtype in ["int8", "int16", "uint8", "float16"]: return iter([to_ivy(i) for i in ivy.unstack(self._data)]) elif self.ndim == 1: return iter([to_ivy(i).squeeze(axis=0) for i in self._data]) return iter([to_ivy(i) for i in self._data])
ivy/ivy/data_classes/array/array.py/0
{ "file_path": "ivy/ivy/data_classes/array/array.py", "repo_id": "ivy", "token_count": 17731 }
8
# global import abc from typing import Optional, Union, Tuple, List, Literal, Sequence, Callable # local import ivy class _ArrayWithLayersExperimental(abc.ABC): def max_pool1d( self: ivy.Array, kernel: Union[int, Tuple[int, ...]], strides: Union[int, Tuple[int, ...]], padding: Union[str, int, Tuple[int], List[Tuple[int, int]]], /, *, data_format: str = "NWC", dilation: Union[int, Tuple[int]] = 1, ceil_mode: bool = False, out: Optional[ivy.Array] = None, ) -> ivy.Array: """ivy.Array instance method variant of `ivy.max_pool1d`. This method simply wraps the function, and so the docstring for `ivy.max_pool1d` also applies to this method with minimal changes. Parameters ---------- self Input image *[batch_size,w,d_in]*. kernel The size of the window for each dimension of the input tensor. strides The stride of the sliding window for each dimension of input. padding "SAME" or "VALID" indicating the algorithm, or list indicating the per-dimension paddings. data_format "NWC" or "NCW". Defaults to "NWC". dilaton The stride between elements within a sliding window, must be > 0. ceil_mode If True, ceil is used instead of floor to compute the output shape. This ensures that every element is covered by a sliding window. out optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The result of the max pooling operation. Examples -------- >>> x = ivy.arange(0, 24.).reshape((2, 3, 4)) >>> print(x.max_pool1d(2, 2, 'SAME')) ivy.array([[[ 4., 5., 6., 7.], [ 8., 9., 10., 11.]], [[16., 17., 18., 19.], [20., 21., 22., 23.]]]) >>> x = ivy.arange(0, 24.).reshape((2, 3, 4)) >>> print(x.max_pool1d(2, 2, 'VALID')) ivy.array([[[ 4., 5., 6., 7.]], [[16., 17., 18., 19.]]]) """ return ivy.max_pool1d( self, kernel, strides, padding, data_format=data_format, dilation=dilation, ceil_mode=ceil_mode, out=out, ) def max_pool2d( self: ivy.Array, kernel: Union[int, Tuple[int, ...]], strides: Union[int, Tuple[int, ...]], padding: Union[str, int, Tuple[int], List[Tuple[int, int]]], /, *, data_format: str = "NHWC", dilation: Union[int, Tuple[int, ...]] = 1, ceil_mode: bool = False, out: Optional[ivy.Array] = None, ) -> ivy.Array: """ivy.Array instance method variant of `ivy.max_pool2d`. This method simply wraps the function, and so the docstring for `ivy.max_pool2d` also applies to this method with minimal changes. Parameters ---------- self Input image *[batch_size,h,w,d_in]*. kernel The size of the window for each dimension of the input tensor. strides The stride of the sliding window for each dimension of input. padding "SAME" or "VALID" indicating the algorithm, or list indicating the per-dimension paddings. data_format "NHWC" or "NCHW". Defaults to "NHWC". dilaton The stride between elements within a sliding window, must be > 0. ceil_mode If True, ceil is used instead of floor to compute the output shape. This ensures that every element is covered by a sliding window. out optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The result of the max pooling operation. Examples -------- >>> x = ivy.arange(12.).reshape((2, 1, 3, 2)) >>> print(x.max_pool2d((2, 2), (1, 1), 'SAME')) ivy.array([[[[ 2., 3.], [ 4., 5.], [ 4., 5.]]], [[[ 8., 9.], [10., 11.], [10., 11.]]]]) >>> x = ivy.arange(48.).reshape((2, 4, 3, 2)) >>> print(x.max_pool2d(3, 1, 'VALID')) ivy.array([[[[16., 17.]], [[22., 23.]]], [[[40., 41.]], [[46., 47.]]]]) """ return ivy.max_pool2d( self, kernel, strides, padding, data_format=data_format, dilation=dilation, ceil_mode=ceil_mode, out=out, ) def max_pool3d( self: ivy.Array, kernel: Union[int, Tuple[int, ...]], strides: Union[int, Tuple[int, ...]], padding: Union[str, int, Tuple[int], List[Tuple[int, int]]], /, *, data_format: str = "NDHWC", dilation: Union[int, Tuple[int, ...]] = 1, ceil_mode: bool = False, out: Optional[ivy.Array] = None, ) -> ivy.Array: """Compute a 3-D max pool given 5-D input x. Parameters ---------- self Input volume *[batch_size,d,h,w,d_in]*. kernel Convolution filters *[d,h,w]*. strides The stride of the sliding window for each dimension of input. padding "SAME" or "VALID" indicating the algorithm, or list indicating the per-dimension paddings. data_format NDHWC" or "NCDHW". Defaults to "NDHWC". dilaton The stride between elements within a sliding window, must be > 0. ceil_mode If True, ceil is used instead of floor to compute the output shape. This ensures that every element is covered by a sliding window. out optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The result of the pooling operation. Examples -------- >>> x = ivy.arange(48.).reshape((2, 3, 2, 2, 2)) >>> print(x.max_pool3d(2, 2, 'VALID')) ivy.array([[[[[14., 15.]]]], [[[[38., 39.]]]]]) >>> print(x.max_pool3d(2, 2, 'SAME')) ivy.array([[[[[14., 15.]]], [[[22., 23.]]]], [[[[38., 39.]]], [[[46., 47.]]]]]) """ return ivy.max_pool3d( self, kernel, strides, padding, data_format=data_format, dilation=dilation, ceil_mode=ceil_mode, out=out, ) def avg_pool1d( self: ivy.Array, kernel: Union[int, Tuple[int]], strides: Union[int, Tuple[int]], padding: str, /, *, data_format: str = "NWC", count_include_pad: bool = False, ceil_mode: bool = False, out: Optional[ivy.Array] = None, ) -> ivy.Array: """ivy.Array instance method variant of `ivy.avg_pool1d`. This method simply wraps the function, and so the docstring for `ivy.avg_pool1d` also applies to this method with minimal changes. Parameters ---------- self Input image *[batch_size,w,d_in]*. kernel The size of the window for each dimension of the input tensor. strides The stride of the sliding window for each dimension of input. padding "SAME" or "VALID" indicating the algorithm, or list indicating the per-dimension paddings. data_format "NWC" or "NCW". Defaults to "NWC". count_include_pad Whether to include padding in the averaging calculation. ceil_mode Whether to use ceil or floor for creating the output shape. out optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The result of the max pooling operation. Examples -------- >>> x = ivy.arange(0, 24.).reshape((2, 3, 4)) >>> print(x.avg_pool1d(2, 2, 'SAME')) ivy.array([[[ 2., 3., 4., 5.], [ 8., 9., 10., 11.]], [[14., 15., 16., 17.], [20., 21., 22., 23.]]]) >>> x = ivy.arange(0, 24.).reshape((2, 3, 4)) >>> print(x.avg_pool1d(2, 2, 'VALID')) ivy.array([[[ 2., 3., 4., 5.]], [[14., 15., 16., 17.]]]) """ return ivy.avg_pool1d( self, kernel, strides, padding, data_format=data_format, count_include_pad=count_include_pad, ceil_mode=ceil_mode, out=out, ) def avg_pool2d( self: ivy.Array, kernel: Union[int, Tuple[int], Tuple[int, int]], strides: Union[int, Tuple[int], Tuple[int, int]], padding: str, /, *, data_format: str = "NHWC", count_include_pad: bool = False, ceil_mode: bool = False, divisor_override: Optional[int] = None, out: Optional[ivy.Array] = None, ) -> ivy.Array: """ivy.Array instance method variant of `ivy.avg_pool2d`. This method simply wraps the function, and so the docstring for `ivy.avg_pool2d` also applies to this method with minimal changes. Parameters ---------- x Input image *[batch_size,h,w,d_in]*. kernel The size of the window for each dimension of the input tensor. strides The stride of the sliding window for each dimension of input. padding "SAME" or "VALID" indicating the algorithm, or list indicating the per-dimension paddings. data_format "NHWC" or "NCHW". Defaults to "NHWC". count_include_pad Whether to include padding in the averaging calculation. ceil_mode Whether to use ceil or floor for creating the output shape. divisor_override If given, it will be used as the divisor, otherwise kernel_size will be used. out optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The result of the max pooling operation. Examples -------- >>> x = ivy.arange(12.).reshape((2, 1, 3, 2)) >>> print(x.max_pool2d((2, 2), (1, 1), 'SAME')) ivy.array([[[[ 2, 3], [ 4, 5], [ 4, 5]]], [[[ 8, 9], [10, 11], [10, 11]]]]) >>> x = ivy.arange(48.).reshape((2, 4, 3, 2)) >>> print(x.max_pool2d(3, 1, 'VALID')) ivy.array([[[[16, 17]], [[22, 23]]], [[[40, 41]], [[46, 47]]]]) """ return ivy.avg_pool2d( self, kernel, strides, padding, data_format=data_format, count_include_pad=count_include_pad, ceil_mode=ceil_mode, divisor_override=divisor_override, out=out, ) def avg_pool3d( self: ivy.Array, kernel: Union[int, Tuple[int], Tuple[int, int, int]], strides: Union[int, Tuple[int], Tuple[int, int, int]], padding: str, /, *, data_format: str = "NDHWC", count_include_pad: bool = False, ceil_mode: bool = False, divisor_override: Optional[int] = None, out: Optional[ivy.Array] = None, ) -> ivy.Array: """Compute a 3-D max pool given 5-D input x. Parameters ---------- self Input volume *[batch_size,d,h,w,d_in]*. kernel Convolution filters *[d,h,w]*. strides The stride of the sliding window for each dimension of input. padding SAME" or "VALID" indicating the algorithm, or list indicating the per-dimension paddings. data_format NDHWC" or "NCDHW". Defaults to "NDHWC". count_include_pad Whether to include padding in the averaging calculation. ceil_mode Whether to use ceil or floor for creating the output shape. divisor_override If specified, it will be used as divisor, otherwise kernel_size will be used. out optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The result of the pooling operation. Examples -------- >>> x = ivy.arange(48.).reshape((2, 3, 2, 2, 2)) >>> print(x.avg_pool3d(2, 2, 'VALID')) ivy.array([[[[[ 7., 8.]]]], [[[[31., 32.]]]]]) >>> print(x.avg_pool3d(2, 2, 'SAME')) ivy.array([[[[[ 7., 8.]]], [[[19., 20.]]]], [[[[31., 32.]]], [[[43., 44.]]]]]) """ return ivy.avg_pool3d( self, kernel, strides, padding, data_format=data_format, count_include_pad=count_include_pad, ceil_mode=ceil_mode, divisor_override=divisor_override, out=out, ) def dct( self: ivy.Array, /, *, type: Literal[1, 2, 3, 4] = 2, n: Optional[int] = None, axis: int = -1, norm: Optional[Literal["ortho"]] = None, out: Optional[ivy.Array] = None, ) -> ivy.Array: """ivy.Array instance method variant of ivy.dct. This method simply wraps the function, and so the docstring for ivy.dct also applies to this method with minimal changes. Parameters ---------- self The input signal. type The type of the dct. Must be 1, 2, 3 or 4. n The length of the transform. If n is less than the input signal length, then x is truncated, if n is larger than x is zero-padded. norm The type of normalization to be applied. Must be either None or "ortho". out optional output array, for writing the result to. Returns ------- ret Array containing the transformed input. Examples -------- >>> x = ivy.array([8., 16., 24., 32., 40., 48., 56., 64.]) >>> x.dct(type=2, norm="ortho") ivy.array([ 102., -51.5, 0., -5.39, 0., -1.61, 0., -0.406]) """ return ivy.dct( self._data, type=type, n=n, axis=axis, norm=norm, out=out, ) def idct( self: ivy.Array, /, *, type: Literal[1, 2, 3, 4] = 2, n: Optional[int] = None, axis: int = -1, norm: Optional[Literal["ortho"]] = None, out: Optional[ivy.Array] = None, ) -> ivy.Array: """ivy.Array instance method variant of ivy.idct. This method simply wraps the function, and so the docstring for ivy.idct also applies to this method with minimal changes. Parameters ---------- self The input signal. type The type of the idct. Must be 1, 2, 3 or 4. n The length of the transform. If n is less than the input signal length, then x is truncated, if n is larger than x is zero-padded. norm The type of normalization to be applied. Must be either None or "ortho". out optional output array, for writing the result to. Returns ------- ret Array containing the transformed input. Examples -------- >>> x = ivy.array([8., 16., 24., 32., 40., 48., 56., 64.]) >>> x.idct(type=2, norm="ortho") ivy.array([ 79.49862671, -70.37691498, 30.00390816, -23.58938599, 13.92713165, -10.078475 , 5.19664812, -1.95411837]) """ return ivy.idct( self._data, type=type, n=n, axis=axis, norm=norm, out=out, ) def fft( self: ivy.Array, dim: int, /, *, norm: str = "backward", n: Optional[Union[int, Tuple[int]]] = None, out: Optional[ivy.Array] = None, ) -> ivy.Array: """ivy.Array instance method variant of ivy.ifft. This method simply wraps the function, and so the docstring for ivy.ifft also applies to this method with minimal changes. Parameters ---------- self Input volume *[...,d_in,...]*, where d_in indicates the dimension that needs FFT. dim The dimension along which to take the one dimensional FFT. norm Optional argument, "backward", "ortho" or "forward". Defaults to be "backward". "backward" indicates no normalization. "ortho" indicates normalization by 1/sqrt(n). "forward" indicates normalization by 1/n. n Optional argument indicating the sequence length, if given, the input would be padded with zero or truncated to length n before performing FFT. Should be a integer greater than 1. out Optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret Array containing the transformed input. Examples -------- >>> a = ivy.array((np.exp(2j * np.pi * np.arange(8) / 8))) >>> a.fft(0) ivy.array([-3.44509285e-16+1.14423775e-17j, 8.00000000e+00-8.11483250e-16j, 2.33486982e-16+1.22464680e-16j, 0.00000000e+00+1.22464680e-16j, 9.95799250e-17+2.33486982e-16j, 0.00000000e+00+7.66951701e-17j, 1.14423775e-17+1.22464680e-16j, 0.00000000e+00+1.22464680e-16j]) """ return ivy.fft( self._data, dim, norm=norm, n=n, out=out, ) def ifft( self: ivy.Array, dim: int, *, norm: str = "backward", n: Optional[Union[int, Tuple[int]]] = None, out: Optional[ivy.Array] = None, ) -> ivy.Array: """ivy.Array instance method variant of ivy.ifft. This method simply wraps the function, and so the docstring for ivy.ifft also applies to this method with minimal changes. Parameters ---------- self Input volume *[...,d_in,...]*, where d_in indicates the dimension that needs IFFT. dim The dimension along which to take the one dimensional IFFT. norm Optional argument, "backward", "ortho" or "forward". Defaults to be "backward". "backward" indicates no normalization. "ortho" indicates normalization by 1/sqrt(n). "forward" indicates normalization by 1/n. n Optional argument indicating the sequence length, if given, the input would be padded with zero or truncated to length n before performing IFFT. Should be a integer greater than 1. out Optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret Array containing the transformed input. Examples -------- >>> a = ivy.array((np.exp(2j * np.pi * np.arange(8) / 8))) >>> a.ifft(0) ivy.array([-4.30636606e-17+1.43029718e-18j, 0.00000000e+00+1.53080850e-17j, 1.43029718e-18+1.53080850e-17j, 0.00000000e+00+9.58689626e-18j, 1.24474906e-17+2.91858728e-17j, 0.00000000e+00+1.53080850e-17j, 2.91858728e-17+1.53080850e-17j, 1.00000000e+00-1.01435406e-16j]) """ return ivy.ifft( self._data, dim, norm=norm, n=n, out=out, ) def embedding( self: ivy.Array, indices: ivy.Array, /, *, max_norm: Optional[int] = None, out: Optional[ivy.Array] = None, ) -> ivy.Array: return ivy.embedding(self._data, indices, max_norm=max_norm, out=out) def dft( self, /, *, axis: int = 1, inverse: bool = False, onesided: bool = False, dft_length: Optional[Union[int, Tuple[int]]] = None, norm: str = "backward", out: Optional[ivy.Array] = None, ) -> ivy.Array: """Compute the discrete Fourier transform of input. Parameters ---------- self Input volume *[...,d_in,...]*, where d_in indicates the dimension that needs FFT. axis The axis on which to perform the DFT. By default this value is set to 1, which corresponds to the first dimension after the batch index. inverse Whether to perform the inverse discrete fourier transform. By default this value is set to False. onesided If onesided is True, only values for w in [0, 1, 2, …, floor(n_fft/2) + 1] are returned because the real-to-complex Fourier transform satisfies the conjugate symmetry, i.e., X[m, w] = X[m,w]=X[m,n_fft-w]*. Note if the input or window tensors are complex, then onesided output is not possible. Enabling onesided with real inputs performs a Real-valued fast Fourier transform (RFFT). When invoked with real or complex valued input, the default value is False. Values can be True or False. dft_length The length of the signal.If greater than the axis dimension, the signal will be zero-padded up to dft_length. If less than the axis dimension, only the first dft_length values will be used as the signal. It’s an optional value. norm Optional argument, "backward", "ortho" or "forward". Defaults to be "backward". "backward" indicates no normalization. "ortho" indicates normalization by 1/sqrt(n). "forward" indicates normalization by 1/n. out Optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The Fourier Transform of the input vector.If onesided is False, the following shape is expected: [batch_idx][signal_dim1][signal_dim2] …[signal_dimN][2]. If axis=0 and onesided is True, the following shape is expected: [batch_idx][floor(signal_dim1/2)+1][signal_dim2] …[signal_dimN][2]. If axis=1 and onesided is True, the following shape is expected: [batch_idx][signal_dim1] [floor(signal_dim2/2)+1] …[signal_dimN][2]. If axis=N-1 and onesided is True, the following shape is expected: [batch_idx][signal_dim1][signal_dim2]… [floor(signal_dimN/2)+1][2]. The signal_dim at the specified axis is equal to the dft_length. """ return ivy.dft( self._data, axis=axis, inverse=inverse, onesided=onesided, dft_length=dft_length, norm=norm, out=out, ) def interpolate( self, size: Union[Sequence[int], int], /, *, mode: Union[ Literal[ "linear", "bilinear", "trilinear", "nearest", "area", "nearest_exact", "tf_area", "bicubic", ] ] = "linear", scale_factor: Optional[Union[Sequence[int], int]] = None, recompute_scale_factor: Optional[bool] = None, align_corners: Optional[bool] = None, antialias: bool = False, out: Optional[ivy.Array] = None, ) -> ivy.Array: """Down/up samples the input to the given size. The algorithm used for interpolation is determined by mode. Parameters ---------- self Input array, Must have the shape [batch x channels x [optional depth] x [optional height] x width]. size Output size. mode Interpolation mode. Can be one of the following: - linear - bilinear - trilinear - nearest - area - tf_area - bicubic - mitchellcubic - lanczos3 - lanczos5 - gaussian scale_factor Multiplier for spatial size that defines the output size (overwriting `size`). align_corners If True, the corner pixels of the input and output tensors are aligned, and thus preserving the values at the corner pixels. If False, the corner pixels are not aligned, and the interpolation uses edge value padding for out-of-boundary values. only has an effect when mode is 'linear', 'bilinear', 'bicubic' or 'trilinear'. Default: False antialias If True, antialiasing is applied when downsampling an image. Supported modes: 'bilinear', 'bicubic'. out Optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- resized array """ return ivy.interpolate( self._data, size, mode=mode, scale_factor=scale_factor, recompute_scale_factor=recompute_scale_factor, align_corners=align_corners, antialias=antialias, out=out, ) def adaptive_avg_pool1d( self: ivy.Array, output_size: int, ) -> ivy.Array: """Apply a 1D adaptive average pooling over an input signal composed of several input planes. Parameters ---------- self Input array. Must have shape (N, C, L_in) or (C, L_in) where N is the batch dimension, C is the feature dimension, and L_in is the spatial dimension. output_size Spatial output size. Returns ------- The result of the pooling operation. Will have shape (N, C, L_out) or (C, L_out), where L_out = `output_size` """ return ivy.adaptive_avg_pool1d( self._data, output_size, ) def adaptive_avg_pool2d( self: ivy.Array, output_size: Union[Sequence[int], int], /, *, data_format: str = "NHWC", ) -> ivy.Array: """Apply a 2D adaptive average pooling over an input signal composed of several input planes. Parameters ---------- self A 3D or 4D input array. Should have a floating-point data type. output_size Spatial output size. data_format "NHWC" or "NCHW". Defaults to "NHWC". Returns ------- The result of the pooling operation. Will have shape (N, C, S_0, S_1) or (C, S_0, S_1), where S = `output_size` """ return ivy.adaptive_avg_pool2d( self._data, output_size, data_format=data_format, ) def adaptive_max_pool2d( self: ivy.Array, output_size: Union[Sequence[int], int], ) -> ivy.Array: """Apply a 2D adaptive maximum pooling over an input signal composed of several input planes. Parameters ---------- self Input array. Must have shape (N, C, H_in, W_in) or (C, H_in, W_in) where N is the batch dimension, C is the feature dimension, and H_in and W_in are the 2 spatial dimensions. output_size Spatial output size. Returns ------- The result of the pooling operation. Will have shape (N, C, S_0, S_1) or (C, S_0, S_1), where S = `output_size` """ return ivy.adaptive_max_pool2d( self._data, output_size, ) def adaptive_max_pool3d( self: ivy.Array, output_size: Union[Sequence[int], int], ) -> ivy.Array: return ivy.adaptive_max_pool3d( self._data, output_size, ) def reduce_window( self: ivy.Array, init_value: Union[int, float], computation: Callable, window_dimensions: Union[int, Sequence[int]], /, *, window_strides: Union[int, Sequence[int]] = 1, padding: Union[str, int, Sequence[Tuple[int, int]]] = "VALID", base_dilation: Union[int, Sequence[int]] = 1, window_dilation: Union[int, Sequence[int]] = 1, ) -> ivy.Array: """Apply a reduction function to all elements in each window of an array. Parameters ---------- self An array representing the base area on which the window is going to slide over. init_value The starting value for the reduction. computation The reduction function to apply to elements in each window. window_dimensions A sequence containing the window dimensions. window_strides A sequence containing the window strides. padding Either the string ‘SAME’ (padding with zeros evenly), the string ‘VALID’ (no padding), or a sequence of n (low, high) integer pairs that give the padding to apply before and after each spatial dimension. base_dilation A sequence containing the base dilation values. window_dilation A sequence containing the window dilation values. Returns ------- ret The result of the pooling-like operation. Examples -------- >>> x = ivy.array([[1, 2, 3, 4], >>> [5, 6, 7, 8], >>> [9, 10, 11, 12]]) >>> x.reduce_window(0, ivy.sum, (2, 2)) ivy.array([[32.]]) """ return ivy.reduce_window( self._data, init_value, computation, window_dimensions, window_strides=window_strides, padding=padding, base_dilation=base_dilation, window_dilation=window_dilation, ) def fft2( self: ivy.Array, *, s: Optional[Sequence[int]] = None, dim: Sequence[int] = (-2, -1), norm: str = "backward", out: Optional[ivy.Array] = None, ) -> ivy.Array: """Compute the 2-dimensional discrete Fourier Transform. Parameters ---------- x Input volume *[...,d_in,...]*, where d_in indicates the dimension that needs FFT2. s sequence of ints, optional Shape (length of each transformed axis) of the output (s[0] refers to axis 0, s[1] to axis 1, etc.). This corresponds to n for fft(x, n). Along each axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. If s is not given, the shape of the input along the axes specified by axes is used. dim Axes over which to compute the FFT2. If not given, the last two axes are used. A repeated index in axes means the transform over that axis is performed multiple times. A one-element sequence means that a one-dimensional FFT is performed. norm Optional argument, "backward", "ortho" or "forward". Defaults to be "backward". "backward" indicates no normalization. "ortho" indicates normalization by 1/sqrt(n). "forward" indicates normalization by 1/n. out Optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The result of the FFT2 operation. Examples -------- >>> a = ivy.array([[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]]) >>> ivy.fft2(a) array([[ 50. +0.j , 0. +0.j , 0. +0.j , # may vary 0. +0.j , 0. +0.j ], [-12.5+17.20477401j, 0. +0.j , 0. +0.j , 0. +0.j , 0. +0.j ], [-12.5 +4.0614962j , 0. +0.j , 0. +0.j , 0. +0.j , 0. +0.j ], [-12.5 -4.0614962j , 0. +0.j , 0. +0.j , 0. +0.j , 0. +0.j ], [-12.5-17.20477401j, 0. +0.j , 0. +0.j , 0. +0.j , 0. +0.j ]]) """ return ivy.fft2(self._data, s=s, dim=dim, norm=norm, out=out) def ifftn( self: ivy.Array, s: Optional[Union[int, Tuple[int, ...]]] = None, axes: Optional[Union[int, Tuple[int, ...]]] = None, *, norm: str = "backward", out: Optional[ivy.Array] = None, ) -> ivy.Array: """Compute the N-dimensional inverse discrete Fourier Transform. Parameters ---------- x Input array of complex numbers. s sequence of ints, optional Shape (length of transformed axis) of the output (`s[0]` refers to axis 0, `s[1]` to axis 1, etc.). If given shape is smaller than that of the input, the input is cropped. If larger, input is padded with zeros. If `s` is not given, shape of input along axes specified by axes is used. axes axes over which to compute the IFFT. If not given, last `len(s)` axes are used, or all axes if `s` is also not specified. Repeated indices in axes means inverse transform over that axis is performed multiple times. norm Optional argument, "backward", "ortho" or "forward". Defaults to be "backward". "backward" indicates no normalization. "ortho" indicates normalization by 1/sqrt(n). "forward" indicates normalization by 1/n. out Optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The truncated or zero-padded input, transformed along the axes indicated by axes, or by a combination of s or x, as explained in the parameters section above. Examples -------- >>> x = ivy.array([[0.24730653+0.90832391j, 0.49495562+0.9039565j, ... 0.98193269+0.49560517j], ... [0.93280757+0.48075343j, 0.28526384+0.3351205j, ... 0.2343787 +0.83528011j], ... [0.18791352+0.30690572j, 0.82115787+0.96195183j, ... 0.44719226+0.72654048j]]) >>> y = ivy.ifftn(x) >>> print(y) ivy.array([[ 0.51476765+0.66160417j, -0.04319742-0.05411636j, -0.015561 -0.04216015j], [ 0.06310689+0.05347854j, -0.13392983+0.16052352j, -0.08371392+0.17252843j], [-0.0031429 +0.05421245j, -0.10446617-0.17747098j, 0.05344324+0.07972424j]]) >>> x = ivy.array([[0.24730653+0.90832391j, 0.49495562+0.9039565j, ... 0.98193269+0.49560517j], ... [0.93280757+0.48075343j, 0.28526384+0.3351205j, ... 0.2343787 +0.83528011j], ... [0.18791352+0.30690572j, 0.82115787+0.96195183j, ... 0.44719226+0.72654048j]]) >>> y = ivy.ifftn(x, s=[2, 1], axes=[0, 1], norm='ortho') >>> print(y) ivy.array([[ 0.8344667 +0.98222595j], [-0.48472244+0.30233797j]]) """ return ivy.ifftn(self._data, s=s, axes=axes, norm=norm, out=out) def rfft( self: ivy.Array, /, *, n: Optional[int] = None, axis: int = -1, norm: Literal["backward", "ortho", "forward"] = "backward", out: Optional[ivy.Array] = None, ) -> ivy.Array: """ivy.Array instance method variant of ivy.rfft. This method simply wraps the function, and so the docstring for ivy.rfft also applies to this method with minimal changes. Parameters ---------- self input array. Must have a real-valued floating-point data type. n length of the transformed axis of the input. If - n is greater than the length of the input array, the input array is zero-padded to length n. - n is less than the length of the input array, the input array is trimmed to length n. - n is not provided, the length of the transformed axis of the output must equal the length of the input along the axis specified by axis. Default is ``None``. axis axis (dimension) over which to compute the Fourier transform. If not set, the last axis (dimension) is used. Default is ``-1``. norm normalization mode. Should be one of the following modes: - 'backward': no normalization. - 'ortho': normalize by 1/sqrt(n) (i.e., make the FFT orthonormal). - 'forward': normalize by 1/n. Default is ``backward``. out Optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret an array transformed along the axis (dimension) indicated by axis. The returned array must have a complex-valued floating-point data type determined by Type Promotion Rules. Examples -------- >>> x = ivy.array([0,1,2]) >>> y = x.rfft() >>> print(y) ivy.array([ 3. +0.j , -1.5+0.8660254j]) """ return ivy.rfft(self, n=n, axis=axis, norm=norm, out=out) def rfftn( self: ivy.Array, s: Optional[Sequence[int]] = None, axes: Optional[Sequence[int]] = None, *, norm: str = "backward", out: Optional[ivy.Array] = None, ) -> ivy.Array: """Compute the n-dimensional discrete Fourier Transform. Parameters ---------- self Input array. s Shape (length of each transformed axis) of the output. axes Axes over which to compute the RFFT. If not given, the last len(s) axes are used. norm Normalization mode: "backward", "ortho", or "forward". out Optional output array for writing the result. Returns ------- ret The result of the RFFT operation. """ return ivy.rfftn(self._data, s=s, axes=axes, norm=norm, out=out) def stft( self: ivy.Array, frame_length: int, frame_step: int, /, *, fft_length: Optional[int] = None, window_fn: Optional[Callable] = None, pad_end: Optional[bool] = False, name: Optional[str] = None, out: Optional[ivy.Array] = None, ) -> ivy.Array: """Compute the Short-time Fourier Transform of signals. Parameters ---------- self Input Arrays. frame_length An integer scalar Tensor. The window length in samples. frame_step An integer scalar Tensor. The number of samples to step. fft_length An integer scalar Tensor. The size of the FFT to apply. If not provided, uses the smallest power of 2 enclosing frame_length. window_fn A callable that takes a window length and a dtype keyword argument and returns a [window_length] Tensor of samples in the provided datatype. If set to None, no windowing is used. pad_end Whether to pad the end of signals with zeros when the provided frame length and step produces a frame that lies partially past its end. name An optional name for the operation. out Optional output array for writing the result. Returns ------- ret A [..., frames, fft_unique_bins] Tensor of complex64/complex128 STFT values where fft_unique_bins is fft_length // 2 + 1 (the unique components of the FFT). """ return ivy.stft( self._data, frame_length, frame_step, fft_length=fft_length, window_fn=window_fn, pad_end=pad_end, name=name, out=out, ) def sliding_window( self: ivy.Array, window_size: Union[int, Tuple[int, int], Tuple[int, int, int]], /, *, stride: Union[int, Tuple[int, int]] = 1, dilation: Union[int, Tuple[int, int]] = 1, padding: Union[str, int, Sequence[Tuple[int, int]]] = "VALID", ) -> ivy.Array: """Slide a window of specified dimension over all elements of an array. Parameters ---------- input An array representing the base area on which the window is going to slide over. window_size Size of the sliding window for each dimension of the input. stride The stride of the sliding window for each dimension of input padding Either the string ‘SAME’ (padding with zeros evenly), the string ‘VALID’ (no padding), or a sequence of n (low, high) integer pairs that give the padding to apply before and after each spatial dimension. dilation The stride between elements within a sliding window, must be > 0. Returns ------- ret The result of the sliding window operation. Examples -------- >>> x = ivy.array([[1, 2, 3, 4], >>> [5, 6, 7, 8], >>> [9, 10, 11, 12]]) >>> x.sliding_window((2, 2)) ivy.array([[[ 1, 2, 5, 6], [ 2, 3, 6, 7], [ 3, 4, 7, 8]], [[ 5, 6, 9, 10], [ 6, 7, 10, 11], [ 7, 8, 11, 12]]]) """ return ivy.sliding_window( self._data, window_size, stride=stride, dilation=dilation, padding=padding, ) def max_unpool1d( self: ivy.Array, indices: ivy.Array, kernel_size: Union[Tuple[int], int], /, *, strides: Optional[Union[int, Tuple[int]]] = None, padding: Union[int, Tuple[int]] = 0, data_format: Optional[str] = "NCW", ) -> ivy.Array: """Compute a 1-D max unpooling given the 1-D pooled input x and its indices. Parameters ---------- self Pooled input image *[batch_size, w, d_in]*. indices Indices obtained from the corresponding max pooling operation. kernel_size Size of the kernel i.e., the sliding window for each dimension of input. *[w]*. strides The stride of the sliding window for each dimension of input. padding SAME" or "VALID" indicating the algorithm, or list indicating the per-dimension paddings. data_format NWC" or "NCW". Defaults to "NWC". Returns ------- ret The result of the unpooling operation. """ return ivy.max_unpool1d( self._data, indices, kernel_size, strides=strides, padding=padding, data_format=data_format, )
ivy/ivy/data_classes/array/experimental/layers.py/0
{ "file_path": "ivy/ivy/data_classes/array/experimental/layers.py", "repo_id": "ivy", "token_count": 22888 }
9
# global import abc from typing import Optional, Union # local import ivy class _ArrayWithLosses(abc.ABC): def cross_entropy( self: ivy.Array, pred: Union[ivy.Array, ivy.NativeArray], /, *, axis: int = -1, epsilon: float = 1e-7, reduction: str = "mean", out: Optional[ivy.Array] = None, ) -> ivy.Array: """ivy.Array instance method variant of ivy.cross_entropy. This method simply wraps the function, and so the docstring for ivy.cross_entropy also applies to this method with minimal changes. Parameters ---------- self input array containing true labels. pred input array containing the predicted labels. axis the axis along which to compute the cross-entropy. If axis is ``-1``, the cross-entropy will be computed along the last dimension. Default: ``-1``. epsilon a float in [0.0, 1.0] specifying the amount of smoothing when calculating the loss. If epsilon is ``0``, no smoothing will be applied. Default: ``1e-7``. out optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The cross-entropy loss between the given distributions. Examples -------- >>> x = ivy.array([0, 0, 1, 0]) >>> y = ivy.array([0.25, 0.25, 0.25, 0.25]) >>> z = x.cross_entropy(y) >>> print(z) ivy.array(0.34657359) """ return ivy.cross_entropy( self._data, pred, axis=axis, epsilon=epsilon, reduction=reduction, out=out ) def binary_cross_entropy( self: ivy.Array, pred: Union[ivy.Array, ivy.NativeArray], /, *, from_logits: bool = False, epsilon: float = 0.0, reduction: str = "mean", pos_weight: Optional[Union[ivy.Array, ivy.NativeArray]] = None, axis: Optional[int] = None, out: Optional[ivy.Array] = None, ) -> ivy.Array: """ivy.Array instance method variant of ivy.binary_cross_entropy. This method simply wraps the function, and so the docstring for ivy.binary_cross_entropy also applies to this method with minimal changes. Parameters ---------- self input array containing true labels. pred input array containing Predicted labels. from_logits Whether `pred` is expected to be a logits tensor. By default, we assume that `pred` encodes a probability distribution. epsilon a float in [0.0, 1.0] specifying the amount of smoothing when calculating the loss. If epsilon is ``0``, no smoothing will be applied. Default: ``0``. reduction ``'none'``: No reduction will be applied to the output. ``'mean'``: The output will be averaged. ``'sum'``: The output will be summed. Default: ``'none'``. pos_weight a weight for positive examples. Must be an array with length equal to the number of classes. axis Axis along which to compute crossentropy. out optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The binary cross entropy between the given distributions. Examples -------- >>> x = ivy.array([1 , 1, 0]) >>> y = ivy.array([0.7, 0.8, 0.2]) >>> z = x.binary_cross_entropy(y) >>> print(z) ivy.array(0.26765382) """ return ivy.binary_cross_entropy( self._data, pred, from_logits=from_logits, epsilon=epsilon, reduction=reduction, pos_weight=pos_weight, axis=axis, out=out, ) def sparse_cross_entropy( self: ivy.Array, pred: Union[ivy.Array, ivy.NativeArray], /, *, axis: int = -1, epsilon: float = 1e-7, reduction: str = "mean", out: Optional[ivy.Array] = None, ) -> ivy.Array: """ivy.Array instance method variant of ivy.sparse_cross_entropy. This method simply wraps the function, and so the docstring for ivy.sparse_cross_entropy also applies to this method with minimal changes. Parameters ---------- self input array containing the true labels as logits. pred input array containing the predicted labels as logits. axis the axis along which to compute the cross-entropy. If axis is ``-1``, the cross-entropy will be computed along the last dimension. Default: ``-1``. epsilon a float in [0.0, 1.0] specifying the amount of smoothing when calculating the loss. If epsilon is ``0``, no smoothing will be applied. Default: ``1e-7``. epsilon a float in [0.0, 1.0] specifying the amount of smoothing when calculating the loss. If epsilon is ``0``, no smoothing will be applied. Default: ``1e-7``. out optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret The sparse cross-entropy loss between the given distributions. Examples -------- >>> x = ivy.array([1 , 1, 0]) >>> y = ivy.array([0.7, 0.8, 0.2]) >>> z = x.sparse_cross_entropy(y) >>> print(z) ivy.array([0.07438118, 0.07438118, 0.11889165]) """ return ivy.sparse_cross_entropy( self._data, pred, axis=axis, epsilon=epsilon, reduction=reduction, out=out )
ivy/ivy/data_classes/array/losses.py/0
{ "file_path": "ivy/ivy/data_classes/array/losses.py", "repo_id": "ivy", "token_count": 2787 }
10
# global from typing import Optional, Union, List, Dict, Tuple, Callable # local import ivy from ivy.data_classes.container.base import ContainerBase # ToDo: implement all methods here as public instance methods # noinspection PyMissingConstructor class _ContainerWithDataTypes(ContainerBase): @staticmethod def _static_astype( x: ivy.Container, dtype: Union[ivy.Dtype, ivy.Container], key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, *, copy: Union[bool, ivy.Container] = True, out: Optional[ivy.Container] = None, ) -> ivy.Container: """Copy an array to a specified data type irrespective of :ref:`type- promotion` rules. .. note:: Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent. .. note:: When casting a boolean input array to a numeric data type, a value of ``True`` must cast to a numeric value equal to ``1``, and a value of ``False`` must cast to a numeric value equal to ``0``. When casting a numeric input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``. Parameters ---------- x array to cast. dtype desired data type. copy 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 must be returned. Default: ``True``. out optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret an array having the specified data type. The returned array must have the same shape as ``x``. Examples -------- >>> c = ivy.Container(a=ivy.array([False,True,True]), ... b=ivy.array([3.14, 2.718, 1.618])) >>> ivy.Container.static_astype(c, ivy.int32) { a: ivy.array([0, 1, 1]), b: ivy.array([3, 2, 1]) } """ return ContainerBase.cont_multi_map_in_function( "astype", x, dtype, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, copy=copy, out=out, ) def astype( self: ivy.Container, dtype: Union[ivy.Dtype, ivy.Container], key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, *, copy: Union[bool, ivy.Container] = True, out: Optional[ivy.Container] = None, ) -> ivy.Container: """Copy an array to a specified data type irrespective of :ref:`type- promotion` rules. .. note:: Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent. .. note:: When casting a boolean input array to a numeric data type, a value of ``True`` must cast to a numeric value equal to ``1``, and a value of ``False`` must cast to a numeric value equal to ``0``. When casting a numeric input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``. Parameters ---------- self array to cast. dtype desired data type. copy 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 must be returned. Default: ``True``. out optional output array, for writing the result to. It must have a shape that the inputs broadcast to. Returns ------- ret an array having the specified data type. The returned array must have the same shape as ``x``. Examples -------- Using :class:`ivy.Container` instance method: >>> x = ivy.Container(a=ivy.array([False,True,True]), ... b=ivy.array([3.14, 2.718, 1.618])) >>> print(x.astype(ivy.int32)) { a: ivy.array([0, 1, 1]), b: ivy.array([3, 2, 1]) } """ return self._static_astype( self, dtype, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, copy=copy, out=out, ) @staticmethod def _static_broadcast_arrays( *arrays: Union[ivy.Container, ivy.Array, ivy.NativeArray], key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` static method variant of `ivy.broadcast_arrays`. This method simply wraps the function, and so the docstring for `ivy.broadcast_arrays` also applies to this method with minimal changes. Parameters ---------- arrays an arbitrary number of arrays to-be broadcasted. Each array must have the same shape. And Each array must have the same dtype as its corresponding input array. key_chains The key-chains to apply or not apply the method to. Default is ``None``. to_apply If True, the method will be applied to key_chains, otherwise key_chains will be skipped. Default is ``True``. prune_unapplied Whether to prune key_chains for which the function was not applied. Default is ``False``. map_sequences Whether to also map method to sequences (lists, tuples). Default is ``False``. Returns ------- ret A list of containers containing broadcasted arrays Examples -------- With :class:`ivy.Container` inputs: >>> x1 = ivy.Container(a=ivy.array([1, 2]), b=ivy.array([3, 4])) >>> x2 = ivy.Container(a=ivy.array([-1.2, 0.4]), b=ivy.array([0, 1])) >>> y = ivy.Container.static_broadcast_arrays(x1, x2) >>> print(y) [{ a: ivy.array([1, 2]), b: ivy.array([3, 4]) }, { a: ivy.array([-1.2, 0.4]), b: ivy.array([0, 1]) }] With mixed :class:`ivy.Container` and :class:`ivy.Array` inputs: >>> x1 = ivy.Container(a=ivy.array([4, 5]), b=ivy.array([2, -1])) >>> x2 = ivy.array([0.2, 3.]) >>> y = ivy.Container.static_broadcast_arrays(x1, x2) >>> print(y) [{ a: ivy.array([4, 5]), b: ivy.array([2, -1]) }, { a: ivy.array([0.2, 3.]), b: ivy.array([0.2, 3.]) }] """ return ContainerBase.cont_multi_map_in_function( "broadcast_arrays", *arrays, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) def broadcast_arrays( self: ivy.Container, *arrays: Union[ivy.Container, ivy.Array, ivy.NativeArray], key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` instance method variant of `ivy.broadcast_arrays`. This method simply wraps the function, and so the docstring for `ivy.broadcast_arrays` also applies to this method with minimal changes. Parameters ---------- self A container to be broadcatsed against other input arrays. arrays an arbitrary number of containers having arrays to-be broadcasted. Each array must have the same shape. Each array must have the same dtype as its corresponding input array. key_chains The key-chains to apply or not apply the method to. Default is ``None``. to_apply If True, the method will be applied to key_chains, otherwise key_chains will be skipped. Default is ``True``. prune_unapplied Whether to prune key_chains for which the function was not applied. Default is ``False``. map_sequences Whether to also map method to sequences (lists, tuples). Default is ``False``. Examples -------- With :class:`ivy.Container` inputs: >>> x1 = ivy.Container(a=ivy.array([1, 2]), b=ivy.array([3, 4])) >>> x2 = ivy.Container(a=ivy.array([-1.2, 0.4]), b=ivy.array([0, 1])) >>> y = x1.broadcast_arrays(x2) >>> print(y) [{ a: ivy.array([1, 2]), b: ivy.array([3, 4]) }, { a: ivy.array([-1.2, 0.4]), b: ivy.array([0, 1]) }] With mixed :class:`ivy.Container` and :class:`ivy.Array` inputs: >>> x1 = ivy.Container(a=ivy.array([4, 5]), b=ivy.array([2, -1])) >>> x2 = ivy.zeros(2) >>> y = x1.broadcast_arrays(x2) >>> print(y) [{ a: ivy.array([4, 5]), b: ivy.array([2, -1]) }, { a: ivy.array([0., 0.]), b: ivy.array([0., 0.]) }] """ return self._static_broadcast_arrays( self, *arrays, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) @staticmethod def _static_broadcast_to( x: ivy.Container, /, shape: Union[Tuple[int, ...], ivy.Container], *, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, out: Optional[ivy.Container] = None, ) -> ivy.Container: """`ivy.Container` static method variant of `ivy.broadcast_to`. This method simply wraps the function, and so the docstring for `ivy.broadcast_to` also applies to this method with minimal changes. Parameters ---------- x input array to be broadcasted. shape desired shape to be broadcasted to. out Optional array to store the broadcasted array. Returns ------- ret Returns the broadcasted array of shape 'shape' Examples -------- With :class:`ivy.Container` static method: >>> x = ivy.Container(a=ivy.array([1]), ... b=ivy.array([2])) >>> y = ivy.Container.static_broadcast_to(x,(3, 1)) >>> print(y) { a: ivy.array([1], [1], [1]), b: ivy.array([2], [2], [2]) } """ return ContainerBase.cont_multi_map_in_function( "broadcast_to", x, shape, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, out=out, ) def broadcast_to( self: ivy.Container, /, shape: Union[Tuple[int, ...], ivy.Container], *, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, out: Optional[ivy.Container] = None, ) -> ivy.Container: """`ivy.Container` instance method variant of `ivy.broadcast_to`. This method simply wraps the function, and so the docstring for `ivy.broadcast_to` also applies to this method with minimal changes. Parameters ---------- self input array to be broadcasted. shape desired shape to be broadcasted to. out Optional array to store the broadcasted array. Returns ------- ret Returns the broadcasted array of shape 'shape' Examples -------- With :class:`ivy.Container` instance method: >>> x = ivy.Container(a=ivy.array([0, 0.5]), ... b=ivy.array([4, 5])) >>> y = x.broadcast_to((3,2)) >>> print(y) { a: ivy.array([[0., 0.5], [0., 0.5], [0., 0.5]]), b: ivy.array([[4, 5], [4, 5], [4, 5]]) } """ return self._static_broadcast_to( self, shape, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, out=out, ) @staticmethod def _static_can_cast( from_: ivy.Container, to: Union[ivy.Dtype, ivy.Container], key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` static method variant of `ivy.can_cast`. This method simply wraps the function, and so the docstring for `ivy.can_cast` also applies to this method with minimal changes. Parameters ---------- from_ input container from which to cast. to desired data type. key_chains The key-chains to apply or not apply the method to. Default is ``None``. to_apply If True, the method will be applied to key_chains, otherwise key_chains will be skipped. Default is ``True``. prune_unapplied Whether to prune key_chains for which the function was not applied. Default is ``False``. map_sequences Whether to also map method to sequences (lists, tuples). Default is ``False``. Returns ------- ret ``True`` if the cast can occur according to :ref:`type-promotion` rules; otherwise, ``False``. Examples -------- >>> x = ivy.Container(a=ivy.array([0., 1., 2.]), ... b=ivy.array([3, 4, 5])) >>> print(x.a.dtype, x.b.dtype) float32 int32 >>> print(ivy.Container.static_can_cast(x, 'int64')) { a: false, b: true } """ return ContainerBase.cont_multi_map_in_function( "can_cast", from_, to, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) def can_cast( self: ivy.Container, to: Union[ivy.Dtype, ivy.Container], key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` instance method variant of `ivy.can_cast`. This method simply wraps the function, and so the docstring for `ivy.can_cast` also applies to this method with minimal changes. Parameters ---------- self input container from which to cast. to desired data type. key_chains The key-chains to apply or not apply the method to. Default is ``None``. to_apply If True, the method will be applied to key_chains, otherwise key_chains will be skipped. Default is ``True``. prune_unapplied Whether to prune key_chains for which the function was not applied. Default is ``False``. map_sequences Whether to also map method to sequences (lists, tuples). Default is ``False``. Returns ------- ret ``True`` if the cast can occur according to :ref:`type-promotion` rules; otherwise, ``False``. Examples -------- >>> x = ivy.Container(a=ivy.array([0., 1., 2.]), ... b=ivy.array([3, 4, 5])) >>> print(x.a.dtype, x.b.dtype) float32 int32 >>> print(x.can_cast('int64')) { a: False, b: True } """ return self._static_can_cast( self, to, key_chains, to_apply, prune_unapplied, map_sequences ) @staticmethod def _static_dtype( x: ivy.Container, *, as_native: Union[bool, ivy.Container] = False, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, out: Optional[ivy.Container] = None, ) -> ivy.Container: return ContainerBase.cont_multi_map_in_function( "dtype", x, as_native=as_native, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, out=out, ) def dtype( self: ivy.Container, *, as_native: Union[bool, ivy.Container] = False, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, out: Optional[ivy.Container] = None, ) -> ivy.Container: """ Examples -------- >>> x = ivy.Container(a=ivy.array([1, 2, 3]), b=ivy.array([2, 3, 4])) >>> y = x.dtype() >>> print(y) { a: int32, b: int32 } """ return self._static_dtype( self, as_native=as_native, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, out=out, ) @staticmethod def _static_default_float_dtype( *, input: Optional[Union[ivy.Array, ivy.NativeArray, ivy.Container]] = None, float_dtype: Optional[ Union[ivy.FloatDtype, ivy.NativeDtype, ivy.Container] ] = None, as_native: Optional[Union[bool, ivy.Container]] = None, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: return ContainerBase.cont_multi_map_in_function( "default_float_dtype", input=input, float_dtype=float_dtype, as_native=as_native, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) @staticmethod def _static_default_complex_dtype( *, input: Optional[Union[ivy.Array, ivy.NativeArray, ivy.Container]] = None, complex_dtype: Optional[ Union[ivy.FloatDtype, ivy.NativeDtype, ivy.Container] ] = None, as_native: Optional[Union[bool, ivy.Container]] = None, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: return ContainerBase.cont_multi_map_in_function( "default_complex_dtype", input=input, complex_dtype=complex_dtype, as_native=as_native, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) @staticmethod def _static_function_supported_dtypes( fn: Union[Callable, ivy.Container], key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: return ContainerBase.cont_multi_map_in_function( "function_supported_dtypes", fn, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) @staticmethod def _static_function_unsupported_dtypes( fn: Union[Callable, ivy.Container], key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: return ContainerBase.cont_multi_map_in_function( "function_unsupported_dtypes", fn, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) @staticmethod def _static_finfo( type: ivy.Container, /, *, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` static method variant of `ivy.finfo`. Parameters ---------- type input container with leaves to inquire information about. Returns ------- ret container of the same structure as `self`, with each element as a finfo object for the corresponding dtype of leave in`self`. Examples -------- >>> c = ivy.Container(x=ivy.array([-9.5,1.8,-8.9], dtype=ivy.float16), ... y=ivy.array([7.6,8.1,1.6], dtype=ivy.float64)) >>> y = ivy.Container.static_finfo(c) >>> print(y) { x: finfo(resolution=0.001, min=-6.55040e+04, max=6.55040e+04,\ dtype=float16), y: finfo(resolution=1e-15, min=-1.7976931348623157e+308, \ max=1.7976931348623157e+308, dtype=float64) } """ return ContainerBase.cont_multi_map_in_function( "finfo", type, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) def finfo( self: ivy.Container, /, *, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` instance method variant of `ivy.finfo`. Parameters ---------- self input container with leaves to inquire information about. Returns ------- ret container of the same structure as `self`, with each element as a finfo object for the corresponding dtype of leave in`self`. Examples -------- >>> c = ivy.Container(x=ivy.array([-9.5,1.8,-8.9], dtype=ivy.float16), ... y=ivy.array([7.6,8.1,1.6], dtype=ivy.float64)) >>> print(c.finfo()) { x: finfo(resolution=0.001, min=-6.55040e+04, max=6.55040e+04,\ dtype=float16), y: finfo(resolution=1e-15, min=-1.7976931348623157e+308, \ max=1.7976931348623157e+308, dtype=float64) } """ return self._static_finfo( self, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) @staticmethod def _static_iinfo( type: ivy.Container, /, *, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` static method variant of `ivy.iinfo`. This method simply wraps the function, and so the docstring for `ivy.iinfo` also applies to this method with minimal changes. Parameters ---------- type input container with leaves to inquire information about. key_chains The key-chains to apply or not apply the method to. Default is ``None``. to_apply Boolean indicating whether to apply the method to the key-chains. Default is ``True``. prune_unapplied Boolean indicating whether to prune the key-chains that were not applied. Default is ``False``. map_sequences Boolean indicating whether to map method to sequences (list, tuple). Default is ``False``. Returns ------- ret container of the same structure as `type`, with each element as an iinfo object for the corresponding dtype of leave in`type`. Examples -------- >>> c = ivy.Container(x=ivy.array([12,-1800,1084], dtype=ivy.int16), ... y=ivy.array([-40000,99,1], dtype=ivy.int32)) >>> y = ivy.Container.static_iinfo(c) >>> print(y) { x: iinfo(min=-32768, max=32767, dtype=int16), y: iinfo(min=-2147483648, max=2147483647, dtype=int32) } """ return ContainerBase.cont_multi_map_in_function( "iinfo", type, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) def iinfo( self: ivy.Container, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` instance method variant of `ivy.iinfo`. This method simply wraps the function, and so the docstring for `ivy.iinfo` also applies to this method with minimal changes. Parameters ---------- self input container with leaves to inquire information about. key_chains The key-chains to apply or not apply the method to. Default is ``None``. to_apply Boolean indicating whether to apply the method to the key-chains. Default is ``True``. prune_unapplied Boolean indicating whether to prune the key-chains that were not applied. Default is ``False``. map_sequences Boolean indicating whether to map method to sequences (list, tuple). Default is ``False``. Returns ------- ret container of the same structure as `self`, with each element as an iinfo object for the corresponding dtype of leave in`self`. Examples -------- >>> c = ivy.Container(x=ivy.array([-9,1800,89], dtype=ivy.int16), ... y=ivy.array([76,-81,16], dtype=ivy.int32)) >>> c.iinfo() { x: iinfo(min=-32768, max=32767, dtype=int16), y: iinfo(min=-2147483648, max=2147483647, dtype=int32) } >>> c = ivy.Container(x=ivy.array([-12,123,4], dtype=ivy.int8), ... y=ivy.array([76,-81,16], dtype=ivy.int16)) >>> c.iinfo() { x: iinfo(min=-128, max=127, dtype=int8), y: iinfo(min=-32768, max=32767, dtype=int16) } """ return self._static_iinfo( self, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) @staticmethod def _static_is_bool_dtype( dtype_in: ivy.Container, /, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: return ContainerBase.cont_multi_map_in_function( "is_bool_dtype", dtype_in, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) def is_bool_dtype( self: ivy.Container, /, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: return self._static_is_bool_dtype( self, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) @staticmethod def _static_is_float_dtype( dtype_in: ivy.Container, /, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` static method variant of `is_float_dtype`. This method simply wraps this function, so the docstring of `is_float_dtype` roughly applies to this method. Parameters ---------- dtype_in : ivy.Container The input to check for float dtype. key_chains : Optional[Union[List[str], Dict[str, str]]] The key chains to use when mapping over the input. to_apply : bool Whether to apply the mapping over the input. prune_unapplied : bool Whether to prune the keys that were not applied. map_sequences : bool Boolean indicating whether to map method to sequences (list, tuple). Default is ``False``. Returns ------- ret : bool Boolean indicating whether the input has float dtype. Examples -------- >>> x = ivy.static_is_float_dtype(ivy.float32) >>> print(x) True >>> x = ivy.static_is_float_dtype(ivy.int64) >>> print(x) False >>> x = ivy.static_is_float_dtype(ivy.int32) >>> print(x) False >>> x = ivy.static_is_float_dtype(ivy.bool) >>> print(x) False >>> arr = ivy.array([1.2, 3.2, 4.3], dtype=ivy.float32) >>> print(arr.is_float_dtype()) True >>> x = ivy.Container(a=ivy.array([0., 1., 2.]), b=ivy.array([3, 4, 5])) >>> print(x.a.dtype, x.b.dtype) float32 int32 """ return ContainerBase.cont_multi_map_in_function( "is_float_dtype", dtype_in, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) def is_float_dtype( self: ivy.Container, /, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` instance method variant of `ivy.is_float_dtype`. This method simply wraps the function, and so the docstring for `ivy.is_float_dtype` also applies to this method with minimal changes. Parameters ---------- self : ivy.Container The `ivy.Container` instance to call `ivy.is_float_dtype` on. key_chains : Union[List[str], Dict[str, str]] The key-chains to apply or not apply the method to. Default is ``None``. to_apply : bool Boolean indicating whether to apply the method to the key-chains. Default is ``False``. prune_unapplied : bool Boolean indicating whether to prune the key-chains that were not applied. Default is ``False``. map_sequences : bool Boolean indicating whether to map method to sequences (list, tuple). Default is ``False``. Returns ------- ret : bool Boolean of whether the input is of a float dtype. Examples -------- >>> x = ivy.is_float_dtype(ivy.float32) >>> print(x) True >>> x = ivy.is_float_dtype(ivy.int64) >>> print(x) False >>> x = ivy.is_float_dtype(ivy.int32) >>> print(x) False >>> x = ivy.is_float_dtype(ivy.bool) >>> print(x) False >>> arr = ivy.array([1.2, 3.2, 4.3], dtype=ivy.float32) >>> print(arr.is_float_dtype()) True >>> x = ivy.Container(a=ivy.array([0., 1., 2.]), b=ivy.array([3, 4, 5])) >>> print(x.a.dtype, x.b.dtype) float32 int32 """ return self._static_is_float_dtype( self, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) @staticmethod def _static_is_int_dtype( dtype_in: ivy.Container, /, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: return ContainerBase.cont_multi_map_in_function( "is_int_dtype", dtype_in, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) def is_int_dtype( self: ivy.Container, /, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: return self._static_is_int_dtype( self, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) @staticmethod def _static_is_uint_dtype( dtype_in: ivy.Container, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: return ContainerBase.cont_multi_map_in_function( "is_uint_dtype", dtype_in, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) def is_uint_dtype( self: ivy.Container, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: return self._static_is_uint_dtype( self, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) @staticmethod def _static_is_complex_dtype( dtype_in: ivy.Container, /, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` static method variant of `is_complex_dtype`. This method simply wraps this function, so the docstring of `is_complex_dtype` roughly applies to this method. Parameters ---------- dtype_in : ivy.Container The input to check for complex dtype. key_chains : Optional[Union[List[str], Dict[str, str]]] The key chains to use when mapping over the input. to_apply : bool Whether to apply the mapping over the input. prune_unapplied : bool Whether to prune the keys that were not applied. map_sequences : bool Boolean indicating whether to map method to sequences (list, tuple). Default is ``False``. Returns ------- ret : bool Boolean indicating whether the input has float dtype. Examples -------- >>> x = ivy.Container.static_is_complex_dtype(ivy.complex64) >>> print(x) True >>> x = ivy.Container.static_is_complex_dtype(ivy.int64) >>> print(x) False >>> x = ivy.Container.static_is_complex_dtype(ivy.float32) >>> print(x) False """ return ContainerBase.cont_multi_map_in_function( "is_complex_dtype", dtype_in, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) def is_complex_dtype( self: ivy.Container, /, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` instance method variant of `ivy.is_complex_dtype`. This method simply wraps the function, and so the docstring for `ivy.is_complex_dtype` also applies to this method with minimal changes. Parameters ---------- self : ivy.Container The `ivy.Container` instance to call `ivy.is_complex_dtype` on. key_chains : Union[List[str], Dict[str, str]] The key-chains to apply or not apply the method to. Default is ``None``. to_apply : bool Boolean indicating whether to apply the method to the key-chains. Default is ``False``. prune_unapplied : bool Boolean indicating whether to prune the key-chains that were not applied. Default is ``False``. map_sequences : bool Boolean indicating whether to map method to sequences (list, tuple). Default is ``False``. Returns ------- ret : bool Boolean of whether the input is of a complex dtype. Examples -------- >>> x = ivy.is_complex_dtype(ivy.complex64) >>> print(x) True >>> x = ivy.is_complex_dtype(ivy.int64) >>> print(x) False >>> x = ivy.is_complex_dtype(ivy.float32) >>> print(x) False """ return self._static_is_complex_dtype( self, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) @staticmethod def _static_result_type( *arrays_and_dtypes: ivy.Container, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` static method variant of `ivy.result_type`. This method simply wraps the function, and so the docstring for `ivy.result_type` also applies to this method with minimal changes. Parameters ---------- arrays_and_dtypes an arbitrary number of input arrays and/or dtypes. key_chains The key-chains to apply or not apply the method to. Default is ``None``. to_apply If True, the method will be applied to key_chains, otherwise key_chains will be skipped. Default is ``True``. prune_unapplied Whether to prune key_chains for which the function was not applied. Default is ``False``. map_sequences Whether to also map method to sequences (lists, tuples). Default is ``False``. Returns ------- ret the dtype resulting from an operation involving the input arrays and dtypes. Examples -------- >>> x = ivy.Container(a = ivy.array([0, 1, 2]), ... b = ivy.array([3., 4., 5.])) >>> print(x.a.dtype, x.b.dtype) int32 float32 >>> print(ivy.Container.static_result_type(x, ivy.float64)) { a: float64, b: float32 } """ return ContainerBase.cont_multi_map_in_function( "result_type", *arrays_and_dtypes, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, ) def result_type( self: ivy.Container, *arrays_and_dtypes: ivy.Container, key_chains: Optional[Union[List[str], Dict[str, str], ivy.Container]] = None, to_apply: Union[bool, ivy.Container] = True, prune_unapplied: Union[bool, ivy.Container] = False, map_sequences: Union[bool, ivy.Container] = False, ) -> ivy.Container: """`ivy.Container` instance method variant of `ivy.result_type`. This method simply wraps the function, and so the docstring for `ivy.result_type` also applies to this method with minimal changes. Parameters ---------- self input container from which to cast. arrays_and_dtypes an arbitrary number of input arrays and/or dtypes. key_chains The key-chains to apply or not apply the method to. Default is ``None``. to_apply If True, the method will be applied to key_chains, otherwise key_chains will be skipped. Default is ``True``. prune_unapplied Whether to prune key_chains for which the function was not applied. Default is ``False``. map_sequences Whether to also map method to sequences (lists, tuples). Default is ``False``. Returns ------- ret the dtype resulting from an operation involving the input arrays and dtypes. Examples -------- >>> x = ivy.Container(a = ivy.array([3, 3, 3])) >>> print(x.a.dtype) int32 >>> y = ivy.Container(b = ivy.float64) >>> print(x.result_type(y)) { a: { b: float64 } } """ return self._static_result_type( self, *arrays_and_dtypes, key_chains=key_chains, to_apply=to_apply, prune_unapplied=prune_unapplied, map_sequences=map_sequences, )
ivy/ivy/data_classes/container/data_type.py/0
{ "file_path": "ivy/ivy/data_classes/container/data_type.py", "repo_id": "ivy", "token_count": 22747 }
11

Dataset Card for "unifyai-ivy-code-dataset"

More Information needed

Downloads last month
39