Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- shared/package-files/24/2401f8891988a22bdb5937ea83f4eae85d8077566f0663cc72af2642884666d5/enet_poisson.csv +200 -0
- shared/package-files/24/24023790eeb1292323b0bc65624e048a306e92d38747053d53dd5af763af6274/csvs.py +330 -0
- shared/package-files/24/2402e13bbbee2f27a17427b979c3c06e2fd7f9678f880ab3a18525deefe6aca5/quantization.h +38 -0
- shared/package-files/24/2403a7a3ddf4893c9f6482cc7f5d6f5ad89a4e0ac970fa4fe8545346110c303e/pbkdi8a.afm +417 -0
- shared/package-files/24/240417d84507c25a4a09f2431aca5a95d9ac2116c7c675e9b0d52bbd1ae72041/test_transpose.py +80 -0
- shared/package-files/24/24059769bf429929af981af5b71ab1c0ad45bef9b9911d9573cea0793f045fee/_adaptive_avg_pool3d_compositeexplicitautograd_dispatch.h +26 -0
- shared/package-files/24/240866561bb149091666d7d80374308601932ae0bfbaa2290c8c5fc4c71ec247/_storage_utils.py +50 -0
- shared/package-files/24/2409674eb17759c589a0e81027dc5cc15f353ff0b7615cf0ee14de1f2e9b053a/randn_like_native.h +22 -0
- shared/package-files/24/2409abaeb08471dc999602cefd8e279ac521539ea02b2acc937f5653df7529ba/aaa-rv-unk +0 -0
- shared/package-files/24/240b1bc868eff321ddf6abec22e6ff6a6242bc8a94cbb9079d650c15ad6aa439/cummax_compositeexplicitautograd_dispatch.h +25 -0
- shared/package-files/24/240cf4858d60049bb743f76fb1c42b4897602aec298ea159570cfeb0e410db5c/expn_asy.py +54 -0
- shared/package-files/24/240df50f08152d7462a1bbf2e9ef1e13f302548755f2dbfa8c4b02bc0747eef6/gradient_compositeimplicitautograd_dispatch.h +29 -0
- shared/package-files/24/240ec356d2e50b782c932b20b4e46d9bdfb851687d916afd1636d76dd42c211a/logging.py +38 -0
- shared/package-files/24/240ef7ea81b7b3c3cf74a85db182be06774b52c1ab24224021106c79220466d3/some_functions.mat +0 -0
- shared/package-files/24/241601dc076764ac412e2de0ce415427a744dcce14d4a07a9ab099c2b0b45759/api.py +575 -0
- shared/package-files/24/2417ef38fa791d31a9e9bd24ca7923cee24e4d101d4ec2497633d62c0b6ed5fa/mips.py +128 -0
- shared/package-files/24/241c13f3f868899bbe62b4183bc9366f3c6ade58af2a0aac78050e397cb00a7f/_scaled_dot_product_flash_attention_for_cpu_backward_native.h +21 -0
- shared/package-files/24/241e0d5f147c401880086352dc008993216c3358c41ee9a6f4ee445dce642972/reaching.py +204 -0
- shared/package-files/24/242443b3bdc867472e27cea8a2650b10e1278d85dcd9e892ff68bde81fe2dabd/q_per_channel_scales.h +39 -0
- shared/package-files/24/2429fc58747ec180ecf23879f08199e932d28a4e73b86b3110e6a57b5997e414/cyk.py +340 -0
- shared/package-files/24/242cfa28c340e230ca7a721f8b46762a156954e6f56f3cc196d133ee84ce5e5c/evalpoly.h +47 -0
- shared/package-files/24/242d057d55ec9c1da56476fe9c66f24a7c6fffd5470320f498a68b0e8c1ccc55/gh21665.f90 +9 -0
- shared/package-files/24/2434fd89260c74b25f22debe4869340d8597173f49305e1621927e24ad009251/retains_grad.h +26 -0
- shared/package-files/24/243a14b3dc356d899eeda1bf789d5c0adb2d453583ef50731bc8918be1b67871/entry_points.txt +5 -0
- shared/package-files/24/243abe485005fa96b0727700f1b0aa58512605d43c9f58fd3c751ecb8058fe74/test_openml.py +1636 -0
- shared/package-files/24/243b231c639f70b7ee8d8b166f9f3fe40986a5e8123768448e1d5091af3a6799/reproc++-config-version.cmake +70 -0
- shared/package-files/24/243b231c639f70b7ee8d8b166f9f3fe40986a5e8123768448e1d5091af3a6799/reproc-config-version.cmake +70 -0
- shared/package-files/24/243b94504f86c8f6a190d9c364b58d1f20262769493c29cbb885057c79233330/fujitsuccompiler.py +28 -0
- shared/package-files/24/243d45e43b41d84a74d19255a6296096e96a2adeac4c1c2eee14bf0a6c3609e9/THConcat.h +19 -0
- shared/package-files/24/243de318102a4474586f58da6e5ae9abf44542f62d61fc2d2083c9810a5b28f7/axes_divider.py +618 -0
- shared/package-files/24/244001226e8b3724826d252ae872d2fbfa9318adc78157127125cba43b2b27ca/test_isocalendar.py +28 -0
- shared/package-files/24/24415b8f3a5774313e414ce08ad16956d9dbd2f7b93418da69c833d6e8a5dd38/test_shimmodule.py +12 -0
- shared/package-files/24/2443e65ae9a693b8347671f908438d3dd72ad29ab2384a227e1b8f1734ac5e36/METADATA +63 -0
- shared/package-files/24/244432432425902d28e994dd7958d984220e87a70ae5317b1f4d0f925b3eb142/GMT+10 +0 -0
- shared/package-files/24/2446203c7a2bbe557dce6f2b235f7e79cba0addfdb6f97d3c46850e63aa36c0f/_thread_flow_location.py +67 -0
- shared/package-files/24/2449929a6aaa2f26b0f0fe75814226661f06c20f62d7349ef83a2a022b67da77/__init__.py +49 -0
- shared/package-files/24/244efc06cf6026643cd2adbbbfc92f2481210e8f1f4d5ac59c2b3a61b7a9e1f8/spectral.py +554 -0
- shared/package-files/24/2453a1a5d8c04244ff7bb1449c76ee8dc796bb1ed41cb1cfb8c03c1f7b9ef370/gelu_meta_dispatch.h +26 -0
- shared/package-files/24/245536c3df1c07f5cdc1faea36d234c834e6a4477160efd4125da9808feb9edf/foo.f90 +34 -0
- shared/package-files/24/245812393de1bba77b321f6c76abd2c42dd1c655651ff73282c5e9b17f7b60c6/recurrence.py +365 -0
- shared/package-files/24/245b08a462f0ba7494a889a259472293fdc05fb251a914d8e2a81934c9cf8267/test_make_function_to_jit_function.py +284 -0
- shared/package-files/24/245d3068e31e571032a39dd504e627662b96f2870b953c7fd326f45412889db0/_cudnn_ctc_loss_compositeexplicitautograd_dispatch.h +24 -0
- shared/package-files/24/24630064571ade8d27bfeff84cae09ffec452a0ec3ccd984ff31e8a7821c27e1/platform-1.0.18.tm +439 -0
- shared/package-files/24/2464429fd69c57cd260e211ebf3a11995d1dc1457103d2c470b947b6a2bc7500/nodes.py +135 -0
- shared/package-files/24/24661a72a24c12a1d2ea84f6018b3d77b8aeb4811bdf63e426cf4426a387c5c4/test_demidovich.py +143 -0
- shared/package-files/24/246b1b277cc14186ae6720e94827eb5e64543b8a671fe0487f03835f7a804e83/test_xs.py +444 -0
- shared/package-files/24/246f87751c118f2a5cfa588356a577af4147982ab5d60cbda4ac7676ba08cd83/MaybeOwned.h +237 -0
- shared/package-files/24/246feb139039664e5ec657e2bd91e7388dd4a739bc7498e628a1e4c048dee0b4/test_non_unique.py +140 -0
- shared/package-files/24/24703165ad1fd520140a056ab8e75450e1aa49170ccb3deb9298972f53e5a1cf/entry_points.txt +2 -0
- shared/package-files/24/2471caaaa65bda395622483db7a4acc5b2cbdbb485e555b2181ea2517a97d40d/models.py +219 -0
shared/package-files/24/2401f8891988a22bdb5937ea83f4eae85d8077566f0663cc72af2642884666d5/enet_poisson.csv
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.31,-1.11
|
| 13 |
+
1.00,-0.17,-0.37,-0.85,0.07,2.76
|
| 14 |
+
1.00,1.28,-1.07,-0.26,0.62,0.96
|
| 15 |
+
3.00,-0.59,1.92,1.04,-0.48,0.69
|
| 16 |
+
1.00,0.42,0.05,1.47,-0.74,0.91
|
| 17 |
+
3.00,0.76,1.23,1.53,-1.09,3.17
|
| 18 |
+
0.00,0.23,0.28,0.60,1.13,0.05
|
| 19 |
+
3.00,1.10,-1.38,0.27,0.82,0.47
|
| 20 |
+
0.00,-0.87,-0.78,-0.47,1.55,-1.25
|
| 21 |
+
1.00,0.22,-0.46,-0.10,-2.41,2.14
|
| 22 |
+
1.00,-2.31,0.31,-1.17,-0.52,1.06
|
| 23 |
+
1.00,-1.42,1.02,2.48,-0.11,1.07
|
| 24 |
+
1.00,0.28,1.25,0.83,0.48,-1.04
|
| 25 |
+
0.00,-0.48,0.24,-0.44,1.00,1.06
|
| 26 |
+
3.00,-0.30,-0.92,0.96,0.33,2.13
|
| 27 |
+
0.00,1.20,-0.39,0.03,-0.55,-1.21
|
| 28 |
+
1.00,-0.10,-0.68,0.11,-1.40,-0.35
|
| 29 |
+
1.00,-1.16,0.73,-0.53,0.14,0.08
|
| 30 |
+
1.00,-1.74,-0.43,-0.84,0.35,-2.00
|
| 31 |
+
2.00,0.48,0.33,0.46,0.34,-0.14
|
| 32 |
+
2.00,-0.41,0.13,0.65,-0.76,1.13
|
| 33 |
+
3.00,0.61,-0.48,1.36,1.34,0.68
|
| 34 |
+
0.00,1.12,-2.13,-0.99,-1.13,-0.29
|
| 35 |
+
2.00,-1.71,0.91,-0.63,0.48,-0.48
|
| 36 |
+
1.00,-1.19,0.02,-0.21,0.51,0.67
|
| 37 |
+
3.00,1.09,-0.63,0.82,-0.27,-1.37
|
| 38 |
+
3.00,1.46,1.03,-0.84,-0.66,-0.38
|
| 39 |
+
5.00,1.84,1.02,1.67,-0.97,0.69
|
| 40 |
+
2.00,0.30,1.62,-1.31,2.28,-0.43
|
| 41 |
+
0.00,0.50,-0.04,-0.99,0.24,-0.86
|
| 42 |
+
0.00,-0.75,1.09,0.22,1.85,0.77
|
| 43 |
+
1.00,1.36,-0.40,-0.52,0.15,-0.18
|
| 44 |
+
2.00,-1.14,0.19,0.36,0.60,-2.80
|
| 45 |
+
1.00,0.54,-1.31,-0.34,-1.65,1.17
|
| 46 |
+
0.00,1.82,-0.44,-0.76,0.99,-0.24
|
| 47 |
+
0.00,-0.19,-0.41,1.63,1.14,-0.50
|
| 48 |
+
4.00,1.01,0.72,0.97,0.90,1.68
|
| 49 |
+
1.00,-1.40,0.12,1.25,1.86,-0.14
|
| 50 |
+
0.00,-0.36,0.64,0.23,-0.71,-2.03
|
| 51 |
+
2.00,0.00,0.92,-0.16,0.08,0.47
|
| 52 |
+
1.00,-0.38,-2.33,1.56,-0.86,-0.31
|
| 53 |
+
0.00,-1.03,-1.43,0.72,0.97,-1.50
|
| 54 |
+
4.00,0.97,1.11,-0.89,0.29,0.89
|
| 55 |
+
0.00,0.66,-1.89,-1.69,1.10,-1.02
|
| 56 |
+
1.00,0.24,0.47,-1.71,1.10,-1.43
|
| 57 |
+
0.00,-0.14,-0.69,0.38,-0.50,-0.11
|
| 58 |
+
2.00,0.02,0.88,-1.96,-0.12,0.94
|
| 59 |
+
2.00,-0.38,-0.27,1.16,0.48,1.98
|
| 60 |
+
1.00,0.22,1.57,-0.77,0.53,0.88
|
| 61 |
+
4.00,0.13,0.49,1.35,-0.23,1.48
|
| 62 |
+
2.00,0.41,-2.89,1.12,-0.00,1.79
|
| 63 |
+
1.00,-1.47,1.51,0.11,0.41,0.68
|
| 64 |
+
2.00,-0.58,1.42,0.43,0.62,1.34
|
| 65 |
+
1.00,0.35,0.71,0.30,-2.30,1.33
|
| 66 |
+
2.00,0.42,-0.55,2.37,0.76,0.70
|
| 67 |
+
1.00,-0.65,0.19,-1.47,-0.08,-0.63
|
| 68 |
+
1.00,-0.75,-1.08,-0.14,1.10,-1.14
|
| 69 |
+
3.00,1.48,-1.65,0.97,-0.25,-0.48
|
| 70 |
+
4.00,-0.42,-1.86,-1.33,-0.63,0.28
|
| 71 |
+
2.00,1.61,-1.08,-0.18,-1.78,0.49
|
| 72 |
+
2.00,-0.45,0.02,1.47,0.80,0.58
|
| 73 |
+
1.00,-1.11,1.13,0.17,1.12,0.49
|
| 74 |
+
1.00,1.61,0.16,1.27,-1.95,-0.00
|
| 75 |
+
4.00,-0.67,0.76,1.21,2.99,-0.07
|
| 76 |
+
0.00,-0.16,-0.75,-0.38,-0.71,-1.44
|
| 77 |
+
2.00,-0.29,0.61,0.88,-0.11,0.31
|
| 78 |
+
0.00,-0.14,0.03,-0.63,-1.06,-0.01
|
| 79 |
+
0.00,0.68,0.53,-0.84,1.04,-1.03
|
| 80 |
+
1.00,-0.96,1.24,0.57,-0.01,0.34
|
| 81 |
+
2.00,-0.01,-0.11,0.19,0.46,0.23
|
| 82 |
+
0.00,1.66,-1.70,-0.25,1.15,-0.84
|
| 83 |
+
0.00,-1.43,0.61,-0.84,2.37,0.35
|
| 84 |
+
0.00,-0.08,-1.17,1.60,-0.85,-2.67
|
| 85 |
+
1.00,0.85,0.70,1.40,-0.46,-0.87
|
| 86 |
+
0.00,-0.22,-0.88,-1.94,0.37,1.33
|
| 87 |
+
2.00,-0.84,1.32,-1.02,-0.21,0.93
|
| 88 |
+
3.00,-1.25,0.65,0.75,1.01,-1.05
|
| 89 |
+
0.00,0.84,-1.04,0.08,-0.24,1.48
|
| 90 |
+
0.00,0.32,-0.69,0.83,-0.29,-1.36
|
| 91 |
+
0.00,0.72,-0.44,-1.80,-0.37,0.33
|
| 92 |
+
0.00,-2.29,-0.09,0.28,-0.99,0.85
|
| 93 |
+
2.00,1.01,-1.89,0.66,-0.11,-0.19
|
| 94 |
+
1.00,0.07,-0.78,-0.65,0.87,1.86
|
| 95 |
+
1.00,0.13,-1.87,0.38,-0.84,-0.38
|
| 96 |
+
1.00,1.14,-0.59,1.22,2.11,1.43
|
| 97 |
+
0.00,-1.29,1.29,0.87,-1.83,1.59
|
| 98 |
+
0.00,-1.14,-2.02,0.17,0.08,-2.81
|
| 99 |
+
1.00,-0.02,-1.71,2.18,0.66,1.10
|
| 100 |
+
1.00,-0.69,-0.79,0.27,0.14,-1.79
|
| 101 |
+
2.00,-0.22,-0.65,-0.09,1.15,-0.47
|
| 102 |
+
0.00,-0.35,0.12,0.36,-0.00,1.00
|
| 103 |
+
0.00,-0.47,1.60,-1.96,0.11,0.88
|
| 104 |
+
2.00,0.29,0.33,0.73,-0.55,0.34
|
| 105 |
+
0.00,-0.25,-1.42,0.76,-1.71,-0.60
|
| 106 |
+
2.00,-0.48,0.83,0.19,-1.23,-0.61
|
| 107 |
+
1.00,-2.01,0.45,-0.78,0.64,1.34
|
| 108 |
+
1.00,-0.34,-2.13,1.11,0.30,-1.44
|
| 109 |
+
0.00,-1.29,1.85,1.03,2.08,-0.67
|
| 110 |
+
1.00,1.44,-0.45,-0.58,0.76,1.95
|
| 111 |
+
1.00,-0.07,-0.15,0.19,2.36,0.60
|
| 112 |
+
1.00,0.37,1.25,-0.67,1.64,-1.62
|
| 113 |
+
4.00,0.51,-0.72,0.82,-0.02,1.77
|
| 114 |
+
1.00,-0.26,-0.14,0.05,1.64,0.72
|
| 115 |
+
2.00,1.88,0.38,-0.50,0.67,0.55
|
| 116 |
+
2.00,-1.71,-1.24,0.44,1.06,1.13
|
| 117 |
+
1.00,0.30,1.03,-0.50,0.88,0.78
|
| 118 |
+
2.00,-0.15,1.82,-0.96,0.14,-0.31
|
| 119 |
+
0.00,0.88,-0.33,-1.65,-1.40,-0.09
|
| 120 |
+
1.00,0.97,-0.95,-0.94,-1.24,-0.31
|
| 121 |
+
1.00,1.29,-1.08,0.01,0.39,0.49
|
| 122 |
+
2.00,-0.22,0.27,1.00,0.47,0.25
|
| 123 |
+
0.00,-0.11,-1.03,-1.13,-2.08,-0.15
|
| 124 |
+
1.00,0.31,-1.72,0.23,1.15,0.74
|
| 125 |
+
3.00,0.04,0.92,1.23,-0.51,-0.76
|
| 126 |
+
0.00,-0.79,0.91,-1.62,-0.01,-0.79
|
| 127 |
+
5.00,1.37,-0.86,2.21,0.87,0.23
|
| 128 |
+
2.00,1.35,-0.51,-2.27,0.46,1.89
|
| 129 |
+
0.00,1.17,-0.37,0.60,1.29,-0.44
|
| 130 |
+
2.00,-0.46,-1.17,1.10,1.61,0.38
|
| 131 |
+
0.00,0.82,0.66,-0.48,-0.52,0.36
|
| 132 |
+
0.00,-1.04,-0.38,-2.27,-0.51,-1.08
|
| 133 |
+
4.00,0.18,-0.20,0.48,1.22,1.19
|
| 134 |
+
6.00,1.58,0.59,0.56,0.04,0.34
|
| 135 |
+
2.00,1.99,0.31,0.77,0.23,-0.12
|
| 136 |
+
1.00,-0.89,1.15,-0.97,0.29,0.60
|
| 137 |
+
0.00,0.08,0.18,1.04,1.09,0.21
|
| 138 |
+
1.00,0.13,-1.82,1.29,1.21,1.16
|
| 139 |
+
1.00,1.60,0.76,-0.37,0.69,-1.22
|
| 140 |
+
0.00,1.43,-0.60,-1.89,-1.00,0.78
|
| 141 |
+
0.00,-0.37,-0.40,0.17,-0.64,0.31
|
| 142 |
+
0.00,0.39,0.90,-0.97,-0.47,0.87
|
| 143 |
+
2.00,0.98,-0.64,-1.86,0.68,0.60
|
| 144 |
+
0.00,1.05,-0.40,0.24,-0.65,0.69
|
| 145 |
+
2.00,1.28,-0.66,1.18,-0.64,0.90
|
| 146 |
+
0.00,-0.03,-1.60,-0.76,-0.46,-0.57
|
| 147 |
+
3.00,1.81,-0.33,-0.25,1.47,1.59
|
| 148 |
+
3.00,0.94,-1.43,0.54,0.31,0.03
|
| 149 |
+
1.00,-0.85,1.07,0.98,-2.15,-0.79
|
| 150 |
+
3.00,1.60,-1.28,1.15,0.10,-0.33
|
| 151 |
+
1.00,2.01,-0.29,1.21,0.50,-1.70
|
| 152 |
+
1.00,-1.23,1.40,-1.12,-1.08,0.25
|
| 153 |
+
0.00,0.01,2.06,0.57,-0.42,-0.56
|
| 154 |
+
1.00,-0.45,0.75,1.28,-0.39,0.30
|
| 155 |
+
1.00,-0.08,-1.03,0.64,-0.02,0.78
|
| 156 |
+
0.00,1.13,0.08,0.16,0.73,-0.09
|
| 157 |
+
2.00,-2.34,0.61,0.44,0.90,0.65
|
| 158 |
+
0.00,-2.00,1.51,-1.33,1.11,-0.59
|
| 159 |
+
0.00,-0.50,-0.01,0.67,-0.19,0.50
|
| 160 |
+
1.00,-0.89,0.61,0.36,1.33,0.69
|
| 161 |
+
0.00,0.92,1.10,-0.47,-1.66,0.64
|
| 162 |
+
2.00,0.80,-0.24,-0.91,1.46,1.74
|
| 163 |
+
2.00,0.69,-0.20,-0.91,-0.91,0.21
|
| 164 |
+
0.00,-0.46,0.43,0.47,0.40,-0.58
|
| 165 |
+
1.00,1.24,-0.76,-0.41,0.88,-0.27
|
| 166 |
+
0.00,-0.15,-1.04,0.63,0.51,-2.06
|
| 167 |
+
2.00,-1.55,-0.59,1.03,-0.31,1.49
|
| 168 |
+
1.00,0.23,-0.45,0.60,0.22,-1.05
|
| 169 |
+
2.00,-0.21,-1.30,1.60,-0.72,1.09
|
| 170 |
+
2.00,0.35,-1.89,1.42,-1.77,-0.14
|
| 171 |
+
0.00,-2.33,0.16,-1.60,-1.17,-0.16
|
| 172 |
+
0.00,0.37,-1.10,0.43,1.19,-1.41
|
| 173 |
+
4.00,-0.32,1.94,0.49,0.14,1.12
|
| 174 |
+
1.00,-1.03,1.27,0.49,-0.55,0.07
|
| 175 |
+
2.00,-0.83,0.66,1.13,0.16,-1.13
|
| 176 |
+
0.00,-1.17,-0.10,-0.09,-0.09,-0.49
|
| 177 |
+
0.00,-1.17,-0.07,-0.10,1.42,-1.77
|
| 178 |
+
0.00,1.66,-1.07,-0.96,1.12,-1.98
|
| 179 |
+
0.00,2.75,1.14,-0.05,0.58,0.14
|
| 180 |
+
1.00,-1.06,0.66,-0.98,1.17,0.02
|
| 181 |
+
0.00,-1.02,-0.36,0.06,0.67,-0.29
|
| 182 |
+
2.00,0.28,0.73,-0.62,-0.56,1.98
|
| 183 |
+
0.00,-0.17,-2.83,-1.42,-0.19,-0.77
|
| 184 |
+
2.00,1.64,-0.91,-1.54,-2.04,1.41
|
| 185 |
+
1.00,1.48,0.46,-0.46,-0.71,-1.07
|
| 186 |
+
0.00,0.02,0.93,2.02,-0.84,1.44
|
| 187 |
+
1.00,0.13,-0.27,1.43,0.22,-1.15
|
| 188 |
+
1.00,0.26,-1.04,0.11,0.18,0.46
|
| 189 |
+
2.00,0.51,-1.22,-0.03,0.11,0.86
|
| 190 |
+
3.00,-1.07,-1.32,-0.11,-0.03,-0.11
|
| 191 |
+
4.00,-1.67,1.23,0.01,-0.85,-0.45
|
| 192 |
+
1.00,0.99,1.07,-0.37,0.38,0.95
|
| 193 |
+
1.00,-1.77,-0.72,-0.54,-0.05,1.08
|
| 194 |
+
0.00,-0.80,-0.03,-0.00,0.92,1.12
|
| 195 |
+
2.00,-0.77,-0.08,-0.41,2.02,-0.62
|
| 196 |
+
0.00,0.80,0.03,0.90,-1.62,-0.40
|
| 197 |
+
0.00,1.06,1.06,-0.73,-0.11,0.04
|
| 198 |
+
1.00,0.25,-0.36,-0.44,0.40,-0.13
|
| 199 |
+
1.00,0.38,-0.47,-1.65,0.47,-0.13
|
| 200 |
+
5.00,1.12,0.34,-0.87,1.43,0.07
|
shared/package-files/24/24023790eeb1292323b0bc65624e048a306e92d38747053d53dd5af763af6274/csvs.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Module for formatting output data into CSV files.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from collections.abc import (
|
| 8 |
+
Hashable,
|
| 9 |
+
Iterable,
|
| 10 |
+
Iterator,
|
| 11 |
+
Sequence,
|
| 12 |
+
)
|
| 13 |
+
import csv as csvlib
|
| 14 |
+
import os
|
| 15 |
+
from typing import (
|
| 16 |
+
TYPE_CHECKING,
|
| 17 |
+
Any,
|
| 18 |
+
cast,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
from pandas._libs import writers as libwriters
|
| 24 |
+
from pandas._typing import SequenceNotStr
|
| 25 |
+
from pandas.util._decorators import cache_readonly
|
| 26 |
+
|
| 27 |
+
from pandas.core.dtypes.generic import (
|
| 28 |
+
ABCDatetimeIndex,
|
| 29 |
+
ABCIndex,
|
| 30 |
+
ABCMultiIndex,
|
| 31 |
+
ABCPeriodIndex,
|
| 32 |
+
)
|
| 33 |
+
from pandas.core.dtypes.missing import notna
|
| 34 |
+
|
| 35 |
+
from pandas.core.indexes.api import Index
|
| 36 |
+
|
| 37 |
+
from pandas.io.common import get_handle
|
| 38 |
+
|
| 39 |
+
if TYPE_CHECKING:
|
| 40 |
+
from pandas._typing import (
|
| 41 |
+
CompressionOptions,
|
| 42 |
+
FilePath,
|
| 43 |
+
FloatFormatType,
|
| 44 |
+
IndexLabel,
|
| 45 |
+
StorageOptions,
|
| 46 |
+
WriteBuffer,
|
| 47 |
+
npt,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
from pandas.io.formats.format import DataFrameFormatter
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
_DEFAULT_CHUNKSIZE_CELLS = 100_000
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class CSVFormatter:
|
| 57 |
+
cols: npt.NDArray[np.object_]
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
formatter: DataFrameFormatter,
|
| 62 |
+
path_or_buf: FilePath | WriteBuffer[str] | WriteBuffer[bytes] = "",
|
| 63 |
+
sep: str = ",",
|
| 64 |
+
cols: Sequence[Hashable] | None = None,
|
| 65 |
+
index_label: IndexLabel | None = None,
|
| 66 |
+
mode: str = "w",
|
| 67 |
+
encoding: str | None = None,
|
| 68 |
+
errors: str = "strict",
|
| 69 |
+
compression: CompressionOptions = "infer",
|
| 70 |
+
quoting: int | None = None,
|
| 71 |
+
lineterminator: str | None = "\n",
|
| 72 |
+
chunksize: int | None = None,
|
| 73 |
+
quotechar: str | None = '"',
|
| 74 |
+
date_format: str | None = None,
|
| 75 |
+
doublequote: bool = True,
|
| 76 |
+
escapechar: str | None = None,
|
| 77 |
+
storage_options: StorageOptions | None = None,
|
| 78 |
+
) -> None:
|
| 79 |
+
self.fmt = formatter
|
| 80 |
+
|
| 81 |
+
self.obj = self.fmt.frame
|
| 82 |
+
|
| 83 |
+
self.filepath_or_buffer = path_or_buf
|
| 84 |
+
self.encoding = encoding
|
| 85 |
+
self.compression: CompressionOptions = compression
|
| 86 |
+
self.mode = mode
|
| 87 |
+
self.storage_options = storage_options
|
| 88 |
+
|
| 89 |
+
self.sep = sep
|
| 90 |
+
self.index_label = self._initialize_index_label(index_label)
|
| 91 |
+
self.errors = errors
|
| 92 |
+
self.quoting = quoting or csvlib.QUOTE_MINIMAL
|
| 93 |
+
self.quotechar = self._initialize_quotechar(quotechar)
|
| 94 |
+
self.doublequote = doublequote
|
| 95 |
+
self.escapechar = escapechar
|
| 96 |
+
self.lineterminator = lineterminator or os.linesep
|
| 97 |
+
self.date_format = date_format
|
| 98 |
+
self.cols = self._initialize_columns(cols)
|
| 99 |
+
self.chunksize = self._initialize_chunksize(chunksize)
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def na_rep(self) -> str:
|
| 103 |
+
return self.fmt.na_rep
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def float_format(self) -> FloatFormatType | None:
|
| 107 |
+
return self.fmt.float_format
|
| 108 |
+
|
| 109 |
+
@property
|
| 110 |
+
def decimal(self) -> str:
|
| 111 |
+
return self.fmt.decimal
|
| 112 |
+
|
| 113 |
+
@property
|
| 114 |
+
def header(self) -> bool | SequenceNotStr[str]:
|
| 115 |
+
return self.fmt.header
|
| 116 |
+
|
| 117 |
+
@property
|
| 118 |
+
def index(self) -> bool:
|
| 119 |
+
return self.fmt.index
|
| 120 |
+
|
| 121 |
+
def _initialize_index_label(self, index_label: IndexLabel | None) -> IndexLabel:
|
| 122 |
+
if index_label is not False:
|
| 123 |
+
if index_label is None:
|
| 124 |
+
return self._get_index_label_from_obj()
|
| 125 |
+
elif not isinstance(index_label, (list, tuple, np.ndarray, ABCIndex)):
|
| 126 |
+
# given a string for a DF with Index
|
| 127 |
+
return [index_label]
|
| 128 |
+
return index_label
|
| 129 |
+
|
| 130 |
+
def _get_index_label_from_obj(self) -> Sequence[Hashable]:
|
| 131 |
+
if isinstance(self.obj.index, ABCMultiIndex):
|
| 132 |
+
return self._get_index_label_multiindex()
|
| 133 |
+
else:
|
| 134 |
+
return self._get_index_label_flat()
|
| 135 |
+
|
| 136 |
+
def _get_index_label_multiindex(self) -> Sequence[Hashable]:
|
| 137 |
+
return [name or "" for name in self.obj.index.names]
|
| 138 |
+
|
| 139 |
+
def _get_index_label_flat(self) -> Sequence[Hashable]:
|
| 140 |
+
index_label = self.obj.index.name
|
| 141 |
+
return [""] if index_label is None else [index_label]
|
| 142 |
+
|
| 143 |
+
def _initialize_quotechar(self, quotechar: str | None) -> str | None:
|
| 144 |
+
if self.quoting != csvlib.QUOTE_NONE:
|
| 145 |
+
# prevents crash in _csv
|
| 146 |
+
return quotechar
|
| 147 |
+
return None
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def has_mi_columns(self) -> bool:
|
| 151 |
+
return bool(isinstance(self.obj.columns, ABCMultiIndex))
|
| 152 |
+
|
| 153 |
+
def _initialize_columns(
|
| 154 |
+
self, cols: Iterable[Hashable] | None
|
| 155 |
+
) -> npt.NDArray[np.object_]:
|
| 156 |
+
# validate mi options
|
| 157 |
+
if self.has_mi_columns:
|
| 158 |
+
if cols is not None:
|
| 159 |
+
msg = "cannot specify cols with a MultiIndex on the columns"
|
| 160 |
+
raise TypeError(msg)
|
| 161 |
+
|
| 162 |
+
if cols is not None:
|
| 163 |
+
if isinstance(cols, ABCIndex):
|
| 164 |
+
cols = cols._get_values_for_csv(**self._number_format)
|
| 165 |
+
else:
|
| 166 |
+
cols = list(cols)
|
| 167 |
+
self.obj = self.obj.loc[:, cols]
|
| 168 |
+
|
| 169 |
+
# update columns to include possible multiplicity of dupes
|
| 170 |
+
# and make sure cols is just a list of labels
|
| 171 |
+
new_cols = self.obj.columns
|
| 172 |
+
return new_cols._get_values_for_csv(**self._number_format)
|
| 173 |
+
|
| 174 |
+
def _initialize_chunksize(self, chunksize: int | None) -> int:
|
| 175 |
+
if chunksize is None:
|
| 176 |
+
return (_DEFAULT_CHUNKSIZE_CELLS // (len(self.cols) or 1)) or 1
|
| 177 |
+
return int(chunksize)
|
| 178 |
+
|
| 179 |
+
@property
|
| 180 |
+
def _number_format(self) -> dict[str, Any]:
|
| 181 |
+
"""Dictionary used for storing number formatting settings."""
|
| 182 |
+
return {
|
| 183 |
+
"na_rep": self.na_rep,
|
| 184 |
+
"float_format": self.float_format,
|
| 185 |
+
"date_format": self.date_format,
|
| 186 |
+
"quoting": self.quoting,
|
| 187 |
+
"decimal": self.decimal,
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
@cache_readonly
|
| 191 |
+
def data_index(self) -> Index:
|
| 192 |
+
data_index = self.obj.index
|
| 193 |
+
if (
|
| 194 |
+
isinstance(data_index, (ABCDatetimeIndex, ABCPeriodIndex))
|
| 195 |
+
and self.date_format is not None
|
| 196 |
+
):
|
| 197 |
+
data_index = Index(
|
| 198 |
+
[x.strftime(self.date_format) if notna(x) else "" for x in data_index]
|
| 199 |
+
)
|
| 200 |
+
elif isinstance(data_index, ABCMultiIndex):
|
| 201 |
+
data_index = data_index.remove_unused_levels()
|
| 202 |
+
return data_index
|
| 203 |
+
|
| 204 |
+
@property
|
| 205 |
+
def nlevels(self) -> int:
|
| 206 |
+
if self.index:
|
| 207 |
+
return getattr(self.data_index, "nlevels", 1)
|
| 208 |
+
else:
|
| 209 |
+
return 0
|
| 210 |
+
|
| 211 |
+
@property
|
| 212 |
+
def _has_aliases(self) -> bool:
|
| 213 |
+
return isinstance(self.header, (tuple, list, np.ndarray, ABCIndex))
|
| 214 |
+
|
| 215 |
+
@property
|
| 216 |
+
def _need_to_save_header(self) -> bool:
|
| 217 |
+
return bool(self._has_aliases or self.header)
|
| 218 |
+
|
| 219 |
+
@property
|
| 220 |
+
def write_cols(self) -> SequenceNotStr[Hashable]:
|
| 221 |
+
if self._has_aliases:
|
| 222 |
+
assert not isinstance(self.header, bool)
|
| 223 |
+
if len(self.header) != len(self.cols):
|
| 224 |
+
raise ValueError(
|
| 225 |
+
f"Writing {len(self.cols)} cols but got {len(self.header)} aliases"
|
| 226 |
+
)
|
| 227 |
+
return self.header
|
| 228 |
+
else:
|
| 229 |
+
# self.cols is an ndarray derived from Index._get_values_for_csv,
|
| 230 |
+
# so its entries are strings, i.e. hashable
|
| 231 |
+
return cast(SequenceNotStr[Hashable], self.cols)
|
| 232 |
+
|
| 233 |
+
@property
|
| 234 |
+
def encoded_labels(self) -> list[Hashable]:
|
| 235 |
+
encoded_labels: list[Hashable] = []
|
| 236 |
+
|
| 237 |
+
if self.index and self.index_label:
|
| 238 |
+
assert isinstance(self.index_label, Sequence)
|
| 239 |
+
encoded_labels = list(self.index_label)
|
| 240 |
+
|
| 241 |
+
if not self.has_mi_columns or self._has_aliases:
|
| 242 |
+
encoded_labels += list(self.write_cols)
|
| 243 |
+
|
| 244 |
+
return encoded_labels
|
| 245 |
+
|
| 246 |
+
def save(self) -> None:
|
| 247 |
+
"""
|
| 248 |
+
Create the writer & save.
|
| 249 |
+
"""
|
| 250 |
+
# apply compression and byte/text conversion
|
| 251 |
+
with get_handle(
|
| 252 |
+
self.filepath_or_buffer,
|
| 253 |
+
self.mode,
|
| 254 |
+
encoding=self.encoding,
|
| 255 |
+
errors=self.errors,
|
| 256 |
+
compression=self.compression,
|
| 257 |
+
storage_options=self.storage_options,
|
| 258 |
+
) as handles:
|
| 259 |
+
# Note: self.encoding is irrelevant here
|
| 260 |
+
self.writer = csvlib.writer(
|
| 261 |
+
handles.handle,
|
| 262 |
+
lineterminator=self.lineterminator,
|
| 263 |
+
delimiter=self.sep,
|
| 264 |
+
quoting=self.quoting,
|
| 265 |
+
doublequote=self.doublequote,
|
| 266 |
+
escapechar=self.escapechar,
|
| 267 |
+
quotechar=self.quotechar,
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
self._save()
|
| 271 |
+
|
| 272 |
+
def _save(self) -> None:
|
| 273 |
+
if self._need_to_save_header:
|
| 274 |
+
self._save_header()
|
| 275 |
+
self._save_body()
|
| 276 |
+
|
| 277 |
+
def _save_header(self) -> None:
|
| 278 |
+
if not self.has_mi_columns or self._has_aliases:
|
| 279 |
+
self.writer.writerow(self.encoded_labels)
|
| 280 |
+
else:
|
| 281 |
+
for row in self._generate_multiindex_header_rows():
|
| 282 |
+
self.writer.writerow(row)
|
| 283 |
+
|
| 284 |
+
def _generate_multiindex_header_rows(self) -> Iterator[list[Hashable]]:
|
| 285 |
+
columns = self.obj.columns
|
| 286 |
+
for i in range(columns.nlevels):
|
| 287 |
+
# we need at least 1 index column to write our col names
|
| 288 |
+
col_line = []
|
| 289 |
+
if self.index:
|
| 290 |
+
# name is the first column
|
| 291 |
+
col_line.append(columns.names[i])
|
| 292 |
+
|
| 293 |
+
if isinstance(self.index_label, list) and len(self.index_label) > 1:
|
| 294 |
+
col_line.extend([""] * (len(self.index_label) - 1))
|
| 295 |
+
|
| 296 |
+
col_line.extend(columns._get_level_values(i))
|
| 297 |
+
yield col_line
|
| 298 |
+
|
| 299 |
+
# Write out the index line if it's not empty.
|
| 300 |
+
# Otherwise, we will print out an extraneous
|
| 301 |
+
# blank line between the mi and the data rows.
|
| 302 |
+
if self.encoded_labels and set(self.encoded_labels) != {""}:
|
| 303 |
+
yield self.encoded_labels + [""] * len(columns)
|
| 304 |
+
|
| 305 |
+
def _save_body(self) -> None:
|
| 306 |
+
nrows = len(self.data_index)
|
| 307 |
+
chunks = (nrows // self.chunksize) + 1
|
| 308 |
+
for i in range(chunks):
|
| 309 |
+
start_i = i * self.chunksize
|
| 310 |
+
end_i = min(start_i + self.chunksize, nrows)
|
| 311 |
+
if start_i >= end_i:
|
| 312 |
+
break
|
| 313 |
+
self._save_chunk(start_i, end_i)
|
| 314 |
+
|
| 315 |
+
def _save_chunk(self, start_i: int, end_i: int) -> None:
|
| 316 |
+
# create the data for a chunk
|
| 317 |
+
slicer = slice(start_i, end_i)
|
| 318 |
+
df = self.obj.iloc[slicer]
|
| 319 |
+
|
| 320 |
+
res = df._get_values_for_csv(**self._number_format)
|
| 321 |
+
data = list(res._iter_column_arrays())
|
| 322 |
+
|
| 323 |
+
ix = self.data_index[slicer]._get_values_for_csv(**self._number_format)
|
| 324 |
+
libwriters.write_csv_rows(
|
| 325 |
+
data,
|
| 326 |
+
ix,
|
| 327 |
+
self.nlevels,
|
| 328 |
+
self.cols,
|
| 329 |
+
self.writer,
|
| 330 |
+
)
|
shared/package-files/24/2402e13bbbee2f27a17427b979c3c06e2fd7f9678f880ab3a18525deefe6aca5/quantization.h
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <c10/macros/Export.h>
|
| 4 |
+
#include <string>
|
| 5 |
+
|
| 6 |
+
namespace torch {
|
| 7 |
+
namespace jit {
|
| 8 |
+
namespace mobile {
|
| 9 |
+
class Module;
|
| 10 |
+
namespace quantization {
|
| 11 |
+
/*
|
| 12 |
+
* Device side PTQ API.
|
| 13 |
+
* Once the model has been prepared for quantization on server side, such model
|
| 14 |
+
* is sent to device. On device side the model is further trained. At the end of
|
| 15 |
+
* the training, before the model is readied for inference, we need to quantize
|
| 16 |
+
* the model.
|
| 17 |
+
* Usage of this API is as follows.
|
| 18 |
+
* PTQQuanizationHelper ptq_helper;
|
| 19 |
+
* ptq_helper.quantize_dynamic(m, "forward");
|
| 20 |
+
* Args:
|
| 21 |
+
* m: Captured by reference, an instance of mobile::Module. This module will be
|
| 22 |
+
* mutated in place to replace its <method_name> method with quantized
|
| 23 |
+
* equivalent. method:name: Name of the method to be quantized. AOT preparation
|
| 24 |
+
* for quantization must also have been done for this method. Returns: In place
|
| 25 |
+
* mutated `m` whose size should be smaller due to weight quantization and whose
|
| 26 |
+
* <method_name> method should use quantized ops
|
| 27 |
+
*/
|
| 28 |
+
class TORCH_API PTQQuanizationHelper {
|
| 29 |
+
public:
|
| 30 |
+
PTQQuanizationHelper() = default;
|
| 31 |
+
void quantize_dynamic(
|
| 32 |
+
torch::jit::mobile::Module& m,
|
| 33 |
+
const std::string& method_name);
|
| 34 |
+
};
|
| 35 |
+
} // namespace quantization
|
| 36 |
+
} // namespace mobile
|
| 37 |
+
} // namespace jit
|
| 38 |
+
} // namespace torch
|
shared/package-files/24/2403a7a3ddf4893c9f6482cc7f5d6f5ad89a4e0ac970fa4fe8545346110c303e/pbkdi8a.afm
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
StartFontMetrics 2.0
|
| 2 |
+
Comment Copyright (c) 1985, 1987, 1989, 1992 Adobe Systems Incorporated. All Rights Reserved.
|
| 3 |
+
Comment Creation Date: Tue Jan 21 16:12:43 1992
|
| 4 |
+
Comment UniqueID 37832
|
| 5 |
+
Comment VMusage 32139 39031
|
| 6 |
+
FontName Bookman-DemiItalic
|
| 7 |
+
FullName ITC Bookman Demi Italic
|
| 8 |
+
FamilyName ITC Bookman
|
| 9 |
+
Weight Demi
|
| 10 |
+
ItalicAngle -10
|
| 11 |
+
IsFixedPitch false
|
| 12 |
+
FontBBox -231 -250 1333 941
|
| 13 |
+
UnderlinePosition -100
|
| 14 |
+
UnderlineThickness 50
|
| 15 |
+
Version 001.004
|
| 16 |
+
Notice Copyright (c) 1985, 1987, 1989, 1992 Adobe Systems Incorporated. All Rights Reserved.ITC Bookman is a registered trademark of International Typeface Corporation.
|
| 17 |
+
EncodingScheme AdobeStandardEncoding
|
| 18 |
+
CapHeight 681
|
| 19 |
+
XHeight 515
|
| 20 |
+
Ascender 732
|
| 21 |
+
Descender -213
|
| 22 |
+
StartCharMetrics 228
|
| 23 |
+
C 32 ; WX 340 ; N space ; B 0 0 0 0 ;
|
| 24 |
+
C 33 ; WX 320 ; N exclam ; B 86 -8 366 698 ;
|
| 25 |
+
C 34 ; WX 380 ; N quotedbl ; B 140 371 507 697 ;
|
| 26 |
+
C 35 ; WX 680 ; N numbersign ; B 157 0 649 681 ;
|
| 27 |
+
C 36 ; WX 680 ; N dollar ; B 45 -164 697 790 ;
|
| 28 |
+
C 37 ; WX 880 ; N percent ; B 106 -17 899 698 ;
|
| 29 |
+
C 38 ; WX 980 ; N ampersand ; B 48 -17 1016 698 ;
|
| 30 |
+
C 39 ; WX 320 ; N quoteright ; B 171 420 349 698 ;
|
| 31 |
+
C 40 ; WX 260 ; N parenleft ; B 31 -134 388 741 ;
|
| 32 |
+
C 41 ; WX 260 ; N parenright ; B -35 -134 322 741 ;
|
| 33 |
+
C 42 ; WX 460 ; N asterisk ; B 126 346 508 698 ;
|
| 34 |
+
C 43 ; WX 600 ; N plus ; B 91 9 595 514 ;
|
| 35 |
+
C 44 ; WX 340 ; N comma ; B 100 -124 298 185 ;
|
| 36 |
+
C 45 ; WX 280 ; N hyphen ; B 59 218 319 313 ;
|
| 37 |
+
C 46 ; WX 340 ; N period ; B 106 -8 296 177 ;
|
| 38 |
+
C 47 ; WX 360 ; N slash ; B 9 -106 502 742 ;
|
| 39 |
+
C 48 ; WX 680 ; N zero ; B 87 -17 703 698 ;
|
| 40 |
+
C 49 ; WX 680 ; N one ; B 123 0 565 681 ;
|
| 41 |
+
C 50 ; WX 680 ; N two ; B 67 0 674 698 ;
|
| 42 |
+
C 51 ; WX 680 ; N three ; B 72 -17 683 698 ;
|
| 43 |
+
C 52 ; WX 680 ; N four ; B 63 0 708 681 ;
|
| 44 |
+
C 53 ; WX 680 ; N five ; B 78 -17 669 681 ;
|
| 45 |
+
C 54 ; WX 680 ; N six ; B 88 -17 704 698 ;
|
| 46 |
+
C 55 ; WX 680 ; N seven ; B 123 0 739 681 ;
|
| 47 |
+
C 56 ; WX 680 ; N eight ; B 68 -17 686 698 ;
|
| 48 |
+
C 57 ; WX 680 ; N nine ; B 71 -17 712 698 ;
|
| 49 |
+
C 58 ; WX 340 ; N colon ; B 106 -8 356 515 ;
|
| 50 |
+
C 59 ; WX 340 ; N semicolon ; B 100 -124 352 515 ;
|
| 51 |
+
C 60 ; WX 620 ; N less ; B 79 -9 588 540 ;
|
| 52 |
+
C 61 ; WX 600 ; N equal ; B 91 109 595 421 ;
|
| 53 |
+
C 62 ; WX 620 ; N greater ; B 89 -9 598 540 ;
|
| 54 |
+
C 63 ; WX 620 ; N question ; B 145 -8 668 698 ;
|
| 55 |
+
C 64 ; WX 780 ; N at ; B 80 -17 790 698 ;
|
| 56 |
+
C 65 ; WX 720 ; N A ; B -27 0 769 681 ;
|
| 57 |
+
C 66 ; WX 720 ; N B ; B 14 0 762 681 ;
|
| 58 |
+
C 67 ; WX 700 ; N C ; B 78 -17 754 698 ;
|
| 59 |
+
C 68 ; WX 760 ; N D ; B 14 0 805 681 ;
|
| 60 |
+
C 69 ; WX 720 ; N E ; B 14 0 777 681 ;
|
| 61 |
+
C 70 ; WX 660 ; N F ; B 14 0 763 681 ;
|
| 62 |
+
C 71 ; WX 760 ; N G ; B 77 -17 828 698 ;
|
| 63 |
+
C 72 ; WX 800 ; N H ; B 14 0 910 681 ;
|
| 64 |
+
C 73 ; WX 380 ; N I ; B 14 0 485 681 ;
|
| 65 |
+
C 74 ; WX 620 ; N J ; B 8 -17 721 681 ;
|
| 66 |
+
C 75 ; WX 780 ; N K ; B 14 0 879 681 ;
|
| 67 |
+
C 76 ; WX 640 ; N L ; B 14 0 725 681 ;
|
| 68 |
+
C 77 ; WX 860 ; N M ; B 14 0 970 681 ;
|
| 69 |
+
C 78 ; WX 740 ; N N ; B 14 0 845 681 ;
|
| 70 |
+
C 79 ; WX 760 ; N O ; B 78 -17 806 698 ;
|
| 71 |
+
C 80 ; WX 640 ; N P ; B -6 0 724 681 ;
|
| 72 |
+
C 81 ; WX 760 ; N Q ; B 37 -213 805 698 ;
|
| 73 |
+
C 82 ; WX 740 ; N R ; B 14 0 765 681 ;
|
| 74 |
+
C 83 ; WX 700 ; N S ; B 59 -17 731 698 ;
|
| 75 |
+
C 84 ; WX 700 ; N T ; B 70 0 802 681 ;
|
| 76 |
+
C 85 ; WX 740 ; N U ; B 112 -17 855 681 ;
|
| 77 |
+
C 86 ; WX 660 ; N V ; B 72 0 819 681 ;
|
| 78 |
+
C 87 ; WX 1000 ; N W ; B 72 0 1090 681 ;
|
| 79 |
+
C 88 ; WX 740 ; N X ; B -7 0 835 681 ;
|
| 80 |
+
C 89 ; WX 660 ; N Y ; B 72 0 817 681 ;
|
| 81 |
+
C 90 ; WX 680 ; N Z ; B 23 0 740 681 ;
|
| 82 |
+
C 91 ; WX 260 ; N bracketleft ; B 9 -118 374 741 ;
|
| 83 |
+
C 92 ; WX 580 ; N backslash ; B 73 0 575 741 ;
|
| 84 |
+
C 93 ; WX 260 ; N bracketright ; B -18 -118 347 741 ;
|
| 85 |
+
C 94 ; WX 620 ; N asciicircum ; B 92 281 594 681 ;
|
| 86 |
+
C 95 ; WX 500 ; N underscore ; B 0 -125 500 -75 ;
|
| 87 |
+
C 96 ; WX 320 ; N quoteleft ; B 155 420 333 698 ;
|
| 88 |
+
C 97 ; WX 680 ; N a ; B 84 -8 735 515 ;
|
| 89 |
+
C 98 ; WX 600 ; N b ; B 57 -8 633 732 ;
|
| 90 |
+
C 99 ; WX 560 ; N c ; B 58 -8 597 515 ;
|
| 91 |
+
C 100 ; WX 680 ; N d ; B 60 -8 714 732 ;
|
| 92 |
+
C 101 ; WX 560 ; N e ; B 59 -8 596 515 ;
|
| 93 |
+
C 102 ; WX 420 ; N f ; B -192 -213 641 741 ; L i fi ; L l fl ;
|
| 94 |
+
C 103 ; WX 620 ; N g ; B 21 -213 669 515 ;
|
| 95 |
+
C 104 ; WX 700 ; N h ; B 93 -8 736 732 ;
|
| 96 |
+
C 105 ; WX 380 ; N i ; B 83 -8 420 755 ;
|
| 97 |
+
C 106 ; WX 320 ; N j ; B -160 -213 392 755 ;
|
| 98 |
+
C 107 ; WX 700 ; N k ; B 97 -8 732 732 ;
|
| 99 |
+
C 108 ; WX 380 ; N l ; B 109 -8 410 732 ;
|
| 100 |
+
C 109 ; WX 960 ; N m ; B 83 -8 996 515 ;
|
| 101 |
+
C 110 ; WX 680 ; N n ; B 83 -8 715 515 ;
|
| 102 |
+
C 111 ; WX 600 ; N o ; B 59 -8 627 515 ;
|
| 103 |
+
C 112 ; WX 660 ; N p ; B -24 -213 682 515 ;
|
| 104 |
+
C 113 ; WX 620 ; N q ; B 60 -213 640 515 ;
|
| 105 |
+
C 114 ; WX 500 ; N r ; B 84 0 582 515 ;
|
| 106 |
+
C 115 ; WX 540 ; N s ; B 32 -8 573 515 ;
|
| 107 |
+
C 116 ; WX 440 ; N t ; B 106 -8 488 658 ;
|
| 108 |
+
C 117 ; WX 680 ; N u ; B 83 -8 720 507 ;
|
| 109 |
+
C 118 ; WX 540 ; N v ; B 56 -8 572 515 ;
|
| 110 |
+
C 119 ; WX 860 ; N w ; B 56 -8 891 515 ;
|
| 111 |
+
C 120 ; WX 620 ; N x ; B 10 -8 654 515 ;
|
| 112 |
+
C 121 ; WX 600 ; N y ; B 25 -213 642 507 ;
|
| 113 |
+
C 122 ; WX 560 ; N z ; B 36 -8 586 515 ;
|
| 114 |
+
C 123 ; WX 300 ; N braceleft ; B 49 -123 413 742 ;
|
| 115 |
+
C 124 ; WX 620 ; N bar ; B 303 -250 422 750 ;
|
| 116 |
+
C 125 ; WX 300 ; N braceright ; B -8 -114 356 751 ;
|
| 117 |
+
C 126 ; WX 620 ; N asciitilde ; B 101 162 605 368 ;
|
| 118 |
+
C 161 ; WX 320 ; N exclamdown ; B 64 -191 344 515 ;
|
| 119 |
+
C 162 ; WX 680 ; N cent ; B 161 25 616 718 ;
|
| 120 |
+
C 163 ; WX 680 ; N sterling ; B 0 -17 787 698 ;
|
| 121 |
+
C 164 ; WX 120 ; N fraction ; B -144 0 382 681 ;
|
| 122 |
+
C 165 ; WX 680 ; N yen ; B 92 0 782 681 ;
|
| 123 |
+
C 166 ; WX 680 ; N florin ; B -28 -199 743 741 ;
|
| 124 |
+
C 167 ; WX 620 ; N section ; B 46 -137 638 698 ;
|
| 125 |
+
C 168 ; WX 680 ; N currency ; B 148 85 637 571 ;
|
| 126 |
+
C 169 ; WX 180 ; N quotesingle ; B 126 370 295 696 ;
|
| 127 |
+
C 170 ; WX 520 ; N quotedblleft ; B 156 420 545 698 ;
|
| 128 |
+
C 171 ; WX 380 ; N guillemotleft ; B 62 84 406 503 ;
|
| 129 |
+
C 172 ; WX 220 ; N guilsinglleft ; B 62 84 249 503 ;
|
| 130 |
+
C 173 ; WX 220 ; N guilsinglright ; B 62 84 249 503 ;
|
| 131 |
+
C 174 ; WX 820 ; N fi ; B -191 -213 850 741 ;
|
| 132 |
+
C 175 ; WX 820 ; N fl ; B -191 -213 850 741 ;
|
| 133 |
+
C 177 ; WX 500 ; N endash ; B 40 219 573 311 ;
|
| 134 |
+
C 178 ; WX 420 ; N dagger ; B 89 -137 466 698 ;
|
| 135 |
+
C 179 ; WX 420 ; N daggerdbl ; B 79 -137 486 698 ;
|
| 136 |
+
C 180 ; WX 340 ; N periodcentered ; B 126 173 316 358 ;
|
| 137 |
+
C 182 ; WX 680 ; N paragraph ; B 137 0 715 681 ;
|
| 138 |
+
C 183 ; WX 360 ; N bullet ; B 60 170 404 511 ;
|
| 139 |
+
C 184 ; WX 300 ; N quotesinglbase ; B 106 -112 284 166 ;
|
| 140 |
+
C 185 ; WX 520 ; N quotedblbase ; B 106 -112 495 166 ;
|
| 141 |
+
C 186 ; WX 520 ; N quotedblright ; B 171 420 560 698 ;
|
| 142 |
+
C 187 ; WX 380 ; N guillemotright ; B 62 84 406 503 ;
|
| 143 |
+
C 188 ; WX 1000 ; N ellipsis ; B 86 -8 942 177 ;
|
| 144 |
+
C 189 ; WX 1360 ; N perthousand ; B 106 -17 1333 698 ;
|
| 145 |
+
C 191 ; WX 620 ; N questiondown ; B 83 -189 606 515 ;
|
| 146 |
+
C 193 ; WX 380 ; N grave ; B 193 566 424 771 ;
|
| 147 |
+
C 194 ; WX 340 ; N acute ; B 176 566 407 771 ;
|
| 148 |
+
C 195 ; WX 480 ; N circumflex ; B 183 582 523 749 ;
|
| 149 |
+
C 196 ; WX 480 ; N tilde ; B 178 587 533 709 ;
|
| 150 |
+
C 197 ; WX 480 ; N macron ; B 177 603 531 691 ;
|
| 151 |
+
C 198 ; WX 460 ; N breve ; B 177 577 516 707 ;
|
| 152 |
+
C 199 ; WX 380 ; N dotaccent ; B 180 570 345 734 ;
|
| 153 |
+
C 200 ; WX 520 ; N dieresis ; B 180 570 569 734 ;
|
| 154 |
+
C 202 ; WX 360 ; N ring ; B 185 558 406 775 ;
|
| 155 |
+
C 203 ; WX 360 ; N cedilla ; B 68 -220 289 -8 ;
|
| 156 |
+
C 205 ; WX 560 ; N hungarumlaut ; B 181 560 616 775 ;
|
| 157 |
+
C 206 ; WX 320 ; N ogonek ; B 68 -182 253 0 ;
|
| 158 |
+
C 207 ; WX 480 ; N caron ; B 183 582 523 749 ;
|
| 159 |
+
C 208 ; WX 1000 ; N emdash ; B 40 219 1073 311 ;
|
| 160 |
+
C 225 ; WX 1140 ; N AE ; B -27 0 1207 681 ;
|
| 161 |
+
C 227 ; WX 440 ; N ordfeminine ; B 118 400 495 685 ;
|
| 162 |
+
C 232 ; WX 640 ; N Lslash ; B 14 0 724 681 ;
|
| 163 |
+
C 233 ; WX 760 ; N Oslash ; B 21 -29 847 725 ;
|
| 164 |
+
C 234 ; WX 1180 ; N OE ; B 94 -17 1245 698 ;
|
| 165 |
+
C 235 ; WX 440 ; N ordmasculine ; B 127 400 455 685 ;
|
| 166 |
+
C 241 ; WX 880 ; N ae ; B 39 -8 913 515 ;
|
| 167 |
+
C 245 ; WX 380 ; N dotlessi ; B 83 -8 420 507 ;
|
| 168 |
+
C 248 ; WX 380 ; N lslash ; B 63 -8 412 732 ;
|
| 169 |
+
C 249 ; WX 600 ; N oslash ; B 17 -54 661 571 ;
|
| 170 |
+
C 250 ; WX 920 ; N oe ; B 48 -8 961 515 ;
|
| 171 |
+
C 251 ; WX 660 ; N germandbls ; B -231 -213 702 741 ;
|
| 172 |
+
C -1 ; WX 560 ; N ecircumflex ; B 59 -8 596 749 ;
|
| 173 |
+
C -1 ; WX 560 ; N edieresis ; B 59 -8 596 734 ;
|
| 174 |
+
C -1 ; WX 680 ; N aacute ; B 84 -8 735 771 ;
|
| 175 |
+
C -1 ; WX 780 ; N registered ; B 83 -17 783 698 ;
|
| 176 |
+
C -1 ; WX 380 ; N icircumflex ; B 83 -8 433 749 ;
|
| 177 |
+
C -1 ; WX 680 ; N udieresis ; B 83 -8 720 734 ;
|
| 178 |
+
C -1 ; WX 600 ; N ograve ; B 59 -8 627 771 ;
|
| 179 |
+
C -1 ; WX 680 ; N uacute ; B 83 -8 720 771 ;
|
| 180 |
+
C -1 ; WX 680 ; N ucircumflex ; B 83 -8 720 749 ;
|
| 181 |
+
C -1 ; WX 720 ; N Aacute ; B -27 0 769 937 ;
|
| 182 |
+
C -1 ; WX 380 ; N igrave ; B 83 -8 424 771 ;
|
| 183 |
+
C -1 ; WX 380 ; N Icircumflex ; B 14 0 493 915 ;
|
| 184 |
+
C -1 ; WX 560 ; N ccedilla ; B 58 -220 597 515 ;
|
| 185 |
+
C -1 ; WX 680 ; N adieresis ; B 84 -8 735 734 ;
|
| 186 |
+
C -1 ; WX 720 ; N Ecircumflex ; B 14 0 777 915 ;
|
| 187 |
+
C -1 ; WX 540 ; N scaron ; B 32 -8 573 749 ;
|
| 188 |
+
C -1 ; WX 660 ; N thorn ; B -24 -213 682 732 ;
|
| 189 |
+
C -1 ; WX 940 ; N trademark ; B 42 277 982 681 ;
|
| 190 |
+
C -1 ; WX 560 ; N egrave ; B 59 -8 596 771 ;
|
| 191 |
+
C -1 ; WX 408 ; N threesuperior ; B 86 269 483 698 ;
|
| 192 |
+
C -1 ; WX 560 ; N zcaron ; B 36 -8 586 749 ;
|
| 193 |
+
C -1 ; WX 680 ; N atilde ; B 84 -8 735 709 ;
|
| 194 |
+
C -1 ; WX 680 ; N aring ; B 84 -8 735 775 ;
|
| 195 |
+
C -1 ; WX 600 ; N ocircumflex ; B 59 -8 627 749 ;
|
| 196 |
+
C -1 ; WX 720 ; N Edieresis ; B 14 0 777 900 ;
|
| 197 |
+
C -1 ; WX 1020 ; N threequarters ; B 86 0 1054 691 ;
|
| 198 |
+
C -1 ; WX 600 ; N ydieresis ; B 25 -213 642 734 ;
|
| 199 |
+
C -1 ; WX 600 ; N yacute ; B 25 -213 642 771 ;
|
| 200 |
+
C -1 ; WX 380 ; N iacute ; B 83 -8 420 771 ;
|
| 201 |
+
C -1 ; WX 720 ; N Acircumflex ; B -27 0 769 915 ;
|
| 202 |
+
C -1 ; WX 740 ; N Uacute ; B 112 -17 855 937 ;
|
| 203 |
+
C -1 ; WX 560 ; N eacute ; B 59 -8 596 771 ;
|
| 204 |
+
C -1 ; WX 760 ; N Ograve ; B 78 -17 806 937 ;
|
| 205 |
+
C -1 ; WX 680 ; N agrave ; B 84 -8 735 771 ;
|
| 206 |
+
C -1 ; WX 740 ; N Udieresis ; B 112 -17 855 900 ;
|
| 207 |
+
C -1 ; WX 680 ; N acircumflex ; B 84 -8 735 749 ;
|
| 208 |
+
C -1 ; WX 380 ; N Igrave ; B 14 0 485 937 ;
|
| 209 |
+
C -1 ; WX 408 ; N twosuperior ; B 91 279 485 698 ;
|
| 210 |
+
C -1 ; WX 740 ; N Ugrave ; B 112 -17 855 937 ;
|
| 211 |
+
C -1 ; WX 1020 ; N onequarter ; B 118 0 1054 681 ;
|
| 212 |
+
C -1 ; WX 740 ; N Ucircumflex ; B 112 -17 855 915 ;
|
| 213 |
+
C -1 ; WX 700 ; N Scaron ; B 59 -17 731 915 ;
|
| 214 |
+
C -1 ; WX 380 ; N Idieresis ; B 14 0 499 900 ;
|
| 215 |
+
C -1 ; WX 380 ; N idieresis ; B 83 -8 479 734 ;
|
| 216 |
+
C -1 ; WX 720 ; N Egrave ; B 14 0 777 937 ;
|
| 217 |
+
C -1 ; WX 760 ; N Oacute ; B 78 -17 806 937 ;
|
| 218 |
+
C -1 ; WX 600 ; N divide ; B 91 9 595 521 ;
|
| 219 |
+
C -1 ; WX 720 ; N Atilde ; B -27 0 769 875 ;
|
| 220 |
+
C -1 ; WX 720 ; N Aring ; B -27 0 769 941 ;
|
| 221 |
+
C -1 ; WX 760 ; N Odieresis ; B 78 -17 806 900 ;
|
| 222 |
+
C -1 ; WX 720 ; N Adieresis ; B -27 0 769 900 ;
|
| 223 |
+
C -1 ; WX 740 ; N Ntilde ; B 14 0 845 875 ;
|
| 224 |
+
C -1 ; WX 680 ; N Zcaron ; B 23 0 740 915 ;
|
| 225 |
+
C -1 ; WX 640 ; N Thorn ; B -6 0 701 681 ;
|
| 226 |
+
C -1 ; WX 380 ; N Iacute ; B 14 0 485 937 ;
|
| 227 |
+
C -1 ; WX 600 ; N plusminus ; B 91 0 595 514 ;
|
| 228 |
+
C -1 ; WX 600 ; N multiply ; B 91 10 595 514 ;
|
| 229 |
+
C -1 ; WX 720 ; N Eacute ; B 14 0 777 937 ;
|
| 230 |
+
C -1 ; WX 660 ; N Ydieresis ; B 72 0 817 900 ;
|
| 231 |
+
C -1 ; WX 408 ; N onesuperior ; B 118 279 406 688 ;
|
| 232 |
+
C -1 ; WX 680 ; N ugrave ; B 83 -8 720 771 ;
|
| 233 |
+
C -1 ; WX 620 ; N logicalnot ; B 81 129 585 421 ;
|
| 234 |
+
C -1 ; WX 680 ; N ntilde ; B 83 -8 715 709 ;
|
| 235 |
+
C -1 ; WX 760 ; N Otilde ; B 78 -17 806 875 ;
|
| 236 |
+
C -1 ; WX 600 ; N otilde ; B 59 -8 627 709 ;
|
| 237 |
+
C -1 ; WX 700 ; N Ccedilla ; B 78 -220 754 698 ;
|
| 238 |
+
C -1 ; WX 720 ; N Agrave ; B -27 0 769 937 ;
|
| 239 |
+
C -1 ; WX 1020 ; N onehalf ; B 118 0 1036 681 ;
|
| 240 |
+
C -1 ; WX 760 ; N Eth ; B 14 0 805 681 ;
|
| 241 |
+
C -1 ; WX 400 ; N degree ; B 130 398 430 698 ;
|
| 242 |
+
C -1 ; WX 660 ; N Yacute ; B 72 0 817 937 ;
|
| 243 |
+
C -1 ; WX 760 ; N Ocircumflex ; B 78 -17 806 915 ;
|
| 244 |
+
C -1 ; WX 600 ; N oacute ; B 59 -8 627 771 ;
|
| 245 |
+
C -1 ; WX 680 ; N mu ; B 54 -213 720 507 ;
|
| 246 |
+
C -1 ; WX 600 ; N minus ; B 91 207 595 323 ;
|
| 247 |
+
C -1 ; WX 600 ; N eth ; B 59 -8 662 741 ;
|
| 248 |
+
C -1 ; WX 600 ; N odieresis ; B 59 -8 627 734 ;
|
| 249 |
+
C -1 ; WX 780 ; N copyright ; B 83 -17 783 698 ;
|
| 250 |
+
C -1 ; WX 620 ; N brokenbar ; B 303 -175 422 675 ;
|
| 251 |
+
EndCharMetrics
|
| 252 |
+
StartKernData
|
| 253 |
+
StartKernPairs 92
|
| 254 |
+
|
| 255 |
+
KPX A y 20
|
| 256 |
+
KPX A w 20
|
| 257 |
+
KPX A v 20
|
| 258 |
+
KPX A Y -25
|
| 259 |
+
KPX A W -35
|
| 260 |
+
KPX A V -40
|
| 261 |
+
KPX A T -17
|
| 262 |
+
|
| 263 |
+
KPX F period -105
|
| 264 |
+
KPX F comma -98
|
| 265 |
+
KPX F A -35
|
| 266 |
+
|
| 267 |
+
KPX L y 62
|
| 268 |
+
KPX L Y -5
|
| 269 |
+
KPX L W -15
|
| 270 |
+
KPX L V -19
|
| 271 |
+
KPX L T -26
|
| 272 |
+
|
| 273 |
+
KPX P period -105
|
| 274 |
+
KPX P comma -98
|
| 275 |
+
KPX P A -31
|
| 276 |
+
|
| 277 |
+
KPX R y 27
|
| 278 |
+
KPX R Y 4
|
| 279 |
+
KPX R W -4
|
| 280 |
+
KPX R V -8
|
| 281 |
+
KPX R T -3
|
| 282 |
+
|
| 283 |
+
KPX T y 56
|
| 284 |
+
KPX T w 69
|
| 285 |
+
KPX T u 42
|
| 286 |
+
KPX T semicolon 31
|
| 287 |
+
KPX T s -1
|
| 288 |
+
KPX T r 41
|
| 289 |
+
KPX T period -107
|
| 290 |
+
KPX T o -5
|
| 291 |
+
KPX T i 42
|
| 292 |
+
KPX T hyphen -20
|
| 293 |
+
KPX T e -10
|
| 294 |
+
KPX T comma -100
|
| 295 |
+
KPX T colon 26
|
| 296 |
+
KPX T c -8
|
| 297 |
+
KPX T a -8
|
| 298 |
+
KPX T A -42
|
| 299 |
+
|
| 300 |
+
KPX V y 17
|
| 301 |
+
KPX V u -1
|
| 302 |
+
KPX V semicolon -22
|
| 303 |
+
KPX V r 2
|
| 304 |
+
KPX V period -115
|
| 305 |
+
KPX V o -50
|
| 306 |
+
KPX V i 32
|
| 307 |
+
KPX V hyphen -20
|
| 308 |
+
KPX V e -50
|
| 309 |
+
KPX V comma -137
|
| 310 |
+
KPX V colon -28
|
| 311 |
+
KPX V a -50
|
| 312 |
+
KPX V A -50
|
| 313 |
+
|
| 314 |
+
KPX W y -51
|
| 315 |
+
KPX W u -69
|
| 316 |
+
KPX W semicolon -81
|
| 317 |
+
KPX W r -66
|
| 318 |
+
KPX W period -183
|
| 319 |
+
KPX W o -100
|
| 320 |
+
KPX W i -36
|
| 321 |
+
KPX W hyphen -22
|
| 322 |
+
KPX W e -100
|
| 323 |
+
KPX W comma -201
|
| 324 |
+
KPX W colon -86
|
| 325 |
+
KPX W a -100
|
| 326 |
+
KPX W A -77
|
| 327 |
+
|
| 328 |
+
KPX Y v 26
|
| 329 |
+
KPX Y u -1
|
| 330 |
+
KPX Y semicolon -4
|
| 331 |
+
KPX Y q -43
|
| 332 |
+
KPX Y period -113
|
| 333 |
+
KPX Y o -41
|
| 334 |
+
KPX Y i 20
|
| 335 |
+
KPX Y hyphen -20
|
| 336 |
+
KPX Y e -46
|
| 337 |
+
KPX Y comma -106
|
| 338 |
+
KPX Y colon -9
|
| 339 |
+
KPX Y a -45
|
| 340 |
+
KPX Y A -30
|
| 341 |
+
|
| 342 |
+
KPX f f 10
|
| 343 |
+
|
| 344 |
+
KPX r q -3
|
| 345 |
+
KPX r period -120
|
| 346 |
+
KPX r o -1
|
| 347 |
+
KPX r n 39
|
| 348 |
+
KPX r m 39
|
| 349 |
+
KPX r hyphen -20
|
| 350 |
+
KPX r h -35
|
| 351 |
+
KPX r g -23
|
| 352 |
+
KPX r f 42
|
| 353 |
+
KPX r e -6
|
| 354 |
+
KPX r d -3
|
| 355 |
+
KPX r comma -113
|
| 356 |
+
KPX r c -5
|
| 357 |
+
EndKernPairs
|
| 358 |
+
EndKernData
|
| 359 |
+
StartComposites 56
|
| 360 |
+
CC Aacute 2 ; PCC A 0 0 ; PCC acute 190 166 ;
|
| 361 |
+
CC Acircumflex 2 ; PCC A 0 0 ; PCC circumflex 120 166 ;
|
| 362 |
+
CC Adieresis 2 ; PCC A 0 0 ; PCC dieresis 100 166 ;
|
| 363 |
+
CC Agrave 2 ; PCC A 0 0 ; PCC grave 170 166 ;
|
| 364 |
+
CC Aring 2 ; PCC A 0 0 ; PCC ring 200 166 ;
|
| 365 |
+
CC Atilde 2 ; PCC A 0 0 ; PCC tilde 120 166 ;
|
| 366 |
+
CC Eacute 2 ; PCC E 0 0 ; PCC acute 190 166 ;
|
| 367 |
+
CC Ecircumflex 2 ; PCC E 0 0 ; PCC circumflex 120 166 ;
|
| 368 |
+
CC Edieresis 2 ; PCC E 0 0 ; PCC dieresis 100 166 ;
|
| 369 |
+
CC Egrave 2 ; PCC E 0 0 ; PCC grave 170 166 ;
|
| 370 |
+
CC Iacute 2 ; PCC I 0 0 ; PCC acute 20 166 ;
|
| 371 |
+
CC Icircumflex 2 ; PCC I 0 0 ; PCC circumflex -30 166 ;
|
| 372 |
+
CC Idieresis 2 ; PCC I 0 0 ; PCC dieresis -70 166 ;
|
| 373 |
+
CC Igrave 2 ; PCC I 0 0 ; PCC grave 0 166 ;
|
| 374 |
+
CC Ntilde 2 ; PCC N 0 0 ; PCC tilde 130 166 ;
|
| 375 |
+
CC Oacute 2 ; PCC O 0 0 ; PCC acute 210 166 ;
|
| 376 |
+
CC Ocircumflex 2 ; PCC O 0 0 ; PCC circumflex 140 166 ;
|
| 377 |
+
CC Odieresis 2 ; PCC O 0 0 ; PCC dieresis 140 166 ;
|
| 378 |
+
CC Ograve 2 ; PCC O 0 0 ; PCC grave 190 166 ;
|
| 379 |
+
CC Otilde 2 ; PCC O 0 0 ; PCC tilde 140 166 ;
|
| 380 |
+
CC Scaron 2 ; PCC S 0 0 ; PCC caron 110 166 ;
|
| 381 |
+
CC Uacute 2 ; PCC U 0 0 ; PCC acute 200 166 ;
|
| 382 |
+
CC Ucircumflex 2 ; PCC U 0 0 ; PCC circumflex 130 166 ;
|
| 383 |
+
CC Udieresis 2 ; PCC U 0 0 ; PCC dieresis 130 166 ;
|
| 384 |
+
CC Ugrave 2 ; PCC U 0 0 ; PCC grave 180 166 ;
|
| 385 |
+
CC Yacute 2 ; PCC Y 0 0 ; PCC acute 160 166 ;
|
| 386 |
+
CC Ydieresis 2 ; PCC Y 0 0 ; PCC dieresis 70 166 ;
|
| 387 |
+
CC Zcaron 2 ; PCC Z 0 0 ; PCC caron 100 166 ;
|
| 388 |
+
CC aacute 2 ; PCC a 0 0 ; PCC acute 170 0 ;
|
| 389 |
+
CC acircumflex 2 ; PCC a 0 0 ; PCC circumflex 100 0 ;
|
| 390 |
+
CC adieresis 2 ; PCC a 0 0 ; PCC dieresis 80 0 ;
|
| 391 |
+
CC agrave 2 ; PCC a 0 0 ; PCC grave 150 0 ;
|
| 392 |
+
CC aring 2 ; PCC a 0 0 ; PCC ring 160 0 ;
|
| 393 |
+
CC atilde 2 ; PCC a 0 0 ; PCC tilde 100 0 ;
|
| 394 |
+
CC eacute 2 ; PCC e 0 0 ; PCC acute 110 0 ;
|
| 395 |
+
CC ecircumflex 2 ; PCC e 0 0 ; PCC circumflex 60 0 ;
|
| 396 |
+
CC edieresis 2 ; PCC e 0 0 ; PCC dieresis 20 0 ;
|
| 397 |
+
CC egrave 2 ; PCC e 0 0 ; PCC grave 90 0 ;
|
| 398 |
+
CC iacute 2 ; PCC dotlessi 0 0 ; PCC acute 0 0 ;
|
| 399 |
+
CC icircumflex 2 ; PCC dotlessi 0 0 ; PCC circumflex -90 0 ;
|
| 400 |
+
CC idieresis 2 ; PCC dotlessi 0 0 ; PCC dieresis -90 0 ;
|
| 401 |
+
CC igrave 2 ; PCC dotlessi 0 0 ; PCC grave 0 0 ;
|
| 402 |
+
CC ntilde 2 ; PCC n 0 0 ; PCC tilde 60 0 ;
|
| 403 |
+
CC oacute 2 ; PCC o 0 0 ; PCC acute 130 0 ;
|
| 404 |
+
CC ocircumflex 2 ; PCC o 0 0 ; PCC circumflex 60 0 ;
|
| 405 |
+
CC odieresis 2 ; PCC o 0 0 ; PCC dieresis 40 0 ;
|
| 406 |
+
CC ograve 2 ; PCC o 0 0 ; PCC grave 110 0 ;
|
| 407 |
+
CC otilde 2 ; PCC o 0 0 ; PCC tilde 60 0 ;
|
| 408 |
+
CC scaron 2 ; PCC s 0 0 ; PCC caron 30 0 ;
|
| 409 |
+
CC uacute 2 ; PCC u 0 0 ; PCC acute 170 0 ;
|
| 410 |
+
CC ucircumflex 2 ; PCC u 0 0 ; PCC circumflex 100 0 ;
|
| 411 |
+
CC udieresis 2 ; PCC u 0 0 ; PCC dieresis 80 0 ;
|
| 412 |
+
CC ugrave 2 ; PCC u 0 0 ; PCC grave 150 0 ;
|
| 413 |
+
CC yacute 2 ; PCC y 0 0 ; PCC acute 130 0 ;
|
| 414 |
+
CC ydieresis 2 ; PCC y 0 0 ; PCC dieresis 40 0 ;
|
| 415 |
+
CC zcaron 2 ; PCC z 0 0 ; PCC caron 40 0 ;
|
| 416 |
+
EndComposites
|
| 417 |
+
EndFontMetrics
|
shared/package-files/24/240417d84507c25a4a09f2431aca5a95d9ac2116c7c675e9b0d52bbd1ae72041/test_transpose.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from numba import cuda
|
| 3 |
+
from numba.cuda.kernels.transpose import transpose
|
| 4 |
+
from numba.cuda.testing import unittest
|
| 5 |
+
from numba.cuda.testing import skip_on_cudasim, CUDATestCase
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
recordwith2darray = np.dtype([('i', np.int32),
|
| 9 |
+
('j', np.float32, (3, 2))])
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@skip_on_cudasim('Device Array API unsupported in the simulator')
|
| 13 |
+
class TestTranspose(CUDATestCase):
|
| 14 |
+
|
| 15 |
+
def test_transpose(self):
|
| 16 |
+
variants = ((5, 6, np.float64),
|
| 17 |
+
(128, 128, np.complex128),
|
| 18 |
+
(1025, 512, np.float64))
|
| 19 |
+
|
| 20 |
+
for rows, cols, dtype in variants:
|
| 21 |
+
with self.subTest(rows=rows, cols=cols, dtype=dtype):
|
| 22 |
+
x = np.arange(rows * cols, dtype=dtype).reshape(cols, rows)
|
| 23 |
+
y = np.zeros(rows * cols, dtype=dtype).reshape(rows, cols)
|
| 24 |
+
dx = cuda.to_device(x)
|
| 25 |
+
dy = cuda.cudadrv.devicearray.from_array_like(y)
|
| 26 |
+
transpose(dx, dy)
|
| 27 |
+
dy.copy_to_host(y)
|
| 28 |
+
np.testing.assert_array_equal(x.transpose(), y)
|
| 29 |
+
|
| 30 |
+
small_variants = ((2, 3), (16, 16), (16, 17), (17, 16), (14, 15), (15, 14),
|
| 31 |
+
(14, 14))
|
| 32 |
+
|
| 33 |
+
def test_transpose_record(self):
|
| 34 |
+
for rows, cols in self.small_variants:
|
| 35 |
+
with self.subTest(rows=rows, cols=cols):
|
| 36 |
+
arr = np.recarray((rows, cols), dtype=recordwith2darray)
|
| 37 |
+
for x in range(rows):
|
| 38 |
+
for y in range(cols):
|
| 39 |
+
arr[x, y].i = x ** 2 + y
|
| 40 |
+
j = np.arange(3 * 2, dtype=np.float32)
|
| 41 |
+
arr[x, y].j = j.reshape(3, 2) * x + y
|
| 42 |
+
|
| 43 |
+
transposed = arr.T
|
| 44 |
+
d_arr = cuda.to_device(arr)
|
| 45 |
+
d_transposed = cuda.device_array_like(transposed)
|
| 46 |
+
transpose(d_arr, d_transposed)
|
| 47 |
+
host_transposed = d_transposed.copy_to_host()
|
| 48 |
+
np.testing.assert_array_equal(transposed, host_transposed)
|
| 49 |
+
|
| 50 |
+
def test_transpose_bool(self):
|
| 51 |
+
for rows, cols in self.small_variants:
|
| 52 |
+
with self.subTest(rows=rows, cols=cols):
|
| 53 |
+
arr = np.random.randint(2, size=(rows, cols), dtype=np.bool_)
|
| 54 |
+
transposed = arr.T
|
| 55 |
+
|
| 56 |
+
d_arr = cuda.to_device(arr)
|
| 57 |
+
d_transposed = cuda.device_array_like(transposed)
|
| 58 |
+
transpose(d_arr, d_transposed)
|
| 59 |
+
|
| 60 |
+
host_transposed = d_transposed.copy_to_host()
|
| 61 |
+
np.testing.assert_array_equal(transposed, host_transposed)
|
| 62 |
+
|
| 63 |
+
def test_transpose_view(self):
|
| 64 |
+
# Because the strides of transposes of views differ to those in NumPy
|
| 65 |
+
# (see issue #4974), we test the shape and strides of a transpose.
|
| 66 |
+
a = np.arange(120, dtype=np.int64).reshape((10, 12))
|
| 67 |
+
a_view_t = a[::2, ::2].T
|
| 68 |
+
|
| 69 |
+
d_a = cuda.to_device(a)
|
| 70 |
+
d_a_view_t = d_a[::2, ::2].T
|
| 71 |
+
|
| 72 |
+
self.assertEqual(d_a_view_t.shape, (6, 5))
|
| 73 |
+
self.assertEqual(d_a_view_t.strides, (40, 8))
|
| 74 |
+
|
| 75 |
+
h_a_view_t = d_a_view_t.copy_to_host()
|
| 76 |
+
np.testing.assert_array_equal(a_view_t, h_a_view_t)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
if __name__ == '__main__':
|
| 80 |
+
unittest.main()
|
shared/package-files/24/24059769bf429929af981af5b71ab1c0ad45bef9b9911d9573cea0793f045fee/_adaptive_avg_pool3d_compositeexplicitautograd_dispatch.h
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 compositeexplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor & _adaptive_avg_pool3d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size);
|
| 21 |
+
TORCH_API at::Tensor & _adaptive_avg_pool3d_outf(const at::Tensor & self, at::IntArrayRef output_size, at::Tensor & out);
|
| 22 |
+
TORCH_API at::Tensor & _adaptive_avg_pool3d_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size);
|
| 23 |
+
TORCH_API at::Tensor & _adaptive_avg_pool3d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, at::Tensor & out);
|
| 24 |
+
|
| 25 |
+
} // namespace compositeexplicitautograd
|
| 26 |
+
} // namespace at
|
shared/package-files/24/240866561bb149091666d7d80374308601932ae0bfbaa2290c8c5fc4c71ec247/_storage_utils.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import List, Type, Union
|
| 3 |
+
|
| 4 |
+
from .filesystem import FileSystemReader, FileSystemWriter
|
| 5 |
+
|
| 6 |
+
from .storage import StorageReader, StorageWriter
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _storage_setup(
|
| 10 |
+
storage: Union[StorageReader, StorageWriter, None],
|
| 11 |
+
checkpoint_id: Union[str, os.PathLike, None],
|
| 12 |
+
reader: bool = False,
|
| 13 |
+
) -> Union[None, StorageReader, StorageWriter]:
|
| 14 |
+
if storage:
|
| 15 |
+
if checkpoint_id is not None:
|
| 16 |
+
storage.reset(checkpoint_id)
|
| 17 |
+
return storage
|
| 18 |
+
|
| 19 |
+
if not checkpoint_id:
|
| 20 |
+
raise RuntimeError(
|
| 21 |
+
"`checkpoint_id` must be specificed if "
|
| 22 |
+
"storage_reader/storage_writer is None."
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
targets: List[Type[Union[StorageReader, StorageWriter]]] = []
|
| 26 |
+
if reader:
|
| 27 |
+
targets = [
|
| 28 |
+
FileSystemReader,
|
| 29 |
+
]
|
| 30 |
+
else:
|
| 31 |
+
targets = [
|
| 32 |
+
FileSystemWriter,
|
| 33 |
+
]
|
| 34 |
+
try:
|
| 35 |
+
from .fsspec import FsspecReader, FsspecWriter
|
| 36 |
+
|
| 37 |
+
targets.append(FsspecReader if reader else FsspecWriter)
|
| 38 |
+
except Exception:
|
| 39 |
+
pass
|
| 40 |
+
|
| 41 |
+
for target in targets:
|
| 42 |
+
if target.validate_checkpoint_id(checkpoint_id):
|
| 43 |
+
storage = target(checkpoint_id) # type: ignore[call-arg]
|
| 44 |
+
storage.reset(checkpoint_id)
|
| 45 |
+
return storage
|
| 46 |
+
|
| 47 |
+
raise RuntimeError(
|
| 48 |
+
"Cannot detect which StorageReader or StorageWriter to use. "
|
| 49 |
+
"Please specify the storage_reader/storage_writer."
|
| 50 |
+
)
|
shared/package-files/24/2409674eb17759c589a0e81027dc5cc15f353ff0b7615cf0ee14de1f2e9b053a/randn_like_native.h
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 randn_like(const at::Tensor & self, c10::optional<at::ScalarType> dtype={}, c10::optional<at::Layout> layout={}, c10::optional<at::Device> device={}, c10::optional<bool> pin_memory={}, c10::optional<at::MemoryFormat> memory_format=c10::nullopt);
|
| 20 |
+
TORCH_API at::Tensor & randn_like_out(const at::Tensor & self, c10::optional<at::MemoryFormat> memory_format, at::Tensor & out);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
shared/package-files/24/2409abaeb08471dc999602cefd8e279ac521539ea02b2acc937f5653df7529ba/aaa-rv-unk
ADDED
|
Binary file (484 Bytes). View file
|
|
|
shared/package-files/24/240b1bc868eff321ddf6abec22e6ff6a6242bc8a94cbb9079d650c15ad6aa439/cummax_compositeexplicitautograd_dispatch.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 compositeexplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor> cummax(const at::Tensor & self, int64_t dim);
|
| 21 |
+
TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> cummax_out(at::Tensor & values, at::Tensor & indices, const at::Tensor & self, int64_t dim);
|
| 22 |
+
TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> cummax_outf(const at::Tensor & self, int64_t dim, at::Tensor & values, at::Tensor & indices);
|
| 23 |
+
|
| 24 |
+
} // namespace compositeexplicitautograd
|
| 25 |
+
} // namespace at
|
shared/package-files/24/240cf4858d60049bb743f76fb1c42b4897602aec298ea159570cfeb0e410db5c/expn_asy.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Precompute the polynomials for the asymptotic expansion of the
|
| 2 |
+
generalized exponential integral.
|
| 3 |
+
|
| 4 |
+
Sources
|
| 5 |
+
-------
|
| 6 |
+
[1] NIST, Digital Library of Mathematical Functions,
|
| 7 |
+
https://dlmf.nist.gov/8.20#ii
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
import sympy
|
| 14 |
+
from sympy import Poly
|
| 15 |
+
x = sympy.symbols('x')
|
| 16 |
+
except ImportError:
|
| 17 |
+
pass
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def generate_A(K):
|
| 21 |
+
A = [Poly(1, x)]
|
| 22 |
+
for k in range(K):
|
| 23 |
+
A.append(Poly(1 - 2*k*x, x)*A[k] + Poly(x*(x + 1))*A[k].diff())
|
| 24 |
+
return A
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
WARNING = """\
|
| 28 |
+
/* This file was automatically generated by _precompute/expn_asy.py.
|
| 29 |
+
* Do not edit it manually!
|
| 30 |
+
*/
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def main():
|
| 35 |
+
print(__doc__)
|
| 36 |
+
fn = os.path.join('..', 'cephes', 'expn.h')
|
| 37 |
+
|
| 38 |
+
K = 12
|
| 39 |
+
A = generate_A(K)
|
| 40 |
+
with open(fn + '.new', 'w') as f:
|
| 41 |
+
f.write(WARNING)
|
| 42 |
+
f.write(f"#define nA {len(A)}\n")
|
| 43 |
+
for k, Ak in enumerate(A):
|
| 44 |
+
', '.join([str(x.evalf(18)) for x in Ak.coeffs()])
|
| 45 |
+
f.write(f"static const double A{k}[] = {{tmp}};\n")
|
| 46 |
+
", ".join([f"A{k}" for k in range(K + 1)])
|
| 47 |
+
f.write("static const double *A[] = {{tmp}};\n")
|
| 48 |
+
", ".join([str(Ak.degree()) for Ak in A])
|
| 49 |
+
f.write("static const int Adegs[] = {{tmp}};\n")
|
| 50 |
+
os.rename(fn + '.new', fn)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
main()
|
shared/package-files/24/240df50f08152d7462a1bbf2e9ef1e13f302548755f2dbfa8c4b02bc0747eef6/gradient_compositeimplicitautograd_dispatch.h
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 compositeimplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API ::std::vector<at::Tensor> gradient(const at::Tensor & self, const c10::optional<at::Scalar> & spacing=c10::nullopt, c10::optional<int64_t> dim=c10::nullopt, int64_t edge_order=1);
|
| 21 |
+
TORCH_API ::std::vector<at::Tensor> gradient(const at::Tensor & self, const at::Scalar & spacing, at::IntArrayRef dim, int64_t edge_order=1);
|
| 22 |
+
TORCH_API ::std::vector<at::Tensor> gradient(const at::Tensor & self, at::IntArrayRef dim, int64_t edge_order=1);
|
| 23 |
+
TORCH_API ::std::vector<at::Tensor> gradient(const at::Tensor & self, at::ArrayRef<at::Scalar> spacing, c10::optional<int64_t> dim=c10::nullopt, int64_t edge_order=1);
|
| 24 |
+
TORCH_API ::std::vector<at::Tensor> gradient(const at::Tensor & self, at::ArrayRef<at::Scalar> spacing, at::IntArrayRef dim, int64_t edge_order=1);
|
| 25 |
+
TORCH_API ::std::vector<at::Tensor> gradient(const at::Tensor & self, at::TensorList spacing, c10::optional<int64_t> dim=c10::nullopt, int64_t edge_order=1);
|
| 26 |
+
TORCH_API ::std::vector<at::Tensor> gradient(const at::Tensor & self, at::TensorList spacing, at::IntArrayRef dim, int64_t edge_order=1);
|
| 27 |
+
|
| 28 |
+
} // namespace compositeimplicitautograd
|
| 29 |
+
} // namespace at
|
shared/package-files/24/240ec356d2e50b782c932b20b4e46d9bdfb851687d916afd1636d76dd42c211a/logging.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import inspect
|
| 3 |
+
import logging
|
| 4 |
+
import distutils.log
|
| 5 |
+
from . import monkey
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _not_warning(record):
|
| 9 |
+
return record.levelno < logging.WARNING
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def configure():
|
| 13 |
+
"""
|
| 14 |
+
Configure logging to emit warning and above to stderr
|
| 15 |
+
and everything else to stdout. This behavior is provided
|
| 16 |
+
for compatibility with distutils.log but may change in
|
| 17 |
+
the future.
|
| 18 |
+
"""
|
| 19 |
+
err_handler = logging.StreamHandler()
|
| 20 |
+
err_handler.setLevel(logging.WARNING)
|
| 21 |
+
out_handler = logging.StreamHandler(sys.stdout)
|
| 22 |
+
out_handler.addFilter(_not_warning)
|
| 23 |
+
handlers = err_handler, out_handler
|
| 24 |
+
logging.basicConfig(
|
| 25 |
+
format="{message}", style='{', handlers=handlers, level=logging.DEBUG
|
| 26 |
+
)
|
| 27 |
+
if inspect.ismodule(distutils.dist.log):
|
| 28 |
+
monkey.patch_func(set_threshold, distutils.log, 'set_threshold')
|
| 29 |
+
# For some reason `distutils.log` module is getting cached in `distutils.dist`
|
| 30 |
+
# and then loaded again when patched,
|
| 31 |
+
# implying: id(distutils.log) != id(distutils.dist.log).
|
| 32 |
+
# Make sure the same module object is used everywhere:
|
| 33 |
+
distutils.dist.log = distutils.log
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def set_threshold(level):
|
| 37 |
+
logging.root.setLevel(level * 10)
|
| 38 |
+
return set_threshold.unpatched(level)
|
shared/package-files/24/240ef7ea81b7b3c3cf74a85db182be06774b52c1ab24224021106c79220466d3/some_functions.mat
ADDED
|
Binary file (1.4 kB). View file
|
|
|
shared/package-files/24/241601dc076764ac412e2de0ce415427a744dcce14d4a07a9ab099c2b0b45759/api.py
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from contextlib import contextmanager, nullcontext
|
| 3 |
+
from copy import copy
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from functools import partial, wraps
|
| 6 |
+
from typing import Any, Callable, cast, Dict, List, Optional, Set, Tuple, Union
|
| 7 |
+
|
| 8 |
+
from functorch import make_fx
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.distributed as dist
|
| 12 |
+
|
| 13 |
+
# We need to import _functional_collectives to trigger op registration
|
| 14 |
+
import torch.distributed._functional_collectives
|
| 15 |
+
import torch.nn as nn
|
| 16 |
+
import torch.utils._pytree as pytree
|
| 17 |
+
|
| 18 |
+
from torch import fx
|
| 19 |
+
from torch._decomp.decompositions import native_layer_norm_backward
|
| 20 |
+
|
| 21 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 22 |
+
from torch.distributed._spmd.data_parallel import gradients_tagging
|
| 23 |
+
from torch.distributed._spmd.parallel_mode import (
|
| 24 |
+
DataParallel,
|
| 25 |
+
DTensorExpandMode,
|
| 26 |
+
ParallelMode,
|
| 27 |
+
)
|
| 28 |
+
from torch.distributed._tensor import Placement
|
| 29 |
+
from torch.fx.graph import _PyTreeCodeGen, _PyTreeInfo, CodeGen
|
| 30 |
+
from torch.nn.utils import stateless
|
| 31 |
+
from torch.nn.utils._named_member_accessor import NamedMemberAccessor
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Override(ABC):
|
| 35 |
+
r"""Override the tracing and transformation behavior of :meth:`~torch.distributed._spmd.compile`.
|
| 36 |
+
|
| 37 |
+
This is useful when any part of the model is not traceable or if you prefer
|
| 38 |
+
to not trace it due to any reason. More specifically, users can implement
|
| 39 |
+
:meth:`torch.distributed._spmd.Override.replacement` to replace an original
|
| 40 |
+
submodule with the return new submodule. The new submodule contains
|
| 41 |
+
operations that users preferred to be traced, which simply be a dummy
|
| 42 |
+
placeholder operator. After tracing, users can implement
|
| 43 |
+
:meth:`torch.distributed._spmd.Override.transform` to transform the traced
|
| 44 |
+
graph, where the dummy placeholder operator serves as an anchor to insert
|
| 45 |
+
new sub-graphs.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
@abstractmethod
|
| 49 |
+
def replacement(self, fqn: str, orig_submodule: torch.nn.Module) -> torch.nn.Module:
|
| 50 |
+
r"""Implement this method to return a new :class:`nn.Module` instance to replace the ``orig_submodule``
|
| 51 |
+
argument in the model.
|
| 52 |
+
|
| 53 |
+
This helps if ``orig_submodule`` is not traceable or should not be traced.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
fqn (str): fully quantified name of the submodule.
|
| 57 |
+
orig_submodule (class:`nn.Module`): original submodule instance to replace.
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
A new :class:`nn.Module` instance to replace the original one.
|
| 61 |
+
|
| 62 |
+
"""
|
| 63 |
+
pass
|
| 64 |
+
|
| 65 |
+
@abstractmethod
|
| 66 |
+
def transform(
|
| 67 |
+
self,
|
| 68 |
+
gm: fx.GraphModule,
|
| 69 |
+
flat_state: List[torch.Tensor],
|
| 70 |
+
) -> fx.GraphModule:
|
| 71 |
+
r"""
|
| 72 |
+
Given a DTensor-expanded graph and sharding schema for every node,
|
| 73 |
+
conduct additional transformation for the sub-graph from the :class:`nn.Module`
|
| 74 |
+
returned by :meth:`torch.distributed._spmd.Override.replacement` if
|
| 75 |
+
necessary.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
gm (:class:`fx.Graph`): a DTensor-expanded graph.
|
| 79 |
+
flat_state (List[str, :class:`Tensor`]): a reference to the list of
|
| 80 |
+
flattened state. The elements in ``flat_state`` map to the first
|
| 81 |
+
``len(flat_state)`` placeholders in the graph. The transformation
|
| 82 |
+
can add state to or remove state from ``flat_state`` as long as
|
| 83 |
+
it keeps ``flat_state`` and the placeholders consistent.
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
The :class:`fx.Graph` after transformation.
|
| 87 |
+
|
| 88 |
+
"""
|
| 89 |
+
pass
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class _PyTreeCodeGenOutputsOnly(_PyTreeCodeGen):
|
| 93 |
+
# pyre-ignore[3]
|
| 94 |
+
def process_inputs(self, *args: Any) -> Any:
|
| 95 |
+
return args
|
| 96 |
+
|
| 97 |
+
# pyre-ignore[2, 3]
|
| 98 |
+
def gen_fn_def(self, free_vars, maybe_return_annotation):
|
| 99 |
+
return CodeGen.gen_fn_def(self, free_vars, maybe_return_annotation)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _to_caller_flattened_graph_module(gm: torch.fx.GraphModule) -> torch.fx.GraphModule:
|
| 103 |
+
"""Move the responsibility of flattening the input arguments from the graph module to the caller.
|
| 104 |
+
|
| 105 |
+
Example:
|
| 106 |
+
|
| 107 |
+
output = gm(my_struct)
|
| 108 |
+
|
| 109 |
+
gm = gm(to_caller_flattened_graph_module)
|
| 110 |
+
|
| 111 |
+
output = gm(*pytree.flatten(my_struct)[0])
|
| 112 |
+
|
| 113 |
+
"""
|
| 114 |
+
# pyre-ignore[16]
|
| 115 |
+
gm._graph._codegen = _PyTreeCodeGenOutputsOnly(
|
| 116 |
+
pytree_info=_PyTreeInfo(
|
| 117 |
+
# pyre-ignore[6]
|
| 118 |
+
orig_args=None, # type: ignore[arg-type]
|
| 119 |
+
# pyre-ignore[6]
|
| 120 |
+
in_spec=None, # type: ignore[arg-type]
|
| 121 |
+
# pyre-ignore[16]
|
| 122 |
+
out_spec=gm._graph._codegen.pytree_info.out_spec,
|
| 123 |
+
)
|
| 124 |
+
)
|
| 125 |
+
gm.recompile()
|
| 126 |
+
return gm
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# Use a dtensor expand mode for now to preserve the old behavior
|
| 130 |
+
# and avoid breaking existing code
|
| 131 |
+
dtensor_expand_mode = DTensorExpandMode()
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _override_placements(t: torch.Tensor, placements: List[Placement]):
|
| 135 |
+
global dtensor_expand_mode
|
| 136 |
+
dtensor_expand_mode._placements_override[id(t)] = placements
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@contextmanager
|
| 140 |
+
def _rematerialize_optimizer(
|
| 141 |
+
opt: torch.optim.Optimizer,
|
| 142 |
+
named_states: Dict[str, Any],
|
| 143 |
+
params: Dict[str, nn.Parameter],
|
| 144 |
+
):
|
| 145 |
+
assert opt is not None
|
| 146 |
+
|
| 147 |
+
# update opt.state with proxy tensors
|
| 148 |
+
orig_states = copy(opt.state)
|
| 149 |
+
for n in named_states:
|
| 150 |
+
# opt.state's key type is string, but optimizer uses Parameter as keys
|
| 151 |
+
opt.state[params[n]] = named_states[n] # type: ignore[index]
|
| 152 |
+
|
| 153 |
+
# FIXME: support multiple parameter groups
|
| 154 |
+
param_group = opt.param_groups[0]
|
| 155 |
+
orig_params = param_group["params"]
|
| 156 |
+
param_group["params"] = params.values()
|
| 157 |
+
|
| 158 |
+
try:
|
| 159 |
+
yield
|
| 160 |
+
finally:
|
| 161 |
+
param_group["params"] = orig_params
|
| 162 |
+
opt.state = orig_states
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
aten = torch.ops.aten # pyre-ignore
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@contextmanager
|
| 169 |
+
def _enable_compile():
|
| 170 |
+
# The return value of torch._utils.is_compiling changes optimizer behavior.
|
| 171 |
+
# We need that function to return True to include optimizer in the graph.
|
| 172 |
+
# See: https://github.com/pytorch/pytorch/blob/a524123c91ab399c9dd6882c1189596dd77e7734/torch/optim/optimizer.py#L41
|
| 173 |
+
def f_true():
|
| 174 |
+
return True
|
| 175 |
+
|
| 176 |
+
orig_is_compiling_code = torch._utils.is_compiling.__code__
|
| 177 |
+
torch._utils.is_compiling.__code__ = f_true.__code__
|
| 178 |
+
try:
|
| 179 |
+
yield
|
| 180 |
+
finally:
|
| 181 |
+
torch._utils.is_compiling.__code__ = orig_is_compiling_code
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _foreach_add_decomp(self, other, alpha=1):
|
| 185 |
+
self_updated = aten._foreach_add.List(self, other, alpha=alpha)
|
| 186 |
+
for s, s_u in zip(self, self_updated):
|
| 187 |
+
s.copy_(s_u)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _foreach_unaop_decomp(op, self):
|
| 191 |
+
self_updated = op(self)
|
| 192 |
+
for s, s_u in zip(self, self_updated):
|
| 193 |
+
s.copy_(s_u)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _foreach_binop_list_decomp(op, self, other):
|
| 197 |
+
self_updated = op(self, other)
|
| 198 |
+
for s, s_u in zip(self, self_updated):
|
| 199 |
+
s.copy_(s_u)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _foreach_binop_scalar_decomp(op, self, scalar=1):
|
| 203 |
+
self_updated = op(self, scalar)
|
| 204 |
+
for s, s_u in zip(self, self_updated):
|
| 205 |
+
s.copy_(s_u)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _foreach_addcop_scalar_decomp(op, self, tensor1, tensor2, scalar=1):
|
| 209 |
+
self_updated = op(self, tensor1, tensor2, scalar)
|
| 210 |
+
for s, s_u in zip(self, self_updated):
|
| 211 |
+
s.copy_(s_u)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _fused_adam_decomp(
|
| 215 |
+
self,
|
| 216 |
+
grads,
|
| 217 |
+
exp_avgs,
|
| 218 |
+
exp_avg_sqs,
|
| 219 |
+
max_exp_avg_sqs,
|
| 220 |
+
state_steps,
|
| 221 |
+
*,
|
| 222 |
+
lr=1,
|
| 223 |
+
beta1=1,
|
| 224 |
+
beta2=1,
|
| 225 |
+
weight_decay=1,
|
| 226 |
+
eps=1,
|
| 227 |
+
amsgrad=True,
|
| 228 |
+
maximize=True,
|
| 229 |
+
grad_scale=None,
|
| 230 |
+
found_inf=None,
|
| 231 |
+
):
|
| 232 |
+
orig_tuple = (self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs)
|
| 233 |
+
updated_tuple = aten._fused_adam.default(
|
| 234 |
+
self,
|
| 235 |
+
grads,
|
| 236 |
+
exp_avgs,
|
| 237 |
+
exp_avg_sqs,
|
| 238 |
+
max_exp_avg_sqs,
|
| 239 |
+
state_steps,
|
| 240 |
+
lr=lr,
|
| 241 |
+
beta1=beta1,
|
| 242 |
+
beta2=beta2,
|
| 243 |
+
weight_decay=weight_decay,
|
| 244 |
+
eps=eps,
|
| 245 |
+
amsgrad=amsgrad,
|
| 246 |
+
maximize=maximize,
|
| 247 |
+
grad_scale=grad_scale,
|
| 248 |
+
found_inf=found_inf,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
for idx, (orig, updated) in enumerate(zip(orig_tuple, updated_tuple)):
|
| 252 |
+
if idx == 1:
|
| 253 |
+
# skip gradient copying as we don't need to copy gradients back
|
| 254 |
+
continue
|
| 255 |
+
for o, u in zip(orig, updated):
|
| 256 |
+
o.copy_(u)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
SPMD_DECOMP_TABLE = {
|
| 260 |
+
aten._foreach_add_.List: _foreach_add_decomp,
|
| 261 |
+
aten._foreach_add_.Scalar: partial(
|
| 262 |
+
_foreach_binop_scalar_decomp, aten._foreach_add.Scalar
|
| 263 |
+
),
|
| 264 |
+
aten._foreach_addcdiv_.Scalar: partial(
|
| 265 |
+
_foreach_addcop_scalar_decomp, aten._foreach_addcdiv.Scalar
|
| 266 |
+
),
|
| 267 |
+
aten._foreach_addcmul_.Scalar: partial(
|
| 268 |
+
_foreach_addcop_scalar_decomp, aten._foreach_addcmul.Scalar
|
| 269 |
+
),
|
| 270 |
+
aten._foreach_div_.List: partial(
|
| 271 |
+
_foreach_binop_list_decomp, aten._foreach_div.List
|
| 272 |
+
),
|
| 273 |
+
aten._foreach_mul_.Scalar: partial(
|
| 274 |
+
_foreach_binop_scalar_decomp, aten._foreach_mul.Scalar
|
| 275 |
+
),
|
| 276 |
+
aten._foreach_div_.Scalar: partial(
|
| 277 |
+
_foreach_binop_scalar_decomp, aten._foreach_div.Scalar
|
| 278 |
+
),
|
| 279 |
+
aten._foreach_neg_.default: partial(
|
| 280 |
+
_foreach_unaop_decomp, aten._foreach_neg.default
|
| 281 |
+
),
|
| 282 |
+
aten._foreach_reciprocal_.default: partial(
|
| 283 |
+
_foreach_unaop_decomp, aten._foreach_reciprocal.default
|
| 284 |
+
),
|
| 285 |
+
aten._foreach_sqrt_.default: partial(
|
| 286 |
+
_foreach_unaop_decomp, aten._foreach_sqrt.default
|
| 287 |
+
),
|
| 288 |
+
aten._foreach_sub_.Scalar: partial(
|
| 289 |
+
_foreach_binop_scalar_decomp, aten._foreach_sub.Scalar
|
| 290 |
+
),
|
| 291 |
+
aten._fused_adam_.default: _fused_adam_decomp,
|
| 292 |
+
aten.native_layer_norm_backward.default: native_layer_norm_backward,
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
DEDUP_TARGETS: Set[torch._ops.OpOverload] = {
|
| 297 |
+
torch.ops.c10d_functional.all_reduce.default,
|
| 298 |
+
torch.ops.c10d_functional.wait_tensor.default,
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def _dedup_collectives(gm: fx.GraphModule) -> fx.GraphModule:
|
| 303 |
+
args_to_node: Dict[Tuple[Any, ...], fx.Node] = {}
|
| 304 |
+
|
| 305 |
+
for node in gm.graph.nodes:
|
| 306 |
+
# replace all args with the results from the first unique comm op
|
| 307 |
+
args = pytree.arg_tree_leaves(*node.args)
|
| 308 |
+
|
| 309 |
+
if node.target in DEDUP_TARGETS:
|
| 310 |
+
args_key = (node.target, *args)
|
| 311 |
+
unique_node = args_to_node.get(args_key, None)
|
| 312 |
+
if unique_node is None:
|
| 313 |
+
# first time seeing this combination, remember it
|
| 314 |
+
args_to_node[args_key] = node
|
| 315 |
+
else:
|
| 316 |
+
# the current node is a duplicate, replace it
|
| 317 |
+
node.replace_all_uses_with(unique_node)
|
| 318 |
+
gm.graph.erase_node(node)
|
| 319 |
+
|
| 320 |
+
gm.recompile()
|
| 321 |
+
|
| 322 |
+
return gm
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
@dataclass
|
| 326 |
+
class _CompiledResult:
|
| 327 |
+
gm: fx.GraphModule
|
| 328 |
+
mod: nn.Module
|
| 329 |
+
opt: Optional[torch.optim.Optimizer]
|
| 330 |
+
flat_state: List[torch.Tensor]
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _compile(
|
| 334 |
+
func: Callable,
|
| 335 |
+
module_override: Optional[List[Override]],
|
| 336 |
+
parallel_mode: ParallelMode,
|
| 337 |
+
*args: Any,
|
| 338 |
+
**kwargs: Any,
|
| 339 |
+
) -> _CompiledResult:
|
| 340 |
+
# 1. Extract nn.Module and Optimizer from args and kwargs
|
| 341 |
+
# FIXME(@mrshenli): support multiple nn.Module instances
|
| 342 |
+
# FIXME(@mrshenli): support multiple Optiimzer instances
|
| 343 |
+
# FIXME(@mrshenli): need to broadcast model to sync parameters
|
| 344 |
+
mod, opt = None, None
|
| 345 |
+
for arg in pytree.arg_tree_leaves(*args, **kwargs):
|
| 346 |
+
if isinstance(arg, nn.Module):
|
| 347 |
+
assert mod is None, "Only support single nn.Module for now"
|
| 348 |
+
mod = arg
|
| 349 |
+
if isinstance(arg, torch.optim.Optimizer):
|
| 350 |
+
assert opt is None, "Only support single Optimizer for now"
|
| 351 |
+
opt = arg
|
| 352 |
+
|
| 353 |
+
assert mod is not None, "Couldn't find nn.Module instances from the arguments."
|
| 354 |
+
|
| 355 |
+
# 2. Override target submodules (e.g., MoE) with dummy replacements
|
| 356 |
+
if module_override:
|
| 357 |
+
accessor = NamedMemberAccessor(mod)
|
| 358 |
+
|
| 359 |
+
def swap(fqn_prefix: str, module: torch.nn.Module) -> None:
|
| 360 |
+
for override in module_override: # type: ignore[union-attr]
|
| 361 |
+
for name, child in module.named_children():
|
| 362 |
+
if len(name) == 0:
|
| 363 |
+
continue
|
| 364 |
+
fqn = fqn_prefix + "." + name if fqn_prefix != "" else name
|
| 365 |
+
new_child = override.replacement(fqn, child)
|
| 366 |
+
if id(new_child) == id(child):
|
| 367 |
+
swap(fqn, new_child)
|
| 368 |
+
else:
|
| 369 |
+
accessor.swap_submodule(fqn, new_child)
|
| 370 |
+
|
| 371 |
+
swap("", mod)
|
| 372 |
+
|
| 373 |
+
# 3. Trace statelss version of the train_step
|
| 374 |
+
params = dict(mod.named_parameters(remove_duplicate=False))
|
| 375 |
+
buffers = dict(mod.named_buffers(remove_duplicate=False))
|
| 376 |
+
|
| 377 |
+
named_states = {}
|
| 378 |
+
if opt is not None:
|
| 379 |
+
# Pass named_states instead of opt.state to stateless_func, because
|
| 380 |
+
# the later uses nn.Parameter as key. During tracing, we need to
|
| 381 |
+
# make sure optimizers can find the states using proxy tensors.
|
| 382 |
+
for n, p in params.items():
|
| 383 |
+
if p in opt.state:
|
| 384 |
+
# opt.state's key type is string, but optimizer uses
|
| 385 |
+
# Parameter as keys
|
| 386 |
+
named_states[n] = opt.state[p] # type: ignore[index]
|
| 387 |
+
|
| 388 |
+
is_data_parallel_mode = isinstance(parallel_mode, DataParallel)
|
| 389 |
+
|
| 390 |
+
# Lift states and parameters as function arguments so that make_fx
|
| 391 |
+
# can trace operations applied to them.
|
| 392 |
+
def stateless_func(func, params, buffers, named_states, args, kwargs):
|
| 393 |
+
with stateless._reparametrize_module(
|
| 394 |
+
mod, {**params, **buffers}
|
| 395 |
+
), _rematerialize_optimizer(
|
| 396 |
+
opt, named_states, params
|
| 397 |
+
) if opt else nullcontext():
|
| 398 |
+
# For DataParallel mode, install hooks first to tag the gradients
|
| 399 |
+
with gradients_tagging(params) if is_data_parallel_mode else nullcontext():
|
| 400 |
+
ret = func(*args, **kwargs)
|
| 401 |
+
|
| 402 |
+
# make sure updated parameters are returned
|
| 403 |
+
return ret, list(mod.parameters()), list(named_states.values()) # type: ignore[union-attr]
|
| 404 |
+
|
| 405 |
+
# FIXME: Using symbolic tracing to work around in DTensor expand mode.
|
| 406 |
+
# Otherwise it hits shape mismatch error, as we use local inputs to
|
| 407 |
+
# trace local graph and use DTensor to expand operators, where
|
| 408 |
+
# DTensor's shape is the global shape.
|
| 409 |
+
tracing_mode = "fake" if is_data_parallel_mode else "symbolic"
|
| 410 |
+
|
| 411 |
+
if is_data_parallel_mode:
|
| 412 |
+
fake_mode = FakeTensorMode()
|
| 413 |
+
data_parallel_mode = cast(DataParallel, parallel_mode)
|
| 414 |
+
|
| 415 |
+
def _get_full_batch_arg(arg: torch.Tensor) -> torch.Tensor:
|
| 416 |
+
# since compilation happens in the first iteration and we
|
| 417 |
+
# receives mini-batch input, convert them to full batch
|
| 418 |
+
# fake tensor input first for data parallel sharding
|
| 419 |
+
# propagations
|
| 420 |
+
fake_arg = fake_mode.from_tensor(arg)
|
| 421 |
+
arg_dims = [1] * arg.ndim
|
| 422 |
+
# expand the tensor to full batch size on its batch dim
|
| 423 |
+
arg_dims[data_parallel_mode.input_batch_dim] *= dist.get_world_size()
|
| 424 |
+
return fake_arg.repeat(arg_dims)
|
| 425 |
+
|
| 426 |
+
args = pytree.tree_map_only(
|
| 427 |
+
torch.Tensor,
|
| 428 |
+
_get_full_batch_arg,
|
| 429 |
+
args,
|
| 430 |
+
)
|
| 431 |
+
kwargs = pytree.tree_map_only(
|
| 432 |
+
torch.Tensor,
|
| 433 |
+
_get_full_batch_arg,
|
| 434 |
+
kwargs,
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
with _enable_compile(), torch.autograd.detect_anomaly(check_nan=False):
|
| 438 |
+
# FIXME(@mrshenli): functionalization does not work for our use
|
| 439 |
+
# case yet. Use explicit decompositions for foreach ops.
|
| 440 |
+
# Remove this when the following issue is addressed.
|
| 441 |
+
# Issue: https://github.com/pytorch/pytorch/issues/97852
|
| 442 |
+
gm = make_fx(
|
| 443 |
+
partial(stateless_func, func),
|
| 444 |
+
tracing_mode=tracing_mode,
|
| 445 |
+
decomposition_table=SPMD_DECOMP_TABLE,
|
| 446 |
+
_allow_non_fake_inputs=False,
|
| 447 |
+
)(params, buffers, named_states, args, kwargs)
|
| 448 |
+
|
| 449 |
+
params_and_buffers: Dict[str, Union[torch.Tensor, nn.Parameter]] = {
|
| 450 |
+
**params,
|
| 451 |
+
**buffers,
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
# 4. parallel mode to expand a single device graph to a distributed graph
|
| 455 |
+
gm = parallel_mode.partition(
|
| 456 |
+
gm,
|
| 457 |
+
mod,
|
| 458 |
+
opt,
|
| 459 |
+
params_and_buffers,
|
| 460 |
+
named_states,
|
| 461 |
+
args,
|
| 462 |
+
kwargs,
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
# 5. Move the responsibility of flattening the input arguments from the
|
| 466 |
+
# graph module to the caller. This serves two purposes:
|
| 467 |
+
# - Transformations that add/remove state need to manipulate a state
|
| 468 |
+
# container that maintains the state tensors in the same order as they
|
| 469 |
+
# appear in graph placeholders.
|
| 470 |
+
# - Reduced runtime cost. The state container is only flattened once upfront.
|
| 471 |
+
flat_state = pytree.tree_leaves([params_and_buffers, named_states])
|
| 472 |
+
gm = _to_caller_flattened_graph_module(gm)
|
| 473 |
+
|
| 474 |
+
# 6. dedup comm operators.
|
| 475 |
+
# The duplication could come from DTensor args and kwargs redistribution.
|
| 476 |
+
# Suppose one operator produces a Partial gradient tensor and model
|
| 477 |
+
# parameters are replicated. In this case, every optimizer operation using
|
| 478 |
+
# that Partial gradient tensor would trigger an allreduce. This is becuase
|
| 479 |
+
# DTensor only has local information on individual tensor/operator, which is
|
| 480 |
+
# not sufficient to detect duplications in the graph. This situation can
|
| 481 |
+
# also happen when inserting FSDP allgather if a parameter is used multiple
|
| 482 |
+
# times in the forward method.
|
| 483 |
+
# TODO(@mrshenli): @yifuwang has a suggestion of conducting expansion and
|
| 484 |
+
# dedup at tracer-level to avoid multiple graph passes.
|
| 485 |
+
gm = _dedup_collectives(gm)
|
| 486 |
+
|
| 487 |
+
# 7. Replace previously inserted dummy ones with real graphs.
|
| 488 |
+
if module_override:
|
| 489 |
+
for override in module_override:
|
| 490 |
+
gm = override.transform(gm, flat_state)
|
| 491 |
+
|
| 492 |
+
return _CompiledResult(gm, mod, opt, flat_state)
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
# Note that the Python convention of __dict__ requires the key to be str.
|
| 496 |
+
# TODO: ensure the key is unique.
|
| 497 |
+
COMPILED_OBJECT_KEY = "_compiled_obj"
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def compile(
|
| 501 |
+
module_override: Optional[List[Override]] = None,
|
| 502 |
+
gm_transformation: Optional[Callable[[fx.GraphModule], fx.GraphModule]] = None,
|
| 503 |
+
parallel_mode: Optional[ParallelMode] = None,
|
| 504 |
+
):
|
| 505 |
+
r"""Compile and optimize a callable, which can be a train step within a training loop.
|
| 506 |
+
|
| 507 |
+
This method will extract :class:`nn.Module` and :class:`torch.optim.Optimizer`
|
| 508 |
+
instances from the input arguments and trace operations applied to their
|
| 509 |
+
parameters and states.
|
| 510 |
+
|
| 511 |
+
Args:
|
| 512 |
+
module_override (Optional[List[Override]]): a list of Override instances
|
| 513 |
+
that will be applied to the module in order. The :class:`Override`
|
| 514 |
+
objects provide :class:`nn.Module` replacements during tracing and a
|
| 515 |
+
graph transformation function after tracing. (Default: ``None``)
|
| 516 |
+
gm_transformation (Optional[Callable[fx.GraphModule, fx.GraphModule]]):
|
| 517 |
+
a callback that will be called after the original callable is
|
| 518 |
+
compiled and distributed (usually after the first iteration) to
|
| 519 |
+
transform the compiled GraphModule into a new optimized one.
|
| 520 |
+
parallel_mode (Optional[ParallelMode]): a :class:`ParallelMode` object
|
| 521 |
+
that specifies how to parallelize the callable. Each ParallelMode
|
| 522 |
+
would have its own strategy to partition the model and the captured
|
| 523 |
+
graph (Default: ``None``)
|
| 524 |
+
|
| 525 |
+
"""
|
| 526 |
+
|
| 527 |
+
def inner(func: Callable):
|
| 528 |
+
@wraps(func)
|
| 529 |
+
def wrapper(*args, **kwargs):
|
| 530 |
+
last_train_step = kwargs.pop("last_train_step", False) if kwargs else False
|
| 531 |
+
first_iter = False
|
| 532 |
+
# Put the COMPILED_OBJECT_KEY in ``wrapper`` instead of ``func`` as
|
| 533 |
+
# ``wrapper`` is the one that users will get.
|
| 534 |
+
compiled_obj = wrapper.__dict__.get(COMPILED_OBJECT_KEY, None)
|
| 535 |
+
if compiled_obj is None:
|
| 536 |
+
first_iter = True
|
| 537 |
+
global dtensor_expand_mode
|
| 538 |
+
mode: ParallelMode = (
|
| 539 |
+
dtensor_expand_mode if parallel_mode is None else parallel_mode
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
compiled_obj = _compile(func, module_override, mode, *args, **kwargs)
|
| 543 |
+
wrapper.__dict__[COMPILED_OBJECT_KEY] = compiled_obj
|
| 544 |
+
|
| 545 |
+
flat_inps = compiled_obj.flat_state + pytree.arg_tree_leaves(
|
| 546 |
+
*args, **kwargs
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
with torch.no_grad():
|
| 550 |
+
# N.B.: we don't need autograd as backward has already been
|
| 551 |
+
# captured in the graph.
|
| 552 |
+
if first_iter and gm_transformation:
|
| 553 |
+
# TODO: SPMD should provid a default and configurable
|
| 554 |
+
# transformation.
|
| 555 |
+
compiled_obj.gm = gm_transformation(compiled_obj.gm)
|
| 556 |
+
if not last_train_step:
|
| 557 |
+
output = compiled_obj.gm(*flat_inps)[0]
|
| 558 |
+
else:
|
| 559 |
+
# This is the last train step. Call IterGraphModule.forward()
|
| 560 |
+
# with the `last_iter` argument and catch the exception in
|
| 561 |
+
# case the compiled_obj is not wrapped with IterGraphModule.
|
| 562 |
+
try:
|
| 563 |
+
output = compiled_obj.gm(*flat_inps, last_iter=last_train_step)[
|
| 564 |
+
0
|
| 565 |
+
]
|
| 566 |
+
except TypeError as e:
|
| 567 |
+
if "last_iter" not in str(e):
|
| 568 |
+
raise e
|
| 569 |
+
output = compiled_obj.gm(*flat_inps)[0]
|
| 570 |
+
|
| 571 |
+
return output
|
| 572 |
+
|
| 573 |
+
return wrapper
|
| 574 |
+
|
| 575 |
+
return inner
|
shared/package-files/24/2417ef38fa791d31a9e9bd24ca7923cee24e4d101d4ec2497633d62c0b6ed5fa/mips.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.lexers.mips
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
Lexers for MIPS assembly.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from pygments.lexer import RegexLexer, words
|
| 12 |
+
from pygments.token import Whitespace, Comment, String, Keyword, Name, Text
|
| 13 |
+
|
| 14 |
+
__all__ = ["MIPSLexer"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class MIPSLexer(RegexLexer):
|
| 18 |
+
"""
|
| 19 |
+
A MIPS Assembly Lexer.
|
| 20 |
+
|
| 21 |
+
Based on the Emacs major mode by hlissner:
|
| 22 |
+
https://github.com/hlissner/emacs-mips-mode
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
name = 'MIPS'
|
| 26 |
+
aliases = ['mips']
|
| 27 |
+
# TODO: add '*.s' and '*.asm', which will require designing an analyse_text
|
| 28 |
+
# method for this lexer and refactoring those from Gas and Nasm in order to
|
| 29 |
+
# have relatively reliable detection
|
| 30 |
+
filenames = ['*.mips', '*.MIPS']
|
| 31 |
+
|
| 32 |
+
keywords = [
|
| 33 |
+
# Arithmetic insturctions
|
| 34 |
+
"add", "sub", "subu", "addi", "subi", "addu", "addiu",
|
| 35 |
+
# Multiplication/division
|
| 36 |
+
"mul", "mult", "multu", "mulu", "madd", "maddu", "msub", "msubu", "div", "divu",
|
| 37 |
+
# Bitwise operations
|
| 38 |
+
"and", "or", "nor", "xor", "andi", "ori", "xori", "clo", "clz",
|
| 39 |
+
# Shifts
|
| 40 |
+
"sll", "srl", "sllv", "srlv", "sra", "srav",
|
| 41 |
+
# Comparisons
|
| 42 |
+
"slt", "sltu", "slti", "sltiu",
|
| 43 |
+
# Move data
|
| 44 |
+
"mfhi", "mthi", "mflo", "mtlo", "movn", "movz", "movf", "movt",
|
| 45 |
+
# Jump
|
| 46 |
+
"j", "jal", "jalr", "jr",
|
| 47 |
+
# branch
|
| 48 |
+
"bc1f", "bc1t", "beq", "bgez", "bgezal", "bgtz", "blez", "bltzal", "bltz", "bne",
|
| 49 |
+
# Load
|
| 50 |
+
"lui", "lb", "lbu", "lh", "lhu", "lw", "lwcl", "lwl", "lwr",
|
| 51 |
+
# Store
|
| 52 |
+
"sb", "sh", "sw", "swl", "swr", # coproc: swc1 sdc1
|
| 53 |
+
# Concurrent load/store
|
| 54 |
+
"ll", "sc",
|
| 55 |
+
# Trap handling
|
| 56 |
+
"teq", "teqi", "tne", "tneqi", "tge", "tgeu", "tgei", "tgeiu", "tlt", "tltu", "tlti",
|
| 57 |
+
"tltiu",
|
| 58 |
+
# Exception / Interrupt
|
| 59 |
+
"eret", "break", "bop", "syscall",
|
| 60 |
+
# --- Floats -----------------------------------------------------
|
| 61 |
+
# Arithmetic
|
| 62 |
+
"add.s", "add.d", "sub.s", "sub.d", "mul.s", "mul.d", "div.s", "div.d", "neg.d",
|
| 63 |
+
"neg.s",
|
| 64 |
+
# Comparison
|
| 65 |
+
"c.e.d", "c.e.s", "c.le.d", "c.le.s", "c.lt.s", "c.lt.d", # "c.gt.s", "c.gt.d",
|
| 66 |
+
"madd.s", "madd.d", "msub.s", "msub.d",
|
| 67 |
+
# Move Floats
|
| 68 |
+
"mov.d", "move.s", "movf.d", "movf.s", "movt.d", "movt.s", "movn.d", "movn.s",
|
| 69 |
+
"movnzd", "movz.s", "movz.d",
|
| 70 |
+
# Conversion
|
| 71 |
+
"cvt.d.s", "cvt.d.w", "cvt.s.d", "cvt.s.w", "cvt.w.d", "cvt.w.s", "trunc.w.d",
|
| 72 |
+
"trunc.w.s",
|
| 73 |
+
# Math
|
| 74 |
+
"abs.s", "abs.d", "sqrt.s", "sqrt.d", "ceil.w.d", "ceil.w.s", "floor.w.d",
|
| 75 |
+
"floor.w.s", "round.w.d", "round.w.s",
|
| 76 |
+
]
|
| 77 |
+
|
| 78 |
+
pseudoinstructions = [
|
| 79 |
+
# Arithmetic & logical
|
| 80 |
+
"rem", "remu", "mulo", "mulou", "abs", "neg", "negu", "not", "rol", "ror",
|
| 81 |
+
# branches
|
| 82 |
+
"b", "beqz", "bge", "bgeu", "bgt", "bgtu", "ble", "bleu", "blt", "bltu", "bnez",
|
| 83 |
+
# loads
|
| 84 |
+
"la", "li", "ld", "ulh", "ulhu", "ulw",
|
| 85 |
+
# Store
|
| 86 |
+
"sd", "ush", "usw",
|
| 87 |
+
# move
|
| 88 |
+
"move", # coproc: "mfc1.d",
|
| 89 |
+
# comparisons
|
| 90 |
+
"sgt", "sgtu", "sge", "sgeu", "sle", "sleu", "sne", "seq",
|
| 91 |
+
# --- Floats -----------------------------------------------------
|
| 92 |
+
# load-store
|
| 93 |
+
"l.d", "l.s", "s.d", "s.s",
|
| 94 |
+
]
|
| 95 |
+
|
| 96 |
+
directives = [
|
| 97 |
+
".align", ".ascii", ".asciiz", ".byte", ".data", ".double", ".extern", ".float",
|
| 98 |
+
".globl", ".half", ".kdata", ".ktext", ".space", ".text", ".word",
|
| 99 |
+
]
|
| 100 |
+
|
| 101 |
+
deprecated = [
|
| 102 |
+
"beql", "bnel", "bgtzl", "bgezl", "bltzl", "blezl", "bltzall", "bgezall",
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
tokens = {
|
| 106 |
+
'root': [
|
| 107 |
+
(r'\s+', Whitespace),
|
| 108 |
+
(r'#.*', Comment),
|
| 109 |
+
(r'"', String, 'string'),
|
| 110 |
+
(r'-?[0-9]+?', Keyword.Constant),
|
| 111 |
+
(r'\w*:', Name.Function),
|
| 112 |
+
(words(deprecated, suffix=r'\b'), Keyword.Pseudo), # need warning face
|
| 113 |
+
(words(pseudoinstructions, suffix=r'\b'), Name.Variable),
|
| 114 |
+
(words(keywords, suffix=r'\b'), Keyword),
|
| 115 |
+
(r'[slm][ftwd]c[0-9]([.]d)?', Keyword),
|
| 116 |
+
(r'\$(f?[0-2][0-9]|f?3[01]|[ft]?[0-9]|[vk][01]|a[0-3]|s[0-7]|[gsf]p|ra|at|zero)',
|
| 117 |
+
Keyword.Type),
|
| 118 |
+
(words(directives, suffix=r'\b'), Name.Entity), # Preprocessor?
|
| 119 |
+
(r':|,|;|\{|\}|=>|@|\$|=', Name.Builtin),
|
| 120 |
+
(r'\w+', Text),
|
| 121 |
+
(r'.', Text),
|
| 122 |
+
],
|
| 123 |
+
'string': [
|
| 124 |
+
(r'\\.', String.Escape),
|
| 125 |
+
(r'"', String, '#pop'),
|
| 126 |
+
(r'[^\\"]+', String),
|
| 127 |
+
],
|
| 128 |
+
}
|
shared/package-files/24/241c13f3f868899bbe62b4183bc9366f3c6ade58af2a0aac78050e397cb00a7f/_scaled_dot_product_flash_attention_for_cpu_backward_native.h
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 ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _scaled_dot_product_flash_attention_cpu_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, double dropout_p, bool is_causal, const c10::optional<at::Tensor> & attn_mask={}, c10::optional<double> scale=c10::nullopt);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
shared/package-files/24/241e0d5f147c401880086352dc008993216c3358c41ee9a6f4ee445dce642972/reaching.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for computing reaching centrality of a node or a graph."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.utils import pairwise
|
| 5 |
+
|
| 6 |
+
__all__ = ["global_reaching_centrality", "local_reaching_centrality"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _average_weight(G, path, weight=None):
|
| 10 |
+
"""Returns the average weight of an edge in a weighted path.
|
| 11 |
+
|
| 12 |
+
Parameters
|
| 13 |
+
----------
|
| 14 |
+
G : graph
|
| 15 |
+
A networkx graph.
|
| 16 |
+
|
| 17 |
+
path: list
|
| 18 |
+
A list of vertices that define the path.
|
| 19 |
+
|
| 20 |
+
weight : None or string, optional (default=None)
|
| 21 |
+
If None, edge weights are ignored. Then the average weight of an edge
|
| 22 |
+
is assumed to be the multiplicative inverse of the length of the path.
|
| 23 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 24 |
+
"""
|
| 25 |
+
path_length = len(path) - 1
|
| 26 |
+
if path_length <= 0:
|
| 27 |
+
return 0
|
| 28 |
+
if weight is None:
|
| 29 |
+
return 1 / path_length
|
| 30 |
+
total_weight = sum(G.edges[i, j][weight] for i, j in pairwise(path))
|
| 31 |
+
return total_weight / path_length
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def global_reaching_centrality(G, weight=None, normalized=True):
|
| 35 |
+
"""Returns the global reaching centrality of a directed graph.
|
| 36 |
+
|
| 37 |
+
The *global reaching centrality* of a weighted directed graph is the
|
| 38 |
+
average over all nodes of the difference between the local reaching
|
| 39 |
+
centrality of the node and the greatest local reaching centrality of
|
| 40 |
+
any node in the graph [1]_. For more information on the local
|
| 41 |
+
reaching centrality, see :func:`local_reaching_centrality`.
|
| 42 |
+
Informally, the local reaching centrality is the proportion of the
|
| 43 |
+
graph that is reachable from the neighbors of the node.
|
| 44 |
+
|
| 45 |
+
Parameters
|
| 46 |
+
----------
|
| 47 |
+
G : DiGraph
|
| 48 |
+
A networkx DiGraph.
|
| 49 |
+
|
| 50 |
+
weight : None or string, optional (default=None)
|
| 51 |
+
Attribute to use for edge weights. If ``None``, each edge weight
|
| 52 |
+
is assumed to be one. A higher weight implies a stronger
|
| 53 |
+
connection between nodes and a *shorter* path length.
|
| 54 |
+
|
| 55 |
+
normalized : bool, optional (default=True)
|
| 56 |
+
Whether to normalize the edge weights by the total sum of edge
|
| 57 |
+
weights.
|
| 58 |
+
|
| 59 |
+
Returns
|
| 60 |
+
-------
|
| 61 |
+
h : float
|
| 62 |
+
The global reaching centrality of the graph.
|
| 63 |
+
|
| 64 |
+
Examples
|
| 65 |
+
--------
|
| 66 |
+
>>> G = nx.DiGraph()
|
| 67 |
+
>>> G.add_edge(1, 2)
|
| 68 |
+
>>> G.add_edge(1, 3)
|
| 69 |
+
>>> nx.global_reaching_centrality(G)
|
| 70 |
+
1.0
|
| 71 |
+
>>> G.add_edge(3, 2)
|
| 72 |
+
>>> nx.global_reaching_centrality(G)
|
| 73 |
+
0.75
|
| 74 |
+
|
| 75 |
+
See also
|
| 76 |
+
--------
|
| 77 |
+
local_reaching_centrality
|
| 78 |
+
|
| 79 |
+
References
|
| 80 |
+
----------
|
| 81 |
+
.. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek.
|
| 82 |
+
"Hierarchy Measure for Complex Networks."
|
| 83 |
+
*PLoS ONE* 7.3 (2012): e33799.
|
| 84 |
+
https://doi.org/10.1371/journal.pone.0033799
|
| 85 |
+
"""
|
| 86 |
+
if nx.is_negatively_weighted(G, weight=weight):
|
| 87 |
+
raise nx.NetworkXError("edge weights must be positive")
|
| 88 |
+
total_weight = G.size(weight=weight)
|
| 89 |
+
if total_weight <= 0:
|
| 90 |
+
raise nx.NetworkXError("Size of G must be positive")
|
| 91 |
+
|
| 92 |
+
# If provided, weights must be interpreted as connection strength
|
| 93 |
+
# (so higher weights are more likely to be chosen). However, the
|
| 94 |
+
# shortest path algorithms in NetworkX assume the provided "weight"
|
| 95 |
+
# is actually a distance (so edges with higher weight are less
|
| 96 |
+
# likely to be chosen). Therefore we need to invert the weights when
|
| 97 |
+
# computing shortest paths.
|
| 98 |
+
#
|
| 99 |
+
# If weight is None, we leave it as-is so that the shortest path
|
| 100 |
+
# algorithm can use a faster, unweighted algorithm.
|
| 101 |
+
if weight is not None:
|
| 102 |
+
|
| 103 |
+
def as_distance(u, v, d):
|
| 104 |
+
return total_weight / d.get(weight, 1)
|
| 105 |
+
|
| 106 |
+
shortest_paths = nx.shortest_path(G, weight=as_distance)
|
| 107 |
+
else:
|
| 108 |
+
shortest_paths = nx.shortest_path(G)
|
| 109 |
+
|
| 110 |
+
centrality = local_reaching_centrality
|
| 111 |
+
# TODO This can be trivially parallelized.
|
| 112 |
+
lrc = [
|
| 113 |
+
centrality(G, node, paths=paths, weight=weight, normalized=normalized)
|
| 114 |
+
for node, paths in shortest_paths.items()
|
| 115 |
+
]
|
| 116 |
+
|
| 117 |
+
max_lrc = max(lrc)
|
| 118 |
+
return sum(max_lrc - c for c in lrc) / (len(G) - 1)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def local_reaching_centrality(G, v, paths=None, weight=None, normalized=True):
|
| 122 |
+
"""Returns the local reaching centrality of a node in a directed
|
| 123 |
+
graph.
|
| 124 |
+
|
| 125 |
+
The *local reaching centrality* of a node in a directed graph is the
|
| 126 |
+
proportion of other nodes reachable from that node [1]_.
|
| 127 |
+
|
| 128 |
+
Parameters
|
| 129 |
+
----------
|
| 130 |
+
G : DiGraph
|
| 131 |
+
A NetworkX DiGraph.
|
| 132 |
+
|
| 133 |
+
v : node
|
| 134 |
+
A node in the directed graph `G`.
|
| 135 |
+
|
| 136 |
+
paths : dictionary (default=None)
|
| 137 |
+
If this is not `None` it must be a dictionary representation
|
| 138 |
+
of single-source shortest paths, as computed by, for example,
|
| 139 |
+
:func:`networkx.shortest_path` with source node `v`. Use this
|
| 140 |
+
keyword argument if you intend to invoke this function many
|
| 141 |
+
times but don't want the paths to be recomputed each time.
|
| 142 |
+
|
| 143 |
+
weight : None or string, optional (default=None)
|
| 144 |
+
Attribute to use for edge weights. If `None`, each edge weight
|
| 145 |
+
is assumed to be one. A higher weight implies a stronger
|
| 146 |
+
connection between nodes and a *shorter* path length.
|
| 147 |
+
|
| 148 |
+
normalized : bool, optional (default=True)
|
| 149 |
+
Whether to normalize the edge weights by the total sum of edge
|
| 150 |
+
weights.
|
| 151 |
+
|
| 152 |
+
Returns
|
| 153 |
+
-------
|
| 154 |
+
h : float
|
| 155 |
+
The local reaching centrality of the node ``v`` in the graph
|
| 156 |
+
``G``.
|
| 157 |
+
|
| 158 |
+
Examples
|
| 159 |
+
--------
|
| 160 |
+
>>> G = nx.DiGraph()
|
| 161 |
+
>>> G.add_edges_from([(1, 2), (1, 3)])
|
| 162 |
+
>>> nx.local_reaching_centrality(G, 3)
|
| 163 |
+
0.0
|
| 164 |
+
>>> G.add_edge(3, 2)
|
| 165 |
+
>>> nx.local_reaching_centrality(G, 3)
|
| 166 |
+
0.5
|
| 167 |
+
|
| 168 |
+
See also
|
| 169 |
+
--------
|
| 170 |
+
global_reaching_centrality
|
| 171 |
+
|
| 172 |
+
References
|
| 173 |
+
----------
|
| 174 |
+
.. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek.
|
| 175 |
+
"Hierarchy Measure for Complex Networks."
|
| 176 |
+
*PLoS ONE* 7.3 (2012): e33799.
|
| 177 |
+
https://doi.org/10.1371/journal.pone.0033799
|
| 178 |
+
"""
|
| 179 |
+
if paths is None:
|
| 180 |
+
if nx.is_negatively_weighted(G, weight=weight):
|
| 181 |
+
raise nx.NetworkXError("edge weights must be positive")
|
| 182 |
+
total_weight = G.size(weight=weight)
|
| 183 |
+
if total_weight <= 0:
|
| 184 |
+
raise nx.NetworkXError("Size of G must be positive")
|
| 185 |
+
if weight is not None:
|
| 186 |
+
# Interpret weights as lengths.
|
| 187 |
+
def as_distance(u, v, d):
|
| 188 |
+
return total_weight / d.get(weight, 1)
|
| 189 |
+
|
| 190 |
+
paths = nx.shortest_path(G, source=v, weight=as_distance)
|
| 191 |
+
else:
|
| 192 |
+
paths = nx.shortest_path(G, source=v)
|
| 193 |
+
# If the graph is unweighted, simply return the proportion of nodes
|
| 194 |
+
# reachable from the source node ``v``.
|
| 195 |
+
if weight is None and G.is_directed():
|
| 196 |
+
return (len(paths) - 1) / (len(G) - 1)
|
| 197 |
+
if normalized and weight is not None:
|
| 198 |
+
norm = G.size(weight=weight) / G.size()
|
| 199 |
+
else:
|
| 200 |
+
norm = 1
|
| 201 |
+
# TODO This can be trivially parallelized.
|
| 202 |
+
avgw = (_average_weight(G, path, weight=weight) for path in paths.values())
|
| 203 |
+
sum_avg_weight = sum(avgw) / norm
|
| 204 |
+
return sum_avg_weight / (len(G) - 1)
|
shared/package-files/24/242443b3bdc867472e27cea8a2650b10e1278d85dcd9e892ff68bde81fe2dabd/q_per_channel_scales.h
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/q_per_channel_scales_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::q_per_channel_scales(Tensor self) -> Tensor
|
| 26 |
+
inline at::Tensor q_per_channel_scales(const at::Tensor & self) {
|
| 27 |
+
return at::_ops::q_per_channel_scales::call(self);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// aten::q_per_channel_scales.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
|
| 31 |
+
inline at::Tensor & q_per_channel_scales_out(at::Tensor & out, const at::Tensor & self) {
|
| 32 |
+
return at::_ops::q_per_channel_scales_out::call(self, out);
|
| 33 |
+
}
|
| 34 |
+
// aten::q_per_channel_scales.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
|
| 35 |
+
inline at::Tensor & q_per_channel_scales_outf(const at::Tensor & self, at::Tensor & out) {
|
| 36 |
+
return at::_ops::q_per_channel_scales_out::call(self, out);
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
}
|
shared/package-files/24/2429fc58747ec180ecf23879f08199e932d28a4e73b86b3110e6a57b5997e414/cyk.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This module implements a CYK parser."""
|
| 2 |
+
|
| 3 |
+
# Author: https://github.com/ehudt (2018)
|
| 4 |
+
#
|
| 5 |
+
# Adapted by Erez
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
import itertools
|
| 10 |
+
|
| 11 |
+
from ..exceptions import ParseError
|
| 12 |
+
from ..lexer import Token
|
| 13 |
+
from ..tree import Tree
|
| 14 |
+
from ..grammar import Terminal as T, NonTerminal as NT, Symbol
|
| 15 |
+
|
| 16 |
+
def match(t, s):
|
| 17 |
+
assert isinstance(t, T)
|
| 18 |
+
return t.name == s.type
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Rule:
|
| 22 |
+
"""Context-free grammar rule."""
|
| 23 |
+
|
| 24 |
+
def __init__(self, lhs, rhs, weight, alias):
|
| 25 |
+
super(Rule, self).__init__()
|
| 26 |
+
assert isinstance(lhs, NT), lhs
|
| 27 |
+
assert all(isinstance(x, NT) or isinstance(x, T) for x in rhs), rhs
|
| 28 |
+
self.lhs = lhs
|
| 29 |
+
self.rhs = rhs
|
| 30 |
+
self.weight = weight
|
| 31 |
+
self.alias = alias
|
| 32 |
+
|
| 33 |
+
def __str__(self):
|
| 34 |
+
return '%s -> %s' % (str(self.lhs), ' '.join(str(x) for x in self.rhs))
|
| 35 |
+
|
| 36 |
+
def __repr__(self):
|
| 37 |
+
return str(self)
|
| 38 |
+
|
| 39 |
+
def __hash__(self):
|
| 40 |
+
return hash((self.lhs, tuple(self.rhs)))
|
| 41 |
+
|
| 42 |
+
def __eq__(self, other):
|
| 43 |
+
return self.lhs == other.lhs and self.rhs == other.rhs
|
| 44 |
+
|
| 45 |
+
def __ne__(self, other):
|
| 46 |
+
return not (self == other)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Grammar:
|
| 50 |
+
"""Context-free grammar."""
|
| 51 |
+
|
| 52 |
+
def __init__(self, rules):
|
| 53 |
+
self.rules = frozenset(rules)
|
| 54 |
+
|
| 55 |
+
def __eq__(self, other):
|
| 56 |
+
return self.rules == other.rules
|
| 57 |
+
|
| 58 |
+
def __str__(self):
|
| 59 |
+
return '\n' + '\n'.join(sorted(repr(x) for x in self.rules)) + '\n'
|
| 60 |
+
|
| 61 |
+
def __repr__(self):
|
| 62 |
+
return str(self)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# Parse tree data structures
|
| 66 |
+
class RuleNode:
|
| 67 |
+
"""A node in the parse tree, which also contains the full rhs rule."""
|
| 68 |
+
|
| 69 |
+
def __init__(self, rule, children, weight=0):
|
| 70 |
+
self.rule = rule
|
| 71 |
+
self.children = children
|
| 72 |
+
self.weight = weight
|
| 73 |
+
|
| 74 |
+
def __repr__(self):
|
| 75 |
+
return 'RuleNode(%s, [%s])' % (repr(self.rule.lhs), ', '.join(str(x) for x in self.children))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class Parser:
|
| 80 |
+
"""Parser wrapper."""
|
| 81 |
+
|
| 82 |
+
def __init__(self, rules):
|
| 83 |
+
super(Parser, self).__init__()
|
| 84 |
+
self.orig_rules = {rule: rule for rule in rules}
|
| 85 |
+
rules = [self._to_rule(rule) for rule in rules]
|
| 86 |
+
self.grammar = to_cnf(Grammar(rules))
|
| 87 |
+
|
| 88 |
+
def _to_rule(self, lark_rule):
|
| 89 |
+
"""Converts a lark rule, (lhs, rhs, callback, options), to a Rule."""
|
| 90 |
+
assert isinstance(lark_rule.origin, NT)
|
| 91 |
+
assert all(isinstance(x, Symbol) for x in lark_rule.expansion)
|
| 92 |
+
return Rule(
|
| 93 |
+
lark_rule.origin, lark_rule.expansion,
|
| 94 |
+
weight=lark_rule.options.priority if lark_rule.options.priority else 0,
|
| 95 |
+
alias=lark_rule)
|
| 96 |
+
|
| 97 |
+
def parse(self, tokenized, start): # pylint: disable=invalid-name
|
| 98 |
+
"""Parses input, which is a list of tokens."""
|
| 99 |
+
assert start
|
| 100 |
+
start = NT(start)
|
| 101 |
+
|
| 102 |
+
table, trees = _parse(tokenized, self.grammar)
|
| 103 |
+
# Check if the parse succeeded.
|
| 104 |
+
if all(r.lhs != start for r in table[(0, len(tokenized) - 1)]):
|
| 105 |
+
raise ParseError('Parsing failed.')
|
| 106 |
+
parse = trees[(0, len(tokenized) - 1)][start]
|
| 107 |
+
return self._to_tree(revert_cnf(parse))
|
| 108 |
+
|
| 109 |
+
def _to_tree(self, rule_node):
|
| 110 |
+
"""Converts a RuleNode parse tree to a lark Tree."""
|
| 111 |
+
orig_rule = self.orig_rules[rule_node.rule.alias]
|
| 112 |
+
children = []
|
| 113 |
+
for child in rule_node.children:
|
| 114 |
+
if isinstance(child, RuleNode):
|
| 115 |
+
children.append(self._to_tree(child))
|
| 116 |
+
else:
|
| 117 |
+
assert isinstance(child.name, Token)
|
| 118 |
+
children.append(child.name)
|
| 119 |
+
t = Tree(orig_rule.origin, children)
|
| 120 |
+
t.rule=orig_rule
|
| 121 |
+
return t
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def print_parse(node, indent=0):
|
| 125 |
+
if isinstance(node, RuleNode):
|
| 126 |
+
print(' ' * (indent * 2) + str(node.rule.lhs))
|
| 127 |
+
for child in node.children:
|
| 128 |
+
print_parse(child, indent + 1)
|
| 129 |
+
else:
|
| 130 |
+
print(' ' * (indent * 2) + str(node.s))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _parse(s, g):
|
| 134 |
+
"""Parses sentence 's' using CNF grammar 'g'."""
|
| 135 |
+
# The CYK table. Indexed with a 2-tuple: (start pos, end pos)
|
| 136 |
+
table = defaultdict(set)
|
| 137 |
+
# Top-level structure is similar to the CYK table. Each cell is a dict from
|
| 138 |
+
# rule name to the best (lightest) tree for that rule.
|
| 139 |
+
trees = defaultdict(dict)
|
| 140 |
+
# Populate base case with existing terminal production rules
|
| 141 |
+
for i, w in enumerate(s):
|
| 142 |
+
for terminal, rules in g.terminal_rules.items():
|
| 143 |
+
if match(terminal, w):
|
| 144 |
+
for rule in rules:
|
| 145 |
+
table[(i, i)].add(rule)
|
| 146 |
+
if (rule.lhs not in trees[(i, i)] or
|
| 147 |
+
rule.weight < trees[(i, i)][rule.lhs].weight):
|
| 148 |
+
trees[(i, i)][rule.lhs] = RuleNode(rule, [T(w)], weight=rule.weight)
|
| 149 |
+
|
| 150 |
+
# Iterate over lengths of sub-sentences
|
| 151 |
+
for l in range(2, len(s) + 1):
|
| 152 |
+
# Iterate over sub-sentences with the given length
|
| 153 |
+
for i in range(len(s) - l + 1):
|
| 154 |
+
# Choose partition of the sub-sentence in [1, l)
|
| 155 |
+
for p in range(i + 1, i + l):
|
| 156 |
+
span1 = (i, p - 1)
|
| 157 |
+
span2 = (p, i + l - 1)
|
| 158 |
+
for r1, r2 in itertools.product(table[span1], table[span2]):
|
| 159 |
+
for rule in g.nonterminal_rules.get((r1.lhs, r2.lhs), []):
|
| 160 |
+
table[(i, i + l - 1)].add(rule)
|
| 161 |
+
r1_tree = trees[span1][r1.lhs]
|
| 162 |
+
r2_tree = trees[span2][r2.lhs]
|
| 163 |
+
rule_total_weight = rule.weight + r1_tree.weight + r2_tree.weight
|
| 164 |
+
if (rule.lhs not in trees[(i, i + l - 1)]
|
| 165 |
+
or rule_total_weight < trees[(i, i + l - 1)][rule.lhs].weight):
|
| 166 |
+
trees[(i, i + l - 1)][rule.lhs] = RuleNode(rule, [r1_tree, r2_tree], weight=rule_total_weight)
|
| 167 |
+
return table, trees
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
# This section implements context-free grammar converter to Chomsky normal form.
|
| 171 |
+
# It also implements a conversion of parse trees from its CNF to the original
|
| 172 |
+
# grammar.
|
| 173 |
+
# Overview:
|
| 174 |
+
# Applies the following operations in this order:
|
| 175 |
+
# * TERM: Eliminates non-solitary terminals from all rules
|
| 176 |
+
# * BIN: Eliminates rules with more than 2 symbols on their right-hand-side.
|
| 177 |
+
# * UNIT: Eliminates non-terminal unit rules
|
| 178 |
+
#
|
| 179 |
+
# The following grammar characteristics aren't featured:
|
| 180 |
+
# * Start symbol appears on RHS
|
| 181 |
+
# * Empty rules (epsilon rules)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class CnfWrapper:
|
| 185 |
+
"""CNF wrapper for grammar.
|
| 186 |
+
|
| 187 |
+
Validates that the input grammar is CNF and provides helper data structures.
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
def __init__(self, grammar):
|
| 191 |
+
super(CnfWrapper, self).__init__()
|
| 192 |
+
self.grammar = grammar
|
| 193 |
+
self.rules = grammar.rules
|
| 194 |
+
self.terminal_rules = defaultdict(list)
|
| 195 |
+
self.nonterminal_rules = defaultdict(list)
|
| 196 |
+
for r in self.rules:
|
| 197 |
+
# Validate that the grammar is CNF and populate auxiliary data structures.
|
| 198 |
+
assert isinstance(r.lhs, NT), r
|
| 199 |
+
if len(r.rhs) not in [1, 2]:
|
| 200 |
+
raise ParseError("CYK doesn't support empty rules")
|
| 201 |
+
if len(r.rhs) == 1 and isinstance(r.rhs[0], T):
|
| 202 |
+
self.terminal_rules[r.rhs[0]].append(r)
|
| 203 |
+
elif len(r.rhs) == 2 and all(isinstance(x, NT) for x in r.rhs):
|
| 204 |
+
self.nonterminal_rules[tuple(r.rhs)].append(r)
|
| 205 |
+
else:
|
| 206 |
+
assert False, r
|
| 207 |
+
|
| 208 |
+
def __eq__(self, other):
|
| 209 |
+
return self.grammar == other.grammar
|
| 210 |
+
|
| 211 |
+
def __repr__(self):
|
| 212 |
+
return repr(self.grammar)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class UnitSkipRule(Rule):
|
| 216 |
+
"""A rule that records NTs that were skipped during transformation."""
|
| 217 |
+
|
| 218 |
+
def __init__(self, lhs, rhs, skipped_rules, weight, alias):
|
| 219 |
+
super(UnitSkipRule, self).__init__(lhs, rhs, weight, alias)
|
| 220 |
+
self.skipped_rules = skipped_rules
|
| 221 |
+
|
| 222 |
+
def __eq__(self, other):
|
| 223 |
+
return isinstance(other, type(self)) and self.skipped_rules == other.skipped_rules
|
| 224 |
+
|
| 225 |
+
__hash__ = Rule.__hash__
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def build_unit_skiprule(unit_rule, target_rule):
|
| 229 |
+
skipped_rules = []
|
| 230 |
+
if isinstance(unit_rule, UnitSkipRule):
|
| 231 |
+
skipped_rules += unit_rule.skipped_rules
|
| 232 |
+
skipped_rules.append(target_rule)
|
| 233 |
+
if isinstance(target_rule, UnitSkipRule):
|
| 234 |
+
skipped_rules += target_rule.skipped_rules
|
| 235 |
+
return UnitSkipRule(unit_rule.lhs, target_rule.rhs, skipped_rules,
|
| 236 |
+
weight=unit_rule.weight + target_rule.weight, alias=unit_rule.alias)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def get_any_nt_unit_rule(g):
|
| 240 |
+
"""Returns a non-terminal unit rule from 'g', or None if there is none."""
|
| 241 |
+
for rule in g.rules:
|
| 242 |
+
if len(rule.rhs) == 1 and isinstance(rule.rhs[0], NT):
|
| 243 |
+
return rule
|
| 244 |
+
return None
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _remove_unit_rule(g, rule):
|
| 248 |
+
"""Removes 'rule' from 'g' without changing the language produced by 'g'."""
|
| 249 |
+
new_rules = [x for x in g.rules if x != rule]
|
| 250 |
+
refs = [x for x in g.rules if x.lhs == rule.rhs[0]]
|
| 251 |
+
new_rules += [build_unit_skiprule(rule, ref) for ref in refs]
|
| 252 |
+
return Grammar(new_rules)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def _split(rule):
|
| 256 |
+
"""Splits a rule whose len(rhs) > 2 into shorter rules."""
|
| 257 |
+
rule_str = str(rule.lhs) + '__' + '_'.join(str(x) for x in rule.rhs)
|
| 258 |
+
rule_name = '__SP_%s' % (rule_str) + '_%d'
|
| 259 |
+
yield Rule(rule.lhs, [rule.rhs[0], NT(rule_name % 1)], weight=rule.weight, alias=rule.alias)
|
| 260 |
+
for i in range(1, len(rule.rhs) - 2):
|
| 261 |
+
yield Rule(NT(rule_name % i), [rule.rhs[i], NT(rule_name % (i + 1))], weight=0, alias='Split')
|
| 262 |
+
yield Rule(NT(rule_name % (len(rule.rhs) - 2)), rule.rhs[-2:], weight=0, alias='Split')
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _term(g):
|
| 266 |
+
"""Applies the TERM rule on 'g' (see top comment)."""
|
| 267 |
+
all_t = {x for rule in g.rules for x in rule.rhs if isinstance(x, T)}
|
| 268 |
+
t_rules = {t: Rule(NT('__T_%s' % str(t)), [t], weight=0, alias='Term') for t in all_t}
|
| 269 |
+
new_rules = []
|
| 270 |
+
for rule in g.rules:
|
| 271 |
+
if len(rule.rhs) > 1 and any(isinstance(x, T) for x in rule.rhs):
|
| 272 |
+
new_rhs = [t_rules[x].lhs if isinstance(x, T) else x for x in rule.rhs]
|
| 273 |
+
new_rules.append(Rule(rule.lhs, new_rhs, weight=rule.weight, alias=rule.alias))
|
| 274 |
+
new_rules.extend(v for k, v in t_rules.items() if k in rule.rhs)
|
| 275 |
+
else:
|
| 276 |
+
new_rules.append(rule)
|
| 277 |
+
return Grammar(new_rules)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def _bin(g):
|
| 281 |
+
"""Applies the BIN rule to 'g' (see top comment)."""
|
| 282 |
+
new_rules = []
|
| 283 |
+
for rule in g.rules:
|
| 284 |
+
if len(rule.rhs) > 2:
|
| 285 |
+
new_rules += _split(rule)
|
| 286 |
+
else:
|
| 287 |
+
new_rules.append(rule)
|
| 288 |
+
return Grammar(new_rules)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def _unit(g):
|
| 292 |
+
"""Applies the UNIT rule to 'g' (see top comment)."""
|
| 293 |
+
nt_unit_rule = get_any_nt_unit_rule(g)
|
| 294 |
+
while nt_unit_rule:
|
| 295 |
+
g = _remove_unit_rule(g, nt_unit_rule)
|
| 296 |
+
nt_unit_rule = get_any_nt_unit_rule(g)
|
| 297 |
+
return g
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def to_cnf(g):
|
| 301 |
+
"""Creates a CNF grammar from a general context-free grammar 'g'."""
|
| 302 |
+
g = _unit(_bin(_term(g)))
|
| 303 |
+
return CnfWrapper(g)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def unroll_unit_skiprule(lhs, orig_rhs, skipped_rules, children, weight, alias):
|
| 307 |
+
if not skipped_rules:
|
| 308 |
+
return RuleNode(Rule(lhs, orig_rhs, weight=weight, alias=alias), children, weight=weight)
|
| 309 |
+
else:
|
| 310 |
+
weight = weight - skipped_rules[0].weight
|
| 311 |
+
return RuleNode(
|
| 312 |
+
Rule(lhs, [skipped_rules[0].lhs], weight=weight, alias=alias), [
|
| 313 |
+
unroll_unit_skiprule(skipped_rules[0].lhs, orig_rhs,
|
| 314 |
+
skipped_rules[1:], children,
|
| 315 |
+
skipped_rules[0].weight, skipped_rules[0].alias)
|
| 316 |
+
], weight=weight)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def revert_cnf(node):
|
| 320 |
+
"""Reverts a parse tree (RuleNode) to its original non-CNF form (Node)."""
|
| 321 |
+
if isinstance(node, T):
|
| 322 |
+
return node
|
| 323 |
+
# Reverts TERM rule.
|
| 324 |
+
if node.rule.lhs.name.startswith('__T_'):
|
| 325 |
+
return node.children[0]
|
| 326 |
+
else:
|
| 327 |
+
children = []
|
| 328 |
+
for child in map(revert_cnf, node.children):
|
| 329 |
+
# Reverts BIN rule.
|
| 330 |
+
if isinstance(child, RuleNode) and child.rule.lhs.name.startswith('__SP_'):
|
| 331 |
+
children += child.children
|
| 332 |
+
else:
|
| 333 |
+
children.append(child)
|
| 334 |
+
# Reverts UNIT rule.
|
| 335 |
+
if isinstance(node.rule, UnitSkipRule):
|
| 336 |
+
return unroll_unit_skiprule(node.rule.lhs, node.rule.rhs,
|
| 337 |
+
node.rule.skipped_rules, children,
|
| 338 |
+
node.rule.weight, node.rule.alias)
|
| 339 |
+
else:
|
| 340 |
+
return RuleNode(node.rule, children)
|
shared/package-files/24/242cfa28c340e230ca7a721f8b46762a156954e6f56f3cc196d133ee84ce5e5c/evalpoly.h
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Translated from Cython into C++ by SciPy developers in 2024.
|
| 2 |
+
*
|
| 3 |
+
* Original author: Josh Wilson, 2016.
|
| 4 |
+
*/
|
| 5 |
+
|
| 6 |
+
/* Evaluate polynomials.
|
| 7 |
+
*
|
| 8 |
+
* All of the coefficients are stored in reverse order, i.e. if the
|
| 9 |
+
* polynomial is
|
| 10 |
+
*
|
| 11 |
+
* u_n x^n + u_{n - 1} x^{n - 1} + ... + u_0,
|
| 12 |
+
*
|
| 13 |
+
* then coeffs[0] = u_n, coeffs[1] = u_{n - 1}, ..., coeffs[n] = u_0.
|
| 14 |
+
*
|
| 15 |
+
* References
|
| 16 |
+
* ----------
|
| 17 |
+
* [1] Knuth, "The Art of Computer Programming, Volume II"
|
| 18 |
+
*/
|
| 19 |
+
|
| 20 |
+
#pragma once
|
| 21 |
+
|
| 22 |
+
#include "config.h"
|
| 23 |
+
|
| 24 |
+
namespace xsf {
|
| 25 |
+
|
| 26 |
+
XSF_HOST_DEVICE inline std::complex<double> cevalpoly(const double *coeffs, int degree, std::complex<double> z) {
|
| 27 |
+
/* Evaluate a polynomial with real coefficients at a complex point.
|
| 28 |
+
*
|
| 29 |
+
* Uses equation (3) in section 4.6.4 of [1]. Note that it is more
|
| 30 |
+
* efficient than Horner's method.
|
| 31 |
+
*/
|
| 32 |
+
double a = coeffs[0];
|
| 33 |
+
double b = coeffs[1];
|
| 34 |
+
double r = 2 * z.real();
|
| 35 |
+
double s = std::norm(z);
|
| 36 |
+
double tmp;
|
| 37 |
+
|
| 38 |
+
for (int j = 2; j < degree + 1; j++) {
|
| 39 |
+
tmp = b;
|
| 40 |
+
b = std::fma(-s, a, coeffs[j]);
|
| 41 |
+
a = std::fma(r, a, tmp);
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
return z * a + b;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
} // namespace xsf
|
shared/package-files/24/242d057d55ec9c1da56476fe9c66f24a7c6fffd5470320f498a68b0e8c1ccc55/gh21665.f90
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module fortfuncs
|
| 2 |
+
implicit none
|
| 3 |
+
contains
|
| 4 |
+
subroutine square(x,y)
|
| 5 |
+
integer, intent(in), value :: x
|
| 6 |
+
integer, intent(out) :: y
|
| 7 |
+
y = x*x
|
| 8 |
+
end subroutine square
|
| 9 |
+
end module fortfuncs
|
shared/package-files/24/2434fd89260c74b25f22debe4869340d8597173f49305e1621927e24ad009251/retains_grad.h
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/retains_grad_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
}
|
shared/package-files/24/243a14b3dc356d899eeda1bf789d5c0adb2d453583ef50731bc8918be1b67871/entry_points.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
hypothesis = hypothesis.extra.cli:main
|
| 3 |
+
|
| 4 |
+
[pytest11]
|
| 5 |
+
hypothesispytest = _hypothesis_pytestplugin
|
shared/package-files/24/243abe485005fa96b0727700f1b0aa58512605d43c9f58fd3c751ecb8058fe74/test_openml.py
ADDED
|
@@ -0,0 +1,1636 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test the openml loader."""
|
| 2 |
+
|
| 3 |
+
import gzip
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
from functools import partial
|
| 8 |
+
from importlib import resources
|
| 9 |
+
from io import BytesIO
|
| 10 |
+
from urllib.error import HTTPError
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import pytest
|
| 14 |
+
import scipy.sparse
|
| 15 |
+
|
| 16 |
+
import sklearn
|
| 17 |
+
from sklearn import config_context
|
| 18 |
+
from sklearn.datasets import fetch_openml as fetch_openml_orig
|
| 19 |
+
from sklearn.datasets._openml import (
|
| 20 |
+
_get_local_path,
|
| 21 |
+
_open_openml_url,
|
| 22 |
+
_retry_with_clean_cache,
|
| 23 |
+
)
|
| 24 |
+
from sklearn.utils import Bunch
|
| 25 |
+
from sklearn.utils._optional_dependencies import check_pandas_support
|
| 26 |
+
from sklearn.utils._testing import (
|
| 27 |
+
SkipTest,
|
| 28 |
+
assert_allclose,
|
| 29 |
+
assert_array_equal,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
OPENML_TEST_DATA_MODULE = "sklearn.datasets.tests.data.openml"
|
| 33 |
+
# if True, urlopen will be monkey patched to only use local files
|
| 34 |
+
test_offline = True
|
| 35 |
+
_MONKEY_PATCH_LOCAL_OPENML_PATH = "data/v1/download/{}"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class _MockHTTPResponse:
|
| 39 |
+
def __init__(self, data, is_gzip):
|
| 40 |
+
self.data = data
|
| 41 |
+
self.is_gzip = is_gzip
|
| 42 |
+
|
| 43 |
+
def read(self, amt=-1):
|
| 44 |
+
return self.data.read(amt)
|
| 45 |
+
|
| 46 |
+
def close(self):
|
| 47 |
+
self.data.close()
|
| 48 |
+
|
| 49 |
+
def info(self):
|
| 50 |
+
if self.is_gzip:
|
| 51 |
+
return {"Content-Encoding": "gzip"}
|
| 52 |
+
return {}
|
| 53 |
+
|
| 54 |
+
def __iter__(self):
|
| 55 |
+
return iter(self.data)
|
| 56 |
+
|
| 57 |
+
def __enter__(self):
|
| 58 |
+
return self
|
| 59 |
+
|
| 60 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 61 |
+
return False
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# Disable the disk-based cache when testing `fetch_openml`:
|
| 65 |
+
# the mock data in sklearn/datasets/tests/data/openml/ is not always consistent
|
| 66 |
+
# with the version on openml.org. If one were to load the dataset outside of
|
| 67 |
+
# the tests, it may result in data that does not represent openml.org.
|
| 68 |
+
fetch_openml = partial(fetch_openml_orig, data_home=None)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _monkey_patch_webbased_functions(context, data_id, gzip_response):
|
| 72 |
+
# monkey patches the urlopen function. Important note: Do NOT use this
|
| 73 |
+
# in combination with a regular cache directory, as the files that are
|
| 74 |
+
# stored as cache should not be mixed up with real openml datasets
|
| 75 |
+
url_prefix_data_description = "https://api.openml.org/api/v1/json/data/"
|
| 76 |
+
url_prefix_data_features = "https://api.openml.org/api/v1/json/data/features/"
|
| 77 |
+
url_prefix_download_data = "https://www.openml.org/data/v1/download"
|
| 78 |
+
url_prefix_data_list = "https://api.openml.org/api/v1/json/data/list/"
|
| 79 |
+
|
| 80 |
+
path_suffix = ".gz"
|
| 81 |
+
read_fn = gzip.open
|
| 82 |
+
|
| 83 |
+
data_module = OPENML_TEST_DATA_MODULE + "." + f"id_{data_id}"
|
| 84 |
+
|
| 85 |
+
def _file_name(url, suffix):
|
| 86 |
+
output = (
|
| 87 |
+
re.sub(r"\W", "-", url[len("https://api.openml.org/") :])
|
| 88 |
+
+ suffix
|
| 89 |
+
+ path_suffix
|
| 90 |
+
)
|
| 91 |
+
# Shorten the filenames to have better compatibility with windows 10
|
| 92 |
+
# and filenames > 260 characters
|
| 93 |
+
return (
|
| 94 |
+
output.replace("-json-data-list", "-jdl")
|
| 95 |
+
.replace("-json-data-features", "-jdf")
|
| 96 |
+
.replace("-json-data-qualities", "-jdq")
|
| 97 |
+
.replace("-json-data", "-jd")
|
| 98 |
+
.replace("-data_name", "-dn")
|
| 99 |
+
.replace("-download", "-dl")
|
| 100 |
+
.replace("-limit", "-l")
|
| 101 |
+
.replace("-data_version", "-dv")
|
| 102 |
+
.replace("-status", "-s")
|
| 103 |
+
.replace("-deactivated", "-dact")
|
| 104 |
+
.replace("-active", "-act")
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
def _mock_urlopen_shared(url, has_gzip_header, expected_prefix, suffix):
|
| 108 |
+
assert url.startswith(expected_prefix), (
|
| 109 |
+
f"{expected_prefix!r} does not match {url!r}"
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
data_file_name = _file_name(url, suffix)
|
| 113 |
+
data_file_path = resources.files(data_module) / data_file_name
|
| 114 |
+
|
| 115 |
+
with data_file_path.open("rb") as f:
|
| 116 |
+
if has_gzip_header and gzip_response:
|
| 117 |
+
fp = BytesIO(f.read())
|
| 118 |
+
return _MockHTTPResponse(fp, True)
|
| 119 |
+
else:
|
| 120 |
+
decompressed_f = read_fn(f, "rb")
|
| 121 |
+
fp = BytesIO(decompressed_f.read())
|
| 122 |
+
return _MockHTTPResponse(fp, False)
|
| 123 |
+
|
| 124 |
+
def _mock_urlopen_data_description(url, has_gzip_header):
|
| 125 |
+
return _mock_urlopen_shared(
|
| 126 |
+
url=url,
|
| 127 |
+
has_gzip_header=has_gzip_header,
|
| 128 |
+
expected_prefix=url_prefix_data_description,
|
| 129 |
+
suffix=".json",
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
def _mock_urlopen_data_features(url, has_gzip_header):
|
| 133 |
+
return _mock_urlopen_shared(
|
| 134 |
+
url=url,
|
| 135 |
+
has_gzip_header=has_gzip_header,
|
| 136 |
+
expected_prefix=url_prefix_data_features,
|
| 137 |
+
suffix=".json",
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def _mock_urlopen_download_data(url, has_gzip_header):
|
| 141 |
+
# For simplicity the mock filenames don't contain the filename, i.e.
|
| 142 |
+
# the last part of the data description url after the last /.
|
| 143 |
+
# For example for id_1, data description download url is:
|
| 144 |
+
# gunzip -c sklearn/datasets/tests/data/openml/id_1/api-v1-jd-1.json.gz | grep '"url" # noqa: E501
|
| 145 |
+
# "https:\/\/www.openml.org\/data\/v1\/download\/1\/anneal.arff"
|
| 146 |
+
# but the mock filename does not contain anneal.arff and is:
|
| 147 |
+
# sklearn/datasets/tests/data/openml/id_1/data-v1-dl-1.arff.gz.
|
| 148 |
+
# We only keep the part of the url before the last /
|
| 149 |
+
url_without_filename = url.rsplit("/", 1)[0]
|
| 150 |
+
|
| 151 |
+
return _mock_urlopen_shared(
|
| 152 |
+
url=url_without_filename,
|
| 153 |
+
has_gzip_header=has_gzip_header,
|
| 154 |
+
expected_prefix=url_prefix_download_data,
|
| 155 |
+
suffix=".arff",
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
def _mock_urlopen_data_list(url, has_gzip_header):
|
| 159 |
+
assert url.startswith(url_prefix_data_list), (
|
| 160 |
+
f"{url_prefix_data_list!r} does not match {url!r}"
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
data_file_name = _file_name(url, ".json")
|
| 164 |
+
data_file_path = resources.files(data_module) / data_file_name
|
| 165 |
+
|
| 166 |
+
# load the file itself, to simulate a http error
|
| 167 |
+
with data_file_path.open("rb") as f:
|
| 168 |
+
decompressed_f = read_fn(f, "rb")
|
| 169 |
+
decoded_s = decompressed_f.read().decode("utf-8")
|
| 170 |
+
json_data = json.loads(decoded_s)
|
| 171 |
+
if "error" in json_data:
|
| 172 |
+
raise HTTPError(
|
| 173 |
+
url=None, code=412, msg="Simulated mock error", hdrs=None, fp=BytesIO()
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
with data_file_path.open("rb") as f:
|
| 177 |
+
if has_gzip_header:
|
| 178 |
+
fp = BytesIO(f.read())
|
| 179 |
+
return _MockHTTPResponse(fp, True)
|
| 180 |
+
else:
|
| 181 |
+
decompressed_f = read_fn(f, "rb")
|
| 182 |
+
fp = BytesIO(decompressed_f.read())
|
| 183 |
+
return _MockHTTPResponse(fp, False)
|
| 184 |
+
|
| 185 |
+
def _mock_urlopen(request, *args, **kwargs):
|
| 186 |
+
url = request.get_full_url()
|
| 187 |
+
has_gzip_header = request.get_header("Accept-encoding") == "gzip"
|
| 188 |
+
if url.startswith(url_prefix_data_list):
|
| 189 |
+
return _mock_urlopen_data_list(url, has_gzip_header)
|
| 190 |
+
elif url.startswith(url_prefix_data_features):
|
| 191 |
+
return _mock_urlopen_data_features(url, has_gzip_header)
|
| 192 |
+
elif url.startswith(url_prefix_download_data):
|
| 193 |
+
return _mock_urlopen_download_data(url, has_gzip_header)
|
| 194 |
+
elif url.startswith(url_prefix_data_description):
|
| 195 |
+
return _mock_urlopen_data_description(url, has_gzip_header)
|
| 196 |
+
else:
|
| 197 |
+
raise ValueError("Unknown mocking URL pattern: %s" % url)
|
| 198 |
+
|
| 199 |
+
# XXX: Global variable
|
| 200 |
+
if test_offline:
|
| 201 |
+
context.setattr(sklearn.datasets._openml, "urlopen", _mock_urlopen)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
###############################################################################
|
| 205 |
+
# Test the behaviour of `fetch_openml` depending of the input parameters.
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@pytest.mark.parametrize(
|
| 209 |
+
"data_id, dataset_params, n_samples, n_features, n_targets",
|
| 210 |
+
[
|
| 211 |
+
# iris
|
| 212 |
+
(61, {"data_id": 61}, 150, 4, 1),
|
| 213 |
+
(61, {"name": "iris", "version": 1}, 150, 4, 1),
|
| 214 |
+
# anneal
|
| 215 |
+
(2, {"data_id": 2}, 11, 38, 1),
|
| 216 |
+
(2, {"name": "anneal", "version": 1}, 11, 38, 1),
|
| 217 |
+
# cpu
|
| 218 |
+
(561, {"data_id": 561}, 209, 7, 1),
|
| 219 |
+
(561, {"name": "cpu", "version": 1}, 209, 7, 1),
|
| 220 |
+
# emotions
|
| 221 |
+
(40589, {"data_id": 40589}, 13, 72, 6),
|
| 222 |
+
# adult-census
|
| 223 |
+
(1119, {"data_id": 1119}, 10, 14, 1),
|
| 224 |
+
(1119, {"name": "adult-census"}, 10, 14, 1),
|
| 225 |
+
# miceprotein
|
| 226 |
+
(40966, {"data_id": 40966}, 7, 77, 1),
|
| 227 |
+
(40966, {"name": "MiceProtein"}, 7, 77, 1),
|
| 228 |
+
# titanic
|
| 229 |
+
(40945, {"data_id": 40945}, 1309, 13, 1),
|
| 230 |
+
],
|
| 231 |
+
)
|
| 232 |
+
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
|
| 233 |
+
@pytest.mark.parametrize("gzip_response", [True, False])
|
| 234 |
+
def test_fetch_openml_as_frame_true(
|
| 235 |
+
monkeypatch,
|
| 236 |
+
data_id,
|
| 237 |
+
dataset_params,
|
| 238 |
+
n_samples,
|
| 239 |
+
n_features,
|
| 240 |
+
n_targets,
|
| 241 |
+
parser,
|
| 242 |
+
gzip_response,
|
| 243 |
+
):
|
| 244 |
+
"""Check the behaviour of `fetch_openml` with `as_frame=True`.
|
| 245 |
+
|
| 246 |
+
Fetch by ID and/or name (depending if the file was previously cached).
|
| 247 |
+
"""
|
| 248 |
+
pd = pytest.importorskip("pandas")
|
| 249 |
+
|
| 250 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=gzip_response)
|
| 251 |
+
bunch = fetch_openml(
|
| 252 |
+
as_frame=True,
|
| 253 |
+
cache=False,
|
| 254 |
+
parser=parser,
|
| 255 |
+
**dataset_params,
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
assert int(bunch.details["id"]) == data_id
|
| 259 |
+
assert isinstance(bunch, Bunch)
|
| 260 |
+
|
| 261 |
+
assert isinstance(bunch.frame, pd.DataFrame)
|
| 262 |
+
assert bunch.frame.shape == (n_samples, n_features + n_targets)
|
| 263 |
+
|
| 264 |
+
assert isinstance(bunch.data, pd.DataFrame)
|
| 265 |
+
assert bunch.data.shape == (n_samples, n_features)
|
| 266 |
+
|
| 267 |
+
if n_targets == 1:
|
| 268 |
+
assert isinstance(bunch.target, pd.Series)
|
| 269 |
+
assert bunch.target.shape == (n_samples,)
|
| 270 |
+
else:
|
| 271 |
+
assert isinstance(bunch.target, pd.DataFrame)
|
| 272 |
+
assert bunch.target.shape == (n_samples, n_targets)
|
| 273 |
+
|
| 274 |
+
assert bunch.categories is None
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@pytest.mark.parametrize(
|
| 278 |
+
"data_id, dataset_params, n_samples, n_features, n_targets",
|
| 279 |
+
[
|
| 280 |
+
# iris
|
| 281 |
+
(61, {"data_id": 61}, 150, 4, 1),
|
| 282 |
+
(61, {"name": "iris", "version": 1}, 150, 4, 1),
|
| 283 |
+
# anneal
|
| 284 |
+
(2, {"data_id": 2}, 11, 38, 1),
|
| 285 |
+
(2, {"name": "anneal", "version": 1}, 11, 38, 1),
|
| 286 |
+
# cpu
|
| 287 |
+
(561, {"data_id": 561}, 209, 7, 1),
|
| 288 |
+
(561, {"name": "cpu", "version": 1}, 209, 7, 1),
|
| 289 |
+
# emotions
|
| 290 |
+
(40589, {"data_id": 40589}, 13, 72, 6),
|
| 291 |
+
# adult-census
|
| 292 |
+
(1119, {"data_id": 1119}, 10, 14, 1),
|
| 293 |
+
(1119, {"name": "adult-census"}, 10, 14, 1),
|
| 294 |
+
# miceprotein
|
| 295 |
+
(40966, {"data_id": 40966}, 7, 77, 1),
|
| 296 |
+
(40966, {"name": "MiceProtein"}, 7, 77, 1),
|
| 297 |
+
],
|
| 298 |
+
)
|
| 299 |
+
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
|
| 300 |
+
def test_fetch_openml_as_frame_false(
|
| 301 |
+
monkeypatch,
|
| 302 |
+
data_id,
|
| 303 |
+
dataset_params,
|
| 304 |
+
n_samples,
|
| 305 |
+
n_features,
|
| 306 |
+
n_targets,
|
| 307 |
+
parser,
|
| 308 |
+
):
|
| 309 |
+
"""Check the behaviour of `fetch_openml` with `as_frame=False`.
|
| 310 |
+
|
| 311 |
+
Fetch both by ID and/or name + version.
|
| 312 |
+
"""
|
| 313 |
+
pytest.importorskip("pandas")
|
| 314 |
+
|
| 315 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
|
| 316 |
+
bunch = fetch_openml(
|
| 317 |
+
as_frame=False,
|
| 318 |
+
cache=False,
|
| 319 |
+
parser=parser,
|
| 320 |
+
**dataset_params,
|
| 321 |
+
)
|
| 322 |
+
assert int(bunch.details["id"]) == data_id
|
| 323 |
+
assert isinstance(bunch, Bunch)
|
| 324 |
+
|
| 325 |
+
assert bunch.frame is None
|
| 326 |
+
|
| 327 |
+
assert isinstance(bunch.data, np.ndarray)
|
| 328 |
+
assert bunch.data.shape == (n_samples, n_features)
|
| 329 |
+
|
| 330 |
+
assert isinstance(bunch.target, np.ndarray)
|
| 331 |
+
if n_targets == 1:
|
| 332 |
+
assert bunch.target.shape == (n_samples,)
|
| 333 |
+
else:
|
| 334 |
+
assert bunch.target.shape == (n_samples, n_targets)
|
| 335 |
+
|
| 336 |
+
assert isinstance(bunch.categories, dict)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@pytest.mark.parametrize("data_id", [61, 1119, 40945])
|
| 340 |
+
def test_fetch_openml_consistency_parser(monkeypatch, data_id):
|
| 341 |
+
"""Check the consistency of the LIAC-ARFF and pandas parsers."""
|
| 342 |
+
pd = pytest.importorskip("pandas")
|
| 343 |
+
|
| 344 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
|
| 345 |
+
bunch_liac = fetch_openml(
|
| 346 |
+
data_id=data_id,
|
| 347 |
+
as_frame=True,
|
| 348 |
+
cache=False,
|
| 349 |
+
parser="liac-arff",
|
| 350 |
+
)
|
| 351 |
+
bunch_pandas = fetch_openml(
|
| 352 |
+
data_id=data_id,
|
| 353 |
+
as_frame=True,
|
| 354 |
+
cache=False,
|
| 355 |
+
parser="pandas",
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
# The data frames for the input features should match up to some numerical
|
| 359 |
+
# dtype conversions (e.g. float64 <=> Int64) due to limitations of the
|
| 360 |
+
# LIAC-ARFF parser.
|
| 361 |
+
data_liac, data_pandas = bunch_liac.data, bunch_pandas.data
|
| 362 |
+
|
| 363 |
+
def convert_numerical_dtypes(series):
|
| 364 |
+
pandas_series = data_pandas[series.name]
|
| 365 |
+
if pd.api.types.is_numeric_dtype(pandas_series):
|
| 366 |
+
return series.astype(pandas_series.dtype)
|
| 367 |
+
else:
|
| 368 |
+
return series
|
| 369 |
+
|
| 370 |
+
data_liac_with_fixed_dtypes = data_liac.apply(convert_numerical_dtypes)
|
| 371 |
+
pd.testing.assert_frame_equal(data_liac_with_fixed_dtypes, data_pandas)
|
| 372 |
+
|
| 373 |
+
# Let's also check that the .frame attributes also match
|
| 374 |
+
frame_liac, frame_pandas = bunch_liac.frame, bunch_pandas.frame
|
| 375 |
+
|
| 376 |
+
# Note that the .frame attribute is a superset of the .data attribute:
|
| 377 |
+
pd.testing.assert_frame_equal(frame_pandas[bunch_pandas.feature_names], data_pandas)
|
| 378 |
+
|
| 379 |
+
# However the remaining columns, typically the target(s), are not necessarily
|
| 380 |
+
# dtyped similarly by both parsers due to limitations of the LIAC-ARFF parser.
|
| 381 |
+
# Therefore, extra dtype conversions are required for those columns:
|
| 382 |
+
|
| 383 |
+
def convert_numerical_and_categorical_dtypes(series):
|
| 384 |
+
pandas_series = frame_pandas[series.name]
|
| 385 |
+
if pd.api.types.is_numeric_dtype(pandas_series):
|
| 386 |
+
return series.astype(pandas_series.dtype)
|
| 387 |
+
elif isinstance(pandas_series.dtype, pd.CategoricalDtype):
|
| 388 |
+
# Compare categorical features by converting categorical liac uses
|
| 389 |
+
# strings to denote the categories, we rename the categories to make
|
| 390 |
+
# them comparable to the pandas parser. Fixing this behavior in
|
| 391 |
+
# LIAC-ARFF would allow to check the consistency in the future but
|
| 392 |
+
# we do not plan to maintain the LIAC-ARFF on the long term.
|
| 393 |
+
return series.cat.rename_categories(pandas_series.cat.categories)
|
| 394 |
+
else:
|
| 395 |
+
return series
|
| 396 |
+
|
| 397 |
+
frame_liac_with_fixed_dtypes = frame_liac.apply(
|
| 398 |
+
convert_numerical_and_categorical_dtypes
|
| 399 |
+
)
|
| 400 |
+
pd.testing.assert_frame_equal(frame_liac_with_fixed_dtypes, frame_pandas)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
|
| 404 |
+
def test_fetch_openml_equivalence_array_dataframe(monkeypatch, parser):
|
| 405 |
+
"""Check the equivalence of the dataset when using `as_frame=False` and
|
| 406 |
+
`as_frame=True`.
|
| 407 |
+
"""
|
| 408 |
+
pytest.importorskip("pandas")
|
| 409 |
+
|
| 410 |
+
data_id = 61
|
| 411 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
|
| 412 |
+
bunch_as_frame_true = fetch_openml(
|
| 413 |
+
data_id=data_id,
|
| 414 |
+
as_frame=True,
|
| 415 |
+
cache=False,
|
| 416 |
+
parser=parser,
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
bunch_as_frame_false = fetch_openml(
|
| 420 |
+
data_id=data_id,
|
| 421 |
+
as_frame=False,
|
| 422 |
+
cache=False,
|
| 423 |
+
parser=parser,
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
assert_allclose(bunch_as_frame_false.data, bunch_as_frame_true.data)
|
| 427 |
+
assert_array_equal(bunch_as_frame_false.target, bunch_as_frame_true.target)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
|
| 431 |
+
def test_fetch_openml_iris_pandas(monkeypatch, parser):
|
| 432 |
+
"""Check fetching on a numerical only dataset with string labels."""
|
| 433 |
+
pd = pytest.importorskip("pandas")
|
| 434 |
+
CategoricalDtype = pd.api.types.CategoricalDtype
|
| 435 |
+
data_id = 61
|
| 436 |
+
data_shape = (150, 4)
|
| 437 |
+
target_shape = (150,)
|
| 438 |
+
frame_shape = (150, 5)
|
| 439 |
+
|
| 440 |
+
target_dtype = CategoricalDtype(
|
| 441 |
+
["Iris-setosa", "Iris-versicolor", "Iris-virginica"]
|
| 442 |
+
)
|
| 443 |
+
data_dtypes = [np.float64] * 4
|
| 444 |
+
data_names = ["sepallength", "sepalwidth", "petallength", "petalwidth"]
|
| 445 |
+
target_name = "class"
|
| 446 |
+
|
| 447 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, True)
|
| 448 |
+
|
| 449 |
+
bunch = fetch_openml(
|
| 450 |
+
data_id=data_id,
|
| 451 |
+
as_frame=True,
|
| 452 |
+
cache=False,
|
| 453 |
+
parser=parser,
|
| 454 |
+
)
|
| 455 |
+
data = bunch.data
|
| 456 |
+
target = bunch.target
|
| 457 |
+
frame = bunch.frame
|
| 458 |
+
|
| 459 |
+
assert isinstance(data, pd.DataFrame)
|
| 460 |
+
assert np.all(data.dtypes == data_dtypes)
|
| 461 |
+
assert data.shape == data_shape
|
| 462 |
+
assert np.all(data.columns == data_names)
|
| 463 |
+
assert np.all(bunch.feature_names == data_names)
|
| 464 |
+
assert bunch.target_names == [target_name]
|
| 465 |
+
|
| 466 |
+
assert isinstance(target, pd.Series)
|
| 467 |
+
assert target.dtype == target_dtype
|
| 468 |
+
assert target.shape == target_shape
|
| 469 |
+
assert target.name == target_name
|
| 470 |
+
assert target.index.is_unique
|
| 471 |
+
|
| 472 |
+
assert isinstance(frame, pd.DataFrame)
|
| 473 |
+
assert frame.shape == frame_shape
|
| 474 |
+
assert np.all(frame.dtypes == data_dtypes + [target_dtype])
|
| 475 |
+
assert frame.index.is_unique
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
|
| 479 |
+
@pytest.mark.parametrize("target_column", ["petalwidth", ["petalwidth", "petallength"]])
|
| 480 |
+
def test_fetch_openml_forcing_targets(monkeypatch, parser, target_column):
|
| 481 |
+
"""Check that we can force the target to not be the default target."""
|
| 482 |
+
pd = pytest.importorskip("pandas")
|
| 483 |
+
|
| 484 |
+
data_id = 61
|
| 485 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, True)
|
| 486 |
+
bunch_forcing_target = fetch_openml(
|
| 487 |
+
data_id=data_id,
|
| 488 |
+
as_frame=True,
|
| 489 |
+
cache=False,
|
| 490 |
+
target_column=target_column,
|
| 491 |
+
parser=parser,
|
| 492 |
+
)
|
| 493 |
+
bunch_default = fetch_openml(
|
| 494 |
+
data_id=data_id,
|
| 495 |
+
as_frame=True,
|
| 496 |
+
cache=False,
|
| 497 |
+
parser=parser,
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
pd.testing.assert_frame_equal(bunch_forcing_target.frame, bunch_default.frame)
|
| 501 |
+
if isinstance(target_column, list):
|
| 502 |
+
pd.testing.assert_index_equal(
|
| 503 |
+
bunch_forcing_target.target.columns, pd.Index(target_column)
|
| 504 |
+
)
|
| 505 |
+
assert bunch_forcing_target.data.shape == (150, 3)
|
| 506 |
+
else:
|
| 507 |
+
assert bunch_forcing_target.target.name == target_column
|
| 508 |
+
assert bunch_forcing_target.data.shape == (150, 4)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
@pytest.mark.parametrize("data_id", [61, 2, 561, 40589, 1119])
|
| 512 |
+
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
|
| 513 |
+
def test_fetch_openml_equivalence_frame_return_X_y(monkeypatch, data_id, parser):
|
| 514 |
+
"""Check the behaviour of `return_X_y=True` when `as_frame=True`."""
|
| 515 |
+
pd = pytest.importorskip("pandas")
|
| 516 |
+
|
| 517 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
|
| 518 |
+
bunch = fetch_openml(
|
| 519 |
+
data_id=data_id,
|
| 520 |
+
as_frame=True,
|
| 521 |
+
cache=False,
|
| 522 |
+
return_X_y=False,
|
| 523 |
+
parser=parser,
|
| 524 |
+
)
|
| 525 |
+
X, y = fetch_openml(
|
| 526 |
+
data_id=data_id,
|
| 527 |
+
as_frame=True,
|
| 528 |
+
cache=False,
|
| 529 |
+
return_X_y=True,
|
| 530 |
+
parser=parser,
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
pd.testing.assert_frame_equal(bunch.data, X)
|
| 534 |
+
if isinstance(y, pd.Series):
|
| 535 |
+
pd.testing.assert_series_equal(bunch.target, y)
|
| 536 |
+
else:
|
| 537 |
+
pd.testing.assert_frame_equal(bunch.target, y)
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
@pytest.mark.parametrize("data_id", [61, 561, 40589, 1119])
|
| 541 |
+
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
|
| 542 |
+
def test_fetch_openml_equivalence_array_return_X_y(monkeypatch, data_id, parser):
|
| 543 |
+
"""Check the behaviour of `return_X_y=True` when `as_frame=False`."""
|
| 544 |
+
pytest.importorskip("pandas")
|
| 545 |
+
|
| 546 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
|
| 547 |
+
bunch = fetch_openml(
|
| 548 |
+
data_id=data_id,
|
| 549 |
+
as_frame=False,
|
| 550 |
+
cache=False,
|
| 551 |
+
return_X_y=False,
|
| 552 |
+
parser=parser,
|
| 553 |
+
)
|
| 554 |
+
X, y = fetch_openml(
|
| 555 |
+
data_id=data_id,
|
| 556 |
+
as_frame=False,
|
| 557 |
+
cache=False,
|
| 558 |
+
return_X_y=True,
|
| 559 |
+
parser=parser,
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
assert_array_equal(bunch.data, X)
|
| 563 |
+
assert_array_equal(bunch.target, y)
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def test_fetch_openml_difference_parsers(monkeypatch):
|
| 567 |
+
"""Check the difference between liac-arff and pandas parser."""
|
| 568 |
+
pytest.importorskip("pandas")
|
| 569 |
+
|
| 570 |
+
data_id = 1119
|
| 571 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
|
| 572 |
+
# When `as_frame=False`, the categories will be ordinally encoded with
|
| 573 |
+
# liac-arff parser while this is not the case with pandas parser.
|
| 574 |
+
as_frame = False
|
| 575 |
+
bunch_liac_arff = fetch_openml(
|
| 576 |
+
data_id=data_id,
|
| 577 |
+
as_frame=as_frame,
|
| 578 |
+
cache=False,
|
| 579 |
+
parser="liac-arff",
|
| 580 |
+
)
|
| 581 |
+
bunch_pandas = fetch_openml(
|
| 582 |
+
data_id=data_id,
|
| 583 |
+
as_frame=as_frame,
|
| 584 |
+
cache=False,
|
| 585 |
+
parser="pandas",
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
assert bunch_liac_arff.data.dtype.kind == "f"
|
| 589 |
+
assert bunch_pandas.data.dtype == "O"
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
###############################################################################
|
| 593 |
+
# Test the ARFF parsing on several dataset to check if detect the correct
|
| 594 |
+
# types (categories, integers, floats).
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
@pytest.fixture(scope="module")
|
| 598 |
+
def datasets_column_names():
|
| 599 |
+
"""Returns the columns names for each dataset."""
|
| 600 |
+
return {
|
| 601 |
+
61: ["sepallength", "sepalwidth", "petallength", "petalwidth", "class"],
|
| 602 |
+
2: [
|
| 603 |
+
"family",
|
| 604 |
+
"product-type",
|
| 605 |
+
"steel",
|
| 606 |
+
"carbon",
|
| 607 |
+
"hardness",
|
| 608 |
+
"temper_rolling",
|
| 609 |
+
"condition",
|
| 610 |
+
"formability",
|
| 611 |
+
"strength",
|
| 612 |
+
"non-ageing",
|
| 613 |
+
"surface-finish",
|
| 614 |
+
"surface-quality",
|
| 615 |
+
"enamelability",
|
| 616 |
+
"bc",
|
| 617 |
+
"bf",
|
| 618 |
+
"bt",
|
| 619 |
+
"bw%2Fme",
|
| 620 |
+
"bl",
|
| 621 |
+
"m",
|
| 622 |
+
"chrom",
|
| 623 |
+
"phos",
|
| 624 |
+
"cbond",
|
| 625 |
+
"marvi",
|
| 626 |
+
"exptl",
|
| 627 |
+
"ferro",
|
| 628 |
+
"corr",
|
| 629 |
+
"blue%2Fbright%2Fvarn%2Fclean",
|
| 630 |
+
"lustre",
|
| 631 |
+
"jurofm",
|
| 632 |
+
"s",
|
| 633 |
+
"p",
|
| 634 |
+
"shape",
|
| 635 |
+
"thick",
|
| 636 |
+
"width",
|
| 637 |
+
"len",
|
| 638 |
+
"oil",
|
| 639 |
+
"bore",
|
| 640 |
+
"packing",
|
| 641 |
+
"class",
|
| 642 |
+
],
|
| 643 |
+
561: ["vendor", "MYCT", "MMIN", "MMAX", "CACH", "CHMIN", "CHMAX", "class"],
|
| 644 |
+
40589: [
|
| 645 |
+
"Mean_Acc1298_Mean_Mem40_Centroid",
|
| 646 |
+
"Mean_Acc1298_Mean_Mem40_Rolloff",
|
| 647 |
+
"Mean_Acc1298_Mean_Mem40_Flux",
|
| 648 |
+
"Mean_Acc1298_Mean_Mem40_MFCC_0",
|
| 649 |
+
"Mean_Acc1298_Mean_Mem40_MFCC_1",
|
| 650 |
+
"Mean_Acc1298_Mean_Mem40_MFCC_2",
|
| 651 |
+
"Mean_Acc1298_Mean_Mem40_MFCC_3",
|
| 652 |
+
"Mean_Acc1298_Mean_Mem40_MFCC_4",
|
| 653 |
+
"Mean_Acc1298_Mean_Mem40_MFCC_5",
|
| 654 |
+
"Mean_Acc1298_Mean_Mem40_MFCC_6",
|
| 655 |
+
"Mean_Acc1298_Mean_Mem40_MFCC_7",
|
| 656 |
+
"Mean_Acc1298_Mean_Mem40_MFCC_8",
|
| 657 |
+
"Mean_Acc1298_Mean_Mem40_MFCC_9",
|
| 658 |
+
"Mean_Acc1298_Mean_Mem40_MFCC_10",
|
| 659 |
+
"Mean_Acc1298_Mean_Mem40_MFCC_11",
|
| 660 |
+
"Mean_Acc1298_Mean_Mem40_MFCC_12",
|
| 661 |
+
"Mean_Acc1298_Std_Mem40_Centroid",
|
| 662 |
+
"Mean_Acc1298_Std_Mem40_Rolloff",
|
| 663 |
+
"Mean_Acc1298_Std_Mem40_Flux",
|
| 664 |
+
"Mean_Acc1298_Std_Mem40_MFCC_0",
|
| 665 |
+
"Mean_Acc1298_Std_Mem40_MFCC_1",
|
| 666 |
+
"Mean_Acc1298_Std_Mem40_MFCC_2",
|
| 667 |
+
"Mean_Acc1298_Std_Mem40_MFCC_3",
|
| 668 |
+
"Mean_Acc1298_Std_Mem40_MFCC_4",
|
| 669 |
+
"Mean_Acc1298_Std_Mem40_MFCC_5",
|
| 670 |
+
"Mean_Acc1298_Std_Mem40_MFCC_6",
|
| 671 |
+
"Mean_Acc1298_Std_Mem40_MFCC_7",
|
| 672 |
+
"Mean_Acc1298_Std_Mem40_MFCC_8",
|
| 673 |
+
"Mean_Acc1298_Std_Mem40_MFCC_9",
|
| 674 |
+
"Mean_Acc1298_Std_Mem40_MFCC_10",
|
| 675 |
+
"Mean_Acc1298_Std_Mem40_MFCC_11",
|
| 676 |
+
"Mean_Acc1298_Std_Mem40_MFCC_12",
|
| 677 |
+
"Std_Acc1298_Mean_Mem40_Centroid",
|
| 678 |
+
"Std_Acc1298_Mean_Mem40_Rolloff",
|
| 679 |
+
"Std_Acc1298_Mean_Mem40_Flux",
|
| 680 |
+
"Std_Acc1298_Mean_Mem40_MFCC_0",
|
| 681 |
+
"Std_Acc1298_Mean_Mem40_MFCC_1",
|
| 682 |
+
"Std_Acc1298_Mean_Mem40_MFCC_2",
|
| 683 |
+
"Std_Acc1298_Mean_Mem40_MFCC_3",
|
| 684 |
+
"Std_Acc1298_Mean_Mem40_MFCC_4",
|
| 685 |
+
"Std_Acc1298_Mean_Mem40_MFCC_5",
|
| 686 |
+
"Std_Acc1298_Mean_Mem40_MFCC_6",
|
| 687 |
+
"Std_Acc1298_Mean_Mem40_MFCC_7",
|
| 688 |
+
"Std_Acc1298_Mean_Mem40_MFCC_8",
|
| 689 |
+
"Std_Acc1298_Mean_Mem40_MFCC_9",
|
| 690 |
+
"Std_Acc1298_Mean_Mem40_MFCC_10",
|
| 691 |
+
"Std_Acc1298_Mean_Mem40_MFCC_11",
|
| 692 |
+
"Std_Acc1298_Mean_Mem40_MFCC_12",
|
| 693 |
+
"Std_Acc1298_Std_Mem40_Centroid",
|
| 694 |
+
"Std_Acc1298_Std_Mem40_Rolloff",
|
| 695 |
+
"Std_Acc1298_Std_Mem40_Flux",
|
| 696 |
+
"Std_Acc1298_Std_Mem40_MFCC_0",
|
| 697 |
+
"Std_Acc1298_Std_Mem40_MFCC_1",
|
| 698 |
+
"Std_Acc1298_Std_Mem40_MFCC_2",
|
| 699 |
+
"Std_Acc1298_Std_Mem40_MFCC_3",
|
| 700 |
+
"Std_Acc1298_Std_Mem40_MFCC_4",
|
| 701 |
+
"Std_Acc1298_Std_Mem40_MFCC_5",
|
| 702 |
+
"Std_Acc1298_Std_Mem40_MFCC_6",
|
| 703 |
+
"Std_Acc1298_Std_Mem40_MFCC_7",
|
| 704 |
+
"Std_Acc1298_Std_Mem40_MFCC_8",
|
| 705 |
+
"Std_Acc1298_Std_Mem40_MFCC_9",
|
| 706 |
+
"Std_Acc1298_Std_Mem40_MFCC_10",
|
| 707 |
+
"Std_Acc1298_Std_Mem40_MFCC_11",
|
| 708 |
+
"Std_Acc1298_Std_Mem40_MFCC_12",
|
| 709 |
+
"BH_LowPeakAmp",
|
| 710 |
+
"BH_LowPeakBPM",
|
| 711 |
+
"BH_HighPeakAmp",
|
| 712 |
+
"BH_HighPeakBPM",
|
| 713 |
+
"BH_HighLowRatio",
|
| 714 |
+
"BHSUM1",
|
| 715 |
+
"BHSUM2",
|
| 716 |
+
"BHSUM3",
|
| 717 |
+
"amazed.suprised",
|
| 718 |
+
"happy.pleased",
|
| 719 |
+
"relaxing.calm",
|
| 720 |
+
"quiet.still",
|
| 721 |
+
"sad.lonely",
|
| 722 |
+
"angry.aggresive",
|
| 723 |
+
],
|
| 724 |
+
1119: [
|
| 725 |
+
"age",
|
| 726 |
+
"workclass",
|
| 727 |
+
"fnlwgt:",
|
| 728 |
+
"education:",
|
| 729 |
+
"education-num:",
|
| 730 |
+
"marital-status:",
|
| 731 |
+
"occupation:",
|
| 732 |
+
"relationship:",
|
| 733 |
+
"race:",
|
| 734 |
+
"sex:",
|
| 735 |
+
"capital-gain:",
|
| 736 |
+
"capital-loss:",
|
| 737 |
+
"hours-per-week:",
|
| 738 |
+
"native-country:",
|
| 739 |
+
"class",
|
| 740 |
+
],
|
| 741 |
+
40966: [
|
| 742 |
+
"DYRK1A_N",
|
| 743 |
+
"ITSN1_N",
|
| 744 |
+
"BDNF_N",
|
| 745 |
+
"NR1_N",
|
| 746 |
+
"NR2A_N",
|
| 747 |
+
"pAKT_N",
|
| 748 |
+
"pBRAF_N",
|
| 749 |
+
"pCAMKII_N",
|
| 750 |
+
"pCREB_N",
|
| 751 |
+
"pELK_N",
|
| 752 |
+
"pERK_N",
|
| 753 |
+
"pJNK_N",
|
| 754 |
+
"PKCA_N",
|
| 755 |
+
"pMEK_N",
|
| 756 |
+
"pNR1_N",
|
| 757 |
+
"pNR2A_N",
|
| 758 |
+
"pNR2B_N",
|
| 759 |
+
"pPKCAB_N",
|
| 760 |
+
"pRSK_N",
|
| 761 |
+
"AKT_N",
|
| 762 |
+
"BRAF_N",
|
| 763 |
+
"CAMKII_N",
|
| 764 |
+
"CREB_N",
|
| 765 |
+
"ELK_N",
|
| 766 |
+
"ERK_N",
|
| 767 |
+
"GSK3B_N",
|
| 768 |
+
"JNK_N",
|
| 769 |
+
"MEK_N",
|
| 770 |
+
"TRKA_N",
|
| 771 |
+
"RSK_N",
|
| 772 |
+
"APP_N",
|
| 773 |
+
"Bcatenin_N",
|
| 774 |
+
"SOD1_N",
|
| 775 |
+
"MTOR_N",
|
| 776 |
+
"P38_N",
|
| 777 |
+
"pMTOR_N",
|
| 778 |
+
"DSCR1_N",
|
| 779 |
+
"AMPKA_N",
|
| 780 |
+
"NR2B_N",
|
| 781 |
+
"pNUMB_N",
|
| 782 |
+
"RAPTOR_N",
|
| 783 |
+
"TIAM1_N",
|
| 784 |
+
"pP70S6_N",
|
| 785 |
+
"NUMB_N",
|
| 786 |
+
"P70S6_N",
|
| 787 |
+
"pGSK3B_N",
|
| 788 |
+
"pPKCG_N",
|
| 789 |
+
"CDK5_N",
|
| 790 |
+
"S6_N",
|
| 791 |
+
"ADARB1_N",
|
| 792 |
+
"AcetylH3K9_N",
|
| 793 |
+
"RRP1_N",
|
| 794 |
+
"BAX_N",
|
| 795 |
+
"ARC_N",
|
| 796 |
+
"ERBB4_N",
|
| 797 |
+
"nNOS_N",
|
| 798 |
+
"Tau_N",
|
| 799 |
+
"GFAP_N",
|
| 800 |
+
"GluR3_N",
|
| 801 |
+
"GluR4_N",
|
| 802 |
+
"IL1B_N",
|
| 803 |
+
"P3525_N",
|
| 804 |
+
"pCASP9_N",
|
| 805 |
+
"PSD95_N",
|
| 806 |
+
"SNCA_N",
|
| 807 |
+
"Ubiquitin_N",
|
| 808 |
+
"pGSK3B_Tyr216_N",
|
| 809 |
+
"SHH_N",
|
| 810 |
+
"BAD_N",
|
| 811 |
+
"BCL2_N",
|
| 812 |
+
"pS6_N",
|
| 813 |
+
"pCFOS_N",
|
| 814 |
+
"SYP_N",
|
| 815 |
+
"H3AcK18_N",
|
| 816 |
+
"EGR1_N",
|
| 817 |
+
"H3MeK4_N",
|
| 818 |
+
"CaNA_N",
|
| 819 |
+
"class",
|
| 820 |
+
],
|
| 821 |
+
40945: [
|
| 822 |
+
"pclass",
|
| 823 |
+
"survived",
|
| 824 |
+
"name",
|
| 825 |
+
"sex",
|
| 826 |
+
"age",
|
| 827 |
+
"sibsp",
|
| 828 |
+
"parch",
|
| 829 |
+
"ticket",
|
| 830 |
+
"fare",
|
| 831 |
+
"cabin",
|
| 832 |
+
"embarked",
|
| 833 |
+
"boat",
|
| 834 |
+
"body",
|
| 835 |
+
"home.dest",
|
| 836 |
+
],
|
| 837 |
+
}
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
@pytest.fixture(scope="module")
|
| 841 |
+
def datasets_missing_values():
|
| 842 |
+
return {
|
| 843 |
+
61: {},
|
| 844 |
+
2: {
|
| 845 |
+
"family": 11,
|
| 846 |
+
"temper_rolling": 9,
|
| 847 |
+
"condition": 2,
|
| 848 |
+
"formability": 4,
|
| 849 |
+
"non-ageing": 10,
|
| 850 |
+
"surface-finish": 11,
|
| 851 |
+
"enamelability": 11,
|
| 852 |
+
"bc": 11,
|
| 853 |
+
"bf": 10,
|
| 854 |
+
"bt": 11,
|
| 855 |
+
"bw%2Fme": 8,
|
| 856 |
+
"bl": 9,
|
| 857 |
+
"m": 11,
|
| 858 |
+
"chrom": 11,
|
| 859 |
+
"phos": 11,
|
| 860 |
+
"cbond": 10,
|
| 861 |
+
"marvi": 11,
|
| 862 |
+
"exptl": 11,
|
| 863 |
+
"ferro": 11,
|
| 864 |
+
"corr": 11,
|
| 865 |
+
"blue%2Fbright%2Fvarn%2Fclean": 11,
|
| 866 |
+
"lustre": 8,
|
| 867 |
+
"jurofm": 11,
|
| 868 |
+
"s": 11,
|
| 869 |
+
"p": 11,
|
| 870 |
+
"oil": 10,
|
| 871 |
+
"packing": 11,
|
| 872 |
+
},
|
| 873 |
+
561: {},
|
| 874 |
+
40589: {},
|
| 875 |
+
1119: {},
|
| 876 |
+
40966: {"BCL2_N": 7},
|
| 877 |
+
40945: {
|
| 878 |
+
"age": 263,
|
| 879 |
+
"fare": 1,
|
| 880 |
+
"cabin": 1014,
|
| 881 |
+
"embarked": 2,
|
| 882 |
+
"boat": 823,
|
| 883 |
+
"body": 1188,
|
| 884 |
+
"home.dest": 564,
|
| 885 |
+
},
|
| 886 |
+
}
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
@pytest.mark.parametrize(
|
| 890 |
+
"data_id, parser, expected_n_categories, expected_n_floats, expected_n_ints",
|
| 891 |
+
[
|
| 892 |
+
# iris dataset
|
| 893 |
+
(61, "liac-arff", 1, 4, 0),
|
| 894 |
+
(61, "pandas", 1, 4, 0),
|
| 895 |
+
# anneal dataset
|
| 896 |
+
(2, "liac-arff", 33, 6, 0),
|
| 897 |
+
(2, "pandas", 33, 2, 4),
|
| 898 |
+
# cpu dataset
|
| 899 |
+
(561, "liac-arff", 1, 7, 0),
|
| 900 |
+
(561, "pandas", 1, 0, 7),
|
| 901 |
+
# emotions dataset
|
| 902 |
+
(40589, "liac-arff", 6, 72, 0),
|
| 903 |
+
(40589, "pandas", 6, 69, 3),
|
| 904 |
+
# adult-census dataset
|
| 905 |
+
(1119, "liac-arff", 9, 6, 0),
|
| 906 |
+
(1119, "pandas", 9, 0, 6),
|
| 907 |
+
# miceprotein
|
| 908 |
+
(40966, "liac-arff", 1, 77, 0),
|
| 909 |
+
(40966, "pandas", 1, 77, 0),
|
| 910 |
+
# titanic
|
| 911 |
+
(40945, "liac-arff", 3, 6, 0),
|
| 912 |
+
(40945, "pandas", 3, 3, 3),
|
| 913 |
+
],
|
| 914 |
+
)
|
| 915 |
+
@pytest.mark.parametrize("gzip_response", [True, False])
|
| 916 |
+
def test_fetch_openml_types_inference(
|
| 917 |
+
monkeypatch,
|
| 918 |
+
data_id,
|
| 919 |
+
parser,
|
| 920 |
+
expected_n_categories,
|
| 921 |
+
expected_n_floats,
|
| 922 |
+
expected_n_ints,
|
| 923 |
+
gzip_response,
|
| 924 |
+
datasets_column_names,
|
| 925 |
+
datasets_missing_values,
|
| 926 |
+
):
|
| 927 |
+
"""Check that `fetch_openml` infer the right number of categories, integers, and
|
| 928 |
+
floats."""
|
| 929 |
+
pd = pytest.importorskip("pandas")
|
| 930 |
+
CategoricalDtype = pd.api.types.CategoricalDtype
|
| 931 |
+
|
| 932 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=gzip_response)
|
| 933 |
+
|
| 934 |
+
bunch = fetch_openml(
|
| 935 |
+
data_id=data_id,
|
| 936 |
+
as_frame=True,
|
| 937 |
+
cache=False,
|
| 938 |
+
parser=parser,
|
| 939 |
+
)
|
| 940 |
+
frame = bunch.frame
|
| 941 |
+
|
| 942 |
+
n_categories = len(
|
| 943 |
+
[dtype for dtype in frame.dtypes if isinstance(dtype, CategoricalDtype)]
|
| 944 |
+
)
|
| 945 |
+
n_floats = len([dtype for dtype in frame.dtypes if dtype.kind == "f"])
|
| 946 |
+
n_ints = len([dtype for dtype in frame.dtypes if dtype.kind == "i"])
|
| 947 |
+
|
| 948 |
+
assert n_categories == expected_n_categories
|
| 949 |
+
assert n_floats == expected_n_floats
|
| 950 |
+
assert n_ints == expected_n_ints
|
| 951 |
+
|
| 952 |
+
assert frame.columns.tolist() == datasets_column_names[data_id]
|
| 953 |
+
|
| 954 |
+
frame_feature_to_n_nan = frame.isna().sum().to_dict()
|
| 955 |
+
for name, n_missing in frame_feature_to_n_nan.items():
|
| 956 |
+
expected_missing = datasets_missing_values[data_id].get(name, 0)
|
| 957 |
+
assert n_missing == expected_missing
|
| 958 |
+
|
| 959 |
+
|
| 960 |
+
###############################################################################
|
| 961 |
+
# Test some more specific behaviour
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
@pytest.mark.parametrize(
|
| 965 |
+
"params, err_msg",
|
| 966 |
+
[
|
| 967 |
+
(
|
| 968 |
+
{"parser": "unknown"},
|
| 969 |
+
"The 'parser' parameter of fetch_openml must be a str among",
|
| 970 |
+
),
|
| 971 |
+
(
|
| 972 |
+
{"as_frame": "unknown"},
|
| 973 |
+
"The 'as_frame' parameter of fetch_openml must be an instance",
|
| 974 |
+
),
|
| 975 |
+
],
|
| 976 |
+
)
|
| 977 |
+
def test_fetch_openml_validation_parameter(monkeypatch, params, err_msg):
|
| 978 |
+
data_id = 1119
|
| 979 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, True)
|
| 980 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 981 |
+
fetch_openml(data_id=data_id, **params)
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
@pytest.mark.parametrize(
|
| 985 |
+
"params",
|
| 986 |
+
[
|
| 987 |
+
{"as_frame": True, "parser": "auto"},
|
| 988 |
+
{"as_frame": "auto", "parser": "auto"},
|
| 989 |
+
{"as_frame": False, "parser": "pandas"},
|
| 990 |
+
{"as_frame": False, "parser": "auto"},
|
| 991 |
+
],
|
| 992 |
+
)
|
| 993 |
+
def test_fetch_openml_requires_pandas_error(monkeypatch, params):
|
| 994 |
+
"""Check that we raise the proper errors when we require pandas."""
|
| 995 |
+
data_id = 1119
|
| 996 |
+
try:
|
| 997 |
+
check_pandas_support("test_fetch_openml_requires_pandas")
|
| 998 |
+
except ImportError:
|
| 999 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, True)
|
| 1000 |
+
err_msg = "requires pandas to be installed. Alternatively, explicitly"
|
| 1001 |
+
with pytest.raises(ImportError, match=err_msg):
|
| 1002 |
+
fetch_openml(data_id=data_id, **params)
|
| 1003 |
+
else:
|
| 1004 |
+
raise SkipTest("This test requires pandas to not be installed.")
|
| 1005 |
+
|
| 1006 |
+
|
| 1007 |
+
@pytest.mark.filterwarnings("ignore:Version 1 of dataset Australian is inactive")
|
| 1008 |
+
@pytest.mark.parametrize(
|
| 1009 |
+
"params, err_msg",
|
| 1010 |
+
[
|
| 1011 |
+
(
|
| 1012 |
+
{"parser": "pandas"},
|
| 1013 |
+
"Sparse ARFF datasets cannot be loaded with parser='pandas'",
|
| 1014 |
+
),
|
| 1015 |
+
(
|
| 1016 |
+
{"as_frame": True},
|
| 1017 |
+
"Sparse ARFF datasets cannot be loaded with as_frame=True.",
|
| 1018 |
+
),
|
| 1019 |
+
(
|
| 1020 |
+
{"parser": "pandas", "as_frame": True},
|
| 1021 |
+
"Sparse ARFF datasets cannot be loaded with as_frame=True.",
|
| 1022 |
+
),
|
| 1023 |
+
],
|
| 1024 |
+
)
|
| 1025 |
+
def test_fetch_openml_sparse_arff_error(monkeypatch, params, err_msg):
|
| 1026 |
+
"""Check that we raise the expected error for sparse ARFF datasets and
|
| 1027 |
+
a wrong set of incompatible parameters.
|
| 1028 |
+
"""
|
| 1029 |
+
pytest.importorskip("pandas")
|
| 1030 |
+
data_id = 292
|
| 1031 |
+
|
| 1032 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, True)
|
| 1033 |
+
with pytest.raises(ValueError, match=err_msg):
|
| 1034 |
+
fetch_openml(
|
| 1035 |
+
data_id=data_id,
|
| 1036 |
+
cache=False,
|
| 1037 |
+
**params,
|
| 1038 |
+
)
|
| 1039 |
+
|
| 1040 |
+
|
| 1041 |
+
@pytest.mark.filterwarnings("ignore:Version 1 of dataset Australian is inactive")
|
| 1042 |
+
@pytest.mark.parametrize(
|
| 1043 |
+
"data_id, data_type",
|
| 1044 |
+
[
|
| 1045 |
+
(61, "dataframe"), # iris dataset version 1
|
| 1046 |
+
(292, "sparse"), # Australian dataset version 1
|
| 1047 |
+
],
|
| 1048 |
+
)
|
| 1049 |
+
def test_fetch_openml_auto_mode(monkeypatch, data_id, data_type):
|
| 1050 |
+
"""Check the auto mode of `fetch_openml`."""
|
| 1051 |
+
pd = pytest.importorskip("pandas")
|
| 1052 |
+
|
| 1053 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, True)
|
| 1054 |
+
data = fetch_openml(data_id=data_id, as_frame="auto", cache=False)
|
| 1055 |
+
klass = pd.DataFrame if data_type == "dataframe" else scipy.sparse.csr_matrix
|
| 1056 |
+
assert isinstance(data.data, klass)
|
| 1057 |
+
|
| 1058 |
+
|
| 1059 |
+
def test_convert_arff_data_dataframe_warning_low_memory_pandas(monkeypatch):
|
| 1060 |
+
"""Check that we raise a warning regarding the working memory when using
|
| 1061 |
+
LIAC-ARFF parser."""
|
| 1062 |
+
pytest.importorskip("pandas")
|
| 1063 |
+
|
| 1064 |
+
data_id = 1119
|
| 1065 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, True)
|
| 1066 |
+
|
| 1067 |
+
msg = "Could not adhere to working_memory config."
|
| 1068 |
+
with pytest.warns(UserWarning, match=msg):
|
| 1069 |
+
with config_context(working_memory=1e-6):
|
| 1070 |
+
fetch_openml(
|
| 1071 |
+
data_id=data_id,
|
| 1072 |
+
as_frame=True,
|
| 1073 |
+
cache=False,
|
| 1074 |
+
parser="liac-arff",
|
| 1075 |
+
)
|
| 1076 |
+
|
| 1077 |
+
|
| 1078 |
+
@pytest.mark.parametrize("gzip_response", [True, False])
|
| 1079 |
+
def test_fetch_openml_iris_warn_multiple_version(monkeypatch, gzip_response):
|
| 1080 |
+
"""Check that a warning is raised when multiple versions exist and no version is
|
| 1081 |
+
requested."""
|
| 1082 |
+
data_id = 61
|
| 1083 |
+
data_name = "iris"
|
| 1084 |
+
|
| 1085 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
|
| 1086 |
+
|
| 1087 |
+
msg = re.escape(
|
| 1088 |
+
"Multiple active versions of the dataset matching the name"
|
| 1089 |
+
" iris exist. Versions may be fundamentally different, "
|
| 1090 |
+
"returning version 1. Available versions:\n"
|
| 1091 |
+
"- version 1, status: active\n"
|
| 1092 |
+
" url: https://www.openml.org/search?type=data&id=61\n"
|
| 1093 |
+
"- version 3, status: active\n"
|
| 1094 |
+
" url: https://www.openml.org/search?type=data&id=969\n"
|
| 1095 |
+
)
|
| 1096 |
+
with pytest.warns(UserWarning, match=msg):
|
| 1097 |
+
fetch_openml(
|
| 1098 |
+
name=data_name,
|
| 1099 |
+
as_frame=False,
|
| 1100 |
+
cache=False,
|
| 1101 |
+
parser="liac-arff",
|
| 1102 |
+
)
|
| 1103 |
+
|
| 1104 |
+
|
| 1105 |
+
@pytest.mark.parametrize("gzip_response", [True, False])
|
| 1106 |
+
def test_fetch_openml_no_target(monkeypatch, gzip_response):
|
| 1107 |
+
"""Check that we can get a dataset without target."""
|
| 1108 |
+
data_id = 61
|
| 1109 |
+
target_column = None
|
| 1110 |
+
expected_observations = 150
|
| 1111 |
+
expected_features = 5
|
| 1112 |
+
|
| 1113 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
|
| 1114 |
+
data = fetch_openml(
|
| 1115 |
+
data_id=data_id,
|
| 1116 |
+
target_column=target_column,
|
| 1117 |
+
cache=False,
|
| 1118 |
+
as_frame=False,
|
| 1119 |
+
parser="liac-arff",
|
| 1120 |
+
)
|
| 1121 |
+
assert data.data.shape == (expected_observations, expected_features)
|
| 1122 |
+
assert data.target is None
|
| 1123 |
+
|
| 1124 |
+
|
| 1125 |
+
@pytest.mark.parametrize("gzip_response", [True, False])
|
| 1126 |
+
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
|
| 1127 |
+
def test_missing_values_pandas(monkeypatch, gzip_response, parser):
|
| 1128 |
+
"""check that missing values in categories are compatible with pandas
|
| 1129 |
+
categorical"""
|
| 1130 |
+
pytest.importorskip("pandas")
|
| 1131 |
+
|
| 1132 |
+
data_id = 42585
|
| 1133 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=gzip_response)
|
| 1134 |
+
penguins = fetch_openml(
|
| 1135 |
+
data_id=data_id,
|
| 1136 |
+
cache=False,
|
| 1137 |
+
as_frame=True,
|
| 1138 |
+
parser=parser,
|
| 1139 |
+
)
|
| 1140 |
+
|
| 1141 |
+
cat_dtype = penguins.data.dtypes["sex"]
|
| 1142 |
+
# there are nans in the categorical
|
| 1143 |
+
assert penguins.data["sex"].isna().any()
|
| 1144 |
+
assert_array_equal(cat_dtype.categories, ["FEMALE", "MALE", "_"])
|
| 1145 |
+
|
| 1146 |
+
|
| 1147 |
+
@pytest.mark.parametrize("gzip_response", [True, False])
|
| 1148 |
+
@pytest.mark.parametrize(
|
| 1149 |
+
"dataset_params",
|
| 1150 |
+
[
|
| 1151 |
+
{"data_id": 40675},
|
| 1152 |
+
{"data_id": None, "name": "glass2", "version": 1},
|
| 1153 |
+
],
|
| 1154 |
+
)
|
| 1155 |
+
def test_fetch_openml_inactive(monkeypatch, gzip_response, dataset_params):
|
| 1156 |
+
"""Check that we raise a warning when the dataset is inactive."""
|
| 1157 |
+
data_id = 40675
|
| 1158 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
|
| 1159 |
+
msg = "Version 1 of dataset glass2 is inactive,"
|
| 1160 |
+
with pytest.warns(UserWarning, match=msg):
|
| 1161 |
+
glass2 = fetch_openml(
|
| 1162 |
+
cache=False, as_frame=False, parser="liac-arff", **dataset_params
|
| 1163 |
+
)
|
| 1164 |
+
assert glass2.data.shape == (163, 9)
|
| 1165 |
+
assert glass2.details["id"] == "40675"
|
| 1166 |
+
|
| 1167 |
+
|
| 1168 |
+
@pytest.mark.parametrize("gzip_response", [True, False])
|
| 1169 |
+
@pytest.mark.parametrize(
|
| 1170 |
+
"data_id, params, err_type, err_msg",
|
| 1171 |
+
[
|
| 1172 |
+
(40675, {"name": "glass2"}, ValueError, "No active dataset glass2 found"),
|
| 1173 |
+
(
|
| 1174 |
+
61,
|
| 1175 |
+
{"data_id": 61, "target_column": ["sepalwidth", "class"]},
|
| 1176 |
+
ValueError,
|
| 1177 |
+
"Can only handle homogeneous multi-target datasets",
|
| 1178 |
+
),
|
| 1179 |
+
(
|
| 1180 |
+
40945,
|
| 1181 |
+
{"data_id": 40945, "as_frame": False},
|
| 1182 |
+
ValueError,
|
| 1183 |
+
(
|
| 1184 |
+
"STRING attributes are not supported for array representation. Try"
|
| 1185 |
+
" as_frame=True"
|
| 1186 |
+
),
|
| 1187 |
+
),
|
| 1188 |
+
(
|
| 1189 |
+
2,
|
| 1190 |
+
{"data_id": 2, "target_column": "family", "as_frame": True},
|
| 1191 |
+
ValueError,
|
| 1192 |
+
"Target column 'family'",
|
| 1193 |
+
),
|
| 1194 |
+
(
|
| 1195 |
+
2,
|
| 1196 |
+
{"data_id": 2, "target_column": "family", "as_frame": False},
|
| 1197 |
+
ValueError,
|
| 1198 |
+
"Target column 'family'",
|
| 1199 |
+
),
|
| 1200 |
+
(
|
| 1201 |
+
61,
|
| 1202 |
+
{"data_id": 61, "target_column": "undefined"},
|
| 1203 |
+
KeyError,
|
| 1204 |
+
"Could not find target_column='undefined'",
|
| 1205 |
+
),
|
| 1206 |
+
(
|
| 1207 |
+
61,
|
| 1208 |
+
{"data_id": 61, "target_column": ["undefined", "class"]},
|
| 1209 |
+
KeyError,
|
| 1210 |
+
"Could not find target_column='undefined'",
|
| 1211 |
+
),
|
| 1212 |
+
],
|
| 1213 |
+
)
|
| 1214 |
+
@pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
|
| 1215 |
+
def test_fetch_openml_error(
|
| 1216 |
+
monkeypatch, gzip_response, data_id, params, err_type, err_msg, parser
|
| 1217 |
+
):
|
| 1218 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
|
| 1219 |
+
if params.get("as_frame", True) or parser == "pandas":
|
| 1220 |
+
pytest.importorskip("pandas")
|
| 1221 |
+
with pytest.raises(err_type, match=err_msg):
|
| 1222 |
+
fetch_openml(cache=False, parser=parser, **params)
|
| 1223 |
+
|
| 1224 |
+
|
| 1225 |
+
@pytest.mark.parametrize(
|
| 1226 |
+
"params, err_type, err_msg",
|
| 1227 |
+
[
|
| 1228 |
+
(
|
| 1229 |
+
{"data_id": -1, "name": None, "version": "version"},
|
| 1230 |
+
ValueError,
|
| 1231 |
+
"The 'version' parameter of fetch_openml must be an int in the range",
|
| 1232 |
+
),
|
| 1233 |
+
(
|
| 1234 |
+
{"data_id": -1, "name": "nAmE"},
|
| 1235 |
+
ValueError,
|
| 1236 |
+
"The 'data_id' parameter of fetch_openml must be an int in the range",
|
| 1237 |
+
),
|
| 1238 |
+
(
|
| 1239 |
+
{"data_id": -1, "name": "nAmE", "version": "version"},
|
| 1240 |
+
ValueError,
|
| 1241 |
+
"The 'version' parameter of fetch_openml must be an int",
|
| 1242 |
+
),
|
| 1243 |
+
(
|
| 1244 |
+
{},
|
| 1245 |
+
ValueError,
|
| 1246 |
+
"Neither name nor data_id are provided. Please provide name or data_id.",
|
| 1247 |
+
),
|
| 1248 |
+
],
|
| 1249 |
+
)
|
| 1250 |
+
def test_fetch_openml_raises_illegal_argument(params, err_type, err_msg):
|
| 1251 |
+
with pytest.raises(err_type, match=err_msg):
|
| 1252 |
+
fetch_openml(**params)
|
| 1253 |
+
|
| 1254 |
+
|
| 1255 |
+
@pytest.mark.parametrize("gzip_response", [True, False])
|
| 1256 |
+
def test_warn_ignore_attribute(monkeypatch, gzip_response):
|
| 1257 |
+
data_id = 40966
|
| 1258 |
+
expected_row_id_msg = "target_column='{}' has flag is_row_identifier."
|
| 1259 |
+
expected_ignore_msg = "target_column='{}' has flag is_ignore."
|
| 1260 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
|
| 1261 |
+
# single column test
|
| 1262 |
+
target_col = "MouseID"
|
| 1263 |
+
msg = expected_row_id_msg.format(target_col)
|
| 1264 |
+
with pytest.warns(UserWarning, match=msg):
|
| 1265 |
+
fetch_openml(
|
| 1266 |
+
data_id=data_id,
|
| 1267 |
+
target_column=target_col,
|
| 1268 |
+
cache=False,
|
| 1269 |
+
as_frame=False,
|
| 1270 |
+
parser="liac-arff",
|
| 1271 |
+
)
|
| 1272 |
+
target_col = "Genotype"
|
| 1273 |
+
msg = expected_ignore_msg.format(target_col)
|
| 1274 |
+
with pytest.warns(UserWarning, match=msg):
|
| 1275 |
+
fetch_openml(
|
| 1276 |
+
data_id=data_id,
|
| 1277 |
+
target_column=target_col,
|
| 1278 |
+
cache=False,
|
| 1279 |
+
as_frame=False,
|
| 1280 |
+
parser="liac-arff",
|
| 1281 |
+
)
|
| 1282 |
+
# multi column test
|
| 1283 |
+
target_col = "MouseID"
|
| 1284 |
+
msg = expected_row_id_msg.format(target_col)
|
| 1285 |
+
with pytest.warns(UserWarning, match=msg):
|
| 1286 |
+
fetch_openml(
|
| 1287 |
+
data_id=data_id,
|
| 1288 |
+
target_column=[target_col, "class"],
|
| 1289 |
+
cache=False,
|
| 1290 |
+
as_frame=False,
|
| 1291 |
+
parser="liac-arff",
|
| 1292 |
+
)
|
| 1293 |
+
target_col = "Genotype"
|
| 1294 |
+
msg = expected_ignore_msg.format(target_col)
|
| 1295 |
+
with pytest.warns(UserWarning, match=msg):
|
| 1296 |
+
fetch_openml(
|
| 1297 |
+
data_id=data_id,
|
| 1298 |
+
target_column=[target_col, "class"],
|
| 1299 |
+
cache=False,
|
| 1300 |
+
as_frame=False,
|
| 1301 |
+
parser="liac-arff",
|
| 1302 |
+
)
|
| 1303 |
+
|
| 1304 |
+
|
| 1305 |
+
@pytest.mark.parametrize("gzip_response", [True, False])
|
| 1306 |
+
def test_dataset_with_openml_error(monkeypatch, gzip_response):
|
| 1307 |
+
data_id = 1
|
| 1308 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
|
| 1309 |
+
msg = "OpenML registered a problem with the dataset. It might be unusable. Error:"
|
| 1310 |
+
with pytest.warns(UserWarning, match=msg):
|
| 1311 |
+
fetch_openml(data_id=data_id, cache=False, as_frame=False, parser="liac-arff")
|
| 1312 |
+
|
| 1313 |
+
|
| 1314 |
+
@pytest.mark.parametrize("gzip_response", [True, False])
|
| 1315 |
+
def test_dataset_with_openml_warning(monkeypatch, gzip_response):
|
| 1316 |
+
data_id = 3
|
| 1317 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
|
| 1318 |
+
msg = "OpenML raised a warning on the dataset. It might be unusable. Warning:"
|
| 1319 |
+
with pytest.warns(UserWarning, match=msg):
|
| 1320 |
+
fetch_openml(data_id=data_id, cache=False, as_frame=False, parser="liac-arff")
|
| 1321 |
+
|
| 1322 |
+
|
| 1323 |
+
def test_fetch_openml_overwrite_default_params_read_csv(monkeypatch):
|
| 1324 |
+
"""Check that we can overwrite the default parameters of `read_csv`."""
|
| 1325 |
+
pytest.importorskip("pandas")
|
| 1326 |
+
data_id = 1590
|
| 1327 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id=data_id, gzip_response=False)
|
| 1328 |
+
|
| 1329 |
+
common_params = {
|
| 1330 |
+
"data_id": data_id,
|
| 1331 |
+
"as_frame": True,
|
| 1332 |
+
"cache": False,
|
| 1333 |
+
"parser": "pandas",
|
| 1334 |
+
}
|
| 1335 |
+
|
| 1336 |
+
# By default, the initial spaces are skipped. We checked that setting the parameter
|
| 1337 |
+
# `skipinitialspace` to False will have an effect.
|
| 1338 |
+
adult_without_spaces = fetch_openml(**common_params)
|
| 1339 |
+
adult_with_spaces = fetch_openml(
|
| 1340 |
+
**common_params, read_csv_kwargs={"skipinitialspace": False}
|
| 1341 |
+
)
|
| 1342 |
+
assert all(
|
| 1343 |
+
cat.startswith(" ") for cat in adult_with_spaces.frame["class"].cat.categories
|
| 1344 |
+
)
|
| 1345 |
+
assert not any(
|
| 1346 |
+
cat.startswith(" ")
|
| 1347 |
+
for cat in adult_without_spaces.frame["class"].cat.categories
|
| 1348 |
+
)
|
| 1349 |
+
|
| 1350 |
+
|
| 1351 |
+
###############################################################################
|
| 1352 |
+
# Test cache, retry mechanisms, checksum, etc.
|
| 1353 |
+
|
| 1354 |
+
|
| 1355 |
+
@pytest.mark.parametrize("gzip_response", [True, False])
|
| 1356 |
+
def test_open_openml_url_cache(monkeypatch, gzip_response, tmpdir):
|
| 1357 |
+
data_id = 61
|
| 1358 |
+
|
| 1359 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
|
| 1360 |
+
openml_path = _MONKEY_PATCH_LOCAL_OPENML_PATH.format(data_id) + "/filename.arff"
|
| 1361 |
+
url = f"https://www.openml.org/{openml_path}"
|
| 1362 |
+
cache_directory = str(tmpdir.mkdir("scikit_learn_data"))
|
| 1363 |
+
# first fill the cache
|
| 1364 |
+
response1 = _open_openml_url(url, cache_directory)
|
| 1365 |
+
# assert file exists
|
| 1366 |
+
location = _get_local_path(openml_path, cache_directory)
|
| 1367 |
+
assert os.path.isfile(location)
|
| 1368 |
+
# redownload, to utilize cache
|
| 1369 |
+
response2 = _open_openml_url(url, cache_directory)
|
| 1370 |
+
assert response1.read() == response2.read()
|
| 1371 |
+
|
| 1372 |
+
|
| 1373 |
+
@pytest.mark.parametrize("write_to_disk", [True, False])
|
| 1374 |
+
def test_open_openml_url_unlinks_local_path(monkeypatch, tmpdir, write_to_disk):
|
| 1375 |
+
data_id = 61
|
| 1376 |
+
openml_path = _MONKEY_PATCH_LOCAL_OPENML_PATH.format(data_id) + "/filename.arff"
|
| 1377 |
+
url = f"https://www.openml.org/{openml_path}"
|
| 1378 |
+
cache_directory = str(tmpdir.mkdir("scikit_learn_data"))
|
| 1379 |
+
location = _get_local_path(openml_path, cache_directory)
|
| 1380 |
+
|
| 1381 |
+
def _mock_urlopen(request, *args, **kwargs):
|
| 1382 |
+
if write_to_disk:
|
| 1383 |
+
with open(location, "w") as f:
|
| 1384 |
+
f.write("")
|
| 1385 |
+
raise ValueError("Invalid request")
|
| 1386 |
+
|
| 1387 |
+
monkeypatch.setattr(sklearn.datasets._openml, "urlopen", _mock_urlopen)
|
| 1388 |
+
|
| 1389 |
+
with pytest.raises(ValueError, match="Invalid request"):
|
| 1390 |
+
_open_openml_url(url, cache_directory)
|
| 1391 |
+
|
| 1392 |
+
assert not os.path.exists(location)
|
| 1393 |
+
|
| 1394 |
+
|
| 1395 |
+
def test_retry_with_clean_cache(tmpdir):
|
| 1396 |
+
data_id = 61
|
| 1397 |
+
openml_path = _MONKEY_PATCH_LOCAL_OPENML_PATH.format(data_id)
|
| 1398 |
+
cache_directory = str(tmpdir.mkdir("scikit_learn_data"))
|
| 1399 |
+
location = _get_local_path(openml_path, cache_directory)
|
| 1400 |
+
os.makedirs(os.path.dirname(location))
|
| 1401 |
+
|
| 1402 |
+
with open(location, "w") as f:
|
| 1403 |
+
f.write("")
|
| 1404 |
+
|
| 1405 |
+
@_retry_with_clean_cache(openml_path, cache_directory)
|
| 1406 |
+
def _load_data():
|
| 1407 |
+
# The first call will raise an error since location exists
|
| 1408 |
+
if os.path.exists(location):
|
| 1409 |
+
raise Exception("File exist!")
|
| 1410 |
+
return 1
|
| 1411 |
+
|
| 1412 |
+
warn_msg = "Invalid cache, redownloading file"
|
| 1413 |
+
with pytest.warns(RuntimeWarning, match=warn_msg):
|
| 1414 |
+
result = _load_data()
|
| 1415 |
+
assert result == 1
|
| 1416 |
+
|
| 1417 |
+
|
| 1418 |
+
def test_retry_with_clean_cache_http_error(tmpdir):
|
| 1419 |
+
data_id = 61
|
| 1420 |
+
openml_path = _MONKEY_PATCH_LOCAL_OPENML_PATH.format(data_id)
|
| 1421 |
+
cache_directory = str(tmpdir.mkdir("scikit_learn_data"))
|
| 1422 |
+
|
| 1423 |
+
@_retry_with_clean_cache(openml_path, cache_directory)
|
| 1424 |
+
def _load_data():
|
| 1425 |
+
raise HTTPError(
|
| 1426 |
+
url=None, code=412, msg="Simulated mock error", hdrs=None, fp=BytesIO()
|
| 1427 |
+
)
|
| 1428 |
+
|
| 1429 |
+
error_msg = "Simulated mock error"
|
| 1430 |
+
with pytest.raises(HTTPError, match=error_msg):
|
| 1431 |
+
_load_data()
|
| 1432 |
+
|
| 1433 |
+
|
| 1434 |
+
@pytest.mark.parametrize("gzip_response", [True, False])
|
| 1435 |
+
def test_fetch_openml_cache(monkeypatch, gzip_response, tmpdir):
|
| 1436 |
+
def _mock_urlopen_raise(request, *args, **kwargs):
|
| 1437 |
+
raise ValueError(
|
| 1438 |
+
"This mechanism intends to test correct cache"
|
| 1439 |
+
"handling. As such, urlopen should never be "
|
| 1440 |
+
"accessed. URL: %s" % request.get_full_url()
|
| 1441 |
+
)
|
| 1442 |
+
|
| 1443 |
+
data_id = 61
|
| 1444 |
+
cache_directory = str(tmpdir.mkdir("scikit_learn_data"))
|
| 1445 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
|
| 1446 |
+
X_fetched, y_fetched = fetch_openml(
|
| 1447 |
+
data_id=data_id,
|
| 1448 |
+
cache=True,
|
| 1449 |
+
data_home=cache_directory,
|
| 1450 |
+
return_X_y=True,
|
| 1451 |
+
as_frame=False,
|
| 1452 |
+
parser="liac-arff",
|
| 1453 |
+
)
|
| 1454 |
+
|
| 1455 |
+
monkeypatch.setattr(sklearn.datasets._openml, "urlopen", _mock_urlopen_raise)
|
| 1456 |
+
|
| 1457 |
+
X_cached, y_cached = fetch_openml(
|
| 1458 |
+
data_id=data_id,
|
| 1459 |
+
cache=True,
|
| 1460 |
+
data_home=cache_directory,
|
| 1461 |
+
return_X_y=True,
|
| 1462 |
+
as_frame=False,
|
| 1463 |
+
parser="liac-arff",
|
| 1464 |
+
)
|
| 1465 |
+
np.testing.assert_array_equal(X_fetched, X_cached)
|
| 1466 |
+
np.testing.assert_array_equal(y_fetched, y_cached)
|
| 1467 |
+
|
| 1468 |
+
|
| 1469 |
+
@pytest.mark.parametrize(
|
| 1470 |
+
"as_frame, parser",
|
| 1471 |
+
[
|
| 1472 |
+
(True, "liac-arff"),
|
| 1473 |
+
(False, "liac-arff"),
|
| 1474 |
+
(True, "pandas"),
|
| 1475 |
+
(False, "pandas"),
|
| 1476 |
+
],
|
| 1477 |
+
)
|
| 1478 |
+
def test_fetch_openml_verify_checksum(monkeypatch, as_frame, tmpdir, parser):
|
| 1479 |
+
"""Check that the checksum is working as expected."""
|
| 1480 |
+
if as_frame or parser == "pandas":
|
| 1481 |
+
pytest.importorskip("pandas")
|
| 1482 |
+
|
| 1483 |
+
data_id = 2
|
| 1484 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, True)
|
| 1485 |
+
|
| 1486 |
+
# create a temporary modified arff file
|
| 1487 |
+
original_data_module = OPENML_TEST_DATA_MODULE + "." + f"id_{data_id}"
|
| 1488 |
+
original_data_file_name = "data-v1-dl-1666876.arff.gz"
|
| 1489 |
+
original_data_path = resources.files(original_data_module) / original_data_file_name
|
| 1490 |
+
corrupt_copy_path = tmpdir / "test_invalid_checksum.arff"
|
| 1491 |
+
with original_data_path.open("rb") as orig_file:
|
| 1492 |
+
orig_gzip = gzip.open(orig_file, "rb")
|
| 1493 |
+
data = bytearray(orig_gzip.read())
|
| 1494 |
+
data[len(data) - 1] = 37
|
| 1495 |
+
|
| 1496 |
+
with gzip.GzipFile(corrupt_copy_path, "wb") as modified_gzip:
|
| 1497 |
+
modified_gzip.write(data)
|
| 1498 |
+
|
| 1499 |
+
# Requests are already mocked by monkey_patch_webbased_functions.
|
| 1500 |
+
# We want to reuse that mock for all requests except file download,
|
| 1501 |
+
# hence creating a thin mock over the original mock
|
| 1502 |
+
mocked_openml_url = sklearn.datasets._openml.urlopen
|
| 1503 |
+
|
| 1504 |
+
def swap_file_mock(request, *args, **kwargs):
|
| 1505 |
+
url = request.get_full_url()
|
| 1506 |
+
if url.endswith("data/v1/download/1666876/anneal.arff"):
|
| 1507 |
+
with open(corrupt_copy_path, "rb") as f:
|
| 1508 |
+
corrupted_data = f.read()
|
| 1509 |
+
return _MockHTTPResponse(BytesIO(corrupted_data), is_gzip=True)
|
| 1510 |
+
else:
|
| 1511 |
+
return mocked_openml_url(request)
|
| 1512 |
+
|
| 1513 |
+
monkeypatch.setattr(sklearn.datasets._openml, "urlopen", swap_file_mock)
|
| 1514 |
+
|
| 1515 |
+
# validate failed checksum
|
| 1516 |
+
with pytest.raises(ValueError) as exc:
|
| 1517 |
+
sklearn.datasets.fetch_openml(
|
| 1518 |
+
data_id=data_id, cache=False, as_frame=as_frame, parser=parser
|
| 1519 |
+
)
|
| 1520 |
+
# exception message should have file-path
|
| 1521 |
+
assert exc.match("1666876")
|
| 1522 |
+
|
| 1523 |
+
|
| 1524 |
+
def test_open_openml_url_retry_on_network_error(monkeypatch):
|
| 1525 |
+
def _mock_urlopen_network_error(request, *args, **kwargs):
|
| 1526 |
+
raise HTTPError(
|
| 1527 |
+
url=None, code=404, msg="Simulated network error", hdrs=None, fp=BytesIO()
|
| 1528 |
+
)
|
| 1529 |
+
|
| 1530 |
+
monkeypatch.setattr(
|
| 1531 |
+
sklearn.datasets._openml, "urlopen", _mock_urlopen_network_error
|
| 1532 |
+
)
|
| 1533 |
+
|
| 1534 |
+
invalid_openml_url = "https://api.openml.org/invalid-url"
|
| 1535 |
+
|
| 1536 |
+
with pytest.warns(
|
| 1537 |
+
UserWarning,
|
| 1538 |
+
match=re.escape(
|
| 1539 |
+
"A network error occurred while downloading"
|
| 1540 |
+
f" {invalid_openml_url}. Retrying..."
|
| 1541 |
+
),
|
| 1542 |
+
) as record:
|
| 1543 |
+
with pytest.raises(HTTPError, match="Simulated network error") as exc_info:
|
| 1544 |
+
_open_openml_url(invalid_openml_url, None, delay=0)
|
| 1545 |
+
assert len(record) == 3
|
| 1546 |
+
# Avoid a ResourceWarning on Python 3.14 and later.
|
| 1547 |
+
exc_info.value.close()
|
| 1548 |
+
|
| 1549 |
+
|
| 1550 |
+
###############################################################################
|
| 1551 |
+
# Non-regressiont tests
|
| 1552 |
+
|
| 1553 |
+
|
| 1554 |
+
@pytest.mark.parametrize("gzip_response", [True, False])
|
| 1555 |
+
@pytest.mark.parametrize("parser", ("liac-arff", "pandas"))
|
| 1556 |
+
def test_fetch_openml_with_ignored_feature(monkeypatch, gzip_response, parser):
|
| 1557 |
+
"""Check that we can load the "zoo" dataset.
|
| 1558 |
+
Non-regression test for:
|
| 1559 |
+
https://github.com/scikit-learn/scikit-learn/issues/14340
|
| 1560 |
+
"""
|
| 1561 |
+
if parser == "pandas":
|
| 1562 |
+
pytest.importorskip("pandas")
|
| 1563 |
+
data_id = 62
|
| 1564 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
|
| 1565 |
+
|
| 1566 |
+
dataset = sklearn.datasets.fetch_openml(
|
| 1567 |
+
data_id=data_id, cache=False, as_frame=False, parser=parser
|
| 1568 |
+
)
|
| 1569 |
+
assert dataset is not None
|
| 1570 |
+
# The dataset has 17 features, including 1 ignored (animal),
|
| 1571 |
+
# so we assert that we don't have the ignored feature in the final Bunch
|
| 1572 |
+
assert dataset["data"].shape == (101, 16)
|
| 1573 |
+
assert "animal" not in dataset["feature_names"]
|
| 1574 |
+
|
| 1575 |
+
|
| 1576 |
+
def test_fetch_openml_strip_quotes(monkeypatch):
|
| 1577 |
+
"""Check that we strip the single quotes when used as a string delimiter.
|
| 1578 |
+
|
| 1579 |
+
Non-regression test for:
|
| 1580 |
+
https://github.com/scikit-learn/scikit-learn/issues/23381
|
| 1581 |
+
"""
|
| 1582 |
+
pd = pytest.importorskip("pandas")
|
| 1583 |
+
data_id = 40966
|
| 1584 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id=data_id, gzip_response=False)
|
| 1585 |
+
|
| 1586 |
+
common_params = {"as_frame": True, "cache": False, "data_id": data_id}
|
| 1587 |
+
mice_pandas = fetch_openml(parser="pandas", **common_params)
|
| 1588 |
+
mice_liac_arff = fetch_openml(parser="liac-arff", **common_params)
|
| 1589 |
+
pd.testing.assert_series_equal(mice_pandas.target, mice_liac_arff.target)
|
| 1590 |
+
assert not mice_pandas.target.str.startswith("'").any()
|
| 1591 |
+
assert not mice_pandas.target.str.endswith("'").any()
|
| 1592 |
+
|
| 1593 |
+
# similar behaviour should be observed when the column is not the target
|
| 1594 |
+
mice_pandas = fetch_openml(parser="pandas", target_column="NUMB_N", **common_params)
|
| 1595 |
+
mice_liac_arff = fetch_openml(
|
| 1596 |
+
parser="liac-arff", target_column="NUMB_N", **common_params
|
| 1597 |
+
)
|
| 1598 |
+
pd.testing.assert_series_equal(
|
| 1599 |
+
mice_pandas.frame["class"], mice_liac_arff.frame["class"]
|
| 1600 |
+
)
|
| 1601 |
+
assert not mice_pandas.frame["class"].str.startswith("'").any()
|
| 1602 |
+
assert not mice_pandas.frame["class"].str.endswith("'").any()
|
| 1603 |
+
|
| 1604 |
+
|
| 1605 |
+
def test_fetch_openml_leading_whitespace(monkeypatch):
|
| 1606 |
+
"""Check that we can strip leading whitespace in pandas parser.
|
| 1607 |
+
|
| 1608 |
+
Non-regression test for:
|
| 1609 |
+
https://github.com/scikit-learn/scikit-learn/issues/25311
|
| 1610 |
+
"""
|
| 1611 |
+
pd = pytest.importorskip("pandas")
|
| 1612 |
+
data_id = 1590
|
| 1613 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id=data_id, gzip_response=False)
|
| 1614 |
+
|
| 1615 |
+
common_params = {"as_frame": True, "cache": False, "data_id": data_id}
|
| 1616 |
+
adult_pandas = fetch_openml(parser="pandas", **common_params)
|
| 1617 |
+
adult_liac_arff = fetch_openml(parser="liac-arff", **common_params)
|
| 1618 |
+
pd.testing.assert_series_equal(
|
| 1619 |
+
adult_pandas.frame["class"], adult_liac_arff.frame["class"]
|
| 1620 |
+
)
|
| 1621 |
+
|
| 1622 |
+
|
| 1623 |
+
def test_fetch_openml_quotechar_escapechar(monkeypatch):
|
| 1624 |
+
"""Check that we can handle escapechar and single/double quotechar.
|
| 1625 |
+
|
| 1626 |
+
Non-regression test for:
|
| 1627 |
+
https://github.com/scikit-learn/scikit-learn/issues/25478
|
| 1628 |
+
"""
|
| 1629 |
+
pd = pytest.importorskip("pandas")
|
| 1630 |
+
data_id = 42074
|
| 1631 |
+
_monkey_patch_webbased_functions(monkeypatch, data_id=data_id, gzip_response=False)
|
| 1632 |
+
|
| 1633 |
+
common_params = {"as_frame": True, "cache": False, "data_id": data_id}
|
| 1634 |
+
adult_pandas = fetch_openml(parser="pandas", **common_params)
|
| 1635 |
+
adult_liac_arff = fetch_openml(parser="liac-arff", **common_params)
|
| 1636 |
+
pd.testing.assert_frame_equal(adult_pandas.frame, adult_liac_arff.frame)
|
shared/package-files/24/243b231c639f70b7ee8d8b166f9f3fe40986a5e8123768448e1d5091af3a6799/reproc++-config-version.cmake
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This is a basic version file for the Config-mode of find_package().
|
| 2 |
+
# It is used by write_basic_package_version_file() as input file for configure_file()
|
| 3 |
+
# to create a version-file which can be installed along a config.cmake file.
|
| 4 |
+
#
|
| 5 |
+
# The created file sets PACKAGE_VERSION_EXACT if the current version string and
|
| 6 |
+
# the requested version string are exactly the same and it sets
|
| 7 |
+
# PACKAGE_VERSION_COMPATIBLE if the current version is >= requested version,
|
| 8 |
+
# but only if the requested major version is the same as the current one.
|
| 9 |
+
# The variable CVF_VERSION must be set before calling configure_file().
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
set(PACKAGE_VERSION "14.2.4")
|
| 13 |
+
|
| 14 |
+
if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
|
| 15 |
+
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
| 16 |
+
else()
|
| 17 |
+
|
| 18 |
+
if("14.2.4" MATCHES "^([0-9]+)\\.")
|
| 19 |
+
set(CVF_VERSION_MAJOR "${CMAKE_MATCH_1}")
|
| 20 |
+
if(NOT CVF_VERSION_MAJOR VERSION_EQUAL 0)
|
| 21 |
+
string(REGEX REPLACE "^0+" "" CVF_VERSION_MAJOR "${CVF_VERSION_MAJOR}")
|
| 22 |
+
endif()
|
| 23 |
+
else()
|
| 24 |
+
set(CVF_VERSION_MAJOR "14.2.4")
|
| 25 |
+
endif()
|
| 26 |
+
|
| 27 |
+
if(PACKAGE_FIND_VERSION_RANGE)
|
| 28 |
+
# both endpoints of the range must have the expected major version
|
| 29 |
+
math (EXPR CVF_VERSION_MAJOR_NEXT "${CVF_VERSION_MAJOR} + 1")
|
| 30 |
+
if (NOT PACKAGE_FIND_VERSION_MIN_MAJOR STREQUAL CVF_VERSION_MAJOR
|
| 31 |
+
OR ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND NOT PACKAGE_FIND_VERSION_MAX_MAJOR STREQUAL CVF_VERSION_MAJOR)
|
| 32 |
+
OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND NOT PACKAGE_FIND_VERSION_MAX VERSION_LESS_EQUAL CVF_VERSION_MAJOR_NEXT)))
|
| 33 |
+
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
| 34 |
+
elseif(PACKAGE_FIND_VERSION_MIN_MAJOR STREQUAL CVF_VERSION_MAJOR
|
| 35 |
+
AND ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_LESS_EQUAL PACKAGE_FIND_VERSION_MAX)
|
| 36 |
+
OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MAX)))
|
| 37 |
+
set(PACKAGE_VERSION_COMPATIBLE TRUE)
|
| 38 |
+
else()
|
| 39 |
+
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
| 40 |
+
endif()
|
| 41 |
+
else()
|
| 42 |
+
if(PACKAGE_FIND_VERSION_MAJOR STREQUAL CVF_VERSION_MAJOR)
|
| 43 |
+
set(PACKAGE_VERSION_COMPATIBLE TRUE)
|
| 44 |
+
else()
|
| 45 |
+
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
| 46 |
+
endif()
|
| 47 |
+
|
| 48 |
+
if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
|
| 49 |
+
set(PACKAGE_VERSION_EXACT TRUE)
|
| 50 |
+
endif()
|
| 51 |
+
endif()
|
| 52 |
+
endif()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# if the installed project requested no architecture check, don't perform the check
|
| 56 |
+
if("FALSE")
|
| 57 |
+
return()
|
| 58 |
+
endif()
|
| 59 |
+
|
| 60 |
+
# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it:
|
| 61 |
+
if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "8" STREQUAL "")
|
| 62 |
+
return()
|
| 63 |
+
endif()
|
| 64 |
+
|
| 65 |
+
# check that the installed version has the same 32/64bit-ness as the one which is currently searching:
|
| 66 |
+
if(NOT CMAKE_SIZEOF_VOID_P STREQUAL "8")
|
| 67 |
+
math(EXPR installedBits "8 * 8")
|
| 68 |
+
set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)")
|
| 69 |
+
set(PACKAGE_VERSION_UNSUITABLE TRUE)
|
| 70 |
+
endif()
|
shared/package-files/24/243b231c639f70b7ee8d8b166f9f3fe40986a5e8123768448e1d5091af3a6799/reproc-config-version.cmake
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This is a basic version file for the Config-mode of find_package().
|
| 2 |
+
# It is used by write_basic_package_version_file() as input file for configure_file()
|
| 3 |
+
# to create a version-file which can be installed along a config.cmake file.
|
| 4 |
+
#
|
| 5 |
+
# The created file sets PACKAGE_VERSION_EXACT if the current version string and
|
| 6 |
+
# the requested version string are exactly the same and it sets
|
| 7 |
+
# PACKAGE_VERSION_COMPATIBLE if the current version is >= requested version,
|
| 8 |
+
# but only if the requested major version is the same as the current one.
|
| 9 |
+
# The variable CVF_VERSION must be set before calling configure_file().
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
set(PACKAGE_VERSION "14.2.4")
|
| 13 |
+
|
| 14 |
+
if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
|
| 15 |
+
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
| 16 |
+
else()
|
| 17 |
+
|
| 18 |
+
if("14.2.4" MATCHES "^([0-9]+)\\.")
|
| 19 |
+
set(CVF_VERSION_MAJOR "${CMAKE_MATCH_1}")
|
| 20 |
+
if(NOT CVF_VERSION_MAJOR VERSION_EQUAL 0)
|
| 21 |
+
string(REGEX REPLACE "^0+" "" CVF_VERSION_MAJOR "${CVF_VERSION_MAJOR}")
|
| 22 |
+
endif()
|
| 23 |
+
else()
|
| 24 |
+
set(CVF_VERSION_MAJOR "14.2.4")
|
| 25 |
+
endif()
|
| 26 |
+
|
| 27 |
+
if(PACKAGE_FIND_VERSION_RANGE)
|
| 28 |
+
# both endpoints of the range must have the expected major version
|
| 29 |
+
math (EXPR CVF_VERSION_MAJOR_NEXT "${CVF_VERSION_MAJOR} + 1")
|
| 30 |
+
if (NOT PACKAGE_FIND_VERSION_MIN_MAJOR STREQUAL CVF_VERSION_MAJOR
|
| 31 |
+
OR ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND NOT PACKAGE_FIND_VERSION_MAX_MAJOR STREQUAL CVF_VERSION_MAJOR)
|
| 32 |
+
OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND NOT PACKAGE_FIND_VERSION_MAX VERSION_LESS_EQUAL CVF_VERSION_MAJOR_NEXT)))
|
| 33 |
+
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
| 34 |
+
elseif(PACKAGE_FIND_VERSION_MIN_MAJOR STREQUAL CVF_VERSION_MAJOR
|
| 35 |
+
AND ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_LESS_EQUAL PACKAGE_FIND_VERSION_MAX)
|
| 36 |
+
OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MAX)))
|
| 37 |
+
set(PACKAGE_VERSION_COMPATIBLE TRUE)
|
| 38 |
+
else()
|
| 39 |
+
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
| 40 |
+
endif()
|
| 41 |
+
else()
|
| 42 |
+
if(PACKAGE_FIND_VERSION_MAJOR STREQUAL CVF_VERSION_MAJOR)
|
| 43 |
+
set(PACKAGE_VERSION_COMPATIBLE TRUE)
|
| 44 |
+
else()
|
| 45 |
+
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
| 46 |
+
endif()
|
| 47 |
+
|
| 48 |
+
if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
|
| 49 |
+
set(PACKAGE_VERSION_EXACT TRUE)
|
| 50 |
+
endif()
|
| 51 |
+
endif()
|
| 52 |
+
endif()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# if the installed project requested no architecture check, don't perform the check
|
| 56 |
+
if("FALSE")
|
| 57 |
+
return()
|
| 58 |
+
endif()
|
| 59 |
+
|
| 60 |
+
# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it:
|
| 61 |
+
if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "8" STREQUAL "")
|
| 62 |
+
return()
|
| 63 |
+
endif()
|
| 64 |
+
|
| 65 |
+
# check that the installed version has the same 32/64bit-ness as the one which is currently searching:
|
| 66 |
+
if(NOT CMAKE_SIZEOF_VOID_P STREQUAL "8")
|
| 67 |
+
math(EXPR installedBits "8 * 8")
|
| 68 |
+
set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)")
|
| 69 |
+
set(PACKAGE_VERSION_UNSUITABLE TRUE)
|
| 70 |
+
endif()
|
shared/package-files/24/243b94504f86c8f6a190d9c364b58d1f20262769493c29cbb885057c79233330/fujitsuccompiler.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from distutils.unixccompiler import UnixCCompiler
|
| 2 |
+
|
| 3 |
+
class FujitsuCCompiler(UnixCCompiler):
|
| 4 |
+
|
| 5 |
+
"""
|
| 6 |
+
Fujitsu compiler.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
compiler_type = 'fujitsu'
|
| 10 |
+
cc_exe = 'fcc'
|
| 11 |
+
cxx_exe = 'FCC'
|
| 12 |
+
|
| 13 |
+
def __init__(self, verbose=0, dry_run=0, force=0):
|
| 14 |
+
UnixCCompiler.__init__(self, verbose, dry_run, force)
|
| 15 |
+
cc_compiler = self.cc_exe
|
| 16 |
+
cxx_compiler = self.cxx_exe
|
| 17 |
+
self.set_executables(
|
| 18 |
+
compiler=cc_compiler +
|
| 19 |
+
' -O3 -Nclang -fPIC',
|
| 20 |
+
compiler_so=cc_compiler +
|
| 21 |
+
' -O3 -Nclang -fPIC',
|
| 22 |
+
compiler_cxx=cxx_compiler +
|
| 23 |
+
' -O3 -Nclang -fPIC',
|
| 24 |
+
linker_exe=cc_compiler +
|
| 25 |
+
' -lfj90i -lfj90f -lfjsrcinfo -lelf -shared',
|
| 26 |
+
linker_so=cc_compiler +
|
| 27 |
+
' -lfj90i -lfj90f -lfjsrcinfo -lelf -shared'
|
| 28 |
+
)
|
shared/package-files/24/243d45e43b41d84a74d19255a6296096e96a2adeac4c1c2eee14bf0a6c3609e9/THConcat.h
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#define TH_CONCAT_STRING_2(x, y) TH_CONCAT_STRING_2_EXPAND(x, y)
|
| 4 |
+
#define TH_CONCAT_STRING_2_EXPAND(x, y) #x #y
|
| 5 |
+
|
| 6 |
+
#define TH_CONCAT_STRING_3(x, y, z) TH_CONCAT_STRING_3_EXPAND(x, y, z)
|
| 7 |
+
#define TH_CONCAT_STRING_3_EXPAND(x, y, z) #x #y #z
|
| 8 |
+
|
| 9 |
+
#define TH_CONCAT_STRING_4(x, y, z, w) TH_CONCAT_STRING_4_EXPAND(x, y, z, w)
|
| 10 |
+
#define TH_CONCAT_STRING_4_EXPAND(x, y, z, w) #x #y #z #w
|
| 11 |
+
|
| 12 |
+
#define TH_CONCAT_2(x, y) TH_CONCAT_2_EXPAND(x, y)
|
| 13 |
+
#define TH_CONCAT_2_EXPAND(x, y) x##y
|
| 14 |
+
|
| 15 |
+
#define TH_CONCAT_3(x, y, z) TH_CONCAT_3_EXPAND(x, y, z)
|
| 16 |
+
#define TH_CONCAT_3_EXPAND(x, y, z) x##y##z
|
| 17 |
+
|
| 18 |
+
#define TH_CONCAT_4_EXPAND(x, y, z, w) x##y##z##w
|
| 19 |
+
#define TH_CONCAT_4(x, y, z, w) TH_CONCAT_4_EXPAND(x, y, z, w)
|
shared/package-files/24/243de318102a4474586f58da6e5ae9abf44542f62d61fc2d2083c9810a5b28f7/axes_divider.py
ADDED
|
@@ -0,0 +1,618 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Helper classes to adjust the positions of multiple axes at drawing time.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import functools
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
import matplotlib as mpl
|
| 10 |
+
from matplotlib import _api
|
| 11 |
+
from matplotlib.gridspec import SubplotSpec
|
| 12 |
+
import matplotlib.transforms as mtransforms
|
| 13 |
+
from . import axes_size as Size
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class Divider:
|
| 17 |
+
"""
|
| 18 |
+
An Axes positioning class.
|
| 19 |
+
|
| 20 |
+
The divider is initialized with lists of horizontal and vertical sizes
|
| 21 |
+
(:mod:`mpl_toolkits.axes_grid1.axes_size`) based on which a given
|
| 22 |
+
rectangular area will be divided.
|
| 23 |
+
|
| 24 |
+
The `new_locator` method then creates a callable object
|
| 25 |
+
that can be used as the *axes_locator* of the axes.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(self, fig, pos, horizontal, vertical,
|
| 29 |
+
aspect=None, anchor="C"):
|
| 30 |
+
"""
|
| 31 |
+
Parameters
|
| 32 |
+
----------
|
| 33 |
+
fig : Figure
|
| 34 |
+
pos : tuple of 4 floats
|
| 35 |
+
Position of the rectangle that will be divided.
|
| 36 |
+
horizontal : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
|
| 37 |
+
Sizes for horizontal division.
|
| 38 |
+
vertical : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
|
| 39 |
+
Sizes for vertical division.
|
| 40 |
+
aspect : bool, optional
|
| 41 |
+
Whether overall rectangular area is reduced so that the relative
|
| 42 |
+
part of the horizontal and vertical scales have the same scale.
|
| 43 |
+
anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
|
| 44 |
+
'NW', 'W'}, default: 'C'
|
| 45 |
+
Placement of the reduced rectangle, when *aspect* is True.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
self._fig = fig
|
| 49 |
+
self._pos = pos
|
| 50 |
+
self._horizontal = horizontal
|
| 51 |
+
self._vertical = vertical
|
| 52 |
+
self._anchor = anchor
|
| 53 |
+
self.set_anchor(anchor)
|
| 54 |
+
self._aspect = aspect
|
| 55 |
+
self._xrefindex = 0
|
| 56 |
+
self._yrefindex = 0
|
| 57 |
+
self._locator = None
|
| 58 |
+
|
| 59 |
+
def get_horizontal_sizes(self, renderer):
|
| 60 |
+
return np.array([s.get_size(renderer) for s in self.get_horizontal()])
|
| 61 |
+
|
| 62 |
+
def get_vertical_sizes(self, renderer):
|
| 63 |
+
return np.array([s.get_size(renderer) for s in self.get_vertical()])
|
| 64 |
+
|
| 65 |
+
def set_position(self, pos):
|
| 66 |
+
"""
|
| 67 |
+
Set the position of the rectangle.
|
| 68 |
+
|
| 69 |
+
Parameters
|
| 70 |
+
----------
|
| 71 |
+
pos : tuple of 4 floats
|
| 72 |
+
position of the rectangle that will be divided
|
| 73 |
+
"""
|
| 74 |
+
self._pos = pos
|
| 75 |
+
|
| 76 |
+
def get_position(self):
|
| 77 |
+
"""Return the position of the rectangle."""
|
| 78 |
+
return self._pos
|
| 79 |
+
|
| 80 |
+
def set_anchor(self, anchor):
|
| 81 |
+
"""
|
| 82 |
+
Parameters
|
| 83 |
+
----------
|
| 84 |
+
anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
|
| 85 |
+
'NW', 'W'}
|
| 86 |
+
Either an (*x*, *y*) pair of relative coordinates (0 is left or
|
| 87 |
+
bottom, 1 is right or top), 'C' (center), or a cardinal direction
|
| 88 |
+
('SW', southwest, is bottom left, etc.).
|
| 89 |
+
|
| 90 |
+
See Also
|
| 91 |
+
--------
|
| 92 |
+
.Axes.set_anchor
|
| 93 |
+
"""
|
| 94 |
+
if isinstance(anchor, str):
|
| 95 |
+
_api.check_in_list(mtransforms.Bbox.coefs, anchor=anchor)
|
| 96 |
+
elif not isinstance(anchor, (tuple, list)) or len(anchor) != 2:
|
| 97 |
+
raise TypeError("anchor must be str or 2-tuple")
|
| 98 |
+
self._anchor = anchor
|
| 99 |
+
|
| 100 |
+
def get_anchor(self):
|
| 101 |
+
"""Return the anchor."""
|
| 102 |
+
return self._anchor
|
| 103 |
+
|
| 104 |
+
def get_subplotspec(self):
|
| 105 |
+
return None
|
| 106 |
+
|
| 107 |
+
def set_horizontal(self, h):
|
| 108 |
+
"""
|
| 109 |
+
Parameters
|
| 110 |
+
----------
|
| 111 |
+
h : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
|
| 112 |
+
sizes for horizontal division
|
| 113 |
+
"""
|
| 114 |
+
self._horizontal = h
|
| 115 |
+
|
| 116 |
+
def get_horizontal(self):
|
| 117 |
+
"""Return horizontal sizes."""
|
| 118 |
+
return self._horizontal
|
| 119 |
+
|
| 120 |
+
def set_vertical(self, v):
|
| 121 |
+
"""
|
| 122 |
+
Parameters
|
| 123 |
+
----------
|
| 124 |
+
v : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
|
| 125 |
+
sizes for vertical division
|
| 126 |
+
"""
|
| 127 |
+
self._vertical = v
|
| 128 |
+
|
| 129 |
+
def get_vertical(self):
|
| 130 |
+
"""Return vertical sizes."""
|
| 131 |
+
return self._vertical
|
| 132 |
+
|
| 133 |
+
def set_aspect(self, aspect=False):
|
| 134 |
+
"""
|
| 135 |
+
Parameters
|
| 136 |
+
----------
|
| 137 |
+
aspect : bool
|
| 138 |
+
"""
|
| 139 |
+
self._aspect = aspect
|
| 140 |
+
|
| 141 |
+
def get_aspect(self):
|
| 142 |
+
"""Return aspect."""
|
| 143 |
+
return self._aspect
|
| 144 |
+
|
| 145 |
+
def set_locator(self, _locator):
|
| 146 |
+
self._locator = _locator
|
| 147 |
+
|
| 148 |
+
def get_locator(self):
|
| 149 |
+
return self._locator
|
| 150 |
+
|
| 151 |
+
def get_position_runtime(self, ax, renderer):
|
| 152 |
+
if self._locator is None:
|
| 153 |
+
return self.get_position()
|
| 154 |
+
else:
|
| 155 |
+
return self._locator(ax, renderer).bounds
|
| 156 |
+
|
| 157 |
+
@staticmethod
|
| 158 |
+
def _calc_k(sizes, total):
|
| 159 |
+
# sizes is a (n, 2) array of (rel_size, abs_size); this method finds
|
| 160 |
+
# the k factor such that sum(rel_size * k + abs_size) == total.
|
| 161 |
+
rel_sum, abs_sum = sizes.sum(0)
|
| 162 |
+
return (total - abs_sum) / rel_sum if rel_sum else 0
|
| 163 |
+
|
| 164 |
+
@staticmethod
|
| 165 |
+
def _calc_offsets(sizes, k):
|
| 166 |
+
# Apply k factors to (n, 2) sizes array of (rel_size, abs_size); return
|
| 167 |
+
# the resulting cumulative offset positions.
|
| 168 |
+
return np.cumsum([0, *(sizes @ [k, 1])])
|
| 169 |
+
|
| 170 |
+
def new_locator(self, nx, ny, nx1=None, ny1=None):
|
| 171 |
+
"""
|
| 172 |
+
Return an axes locator callable for the specified cell.
|
| 173 |
+
|
| 174 |
+
Parameters
|
| 175 |
+
----------
|
| 176 |
+
nx, nx1 : int
|
| 177 |
+
Integers specifying the column-position of the
|
| 178 |
+
cell. When *nx1* is None, a single *nx*-th column is
|
| 179 |
+
specified. Otherwise, location of columns spanning between *nx*
|
| 180 |
+
to *nx1* (but excluding *nx1*-th column) is specified.
|
| 181 |
+
ny, ny1 : int
|
| 182 |
+
Same as *nx* and *nx1*, but for row positions.
|
| 183 |
+
"""
|
| 184 |
+
if nx1 is None:
|
| 185 |
+
nx1 = nx + 1
|
| 186 |
+
if ny1 is None:
|
| 187 |
+
ny1 = ny + 1
|
| 188 |
+
# append_size("left") adds a new size at the beginning of the
|
| 189 |
+
# horizontal size lists; this shift transforms e.g.
|
| 190 |
+
# new_locator(nx=2, ...) into effectively new_locator(nx=3, ...). To
|
| 191 |
+
# take that into account, instead of recording nx, we record
|
| 192 |
+
# nx-self._xrefindex, where _xrefindex is shifted by 1 by each
|
| 193 |
+
# append_size("left"), and re-add self._xrefindex back to nx in
|
| 194 |
+
# _locate, when the actual axes position is computed. Ditto for y.
|
| 195 |
+
xref = self._xrefindex
|
| 196 |
+
yref = self._yrefindex
|
| 197 |
+
locator = functools.partial(
|
| 198 |
+
self._locate, nx - xref, ny - yref, nx1 - xref, ny1 - yref)
|
| 199 |
+
locator.get_subplotspec = self.get_subplotspec
|
| 200 |
+
return locator
|
| 201 |
+
|
| 202 |
+
def _locate(self, nx, ny, nx1, ny1, axes, renderer):
|
| 203 |
+
"""
|
| 204 |
+
Implementation of ``divider.new_locator().__call__``.
|
| 205 |
+
|
| 206 |
+
The axes locator callable returned by ``new_locator()`` is created as
|
| 207 |
+
a `functools.partial` of this method with *nx*, *ny*, *nx1*, and *ny1*
|
| 208 |
+
specifying the requested cell.
|
| 209 |
+
"""
|
| 210 |
+
nx += self._xrefindex
|
| 211 |
+
nx1 += self._xrefindex
|
| 212 |
+
ny += self._yrefindex
|
| 213 |
+
ny1 += self._yrefindex
|
| 214 |
+
|
| 215 |
+
fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
|
| 216 |
+
x, y, w, h = self.get_position_runtime(axes, renderer)
|
| 217 |
+
|
| 218 |
+
hsizes = self.get_horizontal_sizes(renderer)
|
| 219 |
+
vsizes = self.get_vertical_sizes(renderer)
|
| 220 |
+
k_h = self._calc_k(hsizes, fig_w * w)
|
| 221 |
+
k_v = self._calc_k(vsizes, fig_h * h)
|
| 222 |
+
|
| 223 |
+
if self.get_aspect():
|
| 224 |
+
k = min(k_h, k_v)
|
| 225 |
+
ox = self._calc_offsets(hsizes, k)
|
| 226 |
+
oy = self._calc_offsets(vsizes, k)
|
| 227 |
+
|
| 228 |
+
ww = (ox[-1] - ox[0]) / fig_w
|
| 229 |
+
hh = (oy[-1] - oy[0]) / fig_h
|
| 230 |
+
pb = mtransforms.Bbox.from_bounds(x, y, w, h)
|
| 231 |
+
pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh)
|
| 232 |
+
x0, y0 = pb1.anchored(self.get_anchor(), pb).p0
|
| 233 |
+
|
| 234 |
+
else:
|
| 235 |
+
ox = self._calc_offsets(hsizes, k_h)
|
| 236 |
+
oy = self._calc_offsets(vsizes, k_v)
|
| 237 |
+
x0, y0 = x, y
|
| 238 |
+
|
| 239 |
+
if nx1 is None:
|
| 240 |
+
nx1 = -1
|
| 241 |
+
if ny1 is None:
|
| 242 |
+
ny1 = -1
|
| 243 |
+
|
| 244 |
+
x1, w1 = x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w
|
| 245 |
+
y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h
|
| 246 |
+
|
| 247 |
+
return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
|
| 248 |
+
|
| 249 |
+
def append_size(self, position, size):
|
| 250 |
+
_api.check_in_list(["left", "right", "bottom", "top"],
|
| 251 |
+
position=position)
|
| 252 |
+
if position == "left":
|
| 253 |
+
self._horizontal.insert(0, size)
|
| 254 |
+
self._xrefindex += 1
|
| 255 |
+
elif position == "right":
|
| 256 |
+
self._horizontal.append(size)
|
| 257 |
+
elif position == "bottom":
|
| 258 |
+
self._vertical.insert(0, size)
|
| 259 |
+
self._yrefindex += 1
|
| 260 |
+
else: # 'top'
|
| 261 |
+
self._vertical.append(size)
|
| 262 |
+
|
| 263 |
+
def add_auto_adjustable_area(self, use_axes, pad=0.1, adjust_dirs=None):
|
| 264 |
+
"""
|
| 265 |
+
Add auto-adjustable padding around *use_axes* to take their decorations
|
| 266 |
+
(title, labels, ticks, ticklabels) into account during layout.
|
| 267 |
+
|
| 268 |
+
Parameters
|
| 269 |
+
----------
|
| 270 |
+
use_axes : `~matplotlib.axes.Axes` or list of `~matplotlib.axes.Axes`
|
| 271 |
+
The Axes whose decorations are taken into account.
|
| 272 |
+
pad : float, default: 0.1
|
| 273 |
+
Additional padding in inches.
|
| 274 |
+
adjust_dirs : list of {"left", "right", "bottom", "top"}, optional
|
| 275 |
+
The sides where padding is added; defaults to all four sides.
|
| 276 |
+
"""
|
| 277 |
+
if adjust_dirs is None:
|
| 278 |
+
adjust_dirs = ["left", "right", "bottom", "top"]
|
| 279 |
+
for d in adjust_dirs:
|
| 280 |
+
self.append_size(d, Size._AxesDecorationsSize(use_axes, d) + pad)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class SubplotDivider(Divider):
|
| 284 |
+
"""
|
| 285 |
+
The Divider class whose rectangle area is specified as a subplot geometry.
|
| 286 |
+
"""
|
| 287 |
+
|
| 288 |
+
def __init__(self, fig, *args, horizontal=None, vertical=None,
|
| 289 |
+
aspect=None, anchor='C'):
|
| 290 |
+
"""
|
| 291 |
+
Parameters
|
| 292 |
+
----------
|
| 293 |
+
fig : `~matplotlib.figure.Figure`
|
| 294 |
+
|
| 295 |
+
*args : tuple (*nrows*, *ncols*, *index*) or int
|
| 296 |
+
The array of subplots in the figure has dimensions ``(nrows,
|
| 297 |
+
ncols)``, and *index* is the index of the subplot being created.
|
| 298 |
+
*index* starts at 1 in the upper left corner and increases to the
|
| 299 |
+
right.
|
| 300 |
+
|
| 301 |
+
If *nrows*, *ncols*, and *index* are all single digit numbers, then
|
| 302 |
+
*args* can be passed as a single 3-digit number (e.g. 234 for
|
| 303 |
+
(2, 3, 4)).
|
| 304 |
+
horizontal : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`, optional
|
| 305 |
+
Sizes for horizontal division.
|
| 306 |
+
vertical : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`, optional
|
| 307 |
+
Sizes for vertical division.
|
| 308 |
+
aspect : bool, optional
|
| 309 |
+
Whether overall rectangular area is reduced so that the relative
|
| 310 |
+
part of the horizontal and vertical scales have the same scale.
|
| 311 |
+
anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
|
| 312 |
+
'NW', 'W'}, default: 'C'
|
| 313 |
+
Placement of the reduced rectangle, when *aspect* is True.
|
| 314 |
+
"""
|
| 315 |
+
self.figure = fig
|
| 316 |
+
super().__init__(fig, [0, 0, 1, 1],
|
| 317 |
+
horizontal=horizontal or [], vertical=vertical or [],
|
| 318 |
+
aspect=aspect, anchor=anchor)
|
| 319 |
+
self.set_subplotspec(SubplotSpec._from_subplot_args(fig, args))
|
| 320 |
+
|
| 321 |
+
def get_position(self):
|
| 322 |
+
"""Return the bounds of the subplot box."""
|
| 323 |
+
return self.get_subplotspec().get_position(self.figure).bounds
|
| 324 |
+
|
| 325 |
+
def get_subplotspec(self):
|
| 326 |
+
"""Get the SubplotSpec instance."""
|
| 327 |
+
return self._subplotspec
|
| 328 |
+
|
| 329 |
+
def set_subplotspec(self, subplotspec):
|
| 330 |
+
"""Set the SubplotSpec instance."""
|
| 331 |
+
self._subplotspec = subplotspec
|
| 332 |
+
self.set_position(subplotspec.get_position(self.figure))
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class AxesDivider(Divider):
|
| 336 |
+
"""
|
| 337 |
+
Divider based on the preexisting axes.
|
| 338 |
+
"""
|
| 339 |
+
|
| 340 |
+
def __init__(self, axes, xref=None, yref=None):
|
| 341 |
+
"""
|
| 342 |
+
Parameters
|
| 343 |
+
----------
|
| 344 |
+
axes : :class:`~matplotlib.axes.Axes`
|
| 345 |
+
xref
|
| 346 |
+
yref
|
| 347 |
+
"""
|
| 348 |
+
self._axes = axes
|
| 349 |
+
if xref is None:
|
| 350 |
+
self._xref = Size.AxesX(axes)
|
| 351 |
+
else:
|
| 352 |
+
self._xref = xref
|
| 353 |
+
if yref is None:
|
| 354 |
+
self._yref = Size.AxesY(axes)
|
| 355 |
+
else:
|
| 356 |
+
self._yref = yref
|
| 357 |
+
|
| 358 |
+
super().__init__(fig=axes.get_figure(), pos=None,
|
| 359 |
+
horizontal=[self._xref], vertical=[self._yref],
|
| 360 |
+
aspect=None, anchor="C")
|
| 361 |
+
|
| 362 |
+
def _get_new_axes(self, *, axes_class=None, **kwargs):
|
| 363 |
+
axes = self._axes
|
| 364 |
+
if axes_class is None:
|
| 365 |
+
axes_class = type(axes)
|
| 366 |
+
return axes_class(axes.get_figure(), axes.get_position(original=True),
|
| 367 |
+
**kwargs)
|
| 368 |
+
|
| 369 |
+
def new_horizontal(self, size, pad=None, pack_start=False, **kwargs):
|
| 370 |
+
"""
|
| 371 |
+
Helper method for ``append_axes("left")`` and ``append_axes("right")``.
|
| 372 |
+
|
| 373 |
+
See the documentation of `append_axes` for more details.
|
| 374 |
+
|
| 375 |
+
:meta private:
|
| 376 |
+
"""
|
| 377 |
+
if pad is None:
|
| 378 |
+
pad = mpl.rcParams["figure.subplot.wspace"] * self._xref
|
| 379 |
+
pos = "left" if pack_start else "right"
|
| 380 |
+
if pad:
|
| 381 |
+
if not isinstance(pad, Size._Base):
|
| 382 |
+
pad = Size.from_any(pad, fraction_ref=self._xref)
|
| 383 |
+
self.append_size(pos, pad)
|
| 384 |
+
if not isinstance(size, Size._Base):
|
| 385 |
+
size = Size.from_any(size, fraction_ref=self._xref)
|
| 386 |
+
self.append_size(pos, size)
|
| 387 |
+
locator = self.new_locator(
|
| 388 |
+
nx=0 if pack_start else len(self._horizontal) - 1,
|
| 389 |
+
ny=self._yrefindex)
|
| 390 |
+
ax = self._get_new_axes(**kwargs)
|
| 391 |
+
ax.set_axes_locator(locator)
|
| 392 |
+
return ax
|
| 393 |
+
|
| 394 |
+
def new_vertical(self, size, pad=None, pack_start=False, **kwargs):
|
| 395 |
+
"""
|
| 396 |
+
Helper method for ``append_axes("top")`` and ``append_axes("bottom")``.
|
| 397 |
+
|
| 398 |
+
See the documentation of `append_axes` for more details.
|
| 399 |
+
|
| 400 |
+
:meta private:
|
| 401 |
+
"""
|
| 402 |
+
if pad is None:
|
| 403 |
+
pad = mpl.rcParams["figure.subplot.hspace"] * self._yref
|
| 404 |
+
pos = "bottom" if pack_start else "top"
|
| 405 |
+
if pad:
|
| 406 |
+
if not isinstance(pad, Size._Base):
|
| 407 |
+
pad = Size.from_any(pad, fraction_ref=self._yref)
|
| 408 |
+
self.append_size(pos, pad)
|
| 409 |
+
if not isinstance(size, Size._Base):
|
| 410 |
+
size = Size.from_any(size, fraction_ref=self._yref)
|
| 411 |
+
self.append_size(pos, size)
|
| 412 |
+
locator = self.new_locator(
|
| 413 |
+
nx=self._xrefindex,
|
| 414 |
+
ny=0 if pack_start else len(self._vertical) - 1)
|
| 415 |
+
ax = self._get_new_axes(**kwargs)
|
| 416 |
+
ax.set_axes_locator(locator)
|
| 417 |
+
return ax
|
| 418 |
+
|
| 419 |
+
def append_axes(self, position, size, pad=None, *, axes_class=None,
|
| 420 |
+
**kwargs):
|
| 421 |
+
"""
|
| 422 |
+
Add a new axes on a given side of the main axes.
|
| 423 |
+
|
| 424 |
+
Parameters
|
| 425 |
+
----------
|
| 426 |
+
position : {"left", "right", "bottom", "top"}
|
| 427 |
+
Where the new axes is positioned relative to the main axes.
|
| 428 |
+
size : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str
|
| 429 |
+
The axes width or height. float or str arguments are interpreted
|
| 430 |
+
as ``axes_size.from_any(size, AxesX(<main_axes>))`` for left or
|
| 431 |
+
right axes, and likewise with ``AxesY`` for bottom or top axes.
|
| 432 |
+
pad : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str
|
| 433 |
+
Padding between the axes. float or str arguments are interpreted
|
| 434 |
+
as for *size*. Defaults to :rc:`figure.subplot.wspace` times the
|
| 435 |
+
main Axes width (left or right axes) or :rc:`figure.subplot.hspace`
|
| 436 |
+
times the main Axes height (bottom or top axes).
|
| 437 |
+
axes_class : subclass type of `~.axes.Axes`, optional
|
| 438 |
+
The type of the new axes. Defaults to the type of the main axes.
|
| 439 |
+
**kwargs
|
| 440 |
+
All extra keywords arguments are passed to the created axes.
|
| 441 |
+
"""
|
| 442 |
+
create_axes, pack_start = _api.check_getitem({
|
| 443 |
+
"left": (self.new_horizontal, True),
|
| 444 |
+
"right": (self.new_horizontal, False),
|
| 445 |
+
"bottom": (self.new_vertical, True),
|
| 446 |
+
"top": (self.new_vertical, False),
|
| 447 |
+
}, position=position)
|
| 448 |
+
ax = create_axes(
|
| 449 |
+
size, pad, pack_start=pack_start, axes_class=axes_class, **kwargs)
|
| 450 |
+
self._fig.add_axes(ax)
|
| 451 |
+
return ax
|
| 452 |
+
|
| 453 |
+
def get_aspect(self):
|
| 454 |
+
if self._aspect is None:
|
| 455 |
+
aspect = self._axes.get_aspect()
|
| 456 |
+
if aspect == "auto":
|
| 457 |
+
return False
|
| 458 |
+
else:
|
| 459 |
+
return True
|
| 460 |
+
else:
|
| 461 |
+
return self._aspect
|
| 462 |
+
|
| 463 |
+
def get_position(self):
|
| 464 |
+
if self._pos is None:
|
| 465 |
+
bbox = self._axes.get_position(original=True)
|
| 466 |
+
return bbox.bounds
|
| 467 |
+
else:
|
| 468 |
+
return self._pos
|
| 469 |
+
|
| 470 |
+
def get_anchor(self):
|
| 471 |
+
if self._anchor is None:
|
| 472 |
+
return self._axes.get_anchor()
|
| 473 |
+
else:
|
| 474 |
+
return self._anchor
|
| 475 |
+
|
| 476 |
+
def get_subplotspec(self):
|
| 477 |
+
return self._axes.get_subplotspec()
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
# Helper for HBoxDivider/VBoxDivider.
|
| 481 |
+
# The variable names are written for a horizontal layout, but the calculations
|
| 482 |
+
# work identically for vertical layouts.
|
| 483 |
+
def _locate(x, y, w, h, summed_widths, equal_heights, fig_w, fig_h, anchor):
|
| 484 |
+
|
| 485 |
+
total_width = fig_w * w
|
| 486 |
+
max_height = fig_h * h
|
| 487 |
+
|
| 488 |
+
# Determine the k factors.
|
| 489 |
+
n = len(equal_heights)
|
| 490 |
+
eq_rels, eq_abss = equal_heights.T
|
| 491 |
+
sm_rels, sm_abss = summed_widths.T
|
| 492 |
+
A = np.diag([*eq_rels, 0])
|
| 493 |
+
A[:n, -1] = -1
|
| 494 |
+
A[-1, :-1] = sm_rels
|
| 495 |
+
B = [*(-eq_abss), total_width - sm_abss.sum()]
|
| 496 |
+
# A @ K = B: This finds factors {k_0, ..., k_{N-1}, H} so that
|
| 497 |
+
# eq_rel_i * k_i + eq_abs_i = H for all i: all axes have the same height
|
| 498 |
+
# sum(sm_rel_i * k_i + sm_abs_i) = total_width: fixed total width
|
| 499 |
+
# (foo_rel_i * k_i + foo_abs_i will end up being the size of foo.)
|
| 500 |
+
*karray, height = np.linalg.solve(A, B)
|
| 501 |
+
if height > max_height: # Additionally, upper-bound the height.
|
| 502 |
+
karray = (max_height - eq_abss) / eq_rels
|
| 503 |
+
|
| 504 |
+
# Compute the offsets corresponding to these factors.
|
| 505 |
+
ox = np.cumsum([0, *(sm_rels * karray + sm_abss)])
|
| 506 |
+
ww = (ox[-1] - ox[0]) / fig_w
|
| 507 |
+
h0_rel, h0_abs = equal_heights[0]
|
| 508 |
+
hh = (karray[0]*h0_rel + h0_abs) / fig_h
|
| 509 |
+
pb = mtransforms.Bbox.from_bounds(x, y, w, h)
|
| 510 |
+
pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh)
|
| 511 |
+
x0, y0 = pb1.anchored(anchor, pb).p0
|
| 512 |
+
|
| 513 |
+
return x0, y0, ox, hh
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
class HBoxDivider(SubplotDivider):
|
| 517 |
+
"""
|
| 518 |
+
A `.SubplotDivider` for laying out axes horizontally, while ensuring that
|
| 519 |
+
they have equal heights.
|
| 520 |
+
|
| 521 |
+
Examples
|
| 522 |
+
--------
|
| 523 |
+
.. plot:: gallery/axes_grid1/demo_axes_hbox_divider.py
|
| 524 |
+
"""
|
| 525 |
+
|
| 526 |
+
def new_locator(self, nx, nx1=None):
|
| 527 |
+
"""
|
| 528 |
+
Create an axes locator callable for the specified cell.
|
| 529 |
+
|
| 530 |
+
Parameters
|
| 531 |
+
----------
|
| 532 |
+
nx, nx1 : int
|
| 533 |
+
Integers specifying the column-position of the
|
| 534 |
+
cell. When *nx1* is None, a single *nx*-th column is
|
| 535 |
+
specified. Otherwise, location of columns spanning between *nx*
|
| 536 |
+
to *nx1* (but excluding *nx1*-th column) is specified.
|
| 537 |
+
"""
|
| 538 |
+
return super().new_locator(nx, 0, nx1, 0)
|
| 539 |
+
|
| 540 |
+
def _locate(self, nx, ny, nx1, ny1, axes, renderer):
|
| 541 |
+
# docstring inherited
|
| 542 |
+
nx += self._xrefindex
|
| 543 |
+
nx1 += self._xrefindex
|
| 544 |
+
fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
|
| 545 |
+
x, y, w, h = self.get_position_runtime(axes, renderer)
|
| 546 |
+
summed_ws = self.get_horizontal_sizes(renderer)
|
| 547 |
+
equal_hs = self.get_vertical_sizes(renderer)
|
| 548 |
+
x0, y0, ox, hh = _locate(
|
| 549 |
+
x, y, w, h, summed_ws, equal_hs, fig_w, fig_h, self.get_anchor())
|
| 550 |
+
if nx1 is None:
|
| 551 |
+
nx1 = -1
|
| 552 |
+
x1, w1 = x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w
|
| 553 |
+
y1, h1 = y0, hh
|
| 554 |
+
return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
class VBoxDivider(SubplotDivider):
|
| 558 |
+
"""
|
| 559 |
+
A `.SubplotDivider` for laying out axes vertically, while ensuring that
|
| 560 |
+
they have equal widths.
|
| 561 |
+
"""
|
| 562 |
+
|
| 563 |
+
def new_locator(self, ny, ny1=None):
|
| 564 |
+
"""
|
| 565 |
+
Create an axes locator callable for the specified cell.
|
| 566 |
+
|
| 567 |
+
Parameters
|
| 568 |
+
----------
|
| 569 |
+
ny, ny1 : int
|
| 570 |
+
Integers specifying the row-position of the
|
| 571 |
+
cell. When *ny1* is None, a single *ny*-th row is
|
| 572 |
+
specified. Otherwise, location of rows spanning between *ny*
|
| 573 |
+
to *ny1* (but excluding *ny1*-th row) is specified.
|
| 574 |
+
"""
|
| 575 |
+
return super().new_locator(0, ny, 0, ny1)
|
| 576 |
+
|
| 577 |
+
def _locate(self, nx, ny, nx1, ny1, axes, renderer):
|
| 578 |
+
# docstring inherited
|
| 579 |
+
ny += self._yrefindex
|
| 580 |
+
ny1 += self._yrefindex
|
| 581 |
+
fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
|
| 582 |
+
x, y, w, h = self.get_position_runtime(axes, renderer)
|
| 583 |
+
summed_hs = self.get_vertical_sizes(renderer)
|
| 584 |
+
equal_ws = self.get_horizontal_sizes(renderer)
|
| 585 |
+
y0, x0, oy, ww = _locate(
|
| 586 |
+
y, x, h, w, summed_hs, equal_ws, fig_h, fig_w, self.get_anchor())
|
| 587 |
+
if ny1 is None:
|
| 588 |
+
ny1 = -1
|
| 589 |
+
x1, w1 = x0, ww
|
| 590 |
+
y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h
|
| 591 |
+
return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def make_axes_locatable(axes):
|
| 595 |
+
divider = AxesDivider(axes)
|
| 596 |
+
locator = divider.new_locator(nx=0, ny=0)
|
| 597 |
+
axes.set_axes_locator(locator)
|
| 598 |
+
|
| 599 |
+
return divider
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def make_axes_area_auto_adjustable(
|
| 603 |
+
ax, use_axes=None, pad=0.1, adjust_dirs=None):
|
| 604 |
+
"""
|
| 605 |
+
Add auto-adjustable padding around *ax* to take its decorations (title,
|
| 606 |
+
labels, ticks, ticklabels) into account during layout, using
|
| 607 |
+
`.Divider.add_auto_adjustable_area`.
|
| 608 |
+
|
| 609 |
+
By default, padding is determined from the decorations of *ax*.
|
| 610 |
+
Pass *use_axes* to consider the decorations of other Axes instead.
|
| 611 |
+
"""
|
| 612 |
+
if adjust_dirs is None:
|
| 613 |
+
adjust_dirs = ["left", "right", "bottom", "top"]
|
| 614 |
+
divider = make_axes_locatable(ax)
|
| 615 |
+
if use_axes is None:
|
| 616 |
+
use_axes = ax
|
| 617 |
+
divider.add_auto_adjustable_area(use_axes=use_axes, pad=pad,
|
| 618 |
+
adjust_dirs=adjust_dirs)
|
shared/package-files/24/244001226e8b3724826d252ae872d2fbfa9318adc78157127125cba43b2b27ca/test_isocalendar.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pandas import (
|
| 2 |
+
DataFrame,
|
| 3 |
+
DatetimeIndex,
|
| 4 |
+
date_range,
|
| 5 |
+
)
|
| 6 |
+
import pandas._testing as tm
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_isocalendar_returns_correct_values_close_to_new_year_with_tz():
|
| 10 |
+
# GH#6538: Check that DatetimeIndex and its TimeStamp elements
|
| 11 |
+
# return the same weekofyear accessor close to new year w/ tz
|
| 12 |
+
dates = ["2013/12/29", "2013/12/30", "2013/12/31"]
|
| 13 |
+
dates = DatetimeIndex(dates, tz="Europe/Brussels")
|
| 14 |
+
result = dates.isocalendar()
|
| 15 |
+
expected_data_frame = DataFrame(
|
| 16 |
+
[[2013, 52, 7], [2014, 1, 1], [2014, 1, 2]],
|
| 17 |
+
columns=["year", "week", "day"],
|
| 18 |
+
index=dates,
|
| 19 |
+
dtype="UInt32",
|
| 20 |
+
)
|
| 21 |
+
tm.assert_frame_equal(result, expected_data_frame)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_dti_timestamp_isocalendar_fields():
|
| 25 |
+
idx = date_range("2020-01-01", periods=10)
|
| 26 |
+
expected = tuple(idx.isocalendar().iloc[-1].to_list())
|
| 27 |
+
result = idx[-1].isocalendar()
|
| 28 |
+
assert result == expected
|
shared/package-files/24/24415b8f3a5774313e414ce08ad16956d9dbd2f7b93418da69c833d6e8a5dd38/test_shimmodule.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from IPython.utils.shimmodule import ShimModule
|
| 2 |
+
import IPython
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def test_shimmodule_repr_does_not_fail_on_import_error():
|
| 6 |
+
shim_module = ShimModule("shim_module", mirror="mirrored_module_does_not_exist")
|
| 7 |
+
repr(shim_module)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_shimmodule_repr_forwards_to_module():
|
| 11 |
+
shim_module = ShimModule("shim_module", mirror="IPython")
|
| 12 |
+
assert repr(shim_module) == repr(IPython)
|
shared/package-files/24/2443e65ae9a693b8347671f908438d3dd72ad29ab2384a227e1b8f1734ac5e36/METADATA
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: referencing
|
| 3 |
+
Version: 0.30.2
|
| 4 |
+
Summary: JSON Referencing + Python
|
| 5 |
+
Project-URL: Documentation, https://referencing.readthedocs.io/
|
| 6 |
+
Project-URL: Homepage, https://github.com/python-jsonschema/referencing
|
| 7 |
+
Project-URL: Issues, https://github.com/python-jsonschema/referencing/issues/
|
| 8 |
+
Project-URL: Funding, https://github.com/sponsors/Julian
|
| 9 |
+
Project-URL: Source, https://github.com/python-jsonschema/referencing
|
| 10 |
+
Author: Julian Berman
|
| 11 |
+
Author-email: Julian+referencing@GrayVines.com
|
| 12 |
+
License: MIT
|
| 13 |
+
License-File: COPYING
|
| 14 |
+
Keywords: asyncapi,json,jsonschema,openapi,referencing
|
| 15 |
+
Classifier: Development Status :: 3 - Alpha
|
| 16 |
+
Classifier: Intended Audience :: Developers
|
| 17 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 18 |
+
Classifier: Operating System :: OS Independent
|
| 19 |
+
Classifier: Programming Language :: Python
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 25 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 26 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 27 |
+
Classifier: Topic :: File Formats :: JSON
|
| 28 |
+
Classifier: Topic :: File Formats :: JSON :: JSON Schema
|
| 29 |
+
Requires-Python: >=3.8
|
| 30 |
+
Requires-Dist: attrs>=22.2.0
|
| 31 |
+
Requires-Dist: rpds-py>=0.7.0
|
| 32 |
+
Description-Content-Type: text/x-rst
|
| 33 |
+
|
| 34 |
+
===============
|
| 35 |
+
``referencing``
|
| 36 |
+
===============
|
| 37 |
+
|
| 38 |
+
|PyPI| |Pythons| |CI| |ReadTheDocs| |pre-commit|
|
| 39 |
+
|
| 40 |
+
.. |PyPI| image:: https://img.shields.io/pypi/v/referencing.svg
|
| 41 |
+
:alt: PyPI version
|
| 42 |
+
:target: https://pypi.org/project/referencing/
|
| 43 |
+
|
| 44 |
+
.. |Pythons| image:: https://img.shields.io/pypi/pyversions/referencing.svg
|
| 45 |
+
:alt: Supported Python versions
|
| 46 |
+
:target: https://pypi.org/project/referencing/
|
| 47 |
+
|
| 48 |
+
.. |CI| image:: https://github.com/python-jsonschema/referencing/workflows/CI/badge.svg
|
| 49 |
+
:alt: Build status
|
| 50 |
+
:target: https://github.com/python-jsonschema/referencing/actions?query=workflow%3ACI
|
| 51 |
+
|
| 52 |
+
.. |ReadTheDocs| image:: https://readthedocs.org/projects/referencing/badge/?version=stable&style=flat
|
| 53 |
+
:alt: ReadTheDocs status
|
| 54 |
+
:target: https://referencing.readthedocs.io/en/stable/
|
| 55 |
+
|
| 56 |
+
.. |pre-commit| image:: https://results.pre-commit.ci/badge/github/python-jsonschema/referencing/main.svg
|
| 57 |
+
:alt: pre-commit.ci status
|
| 58 |
+
:target: https://results.pre-commit.ci/latest/github/python-jsonschema/referencing/main
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
An implementation-agnostic implementation of JSON reference resolution.
|
| 62 |
+
|
| 63 |
+
See `the documentation <https://referencing.readthedocs.io/>`_ for more details.
|
shared/package-files/24/244432432425902d28e994dd7958d984220e87a70ae5317b1f4d0f925b3eb142/GMT+10
ADDED
|
Binary file (117 Bytes). View file
|
|
|
shared/package-files/24/2446203c7a2bbe557dce6f2b235f7e79cba0addfdb6f97d3c46850e63aa36c0f/_thread_flow_location.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DO NOT EDIT! This file was generated by jschema_to_python version 0.0.1.dev29,
|
| 2 |
+
# with extension for dataclasses and type annotation.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import dataclasses
|
| 7 |
+
from typing import Any, List, Literal, Optional
|
| 8 |
+
|
| 9 |
+
from torch.onnx._internal.diagnostics.infra.sarif import (
|
| 10 |
+
_location,
|
| 11 |
+
_property_bag,
|
| 12 |
+
_reporting_descriptor_reference,
|
| 13 |
+
_stack,
|
| 14 |
+
_web_request,
|
| 15 |
+
_web_response,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclasses.dataclass
|
| 20 |
+
class ThreadFlowLocation(object):
|
| 21 |
+
"""A location visited by an analysis tool while simulating or monitoring the execution of a program."""
|
| 22 |
+
|
| 23 |
+
execution_order: int = dataclasses.field(
|
| 24 |
+
default=-1, metadata={"schema_property_name": "executionOrder"}
|
| 25 |
+
)
|
| 26 |
+
execution_time_utc: Optional[str] = dataclasses.field(
|
| 27 |
+
default=None, metadata={"schema_property_name": "executionTimeUtc"}
|
| 28 |
+
)
|
| 29 |
+
importance: Literal["important", "essential", "unimportant"] = dataclasses.field(
|
| 30 |
+
default="important", metadata={"schema_property_name": "importance"}
|
| 31 |
+
)
|
| 32 |
+
index: int = dataclasses.field(
|
| 33 |
+
default=-1, metadata={"schema_property_name": "index"}
|
| 34 |
+
)
|
| 35 |
+
kinds: Optional[List[str]] = dataclasses.field(
|
| 36 |
+
default=None, metadata={"schema_property_name": "kinds"}
|
| 37 |
+
)
|
| 38 |
+
location: Optional[_location.Location] = dataclasses.field(
|
| 39 |
+
default=None, metadata={"schema_property_name": "location"}
|
| 40 |
+
)
|
| 41 |
+
module: Optional[str] = dataclasses.field(
|
| 42 |
+
default=None, metadata={"schema_property_name": "module"}
|
| 43 |
+
)
|
| 44 |
+
nesting_level: Optional[int] = dataclasses.field(
|
| 45 |
+
default=None, metadata={"schema_property_name": "nestingLevel"}
|
| 46 |
+
)
|
| 47 |
+
properties: Optional[_property_bag.PropertyBag] = dataclasses.field(
|
| 48 |
+
default=None, metadata={"schema_property_name": "properties"}
|
| 49 |
+
)
|
| 50 |
+
stack: Optional[_stack.Stack] = dataclasses.field(
|
| 51 |
+
default=None, metadata={"schema_property_name": "stack"}
|
| 52 |
+
)
|
| 53 |
+
state: Any = dataclasses.field(
|
| 54 |
+
default=None, metadata={"schema_property_name": "state"}
|
| 55 |
+
)
|
| 56 |
+
taxa: Optional[
|
| 57 |
+
List[_reporting_descriptor_reference.ReportingDescriptorReference]
|
| 58 |
+
] = dataclasses.field(default=None, metadata={"schema_property_name": "taxa"})
|
| 59 |
+
web_request: Optional[_web_request.WebRequest] = dataclasses.field(
|
| 60 |
+
default=None, metadata={"schema_property_name": "webRequest"}
|
| 61 |
+
)
|
| 62 |
+
web_response: Optional[_web_response.WebResponse] = dataclasses.field(
|
| 63 |
+
default=None, metadata={"schema_property_name": "webResponse"}
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# flake8: noqa
|
shared/package-files/24/2449929a6aaa2f26b0f0fe75814226661f06c20f62d7349ef83a2a022b67da77/__init__.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import absolute_import
|
| 2 |
+
|
| 3 |
+
# For backwards compatibility, provide imports that used to be here.
|
| 4 |
+
from .connection import is_connection_dropped
|
| 5 |
+
from .request import SKIP_HEADER, SKIPPABLE_HEADERS, make_headers
|
| 6 |
+
from .response import is_fp_closed
|
| 7 |
+
from .retry import Retry
|
| 8 |
+
from .ssl_ import (
|
| 9 |
+
ALPN_PROTOCOLS,
|
| 10 |
+
HAS_SNI,
|
| 11 |
+
IS_PYOPENSSL,
|
| 12 |
+
IS_SECURETRANSPORT,
|
| 13 |
+
PROTOCOL_TLS,
|
| 14 |
+
SSLContext,
|
| 15 |
+
assert_fingerprint,
|
| 16 |
+
resolve_cert_reqs,
|
| 17 |
+
resolve_ssl_version,
|
| 18 |
+
ssl_wrap_socket,
|
| 19 |
+
)
|
| 20 |
+
from .timeout import Timeout, current_time
|
| 21 |
+
from .url import Url, get_host, parse_url, split_first
|
| 22 |
+
from .wait import wait_for_read, wait_for_write
|
| 23 |
+
|
| 24 |
+
__all__ = (
|
| 25 |
+
"HAS_SNI",
|
| 26 |
+
"IS_PYOPENSSL",
|
| 27 |
+
"IS_SECURETRANSPORT",
|
| 28 |
+
"SSLContext",
|
| 29 |
+
"PROTOCOL_TLS",
|
| 30 |
+
"ALPN_PROTOCOLS",
|
| 31 |
+
"Retry",
|
| 32 |
+
"Timeout",
|
| 33 |
+
"Url",
|
| 34 |
+
"assert_fingerprint",
|
| 35 |
+
"current_time",
|
| 36 |
+
"is_connection_dropped",
|
| 37 |
+
"is_fp_closed",
|
| 38 |
+
"get_host",
|
| 39 |
+
"parse_url",
|
| 40 |
+
"make_headers",
|
| 41 |
+
"resolve_cert_reqs",
|
| 42 |
+
"resolve_ssl_version",
|
| 43 |
+
"split_first",
|
| 44 |
+
"ssl_wrap_socket",
|
| 45 |
+
"wait_for_read",
|
| 46 |
+
"wait_for_write",
|
| 47 |
+
"SKIP_HEADER",
|
| 48 |
+
"SKIPPABLE_HEADERS",
|
| 49 |
+
)
|
shared/package-files/24/244efc06cf6026643cd2adbbbfc92f2481210e8f1f4d5ac59c2b3a61b7a9e1f8/spectral.py
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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manifold import SpectralEmbedding
|
| 11 |
+
from sklearn.metrics import pairwise_distances
|
| 12 |
+
from sklearn.metrics.pairwise import _VALID_METRICS as SKLEARN_PAIRWISE_VALID_METRICS
|
| 13 |
+
|
| 14 |
+
from umap.distances import pairwise_special_metric, SPECIAL_METRICS
|
| 15 |
+
from umap.sparse import SPARSE_SPECIAL_METRICS, sparse_named_distances
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def component_layout(
|
| 19 |
+
data,
|
| 20 |
+
n_components,
|
| 21 |
+
component_labels,
|
| 22 |
+
dim,
|
| 23 |
+
random_state,
|
| 24 |
+
metric="euclidean",
|
| 25 |
+
metric_kwds={},
|
| 26 |
+
):
|
| 27 |
+
"""Provide a layout relating the separate connected components. This is done
|
| 28 |
+
by taking the centroid of each component and then performing a spectral embedding
|
| 29 |
+
of the centroids.
|
| 30 |
+
|
| 31 |
+
Parameters
|
| 32 |
+
----------
|
| 33 |
+
data: array of shape (n_samples, n_features)
|
| 34 |
+
The source data -- required so we can generate centroids for each
|
| 35 |
+
connected component of the graph.
|
| 36 |
+
|
| 37 |
+
n_components: int
|
| 38 |
+
The number of distinct components to be layed out.
|
| 39 |
+
|
| 40 |
+
component_labels: array of shape (n_samples)
|
| 41 |
+
For each vertex in the graph the label of the component to
|
| 42 |
+
which the vertex belongs.
|
| 43 |
+
|
| 44 |
+
dim: int
|
| 45 |
+
The chosen embedding dimension.
|
| 46 |
+
|
| 47 |
+
metric: string or callable (optional, default 'euclidean')
|
| 48 |
+
The metric used to measure distances among the source data points.
|
| 49 |
+
|
| 50 |
+
metric_kwds: dict (optional, default {})
|
| 51 |
+
Keyword arguments to be passed to the metric function.
|
| 52 |
+
If metric is 'precomputed', 'linkage' keyword can be used to specify
|
| 53 |
+
'average', 'complete', or 'single' linkage. Default is 'average'
|
| 54 |
+
|
| 55 |
+
Returns
|
| 56 |
+
-------
|
| 57 |
+
component_embedding: array of shape (n_components, dim)
|
| 58 |
+
The ``dim``-dimensional embedding of the ``n_components``-many
|
| 59 |
+
connected components.
|
| 60 |
+
"""
|
| 61 |
+
if data is None:
|
| 62 |
+
# We don't have data to work with; just guess
|
| 63 |
+
return np.random.random(size=(n_components, dim)) * 10.0
|
| 64 |
+
|
| 65 |
+
component_centroids = np.empty((n_components, data.shape[1]), dtype=np.float64)
|
| 66 |
+
|
| 67 |
+
if metric == "precomputed":
|
| 68 |
+
# cannot compute centroids from precomputed distances
|
| 69 |
+
# instead, compute centroid distances using linkage
|
| 70 |
+
distance_matrix = np.zeros((n_components, n_components), dtype=np.float64)
|
| 71 |
+
linkage = metric_kwds.get("linkage", "average")
|
| 72 |
+
if linkage == "average":
|
| 73 |
+
linkage = np.mean
|
| 74 |
+
elif linkage == "complete":
|
| 75 |
+
linkage = np.max
|
| 76 |
+
elif linkage == "single":
|
| 77 |
+
linkage = np.min
|
| 78 |
+
else:
|
| 79 |
+
raise ValueError(
|
| 80 |
+
"Unrecognized linkage '%s'. Please choose from "
|
| 81 |
+
"'average', 'complete', or 'single'" % linkage
|
| 82 |
+
)
|
| 83 |
+
for c_i in range(n_components):
|
| 84 |
+
dm_i = data[component_labels == c_i]
|
| 85 |
+
for c_j in range(c_i + 1, n_components):
|
| 86 |
+
dist = linkage(dm_i[:, component_labels == c_j])
|
| 87 |
+
distance_matrix[c_i, c_j] = dist
|
| 88 |
+
distance_matrix[c_j, c_i] = dist
|
| 89 |
+
else:
|
| 90 |
+
for label in range(n_components):
|
| 91 |
+
component_centroids[label] = data[component_labels == label].mean(axis=0)
|
| 92 |
+
|
| 93 |
+
if scipy.sparse.isspmatrix(component_centroids):
|
| 94 |
+
warn(
|
| 95 |
+
"Forcing component centroids to dense; if you are running out of "
|
| 96 |
+
"memory then consider increasing n_neighbors."
|
| 97 |
+
)
|
| 98 |
+
component_centroids = component_centroids.toarray()
|
| 99 |
+
|
| 100 |
+
if metric in SPECIAL_METRICS:
|
| 101 |
+
distance_matrix = pairwise_special_metric(
|
| 102 |
+
component_centroids,
|
| 103 |
+
metric=metric,
|
| 104 |
+
kwds=metric_kwds,
|
| 105 |
+
)
|
| 106 |
+
elif metric in SPARSE_SPECIAL_METRICS:
|
| 107 |
+
distance_matrix = pairwise_special_metric(
|
| 108 |
+
component_centroids,
|
| 109 |
+
metric=SPARSE_SPECIAL_METRICS[metric],
|
| 110 |
+
kwds=metric_kwds,
|
| 111 |
+
)
|
| 112 |
+
else:
|
| 113 |
+
if callable(metric) and scipy.sparse.isspmatrix(data):
|
| 114 |
+
function_to_name_mapping = {
|
| 115 |
+
sparse_named_distances[k]: k
|
| 116 |
+
for k in set(SKLEARN_PAIRWISE_VALID_METRICS)
|
| 117 |
+
& set(sparse_named_distances.keys())
|
| 118 |
+
}
|
| 119 |
+
try:
|
| 120 |
+
metric_name = function_to_name_mapping[metric]
|
| 121 |
+
except KeyError:
|
| 122 |
+
raise NotImplementedError(
|
| 123 |
+
"Multicomponent layout for custom "
|
| 124 |
+
"sparse metrics is not implemented at "
|
| 125 |
+
"this time."
|
| 126 |
+
)
|
| 127 |
+
distance_matrix = pairwise_distances(
|
| 128 |
+
component_centroids, metric=metric_name, **metric_kwds
|
| 129 |
+
)
|
| 130 |
+
else:
|
| 131 |
+
distance_matrix = pairwise_distances(
|
| 132 |
+
component_centroids, metric=metric, **metric_kwds
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
affinity_matrix = np.exp(-(distance_matrix**2))
|
| 136 |
+
|
| 137 |
+
component_embedding = SpectralEmbedding(
|
| 138 |
+
n_components=dim, affinity="precomputed", random_state=random_state
|
| 139 |
+
).fit_transform(affinity_matrix)
|
| 140 |
+
component_embedding /= component_embedding.max()
|
| 141 |
+
|
| 142 |
+
return component_embedding
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def multi_component_layout(
|
| 146 |
+
data,
|
| 147 |
+
graph,
|
| 148 |
+
n_components,
|
| 149 |
+
component_labels,
|
| 150 |
+
dim,
|
| 151 |
+
random_state,
|
| 152 |
+
metric="euclidean",
|
| 153 |
+
metric_kwds={},
|
| 154 |
+
init="random",
|
| 155 |
+
tol=0.0,
|
| 156 |
+
maxiter=0,
|
| 157 |
+
):
|
| 158 |
+
"""Specialised layout algorithm for dealing with graphs with many connected components.
|
| 159 |
+
This will first find relative positions for the components by spectrally embedding
|
| 160 |
+
their centroids, then spectrally embed each individual connected component positioning
|
| 161 |
+
them according to the centroid embeddings. This provides a decent embedding of each
|
| 162 |
+
component while placing the components in good relative positions to one another.
|
| 163 |
+
|
| 164 |
+
Parameters
|
| 165 |
+
----------
|
| 166 |
+
data: array of shape (n_samples, n_features)
|
| 167 |
+
The source data -- required so we can generate centroids for each
|
| 168 |
+
connected component of the graph.
|
| 169 |
+
|
| 170 |
+
graph: sparse matrix
|
| 171 |
+
The adjacency matrix of the graph to be embedded.
|
| 172 |
+
|
| 173 |
+
n_components: int
|
| 174 |
+
The number of distinct components to be layed out.
|
| 175 |
+
|
| 176 |
+
component_labels: array of shape (n_samples)
|
| 177 |
+
For each vertex in the graph the label of the component to
|
| 178 |
+
which the vertex belongs.
|
| 179 |
+
|
| 180 |
+
dim: int
|
| 181 |
+
The chosen embedding dimension.
|
| 182 |
+
|
| 183 |
+
metric: string or callable (optional, default 'euclidean')
|
| 184 |
+
The metric used to measure distances among the source data points.
|
| 185 |
+
|
| 186 |
+
metric_kwds: dict (optional, default {})
|
| 187 |
+
Keyword arguments to be passed to the metric function.
|
| 188 |
+
|
| 189 |
+
init: string, either "random" or "tsvd"
|
| 190 |
+
Indicates to initialize the eigensolver. Use "random" (the default) to
|
| 191 |
+
use uniformly distributed random initialization; use "tsvd" to warm-start the
|
| 192 |
+
eigensolver with singular vectors of the Laplacian associated to the largest
|
| 193 |
+
singular values. This latter option also forces usage of the LOBPCG eigensolver;
|
| 194 |
+
with the former, ARPACK's solver ``eigsh`` will be used for smaller Laplacians.
|
| 195 |
+
|
| 196 |
+
tol: float, default chosen by implementation
|
| 197 |
+
Stopping tolerance for the numerical algorithm computing the embedding.
|
| 198 |
+
|
| 199 |
+
maxiter: int, default chosen by implementation
|
| 200 |
+
Number of iterations the numerical algorithm will go through at most as it
|
| 201 |
+
attempts to compute the embedding.
|
| 202 |
+
|
| 203 |
+
Returns
|
| 204 |
+
-------
|
| 205 |
+
embedding: array of shape (n_samples, dim)
|
| 206 |
+
The initial embedding of ``graph``.
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
result = np.empty((graph.shape[0], dim), dtype=np.float32)
|
| 210 |
+
|
| 211 |
+
if n_components > 2 * dim:
|
| 212 |
+
meta_embedding = component_layout(
|
| 213 |
+
data,
|
| 214 |
+
n_components,
|
| 215 |
+
component_labels,
|
| 216 |
+
dim,
|
| 217 |
+
random_state,
|
| 218 |
+
metric=metric,
|
| 219 |
+
metric_kwds=metric_kwds,
|
| 220 |
+
)
|
| 221 |
+
else:
|
| 222 |
+
k = int(np.ceil(n_components / 2.0))
|
| 223 |
+
base = np.hstack([np.eye(k), np.zeros((k, dim - k))])
|
| 224 |
+
meta_embedding = np.vstack([base, -base])[:n_components]
|
| 225 |
+
|
| 226 |
+
for label in range(n_components):
|
| 227 |
+
component_graph = graph.tocsr()[component_labels == label, :].tocsc()
|
| 228 |
+
component_graph = component_graph[:, component_labels == label].tocoo()
|
| 229 |
+
|
| 230 |
+
distances = pairwise_distances([meta_embedding[label]], meta_embedding)
|
| 231 |
+
data_range = distances[distances > 0.0].min() / 2.0
|
| 232 |
+
|
| 233 |
+
if component_graph.shape[0] < 2 * dim or component_graph.shape[0] <= dim + 1:
|
| 234 |
+
result[component_labels == label] = (
|
| 235 |
+
random_state.uniform(
|
| 236 |
+
low=-data_range,
|
| 237 |
+
high=data_range,
|
| 238 |
+
size=(component_graph.shape[0], dim),
|
| 239 |
+
)
|
| 240 |
+
+ meta_embedding[label]
|
| 241 |
+
)
|
| 242 |
+
else:
|
| 243 |
+
component_embedding = _spectral_layout(
|
| 244 |
+
data=None,
|
| 245 |
+
graph=component_graph,
|
| 246 |
+
dim=dim,
|
| 247 |
+
random_state=random_state,
|
| 248 |
+
metric=metric,
|
| 249 |
+
metric_kwds=metric_kwds,
|
| 250 |
+
init=init,
|
| 251 |
+
tol=tol,
|
| 252 |
+
maxiter=maxiter,
|
| 253 |
+
)
|
| 254 |
+
expansion = data_range / np.max(np.abs(component_embedding))
|
| 255 |
+
component_embedding *= expansion
|
| 256 |
+
result[component_labels == label] = (
|
| 257 |
+
component_embedding + meta_embedding[label]
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
return result
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def spectral_layout(
|
| 264 |
+
data,
|
| 265 |
+
graph,
|
| 266 |
+
dim,
|
| 267 |
+
random_state,
|
| 268 |
+
metric="euclidean",
|
| 269 |
+
metric_kwds={},
|
| 270 |
+
tol=0.0,
|
| 271 |
+
maxiter=0,
|
| 272 |
+
):
|
| 273 |
+
"""
|
| 274 |
+
Given a graph compute the spectral embedding of the graph. This is
|
| 275 |
+
simply the eigenvectors of the laplacian of the graph. Here we use the
|
| 276 |
+
normalized laplacian.
|
| 277 |
+
|
| 278 |
+
Parameters
|
| 279 |
+
----------
|
| 280 |
+
data: array of shape (n_samples, n_features)
|
| 281 |
+
The source data
|
| 282 |
+
|
| 283 |
+
graph: sparse matrix
|
| 284 |
+
The (weighted) adjacency matrix of the graph as a sparse matrix.
|
| 285 |
+
|
| 286 |
+
dim: int
|
| 287 |
+
The dimension of the space into which to embed.
|
| 288 |
+
|
| 289 |
+
random_state: numpy RandomState or equivalent
|
| 290 |
+
A state capable being used as a numpy random state.
|
| 291 |
+
|
| 292 |
+
tol: float, default chosen by implementation
|
| 293 |
+
Stopping tolerance for the numerical algorithm computing the embedding.
|
| 294 |
+
|
| 295 |
+
maxiter: int, default chosen by implementation
|
| 296 |
+
Number of iterations the numerical algorithm will go through at most as it
|
| 297 |
+
attempts to compute the embedding.
|
| 298 |
+
|
| 299 |
+
Returns
|
| 300 |
+
-------
|
| 301 |
+
embedding: array of shape (n_vertices, dim)
|
| 302 |
+
The spectral embedding of the graph.
|
| 303 |
+
"""
|
| 304 |
+
return _spectral_layout(
|
| 305 |
+
data=data,
|
| 306 |
+
graph=graph,
|
| 307 |
+
dim=dim,
|
| 308 |
+
random_state=random_state,
|
| 309 |
+
metric=metric,
|
| 310 |
+
metric_kwds=metric_kwds,
|
| 311 |
+
init="random",
|
| 312 |
+
tol=tol,
|
| 313 |
+
maxiter=maxiter,
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def tswspectral_layout(
|
| 318 |
+
data,
|
| 319 |
+
graph,
|
| 320 |
+
dim,
|
| 321 |
+
random_state,
|
| 322 |
+
metric="euclidean",
|
| 323 |
+
metric_kwds={},
|
| 324 |
+
method=None,
|
| 325 |
+
tol=0.0,
|
| 326 |
+
maxiter=0,
|
| 327 |
+
):
|
| 328 |
+
"""Given a graph, compute the spectral embedding of the graph. This is
|
| 329 |
+
simply the eigenvectors of the Laplacian of the graph. Here we use the
|
| 330 |
+
normalized laplacian and a truncated SVD-based guess of the
|
| 331 |
+
eigenvectors to "warm" up the eigensolver. This function should
|
| 332 |
+
give results of similar accuracy to the spectral_layout function, but
|
| 333 |
+
may converge more quickly for graph Laplacians that cause
|
| 334 |
+
spectral_layout to take an excessive amount of time to complete.
|
| 335 |
+
|
| 336 |
+
Parameters
|
| 337 |
+
----------
|
| 338 |
+
data: array of shape (n_samples, n_features)
|
| 339 |
+
The source data
|
| 340 |
+
|
| 341 |
+
graph: sparse matrix
|
| 342 |
+
The (weighted) adjacency matrix of the graph as a sparse matrix.
|
| 343 |
+
|
| 344 |
+
dim: int
|
| 345 |
+
The dimension of the space into which to embed.
|
| 346 |
+
|
| 347 |
+
random_state: numpy RandomState or equivalent
|
| 348 |
+
A state capable being used as a numpy random state.
|
| 349 |
+
|
| 350 |
+
metric: string or callable (optional, default 'euclidean')
|
| 351 |
+
The metric used to measure distances among the source data points.
|
| 352 |
+
Used only if the multiple connected components are found in the
|
| 353 |
+
graph.
|
| 354 |
+
|
| 355 |
+
metric_kwds: dict (optional, default {})
|
| 356 |
+
Keyword arguments to be passed to the metric function.
|
| 357 |
+
If metric is 'precomputed', 'linkage' keyword can be used to specify
|
| 358 |
+
'average', 'complete', or 'single' linkage. Default is 'average'.
|
| 359 |
+
Used only if the multiple connected components are found in the
|
| 360 |
+
graph.
|
| 361 |
+
|
| 362 |
+
method: str (optional, default None, values either 'eigsh' or 'lobpcg')
|
| 363 |
+
Name of the eigenvalue computation method to use to compute the spectral
|
| 364 |
+
embedding. If left to None (or empty string), as by default, the method is
|
| 365 |
+
chosen from the number of vectors in play: larger vector collections are
|
| 366 |
+
handled with lobpcg, smaller collections with eigsh. Method names correspond
|
| 367 |
+
to SciPy routines in scipy.sparse.linalg.
|
| 368 |
+
|
| 369 |
+
tol: float, default chosen by implementation
|
| 370 |
+
Stopping tolerance for the numerical algorithm computing the embedding.
|
| 371 |
+
|
| 372 |
+
maxiter: int, default chosen by implementation
|
| 373 |
+
Number of iterations the numerical algorithm will go through at most as it
|
| 374 |
+
attempts to compute the embedding.
|
| 375 |
+
|
| 376 |
+
Returns
|
| 377 |
+
-------
|
| 378 |
+
embedding: array of shape (n_vertices, dim)
|
| 379 |
+
The spectral embedding of the graph.
|
| 380 |
+
"""
|
| 381 |
+
return _spectral_layout(
|
| 382 |
+
data=data,
|
| 383 |
+
graph=graph,
|
| 384 |
+
dim=dim,
|
| 385 |
+
random_state=random_state,
|
| 386 |
+
metric=metric,
|
| 387 |
+
metric_kwds=metric_kwds,
|
| 388 |
+
init="tsvd",
|
| 389 |
+
method=method,
|
| 390 |
+
tol=tol,
|
| 391 |
+
maxiter=maxiter,
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def _spectral_layout(
|
| 396 |
+
data,
|
| 397 |
+
graph,
|
| 398 |
+
dim,
|
| 399 |
+
random_state,
|
| 400 |
+
metric="euclidean",
|
| 401 |
+
metric_kwds={},
|
| 402 |
+
init="random",
|
| 403 |
+
method=None,
|
| 404 |
+
tol=0.0,
|
| 405 |
+
maxiter=0,
|
| 406 |
+
):
|
| 407 |
+
"""General implementation of the spectral embedding of the graph, derived as
|
| 408 |
+
a subset of the eigenvectors of the normalized Laplacian of the graph. The numerical
|
| 409 |
+
method for computing the eigendecomposition is chosen through heuristics.
|
| 410 |
+
|
| 411 |
+
Parameters
|
| 412 |
+
----------
|
| 413 |
+
data: array of shape (n_samples, n_features)
|
| 414 |
+
The source data
|
| 415 |
+
|
| 416 |
+
graph: sparse matrix
|
| 417 |
+
The (weighted) adjacency matrix of the graph as a sparse matrix.
|
| 418 |
+
|
| 419 |
+
dim: int
|
| 420 |
+
The dimension of the space into which to embed.
|
| 421 |
+
|
| 422 |
+
random_state: numpy RandomState or equivalent
|
| 423 |
+
A state capable being used as a numpy random state.
|
| 424 |
+
|
| 425 |
+
metric: string or callable (optional, default 'euclidean')
|
| 426 |
+
The metric used to measure distances among the source data points.
|
| 427 |
+
Used only if the multiple connected components are found in the
|
| 428 |
+
graph.
|
| 429 |
+
|
| 430 |
+
metric_kwds: dict (optional, default {})
|
| 431 |
+
Keyword arguments to be passed to the metric function.
|
| 432 |
+
If metric is 'precomputed', 'linkage' keyword can be used to specify
|
| 433 |
+
'average', 'complete', or 'single' linkage. Default is 'average'.
|
| 434 |
+
Used only if the multiple connected components are found in the
|
| 435 |
+
graph.
|
| 436 |
+
|
| 437 |
+
init: string, either "random" or "tsvd"
|
| 438 |
+
Indicates to initialize the eigensolver. Use "random" (the default) to
|
| 439 |
+
use uniformly distributed random initialization; use "tsvd" to warm-start the
|
| 440 |
+
eigensolver with singular vectors of the Laplacian associated to the largest
|
| 441 |
+
singular values. This latter option also forces usage of the LOBPCG eigensolver;
|
| 442 |
+
with the former, ARPACK's solver ``eigsh`` will be used for smaller Laplacians.
|
| 443 |
+
|
| 444 |
+
method: string -- either "eigsh" or "lobpcg" -- or None
|
| 445 |
+
Name of the eigenvalue computation method to use to compute the spectral
|
| 446 |
+
embedding. If left to None (or empty string), as by default, the method is
|
| 447 |
+
chosen from the number of vectors in play: larger vector collections are
|
| 448 |
+
handled with lobpcg, smaller collections with eigsh. Method names correspond
|
| 449 |
+
to SciPy routines in scipy.sparse.linalg.
|
| 450 |
+
|
| 451 |
+
tol: float, default chosen by implementation
|
| 452 |
+
Stopping tolerance for the numerical algorithm computing the embedding.
|
| 453 |
+
|
| 454 |
+
maxiter: int, default chosen by implementation
|
| 455 |
+
Number of iterations the numerical algorithm will go through at most as it
|
| 456 |
+
attempts to compute the embedding.
|
| 457 |
+
|
| 458 |
+
Returns
|
| 459 |
+
-------
|
| 460 |
+
embedding: array of shape (n_vertices, dim)
|
| 461 |
+
The spectral embedding of the graph.
|
| 462 |
+
"""
|
| 463 |
+
n_samples = graph.shape[0]
|
| 464 |
+
n_components, labels = scipy.sparse.csgraph.connected_components(graph)
|
| 465 |
+
|
| 466 |
+
if n_components > 1:
|
| 467 |
+
return multi_component_layout(
|
| 468 |
+
data,
|
| 469 |
+
graph,
|
| 470 |
+
n_components,
|
| 471 |
+
labels,
|
| 472 |
+
dim,
|
| 473 |
+
random_state,
|
| 474 |
+
metric=metric,
|
| 475 |
+
metric_kwds=metric_kwds,
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
sqrt_deg = np.sqrt(np.asarray(graph.sum(axis=0)).squeeze())
|
| 479 |
+
# standard Laplacian
|
| 480 |
+
# D = scipy.sparse.spdiags(diag_data, 0, graph.shape[0], graph.shape[0])
|
| 481 |
+
# L = D - graph
|
| 482 |
+
# Normalized Laplacian
|
| 483 |
+
I = scipy.sparse.identity(graph.shape[0], dtype=np.float64)
|
| 484 |
+
D = scipy.sparse.spdiags(1.0 / sqrt_deg, 0, graph.shape[0], graph.shape[0])
|
| 485 |
+
L = I - D * graph * D
|
| 486 |
+
if not scipy.sparse.issparse(L):
|
| 487 |
+
L = np.asarray(L)
|
| 488 |
+
|
| 489 |
+
k = dim + 1
|
| 490 |
+
num_lanczos_vectors = max(2 * k + 1, int(np.sqrt(graph.shape[0])))
|
| 491 |
+
gen = (
|
| 492 |
+
random_state
|
| 493 |
+
if isinstance(random_state, (np.random.Generator, np.random.RandomState))
|
| 494 |
+
else np.random.default_rng(seed=random_state)
|
| 495 |
+
)
|
| 496 |
+
if not method:
|
| 497 |
+
method = "eigsh" if L.shape[0] < 2000000 else "lobpcg"
|
| 498 |
+
|
| 499 |
+
try:
|
| 500 |
+
if init == "random":
|
| 501 |
+
X = gen.normal(size=(L.shape[0], k))
|
| 502 |
+
elif init == "tsvd":
|
| 503 |
+
X = TruncatedSVD(
|
| 504 |
+
n_components=k,
|
| 505 |
+
random_state=random_state,
|
| 506 |
+
# algorithm="arpack"
|
| 507 |
+
).fit_transform(L)
|
| 508 |
+
else:
|
| 509 |
+
raise ValueError(
|
| 510 |
+
"The init parameter must be either 'random' or 'tsvd': "
|
| 511 |
+
f"{init} is invalid."
|
| 512 |
+
)
|
| 513 |
+
# For such a normalized Laplacian, the first eigenvector is always
|
| 514 |
+
# proportional to sqrt(degrees). We thus replace the first t-SVD guess
|
| 515 |
+
# with the exact value.
|
| 516 |
+
X[:, 0] = sqrt_deg / np.linalg.norm(sqrt_deg)
|
| 517 |
+
|
| 518 |
+
if method == "eigsh":
|
| 519 |
+
eigenvalues, eigenvectors = scipy.sparse.linalg.eigsh(
|
| 520 |
+
L,
|
| 521 |
+
k,
|
| 522 |
+
which="SM",
|
| 523 |
+
ncv=num_lanczos_vectors,
|
| 524 |
+
tol=tol or 1e-4,
|
| 525 |
+
v0=np.ones(L.shape[0]),
|
| 526 |
+
maxiter=maxiter or graph.shape[0] * 5,
|
| 527 |
+
)
|
| 528 |
+
elif method == "lobpcg":
|
| 529 |
+
with warnings.catch_warnings():
|
| 530 |
+
warnings.filterwarnings(
|
| 531 |
+
category=UserWarning,
|
| 532 |
+
message=r"(?ms).*not reaching the requested tolerance",
|
| 533 |
+
action="error",
|
| 534 |
+
)
|
| 535 |
+
eigenvalues, eigenvectors = scipy.sparse.linalg.lobpcg(
|
| 536 |
+
L,
|
| 537 |
+
np.asarray(X),
|
| 538 |
+
largest=False,
|
| 539 |
+
tol=tol or 1e-4,
|
| 540 |
+
maxiter=maxiter or 5 * graph.shape[0],
|
| 541 |
+
)
|
| 542 |
+
else:
|
| 543 |
+
raise ValueError("Method should either be None, 'eigsh' or 'lobpcg'")
|
| 544 |
+
|
| 545 |
+
order = np.argsort(eigenvalues)[1:k]
|
| 546 |
+
return eigenvectors[:, order]
|
| 547 |
+
except (scipy.sparse.linalg.ArpackError, UserWarning):
|
| 548 |
+
warn(
|
| 549 |
+
"Spectral initialisation failed! The eigenvector solver\n"
|
| 550 |
+
"failed. This is likely due to too small an eigengap. Consider\n"
|
| 551 |
+
"adding some noise or jitter to your data.\n\n"
|
| 552 |
+
"Falling back to random initialisation!"
|
| 553 |
+
)
|
| 554 |
+
return gen.uniform(low=-10.0, high=10.0, size=(graph.shape[0], dim))
|
shared/package-files/24/2453a1a5d8c04244ff7bb1449c76ee8dc796bb1ed41cb1cfb8c03c1f7b9ef370/gelu_meta_dispatch.h
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 meta {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor gelu(const at::Tensor & self, c10::string_view approximate="none");
|
| 21 |
+
TORCH_API at::Tensor & gelu_out(at::Tensor & out, const at::Tensor & self, c10::string_view approximate="none");
|
| 22 |
+
TORCH_API at::Tensor & gelu_outf(const at::Tensor & self, c10::string_view approximate, at::Tensor & out);
|
| 23 |
+
TORCH_API at::Tensor & gelu_(at::Tensor & self, c10::string_view approximate="none");
|
| 24 |
+
|
| 25 |
+
} // namespace meta
|
| 26 |
+
} // namespace at
|
shared/package-files/24/245536c3df1c07f5cdc1faea36d234c834e6a4477160efd4125da9808feb9edf/foo.f90
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module ops_module
|
| 2 |
+
|
| 3 |
+
abstract interface
|
| 4 |
+
subroutine op(x, y, z)
|
| 5 |
+
integer, intent(in) :: x, y
|
| 6 |
+
integer, intent(out) :: z
|
| 7 |
+
end subroutine
|
| 8 |
+
end interface
|
| 9 |
+
|
| 10 |
+
contains
|
| 11 |
+
|
| 12 |
+
subroutine foo(x, y, r1, r2)
|
| 13 |
+
integer, intent(in) :: x, y
|
| 14 |
+
integer, intent(out) :: r1, r2
|
| 15 |
+
procedure (op) add1, add2
|
| 16 |
+
procedure (op), pointer::p
|
| 17 |
+
p=>add1
|
| 18 |
+
call p(x, y, r1)
|
| 19 |
+
p=>add2
|
| 20 |
+
call p(x, y, r2)
|
| 21 |
+
end subroutine
|
| 22 |
+
end module
|
| 23 |
+
|
| 24 |
+
subroutine add1(x, y, z)
|
| 25 |
+
integer, intent(in) :: x, y
|
| 26 |
+
integer, intent(out) :: z
|
| 27 |
+
z = x + y
|
| 28 |
+
end subroutine
|
| 29 |
+
|
| 30 |
+
subroutine add2(x, y, z)
|
| 31 |
+
integer, intent(in) :: x, y
|
| 32 |
+
integer, intent(out) :: z
|
| 33 |
+
z = x + 2 * y
|
| 34 |
+
end subroutine
|
shared/package-files/24/245812393de1bba77b321f6c76abd2c42dd1c655651ff73282c5e9b17f7b60c6/recurrence.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Recurrence Operators"""
|
| 2 |
+
|
| 3 |
+
from sympy.core.singleton import S
|
| 4 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 5 |
+
from sympy.printing import sstr
|
| 6 |
+
from sympy.core.sympify import sympify
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def RecurrenceOperators(base, generator):
|
| 10 |
+
"""
|
| 11 |
+
Returns an Algebra of Recurrence Operators and the operator for
|
| 12 |
+
shifting i.e. the `Sn` operator.
|
| 13 |
+
The first argument needs to be the base polynomial ring for the algebra
|
| 14 |
+
and the second argument must be a generator which can be either a
|
| 15 |
+
noncommutative Symbol or a string.
|
| 16 |
+
|
| 17 |
+
Examples
|
| 18 |
+
========
|
| 19 |
+
|
| 20 |
+
>>> from sympy import ZZ
|
| 21 |
+
>>> from sympy import symbols
|
| 22 |
+
>>> from sympy.holonomic.recurrence import RecurrenceOperators
|
| 23 |
+
>>> n = symbols('n', integer=True)
|
| 24 |
+
>>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn')
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
ring = RecurrenceOperatorAlgebra(base, generator)
|
| 28 |
+
return (ring, ring.shift_operator)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class RecurrenceOperatorAlgebra:
|
| 32 |
+
"""
|
| 33 |
+
A Recurrence Operator Algebra is a set of noncommutative polynomials
|
| 34 |
+
in intermediate `Sn` and coefficients in a base ring A. It follows the
|
| 35 |
+
commutation rule:
|
| 36 |
+
Sn * a(n) = a(n + 1) * Sn
|
| 37 |
+
|
| 38 |
+
This class represents a Recurrence Operator Algebra and serves as the parent ring
|
| 39 |
+
for Recurrence Operators.
|
| 40 |
+
|
| 41 |
+
Examples
|
| 42 |
+
========
|
| 43 |
+
|
| 44 |
+
>>> from sympy import ZZ
|
| 45 |
+
>>> from sympy import symbols
|
| 46 |
+
>>> from sympy.holonomic.recurrence import RecurrenceOperators
|
| 47 |
+
>>> n = symbols('n', integer=True)
|
| 48 |
+
>>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn')
|
| 49 |
+
>>> R
|
| 50 |
+
Univariate Recurrence Operator Algebra in intermediate Sn over the base ring
|
| 51 |
+
ZZ[n]
|
| 52 |
+
|
| 53 |
+
See Also
|
| 54 |
+
========
|
| 55 |
+
|
| 56 |
+
RecurrenceOperator
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(self, base, generator):
|
| 60 |
+
# the base ring for the algebra
|
| 61 |
+
self.base = base
|
| 62 |
+
# the operator representing shift i.e. `Sn`
|
| 63 |
+
self.shift_operator = RecurrenceOperator(
|
| 64 |
+
[base.zero, base.one], self)
|
| 65 |
+
|
| 66 |
+
if generator is None:
|
| 67 |
+
self.gen_symbol = symbols('Sn', commutative=False)
|
| 68 |
+
else:
|
| 69 |
+
if isinstance(generator, str):
|
| 70 |
+
self.gen_symbol = symbols(generator, commutative=False)
|
| 71 |
+
elif isinstance(generator, Symbol):
|
| 72 |
+
self.gen_symbol = generator
|
| 73 |
+
|
| 74 |
+
def __str__(self):
|
| 75 |
+
string = 'Univariate Recurrence Operator Algebra in intermediate '\
|
| 76 |
+
+ sstr(self.gen_symbol) + ' over the base ring ' + \
|
| 77 |
+
(self.base).__str__()
|
| 78 |
+
|
| 79 |
+
return string
|
| 80 |
+
|
| 81 |
+
__repr__ = __str__
|
| 82 |
+
|
| 83 |
+
def __eq__(self, other):
|
| 84 |
+
if self.base == other.base and self.gen_symbol == other.gen_symbol:
|
| 85 |
+
return True
|
| 86 |
+
else:
|
| 87 |
+
return False
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _add_lists(list1, list2):
|
| 91 |
+
if len(list1) <= len(list2):
|
| 92 |
+
sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):]
|
| 93 |
+
else:
|
| 94 |
+
sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):]
|
| 95 |
+
return sol
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class RecurrenceOperator:
|
| 99 |
+
"""
|
| 100 |
+
The Recurrence Operators are defined by a list of polynomials
|
| 101 |
+
in the base ring and the parent ring of the Operator.
|
| 102 |
+
|
| 103 |
+
Explanation
|
| 104 |
+
===========
|
| 105 |
+
|
| 106 |
+
Takes a list of polynomials for each power of Sn and the
|
| 107 |
+
parent ring which must be an instance of RecurrenceOperatorAlgebra.
|
| 108 |
+
|
| 109 |
+
A Recurrence Operator can be created easily using
|
| 110 |
+
the operator `Sn`. See examples below.
|
| 111 |
+
|
| 112 |
+
Examples
|
| 113 |
+
========
|
| 114 |
+
|
| 115 |
+
>>> from sympy.holonomic.recurrence import RecurrenceOperator, RecurrenceOperators
|
| 116 |
+
>>> from sympy import ZZ
|
| 117 |
+
>>> from sympy import symbols
|
| 118 |
+
>>> n = symbols('n', integer=True)
|
| 119 |
+
>>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n),'Sn')
|
| 120 |
+
|
| 121 |
+
>>> RecurrenceOperator([0, 1, n**2], R)
|
| 122 |
+
(1)Sn + (n**2)Sn**2
|
| 123 |
+
|
| 124 |
+
>>> Sn*n
|
| 125 |
+
(n + 1)Sn
|
| 126 |
+
|
| 127 |
+
>>> n*Sn*n + 1 - Sn**2*n
|
| 128 |
+
(1) + (n**2 + n)Sn + (-n - 2)Sn**2
|
| 129 |
+
|
| 130 |
+
See Also
|
| 131 |
+
========
|
| 132 |
+
|
| 133 |
+
DifferentialOperatorAlgebra
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
_op_priority = 20
|
| 137 |
+
|
| 138 |
+
def __init__(self, list_of_poly, parent):
|
| 139 |
+
# the parent ring for this operator
|
| 140 |
+
# must be an RecurrenceOperatorAlgebra object
|
| 141 |
+
self.parent = parent
|
| 142 |
+
# sequence of polynomials in n for each power of Sn
|
| 143 |
+
# represents the operator
|
| 144 |
+
# convert the expressions into ring elements using from_sympy
|
| 145 |
+
if isinstance(list_of_poly, list):
|
| 146 |
+
for i, j in enumerate(list_of_poly):
|
| 147 |
+
if isinstance(j, int):
|
| 148 |
+
list_of_poly[i] = self.parent.base.from_sympy(S(j))
|
| 149 |
+
elif not isinstance(j, self.parent.base.dtype):
|
| 150 |
+
list_of_poly[i] = self.parent.base.from_sympy(j)
|
| 151 |
+
|
| 152 |
+
self.listofpoly = list_of_poly
|
| 153 |
+
self.order = len(self.listofpoly) - 1
|
| 154 |
+
|
| 155 |
+
def __mul__(self, other):
|
| 156 |
+
"""
|
| 157 |
+
Multiplies two Operators and returns another
|
| 158 |
+
RecurrenceOperator instance using the commutation rule
|
| 159 |
+
Sn * a(n) = a(n + 1) * Sn
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
listofself = self.listofpoly
|
| 163 |
+
base = self.parent.base
|
| 164 |
+
|
| 165 |
+
if not isinstance(other, RecurrenceOperator):
|
| 166 |
+
if not isinstance(other, self.parent.base.dtype):
|
| 167 |
+
listofother = [self.parent.base.from_sympy(sympify(other))]
|
| 168 |
+
|
| 169 |
+
else:
|
| 170 |
+
listofother = [other]
|
| 171 |
+
else:
|
| 172 |
+
listofother = other.listofpoly
|
| 173 |
+
# multiply a polynomial `b` with a list of polynomials
|
| 174 |
+
|
| 175 |
+
def _mul_dmp_diffop(b, listofother):
|
| 176 |
+
if isinstance(listofother, list):
|
| 177 |
+
sol = []
|
| 178 |
+
for i in listofother:
|
| 179 |
+
sol.append(i * b)
|
| 180 |
+
return sol
|
| 181 |
+
else:
|
| 182 |
+
return [b * listofother]
|
| 183 |
+
|
| 184 |
+
sol = _mul_dmp_diffop(listofself[0], listofother)
|
| 185 |
+
|
| 186 |
+
# compute Sn^i * b
|
| 187 |
+
def _mul_Sni_b(b):
|
| 188 |
+
sol = [base.zero]
|
| 189 |
+
|
| 190 |
+
if isinstance(b, list):
|
| 191 |
+
for i in b:
|
| 192 |
+
j = base.to_sympy(i).subs(base.gens[0], base.gens[0] + S.One)
|
| 193 |
+
sol.append(base.from_sympy(j))
|
| 194 |
+
|
| 195 |
+
else:
|
| 196 |
+
j = b.subs(base.gens[0], base.gens[0] + S.One)
|
| 197 |
+
sol.append(base.from_sympy(j))
|
| 198 |
+
|
| 199 |
+
return sol
|
| 200 |
+
|
| 201 |
+
for i in range(1, len(listofself)):
|
| 202 |
+
# find Sn^i * b in ith iteration
|
| 203 |
+
listofother = _mul_Sni_b(listofother)
|
| 204 |
+
# solution = solution + listofself[i] * (Sn^i * b)
|
| 205 |
+
sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother))
|
| 206 |
+
|
| 207 |
+
return RecurrenceOperator(sol, self.parent)
|
| 208 |
+
|
| 209 |
+
def __rmul__(self, other):
|
| 210 |
+
if not isinstance(other, RecurrenceOperator):
|
| 211 |
+
|
| 212 |
+
if isinstance(other, int):
|
| 213 |
+
other = S(other)
|
| 214 |
+
|
| 215 |
+
if not isinstance(other, self.parent.base.dtype):
|
| 216 |
+
other = (self.parent.base).from_sympy(other)
|
| 217 |
+
|
| 218 |
+
sol = []
|
| 219 |
+
for j in self.listofpoly:
|
| 220 |
+
sol.append(other * j)
|
| 221 |
+
|
| 222 |
+
return RecurrenceOperator(sol, self.parent)
|
| 223 |
+
|
| 224 |
+
def __add__(self, other):
|
| 225 |
+
if isinstance(other, RecurrenceOperator):
|
| 226 |
+
|
| 227 |
+
sol = _add_lists(self.listofpoly, other.listofpoly)
|
| 228 |
+
return RecurrenceOperator(sol, self.parent)
|
| 229 |
+
|
| 230 |
+
else:
|
| 231 |
+
|
| 232 |
+
if isinstance(other, int):
|
| 233 |
+
other = S(other)
|
| 234 |
+
list_self = self.listofpoly
|
| 235 |
+
if not isinstance(other, self.parent.base.dtype):
|
| 236 |
+
list_other = [((self.parent).base).from_sympy(other)]
|
| 237 |
+
else:
|
| 238 |
+
list_other = [other]
|
| 239 |
+
sol = []
|
| 240 |
+
sol.append(list_self[0] + list_other[0])
|
| 241 |
+
sol += list_self[1:]
|
| 242 |
+
|
| 243 |
+
return RecurrenceOperator(sol, self.parent)
|
| 244 |
+
|
| 245 |
+
__radd__ = __add__
|
| 246 |
+
|
| 247 |
+
def __sub__(self, other):
|
| 248 |
+
return self + (-1) * other
|
| 249 |
+
|
| 250 |
+
def __rsub__(self, other):
|
| 251 |
+
return (-1) * self + other
|
| 252 |
+
|
| 253 |
+
def __pow__(self, n):
|
| 254 |
+
if n == 1:
|
| 255 |
+
return self
|
| 256 |
+
if n == 0:
|
| 257 |
+
return RecurrenceOperator([self.parent.base.one], self.parent)
|
| 258 |
+
# if self is `Sn`
|
| 259 |
+
if self.listofpoly == self.parent.shift_operator.listofpoly:
|
| 260 |
+
sol = []
|
| 261 |
+
for i in range(0, n):
|
| 262 |
+
sol.append(self.parent.base.zero)
|
| 263 |
+
sol.append(self.parent.base.one)
|
| 264 |
+
|
| 265 |
+
return RecurrenceOperator(sol, self.parent)
|
| 266 |
+
|
| 267 |
+
else:
|
| 268 |
+
if n % 2 == 1:
|
| 269 |
+
powreduce = self**(n - 1)
|
| 270 |
+
return powreduce * self
|
| 271 |
+
elif n % 2 == 0:
|
| 272 |
+
powreduce = self**(n / 2)
|
| 273 |
+
return powreduce * powreduce
|
| 274 |
+
|
| 275 |
+
def __str__(self):
|
| 276 |
+
listofpoly = self.listofpoly
|
| 277 |
+
print_str = ''
|
| 278 |
+
|
| 279 |
+
for i, j in enumerate(listofpoly):
|
| 280 |
+
if j == self.parent.base.zero:
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
if i == 0:
|
| 284 |
+
print_str += '(' + sstr(j) + ')'
|
| 285 |
+
continue
|
| 286 |
+
|
| 287 |
+
if print_str:
|
| 288 |
+
print_str += ' + '
|
| 289 |
+
|
| 290 |
+
if i == 1:
|
| 291 |
+
print_str += '(' + sstr(j) + ')Sn'
|
| 292 |
+
continue
|
| 293 |
+
|
| 294 |
+
print_str += '(' + sstr(j) + ')' + 'Sn**' + sstr(i)
|
| 295 |
+
|
| 296 |
+
return print_str
|
| 297 |
+
|
| 298 |
+
__repr__ = __str__
|
| 299 |
+
|
| 300 |
+
def __eq__(self, other):
|
| 301 |
+
if isinstance(other, RecurrenceOperator):
|
| 302 |
+
if self.listofpoly == other.listofpoly and self.parent == other.parent:
|
| 303 |
+
return True
|
| 304 |
+
else:
|
| 305 |
+
return False
|
| 306 |
+
else:
|
| 307 |
+
if self.listofpoly[0] == other:
|
| 308 |
+
for i in self.listofpoly[1:]:
|
| 309 |
+
if i is not self.parent.base.zero:
|
| 310 |
+
return False
|
| 311 |
+
return True
|
| 312 |
+
else:
|
| 313 |
+
return False
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class HolonomicSequence:
|
| 317 |
+
"""
|
| 318 |
+
A Holonomic Sequence is a type of sequence satisfying a linear homogeneous
|
| 319 |
+
recurrence relation with Polynomial coefficients. Alternatively, A sequence
|
| 320 |
+
is Holonomic if and only if its generating function is a Holonomic Function.
|
| 321 |
+
"""
|
| 322 |
+
|
| 323 |
+
def __init__(self, recurrence, u0=[]):
|
| 324 |
+
self.recurrence = recurrence
|
| 325 |
+
if not isinstance(u0, list):
|
| 326 |
+
self.u0 = [u0]
|
| 327 |
+
else:
|
| 328 |
+
self.u0 = u0
|
| 329 |
+
|
| 330 |
+
if len(self.u0) == 0:
|
| 331 |
+
self._have_init_cond = False
|
| 332 |
+
else:
|
| 333 |
+
self._have_init_cond = True
|
| 334 |
+
self.n = recurrence.parent.base.gens[0]
|
| 335 |
+
|
| 336 |
+
def __repr__(self):
|
| 337 |
+
str_sol = 'HolonomicSequence(%s, %s)' % ((self.recurrence).__repr__(), sstr(self.n))
|
| 338 |
+
if not self._have_init_cond:
|
| 339 |
+
return str_sol
|
| 340 |
+
else:
|
| 341 |
+
cond_str = ''
|
| 342 |
+
seq_str = 0
|
| 343 |
+
for i in self.u0:
|
| 344 |
+
cond_str += ', u(%s) = %s' % (sstr(seq_str), sstr(i))
|
| 345 |
+
seq_str += 1
|
| 346 |
+
|
| 347 |
+
sol = str_sol + cond_str
|
| 348 |
+
return sol
|
| 349 |
+
|
| 350 |
+
__str__ = __repr__
|
| 351 |
+
|
| 352 |
+
def __eq__(self, other):
|
| 353 |
+
if self.recurrence == other.recurrence:
|
| 354 |
+
if self.n == other.n:
|
| 355 |
+
if self._have_init_cond and other._have_init_cond:
|
| 356 |
+
if self.u0 == other.u0:
|
| 357 |
+
return True
|
| 358 |
+
else:
|
| 359 |
+
return False
|
| 360 |
+
else:
|
| 361 |
+
return True
|
| 362 |
+
else:
|
| 363 |
+
return False
|
| 364 |
+
else:
|
| 365 |
+
return False
|
shared/package-files/24/245b08a462f0ba7494a889a259472293fdc05fb251a914d8e2a81934c9cf8267/test_make_function_to_jit_function.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numba import njit
|
| 2 |
+
from numba.core import errors
|
| 3 |
+
from numba.core.extending import overload
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
import unittest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@njit
|
| 10 |
+
def consumer(func, *args):
|
| 11 |
+
return func(*args)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@njit
|
| 15 |
+
def consumer2arg(func1, func2):
|
| 16 |
+
return func2(func1)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_global = 123
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class TestMakeFunctionToJITFunction(unittest.TestCase):
|
| 23 |
+
"""
|
| 24 |
+
This tests the pass that converts ir.Expr.op == make_function (i.e. closure)
|
| 25 |
+
into a JIT function.
|
| 26 |
+
"""
|
| 27 |
+
# NOTE: testing this is a bit tricky. The function receiving a JIT'd closure
|
| 28 |
+
# must also be under JIT control so as to handle the JIT'd closure
|
| 29 |
+
# correctly, however, in the case of running the test implementations in the
|
| 30 |
+
# interpreter, the receiving function cannot be JIT'd else it will receive
|
| 31 |
+
# the Python closure and then complain about pyobjects as arguments.
|
| 32 |
+
# The way around this is to use a factory function to close over either the
|
| 33 |
+
# jitted or standard python function as the consumer depending on context.
|
| 34 |
+
|
| 35 |
+
def test_escape(self):
|
| 36 |
+
|
| 37 |
+
def impl_factory(consumer_func):
|
| 38 |
+
def impl():
|
| 39 |
+
def inner():
|
| 40 |
+
return 10
|
| 41 |
+
return consumer_func(inner)
|
| 42 |
+
return impl
|
| 43 |
+
|
| 44 |
+
cfunc = njit(impl_factory(consumer))
|
| 45 |
+
impl = impl_factory(consumer.py_func)
|
| 46 |
+
|
| 47 |
+
self.assertEqual(impl(), cfunc())
|
| 48 |
+
|
| 49 |
+
def test_nested_escape(self):
|
| 50 |
+
|
| 51 |
+
def impl_factory(consumer_func):
|
| 52 |
+
def impl():
|
| 53 |
+
def inner():
|
| 54 |
+
return 10
|
| 55 |
+
|
| 56 |
+
def innerinner(x):
|
| 57 |
+
return x()
|
| 58 |
+
return consumer_func(inner, innerinner)
|
| 59 |
+
return impl
|
| 60 |
+
|
| 61 |
+
cfunc = njit(impl_factory(consumer2arg))
|
| 62 |
+
impl = impl_factory(consumer2arg.py_func)
|
| 63 |
+
|
| 64 |
+
self.assertEqual(impl(), cfunc())
|
| 65 |
+
|
| 66 |
+
def test_closure_in_escaper(self):
|
| 67 |
+
|
| 68 |
+
def impl_factory(consumer_func):
|
| 69 |
+
def impl():
|
| 70 |
+
def callinner():
|
| 71 |
+
def inner():
|
| 72 |
+
return 10
|
| 73 |
+
return inner()
|
| 74 |
+
return consumer_func(callinner)
|
| 75 |
+
return impl
|
| 76 |
+
|
| 77 |
+
cfunc = njit(impl_factory(consumer))
|
| 78 |
+
impl = impl_factory(consumer.py_func)
|
| 79 |
+
|
| 80 |
+
self.assertEqual(impl(), cfunc())
|
| 81 |
+
|
| 82 |
+
def test_close_over_consts(self):
|
| 83 |
+
|
| 84 |
+
def impl_factory(consumer_func):
|
| 85 |
+
def impl():
|
| 86 |
+
y = 10
|
| 87 |
+
|
| 88 |
+
def callinner(z):
|
| 89 |
+
return y + z + _global
|
| 90 |
+
return consumer_func(callinner, 6)
|
| 91 |
+
return impl
|
| 92 |
+
|
| 93 |
+
cfunc = njit(impl_factory(consumer))
|
| 94 |
+
impl = impl_factory(consumer.py_func)
|
| 95 |
+
|
| 96 |
+
self.assertEqual(impl(), cfunc())
|
| 97 |
+
|
| 98 |
+
def test_close_over_consts_w_args(self):
|
| 99 |
+
|
| 100 |
+
def impl_factory(consumer_func):
|
| 101 |
+
def impl(x):
|
| 102 |
+
y = 10
|
| 103 |
+
|
| 104 |
+
def callinner(z):
|
| 105 |
+
return y + z + _global
|
| 106 |
+
return consumer_func(callinner, x)
|
| 107 |
+
return impl
|
| 108 |
+
|
| 109 |
+
cfunc = njit(impl_factory(consumer))
|
| 110 |
+
impl = impl_factory(consumer.py_func)
|
| 111 |
+
|
| 112 |
+
a = 5
|
| 113 |
+
self.assertEqual(impl(a), cfunc(a))
|
| 114 |
+
|
| 115 |
+
def test_with_overload(self):
|
| 116 |
+
|
| 117 |
+
def foo(func, *args):
|
| 118 |
+
nargs = len(args)
|
| 119 |
+
if nargs == 1:
|
| 120 |
+
return func(*args)
|
| 121 |
+
elif nargs == 2:
|
| 122 |
+
return func(func(*args))
|
| 123 |
+
|
| 124 |
+
@overload(foo)
|
| 125 |
+
def foo_ol(func, *args):
|
| 126 |
+
# specialise on the number of args, as per `foo`
|
| 127 |
+
nargs = len(args)
|
| 128 |
+
if nargs == 1:
|
| 129 |
+
def impl(func, *args):
|
| 130 |
+
return func(*args)
|
| 131 |
+
return impl
|
| 132 |
+
elif nargs == 2:
|
| 133 |
+
def impl(func, *args):
|
| 134 |
+
return func(func(*args))
|
| 135 |
+
return impl
|
| 136 |
+
|
| 137 |
+
def impl_factory(consumer_func):
|
| 138 |
+
def impl(x):
|
| 139 |
+
y = 10
|
| 140 |
+
|
| 141 |
+
def callinner(*z):
|
| 142 |
+
return y + np.sum(np.asarray(z)) + _global
|
| 143 |
+
# run both specialisations, 1 arg, and 2 arg.
|
| 144 |
+
return foo(callinner, x), foo(callinner, x, x)
|
| 145 |
+
return impl
|
| 146 |
+
|
| 147 |
+
cfunc = njit(impl_factory(consumer))
|
| 148 |
+
impl = impl_factory(consumer.py_func)
|
| 149 |
+
|
| 150 |
+
a = 5
|
| 151 |
+
self.assertEqual(impl(a), cfunc(a))
|
| 152 |
+
|
| 153 |
+
def test_basic_apply_like_case(self):
|
| 154 |
+
def apply(array, func):
|
| 155 |
+
return func(array)
|
| 156 |
+
|
| 157 |
+
@overload(apply)
|
| 158 |
+
def ov_apply(array, func):
|
| 159 |
+
return lambda array, func: func(array)
|
| 160 |
+
|
| 161 |
+
def impl(array):
|
| 162 |
+
def mul10(x):
|
| 163 |
+
return x * 10
|
| 164 |
+
return apply(array, mul10)
|
| 165 |
+
|
| 166 |
+
cfunc = njit(impl)
|
| 167 |
+
|
| 168 |
+
a = np.arange(10)
|
| 169 |
+
np.testing.assert_allclose(impl(a), cfunc(a))
|
| 170 |
+
|
| 171 |
+
@unittest.skip("Needs option/flag inheritance to work")
|
| 172 |
+
def test_jit_option_inheritance(self):
|
| 173 |
+
|
| 174 |
+
def impl_factory(consumer_func):
|
| 175 |
+
def impl(x):
|
| 176 |
+
def inner(val):
|
| 177 |
+
return 1 / val
|
| 178 |
+
return consumer_func(inner, x)
|
| 179 |
+
return impl
|
| 180 |
+
|
| 181 |
+
cfunc = njit(error_model='numpy')(impl_factory(consumer))
|
| 182 |
+
impl = impl_factory(consumer.py_func)
|
| 183 |
+
|
| 184 |
+
a = 0
|
| 185 |
+
self.assertEqual(impl(a), cfunc(a))
|
| 186 |
+
|
| 187 |
+
# this needs true SSA to be able to work correctly, check error for now
|
| 188 |
+
def test_multiply_defined_freevar(self):
|
| 189 |
+
|
| 190 |
+
@njit
|
| 191 |
+
def impl(c):
|
| 192 |
+
if c:
|
| 193 |
+
x = 3
|
| 194 |
+
|
| 195 |
+
def inner(y):
|
| 196 |
+
return y + x
|
| 197 |
+
|
| 198 |
+
r = consumer(inner, 1)
|
| 199 |
+
else:
|
| 200 |
+
x = 6
|
| 201 |
+
|
| 202 |
+
def inner(y):
|
| 203 |
+
return y + x
|
| 204 |
+
|
| 205 |
+
r = consumer(inner, 2)
|
| 206 |
+
return r
|
| 207 |
+
|
| 208 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 209 |
+
impl(1)
|
| 210 |
+
|
| 211 |
+
self.assertIn("Cannot capture a constant value for variable",
|
| 212 |
+
str(e.exception))
|
| 213 |
+
|
| 214 |
+
def test_non_const_in_escapee(self):
|
| 215 |
+
|
| 216 |
+
@njit
|
| 217 |
+
def impl(x):
|
| 218 |
+
z = np.arange(x)
|
| 219 |
+
|
| 220 |
+
def inner(val):
|
| 221 |
+
return 1 + z + val # z is non-const freevar
|
| 222 |
+
return consumer(inner, x)
|
| 223 |
+
|
| 224 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 225 |
+
impl(1)
|
| 226 |
+
|
| 227 |
+
self.assertIn("Cannot capture the non-constant value associated",
|
| 228 |
+
str(e.exception))
|
| 229 |
+
|
| 230 |
+
def test_escape_with_kwargs(self):
|
| 231 |
+
|
| 232 |
+
def impl_factory(consumer_func):
|
| 233 |
+
def impl():
|
| 234 |
+
t = 12
|
| 235 |
+
|
| 236 |
+
def inner(a, b, c, mydefault1=123, mydefault2=456):
|
| 237 |
+
z = 4
|
| 238 |
+
return mydefault1 + mydefault2 + z + t + a + b + c
|
| 239 |
+
# this is awkward, top and tail closure inlining with a escapees
|
| 240 |
+
# in the middle that do/don't have defaults.
|
| 241 |
+
return (inner(1, 2, 5, 91, 53),
|
| 242 |
+
consumer_func(inner, 1, 2, 3, 73),
|
| 243 |
+
consumer_func(inner, 1, 2, 3,),
|
| 244 |
+
inner(1, 2, 4))
|
| 245 |
+
return impl
|
| 246 |
+
|
| 247 |
+
cfunc = njit(impl_factory(consumer))
|
| 248 |
+
impl = impl_factory(consumer.py_func)
|
| 249 |
+
|
| 250 |
+
np.testing.assert_allclose(impl(), cfunc())
|
| 251 |
+
|
| 252 |
+
def test_escape_with_kwargs_override_kwargs(self):
|
| 253 |
+
|
| 254 |
+
@njit
|
| 255 |
+
def specialised_consumer(func, *args):
|
| 256 |
+
x, y, z = args # unpack to avoid `CALL_FUNCTION_EX`
|
| 257 |
+
a = func(x, y, z, mydefault1=1000)
|
| 258 |
+
b = func(x, y, z, mydefault2=1000)
|
| 259 |
+
c = func(x, y, z, mydefault1=1000, mydefault2=1000)
|
| 260 |
+
return a + b + c
|
| 261 |
+
|
| 262 |
+
def impl_factory(consumer_func):
|
| 263 |
+
def impl():
|
| 264 |
+
t = 12
|
| 265 |
+
|
| 266 |
+
def inner(a, b, c, mydefault1=123, mydefault2=456):
|
| 267 |
+
z = 4
|
| 268 |
+
return mydefault1 + mydefault2 + z + t + a + b + c
|
| 269 |
+
# this is awkward, top and tail closure inlining with a escapees
|
| 270 |
+
# in the middle that get defaults specified in the consumer
|
| 271 |
+
return (inner(1, 2, 5, 91, 53),
|
| 272 |
+
consumer_func(inner, 1, 2, 11),
|
| 273 |
+
consumer_func(inner, 1, 2, 3,),
|
| 274 |
+
inner(1, 2, 4))
|
| 275 |
+
return impl
|
| 276 |
+
|
| 277 |
+
cfunc = njit(impl_factory(specialised_consumer))
|
| 278 |
+
impl = impl_factory(specialised_consumer.py_func)
|
| 279 |
+
|
| 280 |
+
np.testing.assert_allclose(impl(), cfunc())
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
if __name__ == '__main__':
|
| 284 |
+
unittest.main()
|
shared/package-files/24/245d3068e31e571032a39dd504e627662b96f2870b953c7fd326f45412889db0/_cudnn_ctc_loss_compositeexplicitautograd_dispatch.h
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 compositeexplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> _cudnn_ctc_loss_out(at::Tensor & out0, at::Tensor & out1, const at::Tensor & log_probs, const at::Tensor & targets, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, int64_t blank, bool deterministic, bool zero_infinity);
|
| 21 |
+
TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> _cudnn_ctc_loss_outf(const at::Tensor & log_probs, const at::Tensor & targets, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, int64_t blank, bool deterministic, bool zero_infinity, at::Tensor & out0, at::Tensor & out1);
|
| 22 |
+
|
| 23 |
+
} // namespace compositeexplicitautograd
|
| 24 |
+
} // namespace at
|
shared/package-files/24/24630064571ade8d27bfeff84cae09ffec452a0ec3ccd984ff31e8a7821c27e1/platform-1.0.18.tm
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- tcl -*-
|
| 2 |
+
# ### ### ### ######### ######### #########
|
| 3 |
+
## Overview
|
| 4 |
+
|
| 5 |
+
# Heuristics to assemble a platform identifier from publicly available
|
| 6 |
+
# information. The identifier describes the platform of the currently
|
| 7 |
+
# running tcl shell. This is a mixture of the runtime environment and
|
| 8 |
+
# of build-time properties of the executable itself.
|
| 9 |
+
#
|
| 10 |
+
# Examples:
|
| 11 |
+
# <1> A tcl shell executing on a x86_64 processor, but having a
|
| 12 |
+
# wordsize of 4 was compiled for the x86 environment, i.e. 32
|
| 13 |
+
# bit, and loaded packages have to match that, and not the
|
| 14 |
+
# actual cpu.
|
| 15 |
+
#
|
| 16 |
+
# <2> The hp/solaris 32/64 bit builds of the core cannot be
|
| 17 |
+
# distinguished by looking at tcl_platform. As packages have to
|
| 18 |
+
# match the 32/64 information we have to look in more places. In
|
| 19 |
+
# this case we inspect the executable itself (magic numbers,
|
| 20 |
+
# i.e. fileutil::magic::filetype).
|
| 21 |
+
#
|
| 22 |
+
# The basic information used comes out of the 'os' and 'machine'
|
| 23 |
+
# entries of the 'tcl_platform' array. A number of general and
|
| 24 |
+
# os/machine specific transformation are applied to get a canonical
|
| 25 |
+
# result.
|
| 26 |
+
#
|
| 27 |
+
# General
|
| 28 |
+
# Only the first element of 'os' is used - we don't care whether we
|
| 29 |
+
# are on "Windows NT" or "Windows XP" or whatever.
|
| 30 |
+
#
|
| 31 |
+
# Machine specific
|
| 32 |
+
# % amd64 -> x86_64
|
| 33 |
+
# % arm* -> arm
|
| 34 |
+
# % sun4* -> sparc
|
| 35 |
+
# % ia32* -> ix86
|
| 36 |
+
# % intel -> ix86
|
| 37 |
+
# % i*86* -> ix86
|
| 38 |
+
# % Power* -> powerpc
|
| 39 |
+
# % x86_64 + wordSize 4 => x86 code
|
| 40 |
+
#
|
| 41 |
+
# OS specific
|
| 42 |
+
# % AIX are always powerpc machines
|
| 43 |
+
# % HP-UX 9000/800 etc means parisc
|
| 44 |
+
# % linux has to take glibc version into account
|
| 45 |
+
# % sunos -> solaris, and keep version number
|
| 46 |
+
#
|
| 47 |
+
# NOTE: A platform like linux glibc 2.3, which can use glibc 2.2 stuff
|
| 48 |
+
# has to provide all possible allowed platform identifiers when
|
| 49 |
+
# searching search. Ditto a solaris 2.8 platform can use solaris 2.6
|
| 50 |
+
# packages. Etc. This is handled by the other procedure, see below.
|
| 51 |
+
|
| 52 |
+
# ### ### ### ######### ######### #########
|
| 53 |
+
## Requirements
|
| 54 |
+
|
| 55 |
+
namespace eval ::platform {}
|
| 56 |
+
|
| 57 |
+
# ### ### ### ######### ######### #########
|
| 58 |
+
## Implementation
|
| 59 |
+
|
| 60 |
+
# -- platform::generic
|
| 61 |
+
#
|
| 62 |
+
# Assembles an identifier for the generic platform. It leaves out
|
| 63 |
+
# details like kernel version, libc version, etc.
|
| 64 |
+
|
| 65 |
+
proc ::platform::generic {} {
|
| 66 |
+
global tcl_platform
|
| 67 |
+
|
| 68 |
+
set plat [string tolower [lindex $tcl_platform(os) 0]]
|
| 69 |
+
set cpu $tcl_platform(machine)
|
| 70 |
+
|
| 71 |
+
switch -glob -- $cpu {
|
| 72 |
+
sun4* {
|
| 73 |
+
set cpu sparc
|
| 74 |
+
}
|
| 75 |
+
intel -
|
| 76 |
+
ia32* -
|
| 77 |
+
i*86* {
|
| 78 |
+
set cpu ix86
|
| 79 |
+
}
|
| 80 |
+
x86_64 {
|
| 81 |
+
if {$tcl_platform(wordSize) == 4} {
|
| 82 |
+
# See Example <1> at the top of this file.
|
| 83 |
+
set cpu ix86
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
ppc -
|
| 87 |
+
"Power*" {
|
| 88 |
+
set cpu powerpc
|
| 89 |
+
}
|
| 90 |
+
"arm*" {
|
| 91 |
+
set cpu arm
|
| 92 |
+
}
|
| 93 |
+
ia64 {
|
| 94 |
+
if {$tcl_platform(wordSize) == 4} {
|
| 95 |
+
append cpu _32
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
switch -glob -- $plat {
|
| 101 |
+
windows {
|
| 102 |
+
if {$tcl_platform(platform) == "unix"} {
|
| 103 |
+
set plat cygwin
|
| 104 |
+
} else {
|
| 105 |
+
set plat win32
|
| 106 |
+
}
|
| 107 |
+
if {$cpu eq "amd64"} {
|
| 108 |
+
# Do not check wordSize, win32-x64 is an IL32P64 platform.
|
| 109 |
+
set cpu x86_64
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
sunos {
|
| 113 |
+
set plat solaris
|
| 114 |
+
if {[string match "ix86" $cpu]} {
|
| 115 |
+
if {$tcl_platform(wordSize) == 8} {
|
| 116 |
+
set cpu x86_64
|
| 117 |
+
}
|
| 118 |
+
} elseif {![string match "ia64*" $cpu]} {
|
| 119 |
+
# sparc
|
| 120 |
+
if {$tcl_platform(wordSize) == 8} {
|
| 121 |
+
append cpu 64
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
darwin {
|
| 126 |
+
set plat macosx
|
| 127 |
+
# Correctly identify the cpu when running as a 64bit
|
| 128 |
+
# process on a machine with a 32bit kernel
|
| 129 |
+
if {$cpu eq "ix86"} {
|
| 130 |
+
if {$tcl_platform(wordSize) == 8} {
|
| 131 |
+
set cpu x86_64
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
aix {
|
| 136 |
+
set cpu powerpc
|
| 137 |
+
if {$tcl_platform(wordSize) == 8} {
|
| 138 |
+
append cpu 64
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
hp-ux {
|
| 142 |
+
set plat hpux
|
| 143 |
+
if {![string match "ia64*" $cpu]} {
|
| 144 |
+
set cpu parisc
|
| 145 |
+
if {$tcl_platform(wordSize) == 8} {
|
| 146 |
+
append cpu 64
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
}
|
| 150 |
+
osf1 {
|
| 151 |
+
set plat tru64
|
| 152 |
+
}
|
| 153 |
+
default {
|
| 154 |
+
set plat [lindex [split $plat _-] 0]
|
| 155 |
+
}
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
return "${plat}-${cpu}"
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
# -- platform::identify
|
| 162 |
+
#
|
| 163 |
+
# Assembles an identifier for the exact platform, by extending the
|
| 164 |
+
# generic identifier. I.e. it adds in details like kernel version,
|
| 165 |
+
# libc version, etc., if they are relevant for the loading of
|
| 166 |
+
# packages on the platform.
|
| 167 |
+
|
| 168 |
+
proc ::platform::identify {} {
|
| 169 |
+
global tcl_platform
|
| 170 |
+
|
| 171 |
+
set id [generic]
|
| 172 |
+
regexp {^([^-]+)-([^-]+)$} $id -> plat cpu
|
| 173 |
+
|
| 174 |
+
switch -- $plat {
|
| 175 |
+
solaris {
|
| 176 |
+
regsub {^5} $tcl_platform(osVersion) 2 text
|
| 177 |
+
append plat $text
|
| 178 |
+
return "${plat}-${cpu}"
|
| 179 |
+
}
|
| 180 |
+
macosx {
|
| 181 |
+
set major [lindex [split $tcl_platform(osVersion) .] 0]
|
| 182 |
+
if {$major > 19} {
|
| 183 |
+
set minor [lindex [split $tcl_platform(osVersion) .] 1]
|
| 184 |
+
incr major -9
|
| 185 |
+
append plat $major.[expr {$minor - 1}]
|
| 186 |
+
} else {
|
| 187 |
+
incr major -4
|
| 188 |
+
append plat 10.$major
|
| 189 |
+
return "${plat}-${cpu}"
|
| 190 |
+
}
|
| 191 |
+
return "${plat}-${cpu}"
|
| 192 |
+
}
|
| 193 |
+
linux {
|
| 194 |
+
# Look for the libc*.so and determine its version
|
| 195 |
+
# (libc5/6, libc6 further glibc 2.X)
|
| 196 |
+
|
| 197 |
+
set v unknown
|
| 198 |
+
|
| 199 |
+
# Determine in which directory to look. /lib, or /lib64.
|
| 200 |
+
# For that we use the tcl_platform(wordSize).
|
| 201 |
+
#
|
| 202 |
+
# We could use the 'cpu' info, per the equivalence below,
|
| 203 |
+
# that however would be restricted to intel. And this may
|
| 204 |
+
# be a arm, mips, etc. system. The wordsize is more
|
| 205 |
+
# fundamental.
|
| 206 |
+
#
|
| 207 |
+
# ix86 <=> (wordSize == 4) <=> 32 bit ==> /lib
|
| 208 |
+
# x86_64 <=> (wordSize == 8) <=> 64 bit ==> /lib64
|
| 209 |
+
#
|
| 210 |
+
# Do not look into /lib64 even if present, if the cpu
|
| 211 |
+
# doesn't fit.
|
| 212 |
+
|
| 213 |
+
# TODO: Determine the prefixes (i386, x86_64, ...) for
|
| 214 |
+
# other cpus. The path after the generic one is utterly
|
| 215 |
+
# specific to intel right now. Ok, on Ubuntu, possibly
|
| 216 |
+
# other Debian systems we may apparently be able to query
|
| 217 |
+
# the necessary CPU code. If we can't we simply use the
|
| 218 |
+
# hardwired fallback.
|
| 219 |
+
|
| 220 |
+
switch -exact -- $tcl_platform(wordSize) {
|
| 221 |
+
4 {
|
| 222 |
+
lappend bases /lib
|
| 223 |
+
if {[catch {
|
| 224 |
+
exec dpkg-architecture -qDEB_HOST_MULTIARCH
|
| 225 |
+
} res]} {
|
| 226 |
+
lappend bases /lib/i386-linux-gnu
|
| 227 |
+
} else {
|
| 228 |
+
# dpkg-arch returns the full tripled, not just cpu.
|
| 229 |
+
lappend bases /lib/$res
|
| 230 |
+
}
|
| 231 |
+
}
|
| 232 |
+
8 {
|
| 233 |
+
lappend bases /lib64
|
| 234 |
+
if {[catch {
|
| 235 |
+
exec dpkg-architecture -qDEB_HOST_MULTIARCH
|
| 236 |
+
} res]} {
|
| 237 |
+
lappend bases /lib/x86_64-linux-gnu
|
| 238 |
+
} else {
|
| 239 |
+
# dpkg-arch returns the full tripled, not just cpu.
|
| 240 |
+
lappend bases /lib/$res
|
| 241 |
+
}
|
| 242 |
+
}
|
| 243 |
+
default {
|
| 244 |
+
return -code error "Bad wordSize $tcl_platform(wordSize), expected 4 or 8"
|
| 245 |
+
}
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
foreach base $bases {
|
| 249 |
+
if {[LibcVersion $base -> v]} break
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
append plat -$v
|
| 253 |
+
return "${plat}-${cpu}"
|
| 254 |
+
}
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
return $id
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
proc ::platform::LibcVersion {base _->_ vv} {
|
| 261 |
+
upvar 1 $vv v
|
| 262 |
+
set libclist [lsort [glob -nocomplain -directory $base libc*]]
|
| 263 |
+
|
| 264 |
+
if {![llength $libclist]} { return 0 }
|
| 265 |
+
|
| 266 |
+
set libc [lindex $libclist 0]
|
| 267 |
+
|
| 268 |
+
# Try executing the library first. This should suceed
|
| 269 |
+
# for a glibc library, and return the version
|
| 270 |
+
# information.
|
| 271 |
+
|
| 272 |
+
if {![catch {
|
| 273 |
+
set vdata [lindex [split [exec $libc] \n] 0]
|
| 274 |
+
}]} {
|
| 275 |
+
regexp {version ([0-9]+(\.[0-9]+)*)} $vdata -> v
|
| 276 |
+
foreach {major minor} [split $v .] break
|
| 277 |
+
set v glibc${major}.${minor}
|
| 278 |
+
return 1
|
| 279 |
+
} else {
|
| 280 |
+
# We had trouble executing the library. We are now
|
| 281 |
+
# inspecting its name to determine the version
|
| 282 |
+
# number. This code by Larry McVoy.
|
| 283 |
+
|
| 284 |
+
if {[regexp -- {libc-([0-9]+)\.([0-9]+)} $libc -> major minor]} {
|
| 285 |
+
set v glibc${major}.${minor}
|
| 286 |
+
return 1
|
| 287 |
+
}
|
| 288 |
+
}
|
| 289 |
+
return 0
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
# -- platform::patterns
|
| 293 |
+
#
|
| 294 |
+
# Given an exact platform identifier, i.e. _not_ the generic
|
| 295 |
+
# identifier it assembles a list of exact platform identifier
|
| 296 |
+
# describing platform which should be compatible with the
|
| 297 |
+
# input.
|
| 298 |
+
#
|
| 299 |
+
# I.e. packages for all platforms in the result list should be
|
| 300 |
+
# loadable on the specified platform.
|
| 301 |
+
|
| 302 |
+
# << Should we add the generic identifier to the list as well ? In
|
| 303 |
+
# general it is not compatible I believe. So better not. In many
|
| 304 |
+
# cases the exact identifier is identical to the generic one
|
| 305 |
+
# anyway.
|
| 306 |
+
# >>
|
| 307 |
+
|
| 308 |
+
proc ::platform::patterns {id} {
|
| 309 |
+
set res [list $id]
|
| 310 |
+
if {$id eq "tcl"} {return $res}
|
| 311 |
+
|
| 312 |
+
switch -glob -- $id {
|
| 313 |
+
solaris*-* {
|
| 314 |
+
if {[regexp {solaris([^-]*)-(.*)} $id -> v cpu]} {
|
| 315 |
+
if {$v eq ""} {return $id}
|
| 316 |
+
foreach {major minor} [split $v .] break
|
| 317 |
+
incr minor -1
|
| 318 |
+
for {set j $minor} {$j >= 6} {incr j -1} {
|
| 319 |
+
lappend res solaris${major}.${j}-${cpu}
|
| 320 |
+
}
|
| 321 |
+
}
|
| 322 |
+
}
|
| 323 |
+
linux*-* {
|
| 324 |
+
if {[regexp {linux-glibc([^-]*)-(.*)} $id -> v cpu]} {
|
| 325 |
+
foreach {major minor} [split $v .] break
|
| 326 |
+
incr minor -1
|
| 327 |
+
for {set j $minor} {$j >= 0} {incr j -1} {
|
| 328 |
+
lappend res linux-glibc${major}.${j}-${cpu}
|
| 329 |
+
}
|
| 330 |
+
}
|
| 331 |
+
}
|
| 332 |
+
macosx-powerpc {
|
| 333 |
+
lappend res macosx-universal
|
| 334 |
+
}
|
| 335 |
+
macosx-x86_64 {
|
| 336 |
+
lappend res macosx-i386-x86_64
|
| 337 |
+
}
|
| 338 |
+
macosx-ix86 {
|
| 339 |
+
lappend res macosx-universal macosx-i386-x86_64
|
| 340 |
+
}
|
| 341 |
+
macosx*-* {
|
| 342 |
+
# 10.5+,11.0+
|
| 343 |
+
if {[regexp {macosx([^-]*)-(.*)} $id -> v cpu]} {
|
| 344 |
+
|
| 345 |
+
switch -exact -- $cpu {
|
| 346 |
+
ix86 {
|
| 347 |
+
lappend alt i386-x86_64
|
| 348 |
+
lappend alt universal
|
| 349 |
+
}
|
| 350 |
+
x86_64 {
|
| 351 |
+
if {[lindex [split $::tcl_platform(osVersion) .] 0] < 19} {
|
| 352 |
+
set alt i386-x86_64
|
| 353 |
+
} else {
|
| 354 |
+
set alt {}
|
| 355 |
+
}
|
| 356 |
+
}
|
| 357 |
+
arm {
|
| 358 |
+
lappend alt x86_64
|
| 359 |
+
}
|
| 360 |
+
default { set alt {} }
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
if {$v ne ""} {
|
| 364 |
+
foreach {major minor} [split $v .] break
|
| 365 |
+
|
| 366 |
+
set res {}
|
| 367 |
+
if {$major eq 12} {
|
| 368 |
+
# Add 12.0 to 12.minor to patterns.
|
| 369 |
+
for {set j $minor} {$j >= 0} {incr j -1} {
|
| 370 |
+
lappend res macosx${major}.${j}-${cpu}
|
| 371 |
+
foreach a $alt {
|
| 372 |
+
lappend res macosx${major}.${j}-$a
|
| 373 |
+
}
|
| 374 |
+
}
|
| 375 |
+
set major 11
|
| 376 |
+
set minor 5
|
| 377 |
+
}
|
| 378 |
+
if {$major eq 11} {
|
| 379 |
+
# Add 11.0 to 11.minor to patterns.
|
| 380 |
+
for {set j $minor} {$j >= 0} {incr j -1} {
|
| 381 |
+
lappend res macosx${major}.${j}-${cpu}
|
| 382 |
+
foreach a $alt {
|
| 383 |
+
lappend res macosx${major}.${j}-$a
|
| 384 |
+
}
|
| 385 |
+
}
|
| 386 |
+
set major 10
|
| 387 |
+
set minor 15
|
| 388 |
+
}
|
| 389 |
+
# Add 10.5 to 10.minor to patterns.
|
| 390 |
+
for {set j $minor} {$j >= 5} {incr j -1} {
|
| 391 |
+
if {$cpu ne "arm"} {
|
| 392 |
+
lappend res macosx${major}.${j}-${cpu}
|
| 393 |
+
}
|
| 394 |
+
foreach a $alt {
|
| 395 |
+
lappend res macosx${major}.${j}-$a
|
| 396 |
+
}
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
# Add unversioned patterns for 10.3/10.4 builds.
|
| 400 |
+
lappend res macosx-${cpu}
|
| 401 |
+
foreach a $alt {
|
| 402 |
+
lappend res macosx-$a
|
| 403 |
+
}
|
| 404 |
+
} else {
|
| 405 |
+
# No version, just do unversioned patterns.
|
| 406 |
+
foreach a $alt {
|
| 407 |
+
lappend res macosx-$a
|
| 408 |
+
}
|
| 409 |
+
}
|
| 410 |
+
} else {
|
| 411 |
+
# no v, no cpu ... nothing
|
| 412 |
+
}
|
| 413 |
+
}
|
| 414 |
+
}
|
| 415 |
+
lappend res tcl ; # Pure tcl packages are always compatible.
|
| 416 |
+
return $res
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
# ### ### ### ######### ######### #########
|
| 421 |
+
## Ready
|
| 422 |
+
|
| 423 |
+
package provide platform 1.0.18
|
| 424 |
+
|
| 425 |
+
# ### ### ### ######### ######### #########
|
| 426 |
+
## Demo application
|
| 427 |
+
|
| 428 |
+
if {[info exists argv0] && ($argv0 eq [info script])} {
|
| 429 |
+
puts ====================================
|
| 430 |
+
parray tcl_platform
|
| 431 |
+
puts ====================================
|
| 432 |
+
puts Generic\ identification:\ [::platform::generic]
|
| 433 |
+
puts Exact\ identification:\ \ \ [::platform::identify]
|
| 434 |
+
puts ====================================
|
| 435 |
+
puts Search\ patterns:
|
| 436 |
+
puts *\ [join [::platform::patterns [::platform::identify]] \n*\ ]
|
| 437 |
+
puts ====================================
|
| 438 |
+
exit 0
|
| 439 |
+
}
|
shared/package-files/24/2464429fd69c57cd260e211ebf3a11995d1dc1457103d2c470b947b6a2bc7500/nodes.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding: utf-8
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
from ruamel.yaml.compat import _F
|
| 6 |
+
|
| 7 |
+
if False: # MYPY
|
| 8 |
+
from typing import Dict, Any, Text # NOQA
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Node:
|
| 12 |
+
__slots__ = 'tag', 'value', 'start_mark', 'end_mark', 'comment', 'anchor'
|
| 13 |
+
|
| 14 |
+
def __init__(self, tag, value, start_mark, end_mark, comment=None, anchor=None):
|
| 15 |
+
# type: (Any, Any, Any, Any, Any, Any) -> None
|
| 16 |
+
self.tag = tag
|
| 17 |
+
self.value = value
|
| 18 |
+
self.start_mark = start_mark
|
| 19 |
+
self.end_mark = end_mark
|
| 20 |
+
self.comment = comment
|
| 21 |
+
self.anchor = anchor
|
| 22 |
+
|
| 23 |
+
def __repr__(self):
|
| 24 |
+
# type: () -> Any
|
| 25 |
+
value = self.value
|
| 26 |
+
# if isinstance(value, list):
|
| 27 |
+
# if len(value) == 0:
|
| 28 |
+
# value = '<empty>'
|
| 29 |
+
# elif len(value) == 1:
|
| 30 |
+
# value = '<1 item>'
|
| 31 |
+
# else:
|
| 32 |
+
# value = f'<{len(value)} items>'
|
| 33 |
+
# else:
|
| 34 |
+
# if len(value) > 75:
|
| 35 |
+
# value = repr(value[:70]+' ... ')
|
| 36 |
+
# else:
|
| 37 |
+
# value = repr(value)
|
| 38 |
+
value = repr(value)
|
| 39 |
+
return _F(
|
| 40 |
+
'{class_name!s}(tag={self_tag!r}, value={value!s})',
|
| 41 |
+
class_name=self.__class__.__name__,
|
| 42 |
+
self_tag=self.tag,
|
| 43 |
+
value=value,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
def dump(self, indent=0):
|
| 47 |
+
# type: (int) -> None
|
| 48 |
+
if isinstance(self.value, str):
|
| 49 |
+
sys.stdout.write(
|
| 50 |
+
'{}{}(tag={!r}, value={!r})\n'.format(
|
| 51 |
+
' ' * indent, self.__class__.__name__, self.tag, self.value
|
| 52 |
+
)
|
| 53 |
+
)
|
| 54 |
+
if self.comment:
|
| 55 |
+
sys.stdout.write(' {}comment: {})\n'.format(' ' * indent, self.comment))
|
| 56 |
+
return
|
| 57 |
+
sys.stdout.write(
|
| 58 |
+
'{}{}(tag={!r})\n'.format(' ' * indent, self.__class__.__name__, self.tag)
|
| 59 |
+
)
|
| 60 |
+
if self.comment:
|
| 61 |
+
sys.stdout.write(' {}comment: {})\n'.format(' ' * indent, self.comment))
|
| 62 |
+
for v in self.value:
|
| 63 |
+
if isinstance(v, tuple):
|
| 64 |
+
for v1 in v:
|
| 65 |
+
v1.dump(indent + 1)
|
| 66 |
+
elif isinstance(v, Node):
|
| 67 |
+
v.dump(indent + 1)
|
| 68 |
+
else:
|
| 69 |
+
sys.stdout.write('Node value type? {}\n'.format(type(v)))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class ScalarNode(Node):
|
| 73 |
+
"""
|
| 74 |
+
styles:
|
| 75 |
+
? -> set() ? key, no value
|
| 76 |
+
" -> double quoted
|
| 77 |
+
' -> single quoted
|
| 78 |
+
| -> literal style
|
| 79 |
+
> -> folding style
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
__slots__ = ('style',)
|
| 83 |
+
id = 'scalar'
|
| 84 |
+
|
| 85 |
+
def __init__(
|
| 86 |
+
self, tag, value, start_mark=None, end_mark=None, style=None, comment=None, anchor=None
|
| 87 |
+
):
|
| 88 |
+
# type: (Any, Any, Any, Any, Any, Any, Any) -> None
|
| 89 |
+
Node.__init__(self, tag, value, start_mark, end_mark, comment=comment, anchor=anchor)
|
| 90 |
+
self.style = style
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class CollectionNode(Node):
|
| 94 |
+
__slots__ = ('flow_style',)
|
| 95 |
+
|
| 96 |
+
def __init__(
|
| 97 |
+
self,
|
| 98 |
+
tag,
|
| 99 |
+
value,
|
| 100 |
+
start_mark=None,
|
| 101 |
+
end_mark=None,
|
| 102 |
+
flow_style=None,
|
| 103 |
+
comment=None,
|
| 104 |
+
anchor=None,
|
| 105 |
+
):
|
| 106 |
+
# type: (Any, Any, Any, Any, Any, Any, Any) -> None
|
| 107 |
+
Node.__init__(self, tag, value, start_mark, end_mark, comment=comment)
|
| 108 |
+
self.flow_style = flow_style
|
| 109 |
+
self.anchor = anchor
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class SequenceNode(CollectionNode):
|
| 113 |
+
__slots__ = ()
|
| 114 |
+
id = 'sequence'
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class MappingNode(CollectionNode):
|
| 118 |
+
__slots__ = ('merge',)
|
| 119 |
+
id = 'mapping'
|
| 120 |
+
|
| 121 |
+
def __init__(
|
| 122 |
+
self,
|
| 123 |
+
tag,
|
| 124 |
+
value,
|
| 125 |
+
start_mark=None,
|
| 126 |
+
end_mark=None,
|
| 127 |
+
flow_style=None,
|
| 128 |
+
comment=None,
|
| 129 |
+
anchor=None,
|
| 130 |
+
):
|
| 131 |
+
# type: (Any, Any, Any, Any, Any, Any, Any) -> None
|
| 132 |
+
CollectionNode.__init__(
|
| 133 |
+
self, tag, value, start_mark, end_mark, flow_style, comment, anchor
|
| 134 |
+
)
|
| 135 |
+
self.merge = None
|
shared/package-files/24/24661a72a24c12a1d2ea84f6018b3d77b8aeb4811bdf63e426cf4426a387c5c4/test_demidovich.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.numbers import (Rational, oo, pi)
|
| 2 |
+
from sympy.core.singleton import S
|
| 3 |
+
from sympy.core.symbol import Symbol
|
| 4 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 5 |
+
from sympy.functions.elementary.miscellaneous import (root, sqrt)
|
| 6 |
+
from sympy.functions.elementary.trigonometric import (asin, cos, sin, tan)
|
| 7 |
+
from sympy.polys.rationaltools import together
|
| 8 |
+
from sympy.series.limits import limit
|
| 9 |
+
|
| 10 |
+
# Numbers listed with the tests refer to problem numbers in the book
|
| 11 |
+
# "Anti-demidovich, problemas resueltos, Ed. URSS"
|
| 12 |
+
|
| 13 |
+
x = Symbol("x")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_leadterm():
|
| 17 |
+
assert (3 + 2*x**(log(3)/log(2) - 1)).leadterm(x) == (3, 0)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def root3(x):
|
| 21 |
+
return root(x, 3)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def root4(x):
|
| 25 |
+
return root(x, 4)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_Limits_simple_0():
|
| 29 |
+
assert limit((2**(x + 1) + 3**(x + 1))/(2**x + 3**x), x, oo) == 3 # 175
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_Limits_simple_1():
|
| 33 |
+
assert limit((x + 1)*(x + 2)*(x + 3)/x**3, x, oo) == 1 # 172
|
| 34 |
+
assert limit(sqrt(x + 1) - sqrt(x), x, oo) == 0 # 179
|
| 35 |
+
assert limit((2*x - 3)*(3*x + 5)*(4*x - 6)/(3*x**3 + x - 1), x, oo) == 8 # Primjer 1
|
| 36 |
+
assert limit(x/root3(x**3 + 10), x, oo) == 1 # Primjer 2
|
| 37 |
+
assert limit((x + 1)**2/(x**2 + 1), x, oo) == 1 # 181
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_Limits_simple_2():
|
| 41 |
+
assert limit(1000*x/(x**2 - 1), x, oo) == 0 # 182
|
| 42 |
+
assert limit((x**2 - 5*x + 1)/(3*x + 7), x, oo) is oo # 183
|
| 43 |
+
assert limit((2*x**2 - x + 3)/(x**3 - 8*x + 5), x, oo) == 0 # 184
|
| 44 |
+
assert limit((2*x**2 - 3*x - 4)/sqrt(x**4 + 1), x, oo) == 2 # 186
|
| 45 |
+
assert limit((2*x + 3)/(x + root3(x)), x, oo) == 2 # 187
|
| 46 |
+
assert limit(x**2/(10 + x*sqrt(x)), x, oo) is oo # 188
|
| 47 |
+
assert limit(root3(x**2 + 1)/(x + 1), x, oo) == 0 # 189
|
| 48 |
+
assert limit(sqrt(x)/sqrt(x + sqrt(x + sqrt(x))), x, oo) == 1 # 190
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_Limits_simple_3a():
|
| 52 |
+
a = Symbol('a')
|
| 53 |
+
#issue 3513
|
| 54 |
+
assert together(limit((x**2 - (a + 1)*x + a)/(x**3 - a**3), x, a)) == \
|
| 55 |
+
(a - 1)/(3*a**2) # 196
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_Limits_simple_3b():
|
| 59 |
+
h = Symbol("h")
|
| 60 |
+
assert limit(((x + h)**3 - x**3)/h, h, 0) == 3*x**2 # 197
|
| 61 |
+
assert limit((1/(1 - x) - 3/(1 - x**3)), x, 1) == -1 # 198
|
| 62 |
+
assert limit((sqrt(1 + x) - 1)/(root3(1 + x) - 1), x, 0) == Rational(3)/2 # Primer 4
|
| 63 |
+
assert limit((sqrt(x) - 1)/(x - 1), x, 1) == Rational(1)/2 # 199
|
| 64 |
+
assert limit((sqrt(x) - 8)/(root3(x) - 4), x, 64) == 3 # 200
|
| 65 |
+
assert limit((root3(x) - 1)/(root4(x) - 1), x, 1) == Rational(4)/3 # 201
|
| 66 |
+
assert limit(
|
| 67 |
+
(root3(x**2) - 2*root3(x) + 1)/(x - 1)**2, x, 1) == Rational(1)/9 # 202
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_Limits_simple_4a():
|
| 71 |
+
a = Symbol('a')
|
| 72 |
+
assert limit((sqrt(x) - sqrt(a))/(x - a), x, a) == 1/(2*sqrt(a)) # Primer 5
|
| 73 |
+
assert limit((sqrt(x) - 1)/(root3(x) - 1), x, 1) == Rational(3, 2) # 205
|
| 74 |
+
assert limit((sqrt(1 + x) - sqrt(1 - x))/x, x, 0) == 1 # 207
|
| 75 |
+
assert limit(sqrt(x**2 - 5*x + 6) - x, x, oo) == Rational(-5, 2) # 213
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_limits_simple_4aa():
|
| 79 |
+
assert limit(x*(sqrt(x**2 + 1) - x), x, oo) == Rational(1)/2 # 214
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_Limits_simple_4b():
|
| 83 |
+
#issue 3511
|
| 84 |
+
assert limit(x - root3(x**3 - 1), x, oo) == 0 # 215
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_Limits_simple_4c():
|
| 88 |
+
assert limit(log(1 + exp(x))/x, x, -oo) == 0 # 267a
|
| 89 |
+
assert limit(log(1 + exp(x))/x, x, oo) == 1 # 267b
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_bounded():
|
| 93 |
+
assert limit(sin(x)/x, x, oo) == 0 # 216b
|
| 94 |
+
assert limit(x*sin(1/x), x, 0) == 0 # 227a
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_f1a():
|
| 98 |
+
#issue 3508:
|
| 99 |
+
assert limit((sin(2*x)/x)**(1 + x), x, 0) == 2 # Primer 7
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_f1a2():
|
| 103 |
+
#issue 3509:
|
| 104 |
+
assert limit(((x - 1)/(x + 1))**x, x, oo) == exp(-2) # Primer 9
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def test_f1b():
|
| 108 |
+
m = Symbol("m")
|
| 109 |
+
n = Symbol("n")
|
| 110 |
+
h = Symbol("h")
|
| 111 |
+
a = Symbol("a")
|
| 112 |
+
assert limit(sin(x)/x, x, 2) == sin(2)/2 # 216a
|
| 113 |
+
assert limit(sin(3*x)/x, x, 0) == 3 # 217
|
| 114 |
+
assert limit(sin(5*x)/sin(2*x), x, 0) == Rational(5, 2) # 218
|
| 115 |
+
assert limit(sin(pi*x)/sin(3*pi*x), x, 0) == Rational(1, 3) # 219
|
| 116 |
+
assert limit(x*sin(pi/x), x, oo) == pi # 220
|
| 117 |
+
assert limit((1 - cos(x))/x**2, x, 0) == S.Half # 221
|
| 118 |
+
assert limit(x*sin(1/x), x, oo) == 1 # 227b
|
| 119 |
+
assert limit((cos(m*x) - cos(n*x))/x**2, x, 0) == -m**2/2 + n**2/2 # 232
|
| 120 |
+
assert limit((tan(x) - sin(x))/x**3, x, 0) == S.Half # 233
|
| 121 |
+
assert limit((x - sin(2*x))/(x + sin(3*x)), x, 0) == -Rational(1, 4) # 237
|
| 122 |
+
assert limit((1 - sqrt(cos(x)))/x**2, x, 0) == Rational(1, 4) # 239
|
| 123 |
+
assert limit((sqrt(1 + sin(x)) - sqrt(1 - sin(x)))/x, x, 0) == 1 # 240
|
| 124 |
+
|
| 125 |
+
assert limit((1 + h/x)**x, x, oo) == exp(h) # Primer 9
|
| 126 |
+
assert limit((sin(x) - sin(a))/(x - a), x, a) == cos(a) # 222, *176
|
| 127 |
+
assert limit((cos(x) - cos(a))/(x - a), x, a) == -sin(a) # 223
|
| 128 |
+
assert limit((sin(x + h) - sin(x))/h, h, 0) == cos(x) # 225
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def test_f2a():
|
| 132 |
+
assert limit(((x + 1)/(2*x + 1))**(x**2), x, oo) == 0 # Primer 8
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def test_f2():
|
| 136 |
+
assert limit((sqrt(
|
| 137 |
+
cos(x)) - root3(cos(x)))/(sin(x)**2), x, 0) == -Rational(1, 12) # *184
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def test_f3():
|
| 141 |
+
a = Symbol('a')
|
| 142 |
+
#issue 3504
|
| 143 |
+
assert limit(asin(a*x)/x, x, 0) == a
|
shared/package-files/24/246b1b277cc14186ae6720e94827eb5e64543b8a671fe0487f03835f7a804e83/test_xs.py
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas.errors import SettingWithCopyError
|
| 7 |
+
|
| 8 |
+
from pandas import (
|
| 9 |
+
DataFrame,
|
| 10 |
+
Index,
|
| 11 |
+
IndexSlice,
|
| 12 |
+
MultiIndex,
|
| 13 |
+
Series,
|
| 14 |
+
concat,
|
| 15 |
+
)
|
| 16 |
+
import pandas._testing as tm
|
| 17 |
+
|
| 18 |
+
from pandas.tseries.offsets import BDay
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@pytest.fixture
|
| 22 |
+
def four_level_index_dataframe():
|
| 23 |
+
arr = np.array(
|
| 24 |
+
[
|
| 25 |
+
[-0.5109, -2.3358, -0.4645, 0.05076, 0.364],
|
| 26 |
+
[0.4473, 1.4152, 0.2834, 1.00661, 0.1744],
|
| 27 |
+
[-0.6662, -0.5243, -0.358, 0.89145, 2.5838],
|
| 28 |
+
]
|
| 29 |
+
)
|
| 30 |
+
index = MultiIndex(
|
| 31 |
+
levels=[["a", "x"], ["b", "q"], [10.0032, 20.0, 30.0], [3, 4, 5]],
|
| 32 |
+
codes=[[0, 0, 1], [0, 1, 1], [0, 1, 2], [2, 1, 0]],
|
| 33 |
+
names=["one", "two", "three", "four"],
|
| 34 |
+
)
|
| 35 |
+
return DataFrame(arr, index=index, columns=list("ABCDE"))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TestXS:
|
| 39 |
+
def test_xs(
|
| 40 |
+
self, float_frame, datetime_frame, using_copy_on_write, warn_copy_on_write
|
| 41 |
+
):
|
| 42 |
+
float_frame_orig = float_frame.copy()
|
| 43 |
+
idx = float_frame.index[5]
|
| 44 |
+
xs = float_frame.xs(idx)
|
| 45 |
+
for item, value in xs.items():
|
| 46 |
+
if np.isnan(value):
|
| 47 |
+
assert np.isnan(float_frame[item][idx])
|
| 48 |
+
else:
|
| 49 |
+
assert value == float_frame[item][idx]
|
| 50 |
+
|
| 51 |
+
# mixed-type xs
|
| 52 |
+
test_data = {"A": {"1": 1, "2": 2}, "B": {"1": "1", "2": "2", "3": "3"}}
|
| 53 |
+
frame = DataFrame(test_data)
|
| 54 |
+
xs = frame.xs("1")
|
| 55 |
+
assert xs.dtype == np.object_
|
| 56 |
+
assert xs["A"] == 1
|
| 57 |
+
assert xs["B"] == "1"
|
| 58 |
+
|
| 59 |
+
with pytest.raises(
|
| 60 |
+
KeyError, match=re.escape("Timestamp('1999-12-31 00:00:00')")
|
| 61 |
+
):
|
| 62 |
+
datetime_frame.xs(datetime_frame.index[0] - BDay())
|
| 63 |
+
|
| 64 |
+
# xs get column
|
| 65 |
+
series = float_frame.xs("A", axis=1)
|
| 66 |
+
expected = float_frame["A"]
|
| 67 |
+
tm.assert_series_equal(series, expected)
|
| 68 |
+
|
| 69 |
+
# view is returned if possible
|
| 70 |
+
series = float_frame.xs("A", axis=1)
|
| 71 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
| 72 |
+
series[:] = 5
|
| 73 |
+
if using_copy_on_write:
|
| 74 |
+
# but with CoW the view shouldn't propagate mutations
|
| 75 |
+
tm.assert_series_equal(float_frame["A"], float_frame_orig["A"])
|
| 76 |
+
assert not (expected == 5).all()
|
| 77 |
+
else:
|
| 78 |
+
assert (expected == 5).all()
|
| 79 |
+
|
| 80 |
+
def test_xs_corner(self):
|
| 81 |
+
# pathological mixed-type reordering case
|
| 82 |
+
df = DataFrame(index=[0], columns=Index([], dtype="str"))
|
| 83 |
+
df["A"] = 1.0
|
| 84 |
+
df["B"] = "foo"
|
| 85 |
+
df["C"] = 2.0
|
| 86 |
+
df["D"] = "bar"
|
| 87 |
+
df["E"] = 3.0
|
| 88 |
+
|
| 89 |
+
xs = df.xs(0)
|
| 90 |
+
exp = Series([1.0, "foo", 2.0, "bar", 3.0], index=list("ABCDE"), name=0)
|
| 91 |
+
tm.assert_series_equal(xs, exp)
|
| 92 |
+
|
| 93 |
+
# no columns but Index(dtype=object)
|
| 94 |
+
df = DataFrame(index=["a", "b", "c"])
|
| 95 |
+
result = df.xs("a")
|
| 96 |
+
expected = Series([], name="a", dtype=np.float64)
|
| 97 |
+
tm.assert_series_equal(result, expected)
|
| 98 |
+
|
| 99 |
+
def test_xs_duplicates(self):
|
| 100 |
+
df = DataFrame(
|
| 101 |
+
np.random.default_rng(2).standard_normal((5, 2)),
|
| 102 |
+
index=["b", "b", "c", "b", "a"],
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
cross = df.xs("c")
|
| 106 |
+
exp = df.iloc[2]
|
| 107 |
+
tm.assert_series_equal(cross, exp)
|
| 108 |
+
|
| 109 |
+
def test_xs_keep_level(self):
|
| 110 |
+
df = DataFrame(
|
| 111 |
+
{
|
| 112 |
+
"day": {0: "sat", 1: "sun"},
|
| 113 |
+
"flavour": {0: "strawberry", 1: "strawberry"},
|
| 114 |
+
"sales": {0: 10, 1: 12},
|
| 115 |
+
"year": {0: 2008, 1: 2008},
|
| 116 |
+
}
|
| 117 |
+
).set_index(["year", "flavour", "day"])
|
| 118 |
+
result = df.xs("sat", level="day", drop_level=False)
|
| 119 |
+
expected = df[:1]
|
| 120 |
+
tm.assert_frame_equal(result, expected)
|
| 121 |
+
|
| 122 |
+
result = df.xs((2008, "sat"), level=["year", "day"], drop_level=False)
|
| 123 |
+
tm.assert_frame_equal(result, expected)
|
| 124 |
+
|
| 125 |
+
def test_xs_view(
|
| 126 |
+
self, using_array_manager, using_copy_on_write, warn_copy_on_write
|
| 127 |
+
):
|
| 128 |
+
# in 0.14 this will return a view if possible a copy otherwise, but
|
| 129 |
+
# this is numpy dependent
|
| 130 |
+
|
| 131 |
+
dm = DataFrame(np.arange(20.0).reshape(4, 5), index=range(4), columns=range(5))
|
| 132 |
+
df_orig = dm.copy()
|
| 133 |
+
|
| 134 |
+
if using_copy_on_write:
|
| 135 |
+
with tm.raises_chained_assignment_error():
|
| 136 |
+
dm.xs(2)[:] = 20
|
| 137 |
+
tm.assert_frame_equal(dm, df_orig)
|
| 138 |
+
elif using_array_manager:
|
| 139 |
+
# INFO(ArrayManager) with ArrayManager getting a row as a view is
|
| 140 |
+
# not possible
|
| 141 |
+
msg = r"\nA value is trying to be set on a copy of a slice from a DataFrame"
|
| 142 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 143 |
+
dm.xs(2)[:] = 20
|
| 144 |
+
assert not (dm.xs(2) == 20).any()
|
| 145 |
+
else:
|
| 146 |
+
with tm.raises_chained_assignment_error():
|
| 147 |
+
dm.xs(2)[:] = 20
|
| 148 |
+
assert (dm.xs(2) == 20).all()
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class TestXSWithMultiIndex:
|
| 152 |
+
def test_xs_doc_example(self):
|
| 153 |
+
# TODO: more descriptive name
|
| 154 |
+
# based on example in advanced.rst
|
| 155 |
+
arrays = [
|
| 156 |
+
["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
|
| 157 |
+
["one", "two", "one", "two", "one", "two", "one", "two"],
|
| 158 |
+
]
|
| 159 |
+
tuples = list(zip(*arrays))
|
| 160 |
+
|
| 161 |
+
index = MultiIndex.from_tuples(tuples, names=["first", "second"])
|
| 162 |
+
df = DataFrame(
|
| 163 |
+
np.random.default_rng(2).standard_normal((3, 8)),
|
| 164 |
+
index=["A", "B", "C"],
|
| 165 |
+
columns=index,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
result = df.xs(("one", "bar"), level=("second", "first"), axis=1)
|
| 169 |
+
|
| 170 |
+
expected = df.iloc[:, [0]]
|
| 171 |
+
tm.assert_frame_equal(result, expected)
|
| 172 |
+
|
| 173 |
+
def test_xs_integer_key(self):
|
| 174 |
+
# see GH#2107
|
| 175 |
+
dates = range(20111201, 20111205)
|
| 176 |
+
ids = list("abcde")
|
| 177 |
+
index = MultiIndex.from_product([dates, ids], names=["date", "secid"])
|
| 178 |
+
df = DataFrame(
|
| 179 |
+
np.random.default_rng(2).standard_normal((len(index), 3)),
|
| 180 |
+
index,
|
| 181 |
+
["X", "Y", "Z"],
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
result = df.xs(20111201, level="date")
|
| 185 |
+
expected = df.loc[20111201, :]
|
| 186 |
+
tm.assert_frame_equal(result, expected)
|
| 187 |
+
|
| 188 |
+
def test_xs_level(self, multiindex_dataframe_random_data):
|
| 189 |
+
df = multiindex_dataframe_random_data
|
| 190 |
+
result = df.xs("two", level="second")
|
| 191 |
+
expected = df[df.index.get_level_values(1) == "two"]
|
| 192 |
+
expected.index = Index(["foo", "bar", "baz", "qux"], name="first")
|
| 193 |
+
tm.assert_frame_equal(result, expected)
|
| 194 |
+
|
| 195 |
+
def test_xs_level_eq_2(self):
|
| 196 |
+
arr = np.random.default_rng(2).standard_normal((3, 5))
|
| 197 |
+
index = MultiIndex(
|
| 198 |
+
levels=[["a", "p", "x"], ["b", "q", "y"], ["c", "r", "z"]],
|
| 199 |
+
codes=[[2, 0, 1], [2, 0, 1], [2, 0, 1]],
|
| 200 |
+
)
|
| 201 |
+
df = DataFrame(arr, index=index)
|
| 202 |
+
expected = DataFrame(arr[1:2], index=[["a"], ["b"]])
|
| 203 |
+
result = df.xs("c", level=2)
|
| 204 |
+
tm.assert_frame_equal(result, expected)
|
| 205 |
+
|
| 206 |
+
def test_xs_setting_with_copy_error(
|
| 207 |
+
self,
|
| 208 |
+
multiindex_dataframe_random_data,
|
| 209 |
+
using_copy_on_write,
|
| 210 |
+
warn_copy_on_write,
|
| 211 |
+
):
|
| 212 |
+
# this is a copy in 0.14
|
| 213 |
+
df = multiindex_dataframe_random_data
|
| 214 |
+
df_orig = df.copy()
|
| 215 |
+
result = df.xs("two", level="second")
|
| 216 |
+
|
| 217 |
+
if using_copy_on_write or warn_copy_on_write:
|
| 218 |
+
result[:] = 10
|
| 219 |
+
else:
|
| 220 |
+
# setting this will give a SettingWithCopyError
|
| 221 |
+
# as we are trying to write a view
|
| 222 |
+
msg = "A value is trying to be set on a copy of a slice from a DataFrame"
|
| 223 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 224 |
+
result[:] = 10
|
| 225 |
+
tm.assert_frame_equal(df, df_orig)
|
| 226 |
+
|
| 227 |
+
def test_xs_setting_with_copy_error_multiple(
|
| 228 |
+
self, four_level_index_dataframe, using_copy_on_write, warn_copy_on_write
|
| 229 |
+
):
|
| 230 |
+
# this is a copy in 0.14
|
| 231 |
+
df = four_level_index_dataframe
|
| 232 |
+
df_orig = df.copy()
|
| 233 |
+
result = df.xs(("a", 4), level=["one", "four"])
|
| 234 |
+
|
| 235 |
+
if using_copy_on_write or warn_copy_on_write:
|
| 236 |
+
result[:] = 10
|
| 237 |
+
else:
|
| 238 |
+
# setting this will give a SettingWithCopyError
|
| 239 |
+
# as we are trying to write a view
|
| 240 |
+
msg = "A value is trying to be set on a copy of a slice from a DataFrame"
|
| 241 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 242 |
+
result[:] = 10
|
| 243 |
+
tm.assert_frame_equal(df, df_orig)
|
| 244 |
+
|
| 245 |
+
@pytest.mark.parametrize("key, level", [("one", "second"), (["one"], ["second"])])
|
| 246 |
+
def test_xs_with_duplicates(self, key, level, multiindex_dataframe_random_data):
|
| 247 |
+
# see GH#13719
|
| 248 |
+
frame = multiindex_dataframe_random_data
|
| 249 |
+
df = concat([frame] * 2)
|
| 250 |
+
assert df.index.is_unique is False
|
| 251 |
+
expected = concat([frame.xs("one", level="second")] * 2)
|
| 252 |
+
|
| 253 |
+
if isinstance(key, list):
|
| 254 |
+
result = df.xs(tuple(key), level=level)
|
| 255 |
+
else:
|
| 256 |
+
result = df.xs(key, level=level)
|
| 257 |
+
tm.assert_frame_equal(result, expected)
|
| 258 |
+
|
| 259 |
+
def test_xs_missing_values_in_index(self):
|
| 260 |
+
# see GH#6574
|
| 261 |
+
# missing values in returned index should be preserved
|
| 262 |
+
acc = [
|
| 263 |
+
("a", "abcde", 1),
|
| 264 |
+
("b", "bbcde", 2),
|
| 265 |
+
("y", "yzcde", 25),
|
| 266 |
+
("z", "xbcde", 24),
|
| 267 |
+
("z", None, 26),
|
| 268 |
+
("z", "zbcde", 25),
|
| 269 |
+
("z", "ybcde", 26),
|
| 270 |
+
]
|
| 271 |
+
df = DataFrame(acc, columns=["a1", "a2", "cnt"]).set_index(["a1", "a2"])
|
| 272 |
+
expected = DataFrame(
|
| 273 |
+
{"cnt": [24, 26, 25, 26]},
|
| 274 |
+
index=Index(["xbcde", np.nan, "zbcde", "ybcde"], name="a2"),
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
result = df.xs("z", level="a1")
|
| 278 |
+
tm.assert_frame_equal(result, expected)
|
| 279 |
+
|
| 280 |
+
@pytest.mark.parametrize(
|
| 281 |
+
"key, level, exp_arr, exp_index",
|
| 282 |
+
[
|
| 283 |
+
("a", "lvl0", lambda x: x[:, 0:2], Index(["bar", "foo"], name="lvl1")),
|
| 284 |
+
("foo", "lvl1", lambda x: x[:, 1:2], Index(["a"], name="lvl0")),
|
| 285 |
+
],
|
| 286 |
+
)
|
| 287 |
+
def test_xs_named_levels_axis_eq_1(self, key, level, exp_arr, exp_index):
|
| 288 |
+
# see GH#2903
|
| 289 |
+
arr = np.random.default_rng(2).standard_normal((4, 4))
|
| 290 |
+
index = MultiIndex(
|
| 291 |
+
levels=[["a", "b"], ["bar", "foo", "hello", "world"]],
|
| 292 |
+
codes=[[0, 0, 1, 1], [0, 1, 2, 3]],
|
| 293 |
+
names=["lvl0", "lvl1"],
|
| 294 |
+
)
|
| 295 |
+
df = DataFrame(arr, columns=index)
|
| 296 |
+
result = df.xs(key, level=level, axis=1)
|
| 297 |
+
expected = DataFrame(exp_arr(arr), columns=exp_index)
|
| 298 |
+
tm.assert_frame_equal(result, expected)
|
| 299 |
+
|
| 300 |
+
@pytest.mark.parametrize(
|
| 301 |
+
"indexer",
|
| 302 |
+
[
|
| 303 |
+
lambda df: df.xs(("a", 4), level=["one", "four"]),
|
| 304 |
+
lambda df: df.xs("a").xs(4, level="four"),
|
| 305 |
+
],
|
| 306 |
+
)
|
| 307 |
+
def test_xs_level_multiple(self, indexer, four_level_index_dataframe):
|
| 308 |
+
df = four_level_index_dataframe
|
| 309 |
+
expected_values = [[0.4473, 1.4152, 0.2834, 1.00661, 0.1744]]
|
| 310 |
+
expected_index = MultiIndex(
|
| 311 |
+
levels=[["q"], [20.0]], codes=[[0], [0]], names=["two", "three"]
|
| 312 |
+
)
|
| 313 |
+
expected = DataFrame(
|
| 314 |
+
expected_values, index=expected_index, columns=list("ABCDE")
|
| 315 |
+
)
|
| 316 |
+
result = indexer(df)
|
| 317 |
+
tm.assert_frame_equal(result, expected)
|
| 318 |
+
|
| 319 |
+
@pytest.mark.parametrize(
|
| 320 |
+
"indexer", [lambda df: df.xs("a", level=0), lambda df: df.xs("a")]
|
| 321 |
+
)
|
| 322 |
+
def test_xs_level0(self, indexer, four_level_index_dataframe):
|
| 323 |
+
df = four_level_index_dataframe
|
| 324 |
+
expected_values = [
|
| 325 |
+
[-0.5109, -2.3358, -0.4645, 0.05076, 0.364],
|
| 326 |
+
[0.4473, 1.4152, 0.2834, 1.00661, 0.1744],
|
| 327 |
+
]
|
| 328 |
+
expected_index = MultiIndex(
|
| 329 |
+
levels=[["b", "q"], [10.0032, 20.0], [4, 5]],
|
| 330 |
+
codes=[[0, 1], [0, 1], [1, 0]],
|
| 331 |
+
names=["two", "three", "four"],
|
| 332 |
+
)
|
| 333 |
+
expected = DataFrame(
|
| 334 |
+
expected_values, index=expected_index, columns=list("ABCDE")
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
result = indexer(df)
|
| 338 |
+
tm.assert_frame_equal(result, expected)
|
| 339 |
+
|
| 340 |
+
def test_xs_values(self, multiindex_dataframe_random_data):
|
| 341 |
+
df = multiindex_dataframe_random_data
|
| 342 |
+
result = df.xs(("bar", "two")).values
|
| 343 |
+
expected = df.values[4]
|
| 344 |
+
tm.assert_almost_equal(result, expected)
|
| 345 |
+
|
| 346 |
+
def test_xs_loc_equality(self, multiindex_dataframe_random_data):
|
| 347 |
+
df = multiindex_dataframe_random_data
|
| 348 |
+
result = df.xs(("bar", "two"))
|
| 349 |
+
expected = df.loc[("bar", "two")]
|
| 350 |
+
tm.assert_series_equal(result, expected)
|
| 351 |
+
|
| 352 |
+
def test_xs_IndexSlice_argument_not_implemented(self, frame_or_series):
|
| 353 |
+
# GH#35301
|
| 354 |
+
|
| 355 |
+
index = MultiIndex(
|
| 356 |
+
levels=[[("foo", "bar", 0), ("foo", "baz", 0), ("foo", "qux", 0)], [0, 1]],
|
| 357 |
+
codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
obj = DataFrame(np.random.default_rng(2).standard_normal((6, 4)), index=index)
|
| 361 |
+
if frame_or_series is Series:
|
| 362 |
+
obj = obj[0]
|
| 363 |
+
|
| 364 |
+
expected = obj.iloc[-2:].droplevel(0)
|
| 365 |
+
|
| 366 |
+
result = obj.xs(IndexSlice[("foo", "qux", 0), :])
|
| 367 |
+
tm.assert_equal(result, expected)
|
| 368 |
+
|
| 369 |
+
result = obj.loc[IndexSlice[("foo", "qux", 0), :]]
|
| 370 |
+
tm.assert_equal(result, expected)
|
| 371 |
+
|
| 372 |
+
def test_xs_levels_raises(self, frame_or_series):
|
| 373 |
+
obj = DataFrame({"A": [1, 2, 3]})
|
| 374 |
+
if frame_or_series is Series:
|
| 375 |
+
obj = obj["A"]
|
| 376 |
+
|
| 377 |
+
msg = "Index must be a MultiIndex"
|
| 378 |
+
with pytest.raises(TypeError, match=msg):
|
| 379 |
+
obj.xs(0, level="as")
|
| 380 |
+
|
| 381 |
+
def test_xs_multiindex_droplevel_false(self):
|
| 382 |
+
# GH#19056
|
| 383 |
+
mi = MultiIndex.from_tuples(
|
| 384 |
+
[("a", "x"), ("a", "y"), ("b", "x")], names=["level1", "level2"]
|
| 385 |
+
)
|
| 386 |
+
df = DataFrame([[1, 2, 3]], columns=mi)
|
| 387 |
+
result = df.xs("a", axis=1, drop_level=False)
|
| 388 |
+
expected = DataFrame(
|
| 389 |
+
[[1, 2]],
|
| 390 |
+
columns=MultiIndex.from_tuples(
|
| 391 |
+
[("a", "x"), ("a", "y")], names=["level1", "level2"]
|
| 392 |
+
),
|
| 393 |
+
)
|
| 394 |
+
tm.assert_frame_equal(result, expected)
|
| 395 |
+
|
| 396 |
+
def test_xs_droplevel_false(self):
|
| 397 |
+
# GH#19056
|
| 398 |
+
df = DataFrame([[1, 2, 3]], columns=Index(["a", "b", "c"]))
|
| 399 |
+
result = df.xs("a", axis=1, drop_level=False)
|
| 400 |
+
expected = DataFrame({"a": [1]})
|
| 401 |
+
tm.assert_frame_equal(result, expected)
|
| 402 |
+
|
| 403 |
+
def test_xs_droplevel_false_view(
|
| 404 |
+
self, using_array_manager, using_copy_on_write, warn_copy_on_write
|
| 405 |
+
):
|
| 406 |
+
# GH#37832
|
| 407 |
+
df = DataFrame([[1, 2, 3]], columns=Index(["a", "b", "c"]))
|
| 408 |
+
result = df.xs("a", axis=1, drop_level=False)
|
| 409 |
+
# check that result still views the same data as df
|
| 410 |
+
assert np.shares_memory(result.iloc[:, 0]._values, df.iloc[:, 0]._values)
|
| 411 |
+
|
| 412 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
| 413 |
+
df.iloc[0, 0] = 2
|
| 414 |
+
if using_copy_on_write:
|
| 415 |
+
# with copy on write the subset is never modified
|
| 416 |
+
expected = DataFrame({"a": [1]})
|
| 417 |
+
else:
|
| 418 |
+
# modifying original df also modifies result when having a single block
|
| 419 |
+
expected = DataFrame({"a": [2]})
|
| 420 |
+
tm.assert_frame_equal(result, expected)
|
| 421 |
+
|
| 422 |
+
# with mixed dataframe, modifying the parent doesn't modify result
|
| 423 |
+
# TODO the "split" path behaves differently here as with single block
|
| 424 |
+
df = DataFrame([[1, 2.5, "a"]], columns=Index(["a", "b", "c"]))
|
| 425 |
+
result = df.xs("a", axis=1, drop_level=False)
|
| 426 |
+
df.iloc[0, 0] = 2
|
| 427 |
+
if using_copy_on_write:
|
| 428 |
+
# with copy on write the subset is never modified
|
| 429 |
+
expected = DataFrame({"a": [1]})
|
| 430 |
+
elif using_array_manager:
|
| 431 |
+
# Here the behavior is consistent
|
| 432 |
+
expected = DataFrame({"a": [2]})
|
| 433 |
+
else:
|
| 434 |
+
# FIXME: iloc does not update the array inplace using
|
| 435 |
+
# "split" path
|
| 436 |
+
expected = DataFrame({"a": [1]})
|
| 437 |
+
tm.assert_frame_equal(result, expected)
|
| 438 |
+
|
| 439 |
+
def test_xs_list_indexer_droplevel_false(self):
|
| 440 |
+
# GH#41760
|
| 441 |
+
mi = MultiIndex.from_tuples([("x", "m", "a"), ("x", "n", "b"), ("y", "o", "c")])
|
| 442 |
+
df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=mi)
|
| 443 |
+
with pytest.raises(KeyError, match="y"):
|
| 444 |
+
df.xs(("x", "y"), drop_level=False, axis=1)
|
shared/package-files/24/246f87751c118f2a5cfa588356a577af4147982ab5d60cbda4ac7676ba08cd83/MaybeOwned.h
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <c10/macros/Macros.h>
|
| 4 |
+
#include <c10/util/Exception.h>
|
| 5 |
+
|
| 6 |
+
#include <memory>
|
| 7 |
+
#include <type_traits>
|
| 8 |
+
#include <utility>
|
| 9 |
+
|
| 10 |
+
namespace c10 {
|
| 11 |
+
|
| 12 |
+
/// MaybeOwnedTraits<T> describes how to borrow from T. Here is how we
|
| 13 |
+
/// can implement borrowing from an arbitrary type T using a raw
|
| 14 |
+
/// pointer to const:
|
| 15 |
+
template <typename T>
|
| 16 |
+
struct MaybeOwnedTraitsGenericImpl {
|
| 17 |
+
using owned_type = T;
|
| 18 |
+
using borrow_type = const T*;
|
| 19 |
+
|
| 20 |
+
static borrow_type createBorrow(const owned_type& from) {
|
| 21 |
+
return &from;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
static void assignBorrow(borrow_type& lhs, borrow_type rhs) {
|
| 25 |
+
lhs = rhs;
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
static void destroyBorrow(borrow_type& /*toDestroy*/) {}
|
| 29 |
+
|
| 30 |
+
static const owned_type& referenceFromBorrow(const borrow_type& borrow) {
|
| 31 |
+
return *borrow;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
static const owned_type* pointerFromBorrow(const borrow_type& borrow) {
|
| 35 |
+
return borrow;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
static bool debugBorrowIsValid(const borrow_type& borrow) {
|
| 39 |
+
return borrow != nullptr;
|
| 40 |
+
}
|
| 41 |
+
};
|
| 42 |
+
|
| 43 |
+
/// It is possible to eliminate the extra layer of indirection for
|
| 44 |
+
/// borrows for some types that we control. For examples, see
|
| 45 |
+
/// intrusive_ptr.h and TensorBody.h.
|
| 46 |
+
|
| 47 |
+
template <typename T>
|
| 48 |
+
struct MaybeOwnedTraits;
|
| 49 |
+
|
| 50 |
+
// Explicitly enable MaybeOwned<shared_ptr<T>>, rather than allowing
|
| 51 |
+
// MaybeOwned to be used for any type right away.
|
| 52 |
+
template <typename T>
|
| 53 |
+
struct MaybeOwnedTraits<std::shared_ptr<T>>
|
| 54 |
+
: public MaybeOwnedTraitsGenericImpl<std::shared_ptr<T>> {};
|
| 55 |
+
|
| 56 |
+
/// A smart pointer around either a borrowed or owned T. When
|
| 57 |
+
/// constructed with borrowed(), the caller MUST ensure that the
|
| 58 |
+
/// borrowed-from argument outlives this MaybeOwned<T>. Compare to
|
| 59 |
+
/// Rust's std::borrow::Cow
|
| 60 |
+
/// (https://doc.rust-lang.org/std/borrow/enum.Cow.html), but note
|
| 61 |
+
/// that it is probably not suitable for general use because C++ has
|
| 62 |
+
/// no borrow checking. Included here to support
|
| 63 |
+
/// Tensor::expect_contiguous.
|
| 64 |
+
template <typename T>
|
| 65 |
+
class MaybeOwned final {
|
| 66 |
+
using borrow_type = typename MaybeOwnedTraits<T>::borrow_type;
|
| 67 |
+
using owned_type = typename MaybeOwnedTraits<T>::owned_type;
|
| 68 |
+
|
| 69 |
+
bool isBorrowed_;
|
| 70 |
+
union {
|
| 71 |
+
borrow_type borrow_;
|
| 72 |
+
owned_type own_;
|
| 73 |
+
};
|
| 74 |
+
|
| 75 |
+
/// Don't use this; use borrowed() instead.
|
| 76 |
+
explicit MaybeOwned(const owned_type& t)
|
| 77 |
+
: isBorrowed_(true), borrow_(MaybeOwnedTraits<T>::createBorrow(t)) {}
|
| 78 |
+
|
| 79 |
+
/// Don't use this; use owned() instead.
|
| 80 |
+
explicit MaybeOwned(T&& t) noexcept(std::is_nothrow_move_constructible_v<T>)
|
| 81 |
+
: isBorrowed_(false), own_(std::move(t)) {}
|
| 82 |
+
|
| 83 |
+
/// Don't use this; use owned() instead.
|
| 84 |
+
template <class... Args>
|
| 85 |
+
explicit MaybeOwned(std::in_place_t, Args&&... args)
|
| 86 |
+
: isBorrowed_(false), own_(std::forward<Args>(args)...) {}
|
| 87 |
+
|
| 88 |
+
public:
|
| 89 |
+
explicit MaybeOwned() : isBorrowed_(true), borrow_() {}
|
| 90 |
+
|
| 91 |
+
// Copying a borrow yields another borrow of the original, as with a
|
| 92 |
+
// T*. Copying an owned T yields another owned T for safety: no
|
| 93 |
+
// chains of borrowing by default! (Note you could get that behavior
|
| 94 |
+
// with MaybeOwned<T>::borrowed(*rhs) if you wanted it.)
|
| 95 |
+
MaybeOwned(const MaybeOwned& rhs) : isBorrowed_(rhs.isBorrowed_) {
|
| 96 |
+
if (C10_LIKELY(rhs.isBorrowed_)) {
|
| 97 |
+
MaybeOwnedTraits<T>::assignBorrow(borrow_, rhs.borrow_);
|
| 98 |
+
} else {
|
| 99 |
+
new (&own_) T(rhs.own_);
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
MaybeOwned& operator=(const MaybeOwned& rhs) {
|
| 104 |
+
if (this == &rhs) {
|
| 105 |
+
return *this;
|
| 106 |
+
}
|
| 107 |
+
if (C10_UNLIKELY(!isBorrowed_)) {
|
| 108 |
+
if (rhs.isBorrowed_) {
|
| 109 |
+
own_.~T();
|
| 110 |
+
MaybeOwnedTraits<T>::assignBorrow(borrow_, rhs.borrow_);
|
| 111 |
+
isBorrowed_ = true;
|
| 112 |
+
} else {
|
| 113 |
+
own_ = rhs.own_;
|
| 114 |
+
}
|
| 115 |
+
} else {
|
| 116 |
+
if (C10_LIKELY(rhs.isBorrowed_)) {
|
| 117 |
+
MaybeOwnedTraits<T>::assignBorrow(borrow_, rhs.borrow_);
|
| 118 |
+
} else {
|
| 119 |
+
MaybeOwnedTraits<T>::destroyBorrow(borrow_);
|
| 120 |
+
new (&own_) T(rhs.own_);
|
| 121 |
+
isBorrowed_ = false;
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isBorrowed_ == rhs.isBorrowed_);
|
| 125 |
+
return *this;
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
MaybeOwned(MaybeOwned&& rhs) noexcept(
|
| 129 |
+
// NOLINTNEXTLINE(*-noexcept-move-*)
|
| 130 |
+
std::is_nothrow_move_constructible_v<T> &&
|
| 131 |
+
std::is_nothrow_move_assignable_v<borrow_type>)
|
| 132 |
+
: isBorrowed_(rhs.isBorrowed_) {
|
| 133 |
+
if (C10_LIKELY(rhs.isBorrowed_)) {
|
| 134 |
+
MaybeOwnedTraits<T>::assignBorrow(borrow_, rhs.borrow_);
|
| 135 |
+
} else {
|
| 136 |
+
new (&own_) T(std::move(rhs.own_));
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
MaybeOwned& operator=(MaybeOwned&& rhs) noexcept(
|
| 141 |
+
std::is_nothrow_move_assignable_v<T> &&
|
| 142 |
+
std::is_nothrow_move_assignable_v<borrow_type> &&
|
| 143 |
+
std::is_nothrow_move_constructible_v<T> &&
|
| 144 |
+
// NOLINTNEXTLINE(*-noexcept-move-*)
|
| 145 |
+
std::is_nothrow_destructible_v<T> &&
|
| 146 |
+
std::is_nothrow_destructible_v<borrow_type>) {
|
| 147 |
+
if (this == &rhs) {
|
| 148 |
+
return *this;
|
| 149 |
+
}
|
| 150 |
+
if (C10_UNLIKELY(!isBorrowed_)) {
|
| 151 |
+
if (rhs.isBorrowed_) {
|
| 152 |
+
own_.~T();
|
| 153 |
+
MaybeOwnedTraits<T>::assignBorrow(borrow_, rhs.borrow_);
|
| 154 |
+
isBorrowed_ = true;
|
| 155 |
+
} else {
|
| 156 |
+
own_ = std::move(rhs.own_);
|
| 157 |
+
}
|
| 158 |
+
} else {
|
| 159 |
+
if (C10_LIKELY(rhs.isBorrowed_)) {
|
| 160 |
+
MaybeOwnedTraits<T>::assignBorrow(borrow_, rhs.borrow_);
|
| 161 |
+
} else {
|
| 162 |
+
MaybeOwnedTraits<T>::destroyBorrow(borrow_);
|
| 163 |
+
new (&own_) T(std::move(rhs.own_));
|
| 164 |
+
isBorrowed_ = false;
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
return *this;
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
static MaybeOwned borrowed(const T& t) {
|
| 171 |
+
return MaybeOwned(t);
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
static MaybeOwned owned(T&& t) noexcept(
|
| 175 |
+
std::is_nothrow_move_constructible_v<T>) {
|
| 176 |
+
return MaybeOwned(std::move(t));
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
template <class... Args>
|
| 180 |
+
static MaybeOwned owned(std::in_place_t, Args&&... args) {
|
| 181 |
+
return MaybeOwned(std::in_place, std::forward<Args>(args)...);
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
~MaybeOwned() noexcept(
|
| 185 |
+
// NOLINTNEXTLINE(*-noexcept-destructor)
|
| 186 |
+
std::is_nothrow_destructible_v<T> &&
|
| 187 |
+
std::is_nothrow_destructible_v<borrow_type>) {
|
| 188 |
+
if (C10_UNLIKELY(!isBorrowed_)) {
|
| 189 |
+
own_.~T();
|
| 190 |
+
} else {
|
| 191 |
+
MaybeOwnedTraits<T>::destroyBorrow(borrow_);
|
| 192 |
+
}
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
// This is an implementation detail! You should know what you're doing
|
| 196 |
+
// if you are testing this. If you just want to guarantee ownership move
|
| 197 |
+
// this into a T
|
| 198 |
+
bool unsafeIsBorrowed() const {
|
| 199 |
+
return isBorrowed_;
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
const T& operator*() const& {
|
| 203 |
+
if (isBorrowed_) {
|
| 204 |
+
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
|
| 205 |
+
MaybeOwnedTraits<T>::debugBorrowIsValid(borrow_));
|
| 206 |
+
}
|
| 207 |
+
return C10_LIKELY(isBorrowed_)
|
| 208 |
+
? MaybeOwnedTraits<T>::referenceFromBorrow(borrow_)
|
| 209 |
+
: own_;
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
const T* operator->() const {
|
| 213 |
+
if (isBorrowed_) {
|
| 214 |
+
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
|
| 215 |
+
MaybeOwnedTraits<T>::debugBorrowIsValid(borrow_));
|
| 216 |
+
}
|
| 217 |
+
return C10_LIKELY(isBorrowed_)
|
| 218 |
+
? MaybeOwnedTraits<T>::pointerFromBorrow(borrow_)
|
| 219 |
+
: &own_;
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
// If borrowed, copy the underlying T. If owned, move from
|
| 223 |
+
// it. borrowed/owned state remains the same, and either we
|
| 224 |
+
// reference the same borrow as before or we are an owned moved-from
|
| 225 |
+
// T.
|
| 226 |
+
T operator*() && {
|
| 227 |
+
if (isBorrowed_) {
|
| 228 |
+
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
|
| 229 |
+
MaybeOwnedTraits<T>::debugBorrowIsValid(borrow_));
|
| 230 |
+
return MaybeOwnedTraits<T>::referenceFromBorrow(borrow_);
|
| 231 |
+
} else {
|
| 232 |
+
return std::move(own_);
|
| 233 |
+
}
|
| 234 |
+
}
|
| 235 |
+
};
|
| 236 |
+
|
| 237 |
+
} // namespace c10
|
shared/package-files/24/246feb139039664e5ec657e2bd91e7388dd4a739bc7498e628a1e4c048dee0b4/test_non_unique.py
ADDED
|
@@ -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| 12 |
+
from pandas.io.formats.style import Styler
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.fixture
|
| 16 |
+
def df():
|
| 17 |
+
return DataFrame(
|
| 18 |
+
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
|
| 19 |
+
index=["i", "j", "j"],
|
| 20 |
+
columns=["c", "d", "d"],
|
| 21 |
+
dtype=float,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.fixture
|
| 26 |
+
def styler(df):
|
| 27 |
+
return Styler(df, uuid_len=0)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_format_non_unique(df):
|
| 31 |
+
# GH 41269
|
| 32 |
+
|
| 33 |
+
# test dict
|
| 34 |
+
html = df.style.format({"d": "{:.1f}"}).to_html()
|
| 35 |
+
for val in ["1.000000<", "4.000000<", "7.000000<"]:
|
| 36 |
+
assert val in html
|
| 37 |
+
for val in ["2.0<", "3.0<", "5.0<", "6.0<", "8.0<", "9.0<"]:
|
| 38 |
+
assert val in html
|
| 39 |
+
|
| 40 |
+
# test subset
|
| 41 |
+
html = df.style.format(precision=1, subset=IndexSlice["j", "d"]).to_html()
|
| 42 |
+
for val in ["1.000000<", "4.000000<", "7.000000<", "2.000000<", "3.000000<"]:
|
| 43 |
+
assert val in html
|
| 44 |
+
for val in ["5.0<", "6.0<", "8.0<", "9.0<"]:
|
| 45 |
+
assert val in html
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@pytest.mark.parametrize("func", ["apply", "map"])
|
| 49 |
+
def test_apply_map_non_unique_raises(df, func):
|
| 50 |
+
# GH 41269
|
| 51 |
+
if func == "apply":
|
| 52 |
+
op = lambda s: ["color: red;"] * len(s)
|
| 53 |
+
else:
|
| 54 |
+
op = lambda v: "color: red;"
|
| 55 |
+
|
| 56 |
+
with pytest.raises(KeyError, match="`Styler.apply` and `.map` are not"):
|
| 57 |
+
getattr(df.style, func)(op)._compute()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def test_table_styles_dict_non_unique_index(styler):
|
| 61 |
+
styles = styler.set_table_styles(
|
| 62 |
+
{"j": [{"selector": "td", "props": "a: v;"}]}, axis=1
|
| 63 |
+
).table_styles
|
| 64 |
+
assert styles == [
|
| 65 |
+
{"selector": "td.row1", "props": [("a", "v")]},
|
| 66 |
+
{"selector": "td.row2", "props": [("a", "v")]},
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_table_styles_dict_non_unique_columns(styler):
|
| 71 |
+
styles = styler.set_table_styles(
|
| 72 |
+
{"d": [{"selector": "td", "props": "a: v;"}]}, axis=0
|
| 73 |
+
).table_styles
|
| 74 |
+
assert styles == [
|
| 75 |
+
{"selector": "td.col1", "props": [("a", "v")]},
|
| 76 |
+
{"selector": "td.col2", "props": [("a", "v")]},
|
| 77 |
+
]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_tooltips_non_unique_raises(styler):
|
| 81 |
+
# ttips has unique keys
|
| 82 |
+
ttips = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "b"])
|
| 83 |
+
styler.set_tooltips(ttips=ttips) # OK
|
| 84 |
+
|
| 85 |
+
# ttips has non-unique columns
|
| 86 |
+
ttips = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "c"], index=["a", "b"])
|
| 87 |
+
with pytest.raises(KeyError, match="Tooltips render only if `ttips` has unique"):
|
| 88 |
+
styler.set_tooltips(ttips=ttips)
|
| 89 |
+
|
| 90 |
+
# ttips has non-unique index
|
| 91 |
+
ttips = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "a"])
|
| 92 |
+
with pytest.raises(KeyError, match="Tooltips render only if `ttips` has unique"):
|
| 93 |
+
styler.set_tooltips(ttips=ttips)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_set_td_classes_non_unique_raises(styler):
|
| 97 |
+
# classes has unique keys
|
| 98 |
+
classes = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "b"])
|
| 99 |
+
styler.set_td_classes(classes=classes) # OK
|
| 100 |
+
|
| 101 |
+
# classes has non-unique columns
|
| 102 |
+
classes = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "c"], index=["a", "b"])
|
| 103 |
+
with pytest.raises(KeyError, match="Classes render only if `classes` has unique"):
|
| 104 |
+
styler.set_td_classes(classes=classes)
|
| 105 |
+
|
| 106 |
+
# classes has non-unique index
|
| 107 |
+
classes = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "a"])
|
| 108 |
+
with pytest.raises(KeyError, match="Classes render only if `classes` has unique"):
|
| 109 |
+
styler.set_td_classes(classes=classes)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_hide_columns_non_unique(styler):
|
| 113 |
+
ctx = styler.hide(["d"], axis="columns")._translate(True, True)
|
| 114 |
+
|
| 115 |
+
assert ctx["head"][0][1]["display_value"] == "c"
|
| 116 |
+
assert ctx["head"][0][1]["is_visible"] is True
|
| 117 |
+
|
| 118 |
+
assert ctx["head"][0][2]["display_value"] == "d"
|
| 119 |
+
assert ctx["head"][0][2]["is_visible"] is False
|
| 120 |
+
|
| 121 |
+
assert ctx["head"][0][3]["display_value"] == "d"
|
| 122 |
+
assert ctx["head"][0][3]["is_visible"] is False
|
| 123 |
+
|
| 124 |
+
assert ctx["body"][0][1]["is_visible"] is True
|
| 125 |
+
assert ctx["body"][0][2]["is_visible"] is False
|
| 126 |
+
assert ctx["body"][0][3]["is_visible"] is False
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def test_latex_non_unique(styler):
|
| 130 |
+
result = styler.to_latex()
|
| 131 |
+
assert result == dedent(
|
| 132 |
+
"""\
|
| 133 |
+
\\begin{tabular}{lrrr}
|
| 134 |
+
& c & d & d \\\\
|
| 135 |
+
i & 1.000000 & 2.000000 & 3.000000 \\\\
|
| 136 |
+
j & 4.000000 & 5.000000 & 6.000000 \\\\
|
| 137 |
+
j & 7.000000 & 8.000000 & 9.000000 \\\\
|
| 138 |
+
\\end{tabular}
|
| 139 |
+
"""
|
| 140 |
+
)
|
shared/package-files/24/24703165ad1fd520140a056ab8e75450e1aa49170ccb3deb9298972f53e5a1cf/entry_points.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[conda]
|
| 2 |
+
conda-libmamba-solver = conda_libmamba_solver.plugin
|
shared/package-files/24/2471caaaa65bda395622483db7a4acc5b2cbdbb485e555b2181ea2517a97d40d/models.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import sklearn
|
| 3 |
+
import sklearn.ensemble
|
| 4 |
+
from sklearn.preprocessing import StandardScaler
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class KerasWrap:
|
| 8 |
+
"""A wrapper that allows us to set parameters in the constructor and do a reset before fitting."""
|
| 9 |
+
|
| 10 |
+
def __init__(self, model, epochs, flatten_output=False):
|
| 11 |
+
self.model = model
|
| 12 |
+
self.epochs = epochs
|
| 13 |
+
self.flatten_output = flatten_output
|
| 14 |
+
self.init_weights = None
|
| 15 |
+
self.scaler = StandardScaler()
|
| 16 |
+
|
| 17 |
+
def fit(self, X, y, verbose=0):
|
| 18 |
+
if self.init_weights is None:
|
| 19 |
+
self.init_weights = self.model.get_weights()
|
| 20 |
+
else:
|
| 21 |
+
self.model.set_weights(self.init_weights)
|
| 22 |
+
self.scaler.fit(X)
|
| 23 |
+
return self.model.fit(X, y, epochs=self.epochs, verbose=verbose)
|
| 24 |
+
|
| 25 |
+
def predict(self, X):
|
| 26 |
+
X = self.scaler.transform(X)
|
| 27 |
+
if self.flatten_output:
|
| 28 |
+
return self.model.predict(X).flatten()
|
| 29 |
+
else:
|
| 30 |
+
return self.model.predict(X)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# This models are all tuned for the corrgroups60 dataset
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def corrgroups60__lasso():
|
| 37 |
+
"""Lasso Regression"""
|
| 38 |
+
return sklearn.linear_model.Lasso(alpha=0.1)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def corrgroups60__ridge():
|
| 42 |
+
"""Ridge Regression"""
|
| 43 |
+
return sklearn.linear_model.Ridge(alpha=1.0)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def corrgroups60__decision_tree():
|
| 47 |
+
"""Decision Tree"""
|
| 48 |
+
# max_depth was chosen to minimise test error
|
| 49 |
+
return sklearn.tree.DecisionTreeRegressor(random_state=0, max_depth=6)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def corrgroups60__random_forest():
|
| 53 |
+
"""Random Forest"""
|
| 54 |
+
return sklearn.ensemble.RandomForestRegressor(100, random_state=0)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def corrgroups60__gbm():
|
| 58 |
+
"""Gradient Boosted Trees"""
|
| 59 |
+
import xgboost
|
| 60 |
+
|
| 61 |
+
# max_depth and learning_rate were fixed then n_estimators was chosen using a train/test split
|
| 62 |
+
return xgboost.XGBRegressor(max_depth=6, n_estimators=50, learning_rate=0.1, n_jobs=8, random_state=0)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def corrgroups60__ffnn():
|
| 66 |
+
"""4-Layer Neural Network"""
|
| 67 |
+
import tensorflow as tf
|
| 68 |
+
|
| 69 |
+
model = tf.keras.models.Sequential()
|
| 70 |
+
model.add(tf.keras.layers.Dense(32, activation="relu", input_dim=60))
|
| 71 |
+
model.add(tf.keras.layers.Dense(20, activation="relu"))
|
| 72 |
+
model.add(tf.keras.layers.Dense(20, activation="relu"))
|
| 73 |
+
model.add(tf.keras.layers.Dense(1))
|
| 74 |
+
|
| 75 |
+
model.compile(optimizer="adam", loss="mean_squared_error", metrics=["mean_squared_error"])
|
| 76 |
+
|
| 77 |
+
return KerasWrap(model, 30, flatten_output=True)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def independentlinear60__lasso():
|
| 81 |
+
"""Lasso Regression"""
|
| 82 |
+
return sklearn.linear_model.Lasso(alpha=0.1)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def independentlinear60__ridge():
|
| 86 |
+
"""Ridge Regression"""
|
| 87 |
+
return sklearn.linear_model.Ridge(alpha=1.0)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def independentlinear60__decision_tree():
|
| 91 |
+
"""Decision Tree"""
|
| 92 |
+
# max_depth was chosen to minimise test error
|
| 93 |
+
return sklearn.tree.DecisionTreeRegressor(random_state=0, max_depth=4)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def independentlinear60__random_forest():
|
| 97 |
+
"""Random Forest"""
|
| 98 |
+
return sklearn.ensemble.RandomForestRegressor(100, random_state=0)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def independentlinear60__gbm():
|
| 102 |
+
"""Gradient Boosted Trees"""
|
| 103 |
+
import xgboost
|
| 104 |
+
|
| 105 |
+
# max_depth and learning_rate were fixed then n_estimators was chosen using a train/test split
|
| 106 |
+
return xgboost.XGBRegressor(max_depth=6, n_estimators=100, learning_rate=0.1, n_jobs=8, random_state=0)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def independentlinear60__ffnn():
|
| 110 |
+
"""4-Layer Neural Network"""
|
| 111 |
+
from tensorflow.keras.layers import Dense
|
| 112 |
+
from tensorflow.keras.models import Sequential
|
| 113 |
+
|
| 114 |
+
model = Sequential()
|
| 115 |
+
model.add(Dense(32, activation="relu", input_dim=60))
|
| 116 |
+
model.add(Dense(20, activation="relu"))
|
| 117 |
+
model.add(Dense(20, activation="relu"))
|
| 118 |
+
model.add(Dense(1))
|
| 119 |
+
|
| 120 |
+
model.compile(optimizer="adam", loss="mean_squared_error", metrics=["mean_squared_error"])
|
| 121 |
+
|
| 122 |
+
return KerasWrap(model, 30, flatten_output=True)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def cric__lasso():
|
| 126 |
+
"""Lasso Regression"""
|
| 127 |
+
model = sklearn.linear_model.LogisticRegression(penalty="l1", C=0.002)
|
| 128 |
+
|
| 129 |
+
# we want to explain the raw probability outputs of the trees
|
| 130 |
+
model.predict = lambda X: model.predict_proba(X)[:, 1]
|
| 131 |
+
|
| 132 |
+
return model
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def cric__ridge():
|
| 136 |
+
"""Ridge Regression"""
|
| 137 |
+
model = sklearn.linear_model.LogisticRegression(penalty="l2")
|
| 138 |
+
|
| 139 |
+
# we want to explain the raw probability outputs of the trees
|
| 140 |
+
model.predict = lambda X: model.predict_proba(X)[:, 1]
|
| 141 |
+
|
| 142 |
+
return model
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def cric__decision_tree():
|
| 146 |
+
"""Decision Tree"""
|
| 147 |
+
model = sklearn.tree.DecisionTreeClassifier(random_state=0, max_depth=4)
|
| 148 |
+
|
| 149 |
+
# we want to explain the raw probability outputs of the trees
|
| 150 |
+
model.predict = lambda X: model.predict_proba(X)[:, 1]
|
| 151 |
+
|
| 152 |
+
return model
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def cric__random_forest():
|
| 156 |
+
"""Random Forest"""
|
| 157 |
+
model = sklearn.ensemble.RandomForestClassifier(100, random_state=0)
|
| 158 |
+
|
| 159 |
+
# we want to explain the raw probability outputs of the trees
|
| 160 |
+
model.predict = lambda X: model.predict_proba(X)[:, 1]
|
| 161 |
+
|
| 162 |
+
return model
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def cric__gbm():
|
| 166 |
+
"""Gradient Boosted Trees"""
|
| 167 |
+
import xgboost
|
| 168 |
+
|
| 169 |
+
# max_depth and subsample match the params used for the full cric data in the paper
|
| 170 |
+
# learning_rate was set a bit higher to allow for faster runtimes
|
| 171 |
+
# n_estimators was chosen based on a train/test split of the data
|
| 172 |
+
model = xgboost.XGBClassifier(
|
| 173 |
+
max_depth=5, n_estimators=400, learning_rate=0.01, subsample=0.2, n_jobs=8, random_state=0
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
# we want to explain the margin, not the transformed probability outputs
|
| 177 |
+
model.__orig_predict = model.predict
|
| 178 |
+
model.predict = lambda X: model.__orig_predict(X, output_margin=True)
|
| 179 |
+
|
| 180 |
+
return model
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def cric__ffnn():
|
| 184 |
+
"""4-Layer Neural Network"""
|
| 185 |
+
from tensorflow.keras.layers import Dense, Dropout
|
| 186 |
+
from tensorflow.keras.models import Sequential
|
| 187 |
+
|
| 188 |
+
model = Sequential()
|
| 189 |
+
model.add(Dense(10, activation="relu", input_dim=336))
|
| 190 |
+
model.add(Dropout(0.5))
|
| 191 |
+
model.add(Dense(10, activation="relu"))
|
| 192 |
+
model.add(Dropout(0.5))
|
| 193 |
+
model.add(Dense(1, activation="sigmoid"))
|
| 194 |
+
|
| 195 |
+
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
|
| 196 |
+
|
| 197 |
+
return KerasWrap(model, 30, flatten_output=True)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def human__decision_tree():
|
| 201 |
+
"""Decision Tree"""
|
| 202 |
+
# build data
|
| 203 |
+
N = 1000000
|
| 204 |
+
M = 3
|
| 205 |
+
X = np.zeros((N, M))
|
| 206 |
+
X.shape
|
| 207 |
+
y = np.zeros(N)
|
| 208 |
+
X[0, 0] = 1
|
| 209 |
+
y[0] = 8
|
| 210 |
+
X[1, 1] = 1
|
| 211 |
+
y[1] = 8
|
| 212 |
+
X[2, 0:2] = 1
|
| 213 |
+
y[2] = 4
|
| 214 |
+
|
| 215 |
+
# fit model
|
| 216 |
+
xor_model = sklearn.tree.DecisionTreeRegressor(max_depth=2)
|
| 217 |
+
xor_model.fit(X, y)
|
| 218 |
+
|
| 219 |
+
return xor_model
|