diff --git a/deps/decimal/.formatter.exs b/deps/decimal/.formatter.exs new file mode 100644 index 0000000000000000000000000000000000000000..cc79f6937bd6f18653fa3803e5f5771748051127 --- /dev/null +++ b/deps/decimal/.formatter.exs @@ -0,0 +1,3 @@ +[ + inputs: ["{bench,mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] +] diff --git a/deps/decimal/.hex b/deps/decimal/.hex new file mode 100644 index 0000000000000000000000000000000000000000..6c94f101b4f2c5fb24f2ca30dfdb55117533b505 Binary files /dev/null and b/deps/decimal/.hex differ diff --git a/deps/decimal/CHANGELOG.md b/deps/decimal/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..02f589997756b6a3d4e6f592945d14a05fb9395d --- /dev/null +++ b/deps/decimal/CHANGELOG.md @@ -0,0 +1,150 @@ +# CHANGELOG + +## v2.3.0 (2024-12-13) + +* Implement the upcoming [`JSON.Encoder`](https://hexdocs.pm/elixir/main/JSON.Encoder.html) + protocol + +## v2.2.0 (2024-11-13) + +* Add `Decimal.gte?/2` and `Decimal.lte?/2` +* Add `Decimal.compare/3` and `Decimal.eq?/3` with threshold as parameter + +## v2.1.1 (2023-04-26) + +Decimal v2.1 requires Elixir v1.8+. + +### Bug fixes + +* Fix `Decimal.compare/2` when comparing against `0` + +## v2.1.0 (2023-04-26) + +Decimal v2.1 requires Elixir v1.8+. + +### Enhancements + +* Improve error message from `Decimal.to_integer/1` during precision loss +* `Inspect` protocol implementation returns strings in the `Decimal.new(...)` format +* Add `Decimal.scale/1` +* Optimize `Decimal.compare/2` for numbers with large exponents + +### Bug fixes + +* Fix `Decimal.integer?/1` spec +* Fix `Decimal.integer?/1` check on 0 with >1 significant digits + +## v2.0.0 (2020-09-08) + +Decimal v2.0 requires Elixir v1.2+. + +### Enhancements + +* Add `Decimal.integer?/1` + +### Breaking changes + +* Change `Decimal.compare/2` to return `:lt | :eq | :gt` +* Change `Decimal.cast/1` to return `{:ok, t} | :error` +* Change `Decimal.parse/1` to return `{t, binary} | :error` +* Remove `:message` and `:result` fields from `Decimal.Error` +* Remove sNaN +* Rename qNaN to NaN +* Remove deprecated support for floats in `Decimal.new/1` +* Remove deprecated `Decimal.minus/1` +* Remove deprecated `Decimal.plus/1` +* Remove deprecated `Decimal.reduce/1` +* Remove deprecated `Decimal.with_context/2`, `Decimal.get_context/1`, `Decimal.set_context/1`, + and `Decimal.update_context/1` +* Remove deprecated `Decimal.decimal?/1` + +### Deprecations + +* Deprecate `Decimal.cmp/2` + +## v1.9.0 (2020-09-08) + +### Enhancements + +* Add `Decimal.negate/1` +* Add `Decimal.apply_context/1` +* Add `Decimal.normalize/1` +* Add `Decimal.Context.with/2`, `Decimal.Context.get/1`, `Decimal.Context.set/2`, + and `Decimal.Context.update/1` +* Add `Decimal.is_decimal/1` + +### Deprecations + +* Deprecate `Decimal.minus/1` in favour of the new `Decimal.negate/1` +* Deprecate `Decimal.plus/1` in favour of the new `Decimal.apply_context/1` +* Deprecate `Decimal.reduce/1` in favour of the new `Decimal.normalize/1` +* Deprecate `Decimal.with_context/2`, `Decimal.get_context/1`, `Decimal.set_context/2`, + and `Decimal.update_context/1` in favour of new functions on the `Decimal.Context` module +* Deprecate `Decimal.decimal?/1` in favour of the new `Decimal.is_decimal/1` + +## v1.8.1 (2019-12-20) + +### Bug fixes + +* Fix Decimal.compare/2 with string arguments +* Set :signal on error + +## v1.8.0 (2019-06-24) + +### Enhancements + +* Add `Decimal.cast/1` +* Add `Decimal.eq?/2`, `Decimal.gt?/2`, and `Decimal.lt?/2` +* Add guards to `Decimal.new/3` to prevent invalid Decimal numbers + +## v1.7.0 (2019-02-16) + +### Enhancements + +* Add `Decimal.sqrt/1` + +## v1.6.0 (2018-11-22) + +### Enhancements + +* Support for canonical XSD representation on `Decimal.to_string/2` + +### Bugfixes + +* Fix exponent off-by-one when converting from decimal to float +* Fix negative?/1 and positive?/1 specs + +### Deprecations + +* Deprecate passing float to `Decimal.new/1` in favor of `Decimal.from_float/1` + +## v1.5.0 (2018-03-24) + +### Enhancements + +* Add `Decimal.positive?/1` and `Decimal.negative?/1` +* Accept integers and strings in arithmetic functions, e.g.: `Decimal.add(1, "2.0")` +* Add `Decimal.from_float/1` + +### Soft deprecations (no warnings emitted) + +* Soft deprecate passing float to `new/1` in favor of `from_float/1` + +## v1.4.1 (2017-10-12) + +### Bugfixes + +* Include the given value as part of the error reason +* Fix `:half_even` `:lists.last` bug (empty signif) +* Fix error message for round +* Fix `:half_down` rounding error when remainder is greater than 5 +* Fix `Decimal.new/1` float conversion with bigger precision than 4 +* Fix precision default value + +## v1.4.0 (2017-06-25) + +### Bugfixes + +* Fix `Decimal.to_integer/1` for large coefficients +* Fix rounding of ~0 values +* Fix errors when comparing and adding two infinities diff --git a/deps/decimal/LICENSE.txt b/deps/decimal/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..d9a10c0d8e868ebf8da0b3dc95bb0be634c34bfe --- /dev/null +++ b/deps/decimal/LICENSE.txt @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/deps/decimal/README.md b/deps/decimal/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a3c68660c021b64c417a4051fe43c97b595c6d09 --- /dev/null +++ b/deps/decimal/README.md @@ -0,0 +1,207 @@ +# Decimal + +Arbitrary precision decimal arithmetic. + +## Concept + +Decimal represents values internally using three integers: a sign, a coefficient, and an exponent. +In this way, numbers of any size and with any number of decimal places can be represented exactly. + +```elixir +Decimal.new(_sign = 1, _coefficient = 42, _exponent = 0) #=> Decimal.new("42") +Decimal.new(-1, 42, 0) #=> Decimal.new("-42") +Decimal.new(1, 42, -1) #=> Decimal.new("4.2") +Decimal.new(1, 42, -20) #=> Decimal.new("4.2E-19") +Decimal.new(1, 42, 20) #=> Decimal.new("4.2E+21") +Decimal.new(1, 123456789987654321, -9) #=> Decimal.new("123456789.987654321") +``` + +For calculations, the amount of desired precision - that is, the number of +decimal digits in the coefficient - can be specified. + +## Usage + +Add Decimal as a dependency in your `mix.exs` file: + +```elixir +def deps do + [{:decimal, "~> 2.0"}] +end +``` + +Next, run `mix deps.get` in your shell to fetch and compile `Decimal`. Start an +interactive Elixir shell with `iex -S mix`: + +```elixir +iex> alias Decimal, as: D +iex> D.add(6, 7) +Decimal.new("13") +iex> D.div(1, 3) +Decimal.new("0.3333333333333333333333333333") +iex> D.new("0.33") +Decimal.new("0.33") +``` + +## Examples + +### Using the context + +The context specifies the maximum precision of the result of calculations and +the rounding algorithm if the result has a higher precision than the specified +maximum. It also holds the list of trap enablers and the current set +flags. + +The context is stored in the process dictionary. You don't have to pass the +context around explicitly and the flags will be updated automatically. + +The context is accessed with `Decimal.Context.get/0` and set with +`Decimal.Context.set/1`. It can be set temporarily with +`Decimal.Context.with/2`. + +```elixir +iex> D.Context.get() +%Decimal.Context{flags: [:rounded, :inexact], precision: 9, rounding: :half_up, + traps: [:invalid_operation, :division_by_zero]} + +iex> D.Context.with(%D.Context{precision: 2}, fn -> IO.inspect D.Context.get() end) +%Decimal.Context{flags: [], precision: 2, rounding: :half_up, + traps: [:invalid_operation, :division_by_zero]} +%Decimal.Context{flags: [], precision: 2, rounding: :half_up, + traps: [:invalid_operation, :division_by_zero]} + +iex> D.Context.set(%D.Context{D.Context.get() | traps: []}) +:ok + +iex> D.Context.get() +%Decimal.Context{flags: [:rounded, :inexact], precision: 9, rounding: :half_up, + traps: []} +``` + +### Precision and rounding + +Use `:precision` option to limit the amount of decimal digits in the +coefficient of any calculation result: + +```elixir +iex> D.Context.set(%D.Context{D.Context.get() | precision: 9}) +:ok + +iex> D.div(100, 3) +Decimal.new("33.3333333") + +iex> D.Context.set(%D.Context{D.Context.get() | precision: 2}) +:ok + +iex> D.div(100, 3) +Decimal.new("33") +``` + +The `:rounding` option specifies the algorithm and precision of the rounding +operation: + +```elixir +iex> D.Context.set(%D.Context{D.Context.get() | rounding: :half_up}) +:ok + +iex> D.div(31, 2) +Decimal.new("16") + +iex> D.Context.set(%D.Context{D.Context.get() | rounding: :floor}) +:ok + +iex> D.div(31, 2) +Decimal.new("15") +``` + +### Comparisons + +Using comparison operators (`<`, `=`, `>`) with two or more decimal digits may +not produce accurate result. Instead, use comparison functions. + +```elixir +iex> D.compare(-1, 0) +:lt +iex> D.compare(0, -1) +:gt +iex> D.compare(0, 0) +:eq + +iex> D.equal?(-1, 0) +false +iex> D.equal?(0, "0.0") +true +``` + +### Flags and trap enablers + +When an exceptional condition is signalled, its flag is set in the current +context. `Decimal.Error` will be raised if the trap enabler is set. + +```elixir +iex> D.Context.set(%D.Context{D.Context.get() | rounding: :floor, precision: 2}) +:ok + +iex> D.Context.get().traps +[:invalid_operation, :division_by_zero] + +iex> D.Context.get().flags +[] + +iex> D.div(31, 2) +Decimal.new("15") + +iex> D.Context.get().flags +[:inexact, :rounded] +``` + +`:inexact` and `:rounded` flag were signalled above because the result of the +operation was inexact given the context's precision and had to be rounded to +fit the precision. `Decimal.Error` was not raised because the signals' trap +enablers weren't set. + +```elixir +iex> D.Context.set(%D.Context{D.Context.get() | traps: D.Context.get().traps ++ [:inexact]}) +:ok + +iex> D.div(31, 2) +** (Decimal.Error) +``` + +The default trap enablers, such as `:division_by_zero`, can be unset: + +```elixir +iex> D.Context.get().traps +[:invalid_operation, :division_by_zero] + +iex> D.div(42, 0) +** (Decimal.Error) + +iex> D.Context.set(%D.Context{D.Context.get() | traps: [], flags: []}) +:ok + +iex> D.div(42, 0) +Decimal.new("Infinity") + +iex> D.Context.get().flags +[:division_by_zero] +``` + +### Mitigating rounding errors + +TODO + +## License + + Copyright 2013 Eric Meadows-Jönsson + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/deps/decimal/hex_metadata.config b/deps/decimal/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..266bf526fb02d98fc181f9791926ffceaecf430f --- /dev/null +++ b/deps/decimal/hex_metadata.config @@ -0,0 +1,14 @@ +{<<"links">>,[{<<"GitHub">>,<<"https://github.com/ericmj/decimal">>}]}. +{<<"name">>,<<"decimal">>}. +{<<"version">>,<<"2.3.0">>}. +{<<"description">>,<<"Arbitrary precision decimal arithmetic.">>}. +{<<"elixir">>,<<"~> 1.8">>}. +{<<"app">>,<<"decimal">>}. +{<<"licenses">>,[<<"Apache-2.0">>]}. +{<<"requirements">>,[]}. +{<<"files">>, + [<<"lib">>,<<"lib/decimal">>,<<"lib/decimal/error.ex">>, + <<"lib/decimal/context.ex">>,<<"lib/decimal/macros.ex">>, + <<"lib/decimal.ex">>,<<".formatter.exs">>,<<"mix.exs">>,<<"README.md">>, + <<"LICENSE.txt">>,<<"CHANGELOG.md">>]}. +{<<"build_tools">>,[<<"mix">>]}. diff --git a/deps/decimal/lib/decimal.ex b/deps/decimal/lib/decimal.ex new file mode 100644 index 0000000000000000000000000000000000000000..8205680fe9337320d6a791dab11f6fbb7f5ff5b7 --- /dev/null +++ b/deps/decimal/lib/decimal.ex @@ -0,0 +1,2106 @@ +defmodule Decimal do + @moduledoc """ + Decimal arithmetic on arbitrary precision floating-point numbers. + + A number is represented by a signed coefficient and exponent such that: `sign + * coefficient * 10 ^ exponent`. All numbers are represented and calculated + exactly, but the result of an operation may be rounded depending on the + context the operation is performed with, see: `Decimal.Context`. Trailing + zeros in the coefficient are never truncated to preserve the number of + significant digits unless explicitly done so. + + There are also special values such as NaN (not a number) and ±Infinity. + -0 and +0 are two distinct values. + Some operation results are not defined and will return NaN. + This kind of NaN is quiet, any operation returning a number will return + NaN when given a quiet NaN (the NaN value will flow through all operations). + + Exceptional conditions are grouped into signals, each signal has a flag and a + trap enabler in the context. Whenever a signal is triggered it's flag is set + in the context and will be set until explicitly cleared. If the signal is trap + enabled `Decimal.Error` will be raised. + + ## Specifications + + * [IBM's General Decimal Arithmetic Specification](http://speleotrove.com/decimal/decarith.html) + * [IEEE standard 854-1987](http://web.archive.org/web/20150908012941/http://754r.ucbtest.org/standards/854.pdf) + + This library follows the above specifications for reference of arithmetic + operation implementations, but the public APIs may differ to provide a + more idiomatic Elixir interface. + + The specification models the sign of the number as 1, for a negative number, + and 0 for a positive number. Internally this implementation models the sign as + 1 or -1 such that the complete number will be `sign * coefficient * + 10 ^ exponent` and will refer to the sign in documentation as either *positive* + or *negative*. + + There is currently no maximum or minimum values for the exponent. Because of + that all numbers are "normal". This means that when an operation should, + according to the specification, return a number that "underflows" 0 is returned + instead of Etiny. This may happen when dividing a number with infinity. + Additionally, overflow, underflow and clamped may never be signalled. + """ + + import Bitwise + import Kernel, except: [abs: 1, div: 2, max: 2, min: 2, rem: 2, round: 1] + import Decimal.Macros + alias Decimal.Context + alias Decimal.Error + + @power_of_2_to_52 4_503_599_627_370_496 + + @typedoc """ + The coefficient of the power of `10`. Non-negative because the sign is stored separately in `sign`. + + * `non_neg_integer` - when the `t` represents a number, instead of one of the special values below. + * `:NaN` - Not a Number. + * `:inf` - Infinity. + + """ + @type coefficient :: non_neg_integer | :NaN | :inf + + @typedoc """ + The exponent to which `10` is raised. + """ + @type exponent :: integer + + @typedoc """ + + * `1` for positive + * `-1` for negative + + """ + @type sign :: 1 | -1 + + @type signal :: + :invalid_operation + | :division_by_zero + | :rounded + | :inexact + + @type compare_result :: + :lt | :gt | :eq + + @typedoc """ + Rounding algorithm. + + See `Decimal.Context` for more information. + """ + @type rounding :: + :down + | :half_up + | :half_even + | :ceiling + | :floor + | :half_down + | :up + + @typedoc """ + This implementation models the `sign` as `1` or `-1` such that the complete number will be: `sign * coef * 10 ^ exp`. + + * `coef` - the coefficient of the power of `10`. + * `exp` - the exponent of the power of `10`. + * `sign` - `1` for positive, `-1` for negative. + + """ + @type t :: %__MODULE__{ + sign: sign, + coef: coefficient, + exp: exponent + } + + @type decimal :: t | integer | String.t() + + defstruct sign: 1, coef: 0, exp: 0 + + defmacrop error(flags, reason, result, context \\ nil) do + quote bind_quoted: binding() do + case handle_error(flags, reason, result, context) do + {:ok, result} -> result + {:error, error} -> raise Error, error + end + end + end + + @doc """ + Returns `true` if number is NaN, otherwise `false`. + + ## Examples + + iex> Decimal.nan?(Decimal.new("NaN")) + true + + iex> Decimal.nan?(Decimal.new(42)) + false + + """ + @spec nan?(t) :: boolean + def nan?(%Decimal{coef: :NaN}), do: true + def nan?(%Decimal{}), do: false + + @doc """ + Returns `true` if number is ±Infinity, otherwise `false`. + + ## Examples + + iex> Decimal.inf?(Decimal.new("+Infinity")) + true + + iex> Decimal.inf?(Decimal.new("-Infinity")) + true + + iex> Decimal.inf?(Decimal.new("1.5")) + false + + """ + @spec inf?(t) :: boolean + def inf?(%Decimal{coef: :inf}), do: true + def inf?(%Decimal{}), do: false + + @doc """ + Returns `true` if argument is a decimal number, otherwise `false`. + + ## Examples + + iex> Decimal.is_decimal(Decimal.new(42)) + true + + iex> Decimal.is_decimal(42) + false + + Allowed in guard tests on OTP 21+. + """ + doc_since("1.9.0") + defmacro is_decimal(term) + + if function_exported?(:erlang, :is_map_key, 2) do + defmacro is_decimal(term) do + case __CALLER__.context do + nil -> + quote do + case unquote(term) do + %Decimal{} -> true + _ -> false + end + end + + :match -> + raise ArgumentError, + "invalid expression in match, is_decimal is not allowed in patterns " <> + "such as function clauses, case clauses or on the left side of the = operator" + + :guard -> + quote do + is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and + :erlang.map_get(:__struct__, unquote(term)) == Decimal + end + end + end + else + # TODO: remove when we require Elixir v1.10 + defmacro is_decimal(term) do + quote do + case unquote(term) do + %Decimal{} -> true + _ -> false + end + end + end + end + + @doc """ + The absolute value of given number. Sets the number's sign to positive. + + ## Examples + + iex> Decimal.abs(Decimal.new("1")) + Decimal.new("1") + + iex> Decimal.abs(Decimal.new("-1")) + Decimal.new("1") + + iex> Decimal.abs(Decimal.new("NaN")) + Decimal.new("NaN") + + """ + @spec abs(t) :: t + def abs(%Decimal{coef: :NaN} = num), do: %{num | sign: 1} + def abs(%Decimal{} = num), do: context(%{num | sign: 1}) + + @doc """ + Adds two numbers together. + + ## Exceptional conditions + + * If one number is -Infinity and the other +Infinity, `:invalid_operation` will + be signalled. + + ## Examples + + iex> Decimal.add(1, "1.1") + Decimal.new("2.1") + + iex> Decimal.add(1, "Inf") + Decimal.new("Infinity") + + """ + @spec add(decimal, decimal) :: t + def add(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1 + + def add(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2 + + def add(%Decimal{coef: :inf, sign: sign} = num1, %Decimal{coef: :inf, sign: sign} = num2) do + if num1.exp > num2.exp do + num1 + else + num2 + end + end + + def add(%Decimal{coef: :inf}, %Decimal{coef: :inf}), + do: error(:invalid_operation, "adding +Infinity and -Infinity", %Decimal{coef: :NaN}) + + def add(%Decimal{coef: :inf} = num1, %Decimal{}), do: num1 + + def add(%Decimal{}, %Decimal{coef: :inf} = num2), do: num2 + + def add(%Decimal{} = num1, %Decimal{} = num2) do + %Decimal{sign: sign1, coef: coef1, exp: exp1} = num1 + %Decimal{sign: sign2, coef: coef2, exp: exp2} = num2 + + {coef1, coef2} = add_align(coef1, exp1, coef2, exp2) + coef = sign1 * coef1 + sign2 * coef2 + exp = Kernel.min(exp1, exp2) + sign = add_sign(sign1, sign2, coef) + context(%Decimal{sign: sign, coef: Kernel.abs(coef), exp: exp}) + end + + def add(num1, num2), do: add(decimal(num1), decimal(num2)) + + @doc """ + Subtracts second number from the first. Equivalent to `Decimal.add/2` when the + second number's sign is negated. + + ## Exceptional conditions + + * If one number is -Infinity and the other +Infinity `:invalid_operation` will + be signalled. + + ## Examples + + iex> Decimal.sub(1, "0.1") + Decimal.new("0.9") + + iex> Decimal.sub(1, "Inf") + Decimal.new("-Infinity") + + """ + @spec sub(decimal, decimal) :: t + def sub(%Decimal{} = num1, %Decimal{sign: sign} = num2) do + add(num1, %{num2 | sign: -sign}) + end + + def sub(num1, num2) do + sub(decimal(num1), decimal(num2)) + end + + @doc """ + Compares two numbers numerically using a threshold. If the first number added + to the threshold is greater than the second number, and the first number + subtracted by the threshold is smaller than the second number, then the two + numbers are considered equal. + + ## Examples + + iex> Decimal.compare("1.1", 1, "0.2") + :eq + + iex> Decimal.compare("1.2", 1, "0.1") + :gt + + iex> Decimal.compare("1.0", "1.2", "0.1") + :lt + """ + @spec compare(decimal :: decimal(), decimal :: decimal(), threshold :: decimal()) :: + compare_result() + + def compare(_, _, %Decimal{sign: -1}), do: raise(Error, reason: "threshold cannot be negative") + + def compare(%Decimal{} = n1, %Decimal{} = n2, %Decimal{} = threshold) do + add_threshold = n1 |> Decimal.add(threshold) + sub_threshold = n1 |> Decimal.sub(threshold) + case1 = compare(add_threshold, n2) + case2 = compare(sub_threshold, n2) + + cond do + (case1 == :gt or case1 == :eq) and (case2 == :lt or case2 == :eq) -> :eq + case1 == :gt -> :gt + case2 == :lt -> :lt + end + end + + def compare(n1, n2, threshold), do: compare(decimal(n1), decimal(n2), decimal(threshold)) + + @doc """ + Compares two numbers numerically. If the first number is greater than the second + `:gt` is returned, if less than `:lt` is returned, if both numbers are equal + `:eq` is returned. + + Neither number can be a NaN. + + ## Examples + + iex> Decimal.compare("1.0", 1) + :eq + + iex> Decimal.compare("Inf", -1) + :gt + + """ + @spec compare(decimal, decimal) :: compare_result() + def compare(%Decimal{coef: :inf, sign: sign}, %Decimal{coef: :inf, sign: sign}), + do: :eq + + def compare(%Decimal{coef: :inf, sign: sign1}, %Decimal{coef: :inf, sign: sign2}) + when sign1 < sign2, + do: :lt + + def compare(%Decimal{coef: :inf, sign: sign1}, %Decimal{coef: :inf, sign: sign2}) + when sign1 > sign2, + do: :gt + + def compare(%Decimal{coef: :inf, sign: 1}, _num2), do: :gt + def compare(%Decimal{coef: :inf, sign: -1}, _num2), do: :lt + + def compare(_num1, %Decimal{coef: :inf, sign: 1}), do: :lt + def compare(_num1, %Decimal{coef: :inf, sign: -1}), do: :gt + + def compare(%Decimal{coef: :NaN} = num1, _num2), + do: error(:invalid_operation, "operation on NaN", num1) + + def compare(_num1, %Decimal{coef: :NaN} = num2), + do: error(:invalid_operation, "operation on NaN", num2) + + def compare(%Decimal{coef: 0}, %Decimal{coef: 0}), do: :eq + + def compare(%Decimal{sign: 1}, %Decimal{coef: 0}), do: :gt + def compare(%Decimal{coef: 0}, %Decimal{sign: 1}), do: :lt + def compare(%Decimal{sign: -1}, %Decimal{coef: 0}), do: :lt + def compare(%Decimal{coef: 0}, %Decimal{sign: -1}), do: :gt + + def compare(%Decimal{sign: 1}, %Decimal{sign: -1}), do: :gt + def compare(%Decimal{sign: -1}, %Decimal{sign: 1}), do: :lt + + def compare(%Decimal{} = num1, %Decimal{} = num2) do + adjusted_exp1 = adjust_exp(num1) + adjusted_exp2 = adjust_exp(num2) + + sign = + cond do + adjusted_exp1 == adjusted_exp2 -> + padded_num1 = pad_num(num1, num1.exp - num2.exp) + padded_num2 = pad_num(num2, num2.exp - num1.exp) + + cond do + padded_num1 == padded_num2 -> 0 + padded_num1 < padded_num2 -> -num1.sign + true -> num1.sign + end + + adjusted_exp1 < adjusted_exp2 -> + -num1.sign + + true -> + num1.sign + end + + case sign do + 0 -> :eq + 1 -> :gt + -1 -> :lt + end + end + + def compare(num1, num2) do + compare(decimal(num1), decimal(num2)) + end + + defp adjust_exp(%Decimal{coef: coef, exp: exp}) do + coef_adjustment = coef_length(coef) + exp + coef_adjustment - 1 + end + + defp coef_length(0), do: 1 + defp coef_length(coef), do: coef_length(coef, 0) + + defp coef_length(0, length), do: length + defp coef_length(coef, length), do: coef_length(Kernel.div(coef, 10), length + 1) + + defp pad_num(%Decimal{coef: coef}, n) do + coef * pow10(Kernel.max(n, 0) + 1) + end + + @deprecated "Use compare/2 instead" + @spec cmp(decimal, decimal) :: :lt | :eq | :gt + def cmp(num1, num2) do + compare(num1, num2) + end + + @doc """ + Compares two numbers numerically and returns `true` if they are equal, + otherwise `false`. If one of the operands is a quiet NaN this operation + will always return `false`. + + ## Examples + + iex> Decimal.equal?("1.0", 1) + true + + iex> Decimal.equal?(1, -1) + false + + """ + @spec equal?(decimal, decimal) :: boolean + def equal?(num1, num2) do + eq?(num1, num2) + end + + @doc """ + Compares two numbers numerically and returns `true` if they are equal, + otherwise `false`. If one of the operands is a quiet NaN this operation + will always return `false`. + + ## Examples + + iex> Decimal.eq?("1.0", 1) + true + + iex> Decimal.eq?(1, -1) + false + + """ + doc_since("1.8.0") + @spec eq?(decimal, decimal) :: boolean + def eq?(%Decimal{coef: :NaN}, _num2), do: false + def eq?(_num1, %Decimal{coef: :NaN}), do: false + def eq?(num1, num2), do: compare(num1, num2) == :eq + + @doc """ + It compares the equality of two numbers. If the second number is within + the range of first - threshold and first + threshold, it returns true; + otherwise, it returns false. + + ## Examples + + iex> Decimal.eq?("1.0", 1, "0") + true + + iex> Decimal.eq?("1.2", 1, "0.1") + false + + iex> Decimal.eq?("1.2", 1, "0.2") + true + + iex> Decimal.eq?(1, -1, "0.0") + false + + """ + @spec eq?(decimal :: decimal(), decimal :: decimal(), thresrold :: decimal()) :: boolean() + def eq?(num1, num2, thresrold), do: compare(num1, num2, thresrold) == :eq + + @doc """ + Compares two numbers numerically and returns `true` if the first argument + is greater than the second, otherwise `false`. If one the operands is a + quiet NaN this operation will always return `false`. + + ## Examples + + iex> Decimal.gt?("1.3", "1.2") + true + + iex> Decimal.gt?("1.2", "1.3") + false + + """ + doc_since("1.8.0") + @spec gt?(decimal, decimal) :: boolean + def gt?(%Decimal{coef: :NaN}, _num2), do: false + def gt?(_num1, %Decimal{coef: :NaN}), do: false + def gt?(num1, num2), do: compare(num1, num2) == :gt + + @doc """ + Compares two numbers numerically and returns `true` if the first number is + less than the second number, otherwise `false`. If one of the operands is a + quiet NaN this operation will always return `false`. + + ## Examples + + iex> Decimal.lt?("1.1", "1.2") + true + + iex> Decimal.lt?("1.4", "1.2") + false + + """ + doc_since("1.8.0") + @spec lt?(decimal, decimal) :: boolean + def lt?(%Decimal{coef: :NaN}, _num2), do: false + def lt?(_num1, %Decimal{coef: :NaN}), do: false + def lt?(num1, num2), do: compare(num1, num2) == :lt + + @doc """ + Compares two numbers numerically and returns `true` if + the first argument is greater than or equal the second, + otherwise `false`. + + If one the operands is a quiet NaN this operation + will always return `false`. + + ## Examples + + iex> Decimal.gte?("1.3", "1.3") + true + + iex> Decimal.gte?("1.3", "1.2") + true + + iex> Decimal.gte?("1.2", "1.3") + false + + """ + doc_since("2.2.0") + @spec gte?(decimal, decimal) :: boolean + + def gte?(%Decimal{coef: :NaN}, _num2), do: false + def gte?(_num1, %Decimal{coef: :NaN}), do: false + + def gte?(num1, num2) do + case compare(num1, num2) do + :gt -> true + :eq -> true + _ -> false + end + end + + @doc """ + Compares two numbers numerically and returns `true` if + the first number is less than or equal the second number, + otherwise `false`. + + If one of the operands is a quiet NaN this operation + will always return `false`. + + ## Examples + + iex> Decimal.lte?("1.1", "1.1") + true + + iex> Decimal.lte?("1.1", "1.2") + true + + iex> Decimal.lte?("1.4", "1.2") + false + + """ + doc_since("2.2.0") + @spec lte?(decimal, decimal) :: boolean + + def lte?(%Decimal{coef: :NaN}, _num2), do: false + def lte?(_num1, %Decimal{coef: :NaN}), do: false + + def lte?(num1, num2) do + case compare(num1, num2) do + :lt -> true + :eq -> true + _ -> false + end + end + + @doc """ + Divides two numbers. + + ## Exceptional conditions + + * If both numbers are ±Infinity `:invalid_operation` is signalled. + * If both numbers are ±0 `:invalid_operation` is signalled. + * If second number (denominator) is ±0 `:division_by_zero` is signalled. + + ## Examples + + iex> Decimal.div(3, 4) + Decimal.new("0.75") + + iex> Decimal.div("Inf", -1) + Decimal.new("-Infinity") + + """ + @spec div(decimal, decimal) :: t + def div(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1 + + def div(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2 + + def div(%Decimal{coef: :inf}, %Decimal{coef: :inf}), + do: error(:invalid_operation, "±Infinity / ±Infinity", %Decimal{coef: :NaN}) + + def div(%Decimal{sign: sign1, coef: :inf} = num1, %Decimal{sign: sign2}) do + sign = if sign1 == sign2, do: 1, else: -1 + %{num1 | sign: sign} + end + + def div(%Decimal{sign: sign1, exp: exp1}, %Decimal{sign: sign2, coef: :inf, exp: exp2}) do + sign = if sign1 == sign2, do: 1, else: -1 + # TODO: Subnormal + # exponent? + %Decimal{sign: sign, coef: 0, exp: exp1 - exp2} + end + + def div(%Decimal{coef: 0}, %Decimal{coef: 0}), + do: error(:invalid_operation, "0 / 0", %Decimal{coef: :NaN}) + + def div(%Decimal{sign: sign1}, %Decimal{sign: sign2, coef: 0}) do + sign = if sign1 == sign2, do: 1, else: -1 + error(:division_by_zero, nil, %Decimal{sign: sign, coef: :inf}) + end + + def div(%Decimal{} = num1, %Decimal{} = num2) do + %Decimal{sign: sign1, coef: coef1, exp: exp1} = num1 + %Decimal{sign: sign2, coef: coef2, exp: exp2} = num2 + sign = if sign1 == sign2, do: 1, else: -1 + + if coef1 == 0 do + context(%Decimal{sign: sign, coef: 0, exp: exp1 - exp2}, []) + else + prec10 = pow10(Context.get().precision) + {coef1, coef2, adjust} = div_adjust(coef1, coef2, 0) + {coef, adjust, _rem, signals} = div_calc(coef1, coef2, 0, adjust, prec10) + + context(%Decimal{sign: sign, coef: coef, exp: exp1 - exp2 - adjust}, signals) + end + end + + def div(num1, num2) do + div(decimal(num1), decimal(num2)) + end + + @doc """ + Divides two numbers and returns the integer part. + + ## Exceptional conditions + + * If both numbers are ±Infinity `:invalid_operation` is signalled. + * If both numbers are ±0 `:invalid_operation` is signalled. + * If second number (denominator) is ±0 `:division_by_zero` is signalled. + + ## Examples + + iex> Decimal.div_int(5, 2) + Decimal.new("2") + + iex> Decimal.div_int("Inf", -1) + Decimal.new("-Infinity") + + """ + @spec div_int(decimal, decimal) :: t + def div_int(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1 + + def div_int(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2 + + def div_int(%Decimal{coef: :inf}, %Decimal{coef: :inf}), + do: error(:invalid_operation, "±Infinity / ±Infinity", %Decimal{coef: :NaN}) + + def div_int(%Decimal{sign: sign1, coef: :inf} = num1, %Decimal{sign: sign2}) do + sign = if sign1 == sign2, do: 1, else: -1 + %{num1 | sign: sign} + end + + def div_int(%Decimal{sign: sign1, exp: exp1}, %Decimal{sign: sign2, coef: :inf, exp: exp2}) do + sign = if sign1 == sign2, do: 1, else: -1 + # TODO: Subnormal + # exponent? + %Decimal{sign: sign, coef: 0, exp: exp1 - exp2} + end + + def div_int(%Decimal{coef: 0}, %Decimal{coef: 0}), + do: error(:invalid_operation, "0 / 0", %Decimal{coef: :NaN}) + + def div_int(%Decimal{sign: sign1}, %Decimal{sign: sign2, coef: 0}) do + div_sign = if sign1 == sign2, do: 1, else: -1 + error(:division_by_zero, nil, %Decimal{sign: div_sign, coef: :inf}) + end + + def div_int(%Decimal{} = num1, %Decimal{} = num2) do + %Decimal{sign: sign1, coef: coef1, exp: exp1} = num1 + %Decimal{sign: sign2, coef: coef2, exp: exp2} = num2 + div_sign = if sign1 == sign2, do: 1, else: -1 + + cond do + compare(%{num1 | sign: 1}, %{num2 | sign: 1}) == :lt -> + %Decimal{sign: div_sign, coef: 0, exp: exp1 - exp2} + + coef1 == 0 -> + context(%{num1 | sign: div_sign}) + + true -> + case integer_division(div_sign, coef1, exp1, coef2, exp2) do + {:ok, result} -> + result + + {:error, error, reason, num} -> + error(error, reason, num) + end + end + end + + def div_int(num1, num2) do + div_int(decimal(num1), decimal(num2)) + end + + @doc """ + Remainder of integer division of two numbers. The result will have the sign of + the first number. + + ## Exceptional conditions + + * If both numbers are ±Infinity `:invalid_operation` is signalled. + * If both numbers are ±0 `:invalid_operation` is signalled. + * If second number (denominator) is ±0 `:division_by_zero` is signalled. + + ## Examples + + iex> Decimal.rem(5, 2) + Decimal.new("1") + + """ + @spec rem(decimal, decimal) :: t + def rem(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1 + + def rem(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2 + + def rem(%Decimal{coef: :inf}, %Decimal{coef: :inf}), + do: error(:invalid_operation, "±Infinity / ±Infinity", %Decimal{coef: :NaN}) + + def rem(%Decimal{sign: sign1, coef: :inf}, %Decimal{}), do: %Decimal{sign: sign1, coef: 0} + + def rem(%Decimal{sign: sign1}, %Decimal{coef: :inf} = num2) do + # TODO: Subnormal + # exponent? + %{num2 | sign: sign1} + end + + def rem(%Decimal{coef: 0}, %Decimal{coef: 0}), + do: error(:invalid_operation, "0 / 0", %Decimal{coef: :NaN}) + + def rem(%Decimal{sign: sign1}, %Decimal{coef: 0}), + do: error(:division_by_zero, nil, %Decimal{sign: sign1, coef: 0}) + + def rem(%Decimal{} = num1, %Decimal{} = num2) do + %Decimal{sign: sign1, coef: coef1, exp: exp1} = num1 + %Decimal{sign: sign2, coef: coef2, exp: exp2} = num2 + + cond do + compare(%{num1 | sign: 1}, %{num2 | sign: 1}) == :lt -> + %{num1 | sign: sign1} + + coef1 == 0 -> + context(%{num2 | sign: sign1}) + + true -> + div_sign = if sign1 == sign2, do: 1, else: -1 + + case integer_division(div_sign, coef1, exp1, coef2, exp2) do + {:ok, result} -> + sub(num1, mult(num2, result)) + + {:error, error, reason, num} -> + error(error, reason, num) + end + end + end + + def rem(num1, num2) do + rem(decimal(num1), decimal(num2)) + end + + @doc """ + Integer division of two numbers and the remainder. Should be used when both + `div_int/2` and `rem/2` is needed. Equivalent to: `{Decimal.div_int(x, y), + Decimal.rem(x, y)}`. + + ## Exceptional conditions + + * If both numbers are ±Infinity `:invalid_operation` is signalled. + * If both numbers are ±0 `:invalid_operation` is signalled. + * If second number (denominator) is ±0 `:division_by_zero` is signalled. + + ## Examples + + iex> Decimal.div_rem(5, 2) + {Decimal.new(2), Decimal.new(1)} + + """ + @spec div_rem(decimal, decimal) :: {t, t} + def div_rem(%Decimal{coef: :NaN} = num1, %Decimal{}), do: {num1, num1} + + def div_rem(%Decimal{}, %Decimal{coef: :NaN} = num2), do: {num2, num2} + + def div_rem(%Decimal{coef: :inf}, %Decimal{coef: :inf}) do + numbers = {%Decimal{coef: :NaN}, %Decimal{coef: :NaN}} + error(:invalid_operation, "±Infinity / ±Infinity", numbers) + end + + def div_rem(%Decimal{sign: sign1, coef: :inf} = num1, %Decimal{sign: sign2}) do + sign = if sign1 == sign2, do: 1, else: -1 + {%{num1 | sign: sign}, %Decimal{sign: sign1, coef: 0}} + end + + def div_rem(%Decimal{} = num1, %Decimal{coef: :inf} = num2) do + %Decimal{sign: sign1, exp: exp1} = num1 + %Decimal{sign: sign2, exp: exp2} = num2 + + sign = if sign1 == sign2, do: 1, else: -1 + # TODO: Subnormal + # exponent? + {%Decimal{sign: sign, coef: 0, exp: exp1 - exp2}, %{num2 | sign: sign1}} + end + + def div_rem(%Decimal{coef: 0}, %Decimal{coef: 0}) do + error = error(:invalid_operation, "0 / 0", %Decimal{coef: :NaN}) + {error, error} + end + + def div_rem(%Decimal{sign: sign1}, %Decimal{sign: sign2, coef: 0}) do + div_sign = if sign1 == sign2, do: 1, else: -1 + div_error = error(:division_by_zero, nil, %Decimal{sign: div_sign, coef: :inf}) + rem_error = error(:division_by_zero, nil, %Decimal{sign: sign1, coef: 0}) + {div_error, rem_error} + end + + def div_rem(%Decimal{} = num1, %Decimal{} = num2) do + %Decimal{sign: sign1, coef: coef1, exp: exp1} = num1 + %Decimal{sign: sign2, coef: coef2, exp: exp2} = num2 + div_sign = if sign1 == sign2, do: 1, else: -1 + + cond do + compare(%{num1 | sign: 1}, %{num2 | sign: 1}) == :lt -> + {%Decimal{sign: div_sign, coef: 0, exp: exp1 - exp2}, %{num1 | sign: sign1}} + + coef1 == 0 -> + {context(%{num1 | sign: div_sign}), context(%{num2 | sign: sign1})} + + true -> + case integer_division(div_sign, coef1, exp1, coef2, exp2) do + {:ok, result} -> + {result, sub(num1, mult(num2, result))} + + {:error, error, reason, num} -> + error(error, reason, {num, num}) + end + end + end + + def div_rem(num1, num2) do + div_rem(decimal(num1), decimal(num2)) + end + + @doc """ + Compares two values numerically and returns the maximum. Unlike most other + functions in `Decimal` if a number is NaN the result will be the other number. + Only if both numbers are NaN will NaN be returned. + + ## Examples + + iex> Decimal.max(1, "2.0") + Decimal.new("2.0") + + iex> Decimal.max(1, "NaN") + Decimal.new("1") + + iex> Decimal.max("NaN", "NaN") + Decimal.new("NaN") + + """ + @spec max(decimal, decimal) :: t + def max(%Decimal{coef: :NaN}, %Decimal{} = num2), do: num2 + + def max(%Decimal{} = num1, %Decimal{coef: :NaN}), do: num1 + + def max(%Decimal{sign: sign1, exp: exp1} = num1, %Decimal{sign: sign2, exp: exp2} = num2) do + case compare(num1, num2) do + :lt -> + num2 + + :gt -> + num1 + + :eq -> + cond do + sign1 != sign2 -> + if sign1 == 1, do: num1, else: num2 + + sign1 == 1 -> + if exp1 > exp2, do: num1, else: num2 + + sign1 == -1 -> + if exp1 < exp2, do: num1, else: num2 + end + end + |> context() + end + + def max(num1, num2) do + max(decimal(num1), decimal(num2)) + end + + @doc """ + Compares two values numerically and returns the minimum. Unlike most other + functions in `Decimal` if a number is NaN the result will be the other number. + Only if both numbers are NaN will NaN be returned. + + ## Examples + + iex> Decimal.min(1, "2.0") + Decimal.new("1") + + iex> Decimal.min(1, "NaN") + Decimal.new("1") + + iex> Decimal.min("NaN", "NaN") + Decimal.new("NaN") + + """ + @spec min(decimal, decimal) :: t + def min(%Decimal{coef: :NaN}, %Decimal{} = num2), do: num2 + + def min(%Decimal{} = num1, %Decimal{coef: :NaN}), do: num1 + + def min(%Decimal{sign: sign1, exp: exp1} = num1, %Decimal{sign: sign2, exp: exp2} = num2) do + case compare(num1, num2) do + :lt -> + num1 + + :gt -> + num2 + + :eq -> + cond do + sign1 != sign2 -> + if sign1 == -1, do: num1, else: num2 + + sign1 == 1 -> + if exp1 < exp2, do: num1, else: num2 + + sign1 == -1 -> + if exp1 > exp2, do: num1, else: num2 + end + end + |> context() + end + + def min(num1, num2) do + min(decimal(num1), decimal(num2)) + end + + @doc """ + Negates the given number. + + ## Examples + + iex> Decimal.negate(1) + Decimal.new("-1") + + iex> Decimal.negate("-Inf") + Decimal.new("Infinity") + + """ + doc_since("1.9.0") + @spec negate(decimal) :: t + def negate(%Decimal{coef: :NaN} = num), do: num + def negate(%Decimal{sign: sign} = num), do: context(%{num | sign: -sign}) + def negate(num), do: negate(decimal(num)) + + @doc """ + Applies the context to the given number rounding it to specified precision. + """ + doc_since("1.9.0") + @spec apply_context(t) :: t + def apply_context(%Decimal{} = num), do: context(num) + + @doc """ + Returns `true` if given number is positive, otherwise `false`. + + ## Examples + + iex> Decimal.positive?(Decimal.new("42")) + true + + iex> Decimal.positive?(Decimal.new("-42")) + false + + iex> Decimal.positive?(Decimal.new("0")) + false + + iex> Decimal.positive?(Decimal.new("NaN")) + false + + """ + doc_since("1.5.0") + @spec positive?(t) :: boolean + def positive?(%Decimal{coef: :NaN}), do: false + def positive?(%Decimal{coef: 0}), do: false + def positive?(%Decimal{sign: -1}), do: false + def positive?(%Decimal{sign: 1}), do: true + + @doc """ + Returns `true` if given number is negative, otherwise `false`. + + ## Examples + + iex> Decimal.negative?(Decimal.new("-42")) + true + + iex> Decimal.negative?(Decimal.new("42")) + false + + iex> Decimal.negative?(Decimal.new("0")) + false + + iex> Decimal.negative?(Decimal.new("NaN")) + false + + """ + doc_since("1.5.0") + @spec negative?(t) :: boolean + def negative?(%Decimal{coef: :NaN}), do: false + def negative?(%Decimal{coef: 0}), do: false + def negative?(%Decimal{sign: 1}), do: false + def negative?(%Decimal{sign: -1}), do: true + + @doc """ + Multiplies two numbers. + + ## Exceptional conditions + + * If one number is ±0 and the other is ±Infinity `:invalid_operation` is + signalled. + + ## Examples + + iex> Decimal.mult("0.5", 3) + Decimal.new("1.5") + + iex> Decimal.mult("Inf", -1) + Decimal.new("-Infinity") + + """ + @spec mult(decimal, decimal) :: t + def mult(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1 + + def mult(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2 + + def mult(%Decimal{coef: 0}, %Decimal{coef: :inf}), + do: error(:invalid_operation, "0 * ±Infinity", %Decimal{coef: :NaN}) + + def mult(%Decimal{coef: :inf}, %Decimal{coef: 0}), + do: error(:invalid_operation, "0 * ±Infinity", %Decimal{coef: :NaN}) + + def mult(%Decimal{sign: sign1, coef: :inf, exp: exp1}, %Decimal{sign: sign2, exp: exp2}) do + sign = if sign1 == sign2, do: 1, else: -1 + # exponent? + %Decimal{sign: sign, coef: :inf, exp: exp1 + exp2} + end + + def mult(%Decimal{sign: sign1, exp: exp1}, %Decimal{sign: sign2, coef: :inf, exp: exp2}) do + sign = if sign1 == sign2, do: 1, else: -1 + # exponent? + %Decimal{sign: sign, coef: :inf, exp: exp1 + exp2} + end + + def mult(%Decimal{} = num1, %Decimal{} = num2) do + %Decimal{sign: sign1, coef: coef1, exp: exp1} = num1 + %Decimal{sign: sign2, coef: coef2, exp: exp2} = num2 + sign = if sign1 == sign2, do: 1, else: -1 + %Decimal{sign: sign, coef: coef1 * coef2, exp: exp1 + exp2} |> context() + end + + def mult(num1, num2) do + mult(decimal(num1), decimal(num2)) + end + + @doc """ + Normalizes the given decimal: removes trailing zeros from coefficient while + keeping the number numerically equivalent by increasing the exponent. + + ## Examples + + iex> Decimal.normalize(Decimal.new("1.00")) + Decimal.new("1") + + iex> Decimal.normalize(Decimal.new("1.01")) + Decimal.new("1.01") + + """ + doc_since("1.9.0") + @spec normalize(t) :: t + def normalize(%Decimal{coef: :NaN} = num), do: num + + def normalize(%Decimal{coef: :inf} = num) do + # exponent? + %{num | exp: 0} + end + + def normalize(%Decimal{sign: sign, coef: coef, exp: exp}) do + if coef == 0 do + %Decimal{sign: sign, coef: 0, exp: 0} + else + %{do_normalize(coef, exp) | sign: sign} |> context + end + end + + @doc """ + Rounds the given number to specified decimal places with the given strategy + (default is to round to nearest one). If places is negative, at least that + many digits to the left of the decimal point will be zero. + + See `Decimal.Context` for more information about rounding algorithms. + + ## Examples + + iex> Decimal.round("1.234") + Decimal.new("1") + + iex> Decimal.round("1.234", 1) + Decimal.new("1.2") + + """ + @spec round(decimal, integer, rounding) :: t + def round(num, places \\ 0, mode \\ :half_up) + + def round(%Decimal{coef: :NaN} = num, _, _), do: num + + def round(%Decimal{coef: :inf} = num, _, _), do: num + + def round(%Decimal{} = num, n, mode) do + %Decimal{sign: sign, coef: coef, exp: exp} = normalize(num) + digits = :erlang.integer_to_list(coef) + target_exp = -n + value = do_round(sign, digits, exp, target_exp, mode) + context(value, []) + end + + def round(num, n, mode) do + round(decimal(num), n, mode) + end + + @doc """ + Finds the square root. + + ## Examples + + iex> Decimal.sqrt("100") + Decimal.new("10") + + """ + doc_since("1.7.0") + @spec sqrt(decimal) :: t + def sqrt(%Decimal{coef: :NaN} = num), + do: error(:invalid_operation, "operation on NaN", num) + + def sqrt(%Decimal{coef: 0, exp: exp} = num), + do: %{num | exp: exp >>> 1} + + def sqrt(%Decimal{sign: -1} = num), + do: error(:invalid_operation, "less than zero", num) + + def sqrt(%Decimal{sign: 1, coef: :inf} = num), + do: num + + def sqrt(%Decimal{sign: 1, coef: coef, exp: exp}) do + precision = Context.get().precision + 1 + digits = :erlang.integer_to_list(coef) + num_digits = length(digits) + + # Since the root is calculated from integer operations only, it must be + # large enough to contain the desired precision. Calculate the amount of + # `shift` required (powers of 10). + case exp &&& 1 do + 0 -> + # To get the desired `shift`, subtract the precision of `coef`'s square + # root from the desired precision. + # + # If `coef` is 10_000, the root is 100 (3 digits of precision). + # If `coef` is 100, the root is 10 (2 digits of precision). + shift = precision - ((num_digits + 1) >>> 1) + sqrt(coef, shift, exp) + + _ -> + # If `exp` is odd, multiply `coef` by 10 and reduce shift by 1/2. `exp` + # must be even so the root's exponent is an integer. + shift = precision - ((num_digits >>> 1) + 1) + sqrt(coef * 10, shift, exp) + end + end + + def sqrt(num) do + sqrt(decimal(num)) + end + + defp sqrt(coef, shift, exp) do + if shift >= 0 do + # shift `coef` up by `shift * 2` digits + sqrt(coef * pow10(shift <<< 1), shift, exp, true) + else + # shift `coef` down by `shift * 2` digits + operand = pow10(-shift <<< 1) + sqrt(Kernel.div(coef, operand), shift, exp, Kernel.rem(coef, operand) === 0) + end + end + + defp sqrt(shifted_coef, shift, exp, exact) do + # the preferred exponent is `exp / 2` as per IEEE 754 + exp = exp >>> 1 + # guess a root 10x higher than desired precision + guess = pow10(Context.get().precision + 1) + root = sqrt_loop(shifted_coef, guess) + + if exact and root * root === shifted_coef do + # if the root is exact, use preferred `exp` and shift `coef` to match + coef = + if shift >= 0, + do: Kernel.div(root, pow10(shift)), + else: root * pow10(-shift) + + context(%Decimal{sign: 1, coef: coef, exp: exp}) + else + # otherwise the calculated root is inexact (but still meets precision), + # so use the root as `coef` and get the final exponent by shifting `exp` + context(%Decimal{sign: 1, coef: root, exp: exp - shift}) + end + end + + # Babylonion method + defp sqrt_loop(coef, guess) do + quotient = Kernel.div(coef, guess) + + if guess <= quotient do + guess + else + sqrt_loop(coef, (guess + quotient) >>> 1) + end + end + + @doc """ + Creates a new decimal number from an integer or a string representation. + + A decimal number will always be created exactly as specified with all digits + kept - it will not be rounded with the context. + + ## Backus–Naur form + + sign ::= "+" | "-" + digit ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" + indicator ::= "e" | "E" + digits ::= digit [digit]... + decimal-part ::= digits "." [digits] | ["."] digits + exponent-part ::= indicator [sign] digits + infinity ::= "Infinity" | "Inf" + nan ::= "NaN" [digits] + numeric-value ::= decimal-part [exponent-part] | infinity + numeric-string ::= [sign] numeric-value | [sign] nan + + ## Floats + + See also `from_float/1`. + + ## Examples + + iex> Decimal.new(1) + Decimal.new("1") + + iex> Decimal.new("3.14") + Decimal.new("3.14") + + """ + @spec new(decimal) :: t + def new(%Decimal{sign: sign, coef: coef, exp: exp} = num) + when sign in [1, -1] and ((is_integer(coef) and coef >= 0) or coef in [:NaN, :inf]) and + is_integer(exp), + do: num + + def new(int) when is_integer(int), + do: %Decimal{sign: if(int < 0, do: -1, else: 1), coef: Kernel.abs(int)} + + def new(binary) when is_binary(binary) do + case parse(binary) do + {decimal, ""} -> decimal + _ -> raise Error, reason: "number parsing syntax: #{inspect(binary)}" + end + end + + @doc """ + Creates a new decimal number from the sign, coefficient and exponent such that + the number will be: `sign * coefficient * 10 ^ exponent`. + + A decimal number will always be created exactly as specified with all digits + kept - it will not be rounded with the context. + + ## Examples + + iex> Decimal.new(1, 42, 0) + Decimal.new("42") + + """ + @spec new(sign :: 1 | -1, coef :: non_neg_integer | :NaN | :inf, exp :: integer) :: t + def new(sign, coef, exp) + when sign in [1, -1] and ((is_integer(coef) and coef >= 0) or coef in [:NaN, :inf]) and + is_integer(exp), + do: %Decimal{sign: sign, coef: coef, exp: exp} + + @doc """ + Creates a new decimal number from a floating point number. + + Floating point numbers use a fixed number of binary digits to represent + a decimal number which has inherent inaccuracy as some decimal numbers cannot + be represented exactly in limited precision binary. + + Floating point numbers will be converted to decimal numbers with + `:io_lib_format.fwrite_g/1`. Since this conversion is not exact and + because of inherent inaccuracy mentioned above, we may run into counter-intuitive results: + + iex> Enum.reduce([0.1, 0.1, 0.1], &+/2) + 0.30000000000000004 + + iex> Enum.reduce([Decimal.new("0.1"), Decimal.new("0.1"), Decimal.new("0.1")], &Decimal.add/2) + Decimal.new("0.3") + + For this reason, it's recommended to build decimals with `new/1`, which is always precise, instead. + + ## Examples + + iex> Decimal.from_float(3.14) + Decimal.new("3.14") + + """ + doc_since("1.5.0") + @spec from_float(float) :: t + def from_float(float) when is_float(float) do + float + |> :io_lib_format.fwrite_g() + |> fix_float_exp() + |> IO.iodata_to_binary() + |> new() + end + + @doc """ + Creates a new decimal number from an integer, string, float, or existing decimal number. + + Because conversion from a floating point number is not exact, it's recommended + to instead use `new/1` or `from_float/1` when the argument's type is certain. + See `from_float/1`. + + ## Examples + + iex> {:ok, decimal} = Decimal.cast(3) + iex> decimal + Decimal.new("3") + + iex> Decimal.cast("bad") + :error + + """ + @spec cast(term) :: {:ok, t} | :error + def cast(integer) when is_integer(integer), do: {:ok, Decimal.new(integer)} + def cast(%Decimal{} = decimal), do: {:ok, decimal} + def cast(float) when is_float(float), do: {:ok, from_float(float)} + + def cast(binary) when is_binary(binary) do + case parse(binary) do + {decimal, ""} -> {:ok, decimal} + _ -> :error + end + end + + def cast(_), do: :error + + @doc """ + Parses a binary into a decimal. + + If successful, returns a tuple in the form of `{decimal, remainder_of_binary}`, + otherwise `:error`. + + ## Examples + + iex> Decimal.parse("3.14") + {%Decimal{coef: 314, exp: -2, sign: 1}, ""} + + iex> Decimal.parse("3.14.15") + {%Decimal{coef: 314, exp: -2, sign: 1}, ".15"} + + iex> Decimal.parse("-1.1e3") + {%Decimal{coef: 11, exp: 2, sign: -1}, ""} + + iex> Decimal.parse("bad") + :error + + """ + @spec parse(binary()) :: {t(), binary()} | :error + def parse("+" <> rest) do + parse_unsign(rest) + end + + def parse("-" <> rest) do + case parse_unsign(rest) do + {%Decimal{} = num, rest} -> {%{num | sign: -1}, rest} + :error -> :error + end + end + + def parse(binary) when is_binary(binary) do + parse_unsign(binary) + end + + @doc """ + Converts given number to its string representation. + + ## Options + + * `:scientific` - number converted to scientific notation. + * `:normal` - number converted without a exponent. + * `:xsd` - number converted to the [canonical XSD representation](https://www.w3.org/TR/xmlschema-2/#decimal). + * `:raw` - number converted to its raw, internal format. + + ## Examples + + iex> Decimal.to_string(Decimal.new("1.00")) + "1.00" + + iex> Decimal.to_string(Decimal.new("123e1"), :scientific) + "1.23E+3" + + iex> Decimal.to_string(Decimal.new("42.42"), :normal) + "42.42" + + iex> Decimal.to_string(Decimal.new("1.00"), :xsd) + "1.0" + + iex> Decimal.to_string(Decimal.new("4321.768"), :raw) + "4321768E-3" + + """ + @spec to_string(t, :scientific | :normal | :xsd | :raw) :: String.t() + def to_string(num, type \\ :scientific) + + def to_string(%Decimal{sign: sign, coef: :NaN}, _type) do + if sign == 1, do: "NaN", else: "-NaN" + end + + def to_string(%Decimal{sign: sign, coef: :inf}, _type) do + if sign == 1, do: "Infinity", else: "-Infinity" + end + + def to_string(%Decimal{sign: sign, coef: coef, exp: exp}, :normal) do + list = integer_to_charlist(coef) + + list = + if exp >= 0 do + list ++ :lists.duplicate(exp, ?0) + else + diff = length(list) + exp + + if diff > 0 do + List.insert_at(list, diff, ?.) + else + ~c"0." ++ :lists.duplicate(-diff, ?0) ++ list + end + end + + list = if sign == -1, do: [?- | list], else: list + IO.iodata_to_binary(list) + end + + def to_string(%Decimal{sign: sign, coef: coef, exp: exp}, :scientific) do + list = integer_to_charlist(coef) + length = length(list) + adjusted = exp + length - 1 + + list = + cond do + exp == 0 -> + list + + exp < 0 and adjusted >= -6 -> + abs_exp = Kernel.abs(exp) + diff = -length + abs_exp + 1 + + if diff > 0 do + list = :lists.duplicate(diff, ?0) ++ list + List.insert_at(list, 1, ?.) + else + List.insert_at(list, exp - 1, ?.) + end + + true -> + list = if length > 1, do: List.insert_at(list, 1, ?.), else: list + list = list ++ ~c"E" + list = if exp >= 0, do: list ++ ~c"+", else: list + list ++ integer_to_charlist(adjusted) + end + + list = if sign == -1, do: [?- | list], else: list + IO.iodata_to_binary(list) + end + + def to_string(%Decimal{sign: sign, coef: coef, exp: exp}, :raw) do + str = Integer.to_string(coef) + str = if sign == -1, do: [?- | str], else: str + str = if exp != 0, do: [str, "E", Integer.to_string(exp)], else: str + + IO.iodata_to_binary(str) + end + + def to_string(%Decimal{} = decimal, :xsd) do + decimal |> canonical_xsd() |> to_string(:normal) + end + + defp canonical_xsd(%Decimal{coef: 0} = decimal), do: %{decimal | exp: -1} + + defp canonical_xsd(%Decimal{coef: coef, exp: 0} = decimal), + do: %{decimal | coef: coef * 10, exp: -1} + + defp canonical_xsd(%Decimal{coef: coef, exp: exp} = decimal) + when exp > 0, + do: canonical_xsd(%{decimal | coef: coef * 10, exp: exp - 1}) + + defp canonical_xsd(%Decimal{coef: coef} = decimal) + when Kernel.rem(coef, 10) != 0, + do: decimal + + defp canonical_xsd(%Decimal{coef: coef, exp: exp} = decimal), + do: canonical_xsd(%{decimal | coef: Kernel.div(coef, 10), exp: exp + 1}) + + @doc """ + Returns the decimal represented as an integer. + + Fails when loss of precision will occur. + + ## Examples + + iex> Decimal.to_integer(Decimal.new("42")) + 42 + + iex> Decimal.to_integer(Decimal.new("1.00")) + 1 + + iex> Decimal.to_integer(Decimal.new("1.10")) + ** (ArgumentError) cannot convert Decimal.new("1.1") without losing precision. Use Decimal.round/3 first. + + """ + @spec to_integer(t) :: integer + def to_integer(%Decimal{sign: sign, coef: coef, exp: 0}) + when is_integer(coef), + do: sign * coef + + def to_integer(%Decimal{sign: sign, coef: coef, exp: exp}) + when is_integer(coef) and exp > 0, + do: to_integer(%Decimal{sign: sign, coef: coef * 10, exp: exp - 1}) + + def to_integer(%Decimal{sign: sign, coef: coef, exp: exp}) + when is_integer(coef) and exp < 0 and Kernel.rem(coef, 10) == 0, + do: to_integer(%Decimal{sign: sign, coef: Kernel.div(coef, 10), exp: exp + 1}) + + def to_integer(%Decimal{coef: coef} = decimal) when is_integer(coef) do + raise ArgumentError, + "cannot convert #{inspect(decimal)} without losing precision. Use Decimal.round/3 first." + end + + @doc """ + Returns the decimal converted to a float. + + The returned float may have lower precision than the decimal. Fails if + the decimal cannot be converted to a float. + + ## Examples + + iex> Decimal.to_float(Decimal.new("1.5")) + 1.5 + + """ + @spec to_float(t) :: float + def to_float(%Decimal{sign: sign, coef: coef, exp: exp}) when is_integer(coef) do + # Convert back to float without loss + # http://www.exploringbinary.com/correct-decimal-to-floating-point-using-big-integers/ + {num, den} = ratio(coef, exp) + + boundary = den <<< 52 + + cond do + num == 0 -> + 0.0 + + num >= boundary -> + {den, exp} = scale_down(num, boundary, 52) + decimal_to_float(sign, num, den, exp) + + true -> + {num, exp} = scale_up(num, boundary, 52) + decimal_to_float(sign, num, den, exp) + end + end + + @doc """ + Returns the scale of the decimal. + + A decimal's scale is the number of digits after the decimal point. This + includes trailing zeros; see `normalize/1` to remove them. + + ## Examples + + iex> Decimal.scale(Decimal.new("42")) + 0 + + iex> Decimal.scale(Decimal.new(1, 2, 26)) + 0 + + iex> Decimal.scale(Decimal.new("99.12345")) + 5 + + iex> Decimal.scale(Decimal.new("1.50")) + 2 + """ + @spec scale(t) :: non_neg_integer() + def scale(%Decimal{exp: exp}), do: Kernel.max(0, -exp) + + defp scale_up(num, den, exp) when num >= den, do: {num, exp} + defp scale_up(num, den, exp), do: scale_up(num <<< 1, den, exp - 1) + + defp scale_down(num, den, exp) do + new_den = den <<< 1 + + if num < new_den do + {den >>> 52, exp} + else + scale_down(num, new_den, exp + 1) + end + end + + defp decimal_to_float(sign, num, den, exp) do + quo = Kernel.div(num, den) + rem = num - quo * den + + tmp = + case den >>> 1 do + den when rem > den -> quo + 1 + den when rem < den -> quo + _ when (quo &&& 1) === 1 -> quo + 1 + _ -> quo + end + + sign = if sign == -1, do: 1, else: 0 + tmp = tmp - @power_of_2_to_52 + exp = if tmp < @power_of_2_to_52, do: exp, else: exp + 1 + <> = <> + tmp + end + + @doc """ + Returns `true` when the given `decimal` has no significant digits after the decimal point. + + ## Examples + + iex> Decimal.integer?("1.00") + true + + iex> Decimal.integer?("1.10") + false + + """ + doc_since("2.0.0") + @spec integer?(decimal()) :: boolean + def integer?(%Decimal{coef: :NaN}), do: false + def integer?(%Decimal{coef: :inf}), do: false + def integer?(%Decimal{coef: coef, exp: exp}), do: exp >= 0 or zero_after_dot?(coef, exp) + def integer?(num), do: integer?(decimal(num)) + + defp zero_after_dot?(coef, exp) when coef >= 10 and exp < 0, + do: Kernel.rem(coef, 10) == 0 and zero_after_dot?(Kernel.div(coef, 10), exp + 1) + + defp zero_after_dot?(coef, exp), + do: coef == 0 or exp == 0 + + ## ARITHMETIC ## + + defp add_align(coef1, exp1, coef2, exp2) when exp1 == exp2, do: {coef1, coef2} + + defp add_align(coef1, exp1, coef2, exp2) when exp1 > exp2, + do: {coef1 * pow10(exp1 - exp2), coef2} + + defp add_align(coef1, exp1, coef2, exp2) when exp1 < exp2, + do: {coef1, coef2 * pow10(exp2 - exp1)} + + defp add_sign(sign1, sign2, coef) do + cond do + coef > 0 -> 1 + coef < 0 -> -1 + sign1 == -1 and sign2 == -1 -> -1 + sign1 != sign2 and Context.get().rounding == :floor -> -1 + true -> 1 + end + end + + defp div_adjust(coef1, coef2, adjust) when coef1 < coef2, + do: div_adjust(coef1 * 10, coef2, adjust + 1) + + defp div_adjust(coef1, coef2, adjust) when coef1 >= coef2 * 10, + do: div_adjust(coef1, coef2 * 10, adjust - 1) + + defp div_adjust(coef1, coef2, adjust), do: {coef1, coef2, adjust} + + defp div_calc(coef1, coef2, coef, adjust, prec10) do + cond do + coef1 >= coef2 -> + div_calc(coef1 - coef2, coef2, coef + 1, adjust, prec10) + + coef1 == 0 and adjust >= 0 -> + {coef, adjust, coef1, []} + + coef >= prec10 -> + signals = [:rounded] + signals = if base10?(coef1), do: signals, else: [:inexact | signals] + {coef, adjust, coef1, signals} + + true -> + div_calc(coef1 * 10, coef2, coef * 10, adjust + 1, prec10) + end + end + + defp div_int_calc(coef1, coef2, coef, adjust, precision) do + cond do + coef1 >= coef2 -> + div_int_calc(coef1 - coef2, coef2, coef + 1, adjust, precision) + + adjust != precision -> + div_int_calc(coef1 * 10, coef2, coef * 10, adjust + 1, precision) + + true -> + {coef, coef1} + end + end + + defp integer_division(div_sign, coef1, exp1, coef2, exp2) do + precision = exp1 - exp2 + {coef1, coef2, adjust} = div_adjust(coef1, coef2, 0) + + {coef, _rem} = div_int_calc(coef1, coef2, 0, adjust, precision) + + prec10 = pow10(Context.get().precision) + + if coef > prec10 do + { + :error, + :invalid_operation, + "integer division impossible, quotient too large", + %Decimal{coef: :NaN} + } + else + {:ok, %Decimal{sign: div_sign, coef: coef, exp: 0}} + end + end + + defp do_normalize(coef, exp) do + if Kernel.rem(coef, 10) == 0 do + do_normalize(Kernel.div(coef, 10), exp + 1) + else + %Decimal{coef: coef, exp: exp} + end + end + + defp ratio(coef, exp) when exp >= 0, do: {coef * pow10(exp), 1} + defp ratio(coef, exp) when exp < 0, do: {coef, pow10(-exp)} + + pow10_max = + Enum.reduce(0..104, 1, fn int, acc -> + defp pow10(unquote(int)), do: unquote(acc) + defp base10?(unquote(acc)), do: true + acc * 10 + end) + + defp pow10(num) when num > 104, do: pow10(104) * pow10(num - 104) + + defp base10?(num) when num >= unquote(pow10_max) do + if Kernel.rem(num, unquote(pow10_max)) == 0 do + base10?(Kernel.div(num, unquote(pow10_max))) + else + false + end + end + + defp base10?(_num), do: false + + ## ROUNDING ## + + defp do_round(sign, digits, exp, target_exp, rounding) do + num_digits = length(digits) + precision = num_digits - (target_exp - exp) + + cond do + exp == target_exp -> + %Decimal{sign: sign, coef: digits_to_integer(digits), exp: exp} + + exp < target_exp and precision < 0 -> + zeros = :lists.duplicate(target_exp - exp, ?0) + digits = zeros ++ digits + {signif, remain} = :lists.split(1, digits) + + signif = + if increment?(rounding, sign, signif, remain), + do: digits_increment(signif), + else: signif + + coef = digits_to_integer(signif) + %Decimal{sign: sign, coef: coef, exp: target_exp} + + exp < target_exp and precision >= 0 -> + {signif, remain} = :lists.split(precision, digits) + + signif = + if increment?(rounding, sign, signif, remain), + do: digits_increment(signif), + else: signif + + coef = digits_to_integer(signif) + %Decimal{sign: sign, coef: coef, exp: target_exp} + + exp > target_exp -> + digits = digits ++ Enum.map(1..(exp - target_exp), fn _ -> ?0 end) + coef = digits_to_integer(digits) + %Decimal{sign: sign, coef: coef, exp: target_exp} + end + end + + defp digits_to_integer([]), do: 0 + defp digits_to_integer(digits), do: :erlang.list_to_integer(digits) + + defp precision(%Decimal{coef: :NaN} = num, _precision, _rounding) do + {num, []} + end + + defp precision(%Decimal{coef: :inf} = num, _precision, _rounding) do + {num, []} + end + + defp precision(%Decimal{sign: sign, coef: coef, exp: exp} = num, precision, rounding) do + digits = :erlang.integer_to_list(coef) + num_digits = length(digits) + + if num_digits > precision do + do_precision(sign, digits, num_digits, exp, precision, rounding) + else + {num, []} + end + end + + defp do_precision(sign, digits, num_digits, exp, precision, rounding) do + precision = Kernel.min(num_digits, precision) + {signif, remain} = :lists.split(precision, digits) + + signif = + if increment?(rounding, sign, signif, remain), do: digits_increment(signif), else: signif + + signals = if any_nonzero(remain), do: [:inexact, :rounded], else: [:rounded] + + exp = exp + length(remain) + coef = digits_to_integer(signif) + dec = %Decimal{sign: sign, coef: coef, exp: exp} + {dec, signals} + end + + defp increment?(_, _, _, []), do: false + + defp increment?(:down, _, _, _), do: false + + defp increment?(:up, _, _, _), do: true + + defp increment?(:ceiling, sign, _, remain), do: sign == 1 and any_nonzero(remain) + + defp increment?(:floor, sign, _, remain), do: sign == -1 and any_nonzero(remain) + + defp increment?(:half_up, _, _, [digit | _]), do: digit >= ?5 + + defp increment?(:half_even, _, [], [?5 | rest]), do: any_nonzero(rest) + + defp increment?(:half_even, _, signif, [?5 | rest]), + do: any_nonzero(rest) or Kernel.rem(:lists.last(signif), 2) == 1 + + defp increment?(:half_even, _, _, [digit | _]), do: digit > ?5 + + defp increment?(:half_down, _, _, [digit | rest]), + do: digit > ?5 or (digit == ?5 and any_nonzero(rest)) + + defp any_nonzero(digits), do: :lists.any(fn digit -> digit != ?0 end, digits) + + defp digits_increment(digits), do: digits_increment(:lists.reverse(digits), []) + + defp digits_increment([?9 | rest], acc), do: digits_increment(rest, [?0 | acc]) + + defp digits_increment([head | rest], acc), do: :lists.reverse(rest, [head + 1 | acc]) + + defp digits_increment([], acc), do: [?1 | acc] + + ## CONTEXT ## + + defp context(num, signals \\ []) do + context = Context.get() + {result, prec_signals} = precision(num, context.precision, context.rounding) + error(put_uniq(signals, prec_signals), nil, result, context) + end + + defp put_uniq(list, elems) when is_list(elems) do + Enum.reduce(elems, list, &put_uniq(&2, &1)) + end + + defp put_uniq(list, elem) do + if elem in list, do: list, else: [elem | list] + end + + ## PARSING ## + + defp parse_unsign(<>) when first in [?i, ?I] do + if String.downcase(remainder) == "nfinity" do + {%Decimal{coef: :inf}, rest} + else + :error + end + end + + defp parse_unsign(<>) when first in [?i, ?I] do + if String.downcase(remainder) == "nf" do + {%Decimal{coef: :inf}, rest} + else + :error + end + end + + defp parse_unsign(<>) when first in [?n, ?N] do + if String.downcase(remainder) == "an" do + {%Decimal{coef: :NaN}, rest} + else + :error + end + end + + defp parse_unsign(bin) do + {int, rest} = parse_digits(bin) + {float, rest} = parse_float(rest) + {exp, rest} = parse_exp(rest) + + if int == [] and float == [] do + :error + else + int = if int == [], do: ~c"0", else: int + exp = if exp == [], do: ~c"0", else: exp + + number = %Decimal{ + coef: List.to_integer(int ++ float), + exp: List.to_integer(exp) - length(float) + } + + {number, rest} + end + end + + defp parse_float("." <> rest), do: parse_digits(rest) + defp parse_float(bin), do: {[], bin} + + defp parse_exp(<>) when e in [?e, ?E] do + case rest do + <> when sign in [?+, ?-] -> + {digits, rest} = parse_digits(rest) + {[sign | digits], rest} + + _ -> + parse_digits(rest) + end + end + + defp parse_exp(bin) do + {[], bin} + end + + defp parse_digits(bin), do: parse_digits(bin, []) + + defp parse_digits(<>, acc) when digit in ?0..?9 do + parse_digits(rest, [digit | acc]) + end + + defp parse_digits(rest, acc) do + {:lists.reverse(acc), rest} + end + + # Util + + defp decimal(%Decimal{} = num), do: num + defp decimal(num) when is_integer(num), do: new(num) + defp decimal(num) when is_binary(num), do: new(num) + + defp decimal(other) when is_float(other) do + raise ArgumentError, + "implicit conversion of #{inspect(other)} to Decimal is not allowed. Use Decimal.from_float/1" + end + + defp handle_error(signals, reason, result, context) do + context = context || Context.get() + signals = List.wrap(signals) + + flags = Enum.reduce(signals, context.flags, &put_uniq(&2, &1)) + Context.set(%{context | flags: flags}) + error_signal = Enum.find(signals, &(&1 in context.traps)) + + if error_signal do + error = [signal: error_signal, reason: reason] + {:error, error} + else + {:ok, result} + end + end + + defp fix_float_exp(digits) do + fix_float_exp(digits, []) + end + + defp fix_float_exp([?e | rest], [?0 | [?. | result]]) do + fix_float_exp(rest, [?e | result]) + end + + defp fix_float_exp([digit | rest], result) do + fix_float_exp(rest, [digit | result]) + end + + defp fix_float_exp([], result), do: :lists.reverse(result) + + if Version.compare(System.version(), "1.3.0") == :lt do + defp integer_to_charlist(string), do: Integer.to_char_list(string) + else + defp integer_to_charlist(string), do: Integer.to_charlist(string) + end +end + +defimpl Inspect, for: Decimal do + def inspect(dec, _opts) do + "Decimal.new(\"" <> Decimal.to_string(dec) <> "\")" + end +end + +defimpl String.Chars, for: Decimal do + def to_string(dec) do + Decimal.to_string(dec) + end +end + +# TODO: remove when we require Elixir 1.18 +if Code.ensure_loaded?(JSON.Encoder) and function_exported?(JSON.Encoder, :encode, 2) do + defimpl JSON.Encoder, for: Decimal do + def encode(decimal, _encoder) do + [?", Decimal.to_string(decimal), ?"] + end + end +end diff --git a/deps/decimal/lib/decimal/context.ex b/deps/decimal/lib/decimal/context.ex new file mode 100644 index 0000000000000000000000000000000000000000..c1c85be33e596974e4a3682b84e7b0181f373c58 --- /dev/null +++ b/deps/decimal/lib/decimal/context.ex @@ -0,0 +1,125 @@ +defmodule Decimal.Context do + import Decimal.Macros + alias Decimal.Context + + @moduledoc """ + The context is kept in the process dictionary. It can be accessed with + `get/0` and `set/1`. + + The default context has a precision of 28, the rounding algorithm is + `:half_up`. The set trap enablers are `:invalid_operation` and + `:division_by_zero`. + + ## Fields + + * `precision` - maximum number of decimal digits in the coefficient. If an + operation result has more digits it will be rounded to `precision` + digits with the rounding algorithm in `rounding`. + * `rounding` - the rounding algorithm used when the coefficient's number of + exceeds `precision`. Strategies explained below. + * `flags` - a list of signals that for which the flag is sent. When an + exceptional condition is signalled its flag is set. The flags are sticky + and will be set until explicitly cleared. + * `traps` - a list of set trap enablers for signals. When a signal's trap + enabler is set the condition causes `Decimal.Error` to be raised. + + ## Rounding algorithms + + * `:down` - round toward zero (truncate). Discarded digits are ignored, + result is unchanged. + * `:half_up` - if the discarded digits is greater than or equal to half of + the value of a one in the next left position then the coefficient will be + incremented by one (rounded up). Otherwise (the discarded digits are less + than half) the discarded digits will be ignored. + * `:half_even` - also known as "round to nearest" or "banker's rounding". If + the discarded digits is greater than half of the value of a one in the + next left position then the coefficient will be incremented by one + (rounded up). If they represent less than half discarded digits will be + ignored. Otherwise (exactly half), the coefficient is not altered if it's + even, or incremented by one (rounded up) if it's odd (to make an even + number). + * `:ceiling` - round toward +Infinity. If all of the discarded digits are + zero or the sign is negative the result is unchanged. Otherwise, the + coefficient will be incremented by one (rounded up). + * `:floor` - round toward -Infinity. If all of the discarded digits are zero + or the sign is positive the result is unchanged. Otherwise, the sign is + negative and coefficient will be incremented by one. + * `:half_down` - if the discarded digits is greater than half of the value + of a one in the next left position then the coefficient will be + incremented by one (rounded up). Otherwise (the discarded digits are half + or less) the discarded digits are ignored. + * `:up` - round away from zero. If all discarded digits are zero the + coefficient is not changed, otherwise it is incremented by one (rounded + up). + + This table shows the results of rounding operations for all the rounding + algorithms: + + Rounding algorithm | 5.5 | 2.5 | 1.6 | 1.1 | 1.0 | -1.0 | -1.1 | -1.6 | -2.5 | -5.5 + :----------------- | :-- | :-- | :-- | :-- | :-- | :--- | :--- | :--- | :--- | :--- + `:up` | 6 | 3 | 2 | 2 | 1 | -1 | -2 | -2 | -3 | -6 + `:down` | 5 | 2 | 1 | 1 | 1 | -1 | -1 | -1 | -2 | -5 + `:ceiling` | 6 | 3 | 2 | 2 | 1 | -1 | -1 | -1 | -2 | -5 + `:floor` | 5 | 2 | 1 | 1 | 1 | -1 | -2 | -2 | -3 | -6 + `:half_up` | 6 | 3 | 2 | 1 | 1 | -1 | -1 | -2 | -3 | -6 + `:half_down` | 5 | 2 | 2 | 1 | 1 | -1 | -1 | -2 | -2 | -5 + `:half_even` | 6 | 2 | 2 | 1 | 1 | -1 | -1 | -2 | -2 | -6 + + """ + @type t :: %__MODULE__{ + precision: pos_integer, + rounding: Decimal.rounding(), + flags: [Decimal.signal()], + traps: [Decimal.signal()] + } + + defstruct precision: 28, + rounding: :half_up, + flags: [], + traps: [:invalid_operation, :division_by_zero] + + @context_key :"$decimal_context" + + @doc """ + Runs function with given context. + """ + doc_since("1.9.0") + @spec with(t(), (-> x)) :: x when x: var + def with(%Context{} = context, fun) when is_function(fun, 0) do + old = Process.put(@context_key, context) + + try do + fun.() + after + set(old || %Context{}) + end + end + + @doc """ + Gets the process' context. + """ + doc_since("1.9.0") + @spec get() :: t() + def get() do + Process.get(@context_key, %Context{}) + end + + @doc """ + Set the process' context. + """ + doc_since("1.9.0") + @spec set(t()) :: :ok + def set(%Context{} = context) do + Process.put(@context_key, context) + :ok + end + + @doc """ + Update the process' context. + """ + doc_since("1.9.0") + @spec update((t() -> t())) :: :ok + def update(fun) when is_function(fun, 1) do + get() |> fun.() |> set() + end +end diff --git a/deps/decimal/lib/decimal/error.ex b/deps/decimal/lib/decimal/error.ex new file mode 100644 index 0000000000000000000000000000000000000000..1f3b08f473aba3e080843d7cb98a4909d4b2fce2 --- /dev/null +++ b/deps/decimal/lib/decimal/error.ex @@ -0,0 +1,24 @@ +defmodule Decimal.Error do + @moduledoc """ + The exception that all decimal operations may raise. + + ## Fields + + * `signal` - the signalled error, additional signalled errors will be found + in the context. + * `reason` - the reason for the error. + + Rescuing the error to access the result or the other fields of the error is + discouraged and should only be done for exceptional conditions. It is more + pragmatic to set the appropriate traps on the context and check the flags + after the operation if the result needs to be inspected. + """ + + defexception [:signal, :reason] + + @impl true + def message(%{signal: signal, reason: reason}) do + reason = reason && ": " <> reason + "#{signal}#{reason}" + end +end diff --git a/deps/decimal/lib/decimal/macros.ex b/deps/decimal/lib/decimal/macros.ex new file mode 100644 index 0000000000000000000000000000000000000000..f8fca789c216bf92fbb999f7d61ddd3676420144 --- /dev/null +++ b/deps/decimal/lib/decimal/macros.ex @@ -0,0 +1,11 @@ +defmodule Decimal.Macros do + @moduledoc false + + defmacro doc_since(version) do + if Version.match?(System.version(), ">= 1.7.0") do + quote do + @doc since: unquote(version) + end + end + end +end diff --git a/deps/decimal/mix.exs b/deps/decimal/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..0aa3def840fc59c373c0a12c61fffd2cb7e35307 --- /dev/null +++ b/deps/decimal/mix.exs @@ -0,0 +1,43 @@ +defmodule Decimal.Mixfile do + use Mix.Project + + @version "2.3.0" + @source_url "https://github.com/ericmj/decimal" + + def project() do + [ + app: :decimal, + version: @version, + elixir: "~> 1.8", + deps: deps(), + name: "Decimal", + source_url: @source_url, + docs: [source_ref: "v#{@version}", main: "readme", extras: ["README.md"]], + description: description(), + package: package() + ] + end + + def application() do + [] + end + + defp deps() do + [ + {:ex_doc, ">= 0.0.0", only: :dev}, + {:stream_data, "~> 0.5.0", only: :test} + ] + end + + defp description() do + "Arbitrary precision decimal arithmetic." + end + + defp package() do + [ + maintainers: ["Eric Meadows-Jönsson"], + licenses: ["Apache-2.0"], + links: %{"GitHub" => @source_url} + ] + end +end diff --git a/deps/explorer/.hex b/deps/explorer/.hex new file mode 100644 index 0000000000000000000000000000000000000000..ff980c66f6cc9e57348262f49b5674fe2d3860bb Binary files /dev/null and b/deps/explorer/.hex differ diff --git a/deps/explorer/CHANGELOG.md b/deps/explorer/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..86bb49a34a6a48488f5690314104c77f62cefd8f --- /dev/null +++ b/deps/explorer/CHANGELOG.md @@ -0,0 +1,1228 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [v0.10.1] - 2024-11-28 + +### Fixed + +- Fix creation of series of `{:list, {:decimal, ...}}` containing empty lists. + +- Use `i128` for `:coef` field in the Rust code. + + This field is a positive, arbitrary precision integer on the Elixir side. + It's convenient to represent it as a signed `i128` because that's + what the Decimal dtype expects. While you could technically create an + `ExDecimal` struct with a negative `coef`, it's not a practical concern. + +- Fix `Explorer.DataFrame.print/1` for empty dataframes. + +- Fix datetime encoding overflow. + + Before we were always converting first to a microsecond-based representation + then to the final representation. The intermediate conversion is unecessary + and risks overflows when trying to convert to a different time unit later. + This approach converts directly to `i64` from the Elixir struct and time unit. + +- Encode millisecond precision for time and datetime series. + +- Fix list struct print bug. + + Fixes an issue where we can't print columns with a dtype like `{:list, {:struct, ...}}` + where the root of the tree isn't a `:struct` but it contains a `:struct`. + +### Deprecated + +- Remove documentation for deprecated functions `to_date/1` and `to_time/1`. + They are functions from the `Explorer.Series` that soon will be removed. + +## [v0.10.0] - 2024-10-23 + +### Added + +- Add support for the decimals data type. + + Decimals dtypes are represented by the `{:decimal, precision, scale}` tuple, + where precision can be a positive integer from 0 to 38, and is the maximum number + of digits that can be represented by the decimal. The scale is the number of + digits after the decimal point. + + With this addition, we also added the `:decimal` package as a new dependency. + The `Explorer.Series.from_list/2` function accepts decimal numbers from that + package as values - `%Decimal{}`. + + This version has a small number of operations, but is a good foundation. + +- Allow the usage of queries and lazy series outside callbacks and macros. + This is an improvement to functions that were originally designed to accept callbacks. + With this change you can now reuse lazy series across different "queries". + See the `Explorer.Query` docs for details. + + The affected functions are: + + * `Explorer.DataFrame.filter_with/2` + * `Explorer.DataFrame.mutate_with/2` + * `Explorer.DataFrame.sort_with/2` + * `Explorer.DataFrame.summarise_with/2` + +- Allow accessing the dataframe inside query. + +- Add "lazy read" support for Parquet and NDJSON from HTTP(s). + +- Expose more options for `Explorer.Series.cut/3` and `Explorer.Series.qcut/3`. + These options were available in Polars, but not in our APIs. + +### Fixed + +- Fix creation of series where a `nil` value inside a list - for a `{:list, any()}` dtype - + could result in an incompatible dtype. This fix will prevent panics for list of lists with + `nil` entries. + +- Fix `Explorer.DataFrame.dump_ndjson/2` when date time is in use. + +- Fix `Explorer.Series.product/1` for lazy series. + +- Accept `%FSS.HTTP.Entry{}` structs in functions like `Explorer.DataFrame.from_parquet/2`. + +- Fix encode of binaries to terms from series of the `{:struct, any()}` dtype. + In case the inner fields of the struct had any binary (`:binary` dtype), it was + causing a panic. + +### Changed + +- Change the defaults of the functions `Explorer.Series.cut/3` and `Explorer.Series.qcut/3` + to not have "break points" column in the resultant dataframe. + So the `:include_breaks` is now `false` by default. + +## [v0.9.2] - 2024-08-27 + +### Added + +- Add a new `:keep` option to the `mutate_with/3` function and `mutate/3` macro. + This option allows users to control which columns are retained in the output + dataframe after a mutation operation. You can use `:all` (the default) or `:none`. + +### Fixed + +- Fix handling of "LazySeries" with remote dataframes. +- Fix typespecs of `Explorer.Series.cast/2` by adding a `dtype_alias()` type. + +## [v0.9.1] - 2024-08-15 + +### Added + +- Add support for saving to the cloud using streaming and the IPC format. + This will enable saving a lazy frame to the cloud without loading it + entirely in memory. It only supports saves to S3-compatible storage services. + +### Changed + +- Force garbage collection on remote gc. + +### Fixed + +- Re-enable support for saving to the cloud using streaming and the Parquet format. + It's a fix from the release of `v0.9.0` that disabled this feature. + +- Fix overwrite of dtypes for `Explorer.DataFrame.load_csv/2`. + This was a regression introduced in `v0.9.0`. + +## [v0.9.0] - 2024-07-26 + +### Added + +- Add initial support for SQL queries. + + The `Explorer.DataFrame.sql/3` is a function that accepts a dataframe and + a SQL query. The SQL is not validated by Explorer, so the queries will be + backend dependent. Right now we have only Polars as the backend. + +- Add support for remote series and dataframes. + + Automatically transfer data between nodes for remote series + and dataframes and perform distributed garbage collection. + + The functions in `Explorer.DataFrame` and `Explorer.Series` + will automatically move operations on remote dataframes to + the nodes they belong to. The `Explorer.Remote` module provides + additional conveniences for manual placement. + +- Add FLAME integration, so we automatically track remote series and + dataframes returned from `FLAME` calls when the `:track_resources` + option is enabled. + See [FLAME](https://github.com/phoenixframework/flame) for more. + +- Add `Explorer.DataFrame.transform/3` that applies an Elixir function to + each row. This function is similar to `Explorer.Series.transform/2`, and + as such, it's considered an expensive operation. So it's recommended only if + there is no similar dataframe or series operation available. + +- Improve performance of `Explorer.Series.from_list/2` for most of the cases + where the `:dtype` option is given. This is specially true for when the + dtype is `:binary`. + +### Changed + +- Stop inference of _dtypes_ if the `:dtype` option is given by the user. + The main goal of this change is to improve performance. We are now delegating + the job of decoding the terms as the given `:dtype` to the backend. + +- `Explorer.Series.pow/2` no longer casts to float when the exponent is a signed + integer. We are following the way Polars works now, which is to try to execute + the operation or raise an exception in case the exponent is negative. + +- `Explorer.Series.pivot_wider/4` no longer includes the `names_from` column + name in the new columns when `values_from` is a list of columns. This is more + consistent with its behaviour when `values_from` is a single column. + +- `Explorer.Series.substring/3` no longer cycles to the end of the string if the + negative offset surpasses the beginning of that string. In that case, an empty + string is returned. + +- The `Explorer.Series.ewm_*` functions no longer replace `nil` values with the + value at the previous index. They now propogate `nil` values through to the + result series. + +- Saving a dataframe as a Parquet file to S3 services no longer works when + streaming is enabled. This is temporary due to a bug in Polars. An exception + should be raised instead. + +## [v0.8.3] - 2024-06-10 + +### Added + +- Add new data type for datetimes with timezones: `{:datetime, precision, time_zone}` + The old dtype is now `{:naive_datetime, precision}`. + +- Add option to rechunk the dataframes when using `Explorer.DataFrame.from_parquet/3` + +### Changed + +- Change the `{:datetime, precision}` dtype to `{:naive_datetime, precision}`. + The idea is to mirror Elixir's datetime, and introduce support for time zones. + Please note: `{:datetime, precision}` will work as an alias for `{:naive_datetime, precision}` for now but will raise a warning. + The alias will be removed in a future release. + +- Literal `%NaiveDateTime{}` structs used in expressions will now have `:microsecond` precision. + Previously they defaulted to `:nanosecond` precision. + This was incorrect because `%NaiveDateTime{}` structs only have `:microsecond` precision. + +### Fixed + +- Fix regression in `Explorer.DataFrame.concat_rows/2`. + It's possible to concat dataframes that are not aligned again. + +- Fix "is_finite" and "is_infinite" from `Series` to work in the context of a `Explorer.Query`. + +## [v0.8.2] - 2024-04-22 + +### Added + +- Add functions to work with strings and regexes. + + Some of the functions have the prefix "re_", because they accept a string that + represents a regular expression. + + There is an important detail: we do not accept Elixir regexes, because we cannot + guarantee that the backend supports it. Instead we accept a plain string that + is "escaped". This means that you can use the `~S` sigil to build that string. + Example: `~S/(a|b)/`. + + The added functions are the following: + + - `Explorer.Series.split_into/3` - split a string series into a struct + of string fields. This function accepts a string as a separator. + + - `Explorer.Series.re_contains/2` - check is the string series matches the regex + pattern. Like the "non regex" counterpart, it returns a boolean series. + + - `Explorer.Series.re_replace/3` - replaces all occurences of a pattern with + replacement in string series. The replacement can refer to groups captures + by using the `${x}`, where `x` is the group index (starts with 1) or name. + + - `Explorer.Series.count_matches/2` - count how many times a substring appears + in a string series. + + - `Explorer.Series.re_count_matches/2` - count how many times a pattern matches + in a string series. + + - `Explorer.Series.re_scan/2` - scan for all matches for the given regex pattern. + This is going to result in a series of lists of strings - `{:list, :string}`. + + - `Explorer.Series.re_named_captures/2` - extract all capture groups as a struct + for the given regex pattern. In case the groups are not named, their positions + are used as names. + +- Enable the usage of system certificates if OTP version 25 or above. + +- Add support for the `:streaming` option in `Explorer.DataFrame.to_csv/3`. + +- Support operations with groups in the Lazy Polars backend. This change makes + the lazy frame implementation more useful, by supporting the usage of groups in + following functions: + + - `Explorer.DataFrame.slice/3` + + - `Explorer.DataFrame.head/2` + + - `Explorer.DataFrame.tail/2` + + - `Explorer.DataFrame.filter_with/2` and the macro version of it, `filter/2`. + + - `Explorer.DataFrame.sort_with/3`, although it ignores "maintain order" + and "nulls last" options when used with groups. + + - `Explorer.DataFrame.mutate_with/2` and its macro version, `mutate/2`. + +### Changed + +- We now avoid raising an exception if a non existent column is used in + `Explorer.DataFrame.discard/2`. + +- Make the dependency of `cacerts` optional. This is because people using + Erlang/OTP 25 or above can use the certificates provided by the system. + So you may need to add the dependency of `cacerts` if your OTP version + is older than that. + +- Some precision differences in float operations may appear. This is due to + an update in the Polars version to "v0.38.1". Polars is our default backend. + +### Fixed + +- Fix `Explorer.Series.split/2` inside the context of `Explorer.Query`. + +- Add optional `X-Amz-Security-Token` header to S3 request. This is needed + in case the user is passing down a `token` for authentication. + +- Fix `Explorer.DataFrame.sort_by/3` with groups to respect `:nils` option. + This is considering only the eager implementation. + +- Fix inspection of lazy frames in remote nodes. + +## [v0.8.1] - 2024-02-24 + +### Added + +- Add `Explorer.Series.field/2` to extract a field from a struct series. + It returns a new series with the field's dtype. + +- Add `Explorer.Series.json_decode/2` that can decode a string series containing + valid JSON objects according to `dtype`. + +- Add eager `count/1` and lazy `size/1` to `Explorer.Series`. + +- Add support for maps as expressions inside `Explorer.Query`. They are "converted" + to structs. + +- Add `json_path_match/2` to extract a string series from a string containing valid + JSON objects. See the article [JSONPath - XPath for JSON](https://goessner.net/articles/JsonPath/) + for details about JSON paths. + +- Add `Explorer.Series.row_index/1` to retrieve the index of rows starting from 0. + +- Add support for passing the `:on` column directly (instead of inside a list) + in `Explorer.DataFrame.join/3`. + +### Changed + +- Remove some deprecated functions from documentation. + +- Change internal representation of the `:struct` dtype to use list of tuples instead of a map + to represent the dtypes of each field. This shouldn't break because we normalise maps to lists + when a struct dtype is passed in `from_list/2` or `cast/2`. + +- Update Rustler minimum version to `~> 0.31`. Since Rustler is optional, this shouldn't affect + most of the users. + +### Fixed + +- Fix float overflow error to avoid crashing the VM, and instead it returns an argument error. + +- Fix `Explorer.DataFrame.print/2` for when the DF contains structs. + +## [v0.8.0] - 2024-01-20 + +### Added + +- Add `explode/2` to `Explorer.DataFrame`. This function is useful to expand + the contents of a `{:list, inner_dtype}` series into a "`inner_dtype`" series. + +- Add the new series functions `all?/1` and `any?/1`, to work with boolean series. + +- Add support for the "struct" dtype. This new dtype represents the struct + dtype from Polars/Arrow. + +- Add `map/2` and `map_with/2` to the `Explorer.Series` module. + This change enables the usage of the `Explore.Query` features in a series. + +- Add `sort_by/2` and `sort_with/2` to the `Explorer.Series` module. + This change enables the usage of the lazy computations and the `Explorer.Query` + module. + +- Add `unnest/2` to `Explorer.DataFrame`. It works by taking the fields of a "struct" - + the new dtype - and transform them into columns. + +- Add pairwise correlation - `Explorer.DataFrame.correlation/2` - to calculate the + correlation between numeric columns inside a data frame. + +- Add pairwise covariance - `Explorer.DataFrame.covariance/2` - to calculate the + covariance between numeric columns inside a data frame. + +- Add support for more integer dtypes. This change introduces new signed and + unsigned integer dtypes: + - `{:s, 8}`, `{:s, 16}`, `{:s, 32}` + - `{:u, 8}`, `{:u, 16}`, `{:u, 32}`, `{:u, 64}`. + + The existing `:integer` dtype is now represented as `{:s, 64}`, and it's still + the default dtype for integers. But series and data frames can now work with the + new dtypes. Short names for these new dtypes can be used in functions like + `Explorer.Series.from_list/2`. For example, `{:u, 32}` can be represented with + the atom `:u32`. + + This may bring more interoperability with Nx, and with Arrow related things, like + ADBC and Parquet. + +- Add `ewm_standard_deviation/2` and `ewm_variance/2` to `Explorer.Series`. + They calculate the "exponentially weighted moving" variance and standard deviation. + +- Add support for `:skip_rows_after_header` option for the CSV reader functions. + +- Support `{:list, numeric_dtype}` for `Explorer.Series.frequencies/1`. + +- Support pins in `cond`, inside the context of `Explorer.Query`. + +- Introduce the `:null` dtype. This is a special dtype from Polars and Apache Arrow + to represent "all null" series. + +- Add `Explorer.DataFrame.transpose/2` to transpose a data frame. + +### Changed + +- Rename the functions related to sorting/arranging of the `Explorer.DataFrame`. + Now `arrange_with` is named `sort_with`, and `arrange` is `sort_by`. + + The `sort_by/3` is a macro and it is going to work using the `Explorer.Query` + module. On the other side, the `sort_with/2` uses a callback function. + +- Remove unnecessary casts to `{:s, 64}` now that we support more integer dtypes. + It affects some functions, like the following in the `Explorer.Series` module: + + - `argsort` + - `count` + - `rank` + - `day_of_week`, `day_of_year`, `week_of_year`, `month`, `year`, `hour`, `minute`, `second` + - `abs` + - `clip` + - `lengths` + - `slice` + - `n_distinct` + - `frequencies` + + And also some functions from the `Explorer.DataFrame` module: + + - `mutate` - mostly because of series changes + - `summarise` - mostly because of series changes + - `slice` + +### Fixed + +- Fix inspection of series and data frames between nodes. + +- Fix cast of `:string` series to `{:datetime, any()}` + +- Fix mismatched types in `Explorer.Series.pow/2`, making it more consistent. + +- Normalize sorting options. + +- Fix functions with dtype mismatching the result from Polars. + This fix is affecting the following functions: + + - `quantile/2` in the context of a lazy series + - `mode/1` inside a summarisation + - `strftime/2` in the context of a lazy series + - `mutate_with/2` when creating a column from a `NaiveDateTime` or `Explorer.Duration`. + +## [v0.7.2] - 2023-11-30 + +### Added + +- Add the functions `day_of_year/1` and `week_of_year/1` to `Explorer.Series`. + +- Add `filter/2` - a macro -, and `filter_with/2` to `Explorer.Series`. + + This change enables the usage of queries - using `Explorer.Query` - when + filtering a series. The main difference is that series does not have a + name when used outside a dataframe. So to refer to itself inside the + query, we can use the special `_` variable. + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.filter(s, _ > 2) + #Explorer.Series< + Polars[1] + integer [3] + > + +- Add support for the `{:list, any()}` dtype, where `any()` can be any other + valid dtype. This is a recursive dtype, that can represent nested lists. + It's useful to group data together in the same series. + +- Add `Explorer.Series.mode/2` to get the most common value(s) of the series. + +- Add `split/2` and `join/2` to the `Explorer.Series` module. + These functions are useful to split string series into `{:list, :string}`, + or to join parts of a `{:list, :string}` and return a `:string` series. + +- Expose `ddof` option for variance, covariance and standard deviation. + +- Add a new `{:f, 32}` dtype to represent 32 bits float series. + It's also possible to use the atom `:f32` to create this type of series. + The atom `:f64` can be used as an alias for `{:f, 64}`, just like the + `:float` atom. + +- Add `lengths/1` and `member?/2` to `Explorer.Series`. + These functions work with `{:list, any()}`, where `any()` is any valid dtype. + The idea is to count the members of a "list" series, and check if a given + value is member of a list series, respectively. + +- Add support for streaming parquet files from a lazy dataframe to AWS S3 + compatible services. + +### Changed + +- Remove restriction on `pivot_wider` dtypes. + In the early days, Polars only supported numeric dtypes for the "first" + aggregation. This is not true anymore, and we can lift this restriction. + +- Change `:float` dtype to be represented as `{:f, 64}`. It's still possible + to use the atom `:float` to create float series, but now `Explorer.Series.dtype/1` + returns `{:f, 64}` for float 64 bits series. + +### Fixed + +- Add missing implementation of `Explorer.Series.replace/3` for lazy series. + +- Fix inspection of DFs and series when `limit: :infinity` is used. + +### Removed + +- Drop support for the `riscv64gc-unknown-linux-gnu` target. + + We decided to stop precompiling to this target because it's been hard to maintain it. + Ideally we should support it again in the future. + +## [v0.7.1] - 2023-09-25 + +### Added + +- Add more temporal arithmetic operations. This change makes possible + to mix some datatypes, like `date`, `duration` and scalar types like + `integers` and `floats`. + + The following operations are possible now: + + * `date - date` + * `date + duration` + * `date - duration` + * `duration + date` + * `duration * integer` + * `duration * float` + * `duration / integer` + * `duration / float` + * `integer * duration` + * `float * duration` + +- Support lazy dataframes on `Explorer.DataFrame.print/2`. + +- Add support for strings as the "indexes" of `Explorer.Series.categorise/2`. + This makes possible to categorise a string series with a categories series. + +- Introduce `cond/1` support in queries, which enables multi-clause conditions. + Example of usage: + + iex> df = DF.new(a: [10, 4, 6]) + iex> DF.mutate(df, + ...> b: + ...> cond do + ...> a > 9 -> "Exceptional" + ...> a > 5 -> "Passed" + ...> true -> "Failed" + ...> end + ...> ) + #Explorer.DataFrame< + Polars[3 x 2] + a integer [10, 4, 6] + b string ["Exceptional", "Failed", "Passed"] + > + +- Similar to `cond/1`, this version also introduces support for the `if/2` + and `unless/2` macros inside queries. + +- Allow the usage of scalar booleans inside queries. + +- Add `Explorer.Series.replace/3` for string series. + This enables the replacement of patterns inside string series. + +### Deprecated + +- Deprecate `Explorer.DataFrame.to_lazy/1` in favor of just `lazy/1`. + +### Fixed + +- Fix the `Explorer.Series.in/2` function to work with series of the + `:category` dtype. + + Now, if both series shares the same categories, we can compare them. + To make sure that a categorical series shares the same categories from + another series, you must create that series using the + `Explorer.Series.categorise/2` function. + +- Display the dtype of duration series correctly in `Explorer.DataFrame.print/2`. + +## [v0.7.0] - 2023-08-28 + +### Added + +- Enable reads and writes of dataframes from/to external file systems. + + It supports HTTP(s) URLs or AWS S3 locations. + + This feature introduces the [FSS](https://github.com/elixir-explorer/fss) abstraction, + which is also going to be present in newer versions of Kino. This is going to make the integration + of Livebook files with Explorer much easier. + + The implementation is done differently, depending on which file format is used, and if + it's a read or write. All the writes to AWS S3 are done in the Rust side - using an abstraction + called `CloudWriter` -, and most of the readers are implemented in Elixir, by doing a download + of the files, and then loading the dataframe from it. The only exception is the reads of + parquet files, which are done in Rust, using Polars' `scan_parquet` with streaming. + + We want to give a special thanks to [Qqwy / Marten](https://github.com/Qqwy) for the + `CloudWriter` implementation! + +- Add ADBC: Arrow Database Connectivity. + + Continuing with improvements in the IO area, we added support for reading dataframes from + databases using ADBC, which is similar in idea to ODBC, but integrates much better with + Apache Arrow, that is the backbone of Polars - our backend today. + + The function `Explorer.DataFrame.from_query/1` is the entrypoint for this feature, and it + allows quering databases like PostgreSQL, SQLite and Snowflake. + + Check the [Elixir ADBC bindings docs](https://hexdocs.pm/adbc) for more information. + + For the this feature, we had a fundamental contribution from [Cocoa](https://github.com/cocoa-xu) + in the ADBC bindings, so we want to say a special thanks to her! + + We want to thank the people that joined José in [his live streamings on Twitch](https://www.twitch.tv/josevalim), + and helped to build this feature! + +- Add the following functions to `Explorer.Series`: + - [`window_median/3`](https://hexdocs.pm/explorer/Explorer.Series.html#window_median/3) + - [`substring/3`](https://hexdocs.pm/explorer/Explorer.Series.html#substring/3) + +- Add duration dtypes. This is adds the following dtypes: + - `{:duration, :nanosecond}` + - `{:duration, :microsecond}` + - `{:duration, :millisecond}` + + This feature was a great contribution from [Billy Lanchantin](https://github.com/billylanchantin), + and we want to thank him for this! + +### Changed + +- Return exception structs instead of strings for all IO operation errors, and for anything + that returns an error from the NIF integration. + + This change makes easier to define which type of error we want to raise. + +- Update Polars to v0.32. + + With that we made some minor API changes, like changing some options for `cut/qcut` operations + in the `Explorer.Series` module. + +- Use `nil_values` instead of `null_character` for IO operations. + +- Never expect `nil` for CSV IO dtypes. + +- Rename `Explorer.DataFrame.table/2` to `Explorer.DataFrame.print/2`. + +- Change `:datetime` dtype to be `{:datetime, time_unit}`, where time unit can be + the following: + - `:millisecond` + - `:microsecond` + - `:nanosecond` + +- Rename the following `Series` functions: + - `trim/1` to `strip/2` + - `trim_leading/1` to `lstrip/2` + - `trim_trailing/1` to `rstrip/2` + + These functions now support a string argument. + +### Fixed + +- Fix warnings for the upcoming Elixir v1.16. + +- Fix `Explorer.Series.abs/1` type specs. + +- Allow comparison of strings with categories. + +- Fix `Explorer.Series.is_nan/1` inside the context of `Explorer.Query`. + The NIF function was not being exported. + +## [v0.6.1] - 2023-07-06 + +### Fixed + +- Fix summarise without groups for lazy frames. + +## [v0.6.0] - 2023-07-05 + +### Added + +- Add support for OTP 26 and Elixir 1.15. + +- Allow `Explorer.DataFrame.summarise/2` to work without groups. + The aggregations can work considering the entire dataframe. + +- Add the following series functions: `product/1`, `cummulative_product/1`, `abs/1`, + `skew/2`, `window_standard_deviation/3`, `rank/2`, `year/1`, `mounth/1`, `day/1`, + `hour/1`, `minute/1`, `second/1`, `strptime/2`, `strftime/2`, `argmin/1`, `argmax/1`, + `cut/3`, `qcut/3`, `correlation/3`, `covariance/2` and `clip/3`. + + They cover a lot in terms of functionality, so please check the `Explorer.Series` + docs for further details. + +- Add `Explorer.DataFrame.nil_count/1` that counts the number of nil elements in each + column. + +- Add `Explorer.DataFrame.frequencies/2` that creates a new dataframe with unique rows + and the frequencies of each. + +- Add `Explorer.DataFrame.relocate/3` that enables changing order of columns from a df. + +- Add precompiled NIFs for FreeBSD. + +- Support scalar values in the `on_true` and `on_false` arguments of `Explore.Series.select/3`. + +### Fixed + +- Fix `Series.day_of_week/1` and `Series.round/2` for operations using a lazy frame. + +- Fix upcasted date to datetime for literal expressions. It allows to use scalar dates + in expressions like this: `DF.mutate(a: ~D[2023-01-01])`. This also fixes the support + for naive datetimes. + +- Improve error messages returned from the NIF to be always strings. Now we add more + context to the string returned, instead of having `{:context, error_message}`. + +- Fix the `:infer_schema_length` option of `Explorer.DataFrame.from_csv/2` when passing `nil`. + Now it's possible to take into account the entire file to infer the schema. + + +### Deprecated + +- Deprecate `Explorer.Series.to_date/1` and `Explorer.Series.to_time/1` in favor of + using `Explorer.Series.cast(s, :date)` and `Explorer.Series.cast(s, :time)` respectively. + +## [v0.5.7] - 2023-05-10 + +### Added + +- Allow `Explorer.Series.select/3` to receive series of size 1 in both sides. + +- Add trigonometric functions `sin/1`, `cos/1`, `tan/1`, `asin/1`, `acos/1` and + `atan/1` to `Explorer.Series`. + +- Add `Explorer.DataFrame.to_rows_stream/2` function. This is useful to traverse + dataframes with large series, but is not recommended since it can be an expensive + operation. + +- Add LazyFrame version of `Explorer.DataFrame.to_ipc/3`. + +- Add options to control streaming when writing lazy dataframes. Now users can + toggle streaming for the `to_ipc/3` and `to_parquet/3` functions. + +- Add `Explorer.DataFrame.from_ipc_stream/2` lazy, but using the eager implementation + underneath. + +- Add option to control the end of line (EOF) char when reading CSV files. + We call this new option `:eol_delimiter`, and it's available for the `from_csv/2` + and `load_csv/2` functions in the `Explorer.DataFrame` module. + +- Allow `Explorer.DataFrame.pivot_wider/4` to use category fields. + +### Fixed + +- Fix `nif_not_loaded` error when `Explorer.Series.ewm_mean/2` is called from query. + +- Type check arguments for boolean series operations, only allowing series of + the `boolean` dtype. + +- Do not use `../0` in order to keep compatible with Elixir 1.13 + +### Removed + +- Temporarely remove support for ARM 32 bits computers in the precompilation + workflow. + +## [v0.5.6] - 2023-03-24 + +### Added + +- Add the following functions to the `Explorer.Series` module: `log/1`, `log/2` + and `exp/1`. They compute the logarithm and exponential of a series. + +### Fixed + +- Allow `Explorer.Series.select/3` to receive series of size 1 for both the + `on_true` and `on_false` arguments. + +- Fix the encoding of special float values that may return from some series + functions. This is going to encode the atoms for NaN and infinity values. + +## [v0.5.5] - 2023-03-13 + +### Added + +- Add support for multiple value columns in pivot wider. + The resultant dataframe that is created from this type of pivoting is going + to have columns with the names prefixed by the original value column, followed + by an underscore and the name of the variable. + +- Add `Explorer.Series.ewm_mean/2` for calculating exponentially weighted moving + average. + +### Changed + +- Change the `Explorer.Backend.DataFrame`'s `pivot_wider` callback to work with + multiple columns instead of only one. + +- Change the `Explorer.Backend.DataFrame`'s `window_*` callbacks to work with + variables instead of keyword args. This is needed to make explicit when a backend + is not implementing an option. + +- Change the `Explorer.Backend.DataFrame`'s `describe` callback and remove the + need for an "out df", since we won't have a lazy version of that funcion. + +- This shouldn't affect the API, but we had an update in Polars. + It is now using `v0.27.2`. For further details, see: + [Rust Polars 0.27.0](https://github.com/pola-rs/polars/releases/tag/rs-0.27.0). + +### Fixed + +- Provide hints when converting string/binary series to tensors. + +- Add libatomic as a link to the generated NIF. This is needed to fix the load + of the Explorer NIF when running on ARM 32 bits machines like the Pi 3. + See the [original issue](https://github.com/philss/rustler_precompiled/issues/53) + +## [v0.5.4] - 2023-03-09 + +### Fixed + +- Fix missing "README.md" file in the list of package files. + Our readme is now required in compilation, because it contains the moduledoc for + the main `Explorer` module. + +## [v0.5.3] - 2023-03-08 + +### Added + +- Add the `Explorer.Series.format/1` function that concatenates multiple series together, + always returning a string series. + +- With the addition of `format/1`, we also have a new operator for string concatenation + inside `Explorer.Query`. It is the `<>` operator, that is similar to what the `Kernel.<>/2` + operator does, but instead of concatenating strings, it concatenates two series, returning + a string series - it is using `format/1` underneath. + +- Add support for slicing by series in dataframes and other series. + +- Add support for 2D tensors in `Explorer.DataFrame.new/2`. + +### Fixed + +- Fix `Explorer.DataFrame.new/2` to respect the selected dtype when an entire series is nil. + +- Improve error message for mismatched dtypes in series operations. + +- Fix lazy series operations of binary series and binary values. This is going to wrap binary + values in the correct dtype, in order to pass down to Polars. + +- Fix two bugs in `Explorer.DataFrame.pivot_wider/3`: `nil` values in the series that is + used for new column names is now correctly creating a `nil` column. We also fixed the problem + of a duplicated column created after pivoting, and possibly conflicting with an existing + ID column. We add a suffix for these columns. + +## [v0.5.2] - 2023-02-28 + +### Added + +- Add `across` and comprehensions to `Explorer.Query`. These features allow a + more flexible and elegant way to work with multiple columns at once. Example: + + ```elixir + iris = Explorer.Datasets.iris() + Explorer.DataFrame.mutate(iris, + for col <- across(["sepal_width", "sepal_length", "petal_length", "petal_width"]) do + {col.name, (col - mean(col)) / variance(col)} + end + ) + ``` + + See the `Explorer.Query` documentation for further details. + +- Add support for regexes to select columns of a dataframe. Example: + + ```elixir + df = Explorer.Datasets.wine() + df[~r/(class|hue)/] + ``` + +- Add the `:max_rows` and `:columns` options to `Explorer.DataFrame.from_parquet/2`. This mirrors + the `from_csv/2` function. + +- Allow `Explorer.Series` functions that accept floats to work with `:nan`, `:infinity` + and `:neg_infinity` values. + +- Add `Explorer.DataFrame.shuffle/2` and `Explorer.Series.shuffle/2`. + +- Add support for a list of filters in `Explorer.DataFrame.filter/2`. These filters are + joined as `and` expressions. + +### Fixed + +- Add `is_integer/1` guard to `Explorer.Series.shift/2`. +- Raise if series sizes do not match for binary operations. + +### Changed + +- Rename the option `:replacement` to `:replace` for `Explorer.DataFrame.sample/3` and + `Explorer.Series.sample/3`. + +- Change the default behaviour of sampling to not shuffle by default. A new option + named `:shuffle` was added to control that. + +## [v0.5.1] - 2023-02-17 + +### Added + +- Add boolean dtype to `Series.in/2`. +- Add binary dtype to `Series.in/2`. +- Add `Series.day_of_week/1`. + +- Allow `Series.fill_missing/2` to: + - receive `:infinity` and `:neg_infinity` values. + - receive date and datetime values. + - receive binary values. + +- Add support for `time` dtype. +- Add version of `Series.pow/2` that accepts series on both sides. +- Allow `Series.from_list/2` to receive `:nan`, `:infinity` and `:neg_infinity` atoms. +- Add `Series.to_date/1` and `Series.to_time/1` for datetime series. +- Allow casting of string series to category. +- Accept tensors when creating a new dataframe. +- Add compatibility with Nx v0.5. +- Add support for Nx's serialize and deserialize. + +- Add the following function implementations for the Polars' Lazy dataframe backend: + - `arrange_with` + - `concat_columns` + - `concat_rows` + - `distinct` + - `drop_nil` + - `filter_with` + - `join` + - `mutate_with` + - `pivot_longer` + - `rename` + - `summarise_with` + - `to_parquet` + + Only `summarise_with` supports groups for this version. + +### Changed + +- Require version of Rustler to be `~> 0.27.0`, which mirrors the NIF requirement. + +### Fixed + +- Casting to an unknown dtype returns a better error message. + +## [v0.5.0] - 2023-01-12 + +### Added + +- Add `DataFrame.describe/2` to gather some statistics from a dataframe. +- Add `Series.nil_count/1` to count nil values. +- Add `Series.in/2` to check if a given value is inside a series. +- Add `Series` float predicates: `is_finite/1`, `is_infinite/1` and `is_nan/1`. +- Add `Series` string functions: `contains/2`, `trim/1`, `trim_leading/1`, `trim_trailing/1`, + `upcase/1` and `downcase/1`. + +- Enable slicing of lazy frames (`LazyFrame`). +- Add IO operations "from/load" to the lazy frame implementation. +- Add support for the `:lazy` option in the `DataFrame.new/2` function. +- Add `Series` float rounding methods: `round/2`, `floor/1` and `ceil/1`. +- Add support for precompiling to Linux running on RISCV CPUs. +- Add support for precompiling to Linux - with musl - running on AARCH64 computers. +- Allow `DataFrame.new/1` to receive the `:dtypes` option. +- Accept `:nan` as an option for `Series.fill_missing/2` with float series. +- Add basic support for the categorical dtype - the `:category` dtype. +- Add `Series.categories/1` to return categories from a categorical series. +- Add `Series.categorise/2` to categorise a series of integers using predefined categories. +- Add `Series.replace/2` to replace the contents of a series. +- Support selecting columns with unusual names (like with spaces) inside `Explorer.Query` + with `col/1`. + + The usage is like this: + + ```elixir + Explorer.DataFrame.filter(df, col("my col") > 42) + ``` + +### Fixed + +- Fix `DataFrame.mutate/2` using a boolean scalar value. +- Stop leaking `UInt32` series to Elixir. +- Cast numeric columns to our supported dtypes after IO read. + This fix is only applied for the eager implementation for now. + +### Changed + +- Rename `Series.bintype/1` to `Series.iotype/1`. + +## [v0.4.0] - 2022-11-29 + +### Added + +- Add `Series.quotient/2` and `Series.remainder/2` to work with integer division. +- Add `Series.iotype/1` to return the underlying representation type. +- Allow series on both sides of binary operations, like: `add(series, 1)` + and `add(1, series)`. + +- Allow comparison, concat and coalesce operations on "(series, lazy series)". +- Add lazy version of `Series.sample/3` and `Series.size/1`. +- Add support for Arrow IPC Stream files. +- Add `Explorer.Query` and the macros that allow a simplified query API. + This is a huge improvement to some of the main functions, and allow refering to + columns as they were variables. + + Before this change we would need to write a filter like this: + + ```elixir + Explorer.DataFrame.filter_with(df, &Explorer.Series.greater(&1["col1"], 42)) + ``` + + But now it's also possible to write this operation like this: + + ```elixir + Explorer.DataFrame.filter(df, col1 > 42) + ``` + + This operation is going to use `filter_with/2` underneath, which means that + is going to use lazy series and compute the results at once. + Notice that is mandatory to "require" the DataFrame module, since these operations + are implemented as macros. + + The following new macros were added: + - `filter/2` + - `mutate/2` + - `summarise/2` + - `arrange/2` + + They substitute older versions that did not accept the new query syntax. + +- Add `DataFrame.put/3` to enable adding or replacing columns in a eager manner. + This works similar to the previous version of `mutate/2`. + +- Add `Series.select/3` operation that enables selecting a value + from two series based on a predicate. + +- Add "dump" and "load" functions to IO operations. They are useful to load + or dump dataframes from/to memory. + +- Add `Series.to_iovec/2` and `Series.to_binary/1`. They return the underlying + representation of series as binary. The first one returns a list of binaries, + possibly with one element if the series is contiguous in memory. The second one + returns a single binary representing the series. + +- Add `Series.shift/2` that shifts the series by an offset with nil values. +- Rename `Series.fetch!/2` and `Series.take_every/2` to `Series.at/2` + and `Series.at_every/2`. + +- Add `DataFrame.discard/2` to drop columns. This is the opposite of `select/2`. + +- Implement `Nx.LazyContainer` for `Explorer.DataFrame` and `Explorer.Series` + so data can be passed into Nx. + +- Add `Series.not/1` that negates values in a boolean series. +- Add the `:binary` dtype for Series. This enables the usage of arbitrary binaries. + +### Changed + +- Change DataFrame's `to_*` functions to return only `:ok`. +- Change series inspect to resamble the dataframe inspect with the backend name. +- Rename `Series.var/1` to `Series.variance/1` +- Rename `Series.std/1` to `Series.standard_deviation/1` +- Rename `Series.count/2` to `Series.frequencies/1` and add a new `Series.count/1` + that returns the size of an "eager" series, or the count of members in a group + for a lazy series. + In case there is no groups, it calculates the size of the dataframe. +- Change the option to control direction in `Series.sort/2` and `Series.argsort/2`. + Instead of a boolean, now we have a new option called `:direction` that accepts + `:asc` or `:desc`. + +### Fixed + +- Fix the following DataFrame functions to work with groups: + - `filter_with/2` + - `head/2` + - `tail/2` + - `slice/2` + - `slice/3` + - `pivot_longer/3` + - `pivot_wider/4` + - `concat_rows/1` + - `concat_columns/1` +- Improve the documentation of functions that behave differently with groups. +- Fix `arrange_with/2` to use "group by" stable, making results more predictable. +- Add `nil` as a possible return value of aggregations. +- Fix the behaviour of `Series.sort/2` and `Series.argsort/2` to add nils at the + front when direction is descending, or at the back when the direction is ascending. + This also adds an option to control this behaviour. + +### Removed + +- Remove support for `NDJSON` read and write for ARM 32 bits targets. + This is due to a limitation of a dependency of Polars. + +## [v0.3.1] - 2022-09-09 + +### Fixed + +- Define `multiply` inside `*_with` operations. +- Fix column types in several operations, such as `n_distinct`. + +## [v0.3.0] - 2022-09-01 + +### Added + +- Add `DataFrame.concat_columns/1` and `DataFrame.concat_columns/2` for horizontally stacking + dataframes. +- Add compression as an option to write parquet files. +- Add count metadata to `DataFrame` table reader. +- Add `DataFrame.filter_with/2`, `DataFrame.summarise_with/2`, `DataFrame.mutate_with/2` and +`DataFrame.arrange_with/2`. They all accept a `DataFrame` and a function, and they all work with + a new concept called "lazy series". + + Lazy Series is an opaque representation of a series that can be + used to perform complex operations without pulling data from the series. This is faster than + using masks. There is no big difference from the API perspective compared to the functions that were + accepting callbacks before (eg. `filter/2` and the new `filter_with/2`), with the exception being + `DataFrame.summarise_with/2` that now accepts a lot more operations. + +### Changed + +- Bump version requirement of the `table` dependency to `~> 0.1.2`, and raise for non-tabular values. +- Normalize how columns are handled. This changes some functions to accept one column or +a list of columns, ranges, indexes and callbacks selecting columns. +- Rename `DataFrame.filter/2` to `DataFrame.mask/2`. +- Rename `Series.filter/2` to `Series.mask/2`. +- Rename `take/2` from both `Series` and `DataFrame` to `slice/2`. `slice/2` now they accept ranges as well. +- Raise an error if `DataFrame.pivot_wider/4` has float columns as IDs. This is because we can´t +properly compare floats. +- Change `DataFrame.distinct/2` to accept columns as argument instead of receiving it as option. + +### Fixed + +- Ensure that we can compare boolean series in functions like `Series.equal/2`. +- Fix rename of columns after summarise. +- Fix inspect of float series containing `NaN` or `Infinity` values. They are represented as atoms. + +### Deprecated + +- Deprecate `DataFrame.filter/2` with a callback in favor of `DataFrame.filter_with/2`. + +## [v0.2.0] - 2022-06-22 + +### Added + +- Consistently support ranges throughout the columns API +- Support negative indexes throughout the columns API +- Integrate with the `table` package +- Add `Series.to_enum/1` for lazily traversing the series +- Add `Series.coalesce/1` and `Series.coalesce/2` for finding the first non-null value in a list of series + +### Changed + +- `Series.length/1` is now `Series.size/1` in keeping with Elixir idioms +- `Nx` is now an optional dependency +- Minimum Elixir version is now 1.13 +- `DataFrame.to_map/2` is now `DataFrame.to_columns/2` and `DataFrame.to_series/2` +- `Rustler` is now an optional dependency +- `read_` and `write_` IO functions are now `from_` and `to_` +- `to_binary` is now `dump_csv` +- Now uses `polars`'s "simd" feature +- Now uses `polars`'s "performant" feature +- `Explorer.default_backend/0` is now `Explorer.Backend.get/0` +- `Explorer.default_backend/1` is now `Explorer.Backend.put/1` +- `Series.cum_*` functions are now `Series.cumulative_*` to mirror `Nx` +- `Series.rolling_*` functions are now `Series.window_*` to mirror `Nx` +- `reverse?` is now an option instead of an argument in `Series.cumulative_*` functions +- `DataFrame.from_columns/2` and `DataFrame.from_rows/2` is now `DataFrame.new/2` +- Rename "col" to "column" throughout the API +- Remove "with\_" prefix in options throughout the API +- `DataFrame.table/2` accepts options with `:limit` instead of single integer +- `rename/2` no longer accepts a function, use `rename_with/2` instead +- `rename_with/3` now expects the function as the last argument + +### Fixed + +- Explorer now works on Linux with musl + +## [v0.1.1] - 2022-04-27 + +### Security + +- Updated Rust dependencies to address Dependabot security alerts: [1](https://github.com/elixir-explorer/explorer/security/dependabot/1), [2](https://github.com/elixir-explorer/explorer/security/dependabot/3), [3](https://github.com/elixir-explorer/explorer/security/dependabot/4) + +## [v0.1.0] - 2022-04-26 + +First release. + +[Unreleased]: https://github.com/elixir-explorer/explorer/compare/v0.10.1...HEAD +[v0.10.1]: https://github.com/elixir-explorer/explorer/compare/v0.10.0...v0.10.1 +[v0.10.0]: https://github.com/elixir-explorer/explorer/compare/v0.9.2...v0.10.0 +[v0.9.2]: https://github.com/elixir-explorer/explorer/compare/v0.9.1...v0.9.2 +[v0.9.1]: https://github.com/elixir-explorer/explorer/compare/v0.9.0...v0.9.1 +[v0.9.0]: https://github.com/elixir-explorer/explorer/compare/v0.8.3...v0.9.0 +[v0.8.3]: https://github.com/elixir-explorer/explorer/compare/v0.8.2...v0.8.3 +[v0.8.2]: https://github.com/elixir-explorer/explorer/compare/v0.8.1...v0.8.2 +[v0.8.1]: https://github.com/elixir-explorer/explorer/compare/v0.8.0...v0.8.1 +[v0.8.0]: https://github.com/elixir-explorer/explorer/compare/v0.7.2...v0.8.0 +[v0.7.2]: https://github.com/elixir-explorer/explorer/compare/v0.7.1...v0.7.2 +[v0.7.1]: https://github.com/elixir-explorer/explorer/compare/v0.7.0...v0.7.1 +[v0.7.0]: https://github.com/elixir-explorer/explorer/compare/v0.6.1...v0.7.0 +[v0.6.1]: https://github.com/elixir-explorer/explorer/compare/v0.6.0...v0.6.1 +[v0.6.0]: https://github.com/elixir-explorer/explorer/compare/v0.5.7...v0.6.0 +[v0.5.7]: https://github.com/elixir-explorer/explorer/compare/v0.5.6...v0.5.7 +[v0.5.6]: https://github.com/elixir-explorer/explorer/compare/v0.5.5...v0.5.6 +[v0.5.5]: https://github.com/elixir-explorer/explorer/compare/v0.5.4...v0.5.5 +[v0.5.4]: https://github.com/elixir-explorer/explorer/compare/v0.5.3...v0.5.4 +[v0.5.3]: https://github.com/elixir-explorer/explorer/compare/v0.5.2...v0.5.3 +[v0.5.2]: https://github.com/elixir-explorer/explorer/compare/v0.5.1...v0.5.2 +[v0.5.1]: https://github.com/elixir-explorer/explorer/compare/v0.5.0...v0.5.1 +[v0.5.0]: https://github.com/elixir-explorer/explorer/compare/v0.4.0...v0.5.0 +[v0.4.0]: https://github.com/elixir-explorer/explorer/compare/v0.3.1...v0.4.0 +[v0.3.1]: https://github.com/elixir-explorer/explorer/compare/v0.3.0...v0.3.1 +[v0.3.0]: https://github.com/elixir-explorer/explorer/compare/v0.2.0...v0.3.0 +[v0.2.0]: https://github.com/elixir-explorer/explorer/compare/v0.1.1...v0.2.0 +[v0.1.1]: https://github.com/elixir-explorer/explorer/compare/v0.1.0...v0.1.1 +[v0.1.0]: https://github.com/elixir-explorer/explorer/releases/tag/v0.1.0 diff --git a/deps/explorer/LICENSE b/deps/explorer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1882b3908cc2a3bbc97e7efa9f5bde7353672733 --- /dev/null +++ b/deps/explorer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Amplified AI, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/deps/explorer/README.md b/deps/explorer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ee3478ab5de3d785d13c8de7b2bad489d9972c51 --- /dev/null +++ b/deps/explorer/README.md @@ -0,0 +1,307 @@ +

Explorer

+ +![CI](https://github.com/elixir-nx/explorer/actions/workflows/ci.yml/badge.svg) +[![Documentation](http://img.shields.io/badge/hex.pm-docs-green.svg?style=flat)](https://hexdocs.pm/explorer) +[![Package](https://img.shields.io/hexpm/v/explorer.svg)](https://hex.pm/packages/explorer) + + + +Explorer brings series (one-dimensional) and dataframes (two-dimensional) for fast +data exploration to Elixir. + +## Features and design + +Explorer high-level features are: + +- Simply typed series: `:binary`, `:boolean`, `:category`, `:date`, `:datetime`, + `:duration`, floats of 32 and 64 bits (`{:f, size}`), integers of 8, 16, 32 + and 64 bits (`{:s, size}`, `{:u, size}`), `:null`, `:string`, `:time`, `:list`, + and `:struct`. + +- A powerful but constrained and opinionated API, so you spend less time looking + for the right function and more time doing data manipulation. + +- Support for CSV, Parquet, NDJSON, and Arrow IPC formats + +- Integration with external databases via [ADBC](https://github.com/elixir-explorer/adbc) + and direct connection to file storages such as S3 + +- Pluggable backends, providing a uniform API whether you're working in-memory + or (forthcoming) on remote databases or even Spark dataframes. + +- The first (and default) backend is based on NIF bindings to the blazing-fast + [polars](https://docs.rs/polars) library. + +The API is heavily influenced by [Tidy Data](https://vita.had.co.nz/papers/tidy-data.pdf) +and borrows much of its design from [dplyr](https://dplyr.tidyverse.org). The philosophy +is heavily influenced by this passage from `dplyr`'s documentation: + +> - By constraining your options, it helps you think about your data manipulation +> challenges. +> +> - It provides simple “verbs”, functions that correspond to the most common data +> manipulation tasks, to help you translate your thoughts into code. +> +> - It uses efficient backends, so you spend less time waiting for the computer. + +The aim here isn't to have the fastest dataframe library around (though it certainly +helps that [we're building on Polars, one of the fastest](https://h2oai.github.io/db-benchmark/)). +Instead, we're aiming to bridge the best of many worlds: + +- the elegance of `dplyr` +- the speed of `polars` +- the joy of Elixir + +That means you can expect the guiding principles to be 'Elixir-ish'. For example, +you won't see the underlying data mutated, even if that's the most efficient implementation. +Explorer functions will always return a new dataframe or series. + +## Getting started + +Inside an Elixir script or [Livebook](https://livebook.dev): + +```elixir +Mix.install([ + {:explorer, "~> 0.10.0"} +]) +``` + +Or in the `mix.exs` file of your application: + +```elixir +def deps do + [ + {:explorer, "~> 0.10.0"} + ] +end +``` + +Explorer will download a precompiled version of its native code upon installation. You can force a local build by setting the environment variable `EXPLORER_BUILD=1` and including `:rustler` as a dependency: + +```elixir + {:explorer, "~> 0.10.0", system_env: %{"EXPLORER_BUILD" => "1"}}, + {:rustler, ">= 0.0.0"} +``` + +If necessary, clean up before rebuilding with `mix deps.clean explorer`. + +## A glimpse of the API + +We have two ways to represent data with Explorer: + +- using a series, that is similar to a list, but is guaranteed to contain items + of one data type only - or one *dtype* for short. Notice that nil values are + permitted in series of any dtype. + +- using a dataframe, that is just a way to represent one or more series together, + and work with them as a whole. The only restriction is that all the series share + the same size. + +A series can be created from a list: + +```elixir +fruits = Explorer.Series.from_list(["apple", "mango", "banana", "orange"]) +``` + +Your newly created series is going to look like: + +``` +#Explorer.Series< + Polars[4] + string ["apple", "mango", "banana", "orange"] +> +``` + +And you can, for example, sort that series: + +```elixir +Explorer.Series.sort(fruits) +``` + +Resulting in the following: + +``` +#Explorer.Series< + Polars[4] + string ["apple", "banana", "mango", "orange"] +> +``` + +### Dataframes + +Dataframes can be created in two ways: + +- by reading from files or memory using the + [IO functions](https://hexdocs.pm/explorer/Explorer.DataFrame.html#module-io-operations). + This is by far the most common way to load dataframes in Explorer. + We accept Parquet, IPC, CSV, and NDJSON files. + +- by using the `Explorer.DataFrame.new/2` function, that is neat for small experiments. + We are going to use this function here. + +You can pass either series or lists to it: + +```elixir +mountains = Explorer.DataFrame.new(name: ["Everest", "K2", "Aconcagua"], elevation: [8848, 8611, 6962]) +``` + +Your dataframe is going to look like this: + +``` +#Explorer.DataFrame< + Polars[3 x 2] + name string ["Everest", "K2", "Aconcagua"] + elevation s64 [8848, 8611, 6962] +> +``` + +It's also possible to see a dataframe like a table, using the `Explorer.DataFrame.print/2` +function: + +```elixir +Explorer.DataFrame.print(mountains) +``` + +Prints: + +``` ++-------------------------------------------+ +| Explorer DataFrame: [rows: 3, columns: 2] | ++---------------------+---------------------+ +| name | elevation | +| | | ++=====================+=====================+ +| Everest | 8848 | ++---------------------+---------------------+ +| K2 | 8611 | ++---------------------+---------------------+ +| Aconcagua | 6962 | ++---------------------+---------------------+ +``` + +And now I want to show you how to filter our dataframe. But first, let's require +the `Explorer.DataFrame` module and give a short name to it: + +```elixir +require Explorer.DataFrame, as: DF +``` + +The "require" is needed to load the macro features of that module. +We give it a shorter name to simplify our examples. + +Now let's go to the filter. I want to filter the mountains that are above +the mean elevation in our dataframe: + +```elixir +DF.filter(mountains, elevation > mean(elevation)) +``` + +You can see that we can refer to the columns using their names, and use functions +without defining them. This is possible due to the powerful `Explorer.Query` features, +and it's the main reason we need to "require" the `Explorer.DataFrame` module. + +The result is going to look like this: + +``` +#Explorer.DataFrame< + Polars[2 x 2] + name string ["Everest", "K2"] + elevation s64 [8848, 8611] +> +``` + +There is an extensive guide that you can play with Livebook: +[Ten Minutes to Explorer](https://hexdocs.pm/explorer/exploring_explorer.html) + +You can also check the `Explorer.DataFrame` and `Explorer.Series` docs for further +details. + + + +## Contributing + +Explorer uses Rust for its default backend implementation, and while Rust is not +necessary to use Explorer as a package, you need Rust tooling installed on your +machine if you want to compile from source, which is the case when contributing +to Explorer. + +We require Rust Nightly, which can be installed with [Rustup](https://rust-lang.github.io/rustup/installation/index.html). +If you already have Rustup and a recent version of Cargo installed, then the correct version of +Rust is going to be installed in the first compilation of the project. Otherwise, you can manually +install the correct version: + +```sh +rustup toolchain install nightly-2024-07-26 +``` + +You can also use [asdf](https://asdf-vm.com/): + +```sh +asdf install rust nightly-2024-07-26 +``` + +It's possible that you may need to install [`CMake`](https://cmake.org/) in order to build the project, +if that is not already installed. + +Once you have made your changes, run `mix ci`, to lint and format both Elixir +and Rust code. + +Our integration tests require the [AWS CLI to be installed](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html), +and also a container engine that can be [Podman](https://podman.io) or [Docker](https://docker.com). + +Once these dependencies are installed, you need to run the `mix localstack.setup` command, +and then run the cloud integration tests with `mix test --only cloud_integration`. + +Just to recap, here is the combo of commands you need to run: + +```sh +mix ci +mix localstack.setup +mix test --only cloud_integration +``` + +## Precompilation + +Explorer ships with the NIF code precompiled for the most popular architectures out there. +We support the following: + +- `aarch64-apple-darwin` - MacOS running on ARM 64 bits CPUs. +- `aarch64-unknown-linux-gnu` - Linux running on ARM 64 bits CPUs, compiled with GCC. +- `aarch64-unknown-linux-musl` - Linux running on ARM 64 bits CPUs, compiled with Musl. +- `x86_64-apple-darwin` - MacOS running on Intel/AMD 64 bits CPUs. +- `x86_64-pc-windows-msvc` - Windows running on Intel/AMD 64 bits CPUs, compiled with Visual C++. +- `x86_64-pc-windows-gnu` - Windows running on Intel/AMD 64 bits CPUs, compiled with GCC. +- `x86_64-unknown-linux-gnu` - Linux running on Intel/AMD 64 bits CPUs, compiled with GCC. +- `x86_64-unknown-linux-musl` - Linux running on Intel/AMD 64 bits CPUs, compiled with Musl. +- `x86_64-unknown-freebsd` - FreeBSD running on Intel/AMD 64 bits. + +This means that Explorer is going to work without the need to compile it from source. + +This currently **only works for Hex releases**. For more information on how it works, please +check the [RustlerPrecompiled project](https://hexdocs.pm/rustler_precompiled). + +### Legacy CPUs + +We ship some of the precompiled artifacts with modern CPU features enabled by default. But in +case your computer is not compatible with them, you can set an application environment that is +going to be read at compile time, enabling the legacy variants of artifacts. + +```elixir +config :explorer, use_legacy_artifacts: true +``` + +If you see the error message "Illegal instruction" after your project compiles, you need to +enable the legacy artifacts. + +### Features disabled + +Some of the features cannot be compiled to some targets, because one of the dependencies +don't work on it. + +This is the case for the **NDJSON** reads and writes, that don't work for the RISCV target. +We also disable the AWS S3 reads and writes for the RISCV target, because one of the dependencies +of `ObjectStore` does not compile on it. + +## Sponsors + +Amplified diff --git a/deps/explorer/checksum-Elixir.Explorer.PolarsBackend.Native.exs b/deps/explorer/checksum-Elixir.Explorer.PolarsBackend.Native.exs new file mode 100644 index 0000000000000000000000000000000000000000..5fd017d8f43e109ae7c39181deba1ec96e812f72 --- /dev/null +++ b/deps/explorer/checksum-Elixir.Explorer.PolarsBackend.Native.exs @@ -0,0 +1,15 @@ +%{ + "explorer-v0.10.1-nif-2.15-x86_64-pc-windows-gnu--legacy_cpu.dll.tar.gz" => "sha256:d5b411a209e215a435557c17320084efd01f3d8d409c4c62f3cd8ecf24cea2ec", + "explorer-v0.10.1-nif-2.15-x86_64-pc-windows-gnu.dll.tar.gz" => "sha256:afa33f6285fc1f2bec84ae4d40a405d6be2956643372650b0c80d5d22b09c5f9", + "explorer-v0.10.1-nif-2.15-x86_64-pc-windows-msvc--legacy_cpu.dll.tar.gz" => "sha256:48efe024015f4210f80858d91a35f0b5018b55af1221b7ce8b3ec03762d9402c", + "explorer-v0.10.1-nif-2.15-x86_64-pc-windows-msvc.dll.tar.gz" => "sha256:4c1cf15bda0d706535fe83c647f0f0870c9cfe4d912112aee529e49887c05c74", + "libexplorer-v0.10.1-nif-2.15-aarch64-apple-darwin.so.tar.gz" => "sha256:4c7302413bad0625f99433712cb43105134f280526dd51a0a6967c0f1ed674c4", + "libexplorer-v0.10.1-nif-2.15-aarch64-unknown-linux-gnu.so.tar.gz" => "sha256:90fbd41ff49ea5f002e9b7a5d81998a8a08999526526c2a48ba0d0c93931af75", + "libexplorer-v0.10.1-nif-2.15-aarch64-unknown-linux-musl.so.tar.gz" => "sha256:7530142224f105c8be1c406b32d735a7b45a9c9a68b70317c711f22d3098d2d0", + "libexplorer-v0.10.1-nif-2.15-x86_64-apple-darwin.so.tar.gz" => "sha256:d4d38fbe70c40ed8d46111ce0b87a6ad3b8faad224e36b9f8c30396f5e4c4739", + "libexplorer-v0.10.1-nif-2.15-x86_64-unknown-freebsd--legacy_cpu.so.tar.gz" => "sha256:c4e0256845332d111bdf0b4c02f0654f4a28f0dbfea8695cb6547b864391731b", + "libexplorer-v0.10.1-nif-2.15-x86_64-unknown-freebsd.so.tar.gz" => "sha256:167de9dd4aa75864d453cf31daed8d28da3977ae9c5cc1eee445331cb0a45336", + "libexplorer-v0.10.1-nif-2.15-x86_64-unknown-linux-gnu--legacy_cpu.so.tar.gz" => "sha256:aa6554366140259ef9dec5ef197d70a838f7ff7e26797da34fd0dd2ebe49d7ef", + "libexplorer-v0.10.1-nif-2.15-x86_64-unknown-linux-gnu.so.tar.gz" => "sha256:ea3146648bec7e1ad30956e4609a5522a15db026c33e51a95c23d90064a1541c", + "libexplorer-v0.10.1-nif-2.15-x86_64-unknown-linux-musl.so.tar.gz" => "sha256:5c049bd578ef80814863a04fbfb56a593b273dae3aa5e7e8f4da62ffd6e84b9d", +} diff --git a/deps/explorer/datasets/fossil_fuels.csv b/deps/explorer/datasets/fossil_fuels.csv new file mode 100644 index 0000000000000000000000000000000000000000..55b167bd85d037e61f53f88e4f643967d1282428 --- /dev/null +++ b/deps/explorer/datasets/fossil_fuels.csv @@ -0,0 +1,1095 @@ +year,country,total,solid_fuel,liquid_fuel,gas_fuel,cement,gas_flaring,per_capita,bunker_fuels +2010,AFGHANISTAN,2308,627,1601,74,5,0,0.08,9 +2010,ALBANIA,1254,117,953,7,177,0,0.43,7 +2010,ALGERIA,32500,332,12381,14565,2598,2623,0.9,663 +2010,ANDORRA,141,0,141,0,0,0,1.68,0 +2010,ANGOLA,7924,0,3649,374,204,3697,0.37,321 +2010,ANGUILLA,41,0,41,0,0,0,2.98,0 +2010,ANTIGUA & BARBUDA,143,0,143,0,0,0,1.64,39 +2010,ARGENTINA,51246,1089,24606,23725,1418,407,1.24,1542 +2010,ARMENIA,1150,3,275,806,66,0,0.39,37 +2010,ARUBA,684,0,684,0,0,0,6.73,74 +2010,AUSTRALIA,106589,56257,31308,17763,1129,132,4.81,3307 +2010,AUSTRIA,18408,3537,9218,5073,579,0,2.19,575 +2010,AZERBAIJAN,8366,6,2373,4904,174,909,0.92,398 +2010,BAHAMAS,451,1,450,0,0,0,1.25,179 +2010,BAHRAIN,7981,0,1123,6696,163,0,6.33,545 +2010,BANGLADESH,16345,839,2881,10753,1873,0,0.11,313 +2010,BARBADOS,403,0,363,8,31,1,1.44,108 +2010,BELARUS,17192,620,4620,11336,616,0,1.81,0 +2010,BELGIUM,30222,3787,14993,10613,829,0,2.77,7916 +2010,BELIZE,147,0,143,3,0,0,0.46,11 +2010,BENIN,1388,0,1211,0,177,0,0.15,127 +2010,BERMUDA,166,0,166,0,0,0,2.59,50 +2010,BHUTAN,133,21,85,0,27,0,0.19,1 +2010,BOSNIA & HERZEGOVINA,5802,4332,1217,125,129,0,1.51,4 +2010,BOTSWANA,1278,576,667,0,35,0,0.62,14 +2010,BRAZIL,114468,15965,74689,14372,8040,1402,0.58,5101 +2010,BRITISH VIRGIN ISLANDS,47,0,47,0,0,0,1.72,0 +2010,BRUNEI (DARUSSALAM),2237,0,434,1672,37,94,5.69,167 +2010,BULGARIA,12030,7284,3042,1437,267,0,1.62,223 +2010,BURKINA FASO,535,0,455,0,80,0,0.03,30 +2010,BURUNDI,58,5,53,0,0,0,0.01,4 +2010,CAMBODIA,1367,9,1252,0,107,0,0.1,32 +2010,CANADA,145806,24504,69694,49114,1691,804,4.27,1518 +2010,CAPE VERDE,152,0,152,0,0,0,0.31,71 +2010,CAYMAN ISLANDS,152,0,152,0,0,0,2.75,9 +2010,CENTRAL AFRICAN REPUBLIC,72,0,72,0,0,0,0.02,27 +2010,CHAD,141,0,141,0,0,0,0.01,15 +2010,CHILE,19703,4510,11861,2791,526,14,1.16,768 +2010,CHINA (MAINLAND),2393248,1792793,298191,54472,247792,0,1.78,11687 +2010,COLOMBIA,20773,3677,9507,6001,1293,295,0.45,1122 +2010,COMOROS,44,0,44,0,0,0,0.06,2 +2010,CONGO,540,0,476,53,11,0,0.13,38 +2010,COOK ISLANDS,19,0,19,0,0,0,0.95,2 +2010,COSTA RICA,2064,63,1828,0,174,0,0.45,0 +2010,COTE D IVOIRE,1900,0,826,829,245,0,0.09,64 +2010,CROATIA,5501,704,2815,1644,338,0,1.27,86 +2010,CUBA,10465,21,9659,562,222,0,0.93,140 +2010,CYPRUS,2102,19,1901,0,181,0,1.9,391 +2010,CZECH REPUBLIC,30428,19505,5423,5040,460,0,2.9,259 +2010,DEMOCRATIC PEOPLE S REPUBLIC OF KOREA,18122,16591,701,0,830,0,0.74,0 +2010,DEMOCRATIC REPUBLIC OF THE CONGO (FORMERLY ZAIRE),551,0,471,12,67,0,0.01,126 +2010,DENMARK,12719,4172,5504,2762,211,70,2.29,1272 +2010,DJIBOUTI,141,0,141,0,0,0,0.17,88 +2010,DOMINICA,38,0,38,0,0,0,0.53,2 +2010,DOMINICAN REPUBLIC,5733,505,4262,408,558,0,0.58,357 +2010,ECUADOR,9943,0,8517,397,719,310,0.67,708 +2010,EGYPT,55281,1126,25725,22366,6065,0,0.67,2602 +2010,EL SALVADOR,1761,0,1586,0,175,0,0.29,92 +2010,EQUATORIAL GUINEA,1276,0,166,827,0,283,1.75,30 +2010,ERITREA,140,0,134,0,6,0,0.03,1 +2010,ESTONIA,4938,4158,378,351,51,0,3.71,224 +2010,ETHIOPIA,1796,36,1537,0,223,0,0.02,233 +2010,FAEROE ISLANDS,172,0,172,0,0,0,3.53,26 +2010,FALKLAND ISLANDS (MALVINAS),15,3,12,0,0,0,5.22,0 +2010,FEDERATED STATES OF MICRONESIA,31,0,31,0,0,0,0.3,1 +2010,FIJI,333,0,310,1,22,0,0.39,139 +2010,FINLAND,16930,7388,6980,2397,165,0,3.15,630 +2010,FRANCE (INCLUDING MONACO),96273,12332,54960,26569,2412,0,1.53,6636 +2010,FRENCH GUIANA,174,0,162,0,12,0,0.75,32 +2010,FRENCH POLYNESIA,234,0,234,0,0,0,0.87,50 +2010,GABON,1312,0,537,168,30,577,0.85,248 +2010,GAMBIA,118,0,116,1,0,0,0.07,15 +2010,GEORGIA,1722,218,754,634,117,0,0.41,34 +2010,GERMANY,206943,83574,71983,47408,3972,6,2.57,9078 +2010,GHANA,2715,0,2208,221,286,0,0.11,169 +2010,GIBRALTAR,127,0,127,0,0,0,4.14,3666 +2010,GREECE,22868,8457,11130,2020,1260,0,2.05,2973 +2010,GREENLAND,181,0,181,0,0,0,3.2,34 +2010,GRENADA,71,0,71,0,0,0,0.68,4 +2010,GUADELOUPE,627,112,474,0,41,0,1.37,91 +2010,GUATEMALA,3181,356,2445,0,380,0,0.22,293 +2010,GUINEA,710,0,678,0,32,0,0.06,21 +2010,GUINEA BISSAU,65,0,65,0,0,0,0.04,9 +2010,GUYANA,469,0,469,0,0,0,0.62,8 +2010,HAITI,580,0,539,0,41,0,0.06,17 +2010,HONDURAS,2175,124,1833,0,218,0,0.29,40 +2010,HONG KONG SPECIAL ADMINSTRATIVE REGION OF CHINA,11093,6438,2688,1768,199,0,1.59,13595 +2010,HUNGARY,13696,2958,4318,6131,290,0,1.37,196 +2010,ICELAND,535,93,423,0,19,0,1.68,152 +2010,INDIA,468964,298209,112969,27357,29920,509,0.38,4035 +2010,INDONESIA,116924,35295,53405,20123,5369,2733,0.48,248 +2010,IRAQ,30596,0,21668,4044,1088,3796,0.99,0 +2010,IRELAND,10923,2201,5469,2930,324,0,2.37,671 +2010,ISLAMIC REPUBLIC OF IRAN,156267,1487,62100,75661,8296,8723,2.1,3088 +2010,ISRAEL,18784,7661,7673,2751,699,0,2.53,944 +2010,ITALY (INCLUDING SAN MARINO),110543,14655,48702,42507,4679,0,1.85,5284 +2010,JAMAICA,1990,31,1861,0,98,0,0.73,224 +2010,JAPAN,319505,119676,139083,53738,7008,0,2.51,8339 +2010,JORDAN,5776,0,3813,1429,534,0,0.89,119 +2010,KAZAKHSTAN,67780,35784,12921,18166,909,0,4.16,174 +2010,KENYA,3320,171,2644,0,505,0,0.08,576 +2010,KIRIBATI,17,0,17,0,0,0,0.16,3 +2010,KUWAIT,24441,0,16377,7678,272,114,7.99,1072 +2010,KYRGYZSTAN,1741,732,752,154,103,0,0.32,230 +2010,LAO PEOPLE S DEMOCRATIC REPUBLIC,447,181,104,0,163,0,0.07,9 +2010,LATVIA,2202,112,1091,913,86,0,1.05,316 +2010,LEBANON,5467,154,4470,132,711,0,1.26,213 +2010,LESOTHO,621,478,143,0,0,0,0.31,0 +2010,LIBERIA,216,0,206,0,10,0,0.05,15 +2010,LIBYAN ARAB JAMAHIRIYAH,16897,0,10515,3602,952,1829,2.7,486 +2010,LIECHTENSTEIN,15,0,0,15,0,0,0.4,0 +2010,LITHUANIA,3673,219,1785,1556,113,0,1.18,164 +2010,LUXEMBOURG,2991,78,2019,747,147,0,5.89,358 +2010,MACAU SPECIAL ADMINSTRATIVE REGION OF CHINA,384,0,303,81,0,0,0.72,0 +2010,MACEDONIA,2346,1426,749,60,112,0,1.14,6 +2010,MADAGASCAR,534,29,483,0,22,0,0.03,54 +2010,MALAWI,312,46,240,0,26,0,0.02,6 +2010,MALAYSIA,59579,15103,20006,16596,2688,5186,2.12,1432 +2010,MALDIVES,255,0,255,0,0,0,0.77,39 +2010,MALI,263,0,263,0,0,0,0.02,18 +2010,MALTA,698,0,698,0,0,0,1.69,1365 +2010,MARSHALL ISLANDS,28,0,28,0,0,0,0.54,0 +2010,MARTINIQUE,548,0,528,0,20,0,1.39,117 +2010,MAURITANIA,610,0,535,0,75,0,0.17,15 +2010,MAURITIUS,1068,429,639,0,0,0,0.86,300 +2010,MEXICO,126618,13934,70873,33876,4692,3243,1.07,2875 +2010,MONGOLIA,3769,3051,674,0,44,0,1.39,0 +2010,MONTENEGRO,704,443,261,0,0,0,1.13,2 +2010,MONTSERRAT,18,0,18,0,0,0,3.55,1 +2010,MOROCCO,15260,3609,9391,356,1904,0,0.47,490 +2010,MOZAMBIQUE,746,7,577,42,120,0,0.03,55 +2010,MYANMAR (FORMERLY BURMA),3413,160,2046,1130,73,3,0.07,17 +2010,NAMIBIA,846,76,769,0,1,0,0.39,32 +2010,NAURU,12,0,12,0,0,0,1.17,4 +2010,NEPAL,1379,301,893,0,185,0,0.05,68 +2010,NETHERLAND ANTILLES,1244,0,1244,0,0,0,5.99,2061 +2010,NETHERLANDS,49919,6902,18219,24487,291,20,3.0,14837 +2010,NEW CALEDONIA,966,332,612,0,22,0,3.92,28 +2010,NEW ZEALAND,8667,1416,4672,2329,150,101,1.98,907 +2010,NICARAGUA,1237,0,1155,0,82,0,0.22,15 +2010,NIGER,320,90,226,0,4,0,0.02,11 +2010,NIGERIA,24957,28,10028,5512,1360,8029,0.16,498 +2010,NIUE,1,0,1,0,0,0,0.52,0 +2010,NORWAY,16391,790,10300,4843,177,282,3.35,693 +2010,OCCUPIED PALESTINIAN TERRITORY,555,0,555,0,0,0,0.14,0 +2010,OMAN,12931,0,2331,9309,612,679,4.39,1342 +2010,PAKISTAN,44013,4756,16989,18188,4080,0,0.26,286 +2010,PALAU,69,0,69,0,0,0,3.35,14 +2010,PANAMA,2499,70,2225,0,203,0,0.69,2916 +2010,PAPUA NEW GUINEA,1299,0,1193,79,27,0,0.19,64 +2010,PARAGUAY,1390,0,1302,0,88,0,0.22,22 +2010,PERU,15706,772,6330,3433,1142,4029,0.53,732 +2010,PHILIPPINES,23144,7697,11356,1929,2162,0,0.25,1020 +2010,PLURINATIONAL STATE OF BOLIVIA,4146,0,2178,1595,328,45,0.42,38 +2010,POLAND,86246,58230,17902,7998,2111,5,2.24,612 +2010,PORTUGAL,13127,1719,7981,2803,624,0,1.24,1138 +2010,QATAR,19773,0,4149,14573,514,537,11.2,942 +2010,REPUBLIC OF CAMEROON,1849,0,1551,162,136,0,0.09,92 +2010,REPUBLIC OF KOREA,154545,76263,47701,24131,6449,0,3.15,10794 +2010,REPUBLIC OF MOLDOVA,1345,89,593,541,122,0,0.33,11 +2010,REUNION,1137,503,593,0,41,0,1.37,56 +2010,ROMANIA,21656,7489,6489,6738,940,0,1.07,134 +2010,RUSSIAN FEDERATION,455558,107603,93687,239553,6854,7861,3.18,6514 +2010,RWANDA,161,0,147,0,13,0,0.02,13 +2010,SAINT HELENA,3,0,3,0,0,0,0.8,0 +2010,SAINT LUCIA,110,0,110,0,0,0,0.62,5 +2010,SAMOA,51,0,51,0,0,0,0.27,9 +2010,SAO TOME & PRINCIPE,27,0,27,0,0,0,0.16,9 +2010,SAUDI ARABIA,141394,0,98157,37412,5825,0,5.03,3920 +2010,SENEGAL,2112,184,1362,13,553,0,0.16,244 +2010,SERBIA,12532,8412,2616,1158,347,0,1.38,35 +2010,SEYCHELLES,121,0,121,0,0,0,1.3,158 +2010,SIERRA LEONE,198,0,157,0,41,0,0.03,7 +2010,SINGAPORE,15174,7,10661,4506,0,0,2.99,39109 +2010,SLOVAKIA,9883,4144,2214,3127,393,5,1.83,34 +2010,SLOVENIA,4182,1529,2005,539,109,0,2.04,39 +2010,SOLOMON ISLANDS,54,0,54,0,0,0,0.1,4 +2010,SOMALIA,167,0,167,0,0,0,0.02,56 +2010,SOUTH AFRICA,129288,111034,14356,2420,1478,0,2.5,3323 +2010,SPAIN,73878,8463,42407,19443,3566,0,1.59,9913 +2010,SRI LANKA,3617,62,3319,0,236,0,0.18,337 +2010,ST. KITTS-NEVIS,60,0,60,0,0,0,1.15,4 +2010,ST. PIERRE & MIQUELON,19,0,19,0,0,0,3.07,5 +2010,ST. VINCENT & THE GRENADINES,60,0,60,0,0,0,0.55,0 +2010,SUDAN,4347,0,4085,0,262,0,0.1,244 +2010,SURINAME,655,0,646,2,6,1,1.26,62 +2010,SWAZILAND,283,101,183,0,0,0,0.24,1 +2010,SWEDEN,14187,2596,10431,916,244,0,1.51,2298 +2010,SWITZERLAND,10634,149,7989,1880,616,0,1.35,1177 +2010,SYRIAN ARAB REPUBLIC,16800,3,10874,4874,816,233,0.81,952 +2010,TAIWAN,73629,42913,20199,8299,2217,0,3.17,3198 +2010,TAJIKISTAN,694,92,462,100,39,0,0.09,25 +2010,THAILAND,76882,15323,35535,22102,3922,0,1.15,2660 +2010,TIMOR-LESTE (FORMERLY EAST TIMOR),64,0,64,0,0,0,0.06,3 +2010,TOGO,720,0,559,0,161,0,0.11,72 +2010,TONGA,32,0,32,0,0,0,0.31,3 +2010,TRINIDAD AND TOBAGO,13072,0,1500,11465,108,0,9.84,519 +2010,TUNISIA,7543,15,3138,3176,1098,116,0.71,219 +2010,TURKEY,81266,33918,19206,19609,8532,1,1.12,1330 +2010,TURKMENISTAN,15623,0,4636,10831,156,0,3.1,453 +2010,TURKS AND CAICOS ISLANDS,52,0,52,0,0,0,1.67,0 +2010,TUVALU,2,0,2,0,0,0,0.0,0 +2010,UGANDA,1069,0,886,0,183,0,0.03,74 +2010,UKRAINE,83077,36870,10413,34508,1286,0,1.82,228 +2010,UNITED ARAB EMIRATES,43854,703,8297,31896,2448,510,5.26,18488 +2010,UNITED KINGDOM,134499,31709,47810,53120,1072,787,2.14,11334 +2010,UNITED REPUBLIC OF TANZANIA,1938,0,1222,402,314,1,0.04,131 +2010,UNITED STATES OF AMERICA,1471375,521330,590751,347716,9139,2439,4.69,40388 +2010,URUGUAY,1742,1,1587,41,113,0,0.52,451 +2010,UZBEKISTAN,28407,1406,2813,23253,935,0,1.02,0 +2010,VANUATU,33,0,33,0,0,0,0.14,9 +2010,VENEZUELA,51560,206,30725,16153,968,3507,1.78,1200 +2010,VIET NAM,38925,12954,13456,4926,7589,0,0.44,835 +2010,WALLIS AND FUTUNA ISLANDS,8,0,8,0,0,0,0.56,1 +2010,YEMEN,6390,123,5482,531,254,0,0.27,190 +2010,ZAMBIA,734,104,477,0,153,0,0.05,25 +2010,ZIMBABWE,2121,1531,481,0,109,0,0.15,7 +2011,AFGHANISTAN,3338,1174,2075,84,5,0,0.12,9 +2011,ALBANIA,1429,146,1030,8,245,0,0.5,7 +2011,ALGERIA,33048,286,12806,15481,2584,1892,0.9,609 +2011,ANDORRA,134,0,134,0,0,0,1.63,0 +2011,ANGOLA,8274,0,3915,384,204,3771,0.38,314 +2011,ANGUILLA,39,0,39,0,0,0,2.76,0 +2011,ANTIGUA & BARBUDA,140,0,140,0,0,0,1.59,41 +2011,ARGENTINA,52259,1289,23723,25269,1577,401,1.25,1772 +2011,ARMENIA,1341,2,257,1025,57,0,0.45,38 +2011,ARUBA,682,0,682,0,0,0,6.69,75 +2011,AUSTRALIA,106850,54287,32565,18687,1170,142,4.74,3177 +2011,AUSTRIA,17731,3599,8742,4788,602,0,2.1,605 +2011,AZERBAIJAN,9121,5,2855,5192,194,874,0.99,430 +2011,BAHAMAS,509,1,507,0,0,0,1.39,161 +2011,BAHRAIN,7813,0,1008,6628,177,0,5.98,507 +2011,BANGLADESH,17293,774,3706,10815,1998,0,0.11,359 +2011,BARBADOS,417,0,378,9,30,1,1.49,121 +2011,BELARUS,17470,632,5479,10733,626,0,1.84,0 +2011,BELGIUM,27255,3522,13799,8988,946,0,2.48,7243 +2011,BELIZE,164,0,161,3,0,0,0.5,9 +2011,BENIN,1444,0,1245,0,199,0,0.15,131 +2011,BERMUDA,121,0,121,0,0,0,1.9,18 +2011,BHUTAN,200,26,100,0,74,0,0.27,1 +2011,BOSNIA & HERZEGOVINA,6514,5045,1206,142,121,0,1.7,4 +2011,BOTSWANA,1139,390,707,0,41,0,0.54,15 +2011,BRAZIL,119829,17498,78849,13778,8717,987,0.6,5516 +2011,BRITISH VIRGIN ISLANDS,48,0,48,0,0,0,1.71,0 +2011,BRUNEI (DARUSSALAM),2644,0,534,1989,39,82,6.62,175 +2011,BULGARIA,13457,8738,2822,1643,254,0,1.83,206 +2011,BURKINA FASO,603,0,523,0,80,0,0.04,35 +2011,BURUNDI,66,3,58,0,5,0,0.01,3 +2011,CAMBODIA,1420,10,1288,0,123,0,0.1,38 +2011,CANADA,146472,21966,69866,52135,1632,873,4.25,1223 +2011,CAPE VERDE,168,0,168,0,0,0,0.34,94 +2011,CAYMAN ISLANDS,160,0,160,0,0,0,2.83,9 +2011,CENTRAL AFRICAN REPUBLIC,76,0,76,0,0,0,0.02,27 +2011,CHAD,147,0,147,0,0,0,0.01,15 +2011,CHILE,21610,5690,12453,2852,599,16,1.26,790 +2011,CHINA (MAINLAND),2654360,1995029,306730,67137,285464,0,1.97,12636 +2011,COLOMBIA,20870,3762,9537,5745,1466,359,0.45,1241 +2011,COMOROS,37,0,37,0,0,0,0.05,3 +2011,CONGO,616,0,529,77,10,0,0.15,42 +2011,COOK ISLANDS,19,0,19,0,0,0,0.94,2 +2011,COSTA RICA,2111,62,1859,0,190,0,0.46,0 +2011,COTE D IVOIRE,1977,0,915,817,245,0,0.1,56 +2011,CROATIA,5402,730,2730,1605,336,0,1.26,105 +2011,CUBA,9814,3,9040,534,236,0,0.87,140 +2011,CYPRUS,2025,9,1852,0,164,0,1.81,422 +2011,CZECH REPUBLIC,29154,19062,5304,4253,535,0,2.77,257 +2011,DEMOCRATIC PEOPLE S REPUBLIC OF KOREA,13099,11521,721,0,857,0,0.53,0 +2011,DEMOCRATIC REPUBLIC OF THE CONGO (FORMERLY ZAIRE),680,0,606,12,62,0,0.01,124 +2011,DENMARK,11084,3348,5121,2322,246,48,1.99,1299 +2011,DJIBOUTI,129,0,129,0,0,0,0.15,85 +2011,DOMINICA,35,0,35,0,0,0,0.49,2 +2011,DOMINICAN REPUBLIC,5789,573,4232,440,544,0,0.58,364 +2011,ECUADOR,10529,0,9046,365,776,343,0.69,707 +2011,EGYPT,59221,464,27562,25295,5900,0,0.71,990 +2011,EL SALVADOR,1813,0,1633,0,180,0,0.3,94 +2011,EQUATORIAL GUINEA,1671,0,166,880,0,625,2.23,30 +2011,ERITREA,162,0,136,0,26,0,0.03,1 +2011,ESTONIA,5074,4349,350,314,61,0,3.82,194 +2011,ETHIOPIA,2107,123,1701,0,283,0,0.02,233 +2011,FAEROE ISLANDS,155,0,155,0,0,0,3.19,29 +2011,FALKLAND ISLANDS (MALVINAS),15,3,12,0,0,0,5.22,0 +2011,FEDERATED STATES OF MICRONESIA,33,0,33,0,0,0,0.32,1 +2011,FIJI,297,0,274,0,23,0,0.34,44 +2011,FINLAND,15494,6325,6881,2099,189,0,2.87,701 +2011,FRANCE (INCLUDING MONACO),90484,10543,54185,23136,2621,0,1.43,7029 +2011,FRENCH GUIANA,175,0,163,0,12,0,0.73,33 +2011,FRENCH POLYNESIA,227,0,227,0,0,0,0.84,47 +2011,GABON,1356,0,604,188,31,532,0.86,224 +2011,GAMBIA,122,0,121,1,0,0,0.07,18 +2011,GEORGIA,2174,289,739,942,204,0,0.52,30 +2011,GERMANY,199754,82252,69465,43468,4561,8,2.48,8789 +2011,GHANA,2681,0,1909,432,340,0,0.11,178 +2011,GIBRALTAR,123,0,123,0,0,0,3.96,3653 +2011,GREECE,21773,8491,10046,2481,755,0,1.95,3061 +2011,GREENLAND,193,0,193,0,0,0,3.43,40 +2011,GRENADA,69,0,69,0,0,0,0.65,3 +2011,GUADELOUPE,663,145,477,0,41,0,1.45,91 +2011,GUATEMALA,3228,357,2483,0,388,0,0.21,298 +2011,GUINEA,758,0,708,0,50,0,0.07,21 +2011,GUINEA BISSAU,67,0,67,0,0,0,0.04,9 +2011,GUYANA,486,0,486,0,0,0,0.64,8 +2011,HAITI,605,0,564,0,41,0,0.06,15 +2011,HONDURAS,2442,181,2040,0,220,0,0.32,45 +2011,HONG KONG SPECIAL ADMINSTRATIVE REGION OF CHINA,11943,7659,2637,1438,209,0,1.7,13924 +2011,HUNGARY,13047,3008,3967,5842,230,0,1.31,198 +2011,ICELAND,513,94,400,0,19,0,1.6,168 +2011,INDIA,502257,330199,113915,24937,32640,567,0.4,4035 +2011,INDONESIA,164621,75931,57677,22258,6152,2603,0.67,744 +2011,IRAQ,36647,0,27114,3127,1360,5046,1.15,815 +2011,IRELAND,9717,2059,4796,2576,286,0,2.09,644 +2011,ISLAMIC REPUBLIC OF IRAN,160637,1450,61052,80039,8976,9119,2.14,2935 +2011,ISRAEL,18852,7915,7642,2550,745,0,2.49,964 +2011,ITALY (INCLUDING SAN MARINO),108534,16433,47740,39857,4504,0,1.82,4926 +2011,JAMAICA,2143,58,1981,0,104,0,0.78,213 +2011,JAPAN,324809,111852,143467,62514,6976,0,2.55,8406 +2011,JORDAN,5909,0,4981,545,383,0,0.87,104 +2011,KAZAKHSTAN,70646,39193,10260,20154,1039,0,4.27,151 +2011,KENYA,3670,277,2784,0,609,0,0.09,597 +2011,KIRIBATI,17,0,17,0,0,0,0.16,3 +2011,KUWAIT,24824,0,15436,8968,306,114,7.66,1488 +2011,KYRGYZSTAN,2088,782,993,174,139,0,0.38,44 +2011,LAO PEOPLE S DEMOCRATIC REPUBLIC,443,151,115,0,177,0,0.07,9 +2011,LATVIA,1989,114,968,805,102,0,0.96,284 +2011,LEBANON,5575,171,4656,0,748,0,1.21,216 +2011,LESOTHO,636,485,151,0,0,0,0.31,0 +2011,LIBERIA,243,0,232,0,11,0,0.06,16 +2011,LIBYAN ARAB JAMAHIRIYAH,10827,0,6892,2775,476,684,1.72,114 +2011,LIECHTENSTEIN,13,0,0,13,0,0,0.35,0 +2011,LITHUANIA,3760,250,1677,1698,135,0,1.22,171 +2011,LUXEMBOURG,2983,60,2099,645,179,0,5.74,335 +2011,MACAU SPECIAL ADMINSTRATIVE REGION OF CHINA,395,0,357,39,0,0,0.72,0 +2011,MACEDONIA,2563,1588,774,69,133,0,1.24,3 +2011,MADAGASCAR,638,111,500,0,27,0,0.03,68 +2011,MALAWI,322,67,227,0,28,0,0.02,6 +2011,MALAYSIA,60105,15159,19794,17681,2883,4587,2.1,1653 +2011,MALDIVES,269,0,269,0,0,0,0.79,49 +2011,MALI,285,0,285,0,0,0,0.02,18 +2011,MALTA,693,0,693,0,0,0,1.67,1267 +2011,MARSHALL ISLANDS,28,0,28,0,0,0,0.54,0 +2011,MARTINIQUE,605,0,585,0,20,0,1.53,120 +2011,MAURITANIA,653,0,576,0,77,0,0.18,15 +2011,MAURITIUS,1069,411,658,0,0,0,0.85,345 +2011,MEXICO,132105,15295,74375,35673,4814,1947,1.1,2982 +2011,MONGOLIA,5863,4968,837,0,58,0,2.13,0 +2011,MONTENEGRO,701,457,244,0,0,0,1.13,9 +2011,MONTSERRAT,11,0,11,0,0,0,2.18,1 +2011,MOROCCO,15731,3869,9508,450,1904,0,0.48,549 +2011,MOZAMBIQUE,879,34,662,50,133,0,0.04,50 +2011,MYANMAR (FORMERLY BURMA),3899,227,2096,1500,73,3,0.07,16 +2011,NAMIBIA,772,19,700,0,53,0,0.34,11 +2011,NAURU,11,0,11,0,0,0,1.08,4 +2011,NEPAL,1509,304,919,0,286,0,0.06,76 +2011,NETHERLAND ANTILLES,1587,0,1587,0,0,0,7.45,2086 +2011,NETHERLANDS,47496,7475,18317,21364,315,25,2.85,15879 +2011,NEW CALEDONIA,995,345,630,0,20,0,3.98,27 +2011,NEW ZEALAND,8591,1549,4661,2130,163,87,1.95,918 +2011,NICARAGUA,1331,0,1236,0,95,0,0.23,17 +2011,NIGER,362,101,250,0,10,0,0.02,13 +2011,NIGERIA,26096,23,9307,7643,1632,7491,0.16,498 +2011,NIUE,2,0,2,0,0,0,1.04,0 +2011,NORWAY,12325,874,7971,3022,189,269,2.49,679 +2011,OCCUPIED PALESTINIAN TERRITORY,613,0,613,0,0,0,0.15,0 +2011,OMAN,14734,0,2897,10676,680,482,4.59,817 +2011,PAKISTAN,44166,4685,16528,19009,3944,0,0.25,257 +2011,PALAU,69,0,69,0,0,0,3.37,15 +2011,PANAMA,2754,223,2291,0,240,0,0.75,3267 +2011,PAPUA NEW GUINEA,1453,0,1344,83,27,0,0.21,68 +2011,PARAGUAY,1451,1,1362,0,88,0,0.23,22 +2011,PERU,13535,780,6526,3184,1156,1888,0.45,791 +2011,PHILIPPINES,23315,8465,10582,2082,2185,0,0.25,1117 +2011,PLURINATIONAL STATE OF BOLIVIA,4403,0,2308,1685,361,49,0.44,41 +2011,POLAND,86446,57784,18116,8017,2523,6,2.24,563 +2011,PORTUGAL,12987,2285,7225,2788,689,0,1.23,1259 +2011,QATAR,21935,0,2763,18199,680,293,11.51,1243 +2011,REPUBLIC OF CAMEROON,1573,0,1301,116,156,0,0.07,97 +2011,REPUBLIC OF KOREA,160731,83147,45047,25975,6562,0,3.26,10614 +2011,REPUBLIC OF MOLDOVA,1374,91,624,523,136,0,0.34,11 +2011,REUNION,1165,495,636,0,34,0,1.39,61 +2011,ROMANIA,23147,8791,6426,6936,994,0,1.15,115 +2011,RUSSIAN FEDERATION,480885,109218,108312,247327,7643,8385,3.36,7962 +2011,RWANDA,181,0,167,0,13,0,0.02,15 +2011,SAINT HELENA,3,0,3,0,0,0,0.81,0 +2011,SAINT LUCIA,111,0,111,0,0,0,0.62,5 +2011,SAMOA,55,0,55,0,0,0,0.29,9 +2011,SAO TOME & PRINCIPE,28,0,28,0,0,0,0.16,9 +2011,SAUDI ARABIA,136318,0,91624,38105,6589,0,4.74,4452 +2011,SENEGAL,2282,257,1378,10,636,0,0.17,247 +2011,SERBIA,13422,9355,2537,1188,342,0,1.49,39 +2011,SEYCHELLES,93,0,93,0,0,0,0.99,151 +2011,SIERRA LEONE,245,0,203,0,42,0,0.04,7 +2011,SINGAPORE,12332,7,7774,4551,0,0,2.38,41786 +2011,SLOVAKIA,9415,3920,2156,2896,438,5,1.74,36 +2011,SLOVENIA,4115,1571,1999,461,84,0,2.0,48 +2011,SOLOMON ISLANDS,54,0,54,0,0,0,0.1,4 +2011,SOMALIA,165,0,165,0,0,0,0.02,56 +2011,SOUTH AFRICA,128329,109120,15279,2402,1528,0,2.46,3458 +2011,SPAIN,73779,12922,39769,18073,3016,0,1.58,10585 +2011,SRI LANKA,4128,309,3549,0,270,0,0.2,511 +2011,ST. KITTS-NEVIS,63,0,63,0,0,0,1.18,4 +2011,ST. PIERRE & MIQUELON,19,0,19,0,0,0,3.07,5 +2011,ST. VINCENT & THE GRENADINES,54,0,54,0,0,0,0.49,0 +2011,SUDAN,4270,0,3862,0,408,0,0.09,280 +2011,SURINAME,537,0,524,2,10,1,1.03,56 +2011,SWAZILAND,286,102,184,0,0,0,0.24,1 +2011,SWEDEN,14108,2589,10514,724,281,0,1.49,2129 +2011,SWITZERLAND,10081,139,7652,1667,622,0,1.27,1263 +2011,SYRIAN ARAB REPUBLIC,15519,3,10376,4110,680,350,0.76,827 +2011,TAIWAN,73406,42590,19763,8760,2292,0,3.16,3067 +2011,TAJIKISTAN,641,101,399,101,41,0,0.08,27 +2011,THAILAND,75898,17009,33725,21045,4119,0,1.13,2857 +2011,TIMOR-LESTE (FORMERLY EAST TIMOR),67,0,67,0,0,0,0.06,3 +2011,TOGO,672,0,510,4,158,0,0.1,66 +2011,TONGA,28,0,28,0,0,0,0.27,3 +2011,TRINIDAD AND TOBAGO,12799,0,1374,11313,112,0,9.59,577 +2011,TUNISIA,7096,12,2940,3075,959,110,0.66,210 +2011,TURKEY,87494,35570,20323,22977,8623,0,1.19,1099 +2011,TURKMENISTAN,17035,0,4845,11925,265,0,3.34,410 +2011,TURKS AND CAICOS ISLANDS,52,0,52,0,0,0,1.64,0 +2011,TUVALU,2,0,2,0,0,0,0.0,0 +2011,UGANDA,1163,0,936,0,227,0,0.03,77 +2011,UKRAINE,78100,37928,9479,29262,1430,0,1.72,205 +2011,UNITED ARAB EMIRATES,45116,516,6109,35527,2448,516,5.17,18713 +2011,UNITED KINGDOM,122124,31296,45006,44043,1160,618,1.93,11977 +2011,UNITED REPUBLIC OF TANZANIA,2207,59,1376,444,328,1,0.05,139 +2011,UNITED STATES OF AMERICA,1442509,498720,575746,355630,9335,3079,4.56,40600 +2011,URUGUAY,2117,1,1943,40,132,0,0.63,401 +2011,UZBEKISTAN,31002,1478,2649,25964,911,0,1.1,0 +2011,VANUATU,36,0,36,0,0,0,0.15,9 +2011,VENEZUELA,48220,212,25860,16219,1055,4874,1.64,857 +2011,VIET NAM,41497,16253,12876,4443,7925,0,0.46,660 +2011,WALLIS AND FUTUNA ISLANDS,7,0,7,0,0,0,0.5,1 +2011,YEMEN,5363,126,4752,355,129,0,0.22,134 +2011,ZAMBIA,801,73,562,0,167,0,0.06,28 +2011,ZIMBABWE,2608,1584,888,0,136,0,0.18,8 +2012,AFGHANISTAN,2933,1000,1844,84,5,0,0.1,9 +2012,ALBANIA,1339,171,861,8,299,0,0.46,7 +2012,ALGERIA,35448,283,13248,17499,2584,1835,0.95,658 +2012,ANDORRA,133,0,133,0,0,0,1.68,0 +2012,ANGOLA,9108,0,4691,388,218,3811,0.4,470 +2012,ANGUILLA,39,0,39,0,0,0,2.73,0 +2012,ANTIGUA & BARBUDA,143,0,143,0,0,0,1.61,42 +2012,ARGENTINA,52456,1180,23363,26032,1457,424,1.25,2068 +2012,ARMENIA,1553,2,244,1246,60,0,0.52,40 +2012,ARUBA,368,0,368,0,0,0,3.59,79 +2012,AUSTRALIA,105843,53298,33410,17843,1156,136,4.62,3433 +2012,AUSTRIA,16982,3342,8458,4576,606,0,2.01,581 +2012,AZERBAIJAN,9696,4,3220,5413,267,792,1.04,391 +2012,BAHAMAS,537,1,536,0,0,0,1.44,192 +2012,BAHRAIN,7274,0,432,6658,184,0,5.45,481 +2012,BANGLADESH,18409,934,4015,11385,2074,0,0.12,343 +2012,BARBADOS,401,0,367,10,24,1,1.43,97 +2012,BELARUS,17241,803,5193,10579,667,0,1.82,0 +2012,BELGIUM,25936,3205,12904,8973,854,0,2.34,6507 +2012,BELIZE,130,0,128,2,0,0,0.39,9 +2012,BENIN,1492,0,1303,0,189,0,0.15,137 +2012,BERMUDA,130,0,130,0,0,0,2.05,18 +2012,BHUTAN,223,38,114,0,71,0,0.3,2 +2012,"BONAIRE, SAINT EUSTATIUS, AND SABA",85,0,85,0,0,0,3.72,185 +2012,BOSNIA & HERZEGOVINA,6070,4704,1121,131,115,0,1.59,4 +2012,BOTSWANA,1154,355,749,0,50,0,0.54,10 +2012,BRAZIL,128178,17165,84409,16328,9428,848,0.63,5168 +2012,BRITISH VIRGIN ISLANDS,48,0,48,0,0,0,1.67,0 +2012,BRUNEI (DARUSSALAM),2636,0,564,1942,45,86,6.5,125 +2012,BULGARIA,12192,7479,2979,1531,203,0,1.67,191 +2012,BURKINA FASO,717,0,627,0,90,0,0.04,37 +2012,BURUNDI,77,8,59,0,10,0,0.01,3 +2012,CAMBODIA,1488,11,1344,0,133,0,0.1,47 +2012,CANADA,141112,20803,65652,51994,1695,968,4.05,1171 +2012,CAPE VERDE,138,0,138,0,0,0,0.28,89 +2012,CAYMAN ISLANDS,146,0,146,0,0,0,2.53,10 +2012,CENTRAL AFRICAN REPUBLIC,80,0,80,0,0,0,0.02,28 +2012,CHAD,167,0,148,0,19,0,0.01,15 +2012,CHILE,22082,6407,12326,2677,642,29,1.27,718 +2012,CHINA (MAINLAND),2734817,2037338,321155,75764,300560,0,2.02,12701 +2012,COLOMBIA,21803,3150,10556,6250,1486,361,0.47,1188 +2012,COMOROS,39,0,39,0,0,0,0.05,3 +2012,CONGO,810,0,679,111,20,0,0.19,40 +2012,COOK ISLANDS,19,0,19,0,0,0,0.94,2 +2012,COSTA RICA,2118,63,1865,0,190,0,0.46,0 +2012,COTE D IVOIRE,2535,0,1386,891,258,0,0.12,68 +2012,CROATIA,4907,654,2452,1507,293,0,1.14,90 +2012,CUBA,9860,4,9066,542,248,0,0.87,140 +2012,CURACAO,1636,0,1636,0,0,0,10.72,1408 +2012,CYPRUS,1887,0,1747,0,140,0,1.67,394 +2012,CZECH REPUBLIC,27551,17685,5117,4282,467,0,2.61,243 +2012,DEMOCRATIC PEOPLE S REPUBLIC OF KOREA,13378,11803,691,0,884,0,0.54,0 +2012,DEMOCRATIC REPUBLIC OF THE CONGO (FORMERLY ZAIRE),655,0,599,0,56,0,0.01,119 +2012,DENMARK,9934,2553,4918,2176,245,42,1.77,1138 +2012,DJIBOUTI,141,0,141,0,0,0,0.17,87 +2012,DOMINICA,37,0,37,0,0,0,0.51,2 +2012,DOMINICAN REPUBLIC,6033,637,4249,585,562,0,0.59,409 +2012,ECUADOR,10401,0,8806,464,819,312,0.67,624 +2012,EGYPT,59195,492,25836,25360,7507,0,0.69,1001 +2012,EL SALVADOR,1817,0,1629,0,188,0,0.3,71 +2012,EQUATORIAL GUINEA,1395,0,166,933,0,297,1.8,30 +2012,ERITREA,180,0,145,0,35,0,0.04,1 +2012,ESTONIA,4806,4062,337,341,66,0,3.63,382 +2012,ETHIOPIA,2335,162,1697,0,476,0,0.03,272 +2012,FAEROE ISLANDS,161,0,161,0,0,0,3.32,27 +2012,FALKLAND ISLANDS (MALVINAS),15,3,12,0,0,0,5.21,0 +2012,FEDERATED STATES OF MICRONESIA,37,0,37,0,0,0,0.36,1 +2012,FIJI,289,0,269,0,20,0,0.33,44 +2012,FINLAND,13399,4911,6436,1877,176,0,2.47,616 +2012,FRANCE (INCLUDING MONACO),90872,11645,52933,23871,2422,0,1.43,6775 +2012,FRENCH GUIANA,161,0,147,0,14,0,0.65,33 +2012,FRENCH POLYNESIA,222,0,222,0,0,0,0.81,45 +2012,GABON,1392,0,646,193,27,527,0.86,237 +2012,GAMBIA,124,0,122,1,0,0,0.07,13 +2012,GEORGIA,2302,322,741,1029,210,0,0.56,32 +2012,GERMANY,201762,84428,69309,43608,4411,6,2.51,9060 +2012,GHANA,3239,0,2611,219,408,0,0.13,176 +2012,GIBRALTAR,126,0,126,0,0,0,4.0,3682 +2012,GREECE,21828,8760,10099,2287,681,0,1.96,2545 +2012,GREENLAND,155,0,155,0,0,0,2.75,19 +2012,GRENADA,74,0,74,0,0,0,0.7,3 +2012,GUADELOUPE,694,145,508,0,41,0,1.51,92 +2012,GUATEMALA,3265,361,2513,0,392,0,0.21,292 +2012,GUINEA,704,0,661,0,43,0,0.06,21 +2012,GUINEA BISSAU,69,0,69,0,0,0,0.04,9 +2012,GUYANA,544,0,544,0,0,0,0.72,13 +2012,HAITI,631,0,590,0,41,0,0.06,44 +2012,HONDURAS,2450,183,2033,0,235,0,0.32,43 +2012,HONG KONG SPECIAL ADMINSTRATIVE REGION OF CHINA,11842,7540,2741,1333,228,0,1.67,13123 +2012,HUNGARY,12158,2901,3771,5232,254,0,1.22,142 +2012,ICELAND,491,96,395,0,0,0,1.52,170 +2012,INDIA,550451,372453,119399,21312,36720,567,0.44,4035 +2012,INDONESIA,173733,81711,59710,21851,7120,3342,0.7,790 +2012,IRAQ,41648,0,30924,3077,1360,6287,1.26,426 +2012,IRELAND,9706,2455,4576,2513,163,0,2.08,553 +2012,ISLAMIC REPUBLIC OF IRAN,166828,1126,66900,79769,9554,9479,2.19,2643 +2012,ISRAEL,20597,8891,9592,1314,801,0,2.68,950 +2012,ITALY (INCLUDING SAN MARINO),100755,16819,42046,38321,3569,0,1.69,4779 +2012,JAMAICA,2035,53,1880,0,103,0,0.74,209 +2012,JAPAN,335470,115977,146258,65791,7444,0,2.64,8600 +2012,JORDAN,6666,0,5703,412,552,0,0.95,126 +2012,KAZAKHSTAN,66259,39243,8834,17223,959,0,3.94,168 +2012,KENYA,3413,248,2534,0,631,0,0.08,585 +2012,KIRIBATI,17,0,17,0,0,0,0.16,3 +2012,KUWAIT,27907,0,17982,9479,326,119,8.16,1629 +2012,KYRGYZSTAN,2763,1096,1275,223,169,0,0.49,26 +2012,LAO PEOPLE S DEMOCRATIC REPUBLIC,463,142,116,0,204,0,0.07,9 +2012,LATVIA,1926,95,951,756,123,0,0.95,307 +2012,LEBANON,6172,171,5279,0,722,0,1.25,203 +2012,LESOTHO,656,492,163,0,0,0,0.32,0 +2012,LIBERIA,280,0,263,0,17,0,0.07,18 +2012,LIBYAN ARAB JAMAHIRIYAH,14367,0,9113,2923,272,2059,2.29,484 +2012,LIECHTENSTEIN,13,0,0,13,0,0,0.36,0 +2012,LITHUANIA,3772,245,1731,1658,138,0,1.25,159 +2012,LUXEMBOURG,2908,56,2036,656,160,0,5.46,309 +2012,MACAU SPECIAL ADMINSTRATIVE REGION OF CHINA,358,0,358,0,0,0,0.64,0 +2012,MACEDONIA,2445,1508,773,71,93,0,1.18,7 +2012,MADAGASCAR,738,190,517,0,31,0,0.03,70 +2012,MALAWI,299,59,217,0,23,0,0.02,6 +2012,MALAYSIA,59642,16340,20544,18092,2955,1712,2.06,1509 +2012,MALDIVES,303,0,303,0,0,0,0.88,101 +2012,MALI,271,0,271,0,0,0,0.02,19 +2012,MALTA,731,0,731,0,0,0,1.76,1129 +2012,MARSHALL ISLANDS,28,0,28,0,0,0,0.52,0 +2012,MARTINIQUE,604,0,584,0,20,0,1.53,119 +2012,MAURITANIA,724,0,636,0,88,0,0.19,20 +2012,MAURITIUS,1082,433,649,0,0,0,0.86,321 +2012,MEXICO,135349,13434,79191,37043,4921,759,1.11,3115 +2012,MONGOLIA,7152,6156,949,0,47,0,2.55,0 +2012,MONTENEGRO,637,411,226,0,0,0,1.02,10 +2012,MONTSERRAT,12,0,12,0,0,0,2.33,1 +2012,MOROCCO,17107,3991,10251,651,2213,0,0.51,800 +2012,MOZAMBIQUE,851,11,632,47,161,0,0.03,56 +2012,MYANMAR (FORMERLY BURMA),3019,301,1613,976,125,3,0.06,31 +2012,NAMIBIA,923,75,779,0,68,0,0.4,33 +2012,NAURU,11,0,11,0,0,0,1.08,4 +2012,NEPAL,1597,227,1001,0,370,0,0.06,80 +2012,NETHERLANDS,46444,8227,17457,20457,280,23,2.77,14710 +2012,NEW CALEDONIA,990,345,628,0,17,0,3.91,27 +2012,NEW ZEALAND,9313,1756,4941,2398,155,63,2.1,918 +2012,NICARAGUA,1260,0,1176,0,84,0,0.21,18 +2012,NIGER,509,105,394,0,10,0,0.03,10 +2012,NIGERIA,26862,35,9851,7880,2176,6920,0.16,492 +2012,NIUE,2,0,2,0,0,0,1.04,0 +2012,NORWAY,13605,847,9403,2872,226,257,2.71,617 +2012,OCCUPIED PALESTINIAN TERRITORY,600,0,600,0,0,0,0.14,0 +2012,OMAN,16133,0,3394,11363,694,681,4.55,1029 +2012,PAKISTAN,44586,4011,17409,19086,4080,0,0.25,237 +2012,PALAU,69,0,69,0,0,0,3.31,15 +2012,PANAMA,2758,340,2104,0,314,0,0.74,3349 +2012,PAPUA NEW GUINEA,1385,0,1287,71,27,0,0.19,50 +2012,PARAGUAY,1441,1,1330,0,109,0,0.23,23 +2012,PERU,15018,704,7013,3533,1374,2394,0.5,750 +2012,PHILIPPINES,24872,8855,11449,1996,2571,0,0.26,1099 +2012,PLURINATIONAL STATE OF BOLIVIA,5125,0,2796,1919,369,42,0.5,36 +2012,POLAND,81792,53724,17353,8544,2165,6,2.12,573 +2012,PORTUGAL,12548,3036,6500,2456,556,0,1.19,1306 +2012,QATAR,25668,0,2261,22289,748,369,12.73,1536 +2012,REPUBLIC OF CAMEROON,1671,0,1359,139,173,0,0.08,101 +2012,REPUBLIC OF KOREA,159249,79765,45017,28093,6373,0,3.21,10420 +2012,REPUBLIC OF MOLDOVA,1343,113,569,498,163,0,0.33,19 +2012,REPUBLIC OF SOUTH SUDAN,363,0,363,0,0,0,0.03,27 +2012,REPUBLIC OF SUDAN,3993,0,3516,0,477,0,0.11,203 +2012,REUNION,1159,513,598,0,48,0,1.37,54 +2012,ROMANIA,22286,8141,6295,6731,1118,0,1.12,110 +2012,RUSSIAN FEDERATION,499272,124583,115878,241786,8391,8635,3.48,7034 +2012,RWANDA,201,0,187,0,14,0,0.02,17 +2012,SAINT HELENA,3,0,3,0,0,0,0.82,0 +2012,SAINT LUCIA,111,0,111,0,0,0,0.61,5 +2012,SAINT MARTIN (DUTCH PORTION),190,0,190,0,0,0,5.41,201 +2012,SAMOA,54,0,54,0,0,0,0.28,9 +2012,SAO TOME & PRINCIPE,31,0,31,0,0,0,0.17,9 +2012,SAUDI ARABIA,154034,0,105409,41372,7253,0,5.22,4671 +2012,SENEGAL,2158,223,1282,15,638,0,0.16,229 +2012,SERBIA,12016,8219,2427,1048,322,0,1.34,35 +2012,SEYCHELLES,120,0,120,0,0,0,1.27,162 +2012,SIERRA LEONE,281,0,235,0,46,0,0.05,7 +2012,SINGAPORE,9919,29,4955,4935,0,0,1.87,41967 +2012,SLOVAKIA,8935,3660,2146,2726,396,7,1.65,31 +2012,SLOVENIA,4031,1514,1943,444,130,0,1.95,63 +2012,SOLOMON ISLANDS,54,0,54,0,0,0,0.1,4 +2012,SOMALIA,166,0,166,0,0,0,0.02,57 +2012,SOUTH AFRICA,127835,108478,15265,2521,1572,0,2.42,3737 +2012,SPAIN,72206,15896,36295,17847,2168,0,1.55,10375 +2012,SRI LANKA,4372,524,3576,0,273,0,0.21,563 +2012,ST. KITTS-NEVIS,60,0,60,0,0,0,1.12,4 +2012,ST. PIERRE & MIQUELON,19,0,19,0,0,0,3.07,5 +2012,ST. VINCENT & THE GRENADINES,69,0,69,0,0,0,0.63,0 +2012,SURINAME,616,0,597,2,16,1,1.17,68 +2012,SWAZILAND,329,142,188,0,0,0,0.27,1 +2012,SWEDEN,12830,2265,9645,629,291,0,1.34,2071 +2012,SWITZERLAND,10301,126,7730,1828,617,0,1.28,1283 +2012,SYRIAN ARAB REPUBLIC,12198,1,7909,3265,816,208,0.61,437 +2012,TAIWAN,70393,41269,18701,8273,2150,0,3.02,2774 +2012,TAJIKISTAN,800,192,501,74,34,0,0.1,28 +2012,THAILAND,80883,17871,35652,23041,4319,0,1.2,2857 +2012,TIMOR-LESTE (FORMERLY EAST TIMOR),80,0,80,0,0,0,0.07,3 +2012,TOGO,678,0,451,9,218,0,0.1,73 +2012,TONGA,29,0,29,0,0,0,0.28,3 +2012,TRINIDAD AND TOBAGO,12386,0,1222,11075,89,0,9.23,536 +2012,TUNISIA,7364,0,2954,3318,985,107,0.68,251 +2012,TURKEY,89872,36927,20984,23273,8688,0,1.2,1017 +2012,TURKMENISTAN,17691,0,5070,12300,322,0,3.42,355 +2012,TURKS AND CAICOS ISLANDS,54,0,54,0,0,0,1.68,0 +2012,TUVALU,3,0,3,0,0,0,0.0,0 +2012,UGANDA,1110,0,868,0,242,0,0.03,79 +2012,UKRAINE,80663,43570,8877,26876,1339,0,1.78,255 +2012,UNITED ARAB EMIRATES,48101,1540,7740,36191,2094,535,5.37,19340 +2012,UNITED KINGDOM,127781,39717,44872,41549,1081,563,2.01,11295 +2012,UNITED REPUBLIC OF TANZANIA,2603,57,1686,507,351,1,0.05,149 +2012,UNITED STATES OF AMERICA,1396083,443904,566582,372277,10191,3129,4.38,29859 +2012,URUGUAY,2371,2,2220,29,119,0,0.7,321 +2012,UZBEKISTAN,31583,1493,2352,26813,925,0,1.1,0 +2012,VANUATU,31,0,31,0,0,0,0.13,9 +2012,VENEZUELA,54204,218,30075,16851,1103,5957,1.82,1280 +2012,VIET NAM,38784,14265,12066,4901,7552,0,0.43,693 +2012,WALLIS AND FUTUNA ISLANDS,7,0,7,0,0,0,0.5,1 +2012,YEMEN,5091,129,4173,414,375,0,0.2,111 +2012,ZAMBIA,1000,95,690,0,215,0,0.07,43 +2012,ZIMBABWE,2125,917,1006,0,201,0,0.15,9 +2013,AFGHANISTAN,2731,1075,1568,81,7,0,0.09,9 +2013,ALBANIA,1381,150,909,9,313,0,0.48,24 +2013,ALGERIA,36669,198,14170,17863,2516,1922,0.96,687 +2013,ANDORRA,130,0,130,0,0,0,1.71,0 +2013,ANGOLA,8895,0,4738,209,272,3675,0.38,374 +2013,ANGUILLA,37,0,37,0,0,0,2.58,0 +2013,ANTIGUA & BARBUDA,143,0,143,0,0,0,1.59,42 +2013,ARGENTINA,51773,649,24226,24771,1617,510,1.22,2253 +2013,ARMENIA,1499,1,232,1207,59,0,0.5,39 +2013,ARUBA,235,0,235,0,0,0,2.29,80 +2013,AUSTRALIA,101518,47663,33655,18902,1142,155,4.36,3445 +2013,AUSTRIA,17040,3402,8632,4410,596,0,2.01,555 +2013,AZERBAIJAN,9720,3,3293,5436,312,675,1.02,393 +2013,BAHAMAS,764,1,763,0,0,0,2.02,167 +2013,BAHRAIN,8539,0,1211,7145,184,0,6.33,344 +2013,BANGLADESH,19010,1023,3866,11839,2282,0,0.12,352 +2013,BARBADOS,395,0,360,12,22,1,1.4,109 +2013,BELARUS,17390,858,5170,10675,688,0,1.83,86 +2013,BELGIUM,26444,3291,13330,8991,832,0,2.37,6542 +2013,BELIZE,140,0,138,2,0,0,0.41,12 +2013,BENIN,1585,0,1392,0,193,0,0.15,146 +2013,BERMUDA,125,0,125,0,0,0,1.99,18 +2013,BHUTAN,251,53,120,0,78,0,0.33,3 +2013,"BONAIRE, SAINT EUSTATIUS, AND SABA",88,0,88,0,0,0,3.71,190 +2013,BOSNIA & HERZEGOVINA,5978,4663,1093,102,120,0,1.56,3 +2013,BOTSWANA,1426,589,787,0,50,0,0.66,11 +2013,BRAZIL,137354,18773,88898,19399,9517,767,0.67,4895 +2013,BRITISH VIRGIN ISLANDS,48,0,48,0,0,0,1.64,0 +2013,BRUNEI (DARUSSALAM),2128,0,452,1535,46,95,5.17,139 +2013,BULGARIA,10799,6326,2729,1498,246,0,1.49,210 +2013,BURKINA FASO,834,0,755,0,79,0,0.05,47 +2013,BURUNDI,79,6,59,0,14,0,0.01,3 +2013,CAMBODIA,1528,49,1335,0,144,0,0.1,54 +2013,CANADA,141031,18778,65850,53841,1579,983,4.0,1048 +2013,CAPE VERDE,136,0,136,0,0,0,0.27,86 +2013,CAYMAN ISLANDS,146,0,146,0,0,0,2.5,9 +2013,CENTRAL AFRICAN REPUBLIC,81,0,81,0,0,0,0.02,28 +2013,CHAD,191,0,167,0,24,0,0.01,15 +2013,CHILE,22696,6931,12531,2536,664,33,1.29,689 +2013,CHINA (MAINLAND),2797384,2045156,336960,87371,327896,0,2.05,12057 +2013,COLOMBIA,24441,3581,11564,6306,1530,1459,0.52,1547 +2013,COMOROS,48,0,48,0,0,0,0.06,3 +2013,CONGO,842,0,693,115,34,0,0.19,37 +2013,COOK ISLANDS,19,0,19,0,0,0,0.93,2 +2013,COSTA RICA,2072,63,1809,0,199,0,0.44,133 +2013,COTE D IVOIRE,2914,0,1578,1023,313,0,0.13,62 +2013,CROATIA,4786,699,2344,1425,317,0,1.12,98 +2013,CUBA,9490,10,8696,558,226,0,0.84,203 +2013,CURACAO,1422,0,1422,0,0,0,9.21,1421 +2013,CYPRUS,1622,0,1505,0,116,0,1.42,406 +2013,CZECH REPUBLIC,26909,17124,5010,4339,437,0,2.55,234 +2013,DEMOCRATIC PEOPLE S REPUBLIC OF KOREA,9820,8108,746,0,966,0,0.39,0 +2013,DEMOCRATIC REPUBLIC OF THE CONGO (FORMERLY ZAIRE),979,0,918,0,61,0,0.01,129 +2013,DENMARK,10508,3248,4884,2071,249,56,1.87,1230 +2013,DJIBOUTI,166,0,146,0,20,0,0.19,92 +2013,DOMINICA,36,0,36,0,0,0,0.5,2 +2013,DOMINICAN REPUBLIC,5847,604,4136,530,577,0,0.57,371 +2013,ECUADOR,11180,0,9454,539,907,280,0.71,634 +2013,EGYPT,58198,224,26501,24672,6800,0,0.66,694 +2013,EL SALVADOR,1699,0,1536,0,163,0,0.28,123 +2013,EQUATORIAL GUINEA,1408,0,166,823,0,420,1.77,30 +2013,ERITREA,182,0,147,0,35,0,0.04,1 +2013,ESTONIA,5425,4736,280,347,62,0,4.11,393 +2013,ETHIOPIA,2900,211,2009,0,680,0,0.03,299 +2013,FAEROE ISLANDS,185,0,185,0,0,0,3.83,20 +2013,FALKLAND ISLANDS (MALVINAS),15,3,12,0,0,0,5.18,0 +2013,FEDERATED STATES OF MICRONESIA,39,0,39,0,0,0,0.37,1 +2013,FIJI,314,0,289,0,25,0,0.36,48 +2013,FINLAND,12877,5478,5437,1784,177,0,2.36,639 +2013,FRANCE (INCLUDING MONACO),91109,12683,51614,24363,2450,0,1.43,6547 +2013,FRENCH GUIANA,172,0,159,0,13,0,0.68,33 +2013,FRENCH POLYNESIA,224,0,224,0,0,0,0.81,46 +2013,GABON,1440,0,738,158,23,522,0.87,222 +2013,GAMBIA,118,0,116,1,0,0,0.06,18 +2013,GEORGIA,2143,331,726,867,220,0,0.52,73 +2013,GERMANY,206521,86226,70373,45658,4258,5,2.56,8982 +2013,GHANA,3987,0,3415,164,408,0,0.15,153 +2013,GIBRALTAR,134,0,134,0,0,0,4.22,3370 +2013,GREECE,18948,7517,8594,2021,815,0,1.71,2443 +2013,GREENLAND,151,0,151,0,0,0,2.68,14 +2013,GRENADA,83,0,83,0,0,0,0.78,3 +2013,GUADELOUPE,697,145,511,0,41,0,1.5,92 +2013,GUATEMALA,3718,361,2954,0,404,0,0.24,310 +2013,GUINEA,627,0,576,0,51,0,0.05,21 +2013,GUINEA BISSAU,70,0,70,0,0,0,0.04,9 +2013,GUYANA,528,0,528,0,0,0,0.69,9 +2013,HAITI,656,0,615,0,41,0,0.06,76 +2013,HONDURAS,2472,186,2055,0,231,0,0.31,36 +2013,HONG KONG SPECIAL ADMINSTRATIVE REGION OF CHINA,12273,8037,2698,1298,240,0,1.71,13498 +2013,HUNGARY,11492,2547,3923,4747,275,0,1.16,139 +2013,ICELAND,518,101,417,0,0,0,1.59,156 +2013,INDIA,554882,362676,125763,27784,38080,579,0.43,4405 +2013,INDONESIA,133686,39375,65400,17673,7710,3528,0.53,1068 +2013,IRAQ,45134,0,33411,3564,1632,6527,1.32,491 +2013,IRELAND,9505,2132,4705,2395,272,0,2.03,631 +2013,ISLAMIC REPUBLIC OF IRAN,169015,1160,68466,80495,9343,9550,2.19,3665 +2013,ISRAEL,18290,7281,6554,3585,870,0,2.34,1130 +2013,ITALY (INCLUDING SAN MARINO),94169,14007,41178,35842,3142,0,1.57,4440 +2013,JAMAICA,2207,64,2030,0,112,0,0.8,195 +2013,JAPAN,339928,125408,140230,66407,7883,0,2.68,8631 +2013,JORDAN,6651,322,5248,510,571,0,0.92,121 +2013,KAZAKHSTAN,71679,38840,12964,18914,962,0,4.19,140 +2013,KENYA,3636,274,2673,0,688,0,0.08,495 +2013,KIRIBATI,17,0,17,0,0,0,0.15,3 +2013,KUWAIT,26819,0,16863,9434,408,114,7.46,1599 +2013,KYRGYZSTAN,2684,976,1309,171,228,0,0.47,41 +2013,LAO PEOPLE S DEMOCRATIC REPUBLIC,430,105,121,0,204,0,0.07,9 +2013,LATVIA,1931,82,960,752,136,0,0.96,310 +2013,LEBANON,6158,137,5228,0,793,0,1.16,247 +2013,LESOTHO,664,500,164,0,0,0,0.32,0 +2013,LIBERIA,261,0,235,0,26,0,0.06,18 +2013,LIBYAN ARAB JAMAHIRIYAH,15344,0,9745,3622,272,1705,2.45,339 +2013,LIECHTENSTEIN,14,0,0,14,0,0,0.37,0 +2013,LITHUANIA,3447,280,1669,1352,146,0,1.16,135 +2013,LUXEMBOURG,2741,49,2004,556,133,0,5.03,310 +2013,MACAU SPECIAL ADMINSTRATIVE REGION OF CHINA,322,0,322,0,0,0,0.57,0 +2013,MACEDONIA,2140,1244,711,81,104,0,1.03,9 +2013,MADAGASCAR,850,308,511,0,31,0,0.04,60 +2013,MALAWI,334,60,229,0,44,0,0.02,6 +2013,MALAYSIA,64497,15827,23656,20556,2918,1540,2.19,2286 +2013,MALDIVES,298,0,298,0,0,0,0.85,125 +2013,MALI,280,0,280,0,0,0,0.02,20 +2013,MALTA,638,0,638,0,0,0,1.53,1129 +2013,MARSHALL ISLANDS,28,0,28,0,0,0,0.54,0 +2013,MARTINIQUE,603,0,583,0,20,0,1.52,119 +2013,MAURITANIA,728,0,634,0,94,0,0.19,25 +2013,MAURITIUS,1110,456,654,0,0,0,0.88,330 +2013,MEXICO,133717,13640,75790,38831,4707,749,1.08,3124 +2013,MONGOLIA,10568,9531,1002,0,35,0,3.7,0 +2013,MONTENEGRO,613,397,217,0,0,0,0.98,11 +2013,MONTSERRAT,14,0,14,0,0,0,2.81,1 +2013,MOROCCO,16112,3104,10067,646,2294,0,0.47,610 +2013,MOZAMBIQUE,1096,10,811,97,177,0,0.04,60 +2013,MYANMAR (FORMERLY BURMA),3507,352,1853,1147,152,3,0.07,33 +2013,NAMIBIA,717,29,598,0,90,0,0.31,17 +2013,NAURU,12,0,12,0,0,0,1.16,4 +2013,NEPAL,1810,284,1119,0,407,0,0.07,80 +2013,NETHERLANDS,47247,8088,18056,20810,272,20,2.81,14274 +2013,NEW CALEDONIA,1157,366,775,0,16,0,4.51,11 +2013,NEW ZEALAND,9124,1545,4898,2486,158,38,2.04,953 +2013,NICARAGUA,1241,0,1153,0,88,0,0.21,17 +2013,NIGER,529,93,432,0,4,0,0.03,19 +2013,NIGERIA,26762,32,9838,7814,2720,6359,0.15,607 +2013,NIUE,2,0,2,0,0,0,1.04,0 +2013,NORWAY,15861,802,10960,3582,231,286,3.12,717 +2013,OCCUPIED PALESTINIAN TERRITORY,665,0,665,0,0,0,0.15,0 +2013,OMAN,16738,0,2870,12455,608,806,4.28,1075 +2013,PAKISTAN,44812,3728,18982,17886,4216,0,0.25,252 +2013,PALAU,70,0,70,0,0,0,3.36,15 +2013,PANAMA,2923,351,2250,0,322,0,0.77,3268 +2013,PAPUA NEW GUINEA,1687,0,1588,71,27,0,0.23,54 +2013,PARAGUAY,1482,0,1351,0,131,0,0.23,27 +2013,PERU,15586,784,7097,3238,1432,3036,0.51,617 +2013,PHILIPPINES,26760,10924,11257,1839,2740,0,0.27,1096 +2013,PLURINATIONAL STATE OF BOLIVIA,5159,0,2752,1934,422,51,0.5,44 +2013,POLAND,82432,56336,15528,8579,1977,11,2.13,558 +2013,PORTUGAL,12388,2741,6621,2346,680,0,1.18,1349 +2013,QATAR,23186,0,3215,18855,726,389,11.03,1700 +2013,REPUBLIC OF CAMEROON,1847,0,1417,239,190,0,0.08,106 +2013,REPUBLIC OF KOREA,161576,80733,44671,29741,6432,0,3.24,10442 +2013,REPUBLIC OF MOLDOVA,1363,151,586,470,156,0,0.33,18 +2013,REPUBLIC OF SOUTH SUDAN,395,0,395,0,0,0,0.03,31 +2013,REPUBLIC OF SUDAN,4220,0,3739,0,481,0,0.11,180 +2013,REUNION,1118,492,572,0,54,0,1.32,47 +2013,ROMANIA,19347,6153,6036,6145,1013,0,0.98,156 +2013,RUSSIAN FEDERATION,485018,114984,105329,246808,9044,8853,3.38,9524 +2013,RWANDA,219,0,203,0,15,0,0.02,16 +2013,SAINT HELENA,3,0,3,0,0,0,0.83,0 +2013,SAINT LUCIA,111,0,111,0,0,0,0.61,5 +2013,SAINT MARTIN (DUTCH PORTION),195,0,195,0,0,0,5.35,203 +2013,SAMOA,54,0,54,0,0,0,0.28,9 +2013,SAO TOME & PRINCIPE,31,0,31,0,0,0,0.17,9 +2013,SAUDI ARABIA,147545,0,98085,41812,7648,0,4.89,4526 +2013,SENEGAL,2297,224,1346,20,706,0,0.16,271 +2013,SERBIA,12240,8539,2242,1166,293,0,1.37,44 +2013,SEYCHELLES,110,0,110,0,0,0,1.15,158 +2013,SIERRA LEONE,325,0,282,0,43,0,0.05,7 +2013,SINGAPORE,15183,308,9324,5550,0,0,2.81,42215 +2013,SLOVAKIA,9024,3657,2090,2847,424,7,1.67,34 +2013,SLOVENIA,3859,1441,1831,432,155,0,1.87,74 +2013,SOLOMON ISLANDS,55,0,55,0,0,0,0.1,4 +2013,SOMALIA,166,0,166,0,0,0,0.02,57 +2013,SOUTH AFRICA,127182,106634,16337,2556,1655,0,2.38,3624 +2013,SPAIN,64640,11355,35077,16341,1868,0,1.39,9324 +2013,SRI LANKA,4224,551,3411,0,262,0,0.21,524 +2013,ST. KITTS-NEVIS,61,0,61,0,0,0,1.13,4 +2013,ST. PIERRE & MIQUELON,20,0,20,0,0,0,3.2,5 +2013,ST. VINCENT & THE GRENADINES,57,0,57,0,0,0,0.52,0 +2013,SURINAME,523,0,502,2,18,1,0.98,60 +2013,SWAZILAND,297,106,191,0,0,0,0.24,1 +2013,SWEDEN,12230,2298,8988,597,348,0,1.27,2064 +2013,SWITZERLAND,10970,128,8299,1925,618,0,1.35,1288 +2013,SYRIAN ARAB REPUBLIC,9937,1,6431,2683,544,279,0.51,403 +2013,TAIWAN,71022,41957,18614,8201,2251,0,3.04,2917 +2013,TAJIKISTAN,949,239,500,158,52,0,0.12,30 +2013,THAILAND,81835,18073,35244,23641,4876,0,1.21,3772 +2013,TIMOR-LESTE (FORMERLY EAST TIMOR),120,0,120,0,0,0,0.11,3 +2013,TOGO,725,0,470,11,244,0,0.1,77 +2013,TONGA,31,0,31,0,0,0,0.29,1 +2013,TRINIDAD AND TOBAGO,12692,0,1374,11209,109,0,9.41,709 +2013,TUNISIA,7545,0,3108,3309,1021,107,0.69,251 +2013,TURKEY,88566,34281,21125,23456,9702,1,1.16,1908 +2013,TURKMENISTAN,18199,0,5211,12628,360,0,3.47,389 +2013,TURKS AND CAICOS ISLANDS,54,0,54,0,0,0,1.64,0 +2013,TUVALU,3,0,3,0,0,0,0.0,0 +2013,UGANDA,1328,125,929,0,275,0,0.04,79 +2013,UKRAINE,74141,40630,7527,24643,1341,0,1.64,105 +2013,UNITED ARAB EMIRATES,46552,1947,4708,37226,2135,536,5.15,21260 +2013,UNITED KINGDOM,124966,38543,43698,41024,1116,586,1.95,11111 +2013,UNITED REPUBLIC OF TANZANIA,3048,62,2157,510,319,1,0.06,159 +2013,UNITED STATES OF AMERICA,1406916,450641,562260,379659,10528,3828,4.38,31592 +2013,URUGUAY,2069,2,1924,27,116,0,0.61,257 +2013,UZBEKISTAN,28185,1552,2216,23466,951,0,0.97,0 +2013,VANUATU,29,0,29,0,0,0,0.12,9 +2013,VENEZUELA,50156,217,28343,13240,1151,7205,1.66,1272 +2013,VIET NAM,40150,15359,11860,5109,7822,0,0.44,752 +2013,WALLIS AND FUTUNA ISLANDS,6,0,6,0,0,0,0.44,1 +2013,YEMEN,6953,134,5811,560,449,0,0.27,166 +2013,ZAMBIA,1079,125,708,0,246,0,0.07,43 +2013,ZIMBABWE,3184,1902,1119,0,162,0,0.21,9 +2014,AFGHANISTAN,2675,1194,1393,74,14,0,0.08,9 +2014,ALBANIA,1559,191,1053,16,299,0,0.54,23 +2014,ALGERIA,39651,149,14422,20151,2856,2073,1.02,581 +2014,ANDORRA,126,0,126,0,0,0,1.74,0 +2014,ANGOLA,9480,0,5310,158,340,3672,0.39,509 +2014,ANGUILLA,39,0,39,0,0,0,2.66,0 +2014,ANTIGUA & BARBUDA,145,0,145,0,0,0,1.59,44 +2014,ARGENTINA,55638,1588,25685,26368,1551,446,1.29,2079 +2014,ARMENIA,1508,0,234,1216,58,0,0.5,34 +2014,ARUBA,238,0,238,0,0,0,2.3,80 +2014,AUSTRALIA,98517,44558,32778,19800,1224,157,4.17,3754 +2014,AUSTRIA,16011,3129,8259,4025,598,0,1.88,553 +2014,AZERBAIJAN,10223,2,3174,5782,390,876,1.06,360 +2014,BAHAMAS,659,1,657,0,0,0,1.72,162 +2014,BAHRAIN,8546,0,604,7738,204,0,6.28,338 +2014,BANGLADESH,19959,957,4154,12536,2312,0,0.13,362 +2014,BARBADOS,347,0,317,7,22,0,1.22,27 +2014,BELARUS,17316,888,5072,10592,764,0,1.82,94 +2014,BELGIUM,25457,3215,13543,7869,830,0,2.27,5889 +2014,BELIZE,135,0,134,1,0,0,0.38,10 +2014,BENIN,1723,51,1483,0,190,0,0.16,156 +2014,BERMUDA,157,0,157,0,0,0,2.51,24 +2014,BHUTAN,273,69,111,0,94,0,0.36,3 +2014,"BONAIRE, SAINT EUSTATIUS, AND SABA",88,0,88,0,0,0,3.62,190 +2014,BOSNIA & HERZEGOVINA,6063,4738,1117,95,114,0,1.59,3 +2014,BOTSWANA,1918,1049,819,0,50,0,0.86,9 +2014,BRAZIL,144480,20089,92454,21297,9691,949,0.7,4895 +2014,BRITISH VIRGIN ISLANDS,49,0,49,0,0,0,1.64,0 +2014,BRUNEI (DARUSSALAM),2484,0,461,1848,48,127,5.95,122 +2014,BULGARIA,11567,6821,3018,1476,252,0,1.61,211 +2014,BURKINA FASO,777,0,722,0,55,0,0.04,29 +2014,BURUNDI,120,4,106,0,10,0,0.01,3 +2014,CAMBODIA,1823,251,1382,0,190,0,0.12,63 +2014,CANADA,146494,20667,67717,55436,1616,1059,4.12,914 +2014,CAPE VERDE,134,0,134,0,0,0,0.26,105 +2014,CAYMAN ISLANDS,148,0,148,0,0,0,2.5,9 +2014,CENTRAL AFRICAN REPUBLIC,82,0,82,0,0,0,0.02,29 +2014,CHAD,199,0,172,0,27,0,0.01,15 +2014,CHILE,22515,6989,12610,2223,680,13,1.27,702 +2014,CHINA (MAINLAND),2806634,2026492,344725,96504,338912,0,2.05,12066 +2014,COLOMBIA,22932,3988,10856,6186,1684,218,0.48,1636 +2014,COMOROS,42,0,42,0,0,0,0.05,3 +2014,CONGO,844,0,658,123,63,0,0.19,34 +2014,COOK ISLANDS,19,0,19,0,0,0,0.93,2 +2014,COSTA RICA,2116,63,1849,0,204,0,0.44,132 +2014,COTE D IVOIRE,3012,0,1627,1032,354,0,0.14,96 +2014,CROATIA,4593,670,2343,1261,319,0,1.08,98 +2014,CUBA,9500,1,8655,629,215,0,0.83,206 +2014,CURACAO,1604,0,1604,0,0,0,10.3,1446 +2014,CYPRUS,1653,3,1551,0,100,0,1.43,397 +2014,CZECH REPUBLIC,26309,16744,5202,3861,502,0,2.5,242 +2014,DEMOCRATIC PEOPLE S REPUBLIC OF KOREA,11052,9361,712,0,979,0,0.44,0 +2014,DEMOCRATIC REPUBLIC OF THE CONGO (FORMERLY ZAIRE),1274,0,1228,1,45,0,0.02,193 +2014,DENMARK,9135,2468,4606,1757,255,50,1.62,1383 +2014,DJIBOUTI,197,0,149,0,48,0,0.22,94 +2014,DOMINICA,37,0,37,0,0,0,0.51,2 +2014,DOMINICAN REPUBLIC,5874,765,3938,518,653,0,0.56,414 +2014,ECUADOR,11977,0,10114,548,898,417,0.75,664 +2014,EGYPT,55057,408,22480,25505,6664,0,0.61,1942 +2014,EL SALVADOR,1714,0,1578,0,136,0,0.28,130 +2014,EQUATORIAL GUINEA,1458,0,166,864,0,428,1.78,30 +2014,ERITREA,190,0,149,0,41,0,0.04,1 +2014,ESTONIA,5323,4767,223,272,61,0,4.04,317 +2014,ETHIOPIA,3163,232,2197,0,734,0,0.03,330 +2014,FAEROE ISLANDS,163,0,163,0,0,0,3.39,20 +2014,FALKLAND ISLANDS (MALVINAS),15,3,12,0,0,0,5.16,0 +2014,FEDERATED STATES OF MICRONESIA,41,0,41,0,0,0,0.39,1 +2014,FIJI,319,0,293,0,26,0,0.36,56 +2014,FINLAND,12899,4677,6482,1570,170,0,2.35,602 +2014,FRANCE (INCLUDING MONACO),82704,9419,50615,20358,2312,0,1.29,6306 +2014,FRENCH GUIANA,200,0,188,0,12,0,0.76,33 +2014,FRENCH POLYNESIA,219,0,219,0,0,0,0.78,45 +2014,GABON,1416,0,749,173,23,471,0.84,211 +2014,GAMBIA,140,0,138,1,0,0,0.07,12 +2014,GEORGIA,2451,310,774,1145,221,0,0.61,68 +2014,GERMANY,196314,84098,68263,39582,4365,5,2.43,8706 +2014,GHANA,3945,0,3188,349,408,0,0.15,104 +2014,GIBRALTAR,144,0,144,0,0,0,4.5,2509 +2014,GREECE,18358,7203,8906,1552,697,0,1.67,2301 +2014,GREENLAND,138,0,138,0,0,0,2.46,15 +2014,GRENADA,66,0,66,0,0,0,0.62,4 +2014,GUADELOUPE,700,145,514,0,41,0,1.5,93 +2014,GUATEMALA,4998,521,4000,0,476,0,0.31,311 +2014,GUINEA,668,0,599,0,68,0,0.05,21 +2014,GUINEA BISSAU,74,0,74,0,0,0,0.04,10 +2014,GUYANA,548,0,548,0,0,0,0.72,8 +2014,HAITI,780,0,739,0,41,0,0.07,29 +2014,HONDURAS,2583,145,2207,0,231,0,0.32,57 +2014,HONG KONG SPECIAL ADMINSTRATIVE REGION OF CHINA,12605,8420,2659,1268,258,0,1.74,12769 +2014,HUNGARY,11477,2400,4431,4361,286,0,1.16,146 +2014,ICELAND,541,90,451,0,0,0,1.65,171 +2014,INDIA,610411,407077,140199,25278,37400,457,0.47,4396 +2014,INDONESIA,126582,33370,63677,17035,7888,4612,0.5,1356 +2014,IRAQ,45935,0,33962,3448,1768,6757,1.3,611 +2014,IRELAND,9290,2114,4580,2325,272,0,1.99,711 +2014,ISLAMIC REPUBLIC OF IRAN,177115,900,66662,91127,8976,9450,2.27,4218 +2014,ISRAEL,17617,6775,6013,3930,898,0,2.22,1011 +2014,ITALY (INCLUDING SAN MARINO),87377,13532,39265,31670,2910,0,1.46,4265 +2014,JAMAICA,2024,75,1835,0,113,0,0.73,182 +2014,JAPAN,331074,122461,133395,67342,7876,0,2.61,8123 +2014,JORDAN,7213,375,6057,169,612,0,0.97,110 +2014,KAZAKHSTAN,67716,38375,8819,19438,1085,0,3.9,193 +2014,KENYA,3896,340,2796,0,759,0,0.09,194 +2014,KIRIBATI,17,0,17,0,0,0,0.15,3 +2014,KUWAIT,26018,0,15952,9433,517,116,6.93,1585 +2014,KYRGYZSTAN,2620,1229,1016,141,235,0,0.45,3 +2014,LAO PEOPLE S DEMOCRATIC REPUBLIC,533,84,122,0,326,0,0.08,9 +2014,LATVIA,1902,62,1002,676,163,0,0.96,292 +2014,LEBANON,6564,171,5643,0,750,0,1.17,222 +2014,LESOTHO,673,507,167,0,0,0,0.32,0 +2014,LIBERIA,255,0,215,0,40,0,0.06,19 +2014,LIBYAN ARAB JAMAHIRIYAH,15543,0,9885,3031,272,2355,2.48,183 +2014,LIECHTENSTEIN,12,0,0,12,0,0,0.31,0 +2014,LITHUANIA,3501,237,1852,1289,123,0,1.2,74 +2014,LUXEMBOURG,2634,55,1903,527,150,0,4.73,337 +2014,MACAU SPECIAL ADMINSTRATIVE REGION OF CHINA,350,0,320,31,0,0,0.61,56 +2014,MACEDONIA,2048,1177,709,69,93,0,0.99,10 +2014,MADAGASCAR,839,278,527,0,33,0,0.04,64 +2014,MALAWI,348,55,232,0,61,0,0.02,6 +2014,MALAYSIA,66218,15793,24442,21399,2992,1591,2.21,2271 +2014,MALDIVES,364,0,364,0,0,0,1.02,204 +2014,MALI,385,0,385,0,0,0,0.02,20 +2014,MALTA,640,0,640,0,0,0,1.53,1166 +2014,MARSHALL ISLANDS,28,0,28,0,0,0,0.52,0 +2014,MARTINIQUE,627,0,607,0,20,0,1.58,124 +2014,MAURITANIA,739,0,634,0,105,0,0.19,25 +2014,MAURITIUS,1153,474,680,0,0,0,0.91,351 +2014,MEXICO,130971,13358,73374,37801,4760,1678,1.04,3300 +2014,MONGOLIA,5683,4702,925,0,56,0,1.95,0 +2014,MONTENEGRO,603,387,216,0,0,0,0.96,15 +2014,MONTSERRAT,13,0,13,0,0,0,2.63,1 +2014,MOROCCO,16325,4176,9384,629,2137,0,0.47,656 +2014,MOZAMBIQUE,2298,225,1507,362,204,0,0.08,103 +2014,MYANMAR (FORMERLY BURMA),5899,390,4008,1318,179,4,0.11,34 +2014,NAMIBIA,1024,19,907,0,99,0,0.43,40 +2014,NAURU,13,0,13,0,0,0,1.32,4 +2014,NEPAL,2190,501,1267,0,422,0,0.08,119 +2014,NETHERLANDS,45624,9070,18272,18010,272,0,2.7,14210 +2014,NEW CALEDONIA,1170,426,729,0,14,0,4.5,9 +2014,NEW ZEALAND,9453,1505,5014,2744,150,39,2.1,918 +2014,NICARAGUA,1326,0,1231,0,95,0,0.22,19 +2014,NIGER,580,98,480,0,3,0,0.03,25 +2014,NIGERIA,26256,33,8830,9035,2720,5637,0.15,581 +2014,NIUE,3,0,3,0,0,0,1.56,0 +2014,NORWAY,12988,879,8542,3085,231,251,2.52,545 +2014,OCCUPIED PALESTINIAN TERRITORY,774,0,774,0,0,0,0.17,0 +2014,OMAN,16681,0,2904,12272,680,824,3.94,1442 +2014,PAKISTAN,45350,3535,19726,17736,4352,0,0.25,263 +2014,PALAU,71,0,71,0,0,0,3.37,15 +2014,PANAMA,2400,354,1748,0,298,0,0.62,3086 +2014,PAPUA NEW GUINEA,1723,0,1628,67,27,0,0.23,49 +2014,PARAGUAY,1555,0,1419,0,136,0,0.24,32 +2014,PERU,16838,780,7089,4512,1452,3005,0.54,681 +2014,PHILIPPINES,28812,11662,12224,1934,2992,0,0.29,980 +2014,PLURINATIONAL STATE OF BOLIVIA,5566,0,2897,2142,476,51,0.53,50 +2014,POLAND,77922,52194,15261,8372,2089,6,2.02,613 +2014,PORTUGAL,12286,2761,6608,2169,748,0,1.18,1359 +2014,QATAR,29412,0,1499,26725,816,372,13.54,1072 +2014,REPUBLIC OF CAMEROON,1910,0,1386,347,177,0,0.08,112 +2014,REPUBLIC OF KOREA,160119,84161,42616,26942,6399,0,3.2,10570 +2014,REPUBLIC OF MOLDOVA,1345,94,595,478,177,0,0.33,21 +2014,REPUBLIC OF SOUTH SUDAN,408,0,408,0,0,0,0.03,32 +2014,REPUBLIC OF SUDAN,4190,0,3717,0,473,0,0.11,226 +2014,REUNION,1138,463,620,0,54,0,1.33,49 +2014,ROMANIA,19090,6126,6042,5849,1074,0,0.97,220 +2014,RUSSIAN FEDERATION,465052,110403,107368,232204,9322,5755,3.24,17585 +2014,RWANDA,229,0,210,0,19,0,0.02,17 +2014,SAINT HELENA,3,0,3,0,0,0,0.84,0 +2014,SAINT LUCIA,111,0,111,0,0,0,0.61,5 +2014,SAINT MARTIN (DUTCH PORTION),200,0,200,0,0,0,5.31,205 +2014,SAMOA,54,0,54,0,0,0,0.28,9 +2014,SAO TOME & PRINCIPE,31,0,31,0,0,0,0.17,9 +2014,SAUDI ARABIA,163907,0,112689,43430,7782,5,5.31,4718 +2014,SENEGAL,2415,235,1493,21,666,0,0.16,284 +2014,SERBIA,10272,6721,2242,1005,304,0,1.16,70 +2014,SEYCHELLES,135,0,135,0,0,0,1.41,155 +2014,SIERRA LEONE,357,0,311,0,46,0,0.06,7 +2014,SINGAPORE,15373,456,9118,5800,0,0,2.79,42028 +2014,SLOVAKIA,8366,3624,1932,2356,451,3,1.54,29 +2014,SLOVENIA,3494,1136,1788,391,180,0,1.69,71 +2014,SOLOMON ISLANDS,55,0,55,0,0,0,0.1,4 +2014,SOMALIA,166,0,166,0,0,0,0.02,57 +2014,SOUTH AFRICA,133562,113068,16448,2404,1642,0,2.47,2945 +2014,SPAIN,63806,11852,35189,14781,1984,0,1.38,9892 +2014,SRI LANKA,5016,1059,3701,0,256,0,0.24,681 +2014,ST. KITTS-NEVIS,63,0,63,0,0,0,1.14,4 +2014,ST. PIERRE & MIQUELON,21,0,21,0,0,0,3.33,5 +2014,ST. VINCENT & THE GRENADINES,57,0,57,0,0,0,0.52,0 +2014,SURINAME,543,0,522,2,18,1,1.01,66 +2014,SWAZILAND,328,131,197,0,0,0,0.26,1 +2014,SWEDEN,11841,2183,8822,496,340,0,1.22,2107 +2014,SWITZERLAND,9628,148,7230,1668,583,0,1.17,1312 +2014,SYRIAN ARAB REPUBLIC,8373,1,5198,2480,517,178,0.45,219 +2014,TAIWAN,72013,42516,18985,8526,1985,0,3.08,3046 +2014,TAJIKISTAN,1415,404,689,166,156,0,0.17,52 +2014,THAILAND,86232,16612,41230,23633,4757,0,1.27,3980 +2014,TIMOR-LESTE (FORMERLY EAST TIMOR),128,0,128,0,0,0,0.11,3 +2014,TOGO,715,0,467,20,228,0,0.1,81 +2014,TONGA,33,0,33,0,0,0,0.31,3 +2014,TRINIDAD AND TOBAGO,12619,0,1243,11262,114,0,9.32,575 +2014,TUNISIA,7862,0,3235,3291,1241,96,0.71,239 +2014,TURKEY,94350,37875,21662,25111,9701,0,1.22,3054 +2014,TURKMENISTAN,18659,0,5453,12812,394,0,3.52,402 +2014,TURKS AND CAICOS ISLANDS,56,0,56,0,0,0,1.66,0 +2014,TUVALU,3,0,3,0,0,0,0.0,0 +2014,UGANDA,1426,125,1011,0,291,0,0.04,98 +2014,UKRAINE,61985,31649,8151,20874,1310,0,1.38,109 +2014,UNITED ARAB EMIRATES,57641,2157,17922,34852,2176,534,6.34,17317 +2014,UNITED KINGDOM,114486,31081,44274,37340,1218,573,1.78,10921 +2014,UNITED REPUBLIC OF TANZANIA,3153,178,2117,475,382,1,0.06,170 +2014,UNITED STATES OF AMERICA,1432855,450047,576531,390719,11314,4244,4.43,30722 +2014,URUGUAY,1840,2,1700,25,112,0,0.54,251 +2014,UZBEKISTAN,28692,1677,2086,23929,1000,0,0.97,0 +2014,VANUATU,42,0,42,0,0,0,0.16,10 +2014,VENEZUELA,50510,204,28445,12731,1088,8042,1.65,1256 +2014,VIET NAM,45517,19246,12694,5349,8229,0,0.49,761 +2014,WALLIS AND FUTUNA ISLANDS,6,0,6,0,0,0,0.44,1 +2014,YEMEN,6190,137,5090,581,381,0,0.24,153 +2014,ZAMBIA,1228,132,797,0,299,0,0.08,33 +2014,ZIMBABWE,3278,2097,1005,0,177,0,0.22,9 diff --git a/deps/explorer/datasets/iris.csv b/deps/explorer/datasets/iris.csv new file mode 100644 index 0000000000000000000000000000000000000000..94c1b12be9e2770dc7032c22f807d2b46c1949c2 --- /dev/null +++ b/deps/explorer/datasets/iris.csv @@ -0,0 +1,151 @@ +sepal_length,sepal_width,petal_length,petal_width,species +5.1,3.5,1.4,0.2,Iris-setosa +4.9,3.0,1.4,0.2,Iris-setosa +4.7,3.2,1.3,0.2,Iris-setosa +4.6,3.1,1.5,0.2,Iris-setosa +5.0,3.6,1.4,0.2,Iris-setosa +5.4,3.9,1.7,0.4,Iris-setosa +4.6,3.4,1.4,0.3,Iris-setosa +5.0,3.4,1.5,0.2,Iris-setosa +4.4,2.9,1.4,0.2,Iris-setosa +4.9,3.1,1.5,0.1,Iris-setosa +5.4,3.7,1.5,0.2,Iris-setosa +4.8,3.4,1.6,0.2,Iris-setosa +4.8,3.0,1.4,0.1,Iris-setosa +4.3,3.0,1.1,0.1,Iris-setosa +5.8,4.0,1.2,0.2,Iris-setosa +5.7,4.4,1.5,0.4,Iris-setosa +5.4,3.9,1.3,0.4,Iris-setosa +5.1,3.5,1.4,0.3,Iris-setosa +5.7,3.8,1.7,0.3,Iris-setosa +5.1,3.8,1.5,0.3,Iris-setosa +5.4,3.4,1.7,0.2,Iris-setosa +5.1,3.7,1.5,0.4,Iris-setosa +4.6,3.6,1.0,0.2,Iris-setosa +5.1,3.3,1.7,0.5,Iris-setosa +4.8,3.4,1.9,0.2,Iris-setosa +5.0,3.0,1.6,0.2,Iris-setosa +5.0,3.4,1.6,0.4,Iris-setosa +5.2,3.5,1.5,0.2,Iris-setosa +5.2,3.4,1.4,0.2,Iris-setosa +4.7,3.2,1.6,0.2,Iris-setosa +4.8,3.1,1.6,0.2,Iris-setosa +5.4,3.4,1.5,0.4,Iris-setosa +5.2,4.1,1.5,0.1,Iris-setosa +5.5,4.2,1.4,0.2,Iris-setosa +4.9,3.1,1.5,0.1,Iris-setosa +5.0,3.2,1.2,0.2,Iris-setosa +5.5,3.5,1.3,0.2,Iris-setosa +4.9,3.1,1.5,0.1,Iris-setosa +4.4,3.0,1.3,0.2,Iris-setosa +5.1,3.4,1.5,0.2,Iris-setosa +5.0,3.5,1.3,0.3,Iris-setosa +4.5,2.3,1.3,0.3,Iris-setosa +4.4,3.2,1.3,0.2,Iris-setosa +5.0,3.5,1.6,0.6,Iris-setosa +5.1,3.8,1.9,0.4,Iris-setosa +4.8,3.0,1.4,0.3,Iris-setosa +5.1,3.8,1.6,0.2,Iris-setosa +4.6,3.2,1.4,0.2,Iris-setosa +5.3,3.7,1.5,0.2,Iris-setosa +5.0,3.3,1.4,0.2,Iris-setosa +7.0,3.2,4.7,1.4,Iris-versicolor +6.4,3.2,4.5,1.5,Iris-versicolor +6.9,3.1,4.9,1.5,Iris-versicolor +5.5,2.3,4.0,1.3,Iris-versicolor +6.5,2.8,4.6,1.5,Iris-versicolor +5.7,2.8,4.5,1.3,Iris-versicolor +6.3,3.3,4.7,1.6,Iris-versicolor +4.9,2.4,3.3,1.0,Iris-versicolor +6.6,2.9,4.6,1.3,Iris-versicolor +5.2,2.7,3.9,1.4,Iris-versicolor +5.0,2.0,3.5,1.0,Iris-versicolor +5.9,3.0,4.2,1.5,Iris-versicolor +6.0,2.2,4.0,1.0,Iris-versicolor +6.1,2.9,4.7,1.4,Iris-versicolor +5.6,2.9,3.6,1.3,Iris-versicolor +6.7,3.1,4.4,1.4,Iris-versicolor +5.6,3.0,4.5,1.5,Iris-versicolor +5.8,2.7,4.1,1.0,Iris-versicolor +6.2,2.2,4.5,1.5,Iris-versicolor +5.6,2.5,3.9,1.1,Iris-versicolor +5.9,3.2,4.8,1.8,Iris-versicolor +6.1,2.8,4.0,1.3,Iris-versicolor +6.3,2.5,4.9,1.5,Iris-versicolor +6.1,2.8,4.7,1.2,Iris-versicolor +6.4,2.9,4.3,1.3,Iris-versicolor +6.6,3.0,4.4,1.4,Iris-versicolor +6.8,2.8,4.8,1.4,Iris-versicolor +6.7,3.0,5.0,1.7,Iris-versicolor +6.0,2.9,4.5,1.5,Iris-versicolor +5.7,2.6,3.5,1.0,Iris-versicolor +5.5,2.4,3.8,1.1,Iris-versicolor +5.5,2.4,3.7,1.0,Iris-versicolor +5.8,2.7,3.9,1.2,Iris-versicolor +6.0,2.7,5.1,1.6,Iris-versicolor +5.4,3.0,4.5,1.5,Iris-versicolor +6.0,3.4,4.5,1.6,Iris-versicolor +6.7,3.1,4.7,1.5,Iris-versicolor +6.3,2.3,4.4,1.3,Iris-versicolor +5.6,3.0,4.1,1.3,Iris-versicolor +5.5,2.5,4.0,1.3,Iris-versicolor +5.5,2.6,4.4,1.2,Iris-versicolor +6.1,3.0,4.6,1.4,Iris-versicolor +5.8,2.6,4.0,1.2,Iris-versicolor +5.0,2.3,3.3,1.0,Iris-versicolor +5.6,2.7,4.2,1.3,Iris-versicolor +5.7,3.0,4.2,1.2,Iris-versicolor +5.7,2.9,4.2,1.3,Iris-versicolor +6.2,2.9,4.3,1.3,Iris-versicolor +5.1,2.5,3.0,1.1,Iris-versicolor +5.7,2.8,4.1,1.3,Iris-versicolor +6.3,3.3,6.0,2.5,Iris-virginica +5.8,2.7,5.1,1.9,Iris-virginica +7.1,3.0,5.9,2.1,Iris-virginica +6.3,2.9,5.6,1.8,Iris-virginica +6.5,3.0,5.8,2.2,Iris-virginica +7.6,3.0,6.6,2.1,Iris-virginica +4.9,2.5,4.5,1.7,Iris-virginica +7.3,2.9,6.3,1.8,Iris-virginica +6.7,2.5,5.8,1.8,Iris-virginica +7.2,3.6,6.1,2.5,Iris-virginica +6.5,3.2,5.1,2.0,Iris-virginica +6.4,2.7,5.3,1.9,Iris-virginica +6.8,3.0,5.5,2.1,Iris-virginica +5.7,2.5,5.0,2.0,Iris-virginica +5.8,2.8,5.1,2.4,Iris-virginica +6.4,3.2,5.3,2.3,Iris-virginica +6.5,3.0,5.5,1.8,Iris-virginica +7.7,3.8,6.7,2.2,Iris-virginica +7.7,2.6,6.9,2.3,Iris-virginica +6.0,2.2,5.0,1.5,Iris-virginica +6.9,3.2,5.7,2.3,Iris-virginica +5.6,2.8,4.9,2.0,Iris-virginica +7.7,2.8,6.7,2.0,Iris-virginica +6.3,2.7,4.9,1.8,Iris-virginica +6.7,3.3,5.7,2.1,Iris-virginica +7.2,3.2,6.0,1.8,Iris-virginica +6.2,2.8,4.8,1.8,Iris-virginica +6.1,3.0,4.9,1.8,Iris-virginica +6.4,2.8,5.6,2.1,Iris-virginica +7.2,3.0,5.8,1.6,Iris-virginica +7.4,2.8,6.1,1.9,Iris-virginica +7.9,3.8,6.4,2.0,Iris-virginica +6.4,2.8,5.6,2.2,Iris-virginica +6.3,2.8,5.1,1.5,Iris-virginica +6.1,2.6,5.6,1.4,Iris-virginica +7.7,3.0,6.1,2.3,Iris-virginica +6.3,3.4,5.6,2.4,Iris-virginica +6.4,3.1,5.5,1.8,Iris-virginica +6.0,3.0,4.8,1.8,Iris-virginica +6.9,3.1,5.4,2.1,Iris-virginica +6.7,3.1,5.6,2.4,Iris-virginica +6.9,3.1,5.1,2.3,Iris-virginica +5.8,2.7,5.1,1.9,Iris-virginica +6.8,3.2,5.9,2.3,Iris-virginica +6.7,3.3,5.7,2.5,Iris-virginica +6.7,3.0,5.2,2.3,Iris-virginica +6.3,2.5,5.0,1.9,Iris-virginica +6.5,3.0,5.2,2.0,Iris-virginica +6.2,3.4,5.4,2.3,Iris-virginica +5.9,3.0,5.1,1.8,Iris-virginica diff --git a/deps/explorer/datasets/wine.csv b/deps/explorer/datasets/wine.csv new file mode 100644 index 0000000000000000000000000000000000000000..5317289c503404f791a00fa3689e74e43d54bd3b --- /dev/null +++ b/deps/explorer/datasets/wine.csv @@ -0,0 +1,179 @@ +class,alcohol,malic_acid,ash,alcalinity_of_ash,magnesium,total_phenols,flavanoids,nonflavanoid_phenols,proanthocyanins,color_intensity,hue,od280_over_od315_of_diluted_wines,proline +1,14.23,1.71,2.43,15.6,127,2.8,3.06,0.28,2.29,5.64,1.04,3.92,1065 +1,13.2,1.78,2.14,11.2,100,2.65,2.76,0.26,1.28,4.38,1.05,3.4,1050 +1,13.16,2.36,2.67,18.6,101,2.8,3.24,0.3,2.81,5.68,1.03,3.17,1185 +1,14.37,1.95,2.5,16.8,113,3.85,3.49,0.24,2.18,7.8,0.86,3.45,1480 +1,13.24,2.59,2.87,21.0,118,2.8,2.69,0.39,1.82,4.32,1.04,2.93,735 +1,14.2,1.76,2.45,15.2,112,3.27,3.39,0.34,1.97,6.75,1.05,2.85,1450 +1,14.39,1.87,2.45,14.6,96,2.5,2.52,0.3,1.98,5.25,1.02,3.58,1290 +1,14.06,2.15,2.61,17.6,121,2.6,2.51,0.31,1.25,5.05,1.06,3.58,1295 +1,14.83,1.64,2.17,14.0,97,2.8,2.98,0.29,1.98,5.2,1.08,2.85,1045 +1,13.86,1.35,2.27,16.0,98,2.98,3.15,0.22,1.85,7.22,1.01,3.55,1045 +1,14.1,2.16,2.3,18.0,105,2.95,3.32,0.22,2.38,5.75,1.25,3.17,1510 +1,14.12,1.48,2.32,16.8,95,2.2,2.43,0.26,1.57,5.0,1.17,2.82,1280 +1,13.75,1.73,2.41,16.0,89,2.6,2.76,0.29,1.81,5.6,1.15,2.9,1320 +1,14.75,1.73,2.39,11.4,91,3.1,3.69,0.43,2.81,5.4,1.25,2.73,1150 +1,14.38,1.87,2.38,12.0,102,3.3,3.64,0.29,2.96,7.5,1.2,3.0,1547 +1,13.63,1.81,2.7,17.2,112,2.85,2.91,0.3,1.46,7.3,1.28,2.88,1310 +1,14.3,1.92,2.72,20.0,120,2.8,3.14,0.33,1.97,6.2,1.07,2.65,1280 +1,13.83,1.57,2.62,20.0,115,2.95,3.4,0.4,1.72,6.6,1.13,2.57,1130 +1,14.19,1.59,2.48,16.5,108,3.3,3.93,0.32,1.86,8.7,1.23,2.82,1680 +1,13.64,3.1,2.56,15.2,116,2.7,3.03,0.17,1.66,5.1,0.96,3.36,845 +1,14.06,1.63,2.28,16.0,126,3.0,3.17,0.24,2.1,5.65,1.09,3.71,780 +1,12.93,3.8,2.65,18.6,102,2.41,2.41,0.25,1.98,4.5,1.03,3.52,770 +1,13.71,1.86,2.36,16.6,101,2.61,2.88,0.27,1.69,3.8,1.11,4.0,1035 +1,12.85,1.6,2.52,17.8,95,2.48,2.37,0.26,1.46,3.93,1.09,3.63,1015 +1,13.5,1.81,2.61,20.0,96,2.53,2.61,0.28,1.66,3.52,1.12,3.82,845 +1,13.05,2.05,3.22,25.0,124,2.63,2.68,0.47,1.92,3.58,1.13,3.2,830 +1,13.39,1.77,2.62,16.1,93,2.85,2.94,0.34,1.45,4.8,0.92,3.22,1195 +1,13.3,1.72,2.14,17.0,94,2.4,2.19,0.27,1.35,3.95,1.02,2.77,1285 +1,13.87,1.9,2.8,19.4,107,2.95,2.97,0.37,1.76,4.5,1.25,3.4,915 +1,14.02,1.68,2.21,16.0,96,2.65,2.33,0.26,1.98,4.7,1.04,3.59,1035 +1,13.73,1.5,2.7,22.5,101,3.0,3.25,0.29,2.38,5.7,1.19,2.71,1285 +1,13.58,1.66,2.36,19.1,106,2.86,3.19,0.22,1.95,6.9,1.09,2.88,1515 +1,13.68,1.83,2.36,17.2,104,2.42,2.69,0.42,1.97,3.84,1.23,2.87,990 +1,13.76,1.53,2.7,19.5,132,2.95,2.74,0.5,1.35,5.4,1.25,3.0,1235 +1,13.51,1.8,2.65,19.0,110,2.35,2.53,0.29,1.54,4.2,1.1,2.87,1095 +1,13.48,1.81,2.41,20.5,100,2.7,2.98,0.26,1.86,5.1,1.04,3.47,920 +1,13.28,1.64,2.84,15.5,110,2.6,2.68,0.34,1.36,4.6,1.09,2.78,880 +1,13.05,1.65,2.55,18.0,98,2.45,2.43,0.29,1.44,4.25,1.12,2.51,1105 +1,13.07,1.5,2.1,15.5,98,2.4,2.64,0.28,1.37,3.7,1.18,2.69,1020 +1,14.22,3.99,2.51,13.2,128,3.0,3.04,0.2,2.08,5.1,0.89,3.53,760 +1,13.56,1.71,2.31,16.2,117,3.15,3.29,0.34,2.34,6.13,0.95,3.38,795 +1,13.41,3.84,2.12,18.8,90,2.45,2.68,0.27,1.48,4.28,0.91,3.0,1035 +1,13.88,1.89,2.59,15.0,101,3.25,3.56,0.17,1.7,5.43,0.88,3.56,1095 +1,13.24,3.98,2.29,17.5,103,2.64,2.63,0.32,1.66,4.36,0.82,3.0,680 +1,13.05,1.77,2.1,17.0,107,3.0,3.0,0.28,2.03,5.04,0.88,3.35,885 +1,14.21,4.04,2.44,18.9,111,2.85,2.65,0.3,1.25,5.24,0.87,3.33,1080 +1,14.38,3.59,2.28,16.0,102,3.25,3.17,0.27,2.19,4.9,1.04,3.44,1065 +1,13.9,1.68,2.12,16.0,101,3.1,3.39,0.21,2.14,6.1,0.91,3.33,985 +1,14.1,2.02,2.4,18.8,103,2.75,2.92,0.32,2.38,6.2,1.07,2.75,1060 +1,13.94,1.73,2.27,17.4,108,2.88,3.54,0.32,2.08,8.9,1.12,3.1,1260 +1,13.05,1.73,2.04,12.4,92,2.72,3.27,0.17,2.91,7.2,1.12,2.91,1150 +1,13.83,1.65,2.6,17.2,94,2.45,2.99,0.22,2.29,5.6,1.24,3.37,1265 +1,13.82,1.75,2.42,14.0,111,3.88,3.74,0.32,1.87,7.05,1.01,3.26,1190 +1,13.77,1.9,2.68,17.1,115,3.0,2.79,0.39,1.68,6.3,1.13,2.93,1375 +1,13.74,1.67,2.25,16.4,118,2.6,2.9,0.21,1.62,5.85,0.92,3.2,1060 +1,13.56,1.73,2.46,20.5,116,2.96,2.78,0.2,2.45,6.25,0.98,3.03,1120 +1,14.22,1.7,2.3,16.3,118,3.2,3.0,0.26,2.03,6.38,0.94,3.31,970 +1,13.29,1.97,2.68,16.8,102,3.0,3.23,0.31,1.66,6.0,1.07,2.84,1270 +1,13.72,1.43,2.5,16.7,108,3.4,3.67,0.19,2.04,6.8,0.89,2.87,1285 +2,12.37,0.94,1.36,10.6,88,1.98,0.57,0.28,0.42,1.95,1.05,1.82,520 +2,12.33,1.1,2.28,16.0,101,2.05,1.09,0.63,0.41,3.27,1.25,1.67,680 +2,12.64,1.36,2.02,16.8,100,2.02,1.41,0.53,0.62,5.75,0.98,1.59,450 +2,13.67,1.25,1.92,18.0,94,2.1,1.79,0.32,0.73,3.8,1.23,2.46,630 +2,12.37,1.13,2.16,19.0,87,3.5,3.1,0.19,1.87,4.45,1.22,2.87,420 +2,12.17,1.45,2.53,19.0,104,1.89,1.75,0.45,1.03,2.95,1.45,2.23,355 +2,12.37,1.21,2.56,18.1,98,2.42,2.65,0.37,2.08,4.6,1.19,2.3,678 +2,13.11,1.01,1.7,15.0,78,2.98,3.18,0.26,2.28,5.3,1.12,3.18,502 +2,12.37,1.17,1.92,19.6,78,2.11,2.0,0.27,1.04,4.68,1.12,3.48,510 +2,13.34,0.94,2.36,17.0,110,2.53,1.3,0.55,0.42,3.17,1.02,1.93,750 +2,12.21,1.19,1.75,16.8,151,1.85,1.28,0.14,2.5,2.85,1.28,3.07,718 +2,12.29,1.61,2.21,20.4,103,1.1,1.02,0.37,1.46,3.05,0.906,1.82,870 +2,13.86,1.51,2.67,25.0,86,2.95,2.86,0.21,1.87,3.38,1.36,3.16,410 +2,13.49,1.66,2.24,24.0,87,1.88,1.84,0.27,1.03,3.74,0.98,2.78,472 +2,12.99,1.67,2.6,30.0,139,3.3,2.89,0.21,1.96,3.35,1.31,3.5,985 +2,11.96,1.09,2.3,21.0,101,3.38,2.14,0.13,1.65,3.21,0.99,3.13,886 +2,11.66,1.88,1.92,16.0,97,1.61,1.57,0.34,1.15,3.8,1.23,2.14,428 +2,13.03,0.9,1.71,16.0,86,1.95,2.03,0.24,1.46,4.6,1.19,2.48,392 +2,11.84,2.89,2.23,18.0,112,1.72,1.32,0.43,0.95,2.65,0.96,2.52,500 +2,12.33,0.99,1.95,14.8,136,1.9,1.85,0.35,2.76,3.4,1.06,2.31,750 +2,12.7,3.87,2.4,23.0,101,2.83,2.55,0.43,1.95,2.57,1.19,3.13,463 +2,12.0,0.92,2.0,19.0,86,2.42,2.26,0.3,1.43,2.5,1.38,3.12,278 +2,12.72,1.81,2.2,18.8,86,2.2,2.53,0.26,1.77,3.9,1.16,3.14,714 +2,12.08,1.13,2.51,24.0,78,2.0,1.58,0.4,1.4,2.2,1.31,2.72,630 +2,13.05,3.86,2.32,22.5,85,1.65,1.59,0.61,1.62,4.8,0.84,2.01,515 +2,11.84,0.89,2.58,18.0,94,2.2,2.21,0.22,2.35,3.05,0.79,3.08,520 +2,12.67,0.98,2.24,18.0,99,2.2,1.94,0.3,1.46,2.62,1.23,3.16,450 +2,12.16,1.61,2.31,22.8,90,1.78,1.69,0.43,1.56,2.45,1.33,2.26,495 +2,11.65,1.67,2.62,26.0,88,1.92,1.61,0.4,1.34,2.6,1.36,3.21,562 +2,11.64,2.06,2.46,21.6,84,1.95,1.69,0.48,1.35,2.8,1.0,2.75,680 +2,12.08,1.33,2.3,23.6,70,2.2,1.59,0.42,1.38,1.74,1.07,3.21,625 +2,12.08,1.83,2.32,18.5,81,1.6,1.5,0.52,1.64,2.4,1.08,2.27,480 +2,12.0,1.51,2.42,22.0,86,1.45,1.25,0.5,1.63,3.6,1.05,2.65,450 +2,12.69,1.53,2.26,20.7,80,1.38,1.46,0.58,1.62,3.05,0.96,2.06,495 +2,12.29,2.83,2.22,18.0,88,2.45,2.25,0.25,1.99,2.15,1.15,3.3,290 +2,11.62,1.99,2.28,18.0,98,3.02,2.26,0.17,1.35,3.25,1.16,2.96,345 +2,12.47,1.52,2.2,19.0,162,2.5,2.27,0.32,3.28,2.6,1.16,2.63,937 +2,11.81,2.12,2.74,21.5,134,1.6,0.99,0.14,1.56,2.5,0.95,2.26,625 +2,12.29,1.41,1.98,16.0,85,2.55,2.5,0.29,1.77,2.9,1.23,2.74,428 +2,12.37,1.07,2.1,18.5,88,3.52,3.75,0.24,1.95,4.5,1.04,2.77,660 +2,12.29,3.17,2.21,18.0,88,2.85,2.99,0.45,2.81,2.3,1.42,2.83,406 +2,12.08,2.08,1.7,17.5,97,2.23,2.17,0.26,1.4,3.3,1.27,2.96,710 +2,12.6,1.34,1.9,18.5,88,1.45,1.36,0.29,1.35,2.45,1.04,2.77,562 +2,12.34,2.45,2.46,21.0,98,2.56,2.11,0.34,1.31,2.8,0.8,3.38,438 +2,11.82,1.72,1.88,19.5,86,2.5,1.64,0.37,1.42,2.06,0.94,2.44,415 +2,12.51,1.73,1.98,20.5,85,2.2,1.92,0.32,1.48,2.94,1.04,3.57,672 +2,12.42,2.55,2.27,22.0,90,1.68,1.84,0.66,1.42,2.7,0.86,3.3,315 +2,12.25,1.73,2.12,19.0,80,1.65,2.03,0.37,1.63,3.4,1.0,3.17,510 +2,12.72,1.75,2.28,22.5,84,1.38,1.76,0.48,1.63,3.3,0.88,2.42,488 +2,12.22,1.29,1.94,19.0,92,2.36,2.04,0.39,2.08,2.7,0.86,3.02,312 +2,11.61,1.35,2.7,20.0,94,2.74,2.92,0.29,2.49,2.65,0.96,3.26,680 +2,11.46,3.74,1.82,19.5,107,3.18,2.58,0.24,3.58,2.9,0.75,2.81,562 +2,12.52,2.43,2.17,21.0,88,2.55,2.27,0.26,1.22,2.0,0.9,2.78,325 +2,11.76,2.68,2.92,20.0,103,1.75,2.03,0.6,1.05,3.8,1.23,2.5,607 +2,11.41,0.74,2.5,21.0,88,2.48,2.01,0.42,1.44,3.08,1.1,2.31,434 +2,12.08,1.39,2.5,22.5,84,2.56,2.29,0.43,1.04,2.9,0.93,3.19,385 +2,11.03,1.51,2.2,21.5,85,2.46,2.17,0.52,2.01,1.9,1.71,2.87,407 +2,11.82,1.47,1.99,20.8,86,1.98,1.6,0.3,1.53,1.95,0.95,3.33,495 +2,12.42,1.61,2.19,22.5,108,2.0,2.09,0.34,1.61,2.06,1.06,2.96,345 +2,12.77,3.43,1.98,16.0,80,1.63,1.25,0.43,0.83,3.4,0.7,2.12,372 +2,12.0,3.43,2.0,19.0,87,2.0,1.64,0.37,1.87,1.28,0.93,3.05,564 +2,11.45,2.4,2.42,20.0,96,2.9,2.79,0.32,1.83,3.25,0.8,3.39,625 +2,11.56,2.05,3.23,28.5,119,3.18,5.08,0.47,1.87,6.0,0.93,3.69,465 +2,12.42,4.43,2.73,26.5,102,2.2,2.13,0.43,1.71,2.08,0.92,3.12,365 +2,13.05,5.8,2.13,21.5,86,2.62,2.65,0.3,2.01,2.6,0.73,3.1,380 +2,11.87,4.31,2.39,21.0,82,2.86,3.03,0.21,2.91,2.8,0.75,3.64,380 +2,12.07,2.16,2.17,21.0,85,2.6,2.65,0.37,1.35,2.76,0.86,3.28,378 +2,12.43,1.53,2.29,21.5,86,2.74,3.15,0.39,1.77,3.94,0.69,2.84,352 +2,11.79,2.13,2.78,28.5,92,2.13,2.24,0.58,1.76,3.0,0.97,2.44,466 +2,12.37,1.63,2.3,24.5,88,2.22,2.45,0.4,1.9,2.12,0.89,2.78,342 +2,12.04,4.3,2.38,22.0,80,2.1,1.75,0.42,1.35,2.6,0.79,2.57,580 +3,12.86,1.35,2.32,18.0,122,1.51,1.25,0.21,0.94,4.1,0.76,1.29,630 +3,12.88,2.99,2.4,20.0,104,1.3,1.22,0.24,0.83,5.4,0.74,1.42,530 +3,12.81,2.31,2.4,24.0,98,1.15,1.09,0.27,0.83,5.7,0.66,1.36,560 +3,12.7,3.55,2.36,21.5,106,1.7,1.2,0.17,0.84,5.0,0.78,1.29,600 +3,12.51,1.24,2.25,17.5,85,2.0,0.58,0.6,1.25,5.45,0.75,1.51,650 +3,12.6,2.46,2.2,18.5,94,1.62,0.66,0.63,0.94,7.1,0.73,1.58,695 +3,12.25,4.72,2.54,21.0,89,1.38,0.47,0.53,0.8,3.85,0.75,1.27,720 +3,12.53,5.51,2.64,25.0,96,1.79,0.6,0.63,1.1,5.0,0.82,1.69,515 +3,13.49,3.59,2.19,19.5,88,1.62,0.48,0.58,0.88,5.7,0.81,1.82,580 +3,12.84,2.96,2.61,24.0,101,2.32,0.6,0.53,0.81,4.92,0.89,2.15,590 +3,12.93,2.81,2.7,21.0,96,1.54,0.5,0.53,0.75,4.6,0.77,2.31,600 +3,13.36,2.56,2.35,20.0,89,1.4,0.5,0.37,0.64,5.6,0.7,2.47,780 +3,13.52,3.17,2.72,23.5,97,1.55,0.52,0.5,0.55,4.35,0.89,2.06,520 +3,13.62,4.95,2.35,20.0,92,2.0,0.8,0.47,1.02,4.4,0.91,2.05,550 +3,12.25,3.88,2.2,18.5,112,1.38,0.78,0.29,1.14,8.21,0.65,2.0,855 +3,13.16,3.57,2.15,21.0,102,1.5,0.55,0.43,1.3,4.0,0.6,1.68,830 +3,13.88,5.04,2.23,20.0,80,0.98,0.34,0.4,0.68,4.9,0.58,1.33,415 +3,12.87,4.61,2.48,21.5,86,1.7,0.65,0.47,0.86,7.65,0.54,1.86,625 +3,13.32,3.24,2.38,21.5,92,1.93,0.76,0.45,1.25,8.42,0.55,1.62,650 +3,13.08,3.9,2.36,21.5,113,1.41,1.39,0.34,1.14,9.4,0.57,1.33,550 +3,13.5,3.12,2.62,24.0,123,1.4,1.57,0.22,1.25,8.6,0.59,1.3,500 +3,12.79,2.67,2.48,22.0,112,1.48,1.36,0.24,1.26,10.8,0.48,1.47,480 +3,13.11,1.9,2.75,25.5,116,2.2,1.28,0.26,1.56,7.1,0.61,1.33,425 +3,13.23,3.3,2.28,18.5,98,1.8,0.83,0.61,1.87,10.52,0.56,1.51,675 +3,12.58,1.29,2.1,20.0,103,1.48,0.58,0.53,1.4,7.6,0.58,1.55,640 +3,13.17,5.19,2.32,22.0,93,1.74,0.63,0.61,1.55,7.9,0.6,1.48,725 +3,13.84,4.12,2.38,19.5,89,1.8,0.83,0.48,1.56,9.01,0.57,1.64,480 +3,12.45,3.03,2.64,27.0,97,1.9,0.58,0.63,1.14,7.5,0.67,1.73,880 +3,14.34,1.68,2.7,25.0,98,2.8,1.31,0.53,2.7,13.0,0.57,1.96,660 +3,13.48,1.67,2.64,22.5,89,2.6,1.1,0.52,2.29,11.75,0.57,1.78,620 +3,12.36,3.83,2.38,21.0,88,2.3,0.92,0.5,1.04,7.65,0.56,1.58,520 +3,13.69,3.26,2.54,20.0,107,1.83,0.56,0.5,0.8,5.88,0.96,1.82,680 +3,12.85,3.27,2.58,22.0,106,1.65,0.6,0.6,0.96,5.58,0.87,2.11,570 +3,12.96,3.45,2.35,18.5,106,1.39,0.7,0.4,0.94,5.28,0.68,1.75,675 +3,13.78,2.76,2.3,22.0,90,1.35,0.68,0.41,1.03,9.58,0.7,1.68,615 +3,13.73,4.36,2.26,22.5,88,1.28,0.47,0.52,1.15,6.62,0.78,1.75,520 +3,13.45,3.7,2.6,23.0,111,1.7,0.92,0.43,1.46,10.68,0.85,1.56,695 +3,12.82,3.37,2.3,19.5,88,1.48,0.66,0.4,0.97,10.26,0.72,1.75,685 +3,13.58,2.58,2.69,24.5,105,1.55,0.84,0.39,1.54,8.66,0.74,1.8,750 +3,13.4,4.6,2.86,25.0,112,1.98,0.96,0.27,1.11,8.5,0.67,1.92,630 +3,12.2,3.03,2.32,19.0,96,1.25,0.49,0.4,0.73,5.5,0.66,1.83,510 +3,12.77,2.39,2.28,19.5,86,1.39,0.51,0.48,0.64,9.899999,0.57,1.63,470 +3,14.16,2.51,2.48,20.0,91,1.68,0.7,0.44,1.24,9.7,0.62,1.71,660 +3,13.71,5.65,2.45,20.5,95,1.68,0.61,0.52,1.06,7.7,0.64,1.74,740 +3,13.4,3.91,2.48,23.0,102,1.8,0.75,0.43,1.41,7.3,0.7,1.56,750 +3,13.27,4.28,2.26,20.0,120,1.59,0.69,0.43,1.35,10.2,0.59,1.56,835 +3,13.17,2.59,2.37,20.0,120,1.65,0.68,0.53,1.46,9.3,0.6,1.62,840 +3,14.13,4.1,2.74,24.5,96,2.05,0.76,0.56,1.35,9.2,0.61,1.6,560 diff --git a/deps/explorer/hex_metadata.config b/deps/explorer/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..d6092675ed37536af7f4d1363b405b6421599308 --- /dev/null +++ b/deps/explorer/hex_metadata.config @@ -0,0 +1,113 @@ +{<<"links">>, + [{<<"Changelog">>, + <<"https://github.com/elixir-nx/explorer/blob/v0.10.1/CHANGELOG.md">>}, + {<<"GitHub">>,<<"https://github.com/elixir-nx/explorer">>}]}. +{<<"name">>,<<"explorer">>}. +{<<"version">>,<<"0.10.1">>}. +{<<"description">>, + <<"Series (one-dimensional) and dataframes (two-dimensional) for fast data exploration in Elixir">>}. +{<<"elixir">>,<<"~> 1.14">>}. +{<<"app">>,<<"explorer">>}. +{<<"files">>, + [<<"lib">>,<<"lib/explorer">>,<<"lib/explorer/remote.ex">>, + <<"lib/explorer/duration.ex">>,<<"lib/explorer/series.ex">>, + <<"lib/explorer/datasets.ex">>,<<"lib/explorer/comptime_utils.ex">>, + <<"lib/explorer/polars_backend">>, + <<"lib/explorer/polars_backend/native.ex">>, + <<"lib/explorer/polars_backend/series.ex">>, + <<"lib/explorer/polars_backend/expression.ex">>, + <<"lib/explorer/polars_backend/lazy_frame.ex">>, + <<"lib/explorer/polars_backend/shared.ex">>, + <<"lib/explorer/polars_backend/data_frame.ex">>,<<"lib/explorer/fss.ex">>, + <<"lib/explorer/backend.ex">>,<<"lib/explorer/backend">>, + <<"lib/explorer/backend/series.ex">>, + <<"lib/explorer/backend/query_frame.ex">>, + <<"lib/explorer/backend/lazy_series.ex">>, + <<"lib/explorer/backend/data_frame.ex">>,<<"lib/explorer/query.ex">>, + <<"lib/explorer/polars_backend.ex">>,<<"lib/explorer/shared.ex">>, + <<"lib/explorer/application.ex">>,<<"lib/explorer/fss">>, + <<"lib/explorer/fss/s3.ex">>,<<"lib/explorer/fss/utils.ex">>, + <<"lib/explorer/fss/http.ex">>,<<"lib/explorer/data_frame.ex">>, + <<"lib/explorer/tensor_frame.ex">>,<<"lib/explorer/remote">>, + <<"lib/explorer/remote/holder.ex">>,<<"lib/explorer/remote/local_gc.ex">>, + <<"lib/explorer.ex">>,<<"native">>,<<"native/explorer">>, + <<"native/explorer/Cargo.toml">>,<<"native/explorer/Cross.toml">>, + <<"native/explorer/Cargo.lock">>,<<"native/explorer/.cargo">>, + <<"native/explorer/.cargo/config.toml">>,<<"native/explorer/.gitignore">>, + <<"native/explorer/rust-toolchain.toml">>,<<"native/explorer/src">>, + <<"native/explorer/src/series">>, + <<"native/explorer/src/series/from_list.rs">>, + <<"native/explorer/src/series/log.rs">>,<<"native/explorer/src/series.rs">>, + <<"native/explorer/src/lazyframe.rs">>,<<"native/explorer/src/dataframe">>, + <<"native/explorer/src/dataframe/io.rs">>, + <<"native/explorer/src/dataframe.rs">>, + <<"native/explorer/src/local_message.rs">>, + <<"native/explorer/src/expressions.rs">>,<<"native/explorer/src/error.rs">>, + <<"native/explorer/src/encoding.rs">>,<<"native/explorer/src/datatypes">>, + <<"native/explorer/src/datatypes/ex_dtypes.rs">>, + <<"native/explorer/src/lib.rs">>,<<"native/explorer/src/cloud_writer.rs">>, + <<"native/explorer/src/lazyframe">>, + <<"native/explorer/src/lazyframe/io.rs">>, + <<"native/explorer/src/datatypes.rs">>,<<"datasets">>, + <<"datasets/iris.csv">>,<<"datasets/wine.csv">>, + <<"datasets/fossil_fuels.csv">>, + <<"checksum-Elixir.Explorer.PolarsBackend.Native.exs">>,<<"mix.exs">>, + <<"CHANGELOG.md">>,<<"README.md">>,<<"LICENSE">>]}. +{<<"licenses">>,[<<"MIT">>]}. +{<<"requirements">>, + [[{<<"name">>,<<"aws_signature">>}, + {<<"app">>,<<"aws_signature">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.3">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"fss">>}, + {<<"app">>,<<"fss">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.1">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"rustler_precompiled">>}, + {<<"app">>,<<"rustler_precompiled">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.7">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"table">>}, + {<<"app">>,<<"table">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.1.2">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"table_rex">>}, + {<<"app">>,<<"table_rex">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 3.1.1 or ~> 4.0.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"decimal">>}, + {<<"app">>,<<"decimal">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 2.1">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"flame">>}, + {<<"app">>,<<"flame">>}, + {<<"optional">>,true}, + {<<"requirement">>,<<"~> 0.3">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"castore">>}, + {<<"app">>,<<"castore">>}, + {<<"optional">>,true}, + {<<"requirement">>,<<"~> 1.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"adbc">>}, + {<<"app">>,<<"adbc">>}, + {<<"optional">>,true}, + {<<"requirement">>,<<"~> 0.1">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"nx">>}, + {<<"app">>,<<"nx">>}, + {<<"optional">>,true}, + {<<"requirement">>,<<"~> 0.4">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"rustler">>}, + {<<"app">>,<<"rustler">>}, + {<<"optional">>,true}, + {<<"requirement">>,<<"~> 0.34.0">>}, + {<<"repository">>,<<"hexpm">>}]]}. +{<<"build_tools">>,[<<"mix">>]}. diff --git a/deps/explorer/lib/explorer.ex b/deps/explorer/lib/explorer.ex new file mode 100644 index 0000000000000000000000000000000000000000..eda5ec8c5726ebe1a1007460492d1c7bd073823b --- /dev/null +++ b/deps/explorer/lib/explorer.ex @@ -0,0 +1,8 @@ +defmodule Explorer do + @external_resource "README.md" + + @moduledoc "README.md" + |> File.read!() + |> String.split("") + |> Enum.fetch!(1) +end diff --git a/deps/explorer/lib/explorer/application.ex b/deps/explorer/lib/explorer/application.ex new file mode 100644 index 0000000000000000000000000000000000000000..c2a324f81acf4b06e95f46a3c1387b0d32db40e2 --- /dev/null +++ b/deps/explorer/lib/explorer/application.ex @@ -0,0 +1,13 @@ +defmodule Explorer.Application do + @moduledoc false + use Application + + def start(_type, _args) do + children = [ + {DynamicSupervisor, name: Explorer.Remote.Supervisor, strategy: :one_for_one}, + Explorer.Remote.LocalGC + ] + + Supervisor.start_link(children, strategy: :one_for_one) + end +end diff --git a/deps/explorer/lib/explorer/backend.ex b/deps/explorer/lib/explorer/backend.ex new file mode 100644 index 0000000000000000000000000000000000000000..7664cdf98fece918bbfa6875826cda47849d5d34 --- /dev/null +++ b/deps/explorer/lib/explorer/backend.ex @@ -0,0 +1,55 @@ +defmodule Explorer.Backend do + @moduledoc """ + The behaviour for Explorer backends and associated functions. + + Each backend is a module with `DataFrame` and `Series` submodules that match the + respective behaviours for each. + + The default backend is read from the application environment. Currently, the only + backend is an in-memory, eager one based on + [`Polars`](https://github.com/pola-rs/polars). When alternatives are + available, you can use them by configuring your runtime: + + # config/runtime.exs + import Config + config :explorer, default_backend: Lib.CustomBackend + + """ + + @backend_key {Explorer, :default_backend} + + @doc """ + Sets the current process default backend to `backend`. + + The default backend is stored only in the process dictionary. This means if + you start a separate process, such as `Task`, the default backend must be set + on the new process too. + + ## Examples + iex> Explorer.Backend.put(Lib.CustomBackend) + Explorer.PolarsBackend + iex> Explorer.Backend.get() + Lib.CustomBackend + """ + def put(backend) do + Process.put(@backend_key, backend!(backend)) || + backend!(Application.fetch_env!(:explorer, :default_backend)) + end + + @doc """ + Gets the default backend for the current process. + """ + def get do + Process.get(@backend_key) || backend!(Application.fetch_env!(:explorer, :default_backend)) + end + + ## Helpers + + defp backend!(backend) when is_atom(backend), + do: backend + + defp backend!(other) do + raise ArgumentError, + "backend must be an atom, got: #{inspect(other)}" + end +end diff --git a/deps/explorer/lib/explorer/backend/data_frame.ex b/deps/explorer/lib/explorer/backend/data_frame.ex new file mode 100644 index 0000000000000000000000000000000000000000..149ac64935e7a3ec1af12d85945e58afaa54c58e --- /dev/null +++ b/deps/explorer/lib/explorer/backend/data_frame.ex @@ -0,0 +1,350 @@ +defmodule Explorer.Backend.DataFrame do + @moduledoc """ + The behaviour for DataFrame backends. + """ + + @type t :: struct() + + @type df :: Explorer.DataFrame.t() + + @type option(type) :: type | nil + + # Types for IO operations + @type ok_result() :: :ok | {:error, Exception.t()} + @type io_result(t) :: {:ok, t} | {:error, Exception.t()} + + # Generic result + @type result(t) :: {:ok, t} | {:error, term()} + + @type series :: Explorer.Series.t() + @type column_name :: String.t() + @type dtype :: Explorer.Series.dtype() + @type dtypes :: %{column_name() => dtype()} + @type io_dtypes :: [{column_name(), dtype()}] + + @type basic_types :: float() | integer() | String.t() | Date.t() | DateTime.t() + @type mutate_value :: + series() + | basic_types() + | [basic_types()] + | (df() -> series() | basic_types() | [basic_types()]) + + @type query_frame :: Explorer.Backend.QueryFrame.t() + @type lazy_series :: Explorer.Backend.LazySeries.t() + + @type compression :: {algorithm :: option(atom()), level :: option(integer())} + @type columns_for_io :: list(column_name()) | list(pos_integer()) | nil + + @type fs_entry :: Explorer.DataFrame.fs_entry() + + # IO: query + @callback from_query( + Adbc.Connection.t(), + query :: String.t(), + params :: list(term) + ) :: result(df) + + # IO: CSV + @callback from_csv( + entry :: fs_entry(), + io_dtypes, + delimiter :: String.t(), + nil_values :: list(String.t()), + skip_rows :: integer(), + skip_rows_after_header :: integer(), + header? :: boolean(), + encoding :: String.t(), + max_rows :: option(integer()), + columns :: columns_for_io(), + infer_schema_length :: option(integer()), + parse_dates :: boolean(), + eol_delimiter :: option(String.t()) + ) :: io_result(df) + @callback to_csv( + df, + entry :: fs_entry(), + header? :: boolean(), + delimiter :: String.t(), + streaming :: boolean() + ) :: + ok_result() + @callback dump_csv(df, header? :: boolean(), delimiter :: String.t()) :: io_result(binary()) + + @callback load_csv( + contents :: String.t(), + io_dtypes, + delimiter :: String.t(), + nil_values :: list(String.t()), + skip_rows :: integer(), + skip_rows_after_header :: integer(), + header? :: boolean(), + encoding :: String.t(), + max_rows :: option(integer()), + columns :: columns_for_io(), + infer_schema_length :: option(integer()), + parse_dates :: boolean(), + eol_delimiter :: option(String.t()) + ) :: io_result(df) + + # IO: Parquet + @callback from_parquet( + entry :: fs_entry(), + max_rows :: option(integer()), + columns :: columns_for_io(), + rechunk :: boolean() + ) :: io_result(df) + @callback to_parquet( + df, + entry :: fs_entry(), + compression(), + streaming :: boolean() + ) :: + ok_result() + @callback dump_parquet(df, compression()) :: io_result(binary()) + @callback load_parquet(contents :: binary()) :: io_result(df) + + # IO: IPC + @callback from_ipc( + entry :: fs_entry(), + columns :: columns_for_io() + ) :: io_result(df) + @callback to_ipc(df, entry :: fs_entry(), compression(), streaming :: boolean()) :: + ok_result() + @callback dump_ipc(df, compression()) :: io_result(binary()) + @callback load_ipc( + contents :: binary(), + columns :: columns_for_io() + ) :: io_result(df) + + # IO: IPC Stream + @callback from_ipc_stream( + filename :: fs_entry(), + columns :: columns_for_io() + ) :: io_result(df) + @callback to_ipc_stream( + df, + entry :: fs_entry(), + compression() + ) :: + ok_result() + @callback dump_ipc_stream(df, compression()) :: io_result(binary()) + @callback load_ipc_stream( + contents :: binary(), + columns :: columns_for_io() + ) :: io_result(df) + + # IO: IPC NDJSON + @callback from_ndjson( + filename :: fs_entry(), + infer_schema_length :: integer(), + batch_size :: integer() + ) :: io_result(df) + @callback to_ndjson(df, entry :: fs_entry()) :: ok_result() + + @callback dump_ndjson(df) :: io_result(binary()) + + @callback load_ndjson( + contents :: String.t(), + infer_schema_length :: integer(), + batch_size :: integer() + ) :: io_result(df) + + # Conversion + + @callback lazy() :: module() + @callback lazy(df) :: df + @callback compute(df) :: df + @callback from_tabular(Table.Reader.t(), io_dtypes) :: df + @callback from_series([{binary(), Series.t()}]) :: df + @callback to_rows(df, atom_keys? :: boolean()) :: [map()] + @callback to_rows_stream(df, atom_keys? :: boolean(), chunk_size :: integer()) :: Enumerable.t() + + # Ownership + + @callback owner_reference(df) :: reference() | nil + @callback owner_import(term()) :: io_result(df) + @callback owner_export(df) :: io_result(term()) + + # Introspection + + @callback n_rows(df) :: integer() + @callback inspect(df, opts :: Inspect.Opts.t()) :: Inspect.Algebra.t() + @callback re_dtype(String.t()) :: dtype() + + # Single table verbs + + @callback head(df, rows :: integer()) :: df + @callback tail(df, rows :: integer()) :: df + @callback select(df, out_df :: df()) :: df + @callback mask(df, mask :: series) :: df + @callback filter_with(df, out_df :: df(), lazy_series()) :: df + @callback mutate_with(df, out_df :: df(), mutations :: [{column_name(), lazy_series()}]) :: df + @callback sort_with( + df, + out_df :: df(), + directions :: [{:asc | :desc, lazy_series()}], + maintain_order? :: boolean(), + multithreaded? :: boolean(), + nulls_last? :: boolean() + ) :: df + @callback distinct(df, out_df :: df(), columns :: [column_name()]) :: df + @callback rename(df, out_df :: df(), [{old :: column_name(), new :: column_name()}]) :: df + @callback dummies(df, out_df :: df(), columns :: [column_name()]) :: df + @callback sample( + df, + n_or_frac :: number(), + replace :: boolean(), + shuffle :: boolean(), + seed :: option(integer()) + ) :: df + @callback pull(df, column :: column_name()) :: series + @callback slice(df, indices :: list(integer()) | series() | %Range{}) :: df + @callback slice(df, offset :: integer(), length :: integer()) :: df + @callback drop_nil(df, columns :: [column_name()]) :: df + @callback pivot_wider( + df, + id_columns :: [column_name()], + names_from :: column_name(), + values_from :: [column_name()], + names_prefix :: String.t() + ) :: df + @callback pivot_longer( + df, + out_df :: df(), + columns_to_pivot :: [column_name()], + columns_to_keep :: [column_name()], + names_to :: column_name(), + values_to :: column_name() + ) :: df + @callback transpose( + df, + out_df :: df(), + keep_names_as :: column_name(), + new_column_names :: [column_name()] + ) :: df + @callback put(df, out_df :: df(), column_name(), series()) :: df + @callback nil_count(df) :: df() + @callback explode(df, out_df :: df(), columns :: [column_name()]) :: df() + @callback unnest(df, out_df :: df(), columns :: [column_name()]) :: df() + @callback correlation(df, out_df :: df(), ddof :: integer(), method :: atom()) :: df() + @callback covariance(df, out_df :: df(), ddof :: integer()) :: df() + + # Two or more table verbs + + @callback join( + [df()], + out_df :: df(), + on :: list({column_name(), column_name()}), + how :: :left | :inner | :outer | :right | :cross + ) :: df + + @callback concat_columns([df], out_df :: df()) :: df + @callback concat_rows([df], out_df :: df()) :: df + + # Groups + + @callback summarise_with(df, out_df :: df(), aggregations :: [{column_name(), lazy_series()}]) :: + df + + # SQL + + @callback sql(df, sql_string :: binary(), table_name :: binary()) :: df() + + # Functions + alias Explorer.{DataFrame, Series} + + @doc """ + Creates a new DataFrame for a given backend. + """ + def new(data, names, dtypes) when is_list(dtypes) do + dtypes = Map.new(Enum.zip(names, dtypes)) + + new(data, names, dtypes) + end + + def new(data, names, dtypes) when is_list(names) and is_map(dtypes) do + %DataFrame{data: data, names: names, dtypes: dtypes, groups: []} + end + + @default_limit 5 + alias Inspect.Algebra, as: A + + @doc """ + Default inspect implementation for backends. + """ + def inspect(df, backend, n_rows, inspect_opts, opts \\ []) + when is_binary(backend) and (is_integer(n_rows) or is_nil(n_rows)) and + is_list(opts) do + inspect_opts = %{inspect_opts | limit: @default_limit} + elide_columns? = Keyword.get(opts, :elide_columns, false) + open = A.color("[", :list, inspect_opts) + close = A.color("]", :list, inspect_opts) + + cols_algebra = build_cols_algebra(df, inspect_opts, elide_columns?) + df_info = "#{n_rows || "???"} x #{length(cols_algebra)}" + + A.concat([ + A.color(backend, :atom, inspect_opts), + open, + df_info, + close, + groups_algebra(df.groups, inspect_opts) | cols_algebra + ]) + end + + defp build_cols_algebra(df, inspect_opts, true) do + for name <- DataFrame.names(df) do + type = + df + |> DataFrame.dtypes() + |> Map.get(name) + |> Explorer.Shared.dtype_to_string() + + A.concat([ + A.line(), + A.color("#{name} ", :map, inspect_opts), + A.color("#{type} ", :atom, inspect_opts), + "???" + ]) + end + end + + defp build_cols_algebra(df, inspect_opts, false) do + for name <- DataFrame.names(df) do + series = df[name] + + series = + case inspect_opts.limit do + :infinity -> series + limit when is_integer(limit) -> Series.slice(series, 0, limit + 1) + end + + data = + series + |> Series.to_list() + |> Explorer.Shared.to_doc(inspect_opts) + + type = + series + |> Series.dtype() + |> Explorer.Shared.dtype_to_string() + + A.concat([ + A.line(), + A.color("#{name} ", :map, inspect_opts), + A.color("#{type} ", :atom, inspect_opts), + data + ]) + end + end + + defp groups_algebra([_ | _] = groups, opts), + do: + A.concat([ + A.line(), + A.color("Groups: ", :atom, opts), + A.to_doc(groups, opts) + ]) + + defp groups_algebra([], _), do: "" +end diff --git a/deps/explorer/lib/explorer/backend/lazy_series.ex b/deps/explorer/lib/explorer/backend/lazy_series.ex new file mode 100644 index 0000000000000000000000000000000000000000..764d0251bf6208e87e754132224007bb8f1ca8ac --- /dev/null +++ b/deps/explorer/lib/explorer/backend/lazy_series.ex @@ -0,0 +1,1267 @@ +defmodule Explorer.Backend.LazySeries do + @moduledoc """ + This is an opaque implementation of a Series. + + It represents an operation with its arguments. + """ + alias Explorer.Series + alias Explorer.Backend + + @behaviour Explorer.Backend.Series + + defstruct op: nil, args: [], dtype: nil, aggregation: false, backend: nil, resource: nil + + @type t :: %__MODULE__{ + op: atom(), + args: list(), + dtype: any(), + aggregation: boolean(), + backend: nil | module(), + resource: nil + } + + @operations [ + # Element-wise + all_equal: 2, + equal: 2, + not_equal: 2, + greater: 2, + greater_equal: 2, + less: 2, + less_equal: 2, + is_nil: 1, + is_not_nil: 1, + is_finite: 1, + is_infinite: 1, + is_nan: 1, + binary_and: 2, + binary_or: 2, + binary_in: 2, + add: 2, + subtract: 2, + multiply: 2, + divide: 2, + quotient: 2, + remainder: 2, + pow: 2, + log: 1, + log: 2, + exp: 1, + fill_missing_with_value: 2, + fill_missing_with_strategy: 2, + format: 1, + concat: 1, + coalesce: 2, + cast: 2, + select: 3, + abs: 1, + strptime: 2, + strftime: 2, + clip_float: 3, + clip_integer: 3, + + # Trigonometric functions + acos: 1, + asin: 1, + atan: 1, + cos: 1, + sin: 1, + tan: 1, + + # Window functions + cumulative_max: 2, + cumulative_min: 2, + cumulative_sum: 2, + cumulative_product: 2, + window_max: 5, + window_mean: 5, + window_median: 5, + window_min: 5, + window_sum: 5, + window_standard_deviation: 5, + ewm_mean: 5, + ewm_standard_deviation: 6, + ewm_variance: 6, + # Transformation + column: 1, + reverse: 1, + argsort: 5, + sort: 5, + distinct: 1, + unordered_distinct: 1, + slice: 2, + slice: 3, + sample_n: 5, + sample_frac: 5, + head: 2, + tail: 2, + shift: 3, + peaks: 2, + unary_not: 1, + # Aggregations + sum: 1, + min: 1, + max: 1, + argmin: 1, + argmax: 1, + mean: 1, + median: 1, + mode: 1, + n_distinct: 1, + variance: 2, + standard_deviation: 2, + quantile: 2, + rank: 4, + product: 1, + first: 1, + last: 1, + count: 1, + nil_count: 1, + size: 1, + skew: 2, + correlation: 4, + covariance: 3, + all: 1, + any: 1, + row_index: 1, + # Strings + contains: 2, + re_contains: 2, + replace: 3, + re_replace: 3, + lstrip: 2, + rstrip: 2, + strip: 2, + upcase: 1, + downcase: 1, + substring: 3, + split: 2, + split_into: 3, + json_decode: 2, + json_path_match: 2, + count_matches: 2, + re_count_matches: 2, + re_scan: 2, + re_named_captures: 2, + # Float round + round: 2, + floor: 1, + ceil: 1, + # Date functions + day_of_week: 1, + day_of_year: 1, + week_of_year: 1, + month: 1, + year: 1, + hour: 1, + minute: 1, + second: 1, + # List functions + join: 2, + lengths: 1, + member: 3, + # Struct functions + field: 2 + ] + + @comparison_operations [:equal, :not_equal, :greater, :greater_equal, :less, :less_equal] + + @basic_arithmetic_operations [:add, :subtract, :multiply, :divide, :pow] + @other_arithmetic_operations [:quotient, :remainder] + + @aggregation_operations [ + :sum, + :min, + :max, + :argmin, + :argmax, + :mean, + :median, + :mode, + :count, + :product, + :nil_count, + :size, + :first, + :last, + :n_distinct + ] + + @window_fun_operations [ + :window_max, + :window_mean, + :window_median, + :window_min, + :window_sum + ] + @cumulative_operations [ + :cumulative_max, + :cumulative_min, + :cumulative_sum, + :cumulative_product + ] + + @float_predicates [:is_finite, :is_infinite, :is_nan] + + # Used only internally to build new series as we go. + defp new(op, args, dtype, aggregation \\ false) do + dtype = Explorer.Shared.normalise_dtype!(dtype) + + {backend, resource} = + Enum.find_value(args, {nil, nil}, fn + %__MODULE__{backend: backend, resource: resource} when backend != nil -> + {backend, resource} + + _other -> + nil + end) + + %__MODULE__{ + op: op, + args: args, + dtype: dtype, + backend: backend, + resource: resource, + aggregation: aggregation + } + end + + @doc false + # This is called from places where we want to start a new lazy series + # and it has a backend that owns it. + def backed(op, args, dtype, resource, backend) do + dtype = Explorer.Shared.normalise_dtype!(dtype) + %__MODULE__{op: op, args: args, dtype: dtype, backend: backend, resource: resource} + end + + @doc false + # This is called from places where we want to start a new lazy series + # and it has no backend that owns it. + def unbacked(op, args, dtype) do + dtype = Explorer.Shared.normalise_dtype!(dtype) + %__MODULE__{op: op, args: args, dtype: dtype} + end + + @doc false + def operations, do: @operations + + @impl true + # When performing lazy operations, we should only have a single + # LazySeries with a resource, it is not possible to operate on + # different lazy series from different nodes, and + # Explorer.Shared.apply_series was written such that a LazySeries + # always wins. This means LazySeries can have references, but + # operations will always run on the node with the LazySeries, + # so they never have to be imported/exported. + def owner_reference(s), do: s.data.resource + + @impl true + def cast(%Series{} = s, dtype) do + args = [lazy_series!(s), dtype] + data = new(:cast, args, dtype, aggregations?(args)) + Backend.Series.new(data, dtype) + end + + @impl true + def from_list(list, dtype) when is_list(list) do + data = new(:from_list, [list, dtype], dtype, false) + + Backend.Series.new(data, dtype) + end + + @impl true + def from_binary(binary, dtype) when is_binary(binary) do + data = new(:from_binary, [binary, dtype], dtype, false) + Backend.Series.new(data, dtype) + end + + @impl true + def reverse(%Series{} = s) do + args = [lazy_series!(s)] + data = new(:reverse, args, s.dtype, aggregations?(args)) + + Backend.Series.new(data, s.dtype) + end + + @impl true + def argsort(%Series{} = s, descending?, maintain_order?, multithreaded?, nulls_last?) do + args = [lazy_series!(s), descending?, maintain_order?, multithreaded?, nulls_last?] + data = new(:argsort, args, {:u, 32}, aggregations?(args)) + + Backend.Series.new(data, {:u, 32}) + end + + @impl true + def sort(%Series{} = s, descending?, maintain_order?, multithreaded?, nulls_last?) do + args = [lazy_series!(s), descending?, maintain_order?, multithreaded?, nulls_last?] + data = new(:sort, args, s.dtype, aggregations?(args)) + + Backend.Series.new(data, s.dtype) + end + + @impl true + def distinct(%Series{} = s) do + args = [lazy_series!(s)] + data = new(:distinct, args, s.dtype, aggregations?(args)) + + Backend.Series.new(data, s.dtype) + end + + @impl true + def unordered_distinct(%Series{} = s) do + args = [lazy_series!(s)] + data = new(:unordered_distinct, args, s.dtype, aggregations?(args)) + + Backend.Series.new(data, s.dtype) + end + + @impl true + def slice(%Series{} = s, offset, length) do + args = [lazy_series!(s), offset, length] + data = new(:slice, args, s.dtype, aggregations?(args)) + + Backend.Series.new(data, s.dtype) + end + + @impl true + def slice(%Series{} = s, indices) when is_list(indices) do + args = [lazy_series!(s), indices] + data = new(:slice, args, s.dtype, aggregations?(args)) + + Backend.Series.new(data, s.dtype) + end + + @impl true + def slice(%Series{} = s, %Series{} = indices) do + args = [lazy_series!(s), series_or_lazy_series!(indices)] + data = new(:slice, args, s.dtype, aggregations?(args)) + + Backend.Series.new(data, s.dtype) + end + + @impl true + def head(%Series{} = s, length) do + args = [lazy_series!(s), length] + data = new(:head, args, s.dtype, aggregations?(args)) + + Backend.Series.new(data, s.dtype) + end + + @impl true + def tail(%Series{} = s, length) do + args = [lazy_series!(s), length] + data = new(:tail, args, s.dtype, aggregations?(args)) + + Backend.Series.new(data, s.dtype) + end + + @impl true + def shift(%Series{} = s, offset, default) do + args = [lazy_series!(s), offset, default] + data = new(:shift, args, s.dtype, aggregations?(args)) + + Backend.Series.new(data, s.dtype) + end + + @impl true + def peaks(%Series{} = s, min_or_max) when is_atom(min_or_max) do + args = [lazy_series!(s), Atom.to_string(min_or_max)] + data = new(:peaks, args, :boolean, aggregations?(args)) + + Backend.Series.new(data, :boolean) + end + + @impl true + def fill_missing_with_strategy(%Series{} = s, strategy) do + args = [lazy_series!(s), strategy] + dtype = if strategy == :mean, do: {:f, 64}, else: s.dtype + data = new(:fill_missing_with_strategy, args, dtype, aggregations?(args)) + Backend.Series.new(data, dtype) + end + + @impl true + def fill_missing_with_value(%Series{} = s, value) do + args = [lazy_series!(s), value] + data = new(:fill_missing_with_value, args, s.dtype, aggregations?(args)) + + Backend.Series.new(data, s.dtype) + end + + @impl true + def sample(%Series{} = s, n, replacement, shuffle, seed) when is_integer(n) do + args = [lazy_series!(s), n, replacement, shuffle, seed] + data = new(:sample_n, args, s.dtype, aggregations?(args)) + + Backend.Series.new(data, s.dtype) + end + + @impl true + def sample(%Series{} = s, frac, replacement, shuffle, seed) when is_float(frac) do + args = [lazy_series!(s), frac, replacement, shuffle, seed] + data = new(:sample_frac, args, s.dtype, aggregations?(args)) + + Backend.Series.new(data, s.dtype) + end + + # Implements all the comparison operations that + # accepts Series or number on both sides. + # + # It also handles the case for binaries and strings, creating + # a one element series when binaries are present on either sides. + for op <- @comparison_operations do + @impl true + def unquote(op)(left, right) do + args = binary_args(left, right) + data = new(unquote(op), args, :boolean, aggregations?(args)) + + Backend.Series.new(data, :boolean) + end + end + + defp binary_args(left, right) do + case {left, right} do + {%Series{}, %Series{}} -> + [data!(left), data!(right)] + + {%Series{dtype: dtype}, value} + when dtype in [:binary, :string, :category] and is_binary(value) -> + [data!(left), from_list([value], dtype).data] + + {value, %Series{dtype: dtype}} + when dtype in [:binary, :string, :category] and is_binary(value) -> + [from_list([value], dtype).data, data!(right)] + + {%Series{}, other} -> + [data!(left), other] + + {other, %Series{}} -> + [other, data!(right)] + end + end + + # These are also comparison operations, but they only accept `Series`. + for op <- [:binary_and, :binary_or, :binary_in] do + @impl true + def unquote(op)(%Series{} = left, %Series{} = right) do + args = [series_or_lazy_series!(left), series_or_lazy_series!(right)] + data = new(unquote(op), args, :boolean, aggregations?(args)) + + Backend.Series.new(data, :boolean) + end + end + + for op <- @basic_arithmetic_operations do + @impl true + def unquote(op)(dtype, %Series{} = left, %Series{} = right) do + args = [data!(left), data!(right)] + data = new(unquote(op), args, dtype, aggregations?(args)) + + Backend.Series.new(data, dtype) + end + end + + for op <- @other_arithmetic_operations do + @impl true + def unquote(op)(left, right) do + dtype = resolve_numeric_dtype([left, right]) + + args = [data!(left), data!(right)] + data = new(unquote(op), args, dtype, aggregations?(args)) + + Backend.Series.new(data, dtype) + end + end + + for op <- @aggregation_operations do + @impl true + def unquote(op)(%Series{} = series) do + args = [lazy_series!(series)] + dtype = dtype_for_agg_operation(unquote(op), series) + data = new(unquote(op), args, dtype, true) + + Backend.Series.new(data, dtype) + end + end + + for op <- @window_fun_operations do + @impl true + def unquote(op)(%Series{} = series, window_size, weights, min_periods, center) do + args = [lazy_series!(series), window_size, weights, min_periods, center] + + if aggregations?(args), do: raise_agg_inside_window(unquote(op)) + + dtype = resolve_numeric_dtype(unquote(op), [series | List.wrap(weights)]) + + data = new(unquote(op), args, dtype, false) + + Backend.Series.new(data, dtype) + end + end + + @impl true + def window_standard_deviation(%Series{} = series, window_size, weights, min_periods, center) do + args = [lazy_series!(series), window_size, weights, min_periods, center] + + if aggregations?(args), do: raise_agg_inside_window(:window_standard_deviation) + + data = new(:window_standard_deviation, args, {:f, 64}, false) + + Backend.Series.new(data, {:f, 64}) + end + + for op <- @cumulative_operations do + @impl true + def unquote(op)(%Series{} = series, reverse) do + args = [lazy_series!(series), reverse] + + if aggregations?(args), do: raise_agg_inside_window(unquote(op)) + + data = new(unquote(op), args, series.dtype, false) + + Backend.Series.new(data, series.dtype) + end + end + + for predicate <- @float_predicates do + @impl true + def unquote(predicate)(%Series{} = series) do + data = new(unquote(predicate), [lazy_series!(series)], :boolean) + + Backend.Series.new(data, :boolean) + end + end + + defp raise_agg_inside_window(op) do + raise "it's not possible to have an aggregation operation inside #{inspect(op)}, " <> + "which is a window function" + end + + @impl true + def quantile(%Series{} = series, float) when is_float(float) do + args = [lazy_series!(series), float] + # According to https://github.com/pola-rs/polars/issues/4796, + # it's expected that quantile returns float for integer columns. + dtype = + if series.dtype in Explorer.Shared.integer_types() do + {:f, 64} + else + series.dtype + end + + data = new(:quantile, args, dtype, true) + + Backend.Series.new(data, dtype) + end + + @impl true + def rank(%Series{} = series, method, descending, seed) do + args = [series_or_lazy_series!(series), method, descending, seed] + + target_dtype = + if method == :ordinal do + {:u, 32} + else + series.dtype + end + + data = new(:rank, args, target_dtype, true) + + Backend.Series.new(data, target_dtype) + end + + @impl true + def skew(%Series{} = series, bias) do + args = [series_or_lazy_series!(series), bias] + data = new(:skew, args, {:f, 64}, true) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def correlation(%Series{} = left, %Series{} = right, ddof, method) do + args = [series_or_lazy_series!(left), series_or_lazy_series!(right), ddof, method] + data = new(:correlation, args, {:f, 64}, true) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def covariance(%Series{} = left, %Series{} = right, ddof \\ 1) do + args = [series_or_lazy_series!(left), series_or_lazy_series!(right), ddof] + data = new(:covariance, args, {:f, 64}, true) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def variance(%Series{} = s, ddof \\ 1) do + args = [series_or_lazy_series!(s), ddof] + data = new(:variance, args, {:f, 64}, true) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def standard_deviation(%Series{} = s, ddof \\ 1) do + args = [series_or_lazy_series!(s), ddof] + data = new(:standard_deviation, args, {:f, 64}, true) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def all?(%Series{} = s) do + args = [series_or_lazy_series!(s)] + + data = new(:all, args, :boolean, true) + + Backend.Series.new(data, :boolean) + end + + @impl true + def any?(%Series{} = s) do + args = [series_or_lazy_series!(s)] + + data = new(:any, args, :boolean, true) + + Backend.Series.new(data, :boolean) + end + + @impl true + def coalesce(%Series{} = left, %Series{} = right) do + args = [series_or_lazy_series!(left), series_or_lazy_series!(right)] + + dtype = + if left.dtype in Explorer.Shared.numeric_types() do + resolve_numeric_dtype([left, right]) + else + left.dtype + end + + data = new(:coalesce, args, dtype, aggregations?(args)) + + Backend.Series.new(data, dtype) + end + + @impl true + def select(%Series{} = predicate, %{dtype: dtype} = on_true, on_false) do + args = [series_or_lazy_series!(predicate) | binary_args(on_true, on_false)] + + dtype = + if dtype in Explorer.Shared.numeric_types() do + resolve_numeric_dtype([on_true, on_false]) + else + dtype + end + + data = new(:select, args, dtype, aggregations?(args)) + + Backend.Series.new(data, dtype) + end + + @impl true + def format(list) do + series_list = + Enum.map(list, fn + s when is_binary(s) -> s + s -> series_or_lazy_series!(s) + end) + + data = new(:format, [series_list], :string, aggregations?(series_list)) + + Backend.Series.new(data, :string) + end + + @impl true + def concat([%Series{} = head | _tail] = series) do + series_list = Enum.map(series, &series_or_lazy_series!/1) + data = new(:concat, [series_list], head.dtype, aggregations?(series_list)) + + Backend.Series.new(data, head.dtype) + end + + @impl true + def day_of_week(%Series{} = s) do + data = new(:day_of_week, [lazy_series!(s)], {:s, 8}) + + Backend.Series.new(data, {:s, 8}) + end + + @impl true + def day_of_year(%Series{} = s) do + data = new(:day_of_year, [lazy_series!(s)], {:s, 16}) + + Backend.Series.new(data, {:s, 16}) + end + + @impl true + def week_of_year(%Series{} = s) do + data = new(:week_of_year, [lazy_series!(s)], {:s, 8}) + + Backend.Series.new(data, {:s, 8}) + end + + @impl true + def month(%Series{} = s) do + data = new(:month, [lazy_series!(s)], {:s, 8}) + + Backend.Series.new(data, {:s, 8}) + end + + @impl true + def year(%Series{} = s) do + data = new(:year, [lazy_series!(s)], {:s, 32}) + + Backend.Series.new(data, {:s, 32}) + end + + @impl true + def hour(%Series{} = s) do + data = new(:hour, [lazy_series!(s)], {:s, 8}) + + Backend.Series.new(data, {:s, 8}) + end + + @impl true + def minute(%Series{} = s) do + data = new(:minute, [lazy_series!(s)], {:s, 8}) + + Backend.Series.new(data, {:s, 8}) + end + + @impl true + def second(%Series{} = s) do + data = new(:second, [lazy_series!(s)], {:s, 8}) + + Backend.Series.new(data, {:s, 8}) + end + + @impl true + def ewm_mean(%Series{} = series, alpha, adjust, min_periods, ignore_nils) do + args = [lazy_series!(series), alpha, adjust, min_periods, ignore_nils] + + if aggregations?(args), do: raise_agg_inside_window(:ewm_mean) + + data = new(:ewm_mean, args, {:f, 64}, false) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def ewm_standard_deviation(%Series{} = series, alpha, adjust, bias, min_periods, ignore_nils) do + args = [lazy_series!(series), alpha, adjust, bias, min_periods, ignore_nils] + + if aggregations?(args), do: raise_agg_inside_window(:ewm_standard_deviation) + + data = new(:ewm_standard_deviation, args, {:f, 64}, false) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def ewm_variance(%Series{} = series, alpha, adjust, bias, min_periods, ignore_nils) do + args = [lazy_series!(series), alpha, adjust, bias, min_periods, ignore_nils] + + if aggregations?(args), do: raise_agg_inside_window(:ewm_variance) + + data = new(:ewm_variance, args, {:f, 64}, false) + + Backend.Series.new(data, {:f, 64}) + end + + defp dtype_for_agg_operation(op, _) + when op in [:count, :nil_count, :size, :n_distinct, :argmin, :argmax], + do: {:u, 32} + + defp dtype_for_agg_operation(op, series) + when op in [:first, :last, :sum, :min, :max, :product], + do: series.dtype + + defp dtype_for_agg_operation(op, _) when op in [:all?, :any?], do: :boolean + defp dtype_for_agg_operation(:mode, series), do: {:list, series.dtype} + + defp dtype_for_agg_operation(_, _), do: {:f, 64} + + defp resolve_numeric_dtype(items) do + dtypes = + for item <- items, uniq: true do + case item do + %Series{dtype: dtype} -> dtype + other -> Explorer.Shared.dtype_from_list!([other]) + end + end + + case dtypes do + [dtype] -> + if dtype in Explorer.Shared.numeric_types() do + dtype + else + raise "invalid dtype for numeric items: #{inspect(dtype)}" + end + + [_, _] -> + {:f, 64} + end + end + + defp resolve_numeric_dtype(:window_mean, _items), do: {:f, 64} + defp resolve_numeric_dtype(_op, items), do: resolve_numeric_dtype(items) + + # Returns the inner `data` if it's a lazy series. Otherwise raises an error. + defp lazy_series!(series) do + case series do + %Series{data: %__MODULE__{} = data} -> + data + + %Series{} -> + raise ArgumentError, "expecting a LazySeries, but instead got #{inspect(series)}" + end + end + + defp series_or_lazy_series!(%Series{} = series), do: data!(series) + + defp data!(%Series{data: %__MODULE__{} = data}), do: data + defp data!(value), do: value + + defp aggregations?(args) do + Enum.any?(args, fn + %__MODULE__{aggregation: is_agg} -> is_agg + _other -> false + end) + end + + @impl true + def is_nil(%Series{} = series) do + data = new(:is_nil, [lazy_series!(series)], :boolean) + + Backend.Series.new(data, :boolean) + end + + @impl true + def is_not_nil(%Series{} = series) do + data = new(:is_not_nil, [lazy_series!(series)], :boolean) + + Backend.Series.new(data, :boolean) + end + + @impl true + def all_equal(%Series{} = left, %Series{} = right) do + args = [lazy_series!(left), lazy_series!(right)] + data = new(:all_equal, args, :boolean, aggregations?(args)) + + Backend.Series.new(data, :boolean) + end + + @impl true + def unary_not(%Series{} = series) do + data = new(:unary_not, [lazy_series!(series)], :boolean) + + Backend.Series.new(data, :boolean) + end + + @impl true + def log(%Series{} = series) do + data = new(:log, [lazy_series!(series)], {:f, 64}) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def log(%Series{} = series, base) do + data = new(:log, [lazy_series!(series), base], {:f, 64}) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def exp(%Series{} = series) do + data = new(:exp, [lazy_series!(series)], {:f, 64}) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def abs(%Series{} = series) do + data = new(:abs, [lazy_series!(series)], series.dtype) + + Backend.Series.new(data, series.dtype) + end + + @impl true + def strptime(%Series{} = series, format_string) do + dtype = {:naive_datetime, :microsecond} + data = new(:strptime, [lazy_series!(series), format_string], dtype) + + Backend.Series.new(data, dtype) + end + + @impl true + def strftime(%Series{} = series, format_string) do + dtype = :string + data = new(:strftime, [lazy_series!(series), format_string], dtype) + + Backend.Series.new(data, dtype) + end + + @impl true + def clip(%Series{dtype: {s_or_u, _} = dtype} = series, min, max) + when s_or_u in [:s, :u] and is_integer(min) and is_integer(max) do + data = new(:clip_integer, [lazy_series!(series), min, max], dtype) + + Backend.Series.new(data, dtype) + end + + def clip(%Series{} = series, min, max) do + data = new(:clip_float, [lazy_series!(series), min * 1.0, max * 1.0], {:f, 64}) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def sin(%Series{} = series) do + data = new(:sin, [lazy_series!(series)], {:f, 64}) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def cos(%Series{} = series) do + data = new(:cos, [lazy_series!(series)], {:f, 64}) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def tan(%Series{} = series) do + data = new(:tan, [lazy_series!(series)], {:f, 64}) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def asin(%Series{} = series) do + data = new(:asin, [lazy_series!(series)], {:f, 64}) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def acos(%Series{} = series) do + data = new(:acos, [lazy_series!(series)], {:f, 64}) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def atan(%Series{} = series) do + data = new(:atan, [lazy_series!(series)], {:f, 64}) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def inspect(series, opts) do + alias Inspect.Algebra, as: A + + open = A.color("(", :list, opts) + close = A.color(")", :list, opts) + + dtype = + series + |> Series.dtype() + |> Explorer.Shared.dtype_to_string() + |> A.color(:atom, opts) + + A.concat([ + A.color("LazySeries[???]", :atom, opts), + A.line(), + dtype, + " ", + open, + Code.quoted_to_algebra(to_elixir_ast(series.data)), + close + ]) + end + + @to_elixir_op %{ + add: :+, + subtract: :-, + multiply: :*, + divide: :/, + pow: :**, + equal: :==, + not_equal: :!=, + greater: :>, + greater_equal: :>=, + less: :<, + less_equal: :<=, + binary_and: :and, + binary_or: :or, + binary_in: :in, + unary_not: :not + } + + defp to_elixir_ast(%__MODULE__{op: :from_list, args: [[single], _]}) do + single + end + + defp to_elixir_ast(%__MODULE__{op: op, args: args}) do + {Map.get(@to_elixir_op, op, op), [], Enum.map(args, &to_elixir_ast/1)} + end + + defp to_elixir_ast(%Series{} = series) do + case Explorer.Series.size(series) do + 1 -> series[0] + _ -> series + end + end + + defp to_elixir_ast(other), do: other + + @impl true + def size(series) do + data = new(:size, [lazy_series!(series)], {:u, 32}) + + Backend.Series.new(data, {:u, 32}) + end + + @impl true + def transform(_series, _fun) do + raise """ + #{unsupported(:transform, 2)} + + If you want to transform a column, you must do so outside of a query. + For example, instead of: + + Explorer.DataFrame.mutate(df, new_column: transform(column, &String.upcase/1)) + + You must write: + + Explorer.DataFrame.put(df, :new_column, Explorer.Series.transform(column, &String.upcase/1)) + + However, keep in mind that in such cases you are loading the data into Elixir and + serializing it back, which may be expensive for large datasets + """ + end + + @impl true + def contains(series, substring) do + data = new(:contains, [lazy_series!(series), substring], :boolean) + + Backend.Series.new(data, :boolean) + end + + @impl true + def re_contains(series, pattern) do + data = new(:re_contains, [lazy_series!(series), pattern], :boolean) + + Backend.Series.new(data, :boolean) + end + + @impl true + def upcase(series) do + data = new(:upcase, [lazy_series!(series)], :string) + + Backend.Series.new(data, :string) + end + + @impl true + def downcase(series) do + data = new(:downcase, [lazy_series!(series)], :string) + + Backend.Series.new(data, :string) + end + + @impl true + def replace(series, substring, replacement) do + data = new(:replace, [lazy_series!(series), substring, replacement], :string) + + Backend.Series.new(data, :string) + end + + @impl true + def re_replace(series, pattern, replacement) do + data = new(:re_replace, [lazy_series!(series), pattern, replacement], :string) + + Backend.Series.new(data, :string) + end + + @impl true + def strip(series, string) do + data = new(:strip, [lazy_series!(series), string], :string) + Backend.Series.new(data, :string) + end + + @impl true + def lstrip(series, string) do + data = new(:lstrip, [lazy_series!(series), string], :string) + + Backend.Series.new(data, :string) + end + + @impl true + def rstrip(series, string) do + data = new(:rstrip, [lazy_series!(series), string], :string) + + Backend.Series.new(data, :string) + end + + @impl true + def substring(series, offset, length) do + data = new(:substring, [lazy_series!(series), offset, length], :string) + + Backend.Series.new(data, :string) + end + + @impl true + def split(series, by) do + data = new(:split, [lazy_series!(series), by], :string) + + Backend.Series.new(data, {:list, :string}) + end + + @impl true + def split_into(series, by, fields) do + data = new(:split_into, [lazy_series!(series), by, fields], :string) + + Backend.Series.new(data, {:struct, Enum.map(fields, &{&1, :string})}) + end + + @impl true + def round(series, decimals) when is_integer(decimals) and decimals >= 0 do + args = [lazy_series!(series), decimals] + data = new(:round, args, {:f, 64}, aggregations?(args)) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def floor(series) do + args = [lazy_series!(series)] + data = new(:floor, args, {:f, 64}, aggregations?(args)) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def ceil(series) do + args = [lazy_series!(series)] + data = new(:ceil, args, {:f, 64}, aggregations?(args)) + + Backend.Series.new(data, {:f, 64}) + end + + @impl true + def join(series, separator) do + data = new(:join, [lazy_series!(series), separator], {:list, :string}) + + Backend.Series.new(data, :string) + end + + @impl true + def lengths(series) do + data = new(:lengths, [lazy_series!(series)], {:u, 32}) + + Backend.Series.new(data, {:u, 32}) + end + + @impl true + def member?(%Series{dtype: {:list, inner_dtype}} = series, value) do + data = new(:member, [lazy_series!(series), value, inner_dtype], :boolean) + + Backend.Series.new(data, :boolean) + end + + @impl true + def field(%Series{dtype: {:struct, inner_dtype}} = series, name) do + {^name, dtype} = List.keyfind!(inner_dtype, name, 0) + data = new(:field, [lazy_series!(series), name], dtype) + + Backend.Series.new(data, dtype) + end + + @impl true + def json_decode(series, dtype) do + data = new(:json_decode, [lazy_series!(series), dtype], dtype) + + Backend.Series.new(data, dtype) + end + + @impl true + def json_path_match(series, json_path) do + data = new(:json_path_match, [lazy_series!(series), json_path], :string) + + Backend.Series.new(data, :string) + end + + @impl true + def row_index(series) do + data = new(:row_index, [lazy_series!(series)], {:u, 32}) + + Backend.Series.new(data, {:u, 32}) + end + + @impl true + def count_matches(series, substring) do + data = new(:count_matches, [lazy_series!(series), substring], {:u, 32}) + + Backend.Series.new(data, {:u, 32}) + end + + @impl true + def re_count_matches(series, pattern) do + data = new(:re_count_matches, [lazy_series!(series), pattern], {:u, 32}) + + Backend.Series.new(data, {:u, 32}) + end + + @impl true + def re_scan(series, pattern) do + data = new(:re_scan, [lazy_series!(series), pattern], {:list, :string}) + + Backend.Series.new(data, {:list, :string}) + end + + @impl true + def re_named_captures(series, pattern) do + lazy_s = lazy_series!(series) + + backend = get_backend(lazy_s, "re_named_captures/2") + target_dtype = backend.re_dtype(pattern) + + data = new(:re_named_captures, [lazy_s, pattern], target_dtype) + + Backend.Series.new(data, target_dtype) + end + + defp get_backend(%__MODULE__{} = lazy_series, function) do + lazy_series.backend || + raise "cannot get backend from Explorer.Backend.LazySeries for `#{function}`" + end + + @remaining_non_lazy_operations [ + at: 2, + at_every: 2, + categories: 1, + categorise: 2, + cut: 7, + frequencies: 1, + qcut: 8, + mask: 2, + owner_import: 1, + owner_export: 1, + to_iovec: 1, + to_list: 1 + ] + + for {fun, arity} <- @remaining_non_lazy_operations do + args = Macro.generate_arguments(arity, __MODULE__) + @impl true + def unquote(fun)(unquote_splicing(args)), do: raise(unsupported(unquote(fun), unquote(arity))) + end + + defp unsupported(fun, arity) do + "cannot perform #{fun}/#{arity} operation on Explorer.Backend.LazySeries. " <> + "Query operations work on lazy series and those support only a subset of series operations" + end +end diff --git a/deps/explorer/lib/explorer/backend/query_frame.ex b/deps/explorer/lib/explorer/backend/query_frame.ex new file mode 100644 index 0000000000000000000000000000000000000000..5c3dc0217270425d8e2d9ebccfe6be16e78bf4a7 --- /dev/null +++ b/deps/explorer/lib/explorer/backend/query_frame.ex @@ -0,0 +1,118 @@ +defmodule Explorer.Backend.QueryFrame do + @moduledoc """ + Represents a lazy dataframe for building query expressions. + + You may call `Explorer.Query.new` to create a query-backed dataframe. + The QueryFrame is available inside `filter_with`, `mutate_with`, and + similar. You cannot perform any operation on them except accessing + its underlying series. + """ + + alias Explorer.Backend + alias Explorer.Backend.LazySeries + + defstruct dtypes: %{}, names: [], backend: nil, resource: nil + + @type t :: %__MODULE__{ + backend: module(), + dtypes: Backend.DataFrame.dtypes(), + names: Backend.DataFrame.column_name(), + resource: reference() | nil + } + + @behaviour Backend.DataFrame + + @doc false + def new(df) do + %module{} = df.data + + Explorer.Backend.DataFrame.new( + %__MODULE__{ + names: df.names, + dtypes: df.dtypes, + backend: module, + resource: module.owner_reference(df) + }, + df.names, + df.dtypes + ) + end + + # We don't implement owner reference here because no + # cross node operations happen at the lazy frame level. + # Instead, we store the resource and we delegate them + # to the underlying lazy series. + @impl Backend.DataFrame + def owner_reference(_), do: nil + + @impl Backend.DataFrame + def lazy, do: __MODULE__ + + @impl Backend.DataFrame + def lazy(ldf), do: ldf + + @impl Backend.DataFrame + def inspect(ldf, opts) do + import Inspect.Algebra + + open = color("[", :list, opts) + close = color("]", :list, opts) + + dtypes = ldf.data.dtypes + + cols_algebra = + for name <- ldf.data.names do + concat([ + line(), + color("#{name} ", :map, opts), + color("#{Explorer.Shared.dtype_to_string(dtypes[name])}", :atom, opts) + ]) + end + + concat([ + color("QueryFrame", :atom, opts), + open, + "??? x #{length(cols_algebra)}", + close, + groups_algebra(ldf.groups, opts) | cols_algebra + ]) + end + + defp groups_algebra([_ | _] = groups, opts), + do: + Inspect.Algebra.concat([ + Inspect.Algebra.line(), + Inspect.Algebra.color("Groups: ", :atom, opts), + Inspect.Algebra.to_doc(groups, opts) + ]) + + defp groups_algebra([], _), do: "" + + @impl Backend.DataFrame + def pull(%{data: data, dtypes: dtypes}, column) do + dtype_for_column = dtypes[column] + + data = LazySeries.backed(:column, [column], dtype_for_column, data.resource, data.backend) + + Backend.Series.new(data, dtype_for_column) + end + + funs = + Backend.DataFrame.behaviour_info(:callbacks) -- + (Backend.DataFrame.behaviour_info(:optional_callbacks) ++ + Module.definitions_in(__MODULE__, :def)) + + for {fun, arity} <- funs do + args = Macro.generate_arguments(arity, __MODULE__) + + @impl Backend.DataFrame + def unquote(fun)(unquote_splicing(args)) do + raise """ + cannot perform operation #{unquote(fun)} on Explorer.Backend.QueryFrame. + + The QueryFrame is available inside filter_with, mutate_with, and \ + similar and they support only a limited subset of the Series API + """ + end + end +end diff --git a/deps/explorer/lib/explorer/backend/series.ex b/deps/explorer/lib/explorer/backend/series.ex new file mode 100644 index 0000000000000000000000000000000000000000..ded01966467659c4a8af5ccea5e94214ea40c989 --- /dev/null +++ b/deps/explorer/lib/explorer/backend/series.ex @@ -0,0 +1,398 @@ +defmodule Explorer.Backend.Series do + @moduledoc """ + The behaviour for series backends. + """ + + @type t :: struct() + + @type s :: Explorer.Series.t() + @type lazy_s :: Explorer.Series.lazy_t() + @type df :: Explorer.DataFrame.t() + @type dtype :: Explorer.Series.dtype() + + @type valid_types :: + number() + | boolean() + | String.t() + | Date.t() + | Time.t() + | NaiveDateTime.t() + | Explorer.Duration.t() + | Decimal.t() + + @type non_finite :: Explorer.Series.non_finite() + @type option(type) :: type | nil + @type io_result(t) :: {:ok, t} | {:error, Exception.t()} + + # Conversion + + @callback from_list(list(), dtype()) :: s + @callback from_binary(binary(), dtype()) :: s + @callback to_list(s) :: list() + @callback to_iovec(s) :: [binary()] + @callback cast(s, dtype) :: s + @callback categorise(s, s) :: s + @callback strptime(s, String.t()) :: s + @callback strftime(s, String.t()) :: s + + # Ownership + + @callback owner_reference(s) :: reference() | nil + @callback owner_import(term()) :: io_result(s) + @callback owner_export(s) :: io_result(term()) + + # Introspection + + @callback size(s) :: non_neg_integer() | lazy_s() + @callback inspect(s, opts :: Inspect.Opts.t()) :: Inspect.Algebra.t() + @callback categories(s) :: s + + # Slice and dice + + @callback head(s, n :: integer()) :: s + @callback tail(s, n :: integer()) :: s + @callback sample( + s, + n_or_frac :: number(), + replacement :: boolean(), + shuffle :: boolean(), + seed :: option(integer()) + ) :: s + @callback at(s, idx :: integer()) :: s + @callback at_every(s, integer()) :: s + @callback mask(s, mask :: s) :: s + @callback slice(s, indices :: list() | s()) :: s + @callback slice(s, offset :: integer(), length :: integer()) :: s + @callback format(list(s)) :: s + @callback concat(list(s)) :: s + @callback coalesce(s, s) :: s + @callback first(s) :: valid_types() | lazy_s() + @callback last(s) :: valid_types() | lazy_s() + @callback select(predicate :: s, s, s) :: s + @callback shift(s, offset :: integer, default :: nil) :: s + @callback rank( + s, + method :: atom(), + descending :: boolean(), + seed :: option(integer()) + ) :: s | lazy_s() + # Aggregation + + @callback count(s) :: number() | lazy_s() + @callback sum(s) :: number() | non_finite() | lazy_s() | nil + @callback min(s) :: number() | non_finite() | Date.t() | NaiveDateTime.t() | lazy_s() | nil + @callback max(s) :: number() | non_finite() | Date.t() | NaiveDateTime.t() | lazy_s() | nil + @callback argmin(s) :: number() | non_finite() | lazy_s() | nil + @callback argmax(s) :: number() | non_finite() | lazy_s() | nil + @callback mean(s) :: float() | non_finite() | lazy_s() | nil + @callback median(s) :: float() | non_finite() | lazy_s() | nil + @callback mode(s) :: s | lazy_s() + @callback variance(s, ddof :: non_neg_integer()) :: float() | non_finite() | lazy_s() | nil + @callback standard_deviation(s, ddof :: non_neg_integer()) :: + float() | non_finite() | lazy_s() | nil + @callback quantile(s, float()) :: + number() | non_finite() | Date.t() | NaiveDateTime.t() | lazy_s() | nil + @callback nil_count(s) :: number() | lazy_s() + @callback product(s) :: float() | non_finite() | lazy_s() | nil + @callback skew(s, bias? :: boolean()) :: float() | non_finite() | lazy_s() | nil + @callback correlation(s, s, ddof :: non_neg_integer(), method :: atom()) :: + float() | non_finite() | lazy_s() | nil + @callback covariance(s, s, ddof :: non_neg_integer()) :: float() | non_finite() | lazy_s() | nil + @callback all?(s) :: boolean() | lazy_s() + @callback any?(s) :: boolean() | lazy_s() + @callback row_index(s) :: s | lazy_s() + + # Cumulative + + @callback cumulative_max(s, reverse? :: boolean()) :: s + @callback cumulative_min(s, reverse? :: boolean()) :: s + @callback cumulative_sum(s, reverse? :: boolean()) :: s + @callback cumulative_product(s, reverse? :: boolean()) :: s + + # Local minima/maxima + + @callback peaks(s, :max | :min) :: s + + # Arithmetic + + @callback add(out_dtype :: dtype(), s, s) :: s + @callback subtract(out_dtype :: dtype(), s, s) :: s + @callback multiply(out_dtype :: dtype(), s, s) :: s + @callback divide(out_dtype :: dtype(), s, s) :: s + @callback quotient(s, s) :: s + @callback remainder(s, s) :: s + @callback pow(out_dtype :: dtype(), s, s) :: s + @callback log(argument :: s) :: s + @callback log(argument :: s, base :: float()) :: s + @callback exp(s) :: s + @callback abs(s) :: s + @callback clip(s, number(), number()) :: s + + # Trigonometry + + @callback acos(s) :: s + @callback asin(s) :: s + @callback atan(s) :: s + @callback cos(s) :: s + @callback sin(s) :: s + @callback tan(s) :: s + + # Comparisons + + @callback equal(s, s) :: s + @callback not_equal(s, s) :: s + @callback greater(s, s) :: s + @callback greater_equal(s, s) :: s + @callback less(s, s) :: s + @callback less_equal(s, s) :: s + @callback all_equal(s, s) :: boolean() | lazy_s() + + @callback binary_and(s, s) :: s + @callback binary_or(s, s) :: s + @callback binary_in(s, s) :: s + + # Float predicates + @callback is_finite(s) :: s + @callback is_infinite(s) :: s + @callback is_nan(s) :: s + + # Float round + @callback round(s, decimals :: non_neg_integer()) :: s + @callback floor(s) :: s + @callback ceil(s) :: s + + # Coercion + + # Sort + + @callback sort( + s, + descending? :: boolean(), + maintain_order? :: boolean(), + multithreaded? :: boolean(), + nulls_last? :: boolean() + ) :: s + @callback argsort( + s, + descending? :: boolean(), + maintain_order? :: boolean(), + multithreaded? :: boolean(), + nulls_last? :: boolean() + ) :: s + @callback reverse(s) :: s + + # Distinct + + @callback distinct(s) :: s + @callback unordered_distinct(s) :: s + @callback n_distinct(s) :: integer() | lazy_s() + @callback frequencies(s) :: df + + # Categorisation + + @callback cut( + s, + bins :: [float()], + labels :: option([String.t()]), + break_point_label :: option(String.t()), + category_label :: option(String.t()), + left_close :: boolean(), + include_breaks :: boolean() + ) :: + df + @callback qcut( + s, + quantiles :: [float()], + labels :: option([String.t()]), + break_point_label :: option(String.t()), + category_label :: option(String.t()), + allow_duplicates :: boolean(), + left_close :: boolean(), + include_breaks :: boolean() + ) :: + df + + # Rolling + + @callback window_sum( + s, + window_size :: integer(), + weights :: [float()] | nil, + min_periods :: integer() | nil, + center :: boolean() + ) :: s + @callback window_min( + s, + window_size :: integer(), + weights :: [float()] | nil, + min_periods :: integer() | nil, + center :: boolean() + ) :: s + @callback window_max( + s, + window_size :: integer(), + weights :: [float()] | nil, + min_periods :: integer() | nil, + center :: boolean() + ) :: s + @callback window_mean( + s, + window_size :: integer(), + weights :: [float()] | nil, + min_periods :: integer() | nil, + center :: boolean() + ) :: s + @callback window_median( + s, + window_size :: integer(), + weights :: [float()] | nil, + min_periods :: integer() | nil, + center :: boolean() + ) :: s + @callback window_standard_deviation( + s, + window_size :: integer(), + weights :: [float()] | nil, + min_periods :: integer() | nil, + center :: boolean() + ) :: s + + # Exponentially weighted windows + + @callback ewm_mean( + s, + alpha :: float(), + adjust :: boolean(), + min_periods :: integer(), + ignore_nils :: boolean() + ) :: s + + @callback ewm_standard_deviation( + s, + alpha :: float(), + adjust :: boolean(), + bias :: boolean(), + min_periods :: integer(), + ignore_nils :: boolean() + ) :: s + + @callback ewm_variance( + s, + alpha :: float(), + adjust :: boolean(), + bias :: boolean(), + min_periods :: integer(), + ignore_nils :: boolean() + ) :: s + + # Nulls + + @callback fill_missing_with_strategy(s, :backward | :forward | :min | :max | :mean) :: s + @callback fill_missing_with_value(s, :nan | valid_types()) :: s + @callback is_nil(s) :: s + @callback is_not_nil(s) :: s + + # Escape hatch + + @callback transform(s, fun) :: s + + # Inversions + + @callback unary_not(s) :: s + + # Strings + + @callback contains(s, String.t()) :: s + @callback upcase(s) :: s + @callback downcase(s) :: s + @callback replace(s, String.t(), String.t()) :: s + @callback strip(s, String.t() | nil) :: s + @callback lstrip(s, String.t() | nil) :: s + @callback rstrip(s, String.t() | nil) :: s + @callback substring(s, integer(), non_neg_integer() | nil) :: s + @callback split(s, String.t()) :: s + @callback split_into(s, String.t(), list(String.t() | atom())) :: s + @callback json_decode(s, dtype()) :: s + @callback json_path_match(s, String.t()) :: s + @callback count_matches(s, String.t()) :: s + + ## String - Regular expression versions + @callback re_contains(s, String.t()) :: s + @callback re_replace(s, String.t(), String.t()) :: s + @callback re_count_matches(s, String.t()) :: s + @callback re_scan(s, String.t()) :: s + @callback re_named_captures(s, String.t()) :: s + + # Date / DateTime + + @callback day_of_week(s) :: s + @callback day_of_year(s) :: s + @callback week_of_year(s) :: s + @callback month(s) :: s + @callback year(s) :: s + @callback hour(s) :: s + @callback minute(s) :: s + @callback second(s) :: s + + # List + @callback join(s, String.t()) :: s + @callback lengths(s) :: s + @callback member?(s, valid_types()) :: s + + # Struct + @callback field(s, String.t()) :: s + + # Functions + + @doc """ + Create a new `Series`. + """ + def new(data, dtype) do + dtype = Explorer.Shared.normalise_dtype!(dtype) + + %Explorer.Series{data: data, dtype: dtype} + end + + alias Inspect.Algebra, as: A + alias Explorer.Series + + @doc """ + Default inspect implementation for backends. + """ + def inspect(series, backend, n_rows, inspect_opts, opts \\ []) + when is_binary(backend) and (is_integer(n_rows) or is_nil(n_rows) or is_binary(n_rows)) and + is_list(opts) do + open = A.color("[", :list, inspect_opts) + close = A.color("]", :list, inspect_opts) + + type = + series + |> Series.dtype() + |> Explorer.Shared.dtype_to_string() + + dtype = A.color("#{type} ", :atom, inspect_opts) + data = build_series_data(series, inspect_opts) + + A.concat([ + A.color(backend, :atom, inspect_opts), + open, + "#{n_rows || "???"}", + close, + A.line(), + dtype, + data + ]) + end + + defp build_series_data(series, inspect_opts) do + series = + case inspect_opts.limit do + :infinity -> series + limit when is_integer(limit) -> Series.slice(series, 0, limit + 1) + end + + series + |> Series.to_list() + |> Explorer.Shared.to_doc(inspect_opts) + end +end diff --git a/deps/explorer/lib/explorer/comptime_utils.ex b/deps/explorer/lib/explorer/comptime_utils.ex new file mode 100644 index 0000000000000000000000000000000000000000..e265c0decf5119b6dc0ecd643e2dd94aa2a922db --- /dev/null +++ b/deps/explorer/lib/explorer/comptime_utils.ex @@ -0,0 +1,32 @@ +defmodule Explorer.ComptimeUtils do + @moduledoc false + # This module is useful to control some aspects of compilation. + # It is mostly used in the `Explorer.PolarsBackend.Native` compilation. + + # Only works for Linux targets today, but we don't need more. + @doc false + def cpu_with_all_caps?(needed_flags, opts \\ []) do + opts = Keyword.validate!(opts, cpu_info_file_path: "/proc/cpuinfo", target: nil) + + case File.read(opts[:cpu_info_file_path]) do + {:ok, contents} -> + flags = + contents + |> String.split("\n") + |> Stream.filter(&String.starts_with?(&1, "flags")) + |> Stream.map(fn line -> + [_, flags] = String.split(line, ": ") + String.split(flags) + end) + |> Stream.uniq() + |> Enum.to_list() + |> List.flatten() + + Enum.all?(needed_flags, fn flag -> flag in flags end) + + {:error, _} -> + # There is no way to say, so we default to false. + false + end + end +end diff --git a/deps/explorer/lib/explorer/data_frame.ex b/deps/explorer/lib/explorer/data_frame.ex new file mode 100644 index 0000000000000000000000000000000000000000..df8a5ad366e2f4482052fbaf451e76f8115b0afe --- /dev/null +++ b/deps/explorer/lib/explorer/data_frame.ex @@ -0,0 +1,6404 @@ +defmodule Explorer.DataFrame do + @moduledoc """ + The DataFrame struct and API. + + Dataframes are two-dimensional tabular data structures similar to a spreadsheet. + For example, the Iris dataset: + + iex> Explorer.Datasets.iris() + #Explorer.DataFrame< + Polars[150 x 5] + sepal_length f64 [5.1, 4.9, 4.7, 4.6, 5.0, ...] + sepal_width f64 [3.5, 3.0, 3.2, 3.1, 3.6, ...] + petal_length f64 [1.4, 1.4, 1.3, 1.5, 1.4, ...] + petal_width f64 [0.2, 0.2, 0.2, 0.2, 0.2, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + > + + This dataframe has 150 rows and five columns. Each column is an `Explorer.Series` + of the same size (150): + + iex> df = Explorer.Datasets.iris() + iex> df["sepal_length"] + #Explorer.Series< + Polars[150] + f64 [5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.4, 4.8, 4.8, 4.3, 5.8, 5.7, 5.4, 5.1, 5.7, 5.1, 5.4, 5.1, 4.6, 5.1, 4.8, 5.0, 5.0, 5.2, 5.2, 4.7, 4.8, 5.4, 5.2, 5.5, 4.9, 5.0, 5.5, 4.9, 4.4, 5.1, 5.0, 4.5, 4.4, 5.0, 5.1, 4.8, 5.1, 4.6, 5.3, 5.0, ...] + > + + ## Creating dataframes + + Dataframes can be created from normal Elixir terms. The main way you might do this is + with the `new/1` function. For example: + + iex> Explorer.DataFrame.new(a: ["a", "b"], b: [1, 2]) + #Explorer.DataFrame< + Polars[2 x 2] + a string ["a", "b"] + b s64 [1, 2] + > + + Or with a list of maps: + + iex> Explorer.DataFrame.new([%{"col1" => "a", "col2" => 1}, %{"col1" => "b", "col2" => 2}]) + #Explorer.DataFrame< + Polars[2 x 2] + col1 string ["a", "b"] + col2 s64 [1, 2] + > + + ## Verbs + + Explorer uses the idea of a consistent set of SQL-like `verbs` like + [`dplyr`](https://dplyr.tidyverse.org) which can help solve common + data manipulation challenges. These are split into single table verbs, + multiple table verbs, and row-based verbs: + + ### Single table verbs + + Single table verbs are (unsurprisingly) used for manipulating a single dataframe. + Those operations typically driven by column names. These are: + + - `select/2` for picking columns and `discard/2` to discard them + - `filter/2` for picking rows based on predicates + - `mutate/2` for adding or replacing columns that are functions of existing columns + - `sort_by/2` for changing the ordering of rows + - `distinct/2` for picking unique rows + - `summarise/2` for reducing multiple rows down to a single summary + - `pivot_longer/3` and `pivot_wider/4` for massaging dataframes into longer or + wider forms, respectively + + Each of these combine with `Explorer.DataFrame.group_by/2` for operating by group. + + ### Multiple table verbs + + Multiple table verbs are used for combining tables. These are: + + - `join/3` for performing SQL-like joins + - `concat_columns/1` for horizontally "stacking" dataframes + - `concat_rows/1` for vertically "stacking" dataframes + + ### Row-based verbs + + Those operations are driven by the row index. These are: + + - `head/2` for picking the first rows + - `tail/2` for picking the last rows + - `slice/2` for slicing the dataframe by row indexes or a range + - `slice/3` for slicing a section by an offset + - `sample/2` for sampling the data-frame by row + + ## IO operations + + Explorer supports reading and writing of: + + - delimited files (such as CSV or TSV) + - [Parquet](https://databricks.com/glossary/what-is-parquet) + - [Arrow IPC](https://arrow.apache.org/docs/format/Columnar.html#ipc-file-format) + - [Arrow Streaming IPC](https://arrow.apache.org/docs/format/Columnar.html#ipc-streaming-format) + - [Newline Delimited JSON](https://github.com/ndjson/ndjson-spec) + - Databases via `Adbc` in `from_query/3` + + The convention Explorer uses is to have `from_*` and `to_*` functions to read and write + to files in the formats above. `load_*` and `dump_*` versions are also available to read + and write those formats directly in memory. + + Files can be fetched from local or remote file system, such as S3, using the following formats: + + # path to a file in disk + Explorer.DataFrame.from_parquet("/path/to/file.parquet") + + # path to a URL schema (with optional configuration) + Explorer.DataFrame.from_parquet("s3://bucket/file.parquet", config: FSS.S3.config_from_system_env()) + + # it's possible to configure using keyword lists + Explorer.DataFrame.from_parquet("s3://bucket/file.parquet", config: [access_key_id: "my-key", secret_access_key: "my-secret"]) + + # a FSS entry (it already includes its config) + Explorer.DataFrame.from_parquet(FSS.S3.parse("s3://bucket/file.parquet")) + + The `:config` option of `from_*` functions is only required if the filename is a path + to a remote resource. In case it's a FSS entry, the requirement is that the config is passed + inside the entry struct. + + For more details about the options, see the [FSS docs](https://hexdocs.pm/fss). + + ## Selecting columns and access + + Several functions in this module, such as `select/2`, `discard/2`, `drop_nil/2`, and so + forth accept a single or multiple columns as arguments. The columns can be specified in + a variety of formats, which we describe below. + + `Explorer.DataFrame` also implements the `Access` behaviour (also known as the brackets + syntax). This should be familiar for users coming from other language with dataframes + such as R or Python. For example: + + iex> df = Explorer.Datasets.wine() + iex> df["class"] + #Explorer.Series< + Polars[178] + s64 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...] + > + + Accessing the dataframe with a column name either as a string or an atom, will return + the column. You can also pass an integer representing the column order: + + iex> df = Explorer.Datasets.wine() + iex> df[0] + #Explorer.Series< + Polars[178] + s64 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...] + > + + You can also pass a list, a range, or a regex to return a dataframe matching + the given data type. For example, by passing a list: + + iex> df = Explorer.Datasets.wine() + iex> df[["class", "hue"]] + #Explorer.DataFrame< + Polars[178 x 2] + class s64 [1, 1, 1, 1, 1, ...] + hue f64 [1.04, 1.05, 1.03, 0.86, 1.04, ...] + > + + Or a range for the given positions: + + iex> df = Explorer.Datasets.wine() + iex> df[0..2] + #Explorer.DataFrame< + Polars[178 x 3] + class s64 [1, 1, 1, 1, 1, ...] + alcohol f64 [14.23, 13.2, 13.16, 14.37, 13.24, ...] + malic_acid f64 [1.71, 1.78, 2.36, 1.95, 2.59, ...] + > + + Or a regex to keep only columns matching a given pattern: + + iex> df = Explorer.Datasets.wine() + iex> df[~r/(class|hue)/] + #Explorer.DataFrame< + Polars[178 x 2] + class s64 [1, 1, 1, 1, 1, ...] + hue f64 [1.04, 1.05, 1.03, 0.86, 1.04, ...] + > + + Given you can also access a series using its index, you can use + multiple accesses to select a column and row at the same time: + + iex> df = Explorer.Datasets.wine() + iex> df["class"][3] + 1 + + When trying to access a column in the dataframe that does not exist, an `ArgumentError` is raised. + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3]) + iex> df["b"] + ** (ArgumentError) could not find column name "b". The available columns are: ["a"]. + If you are attempting to interpolate a value, use ^b. + """ + + alias __MODULE__, as: DataFrame + alias Explorer.Series + alias Explorer.Shared + alias Explorer.Backend.LazySeries + + alias FSS.HTTP + alias FSS.Local + alias FSS.S3 + + @enforce_keys [:data, :groups, :names, :dtypes] + defstruct [:data, :groups, :names, :dtypes, :remote] + + @typedoc """ + Represents a column name as atom or string. + """ + @type column_name :: atom() | String.t() + + @typedoc """ + Represents a column name or its index. + """ + @type column :: column_name() | non_neg_integer() + + @typedoc """ + Represents multiple columns. + + The columns may be specified as one of: + + * a list of columns indexes or names as atoms and strings + + * a range + + * a regex that keeps only the names matching the regex + + * a one-arity function that receives column names and returns + true for column names to keep + + * a two-arity function that receives column names and types and + returns true for column names to keep + + """ + @type columns :: + [column] + | Range.t() + | (String.t() -> boolean()) + | (String.t(), Explorer.Series.dtype() -> boolean()) + + @typedoc """ + Represents multiple column names as atoms or strings. + """ + @type column_names :: [column_name] + + @typedoc """ + Represents a column pair where the value is a column name or + a column index, and the value is of type `value`. + """ + @type column_pairs(value) :: [{column(), value}] | %{column() => value} + + @typedoc """ + Represents a filesystem entry, that can be local, S3 or URL. + """ + @type fs_entry :: FSS.entry() + + @typedoc """ + Represents a dataframe. + """ + @type t :: %DataFrame{ + data: Explorer.Backend.DataFrame.t(), + groups: [String.t()], + names: [String.t()], + dtypes: %{String.t() => Explorer.Series.dtype()} + } + + @default_infer_schema_length 1000 + @default_sample_nrows 5 + @integer_types Explorer.Shared.integer_types() + + # Guards and helpers for columns + + defguardp is_column(column) when is_binary(column) or is_atom(column) or is_integer(column) + defguardp is_column_name(column) when is_binary(column) or is_atom(column) + + # TODO: Use is_non_struct_map when we require Elixir v1.18+ + defguardp is_column_pairs(columns) + when is_list(columns) or (is_map(columns) and not is_struct(columns)) + + # Normalize a column name to string + defp to_column_name(column) when is_binary(column), do: column + defp to_column_name(column) when is_atom(column), do: Atom.to_string(column) + + # Normalize pairs of `{column, value}` where value can be anything. + # The `column` is only validated if it's an integer. We check that the index is present. + # The function allows to change the `value` for each pair. + defp to_column_pairs(df, pairs, value_fun) + when is_column_pairs(pairs) and is_function(value_fun, 1) do + existing_columns = df.names + + pairs + |> Enum.map_reduce(nil, fn + {column, value}, maybe_map when is_integer(column) -> + map = maybe_map || column_index_map(existing_columns) + existing_column = fetch_column_at!(map, column) + {{existing_column, value_fun.(value)}, map} + + {column, value}, maybe_map when is_atom(column) -> + column = Atom.to_string(column) + {{column, value_fun.(value)}, maybe_map} + + {column, value}, maybe_map when is_binary(column) -> + {{column, value_fun.(value)}, maybe_map} + end) + |> then(fn {pairs, _} -> pairs end) + end + + defp fetch_column_at!(map, index) do + normalized = if index < 0, do: index + map_size(map), else: index + + case map do + %{^normalized => column} -> column + %{} -> raise ArgumentError, "no column exists at index #{index}" + end + end + + defp column_index_map(names), + do: for({name, idx} <- Enum.with_index(names), into: %{}, do: {idx, name}) + + # Normalizes column names and raise if column does not exist. + defp to_existing_columns(df, columns, raise? \\ true) do + Explorer.Shared.to_existing_columns(df, columns, raise?) + end + + # Normalizes the "columns" option for some IO operations. + defp to_columns_for_io(nil), do: nil + + defp to_columns_for_io([h | _] = columns) when is_integer(h) do + if Enum.all?(columns, &is_integer/1) do + columns + else + raise ArgumentError, + "expected :columns to be a list of only integers, only atoms, or only binaries, " <> + "got: #{inspect(columns)}" + end + end + + defp to_columns_for_io([h | _] = columns) when is_column_name(h), + do: Enum.map(columns, &to_column_name/1) + + defp to_columns_for_io(other) do + raise ArgumentError, + "expected :columns to be a list of only integers, only atoms, or only binaries, " <> + "got: #{inspect(other)}" + end + + defp check_dtypes!(dtypes) do + Enum.map(dtypes, fn + {key, value} when is_atom(key) -> + {Atom.to_string(key), check_dtype!(key, value)} + + {key, value} when is_binary(key) -> + {key, check_dtype!(key, value)} + + _ -> + raise ArgumentError, + "dtypes must be a list/map of column names as keys and types as values, " <> + "where the keys are atoms or binaries. Got: #{inspect(dtypes)}" + end) + end + + defp check_dtype!(key, value) do + if dtype = Shared.normalise_dtype(value) do + dtype + else + raise ArgumentError, + "invalid dtype #{inspect(value)} for #{inspect(key)} (expected one of #{inspect(Shared.dtypes())})" + end + end + + # Access + + @behaviour Access + @compile {:no_warn_undefined, Nx} + + @impl true + def fetch(df, column) when is_column(column) do + {:ok, pull(df, column)} + end + + def fetch(df, columns) do + columns = to_existing_columns(df, columns) + + {:ok, select(df, columns)} + end + + @impl true + def pop(df, column) when is_column(column) do + [column] = to_existing_columns(df, [column]) + {pull_existing(df, column), discard(df, [column])} + end + + def pop(df, columns) do + columns = to_existing_columns(df, columns) + {select(df, columns), discard(df, columns)} + end + + # Notice that the resultant series is going to have the `:name` field + # equals to the column name. + @impl true + def get_and_update(df, column, fun) when is_column(column) do + [column] = to_existing_columns(df, [column]) + value = pull_existing(df, column) + {current_value, new_value} = fun.(value) + new_df = put(df, column, new_value) + {%{current_value | name: column}, new_df} + end + + # IO + + @doc """ + Reads data from a query. + + `conn` must be a `Adbc.Connection` process. `sql` is a string representing + the sql query and `params` is the list of query parameters. See `Adbc` + for more information. + + ## Example + + In order to read data from a database, you must list `:adbc` as a dependency, + download the relevant driver, and start both database and connection processes + in your supervision tree. + + First, add `:adbc` as a dependency in your `mix.exs`: + + {:adbc, "~> 0.1"} + + Now, in your config/config.exs, configure the drivers you are going to use + (see `Adbc` module docs for more information on supported drivers): + + config :adbc, :drivers, [:sqlite] + + If you are using a notebook or scripting, you can also use `Adbc.download_driver!/1` + to dynamically download one. + + Then start the database and the relevant connection processes in your + supervision tree: + + children = [ + {Adbc.Database, + driver: :sqlite, + process_options: [name: MyApp.DB]}, + {Adbc.Connection, + database: MyApp.DB, + process_options: [name: MyApp.Conn]} + ] + + Supervisor.start_link(children, strategy: :one_for_one) + + In a notebook, the above would look like this: + + db = Kino.start_child!({Adbc.Database, driver: :sqlite}) + conn = Kino.start_child!({Adbc.Connection, database: db}) + + And now you can make queries with: + + # For named connections + {:ok, _} = Explorer.DataFrame.from_query(MyApp.Conn, "SELECT 123", []) + + # When using the conn PID directly + {:ok, _} = Explorer.DataFrame.from_query(conn, "SELECT 123", []) + + Parameterized queries are possible by passing a list of parameters as the third argument. The + query string will use a different placeholder depending on the driver. For example, `?` for + SQLite and `$1`, `$2`, etc. for PostgreSQL. + + # For SQLite + {:ok, _} = Explorer.DataFrame.from_query(conn, "SELECT ?", [123]) + + # When using PostgreSQL + {:ok, _} = Explorer.DataFrame.from_query(conn, "SELECT $1", [123]) + + ## Options + + * `:backend` - The Explorer backend to use. Defaults to the value returned by `Explorer.Backend.get/0`. + + * `:lazy` - force the results into the lazy version of the current backend. + """ + @doc type: :io + @spec from_query( + Adbc.Connection.t(), + query :: String.t(), + params :: list(term), + opts :: Keyword.t() + ) :: + {:ok, DataFrame.t()} | {:error, Exception.t()} + def from_query(conn, query, params, opts \\ []) + + if Code.ensure_loaded?(Adbc) do + def from_query(conn, query, params, opts) + when is_binary(query) and is_list(params) and is_list(opts) do + opts = Keyword.validate!(opts, [:backend, :lazy]) + backend = backend_from_options!(opts) + backend.from_query(conn, query, params) + end + else + def from_query(_conn, _query, _params, _opts) do + raise "you must install :adbc as a dependency in order to use from_query/3" + end + end + + @doc """ + Similar to `from_query/4` but raises if there is an error. + """ + @doc type: :io + @spec from_query!( + Adbc.Connection.t(), + query :: String.t(), + params :: list(term), + opts :: Keyword.t() + ) :: + DataFrame.t() + def from_query!(conn, query, params, opts \\ []) do + case from_query(conn, query, params, opts) do + {:ok, df} -> df + {:error, error} -> raise error + end + end + + @doc """ + Reads a delimited file into a dataframe. + + It accepts a filename that can be a local file, a "s3://" schema, or + a `FSS` entry like `FSS.S3.Entry`. + + If the CSV is compressed, it is automatically decompressed. + + ## Options + + * `:delimiter` - A single character used to separate fields within a record. (default: `","`) + + * `:dtypes` - A list of shape `[column_name: dtype]`. The column names must match the ones in the + CSV header or the ones given in the `:columns` option. Any non-specified column has its type + imputed from the first 1000 rows. (default: `[]`) + + * `:header` - Does the file have a header of column names as the first row or not? (default: `true`) + + * `:max_rows` - Maximum number of lines to read. (default: `nil`) + + * `:nil_values` - A list of strings that should be interpreted as a nil values. (default: `[]`) + + * `:skip_rows` - The number of lines to skip at the beginning of the file. (default: `0`) + + * `:skip_rows_after_header` - The number of lines to skip after the header row. (default: `0`) + + * `:columns` - A list of column names or indexes to keep. + If present, only these columns are read into the dataframe. (default: `nil`) + + * `:infer_schema_length` - Maximum number of rows read for schema inference. + Set it to zero to disable inference and default all values to string. + Setting this to nil will do a full table scan and will be slow (default: `1000`). + + * `:parse_dates` - Automatically try to parse dates/ datetimes and time. + If parsing fails, columns remain of dtype `string` + + * `:eol_delimiter` - A single character used to represent new lines. (default: `"\n"`) + + * `:config` - An optional struct, keyword list or map, normally associated with remote + file systems. See [IO section](#module-io-operations) for more details. (default: `nil`) + + * `:backend` - The Explorer backend to use. Defaults to the value returned by `Explorer.Backend.get/0`. + + * `:lazy` - force the results into the lazy version of the current backend. + + * `:node` - The Erlang node to allocate the data frame on. + + * `:encoding` - Encoding to use when reading the file. For now, the only possible values are `utf8` and `utf8-lossy`. + The utf8-lossy option means that invalid utf8 values are replaced with � characters. (default: `"utf8"`) + + """ + @doc type: :io + @spec from_csv(filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: + {:ok, DataFrame.t()} | {:error, Exception.t()} + def from_csv(filename, opts \\ []) do + {backend_opts, opts} = Keyword.split(opts, [:backend, :lazy, :node]) + + opts = + Keyword.validate!(opts, + config: nil, + delimiter: ",", + dtypes: [], + encoding: "utf8", + header: true, + max_rows: nil, + nil_values: [], + skip_rows: 0, + skip_rows_after_header: 0, + columns: nil, + infer_schema_length: @default_infer_schema_length, + parse_dates: false, + eol_delimiter: nil + ) + + backend = backend_from_options!(backend_opts) + + with {:ok, entry} <- normalise_entry(filename, opts[:config]) do + args = [ + entry, + check_dtypes!(opts[:dtypes]), + opts[:delimiter], + opts[:nil_values], + opts[:skip_rows], + opts[:skip_rows_after_header], + opts[:header], + opts[:encoding], + opts[:max_rows], + to_columns_for_io(opts[:columns]), + opts[:infer_schema_length], + opts[:parse_dates], + opts[:eol_delimiter] + ] + + Shared.apply_init(backend, :from_csv, args, backend_opts) + end + end + + @doc """ + Similar to `from_csv/2` but raises if there is a problem reading the CSV. + """ + @doc type: :io + @spec from_csv!(filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: DataFrame.t() + def from_csv!(filename, opts \\ []) do + case from_csv(filename, opts) do + {:ok, df} -> + df + + {:error, %module{} = e} when module in [ArgumentError, RuntimeError] -> + raise module, "from_csv failed: #{e.message}" + + {:error, error} -> + raise "from_csv failed: #{inspect(error)}" + end + end + + @doc """ + Writes a dataframe to a delimited file. + + Note not all fields can be serialized to csv and it may require + explicitly casting to other formats. In such cases, an error is returned. + + Groups are ignored if the dataframe is using any. + + ## Options + + * `:header` - Should the column names be written as the first line of the file? (default: `true`) + + * `:delimiter` - A single character used to separate fields within a record. (default: `","`) + + * `:config` - An optional struct, keyword list or map, normally associated with remote + file systems. See [IO section](#module-io-operations) for more details. (default: `nil`) + + * `:streaming` - Tells the backend if it should use streaming, which means + that the dataframe is not loaded to the memory at once, and instead it is + written in chunks from a lazy dataframe. Defaults to true for local filesystems, + ignored on all others. + + """ + @doc type: :io + @spec to_csv(df :: DataFrame.t(), filename :: fs_entry() | String.t(), opts :: Keyword.t()) :: + :ok | {:error, Exception.t()} + def to_csv(df, filename, opts \\ []) do + opts = Keyword.validate!(opts, header: true, delimiter: ",", streaming: true, config: nil) + + with {:ok, entry} <- normalise_entry(filename, opts[:config]) do + Shared.apply_dataframe(df, :to_csv, [ + entry, + opts[:header], + opts[:delimiter], + opts[:streaming] + ]) + end + end + + @doc """ + Similar to `to_csv/3` but raises if there is a problem reading the CSV. + """ + @doc type: :io + @spec to_csv!(df :: DataFrame.t(), filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: + :ok + def to_csv!(df, filename, opts \\ []) do + case to_csv(df, filename, opts) do + :ok -> + :ok + + {:error, %module{} = e} when module in [ArgumentError, RuntimeError] -> + raise module, "to_csv failed: #{e.message}" + + {:error, error} -> + raise "to_csv failed: #{inspect(error)}" + end + end + + @doc """ + Writes a dataframe to a binary representation of a delimited file. + + ## Options + + * `:header` - Should the column names be written as the first line of the file? (default: `true`) + * `:delimiter` - A single character used to separate fields within a record. (default: `","`) + + ## Examples + + iex> df = Explorer.Datasets.fossil_fuels() |> Explorer.DataFrame.head(2) + iex> Explorer.DataFrame.dump_csv(df) + {:ok, "year,country,total,solid_fuel,liquid_fuel,gas_fuel,cement,gas_flaring,per_capita,bunker_fuels\\n2010,AFGHANISTAN,2308,627,1601,74,5,0,0.08,9\\n2010,ALBANIA,1254,117,953,7,177,0,0.43,7\\n"} + """ + @doc type: :io + @spec dump_csv(df :: DataFrame.t(), opts :: Keyword.t()) :: + {:ok, String.t()} | {:error, Exception.t()} + def dump_csv(df, opts \\ []) do + opts = Keyword.validate!(opts, header: true, delimiter: ",") + Shared.apply_dataframe(df, :dump_csv, [opts[:header], opts[:delimiter]], false) + end + + @doc """ + Similar to `dump_csv/2`, but raises in case of error. + """ + @doc type: :io + @spec dump_csv!(df :: DataFrame.t(), opts :: Keyword.t()) :: String.t() + def dump_csv!(df, opts \\ []) do + case dump_csv(df, opts) do + {:ok, csv} -> csv + {:error, error} -> raise "dump_csv failed: #{inspect(error)}" + end + end + + @doc """ + Reads a representation of a CSV file into a dataframe. + + If the CSV is compressed, it is automatically decompressed. + + Accepts the same options as `from_csv/2`. + """ + @doc type: :io + @spec load_csv(contents :: String.t(), opts :: Keyword.t()) :: + {:ok, DataFrame.t()} | {:error, Exception.t()} + def load_csv(contents, opts \\ []) do + {backend_opts, opts} = Keyword.split(opts, [:backend, :lazy, :node]) + + opts = + Keyword.validate!(opts, + delimiter: ",", + dtypes: [], + encoding: "utf8", + header: true, + max_rows: nil, + nil_values: [], + skip_rows: 0, + skip_rows_after_header: 0, + columns: nil, + infer_schema_length: @default_infer_schema_length, + parse_dates: false, + eol_delimiter: nil + ) + + backend = backend_from_options!(backend_opts) + + args = [ + contents, + check_dtypes!(opts[:dtypes]), + opts[:delimiter], + opts[:nil_values], + opts[:skip_rows], + opts[:skip_rows_after_header], + opts[:header], + opts[:encoding], + opts[:max_rows], + to_columns_for_io(opts[:columns]), + opts[:infer_schema_length], + opts[:parse_dates], + opts[:eol_delimiter] + ] + + Shared.apply_init(backend, :load_csv, args, backend_opts) + end + + @doc """ + Similar to `load_csv/2` but raises if there is a problem reading the CSV. + """ + @doc type: :io + @spec load_csv!(contents :: String.t(), opts :: Keyword.t()) :: DataFrame.t() + def load_csv!(contents, opts \\ []) do + case load_csv(contents, opts) do + {:ok, df} -> df + {:error, error} -> raise "load_csv failed: #{inspect(error)}" + end + end + + @doc """ + Reads a parquet file into a dataframe. + + It accepts a filename that can be a local file, a "s3://" schema, or + a `FSS` entry like `FSS.S3.Entry`. + + ## Options + + * `:max_rows` - Maximum number of lines to read. (default: `nil`) + + * `:columns` - A list of column names or indexes to keep. If present, + only these columns are read into the dataframe. (default: `nil`) + + * `:rechunk` - Make sure that all columns are contiguous in memory + by aggregating the chunks into a single array. (default: `false`) + + * `:config` - An optional struct, keyword list or map, normally associated with remote + file systems. See [IO section](#module-io-operations) for more details. (default: `nil`) + + * `:backend` - The Explorer backend to use. Defaults to the value returned by `Explorer.Backend.get/0`. + + * `:lazy` - force the results into the lazy version of the current backend. + + * `:node` - The Erlang node to allocate the data frame on. + """ + @doc type: :io + @spec from_parquet(filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: + {:ok, DataFrame.t()} | {:error, Exception.t()} + def from_parquet(filename, opts \\ []) do + {backend_opts, opts} = Keyword.split(opts, [:backend, :lazy, :node]) + + opts = + Keyword.validate!(opts, + max_rows: nil, + columns: nil, + config: nil, + rechunk: false + ) + + backend = backend_from_options!(backend_opts) + + with {:ok, entry} <- normalise_entry(filename, opts[:config]) do + args = [ + entry, + opts[:max_rows], + to_columns_for_io(opts[:columns]), + opts[:rechunk] + ] + + Shared.apply_init(backend, :from_parquet, args, backend_opts) + end + end + + defp normalise_entry(%_{} = entry, config) when config != nil do + {:error, + ArgumentError.message( + ":config key is only supported when the argument is a string, got #{inspect(entry)} with config #{inspect(config)}" + )} + end + + defp normalise_entry(%Local.Entry{} = entry, nil), do: {:ok, entry} + defp normalise_entry(%HTTP.Entry{} = entry, nil), do: {:ok, entry} + defp normalise_entry(%S3.Entry{config: %S3.Config{}} = entry, nil), do: {:ok, entry} + + defp normalise_entry("s3://" <> _rest = entry, config) do + S3.parse(entry, config: config) + end + + defp normalise_entry("file://" <> path, _config), do: {:ok, Local.from_path(path)} + + defp normalise_entry("http://" <> _rest = url, config) do + HTTP.parse(url, config: config) + end + + defp normalise_entry("https://" <> _rest = url, config) do + HTTP.parse(url, config: config) + end + + defp normalise_entry(filepath, _config) when is_binary(filepath) do + {:ok, Local.from_path(filepath)} + end + + @doc """ + Similar to `from_parquet/2` but raises if there is a problem reading the Parquet file. + """ + @doc type: :io + @spec from_parquet!(filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: DataFrame.t() + def from_parquet!(filename, opts \\ []) do + case from_parquet(filename, opts) do + {:ok, df} -> + df + + {:error, %module{} = e} when module in [ArgumentError, RuntimeError] -> + raise module, "from_parquet failed: #{e.message}" + + {:error, error} -> + raise "from_parquet failed: #{inspect(error)}" + end + end + + @doc """ + Writes a dataframe to a parquet file. + + Groups are ignored if the dataframe is using any. + + ## Options + + * `:compression` - The compression algorithm to use when writing files. + Where a compression level is available, this can be passed as a tuple, + such as `{:zstd, 3}`. Supported options are: + + * `nil` (uncompressed, default) + * `:snappy` + * `:gzip` (with levels 1-9) + * `:brotli` (with levels 1-11) + * `:zstd` (with levels -7-22) + * `:lz4raw`. + + * `:streaming` - Tells the backend if it should use streaming, which means + that the dataframe is not loaded to the memory at once, and instead it is + written in chunks from a lazy dataframe. + + This option has no effect on eager - the default - dataframes. + It defaults to `true`. + + * `:config` - An optional struct, keyword list or map, normally associated with remote + file systems. See [IO section](#module-io-operations) for more details. (default: `nil`) + + """ + @doc type: :io + @spec to_parquet(df :: DataFrame.t(), filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: + :ok | {:error, Exception.t()} + def to_parquet(%DataFrame{} = df, filename, opts \\ []) do + opts = Keyword.validate!(opts, compression: nil, streaming: true, config: nil) + compression = parquet_compression(opts[:compression]) + + with {:ok, entry} <- normalise_entry(filename, opts[:config]) do + Shared.apply_dataframe(df, :to_parquet, [entry, compression, opts[:streaming]]) + end + end + + defp parquet_compression(nil), do: {nil, nil} + + defp parquet_compression(algorithm) when algorithm in ~w(snappy gzip brotli zstd lz4raw)a do + {algorithm, nil} + end + + for {algorithm, min, max} <- [{:gzip, 1, 9}, {:brotli, 1, 11}, {:zstd, -7, 22}] do + defp parquet_compression({unquote(algorithm), level}) do + if level in unquote(min)..unquote(max) or is_nil(level) do + {unquote(algorithm), level} + else + raise ArgumentError, + "#{unquote(algorithm)} compression level must be between #{unquote(min)} and #{unquote(max)} inclusive or nil, got #{level}" + end + end + end + + defp parquet_compression(other) do + raise ArgumentError, "unsupported :compression #{inspect(other)} for Parquet" + end + + @doc """ + Similar to `to_parquet/3`, but raises in case of error. + """ + @doc type: :io + @spec to_parquet!(df :: DataFrame.t(), filename :: String.t() | fs_entry()) :: :ok + def to_parquet!(df, filename, opts \\ []) do + case to_parquet(df, filename, opts) do + :ok -> + :ok + + {:error, %module{} = e} when module in [ArgumentError, RuntimeError] -> + raise module, "to_parquet failed: #{e.message}" + + {:error, error} -> + raise "to_parquet failed: #{inspect(error)}" + end + end + + @doc """ + Writes a dataframe to a binary representation of a Parquet file. + + Groups are ignored if the dataframe is using any. + + ## Options + + * `:compression` - The compression algorithm to use when writing files. + Where a compression level is available, this can be passed as a tuple, + such as `{:zstd, 3}`. Supported options are: + + * `nil` (uncompressed, default) + * `:snappy` + * `:gzip` (with levels 1-9) + * `:brotli` (with levels 1-11) + * `:zstd` (with levels -7-22) + * `:lz4raw`. + + """ + @doc type: :io + @spec dump_parquet(df :: DataFrame.t(), opts :: Keyword.t()) :: + {:ok, binary()} | {:error, Exception.t()} + def dump_parquet(df, opts \\ []) do + opts = Keyword.validate!(opts, compression: nil) + compression = parquet_compression(opts[:compression]) + + Shared.apply_dataframe(df, :dump_parquet, [compression], false) + end + + @doc """ + Similar to `dump_parquet/2`, but raises in case of error. + """ + @doc type: :io + @spec dump_parquet!(df :: DataFrame.t(), opts :: Keyword.t()) :: binary() + def dump_parquet!(df, opts \\ []) do + case dump_parquet(df, opts) do + {:ok, parquet} -> parquet + {:error, error} -> raise "dump_parquet failed: #{inspect(error)}" + end + end + + @doc """ + Reads a binary representation of a parquet file into a dataframe. + + Accepts the same options as `from_parquet/2`. + """ + @doc type: :io + @spec load_parquet(contents :: binary(), opts :: Keyword.t()) :: + {:ok, DataFrame.t()} | {:error, Exception.t()} + def load_parquet(contents, opts \\ []) do + opts = Keyword.validate!(opts, [:backend, :lazy, :node]) + backend = backend_from_options!(opts) + Shared.apply_init(backend, :load_parquet, [contents], opts) + end + + @doc """ + Similar to `load_parquet/2` but raises if there is a problem reading the Parquet file. + """ + @doc type: :io + @spec load_parquet!(contents :: binary(), opts :: Keyword.t()) :: DataFrame.t() + def load_parquet!(contents, opts \\ []) do + case load_parquet(contents, opts) do + {:ok, df} -> df + {:error, error} -> raise "load_parquet failed: #{inspect(error)}" + end + end + + @doc """ + Reads an IPC file into a dataframe. + + It accepts a filename that can be a local file, a "s3://" schema, or + a `FSS` entry like `FSS.S3.Entry`. + + ## Options + + * `:columns` - List with the name or index of columns to be selected. + Defaults to all columns. + + * `:config` - An optional struct, keyword list or map, normally associated with remote + file systems. See [IO section](#module-io-operations) for more details. (default: `nil`) + + * `:backend` - The Explorer backend to use. Defaults to the value returned by `Explorer.Backend.get/0`. + + * `:lazy` - force the results into the lazy version of the current backend. + + * `:node` - The Erlang node to allocate the data frame on. + """ + @doc type: :io + @spec from_ipc(filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: + {:ok, DataFrame.t()} | {:error, Exception.t()} + def from_ipc(filename, opts \\ []) do + {backend_opts, opts} = Keyword.split(opts, [:backend, :lazy, :node]) + + opts = + Keyword.validate!(opts, + columns: nil, + config: nil + ) + + backend = backend_from_options!(backend_opts) + + with {:ok, entry} <- normalise_entry(filename, opts[:config]) do + Shared.apply_init( + backend, + :from_ipc, + [entry, to_columns_for_io(opts[:columns])], + backend_opts + ) + end + end + + @doc """ + Similar to `from_ipc/2` but raises if there is a problem reading the IPC file. + """ + @doc type: :io + @spec from_ipc!(filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: DataFrame.t() + def from_ipc!(filename, opts \\ []) do + case from_ipc(filename, opts) do + {:ok, df} -> + df + + {:error, %module{} = e} when module in [ArgumentError, RuntimeError] -> + raise module, "from_ipc failed: #{e.message}" + + {:error, error} -> + raise "from_ipc failed: #{inspect(error)}" + end + end + + @doc """ + Writes a dataframe to an IPC file. + + Apache IPC is a language-agnostic columnar data structure that can be used to store dataframes. + It excels as a format for quickly exchange data between different programming languages. + + Groups are ignored if the dataframe is using any. + + ## Options + + * `:compression` - The compression algorithm to use when writing files. + Supported options are: + + * `nil` (uncompressed, default) + * `:zstd` + * `:lz4`. + + * `:streaming` - Tells the backend if it should use streaming, which means + that the dataframe is not loaded to the memory at once, and instead it is + written in chunks from a lazy dataframe. + + This option has no effect on eager - the default - dataframes. + It defaults to `true`. + + * `:config` - An optional struct, keyword list or map, normally associated with remote + file systems. See [IO section](#module-io-operations) for more details. (default: `nil`) + + """ + @doc type: :io + @spec to_ipc(df :: DataFrame.t(), filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: + :ok | {:error, Exception.t()} + def to_ipc(df, filename, opts \\ []) do + opts = Keyword.validate!(opts, compression: nil, streaming: true, config: nil) + compression = ipc_compression(opts[:compression]) + + with {:ok, entry} <- normalise_entry(filename, opts[:config]) do + Shared.apply_dataframe(df, :to_ipc, [entry, compression, opts[:streaming]]) + end + end + + defp ipc_compression(nil), do: {nil, nil} + defp ipc_compression(algorithm) when algorithm in ~w(zstd lz4)a, do: {algorithm, nil} + + defp ipc_compression(other), + do: raise(ArgumentError, "unsupported :compression #{inspect(other)} for IPC") + + @doc """ + Similar to `to_ipc/3`, but raises in case of error. + """ + @doc type: :io + @spec to_ipc!(df :: DataFrame.t(), filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: + :ok + def to_ipc!(df, filename, opts \\ []) do + case to_ipc(df, filename, opts) do + :ok -> + :ok + + {:error, %module{} = e} when module in [ArgumentError, RuntimeError] -> + raise module, "to_ipc failed: #{e.message}" + + {:error, error} -> + raise "to_ipc failed: #{inspect(error)}" + end + end + + @doc """ + Writes a dataframe to a binary representation of an IPC file. + + Groups are ignored if the dataframe is using any. + + ## Options + + * `:compression` - The compression algorithm to use when writing files. + Supported options are: + + * `nil` (uncompressed, default) + * `:zstd` + * `:lz4`. + + """ + @doc type: :io + @spec dump_ipc(df :: DataFrame.t(), opts :: Keyword.t()) :: + {:ok, binary()} | {:error, Exception.t()} + def dump_ipc(df, opts \\ []) do + opts = Keyword.validate!(opts, compression: nil) + compression = ipc_compression(opts[:compression]) + + Shared.apply_dataframe(df, :dump_ipc, [compression], false) + end + + @doc """ + Similar to `dump_ipc/2`, but raises in case of error. + """ + @doc type: :io + @spec dump_ipc!(df :: DataFrame.t(), opts :: Keyword.t()) :: binary() + def dump_ipc!(df, opts \\ []) do + case dump_ipc(df, opts) do + {:ok, ipc} -> ipc + {:error, error} -> raise "dump_ipc failed: #{inspect(error)}" + end + end + + @doc """ + Reads a binary representing an IPC file into a dataframe. + + Accepts the same options as `from_ipc/2`. + """ + @doc type: :io + @spec load_ipc(contents :: binary(), opts :: Keyword.t()) :: + {:ok, DataFrame.t()} | {:error, Exception.t()} + def load_ipc(contents, opts \\ []) do + {backend_opts, opts} = Keyword.split(opts, [:backend, :lazy, :node]) + + opts = + Keyword.validate!(opts, + columns: nil + ) + + backend = backend_from_options!(backend_opts) + + Shared.apply_init( + backend, + :load_ipc, + [contents, to_columns_for_io(opts[:columns])], + backend_opts + ) + end + + @doc """ + Similar to `load_ipc/2` but raises if there is a problem reading the IPC file. + """ + @doc type: :io + @spec load_ipc!(contents :: binary(), opts :: Keyword.t()) :: DataFrame.t() + def load_ipc!(contents, opts \\ []) do + case load_ipc(contents, opts) do + {:ok, df} -> df + {:error, error} -> raise "load_ipc failed: #{inspect(error)}" + end + end + + @doc """ + Reads an IPC Streaming file into a dataframe. + + It's possible to read from an IPC Streaming file using the lazy Polars + backend, but the implementation is not truly lazy. We are going to read it + first using the eager backend, and then convert the dataframe to lazy. + + ## Options + + * `:columns` - List with the name or index of columns to be selected. + Defaults to all columns. + + * `:backend` - The Explorer backend to use. Defaults to the value returned by `Explorer.Backend.get/0`. + + * `:lazy` - force the results into the lazy version of the current backend. + + * `:node` - The Erlang node to allocate the data frame on. + + * `:config` - An optional struct, keyword list or map, normally associated with remote + file systems. See [IO section](#module-io-operations) for more details. (default: `nil`) + + """ + @doc type: :io + @spec from_ipc_stream(filename :: String.t() | fs_entry()) :: + {:ok, DataFrame.t()} | {:error, Exception.t()} + def from_ipc_stream(filename, opts \\ []) do + {backend_opts, opts} = Keyword.split(opts, [:backend, :lazy, :node]) + + opts = Keyword.validate!(opts, columns: nil, config: nil) + backend = backend_from_options!(backend_opts) + + with {:ok, entry} <- normalise_entry(filename, opts[:config]) do + Shared.apply_init( + backend, + :from_ipc_stream, + [entry, to_columns_for_io(opts[:columns])], + backend_opts + ) + end + end + + @doc """ + Similar to `from_ipc_stream/2` but raises if there is a problem reading the IPC Stream file. + """ + @doc type: :io + @spec from_ipc_stream!(filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: + DataFrame.t() + def from_ipc_stream!(filename, opts \\ []) do + case from_ipc_stream(filename, opts) do + {:ok, df} -> + df + + {:error, %module{} = e} when module in [ArgumentError, RuntimeError] -> + raise module, "from_ipc_stream failed: #{e.message}" + + {:error, error} -> + raise "from_ipc_stream failed: #{inspect(error)}" + end + end + + @doc """ + Writes a dataframe to an IPC Stream file. + + Arrow IPC Streams provide a streaming protocol or “format" for sending an arbitrary + length sequence of record batches. + The format must be processed from start to end, and does not support random access. + + ## Options + + * `:compression` - The compression algorithm to use when writing files. + Supported options are: + + * `nil` (uncompressed, default) + * `:zstd` + * `:lz4`. + + * `:config` - An optional struct, keyword list or map, normally associated with remote + file systems. See [IO section](#module-io-operations) for more details. (default: `nil`) + + """ + @doc type: :io + @spec to_ipc_stream(df :: DataFrame.t(), filename :: String.t() | fs_entry()) :: + :ok | {:error, Exception.t()} + def to_ipc_stream(df, filename, opts \\ []) do + opts = Keyword.validate!(opts, compression: nil, config: nil) + compression = ipc_compression(opts[:compression]) + + with {:ok, entry} <- normalise_entry(filename, opts[:config]) do + Shared.apply_dataframe(df, :to_ipc_stream, [entry, compression]) + end + end + + @doc """ + Similar to `to_ipc_stream/3`, but raises in case of error. + """ + @doc type: :io + @spec to_ipc_stream!( + df :: DataFrame.t(), + filename :: String.t() | fs_entry(), + opts :: Keyword.t() + ) :: :ok + def to_ipc_stream!(df, filename, opts \\ []) do + case to_ipc_stream(df, filename, opts) do + :ok -> + :ok + + {:error, %module{} = e} when module in [ArgumentError, RuntimeError] -> + raise module, "to_ipc_stream failed: #{e.message}" + + {:error, error} -> + raise "to_ipc_stream failed: #{inspect(error)}" + end + end + + @doc """ + Writes a dataframe to a binary representation of an IPC Stream file. + + Groups are ignored if the dataframe is using any. + + ## Options + + * `:compression` - The compression algorithm to use when writing files. + Supported options are: + + * `nil` (uncompressed, default) + * `:zstd` + * `:lz4`. + + """ + @doc type: :io + @spec dump_ipc_stream(df :: DataFrame.t(), opts :: Keyword.t()) :: + {:ok, binary()} | {:error, Exception.t()} + def dump_ipc_stream(df, opts \\ []) do + opts = Keyword.validate!(opts, compression: nil) + compression = ipc_compression(opts[:compression]) + + Shared.apply_dataframe(df, :dump_ipc_stream, [compression], false) + end + + @doc """ + Similar to `dump_ipc_stream/2`, but raises in case of error. + """ + @doc type: :io + @spec dump_ipc_stream!(df :: DataFrame.t(), opts :: Keyword.t()) :: binary() + def dump_ipc_stream!(df, opts \\ []) do + case dump_ipc_stream(df, opts) do + {:ok, ipc} -> ipc + {:error, error} -> raise "dump_ipc_stream failed: #{inspect(error)}" + end + end + + @doc """ + Reads a binary representing an IPC Stream file into a dataframe. + + Accepts the same options as `from_ipc_stream/2`. + """ + @doc type: :io + @spec load_ipc_stream(contents :: binary(), opts :: Keyword.t()) :: + {:ok, DataFrame.t()} | {:error, Exception.t()} + def load_ipc_stream(contents, opts \\ []) do + {backend_opts, opts} = Keyword.split(opts, [:backend, :lazy, :node]) + opts = Keyword.validate!(opts, columns: nil) + + backend = backend_from_options!(backend_opts) + + Shared.apply_init( + backend, + :load_ipc_stream, + [contents, to_columns_for_io(opts[:columns])], + backend_opts + ) + end + + @doc """ + Similar to `load_ipc_stream/2` but raises if there is a problem. + """ + @doc type: :io + @spec load_ipc_stream!(contents :: binary(), opts :: Keyword.t()) :: DataFrame.t() + def load_ipc_stream!(contents, opts \\ []) do + case load_ipc_stream(contents, opts) do + {:ok, df} -> df + {:error, error} -> raise "load_ipc_stream failed: #{inspect(error)}" + end + end + + @doc """ + Read a file of JSON objects or lists separated by new lines + + ## Options + + * `:batch_size` - Sets the batch size for reading rows. + This value may have significant impact in performance, + so adjust it for your needs (default: `1000`). + + * `:infer_schema_length` - Maximum number of rows read for schema inference. + Setting this to nil will do a full table scan and will be slow (default: `1000`). + + * `:backend` - The Explorer backend to use. Defaults to the value returned by `Explorer.Backend.get/0`. + + * `:lazy` - force the results into the lazy version of the current backend. + + * `:node` - The Erlang node to allocate the data frame on. + + * `:config` - An optional struct, keyword list or map, normally associated with remote + file systems. See [IO section](#module-io-operations) for more details. (default: `nil`) + + """ + @doc type: :io + @spec from_ndjson(filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: + {:ok, DataFrame.t()} | {:error, Exception.t()} + def from_ndjson(filename, opts \\ []) do + {backend_opts, opts} = Keyword.split(opts, [:backend, :lazy, :node]) + + opts = + Keyword.validate!(opts, + config: nil, + batch_size: 1000, + infer_schema_length: @default_infer_schema_length + ) + + backend = backend_from_options!(backend_opts) + + with {:ok, entry} <- normalise_entry(filename, opts[:config]) do + args = [entry, opts[:infer_schema_length], opts[:batch_size]] + Shared.apply_init(backend, :from_ndjson, args, backend_opts) + end + end + + @doc """ + Similar to `from_ndjson/2`, but raises in case of error. + """ + @doc type: :io + @spec from_ndjson!(filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: + DataFrame.t() + def from_ndjson!(filename, opts \\ []) do + case from_ndjson(filename, opts) do + {:ok, df} -> + df + + {:error, %module{} = e} when module in [ArgumentError, RuntimeError] -> + raise module, "from_ndjson failed: #{e.message}" + + {:error, error} -> + raise "from_ndjson failed: #{inspect(error)}" + end + end + + @doc """ + Writes a dataframe to a ndjson file. + + Groups are ignored if the dataframe is using any. + + NDJSON are files that contains JSON files separated by new lines. + They are often used as structured logs. + + ## Options + + * `:config` - An optional struct, keyword list or map, normally associated with remote + file systems. See [IO section](#module-io-operations) for more details. (default: `nil`) + + """ + @doc type: :io + @spec to_ndjson(df :: DataFrame.t(), filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: + :ok | {:error, Exception.t()} + def to_ndjson(df, filename, opts \\ []) do + opts = Keyword.validate!(opts, config: nil) + + with {:ok, entry} <- normalise_entry(filename, opts[:config]) do + Shared.apply_dataframe(df, :to_ndjson, [entry]) + end + end + + @doc """ + Similar to `to_ndjson/3`, but raises in case of error. + """ + @doc type: :io + @spec to_ndjson!(df :: DataFrame.t(), filename :: String.t() | fs_entry(), opts :: Keyword.t()) :: + :ok + def to_ndjson!(df, filename, opts \\ []) do + case to_ndjson(df, filename, opts) do + :ok -> + :ok + + {:error, %module{} = e} when module in [ArgumentError, RuntimeError] -> + raise module, "to_ndjson failed: #{e.message}" + + {:error, error} -> + raise "to_ndjson failed: #{inspect(error)}" + end + end + + @doc """ + Writes a dataframe to a binary representation of a NDJSON file. + + Groups are ignored if the dataframe is using any. + + ## Examples + + iex> df = Explorer.DataFrame.new(col_a: [1, 2], col_b: [5.1, 5.2]) + iex> Explorer.DataFrame.dump_ndjson(df) + {:ok, ~s({"col_a":1,"col_b":5.1}\\n{"col_a":2,"col_b":5.2}\\n)} + + """ + @doc type: :io + @spec dump_ndjson(df :: DataFrame.t()) :: {:ok, binary()} | {:error, Exception.t()} + def dump_ndjson(df) do + Shared.apply_dataframe(df, :dump_ndjson, [], false) + end + + @doc """ + Similar to `dump_ndjson!/2`, but raises in case of error. + """ + @doc type: :io + @spec dump_ndjson!(df :: DataFrame.t()) :: binary() + def dump_ndjson!(df) do + case dump_ndjson(df) do + {:ok, ndjson} -> ndjson + {:error, error} -> raise "dump_ndjson failed: #{inspect(error)}" + end + end + + @doc """ + Reads a representation of a NDJSON file into a dataframe. + + Accepts the same options as `from_ndjson/2`. + """ + @doc type: :io + @spec load_ndjson(contents :: String.t(), opts :: Keyword.t()) :: + {:ok, DataFrame.t()} | {:error, Exception.t()} + def load_ndjson(contents, opts \\ []) do + {backend_opts, opts} = Keyword.split(opts, [:backend, :lazy, :node]) + + opts = + Keyword.validate!(opts, + batch_size: 1000, + infer_schema_length: @default_infer_schema_length + ) + + backend = backend_from_options!(backend_opts) + args = [contents, opts[:infer_schema_length], opts[:batch_size]] + Shared.apply_init(backend, :load_ndjson, args, backend_opts) + end + + @doc """ + Similar to `load_ndjson/2`, but raises in case of error. + + ## Examples + + iex> contents = ~s({"col_a":1,"col_b":5.1}\\n{"col_a":2,"col_b":5.2}\\n) + iex> Explorer.DataFrame.load_ndjson!(contents) + #Explorer.DataFrame< + Polars[2 x 2] + col_a s64 [1, 2] + col_b f64 [5.1, 5.2] + > + + """ + @doc type: :io + @spec load_ndjson!(contents :: String.t(), opts :: Keyword.t()) :: + DataFrame.t() + def load_ndjson!(contents, opts \\ []) do + case load_ndjson(contents, opts) do + {:ok, df} -> + df + + {:error, %module{} = e} when module in [ArgumentError, RuntimeError] -> + raise module, "load_ndjson failed: #{e.message}" + + {:error, error} -> + raise "load_ndjson failed: #{inspect(error)}" + end + end + + ## Conversion + + @doc """ + Returns true if the data frame is a lazy one. + """ + @doc type: :conversion + @spec lazy?(df :: DataFrame.t()) :: boolean + def lazy?(%DataFrame{data: %impl{}}), do: impl.lazy() == impl + + @doc """ + Converts the dataframe to the lazy version of the current backend. + + Operations on a lazy dataframe are not executed immediately, instead + they are batched together, and performed when `collect/1` is invoked. + This allows for query optimizations, parallelism, leading to better + performance. + + If already lazy, this is a noop. Converting a grouped dataframe should + return a lazy dataframe with groups. + """ + @doc type: :conversion + @spec lazy(df :: DataFrame.t()) :: DataFrame.t() + def lazy(df), do: Shared.apply_dataframe(df, :lazy) + + @deprecated "Use lazy/1 instead" + @doc false + def to_lazy(df), do: Shared.apply_dataframe(df, :lazy) + + @doc """ + Computes and collects a data frame to the current node. + + If the data frame is already in the current node, it is computed + but no transfer happens. + + ## Examples + + series = Explorer.Series.from_list([1, 2, 3], node: :some@node) + Explorer.Series.collect(series) + + """ + @doc type: :conversion + @spec collect(df :: DataFrame.t()) :: DataFrame.t() + def collect(df) do + %DataFrame{data: %impl{}} = df = compute(df) + + case impl.owner_reference(df) do + ref when is_reference(ref) and node(ref) != node() -> + with {:ok, exported} <- :erpc.call(node(ref), impl, :owner_export, [df]), + {:ok, imported} <- impl.owner_import(exported) do + imported + else + {:error, exception} -> raise exception + end + + _ -> + df + end + end + + @doc """ + Computes the lazy data frame into an eager one, executing the query. + + It is the opposite of `lazy/1`. If it is not a lazy data frame, + this is a noop. + + Collecting a grouped dataframe should return a grouped dataframe. + """ + @doc type: :conversion + @spec compute(df :: DataFrame.t()) :: DataFrame.t() + def compute(df), do: Shared.apply_dataframe(df, :compute) + + @doc """ + Creates a new dataframe. + + It accepts any of: + + * a map or keyword list of string/atom keys and series as values + * a map or keyword list of string/atom keys and tensors as values + * any data structure adhering to the `Table.Reader` protocol + + ## Options + + * `:backend` - The Explorer backend to use. Defaults to the value returned by `Explorer.Backend.get/0`. + * `:dtypes` - A list/map of `{column_name, dtype}` pairs. (default: `[]`) + * `:lazy` - force the results into the lazy version of the current backend. + + ## Examples + + ### From series + + Series can be given either as keyword lists or maps + where the keys are the name and the values are series: + + iex> Explorer.DataFrame.new(%{ + ...> floats: Explorer.Series.from_list([1.0, 2.0]), + ...> ints: Explorer.Series.from_list([1, nil]) + ...> }) + #Explorer.DataFrame< + Polars[2 x 2] + floats f64 [1.0, 2.0] + ints s64 [1, nil] + > + + ### From tensors + + To create dataframe from tensors, you can pass a matrix as argument. + Each matrix column becomes a dataframe column with names x1, x2, x3, + etc: + + iex> Explorer.DataFrame.new(Nx.tensor([ + ...> [1, 2, 3], + ...> [4, 5, 6] + ...> ])) + #Explorer.DataFrame< + Polars[2 x 3] + x1 s64 [1, 4] + x2 s64 [2, 5] + x3 s64 [3, 6] + > + + Explorer expects tensors to have certain types, so you may need to cast + the data accordingly. See `Explorer.Series.from_tensor/2` for more info. + + You can also pass a keyword list or maps of vectors (rank 1 tensors): + + iex> Explorer.DataFrame.new(%{ + ...> floats: Nx.tensor([1.0, 2.0], type: :f64), + ...> ints: Nx.tensor([3, 4]) + ...> }) + #Explorer.DataFrame< + Polars[2 x 2] + floats f64 [1.0, 2.0] + ints s64 [3, 4] + > + + Use dtypes to force a particular representation: + + iex> Explorer.DataFrame.new([ + ...> floats: Nx.tensor([1.0, 2.0], type: :f64), + ...> times: Nx.tensor([3_000, 4_000]) + ...> ], dtypes: [times: :time]) + #Explorer.DataFrame< + Polars[2 x 2] + floats f64 [1.0, 2.0] + times time [00:00:00.000003, 00:00:00.000004] + > + + ### From tabular + + Tabular data can be either columnar or row-based. + Let's start with column data: + + iex> Explorer.DataFrame.new(%{floats: [1.0, 2.0], ints: [1, nil]}) + #Explorer.DataFrame< + Polars[2 x 2] + floats f64 [1.0, 2.0] + ints s64 [1, nil] + > + + iex> Explorer.DataFrame.new(floats: [1.0, 2.0], ints: [1, nil]) + #Explorer.DataFrame< + Polars[2 x 2] + floats f64 [1.0, 2.0] + ints s64 [1, nil] + > + + iex> Explorer.DataFrame.new([floats: [1.0, 2.0], ints: [1, nil], binaries: [<<239, 191, 19>>, nil]], dtypes: [{:binaries, :binary}]) + #Explorer.DataFrame< + Polars[2 x 3] + floats f64 [1.0, 2.0] + ints s64 [1, nil] + binaries binary [<<239, 191, 19>>, nil] + > + + iex> Explorer.DataFrame.new(%{floats: [1.0, 2.0], ints: [1, "wrong"]}) + ** (ArgumentError) cannot create series "ints": the value "wrong" does not match the inferred dtype {:s, 64} + + From row data: + + iex> rows = [%{id: 1, name: "José"}, %{id: 2, name: "Christopher"}, %{id: 3, name: "Cristine"}] + iex> Explorer.DataFrame.new(rows) + #Explorer.DataFrame< + Polars[3 x 2] + id s64 [1, 2, 3] + name string ["José", "Christopher", "Cristine"] + > + + iex> rows = [[id: 1, name: "José"], [id: 2, name: "Christopher"], [id: 3, name: "Cristine"]] + iex> Explorer.DataFrame.new(rows) + #Explorer.DataFrame< + Polars[3 x 2] + id s64 [1, 2, 3] + name string ["José", "Christopher", "Cristine"] + > + """ + @doc type: :conversion + @spec new( + Table.Reader.t() | series_pairs, + opts :: Keyword.t() + ) :: DataFrame.t() + when series_pairs: %{column_name() => Series.t()} | [{column_name(), Series.t()}] + def new(data, opts \\ []) do + opts = Keyword.validate!(opts, lazy: false, backend: nil, dtypes: []) + backend = backend_from_options!(opts) + dtypes = check_dtypes!(opts[:dtypes]) + + case data do + %DataFrame{data: %^backend{}} -> + data + + data -> + case classify_data(data) do + {:series, data} -> + pairs = + for {name, series} <- data do + if not is_struct(series, Series) do + raise ArgumentError, + "expected a list or map of only series, got: #{inspect(series)}" + end + + {to_column_name(name), series} + end + + backend.from_series(pairs) + + {:tensor, data} -> + dtypes = Map.new(dtypes) + s_backend = df_backend_to_s_backend(backend) + + pairs = + for {name, tensor} <- data do + if not is_struct(tensor, Nx.Tensor) do + raise ArgumentError, + "expected a list or map of only tensors, got: #{inspect(tensor)}" + end + + name = to_column_name(name) + dtype = dtypes[name] + opts = [backend: s_backend] + opts = if dtype, do: [dtype: dtype] ++ opts, else: opts + {name, Series.from_tensor(tensor, opts)} + end + + backend.from_series(pairs) + + {:tabular, data} -> + backend.from_tabular(data, dtypes) + end + end + end + + defp classify_data([{_, %struct{}} | _] = data) when struct == Series, do: {:series, data} + defp classify_data([{_, %struct{}} | _] = data) when struct == Nx.Tensor, do: {:tensor, data} + + defp classify_data(%struct{} = data) do + if struct == Nx.Tensor do + case data.shape do + {_, cols} -> + {:tensor, Enum.map(1..cols, fn i -> {"x#{i}", data[[.., i - 1]]} end)} + + _ -> + raise ArgumentError, + "Explorer.DataFrame.new/2 only accepts tensor of rank 2, got: #{inspect(data)}" + end + else + {:tabular, data} + end + end + + defp classify_data(data) when is_map(data) do + case :maps.next(:maps.iterator(data)) do + {_key, %struct{}, _} when struct == Series -> {:series, data} + {_key, %struct{}, _} when struct == Nx.Tensor -> {:tensor, data} + _ -> {:tabular, data} + end + end + + defp classify_data(data), do: {:tabular, data} + + @doc """ + Converts a dataframe to a list of columns with lists as values. + + See `to_series/2` if you want a list of columns with series as values. + Note that this function does not take into account groups. + + > #### Warning {: .warning} + > + > This is an expensive operation since it converts series to lists and doing + > so will copy the whole dataframe. Prefer to use the operations in this and + > the `Explorer.Series` module rather than the ones in `Enum` whenever possible, + > as Explorer is optimized for large series. + + ## Options + + * `:atom_keys` - Configure if the resultant map should have atom keys. (default: `false`) + + ## Examples + + iex> df = Explorer.DataFrame.new(ints: [1, nil], floats: [1.0, 2.0]) + iex> Explorer.DataFrame.to_columns(df) + %{"floats" => [1.0, 2.0], "ints" => [1, nil]} + + iex> df = Explorer.DataFrame.new(floats: [1.0, 2.0], ints: [1, nil]) + iex> Explorer.DataFrame.to_columns(df, atom_keys: true) + %{floats: [1.0, 2.0], ints: [1, nil]} + + """ + @doc type: :conversion + @spec to_columns(df :: DataFrame.t(), Keyword.t()) :: map() + def to_columns(df, opts \\ []) do + opts = Keyword.validate!(opts, atom_keys: false) + atom_keys = opts[:atom_keys] + + for name <- df.names, into: %{} do + series = Shared.apply_dataframe(df, :pull, [name]) + key = if atom_keys, do: String.to_atom(name), else: name + {key, Series.to_list(series)} + end + end + + @doc """ + Converts a dataframe to a list of columns with series as values. + + See `to_columns/2` if you want a list of columns with lists as values. + Note that this function does not take into account groups. + + ## Options + + * `:atom_keys` - Configure if the resultant map should have atom keys. (default: `false`) + + ## Examples + + iex> df = Explorer.DataFrame.new(ints: [1, nil], floats: [1.0, 2.0]) + iex> map = Explorer.DataFrame.to_series(df) + iex> Explorer.Series.to_list(map["floats"]) + [1.0, 2.0] + iex> Explorer.Series.to_list(map["ints"]) + [1, nil] + + """ + @doc type: :conversion + @spec to_series(df :: DataFrame.t(), Keyword.t()) :: map() + def to_series(df, opts \\ []) do + opts = Keyword.validate!(opts, atom_keys: false) + atom_keys = opts[:atom_keys] + + for name <- df.names, into: %{} do + key = if atom_keys, do: String.to_atom(name), else: name + {key, Shared.apply_dataframe(df, :pull, [name])} + end + end + + @doc """ + Converts a dataframe to a list of maps (rows). + + > #### Warning {: .warning} + > + > This is an expensive operation since data is stored in a columnar format. + > You must avoid converting a dataframe to rows, as that will transform and + > copy the whole dataframe in memory. Prefer to use the operations in this + > module rather than the ones in `Enum` whenever possible, as this module is + > optimized for large series. + + ## Options + + * `:atom_keys` - Configure if the resultant maps should have atom keys. (default: `false`) + + ## Examples + + iex> df = Explorer.DataFrame.new(floats: [1.0, 2.0], ints: [1, nil]) + iex> Explorer.DataFrame.to_rows(df) + [%{"floats" => 1.0, "ints" => 1}, %{"floats" => 2.0 ,"ints" => nil}] + + iex> df = Explorer.DataFrame.new(floats: [1.0, 2.0], ints: [1, nil]) + iex> Explorer.DataFrame.to_rows(df, atom_keys: true) + [%{floats: 1.0, ints: 1}, %{floats: 2.0, ints: nil}] + """ + @doc type: :conversion + @spec to_rows(df :: DataFrame.t(), Keyword.t()) :: [map()] + def to_rows(df, opts \\ []) do + opts = Keyword.validate!(opts, atom_keys: false) + + Shared.apply_dataframe(df, :to_rows, [opts[:atom_keys]], false) + end + + @doc """ + Converts a dataframe to a stream of maps (rows). + + > #### Warning {: .warning} + > + > This is an expensive operation since data is stored in a columnar format. + > Prefer to use the operations in this module rather than the ones in `Enum` + > whenever possible, as this module is optimized for large series. + + ## Options + + * `:atom_keys` - Configure if the resultant maps should have atom keys. (default: `false`) + * `:chunk_size` - Number of rows passed to `to_rows/2` while streaming over the data. (default: `1000`) + + ## Examples + + iex> df = Explorer.DataFrame.new(floats: [1.0, 2.0], ints: [1, nil]) + iex> Explorer.DataFrame.to_rows_stream(df) |> Enum.map(& &1) + [%{"floats" => 1.0, "ints" => 1}, %{"floats" => 2.0 ,"ints" => nil}] + + iex> df = Explorer.DataFrame.new(floats: [1.0, 2.0], ints: [1, nil]) + iex> Explorer.DataFrame.to_rows_stream(df, atom_keys: true) |> Enum.map(& &1) + [%{floats: 1.0, ints: 1}, %{floats: 2.0, ints: nil}] + """ + @doc type: :conversion + @spec to_rows_stream(df :: DataFrame.t(), Keyword.t()) :: Enumerable.t() + def to_rows_stream(df, opts \\ []) do + opts = Keyword.validate!(opts, atom_keys: false, chunk_size: 1_000) + + Shared.apply_dataframe(df, :to_rows_stream, [opts[:atom_keys], opts[:chunk_size]], false) + end + + # Introspection + + @doc """ + Gets the names of the dataframe columns. + + ## Examples + + iex> df = Explorer.DataFrame.new(floats: [1.0, 2.0], ints: [1, 2]) + iex> Explorer.DataFrame.names(df) + ["floats", "ints"] + """ + @doc type: :introspection + @spec names(df :: DataFrame.t()) :: [String.t()] + def names(df), do: df.names + + @doc """ + Gets the dtypes of the dataframe columns. + + ## Examples + + iex> df = Explorer.DataFrame.new(floats: [1.0, 2.0], ints: [1, 2]) + iex> Explorer.DataFrame.dtypes(df) + %{"floats" => {:f, 64}, "ints" => {:s, 64}} + """ + @doc type: :introspection + @spec dtypes(df :: DataFrame.t()) :: %{String.t() => Explorer.Series.dtype()} + def dtypes(df), do: df.dtypes + + @doc """ + Gets the shape of the dataframe as a `{height, width}` tuple. + + This function works the same way for grouped dataframes, considering the entire + dataframe in the counting of rows. + + ## Examples + + iex> df = Explorer.DataFrame.new(floats: [1.0, 2.0, 3.0], ints: [1, 2, 3]) + iex> Explorer.DataFrame.shape(df) + {3, 2} + """ + @doc type: :introspection + @spec shape(df :: DataFrame.t()) :: {integer(), integer()} + def shape(df), do: {n_rows(df), n_columns(df)} + + @doc """ + Returns the number of rows in the dataframe. + + This function works the same way for grouped dataframes, considering the entire + dataframe in the counting of rows. + + ## Examples + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.n_rows(df) + 1094 + """ + @doc type: :introspection + @spec n_rows(df :: DataFrame.t()) :: integer() + def n_rows(df), do: Shared.apply_dataframe(df, :n_rows) + + @doc """ + Returns the number of columns in the dataframe. + + This function works the same way for grouped dataframes. + + ## Examples + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.n_columns(df) + 10 + """ + @doc type: :introspection + @spec n_columns(df :: DataFrame.t()) :: integer() + def n_columns(df), do: map_size(df.dtypes) + + @doc """ + Returns the groups of a dataframe. + + ## Examples + + iex> df = Explorer.Datasets.fossil_fuels() + iex> df = Explorer.DataFrame.group_by(df, "country") + iex> Explorer.DataFrame.groups(df) + ["country"] + + iex> df = Explorer.Datasets.iris() + iex> Explorer.DataFrame.groups(df) + [] + """ + @doc type: :introspection + @spec groups(df :: DataFrame.t()) :: list(String.t()) + def groups(%DataFrame{groups: groups}), do: groups + + # Single table verbs + + @doc """ + Returns the first *n* rows of the dataframe. + + By default it returns the first 5 rows. + + If the dataframe is using groups, then the first *n* rows of each group is + returned. + + ## Examples + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.head(df) + #Explorer.DataFrame< + Polars[5 x 10] + year s64 [2010, 2010, 2010, 2010, 2010] + country string ["AFGHANISTAN", "ALBANIA", "ALGERIA", "ANDORRA", "ANGOLA"] + total s64 [2308, 1254, 32500, 141, 7924] + solid_fuel s64 [627, 117, 332, 0, 0] + liquid_fuel s64 [1601, 953, 12381, 141, 3649] + gas_fuel s64 [74, 7, 14565, 0, 374] + cement s64 [5, 177, 2598, 0, 204] + gas_flaring s64 [0, 0, 2623, 0, 3697] + per_capita f64 [0.08, 0.43, 0.9, 1.68, 0.37] + bunker_fuels s64 [9, 7, 663, 0, 321] + > + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.head(df, 2) + #Explorer.DataFrame< + Polars[2 x 10] + year s64 [2010, 2010] + country string ["AFGHANISTAN", "ALBANIA"] + total s64 [2308, 1254] + solid_fuel s64 [627, 117] + liquid_fuel s64 [1601, 953] + gas_fuel s64 [74, 7] + cement s64 [5, 177] + gas_flaring s64 [0, 0] + per_capita f64 [0.08, 0.43] + bunker_fuels s64 [9, 7] + > + + ## Grouped examples + + Using grouped dataframes makes `head/2` return *n* rows from each group. + Here is an example using the Iris dataset, and returning two rows from each group: + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.head(grouped, 2) + #Explorer.DataFrame< + Polars[6 x 5] + Groups: ["species"] + sepal_length f64 [5.1, 4.9, 7.0, 6.4, 6.3, ...] + sepal_width f64 [3.5, 3.0, 3.2, 3.2, 3.3, ...] + petal_length f64 [1.4, 1.4, 4.7, 4.5, 6.0, ...] + petal_width f64 [0.2, 0.2, 1.4, 1.5, 2.5, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-versicolor", "Iris-versicolor", "Iris-virginica", ...] + > + + """ + @doc type: :rows + @spec head(df :: DataFrame.t(), nrows :: integer()) :: DataFrame.t() + def head(df, nrows \\ @default_sample_nrows), do: Shared.apply_dataframe(df, :head, [nrows]) + + @doc """ + Returns the last *n* rows of the dataframe. + + By default it returns the last 5 rows. + + If the dataframe is using groups, then the last *n* rows of each group is + returned. + + ## Examples + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.tail(df) + #Explorer.DataFrame< + Polars[5 x 10] + year s64 [2014, 2014, 2014, 2014, 2014] + country string ["VIET NAM", "WALLIS AND FUTUNA ISLANDS", "YEMEN", "ZAMBIA", "ZIMBABWE"] + total s64 [45517, 6, 6190, 1228, 3278] + solid_fuel s64 [19246, 0, 137, 132, 2097] + liquid_fuel s64 [12694, 6, 5090, 797, 1005] + gas_fuel s64 [5349, 0, 581, 0, 0] + cement s64 [8229, 0, 381, 299, 177] + gas_flaring s64 [0, 0, 0, 0, 0] + per_capita f64 [0.49, 0.44, 0.24, 0.08, 0.22] + bunker_fuels s64 [761, 1, 153, 33, 9] + > + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.tail(df, 2) + #Explorer.DataFrame< + Polars[2 x 10] + year s64 [2014, 2014] + country string ["ZAMBIA", "ZIMBABWE"] + total s64 [1228, 3278] + solid_fuel s64 [132, 2097] + liquid_fuel s64 [797, 1005] + gas_fuel s64 [0, 0] + cement s64 [299, 177] + gas_flaring s64 [0, 0] + per_capita f64 [0.08, 0.22] + bunker_fuels s64 [33, 9] + > + + ## Grouped examples + + Using grouped dataframes makes `tail/2` return **n rows** from each group. + Here is an example using the Iris dataset, and returning two rows from each group: + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.tail(grouped, 2) + #Explorer.DataFrame< + Polars[6 x 5] + Groups: ["species"] + sepal_length f64 [5.3, 5.0, 5.1, 5.7, 6.2, ...] + sepal_width f64 [3.7, 3.3, 2.5, 2.8, 3.4, ...] + petal_length f64 [1.5, 1.4, 3.0, 4.1, 5.4, ...] + petal_width f64 [0.2, 0.2, 1.1, 1.3, 2.3, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-versicolor", "Iris-versicolor", "Iris-virginica", ...] + > + + """ + @doc type: :rows + @spec tail(df :: DataFrame.t(), nrows :: integer()) :: DataFrame.t() + def tail(df, nrows \\ @default_sample_nrows), do: Shared.apply_dataframe(df, :tail, [nrows]) + + @doc """ + Selects a subset of columns by name. + + It's important to notice that groups are kept: + you can't select off grouping columns. + + ## Examples + + You can select a single column: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3]) + iex> Explorer.DataFrame.select(df, "a") + #Explorer.DataFrame< + Polars[3 x 1] + a string ["a", "b", "c"] + > + + Or a list of names: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3]) + iex> Explorer.DataFrame.select(df, ["a"]) + #Explorer.DataFrame< + Polars[3 x 1] + a string ["a", "b", "c"] + > + + You can also use a range or a list of integers: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3], c: [4, 5, 6]) + iex> Explorer.DataFrame.select(df, [0, 1]) + #Explorer.DataFrame< + Polars[3 x 2] + a string ["a", "b", "c"] + b s64 [1, 2, 3] + > + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3], c: [4, 5, 6]) + iex> Explorer.DataFrame.select(df, 0..1) + #Explorer.DataFrame< + Polars[3 x 2] + a string ["a", "b", "c"] + b s64 [1, 2, 3] + > + + Or you can use a callback function that takes the dataframe's names as its first argument: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3]) + iex> Explorer.DataFrame.select(df, &String.starts_with?(&1, "b")) + #Explorer.DataFrame< + Polars[3 x 1] + b s64 [1, 2, 3] + > + + Or, if you prefer, a regex: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3]) + iex> Explorer.DataFrame.select(df, ~r/^b$/) + #Explorer.DataFrame< + Polars[3 x 1] + b s64 [1, 2, 3] + > + + Or a callback function that takes names and types: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3]) + iex> Explorer.DataFrame.select(df, fn _name, type -> type == {:s, 64} end) + #Explorer.DataFrame< + Polars[3 x 1] + b s64 [1, 2, 3] + > + + ## Grouped examples + + Columns that are also groups cannot be removed, + you need to ungroup before removing these columns. + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.select(grouped, ["sepal_width"]) + #Explorer.DataFrame< + Polars[150 x 2] + Groups: ["species"] + sepal_width f64 [3.5, 3.0, 3.2, 3.1, 3.6, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + > + + """ + @doc type: :single + @spec select(df :: DataFrame.t(), column | columns) :: DataFrame.t() + def select(df, columns_or_column) + + def select(df, column) when is_column(column) do + select(df, [column]) + end + + def select(df, columns) do + columns = to_existing_columns(df, columns) + columns_to_keep = Enum.uniq(columns ++ df.groups) + + out_df = out_df(df, columns_to_keep, Map.take(df.dtypes, columns_to_keep)) + Shared.apply_dataframe(df, :select, [out_df]) + end + + @doc """ + Discards a subset of columns by name. + + It's important to notice that groups are kept: + you can't discard grouping columns. + + ## Examples + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3]) + iex> Explorer.DataFrame.discard(df, ["b"]) + #Explorer.DataFrame< + Polars[3 x 1] + a string ["a", "b", "c"] + > + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3], c: [4, 5, 6]) + iex> Explorer.DataFrame.discard(df, ["a", "b"]) + #Explorer.DataFrame< + Polars[3 x 1] + c s64 [4, 5, 6] + > + + Ranges, regexes, and functions are also accepted in column names, as in `select/2`. + + ## Grouped examples + + You cannot discard grouped columns. You need to ungroup before removing them: + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.discard(grouped, ["species"]) + #Explorer.DataFrame< + Polars[150 x 5] + Groups: ["species"] + sepal_length f64 [5.1, 4.9, 4.7, 4.6, 5.0, ...] + sepal_width f64 [3.5, 3.0, 3.2, 3.1, 3.6, ...] + petal_length f64 [1.4, 1.4, 1.3, 1.5, 1.4, ...] + petal_width f64 [0.2, 0.2, 0.2, 0.2, 0.2, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + > + + """ + @doc type: :single + @spec discard(df :: DataFrame.t(), column | columns) :: DataFrame.t() + def discard(df, columns_or_column) + + def discard(df, column) when is_column(column) do + discard(df, [column]) + end + + def discard(df, columns) do + columns = to_existing_columns(df, columns, false) -- df.groups + columns_to_keep = df.names -- columns + + out_df = out_df(df, columns_to_keep, Map.take(df.dtypes, columns_to_keep)) + Shared.apply_dataframe(df, :select, [out_df]) + end + + @doc """ + Picks rows based on a list or series of values. + + ## Examples + + This function must only be used when you need to select rows based + on external values that are not available to the dataframe. For example, + you can pass a list: + + iex> df = Explorer.DataFrame.new(col1: ["a", "b", "c"], col2: [1, 2, 3]) + iex> Explorer.DataFrame.mask(df, [false, true, false]) + #Explorer.DataFrame< + Polars[1 x 2] + col1 string ["b"] + col2 s64 [2] + > + + You must avoid using masks when the masks themselves are computed from + other columns. For example, DO NOT do this: + + iex> df = Explorer.DataFrame.new(col1: ["a", "b", "c"], col2: [1, 2, 3]) + iex> Explorer.DataFrame.mask(df, Explorer.Series.greater(df["col2"], 1)) + #Explorer.DataFrame< + Polars[2 x 2] + col1 string ["b", "c"] + col2 s64 [2, 3] + > + + Instead, do this: + + iex> df = Explorer.DataFrame.new(col1: ["a", "b", "c"], col2: [1, 2, 3]) + iex> Explorer.DataFrame.filter_with(df, fn df -> Explorer.Series.greater(df["col2"], 1) end) + #Explorer.DataFrame< + Polars[2 x 2] + col1 string ["b", "c"] + col2 s64 [2, 3] + > + + The `filter_with/2` version is much more efficient because it doesn't need + to create intermediate series representations to apply the mask. + """ + @doc type: :single + @spec mask(df :: DataFrame.t(), mask :: Series.t() | [boolean()]) :: DataFrame.t() + def mask(df, %Series{} = mask) do + s_len = Series.size(mask) + df_len = n_rows(df) + + case s_len == df_len do + false -> + raise( + ArgumentError, + "size of the mask (#{s_len}) must match number of rows in the dataframe (#{df_len})" + ) + + true -> + Shared.apply_dataframe(df, :mask, [mask]) + end + end + + def mask(df, mask) when is_list(mask), do: mask |> Series.from_list() |> then(&mask(df, &1)) + + @doc """ + Picks rows based on `Explorer.Query`. + + The query is compiled and runs efficiently against the dataframe. + The query must return a boolean expression or a list of boolean expressions. + When a list is returned, they are joined as `and` expressions. + + > #### Notice {: .notice} + > + > This is a macro. You must `require Explorer.DataFrame` before using it. + + Besides element-wise series operations, you can also use window functions + and aggregations inside comparisons. In such cases, grouped dataframes + may have different results than ungrouped ones, because the filtering + is computed withing groups. See examples below. + + See `filter_with/2` for a callback version of this function without + `Explorer.Query`. + + ## Examples + + iex> df = Explorer.DataFrame.new(col1: ["a", "b", "c"], col2: [1, 2, 3]) + iex> Explorer.DataFrame.filter(df, col2 > 2) + #Explorer.DataFrame< + Polars[1 x 2] + col1 string ["c"] + col2 s64 [3] + > + + iex> df = Explorer.DataFrame.new(col1: ["a", "b", "c"], col2: [1, 2, 3]) + iex> Explorer.DataFrame.filter(df, col1 == "b") + #Explorer.DataFrame< + Polars[1 x 2] + col1 string ["b"] + col2 s64 [2] + > + + iex> df = Explorer.DataFrame.new(col1: [5, 4, 3], col2: [1, 2, 3]) + iex> Explorer.DataFrame.filter(df, [col1 > 3, col2 < 3]) + #Explorer.DataFrame< + Polars[2 x 2] + col1 s64 [5, 4] + col2 s64 [1, 2] + > + + Returning a non-boolean expression errors: + + iex> df = Explorer.DataFrame.new(col1: ["a", "b", "c"], col2: [1, 2, 3]) + iex> Explorer.DataFrame.filter(df, cumulative_max(col2)) + ** (ArgumentError) expecting the function to return a boolean LazySeries, but instead it returned a LazySeries of type {:s, 64} + + Which can be addressed by converting it to boolean: + + iex> df = Explorer.DataFrame.new(col1: ["a", "b", "c"], col2: [1, 2, 3]) + iex> Explorer.DataFrame.filter(df, cumulative_max(col2) == 1) + #Explorer.DataFrame< + Polars[1 x 2] + col1 string ["a"] + col2 s64 [1] + > + + ## Grouped examples + + In a grouped dataframe, the aggregation is calculated within each group. + + In the following example we select the flowers of the Iris dataset that have the "petal length" + above the average of each species group. + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.filter(grouped, petal_length > mean(petal_length)) + #Explorer.DataFrame< + Polars[79 x 5] + Groups: ["species"] + sepal_length f64 [4.6, 5.4, 5.0, 4.9, 5.4, ...] + sepal_width f64 [3.1, 3.9, 3.4, 3.1, 3.7, ...] + petal_length f64 [1.5, 1.7, 1.5, 1.5, 1.5, ...] + petal_width f64 [0.2, 0.4, 0.2, 0.1, 0.2, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + > + + """ + @doc type: :single + defmacro filter(df, query) do + quote do + require Explorer.Query + Explorer.DataFrame.filter_with(unquote(df), Explorer.Query.query(unquote(query))) + end + end + + @doc """ + Picks rows based on a callback function. + + The callback receives a lazy dataframe. A lazy dataframe does + not hold any values, instead it stores all operations in order to + execute all filtering performantly. + + This is a callback version of `filter/2`. + + ## Examples + + iex> df = Explorer.DataFrame.new(col1: ["a", "b", "c"], col2: [1, 2, 3]) + iex> Explorer.DataFrame.filter_with(df, &Explorer.Series.greater(&1["col2"], 2)) + #Explorer.DataFrame< + Polars[1 x 2] + col1 string ["c"] + col2 s64 [3] + > + + iex> df = Explorer.DataFrame.new(col1: ["a", "b", "c"], col2: [1, 2, 3]) + iex> Explorer.DataFrame.filter_with(df, fn df -> Explorer.Series.equal(df["col1"], "b") end) + #Explorer.DataFrame< + Polars[1 x 2] + col1 string ["b"] + col2 s64 [2] + > + + ## Grouped examples + + In a grouped dataframe, the aggregation is calculated within each group. + + In the following example we select the flowers of the Iris dataset that have the "petal length" + above the average of each species group. + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.filter_with(grouped, &Explorer.Series.greater(&1["petal_length"], Explorer.Series.mean(&1["petal_length"]))) + #Explorer.DataFrame< + Polars[79 x 5] + Groups: ["species"] + sepal_length f64 [4.6, 5.4, 5.0, 4.9, 5.4, ...] + sepal_width f64 [3.1, 3.9, 3.4, 3.1, 3.7, ...] + petal_length f64 [1.5, 1.7, 1.5, 1.5, 1.5, ...] + petal_width f64 [0.2, 0.4, 0.2, 0.1, 0.2, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + > + """ + @doc type: :single + @spec filter_with( + df :: DataFrame.t(), + callback_or_lazy_series_or_list :: + (Explorer.Backend.QueryFrame.t() -> Series.lazy_t() | [Series.lazy_t()]) + | Series.lazy_t() + | [Series.lazy_t()] + ) :: DataFrame.t() + def filter_with(df, fun) when is_function(fun, 1) do + filter = + df + |> Explorer.Query.new() + |> fun.() + + filter_with(df, filter) + end + + def filter_with(df, filter) do + case filter do + %Series{dtype: :boolean, data: %LazySeries{} = data} -> + Shared.apply_dataframe(df, :filter_with, [df, data]) + + %Series{dtype: dtype, data: %LazySeries{}} -> + raise ArgumentError, + "expecting the function to return a boolean LazySeries, " <> + "but instead it returned a LazySeries of type " <> + inspect(dtype) + + [] -> + df + + [%Series{dtype: :boolean, data: %LazySeries{}} | _rest] = lazy_series -> + first_non_boolean = + Enum.find(lazy_series, &(!match?(%Series{dtype: :boolean, data: %LazySeries{}}, &1))) + + if is_nil(first_non_boolean) do + series = Enum.reduce(lazy_series, &Explorer.Backend.LazySeries.binary_and(&2, &1)) + + Shared.apply_dataframe(df, :filter_with, [df, series.data]) + else + filter_without_boolean_series_error(first_non_boolean) + end + + other -> + filter_without_boolean_series_error(other) + end + end + + defp filter_without_boolean_series_error(term) do + raise ArgumentError, + "expecting the function to return a single or a list of boolean LazySeries, " <> + "but instead it contains:\n#{inspect(term)}" + end + + @doc """ + Creates or modifies columns based on `Explorer.Query`. + + The query is compiled and runs efficiently against the dataframe. + New variables overwrite existing variables of the same name. + Column names are coerced from atoms to strings. + + > #### Notice {: .notice} + > + > This is a macro. You must `require Explorer.DataFrame` before using it. + + Besides element-wise series operations, you can also use window functions + and aggregations inside mutations. In such cases, grouped dataframes + may have different results than ungrouped ones, because the mutation + is computed withing groups. See examples below. + + See `mutate_with/3` for a callback version of this function without + `Explorer.Query`. If your mutation cannot be expressed with queries, + you may compute the values using the `Explorer.Series` API directly + and then add it to the dataframe using `put/3`. + + ## Options + + * `keep` - Controls which columns should be kept in the resulting dataframe. + Supported options for keep are: + + * `:all` - Retains all columns from the input dataframe (default). + * `:none` - Retains only the columns created by the mutation (and + grouping columns if operating on a grouped DataFrame). + + > #### Notice {: .notice} + > + > You will need to wrap your mutations in `[]` in order + > to use the `:keep` option. + + ## Examples + + Mutations are useful to add or modify columns in your dataframe: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3]) + iex> Explorer.DataFrame.mutate(df, c: b + 1) + #Explorer.DataFrame< + Polars[3 x 3] + a string ["a", "b", "c"] + b s64 [1, 2, 3] + c s64 [2, 3, 4] + > + + It's also possible to overwrite existing columns: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3]) + iex> Explorer.DataFrame.mutate(df, a: b * 2) + #Explorer.DataFrame< + Polars[3 x 2] + a s64 [2, 4, 6] + b s64 [1, 2, 3] + > + + Scalar values are repeated to fill the series: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3]) + iex> Explorer.DataFrame.mutate(df, a: 4) + #Explorer.DataFrame< + Polars[3 x 2] + a s64 [4, 4, 4] + b s64 [1, 2, 3] + > + + It's also possible to use functions from the Series module, like `Explorer.Series.window_sum/3`: + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3]) + iex> Explorer.DataFrame.mutate(df, b: window_sum(a, 2)) + #Explorer.DataFrame< + Polars[3 x 2] + a s64 [1, 2, 3] + b s64 [1, 3, 5] + > + + Alternatively, all of the above works with a map instead of a keyword list: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3]) + iex> Explorer.DataFrame.mutate(df, %{"c" => cast(b, {:f, 64})}) + #Explorer.DataFrame< + Polars[3 x 3] + a string ["a", "b", "c"] + b s64 [1, 2, 3] + c f64 [1.0, 2.0, 3.0] + > + + Using the `:keep` option to retain only new columns: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3]) + iex> Explorer.DataFrame.mutate(df, [c: b + 1], keep: :none) + #Explorer.DataFrame< + Polars[3 x 1] + c s64 [2, 3, 4] + > + + ## Grouped examples + + Mutations in grouped dataframes takes the context of the group. + This enables some aggregations to be made considering each group. It's almost like `summarise/2`, + but repeating the results for each member in the group. + For example, if we want to count how many elements of a given group, we can add a new + column with that aggregation: + + iex> df = Explorer.DataFrame.new(id: ["a", "a", "b"], b: [1, 2, 3]) + iex> grouped = Explorer.DataFrame.group_by(df, :id) + iex> Explorer.DataFrame.mutate(grouped, count: count(b)) + #Explorer.DataFrame< + Polars[3 x 3] + Groups: ["id"] + id string ["a", "a", "b"] + b s64 [1, 2, 3] + count u32 [2, 2, 1] + > + + In case we want to get the average size of the petal length from the Iris dataset, we can: + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.mutate(grouped, petal_length_avg: mean(petal_length)) + #Explorer.DataFrame< + Polars[150 x 6] + Groups: ["species"] + sepal_length f64 [5.1, 4.9, 4.7, 4.6, 5.0, ...] + sepal_width f64 [3.5, 3.0, 3.2, 3.1, 3.6, ...] + petal_length f64 [1.4, 1.4, 1.3, 1.5, 1.4, ...] + petal_width f64 [0.2, 0.2, 0.2, 0.2, 0.2, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + petal_length_avg f64 [1.464, 1.464, 1.464, 1.464, 1.464, ...] + > + + We can also use the `keep` option on grouped dataframes: + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.mutate(grouped, [petal_length_avg: mean(petal_length)], keep: :none) + #Explorer.DataFrame< + Polars[150 x 2] + Groups: ["species"] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + petal_length_avg f64 [1.464, 1.464, 1.464, 1.464, 1.464, ...] + > + """ + @doc type: :single + defmacro mutate(df, mutations, opts \\ []) do + quote do + require Explorer.Query + + Explorer.DataFrame.mutate_with( + unquote(df), + Explorer.Query.query(unquote(mutations)), + unquote(opts) + ) + end + end + + @doc """ + Creates or modifies columns using a callback function and an + optional `keep` argument. + + The callback receives a lazy dataframe. A lazy dataframe doesn't + hold any values, instead it stores all operations in order to + execute all mutations performantly. + + This is a callback version of `mutate/3`. If your mutation + cannot be expressed with lazy dataframes, you may compute the + values using the `Explorer.Series` API directly and then add + it to the dataframe using `put/3`. + + ## Options + + * `keep` - Controls which columns should be kept in the resulting dataframe. + Supported options for keep are: + + * `:all` - Retains all columns from the input dataframe (default). + * `:none` - Retains only the columns created by the mutation (and + grouping columns if operating on a grouped DataFrame). + + ## Examples + + Here is an example of a new column that sums the value of two other columns: + + iex> df = Explorer.DataFrame.new(a: [4, 5, 6], b: [1, 2, 3]) + iex> Explorer.DataFrame.mutate_with(df, &[c: Explorer.Series.add(&1["a"], &1["b"])]) + #Explorer.DataFrame< + Polars[3 x 3] + a s64 [4, 5, 6] + b s64 [1, 2, 3] + c s64 [5, 7, 9] + > + + You can overwrite existing columns as well: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "c"], b: [1, 2, 3]) + iex> Explorer.DataFrame.mutate_with(df, &[b: Explorer.Series.pow(&1["b"], 2)]) + #Explorer.DataFrame< + Polars[3 x 2] + a string ["a", "b", "c"] + b s64 [1, 4, 9] + > + + It's possible to "reuse" a variable for different computations: + + iex> df = Explorer.DataFrame.new(a: [4, 5, 6], b: [1, 2, 3]) + iex> Explorer.DataFrame.mutate_with(df, fn ldf -> + iex> c = Explorer.Series.add(ldf["a"], ldf["b"]) + iex> [c: c, d: Explorer.Series.window_sum(c, 2)] + iex> end) + #Explorer.DataFrame< + Polars[3 x 4] + a s64 [4, 5, 6] + b s64 [1, 2, 3] + c s64 [5, 7, 9] + d s64 [5, 12, 16] + > + + ## Grouped examples + + Mutations in grouped dataframes takes the context of the group. + For example, if we want to count how many elements of a given group, + we can add a new column with that aggregation: + + iex> df = Explorer.DataFrame.new(id: ["a", "a", "b"], b: [1, 2, 3]) + iex> grouped = Explorer.DataFrame.group_by(df, :id) + iex> Explorer.DataFrame.mutate_with(grouped, &[count: Explorer.Series.count(&1["b"])]) + #Explorer.DataFrame< + Polars[3 x 3] + Groups: ["id"] + id string ["a", "a", "b"] + b s64 [1, 2, 3] + count u32 [2, 2, 1] + > + + ## Examples with the `keep` option + + Here is an example of a new column that sums the value of two + other columns: + + iex> df = Explorer.DataFrame.new(a: [4, 5, 6], b: [1, 2, 3]) + iex> Explorer.DataFrame.mutate_with(df, &[c: Explorer.Series.add(&1["a"], &1["b"])], keep: :all) + #Explorer.DataFrame< + Polars[3 x 3] + a s64 [4, 5, 6] + b s64 [1, 2, 3] + c s64 [5, 7, 9] + > + + Note that `keep: :all` is the default behavior. + + Using the `:keep` option to retain only new columns: + + iex> df = Explorer.DataFrame.new(a: [4, 5, 6], b: [1, 2, 3]) + iex> Explorer.DataFrame.mutate_with(df, &[c: Explorer.Series.add(&1["a"], &1["b"])], keep: :none) + #Explorer.DataFrame< + Polars[3 x 1] + c s64 [5, 7, 9] + > + + When using `keep: :none` on a grouped DataFrame, the grouping + columns are retained along with the newly created columns: + + iex> df = Explorer.DataFrame.new(name: ["a", "a", "b", "b"], a: [1, 2, 3, 4], b: [5, 6, 7, 8]) + iex> grouped = Explorer.DataFrame.group_by(df, :name) + iex> Explorer.DataFrame.mutate_with(grouped, &[ab_sum: Explorer.Series.sum(Explorer.Series.add(&1["a"], &1["b"]))], keep: :none) + #Explorer.DataFrame< + Polars[4 x 2] + Groups: ["name"] + name string ["a", "a", "b", "b"] + ab_sum s64 [14, 14, 22, 22] + > + + Note that the `name` column is retained because it's the + grouping column, even though `keep: :none` is specified. + The `a` and `b` columns are dropped, and only the new `ab_sum` + column is added. + """ + @doc type: :single + @spec mutate_with( + df :: DataFrame.t(), + callback_or_column_pairs :: + (Explorer.Backend.QueryFrame.t() -> column_pairs(Series.lazy_t())) + | column_pairs(Series.lazy_t()), + opts :: keyword() + ) :: DataFrame.t() + def mutate_with(df, query_or_fun, opts \\ []) + + def mutate_with(%DataFrame{} = df, fun, opts) when is_function(fun, 1) and is_list(opts) do + column_pairs = + df + |> Explorer.Query.new() + |> fun.() + + mutate_with(df, column_pairs, opts) + end + + def mutate_with(%DataFrame{} = df, column_pairs, opts) + when is_column_pairs(column_pairs) and is_list(opts) do + keep = Keyword.get(opts, :keep, :all) + + unless keep in [:all, :none] do + raise ArgumentError, "Invalid value for :keep option. Allowed values are :all or :none." + end + + column_pairs = to_column_pairs(df, column_pairs, &query_to_series!/1) + + new_dtypes = + for {column_name, series} <- column_pairs, into: %{} do + {column_name, series.dtype} + end + + mut_names = Enum.map(column_pairs, &elem(&1, 0)) + new_names = Enum.uniq(df.names ++ mut_names) + out_df = out_df(df, new_names, Map.merge(df.dtypes, new_dtypes)) + + column_pairs = + for {name, %Series{data: data} = series} <- column_pairs do + case data do + %LazySeries{} -> {name, data} + _ -> {name, series} + end + end + + full_df = Shared.apply_dataframe(df, :mutate_with, [out_df, column_pairs]) + + case keep do + :all -> + full_df + + :none -> + group_names = df.groups + selected_columns = group_names ++ (mut_names -- group_names) + Explorer.DataFrame.select(full_df, selected_columns) + end + end + + defp query_to_series!(%Series{} = series), do: series + + defp query_to_series!(list) when is_list(list) do + raise ArgumentError, + "expecting a lazy series or scalar value, but instead got a list. " <> + "consider using `Explorer.Series.from_list/2` to create a `Series`, " <> + "and then `Explorer.DataFrame.put/3` to add the series to your dataframe." + end + + defp query_to_series!(scalar) do + lazy_s = query_to_lazy_series!(scalar) + Explorer.Backend.Series.new(lazy_s, lazy_s.dtype) + end + + defp query_to_lazy_series!(scalar) do + case scalar do + %Series{data: %LazySeries{}} = series -> + series.data + + nil -> + LazySeries.unbacked(:lazy, [nil], :null) + + number when is_number(number) -> + dtype = if is_integer(number), do: {:s, 64}, else: {:f, 64} + LazySeries.unbacked(:lazy, [number], dtype) + + string when is_binary(string) -> + LazySeries.unbacked(:lazy, [string], :string) + + boolean when is_boolean(boolean) -> + LazySeries.unbacked(:lazy, [boolean], :boolean) + + date = %Date{} -> + LazySeries.unbacked(:lazy, [date], :date) + + naive_datetime = %NaiveDateTime{} -> + LazySeries.unbacked(:lazy, [naive_datetime], {:naive_datetime, :microsecond}) + + datetime = %DateTime{time_zone: time_zone} -> + LazySeries.unbacked(:lazy, [datetime], {:datetime, :microsecond, time_zone}) + + duration = %Explorer.Duration{precision: precision} -> + LazySeries.unbacked(:lazy, [duration], {:duration, precision}) + + map = %{} when not is_struct(map) -> + {series_list, dtype_list} = + Enum.reduce(map, {[], []}, fn {name, series}, {sl, dl} -> + lazy_series = query_to_lazy_series!(series) + name = if is_atom(name), do: Atom.to_string(name), else: name + {[{name, lazy_series} | sl], [{name, lazy_series.dtype} | dl]} + end) + + map = Enum.into(series_list, %{}) + dtype_list = Enum.sort(dtype_list) + LazySeries.unbacked(:lazy, [map], {:struct, dtype_list}) + + other -> + raise ArgumentError, + "expecting a lazy series or scalar value, but instead got #{inspect(other)}" + end + end + + @doc """ + Creates or modifies a single column. + + This is a simplified way to add or modify one column, + accepting a series, tensor, or a list. + + If you are computing a series, it is preferrable to use + `mutate/2` or `mutate_with/2` to compute the series and + modify it in a single step, as it is more powerful and + it handles both expressions and scalar values accordingly. + + If you are passing tensors or lists, they will be automatically + converted to a series. By default, the new series will have the + same dtype as the existing series, unless the `:dtype` option + is given. If there is no existing series, one is inferred from + the tensor/list. + + ## Examples + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3]) + iex> Explorer.DataFrame.put(df, :b, Explorer.Series.transform(df[:a], fn n -> n * 2 end)) + #Explorer.DataFrame< + Polars[3 x 2] + a s64 [1, 2, 3] + b s64 [2, 4, 6] + > + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3]) + iex> Explorer.DataFrame.put(df, :b, Explorer.Series.from_list([4, 5, 6])) + #Explorer.DataFrame< + Polars[3 x 2] + a s64 [1, 2, 3] + b s64 [4, 5, 6] + > + + ## Grouped examples + + If the dataframe is grouped, `put/3` is going to ignore the groups. + So the series must be of the same size of the entire dataframe. + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3]) + iex> grouped = Explorer.DataFrame.group_by(df, "a") + iex> series = Explorer.Series.from_list([9, 8, 7]) + iex> Explorer.DataFrame.put(grouped, :b, series) + #Explorer.DataFrame< + Polars[3 x 2] + Groups: ["a"] + a s64 [1, 2, 3] + b s64 [9, 8, 7] + > + + ## Tensor examples + + You can also put tensors into the dataframe: + + iex> df = Explorer.DataFrame.new([]) + iex> Explorer.DataFrame.put(df, :a, Nx.tensor([1, 2, 3])) + #Explorer.DataFrame< + Polars[3 x 1] + a s64 [1, 2, 3] + > + + You can specify which dtype the tensor represents. + For example, a tensor of s64 represents integers + by default, but it may also represent timestamps + in microseconds from the Unix epoch: + + iex> df = Explorer.DataFrame.new([]) + iex> Explorer.DataFrame.put(df, :a, Nx.tensor([1, 2, 3]), dtype: {:naive_datetime, :microsecond}) + #Explorer.DataFrame< + Polars[3 x 1] + a naive_datetime[μs] [1970-01-01 00:00:00.000001, 1970-01-01 00:00:00.000002, 1970-01-01 00:00:00.000003] + > + + If there is already a column where we want to place the tensor, + the column dtype will be automatically used, this means that + updating dataframes in place while preserving their types is + straight-forward: + + iex> df = Explorer.DataFrame.new(a: [~N[1970-01-01 00:00:00]]) + iex> Explorer.DataFrame.put(df, :a, Nx.tensor(529550625987654)) + #Explorer.DataFrame< + Polars[1 x 1] + a naive_datetime[μs] [1986-10-13 01:23:45.987654] + > + + This is particularly useful for categorical columns: + + iex> cat = Explorer.Series.from_list(["foo", "bar", "baz"], dtype: :category) + iex> df = Explorer.DataFrame.new(a: cat) + iex> Explorer.DataFrame.put(df, :a, Nx.tensor([2, 1, 0])) + #Explorer.DataFrame< + Polars[3 x 1] + a category ["baz", "bar", "foo"] + > + + On the other hand, if you try to put a floating tensor on + an integer column, an error will be raised unless a dtype + or `dtype: :infer` is given: + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3]) + iex> Explorer.DataFrame.put(df, :a, Nx.tensor(1.0, type: :f64)) + ** (ArgumentError) dtype {:s, 64} expects a tensor of type {:s, 64} but got type {:f, 64} + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3]) + iex> Explorer.DataFrame.put(df, :a, Nx.tensor(1.0, type: :f64), dtype: {:f, 64}) + #Explorer.DataFrame< + Polars[3 x 1] + a f64 [1.0, 1.0, 1.0] + > + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3]) + iex> Explorer.DataFrame.put(df, :a, Nx.tensor(1.0, type: :f64), dtype: :infer) + #Explorer.DataFrame< + Polars[3 x 1] + a f64 [1.0, 1.0, 1.0] + > + + ## List examples + + Similar to tensors, we can also put lists in the dataframe: + + iex> df = Explorer.DataFrame.new([]) + iex> Explorer.DataFrame.put(df, :a, [1, 2, 3]) + #Explorer.DataFrame< + Polars[3 x 1] + a s64 [1, 2, 3] + > + + The same considerations as above apply. + """ + @doc type: :single + @spec put(DataFrame.t(), column_name(), Series.t() | Nx.Tensor.t() | list()) :: DataFrame.t() + def put(df, column_name, series_or_tensor_or_list, opts \\ []) + + def put(%DataFrame{} = df, column_name, %Series{} = series, opts) + when is_column_name(column_name) do + Keyword.validate!(opts, []) + name = to_column_name(column_name) + new_names = append_unless_present(df.names, name) + + out_df = out_df(df, new_names, Map.put(df.dtypes, name, series.dtype)) + Shared.apply_dataframe(df, :put, [out_df, name, series]) + end + + def put(%DataFrame{} = df, column_name, tensor, opts) + when is_column_name(column_name) and is_struct(tensor, Nx.Tensor) do + put(df, column_name, :from_tensor, tensor, opts) + end + + def put(%DataFrame{} = df, column_name, list, opts) + when is_column_name(column_name) and is_list(list) do + put(df, column_name, :from_list, list, opts) + end + + defp put(%DataFrame{} = df, column_name, fun, arg, opts) when is_column_name(column_name) do + opts = Keyword.validate!(opts, [:dtype]) + name = to_column_name(column_name) + dtype = opts[:dtype] + + if dtype == nil and is_map_key(df.dtypes, name) do + put(df, name, Series.replace(pull(df, name), arg), []) + else + backend = df_backend_to_s_backend(df.data.__struct__) + + opts = + if dtype == nil or dtype == :infer do + [backend: backend] + else + [dtype: Shared.normalise_dtype!(dtype), backend: backend] + end + + put(df, name, apply(Series, fun, [arg, opts]), []) + end + end + + defp df_backend_to_s_backend(backend) do + backend_df_string = Atom.to_string(backend) + backend_string = binary_part(backend_df_string, 0, byte_size(backend_df_string) - 10) + String.to_atom(backend_string) + end + + defp append_unless_present([name | tail], name), do: [name | tail] + defp append_unless_present([head | tail], name), do: [head | append_unless_present(tail, name)] + defp append_unless_present([], name), do: [name] + + @doc """ + Sorts rows by columns using `Explorer.Query`. + + > #### Notice {: .notice} + > + > This is a macro. You must `require Explorer.DataFrame` before using it. + + See `sort_with/2` for a callback version of this function without + `Explorer.Query`. + + ## Options + + * `:nils` - `:first` or `:last`. + By default it is `:last` if direction is `:asc`, and `:first` otherwise. + + * `:parallel` - boolean. + Whether to parallelize the sorting. + By default it is `true`. + + Parallel sort isn't available on certain lazy operations. + In those situations this option is ignored. + + * `:stable` - boolean. + Determines if the sorting is stable (ties are guaranteed to maintain their order) or not. + Unstable sorting may be more performant. + By default it is `false`. + + ## Examples + + A single column name will sort ascending by that column: + + iex> df = Explorer.DataFrame.new(a: ["b", "c", "a"], b: [1, 2, 3]) + iex> Explorer.DataFrame.sort_by(df, a) + #Explorer.DataFrame< + Polars[3 x 2] + a string ["a", "b", "c"] + b s64 [3, 1, 2] + > + + You can also sort descending: + + iex> df = Explorer.DataFrame.new(a: ["b", "c", "a"], b: [1, 2, 3]) + iex> Explorer.DataFrame.sort_by(df, desc: a) + #Explorer.DataFrame< + Polars[3 x 2] + a string ["c", "b", "a"] + b s64 [2, 1, 3] + > + + You can specify how `nil`s are sorted: + + iex> df = Explorer.DataFrame.new(a: ["b", "c", nil, "a"]) + iex> Explorer.DataFrame.sort_by(df, [desc: a], nils: :first) + #Explorer.DataFrame< + Polars[4 x 1] + a string [nil, "c", "b", "a"] + > + + Sorting by more than one column sorts them in the order they are entered: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.sort_by(df, asc: total, desc: country) + #Explorer.DataFrame< + Polars[1094 x 10] + year s64 [2010, 2010, 2011, 2011, 2012, ...] + country string ["NIUE", "TUVALU", "TUVALU", "NIUE", "NIUE", ...] + total s64 [1, 2, 2, 2, 2, ...] + solid_fuel s64 [0, 0, 0, 0, 0, ...] + liquid_fuel s64 [1, 2, 2, 2, 2, ...] + gas_fuel s64 [0, 0, 0, 0, 0, ...] + cement s64 [0, 0, 0, 0, 0, ...] + gas_flaring s64 [0, 0, 0, 0, 0, ...] + per_capita f64 [0.52, 0.0, 0.0, 1.04, 1.04, ...] + bunker_fuels s64 [0, 0, 0, 0, 0, ...] + > + + ## Grouped examples + + When used in a grouped dataframe, sort_by is going to sort each group individually and + then return the entire dataframe with the existing groups. If one of the sort_by columns + is also a group, the sorting for that column is not going to work. It is necessary to + first summarise the desired column and then sort_by it. + + Here is an example using the Iris dataset. We group by species and then we try to sort + the dataframe by species and petal length, but only "petal length" is taken into account + because "species" is a group. + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.sort_by(grouped, desc: species, asc: sepal_width) + #Explorer.DataFrame< + Polars[150 x 5] + Groups: ["species"] + sepal_length f64 [4.5, 4.4, 4.9, 4.8, 4.3, ...] + sepal_width f64 [2.3, 2.9, 3.0, 3.0, 3.0, ...] + petal_length f64 [1.3, 1.4, 1.4, 1.4, 1.1, ...] + petal_width f64 [0.3, 0.2, 0.2, 0.1, 0.1, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + > + """ + @doc type: :single + defmacro sort_by(df, query, opts \\ []) do + quote do + require Explorer.Query + + Explorer.DataFrame.sort_with( + unquote(df), + Explorer.Query.query(unquote(query)), + unquote(opts) + ) + end + end + + @deprecated "Use sort_by/3 instead" + @doc false + defmacro arrange(df, query, opts \\ []) do + quote do + Explorer.DataFrame.sort_by(unquote(df), unquote(query), unquote(opts)) + end + end + + @doc """ + Sorts rows by columns using a callback function. + + The callback receives a lazy dataframe which stores + operations instead of values for efficient sorting. + + This is a callback version of `sort_by/2`. + + ## Options + + * `:nils` - `:first` or `:last`. + By default it is `:last` if direction is `:asc`, and `:first` otherwise. + + * `:parallel` - boolean. + Whether to parallelize the sorting. + By default it is `true`. + + Parallel sort isn't available on certain lazy operations. + In those situations this option is ignored. + + * `:stable` - boolean. + Determines if the sorting is stable (ties are guaranteed to maintain their order) or not. + Unstable sorting may be more performant. + By default it is `false`. + + ## Examples + + A single column name will sort ascending by that column: + + iex> df = Explorer.DataFrame.new(a: ["b", "c", "a"], b: [1, 2, 3]) + iex> Explorer.DataFrame.sort_with(df, &(&1["a"])) + #Explorer.DataFrame< + Polars[3 x 2] + a string ["a", "b", "c"] + b s64 [3, 1, 2] + > + + You can also sort descending: + + iex> df = Explorer.DataFrame.new(a: ["b", "c", "a"], b: [1, 2, 3]) + iex> Explorer.DataFrame.sort_with(df, &[desc: &1["a"]]) + #Explorer.DataFrame< + Polars[3 x 2] + a string ["c", "b", "a"] + b s64 [2, 1, 3] + > + + You can specify how `nil`s are sorted: + + iex> df = Explorer.DataFrame.new(a: ["b", "c", nil, "a"]) + iex> Explorer.DataFrame.sort_with(df, &[desc: &1["a"]], nils: :first) + #Explorer.DataFrame< + Polars[4 x 1] + a string [nil, "c", "b", "a"] + > + + Sorting by more than one column sorts them in the order they are entered: + + iex> df = Explorer.DataFrame.new(a: [3, 1, 3], b: [2, 1, 3]) + iex> Explorer.DataFrame.sort_with(df, &[desc: &1["a"], asc: &1["b"]]) + #Explorer.DataFrame< + Polars[3 x 2] + a s64 [3, 3, 1] + b s64 [2, 3, 1] + > + + ## Grouped examples + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.sort_with(grouped, &[desc: &1["species"], asc: &1["sepal_width"]]) + #Explorer.DataFrame< + Polars[150 x 5] + Groups: ["species"] + sepal_length f64 [4.5, 4.4, 4.9, 4.8, 4.3, ...] + sepal_width f64 [2.3, 2.9, 3.0, 3.0, 3.0, ...] + petal_length f64 [1.3, 1.4, 1.4, 1.4, 1.1, ...] + petal_width f64 [0.3, 0.2, 0.2, 0.1, 0.1, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + > + """ + @doc type: :single + @type sort_callback_result :: + Series.lazy_t() | [Series.lazy_t()] | [{:asc | :desc, Series.lazy_t()}] + @spec sort_with( + df :: DataFrame.t(), + callback_or_result :: + (Explorer.Backend.QueryFrame.t() -> sort_callback_result()) | sort_callback_result(), + opts :: [nils: :first | :last, stable: boolean()] + ) :: DataFrame.t() + def sort_with(df, fun, opts \\ []) + + def sort_with(%DataFrame{} = df, fun, opts) when is_function(fun, 1) do + sortable = + df + |> Explorer.Query.new() + |> fun.() + + sort_with(df, sortable, opts) + end + + def sort_with(%DataFrame{} = df, sortable, opts) do + [_descending? | opts] = Shared.validate_sort_options!(opts) + + dir_and_lazy_series_pairs = + sortable + |> List.wrap() + |> Enum.map(fn + {dir, %Series{data: %LazySeries{} = lazy_series}} when dir in [:asc, :desc] -> + {dir, lazy_series} + + {wrong_dir, %Series{data: %LazySeries{}}} -> + raise "expecting a valid direction, which is :asc or :desc, got: #{inspect(wrong_dir)}" + + {_, other} -> + raise "expecting a lazy series, got: #{inspect(other)}" + + %Series{data: %LazySeries{} = lazy_series} -> + {:asc, lazy_series} + + other -> + raise "not a valid lazy series or sort_by instruction: #{inspect(other)}" + end) + + Shared.apply_dataframe(df, :sort_with, [df, dir_and_lazy_series_pairs] ++ opts) + end + + @deprecated "Use sort_with/3 instead" + @doc false + def arrange_with(df, fun, opts \\ []), do: sort_with(df, fun, opts) + + @doc """ + Takes distinct rows by a selection of columns. + + Distinct is not affected by groups, although groups are kept in the + columns selection if `keep_all` option is false (the default). + + ## Options + + * `:keep_all` - If set to `true`, keep all columns. Default is `false`. + + ## Examples + + By default will return unique values of the requested columns: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.distinct(df, ["year", "country"]) + #Explorer.DataFrame< + Polars[1094 x 2] + year s64 [2010, 2010, 2010, 2010, 2010, ...] + country string ["AFGHANISTAN", "ALBANIA", "ALGERIA", "ANDORRA", "ANGOLA", ...] + > + + If `keep_all` is set to `true`, then the first value of each column not in the requested + columns will be returned: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.distinct(df, ["year", "country"], keep_all: true) + #Explorer.DataFrame< + Polars[1094 x 10] + year s64 [2010, 2010, 2010, 2010, 2010, ...] + country string ["AFGHANISTAN", "ALBANIA", "ALGERIA", "ANDORRA", "ANGOLA", ...] + total s64 [2308, 1254, 32500, 141, 7924, ...] + solid_fuel s64 [627, 117, 332, 0, 0, ...] + liquid_fuel s64 [1601, 953, 12381, 141, 3649, ...] + gas_fuel s64 [74, 7, 14565, 0, 374, ...] + cement s64 [5, 177, 2598, 0, 204, ...] + gas_flaring s64 [0, 0, 2623, 0, 3697, ...] + per_capita f64 [0.08, 0.43, 0.9, 1.68, 0.37, ...] + bunker_fuels s64 [9, 7, 663, 0, 321, ...] + > + + A callback on the dataframe's names can be passed instead of a list (like `select/2`): + + iex> df = Explorer.DataFrame.new(x1: [1, 3, 3], x2: ["a", "c", "c"], y1: [1, 2, 3]) + iex> Explorer.DataFrame.distinct(df, &String.starts_with?(&1, "x")) + #Explorer.DataFrame< + Polars[2 x 2] + x1 s64 [1, 3] + x2 string ["a", "c"] + > + + If the dataframe has groups, then the columns of each group will be added to the distinct columns: + + iex> df = Explorer.DataFrame.new(x1: [1, 3, 3], x2: ["a", "c", "c"], y1: [1, 2, 3]) + iex> df = Explorer.DataFrame.group_by(df, "x1") + iex> Explorer.DataFrame.distinct(df, ["x2"]) + #Explorer.DataFrame< + Polars[2 x 2] + Groups: ["x1"] + x1 s64 [1, 3] + x2 string ["a", "c"] + > + + """ + @doc type: :single + @spec distinct(df :: DataFrame.t(), columns :: columns(), opts :: Keyword.t()) :: DataFrame.t() + def distinct(df, columns \\ .., opts \\ []) + + def distinct(df, columns, opts) do + opts = Keyword.validate!(opts, keep_all: false) + + columns = to_existing_columns(df, columns) + + if columns != [] do + out_df = + if opts[:keep_all] do + df + else + groups = df.groups + keep = if groups == [], do: columns, else: Enum.uniq(groups ++ columns) + out_df(df, keep, Map.take(df.dtypes, keep)) + end + + Shared.apply_dataframe(df, :distinct, [out_df, columns]) + else + df + end + end + + @doc """ + Drop nil values. + + Optionally accepts a subset of columns. + + ## Examples + + To drop nils on all columns: + + iex> df = Explorer.DataFrame.new(a: [1, 2, nil], b: [1, nil, 3]) + iex> Explorer.DataFrame.drop_nil(df) + #Explorer.DataFrame< + Polars[1 x 2] + a s64 [1] + b s64 [1] + > + + To drop nils on a single column: + + iex> df = Explorer.DataFrame.new(a: [1, 2, nil], b: [1, nil, 3]) + iex> Explorer.DataFrame.drop_nil(df, :a) + #Explorer.DataFrame< + Polars[2 x 2] + a s64 [1, 2] + b s64 [1, nil] + > + + To drop some columns: + + iex> df = Explorer.DataFrame.new(a: [1, 2, nil], b: [1, nil, 3], c: [nil, 5, 6]) + iex> Explorer.DataFrame.drop_nil(df, [:a, :c]) + #Explorer.DataFrame< + Polars[1 x 3] + a s64 [2] + b s64 [nil] + c s64 [5] + > + + Ranges, regexes, and functions are also accepted in column names, as in `select/2`. + """ + @doc type: :single + @spec drop_nil(df :: DataFrame.t(), column() | columns()) :: + DataFrame.t() + def drop_nil(df, columns_or_column \\ ..) + + def drop_nil(df, column) when is_column(column), do: drop_nil(df, [column]) + + def drop_nil(df, []), do: df + + def drop_nil(df, columns) do + columns = to_existing_columns(df, columns) + Shared.apply_dataframe(df, :drop_nil, [columns]) + end + + @doc """ + Relocates columns. + + Change column order within a DataFrame. The `before` and `after` options are mutually exclusive. + Providing no options will relocate the columns to beginning of the DataFrame. + + ## Options + + * `:before` - Specifies to relocate before the given column. + It can be an index or a column name. + + * `:after` - Specifies to relocate after the given column. + It can be an index or a column name. + + ## Examples + + Relocate a single column + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "a"], b: [1, 3, 1], c: [nil, 5, 6]) + iex> Explorer.DataFrame.relocate(df, "a", after: "c") + #Explorer.DataFrame< + Polars[3 x 3] + b s64 [1, 3, 1] + c s64 [nil, 5, 6] + a string ["a", "b", "a"] + > + + Relocate (and reorder) multiple columns to the beginning + + iex> df = Explorer.DataFrame.new(a: [1, 2], b: [5.1, 5.2], c: [4, 5], d: ["yes", "no"]) + iex> Explorer.DataFrame.relocate(df, ["d", 1], before: 0) + #Explorer.DataFrame< + Polars[2 x 4] + d string ["yes", "no"] + b f64 [5.1, 5.2] + a s64 [1, 2] + c s64 [4, 5] + > + + Relocate before another column + + iex> df = Explorer.DataFrame.new(a: [1, 2], b: [5.1, 5.2], c: [4, 5], d: ["yes", "no"]) + iex> Explorer.DataFrame.relocate(df, ["a", "c"], before: "b") + #Explorer.DataFrame< + Polars[2 x 4] + a s64 [1, 2] + c s64 [4, 5] + b f64 [5.1, 5.2] + d string ["yes", "no"] + > + """ + + @doc type: :single + @spec relocate( + df :: DataFrame.t(), + columns :: [column()] | column(), + opts :: Keyword.t() + ) :: DataFrame.t() + + def relocate(df, columns_or_column, opts) + + def relocate(df, column, opts) when is_column(column), + do: relocate(df, [column], opts) + + def relocate(df, columns, opts) do + opts = Keyword.validate!(opts, before: nil, after: nil) + + columns = to_existing_columns(df, columns) |> Enum.uniq() + + columns = + case {opts[:before], opts[:after]} do + {before_col, nil} -> + {:before, before_col} + + {nil, after_col} -> + {:after, after_col} + + {before_col, after_col} -> + raise( + ArgumentError, + "only one location must be given. Got both " <> + "before: #{inspect(before_col)} and after: #{inspect(after_col)}" + ) + end + |> relocate_columns(df, columns) + + select(df, columns) + end + + defp relocate_columns({direction, target_column}, df, columns_to_relocate) do + [target_column] = to_existing_columns(df, [target_column]) + + offset = + case direction do + :before -> 0 + :after -> 1 + end + + target_index = Enum.find_index(df.names, fn col -> col == target_column end) + offset + + df.names + |> Enum.split(target_index) + |> Kernel.then(fn {before_cols, after_cols} -> + Enum.reject(before_cols, &(&1 in columns_to_relocate)) ++ + columns_to_relocate ++ Enum.reject(after_cols, &(&1 in columns_to_relocate)) + end) + end + + @doc """ + Renames columns. + + Renaming a column that is also a group is going to rename the group as well. + To apply a function to a subset of columns, see `rename_with/3`. + + ## Examples + + You can pass in a list of new names: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "a"], b: [1, 3, 1]) + iex> Explorer.DataFrame.rename(df, ["c", "d"]) + #Explorer.DataFrame< + Polars[3 x 2] + c string ["a", "b", "a"] + d s64 [1, 3, 1] + > + + Or you can rename individual columns using keyword args: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "a"], b: [1, 3, 1]) + iex> Explorer.DataFrame.rename(df, a: "first") + #Explorer.DataFrame< + Polars[3 x 2] + first string ["a", "b", "a"] + b s64 [1, 3, 1] + > + + Or you can rename individual columns using a map: + + iex> df = Explorer.DataFrame.new(a: ["a", "b", "a"], b: [1, 3, 1]) + iex> Explorer.DataFrame.rename(df, %{"a" => "first"}) + #Explorer.DataFrame< + Polars[3 x 2] + first string ["a", "b", "a"] + b s64 [1, 3, 1] + > + + """ + @doc type: :single + @spec rename( + df :: DataFrame.t(), + names :: column_names() | column_pairs(column_name()) + ) :: + DataFrame.t() + def rename(df, [name | _] = names) when is_column_name(name) do + check_new_names_length!(df, names) + rename(df, Enum.zip(df.names, names)) + end + + def rename(df, names) when is_column_pairs(names) do + case to_column_pairs(df, names, &to_column_name(&1)) do + [] -> + df + + pairs -> + pairs_map = Map.new(pairs) + + if Enum.count(pairs) != map_size(pairs_map), + do: raise(ArgumentError, "duplicate source column for rename") + + old_dtypes = df.dtypes + + for {name, _} <- pairs do + Shared.maybe_raise_column_not_found(df, name) + end + + new_dtypes = + for name <- df.names do + {Map.get(pairs_map, name, name), Map.fetch!(old_dtypes, name)} + end + + new_names = Enum.map(new_dtypes, &elem(&1, 0)) + + new_groups = + for group <- df.groups do + Map.get(pairs_map, group, group) + end + + out_df = out_df(%{df | groups: new_groups}, new_names, Map.new(new_dtypes)) + Shared.apply_dataframe(df, :rename, [out_df, pairs]) + end + end + + defp check_new_names_length!(df, names) do + width = n_columns(df) + n_new_names = length(names) + + if width != n_new_names, + do: + raise( + ArgumentError, + "list of new names must match the number of columns in the dataframe; found " <> + "#{n_new_names} new name(s), but the supplied dataframe has #{width} column(s)" + ) + end + + @doc """ + Renames columns with a function. + + Renaming a column that is also a group is going to rename the group as well. + + ## Examples + + If no columns are specified, it will apply the function to all column names: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.rename_with(df, &String.upcase/1) + #Explorer.DataFrame< + Polars[1094 x 10] + YEAR s64 [2010, 2010, 2010, 2010, 2010, ...] + COUNTRY string ["AFGHANISTAN", "ALBANIA", "ALGERIA", "ANDORRA", "ANGOLA", ...] + TOTAL s64 [2308, 1254, 32500, 141, 7924, ...] + SOLID_FUEL s64 [627, 117, 332, 0, 0, ...] + LIQUID_FUEL s64 [1601, 953, 12381, 141, 3649, ...] + GAS_FUEL s64 [74, 7, 14565, 0, 374, ...] + CEMENT s64 [5, 177, 2598, 0, 204, ...] + GAS_FLARING s64 [0, 0, 2623, 0, 3697, ...] + PER_CAPITA f64 [0.08, 0.43, 0.9, 1.68, 0.37, ...] + BUNKER_FUELS s64 [9, 7, 663, 0, 321, ...] + > + + A callback can be used to filter the column names that will be renamed, similarly to `select/2`: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.rename_with(df, &String.ends_with?(&1, "_fuel"), &String.trim_trailing(&1, "_fuel")) + #Explorer.DataFrame< + Polars[1094 x 10] + year s64 [2010, 2010, 2010, 2010, 2010, ...] + country string ["AFGHANISTAN", "ALBANIA", "ALGERIA", "ANDORRA", "ANGOLA", ...] + total s64 [2308, 1254, 32500, 141, 7924, ...] + solid s64 [627, 117, 332, 0, 0, ...] + liquid s64 [1601, 953, 12381, 141, 3649, ...] + gas s64 [74, 7, 14565, 0, 374, ...] + cement s64 [5, 177, 2598, 0, 204, ...] + gas_flaring s64 [0, 0, 2623, 0, 3697, ...] + per_capita f64 [0.08, 0.43, 0.9, 1.68, 0.37, ...] + bunker_fuels s64 [9, 7, 663, 0, 321, ...] + > + + Or you can just pass in the list of column names you'd like to apply the function to: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.rename_with(df, ["total", "cement"], &String.upcase/1) + #Explorer.DataFrame< + Polars[1094 x 10] + year s64 [2010, 2010, 2010, 2010, 2010, ...] + country string ["AFGHANISTAN", "ALBANIA", "ALGERIA", "ANDORRA", "ANGOLA", ...] + TOTAL s64 [2308, 1254, 32500, 141, 7924, ...] + solid_fuel s64 [627, 117, 332, 0, 0, ...] + liquid_fuel s64 [1601, 953, 12381, 141, 3649, ...] + gas_fuel s64 [74, 7, 14565, 0, 374, ...] + CEMENT s64 [5, 177, 2598, 0, 204, ...] + gas_flaring s64 [0, 0, 2623, 0, 3697, ...] + per_capita f64 [0.08, 0.43, 0.9, 1.68, 0.37, ...] + bunker_fuels s64 [9, 7, 663, 0, 321, ...] + > + + Ranges, regexes, and functions are also accepted in column names, as in `select/2`. + """ + @doc type: :single + @spec rename_with(df :: DataFrame.t(), columns :: columns(), callback :: function()) :: + DataFrame.t() + def rename_with(df, columns \\ .., callback) + + def rename_with(df, .., callback) when is_function(callback) do + df.names + |> Enum.map(callback) + |> then(&rename(df, &1)) + end + + def rename_with(df, columns, callback) when is_function(callback) do + columns = to_existing_columns(df, columns) + renames = for name <- df.names, name in columns, do: {name, callback.(name)} + rename(df, renames) + end + + @doc """ + Turns a set of columns to dummy variables. + + In case the dataframe is using groups, all groups will be removed. + + ## Examples + + To mark a single column as dummy: + + iex> df = Explorer.DataFrame.new(col_x: ["a", "b", "a", "c"], col_y: ["b", "a", "b", "d"]) + iex> Explorer.DataFrame.dummies(df, "col_x") + #Explorer.DataFrame< + Polars[4 x 3] + col_x_a u8 [1, 0, 1, 0] + col_x_b u8 [0, 1, 0, 0] + col_x_c u8 [0, 0, 0, 1] + > + + Or multiple columns: + + iex> df = Explorer.DataFrame.new(col_x: ["a", "b", "a", "c"], col_y: ["b", "a", "b", "d"]) + iex> Explorer.DataFrame.dummies(df, ["col_x", "col_y"]) + #Explorer.DataFrame< + Polars[4 x 6] + col_x_a u8 [1, 0, 1, 0] + col_x_b u8 [0, 1, 0, 0] + col_x_c u8 [0, 0, 0, 1] + col_y_b u8 [1, 0, 1, 0] + col_y_a u8 [0, 1, 0, 0] + col_y_d u8 [0, 0, 0, 1] + > + + Or all string columns: + + iex> df = Explorer.DataFrame.new(num: [1, 2, 3, 4], col_y: ["b", "a", "b", "d"]) + iex> Explorer.DataFrame.dummies(df, fn _name, type -> type == :string end) + #Explorer.DataFrame< + Polars[4 x 3] + col_y_b u8 [1, 0, 1, 0] + col_y_a u8 [0, 1, 0, 0] + col_y_d u8 [0, 0, 0, 1] + > + + Ranges, regexes, and functions are also accepted in column names, as in `select/2`. + """ + @doc type: :single + @spec dummies(df :: DataFrame.t(), column() | columns()) :: + DataFrame.t() + def dummies(df, columns_or_column) + + def dummies(df, column) when is_column(column), do: dummies(df, [column]) + + def dummies(df, columns) do + columns = to_existing_columns(df, columns) + + out_columns = + for column <- columns, + value <- Series.to_list(Series.distinct(df[column])), + do: column <> "_#{value}" + + out_dtypes = for new_column <- out_columns, into: %{}, do: {new_column, {:u, 8}} + + out_df = out_df(%{df | groups: []}, out_columns, out_dtypes) + Shared.apply_dataframe(df, :dummies, [out_df, columns]) + end + + @doc """ + Extracts a single column as a series. + + This is equivalent to `df[field]` for retrieving a single field. + The returned series will have its `:name` field set to the column name. + + ## Examples + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.pull(df, "total") + #Explorer.Series< + Polars[1094] + s64 [2308, 1254, 32500, 141, 7924, 41, 143, 51246, 1150, 684, 106589, 18408, 8366, 451, 7981, 16345, 403, 17192, 30222, 147, 1388, 166, 133, 5802, 1278, 114468, 47, 2237, 12030, 535, 58, 1367, 145806, 152, 152, 72, 141, 19703, 2393248, 20773, 44, 540, 19, 2064, 1900, 5501, 10465, 2102, 30428, 18122, ...] + > + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.pull(df, 2) + #Explorer.Series< + Polars[1094] + s64 [2308, 1254, 32500, 141, 7924, 41, 143, 51246, 1150, 684, 106589, 18408, 8366, 451, 7981, 16345, 403, 17192, 30222, 147, 1388, 166, 133, 5802, 1278, 114468, 47, 2237, 12030, 535, 58, 1367, 145806, 152, 152, 72, 141, 19703, 2393248, 20773, 44, 540, 19, 2064, 1900, 5501, 10465, 2102, 30428, 18122, ...] + > + """ + @doc type: :single + @spec pull(df :: DataFrame.t(), column :: column()) :: Series.t() + def pull(df, column) when is_column(column) do + [column] = to_existing_columns(df, [column]) + pull_existing(df, column) + end + + defp pull_existing(df, column) do + series = Shared.apply_dataframe(df, :pull, [column]) + %{series | name: column} + end + + @doc """ + Subset a continuous set of rows. + + ## Examples + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.slice(df, 1, 2) + #Explorer.DataFrame< + Polars[2 x 10] + year s64 [2010, 2010] + country string ["ALBANIA", "ALGERIA"] + total s64 [1254, 32500] + solid_fuel s64 [117, 332] + liquid_fuel s64 [953, 12381] + gas_fuel s64 [7, 14565] + cement s64 [177, 2598] + gas_flaring s64 [0, 2623] + per_capita f64 [0.43, 0.9] + bunker_fuels s64 [7, 663] + > + + Negative offsets count from the end of the series: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.slice(df, -10, 2) + #Explorer.DataFrame< + Polars[2 x 10] + year s64 [2014, 2014] + country string ["UNITED STATES OF AMERICA", "URUGUAY"] + total s64 [1432855, 1840] + solid_fuel s64 [450047, 2] + liquid_fuel s64 [576531, 1700] + gas_fuel s64 [390719, 25] + cement s64 [11314, 112] + gas_flaring s64 [4244, 0] + per_capita f64 [4.43, 0.54] + bunker_fuels s64 [30722, 251] + > + + If the length would run past the end of the dataframe, the result may be shorter than the length: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.slice(df, -10, 20) + #Explorer.DataFrame< + Polars[10 x 10] + year s64 [2014, 2014, 2014, 2014, 2014, ...] + country string ["UNITED STATES OF AMERICA", "URUGUAY", "UZBEKISTAN", "VANUATU", "VENEZUELA", ...] + total s64 [1432855, 1840, 28692, 42, 50510, ...] + solid_fuel s64 [450047, 2, 1677, 0, 204, ...] + liquid_fuel s64 [576531, 1700, 2086, 42, 28445, ...] + gas_fuel s64 [390719, 25, 23929, 0, 12731, ...] + cement s64 [11314, 112, 1000, 0, 1088, ...] + gas_flaring s64 [4244, 0, 0, 0, 8042, ...] + per_capita f64 [4.43, 0.54, 0.97, 0.16, 1.65, ...] + bunker_fuels s64 [30722, 251, 0, 10, 1256, ...] + > + + ## Grouped examples + + We want to take the first 3 rows of each group. We need the offset 0 and the length 3: + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.slice(grouped, 0, 3) + #Explorer.DataFrame< + Polars[9 x 5] + Groups: ["species"] + sepal_length f64 [5.1, 4.9, 4.7, 7.0, 6.4, ...] + sepal_width f64 [3.5, 3.0, 3.2, 3.2, 3.2, ...] + petal_length f64 [1.4, 1.4, 1.3, 4.7, 4.5, ...] + petal_width f64 [0.2, 0.2, 0.2, 1.4, 1.5, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-versicolor", "Iris-versicolor", ...] + > + + We can also pass a negative offset: + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.slice(grouped, -6, 3) + #Explorer.DataFrame< + Polars[9 x 5] + Groups: ["species"] + sepal_length f64 [5.1, 4.8, 5.1, 5.6, 5.7, ...] + sepal_width f64 [3.8, 3.0, 3.8, 2.7, 3.0, ...] + petal_length f64 [1.9, 1.4, 1.6, 4.2, 4.2, ...] + petal_width f64 [0.4, 0.3, 0.2, 1.3, 1.2, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-versicolor", "Iris-versicolor", ...] + > + + """ + @doc type: :rows + def slice(df, offset, length) when is_integer(offset) and is_integer(length) and length >= 0, + do: Shared.apply_dataframe(df, :slice, [offset, length]) + + @doc """ + Slices rows at the given indices as a new dataframe. + + The indices may be a list or series of indices, or a range. + A list of indices does not support negative numbers. + Ranges may be negative on either end, which are then + normalized. Note ranges in Elixir are inclusive. + + Slice works differently when a dataframe is grouped. + It is going to consider the indices of each group + instead of the entire dataframe. See the examples below. + + If your intention is to grab a portion of each group, + prefer to use `sample/3` instead. + + ## Examples + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> Explorer.DataFrame.slice(df, [0, 2]) + #Explorer.DataFrame< + Polars[2 x 2] + a s64 [1, 3] + b string ["a", "c"] + > + + With a series + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> Explorer.DataFrame.slice(df, Explorer.Series.from_list([0, 2])) + #Explorer.DataFrame< + Polars[2 x 2] + a s64 [1, 3] + b string ["a", "c"] + > + + With a range: + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> Explorer.DataFrame.slice(df, 1..2) + #Explorer.DataFrame< + Polars[2 x 2] + a s64 [2, 3] + b string ["b", "c"] + > + + With a range with negative first and last: + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> Explorer.DataFrame.slice(df, -2..-1) + #Explorer.DataFrame< + Polars[2 x 2] + a s64 [2, 3] + b string ["b", "c"] + > + + ## Grouped examples + + We are going to once again use the Iris dataset. + In this example we want to take elements at indexes + 0 and 2: + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.slice(grouped, [0, 2]) + #Explorer.DataFrame< + Polars[6 x 5] + Groups: ["species"] + sepal_length f64 [5.1, 4.7, 7.0, 6.9, 6.3, ...] + sepal_width f64 [3.5, 3.2, 3.2, 3.1, 3.3, ...] + petal_length f64 [1.4, 1.3, 4.7, 4.9, 6.0, ...] + petal_width f64 [0.2, 0.2, 1.4, 1.5, 2.5, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-versicolor", "Iris-versicolor", "Iris-virginica", ...] + > + + Now we want to take the first 3 rows of each group. + This is going to work with the range `0..2`: + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.slice(grouped, 0..2) + #Explorer.DataFrame< + Polars[9 x 5] + Groups: ["species"] + sepal_length f64 [5.1, 4.9, 4.7, 7.0, 6.4, ...] + sepal_width f64 [3.5, 3.0, 3.2, 3.2, 3.2, ...] + petal_length f64 [1.4, 1.4, 1.3, 4.7, 4.5, ...] + petal_width f64 [0.2, 0.2, 0.2, 1.4, 1.5, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-versicolor", "Iris-versicolor", ...] + > + + """ + @doc type: :rows + def slice(%DataFrame{groups: []} = df, row_indices) when is_list(row_indices) do + n_rows = n_rows(df) + + Enum.each(row_indices, fn idx -> + if idx > n_rows or idx < -n_rows, + do: + raise( + ArgumentError, + "requested row index (#{idx}) out of bounds (-#{n_rows}:#{n_rows})" + ) + end) + + Shared.apply_dataframe(df, :slice, [row_indices]) + end + + def slice(%DataFrame{} = df, %Series{dtype: int_dtype} = indices) + when int_dtype in @integer_types do + Shared.apply_dataframe(df, :slice, [indices]) + end + + def slice(%DataFrame{groups: []} = df, first..last//1) do + first = if first < 0, do: first + n_rows(df), else: first + last = if last < 0, do: last + n_rows(df), else: last + size = last - first + 1 + + if first >= 0 and size >= 0 do + Shared.apply_dataframe(df, :slice, [first, size]) + else + Shared.apply_dataframe(df, :slice, [[]]) + end + end + + def slice(%DataFrame{groups: []} = df, %Range{} = range) do + slice(df, Enum.slice(0..(n_rows(df) - 1)//1, range)) + end + + def slice(%DataFrame{groups: [_ | _]} = df, row_indices) when is_list(row_indices), + do: Shared.apply_dataframe(df, :slice, [row_indices]) + + def slice(%DataFrame{groups: [_ | _]} = df, %Range{} = range), + do: Shared.apply_dataframe(df, :slice, [range]) + + @doc """ + Sample rows from a dataframe. + + If given an integer as the second argument, it will return N samples. If given a float, it will + return that proportion of the series. + + Can sample with or without replacement. + + For grouped dataframes, sample will take into account the rows of each group, meaning that + if you try to get N samples and you have G groups, you will get N * G rows. See the examples + below. + + ## Options + + * `:replace` - If set to `true`, each sample will be independent and therefore + values may repeat. Required to be `true` for `n` greater then the number of rows + in the dataframe or `frac` > 1.0. (default: `false`) + + * `:seed` - An integer to be used as a random seed. If nil, a random value between 0 + and 2^64 - 1 will be used. (default: `nil`) + + * `:shuffle` - If set to `true`, the resultant dataframe is going to be shuffle + if the sample is equal to the size of the dataframe. (default: `false`) + + ## Examples + + You can sample N rows: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.sample(df, 3, seed: 100) + #Explorer.DataFrame< + Polars[3 x 10] + year s64 [2012, 2013, 2014] + country string ["SYRIAN ARAB REPUBLIC", "EGYPT", "AFGHANISTAN"] + total s64 [12198, 58198, 2675] + solid_fuel s64 [1, 224, 1194] + liquid_fuel s64 [7909, 26501, 1393] + gas_fuel s64 [3265, 24672, 74] + cement s64 [816, 6800, 14] + gas_flaring s64 [208, 0, 0] + per_capita f64 [0.61, 0.66, 0.08] + bunker_fuels s64 [437, 694, 9] + > + + Or you can sample a proportion of rows: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.sample(df, 0.03, seed: 100) + #Explorer.DataFrame< + Polars[32 x 10] + year s64 [2013, 2012, 2014, 2011, 2011, ...] + country string ["BRITISH VIRGIN ISLANDS", "TAJIKISTAN", "AFGHANISTAN", "ICELAND", "SINGAPORE", ...] + total s64 [48, 800, 2675, 513, 12332, ...] + solid_fuel s64 [0, 192, 1194, 94, 7, ...] + liquid_fuel s64 [48, 501, 1393, 400, 7774, ...] + gas_fuel s64 [0, 74, 74, 0, 4551, ...] + cement s64 [0, 34, 14, 19, 0, ...] + gas_flaring s64 [0, 0, 0, 0, 0, ...] + per_capita f64 [1.64, 0.1, 0.08, 1.6, 2.38, ...] + bunker_fuels s64 [0, 28, 9, 168, 41786, ...] + > + + ## Grouped examples + + In the following example we have the Iris dataset grouped by species, and we want + to take a sample of two plants from each group. Since we have three species, the + resultant dataframe is going to have six rows (2 * 3). + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.sample(grouped, 2, seed: 100) + #Explorer.DataFrame< + Polars[6 x 5] + Groups: ["species"] + sepal_length f64 [4.8, 5.0, 5.5, 6.5, 7.4, ...] + sepal_width f64 [3.1, 3.6, 2.4, 2.8, 2.8, ...] + petal_length f64 [1.6, 1.4, 3.8, 4.6, 6.1, ...] + petal_width f64 [0.2, 0.2, 1.1, 1.5, 1.9, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-versicolor", "Iris-versicolor", "Iris-virginica", ...] + > + + The behaviour is similar when you want to take a fraction of the rows from each group. The main + difference is that each group can have more or less rows, depending on its size. + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.sample(grouped, 0.1, seed: 100) + #Explorer.DataFrame< + Polars[15 x 5] + Groups: ["species"] + sepal_length f64 [5.2, 5.0, 5.2, 5.0, 5.0, ...] + sepal_width f64 [3.4, 3.6, 3.5, 3.0, 3.4, ...] + petal_length f64 [1.4, 1.4, 1.5, 1.6, 1.6, ...] + petal_width f64 [0.2, 0.2, 0.2, 0.2, 0.4, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + > + + """ + @doc type: :rows + @spec sample(df :: DataFrame.t(), n_or_frac :: number(), opts :: Keyword.t()) :: DataFrame.t() + def sample(df, n_or_frac, opts \\ []) + + def sample(df, n_or_frac, opts) when is_number(n_or_frac) do + opts = Keyword.validate!(opts, replace: false, shuffle: false, seed: nil) + + if groups(df) == [] do + n_rows = n_rows(df) + n = if is_integer(n_or_frac), do: n_or_frac, else: round(n_or_frac * n_rows) + + if n > n_rows && opts[:replace] == false do + raise ArgumentError, + "in order to sample more rows than are in the dataframe (#{n_rows}), sampling " <> + "`replace` must be true" + end + end + + Shared.apply_dataframe(df, :sample, [n_or_frac, opts[:replace], opts[:shuffle], opts[:seed]]) + end + + @doc """ + Change the order of the rows of a dataframe randomly. + + This function is going to ignore groups. + + ## Options + + * `:seed` - An integer to be used as a random seed. If nil, a random value between 0 + and 2^64 - 1 will be used. (default: `nil`) + + ## Examples + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.shuffle(df, seed: 100) + #Explorer.DataFrame< + Polars[1094 x 10] + year s64 [2014, 2014, 2014, 2012, 2010, ...] + country string ["ISRAEL", "ARGENTINA", "NETHERLANDS", "YEMEN", "GRENADA", ...] + total s64 [17617, 55638, 45624, 5091, 71, ...] + solid_fuel s64 [6775, 1588, 9070, 129, 0, ...] + liquid_fuel s64 [6013, 25685, 18272, 4173, 71, ...] + gas_fuel s64 [3930, 26368, 18010, 414, 0, ...] + cement s64 [898, 1551, 272, 375, 0, ...] + gas_flaring s64 [0, 446, 0, 0, 0, ...] + per_capita f64 [2.22, 1.29, 2.7, 0.2, 0.68, ...] + bunker_fuels s64 [1011, 2079, 14210, 111, 4, ...] + > + + """ + @doc type: :rows + @spec shuffle(df :: DataFrame.t(), opts :: Keyword.t()) :: DataFrame.t() + def shuffle(df, opts \\ []) + + def shuffle(df, opts) do + opts = Keyword.validate!(opts, seed: nil) + + sample(df, 1.0, seed: opts[:seed], shuffle: true) + end + + @doc ~S""" + Make new columns by applying a native Elixir function to each row. + + The native Elixir function should take a map (an element from + `to_rows_stream/2`) as input and return a map where the keys are the desired + new columns and the values are the values for that row. + + See also the version of this function for a single series: + + * `Explorer.Series.transform/2` + + > ### Warning {: .warning} + > + > This is an expensive operation since data is stored in a columnar format. + > You should avoid converting a dataframe to rows where possible as it + > will incur significant overhead. Prefer instead to use the operations in + > this module rather than native Elixir ones. This function should only be + > used as a fallback when no equivalent DataFrame operation is available. + + ## Options + + * `:names` - Column names to select for serializing. + By default all columns will be returned. + + Also, all options which are valid for `to_rows_stream` are valid here. + + > ### The `:names` field is recommended {: .info} + > + > It's recommended that you provide the `:names` option and to set it to only + > those column names needed by your function. Otherwise, you'll be serializing + > unnecessary information. + + ## Examples + + Pre-selecting with `:names`: + + iex> alias Explorer.DataFrame, as: DF + iex> df = DF.new( + ...> numbers: [1, 2], + ...> datetime_local: [~N[2024-01-01 00:00:00], ~N[2024-01-01 00:00:00]], + ...> timezone: ["Etc/UTC", "America/New_York"] + ...> ) + iex> DF.transform(df, [names: ["datetime_local", "timezone"]], fn row -> + ...> datetime_utc = + ...> row["datetime_local"] + ...> |> DateTime.from_naive!(row["timezone"]) + ...> |> DateTime.shift_zone!("Etc/UTC") + ...> + ...> %{datetime_utc: datetime_utc} + ...> end) + #Explorer.DataFrame< + Polars[2 x 4] + numbers s64 [1, 2] + datetime_local naive_datetime[μs] [2024-01-01 00:00:00.000000, 2024-01-01 00:00:00.000000] + timezone string ["Etc/UTC", "America/New_York"] + datetime_utc datetime[μs, Etc/UTC] [2024-01-01 00:00:00.000000Z, 2024-01-01 05:00:00.000000Z] + > + + Converting to atoms with `:atom_keys`: + + iex> alias Explorer.DataFrame, as: DF + iex> df = DF.new( + ...> major: [1, 2, 3], + ...> minor: [11, 12, 13], + ...> patch: [0, 0, 0] + ...> ) + iex> DF.transform(df, [atom_keys: true], fn row -> + ...> version = Version.parse!("#{row.major}.#{row.minor}.#{row.patch}") + ...> %{meets_requirements: Version.match?(version, "> 2.0.0")} + ...> end) + #Explorer.DataFrame< + Polars[3 x 4] + major s64 [1, 2, 3] + minor s64 [11, 12, 13] + patch s64 [0, 0, 0] + meets_requirements boolean [false, true, true] + > + """ + @doc type: :single + @spec transform(DataFrame.t(), Keyword.t(), fun()) :: DataFrame.t() + def transform(df, opts \\ [], row_transform) when is_function(row_transform, 1) do + {names, to_rows_stream_opts} = Keyword.pop(opts, :names, df.names) + + df_new = + df + |> select(names) + |> to_rows_stream(to_rows_stream_opts) + |> Enum.map(row_transform) + |> new() + + concat_columns(df, df_new) + end + + @doc """ + Transpose a DataFrame. + + > #### Warning {: .warning} + > + > This is an expensive operation since data is stored in a columnar format. + + ## Options + + * `:header` - When a string is passed, name of the header column is set to the value. When `header` is `true`, name is set to `column` (default: `false`) + * `:columns` - names for non header columns. Length of column_names should match the row count of data frame. (default: `nil`) + + ## Examples + + iex> df = Explorer.DataFrame.new(a: ["d", nil], b: [1, 2], c: ["a", "b"]) + iex> Explorer.DataFrame.transpose(df) + #Explorer.DataFrame< + Polars[3 x 2] + column_0 string ["d", "1", "a"] + column_1 string [nil, "2", "b"] + > + + iex> df = Explorer.DataFrame.new(a: ["d", nil], b: [1, 2], c: ["a", "b"]) + iex> Explorer.DataFrame.transpose(df, columns: ["x", "y"]) + #Explorer.DataFrame< + Polars[3 x 2] + x string ["d", "1", "a"] + y string [nil, "2", "b"] + > + + iex> df = Explorer.DataFrame.new(a: ["d", nil], b: [1, 2], c: ["a", "b"]) + iex> Explorer.DataFrame.transpose(df, header: "name") + #Explorer.DataFrame< + Polars[3 x 3] + name string ["a", "b", "c"] + column_0 string ["d", "1", "a"] + column_1 string [nil, "2", "b"] + > + """ + @doc type: :single + @spec transpose(df :: DataFrame.t(), opts :: Keyword.t()) :: DataFrame.t() + def transpose(df, opts \\ []) do + opts = Keyword.validate!(opts, header: false, columns: nil) + + header = + case opts[:header] do + false -> nil + true -> "column" + header -> to_column_name(header) + end + + columns = opts[:columns] && Enum.map(opts[:columns], &to_column_name/1) + + df_length = n_rows(df) + + names = + cond do + columns == nil -> + for i <- 0..(df_length - 1), do: "column_#{i}" + + length(columns) == df_length -> + columns + + true -> + raise ArgumentError, + "invalid :columns option, length of column names (#{length(columns)}) must match the row count (#{df_length})" + end + + names = if header, do: [header | names], else: names + dtypes = Map.new(names, fn n -> {n, :string} end) + out_df = out_df(df, names, dtypes) + + args = [out_df, header, columns] + Shared.apply_dataframe(df, :transpose, args) + end + + @doc """ + Pivot data from wide to long. + + `pivot_longer/3` "lengthens" data, increasing the number of rows and + decreasing the number of columns. The inverse transformation is `pivot_wider/4`. + + The second argument, `columns_to_pivot`, can be either list of column names to pivot. + Ranges, regexes, and functions are also accepted in column names, as in `select/2`. + The selected columns must always have the same data type. + + In case the dataframe is using groups, the groups that are also in the list of columns + to pivot will be removed from the resultant dataframe. See the examples below. + + ## Options + + * `:select` - Columns that are not in the list of pivot and should be kept in the dataframe. + Ranges, regexes, and functions are also accepted in column names, as in `select/2`. + Defaults to all columns except the ones to pivot. + + * `:discard` - Columns that are not in the list of pivot and should be dropped from the dataframe. + Ranges, regexes, and functions are also accepted in column names, as in `select/2`. + This list of columns is going to be subtracted from the list of `select`. + Defaults to an empty list. + + * `:names_to` - A string specifying the name of the column to create from the data stored + in the column names of the dataframe. Defaults to `"variable"`. + + * `:values_to` - A string specifying the name of the column to create from the data stored + in series element values. Defaults to `"value"`. + + ## Examples + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.pivot_longer(df, &String.ends_with?(&1, "fuel")) + #Explorer.DataFrame< + Polars[3282 x 9] + year s64 [2010, 2010, 2010, 2010, 2010, ...] + country string ["AFGHANISTAN", "ALBANIA", "ALGERIA", "ANDORRA", "ANGOLA", ...] + total s64 [2308, 1254, 32500, 141, 7924, ...] + cement s64 [5, 177, 2598, 0, 204, ...] + gas_flaring s64 [0, 0, 2623, 0, 3697, ...] + per_capita f64 [0.08, 0.43, 0.9, 1.68, 0.37, ...] + bunker_fuels s64 [9, 7, 663, 0, 321, ...] + variable string ["solid_fuel", "solid_fuel", "solid_fuel", "solid_fuel", "solid_fuel", ...] + value s64 [627, 117, 332, 0, 0, ...] + > + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.pivot_longer(df, &String.ends_with?(&1, "fuel"), select: ["year", "country"]) + #Explorer.DataFrame< + Polars[3282 x 4] + year s64 [2010, 2010, 2010, 2010, 2010, ...] + country string ["AFGHANISTAN", "ALBANIA", "ALGERIA", "ANDORRA", "ANGOLA", ...] + variable string ["solid_fuel", "solid_fuel", "solid_fuel", "solid_fuel", "solid_fuel", ...] + value s64 [627, 117, 332, 0, 0, ...] + > + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.pivot_longer(df, ["total"], select: ["year", "country"], discard: ["country"]) + #Explorer.DataFrame< + Polars[1094 x 3] + year s64 [2010, 2010, 2010, 2010, 2010, ...] + variable string ["total", "total", "total", "total", "total", ...] + value s64 [2308, 1254, 32500, 141, 7924, ...] + > + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.pivot_longer(df, ["total"], select: [], names_to: "my_var", values_to: "my_value") + #Explorer.DataFrame< + Polars[1094 x 2] + my_var string ["total", "total", "total", "total", "total", ...] + my_value s64 [2308, 1254, 32500, 141, 7924, ...] + > + + ## Grouped examples + + In the following example we want to take the Iris dataset and increase the number of rows by + pivoting the "sepal_length" column. This dataset is grouped by "species", so the resultant + dataframe is going to keep the "species" group: + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.pivot_longer(grouped, ["sepal_length"]) + #Explorer.DataFrame< + Polars[150 x 6] + Groups: ["species"] + sepal_width f64 [3.5, 3.0, 3.2, 3.1, 3.6, ...] + petal_length f64 [1.4, 1.4, 1.3, 1.5, 1.4, ...] + petal_width f64 [0.2, 0.2, 0.2, 0.2, 0.2, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + variable string ["sepal_length", "sepal_length", "sepal_length", "sepal_length", "sepal_length", ...] + value f64 [5.1, 4.9, 4.7, 4.6, 5.0, ...] + > + + Now we want to do something different: we want to pivot the "species" column that is also a group. + This is going to remove the group in the resultant dataframe: + + iex> df = Explorer.Datasets.iris() + iex> grouped = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.pivot_longer(grouped, ["species"]) + #Explorer.DataFrame< + Polars[150 x 6] + sepal_length f64 [5.1, 4.9, 4.7, 4.6, 5.0, ...] + sepal_width f64 [3.5, 3.0, 3.2, 3.1, 3.6, ...] + petal_length f64 [1.4, 1.4, 1.3, 1.5, 1.4, ...] + petal_width f64 [0.2, 0.2, 0.2, 0.2, 0.2, ...] + variable string ["species", "species", "species", "species", "species", ...] + value string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + > + + """ + @doc type: :single + @spec pivot_longer( + df :: DataFrame.t(), + columns_to_pivot :: columns(), + opts :: Keyword.t() + ) :: DataFrame.t() + def pivot_longer(df, columns_to_pivot, opts \\ []) + + def pivot_longer(df, columns_to_pivot, opts) do + opts = + Keyword.validate!(opts, + select: .., + discard: [], + names_to: "variable", + values_to: "value" + ) + + names_to = to_column_name(opts[:names_to]) + values_to = to_column_name(opts[:values_to]) + + columns_to_pivot = to_existing_columns(df, columns_to_pivot) + dtypes = df.dtypes + + columns_to_keep = + case opts[:select] do + keep when is_list(keep) -> + Enum.each(keep, fn column -> + if column in columns_to_pivot do + raise ArgumentError, + "selected columns must not include columns to pivot, but found #{inspect(column)} in both" + end + end) + + to_existing_columns(df, keep) + + keep -> + to_existing_columns(df, keep) + end + + columns_to_keep = + (columns_to_keep -- columns_to_pivot) -- to_existing_columns(df, opts[:discard]) + + values_dtype = + dtypes + |> Map.take(columns_to_pivot) + |> Map.values() + |> Enum.uniq() + |> case do + [dtype] -> + dtype + + [_ | _] = dtypes -> + raise ArgumentError, + "columns to pivot must include columns with the same dtype, but found multiple dtypes: #{Shared.inspect_dtypes(dtypes)}" + end + + new_dtypes = + dtypes + |> Map.take(columns_to_keep) + |> Map.put(names_to, :string) + |> Map.put(values_to, values_dtype) + + out_df = + out_df( + %{df | groups: df.groups -- columns_to_pivot}, + columns_to_keep ++ [names_to, values_to], + new_dtypes + ) + + args = [out_df, columns_to_pivot, columns_to_keep, names_to, values_to] + Shared.apply_dataframe(df, :pivot_longer, args) + end + + @doc """ + Pivot data from long to wide. + + `pivot_wider/4` "widens" data, increasing the number of columns and decreasing the number of rows. + The inverse transformation is `pivot_longer/3`. + + In case the dataframe is using groups, the groups that are also in the list of columns + to pivot will be removed from the resultant dataframe. See the examples below. + + ## Options + + * `:id_columns` - A set of columns that uniquely identifies each observation. + + Defaults to all columns in data except for the columns specified in `names_from` and `values_from`, + and columns that are of the `{:f, 64}` dtype. + + Typically used when you have redundant variables, i.e. variables whose values are perfectly correlated + with existing variables. May accept a filter callback, a list or a range of column names. + If an empty list is passed, or a range that results in a empty list of column names, it raises an error. + + ID columns cannot be of the float type and any columns of this dtype is discarded. + If you need to use float columns as IDs, you must carefully consider rounding + or truncating the column and converting it to integer, as long as doing so + preserves the properties of the column. + + * `:names_prefix` - String added to the start of every variable name. + This is particularly useful if `names_from` is a numeric vector and you want to create syntactic variable names. + + ## Examples + + Suppose we have a basketball court and multiple teams that want to train in that court. They need + to share a schedule with the hours each team is going to use it. Here is a dataframe representing + that schedule: + + iex> Explorer.DataFrame.new( + iex> weekday: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"], + iex> team: ["A", "B", "C", "A", "B", "C", "A", "B", "C", "A"], + iex> hour: [10, 9, 10, 10, 11, 15, 14, 16, 14, 16] + iex> ) + + This dataframe is going to look like this - using `print/2`: + + +----------------------------------------------+ + | Explorer DataFrame: [rows: 10, columns: 3] | + +---------------+--------------+---------------+ + | weekday | team | hour | + | | | | + +===============+==============+===============+ + | Monday | A | 10 | + +---------------+--------------+---------------+ + | Tuesday | B | 9 | + +---------------+--------------+---------------+ + | Wednesday | C | 10 | + +---------------+--------------+---------------+ + | Thursday | A | 10 | + +---------------+--------------+---------------+ + | Friday | B | 11 | + +---------------+--------------+---------------+ + | Monday | C | 15 | + +---------------+--------------+---------------+ + | Tuesday | A | 14 | + +---------------+--------------+---------------+ + | Wednesday | B | 16 | + +---------------+--------------+---------------+ + | Thursday | C | 14 | + +---------------+--------------+---------------+ + | Friday | A | 16 | + +---------------+--------------+---------------+ + + You can see that the "weekday" repeats, and it's not clear how free the agenda is. + We can solve that by pivoting the "weekday" column in multiple columns, making each weekday + a new column in the resultant dataframe. + + iex> df = Explorer.DataFrame.new( + iex> weekday: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"], + iex> team: ["A", "B", "C", "A", "B", "C", "A", "B", "C", "A"], + iex> hour: [10, 9, 10, 10, 11, 15, 14, 16, 14, 16] + iex> ) + iex> Explorer.DataFrame.pivot_wider(df, "weekday", "hour") + #Explorer.DataFrame< + Polars[3 x 6] + team string ["A", "B", "C"] + Monday s64 [10, nil, 15] + Tuesday s64 [14, 9, nil] + Wednesday s64 [nil, 16, 10] + Thursday s64 [10, nil, 14] + Friday s64 [16, 11, nil] + > + + Now if we print that same dataframe with `print/2`, we get a better picture of the schedule: + + +----------------------------------------------------------------------+ + | Explorer DataFrame: [rows: 3, columns: 6] | + +----------+-----------+-----------+-----------+-----------+-----------+ + | team | Monday | Tuesday | Wednesday | Thursday | Friday | + | | | | | | | + +==========+===========+===========+===========+===========+===========+ + | A | 10 | 14 | | 10 | 16 | + +----------+-----------+-----------+-----------+-----------+-----------+ + | B | | 9 | 16 | | 11 | + +----------+-----------+-----------+-----------+-----------+-----------+ + | C | 15 | | 10 | 14 | | + +----------+-----------+-----------+-----------+-----------+-----------+ + + Pivot wider can create unpredictable column names, and sometimes they can conflict with ID columns. + In that scenario, we add a number as suffix to duplicated column names. Here is an example: + + iex> df = Explorer.DataFrame.new( + iex> product_id: [1, 1, 1, 1, 2, 2, 2, 2], + iex> property: ["product_id", "width_cm", "height_cm", "length_cm", "product_id", "width_cm", "height_cm", "length_cm"], + iex> property_value: [1, 42, 40, 64, 2, 35, 20, 40] + iex> ) + iex> Explorer.DataFrame.pivot_wider(df, "property", "property_value") + #Explorer.DataFrame< + Polars[2 x 5] + product_id s64 [1, 2] + product_id_1 s64 [1, 2] + width_cm s64 [42, 35] + height_cm s64 [40, 20] + length_cm s64 [64, 40] + > + + But if the option `:names_prefix` is used, that suffix is not added: + + iex> df = Explorer.DataFrame.new( + iex> product_id: [1, 1, 1, 1, 2, 2, 2, 2], + iex> property: ["product_id", "width_cm", "height_cm", "length_cm", "product_id", "width_cm", "height_cm", "length_cm"], + iex> property_value: [1, 42, 40, 64, 2, 35, 20, 40] + iex> ) + iex> Explorer.DataFrame.pivot_wider(df, "property", "property_value", names_prefix: "col_") + #Explorer.DataFrame< + Polars[2 x 5] + product_id s64 [1, 2] + col_product_id s64 [1, 2] + col_width_cm s64 [42, 35] + col_height_cm s64 [40, 20] + col_length_cm s64 [64, 40] + > + + Multiple columns are accepted for the `values_from` parameter, but the behaviour is slightly + different for the naming of new columns in the resultant dataframe. The new columns are going + to be prefixed by the name of the original value column, followed by the name of the variable. + + iex> df = Explorer.DataFrame.new( + iex> product_id: [1, 1, 1, 1, 2, 2, 2, 2], + iex> property: ["product_id", "width_cm", "height_cm", "length_cm", "product_id", "width_cm", "height_cm", "length_cm"], + iex> property_value: [1, 42, 40, 64, 2, 35, 20, 40], + iex> another_value: [1, 43, 41, 65, 2, 36, 21, 42] + iex> ) + iex> Explorer.DataFrame.pivot_wider(df, "property", ["property_value", "another_value"]) + #Explorer.DataFrame< + Polars[2 x 9] + product_id s64 [1, 2] + property_value_product_id s64 [1, 2] + property_value_width_cm s64 [42, 35] + property_value_height_cm s64 [40, 20] + property_value_length_cm s64 [64, 40] + another_value_product_id s64 [1, 2] + another_value_width_cm s64 [43, 36] + another_value_height_cm s64 [41, 21] + another_value_length_cm s64 [65, 42] + > + + ## Grouped examples + + Now using the same idea, we can see that there is not much difference for grouped dataframes. + The only detail is that groups that are not ID columns are discarded. + + iex> df = Explorer.DataFrame.new( + iex> weekday: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"], + iex> team: ["A", "B", "C", "A", "B", "C", "A", "B", "C", "A"], + iex> hour: [10, 9, 10, 10, 11, 15, 14, 16, 14, 16] + iex> ) + iex> grouped = Explorer.DataFrame.group_by(df, "team") + iex> Explorer.DataFrame.pivot_wider(grouped, "weekday", "hour") + #Explorer.DataFrame< + Polars[3 x 6] + Groups: ["team"] + team string ["A", "B", "C"] + Monday s64 [10, nil, 15] + Tuesday s64 [14, 9, nil] + Wednesday s64 [nil, 16, 10] + Thursday s64 [10, nil, 14] + Friday s64 [16, 11, nil] + > + + In the following example the group "weekday" is going to be removed, because the column is going + to be pivoted in multiple columns: + + iex> df = Explorer.DataFrame.new( + iex> weekday: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"], + iex> team: ["A", "B", "C", "A", "B", "C", "A", "B", "C", "A"], + iex> hour: [10, 9, 10, 10, 11, 15, 14, 16, 14, 16] + iex> ) + iex> grouped = Explorer.DataFrame.group_by(df, "weekday") + iex> Explorer.DataFrame.pivot_wider(grouped, "weekday", "hour") + #Explorer.DataFrame< + Polars[3 x 6] + team string ["A", "B", "C"] + Monday s64 [10, nil, 15] + Tuesday s64 [14, 9, nil] + Wednesday s64 [nil, 16, 10] + Thursday s64 [10, nil, 14] + Friday s64 [16, 11, nil] + > + + """ + @doc type: :single + @spec pivot_wider( + df :: DataFrame.t(), + names_from :: column(), + values_from :: column() | columns(), + opts :: + Keyword.t() + ) :: DataFrame.t() + + def pivot_wider(df, names_from, values_from, opts \\ []) + + def pivot_wider(df, names_from, values_from, opts) when is_column(values_from) do + pivot_wider(df, names_from, [values_from], opts) + end + + def pivot_wider(df, names_from, values_from, opts) when is_list(values_from) do + opts = Keyword.validate!(opts, id_columns: .., names_prefix: "") + + [names_from | values_from] = to_existing_columns(df, [names_from | values_from]) + + id_columns = + for column_name <- to_existing_columns(df, opts[:id_columns]) -- [names_from | values_from], + df.dtypes[column_name] != {:f, 64}, + do: column_name + + if id_columns == [] do + raise ArgumentError, + "id_columns must select at least one existing column, but #{inspect(opts[:id_columns])} selects none. " <> + "Note that float columns are discarded from the selection." + end + + out_df = + Shared.apply_dataframe(df, :pivot_wider, [ + id_columns, + names_from, + values_from, + opts[:names_prefix] + ]) + + %{out_df | groups: Enum.filter(df.groups, &(&1 in id_columns))} + end + + # Two table verbs + + @valid_join_types [:inner, :left, :right, :outer, :cross] + + @doc """ + Join two tables. + + ## Join types + + * `:inner` - Returns all rows from `left` where there are matching values in `right`, and all columns from `left` and `right`. + * `:left` - Returns all rows from `left` and all columns from `left` and `right`. Rows in `left` with no match in `right` will have `nil` values in the new columns. + * `:right` - Returns all rows from `right` and all columns from `left` and `right`. Rows in `right` with no match in `left` will have `nil` values in the new columns. + * `:outer` - Returns all rows and all columns from both `left` and `right`. Where there are not matching values, returns `nil` for the one missing. + * `:cross` - Also known as a cartesian join. Returns all combinations of `left` and `right`. Can be very computationally expensive. + + ## Options + + * `:on` - The column(s) to join on. Defaults to overlapping columns. Does not apply to cross join. + * `:how` - One of the join types (as an atom) described above. Defaults to `:inner`. + + ## Examples + + Inner join: + + iex> left = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> right = Explorer.DataFrame.new(a: [1, 2, 2], c: ["d", "e", "f"]) + iex> Explorer.DataFrame.join(left, right) + #Explorer.DataFrame< + Polars[3 x 3] + a s64 [1, 2, 2] + b string ["a", "b", "b"] + c string ["d", "e", "f"] + > + + Left join: + + iex> left = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> right = Explorer.DataFrame.new(a: [1, 2, 2], c: ["d", "e", "f"]) + iex> Explorer.DataFrame.join(left, right, how: :left) + #Explorer.DataFrame< + Polars[4 x 3] + a s64 [1, 2, 2, 3] + b string ["a", "b", "b", "c"] + c string ["d", "e", "f", nil] + > + + Right join: + + iex> left = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> right = Explorer.DataFrame.new(a: [1, 2, 4], c: ["d", "e", "f"]) + iex> Explorer.DataFrame.join(left, right, how: :right) + #Explorer.DataFrame< + Polars[3 x 3] + a s64 [1, 2, 4] + c string ["d", "e", "f"] + b string ["a", "b", nil] + > + + Outer join: + + iex> left = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> right = Explorer.DataFrame.new(a: [1, 2, 4], c: ["d", "e", "f"]) + iex> Explorer.DataFrame.join(left, right, how: :outer) + #Explorer.DataFrame< + Polars[4 x 4] + a s64 [1, 2, nil, 3] + b string ["a", "b", nil, "c"] + a_right s64 [1, 2, 4, nil] + c string ["d", "e", "f", nil] + > + + + Cross join: + + iex> left = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> right = Explorer.DataFrame.new(a: [1, 2, 4], c: ["d", "e", "f"]) + iex> Explorer.DataFrame.join(left, right, how: :cross) + #Explorer.DataFrame< + Polars[9 x 4] + a s64 [1, 1, 1, 2, 2, ...] + b string ["a", "a", "a", "b", "b", ...] + a_right s64 [1, 2, 4, 1, 2, ...] + c string ["d", "e", "f", "d", "e", ...] + > + + Inner join with different names: + + iex> left = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> right = Explorer.DataFrame.new(d: [1, 2, 2], c: ["d", "e", "f"]) + iex> Explorer.DataFrame.join(left, right, on: [a: :d]) + #Explorer.DataFrame< + Polars[3 x 3] + a s64 [1, 2, 2] + b string ["a", "b", "b"] + c string ["d", "e", "f"] + > + + ## Grouped examples + + When doing a join operation with grouped dataframes, the joined dataframe + may keep the groups from only one side. + + An inner join operation will keep the groups from the left-hand side dataframe: + + iex> left = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> right = Explorer.DataFrame.new(a: [1, 2, 2], c: ["d", "e", "f"]) + iex> grouped_left = Explorer.DataFrame.group_by(left, "b") + iex> grouped_right = Explorer.DataFrame.group_by(right, "c") + iex> Explorer.DataFrame.join(grouped_left, grouped_right) + #Explorer.DataFrame< + Polars[3 x 3] + Groups: ["b"] + a s64 [1, 2, 2] + b string ["a", "b", "b"] + c string ["d", "e", "f"] + > + + A left join operation will keep the groups from the left-hand side dataframe: + + iex> left = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> right = Explorer.DataFrame.new(a: [1, 2, 2], c: ["d", "e", "f"]) + iex> grouped_left = Explorer.DataFrame.group_by(left, "b") + iex> grouped_right = Explorer.DataFrame.group_by(right, "c") + iex> Explorer.DataFrame.join(grouped_left, grouped_right, how: :left) + #Explorer.DataFrame< + Polars[4 x 3] + Groups: ["b"] + a s64 [1, 2, 2, 3] + b string ["a", "b", "b", "c"] + c string ["d", "e", "f", nil] + > + + A right join operation will keep the groups from the right-hand side dataframe: + + iex> left = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> right = Explorer.DataFrame.new(a: [1, 2, 4], c: ["d", "e", "f"]) + iex> grouped_left = Explorer.DataFrame.group_by(left, "b") + iex> grouped_right = Explorer.DataFrame.group_by(right, "c") + iex> Explorer.DataFrame.join(grouped_left, grouped_right, how: :right) + #Explorer.DataFrame< + Polars[3 x 3] + Groups: ["c"] + a s64 [1, 2, 4] + c string ["d", "e", "f"] + b string ["a", "b", nil] + > + + An outer join operation is going to keep the groups from the left-hand side dataframe: + + iex> left = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> right = Explorer.DataFrame.new(a: [1, 2, 4], c: ["d", "e", "f"]) + iex> grouped_left = Explorer.DataFrame.group_by(left, "b") + iex> grouped_right = Explorer.DataFrame.group_by(right, "c") + iex> Explorer.DataFrame.join(grouped_left, grouped_right, how: :outer) + #Explorer.DataFrame< + Polars[4 x 4] + Groups: ["b"] + a s64 [1, 2, nil, 3] + b string ["a", "b", nil, "c"] + a_right s64 [1, 2, 4, nil] + c string ["d", "e", "f", nil] + > + + + + A cross join operation is going to keep the groups from the left-hand side dataframe: + + iex> left = Explorer.DataFrame.new(a: [1, 2, 3], b: ["a", "b", "c"]) + iex> right = Explorer.DataFrame.new(a: [1, 2, 4], c: ["d", "e", "f"]) + iex> grouped_left = Explorer.DataFrame.group_by(left, "b") + iex> grouped_right = Explorer.DataFrame.group_by(right, "c") + iex> Explorer.DataFrame.join(grouped_left, grouped_right, how: :cross) + #Explorer.DataFrame< + Polars[9 x 4] + Groups: ["b"] + a s64 [1, 1, 1, 2, 2, ...] + b string ["a", "a", "a", "b", "b", ...] + a_right s64 [1, 2, 4, 1, 2, ...] + c string ["d", "e", "f", "d", "e", ...] + > + + """ + @doc type: :multi + @spec join(left :: DataFrame.t(), right :: DataFrame.t(), opts :: Keyword.t()) :: DataFrame.t() + def join(%DataFrame{} = left, %DataFrame{} = right, opts \\ []) do + left_columns = left.names + right_columns = right.names + + opts = + Keyword.validate!(opts, + on: find_overlapping_columns(left_columns, right_columns), + how: :inner + ) + + unless opts[:how] in @valid_join_types do + raise ArgumentError, + "join type is not valid: #{inspect(opts[:how])}. " <> + "Valid options are: #{Enum.map_join(@valid_join_types, ", ", &inspect/1)}" + end + + {on, how} = + case {List.wrap(opts[:on]), opts[:how]} do + {[], :cross} -> + {[], :cross} + + {[], _} -> + raise(ArgumentError, "could not find any overlapping columns") + + {[_ | _] = on, how} -> + normalized_on = + Enum.map(on, fn + {l_name, r_name} -> + [l_column] = to_existing_columns(left, [l_name]) + [r_column] = to_existing_columns(right, [r_name]) + {l_column, r_column} + + name -> + [l_column] = to_existing_columns(left, [name]) + [r_column] = to_existing_columns(right, [name]) + + # This is an edge case for when an index is passed as column selection + if l_column != r_column do + raise ArgumentError, + "the column given to option `:on` is not the same for both dataframes" + end + + {l_column, r_column} + end) + + {normalized_on, how} + end + + out_df = out_df_for_join(how, left, right, on) + + Shared.apply_dataframe([left, right], :join, [out_df, on, how]) + end + + defp find_overlapping_columns(left_columns, right_columns) do + left_columns = MapSet.new(left_columns) + right_columns = MapSet.new(right_columns) + left_columns |> MapSet.intersection(right_columns) |> MapSet.to_list() + end + + defp out_df_for_join(:right, left, right, on) do + {left_on, _right_on} = Enum.unzip(on) + pairs = dtypes_pairs_for_common_join(right, left, left_on, "_left") + + {new_names, _} = Enum.unzip(pairs) + out_df(right, new_names, Map.new(pairs)) + end + + defp out_df_for_join(how, left, right, on) do + {_left_on, right_on} = Enum.unzip(on) + right_on = if how in [:cross, :outer], do: [], else: right_on + pairs = dtypes_pairs_for_common_join(left, right, right_on) + + {new_names, _} = Enum.unzip(pairs) + out_df(left, new_names, Map.new(pairs)) + end + + defp dtypes_pairs_for_common_join(left, right, right_on, suffix \\ "_right") do + Enum.map(left.names, fn name -> {name, left.dtypes[name]} end) ++ + Enum.map(right.names -- right_on, fn right_name -> + name = + if right_name in left.names do + right_name <> suffix + else + right_name + end + + {name, right.dtypes[right_name]} + end) + end + + @doc """ + Combine two or more dataframes column-wise. + + This function expects the dataframes to have the same number of rows, + otherwise rows may be silently discarded. Eager backends may check + whenever this happens and raise instead of silently fail. But this may not + be possible for lazy dataframes as the number of rows is not known upfront. + + When working with grouped dataframes, be aware that only groups from the first + dataframe are kept in the resultant dataframe. + + ## Examples + + iex> df1 = Explorer.DataFrame.new(x: [1, 2, 3], y: ["a", "b", "c"]) + iex> df2 = Explorer.DataFrame.new(z: [4, 5, 6], a: ["d", "e", "f"]) + iex> Explorer.DataFrame.concat_columns([df1, df2]) + #Explorer.DataFrame< + Polars[3 x 4] + x s64 [1, 2, 3] + y string ["a", "b", "c"] + z s64 [4, 5, 6] + a string ["d", "e", "f"] + > + + Conflicting names are suffixed with the index of the dataframe in the array: + + iex> df1 = Explorer.DataFrame.new(x: [1, 2, 3], y: ["a", "b", "c"]) + iex> df2 = Explorer.DataFrame.new(x: [4, 5, 6], a: ["d", "e", "f"]) + iex> Explorer.DataFrame.concat_columns([df1, df2]) + #Explorer.DataFrame< + Polars[3 x 4] + x s64 [1, 2, 3] + y string ["a", "b", "c"] + x_1 s64 [4, 5, 6] + a string ["d", "e", "f"] + > + + """ + @doc type: :multi + @spec concat_columns([DataFrame.t()]) :: DataFrame.t() + def concat_columns([%DataFrame{} = head | tail] = dfs) do + {{names, dtypes}, _} = + Enum.reduce(tail, {{[], head.dtypes}, 1}, fn df, {acc, idx} -> + acc = + Enum.reduce(df.names, acc, fn name, {names, dtypes} -> + new_name = if Map.has_key?(dtypes, name), do: name <> "_#{idx}", else: name + {[new_name | names], Map.put(dtypes, new_name, df.dtypes[name])} + end) + + {acc, idx + 1} + end) + + out_df = out_df(head, head.names ++ Enum.reverse(names), dtypes) + Shared.apply_dataframe(dfs, :concat_columns, [out_df]) + end + + @doc """ + Combine two dataframes column-wise. + + When working with grouped dataframes, be aware that only groups from the left-hand side + dataframe are kept in the resultant dataframe. + + `concat_columns(df1, df2)` is equivalent to `concat_columns([df1, df2])`. + """ + @doc type: :multi + @spec concat_columns(DataFrame.t(), DataFrame.t()) :: DataFrame.t() + def concat_columns(%DataFrame{} = df1, %DataFrame{} = df2), do: concat_columns([df1, df2]) + def concat_columns(%DataFrame{} = df, [%DataFrame{} | _] = dfs), do: concat_columns([df | dfs]) + + @doc """ + Combine two or more dataframes row-wise (stack). + + Column names and dtypes must match. The only exception is for numeric + columns that can be mixed together, and casted automatically to the + "highest" dtype. + + For example, if a column is represented by `{:u, 16}` and `{:u, 32}`, + it will be casted to the highest unsigned integer dtype between the two, + which is `{:u, 32}`. + If it is mixing signed and unsigned integers, it will be casted to + the highest signed integer possible. + And if floats and integers are mixed together, Explorer will cast + them to the float dtype `{:f, 64}`. + + When working with grouped dataframes, be aware that only groups from the first + dataframe are kept in the resultant dataframe. + + ## Examples + + iex> df1 = Explorer.DataFrame.new(x: [1, 2, 3], y: ["a", "b", "c"]) + iex> df2 = Explorer.DataFrame.new(x: [4, 5, 6], y: ["d", "e", "f"]) + iex> Explorer.DataFrame.concat_rows([df1, df2]) + #Explorer.DataFrame< + Polars[6 x 2] + x s64 [1, 2, 3, 4, 5, ...] + y string ["a", "b", "c", "d", "e", ...] + > + + iex> df1 = Explorer.DataFrame.new(x: [1, 2, 3], y: ["a", "b", "c"]) + iex> df2 = Explorer.DataFrame.new(x: [4.2, 5.3, 6.4], y: ["d", "e", "f"]) + iex> Explorer.DataFrame.concat_rows([df1, df2]) + #Explorer.DataFrame< + Polars[6 x 2] + x f64 [1.0, 2.0, 3.0, 4.2, 5.3, ...] + y string ["a", "b", "c", "d", "e", ...] + > + """ + @doc type: :multi + @spec concat_rows([DataFrame.t()]) :: DataFrame.t() + def concat_rows([%DataFrame{} = head | _tail] = dfs) do + changed_types = compute_changed_types_concat_rows(dfs) + out_df = out_df(head, head.names, Map.merge(head.dtypes, changed_types)) + + dfs = + if changed_types == %{} do + dfs + else + for df <- dfs do + mutate_with(ungroup(df), fn ldf -> + for {column, target_type} <- changed_types, + do: {column, Series.cast(ldf[column], target_type)} + end) + end + end + + Shared.apply_dataframe(dfs, :concat_rows, [out_df]) + end + + defp compute_changed_types_concat_rows([head | tail]) do + types = head.dtypes + + Enum.reduce(tail, %{}, fn df, changed_types -> + if n_columns(df) != map_size(types) do + raise ArgumentError, + "dataframes must have the same columns" + end + + Enum.reduce(df.dtypes, changed_types, fn {name, type}, changed_types -> + case types do + %{^name => current_type} -> + if dtype = Shared.merge_dtype(Map.get(changed_types, name, current_type), type) do + Map.put(changed_types, name, dtype) + else + raise ArgumentError, + "columns and dtypes must be identical for all dataframes" + end + + %{} -> + raise ArgumentError, "dataframes must have the same columns" + end + end) + end) + end + + @doc """ + Combine two dataframes row-wise. + + `concat_rows(df1, df2)` is equivalent to `concat_rows([df1, df2])`. + + When working with grouped dataframes, be aware that only groups from the left-hand side + dataframe are kept in the resultant dataframe. + """ + @doc type: :multi + @spec concat_rows(DataFrame.t(), DataFrame.t()) :: DataFrame.t() + def concat_rows(%DataFrame{} = df1, %DataFrame{} = df2), do: concat_rows([df1, df2]) + def concat_rows(%DataFrame{} = df, [%DataFrame{} | _] = dfs), do: concat_rows([df | dfs]) + + # Groups + + @doc """ + Group the dataframe by one or more variables. + + When the dataframe has grouping variables, operations are performed per group. + `Explorer.DataFrame.ungroup/2` removes grouping. + + ## Examples + + You can group by a single variable: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.group_by(df, "country") + #Explorer.DataFrame< + Polars[1094 x 10] + Groups: ["country"] + year s64 [2010, 2010, 2010, 2010, 2010, ...] + country string ["AFGHANISTAN", "ALBANIA", "ALGERIA", "ANDORRA", "ANGOLA", ...] + total s64 [2308, 1254, 32500, 141, 7924, ...] + solid_fuel s64 [627, 117, 332, 0, 0, ...] + liquid_fuel s64 [1601, 953, 12381, 141, 3649, ...] + gas_fuel s64 [74, 7, 14565, 0, 374, ...] + cement s64 [5, 177, 2598, 0, 204, ...] + gas_flaring s64 [0, 0, 2623, 0, 3697, ...] + per_capita f64 [0.08, 0.43, 0.9, 1.68, 0.37, ...] + bunker_fuels s64 [9, 7, 663, 0, 321, ...] + > + + Or you can group by multiple columns in a given list: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.group_by(df, ["country", "year"]) + #Explorer.DataFrame< + Polars[1094 x 10] + Groups: ["country", "year"] + year s64 [2010, 2010, 2010, 2010, 2010, ...] + country string ["AFGHANISTAN", "ALBANIA", "ALGERIA", "ANDORRA", "ANGOLA", ...] + total s64 [2308, 1254, 32500, 141, 7924, ...] + solid_fuel s64 [627, 117, 332, 0, 0, ...] + liquid_fuel s64 [1601, 953, 12381, 141, 3649, ...] + gas_fuel s64 [74, 7, 14565, 0, 374, ...] + cement s64 [5, 177, 2598, 0, 204, ...] + gas_flaring s64 [0, 0, 2623, 0, 3697, ...] + per_capita f64 [0.08, 0.43, 0.9, 1.68, 0.37, ...] + bunker_fuels s64 [9, 7, 663, 0, 321, ...] + > + + Or by a range: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> Explorer.DataFrame.group_by(df, 0..1) + #Explorer.DataFrame< + Polars[1094 x 10] + Groups: ["year", "country"] + year s64 [2010, 2010, 2010, 2010, 2010, ...] + country string ["AFGHANISTAN", "ALBANIA", "ALGERIA", "ANDORRA", "ANGOLA", ...] + total s64 [2308, 1254, 32500, 141, 7924, ...] + solid_fuel s64 [627, 117, 332, 0, 0, ...] + liquid_fuel s64 [1601, 953, 12381, 141, 3649, ...] + gas_fuel s64 [74, 7, 14565, 0, 374, ...] + cement s64 [5, 177, 2598, 0, 204, ...] + gas_flaring s64 [0, 0, 2623, 0, 3697, ...] + per_capita f64 [0.08, 0.43, 0.9, 1.68, 0.37, ...] + bunker_fuels s64 [9, 7, 663, 0, 321, ...] + > + + Regexes and functions are also accepted in column names, as in `select/2`. + """ + @doc type: :single + @spec group_by(df :: DataFrame.t(), groups_or_group :: column_names() | column_name()) :: + DataFrame.t() + def group_by(df, group) when is_column(group), do: group_by(df, [group]) + + def group_by(df, groups) do + groups = to_existing_columns(df, groups) + all_groups = Enum.uniq(df.groups ++ groups) + %{df | groups: all_groups} + end + + @doc """ + Removes grouping variables. + + Accepts a list of group names. If groups is not specified, then all groups are + removed. + + ## Examples + + Ungroups all by default: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> df = Explorer.DataFrame.group_by(df, ["country", "year"]) + iex> Explorer.DataFrame.ungroup(df) + #Explorer.DataFrame< + Polars[1094 x 10] + year s64 [2010, 2010, 2010, 2010, 2010, ...] + country string ["AFGHANISTAN", "ALBANIA", "ALGERIA", "ANDORRA", "ANGOLA", ...] + total s64 [2308, 1254, 32500, 141, 7924, ...] + solid_fuel s64 [627, 117, 332, 0, 0, ...] + liquid_fuel s64 [1601, 953, 12381, 141, 3649, ...] + gas_fuel s64 [74, 7, 14565, 0, 374, ...] + cement s64 [5, 177, 2598, 0, 204, ...] + gas_flaring s64 [0, 0, 2623, 0, 3697, ...] + per_capita f64 [0.08, 0.43, 0.9, 1.68, 0.37, ...] + bunker_fuels s64 [9, 7, 663, 0, 321, ...] + > + + Ungrouping a single column: + + iex> df = Explorer.Datasets.fossil_fuels() + iex> df = Explorer.DataFrame.group_by(df, ["country", "year"]) + iex> Explorer.DataFrame.ungroup(df, "country") + #Explorer.DataFrame< + Polars[1094 x 10] + Groups: ["year"] + year s64 [2010, 2010, 2010, 2010, 2010, ...] + country string ["AFGHANISTAN", "ALBANIA", "ALGERIA", "ANDORRA", "ANGOLA", ...] + total s64 [2308, 1254, 32500, 141, 7924, ...] + solid_fuel s64 [627, 117, 332, 0, 0, ...] + liquid_fuel s64 [1601, 953, 12381, 141, 3649, ...] + gas_fuel s64 [74, 7, 14565, 0, 374, ...] + cement s64 [5, 177, 2598, 0, 204, ...] + gas_flaring s64 [0, 0, 2623, 0, 3697, ...] + per_capita f64 [0.08, 0.43, 0.9, 1.68, 0.37, ...] + bunker_fuels s64 [9, 7, 663, 0, 321, ...] + > + + Lists, ranges, regexes, and functions are also accepted in column names, as in `select/2`. + """ + @doc type: :single + @spec ungroup(df :: DataFrame.t(), groups_or_group :: column_names() | column_name() | :all) :: + DataFrame.t() + def ungroup(df, groups \\ ..) + + def ungroup(df, ..), do: %{df | groups: []} + + def ungroup(df, group) when is_column(group), do: ungroup(df, [group]) + + def ungroup(df, groups) do + current_groups = groups(df) + groups = to_existing_columns(df, groups) + + Enum.each(groups, fn group -> + if group not in current_groups do + raise ArgumentError, + "could not find #{group} in current groups (#{current_groups})" + end + end) + + %{df | groups: current_groups -- groups} + end + + @doc """ + Summarise each group to a single row using `Explorer.Query`. + + To summarise, you must either perform an aggregation (defined in `Explorer.Series`) + on the desired columns, or select plain columns to retrieve all elements of a group. + + The query is compiled and runs efficiently against the dataframe. This function + performs aggregations based on groups and it implicitly ungroups the resultant dataframe. + + > #### Notice {: .notice} + > + > This is a macro. You must `require Explorer.DataFrame` before using it. + + See `summarise_with/2` for a callback version of this function without + `Explorer.Query`. + + ## Examples + + iex> df = Explorer.DataFrame.new(letters: ~w(a b c d e), is_vowel: [true, false, false, false, true]) + iex> grouped_df = Explorer.DataFrame.group_by(df, :is_vowel) + iex> Explorer.DataFrame.summarise(grouped_df, letters: letters) + #Explorer.DataFrame< + Polars[2 x 2] + is_vowel boolean [true, false] + letters list[string] [["a", "e"], ["b", "c", "d"]] + > + + iex> df = Explorer.Datasets.fossil_fuels() + iex> grouped_df = Explorer.DataFrame.group_by(df, "year") + iex> Explorer.DataFrame.summarise(grouped_df, total_max: max(total), total_min: min(total)) + #Explorer.DataFrame< + Polars[5 x 3] + year s64 [2010, 2011, 2012, 2013, 2014] + total_max s64 [2393248, 2654360, 2734817, 2797384, 2806634] + total_min s64 [1, 2, 2, 2, 3] + > + + Suppose you want to get the mean sepal width of each Iris species. You could do something + like this: + + iex> df = Explorer.Datasets.iris() + iex> grouped_df = Explorer.DataFrame.group_by(df, "species") + iex> Explorer.DataFrame.summarise(grouped_df, mean_sepal_width: round(mean(sepal_width), 3)) + #Explorer.DataFrame< + Polars[3 x 2] + species string ["Iris-setosa", "Iris-versicolor", "Iris-virginica"] + mean_sepal_width f64 [3.418, 2.77, 2.974] + > + + In case aggregations for all the dataframe is what you want, you can use ungrouped + dataframes: + + iex> df = Explorer.Datasets.iris() + iex> Explorer.DataFrame.summarise(df, mean_petal_length: round(mean(petal_length), 2)) + #Explorer.DataFrame< + Polars[1 x 1] + mean_petal_length f64 [3.76] + > + + """ + @doc type: :single + defmacro summarise(df, query) do + quote do + require Explorer.Query + Explorer.DataFrame.summarise_with(unquote(df), Explorer.Query.query(unquote(query))) + end + end + + @doc """ + Summarise each group to a single row using a callback function. + + In case no group is set, the entire dataframe will be considered. + The callback receives a lazy dataframe. A lazy dataframe does not + hold any values, instead it stores all operations in order to + execute all summarizations performantly. + + This is a callback version of `summarise/2`. + + ## Examples + + iex> alias Explorer.{DataFrame, Series} + iex> df = Explorer.Datasets.fossil_fuels() |> DataFrame.group_by("year") + iex> DataFrame.summarise_with(df, &[total_max: Series.max(&1["total"]), countries: Series.n_distinct(&1["country"])]) + #Explorer.DataFrame< + Polars[5 x 3] + year s64 [2010, 2011, 2012, 2013, 2014] + total_max s64 [2393248, 2654360, 2734817, 2797384, 2806634] + countries u32 [217, 217, 220, 220, 220] + > + + iex> alias Explorer.{DataFrame, Series} + iex> df = Explorer.Datasets.fossil_fuels() + iex> DataFrame.summarise_with(df, &[total_max: Series.max(&1["total"]), countries: Series.n_distinct(&1["country"])]) + #Explorer.DataFrame< + Polars[1 x 2] + total_max s64 [2806634] + countries u32 [222] + > + + """ + @doc type: :single + @spec summarise_with( + df :: DataFrame.t(), + callback_or_column_pairs :: + (Explorer.Backend.QueryFrame.t() -> column_pairs(Series.lazy_t())) + | column_pairs(Series.lazy_t()) + ) :: DataFrame.t() + def summarise_with(%DataFrame{} = df, fun) when is_function(fun, 1) do + column_pairs = + df + |> Explorer.Query.new() + |> fun.() + + summarise_with(df, column_pairs) + end + + def summarise_with(%DataFrame{} = df, column_pairs) when is_column_pairs(column_pairs) do + column_pairs = + Enum.map(column_pairs, fn + {key, nil} -> + lazy_s = LazySeries.unbacked(:lazy, [nil], :null) + {key, Explorer.Backend.Series.new(lazy_s, :null)} + + pair -> + pair + end) + + column_pairs = + to_column_pairs(df, column_pairs, fn value -> + case value do + %Series{data: %LazySeries{op: :lazy, args: [nil], dtype: :null}} -> + value + + %Series{data: %LazySeries{aggregation: true}} -> + value + + %Series{data: %LazySeries{op: :column}} -> + %{value | dtype: {:list, value.dtype}} + + %Series{data: %LazySeries{}} = series -> + raise "expecting summarise with an aggregation operation or plain column, " <> + "but none of which were found in: #{inspect(series)}" + + other -> + raise "expecting a lazy series, got: #{inspect(other)}" + end + end) + + new_dtypes = names_with_dtypes_for_column_pairs(df, column_pairs) + new_names = for {name, _} <- new_dtypes, do: name + out_df = out_df(%{df | groups: []}, new_names, Map.new(new_dtypes)) + + column_pairs = for {name, %Series{data: lazy_series}} <- column_pairs, do: {name, lazy_series} + + Shared.apply_dataframe(df, :summarise_with, [out_df, column_pairs]) + end + + defp names_with_dtypes_for_column_pairs(df, column_pairs) do + groups = for group <- df.groups, do: {group, df.dtypes[group]} + + names_with_dtypes = + for {column_name, series} <- column_pairs do + {column_name, series.dtype} + end + + groups ++ names_with_dtypes + end + + @doc """ + Explodes one or multiple list column into multiple rows. + + When exploding multiple columns, the number of list elements in each row for + the exploded columns must be the same. + + ## Examples + + iex> df = Explorer.DataFrame.new(a: [[1, 2], [3, 4]], b: [[5, 6], [7, 8]], c: ["a", "b"]) + iex> Explorer.DataFrame.explode(df, :a) + #Explorer.DataFrame< + Polars[4 x 3] + a s64 [1, 2, 3, 4] + b list[s64] [[5, 6], [5, 6], [7, 8], [7, ...]] + c string ["a", "a", "b", "b"] + > + iex> Explorer.DataFrame.explode(df, [:a, :b]) + #Explorer.DataFrame< + Polars[4 x 3] + a s64 [1, 2, 3, 4] + b s64 [5, 6, 7, 8] + c string ["a", "a", "b", "b"] + > + + You can think of exploding multiple list columns as being the inverse of + aggregating the elements the exploded columns into lists: + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3, 4], b: [5, 6, 7, 8], c: ["a", "a", "b", "b"]) + iex> df = df |> Explorer.DataFrame.group_by(:c) |> Explorer.DataFrame.summarise(a: a, b: b) + #Explorer.DataFrame< + Polars[2 x 3] + c string ["a", "b"] + a list[s64] [[1, 2], [3, 4]] + b list[s64] [[5, 6], [7, 8]] + > + iex> Explorer.DataFrame.explode(df, [:a, :b]) # we are back where we started + #Explorer.DataFrame< + Polars[4 x 3] + c string ["a", "a", "b", "b"] + a s64 [1, 2, 3, 4] + b s64 [5, 6, 7, 8] + > + + If you want to perform the cartesian product of two list columns, you must + call `explode/2` once for each column: + + iex> df = Explorer.DataFrame.new(a: [[1, 2], [3, 4]], b: [[5, 6], [7, 8]], c: ["a", "b"]) + iex> df |> Explorer.DataFrame.explode(:a) |> Explorer.DataFrame.explode(:b) + #Explorer.DataFrame< + Polars[8 x 3] + a s64 [1, 1, 2, 2, 3, ...] + b s64 [5, 6, 5, 6, 7, ...] + c string ["a", "a", "a", "a", "b", ...] + > + """ + @doc type: :single + @spec explode(df :: DataFrame.t(), column :: column_name() | [column_name()]) :: DataFrame.t() + def explode(%DataFrame{} = df, column_or_columns) do + columns = to_existing_columns(df, List.wrap(column_or_columns)) + + dtypes = Enum.map(columns, &Map.fetch!(df.dtypes, &1)) + + unless Enum.all?(dtypes, &match?({:list, _}, &1)) do + raise ArgumentError, + "explode/2 expects list columns, but the given columns have the types: #{Shared.inspect_dtypes(dtypes)}" + end + + out_dtypes = + Enum.reduce(columns, df.dtypes, fn column, dtypes -> + Map.update!(dtypes, column, fn {:list, inner_dtype} -> inner_dtype end) + end) + + out_df = out_df(df, df.names, out_dtypes) + Shared.apply_dataframe(df, :explode, [out_df, columns]) + end + + @doc """ + Unnests one or multiple struct columns into individual columns. + + The field names in a unnested column must not exist in the dataframe + or in any other unnested columns. + + ## Examples + + iex> df = Explorer.DataFrame.new(before: [1, 2], struct: [%{x: 1, y: 2}, %{x: 3, y: 4}], after: [3, 4]) + iex> Explorer.DataFrame.unnest(df, :struct) + #Explorer.DataFrame< + Polars[2 x 4] + before s64 [1, 2] + x s64 [1, 3] + y s64 [2, 4] + after s64 [3, 4] + > + + iex> df = Explorer.DataFrame.new(struct1: [%{x: 1, y: 2}, %{x: 3, y: 4}], struct2: [%{z: 5}, %{z: 6}]) + iex> Explorer.DataFrame.unnest(df, [:struct1, :struct2]) + #Explorer.DataFrame< + Polars[2 x 3] + x s64 [1, 3] + y s64 [2, 4] + z s64 [5, 6] + > + """ + @doc type: :single + @spec unnest(df :: DataFrame.t(), column_or_columns :: column_name() | [column_name()]) :: + DataFrame.t() + def unnest(%DataFrame{} = df, column_or_columns) do + columns = to_existing_columns(df, List.wrap(column_or_columns)) + + dtypes = Enum.map(columns, &Map.fetch!(df.dtypes, &1)) + + unless Enum.all?(dtypes, &match?({:struct, _}, &1)) do + raise ArgumentError, + "unnest/2 expects struct columns, but the given columns have the types: #{Shared.inspect_dtypes(dtypes)}" + end + + {new_dtypes, new_names} = + columns + |> Enum.zip(dtypes) + |> Enum.reduce({%{}, %{}}, fn {column, {:struct, inner_dtypes}}, {new_dtypes, new_names} -> + new_dtypes = Map.merge(new_dtypes, Map.new(inner_dtypes)) + new_names = Map.put(new_names, column, Enum.map(inner_dtypes, &elem(&1, 0))) + + {new_dtypes, new_names} + end) + + out_dtypes = + df.dtypes + |> Map.drop(columns) + |> Map.merge(new_dtypes) + + out_names = + Enum.flat_map(df.names, fn name -> + case Map.fetch(new_names, name) do + {:ok, names} -> names + :error -> [name] + end + end) + + out_df = out_df(df, out_names, out_dtypes) + Shared.apply_dataframe(df, :unnest, [out_df, columns]) + end + + @doc """ + Prints the DataFrame in a tabular fashion. + + ## Options + + * `:limit` (non_neg_integer() | :infinity) - number of rows to print. + + ## Examples + + df = Explorer.Datasets.iris() + Explorer.DataFrame.print(df) + Explorer.DataFrame.print(df, limit: 1) + Explorer.DataFrame.print(df, limit: :infinity) + """ + @doc type: :introspection + @spec print(df :: DataFrame.t(), opts :: Keyword.t()) :: :ok + def print(df, opts \\ []) do + string = + if n_columns(df) == 0 do + empty_table_string() + else + non_empty_table_string(df, opts) + end + + IO.puts(string) + end + + defp empty_table_string() do + TableRex.Table.new() + |> TableRex.Table.add_rows([["Explorer DataFrame: [rows: 0, columns: 0]"]]) + |> TableRex.Table.render!() + end + + defp non_empty_table_string(df, opts) do + {rows, columns} = + if lazy?(df) do + {"???", n_columns(df)} + else + shape(df) + end + + headers = df.names + + df = + case opts[:limit] do + :infinity -> df + nrow when is_integer(nrow) and nrow >= 0 -> slice(df, 0, nrow) + _ -> slice(df, 0, @default_sample_nrows) + end + |> collect() + + types = Enum.map(df.names, &"\n<#{Shared.dtype_to_string(df.dtypes[&1])}>") + + values = + headers + |> Enum.map(&format_column(df[&1])) + |> Enum.zip_with(& &1) + + name_type = Enum.zip_with(headers, types, fn x, y -> x <> y end) + + TableRex.Table.new() + |> TableRex.Table.put_title("Explorer DataFrame: [rows: #{rows}, columns: #{columns}]") + |> TableRex.Table.put_header(name_type) + |> TableRex.Table.put_header_meta(0..columns, align: :center) + |> TableRex.Table.add_rows(values) + |> TableRex.Table.render!( + header_separator_symbol: "=", + horizontal_style: :all + ) + end + + defp format_column(%Series{} = series) do + series + |> Series.to_list() + |> format_column(0) + end + + defp format_column(list, 0) when is_list(list) do + Enum.map(list, &format_column(&1, 1)) + end + + defp format_column(list, depth) when is_list(list) do + list + |> Enum.map(&format_column(&1, depth + 1)) + |> multiline(depth, "[", "]") + end + + # TODO: Use is_non_struct_map when we require Elixir v1.17+ + defp format_column(map, depth) when is_map(map) and not is_struct(map) do + map + |> Enum.sort_by(fn {k, _} -> k end) + |> Enum.map(fn {k, v} -> "#{k}: #{format_column(v, depth + 1)}" end) + |> multiline(depth, "{", "}") + end + + defp format_column(value, depth) do + cond do + is_nil(value) -> + "nil" + + is_binary(value) and not String.valid?(value) -> + value + |> String.codepoints() + |> Enum.map(fn <> -> to_string(x) end) + |> multiline(depth, "<<", ">>") + + true -> + to_string(value) + end + end + + defp multiline(contents, depth, left, right) do + indent = String.duplicate(" ", max(depth - 1, 0)) + + if length(contents) > 1 or Enum.any?(contents, &String.contains?(&1, "\n")) do + "#{left}\n #{indent}#{Enum.join(contents, "\n " <> indent)}\n#{indent}#{right}" + else + "#{left}#{contents}#{right}" + end + end + + @doc """ + Describe numeric columns of a DataFrame. + + Groups are ignored if the dataframe is using any. + + ## Options + + * `:percentiles` - Floating point list with the percentiles to be calculated. (default: `[0.25, 0.5, 0.75]`) + + ## Examples + + iex> df = Explorer.DataFrame.new(a: ["d", nil, "f"], b: [1, 2, 3], c: ["a", "b", "c"]) + iex> Explorer.DataFrame.describe(df) + #Explorer.DataFrame< + Polars[9 x 4] + describe string ["count", "nil_count", "mean", "std", "min", ...] + a string ["2", "1", nil, nil, nil, ...] + b f64 [3.0, 0.0, 2.0, 1.0, 1.0, ...] + c string ["3", "0", nil, nil, nil, ...] + > + + iex> df = Explorer.DataFrame.new(a: ["d", nil, "f"], b: [1, 2, 3], c: ["a", "b", "c"]) + iex> Explorer.DataFrame.describe(df, percentiles: [0.3, 0.5, 0.8]) + #Explorer.DataFrame< + Polars[9 x 4] + describe string ["count", "nil_count", "mean", "std", "min", ...] + a string ["2", "1", nil, nil, nil, ...] + b f64 [3.0, 0.0, 2.0, 1.0, 1.0, ...] + c string ["3", "0", nil, nil, nil, ...] + > + """ + @doc type: :single + @spec describe(df :: DataFrame.t(), Keyword.t()) :: DataFrame.t() + def describe(df, opts \\ []) do + opts = Keyword.validate!(opts, percentiles: nil) + + if Enum.empty?(df.names) do + raise ArgumentError, "cannot describe a DataFrame without any columns" + end + + stat_cols = df.names + percentiles = process_percentiles(opts[:percentiles]) + numeric_types = Shared.numeric_types() + naive_datetime_types = Shared.naive_datetime_types() + duration_types = Shared.duration_types() + + metrics_df = + summarise_with(df, fn x -> + Enum.flat_map(stat_cols, fn c -> + dt = x[c].dtype + numeric? = dt in numeric_types + min_max? = numeric? or dt in naive_datetime_types or dt in duration_types + + [ + {"count:#{c}", Series.count(x[c])}, + {"nil_count:#{c}", Series.nil_count(x[c])}, + {"mean:#{c}", if(numeric?, do: Series.mean(x[c]))}, + {"std:#{c}", if(numeric?, do: Series.standard_deviation(x[c]))}, + {"min:#{c}", if(min_max?, do: Series.min(x[c]))} + ] ++ + for p <- percentiles do + {"#{trunc(p * 100)}%:#{c}", if(numeric?, do: Series.quantile(x[c], p))} + end ++ + [{"max:#{c}", if(min_max?, do: Series.max(x[c]))}] + end) + end) + + [metrics_row] = metrics_df |> collect() |> to_rows() + + metrics = + ["count", "nil_count", "mean", "std", "min"] ++ + for(p <- percentiles, do: "#{trunc(p * 100)}%") ++ ["max"] + + data = + metrics_df.names + |> Enum.chunk_every(length(metrics)) + |> Enum.zip_with(stat_cols, fn metrics, col -> + if df.dtypes[col] in numeric_types do + {col, Enum.map(metrics, &metrics_row[&1])} + else + {col, Enum.map(metrics, &(metrics_row[&1] && "#{metrics_row[&1]}"))} + end + end) + + new([{"describe", metrics} | data]) + end + + defp process_percentiles(nil), do: [0.25, 0.50, 0.75] + + defp process_percentiles(percentiles) do + Enum.each(percentiles, fn p -> + if p < 0 or p > 1 do + raise ArgumentError, message: "percentiles must all be in the range [0, 1]" + end + end) + + Enum.sort(percentiles) + end + + @doc """ + Counts the number of `nil` elements in each column. + + ## Examples + + iex> df = Explorer.DataFrame.new(a: ["d", nil, "f"], b: [nil, 2, nil], c: ["a", "b", "c"]) + iex> Explorer.DataFrame.nil_count(df) + #Explorer.DataFrame< + Polars[1 x 3] + a u32 [1] + b u32 [2] + c u32 [0] + > + """ + @doc type: :single + @spec nil_count(df :: DataFrame.t()) :: DataFrame.t() + def nil_count(df), do: Shared.apply_dataframe(df, :nil_count) + + @doc """ + Creates a new dataframe with unique rows and the frequencies of each. + + ## Examples + + iex> df = Explorer.DataFrame.new(a: ["a", "a", "b"], b: [1, 1, nil]) + iex> Explorer.DataFrame.frequencies(df, [:a, :b]) + #Explorer.DataFrame< + Polars[2 x 3] + a string ["a", "b"] + b s64 [1, nil] + counts u32 [2, 1] + > + """ + @doc type: :single + @spec frequencies(df :: DataFrame.t(), columns :: column_names()) :: DataFrame.t() + def frequencies(%DataFrame{} = df, [col | _] = columns) do + df + |> group_by(columns) + |> summarise_with(&[counts: Series.count(&1[col])]) + |> sort_with(&[desc: &1[:counts]]) + end + + def frequencies(_df, []), do: raise(ArgumentError, "columns cannot be empty") + + @doc """ + Calculates the pairwise correlation of numeric columns. + + The returned dataframe is the correlation matrix. + + ## Supported dtypes + + Only columns with the following dtypes are taken into account. + + * floats: #{Shared.inspect_dtypes(Shared.float_types(), backticks: true)} + * integers: #{Shared.inspect_dtypes(Shared.integer_types(), backticks: true)} + + The resultant columns are always `{:f, 64}`. + + ## Options + + * `:columns` - the selection of columns to calculate. Defaults to all numeric columns. + * `:column_name` - the name of the column with column names. Defaults to "names". + * `:ddof` - the 'delta degrees of freedom' - the divisor used in the correlation + calculation. Defaults to 1. + * `:method` refers to the correlation method. The following methods are available: + - `:pearson` : Standard correlation coefficient. (default) + - `:spearman` : Spearman rank correlation. + + ## Examples + + iex> df = Explorer.DataFrame.new(dogs: [1, 8, 3], cats: [4, 5, 2]) + iex> Explorer.DataFrame.correlation(df) + #Explorer.DataFrame< + Polars[2 x 3] + names string ["dogs", "cats"] + dogs f64 [1.0000000000000002, 0.5447047794019219] + cats f64 [0.5447047794019219, 1.0] + > + """ + @doc type: :single + @spec correlation(df :: DataFrame.t(), opts :: Keyword.t()) :: df :: DataFrame.t() + def correlation(df, opts \\ []) do + opts = + Keyword.validate!(opts, + column_name: "names", + columns: names(df), + ddof: 1, + method: :pearson + ) + + out_df = pairwise_df(df, opts) + Shared.apply_dataframe(df, :correlation, [out_df, opts[:ddof], opts[:method]]) + end + + @doc """ + Calculates the pairwise covariance of numeric columns. + + The returned dataframe is the covariance matrix. + + ## Supported dtypes + + Only columns with the following dtypes are taken into account. + + * floats: #{Shared.inspect_dtypes(Shared.float_types(), backticks: true)} + * integers: #{Shared.inspect_dtypes(Shared.integer_types(), backticks: true)} + + The resultant columns are always `{:f, 64}`. + + ## Options + + * `:columns` - the selection of columns to calculate. Defaults to all numeric columns. + * `:column_name` - the name of the column with column names. Defaults to "names". + * `:ddof` - the 'delta degrees of freedom' - the divisor used in the covariance + calculation. Defaults to 1. + + ## Examples + + iex> df = Explorer.DataFrame.new(dogs: [1, 0, 2, 1], cats: [2, 3, 0, 1]) + iex> Explorer.DataFrame.covariance(df) + #Explorer.DataFrame< + Polars[2 x 3] + names string ["dogs", "cats"] + dogs f64 [0.6666666666666666, -1.0] + cats f64 [-1.0, 1.6666666666666667] + > + """ + @doc type: :single + @spec covariance(df :: DataFrame.t(), opts :: Keyword.t()) :: df :: DataFrame.t() + def covariance(df, opts \\ []) do + opts = Keyword.validate!(opts, column_name: "names", columns: names(df), ddof: 1) + out_df = pairwise_df(df, opts) + Shared.apply_dataframe(df, :covariance, [out_df, opts[:ddof]]) + end + + # SQL + + @doc """ + Create a dataframe from the result of a SQL query on an existing dataframe. + + > ### SQL Query is Unvalidated {: .warning} + > + > Explorer does not validate the SQL query string provided. Instead it passes + > it directly to the backend. As such, the SQL dialect will be backend + > dependent and any errors will come directly from the backend. + + ## `from` Clause + + The `from` clause of the SQL query should reference a chosen table name. The + default name is `"df"`. See the examples for a custom table name. + + ## Examples + + Basic example: + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3], b: ["x", "y", "y"]) + iex> Explorer.DataFrame.sql(df, "select ARRAY_AGG(a), b from df group by b order by b") + #Explorer.DataFrame< + Polars[2 x 2] + a list[s64] [[1], [2, 3]] + b string ["x", "y"] + > + + Custom table name: + + iex> df = Explorer.DataFrame.new(a: [1, 2, 3]) + iex> Explorer.DataFrame.sql(df, "select a + 1 from my_table", table_name: "my_table") + #Explorer.DataFrame< + Polars[3 x 1] + a s64 [2, 3, 4] + > + """ + @doc type: :single + @spec sql(df :: DataFrame.t(), sql_string :: binary(), opts :: Keyword.t()) :: + df :: DataFrame.t() + def sql(%__MODULE__{} = df, sql_string, opts \\ []) + when is_binary(sql_string) and is_list(opts) do + [table_name: table_name] = Keyword.validate!(opts, table_name: "df") + Shared.apply_dataframe(df, :sql, [sql_string, table_name]) + end + + # Helpers + + defp backend_from_options!(opts) do + backend = Explorer.Shared.backend_from_options!(opts) || Explorer.Backend.get() + + if opts[:lazy] do + :"#{backend}.LazyFrame" + else + :"#{backend}.DataFrame" + end + end + + defp numeric_column?(df, name) do + Series.dtype(df[name]) in Explorer.Shared.numeric_types() + end + + defp out_df(df, names, dtypes) do + %{df | names: names, dtypes: dtypes, remote: nil} + end + + defp pairwise_df(df, opts) do + column_name = to_column_name(opts[:column_name]) + + cols = + df + |> to_existing_columns(opts[:columns]) + |> Enum.filter(fn name -> numeric_column?(df, name) end) + + out_dtypes = for col <- cols, into: %{column_name => :string}, do: {col, {:f, 64}} + out_df(df, [column_name | cols], out_dtypes) + end + + defimpl Inspect do + import Inspect.Algebra + + def inspect(df, opts) do + remote_ref = + case df.remote do + {_local_gc, _remote_pid, remote_ref} -> remote_ref + _ -> df.data.__struct__.owner_reference(df) + end + + remote = + if is_reference(remote_ref) and node(remote_ref) != node() do + concat(line(), Atom.to_string(node(remote_ref))) + else + empty() + end + + force_unfit( + concat([ + color("#Explorer.DataFrame<", :map, opts), + nest( + concat([remote, line(), Shared.apply_dataframe(df, :inspect, [opts])]), + 2 + ), + line(), + color(">", :map, opts) + ]) + ) + end + end +end + +defimpl Table.Reader, for: Explorer.DataFrame do + def init(df) do + df = Explorer.DataFrame.collect(df) + columns = Explorer.DataFrame.names(df) + + data = + Enum.map(columns, fn column -> + df + |> Explorer.DataFrame.pull(column) + |> Explorer.Series.to_enum() + end) + + {:columns, %{columns: columns, count: Explorer.DataFrame.n_rows(df)}, data} + end +end diff --git a/deps/explorer/lib/explorer/datasets.ex b/deps/explorer/lib/explorer/datasets.ex new file mode 100644 index 0000000000000000000000000000000000000000..fcd7369cf17cbc19187544cfbc94892b501d225f --- /dev/null +++ b/deps/explorer/lib/explorer/datasets.ex @@ -0,0 +1,78 @@ +defmodule Explorer.Datasets do + @moduledoc """ + Datasets used in examples and exploration. + + Note those datasets are not available inside Elixir releases + (see `mix release`), which is the usual way to deploy Elixir + in production. Therefore, if you need one of those datasets + in production, you must download the source files to your + own application `priv` directory and load them yourself. + For example: + + Explorer.DataFrame.from_csv!(Application.app_dir(:my_app, "priv/iris.csv")) + """ + alias Explorer.DataFrame + + @datasets_dir Path.join(File.cwd!(), "datasets") + + @doc """ + CO2 emissions from fossil fuels since 2010, by country + + ## Citation + + Boden, T.A., G. Marland, and R.J. Andres. 2013. Global, Regional, and National Fossil-Fuel CO2 + Emissions. Carbon Dioxide Information Analysis Center, Oak Ridge National Laboratory, U.S. + Department of Energy, Oak Ridge, Tenn., U.S.A. doi 10.3334/CDIAC/00001_V2013 + """ + def fossil_fuels, do: read_dataset!("fossil_fuels") + + @doc """ + Wine Dataset. + + The data is the result of a chemical analysis of wines grown in the same + region in Italy but derived from three different cultivars. The analysis + determined the quantities of 13 constituents found in each of the three + types of wines. + + Downloaded and modified from: https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data + + ## Citation + + Aeberhard,Stefan and Forina,M.. (1991). Wine. UCI Machine Learning Repository. https://doi.org/10.24432/C5PC7J. + """ + def wine, do: read_dataset!("wine") + + @doc """ + Iris Dataset. + + This classic dataset was collected by Edgar Anderson in 1936 + and made famous by R. A. Fisher's 1936 paper. It consists of + several measurements of three species of Iris (Iris setosa, + Iris virginica and Iris versicolor). + + Downloaded and modified from: https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data + + ## Citation + + Fisher,R. A.. (1988). Iris. UCI Machine Learning Repository. https://doi.org/10.24432/C56C76. + """ + def iris, do: read_dataset!("iris") + + defp read_dataset!(name) do + key = {:explorer_datasets, name} + + # Persistent term is used as a cache, in order to avoid + # several calls to the filesystem. This is mostly useful + # to speed up reads in tests. + case :persistent_term.get(key, nil) do + nil -> + @datasets_dir + |> Path.join("#{name}.csv") + |> DataFrame.from_csv!() + |> tap(&:persistent_term.put(key, &1)) + + %DataFrame{} = df -> + df + end + end +end diff --git a/deps/explorer/lib/explorer/duration.ex b/deps/explorer/lib/explorer/duration.ex new file mode 100644 index 0000000000000000000000000000000000000000..b833eac334203fb951f93974cdf1eb180767b79e --- /dev/null +++ b/deps/explorer/lib/explorer/duration.ex @@ -0,0 +1,71 @@ +defmodule Explorer.Duration do + @moduledoc """ + Represents a duration of time. + + The value is represented by an integer, and the precision can be one + of the following: + + * `:millisecond` + * `:microsecond` + * `:nanosecond` + """ + alias Explorer.Duration + + @enforce_keys [:value, :precision] + defstruct [:value, :precision] + + @type precision :: :millisecond | :microsecond | :nanosecond + @type t :: %__MODULE__{value: integer(), precision: precision()} + + # Nanosecond constants + @us_ns 1_000 + @ms_ns 1_000 * @us_ns + @sec_ns 1_000 * @ms_ns + @min_ns 60 * @sec_ns + @hour_ns 60 * @min_ns + @day_ns 24 * @hour_ns + + def to_string(%Explorer.Duration{value: value, precision: precision}) do + case precision do + :millisecond -> format_nanoseconds(value * @ms_ns) + :microsecond -> format_nanoseconds(value * @us_ns) + :nanosecond -> format_nanoseconds(value) + end + end + + defp format_nanoseconds(nanoseconds) when is_integer(nanoseconds) do + result = nanoseconds |> abs |> format_pos_nanoseconds() + + if nanoseconds < 0 do + "-" <> result + else + result + end + end + + defp format_pos_nanoseconds(nanoseconds) when is_integer(nanoseconds) and nanoseconds >= 0 do + [d: @day_ns, h: @hour_ns, m: @min_ns, s: @sec_ns, ms: @ms_ns, us: @us_ns, ns: 1] + |> Enum.flat_map_reduce(nanoseconds, fn {unit, ns_per_unit}, ns -> + if ns >= ns_per_unit do + {[{unit, div(ns, ns_per_unit)}], rem(ns, ns_per_unit)} + else + {[], ns} + end + end) + |> then(fn {parts_reversed, _} -> parts_reversed end) + |> Enum.map_join(" ", fn {unit, value} -> "#{value}#{unit}" end) + |> case do + "" -> "0" + result -> result + end + end + + defimpl String.Chars do + def to_string(%Duration{} = duration), do: Duration.to_string(duration) + end + + defimpl Inspect do + def inspect(%Duration{} = duration, _), + do: "#Explorer.Duration[" <> Duration.to_string(duration) <> "]" + end +end diff --git a/deps/explorer/lib/explorer/fss.ex b/deps/explorer/lib/explorer/fss.ex new file mode 100644 index 0000000000000000000000000000000000000000..310c13c55a1e9a51dfa18aefa3423fd77c36b014 --- /dev/null +++ b/deps/explorer/lib/explorer/fss.ex @@ -0,0 +1,9 @@ +defprotocol Explorer.FSS do + @moduledoc false + + @doc """ + Downloads a given entry to a path. + """ + @spec download(t(), path :: Path.t()) :: :ok | {:error, Exception.t()} + def download(entry, path) +end diff --git a/deps/explorer/lib/explorer/fss/http.ex b/deps/explorer/lib/explorer/fss/http.ex new file mode 100644 index 0000000000000000000000000000000000000000..cddd0bf53963282171b3ff25959875cebde2e432 --- /dev/null +++ b/deps/explorer/lib/explorer/fss/http.ex @@ -0,0 +1,16 @@ +defimpl Explorer.FSS, for: FSS.HTTP.Entry do + alias Explorer.FSS.Utils + + def download(entry, path) do + with :ok <- Utils.assert_regular_path(path) do + headers = entry.config.headers + collectable = File.stream!(path) + + case Utils.download(entry.url, collectable, headers: headers) do + {:ok, _collectable} -> :ok + {:error, _message, 404} -> {:error, ArgumentError.exception("resource not found (404)")} + {:error, exception, _status} -> {:error, exception} + end + end + end +end diff --git a/deps/explorer/lib/explorer/fss/s3.ex b/deps/explorer/lib/explorer/fss/s3.ex new file mode 100644 index 0000000000000000000000000000000000000000..5a83ed6bc3c13c8580dc7d16ecb1e2a7a6432496 --- /dev/null +++ b/deps/explorer/lib/explorer/fss/s3.ex @@ -0,0 +1,75 @@ +defimpl Explorer.FSS, for: FSS.S3.Entry do + alias Explorer.FSS.Utils + + def download(entry, path) do + with :ok <- Utils.assert_regular_path(path), + {:ok, url} <- url(entry) do + headers = headers(entry, :get, url, []) + collectable = File.stream!(path) + + case Utils.download(url, collectable, headers: headers) do + {:ok, _collectable} -> :ok + {:error, _message, 404} -> {:error, ArgumentError.exception("resource not found (404)")} + {:error, exception, _status} -> {:error, exception} + end + end + end + + defp url(%FSS.S3.Entry{} = entry) do + config = entry.config + + uri = URI.parse(config.endpoint) + + maybe_uri = + if is_nil(config.bucket) do + {:ok, uri} + else + append_path(uri, "/" <> config.bucket) + end + + with {:ok, uri} <- maybe_uri, + {:ok, uri_with_key} <- append_path(uri, "/" <> entry.key) do + {:ok, URI.to_string(uri_with_key)} + end + end + + # Once we depend on Elixir ~> 1.15, we can use `URI.append_path/2`. + defp append_path(%URI{}, "//" <> _ = path) do + {:error, ArgumentError.exception(~s|path cannot start with "//", got: #{inspect(path)}|)} + end + + defp append_path(%URI{path: path} = uri, "/" <> rest = all) do + updated_uri = + cond do + path == nil -> %{uri | path: all} + path != "" and :binary.last(path) == ?/ -> %{uri | path: path <> rest} + true -> %{uri | path: path <> all} + end + + {:ok, updated_uri} + end + + defp headers(%FSS.S3.Entry{} = entry, method, url, headers, body \\ nil) do + now = NaiveDateTime.utc_now() |> NaiveDateTime.to_erl() + %{host: host} = URI.parse(url) + headers = [{"Host", host} | headers] + + headers = + if entry.config.token, + do: [{"X-Amz-Security-Token", entry.config.token} | headers], + else: headers + + :aws_signature.sign_v4( + entry.config.access_key_id, + entry.config.secret_access_key, + entry.config.region, + "s3", + now, + Atom.to_string(method), + url, + headers, + body || "", + uri_encode_path: false + ) + end +end diff --git a/deps/explorer/lib/explorer/fss/utils.ex b/deps/explorer/lib/explorer/fss/utils.ex new file mode 100644 index 0000000000000000000000000000000000000000..1f36c591b96e34fca054d8d6a5afba04a5d5c003 --- /dev/null +++ b/deps/explorer/lib/explorer/fss/utils.ex @@ -0,0 +1,215 @@ +defmodule Explorer.FSS.Utils do + # Copied from Livebook's code: https://github.com/livebook-dev/livebook/blob/481d39d7edbb7498c8372d0e35f143935e0aeb92/lib/livebook/file_system/utils.ex + @moduledoc false + + @type path() :: String.t() + @type status() :: non_neg_integer() + + @doc """ + Asserts that the given path is a regular file path. + + It returns an error in case the file is a directory. + """ + @spec assert_regular_path(path()) :: :ok | {:error, Exception.t()} + def assert_regular_path(path) do + if regular_path?(path) do + :ok + else + {:error, ArgumentError.exception("expected a regular file path, got: #{inspect(path)}")} + end + end + + @doc """ + Checks if the given path describes a regular file. + """ + @spec regular_path?(path()) :: boolean() + def regular_path?(path) do + not String.ends_with?(path, "/") + end + + @doc """ + Downloads resource at the given URL into `collectable`. + + If collectable raises and error, it is rescued and an error tuple + is returned. + + ## Options + + * `:headers` - request headers + + """ + @spec download(String.t(), Collectable.t(), keyword()) :: + {:ok, Collectable.t()} | {:error, Exception.t(), status()} + def download(url, collectable, opts \\ []) do + headers = build_headers(opts[:headers] || []) + + request = {url, headers} + http_opts = [ssl: http_ssl_opts()] + + caller = self() + + receiver = fn reply_info -> + request_id = elem(reply_info, 0) + + # Cancel the request if the caller terminates + if Process.alive?(caller) do + send(caller, {:http, reply_info}) + else + :httpc.cancel_request(request_id) + end + end + + opts = [stream: :self, sync: false, receiver: receiver] + + {:ok, request_id} = :httpc.request(:get, request, http_opts, opts) + + try do + {acc, collector} = Collectable.into(collectable) + + try do + download_loop(%{ + request_id: request_id, + total_size: nil, + size: nil, + acc: acc, + collector: collector + }) + catch + kind, reason -> + collector.(acc, :halt) + :httpc.cancel_request(request_id) + exception = Exception.normalize(kind, reason, __STACKTRACE__) + {:error, exception, nil} + else + {:ok, state} -> + acc = state.collector.(state.acc, :done) + {:ok, acc} + + {:error, message, status} -> + collector.(acc, :halt) + :httpc.cancel_request(request_id) + {:error, ArgumentError.exception(message), status} + end + catch + kind, reason -> + :httpc.cancel_request(request_id) + exception = Exception.normalize(kind, reason, __STACKTRACE__) + {:error, exception, nil} + end + end + + defp download_loop(state) do + receive do + {:http, reply_info} when elem(reply_info, 0) == state.request_id -> + download_receive(state, reply_info) + end + end + + defp download_receive(_state, {_, {:error, error}}) do + {:error, "reason: #{inspect(error)}", nil} + end + + defp download_receive(state, {_, {{_, 200, _}, _headers, body}}) do + acc = state.collector.(state.acc, {:cont, body}) + {:ok, %{state | acc: acc}} + end + + defp download_receive(_state, {_, {{_, status, _}, _headers, _body}}) do + {:error, "got HTTP status: #{status}", status} + end + + defp download_receive(state, {_, :stream_start, headers}) do + total_size = total_size(headers) + download_loop(%{state | total_size: total_size, size: 0}) + end + + defp download_receive(state, {_, :stream, body_part}) do + acc = state.collector.(state.acc, {:cont, body_part}) + state = %{state | acc: acc} + + part_size = byte_size(body_part) + state = update_in(state.size, &(&1 + part_size)) + download_loop(state) + end + + defp download_receive(state, {_, :stream_end, _headers}) do + {:ok, state} + end + + defp total_size(headers) do + case List.keyfind(headers, ~c"content-length", 0) do + {_, content_length} -> + List.to_integer(content_length) + + _ -> + nil + end + end + + defp build_headers(entries) do + headers = + Enum.map(entries, fn {key, value} -> + {to_charlist(key), to_charlist(value)} + end) + + [{~c"user-agent", ~c"elixir-explorer"} | headers] + end + + # Load SSL certificates + + defp http_ssl_opts() do + # TODO: Remove castore fallback when we require Elixir v1.17+ + # Use secure options, see https://gist.github.com/jonatanklosko/5e20ca84127f6b31bbe3906498e1a1d7 + [ + verify: :verify_peer, + # We need to increase depth because the default value is 1. + # See: https://erlef.github.io/security-wg/secure_coding_and_deployment_hardening/ssl + depth: 3, + customize_hostname_check: [ + match_fun: :public_key.pkix_verify_hostname_match_fun(:https) + ] + ] ++ cacerts_opts() + end + + defp cacerts_opts do + cond do + certs = otp_cacerts() -> + [cacerts: certs] + + Application.spec(:castore, :vsn) -> + [cacertfile: Application.app_dir(:castore, "priv/cacerts.pem")] + + true -> + IO.warn(""" + No certificate trust store was found. + + A certificate trust store is required in + order to download locales for your configuration. + Since elixir_make could not detect a system + installed certificate trust store one of the + following actions may be taken: + + 1. Use OTP 25+ on an OS that has built-in certificate + trust store. + + 2. Install the hex package `castore`. It will + be automatically detected after recompilation. + + """) + + [] + end + end + + defp otp_cacerts do + if System.otp_release() >= "25" do + # cacerts_get/0 raises if no certs found + try do + :public_key.cacerts_get() + rescue + _ -> + nil + end + end + end +end diff --git a/deps/explorer/lib/explorer/polars_backend.ex b/deps/explorer/lib/explorer/polars_backend.ex new file mode 100644 index 0000000000000000000000000000000000000000..ab4a10eed3499456d742d22dff7ee9d7c3e3b434 --- /dev/null +++ b/deps/explorer/lib/explorer/polars_backend.ex @@ -0,0 +1,5 @@ +defmodule Explorer.PolarsBackend do + @moduledoc """ + The Explorer backend for Polars. + """ +end diff --git a/deps/explorer/lib/explorer/polars_backend/data_frame.ex b/deps/explorer/lib/explorer/polars_backend/data_frame.ex new file mode 100644 index 0000000000000000000000000000000000000000..fe5848269bf67c41e1a3154a039f43048ce6d0b2 --- /dev/null +++ b/deps/explorer/lib/explorer/polars_backend/data_frame.ex @@ -0,0 +1,944 @@ +defmodule Explorer.PolarsBackend.DataFrame do + @moduledoc false + + alias Explorer.DataFrame, as: DataFrame + alias Explorer.PolarsBackend.LazyFrame + alias Explorer.PolarsBackend.Native + alias Explorer.PolarsBackend.Series, as: PolarsSeries + alias Explorer.PolarsBackend.Shared + alias Explorer.Series, as: Series + + alias FSS.HTTP + alias FSS.Local + alias FSS.S3 + + import Explorer.PolarsBackend.Expression, only: [to_expr: 1] + + defstruct resource: nil + + @type t :: %__MODULE__{resource: reference()} + + @behaviour Explorer.Backend.DataFrame + + # IO + + @compile {:no_warn_undefined, Adbc.Connection} + @impl true + def from_query(conn, query, params) do + adbc_result = + Adbc.Connection.query_pointer(conn, query, params, fn pointer, _num_rows -> + Explorer.PolarsBackend.Native.df_from_arrow_stream_pointer(pointer) + end) + + with {:ok, df_result} <- adbc_result, + {:ok, df} <- df_result, + do: Shared.create_dataframe(df) + end + + @impl true + def from_csv( + %module{} = entry, + dtypes, + delimiter, + nil_values, + skip_rows, + skip_rows_after_header, + header?, + encoding, + max_rows, + columns, + infer_schema_length, + parse_dates, + eol_delimiter + ) + when module in [S3.Entry, HTTP.Entry] do + path = Shared.build_path_for_entry(entry) + + with :ok <- Explorer.FSS.download(entry, path) do + entry = Local.from_path(path) + + result = + from_csv( + entry, + dtypes, + delimiter, + nil_values, + skip_rows, + skip_rows_after_header, + header?, + encoding, + max_rows, + columns, + infer_schema_length, + parse_dates, + eol_delimiter + ) + + File.rm(path) + result + end + end + + @impl true + def from_csv( + %Local.Entry{} = entry, + dtypes, + <>, + nil_values, + skip_rows, + skip_rows_after_header, + header?, + encoding, + max_rows, + columns, + infer_schema_length, + parse_dates, + eol_delimiter + ) do + infer_schema_length = + if infer_schema_length == nil, + do: max_rows, + else: infer_schema_length + + {columns, with_projection} = column_names_or_projection(columns) + + df = + Native.df_from_csv( + entry.path, + infer_schema_length, + header?, + max_rows, + skip_rows, + skip_rows_after_header, + with_projection, + delimiter, + true, + columns, + dtypes, + encoding, + nil_values, + parse_dates, + char_byte(eol_delimiter) + ) + + case df do + {:ok, df} -> Shared.create_dataframe(df) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + # In case column names are given, it returns the columns. + # Otherwise returns the list of integers, selecting the "projection" of columns. + defp column_names_or_projection(nil), do: {nil, nil} + + defp column_names_or_projection(list) do + cond do + Enum.all?(list, &is_binary/1) -> + {list, nil} + + Enum.all?(list, &is_integer/1) -> + {nil, list} + + true -> + {nil, nil} + end + end + + @impl true + def to_csv(%DataFrame{data: df}, %Local.Entry{} = entry, header?, delimiter, _streaming) do + <> = delimiter + + case Native.df_to_csv(df, entry.path, header?, delimiter) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_csv(%DataFrame{data: df}, %S3.Entry{} = entry, header?, delimiter, _streaming) do + <> = delimiter + + case Native.df_to_csv_cloud(df, entry, header?, delimiter) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def dump_csv(%DataFrame{} = df, header?, <>) do + case Native.df_dump_csv(df.data, header?, delimiter) do + {:ok, string} -> {:ok, string} + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def load_csv( + contents, + dtypes, + <>, + nil_values, + skip_rows, + skip_rows_after_header, + header?, + encoding, + max_rows, + columns, + infer_schema_length, + parse_dates, + eol_delimiter + ) do + infer_schema_length = + if infer_schema_length == nil, + do: max_rows, + else: infer_schema_length + + {columns, with_projection} = column_names_or_projection(columns) + + df = + Native.df_load_csv( + contents, + infer_schema_length, + header?, + max_rows, + skip_rows, + skip_rows_after_header, + with_projection, + delimiter, + true, + columns, + dtypes, + encoding, + nil_values, + parse_dates, + char_byte(eol_delimiter) + ) + + case df do + {:ok, df} -> Shared.create_dataframe(df) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + defp char_byte(nil), do: nil + defp char_byte(<>), do: char + + @impl true + + def from_ndjson(%module{} = entry, infer_schema_length, batch_size) + when module in [S3.Entry, HTTP.Entry] do + path = Shared.build_path_for_entry(entry) + + with :ok <- Explorer.FSS.download(entry, path) do + entry = Local.from_path(path) + + result = from_ndjson(entry, infer_schema_length, batch_size) + + File.rm(path) + result + end + end + + @impl true + def from_ndjson(%Local.Entry{} = entry, infer_schema_length, batch_size) do + case Native.df_from_ndjson(entry.path, infer_schema_length, batch_size) do + {:ok, df} -> Shared.create_dataframe(df) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_ndjson(%DataFrame{data: df}, %Local.Entry{} = entry) do + case Native.df_to_ndjson(df, entry.path) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_ndjson(%DataFrame{data: df}, %S3.Entry{} = entry) do + case Native.df_to_ndjson_cloud(df, entry) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def dump_ndjson(%DataFrame{} = df) do + case Native.df_dump_ndjson(df.data) do + {:ok, string} -> {:ok, string} + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def load_ndjson(contents, infer_schema_length, batch_size) when is_binary(contents) do + case Native.df_load_ndjson(contents, infer_schema_length, batch_size) do + {:ok, df} -> Shared.create_dataframe(df) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def from_parquet(%S3.Entry{} = entry, max_rows, columns, _rechunk) do + # We first read using a lazy dataframe, then we collect. + with {:ok, ldf} <- Native.lf_from_parquet_cloud(entry, max_rows, columns), + {:ok, df} <- Native.lf_compute(ldf) do + Shared.create_dataframe(df) + end + end + + @impl true + def from_parquet(%HTTP.Entry{} = entry, max_rows, columns, rechunk) do + path = Shared.build_path_for_entry(entry) + + with :ok <- Explorer.FSS.download(entry, path) do + entry = Local.from_path(path) + + result = from_parquet(entry, max_rows, columns, rechunk) + + File.rm(path) + result + end + end + + @impl true + def from_parquet(%Local.Entry{} = entry, max_rows, columns, rechunk) do + {columns, with_projection} = column_names_or_projection(columns) + + df = + Native.df_from_parquet( + entry.path, + max_rows, + columns, + with_projection, + rechunk + ) + + case df do + {:ok, df} -> Shared.create_dataframe(df) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_parquet( + %DataFrame{data: df}, + %Local.Entry{} = entry, + {compression, compression_level}, + _streaming + ) do + case Native.df_to_parquet(df, entry.path, parquet_compression(compression, compression_level)) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_parquet( + %DataFrame{data: df}, + %S3.Entry{} = entry, + {compression, compression_level}, + _streaming + ) do + case Native.df_to_parquet_cloud( + df, + entry, + parquet_compression(compression, compression_level) + ) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def dump_parquet(%DataFrame{data: df}, {compression, compression_level}) do + case Native.df_dump_parquet(df, parquet_compression(compression, compression_level)) do + {:ok, string} -> {:ok, string} + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + defp parquet_compression(nil, _), do: :uncompressed + + defp parquet_compression(algorithm, level) when algorithm in ~w(gzip brotli zstd)a do + {algorithm, level} + end + + defp parquet_compression(algorithm, _) when algorithm in ~w(snappy lz4raw)a, do: algorithm + + @impl true + def load_parquet(contents) when is_binary(contents) do + case Native.df_load_parquet(contents) do + {:ok, df} -> Shared.create_dataframe(df) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def from_ipc(%module{} = entry, columns) when module in [S3.Entry, HTTP.Entry] do + path = Shared.build_path_for_entry(entry) + + with :ok <- Explorer.FSS.download(entry, path) do + entry = Local.from_path(path) + + result = from_ipc(entry, columns) + + File.rm(path) + result + end + end + + @impl true + def from_ipc(%Local.Entry{} = entry, columns) do + {columns, projection} = column_names_or_projection(columns) + + case Native.df_from_ipc(entry.path, columns, projection) do + {:ok, df} -> Shared.create_dataframe(df) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_ipc(%DataFrame{data: df}, %Local.Entry{} = entry, {compression, _level}, _streaming) do + case Native.df_to_ipc(df, entry.path, maybe_atom_to_string(compression)) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_ipc(%DataFrame{data: df}, %S3.Entry{} = entry, {compression, _level}, _streaming) do + case Native.df_to_ipc_cloud(df, entry, maybe_atom_to_string(compression)) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def dump_ipc(%DataFrame{data: df}, {compression, _level}) do + case Native.df_dump_ipc(df, maybe_atom_to_string(compression)) do + {:ok, string} -> {:ok, string} + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def load_ipc(contents, columns) when is_binary(contents) do + {columns, projection} = column_names_or_projection(columns) + + case Native.df_load_ipc(contents, columns, projection) do + {:ok, df} -> Shared.create_dataframe(df) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def from_ipc_stream(%module{} = entry, columns) when module in [S3.Entry, HTTP.Entry] do + path = Shared.build_path_for_entry(entry) + + with :ok <- Explorer.FSS.download(entry, path) do + entry = Local.from_path(path) + + result = from_ipc_stream(entry, columns) + + File.rm(path) + result + end + end + + @impl true + def from_ipc_stream(%Local.Entry{} = entry, columns) do + {columns, projection} = column_names_or_projection(columns) + + case Native.df_from_ipc_stream(entry.path, columns, projection) do + {:ok, df} -> Shared.create_dataframe(df) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_ipc_stream(%DataFrame{data: df}, %Local.Entry{} = entry, {compression, _level}) do + case Native.df_to_ipc_stream(df, entry.path, maybe_atom_to_string(compression)) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_ipc_stream(%DataFrame{data: df}, %S3.Entry{} = entry, {compression, _level}) do + case Native.df_to_ipc_stream_cloud(df, entry, maybe_atom_to_string(compression)) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def dump_ipc_stream(%DataFrame{data: df}, {compression, _level}) do + case Native.df_dump_ipc_stream(df, maybe_atom_to_string(compression)) do + {:ok, string} -> {:ok, string} + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def load_ipc_stream(contents, columns) when is_binary(contents) do + {columns, projection} = column_names_or_projection(columns) + + case Native.df_load_ipc_stream(contents, columns, projection) do + {:ok, df} -> Shared.create_dataframe(df) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + defp maybe_atom_to_string(nil), do: nil + defp maybe_atom_to_string(atom) when is_atom(atom), do: Atom.to_string(atom) + + # Conversion + + @impl true + def lazy, do: Explorer.PolarsBackend.LazyFrame + + @impl true + def lazy(df) do + case Native.df_lazy(df.data) do + {:ok, polars_df} -> + %{df | data: polars_df} + + {:error, error} -> + raise "error when assigning lazy frame: #{inspect(error)}" + end + end + + @impl true + def compute(df), do: df + + @impl true + def from_tabular(tabular, io_dtypes) do + dtypes = Map.new(io_dtypes) + {_, %{columns: keys}, _} = reader = init_reader!(tabular) + columns = Table.to_columns(reader) + + keys + |> Enum.map(fn key -> + column_name = to_column_name!(key) + values = Enum.to_list(columns[key]) + dtype = Map.get(dtypes, column_name) + + column_name + |> series_from_list!(values, dtype) + |> then(fn series -> + if not is_nil(dtype) and series.dtype != dtype do + PolarsSeries.cast(series, dtype) + else + series + end + end) + end) + |> from_series_list() + end + + defp init_reader!(tabular) do + with :none <- Table.Reader.init(tabular) do + raise ArgumentError, "expected valid tabular data, but got: #{inspect(tabular)}" + end + end + + @impl true + def from_series(pairs) when is_list(pairs) do + pairs + |> Enum.map(fn {name, series} -> + PolarsSeries.rename(series, name) + end) + |> from_series_list() + end + + defp from_series_list(list) do + list = Enum.map(list, & &1.data) + + Shared.apply(:df_from_series, [list]) + |> Shared.create_dataframe!() + end + + defp to_column_name!(column_name) when is_binary(column_name), do: column_name + defp to_column_name!(column_name) when is_atom(column_name), do: Atom.to_string(column_name) + + defp to_column_name!(column_name) do + raise ArgumentError, + "expected column name to be either string or atom, got: #{inspect(column_name)}" + end + + # Like `Explorer.Series.from_list/2`, but gives a better error message with the series name. + defp series_from_list!(name, list, dtype) do + type = Explorer.Shared.dtype_from_list!(list, dtype) + series = Shared.from_list(list, type, name) + Explorer.Backend.Series.new(series, type) + rescue + e -> + raise ArgumentError, "cannot create series #{inspect(name)}: " <> Exception.message(e) + end + + @impl true + def to_rows(%DataFrame{data: polars_df, names: names} = df, atom_keys?) do + keys = if atom_keys?, do: Enum.map(names, &String.to_atom/1), else: df.names + + names + |> Enum.map(fn name -> + {:ok, series} = Native.df_pull(polars_df, name) + {:ok, list} = Native.s_to_list(series) + list + end) + |> Enum.zip_with(fn row -> keys |> Enum.zip(row) |> Map.new() end) + end + + @impl true + def to_rows_stream(%DataFrame{} = df, atom_keys?, chunk_size) do + Range.new(0, n_rows(df) - 1, chunk_size) + |> Stream.map(&slice(df, &1, chunk_size)) + |> Stream.flat_map(&to_rows(&1, atom_keys?)) + end + + # Ownership + + @impl true + def owner_reference(df), do: df.data.resource + + @impl true + def owner_export(df), do: dump_ipc(df, {nil, nil}) + + @impl true + def owner_import(term), do: load_ipc(term, nil) + + # Introspection + + @impl true + def n_rows(df), do: Shared.apply_dataframe(df, :df_n_rows) + + # Single table verbs + + @impl true + def head(%DataFrame{} = df, rows) do + df + |> lazy() + |> LazyFrame.head(rows) + |> LazyFrame.compute() + end + + @impl true + def tail(%DataFrame{} = df, rows) do + df + |> lazy() + |> LazyFrame.tail(rows) + |> LazyFrame.compute() + end + + @impl true + def select(df, out_df) do + df + |> lazy() + |> LazyFrame.select(out_df) + |> LazyFrame.compute() + end + + @impl true + def mask(df, %Series{} = mask), + do: Shared.apply_dataframe(df, df, :df_mask, [mask.data]) + + @impl true + def filter_with(df, out_df, %Explorer.Backend.LazySeries{} = lseries) do + df + |> lazy() + |> LazyFrame.filter_with(out_df, lseries) + |> LazyFrame.compute() + end + + @impl true + def mutate_with(%DataFrame{} = df, %DataFrame{} = out_df, column_pairs) do + df + |> lazy() + |> LazyFrame.mutate_with(out_df, column_pairs) + |> LazyFrame.compute() + end + + @impl true + def put(%DataFrame{} = df, %DataFrame{} = out_df, new_column_name, series) do + series = PolarsSeries.rename(Explorer.Series.collect(series), new_column_name) + + Shared.apply_dataframe(df, out_df, :df_put_column, [series.data]) + end + + @impl true + def nil_count(%DataFrame{} = df) do + Shared.apply(:df_nil_count, [df.data]) + |> Shared.create_dataframe!() + end + + @impl true + def sort_with( + %DataFrame{} = df, + out_df, + column_pairs, + maintain_order?, + multithreaded?, + nulls_last? + ) + when is_boolean(maintain_order?) and is_boolean(multithreaded?) and + is_boolean(nulls_last?) do + if Enum.all?(column_pairs, fn {_, %{op: op}} -> op == :column end) do + {directions, column_names} = + column_pairs + |> Enum.map(fn {dir, %{args: [col]}} -> {dir == :desc, col} end) + |> Enum.unzip() + + Shared.apply_dataframe(df, out_df, :df_sort_by, [ + column_names, + directions, + maintain_order?, + multithreaded?, + nulls_last?, + df.groups + ]) + else + {directions, expressions} = + column_pairs + |> Enum.map(fn {dir, lazy_series} -> {dir == :desc, to_expr(lazy_series)} end) + |> Enum.unzip() + + Shared.apply_dataframe(df, out_df, :df_sort_with, [ + expressions, + directions, + maintain_order?, + multithreaded?, + nulls_last?, + df.groups + ]) + end + end + + @impl true + def distinct(%DataFrame{} = df, %DataFrame{} = out_df, columns) do + df + |> lazy() + |> LazyFrame.distinct(out_df, columns) + |> LazyFrame.compute() + end + + @impl true + def rename(%DataFrame{} = df, %DataFrame{} = out_df, pairs) do + df + |> lazy() + |> LazyFrame.rename(out_df, pairs) + |> LazyFrame.compute() + end + + @impl true + def dummies(df, out_df, names), + do: Shared.apply_dataframe(df, out_df, :df_to_dummies, [names]) + + @impl true + def sample(df, n, replacement, shuffle, seed) when is_integer(n) do + Shared.apply_dataframe(df, df, :df_sample_n, [n, replacement, shuffle, seed, df.groups]) + end + + @impl true + def sample(df, frac, replacement, shuffle, seed) when is_float(frac) do + # Avoid grouping if the sample is of the entire DF. + groups = if frac == 1.0, do: [], else: df.groups + + Shared.apply_dataframe(df, df, :df_sample_frac, [frac, replacement, shuffle, seed, groups]) + end + + @impl true + def pull(df, column), do: Shared.apply_dataframe(df, :df_pull, [column]) + + @impl true + def slice(%DataFrame{} = df, row_indices) when is_list(row_indices) do + Shared.apply_dataframe(df, df, :df_slice_by_indices, [row_indices, df.groups]) + end + + @impl true + def slice(%DataFrame{} = df, %Series{} = row_indices) do + Shared.apply_dataframe(df, df, :df_slice_by_series, [row_indices.data, df.groups]) + end + + # TODO: If we expose group_indices at the Explorer.DataFrame level, + # then we can implement this in pure Elixir. + @impl true + def slice(%DataFrame{groups: [_ | _]} = df, %Range{} = range) do + {:ok, group_indices} = Native.df_group_indices(df.data, df.groups) + + idx = + Enum.map(group_indices, fn series -> + {:ok, size} = Native.s_size(series) + indices = Enum.slice(0..(size - 1)//1, range) + + {:ok, sliced} = Native.s_slice_by_indices(series, indices) + sliced + end) + + {:ok, idx} = Native.s_concat(idx) + + Shared.apply_dataframe(df, df, :df_slice_by_series, [idx, []]) + end + + @impl true + def slice(%DataFrame{} = df, offset, length) + when is_integer(offset) and is_integer(length), + do: Shared.apply_dataframe(df, df, :df_slice, [offset, length, df.groups]) + + @impl true + def drop_nil(df, columns) do + df + |> lazy() + |> LazyFrame.drop_nil(columns) + |> LazyFrame.compute() + end + + @impl true + def pivot_longer(df, out_df, cols_to_pivot, cols_to_keep, names_to, values_to) do + df + |> lazy() + |> LazyFrame.pivot_longer(out_df, cols_to_pivot, cols_to_keep, names_to, values_to) + |> LazyFrame.compute() + end + + @impl true + def pivot_wider(df, id_columns, names_from, values_from, names_prefix) do + names_prefix_optional = unless names_prefix == "", do: names_prefix + + Shared.apply(:df_pivot_wider, [ + df.data, + id_columns, + names_from, + values_from, + names_prefix_optional + ]) + |> Shared.create_dataframe!() + end + + @impl true + def transpose(df, out_df, keep_names_as, new_col_names) do + Shared.apply_dataframe(df, out_df, :df_transpose, [keep_names_as, new_col_names]) + end + + @impl true + def explode(df, out_df, columns) do + df + |> lazy() + |> LazyFrame.explode(out_df, columns) + |> LazyFrame.compute() + end + + @impl true + def unnest(df, out_df, columns) do + df + |> lazy() + |> LazyFrame.unnest(out_df, columns) + |> LazyFrame.compute() + end + + @impl true + def correlation(df, out_df, ddof, method) do + pairwise(df, out_df, fn left, right -> + PolarsSeries.correlation(left, right, ddof, method) + end) + end + + @impl true + def covariance(df, out_df, ddof) do + pairwise(df, out_df, fn left, right -> PolarsSeries.covariance(left, right, ddof) end) + end + + # Two or more table verbs + + @impl true + def join([left, right], out_df, on, how) do + left = lazy(left) + right = lazy(right) + + ldf = LazyFrame.join([left, right], out_df, on, how) + LazyFrame.compute(ldf) + end + + @impl true + def concat_rows([_head | _tail] = dfs, out_df) do + lazy_dfs = Enum.map(dfs, &lazy/1) + + lazy_dfs + |> LazyFrame.concat_rows(out_df) + |> LazyFrame.compute() + end + + @impl true + def concat_columns([head | tail], out_df) do + n_rows = n_rows(head) + + tail = + Enum.map(tail, fn df -> + if n_rows(df) != n_rows do + raise ArgumentError, "all dataframes must have the same number of rows" + end + + df.data + end) + + out_data = Shared.apply(:df_concat_columns, [[head.data | tail]]) + %{out_df | data: out_data} + end + + # Groups + + @impl true + def summarise_with(%DataFrame{} = df, %DataFrame{} = out_df, column_pairs) do + df + |> lazy() + |> LazyFrame.summarise_with(out_df, column_pairs) + |> LazyFrame.compute() + end + + # Inspect + + @impl true + def inspect(df, opts) do + Explorer.Backend.DataFrame.inspect(df, "Polars", n_rows(df), opts) + end + + # SQL + + @impl true + def sql(%DataFrame{} = df, sql_string, table_name) do + df + |> lazy() + |> LazyFrame.sql(sql_string, table_name) + |> LazyFrame.compute() + end + + @impl true + def re_dtype(regex_as_string) when is_binary(regex_as_string) do + case Explorer.PolarsBackend.Native.df_re_dtype(regex_as_string) do + {:ok, dtype} -> dtype + {:error, error} -> raise error + end + end + + # helpers + + defp pairwise(df, out_df, operation) do + [column_name | cols] = out_df.names + + pairwise_results = + Enum.map(cols, fn left -> + corr_series = + cols + |> Enum.map(fn right -> operation.(df[left], df[right]) end) + |> Shared.from_list({:f, 64}) + |> Shared.create_series() + + {left, corr_series} + end) + + names_series = cols |> Shared.from_list(:string) |> Shared.create_series() + + from_series([{column_name, names_series} | pairwise_results]) + end +end diff --git a/deps/explorer/lib/explorer/polars_backend/expression.ex b/deps/explorer/lib/explorer/polars_backend/expression.ex new file mode 100644 index 0000000000000000000000000000000000000000..8582caf011f79bef096d17049489bc1feb133842 --- /dev/null +++ b/deps/explorer/lib/explorer/polars_backend/expression.ex @@ -0,0 +1,369 @@ +defmodule Explorer.PolarsBackend.Expression do + @moduledoc false + # This module is responsible for translating the opaque LazySeries + # to polars expressions in the Rust side. + + alias Explorer.DataFrame + alias Explorer.Backend.LazySeries + alias Explorer.PolarsBackend.Native + alias Explorer.PolarsBackend.Series, as: PolarsSeries + + defstruct resource: nil + + @type t :: %__MODULE__{resource: reference()} + + @all_expressions [ + all: 1, + add: 2, + any: 1, + all_equal: 2, + argmax: 1, + argmin: 1, + binary_and: 2, + binary_or: 2, + binary_in: 2, + coalesce: 2, + count: 1, + size: 1, + day_of_week: 1, + day_of_year: 1, + week_of_year: 1, + month: 1, + year: 1, + hour: 1, + minute: 1, + second: 1, + distinct: 1, + equal: 2, + exp: 1, + abs: 1, + fill_missing_with_value: 2, + first: 1, + format: 1, + greater: 2, + greater_equal: 2, + is_nil: 1, + is_not_nil: 1, + is_finite: 1, + is_infinite: 1, + is_nan: 1, + last: 1, + less: 2, + less_equal: 2, + max: 1, + mean: 1, + median: 1, + min: 1, + mode: 1, + n_distinct: 1, + nil_count: 1, + not_equal: 2, + unary_not: 1, + pow: 2, + product: 1, + quotient: 2, + remainder: 2, + reverse: 1, + floor: 1, + ceil: 1, + select: 3, + sin: 1, + cos: 1, + tan: 1, + asin: 1, + acos: 1, + atan: 1, + standard_deviation: 2, + subtract: 2, + sum: 1, + unordered_distinct: 1, + variance: 2, + skew: 2 + ] + + @first_only_expressions [ + quantile: 2, + argsort: 5, + sort: 5, + head: 2, + tail: 2, + peaks: 2, + rank: 4, + sample_n: 5, + sample_frac: 5, + exp: 1, + skew: 2, + round: 2, + clip_float: 3, + clip_integer: 3, + variance: 2, + standard_deviation: 2, + + # Trigonometric operations + acos: 1, + asin: 1, + atan: 1, + cos: 1, + sin: 1, + tan: 1, + + # Window operations + cumulative_max: 2, + cumulative_min: 2, + cumulative_sum: 2, + cumulative_product: 2, + window_max: 5, + window_mean: 5, + window_median: 5, + window_min: 5, + window_sum: 5, + window_standard_deviation: 5, + ewm_mean: 5, + ewm_standard_deviation: 6, + ewm_variance: 6, + + # Conversions + strptime: 2, + strftime: 2, + + # Strings + contains: 2, + re_contains: 2, + replace: 3, + re_replace: 3, + strip: 2, + lstrip: 2, + rstrip: 2, + downcase: 1, + upcase: 1, + substring: 3, + split: 2, + split_into: 3, + json_decode: 2, + json_path_match: 2, + count_matches: 2, + re_count_matches: 2, + re_scan: 2, + re_named_captures: 2, + + # Lists + join: 2, + lengths: 1, + member: 3, + + # Structs + field: 2 + ] + + @custom_expressions [ + divide: 2, + multiply: 2, + cast: 2, + fill_missing_with_strategy: 2, + from_list: 2, + from_binary: 2, + log: 1, + log: 2, + lazy: 1, + shift: 3, + slice: 2, + slice: 3, + row_index: 1, + concat: 1, + column: 1, + correlation: 4, + covariance: 3 + ] + + missing = + ((Explorer.Backend.LazySeries.operations() -- @all_expressions) -- @first_only_expressions) -- + @custom_expressions + + if missing != [] do + raise ArgumentError, "missing #{inspect(__MODULE__)} nodes: #{inspect(missing)}" + end + + def to_expr(%LazySeries{op: :cast, args: [lazy_series, dtype]}) do + lazy_series_expr = to_expr(lazy_series) + Native.expr_cast(lazy_series_expr, dtype) + end + + def to_expr(%LazySeries{op: :fill_missing_with_strategy, args: [lazy_series, strategy]}) do + expr = to_expr(lazy_series) + Native.expr_fill_missing_with_strategy(expr, Atom.to_string(strategy)) + end + + def to_expr(%LazySeries{op: :from_list, args: [list, dtype]}) do + series = Explorer.PolarsBackend.Shared.from_list(list, dtype) + Native.expr_series(series) + end + + def to_expr(%LazySeries{op: :from_binary, args: [binary, dtype]}) do + series = Explorer.PolarsBackend.Shared.from_binary(binary, dtype) + Native.expr_series(series) + end + + def to_expr(%LazySeries{op: :lazy, args: [data]}) do + to_expr(data) + end + + def to_expr(%LazySeries{op: :shift, args: [lazy_series, offset, nil]}) do + Native.expr_shift(to_expr(lazy_series), offset, nil) + end + + def to_expr(%LazySeries{op: :column, args: [name]}) do + Native.expr_column(name) + end + + def to_expr(%LazySeries{op: :concat, args: [series_list]}) when is_list(series_list) do + expr_list = Enum.map(series_list, &to_expr/1) + + Native.expr_concat(expr_list) + end + + def to_expr(%LazySeries{op: :correlation, args: [series1, series2, ddof, method]}) do + Native.expr_correlation(to_expr(series1), to_expr(series2), ddof, method) + end + + def to_expr(%LazySeries{op: :covariance, args: [series1, series2, ddof]}) do + Native.expr_covariance(to_expr(series1), to_expr(series2), ddof) + end + + def to_expr(%LazySeries{op: :format, args: [series_list]}) when is_list(series_list) do + expr_list = Enum.map(series_list, &to_expr/1) + + Native.expr_format(expr_list) + end + + def to_expr(%LazySeries{op: :slice, args: [lazy_series, lazy_series_or_list]}) do + indices = + if is_list(lazy_series_or_list) do + lazy_series_or_list + |> Explorer.PolarsBackend.Shared.from_list({:s, 64}) + |> Native.expr_series() + else + to_expr(lazy_series_or_list) + end + + Native.expr_slice_by_indices(to_expr(lazy_series), indices) + end + + def to_expr(%LazySeries{op: :slice, args: [lazy_series, offset, length]}) do + expr = to_expr(lazy_series) + + Native.expr_slice(expr, offset, length) + end + + def to_expr(%LazySeries{op: :log, args: [lazy_series]}) do + expr = to_expr(lazy_series) + + Native.expr_log_natural(expr) + end + + def to_expr(%LazySeries{op: :log, args: [lazy_series, base]}) do + expr = to_expr(lazy_series) + + Native.expr_log(expr, base) + end + + for {op, _arity} <- @first_only_expressions do + expr_op = :"expr_#{op}" + + def to_expr(%LazySeries{op: unquote(op), args: [lazy_series | args]}) do + expr = to_expr(lazy_series) + + apply(Native, unquote(expr_op), [expr | args]) + end + end + + def to_expr(%LazySeries{op: :multiply, args: [left, right] = args}) do + expr = Native.expr_multiply(to_expr(left), to_expr(right)) + + input_dtypes = Enum.map(args, &dtype/1) + duration_dtype = Enum.find(input_dtypes, &match?({:duration, _}, &1)) + numeric? = Enum.any?(input_dtypes, &(&1 in Explorer.Shared.numeric_types())) + + if duration_dtype && numeric? do + Native.expr_cast(expr, duration_dtype) + else + expr + end + end + + def to_expr(%LazySeries{op: :divide, args: [left, right]}) do + expr = Native.expr_divide(to_expr(left), to_expr(right)) + + case {dtype(left), dtype(right)} do + {{:duration, _} = left_dtype, right_dtype} -> + if right_dtype in Explorer.Shared.numeric_types() do + Native.expr_cast(expr, left_dtype) + else + expr + end + + {_, _} -> + expr + end + end + + def to_expr(%LazySeries{op: :row_index, args: [lazy_series]}) do + size_expr = Native.expr_size(to_expr(lazy_series)) + Native.expr_int_range(to_expr(0), size_expr, 1, {:u, 32}) + end + + for {op, arity} <- @all_expressions do + args = Macro.generate_arguments(arity, __MODULE__) + + updates = + for arg <- args do + quote do + to_expr(unquote(arg)) + end + end + + expr_op = :"expr_#{op}" + + def to_expr(%LazySeries{op: unquote(op), args: unquote(args)}) do + Native.unquote(expr_op)(unquote_splicing(updates)) + end + end + + def to_expr(nil), do: Native.expr_nil() + def to_expr(bool) when is_boolean(bool), do: Native.expr_boolean(bool) + def to_expr(atom) when is_atom(atom), do: Native.expr_atom(Atom.to_string(atom)) + def to_expr(binary) when is_binary(binary), do: Native.expr_string(binary) + def to_expr(number) when is_integer(number), do: Native.expr_integer(number) + def to_expr(number) when is_float(number), do: Native.expr_float(number) + def to_expr(%Date{} = date), do: Native.expr_date(date) + def to_expr(%NaiveDateTime{} = naive_datetime), do: Native.expr_naive_datetime(naive_datetime) + def to_expr(%DateTime{} = datetime), do: Native.expr_datetime(datetime) + def to_expr(%Explorer.Duration{} = duration), do: Native.expr_duration(duration) + + def to_expr(%Explorer.Series{data: %PolarsSeries{} = polars_series}), + do: Native.expr_series(polars_series) + + def to_expr(%_{} = struct), + do: raise("unsupported struct in expression: #{inspect(struct)}") + + def to_expr(map) when is_map(map) do + expr_list = + Enum.map(map, fn {name, series} -> + series |> to_expr() |> alias_expr(name) + end) + + Native.expr_struct(expr_list) + end + + # Used by Explorer.PolarsBackend.DataFrame + def alias_expr(%__MODULE__{} = expr, alias_name) when is_binary(alias_name) do + Native.expr_alias(expr, alias_name) + end + + # Only for inspecting the expression in tests + def describe_filter_plan(%DataFrame{data: polars_df}, %__MODULE__{} = expression) do + Native.expr_describe_filter_plan(polars_df, expression) + end + + defp dtype(%LazySeries{dtype: dtype}), do: dtype + defp dtype(%Explorer.Series{dtype: dtype}), do: dtype +end diff --git a/deps/explorer/lib/explorer/polars_backend/lazy_frame.ex b/deps/explorer/lib/explorer/polars_backend/lazy_frame.ex new file mode 100644 index 0000000000000000000000000000000000000000..70ddfc55266a4889967e4e8af6042af637af8e94 --- /dev/null +++ b/deps/explorer/lib/explorer/polars_backend/lazy_frame.ex @@ -0,0 +1,670 @@ +defmodule Explorer.PolarsBackend.LazyFrame do + @moduledoc false + + alias Explorer.Backend.LazySeries + alias Explorer.DataFrame, as: DF + + alias Explorer.PolarsBackend.Native + alias Explorer.PolarsBackend.Shared + alias Explorer.PolarsBackend.DataFrame, as: Eager + + alias FSS.Local + alias FSS.S3 + alias FSS.HTTP + + import Explorer.PolarsBackend.Expression, only: [to_expr: 1, alias_expr: 2] + + # This resource is going to be a "ResourceArc" on Rust side. + defstruct resource: nil + + @type t :: %__MODULE__{resource: reference()} + + @behaviour Explorer.Backend.DataFrame + + # Conversion + + @impl true + def lazy, do: __MODULE__ + + @impl true + def lazy(ldf), do: ldf + + @impl true + def compute(ldf), do: Shared.apply_dataframe(ldf, ldf, :lf_compute, []) + + @impl true + def from_tabular(tabular, dtypes), + do: Eager.from_tabular(tabular, dtypes) |> Eager.lazy() + + @impl true + def from_series(pairs), do: Eager.from_series(pairs) |> Eager.lazy() + + # Introspection + + @impl true + def owner_reference(df), do: df.data.resource + + @impl true + def owner_export(df) do + raise """ + it is not possible to transfer a lazy data frame between nodes. \ + You must collect the operands to the same node between continuing, got: + + #{inspect(df)} + """ + end + + @impl true + def owner_import(_exported) do + raise "not implemented" + end + + @impl true + def inspect(ldf, opts) when node(ldf.data.resource) != node() do + Explorer.Backend.DataFrame.inspect( + ldf, + "LazyPolars (node: #{node(ldf.data.resource)})", + nil, + opts, + elide_columns: true + ) + end + + def inspect(ldf, opts) do + case Native.lf_fetch(ldf.data, opts.limit) do + {:ok, df} -> + df = Explorer.Backend.DataFrame.new(df, ldf.names, ldf.dtypes) + df = %{df | groups: ldf.groups} + + Explorer.Backend.DataFrame.inspect(df, "LazyPolars", nil, opts) + + {:error, error} -> + raise "inspection error: #{inspect(error)}" + end + end + + # Single table verbs + + @impl true + def head(ldf, rows), + do: Shared.apply_dataframe(ldf, ldf, :lf_head, [rows, groups_exprs(ldf.groups)]) + + @impl true + def tail(ldf, rows), + do: Shared.apply_dataframe(ldf, ldf, :lf_tail, [rows, groups_exprs(ldf.groups)]) + + @impl true + def select(ldf, out_ldf), do: Shared.apply_dataframe(ldf, out_ldf, :lf_select, [out_ldf.names]) + + @impl true + def slice(ldf, offset, length), + do: Shared.apply_dataframe(ldf, ldf, :lf_slice, [offset, length, ldf.groups]) + + defp groups_exprs(groups), do: Enum.map(groups, &Native.expr_column/1) + + # IO + + @impl true + def from_query(conn, query, params) do + with {:ok, df} <- Eager.from_query(conn, query, params) do + {:ok, Eager.lazy(df)} + end + end + + @impl true + def from_csv( + %S3.Entry{}, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _ + ) do + {:error, + ArgumentError.exception("reading CSV from AWS S3 is not supported for Lazy dataframes")} + end + + @impl true + def from_csv( + %Local.Entry{} = entry, + dtypes, + <>, + nil_values, + skip_rows, + skip_rows_after_header, + header?, + encoding, + max_rows, + columns, + infer_schema_length, + parse_dates, + eol_delimiter + ) + when is_nil(columns) do + infer_schema_length = + if infer_schema_length == nil, + do: max_rows, + else: infer_schema_length + + result = + Native.lf_from_csv( + entry.path, + infer_schema_length, + header?, + max_rows, + skip_rows, + skip_rows_after_header, + delimiter, + true, + dtypes, + encoding, + nil_values, + parse_dates, + char_byte(eol_delimiter) + ) + + case result do + {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def from_csv( + %Local.Entry{}, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _ + ) do + {:error, + ArgumentError.exception( + "`columns` is not supported by Polars' lazy backend. " <> + "Consider using `select/2` after reading the CSV" + )} + end + + defp char_byte(nil), do: nil + defp char_byte(<>), do: char + + @impl true + def from_parquet(%S3.Entry{} = entry, max_rows, columns, _rechunk) do + case Native.lf_from_parquet_cloud(entry, max_rows, columns) do + {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def from_parquet(%HTTP.Entry{url: url}, max_rows, columns, _rechunk) do + case Native.lf_from_parquet(url, max_rows, columns) do + {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def from_parquet(%Local.Entry{} = entry, max_rows, columns, _rechunk) do + case Native.lf_from_parquet(entry.path, max_rows, columns) do + {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def from_ndjson(%S3.Entry{}, _, _) do + {:error, + ArgumentError.exception("reading NDJSON from AWS S3 is not supported for Lazy dataframes")} + end + + @impl true + def from_ndjson(%Local.Entry{} = entry, infer_schema_length, batch_size) do + case Native.lf_from_ndjson(entry.path, infer_schema_length, batch_size) do + {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def from_ndjson(%HTTP.Entry{url: url}, infer_schema_length, batch_size) do + case Native.lf_from_ndjson(url, infer_schema_length, batch_size) do + {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def from_ipc(%S3.Entry{}, _) do + {:error, + ArgumentError.exception("reading IPC from AWS S3 is not supported for Lazy dataframes")} + end + + @impl true + def from_ipc(%Local.Entry{} = entry, columns) when is_nil(columns) do + case Native.lf_from_ipc(entry.path) do + {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf) + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def from_ipc(%Local.Entry{}, _columns) do + {:error, + ArgumentError.exception( + "`columns` is not supported by Polars' lazy backend. " <> + "Consider using `select/2` after reading the IPC file" + )} + end + + @impl true + def from_ipc_stream(%S3.Entry{}, _) do + {:error, + ArgumentError.exception( + "reading IPC Stream from AWS S3 is not supported for Lazy dataframes" + )} + end + + @impl true + def from_ipc_stream(%Local.Entry{} = fs_entry, columns) do + with {:ok, df} <- Eager.from_ipc_stream(fs_entry, columns) do + {:ok, Eager.lazy(df)} + end + end + + @impl true + def load_csv( + contents, + dtypes, + delimiter, + nil_values, + skip_rows, + skip_rows_after_header, + header?, + encoding, + max_rows, + columns, + infer_schema_length, + parse_dates, + eol_delimiter + ) do + with {:ok, df} <- + Eager.load_csv( + contents, + dtypes, + delimiter, + nil_values, + skip_rows, + skip_rows_after_header, + header?, + encoding, + max_rows, + columns, + infer_schema_length, + parse_dates, + eol_delimiter + ) do + {:ok, Eager.lazy(df)} + end + end + + @impl true + def load_parquet(contents) do + with {:ok, df} <- Eager.load_parquet(contents) do + {:ok, Eager.lazy(df)} + end + end + + @impl true + def load_ndjson(contents, infer_schema_length, batch_size) do + with {:ok, df} <- Eager.load_ndjson(contents, infer_schema_length, batch_size) do + {:ok, Eager.lazy(df)} + end + end + + @impl true + def load_ipc(contents, columns) do + with {:ok, df} <- Eager.load_ipc(contents, columns) do + {:ok, Eager.lazy(df)} + end + end + + @impl true + def load_ipc_stream(contents, columns) do + with {:ok, df} <- Eager.load_ipc_stream(contents, columns) do + {:ok, Eager.lazy(df)} + end + end + + @impl true + def to_csv(%DF{} = ldf, %Local.Entry{} = entry, header?, delimiter, streaming) do + <> = delimiter + + case Native.lf_to_csv(ldf.data, entry.path, header?, delimiter, streaming) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_csv(%DF{} = ldf, %S3.Entry{} = entry, header?, delimiter, _streaming) do + eager_df = compute(ldf) + + Eager.to_csv(eager_df, entry, header?, delimiter, false) + end + + @impl true + def to_parquet(%DF{} = ldf, %Local.Entry{} = entry, {compression, level}, streaming) do + case Native.lf_to_parquet( + ldf.data, + entry.path, + Shared.parquet_compression(compression, level), + streaming + ) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_parquet(%DF{} = ldf, %S3.Entry{} = entry, {compression, level}, _streaming = true) do + case Native.lf_to_parquet_cloud( + ldf.data, + entry, + Shared.parquet_compression(compression, level) + ) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_parquet(%DF{} = ldf, %S3.Entry{} = entry, compression, _streaming = false) do + eager_df = compute(ldf) + + Eager.to_parquet(eager_df, entry, compression, false) + end + + @impl true + def to_ipc(%DF{} = ldf, %Local.Entry{} = entry, {compression, _level}, streaming) do + case Native.lf_to_ipc(ldf.data, entry.path, Atom.to_string(compression), streaming) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_ipc(%DF{} = ldf, %S3.Entry{} = entry, {compression, _level}, _streaming = true) do + case Native.lf_to_ipc_cloud( + ldf.data, + entry, + Atom.to_string(compression) + ) do + {:ok, _} -> :ok + {:error, error} -> {:error, RuntimeError.exception(error)} + end + end + + @impl true + def to_ipc(%DF{} = ldf, %S3.Entry{} = entry, compression, _streaming = false) do + eager_df = compute(ldf) + + Eager.to_ipc(eager_df, entry, compression, false) + end + + @impl true + def filter_with(df, out_df, %LazySeries{} = lseries) do + expression = + if df.groups == [] do + to_expr(lseries) + else + lseries + |> to_expr() + |> Native.expr_over(groups_exprs(df.groups)) + end + + Shared.apply_dataframe(df, out_df, :lf_filter_with, [expression]) + end + + @impl true + def sort_with( + %DF{} = df, + out_df, + column_pairs, + maintain_order?, + multithreaded?, + nulls_last? + ) + when is_boolean(maintain_order?) and is_boolean(multithreaded?) and + is_boolean(nulls_last?) do + {directions, expressions} = + column_pairs + |> Enum.map(fn {direction, lazy_series} -> {direction == :desc, to_expr(lazy_series)} end) + |> Enum.unzip() + + if df.groups == [] do + Shared.apply_dataframe( + df, + out_df, + :lf_sort_with, + [ + expressions, + directions, + maintain_order?, + nulls_last? + ] + ) + else + # TODO: log that we cannot set `maintain_order?` nor `nulls_last?` + # This is a limitation of the grouped lazy frame. + Shared.apply_dataframe( + df, + out_df, + :lf_grouped_sort_with, + [ + expressions, + groups_exprs(df.groups), + directions + ] + ) + end + end + + @impl true + def distinct(%DF{} = df, %DF{} = out_df, columns) do + maybe_columns_to_keep = + if df.names != out_df.names, do: Enum.map(out_df.names, &Native.expr_column/1) + + Shared.apply_dataframe(df, out_df, :lf_distinct, [columns, maybe_columns_to_keep]) + end + + @impl true + def mutate_with(%DF{} = df, %DF{} = out_df, column_pairs) do + maybe_over_groups_fun = + if df.groups == [] do + &Function.identity/1 + else + fn expr -> Native.expr_over(expr, groups_exprs(df.groups)) end + end + + exprs = + for {name, lazy_series} <- column_pairs do + lazy_series + |> to_expr() + |> then(maybe_over_groups_fun) + |> alias_expr(name) + end + + Shared.apply_dataframe(df, out_df, :lf_mutate_with, [exprs]) + end + + @impl true + def rename(%DF{} = df, %DF{} = out_df, pairs), + do: Shared.apply_dataframe(df, out_df, :lf_rename_columns, [pairs]) + + @impl true + def drop_nil(%DF{} = df, columns) do + exprs = for col <- columns, do: Native.expr_column(col) + Shared.apply_dataframe(df, df, :lf_drop_nils, [exprs]) + end + + @impl true + def pivot_longer(%DF{} = df, %DF{} = out_df, cols_to_pivot, cols_to_keep, names_to, values_to) do + Shared.apply_dataframe( + df, + out_df, + :lf_pivot_longer, + [ + cols_to_keep, + cols_to_pivot, + names_to, + values_to + ] + ) + end + + @impl true + def explode(%DF{} = df, %DF{} = out_df, columns), + do: Shared.apply_dataframe(df, out_df, :lf_explode, [columns]) + + @impl true + def unnest(%DF{} = df, %DF{} = out_df, columns), + do: Shared.apply_dataframe(df, out_df, :lf_unnest, [columns]) + + # Groups + + @impl true + def summarise_with(%DF{groups: groups} = df, %DF{} = out_df, column_pairs) do + exprs = + for {name, lazy_series} <- column_pairs do + original_expr = to_expr(lazy_series) + alias_expr(original_expr, name) + end + + groups_exprs = for group <- groups, do: Native.expr_column(group) + + Shared.apply_dataframe(df, out_df, :lf_summarise_with, [groups_exprs, exprs]) + end + + # Two or more tables + + @impl true + def join([%DF{} = left, %DF{} = right], %DF{} = out_df, on, how) + when is_list(on) and how in [:left, :inner, :cross, :outer] do + how = Atom.to_string(how) + + {left_on, right_on} = + on + |> Enum.map(fn {left, right} -> {Native.expr_column(left), Native.expr_column(right)} end) + |> Enum.unzip() + + Shared.apply_dataframe( + left, + out_df, + :lf_join, + [right.data, left_on, right_on, how, "_right"] + ) + end + + @impl true + def join([%DF{} = left, %DF{} = right], %DF{} = out_df, on, :right) + when is_list(on) do + # Right join is the opposite of left join. So we swap the "on" keys, and swap the DFs + # in the join. + {left_on, right_on} = + on + |> Enum.map(fn {left, right} -> {Native.expr_column(right), Native.expr_column(left)} end) + |> Enum.unzip() + + Shared.apply_dataframe( + right, + out_df, + :lf_join, + [ + left.data, + left_on, + right_on, + "left", + "_left" + ] + ) + end + + @impl true + def concat_rows([%DF{} | _tail] = dfs, %DF{} = out_df) do + polars_dfs = Enum.map(dfs, fn df -> select(df, out_df).data end) + %__MODULE__{} = polars_df = Shared.apply(:lf_concat_rows, [polars_dfs]) + + %{out_df | data: polars_df} + end + + @impl true + def sql(ldf, sql_string, table_name) do + with {:ok, polars_lf} <- Native.lf_sql(ldf.data, sql_string, table_name), + {:ok, names} <- Native.lf_names(polars_lf), + {:ok, dtypes} <- Native.lf_dtypes(polars_lf) do + Explorer.Backend.DataFrame.new(polars_lf, names, dtypes) + else + {:error, polars_error} -> raise polars_error + end + end + + @impl true + def concat_columns([%DF{data: head_data} | tail], %DF{} = out_df) do + out_ldf_data = Shared.apply(:lf_concat_columns, [[head_data | Enum.map(tail, & &1.data)]]) + %{out_df | data: out_ldf_data} + end + + @impl true + def re_dtype(regex_as_string) when is_binary(regex_as_string) do + Eager.re_dtype(regex_as_string) + end + + not_available_funs = [ + correlation: 4, + covariance: 3, + nil_count: 1, + dummies: 3, + dump_csv: 3, + dump_ipc: 2, + dump_ipc_stream: 2, + dump_ndjson: 1, + dump_parquet: 2, + mask: 2, + n_rows: 1, + pivot_wider: 5, + pull: 2, + put: 4, + sample: 5, + slice: 2, + to_ipc_stream: 3, + to_ndjson: 2, + to_rows: 2, + to_rows_stream: 3, + transpose: 4 + ] + + for {fun, arity} <- not_available_funs do + args = Macro.generate_arguments(arity, __MODULE__) + + @impl true + def unquote(fun)(unquote_splicing(args)) do + raise "the function `#{unquote(fun)}/#{unquote(arity)}` is not available for the Explorer.PolarsBackend.LazyFrame backend. " <> + "Please use Explorer.DataFrame.collect/1 and then call this function upon the resultant dataframe" + end + end +end diff --git a/deps/explorer/lib/explorer/polars_backend/native.ex b/deps/explorer/lib/explorer/polars_backend/native.ex new file mode 100644 index 0000000000000000000000000000000000000000..688ed0827f751aeed49e62669069e976d7681332 --- /dev/null +++ b/deps/explorer/lib/explorer/polars_backend/native.ex @@ -0,0 +1,490 @@ +defmodule Explorer.PolarsBackend.Native do + @moduledoc false + + mix_config = Mix.Project.config() + version = mix_config[:version] + github_url = mix_config[:package][:links]["GitHub"] + # Since Rustler 0.27.0, we need to change manually the mode for each env. + # We want "debug" in dev and test because it's faster to compile. + mode = if Mix.env() in [:dev, :test], do: :debug, else: :release + + use_legacy = + Application.compile_env( + :explorer, + :use_legacy_artifacts, + System.get_env("EXPLORER_USE_LEGACY_ARTIFACTS") in ["true", "1"] + ) + + variants_for_linux = [ + legacy_cpu: fn -> + # These are the same from the release workflow. + # See the meaning in: https://unix.stackexchange.com/a/43540 + needed_caps = ~w[fxsr sse sse2 ssse3 sse4_1 sse4_2 popcnt avx fma] + + use_legacy or + (is_nil(use_legacy) and + not Explorer.ComptimeUtils.cpu_with_all_caps?(needed_caps)) + end + ] + + other_variants = [legacy_cpu: fn -> use_legacy end] + + use RustlerPrecompiled, + otp_app: :explorer, + version: version, + base_url: "#{github_url}/releases/download/v#{version}", + targets: ~w( + aarch64-apple-darwin + aarch64-unknown-linux-gnu + aarch64-unknown-linux-musl + x86_64-apple-darwin + x86_64-pc-windows-msvc + x86_64-pc-windows-gnu + x86_64-unknown-linux-gnu + x86_64-unknown-linux-musl + x86_64-unknown-freebsd + ), + variants: %{ + "x86_64-unknown-linux-gnu" => variants_for_linux, + "x86_64-pc-windows-msvc" => other_variants, + "x86_64-pc-windows-gnu" => other_variants, + "x86_64-unknown-freebsd" => other_variants + }, + # We don't use any features of newer NIF versions, so 2.15 is enough. + nif_versions: ["2.15"], + mode: mode, + force_build: System.get_env("EXPLORER_BUILD") in ["1", "true"] + + defstruct [:inner] + + def df_from_arrow_stream_pointer(_stream_ptr), do: err() + + def df_sort_by(_df, _by, _reverse, _maintain_order?, _multithreaded?, _nulls_last?, _groups), + do: err() + + def df_sort_with( + _df, + _expressions, + _directions, + _maintain_order?, + _multithreaded?, + _nulls_last?, + _groups + ), + do: err() + + def df_concat_columns(_dfs), do: err() + def df_drop(_df, _name), do: err() + def df_dtypes(_df), do: err() + def df_dump_csv(_df, _has_headers, _delimiter), do: err() + def df_dump_ndjson(_df), do: err() + def df_dump_parquet(_df, _compression), do: err() + def df_dump_ipc(_df, _compression), do: err() + def df_dump_ipc_stream(_df, _compression), do: err() + + def df_from_csv( + _filename, + _infer_schema_length, + _has_header, + _stop_after_n_rows, + _skip_rows, + _skip_rows_after_header, + _projection, + _sep, + _rechunk, + _columns, + _dtypes, + _encoding, + _nil_vals, + _parse_dates, + _eol_delimiter + ), + do: err() + + def df_from_ipc(_filename, _columns, _projection), do: err() + def df_from_ipc_stream(_filename, _columns, _projection), do: err() + def df_from_ndjson(_filename, _infer_schema_length, _batch_size), do: err() + + def df_from_parquet( + _filename, + _stop_after_n_rows, + _columns, + _projection, + _rechunk + ), + do: err() + + def df_from_series(_columns), do: err() + def df_group_indices(_df, _column_names), do: err() + def df_groups(_df, _column_names), do: err() + + def df_load_csv( + _binary, + _infer_schema_length, + _has_header, + _stop_after_n_rows, + _skip_rows, + _skip_rows_after_header, + _projection, + _sep, + _rechunk, + _columns, + _dtypes, + _encoding, + _nil_vals, + _parse_dates, + _eol_delimiter + ), + do: err() + + def df_load_ipc(_binary, _columns, _projection), do: err() + def df_load_ipc_stream(_binary, _columns, _projection), do: err() + def df_load_ndjson(_binary, _infer_schema_length, _batch_size), do: err() + def df_load_parquet(_binary), do: err() + + def df_mask(_df, _mask), do: err() + def df_n_rows(_df), do: err() + def df_names(_df), do: err() + def df_pivot_wider(_df, _id_columns, _pivot_column, _values_column, _names_prefix), do: err() + def df_pull(_df, _name), do: err() + def df_put_column(_df, _series), do: err() + def df_sample_frac(_df, _frac, _with_replacement, _shuffle, _seed, _groups), do: err() + def df_sample_n(_df, _n, _with_replacement, _shuffle, _seed, _groups), do: err() + def df_select_at_idx(_df, _idx), do: err() + def df_shape(_df), do: err() + def df_slice(_df, _offset, _length, _groups), do: err() + def df_slice_by_indices(_df, _indices, _groups), do: err() + def df_slice_by_series(_df, _series, _groups), do: err() + def df_transpose(_df, _keep_names_as, _new_col_names), do: err() + def df_to_csv(_df, _filename, _has_headers, _delimiter), do: err() + def df_to_csv_cloud(_df, _ex_entry, _has_headers, _delimiter), do: err() + def df_to_dummies(_df, _columns), do: err() + def df_to_ipc(_df, _filename, _compression), do: err() + def df_to_ipc_cloud(_df, _ex_entry, _compression), do: err() + def df_to_ipc_stream(_df, _filename, _compression), do: err() + def df_to_ipc_stream_cloud(_df, _ex_entry, _compression), do: err() + def df_lazy(_df), do: err() + def df_to_ndjson(_df, _filename), do: err() + def df_to_ndjson_cloud(_df, _ex_entry), do: err() + def df_to_parquet(_df, _filename, _compression), do: err() + def df_to_parquet_cloud(_df, _ex_entry, _compression), do: err() + def df_width(_df), do: err() + def df_nil_count(_df), do: err() + def df_re_dtype(_pattern), do: err() + + # Expressions (for lazy queries) + @multi_arity_expressions [slice: 2, slice: 3, log: 1, log: 2] + + # We first generate functions for known operations. + for {op, arity} <- Explorer.Backend.LazySeries.operations() -- @multi_arity_expressions do + args = Macro.generate_arguments(arity, __MODULE__) + expr_op = :"expr_#{op}" + def unquote(expr_op)(unquote_splicing(args)), do: err() + end + + def expr_slice(_lazy_series, _offset, _length), do: err() + def expr_slice_by_indices(_lazy_series, _series), do: err() + + def expr_log(_lazy_series, _base), do: err() + def expr_log_natural(_lazy_series), do: err() + + # Then we generate for some specific expressions + def expr_alias(_ex_expr, _alias_name), do: err() + def expr_nil(), do: err() + def expr_atom(_atom), do: err() + def expr_boolean(_bool), do: err() + def expr_date(_date), do: err() + def expr_naive_datetime(_datetime), do: err() + def expr_datetime(_datetime), do: err() + def expr_duration(_duration), do: err() + def expr_describe_filter_plan(_df, _expr), do: err() + def expr_float(_number), do: err() + def expr_integer(_number), do: err() + def expr_int_range(_start, _end, _step, _dtype), do: err() + def expr_over(_ex_expr, _groups_exprs), do: err() + def expr_series(_series), do: err() + def expr_string(_string), do: err() + def expr_struct(_map), do: err() + + # LazyFrame + def lf_compute(_df), do: err() + def lf_describe_plan(_df, _optimized), do: err() + def lf_drop(_df, _columns), do: err() + def lf_dtypes(_df), do: err() + def lf_fetch(_df, _n_rows), do: err() + def lf_head(_df, _n_rows, _groups), do: err() + def lf_names(_df), do: err() + def lf_select(_df, _columns), do: err() + def lf_tail(_df, _n_rows, _groups), do: err() + def lf_slice(_df, _offset, _length, _groups), do: err() + def lf_explode(_df, _columns), do: err() + def lf_unnest(_df, _columns), do: err() + def lf_from_ipc(_filename), do: err() + def lf_from_ndjson(_filename, _infer_schema_length, _batch_size), do: err() + def lf_from_parquet(_filename, _stop_after_n_rows, _maybe_columns), do: err() + def lf_from_parquet_cloud(_ex_s3_entry, _stop_after_n_rows, _maybe_columns), do: err() + + def lf_from_csv( + _filename, + _infer_schema_length, + _has_header, + _stop_after_n_rows, + _skip_rows, + _skip_rows_after_header, + _sep, + _rechunk, + _dtypes, + _encoding, + _nil_vals, + _parse_dates, + _eol_delimiter + ), + do: err() + + def lf_filter_with(_df, _expression), do: err() + + def lf_sort_with( + _df, + _expressions, + _directions, + _maintain_order?, + _nulls_last? + ), + do: err() + + def lf_grouped_sort_with( + _df, + _expressions, + _groups_expr, + _directions + ), + do: err() + + def lf_distinct(_df, _subset, _selection), do: err() + def lf_mutate_with(_df, _exprs), do: err() + def lf_summarise_with(_df, _groups, _aggs), do: err() + def lf_rename_columns(_df, _column_pairs), do: err() + def lf_drop_nils(_df, _column_pairs), do: err() + def lf_pivot_longer(_df, _id_vars, _value_vars, _names_to, _values_to), do: err() + def lf_join(_df, _other, _left_on, _right_on, _how, _suffix), do: err() + def lf_concat_rows(_dfs), do: err() + def lf_concat_columns(_ldfs), do: err() + def lf_to_parquet(_df, _filename, _compression, _streaming), do: err() + def lf_to_parquet_cloud(_df, _filename, _compression), do: err() + def lf_to_ipc(_df, _filename, _compression, _streaming), do: err() + def lf_to_ipc_cloud(_df, _cloud_entry, _compression), do: err() + def lf_to_csv(_df, _filename, _header, _delimiter, _streaming), do: err() + def lf_sql(_df, _sql_string, _table_name), do: err() + + # Series + def s_as_str(_s), do: err() + def s_add(_s, _other), do: err() + def s_all(_s), do: err() + def s_and(_s, _s2), do: err() + def s_any(_s), do: err() + def s_argmax(_s), do: err() + def s_argmin(_s), do: err() + def s_argsort(_s, _descending?, _maintain_order?, _multithreaded?, _nulls_last?), do: err() + def s_cast(_s, _dtype), do: err() + def s_categories(_s), do: err() + def s_categorise(_s, _s_categories), do: err() + def s_coalesce(_s, _other), do: err() + def s_concat(_series_list), do: err() + def s_contains(_s, _pattern, _is_literal), do: err() + def s_count_matches(_s, _pattern, _is_literal), do: err() + def s_re_scan(_s, _pattern), do: err() + def s_re_named_captures(_s, _pattern), do: err() + def s_cumulative_max(_s, _reverse), do: err() + def s_cumulative_min(_s, _reverse), do: err() + def s_cumulative_sum(_s, _reverse), do: err() + def s_cumulative_product(_s, _reverse), do: err() + def s_skew(_s, _bias), do: err() + def s_correlation(_s1, _s2, _ddof, _method), do: err() + def s_covariance(_s1, _s2, _ddof), do: err() + def s_distinct(_s), do: err() + def s_divide(_s, _other), do: err() + def s_dtype(_s), do: err() + def s_equal(_s, _rhs), do: err() + def s_exp(_s), do: err() + def s_abs(_s), do: err() + def s_strptime(_s, _format_string, _precision), do: err() + def s_strftime(_s, _format_string), do: err() + def s_clip_integer(_s, _min, _max), do: err() + def s_clip_float(_s, _min, _max), do: err() + def s_fill_missing_with_strategy(_s, _strategy), do: err() + def s_fill_missing_with_boolean(_s, _value), do: err() + def s_fill_missing_with_bin(_s, _value), do: err() + def s_fill_missing_with_float(_s, _value), do: err() + def s_fill_missing_with_int(_s, _value), do: err() + def s_fill_missing_with_atom(_s, _value), do: err() + def s_fill_missing_with_date(_s, _value), do: err() + def s_fill_missing_with_datetime(_s, _value), do: err() + def s_fill_missing_with_decimal(_s, _value), do: err() + def s_greater(_s, _rhs), do: err() + def s_greater_equal(_s, _rhs), do: err() + def s_head(_s, _length), do: err() + def s_is_finite(_s), do: err() + def s_is_infinite(_s), do: err() + def s_is_nan(_s), do: err() + def s_is_not_null(_s), do: err() + def s_is_null(_s), do: err() + def s_less(_s, _rhs), do: err() + def s_less_equal(_s, _rhs), do: err() + def s_lstrip(_s, _string), do: err() + def s_mask(_s, _filter), do: err() + def s_max(_s), do: err() + def s_mean(_s), do: err() + def s_median(_s), do: err() + def s_product(_s), do: err() + def s_min(_s), do: err() + def s_mode(_s), do: err() + def s_multiply(_s, _other), do: err() + def s_n_chunks(_s), do: err() + def s_n_distinct(_s), do: err() + def s_name(_s), do: err() + def s_nil_count(_s), do: err() + def s_not(_s), do: err() + def s_from_list_null(_name, _val), do: err() + def s_from_list_bool(_name, _val), do: err() + def s_from_list_date(_name, _val), do: err() + def s_from_list_time(_name, _val), do: err() + def s_from_list_naive_datetime(_name, _val, _precision), do: err() + def s_from_list_datetime(_name, _val, _precision, _tz), do: err() + def s_from_list_duration(_name, _val, _precision), do: err() + def s_from_list_f32(_name, _val), do: err() + def s_from_list_f64(_name, _val), do: err() + def s_from_list_s8(_name, _val), do: err() + def s_from_list_s16(_name, _val), do: err() + def s_from_list_s32(_name, _val), do: err() + def s_from_list_s64(_name, _val), do: err() + def s_from_list_u8(_name, _val), do: err() + def s_from_list_u16(_name, _val), do: err() + def s_from_list_u32(_name, _val), do: err() + def s_from_list_u64(_name, _val), do: err() + def s_from_list_str(_name, _val), do: err() + def s_from_list_binary(_name, _val), do: err() + def s_from_list_categories(_name, _val), do: err() + def s_from_list_decimal(_name, _val, _precision, _scale), do: err() + def s_from_list_of_series(_name, _val, _dtype), do: err() + def s_from_list_of_series_as_structs(_name, _val, _dtype), do: err() + def s_from_binary_f32(_name, _val), do: err() + def s_from_binary_f64(_name, _val), do: err() + def s_from_binary_s8(_name, _val), do: err() + def s_from_binary_s16(_name, _val), do: err() + def s_from_binary_s32(_name, _val), do: err() + def s_from_binary_s64(_name, _val), do: err() + def s_from_binary_u8(_name, _val), do: err() + def s_from_binary_u16(_name, _val), do: err() + def s_from_binary_u32(_name, _val), do: err() + def s_from_binary_u64(_name, _val), do: err() + def s_not_equal(_s, _rhs), do: err() + def s_or(_s, _s2), do: err() + def s_peak_max(_s), do: err() + def s_peak_min(_s), do: err() + def s_select(_pred, _on_true, _on_false), do: err() + def s_log_natural(_s_argument), do: err() + def s_log(_s_argument, _base_as_float), do: err() + def s_quantile(_s, _quantile, _strategy), do: err() + def s_quotient(_s, _rhs), do: err() + def s_remainder(_s, _rhs), do: err() + def s_rename(_s, _name), do: err() + def s_reverse(_s), do: err() + def s_round(_s, _decimals), do: err() + def s_row_index(_s), do: err() + def s_floor(_s), do: err() + def s_ceil(_s), do: err() + def s_rstrip(_s, _string), do: err() + def s_rank(_s, _method, _descending, _seed), do: err() + def s_replace(_s, _pattern, _replacement, _literal), do: err() + def s_sample_n(_s, _n, _replace, _shuffle, _seed), do: err() + def s_sample_frac(_s, _frac, _replace, _shuffle, _seed), do: err() + def s_series_equal(_s, _other, _null_equal), do: err() + def s_size(_s), do: err() + def s_slice(_s, _offset, _length), do: err() + def s_slice_by_indices(_s, _indices), do: err() + def s_slice_by_series(_s, _series), do: err() + def s_sort(_s, _descending?, _maintain_order?, _multithreaded?, _nulls_last?), do: err() + def s_standard_deviation(_s, _ddof), do: err() + def s_strip(_s, _string), do: err() + def s_subtract(_s, _other), do: err() + def s_sum(_s), do: err() + def s_tail(_s, _length), do: err() + def s_shift(_s, _offset), do: err() + def s_at(_s, _rhs), do: err() + def s_at_every(_s, _n), do: err() + def s_to_list(_s), do: err() + def s_downcase(_s), do: err() + def s_to_iovec(_s), do: err() + def s_upcase(_s), do: err() + def s_unordered_distinct(_s), do: err() + def s_frequencies(_s), do: err() + + def s_cut( + _s, + _bins, + _labels, + _break_point_label, + _category_label, + _left_close, + _include_breaks + ), + do: err() + + def s_substring(_s, _offset, _length), do: err() + def s_split(_s, _by), do: err() + def s_split_into(_s, _by, _num_fields), do: err() + + def s_qcut( + _s, + _quantiles, + _labels, + _break_point_label, + _category_label, + _allow_duplicates, + _left_close, + _include_breaks + ), + do: err() + + def s_variance(_s, _ddof), do: err() + def s_window_max(_s, _window_size, _weight, _ignore_null, _min_periods), do: err() + def s_window_mean(_s, _window_size, _weight, _ignore_null, _min_periods), do: err() + def s_window_median(_s, _window_size, _weight, _ignore_null, _min_periods), do: err() + def s_window_min(_s, _window_size, _weight, _ignore_null, _min_periods), do: err() + def s_window_sum(_s, _window_size, _weight, _ignore_null, _min_periods), do: err() + + def s_window_standard_deviation(_s, _window_size, _weight, _ignore_null, _min_periods), + do: err() + + def s_ewm_mean(_s, _alpha, _adjust, _min_periods, _ignore_nils), do: err() + def s_ewm_standard_deviation(_s, _alpha, _adjust, _bias, _min_periods, _ignore_nils), do: err() + def s_ewm_variance(_s, _alpha, _adjust, _bias, _min_periods, _ignore_nils), do: err() + def s_in(_s, _other), do: err() + def s_day_of_week(_s), do: err() + def s_day_of_year(_s), do: err() + def s_week_of_year(_s), do: err() + def s_month(_s), do: err() + def s_year(_s), do: err() + def s_hour(_s), do: err() + def s_minute(_s), do: err() + def s_second(_s), do: err() + def s_sin(_s), do: err() + def s_cos(_s), do: err() + def s_tan(_s), do: err() + def s_asin(_s), do: err() + def s_acos(_s), do: err() + def s_atan(_s), do: err() + + def s_join(_s, _separator), do: err() + def s_lengths(_s), do: err() + def s_member(_s, _value, _inner_dtype), do: err() + + def s_field(_s, _name), do: err() + def s_json_decode(_s, _dtype), do: err() + def s_json_path_match(_s, _json_path), do: err() + + def message_on_gc(_pid, _payload), do: err() + def is_message_on_gc(_term), do: err() + + defp err, do: :erlang.nif_error(:nif_not_loaded) +end diff --git a/deps/explorer/lib/explorer/polars_backend/series.ex b/deps/explorer/lib/explorer/polars_backend/series.ex new file mode 100644 index 0000000000000000000000000000000000000000..56af73590083a9b69efe509d3b71585e04ee8e54 --- /dev/null +++ b/deps/explorer/lib/explorer/polars_backend/series.ex @@ -0,0 +1,899 @@ +defmodule Explorer.PolarsBackend.Series do + @moduledoc false + + alias Explorer.DataFrame + alias Explorer.PolarsBackend.Shared + alias Explorer.Series + + @type t :: %__MODULE__{resource: reference()} + + defstruct resource: nil + + @behaviour Explorer.Backend.Series + + defguardp is_non_finite(n) when n in [:nan, :infinity, :neg_infinity] + defguardp is_numeric(n) when is_number(n) or is_non_finite(n) + + @integer_types Explorer.Shared.integer_types() + @numeric_types Explorer.Shared.numeric_types() + + # Conversion + + @impl true + def from_list(data, type) when is_list(data) do + series = Shared.from_list(data, type) + + Explorer.Backend.Series.new(series, type) + end + + @impl true + def from_binary(data, dtype) when is_binary(data) do + series = Shared.from_binary(data, dtype) + Explorer.Backend.Series.new(series, dtype) + end + + @impl true + def to_list(series), do: Shared.apply_series(series, :s_to_list) + + @impl true + def to_iovec(series), do: Shared.apply_series(series, :s_to_iovec) + + @impl true + def cast(%Series{dtype: :string} = series, {:naive_datetime, precision}), + do: Shared.apply_series(series, :s_strptime, [nil, precision]) + + def cast(series, dtype), + do: Shared.apply_series(series, :s_cast, [dtype]) + + @impl true + def strptime(%Series{} = series, format_string) do + Shared.apply_series(series, :s_strptime, [format_string, nil]) + end + + @impl true + def strftime(%Series{} = series, format_string) do + Shared.apply_series(series, :s_strftime, [format_string]) + end + + # Ownership + + @impl true + def owner_reference(series), do: series.data.resource + + @impl true + def owner_export(series) do + Explorer.DataFrame.new(series: series) + |> Explorer.DataFrame.dump_ipc() + end + + @impl true + def owner_import(dumped) do + with {:ok, df} <- Explorer.DataFrame.load_ipc(dumped) do + {:ok, df[:series]} + end + end + + # Introspection + + defp dtype(series), do: Shared.apply_series(series, :s_dtype) + + @impl true + def size(series), do: Shared.apply_series(series, :s_size) + + @impl true + def categories(%Series{dtype: :category} = series), + do: Shared.apply_series(series, :s_categories) + + @impl true + def categorise(%Series{dtype: {integer_type, _}} = series, %Series{dtype: dtype} = categories) + when dtype in [:string, :category] and integer_type in [:s, :u], + do: Shared.apply_series(series, :s_categorise, [categories.data]) + + @impl true + def categorise(%Series{dtype: :string} = series, %Series{dtype: dtype} = categories) + when dtype in [:string, :category], + do: Shared.apply_series(series, :s_categorise, [categories.data]) + + # Slice and dice + + @impl true + def head(series, n_elements), do: Shared.apply_series(series, :s_head, [n_elements]) + + @impl true + def tail(series, n_elements), do: Shared.apply_series(series, :s_tail, [n_elements]) + + @impl true + def first(series), do: series[0] + + @impl true + def last(series), do: series[-1] + + @impl true + def shift(series, offset, nil), do: Shared.apply_series(series, :s_shift, [offset]) + + @impl true + def sample(series, n, replacement, shuffle, seed) when is_integer(n) do + Shared.apply_series(series, :s_sample_n, [n, replacement, shuffle, seed]) + end + + @impl true + def sample(series, frac, replacement, shuffle, seed) when is_float(frac) do + Shared.apply_series(series, :s_sample_frac, [frac, replacement, shuffle, seed]) + end + + @impl true + def rank(series, method, descending, seed) do + Shared.apply_series(series, :s_rank, [method, descending, seed]) + end + + @impl true + def at_every(series, every_n), + do: Shared.apply_series(series, :s_at_every, [every_n]) + + @impl true + def mask(series, %Series{} = mask), + do: Shared.apply_series(series, :s_mask, [mask.data]) + + @impl true + def slice(series, indices) when is_list(indices), + do: Shared.apply_series(series, :s_slice_by_indices, [indices]) + + @impl true + def slice(series, %Series{} = indices), + do: Shared.apply_series(series, :s_slice_by_series, [indices.data]) + + @impl true + def slice(series, offset, length), do: Shared.apply_series(series, :s_slice, [offset, length]) + + @impl true + def at(series, idx), do: Shared.apply_series(series, :s_at, [idx]) + + @impl true + def format(list) do + {_, df_args, params} = + Enum.reduce(list, {0, [], []}, fn s, {counter, df_args, params} -> + if is_binary(s) or Kernel.is_nil(s) do + {counter, df_args, [s | params]} + else + counter = counter + 1 + name = "#{counter}" + column = Explorer.Backend.LazySeries.unbacked(:column, [name], :string) + {counter, [{name, s} | df_args], [column | params]} + end + end) + + df = Explorer.PolarsBackend.DataFrame.from_series(df_args) + format_expr = Explorer.Backend.LazySeries.unbacked(:format, [Enum.reverse(params)], :string) + out_dtypes = Map.put(df.dtypes, "result", :string) + out_names = ["result" | df.names] + out_df = %{df | dtypes: out_dtypes, names: out_names} + + Explorer.PolarsBackend.DataFrame.mutate_with(df, out_df, [{"result", format_expr}]) + |> Explorer.PolarsBackend.DataFrame.pull("result") + end + + @impl true + def concat([%Series{} | _] = series) do + polars_series = for s <- series, do: s.data + + Shared.apply(:s_concat, [polars_series]) + |> Shared.create_series() + end + + @impl true + def coalesce(s1, s2), do: Shared.apply_series(s1, :s_coalesce, [s2.data]) + + @impl true + def select(%Series{} = predicate, %Series{} = on_true, %Series{} = on_false) do + predicate_size = size(predicate) + on_true_size = size(on_true) + on_false_size = size(on_false) + singleton_condition = on_true_size == 1 or on_false_size == 1 + + if on_true_size != on_false_size and not singleton_condition do + raise ArgumentError, + "series in select/3 must have the same size or size of 1, got: #{on_true_size} and #{on_false_size}" + end + + if predicate_size != 1 and predicate_size != on_true_size and predicate_size != on_false_size and + not singleton_condition do + raise ArgumentError, + "predicate in select/3 must have size of 1 or have the same size as operands, got: #{predicate_size} and #{Enum.max([on_true_size, on_false_size])}" + end + + Shared.apply_series(predicate, :s_select, [on_true.data, on_false.data]) + end + + # Aggregation + + @impl true + # There is no `count` equivalent in Polars, so we need to make our own. + def count(series), do: size(series) - nil_count(series) + + @impl true + def nil_count(series), do: Shared.apply_series(series, :s_nil_count) + + @impl true + def sum(series), do: Shared.apply_series(series, :s_sum) + + @impl true + def min(series), do: Shared.apply_series(series, :s_min) + + @impl true + def max(series), do: Shared.apply_series(series, :s_max) + + @impl true + def argmin(series), do: Shared.apply_series(series, :s_argmin) + + @impl true + def argmax(series), do: Shared.apply_series(series, :s_argmax) + + @impl true + def mean(series), do: Shared.apply_series(series, :s_mean) + + @impl true + def median(series), do: Shared.apply_series(series, :s_median) + + @impl true + def mode(series), do: Shared.apply_series(series, :s_mode) + + @impl true + def variance(series, ddof), do: series |> Shared.apply_series(:s_variance, [ddof]) |> at(0) + + @impl true + def standard_deviation(series, ddof), + do: series |> Shared.apply_series(:s_standard_deviation, [ddof]) |> at(0) + + @impl true + def quantile(series, quantile), + do: Shared.apply_series(series, :s_quantile, [quantile, "nearest"]) + + @impl true + def product(series), do: first(Shared.apply_series(series, :s_product)) + + @impl true + def skew(series, bias?), + do: Shared.apply_series(series, :s_skew, [bias?]) + + @impl true + def correlation(left, right, ddof, method), + do: + Shared.apply_series(matching_size!(left, right), :s_correlation, [right.data, ddof, method]) + + @impl true + def covariance(left, right, ddof), + do: Shared.apply_series(matching_size!(left, right), :s_covariance, [right.data, ddof]) + + @impl true + def all?(series), do: Shared.apply_series(series, :s_all) + + @impl true + def any?(series), do: Shared.apply_series(series, :s_any) + + @impl true + def row_index(series), do: Shared.apply_series(series, :s_row_index) + + # Cumulative + + @impl true + def cumulative_max(series, reverse?), + do: Shared.apply_series(series, :s_cumulative_max, [reverse?]) + + @impl true + def cumulative_min(series, reverse?), + do: Shared.apply_series(series, :s_cumulative_min, [reverse?]) + + @impl true + def cumulative_sum(series, reverse?), + do: Shared.apply_series(series, :s_cumulative_sum, [reverse?]) + + @impl true + def cumulative_product(series, reverse?), + do: Shared.apply_series(series, :s_cumulative_product, [reverse?]) + + # Local minima/maxima + + @impl true + def peaks(series, :max), do: Shared.apply_series(series, :s_peak_max) + def peaks(series, :min), do: Shared.apply_series(series, :s_peak_min) + + # Arithmetic + + @impl true + def add(out_dtype, left, right) do + result = Shared.apply_series(matching_size!(left, right), :s_add, [right.data]) + + if match?({:decimal, _, _}, out_dtype) and out_dtype != dtype(result) do + cast(result, out_dtype) + else + result + end + end + + @impl true + def subtract(out_dtype, left, right) do + left = matching_size!(left, right) + + result = Shared.apply_series(left, :s_subtract, [right.data]) + + if match?({:decimal, _, _}, out_dtype) and out_dtype != dtype(result) do + cast(result, out_dtype) + else + result + end + end + + @impl true + def multiply(out_dtype, left, right) do + result = Shared.apply_series(matching_size!(left, right), :s_multiply, [right.data]) + + # Polars currently returns inconsistent dtypes, e.g.: + # * `integer * duration -> duration` when `integer` is a scalar + # * `integer * duration -> integer` when `integer` is a series + # We need to return duration in these cases, so we need an additional cast. + if (match?({:duration, _}, out_dtype) or match?({:decimal, _, _}, out_dtype)) and + out_dtype != dtype(result) do + cast(result, out_dtype) + else + result + end + end + + @impl true + def divide(out_dtype, left, right) do + result = Shared.apply_series(matching_size!(left, right), :s_divide, [right.data]) + + # Polars currently returns inconsistent dtypes, e.g.: + # * `duration / integer -> duration` when `integer` is a scalar + # * `duration / integer -> integer` when `integer` is a series + # We need to return duration in these cases, so we need an additional cast. + if (match?({:duration, _}, out_dtype) or match?({:decimal, _, _}, out_dtype)) and + out_dtype != dtype(result) do + cast(result, out_dtype) + else + result + end + end + + @impl true + def quotient(left, right), + do: Shared.apply_series(matching_size!(left, right), :s_quotient, [right.data]) + + @impl true + def remainder(left, right), + do: Shared.apply_series(matching_size!(left, right), :s_remainder, [right.data]) + + @impl true + def pow(out_dtype, left, right) do + _ = matching_size!(left, right) + + # We need to pre-cast or we may lose precision. + left = Explorer.Series.cast(left, out_dtype) + + left_lazy = Explorer.Backend.LazySeries.unbacked(:column, ["base"], left.dtype) + right_lazy = Explorer.Backend.LazySeries.unbacked(:column, ["exponent"], right.dtype) + + {df_args, pow_args} = + case {size(left), size(right)} do + {n, n} -> {[{"base", left}, {"exponent", right}], [left_lazy, right_lazy]} + {1, _} -> {[{"exponent", right}], [Explorer.Series.at(left, 0), right_lazy]} + {_, 1} -> {[{"base", left}], [left_lazy, Explorer.Series.at(right, 0)]} + end + + df = Explorer.PolarsBackend.DataFrame.from_series(df_args) + pow = Explorer.Backend.LazySeries.unbacked(:pow, pow_args, out_dtype) + + out_dtypes = Map.put(df.dtypes, "pow", out_dtype) + out_names = df.names ++ ["pow"] + out_df = %{df | dtypes: out_dtypes, names: out_names} + + Explorer.PolarsBackend.DataFrame.mutate_with(df, out_df, [{"pow", pow}]) + |> Explorer.PolarsBackend.DataFrame.pull("pow") + end + + @impl true + def log(%Series{} = argument), do: Shared.apply_series(argument, :s_log_natural, []) + + @impl true + def log(%Series{} = argument, base) when is_numeric(base), + do: Shared.apply_series(argument, :s_log, [base]) + + @impl true + def exp(%Series{} = s), do: Shared.apply_series(s, :s_exp, []) + + @impl true + def abs(%Series{} = s), do: Shared.apply_series(s, :s_abs, []) + + @impl true + def clip(%Series{dtype: dtype} = s, min, max) + when dtype in @integer_types and is_integer(min) and is_integer(max), + do: Shared.apply_series(s, :s_clip_integer, [min, max]) + + def clip(%Series{} = s, min, max), + do: s |> cast({:f, 64}) |> Shared.apply_series(:s_clip_float, [min * 1.0, max * 1.0]) + + # Trigonometry + + @impl true + def sin(%Series{} = s), do: Shared.apply_series(s, :s_sin, []) + + @impl true + def cos(%Series{} = s), do: Shared.apply_series(s, :s_cos, []) + + @impl true + def tan(%Series{} = s), do: Shared.apply_series(s, :s_tan, []) + + @impl true + def asin(%Series{} = s), do: Shared.apply_series(s, :s_asin, []) + + @impl true + def acos(%Series{} = s), do: Shared.apply_series(s, :s_acos, []) + + @impl true + def atan(%Series{} = s), do: Shared.apply_series(s, :s_atan, []) + + # Comparisons + + @impl true + def equal(left, right), + do: Shared.apply_series(matching_size!(left, right), :s_equal, [right.data]) + + @impl true + def not_equal(left, right), + do: Shared.apply_series(matching_size!(left, right), :s_not_equal, [right.data]) + + @impl true + def greater(left, right), + do: Shared.apply_series(matching_size!(left, right), :s_greater, [right.data]) + + @impl true + def less(left, right), + do: Shared.apply_series(matching_size!(left, right), :s_less, [right.data]) + + @impl true + def greater_equal(left, right), + do: Shared.apply_series(matching_size!(left, right), :s_greater_equal, [right.data]) + + @impl true + def less_equal(left, right), + do: Shared.apply_series(matching_size!(left, right), :s_less_equal, [right.data]) + + @impl true + def all_equal(%Series{} = left, %Series{} = right), + do: Shared.apply_series(matching_size!(left, right), :s_series_equal, [right.data, true]) + + @impl true + def binary_in(%Series{} = left, %Series{} = right), + do: Shared.apply_series(left, :s_in, [right.data]) + + @impl true + def binary_and(%Series{} = left, %Series{} = right), + do: Shared.apply_series(matching_size!(left, right), :s_and, [right.data]) + + @impl true + def binary_or(%Series{} = left, %Series{} = right), + do: Shared.apply_series(matching_size!(left, right), :s_or, [right.data]) + + # Float predicates + + @impl true + def is_finite(series), do: Shared.apply_series(series, :s_is_finite) + + @impl true + def is_infinite(series), do: Shared.apply_series(series, :s_is_infinite) + + @impl true + def is_nan(series), do: Shared.apply_series(series, :s_is_nan) + + # Sort + + @impl true + def sort(series, descending?, maintain_order?, multithreaded?, nulls_last?) + when is_boolean(descending?) and is_boolean(maintain_order?) and is_boolean(multithreaded?) and + is_boolean(nulls_last?) do + Shared.apply_series(series, :s_sort, [ + descending?, + maintain_order?, + multithreaded?, + nulls_last? + ]) + end + + @impl true + def argsort(series, descending?, maintain_order?, multithreaded?, nulls_last?) + when is_boolean(descending?) and is_boolean(maintain_order?) and is_boolean(multithreaded?) and + is_boolean(nulls_last?) do + Shared.apply_series(series, :s_argsort, [ + descending?, + maintain_order?, + multithreaded?, + nulls_last? + ]) + end + + @impl true + def reverse(series), do: Shared.apply_series(series, :s_reverse) + + # Distinct + + @impl true + def distinct(series), do: Shared.apply_series(series, :s_distinct) + + @impl true + def unordered_distinct(series), do: Shared.apply_series(series, :s_unordered_distinct) + + @impl true + def n_distinct(series), do: Shared.apply_series(series, :s_n_distinct) + + @impl true + def frequencies(%Series{dtype: {:list, inner_dtype} = dtype}) + when inner_dtype not in @numeric_types do + raise ArgumentError, + "frequencies/1 only works with series of lists of numeric types, but #{Explorer.Shared.dtype_to_string(dtype)} was given" + end + + def frequencies(%Series{} = series) do + Shared.apply(:s_frequencies, [series.data]) + |> Shared.create_dataframe!() + |> DataFrame.rename(["values", "counts"]) + end + + # Categorisation + + @impl true + def cut(series, bins, labels, break_point_label, category_label, left_close, include_breaks) do + case Explorer.PolarsBackend.Native.s_cut( + series.data, + bins, + labels, + break_point_label, + category_label, + left_close, + include_breaks + ) do + {:ok, polars_df} -> + Shared.create_dataframe!(polars_df) + + {:error, "Polars Error: lengths don't match: " <> _rest} -> + raise ArgumentError, "lengths don't match: labels count must equal bins count" + + {:error, msg} -> + raise msg + end + end + + @impl true + def qcut( + series, + quantiles, + labels, + break_point_label, + category_label, + allow_duplicates, + left_close, + include_breaks + ) do + Shared.apply(:s_qcut, [ + series.data, + quantiles, + labels, + break_point_label, + category_label, + allow_duplicates, + left_close, + include_breaks + ]) + |> Shared.create_dataframe!() + end + + # Window + + @impl true + def window_max(series, window_size, weights, min_periods, center) do + window_function(:s_window_max, series, window_size, weights, min_periods, center) + end + + @impl true + def window_mean(series, window_size, weights, min_periods, center) do + window_function(:s_window_mean, series, window_size, weights, min_periods, center) + end + + @impl true + def window_median(series, window_size, weights, min_periods, center) do + window_function(:s_window_median, series, window_size, weights, min_periods, center) + end + + @impl true + def window_min(series, window_size, weights, min_periods, center) do + window_function(:s_window_min, series, window_size, weights, min_periods, center) + end + + @impl true + def window_sum(series, window_size, weights, min_periods, center) do + window_function(:s_window_sum, series, window_size, weights, min_periods, center) + end + + @impl true + def window_standard_deviation(series, window_size, weights, min_periods, center) do + window_function( + :s_window_standard_deviation, + series, + window_size, + weights, + min_periods, + center + ) + end + + defp window_function(operation, series, window_size, weights, min_periods, center) do + series = + if List.wrap(weights) == [] do + series + else + cast(series, {:f, 64}) + end + + Shared.apply_series(series, operation, [window_size, weights, min_periods, center]) + end + + @impl true + def ewm_mean(series, alpha, adjust, min_periods, ignore_nils) do + Shared.apply_series(series, :s_ewm_mean, [alpha, adjust, min_periods, ignore_nils]) + end + + @impl true + def ewm_standard_deviation(series, alpha, adjust, bias, min_periods, ignore_nils) do + Shared.apply_series( + series, + :s_ewm_standard_deviation, + [alpha, adjust, bias, min_periods, ignore_nils] + ) + end + + @impl true + def ewm_variance(series, alpha, adjust, bias, min_periods, ignore_nils) do + Shared.apply_series(series, :s_ewm_variance, [alpha, adjust, bias, min_periods, ignore_nils]) + end + + # Missing values + + @impl true + def fill_missing_with_strategy(series, strategy), + do: Shared.apply_series(series, :s_fill_missing_with_strategy, [Atom.to_string(strategy)]) + + @impl true + def fill_missing_with_value(series, value) when is_atom(value) and not is_boolean(value) do + Shared.apply_series(series, :s_fill_missing_with_atom, [Atom.to_string(value)]) + end + + def fill_missing_with_value(series, value) do + operation = + cond do + is_float(value) -> :s_fill_missing_with_float + is_integer(value) -> :s_fill_missing_with_int + is_binary(value) -> :s_fill_missing_with_bin + is_boolean(value) -> :s_fill_missing_with_boolean + is_struct(value, Date) -> :s_fill_missing_with_date + is_struct(value, NaiveDateTime) -> :s_fill_missing_with_datetime + is_struct(value, Decimal) -> :s_fill_missing_with_decimal + true -> raise "cannot fill missing with value: #{inspect(value)}" + end + + Shared.apply_series(series, operation, [value]) + end + + @impl true + def is_nil(series), do: Shared.apply_series(series, :s_is_null) + + @impl true + def is_not_nil(series), do: Shared.apply_series(series, :s_is_not_null) + + @impl true + def transform(series, fun) do + series + |> Series.to_list() + |> Enum.map(fun) + |> Series.from_list(backend: Explorer.PolarsBackend) + end + + @impl true + def inspect(series, opts) do + Explorer.Backend.Series.inspect(series, "Polars", Series.size(series), opts) + end + + # Inversions + + @impl true + def unary_not(%Series{} = series), do: Shared.apply_series(series, :s_not, []) + + # Strings + + @impl true + def contains(series, substring), + do: Shared.apply_series(series, :s_contains, [substring, true]) + + @impl true + def re_contains(series, pattern), + do: Shared.apply_series(series, :s_contains, [pattern, false]) + + @impl true + def upcase(series), + do: Shared.apply_series(series, :s_upcase) + + @impl true + def downcase(series), + do: Shared.apply_series(series, :s_downcase) + + @impl true + def replace(series, pattern, replacement), + do: Shared.apply_series(series, :s_replace, [pattern, replacement, true]) + + @impl true + def re_replace(series, pattern, replacement), + do: Shared.apply_series(series, :s_replace, [pattern, replacement, false]) + + @impl true + def strip(series, str), + do: Shared.apply_series(series, :s_strip, [str]) + + @impl true + def lstrip(series, str), + do: Shared.apply_series(series, :s_lstrip, [str]) + + @impl true + def rstrip(series, str), + do: Shared.apply_series(series, :s_rstrip, [str]) + + @impl true + def substring(series, offset, length), + do: Shared.apply_series(series, :s_substring, [offset, length]) + + @impl true + def split(series, by), + do: Shared.apply_series(series, :s_split, [by]) + + @impl true + def split_into(series, by, fields), + do: Shared.apply_series(series, :s_split_into, [by, fields]) + + # Float round + @impl true + def round(series, decimals), + do: Shared.apply_series(series, :s_round, [decimals]) + + @impl true + def floor(series), + do: Shared.apply_series(series, :s_floor) + + @impl true + def ceil(series), + do: Shared.apply_series(series, :s_ceil) + + # Date / DateTime + @impl true + def day_of_week(series), + do: Shared.apply_series(series, :s_day_of_week) + + @impl true + def day_of_year(series), + do: Shared.apply_series(series, :s_day_of_year) + + @impl true + def week_of_year(series), + do: Shared.apply_series(series, :s_week_of_year) + + @impl true + def month(series), + do: Shared.apply_series(series, :s_month) + + @impl true + def year(series), + do: Shared.apply_series(series, :s_year) + + @impl true + def hour(series), + do: Shared.apply_series(series, :s_hour) + + @impl true + def minute(series), + do: Shared.apply_series(series, :s_minute) + + @impl true + def second(series), + do: Shared.apply_series(series, :s_second) + + # Lists + + @impl true + def join(series, separator), + do: Shared.apply_series(series, :s_join, [separator]) + + @impl true + def lengths(series), + do: Shared.apply_series(series, :s_lengths) + + @impl true + def member?(%Series{dtype: {:list, inner_dtype}} = series, value), + do: Shared.apply_series(series, :s_member, [value, inner_dtype]) + + @impl true + def field(%Series{dtype: {:struct, _inner_dtype}} = series, name), + do: Shared.apply_series(series, :s_field, [name]) + + @impl true + def json_decode(series, dtype), + do: Shared.apply_series(series, :s_json_decode, [dtype]) + + @impl true + def json_path_match(series, json_path), + do: Shared.apply_series(series, :s_json_path_match, [json_path]) + + @impl true + def count_matches(series, substring) do + Shared.apply_series(series, :s_count_matches, [substring, true]) + end + + @impl true + def re_count_matches(series, pattern) do + Shared.apply_series(series, :s_count_matches, [pattern, false]) + end + + @impl true + def re_scan(series, pattern) do + Shared.apply_series(series, :s_re_scan, [pattern]) + end + + @impl true + def re_named_captures(series, pattern) do + Shared.apply_series(series, :s_re_named_captures, [pattern]) + end + + # Polars specific functions + + def name(series), do: Shared.apply_series(series, :s_name) + def rename(series, name), do: Shared.apply_series(series, :s_rename, [name]) + + # Helpers + + defp matching_size!(series, other) do + case size(series) do + 1 -> + series + + i -> + case size(other) do + 1 -> + series + + ^i -> + series + + j -> + raise ArgumentError, + "series must either have the same size or one of them must have size of 1, got: #{i} and #{j}" + end + end + end +end + +defimpl Inspect, for: Explorer.PolarsBackend.Series do + import Inspect.Algebra + + def inspect(s, _opts) do + doc = + try do + Explorer.PolarsBackend.Native.s_as_str(s) + rescue + _ -> inspect(s.resource) + else + {:ok, str} -> str + {:error, _} -> inspect(s.resource) + end + |> String.split("\n") + |> Enum.intersperse(line()) + |> then(&concat([line() | &1])) + |> nest(2) + + concat(["#Explorer.PolarsBackend.Series<", doc, line(), ">"]) + end +end diff --git a/deps/explorer/lib/explorer/polars_backend/shared.ex b/deps/explorer/lib/explorer/polars_backend/shared.ex new file mode 100644 index 0000000000000000000000000000000000000000..81cb381d32a32ec67da623ffe2ce49ededdb82c5 --- /dev/null +++ b/deps/explorer/lib/explorer/polars_backend/shared.ex @@ -0,0 +1,300 @@ +defmodule Explorer.PolarsBackend.Shared do + # A collection of **private** helpers shared in Explorer.PolarsBackend. + @moduledoc false + + alias Explorer.DataFrame, as: DataFrame + alias Explorer.PolarsBackend.DataFrame, as: PolarsDataFrame + alias Explorer.PolarsBackend.LazyFrame, as: PolarsLazyFrame + alias Explorer.PolarsBackend.Native + alias Explorer.PolarsBackend.Series, as: PolarsSeries + alias Explorer.Series, as: Series + import Kernel, except: [apply: 2] + + @polars_df [PolarsDataFrame, PolarsLazyFrame] + + def apply(fun, args \\ []) do + case Kernel.apply(Native, fun, args) do + {:ok, value} -> value + {:error, error} -> raise runtime_error(error) + end + end + + # Applies to a series. Expects a series or a value back. + def apply_series(%Series{} = series, fun, args \\ []) do + case apply(Native, fun, [series.data | args]) do + {:ok, %PolarsSeries{} = new_series} -> create_series(new_series) + {:ok, value} -> value + {:error, error} -> raise runtime_error(error) + end + end + + # Applies to a dataframe. Expects a series or a value back. + def apply_dataframe(%DataFrame{} = df, fun, args \\ []) do + case apply(Native, fun, [df.data | args]) do + {:ok, %PolarsSeries{} = new_series} -> create_series(new_series) + {:ok, value} -> value + {:error, error} -> raise runtime_error(error) + end + end + + @check_frames Application.compile_env(:explorer, :check_polars_frames, false) + + # Applies to a dataframe. Expects a dataframe back. + def apply_dataframe(%DataFrame{} = df, %DataFrame{} = out_df, fun, args) do + case apply(Native, fun, [df.data | args]) do + {:ok, %module{} = new_df} when module in @polars_df -> + if @check_frames do + # We need to collect here, because the lazy frame may not have + # the full picture of the result yet. + check_df = + if match?(%PolarsLazyFrame{}, new_df) do + case Native.lf_compute(new_df) do + {:ok, new_df} -> create_dataframe!(new_df) + {:error, error} -> raise runtime_error(error) + end + else + create_dataframe!(new_df) + end + + if Enum.sort(out_df.names) != Enum.sort(check_df.names) or + out_df.dtypes != check_df.dtypes do + raise """ + DataFrame mismatch. + + expected: + + names: #{inspect(out_df.names)} + dtypes: #{inspect(out_df.dtypes)} + + got: + + names: #{inspect(check_df.names)} + dtypes: #{inspect(check_df.dtypes)} + """ + end + end + + %{out_df | data: new_df} + + {:error, error} -> + raise runtime_error(error) + end + end + + def create_series(%PolarsSeries{} = polars_series) do + dtype = + case Native.s_dtype(polars_series) do + {:ok, dtype} -> + dtype + + {:error, reason} -> + raise ArgumentError, reason + end + + Explorer.Backend.Series.new(polars_series, dtype) + end + + def create_dataframe(polars_df) do + with {:ok, names} <- df_names(polars_df), {:ok, dtypes} <- df_dtypes(polars_df) do + {:ok, Explorer.Backend.DataFrame.new(polars_df, names, dtypes)} + else + {:error, error} -> {:error, runtime_error(error)} + end + end + + def create_dataframe!(polars_df) do + case create_dataframe(polars_df) do + {:ok, df} -> df + {:error, error} -> raise error + end + end + + defp df_names(%PolarsDataFrame{} = polars_df) do + Native.df_names(polars_df) + end + + defp df_names(%PolarsLazyFrame{} = polars_df) do + Native.lf_names(polars_df) + end + + defp df_dtypes(%PolarsDataFrame{} = polars_df) do + Native.df_dtypes(polars_df) + end + + defp df_dtypes(%PolarsLazyFrame{} = polars_df) do + Native.lf_dtypes(polars_df) + end + + def from_list(list, dtype), do: from_list(list, dtype, "") + + def from_list(list, {:list, inner_dtype} = dtype, name) do + series = + Enum.map(list, fn + inner_list when is_list(inner_list) -> from_list(inner_list, inner_dtype, name) + _ -> nil + end) + + Native.s_from_list_of_series(name, series, dtype) + end + + def from_list(list, {:struct, fields} = dtype, name) when is_list(list) do + columns = Map.new(fields, fn {k, _v} -> {k, []} end) + + columns = + Enum.reduce(list, columns, fn + nil, columns -> + Enum.reduce(fields, columns, fn {field, _}, columns -> + Map.update!(columns, field, &[nil | &1]) + end) + + row, columns -> + Enum.reduce(row, columns, fn {field, value}, columns -> + Map.update!(columns, to_string(field), &[value | &1]) + end) + end) + + series = + for {field, inner_dtype} <- fields do + columns + |> Map.fetch!(field) + |> Enum.reverse() + |> from_list(inner_dtype, field) + end + + Native.s_from_list_of_series_as_structs(name, series, dtype) + end + + def from_list(list, dtype, name) when is_list(list) do + case dtype do + # Signed integers + {:s, 8} -> Native.s_from_list_s8(name, list) + {:s, 16} -> Native.s_from_list_s16(name, list) + {:s, 32} -> Native.s_from_list_s32(name, list) + {:s, 64} -> Native.s_from_list_s64(name, list) + # Unsigned integers + {:u, 8} -> Native.s_from_list_u8(name, list) + {:u, 16} -> Native.s_from_list_u16(name, list) + {:u, 32} -> Native.s_from_list_u32(name, list) + {:u, 64} -> Native.s_from_list_u64(name, list) + # Floats + {:f, 32} -> Native.s_from_list_f32(name, list) + {:f, 64} -> Native.s_from_list_f64(name, list) + :boolean -> Native.s_from_list_bool(name, list) + :string -> Native.s_from_list_str(name, list) + :category -> Native.s_from_list_categories(name, list) + :date -> apply(:s_from_list_date, [name, list]) + :time -> apply(:s_from_list_time, [name, list]) + {:naive_datetime, precision} -> apply(:s_from_list_naive_datetime, [name, list, precision]) + {:datetime, precision, tz} -> apply(:s_from_list_datetime, [name, list, precision, tz]) + {:duration, precision} -> apply(:s_from_list_duration, [name, list, precision]) + :binary -> Native.s_from_list_binary(name, list) + :null -> Native.s_from_list_null(name, length(list)) + {:decimal, precision, scale} -> apply(:s_from_list_decimal, [name, list, precision, scale]) + end + end + + def from_binary(binary, dtype, name \\ "") when is_binary(binary) do + case dtype do + :boolean -> + Native.s_from_binary_u8(name, binary) |> Native.s_cast(dtype) |> ok() + + :date -> + Native.s_from_binary_s32(name, binary) |> Native.s_cast(dtype) |> ok() + + :time -> + Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok() + + {:naive_datetime, :millisecond} -> + Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok() + + {:naive_datetime, :microsecond} -> + Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok() + + {:naive_datetime, :nanosecond} -> + Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok() + + {:duration, :millisecond} -> + Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok() + + {:duration, :microsecond} -> + Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok() + + {:duration, :nanosecond} -> + Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok() + + {:s, 8} -> + Native.s_from_binary_s8(name, binary) + + {:s, 16} -> + Native.s_from_binary_s16(name, binary) + + {:s, 32} -> + Native.s_from_binary_s32(name, binary) + + {:s, 64} -> + Native.s_from_binary_s64(name, binary) + + {:u, 8} -> + Native.s_from_binary_u8(name, binary) + + {:u, 16} -> + Native.s_from_binary_u16(name, binary) + + {:u, 32} -> + Native.s_from_binary_u32(name, binary) + + {:u, 64} -> + Native.s_from_binary_u64(name, binary) + + {:f, 32} -> + Native.s_from_binary_f32(name, binary) + + {:f, 64} -> + Native.s_from_binary_f64(name, binary) + end + end + + defp ok({:ok, value}), do: value + + defp runtime_error(error) when is_binary(error), do: RuntimeError.exception(error) + + def parquet_compression(nil, _), do: :uncompressed + + def parquet_compression(algorithm, level) when algorithm in ~w(gzip brotli zstd)a, + do: {algorithm, level} + + def parquet_compression(algorithm, _) when algorithm in ~w(snappy lz4raw)a, do: algorithm + + @doc """ + Builds and returns a path for a new file. + + It saves in a directory called "elixir-explorer-datasets" inside + the `System.tmp_dir()`. + """ + def build_path_for_entry(%FSS.S3.Entry{} = entry) do + bucket = entry.config.bucket || "default-explorer-bucket" + + hash = + :crypto.hash(:sha256, entry.config.endpoint <> "/" <> bucket <> "/" <> entry.key) + |> Base.url_encode64(padding: false) + + id = "s3-file-#{hash}" + + build_tmp_path(id) + end + + def build_path_for_entry(%FSS.HTTP.Entry{} = entry) do + hash = :crypto.hash(:sha256, entry.url) |> Base.url_encode64(padding: false) + + id = "http-file-#{hash}" + + build_tmp_path(id) + end + + defp build_tmp_path(id) do + base_dir = Path.join([System.tmp_dir!(), "elixir-explorer-datasets"]) + File.mkdir_p!(base_dir) + + Path.join([base_dir, id]) + end +end diff --git a/deps/explorer/lib/explorer/query.ex b/deps/explorer/lib/explorer/query.ex new file mode 100644 index 0000000000000000000000000000000000000000..7cccd63abcd9ffcef7c11c1fa2454a4ec5c11fd7 --- /dev/null +++ b/deps/explorer/lib/explorer/query.ex @@ -0,0 +1,826 @@ +import Kernel, except: [if: 2, unless: 2] + +defmodule Explorer.Query do + @moduledoc ~S""" + High-level query for Explorer. + + > #### Explorer.DataFrame vs DF {: .tip} + > + > All examples below assume you have defined aliased + > `Explorer.DataFrame` to `DF` as shown below: + > + > require Explorer.DataFrame, as: DF + > + + Queries convert regular Elixir code which compile to efficient + dataframes operations. Inside a query, only the limited set of + Series operations are available and identifiers, such as `strs` + and `nums`, represent dataframe column names: + + iex> df = DF.new(strs: ["a", "b", "c"], nums: [1, 2, 3]) + iex> DF.filter(df, nums > 2) + #Explorer.DataFrame< + Polars[1 x 2] + strs string ["c"] + nums s64 [3] + > + + If a column has unusual format, you can either rename it before-hand, + or use `col/1` inside queries: + + iex> df = DF.new("unusual nums": [1, 2, 3]) + iex> DF.filter(df, col("unusual nums") > 2) + #Explorer.DataFrame< + Polars[1 x 1] + unusual nums s64 [3] + > + + All operations from `Explorer.Series` are imported inside queries. + This module also provides operators to use in queries, which are + also imported into queries. + + ## Supported operations + + Queries are supported in the following operations: + + * `Explorer.DataFrame.sort_by/2` + * `Explorer.DataFrame.filter/2` + * `Explorer.DataFrame.mutate/2` + * `Explorer.DataFrame.summarise/2` + + ## Interpolation + + If you want to access variables defined outside of the query + or get access to all Elixir constructs, you must use `^`: + + iex> min = 2 + iex> df = DF.new(strs: ["a", "b", "c"], nums: [1, 2, 3]) + iex> DF.filter(df, nums > ^min) + #Explorer.DataFrame< + Polars[1 x 2] + strs string ["c"] + nums s64 [3] + > + + iex> min = 2 + iex> df = DF.new(strs: ["a", "b", "c"], nums: [1, 2, 3]) + iex> DF.filter(df, nums < ^if(min > 0, do: 10, else: -10)) + #Explorer.DataFrame< + Polars[3 x 2] + strs string ["a", "b", "c"] + nums s64 [1, 2, 3] + > + + `^` can be used with `col` to access columns dynamically: + + iex> df = DF.new("unusual nums": [1, 2, 3]) + iex> name = "unusual nums" + iex> DF.filter(df, col(^name) > 2) + #Explorer.DataFrame< + Polars[1 x 1] + unusual nums s64 [3] + > + + ## Conditionals + + Queries support both `if/2` and `unless/2` operations inside queries. + + `cond/1` can be used to write multi-clause conditions: + + iex> df = DF.new(a: [10, 4, 6]) + iex> DF.mutate(df, + ...> b: + ...> cond do + ...> a > 9 -> "Exceptional" + ...> a > 5 -> "Passed" + ...> true -> "Failed" + ...> end + ...> ) + #Explorer.DataFrame< + Polars[3 x 2] + a s64 [10, 4, 6] + b string ["Exceptional", "Failed", "Passed"] + > + + ## Across and comprehensions + + `Explorer.Query` leverages the power behind Elixir for-comprehensions + to provide a powerful syntax for traversing several columns in a dataframe + at once. For example, imagine you want to standardize the data on the + iris dataset, you could write this: + + iex> iris = Explorer.Datasets.iris() + iex> DF.mutate(iris, + ...> sepal_width: (sepal_width - mean(sepal_width)) / variance(sepal_width), + ...> sepal_length: (sepal_length - mean(sepal_length)) / variance(sepal_length), + ...> petal_length: (petal_length - mean(petal_length)) / variance(petal_length), + ...> petal_width: (petal_width - mean(petal_width)) / variance(petal_width) + ...> ) + #Explorer.DataFrame< + Polars[150 x 5] + sepal_length f64 [-1.0840606189132322, -1.3757361217598405, -1.66741162460645, -1.8132493760297554, -1.2298983703365363, ...] + sepal_width f64 [2.3722896125315045, -0.28722789030650403, 0.7765791108287005, 0.2446756102610982, 2.9041931130991068, ...] + petal_length f64 [-0.7576391687443839, -0.7576391687443839, -0.7897606710936369, -0.7255176663951307, -0.7576391687443839, ...] + petal_width f64 [-1.7147014356654708, -1.7147014356654708, -1.7147014356654708, -1.7147014356654708, -1.7147014356654708, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + > + + While the code above does its job, it is quite repetitive. With across and for-comprehensions, + we could instead write: + + iex> iris = Explorer.Datasets.iris() + iex> DF.mutate(iris, + ...> for col <- across(["sepal_width", "sepal_length", "petal_length", "petal_width"]) do + ...> {col.name, (col - mean(col)) / variance(col)} + ...> end + ...> ) + #Explorer.DataFrame< + Polars[150 x 5] + sepal_length f64 [-1.0840606189132322, -1.3757361217598405, -1.66741162460645, -1.8132493760297554, -1.2298983703365363, ...] + sepal_width f64 [2.3722896125315045, -0.28722789030650403, 0.7765791108287005, 0.2446756102610982, 2.9041931130991068, ...] + petal_length f64 [-0.7576391687443839, -0.7576391687443839, -0.7897606710936369, -0.7255176663951307, -0.7576391687443839, ...] + petal_width f64 [-1.7147014356654708, -1.7147014356654708, -1.7147014356654708, -1.7147014356654708, -1.7147014356654708, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + > + + Which achieves the same result in a more concise and maintainable way. + `across/1` may receive any of the following input as arguments: + + * a list of columns indexes or names as atoms and strings + + * a range + + * a regex that keeps only the names matching the regex + + For example, since we know the width and length columns are the first four, + we could also have written (remember ranges in Elixir are inclusive): + + DF.mutate(iris, + for col <- across(0..3) do + {col.name, (col - mean(col)) / variance(col)} + end + ) + + Or using a regex: + + DF.mutate(iris, + for col <- across(~r/(sepal|petal)_(length|width)/) do + {col.name, (col - mean(col)) / variance(col)} + end + ) + + For those new to Elixir, for-comprehensions have the following format: + + for PATTERN <- GENERATOR, FILTER do + EXPR + end + + A comprehension filter is a mechanism that allows us to keep only columns + based on additional properties, such as its `dtype`. A for-comprehension can + have multiple generators and filters. For instance, if you want to apply + standardization to all float columns, we can use `across/0` to access all + columns and then use a filter to keep only the float ones: + + iex> iris = Explorer.Datasets.iris() + iex> DF.mutate(iris, + ...> for col <- across(), col.dtype == {:f, 64} do + ...> {col.name, (col - mean(col)) / variance(col)} + ...> end + ...> ) + #Explorer.DataFrame< + Polars[150 x 5] + sepal_length f64 [-1.0840606189132322, -1.3757361217598405, -1.66741162460645, -1.8132493760297554, -1.2298983703365363, ...] + sepal_width f64 [2.3722896125315045, -0.28722789030650403, 0.7765791108287005, 0.2446756102610982, 2.9041931130991068, ...] + petal_length f64 [-0.7576391687443839, -0.7576391687443839, -0.7897606710936369, -0.7255176663951307, -0.7576391687443839, ...] + petal_width f64 [-1.7147014356654708, -1.7147014356654708, -1.7147014356654708, -1.7147014356654708, -1.7147014356654708, ...] + species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...] + > + + For-comprehensions works with all dataframe verbs. As we have seen + above, for mutations we must return tuples as pair with the mutation + name and its value. `summarise` works similarly. Note in both cases + the name could also be generated dynamically. For example, to compute + the mean per species, you could write: + + iex> Explorer.Datasets.iris() + ...> |> DF.group_by("species") + ...> |> DF.summarise( + ...> for col <- across(), col.dtype == {:f, 64} do + ...> {"#{col.name}_mean", round(mean(col), 3)} + ...> end + ...> ) + #Explorer.DataFrame< + Polars[3 x 5] + species string ["Iris-setosa", "Iris-versicolor", "Iris-virginica"] + sepal_length_mean f64 [5.006, 5.936, 6.588] + sepal_width_mean f64 [3.418, 2.77, 2.974] + petal_length_mean f64 [1.464, 4.26, 5.552] + petal_width_mean f64 [0.244, 1.326, 2.026] + > + + `sort_by` expects a list of columns to sort by, while for-comprehensions + in `filter` generate a list of conditions, which are joined using `and`. + For example, to filter all entries have both sepal and petal length above + average, using a filter on the column name, one could write: + + iex> iris = Explorer.Datasets.iris() + iex> DF.filter(iris, + ...> for col <- across(), String.ends_with?(col.name, "_length") do + ...> col > mean(col) + ...> end + ...> ) + #Explorer.DataFrame< + Polars[70 x 5] + sepal_length f64 [7.0, 6.4, 6.9, 6.5, 6.3, ...] + sepal_width f64 [3.2, 3.2, 3.1, 2.8, 3.3, ...] + petal_length f64 [4.7, 4.5, 4.9, 4.6, 4.7, ...] + petal_width f64 [1.4, 1.5, 1.5, 1.5, 1.6, ...] + species string ["Iris-versicolor", "Iris-versicolor", "Iris-versicolor", "Iris-versicolor", "Iris-versicolor", ...] + > + + > #### Do not mix comprehension and queries {: .warning} + > + > The filter inside a for-comprehension works at the meta level: + > it can only filter columns based on their names and dtypes, but + > not on their values. For example, this code does not make any + > sense and it will fail to compile: + > + > |> DF.filter( + > for col <- across(), col > mean(col) do + > col + > end + > end) + > + > Another way to think about it, the comprehensions traverse on the + > columns themselves, the contents inside the comprehension do-block + > traverse on the values inside the columns. + + ## Implementation details + + Queries simply become lazy dataframe operations at runtime. + For example, the following query + + Explorer.DataFrame.filter(df, nums > 2) + + is equivalent to + + Explorer.DataFrame.filter_with(df, fn df -> Explorer.Series.greater(df["nums"], 2) end) + + This means that, whenever you want to generate queries programatically, + you can fallback to the regular `_with` APIs. + + In the `_with` APIs, the callbacks receive an `Explorer.DataFrame` as an + input. That dataframe is backed by the special `Explorer.Backend.QueryFrame` + backend. + + Explorer.DataFrame.filter_with(df, fn query_backed_frame -> + IO.inspect(query_backed_frame) + ... + end) + # #Explorer.DataFrame< + # QueryFrame[??? x 1] + # ... + # > + + A "query-backed" dataframe cannot be manipulated. You may only access its + series. And when you do, you get back "lazy-backed" versions of those series: + + Explorer.DataFrame.filter_with(df, fn query_backed_frame -> + IO.inspect(query_backed_frame["a"]) + ... + end) + # #Explorer.Series< + # LazySeries[???] + # s64 (column("a")) + # > + + "Lazy-backed" series are backed by the special `Explorer.Backend.LazySeries` + backend. All `Explorer.Series` functions work on lazy-backed series too. So + you can write your `_with` callbacks without ever referencing the fact that + the backend is the lazy one. + """ + + kernel_all = Kernel.__info__(:functions) ++ Kernel.__info__(:macros) + + kernel_only = [ + @: 1, + |>: 2, + dbg: 0, + dbg: 1, + dbg: 2, + sigil_c: 2, + sigil_C: 2, + sigil_D: 2, + sigil_N: 2, + sigil_s: 2, + sigil_S: 2, + sigil_w: 2, + sigil_W: 2, + tap: 2, + then: 2 + ] + + @kernel_only kernel_only -- kernel_only -- kernel_all + + @doc """ + Returns a "query-backed" `Explorer.DataFrame` for use in queries. + + This function is mostly an implementation detail for the `*_with` callbacks. + See the "Implementation details" section of the `@moduledoc` for details. + + There are some limited instances where it's more convenient to work with + query-backed `DataFrame`s. For example, if you want to re-use a lazy series, + you can do so like this: + + alias Explorer.{DataFrame, Query, Series} + + df = DataFrame.new(a: [1, 2, 3]) + qf = Query.new(df) + + gt_1 = Series.greater(qf["a"], 1) + lt_3 = Series.less(qf["a"], 3) + + df + |> DataFrame.filter_with(gt_1) + |> DataFrame.to_columns(atom_keys: true) + #=> %{a: [2, 3]} + + df + |> DataFrame.filter_with(lt_3) + |> DataFrame.to_columns(atom_keys: true) + #=> %{a: [1, 2]} + + df + |> DataFrame.filter_with(Series.and(gt_1, lt_3)) + |> DataFrame.to_columns(atom_keys: true) + #=> %{a: [2]} + + However, if you think you need `new/1`, first check that you can't accomplish + the same thing with `across/0` inside a macro. The latter is usually easier to + work with. + """ + def new(%Explorer.DataFrame{} = df) do + Explorer.Backend.QueryFrame.new(df) + end + + @doc """ + Builds an anonymous function from a query. + + This is the entry point used by `Explorer.DataFrame.filter/2` + and friends to convert queries into anonymous functions. + See the moduledoc for more information. + """ + defmacro query(expression) do + df = df_var() + + quote do + fn unquote(df) -> + unquote(traverse(expression, df)) + end + end + end + + defp traverse({:for, meta, [_ | _] = args}, df) do + {args, [opts]} = Enum.split(args, Kernel.-(1)) + + block = + Keyword.get(opts, :do) || raise ArgumentError, "expected do-block in for-comprehension" + + {args, known_vars} = + Enum.map_reduce(args, %{}, fn + {:<-, meta, [pattern, generator]}, acc -> + generator = traverse_for(generator, df, acc) + {{:<-, meta, [pattern, generator]}, collect_pattern_vars(pattern, acc)} + + other, acc -> + {traverse_for(other, df, acc), acc} + end) + + {query, vars} = + traverse(block, [], %{df: df, known_vars: known_vars, collect_pins_and_vars: true}) + + block = + quote do + unquote_splicing(Enum.reverse(vars)) + import Kernel, only: unquote(@kernel_only) + import Explorer.Query, except: [query: 1] + import Explorer.Series + unquote(query) + end + + for = {:for, meta, args ++ [Keyword.put(opts, :do, block)]} + + quote do + import Explorer.Query, only: [across: 0, across: 1] + unquote(for) + end + end + + defp traverse(expression, df) do + {query, vars} = + traverse(expression, [], %{df: df, known_vars: %{}, collect_pins_and_vars: true}) + + quote do + unquote_splicing(Enum.reverse(vars)) + import Kernel, only: unquote(@kernel_only) + import Explorer.Query, except: [query: 1] + import Explorer.Series, except: [and: 2, or: 2, not: 1] + unquote(query) + end + end + + defp traverse({:^, meta, [expr]}, vars, state) do + cond do + state.collect_pins_and_vars -> + var = Macro.unique_var(:pin, __MODULE__) + {var, [{:=, meta, [var, expr]} | vars]} + + true -> + {expr, vars} + end + end + + defp traverse({:for, _meta, [_ | _]}, _vars, _state) do + raise ArgumentError, "for-comprehensions are only supported at the root of queries" + end + + defp traverse({:"::", meta, [left, right]}, vars, state) do + {left, vars} = traverse(left, vars, state) + {{:"::", meta, [left, right]}, vars} + end + + defp traverse({:cond, _meta, [[do: clauses]]}, vars, state) do + {clauses, vars} = + Enum.map_reduce(clauses, vars, fn {:->, _, [[on_condition], on_true]}, vars -> + {condition, vars} = traverse(on_condition, vars, state) + {truthy, vars} = traverse(on_true, vars, state) + {{condition, truthy}, vars} + end) + + body = + quote do + Explorer.Query.__cond__(unquote(Enum.reverse(clauses))) + end + + {body, vars} + end + + defp traverse({var, meta, ctx} = expr, vars, state) + when Kernel.and(is_atom(var), is_atom(ctx)) do + cond do + Map.has_key?(state.known_vars, {var, ctx}) -> + {expr, vars} + + state.collect_pins_and_vars -> + {{{:., meta, [Explorer.DataFrame, :pull]}, meta, [state.df, var]}, vars} + + true -> + raise ArgumentError, "undefined variable \"#{Macro.to_string(expr)}\"" + end + end + + defp traverse({left, meta, right}, vars, state) do + cond do + Kernel.and( + Kernel.and(is_atom(left), is_list(right)), + special_form_defines_var?(left, right) + ) -> + raise ArgumentError, + "#{left}/#{length(right)} is not currently supported in Explorer.Query" + + true -> + {left, vars} = traverse(left, vars, state) + {right, vars} = traverse(right, vars, state) + {{left, meta, right}, vars} + end + end + + defp traverse({left, right}, vars, state) do + {left, vars} = traverse(left, vars, state) + {right, vars} = traverse(right, vars, state) + {{left, right}, vars} + end + + defp traverse(list, vars, state) when is_list(list) do + Enum.map_reduce(list, vars, &traverse(&1, &2, state)) + end + + defp traverse(other, vars, _state), do: {other, vars} + + defp special_form_defines_var?(:=, [_, _]), do: true + defp special_form_defines_var?(:case, [_, _]), do: true + defp special_form_defines_var?(:receive, [_]), do: true + defp special_form_defines_var?(:try, [_]), do: true + defp special_form_defines_var?(:with, [_ | _]), do: true + defp special_form_defines_var?(_, _), do: false + + defp traverse_for(expr, df, known_vars) do + {expr, []} = + traverse(expr, [], %{df: df, known_vars: known_vars, collect_pins_and_vars: false}) + + expr + end + + defp collect_pattern_vars({:when, _, [pattern, _]}, known_vars) do + collect_pattern_vars(pattern, known_vars) + end + + defp collect_pattern_vars(expr, known_vars) do + expr + |> Macro.prewalk(known_vars, fn + {:"::", _, [left, _right]}, acc -> + {left, acc} + + {skip, _, [_ | _]}, acc when skip in [:^, :@, :quote] -> + {:ok, acc} + + {:_, _, context}, acc when is_atom(context) -> + {:ok, acc} + + {name, _meta, context}, acc when Kernel.and(is_atom(name), is_atom(context)) -> + {:ok, Map.put(acc, {name, context}, true)} + + node, acc -> + {node, acc} + end) + |> elem(1) + end + + # and and or are sent as is to queries + binary_delegates = [ + ==: :equal, + !=: :not_equal, + >: :greater, + >=: :greater_equal, + <: :less, + <=: :less_equal, + +: :add, + -: :subtract, + *: :multiply, + /: :divide, + **: :pow + ] + + for {operator, delegate} <- binary_delegates do + @doc """ + Delegate to `Explorer.Series.#{delegate}/2`. + """ + def unquote(operator)(left, right), do: Explorer.Series.unquote(delegate)(left, right) + end + + @doc """ + Unary minus operator. + + Works with numbers and series. + """ + def -number when is_number(number), do: Kernel.-(number) + + def -series when is_struct(series, Explorer.Series), + do: Explorer.Series.multiply(series, Kernel.-(1)) + + @doc """ + Unary plus operator. + + Works with numbers and series. + """ + def +number when is_number(number), do: number + def +series when is_struct(series, Explorer.Series), do: series + + @doc """ + Binary and operator. + + Works with boolean and series. + """ + def left and right when Kernel.and(is_boolean(left), is_boolean(right)), + do: Kernel.and(left, right) + + def left and right, do: Explorer.Series.and(boolean!(left), boolean!(right)) + + @doc """ + Binary or operator. + + Works with boolean and series. + """ + def left or right when Kernel.or(is_boolean(left), is_boolean(right)), + do: Kernel.or(left, right) + + def left or right, do: Explorer.Series.or(boolean!(left), boolean!(right)) + + @doc """ + Unary not operator. + + Works with boolean and series. + """ + def not value when is_boolean(value), do: Kernel.not(value) + + def not value, do: Explorer.Series.not(boolean!(value)) + + defp boolean!(%Explorer.Series{dtype: :boolean} = series), do: series + defp boolean!(value) when is_boolean(value), do: Explorer.Series.from_list([value]) + + defp boolean!(other) do + raise ArgumentError, + "boolean operators require either a boolean (true/false) or a boolean series, got: #{inspect(other)}" + end + + @doc """ + String concatenation operator. + + Works with strings and series of strings. + + ## Examples + + DF.mutate(df, name: first_name <> " " <> last_name) + + If you want to convert concatenate non-string + series, you can explicitly cast them to string + before: + + DF.mutate(df, name: cast(year, :string) <> "-" <> cast(month, :string)) + + Or use format: + + DF.mutate(df, name: format([year, "-", month])) + """ + defmacro left <> right do + parts = [left | extract_concatenations(right)] + + quote do + unquote(__MODULE__).__concatenate__(unquote(parts)) + end + end + + defp extract_concatenations({:<>, _, [left, right]}), do: [left | extract_concatenations(right)] + defp extract_concatenations(other), do: [other] + + @doc false + def __concatenate__(parts) do + case validate_concatenation(parts, true) do + true -> IO.iodata_to_binary(parts) + false -> Explorer.Series.format(parts) + end + end + + @error_message "the string concatenation operator (<>) inside Explorer.Query expects either " <> + "an Elixir string or a Series with :string dtype, got: " + + defp validate_concatenation([%Explorer.Series{dtype: :string} | parts], _all_binary?) do + validate_concatenation(parts, false) + end + + defp validate_concatenation([%Explorer.Series{} = part | _parts], _all_binary?) do + raise ArgumentError, + <<@error_message, inspect(part)::binary, + " (use cast(series, :string) to convert an existing series)"::binary>> + end + + defp validate_concatenation([part | parts], all_binary?) when is_binary(part) do + validate_concatenation(parts, all_binary?) + end + + defp validate_concatenation([part | _parts], _all_binary?) do + raise ArgumentError, + <<@error_message, inspect(part)::binary, + " (use Kernel.to_string(value) to convert an existing value to string)">> + end + + defp validate_concatenation([], all_binary?), do: all_binary? + + @doc """ + Provides `if/2` conditionals inside queries. + """ + def if(condition, do: do_clause) do + if(condition, do: do_clause, else: nil) + end + + def if(condition, do: do_clause, else: else_clause) do + __cond__([{true, else_clause}, {condition, do_clause}]) + end + + def if(_condition, _arguments) do + raise ArgumentError, + "invalid or duplicate keys for if, only \"do\" and an optional \"else\" are permitted" + end + + @doc """ + Provides `unless/2` conditionals inside queries. + """ + def unless(condition, do: do_clause) do + unless(condition, do: do_clause, else: nil) + end + + def unless(condition, do: do_clause, else: else_clause) do + __cond__([{true, do_clause}, {condition, else_clause}]) + end + + def unless(_condition, _arguments) do + raise ArgumentError, + "invalid or duplicate keys for unless, only \"do\" and an optional \"else\" are permitted" + end + + @doc false + def __cond__(clauses) do + Enum.reduce(clauses, nil, fn + {true, truthy}, _acc -> + lazy_series_for_cond!(truthy, clauses) + + {false, _truthy}, acc -> + lazy_series_for_cond!(acc, clauses) + + {%Explorer.Series{} = predicate, truthy}, acc -> + on_true = lazy_series_for_cond!(truthy, clauses) + on_false = lazy_series_for_cond!(acc, clauses) + Explorer.Backend.LazySeries.select(predicate, on_true, on_false) + + {other, _truthy}, _acc -> + raise ArgumentError, + "conditionals expect predicates to be series or a boolean, got: #{inspect(other)}" + end) + end + + defp lazy_series_for_cond!(%Explorer.Series{} = val, _clauses), do: val + + defp lazy_series_for_cond!(nil, clauses) do + {_, non_empty_clause} = Enum.find(clauses, fn {_condition, truthy} -> truthy end) + series = lazy_series_for_cond!(non_empty_clause, clauses) + Explorer.Backend.LazySeries.from_list([nil], series.dtype) + end + + defp lazy_series_for_cond!(val, _clauses), + do: Explorer.Backend.LazySeries.from_list([val], Explorer.Shared.dtype_from_list!([val])) + + @doc """ + Accesses a column by name. + + If your column name contains whitespace or start with + uppercase letters, you can still access its name by + using this macro: + + iex> df = Explorer.DataFrame.new("unusual nums": [1, 2, 3]) + iex> Explorer.DataFrame.filter(df, col("unusual nums") > 2) + #Explorer.DataFrame< + Polars[1 x 1] + unusual nums s64 [3] + > + + `name` must be an atom, a string, or an integer. + It is equivalent to `df[name]` but inside a query. + + This can also be used if you want to access a column + programmatically, for example: + + iex> df = Explorer.DataFrame.new(nums: [1, 2, 3]) + iex> name = :nums + iex> Explorer.DataFrame.filter(df, col(^name) > 2) + #Explorer.DataFrame< + Polars[1 x 1] + nums s64 [3] + > + + For traversing multiple columns programmatically, + see `across/0` and `across/1`. + """ + defmacro col(name) do + quote do: Explorer.DataFrame.pull(unquote(df_var()), unquote(name)) + end + + @doc """ + Accesses all columns in the dataframe. + + This is the equivalent to `across(..)`. + + See the module docs for more information. + """ + defmacro across() do + quote do + Explorer.Query.__across__(unquote(df_var()), ..) + end + end + + @doc """ + Accesses the columns given by `selector` in the dataframe. + + `across/1` is used as the generator inside for-comprehensions. + + See the module docs for more information. + """ + defmacro across(selector) do + quote do + Explorer.Query.__across__(unquote(df_var()), unquote(selector)) + end + end + + @doc """ + Returns the dataframe scoped by this query. + """ + defmacro df(), do: df_var() + + @doc false + def __across__(df, selector) do + df + |> Explorer.Shared.to_existing_columns(selector) + |> Enum.map(&%{Explorer.Shared.apply_dataframe(df, :pull, [&1]) | name: &1}) + end + + defp df_var(), do: quote(do: var!(df, Explorer.Query)) +end diff --git a/deps/explorer/lib/explorer/remote.ex b/deps/explorer/lib/explorer/remote.ex new file mode 100644 index 0000000000000000000000000000000000000000..6248158f01fa0a501695c3f7ad03d8f10e635d6a --- /dev/null +++ b/deps/explorer/lib/explorer/remote.ex @@ -0,0 +1,230 @@ +defmodule Explorer.Remote do + @moduledoc """ + A module responsible for placing remote dataframes and + garbage collect them. + + The functions in `Explorer.DataFrame` and `Explorer.Series` + will automatically move operations on remote dataframes to + the nodes they belong to. `Explorer` also integrates with + `FLAME` and automatically tracks remote dataframes and + series returned from `FLAME` calls when the `:track_resources` + option is enabled. + + This module provides additional conveniences for manual placement. + + ## Implementation details + + In order to understand what this module does, we need + to understand the challenges in working with remote series + and dataframes. + + Series and dataframes are actually NIF resources: they are + pointers to blobs of memory operated by low-level libraries. + Those are represented in Erlang/Elixir as references (the + same as the one returned by `make_ref/0`). Once the reference + is garbage collected (based on refcounting), those NIF + resources are garbage collected and the memory is reclaimed. + + When using Distributed Erlang, you may write this code: + + remote_series = :erpc.call(node, Explorer.Series, :from_list, [[1, 2, 3]]) + + However, the code above will not work, because the series + will be allocated in the remote node and the remote node + won't hold a reference to said series! This means the series + is garbage collected and if we attempt to read it later on, + from the caller node, it will no longer exist. Therefore, + we must explicitly place these resources in remote nodes + by spawning processes to hold these references. That's what + the `place/2` function in this module does. + + We also need to guarantee these resources are not kept + forever by these remote nodes, so `place/2` creates a + local NIF resource that notifies the remote resources + they have been GCed, effectively implementing a remote + garbage collector. + """ + + @doc """ + Receives a data structure and traverses it looking + for remote dataframes and series. + + If any is found, it spawns a process on the remote node + and sets up a distributed garbage collector. This function + only traverses maps, lists, and tuples, it does not support + arbitrary structs (such as map sets). + + It returns the updated term and a list of remote PIDs + spawned. + """ + def place(term, acc \\ []), do: place_on_node(term, acc) + + defp place_on_node(term, acc) do + place(term, acc, &Explorer.Remote.Holder.start_child/2) + end + + defp place_on_pid(term, remote_pid) do + place(term, [], fn _remote_ref, _local_gc -> + {:ok, remote_pid} + end) + end + + defp place(tuple, acc, fun) when is_tuple(tuple) do + {list, acc} = tuple |> Tuple.to_list() |> place(acc, fun) + {List.to_tuple(list), acc} + end + + defp place(list, acc, fun) when is_list(list) do + Enum.map_reduce(list, acc, &place(&1, &2, fun)) + end + + defp place(%Explorer.Backend.LazySeries{args: args} = lazy_series, acc, fun) do + {args, acc} = Enum.map_reduce(args, acc, &place(&1, &2, fun)) + {%{lazy_series | args: args}, acc} + end + + defp place(%Explorer.Series{data: %Explorer.Backend.LazySeries{} = data} = series, acc, fun) do + {data, acc} = place(data, acc, fun) + {%{series | data: data}, acc} + end + + defp place(%Explorer.Series{data: %impl{}} = series, acc, fun) do + place_impl(impl, series, acc, fun) + end + + defp place(%Explorer.DataFrame{data: %impl{}} = df, acc, fun) do + place_impl(impl, df, acc, fun) + end + + defp place(%_{} = other, acc, _fun) do + {other, acc} + end + + defp place(%{} = map, acc, fun) do + {pairs, acc} = + Enum.map_reduce(map, acc, fn {k, v}, acc -> + {k, acc} = place(k, acc, fun) + {v, acc} = place(v, acc, fun) + {{k, v}, acc} + end) + + {Map.new(pairs), acc} + end + + defp place(other, acc, _fun) do + {other, acc} + end + + defp place_impl(impl, struct, acc, fun) do + with remote_ref when is_reference(remote_ref) and node(remote_ref) != node() <- + impl.owner_reference(struct), + false <- alive?(remote_ref, struct) do + {local_ref, remote_pid} = place_remote_ref(remote_ref, fun) + {%{struct | remote: {local_ref, remote_pid, remote_ref}}, [remote_pid | acc]} + else + _ -> + {struct, acc} + end + end + + defp alive?(remote_ref, %{remote: {local_gc_ref, _, remote_ref}}) + when is_reference(local_gc_ref) and node(local_gc_ref) == node(), + do: Explorer.Remote.LocalGC.alive?(local_gc_ref) + + defp alive?(_remote_ref, _struct), do: false + + defp place_remote_ref(remote_ref, fun) do + local_gc = Explorer.Remote.LocalGC.whereis!() + {:ok, remote_pid} = fun.(remote_ref, local_gc) + local_ref = Explorer.Remote.LocalGC.track(local_gc, remote_pid, remote_ref) + Explorer.Remote.Holder.hold(remote_pid, remote_ref, local_gc) + {local_ref, remote_pid} + end + + @doc false + # Applies the given mod/fun/args in the remote node. + # If a pid is given, we assume the pid will hold those references + # and avoid spawning new ones. If a node is given, regular placement + # occurs. + def apply(pid, mod, fun, resources, args_callback, place?) when is_pid(pid) do + placing_callback = if place?, do: &place_on_pid(&1, pid), else: &{&1, []} + do_apply(node(pid), mod, fun, resources, args_callback, placing_callback) + end + + def apply(node, mod, fun, resources, args_callback, place?) when is_atom(node) do + placing_callback = if place?, do: &place_on_node(&1, []), else: &{&1, []} + do_apply(node, mod, fun, resources, args_callback, placing_callback) + end + + defp do_apply(node, mod, fun, resources, args_callback, placing_callback) do + resources = + Enum.map(resources, fn + {resource_data, resource_node} when resource_node == node or resource_node == nil -> + {:local, resource_data} + + {%{data: %impl{}} = resource_data, resource_node} -> + {:remote, impl, owner_export(resource_node, impl, resource_data)} + end) + + message_ref = :erlang.make_ref() + remote_args = [self(), message_ref, mod, fun, resources, args_callback] + child = Node.spawn_link(node, __MODULE__, :remote_apply, remote_args) + monitor_ref = Process.monitor(child) + + receive do + {^message_ref, result} -> + Process.demonitor(monitor_ref, [:flush]) + {term, _acc} = placing_callback.(result) + send(child, {message_ref, :ok}) + term + + {:DOWN, ^monitor_ref, _, _, reason} -> + exit(reason) + end + end + + defp owner_export(resource_node, impl, resource_data) do + case :erpc.call(resource_node, impl, :owner_export, [resource_data]) do + {:ok, val} -> val + {:error, error} -> raise error + end + end + + defp owner_import(impl, exported_data) do + case impl.owner_import(exported_data) do + {:ok, val} -> val + {:error, error} -> raise error + end + end + + @doc false + def remote_apply(parent, message_ref, mod, fun, resources, args_callback) do + resources = + Enum.map(resources, fn + {:local, value} -> value + {:remote, impl, value} -> owner_import(impl, value) + end) + + monitor_ref = Process.monitor(parent) + result = apply(mod, fun, args_callback.(resources)) + send(parent, {message_ref, result}) + + receive do + {^message_ref, :ok} -> + Process.demonitor(monitor_ref, [:flush]) + # Call a remote function to prevent garbage collection from happening until we are done + Explorer.Remote.LocalGC.identity(result) + + {:DOWN, ^monitor_ref, _, _, reason} -> + exit(reason) + end + end +end + +if Code.ensure_loaded?(FLAME.Trackable) do + defimpl FLAME.Trackable, for: [Explorer.DataFrame, Explorer.Series, Explorer.Backend.LazySeries] do + def track(data, acc, _node) do + Explorer.Remote.place(data, acc) + end + end +end diff --git a/deps/explorer/lib/explorer/remote/holder.ex b/deps/explorer/lib/explorer/remote/holder.ex new file mode 100644 index 0000000000000000000000000000000000000000..7a2dcbcc1a3bff8366370ae7f786572662c06b6d --- /dev/null +++ b/deps/explorer/lib/explorer/remote/holder.ex @@ -0,0 +1,76 @@ +defmodule Explorer.Remote.Holder do + # This process is spawned dynamically by a node + # that wants to hold a reference to a resource + # on this node. To avoid leaking resources, it + # is tied to the local GC process of the spawned node. + @moduledoc false + + use GenServer, restart: :transient + + def start_child(remote_ref, local_gc) when is_reference(remote_ref) and is_pid(local_gc) do + DynamicSupervisor.start_child( + {Explorer.Remote.Supervisor, node(remote_ref)}, + {__MODULE__, local_gc} + ) + end + + def hold(holder, ref, pid) when is_pid(pid) and node(ref) == node(holder) do + GenServer.call(holder, {:hold, ref, pid}, :infinity) + end + + def start_link(pid) when is_pid(pid) do + GenServer.start_link(__MODULE__, pid) + end + + @impl true + def init(pid) do + ref = Process.monitor(pid) + state = %{owner_ref: ref, refs: %{}, pids: %{}} + {:ok, state} + end + + @impl true + def handle_call({:hold, ref, pid}, _from, state) do + _ = Process.monitor(pid) + refs = Map.update(state.refs, ref, [pid], &[pid | &1]) + pids = Map.update(state.pids, pid, [ref], &[ref | &1]) + {:reply, :ok, %{state | refs: refs, pids: pids, owner_ref: nil}} + end + + @impl true + def handle_info({:gc, ref, pid}, state) do + refs = pop_from_list(state.refs, ref, pid) + pids = pop_from_list(state.pids, pid, ref) + :erlang.garbage_collect() + noreply_or_stop(%{state | pids: pids, refs: refs}) + end + + # We will only match this clause during initialization, + # the goal is to not leave orphaned processes. + def handle_info({:DOWN, owner_ref, _, _, reason}, %{owner_ref: owner_ref} = state) do + {:stop, reason, state} + end + + def handle_info({:DOWN, _, _, pid, _}, state) do + {pid_refs, pids} = Map.pop(state.pids, pid, []) + refs = Enum.reduce(pid_refs, state.refs, &pop_from_list(&2, &1, pid)) + :erlang.garbage_collect() + noreply_or_stop(%{state | pids: pids, refs: refs}) + end + + defp noreply_or_stop(%{refs: refs} = state) when refs == %{}, do: {:stop, :shutdown, state} + defp noreply_or_stop(state), do: {:noreply, state} + + defp pop_from_list(map, key, value) do + case map do + %{^key => list} -> + case List.delete(list, value) do + [] -> Map.delete(map, key) + new_value -> Map.put(map, key, new_value) + end + + %{} -> + map + end + end +end diff --git a/deps/explorer/lib/explorer/remote/local_gc.ex b/deps/explorer/lib/explorer/remote/local_gc.ex new file mode 100644 index 0000000000000000000000000000000000000000..cc47f61387d9217cb32c8105e527c1dcbc41347a --- /dev/null +++ b/deps/explorer/lib/explorer/remote/local_gc.ex @@ -0,0 +1,57 @@ +defmodule Explorer.Remote.LocalGC do + # This process is spawned on every node running Explorer. + # It is responsible for tracking the local GC and reporting + # them to the remote holder nodes. + @moduledoc false + + use GenServer + @name __MODULE__ + + def start_link(_opts) do + GenServer.start_link(__MODULE__, :ok, name: @name) + end + + @doc """ + An identity function to prevent GC. + """ + def identity(data), do: data + + @doc """ + Locates the LocalGC process. + """ + def whereis! do + Process.whereis(@name) || exit({:noproc, {__MODULE__, :whereis!, []}}) + end + + @doc """ + This is a function that receives a process and a payload + and it returns a NIF resource. + + Once the NIF resource is GCed, it sends a message `{:gc, pid, ref}` + to the local GC process, which forwards it to the holder node. + """ + def track(local_gc, remote_pid, remote_ref) + when is_pid(local_gc) and is_pid(remote_pid) and is_reference(remote_ref) do + Explorer.PolarsBackend.Native.message_on_gc(local_gc, {:gc, remote_pid, remote_ref}) + end + + @doc """ + Check is a local gc reference is alive. + """ + def alive?(local_gc_ref) when is_reference(local_gc_ref) do + Explorer.PolarsBackend.Native.is_message_on_gc(local_gc_ref) + end + + ## Callbacks + + @impl true + def init(:ok) do + {:ok, :unused_state} + end + + @impl true + def handle_info({:gc, remote_pid, remote_ref}, state) do + send(remote_pid, {:gc, remote_ref, self()}) + {:noreply, state} + end +end diff --git a/deps/explorer/lib/explorer/series.ex b/deps/explorer/lib/explorer/series.ex new file mode 100644 index 0000000000000000000000000000000000000000..2cd891fd9a166bef59eed4c53b8b8567a1bb7094 --- /dev/null +++ b/deps/explorer/lib/explorer/series.ex @@ -0,0 +1,6909 @@ +import Explorer.Shared, + only: [ + apply_series: 2, + apply_series: 3, + apply_series: 4, + apply_series_list: 2, + apply_series_varargs: 2 + ] + +defmodule Explorer.Series do + @moduledoc """ + The Series struct and API. + + A series can be of the following data types: + + * `:binary` - Binaries (sequences of bytes) + * `:boolean` - Boolean + * `:category` - Strings but represented internally as integers + * `:date` - Date type that unwraps to `Elixir.Date` + * `{:naive_datetime, precision}` - Naive DateTime type with millisecond/microsecond/nanosecond + precision that unwraps to `Elixir.NaiveDateTime` + * `{:datetime, precision, time_zone}` - DateTime type with millisecond/microsecond/nanosecond + precision that unwraps to `Elixir.DateTime` + * `{:duration, precision}` - Duration type with millisecond/microsecond/nanosecond + precision that unwraps to `Explorer.Duration` + * `{:f, size}` - a 64-bit or 32-bit floating point number + * `{:s, size}` - a 8-bit or 16-bit or 32-bit or 64-bit signed integer number. + * `{:u, size}` - a 8-bit or 16-bit or 32-bit or 64-bit unsigned integer number. + * `{:decimal, precision, scale}` - a 128-bit signed integer number representing a decimal, + with a scale and precision. This unwraps to `Decimal`, using the `:decimal` package. + * `:null` - `nil`s exclusively + * `:string` - UTF-8 encoded binary + * `:time` - Time type that unwraps to `Elixir.Time` + * `{:list, dtype}` - A recursive dtype that can store lists. Examples: `{:list, :boolean}` or + a nested list dtype like `{:list, {:list, :boolean}}`. + * `{:struct, [{key, dtype}]}` - A recursive dtype that can store Arrow/Polars structs (not to be + confused with Elixir's struct). This type unwraps to Elixir maps with string keys. Examples: + `{:struct, [{"a", :string}]}` or a nested struct dtype like `{:struct, [{"a", {:struct, [{"b", :string}]}}]}`. + + When passing a dtype as argument, aliases are supported for convenience + and compatibility with the Elixir ecosystem: + + * All numeric dtypes (signed integer, unsigned integer, floats and decimals) can + be specified as an atom in the form of `:s32`, `:u8`, `:f32` and so on. + * The atom `:float` as an alias for `{:f, 64}` to mirror Elixir's floats + * The atom `:integer` as an alias for `{:s, 64}` to mirror Elixir's integers + * The atom `:decimal` as an alias for the `{:decimal, 38, 0}`. + + A series must consist of a single data type only. Series may have `nil` values in them. + The series `dtype` can be retrieved via the `dtype/1` function or directly accessed as + `series.dtype`. A `series.name` field is also available, but it is always `nil` unless + the series is retrieved from a dataframe. + + Many functions only apply to certain dtypes. These functions may appear on distinct + categories on the sidebar. Other functions may work on several datatypes, such as + comparison functions. In such cases, a "Supported dtypes" section will be available + in the function documentation. + + ## Creating series + + Series can be created using `from_list/2`, `from_binary/3`, and friends: + + Series can be made of numbers: + + iex> Explorer.Series.from_list([1, 2, 3]) + #Explorer.Series< + Polars[3] + s64 [1, 2, 3] + > + + Series are nullable, so you may also include nils: + + iex> Explorer.Series.from_list([1.0, nil, 2.5, 3.1]) + #Explorer.Series< + Polars[4] + f64 [1.0, nil, 2.5, 3.1] + > + + Any of the dtypes above are supported, such as strings: + + iex> Explorer.Series.from_list(["foo", "bar", "baz"]) + #Explorer.Series< + Polars[3] + string ["foo", "bar", "baz"] + > + + ## Casting numeric series (type promotion) + + Series of integers and floats are automatically cast when executing certain + operations. For example, adding a series of s64 with f64 will return a list + of f64. + + Numeric casting works like this: + + * when working with the same numeric type but of different precisions, + the higher precision wins + + * when working with unsigned integers and signed integers, unsigned integers + are cast to signed integers using double of its precision (maximum of 64 bits) + + * when working with integers and floats, integers are always cast floats, + keep the floating number precision + + ## Series queries + + DataFrames have named columns, so their queries use column names as variables: + + iex> require Explorer.DataFrame + iex> df = Explorer.DataFrame.new(col_name: [1, 2, 3]) + iex> Explorer.DataFrame.filter(df, col_name > 2) + #Explorer.DataFrame< + Polars[1 x 1] + col_name s64 [3] + > + + Series have no named columns (a series constitutes a single column, + so no name is required). This means their queries can't use column + names as variables. Instead, series queries use the special `_` variable like so: + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.filter(s, _ > 2) + #Explorer.Series< + Polars[1] + s64 [3] + > + + """ + + import Kernel, except: [and: 2, not: 1, in: 2] + + alias __MODULE__, as: Series + alias Kernel, as: K + alias Explorer.Duration + alias Explorer.Shared + + @naive_datetime_dtypes Explorer.Shared.naive_datetime_types() + @duration_dtypes Explorer.Shared.duration_types() + @float_dtypes Explorer.Shared.float_types() + @integer_types Explorer.Shared.integer_types() + + @date_or_naive_datetime_dtypes [:date | @naive_datetime_dtypes] + @temporal_dtypes [:time | @date_or_naive_datetime_dtypes ++ @duration_dtypes] + @numeric_dtypes Explorer.Shared.numeric_types() + @numeric_or_temporal_dtypes @numeric_dtypes ++ @temporal_dtypes + + @io_dtypes Shared.dtypes() -- + [ + :binary, + :string, + {:list, :any}, + {:struct, :any}, + {:decimal, :pos_integer, :pos_integer} + ] + + @type dtype :: + :null + | :binary + | :boolean + | :category + | :date + | :time + | :string + | datetime_dtype + | decimal_dtype + | duration_dtype + | float_dtype + | list_dtype + | naive_datetime_dtype + | signed_integer_dtype + | struct_dtype + | unsigned_integer_dtype + + @type time_unit :: :nanosecond | :microsecond | :millisecond + @type time_zone :: String.t() + @type naive_datetime_dtype :: {:naive_datetime, time_unit} + @type datetime_dtype :: {:datetime, time_unit, time_zone} + @type duration_dtype :: {:duration, time_unit} + @type list_dtype :: {:list, dtype()} + @type struct_dtype :: {:struct, [{String.t(), dtype()}]} + + @type signed_integer_dtype :: {:s, 8} | {:s, 16} | {:s, 32} | {:s, 64} + @type unsigned_integer_dtype :: {:u, 8} | {:u, 16} | {:u, 32} | {:u, 64} + @type float_dtype :: {:f, 32} | {:f, 64} + @type decimal_dtype :: {:decimal, pos_integer(), pos_integer()} + + @type dtype_alias :: integer_dtype_alias | float_dtype_alias | decimal_dtype_alias + @type float_dtype_alias :: :float | :f32 | :f64 + @type integer_dtype_alias :: :integer | :u8 | :u16 | :u32 | :u64 | :s8 | :s16 | :s32 | :s64 + @type decimal_dtype_alias :: :decimal + + @type t :: %Series{data: Explorer.Backend.Series.t(), dtype: dtype()} + @type lazy_t :: %Series{data: Explorer.Backend.LazySeries.t(), dtype: dtype()} + + @type non_finite :: :nan | :infinity | :neg_infinity + @type inferable_scalar :: + number() + | non_finite() + | boolean() + | map() + | String.t() + | Date.t() + | Time.t() + | NaiveDateTime.t() + | DateTime.t() + + @doc false + @enforce_keys [:data, :dtype] + defstruct [:data, :dtype, :name, :remote] + + @behaviour Access + @compile {:no_warn_undefined, Nx} + + defguardp is_numeric(n) + when is_number(n) + |> K.or(K.in(n, [:nan, :infinity, :neg_infinity])) + |> K.or(is_struct(n, Decimal)) + + defguardp is_io_dtype(dtype) when K.in(dtype, @io_dtypes) + + defguardp is_decimal_dtype(dtype) + when is_tuple(dtype) + |> K.and(tuple_size(dtype) == 3) + |> K.and(elem(dtype, 0) == :decimal) + |> K.and(elem(dtype, 2) |> K.is_integer()) + + defguardp is_numeric_dtype(dtype) + when K.or(K.in(dtype, @numeric_dtypes), is_decimal_dtype(dtype)) + + defguardp is_numeric_or_bool_dtype(dtype) + when K.or(dtype == :boolean, is_numeric_dtype(dtype)) + + defguardp is_precision(precision) + when K.in(precision, [:millisecond, :microsecond, :nanosecond]) + + defguardp is_duration_dtype(dtype) + when is_tuple(dtype) + |> K.and(tuple_size(dtype) == 2) + |> K.and(elem(dtype, 0) == :duration) + |> K.and(elem(dtype, 1) |> is_precision()) + + defguardp is_naive_datetime_dtype(dtype) + when is_tuple(dtype) + |> K.and(tuple_size(dtype) == 2) + |> K.and(elem(dtype, 0) == :naive_datetime) + |> K.and(elem(dtype, 1) |> is_precision()) + + defguardp is_datetime_dtype(dtype) + when is_tuple(dtype) + |> K.and(tuple_size(dtype) == 3) + |> K.and(elem(dtype, 0) == :datetime) + |> K.and(elem(dtype, 1) |> is_precision()) + |> K.and(elem(dtype, 2) |> is_binary()) + + defguardp is_datetime_like_dtype(dtype) + when is_datetime_dtype(dtype) + |> K.or(is_naive_datetime_dtype(dtype)) + + defguardp is_date_like_dtype(dtype) + when (dtype == :date) + |> K.or(dtype |> is_datetime_like_dtype()) + + defguardp is_time_like_dtype(dtype) + when (dtype == :time) + |> K.or(dtype |> is_datetime_like_dtype()) + + defguardp is_temporal_dtype(dtype) + when (dtype == :date) + |> K.or(dtype == :time) + |> K.or(dtype |> is_datetime_like_dtype()) + |> K.or(dtype |> is_duration_dtype()) + + defguardp is_numeric_or_temporal_dtype(dtype) + when is_numeric_dtype(dtype) + |> K.or(dtype |> is_temporal_dtype()) + + @impl true + def fetch(series, idx) when is_integer(idx), do: {:ok, fetch!(series, idx)} + def fetch(series, indices) when is_list(indices), do: {:ok, slice(series, indices)} + def fetch(series, %Range{} = range), do: {:ok, slice(series, range)} + + @impl true + def pop(series, idx) when is_integer(idx) do + mask = 0..(size(series) - 1) |> Enum.map(&(&1 != idx)) |> from_list() + value = fetch!(series, idx) + series = mask(series, mask) + {value, series} + end + + def pop(series, indices) when is_list(indices) do + mask = 0..(size(series) - 1) |> Enum.map(&K.not(Enum.member?(indices, &1))) |> from_list() + value = slice(series, indices) + series = mask(series, mask) + {value, series} + end + + def pop(series, %Range{} = range) do + mask = 0..(size(series) - 1) |> Enum.map(&K.not(Enum.member?(range, &1))) |> from_list() + value = slice(series, range) + series = mask(series, mask) + {value, series} + end + + @impl true + def get_and_update(series, idx, fun) when is_integer(idx) do + value = fetch!(series, idx) + {current_value, new_value} = fun.(value) + new_data = series |> to_list() |> List.replace_at(idx, new_value) |> from_list() + {current_value, new_data} + end + + defp fetch!(series, idx) do + size = size(series) + idx = if idx < 0, do: idx + size, else: idx + + if K.or(idx < 0, idx > size), + do: raise(ArgumentError, "index #{idx} out of bounds for series of size #{size}") + + apply_series(series, :at, [idx]) + end + + # Conversion + + @doc """ + Creates a new series from a list. + + The list must consist of a single data type and nils. It is possible to have + a list of only nil values. In this case, the list will have the `:dtype` of `:null`. + + ## Options + + * `:backend` - The backend to allocate the series on. + * `:node` - The Erlang node to allocate the series on. + * `:dtype` - Create a series of a given `:dtype`. By default this is `nil`, which means + that Explorer will infer the type from the values in the list. + See the module docs for the list of valid dtypes and aliases. + + ## Examples + + Explorer will infer the type from the values in the list. + Integers are always treated as `s64` and floats are always + treated as `f64`: + + iex> Explorer.Series.from_list([1, 2, 3]) + #Explorer.Series< + Polars[3] + s64 [1, 2, 3] + > + iex> Explorer.Series.from_list([1.0, 2.0, 3.0]) + #Explorer.Series< + Polars[3] + f64 [1.0, 2.0, 3.0] + > + + Series are nullable, so you may also include nils: + + iex> Explorer.Series.from_list([1.0, nil, 2.5, 3.1]) + #Explorer.Series< + Polars[4] + f64 [1.0, nil, 2.5, 3.1] + > + + A mix of integers and floats will be cast to a float: + + iex> Explorer.Series.from_list([1, 2.0]) + #Explorer.Series< + Polars[2] + f64 [1.0, 2.0] + > + + Floats series can accept NaN, Inf, and -Inf values: + + iex> Explorer.Series.from_list([1.0, 2.0, :nan, 4.0]) + #Explorer.Series< + Polars[4] + f64 [1.0, 2.0, NaN, 4.0] + > + + iex> Explorer.Series.from_list([1.0, 2.0, :infinity, 4.0]) + #Explorer.Series< + Polars[4] + f64 [1.0, 2.0, Inf, 4.0] + > + + iex> Explorer.Series.from_list([1.0, 2.0, :neg_infinity, 4.0]) + #Explorer.Series< + Polars[4] + f64 [1.0, 2.0, -Inf, 4.0] + > + + Trying to create an empty series or a series of nils will, by default, + result in a series of `:null` type: + + iex> Explorer.Series.from_list([]) + #Explorer.Series< + Polars[0] + null [] + > + iex> Explorer.Series.from_list([nil, nil]) + #Explorer.Series< + Polars[2] + null [nil, nil] + > + + A list of `Date`, `Time`, `NaiveDateTime`, `DateTime`, and + `Explorer.Duration` structs are also supported, and they will become series + with the respective dtypes: `:date`, `:time`, `{:naive_datetime, :microsecond}`, + `{:datetime, :microsecond, time_zone}` and `{:duration, precision}`. + For example: + + iex> Explorer.Series.from_list([~D[0001-01-01], ~D[1970-01-01], ~D[1986-10-13]]) + #Explorer.Series< + Polars[3] + date [0001-01-01, 1970-01-01, 1986-10-13] + > + + ## The `:dtype` option + + You can specify the desired `dtype` for a series with the `:dtype` option, + as long as the list contains compatible representations of the `dtype`. For + example, a list of nils may represent integers: + + iex> Explorer.Series.from_list([nil, nil], dtype: :integer) + #Explorer.Series< + Polars[2] + s64 [nil, nil] + > + + And integers can be representations of floating numbers (but not vice-versa): + + iex> Explorer.Series.from_list([1, 2], dtype: :f32) + #Explorer.Series< + Polars[2] + f32 [1.0, 2.0] + > + + iex> Explorer.Series.from_list([1, nil, 2], dtype: :float) + #Explorer.Series< + Polars[3] + f64 [1.0, nil, 2.0] + > + + The `dtype` option is particulary important if a `:binary` series + is desired, because by default binary series will have the dtype + of `:string`: + + iex> Explorer.Series.from_list([<<228, 146, 51>>, <<42, 209, 236>>], dtype: :binary) + #Explorer.Series< + Polars[2] + binary [<<228, 146, 51>>, <<42, 209, 236>>] + > + + A series mixing UTF8 strings and binaries is possible: + + iex> Explorer.Series.from_list([<<228, 146, 51>>, "Elixir"], dtype: :binary) + #Explorer.Series< + Polars[2] + binary [<<228, 146, 51>>, "Elixir"] + > + + Another option is to create a categorical series from a list of strings: + + iex> Explorer.Series.from_list(["EUA", "Brazil", "Poland"], dtype: :category) + #Explorer.Series< + Polars[3] + category ["EUA", "Brazil", "Poland"] + > + + If you need to create a series of dates, you can pass `Date` structs, but also + a series of integers representing days since Unix Epoch: + + iex> Explorer.Series.from_list([1, nil], dtype: :date) + #Explorer.Series< + Polars[2] + date [1970-01-02, nil] + > + + It is possible to create a series of `:datetime` from a list of microseconds since Unix Epoch: + + iex> Explorer.Series.from_list([1649883642 * 1_000 * 1_000], dtype: {:naive_datetime, :microsecond}) + #Explorer.Series< + Polars[1] + naive_datetime[μs] [2022-04-13 21:00:42.000000] + > + + Or a series of `:time` from a list of nanoseconds since midnight: + + iex> Explorer.Series.from_list([123 * 1_000 * 1_000 * 1_000], dtype: :time) + #Explorer.Series< + Polars[1] + time [00:02:03.000000] + > + + In such cases, you may even mix integers with their regular data structures, + as long as the desired dtype is given: + + iex> Explorer.Series.from_list([1, nil, ~D[2024-06-13]], dtype: :date) + #Explorer.Series< + Polars[3] + date [1970-01-02, nil, 2024-06-13] + > + + Outside of these scenarios, mixing data types or giving an incompatible + `dtype` will raise `ArgumentError`: + + iex> Explorer.Series.from_list([1, "a"]) + ** (ArgumentError) the value "a" does not match the inferred dtype {:s, 64} + + In particular, the `:dtype` option won't perform any parsing, as the goal of + this function is to load Elixir data as quickly as possible into the native + library. For instance, you can't pass a list of strings and convert them into + `:date`s via the `:dtype` option. Use either `cast/2` or custom functions + (in this particular case, `strptime/2`). + """ + @doc type: :conversion + @spec from_list(list :: list(), opts :: Keyword.t()) :: Series.t() + def from_list(list, opts \\ []) do + opts = Keyword.validate!(opts, [:dtype, :backend, :node]) + backend = backend_from_options!(opts) + + normalised_dtype = if opts[:dtype], do: Shared.normalise_dtype!(opts[:dtype]) + + dtype = Shared.dtype_from_list!(list, normalised_dtype) + Shared.apply_init(backend, :from_list, [list, dtype], opts) + end + + defp from_same_value(%{data: %backend{}}, value) do + backend.from_list([value], Shared.dtype_from_list!([value])) + end + + defp from_same_value(%{data: %backend{}}, value, dtype) do + backend.from_list([value], dtype) + end + + @doc """ + Builds a series of `dtype` from `binary`. + + All binaries must be in native endianness. + + ## Options + + * `:backend` - The backend to allocate the series on. + * `:node` - The Erlang node to allocate the series on. + + ## Examples + + Integers and floats follow their native encoding: + + iex> Explorer.Series.from_binary(<<1.0::float-64-native, 2.0::float-64-native>>, {:f, 64}) + #Explorer.Series< + Polars[2] + f64 [1.0, 2.0] + > + + iex> Explorer.Series.from_binary(<<-1::signed-64-native, 1::signed-64-native>>, :integer) + #Explorer.Series< + Polars[2] + s64 [-1, 1] + > + + Booleans are unsigned integers: + + iex> Explorer.Series.from_binary(<<1, 0, 1>>, :boolean) + #Explorer.Series< + Polars[3] + boolean [true, false, true] + > + + Dates are encoded as s32 representing days from the Unix epoch (1970-01-01): + + iex> binary = <<-719162::signed-32-native, 0::signed-32-native, 6129::signed-32-native>> + iex> Explorer.Series.from_binary(binary, :date) + #Explorer.Series< + Polars[3] + date [0001-01-01, 1970-01-01, 1986-10-13] + > + + Times are encoded as s64 representing nanoseconds from midnight: + + iex> binary = <<0::signed-64-native, 86399999999000::signed-64-native>> + iex> Explorer.Series.from_binary(binary, :time) + #Explorer.Series< + Polars[2] + time [00:00:00.000000, 23:59:59.999999] + > + + Datetimes are encoded as s64 representing microseconds from the Unix epoch (1970-01-01): + + iex> binary = <<0::signed-64-native, 529550625987654::signed-64-native>> + iex> Explorer.Series.from_binary(binary, {:naive_datetime, :microsecond}) + #Explorer.Series< + Polars[2] + naive_datetime[μs] [1970-01-01 00:00:00.000000, 1986-10-13 01:23:45.987654] + > + + """ + @doc type: :conversion + @spec from_binary( + binary, + :boolean + | :date + | :time + | datetime_dtype + | duration_dtype + | float_dtype + | float_dtype_alias + | integer_dtype_alias + | signed_integer_dtype + | unsigned_integer_dtype, + keyword + ) :: + Series.t() + def from_binary(binary, dtype, opts \\ []) when K.and(is_binary(binary), is_list(opts)) do + opts = Keyword.validate!(opts, [:backend, :node]) + dtype = Shared.normalise_dtype!(dtype) + + {_type, alignment} = dtype |> Shared.dtype_to_iotype!() + + if rem(bit_size(binary), alignment) != 0 do + raise ArgumentError, + "binary for dtype #{Shared.dtype_to_string(dtype)} is expected to be #{alignment}-bit aligned" + end + + backend = backend_from_options!(opts) + Shared.apply_init(backend, :from_binary, [binary, dtype], opts) + end + + @doc """ + Converts a `t:Nx.Tensor.t/0` to a series. + + > #### Warning {: .warning} + > + > `Nx` is an optional dependency. You will need to ensure it's installed to use this function. + + ## Options + + * `:backend` - The backend to allocate the series on. + * `:node` - The Erlang node to allocate the series on. + * `:dtype` - The dtype of the series that must match the underlying tensor type. + + The series can have a different dtype if the tensor is compatible with it. + For example, a tensor of `{:u, 8}` can represent a series of `:boolean` dtype. + + Here are the list of compatible tensor types and dtypes: + + * `{:u, 8}` tensor as a `:boolean` series. + * `{:s, 32}` tensor as a `:date` series. + * `{:s, 64}` tensor as a `:time` series. + * `{:s, 64}` tensor as a `{:naive_datetime, unit}` or `{:duration, unit}` series. + + ## Examples + + Integers and floats: + + iex> tensor = Nx.tensor([1, 2, 3]) + iex> Explorer.Series.from_tensor(tensor) + #Explorer.Series< + Polars[3] + s64 [1, 2, 3] + > + + iex> tensor = Nx.tensor([1.0, 2.0, 3.0], type: :f64) + iex> Explorer.Series.from_tensor(tensor) + #Explorer.Series< + Polars[3] + f64 [1.0, 2.0, 3.0] + > + + iex> tensor = Nx.tensor([1, 0, 1], type: :u8) + iex> Explorer.Series.from_tensor(tensor) + #Explorer.Series< + Polars[3] + u8 [1, 0, 1] + > + + iex> tensor = Nx.tensor([-719162, 0, 6129], type: :s32) + iex> Explorer.Series.from_tensor(tensor) + #Explorer.Series< + Polars[3] + s32 [-719162, 0, 6129] + > + + Booleans can be read from a tensor of `{:u, 8}` type if the dtype is explicitly given: + + iex> tensor = Nx.tensor([1, 0, 1], type: :u8) + iex> Explorer.Series.from_tensor(tensor, dtype: :boolean) + #Explorer.Series< + Polars[3] + boolean [true, false, true] + > + + Times are signed 64-bit representing nanoseconds from midnight and + therefore must have their dtype explicitly given: + + iex> tensor = Nx.tensor([0, 86399999999000]) + iex> Explorer.Series.from_tensor(tensor, dtype: :time) + #Explorer.Series< + Polars[2] + time [00:00:00.000000, 23:59:59.999999] + > + + Datetimes are signed 64-bit and therefore must have their dtype explicitly given: + + iex> tensor = Nx.tensor([0, 529550625987654]) + iex> Explorer.Series.from_tensor(tensor, dtype: {:naive_datetime, :microsecond}) + #Explorer.Series< + Polars[2] + naive_datetime[μs] [1970-01-01 00:00:00.000000, 1986-10-13 01:23:45.987654] + > + """ + @doc type: :conversion + @spec from_tensor(tensor :: Nx.Tensor.t(), opts :: Keyword.t()) :: Series.t() + def from_tensor(tensor, opts \\ []) when is_struct(tensor, Nx.Tensor) do + opts = Keyword.validate!(opts, [:dtype, :backend, :node]) + type = Nx.type(tensor) + {dtype, opts} = Keyword.pop_lazy(opts, :dtype, fn -> Shared.iotype_to_dtype!(type) end) + + dtype = Shared.normalise_dtype!(dtype) + + if Shared.dtype_to_iotype!(dtype) != type do + raise ArgumentError, + "dtype #{inspect(dtype)} expects a tensor of type #{inspect(Shared.dtype_to_iotype!(dtype))} " <> + "but got type #{inspect(type)}" + end + + backend = backend_from_options!(opts) + Shared.apply_init(backend, :from_binary, [Nx.to_binary(tensor), dtype], opts) + end + + @doc """ + Replaces the contents of the given series by the one given in + a tensor or list. + + The new series will have the same dtype and backend as the current + series, but the size may not necessarily match. + + ## Tensor examples + + iex> s = Explorer.Series.from_list([0, 1, 2]) + iex> Explorer.Series.replace(s, Nx.tensor([1, 2, 3])) + #Explorer.Series< + Polars[3] + s64 [1, 2, 3] + > + + This is particularly useful for categorical columns: + + iex> s = Explorer.Series.from_list(["foo", "bar", "baz"], dtype: :category) + iex> Explorer.Series.replace(s, Nx.tensor([2, 1, 0])) + #Explorer.Series< + Polars[3] + category ["baz", "bar", "foo"] + > + + ## List examples + + Similar to tensors, we can also replace by lists: + + iex> s = Explorer.Series.from_list([0, 1, 2]) + iex> Explorer.Series.replace(s, [1, 2, 3, 4, 5]) + #Explorer.Series< + Polars[5] + s64 [1, 2, 3, 4, 5] + > + + The same considerations as above apply. + """ + @doc type: :conversion + @spec replace(Series.t(), Nx.Tensor.t() | list()) :: Series.t() + def replace(series, tensor_or_list) + + def replace(series, tensor) when is_struct(tensor, Nx.Tensor) do + replace_tensor_or_list(series, :from_tensor, tensor) + end + + def replace(series, list) when is_list(list) do + replace_tensor_or_list(series, :from_list, list) + end + + defp replace_tensor_or_list(series, fun, arg) do + backend_series_string = Atom.to_string(series.data.__struct__) + backend_string = binary_part(backend_series_string, 0, byte_size(backend_series_string) - 7) + backend = String.to_atom(backend_string) + + case series.dtype do + :category -> + Series + |> apply(fun, [arg, [dtype: {:s, 64}, backend: backend]]) + |> categorise(series) + + dtype -> + apply(Series, fun, [arg, [dtype: dtype, backend: backend]]) + end + end + + @doc """ + Collects a series to the current node. + + If the series is already in the current node, it works as a no-op. + + ## Examples + + series = Explorer.Series.from_list([1, 2, 3], node: :some@node) + Explorer.Series.collect(series) + + """ + @doc type: :conversion + @spec collect(series :: Series.t()) :: Series.t() + def collect(%Series{data: %impl{}} = series) do + case impl.owner_reference(series) do + ref when K.and(is_reference(ref), node(ref) != node()) -> + with {:ok, exported} <- :erpc.call(node(ref), impl, :owner_export, [series]), + {:ok, imported} <- impl.owner_import(exported) do + imported + else + {:error, exception} -> raise exception + end + + _ -> + series + end + end + + @doc """ + Converts a series to a list. + + > #### Warning {: .warning} + > + > You must avoid converting a series to list, as that requires copying + > the whole series in memory. Prefer to use the operations in this module + > rather than the ones in `Enum` whenever possible, as this module is + > optimized for large series. + + ## Examples + + iex> series = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.to_list(series) + [1, 2, 3] + """ + @doc type: :conversion + @spec to_list(series :: Series.t()) :: list() + def to_list(series), do: apply_series(series, :to_list, [], false) + + @doc """ + Converts a series to an enumerable. + + The enumerable will lazily traverse the series. + + > #### Warning {: .warning} + > + > You must avoid converting a series to enum, as that will copy the whole + > series in memory as you traverse it. Prefer to use the operations in this + > module rather than the ones in `Enum` whenever possible, as this module is + > optimized for large series. + + ## Examples + + iex> series = Explorer.Series.from_list([1, 2, 3]) + iex> series |> Explorer.Series.to_enum() |> Enum.to_list() + [1, 2, 3] + """ + @doc type: :conversion + @spec to_enum(series :: Series.t()) :: Enumerable.t() + def to_enum(series), do: Explorer.Series.Iterator.new(series) + + @doc """ + Returns a series as a list of fixed-width binaries. + + An io vector (`iovec`) is the Erlang VM term for a flat list of binaries. + This is typically a reference to the in-memory representation of the series. + If the whole series in contiguous in memory, then the list will have a single + element. All binaries are in native endianness. + + This operation fails if the series has `nil` values. + Use `fill_missing/1` to handle them accordingly. + + To retrieve the type of the underlying io vector, use `iotype/1`. + To convert an iovec to a binary, you can use `IO.iodata_to_binary/1`. + + ## Examples + + Integers and floats follow their native encoding: + + iex> series = Explorer.Series.from_list([-1, 0, 1]) + iex> Explorer.Series.to_iovec(series) + [<<-1::signed-64-native, 0::signed-64-native, 1::signed-64-native>>] + + iex> series = Explorer.Series.from_list([1.0, 2.0, 3.0]) + iex> Explorer.Series.to_iovec(series) + [<<1.0::float-64-native, 2.0::float-64-native, 3.0::float-64-native>>] + + Booleans are encoded as 0 and 1: + + iex> series = Explorer.Series.from_list([true, false, true]) + iex> Explorer.Series.to_iovec(series) + [<<1, 0, 1>>] + + Dates are encoded as s32 representing days from the Unix epoch (1970-01-01): + + iex> series = Explorer.Series.from_list([~D[0001-01-01], ~D[1970-01-01], ~D[1986-10-13]]) + iex> Explorer.Series.to_iovec(series) + [<<-719162::signed-32-native, 0::signed-32-native, 6129::signed-32-native>>] + + Times are encoded as s64 representing nanoseconds from midnight: + + iex> series = Explorer.Series.from_list([~T[00:00:00.000000], ~T[23:59:59.999999]]) + iex> Explorer.Series.to_iovec(series) + [<<0::signed-64-native, 86399999999000::signed-64-native>>] + + Datetimes are encoded as s64 representing their precision from the Unix epoch (1970-01-01): + + iex> series = Explorer.Series.from_list([~N[0001-01-01 00:00:00], ~N[1970-01-01 00:00:00], ~N[1986-10-13 01:23:45.987654]]) + iex> Explorer.Series.to_iovec(series) + [<<-62135596800000000::signed-64-native, 0::signed-64-native, 529550625987654::signed-64-native>>] + + The operation raises for binaries and strings, as they do not provide a fixed-width + binary representation: + + iex> s = Explorer.Series.from_list(["a", "b", "c", "b"]) + iex> Explorer.Series.to_iovec(s) + ** (ArgumentError) cannot convert series of dtype :string into iovec + + However, if appropriate, you can convert them to categorical types, + which will then return the index of each category: + + iex> series = Explorer.Series.from_list(["a", "b", "c", "b"], dtype: :category) + iex> Explorer.Series.to_iovec(series) + [<<0::unsigned-32-native, 1::unsigned-32-native, 2::unsigned-32-native, 1::unsigned-32-native>>] + + """ + @doc type: :conversion + @spec to_iovec(series :: Series.t()) :: [binary] + def to_iovec(%Series{dtype: dtype} = series) do + if is_io_dtype(dtype) do + apply_series(series, :to_iovec, [], false) + else + raise ArgumentError, "cannot convert series of dtype #{inspect(dtype)} into iovec" + end + end + + @doc """ + Returns a series as a fixed-width binary. + + This is a shortcut around `to_iovec/1`. If possible, prefer + to use `to_iovec/1` as that avoids copying binaries. + + ## Examples + + iex> series = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.to_binary(series) + <<1::signed-64-native, 2::signed-64-native, 3::signed-64-native>> + + iex> series = Explorer.Series.from_list([true, false, true]) + iex> Explorer.Series.to_binary(series) + <<1, 0, 1>> + + """ + @doc type: :conversion + @spec to_binary(series :: Series.t()) :: binary + def to_binary(series), do: series |> to_iovec() |> IO.iodata_to_binary() + + @doc """ + Converts a series to a `t:Nx.Tensor.t/0`. + + Note that `Explorer.Series` are automatically converted + to tensors when passed to numerical definitions. + The tensor type is given by `iotype/1`. + + > #### Warning {: .warning} + > + > `Nx` is an optional dependency. You will need to ensure it's installed to use this function. + + ## Options + + * `:backend` - the Nx backend to allocate the tensor on + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.to_tensor(s) + #Nx.Tensor< + s64[3] + [1, 2, 3] + > + + iex> s = Explorer.Series.from_list([true, false, true]) + iex> Explorer.Series.to_tensor(s) + #Nx.Tensor< + u8[3] + [1, 0, 1] + > + + """ + @doc type: :conversion + @spec to_tensor(series :: Series.t(), tensor_opts :: Keyword.t()) :: Nx.Tensor.t() + def to_tensor(%Series{dtype: dtype} = series, tensor_opts \\ []) do + case iotype(series) do + {_, _} = type -> + Nx.from_binary(to_binary(series), type, tensor_opts) + + :none when Kernel.in(dtype, [:string, :binary]) -> + raise ArgumentError, + "cannot convert #{inspect(dtype)} series to tensor (consider casting the series to a :category type before)" + + :none -> + raise ArgumentError, "cannot convert #{inspect(dtype)} series to tensor" + end + end + + @doc """ + Cast the series to another type. + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.cast(s, :string) + #Explorer.Series< + Polars[3] + string ["1", "2", "3"] + > + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.cast(s, {:f, 64}) + #Explorer.Series< + Polars[3] + f64 [1.0, 2.0, 3.0] + > + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.cast(s, :date) + #Explorer.Series< + Polars[3] + date [1970-01-02, 1970-01-03, 1970-01-04] + > + + Note that `time` is represented as an integer of nanoseconds since midnight. + In Elixir we can't represent nanoseconds, only microseconds. So be aware that + information can be lost if a conversion is needed (e.g. calling `to_list/1`). + + iex> s = Explorer.Series.from_list([1_000, 2_000, 3_000]) + iex> Explorer.Series.cast(s, :time) + #Explorer.Series< + Polars[3] + time [00:00:00.000001, 00:00:00.000002, 00:00:00.000003] + > + + iex> s = Explorer.Series.from_list([86399 * 1_000 * 1_000 * 1_000]) + iex> Explorer.Series.cast(s, :time) + #Explorer.Series< + Polars[1] + time [23:59:59.000000] + > + + Note that `datetime` is represented as an integer of microseconds since Unix Epoch (1970-01-01 00:00:00). + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.cast(s, {:naive_datetime, :microsecond}) + #Explorer.Series< + Polars[3] + naive_datetime[μs] [1970-01-01 00:00:00.000001, 1970-01-01 00:00:00.000002, 1970-01-01 00:00:00.000003] + > + + iex> s = Explorer.Series.from_list([1649883642 * 1_000 * 1_000]) + iex> Explorer.Series.cast(s, {:naive_datetime, :microsecond}) + #Explorer.Series< + Polars[1] + naive_datetime[μs] [2022-04-13 21:00:42.000000] + > + + You can also use `cast/2` to categorise a string: + + iex> s = Explorer.Series.from_list(["apple", "banana", "apple", "lemon"]) + iex> Explorer.Series.cast(s, :category) + #Explorer.Series< + Polars[4] + category ["apple", "banana", "apple", "lemon"] + > + + `cast/2` will return the series as a no-op if you try to cast to the same dtype. + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.cast(s, :integer) + #Explorer.Series< + Polars[3] + s64 [1, 2, 3] + > + """ + @doc type: :element_wise + @spec cast(series :: Series.t(), dtype :: dtype() | dtype_alias()) :: Series.t() + def cast(%Series{dtype: original_dtype} = series, dtype) do + if normalised = Shared.normalise_dtype(dtype) do + if normalised == original_dtype do + series + else + apply_series(series, :cast, [normalised]) + end + else + dtype_error("cast/2", dtype, Shared.dtypes()) + end + end + + @doc """ + Converts a string series to a datetime series with a given `format_string`. + + For the format string specification, refer to the + [chrono crate documentation](https://docs.rs/chrono/latest/chrono/format/strftime/). + + Use `cast(series, :datetime)` if you prefer the format to be inferred (if possible). + + ## Examples + + iex> s = Explorer.Series.from_list(["2023-01-05 12:34:56", "XYZ", nil]) + iex> Explorer.Series.strptime(s, "%Y-%m-%d %H:%M:%S") + #Explorer.Series< + Polars[3] + naive_datetime[μs] [2023-01-05 12:34:56.000000, nil, nil] + > + """ + @doc type: :element_wise + @spec strptime(series :: Series.t(), format_string :: String.t()) :: Series.t() + def strptime(%Series{dtype: dtype} = series, format_string) when K.in(dtype, [:string]), + do: apply_series(series, :strptime, [format_string]) + + def strptime(%Series{dtype: dtype}, _format_string), + do: dtype_error("strptime/2", dtype, [:string]) + + @doc """ + Converts a datetime series to a string series. + + For the format string specification, refer to the + [chrono crate documentation](https://docs.rs/chrono/latest/chrono/format/strftime/index.html). + + Use `cast(series, :string)` for the default `"%Y-%m-%d %H:%M:%S%.6f"` format. + + ## Examples + + iex> s = Explorer.Series.from_list([~N[2023-01-05 12:34:56], nil]) + iex> Explorer.Series.strftime(s, "%Y/%m/%d %H:%M:%S") + #Explorer.Series< + Polars[2] + string ["2023/01/05 12:34:56", nil] + > + """ + @doc type: :element_wise + @spec strftime(series :: Series.t(), format_string :: String.t()) :: Series.t() + def strftime(%Series{dtype: dtype} = series, format_string) when is_datetime_like_dtype(dtype), + do: apply_series(series, :strftime, [format_string]) + + def strftime(%Series{dtype: dtype}, _format_string), + do: dtype_error("strftime/2", dtype, :datetime_like) + + @doc """ + Clip (or clamp) the values in a series. + + Values that fall outside of the interval defined by the `min` and `max` + bounds are clipped to the bounds. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + + Clipping other dtypes are possible using `select/3`. + + ## Examples + + iex> s = Explorer.Series.from_list([-50, 5, nil, 50]) + iex> Explorer.Series.clip(s, 1, 10) + #Explorer.Series< + Polars[4] + s64 [1, 5, nil, 10] + > + + iex> s = Explorer.Series.from_list([-50, 5, nil, 50]) + iex> Explorer.Series.clip(s, 1.5, 10.5) + #Explorer.Series< + Polars[4] + f64 [1.5, 5.0, nil, 10.5] + > + """ + @doc type: :element_wise + @spec clip(series :: Series.t(), min :: number(), max :: number()) :: Series.t() + def clip(%Series{dtype: dtype} = series, min, max) when is_numeric_dtype(dtype) do + if !K.and(is_number(min), is_number(max)) do + raise ArgumentError, + "Explorer.Series.clip/3 expects both the min and max bounds to be numbers" + end + + if min > max do + raise ArgumentError, + "Explorer.Series.clip/3 expects the max bound to be greater than the min bound" + end + + apply_series(series, :clip, [min, max]) + end + + def clip(%Series{dtype: dtype}, _min, _max), + do: dtype_error("clip/3", dtype, @numeric_dtypes) + + # Introspection + + @doc """ + Returns the data type of the series. + + See the moduledoc for all supported dtypes. + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.dtype(s) + {:s, 64} + + iex> s = Explorer.Series.from_list(["a", nil, "b", "c"]) + iex> Explorer.Series.dtype(s) + :string + """ + @doc type: :introspection + @spec dtype(series :: Series.t()) :: dtype() + def dtype(%Series{dtype: dtype}), do: dtype + + @doc """ + Returns the number of elements in the series. + + See also: + + * `count/1` - counts only the non-`nil` elements. + * `nil_count/1` - counts all `nil` elements. + + ## Examples + + Basic example: + + iex> s = Explorer.Series.from_list([~D[1999-12-31], ~D[1989-01-01]]) + iex> Explorer.Series.size(s) + 2 + + With lists: + + iex> s = Explorer.Series.from_list([[1, 2, 3], [4, 5]]) + iex> Explorer.Series.size(s) + 2 + """ + @doc type: :introspection + @spec size(series :: Series.t()) :: non_neg_integer() | lazy_t() + def size(series), do: apply_series(series, :size) + + @doc """ + Returns the type of the underlying fixed-width binary representation. + + It returns something in the shape of `{atom(), bits_size}` or `:none`. + It is often used in conjunction with `to_iovec/1` and `to_binary/1`. + + The possible iotypes are: + + * `:u` for unsigned integers. + * `:s` for signed integers. + * `:f` for floats. + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 3, 4]) + iex> Explorer.Series.iotype(s) + {:s, 64} + + iex> s = Explorer.Series.from_list([~D[1999-12-31], ~D[1989-01-01]]) + iex> Explorer.Series.iotype(s) + {:s, 32} + + iex> s = Explorer.Series.from_list([~T[00:00:00.000000], ~T[23:59:59.999999]]) + iex> Explorer.Series.iotype(s) + {:s, 64} + + iex> s = Explorer.Series.from_list([1.2, 2.3, 3.5, 4.5]) + iex> Explorer.Series.iotype(s) + {:f, 64} + + iex> s = Explorer.Series.from_list([true, false, true]) + iex> Explorer.Series.iotype(s) + {:u, 8} + + The operation returns `:none` for strings and binaries, as they do not + provide a fixed-width binary representation: + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.iotype(s) + :none + + However, if appropriate, you can convert them to categorical types, + which will then return the index of each category: + + iex> s = Explorer.Series.from_list(["a", "b", "c"], dtype: :category) + iex> Explorer.Series.iotype(s) + {:u, 32} + + """ + @doc type: :introspection + @spec iotype(series :: Series.t()) :: {:s | :u | :f, non_neg_integer()} | :none + def iotype(%Series{dtype: dtype}) do + case dtype do + :category -> {:u, 32} + {:decimal, _, _} -> {:s, 128} + other -> Shared.dtype_to_iotype(other) + end + end + + @doc """ + Return a series with the category names of a categorical series. + + Each category has the index equal to its position. + No order for the categories is guaranteed. + + ## Examples + + iex> s = Explorer.Series.from_list(["a", "b", "c", nil, "a", "c"], dtype: :category) + iex> Explorer.Series.categories(s) + #Explorer.Series< + Polars[3] + string ["a", "b", "c"] + > + + iex> s = Explorer.Series.from_list(["c", "a", "b"], dtype: :category) + iex> Explorer.Series.categories(s) + #Explorer.Series< + Polars[3] + string ["c", "a", "b"] + > + + """ + @doc type: :introspection + @spec categories(series :: Series.t()) :: Series.t() + def categories(%Series{dtype: :category} = series), do: apply_series(series, :categories) + def categories(%Series{dtype: dtype}), do: dtype_error("categories/1", dtype, [:category]) + + @doc """ + Categorise a series of integers or strings according to `categories`. + + This function receives a series of integers or strings and convert them + into the categories specified by the second argument. + The second argument can be one of: + + * a series with dtype `:category`. The integers will be indexes into + the categories of the given series (returned by `categories/1`) + + * a series with dtype `:string`. The integers will be indexes into + the series itself + + * a list of strings. The integers will be indexes into the list + + This is going to essentially "copy" the source of categories from the left series + to the right. All members from the left that are not present in the right hand-side + are going to be `nil`. + + If you have a series of strings and you want to convert them into categories, + invoke `cast(series, :category)` instead. + + ## Examples + + If a categorical series is given as second argument, we will extract its + categories and map the integers into it: + + iex> categories = Explorer.Series.from_list(["a", "b", "c", nil, "a"], dtype: :category) + iex> indexes = Explorer.Series.from_list([0, 2, 1, 0, 2]) + iex> Explorer.Series.categorise(indexes, categories) + #Explorer.Series< + Polars[5] + category ["a", "c", "b", "a", "c"] + > + + Otherwise, if a list of strings or a series of strings is given, they are + considered to be the categories series itself: + + iex> categories = Explorer.Series.from_list(["a", "b", "c"]) + iex> indexes = Explorer.Series.from_list([0, 2, 1, 0, 2]) + iex> Explorer.Series.categorise(indexes, categories) + #Explorer.Series< + Polars[5] + category ["a", "c", "b", "a", "c"] + > + + iex> indexes = Explorer.Series.from_list([0, 2, 1, 0, 2]) + iex> Explorer.Series.categorise(indexes, ["a", "b", "c"]) + #Explorer.Series< + Polars[5] + category ["a", "c", "b", "a", "c"] + > + + Elements that are not mapped to a category will become `nil`: + + iex> indexes = Explorer.Series.from_list([0, 2, nil, 0, 2, 7]) + iex> Explorer.Series.categorise(indexes, ["a", "b", "c"]) + #Explorer.Series< + Polars[6] + category ["a", "c", nil, "a", "c", nil] + > + + Strings can be used as "indexes" to create a categorical series + with the intersection of members: + + iex> strings = Explorer.Series.from_list(["a", "c", nil, "c", "b", "d"]) + iex> Explorer.Series.categorise(strings, ["a", "b", "c"]) + #Explorer.Series< + Polars[6] + category ["a", "c", nil, "c", "b", nil] + > + + """ + @doc type: :element_wise + def categorise(%Series{dtype: l_dtype} = series, %Series{dtype: :category} = categories) + when K.in(l_dtype, [:string | @integer_types]), + do: apply_series(series, :categorise, [categories]) + + def categorise(%Series{dtype: l_dtype} = series, %Series{dtype: :string} = categories) + when K.in(l_dtype, [:string | @integer_types]) do + if nil_count(categories) != 0 do + raise(ArgumentError, "categories as strings cannot have nil values") + end + + if count(categories) != n_distinct(categories) do + raise(ArgumentError, "categories as strings cannot have duplicated values") + end + + categories = cast(categories, :category) + apply_series(series, :categorise, [categories]) + end + + def categorise(%Series{dtype: l_dtype} = series, [head | _] = categories) + when K.and(K.in(l_dtype, [:string | @integer_types]), is_binary(head)), + do: categorise(series, from_list(categories, dtype: :string)) + + # Slice and dice + + @doc """ + Returns the first N elements of the series. + + ## Examples + + iex> s = 1..100 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.head(s) + #Explorer.Series< + Polars[10] + s64 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + > + """ + @doc type: :shape + @spec head(series :: Series.t(), n_elements :: integer()) :: Series.t() + def head(series, n_elements \\ 10), do: apply_series(series, :head, [n_elements]) + + @doc """ + Returns the last N elements of the series. + + ## Examples + + iex> s = 1..100 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.tail(s) + #Explorer.Series< + Polars[10] + s64 [91, 92, 93, 94, 95, 96, 97, 98, 99, 100] + > + """ + @doc type: :shape + @spec tail(series :: Series.t(), n_elements :: integer()) :: Series.t() + def tail(series, n_elements \\ 10), do: apply_series(series, :tail, [n_elements]) + + @doc """ + Returns the first element of the series. + + ## Examples + + iex> s = 1..100 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.first(s) + 1 + """ + @doc type: :shape + @spec first(series :: Series.t()) :: any() + def first(series), do: apply_series(series, :first, []) + + @doc """ + Returns the last element of the series. + + ## Examples + + iex> s = 1..100 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.last(s) + 100 + """ + @doc type: :shape + @spec last(series :: Series.t()) :: any() + def last(series), do: apply_series(series, :last, []) + + @doc """ + Shifts `series` by `offset` with `nil` values. + + Positive offset shifts from first, negative offset shifts from last. + + ## Examples + + iex> s = 1..5 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.shift(s, 2) + #Explorer.Series< + Polars[5] + s64 [nil, nil, 1, 2, 3] + > + + iex> s = 1..5 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.shift(s, -2) + #Explorer.Series< + Polars[5] + s64 [3, 4, 5, nil, nil] + > + """ + @doc type: :shape + @spec shift(series :: Series.t(), offset :: integer()) :: Series.t() + def shift(series, offset) + when is_integer(offset), + do: apply_series(series, :shift, [offset, nil]) + + @doc """ + Returns a series from two series, based on a predicate. + + The resulting series is built by evaluating each element of + `predicate` and returning either the corresponding element from + `on_true` or `on_false`. + + `predicate` must be a boolean series. `on_true` and `on_false` must be + a series of the same size as `predicate` or a series of size 1. + + It is possible to mix numeric series in the `on_true` and `on_false`, + and the resultant series will have the dtype of the greater side. + For example, `:u8` and `:s16` is going to result in `:s16` series. + """ + @doc type: :element_wise + @spec select( + predicate :: Series.t(), + on_true :: Series.t() | inferable_scalar(), + on_false :: Series.t() | inferable_scalar() + ) :: + Series.t() + def select(%Series{dtype: predicate_dtype} = predicate, on_true, on_false) do + if predicate_dtype != :boolean do + raise ArgumentError, + "Explorer.Series.select/3 expect the first argument to be a series of booleans, got: #{inspect(predicate_dtype)}" + end + + %Series{dtype: on_true_dtype} = on_true = maybe_from_list(on_true) + %Series{dtype: on_false_dtype} = on_false = maybe_from_list(on_false) + + cond do + K.and(is_numeric_dtype(on_true_dtype), is_numeric_dtype(on_false_dtype)) -> + apply_series_list(:select, [predicate, on_true, on_false]) + + on_true_dtype == on_false_dtype -> + apply_series_list(:select, [predicate, on_true, on_false]) + + true -> + dtype_mismatch_error("select/3", on_true_dtype, on_false_dtype) + end + end + + defp maybe_from_list(%Series{} = series), do: series + defp maybe_from_list(other), do: from_list([other]) + + @doc """ + Returns a random sample of the series. + + If given an integer as the second argument, it will return N samples. If given a float, it will + return that proportion of the series. + + Can sample with or without replace. + + ## Options + + * `:replace` - If set to `true`, each sample will be independent and therefore values may repeat. + Required to be `true` for `n` greater then the number of rows in the series or `frac` > 1.0. (default: `false`) + * `:seed` - An integer to be used as a random seed. If nil, a random value between 0 and 2^64 − 1 will be used. (default: nil) + * `:shuffle` - In case the sample is equal to the size of the series, shuffle tells if the resultant + series should be shuffled or if it should return the same series. (default: `false`). + + ## Examples + + iex> s = 1..100 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.sample(s, 10, seed: 100) + #Explorer.Series< + Polars[10] + s64 [57, 9, 54, 62, 50, 77, 35, 88, 1, 69] + > + + iex> s = 1..100 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.sample(s, 0.05, seed: 100) + #Explorer.Series< + Polars[5] + s64 [9, 56, 79, 28, 54] + > + + iex> s = 1..5 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.sample(s, 7, seed: 100, replace: true) + #Explorer.Series< + Polars[7] + s64 [4, 1, 3, 4, 3, 4, 2] + > + + iex> s = 1..5 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.sample(s, 1.2, seed: 100, replace: true) + #Explorer.Series< + Polars[6] + s64 [4, 1, 3, 4, 3, 4] + > + + iex> s = 0..9 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.sample(s, 1.0, seed: 100, shuffle: false) + #Explorer.Series< + Polars[10] + s64 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + > + + iex> s = 0..9 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.sample(s, 1.0, seed: 100, shuffle: true) + #Explorer.Series< + Polars[10] + s64 [7, 9, 2, 0, 4, 1, 3, 8, 5, 6] + > + + """ + @doc type: :shape + @spec sample(series :: Series.t(), n_or_frac :: number(), opts :: Keyword.t()) :: Series.t() + def sample(series, n_or_frac, opts \\ []) when is_number(n_or_frac) do + opts = Keyword.validate!(opts, replace: false, shuffle: false, seed: nil) + + size = size(series) + + # In case the series is lazy, we don't perform this check here. + if K.and( + is_integer(size), + K.and(opts[:replace] == false, invalid_size_for_sample?(n_or_frac, size)) + ) do + raise ArgumentError, + "in order to sample more elements than are in the series (#{size}), sampling " <> + "`replace` must be true" + end + + apply_series(series, :sample, [n_or_frac, opts[:replace], opts[:shuffle], opts[:seed]]) + end + + defp invalid_size_for_sample?(n, size) when is_integer(n), do: n > size + + defp invalid_size_for_sample?(frac, size) when is_float(frac), + do: invalid_size_for_sample?(round(frac * size), size) + + @doc """ + Change the elements order randomly. + + ## Options + + * `:seed` - An integer to be used as a random seed. If nil, + a random value between 0 and 2^64 − 1 will be used. (default: nil) + + ## Examples + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.shuffle(s, seed: 100) + #Explorer.Series< + Polars[10] + s64 [8, 10, 3, 1, 5, 2, 4, 9, 6, 7] + > + + """ + @doc type: :shape + @spec shuffle(series :: Series.t(), opts :: Keyword.t()) :: Series.t() + def shuffle(series, opts \\ []) + + def shuffle(series, opts) do + opts = Keyword.validate!(opts, seed: nil) + + sample(series, 1.0, seed: opts[:seed], shuffle: true) + end + + @doc """ + Takes every *n*th value in this series, returned as a new series. + + ## Examples + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.at_every(s, 2) + #Explorer.Series< + Polars[5] + s64 [1, 3, 5, 7, 9] + > + + If *n* is bigger than the size of the series, the result is a new series with only the first value of the supplied series. + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.at_every(s, 20) + #Explorer.Series< + Polars[1] + s64 [1] + > + """ + @doc type: :shape + @spec at_every(series :: Series.t(), every_n :: integer()) :: Series.t() + def at_every(series, every_n), do: apply_series(series, :at_every, [every_n]) + + # Macros + + @doc """ + Picks values based on an `Explorer.Query`. + + The query is compiled and runs efficiently against the series. + The query must return a boolean expression or a list of boolean expressions. + When a list is returned, they are joined as `and` expressions. + + > #### Notice {: .notice} + > + > This is a macro. + > + > * You must `require Explorer.Series` before using it. + > * You must use the special `_` syntax. See the moduledoc for details. + + Besides element-wise series operations, you can also use window functions + and aggregations inside comparisons. + + See `filter_with/2` for a callback version of this function without + `Explorer.Query`. + See `mask/2` if you want to filter values based on another series. + + ## Examples + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.filter(s, _ == "b") + #Explorer.Series< + Polars[1] + string ["b"] + > + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.filter(s, remainder(_, 2) == 1) + #Explorer.Series< + Polars[2] + s64 [1, 3] + > + + Returning a non-boolean expression errors: + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.filter(s, cumulative_max(_)) + ** (ArgumentError) expecting the function to return a boolean LazySeries, but instead it returned a LazySeries of type {:s, 64} + + Which can be addressed by converting it to boolean: + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.filter(s, cumulative_max(_) == 1) + #Explorer.Series< + Polars[1] + s64 [1] + > + """ + @doc type: :element_wise + defmacro filter(series, query) do + quote do + require Explorer.Query + + Explorer.DataFrame.new(_: unquote(series)) + |> Explorer.DataFrame.filter_with(Explorer.Query.query(unquote(query))) + |> Explorer.DataFrame.pull(:_) + end + end + + @doc """ + Filters a series with a callback function. + + See `mask/2` if you want to filter values based on another series. + + ## Examples + + iex> series = Explorer.Series.from_list([1, 2, 3]) + iex> is_odd = fn s -> s |> Explorer.Series.remainder(2) |> Explorer.Series.equal(1) end + iex> Explorer.Series.filter_with(series, is_odd) + #Explorer.Series< + Polars[2] + s64 [1, 3] + > + """ + @doc type: :element_wise + @spec filter_with( + series :: Series.t(), + fun :: (Series.t() -> Series.lazy_t()) + ) :: Series.t() + def filter_with(%Series{} = series, fun) when is_function(fun, 1) do + Explorer.DataFrame.new(series: series) + |> Explorer.DataFrame.filter_with(&fun.(&1[:series])) + |> Explorer.DataFrame.pull(:series) + end + + @doc """ + Maps values based on an `Explorer.Query`. + + The query is compiled and runs efficiently against the series. + + > #### Notice {: .notice} + > + > This is a macro. + > + > * You must `require Explorer.Series` before using it. + > * You must use the special `_` syntax. See the moduledoc for details. + + See `map_with/2` for a callback version of this function without `Explorer.Query`. + + This function only works with lazy computations. + See `transform/2` for a version that works with any Elixir function. + + ## Examples + + Basic example: + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.map(s, _ * 2) + #Explorer.Series< + Polars[3] + s64 [2, 4, 6] + > + + You can also use window functions and aggregations: + + iex> s = Explorer.Series.from_list([2, 3, 4]) + iex> Explorer.Series.map(s, _ - min(_)) + #Explorer.Series< + Polars[3] + s64 [0, 1, 2] + > + """ + @doc type: :element_wise + defmacro map(series, query) do + quote do + require Explorer.DataFrame + + Explorer.DataFrame.new(_: unquote(series)) + |> Explorer.DataFrame.mutate(_: unquote(query)) + |> Explorer.DataFrame.pull(:_) + end + end + + @doc """ + Maps a series with a callback function. + + This function only works with lazy computations. + See `transform/2` for a version that works with any Elixir function. + + ## Examples + + iex> series = Explorer.Series.from_list([2, 3, 4]) + iex> shift_left = fn s -> Explorer.Series.subtract(s, Explorer.Series.min(s)) end + iex> Explorer.Series.map_with(series, shift_left) + #Explorer.Series< + Polars[3] + s64 [0, 1, 2] + > + """ + @doc type: :element_wise + def map_with(%Series{} = series, fun) when is_function(fun, 1) do + Explorer.DataFrame.new(series: series) + |> Explorer.DataFrame.mutate_with(&[series: fun.(&1[:series])]) + |> Explorer.DataFrame.pull(:series) + end + + @doc """ + Sorts the series based on an expression. + + > #### Notice {: .notice} + > + > This is a macro. + > + > * You must `require Explorer.Series` before using it. + > * You must use the special `_` syntax. See the moduledoc for details. + + See `sort_with/3` for the callback-based version of this function. + + ## Options + + * `:direction` - `:asc` or `:desc`, meaning "ascending" or "descending", respectively. + By default it sorts in ascending order. + + * `:nils` - `:first` or `:last`. + By default it is `:last` if direction is `:asc`, and `:first` otherwise. + + * `:parallel` - boolean. + Whether to parallelize the sorting. + By default it is `true`. + + Parallel sort isn't available on certain lazy operations. + In those situations this option is ignored. + + * `:stable` - boolean. + Determines if the sorting is stable (ties are guaranteed to maintain their order) or not. + Unstable sorting may be more performant. + By default it is `false`. + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.sort_by(s, remainder(_, 3)) + #Explorer.Series< + Polars[3] + s64 [3, 1, 2] + > + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.sort_by(s, remainder(_, 3), direction: :desc) + #Explorer.Series< + Polars[3] + s64 [2, 1, 3] + > + + iex> s = Explorer.Series.from_list([1, nil, 2, 3]) + iex> Explorer.Series.sort_by(s, -2 * _, nils: :first) + #Explorer.Series< + Polars[4] + s64 [nil, 3, 2, 1] + > + """ + @doc type: :shape + defmacro sort_by(series, query, opts \\ []) do + {direction, opts} = Keyword.pop(opts, :direction, :asc) + + quote do + require Explorer.DataFrame + + Explorer.DataFrame.new(_: unquote(series)) + |> Explorer.DataFrame.sort_by([{unquote(direction), unquote(query)}], unquote(opts)) + |> Explorer.DataFrame.pull(:_) + end + end + + @doc """ + Sorts the series based on a callback that returns a lazy series. + + See `sort_by/3` for the expression-based version of this function. + + ## Options + + * `:direction` - `:asc` or `:desc`, meaning "ascending" or "descending", respectively. + By default it sorts in ascending order. + + * `:nils` - `:first` or `:last`. + By default it is `:last` if direction is `:asc`, and `:first` otherwise. + + * `:parallel` - boolean. + Whether to parallelize the sorting. + By default it is `true`. + + Parallel sort isn't available on certain lazy operations. + In those situations this option is ignored. + + * `:stable` - boolean. + Determines if the sorting is stable (ties are guaranteed to maintain their order) or not. + Unstable sorting may be more performant. + By default it is `false`. + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.sort_with(s, &Explorer.Series.remainder(&1, 3)) + #Explorer.Series< + Polars[3] + s64 [3, 1, 2] + > + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.sort_with(s, &Explorer.Series.remainder(&1, 3), direction: :desc) + #Explorer.Series< + Polars[3] + s64 [2, 1, 3] + > + + iex> s = Explorer.Series.from_list([1, nil, 2, 3]) + iex> Explorer.Series.sort_with(s, &Explorer.Series.multiply(-2, &1), nils: :first) + #Explorer.Series< + Polars[4] + s64 [nil, 3, 2, 1] + > + """ + @doc type: :shape + def sort_with(%Series{} = series, fun, opts \\ []) do + {direction, opts} = Keyword.pop(opts, :direction, :asc) + + Explorer.DataFrame.new(series: series) + |> Explorer.DataFrame.sort_with(&[{direction, fun.(&1[:series])}], opts) + |> Explorer.DataFrame.pull(:series) + end + + @doc """ + Filters a series with a mask. + + ## Examples + + iex> s1 = Explorer.Series.from_list([1,2,3]) + iex> s2 = Explorer.Series.from_list([true, false, true]) + iex> Explorer.Series.mask(s1, s2) + #Explorer.Series< + Polars[2] + s64 [1, 3] + > + """ + @doc type: :element_wise + @spec mask(series :: Series.t(), mask :: Series.t()) :: Series.t() + def mask(series, %Series{} = mask), do: apply_series(series, :mask, [mask]) + + @doc """ + Assign ranks to data with appropriate handling of tied values. + + ## Options + + * `:method` - Determine how ranks are assigned to tied elements. The following methods are available: + - `:average` : Each value receives the average rank that would be assigned to all tied values. (default) + - `:min` : Tied values are assigned the minimum rank. Also known as "competition" ranking. + - `:max` : Tied values are assigned the maximum of their ranks. + - `:dense` : Similar to `:min`, but the rank of the next highest element is assigned the rank immediately after those assigned to the tied elements. + - `:ordinal` : Each value is given a distinct rank based on its occurrence in the series. + - `:random` : Similar to `:ordinal`, but the rank for ties is not dependent on the order that the values occur in the Series. + * `:descending` - Rank in descending order. + * `:seed` - An integer to be used as a random seed. If nil, a random value between 0 and 2^64 − 1 will be used. (default: nil) + + ## Examples + + iex> s = Explorer.Series.from_list([3, 6, 1, 1, 6]) + iex> Explorer.Series.rank(s) + #Explorer.Series< + Polars[5] + f64 [3.0, 4.5, 1.5, 1.5, 4.5] + > + + iex> s = Explorer.Series.from_list([1.1, 2.4, 3.2]) + iex> Explorer.Series.rank(s, method: :ordinal) + #Explorer.Series< + Polars[3] + u32 [1, 2, 3] + > + + iex> s = Explorer.Series.from_list([ ~N[2022-07-07 17:44:13.020548], ~N[2022-07-07 17:43:08.473561], ~N[2022-07-07 17:45:00.116337] ]) + iex> Explorer.Series.rank(s, method: :average) + #Explorer.Series< + Polars[3] + f64 [2.0, 1.0, 3.0] + > + + iex> s = Explorer.Series.from_list([3, 6, 1, 1, 6]) + iex> Explorer.Series.rank(s, method: :min) + #Explorer.Series< + Polars[5] + s64 [3, 4, 1, 1, 4] + > + + iex> s = Explorer.Series.from_list([3, 6, 1, 1, 6]) + iex> Explorer.Series.rank(s, method: :dense) + #Explorer.Series< + Polars[5] + s64 [2, 3, 1, 1, 3] + > + + + iex> s = Explorer.Series.from_list([3, 6, 1, 1, 6]) + iex> Explorer.Series.rank(s, method: :random, seed: 42) + #Explorer.Series< + Polars[5] + s64 [3, 4, 2, 1, 5] + > + """ + @doc type: :element_wise + @spec rank(series :: Series.t(), opts :: Keyword.t()) :: Series.t() + def rank(series, opts \\ []) + + def rank(series, opts) do + opts = Keyword.validate!(opts, method: :average, descending: false, seed: nil) + + if K.not(K.in(opts[:method], [:average, :min, :max, :dense, :ordinal, :random])), + do: raise(ArgumentError, "unsupported rank method #{inspect(opts[:method])}") + + apply_series(series, :rank, [opts[:method], opts[:descending], opts[:seed]]) + end + + @doc """ + Returns a slice of the series, with `size` elements starting at `offset`. + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 3, 4, 5]) + iex> Explorer.Series.slice(s, 1, 2) + #Explorer.Series< + Polars[2] + s64 [2, 3] + > + + Negative offsets count from the end of the series: + + iex> s = Explorer.Series.from_list([1, 2, 3, 4, 5]) + iex> Explorer.Series.slice(s, -3, 2) + #Explorer.Series< + Polars[2] + s64 [3, 4] + > + + If the offset runs past the end of the series, + the series is empty: + + iex> s = Explorer.Series.from_list([1, 2, 3, 4, 5]) + iex> Explorer.Series.slice(s, 10, 3) + #Explorer.Series< + Polars[0] + s64 [] + > + + If the size runs past the end of the series, + the result may be shorter than the size: + + iex> s = Explorer.Series.from_list([1, 2, 3, 4, 5]) + iex> Explorer.Series.slice(s, -3, 4) + #Explorer.Series< + Polars[3] + s64 [3, 4, 5] + > + """ + @doc type: :shape + @spec slice(series :: Series.t(), offset :: integer(), size :: integer()) :: Series.t() + def slice(series, offset, size), do: apply_series(series, :slice, [offset, size]) + + @doc """ + Slices the elements at the given indices as a new series. + + The indices may be either a list (or series) of indices or a range. + A list or series of indices does not support negative numbers. + Ranges may be negative on either end, which are then + normalized. Note ranges in Elixir are inclusive. + + ## Examples + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.slice(s, [0, 2]) + #Explorer.Series< + Polars[2] + string ["a", "c"] + > + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.slice(s, 1..2) + #Explorer.Series< + Polars[2] + string ["b", "c"] + > + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.slice(s, -2..-1) + #Explorer.Series< + Polars[2] + string ["b", "c"] + > + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.slice(s, 3..2//1) + #Explorer.Series< + Polars[0] + string [] + > + + """ + @doc type: :shape + @spec slice(series :: Series.t(), indices :: [integer()] | Range.t() | Series.t()) :: Series.t() + def slice(series, indices) when is_list(indices), + do: apply_series(series, :slice, [indices]) + + def slice(series, %Series{dtype: int_dtype} = indices) when K.in(int_dtype, @integer_types), + do: apply_series(series, :slice, [indices]) + + def slice(_series, %Series{dtype: invalid_dtype}), + do: dtype_error("slice/2", invalid_dtype, @integer_types) + + def slice(series, first..last//1) do + first = if first < 0, do: first + size(series), else: first + last = if last < 0, do: last + size(series), else: last + size = last - first + 1 + + if K.and(first >= 0, size >= 0) do + apply_series(series, :slice, [first, size]) + else + apply_series(series, :slice, [[]]) + end + end + + def slice(series, %Range{} = range), + do: slice(series, Enum.slice(0..(size(series) - 1)//1, range)) + + @doc """ + Returns the value of the series at the given index. + + This function will raise an error in case the index + is out of bounds. + + ## Examples + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.at(s, 2) + "c" + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.at(s, 4) + ** (ArgumentError) index 4 out of bounds for series of size 3 + """ + @doc type: :shape + @spec at(series :: Series.t(), idx :: integer()) :: any() + def at(series, idx), do: fetch!(series, idx) + + @doc """ + Returns a string series with all values concatenated. + + ## Examples + + iex> s1 = Explorer.Series.from_list(["a", "b", "c"]) + iex> s2 = Explorer.Series.from_list(["d", "e", "f"]) + iex> s3 = Explorer.Series.from_list(["g", "h", "i"]) + iex> Explorer.Series.format([s1, s2, s3]) + #Explorer.Series< + Polars[3] + string ["adg", "beh", "cfi"] + > + + iex> s1 = Explorer.Series.from_list(["a", "b", "c", "d"]) + iex> s2 = Explorer.Series.from_list([1, 2, 3, 4]) + iex> s3 = Explorer.Series.from_list([1.5, :nan, :infinity, :neg_infinity]) + iex> Explorer.Series.format([s1, "/", s2, "/", s3]) + #Explorer.Series< + Polars[4] + string ["a/1/1.5", "b/2/NaN", "c/3/inf", "d/4/-inf"] + > + + iex> s1 = Explorer.Series.from_list([<<1>>, <<239, 191, 19>>], dtype: :binary) + iex> s2 = Explorer.Series.from_list([<<3>>, <<4>>], dtype: :binary) + iex> Explorer.Series.format([s1, s2]) + ** (RuntimeError) Polars Error: invalid utf8 + """ + @doc type: :shape + @spec format([Series.t() | String.t()]) :: Series.t() + def format([_ | _] = list) do + case cast_to_string(list) do + {[head | tail], true} -> + apply_series_varargs(:format, [from_list([head], dtype: :string) | tail]) + + {list, false} -> + apply_series_varargs(:format, list) + end + end + + defp cast_to_string(list) do + Enum.map_reduce(list, true, fn + %Series{dtype: :string} = s, _literal? -> + {s, false} + + %Series{} = s, _literal? -> + {cast(s, :string), false} + + value, literal? when K.or(is_binary(value), K.is_nil(value)) -> + {value, literal?} + + other, _literal? -> + raise ArgumentError, + "format/1 expects a list of series or strings, got: #{inspect(other)}" + end) + end + + @doc """ + Concatenate one or more series. + + Type promotion may happen between numeric series or + null series. All other dtypes must match. + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> s2 = Explorer.Series.from_list([4, 5, 6]) + iex> Explorer.Series.concat([s1, s2]) + #Explorer.Series< + Polars[6] + s64 [1, 2, 3, 4, 5, 6] + > + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> s2 = Explorer.Series.from_list([4.0, 5.0, 6.4]) + iex> Explorer.Series.concat([s1, s2]) + #Explorer.Series< + Polars[6] + f64 [1.0, 2.0, 3.0, 4.0, 5.0, 6.4] + > + """ + @doc type: :shape + @spec concat([Series.t()]) :: Series.t() + def concat([%Series{} | _t] = series) do + dtypes = series |> Enum.map(& &1.dtype) |> Enum.uniq() + + series = + case List.delete(dtypes, :null) do + [] -> + series + + [dtype] -> + if Enum.member?(dtypes, :null), do: Enum.map(series, &cast(&1, dtype)), else: series + + dtypes -> + dtype = + Enum.reduce(dtypes, fn left, right -> + Shared.merge_numeric_dtype(left, right) || + raise ArgumentError, + "cannot concatenate series with mismatched dtypes: #{inspect(dtypes)}. " <> + "First cast the series to the desired dtype." + end) + + Enum.map(series, &cast(&1, dtype)) + end + + apply_series_varargs(:concat, series) + end + + @doc """ + Concatenate two series. + + `concat(s1, s2)` is equivalent to `concat([s1, s2])`. + """ + @doc type: :shape + @spec concat(s1 :: Series.t(), s2 :: Series.t()) :: Series.t() + def concat(%Series{} = s1, %Series{} = s2), + do: concat([s1, s2]) + + @doc """ + Finds the first non-missing element at each position. + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, nil, nil]) + iex> s2 = Explorer.Series.from_list([1, 2, nil, 4]) + iex> s3 = Explorer.Series.from_list([nil, nil, 3, 4]) + iex> Explorer.Series.coalesce([s1, s2, s3]) + #Explorer.Series< + Polars[4] + s64 [1, 2, 3, 4] + > + """ + @doc type: :element_wise + @spec coalesce([Series.t()]) :: Series.t() + def coalesce([%Series{} = h | t]), + do: Enum.reduce(t, h, &coalesce(&2, &1)) + + @doc """ + Finds the first non-missing element at each position. + + `coalesce(s1, s2)` is equivalent to `coalesce([s1, s2])`. + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, nil, 3, nil]) + iex> s2 = Explorer.Series.from_list([1, 2, nil, 4]) + iex> Explorer.Series.coalesce(s1, s2) + #Explorer.Series< + Polars[4] + s64 [1, 2, 3, 4] + > + + iex> s1 = Explorer.Series.from_list(["foo", nil, "bar", nil]) + iex> s2 = Explorer.Series.from_list([1, 2, nil, 4]) + iex> Explorer.Series.coalesce(s1, s2) + ** (ArgumentError) cannot invoke Explorer.Series.coalesce/2 with mismatched dtypes: :string and {:s, 64} + """ + @doc type: :element_wise + @spec coalesce(s1 :: Series.t(), s2 :: Series.t()) :: Series.t() + def coalesce(s1, s2) do + :ok = check_dtypes_for_coalesce!(s1, s2) + apply_series_list(:coalesce, [s1, s2]) + end + + # Aggregation + + @doc """ + Gets the sum of the series. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:boolean` + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, nil, 3]) + iex> Explorer.Series.sum(s) + 6 + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, 3.0]) + iex> Explorer.Series.sum(s) + 6.0 + + iex> s = Explorer.Series.from_list([true, false, true]) + iex> Explorer.Series.sum(s) + 2 + + iex> s = Explorer.Series.from_list([~D[2021-01-01], ~D[1999-12-31]]) + iex> Explorer.Series.sum(s) + ** (ArgumentError) Explorer.Series.sum/1 not implemented for dtype :date. Valid dtypes are :boolean, {:f, 32}, {:f, 64}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :aggregation + @spec sum(series :: Series.t()) :: number() | non_finite() | nil + def sum(%Series{dtype: dtype} = series) when is_numeric_or_bool_dtype(dtype), + do: apply_series(series, :sum) + + def sum(%Series{dtype: dtype}), + do: dtype_error("sum/1", dtype, [:boolean | @numeric_dtypes]) + + @doc """ + Gets the minimum value of the series. + + ## Supported dtypes + + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:date` + * `:time` + * `:datetime` + * `:duration` + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, nil, 3]) + iex> Explorer.Series.min(s) + 1 + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, 3.0]) + iex> Explorer.Series.min(s) + 1.0 + + iex> s = Explorer.Series.from_list([~D[2021-01-01], ~D[1999-12-31]]) + iex> Explorer.Series.min(s) + ~D[1999-12-31] + + iex> s = Explorer.Series.from_list([~N[2021-01-01 00:00:00], ~N[1999-12-31 00:00:00]]) + iex> Explorer.Series.min(s) + ~N[1999-12-31 00:00:00.000000] + + iex> s = Explorer.Series.from_list([~T[00:02:03.000451], ~T[00:05:04.000134]]) + iex> Explorer.Series.min(s) + ~T[00:02:03.000451] + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.min(s) + ** (ArgumentError) Explorer.Series.min/1 not implemented for dtype :string. Valid dtypes are :date, :time, {:duration, :microsecond}, {:duration, :millisecond}, {:duration, :nanosecond}, {:f, 32}, {:f, 64}, {:naive_datetime, :microsecond}, {:naive_datetime, :millisecond}, {:naive_datetime, :nanosecond}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :aggregation + @spec min(series :: Series.t()) :: + number() | non_finite() | Date.t() | Time.t() | DateTime.t() | NaiveDateTime.t() | nil + def min(%Series{dtype: dtype} = series) when is_numeric_or_temporal_dtype(dtype), + do: apply_series(series, :min) + + def min(%Series{dtype: dtype}), do: dtype_error("min/1", dtype, @numeric_or_temporal_dtypes) + + @doc """ + Gets the maximum value of the series. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:date` + * `:time` + * `:naive_datetime` + * `:datetime` + * `:duration` + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, nil, 3]) + iex> Explorer.Series.max(s) + 3 + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, 3.0]) + iex> Explorer.Series.max(s) + 3.0 + + iex> s = Explorer.Series.from_list([~D[2021-01-01], ~D[1999-12-31]]) + iex> Explorer.Series.max(s) + ~D[2021-01-01] + + iex> s = Explorer.Series.from_list([~N[2021-01-01 00:00:00], ~N[1999-12-31 00:00:00]]) + iex> Explorer.Series.max(s) + ~N[2021-01-01 00:00:00.000000] + + iex> s = Explorer.Series.from_list([~T[00:02:03.000212], ~T[00:05:04.000456]]) + iex> Explorer.Series.max(s) + ~T[00:05:04.000456] + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.max(s) + ** (ArgumentError) Explorer.Series.max/1 not implemented for dtype :string. Valid dtypes are :date, :time, {:duration, :microsecond}, {:duration, :millisecond}, {:duration, :nanosecond}, {:f, 32}, {:f, 64}, {:naive_datetime, :microsecond}, {:naive_datetime, :millisecond}, {:naive_datetime, :nanosecond}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :aggregation + @spec max(series :: Series.t()) :: + number() | non_finite() | Date.t() | Time.t() | NaiveDateTime.t() | nil + def max(%Series{dtype: dtype} = series) when is_numeric_or_temporal_dtype(dtype), + do: apply_series(series, :max) + + def max(%Series{dtype: dtype}), do: dtype_error("max/1", dtype, @numeric_or_temporal_dtypes) + + @doc """ + Gets the index of the maximum value of the series. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:date` + * `:time` + * `:datetime` + * `:duration` + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, nil, 3]) + iex> Explorer.Series.argmax(s) + 3 + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, 3.0]) + iex> Explorer.Series.argmax(s) + 3 + + iex> s = Explorer.Series.from_list([~D[2021-01-01], ~D[1999-12-31]]) + iex> Explorer.Series.argmax(s) + 0 + + iex> s = Explorer.Series.from_list([~N[2021-01-01 00:00:00], ~N[1999-12-31 00:00:00]]) + iex> Explorer.Series.argmax(s) + 0 + + iex> s = Explorer.Series.from_list([~T[00:02:03.000212], ~T[00:05:04.000456]]) + iex> Explorer.Series.argmax(s) + 1 + + iex> s = Explorer.Series.from_list([], dtype: :integer) + iex> Explorer.Series.argmax(s) + nil + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.argmax(s) + ** (ArgumentError) Explorer.Series.argmax/1 not implemented for dtype :string. Valid dtypes are :date, :time, {:duration, :microsecond}, {:duration, :millisecond}, {:duration, :nanosecond}, {:f, 32}, {:f, 64}, {:naive_datetime, :microsecond}, {:naive_datetime, :millisecond}, {:naive_datetime, :nanosecond}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :aggregation + @spec argmax(series :: Series.t()) :: number() | non_finite() | nil + def argmax(%Series{dtype: dtype} = series) when is_numeric_or_temporal_dtype(dtype), + do: apply_series(series, :argmax) + + def argmax(%Series{dtype: dtype}), + do: dtype_error("argmax/1", dtype, @numeric_or_temporal_dtypes) + + @doc """ + Gets the index of the minimum value of the series. + + Note that `nil` is ignored. In case an empty list + or a series whose all elements are `nil` is used, + the result will be `nil`. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:date` + * `:time` + * `:datetime` + * `:duration` + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, nil, 3]) + iex> Explorer.Series.argmin(s) + 0 + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, 3.0]) + iex> Explorer.Series.argmin(s) + 0 + + iex> s = Explorer.Series.from_list([~D[2021-01-01], ~D[1999-12-31]]) + iex> Explorer.Series.argmin(s) + 1 + + iex> s = Explorer.Series.from_list([~N[2021-01-01 00:00:00], ~N[1999-12-31 00:00:00]]) + iex> Explorer.Series.argmin(s) + 1 + + iex> s = Explorer.Series.from_list([~T[00:02:03.000212], ~T[00:05:04.000456]]) + iex> Explorer.Series.argmin(s) + 0 + + iex> s = Explorer.Series.from_list([], dtype: :integer) + iex> Explorer.Series.argmin(s) + nil + + iex> s = Explorer.Series.from_list([nil], dtype: :integer) + iex> Explorer.Series.argmin(s) + nil + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.argmin(s) + ** (ArgumentError) Explorer.Series.argmin/1 not implemented for dtype :string. Valid dtypes are :date, :time, {:duration, :microsecond}, {:duration, :millisecond}, {:duration, :nanosecond}, {:f, 32}, {:f, 64}, {:naive_datetime, :microsecond}, {:naive_datetime, :millisecond}, {:naive_datetime, :nanosecond}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :aggregation + @spec argmin(series :: Series.t()) :: number() | non_finite() | nil + def argmin(%Series{dtype: dtype} = series) when is_numeric_or_temporal_dtype(dtype), + do: apply_series(series, :argmin) + + def argmin(%Series{dtype: dtype}), + do: dtype_error("argmin/1", dtype, @numeric_or_temporal_dtypes) + + @doc """ + Gets the mean value of the series. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * decimals: the result will be a float + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, nil, 3]) + iex> Explorer.Series.mean(s) + 2.0 + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, 3.0]) + iex> Explorer.Series.mean(s) + 2.0 + + iex> s = Explorer.Series.from_list([~D[2021-01-01], ~D[1999-12-31]]) + iex> Explorer.Series.mean(s) + ** (ArgumentError) Explorer.Series.mean/1 not implemented for dtype :date. Valid dtypes are {:f, 32}, {:f, 64}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :aggregation + @spec mean(series :: Series.t()) :: float() | non_finite() | nil + def mean(%Series{dtype: dtype} = series) when is_numeric_dtype(dtype), + do: apply_series(series, :mean) + + def mean(%Series{dtype: dtype}), + do: dtype_error("mean/1", dtype, @numeric_dtypes) + + @doc """ + Gets the most common value(s) of the series. + + This function will return multiple values when there's a tie. + + ## Supported dtypes + + All except `:list` and `:struct`. + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 2, nil]) + iex> Explorer.Series.mode(s) + #Explorer.Series< + Polars[1] + s64 [2] + > + + iex> s = Explorer.Series.from_list(["a", "b", "b", "c"]) + iex> Explorer.Series.mode(s) + #Explorer.Series< + Polars[1] + string ["b"] + > + + This function can return multiple entries, but the order is not guaranteed. + You may sort the series if desired. + + iex> s = Explorer.Series.from_list([1.0, 2.0, 2.0, 3.0, 3.0]) + iex> Explorer.Series.mode(s) |> Explorer.Series.sort() + #Explorer.Series< + Polars[2] + f64 [2.0, 3.0] + > + """ + @doc type: :aggregation + @spec mode(series :: Series.t()) :: Series.t() | nil + def mode(%Series{dtype: {composite, _} = dtype}) when K.in(composite, [:list, :struct]), + do: dtype_error("mode/1", dtype, Shared.dtypes() -- [{:list, :any}, {:struct, :any}]) + + def mode(%Series{} = series), + do: apply_series(series, :mode) + + @doc """ + Gets the median value of the series. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * decimals: the result will be a float + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, nil, 3]) + iex> Explorer.Series.median(s) + 2.0 + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, 3.0]) + iex> Explorer.Series.median(s) + 2.0 + + iex> s = Explorer.Series.from_list([~D[2021-01-01], ~D[1999-12-31]]) + iex> Explorer.Series.median(s) + ** (ArgumentError) Explorer.Series.median/1 not implemented for dtype :date. Valid dtypes are {:f, 32}, {:f, 64}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :aggregation + @spec median(series :: Series.t()) :: float() | non_finite() | nil + def median(%Series{dtype: dtype} = series) when is_numeric_dtype(dtype), + do: apply_series(series, :median) + + def median(%Series{dtype: dtype}), + do: dtype_error("median/1", dtype, @numeric_dtypes) + + @doc """ + Gets the variance of the series. + + By default, this is the sample variance. This function also takes an optional + delta degrees of freedom (ddof). Setting this to zero corresponds to the population + variance. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, nil, 3]) + iex> Explorer.Series.variance(s) + 1.0 + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, 3.0]) + iex> Explorer.Series.variance(s) + 1.0 + + iex> s = Explorer.Series.from_list([~N[2021-01-01 00:00:00], ~N[1999-12-31 00:00:00]]) + iex> Explorer.Series.variance(s) + ** (ArgumentError) Explorer.Series.variance/1 not implemented for dtype {:naive_datetime, :microsecond}. Valid dtypes are {:f, 32}, {:f, 64}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :aggregation + @spec variance(series :: Series.t(), ddof :: non_neg_integer()) :: float() | non_finite() | nil + def variance(series, ddof \\ 1) + + def variance(%Series{dtype: dtype} = series, ddof) when is_numeric_dtype(dtype), + do: apply_series(series, :variance, [ddof]) + + def variance(%Series{dtype: dtype}, _), do: dtype_error("variance/1", dtype, @numeric_dtypes) + + @doc """ + Gets the standard deviation of the series. + + By default, this is the sample standard deviation. This function also takes an optional + delta degrees of freedom (ddof). Setting this to zero corresponds to the population + sample standard deviation. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * decimals: the result will be a float + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, nil, 3]) + iex> Explorer.Series.standard_deviation(s) + 1.0 + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, 3.0]) + iex> Explorer.Series.standard_deviation(s) + 1.0 + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.standard_deviation(s) + ** (ArgumentError) Explorer.Series.standard_deviation/1 not implemented for dtype :string. Valid dtypes are {:f, 32}, {:f, 64}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :aggregation + @spec standard_deviation(series :: Series.t(), ddof :: non_neg_integer()) :: + float() | non_finite() | nil + def standard_deviation(series, ddof \\ 1) + + def standard_deviation(%Series{dtype: dtype} = series, ddof) when is_numeric_dtype(dtype), + do: apply_series(series, :standard_deviation, [ddof]) + + def standard_deviation(%Series{dtype: dtype}, _), + do: dtype_error("standard_deviation/1", dtype, @numeric_dtypes) + + @doc """ + Reduce this Series to the product value. + + Note that an empty series is going to result in a + product of `1`. Values that are `nil` are ignored. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.product(s) + 6 + + iex> s = Explorer.Series.from_list([], dtype: :float) + iex> Explorer.Series.product(s) + 1.0 + + iex> s = Explorer.Series.from_list([true, false, true]) + iex> Explorer.Series.product(s) + ** (ArgumentError) Explorer.Series.product/1 not implemented for dtype :boolean. Valid dtypes are {:f, 32}, {:f, 64}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :aggregation + @spec product(series :: Series.t()) :: float() | non_finite() | nil + def product(%Series{dtype: dtype} = series) when is_numeric_dtype(dtype), + do: apply_series(series, :product) + + def product(%Series{dtype: dtype}), + do: dtype_error("product/1", dtype, @numeric_dtypes) + + @doc """ + Gets the given quantile of the series. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:date` + * `:time` + * `:datetime` + * `:duration` + * `:decimal` + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, nil, 3]) + iex> Explorer.Series.quantile(s, 0.2) + 1 + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, 3.0]) + iex> Explorer.Series.quantile(s, 0.5) + 2.0 + + iex> s = Explorer.Series.from_list([~D[2021-01-01], ~D[1999-12-31]]) + iex> Explorer.Series.quantile(s, 0.5) + ~D[2021-01-01] + + iex> s = Explorer.Series.from_list([~N[2021-01-01 00:00:00], ~N[1999-12-31 00:00:00]]) + iex> Explorer.Series.quantile(s, 0.5) + ~N[2021-01-01 00:00:00.000000] + + iex> s = Explorer.Series.from_list([~T[01:55:00], ~T[15:35:00], ~T[23:00:00]]) + iex> Explorer.Series.quantile(s, 0.5) + ~T[15:35:00.000000] + + iex> s = Explorer.Series.from_list([true, false, true]) + iex> Explorer.Series.quantile(s, 0.5) + ** (ArgumentError) Explorer.Series.quantile/2 not implemented for dtype :boolean. Valid dtypes are any subtype of [:u, :s, :f, :date, :time, :naive_datetime, :datetime] + """ + @doc type: :aggregation + @spec quantile(series :: Series.t(), quantile :: float()) :: any() + def quantile(%Series{dtype: dtype} = series, quantile) + when is_numeric_or_temporal_dtype(dtype), + do: apply_series(series, :quantile, [quantile]) + + def quantile(%Series{dtype: dtype}, _) do + super_dtypes = [:u, :s, :f, :date, :time, :naive_datetime, :datetime] + super_dtype_error("quantile/2", dtype, super_dtypes) + end + + @doc """ + Compute the sample skewness of a series. + + For normally distributed data, the skewness should be about zero. + + For unimodal continuous distributions, a skewness value greater + than zero means that there is more weight in the right tail of the + distribution. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 3, 4, 5, 23]) + iex> Explorer.Series.skew(s) + 1.6727687946848508 + + iex> s = Explorer.Series.from_list([1, 2, 3, 4, 5, 23]) + iex> Explorer.Series.skew(s, bias: false) + 2.2905330058490514 + + iex> s = Explorer.Series.from_list([1, 2, 3, nil, 1]) + iex> Explorer.Series.skew(s, bias: false) + 0.8545630383279712 + + iex> s = Explorer.Series.from_list([1, 2, 3, nil, 1]) + iex> Explorer.Series.skew(s) + 0.49338220021815865 + + iex> s = Explorer.Series.from_list([true, false, true]) + iex> Explorer.Series.skew(s, false) + ** (ArgumentError) Explorer.Series.skew/2 not implemented for dtype :boolean. Valid dtypes are {:f, 32}, {:f, 64}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :aggregation + @spec skew(series :: Series.t(), opts :: Keyword.t()) :: float() | non_finite() | nil + def skew(series, opts \\ []) + + def skew(%Series{dtype: dtype} = series, opts) when is_numeric_dtype(dtype) do + opts = Keyword.validate!(opts, bias: true) + apply_series(series, :skew, [opts[:bias]]) + end + + def skew(%Series{dtype: dtype}, _), + do: dtype_error("skew/2", dtype, @numeric_dtypes) + + @doc """ + Compute the correlation between two series. + + The parameter `ddof` refers to the 'delta degrees of freedom' - the divisor + used in the correlation calculation. Defaults to 1. + + The parameter `:method` refers to the correlation method. The following methods are available: + - `:pearson` : Standard correlation coefficient. (default) + - `:spearman` : Spearman rank correlation. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * decimals: the result will be a float + + ## Examples + + iex> s1 = Series.from_list([1, 8, 3]) + iex> s2 = Series.from_list([4, 5, 2]) + iex> Series.correlation(s1, s2) + 0.5447047794019219 + """ + @doc type: :aggregation + @spec correlation( + left :: Series.t() | number(), + right :: Series.t() | number(), + opts :: Keyword.t() + ) :: + float() | non_finite() | nil + def correlation(left, right, opts \\ []) do + opts = Keyword.validate!(opts, ddof: 1, method: :pearson) + + if K.not(K.in(opts[:method], [:pearson, :spearman])), + do: raise(ArgumentError, "unsupported correlation method #{inspect(opts[:method])}") + + basic_numeric_operation(:correlation, left, right, [opts[:ddof], opts[:method]]) + end + + @doc """ + Compute the covariance between two series. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * decimals: the result will be a float + + ## Examples + + iex> s1 = Series.from_list([1, 8, 3]) + iex> s2 = Series.from_list([4, 5, 2]) + iex> Series.covariance(s1, s2) + 3.0 + """ + @doc type: :aggregation + @spec covariance( + left :: Series.t() | number(), + right :: Series.t() | number(), + ddof :: non_neg_integer() + ) :: + float() | non_finite() | nil + def covariance(left, right, ddof \\ 1) do + basic_numeric_operation(:covariance, left, right, [ddof]) + end + + @doc """ + Returns if all the values in a boolean series are true. + + ## Supported dtypes + + * `:boolean` + + ## Examples + + iex> s = Series.from_list([true, true, true]) + iex> Series.all?(s) + true + + iex> s = Series.from_list([true, false, true]) + iex> Series.all?(s) + false + + iex> s = Series.from_list([1, 2, 3]) + iex> Series.all?(s) + ** (ArgumentError) Explorer.Series.all?/1 not implemented for dtype {:s, 64}. Valid dtype is :boolean + + An empty series will always return true: + + iex> s = Series.from_list([], dtype: :boolean) + iex> Series.all?(s) + true + + Opposite to Elixir but similar to databases, `nil` values are ignored: + + iex> s = Series.from_list([nil, true, true]) + iex> Series.all?(s) + true + + iex> s = Series.from_list([nil, nil, nil], dtype: :boolean) + iex> Series.all?(s) + true + """ + @doc type: :aggregation + @spec all?(series :: Series.t()) :: boolean() + def all?(%Series{dtype: :boolean} = series), do: apply_series(series, :all?) + def all?(%Series{dtype: dtype}), do: dtype_error("all?/1", dtype, [:boolean]) + + @doc """ + Returns if any of the values in a boolean series are true. + + ## Supported dtypes + + * `:boolean` + + ## Examples + + iex> s = Series.from_list([true, true, true]) + iex> Series.any?(s) + true + + iex> s = Series.from_list([true, false, true]) + iex> Series.any?(s) + true + + iex> s = Series.from_list([1, 2, 3]) + iex> Series.any?(s) + ** (ArgumentError) Explorer.Series.any?/1 not implemented for dtype {:s, 64}. Valid dtype is :boolean + + An empty series will always return `false`: + + iex> s = Series.from_list([], dtype: :boolean) + iex> Series.any?(s) + false + + Opposite to Elixir but similar to databases, `nil` values are ignored: + + iex> s = Series.from_list([nil, true, true]) + iex> Series.any?(s) + true + + iex> s = Series.from_list([nil, nil, nil], dtype: :boolean) + iex> Series.any?(s) + false + """ + @doc type: :aggregation + @spec any?(series :: Series.t()) :: boolean() + def any?(%Series{dtype: :boolean} = series), do: apply_series(series, :any?) + def any?(%Series{dtype: dtype}), do: dtype_error("any?/1", dtype, [:boolean]) + + @doc """ + Returns a series of indexes for each item (row) in the series, starting from 0. + + ## Examples + + iex> s = Series.from_list([nil, true, true]) + iex> Series.row_index(s) + #Explorer.Series< + Polars[3] + u32 [0, 1, 2] + > + + This function can be used to add a row index as the first column of a dataframe. + The resulting column is a regular column of type `:u32`. + + iex> require Explorer.DataFrame, as: DF + iex> df = DF.new(a: [1, 3, 5], b: [2, 4, 6]) + iex> DF.mutate(df, index: row_index(a)) |> DF.relocate("index", before: 0) + #Explorer.DataFrame< + Polars[3 x 3] + index u32 [0, 1, 2] + a s64 [1, 3, 5] + b s64 [2, 4, 6] + > + iex> df = DF.new(a: [1, 3, 5], b: [2, 4, 6]) + iex> DF.mutate(df, id: row_index(a) + 1000) + #Explorer.DataFrame< + Polars[3 x 3] + a s64 [1, 3, 5] + b s64 [2, 4, 6] + id s64 [1000, 1001, 1002] + > + """ + @doc type: :element_wise + @spec row_index(Series.t()) :: Series.t() + def row_index(%Series{} = series), do: apply_series(series, :row_index) + + # Cumulative + + @doc """ + Calculates the cumulative maximum of the series. + + Optionally, can accumulate in reverse. + + Does not fill nil values. See `fill_missing/2`. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:date` + * `:time` + * `:datetime` + * `:duration` + + ## Examples + + iex> s = [1, 2, 3, 4] |> Explorer.Series.from_list() + iex> Explorer.Series.cumulative_max(s) + #Explorer.Series< + Polars[4] + s64 [1, 2, 3, 4] + > + + iex> s = [1, 2, nil, 4] |> Explorer.Series.from_list() + iex> Explorer.Series.cumulative_max(s) + #Explorer.Series< + Polars[4] + s64 [1, 2, nil, 4] + > + + iex> s = [~T[03:00:02.000000], ~T[02:04:19.000000], nil, ~T[13:24:56.000000]] |> Explorer.Series.from_list() + iex> Explorer.Series.cumulative_max(s) + #Explorer.Series< + Polars[4] + time [03:00:02.000000, 03:00:02.000000, nil, 13:24:56.000000] + > + """ + @doc type: :window + @spec cumulative_max(series :: Series.t(), opts :: Keyword.t()) :: Series.t() + def cumulative_max(series, opts \\ []) + + def cumulative_max(%Series{dtype: dtype} = series, opts) + when is_numeric_or_temporal_dtype(dtype) do + opts = Keyword.validate!(opts, reverse: false) + apply_series(series, :cumulative_max, [opts[:reverse]]) + end + + def cumulative_max(%Series{dtype: dtype}, _), + do: dtype_error("cumulative_max/2", dtype, @numeric_or_temporal_dtypes) + + @doc """ + Calculates the cumulative minimum of the series. + + Optionally, can accumulate in reverse. + + Does not fill nil values. See `fill_missing/2`. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:date` + * `:time` + * `:datetime` + * `:duration` + + ## Examples + + iex> s = [1, 2, 3, 4] |> Explorer.Series.from_list() + iex> Explorer.Series.cumulative_min(s) + #Explorer.Series< + Polars[4] + s64 [1, 1, 1, 1] + > + + iex> s = [1, 2, nil, 4] |> Explorer.Series.from_list() + iex> Explorer.Series.cumulative_min(s) + #Explorer.Series< + Polars[4] + s64 [1, 1, nil, 1] + > + + iex> s = [~T[03:00:02.000000], ~T[02:04:19.000000], nil, ~T[13:24:56.000000]] |> Explorer.Series.from_list() + iex> Explorer.Series.cumulative_min(s) + #Explorer.Series< + Polars[4] + time [03:00:02.000000, 02:04:19.000000, nil, 02:04:19.000000] + > + """ + @doc type: :window + @spec cumulative_min(series :: Series.t(), opts :: Keyword.t()) :: Series.t() + def cumulative_min(series, opts \\ []) + + def cumulative_min(%Series{dtype: dtype} = series, opts) + when is_numeric_or_temporal_dtype(dtype) do + opts = Keyword.validate!(opts, reverse: false) + apply_series(series, :cumulative_min, [opts[:reverse]]) + end + + def cumulative_min(%Series{dtype: dtype}, _), + do: dtype_error("cumulative_min/2", dtype, @numeric_or_temporal_dtypes) + + @doc """ + Calculates the cumulative sum of the series. + + Optionally, can accumulate in reverse. + + Does not fill nil values. See `fill_missing/2`. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:boolean` + + ## Examples + + iex> s = [1, 2, 3, 4] |> Explorer.Series.from_list() + iex> Explorer.Series.cumulative_sum(s) + #Explorer.Series< + Polars[4] + s64 [1, 3, 6, 10] + > + + iex> s = [1, 2, nil, 4] |> Explorer.Series.from_list() + iex> Explorer.Series.cumulative_sum(s) + #Explorer.Series< + Polars[4] + s64 [1, 3, nil, 7] + > + """ + @doc type: :window + @spec cumulative_sum(series :: Series.t(), opts :: Keyword.t()) :: Series.t() + def cumulative_sum(series, opts \\ []) + + def cumulative_sum(%Series{dtype: dtype} = series, opts) + when is_numeric_dtype(dtype) do + opts = Keyword.validate!(opts, reverse: false) + apply_series(series, :cumulative_sum, [opts[:reverse]]) + end + + def cumulative_sum(%Series{dtype: dtype}, _), + do: dtype_error("cumulative_sum/2", dtype, @numeric_dtypes) + + @doc """ + Calculates the cumulative product of the series. + + Optionally, can accumulate in reverse. + + Does not fill nil values. See `fill_missing/2`. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + + ## Examples + + iex> s = [1, 2, 3, 2] |> Explorer.Series.from_list() + iex> Explorer.Series.cumulative_product(s) + #Explorer.Series< + Polars[4] + s64 [1, 2, 6, 12] + > + + iex> s = [1, 2, nil, 4] |> Explorer.Series.from_list() + iex> Explorer.Series.cumulative_product(s) + #Explorer.Series< + Polars[4] + s64 [1, 2, nil, 8] + > + """ + @doc type: :window + @spec cumulative_product(series :: Series.t(), opts :: Keyword.t()) :: Series.t() + def cumulative_product(series, opts \\ []) + + def cumulative_product(%Series{dtype: dtype} = series, opts) + when is_numeric_dtype(dtype) do + opts = Keyword.validate!(opts, reverse: false) + apply_series(series, :cumulative_product, [opts[:reverse]]) + end + + def cumulative_product(%Series{dtype: dtype}, _), + do: dtype_error("cumulative_product/2", dtype, @numeric_dtypes) + + # Local minima/maxima + + @doc """ + Returns a boolean mask with `true` where the 'peaks' (series max or min, default max) are. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:date` + * `:time` + * `:datetime` + * `:duration` + * `:decimal` + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 4, 1, 4]) + iex> Explorer.Series.peaks(s) + #Explorer.Series< + Polars[5] + boolean [false, false, true, false, true] + > + + iex> s = [~T[03:00:02.000000], ~T[13:24:56.000000], ~T[02:04:19.000000]] |> Explorer.Series.from_list() + iex> Explorer.Series.peaks(s) + #Explorer.Series< + Polars[3] + boolean [false, true, false] + > + """ + @doc type: :element_wise + @spec peaks(series :: Series.t(), max_or_min :: :max | :min) :: Series.t() + def peaks(series, max_or_min \\ :max) + + def peaks(%Series{dtype: dtype} = series, max_or_min) + when is_numeric_or_temporal_dtype(dtype), + do: apply_series(series, :peaks, [max_or_min]) + + def peaks(%Series{dtype: dtype}, _), + do: dtype_error("peaks/2", dtype, @numeric_or_temporal_dtypes) + + # Arithmetic + + defp cast_for_arithmetic(function, [_, _] = args) do + args + |> case do + [%Series{}, %Series{}] -> args + [left, %Series{} = right] -> [from_list([left]), right] + [%Series{} = left, right] -> [left, from_list([right])] + [left, right] -> no_series_error(function, left, right) + end + |> enforce_highest_precision() + end + + defp enforce_highest_precision([ + %Series{dtype: dtype_left} = left, + %Series{dtype: dtype_right} = right + ]) + when K.and( + K.or(is_datetime_like_dtype(dtype_left), is_duration_dtype(dtype_left)), + K.or(is_datetime_like_dtype(dtype_right), is_duration_dtype(dtype_right)) + ) do + # Higher precision wins, otherwise information is lost. + case {extract_precision(dtype_left), extract_precision(dtype_right)} do + {equal, equal} -> [left, right] + {:nanosecond, _} -> [left, cast(right, update_precision(dtype_right, :nanosecond))] + {_, :nanosecond} -> [cast(left, update_precision(dtype_left, :nanosecond)), right] + {:microsecond, _} -> [left, cast(right, update_precision(dtype_right, :microsecond))] + {_, :microsecond} -> [cast(left, update_precision(dtype_right, :microsecond)), right] + end + end + + defp enforce_highest_precision(args), do: args + + defp extract_precision({:naive_datetime, precision}), do: precision + defp extract_precision({:datetime, precision, _time_zone}), do: precision + defp extract_precision({:duration, precision}), do: precision + + defp update_precision({:naive_datetime, _old}, new), do: {:naive_datetime, new} + defp update_precision({:datetime, _old, time_zone}, new), do: {:datetime, new, time_zone} + defp update_precision({:duration, _old}, new), do: {:duration, new} + + @doc """ + Adds right to left, element-wise. + + When mixing floats and integers, the resulting series will have dtype `{:f, 64}`. + + At least one of the arguments must be a series. If both + sizes are series, the series must have the same size or + at last one of them must have size of 1. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:decimal` + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> s2 = Explorer.Series.from_list([4, 5, 6]) + iex> Explorer.Series.add(s1, s2) + #Explorer.Series< + Polars[3] + s64 [5, 7, 9] + > + + You can also use scalar values on both sides: + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.add(s1, 2) + #Explorer.Series< + Polars[3] + s64 [3, 4, 5] + > + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.add(2, s1) + #Explorer.Series< + Polars[3] + s64 [3, 4, 5] + > + """ + @doc type: :element_wise + @spec add( + left :: + Series.t() | number() | Date.t() | DateTime.t() | NaiveDateTime.t() | Duration.t(), + right :: + Series.t() | number() | Date.t() | DateTime.t() | NaiveDateTime.t() | Duration.t() + ) :: Series.t() + def add(left, right) do + [left, right] = cast_for_arithmetic("add/2", [left, right]) + + if out_dtype = cast_to_add(dtype(left), dtype(right)) do + apply_series_list(:add, [out_dtype, left, right]) + else + dtype_mismatch_error("add/2", left, right) + end + end + + defp cast_to_add(:date, {:duration, _}), do: :date + defp cast_to_add({:duration, _}, :date), do: :date + defp cast_to_add({:naive_datetime, p}, {:duration, p}), do: {:naive_datetime, p} + defp cast_to_add({:duration, p}, {:naive_datetime, p}), do: {:naive_datetime, p} + defp cast_to_add({:datetime, p, tz}, {:duration, p}), do: {:datetime, p, tz} + defp cast_to_add({:duration, p}, {:datetime, p, tz}), do: {:datetime, p, tz} + defp cast_to_add({:duration, p}, {:duration, p}), do: {:duration, p} + + defp cast_to_add({:decimal, p1, s1}, {:decimal, p2, s2}), + do: {:decimal, maybe_max(p1, p2), maybe_max(s1, s2)} + + defp cast_to_add(left, right), do: Shared.merge_numeric_dtype(left, right) + + defp maybe_max(left, right) when K.and(is_integer(left), is_integer(right)), + do: K.max(left, right) + + defp maybe_max(left, nil), do: left + defp maybe_max(nil, right), do: right + + @doc """ + Subtracts right from left, element-wise. + + When mixing floats and integers, the resulting series will have dtype `{:f, 64}`. + In case both series are of unsigned integers, we will try to subtract, + but an exception is raised if overflow occurs. + + At least one of the arguments must be a series. If both + sizes are series, the series must have the same size or + at last one of them must have size of 1. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * decimals + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> s2 = Explorer.Series.from_list([4, 5, 6]) + iex> Explorer.Series.subtract(s1, s2) + #Explorer.Series< + Polars[3] + s64 [-3, -3, -3] + > + + You can also use scalar values on both sides: + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.subtract(s1, 2) + #Explorer.Series< + Polars[3] + s64 [-1, 0, 1] + > + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.subtract(2, s1) + #Explorer.Series< + Polars[3] + s64 [1, 0, -1] + > + """ + @doc type: :element_wise + @spec subtract( + left :: + Series.t() | number() | Date.t() | DateTime.t() | NaiveDateTime.t() | Duration.t(), + right :: + Series.t() | number() | Date.t() | DateTime.t() | NaiveDateTime.t() | Duration.t() + ) :: Series.t() + def subtract(left, right) do + [left, right] = cast_for_arithmetic("subtract/2", [left, right]) + + if out_dtype = cast_to_subtract(dtype(left), dtype(right)) do + apply_series_list(:subtract, [out_dtype, left, right]) + else + dtype_mismatch_error("subtract/2", left, right) + end + end + + defp cast_to_subtract(:date, :date), do: {:duration, :millisecond} + defp cast_to_subtract(:date, {:duration, _}), do: :date + defp cast_to_subtract({:naive_datetime, p}, {:naive_datetime, p}), do: {:duration, p} + defp cast_to_subtract({:naive_datetime, p}, {:duration, p}), do: {:naive_datetime, p} + defp cast_to_subtract({:datetime, p, tz}, {:datetime, p, tz}), do: {:duration, p} + defp cast_to_subtract({:datetime, p, tz}, {:duration, p}), do: {:datetime, p, tz} + defp cast_to_subtract({:duration, p}, {:duration, p}), do: {:duration, p} + + defp cast_to_subtract({:decimal, p1, s1}, {:decimal, p2, s2}), + do: {:decimal, maybe_max(p1, p2), maybe_max(s1, s2)} + + defp cast_to_subtract(left, right), do: Shared.merge_numeric_dtype(left, right) + + @doc """ + Multiplies left and right, element-wise. + + When mixing floats and integers, the resulting series will have dtype `{:f, 64}`. + + At least one of the arguments must be a series. If both + sizes are series, the series must have the same size or + at last one of them must have size of 1. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * decimals: the result will be a decimal series + + ## Examples + + iex> s1 = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> s2 = 11..20 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.multiply(s1, s2) + #Explorer.Series< + Polars[10] + s64 [11, 24, 39, 56, 75, 96, 119, 144, 171, 200] + > + + iex> s1 = 1..5 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.multiply(s1, 2) + #Explorer.Series< + Polars[5] + s64 [2, 4, 6, 8, 10] + > + """ + @doc type: :element_wise + @spec multiply( + left :: Series.t() | number() | Duration.t(), + right :: Series.t() | number() | Duration.t() + ) :: Series.t() + def multiply(left, right) do + [left, right] = cast_for_arithmetic("multiply/2", [left, right]) + + if out_dtype = cast_to_multiply(dtype(left), dtype(right)) do + apply_series_list(:multiply, [out_dtype, left, right]) + else + dtype_mismatch_error("multiply/2", left, right) + end + end + + defp cast_to_multiply({:s, _}, {:duration, p}), do: {:duration, p} + defp cast_to_multiply({:duration, p}, {:s, _}), do: {:duration, p} + defp cast_to_multiply({:f, _}, {:duration, p}), do: {:duration, p} + defp cast_to_multiply({:duration, p}, {:f, _}), do: {:duration, p} + + defp cast_to_multiply({:decimal, p1, s1}, {:decimal, p2, s2}), + do: {:decimal, maybe_max(p1, p2), maybe_max(s1, s2)} + + defp cast_to_multiply(left, right), do: Shared.merge_numeric_dtype(left, right) + + @doc """ + Divides left by right, element-wise. + + The resulting series will have the dtype as `{:f, 64}`. + + At least one of the arguments must be a series. If both + sizes are series, the series must have the same size or + at last one of them must have size of 1. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * decimals: the result will be a float series + + ## Examples + + iex> s1 = [10, 10, 10] |> Explorer.Series.from_list() + iex> s2 = [2, 2, 2] |> Explorer.Series.from_list() + iex> Explorer.Series.divide(s1, s2) + #Explorer.Series< + Polars[3] + f64 [5.0, 5.0, 5.0] + > + + iex> s1 = [10, 10, 10] |> Explorer.Series.from_list() + iex> Explorer.Series.divide(s1, 2) + #Explorer.Series< + Polars[3] + f64 [5.0, 5.0, 5.0] + > + + iex> s1 = [10, 52 ,10] |> Explorer.Series.from_list() + iex> Explorer.Series.divide(s1, 2.5) + #Explorer.Series< + Polars[3] + f64 [4.0, 20.8, 4.0] + > + + iex> s1 = [10, 10, 10] |> Explorer.Series.from_list() + iex> s2 = [2, 0, 2] |> Explorer.Series.from_list() + iex> Explorer.Series.divide(s1, s2) + #Explorer.Series< + Polars[3] + f64 [5.0, Inf, 5.0] + > + """ + @doc type: :element_wise + @spec divide( + left :: Series.t() | number() | Duration.t(), + right :: Series.t() | number() + ) :: Series.t() + def divide(left, right) do + [left, right] = cast_for_arithmetic("divide/2", [left, right]) + + if out_dtype = cast_to_divide(dtype(left), dtype(right)) do + apply_series_list(:divide, [out_dtype, left, right]) + else + case dtype(right) do + {:duration, _} -> raise(ArgumentError, "cannot divide by duration") + _ -> dtype_mismatch_error("divide/2", left, right) + end + end + end + + # Review the size needed for this operation. + defp cast_to_divide({int_type, _}, {int_type, _}) when K.in(int_type, [:s, :u]), do: {:f, 64} + defp cast_to_divide({:s, _}, {:u, _}), do: {:f, 64} + defp cast_to_divide({:u, _}, {:s, _}), do: {:f, 64} + defp cast_to_divide({int_type, _}, {:f, _} = float) when K.in(int_type, [:s, :u]), do: float + defp cast_to_divide({:f, _} = float, {int_type, _}) when K.in(int_type, [:s, :u]), do: float + defp cast_to_divide({:f, left}, {:f, right}), do: {:f, max(left, right)} + defp cast_to_divide({:duration, p}, {:s, _}), do: {:duration, p} + defp cast_to_divide({:duration, p}, {:f, _}), do: {:duration, p} + # This is due limitations of Polars. Ideally it should be decimal here. + defp cast_to_divide({:decimal, _, _}, {:decimal, _, _}), do: {:f, 64} + defp cast_to_divide(_, _), do: nil + + @doc """ + Raises a numeric series to the power of the exponent. + + At least one of the arguments must be a series. If both + sides are series, the series must have the same size or + at last one of them must have size of 1. + + Note that this operation can fail if the exponent is a + signed integer series or scalar containing negative values, + and the base is also of an integer type. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * decimals: the result will be a float series + + ## Examples + + iex> s = [8, 16, 32] |> Explorer.Series.from_list() + iex> Explorer.Series.pow(s, 2.0) + #Explorer.Series< + Polars[3] + f64 [64.0, 256.0, 1024.0] + > + + iex> s = [2, 4, 6] |> Explorer.Series.from_list() + iex> Explorer.Series.pow(s, 3) + #Explorer.Series< + Polars[3] + s64 [8, 64, 216] + > + + iex> s = [2, 4, 6] |> Explorer.Series.from_list() + iex> Explorer.Series.pow(s, -3.0) + #Explorer.Series< + Polars[3] + f64 [0.125, 0.015625, 0.004629629629629629] + > + + iex> s = [1.0, 2.0, 3.0] |> Explorer.Series.from_list() + iex> Explorer.Series.pow(s, 3.0) + #Explorer.Series< + Polars[3] + f64 [1.0, 8.0, 27.0] + > + + iex> s = [2.0, 4.0, 6.0] |> Explorer.Series.from_list() + iex> Explorer.Series.pow(s, 2) + #Explorer.Series< + Polars[3] + f64 [4.0, 16.0, 36.0] + > + """ + @doc type: :element_wise + @spec pow(left :: Series.t() | number(), right :: Series.t() | number()) :: Series.t() + def pow(left, right) do + [left, right] = cast_for_arithmetic("pow/2", [left, right]) + + if out_dtype = cast_to_pow(dtype(left), dtype(right)) do + apply_series_list(:pow, [out_dtype, left, right]) + else + dtype_mismatch_error("pow/2", left, right) + end + end + + defp cast_to_pow({:u, l}, {:u, r}), do: {:u, max(l, r)} + defp cast_to_pow({:s, s}, {:u, u}), do: {:s, min(64, max(2 * u, s))} + defp cast_to_pow({:f, l}, {:f, r}), do: {:f, max(l, r)} + defp cast_to_pow({:f, l}, {n, _}) when K.in(n, [:u, :s]), do: {:f, l} + defp cast_to_pow({n, _}, {:f, r}) when K.in(n, [:u, :s]), do: {:f, r} + defp cast_to_pow({n, _}, {:s, _}) when K.in(n, [:u, :s]), do: {:s, 64} + # Due to a limitation in Polars, it's not possible to use decimals only here. + defp cast_to_pow({:decimal, _, _}, {:decimal, _, _}), do: {:f, 64} + defp cast_to_pow({:decimal, _, _}, {:s, _}), do: {:f, 64} + defp cast_to_pow(_, _), do: nil + + @doc """ + Calculates the natural logarithm. + + The resultant series is going to be of dtype `{:f, 64}`. + See `log/2` for passing a custom base. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:decimal` - returns f64 series. + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 3, nil, 4]) + iex> Explorer.Series.log(s) + #Explorer.Series< + Polars[5] + f64 [0.0, 0.6931471805599453, 1.0986122886681098, nil, 1.3862943611198906] + > + + """ + @doc type: :element_wise + @spec log(argument :: Series.t()) :: Series.t() + def log(%Series{} = s), do: apply_series(s, :log, []) + + @doc """ + Calculates the logarithm on a given base. + + The resultant series is going to be of dtype `{:f, 64}`. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:decimal`. + + ## Examples + + iex> s = Explorer.Series.from_list([8, 16, 32]) + iex> Explorer.Series.log(s, 2) + #Explorer.Series< + Polars[3] + f64 [3.0, 4.0, 5.0] + > + + """ + @doc type: :element_wise + @spec log(argument :: Series.t(), base :: number()) :: Series.t() + def log(%Series{dtype: dtype} = series, base) + when K.and(is_numeric_dtype(dtype), is_number(base)) do + if base <= 0, do: raise(ArgumentError, "base must be a positive number") + if base == 1, do: raise(ArgumentError, "base cannot be equal to 1") + + base = if is_integer(base), do: base / 1.0, else: base + apply_series(series, :log, [base]) + end + + @doc """ + Calculates the exponential of all elements. + """ + @doc type: :element_wise + @spec exp(Series.t()) :: Series.t() + def exp(%Series{} = series), do: apply_series(series, :exp, []) + + @doc """ + Element-wise integer division. + + At least one of the arguments must be a series. If both + sizes are series, the series must have the same size or + at last one of them must have size of 1. + + ## Supported dtype + + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + + Returns `nil` if there is a zero in the right-hand side. + + ## Examples + + iex> s1 = [10, 11, 10] |> Explorer.Series.from_list() + iex> s2 = [2, 2, 2] |> Explorer.Series.from_list() + iex> Explorer.Series.quotient(s1, s2) + #Explorer.Series< + Polars[3] + s64 [5, 5, 5] + > + + iex> s1 = [10, 11, 10] |> Explorer.Series.from_list() + iex> s2 = [2, 2, 0] |> Explorer.Series.from_list() + iex> Explorer.Series.quotient(s1, s2) + #Explorer.Series< + Polars[3] + s64 [5, 5, nil] + > + + iex> s1 = [10, 12, 15] |> Explorer.Series.from_list() + iex> Explorer.Series.quotient(s1, 3) + #Explorer.Series< + Polars[3] + s64 [3, 4, 5] + > + + """ + @doc type: :element_wise + @spec quotient(left :: Series.t(), right :: Series.t() | integer()) :: Series.t() + def quotient(%Series{dtype: l_dtype} = left, %Series{dtype: r_dtype} = right) + when K.and(K.in(l_dtype, @integer_types), K.in(r_dtype, @integer_types)), + do: apply_series_list(:quotient, [left, right]) + + def quotient(%Series{dtype: l_dtype} = left, right) + when K.and(K.in(l_dtype, @integer_types), is_integer(right)), + do: apply_series_list(:quotient, [left, from_list([right])]) + + def quotient(left, %Series{dtype: r_dtype} = right) + when K.and(K.in(r_dtype, @integer_types), is_integer(left)), + do: apply_series_list(:quotient, [from_list([left]), right]) + + @doc """ + Computes the remainder of an element-wise integer division. + + At least one of the arguments must be a series. If both + sizes are series, the series must have the same size or + at last one of them must have size of 1. + + ## Supported dtype + + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + + Returns `nil` if there is a zero in the right-hand side. + + ## Examples + + iex> s1 = [10, 11, 10] |> Explorer.Series.from_list() + iex> s2 = [2, 2, 2] |> Explorer.Series.from_list() + iex> Explorer.Series.remainder(s1, s2) + #Explorer.Series< + Polars[3] + s64 [0, 1, 0] + > + + iex> s1 = [10, 11, 10] |> Explorer.Series.from_list() + iex> s2 = [2, 2, 0] |> Explorer.Series.from_list() + iex> Explorer.Series.remainder(s1, s2) + #Explorer.Series< + Polars[3] + s64 [0, 1, nil] + > + + iex> s1 = [10, 11, 9] |> Explorer.Series.from_list() + iex> Explorer.Series.remainder(s1, 3) + #Explorer.Series< + Polars[3] + s64 [1, 2, 0] + > + + """ + @doc type: :element_wise + @spec remainder(left :: Series.t(), right :: Series.t() | integer()) :: Series.t() + def remainder(%Series{dtype: l_dtype} = left, %Series{dtype: r_dtype} = right) + when K.and(K.in(l_dtype, @integer_types), K.in(r_dtype, @integer_types)), + do: apply_series_list(:remainder, [left, right]) + + def remainder(%Series{dtype: l_dtype} = left, right) + when K.and(K.in(l_dtype, @integer_types), is_integer(right)), + do: apply_series_list(:remainder, [left, from_list([right])]) + + def remainder(left, %Series{dtype: r_dtype} = right) + when K.and(K.in(r_dtype, @integer_types), is_integer(left)), + do: apply_series_list(:remainder, [from_list([left]), right]) + + @doc """ + Computes the the sine of a number (in radians). + The resultant series is going to be of dtype `{:f, 64}`, with values between 1 and -1. + + ## Supported dtype + + * `{:f, 32}` + * `{:f, 64}` + + ## Examples + + iex> pi = :math.pi() + iex> s = [-pi * 3/2, -pi, -pi / 2, -pi / 4, 0, pi / 4, pi / 2, pi, pi * 3/2] |> Explorer.Series.from_list() + iex> Explorer.Series.sin(s) + #Explorer.Series< + Polars[9] + f64 [1.0, -1.2246467991473532e-16, -1.0, -0.7071067811865475, 0.0, 0.7071067811865475, 1.0, 1.2246467991473532e-16, -1.0] + > + """ + @doc type: :float_wise + @spec sin(series :: Series.t()) :: Series.t() + def sin(%Series{dtype: dtype} = series) when K.in(dtype, @float_dtypes), + do: apply_series(series, :sin) + + def sin(%Series{dtype: dtype}), + do: dtype_error("sin/1", dtype, [{:f, 32}, {:f, 64}]) + + @doc """ + Computes the the cosine of a number (in radians). + The resultant series is going to be of dtype `{:f, 64}`, with values between 1 and -1. + + ## Supported dtype + + * `{:f, 32}` + * `{:f, 64}` + + ## Examples + + iex> pi = :math.pi() + iex> s = [-pi * 3/2, -pi, -pi / 2, -pi / 4, 0, pi / 4, pi / 2, pi, pi * 3/2] |> Explorer.Series.from_list() + iex> Explorer.Series.cos(s) + #Explorer.Series< + Polars[9] + f64 [-1.8369701987210297e-16, -1.0, 6.123233995736766e-17, 0.7071067811865476, 1.0, 0.7071067811865476, 6.123233995736766e-17, -1.0, -1.8369701987210297e-16] + > + """ + @doc type: :float_wise + @spec cos(series :: Series.t()) :: Series.t() + def cos(%Series{dtype: dtype} = series) when K.in(dtype, @float_dtypes), + do: apply_series(series, :cos) + + def cos(%Series{dtype: dtype}), + do: dtype_error("cos/1", dtype, [{:f, 32}, {:f, 64}]) + + @doc """ + Computes the tangent of a number (in radians). + The resultant series is going to be of dtype `{:f, 64}`. + + ## Supported dtype + + * `{:f, 32}` + * `{:f, 64}` + + ## Examples + + iex> pi = :math.pi() + iex> s = [-pi * 3/2, -pi, -pi / 2, -pi / 4, 0, pi / 4, pi / 2, pi, pi * 3/2] |> Explorer.Series.from_list() + iex> Explorer.Series.tan(s) + #Explorer.Series< + Polars[9] + f64 [-5443746451065123.0, 1.2246467991473532e-16, -1.633123935319537e16, -0.9999999999999999, 0.0, 0.9999999999999999, 1.633123935319537e16, -1.2246467991473532e-16, 5443746451065123.0] + > + """ + @doc type: :float_wise + @spec tan(series :: Series.t()) :: Series.t() + def tan(%Series{dtype: dtype} = series) when K.in(dtype, @float_dtypes), + do: apply_series(series, :tan) + + def tan(%Series{dtype: dtype}), + do: dtype_error("tan/1", dtype, [{:f, 32}, {:f, 64}]) + + @doc """ + Computes the the arcsine of a number. + The resultant series is going to be of dtype `{:f, 64}`, in radians, with values between -pi/2 and pi/2. + + ## Supported dtype + + * `{:f, 32}` + * `{:f, 64}` + + ## Examples + + iex> s = [1.0, 0.0, -1.0, -0.7071067811865475, 0.7071067811865475] |> Explorer.Series.from_list() + iex> Explorer.Series.asin(s) + #Explorer.Series< + Polars[5] + f64 [1.5707963267948966, 0.0, -1.5707963267948966, -0.7853981633974482, 0.7853981633974482] + > + """ + @doc type: :float_wise + @spec asin(series :: Series.t()) :: Series.t() + def asin(%Series{dtype: dtype} = series) when K.in(dtype, @float_dtypes), + do: apply_series(series, :asin) + + def asin(%Series{dtype: dtype}), + do: dtype_error("asin/1", dtype, [{:f, 32}, {:f, 64}]) + + @doc """ + Computes the the arccosine of a number. + The resultant series is going to be of dtype `{:f, 64}`, in radians, with values between 0 and pi. + + ## Supported dtype + + * `{:f, 32}` + * `{:f, 64}` + + ## Examples + + iex> s = [1.0, 0.0, -1.0, -0.7071067811865475, 0.7071067811865475] |> Explorer.Series.from_list() + iex> Explorer.Series.acos(s) + #Explorer.Series< + Polars[5] + f64 [0.0, 1.5707963267948966, 3.141592653589793, 2.356194490192345, 0.7853981633974484] + > + """ + @doc type: :float_wise + @spec acos(series :: Series.t()) :: Series.t() + def acos(%Series{dtype: dtype} = series) when K.in(dtype, @float_dtypes), + do: apply_series(series, :acos) + + def acos(%Series{dtype: dtype}), + do: dtype_error("acos/1", dtype, [{:f, 32}, {:f, 64}]) + + @doc """ + Computes the the arctangent of a number. + The resultant series is going to be of dtype `{:f, 64}`, in radians, with values between -pi/2 and pi/2. + + ## Supported dtype + + * `{:f, 32}` + * `{:f, 64}` + + ## Examples + + iex> s = [1.0, 0.0, -1.0, -0.7071067811865475, 0.7071067811865475] |> Explorer.Series.from_list() + iex> Explorer.Series.atan(s) + #Explorer.Series< + Polars[5] + f64 [0.7853981633974483, 0.0, -0.7853981633974483, -0.6154797086703873, 0.6154797086703873] + > + """ + @doc type: :float_wise + @spec atan(series :: Series.t()) :: Series.t() + def atan(%Series{dtype: dtype} = series) when K.in(dtype, @float_dtypes), + do: apply_series(series, :atan) + + def atan(%Series{dtype: dtype}), + do: dtype_error("atan/1", dtype, [{:f, 32}, {:f, 64}]) + + defp basic_numeric_operation(operation, %Series{} = left, right, args) when is_numeric(right), + do: basic_numeric_operation(operation, left, from_same_value(left, right), args) + + defp basic_numeric_operation(operation, left, %Series{} = right, args) when is_numeric(left), + do: basic_numeric_operation(operation, from_same_value(right, left), right, args) + + defp basic_numeric_operation( + operation, + %Series{dtype: left_dtype} = left, + %Series{dtype: right_dtype} = right, + args + ) + when K.and(is_numeric_dtype(left_dtype), is_numeric_dtype(right_dtype)), + do: apply_series_list(operation, [left, right | args]) + + defp basic_numeric_operation(operation, %Series{} = left, %Series{} = right, args), + do: dtype_mismatch_error("#{operation}/#{length(args) + 2}", left, right) + + defp basic_numeric_operation(operation, _, %Series{dtype: dtype}, args), + do: dtype_error("#{operation}/#{length(args) + 2}", dtype, @numeric_dtypes) + + defp basic_numeric_operation(operation, %Series{dtype: dtype}, _, args), + do: dtype_error("#{operation}/#{length(args) + 2}", dtype, @numeric_dtypes) + + defp basic_numeric_operation(operation, left, right, args) + when K.and(is_numeric(left), is_numeric(right)), + do: no_series_error("#{operation}/#{length(args) + 2}", left, right) + + defp no_series_error(function, left, right) do + raise ArgumentError, + "#{function} expects a series as one of its arguments, " <> + "instead got two scalars: #{inspect(left)} and #{inspect(right)}" + end + + # Comparisons + + @doc """ + Returns boolean mask of `left == right`, element-wise. + + At least one of the arguments must be a series. If both + sizes are series, the series must have the same size or + at last one of them must have size of 1. + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> s2 = Explorer.Series.from_list([1, 2, 4]) + iex> Explorer.Series.equal(s1, s2) + #Explorer.Series< + Polars[3] + boolean [true, true, false] + > + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.equal(s, 1) + #Explorer.Series< + Polars[3] + boolean [true, false, false] + > + + iex> s = Explorer.Series.from_list([true, true, false]) + iex> Explorer.Series.equal(s, true) + #Explorer.Series< + Polars[3] + boolean [true, true, false] + > + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.equal(s, "a") + #Explorer.Series< + Polars[3] + boolean [true, false, false] + > + + iex> s = Explorer.Series.from_list([~D[2021-01-01], ~D[1999-12-31]]) + iex> Explorer.Series.equal(s, ~D[1999-12-31]) + #Explorer.Series< + Polars[2] + boolean [false, true] + > + + iex> s = Explorer.Series.from_list([~N[2022-01-01 00:00:00], ~N[2022-01-01 23:00:00]]) + iex> Explorer.Series.equal(s, ~N[2022-01-01 00:00:00]) + #Explorer.Series< + Polars[2] + boolean [true, false] + > + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.equal(s, false) + ** (ArgumentError) cannot invoke Explorer.Series.equal/2 with mismatched dtypes: :string and false + """ + @doc type: :element_wise + @spec equal( + left :: Series.t() | number() | Date.t() | NaiveDateTime.t() | boolean() | String.t(), + right :: Series.t() | number() | Date.t() | NaiveDateTime.t() | boolean() | String.t() + ) :: Series.t() + def equal(left, right) do + if args = cast_for_comparable_operation(left, right) do + apply_series_list(:equal, args) + else + dtype_mismatch_error("equal/2", left, right) + end + end + + @doc """ + Returns boolean mask of `left != right`, element-wise. + + At least one of the arguments must be a series. If both + sizes are series, the series must have the same size or + at last one of them must have size of 1. + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> s2 = Explorer.Series.from_list([1, 2, 4]) + iex> Explorer.Series.not_equal(s1, s2) + #Explorer.Series< + Polars[3] + boolean [false, false, true] + > + + iex> s = Explorer.Series.from_list([1, 2, 3]) + iex> Explorer.Series.not_equal(s, 1) + #Explorer.Series< + Polars[3] + boolean [false, true, true] + > + + iex> s = Explorer.Series.from_list([true, true, false]) + iex> Explorer.Series.not_equal(s, true) + #Explorer.Series< + Polars[3] + boolean [false, false, true] + > + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.not_equal(s, "a") + #Explorer.Series< + Polars[3] + boolean [false, true, true] + > + + iex> s = Explorer.Series.from_list([~D[2021-01-01], ~D[1999-12-31]]) + iex> Explorer.Series.not_equal(s, ~D[1999-12-31]) + #Explorer.Series< + Polars[2] + boolean [true, false] + > + + iex> s = Explorer.Series.from_list([~N[2022-01-01 00:00:00], ~N[2022-01-01 23:00:00]]) + iex> Explorer.Series.not_equal(s, ~N[2022-01-01 00:00:00]) + #Explorer.Series< + Polars[2] + boolean [false, true] + > + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.not_equal(s, false) + ** (ArgumentError) cannot invoke Explorer.Series.not_equal/2 with mismatched dtypes: :string and false + """ + @doc type: :element_wise + @spec not_equal( + left :: Series.t() | number() | Date.t() | NaiveDateTime.t() | boolean() | String.t(), + right :: Series.t() | number() | Date.t() | NaiveDateTime.t() | boolean() | String.t() + ) :: Series.t() + def not_equal(left, right) do + if args = cast_for_comparable_operation(left, right) do + apply_series_list(:not_equal, args) + else + dtype_mismatch_error("not_equal/2", left, right) + end + end + + @doc """ + Returns boolean mask of `left > right`, element-wise. + + At least one of the arguments must be a series. If both + sizes are series, the series must have the same size or + at last one of them must have size of 1. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:date` + * `:time` + * `:datetime` + * `:duration` + * `:decimal` + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> s2 = Explorer.Series.from_list([1, 2, 4]) + iex> Explorer.Series.greater(s1, s2) + #Explorer.Series< + Polars[3] + boolean [false, false, false] + > + """ + @doc type: :element_wise + @spec greater( + left :: Series.t() | number() | Date.t() | NaiveDateTime.t(), + right :: Series.t() | number() | Date.t() | NaiveDateTime.t() + ) :: Series.t() + def greater(left, right) do + if args = cast_for_ordered_operation(left, right) do + apply_series_list(:greater, args) + else + dtype_mismatch_error("greater/2", left, right, @numeric_or_temporal_dtypes) + end + end + + @doc """ + Returns boolean mask of `left >= right`, element-wise. + + At least one of the arguments must be a series. If both + sizes are series, the series must have the same size or + at last one of them must have size of 1. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:date` + * `:time` + * `:datetime` + * `:duration` + * `:decimal` + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> s2 = Explorer.Series.from_list([1, 2, 4]) + iex> Explorer.Series.greater_equal(s1, s2) + #Explorer.Series< + Polars[3] + boolean [true, true, false] + > + """ + @doc type: :element_wise + @spec greater_equal( + left :: Series.t() | number() | Date.t() | NaiveDateTime.t(), + right :: Series.t() | number() | Date.t() | NaiveDateTime.t() + ) :: Series.t() + def greater_equal(left, right) do + if args = cast_for_ordered_operation(left, right) do + apply_series_list(:greater_equal, args) + else + dtype_mismatch_error("greater_equal/2", left, right, @numeric_or_temporal_dtypes) + end + end + + @doc """ + Returns boolean mask of `left < right`, element-wise. + + At least one of the arguments must be a series. If both + sizes are series, the series must have the same size or + at last one of them must have size of 1. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:date` + * `:time` + * `:datetime` + * `:duration` + * `:decimal` + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> s2 = Explorer.Series.from_list([1, 2, 4]) + iex> Explorer.Series.less(s1, s2) + #Explorer.Series< + Polars[3] + boolean [false, false, true] + > + """ + @doc type: :element_wise + @spec less( + left :: Series.t() | number() | Date.t() | NaiveDateTime.t(), + right :: Series.t() | number() | Date.t() | NaiveDateTime.t() + ) :: Series.t() + def less(left, right) do + if args = cast_for_ordered_operation(left, right) do + apply_series_list(:less, args) + else + dtype_mismatch_error("less/2", left, right, @numeric_or_temporal_dtypes) + end + end + + @doc """ + Returns boolean mask of `left <= right`, element-wise. + + At least one of the arguments must be a series. If both + sizes are series, the series must have the same size or + at last one of them must have size of 1. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:date` + * `:time` + * `:datetime` + * `:duration` + * `:decimal` + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> s2 = Explorer.Series.from_list([1, 2, 4]) + iex> Explorer.Series.less_equal(s1, s2) + #Explorer.Series< + Polars[3] + boolean [true, true, true] + > + """ + @doc type: :element_wise + @spec less_equal( + left :: Series.t() | number() | Date.t() | NaiveDateTime.t(), + right :: Series.t() | number() | Date.t() | NaiveDateTime.t() + ) :: Series.t() + def less_equal(left, right) do + if args = cast_for_ordered_operation(left, right) do + apply_series_list(:less_equal, args) + else + dtype_mismatch_error("less_equal/2", left, right, @numeric_or_temporal_dtypes) + end + end + + @doc """ + Checks if each element of the series in the left exists in the series + on the right, returning a boolean mask. + + The series sizes do not have to match. + + See `member?/2` if you want to check if a literal belongs to a list. + + ## Examples + + iex> left = Explorer.Series.from_list([1, 2, 3]) + iex> right = Explorer.Series.from_list([1, 2]) + iex> Series.in(left, right) + #Explorer.Series< + Polars[3] + boolean [true, true, false] + > + + iex> left = Explorer.Series.from_list([~D[1970-01-01], ~D[2000-01-01], ~D[2010-04-17]]) + iex> right = Explorer.Series.from_list([~D[1970-01-01], ~D[2010-04-17]]) + iex> Series.in(left, right) + #Explorer.Series< + Polars[3] + boolean [true, false, true] + > + """ + @doc type: :element_wise + def (%Series{} = left) in (%Series{} = right) do + if args = cast_for_comparable_operation(left, right) do + apply_series_list(:binary_in, args) + else + dtype_mismatch_error("in/2", left, right) + end + end + + def (%Series{data: %backend{}} = left) in right when is_list(right), + do: left in backend.from_list(right, Shared.dtype_from_list!(right)) + + ## Comparable (a superset of ordered) + + defp cast_for_comparable_operation( + %Series{dtype: left_dtype} = left, + %Series{dtype: right_dtype} = right + ) do + if valid_comparable_series?(left_dtype, right_dtype) do + [left, right] + else + nil + end + end + + defp cast_for_comparable_operation(%Series{dtype: dtype} = series, value) do + if dtype = cast_to_comparable_series(dtype, value) do + [series, from_same_value(series, value, dtype)] + else + nil + end + end + + defp cast_for_comparable_operation(value, %Series{dtype: dtype} = series) do + if dtype = cast_to_comparable_series(dtype, value) do + [from_same_value(series, value, dtype), series] + else + nil + end + end + + defp cast_for_comparable_operation(_left, _right), + do: nil + + defp valid_comparable_series?(:category, :string), do: true + defp valid_comparable_series?(:string, :category), do: true + + defp valid_comparable_series?(left_dtype, right_dtype), + do: valid_ordered_series?(left_dtype, right_dtype) + + defp cast_to_comparable_series(:category, value) when is_binary(value), do: :string + defp cast_to_comparable_series(:string, value) when is_binary(value), do: :string + defp cast_to_comparable_series(:binary, value) when is_binary(value), do: :binary + defp cast_to_comparable_series(:boolean, value) when is_boolean(value), do: :boolean + defp cast_to_comparable_series(dtype, value), do: cast_to_ordered_series(dtype, value) + + ## Ordered + + defp cast_for_ordered_operation( + %Series{dtype: left_dtype} = left, + %Series{dtype: right_dtype} = right + ) do + if valid_ordered_series?(left_dtype, right_dtype) do + [left, right] + else + nil + end + end + + defp cast_for_ordered_operation(%Series{dtype: dtype} = series, value) do + if dtype = cast_to_ordered_series(dtype, value) do + [series, from_same_value(series, value, dtype)] + else + nil + end + end + + defp cast_for_ordered_operation(value, %Series{dtype: dtype} = series) do + if dtype = cast_to_ordered_series(dtype, value) do + [from_same_value(series, value, dtype), series] + else + nil + end + end + + defp cast_for_ordered_operation(_left, _right), + do: nil + + defp valid_ordered_series?(dtype, dtype), + do: true + + defp valid_ordered_series?(left_dtype, right_dtype) + when K.and(is_numeric_dtype(left_dtype), is_numeric_dtype(right_dtype)), + do: true + + defp valid_ordered_series?(_, _), + do: false + + defp cast_to_ordered_series(dtype, value) + when K.and(is_numeric_dtype(dtype), is_integer(value)), + do: {:s, 64} + + defp cast_to_ordered_series(dtype, value) + when K.and(is_numeric_dtype(dtype), is_numeric(value)), + do: {:f, 64} + + defp cast_to_ordered_series(:date, %Date{}), do: :date + defp cast_to_ordered_series(:time, %Time{}), do: :time + + defp cast_to_ordered_series({:naive_datetime, _}, %NaiveDateTime{}), + do: {:naive_datetime, :microsecond} + + defp cast_to_ordered_series({:duration, _}, value) + when is_integer(value), + do: {:s, 64} + + defp cast_to_ordered_series({:duration, _}, %Explorer.Duration{}), + do: :duration + + defp cast_to_ordered_series({:decimal, _precision, _scale} = decimal, %Decimal{}), do: decimal + + defp cast_to_ordered_series(_dtype, _value), + do: nil + + @doc """ + Returns a boolean mask of `left and right`, element-wise. + + Both sizes must be series, the series must have the same + size or at last one of them must have size of 1. + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> mask1 = Explorer.Series.greater(s1, 1) + iex> mask2 = Explorer.Series.less(s1, 3) + iex> Explorer.Series.and(mask1, mask2) + #Explorer.Series< + Polars[3] + boolean [false, true, false] + > + + """ + @doc type: :element_wise + def (%Series{dtype: :boolean} = left) and (%Series{dtype: :boolean} = right), + do: apply_series_list(:binary_and, [left, right]) + + def (%Series{} = left) and (%Series{} = right), + do: dtype_mismatch_error("and/2", left, right, [:boolean]) + + @doc """ + Returns a boolean mask of `left or right`, element-wise. + + Both sizes must be series, the series must have the same + size or at last one of them must have size of 1. + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, 3]) + iex> mask1 = Explorer.Series.less(s1, 2) + iex> mask2 = Explorer.Series.greater(s1, 2) + iex> Explorer.Series.or(mask1, mask2) + #Explorer.Series< + Polars[3] + boolean [true, false, true] + > + + """ + @doc type: :element_wise + def (%Series{dtype: :boolean} = left) or (%Series{dtype: :boolean} = right), + do: apply_series_list(:binary_or, [left, right]) + + def (%Series{} = left) or (%Series{} = right), + do: dtype_mismatch_error("or/2", left, right, [:boolean]) + + @doc """ + Checks equality between two entire series. + + ## Examples + + iex> s1 = Explorer.Series.from_list(["a", "b"]) + iex> s2 = Explorer.Series.from_list(["a", "b"]) + iex> Explorer.Series.all_equal(s1, s2) + true + + iex> s1 = Explorer.Series.from_list(["a", "b"]) + iex> s2 = Explorer.Series.from_list(["a", "c"]) + iex> Explorer.Series.all_equal(s1, s2) + false + + iex> s1 = Explorer.Series.from_list(["a", "b"]) + iex> s2 = Explorer.Series.from_list([1, 2]) + iex> Explorer.Series.all_equal(s1, s2) + false + """ + @doc type: :element_wise + def all_equal(%Series{dtype: dtype} = left, %Series{dtype: dtype} = right), + do: apply_series_list(:all_equal, [left, right]) + + def all_equal(%Series{dtype: left_dtype}, %Series{dtype: right_dtype}) + when left_dtype != + right_dtype, + do: false + + @doc """ + Negate the elements of a boolean series. + + ## Examples + + iex> s1 = Explorer.Series.from_list([true, false, false]) + iex> Explorer.Series.not(s1) + #Explorer.Series< + Polars[3] + boolean [false, true, true] + > + + """ + @doc type: :element_wise + def not (%Series{dtype: :boolean} = series), do: apply_series(series, :unary_not, []) + def not %Series{dtype: dtype}, do: dtype_error("not/1", dtype, [:boolean]) + + # Sort + + @doc """ + Sorts the series. + + See `sort_by/3` for an expression-based sorting function. + See `sort_with/3` for a callback-based sorting function. + + ## Options + + * `:direction` - `:asc` or `:desc`, meaning "ascending" or "descending", respectively. + By default it sorts in ascending order. + + * `:nils` - `:first` or `:last`. + By default it is `:last` if direction is `:asc`, and `:first` otherwise. + + * `:parallel` - boolean. + Whether to parallelize the sorting. + By default it is `true`. + + * `:stable` - boolean. + Determines if the sorting is stable (ties are guaranteed to maintain their order) or not. + Unstable sorting may be more performant. + By default it is `false`. + + ## Examples + + iex> s = Explorer.Series.from_list([9, 3, 7, 1]) + iex> Explorer.Series.sort(s) + #Explorer.Series< + Polars[4] + s64 [1, 3, 7, 9] + > + + iex> s = Explorer.Series.from_list([9, 3, 7, 1]) + iex> Explorer.Series.sort(s, direction: :desc) + #Explorer.Series< + Polars[4] + s64 [9, 7, 3, 1] + > + + """ + @doc type: :shape + def sort(series, opts \\ []) do + apply_series(series, :sort, Shared.validate_sort_options!(opts)) + end + + @doc """ + Returns the indices that would sort the series. + + The resultant series is going to have the `{:u, 32}` dtype. + + ## Options + + * `:direction` - `:asc` or `:desc`, meaning "ascending" or "descending", respectively. + By default it sorts in ascending order. + + * `:nils` - `:first` or `:last`. + By default it is `:last` if direction is `:asc`, and `:first` otherwise. + + * `:parallel` - boolean. + Whether to parallelize the sorting. + By default it is `true`. + + * `:stable` - boolean. + Determines if the sorting is stable (ties are guaranteed to maintain their order) or not. + Unstable sorting may be more performant. + By default it is `false`. + + ## Examples + + iex> s = Explorer.Series.from_list([9, 3, 7, 1]) + iex> Explorer.Series.argsort(s) + #Explorer.Series< + Polars[4] + u32 [3, 1, 2, 0] + > + + iex> s = Explorer.Series.from_list([9, 3, 7, 1]) + iex> Explorer.Series.argsort(s, direction: :desc) + #Explorer.Series< + Polars[4] + u32 [0, 2, 1, 3] + > + + """ + @doc type: :shape + def argsort(series, opts \\ []) do + apply_series(series, :argsort, Shared.validate_sort_options!(opts)) + end + + @doc """ + Reverses the series order. + + ## Example + + iex> s = [1, 2, 3] |> Explorer.Series.from_list() + iex> Explorer.Series.reverse(s) + #Explorer.Series< + Polars[3] + s64 [3, 2, 1] + > + """ + @doc type: :shape + def reverse(series), do: apply_series(series, :reverse) + + # Distinct + + @doc """ + Returns the unique values of the series. + + ## Examples + + iex> s = [1, 1, 2, 2, 3, 3] |> Explorer.Series.from_list() + iex> Explorer.Series.distinct(s) + #Explorer.Series< + Polars[3] + s64 [1, 2, 3] + > + """ + @doc type: :shape + def distinct(series), do: apply_series(series, :distinct) + + @doc """ + Returns the unique values of the series, but does not maintain order. + + Faster than `distinct/1`. + + ## Examples + + iex> s = [1, 1, 2, 2, 3, 3] |> Explorer.Series.from_list() + iex> Explorer.Series.unordered_distinct(s) + """ + @doc type: :shape + def unordered_distinct(series), do: apply_series(series, :unordered_distinct) + + @doc """ + Returns the number of unique values in the series. + + ## Examples + + iex> s = Explorer.Series.from_list(["a", "b", "a", "b"]) + iex> Explorer.Series.n_distinct(s) + 2 + """ + @doc type: :aggregation + def n_distinct(series), do: apply_series(series, :n_distinct) + + @doc """ + Creates a new dataframe with unique values and the frequencies of each. + + ## Examples + + iex> s = Explorer.Series.from_list(["a", "a", "b", "c", "c", "c"]) + iex> Explorer.Series.frequencies(s) + #Explorer.DataFrame< + Polars[3 x 2] + values string ["c", "a", "b"] + counts u32 [3, 2, 1] + > + """ + @doc type: :aggregation + def frequencies(series), do: apply_series(series, :frequencies) + + @doc """ + Bins values into discrete values. + + Given a `bins` length of N, there will be N+1 categories. + + ## Options + + * `:labels` - The labels assigned to the bins. Given `bins` of + length N, `:labels` must be of length N+1. Defaults to the bin + bounds (e.g. `(-inf -1.0]`, `(-1.0, 1.0]`, `(1.0, inf]`) + + * `:break_point_label` - The name given to the breakpoint column. + This is only relevant if `:include_breaks` is `true`. + Defaults to `break_point`. + + * `:category_label` - The name given to the category column. + Defaults to `category`. + + * `:left_closed` - Set the intervals to be left-closed instead + of right-closed. Defaults to `false`. + + * `:include_breaks` - Include a column with the right endpoint + of the bin that each observation falls in. + Defaults to `false`. + + ## Examples + + iex> s = Explorer.Series.from_list([1.0, 2.0, 3.0]) + iex> Explorer.Series.cut(s, [1.5, 2.5], include_breaks: true) + #Explorer.DataFrame< + Polars[3 x 3] + values f64 [1.0, 2.0, 3.0] + break_point f64 [1.5, 2.5, Inf] + category category ["(-inf, 1.5]", "(1.5, 2.5]", "(2.5, inf]"] + > + + iex> s = Explorer.Series.from_list([1.0, 2.0, 3.0]) + iex> Explorer.Series.cut(s, [1.5, 2.5]) + #Explorer.DataFrame< + Polars[3 x 2] + values f64 [1.0, 2.0, 3.0] + category category ["(-inf, 1.5]", "(1.5, 2.5]", "(2.5, inf]"] + > + """ + @doc type: :aggregation + def cut(series, bins, opts \\ []) do + opts = + Keyword.validate!(opts, + labels: nil, + break_point_label: nil, + category_label: nil, + left_close: false, + include_breaks: false + ) + + apply_series(series, :cut, [ + Enum.map(bins, &(&1 / 1.0)), + opts[:labels], + opts[:break_point_label], + opts[:category_label], + opts[:left_close], + opts[:include_breaks] + ]) + end + + @doc """ + Bins values into discrete values base on their quantiles. + + Given a `quantiles` length of N, there will be N+1 categories. Each + element of `quantiles` is expected to be between 0.0 and 1.0. + + ## Options + + * `:labels` - The labels assigned to the bins. Given `bins` of + length N, `:labels` must be of length N+1. Defaults to the bin + bounds (e.g. `(-inf -1.0]`, `(-1.0, 1.0]`, `(1.0, inf]`) + + * `:break_point_label` - The name given to the breakpoint column. + This is only relevant if `:include_breaks` is `true`. + Defaults to `break_point`. + + * `:category_label` - The name given to the category column. + Defaults to `category`. + + * `:allow_duplicates` - If quantiles can have duplicated values. + Defaults to `false`. + + * `:left_closed` - Set the intervals to be left-closed instead + of right-closed. Defaults to `false`. + + * `:include_breaks` - Include a column with the right endpoint + of the bin that each observation falls in. + Defaults to `false`. + + ## Examples + + iex> s = Explorer.Series.from_list([1.0, 2.0, 3.0, 4.0, 5.0]) + iex> Explorer.Series.qcut(s, [0.25, 0.75]) + #Explorer.DataFrame< + Polars[5 x 2] + values f64 [1.0, 2.0, 3.0, 4.0, 5.0] + category category ["(-inf, 2]", "(-inf, 2]", "(2, 4]", "(2, 4]", "(4, inf]"] + > + """ + @doc type: :aggregation + def qcut(series, quantiles, opts \\ []) do + opts = + Keyword.validate!(opts, + labels: nil, + break_point_label: nil, + category_label: nil, + allow_duplicates: false, + left_close: false, + include_breaks: false + ) + + apply_series(series, :qcut, [ + Enum.map(quantiles, &(&1 / 1.0)), + opts[:labels], + opts[:break_point_label], + opts[:category_label], + opts[:allow_duplicates], + opts[:left_close], + opts[:include_breaks] + ]) + end + + @doc """ + Counts the number of non-`nil` elements in a series. + + See also: + + * `count_nil/1` - counts only the `nil` elements. + * `size/1` - counts all elements. + + ## Examples + + Without `nil`: + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.count(s) + 3 + + With `nil`: + + iex> s = Explorer.Series.from_list(["a", nil, "c"]) + iex> Explorer.Series.count(s) + 2 + + With `:nan` (`:nan` does not count as `nil`): + + iex> s = Explorer.Series.from_list([1, :nan, 3]) + iex> Explorer.Series.count(s) + 3 + """ + @doc type: :aggregation + def count(series), do: apply_series(series, :count) + + @doc """ + Counts the number of `nil` elements in a series. + + When used in a query on grouped data, `count_nil/1` is a per-group operation. + + See also: + + * `count/1` - counts only the non-`nil` elements. + * `size/1` - counts all elements. + + ## Examples + + Without `nil`s: + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.nil_count(s) + 0 + + With `nil`s: + + iex> s = Explorer.Series.from_list(["a", nil, "c"]) + iex> Explorer.Series.nil_count(s) + 1 + + With `:nan`s (`:nan` does not count as `nil`): + + iex> s = Explorer.Series.from_list([1, :nan, 3]) + iex> Explorer.Series.nil_count(s) + 0 + """ + @doc type: :aggregation + def nil_count(series), do: apply_series(series, :nil_count) + + # Window + + @doc """ + Calculate the rolling sum, given a window size and optional list of weights. + + ## Options + + * `:weights` - An optional list of weights with the same length as the window + that will be multiplied elementwise with the values in the window. Defaults to `nil`. + + * `:min_periods` - The number of values in the window that should be non-nil + before computing a result. If `nil`, it will be set equal to window size. Defaults to `1`. + + * `:center` - Set the labels at the center of the window. Defaults to `false`. + + ## Examples + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.window_sum(s, 4) + #Explorer.Series< + Polars[10] + s64 [1, 3, 6, 10, 14, 18, 22, 26, 30, 34] + > + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.window_sum(s, 2, weights: [1.0, 2.0]) + #Explorer.Series< + Polars[10] + f64 [1.0, 5.0, 8.0, 11.0, 14.0, 17.0, 20.0, 23.0, 26.0, 29.0] + > + """ + @doc type: :window + def window_sum(series, window_size, opts \\ []), + do: apply_series(series, :window_sum, [window_size | window_args(opts)]) + + @doc """ + Calculate the rolling mean, given a window size and optional list of weights. + + ## Options + + * `:weights` - An optional list of weights with the same length as the window + that will be multiplied elementwise with the values in the window. Defaults to `nil`. + + * `:min_periods` - The number of values in the window that should be non-nil + before computing a result. If `nil`, it will be set equal to window size. Defaults to `1`. + + * `:center` - Set the labels at the center of the window. Defaults to `false`. + + ## Examples + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.window_mean(s, 4) + #Explorer.Series< + Polars[10] + f64 [1.0, 1.5, 2.0, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5] + > + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.window_mean(s, 2, weights: [0.25, 0.75]) + #Explorer.Series< + Polars[10] + f64 [0.25, 1.75, 2.75, 3.75, 4.75, 5.75, 6.75, 7.75, 8.75, 9.75] + > + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.window_mean(s, 2, weights: [0.25, 0.75], min_periods: nil) + #Explorer.Series< + Polars[10] + f64 [nil, 1.75, 2.75, 3.75, 4.75, 5.75, 6.75, 7.75, 8.75, 9.75] + > + """ + @doc type: :window + def window_mean(series, window_size, opts \\ []), + do: apply_series(series, :window_mean, [window_size | window_args(opts)]) + + @doc """ + Calculate the rolling median, given a window size and optional list of weights. + + ## Options + + * `:weights` - An optional list of weights with the same length as the window + that will be multiplied elementwise with the values in the window. Defaults to `nil`. + + * `:min_periods` - The number of values in the window that should be non-nil + before computing a result. If `nil`, it will be set equal to window size. Defaults to `1`. + + * `:center` - Set the labels at the center of the window. Defaults to `false`. + + ## Examples + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.window_median(s, 4) + #Explorer.Series< + Polars[10] + f64 [1.0, 1.5, 2.0, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5] + > + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.window_median(s, 2, weights: [0.25, 0.75]) + #Explorer.Series< + Polars[10] + f64 [1.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5] + > + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.window_median(s, 2, weights: [0.25, 0.75], min_periods: nil) + #Explorer.Series< + Polars[10] + f64 [nil, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5] + > + """ + @doc type: :window + def window_median(series, window_size, opts \\ []), + do: apply_series(series, :window_median, [window_size | window_args(opts)]) + + @doc """ + Calculate the rolling min, given a window size and optional list of weights. + + ## Options + + * `:weights` - An optional list of weights with the same length as the window + that will be multiplied elementwise with the values in the window. Defaults to `nil`. + + * `:min_periods` - The number of values in the window that should be non-nil + before computing a result. If `nil`, it will be set equal to window size. Defaults to `1`. + + * `:center` - Set the labels at the center of the window. Defaults to `false`. + + ## Examples + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.window_min(s, 4) + #Explorer.Series< + Polars[10] + s64 [1, 1, 1, 1, 2, 3, 4, 5, 6, 7] + > + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.window_min(s, 2, weights: [1.0, 2.0]) + #Explorer.Series< + Polars[10] + f64 [1.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] + > + """ + @doc type: :window + def window_min(series, window_size, opts \\ []), + do: apply_series(series, :window_min, [window_size | window_args(opts)]) + + @doc """ + Calculate the rolling max, given a window size and optional list of weights. + + ## Options + + * `:weights` - An optional list of weights with the same length as the window + that will be multiplied elementwise with the values in the window. Defaults to `nil`. + + * `:min_periods` - The number of values in the window that should be non-nil + before computing a result. If `nil`, it will be set equal to window size. Defaults to `1`. + + * `:center` - Set the labels at the center of the window. Defaults to `false`. + + ## Examples + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.window_max(s, 4) + #Explorer.Series< + Polars[10] + s64 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + > + + iex> s = 1..10 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.window_max(s, 2, weights: [1.0, 2.0]) + #Explorer.Series< + Polars[10] + f64 [1.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0] + > + """ + @doc type: :window + def window_max(series, window_size, opts \\ []), + do: apply_series(series, :window_max, [window_size | window_args(opts)]) + + @doc """ + Calculate the rolling standard deviation, given a window size and optional list of weights. + + ## Options + + * `:weights` - An optional list of weights with the same length as the window + that will be multiplied elementwise with the values in the window. Defaults to `nil`. + + * `:min_periods` - The number of values in the window that should be non-nil + before computing a result. If `nil`, it will be set equal to window size. Defaults to `1`. + + * `:center` - Set the labels at the center of the window. Defaults to `false`. + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 3, 4, 1]) + iex> Explorer.Series.window_standard_deviation(s, 2) + #Explorer.Series< + Polars[5] + f64 [nil, 0.7071067811865476, 0.7071067811865476, 0.7071067811865476, 2.1213203435596424] + > + + iex> s = Explorer.Series.from_list([1, 2, 3, 4, 5, 6]) + iex> Explorer.Series.window_standard_deviation(s, 2, weights: [0.25, 0.75]) + #Explorer.Series< + Polars[6] + f64 [0.4330127018922193, 0.4330127018922193, 0.4330127018922193, 0.4330127018922193, 0.4330127018922193, 0.4330127018922193] + > + """ + @doc type: :window + def window_standard_deviation(series, window_size, opts \\ []) do + apply_series(series, :window_standard_deviation, [window_size | window_args(opts)]) + end + + defp window_args(opts) do + opts = Keyword.validate!(opts, weights: nil, min_periods: 1, center: false) + [opts[:weights], opts[:min_periods], opts[:center]] + end + + @doc """ + Calculate the exponentially weighted moving average, given smoothing factor alpha. + + ## Options + + * `:alpha` - Optional smoothing factor which specifies the importance given + to most recent observations. It is a value such that, 0 < alpha <= 1. Defaults to 0.5. + + * `:adjust` - If set to true, it corrects the bias introduced by smoothing process. + Defaults to `true`. + + * `:min_periods` - The number of values in the window that should be non-nil + before computing a result. Defaults to `1`. + + * `:ignore_nils` - If set to true, it ignore nulls in the calculation. Defaults to `true`. + + ## Examples + + iex> s = 1..5 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.ewm_mean(s) + #Explorer.Series< + Polars[5] + f64 [1.0, 1.6666666666666667, 2.4285714285714284, 3.2666666666666666, 4.161290322580645] + > + + iex> s = 1..5 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.ewm_mean(s, alpha: 0.1) + #Explorer.Series< + Polars[5] + f64 [1.0, 1.5263157894736843, 2.070110701107011, 2.6312881651642916, 3.2097140484969833] + > + """ + @doc type: :window + def ewm_mean(series, opts \\ []) do + opts = Keyword.validate!(opts, alpha: 0.5, adjust: true, min_periods: 1, ignore_nils: true) + + apply_series(series, :ewm_mean, [ + opts[:alpha], + opts[:adjust], + opts[:min_periods], + opts[:ignore_nils] + ]) + end + + @doc """ + Calculate the exponentially weighted moving standard deviation, given smoothing factor alpha. + + ## Options + + * `:alpha` - Optional smoothing factor which specifies the importance given + to most recent observations. It is a value such that, 0 < alpha <= 1. Defaults to 0.5. + + * `:adjust` - If set to true, it corrects the bias introduced by smoothing process. + Defaults to `true`. + + * `:bias` - If set to false, it corrects the estimate to be statistically unbiased. + Defaults to `false`. + + * `:min_periods` - The number of values in the window that should be non-nil + before computing a result. Defaults to `1`. + + * `:ignore_nils` - If set to true, it ignore nulls in the calculation. Defaults to `true`. + + ## Examples + + iex> s = 1..5 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.ewm_standard_deviation(s) + #Explorer.Series< + Polars[5] + f64 [0.0, 0.7071067811865476, 0.9636241116594314, 1.1771636613972951, 1.3452425132127066] + > + + iex> s = 1..5 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.ewm_standard_deviation(s, alpha: 0.1) + #Explorer.Series< + Polars[5] + f64 [0.0, 0.7071067811865476, 0.9990770648702808, 1.2879021599718157, 1.5741638698820746] + > + """ + @doc type: :window + def ewm_standard_deviation(series, opts \\ []) do + opts = + Keyword.validate!(opts, + alpha: 0.5, + adjust: true, + bias: false, + min_periods: 1, + ignore_nils: true + ) + + apply_series(series, :ewm_standard_deviation, [ + opts[:alpha], + opts[:adjust], + opts[:bias], + opts[:min_periods], + opts[:ignore_nils] + ]) + end + + @doc """ + Calculate the exponentially weighted moving variance, given smoothing factor alpha. + + ## Options + + * `:alpha` - Optional smoothing factor which specifies the importance given + to most recent observations. It is a value such that, 0 < alpha <= 1. Defaults to 0.5. + + * `:adjust` - If set to true, it corrects the bias introduced by smoothing process. + Defaults to `true`. + + * `:bias` - If set to false, it corrects the estimate to be statistically unbiased. + Defaults to `false`. + + * `:min_periods` - The number of values in the window that should be non-nil + before computing a result. Defaults to `1`. + + * `:ignore_nils` - If set to true, it ignore nulls in the calculation. Defaults to `true`. + + ## Examples + + iex> s = 1..5 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.ewm_variance(s) + #Explorer.Series< + Polars[5] + f64 [0.0, 0.5, 0.9285714285714284, 1.385714285714286, 1.8096774193548393] + > + + iex> s = 1..5 |> Enum.to_list() |> Explorer.Series.from_list() + iex> Explorer.Series.ewm_variance(s, alpha: 0.1) + #Explorer.Series< + Polars[5] + f64 [0.0, 0.5, 0.9981549815498153, 1.6586919736600685, 2.4779918892421087] + > + """ + @doc type: :window + def ewm_variance(series, opts \\ []) do + opts = + Keyword.validate!(opts, + alpha: 0.5, + adjust: true, + bias: false, + min_periods: 1, + ignore_nils: true + ) + + apply_series(series, :ewm_variance, [ + opts[:alpha], + opts[:adjust], + opts[:bias], + opts[:min_periods], + opts[:ignore_nils] + ]) + end + + # Missing values + + @doc """ + Fill missing values with the given strategy. If a scalar value is provided instead of a strategy + atom, `nil` will be replaced with that value. It must be of the same `dtype` as the series. + + ## Strategies + + * `:forward` - replace nil with the previous value + * `:backward` - replace nil with the next value + * `:max` - replace nil with the series maximum + * `:min` - replace nil with the series minimum + * `:mean` - replace nil with the series mean + * `:nan` (float only) - replace nil with `NaN` + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, nil, 4]) + iex> Explorer.Series.fill_missing(s, :forward) + #Explorer.Series< + Polars[4] + s64 [1, 2, 2, 4] + > + + iex> s = Explorer.Series.from_list([1, 2, nil, 4]) + iex> Explorer.Series.fill_missing(s, :backward) + #Explorer.Series< + Polars[4] + s64 [1, 2, 4, 4] + > + + iex> s = Explorer.Series.from_list([1, 2, nil, 4]) + iex> Explorer.Series.fill_missing(s, :max) + #Explorer.Series< + Polars[4] + s64 [1, 2, 4, 4] + > + + iex> s = Explorer.Series.from_list([1, 2, nil, 4]) + iex> Explorer.Series.fill_missing(s, :min) + #Explorer.Series< + Polars[4] + s64 [1, 2, 1, 4] + > + + iex> s = Explorer.Series.from_list([1, 2, nil, 4]) + iex> Explorer.Series.fill_missing(s, :mean) + #Explorer.Series< + Polars[4] + s64 [1, 2, 2, 4] + > + + Values that belong to the series itself can also be added as missing: + + iex> s = Explorer.Series.from_list([1, 2, nil, 4]) + iex> Explorer.Series.fill_missing(s, 3) + #Explorer.Series< + Polars[4] + s64 [1, 2, 3, 4] + > + + iex> s = Explorer.Series.from_list(["a", "b", nil, "d"]) + iex> Explorer.Series.fill_missing(s, "c") + #Explorer.Series< + Polars[4] + string ["a", "b", "c", "d"] + > + + Mismatched types will raise: + + iex> s = Explorer.Series.from_list([1, 2, nil, 4]) + iex> Explorer.Series.fill_missing(s, "foo") + ** (ArgumentError) cannot invoke Explorer.Series.fill_missing/2 with mismatched dtypes: {:s, 64} and "foo" + + Floats in particular accept missing values to be set to NaN, Inf, and -Inf: + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, 4.0]) + iex> Explorer.Series.fill_missing(s, :nan) + #Explorer.Series< + Polars[4] + f64 [1.0, 2.0, NaN, 4.0] + > + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, 4.0]) + iex> Explorer.Series.fill_missing(s, :infinity) + #Explorer.Series< + Polars[4] + f64 [1.0, 2.0, Inf, 4.0] + > + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, 4.0]) + iex> Explorer.Series.fill_missing(s, :neg_infinity) + #Explorer.Series< + Polars[4] + f64 [1.0, 2.0, -Inf, 4.0] + > + + """ + @doc type: :window + @spec fill_missing( + Series.t(), + :forward + | :backward + | :max + | :min + | :mean + | :nan + | :infinity + | :neg_infinity + | Explorer.Backend.Series.valid_types() + ) :: Series.t() + def fill_missing(%Series{} = series, value) + when K.in(value, [:nan, :infinity, :neg_infinity]) do + if K.not(K.in(series.dtype, [{:f, 32}, {:f, 64}])) do + raise ArgumentError, + "fill_missing with :#{value} values require a float series, got #{inspect(series.dtype)}" + end + + apply_series(series, :fill_missing_with_value, [value]) + end + + def fill_missing(%Series{} = series, strategy) + when K.in(strategy, [:forward, :backward, :min, :max, :mean]), + do: apply_series(series, :fill_missing_with_strategy, [strategy]) + + def fill_missing(%Series{dtype: dtype} = series, value) do + if cast_to_comparable_series(dtype, value) do + apply_series(series, :fill_missing_with_value, [value]) + else + dtype_mismatch_error("fill_missing/2", series, value) + end + end + + @doc """ + Returns a mask of nil values. + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, nil, 4]) + iex> Explorer.Series.is_nil(s) + #Explorer.Series< + Polars[4] + boolean [false, false, true, false] + > + """ + @doc type: :element_wise + @spec is_nil(Series.t()) :: Series.t() + def is_nil(series), do: apply_series(series, :is_nil) + + @doc """ + Returns a mask of not nil values. + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, nil, 4]) + iex> Explorer.Series.is_not_nil(s) + #Explorer.Series< + Polars[4] + boolean [true, true, false, true] + > + """ + @doc type: :element_wise + @spec is_not_nil(Series.t()) :: Series.t() + def is_not_nil(series), do: apply_series(series, :is_not_nil) + + @doc """ + Gets the series absolute values. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, -1, -3]) + iex> Explorer.Series.abs(s) + #Explorer.Series< + Polars[4] + s64 [1, 2, 1, 3] + > + + iex> s = Explorer.Series.from_list([1.0, 2.0, -1.0, -3.0]) + iex> Explorer.Series.abs(s) + #Explorer.Series< + Polars[4] + f64 [1.0, 2.0, 1.0, 3.0] + > + + iex> s = Explorer.Series.from_list([1.0, 2.0, nil, -3.0]) + iex> Explorer.Series.abs(s) + #Explorer.Series< + Polars[4] + f64 [1.0, 2.0, nil, 3.0] + > + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.abs(s) + ** (ArgumentError) Explorer.Series.abs/1 not implemented for dtype :string. Valid dtypes are {:f, 32}, {:f, 64}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :element_wise + @spec abs(series :: Series.t()) :: Series.t() + def abs(%Series{dtype: dtype} = series) when is_numeric_dtype(dtype), + do: apply_series(series, :abs) + + def abs(%Series{dtype: dtype}), + do: dtype_error("abs/1", dtype, @numeric_dtypes) + + # Strings + + @doc """ + Detects whether a string contains a substring. + + > ### Notice {: .warning} + > + > This function detects only literal strings. For regular expressions, see `re_contains/2`. + + ## Examples + + iex> s = Explorer.Series.from_list(["abc", "def", "bcd"]) + iex> Explorer.Series.contains(s, "bc") + #Explorer.Series< + Polars[3] + boolean [true, false, true] + > + """ + @doc type: :string_wise + @spec contains(Series.t(), String.t()) :: Series.t() + def contains(%Series{dtype: :string} = series, substring) + when K.is_binary(substring), + do: apply_series(series, :contains, [substring]) + + def contains(%Series{dtype: dtype}, _), do: dtype_error("contains/2", dtype, [:string]) + + @doc """ + Detects whether a string matches a pattern. + + > ### Notice {: .warning} + > + > This function matches against a regular expression. It does not expect an Elixir regex, + > but a escaped string and you can use the `~S` sigil for escaping it. Since each Explorer + > backend may have its own regular expression rules, you must consult their underlying + > engine. For the default backend (Polars), the rules are outlined in the Rust create named + > [`regex`](https://docs.rs/regex/latest/regex/). + > + > To match literal strings, you can use `contains/2`. + + ## Examples + + iex> s = Explorer.Series.from_list(["abc", "def", "bcd"]) + iex> Explorer.Series.re_contains(s, ~S/(a|e)/) + #Explorer.Series< + Polars[3] + boolean [true, true, false] + > + """ + @doc type: :string_wise + @spec re_contains(Series.t(), String.t()) :: Series.t() + def re_contains(%Series{dtype: :string} = series, pattern) + when K.is_binary(pattern), + do: apply_series(series, :re_contains, [pattern]) + + def re_contains(%Series{dtype: :string}, %Regex{}) do + raise ArgumentError, + "standard regexes cannot be used as pattern because it may be incompatible with the backend. " <> + "Please use the `~S` sigil or extract the source from the regex with `Regex.source/1`" + end + + def re_contains(%Series{dtype: dtype}, _), do: dtype_error("re_contains/2", dtype, [:string]) + + @doc """ + Converts all characters to uppercase. + + ## Examples + + iex> s = Explorer.Series.from_list(["abc", "def", "bcd"]) + iex> Explorer.Series.upcase(s) + #Explorer.Series< + Polars[3] + string ["ABC", "DEF", "BCD"] + > + """ + @doc type: :string_wise + @spec upcase(Series.t()) :: Series.t() + def upcase(%Series{dtype: :string} = series), + do: apply_series(series, :upcase) + + def upcase(%Series{dtype: dtype}), do: dtype_error("upcase/1", dtype, [:string]) + + @doc """ + Converts all characters to lowercase. + + ## Examples + + iex> s = Explorer.Series.from_list(["ABC", "DEF", "BCD"]) + iex> Explorer.Series.downcase(s) + #Explorer.Series< + Polars[3] + string ["abc", "def", "bcd"] + > + """ + @doc type: :string_wise + @spec downcase(Series.t()) :: Series.t() + def downcase(%Series{dtype: :string} = series), + do: apply_series(series, :downcase) + + def downcase(%Series{dtype: dtype}), do: dtype_error("downcase/1", dtype, [:string]) + + @doc """ + Replaces all occurences of a substring with replacement in string series. + + Both substring and replacement must be of type string. + + > ### Notice {: .warning} + > + > This function replaces only literal strings. For regular expressions, see `re_replace/3`. + + ## Examples + + iex> series = Explorer.Series.from_list(["1,200", "1,234,567", "asdf", nil]) + iex> Explorer.Series.replace(series, ",", "") + #Explorer.Series< + Polars[4] + string ["1200", "1234567", "asdf", nil] + > + """ + @doc type: :string_wise + @spec replace(Series.t(), binary(), binary()) :: Series.t() + def replace(%Series{dtype: :string} = series, substring, replacement) + when K.and(is_binary(substring), is_binary(replacement)), + do: apply_series(series, :replace, [substring, replacement]) + + def replace(%Series{dtype: :string}, _, _), + do: raise(ArgumentError, "substring and replacement in replace/3 need to be a string") + + def replace(%Series{dtype: dtype}, _, _), do: dtype_error("replace/3", dtype, [:string]) + + @doc """ + Replaces all occurences of a pattern with replacement in string series. + + Both pattern and replacement must be of type string. The replacement + can refer to groups captures by using the `${x}`, where `x` is a number starting from 1. + It can also refer to named groups using the same syntax. + + > ### Notice {: .warning} + > + > This function matches against a regular expression. It does not expect an Elixir regex, + > but a escaped string and you can use the `~S` sigil for escaping it. Since each Explorer + > backend may have its own regular expression rules, you must consult their underlying + > engine. For the default backend (Polars), the rules are outlined in the Rust create named + > [`regex`](https://docs.rs/regex/latest/regex/). + > + > To replace by literal strings, you can use `replace/3`. + + ## Examples + + iex> series = Explorer.Series.from_list(["1.200,45", "1.234.567,30", "asdf", nil]) + iex> Explorer.Series.re_replace(series, ~S/[,.]/, "") + #Explorer.Series< + Polars[4] + string ["120045", "123456730", "asdf", nil] + > + + iex> series = Explorer.Series.from_list(["hat", "hut"]) + iex> Explorer.Series.re_replace(series, ~S/h(.)t/, "b${1}d") + #Explorer.Series< + Polars[2] + string ["bad", "bud"] + > + + iex> series = Explorer.Series.from_list(["hat", "hut"]) + iex> Explorer.Series.re_replace(series, ~S/h(?.)t/, "b${vowel}d") + #Explorer.Series< + Polars[2] + string ["bad", "bud"] + > + + Apply case-insensitive string replacement using the `(?i)` flag - remember, from the `regex` Rust crate. + + iex> series = Explorer.Series.from_list(["Foggy", "Rainy", "Sunny"]) + iex> Explorer.Series.re_replace(series, ~S/(?i)foggy|rainy/, "Sunny") + #Explorer.Series< + Polars[3] + string ["Sunny", "Sunny", "Sunny"] + > + + With an Elixir regex it causes an error: + + iex> series = Explorer.Series.from_list(["hat", "hut"]) + iex> Explorer.Series.re_replace(series, ~r/h(.)t/, "b${1}d") + ** (ArgumentError) standard regexes cannot be used as pattern because it may be incompatible with the backend. Please use the `~S` sigil or extract the source from the regex with `Regex.source/1` + + """ + @doc type: :string_wise + @spec re_replace(Series.t(), binary(), binary()) :: Series.t() + def re_replace(%Series{dtype: :string} = series, pattern, replacement) + when K.and(is_binary(pattern), is_binary(replacement)), + do: apply_series(series, :re_replace, [pattern, replacement]) + + def re_replace(%Series{dtype: :string}, %Regex{}, _) do + raise ArgumentError, + "standard regexes cannot be used as pattern because it may be incompatible with the backend. " <> + "Please use the `~S` sigil or extract the source from the regex with `Regex.source/1`" + end + + def re_replace(%Series{dtype: :string}, _, _), + do: raise(ArgumentError, "pattern and replacement in re_replace/3 need to be a string") + + def re_replace(%Series{dtype: dtype}, _, _), do: dtype_error("re_replace/3", dtype, [:string]) + + @doc """ + Returns a string series where all leading and trailing Unicode whitespaces + have been removed. + + ## Examples + + iex> s = Explorer.Series.from_list([" abc", "def ", " bcd "]) + iex> Explorer.Series.strip(s) + #Explorer.Series< + Polars[3] + string ["abc", "def", "bcd"] + > + + """ + @doc type: :string_wise + @spec strip(Series.t()) :: Series.t() + def strip(%Series{dtype: :string} = series), + do: apply_series(series, :strip, [nil]) + + @doc """ + Returns a string series where all leading and trailing examples of the provided string + have been removed. + + Where multiple characters are provided, all combinations of this set of characters will be stripped + + ## Examples + + iex> s = Explorer.Series.from_list(["£123", "1.00£", "£1.00£"]) + iex> Explorer.Series.strip(s, "£") + #Explorer.Series< + Polars[3] + string ["123", "1.00", "1.00"] + > + + iex> s = Explorer.Series.from_list(["abc", "adefa", "bcda"]) + iex> Explorer.Series.strip(s, "ab") + #Explorer.Series< + Polars[3] + string ["c", "def", "cd"] + > + + """ + @doc type: :string_wise + @spec strip(Series.t(), String.t()) :: Series.t() + def strip(%Series{dtype: :string} = series, string) when is_binary(string), + do: apply_series(series, :strip, [string]) + + def strip(%Series{dtype: dtype}, _string), do: dtype_error("strip/2", dtype, [:string]) + + @doc """ + Returns a string series where all leading Unicode whitespaces have been removed. + + ## Examples + + iex> s = Explorer.Series.from_list([" abc", "def ", " bcd"]) + iex> Explorer.Series.lstrip(s) + #Explorer.Series< + Polars[3] + string ["abc", "def ", "bcd"] + > + """ + @doc type: :string_wise + @spec lstrip(Series.t()) :: Series.t() + def lstrip(%Series{dtype: :string} = series), + do: apply_series(series, :lstrip, [nil]) + + @doc """ + Returns a string series where all leading examples of the provided string + have been removed. + + Where multiple characters are provided, all combinations of this set of characters will be stripped + ## Examples + + iex> s = Explorer.Series.from_list(["$1", "$$200$$", "$$$3000$"]) + iex> Explorer.Series.lstrip(s, "$") + #Explorer.Series< + Polars[3] + string ["1", "200$$", "3000$"] + > + + iex> s = Explorer.Series.from_list(["abc", "adefa", "bcda"]) + iex> Explorer.Series.lstrip(s, "ab") + #Explorer.Series< + Polars[3] + string ["c", "defa", "cda"] + > + """ + @doc type: :string_wise + @spec lstrip(Series.t(), String.t()) :: Series.t() + def lstrip(%Series{dtype: :string} = series, string) when is_binary(string), + do: apply_series(series, :lstrip, [string]) + + def lstrip(%Series{dtype: dtype}, _string), + do: dtype_error("lstrip/2", dtype, [:string]) + + @doc """ + Returns a string series where all trailing Unicode whitespaces have been removed. + + ## Examples + + iex> s = Explorer.Series.from_list([" abc", "def ", " bcd"]) + iex> Explorer.Series.rstrip(s) + #Explorer.Series< + Polars[3] + string [" abc", "def", " bcd"] + > + """ + @doc type: :string_wise + @spec rstrip(Series.t()) :: Series.t() + def rstrip(%Series{dtype: :string} = series), + do: apply_series(series, :rstrip, [nil]) + + @doc """ + Returns a string series where all trailing examples of the provided string + have been removed. + + Where multiple characters are provided, all combinations of this set of characters will be stripped + + ## Examples + + iex> s = Explorer.Series.from_list(["__abc__", "def_", "__bcd_"]) + iex> Explorer.Series.rstrip(s, "_") + #Explorer.Series< + Polars[3] + string ["__abc", "def", "__bcd"] + > + + iex> s = Explorer.Series.from_list(["abc", "adefa", "bcdabaaa"]) + iex> Explorer.Series.rstrip(s, "ab") + #Explorer.Series< + Polars[3] + string ["abc", "adef", "bcd"] + > + """ + @doc type: :string_wise + @spec rstrip(Series.t(), String.t()) :: Series.t() + def rstrip(%Series{dtype: :string} = series, string) when is_binary(string), + do: apply_series(series, :rstrip, [string]) + + def rstrip(%Series{dtype: dtype}, _string), + do: dtype_error("rstrip/2", dtype, [:string]) + + @doc """ + Returns a string sliced from the offset to the end of the string, supporting + negative indexing + + ## Examples + + iex> s = Explorer.Series.from_list(["earth", "mars", "neptune"]) + iex> Explorer.Series.substring(s, -3) + #Explorer.Series< + Polars[3] + string ["rth", "ars", "une"] + > + + iex> s = Explorer.Series.from_list(["earth", "mars", "neptune"]) + iex> Explorer.Series.substring(s, 1) + #Explorer.Series< + Polars[3] + string ["arth", "ars", "eptune"] + > + """ + @doc type: :string_wise + @spec substring(Series.t(), integer()) :: Series.t() + def substring(%Series{dtype: :string} = series, offset) when is_integer(offset), + do: apply_series(series, :substring, [offset, nil]) + + @doc """ + Returns a string sliced from the offset to the length provided, supporting + negative indexing + + ## Examples + + iex> s = Explorer.Series.from_list(["earth", "mars", "neptune"]) + iex> Explorer.Series.substring(s, -3, 2) + #Explorer.Series< + Polars[3] + string ["rt", "ar", "un"] + > + + iex> s = Explorer.Series.from_list(["earth", "mars", "neptune"]) + iex> Explorer.Series.substring(s, 1, 5) + #Explorer.Series< + Polars[3] + string ["arth", "ars", "eptun"] + > + + iex> d = Explorer.Series.from_list(["こんにちは世界", "مرحبًا", "안녕하세요"]) + iex> Explorer.Series.substring(d, 1, 3) + #Explorer.Series< + Polars[3] + string ["んにち", "رحب", "녕하세"] + > + """ + @doc type: :string_wise + @spec substring(Series.t(), integer(), integer()) :: Series.t() + def substring(%Series{dtype: :string} = series, offset, length) + when is_integer(offset) + when is_integer(length) + when length >= 0, + do: apply_series(series, :substring, [offset, length]) + + def substring(%Series{dtype: dtype}, _offset, _length), + do: dtype_error("substring/3", dtype, [:string]) + + @doc """ + Split the string by a substring. + + ## Examples + + iex> s = Series.from_list(["1", "1|2"]) + iex> Series.split(s, "|") + #Explorer.Series< + Polars[2] + list[string] [["1"], ["1", "2"]] + > + + """ + @doc type: :string_wise + @spec split(Series.t(), String.t()) :: Series.t() + def split(%Series{dtype: :string} = series, by) + when is_binary(by), + do: apply_series(series, :split, [by]) + + def split(%Series{dtype: dtype}, _by), + do: dtype_error("split/2", dtype, [:string]) + + @doc """ + Split a string Series into a struct of string `fields`. + + The length of the field names list determines how many times the + string will be split at most. If the string cannot be split into that + many separate strings, null values will be provided for the + remaining fields. + + ## Examples + + iex> s = Series.from_list(["Smith, John", "Jones, Jane"]) + iex> Series.split_into(s, ", ", ["Last Name", "First Name"]) + #Explorer.Series< + Polars[2] + struct[2] [%{"First Name" => "John", "Last Name" => "Smith"}, %{"First Name" => "Jane", "Last Name" => "Jones"}] + > + + """ + @doc type: :string_wise + @spec split_into(Series.t(), String.t(), list(String.t() | atom())) :: Series.t() + def split_into(%Series{dtype: :string} = series, by, [_ | _] = fields) when is_binary(by), + do: apply_series(series, :split_into, [by, Enum.map(fields, &to_string/1)]) + + def split_into(%Series{dtype: dtype}, by, [_ | _]) when is_binary(by), + do: dtype_error("split_into/3", dtype, [:string]) + + @doc """ + Count how many times a substring appears in a string. + + > ### Notice {: .warning} + > + > This function detects only literal strings. For regular expressions, see `re_count_matches/2`. + + ## Examples + + iex> s = Explorer.Series.from_list(["abc", "def", "bcd", nil]) + iex> Explorer.Series.count_matches(s, "bc") + #Explorer.Series< + Polars[4] + u32 [1, 0, 1, nil] + > + """ + @doc type: :string_wise + @spec count_matches(Series.t(), String.t()) :: Series.t() + def count_matches(%Series{dtype: :string} = series, substring) + when K.is_binary(substring), + do: apply_series(series, :count_matches, [substring]) + + def count_matches(%Series{dtype: dtype}, _), + do: dtype_error("count_matches/2", dtype, [:string]) + + @doc """ + Count how many times a pattern matches a string. + + > ### Notice {: .warning} + > + > This function matches against a regular expression. It does not expect an Elixir regex, + > but a escaped string and you can use the `~S` sigil for escaping it. Since each Explorer + > backend may have its own regular expression rules, you must consult their underlying + > engine. For the default backend (Polars), the rules are outlined in the Rust create named + > [`regex`](https://docs.rs/regex/latest/regex/). + > + > To count matching literal strings, you can use `count_matches/2`. + + ## Examples + + iex> s = Explorer.Series.from_list(["abc", "def def", "bcd", nil]) + iex> Explorer.Series.re_count_matches(s, ~S/(a|e)/) + #Explorer.Series< + Polars[4] + u32 [1, 2, 0, nil] + > + """ + @doc type: :string_wise + @spec re_count_matches(Series.t(), String.t()) :: Series.t() + def re_count_matches(%Series{dtype: :string} = series, pattern) + when K.is_binary(pattern), + do: apply_series(series, :re_count_matches, [pattern]) + + def re_count_matches(%Series{dtype: :string}, %Regex{}) do + raise ArgumentError, + "standard regexes cannot be used as pattern because it may be incompatible with the backend. " <> + "Please use the `~S` sigil or extract the source from the regex with `Regex.source/1`" + end + + def re_count_matches(%Series{dtype: dtype}, _), + do: dtype_error("re_count_matches/2", dtype, [:string]) + + @doc """ + Scan for all matches for the given regex pattern. + + Extract each successive non-overlapping regex match in an individual string as a list. + + > ### Notice {: .warning} + > + > This function matches against a regular expression. It does not expect an Elixir regex, + > but a escaped string and you can use the `~S` sigil for escaping it. Since each Explorer + > backend may have its own regular expression rules, you must consult their underlying + > engine. For the default backend (Polars), the rules are outlined in the Rust create named + > [`regex`](https://docs.rs/regex/latest/regex/). + + ## Examples + + iex> s = Explorer.Series.from_list(["abc", "def def", "bcd", nil]) + iex> Explorer.Series.re_scan(s, ~S/(b|d)/) + #Explorer.Series< + Polars[4] + list[string] [["b"], ["d", "d"], ["b", "d"], nil] + > + + """ + @doc type: :string_wise + @spec re_scan(Series.t(), String.t()) :: Series.t() + def re_scan(%Series{dtype: :string} = series, pattern) + when K.is_binary(pattern), + do: apply_series(series, :re_scan, [pattern]) + + def re_scan(%Series{dtype: :string}, %Regex{}) do + raise ArgumentError, + "standard regexes cannot be used as pattern because it may be incompatible with the backend. " <> + "Please use the `~S` sigil or extract the source from the regex with `Regex.source/1`" + end + + def re_scan(%Series{dtype: dtype}, _), + do: dtype_error("re_scan/2", dtype, [:string]) + + @doc """ + Extract all capture groups as a struct for the given regex pattern. + + All group names are strings. If your pattern contains unnamed groups, their numerical position + is converted to a string, starting from "1". + + > ### Notice {: .warning} + > + > This function does not work inside the context of `Explorer.Query`. If you are working on + > a data frame, you first need to extract the series from it. See `Explorer.DataFrame.pull/2`. + > + > This function matches against a regular expression. It does not expect an Elixir regex, + > but a escaped string and you can use the `~S` sigil for escaping it. Since each Explorer + > backend may have its own regular expression rules, you must consult their underlying + > engine. For the default backend (Polars), the rules are outlined in the Rust create named + > [`regex`](https://docs.rs/regex/latest/regex/). + + ## Examples + + iex> s = Explorer.Series.from_list(["abc", "def def", "bcd", nil]) + iex> Explorer.Series.re_named_captures(s, ~S/(b|d)/) + #Explorer.Series< + Polars[4] + struct[1] [%{"1" => "b"}, %{"1" => "d"}, %{"1" => "b"}, nil] + > + + iex> s = Explorer.Series.from_list(["alice@service.com", "bob@example.com"]) + iex> Explorer.Series.re_named_captures(s, ~S/(?[^@]+)@(?.*)/) + #Explorer.Series< + Polars[2] + struct[2] [%{"account" => "alice", "host" => "service.com"}, %{"account" => "bob", "host" => "example.com"}] + > + + """ + @doc type: :string_wise + @spec re_named_captures(Series.t(), String.t()) :: Series.t() + def re_named_captures(%Series{dtype: :string} = series, pattern) + when K.is_binary(pattern), + do: apply_series(series, :re_named_captures, [pattern]) + + def re_named_captures(%Series{dtype: :string}, %Regex{}) do + raise ArgumentError, + "standard regexes cannot be used as pattern because it may be incompatible with the backend. " <> + "Please use the `~S` sigil or extract the source from the regex with `Regex.source/1`" + end + + def re_named_captures(%Series{dtype: dtype}, _), + do: dtype_error("re_named_captures/2", dtype, [:string]) + + # Float + + @doc """ + Round floating point series to given decimal places. + + ## Examples + + iex> s = Explorer.Series.from_list([1.124993, 2.555321, 3.995001]) + iex> Explorer.Series.round(s, 2) + #Explorer.Series< + Polars[3] + f64 [1.12, 2.56, 4.0] + > + """ + @doc type: :float_wise + @spec round(Series.t(), non_neg_integer()) :: Series.t() + def round(%Series{dtype: {:f, _}} = series, decimals) + when K.and(is_integer(decimals), decimals >= 0), + do: apply_series(series, :round, [decimals]) + + def round(%Series{dtype: {:f, _}}, _), + do: raise(ArgumentError, "second argument to round/2 must be a non-negative integer") + + def round(%Series{dtype: dtype}, _), do: dtype_error("round/2", dtype, @float_dtypes) + + @doc """ + Floor floating point series to lowest integers smaller or equal to the float value. + + ## Examples + + iex> s = Explorer.Series.from_list([1.124993, 2.555321, 3.995001]) + iex> Explorer.Series.floor(s) + #Explorer.Series< + Polars[3] + f64 [1.0, 2.0, 3.0] + > + """ + @doc type: :float_wise + @spec floor(Series.t()) :: Series.t() + def floor(%Series{dtype: dtype} = series) when K.in(dtype, @float_dtypes), + do: apply_series(series, :floor) + + def floor(%Series{dtype: dtype}), do: dtype_error("floor/1", dtype, @float_dtypes) + + @doc """ + Ceil floating point series to highest integers smaller or equal to the float value. + + ## Examples + + iex> s = Explorer.Series.from_list([1.124993, 2.555321, 3.995001]) + iex> Explorer.Series.ceil(s) + #Explorer.Series< + Polars[3] + f64 [2.0, 3.0, 4.0] + > + """ + @doc type: :float_wise + @spec ceil(Series.t()) :: Series.t() + def ceil(%Series{dtype: dtype} = series) when K.in(dtype, @float_dtypes), + do: apply_series(series, :ceil) + + def ceil(%Series{dtype: dtype}), do: dtype_error("ceil/1", dtype, @float_dtypes) + + @doc """ + Returns a mask of finite values. + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, 0, nil]) + iex> s2 = Explorer.Series.from_list([0, 2, 0, nil]) + iex> s3 = Explorer.Series.divide(s1, s2) + iex> Explorer.Series.is_finite(s3) + #Explorer.Series< + Polars[4] + boolean [false, true, false, nil] + > + """ + @doc type: :float_wise + @spec is_finite(Series.t()) :: Series.t() + def is_finite(%Series{dtype: dtype} = series) when K.in(dtype, @float_dtypes), + do: apply_series(series, :is_finite) + + def is_finite(%Series{dtype: dtype}), do: dtype_error("is_finite/1", dtype, @float_dtypes) + + @doc """ + Returns a mask of infinite values. + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, -1, 2, 0, nil]) + iex> s2 = Explorer.Series.from_list([0, 0, 2, 0, nil]) + iex> s3 = Explorer.Series.divide(s1, s2) + iex> Explorer.Series.is_infinite(s3) + #Explorer.Series< + Polars[5] + boolean [true, true, false, false, nil] + > + """ + @doc type: :float_wise + @spec is_infinite(Series.t()) :: Series.t() + def is_infinite(%Series{dtype: dtype} = series) when K.in(dtype, @float_dtypes), + do: apply_series(series, :is_infinite) + + def is_infinite(%Series{dtype: dtype}), + do: dtype_error("is_infinite/1", dtype, @float_dtypes) + + @doc """ + Returns a mask of nan values. + + ## Examples + + iex> s1 = Explorer.Series.from_list([1, 2, 0, nil]) + iex> s2 = Explorer.Series.from_list([0, 2, 0, nil]) + iex> s3 = Explorer.Series.divide(s1, s2) + iex> Explorer.Series.is_nan(s3) + #Explorer.Series< + Polars[4] + boolean [false, false, true, nil] + > + """ + @doc type: :float_wise + @spec is_nan(Series.t()) :: Series.t() + def is_nan(%Series{dtype: dtype} = series) when K.in(dtype, @float_dtypes), + do: apply_series(series, :is_nan) + + def is_nan(%Series{dtype: dtype}), do: dtype_error("is_nan/1", dtype, @float_dtypes) + + # Date / DateTime + + @doc """ + Returns the month number starting from 1. The return value ranges from 1 to 12. + + ## Examples + + iex> s = Explorer.Series.from_list([~D[2023-01-15], ~D[2023-02-16], ~D[2023-03-20], nil]) + iex> Explorer.Series.month(s) + #Explorer.Series< + Polars[4] + s8 [1, 2, 3, nil] + > + + It can also be called on a datetime series. + + iex> s = Explorer.Series.from_list([~N[2023-01-15 00:00:00], ~N[2023-02-16 23:59:59.999999], ~N[2023-03-20 12:00:00], nil]) + iex> Explorer.Series.month(s) + #Explorer.Series< + Polars[4] + s8 [1, 2, 3, nil] + > + """ + @doc type: :datetime_wise + @spec month(Series.t()) :: Series.t() + def month(%Series{dtype: dtype} = series) when is_date_like_dtype(dtype), + do: apply_series(series, :month) + + def month(%Series{dtype: dtype}), + do: super_dtype_error("month/1", dtype, [:date, :datetime, :naive_datetime]) + + @doc """ + Returns the year number in the calendar date. + + ## Examples + + iex> s = Explorer.Series.from_list([~D[2023-01-15], ~D[2022-02-16], ~D[2021-03-20], nil]) + iex> Explorer.Series.year(s) + #Explorer.Series< + Polars[4] + s32 [2023, 2022, 2021, nil] + > + + It can also be called on a datetime series. + + iex> s = Explorer.Series.from_list([~N[2023-01-15 00:00:00], ~N[2022-02-16 23:59:59.999999], ~N[2021-03-20 12:00:00], nil]) + iex> Explorer.Series.year(s) + #Explorer.Series< + Polars[4] + s32 [2023, 2022, 2021, nil] + > + """ + @doc type: :datetime_wise + @spec year(Series.t()) :: Series.t() + def year(%Series{dtype: dtype} = series) when is_date_like_dtype(dtype), + do: apply_series(series, :year) + + def year(%Series{dtype: dtype}), + do: super_dtype_error("year/1", dtype, [:date, :datetime, :naive_datetime]) + + @doc """ + Returns the hour number from 0 to 23. + + ## Examples + + iex> s = Explorer.Series.from_list([~N[2023-01-15 00:00:00], ~N[2022-02-16 23:59:59.999999], ~N[2021-03-20 12:00:00], nil]) + iex> Explorer.Series.hour(s) + #Explorer.Series< + Polars[4] + s8 [0, 23, 12, nil] + > + """ + @doc type: :datetime_wise + @spec hour(Series.t()) :: Series.t() + def hour(%Series{dtype: dtype} = series) when is_time_like_dtype(dtype), + do: apply_series(series, :hour) + + def hour(%Series{dtype: dtype}), + do: super_dtype_error("hour/1", dtype, [:time, :datetime, :naive_datetime]) + + @doc """ + Returns the minute number from 0 to 59. + + ## Examples + + iex> s = Explorer.Series.from_list([~N[2023-01-15 00:00:00], ~N[2022-02-16 23:59:59.999999], ~N[2021-03-20 12:00:00], nil]) + iex> Explorer.Series.minute(s) + #Explorer.Series< + Polars[4] + s8 [0, 59, 0, nil] + > + """ + @doc type: :datetime_wise + @spec minute(Series.t()) :: Series.t() + def minute(%Series{dtype: dtype} = series) when is_time_like_dtype(dtype), + do: apply_series(series, :minute) + + def minute(%Series{dtype: dtype}), + do: super_dtype_error("minute/1", dtype, [:time, :datetime, :naive_datetime]) + + @doc """ + Returns the second number from 0 to 59. + + ## Examples + + iex> s = Explorer.Series.from_list([~N[2023-01-15 00:00:00], ~N[2022-02-16 23:59:59.999999], ~N[2021-03-20 12:00:00], nil]) + iex> Explorer.Series.second(s) + #Explorer.Series< + Polars[4] + s8 [0, 59, 0, nil] + > + """ + @doc type: :datetime_wise + @spec second(Series.t()) :: Series.t() + def second(%Series{dtype: dtype} = series) when is_time_like_dtype(dtype), + do: apply_series(series, :second) + + def second(%Series{dtype: dtype}), + do: super_dtype_error("minute/1", dtype, [:time, :datetime, :naive_datetime]) + + @doc """ + Returns a day-of-week number starting from Monday = 1. (ISO 8601 weekday number) + + ## Examples + + iex> s = Explorer.Series.from_list([~D[2023-01-15], ~D[2023-01-16], ~D[2023-01-20], nil]) + iex> Explorer.Series.day_of_week(s) + #Explorer.Series< + Polars[4] + s8 [7, 1, 5, nil] + > + + It can also be called on a datetime series. + + iex> s = Explorer.Series.from_list([~N[2023-01-15 00:00:00], ~N[2023-01-16 23:59:59.999999], ~N[2023-01-20 12:00:00], nil]) + iex> Explorer.Series.day_of_week(s) + #Explorer.Series< + Polars[4] + s8 [7, 1, 5, nil] + > + """ + + @doc type: :datetime_wise + @spec day_of_week(Series.t()) :: Series.t() + def day_of_week(%Series{dtype: dtype} = series) when is_date_like_dtype(dtype), + do: apply_series(series, :day_of_week) + + def day_of_week(%Series{dtype: dtype}), + do: super_dtype_error("day_of_week/1", dtype, [:date, :datetime, :naive_datetime]) + + @doc """ + Returns the day-of-year number starting from 1. + + The return value ranges from 1 to 366 (the last day of year differs by years). + + ## Examples + + iex> s = Explorer.Series.from_list([~D[2023-01-01], ~D[2023-01-02], ~D[2023-02-01], nil]) + iex> Explorer.Series.day_of_year(s) + #Explorer.Series< + Polars[4] + s16 [1, 2, 32, nil] + > + + It can also be called on a datetime series. + + iex> s = Explorer.Series.from_list( + ...> [~N[2023-01-01 00:00:00], ~N[2023-01-02 00:00:00], ~N[2023-02-01 23:59:59], nil] + ...> ) + iex> Explorer.Series.day_of_year(s) + #Explorer.Series< + Polars[4] + s16 [1, 2, 32, nil] + > + """ + @doc type: :datetime_wise + @spec day_of_year(Series.t()) :: Series.t() + def day_of_year(%Series{dtype: dtype} = series) when is_date_like_dtype(dtype), + do: apply_series_list(:day_of_year, [series]) + + def day_of_year(%Series{dtype: dtype}), + do: super_dtype_error("day_of_year/1", dtype, [:date, :datetime, :naive_datetime]) + + @doc """ + Returns the week-of-year number. + + The return value ranges from 1 to 53 (the last week of year differs by years). + + Weeks start on Monday and end on Sunday. If the final week of a year does not end on Sunday, the + first days of the following year will have a week number of 52 (or 53 for a leap year). + + ## Examples + + iex> s = Explorer.Series.from_list([~D[2023-01-01], ~D[2023-01-02], ~D[2023-02-01], nil]) + iex> Explorer.Series.week_of_year(s) + #Explorer.Series< + Polars[4] + s8 [52, 1, 5, nil] + > + + It can also be called on a datetime series. + + iex> s = Explorer.Series.from_list( + ...> [~N[2023-01-01 00:00:00], ~N[2023-01-02 00:00:00], ~N[2023-02-01 23:59:59], nil] + ...> ) + iex> Explorer.Series.week_of_year(s) + #Explorer.Series< + Polars[4] + s8 [52, 1, 5, nil] + > + """ + @doc type: :datetime_wise + @spec week_of_year(Series.t()) :: Series.t() + def week_of_year(%Series{dtype: dtype} = series) when is_date_like_dtype(dtype), + do: apply_series_list(:week_of_year, [series]) + + def week_of_year(%Series{dtype: dtype}), + do: super_dtype_error("week_of_year/1", dtype, [:date, :datetime, :naive_datetime]) + + @deprecated "Use cast(:date) instead" + @doc false + def to_date(%Series{dtype: dtype} = series) when is_datetime_like_dtype(dtype), + do: cast(series, :date) + + def to_date(%Series{dtype: dtype}), + do: super_dtype_error("to_date/1", dtype, [:date, :datetime, :naive_datetime]) + + @deprecated "Use cast(:time) instead" + @doc false + def to_time(%Series{dtype: dtype} = series) when is_datetime_like_dtype(dtype), + do: cast(series, :time) + + def to_time(%Series{dtype: dtype}), + do: super_dtype_error("to_time/1", dtype, [:date, :datetime, :naive_datetime]) + + @doc """ + Join all string items in a sublist and place a separator between them. + + ## Examples + + iex> s = Series.from_list([["1"], ["1", "2"]]) + iex> Series.join(s, "|") + #Explorer.Series< + Polars[2] + string ["1", "1|2"] + > + + """ + @doc type: :list_wise + @spec join(Series.t(), String.t()) :: Series.t() + def join(%Series{dtype: {:list, :string}} = series, separator) + when is_binary(separator), + do: apply_series(series, :join, [separator]) + + def join(%Series{dtype: dtype}, _separator), + do: dtype_error("join/2", dtype, [{:list, :string}]) + + @doc """ + Calculates the length of each list in a list series. + + ## Examples + + iex> s = Series.from_list([[1], [1, 2]]) + iex> Series.lengths(s) + #Explorer.Series< + Polars[2] + u32 [1, 2] + > + + """ + @doc type: :list_wise + @spec lengths(Series.t()) :: Series.t() + def lengths(%Series{dtype: {:list, _}} = series), + do: apply_series(series, :lengths) + + def lengths(%Series{dtype: dtype}), + do: dtype_error("lengths/1", dtype, [{:list, :_}]) + + @doc """ + Checks for the presence of a value in a list series. + + ## Examples + + iex> s = Series.from_list([[1], [1, 2]]) + iex> Series.member?(s, 2) + #Explorer.Series< + Polars[2] + boolean [false, true] + > + + """ + @doc type: :list_wise + @spec member?(Series.t(), Explorer.Backend.Series.valid_types()) :: Series.t() + def member?(%Series{dtype: {:list, dtype}} = series, value) do + if cast_to_comparable_series(dtype, value) do + apply_series(series, :member?, [value]) + else + dtype_mismatch_error("member?/2", series, value) + end + end + + def member?(%Series{dtype: dtype}, _value), + do: dtype_error("member?/2", dtype, [{:list, :_}]) + + # Escape hatch + + @doc """ + Returns an `Explorer.Series` where each element is the result of invoking `fun` on each + corresponding element of `series`. + + This is an expensive operation meant to enable the use of arbitrary Elixir functions against + any backend. The implementation will vary by backend but in most (all?) cases will require + converting to an `Elixir.List`, applying `Enum.map/2`, and then converting back to an + `Explorer.Series`. + + See also the version of this function for a dataframe: + + * `Explorer.DataFrame.transform/3` + + ## Examples + + iex> s = Explorer.Series.from_list(["this ", " is", "great "]) + iex> Explorer.Series.transform(s, &String.trim/1) + #Explorer.Series< + Polars[3] + string ["this", "is", "great"] + > + + iex> s = Explorer.Series.from_list(["this", "is", "great"]) + iex> Explorer.Series.transform(s, &String.length/1) + #Explorer.Series< + Polars[3] + s64 [4, 2, 5] + > + """ + @doc type: :element_wise + def transform(series, fun) do + apply_series(series, :transform, [fun]) + end + + @doc """ + Extracts a field from a struct series + + The field can be an atom or string. + + ## Examples + + iex> s = Series.from_list([%{a: 1}, %{a: 2}]) + iex> Series.field(s, :a) + #Explorer.Series< + Polars[2] + s64 [1, 2] + > + + iex> s = Series.from_list([%{a: 1}, %{a: 2}]) + iex> Series.field(s, "a") + #Explorer.Series< + Polars[2] + s64 [1, 2] + > + """ + @doc type: :struct_wise + @spec field(Series.t(), String.t() | atom()) :: Series.t() + def field(%Series{dtype: {:struct, dtypes}} = series, name) + when K.or(is_binary(name), is_atom(name)) do + name = to_string(name) + + if List.keymember?(dtypes, name, 0) do + apply_series(series, :field, [name]) + else + raise ArgumentError, + "field #{inspect(name)} not found in fields #{inspect(Enum.map(dtypes, &elem(&1, 0)))}" + end + end + + @doc """ + Decodes a string series containing valid JSON according to `dtype`. + + ## Examples + + iex> s = Series.from_list(["1"]) + iex> Series.json_decode(s, {:s, 64}) + #Explorer.Series< + Polars[1] + s64 [1] + > + + iex> s = Series.from_list(["{\\"a\\":1}"]) + iex> Series.json_decode(s, {:struct, [{"a", {:s, 64}}]}) + #Explorer.Series< + Polars[1] + struct[1] [%{"a" => 1}] + > + + If the decoded value does not match the given `dtype`, + nil is returned for the given entry: + + iex> s = Series.from_list(["\\"1\\""]) + iex> Series.json_decode(s, {:s, 64}) + #Explorer.Series< + Polars[1] + s64 [nil] + > + + It raises an exception if the string is invalid JSON. + """ + @doc type: :string_wise + @spec json_decode(Series.t(), dtype() | dtype_alias()) :: Series.t() + def json_decode(%Series{dtype: :string} = series, dtype) do + dtype = Shared.normalise_dtype!(dtype) + + apply_series(series, :json_decode, [dtype]) + end + + @doc """ + Extracts a string series using a [`json_path`](https://goessner.net/articles/JsonPath/) from a series. + + ## Examples + + iex> s = Series.from_list(["{\\"a\\":1}", "{\\"a\\":2}"]) + iex> Series.json_path_match(s, "$.a") + #Explorer.Series< + Polars[2] + string [\"1\", \"2\"] + > + + If `json_path` is not found or if the string is invalid JSON or `nil`, + nil is returned for the given entry: + + iex> s = Series.from_list(["{\\"a\\":1}", nil, "{\\"a\\":2}"]) + iex> Series.json_path_match(s, "$.b") + #Explorer.Series< + Polars[3] + string [nil, nil, nil] + > + + It raises an exception if the `json_path` is invalid. + """ + @doc type: :string_wise + @spec json_path_match(Series.t(), String.t()) :: Series.t() + def json_path_match(%Series{dtype: :string} = series, json_path) do + apply_series(series, :json_path_match, [json_path]) + end + + # Helpers + + defp backend_from_options!(opts) do + backend = Explorer.Shared.backend_from_options!(opts) || Explorer.Backend.get() + + :"#{backend}.Series" + end + + defp super_dtype_error(function, dtype, valid_super_dtypes) do + raise( + ArgumentError, + "Explorer.Series.#{function} not implemented for dtype #{inspect(dtype)}. " <> + "Valid dtypes are any subtype of #{inspect(valid_super_dtypes)}" + ) + end + + defp dtype_error(function, dtype, valid_dtypes) when is_list(valid_dtypes) do + raise ArgumentError, dtype_error_message(function, dtype, valid_dtypes) + end + + defp dtype_error_message(function, dtype, valid_dtypes) when is_list(valid_dtypes) do + "Explorer.Series.#{function} not implemented for dtype #{inspect(dtype)}. " <> + "Valid " <> Shared.inspect_dtypes(valid_dtypes, with_prefix: true) + end + + @spec dtype_mismatch_error(String.t(), any(), any(), [any()]) :: no_return() + defp dtype_mismatch_error(function, left, right, valid) do + left_series? = match?(%Series{}, left) + right_series? = match?(%Series{}, right) + + cond do + Kernel.and(left_series?, Kernel.not(Enum.member?(valid, left.dtype))) -> + dtype_error(function, left.dtype, valid) + + Kernel.and(right_series?, Kernel.not(Enum.member?(valid, right.dtype))) -> + dtype_error(function, right.dtype, valid) + + Kernel.or(left_series?, right_series?) -> + dtype_mismatch_error(function, left, right) + + true -> + raise( + ArgumentError, + "expecting series for one of the sides, but got: " <> + "#{dtype_or_inspect(left)} (lhs) and #{dtype_or_inspect(right)} (rhs)" <> + Shared.maybe_bad_column_hint([left, right]) + ) + end + end + + defp dtype_mismatch_error(function, left, right) do + raise( + ArgumentError, + "cannot invoke Explorer.Series.#{function} with mismatched dtypes: #{dtype_or_inspect(left)} and " <> + "#{dtype_or_inspect(right)}" <> Shared.maybe_bad_column_hint([left, right]) + ) + end + + defp dtype_or_inspect(%Series{dtype: dtype}), do: inspect(dtype) + defp dtype_or_inspect(value), do: inspect(value) + + defp check_dtypes_for_coalesce!(%Series{} = s1, %Series{} = s2) do + # TODO: consider the unsigned types here. + case {s1.dtype, s2.dtype} do + {dtype, dtype} -> :ok + {{:s, _}, {:f, _}} -> :ok + {{:f, _}, {:s, _}} -> :ok + {left, right} -> dtype_mismatch_error("coalesce/2", left, right) + end + end + + defimpl Inspect do + import Inspect.Algebra + + def inspect(%Explorer.Series{data: %struct{}} = series, opts) do + remote_ref = + case series.remote do + {_local_gc, _remote_pid, remote_ref} -> remote_ref + _ -> struct.owner_reference(series) + end + + remote = + if Kernel.and(is_reference(remote_ref), node(remote_ref) != node()) do + concat(line(), Atom.to_string(node(remote_ref))) + else + empty() + end + + force_unfit( + concat([ + color("#Explorer.Series<", :map, opts), + nest( + concat([remote, line(), apply_series(series, :inspect, [opts])]), + 2 + ), + line(), + color(">", :map, opts) + ]) + ) + end + end +end + +defmodule Explorer.Series.Iterator do + @moduledoc false + defstruct [:series, :size] + + def new(series) do + %__MODULE__{series: series, size: Explorer.Series.size(series)} + end + + defimpl Enumerable do + def count(%{size: size}), do: {:ok, size} + + def member?(_iterator, _value), do: {:error, __MODULE__} + + def slice(%{size: size, series: series}) do + {:ok, size, + fn start, size, step -> + if step != 1 do + raise "Explorer.Series can only be sliced with step of 1" + end + + series + |> Explorer.Series.slice(start, size) + |> Explorer.Series.to_list() + end} + end + + def reduce(%{series: series, size: size}, acc, fun) do + reduce(series, size, 0, acc, fun) + end + + defp reduce(_series, _size, _offset, {:halt, acc}, _fun), do: {:halted, acc} + + defp reduce(series, size, offset, {:suspend, acc}, fun) do + {:suspended, acc, &reduce(series, size, offset, &1, fun)} + end + + defp reduce(_series, size, size, {:cont, acc}, _fun), do: {:done, acc} + + defp reduce(series, size, offset, {:cont, acc}, fun) do + value = Explorer.Series.at(series, offset) + reduce(series, size, offset + 1, fun.(value, acc), fun) + end + end +end diff --git a/deps/explorer/lib/explorer/shared.ex b/deps/explorer/lib/explorer/shared.ex new file mode 100644 index 0000000000000000000000000000000000000000..2e3f649ee142051cd5ae55019e47e2b3d3351e2d --- /dev/null +++ b/deps/explorer/lib/explorer/shared.ex @@ -0,0 +1,782 @@ +defmodule Explorer.Shared do + # A collection of **private** helpers shared in Explorer. + @moduledoc false + + require Logger + + @integer_types [ + {:s, 8}, + {:s, 16}, + {:s, 32}, + {:s, 64}, + {:u, 8}, + {:u, 16}, + {:u, 32}, + {:u, 64} + ] + + @precisions [:millisecond, :microsecond, :nanosecond] + + @precision_types for d <- [:naive_datetime, :duration], + p <- @precisions, + do: {d, p} + + @scalar_types @integer_types ++ + @precision_types ++ + [ + :null, + :binary, + :boolean, + :category, + :date, + {:f, 32}, + {:f, 64}, + :string, + :time + ] + + @doc """ + All supported dtypes. + + This list excludes recursive dtypes, such as lists + within lists inside. + """ + def dtypes do + @scalar_types ++ + [{:list, :any}, {:struct, :any}, {:decimal, :pos_integer, :pos_integer}] + end + + @doc """ + Normalise a given dtype and return nil if is invalid. + """ + def normalise_dtype({:list, inner}) do + if maybe_dtype = normalise_dtype(inner), do: {:list, maybe_dtype} + end + + def normalise_dtype({:struct, inner_types}) do + inner_types + |> Enum.reduce_while([], fn {key, dtype}, normalized_dtypes -> + case normalise_dtype(dtype) do + nil -> + {:halt, nil} + + dtype -> + key = to_string(key) + {:cont, List.keystore(normalized_dtypes, key, 0, {key, dtype})} + end + end) + |> then(fn + nil -> + nil + + normalized_dtypes -> + {:struct, + if(is_map(inner_types), do: Enum.sort(normalized_dtypes), else: normalized_dtypes)} + end) + end + + def normalise_dtype({:datetime, p, tz} = dtype) when p in @precisions and is_binary(tz), + do: dtype + + def normalise_dtype(dtype) when dtype in @scalar_types, do: dtype + def normalise_dtype(dtype) when dtype in [:float, :f64], do: {:f, 64} + def normalise_dtype(dtype) when dtype in [:integer, :s64], do: {:s, 64} + def normalise_dtype(:f32), do: {:f, 32} + def normalise_dtype(:s8), do: {:s, 8} + def normalise_dtype(:s16), do: {:s, 16} + def normalise_dtype(:s32), do: {:s, 32} + def normalise_dtype(:u8), do: {:u, 8} + def normalise_dtype(:u16), do: {:u, 16} + def normalise_dtype(:u32), do: {:u, 32} + def normalise_dtype(:u64), do: {:u, 64} + + def normalise_dtype({:datetime, precision}) do + :ok = + Logger.warning(""" + The `{:datetime, _}` dtype has been deprecated. + Please use `{:naive_datetime, _}` instead. + """) + + {:naive_datetime, precision} + end + + # Not a valid option, but this is necessary because the backend + # may return a decimal dtype without precision. We should cast in these cases. + def normalise_dtype({:decimal, nil, scale}), do: normalise_dtype({:decimal, 38, scale}) + + def normalise_dtype({:decimal, precision, scale} = dtype) + when is_integer(scale) and is_integer(precision) do + if precision in 0..38//1 and scale in 0..38//1 and scale <= precision do + dtype + end + end + + def normalise_dtype(_dtype), do: nil + + @doc """ + Normalise a given dtype, but raise error in case it's invalid. + """ + def normalise_dtype!(dtype) do + if maybe_dtype = normalise_dtype(dtype) do + maybe_dtype + else + raise ArgumentError, + "unsupported dtype #{inspect(dtype)}, expected one of #{inspect_dtypes(dtypes())}" + end + end + + @doc """ + Supported naive datetime dtypes. + """ + def naive_datetime_types, do: for(p <- @precisions, do: {:naive_datetime, p}) + + @doc """ + Supported duration dtypes. + """ + def duration_types, do: for(p <- @precisions, do: {:duration, p}) + + @doc """ + Supported float dtypes. + """ + def float_types, do: [{:f, 32}, {:f, 64}] + + @doc """ + Supported signed integer dtypes. + """ + def signed_integer_types, do: [{:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}] + + @doc """ + Supported unsigned integer dtypes. + """ + def unsigned_integer_types, do: [{:u, 8}, {:u, 16}, {:u, 32}, {:u, 64}] + + @doc """ + All integer dtypes. + """ + def integer_types, do: signed_integer_types() ++ unsigned_integer_types() + + @doc """ + Both integer and float dtypes. + """ + def numeric_types, do: float_types() ++ integer_types() + + @doc """ + Gets the backend from a `Keyword.t()` or `nil`. + """ + def backend_from_options!(opts) do + case Keyword.fetch(opts, :backend) do + {:ok, backend} when is_atom(backend) -> + backend + + {:ok, other} -> + raise ArgumentError, + ":backend must be an atom, got: #{inspect(other)}" + + :error -> + nil + end + end + + @doc """ + Normalize column names and raise if column does not exist. + """ + def to_existing_columns(df, columns, raise? \\ true) + + def to_existing_columns(df, columns, raise?) when is_list(columns) do + {columns, _cache} = + Enum.map_reduce(columns, nil, fn + column, maybe_map when is_integer(column) -> + map = maybe_map || column_index_map(df.names) + existing_column = fetch_column_at!(map, column) + {existing_column, map} + + column, maybe_map when is_atom(column) -> + column = Atom.to_string(column) + maybe_raise_column_not_found(df, column, raise?) + {column, maybe_map} + + column, maybe_map when is_binary(column) -> + maybe_raise_column_not_found(df, column, raise?) + {column, maybe_map} + end) + + columns + end + + def to_existing_columns(%{names: names}, .., _raise?) do + names + end + + def to_existing_columns(%{names: names}, %Range{} = columns, _raise?) do + Enum.slice(names, columns) + end + + def to_existing_columns(%{names: names}, %Regex{} = columns, _raise?) do + Enum.filter(names, &Regex.match?(columns, &1)) + end + + def to_existing_columns(%{names: names}, callback, _raise?) when is_function(callback, 1) do + Enum.filter(names, callback) + end + + def to_existing_columns(%{names: names, dtypes: dtypes}, callback, _raise?) + when is_function(callback, 2) do + Enum.filter(names, fn name -> callback.(name, dtypes[name]) end) + end + + def to_existing_columns(_, other, _raise?) do + raise ArgumentError, """ + invalid columns specification. Columns may be specified as one of: + + * a list of columns indexes or names as atoms and strings + + * a range + + * a regex that keeps only the names matching the regex + + * a one-arity function that receives column names and returns + true for column names to keep + + * a two-arity function that receives column names and types and + returns true for column names to keep + + Got: #{inspect(other)} + """ + end + + defp fetch_column_at!(map, index) do + normalized = if index < 0, do: index + map_size(map), else: index + + case map do + %{^normalized => column} -> column + %{} -> raise ArgumentError, "no column exists at index #{index}" + end + end + + defp column_index_map(names), + do: for({name, idx} <- Enum.with_index(names), into: %{}, do: {idx, name}) + + @doc """ + Raises if a column is not found. + """ + def maybe_raise_column_not_found(df, name, raise? \\ true) do + if raise? and Map.has_key?(df.dtypes, name) == false do + raise ArgumentError, + List.to_string( + [ + "could not find column name \"#{name}\"" | did_you_mean(name, df.names) + ] ++ ["\nIf you are attempting to interpolate a value, use ^#{name}."] + ) + end + end + + @doc """ + Gets the `dtype` of a list or raise error if not possible. + """ + def dtype_from_list!(list) do + Enum.reduce(list, :null, &infer_type/2) + end + + @doc """ + Gets the dtype from the list according to the preferred type. + + The dtype from the list is first computed standalone. + If the list can be directly instantiated as the preferred type, + then the preferred type is returned. Otherwise, the inferred type + is returned and a cast call to the preferred type is necessary. + + If no preferred type is given (nil), then the inferred type is returned. + """ + def dtype_from_list!(list, nil), do: dtype_from_list!(list) + def dtype_from_list!(_list, preferred_type), do: preferred_type + + @non_finite [:nan, :infinity, :neg_infinity] + + defp infer_type(nil, type), do: type + defp infer_type(item, :null), do: infer_type(item) + defp infer_type(integer, {:f, 64}) when is_integer(integer), do: {:f, 64} + defp infer_type(float, {:s, 64}) when is_float(float) or float in @non_finite, do: {:f, 64} + + defp infer_type(integer, {:decimal, _, _} = decimal) when is_integer(integer), do: decimal + + defp infer_type(float, {:decimal, _, _} = decimal) when is_float(float), + do: infer_type(Decimal.from_float(float), decimal) + + defp infer_type(list, {:list, type}) when is_list(list), do: infer_list(list, type) + defp infer_type(%{} = map, {:struct, inner}), do: infer_struct(map, inner) + + defp infer_type(%Decimal{} = item, {:decimal, precision, scale}) do + {:decimal, precision, max(Decimal.scale(item), scale)} + end + + defp infer_type(item, type) do + if infer_type(item) == type do + type + else + raise ArgumentError, + "the value #{inspect(item)} does not match the inferred dtype #{inspect(type)}" + end + end + + defp infer_type(%Date{} = _item), do: :date + defp infer_type(%Time{} = _item), do: :time + defp infer_type(%DateTime{time_zone: tz} = _item), do: {:datetime, :microsecond, tz} + defp infer_type(%NaiveDateTime{} = _item), do: {:naive_datetime, :microsecond} + defp infer_type(%Explorer.Duration{precision: precision} = _item), do: {:duration, precision} + defp infer_type(%Decimal{} = item), do: {:decimal, 38, Decimal.scale(item)} + defp infer_type(%_{} = item), do: raise(ArgumentError, "unsupported datatype: #{inspect(item)}") + defp infer_type(item) when is_integer(item), do: {:s, 64} + defp infer_type(item) when is_float(item) or item in @non_finite, do: {:f, 64} + defp infer_type(item) when is_boolean(item), do: :boolean + defp infer_type(item) when is_binary(item), do: :string + defp infer_type(list) when is_list(list), do: infer_list(list, :null) + defp infer_type(%{} = map), do: infer_struct(map, nil) + defp infer_type(item), do: raise(ArgumentError, "unsupported datatype: #{inspect(item)}") + + defp infer_list(list, type) do + {:list, Enum.reduce(list, type, &infer_type/2)} + end + + defp infer_struct(%{} = map, types) do + types = + for {key, value} <- map do + key = to_string(key) + + cond do + types == nil -> + {key, infer_type(value, :null)} + + result = List.keyfind(types, key, 0) -> + {^key, type} = result + {key, infer_type(value, type)} + + true -> + raise ArgumentError, + "the value #{inspect(map)} does not match the inferred dtype #{inspect({:struct, types})}" + end + end + + {:struct, Enum.sort(types)} + end + + @doc """ + Returns the leaf dtype from a {:list, _} dtype, or itself. + """ + def leaf_dtype({:list, inner_dtype}), do: leaf_dtype(inner_dtype) + def leaf_dtype(dtype), do: dtype + + @doc """ + Merge two dtypes. + """ + def merge_dtype(dtype, dtype), do: dtype + def merge_dtype(:null, dtype), do: dtype + def merge_dtype(dtype, :null), do: dtype + def merge_dtype(ltype, rtype), do: merge_numeric_dtype(ltype, rtype) + + @doc """ + Merge two numeric dtypes to a valid precision. + """ + def merge_numeric_dtype({int_type, left}, {int_type, right}) when int_type in [:s, :u], + do: {int_type, max(left, right)} + + def merge_numeric_dtype({:s, s_size}, {:u, u_size}), do: {:s, max(min(64, u_size * 2), s_size)} + def merge_numeric_dtype({:u, s_size}, {:s, u_size}), do: {:s, max(min(64, u_size * 2), s_size)} + def merge_numeric_dtype({int_type, _}, {:f, _} = float) when int_type in [:s, :u], do: float + def merge_numeric_dtype({:f, _} = float, {int_type, _}) when int_type in [:s, :u], do: float + def merge_numeric_dtype({:f, left}, {:f, right}), do: {:f, max(left, right)} + def merge_numeric_dtype({:f, _} = float, :null), do: float + def merge_numeric_dtype(:null, {:f, _} = float), do: float + + def merge_numeric_dtype({:decimal, _, _} = decimal, :null), do: decimal + def merge_numeric_dtype(:null, {:decimal, _, _} = decimal), do: decimal + + def merge_numeric_dtype({:decimal, _, _}, {:f, _} = float), do: float + def merge_numeric_dtype({:f, _} = float, {:decimal, _, _}), do: float + + def merge_numeric_dtype({:decimal, _, _} = decimal, {:s, _}), do: decimal + def merge_numeric_dtype({:s, _}, {:decimal, _, _} = decimal), do: decimal + + def merge_numeric_dtype({:decimal, _, _} = decimal, {:u, _}), do: decimal + def merge_numeric_dtype({:u, _}, {:decimal, _, _} = decimal), do: decimal + + def merge_numeric_dtype(_, _), do: nil + + @doc """ + Helper for shared behaviour in inspect. + """ + def to_doc(item, opts) when is_list(item) do + open = Inspect.Algebra.color("[", :list, opts) + close = Inspect.Algebra.color("]", :list, opts) + Inspect.Algebra.container_doc(open, item, close, opts, &to_doc/2) + end + + def to_doc(item, opts) when is_map(item) and not is_struct(item) do + open = Inspect.Algebra.color("%{", :map, opts) + close = Inspect.Algebra.color("}", :map, opts) + arrow = Inspect.Algebra.color(" => ", :map, opts) + + Inspect.Algebra.container_doc(open, Enum.to_list(item), close, opts, fn {key, value}, opts -> + Inspect.Algebra.concat([ + Inspect.Algebra.color(inspect(key), :string, opts), + arrow, + to_doc(value, opts) + ]) + end) + end + + def to_doc(item, _opts) do + case item do + nil -> "nil" + :nan -> "NaN" + :infinity -> "Inf" + :neg_infinity -> "-Inf" + i when is_binary(i) -> inspect(i) + _ -> Kernel.to_string(item) + end + end + + @doc """ + Helper to inspect dtypes in a sentence. + """ + def inspect_dtypes(dtypes, opts \\ []) do + opts = Keyword.validate!(opts, with_prefix: false, backticks: false) + + inspect_fun = + if opts[:backticks] do + fn item -> "`" <> inspect(item) <> "`" end + else + &Kernel.inspect/1 + end + + case dtypes do + [dtype] -> + if opts[:with_prefix] do + "dtype is #{inspect_fun.(dtype)}" + else + inspect_fun.(dtype) + end + + [_ | _] = dtypes -> + prefix = + if opts[:with_prefix] do + "dtypes are " + else + "" + end + + {items, [last]} = Enum.split(Enum.sort(dtypes), -1) + + IO.iodata_to_binary([ + prefix, + Enum.map_intersperse(items, ", ", inspect_fun), + " and ", + inspect_fun.(last) + ]) + end + end + + @doc """ + Converts a dtype to an iotype. + + Note this is a subset of Series.iotype/1, given we can convert + a category series to iotype but we cannot generally convert + a category dtype to an iotype without the underlying categories. + """ + def dtype_to_iotype(dtype) do + case dtype do + {:f, _} -> dtype + {:s, _} -> dtype + {:u, _} -> dtype + :boolean -> {:u, 8} + :date -> {:s, 32} + :time -> {:s, 64} + {:naive_datetime, _} -> {:s, 64} + {:datetime, _, _} -> {:s, 64} + {:duration, _} -> {:s, 64} + _ -> :none + end + end + + @doc """ + Raising version of `dtype_to_iotype/1`. + """ + def dtype_to_iotype!(dtype) do + case dtype_to_iotype(dtype) do + :none -> raise ArgumentError, "cannot convert dtype #{dtype} into a binary/tensor type" + other -> other + end + end + + @doc """ + Converts an iotype to dtype. + """ + def iotype_to_dtype!(type) do + case type do + {:f, _} -> type + {:s, _} -> type + {:u, _} -> type + _ -> raise ArgumentError, "cannot convert binary/tensor type #{inspect(type)} into dtype" + end + end + + @doc """ + Converts dtype to its string representation. + """ + def dtype_to_string({:naive_datetime, p}), do: "naive_datetime[#{precision_string(p)}]" + def dtype_to_string({:datetime, p, tz}), do: "datetime[#{precision_string(p)}, #{tz}]" + def dtype_to_string({:duration, p}), do: "duration[#{precision_string(p)}]" + def dtype_to_string({:list, dtype}), do: "list[" <> dtype_to_string(dtype) <> "]" + def dtype_to_string({:struct, fields}), do: "struct[#{length(fields)}]" + def dtype_to_string({:f, size}), do: "f" <> Integer.to_string(size) + def dtype_to_string({:s, size}), do: "s" <> Integer.to_string(size) + def dtype_to_string({:u, size}), do: "u" <> Integer.to_string(size) + def dtype_to_string({:decimal, precision, scale}), do: "decimal[#{precision}, #{scale}]" + def dtype_to_string(other) when is_atom(other), do: Atom.to_string(other) + + defp precision_string(:millisecond), do: "ms" + defp precision_string(:microsecond), do: "μs" + defp precision_string(:nanosecond), do: "ns" + + @threshold 0.77 + @max_suggestions 5 + + @doc """ + Provides did_you_mean suggestions based on keys. + """ + def did_you_mean(missing_key, available_keys) do + suggestions = + for key <- available_keys, + distance = String.jaro_distance(missing_key, key), + distance >= @threshold, + do: {distance, key} + + case suggestions do + [] -> [". The available columns are: #{inspect(available_keys)}."] + suggestions -> [". Did you mean:\n\n" | format_suggestions(suggestions)] + end + end + + defp format_suggestions(suggestions) do + suggestions + |> Enum.sort(&(elem(&1, 0) >= elem(&2, 0))) + |> Enum.take(@max_suggestions) + |> Enum.sort(&(elem(&1, 1) <= elem(&2, 1))) + |> Enum.map(fn {_, key} -> [" * ", inspect(key), ?\n] end) + end + + @doc """ + Validate options to be used for the various sorting functions. + """ + def validate_sort_options!(opts) do + opts = Keyword.validate!(opts, [:direction, :nils, parallel: true, stable: false]) + + direction = + case Keyword.fetch(opts, :direction) do + {:ok, d} when d in [:asc, :desc] -> + d + + :error -> + :not_provided + + {:ok, x} -> + raise ArgumentError, "`:direction` must be `:asc` or `:desc`, found: #{inspect(x)}." + end + + nils = + case Keyword.fetch(opts, :nils) do + {:ok, n} when n in [:first, :last] -> + n + + :error -> + case direction do + :asc -> :last + :desc -> :first + :not_provided -> :last + end + + {:ok, x} -> + raise ArgumentError, "`:nils` must be `:first` or `:last`, found: #{inspect(x)}." + end + + parallel = + case Keyword.fetch!(opts, :parallel) do + b when is_boolean(b) -> b + x -> raise ArgumentError, "`:parallel` must be `true` or `false`, found: #{inspect(x)}." + end + + stable = + case Keyword.fetch!(opts, :stable) do + b when is_boolean(b) -> b + x -> raise ArgumentError, "`:stable` must be `true` or `false`, found: #{inspect(x)}." + end + + descending? = direction == :desc + maintain_order? = stable == true + multithreaded? = parallel == true + nulls_last? = nils == :last + + [descending?, maintain_order?, multithreaded?, nulls_last?] + end + + ## Apply + + @doc """ + Initializes a series or a dataframe with node placement. + """ + def apply_init(impl, fun, args, opts) do + if node = opts[:node] do + Explorer.Remote.apply(node, impl, fun, [], fn _ -> args end, true) + else + apply(impl, fun, args) + end + end + + @doc """ + Applies a function with args using the implementation of a dataframe or series. + """ + def apply_dataframe(dfs_or_df, fun, args \\ [], place? \\ true) do + {df_nodes, {impl, remote}} = + dfs_or_df + |> List.wrap() + |> Enum.map_reduce({nil, nil}, fn %{data: %impl{}} = df, {acc_impl, acc_remote} -> + {node, remote} = remote_info(df, impl) + {{df, node}, {pick_df_impl(acc_impl, impl), pick_remote(acc_remote, remote)}} + end) + + if remote do + callback = if is_list(dfs_or_df), do: &[&1 | args], else: &[hd(&1) | args] + Explorer.Remote.apply(remote, impl, fun, df_nodes, callback, place?) + else + apply(impl, fun, [dfs_or_df | args]) + end + end + + defp pick_df_impl(nil, struct), do: struct + defp pick_df_impl(struct, struct), do: struct + + defp pick_df_impl(struct1, struct2) do + raise "cannot invoke Explorer.DataFrame function because it relies on two incompatible implementations: " <> + "#{inspect(struct1)} and #{inspect(struct2)}" + end + + @doc """ + Applies a function to a series. + """ + def apply_series(series, fun, args \\ [], place? \\ true) do + apply_series_impl!([series], fun, &(&1 ++ args), place?) + end + + @doc """ + Applies a function to a list of series. + + The list is typically static and it is passed as arguments. + """ + def apply_series_list(fun, series_or_scalars) when is_list(series_or_scalars) do + apply_series_impl!(series_or_scalars, fun, & &1, true) + end + + @doc """ + Applies a function to a list of unknown size of series. + + The list is passed as a varargs to the backend. + """ + def apply_series_varargs(fun, series_or_scalars) when is_list(series_or_scalars) do + apply_series_impl!(series_or_scalars, fun, &[&1], true) + end + + defp apply_series_impl!([_ | _] = series_or_scalars, fun, args_callback, place?) do + {series_nodes, {impl, {_forced?, remote}, transfer?}} = + Enum.map_reduce(series_or_scalars, {nil, {false, nil}, false}, fn + # A lazy series without a resource is treated as a scalar + %{data: %{__struct__: Explorer.Backend.LazySeries, resource: nil}} = series, + {_acc_impl, acc_remote, acc_transfer?} -> + {{series, nil}, {Explorer.Backend.LazySeries, acc_remote, acc_transfer?}} + + %{data: %impl{}} = series, {acc_impl, acc_remote, acc_transfer?} -> + {node, remote} = remote_info(series, impl) + + {{series, node}, + {pick_series_impl(acc_impl, impl), pick_series_remote(acc_remote, impl, remote), + acc_transfer? or remote != nil}} + + scalar, acc -> + {{scalar, nil}, acc} + end) + + if is_nil(impl) do + raise ArgumentError, + "expected a series as argument for #{fun}, got: #{inspect(series_or_scalars)}" <> + maybe_bad_column_hint(series_or_scalars) + end + + if transfer? do + Explorer.Remote.apply(remote || node(), impl, fun, series_nodes, args_callback, place?) + else + apply(impl, fun, args_callback.(series_or_scalars)) + end + end + + # The lazy series always wins the remote if it has one, + # since we need to transfer it to the dataframe that started the lazy series. + defp pick_series_remote(_acc_remote, Explorer.Backend.LazySeries, remote), + do: {true, remote} + + defp pick_series_remote({true, acc_remote}, _impl, _remote), + do: {true, acc_remote} + + defp pick_series_remote({false, acc_remote}, _impl, remote), + do: {false, pick_remote(acc_remote, remote)} + + defp pick_series_impl(nil, impl), do: impl + defp pick_series_impl(Explorer.Backend.LazySeries, _impl), do: Explorer.Backend.LazySeries + defp pick_series_impl(_impl, Explorer.Backend.LazySeries), do: Explorer.Backend.LazySeries + defp pick_series_impl(impl, impl), do: impl + + defp pick_series_impl(acc_impl, impl) do + raise "cannot invoke Explorer function because it relies on two incompatible series: " <> + "#{inspect(acc_impl)} and #{inspect(impl)}" + end + + @doc """ + A hint in case there is a bad column from a query. + """ + def maybe_bad_column_hint(values) do + atom = Enum.find(values, &is_atom(&1)) + + if Kernel.and(atom != nil, String.starts_with?(Atom.to_string(atom), "Elixir.")) do + "\n\nHINT: we have noticed that one of the values is the atom #{inspect(atom)}. " <> + "If you are inside Explorer.Query and you want to access a column starting in uppercase, " <> + "you must write instead: col(\"#{inspect(atom)}\")" + else + "" + end + end + + # There is remote information and it is GCed by the current node. + # Which means that it resides on the remote node given by remote_pid. + defp remote_info(%{remote: {local_gc, remote_pid, _remote_ref}}, _impl) + when node(local_gc) == node(), + do: {node(remote_pid), remote_pid} + + # There is remote information but it is actually local. Treat it as one. + defp remote_info(%{remote: {_local_gc, remote_pid, _remote_ref}}, _impl) + when node(remote_pid) == node(), + do: {node(), nil} + + # We don't know the remote information, let's ask the backend + defp remote_info(df_or_series, impl) do + case impl.owner_reference(df_or_series) do + remote_ref when is_reference(remote_ref) and node(remote_ref) != node() -> + {node(remote_ref), node(remote_ref)} + + _ -> + {node(), nil} + end + end + + # We need to pick a remote, which one does not matter. + # The important is to keep the PID reference around, if there is one. + defp pick_remote(acc_remote, _remote) when is_pid(acc_remote), do: acc_remote + defp pick_remote(acc_remote, nil), do: acc_remote + defp pick_remote(_acc_remote, remote), do: remote +end diff --git a/deps/explorer/lib/explorer/tensor_frame.ex b/deps/explorer/lib/explorer/tensor_frame.ex new file mode 100644 index 0000000000000000000000000000000000000000..c9c122c7011fc4f1879f5932bb27c28133d4a3f8 --- /dev/null +++ b/deps/explorer/lib/explorer/tensor_frame.ex @@ -0,0 +1,295 @@ +if Code.ensure_loaded?(Nx) do + alias Explorer.Series, as: S, warn: false + alias Explorer.DataFrame, as: DF, warn: false + alias Explorer.TensorFrame, as: TF, warn: false + + defmodule Explorer.TensorFrame do + @moduledoc """ + TensorFrame is a representation of `Explorer.DataFrame` + that is designed to work inside Nx's `defn` expressions. + + For example, imagine the following `defn`: + + defn add_columns(tf) do + tf[:a] + tf[:b] + end + + We can now pass a DataFrame as argument: + + iex> add_columns(Explorer.DataFrame.new(a: [11, 12], b: [21, 22])) + #Nx.Tensor< + s64[2] + [32, 34] + > + + Passing an `Explorer.DataFrame` to a `defn` will automatically + convert it to a TensorFrame. The TensorFrame will lazily + build tensors out of the used dataframe fields. + + ## Stack and concatenating + + Due to the integration with Nx, you can also pass dataframes + into `Nx.stack/2` and `Nx.concatenate` and they will be automatically + converted to tensors. This makes it easy to pass dataframes into + neural networks and other computationally intensive algorithms: + + iex> Nx.concatenate(Explorer.DataFrame.new(a: [11, 12], b: [21, 22])) + #Nx.Tensor< + s64[4] + [11, 12, 21, 22] + > + + iex> Nx.stack(Explorer.DataFrame.new(a: [11, 12], b: [21, 22])) + #Nx.Tensor< + s64[2][2] + [ + [11, 12], + [21, 22] + ] + > + + iex> Nx.stack(Explorer.DataFrame.new(a: [11, 12], b: [21, 22]), axis: -1) + #Nx.Tensor< + s64[2][2] + [ + [11, 21], + [12, 22] + ] + > + + ## Warning: returning TensorFrames + + It is not recommended to return a TensorFrame from a `defn`, + as that would force all columns to be sent to the CPU/GPU + and then copied back. Return only the columns that have been + modified during the computation. For example, in the example + above we used `Nx` to add two columns, if you want to + put the result of the computation back into a DataFrame, + you can use `Explorer.DataFrame.put/4`, which also accepts + tensors: + + iex> df = Explorer.DataFrame.new(a: [11, 12], b: [21, 22]) + iex> Explorer.DataFrame.put(df, "result", add_columns(df)) + #Explorer.DataFrame< + Polars[2 x 3] + a s64 [11, 12] + b s64 [21, 22] + result s64 [32, 34] + > + + One benefit of using `Explorer.DataFrame.put/4` is that it will + preserve the type of the column if one already exists. Alternatively, + use `Explorer.Series.from_tensor/1` to explicitly convert a tensor + back to a series. + + ## Supported dtypes + + The following dtypes can be converted to tensors: + + * `:integer` + * `{:f, 32}` + * `{:f, 64}` + * `:boolean` + * `:date` + * `{:naive_datetime, :millisecond}` + * `{:naive_datetime, :microsecond}` + * `{:naive_datetime, :nanosecond}` + + See `Explorer.Series.to_iovec/1` and `Explorer.Series.to_tensor/1` + to learn more about their internal representation. + """ + + @enforce_keys [:data, :names, :n_rows] + defstruct [:data, :names, :n_rows] + @type t :: %__MODULE__{} + @compile {:no_warn_undefined, Nx} + + ## Nx + + import Nx.Defn + + @doc """ + Pulls a tensor from the TensorFrame. + + This is equivalent to using the `tf[name]` to access + a tensor. + + ## Examples + + Explorer.TensorFrame.pull(tf, "some_column") + + """ + deftransform pull(%TF{} = tf, name) do + fetch!(tf, to_column_name(name)) + end + + @doc """ + Puts a tensor in the TensorFrame. + + This function can be invoked from within `defn`. + + ## Examples + + Explorer.TensorFrame.put(tf, "result", some_tensor) + + """ + deftransform put(%TF{} = tf, name, tensor) do + put!(tf, to_column_name(name), tensor) + end + + ## Access + + @behaviour Access + + @impl Access + def fetch(tf, name) do + {:ok, fetch!(tf, to_column_name(name))} + end + + @impl Access + def get_and_update(tf, name, callback) do + name = to_column_name(name) + {get, update} = callback.(fetch!(tf, name)) + {get, put!(tf, name, update)} + end + + @impl Access + def pop(%TF{data: data, names: names} = tf, name) do + name = to_column_name(name) + + {fetch!(tf, name), %{tf | data: Map.delete(data, name), names: names -- [name]}} + end + + defp fetch!(%TF{data: data}, name) when is_binary(name) do + case data do + %{^name => data} -> + data + + %{} -> + raise ArgumentError, + List.to_string([ + "could not find column \"#{name}\" either because it doesn't exist or its dtype is not supported in Explorer.TensorFrame" + | Explorer.Shared.did_you_mean(name, Map.keys(data)) + ]) + end + end + + ## Helpers + + defp to_column_name(name) when is_atom(name), do: Atom.to_string(name) + defp to_column_name(name) when is_binary(name), do: name + + defp to_column_name(name) do + raise ArgumentError, + "Explorer.TensorFrame only accepts atoms and strings as column names, got: #{inspect(name)}" + end + + defp put!(%{n_rows: n_rows, names: names, data: data} = tf, name, value) + when is_binary(name) do + names = if name in names, do: names, else: names ++ [name] + data = Map.put(data, name, value |> Nx.to_tensor() |> broadcast!(n_rows)) + %{tf | names: names, data: data} + end + + defp broadcast!(%{shape: {}} = tensor, n_rows), do: Nx.broadcast(tensor, {n_rows}) + defp broadcast!(%{shape: {1}} = tensor, n_rows), do: Nx.broadcast(tensor, {n_rows}) + defp broadcast!(%{shape: {n_rows}} = tensor, n_rows), do: tensor + + defp broadcast!(tensor, n_rows) do + raise ArgumentError, + "cannot add tensor that does not match the frame size. " <> + "Expected a tensor of shape {#{n_rows}} but got tensor #{inspect(tensor)}" + end + + defimpl Inspect do + import Inspect.Algebra + + def inspect(tf, opts) do + force_unfit( + concat([ + color("#Explorer.TensorFrame<", :map, opts), + nest(concat([line(), inner(tf, opts)]), 2), + line(), + color(">", :map, opts) + ]) + ) + end + + @default_limit 5 + + defp inner(%{data: data, n_rows: n_rows}, opts) do + opts = %{opts | limit: @default_limit} + open = color("[", :list, opts) + close = color("]", :list, opts) + + pairs = + for {name, tensor} <- Enum.sort(data) do + concat([ + line(), + color("#{name} ", :map, opts), + Inspect.Algebra.to_doc(tensor, opts) + ]) + end + + concat([open, "#{n_rows} x #{map_size(data)}", close | pairs]) + end + end + end + + defimpl Nx.LazyContainer, for: S do + def traverse(series, acc, fun) do + size = S.size(series) + template = Nx.template({size}, S.iotype(series)) + fun.(template, fn -> S.to_tensor(series) end, acc) + end + end + + defimpl Nx.LazyContainer, for: DF do + def traverse(df, acc, fun) do + n_rows = DF.n_rows(df) + + {data, acc} = + Enum.flat_map_reduce(DF.names(df), acc, fn name, acc -> + series = df[name] + + case S.iotype(series) do + {_, _} = type -> + template = Nx.template({n_rows}, type) + {result, acc} = fun.(template, fn -> S.to_tensor(series) end, acc) + {[{name, result}], acc} + + :none -> + {[], acc} + end + end) + + {%TF{data: Map.new(data), names: Enum.map(data, &elem(&1, 0)), n_rows: n_rows}, acc} + end + end + + defimpl Nx.Container, for: TF do + def traverse(tf, acc, fun) do + {data, acc} = + Enum.map_reduce(tf.names, acc, fn name, acc -> + {contents, acc} = fun.(tf[name], acc) + {{name, contents}, acc} + end) + + {%{tf | data: Map.new(data)}, acc} + end + + def reduce(tf, acc, fun) do + Enum.reduce(tf.names, acc, fn name, acc -> + fun.(tf[name], acc) + end) + end + + def serialize(%TF{data: data, names: names, n_rows: n_rows}) do + {__MODULE__, Map.to_list(data), {names, n_rows}} + end + + def deserialize(data, {names, n_rows}) do + %TF{data: Map.new(data), names: names, n_rows: n_rows} + end + end +end diff --git a/deps/explorer/mix.exs b/deps/explorer/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..9008fcd8aeccb8f5de6db9d67e12253f34cab6a7 --- /dev/null +++ b/deps/explorer/mix.exs @@ -0,0 +1,136 @@ +defmodule Explorer.MixProject do + use Mix.Project + + @source_url "https://github.com/elixir-nx/explorer" + @version "0.10.1" + @dev? String.ends_with?(@version, "-dev") + @force_build? System.get_env("EXPLORER_BUILD") in ["1", "true"] + + def project do + [ + app: :explorer, + name: "Explorer", + description: + "Series (one-dimensional) and dataframes (two-dimensional) for fast data exploration in Elixir", + version: @version, + elixir: "~> 1.14", + elixirc_paths: elixirc_paths(Mix.env()), + package: package(), + deps: deps(), + docs: docs(), + preferred_cli_env: [ci: :test, "localstack.setup": :test], + aliases: [ + "rust.lint": ["cmd cargo clippy --manifest-path=native/explorer/Cargo.toml -- -Dwarnings"], + "rust.fmt": ["cmd cargo fmt --manifest-path=native/explorer/Cargo.toml --all"], + "localstack.setup": ["cmd ./test/support/setup-localstack.sh"], + ci: ["format", "rust.fmt", "rust.lint", "test"] + ] + ] + end + + def application do + [ + extra_applications: [:logger, :inets, :ssl], + mod: {Explorer.Application, []}, + env: [default_backend: Explorer.PolarsBackend] + ] + end + + defp elixirc_paths(:test), do: ~w(lib test/support) + defp elixirc_paths(_), do: ~w(lib) + + defp deps do + [ + {:aws_signature, "~> 0.3"}, + {:fss, "~> 0.1"}, + {:rustler_precompiled, "~> 0.7"}, + {:table, "~> 0.1.2"}, + {:table_rex, "~> 3.1.1 or ~> 4.0.0"}, + {:decimal, "~> 2.1"}, + + ## Optional + {:flame, "~> 0.3", optional: true}, + {:castore, "~> 1.0", optional: true}, + {:adbc, "~> 0.1", optional: true}, + {:nx, "~> 0.4", optional: true}, + {:rustler, "~> 0.34.0", optional: not (@dev? or @force_build?)}, + + ## Test + {:bypass, "~> 2.1", only: :test}, + {:stream_data, "~> 1.1", only: :test}, + {:tz, "~> 0.26", only: :test}, + + ## Dev + {:ex_doc, "~> 0.24", only: :dev}, + {:benchee, "~> 1.1", only: :dev} + ] + end + + defp docs do + [ + main: "Explorer", + logo: "explorer-exdoc.png", + source_ref: "v#{@version}", + source_url: @source_url, + groups_for_modules: [ + # Explorer, + # Explorer.DataFrame, + # Explorer.Datasets, + # Explorer.Query, + # Explorer.Series, + "Custom data types": [ + Explorer.Duration, + Explorer.TensorFrame + ], + Backends: [ + Explorer.Backend, + Explorer.Backend.DataFrame, + Explorer.Backend.Series, + Explorer.Backend.QueryFrame, + Explorer.Backend.LazySeries, + Explorer.PolarsBackend + ] + ], + groups_for_docs: [ + "Functions: Conversion": &(&1[:type] == :conversion), + "Functions: Single-table": &(&1[:type] == :single), + "Functions: Multi-table": &(&1[:type] == :multi), + "Functions: Row-based": &(&1[:type] == :rows), + "Functions: Aggregation": &(&1[:type] == :aggregation), + "Functions: Element-wise": &(&1[:type] == :element_wise), + "Functions: Datetime ops": &(&1[:type] == :datetime_wise), + "Functions: Float ops": &(&1[:type] == :float_wise), + "Functions: String ops": &(&1[:type] == :string_wise), + "Functions: List ops": &(&1[:type] == :list_wise), + "Functions: Struct ops": &(&1[:type] == :struct_wise), + "Functions: Introspection": &(&1[:type] == :introspection), + "Functions: IO": &(&1[:type] == :io), + "Functions: Shape": &(&1[:type] == :shape), + "Functions: Window": &(&1[:type] == :window) + ], + extras: ["notebooks/exploring_explorer.livemd", "CHANGELOG.md"], + skip_undefined_reference_warnings_on: ["CHANGELOG.md"] + ] + end + + defp package do + [ + files: [ + "lib", + "native", + "datasets", + "checksum-*.exs", + "mix.exs", + "CHANGELOG.md", + "README.md", + "LICENSE" + ], + licenses: ["MIT"], + links: %{ + "GitHub" => @source_url, + "Changelog" => "#{@source_url}/blob/v#{@version}/CHANGELOG.md" + }, + maintainers: ["Christopher Grainger", "Philip Sampaio", "José Valim"] + ] + end +end diff --git a/deps/explorer/native/explorer/.cargo/config.toml b/deps/explorer/native/explorer/.cargo/config.toml new file mode 100644 index 0000000000000000000000000000000000000000..d438576dc63ac095e27425aa70aebbf1b283ddb3 --- /dev/null +++ b/deps/explorer/native/explorer/.cargo/config.toml @@ -0,0 +1,34 @@ +[target.x86_64-apple-darwin] +rustflags = [ + "-C", "link-arg=-undefined", + "-C", "link-arg=dynamic_lookup", +] + +[target.aarch64-apple-darwin] +rustflags = [ + "-C", "link-arg=-undefined", + "-C", "link-arg=dynamic_lookup", +] + +# See https://github.com/rust-lang/rust/issues/59302 +[target.x86_64-unknown-linux-musl] +rustflags = [ + "-C", "target-feature=-crt-static" +] + +# Same as above +[target.aarch64-unknown-linux-musl] +rustflags = [ + "-C", "target-feature=-crt-static" +] + +# Libatomic is needed for 32 bits ARM. +# See: https://github.com/philss/rustler_precompiled/issues/53 +[target.arm-unknown-linux-gnueabihf] +rustflags = [ + "-l", "dylib=atomic" +] + +# Provides a small build size, but takes more time to build. +[profile.release] +lto = true diff --git a/deps/explorer/native/explorer/.gitignore b/deps/explorer/native/explorer/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ea8c4bf7f35f6f77f75d92ad8ce8349f6e81ddba --- /dev/null +++ b/deps/explorer/native/explorer/.gitignore @@ -0,0 +1 @@ +/target diff --git a/deps/explorer/native/explorer/Cargo.lock b/deps/explorer/native/explorer/Cargo.lock new file mode 100644 index 0000000000000000000000000000000000000000..c00a15469b83f212f694f5373ab81470b85038a6 --- /dev/null +++ b/deps/explorer/native/explorer/Cargo.lock @@ -0,0 +1,3266 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "addr2line" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5fb1d8e4442bd405fdfd1dacb42792696b0cf9cb15882e5d097b742a676d375" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" + +[[package]] +name = "ahash" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" +dependencies = [ + "cfg-if", + "getrandom", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "allocator-api2" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86fdf8605db99b54d3cd748a44c6d04df638eb5dafb219b135d0149bd0db01f6" + +[[package]] +name = "argminmax" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52424b59d69d69d5056d508b260553afd91c57e21849579cd1f50ee8b8b88eaa" +dependencies = [ + "num-traits", +] + +[[package]] +name = "array-init-cursor" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf7d0a018de4f6aa429b9d33d69edf69072b1c5b1cb8d3e4a5f7ef898fc3eb76" + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "async-stream" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd56dd203fef61ac097dd65721a419ddccb106b2d2b70ba60a6b529f03961a51" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "async-trait" +version = "0.1.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "atoi_simd" +version = "0.15.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae037714f313c1353189ead58ef9eec30a8e8dc101b2622d461418fd59e28a9" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" + +[[package]] +name = "backtrace" +version = "0.3.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", + "windows-targets", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" +dependencies = [ + "serde", +] + +[[package]] +name = "blake3" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d82033247fd8e890df8f740e407ad4d038debb9eb1f40533fffb32e7d17dc6f7" +dependencies = [ + "arrayref", + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "brotli" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74f7971dbd9326d58187408ab83117d8ac1bb9c17b085fdacd1cf2f598719b6b" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a45bd2e4095a8b518033b128020dd4a55aab1c0a381ba4404a472630f4bc362" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bumpalo" +version = "3.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" + +[[package]] +name = "bytemuck" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94bbb0ad554ad961ddc5da507a12a29b14e4ae5bda06b19f575a3e6079d2e2ae" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc8b54b395f2fcfbb3d90c47b01c7f444d94d05bdeb775811dec868ac3bbc26" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "428d9aa8fbc0670b7b8d6030a7fadd0f86151cae55e4dbbece15f3780a3dfaf3" + +[[package]] +name = "castaway" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0abae9be0aaf9ea96a3b1b8b1b55c602ca751eba1b1500220cea4ecbafe7c0d5" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cc" +version = "1.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9540e661f81799159abee814118cc139a2004b3a3aa3ea37724a1b66530b90e0" +dependencies = [ + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chrono" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" +dependencies = [ + "android-tzdata", + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-targets", +] + +[[package]] +name = "chrono-tz" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d59ae0466b83e838b81a54256c39d5d7c20b9d7daa10510a242d9b75abd5936e" +dependencies = [ + "chrono", + "chrono-tz-build 0.2.1", + "phf", +] + +[[package]] +name = "chrono-tz" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93698b29de5e97ad0ae26447b344c482a7284c737d9ddc5f9e52b74a336671bb" +dependencies = [ + "chrono", + "chrono-tz-build 0.3.0", + "phf", +] + +[[package]] +name = "chrono-tz-build" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "433e39f13c9a060046954e0592a8d0a4bcb1040125cbf91cb8ee58964cfb350f" +dependencies = [ + "parse-zoneinfo", + "phf", + "phf_codegen", +] + +[[package]] +name = "chrono-tz-build" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c088aee841df9c3041febbb73934cfc39708749bf96dc827e3359cd39ef11b1" +dependencies = [ + "parse-zoneinfo", + "phf", + "phf_codegen", +] + +[[package]] +name = "cmake" +version = "0.1.51" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb1e43aa7fd152b1f968787f7dbcdeb306d1867ff373c69955211876c053f91a" +dependencies = [ + "cc", +] + +[[package]] +name = "compact_str" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6050c3a16ddab2e412160b31f2c871015704239bca62f72f6e5f0be631d3f644" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "serde", + "static_assertions", +] + +[[package]] +name = "constant_time_eq" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "crc32fast" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33480d6946193aa8033910124896ca395333cae7e2d1113d1fef6c3272217df2" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df0346b5d5e76ac2fe4e327c5fd1118d6be7c51dfb18f9b7922923f287471e35" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "doc-comment" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10" + +[[package]] +name = "dyn-clone" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d6ef0072f8a535281e4876be788938b528e9a1d43900b82c2569af7da799125" + +[[package]] +name = "either" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" + +[[package]] +name = "enum_dispatch" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd" +dependencies = [ + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + +[[package]] +name = "errno" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "ethnum" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b90ca2580b73ab6a1f724b76ca11ab632df820fd6040c336200d2c1df7b3c82c" + +[[package]] +name = "explorer" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "chrono-tz 0.9.0", + "either", + "mimalloc", + "object_store", + "polars", + "polars-ops", + "rand", + "rand_pcg", + "rustler", + "thiserror", + "tokio", +] + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fast-float" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95765f67b4b18863968b4a1bd5bb576f732b29a4a28c7cd84c09fa3e2875f33c" + +[[package]] +name = "flate2" +version = "1.0.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1b589b4dc103969ad3cf85c950899926ec64300a1a46d76c03a6072957036f0" +dependencies = [ + "crc32fast", + "libz-ng-sys", + "miniz_oxide", +] + +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" +dependencies = [ + "num-traits", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "form_urlencoded" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs4" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8c6b3bd49c37d2aa3f3f2220233b29a7cd23f79d1fe70e5337d25fb390793de" +dependencies = [ + "rustix", + "windows-sys 0.52.0", +] + +[[package]] +name = "futures" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" + +[[package]] +name = "futures-executor" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" + +[[package]] +name = "futures-macro" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "futures-sink" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" + +[[package]] +name = "futures-task" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" + +[[package]] +name = "futures-util" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "gimli" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32085ea23f3234fc7846555e85283ba4de91e21016dc0455a16286d87a292d64" + +[[package]] +name = "glob" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" + +[[package]] +name = "h2" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "524e8ac6999421f49a846c2d4411f337e53497d8ec55d67753beffa43c5d9205" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "halfbrown" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8588661a8607108a5ca69cab034063441a0413a0b041c13618a7dd348021ef6f" +dependencies = [ + "hashbrown", + "serde", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", + "allocator-api2", + "rayon", + "serde", +] + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "home" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" +dependencies = [ + "windows-sys 0.52.0", +] + +[[package]] +name = "http" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" +dependencies = [ + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fcc0b4a115bf80b728eb8ea024ad5bd707b615bfed49e0665b6e0f86fd082d9" + +[[package]] +name = "humantime" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" + +[[package]] +name = "hyper" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97818827ef4f364230e16705d4706e2897df2bb60617d6ca15d598025a3c481f" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333" +dependencies = [ + "futures-util", + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-native-certs", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41296eb09f183ac68eec06e03cdbea2e759633d4067b2f6552fc2e009bcad08b" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "windows-core 0.52.0", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "idna" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "indexmap" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68b900aa2f7301e21c36462b170ee99994de34dff39a4a6a528e80e7376d07e5" +dependencies = [ + "equivalent", + "hashbrown", + "serde", +] + +[[package]] +name = "inventory" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f958d3d68f4167080a18141e10381e7634563984a537f2a49a30fd8e53ac5767" + +[[package]] +name = "ipnet" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "187674a687eed5fe42285b40c6291f9a01517d415fad1c3cbc6a9f778af7fcd4" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" + +[[package]] +name = "itoap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9028f49264629065d057f340a86acb84867925865f73bbf8d47b4d149a7e88b8" + +[[package]] +name = "jobserver" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0" +dependencies = [ + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.70" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "jsonpath_lib_polars_vendor" +version = "0.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4bd9354947622f7471ff713eacaabdb683ccb13bba4edccaab9860abf480b7d" +dependencies = [ + "log", + "serde", + "serde_json", +] + +[[package]] +name = "lexical-core" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0431c65b318a590c1de6b8fd6e72798c92291d27762d94c9e6c37ed7a73d8458" +dependencies = [ + "lexical-parse-float", + "lexical-parse-integer", + "lexical-util", + "lexical-write-float", + "lexical-write-integer", +] + +[[package]] +name = "lexical-parse-float" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb17a4bdb9b418051aa59d41d65b1c9be5affab314a872e5ad7f06231fb3b4e0" +dependencies = [ + "lexical-parse-integer", + "lexical-util", + "static_assertions", +] + +[[package]] +name = "lexical-parse-integer" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df98f4a4ab53bf8b175b363a34c7af608fe31f93cc1fb1bf07130622ca4ef61" +dependencies = [ + "lexical-util", + "static_assertions", +] + +[[package]] +name = "lexical-util" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85314db53332e5c192b6bca611fb10c114a80d1b831ddac0af1e9be1b9232ca0" +dependencies = [ + "static_assertions", +] + +[[package]] +name = "lexical-write-float" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7c3ad4e37db81c1cbe7cf34610340adc09c322871972f74877a712abc6c809" +dependencies = [ + "lexical-util", + "lexical-write-integer", + "static_assertions", +] + +[[package]] +name = "lexical-write-integer" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb89e9f6958b83258afa3deed90b5de9ef68eef090ad5086c791cd2345610162" +dependencies = [ + "lexical-util", + "static_assertions", +] + +[[package]] +name = "libc" +version = "0.2.159" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "561d97a539a36e26a9a5fad1ea11a3039a67714694aaa379433e580854bc3dc5" + +[[package]] +name = "libm" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" + +[[package]] +name = "libmimalloc-sys" +version = "0.1.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23aa6811d3bd4deb8a84dde645f943476d13b248d818edcf8ce0b2f37f036b44" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "libz-ng-sys" +version = "1.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4436751a01da56f1277f323c80d584ffad94a3d14aecd959dd0dff75aa73a438" +dependencies = [ + "cmake", + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" + +[[package]] +name = "lock_api" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" + +[[package]] +name = "lz4" +version = "1.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d1febb2b4a79ddd1980eede06a8f7902197960aa0383ffcfdd62fe723036725" +dependencies = [ + "lz4-sys", +] + +[[package]] +name = "lz4-sys" +version = "1.11.1+lz4-1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bd8c0d6c6ed0cd30b3652886bb8711dc4bb01d637a68105a3d5158039b418e6" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" + +[[package]] +name = "memmap2" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f49388d20533534cd19360ad3d6a7dadc885944aa802ba3995040c5ec11288c6" +dependencies = [ + "libc", +] + +[[package]] +name = "mimalloc" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68914350ae34959d83f732418d51e2427a794055d0b9529f48259ac07af65633" +dependencies = [ + "libmimalloc-sys", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "miniz_oxide" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" +dependencies = [ + "adler2", +] + +[[package]] +name = "mio" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" +dependencies = [ + "hermit-abi", + "libc", + "wasi", + "windows-sys 0.52.0", +] + +[[package]] +name = "multiversion" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4851161a11d3ad0bf9402d90ffc3967bf231768bfd7aeb61755ad06dbf1a142" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79a74ddee9e0c27d2578323c13905793e91622148f138ba29738f9dddb835e90" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", + "target-features", +] + +[[package]] +name = "now" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d89e9874397a1f0a52fc1f197a8effd9735223cb2390e9dcc83ac6cd02923d0" +dependencies = [ + "chrono", +] + +[[package]] +name = "ntapi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8a3895c6391c39d7fe7ebc444a87eb2991b2a0bc718fdabd071eec617fc68e4" +dependencies = [ + "winapi", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "object" +version = "0.36.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "084f1a5821ac4c651660a94a7153d27ac9d8a53736203f58b31945ded098070a" +dependencies = [ + "memchr", +] + +[[package]] +name = "object_store" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6da452820c715ce78221e8202ccc599b4a52f3e1eb3eedb487b680c81a8e3f3" +dependencies = [ + "async-trait", + "base64", + "bytes", + "chrono", + "futures", + "humantime", + "hyper", + "itertools", + "md-5", + "parking_lot", + "percent-encoding", + "quick-xml", + "rand", + "reqwest", + "ring", + "serde", + "serde_json", + "snafu", + "tokio", + "tracing", + "url", + "walkdir", +] + +[[package]] +name = "once_cell" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" + +[[package]] +name = "openssl-probe" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" + +[[package]] +name = "parking_lot" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets", +] + +[[package]] +name = "parquet-format-safe" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1131c54b167dd4e4799ce762e1ab01549ebb94d5bdd13e6ec1b467491c378e1f" +dependencies = [ + "async-trait", + "futures", +] + +[[package]] +name = "parse-zoneinfo" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f2a05b18d44e2957b88f96ba460715e295bc1d7510468a2f3d3b44535d26c24" +dependencies = [ + "regex", +] + +[[package]] +name = "percent-encoding" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" + +[[package]] +name = "phf" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" +dependencies = [ + "phf_shared", + "rand", +] + +[[package]] +name = "phf_shared" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" + +[[package]] +name = "planus" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1691dd09e82f428ce8d6310bd6d5da2557c82ff17694d2a32cad7242aea89f" +dependencies = [ + "array-init-cursor", +] + +[[package]] +name = "polars" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e248cf2f0069277f8fe80d413cfb9240c7dd1cfa382b5674c1b4afa57222747" +dependencies = [ + "getrandom", + "polars-arrow", + "polars-core", + "polars-error", + "polars-io", + "polars-lazy", + "polars-ops", + "polars-parquet", + "polars-sql", + "polars-time", + "polars-utils", + "version_check", +] + +[[package]] +name = "polars-arrow" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2981d5b2f34c84069a39fceca0d36dffeb97db8cadba101e7ea6605c8d42294d" +dependencies = [ + "ahash", + "atoi", + "atoi_simd", + "bytemuck", + "chrono", + "chrono-tz 0.8.6", + "dyn-clone", + "either", + "ethnum", + "fast-float", + "futures", + "getrandom", + "hashbrown", + "itoa", + "itoap", + "lz4", + "multiversion", + "num-traits", + "parking_lot", + "polars-arrow-format", + "polars-error", + "polars-schema", + "polars-utils", + "ryu", + "serde", + "simdutf8", + "streaming-iterator", + "strength_reduce", + "version_check", + "zstd", +] + +[[package]] +name = "polars-arrow-format" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b0ef2474af9396b19025b189d96e992311e6a47f90c53cd998b36c4c64b84c" +dependencies = [ + "planus", + "serde", +] + +[[package]] +name = "polars-compute" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a97b2a5c9b880ab7e52553c40a336fdb6e3244bf896b4d4917700defe8085d5" +dependencies = [ + "bytemuck", + "either", + "num-traits", + "polars-arrow", + "polars-error", + "polars-utils", + "strength_reduce", + "version_check", +] + +[[package]] +name = "polars-core" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5bc2cadcca904a9dc4d2c2b437c346712806e9a678bf17c7e94ebf622faae76" +dependencies = [ + "ahash", + "bitflags", + "bytemuck", + "chrono", + "chrono-tz 0.8.6", + "either", + "hashbrown", + "indexmap", + "num-traits", + "once_cell", + "polars-arrow", + "polars-compute", + "polars-error", + "polars-row", + "polars-schema", + "polars-utils", + "rand", + "rand_distr", + "rayon", + "regex", + "serde", + "thiserror", + "version_check", + "xxhash-rust", +] + +[[package]] +name = "polars-error" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56b0a8eb9b1e56a4640de6887d613cb4de73c4e09d491f3b779855d4c3bcb9ba" +dependencies = [ + "object_store", + "polars-arrow-format", + "regex", + "simdutf8", + "thiserror", +] + +[[package]] +name = "polars-expr" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34e9c0e8c7ba93aac64051b92dc68eac5a0e9543cf44ca784467db2c035821fe" +dependencies = [ + "ahash", + "bitflags", + "once_cell", + "polars-arrow", + "polars-compute", + "polars-core", + "polars-io", + "polars-ops", + "polars-plan", + "polars-time", + "polars-utils", + "rayon", +] + +[[package]] +name = "polars-io" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "454ebbebe1cb8cb4768adca44b8fc9431abc3c91d5927f6824e73f916bced911" +dependencies = [ + "ahash", + "async-trait", + "atoi_simd", + "blake3", + "bytes", + "chrono", + "chrono-tz 0.8.6", + "fast-float", + "flate2", + "fs4", + "futures", + "glob", + "hashbrown", + "home", + "itoa", + "memchr", + "memmap2", + "num-traits", + "object_store", + "once_cell", + "percent-encoding", + "polars-arrow", + "polars-core", + "polars-error", + "polars-json", + "polars-parquet", + "polars-schema", + "polars-time", + "polars-utils", + "rayon", + "regex", + "reqwest", + "ryu", + "serde", + "serde_json", + "simd-json", + "simdutf8", + "tokio", + "tokio-util", + "url", + "zstd", +] + +[[package]] +name = "polars-json" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca086fbbff6e46efbc97032e93f92690c1fc9c662fd5e1f13a42922bd7d3aa4" +dependencies = [ + "ahash", + "chrono", + "chrono-tz 0.8.6", + "fallible-streaming-iterator", + "hashbrown", + "indexmap", + "itoa", + "num-traits", + "polars-arrow", + "polars-error", + "polars-utils", + "ryu", + "simd-json", + "streaming-iterator", +] + +[[package]] +name = "polars-lazy" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e61c062e833d2376de0a4cf745504449215cbf499cea293cb592e674ffb39ca" +dependencies = [ + "ahash", + "bitflags", + "futures", + "memchr", + "once_cell", + "polars-arrow", + "polars-core", + "polars-expr", + "polars-io", + "polars-json", + "polars-mem-engine", + "polars-ops", + "polars-pipe", + "polars-plan", + "polars-time", + "polars-utils", + "rayon", + "tokio", + "version_check", +] + +[[package]] +name = "polars-mem-engine" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0643812829cc990e1533a5bf48c21a1b3eaa46aabf2967b0f53f99097cbc74c" +dependencies = [ + "futures", + "memmap2", + "polars-arrow", + "polars-core", + "polars-error", + "polars-expr", + "polars-io", + "polars-json", + "polars-ops", + "polars-plan", + "polars-time", + "polars-utils", + "rayon", + "tokio", +] + +[[package]] +name = "polars-ops" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ac14a136d87bea798f3db51d5987556deb2293da34bfc8b105ebffa05f6e810" +dependencies = [ + "ahash", + "argminmax", + "base64", + "bytemuck", + "chrono", + "chrono-tz 0.8.6", + "either", + "hashbrown", + "hex", + "indexmap", + "jsonpath_lib_polars_vendor", + "memchr", + "num-traits", + "polars-arrow", + "polars-compute", + "polars-core", + "polars-error", + "polars-json", + "polars-schema", + "polars-utils", + "rand", + "rand_distr", + "rayon", + "regex", + "serde_json", + "unicode-reverse", + "version_check", +] + +[[package]] +name = "polars-parquet" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "491f5af321169259d5b1294c9fe8ed89faaeac34b4dec4abcedc0d1b3d11013a" +dependencies = [ + "ahash", + "async-stream", + "base64", + "brotli", + "bytemuck", + "ethnum", + "flate2", + "futures", + "hashbrown", + "lz4", + "num-traits", + "parquet-format-safe", + "polars-arrow", + "polars-compute", + "polars-error", + "polars-utils", + "serde", + "simdutf8", + "snap", + "streaming-decompression", + "zstd", +] + +[[package]] +name = "polars-pipe" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29215c31f599295cc0f803c42fc812cc518db6d5ed4d6c7cc03daf3976a0add5" +dependencies = [ + "crossbeam-channel", + "crossbeam-queue", + "enum_dispatch", + "futures", + "hashbrown", + "num-traits", + "polars-arrow", + "polars-compute", + "polars-core", + "polars-expr", + "polars-io", + "polars-ops", + "polars-plan", + "polars-row", + "polars-utils", + "rayon", + "tokio", + "uuid", + "version_check", +] + +[[package]] +name = "polars-plan" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3f728df4bc643492a2057a0a125c7e550cbcfe35b391444653ad294be9ab190" +dependencies = [ + "ahash", + "bitflags", + "bytemuck", + "bytes", + "chrono", + "chrono-tz 0.8.6", + "either", + "futures", + "hashbrown", + "memmap2", + "once_cell", + "percent-encoding", + "polars-arrow", + "polars-core", + "polars-io", + "polars-json", + "polars-ops", + "polars-parquet", + "polars-time", + "polars-utils", + "rayon", + "recursive", + "regex", + "strum_macros", + "version_check", +] + +[[package]] +name = "polars-row" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4eb931f0929ca7498b3ed5056357d2d364cad42cce95383a7e3983dbceb4bed1" +dependencies = [ + "bytemuck", + "polars-arrow", + "polars-error", + "polars-utils", +] + +[[package]] +name = "polars-schema" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c7e1234b942d3244024ecbac9c7f5a48a52a815f8ca4b9d075fbba16afb1a39" +dependencies = [ + "indexmap", + "polars-error", + "polars-utils", + "serde", + "version_check", +] + +[[package]] +name = "polars-sql" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce52bfd2ef1e2e18ac26d7d7ea3f9132b199cff06d975156703fa5badcfae187" +dependencies = [ + "hex", + "once_cell", + "polars-arrow", + "polars-core", + "polars-error", + "polars-lazy", + "polars-ops", + "polars-plan", + "polars-time", + "polars-utils", + "rand", + "serde", + "serde_json", + "sqlparser", +] + +[[package]] +name = "polars-time" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9925ab75e1d859ae2283ca09d7683198b0b9ff5afecd03f2c9180f3e36e35056" +dependencies = [ + "atoi", + "bytemuck", + "chrono", + "chrono-tz 0.8.6", + "now", + "once_cell", + "polars-arrow", + "polars-core", + "polars-error", + "polars-ops", + "polars-utils", + "regex", +] + +[[package]] +name = "polars-utils" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b44846e1fc6ae1dfdc7f65a37af7d270d0a6a17a58fff76716561f5b887a8ad7" +dependencies = [ + "ahash", + "bytemuck", + "bytes", + "compact_str", + "hashbrown", + "indexmap", + "libc", + "memmap2", + "num-traits", + "once_cell", + "polars-error", + "raw-cpuid", + "rayon", + "serde", + "stacker", + "sysinfo", + "version_check", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "psm" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa37f80ca58604976033fae9515a8a2989fc13797d953f7c04fb8fa36a11f205" +dependencies = [ + "cc", +] + +[[package]] +name = "quick-xml" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7649a7b4df05aed9ea7ec6f628c67c9953a43869b8bc50929569b2999d443fe" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "quinn" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7c5fdde3cdae7203427dc4f0a68fe0ed09833edc525a03456b153b79828684" +dependencies = [ + "bytes", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", +] + +[[package]] +name = "quinn-proto" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fadfaed2cd7f389d0161bb73eeb07b7b78f8691047a6f3e73caaeae55310a4a6" +dependencies = [ + "bytes", + "rand", + "ring", + "rustc-hash", + "rustls", + "slab", + "thiserror", + "tinyvec", + "tracing", +] + +[[package]] +name = "quinn-udp" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fe68c2e9e1a1234e218683dbdf9f9dfcb094113c5ac2b938dfcb9bab4c4140b" +dependencies = [ + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.59.0", +] + +[[package]] +name = "quote" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rand_distr" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" +dependencies = [ + "num-traits", + "rand", +] + +[[package]] +name = "rand_pcg" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e" +dependencies = [ + "rand_core", +] + +[[package]] +name = "raw-cpuid" +version = "11.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb9ee317cfe3fbd54b36a511efc1edd42e216903c9cd575e686dd68a2ba90d8d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "rayon" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "recursive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0786a43debb760f491b1bc0269fe5e84155353c67482b9e60d0cfb596054b43e" +dependencies = [ + "recursive-proc-macro-impl", + "stacker", +] + +[[package]] +name = "recursive-proc-macro-impl" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76009fbe0614077fc1a2ce255e3a1881a2e3a3527097d5dc6d8212c585e7e38b" +dependencies = [ + "quote", + "syn 2.0.89", +] + +[[package]] +name = "redox_syscall" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "355ae415ccd3a04315d3f8246e86d67689ea74d88d915576e1589a351062a13b" +dependencies = [ + "bitflags", +] + +[[package]] +name = "ref-cast" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf0a6f84d5f1d581da8b41b47ec8600871962f2a528115b542b362d4b744931" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcc303e793d3734489387d205e9b186fac9c6cfacedd98cbb2e8a5943595f3e6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "regex" +version = "1.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4219d74c6b67a3654a9fbebc4b419e22126d13d2f3c4a07ee0cb61ff79a79619" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" + +[[package]] +name = "reqwest" +version = "0.12.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a77c62af46e79de0a562e1a9849205ffcb7fc1238876e9bd743357570e04046f" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "ipnet", + "js-sys", + "log", + "mime", + "once_cell", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-native-certs", + "rustls-pemfile", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "windows-registry", +] + +[[package]] +name = "ring" +version = "0.17.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "spin", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" + +[[package]] +name = "rustc-hash" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "583034fd73374156e66797ed8e5b0d5690409c9226b22d87cb7f19821c05d152" + +[[package]] +name = "rustix" +version = "0.38.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8acb788b847c24f28525660c4d7758620a7210875711f79e7f663cc152726811" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustler" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e94bdfa68c0388cbd725f1ca54e975956482c262599e5cced04a903eec918b7f" +dependencies = [ + "inventory", + "rustler_codegen", + "rustler_sys", +] + +[[package]] +name = "rustler_codegen" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "996dc019acb78b91b4e0c1bd6fa2cd509a835d309de762dc15213b97eac399da" +dependencies = [ + "heck 0.5.0", + "inventory", + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "rustler_sys" +version = "2.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd0e2c955cfc86ea4680067e1d5e711427b43f7befcb6e23c7807cf3dd90e97" +dependencies = [ + "regex", + "unreachable", +] + +[[package]] +name = "rustls" +version = "0.23.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "934b404430bb06b3fae2cba809eb45a1ab1aecd64491213d7c3301b88393f8d1" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcaf18a4f2be7326cd874a5fa579fae794320a0f388d365dca7e480e55f83f8a" +dependencies = [ + "openssl-probe", + "rustls-pemfile", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pemfile" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "196fe16b00e106300d3e45ecfcb764fa292a535d7326a29a5875c579c7417425" +dependencies = [ + "base64", + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16f1201b3c9a7ee8039bcadc17b7e605e2945b27eee7631788c1bd2b0643674b" + +[[package]] +name = "rustls-webpki" +version = "0.102.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "955d28af4278de8121b7ebeb796b6a45735dc01436d898801014aced2773a3d6" + +[[package]] +name = "ryu" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9aaafd5a2b6e3d657ff009d82fbd630b6bd54dd4eb06f21693925cdf80f9b8b" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea4a292869320c0272d7bc55a5a6aafaff59b4f63404a003887b679a2e05b4b6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "serde" +version = "1.0.210" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8e3592472072e6e22e0a54d5904d9febf8508f65fb8552499a1abc7d1078c3a" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.210" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "243902eda00fad750862fc144cea25caca5e20d615af0a81bee94ca738f1df1f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "serde_json" +version = "1.0.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ff5456707a1de34e7e37f2a6fd3d3f808c318259cbd01ab6377795054b483d8" +dependencies = [ + "indexmap", + "itoa", + "memchr", + "ryu", + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "simd-json" +version = "0.13.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0228a564470f81724e30996bbc2b171713b37b15254a6440c7e2d5449b95691" +dependencies = [ + "ahash", + "getrandom", + "halfbrown", + "lexical-core", + "once_cell", + "ref-cast", + "serde", + "serde_json", + "simdutf8", + "value-trait", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + +[[package]] +name = "slab" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" +dependencies = [ + "autocfg", +] + +[[package]] +name = "smallvec" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" + +[[package]] +name = "snafu" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4de37ad025c587a29e8f3f5605c00f70b98715ef90b9061a815b9e59e9042d6" +dependencies = [ + "doc-comment", + "snafu-derive", +] + +[[package]] +name = "snafu-derive" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990079665f075b699031e9c08fd3ab99be5029b96f3b78dc0709e8f77e4efebf" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "snap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b6b67fb9a61334225b5b790716f609cd58395f895b3fe8b328786812a40bc3b" + +[[package]] +name = "socket2" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + +[[package]] +name = "sqlparser" +version = "0.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4a404d0e14905361b918cb8afdb73605e25c1d5029312bd9785142dcb3aa49e" +dependencies = [ + "log", +] + +[[package]] +name = "stacker" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799c883d55abdb5e98af1a7b3f23b9b6de8ecada0ecac058672d7635eb48ca7b" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.59.0", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "streaming-decompression" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf6cc3b19bfb128a8ad11026086e31d3ce9ad23f8ea37354b31383a187c44cf3" +dependencies = [ + "fallible-streaming-iterator", +] + +[[package]] +name = "streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" + +[[package]] +name = "strength_reduce" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.89", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d46482f1c1c87acd84dea20c1bf5ebff4c757009ed6bf19cfd36fb10e92c4e" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" +dependencies = [ + "futures-core", +] + +[[package]] +name = "sysinfo" +version = "0.31.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "355dbe4f8799b304b05e1b0f05fc59b2a18d36645cf169607da45bde2f69a1be" +dependencies = [ + "core-foundation-sys", + "libc", + "memchr", + "ntapi", + "windows", +] + +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + +[[package]] +name = "thiserror" +version = "1.0.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d50af8abc119fb8bb6dbabcfa89656f46f84aa0ac7688088608076ad2b459a84" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08904e7672f5eb876eaaf87e0ce17857500934f4981c4a0ab2b4aa98baac7fc3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "tinyvec" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.41.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cfb5bee7a6a52939ca9224d6ac897bb669134078daa8735560897f69de4d33" +dependencies = [ + "backtrace", + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.52.0", +] + +[[package]] +name = "tokio-macros" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" +dependencies = [ + "rustls", + "rustls-pki-types", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61e7c3654c13bcd040d4a03abee2c75b1d14a37b423cf5a813ceae1cc903ec6a" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "tracing-core" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" + +[[package]] +name = "unicode-bidi" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" + +[[package]] +name = "unicode-ident" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" + +[[package]] +name = "unicode-normalization" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5033c97c4262335cded6d6fc3e5c18ab755e1a3dc96376350f3d8e9f009ad956" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-reverse" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b6f4888ebc23094adfb574fdca9fdc891826287a6397d2cd28802ffd6f20c76" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "unicode-segmentation" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" + +[[package]] +name = "unreachable" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "382810877fe448991dfc7f0dd6e3ae5d58088fd0ea5e35189655f84e6814fa56" +dependencies = [ + "void", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", +] + +[[package]] +name = "uuid" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81dfa00651efa65069b0b6b651f4aaa31ba9e3c3ce0137aaad053604ee7e0314" +dependencies = [ + "getrandom", +] + +[[package]] +name = "value-trait" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dad8db98c1e677797df21ba03fca7d3bf9bec3ca38db930954e4fe6e1ea27eb4" +dependencies = [ + "float-cmp", + "halfbrown", + "itoa", + "ryu", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5" +dependencies = [ + "cfg-if", + "once_cell", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.89", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61e9300f63a621e96ed275155c108eb6f843b6a26d053f122ab69724559dc8ed" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484" + +[[package]] +name = "wasm-streams" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b65dc4c90b63b118468cf747d8bf3566c1913ef60be765b5730ead9e0a3ba129" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.70" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26fdeaafd9bd129f65e7c031593c24d62186301e0c72c8978fa1678be7d532c0" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143" +dependencies = [ + "windows-core 0.57.0", + "windows-targets", +] + +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-core" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-result 0.1.2", + "windows-targets", +] + +[[package]] +name = "windows-implement" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "windows-interface" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "windows-registry" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e400001bb720a623c1c69032f8e3e4cf09984deec740f007dd2b03ec864804b0" +dependencies = [ + "windows-result 0.2.0", + "windows-strings", + "windows-targets", +] + +[[package]] +name = "windows-result" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-result" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-strings" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" +dependencies = [ + "windows-result 0.2.0", + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "xxhash-rust" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a5cbf750400958819fb6178eaa83bee5cd9c29a26a40cc241df8c70fdd46984" + +[[package]] +name = "zerocopy" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" +dependencies = [ + "byteorder", + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "zeroize" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" + +[[package]] +name = "zstd" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcf2b778a664581e31e389454a7072dab1647606d44f7feea22cd5abb9c9f3f9" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54a3ab4db68cea366acc5c897c7b4d4d1b8994a9cd6e6f841f8964566a419059" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.13+zstd.1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38ff0f21cfee8f97d94cef41359e0c89aa6113028ab0291aa8ca0038995a95aa" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/deps/explorer/native/explorer/Cargo.toml b/deps/explorer/native/explorer/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..1abe37d3ec1d4ed1efc921e7b0771f8cb22504fa --- /dev/null +++ b/deps/explorer/native/explorer/Cargo.toml @@ -0,0 +1,101 @@ +[package] +name = "explorer" +# We don't use versioning in the in this crate. +# Please check the `mix.exs` file at the root of this project for the current version. +version = "0.1.0" +authors = [] +edition = "2021" + +[lib] +name = "explorer" +path = "src/lib.rs" +crate-type = ["cdylib"] + +[dependencies] +anyhow = "1" +chrono = "0.4" +chrono-tz = "0.9" +rand = { version = "0.8", features = ["alloc"] } +rand_pcg = "0.3" +rustler = { version = "0.34.0" } +thiserror = "1" +either = "1" + +# Deps necessary for cloud features. +tokio = { version = "1.40", default-features = false, features = [ + "rt", +], optional = true } +object_store = { version = "0.10", default-features = false, optional = true } + +# MiMalloc won´t compile on Windows with the GCC compiler. +# On Linux with Musl it won´t load correctly. +[target.'cfg(not(any(all(windows, target_env = "gnu"), all(target_os = "linux", target_env = "musl"))))'.dependencies] +mimalloc = { version = "*", default-features = false } + +[dependencies.polars] +version = "0.43" +default-features = false +features = [ + "abs", + "checked_arithmetic", + "concat_str", + "cov", + "cross_join", + "csv", + "cum_agg", + "cutqcut", + "decompress-fast", + "describe", + "dtype-full", + "ewma", + "extract_groups", + "extract_jsonpath", + "ipc_streaming", + "ipc", + "is_in", + "lazy", + "log", + "mode", + "moment", + "parquet", + "peaks", + "performant", + "pivot", + "product", + "propagate_nans", + "random", + "range", + "rank", + "regex", + "rolling_window", + "round_series", + "rows", + "simd", + "sql", + "streaming", + "strings", + "temporal", + "timezones", + "to_dummies", + "trigonometry", +] + +[dependencies.polars-ops] +version = "0.43" +features = ["abs", "ewma", "cum_agg", "cov"] + +[features] +default = ["ndjson", "cloud", "nif_version_2_15"] + +cloud = [ + "object_store", + "tokio", + "aws", + "polars/cloud", + "polars/cloud_write", +] +ndjson = ["polars/json"] +aws = ["object_store/aws", "polars/async", "polars/aws"] + +# Feature necessary for Rustler Precompiled. +nif_version_2_15 = ["rustler/nif_version_2_15"] diff --git a/deps/explorer/native/explorer/Cross.toml b/deps/explorer/native/explorer/Cross.toml new file mode 100644 index 0000000000000000000000000000000000000000..2c0e4bb4a8284328409f5930c073864a3ea69767 --- /dev/null +++ b/deps/explorer/native/explorer/Cross.toml @@ -0,0 +1,5 @@ +[build.env] +passthrough = [ + "RUSTLER_NIF_VERSION", + "RUSTFLAGS" +] diff --git a/deps/explorer/native/explorer/rust-toolchain.toml b/deps/explorer/native/explorer/rust-toolchain.toml new file mode 100644 index 0000000000000000000000000000000000000000..18298500e27e0440115cd38ec8ce10d07264a480 --- /dev/null +++ b/deps/explorer/native/explorer/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "nightly-2024-07-26" +components = ["rustfmt", "clippy"] +profile = "minimal" diff --git a/deps/explorer/native/explorer/src/cloud_writer.rs b/deps/explorer/native/explorer/src/cloud_writer.rs new file mode 100644 index 0000000000000000000000000000000000000000..fecced8c8d4241d38a0b141b8e8fb0023cf4b7bf --- /dev/null +++ b/deps/explorer/native/explorer/src/cloud_writer.rs @@ -0,0 +1,112 @@ +use crate::ExplorerError; +use object_store::path::Path; +use object_store::{ObjectMeta, ObjectStore}; +use std::sync::Arc; + +use object_store::buffered::BufWriter as OSBufWriter; +use tokio::io::AsyncWriteExt; + +#[derive(Debug, PartialEq)] +enum CloudWriterStatus { + Running, + Stopped, + Aborted, +} +/// CloudWriter wraps the asynchronous interface of [ObjectStore's BufWriter](https://docs.rs/object_store/latest/object_store/buffered/struct.BufWriter.html) +/// in a synchronous interface which implements `std::io::Write`. +/// +/// This allows it to be used in sync code which would otherwise write to a simple File or byte stream, +/// such as with `polars::prelude::CsvWriter`. +pub struct CloudWriter { + // The Tokio runtime which the writer uses internally. + runtime: tokio::runtime::Runtime, + // Internal writer, constructed at creation + writer: OSBufWriter, + // The copy of the object_store + object_store: Arc, + // Keep the path for the file, so we can use to read head. + path: Path, + // Private status of the current writer + status: CloudWriterStatus, +} + +impl CloudWriter { + /// Construct a new CloudWriter + /// + /// Creates a new (current-thread) Tokio runtime + /// which bridges the sync writing process with the async ObjectStore uploading. + pub fn new(object_store: Arc, path: Path) -> Result { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_time() + .enable_io() + .build()?; + let writer = OSBufWriter::new(object_store.clone(), path.clone()); + + Ok(CloudWriter { + writer, + runtime, + object_store, + path, + status: CloudWriterStatus::Running, + }) + } + + /// Make a head request to check if the upload has finished. + pub fn finish(&mut self) -> Result { + if self.status != CloudWriterStatus::Stopped { + self.status = CloudWriterStatus::Stopped; + let _ = self.runtime.block_on(self.writer.shutdown()); + self.runtime + .block_on(self.object_store.head(&self.path)) + .map_err(|err| { + ExplorerError::Other(format!( + "cannot read information from file, which means the upload failed. {err}" + )) + }) + } else { + Err(ExplorerError::Other( + "cannot finish cloud writer due to an error, or it was already finished.".into(), + )) + } + } +} + +impl std::io::Write for CloudWriter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + // SAFETY: + // We extend the lifetime for the duration of this function. This is safe as well block the + // async runtime here + // This was copied from Polars' own CloudWriter. + let buf = unsafe { std::mem::transmute::<&[u8], &'static [u8]>(buf) }; + + self.runtime.block_on(async { + // TODO: use writer.put to avoid copying data + let res = self.writer.write(buf).await; + if res.is_err() { + let _ = self.writer.abort().await; + self.status = CloudWriterStatus::Aborted; + } + res + }) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.runtime.block_on(async { + let res = self.writer.flush().await; + if res.is_err() { + let _ = self.writer.abort().await; + self.status = CloudWriterStatus::Aborted; + } + res + }) + } +} + +impl Drop for CloudWriter { + fn drop(&mut self) { + if self.status != CloudWriterStatus::Stopped { + self.status = CloudWriterStatus::Stopped; + let _ = self.runtime.block_on(self.writer.shutdown()); + } + } +} diff --git a/deps/explorer/native/explorer/src/dataframe.rs b/deps/explorer/native/explorer/src/dataframe.rs new file mode 100644 index 0000000000000000000000000000000000000000..4b80591e8f80aa1e324404923fdfe24601900bd5 --- /dev/null +++ b/deps/explorer/native/explorer/src/dataframe.rs @@ -0,0 +1,481 @@ +use polars::prelude::*; +use polars_ops::pivot::{pivot_stable, PivotAgg}; + +use polars::export::{arrow, arrow::ffi}; +use std::collections::HashMap; + +use crate::datatypes::ExSeriesDtype; +use crate::ex_expr_to_exprs; +use crate::{ExDataFrame, ExExpr, ExLazyFrame, ExSeries, ExplorerError}; +use either::Either; + +// Loads the IO functions for read/writing CSV, NDJSON, Parquet, etc. +pub mod io; + +fn to_string_names(names: Vec<&str>) -> Vec { + names.into_iter().map(|s| s.to_string()).collect() +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_transpose( + df: ExDataFrame, + keep_names_as: Option<&str>, + new_col_names: Option>, +) -> Result { + let column_names = new_col_names.map(Either::Right); + let new_df = df.clone_inner().transpose(keep_names_as, column_names)?; + Ok(ExDataFrame::new(new_df)) +} + +#[rustler::nif] +pub fn df_names(df: ExDataFrame) -> Result, ExplorerError> { + let names = df + .get_column_names() + .iter() + .map(|name| name.to_string()) + .collect(); + Ok(names) +} + +#[rustler::nif] +pub fn df_dtypes(df: ExDataFrame) -> Result, ExplorerError> { + let mut dtypes: Vec = vec![]; + + for dtype in df.dtypes().iter() { + dtypes.push(ExSeriesDtype::try_from(dtype)?) + } + + Ok(dtypes) +} + +#[rustler::nif] +pub fn df_shape(df: ExDataFrame) -> Result<(usize, usize), ExplorerError> { + Ok(df.shape()) +} + +#[rustler::nif] +pub fn df_n_rows(df: ExDataFrame) -> Result { + Ok(df.height()) +} + +#[rustler::nif] +pub fn df_width(df: ExDataFrame) -> Result { + Ok(df.width()) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_concat_columns(dfs: Vec) -> Result { + let mut previous_names = PlHashSet::new(); + + let cols = dfs + .iter() + .enumerate() + .flat_map(|(idx, ex_df)| { + let df = ex_df.clone_inner(); + + df.get_columns() + .iter() + .map(|col| { + let name = col.name(); + if previous_names.contains(&name.clone().to_string()) { + let new_name = format!("{name}_{idx}"); + previous_names.insert(new_name.clone()); + col.clone().rename(new_name.into()).to_owned() + } else { + previous_names.insert(name.to_string()); + col.clone().to_owned() + } + }) + .collect::>() + }) + .collect::>(); + + let out_df = DataFrame::new(cols)?; + + Ok(ExDataFrame::new(out_df)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_drop(df: ExDataFrame, name: &str) -> Result { + let new_df = df.drop(name)?; + Ok(ExDataFrame::new(new_df)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_select_at_idx(df: ExDataFrame, idx: usize) -> Result, ExplorerError> { + let result = df.select_at_idx(idx).map(|s| ExSeries::new(s.clone())); + Ok(result) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_pull(df: ExDataFrame, name: &str) -> Result { + let series = df.column(name).map(|s| ExSeries::new(s.clone()))?; + Ok(series) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_mask(df: ExDataFrame, mask: ExSeries) -> Result { + if let Ok(ca) = mask.bool() { + let new_df = df.filter(ca)?; + Ok(ExDataFrame::new(new_df)) + } else { + Err(ExplorerError::Other("Expected a boolean mask".into())) + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_slice_by_indices( + df: ExDataFrame, + indices: Vec, + groups: Vec<&str>, +) -> Result { + let idx = UInt32Chunked::from_vec("idx".into(), indices); + let new_df = if groups.is_empty() { + df.take(&idx)? + } else { + df.group_by_stable(groups)?.apply(|df| df.take(&idx))? + }; + Ok(ExDataFrame::new(new_df)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_slice_by_series( + df: ExDataFrame, + series: ExSeries, + groups: Vec<&str>, +) -> Result { + match series.strict_cast(&DataType::UInt32) { + Ok(casted) => { + let idx = casted.u32()?; + + let new_df = if groups.is_empty() { + df.take(idx)? + } else { + df.group_by_stable(groups)?.apply(|df| df.take(idx))? + }; + + Ok(ExDataFrame::new(new_df)) + } + Err(_) => Err(ExplorerError::Other( + "slice/2 expects a series of positive integers".into(), + )), + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_sample_n( + df: ExDataFrame, + n: u64, + replace: bool, + shuffle: bool, + seed: Option, + groups: Vec, +) -> Result { + let n_s = Series::new("n".into(), &[n]); + let new_df = if groups.is_empty() { + df.sample_n(&n_s, replace, shuffle, seed)? + } else { + df.group_by_stable(groups)? + .apply(|df| df.sample_n(&n_s, replace, shuffle, seed))? + }; + + Ok(ExDataFrame::new(new_df)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_sample_frac( + df: ExDataFrame, + frac: f64, + replace: bool, + shuffle: bool, + seed: Option, + groups: Vec, +) -> Result { + let frac_s = Series::new("frac".into(), &[frac]); + let new_df = if groups.is_empty() { + df.sample_frac(&frac_s, replace, shuffle, seed)? + } else { + df.group_by_stable(groups)? + .apply(|df| df.sample_frac(&frac_s, replace, shuffle, seed))? + }; + + Ok(ExDataFrame::new(new_df)) +} + +#[rustler::nif] +fn df_from_arrow_stream_pointer(stream_ptr: u64) -> Result { + let stream_ptr = stream_ptr as *mut ffi::ArrowArrayStream; + let stream_ref = unsafe { stream_ptr.as_mut() } + .ok_or(ExplorerError::Other("Incorrect stream pointer".into()))?; + + let mut res = unsafe { ffi::ArrowArrayStreamReader::try_new(stream_ref) } + .map_err(arrow_to_explorer_error)?; + + let df = match unsafe { res.next() } { + None => DataFrame::empty(), + Some(maybe) => { + let mut acc = array_to_dataframe(maybe)?; + + while let Some(maybe) = unsafe { res.next() } { + let df = array_to_dataframe(maybe)?; + acc.vstack_mut(&df)?; + } + + acc.align_chunks(); + acc + } + }; + + Ok(ExDataFrame::new(df)) +} + +fn array_to_dataframe( + stream_chunk: PolarsResult>, +) -> Result { + let dyn_array = stream_chunk.map_err(arrow_to_explorer_error)?; + + let struct_array = dyn_array + .as_any() + .downcast_ref::() + .ok_or(ExplorerError::Other( + "Unable to downcast to StructArray in ArrowArrayStreamReader chunk".into(), + ))? + .clone(); + + DataFrame::try_from(struct_array).map_err(ExplorerError::Polars) +} + +fn arrow_to_explorer_error(error: impl std::fmt::Debug) -> ExplorerError { + ExplorerError::Other(format!("Internal Arrow error: #{error:?}")) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_sort_by( + df: ExDataFrame, + by_columns: Vec, + reverse: Vec, + maintain_order: bool, + multithreaded: bool, + nulls_last: bool, + groups: Vec, +) -> Result { + let sort_options = SortMultipleOptions::new() + .with_maintain_order(maintain_order) + .with_multithreaded(multithreaded) + .with_nulls_last(nulls_last) + .with_order_descending_multi(reverse); + + let new_df = if groups.is_empty() { + df.sort(by_columns, sort_options)? + } else { + df.group_by_stable(groups)? + .apply(|df| df.sort(by_columns.clone(), sort_options.clone()))? + }; + + Ok(ExDataFrame::new(new_df)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_sort_with( + data: ExDataFrame, + expressions: Vec, + directions: Vec, + maintain_order: bool, + multithreaded: bool, + nulls_last: bool, + groups: Vec, +) -> Result { + let df = data.clone_inner(); + let exprs = ex_expr_to_exprs(expressions); + + let sort_options = SortMultipleOptions::new() + .with_maintain_order(maintain_order) + .with_multithreaded(multithreaded) + .with_nulls_last(nulls_last) + .with_order_descending_multi(directions); + + let new_df = if groups.is_empty() { + df.lazy().sort_by_exprs(exprs, sort_options).collect()? + } else { + df.group_by_stable(groups)?.apply(|df| { + df.lazy() + .sort_by_exprs(&exprs, sort_options.clone()) + .collect() + })? + }; + + Ok(ExDataFrame::new(new_df)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_slice( + df: ExDataFrame, + offset: i64, + length: usize, + groups: Vec<&str>, +) -> Result { + let new_df = if groups.is_empty() { + df.slice(offset, length) + } else { + df.group_by_stable(groups)? + .apply(|df| Ok(df.slice(offset, length)))? + }; + Ok(ExDataFrame::new(new_df)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_to_dummies(df: ExDataFrame, selection: Vec<&str>) -> Result { + let drop_first = false; + let dummies = df + .select(selection) + .and_then(|df| df.to_dummies(None, drop_first))?; + + Ok(ExDataFrame::new(dummies)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_put_column(df: ExDataFrame, series: ExSeries) -> Result { + let mut df = df.clone(); + let s = series.clone_inner(); + let new_df = df.with_column(s)?.clone(); + + Ok(ExDataFrame::new(new_df)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_nil_count(df: ExDataFrame) -> Result { + let new_df = df.null_count(); + Ok(ExDataFrame::new(new_df)) +} + +#[rustler::nif] +pub fn df_from_series(columns: Vec) -> Result { + let columns = columns.into_iter().map(|c| c.clone_inner()).collect(); + + let df = DataFrame::new(columns)?; + + Ok(ExDataFrame::new(df)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_groups(df: ExDataFrame, groups: Vec<&str>) -> Result { + let groups = df.group_by(groups)?.groups()?; + + Ok(ExDataFrame::new(groups)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_group_indices( + df: ExDataFrame, + groups: Vec<&str>, +) -> Result, ExplorerError> { + let series = df + .group_by_stable(groups)? + .groups()? + .column("groups")? + .list()? + .into_iter() + .map(|series| ExSeries::new(series.unwrap())) + .collect(); + Ok(series) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_pivot_wider( + df: ExDataFrame, + id_columns: Vec<&str>, + pivot_column: &str, + values_column: Vec<&str>, + names_prefix: Option<&str>, +) -> Result { + // We need to preserve the original ID columns with a prefix, + // so if there is any "new column name" coming from a "value column" + // conflicting with some ID column, we can keep that ID column and + // the new column names. + let mut df = df.clone_inner(); + let explorer_prefix = "__explorer_column_id__"; + let temp_id_names: Vec = id_columns + .iter() + .map(|id_name| format!("{explorer_prefix}{id_name}")) + .collect(); + + for (id_name, new_name) in id_columns.iter().zip(&temp_id_names) { + df.rename(id_name, new_name.into())?; + } + + let mut new_df = pivot_stable( + &df, + [pivot_column], + Some(temp_id_names), + Some(values_column), + false, + Some(PivotAgg::First), + None, + )?; + + // Instead of using the names from the pivoted DF, we go back + // and restore the original ID column names, so we can use our + // algo below to preserve all columns. + let clean_names = new_df + .get_column_names() + .iter() + .map(|name| name.trim_start_matches(explorer_prefix)) + .collect(); + + let mut new_names = to_string_names(clean_names); + let mut counter: HashMap = HashMap::new(); + + for name in new_names.iter_mut() { + let original_name = name.clone(); + + if let Some(count) = counter.get(name) { + if let Some(prefix) = names_prefix { + *name = format!("{prefix}{name}"); + } + + if original_name == name.clone() { + *name = format!("{name}_{count}"); + } + + counter + .entry(name.clone()) + .and_modify(|c| *c += 1) + .or_insert(1); + } else { + if !id_columns.contains(&original_name.as_str()) { + if name == "null" { + *name = "nil".to_string(); + } + + if let Some(prefix) = names_prefix { + *name = format!("{prefix}{name}"); + } + } + + counter.insert(name.to_string(), 1); + } + } + + new_df.set_column_names(&new_names)?; + + Ok(ExDataFrame::new(new_df)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_lazy(df: ExDataFrame) -> Result { + let new_lf = df.clone_inner().lazy(); + Ok(ExLazyFrame::new(new_lf)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_re_dtype(pattern: &str) -> Result { + let s = Series::new("dummy".into(), [""]) + .into_frame() + .lazy() + .with_column(col("dummy").str().extract_groups(pattern)?.alias("dummy")) + .collect()? + .column("dummy")? + .clone(); + let ex_dtype = ExSeriesDtype::try_from(s.dtype())?; + Ok(ex_dtype) +} diff --git a/deps/explorer/native/explorer/src/dataframe/io.rs b/deps/explorer/native/explorer/src/dataframe/io.rs new file mode 100644 index 0000000000000000000000000000000000000000..8a6d5617e8d3d6419ffd50ccfef9fb87a065fb67 --- /dev/null +++ b/deps/explorer/native/explorer/src/dataframe/io.rs @@ -0,0 +1,714 @@ +// This file contains the IO functions related to a dataframe. +// Each format has 8 functions related. They do the following: +// +// - dump: dump a dataframe to a binary/string using the given format (like in a CSV string). +// - load: load a dataframe from a given binary/string (let's say, from a CSV string). +// - from: reads a dataframe from a file that is encoded in a given format. +// - to: writes a dataframe to a file in a given format. +// +// Today we have the following formats: CSV, NDJSON, Parquet, Apache Arrow and Apache Arrow Stream. +// +use polars::prelude::*; +use std::num::NonZeroUsize; + +use rustler::{Binary, Env, NewBinary}; +use std::fs::File; +use std::io::{BufReader, BufWriter, Cursor}; + +use crate::datatypes::{ExParquetCompression, ExS3Entry, ExSeriesDtype}; +use crate::{ExDataFrame, ExplorerError}; + +#[cfg(feature = "cloud")] +use crate::cloud_writer::CloudWriter; + +// ============ CSV ============ // + +#[rustler::nif(schedule = "DirtyIo")] +#[allow(clippy::too_many_arguments)] +pub fn df_from_csv( + filename: &str, + infer_schema_length: Option, + has_header: bool, + stop_after_n_rows: Option, + skip_rows: usize, + skip_rows_after_header: usize, + projection: Option>, + delimiter_as_byte: u8, + do_rechunk: bool, + column_names: Option>, + dtypes: Vec<(&str, ExSeriesDtype)>, + encoding: &str, + null_vals: Vec, + parse_dates: bool, + eol_delimiter: Option, +) -> Result { + let encoding = match encoding { + "utf8-lossy" => CsvEncoding::LossyUtf8, + _ => CsvEncoding::Utf8, + }; + + let dataframe = CsvReadOptions::default() + .with_schema_overwrite(schema_from_dtypes_pairs(dtypes)?) + .with_infer_schema_length(infer_schema_length) + .with_has_header(has_header) + .with_n_rows(stop_after_n_rows) + .with_skip_rows(skip_rows) + .with_skip_rows_after_header(skip_rows_after_header) + .with_projection(projection.map(Arc::new)) + .with_rechunk(do_rechunk) + .with_columns(column_names.map(|names| { + names + .iter() + .map(|name| PlSmallStr::from_string(name.clone())) + .collect() + })) + .with_parse_options( + CsvParseOptions::default() + .with_encoding(encoding) + .with_truncate_ragged_lines(true) + .with_try_parse_dates(parse_dates) + .with_separator(delimiter_as_byte) + .with_eol_char(eol_delimiter.unwrap_or(b'\n')) + .with_null_values(Some(NullValues::AllColumns( + null_vals.iter().map(|val| val.into()).collect(), + ))), + ) + .try_into_reader_with_file_path(Some(filename.into()))? + .finish(); + + Ok(ExDataFrame::new(dataframe?)) +} + +pub fn schema_from_dtypes_pairs( + dtypes: Vec<(&str, ExSeriesDtype)>, +) -> Result>, ExplorerError> { + if dtypes.is_empty() { + return Ok(None); + } + + let mut schema = Schema::with_capacity(dtypes.len()); + for (name, ex_dtype) in dtypes { + let dtype = DataType::try_from(&ex_dtype)?; + schema.with_column(name.into(), dtype); + } + Ok(Some(Arc::new(schema))) +} + +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_to_csv( + data: ExDataFrame, + filename: &str, + include_headers: bool, + delimiter: u8, +) -> Result<(), ExplorerError> { + let file = File::create(filename)?; + let mut buf_writer = BufWriter::new(file); + CsvWriter::new(&mut buf_writer) + .include_header(include_headers) + .with_separator(delimiter) + .finish(&mut data.clone())?; + Ok(()) +} + +#[cfg(feature = "aws")] +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_to_csv_cloud( + data: ExDataFrame, + ex_entry: ExS3Entry, + include_headers: bool, + delimiter: u8, +) -> Result<(), ExplorerError> { + let mut cloud_writer = build_aws_s3_cloud_writer(ex_entry)?; + + CsvWriter::new(&mut cloud_writer) + .include_header(include_headers) + .with_separator(delimiter) + .finish(&mut data.clone())?; + + let _ = cloud_writer.finish()?; + + Ok(()) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_dump_csv( + env: Env, + data: ExDataFrame, + include_headers: bool, + delimiter: u8, +) -> Result { + let mut buf = vec![]; + + CsvWriter::new(&mut buf) + .include_header(include_headers) + .with_separator(delimiter) + .finish(&mut data.clone())?; + + let mut values_binary = NewBinary::new(env, buf.len()); + values_binary.copy_from_slice(&buf); + + Ok(values_binary.into()) +} + +#[rustler::nif(schedule = "DirtyCpu")] +#[allow(clippy::too_many_arguments)] +pub fn df_load_csv( + binary: Binary, + infer_schema_length: Option, + has_header: bool, + stop_after_n_rows: Option, + skip_rows: usize, + skip_rows_after_header: usize, + projection: Option>, + delimiter_as_byte: u8, + do_rechunk: bool, + column_names: Option>, + dtypes: Vec<(&str, ExSeriesDtype)>, + encoding: &str, + null_vals: Vec, + parse_dates: bool, + eol_delimiter: Option, +) -> Result { + let encoding = match encoding { + "utf8-lossy" => CsvEncoding::LossyUtf8, + _ => CsvEncoding::Utf8, + }; + + let cursor = Cursor::new(binary.as_slice()); + + let dataframe = CsvReadOptions::default() + .with_schema_overwrite(schema_from_dtypes_pairs(dtypes)?) + .with_has_header(has_header) + .with_infer_schema_length(infer_schema_length) + .with_n_rows(stop_after_n_rows) + .with_columns(column_names.map(|names| { + names + .iter() + .map(|name| PlSmallStr::from_string(name.clone())) + .collect() + })) + .with_skip_rows(skip_rows) + .with_skip_rows_after_header(skip_rows_after_header) + .with_projection(projection.map(Arc::new)) + .with_rechunk(do_rechunk) + .with_parse_options( + CsvParseOptions::default() + .with_separator(delimiter_as_byte) + .with_encoding(encoding) + .with_null_values(Some(NullValues::AllColumns( + null_vals.iter().map(|x| x.into()).collect(), + ))) + .with_try_parse_dates(parse_dates) + .with_eol_char(eol_delimiter.unwrap_or(b'\n')), + ) + .into_reader_with_file_handle(cursor) + .finish(); + + Ok(ExDataFrame::new(dataframe?)) +} + +// ============ Parquet ============ // + +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_from_parquet( + filename: &str, + stop_after_n_rows: Option, + column_names: Option>, + projection: Option>, + rechunk: bool, +) -> Result { + let file = File::open(filename)?; + let buf_reader = BufReader::new(file); + + let reader = ParquetReader::new(buf_reader) + .with_slice(stop_after_n_rows.map(|max| (0, max))) + .with_columns(column_names) + .with_projection(projection) + .set_rechunk(rechunk); + + Ok(ExDataFrame::new(reader.finish()?)) +} + +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_to_parquet( + data: ExDataFrame, + filename: &str, + ex_compression: ExParquetCompression, +) -> Result<(), ExplorerError> { + let file = File::create(filename)?; + let mut buf_writer = BufWriter::new(file); + + let compression = ParquetCompression::try_from(ex_compression)?; + + ParquetWriter::new(&mut buf_writer) + .with_compression(compression) + .finish(&mut data.clone())?; + Ok(()) +} + +#[cfg(feature = "aws")] +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_to_parquet_cloud( + data: ExDataFrame, + ex_entry: ExS3Entry, + ex_compression: ExParquetCompression, +) -> Result<(), ExplorerError> { + let mut cloud_writer = build_aws_s3_cloud_writer(ex_entry)?; + + let compression = ParquetCompression::try_from(ex_compression)?; + + ParquetWriter::new(&mut cloud_writer) + .with_compression(compression) + .finish(&mut data.clone())?; + + let _ = cloud_writer.finish()?; + + Ok(()) +} + +#[cfg(feature = "aws")] +fn object_store_to_explorer_error(error: impl std::fmt::Debug) -> ExplorerError { + ExplorerError::Other(format!("Internal ObjectStore error: #{error:?}")) +} + +#[cfg(feature = "aws")] +fn build_aws_s3_cloud_writer(ex_entry: ExS3Entry) -> Result { + let config = ex_entry.config; + let mut aws_builder = object_store::aws::AmazonS3Builder::new() + .with_region(&config.region) + .with_access_key_id(&config.access_key_id) + .with_secret_access_key(&config.secret_access_key) + .with_allow_http(true) + .with_endpoint(&config.endpoint); + + if let Some(bucket_name) = &config.bucket { + aws_builder = aws_builder.with_bucket_name(bucket_name); + } else { + // We use the virtual host style, and the bucket name is going to be ignored + // because it's assumed to be already in the endpoint URL. + aws_builder = aws_builder + .with_bucket_name("explorer-default-bucket-name") + .with_virtual_hosted_style_request(true); + } + + if let Some(token) = config.token { + aws_builder = aws_builder.with_token(token); + } + + let aws_s3 = aws_builder + .build() + .map_err(object_store_to_explorer_error)?; + + let object_store: Arc = Arc::new(aws_s3); + CloudWriter::new(object_store, ex_entry.key.into()) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_dump_parquet( + env: Env, + data: ExDataFrame, + ex_compression: ExParquetCompression, +) -> Result { + let mut buf = vec![]; + + let compression = ParquetCompression::try_from(ex_compression)?; + + ParquetWriter::new(&mut buf) + .with_compression(compression) + .finish(&mut data.clone())?; + + let mut values_binary = NewBinary::new(env, buf.len()); + values_binary.copy_from_slice(&buf); + + Ok(values_binary.into()) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_load_parquet(binary: Binary) -> Result { + let cursor = Cursor::new(binary.as_slice()); + let reader = ParquetReader::new(cursor); + + Ok(ExDataFrame::new(reader.finish()?)) +} + +// ============ IPC ============ // + +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_from_ipc( + filename: &str, + columns: Option>, + projection: Option>, +) -> Result { + let file = File::open(filename)?; + let buf_reader = BufReader::new(file); + let reader = IpcReader::new(buf_reader) + .with_columns(columns) + .with_projection(projection); + + Ok(ExDataFrame::new(reader.finish()?)) +} + +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_to_ipc( + data: ExDataFrame, + filename: &str, + compression: Option<&str>, +) -> Result<(), ExplorerError> { + let compression = match compression { + Some(algo) => Some(decode_ipc_compression(algo)?), + None => None, + }; + + let file = File::create(filename)?; + let mut buf_writer = BufWriter::new(file); + IpcWriter::new(&mut buf_writer) + .with_compression(compression) + .finish(&mut data.clone())?; + Ok(()) +} + +#[cfg(feature = "aws")] +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_to_ipc_cloud( + data: ExDataFrame, + ex_entry: ExS3Entry, + compression: Option<&str>, +) -> Result<(), ExplorerError> { + let compression = match compression { + Some(algo) => Some(decode_ipc_compression(algo)?), + None => None, + }; + + let mut cloud_writer = build_aws_s3_cloud_writer(ex_entry)?; + + IpcWriter::new(&mut cloud_writer) + .with_compression(compression) + .finish(&mut data.clone())?; + + let _ = cloud_writer.finish()?; + + Ok(()) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_dump_ipc<'a>( + env: Env<'a>, + data: ExDataFrame, + compression: Option<&str>, +) -> Result, ExplorerError> { + let mut buf = vec![]; + + let compression = match compression { + Some(algo) => Some(decode_ipc_compression(algo)?), + None => None, + }; + + IpcWriter::new(&mut buf) + .with_compression(compression) + .finish(&mut data.clone())?; + + let mut values_binary = NewBinary::new(env, buf.len()); + values_binary.copy_from_slice(&buf); + + Ok(values_binary.into()) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_load_ipc( + binary: Binary, + columns: Option>, + projection: Option>, +) -> Result { + let cursor = Cursor::new(binary.as_slice()); + let reader = IpcReader::new(cursor) + .with_columns(columns) + .with_projection(projection); + + Ok(ExDataFrame::new(reader.finish()?)) +} + +fn decode_ipc_compression(compression: &str) -> Result { + match compression { + "lz4" => Ok(IpcCompression::LZ4), + "zstd" => Ok(IpcCompression::ZSTD), + other => Err(ExplorerError::Other(format!( + "the algorithm {other} is not supported for IPC compression" + ))), + } +} + +// ============ IPC Streaming ============ // + +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_from_ipc_stream( + filename: &str, + columns: Option>, + projection: Option>, +) -> Result { + let file = File::open(filename)?; + let buf_reader = BufReader::new(file); + let reader = IpcStreamReader::new(buf_reader) + .with_columns(columns) + .with_projection(projection); + + Ok(ExDataFrame::new(reader.finish()?)) +} + +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_to_ipc_stream( + data: ExDataFrame, + filename: &str, + compression: Option<&str>, +) -> Result<(), ExplorerError> { + let compression = match compression { + Some(algo) => Some(decode_ipc_compression(algo)?), + None => None, + }; + + let mut file = File::create(filename)?; + IpcStreamWriter::new(&mut file) + .with_compression(compression) + .finish(&mut data.clone())?; + Ok(()) +} + +#[cfg(feature = "aws")] +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_to_ipc_stream_cloud( + data: ExDataFrame, + ex_entry: ExS3Entry, + compression: Option<&str>, +) -> Result<(), ExplorerError> { + let compression = match compression { + Some(algo) => Some(decode_ipc_compression(algo)?), + None => None, + }; + + let mut cloud_writer = build_aws_s3_cloud_writer(ex_entry)?; + + IpcStreamWriter::new(&mut cloud_writer) + .with_compression(compression) + .finish(&mut data.clone())?; + + let _ = cloud_writer.finish()?; + + Ok(()) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_dump_ipc_stream<'a>( + env: Env<'a>, + data: ExDataFrame, + compression: Option<&str>, +) -> Result, ExplorerError> { + let mut buf = vec![]; + + let compression = match compression { + Some(algo) => Some(decode_ipc_compression(algo)?), + None => None, + }; + + IpcStreamWriter::new(&mut buf) + .with_compression(compression) + .finish(&mut data.clone())?; + + let mut values_binary = NewBinary::new(env, buf.len()); + values_binary.copy_from_slice(&buf); + + Ok(values_binary.into()) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_load_ipc_stream( + binary: Binary, + columns: Option>, + projection: Option>, +) -> Result { + let cursor = Cursor::new(binary.as_slice()); + let reader = IpcStreamReader::new(cursor) + .with_columns(columns) + .with_projection(projection); + + Ok(ExDataFrame::new(reader.finish()?)) +} + +// ============ NDJSON ============ // + +#[cfg(feature = "ndjson")] +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_from_ndjson( + filename: &str, + infer_schema_length: Option, + batch_size: usize, +) -> Result { + let file = File::open(filename)?; + let buf_reader = BufReader::new(file); + let batch_size = NonZeroUsize::new(batch_size).ok_or(ExplorerError::Other( + "\"batch_size\" expected to be non zero.".to_string(), + ))?; + let reader = JsonReader::new(buf_reader) + .with_json_format(JsonFormat::JsonLines) + .with_batch_size(batch_size) + .infer_schema_len(infer_schema_length.and_then(NonZeroUsize::new)); + + Ok(ExDataFrame::new(reader.finish()?)) +} + +#[cfg(feature = "ndjson")] +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_to_ndjson(data: ExDataFrame, filename: &str) -> Result<(), ExplorerError> { + let file = File::create(filename)?; + let mut buf_writer = BufWriter::new(file); + + JsonWriter::new(&mut buf_writer) + .with_json_format(JsonFormat::JsonLines) + .finish(&mut data.clone())?; + Ok(()) +} + +#[cfg(all(feature = "ndjson", feature = "aws"))] +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_to_ndjson_cloud(data: ExDataFrame, ex_entry: ExS3Entry) -> Result<(), ExplorerError> { + let mut cloud_writer = build_aws_s3_cloud_writer(ex_entry)?; + + JsonWriter::new(&mut cloud_writer) + .with_json_format(JsonFormat::JsonLines) + .finish(&mut data.clone())?; + + let _ = cloud_writer.finish()?; + + Ok(()) +} + +#[cfg(feature = "ndjson")] +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_dump_ndjson(env: Env, data: ExDataFrame) -> Result { + let mut buf = vec![]; + + JsonWriter::new(&mut buf) + .with_json_format(JsonFormat::JsonLines) + .finish(&mut data.clone())?; + + let mut values_binary = NewBinary::new(env, buf.len()); + values_binary.copy_from_slice(&buf); + + Ok(values_binary.into()) +} + +#[cfg(feature = "ndjson")] +#[rustler::nif(schedule = "DirtyCpu")] +pub fn df_load_ndjson( + binary: Binary, + infer_schema_length: Option, + batch_size: usize, +) -> Result { + let cursor = Cursor::new(binary.as_slice()); + let batch_size = NonZeroUsize::new(batch_size).ok_or(ExplorerError::Other( + "\"batch_size\" expected to be non zero.".to_string(), + ))?; + let reader = JsonReader::new(cursor) + .with_json_format(JsonFormat::JsonLines) + .with_batch_size(batch_size) + .infer_schema_len(infer_schema_length.and_then(NonZeroUsize::new)); + + Ok(ExDataFrame::new(reader.finish()?)) +} + +// ============ For when the feature is not enabled ============ // + +#[cfg(not(feature = "ndjson"))] +#[rustler::nif] +pub fn df_from_ndjson( + _filename: &str, + _infer_schema_length: Option, + _batch_size: usize, +) -> Result { + Err(ExplorerError::Other("Explorer was compiled without the \"ndjson\" feature enabled. \ + This is mostly due to this feature being incompatible with your computer's architecture. \ + Please read the section about precompilation in our README.md: https://github.com/elixir-explorer/explorer#precompilation".to_string())) +} + +#[cfg(not(feature = "ndjson"))] +#[rustler::nif] +pub fn df_to_ndjson(_data: ExDataFrame, _filename: &str) -> Result<(), ExplorerError> { + Err(ExplorerError::Other("Explorer was compiled without the \"ndjson\" feature enabled. \ + This is mostly due to this feature being incompatible with your computer's architecture. \ + Please read the section about precompilation in our README.md: https://github.com/elixir-explorer/explorer#precompilation".to_string())) +} + +#[cfg(not(feature = "ndjson"))] +#[rustler::nif] +pub fn df_dump_ndjson(_data: ExDataFrame) -> Result, ExplorerError> { + Err(ExplorerError::Other("Explorer was compiled without the \"ndjson\" feature enabled. \ + This is mostly due to this feature being incompatible with your computer's architecture. \ + Please read the section about precompilation in our README.md: https://github.com/elixir-explorer/explorer#precompilation".to_string())) +} + +#[cfg(not(feature = "ndjson"))] +#[rustler::nif] +pub fn df_load_ndjson( + _binary: Binary, + _infer_schema_length: Option, + _batch_size: usize, +) -> Result { + Err(ExplorerError::Other("Explorer was compiled without the \"ndjson\" feature enabled. \ + This is mostly due to this feature being incompatible with your computer's architecture. \ + Please read the section about precompilation in our README.md: https://github.com/elixir-explorer/explorer#precompilation".to_string())) +} + +#[cfg(not(feature = "aws"))] +#[rustler::nif] +pub fn df_to_parquet_cloud( + _data: ExDataFrame, + _ex_entry: ExS3Entry, + _ex_compression: ExParquetCompression, +) -> Result<(), ExplorerError> { + Err(ExplorerError::Other("Explorer was compiled without the \"aws\" feature enabled. \ + This is mostly due to this feature being incompatible with your computer's architecture. \ + Please read the section about precompilation in our README.md: https://github.com/elixir-explorer/explorer#precompilation".to_string())) +} + +#[cfg(not(feature = "aws"))] +#[rustler::nif] +pub fn df_to_csv_cloud( + _data: ExDataFrame, + _ex_entry: ExS3Entry, + _has_headers: bool, + _delimiter: u8, +) -> Result<(), ExplorerError> { + Err(ExplorerError::Other("Explorer was compiled without the \"aws\" feature enabled. \ + This is mostly due to this feature being incompatible with your computer's architecture. \ + Please read the section about precompilation in our README.md: https://github.com/elixir-explorer/explorer#precompilation".to_string())) +} + +#[cfg(not(feature = "aws"))] +#[rustler::nif] +pub fn df_to_ipc_cloud( + _data: ExDataFrame, + _ex_entry: ExS3Entry, + _compression: Option<&str>, +) -> Result<(), ExplorerError> { + Err(ExplorerError::Other("Explorer was compiled without the \"aws\" feature enabled. \ + This is mostly due to this feature being incompatible with your computer's architecture. \ + Please read the section about precompilation in our README.md: https://github.com/elixir-explorer/explorer#precompilation".to_string())) +} + +#[cfg(not(feature = "aws"))] +#[rustler::nif] +pub fn df_to_ipc_stream_cloud( + _data: ExDataFrame, + _ex_entry: ExS3Entry, + _compression: Option<&str>, +) -> Result<(), ExplorerError> { + Err(ExplorerError::Other("Explorer was compiled without the \"aws\" feature enabled. \ + This is mostly due to this feature being incompatible with your computer's architecture. \ + Please read the section about precompilation in our README.md: https://github.com/elixir-explorer/explorer#precompilation".to_string())) +} + +#[cfg(not(any(feature = "ndjson", feature = "aws")))] +#[rustler::nif(schedule = "DirtyIo")] +pub fn df_to_ndjson_cloud(_data: ExDataFrame, _ex_entry: ExS3Entry) -> Result<(), ExplorerError> { + Err(ExplorerError::Other("Explorer was compiled without the \"aws\" and \"ndjson\" features enabled. \ + This is mostly due to these feature being incompatible with your computer's architecture. \ + Please read the section about precompilation in our README.md: https://github.com/elixir-explorer/explorer#precompilation".to_string())) +} diff --git a/deps/explorer/native/explorer/src/datatypes.rs b/deps/explorer/native/explorer/src/datatypes.rs new file mode 100644 index 0000000000000000000000000000000000000000..9df8eb90c27e216d0c8fa4c5bc600f779368edde --- /dev/null +++ b/deps/explorer/native/explorer/src/datatypes.rs @@ -0,0 +1,843 @@ +mod ex_dtypes; + +use crate::atoms; +use crate::ExplorerError; +use chrono::prelude::*; + +#[cfg(feature = "cloud")] +use polars::prelude::cloud::CloudOptions; +use polars::prelude::*; +use rustler::{Atom, NifStruct, NifTaggedEnum, Resource, ResourceArc}; +use std::fmt; +use std::ops::Deref; + +#[cfg(feature = "aws")] +use std::str::FromStr; + +#[cfg(feature = "aws")] +use polars::prelude::cloud::AmazonS3ConfigKey as S3Key; + +use chrono_tz::{OffsetComponents, OffsetName, Tz}; + +pub use polars::export::arrow::datatypes::TimeUnit as ArrowTimeUnit; + +pub use polars::export::arrow::temporal_conversions::{ + date32_to_date as days_to_date, timestamp_ms_to_datetime as timestamp_ms_to_naive_datetime, + timestamp_ns_to_datetime as timestamp_ns_to_naive_datetime, + timestamp_to_datetime as arrow_timestamp_to_datetime, + timestamp_us_to_datetime as timestamp_us_to_naive_datetime, +}; + +pub use ex_dtypes::*; + +pub struct ExDataFrameRef(pub DataFrame); + +#[rustler::resource_impl] +impl Resource for ExDataFrameRef {} + +pub struct ExExprRef(pub Expr); + +#[rustler::resource_impl] +impl Resource for ExExprRef {} + +pub struct ExLazyFrameRef(pub LazyFrame); + +#[rustler::resource_impl] +impl Resource for ExLazyFrameRef {} + +pub struct ExSeriesRef(pub Series); + +#[rustler::resource_impl] +impl Resource for ExSeriesRef {} + +// The structs that start with "Ex" are related to the modules in Elixir. +// Some of them are just wrappers around Polars data structs. +// For example, a "ExDataFrame" is a wrapper around Polars' "DataFrame". +// +// In order to facilitate the usage of these structs, we implement the +// "Deref" trait that points to the Polars' equivalent. +// +// See a detailed explanation in this chapter of the Rust Book: +// https://doc.rust-lang.org/nightly/book/ch15-02-deref.html +#[derive(NifStruct)] +#[module = "Explorer.PolarsBackend.DataFrame"] +pub struct ExDataFrame { + pub resource: ResourceArc, +} + +#[derive(NifStruct, Clone)] +#[module = "Explorer.PolarsBackend.Expression"] +pub struct ExExpr { + pub resource: ResourceArc, +} + +#[derive(NifStruct)] +#[module = "Explorer.PolarsBackend.LazyFrame"] +pub struct ExLazyFrame { + pub resource: ResourceArc, +} + +#[derive(NifStruct)] +#[module = "Explorer.PolarsBackend.Series"] +pub struct ExSeries { + pub resource: ResourceArc, +} + +impl ExDataFrameRef { + pub fn new(df: DataFrame) -> Self { + Self(df) + } +} + +impl ExExprRef { + pub fn new(expr: Expr) -> Self { + Self(expr) + } +} + +impl ExLazyFrameRef { + pub fn new(df: LazyFrame) -> Self { + Self(df) + } +} + +impl ExSeriesRef { + pub fn new(s: Series) -> Self { + Self(s) + } +} + +impl ExDataFrame { + pub fn new(df: DataFrame) -> Self { + Self { + resource: ResourceArc::new(ExDataFrameRef::new(df)), + } + } + + // Returns a clone of the DataFrame inside the ResourceArc container. + pub fn clone_inner(&self) -> DataFrame { + self.resource.0.clone() + } +} + +// Implement Deref so we can call `DataFrame` functions directly from a `ExDataFrame` struct. +impl Deref for ExDataFrame { + type Target = DataFrame; + + fn deref(&self) -> &Self::Target { + &self.resource.0 + } +} + +impl ExExpr { + pub fn new(expr: Expr) -> Self { + Self { + resource: ResourceArc::new(ExExprRef::new(expr)), + } + } + + // Returns a clone of the Expr inside the ResourceArc container. + pub fn clone_inner(&self) -> Expr { + self.resource.0.clone() + } +} + +// Implement Deref so we can call `Expr` functions directly from a `ExExpr` struct. +impl Deref for ExExpr { + type Target = Expr; + + fn deref(&self) -> &Self::Target { + &self.resource.0 + } +} + +impl ExLazyFrame { + pub fn new(df: LazyFrame) -> Self { + Self { + resource: ResourceArc::new(ExLazyFrameRef::new(df)), + } + } + + // Returns a clone of the LazyFrame inside the ResourceArc container. + pub fn clone_inner(&self) -> LazyFrame { + self.resource.0.clone() + } +} + +// Implement Deref so we can call `LazyFrame` functions directly from a `ExLazyFrame` struct. +impl Deref for ExLazyFrame { + type Target = LazyFrame; + + fn deref(&self) -> &Self::Target { + &self.resource.0 + } +} + +impl ExSeries { + pub fn new(s: Series) -> Self { + Self { + resource: ResourceArc::new(ExSeriesRef::new(s)), + } + } + + // Returns a clone of the Series inside the ResourceArc container. + pub fn clone_inner(&self) -> Series { + self.resource.0.clone() + } +} + +// Implement Deref so we can call `Series` functions directly from a `ExSeries` struct. +impl Deref for ExSeries { + type Target = Series; + + fn deref(&self) -> &Self::Target { + &self.resource.0 + } +} + +#[derive(NifStruct, Copy, Clone, Debug)] +#[module = "Date"] +pub struct ExDate { + pub calendar: Atom, + pub day: u32, + pub month: u32, + pub year: i32, +} + +impl From for ExDate { + fn from(ts: i32) -> Self { + days_to_date(ts).into() + } +} + +impl From for i32 { + fn from(d: ExDate) -> i32 { + NaiveDate::from_ymd_opt(d.year, d.month, d.day) + .unwrap() + .signed_duration_since(NaiveDate::from_ymd_opt(1970, 1, 1).unwrap()) + .num_days() + .try_into() + .unwrap() + } +} + +impl From for NaiveDate { + fn from(d: ExDate) -> NaiveDate { + NaiveDate::from_ymd_opt(d.year, d.month, d.day).unwrap() + } +} + +impl From for ExDate { + fn from(d: NaiveDate) -> ExDate { + ExDate { + calendar: atoms::calendar_iso_module(), + day: d.day(), + month: d.month(), + year: d.year(), + } + } +} + +impl Literal for ExDate { + fn lit(self) -> Expr { + NaiveDate::from(self).lit().dt().date() + } +} + +#[derive(NifStruct, Copy, Clone, Debug)] +#[module = "Explorer.Duration"] +pub struct ExDuration { + pub value: i64, + pub precision: Atom, +} + +impl From for i64 { + fn from(d: ExDuration) -> i64 { + d.value + } +} + +impl Literal for ExDuration { + fn lit(self) -> Expr { + // Note: it's tempting to use `.lit()` on a `chrono::Duration` struct in this function, but + // doing so will lose precision information as `chrono::Duration`s have no time units. + Expr::Literal(LiteralValue::Duration( + self.value, + time_unit_of_ex_duration(&self), + )) + } +} + +fn time_unit_of_ex_duration(duration: &ExDuration) -> TimeUnit { + let precision = duration.precision; + if precision == atoms::millisecond() { + TimeUnit::Milliseconds + } else if precision == atoms::microsecond() { + TimeUnit::Microseconds + } else if precision == atoms::nanosecond() { + TimeUnit::Nanoseconds + } else { + panic!("unrecognized precision: {precision:?}") + } +} + +#[derive(NifStruct, Copy, Clone, Debug)] +#[module = "NaiveDateTime"] +pub struct ExNaiveDateTime { + pub calendar: Atom, + pub day: u32, + pub hour: u32, + pub microsecond: (u32, u32), + pub minute: u32, + pub month: u32, + pub second: u32, + pub year: i32, +} + +pub fn timestamp_to_datetime( + timestamp: i64, + time_unit: TimeUnit, + time_zone: Tz, +) -> chrono::DateTime { + let arrow_time_unit = convert_to_arrow_time_unit(time_unit); + arrow_timestamp_to_datetime(timestamp, arrow_time_unit, &time_zone) +} + +// Note: arrow has a native datetime analog to `timestamp_to_datetime` but it's +// private, so we're adapting its internals here. +pub fn timestamp_to_naive_datetime(timestamp: i64, time_unit: TimeUnit) -> NaiveDateTime { + match time_unit { + TimeUnit::Milliseconds => timestamp_ms_to_naive_datetime(timestamp), + TimeUnit::Microseconds => timestamp_us_to_naive_datetime(timestamp), + TimeUnit::Nanoseconds => timestamp_ns_to_naive_datetime(timestamp), + } +} + +fn convert_to_arrow_time_unit(time_unit: TimeUnit) -> ArrowTimeUnit { + match time_unit { + TimeUnit::Milliseconds => ArrowTimeUnit::Millisecond, + TimeUnit::Microseconds => ArrowTimeUnit::Microsecond, + TimeUnit::Nanoseconds => ArrowTimeUnit::Nanosecond, + } +} + +/// Trait for the fractional part of seconds for Elixir's time-related structs. +pub trait ExMicrosecondTuple { + /// Get the sub-second part. + fn subsec_micros(&self) -> u32; + + /// Round the sub-second part to a max of 6 digits. + fn subsec_micros_limited(&self) -> u32 { + // In the event of a leap second, `subsec_micros()` may exceed 999,999. + self.subsec_micros().min(999_999_u32) + } + + /// Default representation. + fn microsecond_tuple(&self) -> (u32, u32) { + (self.subsec_micros_limited(), 6) + } + + /// Representation rounded for specific time-units. + fn microsecond_tuple_tu(&self, time_unit: TimeUnit) -> (u32, u32) { + let us = self.subsec_micros_limited(); + + match time_unit { + // If Polars implements `TimeUnit::Seconds`, we'd return `(0, 0)`. + TimeUnit::Microseconds | TimeUnit::Nanoseconds => (us, 6), + TimeUnit::Milliseconds => (((us / 1_000) * 1_000), 3), + } + } +} + +impl ExMicrosecondTuple for NaiveTime { + fn subsec_micros(&self) -> u32 { + self.nanosecond() / 1_000 + } +} + +impl ExMicrosecondTuple for NaiveDateTime { + fn subsec_micros(&self) -> u32 { + self.and_utc().timestamp_subsec_micros() + } +} + +impl ExMicrosecondTuple for DateTime { + fn subsec_micros(&self) -> u32 { + self.timestamp_subsec_micros() + } +} + +impl ExMicrosecondTuple for DateTime { + fn subsec_micros(&self) -> u32 { + self.timestamp_subsec_micros() + } +} + +pub fn ex_naive_datetime_to_timestamp( + ex_naive_datetime: ExNaiveDateTime, + time_unit: TimeUnit, +) -> Result { + let naive_datetime = NaiveDateTime::from(ex_naive_datetime); + + match time_unit { + TimeUnit::Milliseconds => Ok(naive_datetime.and_utc().timestamp_millis()), + TimeUnit::Microseconds => Ok(naive_datetime.and_utc().timestamp_micros()), + TimeUnit::Nanoseconds => naive_datetime.and_utc().timestamp_nanos_opt().ok_or( + ExplorerError::TimestampConversion( + "cannot represent naive datetime(ns) with `i64`".to_string(), + ), + ), + } +} + +impl From for ExNaiveDateTime { + fn from(timestamp: i64) -> Self { + timestamp_to_naive_datetime(timestamp, TimeUnit::Microseconds).into() + } +} + +impl From for NaiveDateTime { + fn from(dt: ExNaiveDateTime) -> NaiveDateTime { + NaiveDate::from_ymd_opt(dt.year, dt.month, dt.day) + .unwrap() + .and_hms_micro_opt(dt.hour, dt.minute, dt.second, dt.microsecond.0) + .unwrap() + } +} + +impl From for ExNaiveDateTime { + fn from(dt: NaiveDateTime) -> Self { + ExNaiveDateTime { + calendar: atoms::calendar_iso_module(), + day: dt.day(), + month: dt.month(), + year: dt.year(), + hour: dt.hour(), + minute: dt.minute(), + second: dt.second(), + microsecond: dt.microsecond_tuple(), + } + } +} + +impl Literal for ExNaiveDateTime { + fn lit(self) -> Expr { + let ndt = NaiveDateTime::from(self); + // We can't call `ndt.lit()` because Polars defaults to nanoseconds + // for all years between 1386 and 2554, but Elixir only represents + // microsecond precision natively. This code is copied from the + // microsecond branch of their `.lit()` implementation. + // + // See here for details: + // polars-time-0.38.3/src/date_range.rs::in_nanoseconds_window + Expr::Literal(LiteralValue::DateTime( + ndt.and_utc().timestamp_micros(), + TimeUnit::Microseconds, + None, + )) + } +} + +#[derive(NifStruct, Copy, Clone, Debug)] +#[module = "DateTime"] +pub struct ExDateTime<'a> { + pub calendar: Atom, + pub day: u32, + pub hour: u32, + pub microsecond: (u32, u32), + pub minute: u32, + pub month: u32, + pub second: u32, + pub std_offset: i64, + pub time_zone: &'a str, + pub utc_offset: i64, + pub year: i32, + pub zone_abbr: &'a str, +} + +pub fn ex_datetime_to_timestamp( + ex_datetime: ExDateTime, + time_unit: TimeUnit, +) -> Result { + let datetime = DateTime::from(ex_datetime); + + match time_unit { + TimeUnit::Milliseconds => Ok(datetime.timestamp_millis()), + TimeUnit::Microseconds => Ok(datetime.timestamp_micros()), + TimeUnit::Nanoseconds => { + datetime + .timestamp_nanos_opt() + .ok_or(ExplorerError::TimestampConversion( + "cannot represent datetime(ns) with `i64`".to_string(), + )) + } + } +} + +impl<'a> From<&'a DateTime> for ExDateTime<'a> { + fn from(dt_tz: &'a DateTime) -> ExDateTime<'a> { + let time_zone = dt_tz.offset().tz_id(); + let zone_abbr = dt_tz.offset().abbreviation(); + + ExDateTime { + calendar: atoms::calendar_iso_module(), + day: dt_tz.day(), + hour: dt_tz.hour(), + microsecond: dt_tz.microsecond_tuple(), + minute: dt_tz.minute(), + month: dt_tz.month(), + second: dt_tz.second(), + std_offset: dt_tz.offset().dst_offset().num_seconds(), + time_zone, + utc_offset: dt_tz.offset().base_utc_offset().num_seconds(), + year: dt_tz.year(), + zone_abbr, + } + } +} + +impl From> for DateTime { + fn from(ex_dt: ExDateTime<'_>) -> DateTime { + let time_zone = ex_dt.time_zone.parse::().unwrap(); + + // Best approach I could find to avoid warning: + // https://github.com/chronotope/chrono/issues/873#issuecomment-1333716953 + let dt_tz_without_micro = time_zone + .with_ymd_and_hms( + ex_dt.year, + ex_dt.month, + ex_dt.day, + ex_dt.hour, + ex_dt.minute, + ex_dt.second, + ) + .unwrap(); + let micro = chrono::Duration::microseconds(ex_dt.microsecond.0.into()); + dt_tz_without_micro + micro + } +} + +impl<'tz> From> for NaiveDateTime { + fn from(dt: ExDateTime) -> NaiveDateTime { + NaiveDate::from_ymd_opt(dt.year, dt.month, dt.day) + .unwrap() + .and_hms_micro_opt(dt.hour, dt.minute, dt.second, dt.microsecond.0) + .unwrap() + } +} + +impl<'tz> Literal for ExDateTime<'tz> { + fn lit(self) -> Expr { + let ndt = NaiveDateTime::from(self); + let time_zone = self.time_zone.to_string(); + + Expr::Literal(LiteralValue::DateTime( + ndt.and_utc().timestamp_micros(), + TimeUnit::Microseconds, + Some(time_zone.into()), + )) + } +} + +#[derive(NifStruct, Copy, Clone, Debug)] +#[module = "Time"] +pub struct ExTime { + pub calendar: Atom, + pub hour: u32, + pub minute: u32, + pub second: u32, + pub microsecond: (u32, u32), +} + +pub use polars::export::arrow::temporal_conversions::time64ns_to_time; + +impl From for ExTime { + fn from(nanoseconds: i64) -> Self { + time64ns_to_time(nanoseconds).into() + } +} + +// In Polars, Time is represented as an i64 in nanoseconds. +// Since we don't have nanoseconds precision in Elixir, +// we just ignore the extra precision when is available. +impl From for i64 { + fn from(t: ExTime) -> i64 { + let midnight = NaiveTime::from_hms_opt(0, 0, 0).unwrap(); + let duration = NaiveTime::from_hms_micro_opt(t.hour, t.minute, t.second, t.microsecond.0) + .unwrap() + .signed_duration_since(midnight); + + match duration.num_microseconds() { + Some(us) => us * 1000, + None => duration.num_milliseconds() * 1_000 * 1000, + } + } +} + +impl From for NaiveTime { + fn from(t: ExTime) -> NaiveTime { + NaiveTime::from_hms_micro_opt(t.hour, t.minute, t.second, t.microsecond.0).unwrap() + } +} + +impl From for ExTime { + fn from(t: NaiveTime) -> Self { + ExTime { + calendar: atoms::calendar_iso_module(), + hour: t.hour(), + minute: t.minute(), + second: t.second(), + microsecond: t.microsecond_tuple(), + } + } +} + +impl Literal for ExTime { + fn lit(self) -> Expr { + Expr::Literal(LiteralValue::Time(self.into())) + } +} + +#[derive(NifStruct, Copy, Clone, Debug)] +#[module = "Decimal"] +pub struct ExDecimal { + pub sign: i8, + // `coef` is a positive, arbitrary precision integer on the Elixir side. + // It's convenient to represent it here as a signed `i128` because that's + // what the Decimal dtype expects. While you could technically create an + // `ExDecimal` struct with a negative `coef`, it's not a practical concern. + pub coef: i128, + pub exp: i64, +} + +impl ExDecimal { + pub fn new(signed_coef: i128, scale: usize) -> Self { + Self { + coef: signed_coef.abs(), + sign: if signed_coef >= 0 { 1 } else { -1 }, + exp: -(scale as i64), + } + } + + pub fn signed_coef(self) -> i128 { + self.sign as i128 * self.coef + } + + pub fn scale(self) -> usize { + self.exp + .abs() + .try_into() + .expect("cannot convert exponent (Elixir) to scale (Rust)") + } +} + +impl Literal for ExDecimal { + fn lit(self) -> Expr { + Expr::Literal(LiteralValue::Decimal( + if self.sign.is_positive() { + self.coef + } else { + -self.coef + }, + usize::try_from(-(self.exp)).expect("exponent should fit an usize"), + )) + } +} + +/// Represents valid Elixir types that can be used as literals in Polars. +pub enum ExValidValue<'a> { + I64(i64), + F64(f64), + Bool(bool), + Str(&'a str), + Date(ExDate), + Time(ExTime), + DateTime(ExNaiveDateTime), + Duration(ExDuration), + Decimal(ExDecimal), +} + +impl<'a> ExValidValue<'a> { + pub fn lit_with_matching_precision(self, data_type: &DataType) -> Expr { + match data_type { + DataType::Datetime(time_unit, _) => self.lit().dt().cast_time_unit(*time_unit), + DataType::Duration(time_unit) => self.lit().dt().cast_time_unit(*time_unit), + _ => self.lit(), + } + } +} + +impl<'a> Literal for &ExValidValue<'a> { + fn lit(self) -> Expr { + match self { + ExValidValue::I64(v) => v.lit(), + ExValidValue::F64(v) => v.lit(), + ExValidValue::Bool(v) => v.lit(), + ExValidValue::Str(v) => v.lit(), + ExValidValue::Date(v) => v.lit(), + ExValidValue::Time(v) => v.lit(), + ExValidValue::DateTime(v) => v.lit(), + ExValidValue::Duration(v) => v.lit(), + ExValidValue::Decimal(v) => v.lit(), + } + } +} + +impl<'a> rustler::Decoder<'a> for ExValidValue<'a> { + fn decode(term: rustler::Term<'a>) -> rustler::NifResult { + use rustler::*; + + match term.get_type() { + TermType::Atom => term.decode::().map(ExValidValue::Bool), + TermType::Binary => term.decode::<&'a str>().map(ExValidValue::Str), + TermType::Float => term.decode::().map(ExValidValue::F64), + TermType::Integer => term.decode::().map(ExValidValue::I64), + TermType::Map => { + if let Ok(date) = term.decode::() { + Ok(ExValidValue::Date(date)) + } else if let Ok(time) = term.decode::() { + Ok(ExValidValue::Time(time)) + } else if let Ok(datetime) = term.decode::() { + Ok(ExValidValue::DateTime(datetime)) + } else if let Ok(duration) = term.decode::() { + Ok(ExValidValue::Duration(duration)) + } else if let Ok(decimal) = term.decode::() { + Ok(ExValidValue::Decimal(decimal)) + } else { + Err(rustler::Error::BadArg) + } + } + _ => Err(rustler::Error::BadArg), + } + } +} + +// In Elixir this would be represented like this: +// * `:uncompressed` for `ExParquetCompression::Uncompressed` +// * `{:brotli, 7}` for `ExParquetCompression::Brotli(Some(7))` +#[derive(NifTaggedEnum)] +pub enum ExParquetCompression { + Brotli(Option), + Gzip(Option), + Lz4raw, + Snappy, + Uncompressed, + Zstd(Option), +} + +#[derive(NifTaggedEnum)] +pub enum ExCorrelationMethod { + Pearson, + Spearman, +} + +#[derive(NifTaggedEnum)] +pub enum ExRankMethod { + Average, + Min, + Max, + Dense, + Ordinal, + Random, +} + +impl TryFrom for ParquetCompression { + type Error = ExplorerError; + + fn try_from(value: ExParquetCompression) -> Result { + let compression = match value { + ExParquetCompression::Brotli(level) => { + let brotli_level = match level.map(BrotliLevel::try_new) { + // Cant' use map because of ? + Some(result) => Some(result?), + None => None, + }; + ParquetCompression::Brotli(brotli_level) + } + ExParquetCompression::Gzip(level) => { + let gzip_level = match level.map(GzipLevel::try_new) { + Some(result) => Some(result?), + None => None, + }; + ParquetCompression::Gzip(gzip_level) + } + ExParquetCompression::Lz4raw => ParquetCompression::Lz4Raw, + ExParquetCompression::Snappy => ParquetCompression::Snappy, + ExParquetCompression::Uncompressed => ParquetCompression::Uncompressed, + ExParquetCompression::Zstd(level) => { + let zstd_level = match level.map(ZstdLevel::try_new) { + Some(result) => Some(result?), + None => None, + }; + ParquetCompression::Zstd(zstd_level) + } + }; + + Ok(compression) + } +} + +// ========================= +// ====== FSS Structs ====== +// ========================= + +#[derive(NifStruct, Clone, Debug)] +#[module = "FSS.S3.Config"] +pub struct ExS3Config { + pub access_key_id: String, + pub secret_access_key: String, + pub region: String, + pub endpoint: String, + pub bucket: Option, + pub token: Option, +} + +#[derive(NifStruct, Clone, Debug)] +#[module = "FSS.S3.Entry"] +pub struct ExS3Entry { + pub key: String, + pub config: ExS3Config, +} + +impl fmt::Display for ExS3Entry { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if let Some(bucket_name) = &self.config.bucket { + write!(f, "s3://{}/{}", bucket_name, self.key) + } else { + write!(f, "s3://default-explorer-bucket/{}", self.key) + } + } +} + +#[cfg(feature = "aws")] +impl ExS3Config { + pub fn to_cloud_options(&self) -> CloudOptions { + let true_as_string = String::from("true"); + let mut aws_opts = vec![ + (S3Key::AccessKeyId, &self.access_key_id), + (S3Key::SecretAccessKey, &self.secret_access_key), + (S3Key::Region, &self.region), + (S3Key::from_str("aws_allow_http").unwrap(), &true_as_string), + ]; + + aws_opts.push((S3Key::Endpoint, &self.endpoint)); + + if let Some(token) = &self.token { + aws_opts.push((S3Key::Token, token)) + } + + // When bucket is not present, we need to force the virtual host style + // in order to ignore the bucket name. + if self.bucket.is_none() { + aws_opts.push((S3Key::VirtualHostedStyleRequest, &true_as_string)); + } + + CloudOptions::default().with_aws(aws_opts) + } +} + +impl From for Expr { + fn from(ex_expr: ExExpr) -> Self { + ex_expr.clone_inner() + } +} diff --git a/deps/explorer/native/explorer/src/datatypes/ex_dtypes.rs b/deps/explorer/native/explorer/src/datatypes/ex_dtypes.rs new file mode 100644 index 0000000000000000000000000000000000000000..4e70257200df633f125c81a7182dd17ee0b7fa26 --- /dev/null +++ b/deps/explorer/native/explorer/src/datatypes/ex_dtypes.rs @@ -0,0 +1,181 @@ +use crate::ExplorerError; +use polars::datatypes::CategoricalOrdering; +use polars::datatypes::DataType; +use polars::datatypes::Field; +use polars::datatypes::TimeUnit; +use rustler::NifTaggedEnum; +use std::ops::Deref; + +impl rustler::Encoder for Box { + fn encode<'a>(&self, env: rustler::Env<'a>) -> rustler::Term<'a> { + let dtype: &ExSeriesDtype = self.deref(); + + dtype.encode(env) + } +} + +impl<'a> rustler::Decoder<'a> for Box { + fn decode(term: rustler::Term<'a>) -> rustler::NifResult { + let dtype: ExSeriesDtype = term.decode()?; + Ok(Box::new(dtype)) + } +} + +#[derive(NifTaggedEnum)] +pub enum ExTimeUnit { + Millisecond, + Microsecond, + Nanosecond, +} + +impl TryFrom<&ExTimeUnit> for TimeUnit { + type Error = ExplorerError; + + fn try_from(value: &ExTimeUnit) -> Result { + match value { + ExTimeUnit::Millisecond => Ok(TimeUnit::Milliseconds), + ExTimeUnit::Microsecond => Ok(TimeUnit::Microseconds), + ExTimeUnit::Nanosecond => Ok(TimeUnit::Nanoseconds), + } + } +} + +impl From<&TimeUnit> for ExTimeUnit { + fn from(value: &TimeUnit) -> ExTimeUnit { + match value { + TimeUnit::Milliseconds => ExTimeUnit::Millisecond, + TimeUnit::Microseconds => ExTimeUnit::Microsecond, + TimeUnit::Nanoseconds => ExTimeUnit::Nanosecond, + } + } +} + +#[derive(NifTaggedEnum)] +pub enum ExSeriesDtype { + Null, + Binary, + Boolean, + Category, + Date, + F(u8), + S(u8), + U(u8), + String, + Time, + NaiveDatetime(ExTimeUnit), + Datetime(ExTimeUnit, String), + Duration(ExTimeUnit), + List(Box), + Struct(Vec<(String, ExSeriesDtype)>), + // Precision and scale. + Decimal(Option, Option), +} + +impl TryFrom<&DataType> for ExSeriesDtype { + type Error = ExplorerError; + + fn try_from(value: &DataType) -> Result { + match value { + DataType::Null => Ok(ExSeriesDtype::Null), + DataType::Binary => Ok(ExSeriesDtype::Binary), + DataType::Boolean => Ok(ExSeriesDtype::Boolean), + DataType::Categorical(_, _) => Ok(ExSeriesDtype::Category), + DataType::Date => Ok(ExSeriesDtype::Date), + DataType::Float64 => Ok(ExSeriesDtype::F(64)), + DataType::Float32 => Ok(ExSeriesDtype::F(32)), + DataType::Int8 => Ok(ExSeriesDtype::S(8)), + DataType::Int16 => Ok(ExSeriesDtype::S(16)), + DataType::Int32 => Ok(ExSeriesDtype::S(32)), + DataType::Int64 => Ok(ExSeriesDtype::S(64)), + + DataType::UInt8 => Ok(ExSeriesDtype::U(8)), + DataType::UInt16 => Ok(ExSeriesDtype::U(16)), + DataType::UInt32 => Ok(ExSeriesDtype::U(32)), + DataType::UInt64 => Ok(ExSeriesDtype::U(64)), + + DataType::Time => Ok(ExSeriesDtype::Time), + DataType::String => Ok(ExSeriesDtype::String), + DataType::Datetime(tu, None) => Ok(ExSeriesDtype::NaiveDatetime(tu.into())), + DataType::Datetime(tu, Some(tz)) => { + Ok(ExSeriesDtype::Datetime(tu.into(), tz.to_string())) + } + DataType::Duration(tu) => Ok(ExSeriesDtype::Duration(tu.into())), + + DataType::List(inner) => Ok(ExSeriesDtype::List(Box::new(Self::try_from( + inner.as_ref(), + )?))), + + DataType::Struct(fields) => { + let mut struct_fields = Vec::new(); + + for field in fields { + struct_fields.push((field.name().to_string(), Self::try_from(field.dtype())?)); + } + + Ok(ExSeriesDtype::Struct(struct_fields)) + } + + DataType::Decimal(precision, scale) => Ok(ExSeriesDtype::Decimal(*precision, *scale)), + + _ => Err(ExplorerError::Other(format!( + "cannot cast to dtype: {value}" + ))), + } + } +} + +impl TryFrom<&ExSeriesDtype> for DataType { + type Error = ExplorerError; + + fn try_from(value: &ExSeriesDtype) -> Result { + match value { + ExSeriesDtype::Null => Ok(DataType::Null), + ExSeriesDtype::Binary => Ok(DataType::Binary), + ExSeriesDtype::Boolean => Ok(DataType::Boolean), + ExSeriesDtype::Category => { + Ok(DataType::Categorical(None, CategoricalOrdering::default())) + } + ExSeriesDtype::Date => Ok(DataType::Date), + ExSeriesDtype::F(64) => Ok(DataType::Float64), + ExSeriesDtype::F(32) => Ok(DataType::Float32), + ExSeriesDtype::F(size) => Err(ExplorerError::Other(format!( + "float dtype of size {size} is not valid" + ))), + ExSeriesDtype::S(8) => Ok(DataType::Int8), + ExSeriesDtype::S(16) => Ok(DataType::Int16), + ExSeriesDtype::S(32) => Ok(DataType::Int32), + ExSeriesDtype::S(64) => Ok(DataType::Int64), + ExSeriesDtype::S(size) => Err(ExplorerError::Other(format!( + "signed integer dtype of size {size} is not valid" + ))), + + ExSeriesDtype::U(8) => Ok(DataType::UInt8), + ExSeriesDtype::U(16) => Ok(DataType::UInt16), + ExSeriesDtype::U(32) => Ok(DataType::UInt32), + ExSeriesDtype::U(64) => Ok(DataType::UInt64), + ExSeriesDtype::U(size) => Err(ExplorerError::Other(format!( + "unsigned integer dtype of size {size} is not valid" + ))), + ExSeriesDtype::String => Ok(DataType::String), + ExSeriesDtype::Time => Ok(DataType::Time), + ExSeriesDtype::NaiveDatetime(ex_timeunit) => { + Ok(DataType::Datetime(ex_timeunit.try_into()?, None)) + } + ExSeriesDtype::Datetime(ex_timeunit, tz_option) => Ok(DataType::Datetime( + ex_timeunit.try_into()?, + Some(tz_option.into()), + )), + ExSeriesDtype::Duration(ex_timeunit) => Ok(DataType::Duration(ex_timeunit.try_into()?)), + ExSeriesDtype::List(inner) => { + Ok(DataType::List(Box::new(Self::try_from(inner.as_ref())?))) + } + ExSeriesDtype::Struct(fields) => Ok(DataType::Struct( + fields + .iter() + .map(|(k, v)| Ok(Field::new(k.into(), v.try_into()?))) + .collect::, Self::Error>>()?, + )), + ExSeriesDtype::Decimal(precision, scale) => Ok(DataType::Decimal(*precision, *scale)), + } + } +} diff --git a/deps/explorer/native/explorer/src/encoding.rs b/deps/explorer/native/explorer/src/encoding.rs new file mode 100644 index 0000000000000000000000000000000000000000..13129a818ea693e5902c1a43f77a14df9ad8aede --- /dev/null +++ b/deps/explorer/native/explorer/src/encoding.rs @@ -0,0 +1,861 @@ +use chrono::prelude::*; +use polars::prelude::*; +use rustler::{Encoder, Env, NewBinary, OwnedBinary, ResourceArc, Term}; +use std::collections::HashMap; +use std::{mem, slice}; + +use chrono_tz::OffsetComponents; +use chrono_tz::OffsetName; +use chrono_tz::Tz; + +use crate::atoms::{ + self, calendar, day, hour, infinity, microsecond, millisecond, minute, month, nan, nanosecond, + neg_infinity, precision, second, std_offset, time_zone, utc_offset, value, year, zone_abbr, +}; +use crate::datatypes::{ + days_to_date, time64ns_to_time, timestamp_to_datetime, timestamp_to_naive_datetime, + ExMicrosecondTuple, ExSeries, ExSeriesRef, +}; +use crate::ExplorerError; + +use rustler::types::atom; +use rustler::wrapper::{list, map, NIF_TERM}; + +// Encoding helpers + +macro_rules! unsafe_iterator_series_to_list { + ($env: ident, $iterator: expr) => {{ + let env_as_c_arg = $env.as_c_arg(); + let acc = unsafe { list::make_list(env_as_c_arg, &[]) }; + + let list = $iterator.rfold(acc, |acc, term| unsafe { + list::make_list_cell(env_as_c_arg, term.as_c_arg(), acc) + }); + + unsafe { Term::new($env, list) } + }}; +} + +macro_rules! unsafe_encode_date { + ($v: ident, $date_struct_keys: ident, $calendar_iso_module: ident, $date_module: ident, $env: ident) => {{ + let dt = days_to_date($v); + + unsafe { + Term::new( + $env, + map::make_map_from_arrays( + $env.as_c_arg(), + $date_struct_keys, + &[ + $date_module, + $calendar_iso_module, + dt.day().encode($env).as_c_arg(), + dt.month().encode($env).as_c_arg(), + dt.year().encode($env).as_c_arg(), + ], + ) + .unwrap(), + ) + } + }}; +} + +// Here we build the Date struct manually, as it's much faster than using Date NifStruct +// This is because we already have the keys (we know this at compile time), and the types, +// so we can build the struct directly. +#[inline] +fn date_struct_keys(env: Env) -> [NIF_TERM; 5] { + return [ + atom::__struct__().encode(env).as_c_arg(), + calendar().encode(env).as_c_arg(), + day().encode(env).as_c_arg(), + month().encode(env).as_c_arg(), + year().encode(env).as_c_arg(), + ]; +} + +#[inline] +fn encode_date(v: i32, env: Env) -> Result { + let date_struct_keys = &date_struct_keys(env); + let calendar_iso_module = atoms::calendar_iso_module().encode(env).as_c_arg(); + let date_module = atoms::date_module().encode(env).as_c_arg(); + Ok(unsafe_encode_date!( + v, + date_struct_keys, + calendar_iso_module, + date_module, + env + )) +} + +#[inline] +fn date_series_to_list<'b>(s: &Series, env: Env<'b>) -> Result, ExplorerError> { + let date_struct_keys = &date_struct_keys(env); + let calendar_iso_module = atoms::calendar_iso_module().encode(env).as_c_arg(); + let date_module = atoms::date_module().encode(env).as_c_arg(); + + Ok(unsafe_iterator_series_to_list!( + env, + s.date()?.into_iter().map(|option| option + .map(|v| unsafe_encode_date!( + v, + date_struct_keys, + calendar_iso_module, + date_module, + env + )) + .encode(env)) + )) +} + +macro_rules! unsafe_encode_naive_datetime { + ( + $timestamp: expr, + $time_unit: expr, + $naive_datetime_struct_keys: ident, + $calendar_iso_module: ident, + $naive_datetime_module: ident, + $env: ident + ) => {{ + let ndt = timestamp_to_naive_datetime($timestamp, $time_unit); + + unsafe { + Term::new( + $env, + map::make_map_from_arrays( + $env.as_c_arg(), + $naive_datetime_struct_keys, + &[ + $naive_datetime_module, + $calendar_iso_module, + ndt.day().encode($env).as_c_arg(), + ndt.month().encode($env).as_c_arg(), + ndt.year().encode($env).as_c_arg(), + ndt.hour().encode($env).as_c_arg(), + ndt.minute().encode($env).as_c_arg(), + ndt.second().encode($env).as_c_arg(), + ndt.microsecond_tuple_tu($time_unit).encode($env).as_c_arg(), + ], + ) + .unwrap(), + ) + } + }}; +} + +// Here we build the NaiveDateTime struct manually, as it's much faster than using NifStruct +// This is because we already have the keys (we know this at compile time), and the types, +// so we can build the struct directly. +fn naive_datetime_struct_keys(env: Env) -> [NIF_TERM; 9] { + return [ + atom::__struct__().encode(env).as_c_arg(), + calendar().encode(env).as_c_arg(), + day().encode(env).as_c_arg(), + month().encode(env).as_c_arg(), + year().encode(env).as_c_arg(), + hour().encode(env).as_c_arg(), + minute().encode(env).as_c_arg(), + second().encode(env).as_c_arg(), + microsecond().encode(env).as_c_arg(), + ]; +} + +#[inline] +pub fn encode_naive_datetime( + timestamp: i64, + time_unit: TimeUnit, + env: Env, +) -> Result { + let naive_datetime_struct_keys = &naive_datetime_struct_keys(env); + let calendar_iso_module = atoms::calendar_iso_module().encode(env).as_c_arg(); + let naive_datetime_module = atoms::naive_datetime_module().encode(env).as_c_arg(); + + Ok(unsafe_encode_naive_datetime!( + timestamp, + time_unit, + naive_datetime_struct_keys, + calendar_iso_module, + naive_datetime_module, + env + )) +} + +#[inline] +fn naive_datetime_series_to_list<'b>(s: &Series, env: Env<'b>) -> Result, ExplorerError> { + let naive_datetime_struct_keys = &naive_datetime_struct_keys(env); + let calendar_iso_module = atoms::calendar_iso_module().encode(env).as_c_arg(); + let naive_datetime_module = atoms::naive_datetime_module().encode(env).as_c_arg(); + let time_unit = match s.dtype() { + DataType::Datetime(time_unit, None) => *time_unit, + _ => panic!("should only use this function for naive datetimes"), + }; + + Ok(unsafe_iterator_series_to_list!( + env, + s.datetime()?.into_iter().map(|opt_timestamp| opt_timestamp + .map(|timestamp| { + unsafe_encode_naive_datetime!( + timestamp, + time_unit, + naive_datetime_struct_keys, + calendar_iso_module, + naive_datetime_module, + env + ) + }) + .encode(env)) + )) +} + +macro_rules! unsafe_encode_datetime { + ( + $timestamp: expr, + $time_unit: expr, + $time_zone: expr, + $datetime_struct_keys: ident, + $calendar_iso_module: ident, + $datetime_module: ident, + $env: ident + ) => {{ + let dt_tz = timestamp_to_datetime($timestamp, $time_unit, $time_zone); + let tz_offset = dt_tz.offset(); + + unsafe { + Term::new( + $env, + map::make_map_from_arrays( + $env.as_c_arg(), + $datetime_struct_keys, + &[ + $datetime_module, + $calendar_iso_module, + dt_tz.day().encode($env).as_c_arg(), + dt_tz.hour().encode($env).as_c_arg(), + dt_tz + .microsecond_tuple_tu($time_unit) + .encode($env) + .as_c_arg(), + dt_tz.minute().encode($env).as_c_arg(), + dt_tz.month().encode($env).as_c_arg(), + dt_tz.second().encode($env).as_c_arg(), + tz_offset.dst_offset().num_seconds().encode($env).as_c_arg(), + $time_zone.to_string().encode($env).as_c_arg(), + tz_offset + .base_utc_offset() + .num_seconds() + .encode($env) + .as_c_arg(), + dt_tz.year().encode($env).as_c_arg(), + tz_offset.abbreviation().encode($env).as_c_arg(), + ], + ) + .unwrap(), + ) + } + }}; +} + +// Here we build the DateTime struct manually, as it's much faster than using NifStruct +// This is because we already have the keys (we know this at compile time), and the types, +// so we can build the struct directly. +fn datetime_struct_keys(env: Env) -> [NIF_TERM; 13] { + return [ + atom::__struct__().encode(env).as_c_arg(), + calendar().encode(env).as_c_arg(), + day().encode(env).as_c_arg(), + hour().encode(env).as_c_arg(), + microsecond().encode(env).as_c_arg(), + minute().encode(env).as_c_arg(), + month().encode(env).as_c_arg(), + second().encode(env).as_c_arg(), + std_offset().encode(env).as_c_arg(), + time_zone().encode(env).as_c_arg(), + utc_offset().encode(env).as_c_arg(), + year().encode(env).as_c_arg(), + zone_abbr().encode(env).as_c_arg(), + ]; +} + +#[inline] +pub fn encode_datetime( + timestamp: i64, + time_unit: TimeUnit, + time_zone: Tz, + env: Env, +) -> Result { + let datetime_struct_keys = &datetime_struct_keys(env); + let calendar_iso_module = atoms::calendar_iso_module().encode(env).as_c_arg(); + let datetime_module = atoms::datetime_module().encode(env).as_c_arg(); + + Ok(unsafe_encode_datetime!( + timestamp, + time_unit, + time_zone, + datetime_struct_keys, + calendar_iso_module, + datetime_module, + env + )) +} + +#[inline] +fn datetime_series_to_list<'b>(s: &Series, env: Env<'b>) -> Result, ExplorerError> { + let datetime_struct_keys = &datetime_struct_keys(env); + let calendar_iso_module = atoms::calendar_iso_module().encode(env).as_c_arg(); + let datetime_module = atoms::datetime_module().encode(env).as_c_arg(); + let time_unit = match s.dtype() { + DataType::Datetime(time_unit, Some(_)) => *time_unit, + _ => panic!("datetime_series_to_list called on series with wrong type"), + }; + let time_zone = match s.dtype() { + DataType::Datetime(_, Some(time_zone)) => time_zone.parse::().unwrap(), + _ => panic!("datetime_series_to_list called on series with wrong type"), + }; + + Ok(unsafe_iterator_series_to_list!( + env, + s.datetime()?.into_iter().map(|opt_timestamp| opt_timestamp + .map(|timestamp| { + unsafe_encode_datetime!( + timestamp, + time_unit, + time_zone, + datetime_struct_keys, + calendar_iso_module, + datetime_module, + env + ) + }) + .encode(env)) + )) +} + +fn time_unit_to_atom(time_unit: TimeUnit) -> atom::Atom { + match time_unit { + TimeUnit::Milliseconds => millisecond(), + TimeUnit::Microseconds => microsecond(), + TimeUnit::Nanoseconds => nanosecond(), + } +} +// ######### Duration ########## +macro_rules! unsafe_encode_duration { + ($v: expr, $time_unit: expr, $duration_struct_keys: ident, $duration_module: ident, $env: ident) => {{ + let value = $v; + let precision = time_unit_to_atom($time_unit); + + unsafe { + Term::new( + $env, + map::make_map_from_arrays( + $env.as_c_arg(), + $duration_struct_keys, + &[ + $duration_module, + value.encode($env).as_c_arg(), + precision.encode($env).as_c_arg(), + ], + ) + .unwrap(), + ) + } + }}; +} + +// Here we build the Explorer.Duration struct manually, as it's much faster than using NifStruct +// This is because we already have the keys (we know this at compile time), and the types, +// so we can build the struct directly. +fn duration_struct_keys(env: Env) -> [NIF_TERM; 3] { + return [ + atom::__struct__().encode(env).as_c_arg(), + value().encode(env).as_c_arg(), + precision().encode(env).as_c_arg(), + ]; +} + +#[inline] +pub fn encode_duration(v: i64, time_unit: TimeUnit, env: Env) -> Result { + let duration_struct_keys = &duration_struct_keys(env); + let duration_module = atoms::duration_module().encode(env).as_c_arg(); + + Ok(unsafe_encode_duration!( + v, + time_unit, + duration_struct_keys, + duration_module, + env + )) +} + +#[inline] +fn duration_series_to_list<'b>( + s: &Series, + time_unit: TimeUnit, + env: Env<'b>, +) -> Result, ExplorerError> { + let duration_struct_keys = &duration_struct_keys(env); + let duration_module = atoms::duration_module().encode(env).as_c_arg(); + + Ok(unsafe_iterator_series_to_list!( + env, + s.duration()?.into_iter().map(|option| option + .map(|v| { + unsafe_encode_duration!(v, time_unit, duration_struct_keys, duration_module, env) + }) + .encode(env)) + )) +} + +// ######### End of Duration ########## + +// ######### Decimal ########## +macro_rules! unsafe_encode_decimal { + ($v: expr, $scale: expr, $decimal_struct_keys: ident, $decimal_module: ident, $env: ident) => {{ + let coef = $v.abs(); + let scale = -($scale as isize); + let sign = $v.signum(); + // Elixir's Decimal has only 1 or -1. We need to treat positive zero as positive - 1. + let sign = if sign == 0 { 1 } else { sign }; + + unsafe { + Term::new( + $env, + map::make_map_from_arrays( + $env.as_c_arg(), + $decimal_struct_keys, + &[ + $decimal_module, + coef.encode($env).as_c_arg(), + scale.encode($env).as_c_arg(), + sign.encode($env).as_c_arg(), + ], + ) + .unwrap(), + ) + } + }}; +} + +// Here we build the Decimal struct manually, as it's much faster than using NifStruct +fn decimal_struct_keys(env: Env) -> [NIF_TERM; 4] { + return [ + atom::__struct__().encode(env).as_c_arg(), + atoms::coef().encode(env).as_c_arg(), + atoms::exp().encode(env).as_c_arg(), + atoms::sign().encode(env).as_c_arg(), + ]; +} + +#[inline] +pub fn encode_decimal(v: i128, scale: usize, env: Env) -> Result { + let struct_keys = &decimal_struct_keys(env); + let module_atom = atoms::decimal_module().encode(env).as_c_arg(); + + Ok(unsafe_encode_decimal!( + v, + scale, + struct_keys, + module_atom, + env + )) +} + +#[inline] +fn decimal_series_to_list<'b>(s: &Series, env: Env<'b>) -> Result, ExplorerError> { + let struct_keys = &decimal_struct_keys(env); + let module_atom = atoms::decimal_module().encode(env).as_c_arg(); + let decimal_chunked = s.decimal()?; + let scale = decimal_chunked.scale(); + + Ok(unsafe_iterator_series_to_list!( + env, + decimal_chunked.into_iter().map(|option| option + .map(|v| { unsafe_encode_decimal!(v, scale, struct_keys, module_atom, env) }) + .encode(env)) + )) +} + +// ######### End of Decimal ########## + +macro_rules! unsafe_encode_time { + ($v: expr, $naive_time_struct_keys: ident, $calendar_iso_module: ident, $time_module: ident, $env: ident) => {{ + let t = time64ns_to_time($v); + let microseconds = t.nanosecond() / 1_000; + + // Limit the number of digits in the microsecond part of a timestamp to 6. + // This is necessary because the microsecond part of Elixir is only 6 digits. + let limited_ms = if microseconds > 999_999 { + 999_999 + } else { + microseconds + }; + + unsafe { + Term::new( + $env, + map::make_map_from_arrays( + $env.as_c_arg(), + $naive_time_struct_keys, + &[ + $time_module, + $calendar_iso_module, + t.hour().encode($env).as_c_arg(), + t.minute().encode($env).as_c_arg(), + t.second().encode($env).as_c_arg(), + (limited_ms, 6).encode($env).as_c_arg(), + ], + ) + .unwrap(), + ) + } + }}; +} + +// Here we build the NaiveTime struct manually, as it's much faster than using NifStruct +// This is because we already have the keys (we know this at compile time), and the types, +// so we can build the struct directly. +fn naive_time_struct_keys(env: Env) -> [NIF_TERM; 6] { + return [ + atom::__struct__().encode(env).as_c_arg(), + calendar().encode(env).as_c_arg(), + hour().encode(env).as_c_arg(), + minute().encode(env).as_c_arg(), + second().encode(env).as_c_arg(), + microsecond().encode(env).as_c_arg(), + ]; +} + +#[inline] +fn encode_time(v: i64, env: Env) -> Result { + let naive_time_struct_keys = &naive_time_struct_keys(env); + let calendar_iso_module = atoms::calendar_iso_module().encode(env).as_c_arg(); + let time_module = atoms::time_module().encode(env).as_c_arg(); + + Ok(unsafe_encode_time!( + v, + naive_time_struct_keys, + calendar_iso_module, + time_module, + env + )) +} + +#[inline] +fn time_series_to_list<'b>(s: &Series, env: Env<'b>) -> Result, ExplorerError> { + let naive_time_struct_keys = &naive_time_struct_keys(env); + let calendar_iso_module = atoms::calendar_iso_module().encode(env).as_c_arg(); + let time_module = atoms::time_module().encode(env).as_c_arg(); + + Ok(unsafe_iterator_series_to_list!( + env, + s.time()?.into_iter().map(|option| option + .map(|v| { + unsafe_encode_time!( + v, + naive_time_struct_keys, + calendar_iso_module, + time_module, + env + ) + }) + .encode(env)) + )) +} + +fn generic_string_series_to_list<'b>(s: &Series, env: Env<'b>) -> Result, ExplorerError> { + Ok(unsafe_iterator_series_to_list!( + env, + s.str()?.into_iter().map(|option| option.encode(env)) + )) +} + +fn generic_binary_series_to_list<'b>( + resource: &ResourceArc, + s: &Series, + env: Env<'b>, +) -> Result, ExplorerError> { + let env_as_c_arg = env.as_c_arg(); + let nil_as_c_arg = atom::nil().to_term(env).as_c_arg(); + let acc = unsafe { list::make_list(env_as_c_arg, &[]) }; + let list = s.binary()?.downcast_iter().rfold(acc, |acc, array| { + array.iter().rfold(acc, |acc, v| { + let term_as_c_arg = match v { + Some(values) => unsafe { resource.make_binary_unsafe(env, |_| values) } + .to_term(env) + .as_c_arg(), + None => nil_as_c_arg, + }; + unsafe { list::make_list_cell(env_as_c_arg, term_as_c_arg, acc) } + }) + }); + Ok(unsafe { Term::new(env, list) }) +} + +fn categorical_series_to_list<'b>( + s: &Series, + env: Env<'b>, + mapping: &Arc, +) -> Result, ExplorerError> { + let env_as_c_arg = env.as_c_arg(); + let nil_as_c_arg = atom::nil().to_term(env).as_c_arg(); + let mut list = unsafe { list::make_list(env_as_c_arg, &[]) }; + + let logical = s.categorical()?.physical(); + let cat_size = mapping.len(); + let mut terms: Vec = vec![nil_as_c_arg; cat_size]; + + for (index, term) in terms.iter_mut().enumerate() { + if let Some(existing_str) = mapping.get_optional(index as u32) { + let mut binary = NewBinary::new(env, existing_str.len()); + binary.copy_from_slice(existing_str.as_bytes()); + + let binary_term: Term = binary.into(); + + *term = binary_term.as_c_arg(); + } + } + + for maybe_index in &logical.reverse() { + let term_ref = match maybe_index { + Some(index) if index < (cat_size as u32) => terms[index as usize], + _ => nil_as_c_arg, + }; + + list = unsafe { list::make_list_cell(env_as_c_arg, term_ref, list) } + } + + Ok(unsafe { Term::new(env, list) }) +} + +// Convert f32 and f64 series taking into account NaN and Infinity floats (they are encoded as atoms). +macro_rules! float_series_to_list { + ($name:ident, $convert_function:ident) => { + #[inline] + fn $name<'b>(s: &Series, env: Env<'b>) -> Result, ExplorerError> { + let nan_atom = nan().encode(env); + let neg_infinity_atom = neg_infinity().encode(env); + let infinity_atom = infinity().encode(env); + let nil_atom = atom::nil().encode(env); + + Ok(unsafe_iterator_series_to_list!( + env, + s.$convert_function()?.into_iter().map(|option| { + match option { + Some(x) => { + if x.is_finite() { + x.encode(env) + } else { + match (x.is_nan(), x.is_sign_negative()) { + (true, _) => nan_atom, + (false, true) => neg_infinity_atom, + (false, false) => infinity_atom, + } + } + } + None => nil_atom, + } + }) + )) + } + }; +} + +float_series_to_list!(float64_series_to_list, f64); +float_series_to_list!(float32_series_to_list, f32); + +macro_rules! series_to_list { + ($s:ident, $env:ident, $convert_function:ident) => { + Ok(unsafe_iterator_series_to_list!( + $env, + $s.$convert_function()? + .into_iter() + .map(|option| option.encode($env)) + )) + }; +} + +#[inline] +fn null_series_to_list<'b>(s: &Series, env: Env<'b>) -> Result, ExplorerError> { + let nil_as_c_arg = atom::nil().to_term(env).as_c_arg(); + let env_as_c_arg = env.as_c_arg(); + let mut list = unsafe { list::make_list(env_as_c_arg, &[]) }; + for _n in 0..s.len() { + list = unsafe { list::make_list_cell(env_as_c_arg, nil_as_c_arg, list) } + } + Ok(unsafe { Term::new(env, list) }) +} + +macro_rules! series_to_iovec { + ($resource:ident, $s:ident, $env:ident, $convert_function:ident, $in_type:ty) => {{ + Ok(unsafe_iterator_series_to_list!( + $env, + $s.$convert_function()?.downcast_iter().map(|array| { + let slice: &[$in_type] = array.values().as_slice(); + + let aligned_slice = unsafe { + slice::from_raw_parts( + slice.as_ptr() as *const u8, + slice.len() * mem::size_of::<$in_type>(), + ) + }; + + unsafe { $resource.make_binary_unsafe($env, |_| aligned_slice) }.to_term($env) + }) + )) + }}; +} + +// API + +pub fn resource_term_from_value<'b>( + resource: &ResourceArc, + v: AnyValue, + env: Env<'b>, +) -> Result, ExplorerError> { + match v { + AnyValue::Binary(v) => unsafe { + Ok(Some(resource.make_binary_unsafe(env, |_| v)).encode(env)) + }, + AnyValue::Null => Ok(atom::nil().to_term(env)), + AnyValue::Boolean(v) => Ok(v.encode(env)), + AnyValue::String(v) => Ok(v.encode(env)), + AnyValue::Int8(v) => Ok(v.encode(env)), + AnyValue::Int16(v) => Ok(v.encode(env)), + AnyValue::Int32(v) => Ok(v.encode(env)), + AnyValue::Int64(v) => Ok(v.encode(env)), + AnyValue::UInt8(v) => Ok(v.encode(env)), + AnyValue::UInt16(v) => Ok(v.encode(env)), + AnyValue::UInt32(v) => Ok(v.encode(env)), + AnyValue::UInt64(v) => Ok(v.encode(env)), + AnyValue::Float32(v) => Ok(term_from_float32(v, env)), + AnyValue::Float64(v) => Ok(term_from_float64(v, env)), + AnyValue::Date(v) => encode_date(v, env), + AnyValue::Time(v) => encode_time(v, env), + AnyValue::Datetime(v, time_unit, None) => encode_naive_datetime(v, time_unit, env), + AnyValue::Datetime(v, time_unit, Some(time_zone)) => { + encode_datetime(v, time_unit, time_zone.parse::().unwrap(), env) + } + AnyValue::Duration(v, time_unit) => encode_duration(v, time_unit, env), + AnyValue::Categorical(idx, mapping, _) => Ok(mapping.get(idx).encode(env)), + AnyValue::List(series) => list_from_series(ExSeries::new(series), env), + AnyValue::Struct(_, _, fields) => v + ._iter_struct_av() + .zip(fields) + .map(|(value, field)| { + Ok(( + field.name.as_str(), + resource_term_from_value(resource, value, env)?, + )) + }) + .collect::, ExplorerError>>() + .map(|map| map.encode(env)), + AnyValue::Decimal(number, scale) => encode_decimal(number, scale, env), + dt => panic!("cannot encode value {dt:?} to term"), + } +} + +// Macro for decoding both f32 and f64 to term. +macro_rules! term_from_float { + ($name:ident, $type:ty) => { + pub fn $name(float: $type, env: Env<'_>) -> Term<'_> { + if float.is_finite() { + float.encode(env) + } else { + match (float.is_nan(), float.is_sign_negative()) { + (true, _) => nan().encode(env), + (false, true) => neg_infinity().encode(env), + (false, false) => infinity().encode(env), + } + } + } + }; +} + +term_from_float!(term_from_float64, f64); +term_from_float!(term_from_float32, f32); + +pub fn list_from_series(s: ExSeries, env: Env) -> Result { + match s.dtype() { + DataType::Null => null_series_to_list(&s, env), + DataType::Boolean => series_to_list!(s, env, bool), + + DataType::Int8 => series_to_list!(s, env, i8), + DataType::Int16 => series_to_list!(s, env, i16), + DataType::Int32 => series_to_list!(s, env, i32), + DataType::Int64 => series_to_list!(s, env, i64), + + DataType::UInt8 => series_to_list!(s, env, u8), + DataType::UInt16 => series_to_list!(s, env, u16), + DataType::UInt32 => series_to_list!(s, env, u32), + DataType::UInt64 => series_to_list!(s, env, u64), + + DataType::Float32 => float32_series_to_list(&s, env), + DataType::Float64 => float64_series_to_list(&s, env), + + DataType::Date => date_series_to_list(&s, env), + DataType::Time => time_series_to_list(&s, env), + DataType::Datetime(_, None) => naive_datetime_series_to_list(&s, env), + DataType::Datetime(_, Some(_)) => datetime_series_to_list(&s, env), + DataType::Duration(time_unit) => duration_series_to_list(&s, *time_unit, env), + + DataType::Binary => generic_binary_series_to_list(&s.resource, &s, env), + DataType::String => generic_string_series_to_list(&s, env), + DataType::Categorical(Some(mapping), _) => categorical_series_to_list(&s, env, mapping), + + DataType::List(_inner_dtype) => s + .list()? + .into_iter() + .map(|item| match item { + Some(list) => list_from_series(ExSeries::new(list), env), + None => Ok(None::.encode(env)), + }) + .collect::, ExplorerError>>() + .map(|lists| lists.encode(env)), + DataType::Struct(_fields) => s + .iter() + .map(|value| resource_term_from_value(&s.resource, value, env)) + .collect::, ExplorerError>>() + .map(|values| values.encode(env)), + DataType::Decimal(_precision, _scale) => decimal_series_to_list(&s, env), + dt => panic!("to_list/1 not implemented for {dt:?}"), + } +} + +#[allow(clippy::size_of_in_element_count)] +pub fn iovec_from_series(s: ExSeries, env: Env) -> Result { + let resource = &s.resource; + + match s.dtype() { + DataType::Boolean => { + let mut bin = OwnedBinary::new(s.len()).unwrap(); + let slice = bin.as_mut_slice(); + for (i, v) in s.bool()?.into_iter().enumerate() { + slice[i] = v.unwrap() as u8; + } + Ok([bin.release(env)].encode(env)) + } + DataType::Int8 => series_to_iovec!(resource, s, env, i8, i8), + DataType::Int16 => series_to_iovec!(resource, s, env, i16, i16), + DataType::Int32 => series_to_iovec!(resource, s, env, i32, i32), + DataType::Int64 => series_to_iovec!(resource, s, env, i64, i64), + DataType::UInt8 => series_to_iovec!(resource, s, env, u8, u8), + DataType::UInt16 => series_to_iovec!(resource, s, env, u16, u16), + DataType::UInt32 => series_to_iovec!(resource, s, env, u32, u32), + DataType::UInt64 => series_to_iovec!(resource, s, env, u64, u64), + DataType::Float32 => series_to_iovec!(resource, s, env, f32, f32), + DataType::Float64 => series_to_iovec!(resource, s, env, f64, f64), + DataType::Date => series_to_iovec!(resource, s, env, date, i32), + DataType::Time => series_to_iovec!(resource, s, env, time, i64), + DataType::Datetime(_, None) => { + series_to_iovec!(resource, s, env, datetime, i64) + } + DataType::Duration(_) => { + series_to_iovec!(resource, s, env, duration, i64) + } + DataType::Categorical(Some(_), _) => { + let cat_series = s.cast(&DataType::UInt32)?; + + series_to_iovec!(resource, cat_series, env, u32, u32) + } + dt => panic!("to_iovec/1 not implemented for {dt:?}"), + } +} diff --git a/deps/explorer/native/explorer/src/error.rs b/deps/explorer/native/explorer/src/error.rs new file mode 100644 index 0000000000000000000000000000000000000000..6b3afb6fde9c010306a322ece3e306eaecfae134 --- /dev/null +++ b/deps/explorer/native/explorer/src/error.rs @@ -0,0 +1,41 @@ +use rustler::{Encoder, Env, Term}; +use std::io; +use thiserror::Error; + +// Defines the atoms for each value of ExplorerError. +rustler::atoms! { + io, + utf8, + polars, + internal, + other, + try_from_int, + parquet, + unknown +} + +#[derive(Error, Debug)] +pub enum ExplorerError { + #[error("IO Error: {0}")] + Io(#[from] io::Error), + #[error("Utf8 Conversion Error: {0}")] + Utf8(#[from] std::string::FromUtf8Error), + #[error("Polars Error: {0}")] + Polars(#[from] polars::prelude::PolarsError), + #[error("Internal Error: {0}")] + Internal(String), + #[error("Generic Error: {0}")] + Other(String), + #[error("Timestamp Conversion Error: {0}")] + TimestampConversion(String), + #[error(transparent)] + TryFromInt(#[from] std::num::TryFromIntError), + #[error(transparent)] + Unknown(#[from] anyhow::Error), +} + +impl Encoder for ExplorerError { + fn encode<'b>(&self, env: Env<'b>) -> Term<'b> { + format!("{self}").encode(env) + } +} diff --git a/deps/explorer/native/explorer/src/expressions.rs b/deps/explorer/native/explorer/src/expressions.rs new file mode 100644 index 0000000000000000000000000000000000000000..9d6fb6104f4b429003a003c122f146dc8c40903d --- /dev/null +++ b/deps/explorer/native/explorer/src/expressions.rs @@ -0,0 +1,1180 @@ +// The idea of this file is to have functions that +// transform the expressions from the Elixir side +// to the Rust side. Each function receives a basic type +// or an expression and returns an expression that is +// wrapped in an Elixir struct. + +use crate::datatypes::{ + ExCorrelationMethod, ExDate, ExDateTime, ExDuration, ExNaiveDateTime, ExRankMethod, + ExSeriesDtype, ExValidValue, +}; +use crate::series::{cast_str_to_f64, ewm_opts, rolling_opts_fixed_window}; +use crate::{ExDataFrame, ExExpr, ExSeries}; +use polars::lazy::dsl; +use polars::prelude::{ + col, concat_str, cov, pearson_corr, spearman_rank_corr, when, IntoLazy, LiteralValue, + SortOptions, +}; +use polars::prelude::{DataType, EWMOptions, Expr, Literal, StrptimeOptions, TimeUnit}; + +// Useful to get an ExExpr vec into a vec of expressions. +pub fn ex_expr_to_exprs(ex_exprs: Vec) -> Vec { + ex_exprs + .iter() + .map(|ex_expr| ex_expr.clone_inner()) + .collect() +} + +#[rustler::nif] +pub fn expr_nil() -> ExExpr { + let expr = Expr::Literal(LiteralValue::Null); + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_integer(number: i64) -> ExExpr { + let expr = Expr::Literal(LiteralValue::Int64(number)); + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_float(number: f64) -> ExExpr { + let expr = Expr::Literal(LiteralValue::Float64(number)); + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_string(string: String) -> ExExpr { + let expr = string.lit(); + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_boolean(boolean: bool) -> ExExpr { + let expr = boolean.lit(); + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_atom(atom: &str) -> ExExpr { + let expr = cast_str_to_f64(atom).lit(); + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_date(date: ExDate) -> ExExpr { + ExExpr::new(date.lit()) +} + +#[rustler::nif] +pub fn expr_datetime(datetime: ExDateTime) -> ExExpr { + ExExpr::new(datetime.lit()) +} + +#[rustler::nif] +pub fn expr_naive_datetime(naive_datetime: ExNaiveDateTime) -> ExExpr { + ExExpr::new(naive_datetime.lit()) +} + +#[rustler::nif] +pub fn expr_duration(duration: ExDuration) -> ExExpr { + ExExpr::new(duration.lit()) +} + +#[rustler::nif] +pub fn expr_series(series: ExSeries) -> ExExpr { + let series = series.clone_inner(); + let expr = series.lit(); + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_cast(data: ExExpr, to_dtype: ExSeriesDtype) -> ExExpr { + let expr = data.clone_inner(); + let to_dtype = DataType::try_from(&to_dtype).expect("dtype is not valid"); + + ExExpr::new(expr.cast(to_dtype)) +} + +#[rustler::nif] +pub fn expr_column(name: &str) -> ExExpr { + let expr = col(name); + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_equal(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + ExExpr::new(left_expr.eq(right_expr)) +} + +#[rustler::nif] +pub fn expr_not_equal(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + ExExpr::new(left_expr.neq(right_expr)) +} + +#[rustler::nif] +pub fn expr_greater(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + ExExpr::new(left_expr.gt(right_expr)) +} + +#[rustler::nif] +pub fn expr_greater_equal(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + ExExpr::new(left_expr.gt_eq(right_expr)) +} + +#[rustler::nif] +pub fn expr_less(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + ExExpr::new(left_expr.lt(right_expr)) +} + +#[rustler::nif] +pub fn expr_less_equal(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + ExExpr::new(left_expr.lt_eq(right_expr)) +} + +#[rustler::nif] +pub fn expr_binary_and(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + ExExpr::new(left_expr.and(right_expr)) +} + +#[rustler::nif] +pub fn expr_binary_or(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + ExExpr::new(left_expr.or(right_expr)) +} + +#[rustler::nif] +pub fn expr_binary_in(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + ExExpr::new(left_expr.is_in(right_expr)) +} + +#[rustler::nif] +pub fn expr_is_nil(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.is_null()) +} + +#[rustler::nif] +pub fn expr_is_not_nil(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.is_not_null()) +} + +#[rustler::nif] +pub fn expr_is_finite(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.is_finite()) +} + +#[rustler::nif] +pub fn expr_is_infinite(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.is_infinite()) +} + +#[rustler::nif] +pub fn expr_is_nan(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.is_nan()) +} + +#[rustler::nif] +pub fn expr_all_equal(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + let drop_nulls = false; + + ExExpr::new(left_expr.eq(right_expr).all(drop_nulls)) +} + +#[rustler::nif] +pub fn expr_slice(expr: ExExpr, offset: i64, length: u32) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.slice(offset, length)) +} + +#[rustler::nif] +pub fn expr_slice_by_indices(expr: ExExpr, indices_expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.gather(indices_expr.clone_inner())) +} + +#[rustler::nif] +pub fn expr_head(expr: ExExpr, length: usize) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.head(Some(length))) +} + +#[rustler::nif] +pub fn expr_tail(expr: ExExpr, length: usize) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.tail(Some(length))) +} + +#[rustler::nif] +pub fn expr_shift(expr: ExExpr, offset: i64, _default: Option) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.shift(offset.into())) +} + +#[rustler::nif] +pub fn expr_sample_n( + expr: ExExpr, + n: u64, + with_replacement: bool, + shuffle: bool, + seed: Option, +) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.sample_n(n.lit(), with_replacement, shuffle, seed)) +} + +#[rustler::nif] +pub fn expr_sample_frac( + expr: ExExpr, + frac: f64, + with_replacement: bool, + shuffle: bool, + seed: Option, +) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.sample_frac(frac.lit(), with_replacement, shuffle, seed)) +} + +#[rustler::nif] +pub fn expr_rank( + expr: ExExpr, + method: ExRankMethod, + descending: bool, + seed: Option, +) -> ExExpr { + let expr = expr.clone_inner(); + let rank_options = crate::parse_rank_method_options(method, descending); + + ExExpr::new(expr.rank(rank_options, seed)) +} + +#[rustler::nif] +pub fn expr_peaks(data: ExExpr, min_or_max: &str) -> ExExpr { + let expr = data.clone_inner(); + let type_expr = if min_or_max == "min" { + expr.min() + } else { + expr.max() + }; + + ExExpr::new(data.clone_inner().eq(type_expr)) +} + +#[rustler::nif] +pub fn expr_fill_missing_with_strategy(data: ExExpr, strategy: &str) -> ExExpr { + let expr = data.clone_inner(); + let result_expr = match strategy { + "backward" => expr.backward_fill(None), + "forward" => expr.forward_fill(None), + "min" => expr.clone().fill_null(expr.min()), + "max" => expr.clone().fill_null(expr.max()), + "mean" => expr.clone().fill_null(expr.mean()), + _other => panic!("unknown strategy {strategy:?}"), + }; + ExExpr::new(result_expr) +} + +#[rustler::nif] +pub fn expr_fill_missing_with_value(data: ExExpr, value: ExExpr) -> ExExpr { + let expr = data.clone_inner(); + let value = value.clone_inner(); + ExExpr::new(expr.fill_null(value)) +} + +#[rustler::nif] +pub fn expr_add(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + ExExpr::new(left_expr + right_expr) +} + +#[rustler::nif] +pub fn expr_subtract(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + ExExpr::new(left_expr - right_expr) +} + +#[rustler::nif] +pub fn expr_divide(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner().cast(DataType::Float64); + let right_expr = right.clone_inner().cast(DataType::Float64); + + ExExpr::new(left_expr / right_expr) +} + +#[rustler::nif] +pub fn expr_quotient(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + let quotient = left_expr + / when(right_expr.clone().eq(0)) + .then(Expr::Literal(LiteralValue::Null)) + .otherwise(right_expr); + + ExExpr::new(quotient) +} + +#[rustler::nif] +pub fn expr_remainder(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + let quotient = left_expr.clone() + / when(right_expr.clone().eq(0)) + .then(Expr::Literal(LiteralValue::Null)) + .otherwise(right_expr.clone()); + + let mult = right_expr * quotient; + let result = left_expr - mult; + + ExExpr::new(result) +} + +#[rustler::nif] +pub fn expr_multiply(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + ExExpr::new(left_expr * right_expr) +} + +#[rustler::nif] +pub fn expr_pow(left: ExExpr, right: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + ExExpr::new(left_expr.pow(right_expr)) +} + +#[rustler::nif] +pub fn expr_log(left: ExExpr, base: f64) -> ExExpr { + let left_expr = left.clone_inner(); + + ExExpr::new(left_expr.log(base)) +} + +#[rustler::nif] +pub fn expr_log_natural(left: ExExpr) -> ExExpr { + let left_expr = left.clone_inner(); + + ExExpr::new(left_expr.log(std::f64::consts::E)) +} + +#[rustler::nif] +pub fn expr_exp(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.exp()) +} + +#[rustler::nif] +pub fn expr_sum(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.sum()) +} + +#[rustler::nif] +pub fn expr_min(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.min()) +} + +#[rustler::nif] +pub fn expr_max(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.max()) +} + +#[rustler::nif] +pub fn expr_argmax(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.arg_max()) +} + +#[rustler::nif] +pub fn expr_argmin(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.arg_min()) +} + +#[rustler::nif] +pub fn expr_mean(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.mean()) +} + +#[rustler::nif] +pub fn expr_median(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.median()) +} + +#[rustler::nif] +pub fn expr_mode(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.mode()) +} + +#[rustler::nif] +pub fn expr_product(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.product()) +} + +#[rustler::nif] +pub fn expr_abs(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.abs()) +} + +#[rustler::nif] +pub fn expr_variance(expr: ExExpr, ddof: u8) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.var(ddof)) +} + +#[rustler::nif] +pub fn expr_standard_deviation(expr: ExExpr, ddof: u8) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.std(ddof)) +} + +#[rustler::nif] +pub fn expr_quantile(expr: ExExpr, quantile: f64) -> ExExpr { + let expr = expr.clone_inner(); + let strategy = crate::parse_quantile_interpol_options("nearest"); + ExExpr::new(expr.quantile(quantile.into(), strategy)) +} + +#[rustler::nif] +pub fn expr_skew(data: ExExpr, bias: bool) -> ExExpr { + let expr = data.clone_inner(); + ExExpr::new(expr.skew(bias)) +} + +#[rustler::nif] +pub fn expr_correlation( + left: ExExpr, + right: ExExpr, + ddof: u8, + method: ExCorrelationMethod, +) -> ExExpr { + let left_expr = left.clone_inner().cast(DataType::Float64); + let right_expr = right.clone_inner().cast(DataType::Float64); + + match method { + ExCorrelationMethod::Pearson => ExExpr::new(pearson_corr(left_expr, right_expr, ddof)), + ExCorrelationMethod::Spearman => { + ExExpr::new(spearman_rank_corr(left_expr, right_expr, ddof, true)) + } + } +} + +#[rustler::nif] +pub fn expr_covariance(left: ExExpr, right: ExExpr, ddof: u8) -> ExExpr { + let left_expr = left.clone_inner().cast(DataType::Float64); + let right_expr = right.clone_inner().cast(DataType::Float64); + ExExpr::new(cov(left_expr, right_expr, ddof)) +} + +#[rustler::nif] +pub fn expr_all(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.all(true)) +} + +#[rustler::nif] +pub fn expr_any(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.any(true)) +} + +#[rustler::nif] +pub fn expr_alias(expr: ExExpr, name: &str) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.alias(name)) +} + +#[rustler::nif] +pub fn expr_count(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.count()) +} + +#[rustler::nif] +pub fn expr_nil_count(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.null_count()) +} + +#[rustler::nif] +pub fn expr_size(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.len()) +} + +#[rustler::nif] +pub fn expr_n_distinct(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.n_unique()) +} + +#[rustler::nif] +pub fn expr_first(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.first()) +} + +#[rustler::nif] +pub fn expr_last(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.last()) +} + +#[rustler::nif] +pub fn expr_format(exprs: Vec) -> ExExpr { + ExExpr::new(concat_str(ex_expr_to_exprs(exprs), "", true)) +} + +#[rustler::nif] +pub fn expr_concat(exprs: Vec) -> ExExpr { + let mut iter = exprs.iter(); + let mut result = iter.next().unwrap().clone_inner(); + + for expr in iter { + result = result.append(expr.clone_inner(), false); + } + + ExExpr::new(result) +} + +#[rustler::nif] +pub fn expr_coalesce(left: ExExpr, right: ExExpr) -> ExExpr { + let predicate = left.clone_inner().is_not_null(); + let left_expr = left.clone_inner(); + let right_expr = right.clone_inner(); + + let condition = when(predicate).then(left_expr).otherwise(right_expr); + + ExExpr::new(condition) +} + +#[rustler::nif] +pub fn expr_select(predicate: ExExpr, on_true: ExExpr, on_false: ExExpr) -> ExExpr { + let predicate_expr = predicate.clone_inner(); + let on_true_expr = on_true.clone_inner(); + let on_false_expr = on_false.clone_inner(); + + let condition = when(predicate_expr) + .then(on_true_expr) + .otherwise(on_false_expr); + + ExExpr::new(condition) +} + +// window functions +macro_rules! init_window_expr_fun { + ($name:ident, $fun:ident) => { + #[rustler::nif(schedule = "DirtyCpu")] + pub fn $name( + data: ExExpr, + window_size: usize, + weights: Option>, + min_periods: Option, + center: bool, + ) -> ExExpr { + let expr = match weights.as_deref() { + Some([]) | None => data.clone_inner(), + _ => data.clone_inner().cast(DataType::Float64), + }; + let opts = rolling_opts_fixed_window(window_size, weights, min_periods, center); + ExExpr::new(expr.$fun(opts)) + } + }; +} + +init_window_expr_fun!(expr_window_max, rolling_max); +init_window_expr_fun!(expr_window_min, rolling_min); +init_window_expr_fun!(expr_window_sum, rolling_sum); +init_window_expr_fun!(expr_window_mean, rolling_mean); +init_window_expr_fun!(expr_window_median, rolling_median); + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn expr_window_standard_deviation( + data: ExExpr, + window_size: usize, + weights: Option>, + min_periods: Option, + center: bool, +) -> ExExpr { + let expr = data.clone_inner(); + let opts = rolling_opts_fixed_window(window_size, weights, min_periods, center); + ExExpr::new(expr.rolling_std(opts).cast(DataType::Float64)) +} + +#[rustler::nif] +pub fn expr_cumulative_min(data: ExExpr, reverse: bool) -> ExExpr { + let expr = data.clone_inner(); + ExExpr::new(expr.cum_min(reverse)) +} + +#[rustler::nif] +pub fn expr_cumulative_max(data: ExExpr, reverse: bool) -> ExExpr { + let expr = data.clone_inner(); + ExExpr::new(expr.cum_max(reverse)) +} + +#[rustler::nif] +pub fn expr_cumulative_sum(data: ExExpr, reverse: bool) -> ExExpr { + let expr = data.clone_inner(); + ExExpr::new(expr.cum_sum(reverse)) +} + +#[rustler::nif] +pub fn expr_cumulative_product(data: ExExpr, reverse: bool) -> ExExpr { + let expr = data.clone_inner(); + ExExpr::new(expr.cum_prod(reverse)) +} + +#[rustler::nif] +pub fn expr_ewm_mean( + data: ExExpr, + alpha: f64, + adjust: bool, + min_periods: usize, + ignore_nulls: bool, +) -> ExExpr { + let expr = data.clone_inner(); + let opts = ewm_opts(alpha, adjust, min_periods, ignore_nulls); + ExExpr::new(expr.ewm_mean(opts)) +} + +#[rustler::nif] +pub fn expr_ewm_standard_deviation( + data: ExExpr, + alpha: f64, + adjust: bool, + bias: bool, + min_periods: usize, + ignore_nulls: bool, +) -> ExExpr { + let expr = data.clone_inner(); + let opts = EWMOptions { + alpha, + adjust, + bias, + min_periods, + ignore_nulls, + }; + ExExpr::new(expr.ewm_std(opts)) +} + +#[rustler::nif] +pub fn expr_ewm_variance( + data: ExExpr, + alpha: f64, + adjust: bool, + bias: bool, + min_periods: usize, + ignore_nulls: bool, +) -> ExExpr { + let expr = data.clone_inner(); + let opts = EWMOptions { + alpha, + adjust, + bias, + min_periods, + ignore_nulls, + }; + ExExpr::new(expr.ewm_var(opts)) +} + +#[rustler::nif] +pub fn expr_reverse(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.reverse()) +} + +#[rustler::nif] +pub fn expr_sort( + expr: ExExpr, + descending: bool, + maintain_order: bool, + multithreaded: bool, + nulls_last: bool, +) -> ExExpr { + let expr = expr.clone_inner(); + + let opts = SortOptions { + descending, + maintain_order, + multithreaded, + nulls_last, + }; + + ExExpr::new(expr.sort(opts)) +} + +#[rustler::nif] +pub fn expr_argsort( + expr: ExExpr, + descending: bool, + maintain_order: bool, + multithreaded: bool, + nulls_last: bool, +) -> ExExpr { + let expr = expr.clone_inner(); + + let opts = SortOptions { + descending, + maintain_order, + multithreaded, + nulls_last, + }; + + ExExpr::new(expr.arg_sort(opts)) +} + +#[rustler::nif] +pub fn expr_distinct(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.unique_stable()) +} + +#[rustler::nif] +pub fn expr_unordered_distinct(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.unique()) +} + +#[rustler::nif] +pub fn expr_unary_not(expr: ExExpr) -> ExExpr { + let predicate = expr.clone_inner(); + ExExpr::new(predicate.not()) +} + +#[rustler::nif] +pub fn expr_describe_filter_plan(data: ExDataFrame, expr: ExExpr) -> String { + let df = data.clone(); + let expressions = expr.clone_inner(); + df.lazy() + .filter(expressions) + .describe_plan() + .expect("error") +} + +#[rustler::nif] +pub fn expr_contains(expr: ExExpr, pattern: &str) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.str().contains_literal(pattern.lit())) +} + +#[rustler::nif] +pub fn expr_re_contains(expr: ExExpr, pattern: &str) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.str().contains(pattern.lit(), true)) +} + +#[rustler::nif] +pub fn expr_upcase(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.str().to_uppercase()) +} + +#[rustler::nif] +pub fn expr_downcase(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.str().to_lowercase()) +} + +#[rustler::nif] +pub fn expr_strip(expr: ExExpr, string: Option) -> ExExpr { + let expr = expr.clone_inner(); + let matches_expr = match string { + Some(string) => string.lit(), + None => Expr::Literal(LiteralValue::Null), + }; + ExExpr::new(expr.str().strip_chars(matches_expr)) +} + +#[rustler::nif] +pub fn expr_lstrip(expr: ExExpr, string: Option) -> ExExpr { + let expr = expr.clone_inner(); + let matches_expr = match string { + Some(string) => string.lit(), + None => Expr::Literal(LiteralValue::Null), + }; + ExExpr::new(expr.str().strip_chars_start(matches_expr)) +} + +#[rustler::nif] +pub fn expr_rstrip(expr: ExExpr, string: Option) -> ExExpr { + let expr = expr.clone_inner(); + let matches_expr = match string { + Some(string) => string.lit(), + None => Expr::Literal(LiteralValue::Null), + }; + ExExpr::new(expr.str().strip_chars_end(matches_expr)) +} + +#[rustler::nif] +pub fn expr_substring(expr: ExExpr, offset: i64, length: Option) -> ExExpr { + let length = match length { + Some(l) => l.lit(), + None => Expr::Literal(LiteralValue::Null), + }; + let expr = expr.clone_inner(); + ExExpr::new(expr.str().slice(offset.lit(), length)) +} + +#[rustler::nif] +pub fn expr_split(expr: ExExpr, substring: String) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.str().split(substring.lit())) +} + +#[rustler::nif] +pub fn expr_replace(expr: ExExpr, pat: String, value: String) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.str().replace_all(pat.lit(), value.lit(), true)) +} + +#[rustler::nif] +pub fn expr_re_replace(expr: ExExpr, pat: String, value: String) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.str().replace_all(pat.lit(), value.lit(), false)) +} + +#[rustler::nif] +pub fn expr_round(expr: ExExpr, decimals: u32) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.round(decimals)) +} + +#[rustler::nif] +pub fn expr_floor(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.floor()) +} + +#[rustler::nif] +pub fn expr_ceil(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.ceil()) +} + +#[rustler::nif] +pub fn expr_sin(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.sin()) +} + +#[rustler::nif] +pub fn expr_cos(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.cos()) +} + +#[rustler::nif] +pub fn expr_tan(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.tan()) +} + +#[rustler::nif] +pub fn expr_asin(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.arcsin()) +} + +#[rustler::nif] +pub fn expr_acos(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.arccos()) +} + +#[rustler::nif] +pub fn expr_atan(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.arctan()) +} + +#[rustler::nif] +pub fn expr_strptime(expr: ExExpr, format_string: &str) -> ExExpr { + let options = StrptimeOptions { + format: Some(format_string.into()), + strict: false, + exact: true, + cache: true, + }; + ExExpr::new(expr.clone_inner().str().to_datetime( + Some(TimeUnit::Microseconds), + None, + options, + "earliest".lit(), + )) +} + +#[rustler::nif] +pub fn expr_strftime(expr: ExExpr, format_string: &str) -> ExExpr { + ExExpr::new(expr.clone_inner().dt().strftime(format_string)) +} + +#[rustler::nif] +pub fn expr_clip_integer(expr: ExExpr, min: i64, max: i64) -> ExExpr { + let expr = expr.clone_inner().clip(min.lit(), max.lit()); + + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_clip_float(expr: ExExpr, min: f64, max: f64) -> ExExpr { + let expr = expr + .clone_inner() + .cast(DataType::Float64) + .clip(min.lit(), max.lit()); + + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_day_of_week(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.dt().weekday()) +} + +#[rustler::nif] +pub fn expr_day_of_year(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.dt().ordinal_day()) +} + +#[rustler::nif] +pub fn expr_week_of_year(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.dt().week()) +} + +#[rustler::nif] +pub fn expr_month(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.dt().month()) +} + +#[rustler::nif] +pub fn expr_year(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.dt().year()) +} + +#[rustler::nif] +pub fn expr_hour(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.dt().hour()) +} + +#[rustler::nif] +pub fn expr_minute(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.dt().minute()) +} + +#[rustler::nif] +pub fn expr_second(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.dt().second()) +} + +#[rustler::nif] +pub fn expr_join(expr: ExExpr, sep: String) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.list().join(sep.lit(), true)) +} + +#[rustler::nif] +pub fn expr_int_range(start: ExExpr, end: ExExpr, step: i64, dtype: ExSeriesDtype) -> ExExpr { + let start = start.clone_inner(); + let end = end.clone_inner(); + let dtype = DataType::try_from(&dtype).unwrap(); + let expr = dsl::int_range(start, end, step, dtype); + + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_lengths(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.list().len()) +} + +#[rustler::nif] +pub fn expr_member(expr: ExExpr, value: ExValidValue, inner_dtype: ExSeriesDtype) -> ExExpr { + let expr = expr.clone_inner(); + let inner_dtype = DataType::try_from(&inner_dtype).unwrap(); + + ExExpr::new( + expr.list() + .contains(value.lit_with_matching_precision(&inner_dtype)), + ) +} + +#[rustler::nif] +pub fn expr_field(expr: ExExpr, name: &str) -> ExExpr { + let expr = expr.clone_inner().struct_().field_by_name(name); + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_json_decode(expr: ExExpr, ex_dtype: ExSeriesDtype) -> ExExpr { + let dtype = DataType::try_from(&ex_dtype).unwrap(); + let expr = expr.clone_inner().str().json_decode(Some(dtype), None); + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_json_path_match(expr: ExExpr, json_path: String) -> ExExpr { + let expr = expr.clone_inner().str().json_path_match(json_path.lit()); + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_split_into(expr: ExExpr, by: String, names: Vec) -> ExExpr { + let expr = expr + .clone_inner() + .str() + .splitn(by.lit(), names.len()) + .struct_() + .rename_fields(names); + + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_struct(ex_exprs: Vec) -> ExExpr { + let exprs = ex_exprs.iter().map(|e| e.clone_inner()).collect(); + let expr = dsl::as_struct(exprs); + + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_over(left: ExExpr, groups: Vec) -> ExExpr { + let expr = left.clone_inner().over(groups); + ExExpr::new(expr) +} + +#[rustler::nif] +pub fn expr_count_matches(expr: ExExpr, pattern: &str) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.str().count_matches(pattern.lit(), true)) +} + +#[rustler::nif] +pub fn expr_re_count_matches(expr: ExExpr, pattern: &str) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.str().count_matches(pattern.lit(), false)) +} + +#[rustler::nif] +pub fn expr_re_scan(expr: ExExpr, pattern: &str) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.str().extract_all(pattern.lit())) +} + +#[rustler::nif] +pub fn expr_re_named_captures(expr: ExExpr, pattern: &str) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new( + expr.str() + .extract_groups(pattern) + .expect("should extract groups"), + ) +} diff --git a/deps/explorer/native/explorer/src/lazyframe.rs b/deps/explorer/native/explorer/src/lazyframe.rs new file mode 100644 index 0000000000000000000000000000000000000000..348f5ce0e0b7020215f0ce95e1d003e7e432d415 --- /dev/null +++ b/deps/explorer/native/explorer/src/lazyframe.rs @@ -0,0 +1,394 @@ +use crate::{ + datatypes::ExSeriesDtype, expressions::ex_expr_to_exprs, ExDataFrame, ExExpr, ExLazyFrame, + ExplorerError, +}; +use polars::{lazy::dsl::Selector, prelude::*}; + +// Loads the IO functions for read/writing CSV, NDJSON, Parquet, etc. +pub mod io; + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn lf_compute(data: ExLazyFrame) -> Result { + let df = data.clone_inner().collect()?; + + Ok(ExDataFrame::new(df)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn lf_fetch(data: ExLazyFrame, n_rows: usize) -> Result { + Ok(ExDataFrame::new(data.clone_inner().fetch(n_rows)?)) +} + +#[rustler::nif] +pub fn lf_describe_plan(data: ExLazyFrame, optimized: bool) -> Result { + let lf = data.clone_inner(); + let plan = match optimized { + true => lf.describe_optimized_plan()?, + false => lf.describe_plan().expect("error"), + }; + Ok(plan) +} + +#[rustler::nif] +pub fn lf_head( + data: ExLazyFrame, + length: u32, + groups: Vec, +) -> Result { + let lf = data.clone_inner(); + let result_lf = if groups.is_empty() { + lf.limit(length) + } else { + lf.group_by_stable(groups).head(Some(length.try_into()?)) + }; + + Ok(ExLazyFrame::new(result_lf)) +} + +#[rustler::nif] +pub fn lf_tail( + data: ExLazyFrame, + length: u32, + groups: Vec, +) -> Result { + let lf = data.clone_inner(); + let result_lf = if groups.is_empty() { + lf.tail(length) + } else { + lf.group_by_stable(groups).tail(Some(length.try_into()?)) + }; + + Ok(ExLazyFrame::new(result_lf)) +} + +#[rustler::nif] +pub fn lf_names(data: ExLazyFrame) -> Result, ExplorerError> { + let mut lf = data.clone_inner(); + let names = lf + .collect_schema()? + .iter_names() + .map(|smart_string| smart_string.to_string()) + .collect(); + + Ok(names) +} + +#[rustler::nif] +pub fn lf_dtypes(data: ExLazyFrame) -> Result, ExplorerError> { + let mut dtypes: Vec = vec![]; + let schema = data.clone_inner().collect_schema()?; + + for (_name, dtype) in schema.iter_names_and_dtypes() { + dtypes.push(ExSeriesDtype::try_from(dtype)?) + } + + Ok(dtypes) +} + +#[rustler::nif] +pub fn lf_select(data: ExLazyFrame, columns: Vec<&str>) -> Result { + let lf = data.clone_inner().select(&[cols(columns)]); + Ok(ExLazyFrame::new(lf)) +} + +#[rustler::nif] +pub fn lf_drop(data: ExLazyFrame, columns: Vec<&str>) -> Result { + let lf = data.clone_inner().select(&[col("*").exclude(columns)]); + Ok(ExLazyFrame::new(lf)) +} + +#[rustler::nif] +pub fn lf_slice( + data: ExLazyFrame, + offset: i64, + length: u32, + groups: Vec, +) -> Result { + let lf = data.clone_inner(); + let result_lf = if groups.is_empty() { + lf.slice(offset, length) + } else { + let groups_exprs: Vec = groups.iter().map(col).collect(); + lf.group_by_stable(groups_exprs) + .agg([col("*").slice(offset, length)]) + .explode([col("*").exclude(groups)]) + }; + + Ok(ExLazyFrame::new(result_lf)) +} + +#[rustler::nif] +pub fn lf_explode(data: ExLazyFrame, columns: Vec<&str>) -> Result { + let lf = data.clone_inner().explode(columns); + Ok(ExLazyFrame::new(lf)) +} + +#[rustler::nif] +pub fn lf_unnest(data: ExLazyFrame, columns: Vec<&str>) -> Result { + let lf = data.clone_inner().unnest(columns); + Ok(ExLazyFrame::new(lf)) +} + +#[rustler::nif] +pub fn lf_filter_with(data: ExLazyFrame, ex_expr: ExExpr) -> Result { + let lf = data.clone_inner(); + let expr = ex_expr.clone_inner(); + + Ok(ExLazyFrame::new(lf.filter(expr))) +} + +#[rustler::nif] +pub fn lf_sort_with( + data: ExLazyFrame, + expressions: Vec, + directions: Vec, + maintain_order: bool, + nulls_last: bool, +) -> Result { + let exprs = ex_expr_to_exprs(expressions); + let sort_options = SortMultipleOptions::new() + .with_nulls_last(nulls_last) + .with_maintain_order(maintain_order) + .with_order_descending_multi(directions); + + let ldf = data.clone_inner().sort_by_exprs(exprs, sort_options); + + Ok(ExLazyFrame::new(ldf)) +} + +#[rustler::nif] +pub fn lf_grouped_sort_with( + data: ExLazyFrame, + expressions: Vec, + groups: Vec, + directions: Vec, +) -> Result { + let sort_options = SortMultipleOptions::new().with_order_descending_multi(directions); + // For grouped lazy frames, we need to use the `#sort_by` method that is + // less powerful, but can be used with `over`. + // See: https://docs.pola.rs/user-guide/expressions/window/#operations-per-group + let ldf = data + .clone_inner() + .with_columns([col("*").sort_by(expressions, sort_options).over(groups)]); + + Ok(ExLazyFrame::new(ldf)) +} + +#[rustler::nif] +pub fn lf_distinct( + data: ExLazyFrame, + subset: Vec, + columns_to_keep: Option>, +) -> Result { + let df = data.clone_inner(); + let subset = subset.iter().map(|x| x.into()).collect::>(); + let new_df = df.unique_stable(Some(subset), UniqueKeepStrategy::First); + + match columns_to_keep { + Some(columns) => Ok(ExLazyFrame::new(new_df.select(ex_expr_to_exprs(columns)))), + None => Ok(ExLazyFrame::new(new_df)), + } +} + +#[rustler::nif] +pub fn lf_mutate_with( + data: ExLazyFrame, + columns: Vec, +) -> Result { + let mutations = ex_expr_to_exprs(columns); + // Maybe there is a bug when some expressions are in use without this "comm_subexpr_elim" + // turned off. + let ldf = data + .clone_inner() + .with_comm_subexpr_elim(false) + .with_columns(mutations); + + Ok(ExLazyFrame::new(ldf)) +} + +#[rustler::nif] +pub fn lf_summarise_with( + data: ExLazyFrame, + groups: Vec, + aggs: Vec, +) -> Result { + let ldf = data.clone_inner(); + let groups = ex_expr_to_exprs(groups); + let aggs = ex_expr_to_exprs(aggs); + + let new_lf = if groups.is_empty() { + // We do add a "shadow" column to be able to group by it. + // This is going to force some aggregations like "mode" to be always inside + // a "list". + ldf.group_by_stable([1.lit().alias("__explorer_literal_for_group__")]) + .agg(aggs) + .select(&[col("*").exclude(["__explorer_literal_for_group__"])]) + } else { + ldf.group_by_stable(groups).agg(aggs) + }; + + Ok(ExLazyFrame::new(new_lf)) +} + +#[rustler::nif] +pub fn lf_rename_columns( + data: ExLazyFrame, + renames: Vec<(&str, &str)>, +) -> Result { + let df = data.clone_inner(); + let (existing, new): (Vec<_>, Vec<_>) = renames.iter().cloned().unzip(); + + Ok(ExLazyFrame::new(df.rename(existing, new))) +} + +#[rustler::nif] +pub fn lf_drop_nils( + data: ExLazyFrame, + subset: Option>, +) -> Result { + let ldf = data.clone_inner(); + let columns = subset.map(ex_expr_to_exprs); + + Ok(ExLazyFrame::new(ldf.drop_nulls(columns))) +} + +#[rustler::nif] +pub fn lf_pivot_longer( + data: ExLazyFrame, + id_vars: Vec, + value_vars: Vec, + names_to: String, + values_to: String, +) -> Result { + let ldf = data.clone_inner(); + let unpivot_opts = polars::lazy::dsl::UnpivotArgsDSL { + index: to_lazy_selectors(id_vars), + on: to_lazy_selectors(value_vars), + variable_name: Some(names_to.into()), + value_name: Some(values_to.into()), + }; + let new_df = ldf.unpivot(unpivot_opts); + Ok(ExLazyFrame::new(new_df)) +} + +fn to_lazy_selectors(values: Vec) -> Vec { + values + .into_iter() + .map(Selector::from) + .collect::>() +} + +#[rustler::nif] +pub fn lf_join( + data: ExLazyFrame, + other: ExLazyFrame, + left_on: Vec, + right_on: Vec, + how: &str, + suffix: &str, +) -> Result { + let how = match how { + "left" => JoinType::Left, + "inner" => JoinType::Inner, + "outer" => JoinType::Full, + "cross" => JoinType::Cross, + _ => { + return Err(ExplorerError::Other(format!( + "Join method {how} not supported" + ))) + } + }; + + let ldf = data.clone_inner(); + let ldf1 = other.clone_inner(); + + let new_ldf = match how { + // Cross-joins no longer accept keys. + // https://github.com/pola-rs/polars/pull/17305 + JoinType::Cross => ldf + .join_builder() + .with(ldf1) + .how(JoinType::Cross) + .suffix(suffix) + .finish(), + _ => ldf + .join_builder() + .with(ldf1) + .how(how) + .left_on(ex_expr_to_exprs(left_on)) + .right_on(ex_expr_to_exprs(right_on)) + .suffix(suffix) + .finish(), + }; + + Ok(ExLazyFrame::new(new_ldf)) +} + +#[rustler::nif] +pub fn lf_concat_rows(lazy_frames: Vec) -> Result { + let inputs: Vec = lazy_frames.iter().map(|lf| lf.clone_inner()).collect(); + let union_args = UnionArgs::default(); + let out_df = concat(inputs, union_args)?; + + Ok(ExLazyFrame::new(out_df)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn lf_concat_columns(ldfs: Vec) -> Result { + let mut previous_names = PlHashSet::new(); + + let renamed_ldfs: Vec = ldfs + .iter() + .enumerate() + .map(|(idx, ex_ldf)| { + let mut ldf = ex_ldf.clone_inner(); + let names: Vec = ldf + .collect_schema() + .expect("should be able to get schema") + .iter_names() + .map(|smart_string| smart_string.to_string()) + .collect(); + + let mut substitutions = vec![]; + + for name in names { + if previous_names.contains(&name) { + let new_name = format!("{name}_{idx}"); + previous_names.insert(new_name.clone()); + substitutions.push((name, new_name)) + } else { + previous_names.insert(name.clone()); + } + } + + if substitutions.is_empty() { + ldf + } else { + let (existing, new): (Vec, Vec) = + substitutions.iter().cloned().unzip(); + ldf.rename(existing, new) + } + }) + .collect(); + + let out_ldf = concat_lf_horizontal(renamed_ldfs, UnionArgs::default())?; + + Ok(ExLazyFrame::new(out_ldf)) +} + +#[rustler::nif] +pub fn lf_sql( + lf: ExLazyFrame, + sql_string: &str, + table_name: &str, +) -> Result { + let mut ctx = polars::sql::SQLContext::new(); + + let lf = lf.clone_inner(); + ctx.register(table_name, lf); + + match ctx.execute(sql_string) { + Ok(lf_sql) => Ok(ExLazyFrame::new(lf_sql)), + Err(polars_error) => Err(ExplorerError::Polars(polars_error)), + } +} diff --git a/deps/explorer/native/explorer/src/lazyframe/io.rs b/deps/explorer/native/explorer/src/lazyframe/io.rs new file mode 100644 index 0000000000000000000000000000000000000000..bfb00cdc43e1811fd3491fa342a2758e25b3f7ac --- /dev/null +++ b/deps/explorer/native/explorer/src/lazyframe/io.rs @@ -0,0 +1,325 @@ +use polars::prelude::*; +use std::fs::File; +use std::io::BufWriter; +use std::num::NonZeroUsize; + +use crate::dataframe::io::schema_from_dtypes_pairs; +use crate::datatypes::{ExParquetCompression, ExS3Entry, ExSeriesDtype}; +use crate::{ExLazyFrame, ExplorerError}; + +#[rustler::nif] +pub fn lf_from_parquet( + filename: &str, + stop_after_n_rows: Option, + columns: Option>, +) -> Result { + let options = ScanArgsParquet { + n_rows: stop_after_n_rows, + ..Default::default() + }; + + let cols: Vec = if let Some(cols) = columns { + cols.iter().map(col).collect() + } else { + vec![all()] + }; + + let lf = LazyFrame::scan_parquet(filename, options)?.select(cols); + + Ok(ExLazyFrame::new(lf)) +} + +// When we have more cloud entries, we could accept an Enum. +#[cfg(feature = "aws")] +#[rustler::nif(schedule = "DirtyIo")] +pub fn lf_from_parquet_cloud( + ex_entry: ExS3Entry, + stop_after_n_rows: Option, + columns: Option>, +) -> Result { + let options = ScanArgsParquet { + n_rows: stop_after_n_rows, + cloud_options: Some(ex_entry.config.to_cloud_options()), + ..Default::default() + }; + let cols: Vec = if let Some(cols) = columns { + cols.iter().map(col).collect() + } else { + vec![all()] + }; + let lf = LazyFrame::scan_parquet(ex_entry.to_string(), options)? + .with_comm_subplan_elim(false) + .with_streaming(true) + .select(cols); + + Ok(ExLazyFrame::new(lf)) +} + +#[cfg(not(feature = "aws"))] +#[rustler::nif(schedule = "DirtyIo")] +pub fn lf_from_parquet_cloud( + _ex_entry: ExS3Entry, + _stop_after_n_rows: Option, + _columns: Option>, +) -> Result { + Err(ExplorerError::Other("Explorer was compiled without the \"aws\" feature enabled. \ + This is mostly due to this feature being incompatible with your computer's architecture. \ + Please read the section about precompilation in our README.md: https://github.com/elixir-explorer/explorer#precompilation".to_string())) +} + +#[rustler::nif(schedule = "DirtyIo")] +pub fn lf_to_parquet( + data: ExLazyFrame, + filename: &str, + ex_compression: ExParquetCompression, + streaming: bool, +) -> Result<(), ExplorerError> { + let compression = ParquetCompression::try_from(ex_compression)?; + + let lf = data.clone_inner(); + + if streaming { + let options = ParquetWriteOptions { + compression, + statistics: StatisticsOptions::empty(), + row_group_size: None, + data_page_size: None, + maintain_order: false, + }; + + lf.with_comm_subplan_elim(false) + .sink_parquet(filename, options)?; + Ok(()) + } else { + let mut df = lf.collect()?; + + let file = File::create(filename)?; + let mut buf_writer = BufWriter::new(file); + + ParquetWriter::new(&mut buf_writer) + .with_compression(compression) + .finish(&mut df)?; + + Ok(()) + } +} + +#[cfg(feature = "aws")] +#[rustler::nif(schedule = "DirtyIo")] +pub fn lf_to_parquet_cloud( + data: ExLazyFrame, + ex_entry: ExS3Entry, + ex_compression: ExParquetCompression, +) -> Result<(), ExplorerError> { + let lf = data.clone_inner(); + let cloud_options = Some(ex_entry.config.to_cloud_options()); + let compression = ParquetCompression::try_from(ex_compression)?; + + let options = ParquetWriteOptions { + compression, + statistics: StatisticsOptions::empty(), + row_group_size: None, + data_page_size: None, + maintain_order: false, + }; + + lf.with_comm_subplan_elim(false).sink_parquet_cloud( + ex_entry.to_string(), + cloud_options, + options, + )?; + Ok(()) +} + +#[cfg(not(feature = "aws"))] +#[rustler::nif(schedule = "DirtyIo")] +pub fn lf_to_parquet_cloud( + _data: ExLazyFrame, + _ex_entry: ExS3Entry, + _ex_compression: ExParquetCompression, +) -> Result<(), ExplorerError> { + Err(ExplorerError::Other("Explorer was compiled without the \"aws\" feature enabled. \ + This is mostly due to this feature being incompatible with your computer's architecture. \ + Please read the section about precompilation in our README.md: https://github.com/elixir-explorer/explorer#precompilation".to_string())) +} + +#[rustler::nif(schedule = "DirtyIo")] +pub fn lf_from_ipc(filename: &str) -> Result { + let lf = LazyFrame::scan_ipc(filename, Default::default())?; + + Ok(ExLazyFrame::new(lf)) +} + +#[rustler::nif(schedule = "DirtyIo")] +pub fn lf_to_ipc( + data: ExLazyFrame, + filename: &str, + compression: Option<&str>, + streaming: bool, +) -> Result<(), ExplorerError> { + // Select the compression algorithm. + let compression = match compression { + Some("lz4") => Some(IpcCompression::LZ4), + Some("zstd") => Some(IpcCompression::ZSTD), + _ => None, + }; + + let lf = data.clone_inner(); + + if streaming { + let options = IpcWriterOptions { + compression, + maintain_order: false, + }; + lf.with_comm_subplan_elim(false) + .sink_ipc(filename, options)?; + Ok(()) + } else { + let mut df = lf.collect()?; + let file = File::create(filename)?; + let mut buf_writer = BufWriter::new(file); + IpcWriter::new(&mut buf_writer) + .with_compression(compression) + .finish(&mut df)?; + Ok(()) + } +} + +#[cfg(feature = "aws")] +#[rustler::nif(schedule = "DirtyIo")] +pub fn lf_to_ipc_cloud( + data: ExLazyFrame, + ex_entry: ExS3Entry, + compression: Option<&str>, +) -> Result<(), ExplorerError> { + let lf = data.clone_inner(); + let cloud_options = Some(ex_entry.config.to_cloud_options()); + // Select the compression algorithm. + let compression = match compression { + Some("lz4") => Some(IpcCompression::LZ4), + Some("zstd") => Some(IpcCompression::ZSTD), + _ => None, + }; + + let options = IpcWriterOptions { + compression, + maintain_order: false, + }; + lf.with_comm_subplan_elim(false).sink_ipc_cloud( + ex_entry.to_string(), + cloud_options, + options, + )?; + + Ok(()) +} + +#[rustler::nif] +#[allow(clippy::too_many_arguments)] +pub fn lf_from_csv( + filename: &str, + infer_schema_length: Option, + has_header: bool, + stop_after_n_rows: Option, + skip_rows: usize, + skip_rows_after_header: usize, + delimiter_as_byte: u8, + do_rechunk: bool, + dtypes: Vec<(&str, ExSeriesDtype)>, + encoding: &str, + null_vals: Vec, + parse_dates: bool, + eol_delimiter: Option, +) -> Result { + let encoding = match encoding { + "utf8-lossy" => CsvEncoding::LossyUtf8, + _ => CsvEncoding::Utf8, + }; + + let df = LazyCsvReader::new(filename) + .with_infer_schema_length(infer_schema_length) + .with_has_header(has_header) + .with_try_parse_dates(parse_dates) + .with_n_rows(stop_after_n_rows) + .with_separator(delimiter_as_byte) + .with_skip_rows(skip_rows) + .with_skip_rows_after_header(skip_rows_after_header) + .with_rechunk(do_rechunk) + .with_encoding(encoding) + .with_dtype_overwrite(schema_from_dtypes_pairs(dtypes)?) + .with_null_values(Some(NullValues::AllColumns( + null_vals.iter().map(|x| x.into()).collect(), + ))) + .with_eol_char(eol_delimiter.unwrap_or(b'\n')) + .finish()?; + + Ok(ExLazyFrame::new(df)) +} + +#[rustler::nif(schedule = "DirtyIo")] +pub fn lf_to_csv( + data: ExLazyFrame, + filename: &str, + include_headers: bool, + delimiter: u8, + streaming: bool, +) -> Result<(), ExplorerError> { + let lf = data.clone_inner(); + if streaming { + let serialize_options = SerializeOptions { + separator: delimiter, + ..Default::default() + }; + + let options = CsvWriterOptions { + include_header: include_headers, + maintain_order: true, + serialize_options, + ..Default::default() + }; + + lf.with_comm_subplan_elim(false) + .sink_csv(filename, options)?; + Ok(()) + } else { + let df = lf.collect()?; + let file = File::create(filename)?; + let mut buf_writer = BufWriter::new(file); + + CsvWriter::new(&mut buf_writer) + .include_header(include_headers) + .with_separator(delimiter) + .finish(&mut df.clone())?; + Ok(()) + } +} + +#[cfg(feature = "ndjson")] +#[rustler::nif] +pub fn lf_from_ndjson( + filename: String, + infer_schema_length: Option, + batch_size: usize, +) -> Result { + let batch_size = NonZeroUsize::new(batch_size).ok_or(ExplorerError::Other( + "\"batch_size\" expected to be non zero.".to_string(), + ))?; + let lf = LazyJsonLineReader::new(filename) + .with_infer_schema_length(infer_schema_length.and_then(NonZeroUsize::new)) + .with_batch_size(Some(batch_size)) + .finish()?; + + Ok(ExLazyFrame::new(lf)) +} + +#[cfg(not(feature = "ndjson"))] +#[rustler::nif] +pub fn lf_from_ndjson( + _filename: &str, + _infer_schema_length: Option, + _batch_size: usize, +) -> Result { + Err(ExplorerError::Other("Explorer was compiled without the \"ndjson\" feature enabled. \ + This is mostly due to this feature being incompatible with your computer's architecture. \ + Please read the section about precompilation in our README.md: https://github.com/elixir-explorer/explorer#precompilation".to_string())) +} diff --git a/deps/explorer/native/explorer/src/lib.rs b/deps/explorer/native/explorer/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..d16015f8471c5ba8dbec7767fd73e0d0c7fcde07 --- /dev/null +++ b/deps/explorer/native/explorer/src/lib.rs @@ -0,0 +1,71 @@ +// MiMalloc won´t compile on Windows with the GCC compiler. +// On Linux with Musl it won´t load correctly. +#[cfg(not(any( + all(windows, target_env = "gnu"), + all(target_os = "linux", target_env = "musl") +)))] +use mimalloc::MiMalloc; + +#[cfg(not(any( + all(windows, target_env = "gnu"), + all(target_os = "linux", target_env = "musl") +)))] +#[global_allocator] +static GLOBAL: MiMalloc = MiMalloc; + +#[cfg(feature = "cloud")] +mod cloud_writer; + +mod dataframe; +mod datatypes; +mod encoding; +mod error; +mod expressions; +mod lazyframe; +mod local_message; +mod series; + +pub use datatypes::{ + ExDataFrame, ExDataFrameRef, ExExpr, ExExprRef, ExLazyFrame, ExLazyFrameRef, ExSeries, + ExSeriesRef, +}; + +pub use error::ExplorerError; +use expressions::*; +use series::*; + +mod atoms { + rustler::atoms! { + calendar_iso_module = "Elixir.Calendar.ISO", + date_module = "Elixir.Date", + datetime_module = "Elixir.DateTime", + duration_module = "Elixir.Explorer.Duration", + naive_datetime_module = "Elixir.NaiveDateTime", + time_module = "Elixir.Time", + decimal_module = "Elixir.Decimal", + hour, + minute, + second, + day, + month, + year, + value, + precision, + millisecond, + microsecond, + nanosecond, + calendar, + nan, + infinity, + neg_infinity, + std_offset, + time_zone, + utc_offset, + zone_abbr, + coef, + exp, + sign, + } +} + +rustler::init!("Elixir.Explorer.PolarsBackend.Native"); diff --git a/deps/explorer/native/explorer/src/local_message.rs b/deps/explorer/native/explorer/src/local_message.rs new file mode 100644 index 0000000000000000000000000000000000000000..25e42283ed36eceb2b6a08fe06d1c6226bd35447 --- /dev/null +++ b/deps/explorer/native/explorer/src/local_message.rs @@ -0,0 +1,42 @@ +use rustler::env::SavedTerm; +use rustler::{Env, LocalPid, OwnedEnv, Resource, ResourceArc, Term}; + +pub struct LocalMessage { + pid: LocalPid, + env: OwnedEnv, + term: SavedTerm, +} + +impl LocalMessage { + pub fn new(pid: LocalPid, term: Term<'_>) -> Self { + let env = OwnedEnv::new(); + let term = env.save(term); + Self { pid, env, term } + } +} + +// This is only safe because we only use the object for its destructor +unsafe impl Sync for LocalMessage {} + +#[rustler::resource_impl] +impl Resource for LocalMessage { + fn destructor(self, env: Env) { + let owned_env = self.env; + + // If the send fails, the other process is gone. + owned_env.run(|owned_env| { + let term = self.term.load(owned_env); + let _ = env.send(&self.pid, term); + }); + } +} + +#[rustler::nif] +pub fn message_on_gc(pid: LocalPid, term: Term<'_>) -> ResourceArc { + LocalMessage::new(pid, term).into() +} + +#[rustler::nif] +pub fn is_message_on_gc(term: Term<'_>) -> bool { + term.decode::>().is_ok() +} diff --git a/deps/explorer/native/explorer/src/series.rs b/deps/explorer/native/explorer/src/series.rs new file mode 100644 index 0000000000000000000000000000000000000000..47a66e27fad494294b66e4d8b0f574b36b33f9bd --- /dev/null +++ b/deps/explorer/native/explorer/src/series.rs @@ -0,0 +1,1745 @@ +use crate::{ + datatypes::{ + ex_naive_datetime_to_timestamp, ExCorrelationMethod, ExDate, ExDecimal, ExNaiveDateTime, + ExRankMethod, ExSeriesDtype, ExTime, ExTimeUnit, ExValidValue, + }, + encoding, ExDataFrame, ExSeries, ExplorerError, +}; + +use encoding::encode_naive_datetime; + +use polars::prelude::*; +use polars_ops::chunked_array::cov::{cov, pearson_corr}; +use polars_ops::prelude::peaks::*; +use rustler::{Binary, Encoder, Env, Term}; + +pub mod from_list; +pub mod log; + +#[rustler::nif] +pub fn s_as_str(data: ExSeries) -> Result { + Ok(format!("{:?}", data.resource.0)) +} + +#[rustler::nif] +pub fn s_name(data: ExSeries) -> Result { + Ok(data.name().to_string()) +} + +#[rustler::nif] +pub fn s_rename(data: ExSeries, name: &str) -> Result { + let mut s = data.clone_inner(); + s.rename(name.into()); + Ok(ExSeries::new(s)) +} + +#[rustler::nif] +pub fn s_dtype(data: ExSeries) -> Result { + ExSeriesDtype::try_from(data.dtype()) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_slice(series: ExSeries, offset: i64, length: usize) -> Result { + Ok(ExSeries::new(series.slice(offset, length))) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_concat(series_vec: Vec) -> Result { + let mut iter = series_vec.iter(); + let mut series = iter.next().unwrap().clone_inner(); + + for s in iter { + series.append(s)?; + } + + Ok(ExSeries::new(series)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_mask(series: ExSeries, filter: ExSeries) -> Result { + if let Ok(ca) = filter.bool() { + let series = series.filter(ca)?; + Ok(ExSeries::new(series)) + } else { + Err(ExplorerError::Other("Expected a boolean mask".into())) + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_add(data: ExSeries, other: ExSeries) -> Result { + let s = data.clone_inner(); + let s1 = other.clone_inner(); + let result = s + s1; + Ok(ExSeries::new(result?)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_subtract(lhs: ExSeries, rhs: ExSeries) -> Result { + let left = lhs.clone_inner(); + let right = rhs.clone_inner(); + let result = left - right; + Ok(ExSeries::new(result?)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_multiply(data: ExSeries, other: ExSeries) -> Result { + let s = data.clone_inner(); + let s1 = other.clone_inner(); + let result = s * s1; + Ok(ExSeries::new(result?)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_divide(data: ExSeries, other: ExSeries) -> Result { + let s = data.clone_inner().cast(&DataType::Float64)?; + let s1 = other.clone_inner().cast(&DataType::Float64)?; + let result = s / s1; + Ok(ExSeries::new(result?)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_quotient(data: ExSeries, other: ExSeries) -> Result { + Ok(ExSeries::new(checked_div(data, other)?)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_remainder(data: ExSeries, other: ExSeries) -> Result { + let s = data.clone_inner(); + let s1 = other.clone_inner(); + let div = checked_div(data, other)?; + let mult = s1 * div; + let result = s - mult?; + + Ok(ExSeries::new(result?)) +} + +// There is a bug in Polars where broadcast is not applied to checked_div +// and instead it discards values. +fn checked_div(data: ExSeries, other: ExSeries) -> Result { + match data.len() { + 1 => { + let num = data.i64()?.get(0).unwrap(); + Ok(Series::new( + data.name().clone(), + other.i64()?.apply(|v| v.and_then(|v| num.checked_div(v))), + )) + } + _ => match other.len() { + 1 => Ok(data.checked_div_num(other.i64()?.get(0).unwrap())?), + _ => Ok(data.checked_div(&other)?), + }, + } +} + +#[rustler::nif] +pub fn s_head(series: ExSeries, length: Option) -> Result { + Ok(ExSeries::new(series.head(length))) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_tail(series: ExSeries, length: Option) -> Result { + Ok(ExSeries::new(series.tail(length))) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_shift(series: ExSeries, offset: i64) -> Result { + Ok(ExSeries::new(series.shift(offset))) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_sort( + series: ExSeries, + descending: bool, + maintain_order: bool, + multithreaded: bool, + nulls_last: bool, +) -> Result { + let opts = SortOptions { + descending, + maintain_order, + multithreaded, + nulls_last, + }; + Ok(ExSeries::new(series.sort_with(opts)?)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_argsort( + series: ExSeries, + descending: bool, + maintain_order: bool, + multithreaded: bool, + nulls_last: bool, +) -> Result { + let opts = SortOptions { + descending, + maintain_order, + multithreaded, + nulls_last, + }; + let indices = series.arg_sort(opts).into_series(); + Ok(ExSeries::new(indices)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_distinct(series: ExSeries) -> Result { + let unique = series.take(&series.arg_unique()?)?; + Ok(ExSeries::new(unique)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_unordered_distinct(series: ExSeries) -> Result { + let unique = series.unique()?; + Ok(ExSeries::new(unique)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_frequencies(series: ExSeries) -> Result { + let df = series.value_counts(true, true, "counts".into(), false)?; + Ok(ExDataFrame::new(df)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_cut( + series: ExSeries, + bins: Vec, + labels: Option>, + break_point_label: Option<&str>, + category_label: Option<&str>, + left_close: bool, + include_breaks: bool, +) -> Result { + let series = series.clone_inner(); + + // Cut is going to return a Series of a Struct. We need to convert it to a DF. + let cut_series = cut( + &series, + bins, + labels.map(|vec| vec.iter().map(|label| label.into()).collect()), + left_close, + include_breaks, + )?; + + if include_breaks { + let mut cut_df = DataFrame::new(cut_series.struct_()?.fields_as_series())?; + + let cut_df = cut_df.insert_column(0, series)?; + + cut_df.set_column_names([ + "values", + break_point_label.unwrap_or("break_point"), + category_label.unwrap_or("category"), + ])?; + + Ok(ExDataFrame::new(cut_df.clone())) + } else { + let mut cut_df = DataFrame::new(vec![series, cut_series])?; + cut_df.set_column_names(["values", category_label.unwrap_or("category")])?; + + Ok(ExDataFrame::new(cut_df.clone())) + } +} + +#[allow(clippy::too_many_arguments)] +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_qcut( + series: ExSeries, + quantiles: Vec, + labels: Option>, + break_point_label: Option<&str>, + category_label: Option<&str>, + allow_duplicates: bool, + left_close: bool, + include_breaks: bool, +) -> Result { + let series = series.clone_inner(); + + let qcut_series: Series = qcut( + &series, + quantiles, + labels.map(|vec| vec.iter().map(|label| label.into()).collect()), + left_close, + allow_duplicates, + include_breaks, + )?; + + if include_breaks { + let mut qcut_df = DataFrame::new(qcut_series.struct_()?.fields_as_series())?; + let qcut_df = qcut_df.insert_column(0, series)?; + + qcut_df.set_column_names([ + "values", + break_point_label.unwrap_or("break_point"), + category_label.unwrap_or("category"), + ])?; + + Ok(ExDataFrame::new(qcut_df.clone())) + } else { + let mut qcut_df = DataFrame::new(vec![series, qcut_series])?; + qcut_df.set_column_names(["values", category_label.unwrap_or("category")])?; + + Ok(ExDataFrame::new(qcut_df.clone())) + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_slice_by_indices(series: ExSeries, indices: Vec) -> Result { + let idx = UInt32Chunked::from_vec("idx".into(), indices); + let s1 = series.take(&idx)?; + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_slice_by_series(series: ExSeries, indices: ExSeries) -> Result { + match indices.strict_cast(&DataType::UInt32) { + Ok(casted) => { + let idx = casted.u32()?; + match series.take(idx) { + Ok(s1) => Ok(ExSeries::new(s1)), + Err(_) => Err(ExplorerError::Other( + "slice/2 cannot select from indices that are out-of-bounds".into(), + )), + } + } + Err(_) => Err(ExplorerError::Other( + "slice/2 expects a series of positive integers".into(), + )), + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_is_null(series: ExSeries) -> Result { + Ok(ExSeries::new(series.is_null().into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_is_not_null(series: ExSeries) -> Result { + Ok(ExSeries::new(series.is_not_null().into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_is_finite(series: ExSeries) -> Result { + Ok(ExSeries::new(series.is_finite()?.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_is_infinite(series: ExSeries) -> Result { + Ok(ExSeries::new(series.is_infinite()?.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_is_nan(series: ExSeries) -> Result { + Ok(ExSeries::new(series.is_nan()?.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_at_every(series: ExSeries, n: usize) -> Result { + Ok(ExSeries::new(series.gather_every(n, 0))) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_series_equal( + series: ExSeries, + other: ExSeries, + null_equal: bool, +) -> Result { + let result = if null_equal { + series.equals_missing(&other) + } else { + series.equals(&other) + }; + + Ok(result) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_equal(lhs: ExSeries, rhs: ExSeries) -> Result { + Ok(ExSeries::new( + lhs.clone_inner().equal(&rhs.clone_inner())?.into_series(), + )) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_not_equal(data: ExSeries, rhs: ExSeries) -> Result { + let s = data.clone_inner(); + let s1 = rhs.clone_inner(); + Ok(ExSeries::new(s.not_equal(&s1)?.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_greater(data: ExSeries, rhs: ExSeries) -> Result { + let s = data.clone_inner(); + let s1 = rhs.clone_inner(); + Ok(ExSeries::new(s.gt(&s1)?.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_greater_equal(data: ExSeries, rhs: ExSeries) -> Result { + let s = data.clone_inner(); + let s1 = rhs.clone_inner(); + Ok(ExSeries::new(s.gt_eq(&s1)?.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_less(data: ExSeries, rhs: ExSeries) -> Result { + let s = data.clone_inner(); + let s1 = rhs.clone_inner(); + Ok(ExSeries::new(s.lt(&s1)?.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_less_equal(data: ExSeries, rhs: ExSeries) -> Result { + let s = data.clone_inner(); + let s1 = rhs.clone_inner(); + Ok(ExSeries::new(s.lt_eq(&s1)?.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_in(s: ExSeries, rhs: ExSeries) -> Result { + let s = match s.dtype() { + DataType::Boolean + | DataType::Int8 + | DataType::Int16 + | DataType::Int32 + | DataType::Int64 + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 + | DataType::Float32 + | DataType::Float64 + | DataType::String + | DataType::Binary + | DataType::Date + | DataType::Time + | DataType::Decimal(_, _) + | DataType::Datetime(_, _) => is_in(&s, &rhs)?, + DataType::Categorical(Some(mapping), _) => { + let l_logical = s.categorical()?.physical(); + + match rhs.dtype() { + DataType::String => { + let mut r_ids: Vec> = vec![]; + + // In case the right-hand is a series of strings, we only care + // about members in the category on the left, or if it's None. + for opt in rhs.unique()?.str()?.into_iter() { + match opt { + Some(slice) => { + if let Some(id) = mapping.find(slice) { + r_ids.push(Some(id)); + } + } + None => r_ids.push(None), + } + } + + let r_logical = Series::new("r_logical".into(), r_ids); + + is_in(&l_logical.clone().into_series(), &r_logical)? + } + DataType::Categorical(Some(rhs_mapping), _) => { + if !mapping.same_src(rhs_mapping) { + return Err(ExplorerError::Other( + "cannot compare categories from different sources. See Explorer.Series.categorise/2".into(), + )); + } + + let r_logical = rhs.categorical()?.physical().clone().into_series(); + + is_in(&l_logical.clone().into_series(), &r_logical)? + } + + dt => panic!("in/2 does not work for categorical and {dt:?} pairs"), + } + } + dt => panic!("in/2 not implemented for {dt:?}"), + }; + + Ok(ExSeries::new(s.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_and(lhs: ExSeries, rhs: ExSeries) -> Result { + let and = lhs.bool()? & rhs.bool()?; + Ok(ExSeries::new(and.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_or(lhs: ExSeries, rhs: ExSeries) -> Result { + let or = lhs.bool()? | rhs.bool()?; + Ok(ExSeries::new(or.into_series())) +} + +#[rustler::nif] +pub fn s_size(series: ExSeries) -> Result { + Ok(series.len()) +} + +#[rustler::nif] +pub fn s_nil_count(series: ExSeries) -> Result { + Ok(series.null_count()) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_fill_missing_with_strategy( + series: ExSeries, + strategy: &str, +) -> Result { + let strat = match strategy { + "backward" => FillNullStrategy::Backward(None), + "forward" => FillNullStrategy::Forward(None), + "min" => FillNullStrategy::Min, + "max" => FillNullStrategy::Max, + "mean" => FillNullStrategy::Mean, + s => return Err(ExplorerError::Other(format!("Strategy {s} not supported"))), + }; + + Ok(ExSeries::new(series.fill_null(strat)?)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_fill_missing_with_atom(series: ExSeries, atom: &str) -> Result { + let value = cast_str_to_f64(atom); + let s = series.f64()?.fill_null_with_values(value)?.into_series(); + Ok(ExSeries::new(s)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_fill_missing_with_int(series: ExSeries, integer: i64) -> Result { + let s = series.i64()?.fill_null_with_values(integer)?.into_series(); + Ok(ExSeries::new(s)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_fill_missing_with_float(series: ExSeries, float: f64) -> Result { + let s = series.f64()?.fill_null_with_values(float)?.into_series(); + Ok(ExSeries::new(s)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_fill_missing_with_bin( + series: ExSeries, + binary: Binary, +) -> Result { + let s = match series.dtype() { + DataType::String => { + if let Ok(_string) = std::str::from_utf8(&binary) { + // This casting is necessary just because it's not possible to fill UTF8 series. + unsafe { + series + .cast_unchecked(&DataType::Binary)? + .binary()? + .fill_null_with_values(&binary)? + .cast_unchecked(&DataType::String)? + } + } else { + return Err(ExplorerError::Other("cannot cast to string".into())); + } + } + DataType::Binary => series + .binary()? + .fill_null_with_values(&binary)? + .into_series(), + dt => panic!("fill_missing/2 not implemented for {dt:?}"), + }; + Ok(ExSeries::new(s)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_fill_missing_with_date(series: ExSeries, date: ExDate) -> Result { + let s = series + .date()? + .fill_null_with_values(date.into())? + .cast(&DataType::Date)? + .into_series(); + Ok(ExSeries::new(s)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_fill_missing_with_datetime( + series: ExSeries, + ex_naive_datetime: ExNaiveDateTime, +) -> Result { + let time_unit = match series._dtype() { + DataType::Datetime(time_unit, _) => *time_unit, + _ => TimeUnit::Microseconds, + }; + + let timestamp = ex_naive_datetime_to_timestamp(ex_naive_datetime, time_unit)?; + + let s = series + .datetime()? + .fill_null_with_values(timestamp)? + .cast(series.dtype())? + .into_series(); + Ok(ExSeries::new(s)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_fill_missing_with_boolean( + series: ExSeries, + boolean: bool, +) -> Result { + let s = series.bool()?.fill_null_with_values(boolean)?.into_series(); + Ok(ExSeries::new(s)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_fill_missing_with_decimal( + _series: ExSeries, + _decimal: ExDecimal, +) -> Result { + // We need to make sure that the series dtype is aligned with the decimal's scale. + // let s = series + // .decimal()? + // .fill_null_with_values(decimal.signed_coef())? + // .into_series(); + // Ok(ExSeries::new(s)) + Err(ExplorerError::Other( + "fill_missing/2 with decimals is not supported yet by Polars".to_string(), + )) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_window_sum( + series: ExSeries, + window_size: usize, + weights: Option>, + min_periods: Option, + center: bool, +) -> Result { + let opts = rolling_opts_fixed_window(window_size, weights, min_periods, center); + let s1 = series.rolling_sum(opts)?; + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_window_mean( + series: ExSeries, + window_size: usize, + weights: Option>, + min_periods: Option, + center: bool, +) -> Result { + let opts = rolling_opts_fixed_window(window_size, weights, min_periods, center); + let s1 = series.rolling_mean(opts)?; + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_window_median( + series: ExSeries, + window_size: usize, + weights: Option>, + min_periods: Option, + center: bool, +) -> Result { + let opts = rolling_opts_fixed_window(window_size, weights, min_periods, center); + let s1 = series + .clone_inner() + .into_frame() + .lazy() + .select([col(series.name().clone()).rolling_median(opts)]) + .collect()? + .column(series.name())? + .clone(); + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_window_max( + series: ExSeries, + window_size: usize, + weights: Option>, + min_periods: Option, + center: bool, +) -> Result { + let opts = rolling_opts_fixed_window(window_size, weights, min_periods, center); + let s1 = series.rolling_max(opts)?; + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_window_min( + series: ExSeries, + window_size: usize, + weights: Option>, + min_periods: Option, + center: bool, +) -> Result { + let opts = rolling_opts_fixed_window(window_size, weights, min_periods, center); + let s1 = series.rolling_min(opts)?; + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_window_standard_deviation( + series: ExSeries, + window_size: usize, + weights: Option>, + min_periods: Option, + center: bool, +) -> Result { + let opts = rolling_opts_fixed_window(window_size, weights, min_periods, center); + let s1 = series.rolling_std(opts)?; + Ok(ExSeries::new(s1)) +} + +// Used for rolling functions - also see "expressions" module +pub fn rolling_opts_fixed_window( + window_size: usize, + weights: Option>, + min_periods: Option, + center: bool, +) -> RollingOptionsFixedWindow { + let min_periods: usize = if let Some(mp) = min_periods { + mp + } else { + window_size + }; + // let window_size_duration = Duration::new(window_size as i64); + + RollingOptionsFixedWindow { + window_size, + weights, + min_periods, + center, + ..Default::default() + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_ewm_mean( + series: ExSeries, + alpha: f64, + adjust: bool, + min_periods: usize, + ignore_nulls: bool, +) -> Result { + let opts = ewm_opts(alpha, adjust, min_periods, ignore_nulls); + let s1 = polars_ops::prelude::ewm_mean(&series, opts)?; + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_ewm_standard_deviation( + series: ExSeries, + alpha: f64, + adjust: bool, + bias: bool, + min_periods: usize, + ignore_nulls: bool, +) -> Result { + let opts = EWMOptions { + alpha, + adjust, + bias, + min_periods, + ignore_nulls, + }; + let s1 = polars_ops::prelude::ewm_std(&series, opts)?; + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_ewm_variance( + series: ExSeries, + alpha: f64, + adjust: bool, + bias: bool, + min_periods: usize, + ignore_nulls: bool, +) -> Result { + let opts = EWMOptions { + alpha, + adjust, + bias, + min_periods, + ignore_nulls, + }; + let s1 = polars_ops::prelude::ewm_var(&series, opts)?; + Ok(ExSeries::new(s1)) +} + +pub fn ewm_opts(alpha: f64, adjust: bool, min_periods: usize, ignore_nulls: bool) -> EWMOptions { + EWMOptions { + alpha, + adjust, + min_periods, + ignore_nulls, + ..Default::default() + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_to_list(env: Env, data: ExSeries) -> Result { + encoding::list_from_series(data, env) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_to_iovec(env: Env, series: ExSeries) -> Result { + if series.null_count() != 0 { + Err(ExplorerError::Other( + "cannot invoke to_iovec on series with nils".into(), + )) + } else { + encoding::iovec_from_series(series, env) + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_sum(env: Env, s: ExSeries) -> Result { + match s.dtype() { + DataType::Boolean => Ok(s.sum::()?.encode(env)), + DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 => { + Ok(s.sum::()?.encode(env)) + } + DataType::UInt8 | DataType::UInt16 | DataType::UInt32 | DataType::UInt64 => { + Ok(s.sum::()?.encode(env)) + } + DataType::Float32 | DataType::Float64 => { + Ok(encoding::term_from_float64(s.sum::()?, env)) + } + dt => panic!("sum/1 not implemented for {dt:?}"), + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_min(env: Env, s: ExSeries) -> Result { + match s.dtype() { + DataType::Int8 => Ok(s.min::()?.encode(env)), + DataType::Int16 => Ok(s.min::()?.encode(env)), + DataType::Int32 => Ok(s.min::()?.encode(env)), + DataType::Int64 => Ok(s.min::()?.encode(env)), + DataType::UInt8 => Ok(s.min::()?.encode(env)), + DataType::UInt16 => Ok(s.min::()?.encode(env)), + DataType::UInt32 => Ok(s.min::()?.encode(env)), + DataType::UInt64 => Ok(s.min::()?.encode(env)), + DataType::Float32 | DataType::Float64 | DataType::Decimal(_, _) => { + Ok(term_from_optional_float(s.min::()?, env)) + } + DataType::Date => Ok(s.min::()?.map(ExDate::from).encode(env)), + DataType::Time => Ok(s.min::()?.map(ExTime::from).encode(env)), + DataType::Datetime(unit, _) => Ok(s + .min::()? + .map(|v| encode_naive_datetime(v, *unit, env).unwrap()) + .encode(env)), + dt => panic!("min/1 not implemented for {dt:?}"), + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_max(env: Env, s: ExSeries) -> Result { + match s.dtype() { + DataType::Int8 => Ok(s.max::()?.encode(env)), + DataType::Int16 => Ok(s.max::()?.encode(env)), + DataType::Int32 => Ok(s.max::()?.encode(env)), + DataType::Int64 => Ok(s.max::()?.encode(env)), + DataType::UInt8 => Ok(s.max::()?.encode(env)), + DataType::UInt16 => Ok(s.max::()?.encode(env)), + DataType::UInt32 => Ok(s.max::()?.encode(env)), + DataType::UInt64 => Ok(s.max::()?.encode(env)), + DataType::Float32 | DataType::Float64 | DataType::Decimal(_, _) => { + Ok(term_from_optional_float(s.max::()?, env)) + } + DataType::Date => Ok(s.max::()?.map(ExDate::from).encode(env)), + DataType::Time => Ok(s.max::()?.map(ExTime::from).encode(env)), + DataType::Datetime(unit, _) => Ok(s + .max::()? + .map(|v| encode_naive_datetime(v, *unit, env).unwrap()) + .encode(env)), + dt => panic!("max/1 not implemented for {dt:?}"), + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_argmax(env: Env, s: ExSeries) -> Result { + Ok(s.arg_max().encode(env)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_argmin(env: Env, s: ExSeries) -> Result { + Ok(s.arg_min().encode(env)) +} + +fn is_numeric(dtype: &DataType) -> bool { + dtype.is_numeric() || matches!(dtype, DataType::Decimal(_, _)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_mean(env: Env, s: ExSeries) -> Result { + if is_numeric(s.dtype()) { + Ok(term_from_optional_float(s.mean(), env)) + } else { + panic!("mean/1 not implemented for {:?}", &s.dtype()) + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_median(env: Env, s: ExSeries) -> Result { + if is_numeric(s.dtype()) { + Ok(term_from_optional_float(s.median(), env)) + } else { + panic!("median/1 not implemented for {:?}", &s.dtype()) + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_mode(s: ExSeries) -> Result { + match mode::mode(&s) { + Ok(s) => Ok(ExSeries::new(s)), + Err(e) => Err(e.into()), + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_product(s: ExSeries) -> Result { + if is_numeric(s.dtype()) { + let series = s + .clone_inner() + .into_frame() + .lazy() + .select([col(s.name().clone()).product()]) + .collect()? + .column(s.name())? + .clone(); + + Ok(ExSeries::new(series)) + } else { + panic!("product/1 not implemented for {:?}", &s.dtype()) + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_variance(s: ExSeries, ddof: u8) -> Result { + if is_numeric(s.dtype()) { + let var_series = s + .clone_inner() + .into_frame() + .lazy() + .select([col(s.name().clone()).var(ddof)]) + .collect()? + .column(s.name())? + .clone(); + + Ok(ExSeries::new(var_series)) + } else { + panic!("variance/2 not implemented for {:?}", &s.dtype()) + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_standard_deviation(s: ExSeries, ddof: u8) -> Result { + if is_numeric(s.dtype()) { + let std_series = s + .clone_inner() + .into_frame() + .lazy() + .select([col(s.name().clone()).std(ddof)]) + .collect()? + .column(s.name())? + .clone(); + + Ok(ExSeries::new(std_series)) + } else { + panic!("standard_deviation/2 not implemented for {:?}", &s.dtype()) + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_skew(env: Env, s: ExSeries, bias: bool) -> Result { + if is_numeric(s.dtype()) { + Ok(term_from_optional_float(s.skew(bias)?, env)) + } else { + panic!("skew/2 not implemented for {:?}", &s.dtype()) + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_correlation( + env: Env, + s1: ExSeries, + s2: ExSeries, + ddof: u8, + method: ExCorrelationMethod, +) -> Result { + let s1 = s1.clone_inner().cast(&DataType::Float64)?; + let s2 = s2.clone_inner().cast(&DataType::Float64)?; + + let corr = match method { + ExCorrelationMethod::Pearson => pearson_corr(s1.f64()?, s2.f64()?, ddof), + ExCorrelationMethod::Spearman => { + let df = df!("s1" => s1, "s2" => s2)? + .lazy() + .with_column(spearman_rank_corr(col("s1"), col("s2"), ddof, true).alias("corr")) + .collect()?; + match df.column("corr")?.get(0)? { + AnyValue::Float64(x) => Some(x), + _ => None, + } + } + }; + Ok(term_from_optional_float(corr, env)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_covariance(env: Env, s1: ExSeries, s2: ExSeries, ddof: u8) -> Result { + let s1 = s1.clone_inner().cast(&DataType::Float64)?; + let s2 = s2.clone_inner().cast(&DataType::Float64)?; + let cov = cov(s1.f64()?, s2.f64()?, ddof); + Ok(term_from_optional_float(cov, env)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_all(s: ExSeries) -> Result { + let s = s.clone_inner(); + + Ok(s.bool()?.all()) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_any(s: ExSeries) -> Result { + let s = s.clone_inner(); + + Ok(s.bool()?.any()) +} + +fn term_from_optional_float(option: Option, env: Env<'_>) -> Term<'_> { + match option { + Some(float) => encoding::term_from_float64(float, env), + None => rustler::types::atom::nil().to_term(env), + } +} + +#[rustler::nif] +pub fn s_at(env: Env, series: ExSeries, idx: usize) -> Result { + encoding::resource_term_from_value(&series.resource, series.get(idx)?, env) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_cumulative_sum(series: ExSeries, reverse: bool) -> Result { + let new_series = polars_ops::prelude::cum_sum(&series, reverse)?; + Ok(ExSeries::new(new_series)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_cumulative_max(series: ExSeries, reverse: bool) -> Result { + let new_series = polars_ops::prelude::cum_max(&series, reverse)?; + Ok(ExSeries::new(new_series)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_cumulative_min(series: ExSeries, reverse: bool) -> Result { + let new_series = polars_ops::prelude::cum_min(&series, reverse)?; + Ok(ExSeries::new(new_series)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_cumulative_product(series: ExSeries, reverse: bool) -> Result { + let new_series = polars_ops::prelude::cum_prod(&series, reverse)?; + Ok(ExSeries::new(new_series)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_quantile<'a>( + env: Env<'a>, + s: ExSeries, + quantile: f64, + strategy: &str, +) -> Result, ExplorerError> { + let dtype = s.dtype(); + let strategy = parse_quantile_interpol_options(strategy); + match dtype { + DataType::Date => match s.date()?.quantile(quantile, strategy)? { + None => Ok(None::.encode(env)), + Some(days) => Ok(ExDate::from(days as i32).encode(env)), + }, + DataType::Time => match s.time()?.quantile(quantile, strategy)? { + None => Ok(None::.encode(env)), + Some(microseconds) => Ok(ExTime::from(microseconds as i64).encode(env)), + }, + DataType::Datetime(unit, None) => match s.datetime()?.quantile(quantile, strategy)? { + None => Ok(None::.encode(env)), + Some(time) => Ok(encode_naive_datetime(time as i64, *unit, env) + .unwrap() + .encode(env)), + }, + _ => encoding::resource_term_from_value( + &s.resource, + s.quantile_reduce(quantile, strategy)? + .into_series("quantile".into()) + .cast(dtype)? + .get(0)?, + env, + ), + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_peak_max(s: ExSeries) -> Result { + let ca = match s.dtype() { + DataType::Int8 => peak_max(s.i8()?), + DataType::Int16 => peak_max(s.i16()?), + DataType::Int32 => peak_max(s.i32()?), + DataType::Int64 => peak_max(s.i64()?), + + DataType::UInt8 => peak_max(s.u8()?), + DataType::UInt16 => peak_max(s.u16()?), + DataType::UInt32 => peak_max(s.u32()?), + DataType::UInt64 => peak_max(s.u64()?), + + DataType::Float32 => peak_max(s.f32()?), + DataType::Float64 => peak_max(s.f64()?), + DataType::Decimal(_, _) => peak_max(s.decimal()?), + + DataType::Date => peak_max(s.date()?), + DataType::Time => peak_max(s.time()?), + DataType::Datetime(_unit, None) => peak_max(s.datetime()?), + DataType::Duration(_unit) => peak_max(s.duration()?), + dt => panic!("peak_max/1 not implemented for {dt:?}"), + }; + + Ok(ExSeries::new(ca.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_peak_min(s: ExSeries) -> Result { + let ca = match s.dtype() { + DataType::Int8 => peak_min(s.i8()?), + DataType::Int16 => peak_min(s.i16()?), + DataType::Int32 => peak_min(s.i32()?), + DataType::Int64 => peak_min(s.i64()?), + + DataType::UInt8 => peak_min(s.u8()?), + DataType::UInt16 => peak_min(s.u16()?), + DataType::UInt32 => peak_min(s.u32()?), + DataType::UInt64 => peak_min(s.u64()?), + + DataType::Float32 => peak_min(s.f32()?), + DataType::Float64 => peak_min(s.f64()?), + DataType::Decimal(_, _) => peak_min(s.decimal()?), + + DataType::Date => peak_min(s.date()?), + DataType::Time => peak_min(s.time()?), + DataType::Datetime(_unit, None) => peak_min(s.datetime()?), + DataType::Duration(_unit) => peak_min(s.duration()?), + dt => panic!("peak_min/1 not implemented for {dt:?}"), + }; + + Ok(ExSeries::new(ca.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_reverse(s: ExSeries) -> Result { + Ok(ExSeries::new(s.reverse())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_n_distinct(s: ExSeries) -> Result { + Ok(s.n_unique()?) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_cast(s: ExSeries, to_type: ExSeriesDtype) -> Result { + let dtype = DataType::try_from(&to_type)?; + Ok(ExSeries::new(s.cast(&dtype)?)) +} + +pub fn cast_str_to_f64(atom: &str) -> f64 { + match atom { + "nan" => f64::NAN, + "infinity" => f64::INFINITY, + "neg_infinity" => f64::NEG_INFINITY, + _ => panic!("unknown literal {atom:?}"), + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_categories(s: ExSeries) -> Result { + match s.dtype() { + DataType::Categorical(Some(mapping), _) => { + let size = mapping.len() as u32; + let categories: Vec<&str> = (0..size).map(|id| mapping.get(id)).collect(); + let series = Series::new("categories".into(), &categories); + Ok(ExSeries::new(series)) + } + _ => panic!("Cannot get categories from non categorical series"), + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_categorise(s: ExSeries, cat: ExSeries) -> Result { + match cat.dtype() { + DataType::Categorical(Some(mapping), _) => { + let chunks = if s.dtype() == &DataType::String { + let ids: ChunkedArray = s + .str()? + .into_iter() + .map(|opt_str| opt_str.and_then(|slice| mapping.find(slice))) + .collect(); + + ids + } else { + s.cast(&DataType::UInt32)?.u32()?.clone() + }; + + let categorical_chunks = unsafe { + CategoricalChunked::from_cats_and_rev_map_unchecked( + chunks, + mapping.clone(), + false, + CategoricalOrdering::default(), + ) + }; + Ok(ExSeries::new(categorical_chunks.into_series())) + } + _ => panic!("Cannot get categories from non categorical or string series"), + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_sample_n( + series: ExSeries, + n: usize, + replace: bool, + shuffle: bool, + seed: Option, +) -> Result { + let new_s = series.sample_n(n, replace, shuffle, seed)?; + + Ok(ExSeries::new(new_s)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_sample_frac( + series: ExSeries, + frac: f64, + replace: bool, + shuffle: bool, + seed: Option, +) -> Result { + let new_s = series.sample_frac(frac, replace, shuffle, seed)?; + + Ok(ExSeries::new(new_s)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_rank( + series: ExSeries, + method: ExRankMethod, + descending: bool, + seed: Option, +) -> Result { + let rank_method = parse_rank_method_options(method, descending); + let rank_data_type = match rank_method.method { + RankMethod::Average => DataType::Float64, + RankMethod::Ordinal => DataType::UInt32, + _ => DataType::Int64, + }; + + let new_s = series + .rank(rank_method, seed) + .cast(&rank_data_type)? + .into_series(); + + Ok(ExSeries::new(new_s)) +} + +pub fn parse_rank_method_options(strategy: ExRankMethod, descending: bool) -> RankOptions { + match strategy { + ExRankMethod::Ordinal => RankOptions { + method: RankMethod::Ordinal, + descending, + }, + ExRankMethod::Random => RankOptions { + method: RankMethod::Random, + descending, + }, + ExRankMethod::Average => RankOptions { + method: RankMethod::Average, + descending, + }, + ExRankMethod::Min => RankOptions { + method: RankMethod::Min, + descending, + }, + ExRankMethod::Max => RankOptions { + method: RankMethod::Max, + descending, + }, + ExRankMethod::Dense => RankOptions { + method: RankMethod::Dense, + descending, + }, + } +} + +pub fn parse_quantile_interpol_options(strategy: &str) -> QuantileInterpolOptions { + match strategy { + "nearest" => QuantileInterpolOptions::Nearest, + "lower" => QuantileInterpolOptions::Lower, + "higher" => QuantileInterpolOptions::Higher, + "midpoint" => QuantileInterpolOptions::Midpoint, + "linear" => QuantileInterpolOptions::Linear, + _ => QuantileInterpolOptions::Nearest, + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_coalesce(s1: ExSeries, s2: ExSeries) -> Result { + let coalesced = s1.zip_with(&s1.is_not_null(), &s2)?; + Ok(ExSeries::new(coalesced)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_select( + pred: ExSeries, + on_true: ExSeries, + on_false: ExSeries, +) -> Result { + match pred.len() { + 1 => match pred.bool().unwrap().get(0).unwrap() { + true => Ok(on_true), + false => Ok(on_false), + }, + _ => { + let selected = on_true.zip_with(pred.bool().unwrap(), &on_false)?; + Ok(ExSeries::new(selected)) + } + } +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_not(s1: ExSeries) -> Result { + let s2 = s1 + .bool()? + .into_iter() + .map(|opt_v| opt_v.map(|v| !v)) + .collect(); + + Ok(ExSeries::new(s2)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_contains(s1: ExSeries, pattern: &str, literal: bool) -> Result { + let chunked_array = if literal { + s1.str()?.contains_literal(pattern)? + } else { + s1.str()?.contains(pattern, true)? + }; + Ok(ExSeries::new(chunked_array.into())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_upcase(s1: ExSeries) -> Result { + Ok(ExSeries::new(s1.str()?.to_uppercase().into())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_downcase(s1: ExSeries) -> Result { + Ok(ExSeries::new(s1.str()?.to_lowercase().into())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_replace( + s1: ExSeries, + pattern: &str, + replacement: &str, + literal: bool, +) -> Result { + let chunked_array = if literal { + s1.str()?.replace_literal_all(pattern, replacement)? + } else { + s1.str()?.replace_all(pattern, replacement)? + }; + Ok(ExSeries::new(chunked_array.into())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_strip(s1: ExSeries, pattern: Option<&str>) -> Result { + // There are no eager strip functions. + let pattern = match pattern { + None => String::from(r"^[ \s]+|[ \s]+$"), + Some(string) => format!(r#"^[{}]+|[{}]+$"#, &string, &string), + }; + + // replace only replaces the leftmost match, so we need to call it twice. + Ok(ExSeries::new( + s1.str()? + .replace(pattern.as_str(), "")? + .replace(pattern.as_str(), "")? + .into(), + )) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_lstrip(s1: ExSeries, pattern: Option<&str>) -> Result { + // There are no eager strip functions. + let pattern = match pattern { + None => String::from(r"^[ \s]+"), + Some(string) => format!(r#"^[{}]+"#, &string), + }; + + Ok(ExSeries::new( + s1.str()?.replace(pattern.as_str(), "")?.into(), + )) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_rstrip(s1: ExSeries, pattern: Option<&str>) -> Result { + // There are no eager strip functions. + let pattern = match pattern { + None => String::from(r"[ \s]+$"), + Some(string) => format!(r#"[{}]+$"#, &string), + }; + + Ok(ExSeries::new( + s1.str()?.replace(pattern.as_str(), "")?.into(), + )) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_substring( + s: ExSeries, + offset: i64, + length: Option, +) -> Result { + let length = match length { + Some(l) => l.lit(), + None => Expr::Literal(LiteralValue::Null), + }; + let s2 = s + .clone_inner() + .into_frame() + .lazy() + .select([col(s.name().clone()).str().slice(offset.lit(), length)]) + .collect()? + .column(s.name())? + .clone(); + Ok(ExSeries::new(s2)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_split(s1: ExSeries, by: &str) -> Result { + let s2 = s1 + .str()? + .split(&ChunkedArray::new("a".into(), &[by])) + .into_series(); + + Ok(ExSeries::new(s2)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_split_into(s1: ExSeries, by: &str, names: Vec) -> Result { + let s2 = s1 + .clone_inner() + .into_frame() + .lazy() + .select([col(s1.name().clone()) + .str() + .splitn(by.lit(), names.len()) + .struct_() + .rename_fields(names) + .alias(s1.name().clone())]) + .collect()? + .column(s1.name())? + .clone(); + + Ok(ExSeries::new(s2)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_round(s: ExSeries, decimals: u32) -> Result { + Ok(ExSeries::new(s.round(decimals)?.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_floor(s: ExSeries) -> Result { + Ok(ExSeries::new(s.floor()?.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_ceil(s: ExSeries) -> Result { + Ok(ExSeries::new(s.ceil()?.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_abs(s: ExSeries) -> Result { + Ok(ExSeries::new(abs(&s)?)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_day_of_week(s: ExSeries) -> Result { + let s1 = s.weekday()?.into_series(); + + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_day_of_year(s: ExSeries) -> Result { + let s1 = s.ordinal_day()?.into_series(); + + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_week_of_year(s: ExSeries) -> Result { + let s1 = s.week()?.into_series(); + + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_month(s: ExSeries) -> Result { + let s1 = s.month()?.into_series(); + + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_year(s: ExSeries) -> Result { + let s1 = s.year()?.into_series(); + + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_hour(s: ExSeries) -> Result { + let s1 = s.hour()?.into_series(); + + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_minute(s: ExSeries) -> Result { + let s1 = s.minute()?.into_series(); + + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_second(s: ExSeries) -> Result { + let s1 = s.second()?.into_series(); + + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_strptime( + s: ExSeries, + format_string: Option<&str>, + precision: Option, +) -> Result { + let timeunit = match precision { + None => TimeUnit::Microseconds, + Some(precision) => TimeUnit::try_from(&precision).unwrap(), + }; + + let s1 = s + .str()? + .as_datetime( + format_string, + timeunit, + true, + false, + None, + &StringChunked::from_iter(std::iter::once("earliest")), + )? + .into_series(); + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_strftime(s: ExSeries, format_string: &str) -> Result { + let s1 = s.strftime(format_string)?; + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_clip_integer(s: ExSeries, min: i64, max: i64) -> Result { + let s1 = clip( + &s, + &Series::new("min_clip".into(), &[min]), + &Series::new("max_clip".into(), &[max]), + )?; + + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_clip_float(s: ExSeries, min: f64, max: f64) -> Result { + let s1 = clip( + &s, + &Series::new("min_clip".into(), &[min]), + &Series::new("max_clip".into(), &[max]), + )?; + + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_sin(s: ExSeries) -> Result { + let s1 = s.f64()?.apply_values(|o| o.sin()).into(); + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_cos(s: ExSeries) -> Result { + let s1 = s.f64()?.apply_values(|o| o.cos()).into(); + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_tan(s: ExSeries) -> Result { + let s1 = s.f64()?.apply_values(|o| o.tan()).into(); + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_asin(s: ExSeries) -> Result { + let s1 = s.f64()?.apply_values(|o| o.asin()).into(); + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_acos(s: ExSeries) -> Result { + let s1 = s.f64()?.apply_values(|o| o.acos()).into(); + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_atan(s: ExSeries) -> Result { + let s1 = s.f64()?.apply_values(|o| o.atan()).into(); + Ok(ExSeries::new(s1)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_join(s1: ExSeries, separator: &str) -> Result { + let s2 = s1 + .list()? + .lst_join(&ChunkedArray::new("a".into(), &[separator]), true)? + .into_series(); + + Ok(ExSeries::new(s2)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_lengths(s: ExSeries) -> Result { + let s2 = s.list()?.lst_lengths().into_series(); + + Ok(ExSeries::new(s2)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +fn s_member( + s: ExSeries, + value: ExValidValue, + inner_dtype: ExSeriesDtype, +) -> Result { + let inner_dtype = DataType::try_from(&inner_dtype)?; + let value_expr = value.lit_with_matching_precision(&inner_dtype); + + let s2 = s + .clone_inner() + .into_frame() + .lazy() + .select([col(s.name().clone()).list().contains(value_expr)]) + .collect()? + .column(s.name())? + .clone(); + + Ok(ExSeries::new(s2)) +} + +#[rustler::nif] +pub fn s_field(s: ExSeries, name: &str) -> Result { + let s2 = s + .clone_inner() + .into_frame() + .lazy() + .select([col(s.name().clone()) + .struct_() + .field_by_name(name) + .alias(name)]) + .collect()? + .column(name)? + .clone(); + Ok(ExSeries::new(s2)) +} + +#[rustler::nif] +pub fn s_json_decode(s: ExSeries, ex_dtype: ExSeriesDtype) -> Result { + let dtype = DataType::try_from(&ex_dtype).unwrap(); + let s2 = s + .clone_inner() + .into_frame() + .lazy() + .select([col(s.name().clone()) + .str() + .json_decode(Some(dtype), None) + .alias(s.name().clone())]) + .collect()? + .column(s.name())? + .clone(); + Ok(ExSeries::new(s2)) +} + +#[rustler::nif] +pub fn s_json_path_match(s: ExSeries, json_path: String) -> Result { + let var_series = s + .clone_inner() + .into_frame() + .lazy() + .select([col(s.name().clone()).str().json_path_match(json_path.lit())]) + .collect()? + .column(s.name())? + .clone(); + + Ok(ExSeries::new(var_series)) +} + +#[rustler::nif] +pub fn s_row_index(series: ExSeries) -> Result { + let len = u32::try_from(series.len())?; + let s = Series::new("row_index".into(), 0..len); + Ok(ExSeries::new(s)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_count_matches( + s1: ExSeries, + pattern: &str, + literal: bool, +) -> Result { + let chunked_array = if literal { + s1.str()?.count_matches(pattern, true)? + } else { + s1.str()?.count_matches(pattern, false)? + }; + Ok(ExSeries::new(chunked_array.into())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_re_scan(s1: ExSeries, pattern: &str) -> Result { + let chunked_array = s1.str()?.extract_all(pattern)?; + Ok(ExSeries::new(chunked_array.into())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_re_named_captures(s1: ExSeries, pattern: &str) -> Result { + let s2 = s1 + .clone_inner() + .into_frame() + .lazy() + .with_column( + col(s1.name().clone()) + .str() + .extract_groups(pattern)? + .alias(s1.name().clone()), + ) + .collect()? + .column(s1.name())? + .clone(); + Ok(ExSeries::new(s2)) +} diff --git a/deps/explorer/native/explorer/src/series/from_list.rs b/deps/explorer/native/explorer/src/series/from_list.rs new file mode 100644 index 0000000000000000000000000000000000000000..42fe9716baf712e9eb81c062b0a06ea4dfcd626d --- /dev/null +++ b/deps/explorer/native/explorer/src/series/from_list.rs @@ -0,0 +1,486 @@ +use crate::atoms; +use crate::datatypes::{ + ex_datetime_to_timestamp, ex_naive_datetime_to_timestamp, ExDate, ExDateTime, ExDecimal, + ExDuration, ExNaiveDateTime, ExSeriesDtype, ExTime, ExTimeUnit, +}; +use crate::{ExSeries, ExplorerError}; + +use polars::datatypes::DataType; +use polars::prelude::*; +use rustler::{Binary, Error, ListIterator, NifResult, Term, TermType}; +use std::slice; + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_from_list_date(name: &str, val: Term) -> Result { + let iterator = val + .decode::() + .map_err(|err| ExplorerError::Other(format!("expecting list as term: {err:?}")))?; + + let values: Vec> = iterator + .map(|item| match item.get_type() { + TermType::Integer => item.decode::>().map_err(|err| { + ExplorerError::Other(format!("int number is too big for an i32: {err:?}")) + }), + TermType::Map => item + .decode::() + .map(|ex_date| Some(i32::from(ex_date))) + .map_err(|error| { + ExplorerError::Other(format!( + "cannot decode a valid date from term. error: {error:?}" + )) + }), + TermType::Atom => Ok(None), + term_type => Err(ExplorerError::Other(format!( + "from_list/2 for dates not implemented for {term_type:?}" + ))), + }) + .collect::>, ExplorerError>>()?; + + Series::new(name.into(), values) + .cast(&DataType::Date) + .map(ExSeries::new) + .map_err(|error| { + ExplorerError::Other(format!( + "from_list/2 cannot cast integer series to a valid date series: {error:?}" + )) + }) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_from_list_naive_datetime( + name: &str, + val: Term, + precision: ExTimeUnit, +) -> Result { + let timeunit = TimeUnit::try_from(&precision)?; + let iterator = val + .decode::() + .map_err(|err| ExplorerError::Other(format!("expecting list as term: {err:?}")))?; + + let values: Vec> = iterator + .map(|item| match item.get_type() { + TermType::Integer => item.decode::>().map_err(|err| { + ExplorerError::Other(format!("int number is too big for an i64: {err:?}")) + }), + TermType::Map => item + .decode::() + .map_err(|error| { + ExplorerError::Other(format!( + "cannot decode a valid naive datetime from term. error: {error:?}" + )) + }) + .and_then(|ex_naive_datetime| { + ex_naive_datetime_to_timestamp(ex_naive_datetime, timeunit).map(Some) + }), + TermType::Atom => Ok(None), + term_type => Err(ExplorerError::Other(format!( + "from_list/2 for naive datetimes not implemented for {term_type:?}" + ))), + }) + .collect::>, ExplorerError>>()?; + + Series::new(name.into(), values) + .cast(&DataType::Datetime(timeunit, None)) + .map(ExSeries::new) + .map_err(|error| { + ExplorerError::Other(format!( + "from_list/2 cannot cast integer series to a valid naive datetime series: {error:?}" + )) + }) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_from_list_datetime( + name: &str, + val: Term, + precision: ExTimeUnit, + time_zone_str: Option<&str>, +) -> Result { + let timeunit = TimeUnit::try_from(&precision)?; + let time_zone = time_zone_str.map(|s| s.to_string()); + let iterator = val + .decode::() + .map_err(|err| ExplorerError::Other(format!("expecting list as term: {err:?}")))?; + + let values: Vec> = iterator + .map(|item| match item.get_type() { + TermType::Integer => item.decode::>().map_err(|err| { + ExplorerError::Other(format!("int number is too big for an i64: {err:?}")) + }), + TermType::Map => item + .decode::() + .map_err(|error| { + ExplorerError::Other(format!( + "cannot decode a valid datetime from term. error: {error:?}" + )) + }) + .and_then(|ex_datetime| ex_datetime_to_timestamp(ex_datetime, timeunit).map(Some)), + TermType::Atom => Ok(None), + term_type => Err(ExplorerError::Other(format!( + "from_list/2 for datetimes not implemented for {term_type:?}" + ))), + }) + .collect::>, ExplorerError>>()?; + + Series::new(name.into(), values) + .cast(&DataType::Datetime( + timeunit, + time_zone.map(|value| value.into()), + )) + .map(ExSeries::new) + .map_err(|error| { + ExplorerError::Other(format!( + "from_list/2 cannot cast integer series to a valid datetime series: {error:?}" + )) + }) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_from_list_duration( + name: &str, + val: Term, + precision: ExTimeUnit, +) -> Result { + let timeunit = TimeUnit::try_from(&precision)?; + let iterator = val + .decode::() + .map_err(|err| ExplorerError::Other(format!("expecting list as term: {err:?}")))?; + + let values: Vec> = iterator + .map(|item| match item.get_type() { + TermType::Integer => item.decode::>().map_err(|err| { + ExplorerError::Other(format!("int number is too big for an i64: {err:?}")) + }), + TermType::Map => item + .decode::() + .map(|ex_duration| Some(i64::from(ex_duration))) + .map_err(|error| { + ExplorerError::Other(format!( + "cannot decode a valid duration from term. error: {error:?}" + )) + }), + TermType::Atom => Ok(None), + term_type => Err(ExplorerError::Other(format!( + "from_list/2 for durations not implemented for {term_type:?}" + ))), + }) + .collect::>, ExplorerError>>()?; + + Series::new(name.into(), values) + .cast(&DataType::Duration(timeunit)) + .map(ExSeries::new) + .map_err(|error| { + ExplorerError::Other(format!( + "from_list/2 cannot cast integer series to a valid duration series: {error:?}" + )) + }) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_from_list_time(name: &str, val: Term) -> Result { + let iterator = val + .decode::() + .map_err(|err| ExplorerError::Other(format!("expecting list as term: {err:?}")))?; + + let values: Vec> = iterator + .map(|item| match item.get_type() { + TermType::Integer => item.decode::>().map_err(|err| { + ExplorerError::Other(format!("int number is too big for an i64: {err:?}")) + }), + TermType::Map => item + .decode::() + .map(|ex_time| Some(i64::from(ex_time))) + .map_err(|error| { + ExplorerError::Other(format!( + "cannot decode a valid time from term. error: {error:?}" + )) + }), + TermType::Atom => Ok(None), + term_type => Err(ExplorerError::Other(format!( + "from_list/2 for time not implemented for {term_type:?}" + ))), + }) + .collect::>, ExplorerError>>()?; + + Series::new(name.into(), values) + .cast(&DataType::Time) + .map(ExSeries::new) + .map_err(|error| { + ExplorerError::Other(format!( + "from_list/2 cannot cast integer series to a valid time series: {error:?}" + )) + }) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_from_list_null(name: &str, length: usize) -> ExSeries { + let s = Series::new_null(name.into(), length); + ExSeries::new(Series::new(name.into(), s)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_from_list_decimal( + name: &str, + val: Term, + precision: Option, + scale: Option, +) -> Result { + let iterator = val + .decode::() + .map_err(|err| ExplorerError::Other(format!("expecting list as term: {err:?}")))?; + + let values: Vec = iterator + .map(|item| match item.get_type() { + TermType::Integer => { + let s = scale.unwrap_or(0); + item.decode::() + .map(|num| AnyValue::Decimal(num, s)) + .map_err(|err| { + ExplorerError::Other(format!("int number is too big for an i128: {err:?}")) + }) + } + + TermType::Map => item + .decode::() + .map(|ex_decimal| AnyValue::Decimal(ex_decimal.signed_coef(), ex_decimal.scale())) + .map_err(|error| { + ExplorerError::Other(format!( + "cannot decode a valid decimal from term; check that `coef` fits into an `i128`. error: {error:?}" + )) + }), + TermType::Atom => Ok(AnyValue::Null), + + TermType::Float => item + .decode::() + .map(|num| match native_float_to_decimal_parts(num) { + Some((integer, scale)) => AnyValue::Decimal(integer, scale), + None => AnyValue::Null, + }) + .map_err(|err| { + ExplorerError::Other(format!("float number is too big f64: {err:?}")) + }), + term_type => Err(ExplorerError::Other(format!( + "from_list/2 for decimals not implemented for {term_type:?}" + ))), + }) + .collect::, ExplorerError>>()?; + + let mut series = Series::from_any_values(name.into(), &values, true)?; + + match series.dtype() { + DataType::Decimal(result_precision, result_scale) => { + let p: Option = Some(precision.unwrap_or(result_precision.unwrap_or(38))); + let s: Option = Some(scale.unwrap_or(result_scale.unwrap_or(0))); + + if *result_precision != p || *result_scale != s { + series = series.cast(&DataType::Decimal(p, s))?; + } + } + // An empty list will result in the `Null` dtype. + DataType::Null => { + let p = Some(precision.unwrap_or(38)); + let s = Some(scale.unwrap_or(0)); + series = series.cast(&DataType::Decimal(p, s))?; + } + other_dtype => panic!("expected dtype to be Decimal. found: {other_dtype:?}"), + } + + Ok(ExSeries::new(series)) +} + +fn native_float_to_decimal_parts(float: f64) -> Option<(i128, usize)> { + let float_str = float.to_string(); + + match float_str.split_once(".") { + Some((integer_part, fraction_part)) => { + let new_str = integer_part.to_string() + fraction_part; + let coef: i128 = new_str.parse().expect("expecting a valid i128 number"); + Some((coef, fraction_part.len())) + } + + None => { + let res_coef = float_str.parse::(); + match res_coef { + Ok(coef) => Some((coef, 0)), + Err(_) => None, + } + } + } +} + +macro_rules! from_list { + ($name:ident, $type:ty) => { + #[rustler::nif(schedule = "DirtyCpu")] + pub fn $name(name: &str, val: Term) -> NifResult { + val.decode::>>() + .map(|values| ExSeries::new(Series::new(name.into(), values.as_slice()))) + } + }; +} + +from_list!(s_from_list_s8, i8); +from_list!(s_from_list_s16, i16); +from_list!(s_from_list_s32, i32); +from_list!(s_from_list_s64, i64); + +from_list!(s_from_list_u8, u8); +from_list!(s_from_list_u16, u16); +from_list!(s_from_list_u32, u32); +from_list!(s_from_list_u64, u64); + +from_list!(s_from_list_bool, bool); +from_list!(s_from_list_str, String); + +macro_rules! from_list_float { + ($name:ident, $type:ty, $module:ident) => { + #[rustler::nif(schedule = "DirtyCpu")] + pub fn $name(name: &str, val: Term) -> NifResult { + let nan = atoms::nan(); + let infinity = atoms::infinity(); + let neg_infinity = atoms::neg_infinity(); + let nil = rustler::types::atom::nil(); + + val.decode::()? + .map(|item| match item.get_type() { + TermType::Float => item.decode::>(), + TermType::Integer => { + let int_value = item.decode::().unwrap(); + Ok(Some(int_value as $type)) + } + TermType::Atom => { + if nan.eq(&item) { + Ok(Some($module::NAN)) + } else if infinity.eq(&item) { + Ok(Some($module::INFINITY)) + } else if neg_infinity.eq(&item) { + Ok(Some($module::NEG_INFINITY)) + } else if nil.eq(&item) { + Ok(None) + } else { + let message = format!( + "from_list/2 cannot read the atom `{item:?}` for a float series" + ); + Err(Error::RaiseTerm(Box::new(message))) + } + } + term_type => { + let message = format!("from_list/2 not implemented for {term_type:?}"); + Err(Error::RaiseTerm(Box::new(message))) + } + }) + .collect::>>>() + .map(|values| { + ExSeries::new(Series::new(name.into(), values)) + }) + } + }; +} + +from_list_float!(s_from_list_f32, f32, f32); +from_list_float!(s_from_list_f64, f64, f64); + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_from_list_binary(name: &str, val: Term) -> NifResult { + val.decode::()? + .map(|term| { + term.decode::>() + .map(|maybe_bin| maybe_bin.map(|bin| bin.as_slice())) + }) + .collect::>>>() + .map(|values| ExSeries::new(Series::new(name.into(), values))) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_from_list_categories(name: &str, val: Term) -> NifResult { + let decoded = val.decode::>>()?; + Ok(ExSeries::new( + Series::new(name.into(), decoded.as_slice()) + .cast(&DataType::Categorical(None, CategoricalOrdering::default())) + .map_err(|err| { + let message = format!( + "from_list/2 cannot cast a string series to categories series: {err:?}" + ); + Error::RaiseTerm(Box::new(message)) + })?, + )) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_from_list_of_series( + name: &str, + series_term: Term, + ex_dtype: ExSeriesDtype, +) -> NifResult { + let dtype = DataType::try_from(&ex_dtype).unwrap(); + + series_term + .decode::>>() + .and_then(|series_vec| { + let lists: Vec> = series_vec + .iter() + .map(|maybe_series| { + maybe_series + .as_ref() + .map(|ex_series| ex_series.clone_inner()) + }) + .collect(); + + Series::new(name.into(), lists).cast(&dtype).map_err(|err| { + let message = format!("from_list/2 cannot create series of lists: {err:?}"); + Error::RaiseTerm(Box::new(message)) + }) + }) + .map(ExSeries::new) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_from_list_of_series_as_structs( + name: &str, + series_term: Term, + ex_dtype: ExSeriesDtype, +) -> NifResult { + let dtype = DataType::try_from(&ex_dtype).unwrap(); + let series_vec = series_term.decode::>()?; + + StructChunked::from_series( + name.into(), + series_vec + .into_iter() + .map(|s| s.clone_inner()) + .collect::>() + .as_slice(), + ) + .map(|struct_chunked| struct_chunked.into_series()) + .and_then(|series| series.cast(&dtype)) + .map_err(|err| { + let message = format!("from_list/2 cannot create series of structs: {err:?}"); + Error::RaiseTerm(Box::new(message)) + }) + .map(ExSeries::new) +} + +macro_rules! from_binary { + ($name:ident, $type:ty, $bytes:expr) => { + #[rustler::nif(schedule = "DirtyCpu")] + pub fn $name(name: &str, val: Binary) -> ExSeries { + let slice = val.as_slice(); + let transmuted = unsafe { + slice::from_raw_parts(slice.as_ptr() as *const $type, slice.len() / $bytes) + }; + ExSeries::new(Series::new(name.into(), transmuted)) + } + }; +} + +from_binary!(s_from_binary_f32, f32, 4); +from_binary!(s_from_binary_f64, f64, 8); + +from_binary!(s_from_binary_s8, i8, 1); +from_binary!(s_from_binary_s16, i16, 2); +from_binary!(s_from_binary_s32, i32, 4); +from_binary!(s_from_binary_s64, i64, 8); + +from_binary!(s_from_binary_u8, u8, 1); +from_binary!(s_from_binary_u16, u16, 2); +from_binary!(s_from_binary_u32, u32, 4); +from_binary!(s_from_binary_u64, u64, 8); diff --git a/deps/explorer/native/explorer/src/series/log.rs b/deps/explorer/native/explorer/src/series/log.rs new file mode 100644 index 0000000000000000000000000000000000000000..d2c6d1ee0b43c40c8091672c4ba836cdbfa32ef4 --- /dev/null +++ b/deps/explorer/native/explorer/src/series/log.rs @@ -0,0 +1,45 @@ +use crate::atoms; +use crate::{ExSeries, ExplorerError}; +use polars::prelude::*; +use rustler::{Term, TermType}; +use std::f64::consts::E; + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_log(s: ExSeries, base: Term) -> Result { + let nan = atoms::nan(); + let infinity = atoms::infinity(); + let neg_infinity = atoms::neg_infinity(); + + let float = match base.get_type() { + TermType::Float => base.decode::().unwrap(), + TermType::Atom => { + if nan.eq(&base) { + f64::NAN + } else if infinity.eq(&base) { + f64::INFINITY + } else if neg_infinity.eq(&base) { + f64::NEG_INFINITY + } else { + return Err(ExplorerError::Other("log/2 invalid float".into())); + } + } + term_type => { + return Err(ExplorerError::Other(format!( + "log/2 not implemented for {term_type:?}" + ))) + } + }; + + let s = s.log(float); + Ok(ExSeries::new(s)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_log_natural(s: ExSeries) -> Result { + Ok(ExSeries::new(s.log(E))) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_exp(s: ExSeries) -> Result { + Ok(ExSeries::new(s.exp())) +} diff --git a/deps/jsx/.hex b/deps/jsx/.hex new file mode 100644 index 0000000000000000000000000000000000000000..1f9ac2bf4d3205a6902ef632a06f56189e9894c9 Binary files /dev/null and b/deps/jsx/.hex differ diff --git a/deps/jsx/LICENSE b/deps/jsx/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..de1b470f38b7031546b8ca0ed5279afc91ea0578 --- /dev/null +++ b/deps/jsx/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2010-2013 alisdair sullivan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/deps/jsx/README.md b/deps/jsx/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f4e27ceb863f9352f7ab0b5c1c7e2546a9f29210 --- /dev/null +++ b/deps/jsx/README.md @@ -0,0 +1,696 @@ +# jsx (v3.0.0) # + + +an erlang application for consuming, producing and manipulating [json][json]. +inspired by [yajl][yajl] + +**jsx** is built via [rebar3][rebar3] + +current status: ![](https://github.com/talentdeficit/jsx/workflows/EUnit/badge.svg) + +**jsx** is released under the terms of the [MIT][MIT] license + +copyright 2010-2016 alisdair sullivan + +## index ## + +* [quickstart](#quickstart) +* [description](#description) + - [migrating from 1.x](#migrating) + - [json <-> erlang mapping](#json---erlang-mapping) + - [incomplete input](#incomplete-input) +* [data types](#data-types) + - [`json_term()`](#json_term) + - [`json_text()`](#json_text) + - [`event()`](#event) + - [`option()`](#option) +* [exports](#exports) + - [`encoder/3`, `decoder/3` & `parser/3`](#encoder3-decoder3--parser3) + - [`decode/1,2`](#decode12) + - [`encode/1,2`](#encode12) + - [`format/1,2`](#format12) + - [`minify/1`](#minify1) + - [`prettify/1`](#prettify1) + - [`is_json/1,2`](#is_json12) + - [`is_term/1,2`](#is_term12) +* [callback exports](#callback_exports) + - [`Module:init/1`](#moduleinit1) + - [`Module:handle_event/2`](#modulehandle_event2) +* [acknowledgements](#acknowledgements) + + +## quickstart ## + +#### to add to a rebar3 project #### +Add to `rebar.config` +```erlang +... +{erl_opts, [debug_info]}. +{deps, [ + ... + {jsx, "~> 3.0"} +]}. +... +``` + +#### to build the library and run tests #### + +```bash +$ rebar3 compile +$ rebar3 eunit +``` + +#### to convert a utf8 binary containing a json string into an erlang term #### + +```erlang +1> jsx:decode(<<"{\"library\": \"jsx\", \"awesome\": true}">>, []). +#{<<"awesome">> => true,<<"library">> => <<"jsx">>} +2> jsx:decode(<<"{\"library\": \"jsx\", \"awesome\": true}">>, [{return_maps, false}]). +[{<<"library">>,<<"jsx">>},{<<"awesome">>,true}] +3> jsx:decode(<<"[\"a\",\"list\",\"of\",\"words\"]">>). +[<<"a">>, <<"list">>, <<"of">>, <<"words">>] +``` + +#### to convert an erlang term into a utf8 binary containing a json string #### + +```erlang +1> jsx:encode(#{<<"library">> => <<"jsx">>, <<"awesome">> => true}). +<<"{\"awesome\":true,\"library\":\"jsx\"}">> +2> jsx:encode([{<<"library">>,<<"jsx">>},{<<"awesome">>,true}]). +<<"{\"library\": \"jsx\", \"awesome\": true}">> +3> jsx:encode([<<"a">>, <<"list">>, <<"of">>, <<"words">>]). +<<"[\"a\",\"list\",\"of\",\"words\"]">> +``` + +#### to check if a binary or a term is valid json #### + +```erlang +1> jsx:is_json(<<"[\"this is json\"]">>). +true +2> jsx:is_json("[\"this is not\"]"). +false +3> jsx:is_term([<<"this is a term">>]). +true +4> jsx:is_term([this, is, not]). +false +``` + +#### to minify some json #### + +```erlang +1> jsx:minify(<<"{ + \"a list\": [ + 1, + 2, + 3 + ] +}">>). +<<"{\"a list\":[1,2,3]}">> +``` + +#### to prettify some json #### + +```erlang +1> jsx:prettify(<<"{\"a list\":[1,2,3]}">>). +<<"{ + \"a list\": [ + 1, + 2, + 3 + ] +}">> +``` + +## description ## + + +**jsx** is an erlang application for consuming, producing and manipulating +[json][json] + +**jsx** follows the json [spec][rfc4627] as closely as possible with allowances for +real world usage + +**jsx** is pragmatic. the json spec allows extensions so **jsx** extends the spec in a +number of ways. see the section on `strict` in [options](#option) below though + +json has no official comments but this parser allows c/c++ style comments. +anywhere whitespace is allowed you can insert comments (both `// ...` and `/* ... */`) + +some particularly irresponsible json emitters leave trailing commas at the end of +objects or arrays. **jsx** allows a single trailing comma in input. multiple commas +in any posistion or a preceding comma are still errors + +all **jsx** decoder input should be `utf8` encoded binaries. sometimes you get binaries +that are almost but not quite valid utf8 whether due to improper escaping or poor +encoding. **jsx** replaces invalid codepoints and poorly formed sequences with the +unicode replacement character (`u+FFFD`) but does it's best to return something +comprehensible + +json only allows keys and strings to be delimited by double quotes (`u+0022`) but +javascript allows them to be delimited by single quotes (`u+0027`) as well. **jsx** +follows javascript in this. strings that start with single quotes can contain double +quotes but must end with single quotes and must escape any single quotes they contain + +json and **jsx** only recognize escape sequences as outlined in the json spec. it just +ignores bad escape sequences leaving them in strings unaltered + +### json <-> erlang mapping ### + +**json** | **erlang** +--------------------------------|-------------------------------- +`number` | `integer()` and `float()` +`string` | `binary()` and `atom()` +`true`, `false` and `null` | `true`, `false` and `null` +`array` | `[]` and `[JSON]` +`object` | `#{}`, `[{}]` and `[{binary() OR atom() OR integer(), JSON}]` +see below | `datetime()` + +* numbers + + javascript and thus json represent all numeric values with floats. there's no + reason for erlang -- a language that supports arbitrarily large integers -- to + restrict all numbers to the ieee754 range + + whenever possible, **jsx** will interpret json numbers that look like integers as + integers. other numbers will be converted to erlang's floating point type, which + is nearly but not quite iee754. negative zero is not representable in erlang (zero + is unsigned in erlang and `0` is equivalent to `-0`) and will be interpreted as + regular zero. numbers not representable are beyond the concern of this implementation, + and will result in parsing errors + + when converting from erlang to json, floats are represented with their + shortest representation that will round trip without loss of precision. this + means that some floats may be superficially dissimilar (although + functionally equivalent). for example, `1.0000000000000001` will be + represented by `1.0` + +* strings + + json strings must be unicode encoded binaries or erlang atoms. in practice, + because **jsx** only accepts `utf8` binaries all binary strings must be `utf8`. + in addition to being unicode json strings restrict a number of codepoints and + define a number of escape sequences + + json string escapes of the form `\uXXXX` will be converted to their + equivalent codepoints during parsing. this means control characters and + other codepoints disallowed by the json spec may be encountered in resulting + strings. the utf8 restriction means the surrogates are explicitly disallowed. + if a string contains escaped surrogates (`u+d800` to `u+dfff`) they are + interpreted but only when they form valid surrogate pairs. surrogates + encountered otherwise are replaced with the replacement codepoint (`u+fffd`) + + all erlang strings are represented by **valid** `utf8` encoded binaries. the + encoder will check strings for conformance. badly formed `utf8` sequences may + be replaced with the replacement codepoint (`u+fffd`) according to the unicode + spec + + this implementation performs no normalization on strings beyond that + detailed here. be careful when comparing strings as equivalent strings + may have different `utf8` encodings + +* true, false and null + + the json primitives `true`, `false` and `null` are represented by the + erlang atoms `true`, `false` and `null`. surprise + +* arrays + + json arrays are represented with erlang lists of json values as described + in this section + +* objects + + json objects are represented by erlang maps. + +* datetime + + erlang datetime tuples (`{{Year, Month, Day}, {Hour, Min, Sec}}`) as returned + from `erlang:localtime/0` are automatically encoded as [iso8601][iso8601] + strings and are assumed to be UTC time. no conversion is attempted of json [iso8601][iso8601] strings in decoded json + + +### incomplete input ### + +**jsx** can handle incomplete json texts. if the option `stream` is passed to the decoder +or parser and if a partial json text is parsed, rather than returning a term from +your callback handler, **jsx** returns `{incomplete, F}` where `F` is a function with +an identical API to the anonymous fun returned from `decoder/3`, `encoder/3` or +`parser/3`. it retains the internal state of the parser at the point where input +was exhausted. this allows you to parse as you stream json over a socket or file +descriptor, or to parse large json texts without needing to keep them entirely in +memory + +however, it is important to recognize that **jsx** is conservative by default. **jsx** will +not consider the parsing complete even when input is exhausted and the json text is +unambiguously incomplete. to end parsing call the `incomplete` function with the +argument `end_stream` (or `end_json`) like: + +```erlang +1> {incomplete, F} = jsx:decode(<<"[">>, [stream]). +{incomplete,#Fun} +2> F(end_stream). % can also be `F(end_json)` +** exception error: bad argument +3> {incomplete, G} = F(<<"]">>). +{incomplete,#Fun} +4> G(end_stream). % can also be `G(end_json)` +[] +``` + + +## data types ## + +#### `json_term()` #### + +```erlang +json_term() = [json_term()] + | [{binary() | atom() | integer(), json_term()}] + | #{} % map of any size, not just the empty map + | true + | false + | null + | integer() + | float() + | binary() + | atom() + | datetime() +``` + +the erlang representation of json. binaries should be `utf8` encoded, or close +at least + +#### `json_text()` #### + +```erlang +json_text() = binary() +``` + +a utf8 encoded binary containing a json string + +#### `event()` #### + +```erlang +event() = start_object + | end_object + | start_array + | end_array + | {key, binary()} + | {string, binary()} + | {integer, integer()} + | {float, float()} + | {literal, true} + | {literal, false} + | {literal, null} + | end_json +``` + +the subset of [`token()`](#token) emitted by the decoder and encoder to handlers + +#### `option()` #### + +```erlang +option() = dirty_strings + | escaped_forward_slashes + | escaped_strings + | repeat_keys + | stream + | strict + | {strict, [strict_option()]} + | return_tail + | uescape + | unescaped_jsonp + +strict_option() = comments + | trailing_commas + | utf8 + | single_quotes + | escapes +``` + +**jsx** functions all take a common set of options. not all flags have meaning +in all contexts, but they are always valid options. functions may have +additional options beyond these. see +[individual function documentation](#exports) for details + +- `dirty_strings` + + json escaping is lossy; it mutates the json string and repeated application + can result in unwanted behaviour. if your strings are already escaped (or + you'd like to force invalid strings into "json" you monster) use this flag + to bypass escaping. this can also be used to read in **really** invalid json + strings. everything between unescaped quotes are passed as is to the resulting + string term. note that this takes precedence over any other options + +- `escaped_forward_slashes` + + json strings are escaped according to the json spec. this means forward + slashes (solidus) are only escaped when this flag is present. otherwise they + are left unescaped. you may want to use this if you are embedding json + directly into a html or xml document + +- `escaped_strings` + + by default both the encoder and decoder return strings as utf8 binaries + appropriate for use in erlang. escape sequences that were present in decoded + terms are converted into the appropriate codepoint while encoded terms are + unaltered. this flag escapes strings as if for output in json, removing + control codes and problematic codepoints and replacing them with the + appropriate escapes + +- `stream` + + see [incomplete input](#incomplete-input) + +- `strict` + + as mentioned [earlier](#description), **jsx** is pragmatic. if you're more of a + json purist or you're really into bdsm stricter adherence to the spec is + possible. the following restrictions are available + + * `comments` + + comments are disabled and result in a `badarg` error + + * `trailing_commas` + + trailing commas in an object or list result in `badarg` errors + + * `utf8` + + invalid codepoints and malformed unicode result in `badarg` errors + + * `single_quotes` + + only keys and strings delimited by double quotes (`u+0022`) are allowed. the + single quote (`u+0027`) results in a `badarg` error + + * `escapes` + + escape sequences not adhering to the json spec result in a `badarg` error + + * `control_codes` + + control codes in strings result in `badarg` errors + + any combination of these can be passed to **jsx** by using `{strict, [strict_option()]}`. + `strict` is equivalent to `{strict, [comments, trailing_commas, utf8, single_quotes, escapes, control_codes]}` + +- `return_tail` + + upon reaching the end of a valid json term in an input stream return the term and any + remaining bytes in the input stream as `{with_tail, term(), binary()}` where the second + member of the tuple is the json term and the third is any remaining bytes. note that + leading whitespace will be stripped from the tail + +- `uescape` + + escape all codepoints outside the ascii range for 7 bit clean output. note + this escaping takes place even if no other string escaping is requested (via + `escaped_strings`) + +- `unescaped_jsonp` + + javascript interpreters treat the codepoints `u+2028` and `u+2029` as + significant whitespace. json strings that contain either of these codepoints + will be parsed incorrectly by some javascript interpreters. by default, + these codepoints are escaped (to `\u2028` and `\u2029`, respectively) to + retain compatibility. this option simply removes that escaping + + +## exports ## + + +#### `encoder/3`, `decoder/3` & `parser/3` #### + +```erlang +decoder(Module, Args, Opts) -> Fun((JSONText) -> any()) +encoder(Module, Args, Opts) -> Fun((JSONTerm) -> any()) +parser(Module, Args, Opts) -> Fun((Tokens) -> any()) + + Module = atom() + Args = any() + Opts = [option()] + JSONText = json_text() + JSONTerm = json_term() + Tokens = event() | [event()] +``` + +**jsx** is a json compiler with interleaved tokenizing, syntactic analysis and +semantic analysis stages. included are two tokenizers; one that handles json +texts (`decoder/3`) and one that handles erlang terms (`encoder/3`). there is +also an entry point to the syntactic analysis stage for use with user-defined +tokenizers (`parser/3`) + +all three functions return an anonymous function that takes the appropriate type +of input and returns the result of performing semantic analysis, the tuple +`{incomplete, F}` where `F` is a new anonymous function (see +[incomplete input](#incomplete_input)) or a `badarg` error exception if +syntactic analysis fails + +`Module` is the name of the callback module + +`Args` is any term that will be passed to `Module:init/1` prior to syntactic +analysis to produce an initial state + +`Opts` are detailed [here](#option) + +check out [callback module documentation](#callback_exports) for details of +the callback module interface + +#### `decode/1,2` #### + +```erlang +decode(JSON) -> Term +decode(JSON, Opts) -> Term + + JSON = json_text() + Term = json_term() + Opts = [option() | labels | {labels, Label} | return_maps] + Label = binary | atom | existing_atom | attempt_atom + F = fun((any()) -> any()) +``` + +`decode` parses a json text (a `utf8` encoded binary) and produces an erlang +term + +the option `labels` controls how keys are converted from json to +erlang terms. `binary` (the default behavior) does no conversion +beyond normal escaping. `atom` converts keys to erlang atoms and +results in a `badarg` error if the keys fall outside the range of erlang +atoms. `existing_atom` is identical to `atom` except it will not add +new atoms to the atom table and will result in a `badarg` error if the atom +does not exist. `attempt_atom` will convert keys to atoms when they exist, +and leave them as binary otherwise + +the option `{return_maps, false}` will return objects as proplists instead +of maps. + +raises a `badarg` error exception if input is not valid json + + +#### `encode/1,2` #### + +```erlang +encode(Term) -> JSON +encode(Term, Opts) -> JSON + + Term = json_term() + JSON = json_text() + Opts = [option() | space | {space, N} | indent | {indent, N}] + N = pos_integer() +``` + +`encode` converts an erlang term into json text (a `utf8` encoded binary) + +the option `{space, N}` inserts `N` spaces after every comma and colon in your +json output. `space` is an alias for `{space, 1}`. the default is `{space, 0}` + +the option `{indent, N}` inserts a newline and `N` spaces for each level of +indentation in your json output. note that this overrides spaces inserted after +a comma. `indent` is an alias for `{indent, 1}`. the default is `{indent, 0}` + +raises a `badarg` error exception if input is not a valid +[erlang representation of json](#json---erlang-mapping) + + +#### `format/1,2` #### + +```erlang +format(JSON) -> JSON +format(JSON, Opts) -> JSON + + JSON = json_text() + Opts = [option() | space | {space, N} | indent | {indent, N} | {newline, LF}] + N = pos_integer() + LF = binary() +``` + +`format` parses a json text (a `utf8` encoded binary) and produces a new json +text according to the format rules specified by `Opts` + +the option `{space, N}` inserts `N` spaces after every comma and colon in your +json output. `space` is an alias for `{space, 1}`. the default is `{space, 0}` + +the option `{indent, N}` inserts a newline and `N` spaces for each level of +indentation in your json output. note that this overrides spaces inserted after +a comma. `indent` is an alias for `{indent, 1}`. the default is `{indent, 0}` + +the option `{newline, LF}` defines a custom newline symbol(s). +the default is `{newline, <<$\n>>}` + +raises a `badarg` error exception if input is not valid json + + +#### `minify/1` #### + +```erlang +minify(JSON) -> JSON + + JSON = json_text() +``` + +`minify` parses a json text (a `utf8` encoded binary) and produces a new json +text stripped of whitespace + +raises a `badarg` error exception if input is not valid json + + +#### `prettify/1` #### + +```erlang +prettify(JSON) -> JSON + + JSON = json_text() +``` + +`prettify` parses a json text (a `utf8` encoded binary) and produces a new json +text equivalent to `format(JSON, [{space, 1}, {indent, 2}])` + +raises a `badarg` error exception if input is not valid json + + +#### `is_json/1,2` #### + +```erlang +is_json(MaybeJSON) -> true | false +is_json(MaybeJSON, Opts) -> true | false + + MaybeJSON = any() + Opts = options() +``` + +returns true if input is a valid json text, false if not + +what exactly constitutes valid json may be [altered](#option) + + +#### `is_term/1,2` #### + +```erlang +is_term(MaybeJSON) -> true | false +is_term(MaybeJSON, Opts) -> true | false + + MaybeJSON = any() + Opts = options() +``` + +returns true if input is a valid erlang representation of json, false if not + +what exactly constitutes valid json may be altered via [options](#option) + +## callback exports ## + +the following functions should be exported from a **jsx** callback module + +#### `Module:init/1` #### + +```erlang +Module:init(Args) -> InitialState + + Args = any() + InitialState = any() +``` + +whenever any of `encoder/3`, `decoder/3` or `parser/3` are called, this function +is called with the `Args` argument provided in the calling function to obtain +`InitialState` + +#### `Module:handle_event/2` #### + +```erlang +Module:handle_event(Event, State) -> NewState + + Event = [event()] + State = any() + NewState = any() +``` + +semantic analysis is performed by repeatedly calling `handle_event/2` with a +stream of events emitted by the tokenizer and the current state. the new state +returned is used as the input to the next call to `handle_event/2`. the +following events must be handled: + +- `start_object` + + the start of a json object + +- '{key, binary()}' + + the key of an entry in a json object + +- `end_object` + + the end of a json object + +- `start_array` + + the start of a json array + +- `end_array` + + the end of a json array + +- `{string, binary()}` + + a json string. it will usually be a `utf8` encoded binary. see the + [options](#option) for possible exceptions. note that keys are also + json strings + +- `{integer, integer()}` + + an erlang integer (bignum) + +- `{float, float()}` + + an erlang float + +- `{literal, true}` + + the atom `true` + +- `{literal, false}` + + the atom `false` + +- `{literal, null}` + + the atom `null` + +- `end_json` + + this event is emitted when syntactic analysis is completed. you should + do any cleanup and return the result of your semantic analysis + + +## acknowledgements ## + +jsx wouldn't be what it is without the contributions of [Paul J. Davis](https://github.com/davisp), [Lloyd Hilaiel](https://github.com/lloyd), [John Engelhart](https://github.com/johnezang), [Bob Ippolito](https://github.com/etrepum), [Brujo Benavides](https://github.com/elbrujohalcon), [Alex Kropivny](https://github.com/amtal), [Steve Strong](https://github.com/srstrong), [Michael Truog](https://github.com/okeuday), [Devin Torres](https://github.com/devinus), [fogfish](https://github.com/fogfish), [emptytea](https://github.com/emptytea), [John Daily](https://github.com/macintux), [Ola Bäckström](https://github.com/olabackstrom), [Joseph Crowe](https://github.com/JosephCrowe), [Patrick Gombert](https://github.com/patrickgombert), [Eshengazin S. Kuat](https://github.com/eskuat), [Max Lapshin](https://github.com/maxlapshin), [Bikram Chatterjee](https://github.com/c-bik), [Michael Uvarov](https://github.com/arcusfelis), [Led](https://github.com/Ledest) and [tvv](https://github.com/tvv) + +[json]: http://json.org +[yajl]: http://lloyd.github.com/yajl +[MIT]: http://www.opensource.org/licenses/mit-license.html +[rebar3]: https://rebar3.org +[meck]: https://github.com/eproxus/meck +[rfc4627]: http://tools.ietf.org/html/rfc4627 +[travis]: https://travis-ci.org/ +[jsxn]: https://github.com/talentdeficit/jsxn +[iso8601]: http://www.iso.org/iso/iso8601 diff --git a/deps/jsx/_build/prod/lib/.rebar3/rebar_compiler_erl/source.dag b/deps/jsx/_build/prod/lib/.rebar3/rebar_compiler_erl/source.dag new file mode 100644 index 0000000000000000000000000000000000000000..c877cc60a45a213d21bfc872c8460c912abcb662 Binary files /dev/null and b/deps/jsx/_build/prod/lib/.rebar3/rebar_compiler_erl/source.dag differ diff --git a/deps/jsx/hex_metadata.config b/deps/jsx/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..63f6e665b3a7433371b0d55283ff644e6ea07420 --- /dev/null +++ b/deps/jsx/hex_metadata.config @@ -0,0 +1,15 @@ +{<<"app">>,<<"jsx">>}. +{<<"build_tools">>,[<<"rebar3">>]}. +{<<"description">>,<<"a streaming, evented json parsing toolkit">>}. +{<<"files">>, + [<<"LICENSE">>,<<"README.md">>,<<"rebar.config">>,<<"rebar.lock">>, + <<"src/jsx.app.src">>,<<"src/jsx.erl">>,<<"src/jsx_config.erl">>, + <<"src/jsx_config.hrl">>,<<"src/jsx_consult.erl">>, + <<"src/jsx_decoder.erl">>,<<"src/jsx_encoder.erl">>, + <<"src/jsx_parser.erl">>,<<"src/jsx_to_json.erl">>, + <<"src/jsx_to_term.erl">>,<<"src/jsx_verify.erl">>]}. +{<<"licenses">>,[<<"MIT">>]}. +{<<"links">>,[{<<"Github">>,<<"https://github.com/talentdeficit/jsx">>}]}. +{<<"name">>,<<"jsx">>}. +{<<"requirements">>,[]}. +{<<"version">>,<<"3.1.0">>}. diff --git a/deps/jsx/rebar.config b/deps/jsx/rebar.config new file mode 100644 index 0000000000000000000000000000000000000000..1c71a9c0280ec6b63f450ae60d6e80d508e5d640 --- /dev/null +++ b/deps/jsx/rebar.config @@ -0,0 +1,17 @@ +{edoc_opts, [{preprocess, true}]}. +{erl_opts, [debug_info]}. +{dialyzer, [ + {warnings, [ + unknown, + unmatched_returns, + error_handling, + underspecs + ]} +]}. +{profiles, [ + {test, [ + {dialyzer, [ + {plt_extra_apps, [eunit]} + ]} + ]} +]}. diff --git a/deps/jsx/rebar.lock b/deps/jsx/rebar.lock new file mode 100644 index 0000000000000000000000000000000000000000..57afcca04590ff2bbf2f83b8eac4f856df782c74 --- /dev/null +++ b/deps/jsx/rebar.lock @@ -0,0 +1 @@ +[]. diff --git a/deps/jsx/src/jsx.app.src b/deps/jsx/src/jsx.app.src new file mode 100644 index 0000000000000000000000000000000000000000..0aff4941ddbf2ad9eb6f5959e4e75af84eb74ee2 --- /dev/null +++ b/deps/jsx/src/jsx.app.src @@ -0,0 +1,10 @@ +{application,jsx, + [{description,"a streaming, evented json parsing toolkit"}, + {vsn,"3.1.0"}, + {modules,[jsx,jsx_encoder,jsx_decoder,jsx_parser,jsx_to_json, + jsx_to_term,jsx_config,jsx_verify]}, + {registered,[]}, + {applications,[kernel,stdlib]}, + {env,[]}, + {licenses,["MIT"]}, + {links,[{"Github","https://github.com/talentdeficit/jsx"}]}]}. diff --git a/deps/jsx/src/jsx.erl b/deps/jsx/src/jsx.erl new file mode 100644 index 0000000000000000000000000000000000000000..d02d33bdda613e331ca0dc382366fa2f6f2b4685 --- /dev/null +++ b/deps/jsx/src/jsx.erl @@ -0,0 +1,506 @@ +%% The MIT License + +%% Copyright (c) 2010-2013 alisdair sullivan + +%% Permission is hereby granted, free of charge, to any person obtaining a copy +%% of this software and associated documentation files (the "Software"), to deal +%% in the Software without restriction, including without limitation the rights +%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +%% copies of the Software, and to permit persons to whom the Software is +%% furnished to do so, subject to the following conditions: + +%% The above copyright notice and this permission notice shall be included in +%% all copies or substantial portions of the Software. + +%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +%% THE SOFTWARE. + + +-module(jsx). + +-export([encode/1, encode/2, decode/1, decode/2]). +-export([is_json/1, is_json/2, is_term/1, is_term/2]). +-export([format/1, format/2, minify/1, prettify/1]). +-export([consult/1, consult/2]). +-export([encoder/3, decoder/3, parser/3]). +-export([resume/3]). + +-export_type([json_term/0, json_text/0, token/0]). +-export_type([encoder/0, decoder/0, parser/0, internal_state/0]). +-export_type([config/0]). + + +-ifdef(TEST). +%% data and helper functions for tests +-export([test_cases/0, special_test_cases/0]). +-export([init/1, handle_event/2]). +-endif. + +-type json_term() :: [{binary() | atom(), json_term()}] | [{},...] + | [json_term()] | [] + | {with_tail, json_term(), binary()} + | #{ binary() | atom() => json_term() } + | true | false | null + | integer() | float() + | binary() | atom() + | calendar:datetime(). + +-type json_text() :: binary(). + +-type config() :: jsx_config:config(). + +-spec encode(Source::json_term()) -> json_text() | {incomplete, encoder()}. + +encode(Source) -> encode(Source, []). + +-spec encode(Source::json_term(), Config::jsx_config:options()) -> json_text() | {incomplete, encoder()}. + +encode(Source, Config) -> jsx_to_json:to_json(Source, Config). + + +-spec decode(Source::json_text()) -> json_term() | {incomplete, decoder()}. + +decode(Source) -> decode(Source, []). + +-spec decode(Source::json_text(), Config::jsx_config:options()) -> json_term() | {incomplete, decoder()}. + +decode(Source, Config) -> jsx_to_term:to_term(Source, Config). + + +-spec format(Source::json_text()) -> json_text(). + +format(Source) -> format(Source, []). + +-spec format(Source::json_text(), Config::jsx_config:options()) -> json_text(). + +format(Source, Config) -> jsx_to_json:format(Source, Config). + + +-spec minify(Source::json_text()) -> json_text(). + +minify(Source) -> format(Source, []). + + +-spec prettify(Source::json_text()) -> json_text(). + +prettify(Source) -> format(Source, [space, {indent, 2}]). + + +-spec is_json(Source::binary()) -> boolean() | {incomplete, decoder()}. + +is_json(Source) -> is_json(Source, []). + +-spec is_json(Source::binary(), Config::jsx_config:options()) -> boolean() | {incomplete, decoder()}. + +is_json(Source, Config) -> jsx_verify:is_json(Source, Config). + + +-spec is_term(Source::json_term() | end_stream | end_json) -> boolean() | {incomplete, encoder()}. + +is_term(Source) -> is_term(Source, []). + +-spec is_term(Source::json_term() | end_stream | end_json, + Config::jsx_config:options()) -> boolean() | {incomplete, encoder()}. + +is_term(Source, Config) -> jsx_verify:is_term(Source, Config). + + +-spec consult(File::file:name_all()) -> list(jsx_consult:json_value()). + +consult(File) -> consult(File, []). + +-spec consult(File::file:name_all(), Config::jsx_consult:config()) -> list(jsx_consult:json_value()). + +consult(File, Config) -> jsx_consult:consult(File, Config). + + +-type decoder() :: fun((json_text() | end_stream | end_json) -> any()). + +-spec decoder(Handler::module(), State::any(), Config::jsx_config:options()) -> decoder(). + +decoder(Handler, State, Config) -> jsx_decoder:decoder(Handler, State, Config). + + +-type encoder() :: fun((json_term() | end_stream | end_json) -> any()). + +-spec encoder(Handler::module(), State::any(), Config::jsx_config:options()) -> encoder(). + +encoder(Handler, State, Config) -> jsx_encoder:encoder(Handler, State, Config). + + +-type token() :: [token()] + | start_object + | end_object + | start_array + | end_array + | {key, binary()} + | {string, binary()} + | binary() + | {number, integer() | float()} + | {integer, integer()} + | {float, float()} + | integer() + | float() + | {literal, true} + | {literal, false} + | {literal, null} + | true + | false + | null + | end_json. + + +-type parser() :: fun((token() | end_stream) -> any()). + +-spec parser(Handler::module(), State::any(), Config::jsx_config:options()) -> parser(). + +parser(Handler, State, Config) -> jsx_parser:parser(Handler, State, Config). + +-opaque internal_state() :: tuple(). + +-spec resume(Term::json_text() | token(), InternalState::internal_state(), + Config::jsx_config:options()) -> jsx:decoder() | {incomplete, jsx:decoder()}. + +resume(Term, {decoder, State, Handler, Acc, Stack}, Config) -> + jsx_decoder:resume(Term, State, Handler, Acc, Stack, jsx_config:parse_config(Config)); +resume(Term, {parser, State, Handler, Stack}, Config) -> + jsx_parser:resume(Term, State, Handler, Stack, jsx_config:parse_config(Config)). + +-ifdef(TEST). + +-include_lib("eunit/include/eunit.hrl"). + + +%% test handler +init([]) -> []. + +handle_event(end_json, State) -> lists:reverse([end_json] ++ State); +handle_event(Event, State) -> [Event] ++ State. + + +test_cases() -> + empty_array() + ++ nested_array() + ++ empty_object() + ++ nested_object() + ++ strings() + ++ literals() + ++ integers() + ++ floats() + ++ compound_object(). + +%% segregate these so we can skip them in `jsx_to_term` +special_test_cases() -> special_objects() ++ special_array(). + + +empty_array() -> [{"[]", <<"[]">>, [], [start_array, end_array]}]. + + +nested_array() -> + [{ + "[[[]]]", + <<"[[[]]]">>, + [[[]]], + [start_array, start_array, start_array, end_array, end_array, end_array] + }]. + + +empty_object() -> [{"{}", <<"{}">>, [{}], [start_object, end_object]}]. + + +nested_object() -> + [{ + "{\"key\":{\"key\":{}}}", + <<"{\"key\":{\"key\":{}}}">>, + [{<<"key">>, [{<<"key">>, [{}]}]}], + [ + start_object, + {key, <<"key">>}, + start_object, + {key, <<"key">>}, + start_object, + end_object, + end_object, + end_object + ] + }]. + + +naked_strings() -> + Raw = [ + "", + "hello world" + ], + [ + { + String, + <<"\"", (list_to_binary(String))/binary, "\"">>, + list_to_binary(String), + [{string, list_to_binary(String)}] + } + || String <- Raw + ]. + + +strings() -> + naked_strings() + ++ [ wrap_with_array(Test) || Test <- naked_strings() ] + ++ [ wrap_with_object(Test) || Test <- naked_strings() ]. + + +naked_integers() -> + Raw = [ + 1, 2, 3, + 127, 128, 129, + 255, 256, 257, + 65534, 65535, 65536, + 18446744073709551616, + 18446744073709551617 + ], + [ + { + integer_to_list(X), + list_to_binary(integer_to_list(X)), + X, + [{integer, X}] + } + || X <- Raw ++ [ -1 * Y || Y <- Raw ] ++ [0] + ]. + + +integers() -> + naked_integers() + ++ [ wrap_with_array(Test) || Test <- naked_integers() ] + ++ [ wrap_with_object(Test) || Test <- naked_integers() ]. + + +naked_floats() -> + Raw = [ + 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, + 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, + 1234567890.0987654321, + 0.0e0, + 1234567890.0987654321e16, + 0.1e0, 0.1e1, 0.1e2, 0.1e4, 0.1e8, 0.1e16, 0.1e308, + 1.0e0, 1.0e1, 1.0e2, 1.0e4, 1.0e8, 1.0e16, 1.0e308, + 2.2250738585072014e-308, %% min normalized float + 1.7976931348623157e308, %% max normalized float + 5.0e-324, %% min denormalized float + 2.225073858507201e-308 %% max denormalized float + ], + [ + { + sane_float_to_list(X), + list_to_binary(sane_float_to_list(X)), + X, + [{float, X}] + } + || X <- Raw ++ [ -1 * Y || Y <- Raw ] + ]. + + +floats() -> + naked_floats() + ++ [ wrap_with_array(Test) || Test <- naked_floats() ] + ++ [ wrap_with_object(Test) || Test <- naked_floats() ]. + + +naked_literals() -> + [ + { + atom_to_list(Literal), + atom_to_binary(Literal, unicode), + Literal, + [{literal, Literal}] + } + || Literal <- [true, false, null] + ]. + + +literals() -> + naked_literals() + ++ [ wrap_with_array(Test) || Test <- naked_literals() ] + ++ [ wrap_with_object(Test) || Test <- naked_literals() ]. + + +compound_object() -> + [{ + "[{\"alpha\":[1,2,3],\"beta\":{\"alpha\":[1.0,2.0,3.0],\"beta\":[true,false]}},[{}]]", + <<"[{\"alpha\":[1,2,3],\"beta\":{\"alpha\":[1.0,2.0,3.0],\"beta\":[true,false]}},[{}]]">>, + [[{<<"alpha">>, [1, 2, 3]}, {<<"beta">>, [{<<"alpha">>, [1.0, 2.0, 3.0]}, {<<"beta">>, [true, false]}]}], [[{}]]], + [ + start_array, + start_object, + {key, <<"alpha">>}, + start_array, + {integer, 1}, + {integer, 2}, + {integer, 3}, + end_array, + {key, <<"beta">>}, + start_object, + {key, <<"alpha">>}, + start_array, + {float, 1.0}, + {float, 2.0}, + {float, 3.0}, + end_array, + {key, <<"beta">>}, + start_array, + {literal, true}, + {literal, false}, + end_array, + end_object, + end_object, + start_array, + start_object, + end_object, + end_array, + end_array + ] + }]. + + +special_objects() -> + [ + { + "[{key, atom}]", + <<"{\"key\":\"atom\"}">>, + [{key, atom}], + [start_object, {key, <<"key">>}, {string, <<"atom">>}, end_object] + }, + { + "[{1, true}]", + <<"{\"1\":true}">>, + [{1, true}], + [start_object, {key, <<"1">>}, {literal, true}, end_object] + } + ]. + + +special_array() -> + [ + { + "[foo, bar]", + <<"[\"foo\",\"bar\"]">>, + [foo, bar], + [start_array, {string, <<"foo">>}, {string, <<"bar">>}, end_array] + } + ]. + + +wrap_with_array({Title, JSON, Term, Events}) -> + { + "[" ++ Title ++ "]", + <<"[", JSON/binary, "]">>, + [Term], + [start_array] ++ Events ++ [end_array] + }. + + +wrap_with_object({Title, JSON, Term, Events}) -> + { + "{\"key\":" ++ Title ++ "}", + <<"{\"key\":", JSON/binary, "}">>, + [{<<"key">>, Term}], + [start_object, {key, <<"key">>}] ++ Events ++ [end_object] + }. + + +sane_float_to_list(X) -> + [Output] = io_lib:format("~p", [X]), + Output. + + +incremental_decode(JSON) -> + Final = lists:foldl( + fun(Byte, Decoder) -> {incomplete, F} = Decoder(Byte), F end, + decoder(jsx, [], [stream]), + json_to_bytes(JSON) + ), + Final(end_stream). + + +incremental_parse(Events) -> + Final = lists:foldl( + fun(Event, Parser) -> {incomplete, F} = Parser(Event), F end, + parser(?MODULE, [], [stream]), + lists:map(fun(X) -> [X] end, Events) + ), + Final(end_stream). + + +%% used to convert a json text into a list of codepoints to be incrementally +%% parsed +json_to_bytes(JSON) -> json_to_bytes(JSON, []). + +json_to_bytes(<<>>, Acc) -> [<<>>] ++ lists:reverse(Acc); +json_to_bytes(<>, Acc) -> json_to_bytes(Rest, [<>] ++ Acc). + + +%% actual tests! +decode_test_() -> + Data = test_cases(), + [{Title, ?_assertEqual(Events ++ [end_json], (decoder(?MODULE, [], []))(JSON))} + || {Title, JSON, _, Events} <- Data + ] ++ + [{Title ++ " (incremental)", ?_assertEqual(Events ++ [end_json], incremental_decode(JSON))} + || {Title, JSON, _, Events} <- Data + ]. + + +parse_test_() -> + Data = test_cases(), + [{Title, ?_assertEqual(Events ++ [end_json], (parser(?MODULE, [], []))(Events ++ [end_json]))} + || {Title, _, _, Events} <- Data + ] ++ + [{Title ++ " (incremental)", ?_assertEqual(Events ++ [end_json], incremental_parse(Events))} + || {Title, _, _, Events} <- Data + ]. + + +encode_test_() -> + Data = test_cases(), + [ + { + Title, ?_assertEqual( + Events ++ [end_json], + (jsx:encoder(jsx, [], []))(Term) + ) + } || {Title, _, Term, Events} <- Data + ]. + +end_stream_test_() -> + Tokens = [start_object, end_object, end_json], + [ + {"encoder end_stream", ?_assertEqual( + Tokens, + begin + {incomplete, F} = (jsx:parser(jsx, [], [stream]))([start_object, end_object]), + F(end_stream) + end + )}, + {"encoder end_json", ?_assertEqual( + Tokens, + begin + {incomplete, F} = (jsx:parser(jsx, [], [stream]))([start_object, end_object]), + F(end_json) + end + )}, + {"decoder end_stream", ?_assertEqual( + Tokens, + begin {incomplete, F} = (jsx:decoder(jsx, [], [stream]))(<<"{}">>), F(end_stream) end + )}, + {"decoder end_json", ?_assertEqual( + Tokens, + begin {incomplete, F} = (jsx:decoder(jsx, [], [stream]))(<<"{}">>), F(end_json) end + )} + ]. + + +-endif. diff --git a/deps/jsx/src/jsx_config.erl b/deps/jsx/src/jsx_config.erl new file mode 100644 index 0000000000000000000000000000000000000000..ba1d872a3bb074e8fc12eab0e59335abae023f08 --- /dev/null +++ b/deps/jsx/src/jsx_config.erl @@ -0,0 +1,393 @@ +%% The MIT License + +%% Copyright (c) 2010-2013 alisdair sullivan + +%% Permission is hereby granted, free of charge, to any person obtaining a copy +%% of this software and associated documentation files (the "Software"), to deal +%% in the Software without restriction, including without limitation the rights +%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +%% copies of the Software, and to permit persons to whom the Software is +%% furnished to do so, subject to the following conditions: + +%% The above copyright notice and this permission notice shall be included in +%% all copies or substantial portions of the Software. + +%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +%% THE SOFTWARE. + + +-module(jsx_config). + +-export([parse_config/1]). +-export([config_to_list/1]). +-export([extract_config/1, valid_flags/0]). + +-ifdef(TEST). +-export([fake_error_handler/3]). +-endif. + +-include("jsx_config.hrl"). + +-type handler_type(Handler) :: + fun((jsx:json_text() | end_stream | + jsx:json_term(), + {decoder, any(), module(), null | list(), list()} | + {parser, any(), module(), list()} | + {encoder, any(), module()}, + list({pre_encode, fun((any()) -> any())} | + {error_handler, Handler} | + {incomplete_handler, Handler} | + atom())) -> any()). +-type handler() :: handler_type(handler()). +-export_type([handler/0]). + +-type config() :: #config{}. +-export_type([config/0]). + +-type option() :: valid_flag() + | {valid_flag(), boolean()} + | {strict, [strict_option()]} + | {error_handler, fun((any(), any(), any()) -> ok)} + | {incomplete_handler, fun((any(), any(), any()) -> ok)} + | {return_maps, boolean()} + | {labels, label_option()} + | {space, non_neg_integer()} + | {indent, non_neg_integer()} + | {depth, non_neg_integer()} + | {newline, binary()} + | legacy_option() + | {legacy_option(), boolean()}. +-type legacy_option() :: strict_comments + | strict_commas + | strict_utf8 + | strict_single_quotes + | strict_escapes + | strict_control_codes. + +-type options() :: [option()]. +-export_type([options/0]). + +-type strict_option() :: comments + | trailing_commas + | utf8 + | single_quotes + | escapes + | control_codes. +-type label_option() :: binary + | atom + | existing_atom + | attempt_atom. + +-type valid_flag() :: escaped_forward_slashes + | escaped_strings + | unescaped_jsonp + | dirty_strings + | multi_term + | return_tail + | repeat_keys + | strict + | stream + | uescape + | error_handler + | incomplete_handler. + +%% parsing of jsx config +-spec parse_config(Config::options()) -> config(). + +parse_config(Config) -> parse_config(Config, #config{}). + +parse_config([], Config) -> Config; +parse_config([escaped_forward_slashes|Rest], Config) -> + parse_config(Rest, Config#config{escaped_forward_slashes=true}); +parse_config([escaped_strings|Rest], Config) -> + parse_config(Rest, Config#config{escaped_strings=true}); +parse_config([unescaped_jsonp|Rest], Config) -> + parse_config(Rest, Config#config{unescaped_jsonp=true}); +parse_config([dirty_strings|Rest], Config) -> + parse_config(Rest, Config#config{dirty_strings=true}); +parse_config([multi_term|Rest], Config) -> + parse_config(Rest, Config#config{multi_term=true}); +parse_config([return_tail|Rest], Config) -> + parse_config(Rest, Config#config{return_tail=true}); +%% retained for backwards compat, now does nothing however +parse_config([repeat_keys|Rest], Config) -> + parse_config(Rest, Config); +parse_config([uescape|Rest], Config) -> + parse_config(Rest, Config#config{uescape=true}); +parse_config([strict|Rest], Config) -> + parse_config(Rest, Config#config{ + strict_comments=true, + strict_commas=true, + strict_utf8=true, + strict_single_quotes=true, + strict_escapes=true, + strict_control_codes=true + }); +parse_config([{strict, Strict}|Rest], Config) -> + parse_strict(Strict, Rest, Config); +parse_config([stream|Rest], Config) -> + parse_config(Rest, Config#config{stream=true}); +parse_config([{error_handler, ErrorHandler}|Rest] = Options, Config) when is_function(ErrorHandler, 3) -> + case Config#config.error_handler of + false -> parse_config(Rest, Config#config{error_handler=ErrorHandler}) + ; _ -> erlang:error(badarg, [Options, Config]) + end; +parse_config([{incomplete_handler, IncompleteHandler}|Rest] = Options, Config) when is_function(IncompleteHandler, 3) -> + case Config#config.incomplete_handler of + false -> parse_config(Rest, Config#config{incomplete_handler=IncompleteHandler}) + ; _ -> erlang:error(badarg, [Options, Config]) + end; +parse_config(_Options, _Config) -> erlang:error(badarg). + + +parse_strict([], Rest, Config) -> parse_config(Rest, Config); +parse_strict([comments|Strict], Rest, Config) -> + parse_strict(Strict, Rest, Config#config{strict_comments=true}); +parse_strict([trailing_commas|Strict], Rest, Config) -> + parse_strict(Strict, Rest, Config#config{strict_commas=true}); +parse_strict([utf8|Strict], Rest, Config) -> + parse_strict(Strict, Rest, Config#config{strict_utf8=true}); +parse_strict([single_quotes|Strict], Rest, Config) -> + parse_strict(Strict, Rest, Config#config{strict_single_quotes=true}); +parse_strict([escapes|Strict], Rest, Config) -> + parse_strict(Strict, Rest, Config#config{strict_escapes=true}); +parse_strict([control_codes|Strict], Rest, Config) -> + parse_strict(Strict, Rest, Config#config{strict_control_codes=true}); +parse_strict(_Strict, _Rest, _Config) -> + erlang:error(badarg). + + + +-spec config_to_list(Config::config()) -> options(). + +config_to_list(Config) -> + reduce_config(lists:map( + fun ({error_handler, F}) -> {error_handler, F}; + ({incomplete_handler, F}) -> {incomplete_handler, F}; + ({Key, true}) -> Key + end, + lists:filter( + fun({_, false}) -> false; (_) -> true end, + lists:zip(record_info(fields, config), tl(tuple_to_list(Config))) + ) + )). + + +reduce_config(Input) -> reduce_config(Input, [], []). + +reduce_config([], Output, Strict) -> + case length(Strict) of + 0 -> lists:reverse(Output); + 5 -> lists:reverse(Output) ++ [strict]; + _ -> lists:reverse(Output) ++ [{strict, lists:reverse(Strict)}] + end; +reduce_config([strict_comments|Input], Output, Strict) -> + reduce_config(Input, Output, [comments] ++ Strict); +reduce_config([strict_utf8|Input], Output, Strict) -> + reduce_config(Input, Output, [utf8] ++ Strict); +reduce_config([strict_single_quotes|Input], Output, Strict) -> + reduce_config(Input, Output, [single_quotes] ++ Strict); +reduce_config([strict_escapes|Input], Output, Strict) -> + reduce_config(Input, Output, [escapes] ++ Strict); +reduce_config([strict_control_codes|Input], Output, Strict) -> + reduce_config(Input, Output, [control_codes] ++ Strict); +reduce_config([Else|Input], Output, Strict) -> + reduce_config(Input, [Else] ++ Output, Strict). + + +-spec valid_flags() -> [valid_flag(), ...]. + +valid_flags() -> + [ + escaped_forward_slashes, + escaped_strings, + unescaped_jsonp, + dirty_strings, + multi_term, + return_tail, + repeat_keys, + strict, + stream, + uescape, + error_handler, + incomplete_handler + ]. + + +-spec extract_config(Config::options()) -> options(). + +extract_config(Config) -> + extract_parser_config(Config, []). + +extract_parser_config([], Acc) -> Acc; +extract_parser_config([{K,V}|Rest], Acc) -> + case lists:member(K, valid_flags()) of + true -> extract_parser_config(Rest, [{K,V}] ++ Acc) + ; false -> extract_parser_config(Rest, Acc) + end; +extract_parser_config([K|Rest], Acc) -> + case lists:member(K, valid_flags()) of + true -> extract_parser_config(Rest, [K] ++ Acc) + ; false -> extract_parser_config(Rest, Acc) + end. + + +%% eunit tests +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). + + +config_test_() -> + [ + {"all flags", + ?_assertEqual( + #config{escaped_forward_slashes = true, + escaped_strings = true, + unescaped_jsonp = true, + dirty_strings = true, + multi_term = true, + return_tail = true, + strict_comments = true, + strict_commas = true, + strict_utf8 = true, + strict_single_quotes = true, + strict_escapes = true, + strict_control_codes = true, + stream = true, + uescape = true + }, + parse_config([dirty_strings, + escaped_forward_slashes, + escaped_strings, + unescaped_jsonp, + multi_term, + return_tail, + repeat_keys, + strict, + stream, + uescape + ]) + ) + }, + {"strict flag", + ?_assertEqual( + #config{strict_comments = true, + strict_commas = true, + strict_utf8 = true, + strict_single_quotes = true, + strict_escapes = true, + strict_control_codes = true + }, + parse_config([strict]) + ) + }, + {"strict selective", + ?_assertEqual( + #config{strict_comments = true}, + parse_config([{strict, [comments]}]) + ) + }, + {"strict expanded", + ?_assertEqual( + #config{strict_comments = true, + strict_utf8 = true, + strict_single_quotes = true, + strict_escapes = true + }, + parse_config([{strict, [comments, utf8, single_quotes, escapes]}]) + ) + }, + {"error_handler flag", ?_assertEqual( + #config{error_handler=fun ?MODULE:fake_error_handler/3}, + parse_config([{error_handler, fun ?MODULE:fake_error_handler/3}]) + )}, + {"two error_handlers defined", ?_assertError( + badarg, + parse_config([ + {error_handler, fun(_, _, _) -> true end}, + {error_handler, fun(_, _, _) -> false end} + ]) + )}, + {"incomplete_handler flag", ?_assertEqual( + #config{incomplete_handler=fun ?MODULE:fake_error_handler/3}, + parse_config([{incomplete_handler, fun ?MODULE:fake_error_handler/3}]) + )}, + {"two incomplete_handlers defined", ?_assertError( + badarg, + parse_config([ + {incomplete_handler, fun(_, _, _) -> true end}, + {incomplete_handler, fun(_, _, _) -> false end} + ]) + )}, + {"bad option flag", ?_assertError(badarg, parse_config([this_flag_does_not_exist]))} + ]. + + +config_to_list_test_() -> + [ + {"empty config", ?_assertEqual( + [], + config_to_list(#config{}) + )}, + {"all flags", ?_assertEqual( + [dirty_strings, + escaped_forward_slashes, + escaped_strings, + multi_term, + stream, + uescape, + unescaped_jsonp, + strict + ], + config_to_list( + #config{escaped_forward_slashes = true, + escaped_strings = true, + unescaped_jsonp = true, + dirty_strings = true, + multi_term = true, + strict_comments = true, + strict_utf8 = true, + strict_single_quotes = true, + strict_escapes = true, + strict_control_codes = true, + stream = true, + uescape = true + } + ) + )}, + {"single strict", ?_assertEqual( + [{strict, [comments]}], + config_to_list(#config{strict_comments = true}) + )}, + {"multiple strict", ?_assertEqual( + [{strict, [utf8, single_quotes, escapes]}], + config_to_list(#config{strict_utf8 = true, strict_single_quotes = true, strict_escapes = true}) + )}, + {"all strict", ?_assertEqual( + [strict], + config_to_list(#config{strict_comments = true, + strict_utf8 = true, + strict_single_quotes = true, + strict_escapes = true, + strict_control_codes = true}) + )}, + {"error handler", ?_assertEqual( + [{error_handler, fun ?MODULE:fake_error_handler/3}], + config_to_list(#config{error_handler=fun ?MODULE:fake_error_handler/3}) + )}, + {"incomplete handler", ?_assertEqual( + [{incomplete_handler, fun ?MODULE:fake_error_handler/3}], + config_to_list(#config{incomplete_handler=fun ?MODULE:fake_error_handler/3}) + )} + ]. + + +fake_error_handler(_, _, _) -> ok. + + +-endif. diff --git a/deps/jsx/src/jsx_config.hrl b/deps/jsx/src/jsx_config.hrl new file mode 100644 index 0000000000000000000000000000000000000000..c89963c5023a4c991cd03940cbbc283ca9b96ce9 --- /dev/null +++ b/deps/jsx/src/jsx_config.hrl @@ -0,0 +1,18 @@ +-record(config, { + dirty_strings = false :: boolean(), + escaped_forward_slashes = false :: boolean(), + escaped_strings = false :: boolean(), + multi_term = false :: boolean(), + strict_comments = false :: boolean(), + strict_commas = false :: boolean(), + strict_utf8 = false :: boolean(), + strict_single_quotes = false :: boolean(), + strict_escapes = false :: boolean(), + strict_control_codes = false :: boolean(), + stream = false :: boolean(), + return_tail = false :: boolean(), + uescape = false :: boolean(), + unescaped_jsonp = false :: boolean(), + error_handler = false :: false | jsx_config:handler(), + incomplete_handler = false :: false | jsx_config:handler() +}). diff --git a/deps/jsx/src/jsx_consult.erl b/deps/jsx/src/jsx_consult.erl new file mode 100644 index 0000000000000000000000000000000000000000..e0e73c9794484fa4a5344d035029498f7263bbac --- /dev/null +++ b/deps/jsx/src/jsx_consult.erl @@ -0,0 +1,81 @@ +%% The MIT License + +%% Copyright (c) 2010-2015 Alisdair Sullivan + +%% Permission is hereby granted, free of charge, to any person obtaining a copy +%% of this software and associated documentation files (the "Software"), to deal +%% in the Software without restriction, including without limitation the rights +%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +%% copies of the Software, and to permit persons to whom the Software is +%% furnished to do so, subject to the following conditions: + +%% The above copyright notice and this permission notice shall be included in +%% all copies or substantial portions of the Software. + +%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +%% THE SOFTWARE. + + +-module(jsx_consult). + +-export([consult/2]). +-export([init/1, reset/1, handle_event/2]). + + +-record(config, { + labels = binary, + return_maps = false +}). + +-type config() :: proplists:proplist(). +-export_type([config/0]). + +-type json_value() :: list(json_value()) + | map() + | true + | false + | null + | integer() + | float() + | binary(). +-export_type([json_value/0]). + +opts(Opts) -> [return_maps, multi_term] ++ Opts. + +-spec consult(File::file:name_all(), Config::config()) -> [json_value()]. + +consult(File, Config) when is_list(Config) -> + case file:read_file(File) of + {ok, Bin} -> + {Final, _, _} = (jsx:decoder( + ?MODULE, + opts(Config), + jsx_config:extract_config(opts(Config)) + ))(Bin), + lists:reverse(Final); + {error, _} -> erlang:error(badarg) + end. + + +-type state() :: {[], config(), {list(), #config{}}}. +-spec init(Config::config()) -> state(). + +init(Config) -> {[], Config, jsx_to_term:start_term(Config)}. + + +-spec reset(State::state()) -> state(). + +reset({Acc, Config, _}) -> {Acc, Config, jsx_to_term:start_term(Config)}. + + +-spec handle_event(Event::any(), State::state()) -> state(). + +handle_event(end_json, {Acc, Config, State}) -> + {[jsx_to_term:get_value(State)] ++ Acc, Config, State}; +handle_event(Event, {Acc, Config, State}) -> + {Acc, Config, jsx_to_term:handle_event(Event, State)}. diff --git a/deps/jsx/src/jsx_decoder.erl b/deps/jsx/src/jsx_decoder.erl new file mode 100644 index 0000000000000000000000000000000000000000..a706c89171709fdb779da4e4d74138cf0e4f18f0 --- /dev/null +++ b/deps/jsx/src/jsx_decoder.erl @@ -0,0 +1,1909 @@ +%% The MIT License + +%% Copyright (c) 2010-2013 alisdair sullivan + +%% Permission is hereby granted, free of charge, to any person obtaining a copy +%% of this software and associated documentation files (the "Software"), to deal +%% in the Software without restriction, including without limitation the rights +%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +%% copies of the Software, and to permit persons to whom the Software is +%% furnished to do so, subject to the following conditions: + +%% The above copyright notice and this permission notice shall be included in +%% all copies or substantial portions of the Software. + +%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +%% THE SOFTWARE. + + +-module(jsx_decoder). + +%% inline handle_event, format_number and maybe_replace +-compile({inline, [handle_event/3]}). +-compile({inline, [format_number/1]}). +-compile({inline, [maybe_replace/2]}). +-compile({inline, [doublequote/5, singlequote/5]}). + +-export([decoder/3, resume/6]). + + +-spec decoder(Handler::module(), State::any(), Config::jsx_config:options()) -> jsx:decoder(). + +decoder(Handler, State, Config) -> + fun(JSON) -> start(JSON, {Handler, Handler:init(State)}, [], jsx_config:parse_config(Config)) end. + + +%% resume allows continuation from interrupted decoding without having to explicitly export +%% all states +-spec resume( + Rest::binary(), + State::atom(), + Handler::module(), + Acc::any(), + Stack::list(atom()), + Config::jsx:config() + ) -> jsx:decoder() | {incomplete, jsx:decoder()}. + +resume(Rest, State, Handler, Acc, Stack, Config) -> + case State of + start -> start(Rest, Handler, Stack, Config); + value -> value(Rest, Handler, Stack, Config); + object -> object(Rest, Handler, Stack, Config); + array -> array(Rest, Handler, Stack, Config); + colon -> colon(Rest, Handler, Stack, Config); + key -> key(Rest, Handler, Stack, Config); + string -> string(Rest, Handler, Acc, Stack, Config); + number -> number(Rest, Handler, Acc, Stack, Config); + true -> true(Rest, Handler, Stack, Config); + false -> false(Rest, Handler, Stack, Config); + null -> null(Rest, Handler, Stack, Config); + comment -> comment(Rest, Handler, Acc, Stack, Config); + maybe_done -> maybe_done(Rest, Handler, Stack, Config); + done -> done(Rest, Handler, Stack, Config) + end. + + +-include("jsx_config.hrl"). + + +%% whitespace +-define(space, 16#20). +-define(tab, 16#09). +-define(cr, 16#0D). +-define(newline, 16#0A). + +%% object delimiters +-define(start_object, 16#7B). +-define(end_object, 16#7D). + +%% array delimiters +-define(start_array, 16#5B). +-define(end_array, 16#5D). + +%% kv seperator +-define(comma, 16#2C). +-define(doublequote, 16#22). +-define(singlequote, 16#27). +-define(colon, 16#3A). + +%% string escape sequences +-define(rsolidus, 16#5C). +-define(solidus, 16#2F). + +%% math +-define(zero, 16#30). +-define(decimalpoint, 16#2E). +-define(negative, 16#2D). +-define(positive, 16#2B). + +%% comments +-define(star, 16#2A). + + +%% some useful guards +-define(is_hex(Symbol), + (Symbol >= $a andalso Symbol =< $f) orelse + (Symbol >= $A andalso Symbol =< $F) orelse + (Symbol >= $0 andalso Symbol =< $9) +). + +-define(is_nonzero(Symbol), + Symbol >= $1 andalso Symbol =< $9 +). + + +%% error is a macro so the stack trace shows the error site when possible +-ifndef(error). +-define(error(State, Bin, Handler, Acc, Stack, Config), + case Config#config.error_handler of + false -> erlang:error(badarg); + F -> F(Bin, {decoder, State, Handler, Acc, Stack}, jsx_config:config_to_list(Config)) + end +). +-define(error(State, Bin, Handler, Stack, Config), + ?error(State, Bin, Handler, null, Stack, Config) +). +-endif. + + +incomplete(State, Rest, Handler, Stack, Config = #config{stream=false}) -> + ?error(State, Rest, Handler, Stack, Config); +incomplete(State, Rest, Handler, Stack, Config) -> + incomplete(State, Rest, Handler, unused, Stack, Config). + + +incomplete(State, Rest, Handler, Acc, Stack, Config = #config{stream=false}) -> + ?error(State, Rest, Handler, Acc, Stack, Config); +incomplete(State, Rest, Handler, Acc, Stack, Config = #config{incomplete_handler=false}) -> + {incomplete, fun(Stream) when is_binary(Stream) -> + resume(<>, State, Handler, Acc, Stack, Config); + (End) when End == end_stream; End == end_json -> + case resume(<>, State, Handler, Acc, Stack, Config#config{stream=false}) of + {incomplete, _} -> ?error(State, Rest, Handler, Acc, Stack, Config); + Else -> Else + end + end + }; +incomplete(State, Rest, Handler, Acc, Stack, Config = #config{incomplete_handler=F}) -> + F(Rest, {decoder, State, Handler, Acc, Stack}, jsx_config:config_to_list(Config)). + + +handle_event(Event, {Handler, State}, _Config) -> {Handler, Handler:handle_event(Event, State)}. + + +start(<<16#ef, 16#bb, 16#bf, Rest/binary>>, Handler, Stack, Config) -> + value(Rest, Handler, Stack, Config); +start(<<16#ef, 16#bb>>, Handler, Stack, Config) -> + incomplete(start, <<16#ef, 16#bb>>, Handler, Stack, Config); +start(<<16#ef>>, Handler, Stack, Config) -> + incomplete(start, <<16#ef>>, Handler, Stack, Config); +start(<<>>, Handler, Stack, Config) -> + incomplete(start, <<>>, Handler, Stack, Config); +start(Bin, Handler, Stack, Config) -> + value(Bin, Handler, Stack, Config). + + +value(<>, Handler, Stack, Config) -> + string(Rest, Handler, Stack, Config); +value(<>, Handler, Stack, Config) -> + value(Rest, Handler, Stack, Config); +value(<>, Handler, Stack, Config) -> + object(Rest, handle_event(start_object, Handler, Config), [key|Stack], Config); +value(<>, Handler, Stack, Config) -> + array(Rest, handle_event(start_array, Handler, Config), [array|Stack], Config); +value(<<$t, $r, $u, $e, Rest/binary>>, Handler, Stack, Config) -> + maybe_done(Rest, handle_event({literal, true}, Handler, Config), Stack, Config); +value(<<$f, $a, $l, $s, $e, Rest/binary>>, Handler, Stack, Config) -> + maybe_done(Rest, handle_event({literal, false}, Handler, Config), Stack, Config); +value(<<$n, $u, $l, $l, Rest/binary>>, Handler, Stack, Config) -> + maybe_done(Rest, handle_event({literal, null}, Handler, Config), Stack, Config); +value(<>, Handler, Stack, Config) -> + number(Rest, Handler, [?zero], [zero|Stack], Config); +value(<<$1, Rest/binary>>, Handler, Stack, Config) -> + number(Rest, Handler, [$1], [integer|Stack], Config); +value(<<$2, Rest/binary>>, Handler, Stack, Config) -> + number(Rest, Handler, [$2], [integer|Stack], Config); +value(<<$3, Rest/binary>>, Handler, Stack, Config) -> + number(Rest, Handler, [$3], [integer|Stack], Config); +value(<<$4, Rest/binary>>, Handler, Stack, Config) -> + number(Rest, Handler, [$4], [integer|Stack], Config); +value(<<$5, Rest/binary>>, Handler, Stack, Config) -> + number(Rest, Handler, [$5], [integer|Stack], Config); +value(<<$6, Rest/binary>>, Handler, Stack, Config) -> + number(Rest, Handler, [$6], [integer|Stack], Config); +value(<<$7, Rest/binary>>, Handler, Stack, Config) -> + number(Rest, Handler, [$7], [integer|Stack], Config); +value(<<$8, Rest/binary>>, Handler, Stack, Config) -> + number(Rest, Handler, [$8], [integer|Stack], Config); +value(<<$9, Rest/binary>>, Handler, Stack, Config) -> + number(Rest, Handler, [$9], [integer|Stack], Config); +value(<>, Handler, Stack, Config) -> + number(Rest, Handler, [$-], [negative|Stack], Config); +value(<>, Handler, Stack, Config) -> + value(Rest, Handler, Stack, Config); +value(<<$t, Rest/binary>>, Handler, Stack, Config) -> + true(Rest, Handler, Stack, Config); +value(<<$f, Rest/binary>>, Handler, Stack, Config) -> + false(Rest, Handler, Stack, Config); +value(<<$n, Rest/binary>>, Handler, Stack, Config) -> + null(Rest, Handler, Stack, Config); +value(<>, Handler, Stack, Config) -> + value(Rest, Handler, Stack, Config); +value(<>, Handler, Stack, Config) -> + value(Rest, Handler, Stack, Config); +value(<>, Handler, Stack, Config=#config{strict_single_quotes=false}) -> + string(Rest, Handler, [singlequote|Stack], Config); +value(<> = Rest, Handler, Stack, Config=#config{strict_commas=false}) -> + maybe_done(Rest, Handler, Stack, Config); +value(<>, Handler, Stack, Config=#config{strict_comments=true}) -> + ?error(value, <>, Handler, Stack, Config); +value(<>, Handler, Stack, Config) -> + comment(Rest, Handler, value, [comment|Stack], Config); +value(<>, Handler, Stack, Config) -> + comment(Rest, Handler, value, [multicomment|Stack], Config); +value(<>, Handler, Stack, Config) -> + incomplete(value, <>, Handler, Stack, Config); +value(<<>>, Handler, Stack, Config) -> + incomplete(value, <<>>, Handler, Stack, Config); +value(Bin, Handler, Stack, Config) -> + ?error(value, Bin, Handler, Stack, Config). + + +object(<>, Handler, Stack, Config) -> + string(Rest, Handler, Stack, Config); +object(<>, Handler, Stack, Config) -> + object(Rest, Handler, Stack, Config); +object(<>, Handler, [key|Stack], Config) -> + maybe_done(Rest, handle_event(end_object, Handler, Config), Stack, Config); +object(<>, Handler, Stack, Config) -> + object(Rest, Handler, Stack, Config); +object(<>, Handler, Stack, Config) -> + object(Rest, Handler, Stack, Config); +object(<>, Handler, Stack, Config) -> + object(Rest, Handler, Stack, Config); +object(<>, Handler, Stack, Config=#config{strict_single_quotes=false}) -> + string(Rest, Handler, [singlequote|Stack], Config); +object(<>, Handler, Stack, Config=#config{strict_comments=true}) -> + ?error(object, <>, Handler, Stack, Config); +object(<>, Handler, Stack, Config) -> + comment(Rest, Handler, object, [comment|Stack], Config); +object(<>, Handler, Stack, Config) -> + comment(Rest, Handler, object, [multicomment|Stack], Config); +object(<>, Handler, Stack, Config) -> + incomplete(object, <>, Handler, Stack, Config); +object(<<>>, Handler, Stack, Config) -> + incomplete(object, <<>>, Handler, Stack, Config); +object(Bin, Handler, Stack, Config) -> + ?error(object, Bin, Handler, Stack, Config). + + +array(<>, Handler, [array|Stack], Config) -> + maybe_done(Rest, handle_event(end_array, Handler, Config), Stack, Config); +array(<>, Handler, Stack, Config) -> + array(Rest, Handler, Stack, Config); +array(<>, Handler, Stack, Config) -> + array(Rest, Handler, Stack, Config); +array(<>, Handler, Stack, Config) -> + array(Rest, Handler, Stack, Config); +array(<>, Handler, Stack, Config) -> + array(Rest, Handler, Stack, Config); +array(<>, Handler, Stack, Config=#config{strict_comments=true}) -> + value(<>, Handler, Stack, Config); +array(<>, Handler, Stack, Config) -> + comment(Rest, Handler, array, [comment|Stack], Config); +array(<>, Handler, Stack, Config) -> + comment(Rest, Handler, array, [multicomment|Stack], Config); +array(<>, Handler, Stack, Config) -> + incomplete(array, <>, Handler, Stack, Config); +array(<<>>, Handler, Stack, Config) -> + incomplete(array, <<>>, Handler, Stack, Config); +array(Bin, Handler, Stack, Config) -> + value(Bin, Handler, Stack, Config). + + +colon(<>, Handler, [key|Stack], Config) -> + value(Rest, Handler, [object|Stack], Config); +colon(<>, Handler, Stack, Config) -> + colon(Rest, Handler, Stack, Config); +colon(<>, Handler, Stack, Config) -> + colon(Rest, Handler, Stack, Config); +colon(<>, Handler, Stack, Config) -> + colon(Rest, Handler, Stack, Config); +colon(<>, Handler, Stack, Config) -> + colon(Rest, Handler, Stack, Config); +colon(<>, Handler, Stack, Config=#config{strict_comments=true}) -> + ?error(colon, <>, Handler, Stack, Config); +colon(<>, Handler, Stack, Config) -> + comment(Rest, Handler, colon, [comment|Stack], Config); +colon(<>, Handler, Stack, Config) -> + comment(Rest, Handler, colon, [multicomment|Stack], Config); +colon(<>, Handler, Stack, Config) -> + incomplete(colon, <>, Handler, Stack, Config); +colon(<<>>, Handler, Stack, Config) -> + incomplete(colon, <<>>, Handler, Stack, Config); +colon(Bin, Handler, Stack, Config) -> + ?error(colon, Bin, Handler, Stack, Config). + + +key(<>, Handler, Stack, Config) -> + string(Rest, Handler, Stack, Config); +key(<>, Handler, Stack, Config) -> + key(Rest, Handler, Stack, Config); +key(<>, Handler, [key|Stack], Config=#config{strict_commas=false}) -> + maybe_done(<>, Handler, [object|Stack], Config); +key(<>, Handler, Stack, Config) -> + key(Rest, Handler, Stack, Config); +key(<>, Handler, Stack, Config) -> + key(Rest, Handler, Stack, Config); +key(<>, Handler, Stack, Config) -> + key(Rest, Handler, Stack, Config); +key(<>, Handler, Stack, Config=#config{strict_single_quotes=false}) -> + string(Rest, Handler, [singlequote|Stack], Config); +key(<>, Handler, Stack, Config=#config{strict_comments=true}) -> + ?error(key, <>, Handler, Stack, Config); +key(<>, Handler, Stack, Config) -> + comment(Rest, Handler, key, [comment|Stack], Config); +key(<>, Handler, Stack, Config) -> + comment(Rest, Handler, key, [multicomment|Stack], Config); +key(<>, Handler, Stack, Config) -> + incomplete(key, <>, Handler, Stack, Config); +key(<<>>, Handler, Stack, Config) -> + incomplete(key, <<>>, Handler, Stack, Config); +key(Bin, Handler, Stack, Config) -> + ?error(key, Bin, Handler, Stack, Config). + + +%% note that if you encounter an error from string and you can't find the clause that +%% caused it here, it might be in unescape below +string(Bin, Handler, Stack, Config) -> + string(Bin, Handler, [], Stack, Config). + + +string(<>, Handler, Acc, Stack, Config) -> + doublequote(Rest, Handler, Acc, Stack, Config); +string(<>, Handler, Acc, Stack, Config) -> + singlequote(Rest, Handler, Acc, Stack, Config); +string(<>, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, maybe_replace(?solidus, Config)], Stack, Config); +string(<>, Handler, Acc, Stack, Config) -> + unescape(Rest, Handler, Acc, Stack, Config); +%% TODO this is pretty gross and i don't like it +string(<> = Bin, Handler, Acc, Stack, Config=#config{uescape=true}) -> + case X of + X when X < 16#80 -> count(Bin, Handler, Acc, Stack, Config); + X -> string(Rest, Handler, [Acc, json_escape_sequence(X)], Stack, Config) + end; +%% u+2028 +string(<<226, 128, 168, Rest/binary>>, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, maybe_replace(16#2028, Config)], Stack, Config); +%% u+2029 +string(<<226, 128, 169, Rest/binary>>, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, maybe_replace(16#2029, Config)], Stack, Config); +string(<> = Bin, Handler, Acc, Stack, Config=#config{strict_control_codes=true}) when X > 16#1f -> + count(Bin, Handler, Acc, Stack, Config); +string(<<_/utf8, _/binary>> = Bin, Handler, Acc, Stack, Config=#config{strict_control_codes=false}) -> + count(Bin, Handler, Acc, Stack, Config); +%% necessary for bytes that are badly formed utf8 that won't match in `count` +string(<>, Handler, Acc, Stack, Config=#config{dirty_strings=true}) -> + string(Rest, Handler, [Acc, X], Stack, Config); +%% u+fffe and u+ffff for R14BXX (subsequent runtimes will happily match with /utf8 +string(<<239, 191, 190, Rest/binary>>, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, <<16#fffe/utf8>>], Stack, Config); +string(<<239, 191, 191, Rest/binary>>, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, <<16#ffff/utf8>>], Stack, Config); +string(<<>>, Handler, Acc, Stack, Config) -> + incomplete(string, <<>>, Handler, Acc, Stack, Config); +string(<>, Handler, Acc, Stack, Config) when X >= 2#11000000 -> + incomplete(string, <>, Handler, Acc, Stack, Config); +string(<>, Handler, Acc, Stack, Config) when X >= 2#11100000, Y >= 2#10000000 -> + incomplete(string, <>, Handler, Acc, Stack, Config); +string(<>, Handler, Acc, Stack, Config) + when X >= 2#11100000, Y >= 2#10000000, Z >= 2#10000000 -> + incomplete(string, <>, Handler, Acc, Stack, Config); +%% surrogates +string(<<237, X, _, Rest/binary>>, Handler, Acc, Stack, Config=#config{strict_utf8=false}) + when X >= 160 -> + string(Rest, Handler, [Acc, <<16#fffd/utf8>>], Stack, Config); +%% overlong encodings and missing continuations of a 2 byte sequence +string(<>, Handler, Acc, Stack, Config=#config{strict_utf8=false}) + when X >= 192, X =< 223 -> + strip_continuations(Rest, Handler, Acc, Stack, Config, 1); +%% overlong encodings and missing continuations of a 3 byte sequence +string(<>, Handler, Acc, Stack, Config=#config{strict_utf8=false}) + when X >= 224, X =< 239 -> + strip_continuations(Rest, Handler, Acc, Stack, Config, 2); +%% overlong encodings and missing continuations of a 4 byte sequence +string(<>, Handler, Acc, Stack, Config=#config{strict_utf8=false}) + when X >= 240, X =< 247 -> + strip_continuations(Rest, Handler, Acc, Stack, Config, 3); +%% incompletes and unexpected bytes, including orphan continuations +string(<<_, Rest/binary>>, Handler, Acc, Stack, Config=#config{strict_utf8=false}) -> + string(Rest, Handler, [Acc, <<16#fffd/utf8>>], Stack, Config); +string(Bin, Handler, Acc, Stack, Config) -> ?error(string, Bin, Handler, Acc, Stack, Config). + + +count(Bin, Handler, Acc, Stack, Config) -> + Size = count(Bin, 0, Config), + <> = Bin, + string(Rest, Handler, [Acc, Clean], Stack, Config). + + +%% explicitly whitelist ascii set for faster parsing. really? really. someone should +%% submit a patch that unrolls simple guards +count(<<32, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<33, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<>, N, _) -> N; +count(<<35, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<36, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<37, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<38, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<>, N, _) -> N; +count(<<40, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<41, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<42, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<43, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<44, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<45, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<46, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<>, N, _) -> N; +count(<<48, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<49, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<50, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<51, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<52, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<53, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<54, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<55, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<56, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<57, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<58, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<59, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<60, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<61, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<62, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<63, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<64, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<65, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<66, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<67, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<68, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<69, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<70, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<71, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<72, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<73, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<74, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<75, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<76, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<77, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<78, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<79, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<80, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<81, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<82, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<83, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<84, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<85, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<86, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<87, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<88, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<89, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<90, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<91, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<>, N, _) -> N; +count(<<93, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<94, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<95, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<96, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<97, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<98, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<99, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<100, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<101, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<102, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<103, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<104, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<105, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<106, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<107, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<108, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<109, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<110, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<111, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<112, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<113, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<114, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<115, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<116, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<117, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<118, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<119, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<120, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<121, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<122, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<123, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<124, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<125, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<126, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<127, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<_, Rest/binary>>, N, Config=#config{dirty_strings=true}) -> + count(Rest, N + 1, Config); +count(<<_/utf8, _/binary>>, N, #config{uescape=true}) -> N; +count(<>, N, Config=#config{strict_control_codes=false}) when X < 32 -> + count(Rest, N + 1, Config); +count(<>, N, #config{strict_control_codes=true}) when X < 32 -> N; +count(<>, N, Config) -> + case X of + X when X < 16#800 -> count(Rest, N + 2, Config); + %% jsonp escaping + 16#2028 -> N; + 16#2029 -> N; + X when X < 16#10000 -> count(Rest, N + 3, Config); + _ -> count(Rest, N + 4, Config) + end; +count(_, N, _) -> N. + + +doublequote(Rest, Handler, Acc, [key|_] = Stack, Config) -> + colon(Rest, handle_event({key, iolist_to_binary(Acc)}, Handler, Config), Stack, Config); +doublequote(Rest, Handler, Acc, [singlequote|_] = Stack, Config) -> + string(Rest, Handler, [Acc, maybe_replace(?doublequote, Config)], Stack, Config); +doublequote(<<>>, Handler, Acc, [singlequote|_] = Stack, Config) -> + incomplete(string, <>, Handler, Acc, Stack, Config); +doublequote(Rest, Handler, Acc, Stack, Config) -> + maybe_done(Rest, handle_event({string, iolist_to_binary(Acc)}, Handler, Config), Stack, Config). + + +singlequote(Rest, Handler, Acc, [singlequote, key|Stack], Config) -> + colon(Rest, handle_event({key, iolist_to_binary(Acc)}, Handler, Config), [key|Stack], Config); +singlequote(Rest, Handler, Acc, [singlequote|Stack], Config) -> + maybe_done(Rest, handle_event({string, iolist_to_binary(Acc)}, Handler, Config), Stack, Config); +singlequote(Rest, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, ?singlequote], Stack, Config). + + +%% strips continuation bytes after bad utf bytes, guards against both too short +%% and overlong sequences. N is the maximum number of bytes to strip +strip_continuations(<>, Handler, Acc, Stack, Config, 0) -> + string(Rest, Handler, [Acc, <<16#fffd/utf8>>], Stack, Config); +strip_continuations(<>, Handler, Acc, Stack, Config, N) when X >= 128, X =< 191 -> + strip_continuations(Rest, Handler, Acc, Stack, Config, N - 1); +%% if end of input is reached before stripping the max number of continuations +%% possible magic numbers are reinserted into the stream that get us back to +%% the same state without complicated machinery +strip_continuations(<<>>, Handler, Acc, Stack, Config, N) -> + case N of + 1 -> incomplete(string, <<192>>, Handler, Acc, Stack, Config); + 2 -> incomplete(string, <<224>>, Handler, Acc, Stack, Config); + 3 -> incomplete(string, <<240>>, Handler, Acc, Stack, Config) + end; +%% not a continuation byte, insert a replacement character for sequence thus +%% far and dispatch back to string +strip_continuations(<>, Handler, Acc, Stack, Config, _) -> + string(Rest, Handler, [Acc, <<16#fffd/utf8>>], Stack, Config). + + +%% this all gets really gross and should probably eventually be folded into +%% but for now it fakes being part of string on incompletes and errors +unescape(<>, Handler, Acc, Stack, Config=#config{dirty_strings=true}) -> + string(<>, Handler, [Acc, <>], Stack, Config); +unescape(<>, Handler, Acc, Stack, Config=#config{dirty_strings=true}) -> + string(Rest, Handler, [Acc, <>], Stack, Config); +unescape(<<$b, Rest/binary>>, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, maybe_replace($\b, Config)], Stack, Config); +unescape(<<$f, Rest/binary>>, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, maybe_replace($\f, Config)], Stack, Config); +unescape(<<$n, Rest/binary>>, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, maybe_replace($\n, Config)], Stack, Config); +unescape(<<$r, Rest/binary>>, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, maybe_replace($\r, Config)], Stack, Config); +unescape(<<$t, Rest/binary>>, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, maybe_replace($\t, Config)], Stack, Config); +unescape(<>, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, maybe_replace($\", Config)], Stack, Config); +unescape(<>, Handler, Acc, Stack, Config=#config{strict_single_quotes=false}) -> + string(Rest, Handler, [Acc, <>], Stack, Config); +unescape(<>, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, maybe_replace($\\, Config)], Stack, Config); +unescape(<>, Handler, Acc, Stack, Config) -> + string(Rest, Handler, [Acc, maybe_replace($/, Config)], Stack, Config); +unescape(<<$u, F, A, B, C, ?rsolidus, $u, G, X, Y, Z, Rest/binary>>, Handler, Acc, Stack, Config) + when (A == $8 orelse A == $9 orelse A == $a orelse A == $b orelse A == $A orelse A == $B), + (X == $c orelse X == $d orelse X == $e orelse X == $f orelse X == $C orelse X == $D orelse X == $E orelse X == $F), + (F == $d orelse F == $D), + (G == $d orelse G == $D), + ?is_hex(B), ?is_hex(C), ?is_hex(Y), ?is_hex(Z) + -> + High = erlang:list_to_integer([$d, A, B, C], 16), + Low = erlang:list_to_integer([$d, X, Y, Z], 16), + Codepoint = (High - 16#d800) * 16#400 + (Low - 16#dc00) + 16#10000, + string(Rest, Handler, [Acc, <>], Stack, Config); +unescape(<<$u, F0, A, B, C, ?rsolidus, $u, W, X, Y, Z, Rest/binary>>, Handler, Acc, Stack, Config) + when (A == $8 orelse A == $9 orelse A == $a orelse A == $b orelse A == $A orelse A == $B), + (F0 == $d orelse F0 == $D), + ?is_hex(B), ?is_hex(C), ?is_hex(W), ?is_hex(X), ?is_hex(Y), ?is_hex(Z) + -> + case Config#config.strict_utf8 of + true -> ?error(string, <<$u, $d, A, B, C, ?rsolidus, $u, W, X, Y, Z, Rest/binary>>, Handler, Acc, Stack, Config); + false -> string(Rest, Handler, [Acc, <<16#fffd/utf8>>, <<16#fffd/utf8>>], Stack, Config) + end; +unescape(<<$u, F, A, B, C, ?rsolidus, Rest/binary>>, Handler, Acc, Stack, Config) + when (A == $8 orelse A == $9 orelse A == $a orelse A == $b orelse A == $A orelse A == $B), + (F == $d orelse F == $D), + ?is_hex(B), ?is_hex(C) + -> + incomplete(string, <>, Handler, Acc, Stack, Config); +unescape(<<$u, F, A, B, C>>, Handler, Acc, Stack, Config) + when (A == $8 orelse A == $9 orelse A == $a orelse A == $b orelse A == $A orelse A == $B), + (F == $d orelse F == $D), + ?is_hex(B), ?is_hex(C) + -> + incomplete(string, <>, Handler, Acc, Stack, Config); +unescape(<<$u, A, B, C, D, Rest/binary>>, Handler, Acc, Stack, Config) + when ?is_hex(A), ?is_hex(B), ?is_hex(C), ?is_hex(D) -> + case erlang:list_to_integer([A, B, C, D], 16) of + Codepoint when Codepoint < 16#d800; Codepoint > 16#dfff -> + string(Rest, Handler, [Acc, maybe_replace(Codepoint, Config)], Stack, Config); + _ when Config#config.strict_utf8 -> + ?error(string, <>, Handler, Acc, Stack, Config); + _ -> string(Rest, Handler, [Acc, <<16#fffd/utf8>>], Stack, Config) + end; +unescape(Bin, Handler, Acc, Stack, Config) -> + case is_partial_escape(Bin) of + true -> incomplete(string, <>, Handler, Acc, Stack, Config); + false -> case Config#config.strict_escapes of + true -> ?error(string, <>, Handler, Acc, Stack, Config); + false -> string(Bin, Handler, [Acc, <>], Stack, Config) + end + end. + + +is_partial_escape(<<$u, A, B, C>>) when ?is_hex(A), ?is_hex(B), ?is_hex(C) -> true; +is_partial_escape(<<$u, A, B>>) when ?is_hex(A), ?is_hex(B) -> true; +is_partial_escape(<<$u, A>>) when ?is_hex(A) -> true; +is_partial_escape(<<$u>>) -> true; +is_partial_escape(<<>>) -> true; +is_partial_escape(_) -> false. + + +maybe_replace(C, #config{dirty_strings=true}) -> <>; +maybe_replace($\b, #config{escaped_strings=true}) -> <<$\\, $b>>; +maybe_replace($\t, #config{escaped_strings=true}) -> <<$\\, $t>>; +maybe_replace($\n, #config{escaped_strings=true}) -> <<$\\, $n>>; +maybe_replace($\f, #config{escaped_strings=true}) -> <<$\\, $f>>; +maybe_replace($\r, #config{escaped_strings=true}) -> <<$\\, $r>>; +maybe_replace($\", #config{escaped_strings=true}) -> <<$\\, $\">>; +maybe_replace($/, Config=#config{escaped_strings=true}) -> + case Config#config.escaped_forward_slashes of + true -> <<$\\, $/>> + ; false -> <<$/>> + end; +maybe_replace($\\, #config{escaped_strings=true}) -> <<$\\, $\\>>; +maybe_replace(X, Config=#config{escaped_strings=true}) when X == 16#2028; X == 16#2029 -> + case Config#config.unescaped_jsonp of + true -> <> + ; false -> json_escape_sequence(X) + end; +maybe_replace(X, #config{escaped_strings=true}) when X < 32 -> + json_escape_sequence(X); +maybe_replace(X, _Config) -> <>. + + +%% convert a codepoint to it's \uXXXX equiv. +json_escape_sequence(X) when X < 65536 -> + <> = <>, + <<$\\, $u, (to_hex(A)), (to_hex(B)), (to_hex(C)), (to_hex(D))>>; +json_escape_sequence(X) -> + Adjusted = X - 16#10000, + <> = <>, + [json_escape_sequence(A + 16#d800), json_escape_sequence(B + 16#dc00)]. + + +%% ascii "1" is [49], "2" is [50], etc... +to_hex(10) -> $a; +to_hex(11) -> $b; +to_hex(12) -> $c; +to_hex(13) -> $d; +to_hex(14) -> $e; +to_hex(15) -> $f; +to_hex(X) -> X + 48. + + +number(<<$e, Rest/binary>>, Handler, Acc, [integer|Stack], Config) -> + number(Rest, Handler, [Acc, $., $0, $e], [e|Stack], Config); +number(<<$E, Rest/binary>>, Handler, Acc, [integer|Stack], Config) -> + number(Rest, Handler, [Acc, $., $0, $e], [e|Stack], Config); +number(<<$e, Rest/binary>>, Handler, Acc, [zero|Stack], Config) -> + number(Rest, Handler, [Acc, $., $0, $e], [e|Stack], Config); +number(<<$E, Rest/binary>>, Handler, Acc, [zero|Stack], Config) -> + number(Rest, Handler, [Acc, $., $0, $e], [e|Stack], Config); +number(<<>>, Handler, Acc, [State|Stack], Config=#config{stream=false}) -> + NumType = case State of + zero -> integer; + integer -> integer; + decimal -> float; + exp -> float + end, + finish_number(<<>>, Handler, {NumType, iolist_to_binary(Acc)}, Stack, Config); +number(<<>>, Handler, Acc, Stack, Config) -> + incomplete(number, <<>>, Handler, Acc, Stack, Config); +number(Bin, Handler, Acc, [State|Stack], Config) -> + Counted = case State of + zero -> zero(Bin, 0); + integer -> integer(Bin, 0); + negative -> negative(Bin, 0); + initialdecimal -> initialdecimal(Bin, 0); + decimal -> decimal(Bin, 0); + e -> e(Bin, 0); + ex -> ex(Bin, 0); + exp -> exp(Bin, 0) + end, + case Counted of + {finish_integer, Size} -> + <> = Bin, + finish_number(Rest, Handler, {integer, iolist_to_binary([Acc, Clean])}, Stack, Config); + {finish_float, Size} -> + <> = Bin, + finish_number(Rest, Handler, {float, iolist_to_binary([Acc, Clean])}, Stack, Config); + {error, Size} -> + <> = Bin, + ?error(number, Rest, Handler, [Acc, Clean], Stack, Config); + {NewState, Size} -> + <> = Bin, + number(Rest, Handler, [Acc, Clean], [NewState|Stack], Config) + end. + + +zero(<>, N) -> initialdecimal(Rest, N + 1); +zero(<<$e, _/binary>>, N) -> {integer, N}; +zero(<<$E, _/binary>>, N) -> {integer, N}; +zero(<<>>, N) -> {zero, N}; +zero(_, N) -> {finish_integer, N}. + + +integer(<<$0, Rest/binary>>, N) -> integer(Rest, N + 1); +integer(<<$1, Rest/binary>>, N) -> integer(Rest, N + 1); +integer(<<$2, Rest/binary>>, N) -> integer(Rest, N + 1); +integer(<<$3, Rest/binary>>, N) -> integer(Rest, N + 1); +integer(<<$4, Rest/binary>>, N) -> integer(Rest, N + 1); +integer(<<$5, Rest/binary>>, N) -> integer(Rest, N + 1); +integer(<<$6, Rest/binary>>, N) -> integer(Rest, N + 1); +integer(<<$7, Rest/binary>>, N) -> integer(Rest, N + 1); +integer(<<$8, Rest/binary>>, N) -> integer(Rest, N + 1); +integer(<<$9, Rest/binary>>, N) -> integer(Rest, N + 1); +integer(<>, N) -> initialdecimal(Rest, N + 1); +integer(<<$e, _/binary>>, N) -> {integer, N}; +integer(<<$E, _/binary>>, N) -> {integer, N}; +integer(<<>>, N) -> {integer, N}; +integer(_, N) -> {finish_integer, N}. + + +negative(<<$0, Rest/binary>>, N) -> zero(Rest, N + 1); +negative(<<$1, Rest/binary>>, N) -> integer(Rest, N + 1); +negative(<<$2, Rest/binary>>, N) -> integer(Rest, N + 1); +negative(<<$3, Rest/binary>>, N) -> integer(Rest, N + 1); +negative(<<$4, Rest/binary>>, N) -> integer(Rest, N + 1); +negative(<<$5, Rest/binary>>, N) -> integer(Rest, N + 1); +negative(<<$6, Rest/binary>>, N) -> integer(Rest, N + 1); +negative(<<$7, Rest/binary>>, N) -> integer(Rest, N + 1); +negative(<<$8, Rest/binary>>, N) -> integer(Rest, N + 1); +negative(<<$9, Rest/binary>>, N) -> integer(Rest, N + 1); +negative(<<>>, N) -> {negative, N}; +negative(_, N) -> {error, N}. + + +initialdecimal(<<$0, Rest/binary>>, N) -> decimal(Rest, N + 1); +initialdecimal(<<$1, Rest/binary>>, N) -> decimal(Rest, N + 1); +initialdecimal(<<$2, Rest/binary>>, N) -> decimal(Rest, N + 1); +initialdecimal(<<$3, Rest/binary>>, N) -> decimal(Rest, N + 1); +initialdecimal(<<$4, Rest/binary>>, N) -> decimal(Rest, N + 1); +initialdecimal(<<$5, Rest/binary>>, N) -> decimal(Rest, N + 1); +initialdecimal(<<$6, Rest/binary>>, N) -> decimal(Rest, N + 1); +initialdecimal(<<$7, Rest/binary>>, N) -> decimal(Rest, N + 1); +initialdecimal(<<$8, Rest/binary>>, N) -> decimal(Rest, N + 1); +initialdecimal(<<$9, Rest/binary>>, N) -> decimal(Rest, N + 1); +initialdecimal(<<>>, N) -> {initialdecimal, N}; +initialdecimal(_, N) -> {error, N}. + + +decimal(<<$0, Rest/binary>>, N) -> decimal(Rest, N + 1); +decimal(<<$1, Rest/binary>>, N) -> decimal(Rest, N + 1); +decimal(<<$2, Rest/binary>>, N) -> decimal(Rest, N + 1); +decimal(<<$3, Rest/binary>>, N) -> decimal(Rest, N + 1); +decimal(<<$4, Rest/binary>>, N) -> decimal(Rest, N + 1); +decimal(<<$5, Rest/binary>>, N) -> decimal(Rest, N + 1); +decimal(<<$6, Rest/binary>>, N) -> decimal(Rest, N + 1); +decimal(<<$7, Rest/binary>>, N) -> decimal(Rest, N + 1); +decimal(<<$8, Rest/binary>>, N) -> decimal(Rest, N + 1); +decimal(<<$9, Rest/binary>>, N) -> decimal(Rest, N + 1); +decimal(<<$e, Rest/binary>>, N) -> e(Rest, N + 1); +decimal(<<$E, Rest/binary>>, N) -> e(Rest, N + 1); +decimal(<<>>, N) -> {decimal, N}; +decimal(_, N) -> {finish_float, N}. + + +e(<<$0, Rest/binary>>, N) -> exp(Rest, N + 1); +e(<<$1, Rest/binary>>, N) -> exp(Rest, N + 1); +e(<<$2, Rest/binary>>, N) -> exp(Rest, N + 1); +e(<<$3, Rest/binary>>, N) -> exp(Rest, N + 1); +e(<<$4, Rest/binary>>, N) -> exp(Rest, N + 1); +e(<<$5, Rest/binary>>, N) -> exp(Rest, N + 1); +e(<<$6, Rest/binary>>, N) -> exp(Rest, N + 1); +e(<<$7, Rest/binary>>, N) -> exp(Rest, N + 1); +e(<<$8, Rest/binary>>, N) -> exp(Rest, N + 1); +e(<<$9, Rest/binary>>, N) -> exp(Rest, N + 1); +e(<>, N) -> ex(Rest, N + 1); +e(<>, N) -> ex(Rest, N + 1); +e(<<>>, N) -> {e, N}; +e(_, N) -> {error, N}. + + +ex(<<$0, Rest/binary>>, N) -> exp(Rest, N + 1); +ex(<<$1, Rest/binary>>, N) -> exp(Rest, N + 1); +ex(<<$2, Rest/binary>>, N) -> exp(Rest, N + 1); +ex(<<$3, Rest/binary>>, N) -> exp(Rest, N + 1); +ex(<<$4, Rest/binary>>, N) -> exp(Rest, N + 1); +ex(<<$5, Rest/binary>>, N) -> exp(Rest, N + 1); +ex(<<$6, Rest/binary>>, N) -> exp(Rest, N + 1); +ex(<<$7, Rest/binary>>, N) -> exp(Rest, N + 1); +ex(<<$8, Rest/binary>>, N) -> exp(Rest, N + 1); +ex(<<$9, Rest/binary>>, N) -> exp(Rest, N + 1); +ex(<<>>, N) -> {ex, N}; +ex(_, N) -> {error, N}. + + +exp(<<$0, Rest/binary>>, N) -> exp(Rest, N + 1); +exp(<<$1, Rest/binary>>, N) -> exp(Rest, N + 1); +exp(<<$2, Rest/binary>>, N) -> exp(Rest, N + 1); +exp(<<$3, Rest/binary>>, N) -> exp(Rest, N + 1); +exp(<<$4, Rest/binary>>, N) -> exp(Rest, N + 1); +exp(<<$5, Rest/binary>>, N) -> exp(Rest, N + 1); +exp(<<$6, Rest/binary>>, N) -> exp(Rest, N + 1); +exp(<<$7, Rest/binary>>, N) -> exp(Rest, N + 1); +exp(<<$8, Rest/binary>>, N) -> exp(Rest, N + 1); +exp(<<$9, Rest/binary>>, N) -> exp(Rest, N + 1); +exp(<<>>, N) -> {exp, N}; +exp(_, N) -> {finish_float, N}. + + +finish_number(Rest, Handler, Acc, Stack, Config) -> + maybe_done(Rest, handle_event(format_number(Acc), Handler, Config), Stack, Config). + +format_number({integer, Acc}) -> {integer, binary_to_integer(Acc)}; +format_number({float, Acc}) -> {float, binary_to_float(Acc)}. + +true(<<$r, $u, $e, Rest/binary>>, Handler, Stack, Config) -> + maybe_done(Rest, handle_event({literal, true}, Handler, Config), Stack, Config); +true(<<$r, $u>>, Handler, Stack, Config) -> + incomplete(true, <<$r, $u>>, Handler, Stack, Config); +true(<<$r>>, Handler, Stack, Config) -> + incomplete(true, <<$r>>, Handler, Stack, Config); +true(<<>>, Handler, Stack, Config) -> + incomplete(true, <<>>, Handler, Stack, Config); +true(Bin, Handler, Stack, Config) -> + ?error(true, Bin, Handler, Stack, Config). + + +false(<<$a, $l, $s, $e, Rest/binary>>, Handler, Stack, Config) -> + maybe_done(Rest, handle_event({literal, false}, Handler, Config), Stack, Config); +false(<<$a, $l, $s>>, Handler, Stack, Config) -> + incomplete(false, <<$a, $l, $s>>, Handler, Stack, Config); +false(<<$a, $l>>, Handler, Stack, Config) -> + incomplete(false, <<$a, $l>>, Handler, Stack, Config); +false(<<$a>>, Handler, Stack, Config) -> + incomplete(false, <<$a>>, Handler, Stack, Config); +false(<<>>, Handler, Stack, Config) -> + incomplete(false, <<>>, Handler, Stack, Config); +false(Bin, Handler, Stack, Config) -> + ?error(false, Bin, Handler, Stack, Config). + + +null(<<$u, $l, $l, Rest/binary>>, Handler, Stack, Config) -> + maybe_done(Rest, handle_event({literal, null}, Handler, Config), Stack, Config); +null(<<$u, $l>>, Handler, Stack, Config) -> + incomplete(null, <<$u, $l>>, Handler, Stack, Config); +null(<<$u>>, Handler, Stack, Config) -> + incomplete(null, <<$u>>, Handler, Stack, Config); +null(<<>>, Handler, Stack, Config) -> + incomplete(null, <<>>, Handler, Stack, Config); +null(Bin, Handler, Stack, Config) -> + ?error(null, Bin, Handler, Stack, Config). + + +comment(<>, Handler, Resume, [comment|Stack], Config) -> + resume(Rest, Resume, Handler, unused, Stack, Config); +comment(<>, Handler, Resume, Stack, Config) -> + comment(Rest, Handler, Resume, [multicomment|Stack], Config); +comment(<>, Handler, Resume, [multicomment|_] = Stack, Config) -> + incomplete(comment, <>, Handler, Resume, Stack, Config); +comment(<>, Handler, Resume, [multicomment|Stack], Config) -> + case Stack of + [multicomment|_] -> comment(Rest, Handler, Resume, Stack, Config); + _ -> resume(Rest, Resume, Handler, unused, Stack, Config) + end; +comment(<>, Handler, Resume, [multicomment|_] = Stack, Config) -> + incomplete(comment, <>, Handler, Resume, Stack, Config); +comment(<<_/utf8, Rest/binary>>, Handler, Resume, Stack, Config) -> + comment(Rest, Handler, Resume, Stack, Config); +comment(<<_, Rest/binary>>, Handler, Resume, Stack, Config=#config{strict_utf8=false}) -> + comment(Rest, Handler, Resume, Stack, Config); +comment(<<>>, Handler, done, [Comment], Config=#config{stream=false}) + when Comment == comment; Comment == multicomment -> + resume(<<>>, done, Handler, unused, [], Config); +comment(<<>>, Handler, Resume, Stack, Config) -> + incomplete(comment, <<>>, Handler, Resume, Stack, Config); +comment(Bin, Handler, Resume, Stack, Config) -> + ?error(comment, Bin, Handler, Resume, Stack, Config). + + +maybe_done(<>, Handler, [], Config) -> + done(Rest, handle_event(end_json, Handler, Config), [], Config); +maybe_done(<>, Handler, Stack, Config) -> + maybe_done(Rest, Handler, Stack, Config); +maybe_done(<>, Handler, [object|Stack], Config) -> + maybe_done(Rest, handle_event(end_object, Handler, Config), Stack, Config); +maybe_done(<>, Handler, [array|Stack], Config) -> + maybe_done(Rest, handle_event(end_array, Handler, Config), Stack, Config); +maybe_done(<>, Handler, [object|Stack], Config) -> + key(Rest, Handler, [key|Stack], Config); +maybe_done(<>, Handler, [array|_] = Stack, Config) -> + value(Rest, Handler, Stack, Config); +maybe_done(<>, Handler, Stack, Config) -> + maybe_done(Rest, Handler, Stack, Config); +maybe_done(<>, Handler, Stack, Config) -> + maybe_done(Rest, Handler, Stack, Config); +maybe_done(<>, Handler, Stack, Config) -> + maybe_done(Rest, Handler, Stack, Config); +maybe_done(<>, Handler, Stack, Config=#config{strict_comments=true}) -> + ?error(maybe_done, <>, Handler, Stack, Config); +maybe_done(<>, Handler, Stack, Config) -> + comment(Rest, Handler, maybe_done, [comment|Stack], Config); +maybe_done(<>, Handler, Stack, Config) -> + comment(Rest, Handler, maybe_done, [multicomment|Stack], Config); +maybe_done(<>, Handler, Stack, Config) -> + incomplete(maybe_done, <>, Handler, Stack, Config); +maybe_done(<<>>, Handler, Stack, Config) when length(Stack) > 0 -> + incomplete(maybe_done, <<>>, Handler, Stack, Config); +maybe_done(Bin, Handler, Stack, Config) -> + ?error(maybe_done, Bin, Handler, Stack, Config). + + +done(<>, Handler, [], Config) -> + done(Rest, Handler, [], Config); +done(<>, Handler, [], Config) -> + done(Rest, Handler, [], Config); +done(<>, Handler, [], Config) -> + done(Rest, Handler, [], Config); +done(<>, Handler, [], Config) -> + done(Rest, Handler, [], Config); +done(<>, Handler, Stack, Config=#config{strict_comments=true}) -> + ?error(done, <>, Handler, Stack, Config); +done(<>, Handler, Stack, Config) -> + comment(Rest, Handler, done, [comment|Stack], Config); +done(<>, Handler, Stack, Config) -> + comment(Rest, Handler, done, [multicomment|Stack], Config); +done(<>, Handler, Stack, Config) -> + incomplete(done, <>, Handler, Stack, Config); +done(Bin, {_Handler, State}, _Stack, #config{return_tail=true}) -> + {with_tail,State, Bin}; +done(<<>>, {Handler, State}, [], Config=#config{stream=true}) -> + incomplete(done, <<>>, {Handler, State}, [], Config); +done(<<>>, {_Handler, State}, [], _Config) -> State; +done(Bin, {Handler, State}, _Stack, Config=#config{multi_term=true}) -> + value(Bin, {Handler, Handler:reset(State)}, [], Config); +done(Bin, Handler, Stack, Config) -> ?error(done, Bin, Handler, Stack, Config). + + + +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). + + +json_to_bytes(JSON) -> json_to_bytes(JSON, []). + +json_to_bytes(<<>>, Acc) -> [<<>>] ++ lists:reverse(Acc); +json_to_bytes(<>, Acc) -> json_to_bytes(Rest, [<>] ++ Acc). + + +decode(JSON) -> decode(JSON, []). +decode(JSON, Config) -> (decoder(jsx, [], Config))(JSON). + + +incremental_decode(JSON) -> incremental_decode(JSON, []). +incremental_decode(JSON, Config) -> + Final = lists:foldl( + fun(Byte, Decoder) -> {incomplete, F} = Decoder(Byte), F end, + decoder(jsx, [], [stream] ++ Config), + json_to_bytes(JSON) + ), + Final(end_stream). + + +%% all these numbers have different representation in erlang than in javascript and +%% do not roundtrip like most integers/floats +special_number_test_() -> + Cases = [ + % {title, test form, json, opt flags} + {"-0", [{integer, 0}, end_json], <<"-0">>}, + {"-0.0", [{float, 0.0}, end_json], <<"-0.0">>}, + {"0e0", [{float, 0.0}, end_json], <<"0e0">>}, + {"0e4", [{float, 0.0}, end_json], <<"0e4">>}, + {"1e0", [{float, 1.0}, end_json], <<"1e0">>}, + {"-1e0", [{float, -1.0}, end_json], <<"-1e0">>}, + {"-0e0", [{float, -0.0}, end_json], <<"-0e0">>}, + {"1e4", [{float, 1.0e4}, end_json], <<"1e4">>}, + {"number terminated by whitespace", + [start_array, {integer, 1}, end_array, end_json], + <<"[ 1 ]">> + }, + {"number terminated by comma", + [start_array, {integer, 1}, {integer, 1}, end_array, end_json], + <<"[ 1, 1 ]">> + }, + {"number terminated by comma in object", + [start_object, {key, <<"x">>}, {integer, 1}, {key, <<"y">>}, {integer, 1}, end_object, end_json], + <<"{\"x\": 1, \"y\": 1}">> + } + ], + [{Title, ?_assertEqual(Events, decode(JSON))} + || {Title, Events, JSON} <- Cases + ] ++ + [{Title ++ " (incremental)", ?_assertEqual(Events, incremental_decode(JSON))} + || {Title, Events, JSON} <- Cases + ]. + + +comments_test_() -> + Cases = [ + % {title, test form, json, opt flags} + {"preceeding // comment", + [start_array, end_array, end_json], + <<"// comment ", ?newline, "[]">> + }, + {"preceeding /**/ comment", + [start_array, end_array, end_json], + <<"/* comment */[]">> + }, + {"trailing // comment", + [start_array, end_array, end_json], + <<"[]// comment", ?newline>> + }, + {"trailing // comment (no newline)", + [start_array, end_array, end_json], + <<"[]// comment">> + }, + {"trailing /**/ comment", + [start_array, end_array, end_json], + <<"[] /* comment */">> + }, + {"// comment inside array", + [start_array, end_array, end_json], + <<"[ // comment", ?newline, "]">> + }, + {"/**/ comment inside array", + [start_array, end_array, end_json], + <<"[ /* comment */ ]">> + }, + {"// comment at beginning of array", + [start_array, {literal, true}, end_array, end_json], + <<"[ // comment", ?newline, "true", ?newline, "]">> + }, + {"/**/ comment at beginning of array", + [start_array, {literal, true}, end_array, end_json], + <<"[ /* comment */ true ]">> + }, + {"// comment at end of array", + [start_array, {literal, true}, end_array, end_json], + <<"[ true // comment", ?newline, "]">> + }, + {"/**/ comment at end of array", + [start_array, {literal, true}, end_array, end_json], + <<"[ true /* comment */ ]">> + }, + {"// comment midarray (post comma)", + [start_array, {literal, true}, {literal, false}, end_array, end_json], + <<"[ true, // comment", ?newline, "false ]">> + }, + {"/**/ comment midarray (post comma)", + [start_array, {literal, true}, {literal, false}, end_array, end_json], + <<"[ true, /* comment */ false ]">> + }, + {"// comment midarray (pre comma)", + [start_array, {literal, true}, {literal, false}, end_array, end_json], + <<"[ true// comment", ?newline, ", false ]">> + }, + {"/**/ comment midarray (pre comma)", + [start_array, {literal, true}, {literal, false}, end_array, end_json], + <<"[ true/* comment */, false ]">> + }, + {"// comment inside object", + [start_object, end_object, end_json], + <<"{ // comment", ?newline, "}">> + }, + {"/**/ comment inside object", + [start_object, end_object, end_json], + <<"{ /* comment */ }">> + }, + {"// comment at beginning of object", + [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], + <<"{ // comment", ?newline, " \"key\": true", ?newline, "}">> + }, + {"/**/ comment at beginning of object", + [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], + <<"{ /* comment */ \"key\": true }">> + }, + {"// comment at end of object", + [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], + <<"{ \"key\": true // comment", ?newline, "}">> + }, + {"/**/ comment at end of object", + [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], + <<"{ \"key\": true /* comment */ }">> + }, + {"// comment midobject (post comma)", + [ + start_object, + {key, <<"x">>}, + {literal, true}, + {key, <<"y">>}, + {literal, false}, + end_object, + end_json + ], + <<"{ \"x\": true, // comment", ?newline, "\"y\": false }">> + }, + {"/**/ comment midobject (post comma)", + [ + start_object, + {key, <<"x">>}, + {literal, true}, + {key, <<"y">>}, + {literal, false}, + end_object, + end_json + ], + <<"{ \"x\": true, /* comment */", ?newline, "\"y\": false }">> + }, + {"// comment midobject (pre comma)", + [ + start_object, + {key, <<"x">>}, + {literal, true}, + {key, <<"y">>}, + {literal, false}, + end_object, + end_json + ], + <<"{ \"x\": true// comment", ?newline, ", \"y\": false }">> + }, + {"/**/ comment midobject (pre comma)", + [ + start_object, + {key, <<"x">>}, + {literal, true}, + {key, <<"y">>}, + {literal, false}, + end_object, + end_json + ], + <<"{ \"x\": true/* comment */", ?newline, ", \"y\": false }">> + }, + {"// comment precolon", + [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], + <<"{ \"key\" // comment", ?newline, ": true }">> + }, + {"/**/ comment precolon", + [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], + <<"{ \"key\"/* comment */: true }">> + }, + {"// comment postcolon", + [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], + <<"{ \"key\": // comment", ?newline, " true }">> + }, + {"/**/ comment postcolon", + [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], + <<"{ \"key\":/* comment */ true }">> + }, + {"// comment terminating zero", + [start_array, {integer, 0}, end_array, end_json], + <<"[ 0// comment", ?newline, "]">> + }, + {"// comment terminating integer", + [start_array, {integer, 1}, end_array, end_json], + <<"[ 1// comment", ?newline, "]">> + }, + {"// comment terminating float", + [start_array, {float, 1.0}, end_array, end_json], + <<"[ 1.0// comment", ?newline, "]">> + }, + {"// comment terminating exp", + [start_array, {float, 1.0e1}, end_array, end_json], + <<"[ 1e1// comment", ?newline, "]">> + }, + {"/**/ comment terminating zero", + [start_array, {integer, 0}, end_array, end_json], + <<"[ 0/* comment */ ]">> + }, + {"/**/ comment terminating integer", + [start_array, {integer, 1}, end_array, end_json], + <<"[ 1/* comment */ ]">> + }, + {"/**/ comment terminating float", + [start_array, {float, 1.0}, end_array, end_json], + <<"[ 1.0/* comment */ ]">> + }, + {"/**/ comment terminating exp", + [start_array, {float, 1.0e1}, end_array, end_json], + <<"[ 1e1/* comment */ ]">> + }, + {"/**/ comment following /**/ comment", + [start_array, {literal, true}, end_array, end_json], + <<"[/* comment *//* comment */true]">> + }, + {"/**/ comment following // comment", + [start_array, {literal, true}, end_array, end_json], + <<"[// comment", ?newline, "/* comment */true]">> + }, + {"// comment following /**/ comment", + [start_array, {literal, true}, end_array, end_json], + <<"[/* comment */// comment", ?newline, "true]">> + }, + {"// comment following // comment", + [start_array, {literal, true}, end_array, end_json], + <<"[// comment", ?newline, "// comment", ?newline, "true]">> + }, + {"/**/ comment inside /**/ comment", + [start_array, {literal, true}, end_array, end_json], + <<"[ /* /* comment */ */ true ]">> + }, + {"/**/ comment with /", + [start_array, {literal, true}, end_array, end_json], + <<"[ /* / */ true ]">> + }, + {"/**/ comment with *", + [start_array, {literal, true}, end_array, end_json], + <<"[ /* * */ true ]">> + }, + {"// comment with badutf", + [start_array, {literal, true}, end_array, end_json], + <<"[ // comment ", 16#00c0, " ", ?newline, "true]">> + }, + {"/**/ comment with badutf", + [start_array, {literal, true}, end_array, end_json], + <<"[ /* comment ", 16#00c0, " */ true]">> + }, + {"/**/ comment with badutf preceeded by /", + [start_array, {literal, true}, end_array, end_json], + <<"[ /* comment /", 16#00c0, " */ true]">> + } + ], + [{Title, ?_assertEqual(Events, decode(JSON))} + || {Title, Events, JSON} <- Cases + ] ++ + [{Title ++ " (incremental)", ?_assertEqual(Events, incremental_decode(JSON))} + || {Title, Events, JSON} <- Cases + ] ++ + % error when `{strict, [comments]}` is present + [{Title, ?_assertError(badarg, decode(JSON, [{strict, [comments]}]))} + || {Title, _Events, JSON} <- Cases + ] ++ + [{Title ++ " (incremental)", ?_assertError( + badarg, + incremental_decode(JSON, [{strict, [comments]}]) + )} || {Title, _Events, JSON} <- Cases + ]. + + +no_comments_test_() -> + Cases = [ + {"// comment with badutf", + badarg, + <<"[ // comment ", 16#00c0, " ", ?newline, "true]">>, + [{strict, [utf8]}] + }, + {"/**/ comment with badutf", + badarg, + <<"[ /* comment ", 16#00c0, " */ true]">>, + [{strict, [utf8]}] + }, + {"/**/ comment with badutf preceeded by /", + badarg, + <<"[ /* comment /", 16#00c0, " */ true]">>, + [{strict, [utf8]}] + } + ], + [{Title, ?_assertError(Error, decode(JSON, Config))} + || {Title, Error, JSON, Config} <- Cases + ] ++ + [{Title ++ " (incremental)", ?_assertError(Error, incremental_decode(JSON, Config))} + || {Title, Error, JSON, Config} <- Cases + ]. + + +% doing the full unicode range takes foreverrrrrrr so just do boundaries +% excludes characters that may need escaping +codepoints() -> + lists:seq(0, 32) ++ + [32, 33] ++ + lists:seq(35, 46) ++ + lists:seq(48, 91) ++ + lists:seq(93, 127) ++ + [16#2027, 16#202a, 16#d7ff, 16#e000] ++ + lists:seq(16#fdd0, 16#ffff) ++ + [16#10000, 16#20000, 16#30000, 16#40000, 16#50000] ++ + [16#60000, 16#70000, 16#80000, 16#90000, 16#a0000, 16#b0000] ++ + [16#c0000, 16#d0000, 16#e0000, 16#f0000, 16#100000]. + + +surrogates() -> lists:seq(16#d800, 16#dfff). + + +%% erlang refuses to decode certain codepoints, so fake them all +to_fake_utf8(N) when N < 16#0080 -> <<34/utf8, N:8, 34/utf8>>; +to_fake_utf8(N) when N < 16#0800 -> + <<0:5, Y:5, X:6>> = <>, + <<34/utf8, 2#110:3, Y:5, 2#10:2, X:6, 34/utf8>>; +to_fake_utf8(N) when N < 16#10000 -> + <> = <>, + <<34/utf8, 2#1110:4, Z:4, 2#10:2, Y:6, 2#10:2, X:6, 34/utf8>>; +to_fake_utf8(N) -> + <<0:3, W:3, Z:6, Y:6, X:6>> = <>, + <<34/utf8, 2#11110:5, W:3, 2#10:2, Z:6, 2#10:2, Y:6, 2#10:2, X:6, 34/utf8>>. + + +clean_string_test_() -> + Clean = codepoints(), + Dirty = surrogates(), + % clean codepoints + [{"clean u+" ++ integer_to_list(Codepoint, 16), ?_assertEqual( + [{string, <>}, end_json], + decode(<<34/utf8, Codepoint/utf8, 34/utf8>>) + )} || Codepoint <- Clean + ] ++ + % bad codepoints replaced by u+FFFD + [{"clean u+" ++ integer_to_list(Codepoint, 16), ?_assertEqual( + [{string, <<16#fffd/utf8>>}, end_json], + decode(to_fake_utf8(Codepoint)) + )} || Codepoint <- Dirty + ] ++ + % bad codepoints that cause errors + [{"dirty u+" ++ integer_to_list(Codepoint, 16), ?_assertError( + badarg, + decode(to_fake_utf8(Codepoint), [{strict, [utf8]}]) + )} || Codepoint <- Dirty + ]. + + +dirty_string_test_() -> + Cases = [ + {"dirty \\n", + [start_array, {string, <<"\\n">>}, end_array, end_json], + <<"[\"\\n\"]">>, + [dirty_strings] + }, + {"dirty \\uwxyz", + [start_array, {string, <<"\\uwxyz">>}, end_array, end_json], + <<"[\"\\uwxyz\"]">>, + [dirty_strings] + }, + {"dirty \\x23", + [start_array, {string, <<"\\x23">>}, end_array, end_json], + <<"[\"\\x23\"]">>, + [dirty_strings] + }, + {"dirty 0", + [start_array, {string, <<0>>}, end_array, end_json], + <<"[\"", 0, "\"]">>, + [dirty_strings] + }, + {"dirty 0\\\"0", + [start_array, {string, <<0, ?rsolidus, ?doublequote, 0>>}, end_array, end_json], + <<"[\"", 0, ?rsolidus, ?doublequote, 0, "\"]">>, + [dirty_strings] + }, + {"dirty 0\\\\\"0", + [start_array, {string, <<0, ?rsolidus, ?rsolidus, ?doublequote, 0>>}, end_array, end_json], + <<"[\"", 0, ?rsolidus, ?rsolidus, ?doublequote, 0, "\"]">>, + [dirty_strings] + }, + {"dirty 16#d800", + [start_array, {string, <<237, 160, 128>>}, end_array, end_json], + <<"[\"", 237, 160, 128, "\"]">>, + [dirty_strings] + }, + {"dirty /", + [start_array, {string, <<$/>>}, end_array, end_json], + <<"[\"", $/, "\"]">>, + [dirty_strings, escaped_forward_slashes] + }, + {"dirty <<194, 129>>", + [start_array, {string, <<194, 129>>}, end_array, end_json], + <<"[\"", 194, 129, "\"]">>, + [dirty_strings] + } + ], + [{Title, ?_assertEqual(Events, decode(JSON, Config))} + || {Title, Events, JSON, Config} <- Cases + ] ++ + % ensure `dirty_strings` and `strict` interact properly + [{Title, ?_assertEqual(Events, decode(JSON, Config ++ [strict]))} + || {Title, Events, JSON, Config} <- Cases + ] ++ + [{Title ++ " (incremental)", ?_assertEqual(Events, incremental_decode(JSON, Config))} + || {Title, Events, JSON, Config} <- Cases + ]. + + +bad_utf8_test_() -> + Cases = [ + {"orphan continuation byte u+0080", <<16#fffd/utf8>>, <<16#0080>>}, + {"orphan continuation byte u+00bf", <<16#fffd/utf8>>, <<16#00bf>>}, + {"2 continuation bytes", + binary:copy(<<16#fffd/utf8>>, 2), + <<(binary:copy(<<16#0080>>, 2))/binary>> + }, + {"3 continuation bytes", + binary:copy(<<16#fffd/utf8>>, 3), + <<(binary:copy(<<16#0080>>, 3))/binary>> + }, + {"4 continuation bytes", + binary:copy(<<16#fffd/utf8>>, 4), + <<(binary:copy(<<16#0080>>, 4))/binary>> + }, + {"5 continuation bytes", + binary:copy(<<16#fffd/utf8>>, 5), + <<(binary:copy(<<16#0080>>, 5))/binary>> + }, + {"6 continuation bytes", + binary:copy(<<16#fffd/utf8>>, 6), + <<(binary:copy(<<16#0080>>, 6))/binary>> + }, + {"all continuation bytes", + binary:copy(<<16#fffd/utf8>>, length(lists:seq(16#0080, 16#00bf))), + <<(list_to_binary(lists:seq(16#0080, 16#00bf)))/binary>> + }, + {"lonely start byte", <<16#fffd/utf8>>, <<16#00c0>>}, + {"lonely start bytes (2 byte)", + <<16#fffd/utf8, 32, 16#fffd/utf8>>, + <<16#00c0, 32, 16#00df>> + }, + {"lonely start bytes (3 byte)", + <<16#fffd/utf8, 32, 16#fffd/utf8>>, + <<16#00e0, 32, 16#00ef>> + }, + {"lonely start bytes (4 byte)", + <<16#fffd/utf8, 32, 16#fffd/utf8>>, + <<16#00f0, 32, 16#00f7>> + }, + {"missing continuation byte (3 byte)", <<16#fffd/utf8, 32>>, <<224, 160, 32>>}, + {"missing continuation byte (4 byte missing one)", + <<16#fffd/utf8, 32>>, + <<240, 144, 128, 32>> + }, + {"missing continuation byte (4 byte missing two)", + <<16#fffd/utf8, 32>>, + <<240, 144, 32>> + }, + {"overlong encoding of u+002f (2 byte)", + <<16#fffd/utf8, 32>>, + <<16#c0, 16#af, 32>> + }, + {"overlong encoding of u+002f (3 byte)", + <<16#fffd/utf8, 32>>, + <<16#e0, 16#80, 16#af, 32>> + }, + {"overlong encoding of u+002f (4 byte)", + <<16#fffd/utf8, 32>>, + <<16#f0, 16#80, 16#80, 16#af, 32>> + }, + {"highest overlong 2 byte sequence", + <<16#fffd/utf8, 32>>, + <<16#c1, 16#bf, 32>> + }, + {"highest overlong 3 byte sequence", + <<16#fffd/utf8, 32>>, + <<16#e0, 16#9f, 16#bf, 32>> + }, + {"highest overlong 4 byte sequence", + <<16#fffd/utf8, 32>>, + <<16#f0, 16#8f, 16#bf, 16#bf, 32>> + } + ], + [{Title, ?_assertError( + badarg, + decode(<<34, JSON/binary, 34>>, [{strict, [utf8]}]) + )} || {Title, _, JSON} <- Cases + ] ++ + [{Title ++ " (incremental)", ?_assertError( + badarg, + incremental_decode(<<34, JSON/binary, 34>>, [{strict, [utf8]}]) + )} || {Title, _, JSON} <- Cases + ] ++ + [{Title ++ " replaced", ?_assertEqual( + [{string, Replacement}, end_json], + decode(<<34, JSON/binary, 34>>) + )} || {Title, Replacement, JSON} <- Cases + ] ++ + [{Title ++ " replaced (incremental)", ?_assertEqual( + [{string, Replacement}, end_json], + incremental_decode(<<34, JSON/binary, 34>>) + )} || {Title, Replacement, JSON} <- Cases + ]. + + +unescape_test_() -> + Cases = [ + {"unescape backspace", <<"\b">>, <<"\\b"/utf8>>}, + {"unescape tab", <<"\t">>, <<"\\t"/utf8>>}, + {"unescape newline", <<"\n">>, <<"\\n"/utf8>>}, + {"unescape formfeed", <<"\f">>, <<"\\f"/utf8>>}, + {"unescape carriage return", <<"\r">>, <<"\\r"/utf8>>}, + {"unescape quote", <<"\"">>, <<"\\\""/utf8>>}, + {"unescape solidus", <<"/">>, <<"\\/"/utf8>>}, + {"unescape reverse solidus", <<"\\">>, <<"\\\\"/utf8>>}, + {"unescape control", <<0>>, <<"\\u0000"/utf8>>}, + {"unescape surrogate pair", <<16#10000/utf8>>, <<"\\ud800\\udc00"/utf8>>}, + {"unescape surrogate pair", <<16#10000/utf8>>, <<"\\uD800\\uDC00"/utf8>>}, + {"replace bad high surrogate", <<16#fffd/utf8>>, <<"\\udc00"/utf8>>}, + {"replace bad high surrogate", <<16#fffd/utf8>>, <<"\\uDC00"/utf8>>}, + {"replace naked high surrogate", + <<16#fffd/utf8, "hello world">>, + <<"\\ud800hello world"/utf8>> + }, + {"replace naked high surrogate", + <<16#fffd/utf8, "hello world">>, + <<"\\uD800hello world"/utf8>> + }, + {"replace naked low surrogate", + <<16#fffd/utf8, "hello world">>, + <<"\\udc00hello world"/utf8>> + }, + {"replace naked low surrogate", + <<16#fffd/utf8, "hello world">>, + <<"\\uDC00hello world"/utf8>> + }, + {"replace bad surrogate pair", <<16#fffd/utf8, 16#fffd/utf8>>, <<"\\ud800\\u0000">>}, + {"replace bad surrogate pair", <<16#fffd/utf8, 16#fffd/utf8>>, <<"\\uD800\\u0000">>} + ], + [{Title, ?_assertEqual([{string, Escaped}, end_json], decode(<<34, JSON/binary, 34>>))} + || {Title, Escaped, JSON} <- Cases + ] ++ + [{Title ++ " (incremental)", ?_assertEqual( + [{string, Escaped}, end_json], + incremental_decode(<<34, JSON/binary, 34>>) + )} || {Title, Escaped, JSON} <- Cases + ]. + + +bad_escaped_surrogate_test_() -> + Cases = [ + {"do not unescape bad high surrogate", <<"\\udc00">>}, + {"do not unescape naked high surrogate", <<"\\ud800hello world">>}, + {"do not unescape naked low surrogate", <<"\\udc00hello world">>}, + {"do not unescape bad surrogate pair", <<"\\ud800\\u0000">>} + ], + [{Title, ?_assertError(badarg, decode(<<34, JSON/binary, 34>>, [{strict, [utf8]}]))} + || {Title, JSON} <- Cases + ]. + + +escape_test_() -> + Cases = [ + {"backspace", <<"\b">>, <<"\\b">>}, + {"tab", <<"\t">>, <<"\\t">>}, + {"newline", <<"\n">>, <<"\\n">>}, + {"formfeed", <<"\f">>, <<"\\f">>}, + {"carriage return", <<"\r">>, <<"\\r">>}, + {"quote", <<"\"">>, <<"\\\"">>}, + {"backslash", <<"\\">>, <<"\\\\">>}, + {"control", <<0>>, <<"\\u0000">>} + ], + [{"escape " ++ Title, ?_assertEqual( + [{string, Escaped}, end_json], + decode(<<34, Escaped/binary, 34>>, [escaped_strings]) + )} || {Title, _Unescaped, Escaped} <- Cases + ] ++ + [{"do not escape " ++ Title, ?_assertEqual( + [{string, Unescaped}, end_json], + decode(<<34, Escaped/binary, 34>>) + )} || {Title, Unescaped, Escaped} <- Cases + ]. + + +special_escape_test_() -> + Cases = [ + {"escape forward slash", <<"\\/">>, <<"/"/utf8>>, [escaped_forward_slashes]}, + {"do not escape forward slash", <<"/">>, <<"/"/utf8>>, []}, + {"escape jsonp", <<"\\u2028">>, <<16#2028/utf8>>, []}, + {"do not escape jsonp", <<16#2028/utf8>>, <<16#2028/utf8>>, [unescaped_jsonp]} + ], + [{Title, ?_assertEqual( + [{string, Expect}, end_json], + decode(<<34, Raw/binary, 34>>, [escaped_strings] ++ Config) + )} || {Title, Expect, Raw, Config} <- Cases + ]. + + +uescape_test_() -> + [ + {"\"\\u0080\"", ?_assertEqual( + [{string, <<"\\u0080">>}, end_json], + decode(<<34, 128/utf8, 34>>, [uescape]) + )}, + {"\"\\u8ca8\\u5481\\u3002\\u0091\\u0091\"", ?_assertEqual( + [{string, <<"\\u8ca8\\u5481\\u3002\\u0091\\u0091">>}, end_json], + decode( + <<34,232,178,168,229,146,129,227,128,130,194,145,194,145,34>>, + [uescape] + ) + )}, + {"\"\\ud834\\udd1e\"", ?_assertEqual( + [{string, <<"\\ud834\\udd1e">>}, end_json], + decode(<<34, 240, 157, 132, 158, 34>>, [uescape]) + )}, + {"\"\\ud83d\\ude0a\"", ?_assertEqual( + [{string, <<"\\ud83d\\ude0a">>}, end_json], + decode(<<34, 240, 159, 152, 138, 34>>, [uescape]) + )} + ]. + + +single_quoted_string_test_() -> + Cases = [ + {"single quoted string", [{string, <<"hello world">>}, end_json], <<39, "hello world", 39>>}, + {"single quoted string with embedded double quotes", + [{string, <<"quoth the raven, \"nevermore\"">>}, end_json], + <<39, "quoth the raven, \"nevermore\"", 39>> + }, + {"escaped single quote", + [{string, <<"quoth the raven, 'nevermore'">>}, end_json], + <<39, "quoth the raven, \\'nevermore\\'", 39>> + }, + {"single quoted key", + [start_object, + {key, <<"key">>}, {string, <<"value">>}, + {key, <<"another key">>}, {string, <<"another value">>}, + end_object, end_json], + <<"{'key':'value','another key':'another value'}">> + } + ], + [{Title, ?_assertEqual(Expect, decode(Raw, []))} || {Title, Expect, Raw} <- Cases] ++ + [{Title, ?_assertError( + badarg, + decode(Raw, [{strict, [single_quotes]}]) + )} || {Title, _Expect, Raw} <- Cases + ]. + + +embedded_single_quoted_string_test_() -> + [ + {"string with embedded single quotes", ?_assertEqual( + [{string, <<"quoth the raven, 'nevermore'">>}, end_json], + decode(<<34, "quoth the raven, 'nevermore'", 34>>, []) + )}, + {"string with embedded single quotes", ?_assertEqual( + [{string, <<"quoth the raven, 'nevermore'">>}, end_json], + decode(<<34, "quoth the raven, 'nevermore'", 34>>, [{strict, [single_quotes]}]) + )} + ]. + + +ignored_bad_escapes_test_() -> + [ + {"ignore unrecognized escape sequence", ?_assertEqual( + [{string, <<"\\x25">>}, end_json], + decode(<<"\"\\x25\"">>, []) + )} + ]. + + +bom_test_() -> + [ + {"bom", ?_assertEqual( + [start_array, end_array, end_json], + decode(<<16#ef, 16#bb, 16#bf, "[]"/utf8>>, []) + )} + ]. + + +trailing_comma_test_() -> + [ + {"trailing comma in object", ?_assertEqual( + [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], + decode(<<"{\"key\": true,}">>, []) + )}, + {"strict trailing comma in object", ?_assertError( + badarg, + decode(<<"{\"key\": true,}">>, [{strict, [trailing_commas]}]) + )}, + {"two trailing commas in object", ?_assertError( + badarg, + decode(<<"{\"key\": true,,}">>, []) + )}, + {"comma in empty object", ?_assertError( + badarg, + decode(<<"{,}">>, []) + )}, + {"trailing comma in list", ?_assertEqual( + [start_array, {literal, true}, end_array, end_json], + decode(<<"[true,]">>, []) + )}, + {"strict trailing comma in list", ?_assertError( + badarg, + decode(<<"[true,]">>, [{strict, [trailing_commas]}]) + )}, + {"two trailing commas in list", ?_assertError( + badarg, + decode(<<"[true,,]">>, []) + )}, + {"comma in empty list", ?_assertError( + badarg, + decode(<<"[,]">>, []) + )} + ]. + + +incomplete_test_() -> + [ + {"stream false", ?_assertError( + badarg, + decode(<<"{">>) + )}, + {"stream true", ?_assertMatch( + {incomplete, _}, + decode(<<"{">>, [stream]) + )}, + {"complete input", ?_assertMatch( + {incomplete, _}, + decode(<<"{}">>, [stream]) + )} + ]. + + +error_test_() -> + Cases = [ + {"maybe_bom error", <<16#ef, 0>>}, + {"definitely_bom error", <<16#ef, 16#bb, 0>>}, + {"object error", <<"{"/utf8, 0>>}, + {"colon error", <<"{\"\""/utf8, 0>>}, + {"key error", <<"{\"\":1,"/utf8, 0>>}, + {"value error", <<0>>}, + {"negative error", <<"-"/utf8, 0>>}, + {"zero error", <<"0"/utf8, 0>>}, + {"integer error", <<"1"/utf8, 0>>}, + {"decimal error", <<"1.0"/utf8, 0>>}, + {"e error", <<"1e"/utf8, 0>>}, + {"ex error", <<"1e+"/utf8, 0>>}, + {"exp error", <<"1e1"/utf8, 0>>}, + {"exp error", <<"1.0e1"/utf8, 0>>}, + {"exp error", <<"1.e"/utf8>>}, + {"true error", <<"tru"/utf8, 0>>}, + {"false error", <<"fals"/utf8, 0>>}, + {"null error", <<"nul"/utf8, 0>>}, + {"maybe_done error", <<"[[]"/utf8, 0>>}, + {"done error", <<"[]"/utf8, 0>>} + ], + [{Title, ?_assertError(badarg, decode(State))} || {Title, State} <- Cases]. + + +custom_incomplete_handler_test_() -> + [ + {"custom incomplete handler", ?_assertError( + incomplete, + decode(<<>>, [{incomplete_handler, fun(_, _, _) -> erlang:error(incomplete) end}, stream]) + )} + ]. + + +return_tail_test_() -> + [ + {"return_tail with tail", ?_assertEqual( + {with_tail,#{},<<"3">>}, + jsx:decode(<<"{} 3">>, [return_tail]) + )}, + {"return_tail without tail", ?_assertEqual( + {with_tail,#{},<<"">>}, + jsx:decode(<<"{}">>, [return_tail]) + )}, + {"return_tail with trimmed whitespace", ?_assertEqual( + {with_tail,#{},<<"">>}, + jsx:decode(<<"{} ">>, [return_tail]) + )}, + {"return_tail and streaming", ?_assertEqual( + {with_tail,#{},<<"3">>}, + begin + {incomplete, F} = jsx:decode(<<"{">>, [return_tail, stream]), + F(<<"} 3">>) + end + )}, + {"return_tail and streaming", ?_assertEqual( + {with_tail,#{},<<"">>}, + begin + %% In case of infinite stream of objects a user does not know + %% when to call F(end_stream). + %% So, return_tail overwrites conservative stream end. + %% This means that we don't need to call end_stream explicitly. + {incomplete, F} = jsx:decode(<<"{">>, [return_tail, stream]), + F(<<"}">>) + end + )} + ]. + +-endif. diff --git a/deps/jsx/src/jsx_encoder.erl b/deps/jsx/src/jsx_encoder.erl new file mode 100644 index 0000000000000000000000000000000000000000..a1242a79745202327270d297e536335108b420f3 --- /dev/null +++ b/deps/jsx/src/jsx_encoder.erl @@ -0,0 +1,116 @@ +%% The MIT License + +%% Copyright (c) 2010-2013 Alisdair Sullivan + +%% Permission is hereby granted, free of charge, to any person obtaining a copy +%% of this software and associated documentation files (the "Software"), to deal +%% in the Software without restriction, including without limitation the rights +%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +%% copies of the Software, and to permit persons to whom the Software is +%% furnished to do so, subject to the following conditions: + +%% The above copyright notice and this permission notice shall be included in +%% all copies or substantial portions of the Software. + +%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +%% THE SOFTWARE. + + +-module(jsx_encoder). + +-export([encoder/3, encode/1, encode/2]). + +-spec encoder(Handler::module(), State::any(), Config::jsx_config:options()) -> jsx:encoder(). + +encoder(Handler, State, Config) -> + Parser = jsx:parser(Handler, State, Config), + fun(Term) -> Parser(encode(Term) ++ [end_json]) end. + + +-spec encode(Term::any()) -> [any(), ...]. + +encode(Term) -> encode(Term, ?MODULE). + + +-spec encode(Term::any(), EntryPoint::module()) -> [any(), ...]. + +encode(Map, _EntryPoint) when is_map(Map), map_size(Map) < 1 -> + [start_object, end_object]; +encode(Term, EntryPoint) when is_map(Term) -> + [start_object] ++ unpack(Term, EntryPoint); +encode(Term, EntryPoint) -> encode_(Term, EntryPoint). + +encode_([], _EntryPoint) -> [start_array, end_array]; +encode_([{}], _EntryPoint) -> [start_object, end_object]; + +%% datetime special case +encode_([{{_,_,_},{_,_,_}} = DateTime|Rest], EntryPoint) -> + [start_array] ++ [DateTime] ++ unhitch(Rest, EntryPoint); +encode_([{_, _}|_] = Term, EntryPoint) -> + [start_object] ++ unzip(Term, EntryPoint); +encode_(Term, EntryPoint) when is_list(Term) -> + [start_array] ++ unhitch(Term, EntryPoint); + +encode_(Else, _EntryPoint) -> [Else]. + + +unzip([{K, V}|Rest], EntryPoint) when is_integer(K); is_binary(K); is_atom(K) -> + [K] ++ EntryPoint:encode(V, EntryPoint) ++ unzip(Rest, EntryPoint); +unzip([], _) -> [end_object]; +unzip(_, _) -> erlang:error(badarg). + + +unhitch([V|Rest], EntryPoint) -> + EntryPoint:encode(V, EntryPoint) ++ unhitch(Rest, EntryPoint); +unhitch([], _) -> [end_array]. + +unpack(Map, EntryPoint) -> unpack(Map, maps:keys(Map), EntryPoint). + +unpack(Map, [K|Rest], EntryPoint) when is_integer(K); is_binary(K); is_atom(K) -> + [K] ++ EntryPoint:encode(maps:get(K, Map), EntryPoint) ++ unpack(Map, Rest, EntryPoint); +unpack(_, [], _) -> [end_object]. + +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). + + +parser(Term, Opts) -> (jsx:parser(jsx, [], Opts))(Term). + + +error_test_() -> + [ + {"value error", ?_assertError(badarg, parser(self(), []))}, + {"string error", ?_assertError(badarg, parser(<<239, 191, 191>>, [strict]))} + ]. + +custom_error_handler_test_() -> + Error = fun(Term, {_, State, _, _}, _) -> {State, Term} end, + [ + {"value error", ?_assertEqual( + {value, [self()]}, + parser(self(), [{error_handler, Error}]) + )}, + {"string error", ?_assertEqual( + {value, [{string, <<237, 160, 128>>}]}, + parser(<<237, 160, 128>>, [{error_handler, Error}, strict]) + )} + ]. + +improper_lists_test_() -> + [ + {"improper proplist", ?_assertError( + badarg, + encode([{<<"key">>, <<"value">>}, false]) + )}, + {"improper list", ?_assertError( + badarg, + encode([{literal, true}, false, null]) + )} + ]. + +-endif. diff --git a/deps/jsx/src/jsx_parser.erl b/deps/jsx/src/jsx_parser.erl new file mode 100644 index 0000000000000000000000000000000000000000..8506b0372c8e5dd7769610e38ee6024dbafdc4ed --- /dev/null +++ b/deps/jsx/src/jsx_parser.erl @@ -0,0 +1,1214 @@ +%% The MIT License + +%% Copyright (c) 2010-2013 Alisdair Sullivan + +%% Permission is hereby granted, free of charge, to any person obtaining a copy +%% of this software and associated documentation files (the "Software"), to deal +%% in the Software without restriction, including without limitation the rights +%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +%% copies of the Software, and to permit persons to whom the Software is +%% furnished to do so, subject to the following conditions: + +%% The above copyright notice and this permission notice shall be included in +%% all copies or substantial portions of the Software. + +%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +%% THE SOFTWARE. + + +-module(jsx_parser). + +-export([parser/3, resume/5]). +-export([init/1, handle_event/2]). + + +-spec parser(Handler::module(), State::any(), Config::jsx_config:options()) -> jsx:parser(). + +parser(Handler, State, Config) -> + fun(Tokens) -> value(Tokens, {Handler, Handler:init(State)}, [], jsx_config:parse_config(Config)) end. + + +%% resume allows continuation from interrupted decoding without having to explicitly export +%% all states +-spec resume( + Rest::jsx:token(), + State::atom(), + Handler::module(), + Stack::list(atom()), + Config::jsx:config() + ) -> jsx:parser() | {incomplete, jsx:parser()}. + +resume(Rest, State, Handler, Stack, Config) -> + case State of + value -> value(Rest, Handler, Stack, Config); + object -> object(Rest, Handler, Stack, Config); + array -> array(Rest, Handler, Stack, Config); + maybe_done -> maybe_done(Rest, Handler, Stack, Config); + done -> done(Rest, Handler, Stack, Config) + end. + + +-include("jsx_config.hrl"). + + +%% error, incomplete and event macros +-ifndef(error). +-define(error(State, Terms, Handler, Stack, Config), + case Config#config.error_handler of + false -> erlang:error(badarg); + F -> F(Terms, {parser, State, Handler, Stack}, jsx_config:config_to_list(Config)) + end + +). +-endif. + + +incomplete(State, Handler, Stack, Config=#config{stream=false}) -> + ?error(State, [], Handler, Stack, Config); +incomplete(State, Handler, Stack, Config=#config{incomplete_handler=false}) -> + {incomplete, fun(End) when End == end_stream; End == end_json -> + case resume([end_json], State, Handler, Stack, Config) of + {incomplete, _} -> ?error(State, [], Handler, Stack, Config); + Else -> Else + end; + (Tokens) -> + resume(Tokens, State, Handler, Stack, Config) + end + }; +incomplete(State, Handler, Stack, Config=#config{incomplete_handler=F}) -> + F([], {parser, State, Handler, Stack}, jsx_config:config_to_list(Config)). + + +handle_event(Event, {Handler, State}, _Config) -> {Handler, Handler:handle_event(Event, State)}. + + +value([String|Tokens], Handler, Stack, Config) when is_binary(String) -> + try clean_string(String, Config) of Clean -> + maybe_done(Tokens, handle_event({string, Clean}, Handler, Config), Stack, Config) + catch error:badarg -> + ?error(value, [{string, String}|Tokens], Handler, Stack, Config) + end; +value([true|Tokens], Handler, Stack, Config) -> + maybe_done(Tokens, handle_event({literal, true}, Handler, Config), Stack, Config); +value([false|Tokens], Handler, Stack, Config) -> + maybe_done(Tokens, handle_event({literal, false}, Handler, Config), Stack, Config); +value([null|Tokens], Handler, Stack, Config) -> + maybe_done(Tokens, handle_event({literal, null}, Handler, Config), Stack, Config); +value([start_object|Tokens], Handler, Stack, Config) -> + object(Tokens, handle_event(start_object, Handler, Config), [object|Stack], Config); +value([start_array|Tokens], Handler, Stack, Config) -> + array(Tokens, handle_event(start_array, Handler, Config), [array|Stack], Config); +value([Number|Tokens], Handler, Stack, Config) when is_integer(Number) -> + maybe_done(Tokens, handle_event({integer, Number}, Handler, Config), Stack, Config); +value([Number|Tokens], Handler, Stack, Config) when is_float(Number) -> + maybe_done(Tokens, handle_event({float, Number}, Handler, Config), Stack, Config); +value([{raw, Raw}|Tokens], Handler, Stack, Config) when is_binary(Raw) -> + value((jsx:decoder(?MODULE, [], []))(Raw) ++ Tokens, Handler, Stack, Config); +value([{_,_,_}=Timestamp|Tokens], Handler, Stack, Config) -> + {{Year, Month, Day}, {Hour, Min, Sec}} = calendar:now_to_datetime( + Timestamp), + value([{string, unicode:characters_to_binary(io_lib:format( + "~4.10.0B-~2.10.0B-~2.10.0BT~2.10.0B:~2.10.0B:~2.10.0BZ", + [Year, Month, Day, Hour, Min, Sec] + ))}|Tokens], + Handler, + Stack, + Config + ); +value([{{Year, Month, Day}, {Hour, Min, Sec}}|Tokens], Handler, Stack, Config) +when is_integer(Year), is_integer(Month), is_integer(Day), is_integer(Hour), is_integer(Min), is_integer(Sec) -> + value([{string, unicode:characters_to_binary(io_lib:format( + "~4.10.0B-~2.10.0B-~2.10.0BT~2.10.0B:~2.10.0B:~2.10.0BZ", + [Year, Month, Day, Hour, Min, Sec] + ))}|Tokens], + Handler, + Stack, + Config + ); +value([{{Year, Month, Day}, {Hour, Min, Sec}}|Tokens], Handler, Stack, Config) +when is_integer(Year), is_integer(Month), is_integer(Day), is_integer(Hour), is_integer(Min), is_float(Sec) -> + value([{string, unicode:characters_to_binary(io_lib:format( + "~4.10.0B-~2.10.0B-~2.10.0BT~2.10.0B:~2.10.0B:~9.6.0fZ", + [Year, Month, Day, Hour, Min, Sec] + ))}|Tokens], + Handler, + Stack, + Config + ); +value([{literal, Value}|Tokens], Handler, Stack, Config) +when Value == true; Value == false; Value == null -> + value([Value] ++ Tokens, Handler, Stack, Config); +value([{integer, Value}|Tokens], Handler, Stack, Config) +when is_integer(Value) -> + value([Value] ++ Tokens, Handler, Stack, Config); +value([{float, Value}|Tokens], Handler, Stack, Config) +when is_float(Value) -> + value([Value] ++ Tokens, Handler, Stack, Config); +value([{string, Value}|Tokens], Handler, Stack, Config) +when is_binary(Value); is_atom(Value) -> + value([Value] ++ Tokens, Handler, Stack, Config); +value([{number, Value}|Tokens], Handler, Stack, Config) +when is_float(Value); is_integer(Value) -> + value([Value] ++ Tokens, Handler, Stack, Config); +value([String|Tokens], Handler, Stack, Config) when is_atom(String) -> + value([{string, atom_to_binary(String, utf8)}] ++ Tokens, Handler, Stack, Config); +value([], Handler, Stack, Config) -> + incomplete(value, Handler, Stack, Config); +value(BadTokens, Handler, Stack, Config) when is_list(BadTokens) -> + ?error(value, BadTokens, Handler, Stack, Config); +value(Token, Handler, Stack, Config) -> + value([Token], Handler, Stack, Config). + + +object([end_object|Tokens], Handler, [object|Stack], Config) -> + maybe_done(Tokens, handle_event(end_object, Handler, Config), Stack, Config); +object([{key, Key}|Tokens], Handler, Stack, Config) +when is_atom(Key); is_binary(Key); is_integer(Key) -> + object([Key|Tokens], Handler, Stack, Config); +object([Key|Tokens], Handler, [object|Stack], Config) +when is_atom(Key); is_binary(Key); is_integer(Key) -> + try clean_string(fix_key(Key), Config) + of K -> + value( + Tokens, + handle_event({key, K}, Handler, Config), + [object|Stack], + Config + ) + catch error:badarg -> + ?error(object, [{string, Key}|Tokens], Handler, Stack, Config) + end; +object([], Handler, Stack, Config) -> + incomplete(object, Handler, Stack, Config); +object(Token, Handler, Stack, Config) -> + object([Token], Handler, Stack, Config). + + +array([end_array|Tokens], Handler, [array|Stack], Config) -> + maybe_done(Tokens, handle_event(end_array, Handler, Config), Stack, Config); +array([], Handler, Stack, Config) -> + incomplete(array, Handler, Stack, Config); +array(Tokens, Handler, Stack, Config) when is_list(Tokens) -> + value(Tokens, Handler, Stack, Config); +array(Token, Handler, Stack, Config) -> + array([Token], Handler, Stack, Config). + + +maybe_done([end_json], Handler, [], Config) -> + done([end_json], Handler, [], Config); +maybe_done(Tokens, Handler, [object|_] = Stack, Config) when is_list(Tokens) -> + object(Tokens, Handler, Stack, Config); +maybe_done(Tokens, Handler, [array|_] = Stack, Config) when is_list(Tokens) -> + array(Tokens, Handler, Stack, Config); +maybe_done([], Handler, Stack, Config) -> + incomplete(maybe_done, Handler, Stack, Config); +maybe_done(BadTokens, Handler, Stack, Config) when is_list(BadTokens) -> + ?error(maybe_done, BadTokens, Handler, Stack, Config); +maybe_done(Token, Handler, Stack, Config) -> + maybe_done([Token], Handler, Stack, Config). + + +done([], Handler, [], Config=#config{stream=true}) -> + incomplete(done, Handler, [], Config); +done(Tokens, Handler, [], Config) when Tokens == [end_json]; Tokens == [] -> + {_, State} = handle_event(end_json, Handler, Config), + State; +done(BadTokens, Handler, Stack, Config) when is_list(BadTokens) -> + ?error(done, BadTokens, Handler, Stack, Config); +done(Token, Handler, Stack, Config) -> + done([Token], Handler, Stack, Config). + + +fix_key(Key) when is_atom(Key) -> atom_to_binary(Key, utf8); +fix_key(Key) when is_integer(Key) -> list_to_binary(integer_to_list(Key)); +fix_key(Key) when is_binary(Key) -> Key. + + +clean_string(Bin, #config{dirty_strings=true}) -> Bin; +clean_string(Bin, Config) -> clean(Bin, [], Config). + + +%% unroll the control characters +clean(<<0, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(0, Config)], Config); +clean(<<1, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(1, Config)], Config); +clean(<<2, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(2, Config)], Config); +clean(<<3, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(3, Config)], Config); +clean(<<4, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(4, Config)], Config); +clean(<<5, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(5, Config)], Config); +clean(<<6, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(6, Config)], Config); +clean(<<7, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(7, Config)], Config); +clean(<<8, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(8, Config)], Config); +clean(<<9, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(9, Config)], Config); +clean(<<10, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(10, Config)], Config); +clean(<<11, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(11, Config)], Config); +clean(<<12, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(12, Config)], Config); +clean(<<13, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(13, Config)], Config); +clean(<<14, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(14, Config)], Config); +clean(<<15, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(15, Config)], Config); +clean(<<16, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(16, Config)], Config); +clean(<<17, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(17, Config)], Config); +clean(<<18, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(18, Config)], Config); +clean(<<19, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(19, Config)], Config); +clean(<<20, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(20, Config)], Config); +clean(<<21, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(21, Config)], Config); +clean(<<22, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(22, Config)], Config); +clean(<<23, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(23, Config)], Config); +clean(<<24, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(24, Config)], Config); +clean(<<25, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(25, Config)], Config); +clean(<<26, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(26, Config)], Config); +clean(<<27, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(27, Config)], Config); +clean(<<28, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(28, Config)], Config); +clean(<<29, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(29, Config)], Config); +clean(<<30, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(30, Config)], Config); +clean(<<31, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(31, Config)], Config); +clean(<<34, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(34, Config)], Config); +clean(<<47, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(47, Config)], Config); +clean(<<92, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(92, Config)], Config); +clean(<> = Bin, Acc, Config=#config{uescape=true}) -> + case X of + X when X < 16#80 -> start_count(Bin, Acc, Config); + _ -> clean(Rest, [Acc, json_escape_sequence(X)], Config) + end; +%% u+2028 +clean(<<226, 128, 168, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(16#2028, Config)], Config); +%% u+2029 +clean(<<226, 128, 169, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(16#2029, Config)], Config); +clean(<<_/utf8, _/binary>> = Bin, Acc, Config) -> start_count(Bin, Acc, Config); +%% surrogates +clean(<<237, X, _, Rest/binary>>, Acc, Config) when X >= 160 -> + clean(Rest, [Acc, maybe_replace(surrogate, Config)], Config); +%% overlong encodings and missing continuations of a 2 byte sequence +clean(<>, Acc, Config) when X >= 192, X =< 223 -> + clean(strip_continuations(Rest, 1), [Acc, maybe_replace(badutf, Config)], Config); +%% overlong encodings and missing continuations of a 3 byte sequence +clean(<>, Acc, Config) when X >= 224, X =< 239 -> + clean(strip_continuations(Rest, 2), [Acc, maybe_replace(badutf, Config)], Config); +%% overlong encodings and missing continuations of a 4 byte sequence +clean(<>, Acc, Config) when X >= 240, X =< 247 -> + clean(strip_continuations(Rest, 3), [Acc, maybe_replace(badutf, Config)], Config); +clean(<<_, Rest/binary>>, Acc, Config) -> + clean(Rest, [Acc, maybe_replace(badutf, Config)], Config); +clean(<<>>, Acc, _) -> iolist_to_binary(Acc). + + +start_count(Bin, Acc, Config) -> + Size = count(Bin, 0, Config), + <> = Bin, + clean(Rest, [Acc, Clean], Config). + + +%% again, unrolling ascii makes a huge difference. sadly +count(<<0, _/binary>>, N, _) -> N; +count(<<1, _/binary>>, N, _) -> N; +count(<<2, _/binary>>, N, _) -> N; +count(<<3, _/binary>>, N, _) -> N; +count(<<4, _/binary>>, N, _) -> N; +count(<<5, _/binary>>, N, _) -> N; +count(<<6, _/binary>>, N, _) -> N; +count(<<7, _/binary>>, N, _) -> N; +count(<<8, _/binary>>, N, _) -> N; +count(<<9, _/binary>>, N, _) -> N; +count(<<10, _/binary>>, N, _) -> N; +count(<<11, _/binary>>, N, _) -> N; +count(<<12, _/binary>>, N, _) -> N; +count(<<13, _/binary>>, N, _) -> N; +count(<<14, _/binary>>, N, _) -> N; +count(<<15, _/binary>>, N, _) -> N; +count(<<16, _/binary>>, N, _) -> N; +count(<<17, _/binary>>, N, _) -> N; +count(<<18, _/binary>>, N, _) -> N; +count(<<19, _/binary>>, N, _) -> N; +count(<<20, _/binary>>, N, _) -> N; +count(<<21, _/binary>>, N, _) -> N; +count(<<22, _/binary>>, N, _) -> N; +count(<<23, _/binary>>, N, _) -> N; +count(<<24, _/binary>>, N, _) -> N; +count(<<25, _/binary>>, N, _) -> N; +count(<<26, _/binary>>, N, _) -> N; +count(<<27, _/binary>>, N, _) -> N; +count(<<28, _/binary>>, N, _) -> N; +count(<<29, _/binary>>, N, _) -> N; +count(<<30, _/binary>>, N, _) -> N; +count(<<31, _/binary>>, N, _) -> N; +count(<<32, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<33, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<34, _/binary>>, N, _) -> N; +count(<<35, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<36, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<37, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<38, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<39, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<40, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<41, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<42, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<43, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<44, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<45, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<46, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<47, _/binary>>, N, _) -> N; +count(<<48, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<49, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<50, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<51, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<52, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<53, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<54, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<55, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<56, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<57, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<58, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<59, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<60, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<61, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<62, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<63, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<64, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<65, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<66, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<67, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<68, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<69, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<70, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<71, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<72, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<73, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<74, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<75, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<76, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<77, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<78, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<79, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<80, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<81, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<82, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<83, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<84, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<85, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<86, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<87, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<88, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<89, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<90, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<91, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<92, _/binary>>, N, _) -> N; +count(<<93, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<94, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<95, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<96, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<97, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<98, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<99, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<100, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<101, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<102, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<103, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<104, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<105, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<106, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<107, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<108, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<109, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<110, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<111, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<112, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<113, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<114, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<115, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<116, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<117, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<118, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<119, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<120, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<121, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<122, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<123, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<124, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<125, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<126, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<127, Rest/binary>>, N, Config) -> + count(Rest, N + 1, Config); +count(<<_/utf8, _/binary>>, N, #config{uescape=true}) -> N; +count(<>, N, Config) -> + case X of + X when X < 16#800 -> count(Rest, N + 2, Config); + 16#2028 -> N; + 16#2029 -> N; + X when X < 16#10000 -> count(Rest, N + 3, Config); + _ -> count(Rest, N + 4, Config) + end; +count(<<_, _/binary>>, N, _) -> N; +count(<<>>, N, _) -> N. + + +strip_continuations(Bin, 0) -> Bin; +strip_continuations(<>, N) when X >= 128, X =< 191 -> + strip_continuations(Rest, N - 1); +%% not a continuation byte +strip_continuations(Bin, _) -> Bin. + + +maybe_replace($\b, #config{escaped_strings=true}) -> <<$\\, $b>>; +maybe_replace($\t, #config{escaped_strings=true}) -> <<$\\, $t>>; +maybe_replace($\n, #config{escaped_strings=true}) -> <<$\\, $n>>; +maybe_replace($\f, #config{escaped_strings=true}) -> <<$\\, $f>>; +maybe_replace($\r, #config{escaped_strings=true}) -> <<$\\, $r>>; +maybe_replace($\", #config{escaped_strings=true}) -> <<$\\, $\">>; +maybe_replace($/, Config=#config{escaped_strings=true}) -> + case Config#config.escaped_forward_slashes of + true -> <<$\\, $/>>; + false -> <<$/>> + end; +maybe_replace($\\, #config{escaped_strings=true}) -> <<$\\, $\\>>; +maybe_replace(X, #config{escaped_strings=true}) when X < 32 -> + json_escape_sequence(X); +maybe_replace(X, Config=#config{escaped_strings=true}) when X == 16#2028; X == 16#2029 -> + case Config#config.unescaped_jsonp of + true -> <>; + false -> json_escape_sequence(X) + end; +maybe_replace(Atom, #config{strict_utf8=true}) when is_atom(Atom) -> + erlang:error(badarg); +maybe_replace(surrogate, _Config) -> + <<16#fffd/utf8>>; +maybe_replace(badutf, _Config) -> + <<16#fffd/utf8>>; +maybe_replace(X, _Config) -> + <>. + + +%% convert a codepoint to it's \uXXXX equiv. +json_escape_sequence(X) when X < 65536 -> + <> = <>, + <<$\\, $u, (to_hex(A)), (to_hex(B)), (to_hex(C)), (to_hex(D))>>; +json_escape_sequence(X) -> + Adjusted = X - 16#10000, + <> = <>, + [json_escape_sequence(A + 16#d800), json_escape_sequence(B + 16#dc00)]. + + +to_hex(10) -> $a; +to_hex(11) -> $b; +to_hex(12) -> $c; +to_hex(13) -> $d; +to_hex(14) -> $e; +to_hex(15) -> $f; +to_hex(X) -> X + 48. %% ascii "1" is [49], "2" is [50], etc... + + +%% for raw input +-spec init([]) -> []. + +init([]) -> []. + + +-spec handle_event(Event::any(), Acc::list()) -> list(). + +handle_event(end_json, State) -> lists:reverse(State); +handle_event(Event, State) -> [Event] ++ State. + + + +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). + + +parse(Events, Config) -> value(Events, {jsx, []}, [], jsx_config:parse_config(Config)). + + +error_test_() -> + [ + {"value error", ?_assertError(badarg, parse([self()], []))}, + {"maybe_done error", ?_assertError(badarg, parse([start_array, end_array, start_array, end_json], []))}, + {"done error", ?_assertError(badarg, parse([{string, <<"">>}, {literal, true}, end_json], []))}, + {"string error", ?_assertError(badarg, parse([{string, <<237, 160, 128>>}, end_json], [strict]))} + ]. + + +custom_error_handler_test_() -> + Error = fun(Rest, {_, State, _, _}, _) -> {State, Rest} end, + [ + {"value error", ?_assertEqual( + {value, [self()]}, + parse([self()], [{error_handler, Error}]) + )}, + {"maybe_done error", ?_assertEqual( + {maybe_done, [start_array, end_json]}, + parse([start_array, end_array, start_array, end_json], [{error_handler, Error}]) + )}, + {"done error", ?_assertEqual( + {maybe_done, [{literal, true}, end_json]}, + parse([{string, <<"">>}, {literal, true}, end_json], [{error_handler, Error}]) + )}, + {"string error", ?_assertEqual( + {value, [{string, <<237, 160, 128>>}, end_json]}, + parse([{string, <<237, 160, 128>>}, end_json], [{error_handler, Error}, strict]) + )} + ]. + + +incomplete_test_() -> + Cases = [ + {"incomplete value", []}, + {"incomplete object", [start_object]}, + {"incomplete array", [start_array]}, + {"incomplete maybe_done", [start_array, end_array]} + ], + [{Title, ?_assertError(badarg, parse(Events, []))} + || {Title, Events} <- Cases + ]. + + +custom_incomplete_handler_test_() -> + [ + {"custom incomplete handler", ?_assertError( + badarg, + parse([], [{incomplete_handler, fun(_, _, _) -> erlang:error(badarg) end}]) + )} + ]. + + +raw_test_() -> + Parse = fun(Events, Config) -> (parser(?MODULE, [], Config))(Events ++ [end_json]) end, + [ + {"raw empty list", ?_assertEqual( + [start_array, end_array], + Parse([{raw, <<"[]">>}], []) + )}, + {"raw empty object", ?_assertEqual( + [start_object, end_object], + Parse([{raw, <<"{}">>}], []) + )}, + {"raw chunk inside stream", ?_assertEqual( + [start_object, {key, <<"key">>}, start_array, {literal, true}, end_array, end_object], + Parse([start_object, {key, <<"key">>}, {raw, <<"[true]">>}, end_object], []) + )} + ]. + + +%% erlang refuses to encode certain codepoints, so fake them +to_fake_utf8(N) when N < 16#0080 -> <>; +to_fake_utf8(N) when N < 16#0800 -> + <<0:5, Y:5, X:6>> = <>, + <<2#110:3, Y:5, 2#10:2, X:6>>; +to_fake_utf8(N) when N < 16#10000 -> + <> = <>, + <<2#1110:4, Z:4, 2#10:2, Y:6, 2#10:2, X:6>>; +to_fake_utf8(N) -> + <<0:3, W:3, Z:6, Y:6, X:6>> = <>, + <<2#11110:5, W:3, 2#10:2, Z:6, 2#10:2, Y:6, 2#10:2, X:6>>. + + +codepoints() -> + unicode:characters_to_binary( + [32, 33] + ++ lists:seq(35, 46) + ++ lists:seq(48, 91) + ++ lists:seq(93, 16#2027) + ++ lists:seq(16#202a, 16#d7ff) + ++ lists:seq(16#e000, 16#ffff) + ). + + +extended_codepoints() -> + unicode:characters_to_binary( + lists:seq(16#10000, 16#1ffff) ++ [ + 16#20000, 16#30000, 16#40000, 16#50000, 16#60000, + 16#70000, 16#80000, 16#90000, 16#a0000, 16#b0000, + 16#c0000, 16#d0000, 16#e0000, 16#f0000, 16#100000 + ] + ). + + +surrogates() -> [ to_fake_utf8(N) || N <- lists:seq(16#d800, 16#dfff) ]. + + +clean_string_helper(String) -> + try clean_string(String, #config{strict_utf8=true}) of Clean -> Clean + catch error:badarg -> {error, badarg} + end. + + +clean_string_test_() -> + [ + {"clean codepoints", ?_assertEqual( + codepoints(), + clean_string(codepoints(), #config{}) + )}, + {"clean extended codepoints", ?_assertEqual( + extended_codepoints(), + clean_string(extended_codepoints(), #config{}) + )}, + {"escape path codepoints", ?_assertEqual( + codepoints(), + clean_string(codepoints(), #config{escaped_strings=true}) + )}, + {"escape path extended codepoints", ?_assertEqual( + extended_codepoints(), + clean_string(extended_codepoints(), #config{escaped_strings=true}) + )}, + {"error surrogates", ?_assertEqual( + lists:duplicate(length(surrogates()), {error, badarg}), + lists:map(fun(Codepoint) -> clean_string_helper(Codepoint) end, surrogates()) + )}, + {"clean surrogates", ?_assertEqual( + lists:duplicate(length(surrogates()), <<16#fffd/utf8>>), + lists:map(fun(Codepoint) -> clean_string(Codepoint, #config{}) end, surrogates()) + )} + ]. + + +escape_test_() -> + [ + {"maybe_escape backspace", ?_assertEqual( + <<"\\b">>, + clean_string(<<16#0008/utf8>>, #config{escaped_strings=true}) + )}, + {"don't escape backspace", ?_assertEqual( + <<"\b">>, + clean_string(<<16#0008/utf8>>, #config{}) + )}, + {"maybe_escape tab", ?_assertEqual( + <<"\\t">>, + clean_string(<<16#0009/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape newline", ?_assertEqual( + <<"\\n">>, + clean_string(<<16#000a/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape formfeed", ?_assertEqual( + <<"\\f">>, + clean_string(<<16#000c/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape carriage return", ?_assertEqual( + <<"\\r">>, + clean_string(<<16#000d/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape quote", ?_assertEqual( + <<"\\\"">>, + clean_string(<<16#0022/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape forward slash", ?_assertEqual( + <<"\\/">>, + clean_string(<<16#002f/utf8>>, #config{escaped_strings=true, escaped_forward_slashes=true}) + )}, + {"do not maybe_escape forward slash", ?_assertEqual( + <<"/">>, + clean_string(<<16#002f/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape backslash", ?_assertEqual( + <<"\\\\">>, + clean_string(<<16#005c/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape jsonp (u2028)", ?_assertEqual( + <<"\\u2028">>, + clean_string(<<16#2028/utf8>>, #config{escaped_strings=true}) + )}, + {"do not maybe_escape jsonp (u2028)", ?_assertEqual( + <<16#2028/utf8>>, + clean_string(<<16#2028/utf8>>, #config{escaped_strings=true, unescaped_jsonp=true}) + )}, + {"maybe_escape jsonp (u2029)", ?_assertEqual( + <<"\\u2029">>, + clean_string(<<16#2029/utf8>>, #config{escaped_strings=true}) + )}, + {"do not maybe_escape jsonp (u2029)", ?_assertEqual( + <<16#2029/utf8>>, + clean_string(<<16#2029/utf8>>, #config{escaped_strings=true, unescaped_jsonp=true}) + )}, + {"maybe_escape u0000", ?_assertEqual( + <<"\\u0000">>, + clean_string(<<16#0000/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0001", ?_assertEqual( + <<"\\u0001">>, + clean_string(<<16#0001/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0002", ?_assertEqual( + <<"\\u0002">>, + clean_string(<<16#0002/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0003", ?_assertEqual( + <<"\\u0003">>, + clean_string(<<16#0003/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0004", ?_assertEqual( + <<"\\u0004">>, + clean_string(<<16#0004/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0005", ?_assertEqual( + <<"\\u0005">>, + clean_string(<<16#0005/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0006", ?_assertEqual( + <<"\\u0006">>, + clean_string(<<16#0006/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0007", ?_assertEqual( + <<"\\u0007">>, + clean_string(<<16#0007/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u000b", ?_assertEqual( + <<"\\u000b">>, + clean_string(<<16#000b/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u000e", ?_assertEqual( + <<"\\u000e">>, + clean_string(<<16#000e/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u000f", ?_assertEqual( + <<"\\u000f">>, + clean_string(<<16#000f/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0010", ?_assertEqual( + <<"\\u0010">>, + clean_string(<<16#0010/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0011", ?_assertEqual( + <<"\\u0011">>, + clean_string(<<16#0011/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0012", ?_assertEqual( + <<"\\u0012">>, + clean_string(<<16#0012/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0013", ?_assertEqual( + <<"\\u0013">>, + clean_string(<<16#0013/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0014", ?_assertEqual( + <<"\\u0014">>, + clean_string(<<16#0014/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0015", ?_assertEqual( + <<"\\u0015">>, + clean_string(<<16#0015/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0016", ?_assertEqual( + <<"\\u0016">>, + clean_string(<<16#0016/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0017", ?_assertEqual( + <<"\\u0017">>, + clean_string(<<16#0017/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0018", ?_assertEqual( + <<"\\u0018">>, + clean_string(<<16#0018/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u0019", ?_assertEqual( + <<"\\u0019">>, + clean_string(<<16#0019/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u001a", ?_assertEqual( + <<"\\u001a">>, + clean_string(<<16#001a/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u001b", ?_assertEqual( + <<"\\u001b">>, + clean_string(<<16#001b/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u001c", ?_assertEqual( + <<"\\u001c">>, + clean_string(<<16#001c/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u001d", ?_assertEqual( + <<"\\u001d">>, + clean_string(<<16#001d/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u001e", ?_assertEqual( + <<"\\u001e">>, + clean_string(<<16#001e/utf8>>, #config{escaped_strings=true}) + )}, + {"maybe_escape u001f", ?_assertEqual( + <<"\\u001f">>, + clean_string(<<16#001f/utf8>>, #config{escaped_strings=true}) + )} + ]. + + +bad_utf8_test_() -> + [ + {"orphan continuation byte u+0080", ?_assertError( + badarg, + clean_string(<<16#0080>>, #config{strict_utf8=true}) + )}, + {"orphan continuation byte u+0080 replaced", ?_assertEqual( + <<16#fffd/utf8>>, + clean_string(<<16#0080>>, #config{}) + )}, + {"orphan continuation byte u+00bf", ?_assertError( + badarg, + clean_string(<<16#00bf>>, #config{strict_utf8=true}) + )}, + {"orphan continuation byte u+00bf replaced", ?_assertEqual( + <<16#fffd/utf8>>, + clean_string(<<16#00bf>>, #config{}) + )}, + {"2 continuation bytes", ?_assertError( + badarg, + clean_string(<<(binary:copy(<<16#0080>>, 2))/binary>>, #config{strict_utf8=true}) + )}, + {"2 continuation bytes replaced", ?_assertEqual( + binary:copy(<<16#fffd/utf8>>, 2), + clean_string(<<(binary:copy(<<16#0080>>, 2))/binary>>, #config{}) + )}, + {"3 continuation bytes", ?_assertError( + badarg, + clean_string(<<(binary:copy(<<16#0080>>, 3))/binary>>, #config{strict_utf8=true}) + )}, + {"3 continuation bytes replaced", ?_assertEqual( + binary:copy(<<16#fffd/utf8>>, 3), + clean_string(<<(binary:copy(<<16#0080>>, 3))/binary>>, #config{}) + )}, + {"4 continuation bytes", ?_assertError( + badarg, + clean_string(<<(binary:copy(<<16#0080>>, 4))/binary>>, #config{strict_utf8=true}) + )}, + {"4 continuation bytes replaced", ?_assertEqual( + binary:copy(<<16#fffd/utf8>>, 4), + clean_string(<<(binary:copy(<<16#0080>>, 4))/binary>>, #config{}) + )}, + {"5 continuation bytes", ?_assertError( + badarg, + clean_string(<<(binary:copy(<<16#0080>>, 5))/binary>>, #config{strict_utf8=true}) + )}, + {"5 continuation bytes replaced", ?_assertEqual( + binary:copy(<<16#fffd/utf8>>, 5), + clean_string(<<(binary:copy(<<16#0080>>, 5))/binary>>, #config{}) + )}, + {"6 continuation bytes", ?_assertError( + badarg, + clean_string(<<(binary:copy(<<16#0080>>, 6))/binary>>, #config{strict_utf8=true}) + )}, + {"6 continuation bytes replaced", ?_assertEqual( + binary:copy(<<16#fffd/utf8>>, 6), + clean_string(<<(binary:copy(<<16#0080>>, 6))/binary>>, #config{}) + )}, + {"all continuation bytes", ?_assertError( + badarg, + clean_string(<<(list_to_binary(lists:seq(16#0080, 16#00bf)))/binary>>, #config{strict_utf8=true}) + )}, + {"all continuation bytes replaced", ?_assertEqual( + binary:copy(<<16#fffd/utf8>>, length(lists:seq(16#0080, 16#00bf))), + clean_string( + <<(list_to_binary(lists:seq(16#0080, 16#00bf)))/binary>>, + #config{} + ) + )}, + {"lonely start byte", ?_assertError( + badarg, + clean_string(<<16#00c0>>, #config{strict_utf8=true}) + )}, + {"lonely start byte replaced", ?_assertEqual( + <<16#fffd/utf8>>, + clean_string(<<16#00c0>>, #config{}) + )}, + {"lonely start bytes (2 byte)", ?_assertError( + badarg, + clean_string(<<16#00c0, 32, 16#00df>>, #config{strict_utf8=true}) + )}, + {"lonely start bytes (2 byte) replaced", ?_assertEqual( + <<16#fffd/utf8, 32, 16#fffd/utf8>>, + clean_string(<<16#00c0, 32, 16#00df>>, #config{}) + )}, + {"lonely start bytes (3 byte)", ?_assertError( + badarg, + clean_string(<<16#00e0, 32, 16#00ef>>, #config{strict_utf8=true}) + )}, + {"lonely start bytes (3 byte) replaced", ?_assertEqual( + <<16#fffd/utf8, 32, 16#fffd/utf8>>, + clean_string(<<16#00e0, 32, 16#00ef>>, #config{}) + )}, + {"lonely start bytes (4 byte)", ?_assertError( + badarg, + clean_string(<<16#00f0, 32, 16#00f7>>, #config{strict_utf8=true}) + )}, + {"lonely start bytes (4 byte) replaced", ?_assertEqual( + <<16#fffd/utf8, 32, 16#fffd/utf8>>, + clean_string(<<16#00f0, 32, 16#00f7>>, #config{}) + )}, + {"missing continuation byte (3 byte)", ?_assertError( + badarg, + clean_string(<<224, 160, 32>>, #config{strict_utf8=true}) + )}, + {"missing continuation byte (3 byte) replaced", ?_assertEqual( + <<16#fffd/utf8, 32>>, + clean_string(<<224, 160, 32>>, #config{}) + )}, + {"missing continuation byte (4 byte missing one)", ?_assertError( + badarg, + clean_string(<<240, 144, 128, 32>>, #config{strict_utf8=true}) + )}, + {"missing continuation byte (4 byte missing one) replaced", ?_assertEqual( + <<16#fffd/utf8, 32>>, + clean_string(<<240, 144, 128, 32>>, #config{}) + )}, + {"missing continuation byte (4 byte missing two)", ?_assertError( + badarg, + clean_string(<<240, 144, 32>>, #config{strict_utf8=true}) + )}, + {"missing continuation byte (4 byte missing two) replaced", ?_assertEqual( + <<16#fffd/utf8, 32>>, + clean_string(<<240, 144, 32>>, #config{}) + )}, + {"overlong encoding of u+002f (2 byte)", ?_assertError( + badarg, + clean_string(<<16#c0, 16#af, 32>>, #config{strict_utf8=true}) + )}, + {"overlong encoding of u+002f (2 byte) replaced", ?_assertEqual( + <<16#fffd/utf8, 32>>, + clean_string(<<16#c0, 16#af, 32>>, #config{}) + )}, + {"overlong encoding of u+002f (3 byte)", ?_assertError( + badarg, + clean_string(<<16#e0, 16#80, 16#af, 32>>, #config{strict_utf8=true}) + )}, + {"overlong encoding of u+002f (3 byte) replaced", ?_assertEqual( + <<16#fffd/utf8, 32>>, + clean_string(<<16#e0, 16#80, 16#af, 32>>, #config{}) + )}, + {"overlong encoding of u+002f (4 byte)", ?_assertError( + badarg, + clean_string(<<16#f0, 16#80, 16#80, 16#af, 32>>, #config{strict_utf8=true}) + )}, + {"overlong encoding of u+002f (4 byte) replaced", ?_assertEqual( + <<16#fffd/utf8, 32>>, + clean_string(<<16#f0, 16#80, 16#80, 16#af, 32>>, #config{}) + )}, + {"highest overlong 2 byte sequence", ?_assertError( + badarg, + clean_string(<<16#c1, 16#bf, 32>>, #config{strict_utf8=true}) + )}, + {"highest overlong 2 byte sequence replaced", ?_assertEqual( + <<16#fffd/utf8, 32>>, + clean_string(<<16#c1, 16#bf, 32>>, #config{}) + )}, + {"highest overlong 3 byte sequence", ?_assertError( + badarg, + clean_string(<<16#e0, 16#9f, 16#bf, 32>>, #config{strict_utf8=true}) + )}, + {"highest overlong 3 byte sequence replaced", ?_assertEqual( + <<16#fffd/utf8, 32>>, + clean_string(<<16#e0, 16#9f, 16#bf, 32>>, #config{}) + )}, + {"highest overlong 4 byte sequence", ?_assertError( + badarg, + clean_string(<<16#f0, 16#8f, 16#bf, 16#bf, 32>>, #config{strict_utf8=true}) + )}, + {"highest overlong 4 byte sequence replaced", ?_assertEqual( + <<16#fffd/utf8, 32>>, + clean_string(<<16#f0, 16#8f, 16#bf, 16#bf, 32>>, #config{}) + )} + ]. + + +json_escape_sequence_test_() -> + [ + {"json escape sequence test - 16#0000", ?_assertEqual(<<"\\u0000"/utf8>>, json_escape_sequence(16#0000))}, + {"json escape sequence test - 16#abc", ?_assertEqual(<<"\\u0abc"/utf8>>, json_escape_sequence(16#abc))}, + {"json escape sequence test - 16#def", ?_assertEqual(<<"\\u0def"/utf8>>, json_escape_sequence(16#def))} + ]. + + +uescape_test_() -> + [ + {"\"\\u0080\"", ?_assertEqual( + <<"\\u0080">>, + clean_string(<<128/utf8>>, #config{uescape=true}) + )}, + {"\"\\u8ca8\\u5481\\u3002\\u0091\\u0091\"", ?_assertEqual( + <<"\\u8ca8\\u5481\\u3002\\u0091\\u0091">>, + clean_string( + <<232,178,168,229,146,129,227,128,130,194,145,194,145>>, + #config{uescape=true} + ) + )}, + {"\"\\ud834\\udd1e\"", ?_assertEqual( + <<"\\ud834\\udd1e">>, + clean_string(<<240, 157, 132, 158>>, #config{uescape=true}) + )}, + {"\"\\ud83d\\ude0a\"", ?_assertEqual( + <<"\\ud83d\\ude0a">>, + clean_string(<<240, 159, 152, 138>>, #config{uescape=true}) + )} + ]. + + +fix_key_test_() -> + [ + {"binary key", ?_assertEqual(fix_key(<<"foo">>), <<"foo">>)}, + {"atom key", ?_assertEqual(fix_key(foo), <<"foo">>)}, + {"integer key", ?_assertEqual(fix_key(123), <<"123">>)} + ]. + + +datetime_test_() -> + [ + {"datetime", ?_assertEqual( + [start_array, {string, <<"2014-08-13T23:12:34Z">>}, end_array, end_json], + parse([start_array, {{2014,08,13},{23,12,34}}, end_array, end_json], []) + )}, + {"datetime", ?_assertEqual( + [start_array, {string, <<"2014-08-13T23:12:34.363369Z">>}, end_array, end_json], + parse([start_array, {{2014,08,13},{23,12,34.363369}}, end_array, end_json], []) + )} + ]. + + +timestamp_test_() -> + [ + {"timestamp", ?_assertEqual( + [start_array, {string, <<"2016-01-15T18:19:28Z">>}, end_array, end_json], + parse([start_array, {1452,881968,111772}, end_array, end_json], []) + )} + ]. + + +rogue_tuple_test_() -> + [ + {"kv in value position of object", ?_assertError( + badarg, + parse([start_object, <<"key">>, {<<"key">>, <<"value">>}, end_object, end_json], []) + )}, + {"kv in value position of list", ?_assertError( + badarg, + parse([start_array, {<<"key">>, <<"value">>}, end_array, end_json], []) + )} + ]. + + +-endif. diff --git a/deps/jsx/src/jsx_to_json.erl b/deps/jsx/src/jsx_to_json.erl new file mode 100644 index 0000000000000000000000000000000000000000..d20add617fd19483d39d418d748dced45b57190a --- /dev/null +++ b/deps/jsx/src/jsx_to_json.erl @@ -0,0 +1,408 @@ +%% The MIT License + +%% Copyright (c) 2010-2013 alisdair sullivan + +%% Permission is hereby granted, free of charge, to any person obtaining a copy +%% of this software and associated documentation files (the "Software"), to deal +%% in the Software without restriction, including without limitation the rights +%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +%% copies of the Software, and to permit persons to whom the Software is +%% furnished to do so, subject to the following conditions: + +%% The above copyright notice and this permission notice shall be included in +%% all copies or substantial portions of the Software. + +%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +%% THE SOFTWARE. + + +-module(jsx_to_json). + +-export([to_json/2, format/2]). +-export([init/1, handle_event/2]). +-export([start_json/0, start_json/1]). +-export([start_object/1, start_array/1, finish/1, insert/2, get_key/1, get_value/1]). + + +-record(config, { + space = 0, + indent = 0, + depth = 0, + newline = <<$\n>> +}). + +-type config() :: proplists:proplist(). + + +-spec to_json(Source::jsx:json_term(), Config::jsx_config:options()) -> binary(). + +to_json(Source, Config) when is_list(Config) -> + (jsx:encoder(?MODULE, Config, jsx_config:extract_config(Config ++ [escaped_strings])))(Source). + + +-spec format(Source::binary(), Config::jsx_config:options()) -> jsx:json_text(). + +format(Source, Config) when is_binary(Source) andalso is_list(Config) -> + (jsx:decoder(?MODULE, Config, jsx_config:extract_config(Config ++ [escaped_strings])))(Source); +format(_, _) -> erlang:error(badarg). + + +parse_config(Config) -> parse_config(Config, #config{}). + +parse_config([{space, Val}|Rest], Config) when is_integer(Val), Val > 0 -> + parse_config(Rest, Config#config{space = Val}); +parse_config([space|Rest], Config) -> + parse_config(Rest, Config#config{space = 1}); +parse_config([{indent, Val}|Rest], Config) when is_integer(Val), Val > 0 -> + parse_config(Rest, Config#config{indent = Val}); +parse_config([indent|Rest], Config) -> + parse_config(Rest, Config#config{indent = 1}); +parse_config([{newline, Val}|Rest], Config) when is_binary(Val) -> + parse_config(Rest, Config#config{newline = Val}); +parse_config([{K, _}|Rest] = Options, Config) -> + case lists:member(K, jsx_config:valid_flags()) of + true -> parse_config(Rest, Config) + ; false -> erlang:error(badarg, [Options, Config]) + end; +parse_config([K|Rest] = Options, Config) -> + case lists:member(K, jsx_config:valid_flags()) of + true -> parse_config(Rest, Config) + ; false -> erlang:error(badarg, [Options, Config]) + end; +parse_config([], Config) -> + Config. + + +-define(start_object, <<"{">>). +-define(start_array, <<"[">>). +-define(end_object, <<"}">>). +-define(end_array, <<"]">>). +-define(colon, <<":">>). +-define(comma, <<",">>). +-define(quote, <<"\"">>). +-define(space, <<" ">>). +-define(newline, <<"\n">>). + + +-type state() :: {unicode:charlist(), #config{}}. +-spec init(Config::config()) -> state(). + +init(Config) -> {[], parse_config(Config)}. + + +-spec handle_event(Event::any(), State::state()) -> state(). + +handle_event(end_json, State) -> get_value(State); + +handle_event(start_object, State) -> start_object(State); +handle_event(end_object, State) -> finish(State); + +handle_event(start_array, State) -> start_array(State); +handle_event(end_array, State) -> finish(State); + +handle_event({Type, Event}, {_, Config} = State) -> insert(encode(Type, Event, Config), State). + + +encode(string, String, _Config) -> + [?quote, String, ?quote]; +encode(key, Key, _Config) -> + [?quote, Key, ?quote]; +encode(literal, Literal, _Config) -> + erlang:atom_to_list(Literal); +encode(integer, Integer, _Config) -> + erlang:integer_to_list(Integer); +encode(float, Float, _Config) -> + io_lib:format("~p", [Float]). + + +space(Config) -> + case Config#config.space of + 0 -> <<>> + ; X when X > 0 -> binary:copy(?space, X) + end. + + +indent(Config) -> + case Config#config.indent of + 0 -> <<>> + ; X when X > 0 -> <<(Config#config.newline)/binary, (binary:copy(?space, X * Config#config.depth))/binary>> + end. + + +indent_or_space(Config) -> + case Config#config.indent > 0 of + true -> indent(Config) + ; false -> space(Config) + end. + + +%% internal state is a stack and a config object +%% `{Stack, Config}` +%% the stack is a list of in progress objects/arrays +%% `[Current, Parent, Grandparent,...OriginalAncestor]` +%% an object has the representation on the stack of +%% `{object, Object}` +%% of if there's a key with a yet to be matched value +%% `{object, Key, Object}` +%% an array looks like +%% `{array, Array}` +%% `Object` and `Array` are utf8 encoded binaries + +start_json() -> {[], #config{}}. + +start_json(Config) when is_list(Config) -> {[], parse_config(Config)}. + +%% allocate a new object on top of the stack +start_object({Stack, Config = #config{depth = Depth}}) -> + {[{object, ?start_object}] ++ Stack, Config#config{depth = Depth + 1}}. + +%% allocate a new array on top of the stack +start_array({Stack, Config = #config{depth = Depth}}) -> + {[{array, ?start_array}] ++ Stack, Config#config{depth = Depth + 1}}. + +%% finish an object or array and insert it into the parent object if it exists +finish({Stack, Config = #config{depth = Depth}}) -> + NewConfig = Config#config{depth = Depth - 1}, + finish_({Stack, NewConfig}). + +finish_({[{object, <<"{">>}], Config}) -> {<<"{}">>, Config}; +finish_({[{array, <<"[">>}], Config}) -> {<<"[]">>, Config}; +finish_({[{object, <<"{">>}|Rest], Config}) -> insert(<<"{}">>, {Rest, Config}); +finish_({[{array, <<"[">>}|Rest], Config}) -> insert(<<"[]">>, {Rest, Config}); +finish_({[{object, Object}], Config}) -> + {[Object, indent(Config), ?end_object], Config}; +finish_({[{object, Object}|Rest], Config}) -> + insert([Object, indent(Config), ?end_object], {Rest, Config}); +finish_({[{array, Array}], Config}) -> + {[Array, indent(Config), ?end_array], Config}; +finish_({[{array, Array}|Rest], Config}) -> + insert([Array, indent(Config), ?end_array], {Rest, Config}); +finish_(_) -> erlang:error(badarg). + +%% insert a value when there's no parent object or array +insert(Value, {[], Config}) -> + {Value, Config}; +%% insert a key or value into an object or array, autodetects the 'right' thing +insert(Key, {[{object, Object}|Rest], Config}) -> + {[{object, Key, Object}] ++ Rest, Config}; +insert(Value, {[{object, Key, ?start_object}|Rest], Config}) -> + { + [{object, [ + ?start_object, + indent(Config), + Key, + ?colon, + space(Config), + Value + ]}] ++ Rest, + Config + }; +insert(Value, {[{object, Key, Object}|Rest], Config}) -> + { + [{object, [ + Object, + ?comma, + indent_or_space(Config), + Key, + ?colon, + space(Config), + Value + ]}] ++ Rest, + Config + }; +insert(Value, {[{array, ?start_array}|Rest], Config}) -> + {[{array, [?start_array, indent(Config), Value]}] ++ Rest, Config}; +insert(Value, {[{array, Array}|Rest], Config}) -> + { + [{array, [Array, + ?comma, + indent_or_space(Config), + Value + ]}] ++ Rest, + Config + }; +insert(_, _) -> erlang:error(badarg). + + +get_key({[{object, Key, _}|_], _}) -> Key; +get_key(_) -> erlang:error(badarg). + + +get_value({Value, _Config}) -> + try unicode:characters_to_binary(Value) + catch error:_ -> erlang:error(badarg) + end; +get_value(_) -> erlang:error(badarg). + + + +%% eunit tests + +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). + + +config_test_() -> + [ + {"empty config", ?_assertEqual(#config{}, parse_config([]))}, + {"unspecified indent/space", ?_assertEqual( + #config{space=1, indent=1}, + parse_config([space, indent]) + )}, + {"specific indent", ?_assertEqual( + #config{indent=4}, + parse_config([{indent, 4}]) + )}, + {"specific space", ?_assertEqual( + #config{space=2}, + parse_config([{space, 2}]) + )}, + {"specific space and indent", ?_assertEqual( + #config{space=2, indent=2}, + parse_config([{space, 2}, {indent, 2}]) + )}, + {"invalid opt flag", ?_assertError(badarg, parse_config([error]))}, + {"invalid opt tuple", ?_assertError(badarg, parse_config([{error, true}]))} + ]. + + +space_test_() -> + [ + {"no space", ?_assertEqual(<<>>, space(#config{space=0}))}, + {"one space", ?_assertEqual(<<" ">>, space(#config{space=1}))}, + {"four spaces", ?_assertEqual(<<" ">>, space(#config{space=4}))} + ]. + + +indent_test_() -> + [ + {"no indent", ?_assertEqual(<<>>, indent(#config{indent=0, depth=1}))}, + {"indent 1 depth 1", ?_assertEqual( + <>/binary>>, + indent(#config{indent=1, depth=1}) + )}, + {"indent 1 depth 2", ?_assertEqual( + <>/binary>>, + indent(#config{indent=1, depth=2}) + )}, + {"indent 4 depth 1", ?_assertEqual( + <>/binary>>, + indent(#config{indent=4, depth=1}) + )}, + {"indent 4 depth 2", ?_assertEqual( + <>/binary, <<" ">>/binary>>, + indent(#config{indent=4, depth=2}) + )} + ]. + + +indent_or_space_test_() -> + [ + {"no indent so space", ?_assertEqual( + <<" ">>, + indent_or_space(#config{space=1, indent=0, depth=1}) + )}, + {"indent so no space", ?_assertEqual( + <>/binary>>, + indent_or_space(#config{space=1, indent=1, depth=1}) + )} + ]. + + +encode_test_() -> + [ + {"0.0", ?_assert(encode(float, 0.0, #config{}) =:= ["0.0"])}, + {"1.0", ?_assert(encode(float, 1.0, #config{}) =:= ["1.0"])}, + {"-1.0", ?_assert(encode(float, -1.0, #config{}) =:= ["-1.0"])}, + {"3.1234567890987654321", + ?_assert( + encode(float, 3.1234567890987654321, #config{}) =:= ["3.1234567890987655"]) + }, + {"1.0e23", ?_assert(encode(float, 1.0e23, #config{}) =:= ["1.0e23"])}, + {"0.3", ?_assert(encode(float, 3.0/10.0, #config{}) =:= ["0.3"])}, + {"0.0001", ?_assert(encode(float, 0.0001, #config{}) =:= ["0.0001"])}, + {"0.00001", ?_assert(encode(float, 0.00001, #config{}) =:= ["1.0e-5"])}, + {"0.00000001", ?_assert(encode(float, 0.00000001, #config{}) =:= ["1.0e-8"])}, + {"1.0e-323", ?_assert(encode(float, 1.0e-323, #config{}) =:= ["1.0e-323"])}, + {"1.0e308", ?_assert(encode(float, 1.0e308, #config{}) =:= ["1.0e308"])}, + {"min normalized float", + ?_assert( + encode(float, math:pow(2, -1022), #config{}) =:= ["2.2250738585072014e-308"] + ) + }, + {"max normalized float", + ?_assert( + encode(float, (2 - math:pow(2, -52)) * math:pow(2, 1023), #config{}) + =:= ["1.7976931348623157e308"] + ) + }, + {"min denormalized float", + ?_assert(encode(float, math:pow(2, -1074), #config{}) =:= ["5.0e-324"]) + }, + {"max denormalized float", + ?_assert( + encode(float, (1 - math:pow(2, -52)) * math:pow(2, -1022), #config{}) + =:= ["2.225073858507201e-308"] + ) + }, + {"hello world", ?_assert(encode(string, <<"hello world">>, #config{}) + =:= [<<"\"">>, <<"hello world">>, <<"\"">>] + )}, + {"key", ?_assert(encode(key, <<"key">>, #config{}) =:= [<<"\"">>, <<"key">>, <<"\"">>])}, + {"1", ?_assert(encode(integer, 1, #config{}) =:= "1")}, + {"-1", ?_assert(encode(integer, -1, #config{}) =:= "-1")}, + {"true", ?_assert(encode(literal, true, #config{}) =:= "true")}, + {"false", ?_assert(encode(literal, false, #config{}) =:= "false")}, + {"null", ?_assert(encode(literal, null, #config{}) =:= "null")} + ]. + + +format_test_() -> + % {minified version, pretty version} + Cases = [ + {"empty object", <<"{}">>, <<"{}">>}, + {"empty array", <<"[]">>, <<"[]">>}, + {"single key object", <<"{\"k\":\"v\"}">>, <<"{\n \"k\": \"v\"\n}">>}, + {"single member array", <<"[true]">>, <<"[\n true\n]">>}, + {"multiple key object", + <<"{\"k\":\"v\",\"x\":\"y\"}">>, + <<"{\n \"k\": \"v\",\n \"x\": \"y\"\n}">> + }, + {"multiple member array", + <<"[1.0,2.0,3.0]">>, + <<"[\n 1.0,\n 2.0,\n 3.0\n]">> + }, + {"nested structure", + <<"[[{},[],true],{\"k\":\"v\",\"x\":\"y\"}]">>, + <<"[\n [\n {},\n [],\n true\n ],\n {\n \"k\": \"v\",\n \"x\": \"y\"\n }\n]">> + } + ], + [{Title, ?_assertEqual(Min, jsx:minify(Pretty))} || {Title, Min, Pretty} <- Cases] ++ + [{Title, ?_assertEqual(Pretty, jsx:prettify(Min))} || {Title, Min, Pretty} <- Cases]. + +custom_newline_test_() -> + [ + {"single key object", ?_assert( + jsx:format(<<"{\"k\":\"v\"}">>, [space, {indent, 2}, {newline, <<$\r>>}]) + =:= <<"{\r \"k\": \"v\"\r}">>) + } + ]. + +handle_event_test_() -> + Data = jsx:test_cases() ++ jsx:special_test_cases(), + [ + { + Title, ?_assertEqual( + JSON, + lists:foldl(fun handle_event/2, init([]), Events ++ [end_json]) + ) + } || {Title, JSON, _, Events} <- Data + ]. + + +-endif. diff --git a/deps/jsx/src/jsx_to_term.erl b/deps/jsx/src/jsx_to_term.erl new file mode 100644 index 0000000000000000000000000000000000000000..07beba4d94866778ffef29f02f87b65cf8064e16 --- /dev/null +++ b/deps/jsx/src/jsx_to_term.erl @@ -0,0 +1,389 @@ +%% The MIT License + +%% Copyright (c) 2010-2013 Alisdair Sullivan + +%% Permission is hereby granted, free of charge, to any person obtaining a copy +%% of this software and associated documentation files (the "Software"), to deal +%% in the Software without restriction, including without limitation the rights +%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +%% copies of the Software, and to permit persons to whom the Software is +%% furnished to do so, subject to the following conditions: + +%% The above copyright notice and this permission notice shall be included in +%% all copies or substantial portions of the Software. + +%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +%% THE SOFTWARE. + + +-module(jsx_to_term). + +-export([to_term/2]). +-export([init/1, handle_event/2]). +-export([ + start_term/1, + start_object/1, + start_array/1, + finish/1, + insert/2, + get_key/1, + get_value/1 +]). + + +-record(config, { + labels = binary, + return_maps = false +}). + +-type config() :: proplists:proplist(). + +-spec to_term(Source::binary(), Config::jsx_config:options()) -> jsx:json_term() | {incomplete, jsx:decoder()}. + +to_term(Source, Config) when is_list(Config) -> + (jsx:decoder(?MODULE, [return_maps] ++ Config, jsx_config:extract_config(Config)))(Source). + +parse_config(Config) -> parse_config(Config, #config{}). + +parse_config([{labels, Val}|Rest], Config) + when Val == binary; Val == atom; Val == existing_atom; Val == attempt_atom -> + parse_config(Rest, Config#config{labels = Val}); +parse_config([labels|Rest], Config) -> + parse_config(Rest, Config#config{labels = binary}); +parse_config([{return_maps, Val}|Rest], Config) + when Val == true; Val == false -> + parse_config(Rest, Config#config{return_maps = Val}); +parse_config([return_maps|Rest], Config) -> + parse_config(Rest, Config#config{return_maps = true}); +parse_config([{K, _}|Rest] = Options, Config) -> + case lists:member(K, jsx_config:valid_flags()) of + true -> parse_config(Rest, Config) + ; false -> erlang:error(badarg, [Options, Config]) + end; +parse_config([K|Rest] = Options, Config) -> + case lists:member(K, jsx_config:valid_flags()) of + true -> parse_config(Rest, Config) + ; false -> erlang:error(badarg, [Options, Config]) + end; +parse_config([], Config) -> + Config. + + +-type state() :: {list(), #config{}}. +-spec init(Config::config()) -> state(). + +init(Config) -> start_term(Config). + +-spec handle_event(Event::any(), State::state()) -> state(). + +handle_event(end_json, State) -> get_value(State); + +handle_event(start_object, State) -> start_object(State); +handle_event(end_object, State) -> finish(State); + +handle_event(start_array, State) -> start_array(State); +handle_event(end_array, State) -> finish(State); + +handle_event({key, Key}, {_, Config} = State) -> insert(format_key(Key, Config), State); + +handle_event({_, Event}, State) -> insert(Event, State). + + +format_key(Key, Config) -> + case Config#config.labels of + binary -> Key + ; atom -> binary_to_atom(Key, utf8) + ; existing_atom -> binary_to_existing_atom(Key, utf8) + ; attempt_atom -> + try binary_to_existing_atom(Key, utf8) of + Result -> Result + catch + error:badarg -> Key + end + end. + + +%% internal state is a stack and a config object +%% `{Stack, Config}` +%% the stack is a list of in progress objects/arrays +%% `[Current, Parent, Grandparent,...OriginalAncestor]` +%% an object has the representation on the stack of +%% `{object, [ +%% {NthKey, NthValue}, +%% {NMinus1Key, NthMinus1Value}, +%% ..., +%% {FirstKey, FirstValue} +%% ]}` +%% or if returning maps +%% `{object, #{ +%% FirstKey => FirstValue, +%% SecondKey => SecondValue, +%% ..., +%% NthKey => NthValue +%% }}` +%% or if there's a key with a yet to be matched value +%% `{object, Key, ...}` +%% an array looks like +%% `{array, [NthValue, NthMinus1Value,...FirstValue]}` + +start_term(Config) when is_list(Config) -> {[], parse_config(Config)}. + +%% allocate a new object on top of the stack +start_object({Stack, Config=#config{return_maps=true}}) -> + {[{object, #{}}] ++ Stack, Config}; +start_object({Stack, Config}) -> + {[{object, []}] ++ Stack, Config}. + + +%% allocate a new array on top of the stack +start_array({Stack, Config}) -> {[{array, []}] ++ Stack, Config}. + + +%% finish an object or array and insert it into the parent object if it exists or +%% return it if it is the root object +finish({[{object, Map}], Config=#config{return_maps=true}}) -> {Map, Config}; +finish({[{object, Map}|Rest], Config=#config{return_maps=true}}) -> insert(Map, {Rest, Config}); +finish({[{object, []}], Config}) -> {[{}], Config}; +finish({[{object, []}|Rest], Config}) -> insert([{}], {Rest, Config}); +finish({[{object, Pairs}], Config}) -> {lists:reverse(Pairs), Config}; +finish({[{object, Pairs}|Rest], Config}) -> insert(lists:reverse(Pairs), {Rest, Config}); +finish({[{array, Values}], Config}) -> {lists:reverse(Values), Config}; +finish({[{array, Values}|Rest], Config}) -> insert(lists:reverse(Values), {Rest, Config}); +finish(_) -> erlang:error(badarg). + + +%% insert a value when there's no parent object or array +insert(Value, {[], Config}) -> {Value, Config}; +%% insert a key or value into an object or array, autodetects the 'right' thing +insert(Key, {[{object, Map}|Rest], Config=#config{return_maps=true}}) -> + {[{object, Key, Map}] ++ Rest, Config}; +insert(Key, {[{object, Pairs}|Rest], Config}) -> + {[{object, Key, Pairs}] ++ Rest, Config}; +insert(Value, {[{object, Key, Map}|Rest], Config=#config{return_maps=true}}) -> + {[{object, maps:put(Key, Value, Map)}] ++ Rest, Config}; +insert(Value, {[{object, Key, Pairs}|Rest], Config}) -> + {[{object, [{Key, Value}] ++ Pairs}] ++ Rest, Config}; +insert(Value, {[{array, Values}|Rest], Config}) -> + {[{array, [Value] ++ Values}] ++ Rest, Config}; +insert(_, _) -> erlang:error(badarg). + +get_key({[{object, Key, _}|_], _}) -> Key; +get_key(_) -> erlang:error(badarg). + + +get_value({Value, _Config}) -> Value; +get_value(_) -> erlang:error(badarg). + + + +%% eunit tests + +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). + + +config_test_() -> + [ + {"empty config", ?_assertEqual(#config{}, parse_config([]))}, + {"implicit binary labels", ?_assertEqual(#config{}, parse_config([labels]))}, + {"binary labels", ?_assertEqual(#config{}, parse_config([{labels, binary}]))}, + {"atom labels", ?_assertEqual(#config{labels=atom}, parse_config([{labels, atom}]))}, + {"existing atom labels", ?_assertEqual( + #config{labels=existing_atom}, + parse_config([{labels, existing_atom}]) + )}, + {"return_maps true", ?_assertEqual( + #config{return_maps=true}, + parse_config([return_maps]) + )}, + {"invalid opt flag", ?_assertError(badarg, parse_config([error]))}, + {"invalid opt tuple", ?_assertError(badarg, parse_config([{error, true}]))} + ]. + + +format_key_test_() -> + [ + {"binary key", ?_assertEqual(<<"key">>, format_key(<<"key">>, #config{labels=binary}))}, + {"atom key", ?_assertEqual(key, format_key(<<"key">>, #config{labels=atom}))}, + {"existing atom key", ?_assertEqual( + key, + format_key(<<"key">>, #config{labels=existing_atom}) + )}, + {"nonexisting atom key", ?_assertError( + badarg, + format_key(<<"nonexistentatom">>, #config{labels=existing_atom}) + )}, + {"sloppy existing atom key", ?_assertEqual( + key, + format_key(<<"key">>, #config{labels=attempt_atom}) + )}, + {"nonexisting atom key", ?_assertEqual( + <<"nonexistentatom">>, + format_key(<<"nonexistentatom">>, #config{labels=attempt_atom}) + )} + ]. + + +rep_manipulation_test_() -> + [ + {"allocate a new context with option", ?_assertEqual( + {[], #config{labels=atom}}, + start_term([{labels, atom}]) + )}, + {"allocate a new object on an empty stack", ?_assertEqual( + {[{object, []}], #config{}}, + start_object({[], #config{}}) + )}, + {"allocate a new object on a stack", ?_assertEqual( + {[{object, []}, {object, []}], #config{}}, + start_object({[{object, []}], #config{}}) + )}, + {"allocate a new array on an empty stack", ?_assertEqual( + {[{array, []}], #config{}}, + start_array({[], #config{}}) + )}, + {"allocate a new array on a stack", ?_assertEqual( + {[{array, []}, {object, []}], #config{}}, + start_array({[{object, []}], #config{}}) + )}, + {"insert a key into an object", ?_assertEqual( + {[{object, key, []}, junk], #config{}}, + insert(key, {[{object, []}, junk], #config{}}) + )}, + {"get current key", ?_assertEqual( + key, + get_key({[{object, key, []}], #config{}}) + )}, + {"try to get non-key from object", ?_assertError( + badarg, + get_key({[{object, []}], #config{}}) + )}, + {"try to get key from array", ?_assertError( + badarg, + get_key({[{array, []}], #config{}}) + )}, + {"insert a value into an object", ?_assertEqual( + {[{object, [{key, value}]}, junk], #config{}}, + insert(value, {[{object, key, []}, junk], #config{}}) + )}, + {"insert a value into an array", ?_assertEqual( + {[{array, [value]}, junk], #config{}}, + insert(value, {[{array, []}, junk], #config{}}) + )}, + {"finish an object with no ancestor", ?_assertEqual( + {[{a, b}, {x, y}], #config{}}, + finish({[{object, [{x, y}, {a, b}]}], #config{}}) + )}, + {"finish an empty object", ?_assertEqual( + {[{}], #config{}}, + finish({[{object, []}], #config{}}) + )}, + {"finish an object with an ancestor", ?_assertEqual( + {[{object, [{key, [{a, b}, {x, y}]}, {foo, bar}]}], #config{}}, + finish({[{object, [{x, y}, {a, b}]}, {object, key, [{foo, bar}]}], #config{}}) + )}, + {"finish an array with no ancestor", ?_assertEqual( + {[a, b, c], #config{}}, + finish({[{array, [c, b, a]}], #config{}}) + )}, + {"finish an array with an ancestor", ?_assertEqual( + {[{array, [[a, b, c], d, e, f]}], #config{}}, + finish({[{array, [c, b, a]}, {array, [d, e, f]}], #config{}}) + )} + ]. + + +rep_manipulation_with_maps_test_() -> + [ + {"allocate a new object on an empty stack", ?_assertEqual( + {[{object, #{}}], #config{return_maps=true}}, + start_object({[], #config{return_maps=true}}) + )}, + {"allocate a new object on a stack", ?_assertEqual( + {[{object, #{}}, {object, #{}}], #config{return_maps=true}}, + start_object({[{object, #{}}], #config{return_maps=true}}) + )}, + {"insert a key into an object", ?_assertEqual( + {[{object, key, #{}}, junk], #config{return_maps=true}}, + insert(key, {[{object, #{}}, junk], #config{return_maps=true}}) + )}, + {"get current key", ?_assertEqual( + key, + get_key({[{object, key, #{}}], #config{return_maps=true}}) + )}, + {"try to get non-key from object", ?_assertError( + badarg, + get_key({[{object, #{}}], #config{return_maps=true}}) + )}, + {"insert a value into an object", ?_assertEqual( + {[{object, #{key => value}}, junk], #config{return_maps=true}}, + insert(value, {[{object, key, #{}}, junk], #config{return_maps=true}}) + )}, + {"finish an object with no ancestor", ?_assertEqual( + {#{a => b, x => y}, #config{return_maps=true}}, + finish({[{object, #{x => y, a => b}}], #config{return_maps=true}}) + )}, + {"finish an empty object", ?_assertEqual( + {#{}, #config{return_maps=true}}, + finish({[{object, #{}}], #config{return_maps=true}}) + )}, + {"finish an object with an ancestor", ?_assertEqual( + { + [{object, #{key => #{a => b, x => y}, foo => bar}}], + #config{return_maps=true} + }, + finish({ + [{object, #{x => y, a => b}}, {object, key, #{foo => bar}}], + #config{return_maps=true} + }) + )} + ]. + + +return_maps_test_() -> + [ + {"an empty map", ?_assertEqual( + #{}, + jsx:decode(<<"{}">>, []) + )}, + {"an empty map", ?_assertEqual( + #{}, + jsx:decode(<<"{}">>, []) + )}, + {"an empty map", ?_assertEqual( + [{}], + jsx:decode(<<"{}">>, [{return_maps, false}]) + )}, + {"a small map", ?_assertEqual( + #{<<"awesome">> => true, <<"library">> => <<"jsx">>}, + jsx:decode(<<"{\"library\": \"jsx\", \"awesome\": true}">>, []) + )}, + {"a recursive map", ?_assertEqual( + #{<<"key">> => #{<<"key">> => true}}, + jsx:decode(<<"{\"key\": {\"key\": true}}">>, []) + )}, + {"a map inside a list", ?_assertEqual( + [#{}], + jsx:decode(<<"[{}]">>, []) + )} + ]. + + +handle_event_test_() -> + Data = jsx:test_cases(), + [ + { + Title, ?_assertEqual( + Term, + lists:foldl(fun handle_event/2, init([]), Events ++ [end_json]) + ) + } || {Title, _, Term, Events} <- Data + ]. + + +-endif. diff --git a/deps/jsx/src/jsx_verify.erl b/deps/jsx/src/jsx_verify.erl new file mode 100644 index 0000000000000000000000000000000000000000..5eef4d2906be1ff8edb7917dfd796362a72ba54c --- /dev/null +++ b/deps/jsx/src/jsx_verify.erl @@ -0,0 +1,121 @@ +%% The MIT License + +%% Copyright (c) 2010-2013 alisdair sullivan + +%% Permission is hereby granted, free of charge, to any person obtaining a copy +%% of this software and associated documentation files (the "Software"), to deal +%% in the Software without restriction, including without limitation the rights +%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +%% copies of the Software, and to permit persons to whom the Software is +%% furnished to do so, subject to the following conditions: + +%% The above copyright notice and this permission notice shall be included in +%% all copies or substantial portions of the Software. + +%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +%% THE SOFTWARE. + + +-module(jsx_verify). + +-export([is_json/2, is_term/2]). +-export([init/1, handle_event/2]). + +-type config() :: proplists:proplist(). + +-spec is_json(Source::binary(), Config::jsx_config:options()) -> true | false | {incomplete, jsx:decoder()}. + +is_json(Source, Config) when is_list(Config) -> + try (jsx:decoder(?MODULE, Config, jsx_config:extract_config(Config)))(Source) + catch error:badarg -> false + end. + + +-spec is_term(Source::jsx:json_term() | end_stream | end_json, + Config::jsx_config:options()) -> true | false | {incomplete, jsx:encoder()}. + +is_term(Source, Config) when is_list(Config) -> + try (jsx:encoder(?MODULE, Config, jsx_config:extract_config(Config)))(Source) + catch error:badarg -> false + end. + + +parse_config(Config) -> parse_config(Config, []). + +%% ignore deprecated flags +parse_config([no_repeated_keys|Rest], Config) -> + parse_config(Rest, Config); +parse_config([{repeated_keys, Val}|Rest], Config) when Val == true; Val == false -> + parse_config(Rest, Config); +parse_config([repeated_keys|Rest], Config) -> + parse_config(Rest, Config); +parse_config([{K, _}|Rest] = Options, Config) -> + case lists:member(K, jsx_config:valid_flags()) of + true -> parse_config(Rest, Config); + false -> erlang:error(badarg, [Options, Config]) + end; +parse_config([K|Rest] = Options, Config) -> + case lists:member(K, jsx_config:valid_flags()) of + true -> parse_config(Rest, Config); + false -> erlang:error(badarg, [Options, Config]) + end; +parse_config([], Config) -> + Config. + + +%% we don't actually need any state for this +-type state() :: []. +-spec init(Config::config()) -> state(). + +init(Config) -> parse_config(Config). + + +-spec handle_event(Event::any(), State::state()) -> state(). + +handle_event(end_json, _) -> true; + +handle_event(_, State) -> State. + + + +%% eunit tests +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). + + +config_test_() -> + [ + {"empty config", ?_assertEqual([], parse_config([]))}, + {"no repeat keys", ?_assertEqual([], parse_config([no_repeated_keys]))}, + {"bare repeated keys", ?_assertEqual([], parse_config([repeated_keys]))}, + {"repeated keys true", ?_assertEqual( + [], + parse_config([{repeated_keys, true}]) + )}, + {"repeated keys false", ?_assertEqual( + [], + parse_config([{repeated_keys, false}]) + )}, + {"invalid opt flag", ?_assertError(badarg, parse_config([error]))}, + {"invalid opt tuple", ?_assertError(badarg, parse_config([{error, true}]))} + ]. + + +handle_event_test_() -> + Data = jsx:test_cases() ++ jsx:special_test_cases(), + [ + { + Title, ?_assertEqual( + true, + lists:foldl(fun handle_event/2, [], Events ++ [end_json]) + ) + } || {Title, _, _, Events} <- Data + ]. + + +-endif. diff --git a/deps/phoenix_live_view/assets/js/phoenix_live_view/aria.js b/deps/phoenix_live_view/assets/js/phoenix_live_view/aria.js new file mode 100644 index 0000000000000000000000000000000000000000..f5308cad0bb85abd68321296a3940fb4e27551f2 --- /dev/null +++ b/deps/phoenix_live_view/assets/js/phoenix_live_view/aria.js @@ -0,0 +1,66 @@ +const ARIA = { + anyOf(instance, classes) { + return classes.find((name) => instance instanceof name); + }, + + isFocusable(el, interactiveOnly) { + return ( + (el instanceof HTMLAnchorElement && el.rel !== "ignore") || + (el instanceof HTMLAreaElement && el.href !== undefined) || + (!el.disabled && + this.anyOf(el, [ + HTMLInputElement, + HTMLSelectElement, + HTMLTextAreaElement, + HTMLButtonElement, + ])) || + el instanceof HTMLIFrameElement || + (el.tabIndex >= 0 && el.getAttribute("aria-hidden") !== "true") || + (!interactiveOnly && + el.getAttribute("tabindex") !== null && + el.getAttribute("aria-hidden") !== "true") + ); + }, + + attemptFocus(el, interactiveOnly) { + if (this.isFocusable(el, interactiveOnly)) { + try { + el.focus(); + } catch { + // that's fine + } + } + return !!document.activeElement && document.activeElement.isSameNode(el); + }, + + focusFirstInteractive(el) { + let child = el.firstElementChild; + while (child) { + if (this.attemptFocus(child, true) || this.focusFirstInteractive(child)) { + return true; + } + child = child.nextElementSibling; + } + }, + + focusFirst(el) { + let child = el.firstElementChild; + while (child) { + if (this.attemptFocus(child) || this.focusFirst(child)) { + return true; + } + child = child.nextElementSibling; + } + }, + + focusLast(el) { + let child = el.lastElementChild; + while (child) { + if (this.attemptFocus(child) || this.focusLast(child)) { + return true; + } + child = child.previousElementSibling; + } + }, +}; +export default ARIA; diff --git a/deps/phoenix_live_view/assets/js/phoenix_live_view/browser.js b/deps/phoenix_live_view/assets/js/phoenix_live_view/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..f1a3929546e58e49c8bb7e92e60ac98babd36417 --- /dev/null +++ b/deps/phoenix_live_view/assets/js/phoenix_live_view/browser.js @@ -0,0 +1,111 @@ +const Browser = { + canPushState() { + return typeof history.pushState !== "undefined"; + }, + + dropLocal(localStorage, namespace, subkey) { + return localStorage.removeItem(this.localKey(namespace, subkey)); + }, + + updateLocal(localStorage, namespace, subkey, initial, func) { + const current = this.getLocal(localStorage, namespace, subkey); + const key = this.localKey(namespace, subkey); + const newVal = current === null ? initial : func(current); + localStorage.setItem(key, JSON.stringify(newVal)); + return newVal; + }, + + getLocal(localStorage, namespace, subkey) { + return JSON.parse(localStorage.getItem(this.localKey(namespace, subkey))); + }, + + updateCurrentState(callback) { + if (!this.canPushState()) { + return; + } + history.replaceState( + callback(history.state || {}), + "", + window.location.href, + ); + }, + + pushState(kind, meta, to) { + if (this.canPushState()) { + if (to !== window.location.href) { + if (meta.type == "redirect" && meta.scroll) { + // If we're redirecting store the current scrollY for the current history state. + const currentState = history.state || {}; + currentState.scroll = meta.scroll; + history.replaceState(currentState, "", window.location.href); + } + + delete meta.scroll; // Only store the scroll in the redirect case. + history[kind + "State"](meta, "", to || null); // IE will coerce undefined to string + + // when using navigate, we'd call pushState immediately before patching the DOM, + // jumping back to the top of the page, effectively ignoring the scrollIntoView; + // therefore we wait for the next frame (after the DOM patch) and only then try + // to scroll to the hashEl + window.requestAnimationFrame(() => { + const hashEl = this.getHashTargetEl(window.location.hash); + + if (hashEl) { + hashEl.scrollIntoView(); + } else if (meta.type === "redirect") { + window.scroll(0, 0); + } + }); + } + } else { + this.redirect(to); + } + }, + + setCookie(name, value, maxAgeSeconds) { + const expires = + typeof maxAgeSeconds === "number" ? ` max-age=${maxAgeSeconds};` : ""; + document.cookie = `${name}=${value};${expires} path=/`; + }, + + getCookie(name) { + return document.cookie.replace( + new RegExp(`(?:(?:^|.*;\s*)${name}\s*\=\s*([^;]*).*$)|^.*$`), + "$1", + ); + }, + + deleteCookie(name) { + document.cookie = `${name}=; max-age=-1; path=/`; + }, + + redirect( + toURL, + flash, + navigate = (url) => { + window.location.href = url; + }, + ) { + if (flash) { + this.setCookie("__phoenix_flash__", flash, 60); + } + navigate(toURL); + }, + + localKey(namespace, subkey) { + return `${namespace}-${subkey}`; + }, + + getHashTargetEl(maybeHash) { + const hash = maybeHash.toString().substring(1); + if (hash === "") { + return; + } + return ( + document.getElementById(hash) || + document.querySelector(`a[name="${hash}"]`) + ); + }, +}; + +export default Browser; diff --git a/deps/phoenix_live_view/assets/js/phoenix_live_view/constants.js b/deps/phoenix_live_view/assets/js/phoenix_live_view/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..730ca7cf270138de597329c0e7130ed09e93ca54 --- /dev/null +++ b/deps/phoenix_live_view/assets/js/phoenix_live_view/constants.js @@ -0,0 +1,121 @@ +export const CONSECUTIVE_RELOADS = "consecutive-reloads"; +export const MAX_RELOADS = 10; +export const RELOAD_JITTER_MIN = 5000; +export const RELOAD_JITTER_MAX = 10000; +export const FAILSAFE_JITTER = 30000; +export const PHX_EVENT_CLASSES = [ + "phx-click-loading", + "phx-change-loading", + "phx-submit-loading", + "phx-keydown-loading", + "phx-keyup-loading", + "phx-blur-loading", + "phx-focus-loading", + "phx-hook-loading", +]; +export const PHX_DROP_TARGET_ACTIVE_CLASS = "phx-drop-target-active"; +export const PHX_COMPONENT = "data-phx-component"; +export const PHX_VIEW_REF = "data-phx-view"; +export const PHX_LIVE_LINK = "data-phx-link"; +export const PHX_TRACK_STATIC = "track-static"; +export const PHX_LINK_STATE = "data-phx-link-state"; +export const PHX_REF_LOADING = "data-phx-ref-loading"; +export const PHX_REF_SRC = "data-phx-ref-src"; +export const PHX_REF_LOCK = "data-phx-ref-lock"; +export const PHX_PENDING_REFS = "phx-pending-refs"; +export const PHX_TRACK_UPLOADS = "track-uploads"; +export const PHX_UPLOAD_REF = "data-phx-upload-ref"; +export const PHX_PREFLIGHTED_REFS = "data-phx-preflighted-refs"; +export const PHX_DONE_REFS = "data-phx-done-refs"; +export const PHX_DROP_TARGET = "drop-target"; +export const PHX_ACTIVE_ENTRY_REFS = "data-phx-active-refs"; +export const PHX_LIVE_FILE_UPDATED = "phx:live-file:updated"; +export const PHX_SKIP = "data-phx-skip"; +export const PHX_MAGIC_ID = "data-phx-id"; +export const PHX_PRUNE = "data-phx-prune"; +export const PHX_CONNECTED_CLASS = "phx-connected"; +export const PHX_LOADING_CLASS = "phx-loading"; +export const PHX_ERROR_CLASS = "phx-error"; +export const PHX_CLIENT_ERROR_CLASS = "phx-client-error"; +export const PHX_SERVER_ERROR_CLASS = "phx-server-error"; +export const PHX_PARENT_ID = "data-phx-parent-id"; +export const PHX_MAIN = "data-phx-main"; +export const PHX_ROOT_ID = "data-phx-root-id"; +export const PHX_VIEWPORT_TOP = "viewport-top"; +export const PHX_VIEWPORT_BOTTOM = "viewport-bottom"; +export const PHX_VIEWPORT_OVERRUN_TARGET = "viewport-overrun-target"; +export const PHX_TRIGGER_ACTION = "trigger-action"; +export const PHX_HAS_FOCUSED = "phx-has-focused"; +export const FOCUSABLE_INPUTS = [ + "text", + "textarea", + "number", + "email", + "password", + "search", + "tel", + "url", + "date", + "time", + "datetime-local", + "color", + "range", +]; +export const CHECKABLE_INPUTS = ["checkbox", "radio"]; +export const PHX_HAS_SUBMITTED = "phx-has-submitted"; +export const PHX_SESSION = "data-phx-session"; +export const PHX_VIEW_SELECTOR = `[${PHX_SESSION}]`; +export const PHX_STICKY = "data-phx-sticky"; +export const PHX_STATIC = "data-phx-static"; +export const PHX_READONLY = "data-phx-readonly"; +export const PHX_DISABLED = "data-phx-disabled"; +export const PHX_DISABLE_WITH = "disable-with"; +export const PHX_DISABLE_WITH_RESTORE = "data-phx-disable-with-restore"; +export const PHX_HOOK = "hook"; +export const PHX_DEBOUNCE = "debounce"; +export const PHX_THROTTLE = "throttle"; +export const PHX_UPDATE = "update"; +export const PHX_STREAM = "stream"; +export const PHX_STREAM_REF = "data-phx-stream"; +export const PHX_PORTAL = "data-phx-portal"; +export const PHX_TELEPORTED_REF = "data-phx-teleported"; +export const PHX_TELEPORTED_SRC = "data-phx-teleported-src"; +export const PHX_RUNTIME_HOOK = "data-phx-runtime-hook"; +export const PHX_LV_PID = "data-phx-pid"; +export const PHX_KEY = "key"; +export const PHX_PRIVATE = "phxPrivate"; +export const PHX_AUTO_RECOVER = "auto-recover"; +export const PHX_LV_DEBUG = "phx:live-socket:debug"; +export const PHX_LV_PROFILE = "phx:live-socket:profiling"; +export const PHX_LV_LATENCY_SIM = "phx:live-socket:latency-sim"; +export const PHX_LV_HISTORY_POSITION = "phx:nav-history-position"; +export const PHX_PROGRESS = "progress"; +export const PHX_MOUNTED = "mounted"; +export const PHX_RELOAD_STATUS = "__phoenix_reload_status__"; +export const LOADER_TIMEOUT = 1; +export const MAX_CHILD_JOIN_ATTEMPTS = 3; +export const BEFORE_UNLOAD_LOADER_TIMEOUT = 200; +export const DISCONNECTED_TIMEOUT = 500; +export const BINDING_PREFIX = "phx-"; +export const PUSH_TIMEOUT = 30000; +export const LINK_HEADER = "x-requested-with"; +export const RESPONSE_URL_HEADER = "x-response-url"; +export const DEBOUNCE_TRIGGER = "debounce-trigger"; +export const THROTTLED = "throttled"; +export const DEBOUNCE_PREV_KEY = "debounce-prev-key"; +export const DEFAULTS = { + debounce: 300, + throttle: 300, +}; +export const PHX_PENDING_ATTRS = [PHX_REF_LOADING, PHX_REF_SRC, PHX_REF_LOCK]; +// Rendered +export const STATIC = "s"; +export const ROOT = "r"; +export const COMPONENTS = "c"; +export const KEYED = "k"; +export const KEYED_COUNT = "kc"; +export const EVENTS = "e"; +export const REPLY = "r"; +export const TITLE = "t"; +export const TEMPLATES = "p"; +export const STREAM = "stream"; diff --git a/deps/phoenix_live_view/assets/js/phoenix_live_view/dom.js b/deps/phoenix_live_view/assets/js/phoenix_live_view/dom.js new file mode 100644 index 0000000000000000000000000000000000000000..87c57f90b473b51b54634004bea3a87509135a47 --- /dev/null +++ b/deps/phoenix_live_view/assets/js/phoenix_live_view/dom.js @@ -0,0 +1,765 @@ +import { + CHECKABLE_INPUTS, + DEBOUNCE_PREV_KEY, + DEBOUNCE_TRIGGER, + FOCUSABLE_INPUTS, + PHX_COMPONENT, + PHX_VIEW_REF, + PHX_TELEPORTED_REF, + PHX_HAS_FOCUSED, + PHX_HAS_SUBMITTED, + PHX_MAIN, + PHX_PARENT_ID, + PHX_PRIVATE, + PHX_REF_SRC, + PHX_REF_LOCK, + PHX_PENDING_ATTRS, + PHX_ROOT_ID, + PHX_SESSION, + PHX_STATIC, + PHX_UPLOAD_REF, + PHX_VIEW_SELECTOR, + PHX_STICKY, + PHX_EVENT_CLASSES, + THROTTLED, + PHX_PORTAL, + PHX_STREAM, +} from "./constants"; + +import { logError } from "./utils"; + +const DOM = { + byId(id) { + return document.getElementById(id) || logError(`no id found for ${id}`); + }, + + removeClass(el, className) { + el.classList.remove(className); + if (el.classList.length === 0) { + el.removeAttribute("class"); + } + }, + + all(node, query, callback) { + if (!node) { + return []; + } + const array = Array.from(node.querySelectorAll(query)); + if (callback) { + array.forEach(callback); + } + return array; + }, + + childNodeLength(html) { + const template = document.createElement("template"); + template.innerHTML = html; + return template.content.childElementCount; + }, + + isUploadInput(el) { + return el.type === "file" && el.getAttribute(PHX_UPLOAD_REF) !== null; + }, + + isAutoUpload(inputEl) { + return inputEl.hasAttribute("data-phx-auto-upload"); + }, + + findUploadInputs(node) { + const formId = node.id; + const inputsOutsideForm = this.all( + document, + `input[type="file"][${PHX_UPLOAD_REF}][form="${formId}"]`, + ); + return this.all(node, `input[type="file"][${PHX_UPLOAD_REF}]`).concat( + inputsOutsideForm, + ); + }, + + findComponentNodeList(viewId, cid, doc = document) { + return this.all( + doc, + `[${PHX_VIEW_REF}="${viewId}"][${PHX_COMPONENT}="${cid}"]`, + ); + }, + + isPhxDestroyed(node) { + return node.id && DOM.private(node, "destroyed") ? true : false; + }, + + wantsNewTab(e) { + const wantsNewTab = + e.ctrlKey || e.shiftKey || e.metaKey || (e.button && e.button === 1); + const isDownload = + e.target instanceof HTMLAnchorElement && + e.target.hasAttribute("download"); + const isTargetBlank = + e.target.hasAttribute("target") && + e.target.getAttribute("target").toLowerCase() === "_blank"; + const isTargetNamedTab = + e.target.hasAttribute("target") && + !e.target.getAttribute("target").startsWith("_"); + return wantsNewTab || isTargetBlank || isDownload || isTargetNamedTab; + }, + + isUnloadableFormSubmit(e) { + // Ignore form submissions intended to close a native element + // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog#usage_notes + const isDialogSubmit = + (e.target && e.target.getAttribute("method") === "dialog") || + (e.submitter && e.submitter.getAttribute("formmethod") === "dialog"); + + if (isDialogSubmit) { + return false; + } else { + return !e.defaultPrevented && !this.wantsNewTab(e); + } + }, + + isNewPageClick(e, currentLocation) { + const href = + e.target instanceof HTMLAnchorElement + ? e.target.getAttribute("href") + : null; + let url; + + if (e.defaultPrevented || href === null || this.wantsNewTab(e)) { + return false; + } + if (href.startsWith("mailto:") || href.startsWith("tel:")) { + return false; + } + if (e.target.isContentEditable) { + return false; + } + + try { + url = new URL(href); + } catch { + try { + url = new URL(href, currentLocation); + } catch { + // bad URL, fallback to let browser try it as external + return true; + } + } + + if ( + url.host === currentLocation.host && + url.protocol === currentLocation.protocol + ) { + if ( + url.pathname === currentLocation.pathname && + url.search === currentLocation.search + ) { + return url.hash === "" && !url.href.endsWith("#"); + } + } + return url.protocol.startsWith("http"); + }, + + markPhxChildDestroyed(el) { + if (this.isPhxChild(el)) { + el.setAttribute(PHX_SESSION, ""); + } + this.putPrivate(el, "destroyed", true); + }, + + findPhxChildrenInFragment(html, parentId) { + const template = document.createElement("template"); + template.innerHTML = html; + return this.findPhxChildren(template.content, parentId); + }, + + isIgnored(el, phxUpdate) { + return ( + (el.getAttribute(phxUpdate) || el.getAttribute("data-phx-update")) === + "ignore" + ); + }, + + isPhxUpdate(el, phxUpdate, updateTypes) { + return ( + el.getAttribute && updateTypes.indexOf(el.getAttribute(phxUpdate)) >= 0 + ); + }, + + findPhxSticky(el) { + return this.all(el, `[${PHX_STICKY}]`); + }, + + findPhxChildren(el, parentId) { + return this.all(el, `${PHX_VIEW_SELECTOR}[${PHX_PARENT_ID}="${parentId}"]`); + }, + + findExistingParentCIDs(viewId, cids) { + // we only want to find parents that exist on the page + // if a cid is not on the page, the only way it can be added back to the page + // is if a parent adds it back, therefore if a cid does not exist on the page, + // we should not try to render it by itself (because it would be rendered twice, + // one by the parent, and a second time by itself) + const parentCids = new Set(); + const childrenCids = new Set(); + + cids.forEach((cid) => { + this.all( + document, + `[${PHX_VIEW_REF}="${viewId}"][${PHX_COMPONENT}="${cid}"]`, + ).forEach((parent) => { + parentCids.add(cid); + this.all(parent, `[${PHX_VIEW_REF}="${viewId}"][${PHX_COMPONENT}]`) + .map((el) => parseInt(el.getAttribute(PHX_COMPONENT))) + .forEach((childCID) => childrenCids.add(childCID)); + }); + }); + + childrenCids.forEach((childCid) => parentCids.delete(childCid)); + + return parentCids; + }, + + private(el, key) { + return el[PHX_PRIVATE] && el[PHX_PRIVATE][key]; + }, + + deletePrivate(el, key) { + el[PHX_PRIVATE] && delete el[PHX_PRIVATE][key]; + }, + + putPrivate(el, key, value) { + if (!el[PHX_PRIVATE]) { + el[PHX_PRIVATE] = {}; + } + el[PHX_PRIVATE][key] = value; + }, + + updatePrivate(el, key, defaultVal, updateFunc) { + const existing = this.private(el, key); + if (existing === undefined) { + this.putPrivate(el, key, updateFunc(defaultVal)); + } else { + this.putPrivate(el, key, updateFunc(existing)); + } + }, + + syncPendingAttrs(fromEl, toEl) { + if (!fromEl.hasAttribute(PHX_REF_SRC)) { + return; + } + PHX_EVENT_CLASSES.forEach((className) => { + fromEl.classList.contains(className) && toEl.classList.add(className); + }); + PHX_PENDING_ATTRS.filter((attr) => fromEl.hasAttribute(attr)).forEach( + (attr) => { + toEl.setAttribute(attr, fromEl.getAttribute(attr)); + }, + ); + }, + + copyPrivates(target, source) { + if (source[PHX_PRIVATE]) { + target[PHX_PRIVATE] = source[PHX_PRIVATE]; + } + }, + + putTitle(str) { + const titleEl = document.querySelector("title"); + if (titleEl) { + const { prefix, suffix, default: defaultTitle } = titleEl.dataset; + const isEmpty = typeof str !== "string" || str.trim() === ""; + if (isEmpty && typeof defaultTitle !== "string") { + return; + } + + const inner = isEmpty ? defaultTitle : str; + document.title = `${prefix || ""}${inner || ""}${suffix || ""}`; + } else { + document.title = str; + } + }, + + debounce( + el, + event, + phxDebounce, + defaultDebounce, + phxThrottle, + defaultThrottle, + asyncFilter, + callback, + ) { + let debounce = el.getAttribute(phxDebounce); + let throttle = el.getAttribute(phxThrottle); + + if (debounce === "") { + debounce = defaultDebounce; + } + if (throttle === "") { + throttle = defaultThrottle; + } + const value = debounce || throttle; + switch (value) { + case null: + return callback(); + + case "blur": + this.incCycle(el, "debounce-blur-cycle", () => { + if (asyncFilter()) { + callback(); + } + }); + if (this.once(el, "debounce-blur")) { + el.addEventListener("blur", () => + this.triggerCycle(el, "debounce-blur-cycle"), + ); + } + return; + + default: + const timeout = parseInt(value); + const trigger = () => + throttle ? this.deletePrivate(el, THROTTLED) : callback(); + const currentCycle = this.incCycle(el, DEBOUNCE_TRIGGER, trigger); + if (isNaN(timeout)) { + return logError(`invalid throttle/debounce value: ${value}`); + } + if (throttle) { + let newKeyDown = false; + if (event.type === "keydown") { + const prevKey = this.private(el, DEBOUNCE_PREV_KEY); + this.putPrivate(el, DEBOUNCE_PREV_KEY, event.key); + newKeyDown = prevKey !== event.key; + } + + if (!newKeyDown && this.private(el, THROTTLED)) { + return false; + } else { + callback(); + const t = setTimeout(() => { + if (asyncFilter()) { + this.triggerCycle(el, DEBOUNCE_TRIGGER); + } + }, timeout); + this.putPrivate(el, THROTTLED, t); + } + } else { + setTimeout(() => { + if (asyncFilter()) { + this.triggerCycle(el, DEBOUNCE_TRIGGER, currentCycle); + } + }, timeout); + } + + const form = el.form; + if (form && this.once(form, "bind-debounce")) { + form.addEventListener("submit", () => { + Array.from(new FormData(form).entries(), ([name]) => { + const namedItem = form.elements.namedItem(name); + const input = + namedItem instanceof RadioNodeList ? namedItem[0] : namedItem; + if (input) { + this.incCycle(input, DEBOUNCE_TRIGGER); + this.deletePrivate(input, THROTTLED); + } + }); + }); + } + if (this.once(el, "bind-debounce")) { + el.addEventListener("blur", () => { + // because we trigger the callback here, + // we also clear the throttle timeout to prevent the callback + // from being called again after the timeout fires + clearTimeout(this.private(el, THROTTLED)); + this.triggerCycle(el, DEBOUNCE_TRIGGER); + }); + } + } + }, + + triggerCycle(el, key, currentCycle) { + const [cycle, trigger] = this.private(el, key); + if (!currentCycle) { + currentCycle = cycle; + } + if (currentCycle === cycle) { + this.incCycle(el, key); + trigger(); + } + }, + + once(el, key) { + if (this.private(el, key) === true) { + return false; + } + this.putPrivate(el, key, true); + return true; + }, + + incCycle(el, key, trigger = function () {}) { + let [currentCycle] = this.private(el, key) || [0, trigger]; + currentCycle++; + this.putPrivate(el, key, [currentCycle, trigger]); + return currentCycle; + }, + + // maintains or adds privately used hook information + // fromEl and toEl can be the same element in the case of a newly added node + // fromEl and toEl can be any HTML node type, so we need to check if it's an element node + maintainPrivateHooks(fromEl, toEl, phxViewportTop, phxViewportBottom) { + // maintain the hooks created with createHook + if ( + fromEl.hasAttribute && + fromEl.hasAttribute("data-phx-hook") && + !toEl.hasAttribute("data-phx-hook") + ) { + toEl.setAttribute("data-phx-hook", fromEl.getAttribute("data-phx-hook")); + } + // add hooks to elements with viewport attributes + if ( + toEl.hasAttribute && + (toEl.hasAttribute(phxViewportTop) || + toEl.hasAttribute(phxViewportBottom)) + ) { + toEl.setAttribute("data-phx-hook", "Phoenix.InfiniteScroll"); + } + }, + + putCustomElHook(el, hook) { + if (el.isConnected) { + el.setAttribute("data-phx-hook", ""); + } else { + console.error(` + hook attached to non-connected DOM element + ensure you are calling createHook within your connectedCallback. ${el.outerHTML} + `); + } + this.putPrivate(el, "custom-el-hook", hook); + }, + + getCustomElHook(el) { + return this.private(el, "custom-el-hook"); + }, + + isUsedInput(el) { + return ( + el.nodeType === Node.ELEMENT_NODE && + (this.private(el, PHX_HAS_FOCUSED) || this.private(el, PHX_HAS_SUBMITTED)) + ); + }, + + resetForm(form) { + Array.from(form.elements).forEach((input) => { + this.deletePrivate(input, PHX_HAS_FOCUSED); + this.deletePrivate(input, PHX_HAS_SUBMITTED); + }); + }, + + isPhxChild(node) { + return node.getAttribute && node.getAttribute(PHX_PARENT_ID); + }, + + isPhxSticky(node) { + return node.getAttribute && node.getAttribute(PHX_STICKY) !== null; + }, + + isChildOfAny(el, parents) { + return !!parents.find((parent) => parent.contains(el)); + }, + + firstPhxChild(el) { + return this.isPhxChild(el) ? el : this.all(el, `[${PHX_PARENT_ID}]`)[0]; + }, + + isPortalTemplate(el) { + return el.tagName === "TEMPLATE" && el.hasAttribute(PHX_PORTAL); + }, + + closestViewEl(el) { + // find the closest portal or view element, whichever comes first + const portalOrViewEl = el.closest( + `[${PHX_TELEPORTED_REF}],${PHX_VIEW_SELECTOR}`, + ); + if (!portalOrViewEl) { + return null; + } + if (portalOrViewEl.hasAttribute(PHX_TELEPORTED_REF)) { + // PHX_TELEPORTED_REF is set to the id of the view that owns the portal element + return this.byId(portalOrViewEl.getAttribute(PHX_TELEPORTED_REF)); + } else if (portalOrViewEl.hasAttribute(PHX_SESSION)) { + return portalOrViewEl; + } + return null; + }, + + dispatchEvent(target, name, opts = {}) { + let defaultBubble = true; + const isUploadTarget = + target.nodeName === "INPUT" && target.type === "file"; + if (isUploadTarget && name === "click") { + defaultBubble = false; + } + const bubbles = opts.bubbles === undefined ? defaultBubble : !!opts.bubbles; + const eventOpts = { + bubbles: bubbles, + cancelable: true, + detail: opts.detail || {}, + }; + const event = + name === "click" + ? new MouseEvent("click", eventOpts) + : new CustomEvent(name, eventOpts); + target.dispatchEvent(event); + }, + + cloneNode(node, html) { + if (typeof html === "undefined") { + return node.cloneNode(true); + } else { + const cloned = node.cloneNode(false); + cloned.innerHTML = html; + return cloned; + } + }, + + // merge attributes from source to target + // if an element is ignored, we only merge data attributes + // including removing data attributes that are no longer in the source + mergeAttrs(target, source, opts = {}) { + const exclude = new Set(opts.exclude || []); + const isIgnored = opts.isIgnored; + const sourceAttrs = source.attributes; + for (let i = sourceAttrs.length - 1; i >= 0; i--) { + const name = sourceAttrs[i].name; + if (!exclude.has(name)) { + const sourceValue = source.getAttribute(name); + if ( + target.getAttribute(name) !== sourceValue && + (!isIgnored || (isIgnored && name.startsWith("data-"))) + ) { + target.setAttribute(name, sourceValue); + } + } else { + // We exclude the value from being merged on focused inputs, because the + // user's input should always win. + // We can still assign it as long as the value property is the same, though. + // This prevents a situation where the updated hook is not being triggered + // when an input is back in its "original state", because the attribute + // was never changed, see: + // https://github.com/phoenixframework/phoenix_live_view/issues/2163 + if (name === "value") { + const sourceValue = source.value ?? source.getAttribute(name); + if (target.value === sourceValue) { + // actually set the value attribute to sync it with the value property + target.setAttribute("value", source.getAttribute(name)); + } + } + } + } + + const targetAttrs = target.attributes; + for (let i = targetAttrs.length - 1; i >= 0; i--) { + const name = targetAttrs[i].name; + if (isIgnored) { + if ( + name.startsWith("data-") && + !source.hasAttribute(name) && + !PHX_PENDING_ATTRS.includes(name) + ) { + target.removeAttribute(name); + } + } else { + if (!source.hasAttribute(name)) { + target.removeAttribute(name); + } + } + } + }, + + mergeFocusedInput(target, source) { + // skip selects because FF will reset highlighted index for any setAttribute + if (!(target instanceof HTMLSelectElement)) { + DOM.mergeAttrs(target, source, { exclude: ["value"] }); + } + + if (source.readOnly) { + target.setAttribute("readonly", true); + } else { + target.removeAttribute("readonly"); + } + }, + + hasSelectionRange(el) { + return ( + el.setSelectionRange && (el.type === "text" || el.type === "textarea") + ); + }, + + restoreFocus(focused, selectionStart, selectionEnd) { + if (focused instanceof HTMLSelectElement) { + focused.focus(); + } + if (!DOM.isTextualInput(focused)) { + return; + } + + const wasFocused = focused.matches(":focus"); + if (!wasFocused) { + focused.focus(); + } + if (this.hasSelectionRange(focused)) { + focused.setSelectionRange(selectionStart, selectionEnd); + } + }, + + isFormInput(el) { + if (el.localName && customElements.get(el.localName)) { + // Custom Elements may be form associated. This allows them + // to participate within a form's lifecycle, including form + // validity and form submissions. + // The spec for Form Associated custom elements requires the + // custom element's class to contain a static boolean value of `formAssociated` + // which identifies this class as allowed to associate to a form. + // See https://html.spec.whatwg.org/dev/custom-elements.html#custom-elements-face-example + // for details. + return customElements.get(el.localName)[`formAssociated`]; + } + + return ( + /^(?:input|select|textarea)$/i.test(el.tagName) && el.type !== "button" + ); + }, + + syncAttrsToProps(el) { + if ( + el instanceof HTMLInputElement && + CHECKABLE_INPUTS.indexOf(el.type.toLocaleLowerCase()) >= 0 + ) { + el.checked = el.getAttribute("checked") !== null; + } + }, + + isTextualInput(el) { + return FOCUSABLE_INPUTS.indexOf(el.type) >= 0; + }, + + isNowTriggerFormExternal(el, phxTriggerExternal) { + return ( + el.getAttribute && + el.getAttribute(phxTriggerExternal) !== null && + document.body.contains(el) + ); + }, + + cleanChildNodes(container, phxUpdate) { + if ( + DOM.isPhxUpdate(container, phxUpdate, ["append", "prepend", PHX_STREAM]) + ) { + const toRemove = []; + container.childNodes.forEach((childNode) => { + if (!childNode.id) { + // Skip warning if it's an empty text node (e.g. a new-line) + const isEmptyTextNode = + childNode.nodeType === Node.TEXT_NODE && + childNode.nodeValue.trim() === ""; + if (!isEmptyTextNode && childNode.nodeType !== Node.COMMENT_NODE) { + logError( + "only HTML element tags with an id are allowed inside containers with phx-update.\n\n" + + `removing illegal node: "${(childNode.outerHTML || childNode.nodeValue).trim()}"\n\n`, + ); + } + toRemove.push(childNode); + } + }); + toRemove.forEach((childNode) => childNode.remove()); + } + }, + + replaceRootContainer(container, tagName, attrs) { + const retainedAttrs = new Set([ + "id", + PHX_SESSION, + PHX_STATIC, + PHX_MAIN, + PHX_ROOT_ID, + ]); + if (container.tagName.toLowerCase() === tagName.toLowerCase()) { + Array.from(container.attributes) + .filter((attr) => !retainedAttrs.has(attr.name.toLowerCase())) + .forEach((attr) => container.removeAttribute(attr.name)); + + Object.keys(attrs) + .filter((name) => !retainedAttrs.has(name.toLowerCase())) + .forEach((attr) => container.setAttribute(attr, attrs[attr])); + + return container; + } else { + const newContainer = document.createElement(tagName); + Object.keys(attrs).forEach((attr) => + newContainer.setAttribute(attr, attrs[attr]), + ); + retainedAttrs.forEach((attr) => + newContainer.setAttribute(attr, container.getAttribute(attr)), + ); + newContainer.innerHTML = container.innerHTML; + container.replaceWith(newContainer); + return newContainer; + } + }, + + getSticky(el, name, defaultVal) { + const op = (DOM.private(el, "sticky") || []).find( + ([existingName]) => name === existingName, + ); + if (op) { + const [_name, _op, stashedResult] = op; + return stashedResult; + } else { + return typeof defaultVal === "function" ? defaultVal() : defaultVal; + } + }, + + deleteSticky(el, name) { + this.updatePrivate(el, "sticky", [], (ops) => { + return ops.filter(([existingName, _]) => existingName !== name); + }); + }, + + putSticky(el, name, op) { + const stashedResult = op(el); + this.updatePrivate(el, "sticky", [], (ops) => { + const existingIndex = ops.findIndex( + ([existingName]) => name === existingName, + ); + if (existingIndex >= 0) { + ops[existingIndex] = [name, op, stashedResult]; + } else { + ops.push([name, op, stashedResult]); + } + return ops; + }); + }, + + applyStickyOperations(el) { + const ops = DOM.private(el, "sticky"); + if (!ops) { + return; + } + + ops.forEach(([name, op, _stashed]) => this.putSticky(el, name, op)); + }, + + isLocked(el) { + return el.hasAttribute && el.hasAttribute(PHX_REF_LOCK); + }, + + attributeIgnored(attribute, ignoredAttributes) { + return ignoredAttributes.some( + (toIgnore) => + attribute.name == toIgnore || + toIgnore === "*" || + (toIgnore.includes("*") && attribute.name.match(toIgnore) != null), + ); + }, +}; + +export default DOM; diff --git a/deps/phoenix_live_view/assets/js/phoenix_live_view/dom_patch.js b/deps/phoenix_live_view/assets/js/phoenix_live_view/dom_patch.js new file mode 100644 index 0000000000000000000000000000000000000000..e5a4801c10dd4612de17c26ea9917be319909f48 --- /dev/null +++ b/deps/phoenix_live_view/assets/js/phoenix_live_view/dom_patch.js @@ -0,0 +1,815 @@ +import { + PHX_COMPONENT, + PHX_PRUNE, + PHX_ROOT_ID, + PHX_SESSION, + PHX_SKIP, + PHX_MAGIC_ID, + PHX_STATIC, + PHX_TRIGGER_ACTION, + PHX_UPDATE, + PHX_REF_SRC, + PHX_REF_LOCK, + PHX_STREAM, + PHX_STREAM_REF, + PHX_VIEWPORT_TOP, + PHX_VIEWPORT_BOTTOM, + PHX_PORTAL, + PHX_TELEPORTED_REF, + PHX_TELEPORTED_SRC, + PHX_RUNTIME_HOOK, +} from "./constants"; + +import { detectDuplicateIds, detectInvalidStreamInserts, isCid } from "./utils"; +import ElementRef from "./element_ref"; +import DOM from "./dom"; +import DOMPostMorphRestorer from "./dom_post_morph_restorer"; +import morphdom from "morphdom"; + +export default class DOMPatch { + constructor(view, container, id, html, streams, targetCID, opts = {}) { + this.view = view; + this.liveSocket = view.liveSocket; + this.container = container; + this.id = id; + this.rootID = view.root.id; + this.html = html; + this.streams = streams; + this.streamInserts = {}; + this.streamComponentRestore = {}; + this.targetCID = targetCID; + this.cidPatch = isCid(this.targetCID); + this.pendingRemoves = []; + this.phxRemove = this.liveSocket.binding("remove"); + this.targetContainer = this.isCIDPatch() + ? this.targetCIDContainer(html) + : container; + this.callbacks = { + beforeadded: [], + beforeupdated: [], + beforephxChildAdded: [], + afteradded: [], + afterupdated: [], + afterdiscarded: [], + afterphxChildAdded: [], + aftertransitionsDiscarded: [], + }; + this.withChildren = opts.withChildren || opts.undoRef || false; + this.undoRef = opts.undoRef; + } + + before(kind, callback) { + this.callbacks[`before${kind}`].push(callback); + } + after(kind, callback) { + this.callbacks[`after${kind}`].push(callback); + } + + trackBefore(kind, ...args) { + this.callbacks[`before${kind}`].forEach((callback) => callback(...args)); + } + + trackAfter(kind, ...args) { + this.callbacks[`after${kind}`].forEach((callback) => callback(...args)); + } + + markPrunableContentForRemoval() { + const phxUpdate = this.liveSocket.binding(PHX_UPDATE); + DOM.all( + this.container, + `[${phxUpdate}=append] > *, [${phxUpdate}=prepend] > *`, + (el) => { + el.setAttribute(PHX_PRUNE, ""); + }, + ); + } + + perform(isJoinPatch) { + const { view, liveSocket, html, container } = this; + let targetContainer = this.targetContainer; + + if (this.isCIDPatch() && !this.targetContainer) { + return; + } + + if (this.isCIDPatch()) { + // https://github.com/phoenixframework/phoenix_live_view/pull/3942 + // we need to ensure that no parent is locked + const closestLock = targetContainer.closest(`[${PHX_REF_LOCK}]`); + // If the targetContainer itself is locked, that's okay. + // https://github.com/phoenixframework/phoenix_live_view/issues/4088 + if (closestLock && !closestLock.isSameNode(targetContainer)) { + const clonedTree = DOM.private(closestLock, PHX_REF_LOCK); + if (clonedTree) { + // if a parent is locked with a cloned tree, we need to patch the cloned tree instead + targetContainer = clonedTree.querySelector( + `[data-phx-component="${this.targetCID}"]`, + ); + } + } + } + + const focused = liveSocket.getActiveElement(); + const { selectionStart, selectionEnd } = + focused && DOM.hasSelectionRange(focused) ? focused : {}; + const phxUpdate = liveSocket.binding(PHX_UPDATE); + const phxViewportTop = liveSocket.binding(PHX_VIEWPORT_TOP); + const phxViewportBottom = liveSocket.binding(PHX_VIEWPORT_BOTTOM); + const phxTriggerExternal = liveSocket.binding(PHX_TRIGGER_ACTION); + const added = []; + const updates = []; + const appendPrependUpdates = []; + + // as the portal target itself could be at the end of the DOM, + // it may not be present while morphing previous parts; + // therefore we apply all teleports after the morphing is done+ + let portalCallbacks = []; + + let externalFormTriggered = null; + + const morph = ( + targetContainer, + source, + withChildren = this.withChildren, + ) => { + const morphCallbacks = { + // normally, we are running with childrenOnly, as the patch HTML for a LV + // does not include the LV attrs (data-phx-session, etc.) + // when we are patching a live component, we do want to patch the root element as well; + // another case is the recursive patch of a stream item that was kept on reset (-> onBeforeNodeAdded) + childrenOnly: + targetContainer.getAttribute(PHX_COMPONENT) === null && !withChildren, + getNodeKey: (node) => { + if (DOM.isPhxDestroyed(node)) { + return null; + } + // If we have a join patch, then by definition there was no PHX_MAGIC_ID. + // This is important to reduce the amount of elements morphdom discards. + if (isJoinPatch) { + return node.id; + } + return ( + node.id || (node.getAttribute && node.getAttribute(PHX_MAGIC_ID)) + ); + }, + // skip indexing from children when container is stream + skipFromChildren: (from) => { + return from.getAttribute(phxUpdate) === PHX_STREAM; + }, + // tell morphdom how to add a child + addChild: (parent, child) => { + const { ref, streamAt } = this.getStreamInsert(child); + if (ref === undefined) { + return parent.appendChild(child); + } + + this.setStreamRef(child, ref); + + // streaming + if (streamAt === 0) { + parent.insertAdjacentElement("afterbegin", child); + } else if (streamAt === -1) { + const lastChild = parent.lastElementChild; + if (lastChild && !lastChild.hasAttribute(PHX_STREAM_REF)) { + const nonStreamChild = Array.from(parent.children).find( + (c) => !c.hasAttribute(PHX_STREAM_REF), + ); + parent.insertBefore(child, nonStreamChild); + } else { + parent.appendChild(child); + } + } else if (streamAt > 0) { + const sibling = Array.from(parent.children)[streamAt]; + parent.insertBefore(child, sibling); + } + }, + onBeforeNodeAdded: (el) => { + // don't add update_only nodes if they did not already exist + if ( + this.getStreamInsert(el)?.updateOnly && + !this.streamComponentRestore[el.id] + ) { + return false; + } + + DOM.maintainPrivateHooks(el, el, phxViewportTop, phxViewportBottom); + this.trackBefore("added", el); + + let morphedEl = el; + // this is a stream item that was kept on reset, recursively morph it + if (this.streamComponentRestore[el.id]) { + morphedEl = this.streamComponentRestore[el.id]; + delete this.streamComponentRestore[el.id]; + morph(morphedEl, el, true); + } + + return morphedEl; + }, + onNodeAdded: (el) => { + if (el.getAttribute) { + this.maybeReOrderStream(el, true); + } + // phx-portal handling + if (DOM.isPortalTemplate(el)) { + portalCallbacks.push(() => this.teleport(el, morph)); + } + + // hack to fix Safari handling of img srcset and video tags + if (el instanceof HTMLImageElement && el.srcset) { + // eslint-disable-next-line no-self-assign + el.srcset = el.srcset; + } else if (el instanceof HTMLVideoElement && el.autoplay) { + el.play(); + } + if (DOM.isNowTriggerFormExternal(el, phxTriggerExternal)) { + externalFormTriggered = el; + } + + // nested view handling + if ( + (DOM.isPhxChild(el) && view.ownsElement(el)) || + (DOM.isPhxSticky(el) && view.ownsElement(el.parentNode)) + ) { + this.trackAfter("phxChildAdded", el); + } + + // data-phx-runtime-hook + if (el.nodeName === "SCRIPT" && el.hasAttribute(PHX_RUNTIME_HOOK)) { + this.handleRuntimeHook(el, source); + } + + added.push(el); + }, + onNodeDiscarded: (el) => this.onNodeDiscarded(el), + onBeforeNodeDiscarded: (el) => { + if (el.getAttribute && el.getAttribute(PHX_PRUNE) !== null) { + return true; + } + if ( + el.parentElement !== null && + el.id && + DOM.isPhxUpdate(el.parentElement, phxUpdate, [ + PHX_STREAM, + "append", + "prepend", + ]) + ) { + return false; + } + // don't remove teleported elements + if (el.getAttribute && el.getAttribute(PHX_TELEPORTED_REF)) { + return false; + } + if (this.maybePendingRemove(el)) { + return false; + } + if (this.skipCIDSibling(el)) { + return false; + } + + if (DOM.isPortalTemplate(el)) { + // if the portal template itself is removed, remove the teleported element as well; + // we also perform a check after morphdom is finished to catch parent removals + const teleportedEl = document.getElementById( + el.content.firstElementChild.id, + ); + if (teleportedEl) { + teleportedEl.remove(); + morphCallbacks.onNodeDiscarded(teleportedEl); + this.view.dropPortalElementId(teleportedEl.id); + } + } + + return true; + }, + onElUpdated: (el) => { + if (DOM.isNowTriggerFormExternal(el, phxTriggerExternal)) { + externalFormTriggered = el; + } + updates.push(el); + this.maybeReOrderStream(el, false); + }, + onBeforeElUpdated: (fromEl, toEl) => { + // if we are patching the root target container and the id has changed, treat it as a new node + // by replacing the fromEl with the toEl, which ensures hooks are torn down and re-created + if ( + fromEl.id && + fromEl.isSameNode(targetContainer) && + fromEl.id !== toEl.id + ) { + morphCallbacks.onNodeDiscarded(fromEl); + fromEl.replaceWith(toEl); + return morphCallbacks.onNodeAdded(toEl); + } + DOM.syncPendingAttrs(fromEl, toEl); + DOM.maintainPrivateHooks( + fromEl, + toEl, + phxViewportTop, + phxViewportBottom, + ); + DOM.cleanChildNodes(toEl, phxUpdate); + if (this.skipCIDSibling(toEl)) { + // if this is a live component used in a stream, we may need to reorder it + this.maybeReOrderStream(fromEl); + return false; + } + if (DOM.isPhxSticky(fromEl)) { + [PHX_SESSION, PHX_STATIC, PHX_ROOT_ID] + .map((attr) => [ + attr, + fromEl.getAttribute(attr), + toEl.getAttribute(attr), + ]) + .forEach(([attr, fromVal, toVal]) => { + if (toVal && fromVal !== toVal) { + fromEl.setAttribute(attr, toVal); + } + }); + + return false; + } + if ( + DOM.isIgnored(fromEl, phxUpdate) || + (fromEl.form && fromEl.form.isSameNode(externalFormTriggered)) + ) { + this.trackBefore("updated", fromEl, toEl); + DOM.mergeAttrs(fromEl, toEl, { + isIgnored: DOM.isIgnored(fromEl, phxUpdate), + }); + updates.push(fromEl); + DOM.applyStickyOperations(fromEl); + return false; + } + if ( + fromEl.type === "number" && + fromEl.validity && + fromEl.validity.badInput + ) { + return false; + } + // If the element has PHX_REF_SRC, it is loading or locked and awaiting an ack. + // If it's locked, we clone the fromEl tree and instruct morphdom to use + // the cloned tree as the source of the morph for this branch from here on out. + // We keep a reference to the cloned tree in the element's private data, and + // on ack (view.undoRefs), we morph the cloned tree with the true fromEl in the DOM to + // apply any changes that happened while the element was locked. + const isFocusedFormEl = + focused && fromEl.isSameNode(focused) && DOM.isFormInput(fromEl); + const focusedSelectChanged = + isFocusedFormEl && this.isChangedSelect(fromEl, toEl); + if (fromEl.hasAttribute(PHX_REF_SRC)) { + const ref = new ElementRef(fromEl); + // only perform the clone step if this is not a patch that unlocks + if ( + ref.lockRef && + (!this.undoRef || !ref.isLockUndoneBy(this.undoRef)) + ) { + DOM.applyStickyOperations(fromEl); + const isLocked = fromEl.hasAttribute(PHX_REF_LOCK); + const clone = isLocked + ? DOM.private(fromEl, PHX_REF_LOCK) || fromEl.cloneNode(true) + : null; + if (clone) { + DOM.putPrivate(fromEl, PHX_REF_LOCK, clone); + if (!isFocusedFormEl) { + fromEl = clone; + } + } + } + } + + // nested view handling + if (DOM.isPhxChild(toEl)) { + const prevSession = fromEl.getAttribute(PHX_SESSION); + DOM.mergeAttrs(fromEl, toEl, { exclude: [PHX_STATIC] }); + if (prevSession !== "") { + fromEl.setAttribute(PHX_SESSION, prevSession); + } + fromEl.setAttribute(PHX_ROOT_ID, this.rootID); + DOM.applyStickyOperations(fromEl); + return false; + } + + // if we are undoing a lock, copy potentially nested clones over + if (this.undoRef && DOM.private(toEl, PHX_REF_LOCK)) { + DOM.putPrivate( + fromEl, + PHX_REF_LOCK, + DOM.private(toEl, PHX_REF_LOCK), + ); + } + // now copy regular DOM.private data + DOM.copyPrivates(toEl, fromEl); + + // phx-portal handling + if (DOM.isPortalTemplate(toEl)) { + portalCallbacks.push(() => this.teleport(toEl, morph)); + // for the magicId optimization we need to ensure that the template contents + // are properly updated as they are used when restoring a cloned tree + // Note: we can't write fromEl.innerHTML = toEl.innerHTML because in Chrome + // the HTML parser would drop nested forms, even when it should not. + // https://issues.chromium.org/issues/490290430 + fromEl.content.replaceChildren(toEl.content.cloneNode(true)); + return false; + } + + // skip patching focused inputs unless focus is a select that has changed options + if ( + isFocusedFormEl && + fromEl.type !== "hidden" && + !focusedSelectChanged + ) { + this.trackBefore("updated", fromEl, toEl); + DOM.mergeFocusedInput(fromEl, toEl); + DOM.syncAttrsToProps(fromEl); + updates.push(fromEl); + DOM.applyStickyOperations(fromEl); + return false; + } else { + // blur focused select if it changed so native UI is updated (ie safari won't update visible options) + if (focusedSelectChanged) { + fromEl.blur(); + } + if (DOM.isPhxUpdate(toEl, phxUpdate, ["append", "prepend"])) { + appendPrependUpdates.push( + new DOMPostMorphRestorer( + fromEl, + toEl, + toEl.getAttribute(phxUpdate), + ), + ); + } + + DOM.syncAttrsToProps(toEl); + DOM.applyStickyOperations(toEl); + this.trackBefore("updated", fromEl, toEl); + return fromEl; + } + }, + }; + + morphdom(targetContainer, source, morphCallbacks); + }; + + this.trackBefore("added", container); + this.trackBefore("updated", container, container); + + liveSocket.time("morphdom", () => { + this.streams.forEach(([ref, inserts, deleteIds, reset]) => { + inserts.forEach(([key, streamAt, limit, updateOnly]) => { + this.streamInserts[key] = { ref, streamAt, limit, reset, updateOnly }; + }); + if (reset !== undefined) { + DOM.all(document, `[${PHX_STREAM_REF}="${ref}"]`, (child) => { + this.removeStreamChildElement(child); + }); + } + deleteIds.forEach((id) => { + const child = document.getElementById(id); + if (child) { + this.removeStreamChildElement(child); + } + }); + }); + + // clear stream items from the dead render if they are not inserted again + if (isJoinPatch) { + DOM.all(this.container, `[${phxUpdate}=${PHX_STREAM}]`) + // it is important to filter the element before removing them, as + // it may happen that streams are nested and the owner check fails if + // a parent is removed before a child + .filter((el) => this.view.ownsElement(el)) + .forEach((el) => { + Array.from(el.children).forEach((child) => { + // we already performed the owner check, each child is guaranteed to be owned + // by the view. To prevent the nested owner check from failing in case of nested + // streams where the parent is removed before the child, we force the removal + this.removeStreamChildElement(child, true); + }); + }); + } + + morph(targetContainer, html); + + // normal patch complete, teleport elements now + // and handle nested teleportation up to depth 5 + let teleportCount = 0; + while (portalCallbacks.length > 0 && teleportCount < 5) { + const copy = portalCallbacks.slice(); + portalCallbacks = []; + copy.forEach((callback) => callback()); + teleportCount++; + } + + // check for any teleported elements that are not in the view any more + // and remove them + this.view.portalElementIds.forEach((id) => { + const el = document.getElementById(id); + if (el) { + const source = document.getElementById( + el.getAttribute(PHX_TELEPORTED_SRC), + ); + if (!source) { + el.remove(); + this.onNodeDiscarded(el); + this.view.dropPortalElementId(id); + } + } + }); + }); + + if (liveSocket.isDebugEnabled()) { + detectDuplicateIds(); + detectInvalidStreamInserts(this.streamInserts); + // warn if there are any inputs named "id" + Array.from(document.querySelectorAll("input[name=id]")).forEach( + (node) => { + if (node instanceof HTMLInputElement && node.form) { + console.error( + 'Detected an input with name="id" inside a form! This will cause problems when patching the DOM.\n', + node, + ); + } + }, + ); + } + + if (appendPrependUpdates.length > 0) { + liveSocket.time("post-morph append/prepend restoration", () => { + appendPrependUpdates.forEach((update) => update.perform()); + }); + } + + liveSocket.silenceEvents(() => + DOM.restoreFocus(focused, selectionStart, selectionEnd), + ); + DOM.dispatchEvent(document, "phx:update"); + added.forEach((el) => this.trackAfter("added", el)); + updates.forEach((el) => this.trackAfter("updated", el)); + + this.transitionPendingRemoves(); + + if (externalFormTriggered) { + liveSocket.unload(); + // check for submitter and inject it as hidden input for external submit; + // In theory, it could happen that the stored submitter is outdated and doesn't + // exist in the DOM any more, but this is unlikely, so we just accept it for now. + const submitter = DOM.private(externalFormTriggered, "submitter"); + if (submitter && submitter.name && targetContainer.contains(submitter)) { + const input = document.createElement("input"); + input.type = "hidden"; + const formId = submitter.getAttribute("form"); + if (formId) { + input.setAttribute("form", formId); + } + input.name = submitter.name; + input.value = submitter.value; + submitter.parentElement.insertBefore(input, submitter); + } + // use prototype's submit in case there's a form control with name or id of "submit" + // https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit + Object.getPrototypeOf(externalFormTriggered).submit.call( + externalFormTriggered, + ); + } + return true; + } + + onNodeDiscarded(el) { + // nested view handling + if (DOM.isPhxChild(el) || DOM.isPhxSticky(el)) { + this.liveSocket.destroyViewByEl(el); + } + this.trackAfter("discarded", el); + } + + maybePendingRemove(node) { + if (node.getAttribute && node.getAttribute(this.phxRemove) !== null) { + this.pendingRemoves.push(node); + return true; + } else { + return false; + } + } + + removeStreamChildElement(child, force = false) { + // make sure to only remove elements owned by the current view + // see https://github.com/phoenixframework/phoenix_live_view/issues/3047 + // and https://github.com/phoenixframework/phoenix_live_view/issues/3681 + if (!force && !this.view.ownsElement(child)) { + return; + } + + // we need to store the node if it is actually re-added in the same patch + // we do NOT want to execute phx-remove, we do NOT want to call onNodeDiscarded + if (this.streamInserts[child.id]) { + this.streamComponentRestore[child.id] = child; + child.remove(); + } else { + // only remove the element now if it has no phx-remove binding + if (!this.maybePendingRemove(child)) { + child.remove(); + this.onNodeDiscarded(child); + } + } + } + + getStreamInsert(el) { + const insert = el.id ? this.streamInserts[el.id] : {}; + return insert || {}; + } + + setStreamRef(el, ref) { + DOM.putSticky(el, PHX_STREAM_REF, (el) => + el.setAttribute(PHX_STREAM_REF, ref), + ); + } + + maybeReOrderStream(el, isNew) { + const { ref, streamAt, reset } = this.getStreamInsert(el); + if (streamAt === undefined) { + return; + } + + // we need to set the PHX_STREAM_REF here as well as addChild is invoked only for parents + this.setStreamRef(el, ref); + + if (!reset && !isNew) { + // we only reorder if the element is new or it's a stream reset + return; + } + + // check if the element has a parent element; + // it doesn't if we are currently recursively morphing (restoring a saved stream child) + // because the element is not yet added to the real dom; + // reordering does not make sense in that case anyway + if (!el.parentElement) { + return; + } + + if (streamAt === 0) { + el.parentElement.insertBefore(el, el.parentElement.firstElementChild); + } else if (streamAt > 0) { + const children = Array.from(el.parentElement.children); + const oldIndex = children.indexOf(el); + if (streamAt >= children.length - 1) { + el.parentElement.appendChild(el); + } else { + const sibling = children[streamAt]; + if (oldIndex > streamAt) { + el.parentElement.insertBefore(el, sibling); + } else { + el.parentElement.insertBefore(el, sibling.nextElementSibling); + } + } + } + + this.maybeLimitStream(el); + } + + maybeLimitStream(el) { + const { limit } = this.getStreamInsert(el); + const children = limit !== null && Array.from(el.parentElement.children); + if (limit && limit < 0 && children.length > limit * -1) { + children + .slice(0, children.length + limit) + .forEach((child) => this.removeStreamChildElement(child)); + } else if (limit && limit >= 0 && children.length > limit) { + children + .slice(limit) + .forEach((child) => this.removeStreamChildElement(child)); + } + } + + transitionPendingRemoves() { + const { pendingRemoves, liveSocket } = this; + if (pendingRemoves.length > 0) { + liveSocket.transitionRemoves(pendingRemoves, () => { + pendingRemoves.forEach((el) => { + const child = DOM.firstPhxChild(el); + if (child) { + liveSocket.destroyViewByEl(child); + } + el.remove(); + }); + this.trackAfter("transitionsDiscarded", pendingRemoves); + }); + } + } + + isChangedSelect(fromEl, toEl) { + if (!(fromEl instanceof HTMLSelectElement) || fromEl.multiple) { + return false; + } + if (fromEl.options.length !== toEl.options.length) { + return true; + } + + // keep the current value + toEl.value = fromEl.value; + + // in general we have to be very careful with using isEqualNode as it does not a reliable + // DOM tree equality check, but for selection attributes and options it works fine + return !fromEl.isEqualNode(toEl); + } + + isCIDPatch() { + return this.cidPatch; + } + + skipCIDSibling(el) { + return el.nodeType === Node.ELEMENT_NODE && el.hasAttribute(PHX_SKIP); + } + + targetCIDContainer(html) { + if (!this.isCIDPatch()) { + return; + } + const [first, ...rest] = DOM.findComponentNodeList( + this.view.id, + this.targetCID, + ); + if (rest.length === 0 && DOM.childNodeLength(html) === 1) { + return first; + } else { + return first && first.parentNode; + } + } + + indexOf(parent, child) { + return Array.from(parent.children).indexOf(child); + } + + teleport(el, morph) { + const targetSelector = el.getAttribute(PHX_PORTAL); + const portalContainer = document.querySelector(targetSelector); + if (!portalContainer) { + throw new Error( + "portal target with selector " + targetSelector + " not found", + ); + } + // phx-portal templates must have a single root element, so we assume this to be + // the case here + const toTeleport = el.content.firstElementChild; + // the PHX_SKIP optimization can also apply inside of the