s42chen commited on
Commit
ced448b
·
verified ·
1 Parent(s): 17e199a

Publish 11 evaluated Astra histories with reproducible checkpoint artifacts (part 5)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +12 -0
  2. shared/package-files/06/0696e309979cee7fae3a3fdc226bbe701d629950b8a1e2fcac95308f16e63787/blob +488 -0
  3. shared/package-files/06/069723f7ea5e8585b6d2f9f8298f7ca400d07790348330d4b94936cb8f07cf23/blob +139 -0
  4. shared/package-files/06/069ad718312002b3c0a162ef04ff183de7efe6fbca3f338dcc1d5b4ab467cda1/blob +133 -0
  5. shared/package-files/06/069d4ee48ec2edb74e10982f4c730a0d8d39bd5c9f7d2cc97ff5322a179999ea/blob +39 -0
  6. shared/package-files/06/069d8f07866ea9e33218850c0e8d5d0a08397899e08d6983aae65c6e82e582fa/blob +472 -0
  7. shared/package-files/06/069eba747d07d88ba42cb4af2f869c43673a8d5510704abea38dddb7eb689976/blob +0 -0
  8. shared/package-files/06/069ed4c1f7c830eee873c527155d75c9819c5d48d26b4361b2e3a041a35132df/blob +441 -0
  9. shared/package-files/06/069f0d6d4cdf0f03e40bf33b01cac2fc3413cce89a528caef3f9c75f4a22ea76/blob +97 -0
  10. shared/package-files/06/069ffbf6861f5711899f998744be7a77b7e156d3899cda37f05548160b640ccf/energy_views.py +15 -0
  11. shared/package-files/06/06a0d61aa47624e544ab2f31ae6c858f4ef591cf8fba38a5695276edb13d3ecb/blob +0 -0
  12. shared/package-files/06/06a1fa254fd8466f82510151513bd68696779988974e6617aaa6992a5a5379bb/blob +23 -0
  13. shared/package-files/06/06a3179ec5e260fa1a94ccc46a49fa9980f18325b937650f174028ef13ee1956/blob +1 -0
  14. shared/package-files/06/06a420d1fa970ff4e600124f4960c2f87d9acedec1e7735f384d520ba99b5e22/blob +1139 -0
  15. shared/package-files/06/06a5c5ca12950e815126549205bfe3c4e9163f333632943aec12a2411f39d80f/blob +788 -0
  16. shared/package-files/06/06a76dad17702ab297ea355df38eb0d44f9707ac4a0e8d0e73291ee6aa4ab3af/blob +21 -0
  17. shared/package-files/06/06afee4a9a5e3b6753f3cc5af979dc409fe959763cb7dedb2c632bc8c21a8bc4/blob +960 -0
  18. shared/package-files/06/06b040956a82a017f58a62be3255645dd5d545658338157d2730bc543b8aa64a/blob +23 -0
  19. shared/package-files/06/06b381caddd5de9c6cedd3e0e350791f7b89745b22a86f514ef65e88772e12aa/blob +23 -0
  20. shared/package-files/06/06b39b66efb6f772121ab44293451f5d2f1ce5b7ce8c198808f967c889db9977/blob +442 -0
  21. shared/package-files/06/06b5f7f9a40b0fd5b5d6dd56f1fd12968d9935b46500a93b66808e44bf349ea6/blob +0 -0
  22. shared/package-files/06/06b83b8b3586648dc1ad136c0ed25301883cc7e7d7f03b3286981416a15b3057/blob +39 -0
  23. shared/package-files/06/06b881b824f71e95d72af4ab865de4c35553e791b6d959a125caac61401cc350/blob +442 -0
  24. shared/package-files/06/06b8b7396bb8964915e9818b68b518b5d03de58f1e84ae4ca1b313843a024edd/blob +62 -0
  25. shared/package-files/06/06bcfff317bfc97d78441e81f29564e8169c33a1e2cea914088439bdcf54fbf2/blob +51 -0
  26. shared/package-files/06/06bd03cb0ab219a5701da59b81b21664b9d0610ed2a5ad38678794f13ac7cfef/blob +309 -0
  27. shared/package-files/06/06befcb259155c51e608af2dade2b9489b0fa76c41343c193b5e073f142b203e/blob +36 -0
  28. shared/package-files/06/06bf5768b6f7ada260d4f4009d5e66799ddfb647e56d702c17a66d0cd7ce88cb/blob +50 -0
  29. shared/package-files/06/06c51c6abfc2d276733c657669c92b27d0a9554f3fd16fe91d82b0a5d9d675d3/blob +1 -0
  30. shared/package-files/06/06c640bb2cf3469d4affb4fc801035db3b053729306a5faa542e9a35104932ed/blob +23 -0
  31. shared/package-files/06/06c8ab6557752e63d64f8b41233ea5a193e365c227a10ac819f0bbaefcea989c/blob +3 -0
  32. shared/package-files/06/06cbdf88bccd27374d0fe0b31052b363769d1faaa425d3910e6ec2d9968b9433/blob +61 -0
  33. shared/package-files/06/06cc5816adde64223c0fedf112013d1636febbe83b34f8cd89d6e0155737380c/blob +0 -0
  34. shared/package-files/06/06cdac7a4743272c3fc2b5291bbbd94061f4cb44b80b801bc464a9794ffc0b6b/blob +184 -0
  35. shared/package-files/06/06ce13e038f1e1764e6ddd251af78123ab55b15bcf19ebf9476dc6b1a8a8768b/blob +372 -0
  36. shared/package-files/06/06d043d88fb3f0ae88e46420f5080735f8995747a72a2e483128b14fee094525/blob +237 -0
  37. shared/package-files/06/06d090ae1a5cf3f42e004c937acfa25d9bcd1830a4e0c7218eaf4e0ee7a40025/blob +39 -0
  38. shared/package-files/06/06d0d1944c1296f3a1c68d38997407a73cada15f8523f2b9c95b344405fc7812/blob +1603 -0
  39. shared/package-files/06/06d3b49e34f00c5ad736bde730aabfa7c3c384fcc7f517f30ab9cb909c73e5fc/blob +364 -0
  40. shared/package-files/06/06d495c7e6c9b6c8ada94a07c3e31a624c551d6fad4e2051f9728d29aeb1bb1c/score_glacier_predictions_serial.py +318 -0
  41. shared/package-files/06/06d5a05ca7ad5be95f0bdccef3be5c8990d91c7cd8407c5c8d5079664130493a/blob +0 -0
  42. shared/package-files/06/06d81abe6df0ddcf6677fe7215faba55ea3fe482bd2ad94b1752443de1e16685/blob +0 -0
  43. shared/package-files/06/06dd7572626df5cb0a8d3affbac9bb74cb12469076836d66fd19ae5b5fab42c7/blob +91 -0
  44. shared/package-files/06/06e073b6b3d045ab149956615ebdbf36026e8dd513361370779f696591e4de50/blob +77 -0
  45. shared/package-files/06/06e09e6fc73ad2e0c7a626e83a4281976baedd3f84121ad841cb5ea2a23186a4/blob +6 -0
  46. shared/package-files/06/06e1e22eec6eeae11f64568f256dd13e93dac5a55cb44400de47522520cbd61c/blob +9 -0
  47. shared/package-files/06/06e2998258a8a448014c373041a91ca92f11ae7ed3cfbafe012ea3c45085f5c2/blob +0 -0
  48. shared/package-files/06/06e2ecaf4175380e08780f35e81cee2c5892346a693e800ba62795dbff0d7e0f/blob +303 -0
  49. shared/package-files/06/06e4113c5d11f4cadb2f31b2338e39475c67e2f79bdca96cd05181611f54afda/blob +22 -0
  50. shared/package-files/06/06e5736b4eef85a7e4abaf15abd8328a482b85c39d0fac6eacfc0f1eaaa8a041/blob +0 -0
.gitattributes CHANGED
@@ -84,3 +84,15 @@ shared/package-files/05/05464db9f29f3e3c72bda50625b2c3ae15931b2a75dfea352a08400d
84
  shared/package-files/05/055a8c8de66579d344ffd20ea68aa6926728f85942aaee502878b5ba3f4cbb88/blob filter=lfs diff=lfs merge=lfs -text
85
  shared/package-files/06/061ac28d1ae2fb1380babbd59c7f2ff9acf3f2a4d6c421590a31edeb3ae6f679/blob filter=lfs diff=lfs merge=lfs -text
86
  shared/package-files/06/0624808a363bd60dbec9c75b37431bbe55a5dfa4f497997723ac26b16d271099/blob filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  shared/package-files/05/055a8c8de66579d344ffd20ea68aa6926728f85942aaee502878b5ba3f4cbb88/blob filter=lfs diff=lfs merge=lfs -text
85
  shared/package-files/06/061ac28d1ae2fb1380babbd59c7f2ff9acf3f2a4d6c421590a31edeb3ae6f679/blob filter=lfs diff=lfs merge=lfs -text
86
  shared/package-files/06/0624808a363bd60dbec9c75b37431bbe55a5dfa4f497997723ac26b16d271099/blob filter=lfs diff=lfs merge=lfs -text
87
+ shared/package-files/06/06fe4495c90199b465e598eff59efdbb7760c4c763e344e5897e5ca6649767c9/blob filter=lfs diff=lfs merge=lfs -text
88
+ shared/package-files/07/070b788db511a6bbd5c3e5d7c4b97acef54977179bb07a61663c6e617a2e4f66/blob filter=lfs diff=lfs merge=lfs -text
89
+ shared/package-files/07/074ce037474f72e2fc9945195ed4c16fb5461760294fcf879724257094ee1810/blob filter=lfs diff=lfs merge=lfs -text
90
+ shared/package-files/07/079c3711962ff08177d6851af6de157d6353461185f7aef7227d5ee8272b5b16/blob filter=lfs diff=lfs merge=lfs -text
91
+ shared/package-files/07/079d8be918d4e69bd3effa36026a1e5764ebd6e3c99a197e03abc63ba609cbc2/blob filter=lfs diff=lfs merge=lfs -text
92
+ shared/package-files/07/07a60a6bf5b0ae455f4d4cb1df5be25ded300842e428a03bb690ab5a0567c013/blob filter=lfs diff=lfs merge=lfs -text
93
+ shared/package-files/07/07ebc7c52f195f037ed4dff87b34ba7779a311e0b94f593ab95f7e8e61109970/blob filter=lfs diff=lfs merge=lfs -text
94
+ shared/package-files/07/07ec62e718c772cda488c50484de7e6b005ffe671567dbe6421685e6874be75d/blob filter=lfs diff=lfs merge=lfs -text
95
+ shared/package-files/07/07f3689f83d0063c0d5630a7052ce390b0612fb91289362ac43974717ad2dce0/blob filter=lfs diff=lfs merge=lfs -text
96
+ shared/package-files/08/083868ebd616dc54ed63229d0c12ba65d11c41834f02554895a5f3750e67712c/blob filter=lfs diff=lfs merge=lfs -text
97
+ shared/package-files/08/08718ad705a9b35495054ffa65e35ac29445fe5ef610620778964a4413901d10/blob filter=lfs diff=lfs merge=lfs -text
98
+ shared/package-files/09/0939533feac811be371ac5aec67815b9c6fccb0c08cf86886c1b86962511fd82/blob filter=lfs diff=lfs merge=lfs -text
shared/package-files/06/0696e309979cee7fae3a3fdc226bbe701d629950b8a1e2fcac95308f16e63787/blob ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .artist import Artist
2
+ from .axes import Axes
3
+ from .backend_bases import FigureCanvasBase, Event, MouseEvent, MouseButton
4
+ from .collections import LineCollection
5
+ from .figure import Figure
6
+ from .lines import Line2D
7
+ from .patches import Polygon, Rectangle
8
+ from .text import Text
9
+
10
+ import PIL.Image
11
+
12
+ from collections.abc import Callable, Collection, Iterable, Sequence
13
+ from typing import Any, Literal
14
+ from numpy.typing import ArrayLike
15
+ from .typing import ColorType
16
+ import numpy as np
17
+
18
+ class LockDraw:
19
+ def __init__(self) -> None: ...
20
+ def __call__(self, o: Any) -> None: ...
21
+ def release(self, o: Any) -> None: ...
22
+ def available(self, o: Any) -> bool: ...
23
+ def isowner(self, o: Any) -> bool: ...
24
+ def locked(self) -> bool: ...
25
+
26
+ class Widget:
27
+ drawon: bool
28
+ eventson: bool
29
+ active: bool
30
+ def set_active(self, active: bool) -> None: ...
31
+ def get_active(self) -> None: ...
32
+ def ignore(self, event) -> bool: ...
33
+
34
+ class AxesWidget(Widget):
35
+ ax: Axes
36
+ def __init__(self, ax: Axes) -> None: ...
37
+ @property
38
+ def canvas(self) -> FigureCanvasBase | None: ...
39
+ def connect_event(self, event: Event, callback: Callable) -> None: ...
40
+ def disconnect_events(self) -> None: ...
41
+
42
+ class Button(AxesWidget):
43
+ label: Text
44
+ color: ColorType
45
+ hovercolor: ColorType
46
+ def __init__(
47
+ self,
48
+ ax: Axes,
49
+ label: str,
50
+ image: ArrayLike | PIL.Image.Image | None = ...,
51
+ color: ColorType = ...,
52
+ hovercolor: ColorType = ...,
53
+ *,
54
+ useblit: bool = ...
55
+ ) -> None: ...
56
+ def on_clicked(self, func: Callable[[Event], Any]) -> int: ...
57
+ def disconnect(self, cid: int) -> None: ...
58
+
59
+ class SliderBase(AxesWidget):
60
+ orientation: Literal["horizontal", "vertical"]
61
+ closedmin: bool
62
+ closedmax: bool
63
+ valmin: float
64
+ valmax: float
65
+ valstep: float | ArrayLike | None
66
+ drag_active: bool
67
+ valfmt: str
68
+ def __init__(
69
+ self,
70
+ ax: Axes,
71
+ orientation: Literal["horizontal", "vertical"],
72
+ closedmin: bool,
73
+ closedmax: bool,
74
+ valmin: float,
75
+ valmax: float,
76
+ valfmt: str,
77
+ dragging: Slider | None,
78
+ valstep: float | ArrayLike | None,
79
+ ) -> None: ...
80
+ def disconnect(self, cid: int) -> None: ...
81
+ def reset(self) -> None: ...
82
+
83
+ class Slider(SliderBase):
84
+ slidermin: Slider | None
85
+ slidermax: Slider | None
86
+ val: float
87
+ valinit: float
88
+ track: Rectangle
89
+ poly: Polygon
90
+ hline: Line2D
91
+ vline: Line2D
92
+ label: Text
93
+ valtext: Text
94
+ def __init__(
95
+ self,
96
+ ax: Axes,
97
+ label: str,
98
+ valmin: float,
99
+ valmax: float,
100
+ *,
101
+ valinit: float = ...,
102
+ valfmt: str | None = ...,
103
+ closedmin: bool = ...,
104
+ closedmax: bool = ...,
105
+ slidermin: Slider | None = ...,
106
+ slidermax: Slider | None = ...,
107
+ dragging: bool = ...,
108
+ valstep: float | ArrayLike | None = ...,
109
+ orientation: Literal["horizontal", "vertical"] = ...,
110
+ initcolor: ColorType = ...,
111
+ track_color: ColorType = ...,
112
+ handle_style: dict[str, Any] | None = ...,
113
+ **kwargs
114
+ ) -> None: ...
115
+ def set_val(self, val: float) -> None: ...
116
+ def on_changed(self, func: Callable[[float], Any]) -> int: ...
117
+
118
+ class RangeSlider(SliderBase):
119
+ val: tuple[float, float]
120
+ valinit: tuple[float, float]
121
+ track: Rectangle
122
+ poly: Polygon
123
+ label: Text
124
+ valtext: Text
125
+ def __init__(
126
+ self,
127
+ ax: Axes,
128
+ label: str,
129
+ valmin: float,
130
+ valmax: float,
131
+ *,
132
+ valinit: tuple[float, float] | None = ...,
133
+ valfmt: str | None = ...,
134
+ closedmin: bool = ...,
135
+ closedmax: bool = ...,
136
+ dragging: bool = ...,
137
+ valstep: float | ArrayLike | None = ...,
138
+ orientation: Literal["horizontal", "vertical"] = ...,
139
+ track_color: ColorType = ...,
140
+ handle_style: dict[str, Any] | None = ...,
141
+ **kwargs
142
+ ) -> None: ...
143
+ def set_min(self, min: float) -> None: ...
144
+ def set_max(self, max: float) -> None: ...
145
+ def set_val(self, val: ArrayLike) -> None: ...
146
+ def on_changed(self, func: Callable[[tuple[float, float]], Any]) -> int: ...
147
+
148
+ class CheckButtons(AxesWidget):
149
+ labels: list[Text]
150
+ def __init__(
151
+ self,
152
+ ax: Axes,
153
+ labels: Sequence[str],
154
+ actives: Iterable[bool] | None = ...,
155
+ *,
156
+ useblit: bool = ...,
157
+ label_props: dict[str, Sequence[Any]] | None = ...,
158
+ frame_props: dict[str, Any] | None = ...,
159
+ check_props: dict[str, Any] | None = ...,
160
+ ) -> None: ...
161
+ def set_label_props(self, props: dict[str, Sequence[Any]]) -> None: ...
162
+ def set_frame_props(self, props: dict[str, Any]) -> None: ...
163
+ def set_check_props(self, props: dict[str, Any]) -> None: ...
164
+ def set_active(self, index: int, state: bool | None = ...) -> None: ... # type: ignore[override]
165
+ def clear(self) -> None: ...
166
+ def get_status(self) -> list[bool]: ...
167
+ def get_checked_labels(self) -> list[str]: ...
168
+ def on_clicked(self, func: Callable[[str | None], Any]) -> int: ...
169
+ def disconnect(self, cid: int) -> None: ...
170
+
171
+ class TextBox(AxesWidget):
172
+ label: Text
173
+ text_disp: Text
174
+ cursor_index: int
175
+ cursor: LineCollection
176
+ color: ColorType
177
+ hovercolor: ColorType
178
+ capturekeystrokes: bool
179
+ def __init__(
180
+ self,
181
+ ax: Axes,
182
+ label: str,
183
+ initial: str = ...,
184
+ *,
185
+ color: ColorType = ...,
186
+ hovercolor: ColorType = ...,
187
+ label_pad: float = ...,
188
+ textalignment: Literal["left", "center", "right"] = ...,
189
+ ) -> None: ...
190
+ @property
191
+ def text(self) -> str: ...
192
+ def set_val(self, val: str) -> None: ...
193
+ def begin_typing(self) -> None: ...
194
+ def stop_typing(self) -> None: ...
195
+ def on_text_change(self, func: Callable[[str], Any]) -> int: ...
196
+ def on_submit(self, func: Callable[[str], Any]) -> int: ...
197
+ def disconnect(self, cid: int) -> None: ...
198
+
199
+ class RadioButtons(AxesWidget):
200
+ activecolor: ColorType
201
+ value_selected: str
202
+ labels: list[Text]
203
+ def __init__(
204
+ self,
205
+ ax: Axes,
206
+ labels: Iterable[str],
207
+ active: int = ...,
208
+ activecolor: ColorType | None = ...,
209
+ *,
210
+ useblit: bool = ...,
211
+ label_props: dict[str, Sequence[Any]] | None = ...,
212
+ radio_props: dict[str, Any] | None = ...,
213
+ ) -> None: ...
214
+ def set_label_props(self, props: dict[str, Sequence[Any]]) -> None: ...
215
+ def set_radio_props(self, props: dict[str, Any]) -> None: ...
216
+ def set_active(self, index: int) -> None: ...
217
+ def clear(self) -> None: ...
218
+ def on_clicked(self, func: Callable[[str | None], Any]) -> int: ...
219
+ def disconnect(self, cid: int) -> None: ...
220
+
221
+ class SubplotTool(Widget):
222
+ figure: Figure
223
+ targetfig: Figure
224
+ buttonreset: Button
225
+ def __init__(self, targetfig: Figure, toolfig: Figure) -> None: ...
226
+
227
+ class Cursor(AxesWidget):
228
+ visible: bool
229
+ horizOn: bool
230
+ vertOn: bool
231
+ useblit: bool
232
+ lineh: Line2D
233
+ linev: Line2D
234
+ background: Any
235
+ needclear: bool
236
+ def __init__(
237
+ self,
238
+ ax: Axes,
239
+ *,
240
+ horizOn: bool = ...,
241
+ vertOn: bool = ...,
242
+ useblit: bool = ...,
243
+ **lineprops
244
+ ) -> None: ...
245
+ def clear(self, event: Event) -> None: ...
246
+ def onmove(self, event: Event) -> None: ...
247
+
248
+ class MultiCursor(Widget):
249
+ axes: Sequence[Axes]
250
+ horizOn: bool
251
+ vertOn: bool
252
+ visible: bool
253
+ useblit: bool
254
+ vlines: list[Line2D]
255
+ hlines: list[Line2D]
256
+ def __init__(
257
+ self,
258
+ canvas: Any,
259
+ axes: Sequence[Axes],
260
+ *,
261
+ useblit: bool = ...,
262
+ horizOn: bool = ...,
263
+ vertOn: bool = ...,
264
+ **lineprops
265
+ ) -> None: ...
266
+ def connect(self) -> None: ...
267
+ def disconnect(self) -> None: ...
268
+ def clear(self, event: Event) -> None: ...
269
+ def onmove(self, event: Event) -> None: ...
270
+
271
+ class _SelectorWidget(AxesWidget):
272
+ onselect: Callable[[float, float], Any]
273
+ useblit: bool
274
+ background: Any
275
+ validButtons: list[MouseButton]
276
+ def __init__(
277
+ self,
278
+ ax: Axes,
279
+ onselect: Callable[[float, float], Any] | None = ...,
280
+ useblit: bool = ...,
281
+ button: MouseButton | Collection[MouseButton] | None = ...,
282
+ state_modifier_keys: dict[str, str] | None = ...,
283
+ use_data_coordinates: bool = ...,
284
+ ) -> None: ...
285
+ def update_background(self, event: Event) -> None: ...
286
+ def connect_default_events(self) -> None: ...
287
+ def ignore(self, event: Event) -> bool: ...
288
+ def update(self) -> None: ...
289
+ def press(self, event: Event) -> bool: ...
290
+ def release(self, event: Event) -> bool: ...
291
+ def onmove(self, event: Event) -> bool: ...
292
+ def on_scroll(self, event: Event) -> None: ...
293
+ def on_key_press(self, event: Event) -> None: ...
294
+ def on_key_release(self, event: Event) -> None: ...
295
+ def set_visible(self, visible: bool) -> None: ...
296
+ def get_visible(self) -> bool: ...
297
+ def clear(self) -> None: ...
298
+ @property
299
+ def artists(self) -> tuple[Artist]: ...
300
+ def set_props(self, **props) -> None: ...
301
+ def set_handle_props(self, **handle_props) -> None: ...
302
+ def add_state(self, state: str) -> None: ...
303
+ def remove_state(self, state: str) -> None: ...
304
+
305
+ class SpanSelector(_SelectorWidget):
306
+ snap_values: ArrayLike | None
307
+ onmove_callback: Callable[[float, float], Any]
308
+ minspan: float
309
+ grab_range: float
310
+ drag_from_anywhere: bool
311
+ ignore_event_outside: bool
312
+ def __init__(
313
+ self,
314
+ ax: Axes,
315
+ onselect: Callable[[float, float], Any],
316
+ direction: Literal["horizontal", "vertical"],
317
+ *,
318
+ minspan: float = ...,
319
+ useblit: bool = ...,
320
+ props: dict[str, Any] | None = ...,
321
+ onmove_callback: Callable[[float, float], Any] | None = ...,
322
+ interactive: bool = ...,
323
+ button: MouseButton | Collection[MouseButton] | None = ...,
324
+ handle_props: dict[str, Any] | None = ...,
325
+ grab_range: float = ...,
326
+ state_modifier_keys: dict[str, str] | None = ...,
327
+ drag_from_anywhere: bool = ...,
328
+ ignore_event_outside: bool = ...,
329
+ snap_values: ArrayLike | None = ...,
330
+ ) -> None: ...
331
+ def new_axes(
332
+ self,
333
+ ax: Axes,
334
+ *,
335
+ _props: dict[str, Any] | None = ...,
336
+ _init: bool = ...,
337
+ ) -> None: ...
338
+ def connect_default_events(self) -> None: ...
339
+ @property
340
+ def direction(self) -> Literal["horizontal", "vertical"]: ...
341
+ @direction.setter
342
+ def direction(self, direction: Literal["horizontal", "vertical"]) -> None: ...
343
+ @property
344
+ def extents(self) -> tuple[float, float]: ...
345
+ @extents.setter
346
+ def extents(self, extents: tuple[float, float]) -> None: ...
347
+
348
+ class ToolLineHandles:
349
+ ax: Axes
350
+ def __init__(
351
+ self,
352
+ ax: Axes,
353
+ positions: ArrayLike,
354
+ direction: Literal["horizontal", "vertical"],
355
+ *,
356
+ line_props: dict[str, Any] | None = ...,
357
+ useblit: bool = ...,
358
+ ) -> None: ...
359
+ @property
360
+ def artists(self) -> tuple[Line2D]: ...
361
+ @property
362
+ def positions(self) -> list[float]: ...
363
+ @property
364
+ def direction(self) -> Literal["horizontal", "vertical"]: ...
365
+ def set_data(self, positions: ArrayLike) -> None: ...
366
+ def set_visible(self, value: bool) -> None: ...
367
+ def set_animated(self, value: bool) -> None: ...
368
+ def remove(self) -> None: ...
369
+ def closest(self, x: float, y: float) -> tuple[int, float]: ...
370
+
371
+ class ToolHandles:
372
+ ax: Axes
373
+ def __init__(
374
+ self,
375
+ ax: Axes,
376
+ x: ArrayLike,
377
+ y: ArrayLike,
378
+ *,
379
+ marker: str = ...,
380
+ marker_props: dict[str, Any] | None = ...,
381
+ useblit: bool = ...,
382
+ ) -> None: ...
383
+ @property
384
+ def x(self) -> ArrayLike: ...
385
+ @property
386
+ def y(self) -> ArrayLike: ...
387
+ @property
388
+ def artists(self) -> tuple[Line2D]: ...
389
+ def set_data(self, pts: ArrayLike, y: ArrayLike | None = ...) -> None: ...
390
+ def set_visible(self, val: bool) -> None: ...
391
+ def set_animated(self, val: bool) -> None: ...
392
+ def closest(self, x: float, y: float) -> tuple[int, float]: ...
393
+
394
+ class RectangleSelector(_SelectorWidget):
395
+ drag_from_anywhere: bool
396
+ ignore_event_outside: bool
397
+ minspanx: float
398
+ minspany: float
399
+ spancoords: Literal["data", "pixels"]
400
+ grab_range: float
401
+ def __init__(
402
+ self,
403
+ ax: Axes,
404
+ onselect: Callable[[MouseEvent, MouseEvent], Any] | None = ...,
405
+ *,
406
+ minspanx: float = ...,
407
+ minspany: float = ...,
408
+ useblit: bool = ...,
409
+ props: dict[str, Any] | None = ...,
410
+ spancoords: Literal["data", "pixels"] = ...,
411
+ button: MouseButton | Collection[MouseButton] | None = ...,
412
+ grab_range: float = ...,
413
+ handle_props: dict[str, Any] | None = ...,
414
+ interactive: bool = ...,
415
+ state_modifier_keys: dict[str, str] | None = ...,
416
+ drag_from_anywhere: bool = ...,
417
+ ignore_event_outside: bool = ...,
418
+ use_data_coordinates: bool = ...,
419
+ ) -> None: ...
420
+ @property
421
+ def corners(self) -> tuple[np.ndarray, np.ndarray]: ...
422
+ @property
423
+ def edge_centers(self) -> tuple[np.ndarray, np.ndarray]: ...
424
+ @property
425
+ def center(self) -> tuple[float, float]: ...
426
+ @property
427
+ def extents(self) -> tuple[float, float, float, float]: ...
428
+ @extents.setter
429
+ def extents(self, extents: tuple[float, float, float, float]) -> None: ...
430
+ @property
431
+ def rotation(self) -> float: ...
432
+ @rotation.setter
433
+ def rotation(self, value: float) -> None: ...
434
+ @property
435
+ def geometry(self) -> np.ndarray: ...
436
+
437
+ class EllipseSelector(RectangleSelector): ...
438
+
439
+ class LassoSelector(_SelectorWidget):
440
+ verts: None | list[tuple[float, float]]
441
+ def __init__(
442
+ self,
443
+ ax: Axes,
444
+ onselect: Callable[[list[tuple[float, float]]], Any] | None = ...,
445
+ *,
446
+ useblit: bool = ...,
447
+ props: dict[str, Any] | None = ...,
448
+ button: MouseButton | Collection[MouseButton] | None = ...,
449
+ ) -> None: ...
450
+
451
+ class PolygonSelector(_SelectorWidget):
452
+ grab_range: float
453
+ def __init__(
454
+ self,
455
+ ax: Axes,
456
+ onselect: Callable[[ArrayLike, ArrayLike], Any] | None = ...,
457
+ *,
458
+ useblit: bool = ...,
459
+ props: dict[str, Any] | None = ...,
460
+ handle_props: dict[str, Any] | None = ...,
461
+ grab_range: float = ...,
462
+ draw_bounding_box: bool = ...,
463
+ box_handle_props: dict[str, Any] | None = ...,
464
+ box_props: dict[str, Any] | None = ...
465
+ ) -> None: ...
466
+ def onmove(self, event: Event) -> bool: ...
467
+ @property
468
+ def verts(self) -> list[tuple[float, float]]: ...
469
+ @verts.setter
470
+ def verts(self, xys: Sequence[tuple[float, float]]) -> None: ...
471
+
472
+ class Lasso(AxesWidget):
473
+ useblit: bool
474
+ background: Any
475
+ verts: list[tuple[float, float]] | None
476
+ line: Line2D
477
+ callback: Callable[[list[tuple[float, float]]], Any]
478
+ def __init__(
479
+ self,
480
+ ax: Axes,
481
+ xy: tuple[float, float],
482
+ callback: Callable[[list[tuple[float, float]]], Any],
483
+ *,
484
+ useblit: bool = ...,
485
+ props: dict[str, Any] | None = ...,
486
+ ) -> None: ...
487
+ def onrelease(self, event: Event) -> None: ...
488
+ def onmove(self, event: Event) -> None: ...
shared/package-files/06/069723f7ea5e8585b6d2f9f8298f7ca400d07790348330d4b94936cb8f07cf23/blob ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numba import cuda
3
+ from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
4
+ from numba.tests.support import linux_only, override_config
5
+ from numba.core.errors import NumbaPerformanceWarning
6
+ import warnings
7
+
8
+
9
+ @skip_on_cudasim('cudasim does not raise performance warnings')
10
+ class TestWarnings(CUDATestCase):
11
+ def test_inefficient_launch_configuration(self):
12
+ @cuda.jit
13
+ def kernel():
14
+ pass
15
+
16
+ with override_config('CUDA_LOW_OCCUPANCY_WARNINGS', 1):
17
+ with warnings.catch_warnings(record=True) as w:
18
+ kernel[1, 1]()
19
+
20
+ self.assertEqual(w[0].category, NumbaPerformanceWarning)
21
+ self.assertIn('Grid size', str(w[0].message))
22
+ self.assertIn('low occupancy', str(w[0].message))
23
+
24
+ def test_efficient_launch_configuration(self):
25
+ @cuda.jit
26
+ def kernel():
27
+ pass
28
+
29
+ with override_config('CUDA_LOW_OCCUPANCY_WARNINGS', 1):
30
+ with warnings.catch_warnings(record=True) as w:
31
+ kernel[256, 256]()
32
+
33
+ self.assertEqual(len(w), 0)
34
+
35
+ def test_warn_on_host_array(self):
36
+ @cuda.jit
37
+ def foo(r, x):
38
+ r[0] = x + 1
39
+
40
+ N = 10
41
+ arr_f32 = np.zeros(N, dtype=np.float32)
42
+ with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1):
43
+ with warnings.catch_warnings(record=True) as w:
44
+ foo[1, N](arr_f32, N)
45
+
46
+ self.assertEqual(w[0].category, NumbaPerformanceWarning)
47
+ self.assertIn('Host array used in CUDA kernel will incur',
48
+ str(w[0].message))
49
+ self.assertIn('copy overhead', str(w[0].message))
50
+
51
+ def test_pinned_warn_on_host_array(self):
52
+ @cuda.jit
53
+ def foo(r, x):
54
+ r[0] = x + 1
55
+
56
+ N = 10
57
+ ary = cuda.pinned_array(N, dtype=np.float32)
58
+
59
+ with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1):
60
+ with warnings.catch_warnings(record=True) as w:
61
+ foo[1, N](ary, N)
62
+
63
+ self.assertEqual(w[0].category, NumbaPerformanceWarning)
64
+ self.assertIn('Host array used in CUDA kernel will incur',
65
+ str(w[0].message))
66
+ self.assertIn('copy overhead', str(w[0].message))
67
+
68
+ def test_nowarn_on_mapped_array(self):
69
+ @cuda.jit
70
+ def foo(r, x):
71
+ r[0] = x + 1
72
+
73
+ N = 10
74
+ ary = cuda.mapped_array(N, dtype=np.float32)
75
+
76
+ with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1):
77
+ with warnings.catch_warnings(record=True) as w:
78
+ foo[1, N](ary, N)
79
+
80
+ self.assertEqual(len(w), 0)
81
+
82
+ @linux_only
83
+ def test_nowarn_on_managed_array(self):
84
+ @cuda.jit
85
+ def foo(r, x):
86
+ r[0] = x + 1
87
+
88
+ N = 10
89
+ ary = cuda.managed_array(N, dtype=np.float32)
90
+
91
+ with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1):
92
+ with warnings.catch_warnings(record=True) as w:
93
+ foo[1, N](ary, N)
94
+
95
+ self.assertEqual(len(w), 0)
96
+
97
+ def test_nowarn_on_device_array(self):
98
+ @cuda.jit
99
+ def foo(r, x):
100
+ r[0] = x + 1
101
+
102
+ N = 10
103
+ ary = cuda.device_array(N, dtype=np.float32)
104
+
105
+ with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1):
106
+ with warnings.catch_warnings(record=True) as w:
107
+ foo[1, N](ary, N)
108
+
109
+ self.assertEqual(len(w), 0)
110
+
111
+ def test_warn_on_debug_and_opt(self):
112
+ with warnings.catch_warnings(record=True) as w:
113
+ cuda.jit(debug=True, opt=True)
114
+
115
+ self.assertEqual(len(w), 1)
116
+ self.assertIn('not supported by CUDA', str(w[0].message))
117
+
118
+ def test_warn_on_debug_and_opt_default(self):
119
+ with warnings.catch_warnings(record=True) as w:
120
+ cuda.jit(debug=True)
121
+
122
+ self.assertEqual(len(w), 1)
123
+ self.assertIn('not supported by CUDA', str(w[0].message))
124
+
125
+ def test_no_warn_on_debug_and_no_opt(self):
126
+ with warnings.catch_warnings(record=True) as w:
127
+ cuda.jit(debug=True, opt=False)
128
+
129
+ self.assertEqual(len(w), 0)
130
+
131
+ def test_no_warn_with_no_debug_and_opt_kwargs(self):
132
+ with warnings.catch_warnings(record=True) as w:
133
+ cuda.jit()
134
+
135
+ self.assertEqual(len(w), 0)
136
+
137
+
138
+ if __name__ == '__main__':
139
+ unittest.main()
shared/package-files/06/069ad718312002b3c0a162ef04ff183de7efe6fbca3f338dcc1d5b4ab467cda1/blob ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the minimum dependencies in README.rst and pyproject.toml"""
2
+
3
+ import os
4
+ import re
5
+ from collections import defaultdict
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ import sklearn
11
+ from sklearn._min_dependencies import dependent_packages
12
+ from sklearn.utils.fixes import parse_version
13
+
14
+ min_depencies_tag_to_packages_without_version = defaultdict(list)
15
+ for package, (min_version, extras) in dependent_packages.items():
16
+ for extra in extras.split(", "):
17
+ min_depencies_tag_to_packages_without_version[extra].append(package)
18
+
19
+ min_dependencies_tag_to_pyproject_section = {
20
+ "build": "build-system.requires",
21
+ "install": "project.dependencies",
22
+ }
23
+ for tag in min_depencies_tag_to_packages_without_version:
24
+ min_dependencies_tag_to_pyproject_section[tag] = (
25
+ f"project.optional-dependencies.{tag}"
26
+ )
27
+
28
+
29
+ def test_min_dependencies_readme():
30
+ # Test that the minimum dependencies in the README.rst file are
31
+ # consistent with the minimum dependencies defined at the file:
32
+ # sklearn/_min_dependencies.py
33
+
34
+ pattern = re.compile(
35
+ r"\.\. \|"
36
+ r"([A-Za-z-]+)"
37
+ r"MinVersion\| replace::"
38
+ r"( [0-9]+\.[0-9]+(\.[0-9]+)?)"
39
+ )
40
+
41
+ readme_path = Path(sklearn.__file__).parent.parent
42
+ readme_file = readme_path / "README.rst"
43
+
44
+ if not os.path.exists(readme_file):
45
+ # Skip the test if the README.rst file is not available.
46
+ # For instance, when installing scikit-learn from wheels
47
+ pytest.skip("The README.rst file is not available.")
48
+
49
+ with readme_file.open("r") as f:
50
+ for line in f:
51
+ matched = pattern.match(line)
52
+
53
+ if not matched:
54
+ continue
55
+
56
+ package, version = matched.group(0), matched.group(1)
57
+ package = package.lower()
58
+
59
+ if package in dependent_packages:
60
+ version = parse_version(version)
61
+ min_version = parse_version(dependent_packages[package][0])
62
+
63
+ assert version == min_version, f"{package} has a mismatched version"
64
+
65
+
66
+ def check_pyproject_section(
67
+ pyproject_section, min_dependencies_tag, skip_version_check_for=None
68
+ ):
69
+ # tomllib is available in Python 3.11
70
+ tomllib = pytest.importorskip("tomllib")
71
+
72
+ if skip_version_check_for is None:
73
+ skip_version_check_for = []
74
+
75
+ expected_packages = min_depencies_tag_to_packages_without_version[
76
+ min_dependencies_tag
77
+ ]
78
+
79
+ root_directory = Path(sklearn.__file__).parent.parent
80
+ pyproject_toml_path = root_directory / "pyproject.toml"
81
+
82
+ if not pyproject_toml_path.exists():
83
+ # Skip the test if the pyproject.toml file is not available.
84
+ # For instance, when installing scikit-learn from wheels
85
+ pytest.skip("pyproject.toml is not available.")
86
+
87
+ with pyproject_toml_path.open("rb") as f:
88
+ pyproject_toml = tomllib.load(f)
89
+
90
+ pyproject_section_keys = pyproject_section.split(".")
91
+ info = pyproject_toml
92
+ for key in pyproject_section_keys:
93
+ info = info[key]
94
+
95
+ pyproject_build_min_versions = {}
96
+ for requirement in info:
97
+ if ">=" in requirement:
98
+ package, version = requirement.split(">=")
99
+ elif "==" in requirement:
100
+ package, version = requirement.split("==")
101
+ else:
102
+ raise NotImplementedError(
103
+ f"{requirement} not supported yet in this test. "
104
+ "Only >= and == are supported for version requirements"
105
+ )
106
+
107
+ pyproject_build_min_versions[package] = version
108
+
109
+ assert sorted(pyproject_build_min_versions) == sorted(expected_packages)
110
+
111
+ for package, version in pyproject_build_min_versions.items():
112
+ version = parse_version(version)
113
+ expected_min_version = parse_version(dependent_packages[package][0])
114
+ if package in skip_version_check_for:
115
+ continue
116
+
117
+ assert version == expected_min_version, f"{package} has a mismatched version"
118
+
119
+
120
+ @pytest.mark.parametrize(
121
+ "min_dependencies_tag, pyproject_section",
122
+ min_dependencies_tag_to_pyproject_section.items(),
123
+ )
124
+ def test_min_dependencies_pyproject_toml(pyproject_section, min_dependencies_tag):
125
+ """Check versions in pyproject.toml is consistent with _min_dependencies."""
126
+ # NumPy is more complex because build-time (>=1.25) and run-time (>=1.19.5)
127
+ # requirement currently don't match
128
+ skip_version_check_for = ["numpy"] if min_dependencies_tag == "build" else None
129
+ check_pyproject_section(
130
+ pyproject_section,
131
+ min_dependencies_tag,
132
+ skip_version_check_for=skip_version_check_for,
133
+ )
shared/package-files/06/069d4ee48ec2edb74e10982f4c730a0d8d39bd5c9f7d2cc97ff5322a179999ea/blob ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/special_bessel_y0_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::special_bessel_y0(Tensor self) -> Tensor
26
+ inline at::Tensor special_bessel_y0(const at::Tensor & self) {
27
+ return at::_ops::special_bessel_y0::call(self);
28
+ }
29
+
30
+ // aten::special_bessel_y0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & special_bessel_y0_out(at::Tensor & out, const at::Tensor & self) {
32
+ return at::_ops::special_bessel_y0_out::call(self, out);
33
+ }
34
+ // aten::special_bessel_y0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & special_bessel_y0_outf(const at::Tensor & self, at::Tensor & out) {
36
+ return at::_ops::special_bessel_y0_out::call(self, out);
37
+ }
38
+
39
+ }
shared/package-files/06/069d8f07866ea9e33218850c0e8d5d0a08397899e08d6983aae65c6e82e582fa/blob ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from statsmodels.compat.platform import PLATFORM_WIN32
2
+
3
+ import numpy as np
4
+ from numpy.testing import assert_allclose, assert_equal
5
+ import pandas as pd
6
+ import pytest
7
+
8
+ from statsmodels.multivariate.pca import PCA, pca
9
+ from statsmodels.multivariate.tests.results.datamlw import (
10
+ data,
11
+ princomp1,
12
+ princomp2,
13
+ )
14
+ from statsmodels.tools.sm_exceptions import EstimationWarning, ValueWarning
15
+
16
+ DECIMAL_5 = 0.00001
17
+
18
+
19
+ class TestPCA:
20
+ @classmethod
21
+ def setup_class(cls):
22
+ rs = np.random.RandomState()
23
+ rs.seed(1234)
24
+ k = 3
25
+ n = 100
26
+ t = 200
27
+ lam = 2
28
+
29
+ norm_rng = rs.standard_normal
30
+ e = norm_rng((t, n))
31
+ f = norm_rng((t, k))
32
+ b = rs.standard_gamma(lam, size=(k, n)) / lam
33
+ cls.x = f.dot(b) + e
34
+ cls.x_copy = cls.x + 0.0
35
+ cls.rs = rs
36
+
37
+ k = 3
38
+ n = 300
39
+ t = 200
40
+ lam = 2
41
+
42
+ norm_rng = rs.standard_normal
43
+ e = norm_rng((t, n))
44
+ f = norm_rng((t, k))
45
+ b = rs.standard_gamma(lam, size=(k, n)) / lam
46
+ cls.x_wide = f.dot(b) + e
47
+
48
+ @pytest.mark.smoke
49
+ @pytest.mark.thread_unsafe(reason="Uses matplotlib")
50
+ @pytest.mark.matplotlib
51
+ def test_smoke_plot_and_repr(self, close_figures):
52
+ pc = PCA(self.x)
53
+ pc.plot_scree()
54
+ pc.plot_scree(ncomp=10)
55
+ pc.plot_scree(log_scale=False)
56
+ pc.plot_scree(cumulative=True)
57
+ pc.plot_rsquare()
58
+ pc.plot_rsquare(ncomp=5)
59
+ # Additional smoke test
60
+ pc.__repr__()
61
+ pc = PCA(self.x, standardize=False)
62
+ pc.__repr__()
63
+ pc = PCA(self.x, standardize=False, demean=False)
64
+ pc.__repr__()
65
+ pc = PCA(self.x, ncomp=2, gls=True)
66
+ assert "GLS" in pc.__repr__()
67
+ # Check data for no changes
68
+ assert_equal(self.x, pc.data)
69
+
70
+ def test_eig_svd_equiv(self):
71
+ # Test leading components since the tail end can differ
72
+ pc_eig = PCA(self.x)
73
+ pc_svd = PCA(self.x, method="svd")
74
+
75
+ assert_allclose(pc_eig.projection, pc_svd.projection)
76
+ assert_allclose(np.abs(pc_eig.factors[:, :2]), np.abs(pc_svd.factors[:, :2]))
77
+ assert_allclose(np.abs(pc_eig.coeff[:2, :]), np.abs(pc_svd.coeff[:2, :]))
78
+ assert_allclose(pc_eig.eigenvals, pc_svd.eigenvals)
79
+ assert_allclose(
80
+ np.abs(pc_eig.eigenvecs[:, :2]), np.abs(pc_svd.eigenvecs[:, :2])
81
+ )
82
+
83
+ pc_svd = PCA(self.x, method="svd", ncomp=2)
84
+ pc_nipals = PCA(self.x, method="nipals", ncomp=2)
85
+ assert_allclose(
86
+ np.abs(pc_nipals.factors), np.abs(pc_svd.factors), atol=DECIMAL_5
87
+ )
88
+ assert_allclose(np.abs(pc_nipals.coeff), np.abs(pc_svd.coeff), atol=DECIMAL_5)
89
+ assert_allclose(pc_nipals.eigenvals, pc_svd.eigenvals, atol=DECIMAL_5)
90
+ assert_allclose(
91
+ np.abs(pc_nipals.eigenvecs), np.abs(pc_svd.eigenvecs), atol=DECIMAL_5
92
+ )
93
+ # Check data for no changes
94
+ assert_equal(self.x, pc_svd.data)
95
+ # Check data for no changes
96
+ assert_equal(self.x, pc_eig.data)
97
+ # Check data for no changes
98
+ assert_equal(self.x, pc_nipals.data)
99
+
100
+ def test_options(self):
101
+ pc = PCA(self.x)
102
+ pc_no_norm = PCA(self.x, normalize=False)
103
+ assert_allclose(
104
+ pc.factors.dot(pc.coeff), pc_no_norm.factors.dot(pc_no_norm.coeff)
105
+ )
106
+ princomp = pc.factors
107
+ assert_allclose(princomp.T.dot(princomp), np.eye(100), atol=1e-5)
108
+ weights = pc_no_norm.coeff
109
+ assert_allclose(weights.T.dot(weights), np.eye(100), atol=1e-5)
110
+
111
+ pc_10 = PCA(self.x, ncomp=10)
112
+ assert_allclose(pc.factors[:, :10], pc_10.factors)
113
+ assert_allclose(pc.coeff[:10, :], pc_10.coeff)
114
+ assert_allclose(pc.rsquare[: (10 + 1)], pc_10.rsquare)
115
+ assert_allclose(pc.eigenvals[:10], pc_10.eigenvals)
116
+ assert_allclose(pc.eigenvecs[:, :10], pc_10.eigenvecs)
117
+
118
+ pc = PCA(self.x, standardize=False, normalize=False)
119
+ mu = self.x.mean(0)
120
+ xdm = self.x - mu
121
+ xpx = xdm.T.dot(xdm)
122
+ val, vec = np.linalg.eigh(xpx)
123
+ ind = np.argsort(val)
124
+ ind = ind[::-1]
125
+ val = val[ind]
126
+ vec = vec[:, ind]
127
+ assert_allclose(xdm, pc.transformed_data)
128
+ assert_allclose(val, pc.eigenvals)
129
+ assert_allclose(np.abs(vec), np.abs(pc.eigenvecs))
130
+ assert_allclose(np.abs(pc.factors), np.abs(xdm.dot(vec)))
131
+ assert_allclose(pc.projection, xdm + mu)
132
+
133
+ pc = PCA(self.x, standardize=False, demean=False, normalize=False)
134
+ x = self.x
135
+ xpx = x.T.dot(x)
136
+ val, vec = np.linalg.eigh(xpx)
137
+ ind = np.argsort(val)
138
+ ind = ind[::-1]
139
+ val = val[ind]
140
+ vec = vec[:, ind]
141
+ assert_allclose(x, pc.transformed_data)
142
+ assert_allclose(val, pc.eigenvals)
143
+ assert_allclose(np.abs(vec), np.abs(pc.eigenvecs))
144
+ assert_allclose(np.abs(pc.factors), np.abs(x.dot(vec)))
145
+
146
+ def test_against_reference(self):
147
+ # Test against MATLAB, which by default demeans but does not standardize
148
+ x = data.xo / 1000.0
149
+ pc = PCA(x, normalize=False, standardize=False)
150
+
151
+ ref = princomp1
152
+ assert_allclose(np.abs(pc.factors), np.abs(ref.factors))
153
+ assert_allclose(pc.factors.dot(pc.coeff) + x.mean(0), x)
154
+ assert_allclose(np.abs(pc.coeff), np.abs(ref.coef.T))
155
+ assert_allclose(pc.factors.dot(pc.coeff), ref.factors.dot(ref.coef.T))
156
+
157
+ pc = PCA(x[:20], normalize=False, standardize=False)
158
+ mu = x[:20].mean(0)
159
+ ref = princomp2
160
+ assert_allclose(np.abs(pc.factors), np.abs(ref.factors))
161
+ assert_allclose(pc.factors.dot(pc.coeff) + mu, x[:20])
162
+ assert_allclose(np.abs(pc.coeff), np.abs(ref.coef.T))
163
+ assert_allclose(pc.factors.dot(pc.coeff), ref.factors.dot(ref.coef.T))
164
+
165
+ @pytest.mark.thread_unsafe(reason="Issues and checks warnings")
166
+ def test_warnings(self):
167
+ with pytest.warns(ValueWarning, match="The requested number of components"):
168
+ PCA(self.x, ncomp=300)
169
+
170
+ rs = self.rs
171
+ x = rs.standard_normal((200, 1)) * np.ones(200)
172
+ with pytest.warns(EstimationWarning, match="Only"):
173
+ PCA(x, method="eig")
174
+
175
+ def test_errors(self):
176
+ with pytest.raises(ValueError):
177
+ PCA(self.x, method="unknown")
178
+ with pytest.raises(ValueError):
179
+ PCA(self.x, missing="unknown")
180
+ with pytest.raises(ValueError):
181
+ PCA(self.x, tol=2.0)
182
+ with pytest.raises(ValueError):
183
+ PCA(np.nan * np.ones((200, 100)), tol=2.0)
184
+
185
+ @pytest.mark.thread_unsafe(reason="Uses matplotlib")
186
+ @pytest.mark.matplotlib
187
+ def test_pandas(self, close_figures):
188
+ pc = PCA(pd.DataFrame(self.x))
189
+ pc1 = PCA(self.x)
190
+ assert_allclose(pc.factors.values, pc1.factors)
191
+ pc.plot_scree()
192
+ pc.plot_scree(ncomp=10)
193
+ pc.plot_scree(log_scale=False)
194
+ pc.plot_rsquare()
195
+ pc.plot_rsquare(ncomp=5)
196
+ pc.project(2)
197
+ PCA(pd.DataFrame(self.x), ncomp=4, gls=True)
198
+ PCA(pd.DataFrame(self.x), ncomp=4, standardize=False)
199
+
200
+ def test_gls_and_weights(self):
201
+ with pytest.raises(ValueError):
202
+ PCA(self.x, gls=True)
203
+ with pytest.raises(ValueError):
204
+ PCA(self.x, weights=np.array([1.0, 1.0]))
205
+
206
+ # Pre-standardize to make comparison simple
207
+ x = self.x - self.x.mean(0)
208
+ x = x / (x**2.0).mean(0)
209
+ pc_gls = PCA(x, ncomp=1, standardize=False, demean=False, gls=True)
210
+ pc = PCA(x, ncomp=1, standardize=False, demean=False)
211
+ errors = x - pc.projection
212
+ var = (errors**2.0).mean(0)
213
+ weights = 1.0 / var
214
+ weights = weights / np.sqrt((weights**2.0).mean())
215
+
216
+ assert_allclose(weights, pc_gls.weights)
217
+ assert_equal(x, pc_gls.data)
218
+ assert_equal(x, pc.data)
219
+
220
+ pc_weights = PCA(x, ncomp=1, standardize=False, demean=False, weights=weights)
221
+
222
+ assert_allclose(weights, pc_weights.weights)
223
+ assert_allclose(np.abs(pc_weights.factors), np.abs(pc_gls.factors))
224
+
225
+ @pytest.mark.slow
226
+ def test_wide(self):
227
+ pc = PCA(self.x_wide)
228
+ assert_equal(pc.factors.shape[1], self.x_wide.shape[0])
229
+ assert_equal(pc.eigenvecs.shape[1], min(np.array(self.x_wide.shape)))
230
+
231
+ pc = PCA(pd.DataFrame(self.x_wide))
232
+ assert_equal(pc.factors.shape[1], self.x_wide.shape[0])
233
+ assert_equal(pc.eigenvecs.shape[1], min(np.array(self.x_wide.shape)))
234
+
235
+ def test_projection(self):
236
+ pc = PCA(self.x, ncomp=5)
237
+ mu = self.x.mean(0)
238
+ demean_x = self.x - mu
239
+ coef = np.linalg.pinv(pc.factors).dot(demean_x)
240
+ direct = pc.factors.dot(coef)
241
+ assert_allclose(pc.projection, direct + mu)
242
+
243
+ pc = PCA(self.x, standardize=False, ncomp=5)
244
+ coef = np.linalg.pinv(pc.factors).dot(demean_x)
245
+ direct = pc.factors.dot(coef)
246
+ assert_allclose(pc.projection, direct + mu)
247
+
248
+ pc = PCA(self.x, standardize=False, demean=False, ncomp=5)
249
+ coef = np.linalg.pinv(pc.factors).dot(self.x)
250
+ direct = pc.factors.dot(coef)
251
+ assert_allclose(pc.projection, direct)
252
+
253
+ pc = PCA(self.x, ncomp=5, gls=True)
254
+ mu = self.x.mean(0)
255
+ demean_x = self.x - mu
256
+ coef = np.linalg.pinv(pc.factors).dot(demean_x)
257
+ direct = pc.factors.dot(coef)
258
+ assert_allclose(pc.projection, direct + mu)
259
+
260
+ pc = PCA(self.x, standardize=False, ncomp=5)
261
+ coef = np.linalg.pinv(pc.factors).dot(demean_x)
262
+ direct = pc.factors.dot(coef)
263
+ assert_allclose(pc.projection, direct + mu)
264
+
265
+ pc = PCA(self.x, standardize=False, demean=False, ncomp=5, gls=True)
266
+ coef = np.linalg.pinv(pc.factors).dot(self.x)
267
+ direct = pc.factors.dot(coef)
268
+ assert_allclose(pc.projection, direct)
269
+
270
+ # Test error for too many factors
271
+ project = pc.project
272
+ with pytest.raises(ValueError):
273
+ project(6)
274
+
275
+ @pytest.mark.skipif(PLATFORM_WIN32, reason="Windows 32-bit")
276
+ def test_replace_missing(self):
277
+ x = self.x.copy()
278
+ x[::5, ::7] = np.nan
279
+
280
+ pc = PCA(x, missing="drop-row")
281
+ x_dropped_row = x[np.logical_not(np.any(np.isnan(x), 1))]
282
+ pc_dropped = PCA(x_dropped_row)
283
+ assert_allclose(pc.projection, pc_dropped.projection)
284
+ assert_equal(x, pc.data)
285
+
286
+ pc = PCA(x, missing="drop-col")
287
+ x_dropped_col = x[:, np.logical_not(np.any(np.isnan(x), 0))]
288
+ pc_dropped = PCA(x_dropped_col)
289
+ assert_allclose(pc.projection, pc_dropped.projection)
290
+ assert_equal(x, pc.data)
291
+
292
+ pc = PCA(x, missing="drop-min")
293
+ if x_dropped_row.size > x_dropped_col.size:
294
+ x_dropped_min = x_dropped_row
295
+ else:
296
+ x_dropped_min = x_dropped_col
297
+ pc_dropped = PCA(x_dropped_min)
298
+ assert_allclose(pc.projection, pc_dropped.projection)
299
+ assert_equal(x, pc.data)
300
+
301
+ pc = PCA(x, ncomp=3, missing="fill-em")
302
+ missing = np.isnan(x)
303
+ mu = np.nanmean(x, axis=0)
304
+ errors = x - mu
305
+ sigma = np.sqrt(np.nanmean(errors**2, axis=0))
306
+ x_std = errors / sigma
307
+ x_std[missing] = 0.0
308
+ last = x_std[missing]
309
+ delta = 1.0
310
+ count = 0
311
+ while delta > 5e-8:
312
+ pc_temp = PCA(x_std, ncomp=3, standardize=False, demean=False)
313
+ x_std[missing] = pc_temp.projection[missing]
314
+ current = x_std[missing]
315
+ diff = current - last
316
+ delta = np.sqrt(np.sum(diff**2)) / np.sqrt(np.sum(current**2))
317
+ last = current
318
+ count += 1
319
+ x = self.x + 0.0
320
+ projection = pc_temp.projection * sigma + mu
321
+ x[missing] = projection[missing]
322
+ assert_allclose(pc._adjusted_data, x)
323
+ # Check data for no changes
324
+ assert_equal(self.x, self.x_copy)
325
+
326
+ x = self.x
327
+ pc = PCA(x)
328
+ pc_dropped = PCA(x, missing="drop-row")
329
+ assert_allclose(pc.projection, pc_dropped.projection, atol=DECIMAL_5)
330
+
331
+ pc_dropped = PCA(x, missing="drop-col")
332
+ assert_allclose(pc.projection, pc_dropped.projection, atol=DECIMAL_5)
333
+
334
+ pc_dropped = PCA(x, missing="drop-min")
335
+ assert_allclose(pc.projection, pc_dropped.projection, atol=DECIMAL_5)
336
+
337
+ pc = PCA(x, ncomp=3)
338
+ pc_dropped = PCA(x, ncomp=3, missing="fill-em")
339
+ assert_allclose(pc.projection, pc_dropped.projection, atol=DECIMAL_5)
340
+
341
+ # Test too many missing for missing='fill-em'
342
+ x = self.x.copy()
343
+ x[:, :] = np.nan
344
+ with pytest.raises(ValueError):
345
+ PCA(x, missing="drop-row")
346
+ with pytest.raises(ValueError):
347
+ PCA(x, missing="drop-col")
348
+ with pytest.raises(ValueError):
349
+ PCA(x, missing="drop-min")
350
+ with pytest.raises(ValueError):
351
+ PCA(x, missing="fill-em")
352
+
353
+ def test_rsquare(self):
354
+ x = self.x + 0.0
355
+ mu = x.mean(0)
356
+ x_demean = x - mu
357
+ std = np.std(x, 0)
358
+ x_std = x_demean / std
359
+
360
+ pc = PCA(self.x)
361
+ nvar = x.shape[1]
362
+ rsquare = np.zeros(nvar + 1)
363
+ tss = np.sum(x_std**2)
364
+ for i in range(nvar + 1):
365
+ errors = x_std - pc.project(i, transform=False, unweight=False)
366
+ rsquare[i] = 1.0 - np.sum(errors**2) / tss
367
+ assert_allclose(rsquare, pc.rsquare)
368
+
369
+ pc = PCA(self.x, standardize=False)
370
+ tss = np.sum(x_demean**2)
371
+ for i in range(nvar + 1):
372
+ errors = x_demean - pc.project(i, transform=False, unweight=False)
373
+ rsquare[i] = 1.0 - np.sum(errors**2) / tss
374
+ assert_allclose(rsquare, pc.rsquare)
375
+
376
+ pc = PCA(self.x, standardize=False, demean=False)
377
+ tss = np.sum(x**2)
378
+ for i in range(nvar + 1):
379
+ errors = x - pc.project(i, transform=False, unweight=False)
380
+ rsquare[i] = 1.0 - np.sum(errors**2) / tss
381
+ assert_allclose(rsquare, pc.rsquare)
382
+
383
+ @pytest.mark.slow
384
+ def test_missing_dataframe(self):
385
+ x = self.x.copy()
386
+ x[::5, ::7] = np.nan
387
+ pc = PCA(x, ncomp=3, missing="fill-em")
388
+
389
+ x = pd.DataFrame(x)
390
+ pc_df = PCA(x, ncomp=3, missing="fill-em")
391
+ assert_allclose(pc.coeff, pc_df.coeff)
392
+ assert_allclose(pc.factors, pc_df.factors)
393
+
394
+ pc_df_nomissing = PCA(pd.DataFrame(self.x.copy()), ncomp=3)
395
+ assert isinstance(pc_df.coeff, type(pc_df_nomissing.coeff))
396
+ assert isinstance(pc_df.data, type(pc_df_nomissing.data))
397
+ assert isinstance(pc_df.eigenvals, type(pc_df_nomissing.eigenvals))
398
+ assert isinstance(pc_df.eigenvecs, type(pc_df_nomissing.eigenvecs))
399
+
400
+ x = self.x.copy()
401
+ x[::5, ::7] = np.nan
402
+ x_df = pd.DataFrame(x)
403
+ pc = PCA(x, missing="drop-row")
404
+ pc_df = PCA(x_df, missing="drop-row")
405
+ assert_allclose(pc.coeff, pc_df.coeff)
406
+ assert_allclose(pc.factors, pc_df.factors)
407
+
408
+ pc = PCA(x, missing="drop-col")
409
+ pc_df = PCA(x_df, missing="drop-col")
410
+ assert_allclose(pc.coeff, pc_df.coeff)
411
+ assert_allclose(pc.factors, pc_df.factors)
412
+
413
+ pc = PCA(x, missing="drop-min")
414
+ pc_df = PCA(x_df, missing="drop-min")
415
+ assert_allclose(pc.coeff, pc_df.coeff)
416
+ assert_allclose(pc.factors, pc_df.factors)
417
+
418
+ def test_equivalence(self):
419
+ x = self.x.copy()
420
+ assert_allclose(PCA(x).factors, pca(x)[0])
421
+
422
+ def test_equivalence_full_matrices(self):
423
+ x = self.x.copy()
424
+ pca_true = PCA(x, svd_full_matrices=True)
425
+ svd_full_matrices_true = pca_true.factors
426
+ assert pca_true._svd_full_matrices
427
+ pca_false = PCA(x)
428
+ svd_full_matrices_false = pca_false.factors
429
+ assert not pca_false._svd_full_matrices
430
+ assert_allclose(svd_full_matrices_true, svd_full_matrices_false)
431
+
432
+
433
+ def test_missing():
434
+ data = np.empty((200, 50))
435
+ data[0, 0] = np.nan
436
+ with pytest.raises(ValueError, match="data contains non-finite values"):
437
+ PCA(data)
438
+
439
+
440
+ def test_too_many_missing():
441
+ rs = np.random.RandomState(83429421)
442
+ data = rs.standard_normal((200, 50))
443
+ data[0, :-3] = np.nan
444
+ with pytest.raises(ValueError):
445
+ PCA(data, ncomp=5, missing="drop-col")
446
+ p = PCA(data, missing="drop-min")
447
+ assert max(p.factors.shape) == max(data.shape) - 1
448
+
449
+
450
+ def test_prepare_data_all_nan():
451
+ # GH: _prepare_data's all-NaN branch did
452
+ # `return np.empty(adj_data.shape[1]).fill(np.nan)`, but ndarray.fill()
453
+ # mutates in place and returns None, so the branch returned None
454
+ # instead of a NaN-filled array.
455
+ rs = np.random.RandomState(0)
456
+ data = rs.standard_normal((10, 4))
457
+ p = PCA(data)
458
+ p._adjusted_data = np.full_like(data, np.nan)
459
+
460
+ result = p._prepare_data()
461
+ assert result is not None
462
+ assert result.shape == (4,)
463
+ assert np.all(np.isnan(result))
464
+
465
+
466
+ def test_gls_warning():
467
+ rs = np.random.RandomState(83429421)
468
+ data = rs.standard_normal((400, 200))
469
+ data[:, 1:] = data[:, :1] + 0.01 * data[:, 1:]
470
+ with pytest.warns(EstimationWarning, match="Many series are being down weighted"):
471
+ factors = PCA(data, ncomp=2, gls=True).factors
472
+ assert factors.shape == (data.shape[0], 2)
shared/package-files/06/069eba747d07d88ba42cb4af2f869c43673a8d5510704abea38dddb7eb689976/blob ADDED
Binary file (4.64 kB). View file
 
shared/package-files/06/069ed4c1f7c830eee873c527155d75c9819c5d48d26b4361b2e3a041a35132df/blob ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.basic import Basic
3
+ from sympy.core.containers import Tuple
4
+ from sympy.core.function import Lambda
5
+ from sympy.core.numbers import (Rational, nan, oo, pi)
6
+ from sympy.core.relational import Eq
7
+ from sympy.core.singleton import S
8
+ from sympy.core.symbol import (Symbol, symbols)
9
+ from sympy.functions.combinatorial.factorials import (FallingFactorial, binomial)
10
+ from sympy.functions.elementary.exponential import (exp, log)
11
+ from sympy.functions.elementary.trigonometric import (cos, sin)
12
+ from sympy.functions.special.delta_functions import DiracDelta
13
+ from sympy.integrals.integrals import integrate
14
+ from sympy.logic.boolalg import (And, Or)
15
+ from sympy.matrices.dense import Matrix
16
+ from sympy.sets.sets import Interval
17
+ from sympy.tensor.indexed import Indexed
18
+ from sympy.stats import (Die, Normal, Exponential, FiniteRV, P, E, H, variance,
19
+ density, given, independent, dependent, where, pspace, GaussianUnitaryEnsemble,
20
+ random_symbols, sample, Geometric, factorial_moment, Binomial, Hypergeometric,
21
+ DiscreteUniform, Poisson, characteristic_function, moment_generating_function,
22
+ BernoulliProcess, Variance, Expectation, Probability, Covariance, covariance, cmoment,
23
+ moment, median)
24
+ from sympy.stats.rv import (IndependentProductPSpace, rs_swap, Density, NamedArgsMixin,
25
+ RandomSymbol, sample_iter, PSpace, is_random, RandomIndexedSymbol, RandomMatrixSymbol)
26
+ from sympy.testing.pytest import raises, skip, XFAIL, warns_deprecated_sympy
27
+ from sympy.external import import_module
28
+ from sympy.core.numbers import comp
29
+ from sympy.stats.frv_types import BernoulliDistribution
30
+ from sympy.core.symbol import Dummy
31
+ from sympy.functions.elementary.piecewise import Piecewise
32
+
33
+ def test_where():
34
+ X, Y = Die('X'), Die('Y')
35
+ Z = Normal('Z', 0, 1)
36
+
37
+ assert where(Z**2 <= 1).set == Interval(-1, 1)
38
+ assert where(Z**2 <= 1).as_boolean() == Interval(-1, 1).as_relational(Z.symbol)
39
+ assert where(And(X > Y, Y > 4)).as_boolean() == And(
40
+ Eq(X.symbol, 6), Eq(Y.symbol, 5))
41
+
42
+ assert len(where(X < 3).set) == 2
43
+ assert 1 in where(X < 3).set
44
+
45
+ X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
46
+ assert where(And(X**2 <= 1, X >= 0)).set == Interval(0, 1)
47
+ XX = given(X, And(X**2 <= 1, X >= 0))
48
+ assert XX.pspace.domain.set == Interval(0, 1)
49
+ assert XX.pspace.domain.as_boolean() == \
50
+ And(0 <= X.symbol, X.symbol**2 <= 1, -oo < X.symbol, X.symbol < oo)
51
+
52
+ with raises(TypeError):
53
+ XX = given(X, X + 3)
54
+
55
+
56
+ def test_random_symbols():
57
+ X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
58
+
59
+ assert set(random_symbols(2*X + 1)) == {X}
60
+ assert set(random_symbols(2*X + Y)) == {X, Y}
61
+ assert set(random_symbols(2*X + Y.symbol)) == {X}
62
+ assert set(random_symbols(2)) == set()
63
+
64
+
65
+ def test_characteristic_function():
66
+ # Imports I from sympy
67
+ from sympy.core.numbers import I
68
+ X = Normal('X',0,1)
69
+ Y = DiscreteUniform('Y', [1,2,7])
70
+ Z = Poisson('Z', 2)
71
+ t = symbols('_t')
72
+ P = Lambda(t, exp(-t**2/2))
73
+ Q = Lambda(t, exp(7*t*I)/3 + exp(2*t*I)/3 + exp(t*I)/3)
74
+ R = Lambda(t, exp(2 * exp(t*I) - 2))
75
+
76
+
77
+ assert characteristic_function(X).dummy_eq(P)
78
+ assert characteristic_function(Y).dummy_eq(Q)
79
+ assert characteristic_function(Z).dummy_eq(R)
80
+
81
+
82
+ def test_moment_generating_function():
83
+
84
+ X = Normal('X',0,1)
85
+ Y = DiscreteUniform('Y', [1,2,7])
86
+ Z = Poisson('Z', 2)
87
+ t = symbols('_t')
88
+ P = Lambda(t, exp(t**2/2))
89
+ Q = Lambda(t, (exp(7*t)/3 + exp(2*t)/3 + exp(t)/3))
90
+ R = Lambda(t, exp(2 * exp(t) - 2))
91
+
92
+
93
+ assert moment_generating_function(X).dummy_eq(P)
94
+ assert moment_generating_function(Y).dummy_eq(Q)
95
+ assert moment_generating_function(Z).dummy_eq(R)
96
+
97
+ def test_sample_iter():
98
+
99
+ X = Normal('X',0,1)
100
+ Y = DiscreteUniform('Y', [1, 2, 7])
101
+ Z = Poisson('Z', 2)
102
+
103
+ scipy = import_module('scipy')
104
+ if not scipy:
105
+ skip('Scipy is not installed. Abort tests')
106
+ expr = X**2 + 3
107
+ iterator = sample_iter(expr)
108
+
109
+ expr2 = Y**2 + 5*Y + 4
110
+ iterator2 = sample_iter(expr2)
111
+
112
+ expr3 = Z**3 + 4
113
+ iterator3 = sample_iter(expr3)
114
+
115
+ def is_iterator(obj):
116
+ if (
117
+ hasattr(obj, '__iter__') and
118
+ (hasattr(obj, 'next') or
119
+ hasattr(obj, '__next__')) and
120
+ callable(obj.__iter__) and
121
+ obj.__iter__() is obj
122
+ ):
123
+ return True
124
+ else:
125
+ return False
126
+ assert is_iterator(iterator)
127
+ assert is_iterator(iterator2)
128
+ assert is_iterator(iterator3)
129
+
130
+ def test_pspace():
131
+ X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
132
+ x = Symbol('x')
133
+
134
+ raises(ValueError, lambda: pspace(5 + 3))
135
+ raises(ValueError, lambda: pspace(x < 1))
136
+ assert pspace(X) == X.pspace
137
+ assert pspace(2*X + 1) == X.pspace
138
+ assert pspace(2*X + Y) == IndependentProductPSpace(Y.pspace, X.pspace)
139
+
140
+ def test_rs_swap():
141
+ X = Normal('x', 0, 1)
142
+ Y = Exponential('y', 1)
143
+
144
+ XX = Normal('x', 0, 2)
145
+ YY = Normal('y', 0, 3)
146
+
147
+ expr = 2*X + Y
148
+ assert expr.subs(rs_swap((X, Y), (YY, XX))) == 2*XX + YY
149
+
150
+
151
+ def test_RandomSymbol():
152
+
153
+ X = Normal('x', 0, 1)
154
+ Y = Normal('x', 0, 2)
155
+ assert X.symbol == Y.symbol
156
+ assert X != Y
157
+
158
+ assert X.name == X.symbol.name
159
+
160
+ X = Normal('lambda', 0, 1) # make sure we can use protected terms
161
+ X = Normal('Lambda', 0, 1) # make sure we can use SymPy terms
162
+
163
+
164
+ def test_RandomSymbol_diff():
165
+ X = Normal('x', 0, 1)
166
+ assert (2*X).diff(X)
167
+
168
+
169
+ def test_random_symbol_no_pspace():
170
+ x = RandomSymbol(Symbol('x'))
171
+ assert x.pspace == PSpace()
172
+
173
+ def test_overlap():
174
+ X = Normal('x', 0, 1)
175
+ Y = Normal('x', 0, 2)
176
+
177
+ raises(ValueError, lambda: P(X > Y))
178
+
179
+
180
+ def test_IndependentProductPSpace():
181
+ X = Normal('X', 0, 1)
182
+ Y = Normal('Y', 0, 1)
183
+ px = X.pspace
184
+ py = Y.pspace
185
+ assert pspace(X + Y) == IndependentProductPSpace(px, py)
186
+ assert pspace(X + Y) == IndependentProductPSpace(py, px)
187
+
188
+
189
+ def test_E():
190
+ assert E(5) == 5
191
+
192
+
193
+ def test_H():
194
+ X = Normal('X', 0, 1)
195
+ D = Die('D', sides = 4)
196
+ G = Geometric('G', 0.5)
197
+ assert H(X, X > 0) == -log(2)/2 + S.Half + log(pi)/2
198
+ assert H(D, D > 2) == log(2)
199
+ assert comp(H(G).evalf().round(2), 1.39)
200
+
201
+
202
+ def test_Sample():
203
+ X = Die('X', 6)
204
+ Y = Normal('Y', 0, 1)
205
+ z = Symbol('z', integer=True)
206
+
207
+ scipy = import_module('scipy')
208
+ if not scipy:
209
+ skip('Scipy is not installed. Abort tests')
210
+ assert sample(X) in [1, 2, 3, 4, 5, 6]
211
+ assert isinstance(sample(X + Y), float)
212
+
213
+ assert P(X + Y > 0, Y < 0, numsamples=10).is_number
214
+ assert E(X + Y, numsamples=10).is_number
215
+ assert E(X**2 + Y, numsamples=10).is_number
216
+ assert E((X + Y)**2, numsamples=10).is_number
217
+ assert variance(X + Y, numsamples=10).is_number
218
+
219
+ raises(TypeError, lambda: P(Y > z, numsamples=5))
220
+
221
+ assert P(sin(Y) <= 1, numsamples=10) == 1.0
222
+ assert P(sin(Y) <= 1, cos(Y) < 1, numsamples=10) == 1.0
223
+
224
+ assert all(i in range(1, 7) for i in density(X, numsamples=10))
225
+ assert all(i in range(4, 7) for i in density(X, X>3, numsamples=10))
226
+
227
+ numpy = import_module('numpy')
228
+ if not numpy:
229
+ skip('Numpy is not installed. Abort tests')
230
+ #Test Issue #21563: Output of sample must be a float or array
231
+ assert isinstance(sample(X), (numpy.int32, numpy.int64))
232
+ assert isinstance(sample(Y), numpy.float64)
233
+ assert isinstance(sample(X, size=2), numpy.ndarray)
234
+
235
+ with warns_deprecated_sympy():
236
+ sample(X, numsamples=2)
237
+
238
+ @XFAIL
239
+ def test_samplingE():
240
+ scipy = import_module('scipy')
241
+ if not scipy:
242
+ skip('Scipy is not installed. Abort tests')
243
+ Y = Normal('Y', 0, 1)
244
+ z = Symbol('z', integer=True)
245
+ assert E(Sum(1/z**Y, (z, 1, oo)), Y > 2, numsamples=3).is_number
246
+
247
+
248
+ def test_given():
249
+ X = Normal('X', 0, 1)
250
+ Y = Normal('Y', 0, 1)
251
+ A = given(X, True)
252
+ B = given(X, Y > 2)
253
+
254
+ assert X == A == B
255
+
256
+
257
+ def test_factorial_moment():
258
+ X = Poisson('X', 2)
259
+ Y = Binomial('Y', 2, S.Half)
260
+ Z = Hypergeometric('Z', 4, 2, 2)
261
+ assert factorial_moment(X, 2) == 4
262
+ assert factorial_moment(Y, 2) == S.Half
263
+ assert factorial_moment(Z, 2) == Rational(1, 3)
264
+
265
+ x, y, z, l = symbols('x y z l')
266
+ Y = Binomial('Y', 2, y)
267
+ Z = Hypergeometric('Z', 10, 2, 3)
268
+ assert factorial_moment(Y, l) == y**2*FallingFactorial(
269
+ 2, l) + 2*y*(1 - y)*FallingFactorial(1, l) + (1 - y)**2*\
270
+ FallingFactorial(0, l)
271
+ assert factorial_moment(Z, l) == 7*FallingFactorial(0, l)/\
272
+ 15 + 7*FallingFactorial(1, l)/15 + FallingFactorial(2, l)/15
273
+
274
+
275
+ def test_dependence():
276
+ X, Y = Die('X'), Die('Y')
277
+ assert independent(X, 2*Y)
278
+ assert not dependent(X, 2*Y)
279
+
280
+ X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
281
+ assert independent(X, Y)
282
+ assert dependent(X, 2*X)
283
+
284
+ # Create a dependency
285
+ XX, YY = given(Tuple(X, Y), Eq(X + Y, 3))
286
+ assert dependent(XX, YY)
287
+
288
+ def test_dependent_finite():
289
+ X, Y = Die('X'), Die('Y')
290
+ # Dependence testing requires symbolic conditions which currently break
291
+ # finite random variables
292
+ assert dependent(X, Y + X)
293
+
294
+ XX, YY = given(Tuple(X, Y), X + Y > 5) # Create a dependency
295
+ assert dependent(XX, YY)
296
+
297
+
298
+ def test_normality():
299
+ X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
300
+ x = Symbol('x', real=True)
301
+ z = Symbol('z', real=True)
302
+ dens = density(X - Y, Eq(X + Y, z))
303
+
304
+ assert integrate(dens(x), (x, -oo, oo)) == 1
305
+
306
+
307
+ def test_Density():
308
+ X = Die('X', 6)
309
+ d = Density(X)
310
+ assert d.doit() == density(X)
311
+
312
+ def test_NamedArgsMixin():
313
+ class Foo(Basic, NamedArgsMixin):
314
+ _argnames = 'foo', 'bar'
315
+
316
+ a = Foo(S(1), S(2))
317
+
318
+ assert a.foo == 1
319
+ assert a.bar == 2
320
+
321
+ raises(AttributeError, lambda: a.baz)
322
+
323
+ class Bar(Basic, NamedArgsMixin):
324
+ pass
325
+
326
+ raises(AttributeError, lambda: Bar(S(1), S(2)).foo)
327
+
328
+ def test_density_constant():
329
+ assert density(3)(2) == 0
330
+ assert density(3)(3) == DiracDelta(0)
331
+
332
+ def test_cmoment_constant():
333
+ assert variance(3) == 0
334
+ assert cmoment(3, 3) == 0
335
+ assert cmoment(3, 4) == 0
336
+ x = Symbol('x')
337
+ assert variance(x) == 0
338
+ assert cmoment(x, 15) == 0
339
+ assert cmoment(x, 0) == 1
340
+
341
+ def test_moment_constant():
342
+ assert moment(3, 0) == 1
343
+ assert moment(3, 1) == 3
344
+ assert moment(3, 2) == 9
345
+ x = Symbol('x')
346
+ assert moment(x, 2) == x**2
347
+
348
+ def test_median_constant():
349
+ assert median(3) == 3
350
+ x = Symbol('x')
351
+ assert median(x) == x
352
+
353
+ def test_real():
354
+ x = Normal('x', 0, 1)
355
+ assert x.is_real
356
+
357
+
358
+ def test_issue_10052():
359
+ X = Exponential('X', 3)
360
+ assert P(X < oo) == 1
361
+ assert P(X > oo) == 0
362
+ assert P(X < 2, X > oo) == 0
363
+ assert P(X < oo, X > oo) == 0
364
+ assert P(X < oo, X > 2) == 1
365
+ assert P(X < 3, X == 2) == 0
366
+ raises(ValueError, lambda: P(1))
367
+ raises(ValueError, lambda: P(X < 1, 2))
368
+
369
+ def test_issue_11934():
370
+ density = {0: .5, 1: .5}
371
+ X = FiniteRV('X', density)
372
+ assert E(X) == 0.5
373
+ assert P( X>= 2) == 0
374
+
375
+ def test_issue_8129():
376
+ X = Exponential('X', 4)
377
+ assert P(X >= X) == 1
378
+ assert P(X > X) == 0
379
+ assert P(X > X+1) == 0
380
+
381
+ def test_issue_12237():
382
+ X = Normal('X', 0, 1)
383
+ Y = Normal('Y', 0, 1)
384
+ U = P(X > 0, X)
385
+ V = P(Y < 0, X)
386
+ W = P(X + Y > 0, X)
387
+ assert W == P(X + Y > 0, X)
388
+ assert U == BernoulliDistribution(S.Half, S.Zero, S.One)
389
+ assert V == S.Half
390
+
391
+ def test_is_random():
392
+ X = Normal('X', 0, 1)
393
+ Y = Normal('Y', 0, 1)
394
+ a, b = symbols('a, b')
395
+ G = GaussianUnitaryEnsemble('U', 2)
396
+ B = BernoulliProcess('B', 0.9)
397
+ assert not is_random(a)
398
+ assert not is_random(a + b)
399
+ assert not is_random(a * b)
400
+ assert not is_random(Matrix([a**2, b**2]))
401
+ assert is_random(X)
402
+ assert is_random(X**2 + Y)
403
+ assert is_random(Y + b**2)
404
+ assert is_random(Y > 5)
405
+ assert is_random(B[3] < 1)
406
+ assert is_random(G)
407
+ assert is_random(X * Y * B[1])
408
+ assert is_random(Matrix([[X, B[2]], [G, Y]]))
409
+ assert is_random(Eq(X, 4))
410
+
411
+ def test_issue_12283():
412
+ x = symbols('x')
413
+ X = RandomSymbol(x)
414
+ Y = RandomSymbol('Y')
415
+ Z = RandomMatrixSymbol('Z', 2, 1)
416
+ W = RandomMatrixSymbol('W', 2, 1)
417
+ RI = RandomIndexedSymbol(Indexed('RI', 3))
418
+ assert pspace(Z) == PSpace()
419
+ assert pspace(RI) == PSpace()
420
+ assert pspace(X) == PSpace()
421
+ assert E(X) == Expectation(X)
422
+ assert P(Y > 3) == Probability(Y > 3)
423
+ assert variance(X) == Variance(X)
424
+ assert variance(RI) == Variance(RI)
425
+ assert covariance(X, Y) == Covariance(X, Y)
426
+ assert covariance(W, Z) == Covariance(W, Z)
427
+
428
+ def test_issue_6810():
429
+ X = Die('X', 6)
430
+ Y = Normal('Y', 0, 1)
431
+ assert P(Eq(X, 2)) == S(1)/6
432
+ assert P(Eq(Y, 0)) == 0
433
+ assert P(Or(X > 2, X < 3)) == 1
434
+ assert P(And(X > 3, X > 2)) == S(1)/2
435
+
436
+ def test_issue_20286():
437
+ n, p = symbols('n p')
438
+ B = Binomial('B', n, p)
439
+ k = Dummy('k', integer = True)
440
+ eq = Sum(Piecewise((-p**k*(1 - p)**(-k + n)*log(p**k*(1 - p)**(-k + n)*binomial(n, k))*binomial(n, k), (k >= 0) & (k <= n)), (nan, True)), (k, 0, n))
441
+ assert eq.dummy_eq(H(B))
shared/package-files/06/069f0d6d4cdf0f03e40bf33b01cac2fc3413cce89a528caef3f9c75f4a22ea76/blob ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/ivalue.h>
3
+ #include <pybind11/pybind11.h>
4
+ #include <torch/csrc/jit/python/pybind_utils.h>
5
+ #include <torch/csrc/python_headers.h>
6
+ #include <torch/csrc/utils/pybind.h>
7
+
8
+ namespace py = pybind11;
9
+
10
+ namespace c10::ivalue {
11
+
12
+ // concrete ivalue Holder that hold a py::object
13
+ struct C10_EXPORT ConcretePyObjectHolder final : PyObjectHolder {
14
+ public:
15
+ static c10::intrusive_ptr<PyObjectHolder> create(py::object py_obj) {
16
+ return c10::make_intrusive<ConcretePyObjectHolder>(std::move(py_obj));
17
+ }
18
+
19
+ static c10::intrusive_ptr<PyObjectHolder> create(const py::handle& handle) {
20
+ py::gil_scoped_acquire ag;
21
+ return c10::make_intrusive<ConcretePyObjectHolder>(
22
+ handle.cast<py::object>());
23
+ }
24
+
25
+ PyObject* getPyObject() override {
26
+ return py_obj_.ptr();
27
+ }
28
+
29
+ InferredType tryToInferType() override {
30
+ pybind11::gil_scoped_acquire ag;
31
+ return torch::jit::tryToInferType(py_obj_);
32
+ }
33
+
34
+ IValue toIValue(const TypePtr& type, c10::optional<int32_t> N = c10::nullopt)
35
+ override {
36
+ pybind11::gil_scoped_acquire ag;
37
+ return torch::jit::toIValue(py_obj_, type, N);
38
+ }
39
+
40
+ std::string toStr() override {
41
+ pybind11::gil_scoped_acquire ag;
42
+ return py::str(py_obj_);
43
+ }
44
+
45
+ std::vector<at::Tensor> extractTensors() override {
46
+ // We could implement this entirely in C++ via pybind11 but it turns out to
47
+ // be substantially slower. Namely, the total time taken by markCompleted on
48
+ // a CUDAFuture is 21.5us with this implementation, but goes up to 58.7us
49
+ // when using C++. The reason is unclear.
50
+ try {
51
+ pybind11::gil_scoped_acquire ag;
52
+ static py::object& extractorFn = *new py::object(
53
+ py::module::import("torch._jit_internal").attr("_extract_tensors"));
54
+ return extractorFn(py_obj_).cast<std::vector<at::Tensor>>();
55
+ } catch (py::error_already_set& e) {
56
+ auto err = std::runtime_error(
57
+ c10::str("Cannot extract tensors from value: ", e.what()));
58
+ {
59
+ pybind11::gil_scoped_acquire ag;
60
+ e.restore();
61
+ PyErr_Clear();
62
+ }
63
+ throw err;
64
+ }
65
+ }
66
+
67
+ // Note [Destructing py::object]
68
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~
69
+ //
70
+ // (1) Why py_obj_ = py::none(); does not work. Because we also need to
71
+ // acquire GIL when destructing py::object of None that de-references None.
72
+ // https://docs.python.org/3/c-api/none.html#c.Py_RETURN_NONE
73
+ //
74
+ // https://stackoverflow.com/questions/15287590/why-should-py-increfpy-none-be-required-before-returning-py-none-in-c
75
+ //
76
+ // (2) Why we need to call dec_ref() explicitly. Because py::object of
77
+ // nullptr, on destruction, effectively does nothing because of it calls
78
+ // Py_XDECREF(NULL) underlying.
79
+ // https://docs.python.org/3/c-api/refcounting.html#c.Py_XDECREF
80
+ ~ConcretePyObjectHolder() override {
81
+ pybind11::gil_scoped_acquire ag;
82
+ py_obj_.dec_ref();
83
+ // explicitly setting PyObject* to nullptr to prevent py::object's dtor to
84
+ // decref on the PyObject again.
85
+ py_obj_.ptr() = nullptr;
86
+ }
87
+
88
+ // explicit construction to avoid errornous implicit conversion and
89
+ // copy-initialization
90
+ explicit ConcretePyObjectHolder(py::object py_obj)
91
+ : py_obj_(std::move(py_obj)) {}
92
+
93
+ private:
94
+ py::object py_obj_;
95
+ };
96
+
97
+ } // namespace c10::ivalue
shared/package-files/06/069ffbf6861f5711899f998744be7a77b7e156d3899cda37f05548160b640ccf/energy_views.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed shared TRAIN energy-distribution model; no per-query fitting."""
2
+ from pathlib import Path
3
+ import json
4
+ import numpy as np
5
+ from energy_prior_runtime import predict_energy_nodes
6
+ CONFIG=json.loads(Path(__file__).with_name('energy_prior.json').read_text())
7
+ def eligible(row):return row.get('collision_energy') is None
8
+ def perturb_meta(meta,rows,selection,view):
9
+ assert meta.dtype==np.float32 and meta.shape==(len(rows),8) and 0<=view<3
10
+ selection=np.asarray(selection,dtype=bool);assert selection.shape==(len(rows),)
11
+ assert np.array_equal(selection,np.asarray([eligible(q) for q in rows])) and np.array_equal(meta[:,6],selection.astype(np.float32))
12
+ out=meta.copy()
13
+ if selection.any():
14
+ indices=np.flatnonzero(selection);nodes=predict_energy_nodes([rows[i] for i in indices],CONFIG);out[indices,6]=0.;out[indices,7]=(nodes[:,view]/100.).astype(np.float32)
15
+ return out
shared/package-files/06/06a0d61aa47624e544ab2f31ae6c858f4ef591cf8fba38a5695276edb13d3ecb/blob ADDED
Binary file (1.13 kB). View file
 
shared/package-files/06/06a1fa254fd8466f82510151513bd68696779988974e6617aaa6992a5a5379bb/blob ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API at::Tensor diag_embed(const at::Tensor & self, int64_t offset=0, int64_t dim1=-2, int64_t dim2=-1);
21
+
22
+ } // namespace compositeexplicitautogradnonfunctional
23
+ } // namespace at
shared/package-files/06/06a3179ec5e260fa1a94ccc46a49fa9980f18325b937650f174028ef13ee1956/blob ADDED
@@ -0,0 +1 @@
 
 
1
+ import xml.parsers as parsers
shared/package-files/06/06a420d1fa970ff4e600124f4960c2f87d9acedec1e7735f384d520ba99b5e22/blob ADDED
@@ -0,0 +1,1139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A module for reading dvi files output by TeX. Several limitations make
3
+ this not (currently) useful as a general-purpose dvi preprocessor, but
4
+ it is currently used by the pdf backend for processing usetex text.
5
+
6
+ Interface::
7
+
8
+ with Dvi(filename, 72) as dvi:
9
+ # iterate over pages:
10
+ for page in dvi:
11
+ w, h, d = page.width, page.height, page.descent
12
+ for x, y, font, glyph, width in page.text:
13
+ fontname = font.texname
14
+ pointsize = font.size
15
+ ...
16
+ for x, y, height, width in page.boxes:
17
+ ...
18
+ """
19
+
20
+ from collections import namedtuple
21
+ import enum
22
+ from functools import lru_cache, partial, wraps
23
+ import logging
24
+ import os
25
+ from pathlib import Path
26
+ import re
27
+ import struct
28
+ import subprocess
29
+ import sys
30
+
31
+ import numpy as np
32
+
33
+ from matplotlib import _api, cbook
34
+
35
+ _log = logging.getLogger(__name__)
36
+
37
+ # Many dvi related files are looked for by external processes, require
38
+ # additional parsing, and are used many times per rendering, which is why they
39
+ # are cached using lru_cache().
40
+
41
+ # Dvi is a bytecode format documented in
42
+ # https://ctan.org/pkg/dvitype
43
+ # https://texdoc.org/serve/dvitype.pdf/0
44
+ #
45
+ # The file consists of a preamble, some number of pages, a postamble,
46
+ # and a finale. Different opcodes are allowed in different contexts,
47
+ # so the Dvi object has a parser state:
48
+ #
49
+ # pre: expecting the preamble
50
+ # outer: between pages (followed by a page or the postamble,
51
+ # also e.g. font definitions are allowed)
52
+ # page: processing a page
53
+ # post_post: state after the postamble (our current implementation
54
+ # just stops reading)
55
+ # finale: the finale (unimplemented in our current implementation)
56
+
57
+ _dvistate = enum.Enum('DviState', 'pre outer inpage post_post finale')
58
+
59
+ # The marks on a page consist of text and boxes. A page also has dimensions.
60
+ Page = namedtuple('Page', 'text boxes height width descent')
61
+ Box = namedtuple('Box', 'x y height width')
62
+
63
+
64
+ # Also a namedtuple, for backcompat.
65
+ class Text(namedtuple('Text', 'x y font glyph width')):
66
+ """
67
+ A glyph in the dvi file.
68
+
69
+ The *x* and *y* attributes directly position the glyph. The *font*,
70
+ *glyph*, and *width* attributes are kept public for back-compatibility,
71
+ but users wanting to draw the glyph themselves are encouraged to instead
72
+ load the font specified by `font_path` at `font_size`, warp it with the
73
+ effects specified by `font_effects`, and load the glyph specified by
74
+ `glyph_name_or_index`.
75
+ """
76
+
77
+ def _get_pdftexmap_entry(self):
78
+ return PsfontsMap(find_tex_file("pdftex.map"))[self.font.texname]
79
+
80
+ @property
81
+ def font_path(self):
82
+ """The `~pathlib.Path` to the font for this glyph."""
83
+ psfont = self._get_pdftexmap_entry()
84
+ if psfont.filename is None:
85
+ raise ValueError("No usable font file found for {} ({}); "
86
+ "the font may lack a Type-1 version"
87
+ .format(psfont.psname.decode("ascii"),
88
+ psfont.texname.decode("ascii")))
89
+ return Path(psfont.filename)
90
+
91
+ @property
92
+ def font_size(self):
93
+ """The font size."""
94
+ return self.font.size
95
+
96
+ @property
97
+ def font_effects(self):
98
+ """
99
+ The "font effects" dict for this glyph.
100
+
101
+ This dict contains the values for this glyph of SlantFont and
102
+ ExtendFont (if any), read off :file:`pdftex.map`.
103
+ """
104
+ return self._get_pdftexmap_entry().effects
105
+
106
+ @property
107
+ def glyph_name_or_index(self):
108
+ """
109
+ Either the glyph name or the native charmap glyph index.
110
+
111
+ If :file:`pdftex.map` specifies an encoding for this glyph's font, that
112
+ is a mapping of glyph indices to Adobe glyph names; use it to convert
113
+ dvi indices to glyph names. Callers can then convert glyph names to
114
+ glyph indices (with FT_Get_Name_Index/get_name_index), and load the
115
+ glyph using FT_Load_Glyph/load_glyph.
116
+
117
+ If :file:`pdftex.map` specifies no encoding, the indices directly map
118
+ to the font's "native" charmap; glyphs should directly load using
119
+ FT_Load_Char/load_char after selecting the native charmap.
120
+ """
121
+ entry = self._get_pdftexmap_entry()
122
+ return (_parse_enc(entry.encoding)[self.glyph]
123
+ if entry.encoding is not None else self.glyph)
124
+
125
+
126
+ # Opcode argument parsing
127
+ #
128
+ # Each of the following functions takes a Dvi object and delta, which is the
129
+ # difference between the opcode and the minimum opcode with the same meaning.
130
+ # Dvi opcodes often encode the number of argument bytes in this delta.
131
+ _arg_mapping = dict(
132
+ # raw: Return delta as is.
133
+ raw=lambda dvi, delta: delta,
134
+ # u1: Read 1 byte as an unsigned number.
135
+ u1=lambda dvi, delta: dvi._read_arg(1, signed=False),
136
+ # u4: Read 4 bytes as an unsigned number.
137
+ u4=lambda dvi, delta: dvi._read_arg(4, signed=False),
138
+ # s4: Read 4 bytes as a signed number.
139
+ s4=lambda dvi, delta: dvi._read_arg(4, signed=True),
140
+ # slen: Read delta bytes as a signed number, or None if delta is None.
141
+ slen=lambda dvi, delta: dvi._read_arg(delta, signed=True) if delta else None,
142
+ # slen1: Read (delta + 1) bytes as a signed number.
143
+ slen1=lambda dvi, delta: dvi._read_arg(delta + 1, signed=True),
144
+ # ulen1: Read (delta + 1) bytes as an unsigned number.
145
+ ulen1=lambda dvi, delta: dvi._read_arg(delta + 1, signed=False),
146
+ # olen1: Read (delta + 1) bytes as an unsigned number if less than 4 bytes,
147
+ # as a signed number if 4 bytes.
148
+ olen1=lambda dvi, delta: dvi._read_arg(delta + 1, signed=(delta == 3)),
149
+ )
150
+
151
+
152
+ def _dispatch(table, min, max=None, state=None, args=('raw',)):
153
+ """
154
+ Decorator for dispatch by opcode. Sets the values in *table*
155
+ from *min* to *max* to this method, adds a check that the Dvi state
156
+ matches *state* if not None, reads arguments from the file according
157
+ to *args*.
158
+
159
+ Parameters
160
+ ----------
161
+ table : dict[int, callable]
162
+ The dispatch table to be filled in.
163
+
164
+ min, max : int
165
+ Range of opcodes that calls the registered function; *max* defaults to
166
+ *min*.
167
+
168
+ state : _dvistate, optional
169
+ State of the Dvi object in which these opcodes are allowed.
170
+
171
+ args : list[str], default: ['raw']
172
+ Sequence of argument specifications:
173
+
174
+ - 'raw': opcode minus minimum
175
+ - 'u1': read one unsigned byte
176
+ - 'u4': read four bytes, treat as an unsigned number
177
+ - 's4': read four bytes, treat as a signed number
178
+ - 'slen': read (opcode - minimum) bytes, treat as signed
179
+ - 'slen1': read (opcode - minimum + 1) bytes, treat as signed
180
+ - 'ulen1': read (opcode - minimum + 1) bytes, treat as unsigned
181
+ - 'olen1': read (opcode - minimum + 1) bytes, treat as unsigned
182
+ if under four bytes, signed if four bytes
183
+ """
184
+ def decorate(method):
185
+ get_args = [_arg_mapping[x] for x in args]
186
+
187
+ @wraps(method)
188
+ def wrapper(self, byte):
189
+ if state is not None and self.state != state:
190
+ raise ValueError("state precondition failed")
191
+ return method(self, *[f(self, byte-min) for f in get_args])
192
+ if max is None:
193
+ table[min] = wrapper
194
+ else:
195
+ for i in range(min, max+1):
196
+ assert table[i] is None
197
+ table[i] = wrapper
198
+ return wrapper
199
+ return decorate
200
+
201
+
202
+ class Dvi:
203
+ """
204
+ A reader for a dvi ("device-independent") file, as produced by TeX.
205
+
206
+ The current implementation can only iterate through pages in order,
207
+ and does not even attempt to verify the postamble.
208
+
209
+ This class can be used as a context manager to close the underlying
210
+ file upon exit. Pages can be read via iteration. Here is an overly
211
+ simple way to extract text without trying to detect whitespace::
212
+
213
+ >>> with matplotlib.dviread.Dvi('input.dvi', 72) as dvi:
214
+ ... for page in dvi:
215
+ ... print(''.join(chr(t.glyph) for t in page.text))
216
+ """
217
+ # dispatch table
218
+ _dtable = [None] * 256
219
+ _dispatch = partial(_dispatch, _dtable)
220
+
221
+ def __init__(self, filename, dpi):
222
+ """
223
+ Read the data from the file named *filename* and convert
224
+ TeX's internal units to units of *dpi* per inch.
225
+ *dpi* only sets the units and does not limit the resolution.
226
+ Use None to return TeX's internal units.
227
+ """
228
+ _log.debug('Dvi: %s', filename)
229
+ self.file = open(filename, 'rb')
230
+ self.dpi = dpi
231
+ self.fonts = {}
232
+ self.state = _dvistate.pre
233
+ self._missing_font = None
234
+
235
+ def __enter__(self):
236
+ """Context manager enter method, does nothing."""
237
+ return self
238
+
239
+ def __exit__(self, etype, evalue, etrace):
240
+ """
241
+ Context manager exit method, closes the underlying file if it is open.
242
+ """
243
+ self.close()
244
+
245
+ def __iter__(self):
246
+ """
247
+ Iterate through the pages of the file.
248
+
249
+ Yields
250
+ ------
251
+ Page
252
+ Details of all the text and box objects on the page.
253
+ The Page tuple contains lists of Text and Box tuples and
254
+ the page dimensions, and the Text and Box tuples contain
255
+ coordinates transformed into a standard Cartesian
256
+ coordinate system at the dpi value given when initializing.
257
+ The coordinates are floating point numbers, but otherwise
258
+ precision is not lost and coordinate values are not clipped to
259
+ integers.
260
+ """
261
+ while self._read():
262
+ yield self._output()
263
+
264
+ def close(self):
265
+ """Close the underlying file if it is open."""
266
+ if not self.file.closed:
267
+ self.file.close()
268
+
269
+ def _output(self):
270
+ """
271
+ Output the text and boxes belonging to the most recent page.
272
+ page = dvi._output()
273
+ """
274
+ minx = miny = np.inf
275
+ maxx = maxy = -np.inf
276
+ maxy_pure = -np.inf
277
+ for elt in self.text + self.boxes:
278
+ if isinstance(elt, Box):
279
+ x, y, h, w = elt
280
+ e = 0 # zero depth
281
+ else: # glyph
282
+ x, y, font, g, w = elt
283
+ h, e = font._height_depth_of(g)
284
+ minx = min(minx, x)
285
+ miny = min(miny, y - h)
286
+ maxx = max(maxx, x + w)
287
+ maxy = max(maxy, y + e)
288
+ maxy_pure = max(maxy_pure, y)
289
+ if self._baseline_v is not None:
290
+ maxy_pure = self._baseline_v # This should normally be the case.
291
+ self._baseline_v = None
292
+
293
+ if not self.text and not self.boxes: # Avoid infs/nans from inf+/-inf.
294
+ return Page(text=[], boxes=[], width=0, height=0, descent=0)
295
+
296
+ if self.dpi is None:
297
+ # special case for ease of debugging: output raw dvi coordinates
298
+ return Page(text=self.text, boxes=self.boxes,
299
+ width=maxx-minx, height=maxy_pure-miny,
300
+ descent=maxy-maxy_pure)
301
+
302
+ # convert from TeX's "scaled points" to dpi units
303
+ d = self.dpi / (72.27 * 2**16)
304
+ descent = (maxy - maxy_pure) * d
305
+
306
+ text = [Text((x-minx)*d, (maxy-y)*d - descent, f, g, w*d)
307
+ for (x, y, f, g, w) in self.text]
308
+ boxes = [Box((x-minx)*d, (maxy-y)*d - descent, h*d, w*d)
309
+ for (x, y, h, w) in self.boxes]
310
+
311
+ return Page(text=text, boxes=boxes, width=(maxx-minx)*d,
312
+ height=(maxy_pure-miny)*d, descent=descent)
313
+
314
+ def _read(self):
315
+ """
316
+ Read one page from the file. Return True if successful,
317
+ False if there were no more pages.
318
+ """
319
+ # Pages appear to start with the sequence
320
+ # bop (begin of page)
321
+ # xxx comment
322
+ # <push, ..., pop> # if using chemformula
323
+ # down
324
+ # push
325
+ # down
326
+ # <push, push, xxx, right, xxx, pop, pop> # if using xcolor
327
+ # down
328
+ # push
329
+ # down (possibly multiple)
330
+ # push <= here, v is the baseline position.
331
+ # etc.
332
+ # (dviasm is useful to explore this structure.)
333
+ # Thus, we use the vertical position at the first time the stack depth
334
+ # reaches 3, while at least three "downs" have been executed (excluding
335
+ # those popped out (corresponding to the chemformula preamble)), as the
336
+ # baseline (the "down" count is necessary to handle xcolor).
337
+ down_stack = [0]
338
+ self._baseline_v = None
339
+ while True:
340
+ byte = self.file.read(1)[0]
341
+ self._dtable[byte](self, byte)
342
+ if self._missing_font:
343
+ raise self._missing_font.to_exception()
344
+ name = self._dtable[byte].__name__
345
+ if name == "_push":
346
+ down_stack.append(down_stack[-1])
347
+ elif name == "_pop":
348
+ down_stack.pop()
349
+ elif name == "_down":
350
+ down_stack[-1] += 1
351
+ if (self._baseline_v is None
352
+ and len(getattr(self, "stack", [])) == 3
353
+ and down_stack[-1] >= 4):
354
+ self._baseline_v = self.v
355
+ if byte == 140: # end of page
356
+ return True
357
+ if self.state is _dvistate.post_post: # end of file
358
+ self.close()
359
+ return False
360
+
361
+ def _read_arg(self, nbytes, signed=False):
362
+ """
363
+ Read and return a big-endian integer *nbytes* long.
364
+ Signedness is determined by the *signed* keyword.
365
+ """
366
+ return int.from_bytes(self.file.read(nbytes), "big", signed=signed)
367
+
368
+ @_dispatch(min=0, max=127, state=_dvistate.inpage)
369
+ def _set_char_immediate(self, char):
370
+ self._put_char_real(char)
371
+ if isinstance(self.fonts[self.f], cbook._ExceptionInfo):
372
+ return
373
+ self.h += self.fonts[self.f]._width_of(char)
374
+
375
+ @_dispatch(min=128, max=131, state=_dvistate.inpage, args=('olen1',))
376
+ def _set_char(self, char):
377
+ self._put_char_real(char)
378
+ if isinstance(self.fonts[self.f], cbook._ExceptionInfo):
379
+ return
380
+ self.h += self.fonts[self.f]._width_of(char)
381
+
382
+ @_dispatch(132, state=_dvistate.inpage, args=('s4', 's4'))
383
+ def _set_rule(self, a, b):
384
+ self._put_rule_real(a, b)
385
+ self.h += b
386
+
387
+ @_dispatch(min=133, max=136, state=_dvistate.inpage, args=('olen1',))
388
+ def _put_char(self, char):
389
+ self._put_char_real(char)
390
+
391
+ def _put_char_real(self, char):
392
+ font = self.fonts[self.f]
393
+ if isinstance(font, cbook._ExceptionInfo):
394
+ self._missing_font = font
395
+ elif font._vf is None:
396
+ self.text.append(Text(self.h, self.v, font, char,
397
+ font._width_of(char)))
398
+ else:
399
+ scale = font._scale
400
+ for x, y, f, g, w in font._vf[char].text:
401
+ newf = DviFont(scale=_mul2012(scale, f._scale),
402
+ tfm=f._tfm, texname=f.texname, vf=f._vf)
403
+ self.text.append(Text(self.h + _mul2012(x, scale),
404
+ self.v + _mul2012(y, scale),
405
+ newf, g, newf._width_of(g)))
406
+ self.boxes.extend([Box(self.h + _mul2012(x, scale),
407
+ self.v + _mul2012(y, scale),
408
+ _mul2012(a, scale), _mul2012(b, scale))
409
+ for x, y, a, b in font._vf[char].boxes])
410
+
411
+ @_dispatch(137, state=_dvistate.inpage, args=('s4', 's4'))
412
+ def _put_rule(self, a, b):
413
+ self._put_rule_real(a, b)
414
+
415
+ def _put_rule_real(self, a, b):
416
+ if a > 0 and b > 0:
417
+ self.boxes.append(Box(self.h, self.v, a, b))
418
+
419
+ @_dispatch(138)
420
+ def _nop(self, _):
421
+ pass
422
+
423
+ @_dispatch(139, state=_dvistate.outer, args=('s4',)*11)
424
+ def _bop(self, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, p):
425
+ self.state = _dvistate.inpage
426
+ self.h = self.v = self.w = self.x = self.y = self.z = 0
427
+ self.stack = []
428
+ self.text = [] # list of Text objects
429
+ self.boxes = [] # list of Box objects
430
+
431
+ @_dispatch(140, state=_dvistate.inpage)
432
+ def _eop(self, _):
433
+ self.state = _dvistate.outer
434
+ del self.h, self.v, self.w, self.x, self.y, self.z, self.stack
435
+
436
+ @_dispatch(141, state=_dvistate.inpage)
437
+ def _push(self, _):
438
+ self.stack.append((self.h, self.v, self.w, self.x, self.y, self.z))
439
+
440
+ @_dispatch(142, state=_dvistate.inpage)
441
+ def _pop(self, _):
442
+ self.h, self.v, self.w, self.x, self.y, self.z = self.stack.pop()
443
+
444
+ @_dispatch(min=143, max=146, state=_dvistate.inpage, args=('slen1',))
445
+ def _right(self, b):
446
+ self.h += b
447
+
448
+ @_dispatch(min=147, max=151, state=_dvistate.inpage, args=('slen',))
449
+ def _right_w(self, new_w):
450
+ if new_w is not None:
451
+ self.w = new_w
452
+ self.h += self.w
453
+
454
+ @_dispatch(min=152, max=156, state=_dvistate.inpage, args=('slen',))
455
+ def _right_x(self, new_x):
456
+ if new_x is not None:
457
+ self.x = new_x
458
+ self.h += self.x
459
+
460
+ @_dispatch(min=157, max=160, state=_dvistate.inpage, args=('slen1',))
461
+ def _down(self, a):
462
+ self.v += a
463
+
464
+ @_dispatch(min=161, max=165, state=_dvistate.inpage, args=('slen',))
465
+ def _down_y(self, new_y):
466
+ if new_y is not None:
467
+ self.y = new_y
468
+ self.v += self.y
469
+
470
+ @_dispatch(min=166, max=170, state=_dvistate.inpage, args=('slen',))
471
+ def _down_z(self, new_z):
472
+ if new_z is not None:
473
+ self.z = new_z
474
+ self.v += self.z
475
+
476
+ @_dispatch(min=171, max=234, state=_dvistate.inpage)
477
+ def _fnt_num_immediate(self, k):
478
+ self.f = k
479
+
480
+ @_dispatch(min=235, max=238, state=_dvistate.inpage, args=('olen1',))
481
+ def _fnt_num(self, new_f):
482
+ self.f = new_f
483
+
484
+ @_dispatch(min=239, max=242, args=('ulen1',))
485
+ def _xxx(self, datalen):
486
+ special = self.file.read(datalen)
487
+ _log.debug(
488
+ 'Dvi._xxx: encountered special: %s',
489
+ ''.join([chr(ch) if 32 <= ch < 127 else '<%02x>' % ch
490
+ for ch in special]))
491
+
492
+ @_dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1'))
493
+ def _fnt_def(self, k, c, s, d, a, l):
494
+ self._fnt_def_real(k, c, s, d, a, l)
495
+
496
+ def _fnt_def_real(self, k, c, s, d, a, l):
497
+ n = self.file.read(a + l)
498
+ fontname = n[-l:].decode('ascii')
499
+ try:
500
+ tfm = _tfmfile(fontname)
501
+ except FileNotFoundError as exc:
502
+ # Explicitly allow defining missing fonts for Vf support; we only
503
+ # register an error when trying to load a glyph from a missing font
504
+ # and throw that error in Dvi._read. For Vf, _finalize_packet
505
+ # checks whether a missing glyph has been used, and in that case
506
+ # skips the glyph definition.
507
+ self.fonts[k] = cbook._ExceptionInfo.from_exception(exc)
508
+ return
509
+ if c != 0 and tfm.checksum != 0 and c != tfm.checksum:
510
+ raise ValueError(f'tfm checksum mismatch: {n}')
511
+ try:
512
+ vf = _vffile(fontname)
513
+ except FileNotFoundError:
514
+ vf = None
515
+ self.fonts[k] = DviFont(scale=s, tfm=tfm, texname=n, vf=vf)
516
+
517
+ @_dispatch(247, state=_dvistate.pre, args=('u1', 'u4', 'u4', 'u4', 'u1'))
518
+ def _pre(self, i, num, den, mag, k):
519
+ self.file.read(k) # comment in the dvi file
520
+ if i != 2:
521
+ raise ValueError(f"Unknown dvi format {i}")
522
+ if num != 25400000 or den != 7227 * 2**16:
523
+ raise ValueError("Nonstandard units in dvi file")
524
+ # meaning: TeX always uses those exact values, so it
525
+ # should be enough for us to support those
526
+ # (There are 72.27 pt to an inch so 7227 pt =
527
+ # 7227 * 2**16 sp to 100 in. The numerator is multiplied
528
+ # by 10^5 to get units of 10**-7 meters.)
529
+ if mag != 1000:
530
+ raise ValueError("Nonstandard magnification in dvi file")
531
+ # meaning: LaTeX seems to frown on setting \mag, so
532
+ # I think we can assume this is constant
533
+ self.state = _dvistate.outer
534
+
535
+ @_dispatch(248, state=_dvistate.outer)
536
+ def _post(self, _):
537
+ self.state = _dvistate.post_post
538
+ # TODO: actually read the postamble and finale?
539
+ # currently post_post just triggers closing the file
540
+
541
+ @_dispatch(249)
542
+ def _post_post(self, _):
543
+ raise NotImplementedError
544
+
545
+ @_dispatch(min=250, max=255)
546
+ def _malformed(self, offset):
547
+ raise ValueError(f"unknown command: byte {250 + offset}")
548
+
549
+
550
+ class DviFont:
551
+ """
552
+ Encapsulation of a font that a DVI file can refer to.
553
+
554
+ This class holds a font's texname and size, supports comparison,
555
+ and knows the widths of glyphs in the same units as the AFM file.
556
+ There are also internal attributes (for use by dviread.py) that
557
+ are *not* used for comparison.
558
+
559
+ The size is in Adobe points (converted from TeX points).
560
+
561
+ Parameters
562
+ ----------
563
+ scale : float
564
+ Factor by which the font is scaled from its natural size.
565
+ tfm : Tfm
566
+ TeX font metrics for this font
567
+ texname : bytes
568
+ Name of the font as used internally by TeX and friends, as an ASCII
569
+ bytestring. This is usually very different from any external font
570
+ names; `PsfontsMap` can be used to find the external name of the font.
571
+ vf : Vf
572
+ A TeX "virtual font" file, or None if this font is not virtual.
573
+
574
+ Attributes
575
+ ----------
576
+ texname : bytes
577
+ size : float
578
+ Size of the font in Adobe points, converted from the slightly
579
+ smaller TeX points.
580
+ widths : list
581
+ Widths of glyphs in glyph-space units, typically 1/1000ths of
582
+ the point size.
583
+
584
+ """
585
+ __slots__ = ('texname', 'size', 'widths', '_scale', '_vf', '_tfm')
586
+
587
+ def __init__(self, scale, tfm, texname, vf):
588
+ _api.check_isinstance(bytes, texname=texname)
589
+ self._scale = scale
590
+ self._tfm = tfm
591
+ self.texname = texname
592
+ self._vf = vf
593
+ self.size = scale * (72.0 / (72.27 * 2**16))
594
+ try:
595
+ nchars = max(tfm.width) + 1
596
+ except ValueError:
597
+ nchars = 0
598
+ self.widths = [(1000*tfm.width.get(char, 0)) >> 20
599
+ for char in range(nchars)]
600
+
601
+ def __eq__(self, other):
602
+ return (type(self) is type(other)
603
+ and self.texname == other.texname and self.size == other.size)
604
+
605
+ def __ne__(self, other):
606
+ return not self.__eq__(other)
607
+
608
+ def __repr__(self):
609
+ return f"<{type(self).__name__}: {self.texname}>"
610
+
611
+ def _width_of(self, char):
612
+ """Width of char in dvi units."""
613
+ width = self._tfm.width.get(char, None)
614
+ if width is not None:
615
+ return _mul2012(width, self._scale)
616
+ _log.debug('No width for char %d in font %s.', char, self.texname)
617
+ return 0
618
+
619
+ def _height_depth_of(self, char):
620
+ """Height and depth of char in dvi units."""
621
+ result = []
622
+ for metric, name in ((self._tfm.height, "height"),
623
+ (self._tfm.depth, "depth")):
624
+ value = metric.get(char, None)
625
+ if value is None:
626
+ _log.debug('No %s for char %d in font %s',
627
+ name, char, self.texname)
628
+ result.append(0)
629
+ else:
630
+ result.append(_mul2012(value, self._scale))
631
+ # cmsyXX (symbols font) glyph 0 ("minus") has a nonzero descent
632
+ # so that TeX aligns equations properly
633
+ # (https://tex.stackexchange.com/q/526103/)
634
+ # but we actually care about the rasterization depth to align
635
+ # the dvipng-generated images.
636
+ if re.match(br'^cmsy\d+$', self.texname) and char == 0:
637
+ result[-1] = 0
638
+ return result
639
+
640
+
641
+ class Vf(Dvi):
642
+ r"""
643
+ A virtual font (\*.vf file) containing subroutines for dvi files.
644
+
645
+ Parameters
646
+ ----------
647
+ filename : str or path-like
648
+
649
+ Notes
650
+ -----
651
+ The virtual font format is a derivative of dvi:
652
+ http://mirrors.ctan.org/info/knuth/virtual-fonts
653
+ This class reuses some of the machinery of `Dvi`
654
+ but replaces the `_read` loop and dispatch mechanism.
655
+
656
+ Examples
657
+ --------
658
+ ::
659
+
660
+ vf = Vf(filename)
661
+ glyph = vf[code]
662
+ glyph.text, glyph.boxes, glyph.width
663
+ """
664
+
665
+ def __init__(self, filename):
666
+ super().__init__(filename, 0)
667
+ try:
668
+ self._first_font = None
669
+ self._chars = {}
670
+ self._read()
671
+ finally:
672
+ self.close()
673
+
674
+ def __getitem__(self, code):
675
+ return self._chars[code]
676
+
677
+ def _read(self):
678
+ """
679
+ Read one page from the file. Return True if successful,
680
+ False if there were no more pages.
681
+ """
682
+ packet_char = packet_ends = None
683
+ packet_len = packet_width = None
684
+ while True:
685
+ byte = self.file.read(1)[0]
686
+ # If we are in a packet, execute the dvi instructions
687
+ if self.state is _dvistate.inpage:
688
+ byte_at = self.file.tell()-1
689
+ if byte_at == packet_ends:
690
+ self._finalize_packet(packet_char, packet_width)
691
+ packet_len = packet_char = packet_width = None
692
+ # fall through to out-of-packet code
693
+ elif byte_at > packet_ends:
694
+ raise ValueError("Packet length mismatch in vf file")
695
+ else:
696
+ if byte in (139, 140) or byte >= 243:
697
+ raise ValueError(f"Inappropriate opcode {byte} in vf file")
698
+ Dvi._dtable[byte](self, byte)
699
+ continue
700
+
701
+ # We are outside a packet
702
+ if byte < 242: # a short packet (length given by byte)
703
+ packet_len = byte
704
+ packet_char = self._read_arg(1)
705
+ packet_width = self._read_arg(3)
706
+ packet_ends = self._init_packet(byte)
707
+ self.state = _dvistate.inpage
708
+ elif byte == 242: # a long packet
709
+ packet_len = self._read_arg(4)
710
+ packet_char = self._read_arg(4)
711
+ packet_width = self._read_arg(4)
712
+ self._init_packet(packet_len)
713
+ elif 243 <= byte <= 246:
714
+ k = self._read_arg(byte - 242, byte == 246)
715
+ c = self._read_arg(4)
716
+ s = self._read_arg(4)
717
+ d = self._read_arg(4)
718
+ a = self._read_arg(1)
719
+ l = self._read_arg(1)
720
+ self._fnt_def_real(k, c, s, d, a, l)
721
+ if self._first_font is None:
722
+ self._first_font = k
723
+ elif byte == 247: # preamble
724
+ i = self._read_arg(1)
725
+ k = self._read_arg(1)
726
+ x = self.file.read(k)
727
+ cs = self._read_arg(4)
728
+ ds = self._read_arg(4)
729
+ self._pre(i, x, cs, ds)
730
+ elif byte == 248: # postamble (just some number of 248s)
731
+ break
732
+ else:
733
+ raise ValueError(f"Unknown vf opcode {byte}")
734
+
735
+ def _init_packet(self, pl):
736
+ if self.state != _dvistate.outer:
737
+ raise ValueError("Misplaced packet in vf file")
738
+ self.h = self.v = self.w = self.x = self.y = self.z = 0
739
+ self.stack = []
740
+ self.text = []
741
+ self.boxes = []
742
+ self.f = self._first_font
743
+ self._missing_font = None
744
+ return self.file.tell() + pl
745
+
746
+ def _finalize_packet(self, packet_char, packet_width):
747
+ if not self._missing_font: # Otherwise we don't have full glyph definition.
748
+ self._chars[packet_char] = Page(
749
+ text=self.text, boxes=self.boxes, width=packet_width,
750
+ height=None, descent=None)
751
+ self.state = _dvistate.outer
752
+
753
+ def _pre(self, i, x, cs, ds):
754
+ if self.state is not _dvistate.pre:
755
+ raise ValueError("pre command in middle of vf file")
756
+ if i != 202:
757
+ raise ValueError(f"Unknown vf format {i}")
758
+ if len(x):
759
+ _log.debug('vf file comment: %s', x)
760
+ self.state = _dvistate.outer
761
+ # cs = checksum, ds = design size
762
+
763
+
764
+ def _mul2012(num1, num2):
765
+ """Multiply two numbers in 20.12 fixed point format."""
766
+ # Separated into a function because >> has surprising precedence
767
+ return (num1*num2) >> 20
768
+
769
+
770
+ class Tfm:
771
+ """
772
+ A TeX Font Metric file.
773
+
774
+ This implementation covers only the bare minimum needed by the Dvi class.
775
+
776
+ Parameters
777
+ ----------
778
+ filename : str or path-like
779
+
780
+ Attributes
781
+ ----------
782
+ checksum : int
783
+ Used for verifying against the dvi file.
784
+ design_size : int
785
+ Design size of the font (unknown units)
786
+ width, height, depth : dict
787
+ Dimensions of each character, need to be scaled by the factor
788
+ specified in the dvi file. These are dicts because indexing may
789
+ not start from 0.
790
+ """
791
+ __slots__ = ('checksum', 'design_size', 'width', 'height', 'depth')
792
+
793
+ def __init__(self, filename):
794
+ _log.debug('opening tfm file %s', filename)
795
+ with open(filename, 'rb') as file:
796
+ header1 = file.read(24)
797
+ lh, bc, ec, nw, nh, nd = struct.unpack('!6H', header1[2:14])
798
+ _log.debug('lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d',
799
+ lh, bc, ec, nw, nh, nd)
800
+ header2 = file.read(4*lh)
801
+ self.checksum, self.design_size = struct.unpack('!2I', header2[:8])
802
+ # there is also encoding information etc.
803
+ char_info = file.read(4*(ec-bc+1))
804
+ widths = struct.unpack(f'!{nw}i', file.read(4*nw))
805
+ heights = struct.unpack(f'!{nh}i', file.read(4*nh))
806
+ depths = struct.unpack(f'!{nd}i', file.read(4*nd))
807
+ self.width = {}
808
+ self.height = {}
809
+ self.depth = {}
810
+ for idx, char in enumerate(range(bc, ec+1)):
811
+ byte0 = char_info[4*idx]
812
+ byte1 = char_info[4*idx+1]
813
+ self.width[char] = widths[byte0]
814
+ self.height[char] = heights[byte1 >> 4]
815
+ self.depth[char] = depths[byte1 & 0xf]
816
+
817
+
818
+ PsFont = namedtuple('PsFont', 'texname psname effects encoding filename')
819
+
820
+
821
+ class PsfontsMap:
822
+ """
823
+ A psfonts.map formatted file, mapping TeX fonts to PS fonts.
824
+
825
+ Parameters
826
+ ----------
827
+ filename : str or path-like
828
+
829
+ Notes
830
+ -----
831
+ For historical reasons, TeX knows many Type-1 fonts by different
832
+ names than the outside world. (For one thing, the names have to
833
+ fit in eight characters.) Also, TeX's native fonts are not Type-1
834
+ but Metafont, which is nontrivial to convert to PostScript except
835
+ as a bitmap. While high-quality conversions to Type-1 format exist
836
+ and are shipped with modern TeX distributions, we need to know
837
+ which Type-1 fonts are the counterparts of which native fonts. For
838
+ these reasons a mapping is needed from internal font names to font
839
+ file names.
840
+
841
+ A texmf tree typically includes mapping files called e.g.
842
+ :file:`psfonts.map`, :file:`pdftex.map`, or :file:`dvipdfm.map`.
843
+ The file :file:`psfonts.map` is used by :program:`dvips`,
844
+ :file:`pdftex.map` by :program:`pdfTeX`, and :file:`dvipdfm.map`
845
+ by :program:`dvipdfm`. :file:`psfonts.map` might avoid embedding
846
+ the 35 PostScript fonts (i.e., have no filename for them, as in
847
+ the Times-Bold example above), while the pdf-related files perhaps
848
+ only avoid the "Base 14" pdf fonts. But the user may have
849
+ configured these files differently.
850
+
851
+ Examples
852
+ --------
853
+ >>> map = PsfontsMap(find_tex_file('pdftex.map'))
854
+ >>> entry = map[b'ptmbo8r']
855
+ >>> entry.texname
856
+ b'ptmbo8r'
857
+ >>> entry.psname
858
+ b'Times-Bold'
859
+ >>> entry.encoding
860
+ '/usr/local/texlive/2008/texmf-dist/fonts/enc/dvips/base/8r.enc'
861
+ >>> entry.effects
862
+ {'slant': 0.16700000000000001}
863
+ >>> entry.filename
864
+ """
865
+ __slots__ = ('_filename', '_unparsed', '_parsed')
866
+
867
+ # Create a filename -> PsfontsMap cache, so that calling
868
+ # `PsfontsMap(filename)` with the same filename a second time immediately
869
+ # returns the same object.
870
+ @lru_cache
871
+ def __new__(cls, filename):
872
+ self = object.__new__(cls)
873
+ self._filename = os.fsdecode(filename)
874
+ # Some TeX distributions have enormous pdftex.map files which would
875
+ # take hundreds of milliseconds to parse, but it is easy enough to just
876
+ # store the unparsed lines (keyed by the first word, which is the
877
+ # texname) and parse them on-demand.
878
+ with open(filename, 'rb') as file:
879
+ self._unparsed = {}
880
+ for line in file:
881
+ tfmname = line.split(b' ', 1)[0]
882
+ self._unparsed.setdefault(tfmname, []).append(line)
883
+ self._parsed = {}
884
+ return self
885
+
886
+ def __getitem__(self, texname):
887
+ assert isinstance(texname, bytes)
888
+ if texname in self._unparsed:
889
+ for line in self._unparsed.pop(texname):
890
+ if self._parse_and_cache_line(line):
891
+ break
892
+ try:
893
+ return self._parsed[texname]
894
+ except KeyError:
895
+ raise LookupError(
896
+ f"An associated PostScript font (required by Matplotlib) "
897
+ f"could not be found for TeX font {texname.decode('ascii')!r} "
898
+ f"in {self._filename!r}; this problem can often be solved by "
899
+ f"installing a suitable PostScript font package in your TeX "
900
+ f"package manager") from None
901
+
902
+ def _parse_and_cache_line(self, line):
903
+ """
904
+ Parse a line in the font mapping file.
905
+
906
+ The format is (partially) documented at
907
+ http://mirrors.ctan.org/systems/doc/pdftex/manual/pdftex-a.pdf
908
+ https://tug.org/texinfohtml/dvips.html#psfonts_002emap
909
+ Each line can have the following fields:
910
+
911
+ - tfmname (first, only required field),
912
+ - psname (defaults to tfmname, must come immediately after tfmname if
913
+ present),
914
+ - fontflags (integer, must come immediately after psname if present,
915
+ ignored by us),
916
+ - special (SlantFont and ExtendFont, only field that is double-quoted),
917
+ - fontfile, encodingfile (optional, prefixed by <, <<, or <[; << always
918
+ precedes a font, <[ always precedes an encoding, < can precede either
919
+ but then an encoding file must have extension .enc; < and << also
920
+ request different font subsetting behaviors but we ignore that; < can
921
+ be separated from the filename by whitespace).
922
+
923
+ special, fontfile, and encodingfile can appear in any order.
924
+ """
925
+ # If the map file specifies multiple encodings for a font, we
926
+ # follow pdfTeX in choosing the last one specified. Such
927
+ # entries are probably mistakes but they have occurred.
928
+ # https://tex.stackexchange.com/q/10826/
929
+
930
+ if not line or line.startswith((b" ", b"%", b"*", b";", b"#")):
931
+ return
932
+ tfmname = basename = special = encodingfile = fontfile = None
933
+ is_subsetted = is_t1 = is_truetype = False
934
+ matches = re.finditer(br'"([^"]*)(?:"|$)|(\S+)', line)
935
+ for match in matches:
936
+ quoted, unquoted = match.groups()
937
+ if unquoted:
938
+ if unquoted.startswith(b"<<"): # font
939
+ fontfile = unquoted[2:]
940
+ elif unquoted.startswith(b"<["): # encoding
941
+ encodingfile = unquoted[2:]
942
+ elif unquoted.startswith(b"<"): # font or encoding
943
+ word = (
944
+ # <foo => foo
945
+ unquoted[1:]
946
+ # < by itself => read the next word
947
+ or next(filter(None, next(matches).groups())))
948
+ if word.endswith(b".enc"):
949
+ encodingfile = word
950
+ else:
951
+ fontfile = word
952
+ is_subsetted = True
953
+ elif tfmname is None:
954
+ tfmname = unquoted
955
+ elif basename is None:
956
+ basename = unquoted
957
+ elif quoted:
958
+ special = quoted
959
+ effects = {}
960
+ if special:
961
+ words = reversed(special.split())
962
+ for word in words:
963
+ if word == b"SlantFont":
964
+ effects["slant"] = float(next(words))
965
+ elif word == b"ExtendFont":
966
+ effects["extend"] = float(next(words))
967
+
968
+ # Verify some properties of the line that would cause it to be ignored
969
+ # otherwise.
970
+ if fontfile is not None:
971
+ if fontfile.endswith((b".ttf", b".ttc")):
972
+ is_truetype = True
973
+ elif not fontfile.endswith(b".otf"):
974
+ is_t1 = True
975
+ elif basename is not None:
976
+ is_t1 = True
977
+ if is_truetype and is_subsetted and encodingfile is None:
978
+ return
979
+ if not is_t1 and ("slant" in effects or "extend" in effects):
980
+ return
981
+ if abs(effects.get("slant", 0)) > 1:
982
+ return
983
+ if abs(effects.get("extend", 0)) > 2:
984
+ return
985
+
986
+ if basename is None:
987
+ basename = tfmname
988
+ if encodingfile is not None:
989
+ encodingfile = find_tex_file(encodingfile)
990
+ if fontfile is not None:
991
+ fontfile = find_tex_file(fontfile)
992
+ self._parsed[tfmname] = PsFont(
993
+ texname=tfmname, psname=basename, effects=effects,
994
+ encoding=encodingfile, filename=fontfile)
995
+ return True
996
+
997
+
998
+ def _parse_enc(path):
999
+ r"""
1000
+ Parse a \*.enc file referenced from a psfonts.map style file.
1001
+
1002
+ The format supported by this function is a tiny subset of PostScript.
1003
+
1004
+ Parameters
1005
+ ----------
1006
+ path : `os.PathLike`
1007
+
1008
+ Returns
1009
+ -------
1010
+ list
1011
+ The nth entry of the list is the PostScript glyph name of the nth
1012
+ glyph.
1013
+ """
1014
+ no_comments = re.sub("%.*", "", Path(path).read_text(encoding="ascii"))
1015
+ array = re.search(r"(?s)\[(.*)\]", no_comments).group(1)
1016
+ lines = [line for line in array.split() if line]
1017
+ if all(line.startswith("/") for line in lines):
1018
+ return [line[1:] for line in lines]
1019
+ else:
1020
+ raise ValueError(f"Failed to parse {path} as Postscript encoding")
1021
+
1022
+
1023
+ class _LuatexKpsewhich:
1024
+ @lru_cache # A singleton.
1025
+ def __new__(cls):
1026
+ self = object.__new__(cls)
1027
+ self._proc = self._new_proc()
1028
+ return self
1029
+
1030
+ def _new_proc(self):
1031
+ return subprocess.Popen(
1032
+ ["luatex", "--luaonly",
1033
+ str(cbook._get_data_path("kpsewhich.lua"))],
1034
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE)
1035
+
1036
+ def search(self, filename):
1037
+ if self._proc.poll() is not None: # Dead, restart it.
1038
+ self._proc = self._new_proc()
1039
+ self._proc.stdin.write(os.fsencode(filename) + b"\n")
1040
+ self._proc.stdin.flush()
1041
+ out = self._proc.stdout.readline().rstrip()
1042
+ return None if out == b"nil" else os.fsdecode(out)
1043
+
1044
+
1045
+ @lru_cache
1046
+ def find_tex_file(filename):
1047
+ """
1048
+ Find a file in the texmf tree using kpathsea_.
1049
+
1050
+ The kpathsea library, provided by most existing TeX distributions, both
1051
+ on Unix-like systems and on Windows (MikTeX), is invoked via a long-lived
1052
+ luatex process if luatex is installed, or via kpsewhich otherwise.
1053
+
1054
+ .. _kpathsea: https://www.tug.org/kpathsea/
1055
+
1056
+ Parameters
1057
+ ----------
1058
+ filename : str or path-like
1059
+
1060
+ Raises
1061
+ ------
1062
+ FileNotFoundError
1063
+ If the file is not found.
1064
+ """
1065
+
1066
+ # we expect these to always be ascii encoded, but use utf-8
1067
+ # out of caution
1068
+ if isinstance(filename, bytes):
1069
+ filename = filename.decode('utf-8', errors='replace')
1070
+
1071
+ try:
1072
+ lk = _LuatexKpsewhich()
1073
+ except FileNotFoundError:
1074
+ lk = None # Fallback to directly calling kpsewhich, as below.
1075
+
1076
+ if lk:
1077
+ path = lk.search(filename)
1078
+ else:
1079
+ if sys.platform == 'win32':
1080
+ # On Windows only, kpathsea can use utf-8 for cmd args and output.
1081
+ # The `command_line_encoding` environment variable is set to force
1082
+ # it to always use utf-8 encoding. See Matplotlib issue #11848.
1083
+ kwargs = {'env': {**os.environ, 'command_line_encoding': 'utf-8'},
1084
+ 'encoding': 'utf-8'}
1085
+ else: # On POSIX, run through the equivalent of os.fsdecode().
1086
+ kwargs = {'encoding': sys.getfilesystemencoding(),
1087
+ 'errors': 'surrogateescape'}
1088
+
1089
+ try:
1090
+ path = (cbook._check_and_log_subprocess(['kpsewhich', filename],
1091
+ _log, **kwargs)
1092
+ .rstrip('\n'))
1093
+ except (FileNotFoundError, RuntimeError):
1094
+ path = None
1095
+
1096
+ if path:
1097
+ return path
1098
+ else:
1099
+ raise FileNotFoundError(
1100
+ f"Matplotlib's TeX implementation searched for a file named "
1101
+ f"{filename!r} in your texmf tree, but could not find it")
1102
+
1103
+
1104
+ @lru_cache
1105
+ def _fontfile(cls, suffix, texname):
1106
+ return cls(find_tex_file(texname + suffix))
1107
+
1108
+
1109
+ _tfmfile = partial(_fontfile, Tfm, ".tfm")
1110
+ _vffile = partial(_fontfile, Vf, ".vf")
1111
+
1112
+
1113
+ if __name__ == '__main__':
1114
+ from argparse import ArgumentParser
1115
+ import itertools
1116
+
1117
+ parser = ArgumentParser()
1118
+ parser.add_argument("filename")
1119
+ parser.add_argument("dpi", nargs="?", type=float, default=None)
1120
+ args = parser.parse_args()
1121
+ with Dvi(args.filename, args.dpi) as dvi:
1122
+ fontmap = PsfontsMap(find_tex_file('pdftex.map'))
1123
+ for page in dvi:
1124
+ print(f"=== new page === "
1125
+ f"(w: {page.width}, h: {page.height}, d: {page.descent})")
1126
+ for font, group in itertools.groupby(
1127
+ page.text, lambda text: text.font):
1128
+ print(f"font: {font.texname.decode('latin-1')!r}\t"
1129
+ f"scale: {font._scale / 2 ** 20}")
1130
+ print("x", "y", "glyph", "chr", "w", "(glyphs)", sep="\t")
1131
+ for text in group:
1132
+ print(text.x, text.y, text.glyph,
1133
+ chr(text.glyph) if chr(text.glyph).isprintable()
1134
+ else ".",
1135
+ text.width, sep="\t")
1136
+ if page.boxes:
1137
+ print("x", "y", "h", "w", "", "(boxes)", sep="\t")
1138
+ for box in page.boxes:
1139
+ print(box.x, box.y, box.height, box.width, sep="\t")
shared/package-files/06/06a5c5ca12950e815126549205bfe3c4e9163f333632943aec12a2411f39d80f/blob ADDED
@@ -0,0 +1,788 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Options manager for :class:`~.Poly` and public API functions. """
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__ = ["Options"]
6
+
7
+ from sympy.core import Basic, sympify
8
+ from sympy.polys.polyerrors import GeneratorsError, OptionError, FlagError
9
+ from sympy.utilities import numbered_symbols, topological_sort, public
10
+ from sympy.utilities.iterables import has_dups, is_sequence
11
+
12
+ import sympy.polys
13
+
14
+ import re
15
+
16
+ class Option:
17
+ """Base class for all kinds of options. """
18
+
19
+ option: str | None = None
20
+
21
+ is_Flag = False
22
+
23
+ requires: list[str] = []
24
+ excludes: list[str] = []
25
+
26
+ after: list[str] = []
27
+ before: list[str] = []
28
+
29
+ @classmethod
30
+ def default(cls):
31
+ return None
32
+
33
+ @classmethod
34
+ def preprocess(cls, option):
35
+ return None
36
+
37
+ @classmethod
38
+ def postprocess(cls, options):
39
+ pass
40
+
41
+
42
+ class Flag(Option):
43
+ """Base class for all kinds of flags. """
44
+
45
+ is_Flag = True
46
+
47
+
48
+ class BooleanOption(Option):
49
+ """An option that must have a boolean value or equivalent assigned. """
50
+
51
+ @classmethod
52
+ def preprocess(cls, value):
53
+ if value in [True, False]:
54
+ return bool(value)
55
+ else:
56
+ raise OptionError("'%s' must have a boolean value assigned, got %s" % (cls.option, value))
57
+
58
+
59
+ class OptionType(type):
60
+ """Base type for all options that does registers options. """
61
+
62
+ def __init__(cls, *args, **kwargs):
63
+ @property
64
+ def getter(self):
65
+ try:
66
+ return self[cls.option]
67
+ except KeyError:
68
+ return cls.default()
69
+
70
+ setattr(Options, cls.option, getter)
71
+ Options.__options__[cls.option] = cls
72
+
73
+
74
+ @public
75
+ class Options(dict):
76
+ """
77
+ Options manager for polynomial manipulation module.
78
+
79
+ Examples
80
+ ========
81
+
82
+ >>> from sympy.polys.polyoptions import Options
83
+ >>> from sympy.polys.polyoptions import build_options
84
+
85
+ >>> from sympy.abc import x, y, z
86
+
87
+ >>> Options((x, y, z), {'domain': 'ZZ'})
88
+ {'auto': False, 'domain': ZZ, 'gens': (x, y, z)}
89
+
90
+ >>> build_options((x, y, z), {'domain': 'ZZ'})
91
+ {'auto': False, 'domain': ZZ, 'gens': (x, y, z)}
92
+
93
+ **Options**
94
+
95
+ * Expand --- boolean option
96
+ * Gens --- option
97
+ * Wrt --- option
98
+ * Sort --- option
99
+ * Order --- option
100
+ * Field --- boolean option
101
+ * Greedy --- boolean option
102
+ * Domain --- option
103
+ * Split --- boolean option
104
+ * Gaussian --- boolean option
105
+ * Extension --- option
106
+ * Modulus --- option
107
+ * Symmetric --- boolean option
108
+ * Strict --- boolean option
109
+
110
+ **Flags**
111
+
112
+ * Auto --- boolean flag
113
+ * Frac --- boolean flag
114
+ * Formal --- boolean flag
115
+ * Polys --- boolean flag
116
+ * Include --- boolean flag
117
+ * All --- boolean flag
118
+ * Gen --- flag
119
+ * Series --- boolean flag
120
+
121
+ """
122
+
123
+ __order__ = None
124
+ __options__: dict[str, type[Option]] = {}
125
+
126
+ def __init__(self, gens, args, flags=None, strict=False):
127
+ dict.__init__(self)
128
+
129
+ if gens and args.get('gens', ()):
130
+ raise OptionError(
131
+ "both '*gens' and keyword argument 'gens' supplied")
132
+ elif gens:
133
+ args = dict(args)
134
+ args['gens'] = gens
135
+
136
+ defaults = args.pop('defaults', {})
137
+
138
+ def preprocess_options(args):
139
+ for option, value in args.items():
140
+ try:
141
+ cls = self.__options__[option]
142
+ except KeyError:
143
+ raise OptionError("'%s' is not a valid option" % option)
144
+
145
+ if issubclass(cls, Flag):
146
+ if flags is None or option not in flags:
147
+ if strict:
148
+ raise OptionError("'%s' flag is not allowed in this context" % option)
149
+
150
+ if value is not None:
151
+ self[option] = cls.preprocess(value)
152
+
153
+ preprocess_options(args)
154
+
155
+ for key, value in dict(defaults).items():
156
+ if key in self:
157
+ del defaults[key]
158
+ else:
159
+ for option in self.keys():
160
+ cls = self.__options__[option]
161
+
162
+ if key in cls.excludes:
163
+ del defaults[key]
164
+ break
165
+
166
+ preprocess_options(defaults)
167
+
168
+ for option in self.keys():
169
+ cls = self.__options__[option]
170
+
171
+ for require_option in cls.requires:
172
+ if self.get(require_option) is None:
173
+ raise OptionError("'%s' option is only allowed together with '%s'" % (option, require_option))
174
+
175
+ for exclude_option in cls.excludes:
176
+ if self.get(exclude_option) is not None:
177
+ raise OptionError("'%s' option is not allowed together with '%s'" % (option, exclude_option))
178
+
179
+ for option in self.__order__:
180
+ self.__options__[option].postprocess(self)
181
+
182
+ @classmethod
183
+ def _init_dependencies_order(cls):
184
+ """Resolve the order of options' processing. """
185
+ if cls.__order__ is None:
186
+ vertices, edges = [], set()
187
+
188
+ for name, option in cls.__options__.items():
189
+ vertices.append(name)
190
+
191
+ for _name in option.after:
192
+ edges.add((_name, name))
193
+
194
+ for _name in option.before:
195
+ edges.add((name, _name))
196
+
197
+ try:
198
+ cls.__order__ = topological_sort((vertices, list(edges)))
199
+ except ValueError:
200
+ raise RuntimeError(
201
+ "cycle detected in sympy.polys options framework")
202
+
203
+ def clone(self, updates={}):
204
+ """Clone ``self`` and update specified options. """
205
+ obj = dict.__new__(self.__class__)
206
+
207
+ for option, value in self.items():
208
+ obj[option] = value
209
+
210
+ for option, value in updates.items():
211
+ obj[option] = value
212
+
213
+ return obj
214
+
215
+ def __setattr__(self, attr, value):
216
+ if attr in self.__options__:
217
+ self[attr] = value
218
+ else:
219
+ super().__setattr__(attr, value)
220
+
221
+ @property
222
+ def args(self):
223
+ args = {}
224
+
225
+ for option, value in self.items():
226
+ if value is not None and option != 'gens':
227
+ cls = self.__options__[option]
228
+
229
+ if not issubclass(cls, Flag):
230
+ args[option] = value
231
+
232
+ return args
233
+
234
+ @property
235
+ def options(self):
236
+ options = {}
237
+
238
+ for option, cls in self.__options__.items():
239
+ if not issubclass(cls, Flag):
240
+ options[option] = getattr(self, option)
241
+
242
+ return options
243
+
244
+ @property
245
+ def flags(self):
246
+ flags = {}
247
+
248
+ for option, cls in self.__options__.items():
249
+ if issubclass(cls, Flag):
250
+ flags[option] = getattr(self, option)
251
+
252
+ return flags
253
+
254
+
255
+ class Expand(BooleanOption, metaclass=OptionType):
256
+ """``expand`` option to polynomial manipulation functions. """
257
+
258
+ option = 'expand'
259
+
260
+ requires: list[str] = []
261
+ excludes: list[str] = []
262
+
263
+ @classmethod
264
+ def default(cls):
265
+ return True
266
+
267
+
268
+ class Gens(Option, metaclass=OptionType):
269
+ """``gens`` option to polynomial manipulation functions. """
270
+
271
+ option = 'gens'
272
+
273
+ requires: list[str] = []
274
+ excludes: list[str] = []
275
+
276
+ @classmethod
277
+ def default(cls):
278
+ return ()
279
+
280
+ @classmethod
281
+ def preprocess(cls, gens):
282
+ if isinstance(gens, Basic):
283
+ gens = (gens,)
284
+ elif len(gens) == 1 and is_sequence(gens[0]):
285
+ gens = gens[0]
286
+
287
+ if gens == (None,):
288
+ gens = ()
289
+ elif has_dups(gens):
290
+ raise GeneratorsError("duplicated generators: %s" % str(gens))
291
+ elif any(gen.is_commutative is False for gen in gens):
292
+ raise GeneratorsError("non-commutative generators: %s" % str(gens))
293
+
294
+ return tuple(gens)
295
+
296
+
297
+ class Wrt(Option, metaclass=OptionType):
298
+ """``wrt`` option to polynomial manipulation functions. """
299
+
300
+ option = 'wrt'
301
+
302
+ requires: list[str] = []
303
+ excludes: list[str] = []
304
+
305
+ _re_split = re.compile(r"\s*,\s*|\s+")
306
+
307
+ @classmethod
308
+ def preprocess(cls, wrt):
309
+ if isinstance(wrt, Basic):
310
+ return [str(wrt)]
311
+ elif isinstance(wrt, str):
312
+ wrt = wrt.strip()
313
+ if wrt.endswith(','):
314
+ raise OptionError('Bad input: missing parameter.')
315
+ if not wrt:
316
+ return []
317
+ return list(cls._re_split.split(wrt))
318
+ elif hasattr(wrt, '__getitem__'):
319
+ return list(map(str, wrt))
320
+ else:
321
+ raise OptionError("invalid argument for 'wrt' option")
322
+
323
+
324
+ class Sort(Option, metaclass=OptionType):
325
+ """``sort`` option to polynomial manipulation functions. """
326
+
327
+ option = 'sort'
328
+
329
+ requires: list[str] = []
330
+ excludes: list[str] = []
331
+
332
+ @classmethod
333
+ def default(cls):
334
+ return []
335
+
336
+ @classmethod
337
+ def preprocess(cls, sort):
338
+ if isinstance(sort, str):
339
+ return [ gen.strip() for gen in sort.split('>') ]
340
+ elif hasattr(sort, '__getitem__'):
341
+ return list(map(str, sort))
342
+ else:
343
+ raise OptionError("invalid argument for 'sort' option")
344
+
345
+
346
+ class Order(Option, metaclass=OptionType):
347
+ """``order`` option to polynomial manipulation functions. """
348
+
349
+ option = 'order'
350
+
351
+ requires: list[str] = []
352
+ excludes: list[str] = []
353
+
354
+ @classmethod
355
+ def default(cls):
356
+ return sympy.polys.orderings.lex
357
+
358
+ @classmethod
359
+ def preprocess(cls, order):
360
+ return sympy.polys.orderings.monomial_key(order)
361
+
362
+
363
+ class Field(BooleanOption, metaclass=OptionType):
364
+ """``field`` option to polynomial manipulation functions. """
365
+
366
+ option = 'field'
367
+
368
+ requires: list[str] = []
369
+ excludes = ['domain', 'split', 'gaussian']
370
+
371
+
372
+ class Greedy(BooleanOption, metaclass=OptionType):
373
+ """``greedy`` option to polynomial manipulation functions. """
374
+
375
+ option = 'greedy'
376
+
377
+ requires: list[str] = []
378
+ excludes = ['domain', 'split', 'gaussian', 'extension', 'modulus', 'symmetric']
379
+
380
+
381
+ class Composite(BooleanOption, metaclass=OptionType):
382
+ """``composite`` option to polynomial manipulation functions. """
383
+
384
+ option = 'composite'
385
+
386
+ @classmethod
387
+ def default(cls):
388
+ return None
389
+
390
+ requires: list[str] = []
391
+ excludes = ['domain', 'split', 'gaussian', 'extension', 'modulus', 'symmetric']
392
+
393
+
394
+ class Domain(Option, metaclass=OptionType):
395
+ """``domain`` option to polynomial manipulation functions. """
396
+
397
+ option = 'domain'
398
+
399
+ requires: list[str] = []
400
+ excludes = ['field', 'greedy', 'split', 'gaussian', 'extension']
401
+
402
+ after = ['gens']
403
+
404
+ _re_realfield = re.compile(r"^(R|RR)(_(\d+))?$")
405
+ _re_complexfield = re.compile(r"^(C|CC)(_(\d+))?$")
406
+ _re_finitefield = re.compile(r"^(FF|GF)\((\d+)\)$")
407
+ _re_polynomial = re.compile(r"^(Z|ZZ|Q|QQ|ZZ_I|QQ_I|R|RR|C|CC)\[(.+)\]$")
408
+ _re_fraction = re.compile(r"^(Z|ZZ|Q|QQ)\((.+)\)$")
409
+ _re_algebraic = re.compile(r"^(Q|QQ)\<(.+)\>$")
410
+
411
+ @classmethod
412
+ def preprocess(cls, domain):
413
+ if isinstance(domain, sympy.polys.domains.Domain):
414
+ return domain
415
+ elif hasattr(domain, 'to_domain'):
416
+ return domain.to_domain()
417
+ elif isinstance(domain, str):
418
+ if domain in ['Z', 'ZZ']:
419
+ return sympy.polys.domains.ZZ
420
+
421
+ if domain in ['Q', 'QQ']:
422
+ return sympy.polys.domains.QQ
423
+
424
+ if domain == 'ZZ_I':
425
+ return sympy.polys.domains.ZZ_I
426
+
427
+ if domain == 'QQ_I':
428
+ return sympy.polys.domains.QQ_I
429
+
430
+ if domain == 'EX':
431
+ return sympy.polys.domains.EX
432
+
433
+ r = cls._re_realfield.match(domain)
434
+
435
+ if r is not None:
436
+ _, _, prec = r.groups()
437
+
438
+ if prec is None:
439
+ return sympy.polys.domains.RR
440
+ else:
441
+ return sympy.polys.domains.RealField(int(prec))
442
+
443
+ r = cls._re_complexfield.match(domain)
444
+
445
+ if r is not None:
446
+ _, _, prec = r.groups()
447
+
448
+ if prec is None:
449
+ return sympy.polys.domains.CC
450
+ else:
451
+ return sympy.polys.domains.ComplexField(int(prec))
452
+
453
+ r = cls._re_finitefield.match(domain)
454
+
455
+ if r is not None:
456
+ return sympy.polys.domains.FF(int(r.groups()[1]))
457
+
458
+ r = cls._re_polynomial.match(domain)
459
+
460
+ if r is not None:
461
+ ground, gens = r.groups()
462
+
463
+ gens = list(map(sympify, gens.split(',')))
464
+
465
+ if ground in ['Z', 'ZZ']:
466
+ return sympy.polys.domains.ZZ.poly_ring(*gens)
467
+ elif ground in ['Q', 'QQ']:
468
+ return sympy.polys.domains.QQ.poly_ring(*gens)
469
+ elif ground in ['R', 'RR']:
470
+ return sympy.polys.domains.RR.poly_ring(*gens)
471
+ elif ground == 'ZZ_I':
472
+ return sympy.polys.domains.ZZ_I.poly_ring(*gens)
473
+ elif ground == 'QQ_I':
474
+ return sympy.polys.domains.QQ_I.poly_ring(*gens)
475
+ else:
476
+ return sympy.polys.domains.CC.poly_ring(*gens)
477
+
478
+ r = cls._re_fraction.match(domain)
479
+
480
+ if r is not None:
481
+ ground, gens = r.groups()
482
+
483
+ gens = list(map(sympify, gens.split(',')))
484
+
485
+ if ground in ['Z', 'ZZ']:
486
+ return sympy.polys.domains.ZZ.frac_field(*gens)
487
+ else:
488
+ return sympy.polys.domains.QQ.frac_field(*gens)
489
+
490
+ r = cls._re_algebraic.match(domain)
491
+
492
+ if r is not None:
493
+ gens = list(map(sympify, r.groups()[1].split(',')))
494
+ return sympy.polys.domains.QQ.algebraic_field(*gens)
495
+
496
+ raise OptionError('expected a valid domain specification, got %s' % domain)
497
+
498
+ @classmethod
499
+ def postprocess(cls, options):
500
+ if 'gens' in options and 'domain' in options and options['domain'].is_Composite and \
501
+ (set(options['domain'].symbols) & set(options['gens'])):
502
+ raise GeneratorsError(
503
+ "ground domain and generators interfere together")
504
+ elif ('gens' not in options or not options['gens']) and \
505
+ 'domain' in options and options['domain'] == sympy.polys.domains.EX:
506
+ raise GeneratorsError("you have to provide generators because EX domain was requested")
507
+
508
+
509
+ class Split(BooleanOption, metaclass=OptionType):
510
+ """``split`` option to polynomial manipulation functions. """
511
+
512
+ option = 'split'
513
+
514
+ requires: list[str] = []
515
+ excludes = ['field', 'greedy', 'domain', 'gaussian', 'extension',
516
+ 'modulus', 'symmetric']
517
+
518
+ @classmethod
519
+ def postprocess(cls, options):
520
+ if 'split' in options:
521
+ raise NotImplementedError("'split' option is not implemented yet")
522
+
523
+
524
+ class Gaussian(BooleanOption, metaclass=OptionType):
525
+ """``gaussian`` option to polynomial manipulation functions. """
526
+
527
+ option = 'gaussian'
528
+
529
+ requires: list[str] = []
530
+ excludes = ['field', 'greedy', 'domain', 'split', 'extension',
531
+ 'modulus', 'symmetric']
532
+
533
+ @classmethod
534
+ def postprocess(cls, options):
535
+ if 'gaussian' in options and options['gaussian'] is True:
536
+ options['domain'] = sympy.polys.domains.QQ_I
537
+ Extension.postprocess(options)
538
+
539
+
540
+ class Extension(Option, metaclass=OptionType):
541
+ """``extension`` option to polynomial manipulation functions. """
542
+
543
+ option = 'extension'
544
+
545
+ requires: list[str] = []
546
+ excludes = ['greedy', 'domain', 'split', 'gaussian', 'modulus',
547
+ 'symmetric']
548
+
549
+ @classmethod
550
+ def preprocess(cls, extension):
551
+ if extension == 1:
552
+ return bool(extension)
553
+ elif extension == 0:
554
+ raise OptionError("'False' is an invalid argument for 'extension'")
555
+ else:
556
+ if not hasattr(extension, '__iter__'):
557
+ extension = {extension}
558
+ else:
559
+ if not extension:
560
+ extension = None
561
+ else:
562
+ extension = set(extension)
563
+
564
+ return extension
565
+
566
+ @classmethod
567
+ def postprocess(cls, options):
568
+ if 'extension' in options and options['extension'] is not True:
569
+ options['domain'] = sympy.polys.domains.QQ.algebraic_field(
570
+ *options['extension'])
571
+
572
+
573
+ class Modulus(Option, metaclass=OptionType):
574
+ """``modulus`` option to polynomial manipulation functions. """
575
+
576
+ option = 'modulus'
577
+
578
+ requires: list[str] = []
579
+ excludes = ['greedy', 'split', 'domain', 'gaussian', 'extension']
580
+
581
+ @classmethod
582
+ def preprocess(cls, modulus):
583
+ modulus = sympify(modulus)
584
+
585
+ if modulus.is_Integer and modulus > 0:
586
+ return int(modulus)
587
+ else:
588
+ raise OptionError(
589
+ "'modulus' must a positive integer, got %s" % modulus)
590
+
591
+ @classmethod
592
+ def postprocess(cls, options):
593
+ if 'modulus' in options:
594
+ modulus = options['modulus']
595
+ symmetric = options.get('symmetric', True)
596
+ options['domain'] = sympy.polys.domains.FF(modulus, symmetric)
597
+
598
+
599
+ class Symmetric(BooleanOption, metaclass=OptionType):
600
+ """``symmetric`` option to polynomial manipulation functions. """
601
+
602
+ option = 'symmetric'
603
+
604
+ requires = ['modulus']
605
+ excludes = ['greedy', 'domain', 'split', 'gaussian', 'extension']
606
+
607
+
608
+ class Strict(BooleanOption, metaclass=OptionType):
609
+ """``strict`` option to polynomial manipulation functions. """
610
+
611
+ option = 'strict'
612
+
613
+ @classmethod
614
+ def default(cls):
615
+ return True
616
+
617
+
618
+ class Auto(BooleanOption, Flag, metaclass=OptionType):
619
+ """``auto`` flag to polynomial manipulation functions. """
620
+
621
+ option = 'auto'
622
+
623
+ after = ['field', 'domain', 'extension', 'gaussian']
624
+
625
+ @classmethod
626
+ def default(cls):
627
+ return True
628
+
629
+ @classmethod
630
+ def postprocess(cls, options):
631
+ if ('domain' in options or 'field' in options) and 'auto' not in options:
632
+ options['auto'] = False
633
+
634
+
635
+ class Frac(BooleanOption, Flag, metaclass=OptionType):
636
+ """``auto`` option to polynomial manipulation functions. """
637
+
638
+ option = 'frac'
639
+
640
+ @classmethod
641
+ def default(cls):
642
+ return False
643
+
644
+
645
+ class Formal(BooleanOption, Flag, metaclass=OptionType):
646
+ """``formal`` flag to polynomial manipulation functions. """
647
+
648
+ option = 'formal'
649
+
650
+ @classmethod
651
+ def default(cls):
652
+ return False
653
+
654
+
655
+ class Polys(BooleanOption, Flag, metaclass=OptionType):
656
+ """``polys`` flag to polynomial manipulation functions. """
657
+
658
+ option = 'polys'
659
+
660
+
661
+ class Include(BooleanOption, Flag, metaclass=OptionType):
662
+ """``include`` flag to polynomial manipulation functions. """
663
+
664
+ option = 'include'
665
+
666
+ @classmethod
667
+ def default(cls):
668
+ return False
669
+
670
+
671
+ class All(BooleanOption, Flag, metaclass=OptionType):
672
+ """``all`` flag to polynomial manipulation functions. """
673
+
674
+ option = 'all'
675
+
676
+ @classmethod
677
+ def default(cls):
678
+ return False
679
+
680
+
681
+ class Gen(Flag, metaclass=OptionType):
682
+ """``gen`` flag to polynomial manipulation functions. """
683
+
684
+ option = 'gen'
685
+
686
+ @classmethod
687
+ def default(cls):
688
+ return 0
689
+
690
+ @classmethod
691
+ def preprocess(cls, gen):
692
+ if isinstance(gen, (Basic, int)):
693
+ return gen
694
+ else:
695
+ raise OptionError("invalid argument for 'gen' option")
696
+
697
+
698
+ class Series(BooleanOption, Flag, metaclass=OptionType):
699
+ """``series`` flag to polynomial manipulation functions. """
700
+
701
+ option = 'series'
702
+
703
+ @classmethod
704
+ def default(cls):
705
+ return False
706
+
707
+
708
+ class Symbols(Flag, metaclass=OptionType):
709
+ """``symbols`` flag to polynomial manipulation functions. """
710
+
711
+ option = 'symbols'
712
+
713
+ @classmethod
714
+ def default(cls):
715
+ return numbered_symbols('s', start=1)
716
+
717
+ @classmethod
718
+ def preprocess(cls, symbols):
719
+ if hasattr(symbols, '__iter__'):
720
+ return iter(symbols)
721
+ else:
722
+ raise OptionError("expected an iterator or iterable container, got %s" % symbols)
723
+
724
+
725
+ class Method(Flag, metaclass=OptionType):
726
+ """``method`` flag to polynomial manipulation functions. """
727
+
728
+ option = 'method'
729
+
730
+ @classmethod
731
+ def preprocess(cls, method):
732
+ if isinstance(method, str):
733
+ return method.lower()
734
+ else:
735
+ raise OptionError("expected a string, got %s" % method)
736
+
737
+
738
+ def build_options(gens, args=None):
739
+ """Construct options from keyword arguments or ... options. """
740
+ if args is None:
741
+ gens, args = (), gens
742
+
743
+ if len(args) != 1 or 'opt' not in args or gens:
744
+ return Options(gens, args)
745
+ else:
746
+ return args['opt']
747
+
748
+
749
+ def allowed_flags(args, flags):
750
+ """
751
+ Allow specified flags to be used in the given context.
752
+
753
+ Examples
754
+ ========
755
+
756
+ >>> from sympy.polys.polyoptions import allowed_flags
757
+ >>> from sympy.polys.domains import ZZ
758
+
759
+ >>> allowed_flags({'domain': ZZ}, [])
760
+
761
+ >>> allowed_flags({'domain': ZZ, 'frac': True}, [])
762
+ Traceback (most recent call last):
763
+ ...
764
+ FlagError: 'frac' flag is not allowed in this context
765
+
766
+ >>> allowed_flags({'domain': ZZ, 'frac': True}, ['frac'])
767
+
768
+ """
769
+ flags = set(flags)
770
+
771
+ for arg in args.keys():
772
+ try:
773
+ if Options.__options__[arg].is_Flag and arg not in flags:
774
+ raise FlagError(
775
+ "'%s' flag is not allowed in this context" % arg)
776
+ except KeyError:
777
+ raise OptionError("'%s' is not a valid option" % arg)
778
+
779
+
780
+ def set_defaults(options, **defaults):
781
+ """Update options with default values. """
782
+ if 'defaults' not in options:
783
+ options = dict(options)
784
+ options['defaults'] = defaults
785
+
786
+ return options
787
+
788
+ Options._init_dependencies_order()
shared/package-files/06/06a76dad17702ab297ea355df38eb0d44f9707ac4a0e8d0e73291ee6aa4ab3af/blob ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API bool is_set_to(const at::Tensor & self, const at::Tensor & tensor);
20
+ } // namespace native
21
+ } // namespace at
shared/package-files/06/06afee4a9a5e3b6753f3cc5af979dc409fe959763cb7dedb2c632bc8c21a8bc4/blob ADDED
@@ -0,0 +1,960 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from typing import List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ from torch import Tensor
6
+ from torch.nn.functional import conv2d, grid_sample, interpolate, pad as torch_pad
7
+
8
+
9
+ def _is_tensor_a_torch_image(x: Tensor) -> bool:
10
+ return x.ndim >= 2
11
+
12
+
13
+ def _assert_image_tensor(img: Tensor) -> None:
14
+ if not _is_tensor_a_torch_image(img):
15
+ raise TypeError("Tensor is not a torch image.")
16
+
17
+
18
+ def get_dimensions(img: Tensor) -> List[int]:
19
+ _assert_image_tensor(img)
20
+ channels = 1 if img.ndim == 2 else img.shape[-3]
21
+ height, width = img.shape[-2:]
22
+ return [channels, height, width]
23
+
24
+
25
+ def get_image_size(img: Tensor) -> List[int]:
26
+ # Returns (w, h) of tensor image
27
+ _assert_image_tensor(img)
28
+ return [img.shape[-1], img.shape[-2]]
29
+
30
+
31
+ def get_image_num_channels(img: Tensor) -> int:
32
+ _assert_image_tensor(img)
33
+ if img.ndim == 2:
34
+ return 1
35
+ elif img.ndim > 2:
36
+ return img.shape[-3]
37
+
38
+ raise TypeError(f"Input ndim should be 2 or more. Got {img.ndim}")
39
+
40
+
41
+ def _max_value(dtype: torch.dtype) -> int:
42
+ if dtype == torch.uint8:
43
+ return 255
44
+ elif dtype == torch.int8:
45
+ return 127
46
+ elif dtype == torch.int16:
47
+ return 32767
48
+ elif dtype == torch.int32:
49
+ return 2147483647
50
+ elif dtype == torch.int64:
51
+ return 9223372036854775807
52
+ else:
53
+ # This is only here for completeness. This value is implicitly assumed in a lot of places so changing it is not
54
+ # easy.
55
+ return 1
56
+
57
+
58
+ def _assert_channels(img: Tensor, permitted: List[int]) -> None:
59
+ c = get_dimensions(img)[0]
60
+ if c not in permitted:
61
+ raise TypeError(f"Input image tensor permitted channel values are {permitted}, but found {c}")
62
+
63
+
64
+ def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype = torch.float) -> torch.Tensor:
65
+ if image.dtype == dtype:
66
+ return image
67
+
68
+ if image.is_floating_point():
69
+
70
+ # TODO: replace with dtype.is_floating_point when torchscript supports it
71
+ if torch.tensor(0, dtype=dtype).is_floating_point():
72
+ return image.to(dtype)
73
+
74
+ # float to int
75
+ if (image.dtype == torch.float32 and dtype in (torch.int32, torch.int64)) or (
76
+ image.dtype == torch.float64 and dtype == torch.int64
77
+ ):
78
+ msg = f"The cast from {image.dtype} to {dtype} cannot be performed safely."
79
+ raise RuntimeError(msg)
80
+
81
+ # https://github.com/pytorch/vision/pull/2078#issuecomment-612045321
82
+ # For data in the range 0-1, (float * 255).to(uint) is only 255
83
+ # when float is exactly 1.0.
84
+ # `max + 1 - epsilon` provides more evenly distributed mapping of
85
+ # ranges of floats to ints.
86
+ eps = 1e-3
87
+ max_val = float(_max_value(dtype))
88
+ result = image.mul(max_val + 1.0 - eps)
89
+ return result.to(dtype)
90
+ else:
91
+ input_max = float(_max_value(image.dtype))
92
+
93
+ # int to float
94
+ # TODO: replace with dtype.is_floating_point when torchscript supports it
95
+ if torch.tensor(0, dtype=dtype).is_floating_point():
96
+ image = image.to(dtype)
97
+ return image / input_max
98
+
99
+ output_max = float(_max_value(dtype))
100
+
101
+ # int to int
102
+ if input_max > output_max:
103
+ # factor should be forced to int for torch jit script
104
+ # otherwise factor is a float and image // factor can produce different results
105
+ factor = int((input_max + 1) // (output_max + 1))
106
+ image = torch.div(image, factor, rounding_mode="floor")
107
+ return image.to(dtype)
108
+ else:
109
+ # factor should be forced to int for torch jit script
110
+ # otherwise factor is a float and image * factor can produce different results
111
+ factor = int((output_max + 1) // (input_max + 1))
112
+ image = image.to(dtype)
113
+ return image * factor
114
+
115
+
116
+ def vflip(img: Tensor) -> Tensor:
117
+ _assert_image_tensor(img)
118
+
119
+ return img.flip(-2)
120
+
121
+
122
+ def hflip(img: Tensor) -> Tensor:
123
+ _assert_image_tensor(img)
124
+
125
+ return img.flip(-1)
126
+
127
+
128
+ def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor:
129
+ _assert_image_tensor(img)
130
+
131
+ _, h, w = get_dimensions(img)
132
+ right = left + width
133
+ bottom = top + height
134
+
135
+ if left < 0 or top < 0 or right > w or bottom > h:
136
+ padding_ltrb = [
137
+ max(-left + min(0, right), 0),
138
+ max(-top + min(0, bottom), 0),
139
+ max(right - max(w, left), 0),
140
+ max(bottom - max(h, top), 0),
141
+ ]
142
+ return pad(img[..., max(top, 0) : bottom, max(left, 0) : right], padding_ltrb, fill=0)
143
+ return img[..., top:bottom, left:right]
144
+
145
+
146
+ def rgb_to_grayscale(img: Tensor, num_output_channels: int = 1) -> Tensor:
147
+ if img.ndim < 3:
148
+ raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}")
149
+ _assert_channels(img, [1, 3])
150
+
151
+ if num_output_channels not in (1, 3):
152
+ raise ValueError("num_output_channels should be either 1 or 3")
153
+
154
+ if img.shape[-3] == 3:
155
+ r, g, b = img.unbind(dim=-3)
156
+ # This implementation closely follows the TF one:
157
+ # https://github.com/tensorflow/tensorflow/blob/v2.3.0/tensorflow/python/ops/image_ops_impl.py#L2105-L2138
158
+ l_img = (0.2989 * r + 0.587 * g + 0.114 * b).to(img.dtype)
159
+ l_img = l_img.unsqueeze(dim=-3)
160
+ else:
161
+ l_img = img.clone()
162
+
163
+ if num_output_channels == 3:
164
+ return l_img.expand(img.shape)
165
+
166
+ return l_img
167
+
168
+
169
+ def adjust_brightness(img: Tensor, brightness_factor: float) -> Tensor:
170
+ if brightness_factor < 0:
171
+ raise ValueError(f"brightness_factor ({brightness_factor}) is not non-negative.")
172
+
173
+ _assert_image_tensor(img)
174
+
175
+ _assert_channels(img, [1, 3])
176
+
177
+ return _blend(img, torch.zeros_like(img), brightness_factor)
178
+
179
+
180
+ def adjust_contrast(img: Tensor, contrast_factor: float) -> Tensor:
181
+ if contrast_factor < 0:
182
+ raise ValueError(f"contrast_factor ({contrast_factor}) is not non-negative.")
183
+
184
+ _assert_image_tensor(img)
185
+
186
+ _assert_channels(img, [3, 1])
187
+ c = get_dimensions(img)[0]
188
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
189
+ if c == 3:
190
+ mean = torch.mean(rgb_to_grayscale(img).to(dtype), dim=(-3, -2, -1), keepdim=True)
191
+ else:
192
+ mean = torch.mean(img.to(dtype), dim=(-3, -2, -1), keepdim=True)
193
+
194
+ return _blend(img, mean, contrast_factor)
195
+
196
+
197
+ def adjust_hue(img: Tensor, hue_factor: float) -> Tensor:
198
+ if not (-0.5 <= hue_factor <= 0.5):
199
+ raise ValueError(f"hue_factor ({hue_factor}) is not in [-0.5, 0.5].")
200
+
201
+ if not (isinstance(img, torch.Tensor)):
202
+ raise TypeError("Input img should be Tensor image")
203
+
204
+ _assert_image_tensor(img)
205
+
206
+ _assert_channels(img, [1, 3])
207
+ if get_dimensions(img)[0] == 1: # Match PIL behaviour
208
+ return img
209
+
210
+ orig_dtype = img.dtype
211
+ img = convert_image_dtype(img, torch.float32)
212
+
213
+ img = _rgb2hsv(img)
214
+ h, s, v = img.unbind(dim=-3)
215
+ h = (h + hue_factor) % 1.0
216
+ img = torch.stack((h, s, v), dim=-3)
217
+ img_hue_adj = _hsv2rgb(img)
218
+
219
+ return convert_image_dtype(img_hue_adj, orig_dtype)
220
+
221
+
222
+ def adjust_saturation(img: Tensor, saturation_factor: float) -> Tensor:
223
+ if saturation_factor < 0:
224
+ raise ValueError(f"saturation_factor ({saturation_factor}) is not non-negative.")
225
+
226
+ _assert_image_tensor(img)
227
+
228
+ _assert_channels(img, [1, 3])
229
+
230
+ if get_dimensions(img)[0] == 1: # Match PIL behaviour
231
+ return img
232
+
233
+ return _blend(img, rgb_to_grayscale(img), saturation_factor)
234
+
235
+
236
+ def adjust_gamma(img: Tensor, gamma: float, gain: float = 1) -> Tensor:
237
+ if not isinstance(img, torch.Tensor):
238
+ raise TypeError("Input img should be a Tensor.")
239
+
240
+ _assert_channels(img, [1, 3])
241
+
242
+ if gamma < 0:
243
+ raise ValueError("Gamma should be a non-negative real number")
244
+
245
+ result = img
246
+ dtype = img.dtype
247
+ if not torch.is_floating_point(img):
248
+ result = convert_image_dtype(result, torch.float32)
249
+
250
+ result = (gain * result**gamma).clamp(0, 1)
251
+
252
+ result = convert_image_dtype(result, dtype)
253
+ return result
254
+
255
+
256
+ def _blend(img1: Tensor, img2: Tensor, ratio: float) -> Tensor:
257
+ ratio = float(ratio)
258
+ bound = _max_value(img1.dtype)
259
+ return (ratio * img1 + (1.0 - ratio) * img2).clamp(0, bound).to(img1.dtype)
260
+
261
+
262
+ def _rgb2hsv(img: Tensor) -> Tensor:
263
+ r, g, b = img.unbind(dim=-3)
264
+
265
+ # Implementation is based on https://github.com/python-pillow/Pillow/blob/4174d4267616897df3746d315d5a2d0f82c656ee/
266
+ # src/libImaging/Convert.c#L330
267
+ maxc = torch.max(img, dim=-3).values
268
+ minc = torch.min(img, dim=-3).values
269
+
270
+ # The algorithm erases S and H channel where `maxc = minc`. This avoids NaN
271
+ # from happening in the results, because
272
+ # + S channel has division by `maxc`, which is zero only if `maxc = minc`
273
+ # + H channel has division by `(maxc - minc)`.
274
+ #
275
+ # Instead of overwriting NaN afterwards, we just prevent it from occurring, so
276
+ # we don't need to deal with it in case we save the NaN in a buffer in
277
+ # backprop, if it is ever supported, but it doesn't hurt to do so.
278
+ eqc = maxc == minc
279
+
280
+ cr = maxc - minc
281
+ # Since `eqc => cr = 0`, replacing denominator with 1 when `eqc` is fine.
282
+ ones = torch.ones_like(maxc)
283
+ s = cr / torch.where(eqc, ones, maxc)
284
+ # Note that `eqc => maxc = minc = r = g = b`. So the following calculation
285
+ # of `h` would reduce to `bc - gc + 2 + rc - bc + 4 + rc - bc = 6` so it
286
+ # would not matter what values `rc`, `gc`, and `bc` have here, and thus
287
+ # replacing denominator with 1 when `eqc` is fine.
288
+ cr_divisor = torch.where(eqc, ones, cr)
289
+ rc = (maxc - r) / cr_divisor
290
+ gc = (maxc - g) / cr_divisor
291
+ bc = (maxc - b) / cr_divisor
292
+
293
+ hr = (maxc == r) * (bc - gc)
294
+ hg = ((maxc == g) & (maxc != r)) * (2.0 + rc - bc)
295
+ hb = ((maxc != g) & (maxc != r)) * (4.0 + gc - rc)
296
+ h = hr + hg + hb
297
+ h = torch.fmod((h / 6.0 + 1.0), 1.0)
298
+ return torch.stack((h, s, maxc), dim=-3)
299
+
300
+
301
+ def _hsv2rgb(img: Tensor) -> Tensor:
302
+ h, s, v = img.unbind(dim=-3)
303
+ i = torch.floor(h * 6.0)
304
+ f = (h * 6.0) - i
305
+ i = i.to(dtype=torch.int32)
306
+
307
+ p = torch.clamp((v * (1.0 - s)), 0.0, 1.0)
308
+ q = torch.clamp((v * (1.0 - s * f)), 0.0, 1.0)
309
+ t = torch.clamp((v * (1.0 - s * (1.0 - f))), 0.0, 1.0)
310
+ i = i % 6
311
+
312
+ mask = i.unsqueeze(dim=-3) == torch.arange(6, device=i.device).view(-1, 1, 1)
313
+
314
+ a1 = torch.stack((v, q, p, p, t, v), dim=-3)
315
+ a2 = torch.stack((t, v, v, q, p, p), dim=-3)
316
+ a3 = torch.stack((p, p, t, v, v, q), dim=-3)
317
+ a4 = torch.stack((a1, a2, a3), dim=-4)
318
+
319
+ return torch.einsum("...ijk, ...xijk -> ...xjk", mask.to(dtype=img.dtype), a4)
320
+
321
+
322
+ def _pad_symmetric(img: Tensor, padding: List[int]) -> Tensor:
323
+ # padding is left, right, top, bottom
324
+
325
+ # crop if needed
326
+ if padding[0] < 0 or padding[1] < 0 or padding[2] < 0 or padding[3] < 0:
327
+ neg_min_padding = [-min(x, 0) for x in padding]
328
+ crop_left, crop_right, crop_top, crop_bottom = neg_min_padding
329
+ img = img[..., crop_top : img.shape[-2] - crop_bottom, crop_left : img.shape[-1] - crop_right]
330
+ padding = [max(x, 0) for x in padding]
331
+
332
+ in_sizes = img.size()
333
+
334
+ _x_indices = [i for i in range(in_sizes[-1])] # [0, 1, 2, 3, ...]
335
+ left_indices = [i for i in range(padding[0] - 1, -1, -1)] # e.g. [3, 2, 1, 0]
336
+ right_indices = [-(i + 1) for i in range(padding[1])] # e.g. [-1, -2, -3]
337
+ x_indices = torch.tensor(left_indices + _x_indices + right_indices, device=img.device)
338
+
339
+ _y_indices = [i for i in range(in_sizes[-2])]
340
+ top_indices = [i for i in range(padding[2] - 1, -1, -1)]
341
+ bottom_indices = [-(i + 1) for i in range(padding[3])]
342
+ y_indices = torch.tensor(top_indices + _y_indices + bottom_indices, device=img.device)
343
+
344
+ ndim = img.ndim
345
+ if ndim == 3:
346
+ return img[:, y_indices[:, None], x_indices[None, :]]
347
+ elif ndim == 4:
348
+ return img[:, :, y_indices[:, None], x_indices[None, :]]
349
+ else:
350
+ raise RuntimeError("Symmetric padding of N-D tensors are not supported yet")
351
+
352
+
353
+ def _parse_pad_padding(padding: Union[int, List[int]]) -> List[int]:
354
+ if isinstance(padding, int):
355
+ if torch.jit.is_scripting():
356
+ # This maybe unreachable
357
+ raise ValueError("padding can't be an int while torchscripting, set it as a list [value, ]")
358
+ pad_left = pad_right = pad_top = pad_bottom = padding
359
+ elif len(padding) == 1:
360
+ pad_left = pad_right = pad_top = pad_bottom = padding[0]
361
+ elif len(padding) == 2:
362
+ pad_left = pad_right = padding[0]
363
+ pad_top = pad_bottom = padding[1]
364
+ else:
365
+ pad_left = padding[0]
366
+ pad_top = padding[1]
367
+ pad_right = padding[2]
368
+ pad_bottom = padding[3]
369
+
370
+ return [pad_left, pad_right, pad_top, pad_bottom]
371
+
372
+
373
+ def pad(
374
+ img: Tensor, padding: Union[int, List[int]], fill: Optional[Union[int, float]] = 0, padding_mode: str = "constant"
375
+ ) -> Tensor:
376
+ _assert_image_tensor(img)
377
+
378
+ if fill is None:
379
+ fill = 0
380
+
381
+ if not isinstance(padding, (int, tuple, list)):
382
+ raise TypeError("Got inappropriate padding arg")
383
+ if not isinstance(fill, (int, float)):
384
+ raise TypeError("Got inappropriate fill arg")
385
+ if not isinstance(padding_mode, str):
386
+ raise TypeError("Got inappropriate padding_mode arg")
387
+
388
+ if isinstance(padding, tuple):
389
+ padding = list(padding)
390
+
391
+ if isinstance(padding, list):
392
+ # TODO: Jit is failing on loading this op when scripted and saved
393
+ # https://github.com/pytorch/pytorch/issues/81100
394
+ if len(padding) not in [1, 2, 4]:
395
+ raise ValueError(
396
+ f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple"
397
+ )
398
+
399
+ if padding_mode not in ["constant", "edge", "reflect", "symmetric"]:
400
+ raise ValueError("Padding mode should be either constant, edge, reflect or symmetric")
401
+
402
+ p = _parse_pad_padding(padding)
403
+
404
+ if padding_mode == "edge":
405
+ # remap padding_mode str
406
+ padding_mode = "replicate"
407
+ elif padding_mode == "symmetric":
408
+ # route to another implementation
409
+ return _pad_symmetric(img, p)
410
+
411
+ need_squeeze = False
412
+ if img.ndim < 4:
413
+ img = img.unsqueeze(dim=0)
414
+ need_squeeze = True
415
+
416
+ out_dtype = img.dtype
417
+ need_cast = False
418
+ if (padding_mode != "constant") and img.dtype not in (torch.float32, torch.float64):
419
+ # Here we temporarily cast input tensor to float
420
+ # until pytorch issue is resolved :
421
+ # https://github.com/pytorch/pytorch/issues/40763
422
+ need_cast = True
423
+ img = img.to(torch.float32)
424
+
425
+ if padding_mode in ("reflect", "replicate"):
426
+ img = torch_pad(img, p, mode=padding_mode)
427
+ else:
428
+ img = torch_pad(img, p, mode=padding_mode, value=float(fill))
429
+
430
+ if need_squeeze:
431
+ img = img.squeeze(dim=0)
432
+
433
+ if need_cast:
434
+ img = img.to(out_dtype)
435
+
436
+ return img
437
+
438
+
439
+ def resize(
440
+ img: Tensor,
441
+ size: List[int],
442
+ interpolation: str = "bilinear",
443
+ antialias: Optional[bool] = True,
444
+ ) -> Tensor:
445
+ _assert_image_tensor(img)
446
+
447
+ if isinstance(size, tuple):
448
+ size = list(size)
449
+
450
+ if antialias is None:
451
+ antialias = False
452
+
453
+ if antialias and interpolation not in ["bilinear", "bicubic"]:
454
+ # We manually set it to False to avoid an error downstream in interpolate()
455
+ # This behaviour is documented: the parameter is irrelevant for modes
456
+ # that are not bilinear or bicubic. We used to raise an error here, but
457
+ # now we don't as True is the default.
458
+ antialias = False
459
+
460
+ img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [torch.float32, torch.float64])
461
+
462
+ # Define align_corners to avoid warnings
463
+ align_corners = False if interpolation in ["bilinear", "bicubic"] else None
464
+
465
+ img = interpolate(img, size=size, mode=interpolation, align_corners=align_corners, antialias=antialias)
466
+
467
+ if interpolation == "bicubic" and out_dtype == torch.uint8:
468
+ img = img.clamp(min=0, max=255)
469
+
470
+ img = _cast_squeeze_out(img, need_cast=need_cast, need_squeeze=need_squeeze, out_dtype=out_dtype)
471
+
472
+ return img
473
+
474
+
475
+ def _assert_grid_transform_inputs(
476
+ img: Tensor,
477
+ matrix: Optional[List[float]],
478
+ interpolation: str,
479
+ fill: Optional[Union[int, float, List[float]]],
480
+ supported_interpolation_modes: List[str],
481
+ coeffs: Optional[List[float]] = None,
482
+ ) -> None:
483
+
484
+ if not (isinstance(img, torch.Tensor)):
485
+ raise TypeError("Input img should be Tensor")
486
+
487
+ _assert_image_tensor(img)
488
+
489
+ if matrix is not None and not isinstance(matrix, list):
490
+ raise TypeError("Argument matrix should be a list")
491
+
492
+ if matrix is not None and len(matrix) != 6:
493
+ raise ValueError("Argument matrix should have 6 float values")
494
+
495
+ if coeffs is not None and len(coeffs) != 8:
496
+ raise ValueError("Argument coeffs should have 8 float values")
497
+
498
+ if fill is not None and not isinstance(fill, (int, float, tuple, list)):
499
+ warnings.warn("Argument fill should be either int, float, tuple or list")
500
+
501
+ # Check fill
502
+ num_channels = get_dimensions(img)[0]
503
+ if fill is not None and isinstance(fill, (tuple, list)) and len(fill) > 1 and len(fill) != num_channels:
504
+ msg = (
505
+ "The number of elements in 'fill' cannot broadcast to match the number of "
506
+ "channels of the image ({} != {})"
507
+ )
508
+ raise ValueError(msg.format(len(fill), num_channels))
509
+
510
+ if interpolation not in supported_interpolation_modes:
511
+ raise ValueError(f"Interpolation mode '{interpolation}' is unsupported with Tensor input")
512
+
513
+
514
+ def _cast_squeeze_in(img: Tensor, req_dtypes: List[torch.dtype]) -> Tuple[Tensor, bool, bool, torch.dtype]:
515
+ need_squeeze = False
516
+ # make image NCHW
517
+ if img.ndim < 4:
518
+ img = img.unsqueeze(dim=0)
519
+ need_squeeze = True
520
+
521
+ out_dtype = img.dtype
522
+ need_cast = False
523
+ if out_dtype not in req_dtypes:
524
+ need_cast = True
525
+ req_dtype = req_dtypes[0]
526
+ img = img.to(req_dtype)
527
+ return img, need_cast, need_squeeze, out_dtype
528
+
529
+
530
+ def _cast_squeeze_out(img: Tensor, need_cast: bool, need_squeeze: bool, out_dtype: torch.dtype) -> Tensor:
531
+ if need_squeeze:
532
+ img = img.squeeze(dim=0)
533
+
534
+ if need_cast:
535
+ if out_dtype in (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64):
536
+ # it is better to round before cast
537
+ img = torch.round(img)
538
+ img = img.to(out_dtype)
539
+
540
+ return img
541
+
542
+
543
+ def _apply_grid_transform(
544
+ img: Tensor, grid: Tensor, mode: str, fill: Optional[Union[int, float, List[float]]]
545
+ ) -> Tensor:
546
+
547
+ img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [grid.dtype])
548
+
549
+ if img.shape[0] > 1:
550
+ # Apply same grid to a batch of images
551
+ grid = grid.expand(img.shape[0], grid.shape[1], grid.shape[2], grid.shape[3])
552
+
553
+ # Append a dummy mask for customized fill colors, should be faster than grid_sample() twice
554
+ if fill is not None:
555
+ mask = torch.ones((img.shape[0], 1, img.shape[2], img.shape[3]), dtype=img.dtype, device=img.device)
556
+ img = torch.cat((img, mask), dim=1)
557
+
558
+ img = grid_sample(img, grid, mode=mode, padding_mode="zeros", align_corners=False)
559
+
560
+ # Fill with required color
561
+ if fill is not None:
562
+ mask = img[:, -1:, :, :] # N * 1 * H * W
563
+ img = img[:, :-1, :, :] # N * C * H * W
564
+ mask = mask.expand_as(img)
565
+ fill_list, len_fill = (fill, len(fill)) if isinstance(fill, (tuple, list)) else ([float(fill)], 1)
566
+ fill_img = torch.tensor(fill_list, dtype=img.dtype, device=img.device).view(1, len_fill, 1, 1).expand_as(img)
567
+ if mode == "nearest":
568
+ mask = mask < 0.5
569
+ img[mask] = fill_img[mask]
570
+ else: # 'bilinear'
571
+ img = img * mask + (1.0 - mask) * fill_img
572
+
573
+ img = _cast_squeeze_out(img, need_cast, need_squeeze, out_dtype)
574
+ return img
575
+
576
+
577
+ def _gen_affine_grid(
578
+ theta: Tensor,
579
+ w: int,
580
+ h: int,
581
+ ow: int,
582
+ oh: int,
583
+ ) -> Tensor:
584
+ # https://github.com/pytorch/pytorch/blob/74b65c32be68b15dc7c9e8bb62459efbfbde33d8/aten/src/ATen/native/
585
+ # AffineGridGenerator.cpp#L18
586
+ # Difference with AffineGridGenerator is that:
587
+ # 1) we normalize grid values after applying theta
588
+ # 2) we can normalize by other image size, such that it covers "extend" option like in PIL.Image.rotate
589
+
590
+ d = 0.5
591
+ base_grid = torch.empty(1, oh, ow, 3, dtype=theta.dtype, device=theta.device)
592
+ x_grid = torch.linspace(-ow * 0.5 + d, ow * 0.5 + d - 1, steps=ow, device=theta.device)
593
+ base_grid[..., 0].copy_(x_grid)
594
+ y_grid = torch.linspace(-oh * 0.5 + d, oh * 0.5 + d - 1, steps=oh, device=theta.device).unsqueeze_(-1)
595
+ base_grid[..., 1].copy_(y_grid)
596
+ base_grid[..., 2].fill_(1)
597
+
598
+ rescaled_theta = theta.transpose(1, 2) / torch.tensor([0.5 * w, 0.5 * h], dtype=theta.dtype, device=theta.device)
599
+ output_grid = base_grid.view(1, oh * ow, 3).bmm(rescaled_theta)
600
+ return output_grid.view(1, oh, ow, 2)
601
+
602
+
603
+ def affine(
604
+ img: Tensor,
605
+ matrix: List[float],
606
+ interpolation: str = "nearest",
607
+ fill: Optional[Union[int, float, List[float]]] = None,
608
+ ) -> Tensor:
609
+ _assert_grid_transform_inputs(img, matrix, interpolation, fill, ["nearest", "bilinear"])
610
+
611
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
612
+ theta = torch.tensor(matrix, dtype=dtype, device=img.device).reshape(1, 2, 3)
613
+ shape = img.shape
614
+ # grid will be generated on the same device as theta and img
615
+ grid = _gen_affine_grid(theta, w=shape[-1], h=shape[-2], ow=shape[-1], oh=shape[-2])
616
+ return _apply_grid_transform(img, grid, interpolation, fill=fill)
617
+
618
+
619
+ def _compute_affine_output_size(matrix: List[float], w: int, h: int) -> Tuple[int, int]:
620
+
621
+ # Inspired of PIL implementation:
622
+ # https://github.com/python-pillow/Pillow/blob/11de3318867e4398057373ee9f12dcb33db7335c/src/PIL/Image.py#L2054
623
+
624
+ # pts are Top-Left, Top-Right, Bottom-Left, Bottom-Right points.
625
+ # Points are shifted due to affine matrix torch convention about
626
+ # the center point. Center is (0, 0) for image center pivot point (w * 0.5, h * 0.5)
627
+ pts = torch.tensor(
628
+ [
629
+ [-0.5 * w, -0.5 * h, 1.0],
630
+ [-0.5 * w, 0.5 * h, 1.0],
631
+ [0.5 * w, 0.5 * h, 1.0],
632
+ [0.5 * w, -0.5 * h, 1.0],
633
+ ]
634
+ )
635
+ theta = torch.tensor(matrix, dtype=torch.float).view(2, 3)
636
+ new_pts = torch.matmul(pts, theta.T)
637
+ min_vals, _ = new_pts.min(dim=0)
638
+ max_vals, _ = new_pts.max(dim=0)
639
+
640
+ # shift points to [0, w] and [0, h] interval to match PIL results
641
+ min_vals += torch.tensor((w * 0.5, h * 0.5))
642
+ max_vals += torch.tensor((w * 0.5, h * 0.5))
643
+
644
+ # Truncate precision to 1e-4 to avoid ceil of Xe-15 to 1.0
645
+ tol = 1e-4
646
+ cmax = torch.ceil((max_vals / tol).trunc_() * tol)
647
+ cmin = torch.floor((min_vals / tol).trunc_() * tol)
648
+ size = cmax - cmin
649
+ return int(size[0]), int(size[1]) # w, h
650
+
651
+
652
+ def rotate(
653
+ img: Tensor,
654
+ matrix: List[float],
655
+ interpolation: str = "nearest",
656
+ expand: bool = False,
657
+ fill: Optional[Union[int, float, List[float]]] = None,
658
+ ) -> Tensor:
659
+ _assert_grid_transform_inputs(img, matrix, interpolation, fill, ["nearest", "bilinear"])
660
+ w, h = img.shape[-1], img.shape[-2]
661
+ ow, oh = _compute_affine_output_size(matrix, w, h) if expand else (w, h)
662
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
663
+ theta = torch.tensor(matrix, dtype=dtype, device=img.device).reshape(1, 2, 3)
664
+ # grid will be generated on the same device as theta and img
665
+ grid = _gen_affine_grid(theta, w=w, h=h, ow=ow, oh=oh)
666
+
667
+ return _apply_grid_transform(img, grid, interpolation, fill=fill)
668
+
669
+
670
+ def _perspective_grid(coeffs: List[float], ow: int, oh: int, dtype: torch.dtype, device: torch.device) -> Tensor:
671
+ # https://github.com/python-pillow/Pillow/blob/4634eafe3c695a014267eefdce830b4a825beed7/
672
+ # src/libImaging/Geometry.c#L394
673
+
674
+ #
675
+ # x_out = (coeffs[0] * x + coeffs[1] * y + coeffs[2]) / (coeffs[6] * x + coeffs[7] * y + 1)
676
+ # y_out = (coeffs[3] * x + coeffs[4] * y + coeffs[5]) / (coeffs[6] * x + coeffs[7] * y + 1)
677
+ #
678
+ theta1 = torch.tensor(
679
+ [[[coeffs[0], coeffs[1], coeffs[2]], [coeffs[3], coeffs[4], coeffs[5]]]], dtype=dtype, device=device
680
+ )
681
+ theta2 = torch.tensor([[[coeffs[6], coeffs[7], 1.0], [coeffs[6], coeffs[7], 1.0]]], dtype=dtype, device=device)
682
+
683
+ d = 0.5
684
+ base_grid = torch.empty(1, oh, ow, 3, dtype=dtype, device=device)
685
+ x_grid = torch.linspace(d, ow * 1.0 + d - 1.0, steps=ow, device=device)
686
+ base_grid[..., 0].copy_(x_grid)
687
+ y_grid = torch.linspace(d, oh * 1.0 + d - 1.0, steps=oh, device=device).unsqueeze_(-1)
688
+ base_grid[..., 1].copy_(y_grid)
689
+ base_grid[..., 2].fill_(1)
690
+
691
+ rescaled_theta1 = theta1.transpose(1, 2) / torch.tensor([0.5 * ow, 0.5 * oh], dtype=dtype, device=device)
692
+ output_grid1 = base_grid.view(1, oh * ow, 3).bmm(rescaled_theta1)
693
+ output_grid2 = base_grid.view(1, oh * ow, 3).bmm(theta2.transpose(1, 2))
694
+
695
+ output_grid = output_grid1 / output_grid2 - 1.0
696
+ return output_grid.view(1, oh, ow, 2)
697
+
698
+
699
+ def perspective(
700
+ img: Tensor,
701
+ perspective_coeffs: List[float],
702
+ interpolation: str = "bilinear",
703
+ fill: Optional[Union[int, float, List[float]]] = None,
704
+ ) -> Tensor:
705
+ if not (isinstance(img, torch.Tensor)):
706
+ raise TypeError("Input img should be Tensor.")
707
+
708
+ _assert_image_tensor(img)
709
+
710
+ _assert_grid_transform_inputs(
711
+ img,
712
+ matrix=None,
713
+ interpolation=interpolation,
714
+ fill=fill,
715
+ supported_interpolation_modes=["nearest", "bilinear"],
716
+ coeffs=perspective_coeffs,
717
+ )
718
+
719
+ ow, oh = img.shape[-1], img.shape[-2]
720
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
721
+ grid = _perspective_grid(perspective_coeffs, ow=ow, oh=oh, dtype=dtype, device=img.device)
722
+ return _apply_grid_transform(img, grid, interpolation, fill=fill)
723
+
724
+
725
+ def _get_gaussian_kernel1d(kernel_size: int, sigma: float) -> Tensor:
726
+ ksize_half = (kernel_size - 1) * 0.5
727
+
728
+ x = torch.linspace(-ksize_half, ksize_half, steps=kernel_size)
729
+ pdf = torch.exp(-0.5 * (x / sigma).pow(2))
730
+ kernel1d = pdf / pdf.sum()
731
+
732
+ return kernel1d
733
+
734
+
735
+ def _get_gaussian_kernel2d(
736
+ kernel_size: List[int], sigma: List[float], dtype: torch.dtype, device: torch.device
737
+ ) -> Tensor:
738
+ kernel1d_x = _get_gaussian_kernel1d(kernel_size[0], sigma[0]).to(device, dtype=dtype)
739
+ kernel1d_y = _get_gaussian_kernel1d(kernel_size[1], sigma[1]).to(device, dtype=dtype)
740
+ kernel2d = torch.mm(kernel1d_y[:, None], kernel1d_x[None, :])
741
+ return kernel2d
742
+
743
+
744
+ def gaussian_blur(img: Tensor, kernel_size: List[int], sigma: List[float]) -> Tensor:
745
+ if not (isinstance(img, torch.Tensor)):
746
+ raise TypeError(f"img should be Tensor. Got {type(img)}")
747
+
748
+ _assert_image_tensor(img)
749
+
750
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
751
+ kernel = _get_gaussian_kernel2d(kernel_size, sigma, dtype=dtype, device=img.device)
752
+ kernel = kernel.expand(img.shape[-3], 1, kernel.shape[0], kernel.shape[1])
753
+
754
+ img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [kernel.dtype])
755
+
756
+ # padding = (left, right, top, bottom)
757
+ padding = [kernel_size[0] // 2, kernel_size[0] // 2, kernel_size[1] // 2, kernel_size[1] // 2]
758
+ img = torch_pad(img, padding, mode="reflect")
759
+ img = conv2d(img, kernel, groups=img.shape[-3])
760
+
761
+ img = _cast_squeeze_out(img, need_cast, need_squeeze, out_dtype)
762
+ return img
763
+
764
+
765
+ def invert(img: Tensor) -> Tensor:
766
+
767
+ _assert_image_tensor(img)
768
+
769
+ if img.ndim < 3:
770
+ raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}")
771
+
772
+ _assert_channels(img, [1, 3])
773
+
774
+ return _max_value(img.dtype) - img
775
+
776
+
777
+ def posterize(img: Tensor, bits: int) -> Tensor:
778
+
779
+ _assert_image_tensor(img)
780
+
781
+ if img.ndim < 3:
782
+ raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}")
783
+ if img.dtype != torch.uint8:
784
+ raise TypeError(f"Only torch.uint8 image tensors are supported, but found {img.dtype}")
785
+
786
+ _assert_channels(img, [1, 3])
787
+ mask = -int(2 ** (8 - bits)) # JIT-friendly for: ~(2 ** (8 - bits) - 1)
788
+ return img & mask
789
+
790
+
791
+ def solarize(img: Tensor, threshold: float) -> Tensor:
792
+
793
+ _assert_image_tensor(img)
794
+
795
+ if img.ndim < 3:
796
+ raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}")
797
+
798
+ _assert_channels(img, [1, 3])
799
+
800
+ if threshold > _max_value(img.dtype):
801
+ raise TypeError("Threshold should be less than bound of img.")
802
+
803
+ inverted_img = invert(img)
804
+ return torch.where(img >= threshold, inverted_img, img)
805
+
806
+
807
+ def _blurred_degenerate_image(img: Tensor) -> Tensor:
808
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
809
+
810
+ kernel = torch.ones((3, 3), dtype=dtype, device=img.device)
811
+ kernel[1, 1] = 5.0
812
+ kernel /= kernel.sum()
813
+ kernel = kernel.expand(img.shape[-3], 1, kernel.shape[0], kernel.shape[1])
814
+
815
+ result_tmp, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [kernel.dtype])
816
+ result_tmp = conv2d(result_tmp, kernel, groups=result_tmp.shape[-3])
817
+ result_tmp = _cast_squeeze_out(result_tmp, need_cast, need_squeeze, out_dtype)
818
+
819
+ result = img.clone()
820
+ result[..., 1:-1, 1:-1] = result_tmp
821
+
822
+ return result
823
+
824
+
825
+ def adjust_sharpness(img: Tensor, sharpness_factor: float) -> Tensor:
826
+ if sharpness_factor < 0:
827
+ raise ValueError(f"sharpness_factor ({sharpness_factor}) is not non-negative.")
828
+
829
+ _assert_image_tensor(img)
830
+
831
+ _assert_channels(img, [1, 3])
832
+
833
+ if img.size(-1) <= 2 or img.size(-2) <= 2:
834
+ return img
835
+
836
+ return _blend(img, _blurred_degenerate_image(img), sharpness_factor)
837
+
838
+
839
+ def autocontrast(img: Tensor) -> Tensor:
840
+
841
+ _assert_image_tensor(img)
842
+
843
+ if img.ndim < 3:
844
+ raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}")
845
+
846
+ _assert_channels(img, [1, 3])
847
+
848
+ bound = _max_value(img.dtype)
849
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
850
+
851
+ minimum = img.amin(dim=(-2, -1), keepdim=True).to(dtype)
852
+ maximum = img.amax(dim=(-2, -1), keepdim=True).to(dtype)
853
+ scale = bound / (maximum - minimum)
854
+ eq_idxs = torch.isfinite(scale).logical_not()
855
+ minimum[eq_idxs] = 0
856
+ scale[eq_idxs] = 1
857
+
858
+ return ((img - minimum) * scale).clamp(0, bound).to(img.dtype)
859
+
860
+
861
+ def _scale_channel(img_chan: Tensor) -> Tensor:
862
+ # TODO: we should expect bincount to always be faster than histc, but this
863
+ # isn't always the case. Once
864
+ # https://github.com/pytorch/pytorch/issues/53194 is fixed, remove the if
865
+ # block and only use bincount.
866
+ if img_chan.is_cuda:
867
+ hist = torch.histc(img_chan.to(torch.float32), bins=256, min=0, max=255)
868
+ else:
869
+ hist = torch.bincount(img_chan.reshape(-1), minlength=256)
870
+
871
+ nonzero_hist = hist[hist != 0]
872
+ step = torch.div(nonzero_hist[:-1].sum(), 255, rounding_mode="floor")
873
+ if step == 0:
874
+ return img_chan
875
+
876
+ lut = torch.div(torch.cumsum(hist, 0) + torch.div(step, 2, rounding_mode="floor"), step, rounding_mode="floor")
877
+ lut = torch.nn.functional.pad(lut, [1, 0])[:-1].clamp(0, 255)
878
+
879
+ return lut[img_chan.to(torch.int64)].to(torch.uint8)
880
+
881
+
882
+ def _equalize_single_image(img: Tensor) -> Tensor:
883
+ return torch.stack([_scale_channel(img[c]) for c in range(img.size(0))])
884
+
885
+
886
+ def equalize(img: Tensor) -> Tensor:
887
+
888
+ _assert_image_tensor(img)
889
+
890
+ if not (3 <= img.ndim <= 4):
891
+ raise TypeError(f"Input image tensor should have 3 or 4 dimensions, but found {img.ndim}")
892
+ if img.dtype != torch.uint8:
893
+ raise TypeError(f"Only torch.uint8 image tensors are supported, but found {img.dtype}")
894
+
895
+ _assert_channels(img, [1, 3])
896
+
897
+ if img.ndim == 3:
898
+ return _equalize_single_image(img)
899
+
900
+ return torch.stack([_equalize_single_image(x) for x in img])
901
+
902
+
903
+ def normalize(tensor: Tensor, mean: List[float], std: List[float], inplace: bool = False) -> Tensor:
904
+ _assert_image_tensor(tensor)
905
+
906
+ if not tensor.is_floating_point():
907
+ raise TypeError(f"Input tensor should be a float tensor. Got {tensor.dtype}.")
908
+
909
+ if tensor.ndim < 3:
910
+ raise ValueError(
911
+ f"Expected tensor to be a tensor image of size (..., C, H, W). Got tensor.size() = {tensor.size()}"
912
+ )
913
+
914
+ if not inplace:
915
+ tensor = tensor.clone()
916
+
917
+ dtype = tensor.dtype
918
+ mean = torch.as_tensor(mean, dtype=dtype, device=tensor.device)
919
+ std = torch.as_tensor(std, dtype=dtype, device=tensor.device)
920
+ if (std == 0).any():
921
+ raise ValueError(f"std evaluated to zero after conversion to {dtype}, leading to division by zero.")
922
+ if mean.ndim == 1:
923
+ mean = mean.view(-1, 1, 1)
924
+ if std.ndim == 1:
925
+ std = std.view(-1, 1, 1)
926
+ return tensor.sub_(mean).div_(std)
927
+
928
+
929
+ def erase(img: Tensor, i: int, j: int, h: int, w: int, v: Tensor, inplace: bool = False) -> Tensor:
930
+ _assert_image_tensor(img)
931
+
932
+ if not inplace:
933
+ img = img.clone()
934
+
935
+ img[..., i : i + h, j : j + w] = v
936
+ return img
937
+
938
+
939
+ def _create_identity_grid(size: List[int]) -> Tensor:
940
+ hw_space = [torch.linspace((-s + 1) / s, (s - 1) / s, s) for s in size]
941
+ grid_y, grid_x = torch.meshgrid(hw_space, indexing="ij")
942
+ return torch.stack([grid_x, grid_y], -1).unsqueeze(0) # 1 x H x W x 2
943
+
944
+
945
+ def elastic_transform(
946
+ img: Tensor,
947
+ displacement: Tensor,
948
+ interpolation: str = "bilinear",
949
+ fill: Optional[Union[int, float, List[float]]] = None,
950
+ ) -> Tensor:
951
+
952
+ if not (isinstance(img, torch.Tensor)):
953
+ raise TypeError(f"img should be Tensor. Got {type(img)}")
954
+
955
+ size = list(img.shape[-2:])
956
+ displacement = displacement.to(img.device)
957
+
958
+ identity_grid = _create_identity_grid(size)
959
+ grid = identity_grid.to(img.device) + displacement
960
+ return _apply_grid_transform(img, grid, interpolation, fill)
shared/package-files/06/06b040956a82a017f58a62be3255645dd5d545658338157d2730bc543b8aa64a/blob ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor _dirichlet_grad(const at::Tensor & x, const at::Tensor & alpha, const at::Tensor & total);
21
+
22
+ } // namespace cuda
23
+ } // namespace at
shared/package-files/06/06b381caddd5de9c6cedd3e0e350791f7b89745b22a86f514ef65e88772e12aa/blob ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API at::Tensor special_zeta(const at::Tensor & self, const at::Tensor & other);
21
+
22
+ } // namespace compositeexplicitautogradnonfunctional
23
+ } // namespace at
shared/package-files/06/06b39b66efb6f772121ab44293451f5d2f1ce5b7ce8c198808f967c889db9977/blob ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Created on Sat May 19 15:53:21 2018
3
+
4
+ Author: Josef Perktold
5
+ License: BSD-3
6
+ """
7
+
8
+ from collections import defaultdict
9
+
10
+ import numpy as np
11
+
12
+ from statsmodels.base._penalties import SCADSmoothed
13
+
14
+
15
+ class ScreeningResults:
16
+ """Results for Variable Screening
17
+
18
+ Note: Indices except for exog_idx and in the iterated case also
19
+ idx_nonzero_batches are based on the combined [exog_keep, exog] array.
20
+
21
+ Attributes
22
+ ----------
23
+ results_final : instance
24
+ Results instance returned by the final fit of the penalized model, i.e.
25
+ after trimming exog with params below trimming threshold.
26
+ results_pen : results instance
27
+ Results instance of the penalized model before trimming. This includes
28
+ variables from the last forward selection.
29
+ idx_nonzero : ndarray
30
+ Index of exog columns in the final selection including exog_keep.
31
+ idx_exog : ndarray
32
+ Index of exog columns in the final selection for exog candidates, i.e.
33
+ without exog_keep.
34
+ idx_excl : ndarray
35
+ Index of excluded exog based on combined [exog_keep, exog] array. This
36
+ is the complement of idx_nonzero.
37
+ converged : bool
38
+ True if the iteration has converged and stopped before maxiter has been
39
+ reached. False if maxiter has been reached.
40
+ iterations : int
41
+ Number of iterations in the screening process. Each iteration consists
42
+ of a forward selection step and a trimming step.
43
+ history : dict of lists
44
+ Results collected for each iteration during the screening process.
45
+ Keys are 'idx_nonzero', 'keep', 'params_keep' and 'idx_added', each
46
+ holding a list with one entry appended per iteration.
47
+ screener : instance of VariableScreening
48
+ The VariableScreening instance that produced these results.
49
+
50
+ The ScreeningResults returned by `screen_exog_iterator` has additional
51
+ attributes:
52
+
53
+ idx_nonzero_batches : ndarray, 2-D
54
+ Two-dimensional array with batch index in the first column and variable
55
+ index within batch in the second column. They can be used jointly as
56
+ index for the data in the exog_iterator.
57
+ exog_final_names : list of str
58
+ 'var<bidx>_<idx>' where `bidx` is the batch index and `idx` is the
59
+ index of the selected column within batch `bidx`.
60
+ history_batches : dict of lists
61
+ This provides information about the selected variables within each
62
+ batch during the first round screening.
63
+ 'idx_nonzero' is based on the array that includes exog_keep, while
64
+ 'idx_exog' is the index based on the exog of the batch.
65
+ """
66
+ def __init__(self, screener, **kwds):
67
+ self.screener = screener
68
+ self.__dict__.update(**kwds)
69
+
70
+
71
+ class VariableScreening:
72
+ """Ultra-high, conditional sure independence screening
73
+
74
+ This is an adjusted version of Fan's sure independence screening.
75
+
76
+ Parameters
77
+ ----------
78
+ model : instance of penalizing model
79
+ Examples: GLMPenalized, PoissonPenalized and LogitPenalized.
80
+ The attributes of the model instance `pen_weight` and `penal` will be
81
+ ignored.
82
+ pen_weight : float, optional
83
+ Penalization weight use in SCAD penalized MLE.
84
+ use_weights : bool, optional
85
+ If True, penalty weights are used so that `exog_keep` is not
86
+ penalized (weight 0) while candidate exog have weight 1. If False,
87
+ all penalty weights are set equally.
88
+ k_add : int, optional
89
+ Number of exog to add during expansion or forward selection.
90
+ See Notes section for tie handling.
91
+ k_max_add : int, optional
92
+ Maximum number of variables to include during variable addition, i.e.
93
+ forward selection. Default is 30.
94
+ threshold_trim : float, optional
95
+ Threshold for trimming parameters to zero, default is 1e-4.
96
+ k_max_included : int, optional
97
+ Maximum total number of variables to include in model.
98
+ ranking_attr : str, optional
99
+ This determines the result attribute or model method that is used for
100
+ the ranking of exog to include. The availability of attributes depends
101
+ on the model.
102
+ Default is 'resid_pearson', 'model.score_factor' can be used in GLM.
103
+ ranking_project : bool, optional
104
+ If ranking_project is True, then the exog candidates for inclusion are
105
+ first projected on the already included exog before the computation
106
+ of the ranking measure. This brings the ranking measure closer to
107
+ the statistic of a score test for variable addition.
108
+
109
+ Notes
110
+ -----
111
+ Status: experimental, tested only on a limited set of models and
112
+ with a limited set of model options.
113
+
114
+ Tie handling: If there are ties at the decision threshold, then all those
115
+ tied exog columns are treated in the same way. During forward selection
116
+ all exog columns with the same boundary value are included. During
117
+ elimination, the tied columns are not dropped. Consequently, if ties are
118
+ present, then the number of included exog can be larger than specified
119
+ by k_add, k_max_add and k_max_included.
120
+
121
+ The screening algorithm works similar to step wise regression. Each
122
+ iteration of the screening algorithm includes a forward selection step
123
+ where variables are added to the model, and a backwards selection step
124
+ where variables are removed. In contrast to step wise regression, we add
125
+ a fixed number of variables at each forward selection step. The
126
+ backwards selection step is based on SCAD penalized estimation and
127
+ trimming of variables with estimated coefficients below a threshold.
128
+ The tuning parameters can be used to adjust the number of variables to add
129
+ and to include depending on the size of the dataset.
130
+
131
+ There is currently no automatic tuning parameter selection. Candidate
132
+ explanatory variables should be standardized or should be on a similar
133
+ scale because penalization and trimming are based on the absolute values
134
+ of the parameters.
135
+
136
+
137
+ TODOs and current limitations:
138
+
139
+ freq_weights are not supported in this. Candidate ranking uses
140
+ moment condition with resid_pearson or others without freq_weights.
141
+ pearson_resid: GLM resid_pearson does not include freq_weights.
142
+
143
+ variable names: do we keep track of those? currently made-up names
144
+
145
+ currently only supports numpy arrays, no exog type check or conversion
146
+
147
+ currently only single columns are selected, no terms (multi column exog)
148
+ """
149
+
150
+ def __init__(self, model, pen_weight=None, use_weights=True, k_add=30,
151
+ k_max_add=30, threshold_trim=1e-4, k_max_included=20,
152
+ ranking_attr="resid_pearson", ranking_project=True):
153
+
154
+ self.model = model
155
+ self.model_class = model.__class__
156
+ self.init_kwds = model._get_init_kwds()
157
+ # pen_weight and penal are explicitly included
158
+ # TODO: check what we want to do here
159
+ self.init_kwds.pop("pen_weight", None)
160
+ self.init_kwds.pop("penal", None)
161
+
162
+ self.endog = model.endog
163
+ self.exog_keep = model.exog
164
+ self.k_keep = model.exog.shape[1]
165
+ self.nobs = len(self.endog)
166
+ self.penal = self._get_penal()
167
+
168
+ if pen_weight is not None:
169
+ self.pen_weight = pen_weight
170
+ else:
171
+ self.pen_weight = self.nobs * 10
172
+
173
+ # option for screening algorithm
174
+ self.use_weights = use_weights
175
+ self.k_add = k_add
176
+ self.k_max_add = k_max_add
177
+ self.threshold_trim = threshold_trim
178
+ self.k_max_included = k_max_included
179
+ self.ranking_attr = ranking_attr
180
+ self.ranking_project = ranking_project
181
+
182
+ def _get_penal(self, weights=None):
183
+ """Create new Penalty instance"""
184
+ return SCADSmoothed(0.1, c0=0.0001, weights=weights)
185
+
186
+ def ranking_measure(self, res_pen, exog, keep=None):
187
+ """Compute measure for ranking exog candidates for inclusion"""
188
+ endog = self.endog
189
+
190
+ if self.ranking_project:
191
+ assert res_pen.model.exog.shape[1] == len(keep)
192
+ ex_incl = res_pen.model.exog[:, keep]
193
+ exog = exog - ex_incl.dot(np.linalg.pinv(ex_incl).dot(exog))
194
+
195
+ if self.ranking_attr == "predicted_poisson":
196
+ # I keep this for more experiments
197
+
198
+ # TODO: does it really help to change/trim params
199
+ # we are not reestimating with trimmed model
200
+ p = res_pen.params.copy()
201
+ if keep is not None:
202
+ p[~keep] = 0
203
+ predicted = res_pen.model.predict(p)
204
+ # this is currently hardcoded for Poisson
205
+ resid_factor = (endog - predicted) / np.sqrt(predicted)
206
+ elif self.ranking_attr[:6] == "model.":
207
+ # use model method, this is intended for score_factor
208
+ attr = self.ranking_attr.split(".")[1]
209
+ resid_factor = getattr(res_pen.model, attr)(res_pen.params)
210
+ if resid_factor.ndim == 2:
211
+ # for score_factor when extra params are in model
212
+ resid_factor = resid_factor[:, 0]
213
+ mom_cond = np.abs(resid_factor.dot(exog))**2
214
+ else:
215
+ # use results attribute
216
+ resid_factor = getattr(res_pen, self.ranking_attr)
217
+ mom_cond = np.abs(resid_factor.dot(exog))**2
218
+ return mom_cond
219
+
220
+ def screen_exog(self, exog, endog=None, maxiter=100, method="bfgs",
221
+ disp=False, fit_kwds=None):
222
+ """Screen and select variables (columns) in exog
223
+
224
+ Parameters
225
+ ----------
226
+ exog : ndarray
227
+ Candidate explanatory variables that are screened for inclusion in
228
+ the model.
229
+ endog : ndarray, optional
230
+ Use a new endog in the screening model.
231
+ This is not tested yet, and might not work correctly.
232
+ maxiter : int, optional
233
+ Number of screening iterations.
234
+ method : str, optional
235
+ Optimization method to use in fit, needs to be only of the gradient
236
+ optimizers.
237
+ disp : bool, optional
238
+ Display option for fit during optimization.
239
+ fit_kwds : dict-like, optional
240
+ Additional keyword arguments passed to the model's `fit` method.
241
+
242
+ Returns
243
+ -------
244
+ res_screen : instance of ScreeningResults
245
+ The attribute `results_final` contains the results instance
246
+ with the final model selection.
247
+ `idx_nonzero` contains the index of the selected exog in the full
248
+ exog, combined exog that are always kept plus exog_candidates.
249
+ See ScreeningResults for a full description.
250
+ """
251
+ model_class = self.model_class
252
+ if endog is None:
253
+ # allow a different endog than used in model
254
+ endog = self.endog
255
+ x0 = self.exog_keep
256
+ k_keep = self.k_keep
257
+ x1 = exog
258
+ k_current = x0.shape[1]
259
+ # TODO: remove the need for x, use x1 separately from x0
260
+ # needs change to idx to be based on x1 (candidate variables)
261
+ x = np.column_stack((x0, x1))
262
+ nobs, k_vars = x.shape
263
+ fkwds = fit_kwds if fit_kwds is not None else {}
264
+ fit_kwds = {"maxiter": 200, "disp": False}
265
+ fit_kwds.update(fkwds)
266
+
267
+ history = defaultdict(list)
268
+ idx_nonzero = np.arange(k_keep, dtype=int)
269
+ keep = np.ones(k_keep, np.bool_)
270
+ idx_excl = np.arange(k_keep, k_vars)
271
+ mod_pen = model_class(endog, x0, **self.init_kwds)
272
+ # do not penalize initial estimate
273
+ mod_pen.pen_weight = 0
274
+ res_pen = mod_pen.fit(**fit_kwds)
275
+ start_params = res_pen.params
276
+ converged = False
277
+ idx_old = []
278
+ iterations = 0
279
+ for _ in range(maxiter):
280
+ iterations += 1
281
+ # candidates for inclusion in next iteration
282
+ x1 = x[:, idx_excl]
283
+ mom_cond = self.ranking_measure(res_pen, x1, keep=keep)
284
+ assert len(mom_cond) == len(idx_excl)
285
+ mcs = np.sort(mom_cond)[::-1]
286
+ idx_thr = min((self.k_max_add, k_current + self.k_add, len(mcs)))
287
+ threshold = mcs[idx_thr]
288
+ # indices of exog in current expansion model
289
+ idx = np.concatenate((idx_nonzero, idx_excl[mom_cond > threshold]))
290
+ start_params2 = np.zeros(len(idx))
291
+ start_params2[:len(start_params)] = start_params
292
+
293
+ if self.use_weights:
294
+ weights = np.ones(len(idx))
295
+ weights[:k_keep] = 0
296
+ # modify Penalty instance attached to self
297
+ # damgerous if res_pen is reused
298
+ self.penal.weights = weights
299
+ mod_pen = model_class(endog, x[:, idx], penal=self.penal,
300
+ pen_weight=self.pen_weight,
301
+ **self.init_kwds)
302
+
303
+ res_pen = mod_pen.fit(method=method,
304
+ start_params=start_params2,
305
+ warn_convergence=False, skip_hessian=True,
306
+ **fit_kwds)
307
+
308
+ keep = np.abs(res_pen.params) > self.threshold_trim
309
+ # use largest params to keep
310
+ if keep.sum() > self.k_max_included:
311
+ # TODO we can use now np.partition with partial sort
312
+ thresh_params = np.sort(np.abs(res_pen.params))[
313
+ -self.k_max_included]
314
+ keep2 = np.abs(res_pen.params) > thresh_params
315
+ keep = np.logical_and(keep, keep2)
316
+
317
+ # Note: idx and keep are for current expansion model
318
+ # idx_nonzero has indices of selected variables in full exog
319
+ keep[:k_keep] = True # always keep exog_keep
320
+ idx_nonzero = idx[keep]
321
+
322
+ if disp:
323
+ print(keep)
324
+ print(idx_nonzero)
325
+ # x0 is exog of currently selected model, not used in iteration
326
+ # x0 = x[:, idx_nonzero]
327
+ k_current = len(idx_nonzero)
328
+ start_params = res_pen.params[keep]
329
+
330
+ # use mask to get excluded indices
331
+ mask_excl = np.ones(k_vars, dtype=bool)
332
+ mask_excl[idx_nonzero] = False
333
+ idx_excl = np.nonzero(mask_excl)[0]
334
+ history["idx_nonzero"].append(idx_nonzero)
335
+ history["keep"].append(keep)
336
+ history["params_keep"].append(start_params)
337
+ history["idx_added"].append(idx)
338
+
339
+ if (len(idx_nonzero) == len(idx_old) and
340
+ (idx_nonzero == idx_old).all()):
341
+ converged = True
342
+ break
343
+ idx_old = idx_nonzero
344
+
345
+ # final esimate
346
+ # check that we still have exog_keep
347
+ assert np.all(idx_nonzero[:k_keep] == np.arange(k_keep))
348
+ if self.use_weights:
349
+ weights = np.ones(len(idx_nonzero))
350
+ weights[:k_keep] = 0
351
+ # create new Penalty instance to avoide sharing attached penal
352
+ penal = self._get_penal(weights=weights)
353
+ else:
354
+ penal = self.penal
355
+ mod_final = model_class(endog, x[:, idx_nonzero],
356
+ penal=penal,
357
+ pen_weight=self.pen_weight,
358
+ **self.init_kwds)
359
+
360
+ res_final = mod_final.fit(method=method,
361
+ start_params=start_params,
362
+ warn_convergence=False,
363
+ **fit_kwds)
364
+ # set exog_names for final model
365
+ xnames = [f"var{ii:4d}" for ii in idx_nonzero]
366
+ res_final.model.exog_names[k_keep:] = xnames[k_keep:]
367
+
368
+ res = ScreeningResults(self,
369
+ results_pen=res_pen,
370
+ results_final=res_final,
371
+ idx_nonzero=idx_nonzero,
372
+ idx_exog=idx_nonzero[k_keep:] - k_keep,
373
+ idx_excl=idx_excl,
374
+ history=history,
375
+ converged=converged,
376
+ iterations=iterations
377
+ )
378
+ return res
379
+
380
+ def screen_exog_iterator(self, exog_iterator):
381
+ """
382
+ Batched version of screen exog
383
+
384
+ This screens variables in a two step process:
385
+
386
+ In the first step screen_exog is used on each element of the
387
+ exog_iterator, and the batch winners are collected.
388
+
389
+ In the second step all batch winners are combined into a new array
390
+ of exog candidates and `screen_exog` is used to select a final
391
+ model.
392
+
393
+ Parameters
394
+ ----------
395
+ exog_iterator : iterator over ndarrays
396
+ Batches of candidate explanatory variables that are screened
397
+ for inclusion in the model.
398
+
399
+ Returns
400
+ -------
401
+ res_screen_final : instance of ScreeningResults
402
+ This is the instance returned by the second round call to
403
+ `screen_exog`. Additional attributes are added to provide
404
+ more information about the batched selection process.
405
+ The index of final nonzero variables is
406
+ `idx_nonzero_batches` which is a 2-dimensional array with batch
407
+ index in the first column and variable index within batch in the
408
+ second column. They can be used jointly as index for the data
409
+ in the exog_iterator.
410
+ See ScreeningResults for a full description.
411
+ """
412
+ k_keep = self.k_keep
413
+ # res_batches = []
414
+ res_idx = []
415
+ exog_winner = []
416
+ exog_idx = []
417
+ for ex in exog_iterator:
418
+ res_screen = self.screen_exog(ex, maxiter=20)
419
+ # avoid storing res_screen, only for debugging
420
+ # res_batches.append(res_screen)
421
+ res_idx.append(res_screen.idx_nonzero)
422
+ exog_winner.append(ex[:, res_screen.idx_nonzero[k_keep:] - k_keep])
423
+ exog_idx.append(res_screen.idx_nonzero[k_keep:] - k_keep)
424
+
425
+ exog_winner = np.column_stack(exog_winner)
426
+ res_screen_final = self.screen_exog(exog_winner, maxiter=20)
427
+
428
+ exog_winner_names = [f"var{bidx:d}_{idx:d}"
429
+ for bidx, batch in enumerate(exog_idx)
430
+ for idx in batch]
431
+
432
+ idx_full = [(bidx, idx)
433
+ for bidx, batch in enumerate(exog_idx)
434
+ for idx in batch]
435
+ ex_final_idx = res_screen_final.idx_nonzero[k_keep:] - k_keep
436
+ final_names = np.array(exog_winner_names)[ex_final_idx]
437
+ res_screen_final.idx_nonzero_batches = np.array(idx_full)[ex_final_idx]
438
+ res_screen_final.exog_final_names = final_names
439
+ history = {"idx_nonzero": res_idx,
440
+ "idx_exog": exog_idx}
441
+ res_screen_final.history_batches = history
442
+ return res_screen_final
shared/package-files/06/06b5f7f9a40b0fd5b5d6dd56f1fd12968d9935b46500a93b66808e44bf349ea6/blob ADDED
Binary file (604 Bytes). View file
 
shared/package-files/06/06b83b8b3586648dc1ad136c0ed25301883cc7e7d7f03b3286981416a15b3057/blob ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API clone {
18
+ using schema = at::Tensor (const at::Tensor &, c10::optional<at::MemoryFormat>);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clone")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clone(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, c10::optional<at::MemoryFormat> memory_format);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional<at::MemoryFormat> memory_format);
26
+ };
27
+
28
+ struct TORCH_API clone_out {
29
+ using schema = at::Tensor & (const at::Tensor &, c10::optional<at::MemoryFormat>, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clone")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clone.out(Tensor self, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & self, c10::optional<at::MemoryFormat> memory_format, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional<at::MemoryFormat> memory_format, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops
shared/package-files/06/06b881b824f71e95d72af4ab865de4c35553e791b6d959a125caac61401cc350/blob ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of JSONEncoder
2
+ """
3
+ import re
4
+
5
+ try:
6
+ from _json import encode_basestring_ascii as c_encode_basestring_ascii
7
+ except ImportError:
8
+ c_encode_basestring_ascii = None
9
+ try:
10
+ from _json import encode_basestring as c_encode_basestring
11
+ except ImportError:
12
+ c_encode_basestring = None
13
+ try:
14
+ from _json import make_encoder as c_make_encoder
15
+ except ImportError:
16
+ c_make_encoder = None
17
+
18
+ ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
19
+ ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
20
+ HAS_UTF8 = re.compile(b'[\x80-\xff]')
21
+ ESCAPE_DCT = {
22
+ '\\': '\\\\',
23
+ '"': '\\"',
24
+ '\b': '\\b',
25
+ '\f': '\\f',
26
+ '\n': '\\n',
27
+ '\r': '\\r',
28
+ '\t': '\\t',
29
+ }
30
+ for i in range(0x20):
31
+ ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
32
+ #ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
33
+
34
+ INFINITY = float('inf')
35
+
36
+ def py_encode_basestring(s):
37
+ """Return a JSON representation of a Python string
38
+
39
+ """
40
+ def replace(match):
41
+ return ESCAPE_DCT[match.group(0)]
42
+ return '"' + ESCAPE.sub(replace, s) + '"'
43
+
44
+
45
+ encode_basestring = (c_encode_basestring or py_encode_basestring)
46
+
47
+
48
+ def py_encode_basestring_ascii(s):
49
+ """Return an ASCII-only JSON representation of a Python string
50
+
51
+ """
52
+ def replace(match):
53
+ s = match.group(0)
54
+ try:
55
+ return ESCAPE_DCT[s]
56
+ except KeyError:
57
+ n = ord(s)
58
+ if n < 0x10000:
59
+ return '\\u{0:04x}'.format(n)
60
+ #return '\\u%04x' % (n,)
61
+ else:
62
+ # surrogate pair
63
+ n -= 0x10000
64
+ s1 = 0xd800 | ((n >> 10) & 0x3ff)
65
+ s2 = 0xdc00 | (n & 0x3ff)
66
+ return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
67
+ return '"' + ESCAPE_ASCII.sub(replace, s) + '"'
68
+
69
+
70
+ encode_basestring_ascii = (
71
+ c_encode_basestring_ascii or py_encode_basestring_ascii)
72
+
73
+ class JSONEncoder(object):
74
+ """Extensible JSON <https://json.org> encoder for Python data structures.
75
+
76
+ Supports the following objects and types by default:
77
+
78
+ +-------------------+---------------+
79
+ | Python | JSON |
80
+ +===================+===============+
81
+ | dict | object |
82
+ +-------------------+---------------+
83
+ | list, tuple | array |
84
+ +-------------------+---------------+
85
+ | str | string |
86
+ +-------------------+---------------+
87
+ | int, float | number |
88
+ +-------------------+---------------+
89
+ | True | true |
90
+ +-------------------+---------------+
91
+ | False | false |
92
+ +-------------------+---------------+
93
+ | None | null |
94
+ +-------------------+---------------+
95
+
96
+ To extend this to recognize other objects, subclass and implement a
97
+ ``.default()`` method with another method that returns a serializable
98
+ object for ``o`` if possible, otherwise it should call the superclass
99
+ implementation (to raise ``TypeError``).
100
+
101
+ """
102
+ item_separator = ', '
103
+ key_separator = ': '
104
+ def __init__(self, *, skipkeys=False, ensure_ascii=True,
105
+ check_circular=True, allow_nan=True, sort_keys=False,
106
+ indent=None, separators=None, default=None):
107
+ """Constructor for JSONEncoder, with sensible defaults.
108
+
109
+ If skipkeys is false, then it is a TypeError to attempt
110
+ encoding of keys that are not str, int, float or None. If
111
+ skipkeys is True, such items are simply skipped.
112
+
113
+ If ensure_ascii is true, the output is guaranteed to be str
114
+ objects with all incoming non-ASCII characters escaped. If
115
+ ensure_ascii is false, the output can contain non-ASCII characters.
116
+
117
+ If check_circular is true, then lists, dicts, and custom encoded
118
+ objects will be checked for circular references during encoding to
119
+ prevent an infinite recursion (which would cause an RecursionError).
120
+ Otherwise, no such check takes place.
121
+
122
+ If allow_nan is true, then NaN, Infinity, and -Infinity will be
123
+ encoded as such. This behavior is not JSON specification compliant,
124
+ but is consistent with most JavaScript based encoders and decoders.
125
+ Otherwise, it will be a ValueError to encode such floats.
126
+
127
+ If sort_keys is true, then the output of dictionaries will be
128
+ sorted by key; this is useful for regression tests to ensure
129
+ that JSON serializations can be compared on a day-to-day basis.
130
+
131
+ If indent is a non-negative integer, then JSON array
132
+ elements and object members will be pretty-printed with that
133
+ indent level. An indent level of 0 will only insert newlines.
134
+ None is the most compact representation.
135
+
136
+ If specified, separators should be an (item_separator, key_separator)
137
+ tuple. The default is (', ', ': ') if *indent* is ``None`` and
138
+ (',', ': ') otherwise. To get the most compact JSON representation,
139
+ you should specify (',', ':') to eliminate whitespace.
140
+
141
+ If specified, default is a function that gets called for objects
142
+ that can't otherwise be serialized. It should return a JSON encodable
143
+ version of the object or raise a ``TypeError``.
144
+
145
+ """
146
+
147
+ self.skipkeys = skipkeys
148
+ self.ensure_ascii = ensure_ascii
149
+ self.check_circular = check_circular
150
+ self.allow_nan = allow_nan
151
+ self.sort_keys = sort_keys
152
+ self.indent = indent
153
+ if separators is not None:
154
+ self.item_separator, self.key_separator = separators
155
+ elif indent is not None:
156
+ self.item_separator = ','
157
+ if default is not None:
158
+ self.default = default
159
+
160
+ def default(self, o):
161
+ """Implement this method in a subclass such that it returns
162
+ a serializable object for ``o``, or calls the base implementation
163
+ (to raise a ``TypeError``).
164
+
165
+ For example, to support arbitrary iterators, you could
166
+ implement default like this::
167
+
168
+ def default(self, o):
169
+ try:
170
+ iterable = iter(o)
171
+ except TypeError:
172
+ pass
173
+ else:
174
+ return list(iterable)
175
+ # Let the base class default method raise the TypeError
176
+ return JSONEncoder.default(self, o)
177
+
178
+ """
179
+ raise TypeError(f'Object of type {o.__class__.__name__} '
180
+ f'is not JSON serializable')
181
+
182
+ def encode(self, o):
183
+ """Return a JSON string representation of a Python data structure.
184
+
185
+ >>> from json.encoder import JSONEncoder
186
+ >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
187
+ '{"foo": ["bar", "baz"]}'
188
+
189
+ """
190
+ # This is for extremely simple cases and benchmarks.
191
+ if isinstance(o, str):
192
+ if self.ensure_ascii:
193
+ return encode_basestring_ascii(o)
194
+ else:
195
+ return encode_basestring(o)
196
+ # This doesn't pass the iterator directly to ''.join() because the
197
+ # exceptions aren't as detailed. The list call should be roughly
198
+ # equivalent to the PySequence_Fast that ''.join() would do.
199
+ chunks = self.iterencode(o, _one_shot=True)
200
+ if not isinstance(chunks, (list, tuple)):
201
+ chunks = list(chunks)
202
+ return ''.join(chunks)
203
+
204
+ def iterencode(self, o, _one_shot=False):
205
+ """Encode the given object and yield each string
206
+ representation as available.
207
+
208
+ For example::
209
+
210
+ for chunk in JSONEncoder().iterencode(bigobject):
211
+ mysocket.write(chunk)
212
+
213
+ """
214
+ if self.check_circular:
215
+ markers = {}
216
+ else:
217
+ markers = None
218
+ if self.ensure_ascii:
219
+ _encoder = encode_basestring_ascii
220
+ else:
221
+ _encoder = encode_basestring
222
+
223
+ def floatstr(o, allow_nan=self.allow_nan,
224
+ _repr=float.__repr__, _inf=INFINITY, _neginf=-INFINITY):
225
+ # Check for specials. Note that this type of test is processor
226
+ # and/or platform-specific, so do tests which don't depend on the
227
+ # internals.
228
+
229
+ if o != o:
230
+ text = 'NaN'
231
+ elif o == _inf:
232
+ text = 'Infinity'
233
+ elif o == _neginf:
234
+ text = '-Infinity'
235
+ else:
236
+ return _repr(o)
237
+
238
+ if not allow_nan:
239
+ raise ValueError(
240
+ "Out of range float values are not JSON compliant: " +
241
+ repr(o))
242
+
243
+ return text
244
+
245
+
246
+ if (_one_shot and c_make_encoder is not None
247
+ and self.indent is None):
248
+ _iterencode = c_make_encoder(
249
+ markers, self.default, _encoder, self.indent,
250
+ self.key_separator, self.item_separator, self.sort_keys,
251
+ self.skipkeys, self.allow_nan)
252
+ else:
253
+ _iterencode = _make_iterencode(
254
+ markers, self.default, _encoder, self.indent, floatstr,
255
+ self.key_separator, self.item_separator, self.sort_keys,
256
+ self.skipkeys, _one_shot)
257
+ return _iterencode(o, 0)
258
+
259
+ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
260
+ _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
261
+ ## HACK: hand-optimized bytecode; turn globals into locals
262
+ ValueError=ValueError,
263
+ dict=dict,
264
+ float=float,
265
+ id=id,
266
+ int=int,
267
+ isinstance=isinstance,
268
+ list=list,
269
+ str=str,
270
+ tuple=tuple,
271
+ _intstr=int.__repr__,
272
+ ):
273
+
274
+ if _indent is not None and not isinstance(_indent, str):
275
+ _indent = ' ' * _indent
276
+
277
+ def _iterencode_list(lst, _current_indent_level):
278
+ if not lst:
279
+ yield '[]'
280
+ return
281
+ if markers is not None:
282
+ markerid = id(lst)
283
+ if markerid in markers:
284
+ raise ValueError("Circular reference detected")
285
+ markers[markerid] = lst
286
+ buf = '['
287
+ if _indent is not None:
288
+ _current_indent_level += 1
289
+ newline_indent = '\n' + _indent * _current_indent_level
290
+ separator = _item_separator + newline_indent
291
+ buf += newline_indent
292
+ else:
293
+ newline_indent = None
294
+ separator = _item_separator
295
+ first = True
296
+ for value in lst:
297
+ if first:
298
+ first = False
299
+ else:
300
+ buf = separator
301
+ if isinstance(value, str):
302
+ yield buf + _encoder(value)
303
+ elif value is None:
304
+ yield buf + 'null'
305
+ elif value is True:
306
+ yield buf + 'true'
307
+ elif value is False:
308
+ yield buf + 'false'
309
+ elif isinstance(value, int):
310
+ # Subclasses of int/float may override __repr__, but we still
311
+ # want to encode them as integers/floats in JSON. One example
312
+ # within the standard library is IntEnum.
313
+ yield buf + _intstr(value)
314
+ elif isinstance(value, float):
315
+ # see comment above for int
316
+ yield buf + _floatstr(value)
317
+ else:
318
+ yield buf
319
+ if isinstance(value, (list, tuple)):
320
+ chunks = _iterencode_list(value, _current_indent_level)
321
+ elif isinstance(value, dict):
322
+ chunks = _iterencode_dict(value, _current_indent_level)
323
+ else:
324
+ chunks = _iterencode(value, _current_indent_level)
325
+ yield from chunks
326
+ if newline_indent is not None:
327
+ _current_indent_level -= 1
328
+ yield '\n' + _indent * _current_indent_level
329
+ yield ']'
330
+ if markers is not None:
331
+ del markers[markerid]
332
+
333
+ def _iterencode_dict(dct, _current_indent_level):
334
+ if not dct:
335
+ yield '{}'
336
+ return
337
+ if markers is not None:
338
+ markerid = id(dct)
339
+ if markerid in markers:
340
+ raise ValueError("Circular reference detected")
341
+ markers[markerid] = dct
342
+ yield '{'
343
+ if _indent is not None:
344
+ _current_indent_level += 1
345
+ newline_indent = '\n' + _indent * _current_indent_level
346
+ item_separator = _item_separator + newline_indent
347
+ yield newline_indent
348
+ else:
349
+ newline_indent = None
350
+ item_separator = _item_separator
351
+ first = True
352
+ if _sort_keys:
353
+ items = sorted(dct.items())
354
+ else:
355
+ items = dct.items()
356
+ for key, value in items:
357
+ if isinstance(key, str):
358
+ pass
359
+ # JavaScript is weakly typed for these, so it makes sense to
360
+ # also allow them. Many encoders seem to do something like this.
361
+ elif isinstance(key, float):
362
+ # see comment for int/float in _make_iterencode
363
+ key = _floatstr(key)
364
+ elif key is True:
365
+ key = 'true'
366
+ elif key is False:
367
+ key = 'false'
368
+ elif key is None:
369
+ key = 'null'
370
+ elif isinstance(key, int):
371
+ # see comment for int/float in _make_iterencode
372
+ key = _intstr(key)
373
+ elif _skipkeys:
374
+ continue
375
+ else:
376
+ raise TypeError(f'keys must be str, int, float, bool or None, '
377
+ f'not {key.__class__.__name__}')
378
+ if first:
379
+ first = False
380
+ else:
381
+ yield item_separator
382
+ yield _encoder(key)
383
+ yield _key_separator
384
+ if isinstance(value, str):
385
+ yield _encoder(value)
386
+ elif value is None:
387
+ yield 'null'
388
+ elif value is True:
389
+ yield 'true'
390
+ elif value is False:
391
+ yield 'false'
392
+ elif isinstance(value, int):
393
+ # see comment for int/float in _make_iterencode
394
+ yield _intstr(value)
395
+ elif isinstance(value, float):
396
+ # see comment for int/float in _make_iterencode
397
+ yield _floatstr(value)
398
+ else:
399
+ if isinstance(value, (list, tuple)):
400
+ chunks = _iterencode_list(value, _current_indent_level)
401
+ elif isinstance(value, dict):
402
+ chunks = _iterencode_dict(value, _current_indent_level)
403
+ else:
404
+ chunks = _iterencode(value, _current_indent_level)
405
+ yield from chunks
406
+ if newline_indent is not None:
407
+ _current_indent_level -= 1
408
+ yield '\n' + _indent * _current_indent_level
409
+ yield '}'
410
+ if markers is not None:
411
+ del markers[markerid]
412
+
413
+ def _iterencode(o, _current_indent_level):
414
+ if isinstance(o, str):
415
+ yield _encoder(o)
416
+ elif o is None:
417
+ yield 'null'
418
+ elif o is True:
419
+ yield 'true'
420
+ elif o is False:
421
+ yield 'false'
422
+ elif isinstance(o, int):
423
+ # see comment for int/float in _make_iterencode
424
+ yield _intstr(o)
425
+ elif isinstance(o, float):
426
+ # see comment for int/float in _make_iterencode
427
+ yield _floatstr(o)
428
+ elif isinstance(o, (list, tuple)):
429
+ yield from _iterencode_list(o, _current_indent_level)
430
+ elif isinstance(o, dict):
431
+ yield from _iterencode_dict(o, _current_indent_level)
432
+ else:
433
+ if markers is not None:
434
+ markerid = id(o)
435
+ if markerid in markers:
436
+ raise ValueError("Circular reference detected")
437
+ markers[markerid] = o
438
+ o = _default(o)
439
+ yield from _iterencode(o, _current_indent_level)
440
+ if markers is not None:
441
+ del markers[markerid]
442
+ return _iterencode
shared/package-files/06/06b8b7396bb8964915e9818b68b518b5d03de58f1e84ae4ca1b313843a024edd/blob ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+ from functools import reduce
3
+
4
+
5
+ def maybe_view(tensor, size, check_same_size=True):
6
+ if check_same_size and tensor.size() == size:
7
+ return tensor
8
+ return tensor.contiguous().view(size)
9
+
10
+
11
+ def maybe_unexpand(tensor, old_size, check_same_size=True):
12
+ if check_same_size and tensor.size() == old_size:
13
+ return tensor
14
+ num_unsqueezed = tensor.dim() - len(old_size)
15
+ expanded_dims = [
16
+ dim
17
+ for dim, (expanded, original) in enumerate(
18
+ zip(tensor.size()[num_unsqueezed:], old_size)
19
+ )
20
+ if expanded != original
21
+ ]
22
+
23
+ for _ in range(num_unsqueezed):
24
+ tensor = tensor.sum(0, keepdim=False)
25
+ for dim in expanded_dims:
26
+ tensor = tensor.sum(dim, keepdim=True)
27
+ return tensor
28
+
29
+
30
+ # Check whether the op enable broadcasting, and whether it is supported by ONNX.
31
+ # If dims1 and dims2 are different, then broadcast is True.
32
+ # We always assume the combination of dims1 and dims2 is broadcastable.
33
+ # The following types of broadcasting are supported in ONNX:
34
+ # 1) Only one element in dims2, such as dims2 = [1, 1]
35
+ # 2) dims2 is suffix of dims1, such as dims1 = [2, 3, 4], and dims2 = [3, 4]
36
+ # Details can be found here: https://github.com/onnx/onnx/blob/master/docs/Operators.md#Gemm
37
+ def check_onnx_broadcast(dims1, dims2):
38
+ broadcast = False
39
+ supported = True
40
+ len1 = len(dims1)
41
+ len2 = len(dims2)
42
+ numel1 = reduce(operator.mul, dims1)
43
+ numel2 = reduce(operator.mul, dims2)
44
+ if len1 < len2:
45
+ broadcast = True
46
+ if numel2 != 1:
47
+ supported = False
48
+ elif len1 > len2:
49
+ broadcast = True
50
+ if numel2 != 1 and dims1[len1 - len2 :] != dims2:
51
+ supported = False
52
+ else:
53
+ if dims1 != dims2:
54
+ broadcast = True
55
+ if numel2 != 1:
56
+ supported = False
57
+
58
+ if not supported:
59
+ raise ValueError(
60
+ f"Numpy style broadcasting is not supported in ONNX. Input dims are: {dims1}, {dims2}"
61
+ )
62
+ return broadcast
shared/package-files/06/06bcfff317bfc97d78441e81f29564e8169c33a1e2cea914088439bdcf54fbf2/blob ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, tzinfo
2
+ from typing import IO, Any, Dict, List, Mapping, Optional, Text, Tuple, Union
3
+
4
+ _FileOrStr = Union[bytes, Text, IO[str], IO[Any]]
5
+
6
+ class parserinfo(object):
7
+ JUMP: List[str]
8
+ WEEKDAYS: List[Tuple[str, str]]
9
+ MONTHS: List[Tuple[str, str]]
10
+ HMS: List[Tuple[str, str, str]]
11
+ AMPM: List[Tuple[str, str]]
12
+ UTCZONE: List[str]
13
+ PERTAIN: List[str]
14
+ TZOFFSET: Dict[str, int]
15
+ def __init__(self, dayfirst: bool = ..., yearfirst: bool = ...) -> None: ...
16
+ def jump(self, name: Text) -> bool: ...
17
+ def weekday(self, name: Text) -> Optional[int]: ...
18
+ def month(self, name: Text) -> Optional[int]: ...
19
+ def hms(self, name: Text) -> Optional[int]: ...
20
+ def ampm(self, name: Text) -> Optional[int]: ...
21
+ def pertain(self, name: Text) -> bool: ...
22
+ def utczone(self, name: Text) -> bool: ...
23
+ def tzoffset(self, name: Text) -> Optional[int]: ...
24
+ def convertyear(self, year: int) -> int: ...
25
+ def validate(self, res: datetime) -> bool: ...
26
+
27
+ class parser(object):
28
+ def __init__(self, info: Optional[parserinfo] = ...) -> None: ...
29
+ def parse(
30
+ self,
31
+ timestr: _FileOrStr,
32
+ default: Optional[datetime] = ...,
33
+ ignoretz: bool = ...,
34
+ tzinfos: Optional[Mapping[Text, tzinfo]] = ...,
35
+ **kwargs: Any,
36
+ ) -> datetime: ...
37
+
38
+ def isoparse(dt_str: Union[str, bytes, IO[str], IO[bytes]]) -> datetime: ...
39
+
40
+ DEFAULTPARSER: parser
41
+
42
+ def parse(timestr: _FileOrStr, parserinfo: Optional[parserinfo] = ..., **kwargs: Any) -> datetime: ...
43
+
44
+ class _tzparser: ...
45
+
46
+ DEFAULTTZPARSER: _tzparser
47
+
48
+ class InvalidDatetimeError(ValueError): ...
49
+ class InvalidDateError(InvalidDatetimeError): ...
50
+ class InvalidTimeError(InvalidDatetimeError): ...
51
+ class ParserError(ValueError): ...
shared/package-files/06/06bd03cb0ab219a5701da59b81b21664b9d0610ed2a5ad38678794f13ac7cfef/blob ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from array import array
3
+ from typing import (
4
+ Any,
5
+ Callable,
6
+ ClassVar,
7
+ Generic,
8
+ Iterable,
9
+ Iterator,
10
+ List,
11
+ Mapping,
12
+ Optional,
13
+ Sequence,
14
+ Text,
15
+ Tuple,
16
+ Type,
17
+ TypeVar,
18
+ Union as _UnionT,
19
+ overload,
20
+ )
21
+
22
+ if sys.version_info >= (3, 9):
23
+ from types import GenericAlias
24
+
25
+ _T = TypeVar("_T")
26
+ _DLLT = TypeVar("_DLLT", bound=CDLL)
27
+ _CT = TypeVar("_CT", bound=_CData)
28
+
29
+ RTLD_GLOBAL: int = ...
30
+ RTLD_LOCAL: int = ...
31
+ DEFAULT_MODE: int = ...
32
+
33
+ class CDLL(object):
34
+ _func_flags_: ClassVar[int] = ...
35
+ _func_restype_: ClassVar[_CData] = ...
36
+ _name: str = ...
37
+ _handle: int = ...
38
+ _FuncPtr: Type[_FuncPointer] = ...
39
+ def __init__(
40
+ self,
41
+ name: Optional[str],
42
+ mode: int = ...,
43
+ handle: Optional[int] = ...,
44
+ use_errno: bool = ...,
45
+ use_last_error: bool = ...,
46
+ winmode: Optional[int] = ...,
47
+ ) -> None: ...
48
+ def __getattr__(self, name: str) -> _NamedFuncPointer: ...
49
+ def __getitem__(self, name: str) -> _NamedFuncPointer: ...
50
+
51
+ if sys.platform == "win32":
52
+ class OleDLL(CDLL): ...
53
+ class WinDLL(CDLL): ...
54
+
55
+ class PyDLL(CDLL): ...
56
+
57
+ class LibraryLoader(Generic[_DLLT]):
58
+ def __init__(self, dlltype: Type[_DLLT]) -> None: ...
59
+ def __getattr__(self, name: str) -> _DLLT: ...
60
+ def __getitem__(self, name: str) -> _DLLT: ...
61
+ def LoadLibrary(self, name: str) -> _DLLT: ...
62
+ if sys.version_info >= (3, 9):
63
+ def __class_getitem__(cls, item: Any) -> GenericAlias: ...
64
+
65
+ cdll: LibraryLoader[CDLL] = ...
66
+ if sys.platform == "win32":
67
+ windll: LibraryLoader[WinDLL] = ...
68
+ oledll: LibraryLoader[OleDLL] = ...
69
+ pydll: LibraryLoader[PyDLL] = ...
70
+ pythonapi: PyDLL = ...
71
+
72
+ # Anything that implements the read-write buffer interface.
73
+ # The buffer interface is defined purely on the C level, so we cannot define a normal Protocol
74
+ # for it. Instead we have to list the most common stdlib buffer classes in a Union.
75
+ _WritableBuffer = _UnionT[bytearray, memoryview, array, _CData]
76
+ # Same as _WritableBuffer, but also includes read-only buffer types (like bytes).
77
+ _ReadOnlyBuffer = _UnionT[_WritableBuffer, bytes]
78
+
79
+ class _CDataMeta(type):
80
+ # By default mypy complains about the following two methods, because strictly speaking cls
81
+ # might not be a Type[_CT]. However this can never actually happen, because the only class that
82
+ # uses _CDataMeta as its metaclass is _CData. So it's safe to ignore the errors here.
83
+ def __mul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore
84
+ def __rmul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore
85
+
86
+ class _CData(metaclass=_CDataMeta):
87
+ _b_base: int = ...
88
+ _b_needsfree_: bool = ...
89
+ _objects: Optional[Mapping[Any, int]] = ...
90
+ @classmethod
91
+ def from_buffer(cls: Type[_CT], source: _WritableBuffer, offset: int = ...) -> _CT: ...
92
+ @classmethod
93
+ def from_buffer_copy(cls: Type[_CT], source: _ReadOnlyBuffer, offset: int = ...) -> _CT: ...
94
+ @classmethod
95
+ def from_address(cls: Type[_CT], address: int) -> _CT: ...
96
+ @classmethod
97
+ def from_param(cls: Type[_CT], obj: Any) -> _UnionT[_CT, _CArgObject]: ...
98
+ @classmethod
99
+ def in_dll(cls: Type[_CT], library: CDLL, name: str) -> _CT: ...
100
+
101
+ class _CanCastTo(_CData): ...
102
+ class _PointerLike(_CanCastTo): ...
103
+
104
+ _ECT = Callable[[Optional[Type[_CData]], _FuncPointer, Tuple[_CData, ...]], _CData]
105
+ _PF = _UnionT[Tuple[int], Tuple[int, str], Tuple[int, str, Any]]
106
+
107
+ class _FuncPointer(_PointerLike, _CData):
108
+ restype: _UnionT[Type[_CData], Callable[[int], None], None] = ...
109
+ argtypes: Sequence[Type[_CData]] = ...
110
+ errcheck: _ECT = ...
111
+ @overload
112
+ def __init__(self, address: int) -> None: ...
113
+ @overload
114
+ def __init__(self, callable: Callable[..., Any]) -> None: ...
115
+ @overload
116
+ def __init__(self, func_spec: Tuple[_UnionT[str, int], CDLL], paramflags: Tuple[_PF, ...] = ...) -> None: ...
117
+ @overload
118
+ def __init__(self, vtlb_index: int, name: str, paramflags: Tuple[_PF, ...] = ..., iid: pointer[c_int] = ...) -> None: ...
119
+ def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
120
+
121
+ class _NamedFuncPointer(_FuncPointer):
122
+ __name__: str
123
+
124
+ class ArgumentError(Exception): ...
125
+
126
+ def CFUNCTYPE(
127
+ restype: Optional[Type[_CData]], *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ...
128
+ ) -> Type[_FuncPointer]: ...
129
+
130
+ if sys.platform == "win32":
131
+ def WINFUNCTYPE(
132
+ restype: Optional[Type[_CData]], *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ...
133
+ ) -> Type[_FuncPointer]: ...
134
+
135
+ def PYFUNCTYPE(restype: Optional[Type[_CData]], *argtypes: Type[_CData]) -> Type[_FuncPointer]: ...
136
+
137
+ class _CArgObject: ...
138
+
139
+ # Any type that can be implicitly converted to c_void_p when passed as a C function argument.
140
+ # (bytes is not included here, see below.)
141
+ _CVoidPLike = _UnionT[_PointerLike, Array[Any], _CArgObject, int]
142
+ # Same as above, but including types known to be read-only (i. e. bytes).
143
+ # This distinction is not strictly necessary (ctypes doesn't differentiate between const
144
+ # and non-const pointers), but it catches errors like memmove(b'foo', buf, 4)
145
+ # when memmove(buf, b'foo', 4) was intended.
146
+ _CVoidConstPLike = _UnionT[_CVoidPLike, bytes]
147
+
148
+ def addressof(obj: _CData) -> int: ...
149
+ def alignment(obj_or_type: _UnionT[_CData, Type[_CData]]) -> int: ...
150
+ def byref(obj: _CData, offset: int = ...) -> _CArgObject: ...
151
+
152
+ _CastT = TypeVar("_CastT", bound=_CanCastTo)
153
+
154
+ def cast(obj: _UnionT[_CData, _CArgObject, int], type: Type[_CastT]) -> _CastT: ...
155
+ def create_string_buffer(init: _UnionT[int, bytes], size: Optional[int] = ...) -> Array[c_char]: ...
156
+
157
+ c_buffer = create_string_buffer
158
+
159
+ def create_unicode_buffer(init: _UnionT[int, Text], size: Optional[int] = ...) -> Array[c_wchar]: ...
160
+
161
+ if sys.platform == "win32":
162
+ def DllCanUnloadNow() -> int: ...
163
+ def DllGetClassObject(rclsid: Any, riid: Any, ppv: Any) -> int: ... # TODO not documented
164
+ def FormatError(code: int) -> str: ...
165
+ def GetLastError() -> int: ...
166
+
167
+ def get_errno() -> int: ...
168
+
169
+ if sys.platform == "win32":
170
+ def get_last_error() -> int: ...
171
+
172
+ def memmove(dst: _CVoidPLike, src: _CVoidConstPLike, count: int) -> None: ...
173
+ def memset(dst: _CVoidPLike, c: int, count: int) -> None: ...
174
+ def POINTER(type: Type[_CT]) -> Type[pointer[_CT]]: ...
175
+
176
+ # The real ctypes.pointer is a function, not a class. The stub version of pointer behaves like
177
+ # ctypes._Pointer in that it is the base class for all pointer types. Unlike the real _Pointer,
178
+ # it can be instantiated directly (to mimic the behavior of the real pointer function).
179
+ class pointer(Generic[_CT], _PointerLike, _CData):
180
+ _type_: ClassVar[Type[_CT]] = ...
181
+ contents: _CT = ...
182
+ def __init__(self, arg: _CT = ...) -> None: ...
183
+ @overload
184
+ def __getitem__(self, i: int) -> _CT: ...
185
+ @overload
186
+ def __getitem__(self, s: slice) -> List[_CT]: ...
187
+ @overload
188
+ def __setitem__(self, i: int, o: _CT) -> None: ...
189
+ @overload
190
+ def __setitem__(self, s: slice, o: Iterable[_CT]) -> None: ...
191
+
192
+ def resize(obj: _CData, size: int) -> None: ...
193
+
194
+ if sys.version_info < (3,):
195
+ def set_conversion_mode(encoding: str, errors: str) -> Tuple[str, str]: ...
196
+
197
+ def set_errno(value: int) -> int: ...
198
+
199
+ if sys.platform == "win32":
200
+ def set_last_error(value: int) -> int: ...
201
+
202
+ def sizeof(obj_or_type: _UnionT[_CData, Type[_CData]]) -> int: ...
203
+ def string_at(address: _CVoidConstPLike, size: int = ...) -> bytes: ...
204
+
205
+ if sys.platform == "win32":
206
+ def WinError(code: Optional[int] = ..., descr: Optional[str] = ...) -> OSError: ...
207
+
208
+ def wstring_at(address: _CVoidConstPLike, size: int = ...) -> str: ...
209
+
210
+ class _SimpleCData(Generic[_T], _CData):
211
+ value: _T = ...
212
+ def __init__(self, value: _T = ...) -> None: ...
213
+
214
+ class c_byte(_SimpleCData[int]): ...
215
+
216
+ class c_char(_SimpleCData[bytes]):
217
+ def __init__(self, value: _UnionT[int, bytes] = ...) -> None: ...
218
+
219
+ class c_char_p(_PointerLike, _SimpleCData[Optional[bytes]]):
220
+ def __init__(self, value: Optional[_UnionT[int, bytes]] = ...) -> None: ...
221
+
222
+ class c_double(_SimpleCData[float]): ...
223
+ class c_longdouble(_SimpleCData[float]): ...
224
+ class c_float(_SimpleCData[float]): ...
225
+ class c_int(_SimpleCData[int]): ...
226
+ class c_int8(_SimpleCData[int]): ...
227
+ class c_int16(_SimpleCData[int]): ...
228
+ class c_int32(_SimpleCData[int]): ...
229
+ class c_int64(_SimpleCData[int]): ...
230
+ class c_long(_SimpleCData[int]): ...
231
+ class c_longlong(_SimpleCData[int]): ...
232
+ class c_short(_SimpleCData[int]): ...
233
+ class c_size_t(_SimpleCData[int]): ...
234
+ class c_ssize_t(_SimpleCData[int]): ...
235
+ class c_ubyte(_SimpleCData[int]): ...
236
+ class c_uint(_SimpleCData[int]): ...
237
+ class c_uint8(_SimpleCData[int]): ...
238
+ class c_uint16(_SimpleCData[int]): ...
239
+ class c_uint32(_SimpleCData[int]): ...
240
+ class c_uint64(_SimpleCData[int]): ...
241
+ class c_ulong(_SimpleCData[int]): ...
242
+ class c_ulonglong(_SimpleCData[int]): ...
243
+ class c_ushort(_SimpleCData[int]): ...
244
+ class c_void_p(_PointerLike, _SimpleCData[Optional[int]]): ...
245
+ class c_wchar(_SimpleCData[Text]): ...
246
+
247
+ class c_wchar_p(_PointerLike, _SimpleCData[Optional[Text]]):
248
+ def __init__(self, value: Optional[_UnionT[int, Text]] = ...) -> None: ...
249
+
250
+ class c_bool(_SimpleCData[bool]):
251
+ def __init__(self, value: bool = ...) -> None: ...
252
+
253
+ if sys.platform == "win32":
254
+ class HRESULT(_SimpleCData[int]): ... # TODO undocumented
255
+
256
+ class py_object(_CanCastTo, _SimpleCData[_T]): ...
257
+
258
+ class _CField:
259
+ offset: int = ...
260
+ size: int = ...
261
+
262
+ class _StructUnionMeta(_CDataMeta):
263
+ _fields_: Sequence[_UnionT[Tuple[str, Type[_CData]], Tuple[str, Type[_CData], int]]] = ...
264
+ _pack_: int = ...
265
+ _anonymous_: Sequence[str] = ...
266
+ def __getattr__(self, name: str) -> _CField: ...
267
+
268
+ class _StructUnionBase(_CData, metaclass=_StructUnionMeta):
269
+ def __init__(self, *args: Any, **kw: Any) -> None: ...
270
+ def __getattr__(self, name: str) -> Any: ...
271
+ def __setattr__(self, name: str, value: Any) -> None: ...
272
+
273
+ class Union(_StructUnionBase): ...
274
+ class Structure(_StructUnionBase): ...
275
+ class BigEndianStructure(Structure): ...
276
+ class LittleEndianStructure(Structure): ...
277
+
278
+ class Array(Generic[_CT], _CData):
279
+ _length_: ClassVar[int] = ...
280
+ _type_: ClassVar[Type[_CT]] = ...
281
+ raw: bytes = ... # Note: only available if _CT == c_char
282
+ value: Any = ... # Note: bytes if _CT == c_char, Text if _CT == c_wchar, unavailable otherwise
283
+ # TODO These methods cannot be annotated correctly at the moment.
284
+ # All of these "Any"s stand for the array's element type, but it's not possible to use _CT
285
+ # here, because of a special feature of ctypes.
286
+ # By default, when accessing an element of an Array[_CT], the returned object has type _CT.
287
+ # However, when _CT is a "simple type" like c_int, ctypes automatically "unboxes" the object
288
+ # and converts it to the corresponding Python primitive. For example, when accessing an element
289
+ # of an Array[c_int], a Python int object is returned, not a c_int.
290
+ # This behavior does *not* apply to subclasses of "simple types".
291
+ # If MyInt is a subclass of c_int, then accessing an element of an Array[MyInt] returns
292
+ # a MyInt, not an int.
293
+ # This special behavior is not easy to model in a stub, so for now all places where
294
+ # the array element type would belong are annotated with Any instead.
295
+ def __init__(self, *args: Any) -> None: ...
296
+ @overload
297
+ def __getitem__(self, i: int) -> Any: ...
298
+ @overload
299
+ def __getitem__(self, s: slice) -> List[Any]: ...
300
+ @overload
301
+ def __setitem__(self, i: int, o: Any) -> None: ...
302
+ @overload
303
+ def __setitem__(self, s: slice, o: Iterable[Any]) -> None: ...
304
+ def __iter__(self) -> Iterator[Any]: ...
305
+ # Can't inherit from Sized because the metaclass conflict between
306
+ # Sized and _CData prevents using _CDataMeta.
307
+ def __len__(self) -> int: ...
308
+ if sys.version_info >= (3, 9):
309
+ def __class_getitem__(cls, item: Any) -> GenericAlias: ...
shared/package-files/06/06befcb259155c51e608af2dade2b9489b0fa76c41343c193b5e073f142b203e/blob ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() #######
3
+ ####### Any changes to this file will be overwritten by the next CMake run ####
4
+ ####### The input file was reproc-config.cmake.in ########
5
+
6
+ get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE)
7
+
8
+ macro(set_and_check _var _file)
9
+ set(${_var} "${_file}")
10
+ if(NOT EXISTS "${_file}")
11
+ message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !")
12
+ endif()
13
+ endmacro()
14
+
15
+ macro(check_required_components _NAME)
16
+ foreach(comp ${${_NAME}_FIND_COMPONENTS})
17
+ if(NOT ${_NAME}_${comp}_FOUND)
18
+ if(${_NAME}_FIND_REQUIRED_${comp})
19
+ set(${_NAME}_FOUND FALSE)
20
+ endif()
21
+ endif()
22
+ endforeach()
23
+ endmacro()
24
+
25
+ ####################################################################################
26
+
27
+ set(REPROC_MULTITHREADED ON)
28
+
29
+ include(CMakeFindDependencyMacro)
30
+
31
+ if(REPROC_MULTITHREADED)
32
+ set(THREADS_PREFER_PTHREAD_FLAG ON)
33
+ find_dependency(Threads)
34
+ endif()
35
+
36
+ include(${CMAKE_CURRENT_LIST_DIR}/reproc-targets.cmake)
shared/package-files/06/06bf5768b6f7ada260d4f4009d5e66799ddfb647e56d702c17a66d0cd7ce88cb/blob ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API arctanh {
18
+ using schema = at::Tensor (const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::arctanh")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "arctanh(Tensor self) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
26
+ };
27
+
28
+ struct TORCH_API arctanh_ {
29
+ using schema = at::Tensor & (at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::arctanh_")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "arctanh_(Tensor(a!) self) -> Tensor(a!)")
35
+ static at::Tensor & call(at::Tensor & self);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self);
37
+ };
38
+
39
+ struct TORCH_API arctanh_out {
40
+ using schema = at::Tensor & (const at::Tensor &, at::Tensor &);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::arctanh")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "arctanh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)")
46
+ static at::Tensor & call(const at::Tensor & self, at::Tensor & out);
47
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out);
48
+ };
49
+
50
+ }} // namespace at::_ops
shared/package-files/06/06c51c6abfc2d276733c657669c92b27d0a9554f3fd16fe91d82b0a5d9d675d3/blob ADDED
@@ -0,0 +1 @@
 
 
1
+ jsonpointer
shared/package-files/06/06c640bb2cf3469d4affb4fc801035db3b053729306a5faa542e9a35104932ed/blob ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> _native_multi_head_attention_out(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const c10::optional<at::Tensor> & mask, bool need_weights, bool average_attn_weights, c10::optional<int64_t> mask_type, at::Tensor & out0, at::Tensor & out1);
20
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor> native_multi_head_attention_cpu(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const c10::optional<at::Tensor> & mask={}, bool need_weights=true, bool average_attn_weights=true, c10::optional<int64_t> mask_type=c10::nullopt);
21
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor> native_multi_head_attention_cuda(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const c10::optional<at::Tensor> & mask={}, bool need_weights=true, bool average_attn_weights=true, c10::optional<int64_t> mask_type=c10::nullopt);
22
+ } // namespace native
23
+ } // namespace at
shared/package-files/06/06c8ab6557752e63d64f8b41233ea5a193e365c227a10ac819f0bbaefcea989c/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Tableau colorblind 10 palette
2
+ axes.prop_cycle: cycler('color', ['006BA4', 'FF800E', 'ABABAB', '595959', '5F9ED1', 'C85200', '898989', 'A2C8EC', 'FFBC79', 'CFCFCF'])
3
+ patch.facecolor: 006BA4
shared/package-files/06/06cbdf88bccd27374d0fe0b31052b363769d1faaa425d3910e6ec2d9968b9433/blob ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API eye {
18
+ using schema = at::Tensor (c10::SymInt, c10::optional<at::ScalarType>, c10::optional<at::Layout>, c10::optional<at::Device>, c10::optional<bool>);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::eye")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "eye(SymInt n, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor")
24
+ static at::Tensor call(c10::SymInt n, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymInt n, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
26
+ };
27
+
28
+ struct TORCH_API eye_m {
29
+ using schema = at::Tensor (c10::SymInt, c10::SymInt, c10::optional<at::ScalarType>, c10::optional<at::Layout>, c10::optional<at::Device>, c10::optional<bool>);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::eye")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "m")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "eye.m(SymInt n, SymInt m, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor")
35
+ static at::Tensor call(c10::SymInt n, c10::SymInt m, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymInt n, c10::SymInt m, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
37
+ };
38
+
39
+ struct TORCH_API eye_out {
40
+ using schema = at::Tensor & (c10::SymInt, at::Tensor &);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::eye")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "eye.out(SymInt n, *, Tensor(a!) out) -> Tensor(a!)")
46
+ static at::Tensor & call(c10::SymInt n, at::Tensor & out);
47
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymInt n, at::Tensor & out);
48
+ };
49
+
50
+ struct TORCH_API eye_m_out {
51
+ using schema = at::Tensor & (c10::SymInt, c10::SymInt, at::Tensor &);
52
+ using ptr_schema = schema*;
53
+ // See Note [static constexpr char* members for windows NVCC]
54
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::eye")
55
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "m_out")
56
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "eye.m_out(SymInt n, SymInt m, *, Tensor(a!) out) -> Tensor(a!)")
57
+ static at::Tensor & call(c10::SymInt n, c10::SymInt m, at::Tensor & out);
58
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymInt n, c10::SymInt m, at::Tensor & out);
59
+ };
60
+
61
+ }} // namespace at::_ops
shared/package-files/06/06cc5816adde64223c0fedf112013d1636febbe83b34f8cd89d6e0155737380c/blob ADDED
Binary file (43.8 kB). View file
 
shared/package-files/06/06cdac7a4743272c3fc2b5291bbbd94061f4cb44b80b801bc464a9794ffc0b6b/blob ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.vector.vector import Vector
2
+ from sympy.vector.coordsysrect import CoordSys3D
3
+ from sympy.vector.functions import express, matrix_to_vector, orthogonalize
4
+ from sympy.core.numbers import Rational
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import symbols
7
+ from sympy.functions.elementary.miscellaneous import sqrt
8
+ from sympy.functions.elementary.trigonometric import (cos, sin)
9
+ from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix
10
+ from sympy.testing.pytest import raises
11
+
12
+ N = CoordSys3D('N')
13
+ q1, q2, q3, q4, q5 = symbols('q1 q2 q3 q4 q5')
14
+ A = N.orient_new_axis('A', q1, N.k) # type: ignore
15
+ B = A.orient_new_axis('B', q2, A.i)
16
+ C = B.orient_new_axis('C', q3, B.j)
17
+
18
+
19
+ def test_express():
20
+ assert express(Vector.zero, N) == Vector.zero
21
+ assert express(S.Zero, N) is S.Zero
22
+ assert express(A.i, C) == cos(q3)*C.i + sin(q3)*C.k
23
+ assert express(A.j, C) == sin(q2)*sin(q3)*C.i + cos(q2)*C.j - \
24
+ sin(q2)*cos(q3)*C.k
25
+ assert express(A.k, C) == -sin(q3)*cos(q2)*C.i + sin(q2)*C.j + \
26
+ cos(q2)*cos(q3)*C.k
27
+ assert express(A.i, N) == cos(q1)*N.i + sin(q1)*N.j
28
+ assert express(A.j, N) == -sin(q1)*N.i + cos(q1)*N.j
29
+ assert express(A.k, N) == N.k
30
+ assert express(A.i, A) == A.i
31
+ assert express(A.j, A) == A.j
32
+ assert express(A.k, A) == A.k
33
+ assert express(A.i, B) == B.i
34
+ assert express(A.j, B) == cos(q2)*B.j - sin(q2)*B.k
35
+ assert express(A.k, B) == sin(q2)*B.j + cos(q2)*B.k
36
+ assert express(A.i, C) == cos(q3)*C.i + sin(q3)*C.k
37
+ assert express(A.j, C) == sin(q2)*sin(q3)*C.i + cos(q2)*C.j - \
38
+ sin(q2)*cos(q3)*C.k
39
+ assert express(A.k, C) == -sin(q3)*cos(q2)*C.i + sin(q2)*C.j + \
40
+ cos(q2)*cos(q3)*C.k
41
+ # Check to make sure UnitVectors get converted properly
42
+ assert express(N.i, N) == N.i
43
+ assert express(N.j, N) == N.j
44
+ assert express(N.k, N) == N.k
45
+ assert express(N.i, A) == (cos(q1)*A.i - sin(q1)*A.j)
46
+ assert express(N.j, A) == (sin(q1)*A.i + cos(q1)*A.j)
47
+ assert express(N.k, A) == A.k
48
+ assert express(N.i, B) == (cos(q1)*B.i - sin(q1)*cos(q2)*B.j +
49
+ sin(q1)*sin(q2)*B.k)
50
+ assert express(N.j, B) == (sin(q1)*B.i + cos(q1)*cos(q2)*B.j -
51
+ sin(q2)*cos(q1)*B.k)
52
+ assert express(N.k, B) == (sin(q2)*B.j + cos(q2)*B.k)
53
+ assert express(N.i, C) == (
54
+ (cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3))*C.i -
55
+ sin(q1)*cos(q2)*C.j +
56
+ (sin(q3)*cos(q1) + sin(q1)*sin(q2)*cos(q3))*C.k)
57
+ assert express(N.j, C) == (
58
+ (sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*C.i +
59
+ cos(q1)*cos(q2)*C.j +
60
+ (sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*C.k)
61
+ assert express(N.k, C) == (-sin(q3)*cos(q2)*C.i + sin(q2)*C.j +
62
+ cos(q2)*cos(q3)*C.k)
63
+
64
+ assert express(A.i, N) == (cos(q1)*N.i + sin(q1)*N.j)
65
+ assert express(A.j, N) == (-sin(q1)*N.i + cos(q1)*N.j)
66
+ assert express(A.k, N) == N.k
67
+ assert express(A.i, A) == A.i
68
+ assert express(A.j, A) == A.j
69
+ assert express(A.k, A) == A.k
70
+ assert express(A.i, B) == B.i
71
+ assert express(A.j, B) == (cos(q2)*B.j - sin(q2)*B.k)
72
+ assert express(A.k, B) == (sin(q2)*B.j + cos(q2)*B.k)
73
+ assert express(A.i, C) == (cos(q3)*C.i + sin(q3)*C.k)
74
+ assert express(A.j, C) == (sin(q2)*sin(q3)*C.i + cos(q2)*C.j -
75
+ sin(q2)*cos(q3)*C.k)
76
+ assert express(A.k, C) == (-sin(q3)*cos(q2)*C.i + sin(q2)*C.j +
77
+ cos(q2)*cos(q3)*C.k)
78
+
79
+ assert express(B.i, N) == (cos(q1)*N.i + sin(q1)*N.j)
80
+ assert express(B.j, N) == (-sin(q1)*cos(q2)*N.i +
81
+ cos(q1)*cos(q2)*N.j + sin(q2)*N.k)
82
+ assert express(B.k, N) == (sin(q1)*sin(q2)*N.i -
83
+ sin(q2)*cos(q1)*N.j + cos(q2)*N.k)
84
+ assert express(B.i, A) == A.i
85
+ assert express(B.j, A) == (cos(q2)*A.j + sin(q2)*A.k)
86
+ assert express(B.k, A) == (-sin(q2)*A.j + cos(q2)*A.k)
87
+ assert express(B.i, B) == B.i
88
+ assert express(B.j, B) == B.j
89
+ assert express(B.k, B) == B.k
90
+ assert express(B.i, C) == (cos(q3)*C.i + sin(q3)*C.k)
91
+ assert express(B.j, C) == C.j
92
+ assert express(B.k, C) == (-sin(q3)*C.i + cos(q3)*C.k)
93
+
94
+ assert express(C.i, N) == (
95
+ (cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3))*N.i +
96
+ (sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*N.j -
97
+ sin(q3)*cos(q2)*N.k)
98
+ assert express(C.j, N) == (
99
+ -sin(q1)*cos(q2)*N.i + cos(q1)*cos(q2)*N.j + sin(q2)*N.k)
100
+ assert express(C.k, N) == (
101
+ (sin(q3)*cos(q1) + sin(q1)*sin(q2)*cos(q3))*N.i +
102
+ (sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*N.j +
103
+ cos(q2)*cos(q3)*N.k)
104
+ assert express(C.i, A) == (cos(q3)*A.i + sin(q2)*sin(q3)*A.j -
105
+ sin(q3)*cos(q2)*A.k)
106
+ assert express(C.j, A) == (cos(q2)*A.j + sin(q2)*A.k)
107
+ assert express(C.k, A) == (sin(q3)*A.i - sin(q2)*cos(q3)*A.j +
108
+ cos(q2)*cos(q3)*A.k)
109
+ assert express(C.i, B) == (cos(q3)*B.i - sin(q3)*B.k)
110
+ assert express(C.j, B) == B.j
111
+ assert express(C.k, B) == (sin(q3)*B.i + cos(q3)*B.k)
112
+ assert express(C.i, C) == C.i
113
+ assert express(C.j, C) == C.j
114
+ assert express(C.k, C) == C.k == (C.k)
115
+
116
+ # Check to make sure Vectors get converted back to UnitVectors
117
+ assert N.i == express((cos(q1)*A.i - sin(q1)*A.j), N).simplify()
118
+ assert N.j == express((sin(q1)*A.i + cos(q1)*A.j), N).simplify()
119
+ assert N.i == express((cos(q1)*B.i - sin(q1)*cos(q2)*B.j +
120
+ sin(q1)*sin(q2)*B.k), N).simplify()
121
+ assert N.j == express((sin(q1)*B.i + cos(q1)*cos(q2)*B.j -
122
+ sin(q2)*cos(q1)*B.k), N).simplify()
123
+ assert N.k == express((sin(q2)*B.j + cos(q2)*B.k), N).simplify()
124
+
125
+
126
+ assert A.i == express((cos(q1)*N.i + sin(q1)*N.j), A).simplify()
127
+ assert A.j == express((-sin(q1)*N.i + cos(q1)*N.j), A).simplify()
128
+
129
+ assert A.j == express((cos(q2)*B.j - sin(q2)*B.k), A).simplify()
130
+ assert A.k == express((sin(q2)*B.j + cos(q2)*B.k), A).simplify()
131
+
132
+ assert A.i == express((cos(q3)*C.i + sin(q3)*C.k), A).simplify()
133
+ assert A.j == express((sin(q2)*sin(q3)*C.i + cos(q2)*C.j -
134
+ sin(q2)*cos(q3)*C.k), A).simplify()
135
+
136
+ assert A.k == express((-sin(q3)*cos(q2)*C.i + sin(q2)*C.j +
137
+ cos(q2)*cos(q3)*C.k), A).simplify()
138
+ assert B.i == express((cos(q1)*N.i + sin(q1)*N.j), B).simplify()
139
+ assert B.j == express((-sin(q1)*cos(q2)*N.i +
140
+ cos(q1)*cos(q2)*N.j + sin(q2)*N.k), B).simplify()
141
+
142
+ assert B.k == express((sin(q1)*sin(q2)*N.i -
143
+ sin(q2)*cos(q1)*N.j + cos(q2)*N.k), B).simplify()
144
+
145
+ assert B.j == express((cos(q2)*A.j + sin(q2)*A.k), B).simplify()
146
+ assert B.k == express((-sin(q2)*A.j + cos(q2)*A.k), B).simplify()
147
+ assert B.i == express((cos(q3)*C.i + sin(q3)*C.k), B).simplify()
148
+ assert B.k == express((-sin(q3)*C.i + cos(q3)*C.k), B).simplify()
149
+ assert C.i == express((cos(q3)*A.i + sin(q2)*sin(q3)*A.j -
150
+ sin(q3)*cos(q2)*A.k), C).simplify()
151
+ assert C.j == express((cos(q2)*A.j + sin(q2)*A.k), C).simplify()
152
+ assert C.k == express((sin(q3)*A.i - sin(q2)*cos(q3)*A.j +
153
+ cos(q2)*cos(q3)*A.k), C).simplify()
154
+ assert C.i == express((cos(q3)*B.i - sin(q3)*B.k), C).simplify()
155
+ assert C.k == express((sin(q3)*B.i + cos(q3)*B.k), C).simplify()
156
+
157
+
158
+ def test_matrix_to_vector():
159
+ m = Matrix([[1], [2], [3]])
160
+ assert matrix_to_vector(m, C) == C.i + 2*C.j + 3*C.k
161
+ m = Matrix([[0], [0], [0]])
162
+ assert matrix_to_vector(m, N) == matrix_to_vector(m, C) == \
163
+ Vector.zero
164
+ m = Matrix([[q1], [q2], [q3]])
165
+ assert matrix_to_vector(m, N) == q1*N.i + q2*N.j + q3*N.k
166
+
167
+
168
+ def test_orthogonalize():
169
+ C = CoordSys3D('C')
170
+ a, b = symbols('a b', integer=True)
171
+ i, j, k = C.base_vectors()
172
+ v1 = i + 2*j
173
+ v2 = 2*i + 3*j
174
+ v3 = 3*i + 5*j
175
+ v4 = 3*i + j
176
+ v5 = 2*i + 2*j
177
+ v6 = a*i + b*j
178
+ v7 = 4*a*i + 4*b*j
179
+ assert orthogonalize(v1, v2) == [C.i + 2*C.j, C.i*Rational(2, 5) + -C.j/5]
180
+ # from wikipedia
181
+ assert orthogonalize(v4, v5, orthonormal=True) == \
182
+ [(3*sqrt(10))*C.i/10 + (sqrt(10))*C.j/10, (-sqrt(10))*C.i/10 + (3*sqrt(10))*C.j/10]
183
+ raises(ValueError, lambda: orthogonalize(v1, v2, v3))
184
+ raises(ValueError, lambda: orthogonalize(v6, v7))
shared/package-files/06/06ce13e038f1e1764e6ddd251af78123ab55b15bcf19ebf9476dc6b1a8a8768b/blob ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/detail/static.h>
4
+ #include <torch/nn/module.h>
5
+ #include <torch/nn/modules/container/any_module_holder.h>
6
+ #include <torch/nn/modules/container/any_value.h>
7
+ #include <torch/nn/pimpl.h>
8
+ #include <torch/types.h>
9
+
10
+ #include <torch/csrc/autograd/variable.h>
11
+ #include <torch/csrc/utils/variadic.h>
12
+
13
+ #include <ATen/Device.h>
14
+
15
+ #include <memory>
16
+ #include <type_traits>
17
+ #include <typeinfo>
18
+ #include <utility>
19
+ #include <vector>
20
+
21
+ namespace torch {
22
+ namespace nn {
23
+
24
+ /// Stores a type erased `Module`.
25
+ ///
26
+ /// The PyTorch C++ API does not impose an interface on the signature of
27
+ /// `forward()` in `Module` subclasses. This gives you complete freedom to
28
+ /// design your `forward()` methods to your liking. However, this also means
29
+ /// there is no unified base type you could store in order to call `forward()`
30
+ /// polymorphically for any module. This is where the `AnyModule` comes in.
31
+ /// Instead of inheritance, it relies on type erasure for polymorphism.
32
+ ///
33
+ /// An `AnyModule` can store any `nn::Module` subclass that provides a
34
+ /// `forward()` method. This `forward()` may accept any types and return any
35
+ /// type. Once stored in an `AnyModule`, you can invoke the underlying module's
36
+ /// `forward()` by calling `AnyModule::forward()` with the arguments you would
37
+ /// supply to the stored module (though see one important limitation below).
38
+ /// Example:
39
+ ///
40
+ /// \rst
41
+ /// .. code-block:: cpp
42
+ ///
43
+ /// struct GenericTrainer {
44
+ /// torch::nn::AnyModule module;
45
+ ///
46
+ /// void train(torch::Tensor input) {
47
+ /// module.forward(input);
48
+ /// }
49
+ /// };
50
+ ///
51
+ /// GenericTrainer trainer1{torch::nn::Linear(3, 4)};
52
+ /// GenericTrainer trainer2{torch::nn::Conv2d(3, 4, 2)};
53
+ /// \endrst
54
+ ///
55
+ /// As `AnyModule` erases the static type of the stored module (and its
56
+ /// `forward()` method) to achieve polymorphism, type checking of arguments is
57
+ /// moved to runtime. That is, passing an argument with an incorrect type to an
58
+ /// `AnyModule` will compile, but throw an exception at runtime:
59
+ ///
60
+ /// \rst
61
+ /// .. code-block:: cpp
62
+ ///
63
+ /// torch::nn::AnyModule module(torch::nn::Linear(3, 4));
64
+ /// // Linear takes a tensor as input, but we are passing an integer.
65
+ /// // This will compile, but throw a `torch::Error` exception at runtime.
66
+ /// module.forward(123);
67
+ /// \endrst
68
+ ///
69
+ /// \rst
70
+ /// .. attention::
71
+ /// One noteworthy limitation of `AnyModule` is that its `forward()` method
72
+ /// does not support implicit conversion of argument types. For example, if
73
+ /// the stored module's `forward()` method accepts a `float` and you call
74
+ /// `any_module.forward(3.4)` (where `3.4` is a `double`), this will throw
75
+ /// an exception.
76
+ /// \endrst
77
+ ///
78
+ /// The return type of the `AnyModule`'s `forward()` method is controlled via
79
+ /// the first template argument to `AnyModule::forward()`. It defaults to
80
+ /// `torch::Tensor`. To change it, you can write `any_module.forward<int>()`,
81
+ /// for example.
82
+ ///
83
+ /// \rst
84
+ /// .. code-block:: cpp
85
+ ///
86
+ /// torch::nn::AnyModule module(torch::nn::Linear(3, 4));
87
+ /// auto output = module.forward(torch::ones({2, 3}));
88
+ ///
89
+ /// struct IntModule {
90
+ /// int forward(int x) { return x; }
91
+ /// };
92
+ /// torch::nn::AnyModule module(IntModule{});
93
+ /// int output = module.forward<int>(5);
94
+ /// \endrst
95
+ ///
96
+ /// The only other method an `AnyModule` provides access to on the stored
97
+ /// module is `clone()`. However, you may acquire a handle on the module via
98
+ /// `.ptr()`, which returns a `shared_ptr<nn::Module>`. Further, if you know
99
+ /// the concrete type of the stored module, you can get a concrete handle to it
100
+ /// using `.get<T>()` where `T` is the concrete module type.
101
+ ///
102
+ /// \rst
103
+ /// .. code-block:: cpp
104
+ ///
105
+ /// torch::nn::AnyModule module(torch::nn::Linear(3, 4));
106
+ /// std::shared_ptr<nn::Module> ptr = module.ptr();
107
+ /// torch::nn::Linear linear(module.get<torch::nn::Linear>());
108
+ /// \endrst
109
+ class AnyModule {
110
+ public:
111
+ /// A default-constructed `AnyModule` is in an empty state.
112
+ AnyModule() = default;
113
+
114
+ /// Constructs an `AnyModule` from a `shared_ptr` to concrete module object.
115
+ template <typename ModuleType>
116
+ explicit AnyModule(std::shared_ptr<ModuleType> module);
117
+
118
+ /// Constructs an `AnyModule` from a concrete module object.
119
+ template <
120
+ typename ModuleType,
121
+ typename = torch::detail::enable_if_module_t<ModuleType>>
122
+ explicit AnyModule(ModuleType&& module);
123
+
124
+ /// Constructs an `AnyModule` from a module holder.
125
+ template <typename ModuleType>
126
+ explicit AnyModule(const ModuleHolder<ModuleType>& module_holder);
127
+
128
+ /// Move construction and assignment is allowed, and follows the default
129
+ /// behavior of move for `std::unique_ptr`.
130
+ AnyModule(AnyModule&&) = default;
131
+ AnyModule& operator=(AnyModule&&) = default;
132
+
133
+ /// Creates a shallow copy of an `AnyModule`.
134
+ AnyModule(const AnyModule& other);
135
+ AnyModule& operator=(const AnyModule& other);
136
+
137
+ /// Creates a deep copy of an `AnyModule` if it contains a module, else an
138
+ /// empty `AnyModule` if it is empty.
139
+ AnyModule clone(optional<Device> device = nullopt) const;
140
+
141
+ /// Assigns a module to the `AnyModule` (to circumvent the explicit
142
+ /// constructor).
143
+ template <typename ModuleType>
144
+ AnyModule& operator=(std::shared_ptr<ModuleType> module);
145
+
146
+ /// Invokes `forward()` on the contained module with the given arguments, and
147
+ /// returns the return value as an `AnyValue`. Use this method when chaining
148
+ /// `AnyModule`s in a loop.
149
+ template <typename... ArgumentTypes>
150
+ AnyValue any_forward(ArgumentTypes&&... arguments);
151
+
152
+ /// Invokes `forward()` on the contained module with the given arguments, and
153
+ /// casts the returned `AnyValue` to the supplied `ReturnType` (which defaults
154
+ /// to `torch::Tensor`).
155
+ template <typename ReturnType = torch::Tensor, typename... ArgumentTypes>
156
+ ReturnType forward(ArgumentTypes&&... arguments);
157
+
158
+ /// Attempts to cast the underlying module to the given module type. Throws an
159
+ /// exception if the types do not match.
160
+ template <typename T, typename = torch::detail::enable_if_module_t<T>>
161
+ T& get();
162
+
163
+ /// Attempts to cast the underlying module to the given module type. Throws an
164
+ /// exception if the types do not match.
165
+ template <typename T, typename = torch::detail::enable_if_module_t<T>>
166
+ const T& get() const;
167
+
168
+ /// Returns the contained module in a `nn::ModuleHolder` subclass if possible
169
+ /// (i.e. if `T` has a constructor for the underlying module type).
170
+ template <typename T, typename ContainedType = typename T::ContainedType>
171
+ T get() const;
172
+
173
+ /// Returns a `std::shared_ptr` whose dynamic type is that of the underlying
174
+ /// module.
175
+ std::shared_ptr<Module> ptr() const;
176
+
177
+ /// Like `ptr()`, but casts the pointer to the given type.
178
+ template <typename T, typename = torch::detail::enable_if_module_t<T>>
179
+ std::shared_ptr<T> ptr() const;
180
+
181
+ /// Returns the `type_info` object of the contained value.
182
+ const std::type_info& type_info() const;
183
+
184
+ /// Returns true if the `AnyModule` does not contain a module.
185
+ bool is_empty() const noexcept;
186
+
187
+ private:
188
+ /// Creates a `unique_ptr<AnyModulePlaceholder>` pointing to a
189
+ /// `AnyModuleHolder` of the correct type. This method is used to deduce the
190
+ /// arguments of the module's `forward()` method.
191
+ template <
192
+ typename ModuleType,
193
+ typename Class,
194
+ typename ReturnType,
195
+ typename... ArgumentTypes>
196
+ std::unique_ptr<AnyModulePlaceholder> make_holder(
197
+ std::shared_ptr<ModuleType>&& module,
198
+ ReturnType (Class::*)(ArgumentTypes...));
199
+
200
+ /// Helper method invoked by const and non-const `get()`.
201
+ template <typename ModuleType, typename ReturnType, typename... ArgumentTypes>
202
+ ModuleType& get_(ReturnType (ModuleType::*)(ArgumentTypes...)) const;
203
+
204
+ /// Helper method invoked by const and non-const `get()`.
205
+ template <typename ModuleType>
206
+ ModuleType& get_() const;
207
+
208
+ /// The type erased module.
209
+ std::unique_ptr<AnyModulePlaceholder> content_;
210
+ };
211
+
212
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AnyModule ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
213
+
214
+ template <typename ModuleType>
215
+ AnyModule::AnyModule(std::shared_ptr<ModuleType> module)
216
+ : content_(make_holder(
217
+ std::move(module),
218
+ &std::remove_reference<ModuleType>::type::forward)) {
219
+ // `AnyModule` can only store an `nn::Module` subclass object that provides
220
+ // a `forward()` method that has a non-templatized return type.
221
+ // (e.g. `AnyModule` cannot store `nn::Sequential`, because `nn::Sequential`'s
222
+ // `forward()` method has a templatized return type.)
223
+ static_assert(
224
+ torch::detail::is_module<ModuleType>::value,
225
+ "Can only store object derived from nn::Module into AnyModule");
226
+ static_assert(
227
+ torch::detail::has_forward<ModuleType>::value,
228
+ "Can only store module with a forward() method that has a non-templatized"
229
+ " argument type and return type into AnyModule (e.g. we cannot store nn::Sequential"
230
+ "into AnyModule, because its forward() method's argument type and return type are templatized."
231
+ " If you need to use nn::Sequentials inside each other you can subclass "
232
+ "nn::Sequential and write a non-templatized forward function for it. You can checkout "
233
+ "https://github.com/pytorch/vision/blob/2f46070f3cb1ea894d82578f3dc5677f82f34958/torchvision/csrc/models/mnasnet.cpp#L59 "
234
+ "for an example on how to do this.).");
235
+ }
236
+
237
+ template <typename ModuleType, typename>
238
+ AnyModule::AnyModule(ModuleType&& module)
239
+ : AnyModule(
240
+ std::make_shared<ModuleType>(std::forward<ModuleType>(module))) {}
241
+
242
+ template <typename ModuleType>
243
+ AnyModule::AnyModule(const ModuleHolder<ModuleType>& module_holder)
244
+ : AnyModule(module_holder.ptr()) {}
245
+
246
+ inline AnyModule::AnyModule(const AnyModule& other)
247
+ : content_(other.content_ ? other.content_->copy() : nullptr) {}
248
+
249
+ inline AnyModule& AnyModule::operator=(const AnyModule& other) {
250
+ if (this != &other) {
251
+ content_ = other.content_ ? other.content_->copy() : nullptr;
252
+ }
253
+ return *this;
254
+ }
255
+
256
+ inline AnyModule AnyModule::clone(optional<Device> device) const {
257
+ AnyModule clone;
258
+ clone.content_ = content_ ? content_->clone_module(device) : nullptr;
259
+ return clone;
260
+ }
261
+
262
+ template <typename ModuleType>
263
+ AnyModule& AnyModule::operator=(std::shared_ptr<ModuleType> module) {
264
+ // NOLINTNEXTLINE(cppcoreguidelines-c-copy-assignment-signature)
265
+ return (*this = AnyModule(std::move(module)));
266
+ }
267
+
268
+ template <typename... ArgumentTypes>
269
+ AnyValue AnyModule::any_forward(ArgumentTypes&&... arguments) {
270
+ TORCH_CHECK(!is_empty(), "Cannot call forward() on an empty AnyModule");
271
+ std::vector<AnyValue> values;
272
+ values.reserve(sizeof...(ArgumentTypes));
273
+ torch::apply(
274
+ [&values](AnyValue&& value) { values.push_back(std::move(value)); },
275
+ AnyValue(std::forward<ArgumentTypes>(arguments))...);
276
+ return content_->forward(std::move(values));
277
+ }
278
+
279
+ template <typename ReturnType, typename... ArgumentTypes>
280
+ ReturnType AnyModule::forward(ArgumentTypes&&... arguments) {
281
+ return any_forward(std::forward<ArgumentTypes>(arguments)...)
282
+ .template get<ReturnType>();
283
+ }
284
+
285
+ template <typename T, typename>
286
+ T& AnyModule::get() {
287
+ TORCH_CHECK(!is_empty(), "Cannot call get() on an empty AnyModule");
288
+ return get_<T>();
289
+ }
290
+
291
+ template <typename T, typename>
292
+ const T& AnyModule::get() const {
293
+ TORCH_CHECK(!is_empty(), "Cannot call get() on an empty AnyModule");
294
+ return get_<T>();
295
+ }
296
+
297
+ template <typename T, typename ContainedType>
298
+ T AnyModule::get() const {
299
+ return T(ptr<ContainedType>());
300
+ }
301
+
302
+ inline std::shared_ptr<Module> AnyModule::ptr() const {
303
+ TORCH_CHECK(!is_empty(), "Cannot call ptr() on an empty AnyModule");
304
+ return content_->ptr();
305
+ }
306
+
307
+ template <typename T, typename>
308
+ std::shared_ptr<T> AnyModule::ptr() const {
309
+ TORCH_CHECK(!is_empty(), "Cannot call ptr() on an empty AnyModule");
310
+ // Call get() but discard the value, just to do the type checking.
311
+ get_<T>();
312
+ return std::dynamic_pointer_cast<T>(ptr());
313
+ }
314
+
315
+ inline const std::type_info& AnyModule::type_info() const {
316
+ TORCH_CHECK(!is_empty(), "Cannot call type_info() on an empty AnyModule");
317
+ return content_->type_info;
318
+ }
319
+
320
+ inline bool AnyModule::is_empty() const noexcept {
321
+ return content_ == nullptr;
322
+ }
323
+
324
+ // Private Methods
325
+
326
+ template <
327
+ typename ModuleType,
328
+ typename Class,
329
+ typename ReturnType,
330
+ typename... ArgumentTypes>
331
+ std::unique_ptr<AnyModulePlaceholder> AnyModule::make_holder(
332
+ std::shared_ptr<ModuleType>&& module,
333
+ ReturnType (Class::*)(ArgumentTypes...)) {
334
+ static_assert(
335
+ torch::detail::check_not_lvalue_references<ArgumentTypes...>(),
336
+ "Modules stored inside AnyModule must not take references. "
337
+ "Use pointers instead.");
338
+ static_assert(
339
+ !std::is_void<ReturnType>::value,
340
+ "AnyModule cannot store modules that return void "
341
+ "(you can return a dummy value).");
342
+ return std::make_unique<
343
+ AnyModuleHolder<decay_t<ModuleType>, ArgumentTypes...>>(
344
+ std::move(module));
345
+ }
346
+
347
+ template <typename ModuleType>
348
+ ModuleType& AnyModule::get_() const {
349
+ using M = typename std::remove_reference<ModuleType>::type;
350
+ static_assert(
351
+ torch::detail::has_forward<M>::value,
352
+ "Can only call AnyModule::get<T> with a type T that has a forward method");
353
+ return get_(&M::forward);
354
+ }
355
+
356
+ template <typename ModuleType, typename ReturnType, typename... ArgumentTypes>
357
+ ModuleType& AnyModule::get_(
358
+ ReturnType (ModuleType::*)(ArgumentTypes...)) const {
359
+ if (typeid(ModuleType).hash_code() == type_info().hash_code()) {
360
+ return *static_cast<AnyModuleHolder<ModuleType, ArgumentTypes...>&>(
361
+ *content_)
362
+ .module;
363
+ }
364
+ AT_ERROR(
365
+ "Attempted to cast module of type ",
366
+ c10::demangle(type_info().name()),
367
+ " to type ",
368
+ c10::demangle(typeid(ModuleType).name()));
369
+ }
370
+
371
+ } // namespace nn
372
+ } // namespace torch
shared/package-files/06/06d043d88fb3f0ae88e46420f5080735f8995747a72a2e483128b14fee094525/blob ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ from torch.distributions import constraints
5
+ from torch.distributions.distribution import Distribution
6
+ from torch.distributions.multivariate_normal import _batch_mahalanobis, _batch_mv
7
+ from torch.distributions.utils import _standard_normal, lazy_property
8
+
9
+ __all__ = ["LowRankMultivariateNormal"]
10
+
11
+
12
+ def _batch_capacitance_tril(W, D):
13
+ r"""
14
+ Computes Cholesky of :math:`I + W.T @ inv(D) @ W` for a batch of matrices :math:`W`
15
+ and a batch of vectors :math:`D`.
16
+ """
17
+ m = W.size(-1)
18
+ Wt_Dinv = W.mT / D.unsqueeze(-2)
19
+ K = torch.matmul(Wt_Dinv, W).contiguous()
20
+ K.view(-1, m * m)[:, :: m + 1] += 1 # add identity matrix to K
21
+ return torch.linalg.cholesky(K)
22
+
23
+
24
+ def _batch_lowrank_logdet(W, D, capacitance_tril):
25
+ r"""
26
+ Uses "matrix determinant lemma"::
27
+ log|W @ W.T + D| = log|C| + log|D|,
28
+ where :math:`C` is the capacitance matrix :math:`I + W.T @ inv(D) @ W`, to compute
29
+ the log determinant.
30
+ """
31
+ return 2 * capacitance_tril.diagonal(dim1=-2, dim2=-1).log().sum(-1) + D.log().sum(
32
+ -1
33
+ )
34
+
35
+
36
+ def _batch_lowrank_mahalanobis(W, D, x, capacitance_tril):
37
+ r"""
38
+ Uses "Woodbury matrix identity"::
39
+ inv(W @ W.T + D) = inv(D) - inv(D) @ W @ inv(C) @ W.T @ inv(D),
40
+ where :math:`C` is the capacitance matrix :math:`I + W.T @ inv(D) @ W`, to compute the squared
41
+ Mahalanobis distance :math:`x.T @ inv(W @ W.T + D) @ x`.
42
+ """
43
+ Wt_Dinv = W.mT / D.unsqueeze(-2)
44
+ Wt_Dinv_x = _batch_mv(Wt_Dinv, x)
45
+ mahalanobis_term1 = (x.pow(2) / D).sum(-1)
46
+ mahalanobis_term2 = _batch_mahalanobis(capacitance_tril, Wt_Dinv_x)
47
+ return mahalanobis_term1 - mahalanobis_term2
48
+
49
+
50
+ class LowRankMultivariateNormal(Distribution):
51
+ r"""
52
+ Creates a multivariate normal distribution with covariance matrix having a low-rank form
53
+ parameterized by :attr:`cov_factor` and :attr:`cov_diag`::
54
+
55
+ covariance_matrix = cov_factor @ cov_factor.T + cov_diag
56
+
57
+ Example:
58
+ >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK)
59
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
60
+ >>> m = LowRankMultivariateNormal(torch.zeros(2), torch.tensor([[1.], [0.]]), torch.ones(2))
61
+ >>> m.sample() # normally distributed with mean=`[0,0]`, cov_factor=`[[1],[0]]`, cov_diag=`[1,1]`
62
+ tensor([-0.2102, -0.5429])
63
+
64
+ Args:
65
+ loc (Tensor): mean of the distribution with shape `batch_shape + event_shape`
66
+ cov_factor (Tensor): factor part of low-rank form of covariance matrix with shape
67
+ `batch_shape + event_shape + (rank,)`
68
+ cov_diag (Tensor): diagonal part of low-rank form of covariance matrix with shape
69
+ `batch_shape + event_shape`
70
+
71
+ Note:
72
+ The computation for determinant and inverse of covariance matrix is avoided when
73
+ `cov_factor.shape[1] << cov_factor.shape[0]` thanks to `Woodbury matrix identity
74
+ <https://en.wikipedia.org/wiki/Woodbury_matrix_identity>`_ and
75
+ `matrix determinant lemma <https://en.wikipedia.org/wiki/Matrix_determinant_lemma>`_.
76
+ Thanks to these formulas, we just need to compute the determinant and inverse of
77
+ the small size "capacitance" matrix::
78
+
79
+ capacitance = I + cov_factor.T @ inv(cov_diag) @ cov_factor
80
+ """
81
+ arg_constraints = {
82
+ "loc": constraints.real_vector,
83
+ "cov_factor": constraints.independent(constraints.real, 2),
84
+ "cov_diag": constraints.independent(constraints.positive, 1),
85
+ }
86
+ support = constraints.real_vector
87
+ has_rsample = True
88
+
89
+ def __init__(self, loc, cov_factor, cov_diag, validate_args=None):
90
+ if loc.dim() < 1:
91
+ raise ValueError("loc must be at least one-dimensional.")
92
+ event_shape = loc.shape[-1:]
93
+ if cov_factor.dim() < 2:
94
+ raise ValueError(
95
+ "cov_factor must be at least two-dimensional, "
96
+ "with optional leading batch dimensions"
97
+ )
98
+ if cov_factor.shape[-2:-1] != event_shape:
99
+ raise ValueError(
100
+ f"cov_factor must be a batch of matrices with shape {event_shape[0]} x m"
101
+ )
102
+ if cov_diag.shape[-1:] != event_shape:
103
+ raise ValueError(
104
+ f"cov_diag must be a batch of vectors with shape {event_shape}"
105
+ )
106
+
107
+ loc_ = loc.unsqueeze(-1)
108
+ cov_diag_ = cov_diag.unsqueeze(-1)
109
+ try:
110
+ loc_, self.cov_factor, cov_diag_ = torch.broadcast_tensors(
111
+ loc_, cov_factor, cov_diag_
112
+ )
113
+ except RuntimeError as e:
114
+ raise ValueError(
115
+ f"Incompatible batch shapes: loc {loc.shape}, cov_factor {cov_factor.shape}, cov_diag {cov_diag.shape}"
116
+ ) from e
117
+ self.loc = loc_[..., 0]
118
+ self.cov_diag = cov_diag_[..., 0]
119
+ batch_shape = self.loc.shape[:-1]
120
+
121
+ self._unbroadcasted_cov_factor = cov_factor
122
+ self._unbroadcasted_cov_diag = cov_diag
123
+ self._capacitance_tril = _batch_capacitance_tril(cov_factor, cov_diag)
124
+ super().__init__(batch_shape, event_shape, validate_args=validate_args)
125
+
126
+ def expand(self, batch_shape, _instance=None):
127
+ new = self._get_checked_instance(LowRankMultivariateNormal, _instance)
128
+ batch_shape = torch.Size(batch_shape)
129
+ loc_shape = batch_shape + self.event_shape
130
+ new.loc = self.loc.expand(loc_shape)
131
+ new.cov_diag = self.cov_diag.expand(loc_shape)
132
+ new.cov_factor = self.cov_factor.expand(loc_shape + self.cov_factor.shape[-1:])
133
+ new._unbroadcasted_cov_factor = self._unbroadcasted_cov_factor
134
+ new._unbroadcasted_cov_diag = self._unbroadcasted_cov_diag
135
+ new._capacitance_tril = self._capacitance_tril
136
+ super(LowRankMultivariateNormal, new).__init__(
137
+ batch_shape, self.event_shape, validate_args=False
138
+ )
139
+ new._validate_args = self._validate_args
140
+ return new
141
+
142
+ @property
143
+ def mean(self):
144
+ return self.loc
145
+
146
+ @property
147
+ def mode(self):
148
+ return self.loc
149
+
150
+ @lazy_property
151
+ def variance(self):
152
+ return (
153
+ self._unbroadcasted_cov_factor.pow(2).sum(-1) + self._unbroadcasted_cov_diag
154
+ ).expand(self._batch_shape + self._event_shape)
155
+
156
+ @lazy_property
157
+ def scale_tril(self):
158
+ # The following identity is used to increase the numerically computation stability
159
+ # for Cholesky decomposition (see http://www.gaussianprocess.org/gpml/, Section 3.4.3):
160
+ # W @ W.T + D = D1/2 @ (I + D-1/2 @ W @ W.T @ D-1/2) @ D1/2
161
+ # The matrix "I + D-1/2 @ W @ W.T @ D-1/2" has eigenvalues bounded from below by 1,
162
+ # hence it is well-conditioned and safe to take Cholesky decomposition.
163
+ n = self._event_shape[0]
164
+ cov_diag_sqrt_unsqueeze = self._unbroadcasted_cov_diag.sqrt().unsqueeze(-1)
165
+ Dinvsqrt_W = self._unbroadcasted_cov_factor / cov_diag_sqrt_unsqueeze
166
+ K = torch.matmul(Dinvsqrt_W, Dinvsqrt_W.mT).contiguous()
167
+ K.view(-1, n * n)[:, :: n + 1] += 1 # add identity matrix to K
168
+ scale_tril = cov_diag_sqrt_unsqueeze * torch.linalg.cholesky(K)
169
+ return scale_tril.expand(
170
+ self._batch_shape + self._event_shape + self._event_shape
171
+ )
172
+
173
+ @lazy_property
174
+ def covariance_matrix(self):
175
+ covariance_matrix = torch.matmul(
176
+ self._unbroadcasted_cov_factor, self._unbroadcasted_cov_factor.mT
177
+ ) + torch.diag_embed(self._unbroadcasted_cov_diag)
178
+ return covariance_matrix.expand(
179
+ self._batch_shape + self._event_shape + self._event_shape
180
+ )
181
+
182
+ @lazy_property
183
+ def precision_matrix(self):
184
+ # We use "Woodbury matrix identity" to take advantage of low rank form::
185
+ # inv(W @ W.T + D) = inv(D) - inv(D) @ W @ inv(C) @ W.T @ inv(D)
186
+ # where :math:`C` is the capacitance matrix.
187
+ Wt_Dinv = (
188
+ self._unbroadcasted_cov_factor.mT
189
+ / self._unbroadcasted_cov_diag.unsqueeze(-2)
190
+ )
191
+ A = torch.linalg.solve_triangular(self._capacitance_tril, Wt_Dinv, upper=False)
192
+ precision_matrix = (
193
+ torch.diag_embed(self._unbroadcasted_cov_diag.reciprocal()) - A.mT @ A
194
+ )
195
+ return precision_matrix.expand(
196
+ self._batch_shape + self._event_shape + self._event_shape
197
+ )
198
+
199
+ def rsample(self, sample_shape=torch.Size()):
200
+ shape = self._extended_shape(sample_shape)
201
+ W_shape = shape[:-1] + self.cov_factor.shape[-1:]
202
+ eps_W = _standard_normal(W_shape, dtype=self.loc.dtype, device=self.loc.device)
203
+ eps_D = _standard_normal(shape, dtype=self.loc.dtype, device=self.loc.device)
204
+ return (
205
+ self.loc
206
+ + _batch_mv(self._unbroadcasted_cov_factor, eps_W)
207
+ + self._unbroadcasted_cov_diag.sqrt() * eps_D
208
+ )
209
+
210
+ def log_prob(self, value):
211
+ if self._validate_args:
212
+ self._validate_sample(value)
213
+ diff = value - self.loc
214
+ M = _batch_lowrank_mahalanobis(
215
+ self._unbroadcasted_cov_factor,
216
+ self._unbroadcasted_cov_diag,
217
+ diff,
218
+ self._capacitance_tril,
219
+ )
220
+ log_det = _batch_lowrank_logdet(
221
+ self._unbroadcasted_cov_factor,
222
+ self._unbroadcasted_cov_diag,
223
+ self._capacitance_tril,
224
+ )
225
+ return -0.5 * (self._event_shape[0] * math.log(2 * math.pi) + log_det + M)
226
+
227
+ def entropy(self):
228
+ log_det = _batch_lowrank_logdet(
229
+ self._unbroadcasted_cov_factor,
230
+ self._unbroadcasted_cov_diag,
231
+ self._capacitance_tril,
232
+ )
233
+ H = 0.5 * (self._event_shape[0] * (1.0 + math.log(2 * math.pi)) + log_det)
234
+ if len(self._batch_shape) == 0:
235
+ return H
236
+ else:
237
+ return H.expand(self._batch_shape)
shared/package-files/06/06d090ae1a5cf3f42e004c937acfa25d9bcd1830a4e0c7218eaf4e0ee7a40025/blob ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API sparse_csc_tensor_ccol_row_value_size {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::IntArrayRef, c10::optional<at::ScalarType>, c10::optional<at::Layout>, c10::optional<at::Device>, c10::optional<bool>);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::sparse_csc_tensor")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ccol_row_value_size")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sparse_csc_tensor.ccol_row_value_size(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
26
+ };
27
+
28
+ struct TORCH_API sparse_csc_tensor_ccol_row_value {
29
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, c10::optional<at::ScalarType>, c10::optional<at::Layout>, c10::optional<at::Device>, c10::optional<bool>);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::sparse_csc_tensor")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ccol_row_value")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sparse_csc_tensor.ccol_row_value(Tensor ccol_indices, Tensor row_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor")
35
+ static at::Tensor call(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
37
+ };
38
+
39
+ }} // namespace at::_ops
shared/package-files/06/06d0d1944c1296f3a1c68d38997407a73cada15f8523f2b9c95b344405fc7812/blob ADDED
@@ -0,0 +1,1603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2009, Pauli Virtanen <pav@iki.fi>
2
+ # Distributed under the same license as SciPy.
3
+
4
+ import inspect
5
+ import sys
6
+ import warnings
7
+
8
+ import numpy as np
9
+ from numpy import asarray, dot, vdot
10
+
11
+ from scipy.linalg import norm, solve, inv, qr, svd, LinAlgError
12
+ import scipy.sparse.linalg
13
+ import scipy.sparse
14
+ from scipy.linalg import get_blas_funcs
15
+ from scipy._lib._util import copy_if_needed
16
+ from scipy._lib._util import getfullargspec_no_self as _getfullargspec
17
+ from ._linesearch import scalar_search_wolfe1, scalar_search_armijo
18
+
19
+
20
+ __all__ = [
21
+ 'broyden1', 'broyden2', 'anderson', 'linearmixing',
22
+ 'diagbroyden', 'excitingmixing', 'newton_krylov',
23
+ 'BroydenFirst', 'KrylovJacobian', 'InverseJacobian', 'NoConvergence']
24
+
25
+ #------------------------------------------------------------------------------
26
+ # Utility functions
27
+ #------------------------------------------------------------------------------
28
+
29
+
30
+ class NoConvergence(Exception):
31
+ """Exception raised when nonlinear solver fails to converge within the specified
32
+ `maxiter`."""
33
+ pass
34
+
35
+
36
+ def maxnorm(x):
37
+ return np.absolute(x).max()
38
+
39
+
40
+ def _as_inexact(x):
41
+ """Return `x` as an array, of either floats or complex floats"""
42
+ x = asarray(x)
43
+ if not np.issubdtype(x.dtype, np.inexact):
44
+ return asarray(x, dtype=np.float64)
45
+ return x
46
+
47
+
48
+ def _array_like(x, x0):
49
+ """Return ndarray `x` as same array subclass and shape as `x0`"""
50
+ x = np.reshape(x, np.shape(x0))
51
+ wrap = getattr(x0, '__array_wrap__', x.__array_wrap__)
52
+ return wrap(x)
53
+
54
+
55
+ def _safe_norm(v):
56
+ if not np.isfinite(v).all():
57
+ return np.array(np.inf)
58
+ return norm(v)
59
+
60
+ #------------------------------------------------------------------------------
61
+ # Generic nonlinear solver machinery
62
+ #------------------------------------------------------------------------------
63
+
64
+
65
+ _doc_parts = dict(
66
+ params_basic="""
67
+ F : function(x) -> f
68
+ Function whose root to find; should take and return an array-like
69
+ object.
70
+ xin : array_like
71
+ Initial guess for the solution
72
+ """.strip(),
73
+ params_extra="""
74
+ iter : int, optional
75
+ Number of iterations to make. If omitted (default), make as many
76
+ as required to meet tolerances.
77
+ verbose : bool, optional
78
+ Print status to stdout on every iteration.
79
+ maxiter : int, optional
80
+ Maximum number of iterations to make. If more are needed to
81
+ meet convergence, `NoConvergence` is raised.
82
+ f_tol : float, optional
83
+ Absolute tolerance (in max-norm) for the residual.
84
+ If omitted, default is 6e-6.
85
+ f_rtol : float, optional
86
+ Relative tolerance for the residual. If omitted, not used.
87
+ x_tol : float, optional
88
+ Absolute minimum step size, as determined from the Jacobian
89
+ approximation. If the step size is smaller than this, optimization
90
+ is terminated as successful. If omitted, not used.
91
+ x_rtol : float, optional
92
+ Relative minimum step size. If omitted, not used.
93
+ tol_norm : function(vector) -> scalar, optional
94
+ Norm to use in convergence check. Default is the maximum norm.
95
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
96
+ Which type of a line search to use to determine the step size in the
97
+ direction given by the Jacobian approximation. Defaults to 'armijo'.
98
+ callback : function, optional
99
+ Optional callback function. It is called on every iteration as
100
+ ``callback(x, f)`` where `x` is the current solution and `f`
101
+ the corresponding residual.
102
+
103
+ Returns
104
+ -------
105
+ sol : ndarray
106
+ An array (of similar array type as `x0`) containing the final solution.
107
+
108
+ Raises
109
+ ------
110
+ NoConvergence
111
+ When a solution was not found.
112
+
113
+ """.strip()
114
+ )
115
+
116
+
117
+ def _set_doc(obj):
118
+ if obj.__doc__:
119
+ obj.__doc__ = obj.__doc__ % _doc_parts
120
+
121
+
122
+ def nonlin_solve(F, x0, jacobian='krylov', iter=None, verbose=False,
123
+ maxiter=None, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
124
+ tol_norm=None, line_search='armijo', callback=None,
125
+ full_output=False, raise_exception=True):
126
+ """
127
+ Find a root of a function, in a way suitable for large-scale problems.
128
+
129
+ Parameters
130
+ ----------
131
+ %(params_basic)s
132
+ jacobian : Jacobian
133
+ A Jacobian approximation: `Jacobian` object or something that
134
+ `asjacobian` can transform to one. Alternatively, a string specifying
135
+ which of the builtin Jacobian approximations to use:
136
+
137
+ krylov, broyden1, broyden2, anderson
138
+ diagbroyden, linearmixing, excitingmixing
139
+
140
+ %(params_extra)s
141
+ full_output : bool
142
+ If true, returns a dictionary `info` containing convergence
143
+ information.
144
+ raise_exception : bool
145
+ If True, a `NoConvergence` exception is raise if no solution is found.
146
+
147
+ See Also
148
+ --------
149
+ asjacobian, Jacobian
150
+
151
+ Notes
152
+ -----
153
+ This algorithm implements the inexact Newton method, with
154
+ backtracking or full line searches. Several Jacobian
155
+ approximations are available, including Krylov and Quasi-Newton
156
+ methods.
157
+
158
+ References
159
+ ----------
160
+ .. [KIM] C. T. Kelley, \"Iterative Methods for Linear and Nonlinear
161
+ Equations\". Society for Industrial and Applied Mathematics. (1995)
162
+ https://archive.siam.org/books/kelley/fr16/
163
+
164
+ """
165
+ # Can't use default parameters because it's being explicitly passed as None
166
+ # from the calling function, so we need to set it here.
167
+ tol_norm = maxnorm if tol_norm is None else tol_norm
168
+ condition = TerminationCondition(f_tol=f_tol, f_rtol=f_rtol,
169
+ x_tol=x_tol, x_rtol=x_rtol,
170
+ iter=iter, norm=tol_norm)
171
+
172
+ x0 = _as_inexact(x0)
173
+ def func(z):
174
+ return _as_inexact(F(_array_like(z, x0))).flatten()
175
+ x = x0.flatten()
176
+
177
+ dx = np.full_like(x, np.inf)
178
+ Fx = func(x)
179
+ Fx_norm = norm(Fx)
180
+
181
+ jacobian = asjacobian(jacobian)
182
+ jacobian.setup(x.copy(), Fx, func)
183
+
184
+ if maxiter is None:
185
+ if iter is not None:
186
+ maxiter = iter + 1
187
+ else:
188
+ maxiter = 100*(x.size+1)
189
+
190
+ if line_search is True:
191
+ line_search = 'armijo'
192
+ elif line_search is False:
193
+ line_search = None
194
+
195
+ if line_search not in (None, 'armijo', 'wolfe'):
196
+ raise ValueError("Invalid line search")
197
+
198
+ # Solver tolerance selection
199
+ gamma = 0.9
200
+ eta_max = 0.9999
201
+ eta_treshold = 0.1
202
+ eta = 1e-3
203
+
204
+ for n in range(maxiter):
205
+ status = condition.check(Fx, x, dx)
206
+ if status:
207
+ break
208
+
209
+ # The tolerance, as computed for scipy.sparse.linalg.* routines
210
+ tol = min(eta, eta*Fx_norm)
211
+ dx = -jacobian.solve(Fx, tol=tol)
212
+
213
+ if norm(dx) == 0:
214
+ raise ValueError("Jacobian inversion yielded zero vector. "
215
+ "This indicates a bug in the Jacobian "
216
+ "approximation.")
217
+
218
+ # Line search, or Newton step
219
+ if line_search:
220
+ s, x, Fx, Fx_norm_new = _nonlin_line_search(func, x, Fx, dx,
221
+ line_search)
222
+ else:
223
+ s = 1.0
224
+ x = x + dx
225
+ Fx = func(x)
226
+ Fx_norm_new = norm(Fx)
227
+
228
+ jacobian.update(x.copy(), Fx)
229
+
230
+ if callback:
231
+ callback(x, Fx)
232
+
233
+ # Adjust forcing parameters for inexact methods
234
+ eta_A = gamma * Fx_norm_new**2 / Fx_norm**2
235
+ if gamma * eta**2 < eta_treshold:
236
+ eta = min(eta_max, eta_A)
237
+ else:
238
+ eta = min(eta_max, max(eta_A, gamma*eta**2))
239
+
240
+ Fx_norm = Fx_norm_new
241
+
242
+ # Print status
243
+ if verbose:
244
+ sys.stdout.write("%d: |F(x)| = %g; step %g\n" % (
245
+ n, tol_norm(Fx), s))
246
+ sys.stdout.flush()
247
+ else:
248
+ if raise_exception:
249
+ raise NoConvergence(_array_like(x, x0))
250
+ else:
251
+ status = 2
252
+
253
+ if full_output:
254
+ info = {'nit': condition.iteration,
255
+ 'fun': Fx,
256
+ 'status': status,
257
+ 'success': status == 1,
258
+ 'message': {1: 'A solution was found at the specified '
259
+ 'tolerance.',
260
+ 2: 'The maximum number of iterations allowed '
261
+ 'has been reached.'
262
+ }[status]
263
+ }
264
+ return _array_like(x, x0), info
265
+ else:
266
+ return _array_like(x, x0)
267
+
268
+
269
+ _set_doc(nonlin_solve)
270
+
271
+
272
+ def _nonlin_line_search(func, x, Fx, dx, search_type='armijo', rdiff=1e-8,
273
+ smin=1e-2):
274
+ tmp_s = [0]
275
+ tmp_Fx = [Fx]
276
+ tmp_phi = [norm(Fx)**2]
277
+ s_norm = norm(x) / norm(dx)
278
+
279
+ def phi(s, store=True):
280
+ if s == tmp_s[0]:
281
+ return tmp_phi[0]
282
+ xt = x + s*dx
283
+ v = func(xt)
284
+ p = _safe_norm(v)**2
285
+ if store:
286
+ tmp_s[0] = s
287
+ tmp_phi[0] = p
288
+ tmp_Fx[0] = v
289
+ return p
290
+
291
+ def derphi(s):
292
+ ds = (abs(s) + s_norm + 1) * rdiff
293
+ return (phi(s+ds, store=False) - phi(s)) / ds
294
+
295
+ if search_type == 'wolfe':
296
+ s, phi1, phi0 = scalar_search_wolfe1(phi, derphi, tmp_phi[0],
297
+ xtol=1e-2, amin=smin)
298
+ elif search_type == 'armijo':
299
+ s, phi1 = scalar_search_armijo(phi, tmp_phi[0], -tmp_phi[0],
300
+ amin=smin)
301
+
302
+ if s is None:
303
+ # XXX: No suitable step length found. Take the full Newton step,
304
+ # and hope for the best.
305
+ s = 1.0
306
+
307
+ x = x + s*dx
308
+ if s == tmp_s[0]:
309
+ Fx = tmp_Fx[0]
310
+ else:
311
+ Fx = func(x)
312
+ Fx_norm = norm(Fx)
313
+
314
+ return s, x, Fx, Fx_norm
315
+
316
+
317
+ class TerminationCondition:
318
+ """
319
+ Termination condition for an iteration. It is terminated if
320
+
321
+ - |F| < f_rtol*|F_0|, AND
322
+ - |F| < f_tol
323
+
324
+ AND
325
+
326
+ - |dx| < x_rtol*|x|, AND
327
+ - |dx| < x_tol
328
+
329
+ """
330
+ def __init__(self, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
331
+ iter=None, norm=maxnorm):
332
+
333
+ if f_tol is None:
334
+ f_tol = np.finfo(np.float64).eps ** (1./3)
335
+ if f_rtol is None:
336
+ f_rtol = np.inf
337
+ if x_tol is None:
338
+ x_tol = np.inf
339
+ if x_rtol is None:
340
+ x_rtol = np.inf
341
+
342
+ self.x_tol = x_tol
343
+ self.x_rtol = x_rtol
344
+ self.f_tol = f_tol
345
+ self.f_rtol = f_rtol
346
+
347
+ self.norm = norm
348
+
349
+ self.iter = iter
350
+
351
+ self.f0_norm = None
352
+ self.iteration = 0
353
+
354
+ def check(self, f, x, dx):
355
+ self.iteration += 1
356
+ f_norm = self.norm(f)
357
+ x_norm = self.norm(x)
358
+ dx_norm = self.norm(dx)
359
+
360
+ if self.f0_norm is None:
361
+ self.f0_norm = f_norm
362
+
363
+ if f_norm == 0:
364
+ return 1
365
+
366
+ if self.iter is not None:
367
+ # backwards compatibility with SciPy 0.6.0
368
+ return 2 * (self.iteration > self.iter)
369
+
370
+ # NB: condition must succeed for rtol=inf even if norm == 0
371
+ return int((f_norm <= self.f_tol
372
+ and f_norm/self.f_rtol <= self.f0_norm)
373
+ and (dx_norm <= self.x_tol
374
+ and dx_norm/self.x_rtol <= x_norm))
375
+
376
+
377
+ #------------------------------------------------------------------------------
378
+ # Generic Jacobian approximation
379
+ #------------------------------------------------------------------------------
380
+
381
+ class Jacobian:
382
+ """
383
+ Common interface for Jacobians or Jacobian approximations.
384
+
385
+ The optional methods come useful when implementing trust region
386
+ etc., algorithms that often require evaluating transposes of the
387
+ Jacobian.
388
+
389
+ Methods
390
+ -------
391
+ solve
392
+ Returns J^-1 * v
393
+ update
394
+ Updates Jacobian to point `x` (where the function has residual `Fx`)
395
+
396
+ matvec : optional
397
+ Returns J * v
398
+ rmatvec : optional
399
+ Returns A^H * v
400
+ rsolve : optional
401
+ Returns A^-H * v
402
+ matmat : optional
403
+ Returns A * V, where V is a dense matrix with dimensions (N,K).
404
+ todense : optional
405
+ Form the dense Jacobian matrix. Necessary for dense trust region
406
+ algorithms, and useful for testing.
407
+
408
+ Attributes
409
+ ----------
410
+ shape
411
+ Matrix dimensions (M, N)
412
+ dtype
413
+ Data type of the matrix.
414
+ func : callable, optional
415
+ Function the Jacobian corresponds to
416
+
417
+ """
418
+
419
+ def __init__(self, **kw):
420
+ names = ["solve", "update", "matvec", "rmatvec", "rsolve",
421
+ "matmat", "todense", "shape", "dtype"]
422
+ for name, value in kw.items():
423
+ if name not in names:
424
+ raise ValueError(f"Unknown keyword argument {name}")
425
+ if value is not None:
426
+ setattr(self, name, kw[name])
427
+
428
+
429
+ if hasattr(self, "todense"):
430
+ def __array__(self, dtype=None, copy=None):
431
+ if dtype is not None:
432
+ raise ValueError(f"`dtype` must be None, was {dtype}")
433
+ return self.todense()
434
+
435
+ def aspreconditioner(self):
436
+ return InverseJacobian(self)
437
+
438
+ def solve(self, v, tol=0):
439
+ raise NotImplementedError
440
+
441
+ def update(self, x, F):
442
+ pass
443
+
444
+ def setup(self, x, F, func):
445
+ self.func = func
446
+ self.shape = (F.size, x.size)
447
+ self.dtype = F.dtype
448
+ if self.__class__.setup is Jacobian.setup:
449
+ # Call on the first point unless overridden
450
+ self.update(x, F)
451
+
452
+
453
+ class InverseJacobian:
454
+ """
455
+ A simple wrapper that inverts the Jacobian using the `solve` method.
456
+
457
+ .. legacy:: class
458
+
459
+ See the newer, more consistent interfaces in :mod:`scipy.optimize`.
460
+
461
+ Parameters
462
+ ----------
463
+ jacobian : Jacobian
464
+ The Jacobian to invert.
465
+
466
+ Attributes
467
+ ----------
468
+ shape
469
+ Matrix dimensions (M, N)
470
+ dtype
471
+ Data type of the matrix.
472
+
473
+ """
474
+ def __init__(self, jacobian):
475
+ self.jacobian = jacobian
476
+ self.matvec = jacobian.solve
477
+ self.update = jacobian.update
478
+ if hasattr(jacobian, 'setup'):
479
+ self.setup = jacobian.setup
480
+ if hasattr(jacobian, 'rsolve'):
481
+ self.rmatvec = jacobian.rsolve
482
+
483
+ @property
484
+ def shape(self):
485
+ return self.jacobian.shape
486
+
487
+ @property
488
+ def dtype(self):
489
+ return self.jacobian.dtype
490
+
491
+
492
+ def asjacobian(J):
493
+ """
494
+ Convert given object to one suitable for use as a Jacobian.
495
+ """
496
+ spsolve = scipy.sparse.linalg.spsolve
497
+ if isinstance(J, Jacobian):
498
+ return J
499
+ elif inspect.isclass(J) and issubclass(J, Jacobian):
500
+ return J()
501
+ elif isinstance(J, np.ndarray):
502
+ if J.ndim > 2:
503
+ raise ValueError('array must have rank <= 2')
504
+ J = np.atleast_2d(np.asarray(J))
505
+ if J.shape[0] != J.shape[1]:
506
+ raise ValueError('array must be square')
507
+
508
+ return Jacobian(matvec=lambda v: dot(J, v),
509
+ rmatvec=lambda v: dot(J.conj().T, v),
510
+ solve=lambda v, tol=0: solve(J, v),
511
+ rsolve=lambda v, tol=0: solve(J.conj().T, v),
512
+ dtype=J.dtype, shape=J.shape)
513
+ elif scipy.sparse.issparse(J):
514
+ if J.shape[0] != J.shape[1]:
515
+ raise ValueError('matrix must be square')
516
+ return Jacobian(matvec=lambda v: J @ v,
517
+ rmatvec=lambda v: J.conj().T @ v,
518
+ solve=lambda v, tol=0: spsolve(J, v),
519
+ rsolve=lambda v, tol=0: spsolve(J.conj().T, v),
520
+ dtype=J.dtype, shape=J.shape)
521
+ elif hasattr(J, 'shape') and hasattr(J, 'dtype') and hasattr(J, 'solve'):
522
+ return Jacobian(matvec=getattr(J, 'matvec'),
523
+ rmatvec=getattr(J, 'rmatvec'),
524
+ solve=J.solve,
525
+ rsolve=getattr(J, 'rsolve'),
526
+ update=getattr(J, 'update'),
527
+ setup=getattr(J, 'setup'),
528
+ dtype=J.dtype,
529
+ shape=J.shape)
530
+ elif callable(J):
531
+ # Assume it's a function J(x) that returns the Jacobian
532
+ class Jac(Jacobian):
533
+ def update(self, x, F):
534
+ self.x = x
535
+
536
+ def solve(self, v, tol=0):
537
+ m = J(self.x)
538
+ if isinstance(m, np.ndarray):
539
+ return solve(m, v)
540
+ elif scipy.sparse.issparse(m):
541
+ return spsolve(m, v)
542
+ else:
543
+ raise ValueError("Unknown matrix type")
544
+
545
+ def matvec(self, v):
546
+ m = J(self.x)
547
+ if isinstance(m, np.ndarray):
548
+ return dot(m, v)
549
+ elif scipy.sparse.issparse(m):
550
+ return m @ v
551
+ else:
552
+ raise ValueError("Unknown matrix type")
553
+
554
+ def rsolve(self, v, tol=0):
555
+ m = J(self.x)
556
+ if isinstance(m, np.ndarray):
557
+ return solve(m.conj().T, v)
558
+ elif scipy.sparse.issparse(m):
559
+ return spsolve(m.conj().T, v)
560
+ else:
561
+ raise ValueError("Unknown matrix type")
562
+
563
+ def rmatvec(self, v):
564
+ m = J(self.x)
565
+ if isinstance(m, np.ndarray):
566
+ return dot(m.conj().T, v)
567
+ elif scipy.sparse.issparse(m):
568
+ return m.conj().T @ v
569
+ else:
570
+ raise ValueError("Unknown matrix type")
571
+ return Jac()
572
+ elif isinstance(J, str):
573
+ return dict(broyden1=BroydenFirst,
574
+ broyden2=BroydenSecond,
575
+ anderson=Anderson,
576
+ diagbroyden=DiagBroyden,
577
+ linearmixing=LinearMixing,
578
+ excitingmixing=ExcitingMixing,
579
+ krylov=KrylovJacobian)[J]()
580
+ else:
581
+ raise TypeError('Cannot convert object to a Jacobian')
582
+
583
+
584
+ #------------------------------------------------------------------------------
585
+ # Broyden
586
+ #------------------------------------------------------------------------------
587
+
588
+ class GenericBroyden(Jacobian):
589
+ def setup(self, x0, f0, func):
590
+ Jacobian.setup(self, x0, f0, func)
591
+ self.last_f = f0
592
+ self.last_x = x0
593
+
594
+ if hasattr(self, 'alpha') and self.alpha is None:
595
+ # Autoscale the initial Jacobian parameter
596
+ # unless we have already guessed the solution.
597
+ normf0 = norm(f0)
598
+ if normf0:
599
+ self.alpha = 0.5*max(norm(x0), 1) / normf0
600
+ else:
601
+ self.alpha = 1.0
602
+
603
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
604
+ raise NotImplementedError
605
+
606
+ def update(self, x, f):
607
+ df = f - self.last_f
608
+ dx = x - self.last_x
609
+ self._update(x, f, dx, df, norm(dx), norm(df))
610
+ self.last_f = f
611
+ self.last_x = x
612
+
613
+
614
+ class LowRankMatrix:
615
+ r"""
616
+ A matrix represented as
617
+
618
+ .. math:: \alpha I + \sum_{n=0}^{n=M} c_n d_n^\dagger
619
+
620
+ However, if the rank of the matrix reaches the dimension of the vectors,
621
+ full matrix representation will be used thereon.
622
+
623
+ """
624
+
625
+ def __init__(self, alpha, n, dtype):
626
+ self.alpha = alpha
627
+ self.cs = []
628
+ self.ds = []
629
+ self.n = n
630
+ self.dtype = dtype
631
+ self.collapsed = None
632
+
633
+ @staticmethod
634
+ def _matvec(v, alpha, cs, ds):
635
+ axpy, scal, dotc = get_blas_funcs(['axpy', 'scal', 'dotc'],
636
+ cs[:1] + [v])
637
+ w = alpha * v
638
+ for c, d in zip(cs, ds):
639
+ a = dotc(d, v)
640
+ w = axpy(c, w, w.size, a)
641
+ return w
642
+
643
+ @staticmethod
644
+ def _solve(v, alpha, cs, ds):
645
+ """Evaluate w = M^-1 v"""
646
+ if len(cs) == 0:
647
+ return v/alpha
648
+
649
+ # (B + C D^H)^-1 = B^-1 - B^-1 C (I + D^H B^-1 C)^-1 D^H B^-1
650
+
651
+ axpy, dotc = get_blas_funcs(['axpy', 'dotc'], cs[:1] + [v])
652
+
653
+ c0 = cs[0]
654
+ A = alpha * np.identity(len(cs), dtype=c0.dtype)
655
+ for i, d in enumerate(ds):
656
+ for j, c in enumerate(cs):
657
+ A[i,j] += dotc(d, c)
658
+
659
+ q = np.zeros(len(cs), dtype=c0.dtype)
660
+ for j, d in enumerate(ds):
661
+ q[j] = dotc(d, v)
662
+ q /= alpha
663
+ q = solve(A, q)
664
+
665
+ w = v/alpha
666
+ for c, qc in zip(cs, q):
667
+ w = axpy(c, w, w.size, -qc)
668
+
669
+ return w
670
+
671
+ def matvec(self, v):
672
+ """Evaluate w = M v"""
673
+ if self.collapsed is not None:
674
+ return np.dot(self.collapsed, v)
675
+ return LowRankMatrix._matvec(v, self.alpha, self.cs, self.ds)
676
+
677
+ def rmatvec(self, v):
678
+ """Evaluate w = M^H v"""
679
+ if self.collapsed is not None:
680
+ return np.dot(self.collapsed.T.conj(), v)
681
+ return LowRankMatrix._matvec(v, np.conj(self.alpha), self.ds, self.cs)
682
+
683
+ def solve(self, v, tol=0):
684
+ """Evaluate w = M^-1 v"""
685
+ if self.collapsed is not None:
686
+ return solve(self.collapsed, v)
687
+ return LowRankMatrix._solve(v, self.alpha, self.cs, self.ds)
688
+
689
+ def rsolve(self, v, tol=0):
690
+ """Evaluate w = M^-H v"""
691
+ if self.collapsed is not None:
692
+ return solve(self.collapsed.T.conj(), v)
693
+ return LowRankMatrix._solve(v, np.conj(self.alpha), self.ds, self.cs)
694
+
695
+ def append(self, c, d):
696
+ if self.collapsed is not None:
697
+ self.collapsed += c[:,None] * d[None,:].conj()
698
+ return
699
+
700
+ self.cs.append(c)
701
+ self.ds.append(d)
702
+
703
+ if len(self.cs) > c.size:
704
+ self.collapse()
705
+
706
+ def __array__(self, dtype=None, copy=None):
707
+ if dtype is not None:
708
+ warnings.warn("LowRankMatrix is scipy-internal code, `dtype` "
709
+ f"should only be None but was {dtype} (not handled)",
710
+ stacklevel=3)
711
+ if copy is not None:
712
+ warnings.warn("LowRankMatrix is scipy-internal code, `copy` "
713
+ f"should only be None but was {copy} (not handled)",
714
+ stacklevel=3)
715
+ if self.collapsed is not None:
716
+ return self.collapsed
717
+
718
+ Gm = self.alpha*np.identity(self.n, dtype=self.dtype)
719
+ for c, d in zip(self.cs, self.ds):
720
+ Gm += c[:,None]*d[None,:].conj()
721
+ return Gm
722
+
723
+ def collapse(self):
724
+ """Collapse the low-rank matrix to a full-rank one."""
725
+ self.collapsed = np.array(self, copy=copy_if_needed)
726
+ self.cs = None
727
+ self.ds = None
728
+ self.alpha = None
729
+
730
+ def restart_reduce(self, rank):
731
+ """
732
+ Reduce the rank of the matrix by dropping all vectors.
733
+ """
734
+ if self.collapsed is not None:
735
+ return
736
+ assert rank > 0
737
+ if len(self.cs) > rank:
738
+ del self.cs[:]
739
+ del self.ds[:]
740
+
741
+ def simple_reduce(self, rank):
742
+ """
743
+ Reduce the rank of the matrix by dropping oldest vectors.
744
+ """
745
+ if self.collapsed is not None:
746
+ return
747
+ assert rank > 0
748
+ while len(self.cs) > rank:
749
+ del self.cs[0]
750
+ del self.ds[0]
751
+
752
+ def svd_reduce(self, max_rank, to_retain=None):
753
+ """
754
+ Reduce the rank of the matrix by retaining some SVD components.
755
+
756
+ This corresponds to the \"Broyden Rank Reduction Inverse\"
757
+ algorithm described in [1]_.
758
+
759
+ Note that the SVD decomposition can be done by solving only a
760
+ problem whose size is the effective rank of this matrix, which
761
+ is viable even for large problems.
762
+
763
+ Parameters
764
+ ----------
765
+ max_rank : int
766
+ Maximum rank of this matrix after reduction.
767
+ to_retain : int, optional
768
+ Number of SVD components to retain when reduction is done
769
+ (ie. rank > max_rank). Default is ``max_rank - 2``.
770
+
771
+ References
772
+ ----------
773
+ .. [1] B.A. van der Rotten, PhD thesis,
774
+ \"A limited memory Broyden method to solve high-dimensional
775
+ systems of nonlinear equations\". Mathematisch Instituut,
776
+ Universiteit Leiden, The Netherlands (2003).
777
+
778
+ https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf
779
+
780
+ """
781
+ if self.collapsed is not None:
782
+ return
783
+
784
+ p = max_rank
785
+ if to_retain is not None:
786
+ q = to_retain
787
+ else:
788
+ q = p - 2
789
+
790
+ if self.cs:
791
+ p = min(p, len(self.cs[0]))
792
+ q = max(0, min(q, p-1))
793
+
794
+ m = len(self.cs)
795
+ if m < p:
796
+ # nothing to do
797
+ return
798
+
799
+ C = np.array(self.cs).T
800
+ D = np.array(self.ds).T
801
+
802
+ D, R = qr(D, mode='economic')
803
+ C = dot(C, R.T.conj())
804
+
805
+ U, S, WH = svd(C, full_matrices=False)
806
+
807
+ C = dot(C, inv(WH))
808
+ D = dot(D, WH.T.conj())
809
+
810
+ for k in range(q):
811
+ self.cs[k] = C[:,k].copy()
812
+ self.ds[k] = D[:,k].copy()
813
+
814
+ del self.cs[q:]
815
+ del self.ds[q:]
816
+
817
+
818
+ _doc_parts['broyden_params'] = """
819
+ alpha : float, optional
820
+ Initial guess for the Jacobian is ``(-1/alpha)``.
821
+ reduction_method : str or tuple, optional
822
+ Method used in ensuring that the rank of the Broyden matrix
823
+ stays low. Can either be a string giving the name of the method,
824
+ or a tuple of the form ``(method, param1, param2, ...)``
825
+ that gives the name of the method and values for additional parameters.
826
+
827
+ Methods available:
828
+
829
+ - ``restart``: drop all matrix columns. Has no extra parameters.
830
+ - ``simple``: drop oldest matrix column. Has no extra parameters.
831
+ - ``svd``: keep only the most significant SVD components.
832
+ Takes an extra parameter, ``to_retain``, which determines the
833
+ number of SVD components to retain when rank reduction is done.
834
+ Default is ``max_rank - 2``.
835
+
836
+ max_rank : int, optional
837
+ Maximum rank for the Broyden matrix.
838
+ Default is infinity (i.e., no rank reduction).
839
+ """.strip()
840
+
841
+
842
+ class BroydenFirst(GenericBroyden):
843
+ """
844
+ Find a root of a function, using Broyden's first Jacobian approximation.
845
+
846
+ This method is also known as "Broyden's good method".
847
+
848
+ Parameters
849
+ ----------
850
+ %(params_basic)s
851
+ %(broyden_params)s
852
+ %(params_extra)s
853
+
854
+ See Also
855
+ --------
856
+ root : Interface to root finding algorithms for multivariate
857
+ functions. See ``method='broyden1'`` in particular.
858
+
859
+ Notes
860
+ -----
861
+ This algorithm implements the inverse Jacobian Quasi-Newton update
862
+
863
+ .. math:: H_+ = H + (dx - H df) dx^\\dagger H / ( dx^\\dagger H df)
864
+
865
+ which corresponds to Broyden's first Jacobian update
866
+
867
+ .. math:: J_+ = J + (df - J dx) dx^\\dagger / dx^\\dagger dx
868
+
869
+
870
+ References
871
+ ----------
872
+ .. [1] B.A. van der Rotten, PhD thesis,
873
+ "A limited memory Broyden method to solve high-dimensional
874
+ systems of nonlinear equations". Mathematisch Instituut,
875
+ Universiteit Leiden, The Netherlands (2003).
876
+ https://math.leidenuniv.nl/scripties/Rotten.pdf
877
+
878
+ Examples
879
+ --------
880
+ The following functions define a system of nonlinear equations
881
+
882
+ >>> def fun(x):
883
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
884
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
885
+
886
+ A solution can be obtained as follows.
887
+
888
+ >>> from scipy import optimize
889
+ >>> sol = optimize.broyden1(fun, [0, 0])
890
+ >>> sol
891
+ array([0.84116396, 0.15883641])
892
+
893
+ """
894
+
895
+ def __init__(self, alpha=None, reduction_method='restart', max_rank=None):
896
+ GenericBroyden.__init__(self)
897
+ self.alpha = alpha
898
+ self.Gm = None
899
+
900
+ if max_rank is None:
901
+ max_rank = np.inf
902
+ self.max_rank = max_rank
903
+
904
+ if isinstance(reduction_method, str):
905
+ reduce_params = ()
906
+ else:
907
+ reduce_params = reduction_method[1:]
908
+ reduction_method = reduction_method[0]
909
+ reduce_params = (max_rank - 1,) + reduce_params
910
+
911
+ if reduction_method == 'svd':
912
+ self._reduce = lambda: self.Gm.svd_reduce(*reduce_params)
913
+ elif reduction_method == 'simple':
914
+ self._reduce = lambda: self.Gm.simple_reduce(*reduce_params)
915
+ elif reduction_method == 'restart':
916
+ self._reduce = lambda: self.Gm.restart_reduce(*reduce_params)
917
+ else:
918
+ raise ValueError(f"Unknown rank reduction method '{reduction_method}'")
919
+
920
+ def setup(self, x, F, func):
921
+ GenericBroyden.setup(self, x, F, func)
922
+ self.Gm = LowRankMatrix(-self.alpha, self.shape[0], self.dtype)
923
+
924
+ def todense(self):
925
+ return inv(self.Gm)
926
+
927
+ def solve(self, f, tol=0):
928
+ r = self.Gm.matvec(f)
929
+ if not np.isfinite(r).all():
930
+ # singular; reset the Jacobian approximation
931
+ self.setup(self.last_x, self.last_f, self.func)
932
+ return self.Gm.matvec(f)
933
+ return r
934
+
935
+ def matvec(self, f):
936
+ return self.Gm.solve(f)
937
+
938
+ def rsolve(self, f, tol=0):
939
+ return self.Gm.rmatvec(f)
940
+
941
+ def rmatvec(self, f):
942
+ return self.Gm.rsolve(f)
943
+
944
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
945
+ self._reduce() # reduce first to preserve secant condition
946
+
947
+ v = self.Gm.rmatvec(dx)
948
+ c = dx - self.Gm.matvec(df)
949
+ d = v / vdot(df, v)
950
+
951
+ self.Gm.append(c, d)
952
+
953
+
954
+ class BroydenSecond(BroydenFirst):
955
+ """
956
+ Find a root of a function, using Broyden\'s second Jacobian approximation.
957
+
958
+ This method is also known as \"Broyden's bad method\".
959
+
960
+ Parameters
961
+ ----------
962
+ %(params_basic)s
963
+ %(broyden_params)s
964
+ %(params_extra)s
965
+
966
+ See Also
967
+ --------
968
+ root : Interface to root finding algorithms for multivariate
969
+ functions. See ``method='broyden2'`` in particular.
970
+
971
+ Notes
972
+ -----
973
+ This algorithm implements the inverse Jacobian Quasi-Newton update
974
+
975
+ .. math:: H_+ = H + (dx - H df) df^\\dagger / ( df^\\dagger df)
976
+
977
+ corresponding to Broyden's second method.
978
+
979
+ References
980
+ ----------
981
+ .. [1] B.A. van der Rotten, PhD thesis,
982
+ \"A limited memory Broyden method to solve high-dimensional
983
+ systems of nonlinear equations\". Mathematisch Instituut,
984
+ Universiteit Leiden, The Netherlands (2003).
985
+
986
+ https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf
987
+
988
+ Examples
989
+ --------
990
+ The following functions define a system of nonlinear equations
991
+
992
+ >>> def fun(x):
993
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
994
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
995
+
996
+ A solution can be obtained as follows.
997
+
998
+ >>> from scipy import optimize
999
+ >>> sol = optimize.broyden2(fun, [0, 0])
1000
+ >>> sol
1001
+ array([0.84116365, 0.15883529])
1002
+
1003
+ """
1004
+
1005
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
1006
+ self._reduce() # reduce first to preserve secant condition
1007
+
1008
+ v = df
1009
+ c = dx - self.Gm.matvec(df)
1010
+ d = v / df_norm**2
1011
+ self.Gm.append(c, d)
1012
+
1013
+
1014
+ #------------------------------------------------------------------------------
1015
+ # Broyden-like (restricted memory)
1016
+ #------------------------------------------------------------------------------
1017
+
1018
+ class Anderson(GenericBroyden):
1019
+ """
1020
+ Find a root of a function, using (extended) Anderson mixing.
1021
+
1022
+ The Jacobian is formed by for a 'best' solution in the space
1023
+ spanned by last `M` vectors. As a result, only a MxM matrix
1024
+ inversions and MxN multiplications are required. [Ey]_
1025
+
1026
+ Parameters
1027
+ ----------
1028
+ %(params_basic)s
1029
+ alpha : float, optional
1030
+ Initial guess for the Jacobian is (-1/alpha).
1031
+ M : float, optional
1032
+ Number of previous vectors to retain. Defaults to 5.
1033
+ w0 : float, optional
1034
+ Regularization parameter for numerical stability.
1035
+ Compared to unity, good values of the order of 0.01.
1036
+ %(params_extra)s
1037
+
1038
+ See Also
1039
+ --------
1040
+ root : Interface to root finding algorithms for multivariate
1041
+ functions. See ``method='anderson'`` in particular.
1042
+
1043
+ References
1044
+ ----------
1045
+ .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996).
1046
+
1047
+ Examples
1048
+ --------
1049
+ The following functions define a system of nonlinear equations
1050
+
1051
+ >>> def fun(x):
1052
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
1053
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
1054
+
1055
+ A solution can be obtained as follows.
1056
+
1057
+ >>> from scipy import optimize
1058
+ >>> sol = optimize.anderson(fun, [0, 0])
1059
+ >>> sol
1060
+ array([0.84116588, 0.15883789])
1061
+
1062
+ """
1063
+
1064
+ # Note:
1065
+ #
1066
+ # Anderson method maintains a rank M approximation of the inverse Jacobian,
1067
+ #
1068
+ # J^-1 v ~ -v*alpha + (dX + alpha dF) A^-1 dF^H v
1069
+ # A = W + dF^H dF
1070
+ # W = w0^2 diag(dF^H dF)
1071
+ #
1072
+ # so that for w0 = 0 the secant condition applies for last M iterates, i.e.,
1073
+ #
1074
+ # J^-1 df_j = dx_j
1075
+ #
1076
+ # for all j = 0 ... M-1.
1077
+ #
1078
+ # Moreover, (from Sherman-Morrison-Woodbury formula)
1079
+ #
1080
+ # J v ~ [ b I - b^2 C (I + b dF^H A^-1 C)^-1 dF^H ] v
1081
+ # C = (dX + alpha dF) A^-1
1082
+ # b = -1/alpha
1083
+ #
1084
+ # and after simplification
1085
+ #
1086
+ # J v ~ -v/alpha + (dX/alpha + dF) (dF^H dX - alpha W)^-1 dF^H v
1087
+ #
1088
+
1089
+ def __init__(self, alpha=None, w0=0.01, M=5):
1090
+ GenericBroyden.__init__(self)
1091
+ self.alpha = alpha
1092
+ self.M = M
1093
+ self.dx = []
1094
+ self.df = []
1095
+ self.gamma = None
1096
+ self.w0 = w0
1097
+
1098
+ def solve(self, f, tol=0):
1099
+ dx = -self.alpha*f
1100
+
1101
+ n = len(self.dx)
1102
+ if n == 0:
1103
+ return dx
1104
+
1105
+ df_f = np.empty(n, dtype=f.dtype)
1106
+ for k in range(n):
1107
+ df_f[k] = vdot(self.df[k], f)
1108
+
1109
+ try:
1110
+ gamma = solve(self.a, df_f)
1111
+ except LinAlgError:
1112
+ # singular; reset the Jacobian approximation
1113
+ del self.dx[:]
1114
+ del self.df[:]
1115
+ return dx
1116
+
1117
+ for m in range(n):
1118
+ dx += gamma[m]*(self.dx[m] + self.alpha*self.df[m])
1119
+ return dx
1120
+
1121
+ def matvec(self, f):
1122
+ dx = -f/self.alpha
1123
+
1124
+ n = len(self.dx)
1125
+ if n == 0:
1126
+ return dx
1127
+
1128
+ df_f = np.empty(n, dtype=f.dtype)
1129
+ for k in range(n):
1130
+ df_f[k] = vdot(self.df[k], f)
1131
+
1132
+ b = np.empty((n, n), dtype=f.dtype)
1133
+ for i in range(n):
1134
+ for j in range(n):
1135
+ b[i,j] = vdot(self.df[i], self.dx[j])
1136
+ if i == j and self.w0 != 0:
1137
+ b[i,j] -= vdot(self.df[i], self.df[i])*self.w0**2*self.alpha
1138
+ gamma = solve(b, df_f)
1139
+
1140
+ for m in range(n):
1141
+ dx += gamma[m]*(self.df[m] + self.dx[m]/self.alpha)
1142
+ return dx
1143
+
1144
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
1145
+ if self.M == 0:
1146
+ return
1147
+
1148
+ self.dx.append(dx)
1149
+ self.df.append(df)
1150
+
1151
+ while len(self.dx) > self.M:
1152
+ self.dx.pop(0)
1153
+ self.df.pop(0)
1154
+
1155
+ n = len(self.dx)
1156
+ a = np.zeros((n, n), dtype=f.dtype)
1157
+
1158
+ for i in range(n):
1159
+ for j in range(i, n):
1160
+ if i == j:
1161
+ wd = self.w0**2
1162
+ else:
1163
+ wd = 0
1164
+ a[i,j] = (1+wd)*vdot(self.df[i], self.df[j])
1165
+
1166
+ a += np.triu(a, 1).T.conj()
1167
+ self.a = a
1168
+
1169
+ #------------------------------------------------------------------------------
1170
+ # Simple iterations
1171
+ #------------------------------------------------------------------------------
1172
+
1173
+
1174
+ class DiagBroyden(GenericBroyden):
1175
+ """
1176
+ Find a root of a function, using diagonal Broyden Jacobian approximation.
1177
+
1178
+ The Jacobian approximation is derived from previous iterations, by
1179
+ retaining only the diagonal of Broyden matrices.
1180
+
1181
+ .. warning::
1182
+
1183
+ This algorithm may be useful for specific problems, but whether
1184
+ it will work may depend strongly on the problem.
1185
+
1186
+ Parameters
1187
+ ----------
1188
+ %(params_basic)s
1189
+ alpha : float, optional
1190
+ Initial guess for the Jacobian is (-1/alpha).
1191
+ %(params_extra)s
1192
+
1193
+ See Also
1194
+ --------
1195
+ root : Interface to root finding algorithms for multivariate
1196
+ functions. See ``method='diagbroyden'`` in particular.
1197
+
1198
+ Examples
1199
+ --------
1200
+ The following functions define a system of nonlinear equations
1201
+
1202
+ >>> def fun(x):
1203
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
1204
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
1205
+
1206
+ A solution can be obtained as follows.
1207
+
1208
+ >>> from scipy import optimize
1209
+ >>> sol = optimize.diagbroyden(fun, [0, 0])
1210
+ >>> sol
1211
+ array([0.84116403, 0.15883384])
1212
+
1213
+ """
1214
+
1215
+ def __init__(self, alpha=None):
1216
+ GenericBroyden.__init__(self)
1217
+ self.alpha = alpha
1218
+
1219
+ def setup(self, x, F, func):
1220
+ GenericBroyden.setup(self, x, F, func)
1221
+ self.d = np.full((self.shape[0],), 1 / self.alpha, dtype=self.dtype)
1222
+
1223
+ def solve(self, f, tol=0):
1224
+ return -f / self.d
1225
+
1226
+ def matvec(self, f):
1227
+ return -f * self.d
1228
+
1229
+ def rsolve(self, f, tol=0):
1230
+ return -f / self.d.conj()
1231
+
1232
+ def rmatvec(self, f):
1233
+ return -f * self.d.conj()
1234
+
1235
+ def todense(self):
1236
+ return np.diag(-self.d)
1237
+
1238
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
1239
+ self.d -= (df + self.d*dx)*dx/dx_norm**2
1240
+
1241
+
1242
+ class LinearMixing(GenericBroyden):
1243
+ """
1244
+ Find a root of a function, using a scalar Jacobian approximation.
1245
+
1246
+ .. warning::
1247
+
1248
+ This algorithm may be useful for specific problems, but whether
1249
+ it will work may depend strongly on the problem.
1250
+
1251
+ Parameters
1252
+ ----------
1253
+ %(params_basic)s
1254
+ alpha : float, optional
1255
+ The Jacobian approximation is (-1/alpha).
1256
+ %(params_extra)s
1257
+
1258
+ See Also
1259
+ --------
1260
+ root : Interface to root finding algorithms for multivariate
1261
+ functions. See ``method='linearmixing'`` in particular.
1262
+
1263
+ """
1264
+
1265
+ def __init__(self, alpha=None):
1266
+ GenericBroyden.__init__(self)
1267
+ self.alpha = alpha
1268
+
1269
+ def solve(self, f, tol=0):
1270
+ return -f*self.alpha
1271
+
1272
+ def matvec(self, f):
1273
+ return -f/self.alpha
1274
+
1275
+ def rsolve(self, f, tol=0):
1276
+ return -f*np.conj(self.alpha)
1277
+
1278
+ def rmatvec(self, f):
1279
+ return -f/np.conj(self.alpha)
1280
+
1281
+ def todense(self):
1282
+ return np.diag(np.full(self.shape[0], -1/self.alpha))
1283
+
1284
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
1285
+ pass
1286
+
1287
+
1288
+ class ExcitingMixing(GenericBroyden):
1289
+ """
1290
+ Find a root of a function, using a tuned diagonal Jacobian approximation.
1291
+
1292
+ The Jacobian matrix is diagonal and is tuned on each iteration.
1293
+
1294
+ .. warning::
1295
+
1296
+ This algorithm may be useful for specific problems, but whether
1297
+ it will work may depend strongly on the problem.
1298
+
1299
+ See Also
1300
+ --------
1301
+ root : Interface to root finding algorithms for multivariate
1302
+ functions. See ``method='excitingmixing'`` in particular.
1303
+
1304
+ Parameters
1305
+ ----------
1306
+ %(params_basic)s
1307
+ alpha : float, optional
1308
+ Initial Jacobian approximation is (-1/alpha).
1309
+ alphamax : float, optional
1310
+ The entries of the diagonal Jacobian are kept in the range
1311
+ ``[alpha, alphamax]``.
1312
+ %(params_extra)s
1313
+ """
1314
+
1315
+ def __init__(self, alpha=None, alphamax=1.0):
1316
+ GenericBroyden.__init__(self)
1317
+ self.alpha = alpha
1318
+ self.alphamax = alphamax
1319
+ self.beta = None
1320
+
1321
+ def setup(self, x, F, func):
1322
+ GenericBroyden.setup(self, x, F, func)
1323
+ self.beta = np.full((self.shape[0],), self.alpha, dtype=self.dtype)
1324
+
1325
+ def solve(self, f, tol=0):
1326
+ return -f*self.beta
1327
+
1328
+ def matvec(self, f):
1329
+ return -f/self.beta
1330
+
1331
+ def rsolve(self, f, tol=0):
1332
+ return -f*self.beta.conj()
1333
+
1334
+ def rmatvec(self, f):
1335
+ return -f/self.beta.conj()
1336
+
1337
+ def todense(self):
1338
+ return np.diag(-1/self.beta)
1339
+
1340
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
1341
+ incr = f*self.last_f > 0
1342
+ self.beta[incr] += self.alpha
1343
+ self.beta[~incr] = self.alpha
1344
+ np.clip(self.beta, 0, self.alphamax, out=self.beta)
1345
+
1346
+
1347
+ #------------------------------------------------------------------------------
1348
+ # Iterative/Krylov approximated Jacobians
1349
+ #------------------------------------------------------------------------------
1350
+
1351
+ class KrylovJacobian(Jacobian):
1352
+ """
1353
+ Find a root of a function, using Krylov approximation for inverse Jacobian.
1354
+
1355
+ This method is suitable for solving large-scale problems.
1356
+
1357
+ Parameters
1358
+ ----------
1359
+ %(params_basic)s
1360
+ rdiff : float, optional
1361
+ Relative step size to use in numerical differentiation.
1362
+ method : str or callable, optional
1363
+ Krylov method to use to approximate the Jacobian. Can be a string,
1364
+ or a function implementing the same interface as the iterative
1365
+ solvers in `scipy.sparse.linalg`. If a string, needs to be one of:
1366
+ ``'lgmres'``, ``'gmres'``, ``'bicgstab'``, ``'cgs'``, ``'minres'``,
1367
+ ``'tfqmr'``.
1368
+
1369
+ The default is `scipy.sparse.linalg.lgmres`.
1370
+ inner_maxiter : int, optional
1371
+ Parameter to pass to the "inner" Krylov solver: maximum number of
1372
+ iterations. Iteration will stop after maxiter steps even if the
1373
+ specified tolerance has not been achieved.
1374
+ inner_M : LinearOperator or InverseJacobian
1375
+ Preconditioner for the inner Krylov iteration.
1376
+ Note that you can use also inverse Jacobians as (adaptive)
1377
+ preconditioners. For example,
1378
+
1379
+ >>> from scipy.optimize import BroydenFirst, KrylovJacobian
1380
+ >>> from scipy.optimize import InverseJacobian
1381
+ >>> jac = BroydenFirst()
1382
+ >>> kjac = KrylovJacobian(inner_M=InverseJacobian(jac))
1383
+
1384
+ If the preconditioner has a method named 'update', it will be called
1385
+ as ``update(x, f)`` after each nonlinear step, with ``x`` giving
1386
+ the current point, and ``f`` the current function value.
1387
+ outer_k : int, optional
1388
+ Size of the subspace kept across LGMRES nonlinear iterations.
1389
+ See `scipy.sparse.linalg.lgmres` for details.
1390
+ inner_kwargs : kwargs
1391
+ Keyword parameters for the "inner" Krylov solver
1392
+ (defined with `method`). Parameter names must start with
1393
+ the `inner_` prefix which will be stripped before passing on
1394
+ the inner method. See, e.g., `scipy.sparse.linalg.gmres` for details.
1395
+ %(params_extra)s
1396
+
1397
+ See Also
1398
+ --------
1399
+ root : Interface to root finding algorithms for multivariate
1400
+ functions. See ``method='krylov'`` in particular.
1401
+ scipy.sparse.linalg.gmres
1402
+ scipy.sparse.linalg.lgmres
1403
+
1404
+ Notes
1405
+ -----
1406
+ This function implements a Newton-Krylov solver. The basic idea is
1407
+ to compute the inverse of the Jacobian with an iterative Krylov
1408
+ method. These methods require only evaluating the Jacobian-vector
1409
+ products, which are conveniently approximated by a finite difference:
1410
+
1411
+ .. math:: J v \\approx (f(x + \\omega*v/|v|) - f(x)) / \\omega
1412
+
1413
+ Due to the use of iterative matrix inverses, these methods can
1414
+ deal with large nonlinear problems.
1415
+
1416
+ SciPy's `scipy.sparse.linalg` module offers a selection of Krylov
1417
+ solvers to choose from. The default here is `lgmres`, which is a
1418
+ variant of restarted GMRES iteration that reuses some of the
1419
+ information obtained in the previous Newton steps to invert
1420
+ Jacobians in subsequent steps.
1421
+
1422
+ For a review on Newton-Krylov methods, see for example [1]_,
1423
+ and for the LGMRES sparse inverse method, see [2]_.
1424
+
1425
+ References
1426
+ ----------
1427
+ .. [1] C. T. Kelley, Solving Nonlinear Equations with Newton's Method,
1428
+ SIAM, pp.57-83, 2003.
1429
+ :doi:`10.1137/1.9780898718898.ch3`
1430
+ .. [2] D.A. Knoll and D.E. Keyes, J. Comp. Phys. 193, 357 (2004).
1431
+ :doi:`10.1016/j.jcp.2003.08.010`
1432
+ .. [3] A.H. Baker and E.R. Jessup and T. Manteuffel,
1433
+ SIAM J. Matrix Anal. Appl. 26, 962 (2005).
1434
+ :doi:`10.1137/S0895479803422014`
1435
+
1436
+ Examples
1437
+ --------
1438
+ The following functions define a system of nonlinear equations
1439
+
1440
+ >>> def fun(x):
1441
+ ... return [x[0] + 0.5 * x[1] - 1.0,
1442
+ ... 0.5 * (x[1] - x[0]) ** 2]
1443
+
1444
+ A solution can be obtained as follows.
1445
+
1446
+ >>> from scipy import optimize
1447
+ >>> sol = optimize.newton_krylov(fun, [0, 0])
1448
+ >>> sol
1449
+ array([0.66731771, 0.66536458])
1450
+
1451
+ """
1452
+
1453
+ def __init__(self, rdiff=None, method='lgmres', inner_maxiter=20,
1454
+ inner_M=None, outer_k=10, **kw):
1455
+ self.preconditioner = inner_M
1456
+ self.rdiff = rdiff
1457
+ # Note that this retrieves one of the named functions, or otherwise
1458
+ # uses `method` as is (i.e., for a user-provided callable).
1459
+ self.method = dict(
1460
+ bicgstab=scipy.sparse.linalg.bicgstab,
1461
+ gmres=scipy.sparse.linalg.gmres,
1462
+ lgmres=scipy.sparse.linalg.lgmres,
1463
+ cgs=scipy.sparse.linalg.cgs,
1464
+ minres=scipy.sparse.linalg.minres,
1465
+ tfqmr=scipy.sparse.linalg.tfqmr,
1466
+ ).get(method, method)
1467
+
1468
+ self.method_kw = dict(maxiter=inner_maxiter, M=self.preconditioner)
1469
+
1470
+ if self.method is scipy.sparse.linalg.gmres:
1471
+ # Replace GMRES's outer iteration with Newton steps
1472
+ self.method_kw['restart'] = inner_maxiter
1473
+ self.method_kw['maxiter'] = 1
1474
+ self.method_kw.setdefault('atol', 0)
1475
+ elif self.method in (scipy.sparse.linalg.gcrotmk,
1476
+ scipy.sparse.linalg.bicgstab,
1477
+ scipy.sparse.linalg.cgs):
1478
+ self.method_kw.setdefault('atol', 0)
1479
+ elif self.method is scipy.sparse.linalg.lgmres:
1480
+ self.method_kw['outer_k'] = outer_k
1481
+ # Replace LGMRES's outer iteration with Newton steps
1482
+ self.method_kw['maxiter'] = 1
1483
+ # Carry LGMRES's `outer_v` vectors across nonlinear iterations
1484
+ self.method_kw.setdefault('outer_v', [])
1485
+ self.method_kw.setdefault('prepend_outer_v', True)
1486
+ # But don't carry the corresponding Jacobian*v products, in case
1487
+ # the Jacobian changes a lot in the nonlinear step
1488
+ #
1489
+ # XXX: some trust-region inspired ideas might be more efficient...
1490
+ # See e.g., Brown & Saad. But needs to be implemented separately
1491
+ # since it's not an inexact Newton method.
1492
+ self.method_kw.setdefault('store_outer_Av', False)
1493
+ self.method_kw.setdefault('atol', 0)
1494
+
1495
+ for key, value in kw.items():
1496
+ if not key.startswith('inner_'):
1497
+ raise ValueError(f"Unknown parameter {key}")
1498
+ self.method_kw[key[6:]] = value
1499
+
1500
+ def _update_diff_step(self):
1501
+ mx = abs(self.x0).max()
1502
+ mf = abs(self.f0).max()
1503
+ self.omega = self.rdiff * max(1, mx) / max(1, mf)
1504
+
1505
+ def matvec(self, v):
1506
+ nv = norm(v)
1507
+ if nv == 0:
1508
+ return 0*v
1509
+ sc = self.omega / nv
1510
+ r = (self.func(self.x0 + sc*v) - self.f0) / sc
1511
+ if not np.all(np.isfinite(r)) and np.all(np.isfinite(v)):
1512
+ raise ValueError('Function returned non-finite results')
1513
+ return r
1514
+
1515
+ def solve(self, rhs, tol=0):
1516
+ if 'rtol' in self.method_kw:
1517
+ sol, info = self.method(self.op, rhs, **self.method_kw)
1518
+ else:
1519
+ sol, info = self.method(self.op, rhs, rtol=tol, **self.method_kw)
1520
+ return sol
1521
+
1522
+ def update(self, x, f):
1523
+ self.x0 = x
1524
+ self.f0 = f
1525
+ self._update_diff_step()
1526
+
1527
+ # Update also the preconditioner, if possible
1528
+ if self.preconditioner is not None:
1529
+ if hasattr(self.preconditioner, 'update'):
1530
+ self.preconditioner.update(x, f)
1531
+
1532
+ def setup(self, x, f, func):
1533
+ Jacobian.setup(self, x, f, func)
1534
+ self.x0 = x
1535
+ self.f0 = f
1536
+ self.op = scipy.sparse.linalg.aslinearoperator(self)
1537
+
1538
+ if self.rdiff is None:
1539
+ self.rdiff = np.finfo(x.dtype).eps ** (1./2)
1540
+
1541
+ self._update_diff_step()
1542
+
1543
+ # Setup also the preconditioner, if possible
1544
+ if self.preconditioner is not None:
1545
+ if hasattr(self.preconditioner, 'setup'):
1546
+ self.preconditioner.setup(x, f, func)
1547
+
1548
+
1549
+ #------------------------------------------------------------------------------
1550
+ # Wrapper functions
1551
+ #------------------------------------------------------------------------------
1552
+
1553
+ def _nonlin_wrapper(name, jac):
1554
+ """
1555
+ Construct a solver wrapper with given name and Jacobian approx.
1556
+
1557
+ It inspects the keyword arguments of ``jac.__init__``, and allows to
1558
+ use the same arguments in the wrapper function, in addition to the
1559
+ keyword arguments of `nonlin_solve`
1560
+
1561
+ """
1562
+ signature = _getfullargspec(jac.__init__)
1563
+ args, varargs, varkw, defaults, kwonlyargs, kwdefaults, _ = signature
1564
+ kwargs = list(zip(args[-len(defaults):], defaults))
1565
+ kw_str = ", ".join([f"{k}={v!r}" for k, v in kwargs])
1566
+ if kw_str:
1567
+ kw_str = ", " + kw_str
1568
+ kwkw_str = ", ".join([f"{k}={k}" for k, v in kwargs])
1569
+ if kwkw_str:
1570
+ kwkw_str = kwkw_str + ", "
1571
+ if kwonlyargs:
1572
+ raise ValueError(f'Unexpected signature {signature}')
1573
+
1574
+ # Construct the wrapper function so that its keyword arguments
1575
+ # are visible in pydoc.help etc.
1576
+ wrapper = """
1577
+ def %(name)s(F, xin, iter=None %(kw)s, verbose=False, maxiter=None,
1578
+ f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
1579
+ tol_norm=None, line_search='armijo', callback=None, **kw):
1580
+ jac = %(jac)s(%(kwkw)s **kw)
1581
+ return nonlin_solve(F, xin, jac, iter, verbose, maxiter,
1582
+ f_tol, f_rtol, x_tol, x_rtol, tol_norm, line_search,
1583
+ callback)
1584
+ """
1585
+
1586
+ wrapper = wrapper % dict(name=name, kw=kw_str, jac=jac.__name__,
1587
+ kwkw=kwkw_str)
1588
+ ns = {}
1589
+ ns.update(globals())
1590
+ exec(wrapper, ns)
1591
+ func = ns[name]
1592
+ func.__doc__ = jac.__doc__
1593
+ _set_doc(func)
1594
+ return func
1595
+
1596
+
1597
+ broyden1 = _nonlin_wrapper('broyden1', BroydenFirst)
1598
+ broyden2 = _nonlin_wrapper('broyden2', BroydenSecond)
1599
+ anderson = _nonlin_wrapper('anderson', Anderson)
1600
+ linearmixing = _nonlin_wrapper('linearmixing', LinearMixing)
1601
+ diagbroyden = _nonlin_wrapper('diagbroyden', DiagBroyden)
1602
+ excitingmixing = _nonlin_wrapper('excitingmixing', ExcitingMixing)
1603
+ newton_krylov = _nonlin_wrapper('newton_krylov', KrylovJacobian)
shared/package-files/06/06d3b49e34f00c5ad736bde730aabfa7c3c384fcc7f517f30ab9cb909c73e5fc/blob ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ test_indexing tests the following Index methods:
3
+ __getitem__
4
+ get_loc
5
+ get_value
6
+ __contains__
7
+ take
8
+ where
9
+ get_indexer
10
+ get_indexer_for
11
+ slice_locs
12
+ asof_locs
13
+
14
+ The corresponding tests.indexes.[index_type].test_indexing files
15
+ contain tests for the corresponding methods specific to those Index subclasses.
16
+ """
17
+ import numpy as np
18
+ import pytest
19
+
20
+ from pandas.compat import PY314
21
+ from pandas.errors import InvalidIndexError
22
+
23
+ from pandas.core.dtypes.common import (
24
+ is_float_dtype,
25
+ is_scalar,
26
+ )
27
+
28
+ from pandas import (
29
+ NA,
30
+ DatetimeIndex,
31
+ Index,
32
+ IntervalIndex,
33
+ MultiIndex,
34
+ NaT,
35
+ PeriodIndex,
36
+ TimedeltaIndex,
37
+ )
38
+ import pandas._testing as tm
39
+
40
+
41
+ class TestTake:
42
+ def test_take_invalid_kwargs(self, index):
43
+ indices = [1, 2]
44
+
45
+ msg = r"take\(\) got an unexpected keyword argument 'foo'"
46
+ with pytest.raises(TypeError, match=msg):
47
+ index.take(indices, foo=2)
48
+
49
+ msg = "the 'out' parameter is not supported"
50
+ with pytest.raises(ValueError, match=msg):
51
+ index.take(indices, out=indices)
52
+
53
+ msg = "the 'mode' parameter is not supported"
54
+ with pytest.raises(ValueError, match=msg):
55
+ index.take(indices, mode="clip")
56
+
57
+ def test_take(self, index):
58
+ indexer = [4, 3, 0, 2]
59
+ if len(index) < 5:
60
+ pytest.skip("Test doesn't make sense since not enough elements")
61
+
62
+ result = index.take(indexer)
63
+ expected = index[indexer]
64
+ assert result.equals(expected)
65
+
66
+ if not isinstance(index, (DatetimeIndex, PeriodIndex, TimedeltaIndex)):
67
+ # GH 10791
68
+ msg = r"'(.*Index)' object has no attribute 'freq'"
69
+ with pytest.raises(AttributeError, match=msg):
70
+ index.freq
71
+
72
+ def test_take_indexer_type(self):
73
+ # GH#42875
74
+ integer_index = Index([0, 1, 2, 3])
75
+ scalar_index = 1
76
+ msg = "Expected indices to be array-like"
77
+ with pytest.raises(TypeError, match=msg):
78
+ integer_index.take(scalar_index)
79
+
80
+ def test_take_minus1_without_fill(self, index):
81
+ # -1 does not get treated as NA unless allow_fill=True is passed
82
+ if len(index) == 0:
83
+ # Test is not applicable
84
+ pytest.skip("Test doesn't make sense for empty index")
85
+
86
+ result = index.take([0, 0, -1])
87
+
88
+ expected = index.take([0, 0, len(index) - 1])
89
+ tm.assert_index_equal(result, expected)
90
+
91
+
92
+ class TestContains:
93
+ @pytest.mark.parametrize(
94
+ "index,val",
95
+ [
96
+ (Index([0, 1, 2]), 2),
97
+ (Index([0, 1, "2"]), "2"),
98
+ (Index([0, 1, 2, np.inf, 4]), 4),
99
+ (Index([0, 1, 2, np.nan, 4]), 4),
100
+ (Index([0, 1, 2, np.inf]), np.inf),
101
+ (Index([0, 1, 2, np.nan]), np.nan),
102
+ ],
103
+ )
104
+ def test_index_contains(self, index, val):
105
+ assert val in index
106
+
107
+ @pytest.mark.parametrize(
108
+ "index,val",
109
+ [
110
+ (Index([0, 1, 2]), "2"),
111
+ (Index([0, 1, "2"]), 2),
112
+ (Index([0, 1, 2, np.inf]), 4),
113
+ (Index([0, 1, 2, np.nan]), 4),
114
+ (Index([0, 1, 2, np.inf]), np.nan),
115
+ (Index([0, 1, 2, np.nan]), np.inf),
116
+ # Checking if np.inf in int64 Index should not cause an OverflowError
117
+ # Related to GH 16957
118
+ (Index([0, 1, 2], dtype=np.int64), np.inf),
119
+ (Index([0, 1, 2], dtype=np.int64), np.nan),
120
+ (Index([0, 1, 2], dtype=np.uint64), np.inf),
121
+ (Index([0, 1, 2], dtype=np.uint64), np.nan),
122
+ ],
123
+ )
124
+ def test_index_not_contains(self, index, val):
125
+ assert val not in index
126
+
127
+ @pytest.mark.parametrize(
128
+ "index,val", [(Index([0, 1, "2"]), 0), (Index([0, 1, "2"]), "2")]
129
+ )
130
+ def test_mixed_index_contains(self, index, val):
131
+ # GH#19860
132
+ assert val in index
133
+
134
+ @pytest.mark.parametrize(
135
+ "index,val", [(Index([0, 1, "2"]), "1"), (Index([0, 1, "2"]), 2)]
136
+ )
137
+ def test_mixed_index_not_contains(self, index, val):
138
+ # GH#19860
139
+ assert val not in index
140
+
141
+ def test_contains_with_float_index(self, any_real_numpy_dtype):
142
+ # GH#22085
143
+ dtype = any_real_numpy_dtype
144
+ data = [0, 1, 2, 3] if not is_float_dtype(dtype) else [0.1, 1.1, 2.2, 3.3]
145
+ index = Index(data, dtype=dtype)
146
+
147
+ if not is_float_dtype(index.dtype):
148
+ assert 1.1 not in index
149
+ assert 1.0 in index
150
+ assert 1 in index
151
+ else:
152
+ assert 1.1 in index
153
+ assert 1.0 not in index
154
+ assert 1 not in index
155
+
156
+ def test_contains_requires_hashable_raises(self, index):
157
+ if isinstance(index, MultiIndex):
158
+ return # TODO: do we want this to raise?
159
+
160
+ msg = "unhashable type: 'list'"
161
+ with pytest.raises(TypeError, match=msg):
162
+ [] in index
163
+
164
+ if PY314:
165
+ container_or_iterable = "a container or iterable"
166
+ else:
167
+ container_or_iterable = "iterable"
168
+
169
+ msg = "|".join(
170
+ [
171
+ r"unhashable type: 'dict'",
172
+ r"must be real number, not dict",
173
+ r"an integer is required",
174
+ r"\{\}",
175
+ r"pandas\._libs\.interval\.IntervalTree' is not "
176
+ f"{container_or_iterable}",
177
+ ]
178
+ )
179
+ with pytest.raises(TypeError, match=msg):
180
+ {} in index._engine
181
+
182
+
183
+ class TestGetLoc:
184
+ def test_get_loc_non_hashable(self, index):
185
+ with pytest.raises(InvalidIndexError, match="[0, 1]"):
186
+ index.get_loc([0, 1])
187
+
188
+ def test_get_loc_non_scalar_hashable(self, index):
189
+ # GH52877
190
+ from enum import Enum
191
+
192
+ class E(Enum):
193
+ X1 = "x1"
194
+
195
+ assert not is_scalar(E.X1)
196
+
197
+ exc = KeyError
198
+ msg = "<E.X1: 'x1'>"
199
+ if isinstance(
200
+ index,
201
+ (
202
+ DatetimeIndex,
203
+ TimedeltaIndex,
204
+ PeriodIndex,
205
+ IntervalIndex,
206
+ ),
207
+ ):
208
+ # TODO: make these more consistent?
209
+ exc = InvalidIndexError
210
+ msg = "E.X1"
211
+ with pytest.raises(exc, match=msg):
212
+ index.get_loc(E.X1)
213
+
214
+ def test_get_loc_generator(self, index):
215
+ exc = KeyError
216
+ if isinstance(
217
+ index,
218
+ (
219
+ DatetimeIndex,
220
+ TimedeltaIndex,
221
+ PeriodIndex,
222
+ IntervalIndex,
223
+ MultiIndex,
224
+ ),
225
+ ):
226
+ # TODO: make these more consistent?
227
+ exc = InvalidIndexError
228
+ with pytest.raises(exc, match="generator object"):
229
+ # MultiIndex specifically checks for generator; others for scalar
230
+ index.get_loc(x for x in range(5))
231
+
232
+ def test_get_loc_masked_duplicated_na(self):
233
+ # GH#48411
234
+ idx = Index([1, 2, NA, NA], dtype="Int64")
235
+ result = idx.get_loc(NA)
236
+ expected = np.array([False, False, True, True])
237
+ tm.assert_numpy_array_equal(result, expected)
238
+
239
+
240
+ class TestGetIndexer:
241
+ def test_get_indexer_base(self, index):
242
+ if index._index_as_unique:
243
+ expected = np.arange(index.size, dtype=np.intp)
244
+ actual = index.get_indexer(index)
245
+ tm.assert_numpy_array_equal(expected, actual)
246
+ else:
247
+ msg = "Reindexing only valid with uniquely valued Index objects"
248
+ with pytest.raises(InvalidIndexError, match=msg):
249
+ index.get_indexer(index)
250
+
251
+ with pytest.raises(ValueError, match="Invalid fill method"):
252
+ index.get_indexer(index, method="invalid")
253
+
254
+ def test_get_indexer_consistency(self, index):
255
+ # See GH#16819
256
+
257
+ if index._index_as_unique:
258
+ indexer = index.get_indexer(index[0:2])
259
+ assert isinstance(indexer, np.ndarray)
260
+ assert indexer.dtype == np.intp
261
+ else:
262
+ msg = "Reindexing only valid with uniquely valued Index objects"
263
+ with pytest.raises(InvalidIndexError, match=msg):
264
+ index.get_indexer(index[0:2])
265
+
266
+ indexer, _ = index.get_indexer_non_unique(index[0:2])
267
+ assert isinstance(indexer, np.ndarray)
268
+ assert indexer.dtype == np.intp
269
+
270
+ def test_get_indexer_masked_duplicated_na(self):
271
+ # GH#48411
272
+ idx = Index([1, 2, NA, NA], dtype="Int64")
273
+ result = idx.get_indexer_for(Index([1, NA], dtype="Int64"))
274
+ expected = np.array([0, 2, 3], dtype=result.dtype)
275
+ tm.assert_numpy_array_equal(result, expected)
276
+
277
+
278
+ class TestConvertSliceIndexer:
279
+ def test_convert_almost_null_slice(self, index):
280
+ # slice with None at both ends, but not step
281
+
282
+ key = slice(None, None, "foo")
283
+
284
+ if isinstance(index, IntervalIndex):
285
+ msg = "label-based slicing with step!=1 is not supported for IntervalIndex"
286
+ with pytest.raises(ValueError, match=msg):
287
+ index._convert_slice_indexer(key, "loc")
288
+ else:
289
+ msg = "'>=' not supported between instances of 'str' and 'int'"
290
+ with pytest.raises(TypeError, match=msg):
291
+ index._convert_slice_indexer(key, "loc")
292
+
293
+
294
+ class TestPutmask:
295
+ def test_putmask_with_wrong_mask(self, index):
296
+ # GH#18368
297
+ if not len(index):
298
+ pytest.skip("Test doesn't make sense for empty index")
299
+
300
+ fill = index[0]
301
+
302
+ msg = "putmask: mask and data must be the same size"
303
+ with pytest.raises(ValueError, match=msg):
304
+ index.putmask(np.ones(len(index) + 1, np.bool_), fill)
305
+
306
+ with pytest.raises(ValueError, match=msg):
307
+ index.putmask(np.ones(len(index) - 1, np.bool_), fill)
308
+
309
+ with pytest.raises(ValueError, match=msg):
310
+ index.putmask("foo", fill)
311
+
312
+
313
+ @pytest.mark.parametrize(
314
+ "idx", [Index([1, 2, 3]), Index([0.1, 0.2, 0.3]), Index(["a", "b", "c"])]
315
+ )
316
+ def test_getitem_deprecated_float(idx):
317
+ # https://github.com/pandas-dev/pandas/issues/34191
318
+
319
+ msg = "Indexing with a float is no longer supported"
320
+ with pytest.raises(IndexError, match=msg):
321
+ idx[1.0]
322
+
323
+
324
+ @pytest.mark.parametrize(
325
+ "idx,target,expected",
326
+ [
327
+ ([np.nan, "var1", np.nan], [np.nan], np.array([0, 2], dtype=np.intp)),
328
+ (
329
+ [np.nan, "var1", np.nan],
330
+ [np.nan, "var1"],
331
+ np.array([0, 2, 1], dtype=np.intp),
332
+ ),
333
+ (
334
+ np.array([np.nan, "var1", np.nan], dtype=object),
335
+ [np.nan],
336
+ np.array([0, 2], dtype=np.intp),
337
+ ),
338
+ (
339
+ DatetimeIndex(["2020-08-05", NaT, NaT]),
340
+ [NaT],
341
+ np.array([1, 2], dtype=np.intp),
342
+ ),
343
+ (["a", "b", "a", np.nan], [np.nan], np.array([3], dtype=np.intp)),
344
+ (
345
+ np.array(["b", np.nan, float("NaN"), "b"], dtype=object),
346
+ Index([np.nan], dtype=object),
347
+ np.array([1, 2], dtype=np.intp),
348
+ ),
349
+ ],
350
+ )
351
+ def test_get_indexer_non_unique_multiple_nans(idx, target, expected):
352
+ # GH 35392
353
+ axis = Index(idx)
354
+ actual = axis.get_indexer_for(target)
355
+ tm.assert_numpy_array_equal(actual, expected)
356
+
357
+
358
+ def test_get_indexer_non_unique_nans_in_object_dtype_target(nulls_fixture):
359
+ idx = Index([1.0, 2.0])
360
+ target = Index([1, nulls_fixture], dtype="object")
361
+
362
+ result_idx, result_missing = idx.get_indexer_non_unique(target)
363
+ tm.assert_numpy_array_equal(result_idx, np.array([0, -1], dtype=np.intp))
364
+ tm.assert_numpy_array_equal(result_missing, np.array([1], dtype=np.intp))
shared/package-files/06/06d495c7e6c9b6c8ada94a07c3e31a624c551d6fad4e2051f9728d29aeb1bb1c/score_glacier_predictions_serial.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import nullcontext
2
+ #!/usr/bin/env python3
3
+ """Score upstream GLACIER PredSpecDB output under the benchmark contract."""
4
+
5
+ import argparse
6
+ from collections import Counter
7
+ from functools import lru_cache
8
+ import json
9
+ import math
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+ from mass_tolerant_entropy import observed_peaks, tolerant_entropy, precursor_removed_entropy, adduct_conditioned_entropy
14
+ from rdkit import Chem
15
+
16
+ from glacier_contract import condition_key
17
+ import ms_pred.common as common
18
+ from ms_pred.common import chem_utils
19
+ from ms_pred.retrieval.retrieval_benchmark import _cosine_sparse, _entropy_sparse
20
+
21
+
22
+ def read_jsonl(path: Path):
23
+ with path.open(encoding="utf-8") as stream:
24
+ for line_number, line in enumerate(stream, 1):
25
+ try:
26
+ value = json.loads(line)
27
+ except json.JSONDecodeError as error:
28
+ raise ValueError(f"invalid JSON at {path}:{line_number}: {error}") from error
29
+ if not isinstance(value, dict):
30
+ raise ValueError(f"expected object at {path}:{line_number}")
31
+ yield value
32
+
33
+
34
+ def load_pools(path: Path) -> dict:
35
+ pools = {}
36
+ for row in read_jsonl(path):
37
+ pool_id = row["candidate_pool_id"]
38
+ if pool_id in pools:
39
+ raise ValueError(f"duplicate candidate pool {pool_id}")
40
+ pools[pool_id] = row["candidates"]
41
+ return pools
42
+
43
+
44
+ @lru_cache(maxsize=262144)
45
+ def prediction_key_and_support(smiles: str) -> tuple[str, str]:
46
+ """Mirror GLACIER's public inference-domain structure checks."""
47
+ try:
48
+ molecule = Chem.MolFromSmiles(smiles)
49
+ if molecule is None:
50
+ return "", "rdkit_invalid"
51
+ if any(atom.GetAtomicNum() == 0 for atom in molecule.GetAtoms()):
52
+ return "", "wildcard_atom"
53
+ if any(
54
+ atom.GetAtomicNum() not in chem_utils.VALID_ATOM_NUM
55
+ for atom in molecule.GetAtoms()
56
+ ):
57
+ return Chem.MolToInchiKey(molecule), "unsupported_atom"
58
+ molecule = Chem.RemoveHs(molecule)
59
+ if molecule.GetNumAtoms() > 100:
60
+ return Chem.MolToInchiKey(molecule), "more_than_100_heavy_atoms"
61
+ return Chem.MolToInchiKey(molecule), "supported"
62
+ except Exception:
63
+ return "", "structure_exception"
64
+
65
+
66
+ def sparse_observed(
67
+ query: dict,
68
+ num_bins: int,
69
+ upper_limit: int,
70
+ max_peaks: int,
71
+ intensity_threshold: float,
72
+ ):
73
+ mzs = np.asarray(query["mzs"], dtype=np.float32)
74
+ intensities = np.asarray(query["intensities"], dtype=np.float32)
75
+ keep = (mzs <= float(query["precursor_mz"]) + 1) & (intensities > 0)
76
+ mzs = mzs[keep]
77
+ intensities = intensities[keep]
78
+ if intensities.size == 0:
79
+ raise ValueError(f"query {query['query_id']} has no usable intensity")
80
+ maximum = float(intensities.max())
81
+ if maximum <= 0:
82
+ raise ValueError(f"query {query['query_id']} has no positive intensity")
83
+ # This reproduces process_spec_file() followed by max_inten_spec() in the
84
+ # official no_subform MassSpecGym preprocessing: max-normalize, square
85
+ # root, retain the strongest 50 peaks, then apply the 0.001 threshold.
86
+ intensities = np.sqrt(intensities / maximum)
87
+ strongest = np.argsort(intensities)[::-1][:max_peaks]
88
+ mzs = mzs[strongest]
89
+ intensities = intensities[strongest]
90
+ above_threshold = intensities > intensity_threshold
91
+ peaks = np.column_stack([mzs[above_threshold], intensities[above_threshold]])
92
+ dense = common.bin_spectra([peaks], num_bins=num_bins, upper_limit=upper_limit)[0]
93
+ indices = np.flatnonzero(dense > 0).astype(np.uint32)
94
+ return indices, dense[indices].astype(np.float32, copy=False)
95
+
96
+
97
+ def main() -> None:
98
+ parser = argparse.ArgumentParser()
99
+ parser.add_argument("--input-root", type=Path, required=True)
100
+ parser.add_argument(
101
+ "--pred-file",
102
+ type=Path,
103
+ required=True,
104
+ nargs="+",
105
+ help="One or more GLACIER PredSpecDB shards.",
106
+ )
107
+ parser.add_argument("--output-root", type=Path, required=True)
108
+ parser.add_argument("--distance", choices=("entropy", "cos", "mass_tolerant_entropy"), default="entropy")
109
+ parser.add_argument(
110
+ "--tie-break",
111
+ choices=("candidate_id", "input_order"),
112
+ default="candidate_id",
113
+ help=(
114
+ "Use content-derived IDs for the benchmark. input_order exists only "
115
+ "to audit answer-keyed upstream candidate tables."
116
+ ),
117
+ )
118
+ parser.add_argument("--num-bins", type=int, default=150000)
119
+ parser.add_argument("--upper-limit", type=int, default=1500)
120
+ parser.add_argument("--max-observed-peaks", type=int, default=50)
121
+ parser.add_argument("--observed-intensity-threshold", type=float, default=0.001)
122
+ parser.add_argument("--max-queries", type=int)
123
+ parser.add_argument(
124
+ "--query-id-file",
125
+ type=Path,
126
+ help="Optional newline-delimited allowlist for query-disjoint scoring shards.",
127
+ )
128
+ parser.add_argument(
129
+ "--exclude-ranking",
130
+ type=Path,
131
+ action="append",
132
+ default=[],
133
+ help=(
134
+ "Skip query IDs already present in a partial ranking file. This is "
135
+ "an answer-free recovery option; merge the disjoint outputs with "
136
+ "merge_partial_rankings.py."
137
+ ),
138
+ )
139
+ parser.add_argument("--scores-output", type=Path)
140
+ args = parser.parse_args()
141
+
142
+ input_root = args.input_root.resolve()
143
+ output_root = args.output_root.resolve()
144
+ if output_root.exists():
145
+ raise FileExistsError(f"refusing to overwrite {output_root}")
146
+ output_root.mkdir(parents=True)
147
+ pools = load_pools(input_root / "candidate_pools.jsonl")
148
+ pool_prediction_keys = {}
149
+ predictions = [
150
+ common.PredSpecDB(h5_path=path.resolve(), mode="r")
151
+ for path in args.pred_file
152
+ ]
153
+ selected_queries = None
154
+ if args.query_id_file is not None:
155
+ selected_queries = {
156
+ line.strip()
157
+ for line in args.query_id_file.read_text(encoding="utf-8").splitlines()
158
+ if line.strip()
159
+ }
160
+ if not selected_queries:
161
+ raise ValueError("query ID allowlist is empty")
162
+ excluded_queries = {
163
+ row["query_id"]
164
+ for ranking_path in args.exclude_ranking
165
+ for row in read_jsonl(ranking_path.resolve())
166
+ }
167
+
168
+ ranked_queries = 0
169
+ candidate_rows = 0
170
+ missing_predictions = 0
171
+ missing_supported_predictions = 0
172
+ unsupported_missing = Counter()
173
+ with (output_root / "rankings.jsonl").open("w", encoding="utf-8") as stream, (args.scores_output.open("w") if args.scores_output else nullcontext(None)) as score_stream:
174
+ for query in read_jsonl(input_root / "queries.jsonl"):
175
+ if (
176
+ selected_queries is not None
177
+ and query["query_id"] not in selected_queries
178
+ ):
179
+ continue
180
+ if args.max_queries is not None and ranked_queries >= args.max_queries:
181
+ break
182
+ if query["query_id"] in excluded_queries:
183
+ continue
184
+ collision_energy = query.get("collision_energy")
185
+ if collision_energy is None:collision_energy='nan'
186
+ pred_name = 'pred_'+condition_key(query)
187
+ shard_specs = []
188
+ for prediction_db in predictions:
189
+ spec_dict, present = prediction_db.read_from_name(pred_name)
190
+ if present:
191
+ shard_specs.append(spec_dict)
192
+ if not shard_specs:
193
+ continue
194
+ by_ikey = {}
195
+ raw_by_ikey = {}
196
+ for spec_dict in shard_specs:
197
+ for remark, ce_dict in spec_dict.items():
198
+ normalized = str(remark).removeprefix("ikey ").strip()
199
+ normalized_specs = by_ikey.setdefault(normalized, {})
200
+ if args.distance == "mass_tolerant_entropy":
201
+ raw_by_ikey.setdefault(normalized, {}).update({
202
+ common.get_collision_energy(ce): spectrum.spec
203
+ for ce, spectrum in ce_dict.items()
204
+ })
205
+ if args.distance != "mass_tolerant_entropy":
206
+ normalized_specs.update({
207
+ common.get_collision_energy(ce): spectrum.binned_spec_sparse
208
+ if spectrum.has_matching_binned_spec(
209
+ mass_upper_limit=args.upper_limit,
210
+ num_bins=args.num_bins,
211
+ pool_fn="add",
212
+ )
213
+ else (
214
+ spectrum.ensure_binned_spectrum(
215
+ mass_upper_limit=args.upper_limit,
216
+ num_bins=args.num_bins,
217
+ pool_fn="add",
218
+ )
219
+ or spectrum.binned_spec_sparse
220
+ )
221
+ for ce, spectrum in ce_dict.items()
222
+ })
223
+
224
+ pool_id = query["candidate_pool_id"]
225
+ candidates = pools[pool_id]
226
+ candidate_keys = pool_prediction_keys.get(pool_id)
227
+ if candidate_keys is None:
228
+ candidate_keys = [
229
+ prediction_key_and_support(candidate["smiles"])
230
+ for candidate in candidates
231
+ ]
232
+ pool_prediction_keys[pool_id] = candidate_keys
233
+ observed = sparse_observed(
234
+ query,
235
+ args.num_bins,
236
+ args.upper_limit,
237
+ args.max_observed_peaks,
238
+ args.observed_intensity_threshold,
239
+ )
240
+ ce_key = common.get_collision_energy(collision_energy)
241
+ candidate_predictions = []
242
+ for candidate_ikey, support in candidate_keys:
243
+ pred = by_ikey.get(candidate_ikey)
244
+ if pred is None:
245
+ missing_predictions += 1
246
+ if support == "supported":
247
+ missing_supported_predictions += 1
248
+ else:
249
+ unsupported_missing[support] += 1
250
+ pred = {}
251
+ candidate_predictions.append(pred)
252
+ if args.distance == "mass_tolerant_entropy":
253
+ raw_observed = observed_peaks(query)
254
+ distances = np.asarray([
255
+ adduct_conditioned_entropy(raw_by_ikey.get(key, {}).get(ce_key, []), raw_observed, float(query['precursor_mz']), query['adduct'])
256
+ for key, support in candidate_keys
257
+ ], dtype=np.float64)
258
+ else:
259
+ distance_fn = _entropy_sparse if args.distance == "entropy" else _cosine_sparse
260
+ distances = distance_fn(candidate_predictions, observed, ce_key, sqrt_inten=True)
261
+ # GLACIER emits identical predictions for candidates that collapse to
262
+ # the same InChIKey. Break exact score ties by the content-derived
263
+ # candidate ID, never by the public candidate-file order.
264
+ candidate_ids = np.asarray(
265
+ [candidate["candidate_id"] for candidate in candidates]
266
+ )
267
+ if args.tie_break == "candidate_id":
268
+ order = np.lexsort((candidate_ids, distances))
269
+ else:
270
+ order = np.argsort(distances, kind="stable")
271
+ ranking = [candidates[int(index)]["candidate_id"] for index in order]
272
+ stream.write(
273
+ json.dumps(
274
+ {"query_id": query["query_id"], "ranking": ranking},
275
+ sort_keys=True,
276
+ separators=(",", ":"),
277
+ )
278
+ + "\n"
279
+ )
280
+ if score_stream is not None:
281
+ score_stream.write(json.dumps({"query_id":query["query_id"],"candidate_ids":candidate_ids.tolist(),"distances":distances.tolist()},separators=(",",":"))+"\n")
282
+ ranked_queries += 1
283
+ candidate_rows += len(candidates)
284
+
285
+ for prediction_db in predictions:
286
+ prediction_db.close()
287
+ if selected_queries is not None and ranked_queries != len(selected_queries):
288
+ raise ValueError(
289
+ "query ID allowlist was not fully ranked: "
290
+ f"{ranked_queries}/{len(selected_queries)}"
291
+ )
292
+ report = {
293
+ "schema": "glacier-contract-score/v2",
294
+ "distance": args.distance,
295
+ "tie_break": args.tie_break,
296
+ "ranked_queries": ranked_queries,
297
+ "candidate_rows": candidate_rows,
298
+ "missing_candidate_predictions": missing_predictions,
299
+ "missing_supported_candidate_predictions": missing_supported_predictions,
300
+ "model_unsupported_candidate_rows": dict(sorted(unsupported_missing.items())),
301
+ "num_bins": args.num_bins,
302
+ "upper_limit": args.upper_limit,
303
+ "prediction_shards": len(predictions),
304
+ "max_observed_peaks": args.max_observed_peaks,
305
+ "observed_intensity_threshold": args.observed_intensity_threshold,
306
+ "excluded_queries": len(excluded_queries),
307
+ "selected_queries": (
308
+ None if selected_queries is None else len(selected_queries)
309
+ ),
310
+ }
311
+ (output_root / "runtime.json").write_text(
312
+ json.dumps(report, sort_keys=True, indent=2) + "\n", encoding="utf-8"
313
+ )
314
+ print(json.dumps(report, sort_keys=True))
315
+
316
+
317
+ if __name__ == "__main__":
318
+ main()
shared/package-files/06/06d5a05ca7ad5be95f0bdccef3be5c8990d91c7cd8407c5c8d5079664130493a/blob ADDED
Binary file (56.6 kB). View file
 
shared/package-files/06/06d81abe6df0ddcf6677fe7215faba55ea3fe482bd2ad94b1752443de1e16685/blob ADDED
Binary file (48 Bytes). View file
 
shared/package-files/06/06dd7572626df5cb0a8d3affbac9bb74cb12469076836d66fd19ae5b5fab42c7/blob ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ namespace eval ::tk {
2
+ ::msgcat::mcset de "&Abort" "&Abbruch"
3
+ ::msgcat::mcset de "&About..." "&\u00dcber..."
4
+ ::msgcat::mcset de "All Files" "Alle Dateien"
5
+ ::msgcat::mcset de "Application Error" "Applikationsfehler"
6
+ ::msgcat::mcset de "&Apply" "&Anwenden"
7
+ ::msgcat::mcset de "Bold" "Fett"
8
+ ::msgcat::mcset de "Bold Italic" "Fett kursiv"
9
+ ::msgcat::mcset de "&Blue" "&Blau"
10
+ ::msgcat::mcset de "Cancel" "Abbruch"
11
+ ::msgcat::mcset de "&Cancel" "&Abbruch"
12
+ ::msgcat::mcset de "Cannot change to the directory \"%1\$s\".\nPermission denied." "Kann nicht in das Verzeichnis \"%1\$s\" wechseln.\nKeine Rechte vorhanden."
13
+ ::msgcat::mcset de "Choose Directory" "W\u00e4hle Verzeichnis"
14
+ ::msgcat::mcset de "Cl&ear" "&R\u00fccksetzen"
15
+ ::msgcat::mcset de "&Clear Console" "&Konsole l\u00f6schen"
16
+ ::msgcat::mcset de "Color" "Farbe"
17
+ ::msgcat::mcset de "Console" "Konsole"
18
+ ::msgcat::mcset de "&Copy" "&Kopieren"
19
+ ::msgcat::mcset de "Cu&t" "Aus&schneiden"
20
+ ::msgcat::mcset de "&Delete" "&L\u00f6schen"
21
+ ::msgcat::mcset de "Details >>"
22
+ ::msgcat::mcset de "Directory \"%1\$s\" does not exist." "Das Verzeichnis \"%1\$s\" existiert nicht."
23
+ ::msgcat::mcset de "&Directory:" "&Verzeichnis:"
24
+ ::msgcat::mcset de "&Edit" "&Bearbeiten"
25
+ ::msgcat::mcset de "Effects" "Effekte"
26
+ ::msgcat::mcset de "Error: %1\$s" "Fehler: %1\$s"
27
+ ::msgcat::mcset de "E&xit" "&Ende"
28
+ ::msgcat::mcset de "&File" "&Datei"
29
+ ::msgcat::mcset de "File \"%1\$s\" already exists.\nDo you want to overwrite it?" "Die Datei \"%1\$s\" ist bereits vorhanden.\nWollen sie diese Datei \u00fcberschreiben ?"
30
+ ::msgcat::mcset de "File \"%1\$s\" already exists.\n\n" "Die Datei \"%1\$s\" ist bereits vorhanden.\n\n"
31
+ ::msgcat::mcset de "File \"%1\$s\" does not exist." "Die Datei \"%1\$s\" existiert nicht."
32
+ ::msgcat::mcset de "File &name:" "Datei&name:"
33
+ ::msgcat::mcset de "File &names:" "Datei&namen:"
34
+ ::msgcat::mcset de "Files of &type:" "Dateien des &Typs:"
35
+ ::msgcat::mcset de "Fi&les:" "Dat&eien:"
36
+ ::msgcat::mcset de "&Filter"
37
+ ::msgcat::mcset de "Fil&ter:"
38
+ ::msgcat::mcset de "Font" "Schriftart"
39
+ ::msgcat::mcset de "&Font:" "Schriftart:"
40
+ ::msgcat::mcset de "Font st&yle:" "Schriftschnitt:"
41
+ ::msgcat::mcset de "&Green" "&Gr\u00fcn"
42
+ ::msgcat::mcset de "&Help" "&Hilfe"
43
+ ::msgcat::mcset de "Hi" "Hallo"
44
+ ::msgcat::mcset de "&Hide Console" "&Konsole unsichtbar machen"
45
+ ::msgcat::mcset de "&Ignore" "&Ignorieren"
46
+ ::msgcat::mcset de "Invalid file name \"%1\$s\"." "Ung\u00fcltiger Dateiname \"%1\$s\"."
47
+ ::msgcat::mcset de "Italic" "Kursiv"
48
+ ::msgcat::mcset de "Log Files" "Protokolldatei"
49
+ ::msgcat::mcset de "&No" "&Nein"
50
+ ::msgcat::mcset de "&OK"
51
+ ::msgcat::mcset de "OK"
52
+ ::msgcat::mcset de "Ok"
53
+ ::msgcat::mcset de "Open" "\u00d6ffnen"
54
+ ::msgcat::mcset de "&Open" "\u00d6&ffnen"
55
+ ::msgcat::mcset de "Open Multiple Files" "Mehrere Dateien \u00F6ffnen"
56
+ ::msgcat::mcset de "P&aste" "E&inf\u00fcgen"
57
+ ::msgcat::mcset de "&Quit" "&Beenden"
58
+ ::msgcat::mcset de "&Red" "&Rot"
59
+ ::msgcat::mcset de "Regular" "Standard"
60
+ ::msgcat::mcset de "Replace existing file?" "Existierende Datei ersetzen?"
61
+ ::msgcat::mcset de "&Retry" "&Wiederholen"
62
+ ::msgcat::mcset de "Sample" "Beispiel"
63
+ ::msgcat::mcset de "&Save" "&Speichern"
64
+ ::msgcat::mcset de "Save As" "Speichern unter"
65
+ ::msgcat::mcset de "Save To Log" "In Protokoll speichern"
66
+ ::msgcat::mcset de "Select Log File" "Protokolldatei ausw\u00e4hlen"
67
+ ::msgcat::mcset de "Select a file to source" "Auszuf\u00fchrende Datei ausw\u00e4hlen"
68
+ ::msgcat::mcset de "&Selection:" "Auswah&l:"
69
+ ::msgcat::mcset de "&Size:" "Schriftgrad:"
70
+ ::msgcat::mcset de "Show &Hidden Directories" "Zeige versteckte Dateien"
71
+ ::msgcat::mcset de "Show &Hidden Files and Directories" "Zeige versteckte Dateien und Verzeichnisse"
72
+ ::msgcat::mcset de "Skip Messages" "Weitere Nachrichten \u00fcberspringen"
73
+ ::msgcat::mcset de "&Source..." "&Ausf\u00fchren..."
74
+ ::msgcat::mcset de "Stri&keout" "&Durchgestrichen"
75
+ ::msgcat::mcset de "Tcl Scripts" "Tcl-Skripte"
76
+ ::msgcat::mcset de "Tcl for Windows" "Tcl f\u00fcr Windows"
77
+ ::msgcat::mcset de "Text Files" "Textdateien"
78
+ ::msgcat::mcset de "&Underline" "&Unterstrichen"
79
+ ::msgcat::mcset de "&Yes" "&Ja"
80
+ ::msgcat::mcset de "abort" "abbrechen"
81
+ ::msgcat::mcset de "blue" "blau"
82
+ ::msgcat::mcset de "cancel" "abbrechen"
83
+ ::msgcat::mcset de "extension" "Erweiterung"
84
+ ::msgcat::mcset de "extensions" "Erweiterungen"
85
+ ::msgcat::mcset de "green" "gr\u00fcn"
86
+ ::msgcat::mcset de "ignore" "ignorieren"
87
+ ::msgcat::mcset de "ok"
88
+ ::msgcat::mcset de "red" "rot"
89
+ ::msgcat::mcset de "retry" "wiederholen"
90
+ ::msgcat::mcset de "yes" "ja"
91
+ }
shared/package-files/06/06e073b6b3d045ab149956615ebdbf36026e8dd513361370779f696591e4de50/blob ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ DType classes and utility (:mod:`numpy.dtypes`)
3
+ ===============================================
4
+
5
+ This module is home to specific dtypes related functionality and their classes.
6
+ For more general information about dtypes, also see `numpy.dtype` and
7
+ :ref:`arrays.dtypes`.
8
+
9
+ Similar to the builtin ``types`` module, this submodule defines types (classes)
10
+ that are not widely used directly.
11
+
12
+ .. versionadded:: NumPy 1.25
13
+
14
+ The dtypes module is new in NumPy 1.25. Previously DType classes were
15
+ only accessible indirectly.
16
+
17
+
18
+ DType classes
19
+ -------------
20
+
21
+ The following are the classes of the corresponding NumPy dtype instances and
22
+ NumPy scalar types. The classes can be used in ``isinstance`` checks and can
23
+ also be instantiated or used directly. Direct use of these classes is not
24
+ typical, since their scalar counterparts (e.g. ``np.float64``) or strings
25
+ like ``"float64"`` can be used.
26
+
27
+ .. list-table::
28
+ :header-rows: 1
29
+
30
+ * - Group
31
+ - DType class
32
+
33
+ * - Boolean
34
+ - ``BoolDType``
35
+
36
+ * - Bit-sized integers
37
+ - ``Int8DType``, ``UInt8DType``, ``Int16DType``, ``UInt16DType``,
38
+ ``Int32DType``, ``UInt32DType``, ``Int64DType``, ``UInt64DType``
39
+
40
+ * - C-named integers (may be aliases)
41
+ - ``ByteDType``, ``UByteDType``, ``ShortDType``, ``UShortDType``,
42
+ ``IntDType``, ``UIntDType``, ``LongDType``, ``ULongDType``,
43
+ ``LongLongDType``, ``ULongLongDType``
44
+
45
+ * - Floating point
46
+ - ``Float16DType``, ``Float32DType``, ``Float64DType``,
47
+ ``LongDoubleDType``
48
+
49
+ * - Complex
50
+ - ``Complex64DType``, ``Complex128DType``, ``CLongDoubleDType``
51
+
52
+ * - Strings
53
+ - ``BytesDType``, ``BytesDType``
54
+
55
+ * - Times
56
+ - ``DateTime64DType``, ``TimeDelta64DType``
57
+
58
+ * - Others
59
+ - ``ObjectDType``, ``VoidDType``
60
+
61
+ """
62
+
63
+ __all__ = []
64
+
65
+
66
+ def _add_dtype_helper(DType, alias):
67
+ # Function to add DTypes a bit more conveniently without channeling them
68
+ # through `numpy.core._multiarray_umath` namespace or similar.
69
+ from numpy import dtypes
70
+
71
+ setattr(dtypes, DType.__name__, DType)
72
+ __all__.append(DType.__name__)
73
+
74
+ if alias:
75
+ alias = alias.removeprefix("numpy.dtypes.")
76
+ setattr(dtypes, alias, DType)
77
+ __all__.append(alias)
shared/package-files/06/06e09e6fc73ad2e0c7a626e83a4281976baedd3f84121ad841cb5ea2a23186a4/blob ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-manylinux_2_12_x86_64
5
+ Tag: cp310-cp310-manylinux2010_x86_64
6
+
shared/package-files/06/06e1e22eec6eeae11f64568f256dd13e93dac5a55cb44400de47522520cbd61c/blob ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import warn
2
+
3
+ from .notebook import * # NOQA
4
+ from .notebook import __all__ # NOQA
5
+ from .std import TqdmDeprecationWarning
6
+
7
+ warn("This function will be removed in tqdm==5.0.0\n"
8
+ "Please use `tqdm.notebook.*` instead of `tqdm._tqdm_notebook.*`",
9
+ TqdmDeprecationWarning, stacklevel=2)
shared/package-files/06/06e2998258a8a448014c373041a91ca92f11ae7ed3cfbafe012ea3c45085f5c2/blob ADDED
The diff for this file is too large to render. See raw diff
 
shared/package-files/06/06e2ecaf4175380e08780f35e81cee2c5892346a693e800ba62795dbff0d7e0f/blob ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ test scalar indexing, including at and iat """
2
+ from datetime import (
3
+ datetime,
4
+ timedelta,
5
+ )
6
+ import itertools
7
+
8
+ import numpy as np
9
+ import pytest
10
+
11
+ from pandas import (
12
+ DataFrame,
13
+ Series,
14
+ Timedelta,
15
+ Timestamp,
16
+ date_range,
17
+ )
18
+ import pandas._testing as tm
19
+
20
+
21
+ def generate_indices(f, values=False):
22
+ """
23
+ generate the indices
24
+ if values is True , use the axis values
25
+ is False, use the range
26
+ """
27
+ axes = f.axes
28
+ if values:
29
+ axes = (list(range(len(ax))) for ax in axes)
30
+
31
+ return itertools.product(*axes)
32
+
33
+
34
+ class TestScalar:
35
+ @pytest.mark.parametrize("kind", ["series", "frame"])
36
+ @pytest.mark.parametrize("col", ["ints", "uints"])
37
+ def test_iat_set_ints(self, kind, col, request):
38
+ f = request.getfixturevalue(f"{kind}_{col}")
39
+ indices = generate_indices(f, True)
40
+ for i in indices:
41
+ f.iat[i] = 1
42
+ expected = f.values[i]
43
+ tm.assert_almost_equal(expected, 1)
44
+
45
+ @pytest.mark.parametrize("kind", ["series", "frame"])
46
+ @pytest.mark.parametrize("col", ["labels", "ts", "floats"])
47
+ def test_iat_set_other(self, kind, col, request):
48
+ f = request.getfixturevalue(f"{kind}_{col}")
49
+ msg = "iAt based indexing can only have integer indexers"
50
+ with pytest.raises(ValueError, match=msg):
51
+ idx = next(generate_indices(f, False))
52
+ f.iat[idx] = 1
53
+
54
+ @pytest.mark.parametrize("kind", ["series", "frame"])
55
+ @pytest.mark.parametrize("col", ["ints", "uints", "labels", "ts", "floats"])
56
+ def test_at_set_ints_other(self, kind, col, request):
57
+ f = request.getfixturevalue(f"{kind}_{col}")
58
+ indices = generate_indices(f, False)
59
+ for i in indices:
60
+ f.at[i] = 1
61
+ expected = f.loc[i]
62
+ tm.assert_almost_equal(expected, 1)
63
+
64
+
65
+ class TestAtAndiAT:
66
+ # at and iat tests that don't need Base class
67
+
68
+ def test_float_index_at_iat(self):
69
+ ser = Series([1, 2, 3], index=[0.1, 0.2, 0.3])
70
+ for el, item in ser.items():
71
+ assert ser.at[el] == item
72
+ for i in range(len(ser)):
73
+ assert ser.iat[i] == i + 1
74
+
75
+ def test_at_iat_coercion(self):
76
+ # as timestamp is not a tuple!
77
+ dates = date_range("1/1/2000", periods=8)
78
+ df = DataFrame(
79
+ np.random.default_rng(2).standard_normal((8, 4)),
80
+ index=dates,
81
+ columns=["A", "B", "C", "D"],
82
+ )
83
+ s = df["A"]
84
+
85
+ result = s.at[dates[5]]
86
+ xp = s.values[5]
87
+ assert result == xp
88
+
89
+ @pytest.mark.parametrize(
90
+ "ser, expected",
91
+ [
92
+ [
93
+ Series(["2014-01-01", "2014-02-02"], dtype="datetime64[ns]"),
94
+ Timestamp("2014-02-02"),
95
+ ],
96
+ [
97
+ Series(["1 days", "2 days"], dtype="timedelta64[ns]"),
98
+ Timedelta("2 days"),
99
+ ],
100
+ ],
101
+ )
102
+ def test_iloc_iat_coercion_datelike(self, indexer_ial, ser, expected):
103
+ # GH 7729
104
+ # make sure we are boxing the returns
105
+ result = indexer_ial(ser)[1]
106
+ assert result == expected
107
+
108
+ def test_imethods_with_dups(self):
109
+ # GH6493
110
+ # iat/iloc with dups
111
+
112
+ s = Series(range(5), index=[1, 1, 2, 2, 3], dtype="int64")
113
+ result = s.iloc[2]
114
+ assert result == 2
115
+ result = s.iat[2]
116
+ assert result == 2
117
+
118
+ msg = "index 10 is out of bounds for axis 0 with size 5"
119
+ with pytest.raises(IndexError, match=msg):
120
+ s.iat[10]
121
+ msg = "index -10 is out of bounds for axis 0 with size 5"
122
+ with pytest.raises(IndexError, match=msg):
123
+ s.iat[-10]
124
+
125
+ result = s.iloc[[2, 3]]
126
+ expected = Series([2, 3], [2, 2], dtype="int64")
127
+ tm.assert_series_equal(result, expected)
128
+
129
+ df = s.to_frame()
130
+ result = df.iloc[2]
131
+ expected = Series(2, index=[0], name=2)
132
+ tm.assert_series_equal(result, expected)
133
+
134
+ result = df.iat[2, 0]
135
+ assert result == 2
136
+
137
+ def test_frame_at_with_duplicate_axes(self):
138
+ # GH#33041
139
+ arr = np.random.default_rng(2).standard_normal(6).reshape(3, 2)
140
+ df = DataFrame(arr, columns=["A", "A"])
141
+
142
+ result = df.at[0, "A"]
143
+ expected = df.iloc[0].copy()
144
+
145
+ tm.assert_series_equal(result, expected)
146
+
147
+ result = df.T.at["A", 0]
148
+ tm.assert_series_equal(result, expected)
149
+
150
+ # setter
151
+ df.at[1, "A"] = 2
152
+ expected = Series([2.0, 2.0], index=["A", "A"], name=1)
153
+ tm.assert_series_equal(df.iloc[1], expected)
154
+
155
+ def test_at_getitem_dt64tz_values(self):
156
+ # gh-15822
157
+ df = DataFrame(
158
+ {
159
+ "name": ["John", "Anderson"],
160
+ "date": [
161
+ Timestamp(2017, 3, 13, 13, 32, 56),
162
+ Timestamp(2017, 2, 16, 12, 10, 3),
163
+ ],
164
+ }
165
+ )
166
+ df["date"] = df["date"].dt.tz_localize("Asia/Shanghai")
167
+
168
+ expected = Timestamp("2017-03-13 13:32:56+0800", tz="Asia/Shanghai")
169
+
170
+ result = df.loc[0, "date"]
171
+ assert result == expected
172
+
173
+ result = df.at[0, "date"]
174
+ assert result == expected
175
+
176
+ def test_mixed_index_at_iat_loc_iloc_series(self):
177
+ # GH 19860
178
+ s = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2])
179
+ for el, item in s.items():
180
+ assert s.at[el] == s.loc[el] == item
181
+ for i in range(len(s)):
182
+ assert s.iat[i] == s.iloc[i] == i + 1
183
+
184
+ with pytest.raises(KeyError, match="^4$"):
185
+ s.at[4]
186
+ with pytest.raises(KeyError, match="^4$"):
187
+ s.loc[4]
188
+
189
+ def test_mixed_index_at_iat_loc_iloc_dataframe(self):
190
+ # GH 19860
191
+ df = DataFrame(
192
+ [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], columns=["a", "b", "c", 1, 2]
193
+ )
194
+ for rowIdx, row in df.iterrows():
195
+ for el, item in row.items():
196
+ assert df.at[rowIdx, el] == df.loc[rowIdx, el] == item
197
+
198
+ for row in range(2):
199
+ for i in range(5):
200
+ assert df.iat[row, i] == df.iloc[row, i] == row * 5 + i
201
+
202
+ with pytest.raises(KeyError, match="^3$"):
203
+ df.at[0, 3]
204
+ with pytest.raises(KeyError, match="^3$"):
205
+ df.loc[0, 3]
206
+
207
+ def test_iat_setter_incompatible_assignment(self):
208
+ # GH 23236
209
+ result = DataFrame({"a": [0.0, 1.0], "b": [4, 5]})
210
+ result.iat[0, 0] = None
211
+ expected = DataFrame({"a": [None, 1], "b": [4, 5]})
212
+ tm.assert_frame_equal(result, expected)
213
+
214
+
215
+ def test_iat_dont_wrap_object_datetimelike():
216
+ # GH#32809 .iat calls go through DataFrame._get_value, should not
217
+ # call maybe_box_datetimelike
218
+ dti = date_range("2016-01-01", periods=3)
219
+ tdi = dti - dti
220
+ ser = Series(dti.to_pydatetime(), dtype=object)
221
+ ser2 = Series(tdi.to_pytimedelta(), dtype=object)
222
+ df = DataFrame({"A": ser, "B": ser2})
223
+ assert (df.dtypes == object).all()
224
+
225
+ for result in [df.at[0, "A"], df.iat[0, 0], df.loc[0, "A"], df.iloc[0, 0]]:
226
+ assert result is ser[0]
227
+ assert isinstance(result, datetime)
228
+ assert not isinstance(result, Timestamp)
229
+
230
+ for result in [df.at[1, "B"], df.iat[1, 1], df.loc[1, "B"], df.iloc[1, 1]]:
231
+ assert result is ser2[1]
232
+ assert isinstance(result, timedelta)
233
+ assert not isinstance(result, Timedelta)
234
+
235
+
236
+ def test_at_with_tuple_index_get():
237
+ # GH 26989
238
+ # DataFrame.at getter works with Index of tuples
239
+ df = DataFrame({"a": [1, 2]}, index=[(1, 2), (3, 4)])
240
+ assert df.index.nlevels == 1
241
+ assert df.at[(1, 2), "a"] == 1
242
+
243
+ # Series.at getter works with Index of tuples
244
+ series = df["a"]
245
+ assert series.index.nlevels == 1
246
+ assert series.at[(1, 2)] == 1
247
+
248
+
249
+ @pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning")
250
+ def test_at_with_tuple_index_set():
251
+ # GH 26989
252
+ # DataFrame.at setter works with Index of tuples
253
+ df = DataFrame({"a": [1, 2]}, index=[(1, 2), (3, 4)])
254
+ assert df.index.nlevels == 1
255
+ df.at[(1, 2), "a"] = 2
256
+ assert df.at[(1, 2), "a"] == 2
257
+
258
+ # Series.at setter works with Index of tuples
259
+ series = df["a"]
260
+ assert series.index.nlevels == 1
261
+ series.at[1, 2] = 3
262
+ assert series.at[1, 2] == 3
263
+
264
+
265
+ class TestMultiIndexScalar:
266
+ def test_multiindex_at_get(self):
267
+ # GH 26989
268
+ # DataFrame.at and DataFrame.loc getter works with MultiIndex
269
+ df = DataFrame({"a": [1, 2]}, index=[[1, 2], [3, 4]])
270
+ assert df.index.nlevels == 2
271
+ assert df.at[(1, 3), "a"] == 1
272
+ assert df.loc[(1, 3), "a"] == 1
273
+
274
+ # Series.at and Series.loc getter works with MultiIndex
275
+ series = df["a"]
276
+ assert series.index.nlevels == 2
277
+ assert series.at[1, 3] == 1
278
+ assert series.loc[1, 3] == 1
279
+
280
+ @pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning")
281
+ def test_multiindex_at_set(self):
282
+ # GH 26989
283
+ # DataFrame.at and DataFrame.loc setter works with MultiIndex
284
+ df = DataFrame({"a": [1, 2]}, index=[[1, 2], [3, 4]])
285
+ assert df.index.nlevels == 2
286
+ df.at[(1, 3), "a"] = 3
287
+ assert df.at[(1, 3), "a"] == 3
288
+ df.loc[(1, 3), "a"] = 4
289
+ assert df.loc[(1, 3), "a"] == 4
290
+
291
+ # Series.at and Series.loc setter works with MultiIndex
292
+ series = df["a"]
293
+ assert series.index.nlevels == 2
294
+ series.at[1, 3] = 5
295
+ assert series.at[1, 3] == 5
296
+ series.loc[1, 3] = 6
297
+ assert series.loc[1, 3] == 6
298
+
299
+ def test_multiindex_at_get_one_level(self):
300
+ # GH#38053
301
+ s2 = Series((0, 1), index=[[False, True]])
302
+ result = s2.at[False]
303
+ assert result == 0
shared/package-files/06/06e4113c5d11f4cadb2f31b2338e39475c67e2f79bdca96cd05181611f54afda/blob ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor linalg_tensorinv(const at::Tensor & self, int64_t ind=2);
20
+ TORCH_API at::Tensor & linalg_tensorinv_out(const at::Tensor & self, int64_t ind, at::Tensor & out);
21
+ } // namespace native
22
+ } // namespace at
shared/package-files/06/06e5736b4eef85a7e4abaf15abd8328a482b85c39d0fac6eacfc0f1eaaa8a041/blob ADDED
Binary file (400 Bytes). View file