gokashi commited on
Commit
4b4f0ad
·
verified ·
1 Parent(s): 4120c29

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. deps/decimal/.formatter.exs +3 -0
  2. deps/decimal/.hex +0 -0
  3. deps/decimal/CHANGELOG.md +150 -0
  4. deps/decimal/LICENSE.txt +176 -0
  5. deps/decimal/README.md +207 -0
  6. deps/decimal/hex_metadata.config +14 -0
  7. deps/decimal/lib/decimal.ex +2106 -0
  8. deps/decimal/lib/decimal/context.ex +125 -0
  9. deps/decimal/lib/decimal/error.ex +24 -0
  10. deps/decimal/lib/decimal/macros.ex +11 -0
  11. deps/decimal/mix.exs +43 -0
  12. deps/explorer/.hex +0 -0
  13. deps/explorer/CHANGELOG.md +1228 -0
  14. deps/explorer/LICENSE +21 -0
  15. deps/explorer/README.md +307 -0
  16. deps/explorer/checksum-Elixir.Explorer.PolarsBackend.Native.exs +15 -0
  17. deps/explorer/datasets/fossil_fuels.csv +1095 -0
  18. deps/explorer/datasets/iris.csv +151 -0
  19. deps/explorer/datasets/wine.csv +179 -0
  20. deps/explorer/hex_metadata.config +113 -0
  21. deps/explorer/lib/explorer.ex +8 -0
  22. deps/explorer/lib/explorer/application.ex +13 -0
  23. deps/explorer/lib/explorer/backend.ex +55 -0
  24. deps/explorer/lib/explorer/backend/data_frame.ex +350 -0
  25. deps/explorer/lib/explorer/backend/lazy_series.ex +1267 -0
  26. deps/explorer/lib/explorer/backend/query_frame.ex +118 -0
  27. deps/explorer/lib/explorer/backend/series.ex +398 -0
  28. deps/explorer/lib/explorer/comptime_utils.ex +32 -0
  29. deps/explorer/lib/explorer/data_frame.ex +0 -0
  30. deps/explorer/lib/explorer/datasets.ex +78 -0
  31. deps/explorer/lib/explorer/duration.ex +71 -0
  32. deps/explorer/lib/explorer/fss.ex +9 -0
  33. deps/explorer/lib/explorer/fss/http.ex +16 -0
  34. deps/explorer/lib/explorer/fss/s3.ex +75 -0
  35. deps/explorer/lib/explorer/fss/utils.ex +215 -0
  36. deps/explorer/lib/explorer/polars_backend.ex +5 -0
  37. deps/explorer/lib/explorer/polars_backend/data_frame.ex +944 -0
  38. deps/explorer/lib/explorer/polars_backend/expression.ex +369 -0
  39. deps/explorer/lib/explorer/polars_backend/lazy_frame.ex +670 -0
  40. deps/explorer/lib/explorer/polars_backend/native.ex +490 -0
  41. deps/explorer/lib/explorer/polars_backend/series.ex +899 -0
  42. deps/explorer/lib/explorer/polars_backend/shared.ex +300 -0
  43. deps/explorer/lib/explorer/query.ex +826 -0
  44. deps/explorer/lib/explorer/remote.ex +230 -0
  45. deps/explorer/lib/explorer/remote/holder.ex +76 -0
  46. deps/explorer/lib/explorer/remote/local_gc.ex +57 -0
  47. deps/explorer/lib/explorer/series.ex +0 -0
  48. deps/explorer/lib/explorer/shared.ex +782 -0
  49. deps/explorer/lib/explorer/tensor_frame.ex +295 -0
  50. deps/explorer/mix.exs +136 -0
deps/decimal/.formatter.exs ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [
2
+ inputs: ["{bench,mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
3
+ ]
deps/decimal/.hex ADDED
Binary file (263 Bytes). View file
 
deps/decimal/CHANGELOG.md ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CHANGELOG
2
+
3
+ ## v2.3.0 (2024-12-13)
4
+
5
+ * Implement the upcoming [`JSON.Encoder`](https://hexdocs.pm/elixir/main/JSON.Encoder.html)
6
+ protocol
7
+
8
+ ## v2.2.0 (2024-11-13)
9
+
10
+ * Add `Decimal.gte?/2` and `Decimal.lte?/2`
11
+ * Add `Decimal.compare/3` and `Decimal.eq?/3` with threshold as parameter
12
+
13
+ ## v2.1.1 (2023-04-26)
14
+
15
+ Decimal v2.1 requires Elixir v1.8+.
16
+
17
+ ### Bug fixes
18
+
19
+ * Fix `Decimal.compare/2` when comparing against `0`
20
+
21
+ ## v2.1.0 (2023-04-26)
22
+
23
+ Decimal v2.1 requires Elixir v1.8+.
24
+
25
+ ### Enhancements
26
+
27
+ * Improve error message from `Decimal.to_integer/1` during precision loss
28
+ * `Inspect` protocol implementation returns strings in the `Decimal.new(...)` format
29
+ * Add `Decimal.scale/1`
30
+ * Optimize `Decimal.compare/2` for numbers with large exponents
31
+
32
+ ### Bug fixes
33
+
34
+ * Fix `Decimal.integer?/1` spec
35
+ * Fix `Decimal.integer?/1` check on 0 with >1 significant digits
36
+
37
+ ## v2.0.0 (2020-09-08)
38
+
39
+ Decimal v2.0 requires Elixir v1.2+.
40
+
41
+ ### Enhancements
42
+
43
+ * Add `Decimal.integer?/1`
44
+
45
+ ### Breaking changes
46
+
47
+ * Change `Decimal.compare/2` to return `:lt | :eq | :gt`
48
+ * Change `Decimal.cast/1` to return `{:ok, t} | :error`
49
+ * Change `Decimal.parse/1` to return `{t, binary} | :error`
50
+ * Remove `:message` and `:result` fields from `Decimal.Error`
51
+ * Remove sNaN
52
+ * Rename qNaN to NaN
53
+ * Remove deprecated support for floats in `Decimal.new/1`
54
+ * Remove deprecated `Decimal.minus/1`
55
+ * Remove deprecated `Decimal.plus/1`
56
+ * Remove deprecated `Decimal.reduce/1`
57
+ * Remove deprecated `Decimal.with_context/2`, `Decimal.get_context/1`, `Decimal.set_context/1`,
58
+ and `Decimal.update_context/1`
59
+ * Remove deprecated `Decimal.decimal?/1`
60
+
61
+ ### Deprecations
62
+
63
+ * Deprecate `Decimal.cmp/2`
64
+
65
+ ## v1.9.0 (2020-09-08)
66
+
67
+ ### Enhancements
68
+
69
+ * Add `Decimal.negate/1`
70
+ * Add `Decimal.apply_context/1`
71
+ * Add `Decimal.normalize/1`
72
+ * Add `Decimal.Context.with/2`, `Decimal.Context.get/1`, `Decimal.Context.set/2`,
73
+ and `Decimal.Context.update/1`
74
+ * Add `Decimal.is_decimal/1`
75
+
76
+ ### Deprecations
77
+
78
+ * Deprecate `Decimal.minus/1` in favour of the new `Decimal.negate/1`
79
+ * Deprecate `Decimal.plus/1` in favour of the new `Decimal.apply_context/1`
80
+ * Deprecate `Decimal.reduce/1` in favour of the new `Decimal.normalize/1`
81
+ * Deprecate `Decimal.with_context/2`, `Decimal.get_context/1`, `Decimal.set_context/2`,
82
+ and `Decimal.update_context/1` in favour of new functions on the `Decimal.Context` module
83
+ * Deprecate `Decimal.decimal?/1` in favour of the new `Decimal.is_decimal/1`
84
+
85
+ ## v1.8.1 (2019-12-20)
86
+
87
+ ### Bug fixes
88
+
89
+ * Fix Decimal.compare/2 with string arguments
90
+ * Set :signal on error
91
+
92
+ ## v1.8.0 (2019-06-24)
93
+
94
+ ### Enhancements
95
+
96
+ * Add `Decimal.cast/1`
97
+ * Add `Decimal.eq?/2`, `Decimal.gt?/2`, and `Decimal.lt?/2`
98
+ * Add guards to `Decimal.new/3` to prevent invalid Decimal numbers
99
+
100
+ ## v1.7.0 (2019-02-16)
101
+
102
+ ### Enhancements
103
+
104
+ * Add `Decimal.sqrt/1`
105
+
106
+ ## v1.6.0 (2018-11-22)
107
+
108
+ ### Enhancements
109
+
110
+ * Support for canonical XSD representation on `Decimal.to_string/2`
111
+
112
+ ### Bugfixes
113
+
114
+ * Fix exponent off-by-one when converting from decimal to float
115
+ * Fix negative?/1 and positive?/1 specs
116
+
117
+ ### Deprecations
118
+
119
+ * Deprecate passing float to `Decimal.new/1` in favor of `Decimal.from_float/1`
120
+
121
+ ## v1.5.0 (2018-03-24)
122
+
123
+ ### Enhancements
124
+
125
+ * Add `Decimal.positive?/1` and `Decimal.negative?/1`
126
+ * Accept integers and strings in arithmetic functions, e.g.: `Decimal.add(1, "2.0")`
127
+ * Add `Decimal.from_float/1`
128
+
129
+ ### Soft deprecations (no warnings emitted)
130
+
131
+ * Soft deprecate passing float to `new/1` in favor of `from_float/1`
132
+
133
+ ## v1.4.1 (2017-10-12)
134
+
135
+ ### Bugfixes
136
+
137
+ * Include the given value as part of the error reason
138
+ * Fix `:half_even` `:lists.last` bug (empty signif)
139
+ * Fix error message for round
140
+ * Fix `:half_down` rounding error when remainder is greater than 5
141
+ * Fix `Decimal.new/1` float conversion with bigger precision than 4
142
+ * Fix precision default value
143
+
144
+ ## v1.4.0 (2017-06-25)
145
+
146
+ ### Bugfixes
147
+
148
+ * Fix `Decimal.to_integer/1` for large coefficients
149
+ * Fix rounding of ~0 values
150
+ * Fix errors when comparing and adding two infinities
deps/decimal/LICENSE.txt ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
deps/decimal/README.md ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Decimal
2
+
3
+ Arbitrary precision decimal arithmetic.
4
+
5
+ ## Concept
6
+
7
+ Decimal represents values internally using three integers: a sign, a coefficient, and an exponent.
8
+ In this way, numbers of any size and with any number of decimal places can be represented exactly.
9
+
10
+ ```elixir
11
+ Decimal.new(_sign = 1, _coefficient = 42, _exponent = 0) #=> Decimal.new("42")
12
+ Decimal.new(-1, 42, 0) #=> Decimal.new("-42")
13
+ Decimal.new(1, 42, -1) #=> Decimal.new("4.2")
14
+ Decimal.new(1, 42, -20) #=> Decimal.new("4.2E-19")
15
+ Decimal.new(1, 42, 20) #=> Decimal.new("4.2E+21")
16
+ Decimal.new(1, 123456789987654321, -9) #=> Decimal.new("123456789.987654321")
17
+ ```
18
+
19
+ For calculations, the amount of desired precision - that is, the number of
20
+ decimal digits in the coefficient - can be specified.
21
+
22
+ ## Usage
23
+
24
+ Add Decimal as a dependency in your `mix.exs` file:
25
+
26
+ ```elixir
27
+ def deps do
28
+ [{:decimal, "~> 2.0"}]
29
+ end
30
+ ```
31
+
32
+ Next, run `mix deps.get` in your shell to fetch and compile `Decimal`. Start an
33
+ interactive Elixir shell with `iex -S mix`:
34
+
35
+ ```elixir
36
+ iex> alias Decimal, as: D
37
+ iex> D.add(6, 7)
38
+ Decimal.new("13")
39
+ iex> D.div(1, 3)
40
+ Decimal.new("0.3333333333333333333333333333")
41
+ iex> D.new("0.33")
42
+ Decimal.new("0.33")
43
+ ```
44
+
45
+ ## Examples
46
+
47
+ ### Using the context
48
+
49
+ The context specifies the maximum precision of the result of calculations and
50
+ the rounding algorithm if the result has a higher precision than the specified
51
+ maximum. It also holds the list of trap enablers and the current set
52
+ flags.
53
+
54
+ The context is stored in the process dictionary. You don't have to pass the
55
+ context around explicitly and the flags will be updated automatically.
56
+
57
+ The context is accessed with `Decimal.Context.get/0` and set with
58
+ `Decimal.Context.set/1`. It can be set temporarily with
59
+ `Decimal.Context.with/2`.
60
+
61
+ ```elixir
62
+ iex> D.Context.get()
63
+ %Decimal.Context{flags: [:rounded, :inexact], precision: 9, rounding: :half_up,
64
+ traps: [:invalid_operation, :division_by_zero]}
65
+
66
+ iex> D.Context.with(%D.Context{precision: 2}, fn -> IO.inspect D.Context.get() end)
67
+ %Decimal.Context{flags: [], precision: 2, rounding: :half_up,
68
+ traps: [:invalid_operation, :division_by_zero]}
69
+ %Decimal.Context{flags: [], precision: 2, rounding: :half_up,
70
+ traps: [:invalid_operation, :division_by_zero]}
71
+
72
+ iex> D.Context.set(%D.Context{D.Context.get() | traps: []})
73
+ :ok
74
+
75
+ iex> D.Context.get()
76
+ %Decimal.Context{flags: [:rounded, :inexact], precision: 9, rounding: :half_up,
77
+ traps: []}
78
+ ```
79
+
80
+ ### Precision and rounding
81
+
82
+ Use `:precision` option to limit the amount of decimal digits in the
83
+ coefficient of any calculation result:
84
+
85
+ ```elixir
86
+ iex> D.Context.set(%D.Context{D.Context.get() | precision: 9})
87
+ :ok
88
+
89
+ iex> D.div(100, 3)
90
+ Decimal.new("33.3333333")
91
+
92
+ iex> D.Context.set(%D.Context{D.Context.get() | precision: 2})
93
+ :ok
94
+
95
+ iex> D.div(100, 3)
96
+ Decimal.new("33")
97
+ ```
98
+
99
+ The `:rounding` option specifies the algorithm and precision of the rounding
100
+ operation:
101
+
102
+ ```elixir
103
+ iex> D.Context.set(%D.Context{D.Context.get() | rounding: :half_up})
104
+ :ok
105
+
106
+ iex> D.div(31, 2)
107
+ Decimal.new("16")
108
+
109
+ iex> D.Context.set(%D.Context{D.Context.get() | rounding: :floor})
110
+ :ok
111
+
112
+ iex> D.div(31, 2)
113
+ Decimal.new("15")
114
+ ```
115
+
116
+ ### Comparisons
117
+
118
+ Using comparison operators (`<`, `=`, `>`) with two or more decimal digits may
119
+ not produce accurate result. Instead, use comparison functions.
120
+
121
+ ```elixir
122
+ iex> D.compare(-1, 0)
123
+ :lt
124
+ iex> D.compare(0, -1)
125
+ :gt
126
+ iex> D.compare(0, 0)
127
+ :eq
128
+
129
+ iex> D.equal?(-1, 0)
130
+ false
131
+ iex> D.equal?(0, "0.0")
132
+ true
133
+ ```
134
+
135
+ ### Flags and trap enablers
136
+
137
+ When an exceptional condition is signalled, its flag is set in the current
138
+ context. `Decimal.Error` will be raised if the trap enabler is set.
139
+
140
+ ```elixir
141
+ iex> D.Context.set(%D.Context{D.Context.get() | rounding: :floor, precision: 2})
142
+ :ok
143
+
144
+ iex> D.Context.get().traps
145
+ [:invalid_operation, :division_by_zero]
146
+
147
+ iex> D.Context.get().flags
148
+ []
149
+
150
+ iex> D.div(31, 2)
151
+ Decimal.new("15")
152
+
153
+ iex> D.Context.get().flags
154
+ [:inexact, :rounded]
155
+ ```
156
+
157
+ `:inexact` and `:rounded` flag were signalled above because the result of the
158
+ operation was inexact given the context's precision and had to be rounded to
159
+ fit the precision. `Decimal.Error` was not raised because the signals' trap
160
+ enablers weren't set.
161
+
162
+ ```elixir
163
+ iex> D.Context.set(%D.Context{D.Context.get() | traps: D.Context.get().traps ++ [:inexact]})
164
+ :ok
165
+
166
+ iex> D.div(31, 2)
167
+ ** (Decimal.Error)
168
+ ```
169
+
170
+ The default trap enablers, such as `:division_by_zero`, can be unset:
171
+
172
+ ```elixir
173
+ iex> D.Context.get().traps
174
+ [:invalid_operation, :division_by_zero]
175
+
176
+ iex> D.div(42, 0)
177
+ ** (Decimal.Error)
178
+
179
+ iex> D.Context.set(%D.Context{D.Context.get() | traps: [], flags: []})
180
+ :ok
181
+
182
+ iex> D.div(42, 0)
183
+ Decimal.new("Infinity")
184
+
185
+ iex> D.Context.get().flags
186
+ [:division_by_zero]
187
+ ```
188
+
189
+ ### Mitigating rounding errors
190
+
191
+ TODO
192
+
193
+ ## License
194
+
195
+ Copyright 2013 Eric Meadows-Jönsson
196
+
197
+ Licensed under the Apache License, Version 2.0 (the "License");
198
+ you may not use this file except in compliance with the License.
199
+ You may obtain a copy of the License at
200
+
201
+ http://www.apache.org/licenses/LICENSE-2.0
202
+
203
+ Unless required by applicable law or agreed to in writing, software
204
+ distributed under the License is distributed on an "AS IS" BASIS,
205
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
206
+ See the License for the specific language governing permissions and
207
+ limitations under the License.
deps/decimal/hex_metadata.config ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {<<"links">>,[{<<"GitHub">>,<<"https://github.com/ericmj/decimal">>}]}.
2
+ {<<"name">>,<<"decimal">>}.
3
+ {<<"version">>,<<"2.3.0">>}.
4
+ {<<"description">>,<<"Arbitrary precision decimal arithmetic.">>}.
5
+ {<<"elixir">>,<<"~> 1.8">>}.
6
+ {<<"app">>,<<"decimal">>}.
7
+ {<<"licenses">>,[<<"Apache-2.0">>]}.
8
+ {<<"requirements">>,[]}.
9
+ {<<"files">>,
10
+ [<<"lib">>,<<"lib/decimal">>,<<"lib/decimal/error.ex">>,
11
+ <<"lib/decimal/context.ex">>,<<"lib/decimal/macros.ex">>,
12
+ <<"lib/decimal.ex">>,<<".formatter.exs">>,<<"mix.exs">>,<<"README.md">>,
13
+ <<"LICENSE.txt">>,<<"CHANGELOG.md">>]}.
14
+ {<<"build_tools">>,[<<"mix">>]}.
deps/decimal/lib/decimal.ex ADDED
@@ -0,0 +1,2106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Decimal do
2
+ @moduledoc """
3
+ Decimal arithmetic on arbitrary precision floating-point numbers.
4
+
5
+ A number is represented by a signed coefficient and exponent such that: `sign
6
+ * coefficient * 10 ^ exponent`. All numbers are represented and calculated
7
+ exactly, but the result of an operation may be rounded depending on the
8
+ context the operation is performed with, see: `Decimal.Context`. Trailing
9
+ zeros in the coefficient are never truncated to preserve the number of
10
+ significant digits unless explicitly done so.
11
+
12
+ There are also special values such as NaN (not a number) and ±Infinity.
13
+ -0 and +0 are two distinct values.
14
+ Some operation results are not defined and will return NaN.
15
+ This kind of NaN is quiet, any operation returning a number will return
16
+ NaN when given a quiet NaN (the NaN value will flow through all operations).
17
+
18
+ Exceptional conditions are grouped into signals, each signal has a flag and a
19
+ trap enabler in the context. Whenever a signal is triggered it's flag is set
20
+ in the context and will be set until explicitly cleared. If the signal is trap
21
+ enabled `Decimal.Error` will be raised.
22
+
23
+ ## Specifications
24
+
25
+ * [IBM's General Decimal Arithmetic Specification](http://speleotrove.com/decimal/decarith.html)
26
+ * [IEEE standard 854-1987](http://web.archive.org/web/20150908012941/http://754r.ucbtest.org/standards/854.pdf)
27
+
28
+ This library follows the above specifications for reference of arithmetic
29
+ operation implementations, but the public APIs may differ to provide a
30
+ more idiomatic Elixir interface.
31
+
32
+ The specification models the sign of the number as 1, for a negative number,
33
+ and 0 for a positive number. Internally this implementation models the sign as
34
+ 1 or -1 such that the complete number will be `sign * coefficient *
35
+ 10 ^ exponent` and will refer to the sign in documentation as either *positive*
36
+ or *negative*.
37
+
38
+ There is currently no maximum or minimum values for the exponent. Because of
39
+ that all numbers are "normal". This means that when an operation should,
40
+ according to the specification, return a number that "underflows" 0 is returned
41
+ instead of Etiny. This may happen when dividing a number with infinity.
42
+ Additionally, overflow, underflow and clamped may never be signalled.
43
+ """
44
+
45
+ import Bitwise
46
+ import Kernel, except: [abs: 1, div: 2, max: 2, min: 2, rem: 2, round: 1]
47
+ import Decimal.Macros
48
+ alias Decimal.Context
49
+ alias Decimal.Error
50
+
51
+ @power_of_2_to_52 4_503_599_627_370_496
52
+
53
+ @typedoc """
54
+ The coefficient of the power of `10`. Non-negative because the sign is stored separately in `sign`.
55
+
56
+ * `non_neg_integer` - when the `t` represents a number, instead of one of the special values below.
57
+ * `:NaN` - Not a Number.
58
+ * `:inf` - Infinity.
59
+
60
+ """
61
+ @type coefficient :: non_neg_integer | :NaN | :inf
62
+
63
+ @typedoc """
64
+ The exponent to which `10` is raised.
65
+ """
66
+ @type exponent :: integer
67
+
68
+ @typedoc """
69
+
70
+ * `1` for positive
71
+ * `-1` for negative
72
+
73
+ """
74
+ @type sign :: 1 | -1
75
+
76
+ @type signal ::
77
+ :invalid_operation
78
+ | :division_by_zero
79
+ | :rounded
80
+ | :inexact
81
+
82
+ @type compare_result ::
83
+ :lt | :gt | :eq
84
+
85
+ @typedoc """
86
+ Rounding algorithm.
87
+
88
+ See `Decimal.Context` for more information.
89
+ """
90
+ @type rounding ::
91
+ :down
92
+ | :half_up
93
+ | :half_even
94
+ | :ceiling
95
+ | :floor
96
+ | :half_down
97
+ | :up
98
+
99
+ @typedoc """
100
+ This implementation models the `sign` as `1` or `-1` such that the complete number will be: `sign * coef * 10 ^ exp`.
101
+
102
+ * `coef` - the coefficient of the power of `10`.
103
+ * `exp` - the exponent of the power of `10`.
104
+ * `sign` - `1` for positive, `-1` for negative.
105
+
106
+ """
107
+ @type t :: %__MODULE__{
108
+ sign: sign,
109
+ coef: coefficient,
110
+ exp: exponent
111
+ }
112
+
113
+ @type decimal :: t | integer | String.t()
114
+
115
+ defstruct sign: 1, coef: 0, exp: 0
116
+
117
+ defmacrop error(flags, reason, result, context \\ nil) do
118
+ quote bind_quoted: binding() do
119
+ case handle_error(flags, reason, result, context) do
120
+ {:ok, result} -> result
121
+ {:error, error} -> raise Error, error
122
+ end
123
+ end
124
+ end
125
+
126
+ @doc """
127
+ Returns `true` if number is NaN, otherwise `false`.
128
+
129
+ ## Examples
130
+
131
+ iex> Decimal.nan?(Decimal.new("NaN"))
132
+ true
133
+
134
+ iex> Decimal.nan?(Decimal.new(42))
135
+ false
136
+
137
+ """
138
+ @spec nan?(t) :: boolean
139
+ def nan?(%Decimal{coef: :NaN}), do: true
140
+ def nan?(%Decimal{}), do: false
141
+
142
+ @doc """
143
+ Returns `true` if number is ±Infinity, otherwise `false`.
144
+
145
+ ## Examples
146
+
147
+ iex> Decimal.inf?(Decimal.new("+Infinity"))
148
+ true
149
+
150
+ iex> Decimal.inf?(Decimal.new("-Infinity"))
151
+ true
152
+
153
+ iex> Decimal.inf?(Decimal.new("1.5"))
154
+ false
155
+
156
+ """
157
+ @spec inf?(t) :: boolean
158
+ def inf?(%Decimal{coef: :inf}), do: true
159
+ def inf?(%Decimal{}), do: false
160
+
161
+ @doc """
162
+ Returns `true` if argument is a decimal number, otherwise `false`.
163
+
164
+ ## Examples
165
+
166
+ iex> Decimal.is_decimal(Decimal.new(42))
167
+ true
168
+
169
+ iex> Decimal.is_decimal(42)
170
+ false
171
+
172
+ Allowed in guard tests on OTP 21+.
173
+ """
174
+ doc_since("1.9.0")
175
+ defmacro is_decimal(term)
176
+
177
+ if function_exported?(:erlang, :is_map_key, 2) do
178
+ defmacro is_decimal(term) do
179
+ case __CALLER__.context do
180
+ nil ->
181
+ quote do
182
+ case unquote(term) do
183
+ %Decimal{} -> true
184
+ _ -> false
185
+ end
186
+ end
187
+
188
+ :match ->
189
+ raise ArgumentError,
190
+ "invalid expression in match, is_decimal is not allowed in patterns " <>
191
+ "such as function clauses, case clauses or on the left side of the = operator"
192
+
193
+ :guard ->
194
+ quote do
195
+ is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and
196
+ :erlang.map_get(:__struct__, unquote(term)) == Decimal
197
+ end
198
+ end
199
+ end
200
+ else
201
+ # TODO: remove when we require Elixir v1.10
202
+ defmacro is_decimal(term) do
203
+ quote do
204
+ case unquote(term) do
205
+ %Decimal{} -> true
206
+ _ -> false
207
+ end
208
+ end
209
+ end
210
+ end
211
+
212
+ @doc """
213
+ The absolute value of given number. Sets the number's sign to positive.
214
+
215
+ ## Examples
216
+
217
+ iex> Decimal.abs(Decimal.new("1"))
218
+ Decimal.new("1")
219
+
220
+ iex> Decimal.abs(Decimal.new("-1"))
221
+ Decimal.new("1")
222
+
223
+ iex> Decimal.abs(Decimal.new("NaN"))
224
+ Decimal.new("NaN")
225
+
226
+ """
227
+ @spec abs(t) :: t
228
+ def abs(%Decimal{coef: :NaN} = num), do: %{num | sign: 1}
229
+ def abs(%Decimal{} = num), do: context(%{num | sign: 1})
230
+
231
+ @doc """
232
+ Adds two numbers together.
233
+
234
+ ## Exceptional conditions
235
+
236
+ * If one number is -Infinity and the other +Infinity, `:invalid_operation` will
237
+ be signalled.
238
+
239
+ ## Examples
240
+
241
+ iex> Decimal.add(1, "1.1")
242
+ Decimal.new("2.1")
243
+
244
+ iex> Decimal.add(1, "Inf")
245
+ Decimal.new("Infinity")
246
+
247
+ """
248
+ @spec add(decimal, decimal) :: t
249
+ def add(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1
250
+
251
+ def add(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2
252
+
253
+ def add(%Decimal{coef: :inf, sign: sign} = num1, %Decimal{coef: :inf, sign: sign} = num2) do
254
+ if num1.exp > num2.exp do
255
+ num1
256
+ else
257
+ num2
258
+ end
259
+ end
260
+
261
+ def add(%Decimal{coef: :inf}, %Decimal{coef: :inf}),
262
+ do: error(:invalid_operation, "adding +Infinity and -Infinity", %Decimal{coef: :NaN})
263
+
264
+ def add(%Decimal{coef: :inf} = num1, %Decimal{}), do: num1
265
+
266
+ def add(%Decimal{}, %Decimal{coef: :inf} = num2), do: num2
267
+
268
+ def add(%Decimal{} = num1, %Decimal{} = num2) do
269
+ %Decimal{sign: sign1, coef: coef1, exp: exp1} = num1
270
+ %Decimal{sign: sign2, coef: coef2, exp: exp2} = num2
271
+
272
+ {coef1, coef2} = add_align(coef1, exp1, coef2, exp2)
273
+ coef = sign1 * coef1 + sign2 * coef2
274
+ exp = Kernel.min(exp1, exp2)
275
+ sign = add_sign(sign1, sign2, coef)
276
+ context(%Decimal{sign: sign, coef: Kernel.abs(coef), exp: exp})
277
+ end
278
+
279
+ def add(num1, num2), do: add(decimal(num1), decimal(num2))
280
+
281
+ @doc """
282
+ Subtracts second number from the first. Equivalent to `Decimal.add/2` when the
283
+ second number's sign is negated.
284
+
285
+ ## Exceptional conditions
286
+
287
+ * If one number is -Infinity and the other +Infinity `:invalid_operation` will
288
+ be signalled.
289
+
290
+ ## Examples
291
+
292
+ iex> Decimal.sub(1, "0.1")
293
+ Decimal.new("0.9")
294
+
295
+ iex> Decimal.sub(1, "Inf")
296
+ Decimal.new("-Infinity")
297
+
298
+ """
299
+ @spec sub(decimal, decimal) :: t
300
+ def sub(%Decimal{} = num1, %Decimal{sign: sign} = num2) do
301
+ add(num1, %{num2 | sign: -sign})
302
+ end
303
+
304
+ def sub(num1, num2) do
305
+ sub(decimal(num1), decimal(num2))
306
+ end
307
+
308
+ @doc """
309
+ Compares two numbers numerically using a threshold. If the first number added
310
+ to the threshold is greater than the second number, and the first number
311
+ subtracted by the threshold is smaller than the second number, then the two
312
+ numbers are considered equal.
313
+
314
+ ## Examples
315
+
316
+ iex> Decimal.compare("1.1", 1, "0.2")
317
+ :eq
318
+
319
+ iex> Decimal.compare("1.2", 1, "0.1")
320
+ :gt
321
+
322
+ iex> Decimal.compare("1.0", "1.2", "0.1")
323
+ :lt
324
+ """
325
+ @spec compare(decimal :: decimal(), decimal :: decimal(), threshold :: decimal()) ::
326
+ compare_result()
327
+
328
+ def compare(_, _, %Decimal{sign: -1}), do: raise(Error, reason: "threshold cannot be negative")
329
+
330
+ def compare(%Decimal{} = n1, %Decimal{} = n2, %Decimal{} = threshold) do
331
+ add_threshold = n1 |> Decimal.add(threshold)
332
+ sub_threshold = n1 |> Decimal.sub(threshold)
333
+ case1 = compare(add_threshold, n2)
334
+ case2 = compare(sub_threshold, n2)
335
+
336
+ cond do
337
+ (case1 == :gt or case1 == :eq) and (case2 == :lt or case2 == :eq) -> :eq
338
+ case1 == :gt -> :gt
339
+ case2 == :lt -> :lt
340
+ end
341
+ end
342
+
343
+ def compare(n1, n2, threshold), do: compare(decimal(n1), decimal(n2), decimal(threshold))
344
+
345
+ @doc """
346
+ Compares two numbers numerically. If the first number is greater than the second
347
+ `:gt` is returned, if less than `:lt` is returned, if both numbers are equal
348
+ `:eq` is returned.
349
+
350
+ Neither number can be a NaN.
351
+
352
+ ## Examples
353
+
354
+ iex> Decimal.compare("1.0", 1)
355
+ :eq
356
+
357
+ iex> Decimal.compare("Inf", -1)
358
+ :gt
359
+
360
+ """
361
+ @spec compare(decimal, decimal) :: compare_result()
362
+ def compare(%Decimal{coef: :inf, sign: sign}, %Decimal{coef: :inf, sign: sign}),
363
+ do: :eq
364
+
365
+ def compare(%Decimal{coef: :inf, sign: sign1}, %Decimal{coef: :inf, sign: sign2})
366
+ when sign1 < sign2,
367
+ do: :lt
368
+
369
+ def compare(%Decimal{coef: :inf, sign: sign1}, %Decimal{coef: :inf, sign: sign2})
370
+ when sign1 > sign2,
371
+ do: :gt
372
+
373
+ def compare(%Decimal{coef: :inf, sign: 1}, _num2), do: :gt
374
+ def compare(%Decimal{coef: :inf, sign: -1}, _num2), do: :lt
375
+
376
+ def compare(_num1, %Decimal{coef: :inf, sign: 1}), do: :lt
377
+ def compare(_num1, %Decimal{coef: :inf, sign: -1}), do: :gt
378
+
379
+ def compare(%Decimal{coef: :NaN} = num1, _num2),
380
+ do: error(:invalid_operation, "operation on NaN", num1)
381
+
382
+ def compare(_num1, %Decimal{coef: :NaN} = num2),
383
+ do: error(:invalid_operation, "operation on NaN", num2)
384
+
385
+ def compare(%Decimal{coef: 0}, %Decimal{coef: 0}), do: :eq
386
+
387
+ def compare(%Decimal{sign: 1}, %Decimal{coef: 0}), do: :gt
388
+ def compare(%Decimal{coef: 0}, %Decimal{sign: 1}), do: :lt
389
+ def compare(%Decimal{sign: -1}, %Decimal{coef: 0}), do: :lt
390
+ def compare(%Decimal{coef: 0}, %Decimal{sign: -1}), do: :gt
391
+
392
+ def compare(%Decimal{sign: 1}, %Decimal{sign: -1}), do: :gt
393
+ def compare(%Decimal{sign: -1}, %Decimal{sign: 1}), do: :lt
394
+
395
+ def compare(%Decimal{} = num1, %Decimal{} = num2) do
396
+ adjusted_exp1 = adjust_exp(num1)
397
+ adjusted_exp2 = adjust_exp(num2)
398
+
399
+ sign =
400
+ cond do
401
+ adjusted_exp1 == adjusted_exp2 ->
402
+ padded_num1 = pad_num(num1, num1.exp - num2.exp)
403
+ padded_num2 = pad_num(num2, num2.exp - num1.exp)
404
+
405
+ cond do
406
+ padded_num1 == padded_num2 -> 0
407
+ padded_num1 < padded_num2 -> -num1.sign
408
+ true -> num1.sign
409
+ end
410
+
411
+ adjusted_exp1 < adjusted_exp2 ->
412
+ -num1.sign
413
+
414
+ true ->
415
+ num1.sign
416
+ end
417
+
418
+ case sign do
419
+ 0 -> :eq
420
+ 1 -> :gt
421
+ -1 -> :lt
422
+ end
423
+ end
424
+
425
+ def compare(num1, num2) do
426
+ compare(decimal(num1), decimal(num2))
427
+ end
428
+
429
+ defp adjust_exp(%Decimal{coef: coef, exp: exp}) do
430
+ coef_adjustment = coef_length(coef)
431
+ exp + coef_adjustment - 1
432
+ end
433
+
434
+ defp coef_length(0), do: 1
435
+ defp coef_length(coef), do: coef_length(coef, 0)
436
+
437
+ defp coef_length(0, length), do: length
438
+ defp coef_length(coef, length), do: coef_length(Kernel.div(coef, 10), length + 1)
439
+
440
+ defp pad_num(%Decimal{coef: coef}, n) do
441
+ coef * pow10(Kernel.max(n, 0) + 1)
442
+ end
443
+
444
+ @deprecated "Use compare/2 instead"
445
+ @spec cmp(decimal, decimal) :: :lt | :eq | :gt
446
+ def cmp(num1, num2) do
447
+ compare(num1, num2)
448
+ end
449
+
450
+ @doc """
451
+ Compares two numbers numerically and returns `true` if they are equal,
452
+ otherwise `false`. If one of the operands is a quiet NaN this operation
453
+ will always return `false`.
454
+
455
+ ## Examples
456
+
457
+ iex> Decimal.equal?("1.0", 1)
458
+ true
459
+
460
+ iex> Decimal.equal?(1, -1)
461
+ false
462
+
463
+ """
464
+ @spec equal?(decimal, decimal) :: boolean
465
+ def equal?(num1, num2) do
466
+ eq?(num1, num2)
467
+ end
468
+
469
+ @doc """
470
+ Compares two numbers numerically and returns `true` if they are equal,
471
+ otherwise `false`. If one of the operands is a quiet NaN this operation
472
+ will always return `false`.
473
+
474
+ ## Examples
475
+
476
+ iex> Decimal.eq?("1.0", 1)
477
+ true
478
+
479
+ iex> Decimal.eq?(1, -1)
480
+ false
481
+
482
+ """
483
+ doc_since("1.8.0")
484
+ @spec eq?(decimal, decimal) :: boolean
485
+ def eq?(%Decimal{coef: :NaN}, _num2), do: false
486
+ def eq?(_num1, %Decimal{coef: :NaN}), do: false
487
+ def eq?(num1, num2), do: compare(num1, num2) == :eq
488
+
489
+ @doc """
490
+ It compares the equality of two numbers. If the second number is within
491
+ the range of first - threshold and first + threshold, it returns true;
492
+ otherwise, it returns false.
493
+
494
+ ## Examples
495
+
496
+ iex> Decimal.eq?("1.0", 1, "0")
497
+ true
498
+
499
+ iex> Decimal.eq?("1.2", 1, "0.1")
500
+ false
501
+
502
+ iex> Decimal.eq?("1.2", 1, "0.2")
503
+ true
504
+
505
+ iex> Decimal.eq?(1, -1, "0.0")
506
+ false
507
+
508
+ """
509
+ @spec eq?(decimal :: decimal(), decimal :: decimal(), thresrold :: decimal()) :: boolean()
510
+ def eq?(num1, num2, thresrold), do: compare(num1, num2, thresrold) == :eq
511
+
512
+ @doc """
513
+ Compares two numbers numerically and returns `true` if the first argument
514
+ is greater than the second, otherwise `false`. If one the operands is a
515
+ quiet NaN this operation will always return `false`.
516
+
517
+ ## Examples
518
+
519
+ iex> Decimal.gt?("1.3", "1.2")
520
+ true
521
+
522
+ iex> Decimal.gt?("1.2", "1.3")
523
+ false
524
+
525
+ """
526
+ doc_since("1.8.0")
527
+ @spec gt?(decimal, decimal) :: boolean
528
+ def gt?(%Decimal{coef: :NaN}, _num2), do: false
529
+ def gt?(_num1, %Decimal{coef: :NaN}), do: false
530
+ def gt?(num1, num2), do: compare(num1, num2) == :gt
531
+
532
+ @doc """
533
+ Compares two numbers numerically and returns `true` if the first number is
534
+ less than the second number, otherwise `false`. If one of the operands is a
535
+ quiet NaN this operation will always return `false`.
536
+
537
+ ## Examples
538
+
539
+ iex> Decimal.lt?("1.1", "1.2")
540
+ true
541
+
542
+ iex> Decimal.lt?("1.4", "1.2")
543
+ false
544
+
545
+ """
546
+ doc_since("1.8.0")
547
+ @spec lt?(decimal, decimal) :: boolean
548
+ def lt?(%Decimal{coef: :NaN}, _num2), do: false
549
+ def lt?(_num1, %Decimal{coef: :NaN}), do: false
550
+ def lt?(num1, num2), do: compare(num1, num2) == :lt
551
+
552
+ @doc """
553
+ Compares two numbers numerically and returns `true` if
554
+ the first argument is greater than or equal the second,
555
+ otherwise `false`.
556
+
557
+ If one the operands is a quiet NaN this operation
558
+ will always return `false`.
559
+
560
+ ## Examples
561
+
562
+ iex> Decimal.gte?("1.3", "1.3")
563
+ true
564
+
565
+ iex> Decimal.gte?("1.3", "1.2")
566
+ true
567
+
568
+ iex> Decimal.gte?("1.2", "1.3")
569
+ false
570
+
571
+ """
572
+ doc_since("2.2.0")
573
+ @spec gte?(decimal, decimal) :: boolean
574
+
575
+ def gte?(%Decimal{coef: :NaN}, _num2), do: false
576
+ def gte?(_num1, %Decimal{coef: :NaN}), do: false
577
+
578
+ def gte?(num1, num2) do
579
+ case compare(num1, num2) do
580
+ :gt -> true
581
+ :eq -> true
582
+ _ -> false
583
+ end
584
+ end
585
+
586
+ @doc """
587
+ Compares two numbers numerically and returns `true` if
588
+ the first number is less than or equal the second number,
589
+ otherwise `false`.
590
+
591
+ If one of the operands is a quiet NaN this operation
592
+ will always return `false`.
593
+
594
+ ## Examples
595
+
596
+ iex> Decimal.lte?("1.1", "1.1")
597
+ true
598
+
599
+ iex> Decimal.lte?("1.1", "1.2")
600
+ true
601
+
602
+ iex> Decimal.lte?("1.4", "1.2")
603
+ false
604
+
605
+ """
606
+ doc_since("2.2.0")
607
+ @spec lte?(decimal, decimal) :: boolean
608
+
609
+ def lte?(%Decimal{coef: :NaN}, _num2), do: false
610
+ def lte?(_num1, %Decimal{coef: :NaN}), do: false
611
+
612
+ def lte?(num1, num2) do
613
+ case compare(num1, num2) do
614
+ :lt -> true
615
+ :eq -> true
616
+ _ -> false
617
+ end
618
+ end
619
+
620
+ @doc """
621
+ Divides two numbers.
622
+
623
+ ## Exceptional conditions
624
+
625
+ * If both numbers are ±Infinity `:invalid_operation` is signalled.
626
+ * If both numbers are ±0 `:invalid_operation` is signalled.
627
+ * If second number (denominator) is ±0 `:division_by_zero` is signalled.
628
+
629
+ ## Examples
630
+
631
+ iex> Decimal.div(3, 4)
632
+ Decimal.new("0.75")
633
+
634
+ iex> Decimal.div("Inf", -1)
635
+ Decimal.new("-Infinity")
636
+
637
+ """
638
+ @spec div(decimal, decimal) :: t
639
+ def div(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1
640
+
641
+ def div(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2
642
+
643
+ def div(%Decimal{coef: :inf}, %Decimal{coef: :inf}),
644
+ do: error(:invalid_operation, "±Infinity / ±Infinity", %Decimal{coef: :NaN})
645
+
646
+ def div(%Decimal{sign: sign1, coef: :inf} = num1, %Decimal{sign: sign2}) do
647
+ sign = if sign1 == sign2, do: 1, else: -1
648
+ %{num1 | sign: sign}
649
+ end
650
+
651
+ def div(%Decimal{sign: sign1, exp: exp1}, %Decimal{sign: sign2, coef: :inf, exp: exp2}) do
652
+ sign = if sign1 == sign2, do: 1, else: -1
653
+ # TODO: Subnormal
654
+ # exponent?
655
+ %Decimal{sign: sign, coef: 0, exp: exp1 - exp2}
656
+ end
657
+
658
+ def div(%Decimal{coef: 0}, %Decimal{coef: 0}),
659
+ do: error(:invalid_operation, "0 / 0", %Decimal{coef: :NaN})
660
+
661
+ def div(%Decimal{sign: sign1}, %Decimal{sign: sign2, coef: 0}) do
662
+ sign = if sign1 == sign2, do: 1, else: -1
663
+ error(:division_by_zero, nil, %Decimal{sign: sign, coef: :inf})
664
+ end
665
+
666
+ def div(%Decimal{} = num1, %Decimal{} = num2) do
667
+ %Decimal{sign: sign1, coef: coef1, exp: exp1} = num1
668
+ %Decimal{sign: sign2, coef: coef2, exp: exp2} = num2
669
+ sign = if sign1 == sign2, do: 1, else: -1
670
+
671
+ if coef1 == 0 do
672
+ context(%Decimal{sign: sign, coef: 0, exp: exp1 - exp2}, [])
673
+ else
674
+ prec10 = pow10(Context.get().precision)
675
+ {coef1, coef2, adjust} = div_adjust(coef1, coef2, 0)
676
+ {coef, adjust, _rem, signals} = div_calc(coef1, coef2, 0, adjust, prec10)
677
+
678
+ context(%Decimal{sign: sign, coef: coef, exp: exp1 - exp2 - adjust}, signals)
679
+ end
680
+ end
681
+
682
+ def div(num1, num2) do
683
+ div(decimal(num1), decimal(num2))
684
+ end
685
+
686
+ @doc """
687
+ Divides two numbers and returns the integer part.
688
+
689
+ ## Exceptional conditions
690
+
691
+ * If both numbers are ±Infinity `:invalid_operation` is signalled.
692
+ * If both numbers are ±0 `:invalid_operation` is signalled.
693
+ * If second number (denominator) is ±0 `:division_by_zero` is signalled.
694
+
695
+ ## Examples
696
+
697
+ iex> Decimal.div_int(5, 2)
698
+ Decimal.new("2")
699
+
700
+ iex> Decimal.div_int("Inf", -1)
701
+ Decimal.new("-Infinity")
702
+
703
+ """
704
+ @spec div_int(decimal, decimal) :: t
705
+ def div_int(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1
706
+
707
+ def div_int(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2
708
+
709
+ def div_int(%Decimal{coef: :inf}, %Decimal{coef: :inf}),
710
+ do: error(:invalid_operation, "±Infinity / ±Infinity", %Decimal{coef: :NaN})
711
+
712
+ def div_int(%Decimal{sign: sign1, coef: :inf} = num1, %Decimal{sign: sign2}) do
713
+ sign = if sign1 == sign2, do: 1, else: -1
714
+ %{num1 | sign: sign}
715
+ end
716
+
717
+ def div_int(%Decimal{sign: sign1, exp: exp1}, %Decimal{sign: sign2, coef: :inf, exp: exp2}) do
718
+ sign = if sign1 == sign2, do: 1, else: -1
719
+ # TODO: Subnormal
720
+ # exponent?
721
+ %Decimal{sign: sign, coef: 0, exp: exp1 - exp2}
722
+ end
723
+
724
+ def div_int(%Decimal{coef: 0}, %Decimal{coef: 0}),
725
+ do: error(:invalid_operation, "0 / 0", %Decimal{coef: :NaN})
726
+
727
+ def div_int(%Decimal{sign: sign1}, %Decimal{sign: sign2, coef: 0}) do
728
+ div_sign = if sign1 == sign2, do: 1, else: -1
729
+ error(:division_by_zero, nil, %Decimal{sign: div_sign, coef: :inf})
730
+ end
731
+
732
+ def div_int(%Decimal{} = num1, %Decimal{} = num2) do
733
+ %Decimal{sign: sign1, coef: coef1, exp: exp1} = num1
734
+ %Decimal{sign: sign2, coef: coef2, exp: exp2} = num2
735
+ div_sign = if sign1 == sign2, do: 1, else: -1
736
+
737
+ cond do
738
+ compare(%{num1 | sign: 1}, %{num2 | sign: 1}) == :lt ->
739
+ %Decimal{sign: div_sign, coef: 0, exp: exp1 - exp2}
740
+
741
+ coef1 == 0 ->
742
+ context(%{num1 | sign: div_sign})
743
+
744
+ true ->
745
+ case integer_division(div_sign, coef1, exp1, coef2, exp2) do
746
+ {:ok, result} ->
747
+ result
748
+
749
+ {:error, error, reason, num} ->
750
+ error(error, reason, num)
751
+ end
752
+ end
753
+ end
754
+
755
+ def div_int(num1, num2) do
756
+ div_int(decimal(num1), decimal(num2))
757
+ end
758
+
759
+ @doc """
760
+ Remainder of integer division of two numbers. The result will have the sign of
761
+ the first number.
762
+
763
+ ## Exceptional conditions
764
+
765
+ * If both numbers are ±Infinity `:invalid_operation` is signalled.
766
+ * If both numbers are ±0 `:invalid_operation` is signalled.
767
+ * If second number (denominator) is ±0 `:division_by_zero` is signalled.
768
+
769
+ ## Examples
770
+
771
+ iex> Decimal.rem(5, 2)
772
+ Decimal.new("1")
773
+
774
+ """
775
+ @spec rem(decimal, decimal) :: t
776
+ def rem(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1
777
+
778
+ def rem(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2
779
+
780
+ def rem(%Decimal{coef: :inf}, %Decimal{coef: :inf}),
781
+ do: error(:invalid_operation, "±Infinity / ±Infinity", %Decimal{coef: :NaN})
782
+
783
+ def rem(%Decimal{sign: sign1, coef: :inf}, %Decimal{}), do: %Decimal{sign: sign1, coef: 0}
784
+
785
+ def rem(%Decimal{sign: sign1}, %Decimal{coef: :inf} = num2) do
786
+ # TODO: Subnormal
787
+ # exponent?
788
+ %{num2 | sign: sign1}
789
+ end
790
+
791
+ def rem(%Decimal{coef: 0}, %Decimal{coef: 0}),
792
+ do: error(:invalid_operation, "0 / 0", %Decimal{coef: :NaN})
793
+
794
+ def rem(%Decimal{sign: sign1}, %Decimal{coef: 0}),
795
+ do: error(:division_by_zero, nil, %Decimal{sign: sign1, coef: 0})
796
+
797
+ def rem(%Decimal{} = num1, %Decimal{} = num2) do
798
+ %Decimal{sign: sign1, coef: coef1, exp: exp1} = num1
799
+ %Decimal{sign: sign2, coef: coef2, exp: exp2} = num2
800
+
801
+ cond do
802
+ compare(%{num1 | sign: 1}, %{num2 | sign: 1}) == :lt ->
803
+ %{num1 | sign: sign1}
804
+
805
+ coef1 == 0 ->
806
+ context(%{num2 | sign: sign1})
807
+
808
+ true ->
809
+ div_sign = if sign1 == sign2, do: 1, else: -1
810
+
811
+ case integer_division(div_sign, coef1, exp1, coef2, exp2) do
812
+ {:ok, result} ->
813
+ sub(num1, mult(num2, result))
814
+
815
+ {:error, error, reason, num} ->
816
+ error(error, reason, num)
817
+ end
818
+ end
819
+ end
820
+
821
+ def rem(num1, num2) do
822
+ rem(decimal(num1), decimal(num2))
823
+ end
824
+
825
+ @doc """
826
+ Integer division of two numbers and the remainder. Should be used when both
827
+ `div_int/2` and `rem/2` is needed. Equivalent to: `{Decimal.div_int(x, y),
828
+ Decimal.rem(x, y)}`.
829
+
830
+ ## Exceptional conditions
831
+
832
+ * If both numbers are ±Infinity `:invalid_operation` is signalled.
833
+ * If both numbers are ±0 `:invalid_operation` is signalled.
834
+ * If second number (denominator) is ±0 `:division_by_zero` is signalled.
835
+
836
+ ## Examples
837
+
838
+ iex> Decimal.div_rem(5, 2)
839
+ {Decimal.new(2), Decimal.new(1)}
840
+
841
+ """
842
+ @spec div_rem(decimal, decimal) :: {t, t}
843
+ def div_rem(%Decimal{coef: :NaN} = num1, %Decimal{}), do: {num1, num1}
844
+
845
+ def div_rem(%Decimal{}, %Decimal{coef: :NaN} = num2), do: {num2, num2}
846
+
847
+ def div_rem(%Decimal{coef: :inf}, %Decimal{coef: :inf}) do
848
+ numbers = {%Decimal{coef: :NaN}, %Decimal{coef: :NaN}}
849
+ error(:invalid_operation, "±Infinity / ±Infinity", numbers)
850
+ end
851
+
852
+ def div_rem(%Decimal{sign: sign1, coef: :inf} = num1, %Decimal{sign: sign2}) do
853
+ sign = if sign1 == sign2, do: 1, else: -1
854
+ {%{num1 | sign: sign}, %Decimal{sign: sign1, coef: 0}}
855
+ end
856
+
857
+ def div_rem(%Decimal{} = num1, %Decimal{coef: :inf} = num2) do
858
+ %Decimal{sign: sign1, exp: exp1} = num1
859
+ %Decimal{sign: sign2, exp: exp2} = num2
860
+
861
+ sign = if sign1 == sign2, do: 1, else: -1
862
+ # TODO: Subnormal
863
+ # exponent?
864
+ {%Decimal{sign: sign, coef: 0, exp: exp1 - exp2}, %{num2 | sign: sign1}}
865
+ end
866
+
867
+ def div_rem(%Decimal{coef: 0}, %Decimal{coef: 0}) do
868
+ error = error(:invalid_operation, "0 / 0", %Decimal{coef: :NaN})
869
+ {error, error}
870
+ end
871
+
872
+ def div_rem(%Decimal{sign: sign1}, %Decimal{sign: sign2, coef: 0}) do
873
+ div_sign = if sign1 == sign2, do: 1, else: -1
874
+ div_error = error(:division_by_zero, nil, %Decimal{sign: div_sign, coef: :inf})
875
+ rem_error = error(:division_by_zero, nil, %Decimal{sign: sign1, coef: 0})
876
+ {div_error, rem_error}
877
+ end
878
+
879
+ def div_rem(%Decimal{} = num1, %Decimal{} = num2) do
880
+ %Decimal{sign: sign1, coef: coef1, exp: exp1} = num1
881
+ %Decimal{sign: sign2, coef: coef2, exp: exp2} = num2
882
+ div_sign = if sign1 == sign2, do: 1, else: -1
883
+
884
+ cond do
885
+ compare(%{num1 | sign: 1}, %{num2 | sign: 1}) == :lt ->
886
+ {%Decimal{sign: div_sign, coef: 0, exp: exp1 - exp2}, %{num1 | sign: sign1}}
887
+
888
+ coef1 == 0 ->
889
+ {context(%{num1 | sign: div_sign}), context(%{num2 | sign: sign1})}
890
+
891
+ true ->
892
+ case integer_division(div_sign, coef1, exp1, coef2, exp2) do
893
+ {:ok, result} ->
894
+ {result, sub(num1, mult(num2, result))}
895
+
896
+ {:error, error, reason, num} ->
897
+ error(error, reason, {num, num})
898
+ end
899
+ end
900
+ end
901
+
902
+ def div_rem(num1, num2) do
903
+ div_rem(decimal(num1), decimal(num2))
904
+ end
905
+
906
+ @doc """
907
+ Compares two values numerically and returns the maximum. Unlike most other
908
+ functions in `Decimal` if a number is NaN the result will be the other number.
909
+ Only if both numbers are NaN will NaN be returned.
910
+
911
+ ## Examples
912
+
913
+ iex> Decimal.max(1, "2.0")
914
+ Decimal.new("2.0")
915
+
916
+ iex> Decimal.max(1, "NaN")
917
+ Decimal.new("1")
918
+
919
+ iex> Decimal.max("NaN", "NaN")
920
+ Decimal.new("NaN")
921
+
922
+ """
923
+ @spec max(decimal, decimal) :: t
924
+ def max(%Decimal{coef: :NaN}, %Decimal{} = num2), do: num2
925
+
926
+ def max(%Decimal{} = num1, %Decimal{coef: :NaN}), do: num1
927
+
928
+ def max(%Decimal{sign: sign1, exp: exp1} = num1, %Decimal{sign: sign2, exp: exp2} = num2) do
929
+ case compare(num1, num2) do
930
+ :lt ->
931
+ num2
932
+
933
+ :gt ->
934
+ num1
935
+
936
+ :eq ->
937
+ cond do
938
+ sign1 != sign2 ->
939
+ if sign1 == 1, do: num1, else: num2
940
+
941
+ sign1 == 1 ->
942
+ if exp1 > exp2, do: num1, else: num2
943
+
944
+ sign1 == -1 ->
945
+ if exp1 < exp2, do: num1, else: num2
946
+ end
947
+ end
948
+ |> context()
949
+ end
950
+
951
+ def max(num1, num2) do
952
+ max(decimal(num1), decimal(num2))
953
+ end
954
+
955
+ @doc """
956
+ Compares two values numerically and returns the minimum. Unlike most other
957
+ functions in `Decimal` if a number is NaN the result will be the other number.
958
+ Only if both numbers are NaN will NaN be returned.
959
+
960
+ ## Examples
961
+
962
+ iex> Decimal.min(1, "2.0")
963
+ Decimal.new("1")
964
+
965
+ iex> Decimal.min(1, "NaN")
966
+ Decimal.new("1")
967
+
968
+ iex> Decimal.min("NaN", "NaN")
969
+ Decimal.new("NaN")
970
+
971
+ """
972
+ @spec min(decimal, decimal) :: t
973
+ def min(%Decimal{coef: :NaN}, %Decimal{} = num2), do: num2
974
+
975
+ def min(%Decimal{} = num1, %Decimal{coef: :NaN}), do: num1
976
+
977
+ def min(%Decimal{sign: sign1, exp: exp1} = num1, %Decimal{sign: sign2, exp: exp2} = num2) do
978
+ case compare(num1, num2) do
979
+ :lt ->
980
+ num1
981
+
982
+ :gt ->
983
+ num2
984
+
985
+ :eq ->
986
+ cond do
987
+ sign1 != sign2 ->
988
+ if sign1 == -1, do: num1, else: num2
989
+
990
+ sign1 == 1 ->
991
+ if exp1 < exp2, do: num1, else: num2
992
+
993
+ sign1 == -1 ->
994
+ if exp1 > exp2, do: num1, else: num2
995
+ end
996
+ end
997
+ |> context()
998
+ end
999
+
1000
+ def min(num1, num2) do
1001
+ min(decimal(num1), decimal(num2))
1002
+ end
1003
+
1004
+ @doc """
1005
+ Negates the given number.
1006
+
1007
+ ## Examples
1008
+
1009
+ iex> Decimal.negate(1)
1010
+ Decimal.new("-1")
1011
+
1012
+ iex> Decimal.negate("-Inf")
1013
+ Decimal.new("Infinity")
1014
+
1015
+ """
1016
+ doc_since("1.9.0")
1017
+ @spec negate(decimal) :: t
1018
+ def negate(%Decimal{coef: :NaN} = num), do: num
1019
+ def negate(%Decimal{sign: sign} = num), do: context(%{num | sign: -sign})
1020
+ def negate(num), do: negate(decimal(num))
1021
+
1022
+ @doc """
1023
+ Applies the context to the given number rounding it to specified precision.
1024
+ """
1025
+ doc_since("1.9.0")
1026
+ @spec apply_context(t) :: t
1027
+ def apply_context(%Decimal{} = num), do: context(num)
1028
+
1029
+ @doc """
1030
+ Returns `true` if given number is positive, otherwise `false`.
1031
+
1032
+ ## Examples
1033
+
1034
+ iex> Decimal.positive?(Decimal.new("42"))
1035
+ true
1036
+
1037
+ iex> Decimal.positive?(Decimal.new("-42"))
1038
+ false
1039
+
1040
+ iex> Decimal.positive?(Decimal.new("0"))
1041
+ false
1042
+
1043
+ iex> Decimal.positive?(Decimal.new("NaN"))
1044
+ false
1045
+
1046
+ """
1047
+ doc_since("1.5.0")
1048
+ @spec positive?(t) :: boolean
1049
+ def positive?(%Decimal{coef: :NaN}), do: false
1050
+ def positive?(%Decimal{coef: 0}), do: false
1051
+ def positive?(%Decimal{sign: -1}), do: false
1052
+ def positive?(%Decimal{sign: 1}), do: true
1053
+
1054
+ @doc """
1055
+ Returns `true` if given number is negative, otherwise `false`.
1056
+
1057
+ ## Examples
1058
+
1059
+ iex> Decimal.negative?(Decimal.new("-42"))
1060
+ true
1061
+
1062
+ iex> Decimal.negative?(Decimal.new("42"))
1063
+ false
1064
+
1065
+ iex> Decimal.negative?(Decimal.new("0"))
1066
+ false
1067
+
1068
+ iex> Decimal.negative?(Decimal.new("NaN"))
1069
+ false
1070
+
1071
+ """
1072
+ doc_since("1.5.0")
1073
+ @spec negative?(t) :: boolean
1074
+ def negative?(%Decimal{coef: :NaN}), do: false
1075
+ def negative?(%Decimal{coef: 0}), do: false
1076
+ def negative?(%Decimal{sign: 1}), do: false
1077
+ def negative?(%Decimal{sign: -1}), do: true
1078
+
1079
+ @doc """
1080
+ Multiplies two numbers.
1081
+
1082
+ ## Exceptional conditions
1083
+
1084
+ * If one number is ±0 and the other is ±Infinity `:invalid_operation` is
1085
+ signalled.
1086
+
1087
+ ## Examples
1088
+
1089
+ iex> Decimal.mult("0.5", 3)
1090
+ Decimal.new("1.5")
1091
+
1092
+ iex> Decimal.mult("Inf", -1)
1093
+ Decimal.new("-Infinity")
1094
+
1095
+ """
1096
+ @spec mult(decimal, decimal) :: t
1097
+ def mult(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1
1098
+
1099
+ def mult(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2
1100
+
1101
+ def mult(%Decimal{coef: 0}, %Decimal{coef: :inf}),
1102
+ do: error(:invalid_operation, "0 * ±Infinity", %Decimal{coef: :NaN})
1103
+
1104
+ def mult(%Decimal{coef: :inf}, %Decimal{coef: 0}),
1105
+ do: error(:invalid_operation, "0 * ±Infinity", %Decimal{coef: :NaN})
1106
+
1107
+ def mult(%Decimal{sign: sign1, coef: :inf, exp: exp1}, %Decimal{sign: sign2, exp: exp2}) do
1108
+ sign = if sign1 == sign2, do: 1, else: -1
1109
+ # exponent?
1110
+ %Decimal{sign: sign, coef: :inf, exp: exp1 + exp2}
1111
+ end
1112
+
1113
+ def mult(%Decimal{sign: sign1, exp: exp1}, %Decimal{sign: sign2, coef: :inf, exp: exp2}) do
1114
+ sign = if sign1 == sign2, do: 1, else: -1
1115
+ # exponent?
1116
+ %Decimal{sign: sign, coef: :inf, exp: exp1 + exp2}
1117
+ end
1118
+
1119
+ def mult(%Decimal{} = num1, %Decimal{} = num2) do
1120
+ %Decimal{sign: sign1, coef: coef1, exp: exp1} = num1
1121
+ %Decimal{sign: sign2, coef: coef2, exp: exp2} = num2
1122
+ sign = if sign1 == sign2, do: 1, else: -1
1123
+ %Decimal{sign: sign, coef: coef1 * coef2, exp: exp1 + exp2} |> context()
1124
+ end
1125
+
1126
+ def mult(num1, num2) do
1127
+ mult(decimal(num1), decimal(num2))
1128
+ end
1129
+
1130
+ @doc """
1131
+ Normalizes the given decimal: removes trailing zeros from coefficient while
1132
+ keeping the number numerically equivalent by increasing the exponent.
1133
+
1134
+ ## Examples
1135
+
1136
+ iex> Decimal.normalize(Decimal.new("1.00"))
1137
+ Decimal.new("1")
1138
+
1139
+ iex> Decimal.normalize(Decimal.new("1.01"))
1140
+ Decimal.new("1.01")
1141
+
1142
+ """
1143
+ doc_since("1.9.0")
1144
+ @spec normalize(t) :: t
1145
+ def normalize(%Decimal{coef: :NaN} = num), do: num
1146
+
1147
+ def normalize(%Decimal{coef: :inf} = num) do
1148
+ # exponent?
1149
+ %{num | exp: 0}
1150
+ end
1151
+
1152
+ def normalize(%Decimal{sign: sign, coef: coef, exp: exp}) do
1153
+ if coef == 0 do
1154
+ %Decimal{sign: sign, coef: 0, exp: 0}
1155
+ else
1156
+ %{do_normalize(coef, exp) | sign: sign} |> context
1157
+ end
1158
+ end
1159
+
1160
+ @doc """
1161
+ Rounds the given number to specified decimal places with the given strategy
1162
+ (default is to round to nearest one). If places is negative, at least that
1163
+ many digits to the left of the decimal point will be zero.
1164
+
1165
+ See `Decimal.Context` for more information about rounding algorithms.
1166
+
1167
+ ## Examples
1168
+
1169
+ iex> Decimal.round("1.234")
1170
+ Decimal.new("1")
1171
+
1172
+ iex> Decimal.round("1.234", 1)
1173
+ Decimal.new("1.2")
1174
+
1175
+ """
1176
+ @spec round(decimal, integer, rounding) :: t
1177
+ def round(num, places \\ 0, mode \\ :half_up)
1178
+
1179
+ def round(%Decimal{coef: :NaN} = num, _, _), do: num
1180
+
1181
+ def round(%Decimal{coef: :inf} = num, _, _), do: num
1182
+
1183
+ def round(%Decimal{} = num, n, mode) do
1184
+ %Decimal{sign: sign, coef: coef, exp: exp} = normalize(num)
1185
+ digits = :erlang.integer_to_list(coef)
1186
+ target_exp = -n
1187
+ value = do_round(sign, digits, exp, target_exp, mode)
1188
+ context(value, [])
1189
+ end
1190
+
1191
+ def round(num, n, mode) do
1192
+ round(decimal(num), n, mode)
1193
+ end
1194
+
1195
+ @doc """
1196
+ Finds the square root.
1197
+
1198
+ ## Examples
1199
+
1200
+ iex> Decimal.sqrt("100")
1201
+ Decimal.new("10")
1202
+
1203
+ """
1204
+ doc_since("1.7.0")
1205
+ @spec sqrt(decimal) :: t
1206
+ def sqrt(%Decimal{coef: :NaN} = num),
1207
+ do: error(:invalid_operation, "operation on NaN", num)
1208
+
1209
+ def sqrt(%Decimal{coef: 0, exp: exp} = num),
1210
+ do: %{num | exp: exp >>> 1}
1211
+
1212
+ def sqrt(%Decimal{sign: -1} = num),
1213
+ do: error(:invalid_operation, "less than zero", num)
1214
+
1215
+ def sqrt(%Decimal{sign: 1, coef: :inf} = num),
1216
+ do: num
1217
+
1218
+ def sqrt(%Decimal{sign: 1, coef: coef, exp: exp}) do
1219
+ precision = Context.get().precision + 1
1220
+ digits = :erlang.integer_to_list(coef)
1221
+ num_digits = length(digits)
1222
+
1223
+ # Since the root is calculated from integer operations only, it must be
1224
+ # large enough to contain the desired precision. Calculate the amount of
1225
+ # `shift` required (powers of 10).
1226
+ case exp &&& 1 do
1227
+ 0 ->
1228
+ # To get the desired `shift`, subtract the precision of `coef`'s square
1229
+ # root from the desired precision.
1230
+ #
1231
+ # If `coef` is 10_000, the root is 100 (3 digits of precision).
1232
+ # If `coef` is 100, the root is 10 (2 digits of precision).
1233
+ shift = precision - ((num_digits + 1) >>> 1)
1234
+ sqrt(coef, shift, exp)
1235
+
1236
+ _ ->
1237
+ # If `exp` is odd, multiply `coef` by 10 and reduce shift by 1/2. `exp`
1238
+ # must be even so the root's exponent is an integer.
1239
+ shift = precision - ((num_digits >>> 1) + 1)
1240
+ sqrt(coef * 10, shift, exp)
1241
+ end
1242
+ end
1243
+
1244
+ def sqrt(num) do
1245
+ sqrt(decimal(num))
1246
+ end
1247
+
1248
+ defp sqrt(coef, shift, exp) do
1249
+ if shift >= 0 do
1250
+ # shift `coef` up by `shift * 2` digits
1251
+ sqrt(coef * pow10(shift <<< 1), shift, exp, true)
1252
+ else
1253
+ # shift `coef` down by `shift * 2` digits
1254
+ operand = pow10(-shift <<< 1)
1255
+ sqrt(Kernel.div(coef, operand), shift, exp, Kernel.rem(coef, operand) === 0)
1256
+ end
1257
+ end
1258
+
1259
+ defp sqrt(shifted_coef, shift, exp, exact) do
1260
+ # the preferred exponent is `exp / 2` as per IEEE 754
1261
+ exp = exp >>> 1
1262
+ # guess a root 10x higher than desired precision
1263
+ guess = pow10(Context.get().precision + 1)
1264
+ root = sqrt_loop(shifted_coef, guess)
1265
+
1266
+ if exact and root * root === shifted_coef do
1267
+ # if the root is exact, use preferred `exp` and shift `coef` to match
1268
+ coef =
1269
+ if shift >= 0,
1270
+ do: Kernel.div(root, pow10(shift)),
1271
+ else: root * pow10(-shift)
1272
+
1273
+ context(%Decimal{sign: 1, coef: coef, exp: exp})
1274
+ else
1275
+ # otherwise the calculated root is inexact (but still meets precision),
1276
+ # so use the root as `coef` and get the final exponent by shifting `exp`
1277
+ context(%Decimal{sign: 1, coef: root, exp: exp - shift})
1278
+ end
1279
+ end
1280
+
1281
+ # Babylonion method
1282
+ defp sqrt_loop(coef, guess) do
1283
+ quotient = Kernel.div(coef, guess)
1284
+
1285
+ if guess <= quotient do
1286
+ guess
1287
+ else
1288
+ sqrt_loop(coef, (guess + quotient) >>> 1)
1289
+ end
1290
+ end
1291
+
1292
+ @doc """
1293
+ Creates a new decimal number from an integer or a string representation.
1294
+
1295
+ A decimal number will always be created exactly as specified with all digits
1296
+ kept - it will not be rounded with the context.
1297
+
1298
+ ## Backus–Naur form
1299
+
1300
+ sign ::= "+" | "-"
1301
+ digit ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
1302
+ indicator ::= "e" | "E"
1303
+ digits ::= digit [digit]...
1304
+ decimal-part ::= digits "." [digits] | ["."] digits
1305
+ exponent-part ::= indicator [sign] digits
1306
+ infinity ::= "Infinity" | "Inf"
1307
+ nan ::= "NaN" [digits]
1308
+ numeric-value ::= decimal-part [exponent-part] | infinity
1309
+ numeric-string ::= [sign] numeric-value | [sign] nan
1310
+
1311
+ ## Floats
1312
+
1313
+ See also `from_float/1`.
1314
+
1315
+ ## Examples
1316
+
1317
+ iex> Decimal.new(1)
1318
+ Decimal.new("1")
1319
+
1320
+ iex> Decimal.new("3.14")
1321
+ Decimal.new("3.14")
1322
+
1323
+ """
1324
+ @spec new(decimal) :: t
1325
+ def new(%Decimal{sign: sign, coef: coef, exp: exp} = num)
1326
+ when sign in [1, -1] and ((is_integer(coef) and coef >= 0) or coef in [:NaN, :inf]) and
1327
+ is_integer(exp),
1328
+ do: num
1329
+
1330
+ def new(int) when is_integer(int),
1331
+ do: %Decimal{sign: if(int < 0, do: -1, else: 1), coef: Kernel.abs(int)}
1332
+
1333
+ def new(binary) when is_binary(binary) do
1334
+ case parse(binary) do
1335
+ {decimal, ""} -> decimal
1336
+ _ -> raise Error, reason: "number parsing syntax: #{inspect(binary)}"
1337
+ end
1338
+ end
1339
+
1340
+ @doc """
1341
+ Creates a new decimal number from the sign, coefficient and exponent such that
1342
+ the number will be: `sign * coefficient * 10 ^ exponent`.
1343
+
1344
+ A decimal number will always be created exactly as specified with all digits
1345
+ kept - it will not be rounded with the context.
1346
+
1347
+ ## Examples
1348
+
1349
+ iex> Decimal.new(1, 42, 0)
1350
+ Decimal.new("42")
1351
+
1352
+ """
1353
+ @spec new(sign :: 1 | -1, coef :: non_neg_integer | :NaN | :inf, exp :: integer) :: t
1354
+ def new(sign, coef, exp)
1355
+ when sign in [1, -1] and ((is_integer(coef) and coef >= 0) or coef in [:NaN, :inf]) and
1356
+ is_integer(exp),
1357
+ do: %Decimal{sign: sign, coef: coef, exp: exp}
1358
+
1359
+ @doc """
1360
+ Creates a new decimal number from a floating point number.
1361
+
1362
+ Floating point numbers use a fixed number of binary digits to represent
1363
+ a decimal number which has inherent inaccuracy as some decimal numbers cannot
1364
+ be represented exactly in limited precision binary.
1365
+
1366
+ Floating point numbers will be converted to decimal numbers with
1367
+ `:io_lib_format.fwrite_g/1`. Since this conversion is not exact and
1368
+ because of inherent inaccuracy mentioned above, we may run into counter-intuitive results:
1369
+
1370
+ iex> Enum.reduce([0.1, 0.1, 0.1], &+/2)
1371
+ 0.30000000000000004
1372
+
1373
+ iex> Enum.reduce([Decimal.new("0.1"), Decimal.new("0.1"), Decimal.new("0.1")], &Decimal.add/2)
1374
+ Decimal.new("0.3")
1375
+
1376
+ For this reason, it's recommended to build decimals with `new/1`, which is always precise, instead.
1377
+
1378
+ ## Examples
1379
+
1380
+ iex> Decimal.from_float(3.14)
1381
+ Decimal.new("3.14")
1382
+
1383
+ """
1384
+ doc_since("1.5.0")
1385
+ @spec from_float(float) :: t
1386
+ def from_float(float) when is_float(float) do
1387
+ float
1388
+ |> :io_lib_format.fwrite_g()
1389
+ |> fix_float_exp()
1390
+ |> IO.iodata_to_binary()
1391
+ |> new()
1392
+ end
1393
+
1394
+ @doc """
1395
+ Creates a new decimal number from an integer, string, float, or existing decimal number.
1396
+
1397
+ Because conversion from a floating point number is not exact, it's recommended
1398
+ to instead use `new/1` or `from_float/1` when the argument's type is certain.
1399
+ See `from_float/1`.
1400
+
1401
+ ## Examples
1402
+
1403
+ iex> {:ok, decimal} = Decimal.cast(3)
1404
+ iex> decimal
1405
+ Decimal.new("3")
1406
+
1407
+ iex> Decimal.cast("bad")
1408
+ :error
1409
+
1410
+ """
1411
+ @spec cast(term) :: {:ok, t} | :error
1412
+ def cast(integer) when is_integer(integer), do: {:ok, Decimal.new(integer)}
1413
+ def cast(%Decimal{} = decimal), do: {:ok, decimal}
1414
+ def cast(float) when is_float(float), do: {:ok, from_float(float)}
1415
+
1416
+ def cast(binary) when is_binary(binary) do
1417
+ case parse(binary) do
1418
+ {decimal, ""} -> {:ok, decimal}
1419
+ _ -> :error
1420
+ end
1421
+ end
1422
+
1423
+ def cast(_), do: :error
1424
+
1425
+ @doc """
1426
+ Parses a binary into a decimal.
1427
+
1428
+ If successful, returns a tuple in the form of `{decimal, remainder_of_binary}`,
1429
+ otherwise `:error`.
1430
+
1431
+ ## Examples
1432
+
1433
+ iex> Decimal.parse("3.14")
1434
+ {%Decimal{coef: 314, exp: -2, sign: 1}, ""}
1435
+
1436
+ iex> Decimal.parse("3.14.15")
1437
+ {%Decimal{coef: 314, exp: -2, sign: 1}, ".15"}
1438
+
1439
+ iex> Decimal.parse("-1.1e3")
1440
+ {%Decimal{coef: 11, exp: 2, sign: -1}, ""}
1441
+
1442
+ iex> Decimal.parse("bad")
1443
+ :error
1444
+
1445
+ """
1446
+ @spec parse(binary()) :: {t(), binary()} | :error
1447
+ def parse("+" <> rest) do
1448
+ parse_unsign(rest)
1449
+ end
1450
+
1451
+ def parse("-" <> rest) do
1452
+ case parse_unsign(rest) do
1453
+ {%Decimal{} = num, rest} -> {%{num | sign: -1}, rest}
1454
+ :error -> :error
1455
+ end
1456
+ end
1457
+
1458
+ def parse(binary) when is_binary(binary) do
1459
+ parse_unsign(binary)
1460
+ end
1461
+
1462
+ @doc """
1463
+ Converts given number to its string representation.
1464
+
1465
+ ## Options
1466
+
1467
+ * `:scientific` - number converted to scientific notation.
1468
+ * `:normal` - number converted without a exponent.
1469
+ * `:xsd` - number converted to the [canonical XSD representation](https://www.w3.org/TR/xmlschema-2/#decimal).
1470
+ * `:raw` - number converted to its raw, internal format.
1471
+
1472
+ ## Examples
1473
+
1474
+ iex> Decimal.to_string(Decimal.new("1.00"))
1475
+ "1.00"
1476
+
1477
+ iex> Decimal.to_string(Decimal.new("123e1"), :scientific)
1478
+ "1.23E+3"
1479
+
1480
+ iex> Decimal.to_string(Decimal.new("42.42"), :normal)
1481
+ "42.42"
1482
+
1483
+ iex> Decimal.to_string(Decimal.new("1.00"), :xsd)
1484
+ "1.0"
1485
+
1486
+ iex> Decimal.to_string(Decimal.new("4321.768"), :raw)
1487
+ "4321768E-3"
1488
+
1489
+ """
1490
+ @spec to_string(t, :scientific | :normal | :xsd | :raw) :: String.t()
1491
+ def to_string(num, type \\ :scientific)
1492
+
1493
+ def to_string(%Decimal{sign: sign, coef: :NaN}, _type) do
1494
+ if sign == 1, do: "NaN", else: "-NaN"
1495
+ end
1496
+
1497
+ def to_string(%Decimal{sign: sign, coef: :inf}, _type) do
1498
+ if sign == 1, do: "Infinity", else: "-Infinity"
1499
+ end
1500
+
1501
+ def to_string(%Decimal{sign: sign, coef: coef, exp: exp}, :normal) do
1502
+ list = integer_to_charlist(coef)
1503
+
1504
+ list =
1505
+ if exp >= 0 do
1506
+ list ++ :lists.duplicate(exp, ?0)
1507
+ else
1508
+ diff = length(list) + exp
1509
+
1510
+ if diff > 0 do
1511
+ List.insert_at(list, diff, ?.)
1512
+ else
1513
+ ~c"0." ++ :lists.duplicate(-diff, ?0) ++ list
1514
+ end
1515
+ end
1516
+
1517
+ list = if sign == -1, do: [?- | list], else: list
1518
+ IO.iodata_to_binary(list)
1519
+ end
1520
+
1521
+ def to_string(%Decimal{sign: sign, coef: coef, exp: exp}, :scientific) do
1522
+ list = integer_to_charlist(coef)
1523
+ length = length(list)
1524
+ adjusted = exp + length - 1
1525
+
1526
+ list =
1527
+ cond do
1528
+ exp == 0 ->
1529
+ list
1530
+
1531
+ exp < 0 and adjusted >= -6 ->
1532
+ abs_exp = Kernel.abs(exp)
1533
+ diff = -length + abs_exp + 1
1534
+
1535
+ if diff > 0 do
1536
+ list = :lists.duplicate(diff, ?0) ++ list
1537
+ List.insert_at(list, 1, ?.)
1538
+ else
1539
+ List.insert_at(list, exp - 1, ?.)
1540
+ end
1541
+
1542
+ true ->
1543
+ list = if length > 1, do: List.insert_at(list, 1, ?.), else: list
1544
+ list = list ++ ~c"E"
1545
+ list = if exp >= 0, do: list ++ ~c"+", else: list
1546
+ list ++ integer_to_charlist(adjusted)
1547
+ end
1548
+
1549
+ list = if sign == -1, do: [?- | list], else: list
1550
+ IO.iodata_to_binary(list)
1551
+ end
1552
+
1553
+ def to_string(%Decimal{sign: sign, coef: coef, exp: exp}, :raw) do
1554
+ str = Integer.to_string(coef)
1555
+ str = if sign == -1, do: [?- | str], else: str
1556
+ str = if exp != 0, do: [str, "E", Integer.to_string(exp)], else: str
1557
+
1558
+ IO.iodata_to_binary(str)
1559
+ end
1560
+
1561
+ def to_string(%Decimal{} = decimal, :xsd) do
1562
+ decimal |> canonical_xsd() |> to_string(:normal)
1563
+ end
1564
+
1565
+ defp canonical_xsd(%Decimal{coef: 0} = decimal), do: %{decimal | exp: -1}
1566
+
1567
+ defp canonical_xsd(%Decimal{coef: coef, exp: 0} = decimal),
1568
+ do: %{decimal | coef: coef * 10, exp: -1}
1569
+
1570
+ defp canonical_xsd(%Decimal{coef: coef, exp: exp} = decimal)
1571
+ when exp > 0,
1572
+ do: canonical_xsd(%{decimal | coef: coef * 10, exp: exp - 1})
1573
+
1574
+ defp canonical_xsd(%Decimal{coef: coef} = decimal)
1575
+ when Kernel.rem(coef, 10) != 0,
1576
+ do: decimal
1577
+
1578
+ defp canonical_xsd(%Decimal{coef: coef, exp: exp} = decimal),
1579
+ do: canonical_xsd(%{decimal | coef: Kernel.div(coef, 10), exp: exp + 1})
1580
+
1581
+ @doc """
1582
+ Returns the decimal represented as an integer.
1583
+
1584
+ Fails when loss of precision will occur.
1585
+
1586
+ ## Examples
1587
+
1588
+ iex> Decimal.to_integer(Decimal.new("42"))
1589
+ 42
1590
+
1591
+ iex> Decimal.to_integer(Decimal.new("1.00"))
1592
+ 1
1593
+
1594
+ iex> Decimal.to_integer(Decimal.new("1.10"))
1595
+ ** (ArgumentError) cannot convert Decimal.new("1.1") without losing precision. Use Decimal.round/3 first.
1596
+
1597
+ """
1598
+ @spec to_integer(t) :: integer
1599
+ def to_integer(%Decimal{sign: sign, coef: coef, exp: 0})
1600
+ when is_integer(coef),
1601
+ do: sign * coef
1602
+
1603
+ def to_integer(%Decimal{sign: sign, coef: coef, exp: exp})
1604
+ when is_integer(coef) and exp > 0,
1605
+ do: to_integer(%Decimal{sign: sign, coef: coef * 10, exp: exp - 1})
1606
+
1607
+ def to_integer(%Decimal{sign: sign, coef: coef, exp: exp})
1608
+ when is_integer(coef) and exp < 0 and Kernel.rem(coef, 10) == 0,
1609
+ do: to_integer(%Decimal{sign: sign, coef: Kernel.div(coef, 10), exp: exp + 1})
1610
+
1611
+ def to_integer(%Decimal{coef: coef} = decimal) when is_integer(coef) do
1612
+ raise ArgumentError,
1613
+ "cannot convert #{inspect(decimal)} without losing precision. Use Decimal.round/3 first."
1614
+ end
1615
+
1616
+ @doc """
1617
+ Returns the decimal converted to a float.
1618
+
1619
+ The returned float may have lower precision than the decimal. Fails if
1620
+ the decimal cannot be converted to a float.
1621
+
1622
+ ## Examples
1623
+
1624
+ iex> Decimal.to_float(Decimal.new("1.5"))
1625
+ 1.5
1626
+
1627
+ """
1628
+ @spec to_float(t) :: float
1629
+ def to_float(%Decimal{sign: sign, coef: coef, exp: exp}) when is_integer(coef) do
1630
+ # Convert back to float without loss
1631
+ # http://www.exploringbinary.com/correct-decimal-to-floating-point-using-big-integers/
1632
+ {num, den} = ratio(coef, exp)
1633
+
1634
+ boundary = den <<< 52
1635
+
1636
+ cond do
1637
+ num == 0 ->
1638
+ 0.0
1639
+
1640
+ num >= boundary ->
1641
+ {den, exp} = scale_down(num, boundary, 52)
1642
+ decimal_to_float(sign, num, den, exp)
1643
+
1644
+ true ->
1645
+ {num, exp} = scale_up(num, boundary, 52)
1646
+ decimal_to_float(sign, num, den, exp)
1647
+ end
1648
+ end
1649
+
1650
+ @doc """
1651
+ Returns the scale of the decimal.
1652
+
1653
+ A decimal's scale is the number of digits after the decimal point. This
1654
+ includes trailing zeros; see `normalize/1` to remove them.
1655
+
1656
+ ## Examples
1657
+
1658
+ iex> Decimal.scale(Decimal.new("42"))
1659
+ 0
1660
+
1661
+ iex> Decimal.scale(Decimal.new(1, 2, 26))
1662
+ 0
1663
+
1664
+ iex> Decimal.scale(Decimal.new("99.12345"))
1665
+ 5
1666
+
1667
+ iex> Decimal.scale(Decimal.new("1.50"))
1668
+ 2
1669
+ """
1670
+ @spec scale(t) :: non_neg_integer()
1671
+ def scale(%Decimal{exp: exp}), do: Kernel.max(0, -exp)
1672
+
1673
+ defp scale_up(num, den, exp) when num >= den, do: {num, exp}
1674
+ defp scale_up(num, den, exp), do: scale_up(num <<< 1, den, exp - 1)
1675
+
1676
+ defp scale_down(num, den, exp) do
1677
+ new_den = den <<< 1
1678
+
1679
+ if num < new_den do
1680
+ {den >>> 52, exp}
1681
+ else
1682
+ scale_down(num, new_den, exp + 1)
1683
+ end
1684
+ end
1685
+
1686
+ defp decimal_to_float(sign, num, den, exp) do
1687
+ quo = Kernel.div(num, den)
1688
+ rem = num - quo * den
1689
+
1690
+ tmp =
1691
+ case den >>> 1 do
1692
+ den when rem > den -> quo + 1
1693
+ den when rem < den -> quo
1694
+ _ when (quo &&& 1) === 1 -> quo + 1
1695
+ _ -> quo
1696
+ end
1697
+
1698
+ sign = if sign == -1, do: 1, else: 0
1699
+ tmp = tmp - @power_of_2_to_52
1700
+ exp = if tmp < @power_of_2_to_52, do: exp, else: exp + 1
1701
+ <<tmp::float>> = <<sign::size(1), exp + 1023::size(11), tmp::size(52)>>
1702
+ tmp
1703
+ end
1704
+
1705
+ @doc """
1706
+ Returns `true` when the given `decimal` has no significant digits after the decimal point.
1707
+
1708
+ ## Examples
1709
+
1710
+ iex> Decimal.integer?("1.00")
1711
+ true
1712
+
1713
+ iex> Decimal.integer?("1.10")
1714
+ false
1715
+
1716
+ """
1717
+ doc_since("2.0.0")
1718
+ @spec integer?(decimal()) :: boolean
1719
+ def integer?(%Decimal{coef: :NaN}), do: false
1720
+ def integer?(%Decimal{coef: :inf}), do: false
1721
+ def integer?(%Decimal{coef: coef, exp: exp}), do: exp >= 0 or zero_after_dot?(coef, exp)
1722
+ def integer?(num), do: integer?(decimal(num))
1723
+
1724
+ defp zero_after_dot?(coef, exp) when coef >= 10 and exp < 0,
1725
+ do: Kernel.rem(coef, 10) == 0 and zero_after_dot?(Kernel.div(coef, 10), exp + 1)
1726
+
1727
+ defp zero_after_dot?(coef, exp),
1728
+ do: coef == 0 or exp == 0
1729
+
1730
+ ## ARITHMETIC ##
1731
+
1732
+ defp add_align(coef1, exp1, coef2, exp2) when exp1 == exp2, do: {coef1, coef2}
1733
+
1734
+ defp add_align(coef1, exp1, coef2, exp2) when exp1 > exp2,
1735
+ do: {coef1 * pow10(exp1 - exp2), coef2}
1736
+
1737
+ defp add_align(coef1, exp1, coef2, exp2) when exp1 < exp2,
1738
+ do: {coef1, coef2 * pow10(exp2 - exp1)}
1739
+
1740
+ defp add_sign(sign1, sign2, coef) do
1741
+ cond do
1742
+ coef > 0 -> 1
1743
+ coef < 0 -> -1
1744
+ sign1 == -1 and sign2 == -1 -> -1
1745
+ sign1 != sign2 and Context.get().rounding == :floor -> -1
1746
+ true -> 1
1747
+ end
1748
+ end
1749
+
1750
+ defp div_adjust(coef1, coef2, adjust) when coef1 < coef2,
1751
+ do: div_adjust(coef1 * 10, coef2, adjust + 1)
1752
+
1753
+ defp div_adjust(coef1, coef2, adjust) when coef1 >= coef2 * 10,
1754
+ do: div_adjust(coef1, coef2 * 10, adjust - 1)
1755
+
1756
+ defp div_adjust(coef1, coef2, adjust), do: {coef1, coef2, adjust}
1757
+
1758
+ defp div_calc(coef1, coef2, coef, adjust, prec10) do
1759
+ cond do
1760
+ coef1 >= coef2 ->
1761
+ div_calc(coef1 - coef2, coef2, coef + 1, adjust, prec10)
1762
+
1763
+ coef1 == 0 and adjust >= 0 ->
1764
+ {coef, adjust, coef1, []}
1765
+
1766
+ coef >= prec10 ->
1767
+ signals = [:rounded]
1768
+ signals = if base10?(coef1), do: signals, else: [:inexact | signals]
1769
+ {coef, adjust, coef1, signals}
1770
+
1771
+ true ->
1772
+ div_calc(coef1 * 10, coef2, coef * 10, adjust + 1, prec10)
1773
+ end
1774
+ end
1775
+
1776
+ defp div_int_calc(coef1, coef2, coef, adjust, precision) do
1777
+ cond do
1778
+ coef1 >= coef2 ->
1779
+ div_int_calc(coef1 - coef2, coef2, coef + 1, adjust, precision)
1780
+
1781
+ adjust != precision ->
1782
+ div_int_calc(coef1 * 10, coef2, coef * 10, adjust + 1, precision)
1783
+
1784
+ true ->
1785
+ {coef, coef1}
1786
+ end
1787
+ end
1788
+
1789
+ defp integer_division(div_sign, coef1, exp1, coef2, exp2) do
1790
+ precision = exp1 - exp2
1791
+ {coef1, coef2, adjust} = div_adjust(coef1, coef2, 0)
1792
+
1793
+ {coef, _rem} = div_int_calc(coef1, coef2, 0, adjust, precision)
1794
+
1795
+ prec10 = pow10(Context.get().precision)
1796
+
1797
+ if coef > prec10 do
1798
+ {
1799
+ :error,
1800
+ :invalid_operation,
1801
+ "integer division impossible, quotient too large",
1802
+ %Decimal{coef: :NaN}
1803
+ }
1804
+ else
1805
+ {:ok, %Decimal{sign: div_sign, coef: coef, exp: 0}}
1806
+ end
1807
+ end
1808
+
1809
+ defp do_normalize(coef, exp) do
1810
+ if Kernel.rem(coef, 10) == 0 do
1811
+ do_normalize(Kernel.div(coef, 10), exp + 1)
1812
+ else
1813
+ %Decimal{coef: coef, exp: exp}
1814
+ end
1815
+ end
1816
+
1817
+ defp ratio(coef, exp) when exp >= 0, do: {coef * pow10(exp), 1}
1818
+ defp ratio(coef, exp) when exp < 0, do: {coef, pow10(-exp)}
1819
+
1820
+ pow10_max =
1821
+ Enum.reduce(0..104, 1, fn int, acc ->
1822
+ defp pow10(unquote(int)), do: unquote(acc)
1823
+ defp base10?(unquote(acc)), do: true
1824
+ acc * 10
1825
+ end)
1826
+
1827
+ defp pow10(num) when num > 104, do: pow10(104) * pow10(num - 104)
1828
+
1829
+ defp base10?(num) when num >= unquote(pow10_max) do
1830
+ if Kernel.rem(num, unquote(pow10_max)) == 0 do
1831
+ base10?(Kernel.div(num, unquote(pow10_max)))
1832
+ else
1833
+ false
1834
+ end
1835
+ end
1836
+
1837
+ defp base10?(_num), do: false
1838
+
1839
+ ## ROUNDING ##
1840
+
1841
+ defp do_round(sign, digits, exp, target_exp, rounding) do
1842
+ num_digits = length(digits)
1843
+ precision = num_digits - (target_exp - exp)
1844
+
1845
+ cond do
1846
+ exp == target_exp ->
1847
+ %Decimal{sign: sign, coef: digits_to_integer(digits), exp: exp}
1848
+
1849
+ exp < target_exp and precision < 0 ->
1850
+ zeros = :lists.duplicate(target_exp - exp, ?0)
1851
+ digits = zeros ++ digits
1852
+ {signif, remain} = :lists.split(1, digits)
1853
+
1854
+ signif =
1855
+ if increment?(rounding, sign, signif, remain),
1856
+ do: digits_increment(signif),
1857
+ else: signif
1858
+
1859
+ coef = digits_to_integer(signif)
1860
+ %Decimal{sign: sign, coef: coef, exp: target_exp}
1861
+
1862
+ exp < target_exp and precision >= 0 ->
1863
+ {signif, remain} = :lists.split(precision, digits)
1864
+
1865
+ signif =
1866
+ if increment?(rounding, sign, signif, remain),
1867
+ do: digits_increment(signif),
1868
+ else: signif
1869
+
1870
+ coef = digits_to_integer(signif)
1871
+ %Decimal{sign: sign, coef: coef, exp: target_exp}
1872
+
1873
+ exp > target_exp ->
1874
+ digits = digits ++ Enum.map(1..(exp - target_exp), fn _ -> ?0 end)
1875
+ coef = digits_to_integer(digits)
1876
+ %Decimal{sign: sign, coef: coef, exp: target_exp}
1877
+ end
1878
+ end
1879
+
1880
+ defp digits_to_integer([]), do: 0
1881
+ defp digits_to_integer(digits), do: :erlang.list_to_integer(digits)
1882
+
1883
+ defp precision(%Decimal{coef: :NaN} = num, _precision, _rounding) do
1884
+ {num, []}
1885
+ end
1886
+
1887
+ defp precision(%Decimal{coef: :inf} = num, _precision, _rounding) do
1888
+ {num, []}
1889
+ end
1890
+
1891
+ defp precision(%Decimal{sign: sign, coef: coef, exp: exp} = num, precision, rounding) do
1892
+ digits = :erlang.integer_to_list(coef)
1893
+ num_digits = length(digits)
1894
+
1895
+ if num_digits > precision do
1896
+ do_precision(sign, digits, num_digits, exp, precision, rounding)
1897
+ else
1898
+ {num, []}
1899
+ end
1900
+ end
1901
+
1902
+ defp do_precision(sign, digits, num_digits, exp, precision, rounding) do
1903
+ precision = Kernel.min(num_digits, precision)
1904
+ {signif, remain} = :lists.split(precision, digits)
1905
+
1906
+ signif =
1907
+ if increment?(rounding, sign, signif, remain), do: digits_increment(signif), else: signif
1908
+
1909
+ signals = if any_nonzero(remain), do: [:inexact, :rounded], else: [:rounded]
1910
+
1911
+ exp = exp + length(remain)
1912
+ coef = digits_to_integer(signif)
1913
+ dec = %Decimal{sign: sign, coef: coef, exp: exp}
1914
+ {dec, signals}
1915
+ end
1916
+
1917
+ defp increment?(_, _, _, []), do: false
1918
+
1919
+ defp increment?(:down, _, _, _), do: false
1920
+
1921
+ defp increment?(:up, _, _, _), do: true
1922
+
1923
+ defp increment?(:ceiling, sign, _, remain), do: sign == 1 and any_nonzero(remain)
1924
+
1925
+ defp increment?(:floor, sign, _, remain), do: sign == -1 and any_nonzero(remain)
1926
+
1927
+ defp increment?(:half_up, _, _, [digit | _]), do: digit >= ?5
1928
+
1929
+ defp increment?(:half_even, _, [], [?5 | rest]), do: any_nonzero(rest)
1930
+
1931
+ defp increment?(:half_even, _, signif, [?5 | rest]),
1932
+ do: any_nonzero(rest) or Kernel.rem(:lists.last(signif), 2) == 1
1933
+
1934
+ defp increment?(:half_even, _, _, [digit | _]), do: digit > ?5
1935
+
1936
+ defp increment?(:half_down, _, _, [digit | rest]),
1937
+ do: digit > ?5 or (digit == ?5 and any_nonzero(rest))
1938
+
1939
+ defp any_nonzero(digits), do: :lists.any(fn digit -> digit != ?0 end, digits)
1940
+
1941
+ defp digits_increment(digits), do: digits_increment(:lists.reverse(digits), [])
1942
+
1943
+ defp digits_increment([?9 | rest], acc), do: digits_increment(rest, [?0 | acc])
1944
+
1945
+ defp digits_increment([head | rest], acc), do: :lists.reverse(rest, [head + 1 | acc])
1946
+
1947
+ defp digits_increment([], acc), do: [?1 | acc]
1948
+
1949
+ ## CONTEXT ##
1950
+
1951
+ defp context(num, signals \\ []) do
1952
+ context = Context.get()
1953
+ {result, prec_signals} = precision(num, context.precision, context.rounding)
1954
+ error(put_uniq(signals, prec_signals), nil, result, context)
1955
+ end
1956
+
1957
+ defp put_uniq(list, elems) when is_list(elems) do
1958
+ Enum.reduce(elems, list, &put_uniq(&2, &1))
1959
+ end
1960
+
1961
+ defp put_uniq(list, elem) do
1962
+ if elem in list, do: list, else: [elem | list]
1963
+ end
1964
+
1965
+ ## PARSING ##
1966
+
1967
+ defp parse_unsign(<<first, remainder::size(7)-binary, rest::binary>>) when first in [?i, ?I] do
1968
+ if String.downcase(remainder) == "nfinity" do
1969
+ {%Decimal{coef: :inf}, rest}
1970
+ else
1971
+ :error
1972
+ end
1973
+ end
1974
+
1975
+ defp parse_unsign(<<first, remainder::size(2)-binary, rest::binary>>) when first in [?i, ?I] do
1976
+ if String.downcase(remainder) == "nf" do
1977
+ {%Decimal{coef: :inf}, rest}
1978
+ else
1979
+ :error
1980
+ end
1981
+ end
1982
+
1983
+ defp parse_unsign(<<first, remainder::size(2)-binary, rest::binary>>) when first in [?n, ?N] do
1984
+ if String.downcase(remainder) == "an" do
1985
+ {%Decimal{coef: :NaN}, rest}
1986
+ else
1987
+ :error
1988
+ end
1989
+ end
1990
+
1991
+ defp parse_unsign(bin) do
1992
+ {int, rest} = parse_digits(bin)
1993
+ {float, rest} = parse_float(rest)
1994
+ {exp, rest} = parse_exp(rest)
1995
+
1996
+ if int == [] and float == [] do
1997
+ :error
1998
+ else
1999
+ int = if int == [], do: ~c"0", else: int
2000
+ exp = if exp == [], do: ~c"0", else: exp
2001
+
2002
+ number = %Decimal{
2003
+ coef: List.to_integer(int ++ float),
2004
+ exp: List.to_integer(exp) - length(float)
2005
+ }
2006
+
2007
+ {number, rest}
2008
+ end
2009
+ end
2010
+
2011
+ defp parse_float("." <> rest), do: parse_digits(rest)
2012
+ defp parse_float(bin), do: {[], bin}
2013
+
2014
+ defp parse_exp(<<e, rest::binary>>) when e in [?e, ?E] do
2015
+ case rest do
2016
+ <<sign, rest::binary>> when sign in [?+, ?-] ->
2017
+ {digits, rest} = parse_digits(rest)
2018
+ {[sign | digits], rest}
2019
+
2020
+ _ ->
2021
+ parse_digits(rest)
2022
+ end
2023
+ end
2024
+
2025
+ defp parse_exp(bin) do
2026
+ {[], bin}
2027
+ end
2028
+
2029
+ defp parse_digits(bin), do: parse_digits(bin, [])
2030
+
2031
+ defp parse_digits(<<digit, rest::binary>>, acc) when digit in ?0..?9 do
2032
+ parse_digits(rest, [digit | acc])
2033
+ end
2034
+
2035
+ defp parse_digits(rest, acc) do
2036
+ {:lists.reverse(acc), rest}
2037
+ end
2038
+
2039
+ # Util
2040
+
2041
+ defp decimal(%Decimal{} = num), do: num
2042
+ defp decimal(num) when is_integer(num), do: new(num)
2043
+ defp decimal(num) when is_binary(num), do: new(num)
2044
+
2045
+ defp decimal(other) when is_float(other) do
2046
+ raise ArgumentError,
2047
+ "implicit conversion of #{inspect(other)} to Decimal is not allowed. Use Decimal.from_float/1"
2048
+ end
2049
+
2050
+ defp handle_error(signals, reason, result, context) do
2051
+ context = context || Context.get()
2052
+ signals = List.wrap(signals)
2053
+
2054
+ flags = Enum.reduce(signals, context.flags, &put_uniq(&2, &1))
2055
+ Context.set(%{context | flags: flags})
2056
+ error_signal = Enum.find(signals, &(&1 in context.traps))
2057
+
2058
+ if error_signal do
2059
+ error = [signal: error_signal, reason: reason]
2060
+ {:error, error}
2061
+ else
2062
+ {:ok, result}
2063
+ end
2064
+ end
2065
+
2066
+ defp fix_float_exp(digits) do
2067
+ fix_float_exp(digits, [])
2068
+ end
2069
+
2070
+ defp fix_float_exp([?e | rest], [?0 | [?. | result]]) do
2071
+ fix_float_exp(rest, [?e | result])
2072
+ end
2073
+
2074
+ defp fix_float_exp([digit | rest], result) do
2075
+ fix_float_exp(rest, [digit | result])
2076
+ end
2077
+
2078
+ defp fix_float_exp([], result), do: :lists.reverse(result)
2079
+
2080
+ if Version.compare(System.version(), "1.3.0") == :lt do
2081
+ defp integer_to_charlist(string), do: Integer.to_char_list(string)
2082
+ else
2083
+ defp integer_to_charlist(string), do: Integer.to_charlist(string)
2084
+ end
2085
+ end
2086
+
2087
+ defimpl Inspect, for: Decimal do
2088
+ def inspect(dec, _opts) do
2089
+ "Decimal.new(\"" <> Decimal.to_string(dec) <> "\")"
2090
+ end
2091
+ end
2092
+
2093
+ defimpl String.Chars, for: Decimal do
2094
+ def to_string(dec) do
2095
+ Decimal.to_string(dec)
2096
+ end
2097
+ end
2098
+
2099
+ # TODO: remove when we require Elixir 1.18
2100
+ if Code.ensure_loaded?(JSON.Encoder) and function_exported?(JSON.Encoder, :encode, 2) do
2101
+ defimpl JSON.Encoder, for: Decimal do
2102
+ def encode(decimal, _encoder) do
2103
+ [?", Decimal.to_string(decimal), ?"]
2104
+ end
2105
+ end
2106
+ end
deps/decimal/lib/decimal/context.ex ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Decimal.Context do
2
+ import Decimal.Macros
3
+ alias Decimal.Context
4
+
5
+ @moduledoc """
6
+ The context is kept in the process dictionary. It can be accessed with
7
+ `get/0` and `set/1`.
8
+
9
+ The default context has a precision of 28, the rounding algorithm is
10
+ `:half_up`. The set trap enablers are `:invalid_operation` and
11
+ `:division_by_zero`.
12
+
13
+ ## Fields
14
+
15
+ * `precision` - maximum number of decimal digits in the coefficient. If an
16
+ operation result has more digits it will be rounded to `precision`
17
+ digits with the rounding algorithm in `rounding`.
18
+ * `rounding` - the rounding algorithm used when the coefficient's number of
19
+ exceeds `precision`. Strategies explained below.
20
+ * `flags` - a list of signals that for which the flag is sent. When an
21
+ exceptional condition is signalled its flag is set. The flags are sticky
22
+ and will be set until explicitly cleared.
23
+ * `traps` - a list of set trap enablers for signals. When a signal's trap
24
+ enabler is set the condition causes `Decimal.Error` to be raised.
25
+
26
+ ## Rounding algorithms
27
+
28
+ * `:down` - round toward zero (truncate). Discarded digits are ignored,
29
+ result is unchanged.
30
+ * `:half_up` - if the discarded digits is greater than or equal to half of
31
+ the value of a one in the next left position then the coefficient will be
32
+ incremented by one (rounded up). Otherwise (the discarded digits are less
33
+ than half) the discarded digits will be ignored.
34
+ * `:half_even` - also known as "round to nearest" or "banker's rounding". If
35
+ the discarded digits is greater than half of the value of a one in the
36
+ next left position then the coefficient will be incremented by one
37
+ (rounded up). If they represent less than half discarded digits will be
38
+ ignored. Otherwise (exactly half), the coefficient is not altered if it's
39
+ even, or incremented by one (rounded up) if it's odd (to make an even
40
+ number).
41
+ * `:ceiling` - round toward +Infinity. If all of the discarded digits are
42
+ zero or the sign is negative the result is unchanged. Otherwise, the
43
+ coefficient will be incremented by one (rounded up).
44
+ * `:floor` - round toward -Infinity. If all of the discarded digits are zero
45
+ or the sign is positive the result is unchanged. Otherwise, the sign is
46
+ negative and coefficient will be incremented by one.
47
+ * `:half_down` - if the discarded digits is greater than half of the value
48
+ of a one in the next left position then the coefficient will be
49
+ incremented by one (rounded up). Otherwise (the discarded digits are half
50
+ or less) the discarded digits are ignored.
51
+ * `:up` - round away from zero. If all discarded digits are zero the
52
+ coefficient is not changed, otherwise it is incremented by one (rounded
53
+ up).
54
+
55
+ This table shows the results of rounding operations for all the rounding
56
+ algorithms:
57
+
58
+ Rounding algorithm | 5.5 | 2.5 | 1.6 | 1.1 | 1.0 | -1.0 | -1.1 | -1.6 | -2.5 | -5.5
59
+ :----------------- | :-- | :-- | :-- | :-- | :-- | :--- | :--- | :--- | :--- | :---
60
+ `:up` | 6 | 3 | 2 | 2 | 1 | -1 | -2 | -2 | -3 | -6
61
+ `:down` | 5 | 2 | 1 | 1 | 1 | -1 | -1 | -1 | -2 | -5
62
+ `:ceiling` | 6 | 3 | 2 | 2 | 1 | -1 | -1 | -1 | -2 | -5
63
+ `:floor` | 5 | 2 | 1 | 1 | 1 | -1 | -2 | -2 | -3 | -6
64
+ `:half_up` | 6 | 3 | 2 | 1 | 1 | -1 | -1 | -2 | -3 | -6
65
+ `:half_down` | 5 | 2 | 2 | 1 | 1 | -1 | -1 | -2 | -2 | -5
66
+ `:half_even` | 6 | 2 | 2 | 1 | 1 | -1 | -1 | -2 | -2 | -6
67
+
68
+ """
69
+ @type t :: %__MODULE__{
70
+ precision: pos_integer,
71
+ rounding: Decimal.rounding(),
72
+ flags: [Decimal.signal()],
73
+ traps: [Decimal.signal()]
74
+ }
75
+
76
+ defstruct precision: 28,
77
+ rounding: :half_up,
78
+ flags: [],
79
+ traps: [:invalid_operation, :division_by_zero]
80
+
81
+ @context_key :"$decimal_context"
82
+
83
+ @doc """
84
+ Runs function with given context.
85
+ """
86
+ doc_since("1.9.0")
87
+ @spec with(t(), (-> x)) :: x when x: var
88
+ def with(%Context{} = context, fun) when is_function(fun, 0) do
89
+ old = Process.put(@context_key, context)
90
+
91
+ try do
92
+ fun.()
93
+ after
94
+ set(old || %Context{})
95
+ end
96
+ end
97
+
98
+ @doc """
99
+ Gets the process' context.
100
+ """
101
+ doc_since("1.9.0")
102
+ @spec get() :: t()
103
+ def get() do
104
+ Process.get(@context_key, %Context{})
105
+ end
106
+
107
+ @doc """
108
+ Set the process' context.
109
+ """
110
+ doc_since("1.9.0")
111
+ @spec set(t()) :: :ok
112
+ def set(%Context{} = context) do
113
+ Process.put(@context_key, context)
114
+ :ok
115
+ end
116
+
117
+ @doc """
118
+ Update the process' context.
119
+ """
120
+ doc_since("1.9.0")
121
+ @spec update((t() -> t())) :: :ok
122
+ def update(fun) when is_function(fun, 1) do
123
+ get() |> fun.() |> set()
124
+ end
125
+ end
deps/decimal/lib/decimal/error.ex ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Decimal.Error do
2
+ @moduledoc """
3
+ The exception that all decimal operations may raise.
4
+
5
+ ## Fields
6
+
7
+ * `signal` - the signalled error, additional signalled errors will be found
8
+ in the context.
9
+ * `reason` - the reason for the error.
10
+
11
+ Rescuing the error to access the result or the other fields of the error is
12
+ discouraged and should only be done for exceptional conditions. It is more
13
+ pragmatic to set the appropriate traps on the context and check the flags
14
+ after the operation if the result needs to be inspected.
15
+ """
16
+
17
+ defexception [:signal, :reason]
18
+
19
+ @impl true
20
+ def message(%{signal: signal, reason: reason}) do
21
+ reason = reason && ": " <> reason
22
+ "#{signal}#{reason}"
23
+ end
24
+ end
deps/decimal/lib/decimal/macros.ex ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Decimal.Macros do
2
+ @moduledoc false
3
+
4
+ defmacro doc_since(version) do
5
+ if Version.match?(System.version(), ">= 1.7.0") do
6
+ quote do
7
+ @doc since: unquote(version)
8
+ end
9
+ end
10
+ end
11
+ end
deps/decimal/mix.exs ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Decimal.Mixfile do
2
+ use Mix.Project
3
+
4
+ @version "2.3.0"
5
+ @source_url "https://github.com/ericmj/decimal"
6
+
7
+ def project() do
8
+ [
9
+ app: :decimal,
10
+ version: @version,
11
+ elixir: "~> 1.8",
12
+ deps: deps(),
13
+ name: "Decimal",
14
+ source_url: @source_url,
15
+ docs: [source_ref: "v#{@version}", main: "readme", extras: ["README.md"]],
16
+ description: description(),
17
+ package: package()
18
+ ]
19
+ end
20
+
21
+ def application() do
22
+ []
23
+ end
24
+
25
+ defp deps() do
26
+ [
27
+ {:ex_doc, ">= 0.0.0", only: :dev},
28
+ {:stream_data, "~> 0.5.0", only: :test}
29
+ ]
30
+ end
31
+
32
+ defp description() do
33
+ "Arbitrary precision decimal arithmetic."
34
+ end
35
+
36
+ defp package() do
37
+ [
38
+ maintainers: ["Eric Meadows-Jönsson"],
39
+ licenses: ["Apache-2.0"],
40
+ links: %{"GitHub" => @source_url}
41
+ ]
42
+ end
43
+ end
deps/explorer/.hex ADDED
Binary file (265 Bytes). View file
 
deps/explorer/CHANGELOG.md ADDED
@@ -0,0 +1,1228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [v0.10.1] - 2024-11-28
11
+
12
+ ### Fixed
13
+
14
+ - Fix creation of series of `{:list, {:decimal, ...}}` containing empty lists.
15
+
16
+ - Use `i128` for `:coef` field in the Rust code.
17
+
18
+ This field is a positive, arbitrary precision integer on the Elixir side.
19
+ It's convenient to represent it as a signed `i128` because that's
20
+ what the Decimal dtype expects. While you could technically create an
21
+ `ExDecimal` struct with a negative `coef`, it's not a practical concern.
22
+
23
+ - Fix `Explorer.DataFrame.print/1` for empty dataframes.
24
+
25
+ - Fix datetime encoding overflow.
26
+
27
+ Before we were always converting first to a microsecond-based representation
28
+ then to the final representation. The intermediate conversion is unecessary
29
+ and risks overflows when trying to convert to a different time unit later.
30
+ This approach converts directly to `i64` from the Elixir struct and time unit.
31
+
32
+ - Encode millisecond precision for time and datetime series.
33
+
34
+ - Fix list struct print bug.
35
+
36
+ Fixes an issue where we can't print columns with a dtype like `{:list, {:struct, ...}}`
37
+ where the root of the tree isn't a `:struct` but it contains a `:struct`.
38
+
39
+ ### Deprecated
40
+
41
+ - Remove documentation for deprecated functions `to_date/1` and `to_time/1`.
42
+ They are functions from the `Explorer.Series` that soon will be removed.
43
+
44
+ ## [v0.10.0] - 2024-10-23
45
+
46
+ ### Added
47
+
48
+ - Add support for the decimals data type.
49
+
50
+ Decimals dtypes are represented by the `{:decimal, precision, scale}` tuple,
51
+ where precision can be a positive integer from 0 to 38, and is the maximum number
52
+ of digits that can be represented by the decimal. The scale is the number of
53
+ digits after the decimal point.
54
+
55
+ With this addition, we also added the `:decimal` package as a new dependency.
56
+ The `Explorer.Series.from_list/2` function accepts decimal numbers from that
57
+ package as values - `%Decimal{}`.
58
+
59
+ This version has a small number of operations, but is a good foundation.
60
+
61
+ - Allow the usage of queries and lazy series outside callbacks and macros.
62
+ This is an improvement to functions that were originally designed to accept callbacks.
63
+ With this change you can now reuse lazy series across different "queries".
64
+ See the `Explorer.Query` docs for details.
65
+
66
+ The affected functions are:
67
+
68
+ * `Explorer.DataFrame.filter_with/2`
69
+ * `Explorer.DataFrame.mutate_with/2`
70
+ * `Explorer.DataFrame.sort_with/2`
71
+ * `Explorer.DataFrame.summarise_with/2`
72
+
73
+ - Allow accessing the dataframe inside query.
74
+
75
+ - Add "lazy read" support for Parquet and NDJSON from HTTP(s).
76
+
77
+ - Expose more options for `Explorer.Series.cut/3` and `Explorer.Series.qcut/3`.
78
+ These options were available in Polars, but not in our APIs.
79
+
80
+ ### Fixed
81
+
82
+ - Fix creation of series where a `nil` value inside a list - for a `{:list, any()}` dtype -
83
+ could result in an incompatible dtype. This fix will prevent panics for list of lists with
84
+ `nil` entries.
85
+
86
+ - Fix `Explorer.DataFrame.dump_ndjson/2` when date time is in use.
87
+
88
+ - Fix `Explorer.Series.product/1` for lazy series.
89
+
90
+ - Accept `%FSS.HTTP.Entry{}` structs in functions like `Explorer.DataFrame.from_parquet/2`.
91
+
92
+ - Fix encode of binaries to terms from series of the `{:struct, any()}` dtype.
93
+ In case the inner fields of the struct had any binary (`:binary` dtype), it was
94
+ causing a panic.
95
+
96
+ ### Changed
97
+
98
+ - Change the defaults of the functions `Explorer.Series.cut/3` and `Explorer.Series.qcut/3`
99
+ to not have "break points" column in the resultant dataframe.
100
+ So the `:include_breaks` is now `false` by default.
101
+
102
+ ## [v0.9.2] - 2024-08-27
103
+
104
+ ### Added
105
+
106
+ - Add a new `:keep` option to the `mutate_with/3` function and `mutate/3` macro.
107
+ This option allows users to control which columns are retained in the output
108
+ dataframe after a mutation operation. You can use `:all` (the default) or `:none`.
109
+
110
+ ### Fixed
111
+
112
+ - Fix handling of "LazySeries" with remote dataframes.
113
+ - Fix typespecs of `Explorer.Series.cast/2` by adding a `dtype_alias()` type.
114
+
115
+ ## [v0.9.1] - 2024-08-15
116
+
117
+ ### Added
118
+
119
+ - Add support for saving to the cloud using streaming and the IPC format.
120
+ This will enable saving a lazy frame to the cloud without loading it
121
+ entirely in memory. It only supports saves to S3-compatible storage services.
122
+
123
+ ### Changed
124
+
125
+ - Force garbage collection on remote gc.
126
+
127
+ ### Fixed
128
+
129
+ - Re-enable support for saving to the cloud using streaming and the Parquet format.
130
+ It's a fix from the release of `v0.9.0` that disabled this feature.
131
+
132
+ - Fix overwrite of dtypes for `Explorer.DataFrame.load_csv/2`.
133
+ This was a regression introduced in `v0.9.0`.
134
+
135
+ ## [v0.9.0] - 2024-07-26
136
+
137
+ ### Added
138
+
139
+ - Add initial support for SQL queries.
140
+
141
+ The `Explorer.DataFrame.sql/3` is a function that accepts a dataframe and
142
+ a SQL query. The SQL is not validated by Explorer, so the queries will be
143
+ backend dependent. Right now we have only Polars as the backend.
144
+
145
+ - Add support for remote series and dataframes.
146
+
147
+ Automatically transfer data between nodes for remote series
148
+ and dataframes and perform distributed garbage collection.
149
+
150
+ The functions in `Explorer.DataFrame` and `Explorer.Series`
151
+ will automatically move operations on remote dataframes to
152
+ the nodes they belong to. The `Explorer.Remote` module provides
153
+ additional conveniences for manual placement.
154
+
155
+ - Add FLAME integration, so we automatically track remote series and
156
+ dataframes returned from `FLAME` calls when the `:track_resources`
157
+ option is enabled.
158
+ See [FLAME](https://github.com/phoenixframework/flame) for more.
159
+
160
+ - Add `Explorer.DataFrame.transform/3` that applies an Elixir function to
161
+ each row. This function is similar to `Explorer.Series.transform/2`, and
162
+ as such, it's considered an expensive operation. So it's recommended only if
163
+ there is no similar dataframe or series operation available.
164
+
165
+ - Improve performance of `Explorer.Series.from_list/2` for most of the cases
166
+ where the `:dtype` option is given. This is specially true for when the
167
+ dtype is `:binary`.
168
+
169
+ ### Changed
170
+
171
+ - Stop inference of _dtypes_ if the `:dtype` option is given by the user.
172
+ The main goal of this change is to improve performance. We are now delegating
173
+ the job of decoding the terms as the given `:dtype` to the backend.
174
+
175
+ - `Explorer.Series.pow/2` no longer casts to float when the exponent is a signed
176
+ integer. We are following the way Polars works now, which is to try to execute
177
+ the operation or raise an exception in case the exponent is negative.
178
+
179
+ - `Explorer.Series.pivot_wider/4` no longer includes the `names_from` column
180
+ name in the new columns when `values_from` is a list of columns. This is more
181
+ consistent with its behaviour when `values_from` is a single column.
182
+
183
+ - `Explorer.Series.substring/3` no longer cycles to the end of the string if the
184
+ negative offset surpasses the beginning of that string. In that case, an empty
185
+ string is returned.
186
+
187
+ - The `Explorer.Series.ewm_*` functions no longer replace `nil` values with the
188
+ value at the previous index. They now propogate `nil` values through to the
189
+ result series.
190
+
191
+ - Saving a dataframe as a Parquet file to S3 services no longer works when
192
+ streaming is enabled. This is temporary due to a bug in Polars. An exception
193
+ should be raised instead.
194
+
195
+ ## [v0.8.3] - 2024-06-10
196
+
197
+ ### Added
198
+
199
+ - Add new data type for datetimes with timezones: `{:datetime, precision, time_zone}`
200
+ The old dtype is now `{:naive_datetime, precision}`.
201
+
202
+ - Add option to rechunk the dataframes when using `Explorer.DataFrame.from_parquet/3`
203
+
204
+ ### Changed
205
+
206
+ - Change the `{:datetime, precision}` dtype to `{:naive_datetime, precision}`.
207
+ The idea is to mirror Elixir's datetime, and introduce support for time zones.
208
+ Please note: `{:datetime, precision}` will work as an alias for `{:naive_datetime, precision}` for now but will raise a warning.
209
+ The alias will be removed in a future release.
210
+
211
+ - Literal `%NaiveDateTime{}` structs used in expressions will now have `:microsecond` precision.
212
+ Previously they defaulted to `:nanosecond` precision.
213
+ This was incorrect because `%NaiveDateTime{}` structs only have `:microsecond` precision.
214
+
215
+ ### Fixed
216
+
217
+ - Fix regression in `Explorer.DataFrame.concat_rows/2`.
218
+ It's possible to concat dataframes that are not aligned again.
219
+
220
+ - Fix "is_finite" and "is_infinite" from `Series` to work in the context of a `Explorer.Query`.
221
+
222
+ ## [v0.8.2] - 2024-04-22
223
+
224
+ ### Added
225
+
226
+ - Add functions to work with strings and regexes.
227
+
228
+ Some of the functions have the prefix "re_", because they accept a string that
229
+ represents a regular expression.
230
+
231
+ There is an important detail: we do not accept Elixir regexes, because we cannot
232
+ guarantee that the backend supports it. Instead we accept a plain string that
233
+ is "escaped". This means that you can use the `~S` sigil to build that string.
234
+ Example: `~S/(a|b)/`.
235
+
236
+ The added functions are the following:
237
+
238
+ - `Explorer.Series.split_into/3` - split a string series into a struct
239
+ of string fields. This function accepts a string as a separator.
240
+
241
+ - `Explorer.Series.re_contains/2` - check is the string series matches the regex
242
+ pattern. Like the "non regex" counterpart, it returns a boolean series.
243
+
244
+ - `Explorer.Series.re_replace/3` - replaces all occurences of a pattern with
245
+ replacement in string series. The replacement can refer to groups captures
246
+ by using the `${x}`, where `x` is the group index (starts with 1) or name.
247
+
248
+ - `Explorer.Series.count_matches/2` - count how many times a substring appears
249
+ in a string series.
250
+
251
+ - `Explorer.Series.re_count_matches/2` - count how many times a pattern matches
252
+ in a string series.
253
+
254
+ - `Explorer.Series.re_scan/2` - scan for all matches for the given regex pattern.
255
+ This is going to result in a series of lists of strings - `{:list, :string}`.
256
+
257
+ - `Explorer.Series.re_named_captures/2` - extract all capture groups as a struct
258
+ for the given regex pattern. In case the groups are not named, their positions
259
+ are used as names.
260
+
261
+ - Enable the usage of system certificates if OTP version 25 or above.
262
+
263
+ - Add support for the `:streaming` option in `Explorer.DataFrame.to_csv/3`.
264
+
265
+ - Support operations with groups in the Lazy Polars backend. This change makes
266
+ the lazy frame implementation more useful, by supporting the usage of groups in
267
+ following functions:
268
+
269
+ - `Explorer.DataFrame.slice/3`
270
+
271
+ - `Explorer.DataFrame.head/2`
272
+
273
+ - `Explorer.DataFrame.tail/2`
274
+
275
+ - `Explorer.DataFrame.filter_with/2` and the macro version of it, `filter/2`.
276
+
277
+ - `Explorer.DataFrame.sort_with/3`, although it ignores "maintain order"
278
+ and "nulls last" options when used with groups.
279
+
280
+ - `Explorer.DataFrame.mutate_with/2` and its macro version, `mutate/2`.
281
+
282
+ ### Changed
283
+
284
+ - We now avoid raising an exception if a non existent column is used in
285
+ `Explorer.DataFrame.discard/2`.
286
+
287
+ - Make the dependency of `cacerts` optional. This is because people using
288
+ Erlang/OTP 25 or above can use the certificates provided by the system.
289
+ So you may need to add the dependency of `cacerts` if your OTP version
290
+ is older than that.
291
+
292
+ - Some precision differences in float operations may appear. This is due to
293
+ an update in the Polars version to "v0.38.1". Polars is our default backend.
294
+
295
+ ### Fixed
296
+
297
+ - Fix `Explorer.Series.split/2` inside the context of `Explorer.Query`.
298
+
299
+ - Add optional `X-Amz-Security-Token` header to S3 request. This is needed
300
+ in case the user is passing down a `token` for authentication.
301
+
302
+ - Fix `Explorer.DataFrame.sort_by/3` with groups to respect `:nils` option.
303
+ This is considering only the eager implementation.
304
+
305
+ - Fix inspection of lazy frames in remote nodes.
306
+
307
+ ## [v0.8.1] - 2024-02-24
308
+
309
+ ### Added
310
+
311
+ - Add `Explorer.Series.field/2` to extract a field from a struct series.
312
+ It returns a new series with the field's dtype.
313
+
314
+ - Add `Explorer.Series.json_decode/2` that can decode a string series containing
315
+ valid JSON objects according to `dtype`.
316
+
317
+ - Add eager `count/1` and lazy `size/1` to `Explorer.Series`.
318
+
319
+ - Add support for maps as expressions inside `Explorer.Query`. They are "converted"
320
+ to structs.
321
+
322
+ - Add `json_path_match/2` to extract a string series from a string containing valid
323
+ JSON objects. See the article [JSONPath - XPath for JSON](https://goessner.net/articles/JsonPath/)
324
+ for details about JSON paths.
325
+
326
+ - Add `Explorer.Series.row_index/1` to retrieve the index of rows starting from 0.
327
+
328
+ - Add support for passing the `:on` column directly (instead of inside a list)
329
+ in `Explorer.DataFrame.join/3`.
330
+
331
+ ### Changed
332
+
333
+ - Remove some deprecated functions from documentation.
334
+
335
+ - Change internal representation of the `:struct` dtype to use list of tuples instead of a map
336
+ to represent the dtypes of each field. This shouldn't break because we normalise maps to lists
337
+ when a struct dtype is passed in `from_list/2` or `cast/2`.
338
+
339
+ - Update Rustler minimum version to `~> 0.31`. Since Rustler is optional, this shouldn't affect
340
+ most of the users.
341
+
342
+ ### Fixed
343
+
344
+ - Fix float overflow error to avoid crashing the VM, and instead it returns an argument error.
345
+
346
+ - Fix `Explorer.DataFrame.print/2` for when the DF contains structs.
347
+
348
+ ## [v0.8.0] - 2024-01-20
349
+
350
+ ### Added
351
+
352
+ - Add `explode/2` to `Explorer.DataFrame`. This function is useful to expand
353
+ the contents of a `{:list, inner_dtype}` series into a "`inner_dtype`" series.
354
+
355
+ - Add the new series functions `all?/1` and `any?/1`, to work with boolean series.
356
+
357
+ - Add support for the "struct" dtype. This new dtype represents the struct
358
+ dtype from Polars/Arrow.
359
+
360
+ - Add `map/2` and `map_with/2` to the `Explorer.Series` module.
361
+ This change enables the usage of the `Explore.Query` features in a series.
362
+
363
+ - Add `sort_by/2` and `sort_with/2` to the `Explorer.Series` module.
364
+ This change enables the usage of the lazy computations and the `Explorer.Query`
365
+ module.
366
+
367
+ - Add `unnest/2` to `Explorer.DataFrame`. It works by taking the fields of a "struct" -
368
+ the new dtype - and transform them into columns.
369
+
370
+ - Add pairwise correlation - `Explorer.DataFrame.correlation/2` - to calculate the
371
+ correlation between numeric columns inside a data frame.
372
+
373
+ - Add pairwise covariance - `Explorer.DataFrame.covariance/2` - to calculate the
374
+ covariance between numeric columns inside a data frame.
375
+
376
+ - Add support for more integer dtypes. This change introduces new signed and
377
+ unsigned integer dtypes:
378
+ - `{:s, 8}`, `{:s, 16}`, `{:s, 32}`
379
+ - `{:u, 8}`, `{:u, 16}`, `{:u, 32}`, `{:u, 64}`.
380
+
381
+ The existing `:integer` dtype is now represented as `{:s, 64}`, and it's still
382
+ the default dtype for integers. But series and data frames can now work with the
383
+ new dtypes. Short names for these new dtypes can be used in functions like
384
+ `Explorer.Series.from_list/2`. For example, `{:u, 32}` can be represented with
385
+ the atom `:u32`.
386
+
387
+ This may bring more interoperability with Nx, and with Arrow related things, like
388
+ ADBC and Parquet.
389
+
390
+ - Add `ewm_standard_deviation/2` and `ewm_variance/2` to `Explorer.Series`.
391
+ They calculate the "exponentially weighted moving" variance and standard deviation.
392
+
393
+ - Add support for `:skip_rows_after_header` option for the CSV reader functions.
394
+
395
+ - Support `{:list, numeric_dtype}` for `Explorer.Series.frequencies/1`.
396
+
397
+ - Support pins in `cond`, inside the context of `Explorer.Query`.
398
+
399
+ - Introduce the `:null` dtype. This is a special dtype from Polars and Apache Arrow
400
+ to represent "all null" series.
401
+
402
+ - Add `Explorer.DataFrame.transpose/2` to transpose a data frame.
403
+
404
+ ### Changed
405
+
406
+ - Rename the functions related to sorting/arranging of the `Explorer.DataFrame`.
407
+ Now `arrange_with` is named `sort_with`, and `arrange` is `sort_by`.
408
+
409
+ The `sort_by/3` is a macro and it is going to work using the `Explorer.Query`
410
+ module. On the other side, the `sort_with/2` uses a callback function.
411
+
412
+ - Remove unnecessary casts to `{:s, 64}` now that we support more integer dtypes.
413
+ It affects some functions, like the following in the `Explorer.Series` module:
414
+
415
+ - `argsort`
416
+ - `count`
417
+ - `rank`
418
+ - `day_of_week`, `day_of_year`, `week_of_year`, `month`, `year`, `hour`, `minute`, `second`
419
+ - `abs`
420
+ - `clip`
421
+ - `lengths`
422
+ - `slice`
423
+ - `n_distinct`
424
+ - `frequencies`
425
+
426
+ And also some functions from the `Explorer.DataFrame` module:
427
+
428
+ - `mutate` - mostly because of series changes
429
+ - `summarise` - mostly because of series changes
430
+ - `slice`
431
+
432
+ ### Fixed
433
+
434
+ - Fix inspection of series and data frames between nodes.
435
+
436
+ - Fix cast of `:string` series to `{:datetime, any()}`
437
+
438
+ - Fix mismatched types in `Explorer.Series.pow/2`, making it more consistent.
439
+
440
+ - Normalize sorting options.
441
+
442
+ - Fix functions with dtype mismatching the result from Polars.
443
+ This fix is affecting the following functions:
444
+
445
+ - `quantile/2` in the context of a lazy series
446
+ - `mode/1` inside a summarisation
447
+ - `strftime/2` in the context of a lazy series
448
+ - `mutate_with/2` when creating a column from a `NaiveDateTime` or `Explorer.Duration`.
449
+
450
+ ## [v0.7.2] - 2023-11-30
451
+
452
+ ### Added
453
+
454
+ - Add the functions `day_of_year/1` and `week_of_year/1` to `Explorer.Series`.
455
+
456
+ - Add `filter/2` - a macro -, and `filter_with/2` to `Explorer.Series`.
457
+
458
+ This change enables the usage of queries - using `Explorer.Query` - when
459
+ filtering a series. The main difference is that series does not have a
460
+ name when used outside a dataframe. So to refer to itself inside the
461
+ query, we can use the special `_` variable.
462
+
463
+ iex> s = Explorer.Series.from_list([1, 2, 3])
464
+ iex> Explorer.Series.filter(s, _ > 2)
465
+ #Explorer.Series<
466
+ Polars[1]
467
+ integer [3]
468
+ >
469
+
470
+ - Add support for the `{:list, any()}` dtype, where `any()` can be any other
471
+ valid dtype. This is a recursive dtype, that can represent nested lists.
472
+ It's useful to group data together in the same series.
473
+
474
+ - Add `Explorer.Series.mode/2` to get the most common value(s) of the series.
475
+
476
+ - Add `split/2` and `join/2` to the `Explorer.Series` module.
477
+ These functions are useful to split string series into `{:list, :string}`,
478
+ or to join parts of a `{:list, :string}` and return a `:string` series.
479
+
480
+ - Expose `ddof` option for variance, covariance and standard deviation.
481
+
482
+ - Add a new `{:f, 32}` dtype to represent 32 bits float series.
483
+ It's also possible to use the atom `:f32` to create this type of series.
484
+ The atom `:f64` can be used as an alias for `{:f, 64}`, just like the
485
+ `:float` atom.
486
+
487
+ - Add `lengths/1` and `member?/2` to `Explorer.Series`.
488
+ These functions work with `{:list, any()}`, where `any()` is any valid dtype.
489
+ The idea is to count the members of a "list" series, and check if a given
490
+ value is member of a list series, respectively.
491
+
492
+ - Add support for streaming parquet files from a lazy dataframe to AWS S3
493
+ compatible services.
494
+
495
+ ### Changed
496
+
497
+ - Remove restriction on `pivot_wider` dtypes.
498
+ In the early days, Polars only supported numeric dtypes for the "first"
499
+ aggregation. This is not true anymore, and we can lift this restriction.
500
+
501
+ - Change `:float` dtype to be represented as `{:f, 64}`. It's still possible
502
+ to use the atom `:float` to create float series, but now `Explorer.Series.dtype/1`
503
+ returns `{:f, 64}` for float 64 bits series.
504
+
505
+ ### Fixed
506
+
507
+ - Add missing implementation of `Explorer.Series.replace/3` for lazy series.
508
+
509
+ - Fix inspection of DFs and series when `limit: :infinity` is used.
510
+
511
+ ### Removed
512
+
513
+ - Drop support for the `riscv64gc-unknown-linux-gnu` target.
514
+
515
+ We decided to stop precompiling to this target because it's been hard to maintain it.
516
+ Ideally we should support it again in the future.
517
+
518
+ ## [v0.7.1] - 2023-09-25
519
+
520
+ ### Added
521
+
522
+ - Add more temporal arithmetic operations. This change makes possible
523
+ to mix some datatypes, like `date`, `duration` and scalar types like
524
+ `integers` and `floats`.
525
+
526
+ The following operations are possible now:
527
+
528
+ * `date - date`
529
+ * `date + duration`
530
+ * `date - duration`
531
+ * `duration + date`
532
+ * `duration * integer`
533
+ * `duration * float`
534
+ * `duration / integer`
535
+ * `duration / float`
536
+ * `integer * duration`
537
+ * `float * duration`
538
+
539
+ - Support lazy dataframes on `Explorer.DataFrame.print/2`.
540
+
541
+ - Add support for strings as the "indexes" of `Explorer.Series.categorise/2`.
542
+ This makes possible to categorise a string series with a categories series.
543
+
544
+ - Introduce `cond/1` support in queries, which enables multi-clause conditions.
545
+ Example of usage:
546
+
547
+ iex> df = DF.new(a: [10, 4, 6])
548
+ iex> DF.mutate(df,
549
+ ...> b:
550
+ ...> cond do
551
+ ...> a > 9 -> "Exceptional"
552
+ ...> a > 5 -> "Passed"
553
+ ...> true -> "Failed"
554
+ ...> end
555
+ ...> )
556
+ #Explorer.DataFrame<
557
+ Polars[3 x 2]
558
+ a integer [10, 4, 6]
559
+ b string ["Exceptional", "Failed", "Passed"]
560
+ >
561
+
562
+ - Similar to `cond/1`, this version also introduces support for the `if/2`
563
+ and `unless/2` macros inside queries.
564
+
565
+ - Allow the usage of scalar booleans inside queries.
566
+
567
+ - Add `Explorer.Series.replace/3` for string series.
568
+ This enables the replacement of patterns inside string series.
569
+
570
+ ### Deprecated
571
+
572
+ - Deprecate `Explorer.DataFrame.to_lazy/1` in favor of just `lazy/1`.
573
+
574
+ ### Fixed
575
+
576
+ - Fix the `Explorer.Series.in/2` function to work with series of the
577
+ `:category` dtype.
578
+
579
+ Now, if both series shares the same categories, we can compare them.
580
+ To make sure that a categorical series shares the same categories from
581
+ another series, you must create that series using the
582
+ `Explorer.Series.categorise/2` function.
583
+
584
+ - Display the dtype of duration series correctly in `Explorer.DataFrame.print/2`.
585
+
586
+ ## [v0.7.0] - 2023-08-28
587
+
588
+ ### Added
589
+
590
+ - Enable reads and writes of dataframes from/to external file systems.
591
+
592
+ It supports HTTP(s) URLs or AWS S3 locations.
593
+
594
+ This feature introduces the [FSS](https://github.com/elixir-explorer/fss) abstraction,
595
+ which is also going to be present in newer versions of Kino. This is going to make the integration
596
+ of Livebook files with Explorer much easier.
597
+
598
+ The implementation is done differently, depending on which file format is used, and if
599
+ it's a read or write. All the writes to AWS S3 are done in the Rust side - using an abstraction
600
+ called `CloudWriter` -, and most of the readers are implemented in Elixir, by doing a download
601
+ of the files, and then loading the dataframe from it. The only exception is the reads of
602
+ parquet files, which are done in Rust, using Polars' `scan_parquet` with streaming.
603
+
604
+ We want to give a special thanks to [Qqwy / Marten](https://github.com/Qqwy) for the
605
+ `CloudWriter` implementation!
606
+
607
+ - Add ADBC: Arrow Database Connectivity.
608
+
609
+ Continuing with improvements in the IO area, we added support for reading dataframes from
610
+ databases using ADBC, which is similar in idea to ODBC, but integrates much better with
611
+ Apache Arrow, that is the backbone of Polars - our backend today.
612
+
613
+ The function `Explorer.DataFrame.from_query/1` is the entrypoint for this feature, and it
614
+ allows quering databases like PostgreSQL, SQLite and Snowflake.
615
+
616
+ Check the [Elixir ADBC bindings docs](https://hexdocs.pm/adbc) for more information.
617
+
618
+ For the this feature, we had a fundamental contribution from [Cocoa](https://github.com/cocoa-xu)
619
+ in the ADBC bindings, so we want to say a special thanks to her!
620
+
621
+ We want to thank the people that joined José in [his live streamings on Twitch](https://www.twitch.tv/josevalim),
622
+ and helped to build this feature!
623
+
624
+ - Add the following functions to `Explorer.Series`:
625
+ - [`window_median/3`](https://hexdocs.pm/explorer/Explorer.Series.html#window_median/3)
626
+ - [`substring/3`](https://hexdocs.pm/explorer/Explorer.Series.html#substring/3)
627
+
628
+ - Add duration dtypes. This is adds the following dtypes:
629
+ - `{:duration, :nanosecond}`
630
+ - `{:duration, :microsecond}`
631
+ - `{:duration, :millisecond}`
632
+
633
+ This feature was a great contribution from [Billy Lanchantin](https://github.com/billylanchantin),
634
+ and we want to thank him for this!
635
+
636
+ ### Changed
637
+
638
+ - Return exception structs instead of strings for all IO operation errors, and for anything
639
+ that returns an error from the NIF integration.
640
+
641
+ This change makes easier to define which type of error we want to raise.
642
+
643
+ - Update Polars to v0.32.
644
+
645
+ With that we made some minor API changes, like changing some options for `cut/qcut` operations
646
+ in the `Explorer.Series` module.
647
+
648
+ - Use `nil_values` instead of `null_character` for IO operations.
649
+
650
+ - Never expect `nil` for CSV IO dtypes.
651
+
652
+ - Rename `Explorer.DataFrame.table/2` to `Explorer.DataFrame.print/2`.
653
+
654
+ - Change `:datetime` dtype to be `{:datetime, time_unit}`, where time unit can be
655
+ the following:
656
+ - `:millisecond`
657
+ - `:microsecond`
658
+ - `:nanosecond`
659
+
660
+ - Rename the following `Series` functions:
661
+ - `trim/1` to `strip/2`
662
+ - `trim_leading/1` to `lstrip/2`
663
+ - `trim_trailing/1` to `rstrip/2`
664
+
665
+ These functions now support a string argument.
666
+
667
+ ### Fixed
668
+
669
+ - Fix warnings for the upcoming Elixir v1.16.
670
+
671
+ - Fix `Explorer.Series.abs/1` type specs.
672
+
673
+ - Allow comparison of strings with categories.
674
+
675
+ - Fix `Explorer.Series.is_nan/1` inside the context of `Explorer.Query`.
676
+ The NIF function was not being exported.
677
+
678
+ ## [v0.6.1] - 2023-07-06
679
+
680
+ ### Fixed
681
+
682
+ - Fix summarise without groups for lazy frames.
683
+
684
+ ## [v0.6.0] - 2023-07-05
685
+
686
+ ### Added
687
+
688
+ - Add support for OTP 26 and Elixir 1.15.
689
+
690
+ - Allow `Explorer.DataFrame.summarise/2` to work without groups.
691
+ The aggregations can work considering the entire dataframe.
692
+
693
+ - Add the following series functions: `product/1`, `cummulative_product/1`, `abs/1`,
694
+ `skew/2`, `window_standard_deviation/3`, `rank/2`, `year/1`, `mounth/1`, `day/1`,
695
+ `hour/1`, `minute/1`, `second/1`, `strptime/2`, `strftime/2`, `argmin/1`, `argmax/1`,
696
+ `cut/3`, `qcut/3`, `correlation/3`, `covariance/2` and `clip/3`.
697
+
698
+ They cover a lot in terms of functionality, so please check the `Explorer.Series`
699
+ docs for further details.
700
+
701
+ - Add `Explorer.DataFrame.nil_count/1` that counts the number of nil elements in each
702
+ column.
703
+
704
+ - Add `Explorer.DataFrame.frequencies/2` that creates a new dataframe with unique rows
705
+ and the frequencies of each.
706
+
707
+ - Add `Explorer.DataFrame.relocate/3` that enables changing order of columns from a df.
708
+
709
+ - Add precompiled NIFs for FreeBSD.
710
+
711
+ - Support scalar values in the `on_true` and `on_false` arguments of `Explore.Series.select/3`.
712
+
713
+ ### Fixed
714
+
715
+ - Fix `Series.day_of_week/1` and `Series.round/2` for operations using a lazy frame.
716
+
717
+ - Fix upcasted date to datetime for literal expressions. It allows to use scalar dates
718
+ in expressions like this: `DF.mutate(a: ~D[2023-01-01])`. This also fixes the support
719
+ for naive datetimes.
720
+
721
+ - Improve error messages returned from the NIF to be always strings. Now we add more
722
+ context to the string returned, instead of having `{:context, error_message}`.
723
+
724
+ - Fix the `:infer_schema_length` option of `Explorer.DataFrame.from_csv/2` when passing `nil`.
725
+ Now it's possible to take into account the entire file to infer the schema.
726
+
727
+
728
+ ### Deprecated
729
+
730
+ - Deprecate `Explorer.Series.to_date/1` and `Explorer.Series.to_time/1` in favor of
731
+ using `Explorer.Series.cast(s, :date)` and `Explorer.Series.cast(s, :time)` respectively.
732
+
733
+ ## [v0.5.7] - 2023-05-10
734
+
735
+ ### Added
736
+
737
+ - Allow `Explorer.Series.select/3` to receive series of size 1 in both sides.
738
+
739
+ - Add trigonometric functions `sin/1`, `cos/1`, `tan/1`, `asin/1`, `acos/1` and
740
+ `atan/1` to `Explorer.Series`.
741
+
742
+ - Add `Explorer.DataFrame.to_rows_stream/2` function. This is useful to traverse
743
+ dataframes with large series, but is not recommended since it can be an expensive
744
+ operation.
745
+
746
+ - Add LazyFrame version of `Explorer.DataFrame.to_ipc/3`.
747
+
748
+ - Add options to control streaming when writing lazy dataframes. Now users can
749
+ toggle streaming for the `to_ipc/3` and `to_parquet/3` functions.
750
+
751
+ - Add `Explorer.DataFrame.from_ipc_stream/2` lazy, but using the eager implementation
752
+ underneath.
753
+
754
+ - Add option to control the end of line (EOF) char when reading CSV files.
755
+ We call this new option `:eol_delimiter`, and it's available for the `from_csv/2`
756
+ and `load_csv/2` functions in the `Explorer.DataFrame` module.
757
+
758
+ - Allow `Explorer.DataFrame.pivot_wider/4` to use category fields.
759
+
760
+ ### Fixed
761
+
762
+ - Fix `nif_not_loaded` error when `Explorer.Series.ewm_mean/2` is called from query.
763
+
764
+ - Type check arguments for boolean series operations, only allowing series of
765
+ the `boolean` dtype.
766
+
767
+ - Do not use `../0` in order to keep compatible with Elixir 1.13
768
+
769
+ ### Removed
770
+
771
+ - Temporarely remove support for ARM 32 bits computers in the precompilation
772
+ workflow.
773
+
774
+ ## [v0.5.6] - 2023-03-24
775
+
776
+ ### Added
777
+
778
+ - Add the following functions to the `Explorer.Series` module: `log/1`, `log/2`
779
+ and `exp/1`. They compute the logarithm and exponential of a series.
780
+
781
+ ### Fixed
782
+
783
+ - Allow `Explorer.Series.select/3` to receive series of size 1 for both the
784
+ `on_true` and `on_false` arguments.
785
+
786
+ - Fix the encoding of special float values that may return from some series
787
+ functions. This is going to encode the atoms for NaN and infinity values.
788
+
789
+ ## [v0.5.5] - 2023-03-13
790
+
791
+ ### Added
792
+
793
+ - Add support for multiple value columns in pivot wider.
794
+ The resultant dataframe that is created from this type of pivoting is going
795
+ to have columns with the names prefixed by the original value column, followed
796
+ by an underscore and the name of the variable.
797
+
798
+ - Add `Explorer.Series.ewm_mean/2` for calculating exponentially weighted moving
799
+ average.
800
+
801
+ ### Changed
802
+
803
+ - Change the `Explorer.Backend.DataFrame`'s `pivot_wider` callback to work with
804
+ multiple columns instead of only one.
805
+
806
+ - Change the `Explorer.Backend.DataFrame`'s `window_*` callbacks to work with
807
+ variables instead of keyword args. This is needed to make explicit when a backend
808
+ is not implementing an option.
809
+
810
+ - Change the `Explorer.Backend.DataFrame`'s `describe` callback and remove the
811
+ need for an "out df", since we won't have a lazy version of that funcion.
812
+
813
+ - This shouldn't affect the API, but we had an update in Polars.
814
+ It is now using `v0.27.2`. For further details, see:
815
+ [Rust Polars 0.27.0](https://github.com/pola-rs/polars/releases/tag/rs-0.27.0).
816
+
817
+ ### Fixed
818
+
819
+ - Provide hints when converting string/binary series to tensors.
820
+
821
+ - Add libatomic as a link to the generated NIF. This is needed to fix the load
822
+ of the Explorer NIF when running on ARM 32 bits machines like the Pi 3.
823
+ See the [original issue](https://github.com/philss/rustler_precompiled/issues/53)
824
+
825
+ ## [v0.5.4] - 2023-03-09
826
+
827
+ ### Fixed
828
+
829
+ - Fix missing "README.md" file in the list of package files.
830
+ Our readme is now required in compilation, because it contains the moduledoc for
831
+ the main `Explorer` module.
832
+
833
+ ## [v0.5.3] - 2023-03-08
834
+
835
+ ### Added
836
+
837
+ - Add the `Explorer.Series.format/1` function that concatenates multiple series together,
838
+ always returning a string series.
839
+
840
+ - With the addition of `format/1`, we also have a new operator for string concatenation
841
+ inside `Explorer.Query`. It is the `<>` operator, that is similar to what the `Kernel.<>/2`
842
+ operator does, but instead of concatenating strings, it concatenates two series, returning
843
+ a string series - it is using `format/1` underneath.
844
+
845
+ - Add support for slicing by series in dataframes and other series.
846
+
847
+ - Add support for 2D tensors in `Explorer.DataFrame.new/2`.
848
+
849
+ ### Fixed
850
+
851
+ - Fix `Explorer.DataFrame.new/2` to respect the selected dtype when an entire series is nil.
852
+
853
+ - Improve error message for mismatched dtypes in series operations.
854
+
855
+ - Fix lazy series operations of binary series and binary values. This is going to wrap binary
856
+ values in the correct dtype, in order to pass down to Polars.
857
+
858
+ - Fix two bugs in `Explorer.DataFrame.pivot_wider/3`: `nil` values in the series that is
859
+ used for new column names is now correctly creating a `nil` column. We also fixed the problem
860
+ of a duplicated column created after pivoting, and possibly conflicting with an existing
861
+ ID column. We add a suffix for these columns.
862
+
863
+ ## [v0.5.2] - 2023-02-28
864
+
865
+ ### Added
866
+
867
+ - Add `across` and comprehensions to `Explorer.Query`. These features allow a
868
+ more flexible and elegant way to work with multiple columns at once. Example:
869
+
870
+ ```elixir
871
+ iris = Explorer.Datasets.iris()
872
+ Explorer.DataFrame.mutate(iris,
873
+ for col <- across(["sepal_width", "sepal_length", "petal_length", "petal_width"]) do
874
+ {col.name, (col - mean(col)) / variance(col)}
875
+ end
876
+ )
877
+ ```
878
+
879
+ See the `Explorer.Query` documentation for further details.
880
+
881
+ - Add support for regexes to select columns of a dataframe. Example:
882
+
883
+ ```elixir
884
+ df = Explorer.Datasets.wine()
885
+ df[~r/(class|hue)/]
886
+ ```
887
+
888
+ - Add the `:max_rows` and `:columns` options to `Explorer.DataFrame.from_parquet/2`. This mirrors
889
+ the `from_csv/2` function.
890
+
891
+ - Allow `Explorer.Series` functions that accept floats to work with `:nan`, `:infinity`
892
+ and `:neg_infinity` values.
893
+
894
+ - Add `Explorer.DataFrame.shuffle/2` and `Explorer.Series.shuffle/2`.
895
+
896
+ - Add support for a list of filters in `Explorer.DataFrame.filter/2`. These filters are
897
+ joined as `and` expressions.
898
+
899
+ ### Fixed
900
+
901
+ - Add `is_integer/1` guard to `Explorer.Series.shift/2`.
902
+ - Raise if series sizes do not match for binary operations.
903
+
904
+ ### Changed
905
+
906
+ - Rename the option `:replacement` to `:replace` for `Explorer.DataFrame.sample/3` and
907
+ `Explorer.Series.sample/3`.
908
+
909
+ - Change the default behaviour of sampling to not shuffle by default. A new option
910
+ named `:shuffle` was added to control that.
911
+
912
+ ## [v0.5.1] - 2023-02-17
913
+
914
+ ### Added
915
+
916
+ - Add boolean dtype to `Series.in/2`.
917
+ - Add binary dtype to `Series.in/2`.
918
+ - Add `Series.day_of_week/1`.
919
+
920
+ - Allow `Series.fill_missing/2` to:
921
+ - receive `:infinity` and `:neg_infinity` values.
922
+ - receive date and datetime values.
923
+ - receive binary values.
924
+
925
+ - Add support for `time` dtype.
926
+ - Add version of `Series.pow/2` that accepts series on both sides.
927
+ - Allow `Series.from_list/2` to receive `:nan`, `:infinity` and `:neg_infinity` atoms.
928
+ - Add `Series.to_date/1` and `Series.to_time/1` for datetime series.
929
+ - Allow casting of string series to category.
930
+ - Accept tensors when creating a new dataframe.
931
+ - Add compatibility with Nx v0.5.
932
+ - Add support for Nx's serialize and deserialize.
933
+
934
+ - Add the following function implementations for the Polars' Lazy dataframe backend:
935
+ - `arrange_with`
936
+ - `concat_columns`
937
+ - `concat_rows`
938
+ - `distinct`
939
+ - `drop_nil`
940
+ - `filter_with`
941
+ - `join`
942
+ - `mutate_with`
943
+ - `pivot_longer`
944
+ - `rename`
945
+ - `summarise_with`
946
+ - `to_parquet`
947
+
948
+ Only `summarise_with` supports groups for this version.
949
+
950
+ ### Changed
951
+
952
+ - Require version of Rustler to be `~> 0.27.0`, which mirrors the NIF requirement.
953
+
954
+ ### Fixed
955
+
956
+ - Casting to an unknown dtype returns a better error message.
957
+
958
+ ## [v0.5.0] - 2023-01-12
959
+
960
+ ### Added
961
+
962
+ - Add `DataFrame.describe/2` to gather some statistics from a dataframe.
963
+ - Add `Series.nil_count/1` to count nil values.
964
+ - Add `Series.in/2` to check if a given value is inside a series.
965
+ - Add `Series` float predicates: `is_finite/1`, `is_infinite/1` and `is_nan/1`.
966
+ - Add `Series` string functions: `contains/2`, `trim/1`, `trim_leading/1`, `trim_trailing/1`,
967
+ `upcase/1` and `downcase/1`.
968
+
969
+ - Enable slicing of lazy frames (`LazyFrame`).
970
+ - Add IO operations "from/load" to the lazy frame implementation.
971
+ - Add support for the `:lazy` option in the `DataFrame.new/2` function.
972
+ - Add `Series` float rounding methods: `round/2`, `floor/1` and `ceil/1`.
973
+ - Add support for precompiling to Linux running on RISCV CPUs.
974
+ - Add support for precompiling to Linux - with musl - running on AARCH64 computers.
975
+ - Allow `DataFrame.new/1` to receive the `:dtypes` option.
976
+ - Accept `:nan` as an option for `Series.fill_missing/2` with float series.
977
+ - Add basic support for the categorical dtype - the `:category` dtype.
978
+ - Add `Series.categories/1` to return categories from a categorical series.
979
+ - Add `Series.categorise/2` to categorise a series of integers using predefined categories.
980
+ - Add `Series.replace/2` to replace the contents of a series.
981
+ - Support selecting columns with unusual names (like with spaces) inside `Explorer.Query`
982
+ with `col/1`.
983
+
984
+ The usage is like this:
985
+
986
+ ```elixir
987
+ Explorer.DataFrame.filter(df, col("my col") > 42)
988
+ ```
989
+
990
+ ### Fixed
991
+
992
+ - Fix `DataFrame.mutate/2` using a boolean scalar value.
993
+ - Stop leaking `UInt32` series to Elixir.
994
+ - Cast numeric columns to our supported dtypes after IO read.
995
+ This fix is only applied for the eager implementation for now.
996
+
997
+ ### Changed
998
+
999
+ - Rename `Series.bintype/1` to `Series.iotype/1`.
1000
+
1001
+ ## [v0.4.0] - 2022-11-29
1002
+
1003
+ ### Added
1004
+
1005
+ - Add `Series.quotient/2` and `Series.remainder/2` to work with integer division.
1006
+ - Add `Series.iotype/1` to return the underlying representation type.
1007
+ - Allow series on both sides of binary operations, like: `add(series, 1)`
1008
+ and `add(1, series)`.
1009
+
1010
+ - Allow comparison, concat and coalesce operations on "(series, lazy series)".
1011
+ - Add lazy version of `Series.sample/3` and `Series.size/1`.
1012
+ - Add support for Arrow IPC Stream files.
1013
+ - Add `Explorer.Query` and the macros that allow a simplified query API.
1014
+ This is a huge improvement to some of the main functions, and allow refering to
1015
+ columns as they were variables.
1016
+
1017
+ Before this change we would need to write a filter like this:
1018
+
1019
+ ```elixir
1020
+ Explorer.DataFrame.filter_with(df, &Explorer.Series.greater(&1["col1"], 42))
1021
+ ```
1022
+
1023
+ But now it's also possible to write this operation like this:
1024
+
1025
+ ```elixir
1026
+ Explorer.DataFrame.filter(df, col1 > 42)
1027
+ ```
1028
+
1029
+ This operation is going to use `filter_with/2` underneath, which means that
1030
+ is going to use lazy series and compute the results at once.
1031
+ Notice that is mandatory to "require" the DataFrame module, since these operations
1032
+ are implemented as macros.
1033
+
1034
+ The following new macros were added:
1035
+ - `filter/2`
1036
+ - `mutate/2`
1037
+ - `summarise/2`
1038
+ - `arrange/2`
1039
+
1040
+ They substitute older versions that did not accept the new query syntax.
1041
+
1042
+ - Add `DataFrame.put/3` to enable adding or replacing columns in a eager manner.
1043
+ This works similar to the previous version of `mutate/2`.
1044
+
1045
+ - Add `Series.select/3` operation that enables selecting a value
1046
+ from two series based on a predicate.
1047
+
1048
+ - Add "dump" and "load" functions to IO operations. They are useful to load
1049
+ or dump dataframes from/to memory.
1050
+
1051
+ - Add `Series.to_iovec/2` and `Series.to_binary/1`. They return the underlying
1052
+ representation of series as binary. The first one returns a list of binaries,
1053
+ possibly with one element if the series is contiguous in memory. The second one
1054
+ returns a single binary representing the series.
1055
+
1056
+ - Add `Series.shift/2` that shifts the series by an offset with nil values.
1057
+ - Rename `Series.fetch!/2` and `Series.take_every/2` to `Series.at/2`
1058
+ and `Series.at_every/2`.
1059
+
1060
+ - Add `DataFrame.discard/2` to drop columns. This is the opposite of `select/2`.
1061
+
1062
+ - Implement `Nx.LazyContainer` for `Explorer.DataFrame` and `Explorer.Series`
1063
+ so data can be passed into Nx.
1064
+
1065
+ - Add `Series.not/1` that negates values in a boolean series.
1066
+ - Add the `:binary` dtype for Series. This enables the usage of arbitrary binaries.
1067
+
1068
+ ### Changed
1069
+
1070
+ - Change DataFrame's `to_*` functions to return only `:ok`.
1071
+ - Change series inspect to resamble the dataframe inspect with the backend name.
1072
+ - Rename `Series.var/1` to `Series.variance/1`
1073
+ - Rename `Series.std/1` to `Series.standard_deviation/1`
1074
+ - Rename `Series.count/2` to `Series.frequencies/1` and add a new `Series.count/1`
1075
+ that returns the size of an "eager" series, or the count of members in a group
1076
+ for a lazy series.
1077
+ In case there is no groups, it calculates the size of the dataframe.
1078
+ - Change the option to control direction in `Series.sort/2` and `Series.argsort/2`.
1079
+ Instead of a boolean, now we have a new option called `:direction` that accepts
1080
+ `:asc` or `:desc`.
1081
+
1082
+ ### Fixed
1083
+
1084
+ - Fix the following DataFrame functions to work with groups:
1085
+ - `filter_with/2`
1086
+ - `head/2`
1087
+ - `tail/2`
1088
+ - `slice/2`
1089
+ - `slice/3`
1090
+ - `pivot_longer/3`
1091
+ - `pivot_wider/4`
1092
+ - `concat_rows/1`
1093
+ - `concat_columns/1`
1094
+ - Improve the documentation of functions that behave differently with groups.
1095
+ - Fix `arrange_with/2` to use "group by" stable, making results more predictable.
1096
+ - Add `nil` as a possible return value of aggregations.
1097
+ - Fix the behaviour of `Series.sort/2` and `Series.argsort/2` to add nils at the
1098
+ front when direction is descending, or at the back when the direction is ascending.
1099
+ This also adds an option to control this behaviour.
1100
+
1101
+ ### Removed
1102
+
1103
+ - Remove support for `NDJSON` read and write for ARM 32 bits targets.
1104
+ This is due to a limitation of a dependency of Polars.
1105
+
1106
+ ## [v0.3.1] - 2022-09-09
1107
+
1108
+ ### Fixed
1109
+
1110
+ - Define `multiply` inside `*_with` operations.
1111
+ - Fix column types in several operations, such as `n_distinct`.
1112
+
1113
+ ## [v0.3.0] - 2022-09-01
1114
+
1115
+ ### Added
1116
+
1117
+ - Add `DataFrame.concat_columns/1` and `DataFrame.concat_columns/2` for horizontally stacking
1118
+ dataframes.
1119
+ - Add compression as an option to write parquet files.
1120
+ - Add count metadata to `DataFrame` table reader.
1121
+ - Add `DataFrame.filter_with/2`, `DataFrame.summarise_with/2`, `DataFrame.mutate_with/2` and
1122
+ `DataFrame.arrange_with/2`. They all accept a `DataFrame` and a function, and they all work with
1123
+ a new concept called "lazy series".
1124
+
1125
+ Lazy Series is an opaque representation of a series that can be
1126
+ used to perform complex operations without pulling data from the series. This is faster than
1127
+ using masks. There is no big difference from the API perspective compared to the functions that were
1128
+ accepting callbacks before (eg. `filter/2` and the new `filter_with/2`), with the exception being
1129
+ `DataFrame.summarise_with/2` that now accepts a lot more operations.
1130
+
1131
+ ### Changed
1132
+
1133
+ - Bump version requirement of the `table` dependency to `~> 0.1.2`, and raise for non-tabular values.
1134
+ - Normalize how columns are handled. This changes some functions to accept one column or
1135
+ a list of columns, ranges, indexes and callbacks selecting columns.
1136
+ - Rename `DataFrame.filter/2` to `DataFrame.mask/2`.
1137
+ - Rename `Series.filter/2` to `Series.mask/2`.
1138
+ - Rename `take/2` from both `Series` and `DataFrame` to `slice/2`. `slice/2` now they accept ranges as well.
1139
+ - Raise an error if `DataFrame.pivot_wider/4` has float columns as IDs. This is because we can´t
1140
+ properly compare floats.
1141
+ - Change `DataFrame.distinct/2` to accept columns as argument instead of receiving it as option.
1142
+
1143
+ ### Fixed
1144
+
1145
+ - Ensure that we can compare boolean series in functions like `Series.equal/2`.
1146
+ - Fix rename of columns after summarise.
1147
+ - Fix inspect of float series containing `NaN` or `Infinity` values. They are represented as atoms.
1148
+
1149
+ ### Deprecated
1150
+
1151
+ - Deprecate `DataFrame.filter/2` with a callback in favor of `DataFrame.filter_with/2`.
1152
+
1153
+ ## [v0.2.0] - 2022-06-22
1154
+
1155
+ ### Added
1156
+
1157
+ - Consistently support ranges throughout the columns API
1158
+ - Support negative indexes throughout the columns API
1159
+ - Integrate with the `table` package
1160
+ - Add `Series.to_enum/1` for lazily traversing the series
1161
+ - Add `Series.coalesce/1` and `Series.coalesce/2` for finding the first non-null value in a list of series
1162
+
1163
+ ### Changed
1164
+
1165
+ - `Series.length/1` is now `Series.size/1` in keeping with Elixir idioms
1166
+ - `Nx` is now an optional dependency
1167
+ - Minimum Elixir version is now 1.13
1168
+ - `DataFrame.to_map/2` is now `DataFrame.to_columns/2` and `DataFrame.to_series/2`
1169
+ - `Rustler` is now an optional dependency
1170
+ - `read_` and `write_` IO functions are now `from_` and `to_`
1171
+ - `to_binary` is now `dump_csv`
1172
+ - Now uses `polars`'s "simd" feature
1173
+ - Now uses `polars`'s "performant" feature
1174
+ - `Explorer.default_backend/0` is now `Explorer.Backend.get/0`
1175
+ - `Explorer.default_backend/1` is now `Explorer.Backend.put/1`
1176
+ - `Series.cum_*` functions are now `Series.cumulative_*` to mirror `Nx`
1177
+ - `Series.rolling_*` functions are now `Series.window_*` to mirror `Nx`
1178
+ - `reverse?` is now an option instead of an argument in `Series.cumulative_*` functions
1179
+ - `DataFrame.from_columns/2` and `DataFrame.from_rows/2` is now `DataFrame.new/2`
1180
+ - Rename "col" to "column" throughout the API
1181
+ - Remove "with\_" prefix in options throughout the API
1182
+ - `DataFrame.table/2` accepts options with `:limit` instead of single integer
1183
+ - `rename/2` no longer accepts a function, use `rename_with/2` instead
1184
+ - `rename_with/3` now expects the function as the last argument
1185
+
1186
+ ### Fixed
1187
+
1188
+ - Explorer now works on Linux with musl
1189
+
1190
+ ## [v0.1.1] - 2022-04-27
1191
+
1192
+ ### Security
1193
+
1194
+ - 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)
1195
+
1196
+ ## [v0.1.0] - 2022-04-26
1197
+
1198
+ First release.
1199
+
1200
+ [Unreleased]: https://github.com/elixir-explorer/explorer/compare/v0.10.1...HEAD
1201
+ [v0.10.1]: https://github.com/elixir-explorer/explorer/compare/v0.10.0...v0.10.1
1202
+ [v0.10.0]: https://github.com/elixir-explorer/explorer/compare/v0.9.2...v0.10.0
1203
+ [v0.9.2]: https://github.com/elixir-explorer/explorer/compare/v0.9.1...v0.9.2
1204
+ [v0.9.1]: https://github.com/elixir-explorer/explorer/compare/v0.9.0...v0.9.1
1205
+ [v0.9.0]: https://github.com/elixir-explorer/explorer/compare/v0.8.3...v0.9.0
1206
+ [v0.8.3]: https://github.com/elixir-explorer/explorer/compare/v0.8.2...v0.8.3
1207
+ [v0.8.2]: https://github.com/elixir-explorer/explorer/compare/v0.8.1...v0.8.2
1208
+ [v0.8.1]: https://github.com/elixir-explorer/explorer/compare/v0.8.0...v0.8.1
1209
+ [v0.8.0]: https://github.com/elixir-explorer/explorer/compare/v0.7.2...v0.8.0
1210
+ [v0.7.2]: https://github.com/elixir-explorer/explorer/compare/v0.7.1...v0.7.2
1211
+ [v0.7.1]: https://github.com/elixir-explorer/explorer/compare/v0.7.0...v0.7.1
1212
+ [v0.7.0]: https://github.com/elixir-explorer/explorer/compare/v0.6.1...v0.7.0
1213
+ [v0.6.1]: https://github.com/elixir-explorer/explorer/compare/v0.6.0...v0.6.1
1214
+ [v0.6.0]: https://github.com/elixir-explorer/explorer/compare/v0.5.7...v0.6.0
1215
+ [v0.5.7]: https://github.com/elixir-explorer/explorer/compare/v0.5.6...v0.5.7
1216
+ [v0.5.6]: https://github.com/elixir-explorer/explorer/compare/v0.5.5...v0.5.6
1217
+ [v0.5.5]: https://github.com/elixir-explorer/explorer/compare/v0.5.4...v0.5.5
1218
+ [v0.5.4]: https://github.com/elixir-explorer/explorer/compare/v0.5.3...v0.5.4
1219
+ [v0.5.3]: https://github.com/elixir-explorer/explorer/compare/v0.5.2...v0.5.3
1220
+ [v0.5.2]: https://github.com/elixir-explorer/explorer/compare/v0.5.1...v0.5.2
1221
+ [v0.5.1]: https://github.com/elixir-explorer/explorer/compare/v0.5.0...v0.5.1
1222
+ [v0.5.0]: https://github.com/elixir-explorer/explorer/compare/v0.4.0...v0.5.0
1223
+ [v0.4.0]: https://github.com/elixir-explorer/explorer/compare/v0.3.1...v0.4.0
1224
+ [v0.3.1]: https://github.com/elixir-explorer/explorer/compare/v0.3.0...v0.3.1
1225
+ [v0.3.0]: https://github.com/elixir-explorer/explorer/compare/v0.2.0...v0.3.0
1226
+ [v0.2.0]: https://github.com/elixir-explorer/explorer/compare/v0.1.1...v0.2.0
1227
+ [v0.1.1]: https://github.com/elixir-explorer/explorer/compare/v0.1.0...v0.1.1
1228
+ [v0.1.0]: https://github.com/elixir-explorer/explorer/releases/tag/v0.1.0
deps/explorer/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Amplified AI, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
deps/explorer/README.md ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <h1><img src="explorer.png" alt="Explorer"></h1>
2
+
3
+ ![CI](https://github.com/elixir-nx/explorer/actions/workflows/ci.yml/badge.svg)
4
+ [![Documentation](http://img.shields.io/badge/hex.pm-docs-green.svg?style=flat)](https://hexdocs.pm/explorer)
5
+ [![Package](https://img.shields.io/hexpm/v/explorer.svg)](https://hex.pm/packages/explorer)
6
+
7
+ <!-- MDOC -->
8
+
9
+ Explorer brings series (one-dimensional) and dataframes (two-dimensional) for fast
10
+ data exploration to Elixir.
11
+
12
+ ## Features and design
13
+
14
+ Explorer high-level features are:
15
+
16
+ - Simply typed series: `:binary`, `:boolean`, `:category`, `:date`, `:datetime`,
17
+ `:duration`, floats of 32 and 64 bits (`{:f, size}`), integers of 8, 16, 32
18
+ and 64 bits (`{:s, size}`, `{:u, size}`), `:null`, `:string`, `:time`, `:list`,
19
+ and `:struct`.
20
+
21
+ - A powerful but constrained and opinionated API, so you spend less time looking
22
+ for the right function and more time doing data manipulation.
23
+
24
+ - Support for CSV, Parquet, NDJSON, and Arrow IPC formats
25
+
26
+ - Integration with external databases via [ADBC](https://github.com/elixir-explorer/adbc)
27
+ and direct connection to file storages such as S3
28
+
29
+ - Pluggable backends, providing a uniform API whether you're working in-memory
30
+ or (forthcoming) on remote databases or even Spark dataframes.
31
+
32
+ - The first (and default) backend is based on NIF bindings to the blazing-fast
33
+ [polars](https://docs.rs/polars) library.
34
+
35
+ The API is heavily influenced by [Tidy Data](https://vita.had.co.nz/papers/tidy-data.pdf)
36
+ and borrows much of its design from [dplyr](https://dplyr.tidyverse.org). The philosophy
37
+ is heavily influenced by this passage from `dplyr`'s documentation:
38
+
39
+ > - By constraining your options, it helps you think about your data manipulation
40
+ > challenges.
41
+ >
42
+ > - It provides simple “verbs”, functions that correspond to the most common data
43
+ > manipulation tasks, to help you translate your thoughts into code.
44
+ >
45
+ > - It uses efficient backends, so you spend less time waiting for the computer.
46
+
47
+ The aim here isn't to have the fastest dataframe library around (though it certainly
48
+ helps that [we're building on Polars, one of the fastest](https://h2oai.github.io/db-benchmark/)).
49
+ Instead, we're aiming to bridge the best of many worlds:
50
+
51
+ - the elegance of `dplyr`
52
+ - the speed of `polars`
53
+ - the joy of Elixir
54
+
55
+ That means you can expect the guiding principles to be 'Elixir-ish'. For example,
56
+ you won't see the underlying data mutated, even if that's the most efficient implementation.
57
+ Explorer functions will always return a new dataframe or series.
58
+
59
+ ## Getting started
60
+
61
+ Inside an Elixir script or [Livebook](https://livebook.dev):
62
+
63
+ ```elixir
64
+ Mix.install([
65
+ {:explorer, "~> 0.10.0"}
66
+ ])
67
+ ```
68
+
69
+ Or in the `mix.exs` file of your application:
70
+
71
+ ```elixir
72
+ def deps do
73
+ [
74
+ {:explorer, "~> 0.10.0"}
75
+ ]
76
+ end
77
+ ```
78
+
79
+ 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:
80
+
81
+ ```elixir
82
+ {:explorer, "~> 0.10.0", system_env: %{"EXPLORER_BUILD" => "1"}},
83
+ {:rustler, ">= 0.0.0"}
84
+ ```
85
+
86
+ If necessary, clean up before rebuilding with `mix deps.clean explorer`.
87
+
88
+ ## A glimpse of the API
89
+
90
+ We have two ways to represent data with Explorer:
91
+
92
+ - using a series, that is similar to a list, but is guaranteed to contain items
93
+ of one data type only - or one *dtype* for short. Notice that nil values are
94
+ permitted in series of any dtype.
95
+
96
+ - using a dataframe, that is just a way to represent one or more series together,
97
+ and work with them as a whole. The only restriction is that all the series share
98
+ the same size.
99
+
100
+ A series can be created from a list:
101
+
102
+ ```elixir
103
+ fruits = Explorer.Series.from_list(["apple", "mango", "banana", "orange"])
104
+ ```
105
+
106
+ Your newly created series is going to look like:
107
+
108
+ ```
109
+ #Explorer.Series<
110
+ Polars[4]
111
+ string ["apple", "mango", "banana", "orange"]
112
+ >
113
+ ```
114
+
115
+ And you can, for example, sort that series:
116
+
117
+ ```elixir
118
+ Explorer.Series.sort(fruits)
119
+ ```
120
+
121
+ Resulting in the following:
122
+
123
+ ```
124
+ #Explorer.Series<
125
+ Polars[4]
126
+ string ["apple", "banana", "mango", "orange"]
127
+ >
128
+ ```
129
+
130
+ ### Dataframes
131
+
132
+ Dataframes can be created in two ways:
133
+
134
+ - by reading from files or memory using the
135
+ [IO functions](https://hexdocs.pm/explorer/Explorer.DataFrame.html#module-io-operations).
136
+ This is by far the most common way to load dataframes in Explorer.
137
+ We accept Parquet, IPC, CSV, and NDJSON files.
138
+
139
+ - by using the `Explorer.DataFrame.new/2` function, that is neat for small experiments.
140
+ We are going to use this function here.
141
+
142
+ You can pass either series or lists to it:
143
+
144
+ ```elixir
145
+ mountains = Explorer.DataFrame.new(name: ["Everest", "K2", "Aconcagua"], elevation: [8848, 8611, 6962])
146
+ ```
147
+
148
+ Your dataframe is going to look like this:
149
+
150
+ ```
151
+ #Explorer.DataFrame<
152
+ Polars[3 x 2]
153
+ name string ["Everest", "K2", "Aconcagua"]
154
+ elevation s64 [8848, 8611, 6962]
155
+ >
156
+ ```
157
+
158
+ It's also possible to see a dataframe like a table, using the `Explorer.DataFrame.print/2`
159
+ function:
160
+
161
+ ```elixir
162
+ Explorer.DataFrame.print(mountains)
163
+ ```
164
+
165
+ Prints:
166
+
167
+ ```
168
+ +-------------------------------------------+
169
+ | Explorer DataFrame: [rows: 3, columns: 2] |
170
+ +---------------------+---------------------+
171
+ | name | elevation |
172
+ | <string> | <s64> |
173
+ +=====================+=====================+
174
+ | Everest | 8848 |
175
+ +---------------------+---------------------+
176
+ | K2 | 8611 |
177
+ +---------------------+---------------------+
178
+ | Aconcagua | 6962 |
179
+ +---------------------+---------------------+
180
+ ```
181
+
182
+ And now I want to show you how to filter our dataframe. But first, let's require
183
+ the `Explorer.DataFrame` module and give a short name to it:
184
+
185
+ ```elixir
186
+ require Explorer.DataFrame, as: DF
187
+ ```
188
+
189
+ The "require" is needed to load the macro features of that module.
190
+ We give it a shorter name to simplify our examples.
191
+
192
+ Now let's go to the filter. I want to filter the mountains that are above
193
+ the mean elevation in our dataframe:
194
+
195
+ ```elixir
196
+ DF.filter(mountains, elevation > mean(elevation))
197
+ ```
198
+
199
+ You can see that we can refer to the columns using their names, and use functions
200
+ without defining them. This is possible due to the powerful `Explorer.Query` features,
201
+ and it's the main reason we need to "require" the `Explorer.DataFrame` module.
202
+
203
+ The result is going to look like this:
204
+
205
+ ```
206
+ #Explorer.DataFrame<
207
+ Polars[2 x 2]
208
+ name string ["Everest", "K2"]
209
+ elevation s64 [8848, 8611]
210
+ >
211
+ ```
212
+
213
+ There is an extensive guide that you can play with Livebook:
214
+ [Ten Minutes to Explorer](https://hexdocs.pm/explorer/exploring_explorer.html)
215
+
216
+ You can also check the `Explorer.DataFrame` and `Explorer.Series` docs for further
217
+ details.
218
+
219
+ <!-- MDOC -->
220
+
221
+ ## Contributing
222
+
223
+ Explorer uses Rust for its default backend implementation, and while Rust is not
224
+ necessary to use Explorer as a package, you need Rust tooling installed on your
225
+ machine if you want to compile from source, which is the case when contributing
226
+ to Explorer.
227
+
228
+ We require Rust Nightly, which can be installed with [Rustup](https://rust-lang.github.io/rustup/installation/index.html).
229
+ If you already have Rustup and a recent version of Cargo installed, then the correct version of
230
+ Rust is going to be installed in the first compilation of the project. Otherwise, you can manually
231
+ install the correct version:
232
+
233
+ ```sh
234
+ rustup toolchain install nightly-2024-07-26
235
+ ```
236
+
237
+ You can also use [asdf](https://asdf-vm.com/):
238
+
239
+ ```sh
240
+ asdf install rust nightly-2024-07-26
241
+ ```
242
+
243
+ It's possible that you may need to install [`CMake`](https://cmake.org/) in order to build the project,
244
+ if that is not already installed.
245
+
246
+ Once you have made your changes, run `mix ci`, to lint and format both Elixir
247
+ and Rust code.
248
+
249
+ Our integration tests require the [AWS CLI to be installed](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html),
250
+ and also a container engine that can be [Podman](https://podman.io) or [Docker](https://docker.com).
251
+
252
+ Once these dependencies are installed, you need to run the `mix localstack.setup` command,
253
+ and then run the cloud integration tests with `mix test --only cloud_integration`.
254
+
255
+ Just to recap, here is the combo of commands you need to run:
256
+
257
+ ```sh
258
+ mix ci
259
+ mix localstack.setup
260
+ mix test --only cloud_integration
261
+ ```
262
+
263
+ ## Precompilation
264
+
265
+ Explorer ships with the NIF code precompiled for the most popular architectures out there.
266
+ We support the following:
267
+
268
+ - `aarch64-apple-darwin` - MacOS running on ARM 64 bits CPUs.
269
+ - `aarch64-unknown-linux-gnu` - Linux running on ARM 64 bits CPUs, compiled with GCC.
270
+ - `aarch64-unknown-linux-musl` - Linux running on ARM 64 bits CPUs, compiled with Musl.
271
+ - `x86_64-apple-darwin` - MacOS running on Intel/AMD 64 bits CPUs.
272
+ - `x86_64-pc-windows-msvc` - Windows running on Intel/AMD 64 bits CPUs, compiled with Visual C++.
273
+ - `x86_64-pc-windows-gnu` - Windows running on Intel/AMD 64 bits CPUs, compiled with GCC.
274
+ - `x86_64-unknown-linux-gnu` - Linux running on Intel/AMD 64 bits CPUs, compiled with GCC.
275
+ - `x86_64-unknown-linux-musl` - Linux running on Intel/AMD 64 bits CPUs, compiled with Musl.
276
+ - `x86_64-unknown-freebsd` - FreeBSD running on Intel/AMD 64 bits.
277
+
278
+ This means that Explorer is going to work without the need to compile it from source.
279
+
280
+ This currently **only works for Hex releases**. For more information on how it works, please
281
+ check the [RustlerPrecompiled project](https://hexdocs.pm/rustler_precompiled).
282
+
283
+ ### Legacy CPUs
284
+
285
+ We ship some of the precompiled artifacts with modern CPU features enabled by default. But in
286
+ case your computer is not compatible with them, you can set an application environment that is
287
+ going to be read at compile time, enabling the legacy variants of artifacts.
288
+
289
+ ```elixir
290
+ config :explorer, use_legacy_artifacts: true
291
+ ```
292
+
293
+ If you see the error message "Illegal instruction" after your project compiles, you need to
294
+ enable the legacy artifacts.
295
+
296
+ ### Features disabled
297
+
298
+ Some of the features cannot be compiled to some targets, because one of the dependencies
299
+ don't work on it.
300
+
301
+ This is the case for the **NDJSON** reads and writes, that don't work for the RISCV target.
302
+ We also disable the AWS S3 reads and writes for the RISCV target, because one of the dependencies
303
+ of `ObjectStore` does not compile on it.
304
+
305
+ ## Sponsors
306
+
307
+ <a href="https://amplified.ai"><img src="sponsors/amplified.png" width=100 alt="Amplified"></a>
deps/explorer/checksum-Elixir.Explorer.PolarsBackend.Native.exs ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %{
2
+ "explorer-v0.10.1-nif-2.15-x86_64-pc-windows-gnu--legacy_cpu.dll.tar.gz" => "sha256:d5b411a209e215a435557c17320084efd01f3d8d409c4c62f3cd8ecf24cea2ec",
3
+ "explorer-v0.10.1-nif-2.15-x86_64-pc-windows-gnu.dll.tar.gz" => "sha256:afa33f6285fc1f2bec84ae4d40a405d6be2956643372650b0c80d5d22b09c5f9",
4
+ "explorer-v0.10.1-nif-2.15-x86_64-pc-windows-msvc--legacy_cpu.dll.tar.gz" => "sha256:48efe024015f4210f80858d91a35f0b5018b55af1221b7ce8b3ec03762d9402c",
5
+ "explorer-v0.10.1-nif-2.15-x86_64-pc-windows-msvc.dll.tar.gz" => "sha256:4c1cf15bda0d706535fe83c647f0f0870c9cfe4d912112aee529e49887c05c74",
6
+ "libexplorer-v0.10.1-nif-2.15-aarch64-apple-darwin.so.tar.gz" => "sha256:4c7302413bad0625f99433712cb43105134f280526dd51a0a6967c0f1ed674c4",
7
+ "libexplorer-v0.10.1-nif-2.15-aarch64-unknown-linux-gnu.so.tar.gz" => "sha256:90fbd41ff49ea5f002e9b7a5d81998a8a08999526526c2a48ba0d0c93931af75",
8
+ "libexplorer-v0.10.1-nif-2.15-aarch64-unknown-linux-musl.so.tar.gz" => "sha256:7530142224f105c8be1c406b32d735a7b45a9c9a68b70317c711f22d3098d2d0",
9
+ "libexplorer-v0.10.1-nif-2.15-x86_64-apple-darwin.so.tar.gz" => "sha256:d4d38fbe70c40ed8d46111ce0b87a6ad3b8faad224e36b9f8c30396f5e4c4739",
10
+ "libexplorer-v0.10.1-nif-2.15-x86_64-unknown-freebsd--legacy_cpu.so.tar.gz" => "sha256:c4e0256845332d111bdf0b4c02f0654f4a28f0dbfea8695cb6547b864391731b",
11
+ "libexplorer-v0.10.1-nif-2.15-x86_64-unknown-freebsd.so.tar.gz" => "sha256:167de9dd4aa75864d453cf31daed8d28da3977ae9c5cc1eee445331cb0a45336",
12
+ "libexplorer-v0.10.1-nif-2.15-x86_64-unknown-linux-gnu--legacy_cpu.so.tar.gz" => "sha256:aa6554366140259ef9dec5ef197d70a838f7ff7e26797da34fd0dd2ebe49d7ef",
13
+ "libexplorer-v0.10.1-nif-2.15-x86_64-unknown-linux-gnu.so.tar.gz" => "sha256:ea3146648bec7e1ad30956e4609a5522a15db026c33e51a95c23d90064a1541c",
14
+ "libexplorer-v0.10.1-nif-2.15-x86_64-unknown-linux-musl.so.tar.gz" => "sha256:5c049bd578ef80814863a04fbfb56a593b273dae3aa5e7e8f4da62ffd6e84b9d",
15
+ }
deps/explorer/datasets/fossil_fuels.csv ADDED
@@ -0,0 +1,1095 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ year,country,total,solid_fuel,liquid_fuel,gas_fuel,cement,gas_flaring,per_capita,bunker_fuels
2
+ 2010,AFGHANISTAN,2308,627,1601,74,5,0,0.08,9
3
+ 2010,ALBANIA,1254,117,953,7,177,0,0.43,7
4
+ 2010,ALGERIA,32500,332,12381,14565,2598,2623,0.9,663
5
+ 2010,ANDORRA,141,0,141,0,0,0,1.68,0
6
+ 2010,ANGOLA,7924,0,3649,374,204,3697,0.37,321
7
+ 2010,ANGUILLA,41,0,41,0,0,0,2.98,0
8
+ 2010,ANTIGUA & BARBUDA,143,0,143,0,0,0,1.64,39
9
+ 2010,ARGENTINA,51246,1089,24606,23725,1418,407,1.24,1542
10
+ 2010,ARMENIA,1150,3,275,806,66,0,0.39,37
11
+ 2010,ARUBA,684,0,684,0,0,0,6.73,74
12
+ 2010,AUSTRALIA,106589,56257,31308,17763,1129,132,4.81,3307
13
+ 2010,AUSTRIA,18408,3537,9218,5073,579,0,2.19,575
14
+ 2010,AZERBAIJAN,8366,6,2373,4904,174,909,0.92,398
15
+ 2010,BAHAMAS,451,1,450,0,0,0,1.25,179
16
+ 2010,BAHRAIN,7981,0,1123,6696,163,0,6.33,545
17
+ 2010,BANGLADESH,16345,839,2881,10753,1873,0,0.11,313
18
+ 2010,BARBADOS,403,0,363,8,31,1,1.44,108
19
+ 2010,BELARUS,17192,620,4620,11336,616,0,1.81,0
20
+ 2010,BELGIUM,30222,3787,14993,10613,829,0,2.77,7916
21
+ 2010,BELIZE,147,0,143,3,0,0,0.46,11
22
+ 2010,BENIN,1388,0,1211,0,177,0,0.15,127
23
+ 2010,BERMUDA,166,0,166,0,0,0,2.59,50
24
+ 2010,BHUTAN,133,21,85,0,27,0,0.19,1
25
+ 2010,BOSNIA & HERZEGOVINA,5802,4332,1217,125,129,0,1.51,4
26
+ 2010,BOTSWANA,1278,576,667,0,35,0,0.62,14
27
+ 2010,BRAZIL,114468,15965,74689,14372,8040,1402,0.58,5101
28
+ 2010,BRITISH VIRGIN ISLANDS,47,0,47,0,0,0,1.72,0
29
+ 2010,BRUNEI (DARUSSALAM),2237,0,434,1672,37,94,5.69,167
30
+ 2010,BULGARIA,12030,7284,3042,1437,267,0,1.62,223
31
+ 2010,BURKINA FASO,535,0,455,0,80,0,0.03,30
32
+ 2010,BURUNDI,58,5,53,0,0,0,0.01,4
33
+ 2010,CAMBODIA,1367,9,1252,0,107,0,0.1,32
34
+ 2010,CANADA,145806,24504,69694,49114,1691,804,4.27,1518
35
+ 2010,CAPE VERDE,152,0,152,0,0,0,0.31,71
36
+ 2010,CAYMAN ISLANDS,152,0,152,0,0,0,2.75,9
37
+ 2010,CENTRAL AFRICAN REPUBLIC,72,0,72,0,0,0,0.02,27
38
+ 2010,CHAD,141,0,141,0,0,0,0.01,15
39
+ 2010,CHILE,19703,4510,11861,2791,526,14,1.16,768
40
+ 2010,CHINA (MAINLAND),2393248,1792793,298191,54472,247792,0,1.78,11687
41
+ 2010,COLOMBIA,20773,3677,9507,6001,1293,295,0.45,1122
42
+ 2010,COMOROS,44,0,44,0,0,0,0.06,2
43
+ 2010,CONGO,540,0,476,53,11,0,0.13,38
44
+ 2010,COOK ISLANDS,19,0,19,0,0,0,0.95,2
45
+ 2010,COSTA RICA,2064,63,1828,0,174,0,0.45,0
46
+ 2010,COTE D IVOIRE,1900,0,826,829,245,0,0.09,64
47
+ 2010,CROATIA,5501,704,2815,1644,338,0,1.27,86
48
+ 2010,CUBA,10465,21,9659,562,222,0,0.93,140
49
+ 2010,CYPRUS,2102,19,1901,0,181,0,1.9,391
50
+ 2010,CZECH REPUBLIC,30428,19505,5423,5040,460,0,2.9,259
51
+ 2010,DEMOCRATIC PEOPLE S REPUBLIC OF KOREA,18122,16591,701,0,830,0,0.74,0
52
+ 2010,DEMOCRATIC REPUBLIC OF THE CONGO (FORMERLY ZAIRE),551,0,471,12,67,0,0.01,126
53
+ 2010,DENMARK,12719,4172,5504,2762,211,70,2.29,1272
54
+ 2010,DJIBOUTI,141,0,141,0,0,0,0.17,88
55
+ 2010,DOMINICA,38,0,38,0,0,0,0.53,2
56
+ 2010,DOMINICAN REPUBLIC,5733,505,4262,408,558,0,0.58,357
57
+ 2010,ECUADOR,9943,0,8517,397,719,310,0.67,708
58
+ 2010,EGYPT,55281,1126,25725,22366,6065,0,0.67,2602
59
+ 2010,EL SALVADOR,1761,0,1586,0,175,0,0.29,92
60
+ 2010,EQUATORIAL GUINEA,1276,0,166,827,0,283,1.75,30
61
+ 2010,ERITREA,140,0,134,0,6,0,0.03,1
62
+ 2010,ESTONIA,4938,4158,378,351,51,0,3.71,224
63
+ 2010,ETHIOPIA,1796,36,1537,0,223,0,0.02,233
64
+ 2010,FAEROE ISLANDS,172,0,172,0,0,0,3.53,26
65
+ 2010,FALKLAND ISLANDS (MALVINAS),15,3,12,0,0,0,5.22,0
66
+ 2010,FEDERATED STATES OF MICRONESIA,31,0,31,0,0,0,0.3,1
67
+ 2010,FIJI,333,0,310,1,22,0,0.39,139
68
+ 2010,FINLAND,16930,7388,6980,2397,165,0,3.15,630
69
+ 2010,FRANCE (INCLUDING MONACO),96273,12332,54960,26569,2412,0,1.53,6636
70
+ 2010,FRENCH GUIANA,174,0,162,0,12,0,0.75,32
71
+ 2010,FRENCH POLYNESIA,234,0,234,0,0,0,0.87,50
72
+ 2010,GABON,1312,0,537,168,30,577,0.85,248
73
+ 2010,GAMBIA,118,0,116,1,0,0,0.07,15
74
+ 2010,GEORGIA,1722,218,754,634,117,0,0.41,34
75
+ 2010,GERMANY,206943,83574,71983,47408,3972,6,2.57,9078
76
+ 2010,GHANA,2715,0,2208,221,286,0,0.11,169
77
+ 2010,GIBRALTAR,127,0,127,0,0,0,4.14,3666
78
+ 2010,GREECE,22868,8457,11130,2020,1260,0,2.05,2973
79
+ 2010,GREENLAND,181,0,181,0,0,0,3.2,34
80
+ 2010,GRENADA,71,0,71,0,0,0,0.68,4
81
+ 2010,GUADELOUPE,627,112,474,0,41,0,1.37,91
82
+ 2010,GUATEMALA,3181,356,2445,0,380,0,0.22,293
83
+ 2010,GUINEA,710,0,678,0,32,0,0.06,21
84
+ 2010,GUINEA BISSAU,65,0,65,0,0,0,0.04,9
85
+ 2010,GUYANA,469,0,469,0,0,0,0.62,8
86
+ 2010,HAITI,580,0,539,0,41,0,0.06,17
87
+ 2010,HONDURAS,2175,124,1833,0,218,0,0.29,40
88
+ 2010,HONG KONG SPECIAL ADMINSTRATIVE REGION OF CHINA,11093,6438,2688,1768,199,0,1.59,13595
89
+ 2010,HUNGARY,13696,2958,4318,6131,290,0,1.37,196
90
+ 2010,ICELAND,535,93,423,0,19,0,1.68,152
91
+ 2010,INDIA,468964,298209,112969,27357,29920,509,0.38,4035
92
+ 2010,INDONESIA,116924,35295,53405,20123,5369,2733,0.48,248
93
+ 2010,IRAQ,30596,0,21668,4044,1088,3796,0.99,0
94
+ 2010,IRELAND,10923,2201,5469,2930,324,0,2.37,671
95
+ 2010,ISLAMIC REPUBLIC OF IRAN,156267,1487,62100,75661,8296,8723,2.1,3088
96
+ 2010,ISRAEL,18784,7661,7673,2751,699,0,2.53,944
97
+ 2010,ITALY (INCLUDING SAN MARINO),110543,14655,48702,42507,4679,0,1.85,5284
98
+ 2010,JAMAICA,1990,31,1861,0,98,0,0.73,224
99
+ 2010,JAPAN,319505,119676,139083,53738,7008,0,2.51,8339
100
+ 2010,JORDAN,5776,0,3813,1429,534,0,0.89,119
101
+ 2010,KAZAKHSTAN,67780,35784,12921,18166,909,0,4.16,174
102
+ 2010,KENYA,3320,171,2644,0,505,0,0.08,576
103
+ 2010,KIRIBATI,17,0,17,0,0,0,0.16,3
104
+ 2010,KUWAIT,24441,0,16377,7678,272,114,7.99,1072
105
+ 2010,KYRGYZSTAN,1741,732,752,154,103,0,0.32,230
106
+ 2010,LAO PEOPLE S DEMOCRATIC REPUBLIC,447,181,104,0,163,0,0.07,9
107
+ 2010,LATVIA,2202,112,1091,913,86,0,1.05,316
108
+ 2010,LEBANON,5467,154,4470,132,711,0,1.26,213
109
+ 2010,LESOTHO,621,478,143,0,0,0,0.31,0
110
+ 2010,LIBERIA,216,0,206,0,10,0,0.05,15
111
+ 2010,LIBYAN ARAB JAMAHIRIYAH,16897,0,10515,3602,952,1829,2.7,486
112
+ 2010,LIECHTENSTEIN,15,0,0,15,0,0,0.4,0
113
+ 2010,LITHUANIA,3673,219,1785,1556,113,0,1.18,164
114
+ 2010,LUXEMBOURG,2991,78,2019,747,147,0,5.89,358
115
+ 2010,MACAU SPECIAL ADMINSTRATIVE REGION OF CHINA,384,0,303,81,0,0,0.72,0
116
+ 2010,MACEDONIA,2346,1426,749,60,112,0,1.14,6
117
+ 2010,MADAGASCAR,534,29,483,0,22,0,0.03,54
118
+ 2010,MALAWI,312,46,240,0,26,0,0.02,6
119
+ 2010,MALAYSIA,59579,15103,20006,16596,2688,5186,2.12,1432
120
+ 2010,MALDIVES,255,0,255,0,0,0,0.77,39
121
+ 2010,MALI,263,0,263,0,0,0,0.02,18
122
+ 2010,MALTA,698,0,698,0,0,0,1.69,1365
123
+ 2010,MARSHALL ISLANDS,28,0,28,0,0,0,0.54,0
124
+ 2010,MARTINIQUE,548,0,528,0,20,0,1.39,117
125
+ 2010,MAURITANIA,610,0,535,0,75,0,0.17,15
126
+ 2010,MAURITIUS,1068,429,639,0,0,0,0.86,300
127
+ 2010,MEXICO,126618,13934,70873,33876,4692,3243,1.07,2875
128
+ 2010,MONGOLIA,3769,3051,674,0,44,0,1.39,0
129
+ 2010,MONTENEGRO,704,443,261,0,0,0,1.13,2
130
+ 2010,MONTSERRAT,18,0,18,0,0,0,3.55,1
131
+ 2010,MOROCCO,15260,3609,9391,356,1904,0,0.47,490
132
+ 2010,MOZAMBIQUE,746,7,577,42,120,0,0.03,55
133
+ 2010,MYANMAR (FORMERLY BURMA),3413,160,2046,1130,73,3,0.07,17
134
+ 2010,NAMIBIA,846,76,769,0,1,0,0.39,32
135
+ 2010,NAURU,12,0,12,0,0,0,1.17,4
136
+ 2010,NEPAL,1379,301,893,0,185,0,0.05,68
137
+ 2010,NETHERLAND ANTILLES,1244,0,1244,0,0,0,5.99,2061
138
+ 2010,NETHERLANDS,49919,6902,18219,24487,291,20,3.0,14837
139
+ 2010,NEW CALEDONIA,966,332,612,0,22,0,3.92,28
140
+ 2010,NEW ZEALAND,8667,1416,4672,2329,150,101,1.98,907
141
+ 2010,NICARAGUA,1237,0,1155,0,82,0,0.22,15
142
+ 2010,NIGER,320,90,226,0,4,0,0.02,11
143
+ 2010,NIGERIA,24957,28,10028,5512,1360,8029,0.16,498
144
+ 2010,NIUE,1,0,1,0,0,0,0.52,0
145
+ 2010,NORWAY,16391,790,10300,4843,177,282,3.35,693
146
+ 2010,OCCUPIED PALESTINIAN TERRITORY,555,0,555,0,0,0,0.14,0
147
+ 2010,OMAN,12931,0,2331,9309,612,679,4.39,1342
148
+ 2010,PAKISTAN,44013,4756,16989,18188,4080,0,0.26,286
149
+ 2010,PALAU,69,0,69,0,0,0,3.35,14
150
+ 2010,PANAMA,2499,70,2225,0,203,0,0.69,2916
151
+ 2010,PAPUA NEW GUINEA,1299,0,1193,79,27,0,0.19,64
152
+ 2010,PARAGUAY,1390,0,1302,0,88,0,0.22,22
153
+ 2010,PERU,15706,772,6330,3433,1142,4029,0.53,732
154
+ 2010,PHILIPPINES,23144,7697,11356,1929,2162,0,0.25,1020
155
+ 2010,PLURINATIONAL STATE OF BOLIVIA,4146,0,2178,1595,328,45,0.42,38
156
+ 2010,POLAND,86246,58230,17902,7998,2111,5,2.24,612
157
+ 2010,PORTUGAL,13127,1719,7981,2803,624,0,1.24,1138
158
+ 2010,QATAR,19773,0,4149,14573,514,537,11.2,942
159
+ 2010,REPUBLIC OF CAMEROON,1849,0,1551,162,136,0,0.09,92
160
+ 2010,REPUBLIC OF KOREA,154545,76263,47701,24131,6449,0,3.15,10794
161
+ 2010,REPUBLIC OF MOLDOVA,1345,89,593,541,122,0,0.33,11
162
+ 2010,REUNION,1137,503,593,0,41,0,1.37,56
163
+ 2010,ROMANIA,21656,7489,6489,6738,940,0,1.07,134
164
+ 2010,RUSSIAN FEDERATION,455558,107603,93687,239553,6854,7861,3.18,6514
165
+ 2010,RWANDA,161,0,147,0,13,0,0.02,13
166
+ 2010,SAINT HELENA,3,0,3,0,0,0,0.8,0
167
+ 2010,SAINT LUCIA,110,0,110,0,0,0,0.62,5
168
+ 2010,SAMOA,51,0,51,0,0,0,0.27,9
169
+ 2010,SAO TOME & PRINCIPE,27,0,27,0,0,0,0.16,9
170
+ 2010,SAUDI ARABIA,141394,0,98157,37412,5825,0,5.03,3920
171
+ 2010,SENEGAL,2112,184,1362,13,553,0,0.16,244
172
+ 2010,SERBIA,12532,8412,2616,1158,347,0,1.38,35
173
+ 2010,SEYCHELLES,121,0,121,0,0,0,1.3,158
174
+ 2010,SIERRA LEONE,198,0,157,0,41,0,0.03,7
175
+ 2010,SINGAPORE,15174,7,10661,4506,0,0,2.99,39109
176
+ 2010,SLOVAKIA,9883,4144,2214,3127,393,5,1.83,34
177
+ 2010,SLOVENIA,4182,1529,2005,539,109,0,2.04,39
178
+ 2010,SOLOMON ISLANDS,54,0,54,0,0,0,0.1,4
179
+ 2010,SOMALIA,167,0,167,0,0,0,0.02,56
180
+ 2010,SOUTH AFRICA,129288,111034,14356,2420,1478,0,2.5,3323
181
+ 2010,SPAIN,73878,8463,42407,19443,3566,0,1.59,9913
182
+ 2010,SRI LANKA,3617,62,3319,0,236,0,0.18,337
183
+ 2010,ST. KITTS-NEVIS,60,0,60,0,0,0,1.15,4
184
+ 2010,ST. PIERRE & MIQUELON,19,0,19,0,0,0,3.07,5
185
+ 2010,ST. VINCENT & THE GRENADINES,60,0,60,0,0,0,0.55,0
186
+ 2010,SUDAN,4347,0,4085,0,262,0,0.1,244
187
+ 2010,SURINAME,655,0,646,2,6,1,1.26,62
188
+ 2010,SWAZILAND,283,101,183,0,0,0,0.24,1
189
+ 2010,SWEDEN,14187,2596,10431,916,244,0,1.51,2298
190
+ 2010,SWITZERLAND,10634,149,7989,1880,616,0,1.35,1177
191
+ 2010,SYRIAN ARAB REPUBLIC,16800,3,10874,4874,816,233,0.81,952
192
+ 2010,TAIWAN,73629,42913,20199,8299,2217,0,3.17,3198
193
+ 2010,TAJIKISTAN,694,92,462,100,39,0,0.09,25
194
+ 2010,THAILAND,76882,15323,35535,22102,3922,0,1.15,2660
195
+ 2010,TIMOR-LESTE (FORMERLY EAST TIMOR),64,0,64,0,0,0,0.06,3
196
+ 2010,TOGO,720,0,559,0,161,0,0.11,72
197
+ 2010,TONGA,32,0,32,0,0,0,0.31,3
198
+ 2010,TRINIDAD AND TOBAGO,13072,0,1500,11465,108,0,9.84,519
199
+ 2010,TUNISIA,7543,15,3138,3176,1098,116,0.71,219
200
+ 2010,TURKEY,81266,33918,19206,19609,8532,1,1.12,1330
201
+ 2010,TURKMENISTAN,15623,0,4636,10831,156,0,3.1,453
202
+ 2010,TURKS AND CAICOS ISLANDS,52,0,52,0,0,0,1.67,0
203
+ 2010,TUVALU,2,0,2,0,0,0,0.0,0
204
+ 2010,UGANDA,1069,0,886,0,183,0,0.03,74
205
+ 2010,UKRAINE,83077,36870,10413,34508,1286,0,1.82,228
206
+ 2010,UNITED ARAB EMIRATES,43854,703,8297,31896,2448,510,5.26,18488
207
+ 2010,UNITED KINGDOM,134499,31709,47810,53120,1072,787,2.14,11334
208
+ 2010,UNITED REPUBLIC OF TANZANIA,1938,0,1222,402,314,1,0.04,131
209
+ 2010,UNITED STATES OF AMERICA,1471375,521330,590751,347716,9139,2439,4.69,40388
210
+ 2010,URUGUAY,1742,1,1587,41,113,0,0.52,451
211
+ 2010,UZBEKISTAN,28407,1406,2813,23253,935,0,1.02,0
212
+ 2010,VANUATU,33,0,33,0,0,0,0.14,9
213
+ 2010,VENEZUELA,51560,206,30725,16153,968,3507,1.78,1200
214
+ 2010,VIET NAM,38925,12954,13456,4926,7589,0,0.44,835
215
+ 2010,WALLIS AND FUTUNA ISLANDS,8,0,8,0,0,0,0.56,1
216
+ 2010,YEMEN,6390,123,5482,531,254,0,0.27,190
217
+ 2010,ZAMBIA,734,104,477,0,153,0,0.05,25
218
+ 2010,ZIMBABWE,2121,1531,481,0,109,0,0.15,7
219
+ 2011,AFGHANISTAN,3338,1174,2075,84,5,0,0.12,9
220
+ 2011,ALBANIA,1429,146,1030,8,245,0,0.5,7
221
+ 2011,ALGERIA,33048,286,12806,15481,2584,1892,0.9,609
222
+ 2011,ANDORRA,134,0,134,0,0,0,1.63,0
223
+ 2011,ANGOLA,8274,0,3915,384,204,3771,0.38,314
224
+ 2011,ANGUILLA,39,0,39,0,0,0,2.76,0
225
+ 2011,ANTIGUA & BARBUDA,140,0,140,0,0,0,1.59,41
226
+ 2011,ARGENTINA,52259,1289,23723,25269,1577,401,1.25,1772
227
+ 2011,ARMENIA,1341,2,257,1025,57,0,0.45,38
228
+ 2011,ARUBA,682,0,682,0,0,0,6.69,75
229
+ 2011,AUSTRALIA,106850,54287,32565,18687,1170,142,4.74,3177
230
+ 2011,AUSTRIA,17731,3599,8742,4788,602,0,2.1,605
231
+ 2011,AZERBAIJAN,9121,5,2855,5192,194,874,0.99,430
232
+ 2011,BAHAMAS,509,1,507,0,0,0,1.39,161
233
+ 2011,BAHRAIN,7813,0,1008,6628,177,0,5.98,507
234
+ 2011,BANGLADESH,17293,774,3706,10815,1998,0,0.11,359
235
+ 2011,BARBADOS,417,0,378,9,30,1,1.49,121
236
+ 2011,BELARUS,17470,632,5479,10733,626,0,1.84,0
237
+ 2011,BELGIUM,27255,3522,13799,8988,946,0,2.48,7243
238
+ 2011,BELIZE,164,0,161,3,0,0,0.5,9
239
+ 2011,BENIN,1444,0,1245,0,199,0,0.15,131
240
+ 2011,BERMUDA,121,0,121,0,0,0,1.9,18
241
+ 2011,BHUTAN,200,26,100,0,74,0,0.27,1
242
+ 2011,BOSNIA & HERZEGOVINA,6514,5045,1206,142,121,0,1.7,4
243
+ 2011,BOTSWANA,1139,390,707,0,41,0,0.54,15
244
+ 2011,BRAZIL,119829,17498,78849,13778,8717,987,0.6,5516
245
+ 2011,BRITISH VIRGIN ISLANDS,48,0,48,0,0,0,1.71,0
246
+ 2011,BRUNEI (DARUSSALAM),2644,0,534,1989,39,82,6.62,175
247
+ 2011,BULGARIA,13457,8738,2822,1643,254,0,1.83,206
248
+ 2011,BURKINA FASO,603,0,523,0,80,0,0.04,35
249
+ 2011,BURUNDI,66,3,58,0,5,0,0.01,3
250
+ 2011,CAMBODIA,1420,10,1288,0,123,0,0.1,38
251
+ 2011,CANADA,146472,21966,69866,52135,1632,873,4.25,1223
252
+ 2011,CAPE VERDE,168,0,168,0,0,0,0.34,94
253
+ 2011,CAYMAN ISLANDS,160,0,160,0,0,0,2.83,9
254
+ 2011,CENTRAL AFRICAN REPUBLIC,76,0,76,0,0,0,0.02,27
255
+ 2011,CHAD,147,0,147,0,0,0,0.01,15
256
+ 2011,CHILE,21610,5690,12453,2852,599,16,1.26,790
257
+ 2011,CHINA (MAINLAND),2654360,1995029,306730,67137,285464,0,1.97,12636
258
+ 2011,COLOMBIA,20870,3762,9537,5745,1466,359,0.45,1241
259
+ 2011,COMOROS,37,0,37,0,0,0,0.05,3
260
+ 2011,CONGO,616,0,529,77,10,0,0.15,42
261
+ 2011,COOK ISLANDS,19,0,19,0,0,0,0.94,2
262
+ 2011,COSTA RICA,2111,62,1859,0,190,0,0.46,0
263
+ 2011,COTE D IVOIRE,1977,0,915,817,245,0,0.1,56
264
+ 2011,CROATIA,5402,730,2730,1605,336,0,1.26,105
265
+ 2011,CUBA,9814,3,9040,534,236,0,0.87,140
266
+ 2011,CYPRUS,2025,9,1852,0,164,0,1.81,422
267
+ 2011,CZECH REPUBLIC,29154,19062,5304,4253,535,0,2.77,257
268
+ 2011,DEMOCRATIC PEOPLE S REPUBLIC OF KOREA,13099,11521,721,0,857,0,0.53,0
269
+ 2011,DEMOCRATIC REPUBLIC OF THE CONGO (FORMERLY ZAIRE),680,0,606,12,62,0,0.01,124
270
+ 2011,DENMARK,11084,3348,5121,2322,246,48,1.99,1299
271
+ 2011,DJIBOUTI,129,0,129,0,0,0,0.15,85
272
+ 2011,DOMINICA,35,0,35,0,0,0,0.49,2
273
+ 2011,DOMINICAN REPUBLIC,5789,573,4232,440,544,0,0.58,364
274
+ 2011,ECUADOR,10529,0,9046,365,776,343,0.69,707
275
+ 2011,EGYPT,59221,464,27562,25295,5900,0,0.71,990
276
+ 2011,EL SALVADOR,1813,0,1633,0,180,0,0.3,94
277
+ 2011,EQUATORIAL GUINEA,1671,0,166,880,0,625,2.23,30
278
+ 2011,ERITREA,162,0,136,0,26,0,0.03,1
279
+ 2011,ESTONIA,5074,4349,350,314,61,0,3.82,194
280
+ 2011,ETHIOPIA,2107,123,1701,0,283,0,0.02,233
281
+ 2011,FAEROE ISLANDS,155,0,155,0,0,0,3.19,29
282
+ 2011,FALKLAND ISLANDS (MALVINAS),15,3,12,0,0,0,5.22,0
283
+ 2011,FEDERATED STATES OF MICRONESIA,33,0,33,0,0,0,0.32,1
284
+ 2011,FIJI,297,0,274,0,23,0,0.34,44
285
+ 2011,FINLAND,15494,6325,6881,2099,189,0,2.87,701
286
+ 2011,FRANCE (INCLUDING MONACO),90484,10543,54185,23136,2621,0,1.43,7029
287
+ 2011,FRENCH GUIANA,175,0,163,0,12,0,0.73,33
288
+ 2011,FRENCH POLYNESIA,227,0,227,0,0,0,0.84,47
289
+ 2011,GABON,1356,0,604,188,31,532,0.86,224
290
+ 2011,GAMBIA,122,0,121,1,0,0,0.07,18
291
+ 2011,GEORGIA,2174,289,739,942,204,0,0.52,30
292
+ 2011,GERMANY,199754,82252,69465,43468,4561,8,2.48,8789
293
+ 2011,GHANA,2681,0,1909,432,340,0,0.11,178
294
+ 2011,GIBRALTAR,123,0,123,0,0,0,3.96,3653
295
+ 2011,GREECE,21773,8491,10046,2481,755,0,1.95,3061
296
+ 2011,GREENLAND,193,0,193,0,0,0,3.43,40
297
+ 2011,GRENADA,69,0,69,0,0,0,0.65,3
298
+ 2011,GUADELOUPE,663,145,477,0,41,0,1.45,91
299
+ 2011,GUATEMALA,3228,357,2483,0,388,0,0.21,298
300
+ 2011,GUINEA,758,0,708,0,50,0,0.07,21
301
+ 2011,GUINEA BISSAU,67,0,67,0,0,0,0.04,9
302
+ 2011,GUYANA,486,0,486,0,0,0,0.64,8
303
+ 2011,HAITI,605,0,564,0,41,0,0.06,15
304
+ 2011,HONDURAS,2442,181,2040,0,220,0,0.32,45
305
+ 2011,HONG KONG SPECIAL ADMINSTRATIVE REGION OF CHINA,11943,7659,2637,1438,209,0,1.7,13924
306
+ 2011,HUNGARY,13047,3008,3967,5842,230,0,1.31,198
307
+ 2011,ICELAND,513,94,400,0,19,0,1.6,168
308
+ 2011,INDIA,502257,330199,113915,24937,32640,567,0.4,4035
309
+ 2011,INDONESIA,164621,75931,57677,22258,6152,2603,0.67,744
310
+ 2011,IRAQ,36647,0,27114,3127,1360,5046,1.15,815
311
+ 2011,IRELAND,9717,2059,4796,2576,286,0,2.09,644
312
+ 2011,ISLAMIC REPUBLIC OF IRAN,160637,1450,61052,80039,8976,9119,2.14,2935
313
+ 2011,ISRAEL,18852,7915,7642,2550,745,0,2.49,964
314
+ 2011,ITALY (INCLUDING SAN MARINO),108534,16433,47740,39857,4504,0,1.82,4926
315
+ 2011,JAMAICA,2143,58,1981,0,104,0,0.78,213
316
+ 2011,JAPAN,324809,111852,143467,62514,6976,0,2.55,8406
317
+ 2011,JORDAN,5909,0,4981,545,383,0,0.87,104
318
+ 2011,KAZAKHSTAN,70646,39193,10260,20154,1039,0,4.27,151
319
+ 2011,KENYA,3670,277,2784,0,609,0,0.09,597
320
+ 2011,KIRIBATI,17,0,17,0,0,0,0.16,3
321
+ 2011,KUWAIT,24824,0,15436,8968,306,114,7.66,1488
322
+ 2011,KYRGYZSTAN,2088,782,993,174,139,0,0.38,44
323
+ 2011,LAO PEOPLE S DEMOCRATIC REPUBLIC,443,151,115,0,177,0,0.07,9
324
+ 2011,LATVIA,1989,114,968,805,102,0,0.96,284
325
+ 2011,LEBANON,5575,171,4656,0,748,0,1.21,216
326
+ 2011,LESOTHO,636,485,151,0,0,0,0.31,0
327
+ 2011,LIBERIA,243,0,232,0,11,0,0.06,16
328
+ 2011,LIBYAN ARAB JAMAHIRIYAH,10827,0,6892,2775,476,684,1.72,114
329
+ 2011,LIECHTENSTEIN,13,0,0,13,0,0,0.35,0
330
+ 2011,LITHUANIA,3760,250,1677,1698,135,0,1.22,171
331
+ 2011,LUXEMBOURG,2983,60,2099,645,179,0,5.74,335
332
+ 2011,MACAU SPECIAL ADMINSTRATIVE REGION OF CHINA,395,0,357,39,0,0,0.72,0
333
+ 2011,MACEDONIA,2563,1588,774,69,133,0,1.24,3
334
+ 2011,MADAGASCAR,638,111,500,0,27,0,0.03,68
335
+ 2011,MALAWI,322,67,227,0,28,0,0.02,6
336
+ 2011,MALAYSIA,60105,15159,19794,17681,2883,4587,2.1,1653
337
+ 2011,MALDIVES,269,0,269,0,0,0,0.79,49
338
+ 2011,MALI,285,0,285,0,0,0,0.02,18
339
+ 2011,MALTA,693,0,693,0,0,0,1.67,1267
340
+ 2011,MARSHALL ISLANDS,28,0,28,0,0,0,0.54,0
341
+ 2011,MARTINIQUE,605,0,585,0,20,0,1.53,120
342
+ 2011,MAURITANIA,653,0,576,0,77,0,0.18,15
343
+ 2011,MAURITIUS,1069,411,658,0,0,0,0.85,345
344
+ 2011,MEXICO,132105,15295,74375,35673,4814,1947,1.1,2982
345
+ 2011,MONGOLIA,5863,4968,837,0,58,0,2.13,0
346
+ 2011,MONTENEGRO,701,457,244,0,0,0,1.13,9
347
+ 2011,MONTSERRAT,11,0,11,0,0,0,2.18,1
348
+ 2011,MOROCCO,15731,3869,9508,450,1904,0,0.48,549
349
+ 2011,MOZAMBIQUE,879,34,662,50,133,0,0.04,50
350
+ 2011,MYANMAR (FORMERLY BURMA),3899,227,2096,1500,73,3,0.07,16
351
+ 2011,NAMIBIA,772,19,700,0,53,0,0.34,11
352
+ 2011,NAURU,11,0,11,0,0,0,1.08,4
353
+ 2011,NEPAL,1509,304,919,0,286,0,0.06,76
354
+ 2011,NETHERLAND ANTILLES,1587,0,1587,0,0,0,7.45,2086
355
+ 2011,NETHERLANDS,47496,7475,18317,21364,315,25,2.85,15879
356
+ 2011,NEW CALEDONIA,995,345,630,0,20,0,3.98,27
357
+ 2011,NEW ZEALAND,8591,1549,4661,2130,163,87,1.95,918
358
+ 2011,NICARAGUA,1331,0,1236,0,95,0,0.23,17
359
+ 2011,NIGER,362,101,250,0,10,0,0.02,13
360
+ 2011,NIGERIA,26096,23,9307,7643,1632,7491,0.16,498
361
+ 2011,NIUE,2,0,2,0,0,0,1.04,0
362
+ 2011,NORWAY,12325,874,7971,3022,189,269,2.49,679
363
+ 2011,OCCUPIED PALESTINIAN TERRITORY,613,0,613,0,0,0,0.15,0
364
+ 2011,OMAN,14734,0,2897,10676,680,482,4.59,817
365
+ 2011,PAKISTAN,44166,4685,16528,19009,3944,0,0.25,257
366
+ 2011,PALAU,69,0,69,0,0,0,3.37,15
367
+ 2011,PANAMA,2754,223,2291,0,240,0,0.75,3267
368
+ 2011,PAPUA NEW GUINEA,1453,0,1344,83,27,0,0.21,68
369
+ 2011,PARAGUAY,1451,1,1362,0,88,0,0.23,22
370
+ 2011,PERU,13535,780,6526,3184,1156,1888,0.45,791
371
+ 2011,PHILIPPINES,23315,8465,10582,2082,2185,0,0.25,1117
372
+ 2011,PLURINATIONAL STATE OF BOLIVIA,4403,0,2308,1685,361,49,0.44,41
373
+ 2011,POLAND,86446,57784,18116,8017,2523,6,2.24,563
374
+ 2011,PORTUGAL,12987,2285,7225,2788,689,0,1.23,1259
375
+ 2011,QATAR,21935,0,2763,18199,680,293,11.51,1243
376
+ 2011,REPUBLIC OF CAMEROON,1573,0,1301,116,156,0,0.07,97
377
+ 2011,REPUBLIC OF KOREA,160731,83147,45047,25975,6562,0,3.26,10614
378
+ 2011,REPUBLIC OF MOLDOVA,1374,91,624,523,136,0,0.34,11
379
+ 2011,REUNION,1165,495,636,0,34,0,1.39,61
380
+ 2011,ROMANIA,23147,8791,6426,6936,994,0,1.15,115
381
+ 2011,RUSSIAN FEDERATION,480885,109218,108312,247327,7643,8385,3.36,7962
382
+ 2011,RWANDA,181,0,167,0,13,0,0.02,15
383
+ 2011,SAINT HELENA,3,0,3,0,0,0,0.81,0
384
+ 2011,SAINT LUCIA,111,0,111,0,0,0,0.62,5
385
+ 2011,SAMOA,55,0,55,0,0,0,0.29,9
386
+ 2011,SAO TOME & PRINCIPE,28,0,28,0,0,0,0.16,9
387
+ 2011,SAUDI ARABIA,136318,0,91624,38105,6589,0,4.74,4452
388
+ 2011,SENEGAL,2282,257,1378,10,636,0,0.17,247
389
+ 2011,SERBIA,13422,9355,2537,1188,342,0,1.49,39
390
+ 2011,SEYCHELLES,93,0,93,0,0,0,0.99,151
391
+ 2011,SIERRA LEONE,245,0,203,0,42,0,0.04,7
392
+ 2011,SINGAPORE,12332,7,7774,4551,0,0,2.38,41786
393
+ 2011,SLOVAKIA,9415,3920,2156,2896,438,5,1.74,36
394
+ 2011,SLOVENIA,4115,1571,1999,461,84,0,2.0,48
395
+ 2011,SOLOMON ISLANDS,54,0,54,0,0,0,0.1,4
396
+ 2011,SOMALIA,165,0,165,0,0,0,0.02,56
397
+ 2011,SOUTH AFRICA,128329,109120,15279,2402,1528,0,2.46,3458
398
+ 2011,SPAIN,73779,12922,39769,18073,3016,0,1.58,10585
399
+ 2011,SRI LANKA,4128,309,3549,0,270,0,0.2,511
400
+ 2011,ST. KITTS-NEVIS,63,0,63,0,0,0,1.18,4
401
+ 2011,ST. PIERRE & MIQUELON,19,0,19,0,0,0,3.07,5
402
+ 2011,ST. VINCENT & THE GRENADINES,54,0,54,0,0,0,0.49,0
403
+ 2011,SUDAN,4270,0,3862,0,408,0,0.09,280
404
+ 2011,SURINAME,537,0,524,2,10,1,1.03,56
405
+ 2011,SWAZILAND,286,102,184,0,0,0,0.24,1
406
+ 2011,SWEDEN,14108,2589,10514,724,281,0,1.49,2129
407
+ 2011,SWITZERLAND,10081,139,7652,1667,622,0,1.27,1263
408
+ 2011,SYRIAN ARAB REPUBLIC,15519,3,10376,4110,680,350,0.76,827
409
+ 2011,TAIWAN,73406,42590,19763,8760,2292,0,3.16,3067
410
+ 2011,TAJIKISTAN,641,101,399,101,41,0,0.08,27
411
+ 2011,THAILAND,75898,17009,33725,21045,4119,0,1.13,2857
412
+ 2011,TIMOR-LESTE (FORMERLY EAST TIMOR),67,0,67,0,0,0,0.06,3
413
+ 2011,TOGO,672,0,510,4,158,0,0.1,66
414
+ 2011,TONGA,28,0,28,0,0,0,0.27,3
415
+ 2011,TRINIDAD AND TOBAGO,12799,0,1374,11313,112,0,9.59,577
416
+ 2011,TUNISIA,7096,12,2940,3075,959,110,0.66,210
417
+ 2011,TURKEY,87494,35570,20323,22977,8623,0,1.19,1099
418
+ 2011,TURKMENISTAN,17035,0,4845,11925,265,0,3.34,410
419
+ 2011,TURKS AND CAICOS ISLANDS,52,0,52,0,0,0,1.64,0
420
+ 2011,TUVALU,2,0,2,0,0,0,0.0,0
421
+ 2011,UGANDA,1163,0,936,0,227,0,0.03,77
422
+ 2011,UKRAINE,78100,37928,9479,29262,1430,0,1.72,205
423
+ 2011,UNITED ARAB EMIRATES,45116,516,6109,35527,2448,516,5.17,18713
424
+ 2011,UNITED KINGDOM,122124,31296,45006,44043,1160,618,1.93,11977
425
+ 2011,UNITED REPUBLIC OF TANZANIA,2207,59,1376,444,328,1,0.05,139
426
+ 2011,UNITED STATES OF AMERICA,1442509,498720,575746,355630,9335,3079,4.56,40600
427
+ 2011,URUGUAY,2117,1,1943,40,132,0,0.63,401
428
+ 2011,UZBEKISTAN,31002,1478,2649,25964,911,0,1.1,0
429
+ 2011,VANUATU,36,0,36,0,0,0,0.15,9
430
+ 2011,VENEZUELA,48220,212,25860,16219,1055,4874,1.64,857
431
+ 2011,VIET NAM,41497,16253,12876,4443,7925,0,0.46,660
432
+ 2011,WALLIS AND FUTUNA ISLANDS,7,0,7,0,0,0,0.5,1
433
+ 2011,YEMEN,5363,126,4752,355,129,0,0.22,134
434
+ 2011,ZAMBIA,801,73,562,0,167,0,0.06,28
435
+ 2011,ZIMBABWE,2608,1584,888,0,136,0,0.18,8
436
+ 2012,AFGHANISTAN,2933,1000,1844,84,5,0,0.1,9
437
+ 2012,ALBANIA,1339,171,861,8,299,0,0.46,7
438
+ 2012,ALGERIA,35448,283,13248,17499,2584,1835,0.95,658
439
+ 2012,ANDORRA,133,0,133,0,0,0,1.68,0
440
+ 2012,ANGOLA,9108,0,4691,388,218,3811,0.4,470
441
+ 2012,ANGUILLA,39,0,39,0,0,0,2.73,0
442
+ 2012,ANTIGUA & BARBUDA,143,0,143,0,0,0,1.61,42
443
+ 2012,ARGENTINA,52456,1180,23363,26032,1457,424,1.25,2068
444
+ 2012,ARMENIA,1553,2,244,1246,60,0,0.52,40
445
+ 2012,ARUBA,368,0,368,0,0,0,3.59,79
446
+ 2012,AUSTRALIA,105843,53298,33410,17843,1156,136,4.62,3433
447
+ 2012,AUSTRIA,16982,3342,8458,4576,606,0,2.01,581
448
+ 2012,AZERBAIJAN,9696,4,3220,5413,267,792,1.04,391
449
+ 2012,BAHAMAS,537,1,536,0,0,0,1.44,192
450
+ 2012,BAHRAIN,7274,0,432,6658,184,0,5.45,481
451
+ 2012,BANGLADESH,18409,934,4015,11385,2074,0,0.12,343
452
+ 2012,BARBADOS,401,0,367,10,24,1,1.43,97
453
+ 2012,BELARUS,17241,803,5193,10579,667,0,1.82,0
454
+ 2012,BELGIUM,25936,3205,12904,8973,854,0,2.34,6507
455
+ 2012,BELIZE,130,0,128,2,0,0,0.39,9
456
+ 2012,BENIN,1492,0,1303,0,189,0,0.15,137
457
+ 2012,BERMUDA,130,0,130,0,0,0,2.05,18
458
+ 2012,BHUTAN,223,38,114,0,71,0,0.3,2
459
+ 2012,"BONAIRE, SAINT EUSTATIUS, AND SABA",85,0,85,0,0,0,3.72,185
460
+ 2012,BOSNIA & HERZEGOVINA,6070,4704,1121,131,115,0,1.59,4
461
+ 2012,BOTSWANA,1154,355,749,0,50,0,0.54,10
462
+ 2012,BRAZIL,128178,17165,84409,16328,9428,848,0.63,5168
463
+ 2012,BRITISH VIRGIN ISLANDS,48,0,48,0,0,0,1.67,0
464
+ 2012,BRUNEI (DARUSSALAM),2636,0,564,1942,45,86,6.5,125
465
+ 2012,BULGARIA,12192,7479,2979,1531,203,0,1.67,191
466
+ 2012,BURKINA FASO,717,0,627,0,90,0,0.04,37
467
+ 2012,BURUNDI,77,8,59,0,10,0,0.01,3
468
+ 2012,CAMBODIA,1488,11,1344,0,133,0,0.1,47
469
+ 2012,CANADA,141112,20803,65652,51994,1695,968,4.05,1171
470
+ 2012,CAPE VERDE,138,0,138,0,0,0,0.28,89
471
+ 2012,CAYMAN ISLANDS,146,0,146,0,0,0,2.53,10
472
+ 2012,CENTRAL AFRICAN REPUBLIC,80,0,80,0,0,0,0.02,28
473
+ 2012,CHAD,167,0,148,0,19,0,0.01,15
474
+ 2012,CHILE,22082,6407,12326,2677,642,29,1.27,718
475
+ 2012,CHINA (MAINLAND),2734817,2037338,321155,75764,300560,0,2.02,12701
476
+ 2012,COLOMBIA,21803,3150,10556,6250,1486,361,0.47,1188
477
+ 2012,COMOROS,39,0,39,0,0,0,0.05,3
478
+ 2012,CONGO,810,0,679,111,20,0,0.19,40
479
+ 2012,COOK ISLANDS,19,0,19,0,0,0,0.94,2
480
+ 2012,COSTA RICA,2118,63,1865,0,190,0,0.46,0
481
+ 2012,COTE D IVOIRE,2535,0,1386,891,258,0,0.12,68
482
+ 2012,CROATIA,4907,654,2452,1507,293,0,1.14,90
483
+ 2012,CUBA,9860,4,9066,542,248,0,0.87,140
484
+ 2012,CURACAO,1636,0,1636,0,0,0,10.72,1408
485
+ 2012,CYPRUS,1887,0,1747,0,140,0,1.67,394
486
+ 2012,CZECH REPUBLIC,27551,17685,5117,4282,467,0,2.61,243
487
+ 2012,DEMOCRATIC PEOPLE S REPUBLIC OF KOREA,13378,11803,691,0,884,0,0.54,0
488
+ 2012,DEMOCRATIC REPUBLIC OF THE CONGO (FORMERLY ZAIRE),655,0,599,0,56,0,0.01,119
489
+ 2012,DENMARK,9934,2553,4918,2176,245,42,1.77,1138
490
+ 2012,DJIBOUTI,141,0,141,0,0,0,0.17,87
491
+ 2012,DOMINICA,37,0,37,0,0,0,0.51,2
492
+ 2012,DOMINICAN REPUBLIC,6033,637,4249,585,562,0,0.59,409
493
+ 2012,ECUADOR,10401,0,8806,464,819,312,0.67,624
494
+ 2012,EGYPT,59195,492,25836,25360,7507,0,0.69,1001
495
+ 2012,EL SALVADOR,1817,0,1629,0,188,0,0.3,71
496
+ 2012,EQUATORIAL GUINEA,1395,0,166,933,0,297,1.8,30
497
+ 2012,ERITREA,180,0,145,0,35,0,0.04,1
498
+ 2012,ESTONIA,4806,4062,337,341,66,0,3.63,382
499
+ 2012,ETHIOPIA,2335,162,1697,0,476,0,0.03,272
500
+ 2012,FAEROE ISLANDS,161,0,161,0,0,0,3.32,27
501
+ 2012,FALKLAND ISLANDS (MALVINAS),15,3,12,0,0,0,5.21,0
502
+ 2012,FEDERATED STATES OF MICRONESIA,37,0,37,0,0,0,0.36,1
503
+ 2012,FIJI,289,0,269,0,20,0,0.33,44
504
+ 2012,FINLAND,13399,4911,6436,1877,176,0,2.47,616
505
+ 2012,FRANCE (INCLUDING MONACO),90872,11645,52933,23871,2422,0,1.43,6775
506
+ 2012,FRENCH GUIANA,161,0,147,0,14,0,0.65,33
507
+ 2012,FRENCH POLYNESIA,222,0,222,0,0,0,0.81,45
508
+ 2012,GABON,1392,0,646,193,27,527,0.86,237
509
+ 2012,GAMBIA,124,0,122,1,0,0,0.07,13
510
+ 2012,GEORGIA,2302,322,741,1029,210,0,0.56,32
511
+ 2012,GERMANY,201762,84428,69309,43608,4411,6,2.51,9060
512
+ 2012,GHANA,3239,0,2611,219,408,0,0.13,176
513
+ 2012,GIBRALTAR,126,0,126,0,0,0,4.0,3682
514
+ 2012,GREECE,21828,8760,10099,2287,681,0,1.96,2545
515
+ 2012,GREENLAND,155,0,155,0,0,0,2.75,19
516
+ 2012,GRENADA,74,0,74,0,0,0,0.7,3
517
+ 2012,GUADELOUPE,694,145,508,0,41,0,1.51,92
518
+ 2012,GUATEMALA,3265,361,2513,0,392,0,0.21,292
519
+ 2012,GUINEA,704,0,661,0,43,0,0.06,21
520
+ 2012,GUINEA BISSAU,69,0,69,0,0,0,0.04,9
521
+ 2012,GUYANA,544,0,544,0,0,0,0.72,13
522
+ 2012,HAITI,631,0,590,0,41,0,0.06,44
523
+ 2012,HONDURAS,2450,183,2033,0,235,0,0.32,43
524
+ 2012,HONG KONG SPECIAL ADMINSTRATIVE REGION OF CHINA,11842,7540,2741,1333,228,0,1.67,13123
525
+ 2012,HUNGARY,12158,2901,3771,5232,254,0,1.22,142
526
+ 2012,ICELAND,491,96,395,0,0,0,1.52,170
527
+ 2012,INDIA,550451,372453,119399,21312,36720,567,0.44,4035
528
+ 2012,INDONESIA,173733,81711,59710,21851,7120,3342,0.7,790
529
+ 2012,IRAQ,41648,0,30924,3077,1360,6287,1.26,426
530
+ 2012,IRELAND,9706,2455,4576,2513,163,0,2.08,553
531
+ 2012,ISLAMIC REPUBLIC OF IRAN,166828,1126,66900,79769,9554,9479,2.19,2643
532
+ 2012,ISRAEL,20597,8891,9592,1314,801,0,2.68,950
533
+ 2012,ITALY (INCLUDING SAN MARINO),100755,16819,42046,38321,3569,0,1.69,4779
534
+ 2012,JAMAICA,2035,53,1880,0,103,0,0.74,209
535
+ 2012,JAPAN,335470,115977,146258,65791,7444,0,2.64,8600
536
+ 2012,JORDAN,6666,0,5703,412,552,0,0.95,126
537
+ 2012,KAZAKHSTAN,66259,39243,8834,17223,959,0,3.94,168
538
+ 2012,KENYA,3413,248,2534,0,631,0,0.08,585
539
+ 2012,KIRIBATI,17,0,17,0,0,0,0.16,3
540
+ 2012,KUWAIT,27907,0,17982,9479,326,119,8.16,1629
541
+ 2012,KYRGYZSTAN,2763,1096,1275,223,169,0,0.49,26
542
+ 2012,LAO PEOPLE S DEMOCRATIC REPUBLIC,463,142,116,0,204,0,0.07,9
543
+ 2012,LATVIA,1926,95,951,756,123,0,0.95,307
544
+ 2012,LEBANON,6172,171,5279,0,722,0,1.25,203
545
+ 2012,LESOTHO,656,492,163,0,0,0,0.32,0
546
+ 2012,LIBERIA,280,0,263,0,17,0,0.07,18
547
+ 2012,LIBYAN ARAB JAMAHIRIYAH,14367,0,9113,2923,272,2059,2.29,484
548
+ 2012,LIECHTENSTEIN,13,0,0,13,0,0,0.36,0
549
+ 2012,LITHUANIA,3772,245,1731,1658,138,0,1.25,159
550
+ 2012,LUXEMBOURG,2908,56,2036,656,160,0,5.46,309
551
+ 2012,MACAU SPECIAL ADMINSTRATIVE REGION OF CHINA,358,0,358,0,0,0,0.64,0
552
+ 2012,MACEDONIA,2445,1508,773,71,93,0,1.18,7
553
+ 2012,MADAGASCAR,738,190,517,0,31,0,0.03,70
554
+ 2012,MALAWI,299,59,217,0,23,0,0.02,6
555
+ 2012,MALAYSIA,59642,16340,20544,18092,2955,1712,2.06,1509
556
+ 2012,MALDIVES,303,0,303,0,0,0,0.88,101
557
+ 2012,MALI,271,0,271,0,0,0,0.02,19
558
+ 2012,MALTA,731,0,731,0,0,0,1.76,1129
559
+ 2012,MARSHALL ISLANDS,28,0,28,0,0,0,0.52,0
560
+ 2012,MARTINIQUE,604,0,584,0,20,0,1.53,119
561
+ 2012,MAURITANIA,724,0,636,0,88,0,0.19,20
562
+ 2012,MAURITIUS,1082,433,649,0,0,0,0.86,321
563
+ 2012,MEXICO,135349,13434,79191,37043,4921,759,1.11,3115
564
+ 2012,MONGOLIA,7152,6156,949,0,47,0,2.55,0
565
+ 2012,MONTENEGRO,637,411,226,0,0,0,1.02,10
566
+ 2012,MONTSERRAT,12,0,12,0,0,0,2.33,1
567
+ 2012,MOROCCO,17107,3991,10251,651,2213,0,0.51,800
568
+ 2012,MOZAMBIQUE,851,11,632,47,161,0,0.03,56
569
+ 2012,MYANMAR (FORMERLY BURMA),3019,301,1613,976,125,3,0.06,31
570
+ 2012,NAMIBIA,923,75,779,0,68,0,0.4,33
571
+ 2012,NAURU,11,0,11,0,0,0,1.08,4
572
+ 2012,NEPAL,1597,227,1001,0,370,0,0.06,80
573
+ 2012,NETHERLANDS,46444,8227,17457,20457,280,23,2.77,14710
574
+ 2012,NEW CALEDONIA,990,345,628,0,17,0,3.91,27
575
+ 2012,NEW ZEALAND,9313,1756,4941,2398,155,63,2.1,918
576
+ 2012,NICARAGUA,1260,0,1176,0,84,0,0.21,18
577
+ 2012,NIGER,509,105,394,0,10,0,0.03,10
578
+ 2012,NIGERIA,26862,35,9851,7880,2176,6920,0.16,492
579
+ 2012,NIUE,2,0,2,0,0,0,1.04,0
580
+ 2012,NORWAY,13605,847,9403,2872,226,257,2.71,617
581
+ 2012,OCCUPIED PALESTINIAN TERRITORY,600,0,600,0,0,0,0.14,0
582
+ 2012,OMAN,16133,0,3394,11363,694,681,4.55,1029
583
+ 2012,PAKISTAN,44586,4011,17409,19086,4080,0,0.25,237
584
+ 2012,PALAU,69,0,69,0,0,0,3.31,15
585
+ 2012,PANAMA,2758,340,2104,0,314,0,0.74,3349
586
+ 2012,PAPUA NEW GUINEA,1385,0,1287,71,27,0,0.19,50
587
+ 2012,PARAGUAY,1441,1,1330,0,109,0,0.23,23
588
+ 2012,PERU,15018,704,7013,3533,1374,2394,0.5,750
589
+ 2012,PHILIPPINES,24872,8855,11449,1996,2571,0,0.26,1099
590
+ 2012,PLURINATIONAL STATE OF BOLIVIA,5125,0,2796,1919,369,42,0.5,36
591
+ 2012,POLAND,81792,53724,17353,8544,2165,6,2.12,573
592
+ 2012,PORTUGAL,12548,3036,6500,2456,556,0,1.19,1306
593
+ 2012,QATAR,25668,0,2261,22289,748,369,12.73,1536
594
+ 2012,REPUBLIC OF CAMEROON,1671,0,1359,139,173,0,0.08,101
595
+ 2012,REPUBLIC OF KOREA,159249,79765,45017,28093,6373,0,3.21,10420
596
+ 2012,REPUBLIC OF MOLDOVA,1343,113,569,498,163,0,0.33,19
597
+ 2012,REPUBLIC OF SOUTH SUDAN,363,0,363,0,0,0,0.03,27
598
+ 2012,REPUBLIC OF SUDAN,3993,0,3516,0,477,0,0.11,203
599
+ 2012,REUNION,1159,513,598,0,48,0,1.37,54
600
+ 2012,ROMANIA,22286,8141,6295,6731,1118,0,1.12,110
601
+ 2012,RUSSIAN FEDERATION,499272,124583,115878,241786,8391,8635,3.48,7034
602
+ 2012,RWANDA,201,0,187,0,14,0,0.02,17
603
+ 2012,SAINT HELENA,3,0,3,0,0,0,0.82,0
604
+ 2012,SAINT LUCIA,111,0,111,0,0,0,0.61,5
605
+ 2012,SAINT MARTIN (DUTCH PORTION),190,0,190,0,0,0,5.41,201
606
+ 2012,SAMOA,54,0,54,0,0,0,0.28,9
607
+ 2012,SAO TOME & PRINCIPE,31,0,31,0,0,0,0.17,9
608
+ 2012,SAUDI ARABIA,154034,0,105409,41372,7253,0,5.22,4671
609
+ 2012,SENEGAL,2158,223,1282,15,638,0,0.16,229
610
+ 2012,SERBIA,12016,8219,2427,1048,322,0,1.34,35
611
+ 2012,SEYCHELLES,120,0,120,0,0,0,1.27,162
612
+ 2012,SIERRA LEONE,281,0,235,0,46,0,0.05,7
613
+ 2012,SINGAPORE,9919,29,4955,4935,0,0,1.87,41967
614
+ 2012,SLOVAKIA,8935,3660,2146,2726,396,7,1.65,31
615
+ 2012,SLOVENIA,4031,1514,1943,444,130,0,1.95,63
616
+ 2012,SOLOMON ISLANDS,54,0,54,0,0,0,0.1,4
617
+ 2012,SOMALIA,166,0,166,0,0,0,0.02,57
618
+ 2012,SOUTH AFRICA,127835,108478,15265,2521,1572,0,2.42,3737
619
+ 2012,SPAIN,72206,15896,36295,17847,2168,0,1.55,10375
620
+ 2012,SRI LANKA,4372,524,3576,0,273,0,0.21,563
621
+ 2012,ST. KITTS-NEVIS,60,0,60,0,0,0,1.12,4
622
+ 2012,ST. PIERRE & MIQUELON,19,0,19,0,0,0,3.07,5
623
+ 2012,ST. VINCENT & THE GRENADINES,69,0,69,0,0,0,0.63,0
624
+ 2012,SURINAME,616,0,597,2,16,1,1.17,68
625
+ 2012,SWAZILAND,329,142,188,0,0,0,0.27,1
626
+ 2012,SWEDEN,12830,2265,9645,629,291,0,1.34,2071
627
+ 2012,SWITZERLAND,10301,126,7730,1828,617,0,1.28,1283
628
+ 2012,SYRIAN ARAB REPUBLIC,12198,1,7909,3265,816,208,0.61,437
629
+ 2012,TAIWAN,70393,41269,18701,8273,2150,0,3.02,2774
630
+ 2012,TAJIKISTAN,800,192,501,74,34,0,0.1,28
631
+ 2012,THAILAND,80883,17871,35652,23041,4319,0,1.2,2857
632
+ 2012,TIMOR-LESTE (FORMERLY EAST TIMOR),80,0,80,0,0,0,0.07,3
633
+ 2012,TOGO,678,0,451,9,218,0,0.1,73
634
+ 2012,TONGA,29,0,29,0,0,0,0.28,3
635
+ 2012,TRINIDAD AND TOBAGO,12386,0,1222,11075,89,0,9.23,536
636
+ 2012,TUNISIA,7364,0,2954,3318,985,107,0.68,251
637
+ 2012,TURKEY,89872,36927,20984,23273,8688,0,1.2,1017
638
+ 2012,TURKMENISTAN,17691,0,5070,12300,322,0,3.42,355
639
+ 2012,TURKS AND CAICOS ISLANDS,54,0,54,0,0,0,1.68,0
640
+ 2012,TUVALU,3,0,3,0,0,0,0.0,0
641
+ 2012,UGANDA,1110,0,868,0,242,0,0.03,79
642
+ 2012,UKRAINE,80663,43570,8877,26876,1339,0,1.78,255
643
+ 2012,UNITED ARAB EMIRATES,48101,1540,7740,36191,2094,535,5.37,19340
644
+ 2012,UNITED KINGDOM,127781,39717,44872,41549,1081,563,2.01,11295
645
+ 2012,UNITED REPUBLIC OF TANZANIA,2603,57,1686,507,351,1,0.05,149
646
+ 2012,UNITED STATES OF AMERICA,1396083,443904,566582,372277,10191,3129,4.38,29859
647
+ 2012,URUGUAY,2371,2,2220,29,119,0,0.7,321
648
+ 2012,UZBEKISTAN,31583,1493,2352,26813,925,0,1.1,0
649
+ 2012,VANUATU,31,0,31,0,0,0,0.13,9
650
+ 2012,VENEZUELA,54204,218,30075,16851,1103,5957,1.82,1280
651
+ 2012,VIET NAM,38784,14265,12066,4901,7552,0,0.43,693
652
+ 2012,WALLIS AND FUTUNA ISLANDS,7,0,7,0,0,0,0.5,1
653
+ 2012,YEMEN,5091,129,4173,414,375,0,0.2,111
654
+ 2012,ZAMBIA,1000,95,690,0,215,0,0.07,43
655
+ 2012,ZIMBABWE,2125,917,1006,0,201,0,0.15,9
656
+ 2013,AFGHANISTAN,2731,1075,1568,81,7,0,0.09,9
657
+ 2013,ALBANIA,1381,150,909,9,313,0,0.48,24
658
+ 2013,ALGERIA,36669,198,14170,17863,2516,1922,0.96,687
659
+ 2013,ANDORRA,130,0,130,0,0,0,1.71,0
660
+ 2013,ANGOLA,8895,0,4738,209,272,3675,0.38,374
661
+ 2013,ANGUILLA,37,0,37,0,0,0,2.58,0
662
+ 2013,ANTIGUA & BARBUDA,143,0,143,0,0,0,1.59,42
663
+ 2013,ARGENTINA,51773,649,24226,24771,1617,510,1.22,2253
664
+ 2013,ARMENIA,1499,1,232,1207,59,0,0.5,39
665
+ 2013,ARUBA,235,0,235,0,0,0,2.29,80
666
+ 2013,AUSTRALIA,101518,47663,33655,18902,1142,155,4.36,3445
667
+ 2013,AUSTRIA,17040,3402,8632,4410,596,0,2.01,555
668
+ 2013,AZERBAIJAN,9720,3,3293,5436,312,675,1.02,393
669
+ 2013,BAHAMAS,764,1,763,0,0,0,2.02,167
670
+ 2013,BAHRAIN,8539,0,1211,7145,184,0,6.33,344
671
+ 2013,BANGLADESH,19010,1023,3866,11839,2282,0,0.12,352
672
+ 2013,BARBADOS,395,0,360,12,22,1,1.4,109
673
+ 2013,BELARUS,17390,858,5170,10675,688,0,1.83,86
674
+ 2013,BELGIUM,26444,3291,13330,8991,832,0,2.37,6542
675
+ 2013,BELIZE,140,0,138,2,0,0,0.41,12
676
+ 2013,BENIN,1585,0,1392,0,193,0,0.15,146
677
+ 2013,BERMUDA,125,0,125,0,0,0,1.99,18
678
+ 2013,BHUTAN,251,53,120,0,78,0,0.33,3
679
+ 2013,"BONAIRE, SAINT EUSTATIUS, AND SABA",88,0,88,0,0,0,3.71,190
680
+ 2013,BOSNIA & HERZEGOVINA,5978,4663,1093,102,120,0,1.56,3
681
+ 2013,BOTSWANA,1426,589,787,0,50,0,0.66,11
682
+ 2013,BRAZIL,137354,18773,88898,19399,9517,767,0.67,4895
683
+ 2013,BRITISH VIRGIN ISLANDS,48,0,48,0,0,0,1.64,0
684
+ 2013,BRUNEI (DARUSSALAM),2128,0,452,1535,46,95,5.17,139
685
+ 2013,BULGARIA,10799,6326,2729,1498,246,0,1.49,210
686
+ 2013,BURKINA FASO,834,0,755,0,79,0,0.05,47
687
+ 2013,BURUNDI,79,6,59,0,14,0,0.01,3
688
+ 2013,CAMBODIA,1528,49,1335,0,144,0,0.1,54
689
+ 2013,CANADA,141031,18778,65850,53841,1579,983,4.0,1048
690
+ 2013,CAPE VERDE,136,0,136,0,0,0,0.27,86
691
+ 2013,CAYMAN ISLANDS,146,0,146,0,0,0,2.5,9
692
+ 2013,CENTRAL AFRICAN REPUBLIC,81,0,81,0,0,0,0.02,28
693
+ 2013,CHAD,191,0,167,0,24,0,0.01,15
694
+ 2013,CHILE,22696,6931,12531,2536,664,33,1.29,689
695
+ 2013,CHINA (MAINLAND),2797384,2045156,336960,87371,327896,0,2.05,12057
696
+ 2013,COLOMBIA,24441,3581,11564,6306,1530,1459,0.52,1547
697
+ 2013,COMOROS,48,0,48,0,0,0,0.06,3
698
+ 2013,CONGO,842,0,693,115,34,0,0.19,37
699
+ 2013,COOK ISLANDS,19,0,19,0,0,0,0.93,2
700
+ 2013,COSTA RICA,2072,63,1809,0,199,0,0.44,133
701
+ 2013,COTE D IVOIRE,2914,0,1578,1023,313,0,0.13,62
702
+ 2013,CROATIA,4786,699,2344,1425,317,0,1.12,98
703
+ 2013,CUBA,9490,10,8696,558,226,0,0.84,203
704
+ 2013,CURACAO,1422,0,1422,0,0,0,9.21,1421
705
+ 2013,CYPRUS,1622,0,1505,0,116,0,1.42,406
706
+ 2013,CZECH REPUBLIC,26909,17124,5010,4339,437,0,2.55,234
707
+ 2013,DEMOCRATIC PEOPLE S REPUBLIC OF KOREA,9820,8108,746,0,966,0,0.39,0
708
+ 2013,DEMOCRATIC REPUBLIC OF THE CONGO (FORMERLY ZAIRE),979,0,918,0,61,0,0.01,129
709
+ 2013,DENMARK,10508,3248,4884,2071,249,56,1.87,1230
710
+ 2013,DJIBOUTI,166,0,146,0,20,0,0.19,92
711
+ 2013,DOMINICA,36,0,36,0,0,0,0.5,2
712
+ 2013,DOMINICAN REPUBLIC,5847,604,4136,530,577,0,0.57,371
713
+ 2013,ECUADOR,11180,0,9454,539,907,280,0.71,634
714
+ 2013,EGYPT,58198,224,26501,24672,6800,0,0.66,694
715
+ 2013,EL SALVADOR,1699,0,1536,0,163,0,0.28,123
716
+ 2013,EQUATORIAL GUINEA,1408,0,166,823,0,420,1.77,30
717
+ 2013,ERITREA,182,0,147,0,35,0,0.04,1
718
+ 2013,ESTONIA,5425,4736,280,347,62,0,4.11,393
719
+ 2013,ETHIOPIA,2900,211,2009,0,680,0,0.03,299
720
+ 2013,FAEROE ISLANDS,185,0,185,0,0,0,3.83,20
721
+ 2013,FALKLAND ISLANDS (MALVINAS),15,3,12,0,0,0,5.18,0
722
+ 2013,FEDERATED STATES OF MICRONESIA,39,0,39,0,0,0,0.37,1
723
+ 2013,FIJI,314,0,289,0,25,0,0.36,48
724
+ 2013,FINLAND,12877,5478,5437,1784,177,0,2.36,639
725
+ 2013,FRANCE (INCLUDING MONACO),91109,12683,51614,24363,2450,0,1.43,6547
726
+ 2013,FRENCH GUIANA,172,0,159,0,13,0,0.68,33
727
+ 2013,FRENCH POLYNESIA,224,0,224,0,0,0,0.81,46
728
+ 2013,GABON,1440,0,738,158,23,522,0.87,222
729
+ 2013,GAMBIA,118,0,116,1,0,0,0.06,18
730
+ 2013,GEORGIA,2143,331,726,867,220,0,0.52,73
731
+ 2013,GERMANY,206521,86226,70373,45658,4258,5,2.56,8982
732
+ 2013,GHANA,3987,0,3415,164,408,0,0.15,153
733
+ 2013,GIBRALTAR,134,0,134,0,0,0,4.22,3370
734
+ 2013,GREECE,18948,7517,8594,2021,815,0,1.71,2443
735
+ 2013,GREENLAND,151,0,151,0,0,0,2.68,14
736
+ 2013,GRENADA,83,0,83,0,0,0,0.78,3
737
+ 2013,GUADELOUPE,697,145,511,0,41,0,1.5,92
738
+ 2013,GUATEMALA,3718,361,2954,0,404,0,0.24,310
739
+ 2013,GUINEA,627,0,576,0,51,0,0.05,21
740
+ 2013,GUINEA BISSAU,70,0,70,0,0,0,0.04,9
741
+ 2013,GUYANA,528,0,528,0,0,0,0.69,9
742
+ 2013,HAITI,656,0,615,0,41,0,0.06,76
743
+ 2013,HONDURAS,2472,186,2055,0,231,0,0.31,36
744
+ 2013,HONG KONG SPECIAL ADMINSTRATIVE REGION OF CHINA,12273,8037,2698,1298,240,0,1.71,13498
745
+ 2013,HUNGARY,11492,2547,3923,4747,275,0,1.16,139
746
+ 2013,ICELAND,518,101,417,0,0,0,1.59,156
747
+ 2013,INDIA,554882,362676,125763,27784,38080,579,0.43,4405
748
+ 2013,INDONESIA,133686,39375,65400,17673,7710,3528,0.53,1068
749
+ 2013,IRAQ,45134,0,33411,3564,1632,6527,1.32,491
750
+ 2013,IRELAND,9505,2132,4705,2395,272,0,2.03,631
751
+ 2013,ISLAMIC REPUBLIC OF IRAN,169015,1160,68466,80495,9343,9550,2.19,3665
752
+ 2013,ISRAEL,18290,7281,6554,3585,870,0,2.34,1130
753
+ 2013,ITALY (INCLUDING SAN MARINO),94169,14007,41178,35842,3142,0,1.57,4440
754
+ 2013,JAMAICA,2207,64,2030,0,112,0,0.8,195
755
+ 2013,JAPAN,339928,125408,140230,66407,7883,0,2.68,8631
756
+ 2013,JORDAN,6651,322,5248,510,571,0,0.92,121
757
+ 2013,KAZAKHSTAN,71679,38840,12964,18914,962,0,4.19,140
758
+ 2013,KENYA,3636,274,2673,0,688,0,0.08,495
759
+ 2013,KIRIBATI,17,0,17,0,0,0,0.15,3
760
+ 2013,KUWAIT,26819,0,16863,9434,408,114,7.46,1599
761
+ 2013,KYRGYZSTAN,2684,976,1309,171,228,0,0.47,41
762
+ 2013,LAO PEOPLE S DEMOCRATIC REPUBLIC,430,105,121,0,204,0,0.07,9
763
+ 2013,LATVIA,1931,82,960,752,136,0,0.96,310
764
+ 2013,LEBANON,6158,137,5228,0,793,0,1.16,247
765
+ 2013,LESOTHO,664,500,164,0,0,0,0.32,0
766
+ 2013,LIBERIA,261,0,235,0,26,0,0.06,18
767
+ 2013,LIBYAN ARAB JAMAHIRIYAH,15344,0,9745,3622,272,1705,2.45,339
768
+ 2013,LIECHTENSTEIN,14,0,0,14,0,0,0.37,0
769
+ 2013,LITHUANIA,3447,280,1669,1352,146,0,1.16,135
770
+ 2013,LUXEMBOURG,2741,49,2004,556,133,0,5.03,310
771
+ 2013,MACAU SPECIAL ADMINSTRATIVE REGION OF CHINA,322,0,322,0,0,0,0.57,0
772
+ 2013,MACEDONIA,2140,1244,711,81,104,0,1.03,9
773
+ 2013,MADAGASCAR,850,308,511,0,31,0,0.04,60
774
+ 2013,MALAWI,334,60,229,0,44,0,0.02,6
775
+ 2013,MALAYSIA,64497,15827,23656,20556,2918,1540,2.19,2286
776
+ 2013,MALDIVES,298,0,298,0,0,0,0.85,125
777
+ 2013,MALI,280,0,280,0,0,0,0.02,20
778
+ 2013,MALTA,638,0,638,0,0,0,1.53,1129
779
+ 2013,MARSHALL ISLANDS,28,0,28,0,0,0,0.54,0
780
+ 2013,MARTINIQUE,603,0,583,0,20,0,1.52,119
781
+ 2013,MAURITANIA,728,0,634,0,94,0,0.19,25
782
+ 2013,MAURITIUS,1110,456,654,0,0,0,0.88,330
783
+ 2013,MEXICO,133717,13640,75790,38831,4707,749,1.08,3124
784
+ 2013,MONGOLIA,10568,9531,1002,0,35,0,3.7,0
785
+ 2013,MONTENEGRO,613,397,217,0,0,0,0.98,11
786
+ 2013,MONTSERRAT,14,0,14,0,0,0,2.81,1
787
+ 2013,MOROCCO,16112,3104,10067,646,2294,0,0.47,610
788
+ 2013,MOZAMBIQUE,1096,10,811,97,177,0,0.04,60
789
+ 2013,MYANMAR (FORMERLY BURMA),3507,352,1853,1147,152,3,0.07,33
790
+ 2013,NAMIBIA,717,29,598,0,90,0,0.31,17
791
+ 2013,NAURU,12,0,12,0,0,0,1.16,4
792
+ 2013,NEPAL,1810,284,1119,0,407,0,0.07,80
793
+ 2013,NETHERLANDS,47247,8088,18056,20810,272,20,2.81,14274
794
+ 2013,NEW CALEDONIA,1157,366,775,0,16,0,4.51,11
795
+ 2013,NEW ZEALAND,9124,1545,4898,2486,158,38,2.04,953
796
+ 2013,NICARAGUA,1241,0,1153,0,88,0,0.21,17
797
+ 2013,NIGER,529,93,432,0,4,0,0.03,19
798
+ 2013,NIGERIA,26762,32,9838,7814,2720,6359,0.15,607
799
+ 2013,NIUE,2,0,2,0,0,0,1.04,0
800
+ 2013,NORWAY,15861,802,10960,3582,231,286,3.12,717
801
+ 2013,OCCUPIED PALESTINIAN TERRITORY,665,0,665,0,0,0,0.15,0
802
+ 2013,OMAN,16738,0,2870,12455,608,806,4.28,1075
803
+ 2013,PAKISTAN,44812,3728,18982,17886,4216,0,0.25,252
804
+ 2013,PALAU,70,0,70,0,0,0,3.36,15
805
+ 2013,PANAMA,2923,351,2250,0,322,0,0.77,3268
806
+ 2013,PAPUA NEW GUINEA,1687,0,1588,71,27,0,0.23,54
807
+ 2013,PARAGUAY,1482,0,1351,0,131,0,0.23,27
808
+ 2013,PERU,15586,784,7097,3238,1432,3036,0.51,617
809
+ 2013,PHILIPPINES,26760,10924,11257,1839,2740,0,0.27,1096
810
+ 2013,PLURINATIONAL STATE OF BOLIVIA,5159,0,2752,1934,422,51,0.5,44
811
+ 2013,POLAND,82432,56336,15528,8579,1977,11,2.13,558
812
+ 2013,PORTUGAL,12388,2741,6621,2346,680,0,1.18,1349
813
+ 2013,QATAR,23186,0,3215,18855,726,389,11.03,1700
814
+ 2013,REPUBLIC OF CAMEROON,1847,0,1417,239,190,0,0.08,106
815
+ 2013,REPUBLIC OF KOREA,161576,80733,44671,29741,6432,0,3.24,10442
816
+ 2013,REPUBLIC OF MOLDOVA,1363,151,586,470,156,0,0.33,18
817
+ 2013,REPUBLIC OF SOUTH SUDAN,395,0,395,0,0,0,0.03,31
818
+ 2013,REPUBLIC OF SUDAN,4220,0,3739,0,481,0,0.11,180
819
+ 2013,REUNION,1118,492,572,0,54,0,1.32,47
820
+ 2013,ROMANIA,19347,6153,6036,6145,1013,0,0.98,156
821
+ 2013,RUSSIAN FEDERATION,485018,114984,105329,246808,9044,8853,3.38,9524
822
+ 2013,RWANDA,219,0,203,0,15,0,0.02,16
823
+ 2013,SAINT HELENA,3,0,3,0,0,0,0.83,0
824
+ 2013,SAINT LUCIA,111,0,111,0,0,0,0.61,5
825
+ 2013,SAINT MARTIN (DUTCH PORTION),195,0,195,0,0,0,5.35,203
826
+ 2013,SAMOA,54,0,54,0,0,0,0.28,9
827
+ 2013,SAO TOME & PRINCIPE,31,0,31,0,0,0,0.17,9
828
+ 2013,SAUDI ARABIA,147545,0,98085,41812,7648,0,4.89,4526
829
+ 2013,SENEGAL,2297,224,1346,20,706,0,0.16,271
830
+ 2013,SERBIA,12240,8539,2242,1166,293,0,1.37,44
831
+ 2013,SEYCHELLES,110,0,110,0,0,0,1.15,158
832
+ 2013,SIERRA LEONE,325,0,282,0,43,0,0.05,7
833
+ 2013,SINGAPORE,15183,308,9324,5550,0,0,2.81,42215
834
+ 2013,SLOVAKIA,9024,3657,2090,2847,424,7,1.67,34
835
+ 2013,SLOVENIA,3859,1441,1831,432,155,0,1.87,74
836
+ 2013,SOLOMON ISLANDS,55,0,55,0,0,0,0.1,4
837
+ 2013,SOMALIA,166,0,166,0,0,0,0.02,57
838
+ 2013,SOUTH AFRICA,127182,106634,16337,2556,1655,0,2.38,3624
839
+ 2013,SPAIN,64640,11355,35077,16341,1868,0,1.39,9324
840
+ 2013,SRI LANKA,4224,551,3411,0,262,0,0.21,524
841
+ 2013,ST. KITTS-NEVIS,61,0,61,0,0,0,1.13,4
842
+ 2013,ST. PIERRE & MIQUELON,20,0,20,0,0,0,3.2,5
843
+ 2013,ST. VINCENT & THE GRENADINES,57,0,57,0,0,0,0.52,0
844
+ 2013,SURINAME,523,0,502,2,18,1,0.98,60
845
+ 2013,SWAZILAND,297,106,191,0,0,0,0.24,1
846
+ 2013,SWEDEN,12230,2298,8988,597,348,0,1.27,2064
847
+ 2013,SWITZERLAND,10970,128,8299,1925,618,0,1.35,1288
848
+ 2013,SYRIAN ARAB REPUBLIC,9937,1,6431,2683,544,279,0.51,403
849
+ 2013,TAIWAN,71022,41957,18614,8201,2251,0,3.04,2917
850
+ 2013,TAJIKISTAN,949,239,500,158,52,0,0.12,30
851
+ 2013,THAILAND,81835,18073,35244,23641,4876,0,1.21,3772
852
+ 2013,TIMOR-LESTE (FORMERLY EAST TIMOR),120,0,120,0,0,0,0.11,3
853
+ 2013,TOGO,725,0,470,11,244,0,0.1,77
854
+ 2013,TONGA,31,0,31,0,0,0,0.29,1
855
+ 2013,TRINIDAD AND TOBAGO,12692,0,1374,11209,109,0,9.41,709
856
+ 2013,TUNISIA,7545,0,3108,3309,1021,107,0.69,251
857
+ 2013,TURKEY,88566,34281,21125,23456,9702,1,1.16,1908
858
+ 2013,TURKMENISTAN,18199,0,5211,12628,360,0,3.47,389
859
+ 2013,TURKS AND CAICOS ISLANDS,54,0,54,0,0,0,1.64,0
860
+ 2013,TUVALU,3,0,3,0,0,0,0.0,0
861
+ 2013,UGANDA,1328,125,929,0,275,0,0.04,79
862
+ 2013,UKRAINE,74141,40630,7527,24643,1341,0,1.64,105
863
+ 2013,UNITED ARAB EMIRATES,46552,1947,4708,37226,2135,536,5.15,21260
864
+ 2013,UNITED KINGDOM,124966,38543,43698,41024,1116,586,1.95,11111
865
+ 2013,UNITED REPUBLIC OF TANZANIA,3048,62,2157,510,319,1,0.06,159
866
+ 2013,UNITED STATES OF AMERICA,1406916,450641,562260,379659,10528,3828,4.38,31592
867
+ 2013,URUGUAY,2069,2,1924,27,116,0,0.61,257
868
+ 2013,UZBEKISTAN,28185,1552,2216,23466,951,0,0.97,0
869
+ 2013,VANUATU,29,0,29,0,0,0,0.12,9
870
+ 2013,VENEZUELA,50156,217,28343,13240,1151,7205,1.66,1272
871
+ 2013,VIET NAM,40150,15359,11860,5109,7822,0,0.44,752
872
+ 2013,WALLIS AND FUTUNA ISLANDS,6,0,6,0,0,0,0.44,1
873
+ 2013,YEMEN,6953,134,5811,560,449,0,0.27,166
874
+ 2013,ZAMBIA,1079,125,708,0,246,0,0.07,43
875
+ 2013,ZIMBABWE,3184,1902,1119,0,162,0,0.21,9
876
+ 2014,AFGHANISTAN,2675,1194,1393,74,14,0,0.08,9
877
+ 2014,ALBANIA,1559,191,1053,16,299,0,0.54,23
878
+ 2014,ALGERIA,39651,149,14422,20151,2856,2073,1.02,581
879
+ 2014,ANDORRA,126,0,126,0,0,0,1.74,0
880
+ 2014,ANGOLA,9480,0,5310,158,340,3672,0.39,509
881
+ 2014,ANGUILLA,39,0,39,0,0,0,2.66,0
882
+ 2014,ANTIGUA & BARBUDA,145,0,145,0,0,0,1.59,44
883
+ 2014,ARGENTINA,55638,1588,25685,26368,1551,446,1.29,2079
884
+ 2014,ARMENIA,1508,0,234,1216,58,0,0.5,34
885
+ 2014,ARUBA,238,0,238,0,0,0,2.3,80
886
+ 2014,AUSTRALIA,98517,44558,32778,19800,1224,157,4.17,3754
887
+ 2014,AUSTRIA,16011,3129,8259,4025,598,0,1.88,553
888
+ 2014,AZERBAIJAN,10223,2,3174,5782,390,876,1.06,360
889
+ 2014,BAHAMAS,659,1,657,0,0,0,1.72,162
890
+ 2014,BAHRAIN,8546,0,604,7738,204,0,6.28,338
891
+ 2014,BANGLADESH,19959,957,4154,12536,2312,0,0.13,362
892
+ 2014,BARBADOS,347,0,317,7,22,0,1.22,27
893
+ 2014,BELARUS,17316,888,5072,10592,764,0,1.82,94
894
+ 2014,BELGIUM,25457,3215,13543,7869,830,0,2.27,5889
895
+ 2014,BELIZE,135,0,134,1,0,0,0.38,10
896
+ 2014,BENIN,1723,51,1483,0,190,0,0.16,156
897
+ 2014,BERMUDA,157,0,157,0,0,0,2.51,24
898
+ 2014,BHUTAN,273,69,111,0,94,0,0.36,3
899
+ 2014,"BONAIRE, SAINT EUSTATIUS, AND SABA",88,0,88,0,0,0,3.62,190
900
+ 2014,BOSNIA & HERZEGOVINA,6063,4738,1117,95,114,0,1.59,3
901
+ 2014,BOTSWANA,1918,1049,819,0,50,0,0.86,9
902
+ 2014,BRAZIL,144480,20089,92454,21297,9691,949,0.7,4895
903
+ 2014,BRITISH VIRGIN ISLANDS,49,0,49,0,0,0,1.64,0
904
+ 2014,BRUNEI (DARUSSALAM),2484,0,461,1848,48,127,5.95,122
905
+ 2014,BULGARIA,11567,6821,3018,1476,252,0,1.61,211
906
+ 2014,BURKINA FASO,777,0,722,0,55,0,0.04,29
907
+ 2014,BURUNDI,120,4,106,0,10,0,0.01,3
908
+ 2014,CAMBODIA,1823,251,1382,0,190,0,0.12,63
909
+ 2014,CANADA,146494,20667,67717,55436,1616,1059,4.12,914
910
+ 2014,CAPE VERDE,134,0,134,0,0,0,0.26,105
911
+ 2014,CAYMAN ISLANDS,148,0,148,0,0,0,2.5,9
912
+ 2014,CENTRAL AFRICAN REPUBLIC,82,0,82,0,0,0,0.02,29
913
+ 2014,CHAD,199,0,172,0,27,0,0.01,15
914
+ 2014,CHILE,22515,6989,12610,2223,680,13,1.27,702
915
+ 2014,CHINA (MAINLAND),2806634,2026492,344725,96504,338912,0,2.05,12066
916
+ 2014,COLOMBIA,22932,3988,10856,6186,1684,218,0.48,1636
917
+ 2014,COMOROS,42,0,42,0,0,0,0.05,3
918
+ 2014,CONGO,844,0,658,123,63,0,0.19,34
919
+ 2014,COOK ISLANDS,19,0,19,0,0,0,0.93,2
920
+ 2014,COSTA RICA,2116,63,1849,0,204,0,0.44,132
921
+ 2014,COTE D IVOIRE,3012,0,1627,1032,354,0,0.14,96
922
+ 2014,CROATIA,4593,670,2343,1261,319,0,1.08,98
923
+ 2014,CUBA,9500,1,8655,629,215,0,0.83,206
924
+ 2014,CURACAO,1604,0,1604,0,0,0,10.3,1446
925
+ 2014,CYPRUS,1653,3,1551,0,100,0,1.43,397
926
+ 2014,CZECH REPUBLIC,26309,16744,5202,3861,502,0,2.5,242
927
+ 2014,DEMOCRATIC PEOPLE S REPUBLIC OF KOREA,11052,9361,712,0,979,0,0.44,0
928
+ 2014,DEMOCRATIC REPUBLIC OF THE CONGO (FORMERLY ZAIRE),1274,0,1228,1,45,0,0.02,193
929
+ 2014,DENMARK,9135,2468,4606,1757,255,50,1.62,1383
930
+ 2014,DJIBOUTI,197,0,149,0,48,0,0.22,94
931
+ 2014,DOMINICA,37,0,37,0,0,0,0.51,2
932
+ 2014,DOMINICAN REPUBLIC,5874,765,3938,518,653,0,0.56,414
933
+ 2014,ECUADOR,11977,0,10114,548,898,417,0.75,664
934
+ 2014,EGYPT,55057,408,22480,25505,6664,0,0.61,1942
935
+ 2014,EL SALVADOR,1714,0,1578,0,136,0,0.28,130
936
+ 2014,EQUATORIAL GUINEA,1458,0,166,864,0,428,1.78,30
937
+ 2014,ERITREA,190,0,149,0,41,0,0.04,1
938
+ 2014,ESTONIA,5323,4767,223,272,61,0,4.04,317
939
+ 2014,ETHIOPIA,3163,232,2197,0,734,0,0.03,330
940
+ 2014,FAEROE ISLANDS,163,0,163,0,0,0,3.39,20
941
+ 2014,FALKLAND ISLANDS (MALVINAS),15,3,12,0,0,0,5.16,0
942
+ 2014,FEDERATED STATES OF MICRONESIA,41,0,41,0,0,0,0.39,1
943
+ 2014,FIJI,319,0,293,0,26,0,0.36,56
944
+ 2014,FINLAND,12899,4677,6482,1570,170,0,2.35,602
945
+ 2014,FRANCE (INCLUDING MONACO),82704,9419,50615,20358,2312,0,1.29,6306
946
+ 2014,FRENCH GUIANA,200,0,188,0,12,0,0.76,33
947
+ 2014,FRENCH POLYNESIA,219,0,219,0,0,0,0.78,45
948
+ 2014,GABON,1416,0,749,173,23,471,0.84,211
949
+ 2014,GAMBIA,140,0,138,1,0,0,0.07,12
950
+ 2014,GEORGIA,2451,310,774,1145,221,0,0.61,68
951
+ 2014,GERMANY,196314,84098,68263,39582,4365,5,2.43,8706
952
+ 2014,GHANA,3945,0,3188,349,408,0,0.15,104
953
+ 2014,GIBRALTAR,144,0,144,0,0,0,4.5,2509
954
+ 2014,GREECE,18358,7203,8906,1552,697,0,1.67,2301
955
+ 2014,GREENLAND,138,0,138,0,0,0,2.46,15
956
+ 2014,GRENADA,66,0,66,0,0,0,0.62,4
957
+ 2014,GUADELOUPE,700,145,514,0,41,0,1.5,93
958
+ 2014,GUATEMALA,4998,521,4000,0,476,0,0.31,311
959
+ 2014,GUINEA,668,0,599,0,68,0,0.05,21
960
+ 2014,GUINEA BISSAU,74,0,74,0,0,0,0.04,10
961
+ 2014,GUYANA,548,0,548,0,0,0,0.72,8
962
+ 2014,HAITI,780,0,739,0,41,0,0.07,29
963
+ 2014,HONDURAS,2583,145,2207,0,231,0,0.32,57
964
+ 2014,HONG KONG SPECIAL ADMINSTRATIVE REGION OF CHINA,12605,8420,2659,1268,258,0,1.74,12769
965
+ 2014,HUNGARY,11477,2400,4431,4361,286,0,1.16,146
966
+ 2014,ICELAND,541,90,451,0,0,0,1.65,171
967
+ 2014,INDIA,610411,407077,140199,25278,37400,457,0.47,4396
968
+ 2014,INDONESIA,126582,33370,63677,17035,7888,4612,0.5,1356
969
+ 2014,IRAQ,45935,0,33962,3448,1768,6757,1.3,611
970
+ 2014,IRELAND,9290,2114,4580,2325,272,0,1.99,711
971
+ 2014,ISLAMIC REPUBLIC OF IRAN,177115,900,66662,91127,8976,9450,2.27,4218
972
+ 2014,ISRAEL,17617,6775,6013,3930,898,0,2.22,1011
973
+ 2014,ITALY (INCLUDING SAN MARINO),87377,13532,39265,31670,2910,0,1.46,4265
974
+ 2014,JAMAICA,2024,75,1835,0,113,0,0.73,182
975
+ 2014,JAPAN,331074,122461,133395,67342,7876,0,2.61,8123
976
+ 2014,JORDAN,7213,375,6057,169,612,0,0.97,110
977
+ 2014,KAZAKHSTAN,67716,38375,8819,19438,1085,0,3.9,193
978
+ 2014,KENYA,3896,340,2796,0,759,0,0.09,194
979
+ 2014,KIRIBATI,17,0,17,0,0,0,0.15,3
980
+ 2014,KUWAIT,26018,0,15952,9433,517,116,6.93,1585
981
+ 2014,KYRGYZSTAN,2620,1229,1016,141,235,0,0.45,3
982
+ 2014,LAO PEOPLE S DEMOCRATIC REPUBLIC,533,84,122,0,326,0,0.08,9
983
+ 2014,LATVIA,1902,62,1002,676,163,0,0.96,292
984
+ 2014,LEBANON,6564,171,5643,0,750,0,1.17,222
985
+ 2014,LESOTHO,673,507,167,0,0,0,0.32,0
986
+ 2014,LIBERIA,255,0,215,0,40,0,0.06,19
987
+ 2014,LIBYAN ARAB JAMAHIRIYAH,15543,0,9885,3031,272,2355,2.48,183
988
+ 2014,LIECHTENSTEIN,12,0,0,12,0,0,0.31,0
989
+ 2014,LITHUANIA,3501,237,1852,1289,123,0,1.2,74
990
+ 2014,LUXEMBOURG,2634,55,1903,527,150,0,4.73,337
991
+ 2014,MACAU SPECIAL ADMINSTRATIVE REGION OF CHINA,350,0,320,31,0,0,0.61,56
992
+ 2014,MACEDONIA,2048,1177,709,69,93,0,0.99,10
993
+ 2014,MADAGASCAR,839,278,527,0,33,0,0.04,64
994
+ 2014,MALAWI,348,55,232,0,61,0,0.02,6
995
+ 2014,MALAYSIA,66218,15793,24442,21399,2992,1591,2.21,2271
996
+ 2014,MALDIVES,364,0,364,0,0,0,1.02,204
997
+ 2014,MALI,385,0,385,0,0,0,0.02,20
998
+ 2014,MALTA,640,0,640,0,0,0,1.53,1166
999
+ 2014,MARSHALL ISLANDS,28,0,28,0,0,0,0.52,0
1000
+ 2014,MARTINIQUE,627,0,607,0,20,0,1.58,124
1001
+ 2014,MAURITANIA,739,0,634,0,105,0,0.19,25
1002
+ 2014,MAURITIUS,1153,474,680,0,0,0,0.91,351
1003
+ 2014,MEXICO,130971,13358,73374,37801,4760,1678,1.04,3300
1004
+ 2014,MONGOLIA,5683,4702,925,0,56,0,1.95,0
1005
+ 2014,MONTENEGRO,603,387,216,0,0,0,0.96,15
1006
+ 2014,MONTSERRAT,13,0,13,0,0,0,2.63,1
1007
+ 2014,MOROCCO,16325,4176,9384,629,2137,0,0.47,656
1008
+ 2014,MOZAMBIQUE,2298,225,1507,362,204,0,0.08,103
1009
+ 2014,MYANMAR (FORMERLY BURMA),5899,390,4008,1318,179,4,0.11,34
1010
+ 2014,NAMIBIA,1024,19,907,0,99,0,0.43,40
1011
+ 2014,NAURU,13,0,13,0,0,0,1.32,4
1012
+ 2014,NEPAL,2190,501,1267,0,422,0,0.08,119
1013
+ 2014,NETHERLANDS,45624,9070,18272,18010,272,0,2.7,14210
1014
+ 2014,NEW CALEDONIA,1170,426,729,0,14,0,4.5,9
1015
+ 2014,NEW ZEALAND,9453,1505,5014,2744,150,39,2.1,918
1016
+ 2014,NICARAGUA,1326,0,1231,0,95,0,0.22,19
1017
+ 2014,NIGER,580,98,480,0,3,0,0.03,25
1018
+ 2014,NIGERIA,26256,33,8830,9035,2720,5637,0.15,581
1019
+ 2014,NIUE,3,0,3,0,0,0,1.56,0
1020
+ 2014,NORWAY,12988,879,8542,3085,231,251,2.52,545
1021
+ 2014,OCCUPIED PALESTINIAN TERRITORY,774,0,774,0,0,0,0.17,0
1022
+ 2014,OMAN,16681,0,2904,12272,680,824,3.94,1442
1023
+ 2014,PAKISTAN,45350,3535,19726,17736,4352,0,0.25,263
1024
+ 2014,PALAU,71,0,71,0,0,0,3.37,15
1025
+ 2014,PANAMA,2400,354,1748,0,298,0,0.62,3086
1026
+ 2014,PAPUA NEW GUINEA,1723,0,1628,67,27,0,0.23,49
1027
+ 2014,PARAGUAY,1555,0,1419,0,136,0,0.24,32
1028
+ 2014,PERU,16838,780,7089,4512,1452,3005,0.54,681
1029
+ 2014,PHILIPPINES,28812,11662,12224,1934,2992,0,0.29,980
1030
+ 2014,PLURINATIONAL STATE OF BOLIVIA,5566,0,2897,2142,476,51,0.53,50
1031
+ 2014,POLAND,77922,52194,15261,8372,2089,6,2.02,613
1032
+ 2014,PORTUGAL,12286,2761,6608,2169,748,0,1.18,1359
1033
+ 2014,QATAR,29412,0,1499,26725,816,372,13.54,1072
1034
+ 2014,REPUBLIC OF CAMEROON,1910,0,1386,347,177,0,0.08,112
1035
+ 2014,REPUBLIC OF KOREA,160119,84161,42616,26942,6399,0,3.2,10570
1036
+ 2014,REPUBLIC OF MOLDOVA,1345,94,595,478,177,0,0.33,21
1037
+ 2014,REPUBLIC OF SOUTH SUDAN,408,0,408,0,0,0,0.03,32
1038
+ 2014,REPUBLIC OF SUDAN,4190,0,3717,0,473,0,0.11,226
1039
+ 2014,REUNION,1138,463,620,0,54,0,1.33,49
1040
+ 2014,ROMANIA,19090,6126,6042,5849,1074,0,0.97,220
1041
+ 2014,RUSSIAN FEDERATION,465052,110403,107368,232204,9322,5755,3.24,17585
1042
+ 2014,RWANDA,229,0,210,0,19,0,0.02,17
1043
+ 2014,SAINT HELENA,3,0,3,0,0,0,0.84,0
1044
+ 2014,SAINT LUCIA,111,0,111,0,0,0,0.61,5
1045
+ 2014,SAINT MARTIN (DUTCH PORTION),200,0,200,0,0,0,5.31,205
1046
+ 2014,SAMOA,54,0,54,0,0,0,0.28,9
1047
+ 2014,SAO TOME & PRINCIPE,31,0,31,0,0,0,0.17,9
1048
+ 2014,SAUDI ARABIA,163907,0,112689,43430,7782,5,5.31,4718
1049
+ 2014,SENEGAL,2415,235,1493,21,666,0,0.16,284
1050
+ 2014,SERBIA,10272,6721,2242,1005,304,0,1.16,70
1051
+ 2014,SEYCHELLES,135,0,135,0,0,0,1.41,155
1052
+ 2014,SIERRA LEONE,357,0,311,0,46,0,0.06,7
1053
+ 2014,SINGAPORE,15373,456,9118,5800,0,0,2.79,42028
1054
+ 2014,SLOVAKIA,8366,3624,1932,2356,451,3,1.54,29
1055
+ 2014,SLOVENIA,3494,1136,1788,391,180,0,1.69,71
1056
+ 2014,SOLOMON ISLANDS,55,0,55,0,0,0,0.1,4
1057
+ 2014,SOMALIA,166,0,166,0,0,0,0.02,57
1058
+ 2014,SOUTH AFRICA,133562,113068,16448,2404,1642,0,2.47,2945
1059
+ 2014,SPAIN,63806,11852,35189,14781,1984,0,1.38,9892
1060
+ 2014,SRI LANKA,5016,1059,3701,0,256,0,0.24,681
1061
+ 2014,ST. KITTS-NEVIS,63,0,63,0,0,0,1.14,4
1062
+ 2014,ST. PIERRE & MIQUELON,21,0,21,0,0,0,3.33,5
1063
+ 2014,ST. VINCENT & THE GRENADINES,57,0,57,0,0,0,0.52,0
1064
+ 2014,SURINAME,543,0,522,2,18,1,1.01,66
1065
+ 2014,SWAZILAND,328,131,197,0,0,0,0.26,1
1066
+ 2014,SWEDEN,11841,2183,8822,496,340,0,1.22,2107
1067
+ 2014,SWITZERLAND,9628,148,7230,1668,583,0,1.17,1312
1068
+ 2014,SYRIAN ARAB REPUBLIC,8373,1,5198,2480,517,178,0.45,219
1069
+ 2014,TAIWAN,72013,42516,18985,8526,1985,0,3.08,3046
1070
+ 2014,TAJIKISTAN,1415,404,689,166,156,0,0.17,52
1071
+ 2014,THAILAND,86232,16612,41230,23633,4757,0,1.27,3980
1072
+ 2014,TIMOR-LESTE (FORMERLY EAST TIMOR),128,0,128,0,0,0,0.11,3
1073
+ 2014,TOGO,715,0,467,20,228,0,0.1,81
1074
+ 2014,TONGA,33,0,33,0,0,0,0.31,3
1075
+ 2014,TRINIDAD AND TOBAGO,12619,0,1243,11262,114,0,9.32,575
1076
+ 2014,TUNISIA,7862,0,3235,3291,1241,96,0.71,239
1077
+ 2014,TURKEY,94350,37875,21662,25111,9701,0,1.22,3054
1078
+ 2014,TURKMENISTAN,18659,0,5453,12812,394,0,3.52,402
1079
+ 2014,TURKS AND CAICOS ISLANDS,56,0,56,0,0,0,1.66,0
1080
+ 2014,TUVALU,3,0,3,0,0,0,0.0,0
1081
+ 2014,UGANDA,1426,125,1011,0,291,0,0.04,98
1082
+ 2014,UKRAINE,61985,31649,8151,20874,1310,0,1.38,109
1083
+ 2014,UNITED ARAB EMIRATES,57641,2157,17922,34852,2176,534,6.34,17317
1084
+ 2014,UNITED KINGDOM,114486,31081,44274,37340,1218,573,1.78,10921
1085
+ 2014,UNITED REPUBLIC OF TANZANIA,3153,178,2117,475,382,1,0.06,170
1086
+ 2014,UNITED STATES OF AMERICA,1432855,450047,576531,390719,11314,4244,4.43,30722
1087
+ 2014,URUGUAY,1840,2,1700,25,112,0,0.54,251
1088
+ 2014,UZBEKISTAN,28692,1677,2086,23929,1000,0,0.97,0
1089
+ 2014,VANUATU,42,0,42,0,0,0,0.16,10
1090
+ 2014,VENEZUELA,50510,204,28445,12731,1088,8042,1.65,1256
1091
+ 2014,VIET NAM,45517,19246,12694,5349,8229,0,0.49,761
1092
+ 2014,WALLIS AND FUTUNA ISLANDS,6,0,6,0,0,0,0.44,1
1093
+ 2014,YEMEN,6190,137,5090,581,381,0,0.24,153
1094
+ 2014,ZAMBIA,1228,132,797,0,299,0,0.08,33
1095
+ 2014,ZIMBABWE,3278,2097,1005,0,177,0,0.22,9
deps/explorer/datasets/iris.csv ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ sepal_length,sepal_width,petal_length,petal_width,species
2
+ 5.1,3.5,1.4,0.2,Iris-setosa
3
+ 4.9,3.0,1.4,0.2,Iris-setosa
4
+ 4.7,3.2,1.3,0.2,Iris-setosa
5
+ 4.6,3.1,1.5,0.2,Iris-setosa
6
+ 5.0,3.6,1.4,0.2,Iris-setosa
7
+ 5.4,3.9,1.7,0.4,Iris-setosa
8
+ 4.6,3.4,1.4,0.3,Iris-setosa
9
+ 5.0,3.4,1.5,0.2,Iris-setosa
10
+ 4.4,2.9,1.4,0.2,Iris-setosa
11
+ 4.9,3.1,1.5,0.1,Iris-setosa
12
+ 5.4,3.7,1.5,0.2,Iris-setosa
13
+ 4.8,3.4,1.6,0.2,Iris-setosa
14
+ 4.8,3.0,1.4,0.1,Iris-setosa
15
+ 4.3,3.0,1.1,0.1,Iris-setosa
16
+ 5.8,4.0,1.2,0.2,Iris-setosa
17
+ 5.7,4.4,1.5,0.4,Iris-setosa
18
+ 5.4,3.9,1.3,0.4,Iris-setosa
19
+ 5.1,3.5,1.4,0.3,Iris-setosa
20
+ 5.7,3.8,1.7,0.3,Iris-setosa
21
+ 5.1,3.8,1.5,0.3,Iris-setosa
22
+ 5.4,3.4,1.7,0.2,Iris-setosa
23
+ 5.1,3.7,1.5,0.4,Iris-setosa
24
+ 4.6,3.6,1.0,0.2,Iris-setosa
25
+ 5.1,3.3,1.7,0.5,Iris-setosa
26
+ 4.8,3.4,1.9,0.2,Iris-setosa
27
+ 5.0,3.0,1.6,0.2,Iris-setosa
28
+ 5.0,3.4,1.6,0.4,Iris-setosa
29
+ 5.2,3.5,1.5,0.2,Iris-setosa
30
+ 5.2,3.4,1.4,0.2,Iris-setosa
31
+ 4.7,3.2,1.6,0.2,Iris-setosa
32
+ 4.8,3.1,1.6,0.2,Iris-setosa
33
+ 5.4,3.4,1.5,0.4,Iris-setosa
34
+ 5.2,4.1,1.5,0.1,Iris-setosa
35
+ 5.5,4.2,1.4,0.2,Iris-setosa
36
+ 4.9,3.1,1.5,0.1,Iris-setosa
37
+ 5.0,3.2,1.2,0.2,Iris-setosa
38
+ 5.5,3.5,1.3,0.2,Iris-setosa
39
+ 4.9,3.1,1.5,0.1,Iris-setosa
40
+ 4.4,3.0,1.3,0.2,Iris-setosa
41
+ 5.1,3.4,1.5,0.2,Iris-setosa
42
+ 5.0,3.5,1.3,0.3,Iris-setosa
43
+ 4.5,2.3,1.3,0.3,Iris-setosa
44
+ 4.4,3.2,1.3,0.2,Iris-setosa
45
+ 5.0,3.5,1.6,0.6,Iris-setosa
46
+ 5.1,3.8,1.9,0.4,Iris-setosa
47
+ 4.8,3.0,1.4,0.3,Iris-setosa
48
+ 5.1,3.8,1.6,0.2,Iris-setosa
49
+ 4.6,3.2,1.4,0.2,Iris-setosa
50
+ 5.3,3.7,1.5,0.2,Iris-setosa
51
+ 5.0,3.3,1.4,0.2,Iris-setosa
52
+ 7.0,3.2,4.7,1.4,Iris-versicolor
53
+ 6.4,3.2,4.5,1.5,Iris-versicolor
54
+ 6.9,3.1,4.9,1.5,Iris-versicolor
55
+ 5.5,2.3,4.0,1.3,Iris-versicolor
56
+ 6.5,2.8,4.6,1.5,Iris-versicolor
57
+ 5.7,2.8,4.5,1.3,Iris-versicolor
58
+ 6.3,3.3,4.7,1.6,Iris-versicolor
59
+ 4.9,2.4,3.3,1.0,Iris-versicolor
60
+ 6.6,2.9,4.6,1.3,Iris-versicolor
61
+ 5.2,2.7,3.9,1.4,Iris-versicolor
62
+ 5.0,2.0,3.5,1.0,Iris-versicolor
63
+ 5.9,3.0,4.2,1.5,Iris-versicolor
64
+ 6.0,2.2,4.0,1.0,Iris-versicolor
65
+ 6.1,2.9,4.7,1.4,Iris-versicolor
66
+ 5.6,2.9,3.6,1.3,Iris-versicolor
67
+ 6.7,3.1,4.4,1.4,Iris-versicolor
68
+ 5.6,3.0,4.5,1.5,Iris-versicolor
69
+ 5.8,2.7,4.1,1.0,Iris-versicolor
70
+ 6.2,2.2,4.5,1.5,Iris-versicolor
71
+ 5.6,2.5,3.9,1.1,Iris-versicolor
72
+ 5.9,3.2,4.8,1.8,Iris-versicolor
73
+ 6.1,2.8,4.0,1.3,Iris-versicolor
74
+ 6.3,2.5,4.9,1.5,Iris-versicolor
75
+ 6.1,2.8,4.7,1.2,Iris-versicolor
76
+ 6.4,2.9,4.3,1.3,Iris-versicolor
77
+ 6.6,3.0,4.4,1.4,Iris-versicolor
78
+ 6.8,2.8,4.8,1.4,Iris-versicolor
79
+ 6.7,3.0,5.0,1.7,Iris-versicolor
80
+ 6.0,2.9,4.5,1.5,Iris-versicolor
81
+ 5.7,2.6,3.5,1.0,Iris-versicolor
82
+ 5.5,2.4,3.8,1.1,Iris-versicolor
83
+ 5.5,2.4,3.7,1.0,Iris-versicolor
84
+ 5.8,2.7,3.9,1.2,Iris-versicolor
85
+ 6.0,2.7,5.1,1.6,Iris-versicolor
86
+ 5.4,3.0,4.5,1.5,Iris-versicolor
87
+ 6.0,3.4,4.5,1.6,Iris-versicolor
88
+ 6.7,3.1,4.7,1.5,Iris-versicolor
89
+ 6.3,2.3,4.4,1.3,Iris-versicolor
90
+ 5.6,3.0,4.1,1.3,Iris-versicolor
91
+ 5.5,2.5,4.0,1.3,Iris-versicolor
92
+ 5.5,2.6,4.4,1.2,Iris-versicolor
93
+ 6.1,3.0,4.6,1.4,Iris-versicolor
94
+ 5.8,2.6,4.0,1.2,Iris-versicolor
95
+ 5.0,2.3,3.3,1.0,Iris-versicolor
96
+ 5.6,2.7,4.2,1.3,Iris-versicolor
97
+ 5.7,3.0,4.2,1.2,Iris-versicolor
98
+ 5.7,2.9,4.2,1.3,Iris-versicolor
99
+ 6.2,2.9,4.3,1.3,Iris-versicolor
100
+ 5.1,2.5,3.0,1.1,Iris-versicolor
101
+ 5.7,2.8,4.1,1.3,Iris-versicolor
102
+ 6.3,3.3,6.0,2.5,Iris-virginica
103
+ 5.8,2.7,5.1,1.9,Iris-virginica
104
+ 7.1,3.0,5.9,2.1,Iris-virginica
105
+ 6.3,2.9,5.6,1.8,Iris-virginica
106
+ 6.5,3.0,5.8,2.2,Iris-virginica
107
+ 7.6,3.0,6.6,2.1,Iris-virginica
108
+ 4.9,2.5,4.5,1.7,Iris-virginica
109
+ 7.3,2.9,6.3,1.8,Iris-virginica
110
+ 6.7,2.5,5.8,1.8,Iris-virginica
111
+ 7.2,3.6,6.1,2.5,Iris-virginica
112
+ 6.5,3.2,5.1,2.0,Iris-virginica
113
+ 6.4,2.7,5.3,1.9,Iris-virginica
114
+ 6.8,3.0,5.5,2.1,Iris-virginica
115
+ 5.7,2.5,5.0,2.0,Iris-virginica
116
+ 5.8,2.8,5.1,2.4,Iris-virginica
117
+ 6.4,3.2,5.3,2.3,Iris-virginica
118
+ 6.5,3.0,5.5,1.8,Iris-virginica
119
+ 7.7,3.8,6.7,2.2,Iris-virginica
120
+ 7.7,2.6,6.9,2.3,Iris-virginica
121
+ 6.0,2.2,5.0,1.5,Iris-virginica
122
+ 6.9,3.2,5.7,2.3,Iris-virginica
123
+ 5.6,2.8,4.9,2.0,Iris-virginica
124
+ 7.7,2.8,6.7,2.0,Iris-virginica
125
+ 6.3,2.7,4.9,1.8,Iris-virginica
126
+ 6.7,3.3,5.7,2.1,Iris-virginica
127
+ 7.2,3.2,6.0,1.8,Iris-virginica
128
+ 6.2,2.8,4.8,1.8,Iris-virginica
129
+ 6.1,3.0,4.9,1.8,Iris-virginica
130
+ 6.4,2.8,5.6,2.1,Iris-virginica
131
+ 7.2,3.0,5.8,1.6,Iris-virginica
132
+ 7.4,2.8,6.1,1.9,Iris-virginica
133
+ 7.9,3.8,6.4,2.0,Iris-virginica
134
+ 6.4,2.8,5.6,2.2,Iris-virginica
135
+ 6.3,2.8,5.1,1.5,Iris-virginica
136
+ 6.1,2.6,5.6,1.4,Iris-virginica
137
+ 7.7,3.0,6.1,2.3,Iris-virginica
138
+ 6.3,3.4,5.6,2.4,Iris-virginica
139
+ 6.4,3.1,5.5,1.8,Iris-virginica
140
+ 6.0,3.0,4.8,1.8,Iris-virginica
141
+ 6.9,3.1,5.4,2.1,Iris-virginica
142
+ 6.7,3.1,5.6,2.4,Iris-virginica
143
+ 6.9,3.1,5.1,2.3,Iris-virginica
144
+ 5.8,2.7,5.1,1.9,Iris-virginica
145
+ 6.8,3.2,5.9,2.3,Iris-virginica
146
+ 6.7,3.3,5.7,2.5,Iris-virginica
147
+ 6.7,3.0,5.2,2.3,Iris-virginica
148
+ 6.3,2.5,5.0,1.9,Iris-virginica
149
+ 6.5,3.0,5.2,2.0,Iris-virginica
150
+ 6.2,3.4,5.4,2.3,Iris-virginica
151
+ 5.9,3.0,5.1,1.8,Iris-virginica
deps/explorer/datasets/wine.csv ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
2
+ 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
3
+ 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
4
+ 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
5
+ 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
6
+ 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
7
+ 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
8
+ 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
9
+ 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
10
+ 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
11
+ 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
12
+ 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
13
+ 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
14
+ 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
15
+ 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
16
+ 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
17
+ 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
18
+ 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
19
+ 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
20
+ 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
21
+ 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
22
+ 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
23
+ 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
24
+ 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
25
+ 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
26
+ 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
27
+ 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
28
+ 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
29
+ 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
30
+ 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
31
+ 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
32
+ 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
33
+ 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
34
+ 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
35
+ 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
36
+ 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
37
+ 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
38
+ 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
39
+ 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
40
+ 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
41
+ 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
42
+ 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
43
+ 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
44
+ 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
45
+ 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
46
+ 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
47
+ 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
48
+ 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
49
+ 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
50
+ 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
51
+ 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
52
+ 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
53
+ 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
54
+ 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
55
+ 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
56
+ 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
57
+ 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
58
+ 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
59
+ 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
60
+ 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
61
+ 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
62
+ 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
63
+ 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
64
+ 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
65
+ 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
66
+ 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
67
+ 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
68
+ 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
69
+ 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
70
+ 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
71
+ 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
72
+ 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
73
+ 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
74
+ 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
75
+ 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
76
+ 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
77
+ 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
78
+ 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
79
+ 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
80
+ 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
81
+ 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
82
+ 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
83
+ 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
84
+ 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
85
+ 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
86
+ 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
87
+ 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
88
+ 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
89
+ 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
90
+ 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
91
+ 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
92
+ 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
93
+ 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
94
+ 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
95
+ 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
96
+ 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
97
+ 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
98
+ 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
99
+ 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
100
+ 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
101
+ 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
102
+ 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
103
+ 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
104
+ 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
105
+ 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
106
+ 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
107
+ 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
108
+ 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
109
+ 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
110
+ 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
111
+ 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
112
+ 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
113
+ 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
114
+ 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
115
+ 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
116
+ 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
117
+ 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
118
+ 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
119
+ 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
120
+ 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
121
+ 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
122
+ 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
123
+ 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
124
+ 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
125
+ 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
126
+ 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
127
+ 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
128
+ 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
129
+ 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
130
+ 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
131
+ 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
132
+ 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
133
+ 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
134
+ 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
135
+ 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
136
+ 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
137
+ 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
138
+ 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
139
+ 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
140
+ 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
141
+ 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
142
+ 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
143
+ 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
144
+ 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
145
+ 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
146
+ 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
147
+ 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
148
+ 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
149
+ 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
150
+ 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
151
+ 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
152
+ 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
153
+ 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
154
+ 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
155
+ 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
156
+ 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
157
+ 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
158
+ 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
159
+ 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
160
+ 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
161
+ 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
162
+ 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
163
+ 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
164
+ 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
165
+ 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
166
+ 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
167
+ 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
168
+ 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
169
+ 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
170
+ 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
171
+ 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
172
+ 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
173
+ 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
174
+ 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
175
+ 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
176
+ 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
177
+ 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
178
+ 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
179
+ 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
deps/explorer/hex_metadata.config ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {<<"links">>,
2
+ [{<<"Changelog">>,
3
+ <<"https://github.com/elixir-nx/explorer/blob/v0.10.1/CHANGELOG.md">>},
4
+ {<<"GitHub">>,<<"https://github.com/elixir-nx/explorer">>}]}.
5
+ {<<"name">>,<<"explorer">>}.
6
+ {<<"version">>,<<"0.10.1">>}.
7
+ {<<"description">>,
8
+ <<"Series (one-dimensional) and dataframes (two-dimensional) for fast data exploration in Elixir">>}.
9
+ {<<"elixir">>,<<"~> 1.14">>}.
10
+ {<<"app">>,<<"explorer">>}.
11
+ {<<"files">>,
12
+ [<<"lib">>,<<"lib/explorer">>,<<"lib/explorer/remote.ex">>,
13
+ <<"lib/explorer/duration.ex">>,<<"lib/explorer/series.ex">>,
14
+ <<"lib/explorer/datasets.ex">>,<<"lib/explorer/comptime_utils.ex">>,
15
+ <<"lib/explorer/polars_backend">>,
16
+ <<"lib/explorer/polars_backend/native.ex">>,
17
+ <<"lib/explorer/polars_backend/series.ex">>,
18
+ <<"lib/explorer/polars_backend/expression.ex">>,
19
+ <<"lib/explorer/polars_backend/lazy_frame.ex">>,
20
+ <<"lib/explorer/polars_backend/shared.ex">>,
21
+ <<"lib/explorer/polars_backend/data_frame.ex">>,<<"lib/explorer/fss.ex">>,
22
+ <<"lib/explorer/backend.ex">>,<<"lib/explorer/backend">>,
23
+ <<"lib/explorer/backend/series.ex">>,
24
+ <<"lib/explorer/backend/query_frame.ex">>,
25
+ <<"lib/explorer/backend/lazy_series.ex">>,
26
+ <<"lib/explorer/backend/data_frame.ex">>,<<"lib/explorer/query.ex">>,
27
+ <<"lib/explorer/polars_backend.ex">>,<<"lib/explorer/shared.ex">>,
28
+ <<"lib/explorer/application.ex">>,<<"lib/explorer/fss">>,
29
+ <<"lib/explorer/fss/s3.ex">>,<<"lib/explorer/fss/utils.ex">>,
30
+ <<"lib/explorer/fss/http.ex">>,<<"lib/explorer/data_frame.ex">>,
31
+ <<"lib/explorer/tensor_frame.ex">>,<<"lib/explorer/remote">>,
32
+ <<"lib/explorer/remote/holder.ex">>,<<"lib/explorer/remote/local_gc.ex">>,
33
+ <<"lib/explorer.ex">>,<<"native">>,<<"native/explorer">>,
34
+ <<"native/explorer/Cargo.toml">>,<<"native/explorer/Cross.toml">>,
35
+ <<"native/explorer/Cargo.lock">>,<<"native/explorer/.cargo">>,
36
+ <<"native/explorer/.cargo/config.toml">>,<<"native/explorer/.gitignore">>,
37
+ <<"native/explorer/rust-toolchain.toml">>,<<"native/explorer/src">>,
38
+ <<"native/explorer/src/series">>,
39
+ <<"native/explorer/src/series/from_list.rs">>,
40
+ <<"native/explorer/src/series/log.rs">>,<<"native/explorer/src/series.rs">>,
41
+ <<"native/explorer/src/lazyframe.rs">>,<<"native/explorer/src/dataframe">>,
42
+ <<"native/explorer/src/dataframe/io.rs">>,
43
+ <<"native/explorer/src/dataframe.rs">>,
44
+ <<"native/explorer/src/local_message.rs">>,
45
+ <<"native/explorer/src/expressions.rs">>,<<"native/explorer/src/error.rs">>,
46
+ <<"native/explorer/src/encoding.rs">>,<<"native/explorer/src/datatypes">>,
47
+ <<"native/explorer/src/datatypes/ex_dtypes.rs">>,
48
+ <<"native/explorer/src/lib.rs">>,<<"native/explorer/src/cloud_writer.rs">>,
49
+ <<"native/explorer/src/lazyframe">>,
50
+ <<"native/explorer/src/lazyframe/io.rs">>,
51
+ <<"native/explorer/src/datatypes.rs">>,<<"datasets">>,
52
+ <<"datasets/iris.csv">>,<<"datasets/wine.csv">>,
53
+ <<"datasets/fossil_fuels.csv">>,
54
+ <<"checksum-Elixir.Explorer.PolarsBackend.Native.exs">>,<<"mix.exs">>,
55
+ <<"CHANGELOG.md">>,<<"README.md">>,<<"LICENSE">>]}.
56
+ {<<"licenses">>,[<<"MIT">>]}.
57
+ {<<"requirements">>,
58
+ [[{<<"name">>,<<"aws_signature">>},
59
+ {<<"app">>,<<"aws_signature">>},
60
+ {<<"optional">>,false},
61
+ {<<"requirement">>,<<"~> 0.3">>},
62
+ {<<"repository">>,<<"hexpm">>}],
63
+ [{<<"name">>,<<"fss">>},
64
+ {<<"app">>,<<"fss">>},
65
+ {<<"optional">>,false},
66
+ {<<"requirement">>,<<"~> 0.1">>},
67
+ {<<"repository">>,<<"hexpm">>}],
68
+ [{<<"name">>,<<"rustler_precompiled">>},
69
+ {<<"app">>,<<"rustler_precompiled">>},
70
+ {<<"optional">>,false},
71
+ {<<"requirement">>,<<"~> 0.7">>},
72
+ {<<"repository">>,<<"hexpm">>}],
73
+ [{<<"name">>,<<"table">>},
74
+ {<<"app">>,<<"table">>},
75
+ {<<"optional">>,false},
76
+ {<<"requirement">>,<<"~> 0.1.2">>},
77
+ {<<"repository">>,<<"hexpm">>}],
78
+ [{<<"name">>,<<"table_rex">>},
79
+ {<<"app">>,<<"table_rex">>},
80
+ {<<"optional">>,false},
81
+ {<<"requirement">>,<<"~> 3.1.1 or ~> 4.0.0">>},
82
+ {<<"repository">>,<<"hexpm">>}],
83
+ [{<<"name">>,<<"decimal">>},
84
+ {<<"app">>,<<"decimal">>},
85
+ {<<"optional">>,false},
86
+ {<<"requirement">>,<<"~> 2.1">>},
87
+ {<<"repository">>,<<"hexpm">>}],
88
+ [{<<"name">>,<<"flame">>},
89
+ {<<"app">>,<<"flame">>},
90
+ {<<"optional">>,true},
91
+ {<<"requirement">>,<<"~> 0.3">>},
92
+ {<<"repository">>,<<"hexpm">>}],
93
+ [{<<"name">>,<<"castore">>},
94
+ {<<"app">>,<<"castore">>},
95
+ {<<"optional">>,true},
96
+ {<<"requirement">>,<<"~> 1.0">>},
97
+ {<<"repository">>,<<"hexpm">>}],
98
+ [{<<"name">>,<<"adbc">>},
99
+ {<<"app">>,<<"adbc">>},
100
+ {<<"optional">>,true},
101
+ {<<"requirement">>,<<"~> 0.1">>},
102
+ {<<"repository">>,<<"hexpm">>}],
103
+ [{<<"name">>,<<"nx">>},
104
+ {<<"app">>,<<"nx">>},
105
+ {<<"optional">>,true},
106
+ {<<"requirement">>,<<"~> 0.4">>},
107
+ {<<"repository">>,<<"hexpm">>}],
108
+ [{<<"name">>,<<"rustler">>},
109
+ {<<"app">>,<<"rustler">>},
110
+ {<<"optional">>,true},
111
+ {<<"requirement">>,<<"~> 0.34.0">>},
112
+ {<<"repository">>,<<"hexpm">>}]]}.
113
+ {<<"build_tools">>,[<<"mix">>]}.
deps/explorer/lib/explorer.ex ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer do
2
+ @external_resource "README.md"
3
+
4
+ @moduledoc "README.md"
5
+ |> File.read!()
6
+ |> String.split("<!-- MDOC -->")
7
+ |> Enum.fetch!(1)
8
+ end
deps/explorer/lib/explorer/application.ex ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.Application do
2
+ @moduledoc false
3
+ use Application
4
+
5
+ def start(_type, _args) do
6
+ children = [
7
+ {DynamicSupervisor, name: Explorer.Remote.Supervisor, strategy: :one_for_one},
8
+ Explorer.Remote.LocalGC
9
+ ]
10
+
11
+ Supervisor.start_link(children, strategy: :one_for_one)
12
+ end
13
+ end
deps/explorer/lib/explorer/backend.ex ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.Backend do
2
+ @moduledoc """
3
+ The behaviour for Explorer backends and associated functions.
4
+
5
+ Each backend is a module with `DataFrame` and `Series` submodules that match the
6
+ respective behaviours for each.
7
+
8
+ The default backend is read from the application environment. Currently, the only
9
+ backend is an in-memory, eager one based on
10
+ [`Polars`](https://github.com/pola-rs/polars). When alternatives are
11
+ available, you can use them by configuring your runtime:
12
+
13
+ # config/runtime.exs
14
+ import Config
15
+ config :explorer, default_backend: Lib.CustomBackend
16
+
17
+ """
18
+
19
+ @backend_key {Explorer, :default_backend}
20
+
21
+ @doc """
22
+ Sets the current process default backend to `backend`.
23
+
24
+ The default backend is stored only in the process dictionary. This means if
25
+ you start a separate process, such as `Task`, the default backend must be set
26
+ on the new process too.
27
+
28
+ ## Examples
29
+ iex> Explorer.Backend.put(Lib.CustomBackend)
30
+ Explorer.PolarsBackend
31
+ iex> Explorer.Backend.get()
32
+ Lib.CustomBackend
33
+ """
34
+ def put(backend) do
35
+ Process.put(@backend_key, backend!(backend)) ||
36
+ backend!(Application.fetch_env!(:explorer, :default_backend))
37
+ end
38
+
39
+ @doc """
40
+ Gets the default backend for the current process.
41
+ """
42
+ def get do
43
+ Process.get(@backend_key) || backend!(Application.fetch_env!(:explorer, :default_backend))
44
+ end
45
+
46
+ ## Helpers
47
+
48
+ defp backend!(backend) when is_atom(backend),
49
+ do: backend
50
+
51
+ defp backend!(other) do
52
+ raise ArgumentError,
53
+ "backend must be an atom, got: #{inspect(other)}"
54
+ end
55
+ end
deps/explorer/lib/explorer/backend/data_frame.ex ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.Backend.DataFrame do
2
+ @moduledoc """
3
+ The behaviour for DataFrame backends.
4
+ """
5
+
6
+ @type t :: struct()
7
+
8
+ @type df :: Explorer.DataFrame.t()
9
+
10
+ @type option(type) :: type | nil
11
+
12
+ # Types for IO operations
13
+ @type ok_result() :: :ok | {:error, Exception.t()}
14
+ @type io_result(t) :: {:ok, t} | {:error, Exception.t()}
15
+
16
+ # Generic result
17
+ @type result(t) :: {:ok, t} | {:error, term()}
18
+
19
+ @type series :: Explorer.Series.t()
20
+ @type column_name :: String.t()
21
+ @type dtype :: Explorer.Series.dtype()
22
+ @type dtypes :: %{column_name() => dtype()}
23
+ @type io_dtypes :: [{column_name(), dtype()}]
24
+
25
+ @type basic_types :: float() | integer() | String.t() | Date.t() | DateTime.t()
26
+ @type mutate_value ::
27
+ series()
28
+ | basic_types()
29
+ | [basic_types()]
30
+ | (df() -> series() | basic_types() | [basic_types()])
31
+
32
+ @type query_frame :: Explorer.Backend.QueryFrame.t()
33
+ @type lazy_series :: Explorer.Backend.LazySeries.t()
34
+
35
+ @type compression :: {algorithm :: option(atom()), level :: option(integer())}
36
+ @type columns_for_io :: list(column_name()) | list(pos_integer()) | nil
37
+
38
+ @type fs_entry :: Explorer.DataFrame.fs_entry()
39
+
40
+ # IO: query
41
+ @callback from_query(
42
+ Adbc.Connection.t(),
43
+ query :: String.t(),
44
+ params :: list(term)
45
+ ) :: result(df)
46
+
47
+ # IO: CSV
48
+ @callback from_csv(
49
+ entry :: fs_entry(),
50
+ io_dtypes,
51
+ delimiter :: String.t(),
52
+ nil_values :: list(String.t()),
53
+ skip_rows :: integer(),
54
+ skip_rows_after_header :: integer(),
55
+ header? :: boolean(),
56
+ encoding :: String.t(),
57
+ max_rows :: option(integer()),
58
+ columns :: columns_for_io(),
59
+ infer_schema_length :: option(integer()),
60
+ parse_dates :: boolean(),
61
+ eol_delimiter :: option(String.t())
62
+ ) :: io_result(df)
63
+ @callback to_csv(
64
+ df,
65
+ entry :: fs_entry(),
66
+ header? :: boolean(),
67
+ delimiter :: String.t(),
68
+ streaming :: boolean()
69
+ ) ::
70
+ ok_result()
71
+ @callback dump_csv(df, header? :: boolean(), delimiter :: String.t()) :: io_result(binary())
72
+
73
+ @callback load_csv(
74
+ contents :: String.t(),
75
+ io_dtypes,
76
+ delimiter :: String.t(),
77
+ nil_values :: list(String.t()),
78
+ skip_rows :: integer(),
79
+ skip_rows_after_header :: integer(),
80
+ header? :: boolean(),
81
+ encoding :: String.t(),
82
+ max_rows :: option(integer()),
83
+ columns :: columns_for_io(),
84
+ infer_schema_length :: option(integer()),
85
+ parse_dates :: boolean(),
86
+ eol_delimiter :: option(String.t())
87
+ ) :: io_result(df)
88
+
89
+ # IO: Parquet
90
+ @callback from_parquet(
91
+ entry :: fs_entry(),
92
+ max_rows :: option(integer()),
93
+ columns :: columns_for_io(),
94
+ rechunk :: boolean()
95
+ ) :: io_result(df)
96
+ @callback to_parquet(
97
+ df,
98
+ entry :: fs_entry(),
99
+ compression(),
100
+ streaming :: boolean()
101
+ ) ::
102
+ ok_result()
103
+ @callback dump_parquet(df, compression()) :: io_result(binary())
104
+ @callback load_parquet(contents :: binary()) :: io_result(df)
105
+
106
+ # IO: IPC
107
+ @callback from_ipc(
108
+ entry :: fs_entry(),
109
+ columns :: columns_for_io()
110
+ ) :: io_result(df)
111
+ @callback to_ipc(df, entry :: fs_entry(), compression(), streaming :: boolean()) ::
112
+ ok_result()
113
+ @callback dump_ipc(df, compression()) :: io_result(binary())
114
+ @callback load_ipc(
115
+ contents :: binary(),
116
+ columns :: columns_for_io()
117
+ ) :: io_result(df)
118
+
119
+ # IO: IPC Stream
120
+ @callback from_ipc_stream(
121
+ filename :: fs_entry(),
122
+ columns :: columns_for_io()
123
+ ) :: io_result(df)
124
+ @callback to_ipc_stream(
125
+ df,
126
+ entry :: fs_entry(),
127
+ compression()
128
+ ) ::
129
+ ok_result()
130
+ @callback dump_ipc_stream(df, compression()) :: io_result(binary())
131
+ @callback load_ipc_stream(
132
+ contents :: binary(),
133
+ columns :: columns_for_io()
134
+ ) :: io_result(df)
135
+
136
+ # IO: IPC NDJSON
137
+ @callback from_ndjson(
138
+ filename :: fs_entry(),
139
+ infer_schema_length :: integer(),
140
+ batch_size :: integer()
141
+ ) :: io_result(df)
142
+ @callback to_ndjson(df, entry :: fs_entry()) :: ok_result()
143
+
144
+ @callback dump_ndjson(df) :: io_result(binary())
145
+
146
+ @callback load_ndjson(
147
+ contents :: String.t(),
148
+ infer_schema_length :: integer(),
149
+ batch_size :: integer()
150
+ ) :: io_result(df)
151
+
152
+ # Conversion
153
+
154
+ @callback lazy() :: module()
155
+ @callback lazy(df) :: df
156
+ @callback compute(df) :: df
157
+ @callback from_tabular(Table.Reader.t(), io_dtypes) :: df
158
+ @callback from_series([{binary(), Series.t()}]) :: df
159
+ @callback to_rows(df, atom_keys? :: boolean()) :: [map()]
160
+ @callback to_rows_stream(df, atom_keys? :: boolean(), chunk_size :: integer()) :: Enumerable.t()
161
+
162
+ # Ownership
163
+
164
+ @callback owner_reference(df) :: reference() | nil
165
+ @callback owner_import(term()) :: io_result(df)
166
+ @callback owner_export(df) :: io_result(term())
167
+
168
+ # Introspection
169
+
170
+ @callback n_rows(df) :: integer()
171
+ @callback inspect(df, opts :: Inspect.Opts.t()) :: Inspect.Algebra.t()
172
+ @callback re_dtype(String.t()) :: dtype()
173
+
174
+ # Single table verbs
175
+
176
+ @callback head(df, rows :: integer()) :: df
177
+ @callback tail(df, rows :: integer()) :: df
178
+ @callback select(df, out_df :: df()) :: df
179
+ @callback mask(df, mask :: series) :: df
180
+ @callback filter_with(df, out_df :: df(), lazy_series()) :: df
181
+ @callback mutate_with(df, out_df :: df(), mutations :: [{column_name(), lazy_series()}]) :: df
182
+ @callback sort_with(
183
+ df,
184
+ out_df :: df(),
185
+ directions :: [{:asc | :desc, lazy_series()}],
186
+ maintain_order? :: boolean(),
187
+ multithreaded? :: boolean(),
188
+ nulls_last? :: boolean()
189
+ ) :: df
190
+ @callback distinct(df, out_df :: df(), columns :: [column_name()]) :: df
191
+ @callback rename(df, out_df :: df(), [{old :: column_name(), new :: column_name()}]) :: df
192
+ @callback dummies(df, out_df :: df(), columns :: [column_name()]) :: df
193
+ @callback sample(
194
+ df,
195
+ n_or_frac :: number(),
196
+ replace :: boolean(),
197
+ shuffle :: boolean(),
198
+ seed :: option(integer())
199
+ ) :: df
200
+ @callback pull(df, column :: column_name()) :: series
201
+ @callback slice(df, indices :: list(integer()) | series() | %Range{}) :: df
202
+ @callback slice(df, offset :: integer(), length :: integer()) :: df
203
+ @callback drop_nil(df, columns :: [column_name()]) :: df
204
+ @callback pivot_wider(
205
+ df,
206
+ id_columns :: [column_name()],
207
+ names_from :: column_name(),
208
+ values_from :: [column_name()],
209
+ names_prefix :: String.t()
210
+ ) :: df
211
+ @callback pivot_longer(
212
+ df,
213
+ out_df :: df(),
214
+ columns_to_pivot :: [column_name()],
215
+ columns_to_keep :: [column_name()],
216
+ names_to :: column_name(),
217
+ values_to :: column_name()
218
+ ) :: df
219
+ @callback transpose(
220
+ df,
221
+ out_df :: df(),
222
+ keep_names_as :: column_name(),
223
+ new_column_names :: [column_name()]
224
+ ) :: df
225
+ @callback put(df, out_df :: df(), column_name(), series()) :: df
226
+ @callback nil_count(df) :: df()
227
+ @callback explode(df, out_df :: df(), columns :: [column_name()]) :: df()
228
+ @callback unnest(df, out_df :: df(), columns :: [column_name()]) :: df()
229
+ @callback correlation(df, out_df :: df(), ddof :: integer(), method :: atom()) :: df()
230
+ @callback covariance(df, out_df :: df(), ddof :: integer()) :: df()
231
+
232
+ # Two or more table verbs
233
+
234
+ @callback join(
235
+ [df()],
236
+ out_df :: df(),
237
+ on :: list({column_name(), column_name()}),
238
+ how :: :left | :inner | :outer | :right | :cross
239
+ ) :: df
240
+
241
+ @callback concat_columns([df], out_df :: df()) :: df
242
+ @callback concat_rows([df], out_df :: df()) :: df
243
+
244
+ # Groups
245
+
246
+ @callback summarise_with(df, out_df :: df(), aggregations :: [{column_name(), lazy_series()}]) ::
247
+ df
248
+
249
+ # SQL
250
+
251
+ @callback sql(df, sql_string :: binary(), table_name :: binary()) :: df()
252
+
253
+ # Functions
254
+ alias Explorer.{DataFrame, Series}
255
+
256
+ @doc """
257
+ Creates a new DataFrame for a given backend.
258
+ """
259
+ def new(data, names, dtypes) when is_list(dtypes) do
260
+ dtypes = Map.new(Enum.zip(names, dtypes))
261
+
262
+ new(data, names, dtypes)
263
+ end
264
+
265
+ def new(data, names, dtypes) when is_list(names) and is_map(dtypes) do
266
+ %DataFrame{data: data, names: names, dtypes: dtypes, groups: []}
267
+ end
268
+
269
+ @default_limit 5
270
+ alias Inspect.Algebra, as: A
271
+
272
+ @doc """
273
+ Default inspect implementation for backends.
274
+ """
275
+ def inspect(df, backend, n_rows, inspect_opts, opts \\ [])
276
+ when is_binary(backend) and (is_integer(n_rows) or is_nil(n_rows)) and
277
+ is_list(opts) do
278
+ inspect_opts = %{inspect_opts | limit: @default_limit}
279
+ elide_columns? = Keyword.get(opts, :elide_columns, false)
280
+ open = A.color("[", :list, inspect_opts)
281
+ close = A.color("]", :list, inspect_opts)
282
+
283
+ cols_algebra = build_cols_algebra(df, inspect_opts, elide_columns?)
284
+ df_info = "#{n_rows || "???"} x #{length(cols_algebra)}"
285
+
286
+ A.concat([
287
+ A.color(backend, :atom, inspect_opts),
288
+ open,
289
+ df_info,
290
+ close,
291
+ groups_algebra(df.groups, inspect_opts) | cols_algebra
292
+ ])
293
+ end
294
+
295
+ defp build_cols_algebra(df, inspect_opts, true) do
296
+ for name <- DataFrame.names(df) do
297
+ type =
298
+ df
299
+ |> DataFrame.dtypes()
300
+ |> Map.get(name)
301
+ |> Explorer.Shared.dtype_to_string()
302
+
303
+ A.concat([
304
+ A.line(),
305
+ A.color("#{name} ", :map, inspect_opts),
306
+ A.color("#{type} ", :atom, inspect_opts),
307
+ "???"
308
+ ])
309
+ end
310
+ end
311
+
312
+ defp build_cols_algebra(df, inspect_opts, false) do
313
+ for name <- DataFrame.names(df) do
314
+ series = df[name]
315
+
316
+ series =
317
+ case inspect_opts.limit do
318
+ :infinity -> series
319
+ limit when is_integer(limit) -> Series.slice(series, 0, limit + 1)
320
+ end
321
+
322
+ data =
323
+ series
324
+ |> Series.to_list()
325
+ |> Explorer.Shared.to_doc(inspect_opts)
326
+
327
+ type =
328
+ series
329
+ |> Series.dtype()
330
+ |> Explorer.Shared.dtype_to_string()
331
+
332
+ A.concat([
333
+ A.line(),
334
+ A.color("#{name} ", :map, inspect_opts),
335
+ A.color("#{type} ", :atom, inspect_opts),
336
+ data
337
+ ])
338
+ end
339
+ end
340
+
341
+ defp groups_algebra([_ | _] = groups, opts),
342
+ do:
343
+ A.concat([
344
+ A.line(),
345
+ A.color("Groups: ", :atom, opts),
346
+ A.to_doc(groups, opts)
347
+ ])
348
+
349
+ defp groups_algebra([], _), do: ""
350
+ end
deps/explorer/lib/explorer/backend/lazy_series.ex ADDED
@@ -0,0 +1,1267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.Backend.LazySeries do
2
+ @moduledoc """
3
+ This is an opaque implementation of a Series.
4
+
5
+ It represents an operation with its arguments.
6
+ """
7
+ alias Explorer.Series
8
+ alias Explorer.Backend
9
+
10
+ @behaviour Explorer.Backend.Series
11
+
12
+ defstruct op: nil, args: [], dtype: nil, aggregation: false, backend: nil, resource: nil
13
+
14
+ @type t :: %__MODULE__{
15
+ op: atom(),
16
+ args: list(),
17
+ dtype: any(),
18
+ aggregation: boolean(),
19
+ backend: nil | module(),
20
+ resource: nil
21
+ }
22
+
23
+ @operations [
24
+ # Element-wise
25
+ all_equal: 2,
26
+ equal: 2,
27
+ not_equal: 2,
28
+ greater: 2,
29
+ greater_equal: 2,
30
+ less: 2,
31
+ less_equal: 2,
32
+ is_nil: 1,
33
+ is_not_nil: 1,
34
+ is_finite: 1,
35
+ is_infinite: 1,
36
+ is_nan: 1,
37
+ binary_and: 2,
38
+ binary_or: 2,
39
+ binary_in: 2,
40
+ add: 2,
41
+ subtract: 2,
42
+ multiply: 2,
43
+ divide: 2,
44
+ quotient: 2,
45
+ remainder: 2,
46
+ pow: 2,
47
+ log: 1,
48
+ log: 2,
49
+ exp: 1,
50
+ fill_missing_with_value: 2,
51
+ fill_missing_with_strategy: 2,
52
+ format: 1,
53
+ concat: 1,
54
+ coalesce: 2,
55
+ cast: 2,
56
+ select: 3,
57
+ abs: 1,
58
+ strptime: 2,
59
+ strftime: 2,
60
+ clip_float: 3,
61
+ clip_integer: 3,
62
+
63
+ # Trigonometric functions
64
+ acos: 1,
65
+ asin: 1,
66
+ atan: 1,
67
+ cos: 1,
68
+ sin: 1,
69
+ tan: 1,
70
+
71
+ # Window functions
72
+ cumulative_max: 2,
73
+ cumulative_min: 2,
74
+ cumulative_sum: 2,
75
+ cumulative_product: 2,
76
+ window_max: 5,
77
+ window_mean: 5,
78
+ window_median: 5,
79
+ window_min: 5,
80
+ window_sum: 5,
81
+ window_standard_deviation: 5,
82
+ ewm_mean: 5,
83
+ ewm_standard_deviation: 6,
84
+ ewm_variance: 6,
85
+ # Transformation
86
+ column: 1,
87
+ reverse: 1,
88
+ argsort: 5,
89
+ sort: 5,
90
+ distinct: 1,
91
+ unordered_distinct: 1,
92
+ slice: 2,
93
+ slice: 3,
94
+ sample_n: 5,
95
+ sample_frac: 5,
96
+ head: 2,
97
+ tail: 2,
98
+ shift: 3,
99
+ peaks: 2,
100
+ unary_not: 1,
101
+ # Aggregations
102
+ sum: 1,
103
+ min: 1,
104
+ max: 1,
105
+ argmin: 1,
106
+ argmax: 1,
107
+ mean: 1,
108
+ median: 1,
109
+ mode: 1,
110
+ n_distinct: 1,
111
+ variance: 2,
112
+ standard_deviation: 2,
113
+ quantile: 2,
114
+ rank: 4,
115
+ product: 1,
116
+ first: 1,
117
+ last: 1,
118
+ count: 1,
119
+ nil_count: 1,
120
+ size: 1,
121
+ skew: 2,
122
+ correlation: 4,
123
+ covariance: 3,
124
+ all: 1,
125
+ any: 1,
126
+ row_index: 1,
127
+ # Strings
128
+ contains: 2,
129
+ re_contains: 2,
130
+ replace: 3,
131
+ re_replace: 3,
132
+ lstrip: 2,
133
+ rstrip: 2,
134
+ strip: 2,
135
+ upcase: 1,
136
+ downcase: 1,
137
+ substring: 3,
138
+ split: 2,
139
+ split_into: 3,
140
+ json_decode: 2,
141
+ json_path_match: 2,
142
+ count_matches: 2,
143
+ re_count_matches: 2,
144
+ re_scan: 2,
145
+ re_named_captures: 2,
146
+ # Float round
147
+ round: 2,
148
+ floor: 1,
149
+ ceil: 1,
150
+ # Date functions
151
+ day_of_week: 1,
152
+ day_of_year: 1,
153
+ week_of_year: 1,
154
+ month: 1,
155
+ year: 1,
156
+ hour: 1,
157
+ minute: 1,
158
+ second: 1,
159
+ # List functions
160
+ join: 2,
161
+ lengths: 1,
162
+ member: 3,
163
+ # Struct functions
164
+ field: 2
165
+ ]
166
+
167
+ @comparison_operations [:equal, :not_equal, :greater, :greater_equal, :less, :less_equal]
168
+
169
+ @basic_arithmetic_operations [:add, :subtract, :multiply, :divide, :pow]
170
+ @other_arithmetic_operations [:quotient, :remainder]
171
+
172
+ @aggregation_operations [
173
+ :sum,
174
+ :min,
175
+ :max,
176
+ :argmin,
177
+ :argmax,
178
+ :mean,
179
+ :median,
180
+ :mode,
181
+ :count,
182
+ :product,
183
+ :nil_count,
184
+ :size,
185
+ :first,
186
+ :last,
187
+ :n_distinct
188
+ ]
189
+
190
+ @window_fun_operations [
191
+ :window_max,
192
+ :window_mean,
193
+ :window_median,
194
+ :window_min,
195
+ :window_sum
196
+ ]
197
+ @cumulative_operations [
198
+ :cumulative_max,
199
+ :cumulative_min,
200
+ :cumulative_sum,
201
+ :cumulative_product
202
+ ]
203
+
204
+ @float_predicates [:is_finite, :is_infinite, :is_nan]
205
+
206
+ # Used only internally to build new series as we go.
207
+ defp new(op, args, dtype, aggregation \\ false) do
208
+ dtype = Explorer.Shared.normalise_dtype!(dtype)
209
+
210
+ {backend, resource} =
211
+ Enum.find_value(args, {nil, nil}, fn
212
+ %__MODULE__{backend: backend, resource: resource} when backend != nil ->
213
+ {backend, resource}
214
+
215
+ _other ->
216
+ nil
217
+ end)
218
+
219
+ %__MODULE__{
220
+ op: op,
221
+ args: args,
222
+ dtype: dtype,
223
+ backend: backend,
224
+ resource: resource,
225
+ aggregation: aggregation
226
+ }
227
+ end
228
+
229
+ @doc false
230
+ # This is called from places where we want to start a new lazy series
231
+ # and it has a backend that owns it.
232
+ def backed(op, args, dtype, resource, backend) do
233
+ dtype = Explorer.Shared.normalise_dtype!(dtype)
234
+ %__MODULE__{op: op, args: args, dtype: dtype, backend: backend, resource: resource}
235
+ end
236
+
237
+ @doc false
238
+ # This is called from places where we want to start a new lazy series
239
+ # and it has no backend that owns it.
240
+ def unbacked(op, args, dtype) do
241
+ dtype = Explorer.Shared.normalise_dtype!(dtype)
242
+ %__MODULE__{op: op, args: args, dtype: dtype}
243
+ end
244
+
245
+ @doc false
246
+ def operations, do: @operations
247
+
248
+ @impl true
249
+ # When performing lazy operations, we should only have a single
250
+ # LazySeries with a resource, it is not possible to operate on
251
+ # different lazy series from different nodes, and
252
+ # Explorer.Shared.apply_series was written such that a LazySeries
253
+ # always wins. This means LazySeries can have references, but
254
+ # operations will always run on the node with the LazySeries,
255
+ # so they never have to be imported/exported.
256
+ def owner_reference(s), do: s.data.resource
257
+
258
+ @impl true
259
+ def cast(%Series{} = s, dtype) do
260
+ args = [lazy_series!(s), dtype]
261
+ data = new(:cast, args, dtype, aggregations?(args))
262
+ Backend.Series.new(data, dtype)
263
+ end
264
+
265
+ @impl true
266
+ def from_list(list, dtype) when is_list(list) do
267
+ data = new(:from_list, [list, dtype], dtype, false)
268
+
269
+ Backend.Series.new(data, dtype)
270
+ end
271
+
272
+ @impl true
273
+ def from_binary(binary, dtype) when is_binary(binary) do
274
+ data = new(:from_binary, [binary, dtype], dtype, false)
275
+ Backend.Series.new(data, dtype)
276
+ end
277
+
278
+ @impl true
279
+ def reverse(%Series{} = s) do
280
+ args = [lazy_series!(s)]
281
+ data = new(:reverse, args, s.dtype, aggregations?(args))
282
+
283
+ Backend.Series.new(data, s.dtype)
284
+ end
285
+
286
+ @impl true
287
+ def argsort(%Series{} = s, descending?, maintain_order?, multithreaded?, nulls_last?) do
288
+ args = [lazy_series!(s), descending?, maintain_order?, multithreaded?, nulls_last?]
289
+ data = new(:argsort, args, {:u, 32}, aggregations?(args))
290
+
291
+ Backend.Series.new(data, {:u, 32})
292
+ end
293
+
294
+ @impl true
295
+ def sort(%Series{} = s, descending?, maintain_order?, multithreaded?, nulls_last?) do
296
+ args = [lazy_series!(s), descending?, maintain_order?, multithreaded?, nulls_last?]
297
+ data = new(:sort, args, s.dtype, aggregations?(args))
298
+
299
+ Backend.Series.new(data, s.dtype)
300
+ end
301
+
302
+ @impl true
303
+ def distinct(%Series{} = s) do
304
+ args = [lazy_series!(s)]
305
+ data = new(:distinct, args, s.dtype, aggregations?(args))
306
+
307
+ Backend.Series.new(data, s.dtype)
308
+ end
309
+
310
+ @impl true
311
+ def unordered_distinct(%Series{} = s) do
312
+ args = [lazy_series!(s)]
313
+ data = new(:unordered_distinct, args, s.dtype, aggregations?(args))
314
+
315
+ Backend.Series.new(data, s.dtype)
316
+ end
317
+
318
+ @impl true
319
+ def slice(%Series{} = s, offset, length) do
320
+ args = [lazy_series!(s), offset, length]
321
+ data = new(:slice, args, s.dtype, aggregations?(args))
322
+
323
+ Backend.Series.new(data, s.dtype)
324
+ end
325
+
326
+ @impl true
327
+ def slice(%Series{} = s, indices) when is_list(indices) do
328
+ args = [lazy_series!(s), indices]
329
+ data = new(:slice, args, s.dtype, aggregations?(args))
330
+
331
+ Backend.Series.new(data, s.dtype)
332
+ end
333
+
334
+ @impl true
335
+ def slice(%Series{} = s, %Series{} = indices) do
336
+ args = [lazy_series!(s), series_or_lazy_series!(indices)]
337
+ data = new(:slice, args, s.dtype, aggregations?(args))
338
+
339
+ Backend.Series.new(data, s.dtype)
340
+ end
341
+
342
+ @impl true
343
+ def head(%Series{} = s, length) do
344
+ args = [lazy_series!(s), length]
345
+ data = new(:head, args, s.dtype, aggregations?(args))
346
+
347
+ Backend.Series.new(data, s.dtype)
348
+ end
349
+
350
+ @impl true
351
+ def tail(%Series{} = s, length) do
352
+ args = [lazy_series!(s), length]
353
+ data = new(:tail, args, s.dtype, aggregations?(args))
354
+
355
+ Backend.Series.new(data, s.dtype)
356
+ end
357
+
358
+ @impl true
359
+ def shift(%Series{} = s, offset, default) do
360
+ args = [lazy_series!(s), offset, default]
361
+ data = new(:shift, args, s.dtype, aggregations?(args))
362
+
363
+ Backend.Series.new(data, s.dtype)
364
+ end
365
+
366
+ @impl true
367
+ def peaks(%Series{} = s, min_or_max) when is_atom(min_or_max) do
368
+ args = [lazy_series!(s), Atom.to_string(min_or_max)]
369
+ data = new(:peaks, args, :boolean, aggregations?(args))
370
+
371
+ Backend.Series.new(data, :boolean)
372
+ end
373
+
374
+ @impl true
375
+ def fill_missing_with_strategy(%Series{} = s, strategy) do
376
+ args = [lazy_series!(s), strategy]
377
+ dtype = if strategy == :mean, do: {:f, 64}, else: s.dtype
378
+ data = new(:fill_missing_with_strategy, args, dtype, aggregations?(args))
379
+ Backend.Series.new(data, dtype)
380
+ end
381
+
382
+ @impl true
383
+ def fill_missing_with_value(%Series{} = s, value) do
384
+ args = [lazy_series!(s), value]
385
+ data = new(:fill_missing_with_value, args, s.dtype, aggregations?(args))
386
+
387
+ Backend.Series.new(data, s.dtype)
388
+ end
389
+
390
+ @impl true
391
+ def sample(%Series{} = s, n, replacement, shuffle, seed) when is_integer(n) do
392
+ args = [lazy_series!(s), n, replacement, shuffle, seed]
393
+ data = new(:sample_n, args, s.dtype, aggregations?(args))
394
+
395
+ Backend.Series.new(data, s.dtype)
396
+ end
397
+
398
+ @impl true
399
+ def sample(%Series{} = s, frac, replacement, shuffle, seed) when is_float(frac) do
400
+ args = [lazy_series!(s), frac, replacement, shuffle, seed]
401
+ data = new(:sample_frac, args, s.dtype, aggregations?(args))
402
+
403
+ Backend.Series.new(data, s.dtype)
404
+ end
405
+
406
+ # Implements all the comparison operations that
407
+ # accepts Series or number on both sides.
408
+ #
409
+ # It also handles the case for binaries and strings, creating
410
+ # a one element series when binaries are present on either sides.
411
+ for op <- @comparison_operations do
412
+ @impl true
413
+ def unquote(op)(left, right) do
414
+ args = binary_args(left, right)
415
+ data = new(unquote(op), args, :boolean, aggregations?(args))
416
+
417
+ Backend.Series.new(data, :boolean)
418
+ end
419
+ end
420
+
421
+ defp binary_args(left, right) do
422
+ case {left, right} do
423
+ {%Series{}, %Series{}} ->
424
+ [data!(left), data!(right)]
425
+
426
+ {%Series{dtype: dtype}, value}
427
+ when dtype in [:binary, :string, :category] and is_binary(value) ->
428
+ [data!(left), from_list([value], dtype).data]
429
+
430
+ {value, %Series{dtype: dtype}}
431
+ when dtype in [:binary, :string, :category] and is_binary(value) ->
432
+ [from_list([value], dtype).data, data!(right)]
433
+
434
+ {%Series{}, other} ->
435
+ [data!(left), other]
436
+
437
+ {other, %Series{}} ->
438
+ [other, data!(right)]
439
+ end
440
+ end
441
+
442
+ # These are also comparison operations, but they only accept `Series`.
443
+ for op <- [:binary_and, :binary_or, :binary_in] do
444
+ @impl true
445
+ def unquote(op)(%Series{} = left, %Series{} = right) do
446
+ args = [series_or_lazy_series!(left), series_or_lazy_series!(right)]
447
+ data = new(unquote(op), args, :boolean, aggregations?(args))
448
+
449
+ Backend.Series.new(data, :boolean)
450
+ end
451
+ end
452
+
453
+ for op <- @basic_arithmetic_operations do
454
+ @impl true
455
+ def unquote(op)(dtype, %Series{} = left, %Series{} = right) do
456
+ args = [data!(left), data!(right)]
457
+ data = new(unquote(op), args, dtype, aggregations?(args))
458
+
459
+ Backend.Series.new(data, dtype)
460
+ end
461
+ end
462
+
463
+ for op <- @other_arithmetic_operations do
464
+ @impl true
465
+ def unquote(op)(left, right) do
466
+ dtype = resolve_numeric_dtype([left, right])
467
+
468
+ args = [data!(left), data!(right)]
469
+ data = new(unquote(op), args, dtype, aggregations?(args))
470
+
471
+ Backend.Series.new(data, dtype)
472
+ end
473
+ end
474
+
475
+ for op <- @aggregation_operations do
476
+ @impl true
477
+ def unquote(op)(%Series{} = series) do
478
+ args = [lazy_series!(series)]
479
+ dtype = dtype_for_agg_operation(unquote(op), series)
480
+ data = new(unquote(op), args, dtype, true)
481
+
482
+ Backend.Series.new(data, dtype)
483
+ end
484
+ end
485
+
486
+ for op <- @window_fun_operations do
487
+ @impl true
488
+ def unquote(op)(%Series{} = series, window_size, weights, min_periods, center) do
489
+ args = [lazy_series!(series), window_size, weights, min_periods, center]
490
+
491
+ if aggregations?(args), do: raise_agg_inside_window(unquote(op))
492
+
493
+ dtype = resolve_numeric_dtype(unquote(op), [series | List.wrap(weights)])
494
+
495
+ data = new(unquote(op), args, dtype, false)
496
+
497
+ Backend.Series.new(data, dtype)
498
+ end
499
+ end
500
+
501
+ @impl true
502
+ def window_standard_deviation(%Series{} = series, window_size, weights, min_periods, center) do
503
+ args = [lazy_series!(series), window_size, weights, min_periods, center]
504
+
505
+ if aggregations?(args), do: raise_agg_inside_window(:window_standard_deviation)
506
+
507
+ data = new(:window_standard_deviation, args, {:f, 64}, false)
508
+
509
+ Backend.Series.new(data, {:f, 64})
510
+ end
511
+
512
+ for op <- @cumulative_operations do
513
+ @impl true
514
+ def unquote(op)(%Series{} = series, reverse) do
515
+ args = [lazy_series!(series), reverse]
516
+
517
+ if aggregations?(args), do: raise_agg_inside_window(unquote(op))
518
+
519
+ data = new(unquote(op), args, series.dtype, false)
520
+
521
+ Backend.Series.new(data, series.dtype)
522
+ end
523
+ end
524
+
525
+ for predicate <- @float_predicates do
526
+ @impl true
527
+ def unquote(predicate)(%Series{} = series) do
528
+ data = new(unquote(predicate), [lazy_series!(series)], :boolean)
529
+
530
+ Backend.Series.new(data, :boolean)
531
+ end
532
+ end
533
+
534
+ defp raise_agg_inside_window(op) do
535
+ raise "it's not possible to have an aggregation operation inside #{inspect(op)}, " <>
536
+ "which is a window function"
537
+ end
538
+
539
+ @impl true
540
+ def quantile(%Series{} = series, float) when is_float(float) do
541
+ args = [lazy_series!(series), float]
542
+ # According to https://github.com/pola-rs/polars/issues/4796,
543
+ # it's expected that quantile returns float for integer columns.
544
+ dtype =
545
+ if series.dtype in Explorer.Shared.integer_types() do
546
+ {:f, 64}
547
+ else
548
+ series.dtype
549
+ end
550
+
551
+ data = new(:quantile, args, dtype, true)
552
+
553
+ Backend.Series.new(data, dtype)
554
+ end
555
+
556
+ @impl true
557
+ def rank(%Series{} = series, method, descending, seed) do
558
+ args = [series_or_lazy_series!(series), method, descending, seed]
559
+
560
+ target_dtype =
561
+ if method == :ordinal do
562
+ {:u, 32}
563
+ else
564
+ series.dtype
565
+ end
566
+
567
+ data = new(:rank, args, target_dtype, true)
568
+
569
+ Backend.Series.new(data, target_dtype)
570
+ end
571
+
572
+ @impl true
573
+ def skew(%Series{} = series, bias) do
574
+ args = [series_or_lazy_series!(series), bias]
575
+ data = new(:skew, args, {:f, 64}, true)
576
+
577
+ Backend.Series.new(data, {:f, 64})
578
+ end
579
+
580
+ @impl true
581
+ def correlation(%Series{} = left, %Series{} = right, ddof, method) do
582
+ args = [series_or_lazy_series!(left), series_or_lazy_series!(right), ddof, method]
583
+ data = new(:correlation, args, {:f, 64}, true)
584
+
585
+ Backend.Series.new(data, {:f, 64})
586
+ end
587
+
588
+ @impl true
589
+ def covariance(%Series{} = left, %Series{} = right, ddof \\ 1) do
590
+ args = [series_or_lazy_series!(left), series_or_lazy_series!(right), ddof]
591
+ data = new(:covariance, args, {:f, 64}, true)
592
+
593
+ Backend.Series.new(data, {:f, 64})
594
+ end
595
+
596
+ @impl true
597
+ def variance(%Series{} = s, ddof \\ 1) do
598
+ args = [series_or_lazy_series!(s), ddof]
599
+ data = new(:variance, args, {:f, 64}, true)
600
+
601
+ Backend.Series.new(data, {:f, 64})
602
+ end
603
+
604
+ @impl true
605
+ def standard_deviation(%Series{} = s, ddof \\ 1) do
606
+ args = [series_or_lazy_series!(s), ddof]
607
+ data = new(:standard_deviation, args, {:f, 64}, true)
608
+
609
+ Backend.Series.new(data, {:f, 64})
610
+ end
611
+
612
+ @impl true
613
+ def all?(%Series{} = s) do
614
+ args = [series_or_lazy_series!(s)]
615
+
616
+ data = new(:all, args, :boolean, true)
617
+
618
+ Backend.Series.new(data, :boolean)
619
+ end
620
+
621
+ @impl true
622
+ def any?(%Series{} = s) do
623
+ args = [series_or_lazy_series!(s)]
624
+
625
+ data = new(:any, args, :boolean, true)
626
+
627
+ Backend.Series.new(data, :boolean)
628
+ end
629
+
630
+ @impl true
631
+ def coalesce(%Series{} = left, %Series{} = right) do
632
+ args = [series_or_lazy_series!(left), series_or_lazy_series!(right)]
633
+
634
+ dtype =
635
+ if left.dtype in Explorer.Shared.numeric_types() do
636
+ resolve_numeric_dtype([left, right])
637
+ else
638
+ left.dtype
639
+ end
640
+
641
+ data = new(:coalesce, args, dtype, aggregations?(args))
642
+
643
+ Backend.Series.new(data, dtype)
644
+ end
645
+
646
+ @impl true
647
+ def select(%Series{} = predicate, %{dtype: dtype} = on_true, on_false) do
648
+ args = [series_or_lazy_series!(predicate) | binary_args(on_true, on_false)]
649
+
650
+ dtype =
651
+ if dtype in Explorer.Shared.numeric_types() do
652
+ resolve_numeric_dtype([on_true, on_false])
653
+ else
654
+ dtype
655
+ end
656
+
657
+ data = new(:select, args, dtype, aggregations?(args))
658
+
659
+ Backend.Series.new(data, dtype)
660
+ end
661
+
662
+ @impl true
663
+ def format(list) do
664
+ series_list =
665
+ Enum.map(list, fn
666
+ s when is_binary(s) -> s
667
+ s -> series_or_lazy_series!(s)
668
+ end)
669
+
670
+ data = new(:format, [series_list], :string, aggregations?(series_list))
671
+
672
+ Backend.Series.new(data, :string)
673
+ end
674
+
675
+ @impl true
676
+ def concat([%Series{} = head | _tail] = series) do
677
+ series_list = Enum.map(series, &series_or_lazy_series!/1)
678
+ data = new(:concat, [series_list], head.dtype, aggregations?(series_list))
679
+
680
+ Backend.Series.new(data, head.dtype)
681
+ end
682
+
683
+ @impl true
684
+ def day_of_week(%Series{} = s) do
685
+ data = new(:day_of_week, [lazy_series!(s)], {:s, 8})
686
+
687
+ Backend.Series.new(data, {:s, 8})
688
+ end
689
+
690
+ @impl true
691
+ def day_of_year(%Series{} = s) do
692
+ data = new(:day_of_year, [lazy_series!(s)], {:s, 16})
693
+
694
+ Backend.Series.new(data, {:s, 16})
695
+ end
696
+
697
+ @impl true
698
+ def week_of_year(%Series{} = s) do
699
+ data = new(:week_of_year, [lazy_series!(s)], {:s, 8})
700
+
701
+ Backend.Series.new(data, {:s, 8})
702
+ end
703
+
704
+ @impl true
705
+ def month(%Series{} = s) do
706
+ data = new(:month, [lazy_series!(s)], {:s, 8})
707
+
708
+ Backend.Series.new(data, {:s, 8})
709
+ end
710
+
711
+ @impl true
712
+ def year(%Series{} = s) do
713
+ data = new(:year, [lazy_series!(s)], {:s, 32})
714
+
715
+ Backend.Series.new(data, {:s, 32})
716
+ end
717
+
718
+ @impl true
719
+ def hour(%Series{} = s) do
720
+ data = new(:hour, [lazy_series!(s)], {:s, 8})
721
+
722
+ Backend.Series.new(data, {:s, 8})
723
+ end
724
+
725
+ @impl true
726
+ def minute(%Series{} = s) do
727
+ data = new(:minute, [lazy_series!(s)], {:s, 8})
728
+
729
+ Backend.Series.new(data, {:s, 8})
730
+ end
731
+
732
+ @impl true
733
+ def second(%Series{} = s) do
734
+ data = new(:second, [lazy_series!(s)], {:s, 8})
735
+
736
+ Backend.Series.new(data, {:s, 8})
737
+ end
738
+
739
+ @impl true
740
+ def ewm_mean(%Series{} = series, alpha, adjust, min_periods, ignore_nils) do
741
+ args = [lazy_series!(series), alpha, adjust, min_periods, ignore_nils]
742
+
743
+ if aggregations?(args), do: raise_agg_inside_window(:ewm_mean)
744
+
745
+ data = new(:ewm_mean, args, {:f, 64}, false)
746
+
747
+ Backend.Series.new(data, {:f, 64})
748
+ end
749
+
750
+ @impl true
751
+ def ewm_standard_deviation(%Series{} = series, alpha, adjust, bias, min_periods, ignore_nils) do
752
+ args = [lazy_series!(series), alpha, adjust, bias, min_periods, ignore_nils]
753
+
754
+ if aggregations?(args), do: raise_agg_inside_window(:ewm_standard_deviation)
755
+
756
+ data = new(:ewm_standard_deviation, args, {:f, 64}, false)
757
+
758
+ Backend.Series.new(data, {:f, 64})
759
+ end
760
+
761
+ @impl true
762
+ def ewm_variance(%Series{} = series, alpha, adjust, bias, min_periods, ignore_nils) do
763
+ args = [lazy_series!(series), alpha, adjust, bias, min_periods, ignore_nils]
764
+
765
+ if aggregations?(args), do: raise_agg_inside_window(:ewm_variance)
766
+
767
+ data = new(:ewm_variance, args, {:f, 64}, false)
768
+
769
+ Backend.Series.new(data, {:f, 64})
770
+ end
771
+
772
+ defp dtype_for_agg_operation(op, _)
773
+ when op in [:count, :nil_count, :size, :n_distinct, :argmin, :argmax],
774
+ do: {:u, 32}
775
+
776
+ defp dtype_for_agg_operation(op, series)
777
+ when op in [:first, :last, :sum, :min, :max, :product],
778
+ do: series.dtype
779
+
780
+ defp dtype_for_agg_operation(op, _) when op in [:all?, :any?], do: :boolean
781
+ defp dtype_for_agg_operation(:mode, series), do: {:list, series.dtype}
782
+
783
+ defp dtype_for_agg_operation(_, _), do: {:f, 64}
784
+
785
+ defp resolve_numeric_dtype(items) do
786
+ dtypes =
787
+ for item <- items, uniq: true do
788
+ case item do
789
+ %Series{dtype: dtype} -> dtype
790
+ other -> Explorer.Shared.dtype_from_list!([other])
791
+ end
792
+ end
793
+
794
+ case dtypes do
795
+ [dtype] ->
796
+ if dtype in Explorer.Shared.numeric_types() do
797
+ dtype
798
+ else
799
+ raise "invalid dtype for numeric items: #{inspect(dtype)}"
800
+ end
801
+
802
+ [_, _] ->
803
+ {:f, 64}
804
+ end
805
+ end
806
+
807
+ defp resolve_numeric_dtype(:window_mean, _items), do: {:f, 64}
808
+ defp resolve_numeric_dtype(_op, items), do: resolve_numeric_dtype(items)
809
+
810
+ # Returns the inner `data` if it's a lazy series. Otherwise raises an error.
811
+ defp lazy_series!(series) do
812
+ case series do
813
+ %Series{data: %__MODULE__{} = data} ->
814
+ data
815
+
816
+ %Series{} ->
817
+ raise ArgumentError, "expecting a LazySeries, but instead got #{inspect(series)}"
818
+ end
819
+ end
820
+
821
+ defp series_or_lazy_series!(%Series{} = series), do: data!(series)
822
+
823
+ defp data!(%Series{data: %__MODULE__{} = data}), do: data
824
+ defp data!(value), do: value
825
+
826
+ defp aggregations?(args) do
827
+ Enum.any?(args, fn
828
+ %__MODULE__{aggregation: is_agg} -> is_agg
829
+ _other -> false
830
+ end)
831
+ end
832
+
833
+ @impl true
834
+ def is_nil(%Series{} = series) do
835
+ data = new(:is_nil, [lazy_series!(series)], :boolean)
836
+
837
+ Backend.Series.new(data, :boolean)
838
+ end
839
+
840
+ @impl true
841
+ def is_not_nil(%Series{} = series) do
842
+ data = new(:is_not_nil, [lazy_series!(series)], :boolean)
843
+
844
+ Backend.Series.new(data, :boolean)
845
+ end
846
+
847
+ @impl true
848
+ def all_equal(%Series{} = left, %Series{} = right) do
849
+ args = [lazy_series!(left), lazy_series!(right)]
850
+ data = new(:all_equal, args, :boolean, aggregations?(args))
851
+
852
+ Backend.Series.new(data, :boolean)
853
+ end
854
+
855
+ @impl true
856
+ def unary_not(%Series{} = series) do
857
+ data = new(:unary_not, [lazy_series!(series)], :boolean)
858
+
859
+ Backend.Series.new(data, :boolean)
860
+ end
861
+
862
+ @impl true
863
+ def log(%Series{} = series) do
864
+ data = new(:log, [lazy_series!(series)], {:f, 64})
865
+
866
+ Backend.Series.new(data, {:f, 64})
867
+ end
868
+
869
+ @impl true
870
+ def log(%Series{} = series, base) do
871
+ data = new(:log, [lazy_series!(series), base], {:f, 64})
872
+
873
+ Backend.Series.new(data, {:f, 64})
874
+ end
875
+
876
+ @impl true
877
+ def exp(%Series{} = series) do
878
+ data = new(:exp, [lazy_series!(series)], {:f, 64})
879
+
880
+ Backend.Series.new(data, {:f, 64})
881
+ end
882
+
883
+ @impl true
884
+ def abs(%Series{} = series) do
885
+ data = new(:abs, [lazy_series!(series)], series.dtype)
886
+
887
+ Backend.Series.new(data, series.dtype)
888
+ end
889
+
890
+ @impl true
891
+ def strptime(%Series{} = series, format_string) do
892
+ dtype = {:naive_datetime, :microsecond}
893
+ data = new(:strptime, [lazy_series!(series), format_string], dtype)
894
+
895
+ Backend.Series.new(data, dtype)
896
+ end
897
+
898
+ @impl true
899
+ def strftime(%Series{} = series, format_string) do
900
+ dtype = :string
901
+ data = new(:strftime, [lazy_series!(series), format_string], dtype)
902
+
903
+ Backend.Series.new(data, dtype)
904
+ end
905
+
906
+ @impl true
907
+ def clip(%Series{dtype: {s_or_u, _} = dtype} = series, min, max)
908
+ when s_or_u in [:s, :u] and is_integer(min) and is_integer(max) do
909
+ data = new(:clip_integer, [lazy_series!(series), min, max], dtype)
910
+
911
+ Backend.Series.new(data, dtype)
912
+ end
913
+
914
+ def clip(%Series{} = series, min, max) do
915
+ data = new(:clip_float, [lazy_series!(series), min * 1.0, max * 1.0], {:f, 64})
916
+
917
+ Backend.Series.new(data, {:f, 64})
918
+ end
919
+
920
+ @impl true
921
+ def sin(%Series{} = series) do
922
+ data = new(:sin, [lazy_series!(series)], {:f, 64})
923
+
924
+ Backend.Series.new(data, {:f, 64})
925
+ end
926
+
927
+ @impl true
928
+ def cos(%Series{} = series) do
929
+ data = new(:cos, [lazy_series!(series)], {:f, 64})
930
+
931
+ Backend.Series.new(data, {:f, 64})
932
+ end
933
+
934
+ @impl true
935
+ def tan(%Series{} = series) do
936
+ data = new(:tan, [lazy_series!(series)], {:f, 64})
937
+
938
+ Backend.Series.new(data, {:f, 64})
939
+ end
940
+
941
+ @impl true
942
+ def asin(%Series{} = series) do
943
+ data = new(:asin, [lazy_series!(series)], {:f, 64})
944
+
945
+ Backend.Series.new(data, {:f, 64})
946
+ end
947
+
948
+ @impl true
949
+ def acos(%Series{} = series) do
950
+ data = new(:acos, [lazy_series!(series)], {:f, 64})
951
+
952
+ Backend.Series.new(data, {:f, 64})
953
+ end
954
+
955
+ @impl true
956
+ def atan(%Series{} = series) do
957
+ data = new(:atan, [lazy_series!(series)], {:f, 64})
958
+
959
+ Backend.Series.new(data, {:f, 64})
960
+ end
961
+
962
+ @impl true
963
+ def inspect(series, opts) do
964
+ alias Inspect.Algebra, as: A
965
+
966
+ open = A.color("(", :list, opts)
967
+ close = A.color(")", :list, opts)
968
+
969
+ dtype =
970
+ series
971
+ |> Series.dtype()
972
+ |> Explorer.Shared.dtype_to_string()
973
+ |> A.color(:atom, opts)
974
+
975
+ A.concat([
976
+ A.color("LazySeries[???]", :atom, opts),
977
+ A.line(),
978
+ dtype,
979
+ " ",
980
+ open,
981
+ Code.quoted_to_algebra(to_elixir_ast(series.data)),
982
+ close
983
+ ])
984
+ end
985
+
986
+ @to_elixir_op %{
987
+ add: :+,
988
+ subtract: :-,
989
+ multiply: :*,
990
+ divide: :/,
991
+ pow: :**,
992
+ equal: :==,
993
+ not_equal: :!=,
994
+ greater: :>,
995
+ greater_equal: :>=,
996
+ less: :<,
997
+ less_equal: :<=,
998
+ binary_and: :and,
999
+ binary_or: :or,
1000
+ binary_in: :in,
1001
+ unary_not: :not
1002
+ }
1003
+
1004
+ defp to_elixir_ast(%__MODULE__{op: :from_list, args: [[single], _]}) do
1005
+ single
1006
+ end
1007
+
1008
+ defp to_elixir_ast(%__MODULE__{op: op, args: args}) do
1009
+ {Map.get(@to_elixir_op, op, op), [], Enum.map(args, &to_elixir_ast/1)}
1010
+ end
1011
+
1012
+ defp to_elixir_ast(%Series{} = series) do
1013
+ case Explorer.Series.size(series) do
1014
+ 1 -> series[0]
1015
+ _ -> series
1016
+ end
1017
+ end
1018
+
1019
+ defp to_elixir_ast(other), do: other
1020
+
1021
+ @impl true
1022
+ def size(series) do
1023
+ data = new(:size, [lazy_series!(series)], {:u, 32})
1024
+
1025
+ Backend.Series.new(data, {:u, 32})
1026
+ end
1027
+
1028
+ @impl true
1029
+ def transform(_series, _fun) do
1030
+ raise """
1031
+ #{unsupported(:transform, 2)}
1032
+
1033
+ If you want to transform a column, you must do so outside of a query.
1034
+ For example, instead of:
1035
+
1036
+ Explorer.DataFrame.mutate(df, new_column: transform(column, &String.upcase/1))
1037
+
1038
+ You must write:
1039
+
1040
+ Explorer.DataFrame.put(df, :new_column, Explorer.Series.transform(column, &String.upcase/1))
1041
+
1042
+ However, keep in mind that in such cases you are loading the data into Elixir and
1043
+ serializing it back, which may be expensive for large datasets
1044
+ """
1045
+ end
1046
+
1047
+ @impl true
1048
+ def contains(series, substring) do
1049
+ data = new(:contains, [lazy_series!(series), substring], :boolean)
1050
+
1051
+ Backend.Series.new(data, :boolean)
1052
+ end
1053
+
1054
+ @impl true
1055
+ def re_contains(series, pattern) do
1056
+ data = new(:re_contains, [lazy_series!(series), pattern], :boolean)
1057
+
1058
+ Backend.Series.new(data, :boolean)
1059
+ end
1060
+
1061
+ @impl true
1062
+ def upcase(series) do
1063
+ data = new(:upcase, [lazy_series!(series)], :string)
1064
+
1065
+ Backend.Series.new(data, :string)
1066
+ end
1067
+
1068
+ @impl true
1069
+ def downcase(series) do
1070
+ data = new(:downcase, [lazy_series!(series)], :string)
1071
+
1072
+ Backend.Series.new(data, :string)
1073
+ end
1074
+
1075
+ @impl true
1076
+ def replace(series, substring, replacement) do
1077
+ data = new(:replace, [lazy_series!(series), substring, replacement], :string)
1078
+
1079
+ Backend.Series.new(data, :string)
1080
+ end
1081
+
1082
+ @impl true
1083
+ def re_replace(series, pattern, replacement) do
1084
+ data = new(:re_replace, [lazy_series!(series), pattern, replacement], :string)
1085
+
1086
+ Backend.Series.new(data, :string)
1087
+ end
1088
+
1089
+ @impl true
1090
+ def strip(series, string) do
1091
+ data = new(:strip, [lazy_series!(series), string], :string)
1092
+ Backend.Series.new(data, :string)
1093
+ end
1094
+
1095
+ @impl true
1096
+ def lstrip(series, string) do
1097
+ data = new(:lstrip, [lazy_series!(series), string], :string)
1098
+
1099
+ Backend.Series.new(data, :string)
1100
+ end
1101
+
1102
+ @impl true
1103
+ def rstrip(series, string) do
1104
+ data = new(:rstrip, [lazy_series!(series), string], :string)
1105
+
1106
+ Backend.Series.new(data, :string)
1107
+ end
1108
+
1109
+ @impl true
1110
+ def substring(series, offset, length) do
1111
+ data = new(:substring, [lazy_series!(series), offset, length], :string)
1112
+
1113
+ Backend.Series.new(data, :string)
1114
+ end
1115
+
1116
+ @impl true
1117
+ def split(series, by) do
1118
+ data = new(:split, [lazy_series!(series), by], :string)
1119
+
1120
+ Backend.Series.new(data, {:list, :string})
1121
+ end
1122
+
1123
+ @impl true
1124
+ def split_into(series, by, fields) do
1125
+ data = new(:split_into, [lazy_series!(series), by, fields], :string)
1126
+
1127
+ Backend.Series.new(data, {:struct, Enum.map(fields, &{&1, :string})})
1128
+ end
1129
+
1130
+ @impl true
1131
+ def round(series, decimals) when is_integer(decimals) and decimals >= 0 do
1132
+ args = [lazy_series!(series), decimals]
1133
+ data = new(:round, args, {:f, 64}, aggregations?(args))
1134
+
1135
+ Backend.Series.new(data, {:f, 64})
1136
+ end
1137
+
1138
+ @impl true
1139
+ def floor(series) do
1140
+ args = [lazy_series!(series)]
1141
+ data = new(:floor, args, {:f, 64}, aggregations?(args))
1142
+
1143
+ Backend.Series.new(data, {:f, 64})
1144
+ end
1145
+
1146
+ @impl true
1147
+ def ceil(series) do
1148
+ args = [lazy_series!(series)]
1149
+ data = new(:ceil, args, {:f, 64}, aggregations?(args))
1150
+
1151
+ Backend.Series.new(data, {:f, 64})
1152
+ end
1153
+
1154
+ @impl true
1155
+ def join(series, separator) do
1156
+ data = new(:join, [lazy_series!(series), separator], {:list, :string})
1157
+
1158
+ Backend.Series.new(data, :string)
1159
+ end
1160
+
1161
+ @impl true
1162
+ def lengths(series) do
1163
+ data = new(:lengths, [lazy_series!(series)], {:u, 32})
1164
+
1165
+ Backend.Series.new(data, {:u, 32})
1166
+ end
1167
+
1168
+ @impl true
1169
+ def member?(%Series{dtype: {:list, inner_dtype}} = series, value) do
1170
+ data = new(:member, [lazy_series!(series), value, inner_dtype], :boolean)
1171
+
1172
+ Backend.Series.new(data, :boolean)
1173
+ end
1174
+
1175
+ @impl true
1176
+ def field(%Series{dtype: {:struct, inner_dtype}} = series, name) do
1177
+ {^name, dtype} = List.keyfind!(inner_dtype, name, 0)
1178
+ data = new(:field, [lazy_series!(series), name], dtype)
1179
+
1180
+ Backend.Series.new(data, dtype)
1181
+ end
1182
+
1183
+ @impl true
1184
+ def json_decode(series, dtype) do
1185
+ data = new(:json_decode, [lazy_series!(series), dtype], dtype)
1186
+
1187
+ Backend.Series.new(data, dtype)
1188
+ end
1189
+
1190
+ @impl true
1191
+ def json_path_match(series, json_path) do
1192
+ data = new(:json_path_match, [lazy_series!(series), json_path], :string)
1193
+
1194
+ Backend.Series.new(data, :string)
1195
+ end
1196
+
1197
+ @impl true
1198
+ def row_index(series) do
1199
+ data = new(:row_index, [lazy_series!(series)], {:u, 32})
1200
+
1201
+ Backend.Series.new(data, {:u, 32})
1202
+ end
1203
+
1204
+ @impl true
1205
+ def count_matches(series, substring) do
1206
+ data = new(:count_matches, [lazy_series!(series), substring], {:u, 32})
1207
+
1208
+ Backend.Series.new(data, {:u, 32})
1209
+ end
1210
+
1211
+ @impl true
1212
+ def re_count_matches(series, pattern) do
1213
+ data = new(:re_count_matches, [lazy_series!(series), pattern], {:u, 32})
1214
+
1215
+ Backend.Series.new(data, {:u, 32})
1216
+ end
1217
+
1218
+ @impl true
1219
+ def re_scan(series, pattern) do
1220
+ data = new(:re_scan, [lazy_series!(series), pattern], {:list, :string})
1221
+
1222
+ Backend.Series.new(data, {:list, :string})
1223
+ end
1224
+
1225
+ @impl true
1226
+ def re_named_captures(series, pattern) do
1227
+ lazy_s = lazy_series!(series)
1228
+
1229
+ backend = get_backend(lazy_s, "re_named_captures/2")
1230
+ target_dtype = backend.re_dtype(pattern)
1231
+
1232
+ data = new(:re_named_captures, [lazy_s, pattern], target_dtype)
1233
+
1234
+ Backend.Series.new(data, target_dtype)
1235
+ end
1236
+
1237
+ defp get_backend(%__MODULE__{} = lazy_series, function) do
1238
+ lazy_series.backend ||
1239
+ raise "cannot get backend from Explorer.Backend.LazySeries for `#{function}`"
1240
+ end
1241
+
1242
+ @remaining_non_lazy_operations [
1243
+ at: 2,
1244
+ at_every: 2,
1245
+ categories: 1,
1246
+ categorise: 2,
1247
+ cut: 7,
1248
+ frequencies: 1,
1249
+ qcut: 8,
1250
+ mask: 2,
1251
+ owner_import: 1,
1252
+ owner_export: 1,
1253
+ to_iovec: 1,
1254
+ to_list: 1
1255
+ ]
1256
+
1257
+ for {fun, arity} <- @remaining_non_lazy_operations do
1258
+ args = Macro.generate_arguments(arity, __MODULE__)
1259
+ @impl true
1260
+ def unquote(fun)(unquote_splicing(args)), do: raise(unsupported(unquote(fun), unquote(arity)))
1261
+ end
1262
+
1263
+ defp unsupported(fun, arity) do
1264
+ "cannot perform #{fun}/#{arity} operation on Explorer.Backend.LazySeries. " <>
1265
+ "Query operations work on lazy series and those support only a subset of series operations"
1266
+ end
1267
+ end
deps/explorer/lib/explorer/backend/query_frame.ex ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.Backend.QueryFrame do
2
+ @moduledoc """
3
+ Represents a lazy dataframe for building query expressions.
4
+
5
+ You may call `Explorer.Query.new` to create a query-backed dataframe.
6
+ The QueryFrame is available inside `filter_with`, `mutate_with`, and
7
+ similar. You cannot perform any operation on them except accessing
8
+ its underlying series.
9
+ """
10
+
11
+ alias Explorer.Backend
12
+ alias Explorer.Backend.LazySeries
13
+
14
+ defstruct dtypes: %{}, names: [], backend: nil, resource: nil
15
+
16
+ @type t :: %__MODULE__{
17
+ backend: module(),
18
+ dtypes: Backend.DataFrame.dtypes(),
19
+ names: Backend.DataFrame.column_name(),
20
+ resource: reference() | nil
21
+ }
22
+
23
+ @behaviour Backend.DataFrame
24
+
25
+ @doc false
26
+ def new(df) do
27
+ %module{} = df.data
28
+
29
+ Explorer.Backend.DataFrame.new(
30
+ %__MODULE__{
31
+ names: df.names,
32
+ dtypes: df.dtypes,
33
+ backend: module,
34
+ resource: module.owner_reference(df)
35
+ },
36
+ df.names,
37
+ df.dtypes
38
+ )
39
+ end
40
+
41
+ # We don't implement owner reference here because no
42
+ # cross node operations happen at the lazy frame level.
43
+ # Instead, we store the resource and we delegate them
44
+ # to the underlying lazy series.
45
+ @impl Backend.DataFrame
46
+ def owner_reference(_), do: nil
47
+
48
+ @impl Backend.DataFrame
49
+ def lazy, do: __MODULE__
50
+
51
+ @impl Backend.DataFrame
52
+ def lazy(ldf), do: ldf
53
+
54
+ @impl Backend.DataFrame
55
+ def inspect(ldf, opts) do
56
+ import Inspect.Algebra
57
+
58
+ open = color("[", :list, opts)
59
+ close = color("]", :list, opts)
60
+
61
+ dtypes = ldf.data.dtypes
62
+
63
+ cols_algebra =
64
+ for name <- ldf.data.names do
65
+ concat([
66
+ line(),
67
+ color("#{name} ", :map, opts),
68
+ color("#{Explorer.Shared.dtype_to_string(dtypes[name])}", :atom, opts)
69
+ ])
70
+ end
71
+
72
+ concat([
73
+ color("QueryFrame", :atom, opts),
74
+ open,
75
+ "??? x #{length(cols_algebra)}",
76
+ close,
77
+ groups_algebra(ldf.groups, opts) | cols_algebra
78
+ ])
79
+ end
80
+
81
+ defp groups_algebra([_ | _] = groups, opts),
82
+ do:
83
+ Inspect.Algebra.concat([
84
+ Inspect.Algebra.line(),
85
+ Inspect.Algebra.color("Groups: ", :atom, opts),
86
+ Inspect.Algebra.to_doc(groups, opts)
87
+ ])
88
+
89
+ defp groups_algebra([], _), do: ""
90
+
91
+ @impl Backend.DataFrame
92
+ def pull(%{data: data, dtypes: dtypes}, column) do
93
+ dtype_for_column = dtypes[column]
94
+
95
+ data = LazySeries.backed(:column, [column], dtype_for_column, data.resource, data.backend)
96
+
97
+ Backend.Series.new(data, dtype_for_column)
98
+ end
99
+
100
+ funs =
101
+ Backend.DataFrame.behaviour_info(:callbacks) --
102
+ (Backend.DataFrame.behaviour_info(:optional_callbacks) ++
103
+ Module.definitions_in(__MODULE__, :def))
104
+
105
+ for {fun, arity} <- funs do
106
+ args = Macro.generate_arguments(arity, __MODULE__)
107
+
108
+ @impl Backend.DataFrame
109
+ def unquote(fun)(unquote_splicing(args)) do
110
+ raise """
111
+ cannot perform operation #{unquote(fun)} on Explorer.Backend.QueryFrame.
112
+
113
+ The QueryFrame is available inside filter_with, mutate_with, and \
114
+ similar and they support only a limited subset of the Series API
115
+ """
116
+ end
117
+ end
118
+ end
deps/explorer/lib/explorer/backend/series.ex ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.Backend.Series do
2
+ @moduledoc """
3
+ The behaviour for series backends.
4
+ """
5
+
6
+ @type t :: struct()
7
+
8
+ @type s :: Explorer.Series.t()
9
+ @type lazy_s :: Explorer.Series.lazy_t()
10
+ @type df :: Explorer.DataFrame.t()
11
+ @type dtype :: Explorer.Series.dtype()
12
+
13
+ @type valid_types ::
14
+ number()
15
+ | boolean()
16
+ | String.t()
17
+ | Date.t()
18
+ | Time.t()
19
+ | NaiveDateTime.t()
20
+ | Explorer.Duration.t()
21
+ | Decimal.t()
22
+
23
+ @type non_finite :: Explorer.Series.non_finite()
24
+ @type option(type) :: type | nil
25
+ @type io_result(t) :: {:ok, t} | {:error, Exception.t()}
26
+
27
+ # Conversion
28
+
29
+ @callback from_list(list(), dtype()) :: s
30
+ @callback from_binary(binary(), dtype()) :: s
31
+ @callback to_list(s) :: list()
32
+ @callback to_iovec(s) :: [binary()]
33
+ @callback cast(s, dtype) :: s
34
+ @callback categorise(s, s) :: s
35
+ @callback strptime(s, String.t()) :: s
36
+ @callback strftime(s, String.t()) :: s
37
+
38
+ # Ownership
39
+
40
+ @callback owner_reference(s) :: reference() | nil
41
+ @callback owner_import(term()) :: io_result(s)
42
+ @callback owner_export(s) :: io_result(term())
43
+
44
+ # Introspection
45
+
46
+ @callback size(s) :: non_neg_integer() | lazy_s()
47
+ @callback inspect(s, opts :: Inspect.Opts.t()) :: Inspect.Algebra.t()
48
+ @callback categories(s) :: s
49
+
50
+ # Slice and dice
51
+
52
+ @callback head(s, n :: integer()) :: s
53
+ @callback tail(s, n :: integer()) :: s
54
+ @callback sample(
55
+ s,
56
+ n_or_frac :: number(),
57
+ replacement :: boolean(),
58
+ shuffle :: boolean(),
59
+ seed :: option(integer())
60
+ ) :: s
61
+ @callback at(s, idx :: integer()) :: s
62
+ @callback at_every(s, integer()) :: s
63
+ @callback mask(s, mask :: s) :: s
64
+ @callback slice(s, indices :: list() | s()) :: s
65
+ @callback slice(s, offset :: integer(), length :: integer()) :: s
66
+ @callback format(list(s)) :: s
67
+ @callback concat(list(s)) :: s
68
+ @callback coalesce(s, s) :: s
69
+ @callback first(s) :: valid_types() | lazy_s()
70
+ @callback last(s) :: valid_types() | lazy_s()
71
+ @callback select(predicate :: s, s, s) :: s
72
+ @callback shift(s, offset :: integer, default :: nil) :: s
73
+ @callback rank(
74
+ s,
75
+ method :: atom(),
76
+ descending :: boolean(),
77
+ seed :: option(integer())
78
+ ) :: s | lazy_s()
79
+ # Aggregation
80
+
81
+ @callback count(s) :: number() | lazy_s()
82
+ @callback sum(s) :: number() | non_finite() | lazy_s() | nil
83
+ @callback min(s) :: number() | non_finite() | Date.t() | NaiveDateTime.t() | lazy_s() | nil
84
+ @callback max(s) :: number() | non_finite() | Date.t() | NaiveDateTime.t() | lazy_s() | nil
85
+ @callback argmin(s) :: number() | non_finite() | lazy_s() | nil
86
+ @callback argmax(s) :: number() | non_finite() | lazy_s() | nil
87
+ @callback mean(s) :: float() | non_finite() | lazy_s() | nil
88
+ @callback median(s) :: float() | non_finite() | lazy_s() | nil
89
+ @callback mode(s) :: s | lazy_s()
90
+ @callback variance(s, ddof :: non_neg_integer()) :: float() | non_finite() | lazy_s() | nil
91
+ @callback standard_deviation(s, ddof :: non_neg_integer()) ::
92
+ float() | non_finite() | lazy_s() | nil
93
+ @callback quantile(s, float()) ::
94
+ number() | non_finite() | Date.t() | NaiveDateTime.t() | lazy_s() | nil
95
+ @callback nil_count(s) :: number() | lazy_s()
96
+ @callback product(s) :: float() | non_finite() | lazy_s() | nil
97
+ @callback skew(s, bias? :: boolean()) :: float() | non_finite() | lazy_s() | nil
98
+ @callback correlation(s, s, ddof :: non_neg_integer(), method :: atom()) ::
99
+ float() | non_finite() | lazy_s() | nil
100
+ @callback covariance(s, s, ddof :: non_neg_integer()) :: float() | non_finite() | lazy_s() | nil
101
+ @callback all?(s) :: boolean() | lazy_s()
102
+ @callback any?(s) :: boolean() | lazy_s()
103
+ @callback row_index(s) :: s | lazy_s()
104
+
105
+ # Cumulative
106
+
107
+ @callback cumulative_max(s, reverse? :: boolean()) :: s
108
+ @callback cumulative_min(s, reverse? :: boolean()) :: s
109
+ @callback cumulative_sum(s, reverse? :: boolean()) :: s
110
+ @callback cumulative_product(s, reverse? :: boolean()) :: s
111
+
112
+ # Local minima/maxima
113
+
114
+ @callback peaks(s, :max | :min) :: s
115
+
116
+ # Arithmetic
117
+
118
+ @callback add(out_dtype :: dtype(), s, s) :: s
119
+ @callback subtract(out_dtype :: dtype(), s, s) :: s
120
+ @callback multiply(out_dtype :: dtype(), s, s) :: s
121
+ @callback divide(out_dtype :: dtype(), s, s) :: s
122
+ @callback quotient(s, s) :: s
123
+ @callback remainder(s, s) :: s
124
+ @callback pow(out_dtype :: dtype(), s, s) :: s
125
+ @callback log(argument :: s) :: s
126
+ @callback log(argument :: s, base :: float()) :: s
127
+ @callback exp(s) :: s
128
+ @callback abs(s) :: s
129
+ @callback clip(s, number(), number()) :: s
130
+
131
+ # Trigonometry
132
+
133
+ @callback acos(s) :: s
134
+ @callback asin(s) :: s
135
+ @callback atan(s) :: s
136
+ @callback cos(s) :: s
137
+ @callback sin(s) :: s
138
+ @callback tan(s) :: s
139
+
140
+ # Comparisons
141
+
142
+ @callback equal(s, s) :: s
143
+ @callback not_equal(s, s) :: s
144
+ @callback greater(s, s) :: s
145
+ @callback greater_equal(s, s) :: s
146
+ @callback less(s, s) :: s
147
+ @callback less_equal(s, s) :: s
148
+ @callback all_equal(s, s) :: boolean() | lazy_s()
149
+
150
+ @callback binary_and(s, s) :: s
151
+ @callback binary_or(s, s) :: s
152
+ @callback binary_in(s, s) :: s
153
+
154
+ # Float predicates
155
+ @callback is_finite(s) :: s
156
+ @callback is_infinite(s) :: s
157
+ @callback is_nan(s) :: s
158
+
159
+ # Float round
160
+ @callback round(s, decimals :: non_neg_integer()) :: s
161
+ @callback floor(s) :: s
162
+ @callback ceil(s) :: s
163
+
164
+ # Coercion
165
+
166
+ # Sort
167
+
168
+ @callback sort(
169
+ s,
170
+ descending? :: boolean(),
171
+ maintain_order? :: boolean(),
172
+ multithreaded? :: boolean(),
173
+ nulls_last? :: boolean()
174
+ ) :: s
175
+ @callback argsort(
176
+ s,
177
+ descending? :: boolean(),
178
+ maintain_order? :: boolean(),
179
+ multithreaded? :: boolean(),
180
+ nulls_last? :: boolean()
181
+ ) :: s
182
+ @callback reverse(s) :: s
183
+
184
+ # Distinct
185
+
186
+ @callback distinct(s) :: s
187
+ @callback unordered_distinct(s) :: s
188
+ @callback n_distinct(s) :: integer() | lazy_s()
189
+ @callback frequencies(s) :: df
190
+
191
+ # Categorisation
192
+
193
+ @callback cut(
194
+ s,
195
+ bins :: [float()],
196
+ labels :: option([String.t()]),
197
+ break_point_label :: option(String.t()),
198
+ category_label :: option(String.t()),
199
+ left_close :: boolean(),
200
+ include_breaks :: boolean()
201
+ ) ::
202
+ df
203
+ @callback qcut(
204
+ s,
205
+ quantiles :: [float()],
206
+ labels :: option([String.t()]),
207
+ break_point_label :: option(String.t()),
208
+ category_label :: option(String.t()),
209
+ allow_duplicates :: boolean(),
210
+ left_close :: boolean(),
211
+ include_breaks :: boolean()
212
+ ) ::
213
+ df
214
+
215
+ # Rolling
216
+
217
+ @callback window_sum(
218
+ s,
219
+ window_size :: integer(),
220
+ weights :: [float()] | nil,
221
+ min_periods :: integer() | nil,
222
+ center :: boolean()
223
+ ) :: s
224
+ @callback window_min(
225
+ s,
226
+ window_size :: integer(),
227
+ weights :: [float()] | nil,
228
+ min_periods :: integer() | nil,
229
+ center :: boolean()
230
+ ) :: s
231
+ @callback window_max(
232
+ s,
233
+ window_size :: integer(),
234
+ weights :: [float()] | nil,
235
+ min_periods :: integer() | nil,
236
+ center :: boolean()
237
+ ) :: s
238
+ @callback window_mean(
239
+ s,
240
+ window_size :: integer(),
241
+ weights :: [float()] | nil,
242
+ min_periods :: integer() | nil,
243
+ center :: boolean()
244
+ ) :: s
245
+ @callback window_median(
246
+ s,
247
+ window_size :: integer(),
248
+ weights :: [float()] | nil,
249
+ min_periods :: integer() | nil,
250
+ center :: boolean()
251
+ ) :: s
252
+ @callback window_standard_deviation(
253
+ s,
254
+ window_size :: integer(),
255
+ weights :: [float()] | nil,
256
+ min_periods :: integer() | nil,
257
+ center :: boolean()
258
+ ) :: s
259
+
260
+ # Exponentially weighted windows
261
+
262
+ @callback ewm_mean(
263
+ s,
264
+ alpha :: float(),
265
+ adjust :: boolean(),
266
+ min_periods :: integer(),
267
+ ignore_nils :: boolean()
268
+ ) :: s
269
+
270
+ @callback ewm_standard_deviation(
271
+ s,
272
+ alpha :: float(),
273
+ adjust :: boolean(),
274
+ bias :: boolean(),
275
+ min_periods :: integer(),
276
+ ignore_nils :: boolean()
277
+ ) :: s
278
+
279
+ @callback ewm_variance(
280
+ s,
281
+ alpha :: float(),
282
+ adjust :: boolean(),
283
+ bias :: boolean(),
284
+ min_periods :: integer(),
285
+ ignore_nils :: boolean()
286
+ ) :: s
287
+
288
+ # Nulls
289
+
290
+ @callback fill_missing_with_strategy(s, :backward | :forward | :min | :max | :mean) :: s
291
+ @callback fill_missing_with_value(s, :nan | valid_types()) :: s
292
+ @callback is_nil(s) :: s
293
+ @callback is_not_nil(s) :: s
294
+
295
+ # Escape hatch
296
+
297
+ @callback transform(s, fun) :: s
298
+
299
+ # Inversions
300
+
301
+ @callback unary_not(s) :: s
302
+
303
+ # Strings
304
+
305
+ @callback contains(s, String.t()) :: s
306
+ @callback upcase(s) :: s
307
+ @callback downcase(s) :: s
308
+ @callback replace(s, String.t(), String.t()) :: s
309
+ @callback strip(s, String.t() | nil) :: s
310
+ @callback lstrip(s, String.t() | nil) :: s
311
+ @callback rstrip(s, String.t() | nil) :: s
312
+ @callback substring(s, integer(), non_neg_integer() | nil) :: s
313
+ @callback split(s, String.t()) :: s
314
+ @callback split_into(s, String.t(), list(String.t() | atom())) :: s
315
+ @callback json_decode(s, dtype()) :: s
316
+ @callback json_path_match(s, String.t()) :: s
317
+ @callback count_matches(s, String.t()) :: s
318
+
319
+ ## String - Regular expression versions
320
+ @callback re_contains(s, String.t()) :: s
321
+ @callback re_replace(s, String.t(), String.t()) :: s
322
+ @callback re_count_matches(s, String.t()) :: s
323
+ @callback re_scan(s, String.t()) :: s
324
+ @callback re_named_captures(s, String.t()) :: s
325
+
326
+ # Date / DateTime
327
+
328
+ @callback day_of_week(s) :: s
329
+ @callback day_of_year(s) :: s
330
+ @callback week_of_year(s) :: s
331
+ @callback month(s) :: s
332
+ @callback year(s) :: s
333
+ @callback hour(s) :: s
334
+ @callback minute(s) :: s
335
+ @callback second(s) :: s
336
+
337
+ # List
338
+ @callback join(s, String.t()) :: s
339
+ @callback lengths(s) :: s
340
+ @callback member?(s, valid_types()) :: s
341
+
342
+ # Struct
343
+ @callback field(s, String.t()) :: s
344
+
345
+ # Functions
346
+
347
+ @doc """
348
+ Create a new `Series`.
349
+ """
350
+ def new(data, dtype) do
351
+ dtype = Explorer.Shared.normalise_dtype!(dtype)
352
+
353
+ %Explorer.Series{data: data, dtype: dtype}
354
+ end
355
+
356
+ alias Inspect.Algebra, as: A
357
+ alias Explorer.Series
358
+
359
+ @doc """
360
+ Default inspect implementation for backends.
361
+ """
362
+ def inspect(series, backend, n_rows, inspect_opts, opts \\ [])
363
+ when is_binary(backend) and (is_integer(n_rows) or is_nil(n_rows) or is_binary(n_rows)) and
364
+ is_list(opts) do
365
+ open = A.color("[", :list, inspect_opts)
366
+ close = A.color("]", :list, inspect_opts)
367
+
368
+ type =
369
+ series
370
+ |> Series.dtype()
371
+ |> Explorer.Shared.dtype_to_string()
372
+
373
+ dtype = A.color("#{type} ", :atom, inspect_opts)
374
+ data = build_series_data(series, inspect_opts)
375
+
376
+ A.concat([
377
+ A.color(backend, :atom, inspect_opts),
378
+ open,
379
+ "#{n_rows || "???"}",
380
+ close,
381
+ A.line(),
382
+ dtype,
383
+ data
384
+ ])
385
+ end
386
+
387
+ defp build_series_data(series, inspect_opts) do
388
+ series =
389
+ case inspect_opts.limit do
390
+ :infinity -> series
391
+ limit when is_integer(limit) -> Series.slice(series, 0, limit + 1)
392
+ end
393
+
394
+ series
395
+ |> Series.to_list()
396
+ |> Explorer.Shared.to_doc(inspect_opts)
397
+ end
398
+ end
deps/explorer/lib/explorer/comptime_utils.ex ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.ComptimeUtils do
2
+ @moduledoc false
3
+ # This module is useful to control some aspects of compilation.
4
+ # It is mostly used in the `Explorer.PolarsBackend.Native` compilation.
5
+
6
+ # Only works for Linux targets today, but we don't need more.
7
+ @doc false
8
+ def cpu_with_all_caps?(needed_flags, opts \\ []) do
9
+ opts = Keyword.validate!(opts, cpu_info_file_path: "/proc/cpuinfo", target: nil)
10
+
11
+ case File.read(opts[:cpu_info_file_path]) do
12
+ {:ok, contents} ->
13
+ flags =
14
+ contents
15
+ |> String.split("\n")
16
+ |> Stream.filter(&String.starts_with?(&1, "flags"))
17
+ |> Stream.map(fn line ->
18
+ [_, flags] = String.split(line, ": ")
19
+ String.split(flags)
20
+ end)
21
+ |> Stream.uniq()
22
+ |> Enum.to_list()
23
+ |> List.flatten()
24
+
25
+ Enum.all?(needed_flags, fn flag -> flag in flags end)
26
+
27
+ {:error, _} ->
28
+ # There is no way to say, so we default to false.
29
+ false
30
+ end
31
+ end
32
+ end
deps/explorer/lib/explorer/data_frame.ex ADDED
The diff for this file is too large to render. See raw diff
 
deps/explorer/lib/explorer/datasets.ex ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.Datasets do
2
+ @moduledoc """
3
+ Datasets used in examples and exploration.
4
+
5
+ Note those datasets are not available inside Elixir releases
6
+ (see `mix release`), which is the usual way to deploy Elixir
7
+ in production. Therefore, if you need one of those datasets
8
+ in production, you must download the source files to your
9
+ own application `priv` directory and load them yourself.
10
+ For example:
11
+
12
+ Explorer.DataFrame.from_csv!(Application.app_dir(:my_app, "priv/iris.csv"))
13
+ """
14
+ alias Explorer.DataFrame
15
+
16
+ @datasets_dir Path.join(File.cwd!(), "datasets")
17
+
18
+ @doc """
19
+ CO2 emissions from fossil fuels since 2010, by country
20
+
21
+ ## Citation
22
+
23
+ Boden, T.A., G. Marland, and R.J. Andres. 2013. Global, Regional, and National Fossil-Fuel CO2
24
+ Emissions. Carbon Dioxide Information Analysis Center, Oak Ridge National Laboratory, U.S.
25
+ Department of Energy, Oak Ridge, Tenn., U.S.A. doi 10.3334/CDIAC/00001_V2013
26
+ """
27
+ def fossil_fuels, do: read_dataset!("fossil_fuels")
28
+
29
+ @doc """
30
+ Wine Dataset.
31
+
32
+ The data is the result of a chemical analysis of wines grown in the same
33
+ region in Italy but derived from three different cultivars. The analysis
34
+ determined the quantities of 13 constituents found in each of the three
35
+ types of wines.
36
+
37
+ Downloaded and modified from: https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data
38
+
39
+ ## Citation
40
+
41
+ Aeberhard,Stefan and Forina,M.. (1991). Wine. UCI Machine Learning Repository. https://doi.org/10.24432/C5PC7J.
42
+ """
43
+ def wine, do: read_dataset!("wine")
44
+
45
+ @doc """
46
+ Iris Dataset.
47
+
48
+ This classic dataset was collected by Edgar Anderson in 1936
49
+ and made famous by R. A. Fisher's 1936 paper. It consists of
50
+ several measurements of three species of Iris (Iris setosa,
51
+ Iris virginica and Iris versicolor).
52
+
53
+ Downloaded and modified from: https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data
54
+
55
+ ## Citation
56
+
57
+ Fisher,R. A.. (1988). Iris. UCI Machine Learning Repository. https://doi.org/10.24432/C56C76.
58
+ """
59
+ def iris, do: read_dataset!("iris")
60
+
61
+ defp read_dataset!(name) do
62
+ key = {:explorer_datasets, name}
63
+
64
+ # Persistent term is used as a cache, in order to avoid
65
+ # several calls to the filesystem. This is mostly useful
66
+ # to speed up reads in tests.
67
+ case :persistent_term.get(key, nil) do
68
+ nil ->
69
+ @datasets_dir
70
+ |> Path.join("#{name}.csv")
71
+ |> DataFrame.from_csv!()
72
+ |> tap(&:persistent_term.put(key, &1))
73
+
74
+ %DataFrame{} = df ->
75
+ df
76
+ end
77
+ end
78
+ end
deps/explorer/lib/explorer/duration.ex ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.Duration do
2
+ @moduledoc """
3
+ Represents a duration of time.
4
+
5
+ The value is represented by an integer, and the precision can be one
6
+ of the following:
7
+
8
+ * `:millisecond`
9
+ * `:microsecond`
10
+ * `:nanosecond`
11
+ """
12
+ alias Explorer.Duration
13
+
14
+ @enforce_keys [:value, :precision]
15
+ defstruct [:value, :precision]
16
+
17
+ @type precision :: :millisecond | :microsecond | :nanosecond
18
+ @type t :: %__MODULE__{value: integer(), precision: precision()}
19
+
20
+ # Nanosecond constants
21
+ @us_ns 1_000
22
+ @ms_ns 1_000 * @us_ns
23
+ @sec_ns 1_000 * @ms_ns
24
+ @min_ns 60 * @sec_ns
25
+ @hour_ns 60 * @min_ns
26
+ @day_ns 24 * @hour_ns
27
+
28
+ def to_string(%Explorer.Duration{value: value, precision: precision}) do
29
+ case precision do
30
+ :millisecond -> format_nanoseconds(value * @ms_ns)
31
+ :microsecond -> format_nanoseconds(value * @us_ns)
32
+ :nanosecond -> format_nanoseconds(value)
33
+ end
34
+ end
35
+
36
+ defp format_nanoseconds(nanoseconds) when is_integer(nanoseconds) do
37
+ result = nanoseconds |> abs |> format_pos_nanoseconds()
38
+
39
+ if nanoseconds < 0 do
40
+ "-" <> result
41
+ else
42
+ result
43
+ end
44
+ end
45
+
46
+ defp format_pos_nanoseconds(nanoseconds) when is_integer(nanoseconds) and nanoseconds >= 0 do
47
+ [d: @day_ns, h: @hour_ns, m: @min_ns, s: @sec_ns, ms: @ms_ns, us: @us_ns, ns: 1]
48
+ |> Enum.flat_map_reduce(nanoseconds, fn {unit, ns_per_unit}, ns ->
49
+ if ns >= ns_per_unit do
50
+ {[{unit, div(ns, ns_per_unit)}], rem(ns, ns_per_unit)}
51
+ else
52
+ {[], ns}
53
+ end
54
+ end)
55
+ |> then(fn {parts_reversed, _} -> parts_reversed end)
56
+ |> Enum.map_join(" ", fn {unit, value} -> "#{value}#{unit}" end)
57
+ |> case do
58
+ "" -> "0"
59
+ result -> result
60
+ end
61
+ end
62
+
63
+ defimpl String.Chars do
64
+ def to_string(%Duration{} = duration), do: Duration.to_string(duration)
65
+ end
66
+
67
+ defimpl Inspect do
68
+ def inspect(%Duration{} = duration, _),
69
+ do: "#Explorer.Duration[" <> Duration.to_string(duration) <> "]"
70
+ end
71
+ end
deps/explorer/lib/explorer/fss.ex ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ defprotocol Explorer.FSS do
2
+ @moduledoc false
3
+
4
+ @doc """
5
+ Downloads a given entry to a path.
6
+ """
7
+ @spec download(t(), path :: Path.t()) :: :ok | {:error, Exception.t()}
8
+ def download(entry, path)
9
+ end
deps/explorer/lib/explorer/fss/http.ex ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defimpl Explorer.FSS, for: FSS.HTTP.Entry do
2
+ alias Explorer.FSS.Utils
3
+
4
+ def download(entry, path) do
5
+ with :ok <- Utils.assert_regular_path(path) do
6
+ headers = entry.config.headers
7
+ collectable = File.stream!(path)
8
+
9
+ case Utils.download(entry.url, collectable, headers: headers) do
10
+ {:ok, _collectable} -> :ok
11
+ {:error, _message, 404} -> {:error, ArgumentError.exception("resource not found (404)")}
12
+ {:error, exception, _status} -> {:error, exception}
13
+ end
14
+ end
15
+ end
16
+ end
deps/explorer/lib/explorer/fss/s3.ex ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defimpl Explorer.FSS, for: FSS.S3.Entry do
2
+ alias Explorer.FSS.Utils
3
+
4
+ def download(entry, path) do
5
+ with :ok <- Utils.assert_regular_path(path),
6
+ {:ok, url} <- url(entry) do
7
+ headers = headers(entry, :get, url, [])
8
+ collectable = File.stream!(path)
9
+
10
+ case Utils.download(url, collectable, headers: headers) do
11
+ {:ok, _collectable} -> :ok
12
+ {:error, _message, 404} -> {:error, ArgumentError.exception("resource not found (404)")}
13
+ {:error, exception, _status} -> {:error, exception}
14
+ end
15
+ end
16
+ end
17
+
18
+ defp url(%FSS.S3.Entry{} = entry) do
19
+ config = entry.config
20
+
21
+ uri = URI.parse(config.endpoint)
22
+
23
+ maybe_uri =
24
+ if is_nil(config.bucket) do
25
+ {:ok, uri}
26
+ else
27
+ append_path(uri, "/" <> config.bucket)
28
+ end
29
+
30
+ with {:ok, uri} <- maybe_uri,
31
+ {:ok, uri_with_key} <- append_path(uri, "/" <> entry.key) do
32
+ {:ok, URI.to_string(uri_with_key)}
33
+ end
34
+ end
35
+
36
+ # Once we depend on Elixir ~> 1.15, we can use `URI.append_path/2`.
37
+ defp append_path(%URI{}, "//" <> _ = path) do
38
+ {:error, ArgumentError.exception(~s|path cannot start with "//", got: #{inspect(path)}|)}
39
+ end
40
+
41
+ defp append_path(%URI{path: path} = uri, "/" <> rest = all) do
42
+ updated_uri =
43
+ cond do
44
+ path == nil -> %{uri | path: all}
45
+ path != "" and :binary.last(path) == ?/ -> %{uri | path: path <> rest}
46
+ true -> %{uri | path: path <> all}
47
+ end
48
+
49
+ {:ok, updated_uri}
50
+ end
51
+
52
+ defp headers(%FSS.S3.Entry{} = entry, method, url, headers, body \\ nil) do
53
+ now = NaiveDateTime.utc_now() |> NaiveDateTime.to_erl()
54
+ %{host: host} = URI.parse(url)
55
+ headers = [{"Host", host} | headers]
56
+
57
+ headers =
58
+ if entry.config.token,
59
+ do: [{"X-Amz-Security-Token", entry.config.token} | headers],
60
+ else: headers
61
+
62
+ :aws_signature.sign_v4(
63
+ entry.config.access_key_id,
64
+ entry.config.secret_access_key,
65
+ entry.config.region,
66
+ "s3",
67
+ now,
68
+ Atom.to_string(method),
69
+ url,
70
+ headers,
71
+ body || "",
72
+ uri_encode_path: false
73
+ )
74
+ end
75
+ end
deps/explorer/lib/explorer/fss/utils.ex ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.FSS.Utils do
2
+ # Copied from Livebook's code: https://github.com/livebook-dev/livebook/blob/481d39d7edbb7498c8372d0e35f143935e0aeb92/lib/livebook/file_system/utils.ex
3
+ @moduledoc false
4
+
5
+ @type path() :: String.t()
6
+ @type status() :: non_neg_integer()
7
+
8
+ @doc """
9
+ Asserts that the given path is a regular file path.
10
+
11
+ It returns an error in case the file is a directory.
12
+ """
13
+ @spec assert_regular_path(path()) :: :ok | {:error, Exception.t()}
14
+ def assert_regular_path(path) do
15
+ if regular_path?(path) do
16
+ :ok
17
+ else
18
+ {:error, ArgumentError.exception("expected a regular file path, got: #{inspect(path)}")}
19
+ end
20
+ end
21
+
22
+ @doc """
23
+ Checks if the given path describes a regular file.
24
+ """
25
+ @spec regular_path?(path()) :: boolean()
26
+ def regular_path?(path) do
27
+ not String.ends_with?(path, "/")
28
+ end
29
+
30
+ @doc """
31
+ Downloads resource at the given URL into `collectable`.
32
+
33
+ If collectable raises and error, it is rescued and an error tuple
34
+ is returned.
35
+
36
+ ## Options
37
+
38
+ * `:headers` - request headers
39
+
40
+ """
41
+ @spec download(String.t(), Collectable.t(), keyword()) ::
42
+ {:ok, Collectable.t()} | {:error, Exception.t(), status()}
43
+ def download(url, collectable, opts \\ []) do
44
+ headers = build_headers(opts[:headers] || [])
45
+
46
+ request = {url, headers}
47
+ http_opts = [ssl: http_ssl_opts()]
48
+
49
+ caller = self()
50
+
51
+ receiver = fn reply_info ->
52
+ request_id = elem(reply_info, 0)
53
+
54
+ # Cancel the request if the caller terminates
55
+ if Process.alive?(caller) do
56
+ send(caller, {:http, reply_info})
57
+ else
58
+ :httpc.cancel_request(request_id)
59
+ end
60
+ end
61
+
62
+ opts = [stream: :self, sync: false, receiver: receiver]
63
+
64
+ {:ok, request_id} = :httpc.request(:get, request, http_opts, opts)
65
+
66
+ try do
67
+ {acc, collector} = Collectable.into(collectable)
68
+
69
+ try do
70
+ download_loop(%{
71
+ request_id: request_id,
72
+ total_size: nil,
73
+ size: nil,
74
+ acc: acc,
75
+ collector: collector
76
+ })
77
+ catch
78
+ kind, reason ->
79
+ collector.(acc, :halt)
80
+ :httpc.cancel_request(request_id)
81
+ exception = Exception.normalize(kind, reason, __STACKTRACE__)
82
+ {:error, exception, nil}
83
+ else
84
+ {:ok, state} ->
85
+ acc = state.collector.(state.acc, :done)
86
+ {:ok, acc}
87
+
88
+ {:error, message, status} ->
89
+ collector.(acc, :halt)
90
+ :httpc.cancel_request(request_id)
91
+ {:error, ArgumentError.exception(message), status}
92
+ end
93
+ catch
94
+ kind, reason ->
95
+ :httpc.cancel_request(request_id)
96
+ exception = Exception.normalize(kind, reason, __STACKTRACE__)
97
+ {:error, exception, nil}
98
+ end
99
+ end
100
+
101
+ defp download_loop(state) do
102
+ receive do
103
+ {:http, reply_info} when elem(reply_info, 0) == state.request_id ->
104
+ download_receive(state, reply_info)
105
+ end
106
+ end
107
+
108
+ defp download_receive(_state, {_, {:error, error}}) do
109
+ {:error, "reason: #{inspect(error)}", nil}
110
+ end
111
+
112
+ defp download_receive(state, {_, {{_, 200, _}, _headers, body}}) do
113
+ acc = state.collector.(state.acc, {:cont, body})
114
+ {:ok, %{state | acc: acc}}
115
+ end
116
+
117
+ defp download_receive(_state, {_, {{_, status, _}, _headers, _body}}) do
118
+ {:error, "got HTTP status: #{status}", status}
119
+ end
120
+
121
+ defp download_receive(state, {_, :stream_start, headers}) do
122
+ total_size = total_size(headers)
123
+ download_loop(%{state | total_size: total_size, size: 0})
124
+ end
125
+
126
+ defp download_receive(state, {_, :stream, body_part}) do
127
+ acc = state.collector.(state.acc, {:cont, body_part})
128
+ state = %{state | acc: acc}
129
+
130
+ part_size = byte_size(body_part)
131
+ state = update_in(state.size, &(&1 + part_size))
132
+ download_loop(state)
133
+ end
134
+
135
+ defp download_receive(state, {_, :stream_end, _headers}) do
136
+ {:ok, state}
137
+ end
138
+
139
+ defp total_size(headers) do
140
+ case List.keyfind(headers, ~c"content-length", 0) do
141
+ {_, content_length} ->
142
+ List.to_integer(content_length)
143
+
144
+ _ ->
145
+ nil
146
+ end
147
+ end
148
+
149
+ defp build_headers(entries) do
150
+ headers =
151
+ Enum.map(entries, fn {key, value} ->
152
+ {to_charlist(key), to_charlist(value)}
153
+ end)
154
+
155
+ [{~c"user-agent", ~c"elixir-explorer"} | headers]
156
+ end
157
+
158
+ # Load SSL certificates
159
+
160
+ defp http_ssl_opts() do
161
+ # TODO: Remove castore fallback when we require Elixir v1.17+
162
+ # Use secure options, see https://gist.github.com/jonatanklosko/5e20ca84127f6b31bbe3906498e1a1d7
163
+ [
164
+ verify: :verify_peer,
165
+ # We need to increase depth because the default value is 1.
166
+ # See: https://erlef.github.io/security-wg/secure_coding_and_deployment_hardening/ssl
167
+ depth: 3,
168
+ customize_hostname_check: [
169
+ match_fun: :public_key.pkix_verify_hostname_match_fun(:https)
170
+ ]
171
+ ] ++ cacerts_opts()
172
+ end
173
+
174
+ defp cacerts_opts do
175
+ cond do
176
+ certs = otp_cacerts() ->
177
+ [cacerts: certs]
178
+
179
+ Application.spec(:castore, :vsn) ->
180
+ [cacertfile: Application.app_dir(:castore, "priv/cacerts.pem")]
181
+
182
+ true ->
183
+ IO.warn("""
184
+ No certificate trust store was found.
185
+
186
+ A certificate trust store is required in
187
+ order to download locales for your configuration.
188
+ Since elixir_make could not detect a system
189
+ installed certificate trust store one of the
190
+ following actions may be taken:
191
+
192
+ 1. Use OTP 25+ on an OS that has built-in certificate
193
+ trust store.
194
+
195
+ 2. Install the hex package `castore`. It will
196
+ be automatically detected after recompilation.
197
+
198
+ """)
199
+
200
+ []
201
+ end
202
+ end
203
+
204
+ defp otp_cacerts do
205
+ if System.otp_release() >= "25" do
206
+ # cacerts_get/0 raises if no certs found
207
+ try do
208
+ :public_key.cacerts_get()
209
+ rescue
210
+ _ ->
211
+ nil
212
+ end
213
+ end
214
+ end
215
+ end
deps/explorer/lib/explorer/polars_backend.ex ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ defmodule Explorer.PolarsBackend do
2
+ @moduledoc """
3
+ The Explorer backend for Polars.
4
+ """
5
+ end
deps/explorer/lib/explorer/polars_backend/data_frame.ex ADDED
@@ -0,0 +1,944 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.PolarsBackend.DataFrame do
2
+ @moduledoc false
3
+
4
+ alias Explorer.DataFrame, as: DataFrame
5
+ alias Explorer.PolarsBackend.LazyFrame
6
+ alias Explorer.PolarsBackend.Native
7
+ alias Explorer.PolarsBackend.Series, as: PolarsSeries
8
+ alias Explorer.PolarsBackend.Shared
9
+ alias Explorer.Series, as: Series
10
+
11
+ alias FSS.HTTP
12
+ alias FSS.Local
13
+ alias FSS.S3
14
+
15
+ import Explorer.PolarsBackend.Expression, only: [to_expr: 1]
16
+
17
+ defstruct resource: nil
18
+
19
+ @type t :: %__MODULE__{resource: reference()}
20
+
21
+ @behaviour Explorer.Backend.DataFrame
22
+
23
+ # IO
24
+
25
+ @compile {:no_warn_undefined, Adbc.Connection}
26
+ @impl true
27
+ def from_query(conn, query, params) do
28
+ adbc_result =
29
+ Adbc.Connection.query_pointer(conn, query, params, fn pointer, _num_rows ->
30
+ Explorer.PolarsBackend.Native.df_from_arrow_stream_pointer(pointer)
31
+ end)
32
+
33
+ with {:ok, df_result} <- adbc_result,
34
+ {:ok, df} <- df_result,
35
+ do: Shared.create_dataframe(df)
36
+ end
37
+
38
+ @impl true
39
+ def from_csv(
40
+ %module{} = entry,
41
+ dtypes,
42
+ delimiter,
43
+ nil_values,
44
+ skip_rows,
45
+ skip_rows_after_header,
46
+ header?,
47
+ encoding,
48
+ max_rows,
49
+ columns,
50
+ infer_schema_length,
51
+ parse_dates,
52
+ eol_delimiter
53
+ )
54
+ when module in [S3.Entry, HTTP.Entry] do
55
+ path = Shared.build_path_for_entry(entry)
56
+
57
+ with :ok <- Explorer.FSS.download(entry, path) do
58
+ entry = Local.from_path(path)
59
+
60
+ result =
61
+ from_csv(
62
+ entry,
63
+ dtypes,
64
+ delimiter,
65
+ nil_values,
66
+ skip_rows,
67
+ skip_rows_after_header,
68
+ header?,
69
+ encoding,
70
+ max_rows,
71
+ columns,
72
+ infer_schema_length,
73
+ parse_dates,
74
+ eol_delimiter
75
+ )
76
+
77
+ File.rm(path)
78
+ result
79
+ end
80
+ end
81
+
82
+ @impl true
83
+ def from_csv(
84
+ %Local.Entry{} = entry,
85
+ dtypes,
86
+ <<delimiter::utf8>>,
87
+ nil_values,
88
+ skip_rows,
89
+ skip_rows_after_header,
90
+ header?,
91
+ encoding,
92
+ max_rows,
93
+ columns,
94
+ infer_schema_length,
95
+ parse_dates,
96
+ eol_delimiter
97
+ ) do
98
+ infer_schema_length =
99
+ if infer_schema_length == nil,
100
+ do: max_rows,
101
+ else: infer_schema_length
102
+
103
+ {columns, with_projection} = column_names_or_projection(columns)
104
+
105
+ df =
106
+ Native.df_from_csv(
107
+ entry.path,
108
+ infer_schema_length,
109
+ header?,
110
+ max_rows,
111
+ skip_rows,
112
+ skip_rows_after_header,
113
+ with_projection,
114
+ delimiter,
115
+ true,
116
+ columns,
117
+ dtypes,
118
+ encoding,
119
+ nil_values,
120
+ parse_dates,
121
+ char_byte(eol_delimiter)
122
+ )
123
+
124
+ case df do
125
+ {:ok, df} -> Shared.create_dataframe(df)
126
+ {:error, error} -> {:error, RuntimeError.exception(error)}
127
+ end
128
+ end
129
+
130
+ # In case column names are given, it returns the columns.
131
+ # Otherwise returns the list of integers, selecting the "projection" of columns.
132
+ defp column_names_or_projection(nil), do: {nil, nil}
133
+
134
+ defp column_names_or_projection(list) do
135
+ cond do
136
+ Enum.all?(list, &is_binary/1) ->
137
+ {list, nil}
138
+
139
+ Enum.all?(list, &is_integer/1) ->
140
+ {nil, list}
141
+
142
+ true ->
143
+ {nil, nil}
144
+ end
145
+ end
146
+
147
+ @impl true
148
+ def to_csv(%DataFrame{data: df}, %Local.Entry{} = entry, header?, delimiter, _streaming) do
149
+ <<delimiter::utf8>> = delimiter
150
+
151
+ case Native.df_to_csv(df, entry.path, header?, delimiter) do
152
+ {:ok, _} -> :ok
153
+ {:error, error} -> {:error, RuntimeError.exception(error)}
154
+ end
155
+ end
156
+
157
+ @impl true
158
+ def to_csv(%DataFrame{data: df}, %S3.Entry{} = entry, header?, delimiter, _streaming) do
159
+ <<delimiter::utf8>> = delimiter
160
+
161
+ case Native.df_to_csv_cloud(df, entry, header?, delimiter) do
162
+ {:ok, _} -> :ok
163
+ {:error, error} -> {:error, RuntimeError.exception(error)}
164
+ end
165
+ end
166
+
167
+ @impl true
168
+ def dump_csv(%DataFrame{} = df, header?, <<delimiter::utf8>>) do
169
+ case Native.df_dump_csv(df.data, header?, delimiter) do
170
+ {:ok, string} -> {:ok, string}
171
+ {:error, error} -> {:error, RuntimeError.exception(error)}
172
+ end
173
+ end
174
+
175
+ @impl true
176
+ def load_csv(
177
+ contents,
178
+ dtypes,
179
+ <<delimiter::utf8>>,
180
+ nil_values,
181
+ skip_rows,
182
+ skip_rows_after_header,
183
+ header?,
184
+ encoding,
185
+ max_rows,
186
+ columns,
187
+ infer_schema_length,
188
+ parse_dates,
189
+ eol_delimiter
190
+ ) do
191
+ infer_schema_length =
192
+ if infer_schema_length == nil,
193
+ do: max_rows,
194
+ else: infer_schema_length
195
+
196
+ {columns, with_projection} = column_names_or_projection(columns)
197
+
198
+ df =
199
+ Native.df_load_csv(
200
+ contents,
201
+ infer_schema_length,
202
+ header?,
203
+ max_rows,
204
+ skip_rows,
205
+ skip_rows_after_header,
206
+ with_projection,
207
+ delimiter,
208
+ true,
209
+ columns,
210
+ dtypes,
211
+ encoding,
212
+ nil_values,
213
+ parse_dates,
214
+ char_byte(eol_delimiter)
215
+ )
216
+
217
+ case df do
218
+ {:ok, df} -> Shared.create_dataframe(df)
219
+ {:error, error} -> {:error, RuntimeError.exception(error)}
220
+ end
221
+ end
222
+
223
+ defp char_byte(nil), do: nil
224
+ defp char_byte(<<char::utf8>>), do: char
225
+
226
+ @impl true
227
+
228
+ def from_ndjson(%module{} = entry, infer_schema_length, batch_size)
229
+ when module in [S3.Entry, HTTP.Entry] do
230
+ path = Shared.build_path_for_entry(entry)
231
+
232
+ with :ok <- Explorer.FSS.download(entry, path) do
233
+ entry = Local.from_path(path)
234
+
235
+ result = from_ndjson(entry, infer_schema_length, batch_size)
236
+
237
+ File.rm(path)
238
+ result
239
+ end
240
+ end
241
+
242
+ @impl true
243
+ def from_ndjson(%Local.Entry{} = entry, infer_schema_length, batch_size) do
244
+ case Native.df_from_ndjson(entry.path, infer_schema_length, batch_size) do
245
+ {:ok, df} -> Shared.create_dataframe(df)
246
+ {:error, error} -> {:error, RuntimeError.exception(error)}
247
+ end
248
+ end
249
+
250
+ @impl true
251
+ def to_ndjson(%DataFrame{data: df}, %Local.Entry{} = entry) do
252
+ case Native.df_to_ndjson(df, entry.path) do
253
+ {:ok, _} -> :ok
254
+ {:error, error} -> {:error, RuntimeError.exception(error)}
255
+ end
256
+ end
257
+
258
+ @impl true
259
+ def to_ndjson(%DataFrame{data: df}, %S3.Entry{} = entry) do
260
+ case Native.df_to_ndjson_cloud(df, entry) do
261
+ {:ok, _} -> :ok
262
+ {:error, error} -> {:error, RuntimeError.exception(error)}
263
+ end
264
+ end
265
+
266
+ @impl true
267
+ def dump_ndjson(%DataFrame{} = df) do
268
+ case Native.df_dump_ndjson(df.data) do
269
+ {:ok, string} -> {:ok, string}
270
+ {:error, error} -> {:error, RuntimeError.exception(error)}
271
+ end
272
+ end
273
+
274
+ @impl true
275
+ def load_ndjson(contents, infer_schema_length, batch_size) when is_binary(contents) do
276
+ case Native.df_load_ndjson(contents, infer_schema_length, batch_size) do
277
+ {:ok, df} -> Shared.create_dataframe(df)
278
+ {:error, error} -> {:error, RuntimeError.exception(error)}
279
+ end
280
+ end
281
+
282
+ @impl true
283
+ def from_parquet(%S3.Entry{} = entry, max_rows, columns, _rechunk) do
284
+ # We first read using a lazy dataframe, then we collect.
285
+ with {:ok, ldf} <- Native.lf_from_parquet_cloud(entry, max_rows, columns),
286
+ {:ok, df} <- Native.lf_compute(ldf) do
287
+ Shared.create_dataframe(df)
288
+ end
289
+ end
290
+
291
+ @impl true
292
+ def from_parquet(%HTTP.Entry{} = entry, max_rows, columns, rechunk) do
293
+ path = Shared.build_path_for_entry(entry)
294
+
295
+ with :ok <- Explorer.FSS.download(entry, path) do
296
+ entry = Local.from_path(path)
297
+
298
+ result = from_parquet(entry, max_rows, columns, rechunk)
299
+
300
+ File.rm(path)
301
+ result
302
+ end
303
+ end
304
+
305
+ @impl true
306
+ def from_parquet(%Local.Entry{} = entry, max_rows, columns, rechunk) do
307
+ {columns, with_projection} = column_names_or_projection(columns)
308
+
309
+ df =
310
+ Native.df_from_parquet(
311
+ entry.path,
312
+ max_rows,
313
+ columns,
314
+ with_projection,
315
+ rechunk
316
+ )
317
+
318
+ case df do
319
+ {:ok, df} -> Shared.create_dataframe(df)
320
+ {:error, error} -> {:error, RuntimeError.exception(error)}
321
+ end
322
+ end
323
+
324
+ @impl true
325
+ def to_parquet(
326
+ %DataFrame{data: df},
327
+ %Local.Entry{} = entry,
328
+ {compression, compression_level},
329
+ _streaming
330
+ ) do
331
+ case Native.df_to_parquet(df, entry.path, parquet_compression(compression, compression_level)) do
332
+ {:ok, _} -> :ok
333
+ {:error, error} -> {:error, RuntimeError.exception(error)}
334
+ end
335
+ end
336
+
337
+ @impl true
338
+ def to_parquet(
339
+ %DataFrame{data: df},
340
+ %S3.Entry{} = entry,
341
+ {compression, compression_level},
342
+ _streaming
343
+ ) do
344
+ case Native.df_to_parquet_cloud(
345
+ df,
346
+ entry,
347
+ parquet_compression(compression, compression_level)
348
+ ) do
349
+ {:ok, _} -> :ok
350
+ {:error, error} -> {:error, RuntimeError.exception(error)}
351
+ end
352
+ end
353
+
354
+ @impl true
355
+ def dump_parquet(%DataFrame{data: df}, {compression, compression_level}) do
356
+ case Native.df_dump_parquet(df, parquet_compression(compression, compression_level)) do
357
+ {:ok, string} -> {:ok, string}
358
+ {:error, error} -> {:error, RuntimeError.exception(error)}
359
+ end
360
+ end
361
+
362
+ defp parquet_compression(nil, _), do: :uncompressed
363
+
364
+ defp parquet_compression(algorithm, level) when algorithm in ~w(gzip brotli zstd)a do
365
+ {algorithm, level}
366
+ end
367
+
368
+ defp parquet_compression(algorithm, _) when algorithm in ~w(snappy lz4raw)a, do: algorithm
369
+
370
+ @impl true
371
+ def load_parquet(contents) when is_binary(contents) do
372
+ case Native.df_load_parquet(contents) do
373
+ {:ok, df} -> Shared.create_dataframe(df)
374
+ {:error, error} -> {:error, RuntimeError.exception(error)}
375
+ end
376
+ end
377
+
378
+ @impl true
379
+ def from_ipc(%module{} = entry, columns) when module in [S3.Entry, HTTP.Entry] do
380
+ path = Shared.build_path_for_entry(entry)
381
+
382
+ with :ok <- Explorer.FSS.download(entry, path) do
383
+ entry = Local.from_path(path)
384
+
385
+ result = from_ipc(entry, columns)
386
+
387
+ File.rm(path)
388
+ result
389
+ end
390
+ end
391
+
392
+ @impl true
393
+ def from_ipc(%Local.Entry{} = entry, columns) do
394
+ {columns, projection} = column_names_or_projection(columns)
395
+
396
+ case Native.df_from_ipc(entry.path, columns, projection) do
397
+ {:ok, df} -> Shared.create_dataframe(df)
398
+ {:error, error} -> {:error, RuntimeError.exception(error)}
399
+ end
400
+ end
401
+
402
+ @impl true
403
+ def to_ipc(%DataFrame{data: df}, %Local.Entry{} = entry, {compression, _level}, _streaming) do
404
+ case Native.df_to_ipc(df, entry.path, maybe_atom_to_string(compression)) do
405
+ {:ok, _} -> :ok
406
+ {:error, error} -> {:error, RuntimeError.exception(error)}
407
+ end
408
+ end
409
+
410
+ @impl true
411
+ def to_ipc(%DataFrame{data: df}, %S3.Entry{} = entry, {compression, _level}, _streaming) do
412
+ case Native.df_to_ipc_cloud(df, entry, maybe_atom_to_string(compression)) do
413
+ {:ok, _} -> :ok
414
+ {:error, error} -> {:error, RuntimeError.exception(error)}
415
+ end
416
+ end
417
+
418
+ @impl true
419
+ def dump_ipc(%DataFrame{data: df}, {compression, _level}) do
420
+ case Native.df_dump_ipc(df, maybe_atom_to_string(compression)) do
421
+ {:ok, string} -> {:ok, string}
422
+ {:error, error} -> {:error, RuntimeError.exception(error)}
423
+ end
424
+ end
425
+
426
+ @impl true
427
+ def load_ipc(contents, columns) when is_binary(contents) do
428
+ {columns, projection} = column_names_or_projection(columns)
429
+
430
+ case Native.df_load_ipc(contents, columns, projection) do
431
+ {:ok, df} -> Shared.create_dataframe(df)
432
+ {:error, error} -> {:error, RuntimeError.exception(error)}
433
+ end
434
+ end
435
+
436
+ @impl true
437
+ def from_ipc_stream(%module{} = entry, columns) when module in [S3.Entry, HTTP.Entry] do
438
+ path = Shared.build_path_for_entry(entry)
439
+
440
+ with :ok <- Explorer.FSS.download(entry, path) do
441
+ entry = Local.from_path(path)
442
+
443
+ result = from_ipc_stream(entry, columns)
444
+
445
+ File.rm(path)
446
+ result
447
+ end
448
+ end
449
+
450
+ @impl true
451
+ def from_ipc_stream(%Local.Entry{} = entry, columns) do
452
+ {columns, projection} = column_names_or_projection(columns)
453
+
454
+ case Native.df_from_ipc_stream(entry.path, columns, projection) do
455
+ {:ok, df} -> Shared.create_dataframe(df)
456
+ {:error, error} -> {:error, RuntimeError.exception(error)}
457
+ end
458
+ end
459
+
460
+ @impl true
461
+ def to_ipc_stream(%DataFrame{data: df}, %Local.Entry{} = entry, {compression, _level}) do
462
+ case Native.df_to_ipc_stream(df, entry.path, maybe_atom_to_string(compression)) do
463
+ {:ok, _} -> :ok
464
+ {:error, error} -> {:error, RuntimeError.exception(error)}
465
+ end
466
+ end
467
+
468
+ @impl true
469
+ def to_ipc_stream(%DataFrame{data: df}, %S3.Entry{} = entry, {compression, _level}) do
470
+ case Native.df_to_ipc_stream_cloud(df, entry, maybe_atom_to_string(compression)) do
471
+ {:ok, _} -> :ok
472
+ {:error, error} -> {:error, RuntimeError.exception(error)}
473
+ end
474
+ end
475
+
476
+ @impl true
477
+ def dump_ipc_stream(%DataFrame{data: df}, {compression, _level}) do
478
+ case Native.df_dump_ipc_stream(df, maybe_atom_to_string(compression)) do
479
+ {:ok, string} -> {:ok, string}
480
+ {:error, error} -> {:error, RuntimeError.exception(error)}
481
+ end
482
+ end
483
+
484
+ @impl true
485
+ def load_ipc_stream(contents, columns) when is_binary(contents) do
486
+ {columns, projection} = column_names_or_projection(columns)
487
+
488
+ case Native.df_load_ipc_stream(contents, columns, projection) do
489
+ {:ok, df} -> Shared.create_dataframe(df)
490
+ {:error, error} -> {:error, RuntimeError.exception(error)}
491
+ end
492
+ end
493
+
494
+ defp maybe_atom_to_string(nil), do: nil
495
+ defp maybe_atom_to_string(atom) when is_atom(atom), do: Atom.to_string(atom)
496
+
497
+ # Conversion
498
+
499
+ @impl true
500
+ def lazy, do: Explorer.PolarsBackend.LazyFrame
501
+
502
+ @impl true
503
+ def lazy(df) do
504
+ case Native.df_lazy(df.data) do
505
+ {:ok, polars_df} ->
506
+ %{df | data: polars_df}
507
+
508
+ {:error, error} ->
509
+ raise "error when assigning lazy frame: #{inspect(error)}"
510
+ end
511
+ end
512
+
513
+ @impl true
514
+ def compute(df), do: df
515
+
516
+ @impl true
517
+ def from_tabular(tabular, io_dtypes) do
518
+ dtypes = Map.new(io_dtypes)
519
+ {_, %{columns: keys}, _} = reader = init_reader!(tabular)
520
+ columns = Table.to_columns(reader)
521
+
522
+ keys
523
+ |> Enum.map(fn key ->
524
+ column_name = to_column_name!(key)
525
+ values = Enum.to_list(columns[key])
526
+ dtype = Map.get(dtypes, column_name)
527
+
528
+ column_name
529
+ |> series_from_list!(values, dtype)
530
+ |> then(fn series ->
531
+ if not is_nil(dtype) and series.dtype != dtype do
532
+ PolarsSeries.cast(series, dtype)
533
+ else
534
+ series
535
+ end
536
+ end)
537
+ end)
538
+ |> from_series_list()
539
+ end
540
+
541
+ defp init_reader!(tabular) do
542
+ with :none <- Table.Reader.init(tabular) do
543
+ raise ArgumentError, "expected valid tabular data, but got: #{inspect(tabular)}"
544
+ end
545
+ end
546
+
547
+ @impl true
548
+ def from_series(pairs) when is_list(pairs) do
549
+ pairs
550
+ |> Enum.map(fn {name, series} ->
551
+ PolarsSeries.rename(series, name)
552
+ end)
553
+ |> from_series_list()
554
+ end
555
+
556
+ defp from_series_list(list) do
557
+ list = Enum.map(list, & &1.data)
558
+
559
+ Shared.apply(:df_from_series, [list])
560
+ |> Shared.create_dataframe!()
561
+ end
562
+
563
+ defp to_column_name!(column_name) when is_binary(column_name), do: column_name
564
+ defp to_column_name!(column_name) when is_atom(column_name), do: Atom.to_string(column_name)
565
+
566
+ defp to_column_name!(column_name) do
567
+ raise ArgumentError,
568
+ "expected column name to be either string or atom, got: #{inspect(column_name)}"
569
+ end
570
+
571
+ # Like `Explorer.Series.from_list/2`, but gives a better error message with the series name.
572
+ defp series_from_list!(name, list, dtype) do
573
+ type = Explorer.Shared.dtype_from_list!(list, dtype)
574
+ series = Shared.from_list(list, type, name)
575
+ Explorer.Backend.Series.new(series, type)
576
+ rescue
577
+ e ->
578
+ raise ArgumentError, "cannot create series #{inspect(name)}: " <> Exception.message(e)
579
+ end
580
+
581
+ @impl true
582
+ def to_rows(%DataFrame{data: polars_df, names: names} = df, atom_keys?) do
583
+ keys = if atom_keys?, do: Enum.map(names, &String.to_atom/1), else: df.names
584
+
585
+ names
586
+ |> Enum.map(fn name ->
587
+ {:ok, series} = Native.df_pull(polars_df, name)
588
+ {:ok, list} = Native.s_to_list(series)
589
+ list
590
+ end)
591
+ |> Enum.zip_with(fn row -> keys |> Enum.zip(row) |> Map.new() end)
592
+ end
593
+
594
+ @impl true
595
+ def to_rows_stream(%DataFrame{} = df, atom_keys?, chunk_size) do
596
+ Range.new(0, n_rows(df) - 1, chunk_size)
597
+ |> Stream.map(&slice(df, &1, chunk_size))
598
+ |> Stream.flat_map(&to_rows(&1, atom_keys?))
599
+ end
600
+
601
+ # Ownership
602
+
603
+ @impl true
604
+ def owner_reference(df), do: df.data.resource
605
+
606
+ @impl true
607
+ def owner_export(df), do: dump_ipc(df, {nil, nil})
608
+
609
+ @impl true
610
+ def owner_import(term), do: load_ipc(term, nil)
611
+
612
+ # Introspection
613
+
614
+ @impl true
615
+ def n_rows(df), do: Shared.apply_dataframe(df, :df_n_rows)
616
+
617
+ # Single table verbs
618
+
619
+ @impl true
620
+ def head(%DataFrame{} = df, rows) do
621
+ df
622
+ |> lazy()
623
+ |> LazyFrame.head(rows)
624
+ |> LazyFrame.compute()
625
+ end
626
+
627
+ @impl true
628
+ def tail(%DataFrame{} = df, rows) do
629
+ df
630
+ |> lazy()
631
+ |> LazyFrame.tail(rows)
632
+ |> LazyFrame.compute()
633
+ end
634
+
635
+ @impl true
636
+ def select(df, out_df) do
637
+ df
638
+ |> lazy()
639
+ |> LazyFrame.select(out_df)
640
+ |> LazyFrame.compute()
641
+ end
642
+
643
+ @impl true
644
+ def mask(df, %Series{} = mask),
645
+ do: Shared.apply_dataframe(df, df, :df_mask, [mask.data])
646
+
647
+ @impl true
648
+ def filter_with(df, out_df, %Explorer.Backend.LazySeries{} = lseries) do
649
+ df
650
+ |> lazy()
651
+ |> LazyFrame.filter_with(out_df, lseries)
652
+ |> LazyFrame.compute()
653
+ end
654
+
655
+ @impl true
656
+ def mutate_with(%DataFrame{} = df, %DataFrame{} = out_df, column_pairs) do
657
+ df
658
+ |> lazy()
659
+ |> LazyFrame.mutate_with(out_df, column_pairs)
660
+ |> LazyFrame.compute()
661
+ end
662
+
663
+ @impl true
664
+ def put(%DataFrame{} = df, %DataFrame{} = out_df, new_column_name, series) do
665
+ series = PolarsSeries.rename(Explorer.Series.collect(series), new_column_name)
666
+
667
+ Shared.apply_dataframe(df, out_df, :df_put_column, [series.data])
668
+ end
669
+
670
+ @impl true
671
+ def nil_count(%DataFrame{} = df) do
672
+ Shared.apply(:df_nil_count, [df.data])
673
+ |> Shared.create_dataframe!()
674
+ end
675
+
676
+ @impl true
677
+ def sort_with(
678
+ %DataFrame{} = df,
679
+ out_df,
680
+ column_pairs,
681
+ maintain_order?,
682
+ multithreaded?,
683
+ nulls_last?
684
+ )
685
+ when is_boolean(maintain_order?) and is_boolean(multithreaded?) and
686
+ is_boolean(nulls_last?) do
687
+ if Enum.all?(column_pairs, fn {_, %{op: op}} -> op == :column end) do
688
+ {directions, column_names} =
689
+ column_pairs
690
+ |> Enum.map(fn {dir, %{args: [col]}} -> {dir == :desc, col} end)
691
+ |> Enum.unzip()
692
+
693
+ Shared.apply_dataframe(df, out_df, :df_sort_by, [
694
+ column_names,
695
+ directions,
696
+ maintain_order?,
697
+ multithreaded?,
698
+ nulls_last?,
699
+ df.groups
700
+ ])
701
+ else
702
+ {directions, expressions} =
703
+ column_pairs
704
+ |> Enum.map(fn {dir, lazy_series} -> {dir == :desc, to_expr(lazy_series)} end)
705
+ |> Enum.unzip()
706
+
707
+ Shared.apply_dataframe(df, out_df, :df_sort_with, [
708
+ expressions,
709
+ directions,
710
+ maintain_order?,
711
+ multithreaded?,
712
+ nulls_last?,
713
+ df.groups
714
+ ])
715
+ end
716
+ end
717
+
718
+ @impl true
719
+ def distinct(%DataFrame{} = df, %DataFrame{} = out_df, columns) do
720
+ df
721
+ |> lazy()
722
+ |> LazyFrame.distinct(out_df, columns)
723
+ |> LazyFrame.compute()
724
+ end
725
+
726
+ @impl true
727
+ def rename(%DataFrame{} = df, %DataFrame{} = out_df, pairs) do
728
+ df
729
+ |> lazy()
730
+ |> LazyFrame.rename(out_df, pairs)
731
+ |> LazyFrame.compute()
732
+ end
733
+
734
+ @impl true
735
+ def dummies(df, out_df, names),
736
+ do: Shared.apply_dataframe(df, out_df, :df_to_dummies, [names])
737
+
738
+ @impl true
739
+ def sample(df, n, replacement, shuffle, seed) when is_integer(n) do
740
+ Shared.apply_dataframe(df, df, :df_sample_n, [n, replacement, shuffle, seed, df.groups])
741
+ end
742
+
743
+ @impl true
744
+ def sample(df, frac, replacement, shuffle, seed) when is_float(frac) do
745
+ # Avoid grouping if the sample is of the entire DF.
746
+ groups = if frac == 1.0, do: [], else: df.groups
747
+
748
+ Shared.apply_dataframe(df, df, :df_sample_frac, [frac, replacement, shuffle, seed, groups])
749
+ end
750
+
751
+ @impl true
752
+ def pull(df, column), do: Shared.apply_dataframe(df, :df_pull, [column])
753
+
754
+ @impl true
755
+ def slice(%DataFrame{} = df, row_indices) when is_list(row_indices) do
756
+ Shared.apply_dataframe(df, df, :df_slice_by_indices, [row_indices, df.groups])
757
+ end
758
+
759
+ @impl true
760
+ def slice(%DataFrame{} = df, %Series{} = row_indices) do
761
+ Shared.apply_dataframe(df, df, :df_slice_by_series, [row_indices.data, df.groups])
762
+ end
763
+
764
+ # TODO: If we expose group_indices at the Explorer.DataFrame level,
765
+ # then we can implement this in pure Elixir.
766
+ @impl true
767
+ def slice(%DataFrame{groups: [_ | _]} = df, %Range{} = range) do
768
+ {:ok, group_indices} = Native.df_group_indices(df.data, df.groups)
769
+
770
+ idx =
771
+ Enum.map(group_indices, fn series ->
772
+ {:ok, size} = Native.s_size(series)
773
+ indices = Enum.slice(0..(size - 1)//1, range)
774
+
775
+ {:ok, sliced} = Native.s_slice_by_indices(series, indices)
776
+ sliced
777
+ end)
778
+
779
+ {:ok, idx} = Native.s_concat(idx)
780
+
781
+ Shared.apply_dataframe(df, df, :df_slice_by_series, [idx, []])
782
+ end
783
+
784
+ @impl true
785
+ def slice(%DataFrame{} = df, offset, length)
786
+ when is_integer(offset) and is_integer(length),
787
+ do: Shared.apply_dataframe(df, df, :df_slice, [offset, length, df.groups])
788
+
789
+ @impl true
790
+ def drop_nil(df, columns) do
791
+ df
792
+ |> lazy()
793
+ |> LazyFrame.drop_nil(columns)
794
+ |> LazyFrame.compute()
795
+ end
796
+
797
+ @impl true
798
+ def pivot_longer(df, out_df, cols_to_pivot, cols_to_keep, names_to, values_to) do
799
+ df
800
+ |> lazy()
801
+ |> LazyFrame.pivot_longer(out_df, cols_to_pivot, cols_to_keep, names_to, values_to)
802
+ |> LazyFrame.compute()
803
+ end
804
+
805
+ @impl true
806
+ def pivot_wider(df, id_columns, names_from, values_from, names_prefix) do
807
+ names_prefix_optional = unless names_prefix == "", do: names_prefix
808
+
809
+ Shared.apply(:df_pivot_wider, [
810
+ df.data,
811
+ id_columns,
812
+ names_from,
813
+ values_from,
814
+ names_prefix_optional
815
+ ])
816
+ |> Shared.create_dataframe!()
817
+ end
818
+
819
+ @impl true
820
+ def transpose(df, out_df, keep_names_as, new_col_names) do
821
+ Shared.apply_dataframe(df, out_df, :df_transpose, [keep_names_as, new_col_names])
822
+ end
823
+
824
+ @impl true
825
+ def explode(df, out_df, columns) do
826
+ df
827
+ |> lazy()
828
+ |> LazyFrame.explode(out_df, columns)
829
+ |> LazyFrame.compute()
830
+ end
831
+
832
+ @impl true
833
+ def unnest(df, out_df, columns) do
834
+ df
835
+ |> lazy()
836
+ |> LazyFrame.unnest(out_df, columns)
837
+ |> LazyFrame.compute()
838
+ end
839
+
840
+ @impl true
841
+ def correlation(df, out_df, ddof, method) do
842
+ pairwise(df, out_df, fn left, right ->
843
+ PolarsSeries.correlation(left, right, ddof, method)
844
+ end)
845
+ end
846
+
847
+ @impl true
848
+ def covariance(df, out_df, ddof) do
849
+ pairwise(df, out_df, fn left, right -> PolarsSeries.covariance(left, right, ddof) end)
850
+ end
851
+
852
+ # Two or more table verbs
853
+
854
+ @impl true
855
+ def join([left, right], out_df, on, how) do
856
+ left = lazy(left)
857
+ right = lazy(right)
858
+
859
+ ldf = LazyFrame.join([left, right], out_df, on, how)
860
+ LazyFrame.compute(ldf)
861
+ end
862
+
863
+ @impl true
864
+ def concat_rows([_head | _tail] = dfs, out_df) do
865
+ lazy_dfs = Enum.map(dfs, &lazy/1)
866
+
867
+ lazy_dfs
868
+ |> LazyFrame.concat_rows(out_df)
869
+ |> LazyFrame.compute()
870
+ end
871
+
872
+ @impl true
873
+ def concat_columns([head | tail], out_df) do
874
+ n_rows = n_rows(head)
875
+
876
+ tail =
877
+ Enum.map(tail, fn df ->
878
+ if n_rows(df) != n_rows do
879
+ raise ArgumentError, "all dataframes must have the same number of rows"
880
+ end
881
+
882
+ df.data
883
+ end)
884
+
885
+ out_data = Shared.apply(:df_concat_columns, [[head.data | tail]])
886
+ %{out_df | data: out_data}
887
+ end
888
+
889
+ # Groups
890
+
891
+ @impl true
892
+ def summarise_with(%DataFrame{} = df, %DataFrame{} = out_df, column_pairs) do
893
+ df
894
+ |> lazy()
895
+ |> LazyFrame.summarise_with(out_df, column_pairs)
896
+ |> LazyFrame.compute()
897
+ end
898
+
899
+ # Inspect
900
+
901
+ @impl true
902
+ def inspect(df, opts) do
903
+ Explorer.Backend.DataFrame.inspect(df, "Polars", n_rows(df), opts)
904
+ end
905
+
906
+ # SQL
907
+
908
+ @impl true
909
+ def sql(%DataFrame{} = df, sql_string, table_name) do
910
+ df
911
+ |> lazy()
912
+ |> LazyFrame.sql(sql_string, table_name)
913
+ |> LazyFrame.compute()
914
+ end
915
+
916
+ @impl true
917
+ def re_dtype(regex_as_string) when is_binary(regex_as_string) do
918
+ case Explorer.PolarsBackend.Native.df_re_dtype(regex_as_string) do
919
+ {:ok, dtype} -> dtype
920
+ {:error, error} -> raise error
921
+ end
922
+ end
923
+
924
+ # helpers
925
+
926
+ defp pairwise(df, out_df, operation) do
927
+ [column_name | cols] = out_df.names
928
+
929
+ pairwise_results =
930
+ Enum.map(cols, fn left ->
931
+ corr_series =
932
+ cols
933
+ |> Enum.map(fn right -> operation.(df[left], df[right]) end)
934
+ |> Shared.from_list({:f, 64})
935
+ |> Shared.create_series()
936
+
937
+ {left, corr_series}
938
+ end)
939
+
940
+ names_series = cols |> Shared.from_list(:string) |> Shared.create_series()
941
+
942
+ from_series([{column_name, names_series} | pairwise_results])
943
+ end
944
+ end
deps/explorer/lib/explorer/polars_backend/expression.ex ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.PolarsBackend.Expression do
2
+ @moduledoc false
3
+ # This module is responsible for translating the opaque LazySeries
4
+ # to polars expressions in the Rust side.
5
+
6
+ alias Explorer.DataFrame
7
+ alias Explorer.Backend.LazySeries
8
+ alias Explorer.PolarsBackend.Native
9
+ alias Explorer.PolarsBackend.Series, as: PolarsSeries
10
+
11
+ defstruct resource: nil
12
+
13
+ @type t :: %__MODULE__{resource: reference()}
14
+
15
+ @all_expressions [
16
+ all: 1,
17
+ add: 2,
18
+ any: 1,
19
+ all_equal: 2,
20
+ argmax: 1,
21
+ argmin: 1,
22
+ binary_and: 2,
23
+ binary_or: 2,
24
+ binary_in: 2,
25
+ coalesce: 2,
26
+ count: 1,
27
+ size: 1,
28
+ day_of_week: 1,
29
+ day_of_year: 1,
30
+ week_of_year: 1,
31
+ month: 1,
32
+ year: 1,
33
+ hour: 1,
34
+ minute: 1,
35
+ second: 1,
36
+ distinct: 1,
37
+ equal: 2,
38
+ exp: 1,
39
+ abs: 1,
40
+ fill_missing_with_value: 2,
41
+ first: 1,
42
+ format: 1,
43
+ greater: 2,
44
+ greater_equal: 2,
45
+ is_nil: 1,
46
+ is_not_nil: 1,
47
+ is_finite: 1,
48
+ is_infinite: 1,
49
+ is_nan: 1,
50
+ last: 1,
51
+ less: 2,
52
+ less_equal: 2,
53
+ max: 1,
54
+ mean: 1,
55
+ median: 1,
56
+ min: 1,
57
+ mode: 1,
58
+ n_distinct: 1,
59
+ nil_count: 1,
60
+ not_equal: 2,
61
+ unary_not: 1,
62
+ pow: 2,
63
+ product: 1,
64
+ quotient: 2,
65
+ remainder: 2,
66
+ reverse: 1,
67
+ floor: 1,
68
+ ceil: 1,
69
+ select: 3,
70
+ sin: 1,
71
+ cos: 1,
72
+ tan: 1,
73
+ asin: 1,
74
+ acos: 1,
75
+ atan: 1,
76
+ standard_deviation: 2,
77
+ subtract: 2,
78
+ sum: 1,
79
+ unordered_distinct: 1,
80
+ variance: 2,
81
+ skew: 2
82
+ ]
83
+
84
+ @first_only_expressions [
85
+ quantile: 2,
86
+ argsort: 5,
87
+ sort: 5,
88
+ head: 2,
89
+ tail: 2,
90
+ peaks: 2,
91
+ rank: 4,
92
+ sample_n: 5,
93
+ sample_frac: 5,
94
+ exp: 1,
95
+ skew: 2,
96
+ round: 2,
97
+ clip_float: 3,
98
+ clip_integer: 3,
99
+ variance: 2,
100
+ standard_deviation: 2,
101
+
102
+ # Trigonometric operations
103
+ acos: 1,
104
+ asin: 1,
105
+ atan: 1,
106
+ cos: 1,
107
+ sin: 1,
108
+ tan: 1,
109
+
110
+ # Window operations
111
+ cumulative_max: 2,
112
+ cumulative_min: 2,
113
+ cumulative_sum: 2,
114
+ cumulative_product: 2,
115
+ window_max: 5,
116
+ window_mean: 5,
117
+ window_median: 5,
118
+ window_min: 5,
119
+ window_sum: 5,
120
+ window_standard_deviation: 5,
121
+ ewm_mean: 5,
122
+ ewm_standard_deviation: 6,
123
+ ewm_variance: 6,
124
+
125
+ # Conversions
126
+ strptime: 2,
127
+ strftime: 2,
128
+
129
+ # Strings
130
+ contains: 2,
131
+ re_contains: 2,
132
+ replace: 3,
133
+ re_replace: 3,
134
+ strip: 2,
135
+ lstrip: 2,
136
+ rstrip: 2,
137
+ downcase: 1,
138
+ upcase: 1,
139
+ substring: 3,
140
+ split: 2,
141
+ split_into: 3,
142
+ json_decode: 2,
143
+ json_path_match: 2,
144
+ count_matches: 2,
145
+ re_count_matches: 2,
146
+ re_scan: 2,
147
+ re_named_captures: 2,
148
+
149
+ # Lists
150
+ join: 2,
151
+ lengths: 1,
152
+ member: 3,
153
+
154
+ # Structs
155
+ field: 2
156
+ ]
157
+
158
+ @custom_expressions [
159
+ divide: 2,
160
+ multiply: 2,
161
+ cast: 2,
162
+ fill_missing_with_strategy: 2,
163
+ from_list: 2,
164
+ from_binary: 2,
165
+ log: 1,
166
+ log: 2,
167
+ lazy: 1,
168
+ shift: 3,
169
+ slice: 2,
170
+ slice: 3,
171
+ row_index: 1,
172
+ concat: 1,
173
+ column: 1,
174
+ correlation: 4,
175
+ covariance: 3
176
+ ]
177
+
178
+ missing =
179
+ ((Explorer.Backend.LazySeries.operations() -- @all_expressions) -- @first_only_expressions) --
180
+ @custom_expressions
181
+
182
+ if missing != [] do
183
+ raise ArgumentError, "missing #{inspect(__MODULE__)} nodes: #{inspect(missing)}"
184
+ end
185
+
186
+ def to_expr(%LazySeries{op: :cast, args: [lazy_series, dtype]}) do
187
+ lazy_series_expr = to_expr(lazy_series)
188
+ Native.expr_cast(lazy_series_expr, dtype)
189
+ end
190
+
191
+ def to_expr(%LazySeries{op: :fill_missing_with_strategy, args: [lazy_series, strategy]}) do
192
+ expr = to_expr(lazy_series)
193
+ Native.expr_fill_missing_with_strategy(expr, Atom.to_string(strategy))
194
+ end
195
+
196
+ def to_expr(%LazySeries{op: :from_list, args: [list, dtype]}) do
197
+ series = Explorer.PolarsBackend.Shared.from_list(list, dtype)
198
+ Native.expr_series(series)
199
+ end
200
+
201
+ def to_expr(%LazySeries{op: :from_binary, args: [binary, dtype]}) do
202
+ series = Explorer.PolarsBackend.Shared.from_binary(binary, dtype)
203
+ Native.expr_series(series)
204
+ end
205
+
206
+ def to_expr(%LazySeries{op: :lazy, args: [data]}) do
207
+ to_expr(data)
208
+ end
209
+
210
+ def to_expr(%LazySeries{op: :shift, args: [lazy_series, offset, nil]}) do
211
+ Native.expr_shift(to_expr(lazy_series), offset, nil)
212
+ end
213
+
214
+ def to_expr(%LazySeries{op: :column, args: [name]}) do
215
+ Native.expr_column(name)
216
+ end
217
+
218
+ def to_expr(%LazySeries{op: :concat, args: [series_list]}) when is_list(series_list) do
219
+ expr_list = Enum.map(series_list, &to_expr/1)
220
+
221
+ Native.expr_concat(expr_list)
222
+ end
223
+
224
+ def to_expr(%LazySeries{op: :correlation, args: [series1, series2, ddof, method]}) do
225
+ Native.expr_correlation(to_expr(series1), to_expr(series2), ddof, method)
226
+ end
227
+
228
+ def to_expr(%LazySeries{op: :covariance, args: [series1, series2, ddof]}) do
229
+ Native.expr_covariance(to_expr(series1), to_expr(series2), ddof)
230
+ end
231
+
232
+ def to_expr(%LazySeries{op: :format, args: [series_list]}) when is_list(series_list) do
233
+ expr_list = Enum.map(series_list, &to_expr/1)
234
+
235
+ Native.expr_format(expr_list)
236
+ end
237
+
238
+ def to_expr(%LazySeries{op: :slice, args: [lazy_series, lazy_series_or_list]}) do
239
+ indices =
240
+ if is_list(lazy_series_or_list) do
241
+ lazy_series_or_list
242
+ |> Explorer.PolarsBackend.Shared.from_list({:s, 64})
243
+ |> Native.expr_series()
244
+ else
245
+ to_expr(lazy_series_or_list)
246
+ end
247
+
248
+ Native.expr_slice_by_indices(to_expr(lazy_series), indices)
249
+ end
250
+
251
+ def to_expr(%LazySeries{op: :slice, args: [lazy_series, offset, length]}) do
252
+ expr = to_expr(lazy_series)
253
+
254
+ Native.expr_slice(expr, offset, length)
255
+ end
256
+
257
+ def to_expr(%LazySeries{op: :log, args: [lazy_series]}) do
258
+ expr = to_expr(lazy_series)
259
+
260
+ Native.expr_log_natural(expr)
261
+ end
262
+
263
+ def to_expr(%LazySeries{op: :log, args: [lazy_series, base]}) do
264
+ expr = to_expr(lazy_series)
265
+
266
+ Native.expr_log(expr, base)
267
+ end
268
+
269
+ for {op, _arity} <- @first_only_expressions do
270
+ expr_op = :"expr_#{op}"
271
+
272
+ def to_expr(%LazySeries{op: unquote(op), args: [lazy_series | args]}) do
273
+ expr = to_expr(lazy_series)
274
+
275
+ apply(Native, unquote(expr_op), [expr | args])
276
+ end
277
+ end
278
+
279
+ def to_expr(%LazySeries{op: :multiply, args: [left, right] = args}) do
280
+ expr = Native.expr_multiply(to_expr(left), to_expr(right))
281
+
282
+ input_dtypes = Enum.map(args, &dtype/1)
283
+ duration_dtype = Enum.find(input_dtypes, &match?({:duration, _}, &1))
284
+ numeric? = Enum.any?(input_dtypes, &(&1 in Explorer.Shared.numeric_types()))
285
+
286
+ if duration_dtype && numeric? do
287
+ Native.expr_cast(expr, duration_dtype)
288
+ else
289
+ expr
290
+ end
291
+ end
292
+
293
+ def to_expr(%LazySeries{op: :divide, args: [left, right]}) do
294
+ expr = Native.expr_divide(to_expr(left), to_expr(right))
295
+
296
+ case {dtype(left), dtype(right)} do
297
+ {{:duration, _} = left_dtype, right_dtype} ->
298
+ if right_dtype in Explorer.Shared.numeric_types() do
299
+ Native.expr_cast(expr, left_dtype)
300
+ else
301
+ expr
302
+ end
303
+
304
+ {_, _} ->
305
+ expr
306
+ end
307
+ end
308
+
309
+ def to_expr(%LazySeries{op: :row_index, args: [lazy_series]}) do
310
+ size_expr = Native.expr_size(to_expr(lazy_series))
311
+ Native.expr_int_range(to_expr(0), size_expr, 1, {:u, 32})
312
+ end
313
+
314
+ for {op, arity} <- @all_expressions do
315
+ args = Macro.generate_arguments(arity, __MODULE__)
316
+
317
+ updates =
318
+ for arg <- args do
319
+ quote do
320
+ to_expr(unquote(arg))
321
+ end
322
+ end
323
+
324
+ expr_op = :"expr_#{op}"
325
+
326
+ def to_expr(%LazySeries{op: unquote(op), args: unquote(args)}) do
327
+ Native.unquote(expr_op)(unquote_splicing(updates))
328
+ end
329
+ end
330
+
331
+ def to_expr(nil), do: Native.expr_nil()
332
+ def to_expr(bool) when is_boolean(bool), do: Native.expr_boolean(bool)
333
+ def to_expr(atom) when is_atom(atom), do: Native.expr_atom(Atom.to_string(atom))
334
+ def to_expr(binary) when is_binary(binary), do: Native.expr_string(binary)
335
+ def to_expr(number) when is_integer(number), do: Native.expr_integer(number)
336
+ def to_expr(number) when is_float(number), do: Native.expr_float(number)
337
+ def to_expr(%Date{} = date), do: Native.expr_date(date)
338
+ def to_expr(%NaiveDateTime{} = naive_datetime), do: Native.expr_naive_datetime(naive_datetime)
339
+ def to_expr(%DateTime{} = datetime), do: Native.expr_datetime(datetime)
340
+ def to_expr(%Explorer.Duration{} = duration), do: Native.expr_duration(duration)
341
+
342
+ def to_expr(%Explorer.Series{data: %PolarsSeries{} = polars_series}),
343
+ do: Native.expr_series(polars_series)
344
+
345
+ def to_expr(%_{} = struct),
346
+ do: raise("unsupported struct in expression: #{inspect(struct)}")
347
+
348
+ def to_expr(map) when is_map(map) do
349
+ expr_list =
350
+ Enum.map(map, fn {name, series} ->
351
+ series |> to_expr() |> alias_expr(name)
352
+ end)
353
+
354
+ Native.expr_struct(expr_list)
355
+ end
356
+
357
+ # Used by Explorer.PolarsBackend.DataFrame
358
+ def alias_expr(%__MODULE__{} = expr, alias_name) when is_binary(alias_name) do
359
+ Native.expr_alias(expr, alias_name)
360
+ end
361
+
362
+ # Only for inspecting the expression in tests
363
+ def describe_filter_plan(%DataFrame{data: polars_df}, %__MODULE__{} = expression) do
364
+ Native.expr_describe_filter_plan(polars_df, expression)
365
+ end
366
+
367
+ defp dtype(%LazySeries{dtype: dtype}), do: dtype
368
+ defp dtype(%Explorer.Series{dtype: dtype}), do: dtype
369
+ end
deps/explorer/lib/explorer/polars_backend/lazy_frame.ex ADDED
@@ -0,0 +1,670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.PolarsBackend.LazyFrame do
2
+ @moduledoc false
3
+
4
+ alias Explorer.Backend.LazySeries
5
+ alias Explorer.DataFrame, as: DF
6
+
7
+ alias Explorer.PolarsBackend.Native
8
+ alias Explorer.PolarsBackend.Shared
9
+ alias Explorer.PolarsBackend.DataFrame, as: Eager
10
+
11
+ alias FSS.Local
12
+ alias FSS.S3
13
+ alias FSS.HTTP
14
+
15
+ import Explorer.PolarsBackend.Expression, only: [to_expr: 1, alias_expr: 2]
16
+
17
+ # This resource is going to be a "ResourceArc" on Rust side.
18
+ defstruct resource: nil
19
+
20
+ @type t :: %__MODULE__{resource: reference()}
21
+
22
+ @behaviour Explorer.Backend.DataFrame
23
+
24
+ # Conversion
25
+
26
+ @impl true
27
+ def lazy, do: __MODULE__
28
+
29
+ @impl true
30
+ def lazy(ldf), do: ldf
31
+
32
+ @impl true
33
+ def compute(ldf), do: Shared.apply_dataframe(ldf, ldf, :lf_compute, [])
34
+
35
+ @impl true
36
+ def from_tabular(tabular, dtypes),
37
+ do: Eager.from_tabular(tabular, dtypes) |> Eager.lazy()
38
+
39
+ @impl true
40
+ def from_series(pairs), do: Eager.from_series(pairs) |> Eager.lazy()
41
+
42
+ # Introspection
43
+
44
+ @impl true
45
+ def owner_reference(df), do: df.data.resource
46
+
47
+ @impl true
48
+ def owner_export(df) do
49
+ raise """
50
+ it is not possible to transfer a lazy data frame between nodes. \
51
+ You must collect the operands to the same node between continuing, got:
52
+
53
+ #{inspect(df)}
54
+ """
55
+ end
56
+
57
+ @impl true
58
+ def owner_import(_exported) do
59
+ raise "not implemented"
60
+ end
61
+
62
+ @impl true
63
+ def inspect(ldf, opts) when node(ldf.data.resource) != node() do
64
+ Explorer.Backend.DataFrame.inspect(
65
+ ldf,
66
+ "LazyPolars (node: #{node(ldf.data.resource)})",
67
+ nil,
68
+ opts,
69
+ elide_columns: true
70
+ )
71
+ end
72
+
73
+ def inspect(ldf, opts) do
74
+ case Native.lf_fetch(ldf.data, opts.limit) do
75
+ {:ok, df} ->
76
+ df = Explorer.Backend.DataFrame.new(df, ldf.names, ldf.dtypes)
77
+ df = %{df | groups: ldf.groups}
78
+
79
+ Explorer.Backend.DataFrame.inspect(df, "LazyPolars", nil, opts)
80
+
81
+ {:error, error} ->
82
+ raise "inspection error: #{inspect(error)}"
83
+ end
84
+ end
85
+
86
+ # Single table verbs
87
+
88
+ @impl true
89
+ def head(ldf, rows),
90
+ do: Shared.apply_dataframe(ldf, ldf, :lf_head, [rows, groups_exprs(ldf.groups)])
91
+
92
+ @impl true
93
+ def tail(ldf, rows),
94
+ do: Shared.apply_dataframe(ldf, ldf, :lf_tail, [rows, groups_exprs(ldf.groups)])
95
+
96
+ @impl true
97
+ def select(ldf, out_ldf), do: Shared.apply_dataframe(ldf, out_ldf, :lf_select, [out_ldf.names])
98
+
99
+ @impl true
100
+ def slice(ldf, offset, length),
101
+ do: Shared.apply_dataframe(ldf, ldf, :lf_slice, [offset, length, ldf.groups])
102
+
103
+ defp groups_exprs(groups), do: Enum.map(groups, &Native.expr_column/1)
104
+
105
+ # IO
106
+
107
+ @impl true
108
+ def from_query(conn, query, params) do
109
+ with {:ok, df} <- Eager.from_query(conn, query, params) do
110
+ {:ok, Eager.lazy(df)}
111
+ end
112
+ end
113
+
114
+ @impl true
115
+ def from_csv(
116
+ %S3.Entry{},
117
+ _,
118
+ _,
119
+ _,
120
+ _,
121
+ _,
122
+ _,
123
+ _,
124
+ _,
125
+ _,
126
+ _,
127
+ _,
128
+ _
129
+ ) do
130
+ {:error,
131
+ ArgumentError.exception("reading CSV from AWS S3 is not supported for Lazy dataframes")}
132
+ end
133
+
134
+ @impl true
135
+ def from_csv(
136
+ %Local.Entry{} = entry,
137
+ dtypes,
138
+ <<delimiter::utf8>>,
139
+ nil_values,
140
+ skip_rows,
141
+ skip_rows_after_header,
142
+ header?,
143
+ encoding,
144
+ max_rows,
145
+ columns,
146
+ infer_schema_length,
147
+ parse_dates,
148
+ eol_delimiter
149
+ )
150
+ when is_nil(columns) do
151
+ infer_schema_length =
152
+ if infer_schema_length == nil,
153
+ do: max_rows,
154
+ else: infer_schema_length
155
+
156
+ result =
157
+ Native.lf_from_csv(
158
+ entry.path,
159
+ infer_schema_length,
160
+ header?,
161
+ max_rows,
162
+ skip_rows,
163
+ skip_rows_after_header,
164
+ delimiter,
165
+ true,
166
+ dtypes,
167
+ encoding,
168
+ nil_values,
169
+ parse_dates,
170
+ char_byte(eol_delimiter)
171
+ )
172
+
173
+ case result do
174
+ {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf)
175
+ {:error, error} -> {:error, RuntimeError.exception(error)}
176
+ end
177
+ end
178
+
179
+ @impl true
180
+ def from_csv(
181
+ %Local.Entry{},
182
+ _,
183
+ _,
184
+ _,
185
+ _,
186
+ _,
187
+ _,
188
+ _,
189
+ _,
190
+ _,
191
+ _,
192
+ _,
193
+ _
194
+ ) do
195
+ {:error,
196
+ ArgumentError.exception(
197
+ "`columns` is not supported by Polars' lazy backend. " <>
198
+ "Consider using `select/2` after reading the CSV"
199
+ )}
200
+ end
201
+
202
+ defp char_byte(nil), do: nil
203
+ defp char_byte(<<char::utf8>>), do: char
204
+
205
+ @impl true
206
+ def from_parquet(%S3.Entry{} = entry, max_rows, columns, _rechunk) do
207
+ case Native.lf_from_parquet_cloud(entry, max_rows, columns) do
208
+ {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf)
209
+ {:error, error} -> {:error, RuntimeError.exception(error)}
210
+ end
211
+ end
212
+
213
+ @impl true
214
+ def from_parquet(%HTTP.Entry{url: url}, max_rows, columns, _rechunk) do
215
+ case Native.lf_from_parquet(url, max_rows, columns) do
216
+ {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf)
217
+ {:error, error} -> {:error, RuntimeError.exception(error)}
218
+ end
219
+ end
220
+
221
+ @impl true
222
+ def from_parquet(%Local.Entry{} = entry, max_rows, columns, _rechunk) do
223
+ case Native.lf_from_parquet(entry.path, max_rows, columns) do
224
+ {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf)
225
+ {:error, error} -> {:error, RuntimeError.exception(error)}
226
+ end
227
+ end
228
+
229
+ @impl true
230
+ def from_ndjson(%S3.Entry{}, _, _) do
231
+ {:error,
232
+ ArgumentError.exception("reading NDJSON from AWS S3 is not supported for Lazy dataframes")}
233
+ end
234
+
235
+ @impl true
236
+ def from_ndjson(%Local.Entry{} = entry, infer_schema_length, batch_size) do
237
+ case Native.lf_from_ndjson(entry.path, infer_schema_length, batch_size) do
238
+ {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf)
239
+ {:error, error} -> {:error, RuntimeError.exception(error)}
240
+ end
241
+ end
242
+
243
+ @impl true
244
+ def from_ndjson(%HTTP.Entry{url: url}, infer_schema_length, batch_size) do
245
+ case Native.lf_from_ndjson(url, infer_schema_length, batch_size) do
246
+ {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf)
247
+ {:error, error} -> {:error, RuntimeError.exception(error)}
248
+ end
249
+ end
250
+
251
+ @impl true
252
+ def from_ipc(%S3.Entry{}, _) do
253
+ {:error,
254
+ ArgumentError.exception("reading IPC from AWS S3 is not supported for Lazy dataframes")}
255
+ end
256
+
257
+ @impl true
258
+ def from_ipc(%Local.Entry{} = entry, columns) when is_nil(columns) do
259
+ case Native.lf_from_ipc(entry.path) do
260
+ {:ok, polars_ldf} -> Shared.create_dataframe(polars_ldf)
261
+ {:error, error} -> {:error, RuntimeError.exception(error)}
262
+ end
263
+ end
264
+
265
+ @impl true
266
+ def from_ipc(%Local.Entry{}, _columns) do
267
+ {:error,
268
+ ArgumentError.exception(
269
+ "`columns` is not supported by Polars' lazy backend. " <>
270
+ "Consider using `select/2` after reading the IPC file"
271
+ )}
272
+ end
273
+
274
+ @impl true
275
+ def from_ipc_stream(%S3.Entry{}, _) do
276
+ {:error,
277
+ ArgumentError.exception(
278
+ "reading IPC Stream from AWS S3 is not supported for Lazy dataframes"
279
+ )}
280
+ end
281
+
282
+ @impl true
283
+ def from_ipc_stream(%Local.Entry{} = fs_entry, columns) do
284
+ with {:ok, df} <- Eager.from_ipc_stream(fs_entry, columns) do
285
+ {:ok, Eager.lazy(df)}
286
+ end
287
+ end
288
+
289
+ @impl true
290
+ def load_csv(
291
+ contents,
292
+ dtypes,
293
+ delimiter,
294
+ nil_values,
295
+ skip_rows,
296
+ skip_rows_after_header,
297
+ header?,
298
+ encoding,
299
+ max_rows,
300
+ columns,
301
+ infer_schema_length,
302
+ parse_dates,
303
+ eol_delimiter
304
+ ) do
305
+ with {:ok, df} <-
306
+ Eager.load_csv(
307
+ contents,
308
+ dtypes,
309
+ delimiter,
310
+ nil_values,
311
+ skip_rows,
312
+ skip_rows_after_header,
313
+ header?,
314
+ encoding,
315
+ max_rows,
316
+ columns,
317
+ infer_schema_length,
318
+ parse_dates,
319
+ eol_delimiter
320
+ ) do
321
+ {:ok, Eager.lazy(df)}
322
+ end
323
+ end
324
+
325
+ @impl true
326
+ def load_parquet(contents) do
327
+ with {:ok, df} <- Eager.load_parquet(contents) do
328
+ {:ok, Eager.lazy(df)}
329
+ end
330
+ end
331
+
332
+ @impl true
333
+ def load_ndjson(contents, infer_schema_length, batch_size) do
334
+ with {:ok, df} <- Eager.load_ndjson(contents, infer_schema_length, batch_size) do
335
+ {:ok, Eager.lazy(df)}
336
+ end
337
+ end
338
+
339
+ @impl true
340
+ def load_ipc(contents, columns) do
341
+ with {:ok, df} <- Eager.load_ipc(contents, columns) do
342
+ {:ok, Eager.lazy(df)}
343
+ end
344
+ end
345
+
346
+ @impl true
347
+ def load_ipc_stream(contents, columns) do
348
+ with {:ok, df} <- Eager.load_ipc_stream(contents, columns) do
349
+ {:ok, Eager.lazy(df)}
350
+ end
351
+ end
352
+
353
+ @impl true
354
+ def to_csv(%DF{} = ldf, %Local.Entry{} = entry, header?, delimiter, streaming) do
355
+ <<delimiter::utf8>> = delimiter
356
+
357
+ case Native.lf_to_csv(ldf.data, entry.path, header?, delimiter, streaming) do
358
+ {:ok, _} -> :ok
359
+ {:error, error} -> {:error, RuntimeError.exception(error)}
360
+ end
361
+ end
362
+
363
+ @impl true
364
+ def to_csv(%DF{} = ldf, %S3.Entry{} = entry, header?, delimiter, _streaming) do
365
+ eager_df = compute(ldf)
366
+
367
+ Eager.to_csv(eager_df, entry, header?, delimiter, false)
368
+ end
369
+
370
+ @impl true
371
+ def to_parquet(%DF{} = ldf, %Local.Entry{} = entry, {compression, level}, streaming) do
372
+ case Native.lf_to_parquet(
373
+ ldf.data,
374
+ entry.path,
375
+ Shared.parquet_compression(compression, level),
376
+ streaming
377
+ ) do
378
+ {:ok, _} -> :ok
379
+ {:error, error} -> {:error, RuntimeError.exception(error)}
380
+ end
381
+ end
382
+
383
+ @impl true
384
+ def to_parquet(%DF{} = ldf, %S3.Entry{} = entry, {compression, level}, _streaming = true) do
385
+ case Native.lf_to_parquet_cloud(
386
+ ldf.data,
387
+ entry,
388
+ Shared.parquet_compression(compression, level)
389
+ ) do
390
+ {:ok, _} -> :ok
391
+ {:error, error} -> {:error, RuntimeError.exception(error)}
392
+ end
393
+ end
394
+
395
+ @impl true
396
+ def to_parquet(%DF{} = ldf, %S3.Entry{} = entry, compression, _streaming = false) do
397
+ eager_df = compute(ldf)
398
+
399
+ Eager.to_parquet(eager_df, entry, compression, false)
400
+ end
401
+
402
+ @impl true
403
+ def to_ipc(%DF{} = ldf, %Local.Entry{} = entry, {compression, _level}, streaming) do
404
+ case Native.lf_to_ipc(ldf.data, entry.path, Atom.to_string(compression), streaming) do
405
+ {:ok, _} -> :ok
406
+ {:error, error} -> {:error, RuntimeError.exception(error)}
407
+ end
408
+ end
409
+
410
+ @impl true
411
+ def to_ipc(%DF{} = ldf, %S3.Entry{} = entry, {compression, _level}, _streaming = true) do
412
+ case Native.lf_to_ipc_cloud(
413
+ ldf.data,
414
+ entry,
415
+ Atom.to_string(compression)
416
+ ) do
417
+ {:ok, _} -> :ok
418
+ {:error, error} -> {:error, RuntimeError.exception(error)}
419
+ end
420
+ end
421
+
422
+ @impl true
423
+ def to_ipc(%DF{} = ldf, %S3.Entry{} = entry, compression, _streaming = false) do
424
+ eager_df = compute(ldf)
425
+
426
+ Eager.to_ipc(eager_df, entry, compression, false)
427
+ end
428
+
429
+ @impl true
430
+ def filter_with(df, out_df, %LazySeries{} = lseries) do
431
+ expression =
432
+ if df.groups == [] do
433
+ to_expr(lseries)
434
+ else
435
+ lseries
436
+ |> to_expr()
437
+ |> Native.expr_over(groups_exprs(df.groups))
438
+ end
439
+
440
+ Shared.apply_dataframe(df, out_df, :lf_filter_with, [expression])
441
+ end
442
+
443
+ @impl true
444
+ def sort_with(
445
+ %DF{} = df,
446
+ out_df,
447
+ column_pairs,
448
+ maintain_order?,
449
+ multithreaded?,
450
+ nulls_last?
451
+ )
452
+ when is_boolean(maintain_order?) and is_boolean(multithreaded?) and
453
+ is_boolean(nulls_last?) do
454
+ {directions, expressions} =
455
+ column_pairs
456
+ |> Enum.map(fn {direction, lazy_series} -> {direction == :desc, to_expr(lazy_series)} end)
457
+ |> Enum.unzip()
458
+
459
+ if df.groups == [] do
460
+ Shared.apply_dataframe(
461
+ df,
462
+ out_df,
463
+ :lf_sort_with,
464
+ [
465
+ expressions,
466
+ directions,
467
+ maintain_order?,
468
+ nulls_last?
469
+ ]
470
+ )
471
+ else
472
+ # TODO: log that we cannot set `maintain_order?` nor `nulls_last?`
473
+ # This is a limitation of the grouped lazy frame.
474
+ Shared.apply_dataframe(
475
+ df,
476
+ out_df,
477
+ :lf_grouped_sort_with,
478
+ [
479
+ expressions,
480
+ groups_exprs(df.groups),
481
+ directions
482
+ ]
483
+ )
484
+ end
485
+ end
486
+
487
+ @impl true
488
+ def distinct(%DF{} = df, %DF{} = out_df, columns) do
489
+ maybe_columns_to_keep =
490
+ if df.names != out_df.names, do: Enum.map(out_df.names, &Native.expr_column/1)
491
+
492
+ Shared.apply_dataframe(df, out_df, :lf_distinct, [columns, maybe_columns_to_keep])
493
+ end
494
+
495
+ @impl true
496
+ def mutate_with(%DF{} = df, %DF{} = out_df, column_pairs) do
497
+ maybe_over_groups_fun =
498
+ if df.groups == [] do
499
+ &Function.identity/1
500
+ else
501
+ fn expr -> Native.expr_over(expr, groups_exprs(df.groups)) end
502
+ end
503
+
504
+ exprs =
505
+ for {name, lazy_series} <- column_pairs do
506
+ lazy_series
507
+ |> to_expr()
508
+ |> then(maybe_over_groups_fun)
509
+ |> alias_expr(name)
510
+ end
511
+
512
+ Shared.apply_dataframe(df, out_df, :lf_mutate_with, [exprs])
513
+ end
514
+
515
+ @impl true
516
+ def rename(%DF{} = df, %DF{} = out_df, pairs),
517
+ do: Shared.apply_dataframe(df, out_df, :lf_rename_columns, [pairs])
518
+
519
+ @impl true
520
+ def drop_nil(%DF{} = df, columns) do
521
+ exprs = for col <- columns, do: Native.expr_column(col)
522
+ Shared.apply_dataframe(df, df, :lf_drop_nils, [exprs])
523
+ end
524
+
525
+ @impl true
526
+ def pivot_longer(%DF{} = df, %DF{} = out_df, cols_to_pivot, cols_to_keep, names_to, values_to) do
527
+ Shared.apply_dataframe(
528
+ df,
529
+ out_df,
530
+ :lf_pivot_longer,
531
+ [
532
+ cols_to_keep,
533
+ cols_to_pivot,
534
+ names_to,
535
+ values_to
536
+ ]
537
+ )
538
+ end
539
+
540
+ @impl true
541
+ def explode(%DF{} = df, %DF{} = out_df, columns),
542
+ do: Shared.apply_dataframe(df, out_df, :lf_explode, [columns])
543
+
544
+ @impl true
545
+ def unnest(%DF{} = df, %DF{} = out_df, columns),
546
+ do: Shared.apply_dataframe(df, out_df, :lf_unnest, [columns])
547
+
548
+ # Groups
549
+
550
+ @impl true
551
+ def summarise_with(%DF{groups: groups} = df, %DF{} = out_df, column_pairs) do
552
+ exprs =
553
+ for {name, lazy_series} <- column_pairs do
554
+ original_expr = to_expr(lazy_series)
555
+ alias_expr(original_expr, name)
556
+ end
557
+
558
+ groups_exprs = for group <- groups, do: Native.expr_column(group)
559
+
560
+ Shared.apply_dataframe(df, out_df, :lf_summarise_with, [groups_exprs, exprs])
561
+ end
562
+
563
+ # Two or more tables
564
+
565
+ @impl true
566
+ def join([%DF{} = left, %DF{} = right], %DF{} = out_df, on, how)
567
+ when is_list(on) and how in [:left, :inner, :cross, :outer] do
568
+ how = Atom.to_string(how)
569
+
570
+ {left_on, right_on} =
571
+ on
572
+ |> Enum.map(fn {left, right} -> {Native.expr_column(left), Native.expr_column(right)} end)
573
+ |> Enum.unzip()
574
+
575
+ Shared.apply_dataframe(
576
+ left,
577
+ out_df,
578
+ :lf_join,
579
+ [right.data, left_on, right_on, how, "_right"]
580
+ )
581
+ end
582
+
583
+ @impl true
584
+ def join([%DF{} = left, %DF{} = right], %DF{} = out_df, on, :right)
585
+ when is_list(on) do
586
+ # Right join is the opposite of left join. So we swap the "on" keys, and swap the DFs
587
+ # in the join.
588
+ {left_on, right_on} =
589
+ on
590
+ |> Enum.map(fn {left, right} -> {Native.expr_column(right), Native.expr_column(left)} end)
591
+ |> Enum.unzip()
592
+
593
+ Shared.apply_dataframe(
594
+ right,
595
+ out_df,
596
+ :lf_join,
597
+ [
598
+ left.data,
599
+ left_on,
600
+ right_on,
601
+ "left",
602
+ "_left"
603
+ ]
604
+ )
605
+ end
606
+
607
+ @impl true
608
+ def concat_rows([%DF{} | _tail] = dfs, %DF{} = out_df) do
609
+ polars_dfs = Enum.map(dfs, fn df -> select(df, out_df).data end)
610
+ %__MODULE__{} = polars_df = Shared.apply(:lf_concat_rows, [polars_dfs])
611
+
612
+ %{out_df | data: polars_df}
613
+ end
614
+
615
+ @impl true
616
+ def sql(ldf, sql_string, table_name) do
617
+ with {:ok, polars_lf} <- Native.lf_sql(ldf.data, sql_string, table_name),
618
+ {:ok, names} <- Native.lf_names(polars_lf),
619
+ {:ok, dtypes} <- Native.lf_dtypes(polars_lf) do
620
+ Explorer.Backend.DataFrame.new(polars_lf, names, dtypes)
621
+ else
622
+ {:error, polars_error} -> raise polars_error
623
+ end
624
+ end
625
+
626
+ @impl true
627
+ def concat_columns([%DF{data: head_data} | tail], %DF{} = out_df) do
628
+ out_ldf_data = Shared.apply(:lf_concat_columns, [[head_data | Enum.map(tail, & &1.data)]])
629
+ %{out_df | data: out_ldf_data}
630
+ end
631
+
632
+ @impl true
633
+ def re_dtype(regex_as_string) when is_binary(regex_as_string) do
634
+ Eager.re_dtype(regex_as_string)
635
+ end
636
+
637
+ not_available_funs = [
638
+ correlation: 4,
639
+ covariance: 3,
640
+ nil_count: 1,
641
+ dummies: 3,
642
+ dump_csv: 3,
643
+ dump_ipc: 2,
644
+ dump_ipc_stream: 2,
645
+ dump_ndjson: 1,
646
+ dump_parquet: 2,
647
+ mask: 2,
648
+ n_rows: 1,
649
+ pivot_wider: 5,
650
+ pull: 2,
651
+ put: 4,
652
+ sample: 5,
653
+ slice: 2,
654
+ to_ipc_stream: 3,
655
+ to_ndjson: 2,
656
+ to_rows: 2,
657
+ to_rows_stream: 3,
658
+ transpose: 4
659
+ ]
660
+
661
+ for {fun, arity} <- not_available_funs do
662
+ args = Macro.generate_arguments(arity, __MODULE__)
663
+
664
+ @impl true
665
+ def unquote(fun)(unquote_splicing(args)) do
666
+ raise "the function `#{unquote(fun)}/#{unquote(arity)}` is not available for the Explorer.PolarsBackend.LazyFrame backend. " <>
667
+ "Please use Explorer.DataFrame.collect/1 and then call this function upon the resultant dataframe"
668
+ end
669
+ end
670
+ end
deps/explorer/lib/explorer/polars_backend/native.ex ADDED
@@ -0,0 +1,490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.PolarsBackend.Native do
2
+ @moduledoc false
3
+
4
+ mix_config = Mix.Project.config()
5
+ version = mix_config[:version]
6
+ github_url = mix_config[:package][:links]["GitHub"]
7
+ # Since Rustler 0.27.0, we need to change manually the mode for each env.
8
+ # We want "debug" in dev and test because it's faster to compile.
9
+ mode = if Mix.env() in [:dev, :test], do: :debug, else: :release
10
+
11
+ use_legacy =
12
+ Application.compile_env(
13
+ :explorer,
14
+ :use_legacy_artifacts,
15
+ System.get_env("EXPLORER_USE_LEGACY_ARTIFACTS") in ["true", "1"]
16
+ )
17
+
18
+ variants_for_linux = [
19
+ legacy_cpu: fn ->
20
+ # These are the same from the release workflow.
21
+ # See the meaning in: https://unix.stackexchange.com/a/43540
22
+ needed_caps = ~w[fxsr sse sse2 ssse3 sse4_1 sse4_2 popcnt avx fma]
23
+
24
+ use_legacy or
25
+ (is_nil(use_legacy) and
26
+ not Explorer.ComptimeUtils.cpu_with_all_caps?(needed_caps))
27
+ end
28
+ ]
29
+
30
+ other_variants = [legacy_cpu: fn -> use_legacy end]
31
+
32
+ use RustlerPrecompiled,
33
+ otp_app: :explorer,
34
+ version: version,
35
+ base_url: "#{github_url}/releases/download/v#{version}",
36
+ targets: ~w(
37
+ aarch64-apple-darwin
38
+ aarch64-unknown-linux-gnu
39
+ aarch64-unknown-linux-musl
40
+ x86_64-apple-darwin
41
+ x86_64-pc-windows-msvc
42
+ x86_64-pc-windows-gnu
43
+ x86_64-unknown-linux-gnu
44
+ x86_64-unknown-linux-musl
45
+ x86_64-unknown-freebsd
46
+ ),
47
+ variants: %{
48
+ "x86_64-unknown-linux-gnu" => variants_for_linux,
49
+ "x86_64-pc-windows-msvc" => other_variants,
50
+ "x86_64-pc-windows-gnu" => other_variants,
51
+ "x86_64-unknown-freebsd" => other_variants
52
+ },
53
+ # We don't use any features of newer NIF versions, so 2.15 is enough.
54
+ nif_versions: ["2.15"],
55
+ mode: mode,
56
+ force_build: System.get_env("EXPLORER_BUILD") in ["1", "true"]
57
+
58
+ defstruct [:inner]
59
+
60
+ def df_from_arrow_stream_pointer(_stream_ptr), do: err()
61
+
62
+ def df_sort_by(_df, _by, _reverse, _maintain_order?, _multithreaded?, _nulls_last?, _groups),
63
+ do: err()
64
+
65
+ def df_sort_with(
66
+ _df,
67
+ _expressions,
68
+ _directions,
69
+ _maintain_order?,
70
+ _multithreaded?,
71
+ _nulls_last?,
72
+ _groups
73
+ ),
74
+ do: err()
75
+
76
+ def df_concat_columns(_dfs), do: err()
77
+ def df_drop(_df, _name), do: err()
78
+ def df_dtypes(_df), do: err()
79
+ def df_dump_csv(_df, _has_headers, _delimiter), do: err()
80
+ def df_dump_ndjson(_df), do: err()
81
+ def df_dump_parquet(_df, _compression), do: err()
82
+ def df_dump_ipc(_df, _compression), do: err()
83
+ def df_dump_ipc_stream(_df, _compression), do: err()
84
+
85
+ def df_from_csv(
86
+ _filename,
87
+ _infer_schema_length,
88
+ _has_header,
89
+ _stop_after_n_rows,
90
+ _skip_rows,
91
+ _skip_rows_after_header,
92
+ _projection,
93
+ _sep,
94
+ _rechunk,
95
+ _columns,
96
+ _dtypes,
97
+ _encoding,
98
+ _nil_vals,
99
+ _parse_dates,
100
+ _eol_delimiter
101
+ ),
102
+ do: err()
103
+
104
+ def df_from_ipc(_filename, _columns, _projection), do: err()
105
+ def df_from_ipc_stream(_filename, _columns, _projection), do: err()
106
+ def df_from_ndjson(_filename, _infer_schema_length, _batch_size), do: err()
107
+
108
+ def df_from_parquet(
109
+ _filename,
110
+ _stop_after_n_rows,
111
+ _columns,
112
+ _projection,
113
+ _rechunk
114
+ ),
115
+ do: err()
116
+
117
+ def df_from_series(_columns), do: err()
118
+ def df_group_indices(_df, _column_names), do: err()
119
+ def df_groups(_df, _column_names), do: err()
120
+
121
+ def df_load_csv(
122
+ _binary,
123
+ _infer_schema_length,
124
+ _has_header,
125
+ _stop_after_n_rows,
126
+ _skip_rows,
127
+ _skip_rows_after_header,
128
+ _projection,
129
+ _sep,
130
+ _rechunk,
131
+ _columns,
132
+ _dtypes,
133
+ _encoding,
134
+ _nil_vals,
135
+ _parse_dates,
136
+ _eol_delimiter
137
+ ),
138
+ do: err()
139
+
140
+ def df_load_ipc(_binary, _columns, _projection), do: err()
141
+ def df_load_ipc_stream(_binary, _columns, _projection), do: err()
142
+ def df_load_ndjson(_binary, _infer_schema_length, _batch_size), do: err()
143
+ def df_load_parquet(_binary), do: err()
144
+
145
+ def df_mask(_df, _mask), do: err()
146
+ def df_n_rows(_df), do: err()
147
+ def df_names(_df), do: err()
148
+ def df_pivot_wider(_df, _id_columns, _pivot_column, _values_column, _names_prefix), do: err()
149
+ def df_pull(_df, _name), do: err()
150
+ def df_put_column(_df, _series), do: err()
151
+ def df_sample_frac(_df, _frac, _with_replacement, _shuffle, _seed, _groups), do: err()
152
+ def df_sample_n(_df, _n, _with_replacement, _shuffle, _seed, _groups), do: err()
153
+ def df_select_at_idx(_df, _idx), do: err()
154
+ def df_shape(_df), do: err()
155
+ def df_slice(_df, _offset, _length, _groups), do: err()
156
+ def df_slice_by_indices(_df, _indices, _groups), do: err()
157
+ def df_slice_by_series(_df, _series, _groups), do: err()
158
+ def df_transpose(_df, _keep_names_as, _new_col_names), do: err()
159
+ def df_to_csv(_df, _filename, _has_headers, _delimiter), do: err()
160
+ def df_to_csv_cloud(_df, _ex_entry, _has_headers, _delimiter), do: err()
161
+ def df_to_dummies(_df, _columns), do: err()
162
+ def df_to_ipc(_df, _filename, _compression), do: err()
163
+ def df_to_ipc_cloud(_df, _ex_entry, _compression), do: err()
164
+ def df_to_ipc_stream(_df, _filename, _compression), do: err()
165
+ def df_to_ipc_stream_cloud(_df, _ex_entry, _compression), do: err()
166
+ def df_lazy(_df), do: err()
167
+ def df_to_ndjson(_df, _filename), do: err()
168
+ def df_to_ndjson_cloud(_df, _ex_entry), do: err()
169
+ def df_to_parquet(_df, _filename, _compression), do: err()
170
+ def df_to_parquet_cloud(_df, _ex_entry, _compression), do: err()
171
+ def df_width(_df), do: err()
172
+ def df_nil_count(_df), do: err()
173
+ def df_re_dtype(_pattern), do: err()
174
+
175
+ # Expressions (for lazy queries)
176
+ @multi_arity_expressions [slice: 2, slice: 3, log: 1, log: 2]
177
+
178
+ # We first generate functions for known operations.
179
+ for {op, arity} <- Explorer.Backend.LazySeries.operations() -- @multi_arity_expressions do
180
+ args = Macro.generate_arguments(arity, __MODULE__)
181
+ expr_op = :"expr_#{op}"
182
+ def unquote(expr_op)(unquote_splicing(args)), do: err()
183
+ end
184
+
185
+ def expr_slice(_lazy_series, _offset, _length), do: err()
186
+ def expr_slice_by_indices(_lazy_series, _series), do: err()
187
+
188
+ def expr_log(_lazy_series, _base), do: err()
189
+ def expr_log_natural(_lazy_series), do: err()
190
+
191
+ # Then we generate for some specific expressions
192
+ def expr_alias(_ex_expr, _alias_name), do: err()
193
+ def expr_nil(), do: err()
194
+ def expr_atom(_atom), do: err()
195
+ def expr_boolean(_bool), do: err()
196
+ def expr_date(_date), do: err()
197
+ def expr_naive_datetime(_datetime), do: err()
198
+ def expr_datetime(_datetime), do: err()
199
+ def expr_duration(_duration), do: err()
200
+ def expr_describe_filter_plan(_df, _expr), do: err()
201
+ def expr_float(_number), do: err()
202
+ def expr_integer(_number), do: err()
203
+ def expr_int_range(_start, _end, _step, _dtype), do: err()
204
+ def expr_over(_ex_expr, _groups_exprs), do: err()
205
+ def expr_series(_series), do: err()
206
+ def expr_string(_string), do: err()
207
+ def expr_struct(_map), do: err()
208
+
209
+ # LazyFrame
210
+ def lf_compute(_df), do: err()
211
+ def lf_describe_plan(_df, _optimized), do: err()
212
+ def lf_drop(_df, _columns), do: err()
213
+ def lf_dtypes(_df), do: err()
214
+ def lf_fetch(_df, _n_rows), do: err()
215
+ def lf_head(_df, _n_rows, _groups), do: err()
216
+ def lf_names(_df), do: err()
217
+ def lf_select(_df, _columns), do: err()
218
+ def lf_tail(_df, _n_rows, _groups), do: err()
219
+ def lf_slice(_df, _offset, _length, _groups), do: err()
220
+ def lf_explode(_df, _columns), do: err()
221
+ def lf_unnest(_df, _columns), do: err()
222
+ def lf_from_ipc(_filename), do: err()
223
+ def lf_from_ndjson(_filename, _infer_schema_length, _batch_size), do: err()
224
+ def lf_from_parquet(_filename, _stop_after_n_rows, _maybe_columns), do: err()
225
+ def lf_from_parquet_cloud(_ex_s3_entry, _stop_after_n_rows, _maybe_columns), do: err()
226
+
227
+ def lf_from_csv(
228
+ _filename,
229
+ _infer_schema_length,
230
+ _has_header,
231
+ _stop_after_n_rows,
232
+ _skip_rows,
233
+ _skip_rows_after_header,
234
+ _sep,
235
+ _rechunk,
236
+ _dtypes,
237
+ _encoding,
238
+ _nil_vals,
239
+ _parse_dates,
240
+ _eol_delimiter
241
+ ),
242
+ do: err()
243
+
244
+ def lf_filter_with(_df, _expression), do: err()
245
+
246
+ def lf_sort_with(
247
+ _df,
248
+ _expressions,
249
+ _directions,
250
+ _maintain_order?,
251
+ _nulls_last?
252
+ ),
253
+ do: err()
254
+
255
+ def lf_grouped_sort_with(
256
+ _df,
257
+ _expressions,
258
+ _groups_expr,
259
+ _directions
260
+ ),
261
+ do: err()
262
+
263
+ def lf_distinct(_df, _subset, _selection), do: err()
264
+ def lf_mutate_with(_df, _exprs), do: err()
265
+ def lf_summarise_with(_df, _groups, _aggs), do: err()
266
+ def lf_rename_columns(_df, _column_pairs), do: err()
267
+ def lf_drop_nils(_df, _column_pairs), do: err()
268
+ def lf_pivot_longer(_df, _id_vars, _value_vars, _names_to, _values_to), do: err()
269
+ def lf_join(_df, _other, _left_on, _right_on, _how, _suffix), do: err()
270
+ def lf_concat_rows(_dfs), do: err()
271
+ def lf_concat_columns(_ldfs), do: err()
272
+ def lf_to_parquet(_df, _filename, _compression, _streaming), do: err()
273
+ def lf_to_parquet_cloud(_df, _filename, _compression), do: err()
274
+ def lf_to_ipc(_df, _filename, _compression, _streaming), do: err()
275
+ def lf_to_ipc_cloud(_df, _cloud_entry, _compression), do: err()
276
+ def lf_to_csv(_df, _filename, _header, _delimiter, _streaming), do: err()
277
+ def lf_sql(_df, _sql_string, _table_name), do: err()
278
+
279
+ # Series
280
+ def s_as_str(_s), do: err()
281
+ def s_add(_s, _other), do: err()
282
+ def s_all(_s), do: err()
283
+ def s_and(_s, _s2), do: err()
284
+ def s_any(_s), do: err()
285
+ def s_argmax(_s), do: err()
286
+ def s_argmin(_s), do: err()
287
+ def s_argsort(_s, _descending?, _maintain_order?, _multithreaded?, _nulls_last?), do: err()
288
+ def s_cast(_s, _dtype), do: err()
289
+ def s_categories(_s), do: err()
290
+ def s_categorise(_s, _s_categories), do: err()
291
+ def s_coalesce(_s, _other), do: err()
292
+ def s_concat(_series_list), do: err()
293
+ def s_contains(_s, _pattern, _is_literal), do: err()
294
+ def s_count_matches(_s, _pattern, _is_literal), do: err()
295
+ def s_re_scan(_s, _pattern), do: err()
296
+ def s_re_named_captures(_s, _pattern), do: err()
297
+ def s_cumulative_max(_s, _reverse), do: err()
298
+ def s_cumulative_min(_s, _reverse), do: err()
299
+ def s_cumulative_sum(_s, _reverse), do: err()
300
+ def s_cumulative_product(_s, _reverse), do: err()
301
+ def s_skew(_s, _bias), do: err()
302
+ def s_correlation(_s1, _s2, _ddof, _method), do: err()
303
+ def s_covariance(_s1, _s2, _ddof), do: err()
304
+ def s_distinct(_s), do: err()
305
+ def s_divide(_s, _other), do: err()
306
+ def s_dtype(_s), do: err()
307
+ def s_equal(_s, _rhs), do: err()
308
+ def s_exp(_s), do: err()
309
+ def s_abs(_s), do: err()
310
+ def s_strptime(_s, _format_string, _precision), do: err()
311
+ def s_strftime(_s, _format_string), do: err()
312
+ def s_clip_integer(_s, _min, _max), do: err()
313
+ def s_clip_float(_s, _min, _max), do: err()
314
+ def s_fill_missing_with_strategy(_s, _strategy), do: err()
315
+ def s_fill_missing_with_boolean(_s, _value), do: err()
316
+ def s_fill_missing_with_bin(_s, _value), do: err()
317
+ def s_fill_missing_with_float(_s, _value), do: err()
318
+ def s_fill_missing_with_int(_s, _value), do: err()
319
+ def s_fill_missing_with_atom(_s, _value), do: err()
320
+ def s_fill_missing_with_date(_s, _value), do: err()
321
+ def s_fill_missing_with_datetime(_s, _value), do: err()
322
+ def s_fill_missing_with_decimal(_s, _value), do: err()
323
+ def s_greater(_s, _rhs), do: err()
324
+ def s_greater_equal(_s, _rhs), do: err()
325
+ def s_head(_s, _length), do: err()
326
+ def s_is_finite(_s), do: err()
327
+ def s_is_infinite(_s), do: err()
328
+ def s_is_nan(_s), do: err()
329
+ def s_is_not_null(_s), do: err()
330
+ def s_is_null(_s), do: err()
331
+ def s_less(_s, _rhs), do: err()
332
+ def s_less_equal(_s, _rhs), do: err()
333
+ def s_lstrip(_s, _string), do: err()
334
+ def s_mask(_s, _filter), do: err()
335
+ def s_max(_s), do: err()
336
+ def s_mean(_s), do: err()
337
+ def s_median(_s), do: err()
338
+ def s_product(_s), do: err()
339
+ def s_min(_s), do: err()
340
+ def s_mode(_s), do: err()
341
+ def s_multiply(_s, _other), do: err()
342
+ def s_n_chunks(_s), do: err()
343
+ def s_n_distinct(_s), do: err()
344
+ def s_name(_s), do: err()
345
+ def s_nil_count(_s), do: err()
346
+ def s_not(_s), do: err()
347
+ def s_from_list_null(_name, _val), do: err()
348
+ def s_from_list_bool(_name, _val), do: err()
349
+ def s_from_list_date(_name, _val), do: err()
350
+ def s_from_list_time(_name, _val), do: err()
351
+ def s_from_list_naive_datetime(_name, _val, _precision), do: err()
352
+ def s_from_list_datetime(_name, _val, _precision, _tz), do: err()
353
+ def s_from_list_duration(_name, _val, _precision), do: err()
354
+ def s_from_list_f32(_name, _val), do: err()
355
+ def s_from_list_f64(_name, _val), do: err()
356
+ def s_from_list_s8(_name, _val), do: err()
357
+ def s_from_list_s16(_name, _val), do: err()
358
+ def s_from_list_s32(_name, _val), do: err()
359
+ def s_from_list_s64(_name, _val), do: err()
360
+ def s_from_list_u8(_name, _val), do: err()
361
+ def s_from_list_u16(_name, _val), do: err()
362
+ def s_from_list_u32(_name, _val), do: err()
363
+ def s_from_list_u64(_name, _val), do: err()
364
+ def s_from_list_str(_name, _val), do: err()
365
+ def s_from_list_binary(_name, _val), do: err()
366
+ def s_from_list_categories(_name, _val), do: err()
367
+ def s_from_list_decimal(_name, _val, _precision, _scale), do: err()
368
+ def s_from_list_of_series(_name, _val, _dtype), do: err()
369
+ def s_from_list_of_series_as_structs(_name, _val, _dtype), do: err()
370
+ def s_from_binary_f32(_name, _val), do: err()
371
+ def s_from_binary_f64(_name, _val), do: err()
372
+ def s_from_binary_s8(_name, _val), do: err()
373
+ def s_from_binary_s16(_name, _val), do: err()
374
+ def s_from_binary_s32(_name, _val), do: err()
375
+ def s_from_binary_s64(_name, _val), do: err()
376
+ def s_from_binary_u8(_name, _val), do: err()
377
+ def s_from_binary_u16(_name, _val), do: err()
378
+ def s_from_binary_u32(_name, _val), do: err()
379
+ def s_from_binary_u64(_name, _val), do: err()
380
+ def s_not_equal(_s, _rhs), do: err()
381
+ def s_or(_s, _s2), do: err()
382
+ def s_peak_max(_s), do: err()
383
+ def s_peak_min(_s), do: err()
384
+ def s_select(_pred, _on_true, _on_false), do: err()
385
+ def s_log_natural(_s_argument), do: err()
386
+ def s_log(_s_argument, _base_as_float), do: err()
387
+ def s_quantile(_s, _quantile, _strategy), do: err()
388
+ def s_quotient(_s, _rhs), do: err()
389
+ def s_remainder(_s, _rhs), do: err()
390
+ def s_rename(_s, _name), do: err()
391
+ def s_reverse(_s), do: err()
392
+ def s_round(_s, _decimals), do: err()
393
+ def s_row_index(_s), do: err()
394
+ def s_floor(_s), do: err()
395
+ def s_ceil(_s), do: err()
396
+ def s_rstrip(_s, _string), do: err()
397
+ def s_rank(_s, _method, _descending, _seed), do: err()
398
+ def s_replace(_s, _pattern, _replacement, _literal), do: err()
399
+ def s_sample_n(_s, _n, _replace, _shuffle, _seed), do: err()
400
+ def s_sample_frac(_s, _frac, _replace, _shuffle, _seed), do: err()
401
+ def s_series_equal(_s, _other, _null_equal), do: err()
402
+ def s_size(_s), do: err()
403
+ def s_slice(_s, _offset, _length), do: err()
404
+ def s_slice_by_indices(_s, _indices), do: err()
405
+ def s_slice_by_series(_s, _series), do: err()
406
+ def s_sort(_s, _descending?, _maintain_order?, _multithreaded?, _nulls_last?), do: err()
407
+ def s_standard_deviation(_s, _ddof), do: err()
408
+ def s_strip(_s, _string), do: err()
409
+ def s_subtract(_s, _other), do: err()
410
+ def s_sum(_s), do: err()
411
+ def s_tail(_s, _length), do: err()
412
+ def s_shift(_s, _offset), do: err()
413
+ def s_at(_s, _rhs), do: err()
414
+ def s_at_every(_s, _n), do: err()
415
+ def s_to_list(_s), do: err()
416
+ def s_downcase(_s), do: err()
417
+ def s_to_iovec(_s), do: err()
418
+ def s_upcase(_s), do: err()
419
+ def s_unordered_distinct(_s), do: err()
420
+ def s_frequencies(_s), do: err()
421
+
422
+ def s_cut(
423
+ _s,
424
+ _bins,
425
+ _labels,
426
+ _break_point_label,
427
+ _category_label,
428
+ _left_close,
429
+ _include_breaks
430
+ ),
431
+ do: err()
432
+
433
+ def s_substring(_s, _offset, _length), do: err()
434
+ def s_split(_s, _by), do: err()
435
+ def s_split_into(_s, _by, _num_fields), do: err()
436
+
437
+ def s_qcut(
438
+ _s,
439
+ _quantiles,
440
+ _labels,
441
+ _break_point_label,
442
+ _category_label,
443
+ _allow_duplicates,
444
+ _left_close,
445
+ _include_breaks
446
+ ),
447
+ do: err()
448
+
449
+ def s_variance(_s, _ddof), do: err()
450
+ def s_window_max(_s, _window_size, _weight, _ignore_null, _min_periods), do: err()
451
+ def s_window_mean(_s, _window_size, _weight, _ignore_null, _min_periods), do: err()
452
+ def s_window_median(_s, _window_size, _weight, _ignore_null, _min_periods), do: err()
453
+ def s_window_min(_s, _window_size, _weight, _ignore_null, _min_periods), do: err()
454
+ def s_window_sum(_s, _window_size, _weight, _ignore_null, _min_periods), do: err()
455
+
456
+ def s_window_standard_deviation(_s, _window_size, _weight, _ignore_null, _min_periods),
457
+ do: err()
458
+
459
+ def s_ewm_mean(_s, _alpha, _adjust, _min_periods, _ignore_nils), do: err()
460
+ def s_ewm_standard_deviation(_s, _alpha, _adjust, _bias, _min_periods, _ignore_nils), do: err()
461
+ def s_ewm_variance(_s, _alpha, _adjust, _bias, _min_periods, _ignore_nils), do: err()
462
+ def s_in(_s, _other), do: err()
463
+ def s_day_of_week(_s), do: err()
464
+ def s_day_of_year(_s), do: err()
465
+ def s_week_of_year(_s), do: err()
466
+ def s_month(_s), do: err()
467
+ def s_year(_s), do: err()
468
+ def s_hour(_s), do: err()
469
+ def s_minute(_s), do: err()
470
+ def s_second(_s), do: err()
471
+ def s_sin(_s), do: err()
472
+ def s_cos(_s), do: err()
473
+ def s_tan(_s), do: err()
474
+ def s_asin(_s), do: err()
475
+ def s_acos(_s), do: err()
476
+ def s_atan(_s), do: err()
477
+
478
+ def s_join(_s, _separator), do: err()
479
+ def s_lengths(_s), do: err()
480
+ def s_member(_s, _value, _inner_dtype), do: err()
481
+
482
+ def s_field(_s, _name), do: err()
483
+ def s_json_decode(_s, _dtype), do: err()
484
+ def s_json_path_match(_s, _json_path), do: err()
485
+
486
+ def message_on_gc(_pid, _payload), do: err()
487
+ def is_message_on_gc(_term), do: err()
488
+
489
+ defp err, do: :erlang.nif_error(:nif_not_loaded)
490
+ end
deps/explorer/lib/explorer/polars_backend/series.ex ADDED
@@ -0,0 +1,899 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.PolarsBackend.Series do
2
+ @moduledoc false
3
+
4
+ alias Explorer.DataFrame
5
+ alias Explorer.PolarsBackend.Shared
6
+ alias Explorer.Series
7
+
8
+ @type t :: %__MODULE__{resource: reference()}
9
+
10
+ defstruct resource: nil
11
+
12
+ @behaviour Explorer.Backend.Series
13
+
14
+ defguardp is_non_finite(n) when n in [:nan, :infinity, :neg_infinity]
15
+ defguardp is_numeric(n) when is_number(n) or is_non_finite(n)
16
+
17
+ @integer_types Explorer.Shared.integer_types()
18
+ @numeric_types Explorer.Shared.numeric_types()
19
+
20
+ # Conversion
21
+
22
+ @impl true
23
+ def from_list(data, type) when is_list(data) do
24
+ series = Shared.from_list(data, type)
25
+
26
+ Explorer.Backend.Series.new(series, type)
27
+ end
28
+
29
+ @impl true
30
+ def from_binary(data, dtype) when is_binary(data) do
31
+ series = Shared.from_binary(data, dtype)
32
+ Explorer.Backend.Series.new(series, dtype)
33
+ end
34
+
35
+ @impl true
36
+ def to_list(series), do: Shared.apply_series(series, :s_to_list)
37
+
38
+ @impl true
39
+ def to_iovec(series), do: Shared.apply_series(series, :s_to_iovec)
40
+
41
+ @impl true
42
+ def cast(%Series{dtype: :string} = series, {:naive_datetime, precision}),
43
+ do: Shared.apply_series(series, :s_strptime, [nil, precision])
44
+
45
+ def cast(series, dtype),
46
+ do: Shared.apply_series(series, :s_cast, [dtype])
47
+
48
+ @impl true
49
+ def strptime(%Series{} = series, format_string) do
50
+ Shared.apply_series(series, :s_strptime, [format_string, nil])
51
+ end
52
+
53
+ @impl true
54
+ def strftime(%Series{} = series, format_string) do
55
+ Shared.apply_series(series, :s_strftime, [format_string])
56
+ end
57
+
58
+ # Ownership
59
+
60
+ @impl true
61
+ def owner_reference(series), do: series.data.resource
62
+
63
+ @impl true
64
+ def owner_export(series) do
65
+ Explorer.DataFrame.new(series: series)
66
+ |> Explorer.DataFrame.dump_ipc()
67
+ end
68
+
69
+ @impl true
70
+ def owner_import(dumped) do
71
+ with {:ok, df} <- Explorer.DataFrame.load_ipc(dumped) do
72
+ {:ok, df[:series]}
73
+ end
74
+ end
75
+
76
+ # Introspection
77
+
78
+ defp dtype(series), do: Shared.apply_series(series, :s_dtype)
79
+
80
+ @impl true
81
+ def size(series), do: Shared.apply_series(series, :s_size)
82
+
83
+ @impl true
84
+ def categories(%Series{dtype: :category} = series),
85
+ do: Shared.apply_series(series, :s_categories)
86
+
87
+ @impl true
88
+ def categorise(%Series{dtype: {integer_type, _}} = series, %Series{dtype: dtype} = categories)
89
+ when dtype in [:string, :category] and integer_type in [:s, :u],
90
+ do: Shared.apply_series(series, :s_categorise, [categories.data])
91
+
92
+ @impl true
93
+ def categorise(%Series{dtype: :string} = series, %Series{dtype: dtype} = categories)
94
+ when dtype in [:string, :category],
95
+ do: Shared.apply_series(series, :s_categorise, [categories.data])
96
+
97
+ # Slice and dice
98
+
99
+ @impl true
100
+ def head(series, n_elements), do: Shared.apply_series(series, :s_head, [n_elements])
101
+
102
+ @impl true
103
+ def tail(series, n_elements), do: Shared.apply_series(series, :s_tail, [n_elements])
104
+
105
+ @impl true
106
+ def first(series), do: series[0]
107
+
108
+ @impl true
109
+ def last(series), do: series[-1]
110
+
111
+ @impl true
112
+ def shift(series, offset, nil), do: Shared.apply_series(series, :s_shift, [offset])
113
+
114
+ @impl true
115
+ def sample(series, n, replacement, shuffle, seed) when is_integer(n) do
116
+ Shared.apply_series(series, :s_sample_n, [n, replacement, shuffle, seed])
117
+ end
118
+
119
+ @impl true
120
+ def sample(series, frac, replacement, shuffle, seed) when is_float(frac) do
121
+ Shared.apply_series(series, :s_sample_frac, [frac, replacement, shuffle, seed])
122
+ end
123
+
124
+ @impl true
125
+ def rank(series, method, descending, seed) do
126
+ Shared.apply_series(series, :s_rank, [method, descending, seed])
127
+ end
128
+
129
+ @impl true
130
+ def at_every(series, every_n),
131
+ do: Shared.apply_series(series, :s_at_every, [every_n])
132
+
133
+ @impl true
134
+ def mask(series, %Series{} = mask),
135
+ do: Shared.apply_series(series, :s_mask, [mask.data])
136
+
137
+ @impl true
138
+ def slice(series, indices) when is_list(indices),
139
+ do: Shared.apply_series(series, :s_slice_by_indices, [indices])
140
+
141
+ @impl true
142
+ def slice(series, %Series{} = indices),
143
+ do: Shared.apply_series(series, :s_slice_by_series, [indices.data])
144
+
145
+ @impl true
146
+ def slice(series, offset, length), do: Shared.apply_series(series, :s_slice, [offset, length])
147
+
148
+ @impl true
149
+ def at(series, idx), do: Shared.apply_series(series, :s_at, [idx])
150
+
151
+ @impl true
152
+ def format(list) do
153
+ {_, df_args, params} =
154
+ Enum.reduce(list, {0, [], []}, fn s, {counter, df_args, params} ->
155
+ if is_binary(s) or Kernel.is_nil(s) do
156
+ {counter, df_args, [s | params]}
157
+ else
158
+ counter = counter + 1
159
+ name = "#{counter}"
160
+ column = Explorer.Backend.LazySeries.unbacked(:column, [name], :string)
161
+ {counter, [{name, s} | df_args], [column | params]}
162
+ end
163
+ end)
164
+
165
+ df = Explorer.PolarsBackend.DataFrame.from_series(df_args)
166
+ format_expr = Explorer.Backend.LazySeries.unbacked(:format, [Enum.reverse(params)], :string)
167
+ out_dtypes = Map.put(df.dtypes, "result", :string)
168
+ out_names = ["result" | df.names]
169
+ out_df = %{df | dtypes: out_dtypes, names: out_names}
170
+
171
+ Explorer.PolarsBackend.DataFrame.mutate_with(df, out_df, [{"result", format_expr}])
172
+ |> Explorer.PolarsBackend.DataFrame.pull("result")
173
+ end
174
+
175
+ @impl true
176
+ def concat([%Series{} | _] = series) do
177
+ polars_series = for s <- series, do: s.data
178
+
179
+ Shared.apply(:s_concat, [polars_series])
180
+ |> Shared.create_series()
181
+ end
182
+
183
+ @impl true
184
+ def coalesce(s1, s2), do: Shared.apply_series(s1, :s_coalesce, [s2.data])
185
+
186
+ @impl true
187
+ def select(%Series{} = predicate, %Series{} = on_true, %Series{} = on_false) do
188
+ predicate_size = size(predicate)
189
+ on_true_size = size(on_true)
190
+ on_false_size = size(on_false)
191
+ singleton_condition = on_true_size == 1 or on_false_size == 1
192
+
193
+ if on_true_size != on_false_size and not singleton_condition do
194
+ raise ArgumentError,
195
+ "series in select/3 must have the same size or size of 1, got: #{on_true_size} and #{on_false_size}"
196
+ end
197
+
198
+ if predicate_size != 1 and predicate_size != on_true_size and predicate_size != on_false_size and
199
+ not singleton_condition do
200
+ raise ArgumentError,
201
+ "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])}"
202
+ end
203
+
204
+ Shared.apply_series(predicate, :s_select, [on_true.data, on_false.data])
205
+ end
206
+
207
+ # Aggregation
208
+
209
+ @impl true
210
+ # There is no `count` equivalent in Polars, so we need to make our own.
211
+ def count(series), do: size(series) - nil_count(series)
212
+
213
+ @impl true
214
+ def nil_count(series), do: Shared.apply_series(series, :s_nil_count)
215
+
216
+ @impl true
217
+ def sum(series), do: Shared.apply_series(series, :s_sum)
218
+
219
+ @impl true
220
+ def min(series), do: Shared.apply_series(series, :s_min)
221
+
222
+ @impl true
223
+ def max(series), do: Shared.apply_series(series, :s_max)
224
+
225
+ @impl true
226
+ def argmin(series), do: Shared.apply_series(series, :s_argmin)
227
+
228
+ @impl true
229
+ def argmax(series), do: Shared.apply_series(series, :s_argmax)
230
+
231
+ @impl true
232
+ def mean(series), do: Shared.apply_series(series, :s_mean)
233
+
234
+ @impl true
235
+ def median(series), do: Shared.apply_series(series, :s_median)
236
+
237
+ @impl true
238
+ def mode(series), do: Shared.apply_series(series, :s_mode)
239
+
240
+ @impl true
241
+ def variance(series, ddof), do: series |> Shared.apply_series(:s_variance, [ddof]) |> at(0)
242
+
243
+ @impl true
244
+ def standard_deviation(series, ddof),
245
+ do: series |> Shared.apply_series(:s_standard_deviation, [ddof]) |> at(0)
246
+
247
+ @impl true
248
+ def quantile(series, quantile),
249
+ do: Shared.apply_series(series, :s_quantile, [quantile, "nearest"])
250
+
251
+ @impl true
252
+ def product(series), do: first(Shared.apply_series(series, :s_product))
253
+
254
+ @impl true
255
+ def skew(series, bias?),
256
+ do: Shared.apply_series(series, :s_skew, [bias?])
257
+
258
+ @impl true
259
+ def correlation(left, right, ddof, method),
260
+ do:
261
+ Shared.apply_series(matching_size!(left, right), :s_correlation, [right.data, ddof, method])
262
+
263
+ @impl true
264
+ def covariance(left, right, ddof),
265
+ do: Shared.apply_series(matching_size!(left, right), :s_covariance, [right.data, ddof])
266
+
267
+ @impl true
268
+ def all?(series), do: Shared.apply_series(series, :s_all)
269
+
270
+ @impl true
271
+ def any?(series), do: Shared.apply_series(series, :s_any)
272
+
273
+ @impl true
274
+ def row_index(series), do: Shared.apply_series(series, :s_row_index)
275
+
276
+ # Cumulative
277
+
278
+ @impl true
279
+ def cumulative_max(series, reverse?),
280
+ do: Shared.apply_series(series, :s_cumulative_max, [reverse?])
281
+
282
+ @impl true
283
+ def cumulative_min(series, reverse?),
284
+ do: Shared.apply_series(series, :s_cumulative_min, [reverse?])
285
+
286
+ @impl true
287
+ def cumulative_sum(series, reverse?),
288
+ do: Shared.apply_series(series, :s_cumulative_sum, [reverse?])
289
+
290
+ @impl true
291
+ def cumulative_product(series, reverse?),
292
+ do: Shared.apply_series(series, :s_cumulative_product, [reverse?])
293
+
294
+ # Local minima/maxima
295
+
296
+ @impl true
297
+ def peaks(series, :max), do: Shared.apply_series(series, :s_peak_max)
298
+ def peaks(series, :min), do: Shared.apply_series(series, :s_peak_min)
299
+
300
+ # Arithmetic
301
+
302
+ @impl true
303
+ def add(out_dtype, left, right) do
304
+ result = Shared.apply_series(matching_size!(left, right), :s_add, [right.data])
305
+
306
+ if match?({:decimal, _, _}, out_dtype) and out_dtype != dtype(result) do
307
+ cast(result, out_dtype)
308
+ else
309
+ result
310
+ end
311
+ end
312
+
313
+ @impl true
314
+ def subtract(out_dtype, left, right) do
315
+ left = matching_size!(left, right)
316
+
317
+ result = Shared.apply_series(left, :s_subtract, [right.data])
318
+
319
+ if match?({:decimal, _, _}, out_dtype) and out_dtype != dtype(result) do
320
+ cast(result, out_dtype)
321
+ else
322
+ result
323
+ end
324
+ end
325
+
326
+ @impl true
327
+ def multiply(out_dtype, left, right) do
328
+ result = Shared.apply_series(matching_size!(left, right), :s_multiply, [right.data])
329
+
330
+ # Polars currently returns inconsistent dtypes, e.g.:
331
+ # * `integer * duration -> duration` when `integer` is a scalar
332
+ # * `integer * duration -> integer` when `integer` is a series
333
+ # We need to return duration in these cases, so we need an additional cast.
334
+ if (match?({:duration, _}, out_dtype) or match?({:decimal, _, _}, out_dtype)) and
335
+ out_dtype != dtype(result) do
336
+ cast(result, out_dtype)
337
+ else
338
+ result
339
+ end
340
+ end
341
+
342
+ @impl true
343
+ def divide(out_dtype, left, right) do
344
+ result = Shared.apply_series(matching_size!(left, right), :s_divide, [right.data])
345
+
346
+ # Polars currently returns inconsistent dtypes, e.g.:
347
+ # * `duration / integer -> duration` when `integer` is a scalar
348
+ # * `duration / integer -> integer` when `integer` is a series
349
+ # We need to return duration in these cases, so we need an additional cast.
350
+ if (match?({:duration, _}, out_dtype) or match?({:decimal, _, _}, out_dtype)) and
351
+ out_dtype != dtype(result) do
352
+ cast(result, out_dtype)
353
+ else
354
+ result
355
+ end
356
+ end
357
+
358
+ @impl true
359
+ def quotient(left, right),
360
+ do: Shared.apply_series(matching_size!(left, right), :s_quotient, [right.data])
361
+
362
+ @impl true
363
+ def remainder(left, right),
364
+ do: Shared.apply_series(matching_size!(left, right), :s_remainder, [right.data])
365
+
366
+ @impl true
367
+ def pow(out_dtype, left, right) do
368
+ _ = matching_size!(left, right)
369
+
370
+ # We need to pre-cast or we may lose precision.
371
+ left = Explorer.Series.cast(left, out_dtype)
372
+
373
+ left_lazy = Explorer.Backend.LazySeries.unbacked(:column, ["base"], left.dtype)
374
+ right_lazy = Explorer.Backend.LazySeries.unbacked(:column, ["exponent"], right.dtype)
375
+
376
+ {df_args, pow_args} =
377
+ case {size(left), size(right)} do
378
+ {n, n} -> {[{"base", left}, {"exponent", right}], [left_lazy, right_lazy]}
379
+ {1, _} -> {[{"exponent", right}], [Explorer.Series.at(left, 0), right_lazy]}
380
+ {_, 1} -> {[{"base", left}], [left_lazy, Explorer.Series.at(right, 0)]}
381
+ end
382
+
383
+ df = Explorer.PolarsBackend.DataFrame.from_series(df_args)
384
+ pow = Explorer.Backend.LazySeries.unbacked(:pow, pow_args, out_dtype)
385
+
386
+ out_dtypes = Map.put(df.dtypes, "pow", out_dtype)
387
+ out_names = df.names ++ ["pow"]
388
+ out_df = %{df | dtypes: out_dtypes, names: out_names}
389
+
390
+ Explorer.PolarsBackend.DataFrame.mutate_with(df, out_df, [{"pow", pow}])
391
+ |> Explorer.PolarsBackend.DataFrame.pull("pow")
392
+ end
393
+
394
+ @impl true
395
+ def log(%Series{} = argument), do: Shared.apply_series(argument, :s_log_natural, [])
396
+
397
+ @impl true
398
+ def log(%Series{} = argument, base) when is_numeric(base),
399
+ do: Shared.apply_series(argument, :s_log, [base])
400
+
401
+ @impl true
402
+ def exp(%Series{} = s), do: Shared.apply_series(s, :s_exp, [])
403
+
404
+ @impl true
405
+ def abs(%Series{} = s), do: Shared.apply_series(s, :s_abs, [])
406
+
407
+ @impl true
408
+ def clip(%Series{dtype: dtype} = s, min, max)
409
+ when dtype in @integer_types and is_integer(min) and is_integer(max),
410
+ do: Shared.apply_series(s, :s_clip_integer, [min, max])
411
+
412
+ def clip(%Series{} = s, min, max),
413
+ do: s |> cast({:f, 64}) |> Shared.apply_series(:s_clip_float, [min * 1.0, max * 1.0])
414
+
415
+ # Trigonometry
416
+
417
+ @impl true
418
+ def sin(%Series{} = s), do: Shared.apply_series(s, :s_sin, [])
419
+
420
+ @impl true
421
+ def cos(%Series{} = s), do: Shared.apply_series(s, :s_cos, [])
422
+
423
+ @impl true
424
+ def tan(%Series{} = s), do: Shared.apply_series(s, :s_tan, [])
425
+
426
+ @impl true
427
+ def asin(%Series{} = s), do: Shared.apply_series(s, :s_asin, [])
428
+
429
+ @impl true
430
+ def acos(%Series{} = s), do: Shared.apply_series(s, :s_acos, [])
431
+
432
+ @impl true
433
+ def atan(%Series{} = s), do: Shared.apply_series(s, :s_atan, [])
434
+
435
+ # Comparisons
436
+
437
+ @impl true
438
+ def equal(left, right),
439
+ do: Shared.apply_series(matching_size!(left, right), :s_equal, [right.data])
440
+
441
+ @impl true
442
+ def not_equal(left, right),
443
+ do: Shared.apply_series(matching_size!(left, right), :s_not_equal, [right.data])
444
+
445
+ @impl true
446
+ def greater(left, right),
447
+ do: Shared.apply_series(matching_size!(left, right), :s_greater, [right.data])
448
+
449
+ @impl true
450
+ def less(left, right),
451
+ do: Shared.apply_series(matching_size!(left, right), :s_less, [right.data])
452
+
453
+ @impl true
454
+ def greater_equal(left, right),
455
+ do: Shared.apply_series(matching_size!(left, right), :s_greater_equal, [right.data])
456
+
457
+ @impl true
458
+ def less_equal(left, right),
459
+ do: Shared.apply_series(matching_size!(left, right), :s_less_equal, [right.data])
460
+
461
+ @impl true
462
+ def all_equal(%Series{} = left, %Series{} = right),
463
+ do: Shared.apply_series(matching_size!(left, right), :s_series_equal, [right.data, true])
464
+
465
+ @impl true
466
+ def binary_in(%Series{} = left, %Series{} = right),
467
+ do: Shared.apply_series(left, :s_in, [right.data])
468
+
469
+ @impl true
470
+ def binary_and(%Series{} = left, %Series{} = right),
471
+ do: Shared.apply_series(matching_size!(left, right), :s_and, [right.data])
472
+
473
+ @impl true
474
+ def binary_or(%Series{} = left, %Series{} = right),
475
+ do: Shared.apply_series(matching_size!(left, right), :s_or, [right.data])
476
+
477
+ # Float predicates
478
+
479
+ @impl true
480
+ def is_finite(series), do: Shared.apply_series(series, :s_is_finite)
481
+
482
+ @impl true
483
+ def is_infinite(series), do: Shared.apply_series(series, :s_is_infinite)
484
+
485
+ @impl true
486
+ def is_nan(series), do: Shared.apply_series(series, :s_is_nan)
487
+
488
+ # Sort
489
+
490
+ @impl true
491
+ def sort(series, descending?, maintain_order?, multithreaded?, nulls_last?)
492
+ when is_boolean(descending?) and is_boolean(maintain_order?) and is_boolean(multithreaded?) and
493
+ is_boolean(nulls_last?) do
494
+ Shared.apply_series(series, :s_sort, [
495
+ descending?,
496
+ maintain_order?,
497
+ multithreaded?,
498
+ nulls_last?
499
+ ])
500
+ end
501
+
502
+ @impl true
503
+ def argsort(series, descending?, maintain_order?, multithreaded?, nulls_last?)
504
+ when is_boolean(descending?) and is_boolean(maintain_order?) and is_boolean(multithreaded?) and
505
+ is_boolean(nulls_last?) do
506
+ Shared.apply_series(series, :s_argsort, [
507
+ descending?,
508
+ maintain_order?,
509
+ multithreaded?,
510
+ nulls_last?
511
+ ])
512
+ end
513
+
514
+ @impl true
515
+ def reverse(series), do: Shared.apply_series(series, :s_reverse)
516
+
517
+ # Distinct
518
+
519
+ @impl true
520
+ def distinct(series), do: Shared.apply_series(series, :s_distinct)
521
+
522
+ @impl true
523
+ def unordered_distinct(series), do: Shared.apply_series(series, :s_unordered_distinct)
524
+
525
+ @impl true
526
+ def n_distinct(series), do: Shared.apply_series(series, :s_n_distinct)
527
+
528
+ @impl true
529
+ def frequencies(%Series{dtype: {:list, inner_dtype} = dtype})
530
+ when inner_dtype not in @numeric_types do
531
+ raise ArgumentError,
532
+ "frequencies/1 only works with series of lists of numeric types, but #{Explorer.Shared.dtype_to_string(dtype)} was given"
533
+ end
534
+
535
+ def frequencies(%Series{} = series) do
536
+ Shared.apply(:s_frequencies, [series.data])
537
+ |> Shared.create_dataframe!()
538
+ |> DataFrame.rename(["values", "counts"])
539
+ end
540
+
541
+ # Categorisation
542
+
543
+ @impl true
544
+ def cut(series, bins, labels, break_point_label, category_label, left_close, include_breaks) do
545
+ case Explorer.PolarsBackend.Native.s_cut(
546
+ series.data,
547
+ bins,
548
+ labels,
549
+ break_point_label,
550
+ category_label,
551
+ left_close,
552
+ include_breaks
553
+ ) do
554
+ {:ok, polars_df} ->
555
+ Shared.create_dataframe!(polars_df)
556
+
557
+ {:error, "Polars Error: lengths don't match: " <> _rest} ->
558
+ raise ArgumentError, "lengths don't match: labels count must equal bins count"
559
+
560
+ {:error, msg} ->
561
+ raise msg
562
+ end
563
+ end
564
+
565
+ @impl true
566
+ def qcut(
567
+ series,
568
+ quantiles,
569
+ labels,
570
+ break_point_label,
571
+ category_label,
572
+ allow_duplicates,
573
+ left_close,
574
+ include_breaks
575
+ ) do
576
+ Shared.apply(:s_qcut, [
577
+ series.data,
578
+ quantiles,
579
+ labels,
580
+ break_point_label,
581
+ category_label,
582
+ allow_duplicates,
583
+ left_close,
584
+ include_breaks
585
+ ])
586
+ |> Shared.create_dataframe!()
587
+ end
588
+
589
+ # Window
590
+
591
+ @impl true
592
+ def window_max(series, window_size, weights, min_periods, center) do
593
+ window_function(:s_window_max, series, window_size, weights, min_periods, center)
594
+ end
595
+
596
+ @impl true
597
+ def window_mean(series, window_size, weights, min_periods, center) do
598
+ window_function(:s_window_mean, series, window_size, weights, min_periods, center)
599
+ end
600
+
601
+ @impl true
602
+ def window_median(series, window_size, weights, min_periods, center) do
603
+ window_function(:s_window_median, series, window_size, weights, min_periods, center)
604
+ end
605
+
606
+ @impl true
607
+ def window_min(series, window_size, weights, min_periods, center) do
608
+ window_function(:s_window_min, series, window_size, weights, min_periods, center)
609
+ end
610
+
611
+ @impl true
612
+ def window_sum(series, window_size, weights, min_periods, center) do
613
+ window_function(:s_window_sum, series, window_size, weights, min_periods, center)
614
+ end
615
+
616
+ @impl true
617
+ def window_standard_deviation(series, window_size, weights, min_periods, center) do
618
+ window_function(
619
+ :s_window_standard_deviation,
620
+ series,
621
+ window_size,
622
+ weights,
623
+ min_periods,
624
+ center
625
+ )
626
+ end
627
+
628
+ defp window_function(operation, series, window_size, weights, min_periods, center) do
629
+ series =
630
+ if List.wrap(weights) == [] do
631
+ series
632
+ else
633
+ cast(series, {:f, 64})
634
+ end
635
+
636
+ Shared.apply_series(series, operation, [window_size, weights, min_periods, center])
637
+ end
638
+
639
+ @impl true
640
+ def ewm_mean(series, alpha, adjust, min_periods, ignore_nils) do
641
+ Shared.apply_series(series, :s_ewm_mean, [alpha, adjust, min_periods, ignore_nils])
642
+ end
643
+
644
+ @impl true
645
+ def ewm_standard_deviation(series, alpha, adjust, bias, min_periods, ignore_nils) do
646
+ Shared.apply_series(
647
+ series,
648
+ :s_ewm_standard_deviation,
649
+ [alpha, adjust, bias, min_periods, ignore_nils]
650
+ )
651
+ end
652
+
653
+ @impl true
654
+ def ewm_variance(series, alpha, adjust, bias, min_periods, ignore_nils) do
655
+ Shared.apply_series(series, :s_ewm_variance, [alpha, adjust, bias, min_periods, ignore_nils])
656
+ end
657
+
658
+ # Missing values
659
+
660
+ @impl true
661
+ def fill_missing_with_strategy(series, strategy),
662
+ do: Shared.apply_series(series, :s_fill_missing_with_strategy, [Atom.to_string(strategy)])
663
+
664
+ @impl true
665
+ def fill_missing_with_value(series, value) when is_atom(value) and not is_boolean(value) do
666
+ Shared.apply_series(series, :s_fill_missing_with_atom, [Atom.to_string(value)])
667
+ end
668
+
669
+ def fill_missing_with_value(series, value) do
670
+ operation =
671
+ cond do
672
+ is_float(value) -> :s_fill_missing_with_float
673
+ is_integer(value) -> :s_fill_missing_with_int
674
+ is_binary(value) -> :s_fill_missing_with_bin
675
+ is_boolean(value) -> :s_fill_missing_with_boolean
676
+ is_struct(value, Date) -> :s_fill_missing_with_date
677
+ is_struct(value, NaiveDateTime) -> :s_fill_missing_with_datetime
678
+ is_struct(value, Decimal) -> :s_fill_missing_with_decimal
679
+ true -> raise "cannot fill missing with value: #{inspect(value)}"
680
+ end
681
+
682
+ Shared.apply_series(series, operation, [value])
683
+ end
684
+
685
+ @impl true
686
+ def is_nil(series), do: Shared.apply_series(series, :s_is_null)
687
+
688
+ @impl true
689
+ def is_not_nil(series), do: Shared.apply_series(series, :s_is_not_null)
690
+
691
+ @impl true
692
+ def transform(series, fun) do
693
+ series
694
+ |> Series.to_list()
695
+ |> Enum.map(fun)
696
+ |> Series.from_list(backend: Explorer.PolarsBackend)
697
+ end
698
+
699
+ @impl true
700
+ def inspect(series, opts) do
701
+ Explorer.Backend.Series.inspect(series, "Polars", Series.size(series), opts)
702
+ end
703
+
704
+ # Inversions
705
+
706
+ @impl true
707
+ def unary_not(%Series{} = series), do: Shared.apply_series(series, :s_not, [])
708
+
709
+ # Strings
710
+
711
+ @impl true
712
+ def contains(series, substring),
713
+ do: Shared.apply_series(series, :s_contains, [substring, true])
714
+
715
+ @impl true
716
+ def re_contains(series, pattern),
717
+ do: Shared.apply_series(series, :s_contains, [pattern, false])
718
+
719
+ @impl true
720
+ def upcase(series),
721
+ do: Shared.apply_series(series, :s_upcase)
722
+
723
+ @impl true
724
+ def downcase(series),
725
+ do: Shared.apply_series(series, :s_downcase)
726
+
727
+ @impl true
728
+ def replace(series, pattern, replacement),
729
+ do: Shared.apply_series(series, :s_replace, [pattern, replacement, true])
730
+
731
+ @impl true
732
+ def re_replace(series, pattern, replacement),
733
+ do: Shared.apply_series(series, :s_replace, [pattern, replacement, false])
734
+
735
+ @impl true
736
+ def strip(series, str),
737
+ do: Shared.apply_series(series, :s_strip, [str])
738
+
739
+ @impl true
740
+ def lstrip(series, str),
741
+ do: Shared.apply_series(series, :s_lstrip, [str])
742
+
743
+ @impl true
744
+ def rstrip(series, str),
745
+ do: Shared.apply_series(series, :s_rstrip, [str])
746
+
747
+ @impl true
748
+ def substring(series, offset, length),
749
+ do: Shared.apply_series(series, :s_substring, [offset, length])
750
+
751
+ @impl true
752
+ def split(series, by),
753
+ do: Shared.apply_series(series, :s_split, [by])
754
+
755
+ @impl true
756
+ def split_into(series, by, fields),
757
+ do: Shared.apply_series(series, :s_split_into, [by, fields])
758
+
759
+ # Float round
760
+ @impl true
761
+ def round(series, decimals),
762
+ do: Shared.apply_series(series, :s_round, [decimals])
763
+
764
+ @impl true
765
+ def floor(series),
766
+ do: Shared.apply_series(series, :s_floor)
767
+
768
+ @impl true
769
+ def ceil(series),
770
+ do: Shared.apply_series(series, :s_ceil)
771
+
772
+ # Date / DateTime
773
+ @impl true
774
+ def day_of_week(series),
775
+ do: Shared.apply_series(series, :s_day_of_week)
776
+
777
+ @impl true
778
+ def day_of_year(series),
779
+ do: Shared.apply_series(series, :s_day_of_year)
780
+
781
+ @impl true
782
+ def week_of_year(series),
783
+ do: Shared.apply_series(series, :s_week_of_year)
784
+
785
+ @impl true
786
+ def month(series),
787
+ do: Shared.apply_series(series, :s_month)
788
+
789
+ @impl true
790
+ def year(series),
791
+ do: Shared.apply_series(series, :s_year)
792
+
793
+ @impl true
794
+ def hour(series),
795
+ do: Shared.apply_series(series, :s_hour)
796
+
797
+ @impl true
798
+ def minute(series),
799
+ do: Shared.apply_series(series, :s_minute)
800
+
801
+ @impl true
802
+ def second(series),
803
+ do: Shared.apply_series(series, :s_second)
804
+
805
+ # Lists
806
+
807
+ @impl true
808
+ def join(series, separator),
809
+ do: Shared.apply_series(series, :s_join, [separator])
810
+
811
+ @impl true
812
+ def lengths(series),
813
+ do: Shared.apply_series(series, :s_lengths)
814
+
815
+ @impl true
816
+ def member?(%Series{dtype: {:list, inner_dtype}} = series, value),
817
+ do: Shared.apply_series(series, :s_member, [value, inner_dtype])
818
+
819
+ @impl true
820
+ def field(%Series{dtype: {:struct, _inner_dtype}} = series, name),
821
+ do: Shared.apply_series(series, :s_field, [name])
822
+
823
+ @impl true
824
+ def json_decode(series, dtype),
825
+ do: Shared.apply_series(series, :s_json_decode, [dtype])
826
+
827
+ @impl true
828
+ def json_path_match(series, json_path),
829
+ do: Shared.apply_series(series, :s_json_path_match, [json_path])
830
+
831
+ @impl true
832
+ def count_matches(series, substring) do
833
+ Shared.apply_series(series, :s_count_matches, [substring, true])
834
+ end
835
+
836
+ @impl true
837
+ def re_count_matches(series, pattern) do
838
+ Shared.apply_series(series, :s_count_matches, [pattern, false])
839
+ end
840
+
841
+ @impl true
842
+ def re_scan(series, pattern) do
843
+ Shared.apply_series(series, :s_re_scan, [pattern])
844
+ end
845
+
846
+ @impl true
847
+ def re_named_captures(series, pattern) do
848
+ Shared.apply_series(series, :s_re_named_captures, [pattern])
849
+ end
850
+
851
+ # Polars specific functions
852
+
853
+ def name(series), do: Shared.apply_series(series, :s_name)
854
+ def rename(series, name), do: Shared.apply_series(series, :s_rename, [name])
855
+
856
+ # Helpers
857
+
858
+ defp matching_size!(series, other) do
859
+ case size(series) do
860
+ 1 ->
861
+ series
862
+
863
+ i ->
864
+ case size(other) do
865
+ 1 ->
866
+ series
867
+
868
+ ^i ->
869
+ series
870
+
871
+ j ->
872
+ raise ArgumentError,
873
+ "series must either have the same size or one of them must have size of 1, got: #{i} and #{j}"
874
+ end
875
+ end
876
+ end
877
+ end
878
+
879
+ defimpl Inspect, for: Explorer.PolarsBackend.Series do
880
+ import Inspect.Algebra
881
+
882
+ def inspect(s, _opts) do
883
+ doc =
884
+ try do
885
+ Explorer.PolarsBackend.Native.s_as_str(s)
886
+ rescue
887
+ _ -> inspect(s.resource)
888
+ else
889
+ {:ok, str} -> str
890
+ {:error, _} -> inspect(s.resource)
891
+ end
892
+ |> String.split("\n")
893
+ |> Enum.intersperse(line())
894
+ |> then(&concat([line() | &1]))
895
+ |> nest(2)
896
+
897
+ concat(["#Explorer.PolarsBackend.Series<", doc, line(), ">"])
898
+ end
899
+ end
deps/explorer/lib/explorer/polars_backend/shared.ex ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.PolarsBackend.Shared do
2
+ # A collection of **private** helpers shared in Explorer.PolarsBackend.
3
+ @moduledoc false
4
+
5
+ alias Explorer.DataFrame, as: DataFrame
6
+ alias Explorer.PolarsBackend.DataFrame, as: PolarsDataFrame
7
+ alias Explorer.PolarsBackend.LazyFrame, as: PolarsLazyFrame
8
+ alias Explorer.PolarsBackend.Native
9
+ alias Explorer.PolarsBackend.Series, as: PolarsSeries
10
+ alias Explorer.Series, as: Series
11
+ import Kernel, except: [apply: 2]
12
+
13
+ @polars_df [PolarsDataFrame, PolarsLazyFrame]
14
+
15
+ def apply(fun, args \\ []) do
16
+ case Kernel.apply(Native, fun, args) do
17
+ {:ok, value} -> value
18
+ {:error, error} -> raise runtime_error(error)
19
+ end
20
+ end
21
+
22
+ # Applies to a series. Expects a series or a value back.
23
+ def apply_series(%Series{} = series, fun, args \\ []) do
24
+ case apply(Native, fun, [series.data | args]) do
25
+ {:ok, %PolarsSeries{} = new_series} -> create_series(new_series)
26
+ {:ok, value} -> value
27
+ {:error, error} -> raise runtime_error(error)
28
+ end
29
+ end
30
+
31
+ # Applies to a dataframe. Expects a series or a value back.
32
+ def apply_dataframe(%DataFrame{} = df, fun, args \\ []) do
33
+ case apply(Native, fun, [df.data | args]) do
34
+ {:ok, %PolarsSeries{} = new_series} -> create_series(new_series)
35
+ {:ok, value} -> value
36
+ {:error, error} -> raise runtime_error(error)
37
+ end
38
+ end
39
+
40
+ @check_frames Application.compile_env(:explorer, :check_polars_frames, false)
41
+
42
+ # Applies to a dataframe. Expects a dataframe back.
43
+ def apply_dataframe(%DataFrame{} = df, %DataFrame{} = out_df, fun, args) do
44
+ case apply(Native, fun, [df.data | args]) do
45
+ {:ok, %module{} = new_df} when module in @polars_df ->
46
+ if @check_frames do
47
+ # We need to collect here, because the lazy frame may not have
48
+ # the full picture of the result yet.
49
+ check_df =
50
+ if match?(%PolarsLazyFrame{}, new_df) do
51
+ case Native.lf_compute(new_df) do
52
+ {:ok, new_df} -> create_dataframe!(new_df)
53
+ {:error, error} -> raise runtime_error(error)
54
+ end
55
+ else
56
+ create_dataframe!(new_df)
57
+ end
58
+
59
+ if Enum.sort(out_df.names) != Enum.sort(check_df.names) or
60
+ out_df.dtypes != check_df.dtypes do
61
+ raise """
62
+ DataFrame mismatch.
63
+
64
+ expected:
65
+
66
+ names: #{inspect(out_df.names)}
67
+ dtypes: #{inspect(out_df.dtypes)}
68
+
69
+ got:
70
+
71
+ names: #{inspect(check_df.names)}
72
+ dtypes: #{inspect(check_df.dtypes)}
73
+ """
74
+ end
75
+ end
76
+
77
+ %{out_df | data: new_df}
78
+
79
+ {:error, error} ->
80
+ raise runtime_error(error)
81
+ end
82
+ end
83
+
84
+ def create_series(%PolarsSeries{} = polars_series) do
85
+ dtype =
86
+ case Native.s_dtype(polars_series) do
87
+ {:ok, dtype} ->
88
+ dtype
89
+
90
+ {:error, reason} ->
91
+ raise ArgumentError, reason
92
+ end
93
+
94
+ Explorer.Backend.Series.new(polars_series, dtype)
95
+ end
96
+
97
+ def create_dataframe(polars_df) do
98
+ with {:ok, names} <- df_names(polars_df), {:ok, dtypes} <- df_dtypes(polars_df) do
99
+ {:ok, Explorer.Backend.DataFrame.new(polars_df, names, dtypes)}
100
+ else
101
+ {:error, error} -> {:error, runtime_error(error)}
102
+ end
103
+ end
104
+
105
+ def create_dataframe!(polars_df) do
106
+ case create_dataframe(polars_df) do
107
+ {:ok, df} -> df
108
+ {:error, error} -> raise error
109
+ end
110
+ end
111
+
112
+ defp df_names(%PolarsDataFrame{} = polars_df) do
113
+ Native.df_names(polars_df)
114
+ end
115
+
116
+ defp df_names(%PolarsLazyFrame{} = polars_df) do
117
+ Native.lf_names(polars_df)
118
+ end
119
+
120
+ defp df_dtypes(%PolarsDataFrame{} = polars_df) do
121
+ Native.df_dtypes(polars_df)
122
+ end
123
+
124
+ defp df_dtypes(%PolarsLazyFrame{} = polars_df) do
125
+ Native.lf_dtypes(polars_df)
126
+ end
127
+
128
+ def from_list(list, dtype), do: from_list(list, dtype, "")
129
+
130
+ def from_list(list, {:list, inner_dtype} = dtype, name) do
131
+ series =
132
+ Enum.map(list, fn
133
+ inner_list when is_list(inner_list) -> from_list(inner_list, inner_dtype, name)
134
+ _ -> nil
135
+ end)
136
+
137
+ Native.s_from_list_of_series(name, series, dtype)
138
+ end
139
+
140
+ def from_list(list, {:struct, fields} = dtype, name) when is_list(list) do
141
+ columns = Map.new(fields, fn {k, _v} -> {k, []} end)
142
+
143
+ columns =
144
+ Enum.reduce(list, columns, fn
145
+ nil, columns ->
146
+ Enum.reduce(fields, columns, fn {field, _}, columns ->
147
+ Map.update!(columns, field, &[nil | &1])
148
+ end)
149
+
150
+ row, columns ->
151
+ Enum.reduce(row, columns, fn {field, value}, columns ->
152
+ Map.update!(columns, to_string(field), &[value | &1])
153
+ end)
154
+ end)
155
+
156
+ series =
157
+ for {field, inner_dtype} <- fields do
158
+ columns
159
+ |> Map.fetch!(field)
160
+ |> Enum.reverse()
161
+ |> from_list(inner_dtype, field)
162
+ end
163
+
164
+ Native.s_from_list_of_series_as_structs(name, series, dtype)
165
+ end
166
+
167
+ def from_list(list, dtype, name) when is_list(list) do
168
+ case dtype do
169
+ # Signed integers
170
+ {:s, 8} -> Native.s_from_list_s8(name, list)
171
+ {:s, 16} -> Native.s_from_list_s16(name, list)
172
+ {:s, 32} -> Native.s_from_list_s32(name, list)
173
+ {:s, 64} -> Native.s_from_list_s64(name, list)
174
+ # Unsigned integers
175
+ {:u, 8} -> Native.s_from_list_u8(name, list)
176
+ {:u, 16} -> Native.s_from_list_u16(name, list)
177
+ {:u, 32} -> Native.s_from_list_u32(name, list)
178
+ {:u, 64} -> Native.s_from_list_u64(name, list)
179
+ # Floats
180
+ {:f, 32} -> Native.s_from_list_f32(name, list)
181
+ {:f, 64} -> Native.s_from_list_f64(name, list)
182
+ :boolean -> Native.s_from_list_bool(name, list)
183
+ :string -> Native.s_from_list_str(name, list)
184
+ :category -> Native.s_from_list_categories(name, list)
185
+ :date -> apply(:s_from_list_date, [name, list])
186
+ :time -> apply(:s_from_list_time, [name, list])
187
+ {:naive_datetime, precision} -> apply(:s_from_list_naive_datetime, [name, list, precision])
188
+ {:datetime, precision, tz} -> apply(:s_from_list_datetime, [name, list, precision, tz])
189
+ {:duration, precision} -> apply(:s_from_list_duration, [name, list, precision])
190
+ :binary -> Native.s_from_list_binary(name, list)
191
+ :null -> Native.s_from_list_null(name, length(list))
192
+ {:decimal, precision, scale} -> apply(:s_from_list_decimal, [name, list, precision, scale])
193
+ end
194
+ end
195
+
196
+ def from_binary(binary, dtype, name \\ "") when is_binary(binary) do
197
+ case dtype do
198
+ :boolean ->
199
+ Native.s_from_binary_u8(name, binary) |> Native.s_cast(dtype) |> ok()
200
+
201
+ :date ->
202
+ Native.s_from_binary_s32(name, binary) |> Native.s_cast(dtype) |> ok()
203
+
204
+ :time ->
205
+ Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok()
206
+
207
+ {:naive_datetime, :millisecond} ->
208
+ Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok()
209
+
210
+ {:naive_datetime, :microsecond} ->
211
+ Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok()
212
+
213
+ {:naive_datetime, :nanosecond} ->
214
+ Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok()
215
+
216
+ {:duration, :millisecond} ->
217
+ Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok()
218
+
219
+ {:duration, :microsecond} ->
220
+ Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok()
221
+
222
+ {:duration, :nanosecond} ->
223
+ Native.s_from_binary_s64(name, binary) |> Native.s_cast(dtype) |> ok()
224
+
225
+ {:s, 8} ->
226
+ Native.s_from_binary_s8(name, binary)
227
+
228
+ {:s, 16} ->
229
+ Native.s_from_binary_s16(name, binary)
230
+
231
+ {:s, 32} ->
232
+ Native.s_from_binary_s32(name, binary)
233
+
234
+ {:s, 64} ->
235
+ Native.s_from_binary_s64(name, binary)
236
+
237
+ {:u, 8} ->
238
+ Native.s_from_binary_u8(name, binary)
239
+
240
+ {:u, 16} ->
241
+ Native.s_from_binary_u16(name, binary)
242
+
243
+ {:u, 32} ->
244
+ Native.s_from_binary_u32(name, binary)
245
+
246
+ {:u, 64} ->
247
+ Native.s_from_binary_u64(name, binary)
248
+
249
+ {:f, 32} ->
250
+ Native.s_from_binary_f32(name, binary)
251
+
252
+ {:f, 64} ->
253
+ Native.s_from_binary_f64(name, binary)
254
+ end
255
+ end
256
+
257
+ defp ok({:ok, value}), do: value
258
+
259
+ defp runtime_error(error) when is_binary(error), do: RuntimeError.exception(error)
260
+
261
+ def parquet_compression(nil, _), do: :uncompressed
262
+
263
+ def parquet_compression(algorithm, level) when algorithm in ~w(gzip brotli zstd)a,
264
+ do: {algorithm, level}
265
+
266
+ def parquet_compression(algorithm, _) when algorithm in ~w(snappy lz4raw)a, do: algorithm
267
+
268
+ @doc """
269
+ Builds and returns a path for a new file.
270
+
271
+ It saves in a directory called "elixir-explorer-datasets" inside
272
+ the `System.tmp_dir()`.
273
+ """
274
+ def build_path_for_entry(%FSS.S3.Entry{} = entry) do
275
+ bucket = entry.config.bucket || "default-explorer-bucket"
276
+
277
+ hash =
278
+ :crypto.hash(:sha256, entry.config.endpoint <> "/" <> bucket <> "/" <> entry.key)
279
+ |> Base.url_encode64(padding: false)
280
+
281
+ id = "s3-file-#{hash}"
282
+
283
+ build_tmp_path(id)
284
+ end
285
+
286
+ def build_path_for_entry(%FSS.HTTP.Entry{} = entry) do
287
+ hash = :crypto.hash(:sha256, entry.url) |> Base.url_encode64(padding: false)
288
+
289
+ id = "http-file-#{hash}"
290
+
291
+ build_tmp_path(id)
292
+ end
293
+
294
+ defp build_tmp_path(id) do
295
+ base_dir = Path.join([System.tmp_dir!(), "elixir-explorer-datasets"])
296
+ File.mkdir_p!(base_dir)
297
+
298
+ Path.join([base_dir, id])
299
+ end
300
+ end
deps/explorer/lib/explorer/query.ex ADDED
@@ -0,0 +1,826 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Kernel, except: [if: 2, unless: 2]
2
+
3
+ defmodule Explorer.Query do
4
+ @moduledoc ~S"""
5
+ High-level query for Explorer.
6
+
7
+ > #### Explorer.DataFrame vs DF {: .tip}
8
+ >
9
+ > All examples below assume you have defined aliased
10
+ > `Explorer.DataFrame` to `DF` as shown below:
11
+ >
12
+ > require Explorer.DataFrame, as: DF
13
+ >
14
+
15
+ Queries convert regular Elixir code which compile to efficient
16
+ dataframes operations. Inside a query, only the limited set of
17
+ Series operations are available and identifiers, such as `strs`
18
+ and `nums`, represent dataframe column names:
19
+
20
+ iex> df = DF.new(strs: ["a", "b", "c"], nums: [1, 2, 3])
21
+ iex> DF.filter(df, nums > 2)
22
+ #Explorer.DataFrame<
23
+ Polars[1 x 2]
24
+ strs string ["c"]
25
+ nums s64 [3]
26
+ >
27
+
28
+ If a column has unusual format, you can either rename it before-hand,
29
+ or use `col/1` inside queries:
30
+
31
+ iex> df = DF.new("unusual nums": [1, 2, 3])
32
+ iex> DF.filter(df, col("unusual nums") > 2)
33
+ #Explorer.DataFrame<
34
+ Polars[1 x 1]
35
+ unusual nums s64 [3]
36
+ >
37
+
38
+ All operations from `Explorer.Series` are imported inside queries.
39
+ This module also provides operators to use in queries, which are
40
+ also imported into queries.
41
+
42
+ ## Supported operations
43
+
44
+ Queries are supported in the following operations:
45
+
46
+ * `Explorer.DataFrame.sort_by/2`
47
+ * `Explorer.DataFrame.filter/2`
48
+ * `Explorer.DataFrame.mutate/2`
49
+ * `Explorer.DataFrame.summarise/2`
50
+
51
+ ## Interpolation
52
+
53
+ If you want to access variables defined outside of the query
54
+ or get access to all Elixir constructs, you must use `^`:
55
+
56
+ iex> min = 2
57
+ iex> df = DF.new(strs: ["a", "b", "c"], nums: [1, 2, 3])
58
+ iex> DF.filter(df, nums > ^min)
59
+ #Explorer.DataFrame<
60
+ Polars[1 x 2]
61
+ strs string ["c"]
62
+ nums s64 [3]
63
+ >
64
+
65
+ iex> min = 2
66
+ iex> df = DF.new(strs: ["a", "b", "c"], nums: [1, 2, 3])
67
+ iex> DF.filter(df, nums < ^if(min > 0, do: 10, else: -10))
68
+ #Explorer.DataFrame<
69
+ Polars[3 x 2]
70
+ strs string ["a", "b", "c"]
71
+ nums s64 [1, 2, 3]
72
+ >
73
+
74
+ `^` can be used with `col` to access columns dynamically:
75
+
76
+ iex> df = DF.new("unusual nums": [1, 2, 3])
77
+ iex> name = "unusual nums"
78
+ iex> DF.filter(df, col(^name) > 2)
79
+ #Explorer.DataFrame<
80
+ Polars[1 x 1]
81
+ unusual nums s64 [3]
82
+ >
83
+
84
+ ## Conditionals
85
+
86
+ Queries support both `if/2` and `unless/2` operations inside queries.
87
+
88
+ `cond/1` can be used to write multi-clause conditions:
89
+
90
+ iex> df = DF.new(a: [10, 4, 6])
91
+ iex> DF.mutate(df,
92
+ ...> b:
93
+ ...> cond do
94
+ ...> a > 9 -> "Exceptional"
95
+ ...> a > 5 -> "Passed"
96
+ ...> true -> "Failed"
97
+ ...> end
98
+ ...> )
99
+ #Explorer.DataFrame<
100
+ Polars[3 x 2]
101
+ a s64 [10, 4, 6]
102
+ b string ["Exceptional", "Failed", "Passed"]
103
+ >
104
+
105
+ ## Across and comprehensions
106
+
107
+ `Explorer.Query` leverages the power behind Elixir for-comprehensions
108
+ to provide a powerful syntax for traversing several columns in a dataframe
109
+ at once. For example, imagine you want to standardize the data on the
110
+ iris dataset, you could write this:
111
+
112
+ iex> iris = Explorer.Datasets.iris()
113
+ iex> DF.mutate(iris,
114
+ ...> sepal_width: (sepal_width - mean(sepal_width)) / variance(sepal_width),
115
+ ...> sepal_length: (sepal_length - mean(sepal_length)) / variance(sepal_length),
116
+ ...> petal_length: (petal_length - mean(petal_length)) / variance(petal_length),
117
+ ...> petal_width: (petal_width - mean(petal_width)) / variance(petal_width)
118
+ ...> )
119
+ #Explorer.DataFrame<
120
+ Polars[150 x 5]
121
+ sepal_length f64 [-1.0840606189132322, -1.3757361217598405, -1.66741162460645, -1.8132493760297554, -1.2298983703365363, ...]
122
+ sepal_width f64 [2.3722896125315045, -0.28722789030650403, 0.7765791108287005, 0.2446756102610982, 2.9041931130991068, ...]
123
+ petal_length f64 [-0.7576391687443839, -0.7576391687443839, -0.7897606710936369, -0.7255176663951307, -0.7576391687443839, ...]
124
+ petal_width f64 [-1.7147014356654708, -1.7147014356654708, -1.7147014356654708, -1.7147014356654708, -1.7147014356654708, ...]
125
+ species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...]
126
+ >
127
+
128
+ While the code above does its job, it is quite repetitive. With across and for-comprehensions,
129
+ we could instead write:
130
+
131
+ iex> iris = Explorer.Datasets.iris()
132
+ iex> DF.mutate(iris,
133
+ ...> for col <- across(["sepal_width", "sepal_length", "petal_length", "petal_width"]) do
134
+ ...> {col.name, (col - mean(col)) / variance(col)}
135
+ ...> end
136
+ ...> )
137
+ #Explorer.DataFrame<
138
+ Polars[150 x 5]
139
+ sepal_length f64 [-1.0840606189132322, -1.3757361217598405, -1.66741162460645, -1.8132493760297554, -1.2298983703365363, ...]
140
+ sepal_width f64 [2.3722896125315045, -0.28722789030650403, 0.7765791108287005, 0.2446756102610982, 2.9041931130991068, ...]
141
+ petal_length f64 [-0.7576391687443839, -0.7576391687443839, -0.7897606710936369, -0.7255176663951307, -0.7576391687443839, ...]
142
+ petal_width f64 [-1.7147014356654708, -1.7147014356654708, -1.7147014356654708, -1.7147014356654708, -1.7147014356654708, ...]
143
+ species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...]
144
+ >
145
+
146
+ Which achieves the same result in a more concise and maintainable way.
147
+ `across/1` may receive any of the following input as arguments:
148
+
149
+ * a list of columns indexes or names as atoms and strings
150
+
151
+ * a range
152
+
153
+ * a regex that keeps only the names matching the regex
154
+
155
+ For example, since we know the width and length columns are the first four,
156
+ we could also have written (remember ranges in Elixir are inclusive):
157
+
158
+ DF.mutate(iris,
159
+ for col <- across(0..3) do
160
+ {col.name, (col - mean(col)) / variance(col)}
161
+ end
162
+ )
163
+
164
+ Or using a regex:
165
+
166
+ DF.mutate(iris,
167
+ for col <- across(~r/(sepal|petal)_(length|width)/) do
168
+ {col.name, (col - mean(col)) / variance(col)}
169
+ end
170
+ )
171
+
172
+ For those new to Elixir, for-comprehensions have the following format:
173
+
174
+ for PATTERN <- GENERATOR, FILTER do
175
+ EXPR
176
+ end
177
+
178
+ A comprehension filter is a mechanism that allows us to keep only columns
179
+ based on additional properties, such as its `dtype`. A for-comprehension can
180
+ have multiple generators and filters. For instance, if you want to apply
181
+ standardization to all float columns, we can use `across/0` to access all
182
+ columns and then use a filter to keep only the float ones:
183
+
184
+ iex> iris = Explorer.Datasets.iris()
185
+ iex> DF.mutate(iris,
186
+ ...> for col <- across(), col.dtype == {:f, 64} do
187
+ ...> {col.name, (col - mean(col)) / variance(col)}
188
+ ...> end
189
+ ...> )
190
+ #Explorer.DataFrame<
191
+ Polars[150 x 5]
192
+ sepal_length f64 [-1.0840606189132322, -1.3757361217598405, -1.66741162460645, -1.8132493760297554, -1.2298983703365363, ...]
193
+ sepal_width f64 [2.3722896125315045, -0.28722789030650403, 0.7765791108287005, 0.2446756102610982, 2.9041931130991068, ...]
194
+ petal_length f64 [-0.7576391687443839, -0.7576391687443839, -0.7897606710936369, -0.7255176663951307, -0.7576391687443839, ...]
195
+ petal_width f64 [-1.7147014356654708, -1.7147014356654708, -1.7147014356654708, -1.7147014356654708, -1.7147014356654708, ...]
196
+ species string ["Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", "Iris-setosa", ...]
197
+ >
198
+
199
+ For-comprehensions works with all dataframe verbs. As we have seen
200
+ above, for mutations we must return tuples as pair with the mutation
201
+ name and its value. `summarise` works similarly. Note in both cases
202
+ the name could also be generated dynamically. For example, to compute
203
+ the mean per species, you could write:
204
+
205
+ iex> Explorer.Datasets.iris()
206
+ ...> |> DF.group_by("species")
207
+ ...> |> DF.summarise(
208
+ ...> for col <- across(), col.dtype == {:f, 64} do
209
+ ...> {"#{col.name}_mean", round(mean(col), 3)}
210
+ ...> end
211
+ ...> )
212
+ #Explorer.DataFrame<
213
+ Polars[3 x 5]
214
+ species string ["Iris-setosa", "Iris-versicolor", "Iris-virginica"]
215
+ sepal_length_mean f64 [5.006, 5.936, 6.588]
216
+ sepal_width_mean f64 [3.418, 2.77, 2.974]
217
+ petal_length_mean f64 [1.464, 4.26, 5.552]
218
+ petal_width_mean f64 [0.244, 1.326, 2.026]
219
+ >
220
+
221
+ `sort_by` expects a list of columns to sort by, while for-comprehensions
222
+ in `filter` generate a list of conditions, which are joined using `and`.
223
+ For example, to filter all entries have both sepal and petal length above
224
+ average, using a filter on the column name, one could write:
225
+
226
+ iex> iris = Explorer.Datasets.iris()
227
+ iex> DF.filter(iris,
228
+ ...> for col <- across(), String.ends_with?(col.name, "_length") do
229
+ ...> col > mean(col)
230
+ ...> end
231
+ ...> )
232
+ #Explorer.DataFrame<
233
+ Polars[70 x 5]
234
+ sepal_length f64 [7.0, 6.4, 6.9, 6.5, 6.3, ...]
235
+ sepal_width f64 [3.2, 3.2, 3.1, 2.8, 3.3, ...]
236
+ petal_length f64 [4.7, 4.5, 4.9, 4.6, 4.7, ...]
237
+ petal_width f64 [1.4, 1.5, 1.5, 1.5, 1.6, ...]
238
+ species string ["Iris-versicolor", "Iris-versicolor", "Iris-versicolor", "Iris-versicolor", "Iris-versicolor", ...]
239
+ >
240
+
241
+ > #### Do not mix comprehension and queries {: .warning}
242
+ >
243
+ > The filter inside a for-comprehension works at the meta level:
244
+ > it can only filter columns based on their names and dtypes, but
245
+ > not on their values. For example, this code does not make any
246
+ > sense and it will fail to compile:
247
+ >
248
+ > |> DF.filter(
249
+ > for col <- across(), col > mean(col) do
250
+ > col
251
+ > end
252
+ > end)
253
+ >
254
+ > Another way to think about it, the comprehensions traverse on the
255
+ > columns themselves, the contents inside the comprehension do-block
256
+ > traverse on the values inside the columns.
257
+
258
+ ## Implementation details
259
+
260
+ Queries simply become lazy dataframe operations at runtime.
261
+ For example, the following query
262
+
263
+ Explorer.DataFrame.filter(df, nums > 2)
264
+
265
+ is equivalent to
266
+
267
+ Explorer.DataFrame.filter_with(df, fn df -> Explorer.Series.greater(df["nums"], 2) end)
268
+
269
+ This means that, whenever you want to generate queries programatically,
270
+ you can fallback to the regular `_with` APIs.
271
+
272
+ In the `_with` APIs, the callbacks receive an `Explorer.DataFrame` as an
273
+ input. That dataframe is backed by the special `Explorer.Backend.QueryFrame`
274
+ backend.
275
+
276
+ Explorer.DataFrame.filter_with(df, fn query_backed_frame ->
277
+ IO.inspect(query_backed_frame)
278
+ ...
279
+ end)
280
+ # #Explorer.DataFrame<
281
+ # QueryFrame[??? x 1]
282
+ # ...
283
+ # >
284
+
285
+ A "query-backed" dataframe cannot be manipulated. You may only access its
286
+ series. And when you do, you get back "lazy-backed" versions of those series:
287
+
288
+ Explorer.DataFrame.filter_with(df, fn query_backed_frame ->
289
+ IO.inspect(query_backed_frame["a"])
290
+ ...
291
+ end)
292
+ # #Explorer.Series<
293
+ # LazySeries[???]
294
+ # s64 (column("a"))
295
+ # >
296
+
297
+ "Lazy-backed" series are backed by the special `Explorer.Backend.LazySeries`
298
+ backend. All `Explorer.Series` functions work on lazy-backed series too. So
299
+ you can write your `_with` callbacks without ever referencing the fact that
300
+ the backend is the lazy one.
301
+ """
302
+
303
+ kernel_all = Kernel.__info__(:functions) ++ Kernel.__info__(:macros)
304
+
305
+ kernel_only = [
306
+ @: 1,
307
+ |>: 2,
308
+ dbg: 0,
309
+ dbg: 1,
310
+ dbg: 2,
311
+ sigil_c: 2,
312
+ sigil_C: 2,
313
+ sigil_D: 2,
314
+ sigil_N: 2,
315
+ sigil_s: 2,
316
+ sigil_S: 2,
317
+ sigil_w: 2,
318
+ sigil_W: 2,
319
+ tap: 2,
320
+ then: 2
321
+ ]
322
+
323
+ @kernel_only kernel_only -- kernel_only -- kernel_all
324
+
325
+ @doc """
326
+ Returns a "query-backed" `Explorer.DataFrame` for use in queries.
327
+
328
+ This function is mostly an implementation detail for the `*_with` callbacks.
329
+ See the "Implementation details" section of the `@moduledoc` for details.
330
+
331
+ There are some limited instances where it's more convenient to work with
332
+ query-backed `DataFrame`s. For example, if you want to re-use a lazy series,
333
+ you can do so like this:
334
+
335
+ alias Explorer.{DataFrame, Query, Series}
336
+
337
+ df = DataFrame.new(a: [1, 2, 3])
338
+ qf = Query.new(df)
339
+
340
+ gt_1 = Series.greater(qf["a"], 1)
341
+ lt_3 = Series.less(qf["a"], 3)
342
+
343
+ df
344
+ |> DataFrame.filter_with(gt_1)
345
+ |> DataFrame.to_columns(atom_keys: true)
346
+ #=> %{a: [2, 3]}
347
+
348
+ df
349
+ |> DataFrame.filter_with(lt_3)
350
+ |> DataFrame.to_columns(atom_keys: true)
351
+ #=> %{a: [1, 2]}
352
+
353
+ df
354
+ |> DataFrame.filter_with(Series.and(gt_1, lt_3))
355
+ |> DataFrame.to_columns(atom_keys: true)
356
+ #=> %{a: [2]}
357
+
358
+ However, if you think you need `new/1`, first check that you can't accomplish
359
+ the same thing with `across/0` inside a macro. The latter is usually easier to
360
+ work with.
361
+ """
362
+ def new(%Explorer.DataFrame{} = df) do
363
+ Explorer.Backend.QueryFrame.new(df)
364
+ end
365
+
366
+ @doc """
367
+ Builds an anonymous function from a query.
368
+
369
+ This is the entry point used by `Explorer.DataFrame.filter/2`
370
+ and friends to convert queries into anonymous functions.
371
+ See the moduledoc for more information.
372
+ """
373
+ defmacro query(expression) do
374
+ df = df_var()
375
+
376
+ quote do
377
+ fn unquote(df) ->
378
+ unquote(traverse(expression, df))
379
+ end
380
+ end
381
+ end
382
+
383
+ defp traverse({:for, meta, [_ | _] = args}, df) do
384
+ {args, [opts]} = Enum.split(args, Kernel.-(1))
385
+
386
+ block =
387
+ Keyword.get(opts, :do) || raise ArgumentError, "expected do-block in for-comprehension"
388
+
389
+ {args, known_vars} =
390
+ Enum.map_reduce(args, %{}, fn
391
+ {:<-, meta, [pattern, generator]}, acc ->
392
+ generator = traverse_for(generator, df, acc)
393
+ {{:<-, meta, [pattern, generator]}, collect_pattern_vars(pattern, acc)}
394
+
395
+ other, acc ->
396
+ {traverse_for(other, df, acc), acc}
397
+ end)
398
+
399
+ {query, vars} =
400
+ traverse(block, [], %{df: df, known_vars: known_vars, collect_pins_and_vars: true})
401
+
402
+ block =
403
+ quote do
404
+ unquote_splicing(Enum.reverse(vars))
405
+ import Kernel, only: unquote(@kernel_only)
406
+ import Explorer.Query, except: [query: 1]
407
+ import Explorer.Series
408
+ unquote(query)
409
+ end
410
+
411
+ for = {:for, meta, args ++ [Keyword.put(opts, :do, block)]}
412
+
413
+ quote do
414
+ import Explorer.Query, only: [across: 0, across: 1]
415
+ unquote(for)
416
+ end
417
+ end
418
+
419
+ defp traverse(expression, df) do
420
+ {query, vars} =
421
+ traverse(expression, [], %{df: df, known_vars: %{}, collect_pins_and_vars: true})
422
+
423
+ quote do
424
+ unquote_splicing(Enum.reverse(vars))
425
+ import Kernel, only: unquote(@kernel_only)
426
+ import Explorer.Query, except: [query: 1]
427
+ import Explorer.Series, except: [and: 2, or: 2, not: 1]
428
+ unquote(query)
429
+ end
430
+ end
431
+
432
+ defp traverse({:^, meta, [expr]}, vars, state) do
433
+ cond do
434
+ state.collect_pins_and_vars ->
435
+ var = Macro.unique_var(:pin, __MODULE__)
436
+ {var, [{:=, meta, [var, expr]} | vars]}
437
+
438
+ true ->
439
+ {expr, vars}
440
+ end
441
+ end
442
+
443
+ defp traverse({:for, _meta, [_ | _]}, _vars, _state) do
444
+ raise ArgumentError, "for-comprehensions are only supported at the root of queries"
445
+ end
446
+
447
+ defp traverse({:"::", meta, [left, right]}, vars, state) do
448
+ {left, vars} = traverse(left, vars, state)
449
+ {{:"::", meta, [left, right]}, vars}
450
+ end
451
+
452
+ defp traverse({:cond, _meta, [[do: clauses]]}, vars, state) do
453
+ {clauses, vars} =
454
+ Enum.map_reduce(clauses, vars, fn {:->, _, [[on_condition], on_true]}, vars ->
455
+ {condition, vars} = traverse(on_condition, vars, state)
456
+ {truthy, vars} = traverse(on_true, vars, state)
457
+ {{condition, truthy}, vars}
458
+ end)
459
+
460
+ body =
461
+ quote do
462
+ Explorer.Query.__cond__(unquote(Enum.reverse(clauses)))
463
+ end
464
+
465
+ {body, vars}
466
+ end
467
+
468
+ defp traverse({var, meta, ctx} = expr, vars, state)
469
+ when Kernel.and(is_atom(var), is_atom(ctx)) do
470
+ cond do
471
+ Map.has_key?(state.known_vars, {var, ctx}) ->
472
+ {expr, vars}
473
+
474
+ state.collect_pins_and_vars ->
475
+ {{{:., meta, [Explorer.DataFrame, :pull]}, meta, [state.df, var]}, vars}
476
+
477
+ true ->
478
+ raise ArgumentError, "undefined variable \"#{Macro.to_string(expr)}\""
479
+ end
480
+ end
481
+
482
+ defp traverse({left, meta, right}, vars, state) do
483
+ cond do
484
+ Kernel.and(
485
+ Kernel.and(is_atom(left), is_list(right)),
486
+ special_form_defines_var?(left, right)
487
+ ) ->
488
+ raise ArgumentError,
489
+ "#{left}/#{length(right)} is not currently supported in Explorer.Query"
490
+
491
+ true ->
492
+ {left, vars} = traverse(left, vars, state)
493
+ {right, vars} = traverse(right, vars, state)
494
+ {{left, meta, right}, vars}
495
+ end
496
+ end
497
+
498
+ defp traverse({left, right}, vars, state) do
499
+ {left, vars} = traverse(left, vars, state)
500
+ {right, vars} = traverse(right, vars, state)
501
+ {{left, right}, vars}
502
+ end
503
+
504
+ defp traverse(list, vars, state) when is_list(list) do
505
+ Enum.map_reduce(list, vars, &traverse(&1, &2, state))
506
+ end
507
+
508
+ defp traverse(other, vars, _state), do: {other, vars}
509
+
510
+ defp special_form_defines_var?(:=, [_, _]), do: true
511
+ defp special_form_defines_var?(:case, [_, _]), do: true
512
+ defp special_form_defines_var?(:receive, [_]), do: true
513
+ defp special_form_defines_var?(:try, [_]), do: true
514
+ defp special_form_defines_var?(:with, [_ | _]), do: true
515
+ defp special_form_defines_var?(_, _), do: false
516
+
517
+ defp traverse_for(expr, df, known_vars) do
518
+ {expr, []} =
519
+ traverse(expr, [], %{df: df, known_vars: known_vars, collect_pins_and_vars: false})
520
+
521
+ expr
522
+ end
523
+
524
+ defp collect_pattern_vars({:when, _, [pattern, _]}, known_vars) do
525
+ collect_pattern_vars(pattern, known_vars)
526
+ end
527
+
528
+ defp collect_pattern_vars(expr, known_vars) do
529
+ expr
530
+ |> Macro.prewalk(known_vars, fn
531
+ {:"::", _, [left, _right]}, acc ->
532
+ {left, acc}
533
+
534
+ {skip, _, [_ | _]}, acc when skip in [:^, :@, :quote] ->
535
+ {:ok, acc}
536
+
537
+ {:_, _, context}, acc when is_atom(context) ->
538
+ {:ok, acc}
539
+
540
+ {name, _meta, context}, acc when Kernel.and(is_atom(name), is_atom(context)) ->
541
+ {:ok, Map.put(acc, {name, context}, true)}
542
+
543
+ node, acc ->
544
+ {node, acc}
545
+ end)
546
+ |> elem(1)
547
+ end
548
+
549
+ # and and or are sent as is to queries
550
+ binary_delegates = [
551
+ ==: :equal,
552
+ !=: :not_equal,
553
+ >: :greater,
554
+ >=: :greater_equal,
555
+ <: :less,
556
+ <=: :less_equal,
557
+ +: :add,
558
+ -: :subtract,
559
+ *: :multiply,
560
+ /: :divide,
561
+ **: :pow
562
+ ]
563
+
564
+ for {operator, delegate} <- binary_delegates do
565
+ @doc """
566
+ Delegate to `Explorer.Series.#{delegate}/2`.
567
+ """
568
+ def unquote(operator)(left, right), do: Explorer.Series.unquote(delegate)(left, right)
569
+ end
570
+
571
+ @doc """
572
+ Unary minus operator.
573
+
574
+ Works with numbers and series.
575
+ """
576
+ def -number when is_number(number), do: Kernel.-(number)
577
+
578
+ def -series when is_struct(series, Explorer.Series),
579
+ do: Explorer.Series.multiply(series, Kernel.-(1))
580
+
581
+ @doc """
582
+ Unary plus operator.
583
+
584
+ Works with numbers and series.
585
+ """
586
+ def +number when is_number(number), do: number
587
+ def +series when is_struct(series, Explorer.Series), do: series
588
+
589
+ @doc """
590
+ Binary and operator.
591
+
592
+ Works with boolean and series.
593
+ """
594
+ def left and right when Kernel.and(is_boolean(left), is_boolean(right)),
595
+ do: Kernel.and(left, right)
596
+
597
+ def left and right, do: Explorer.Series.and(boolean!(left), boolean!(right))
598
+
599
+ @doc """
600
+ Binary or operator.
601
+
602
+ Works with boolean and series.
603
+ """
604
+ def left or right when Kernel.or(is_boolean(left), is_boolean(right)),
605
+ do: Kernel.or(left, right)
606
+
607
+ def left or right, do: Explorer.Series.or(boolean!(left), boolean!(right))
608
+
609
+ @doc """
610
+ Unary not operator.
611
+
612
+ Works with boolean and series.
613
+ """
614
+ def not value when is_boolean(value), do: Kernel.not(value)
615
+
616
+ def not value, do: Explorer.Series.not(boolean!(value))
617
+
618
+ defp boolean!(%Explorer.Series{dtype: :boolean} = series), do: series
619
+ defp boolean!(value) when is_boolean(value), do: Explorer.Series.from_list([value])
620
+
621
+ defp boolean!(other) do
622
+ raise ArgumentError,
623
+ "boolean operators require either a boolean (true/false) or a boolean series, got: #{inspect(other)}"
624
+ end
625
+
626
+ @doc """
627
+ String concatenation operator.
628
+
629
+ Works with strings and series of strings.
630
+
631
+ ## Examples
632
+
633
+ DF.mutate(df, name: first_name <> " " <> last_name)
634
+
635
+ If you want to convert concatenate non-string
636
+ series, you can explicitly cast them to string
637
+ before:
638
+
639
+ DF.mutate(df, name: cast(year, :string) <> "-" <> cast(month, :string))
640
+
641
+ Or use format:
642
+
643
+ DF.mutate(df, name: format([year, "-", month]))
644
+ """
645
+ defmacro left <> right do
646
+ parts = [left | extract_concatenations(right)]
647
+
648
+ quote do
649
+ unquote(__MODULE__).__concatenate__(unquote(parts))
650
+ end
651
+ end
652
+
653
+ defp extract_concatenations({:<>, _, [left, right]}), do: [left | extract_concatenations(right)]
654
+ defp extract_concatenations(other), do: [other]
655
+
656
+ @doc false
657
+ def __concatenate__(parts) do
658
+ case validate_concatenation(parts, true) do
659
+ true -> IO.iodata_to_binary(parts)
660
+ false -> Explorer.Series.format(parts)
661
+ end
662
+ end
663
+
664
+ @error_message "the string concatenation operator (<>) inside Explorer.Query expects either " <>
665
+ "an Elixir string or a Series with :string dtype, got: "
666
+
667
+ defp validate_concatenation([%Explorer.Series{dtype: :string} | parts], _all_binary?) do
668
+ validate_concatenation(parts, false)
669
+ end
670
+
671
+ defp validate_concatenation([%Explorer.Series{} = part | _parts], _all_binary?) do
672
+ raise ArgumentError,
673
+ <<@error_message, inspect(part)::binary,
674
+ " (use cast(series, :string) to convert an existing series)"::binary>>
675
+ end
676
+
677
+ defp validate_concatenation([part | parts], all_binary?) when is_binary(part) do
678
+ validate_concatenation(parts, all_binary?)
679
+ end
680
+
681
+ defp validate_concatenation([part | _parts], _all_binary?) do
682
+ raise ArgumentError,
683
+ <<@error_message, inspect(part)::binary,
684
+ " (use Kernel.to_string(value) to convert an existing value to string)">>
685
+ end
686
+
687
+ defp validate_concatenation([], all_binary?), do: all_binary?
688
+
689
+ @doc """
690
+ Provides `if/2` conditionals inside queries.
691
+ """
692
+ def if(condition, do: do_clause) do
693
+ if(condition, do: do_clause, else: nil)
694
+ end
695
+
696
+ def if(condition, do: do_clause, else: else_clause) do
697
+ __cond__([{true, else_clause}, {condition, do_clause}])
698
+ end
699
+
700
+ def if(_condition, _arguments) do
701
+ raise ArgumentError,
702
+ "invalid or duplicate keys for if, only \"do\" and an optional \"else\" are permitted"
703
+ end
704
+
705
+ @doc """
706
+ Provides `unless/2` conditionals inside queries.
707
+ """
708
+ def unless(condition, do: do_clause) do
709
+ unless(condition, do: do_clause, else: nil)
710
+ end
711
+
712
+ def unless(condition, do: do_clause, else: else_clause) do
713
+ __cond__([{true, do_clause}, {condition, else_clause}])
714
+ end
715
+
716
+ def unless(_condition, _arguments) do
717
+ raise ArgumentError,
718
+ "invalid or duplicate keys for unless, only \"do\" and an optional \"else\" are permitted"
719
+ end
720
+
721
+ @doc false
722
+ def __cond__(clauses) do
723
+ Enum.reduce(clauses, nil, fn
724
+ {true, truthy}, _acc ->
725
+ lazy_series_for_cond!(truthy, clauses)
726
+
727
+ {false, _truthy}, acc ->
728
+ lazy_series_for_cond!(acc, clauses)
729
+
730
+ {%Explorer.Series{} = predicate, truthy}, acc ->
731
+ on_true = lazy_series_for_cond!(truthy, clauses)
732
+ on_false = lazy_series_for_cond!(acc, clauses)
733
+ Explorer.Backend.LazySeries.select(predicate, on_true, on_false)
734
+
735
+ {other, _truthy}, _acc ->
736
+ raise ArgumentError,
737
+ "conditionals expect predicates to be series or a boolean, got: #{inspect(other)}"
738
+ end)
739
+ end
740
+
741
+ defp lazy_series_for_cond!(%Explorer.Series{} = val, _clauses), do: val
742
+
743
+ defp lazy_series_for_cond!(nil, clauses) do
744
+ {_, non_empty_clause} = Enum.find(clauses, fn {_condition, truthy} -> truthy end)
745
+ series = lazy_series_for_cond!(non_empty_clause, clauses)
746
+ Explorer.Backend.LazySeries.from_list([nil], series.dtype)
747
+ end
748
+
749
+ defp lazy_series_for_cond!(val, _clauses),
750
+ do: Explorer.Backend.LazySeries.from_list([val], Explorer.Shared.dtype_from_list!([val]))
751
+
752
+ @doc """
753
+ Accesses a column by name.
754
+
755
+ If your column name contains whitespace or start with
756
+ uppercase letters, you can still access its name by
757
+ using this macro:
758
+
759
+ iex> df = Explorer.DataFrame.new("unusual nums": [1, 2, 3])
760
+ iex> Explorer.DataFrame.filter(df, col("unusual nums") > 2)
761
+ #Explorer.DataFrame<
762
+ Polars[1 x 1]
763
+ unusual nums s64 [3]
764
+ >
765
+
766
+ `name` must be an atom, a string, or an integer.
767
+ It is equivalent to `df[name]` but inside a query.
768
+
769
+ This can also be used if you want to access a column
770
+ programmatically, for example:
771
+
772
+ iex> df = Explorer.DataFrame.new(nums: [1, 2, 3])
773
+ iex> name = :nums
774
+ iex> Explorer.DataFrame.filter(df, col(^name) > 2)
775
+ #Explorer.DataFrame<
776
+ Polars[1 x 1]
777
+ nums s64 [3]
778
+ >
779
+
780
+ For traversing multiple columns programmatically,
781
+ see `across/0` and `across/1`.
782
+ """
783
+ defmacro col(name) do
784
+ quote do: Explorer.DataFrame.pull(unquote(df_var()), unquote(name))
785
+ end
786
+
787
+ @doc """
788
+ Accesses all columns in the dataframe.
789
+
790
+ This is the equivalent to `across(..)`.
791
+
792
+ See the module docs for more information.
793
+ """
794
+ defmacro across() do
795
+ quote do
796
+ Explorer.Query.__across__(unquote(df_var()), ..)
797
+ end
798
+ end
799
+
800
+ @doc """
801
+ Accesses the columns given by `selector` in the dataframe.
802
+
803
+ `across/1` is used as the generator inside for-comprehensions.
804
+
805
+ See the module docs for more information.
806
+ """
807
+ defmacro across(selector) do
808
+ quote do
809
+ Explorer.Query.__across__(unquote(df_var()), unquote(selector))
810
+ end
811
+ end
812
+
813
+ @doc """
814
+ Returns the dataframe scoped by this query.
815
+ """
816
+ defmacro df(), do: df_var()
817
+
818
+ @doc false
819
+ def __across__(df, selector) do
820
+ df
821
+ |> Explorer.Shared.to_existing_columns(selector)
822
+ |> Enum.map(&%{Explorer.Shared.apply_dataframe(df, :pull, [&1]) | name: &1})
823
+ end
824
+
825
+ defp df_var(), do: quote(do: var!(df, Explorer.Query))
826
+ end
deps/explorer/lib/explorer/remote.ex ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.Remote do
2
+ @moduledoc """
3
+ A module responsible for placing remote dataframes and
4
+ garbage collect them.
5
+
6
+ The functions in `Explorer.DataFrame` and `Explorer.Series`
7
+ will automatically move operations on remote dataframes to
8
+ the nodes they belong to. `Explorer` also integrates with
9
+ `FLAME` and automatically tracks remote dataframes and
10
+ series returned from `FLAME` calls when the `:track_resources`
11
+ option is enabled.
12
+
13
+ This module provides additional conveniences for manual placement.
14
+
15
+ ## Implementation details
16
+
17
+ In order to understand what this module does, we need
18
+ to understand the challenges in working with remote series
19
+ and dataframes.
20
+
21
+ Series and dataframes are actually NIF resources: they are
22
+ pointers to blobs of memory operated by low-level libraries.
23
+ Those are represented in Erlang/Elixir as references (the
24
+ same as the one returned by `make_ref/0`). Once the reference
25
+ is garbage collected (based on refcounting), those NIF
26
+ resources are garbage collected and the memory is reclaimed.
27
+
28
+ When using Distributed Erlang, you may write this code:
29
+
30
+ remote_series = :erpc.call(node, Explorer.Series, :from_list, [[1, 2, 3]])
31
+
32
+ However, the code above will not work, because the series
33
+ will be allocated in the remote node and the remote node
34
+ won't hold a reference to said series! This means the series
35
+ is garbage collected and if we attempt to read it later on,
36
+ from the caller node, it will no longer exist. Therefore,
37
+ we must explicitly place these resources in remote nodes
38
+ by spawning processes to hold these references. That's what
39
+ the `place/2` function in this module does.
40
+
41
+ We also need to guarantee these resources are not kept
42
+ forever by these remote nodes, so `place/2` creates a
43
+ local NIF resource that notifies the remote resources
44
+ they have been GCed, effectively implementing a remote
45
+ garbage collector.
46
+ """
47
+
48
+ @doc """
49
+ Receives a data structure and traverses it looking
50
+ for remote dataframes and series.
51
+
52
+ If any is found, it spawns a process on the remote node
53
+ and sets up a distributed garbage collector. This function
54
+ only traverses maps, lists, and tuples, it does not support
55
+ arbitrary structs (such as map sets).
56
+
57
+ It returns the updated term and a list of remote PIDs
58
+ spawned.
59
+ """
60
+ def place(term, acc \\ []), do: place_on_node(term, acc)
61
+
62
+ defp place_on_node(term, acc) do
63
+ place(term, acc, &Explorer.Remote.Holder.start_child/2)
64
+ end
65
+
66
+ defp place_on_pid(term, remote_pid) do
67
+ place(term, [], fn _remote_ref, _local_gc ->
68
+ {:ok, remote_pid}
69
+ end)
70
+ end
71
+
72
+ defp place(tuple, acc, fun) when is_tuple(tuple) do
73
+ {list, acc} = tuple |> Tuple.to_list() |> place(acc, fun)
74
+ {List.to_tuple(list), acc}
75
+ end
76
+
77
+ defp place(list, acc, fun) when is_list(list) do
78
+ Enum.map_reduce(list, acc, &place(&1, &2, fun))
79
+ end
80
+
81
+ defp place(%Explorer.Backend.LazySeries{args: args} = lazy_series, acc, fun) do
82
+ {args, acc} = Enum.map_reduce(args, acc, &place(&1, &2, fun))
83
+ {%{lazy_series | args: args}, acc}
84
+ end
85
+
86
+ defp place(%Explorer.Series{data: %Explorer.Backend.LazySeries{} = data} = series, acc, fun) do
87
+ {data, acc} = place(data, acc, fun)
88
+ {%{series | data: data}, acc}
89
+ end
90
+
91
+ defp place(%Explorer.Series{data: %impl{}} = series, acc, fun) do
92
+ place_impl(impl, series, acc, fun)
93
+ end
94
+
95
+ defp place(%Explorer.DataFrame{data: %impl{}} = df, acc, fun) do
96
+ place_impl(impl, df, acc, fun)
97
+ end
98
+
99
+ defp place(%_{} = other, acc, _fun) do
100
+ {other, acc}
101
+ end
102
+
103
+ defp place(%{} = map, acc, fun) do
104
+ {pairs, acc} =
105
+ Enum.map_reduce(map, acc, fn {k, v}, acc ->
106
+ {k, acc} = place(k, acc, fun)
107
+ {v, acc} = place(v, acc, fun)
108
+ {{k, v}, acc}
109
+ end)
110
+
111
+ {Map.new(pairs), acc}
112
+ end
113
+
114
+ defp place(other, acc, _fun) do
115
+ {other, acc}
116
+ end
117
+
118
+ defp place_impl(impl, struct, acc, fun) do
119
+ with remote_ref when is_reference(remote_ref) and node(remote_ref) != node() <-
120
+ impl.owner_reference(struct),
121
+ false <- alive?(remote_ref, struct) do
122
+ {local_ref, remote_pid} = place_remote_ref(remote_ref, fun)
123
+ {%{struct | remote: {local_ref, remote_pid, remote_ref}}, [remote_pid | acc]}
124
+ else
125
+ _ ->
126
+ {struct, acc}
127
+ end
128
+ end
129
+
130
+ defp alive?(remote_ref, %{remote: {local_gc_ref, _, remote_ref}})
131
+ when is_reference(local_gc_ref) and node(local_gc_ref) == node(),
132
+ do: Explorer.Remote.LocalGC.alive?(local_gc_ref)
133
+
134
+ defp alive?(_remote_ref, _struct), do: false
135
+
136
+ defp place_remote_ref(remote_ref, fun) do
137
+ local_gc = Explorer.Remote.LocalGC.whereis!()
138
+ {:ok, remote_pid} = fun.(remote_ref, local_gc)
139
+ local_ref = Explorer.Remote.LocalGC.track(local_gc, remote_pid, remote_ref)
140
+ Explorer.Remote.Holder.hold(remote_pid, remote_ref, local_gc)
141
+ {local_ref, remote_pid}
142
+ end
143
+
144
+ @doc false
145
+ # Applies the given mod/fun/args in the remote node.
146
+ # If a pid is given, we assume the pid will hold those references
147
+ # and avoid spawning new ones. If a node is given, regular placement
148
+ # occurs.
149
+ def apply(pid, mod, fun, resources, args_callback, place?) when is_pid(pid) do
150
+ placing_callback = if place?, do: &place_on_pid(&1, pid), else: &{&1, []}
151
+ do_apply(node(pid), mod, fun, resources, args_callback, placing_callback)
152
+ end
153
+
154
+ def apply(node, mod, fun, resources, args_callback, place?) when is_atom(node) do
155
+ placing_callback = if place?, do: &place_on_node(&1, []), else: &{&1, []}
156
+ do_apply(node, mod, fun, resources, args_callback, placing_callback)
157
+ end
158
+
159
+ defp do_apply(node, mod, fun, resources, args_callback, placing_callback) do
160
+ resources =
161
+ Enum.map(resources, fn
162
+ {resource_data, resource_node} when resource_node == node or resource_node == nil ->
163
+ {:local, resource_data}
164
+
165
+ {%{data: %impl{}} = resource_data, resource_node} ->
166
+ {:remote, impl, owner_export(resource_node, impl, resource_data)}
167
+ end)
168
+
169
+ message_ref = :erlang.make_ref()
170
+ remote_args = [self(), message_ref, mod, fun, resources, args_callback]
171
+ child = Node.spawn_link(node, __MODULE__, :remote_apply, remote_args)
172
+ monitor_ref = Process.monitor(child)
173
+
174
+ receive do
175
+ {^message_ref, result} ->
176
+ Process.demonitor(monitor_ref, [:flush])
177
+ {term, _acc} = placing_callback.(result)
178
+ send(child, {message_ref, :ok})
179
+ term
180
+
181
+ {:DOWN, ^monitor_ref, _, _, reason} ->
182
+ exit(reason)
183
+ end
184
+ end
185
+
186
+ defp owner_export(resource_node, impl, resource_data) do
187
+ case :erpc.call(resource_node, impl, :owner_export, [resource_data]) do
188
+ {:ok, val} -> val
189
+ {:error, error} -> raise error
190
+ end
191
+ end
192
+
193
+ defp owner_import(impl, exported_data) do
194
+ case impl.owner_import(exported_data) do
195
+ {:ok, val} -> val
196
+ {:error, error} -> raise error
197
+ end
198
+ end
199
+
200
+ @doc false
201
+ def remote_apply(parent, message_ref, mod, fun, resources, args_callback) do
202
+ resources =
203
+ Enum.map(resources, fn
204
+ {:local, value} -> value
205
+ {:remote, impl, value} -> owner_import(impl, value)
206
+ end)
207
+
208
+ monitor_ref = Process.monitor(parent)
209
+ result = apply(mod, fun, args_callback.(resources))
210
+ send(parent, {message_ref, result})
211
+
212
+ receive do
213
+ {^message_ref, :ok} ->
214
+ Process.demonitor(monitor_ref, [:flush])
215
+ # Call a remote function to prevent garbage collection from happening until we are done
216
+ Explorer.Remote.LocalGC.identity(result)
217
+
218
+ {:DOWN, ^monitor_ref, _, _, reason} ->
219
+ exit(reason)
220
+ end
221
+ end
222
+ end
223
+
224
+ if Code.ensure_loaded?(FLAME.Trackable) do
225
+ defimpl FLAME.Trackable, for: [Explorer.DataFrame, Explorer.Series, Explorer.Backend.LazySeries] do
226
+ def track(data, acc, _node) do
227
+ Explorer.Remote.place(data, acc)
228
+ end
229
+ end
230
+ end
deps/explorer/lib/explorer/remote/holder.ex ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.Remote.Holder do
2
+ # This process is spawned dynamically by a node
3
+ # that wants to hold a reference to a resource
4
+ # on this node. To avoid leaking resources, it
5
+ # is tied to the local GC process of the spawned node.
6
+ @moduledoc false
7
+
8
+ use GenServer, restart: :transient
9
+
10
+ def start_child(remote_ref, local_gc) when is_reference(remote_ref) and is_pid(local_gc) do
11
+ DynamicSupervisor.start_child(
12
+ {Explorer.Remote.Supervisor, node(remote_ref)},
13
+ {__MODULE__, local_gc}
14
+ )
15
+ end
16
+
17
+ def hold(holder, ref, pid) when is_pid(pid) and node(ref) == node(holder) do
18
+ GenServer.call(holder, {:hold, ref, pid}, :infinity)
19
+ end
20
+
21
+ def start_link(pid) when is_pid(pid) do
22
+ GenServer.start_link(__MODULE__, pid)
23
+ end
24
+
25
+ @impl true
26
+ def init(pid) do
27
+ ref = Process.monitor(pid)
28
+ state = %{owner_ref: ref, refs: %{}, pids: %{}}
29
+ {:ok, state}
30
+ end
31
+
32
+ @impl true
33
+ def handle_call({:hold, ref, pid}, _from, state) do
34
+ _ = Process.monitor(pid)
35
+ refs = Map.update(state.refs, ref, [pid], &[pid | &1])
36
+ pids = Map.update(state.pids, pid, [ref], &[ref | &1])
37
+ {:reply, :ok, %{state | refs: refs, pids: pids, owner_ref: nil}}
38
+ end
39
+
40
+ @impl true
41
+ def handle_info({:gc, ref, pid}, state) do
42
+ refs = pop_from_list(state.refs, ref, pid)
43
+ pids = pop_from_list(state.pids, pid, ref)
44
+ :erlang.garbage_collect()
45
+ noreply_or_stop(%{state | pids: pids, refs: refs})
46
+ end
47
+
48
+ # We will only match this clause during initialization,
49
+ # the goal is to not leave orphaned processes.
50
+ def handle_info({:DOWN, owner_ref, _, _, reason}, %{owner_ref: owner_ref} = state) do
51
+ {:stop, reason, state}
52
+ end
53
+
54
+ def handle_info({:DOWN, _, _, pid, _}, state) do
55
+ {pid_refs, pids} = Map.pop(state.pids, pid, [])
56
+ refs = Enum.reduce(pid_refs, state.refs, &pop_from_list(&2, &1, pid))
57
+ :erlang.garbage_collect()
58
+ noreply_or_stop(%{state | pids: pids, refs: refs})
59
+ end
60
+
61
+ defp noreply_or_stop(%{refs: refs} = state) when refs == %{}, do: {:stop, :shutdown, state}
62
+ defp noreply_or_stop(state), do: {:noreply, state}
63
+
64
+ defp pop_from_list(map, key, value) do
65
+ case map do
66
+ %{^key => list} ->
67
+ case List.delete(list, value) do
68
+ [] -> Map.delete(map, key)
69
+ new_value -> Map.put(map, key, new_value)
70
+ end
71
+
72
+ %{} ->
73
+ map
74
+ end
75
+ end
76
+ end
deps/explorer/lib/explorer/remote/local_gc.ex ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.Remote.LocalGC do
2
+ # This process is spawned on every node running Explorer.
3
+ # It is responsible for tracking the local GC and reporting
4
+ # them to the remote holder nodes.
5
+ @moduledoc false
6
+
7
+ use GenServer
8
+ @name __MODULE__
9
+
10
+ def start_link(_opts) do
11
+ GenServer.start_link(__MODULE__, :ok, name: @name)
12
+ end
13
+
14
+ @doc """
15
+ An identity function to prevent GC.
16
+ """
17
+ def identity(data), do: data
18
+
19
+ @doc """
20
+ Locates the LocalGC process.
21
+ """
22
+ def whereis! do
23
+ Process.whereis(@name) || exit({:noproc, {__MODULE__, :whereis!, []}})
24
+ end
25
+
26
+ @doc """
27
+ This is a function that receives a process and a payload
28
+ and it returns a NIF resource.
29
+
30
+ Once the NIF resource is GCed, it sends a message `{:gc, pid, ref}`
31
+ to the local GC process, which forwards it to the holder node.
32
+ """
33
+ def track(local_gc, remote_pid, remote_ref)
34
+ when is_pid(local_gc) and is_pid(remote_pid) and is_reference(remote_ref) do
35
+ Explorer.PolarsBackend.Native.message_on_gc(local_gc, {:gc, remote_pid, remote_ref})
36
+ end
37
+
38
+ @doc """
39
+ Check is a local gc reference is alive.
40
+ """
41
+ def alive?(local_gc_ref) when is_reference(local_gc_ref) do
42
+ Explorer.PolarsBackend.Native.is_message_on_gc(local_gc_ref)
43
+ end
44
+
45
+ ## Callbacks
46
+
47
+ @impl true
48
+ def init(:ok) do
49
+ {:ok, :unused_state}
50
+ end
51
+
52
+ @impl true
53
+ def handle_info({:gc, remote_pid, remote_ref}, state) do
54
+ send(remote_pid, {:gc, remote_ref, self()})
55
+ {:noreply, state}
56
+ end
57
+ end
deps/explorer/lib/explorer/series.ex ADDED
The diff for this file is too large to render. See raw diff
 
deps/explorer/lib/explorer/shared.ex ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.Shared do
2
+ # A collection of **private** helpers shared in Explorer.
3
+ @moduledoc false
4
+
5
+ require Logger
6
+
7
+ @integer_types [
8
+ {:s, 8},
9
+ {:s, 16},
10
+ {:s, 32},
11
+ {:s, 64},
12
+ {:u, 8},
13
+ {:u, 16},
14
+ {:u, 32},
15
+ {:u, 64}
16
+ ]
17
+
18
+ @precisions [:millisecond, :microsecond, :nanosecond]
19
+
20
+ @precision_types for d <- [:naive_datetime, :duration],
21
+ p <- @precisions,
22
+ do: {d, p}
23
+
24
+ @scalar_types @integer_types ++
25
+ @precision_types ++
26
+ [
27
+ :null,
28
+ :binary,
29
+ :boolean,
30
+ :category,
31
+ :date,
32
+ {:f, 32},
33
+ {:f, 64},
34
+ :string,
35
+ :time
36
+ ]
37
+
38
+ @doc """
39
+ All supported dtypes.
40
+
41
+ This list excludes recursive dtypes, such as lists
42
+ within lists inside.
43
+ """
44
+ def dtypes do
45
+ @scalar_types ++
46
+ [{:list, :any}, {:struct, :any}, {:decimal, :pos_integer, :pos_integer}]
47
+ end
48
+
49
+ @doc """
50
+ Normalise a given dtype and return nil if is invalid.
51
+ """
52
+ def normalise_dtype({:list, inner}) do
53
+ if maybe_dtype = normalise_dtype(inner), do: {:list, maybe_dtype}
54
+ end
55
+
56
+ def normalise_dtype({:struct, inner_types}) do
57
+ inner_types
58
+ |> Enum.reduce_while([], fn {key, dtype}, normalized_dtypes ->
59
+ case normalise_dtype(dtype) do
60
+ nil ->
61
+ {:halt, nil}
62
+
63
+ dtype ->
64
+ key = to_string(key)
65
+ {:cont, List.keystore(normalized_dtypes, key, 0, {key, dtype})}
66
+ end
67
+ end)
68
+ |> then(fn
69
+ nil ->
70
+ nil
71
+
72
+ normalized_dtypes ->
73
+ {:struct,
74
+ if(is_map(inner_types), do: Enum.sort(normalized_dtypes), else: normalized_dtypes)}
75
+ end)
76
+ end
77
+
78
+ def normalise_dtype({:datetime, p, tz} = dtype) when p in @precisions and is_binary(tz),
79
+ do: dtype
80
+
81
+ def normalise_dtype(dtype) when dtype in @scalar_types, do: dtype
82
+ def normalise_dtype(dtype) when dtype in [:float, :f64], do: {:f, 64}
83
+ def normalise_dtype(dtype) when dtype in [:integer, :s64], do: {:s, 64}
84
+ def normalise_dtype(:f32), do: {:f, 32}
85
+ def normalise_dtype(:s8), do: {:s, 8}
86
+ def normalise_dtype(:s16), do: {:s, 16}
87
+ def normalise_dtype(:s32), do: {:s, 32}
88
+ def normalise_dtype(:u8), do: {:u, 8}
89
+ def normalise_dtype(:u16), do: {:u, 16}
90
+ def normalise_dtype(:u32), do: {:u, 32}
91
+ def normalise_dtype(:u64), do: {:u, 64}
92
+
93
+ def normalise_dtype({:datetime, precision}) do
94
+ :ok =
95
+ Logger.warning("""
96
+ The `{:datetime, _}` dtype has been deprecated.
97
+ Please use `{:naive_datetime, _}` instead.
98
+ """)
99
+
100
+ {:naive_datetime, precision}
101
+ end
102
+
103
+ # Not a valid option, but this is necessary because the backend
104
+ # may return a decimal dtype without precision. We should cast in these cases.
105
+ def normalise_dtype({:decimal, nil, scale}), do: normalise_dtype({:decimal, 38, scale})
106
+
107
+ def normalise_dtype({:decimal, precision, scale} = dtype)
108
+ when is_integer(scale) and is_integer(precision) do
109
+ if precision in 0..38//1 and scale in 0..38//1 and scale <= precision do
110
+ dtype
111
+ end
112
+ end
113
+
114
+ def normalise_dtype(_dtype), do: nil
115
+
116
+ @doc """
117
+ Normalise a given dtype, but raise error in case it's invalid.
118
+ """
119
+ def normalise_dtype!(dtype) do
120
+ if maybe_dtype = normalise_dtype(dtype) do
121
+ maybe_dtype
122
+ else
123
+ raise ArgumentError,
124
+ "unsupported dtype #{inspect(dtype)}, expected one of #{inspect_dtypes(dtypes())}"
125
+ end
126
+ end
127
+
128
+ @doc """
129
+ Supported naive datetime dtypes.
130
+ """
131
+ def naive_datetime_types, do: for(p <- @precisions, do: {:naive_datetime, p})
132
+
133
+ @doc """
134
+ Supported duration dtypes.
135
+ """
136
+ def duration_types, do: for(p <- @precisions, do: {:duration, p})
137
+
138
+ @doc """
139
+ Supported float dtypes.
140
+ """
141
+ def float_types, do: [{:f, 32}, {:f, 64}]
142
+
143
+ @doc """
144
+ Supported signed integer dtypes.
145
+ """
146
+ def signed_integer_types, do: [{:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}]
147
+
148
+ @doc """
149
+ Supported unsigned integer dtypes.
150
+ """
151
+ def unsigned_integer_types, do: [{:u, 8}, {:u, 16}, {:u, 32}, {:u, 64}]
152
+
153
+ @doc """
154
+ All integer dtypes.
155
+ """
156
+ def integer_types, do: signed_integer_types() ++ unsigned_integer_types()
157
+
158
+ @doc """
159
+ Both integer and float dtypes.
160
+ """
161
+ def numeric_types, do: float_types() ++ integer_types()
162
+
163
+ @doc """
164
+ Gets the backend from a `Keyword.t()` or `nil`.
165
+ """
166
+ def backend_from_options!(opts) do
167
+ case Keyword.fetch(opts, :backend) do
168
+ {:ok, backend} when is_atom(backend) ->
169
+ backend
170
+
171
+ {:ok, other} ->
172
+ raise ArgumentError,
173
+ ":backend must be an atom, got: #{inspect(other)}"
174
+
175
+ :error ->
176
+ nil
177
+ end
178
+ end
179
+
180
+ @doc """
181
+ Normalize column names and raise if column does not exist.
182
+ """
183
+ def to_existing_columns(df, columns, raise? \\ true)
184
+
185
+ def to_existing_columns(df, columns, raise?) when is_list(columns) do
186
+ {columns, _cache} =
187
+ Enum.map_reduce(columns, nil, fn
188
+ column, maybe_map when is_integer(column) ->
189
+ map = maybe_map || column_index_map(df.names)
190
+ existing_column = fetch_column_at!(map, column)
191
+ {existing_column, map}
192
+
193
+ column, maybe_map when is_atom(column) ->
194
+ column = Atom.to_string(column)
195
+ maybe_raise_column_not_found(df, column, raise?)
196
+ {column, maybe_map}
197
+
198
+ column, maybe_map when is_binary(column) ->
199
+ maybe_raise_column_not_found(df, column, raise?)
200
+ {column, maybe_map}
201
+ end)
202
+
203
+ columns
204
+ end
205
+
206
+ def to_existing_columns(%{names: names}, .., _raise?) do
207
+ names
208
+ end
209
+
210
+ def to_existing_columns(%{names: names}, %Range{} = columns, _raise?) do
211
+ Enum.slice(names, columns)
212
+ end
213
+
214
+ def to_existing_columns(%{names: names}, %Regex{} = columns, _raise?) do
215
+ Enum.filter(names, &Regex.match?(columns, &1))
216
+ end
217
+
218
+ def to_existing_columns(%{names: names}, callback, _raise?) when is_function(callback, 1) do
219
+ Enum.filter(names, callback)
220
+ end
221
+
222
+ def to_existing_columns(%{names: names, dtypes: dtypes}, callback, _raise?)
223
+ when is_function(callback, 2) do
224
+ Enum.filter(names, fn name -> callback.(name, dtypes[name]) end)
225
+ end
226
+
227
+ def to_existing_columns(_, other, _raise?) do
228
+ raise ArgumentError, """
229
+ invalid columns specification. Columns may be specified as one of:
230
+
231
+ * a list of columns indexes or names as atoms and strings
232
+
233
+ * a range
234
+
235
+ * a regex that keeps only the names matching the regex
236
+
237
+ * a one-arity function that receives column names and returns
238
+ true for column names to keep
239
+
240
+ * a two-arity function that receives column names and types and
241
+ returns true for column names to keep
242
+
243
+ Got: #{inspect(other)}
244
+ """
245
+ end
246
+
247
+ defp fetch_column_at!(map, index) do
248
+ normalized = if index < 0, do: index + map_size(map), else: index
249
+
250
+ case map do
251
+ %{^normalized => column} -> column
252
+ %{} -> raise ArgumentError, "no column exists at index #{index}"
253
+ end
254
+ end
255
+
256
+ defp column_index_map(names),
257
+ do: for({name, idx} <- Enum.with_index(names), into: %{}, do: {idx, name})
258
+
259
+ @doc """
260
+ Raises if a column is not found.
261
+ """
262
+ def maybe_raise_column_not_found(df, name, raise? \\ true) do
263
+ if raise? and Map.has_key?(df.dtypes, name) == false do
264
+ raise ArgumentError,
265
+ List.to_string(
266
+ [
267
+ "could not find column name \"#{name}\"" | did_you_mean(name, df.names)
268
+ ] ++ ["\nIf you are attempting to interpolate a value, use ^#{name}."]
269
+ )
270
+ end
271
+ end
272
+
273
+ @doc """
274
+ Gets the `dtype` of a list or raise error if not possible.
275
+ """
276
+ def dtype_from_list!(list) do
277
+ Enum.reduce(list, :null, &infer_type/2)
278
+ end
279
+
280
+ @doc """
281
+ Gets the dtype from the list according to the preferred type.
282
+
283
+ The dtype from the list is first computed standalone.
284
+ If the list can be directly instantiated as the preferred type,
285
+ then the preferred type is returned. Otherwise, the inferred type
286
+ is returned and a cast call to the preferred type is necessary.
287
+
288
+ If no preferred type is given (nil), then the inferred type is returned.
289
+ """
290
+ def dtype_from_list!(list, nil), do: dtype_from_list!(list)
291
+ def dtype_from_list!(_list, preferred_type), do: preferred_type
292
+
293
+ @non_finite [:nan, :infinity, :neg_infinity]
294
+
295
+ defp infer_type(nil, type), do: type
296
+ defp infer_type(item, :null), do: infer_type(item)
297
+ defp infer_type(integer, {:f, 64}) when is_integer(integer), do: {:f, 64}
298
+ defp infer_type(float, {:s, 64}) when is_float(float) or float in @non_finite, do: {:f, 64}
299
+
300
+ defp infer_type(integer, {:decimal, _, _} = decimal) when is_integer(integer), do: decimal
301
+
302
+ defp infer_type(float, {:decimal, _, _} = decimal) when is_float(float),
303
+ do: infer_type(Decimal.from_float(float), decimal)
304
+
305
+ defp infer_type(list, {:list, type}) when is_list(list), do: infer_list(list, type)
306
+ defp infer_type(%{} = map, {:struct, inner}), do: infer_struct(map, inner)
307
+
308
+ defp infer_type(%Decimal{} = item, {:decimal, precision, scale}) do
309
+ {:decimal, precision, max(Decimal.scale(item), scale)}
310
+ end
311
+
312
+ defp infer_type(item, type) do
313
+ if infer_type(item) == type do
314
+ type
315
+ else
316
+ raise ArgumentError,
317
+ "the value #{inspect(item)} does not match the inferred dtype #{inspect(type)}"
318
+ end
319
+ end
320
+
321
+ defp infer_type(%Date{} = _item), do: :date
322
+ defp infer_type(%Time{} = _item), do: :time
323
+ defp infer_type(%DateTime{time_zone: tz} = _item), do: {:datetime, :microsecond, tz}
324
+ defp infer_type(%NaiveDateTime{} = _item), do: {:naive_datetime, :microsecond}
325
+ defp infer_type(%Explorer.Duration{precision: precision} = _item), do: {:duration, precision}
326
+ defp infer_type(%Decimal{} = item), do: {:decimal, 38, Decimal.scale(item)}
327
+ defp infer_type(%_{} = item), do: raise(ArgumentError, "unsupported datatype: #{inspect(item)}")
328
+ defp infer_type(item) when is_integer(item), do: {:s, 64}
329
+ defp infer_type(item) when is_float(item) or item in @non_finite, do: {:f, 64}
330
+ defp infer_type(item) when is_boolean(item), do: :boolean
331
+ defp infer_type(item) when is_binary(item), do: :string
332
+ defp infer_type(list) when is_list(list), do: infer_list(list, :null)
333
+ defp infer_type(%{} = map), do: infer_struct(map, nil)
334
+ defp infer_type(item), do: raise(ArgumentError, "unsupported datatype: #{inspect(item)}")
335
+
336
+ defp infer_list(list, type) do
337
+ {:list, Enum.reduce(list, type, &infer_type/2)}
338
+ end
339
+
340
+ defp infer_struct(%{} = map, types) do
341
+ types =
342
+ for {key, value} <- map do
343
+ key = to_string(key)
344
+
345
+ cond do
346
+ types == nil ->
347
+ {key, infer_type(value, :null)}
348
+
349
+ result = List.keyfind(types, key, 0) ->
350
+ {^key, type} = result
351
+ {key, infer_type(value, type)}
352
+
353
+ true ->
354
+ raise ArgumentError,
355
+ "the value #{inspect(map)} does not match the inferred dtype #{inspect({:struct, types})}"
356
+ end
357
+ end
358
+
359
+ {:struct, Enum.sort(types)}
360
+ end
361
+
362
+ @doc """
363
+ Returns the leaf dtype from a {:list, _} dtype, or itself.
364
+ """
365
+ def leaf_dtype({:list, inner_dtype}), do: leaf_dtype(inner_dtype)
366
+ def leaf_dtype(dtype), do: dtype
367
+
368
+ @doc """
369
+ Merge two dtypes.
370
+ """
371
+ def merge_dtype(dtype, dtype), do: dtype
372
+ def merge_dtype(:null, dtype), do: dtype
373
+ def merge_dtype(dtype, :null), do: dtype
374
+ def merge_dtype(ltype, rtype), do: merge_numeric_dtype(ltype, rtype)
375
+
376
+ @doc """
377
+ Merge two numeric dtypes to a valid precision.
378
+ """
379
+ def merge_numeric_dtype({int_type, left}, {int_type, right}) when int_type in [:s, :u],
380
+ do: {int_type, max(left, right)}
381
+
382
+ def merge_numeric_dtype({:s, s_size}, {:u, u_size}), do: {:s, max(min(64, u_size * 2), s_size)}
383
+ def merge_numeric_dtype({:u, s_size}, {:s, u_size}), do: {:s, max(min(64, u_size * 2), s_size)}
384
+ def merge_numeric_dtype({int_type, _}, {:f, _} = float) when int_type in [:s, :u], do: float
385
+ def merge_numeric_dtype({:f, _} = float, {int_type, _}) when int_type in [:s, :u], do: float
386
+ def merge_numeric_dtype({:f, left}, {:f, right}), do: {:f, max(left, right)}
387
+ def merge_numeric_dtype({:f, _} = float, :null), do: float
388
+ def merge_numeric_dtype(:null, {:f, _} = float), do: float
389
+
390
+ def merge_numeric_dtype({:decimal, _, _} = decimal, :null), do: decimal
391
+ def merge_numeric_dtype(:null, {:decimal, _, _} = decimal), do: decimal
392
+
393
+ def merge_numeric_dtype({:decimal, _, _}, {:f, _} = float), do: float
394
+ def merge_numeric_dtype({:f, _} = float, {:decimal, _, _}), do: float
395
+
396
+ def merge_numeric_dtype({:decimal, _, _} = decimal, {:s, _}), do: decimal
397
+ def merge_numeric_dtype({:s, _}, {:decimal, _, _} = decimal), do: decimal
398
+
399
+ def merge_numeric_dtype({:decimal, _, _} = decimal, {:u, _}), do: decimal
400
+ def merge_numeric_dtype({:u, _}, {:decimal, _, _} = decimal), do: decimal
401
+
402
+ def merge_numeric_dtype(_, _), do: nil
403
+
404
+ @doc """
405
+ Helper for shared behaviour in inspect.
406
+ """
407
+ def to_doc(item, opts) when is_list(item) do
408
+ open = Inspect.Algebra.color("[", :list, opts)
409
+ close = Inspect.Algebra.color("]", :list, opts)
410
+ Inspect.Algebra.container_doc(open, item, close, opts, &to_doc/2)
411
+ end
412
+
413
+ def to_doc(item, opts) when is_map(item) and not is_struct(item) do
414
+ open = Inspect.Algebra.color("%{", :map, opts)
415
+ close = Inspect.Algebra.color("}", :map, opts)
416
+ arrow = Inspect.Algebra.color(" => ", :map, opts)
417
+
418
+ Inspect.Algebra.container_doc(open, Enum.to_list(item), close, opts, fn {key, value}, opts ->
419
+ Inspect.Algebra.concat([
420
+ Inspect.Algebra.color(inspect(key), :string, opts),
421
+ arrow,
422
+ to_doc(value, opts)
423
+ ])
424
+ end)
425
+ end
426
+
427
+ def to_doc(item, _opts) do
428
+ case item do
429
+ nil -> "nil"
430
+ :nan -> "NaN"
431
+ :infinity -> "Inf"
432
+ :neg_infinity -> "-Inf"
433
+ i when is_binary(i) -> inspect(i)
434
+ _ -> Kernel.to_string(item)
435
+ end
436
+ end
437
+
438
+ @doc """
439
+ Helper to inspect dtypes in a sentence.
440
+ """
441
+ def inspect_dtypes(dtypes, opts \\ []) do
442
+ opts = Keyword.validate!(opts, with_prefix: false, backticks: false)
443
+
444
+ inspect_fun =
445
+ if opts[:backticks] do
446
+ fn item -> "`" <> inspect(item) <> "`" end
447
+ else
448
+ &Kernel.inspect/1
449
+ end
450
+
451
+ case dtypes do
452
+ [dtype] ->
453
+ if opts[:with_prefix] do
454
+ "dtype is #{inspect_fun.(dtype)}"
455
+ else
456
+ inspect_fun.(dtype)
457
+ end
458
+
459
+ [_ | _] = dtypes ->
460
+ prefix =
461
+ if opts[:with_prefix] do
462
+ "dtypes are "
463
+ else
464
+ ""
465
+ end
466
+
467
+ {items, [last]} = Enum.split(Enum.sort(dtypes), -1)
468
+
469
+ IO.iodata_to_binary([
470
+ prefix,
471
+ Enum.map_intersperse(items, ", ", inspect_fun),
472
+ " and ",
473
+ inspect_fun.(last)
474
+ ])
475
+ end
476
+ end
477
+
478
+ @doc """
479
+ Converts a dtype to an iotype.
480
+
481
+ Note this is a subset of Series.iotype/1, given we can convert
482
+ a category series to iotype but we cannot generally convert
483
+ a category dtype to an iotype without the underlying categories.
484
+ """
485
+ def dtype_to_iotype(dtype) do
486
+ case dtype do
487
+ {:f, _} -> dtype
488
+ {:s, _} -> dtype
489
+ {:u, _} -> dtype
490
+ :boolean -> {:u, 8}
491
+ :date -> {:s, 32}
492
+ :time -> {:s, 64}
493
+ {:naive_datetime, _} -> {:s, 64}
494
+ {:datetime, _, _} -> {:s, 64}
495
+ {:duration, _} -> {:s, 64}
496
+ _ -> :none
497
+ end
498
+ end
499
+
500
+ @doc """
501
+ Raising version of `dtype_to_iotype/1`.
502
+ """
503
+ def dtype_to_iotype!(dtype) do
504
+ case dtype_to_iotype(dtype) do
505
+ :none -> raise ArgumentError, "cannot convert dtype #{dtype} into a binary/tensor type"
506
+ other -> other
507
+ end
508
+ end
509
+
510
+ @doc """
511
+ Converts an iotype to dtype.
512
+ """
513
+ def iotype_to_dtype!(type) do
514
+ case type do
515
+ {:f, _} -> type
516
+ {:s, _} -> type
517
+ {:u, _} -> type
518
+ _ -> raise ArgumentError, "cannot convert binary/tensor type #{inspect(type)} into dtype"
519
+ end
520
+ end
521
+
522
+ @doc """
523
+ Converts dtype to its string representation.
524
+ """
525
+ def dtype_to_string({:naive_datetime, p}), do: "naive_datetime[#{precision_string(p)}]"
526
+ def dtype_to_string({:datetime, p, tz}), do: "datetime[#{precision_string(p)}, #{tz}]"
527
+ def dtype_to_string({:duration, p}), do: "duration[#{precision_string(p)}]"
528
+ def dtype_to_string({:list, dtype}), do: "list[" <> dtype_to_string(dtype) <> "]"
529
+ def dtype_to_string({:struct, fields}), do: "struct[#{length(fields)}]"
530
+ def dtype_to_string({:f, size}), do: "f" <> Integer.to_string(size)
531
+ def dtype_to_string({:s, size}), do: "s" <> Integer.to_string(size)
532
+ def dtype_to_string({:u, size}), do: "u" <> Integer.to_string(size)
533
+ def dtype_to_string({:decimal, precision, scale}), do: "decimal[#{precision}, #{scale}]"
534
+ def dtype_to_string(other) when is_atom(other), do: Atom.to_string(other)
535
+
536
+ defp precision_string(:millisecond), do: "ms"
537
+ defp precision_string(:microsecond), do: "μs"
538
+ defp precision_string(:nanosecond), do: "ns"
539
+
540
+ @threshold 0.77
541
+ @max_suggestions 5
542
+
543
+ @doc """
544
+ Provides did_you_mean suggestions based on keys.
545
+ """
546
+ def did_you_mean(missing_key, available_keys) do
547
+ suggestions =
548
+ for key <- available_keys,
549
+ distance = String.jaro_distance(missing_key, key),
550
+ distance >= @threshold,
551
+ do: {distance, key}
552
+
553
+ case suggestions do
554
+ [] -> [". The available columns are: #{inspect(available_keys)}."]
555
+ suggestions -> [". Did you mean:\n\n" | format_suggestions(suggestions)]
556
+ end
557
+ end
558
+
559
+ defp format_suggestions(suggestions) do
560
+ suggestions
561
+ |> Enum.sort(&(elem(&1, 0) >= elem(&2, 0)))
562
+ |> Enum.take(@max_suggestions)
563
+ |> Enum.sort(&(elem(&1, 1) <= elem(&2, 1)))
564
+ |> Enum.map(fn {_, key} -> [" * ", inspect(key), ?\n] end)
565
+ end
566
+
567
+ @doc """
568
+ Validate options to be used for the various sorting functions.
569
+ """
570
+ def validate_sort_options!(opts) do
571
+ opts = Keyword.validate!(opts, [:direction, :nils, parallel: true, stable: false])
572
+
573
+ direction =
574
+ case Keyword.fetch(opts, :direction) do
575
+ {:ok, d} when d in [:asc, :desc] ->
576
+ d
577
+
578
+ :error ->
579
+ :not_provided
580
+
581
+ {:ok, x} ->
582
+ raise ArgumentError, "`:direction` must be `:asc` or `:desc`, found: #{inspect(x)}."
583
+ end
584
+
585
+ nils =
586
+ case Keyword.fetch(opts, :nils) do
587
+ {:ok, n} when n in [:first, :last] ->
588
+ n
589
+
590
+ :error ->
591
+ case direction do
592
+ :asc -> :last
593
+ :desc -> :first
594
+ :not_provided -> :last
595
+ end
596
+
597
+ {:ok, x} ->
598
+ raise ArgumentError, "`:nils` must be `:first` or `:last`, found: #{inspect(x)}."
599
+ end
600
+
601
+ parallel =
602
+ case Keyword.fetch!(opts, :parallel) do
603
+ b when is_boolean(b) -> b
604
+ x -> raise ArgumentError, "`:parallel` must be `true` or `false`, found: #{inspect(x)}."
605
+ end
606
+
607
+ stable =
608
+ case Keyword.fetch!(opts, :stable) do
609
+ b when is_boolean(b) -> b
610
+ x -> raise ArgumentError, "`:stable` must be `true` or `false`, found: #{inspect(x)}."
611
+ end
612
+
613
+ descending? = direction == :desc
614
+ maintain_order? = stable == true
615
+ multithreaded? = parallel == true
616
+ nulls_last? = nils == :last
617
+
618
+ [descending?, maintain_order?, multithreaded?, nulls_last?]
619
+ end
620
+
621
+ ## Apply
622
+
623
+ @doc """
624
+ Initializes a series or a dataframe with node placement.
625
+ """
626
+ def apply_init(impl, fun, args, opts) do
627
+ if node = opts[:node] do
628
+ Explorer.Remote.apply(node, impl, fun, [], fn _ -> args end, true)
629
+ else
630
+ apply(impl, fun, args)
631
+ end
632
+ end
633
+
634
+ @doc """
635
+ Applies a function with args using the implementation of a dataframe or series.
636
+ """
637
+ def apply_dataframe(dfs_or_df, fun, args \\ [], place? \\ true) do
638
+ {df_nodes, {impl, remote}} =
639
+ dfs_or_df
640
+ |> List.wrap()
641
+ |> Enum.map_reduce({nil, nil}, fn %{data: %impl{}} = df, {acc_impl, acc_remote} ->
642
+ {node, remote} = remote_info(df, impl)
643
+ {{df, node}, {pick_df_impl(acc_impl, impl), pick_remote(acc_remote, remote)}}
644
+ end)
645
+
646
+ if remote do
647
+ callback = if is_list(dfs_or_df), do: &[&1 | args], else: &[hd(&1) | args]
648
+ Explorer.Remote.apply(remote, impl, fun, df_nodes, callback, place?)
649
+ else
650
+ apply(impl, fun, [dfs_or_df | args])
651
+ end
652
+ end
653
+
654
+ defp pick_df_impl(nil, struct), do: struct
655
+ defp pick_df_impl(struct, struct), do: struct
656
+
657
+ defp pick_df_impl(struct1, struct2) do
658
+ raise "cannot invoke Explorer.DataFrame function because it relies on two incompatible implementations: " <>
659
+ "#{inspect(struct1)} and #{inspect(struct2)}"
660
+ end
661
+
662
+ @doc """
663
+ Applies a function to a series.
664
+ """
665
+ def apply_series(series, fun, args \\ [], place? \\ true) do
666
+ apply_series_impl!([series], fun, &(&1 ++ args), place?)
667
+ end
668
+
669
+ @doc """
670
+ Applies a function to a list of series.
671
+
672
+ The list is typically static and it is passed as arguments.
673
+ """
674
+ def apply_series_list(fun, series_or_scalars) when is_list(series_or_scalars) do
675
+ apply_series_impl!(series_or_scalars, fun, & &1, true)
676
+ end
677
+
678
+ @doc """
679
+ Applies a function to a list of unknown size of series.
680
+
681
+ The list is passed as a varargs to the backend.
682
+ """
683
+ def apply_series_varargs(fun, series_or_scalars) when is_list(series_or_scalars) do
684
+ apply_series_impl!(series_or_scalars, fun, &[&1], true)
685
+ end
686
+
687
+ defp apply_series_impl!([_ | _] = series_or_scalars, fun, args_callback, place?) do
688
+ {series_nodes, {impl, {_forced?, remote}, transfer?}} =
689
+ Enum.map_reduce(series_or_scalars, {nil, {false, nil}, false}, fn
690
+ # A lazy series without a resource is treated as a scalar
691
+ %{data: %{__struct__: Explorer.Backend.LazySeries, resource: nil}} = series,
692
+ {_acc_impl, acc_remote, acc_transfer?} ->
693
+ {{series, nil}, {Explorer.Backend.LazySeries, acc_remote, acc_transfer?}}
694
+
695
+ %{data: %impl{}} = series, {acc_impl, acc_remote, acc_transfer?} ->
696
+ {node, remote} = remote_info(series, impl)
697
+
698
+ {{series, node},
699
+ {pick_series_impl(acc_impl, impl), pick_series_remote(acc_remote, impl, remote),
700
+ acc_transfer? or remote != nil}}
701
+
702
+ scalar, acc ->
703
+ {{scalar, nil}, acc}
704
+ end)
705
+
706
+ if is_nil(impl) do
707
+ raise ArgumentError,
708
+ "expected a series as argument for #{fun}, got: #{inspect(series_or_scalars)}" <>
709
+ maybe_bad_column_hint(series_or_scalars)
710
+ end
711
+
712
+ if transfer? do
713
+ Explorer.Remote.apply(remote || node(), impl, fun, series_nodes, args_callback, place?)
714
+ else
715
+ apply(impl, fun, args_callback.(series_or_scalars))
716
+ end
717
+ end
718
+
719
+ # The lazy series always wins the remote if it has one,
720
+ # since we need to transfer it to the dataframe that started the lazy series.
721
+ defp pick_series_remote(_acc_remote, Explorer.Backend.LazySeries, remote),
722
+ do: {true, remote}
723
+
724
+ defp pick_series_remote({true, acc_remote}, _impl, _remote),
725
+ do: {true, acc_remote}
726
+
727
+ defp pick_series_remote({false, acc_remote}, _impl, remote),
728
+ do: {false, pick_remote(acc_remote, remote)}
729
+
730
+ defp pick_series_impl(nil, impl), do: impl
731
+ defp pick_series_impl(Explorer.Backend.LazySeries, _impl), do: Explorer.Backend.LazySeries
732
+ defp pick_series_impl(_impl, Explorer.Backend.LazySeries), do: Explorer.Backend.LazySeries
733
+ defp pick_series_impl(impl, impl), do: impl
734
+
735
+ defp pick_series_impl(acc_impl, impl) do
736
+ raise "cannot invoke Explorer function because it relies on two incompatible series: " <>
737
+ "#{inspect(acc_impl)} and #{inspect(impl)}"
738
+ end
739
+
740
+ @doc """
741
+ A hint in case there is a bad column from a query.
742
+ """
743
+ def maybe_bad_column_hint(values) do
744
+ atom = Enum.find(values, &is_atom(&1))
745
+
746
+ if Kernel.and(atom != nil, String.starts_with?(Atom.to_string(atom), "Elixir.")) do
747
+ "\n\nHINT: we have noticed that one of the values is the atom #{inspect(atom)}. " <>
748
+ "If you are inside Explorer.Query and you want to access a column starting in uppercase, " <>
749
+ "you must write instead: col(\"#{inspect(atom)}\")"
750
+ else
751
+ ""
752
+ end
753
+ end
754
+
755
+ # There is remote information and it is GCed by the current node.
756
+ # Which means that it resides on the remote node given by remote_pid.
757
+ defp remote_info(%{remote: {local_gc, remote_pid, _remote_ref}}, _impl)
758
+ when node(local_gc) == node(),
759
+ do: {node(remote_pid), remote_pid}
760
+
761
+ # There is remote information but it is actually local. Treat it as one.
762
+ defp remote_info(%{remote: {_local_gc, remote_pid, _remote_ref}}, _impl)
763
+ when node(remote_pid) == node(),
764
+ do: {node(), nil}
765
+
766
+ # We don't know the remote information, let's ask the backend
767
+ defp remote_info(df_or_series, impl) do
768
+ case impl.owner_reference(df_or_series) do
769
+ remote_ref when is_reference(remote_ref) and node(remote_ref) != node() ->
770
+ {node(remote_ref), node(remote_ref)}
771
+
772
+ _ ->
773
+ {node(), nil}
774
+ end
775
+ end
776
+
777
+ # We need to pick a remote, which one does not matter.
778
+ # The important is to keep the PID reference around, if there is one.
779
+ defp pick_remote(acc_remote, _remote) when is_pid(acc_remote), do: acc_remote
780
+ defp pick_remote(acc_remote, nil), do: acc_remote
781
+ defp pick_remote(_acc_remote, remote), do: remote
782
+ end
deps/explorer/lib/explorer/tensor_frame.ex ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ if Code.ensure_loaded?(Nx) do
2
+ alias Explorer.Series, as: S, warn: false
3
+ alias Explorer.DataFrame, as: DF, warn: false
4
+ alias Explorer.TensorFrame, as: TF, warn: false
5
+
6
+ defmodule Explorer.TensorFrame do
7
+ @moduledoc """
8
+ TensorFrame is a representation of `Explorer.DataFrame`
9
+ that is designed to work inside Nx's `defn` expressions.
10
+
11
+ For example, imagine the following `defn`:
12
+
13
+ defn add_columns(tf) do
14
+ tf[:a] + tf[:b]
15
+ end
16
+
17
+ We can now pass a DataFrame as argument:
18
+
19
+ iex> add_columns(Explorer.DataFrame.new(a: [11, 12], b: [21, 22]))
20
+ #Nx.Tensor<
21
+ s64[2]
22
+ [32, 34]
23
+ >
24
+
25
+ Passing an `Explorer.DataFrame` to a `defn` will automatically
26
+ convert it to a TensorFrame. The TensorFrame will lazily
27
+ build tensors out of the used dataframe fields.
28
+
29
+ ## Stack and concatenating
30
+
31
+ Due to the integration with Nx, you can also pass dataframes
32
+ into `Nx.stack/2` and `Nx.concatenate` and they will be automatically
33
+ converted to tensors. This makes it easy to pass dataframes into
34
+ neural networks and other computationally intensive algorithms:
35
+
36
+ iex> Nx.concatenate(Explorer.DataFrame.new(a: [11, 12], b: [21, 22]))
37
+ #Nx.Tensor<
38
+ s64[4]
39
+ [11, 12, 21, 22]
40
+ >
41
+
42
+ iex> Nx.stack(Explorer.DataFrame.new(a: [11, 12], b: [21, 22]))
43
+ #Nx.Tensor<
44
+ s64[2][2]
45
+ [
46
+ [11, 12],
47
+ [21, 22]
48
+ ]
49
+ >
50
+
51
+ iex> Nx.stack(Explorer.DataFrame.new(a: [11, 12], b: [21, 22]), axis: -1)
52
+ #Nx.Tensor<
53
+ s64[2][2]
54
+ [
55
+ [11, 21],
56
+ [12, 22]
57
+ ]
58
+ >
59
+
60
+ ## Warning: returning TensorFrames
61
+
62
+ It is not recommended to return a TensorFrame from a `defn`,
63
+ as that would force all columns to be sent to the CPU/GPU
64
+ and then copied back. Return only the columns that have been
65
+ modified during the computation. For example, in the example
66
+ above we used `Nx` to add two columns, if you want to
67
+ put the result of the computation back into a DataFrame,
68
+ you can use `Explorer.DataFrame.put/4`, which also accepts
69
+ tensors:
70
+
71
+ iex> df = Explorer.DataFrame.new(a: [11, 12], b: [21, 22])
72
+ iex> Explorer.DataFrame.put(df, "result", add_columns(df))
73
+ #Explorer.DataFrame<
74
+ Polars[2 x 3]
75
+ a s64 [11, 12]
76
+ b s64 [21, 22]
77
+ result s64 [32, 34]
78
+ >
79
+
80
+ One benefit of using `Explorer.DataFrame.put/4` is that it will
81
+ preserve the type of the column if one already exists. Alternatively,
82
+ use `Explorer.Series.from_tensor/1` to explicitly convert a tensor
83
+ back to a series.
84
+
85
+ ## Supported dtypes
86
+
87
+ The following dtypes can be converted to tensors:
88
+
89
+ * `:integer`
90
+ * `{:f, 32}`
91
+ * `{:f, 64}`
92
+ * `:boolean`
93
+ * `:date`
94
+ * `{:naive_datetime, :millisecond}`
95
+ * `{:naive_datetime, :microsecond}`
96
+ * `{:naive_datetime, :nanosecond}`
97
+
98
+ See `Explorer.Series.to_iovec/1` and `Explorer.Series.to_tensor/1`
99
+ to learn more about their internal representation.
100
+ """
101
+
102
+ @enforce_keys [:data, :names, :n_rows]
103
+ defstruct [:data, :names, :n_rows]
104
+ @type t :: %__MODULE__{}
105
+ @compile {:no_warn_undefined, Nx}
106
+
107
+ ## Nx
108
+
109
+ import Nx.Defn
110
+
111
+ @doc """
112
+ Pulls a tensor from the TensorFrame.
113
+
114
+ This is equivalent to using the `tf[name]` to access
115
+ a tensor.
116
+
117
+ ## Examples
118
+
119
+ Explorer.TensorFrame.pull(tf, "some_column")
120
+
121
+ """
122
+ deftransform pull(%TF{} = tf, name) do
123
+ fetch!(tf, to_column_name(name))
124
+ end
125
+
126
+ @doc """
127
+ Puts a tensor in the TensorFrame.
128
+
129
+ This function can be invoked from within `defn`.
130
+
131
+ ## Examples
132
+
133
+ Explorer.TensorFrame.put(tf, "result", some_tensor)
134
+
135
+ """
136
+ deftransform put(%TF{} = tf, name, tensor) do
137
+ put!(tf, to_column_name(name), tensor)
138
+ end
139
+
140
+ ## Access
141
+
142
+ @behaviour Access
143
+
144
+ @impl Access
145
+ def fetch(tf, name) do
146
+ {:ok, fetch!(tf, to_column_name(name))}
147
+ end
148
+
149
+ @impl Access
150
+ def get_and_update(tf, name, callback) do
151
+ name = to_column_name(name)
152
+ {get, update} = callback.(fetch!(tf, name))
153
+ {get, put!(tf, name, update)}
154
+ end
155
+
156
+ @impl Access
157
+ def pop(%TF{data: data, names: names} = tf, name) do
158
+ name = to_column_name(name)
159
+
160
+ {fetch!(tf, name), %{tf | data: Map.delete(data, name), names: names -- [name]}}
161
+ end
162
+
163
+ defp fetch!(%TF{data: data}, name) when is_binary(name) do
164
+ case data do
165
+ %{^name => data} ->
166
+ data
167
+
168
+ %{} ->
169
+ raise ArgumentError,
170
+ List.to_string([
171
+ "could not find column \"#{name}\" either because it doesn't exist or its dtype is not supported in Explorer.TensorFrame"
172
+ | Explorer.Shared.did_you_mean(name, Map.keys(data))
173
+ ])
174
+ end
175
+ end
176
+
177
+ ## Helpers
178
+
179
+ defp to_column_name(name) when is_atom(name), do: Atom.to_string(name)
180
+ defp to_column_name(name) when is_binary(name), do: name
181
+
182
+ defp to_column_name(name) do
183
+ raise ArgumentError,
184
+ "Explorer.TensorFrame only accepts atoms and strings as column names, got: #{inspect(name)}"
185
+ end
186
+
187
+ defp put!(%{n_rows: n_rows, names: names, data: data} = tf, name, value)
188
+ when is_binary(name) do
189
+ names = if name in names, do: names, else: names ++ [name]
190
+ data = Map.put(data, name, value |> Nx.to_tensor() |> broadcast!(n_rows))
191
+ %{tf | names: names, data: data}
192
+ end
193
+
194
+ defp broadcast!(%{shape: {}} = tensor, n_rows), do: Nx.broadcast(tensor, {n_rows})
195
+ defp broadcast!(%{shape: {1}} = tensor, n_rows), do: Nx.broadcast(tensor, {n_rows})
196
+ defp broadcast!(%{shape: {n_rows}} = tensor, n_rows), do: tensor
197
+
198
+ defp broadcast!(tensor, n_rows) do
199
+ raise ArgumentError,
200
+ "cannot add tensor that does not match the frame size. " <>
201
+ "Expected a tensor of shape {#{n_rows}} but got tensor #{inspect(tensor)}"
202
+ end
203
+
204
+ defimpl Inspect do
205
+ import Inspect.Algebra
206
+
207
+ def inspect(tf, opts) do
208
+ force_unfit(
209
+ concat([
210
+ color("#Explorer.TensorFrame<", :map, opts),
211
+ nest(concat([line(), inner(tf, opts)]), 2),
212
+ line(),
213
+ color(">", :map, opts)
214
+ ])
215
+ )
216
+ end
217
+
218
+ @default_limit 5
219
+
220
+ defp inner(%{data: data, n_rows: n_rows}, opts) do
221
+ opts = %{opts | limit: @default_limit}
222
+ open = color("[", :list, opts)
223
+ close = color("]", :list, opts)
224
+
225
+ pairs =
226
+ for {name, tensor} <- Enum.sort(data) do
227
+ concat([
228
+ line(),
229
+ color("#{name} ", :map, opts),
230
+ Inspect.Algebra.to_doc(tensor, opts)
231
+ ])
232
+ end
233
+
234
+ concat([open, "#{n_rows} x #{map_size(data)}", close | pairs])
235
+ end
236
+ end
237
+ end
238
+
239
+ defimpl Nx.LazyContainer, for: S do
240
+ def traverse(series, acc, fun) do
241
+ size = S.size(series)
242
+ template = Nx.template({size}, S.iotype(series))
243
+ fun.(template, fn -> S.to_tensor(series) end, acc)
244
+ end
245
+ end
246
+
247
+ defimpl Nx.LazyContainer, for: DF do
248
+ def traverse(df, acc, fun) do
249
+ n_rows = DF.n_rows(df)
250
+
251
+ {data, acc} =
252
+ Enum.flat_map_reduce(DF.names(df), acc, fn name, acc ->
253
+ series = df[name]
254
+
255
+ case S.iotype(series) do
256
+ {_, _} = type ->
257
+ template = Nx.template({n_rows}, type)
258
+ {result, acc} = fun.(template, fn -> S.to_tensor(series) end, acc)
259
+ {[{name, result}], acc}
260
+
261
+ :none ->
262
+ {[], acc}
263
+ end
264
+ end)
265
+
266
+ {%TF{data: Map.new(data), names: Enum.map(data, &elem(&1, 0)), n_rows: n_rows}, acc}
267
+ end
268
+ end
269
+
270
+ defimpl Nx.Container, for: TF do
271
+ def traverse(tf, acc, fun) do
272
+ {data, acc} =
273
+ Enum.map_reduce(tf.names, acc, fn name, acc ->
274
+ {contents, acc} = fun.(tf[name], acc)
275
+ {{name, contents}, acc}
276
+ end)
277
+
278
+ {%{tf | data: Map.new(data)}, acc}
279
+ end
280
+
281
+ def reduce(tf, acc, fun) do
282
+ Enum.reduce(tf.names, acc, fn name, acc ->
283
+ fun.(tf[name], acc)
284
+ end)
285
+ end
286
+
287
+ def serialize(%TF{data: data, names: names, n_rows: n_rows}) do
288
+ {__MODULE__, Map.to_list(data), {names, n_rows}}
289
+ end
290
+
291
+ def deserialize(data, {names, n_rows}) do
292
+ %TF{data: Map.new(data), names: names, n_rows: n_rows}
293
+ end
294
+ end
295
+ end
deps/explorer/mix.exs ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defmodule Explorer.MixProject do
2
+ use Mix.Project
3
+
4
+ @source_url "https://github.com/elixir-nx/explorer"
5
+ @version "0.10.1"
6
+ @dev? String.ends_with?(@version, "-dev")
7
+ @force_build? System.get_env("EXPLORER_BUILD") in ["1", "true"]
8
+
9
+ def project do
10
+ [
11
+ app: :explorer,
12
+ name: "Explorer",
13
+ description:
14
+ "Series (one-dimensional) and dataframes (two-dimensional) for fast data exploration in Elixir",
15
+ version: @version,
16
+ elixir: "~> 1.14",
17
+ elixirc_paths: elixirc_paths(Mix.env()),
18
+ package: package(),
19
+ deps: deps(),
20
+ docs: docs(),
21
+ preferred_cli_env: [ci: :test, "localstack.setup": :test],
22
+ aliases: [
23
+ "rust.lint": ["cmd cargo clippy --manifest-path=native/explorer/Cargo.toml -- -Dwarnings"],
24
+ "rust.fmt": ["cmd cargo fmt --manifest-path=native/explorer/Cargo.toml --all"],
25
+ "localstack.setup": ["cmd ./test/support/setup-localstack.sh"],
26
+ ci: ["format", "rust.fmt", "rust.lint", "test"]
27
+ ]
28
+ ]
29
+ end
30
+
31
+ def application do
32
+ [
33
+ extra_applications: [:logger, :inets, :ssl],
34
+ mod: {Explorer.Application, []},
35
+ env: [default_backend: Explorer.PolarsBackend]
36
+ ]
37
+ end
38
+
39
+ defp elixirc_paths(:test), do: ~w(lib test/support)
40
+ defp elixirc_paths(_), do: ~w(lib)
41
+
42
+ defp deps do
43
+ [
44
+ {:aws_signature, "~> 0.3"},
45
+ {:fss, "~> 0.1"},
46
+ {:rustler_precompiled, "~> 0.7"},
47
+ {:table, "~> 0.1.2"},
48
+ {:table_rex, "~> 3.1.1 or ~> 4.0.0"},
49
+ {:decimal, "~> 2.1"},
50
+
51
+ ## Optional
52
+ {:flame, "~> 0.3", optional: true},
53
+ {:castore, "~> 1.0", optional: true},
54
+ {:adbc, "~> 0.1", optional: true},
55
+ {:nx, "~> 0.4", optional: true},
56
+ {:rustler, "~> 0.34.0", optional: not (@dev? or @force_build?)},
57
+
58
+ ## Test
59
+ {:bypass, "~> 2.1", only: :test},
60
+ {:stream_data, "~> 1.1", only: :test},
61
+ {:tz, "~> 0.26", only: :test},
62
+
63
+ ## Dev
64
+ {:ex_doc, "~> 0.24", only: :dev},
65
+ {:benchee, "~> 1.1", only: :dev}
66
+ ]
67
+ end
68
+
69
+ defp docs do
70
+ [
71
+ main: "Explorer",
72
+ logo: "explorer-exdoc.png",
73
+ source_ref: "v#{@version}",
74
+ source_url: @source_url,
75
+ groups_for_modules: [
76
+ # Explorer,
77
+ # Explorer.DataFrame,
78
+ # Explorer.Datasets,
79
+ # Explorer.Query,
80
+ # Explorer.Series,
81
+ "Custom data types": [
82
+ Explorer.Duration,
83
+ Explorer.TensorFrame
84
+ ],
85
+ Backends: [
86
+ Explorer.Backend,
87
+ Explorer.Backend.DataFrame,
88
+ Explorer.Backend.Series,
89
+ Explorer.Backend.QueryFrame,
90
+ Explorer.Backend.LazySeries,
91
+ Explorer.PolarsBackend
92
+ ]
93
+ ],
94
+ groups_for_docs: [
95
+ "Functions: Conversion": &(&1[:type] == :conversion),
96
+ "Functions: Single-table": &(&1[:type] == :single),
97
+ "Functions: Multi-table": &(&1[:type] == :multi),
98
+ "Functions: Row-based": &(&1[:type] == :rows),
99
+ "Functions: Aggregation": &(&1[:type] == :aggregation),
100
+ "Functions: Element-wise": &(&1[:type] == :element_wise),
101
+ "Functions: Datetime ops": &(&1[:type] == :datetime_wise),
102
+ "Functions: Float ops": &(&1[:type] == :float_wise),
103
+ "Functions: String ops": &(&1[:type] == :string_wise),
104
+ "Functions: List ops": &(&1[:type] == :list_wise),
105
+ "Functions: Struct ops": &(&1[:type] == :struct_wise),
106
+ "Functions: Introspection": &(&1[:type] == :introspection),
107
+ "Functions: IO": &(&1[:type] == :io),
108
+ "Functions: Shape": &(&1[:type] == :shape),
109
+ "Functions: Window": &(&1[:type] == :window)
110
+ ],
111
+ extras: ["notebooks/exploring_explorer.livemd", "CHANGELOG.md"],
112
+ skip_undefined_reference_warnings_on: ["CHANGELOG.md"]
113
+ ]
114
+ end
115
+
116
+ defp package do
117
+ [
118
+ files: [
119
+ "lib",
120
+ "native",
121
+ "datasets",
122
+ "checksum-*.exs",
123
+ "mix.exs",
124
+ "CHANGELOG.md",
125
+ "README.md",
126
+ "LICENSE"
127
+ ],
128
+ licenses: ["MIT"],
129
+ links: %{
130
+ "GitHub" => @source_url,
131
+ "Changelog" => "#{@source_url}/blob/v#{@version}/CHANGELOG.md"
132
+ },
133
+ maintainers: ["Christopher Grainger", "Philip Sampaio", "José Valim"]
134
+ ]
135
+ end
136
+ end