s42chen commited on
Commit
087d894
·
verified ·
1 Parent(s): fb150a6

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

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +34 -0
  2. shared/package-files/74/74cb5a1b5d641a526b8092601961036590269cefc77d3dcbe17f2923bd8b2c56/blob +0 -0
  3. shared/package-files/74/74d0eaa56b246fa61ee453baacdbeae21f74fb5f5f0dcbd7f482d0e2a99002c3/blob +2390 -0
  4. shared/package-files/74/74d25b704e4e54363fc07c0dfd4054b5f211775dceaaef910443bbe20e52b010/blob +0 -0
  5. shared/package-files/74/74d8c4bc58760b7e17328884fd1ee5889bf972bc97533d9647656cc5d9d0763a/blob +551 -0
  6. shared/package-files/74/74db386f628321c1b833584f06f0f4f7e561ec20f394f22b16c70e76f2f7a75a/blob +988 -0
  7. shared/package-files/74/74dfbdd489c7257280129e4310ebc2f1baa5ee71feac829ef373bc0d40f3d15a/blob +24 -0
  8. shared/package-files/74/74e2d737140952e364e42db839d1c1aef4e603493ae640b9d73ddd0f98163b30/blob +0 -0
  9. shared/package-files/74/74e2d8d3c19397adbd9941224533e5fe224ed877384e632ee23fe65f7851fd38/blob +25 -0
  10. shared/package-files/74/74ed196010d4867d7f963ce3724114d8b52f26ee4bb73bf988c1c08dc85343f8/blob +14 -0
  11. shared/package-files/74/74ed1bf4c7053d42d37e786969414fcb4dfc648f22430a361720ed8f877d3293/blob +384 -0
  12. shared/package-files/74/74f228e0ec0e77185c65426ce5789f97edc5f0c8ac4e864aae98922d988c150d/blob +3 -0
  13. shared/package-files/74/74f50ae63bf42c71641bdc954f8cf4faf960782063c74ef0d05c2be39b62fb76/blob +26 -0
  14. shared/package-files/74/74f6ebb9d073af2e826b07d157521b6c5ed21c6bd26baa038c625ac842e71732/blob +7 -0
  15. shared/package-files/74/74f937df87bb310c25ef5f9abcdc911016155ae15341c54a7e5b65461ae5469c/blob +0 -0
  16. shared/package-files/74/74f9be00518ea6c3d0a8651ec053f14fa9a337dbb1bcbde3a410f753bc970bc9/blob +24 -0
  17. shared/package-files/74/74fb5a1e5668b133d0182c5320a46ae4e8f30aa24f575a3a182210b22e5aa05c/blob +379 -0
  18. shared/package-files/74/74fe34d648c99426271d3dc899c19024a79fd139a0c353fad1b920824b84463f/blob +91 -0
  19. shared/package-files/75/750007a61b9a86c49e4ee516cc31667b7c969861748dee48a2d81cd32b8da07e/blob +23 -0
  20. shared/package-files/75/7501011389a364fb724632972ba67e6cc1c9745aa9c21233c431f8c74e2b2989/blob +0 -0
  21. shared/package-files/75/7502587d52e7810228f2ecb45ac4319ea0f5c008b7ac91053b920010dc6ddf94/blob +690 -0
  22. shared/package-files/75/75038d5b2a5bcdfbf31820ed769dccfcd25ac12709bccd838876f1d64fb0c3b8/blob +188 -0
  23. shared/package-files/75/7505076b53c6a49b0d136c7f490171b4e5fe8e8bac12aa65c07d5b76c93a9a71/blob +4 -0
  24. shared/package-files/75/7505f48f7ae32af9c3cce082d4d3c7d4adc28018d428e52968dd27b50b586edf/blob +24 -0
  25. shared/package-files/75/750a5404fadd8bddb13c09751eacd776c431166e124a0e2dd0d01bd9b8fb2314/blob +590 -0
  26. shared/package-files/75/750aa994ff806563d944a8a8f0b9938d85a5098cfd5665bebac52bb5a2e977fc/blob +56 -0
  27. shared/package-files/75/750c6b9abcaee83e2a1cacaa7e5c588e87c4a28cfac5707dae39edb908087b84/blob +1113 -0
  28. shared/package-files/75/750d3bcc9d7ebe5a45a96041bbf734707c53d325dc192bbba3b2f10c2132077b/blob +274 -0
  29. shared/package-files/75/750dae72b20664681807a852e202c8cc5283118a5f00135b3f9e254bb1fa0084/blob +747 -0
  30. shared/package-files/75/7510eeb3ef2a9159b938104fdf56be45d49a85872b9fd1c66097204dafcb3c12/blob +19 -0
  31. shared/package-files/75/7513950e2f6446f91b49dca77772f4f6da7dfdec7343842a1b7c67371efc25e5/blob +9 -0
  32. shared/package-files/75/7513a174b46308686a1fb6c8dffc946cf06beda20a04cd4ab3f8968beec73aad/blob +15 -0
  33. shared/package-files/75/7514b45c9d86e1bc0b74146328c929c82a4119882e52205043d8fe3f70423c93/blob +0 -0
  34. shared/package-files/75/75173baf355b7493185b2268dc65617e6e061b18fb10cff224171db108ca7600/blob +3 -0
  35. shared/package-files/75/7518c360c036ef0b0fdaebdaec9f8a81dcb952fba4354a7a21f42d8629b35de1/blob +26 -0
  36. shared/package-files/75/75193016ad610ad89daf29e4b2bc84b3c2f8e3667b445c314e3cb0c24d2b6546/blob +23 -0
  37. shared/package-files/75/751945c08fd2c7ac7b49d0be092622eafa5ac58e60d92f99a59b4f8bdc307c33/blob +3 -0
  38. shared/package-files/75/751c6320bf926c5558d2adc88d232b7e00531eb9b52d90e02ceca0541c226197/blob +177 -0
  39. shared/package-files/75/751d9124f157e3907b0ed61ac19ec07444db9edec14cebd0e486f7095d4abe08/blob +204 -0
  40. shared/package-files/75/752297e4e2cef56804b28cb461cfbd7bd8dfcd455b2d42a2797f5a1ced4b692a/blob +98 -0
  41. shared/package-files/75/75235d661a1cf1ae21e74c11b5b3b12f0a668148ae305a5eeb2b532d445ca656/blob +261 -0
  42. shared/package-files/75/7523f6f7746da075be73a707f55468cd1afcd73c2a2f6e03062f7063fa2952ec/blob +21 -0
  43. shared/package-files/75/75240f0a25da63a2c532ae50653cce37807e98e2384f232cf1deabff30686c63/blob +50 -0
  44. shared/package-files/75/7524540714554e1f9d5ccacc47fa10dd9212bb64127e1499962934dcc8dbbb7d/blob +132 -0
  45. shared/package-files/75/752560d1d1de753f70d503b617502f5a87a5e3f87cc26b984b882e11a2fee4a9/blob +0 -0
  46. shared/package-files/75/752571886a9d351ea06c5e34578276b46850f93e110ef4b21b2a47bd870f0d83/blob +38 -0
  47. shared/package-files/75/75292a923cfe979435cef921f0a15ecc2ff9cd1cf0f0137544e28f8d8f78acdc/blob +0 -0
  48. shared/package-files/75/7529f3512586bcbd947268aa68f79cf9d6d344c2063d4ed38fbfafa859751314/blob +82 -0
  49. shared/package-files/75/752ad8827ddb5678e68114cca31f7830a5881b91aeaf8dce47113f2be51df840/blob +24 -0
  50. shared/package-files/75/7531be245e6cf3693e2ebb502ccc7558d65e7f756b6466bfb016ef4d2027938f/blob +39 -0
.gitattributes CHANGED
@@ -573,3 +573,37 @@ shared/package-files/72/72f5b59eddc1e471739db67ab9fb91f2a93df5d12ce5235771371b60
573
  shared/package-files/73/73e4d5ccbe1a229ce1a36bbc0398ca8c8d92f2450db637461b460c18b5dbc4de/blob filter=lfs diff=lfs merge=lfs -text
574
  shared/package-files/73/73fb6a31adbe9e0b4d63cf0981fbfbc7ce53b030751cf47d123c34f9f936d787/blob filter=lfs diff=lfs merge=lfs -text
575
  shared/package-files/74/744d1b57418c2f4d5351de3fc3a654b6c9c06ccd74eb16a27b808b822e6b34ca/blob filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
573
  shared/package-files/73/73e4d5ccbe1a229ce1a36bbc0398ca8c8d92f2450db637461b460c18b5dbc4de/blob filter=lfs diff=lfs merge=lfs -text
574
  shared/package-files/73/73fb6a31adbe9e0b4d63cf0981fbfbc7ce53b030751cf47d123c34f9f936d787/blob filter=lfs diff=lfs merge=lfs -text
575
  shared/package-files/74/744d1b57418c2f4d5351de3fc3a654b6c9c06ccd74eb16a27b808b822e6b34ca/blob filter=lfs diff=lfs merge=lfs -text
576
+ shared/package-files/74/74f228e0ec0e77185c65426ce5789f97edc5f0c8ac4e864aae98922d988c150d/blob filter=lfs diff=lfs merge=lfs -text
577
+ shared/package-files/75/75173baf355b7493185b2268dc65617e6e061b18fb10cff224171db108ca7600/blob filter=lfs diff=lfs merge=lfs -text
578
+ shared/package-files/75/751945c08fd2c7ac7b49d0be092622eafa5ac58e60d92f99a59b4f8bdc307c33/blob filter=lfs diff=lfs merge=lfs -text
579
+ shared/package-files/75/759a552a2ef7efc110201509d3693a34f7055169e41fa28891aeb663336ede38/blob filter=lfs diff=lfs merge=lfs -text
580
+ shared/package-files/75/75e8d14d1843091a6a1952efb4c03b088095d2ade1ea6db7f8105701f306e424/blob filter=lfs diff=lfs merge=lfs -text
581
+ shared/package-files/75/75f9c2b09cbeb44939fe0ef0bf12aeb0143cd656f75e150627f979909589c6da/blob filter=lfs diff=lfs merge=lfs -text
582
+ shared/package-files/76/76a1c1c820477c5eab8f7d4c3504be8f2266a444c5e3b7bb050cd18d25b52d98/blob filter=lfs diff=lfs merge=lfs -text
583
+ shared/package-files/77/771baa4e2d41cbfb53d6e4f1cff3974b97e11bdad3f067eff43afe4b1f201469/blob filter=lfs diff=lfs merge=lfs -text
584
+ shared/package-files/77/77494c45d9a5437d3d4e1ddaf782ea955ff8dc12777a964f61ca0b08f7d62edf/blob filter=lfs diff=lfs merge=lfs -text
585
+ shared/package-files/77/7772e1b01ca6bc9bef27435aa768bd090aeb51c6eee183081721a914ca4b02e5/blob filter=lfs diff=lfs merge=lfs -text
586
+ shared/package-files/77/77a17fc6bf0f558cd4e2a31c9e8bf19ce6f00b928e647c9da5f0478c67f89dc5/blob filter=lfs diff=lfs merge=lfs -text
587
+ shared/package-files/78/784965b9a19f5fd63aae3136a143878d8ffce04d5b2815e08aca379dcd9f59c8/blob filter=lfs diff=lfs merge=lfs -text
588
+ shared/package-files/78/785c212f079c6f7bdff9b4ee1bda32c651da9e459bbf4de075a403f24191027a/blob filter=lfs diff=lfs merge=lfs -text
589
+ shared/package-files/78/786f29b88771e439187dd2e86ad4d255dd185e0c1ea3f8c37d21770fd1df253a/blob filter=lfs diff=lfs merge=lfs -text
590
+ shared/package-files/78/78c9747bc2db92f47ee2775ee64ba4cd7c8d6875c04132782201f543c355ad90/blob filter=lfs diff=lfs merge=lfs -text
591
+ shared/package-files/78/78cce4f3057535eeba51cfb543a88add149d42729036c36fd07e04065aeac9c6/blob filter=lfs diff=lfs merge=lfs -text
592
+ shared/package-files/78/78e0f83db78dcf4ea14887e915a408af08d9d9a351f2542f29a5d222b9284efe/blob filter=lfs diff=lfs merge=lfs -text
593
+ shared/package-files/78/78eea04a7cf86787b8612187b4b17d96d27ab0ba91d08c17a96274ec7a5fc37e/blob filter=lfs diff=lfs merge=lfs -text
594
+ shared/package-files/79/7903c2ea80bd412cc0d6701c38f645063a2f77a502cb7b1c5d9ee9d6ef38e4df/blob filter=lfs diff=lfs merge=lfs -text
595
+ shared/package-files/79/7950309e6824e0e2df93ddcfdf7222ef6c6f4d125a8a6fb548e852ddb4ce2723/blob filter=lfs diff=lfs merge=lfs -text
596
+ shared/package-files/79/7967dcd2f6620ec18ccf458d87780b19c54f2090bd72ea1d32164b8371483666/blob filter=lfs diff=lfs merge=lfs -text
597
+ shared/package-files/79/79881ac42d4a6d3b732d50014e2e6866cee437387bb5177bbf47e7d4e336ea35/blob filter=lfs diff=lfs merge=lfs -text
598
+ shared/package-files/79/79a56868a10be9477478422598c81e6a7ab62003adffe1ff07674bf655a08bd2/blob filter=lfs diff=lfs merge=lfs -text
599
+ shared/package-files/79/79ab3b3a83c989c9d106b98ecf98acb0f6f254535ca75ac54c298f56b55672c1/blob filter=lfs diff=lfs merge=lfs -text
600
+ shared/package-files/79/79ac63ae025a874200da2cb0523344e88fe7b984bace79b7dce55fdbe688d5fa/blob filter=lfs diff=lfs merge=lfs -text
601
+ shared/package-files/79/79e2b33fec758c92063be4422c83fe56ce565389c26c2111defe0815ee2dd254/blob filter=lfs diff=lfs merge=lfs -text
602
+ shared/package-files/7a/7a20c7231ab9446379bf4a8abab27edcc2155734357d4d88e7861c15d9693c01/blob filter=lfs diff=lfs merge=lfs -text
603
+ shared/package-files/7a/7a7c6052968247f06e135e7a59ea2a89823b59fc41215a371f5269af5668f746/blob filter=lfs diff=lfs merge=lfs -text
604
+ shared/package-files/7a/7ad6709bd4713ec24e958368560e08f7ea6bb312967834a9d6f52641d7b4979b/blob filter=lfs diff=lfs merge=lfs -text
605
+ shared/package-files/7b/7b2d3852e9d9a74b13cfd852b138456368a3533ad9711a82e99d2a4454af30a2/blob filter=lfs diff=lfs merge=lfs -text
606
+ shared/package-files/7b/7bccf225b12b5d9679f77ec191715f9d547a985eeed0c6287867b9ad1957b292/blob filter=lfs diff=lfs merge=lfs -text
607
+ shared/package-files/7c/7c0f114b23205230865dbb7c51a67c17cca2566119ff2c9ad0a7c687e03319bb/blob filter=lfs diff=lfs merge=lfs -text
608
+ shared/package-files/7c/7c1459904e57697fddd21e7fa2f52cb9a157eca6609afc58efde3a4614b47517/blob filter=lfs diff=lfs merge=lfs -text
609
+ shared/package-files/7c/7c3d5a1bd3cf76695ccc50d4a89c7b9ef7e881fb0cf87fa9c91a6750cea7f973/blob filter=lfs diff=lfs merge=lfs -text
shared/package-files/74/74cb5a1b5d641a526b8092601961036590269cefc77d3dcbe17f2923bd8b2c56/blob ADDED
Binary file (618 Bytes). View file
 
shared/package-files/74/74d0eaa56b246fa61ee453baacdbeae21f74fb5f5f0dcbd7f482d0e2a99002c3/blob ADDED
@@ -0,0 +1,2390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ """
4
+ Utility function to facilitate testing.
5
+
6
+ """
7
+ import contextlib
8
+ import gc
9
+ import operator
10
+ import os
11
+ import platform
12
+ import pprint
13
+ import re
14
+ import shutil
15
+ import sys
16
+ import warnings
17
+ from functools import wraps
18
+ from io import StringIO
19
+ from tempfile import mkdtemp, mkstemp
20
+ from warnings import WarningMessage
21
+
22
+ import torch._numpy as np
23
+ from torch._numpy import arange, asarray as asanyarray, empty, float32, intp, ndarray
24
+
25
+ __all__ = [
26
+ "assert_equal",
27
+ "assert_almost_equal",
28
+ "assert_approx_equal",
29
+ "assert_array_equal",
30
+ "assert_array_less",
31
+ "assert_string_equal",
32
+ "assert_",
33
+ "assert_array_almost_equal",
34
+ "build_err_msg",
35
+ "decorate_methods",
36
+ "print_assert_equal",
37
+ "verbose",
38
+ "assert_",
39
+ "assert_array_almost_equal_nulp",
40
+ "assert_raises_regex",
41
+ "assert_array_max_ulp",
42
+ "assert_warns",
43
+ "assert_no_warnings",
44
+ "assert_allclose",
45
+ "IgnoreException",
46
+ "clear_and_catch_warnings",
47
+ "temppath",
48
+ "tempdir",
49
+ "IS_PYPY",
50
+ "HAS_REFCOUNT",
51
+ "IS_WASM",
52
+ "suppress_warnings",
53
+ "assert_array_compare",
54
+ "assert_no_gc_cycles",
55
+ "break_cycles",
56
+ "IS_PYSTON",
57
+ ]
58
+
59
+
60
+ verbose = 0
61
+
62
+ IS_WASM = platform.machine() in ["wasm32", "wasm64"]
63
+ IS_PYPY = sys.implementation.name == "pypy"
64
+ IS_PYSTON = hasattr(sys, "pyston_version_info")
65
+ HAS_REFCOUNT = getattr(sys, "getrefcount", None) is not None and not IS_PYSTON
66
+
67
+
68
+ def assert_(val, msg=""):
69
+ """
70
+ Assert that works in release mode.
71
+ Accepts callable msg to allow deferring evaluation until failure.
72
+
73
+ The Python built-in ``assert`` does not work when executing code in
74
+ optimized mode (the ``-O`` flag) - no byte-code is generated for it.
75
+
76
+ For documentation on usage, refer to the Python documentation.
77
+
78
+ """
79
+ __tracebackhide__ = True # Hide traceback for py.test
80
+ if not val:
81
+ try:
82
+ smsg = msg()
83
+ except TypeError:
84
+ smsg = msg
85
+ raise AssertionError(smsg)
86
+
87
+
88
+ def gisnan(x):
89
+ return np.isnan(x)
90
+
91
+
92
+ def gisfinite(x):
93
+ return np.isfinite(x)
94
+
95
+
96
+ def gisinf(x):
97
+ return np.isinf(x)
98
+
99
+
100
+ def build_err_msg(
101
+ arrays,
102
+ err_msg,
103
+ header="Items are not equal:",
104
+ verbose=True,
105
+ names=("ACTUAL", "DESIRED"),
106
+ precision=8,
107
+ ):
108
+ msg = ["\n" + header]
109
+ if err_msg:
110
+ if err_msg.find("\n") == -1 and len(err_msg) < 79 - len(header):
111
+ msg = [msg[0] + " " + err_msg]
112
+ else:
113
+ msg.append(err_msg)
114
+ if verbose:
115
+ for i, a in enumerate(arrays):
116
+ if isinstance(a, ndarray):
117
+ # precision argument is only needed if the objects are ndarrays
118
+ # r_func = partial(array_repr, precision=precision)
119
+ r_func = ndarray.__repr__
120
+ else:
121
+ r_func = repr
122
+
123
+ try:
124
+ r = r_func(a)
125
+ except Exception as exc:
126
+ r = f"[repr failed for <{type(a).__name__}>: {exc}]"
127
+ if r.count("\n") > 3:
128
+ r = "\n".join(r.splitlines()[:3])
129
+ r += "..."
130
+ msg.append(f" {names[i]}: {r}")
131
+ return "\n".join(msg)
132
+
133
+
134
+ def assert_equal(actual, desired, err_msg="", verbose=True):
135
+ """
136
+ Raises an AssertionError if two objects are not equal.
137
+
138
+ Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
139
+ check that all elements of these objects are equal. An exception is raised
140
+ at the first conflicting values.
141
+
142
+ When one of `actual` and `desired` is a scalar and the other is array_like,
143
+ the function checks that each element of the array_like object is equal to
144
+ the scalar.
145
+
146
+ This function handles NaN comparisons as if NaN was a "normal" number.
147
+ That is, AssertionError is not raised if both objects have NaNs in the same
148
+ positions. This is in contrast to the IEEE standard on NaNs, which says
149
+ that NaN compared to anything must return False.
150
+
151
+ Parameters
152
+ ----------
153
+ actual : array_like
154
+ The object to check.
155
+ desired : array_like
156
+ The expected object.
157
+ err_msg : str, optional
158
+ The error message to be printed in case of failure.
159
+ verbose : bool, optional
160
+ If True, the conflicting values are appended to the error message.
161
+
162
+ Raises
163
+ ------
164
+ AssertionError
165
+ If actual and desired are not equal.
166
+
167
+ Examples
168
+ --------
169
+ >>> np.testing.assert_equal([4,5], [4,6])
170
+ Traceback (most recent call last):
171
+ ...
172
+ AssertionError:
173
+ Items are not equal:
174
+ item=1
175
+ ACTUAL: 5
176
+ DESIRED: 6
177
+
178
+ The following comparison does not raise an exception. There are NaNs
179
+ in the inputs, but they are in the same positions.
180
+
181
+ >>> np.testing.assert_equal(np.array([1.0, 2.0, np.nan]), [1, 2, np.nan])
182
+
183
+ """
184
+ __tracebackhide__ = True # Hide traceback for py.test
185
+
186
+ num_nones = sum([actual is None, desired is None])
187
+ if num_nones == 1:
188
+ raise AssertionError(f"Not equal: {actual} != {desired}")
189
+ elif num_nones == 2:
190
+ return True
191
+ # else, carry on
192
+
193
+ if isinstance(actual, np.DType) or isinstance(desired, np.DType):
194
+ result = actual == desired
195
+ if not result:
196
+ raise AssertionError(f"Not equal: {actual} != {desired}")
197
+ else:
198
+ return True
199
+
200
+ if isinstance(desired, str) and isinstance(actual, str):
201
+ assert actual == desired
202
+ return
203
+
204
+ if isinstance(desired, dict):
205
+ if not isinstance(actual, dict):
206
+ raise AssertionError(repr(type(actual)))
207
+ assert_equal(len(actual), len(desired), err_msg, verbose)
208
+ for k in desired.keys():
209
+ if k not in actual:
210
+ raise AssertionError(repr(k))
211
+ assert_equal(actual[k], desired[k], f"key={k!r}\n{err_msg}", verbose)
212
+ return
213
+ if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
214
+ assert_equal(len(actual), len(desired), err_msg, verbose)
215
+ for k in range(len(desired)):
216
+ assert_equal(actual[k], desired[k], f"item={k!r}\n{err_msg}", verbose)
217
+ return
218
+
219
+ from torch._numpy import imag, iscomplexobj, isscalar, ndarray, real, signbit
220
+
221
+ if isinstance(actual, ndarray) or isinstance(desired, ndarray):
222
+ return assert_array_equal(actual, desired, err_msg, verbose)
223
+ msg = build_err_msg([actual, desired], err_msg, verbose=verbose)
224
+
225
+ # Handle complex numbers: separate into real/imag to handle
226
+ # nan/inf/negative zero correctly
227
+ # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
228
+ try:
229
+ usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
230
+ except (ValueError, TypeError):
231
+ usecomplex = False
232
+
233
+ if usecomplex:
234
+ if iscomplexobj(actual):
235
+ actualr = real(actual)
236
+ actuali = imag(actual)
237
+ else:
238
+ actualr = actual
239
+ actuali = 0
240
+ if iscomplexobj(desired):
241
+ desiredr = real(desired)
242
+ desiredi = imag(desired)
243
+ else:
244
+ desiredr = desired
245
+ desiredi = 0
246
+ try:
247
+ assert_equal(actualr, desiredr)
248
+ assert_equal(actuali, desiredi)
249
+ except AssertionError:
250
+ raise AssertionError(msg) # noqa: TRY200
251
+
252
+ # isscalar test to check cases such as [np.nan] != np.nan
253
+ if isscalar(desired) != isscalar(actual):
254
+ raise AssertionError(msg)
255
+
256
+ # Inf/nan/negative zero handling
257
+ try:
258
+ isdesnan = gisnan(desired)
259
+ isactnan = gisnan(actual)
260
+ if isdesnan and isactnan:
261
+ return # both nan, so equal
262
+
263
+ # handle signed zero specially for floats
264
+ array_actual = np.asarray(actual)
265
+ array_desired = np.asarray(desired)
266
+
267
+ if desired == 0 and actual == 0:
268
+ if not signbit(desired) == signbit(actual):
269
+ raise AssertionError(msg)
270
+
271
+ except (TypeError, ValueError, NotImplementedError):
272
+ pass
273
+
274
+ try:
275
+ # Explicitly use __eq__ for comparison, gh-2552
276
+ if not (desired == actual):
277
+ raise AssertionError(msg)
278
+
279
+ except (DeprecationWarning, FutureWarning) as e:
280
+ # this handles the case when the two types are not even comparable
281
+ if "elementwise == comparison" in e.args[0]:
282
+ raise AssertionError(msg) # noqa: TRY200
283
+ else:
284
+ raise
285
+
286
+
287
+ def print_assert_equal(test_string, actual, desired):
288
+ """
289
+ Test if two objects are equal, and print an error message if test fails.
290
+
291
+ The test is performed with ``actual == desired``.
292
+
293
+ Parameters
294
+ ----------
295
+ test_string : str
296
+ The message supplied to AssertionError.
297
+ actual : object
298
+ The object to test for equality against `desired`.
299
+ desired : object
300
+ The expected result.
301
+
302
+ Examples
303
+ --------
304
+ >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 1]) # doctest: +SKIP
305
+ >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2]) # doctest: +SKIP
306
+ Traceback (most recent call last):
307
+ ...
308
+ AssertionError: Test XYZ of func xyz failed
309
+ ACTUAL:
310
+ [0, 1]
311
+ DESIRED:
312
+ [0, 2]
313
+
314
+ """
315
+ __tracebackhide__ = True # Hide traceback for py.test
316
+ import pprint
317
+
318
+ if not (actual == desired):
319
+ msg = StringIO()
320
+ msg.write(test_string)
321
+ msg.write(" failed\nACTUAL: \n")
322
+ pprint.pprint(actual, msg)
323
+ msg.write("DESIRED: \n")
324
+ pprint.pprint(desired, msg)
325
+ raise AssertionError(msg.getvalue())
326
+
327
+
328
+ def assert_almost_equal(actual, desired, decimal=7, err_msg="", verbose=True):
329
+ """
330
+ Raises an AssertionError if two items are not equal up to desired
331
+ precision.
332
+
333
+ .. note:: It is recommended to use one of `assert_allclose`,
334
+ `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
335
+ instead of this function for more consistent floating point
336
+ comparisons.
337
+
338
+ The test verifies that the elements of `actual` and `desired` satisfy.
339
+
340
+ ``abs(desired-actual) < float64(1.5 * 10**(-decimal))``
341
+
342
+ That is a looser test than originally documented, but agrees with what the
343
+ actual implementation in `assert_array_almost_equal` did up to rounding
344
+ vagaries. An exception is raised at conflicting values. For ndarrays this
345
+ delegates to assert_array_almost_equal
346
+
347
+ Parameters
348
+ ----------
349
+ actual : array_like
350
+ The object to check.
351
+ desired : array_like
352
+ The expected object.
353
+ decimal : int, optional
354
+ Desired precision, default is 7.
355
+ err_msg : str, optional
356
+ The error message to be printed in case of failure.
357
+ verbose : bool, optional
358
+ If True, the conflicting values are appended to the error message.
359
+
360
+ Raises
361
+ ------
362
+ AssertionError
363
+ If actual and desired are not equal up to specified precision.
364
+
365
+ See Also
366
+ --------
367
+ assert_allclose: Compare two array_like objects for equality with desired
368
+ relative and/or absolute precision.
369
+ assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
370
+
371
+ Examples
372
+ --------
373
+ >>> from torch._numpy.testing import assert_almost_equal
374
+ >>> assert_almost_equal(2.3333333333333, 2.33333334)
375
+ >>> assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
376
+ Traceback (most recent call last):
377
+ ...
378
+ AssertionError:
379
+ Arrays are not almost equal to 10 decimals
380
+ ACTUAL: 2.3333333333333
381
+ DESIRED: 2.33333334
382
+
383
+ >>> assert_almost_equal(np.array([1.0,2.3333333333333]),
384
+ ... np.array([1.0,2.33333334]), decimal=9)
385
+ Traceback (most recent call last):
386
+ ...
387
+ AssertionError:
388
+ Arrays are not almost equal to 9 decimals
389
+ <BLANKLINE>
390
+ Mismatched elements: 1 / 2 (50%)
391
+ Max absolute difference: 6.666699636781459e-09
392
+ Max relative difference: 2.8571569790287484e-09
393
+ x: torch.ndarray([1.0000, 2.3333], dtype=float64)
394
+ y: torch.ndarray([1.0000, 2.3333], dtype=float64)
395
+
396
+ """
397
+ __tracebackhide__ = True # Hide traceback for py.test
398
+ from torch._numpy import imag, iscomplexobj, ndarray, real
399
+
400
+ # Handle complex numbers: separate into real/imag to handle
401
+ # nan/inf/negative zero correctly
402
+ # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
403
+ try:
404
+ usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
405
+ except ValueError:
406
+ usecomplex = False
407
+
408
+ def _build_err_msg():
409
+ header = "Arrays are not almost equal to %d decimals" % decimal
410
+ return build_err_msg([actual, desired], err_msg, verbose=verbose, header=header)
411
+
412
+ if usecomplex:
413
+ if iscomplexobj(actual):
414
+ actualr = real(actual)
415
+ actuali = imag(actual)
416
+ else:
417
+ actualr = actual
418
+ actuali = 0
419
+ if iscomplexobj(desired):
420
+ desiredr = real(desired)
421
+ desiredi = imag(desired)
422
+ else:
423
+ desiredr = desired
424
+ desiredi = 0
425
+ try:
426
+ assert_almost_equal(actualr, desiredr, decimal=decimal)
427
+ assert_almost_equal(actuali, desiredi, decimal=decimal)
428
+ except AssertionError:
429
+ raise AssertionError(_build_err_msg()) # noqa: TRY200
430
+
431
+ if isinstance(actual, (ndarray, tuple, list)) or isinstance(
432
+ desired, (ndarray, tuple, list)
433
+ ):
434
+ return assert_array_almost_equal(actual, desired, decimal, err_msg)
435
+ try:
436
+ # If one of desired/actual is not finite, handle it specially here:
437
+ # check that both are nan if any is a nan, and test for equality
438
+ # otherwise
439
+ if not (gisfinite(desired) and gisfinite(actual)):
440
+ if gisnan(desired) or gisnan(actual):
441
+ if not (gisnan(desired) and gisnan(actual)):
442
+ raise AssertionError(_build_err_msg())
443
+ else:
444
+ if not desired == actual:
445
+ raise AssertionError(_build_err_msg())
446
+ return
447
+ except (NotImplementedError, TypeError):
448
+ pass
449
+ if abs(desired - actual) >= np.float64(1.5 * 10.0 ** (-decimal)):
450
+ raise AssertionError(_build_err_msg())
451
+
452
+
453
+ def assert_approx_equal(actual, desired, significant=7, err_msg="", verbose=True):
454
+ """
455
+ Raises an AssertionError if two items are not equal up to significant
456
+ digits.
457
+
458
+ .. note:: It is recommended to use one of `assert_allclose`,
459
+ `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
460
+ instead of this function for more consistent floating point
461
+ comparisons.
462
+
463
+ Given two numbers, check that they are approximately equal.
464
+ Approximately equal is defined as the number of significant digits
465
+ that agree.
466
+
467
+ Parameters
468
+ ----------
469
+ actual : scalar
470
+ The object to check.
471
+ desired : scalar
472
+ The expected object.
473
+ significant : int, optional
474
+ Desired precision, default is 7.
475
+ err_msg : str, optional
476
+ The error message to be printed in case of failure.
477
+ verbose : bool, optional
478
+ If True, the conflicting values are appended to the error message.
479
+
480
+ Raises
481
+ ------
482
+ AssertionError
483
+ If actual and desired are not equal up to specified precision.
484
+
485
+ See Also
486
+ --------
487
+ assert_allclose: Compare two array_like objects for equality with desired
488
+ relative and/or absolute precision.
489
+ assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
490
+
491
+ Examples
492
+ --------
493
+ >>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20) # doctest: +SKIP
494
+ >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20, # doctest: +SKIP
495
+ ... significant=8)
496
+ >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20, # doctest: +SKIP
497
+ ... significant=8)
498
+ Traceback (most recent call last):
499
+ ...
500
+ AssertionError:
501
+ Items are not equal to 8 significant digits:
502
+ ACTUAL: 1.234567e-21
503
+ DESIRED: 1.2345672e-21
504
+
505
+ the evaluated condition that raises the exception is
506
+
507
+ >>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1)
508
+ True
509
+
510
+ """
511
+ __tracebackhide__ = True # Hide traceback for py.test
512
+ import numpy as np
513
+
514
+ (actual, desired) = map(float, (actual, desired))
515
+ if desired == actual:
516
+ return
517
+ # Normalized the numbers to be in range (-10.0,10.0)
518
+ # scale = float(pow(10,math.floor(math.log10(0.5*(abs(desired)+abs(actual))))))
519
+ scale = 0.5 * (np.abs(desired) + np.abs(actual))
520
+ scale = np.power(10, np.floor(np.log10(scale)))
521
+ try:
522
+ sc_desired = desired / scale
523
+ except ZeroDivisionError:
524
+ sc_desired = 0.0
525
+ try:
526
+ sc_actual = actual / scale
527
+ except ZeroDivisionError:
528
+ sc_actual = 0.0
529
+ msg = build_err_msg(
530
+ [actual, desired],
531
+ err_msg,
532
+ header="Items are not equal to %d significant digits:" % significant,
533
+ verbose=verbose,
534
+ )
535
+ try:
536
+ # If one of desired/actual is not finite, handle it specially here:
537
+ # check that both are nan if any is a nan, and test for equality
538
+ # otherwise
539
+ if not (gisfinite(desired) and gisfinite(actual)):
540
+ if gisnan(desired) or gisnan(actual):
541
+ if not (gisnan(desired) and gisnan(actual)):
542
+ raise AssertionError(msg)
543
+ else:
544
+ if not desired == actual:
545
+ raise AssertionError(msg)
546
+ return
547
+ except (TypeError, NotImplementedError):
548
+ pass
549
+ if np.abs(sc_desired - sc_actual) >= np.power(10.0, -(significant - 1)):
550
+ raise AssertionError(msg)
551
+
552
+
553
+ def assert_array_compare(
554
+ comparison,
555
+ x,
556
+ y,
557
+ err_msg="",
558
+ verbose=True,
559
+ header="",
560
+ precision=6,
561
+ equal_nan=True,
562
+ equal_inf=True,
563
+ *,
564
+ strict=False,
565
+ ):
566
+ __tracebackhide__ = True # Hide traceback for py.test
567
+ from torch._numpy import all, array, asarray, bool_, inf, isnan, max
568
+
569
+ x = asarray(x)
570
+ y = asarray(y)
571
+
572
+ def array2string(a):
573
+ return str(a)
574
+
575
+ # original array for output formatting
576
+ ox, oy = x, y
577
+
578
+ def func_assert_same_pos(x, y, func=isnan, hasval="nan"):
579
+ """Handling nan/inf.
580
+
581
+ Combine results of running func on x and y, checking that they are True
582
+ at the same locations.
583
+
584
+ """
585
+ __tracebackhide__ = True # Hide traceback for py.test
586
+ x_id = func(x)
587
+ y_id = func(y)
588
+ # We include work-arounds here to handle three types of slightly
589
+ # pathological ndarray subclasses:
590
+ # (1) all() on `masked` array scalars can return masked arrays, so we
591
+ # use != True
592
+ # (2) __eq__ on some ndarray subclasses returns Python booleans
593
+ # instead of element-wise comparisons, so we cast to bool_() and
594
+ # use isinstance(..., bool) checks
595
+ # (3) subclasses with bare-bones __array_function__ implementations may
596
+ # not implement np.all(), so favor using the .all() method
597
+ # We are not committed to supporting such subclasses, but it's nice to
598
+ # support them if possible.
599
+ if (x_id == y_id).all().item() is not True:
600
+ msg = build_err_msg(
601
+ [x, y],
602
+ err_msg + "\nx and y %s location mismatch:" % (hasval),
603
+ verbose=verbose,
604
+ header=header,
605
+ names=("x", "y"),
606
+ precision=precision,
607
+ )
608
+ raise AssertionError(msg)
609
+ # If there is a scalar, then here we know the array has the same
610
+ # flag as it everywhere, so we should return the scalar flag.
611
+ if isinstance(x_id, bool) or x_id.ndim == 0:
612
+ return bool_(x_id)
613
+ elif isinstance(y_id, bool) or y_id.ndim == 0:
614
+ return bool_(y_id)
615
+ else:
616
+ return y_id
617
+
618
+ try:
619
+ if strict:
620
+ cond = x.shape == y.shape and x.dtype == y.dtype
621
+ else:
622
+ cond = (x.shape == () or y.shape == ()) or x.shape == y.shape
623
+ if not cond:
624
+ if x.shape != y.shape:
625
+ reason = f"\n(shapes {x.shape}, {y.shape} mismatch)"
626
+ else:
627
+ reason = f"\n(dtypes {x.dtype}, {y.dtype} mismatch)"
628
+ msg = build_err_msg(
629
+ [x, y],
630
+ err_msg + reason,
631
+ verbose=verbose,
632
+ header=header,
633
+ names=("x", "y"),
634
+ precision=precision,
635
+ )
636
+ raise AssertionError(msg)
637
+
638
+ flagged = bool_(False)
639
+
640
+ if equal_nan:
641
+ flagged = func_assert_same_pos(x, y, func=isnan, hasval="nan")
642
+
643
+ if equal_inf:
644
+ flagged |= func_assert_same_pos(
645
+ x, y, func=lambda xy: xy == +inf, hasval="+inf"
646
+ )
647
+ flagged |= func_assert_same_pos(
648
+ x, y, func=lambda xy: xy == -inf, hasval="-inf"
649
+ )
650
+
651
+ if flagged.ndim > 0:
652
+ x, y = x[~flagged], y[~flagged]
653
+ # Only do the comparison if actual values are left
654
+ if x.size == 0:
655
+ return
656
+ elif flagged:
657
+ # no sense doing comparison if everything is flagged.
658
+ return
659
+
660
+ val = comparison(x, y)
661
+
662
+ if isinstance(val, bool):
663
+ cond = val
664
+ reduced = array([val])
665
+ else:
666
+ reduced = val.ravel()
667
+ cond = reduced.all()
668
+
669
+ # The below comparison is a hack to ensure that fully masked
670
+ # results, for which val.ravel().all() returns np.ma.masked,
671
+ # do not trigger a failure (np.ma.masked != True evaluates as
672
+ # np.ma.masked, which is falsy).
673
+ if not cond:
674
+ n_mismatch = reduced.size - int(reduced.sum(dtype=intp))
675
+ n_elements = flagged.size if flagged.ndim != 0 else reduced.size
676
+ percent_mismatch = 100 * n_mismatch / n_elements
677
+ remarks = [
678
+ f"Mismatched elements: {n_mismatch} / {n_elements} ({percent_mismatch:.3g}%)"
679
+ ]
680
+
681
+ # with errstate(all='ignore'):
682
+ # ignore errors for non-numeric types
683
+ with contextlib.suppress(TypeError, RuntimeError):
684
+ error = abs(x - y)
685
+ if np.issubdtype(x.dtype, np.unsignedinteger):
686
+ error2 = abs(y - x)
687
+ np.minimum(error, error2, out=error)
688
+ max_abs_error = max(error)
689
+ remarks.append(
690
+ "Max absolute difference: " + array2string(max_abs_error.item())
691
+ )
692
+
693
+ # note: this definition of relative error matches that one
694
+ # used by assert_allclose (found in np.isclose)
695
+ # Filter values where the divisor would be zero
696
+ nonzero = bool_(y != 0)
697
+ if all(~nonzero):
698
+ max_rel_error = array(inf)
699
+ else:
700
+ max_rel_error = max(error[nonzero] / abs(y[nonzero]))
701
+ remarks.append(
702
+ "Max relative difference: " + array2string(max_rel_error.item())
703
+ )
704
+
705
+ err_msg += "\n" + "\n".join(remarks)
706
+ msg = build_err_msg(
707
+ [ox, oy],
708
+ err_msg,
709
+ verbose=verbose,
710
+ header=header,
711
+ names=("x", "y"),
712
+ precision=precision,
713
+ )
714
+ raise AssertionError(msg)
715
+ except ValueError:
716
+ import traceback
717
+
718
+ efmt = traceback.format_exc()
719
+ header = f"error during assertion:\n\n{efmt}\n\n{header}"
720
+
721
+ msg = build_err_msg(
722
+ [x, y],
723
+ err_msg,
724
+ verbose=verbose,
725
+ header=header,
726
+ names=("x", "y"),
727
+ precision=precision,
728
+ )
729
+ raise ValueError(msg) # noqa: TRY200
730
+
731
+
732
+ def assert_array_equal(x, y, err_msg="", verbose=True, *, strict=False):
733
+ """
734
+ Raises an AssertionError if two array_like objects are not equal.
735
+
736
+ Given two array_like objects, check that the shape is equal and all
737
+ elements of these objects are equal (but see the Notes for the special
738
+ handling of a scalar). An exception is raised at shape mismatch or
739
+ conflicting values. In contrast to the standard usage in numpy, NaNs
740
+ are compared like numbers, no assertion is raised if both objects have
741
+ NaNs in the same positions.
742
+
743
+ The usual caution for verifying equality with floating point numbers is
744
+ advised.
745
+
746
+ Parameters
747
+ ----------
748
+ x : array_like
749
+ The actual object to check.
750
+ y : array_like
751
+ The desired, expected object.
752
+ err_msg : str, optional
753
+ The error message to be printed in case of failure.
754
+ verbose : bool, optional
755
+ If True, the conflicting values are appended to the error message.
756
+ strict : bool, optional
757
+ If True, raise an AssertionError when either the shape or the data
758
+ type of the array_like objects does not match. The special
759
+ handling for scalars mentioned in the Notes section is disabled.
760
+
761
+ Raises
762
+ ------
763
+ AssertionError
764
+ If actual and desired objects are not equal.
765
+
766
+ See Also
767
+ --------
768
+ assert_allclose: Compare two array_like objects for equality with desired
769
+ relative and/or absolute precision.
770
+ assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
771
+
772
+ Notes
773
+ -----
774
+ When one of `x` and `y` is a scalar and the other is array_like, the
775
+ function checks that each element of the array_like object is equal to
776
+ the scalar. This behaviour can be disabled with the `strict` parameter.
777
+
778
+ Examples
779
+ --------
780
+ The first assert does not raise an exception:
781
+
782
+ >>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
783
+ ... [np.exp(0),2.33333, np.nan])
784
+
785
+ Use `assert_allclose` or one of the nulp (number of floating point values)
786
+ functions for these cases instead:
787
+
788
+ >>> np.testing.assert_allclose([1.0,np.pi,np.nan],
789
+ ... [1, np.sqrt(np.pi)**2, np.nan],
790
+ ... rtol=1e-10, atol=0)
791
+
792
+ As mentioned in the Notes section, `assert_array_equal` has special
793
+ handling for scalars. Here the test checks that each value in `x` is 3:
794
+
795
+ >>> x = np.full((2, 5), fill_value=3)
796
+ >>> np.testing.assert_array_equal(x, 3)
797
+
798
+ Use `strict` to raise an AssertionError when comparing a scalar with an
799
+ array:
800
+
801
+ >>> np.testing.assert_array_equal(x, 3, strict=True)
802
+ Traceback (most recent call last):
803
+ ...
804
+ AssertionError:
805
+ Arrays are not equal
806
+ <BLANKLINE>
807
+ (shapes (2, 5), () mismatch)
808
+ x: torch.ndarray([[3, 3, 3, 3, 3],
809
+ [3, 3, 3, 3, 3]])
810
+ y: torch.ndarray(3)
811
+
812
+ The `strict` parameter also ensures that the array data types match:
813
+
814
+ >>> x = np.array([2, 2, 2])
815
+ >>> y = np.array([2., 2., 2.], dtype=np.float32)
816
+ >>> np.testing.assert_array_equal(x, y, strict=True)
817
+ Traceback (most recent call last):
818
+ ...
819
+ AssertionError:
820
+ Arrays are not equal
821
+ <BLANKLINE>
822
+ (dtypes dtype("int64"), dtype("float32") mismatch)
823
+ x: torch.ndarray([2, 2, 2])
824
+ y: torch.ndarray([2., 2., 2.])
825
+ """
826
+ __tracebackhide__ = True # Hide traceback for py.test
827
+ assert_array_compare(
828
+ operator.__eq__,
829
+ x,
830
+ y,
831
+ err_msg=err_msg,
832
+ verbose=verbose,
833
+ header="Arrays are not equal",
834
+ strict=strict,
835
+ )
836
+
837
+
838
+ def assert_array_almost_equal(x, y, decimal=6, err_msg="", verbose=True):
839
+ """
840
+ Raises an AssertionError if two objects are not equal up to desired
841
+ precision.
842
+
843
+ .. note:: It is recommended to use one of `assert_allclose`,
844
+ `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
845
+ instead of this function for more consistent floating point
846
+ comparisons.
847
+
848
+ The test verifies identical shapes and that the elements of ``actual`` and
849
+ ``desired`` satisfy.
850
+
851
+ ``abs(desired-actual) < 1.5 * 10**(-decimal)``
852
+
853
+ That is a looser test than originally documented, but agrees with what the
854
+ actual implementation did up to rounding vagaries. An exception is raised
855
+ at shape mismatch or conflicting values. In contrast to the standard usage
856
+ in numpy, NaNs are compared like numbers, no assertion is raised if both
857
+ objects have NaNs in the same positions.
858
+
859
+ Parameters
860
+ ----------
861
+ x : array_like
862
+ The actual object to check.
863
+ y : array_like
864
+ The desired, expected object.
865
+ decimal : int, optional
866
+ Desired precision, default is 6.
867
+ err_msg : str, optional
868
+ The error message to be printed in case of failure.
869
+ verbose : bool, optional
870
+ If True, the conflicting values are appended to the error message.
871
+
872
+ Raises
873
+ ------
874
+ AssertionError
875
+ If actual and desired are not equal up to specified precision.
876
+
877
+ See Also
878
+ --------
879
+ assert_allclose: Compare two array_like objects for equality with desired
880
+ relative and/or absolute precision.
881
+ assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
882
+
883
+ Examples
884
+ --------
885
+ the first assert does not raise an exception
886
+
887
+ >>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan],
888
+ ... [1.0,2.333,np.nan])
889
+
890
+ >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
891
+ ... [1.0,2.33339,np.nan], decimal=5)
892
+ Traceback (most recent call last):
893
+ ...
894
+ AssertionError:
895
+ Arrays are not almost equal to 5 decimals
896
+ <BLANKLINE>
897
+ Mismatched elements: 1 / 3 (33.3%)
898
+ Max absolute difference: 5.999999999994898e-05
899
+ Max relative difference: 2.5713661239633743e-05
900
+ x: torch.ndarray([1.0000, 2.3333, nan], dtype=float64)
901
+ y: torch.ndarray([1.0000, 2.3334, nan], dtype=float64)
902
+
903
+ >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
904
+ ... [1.0,2.33333, 5], decimal=5)
905
+ Traceback (most recent call last):
906
+ ...
907
+ AssertionError:
908
+ Arrays are not almost equal to 5 decimals
909
+ <BLANKLINE>
910
+ x and y nan location mismatch:
911
+ x: torch.ndarray([1.0000, 2.3333, nan], dtype=float64)
912
+ y: torch.ndarray([1.0000, 2.3333, 5.0000], dtype=float64)
913
+
914
+ """
915
+ __tracebackhide__ = True # Hide traceback for py.test
916
+ from torch._numpy import any as npany, float_, issubdtype, number, result_type
917
+
918
+ def compare(x, y):
919
+ try:
920
+ if npany(gisinf(x)) or npany(gisinf(y)):
921
+ xinfid = gisinf(x)
922
+ yinfid = gisinf(y)
923
+ if not (xinfid == yinfid).all():
924
+ return False
925
+ # if one item, x and y is +- inf
926
+ if x.size == y.size == 1:
927
+ return x == y
928
+ x = x[~xinfid]
929
+ y = y[~yinfid]
930
+ except (TypeError, NotImplementedError):
931
+ pass
932
+
933
+ # make sure y is an inexact type to avoid abs(MIN_INT); will cause
934
+ # casting of x later.
935
+ dtype = result_type(y, 1.0)
936
+ y = asanyarray(y, dtype)
937
+ z = abs(x - y)
938
+
939
+ if not issubdtype(z.dtype, number):
940
+ z = z.astype(float_) # handle object arrays
941
+
942
+ return z < 1.5 * 10.0 ** (-decimal)
943
+
944
+ assert_array_compare(
945
+ compare,
946
+ x,
947
+ y,
948
+ err_msg=err_msg,
949
+ verbose=verbose,
950
+ header=("Arrays are not almost equal to %d decimals" % decimal),
951
+ precision=decimal,
952
+ )
953
+
954
+
955
+ def assert_array_less(x, y, err_msg="", verbose=True):
956
+ """
957
+ Raises an AssertionError if two array_like objects are not ordered by less
958
+ than.
959
+
960
+ Given two array_like objects, check that the shape is equal and all
961
+ elements of the first object are strictly smaller than those of the
962
+ second object. An exception is raised at shape mismatch or incorrectly
963
+ ordered values. Shape mismatch does not raise if an object has zero
964
+ dimension. In contrast to the standard usage in numpy, NaNs are
965
+ compared, no assertion is raised if both objects have NaNs in the same
966
+ positions.
967
+
968
+
969
+
970
+ Parameters
971
+ ----------
972
+ x : array_like
973
+ The smaller object to check.
974
+ y : array_like
975
+ The larger object to compare.
976
+ err_msg : string
977
+ The error message to be printed in case of failure.
978
+ verbose : bool
979
+ If True, the conflicting values are appended to the error message.
980
+
981
+ Raises
982
+ ------
983
+ AssertionError
984
+ If actual and desired objects are not equal.
985
+
986
+ See Also
987
+ --------
988
+ assert_array_equal: tests objects for equality
989
+ assert_array_almost_equal: test objects for equality up to precision
990
+
991
+
992
+
993
+ Examples
994
+ --------
995
+ >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan])
996
+ >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan])
997
+ Traceback (most recent call last):
998
+ ...
999
+ AssertionError:
1000
+ Arrays are not less-ordered
1001
+ <BLANKLINE>
1002
+ Mismatched elements: 1 / 3 (33.3%)
1003
+ Max absolute difference: 1.0
1004
+ Max relative difference: 0.5
1005
+ x: torch.ndarray([1., 1., nan], dtype=float64)
1006
+ y: torch.ndarray([1., 2., nan], dtype=float64)
1007
+
1008
+ >>> np.testing.assert_array_less([1.0, 4.0], 3)
1009
+ Traceback (most recent call last):
1010
+ ...
1011
+ AssertionError:
1012
+ Arrays are not less-ordered
1013
+ <BLANKLINE>
1014
+ Mismatched elements: 1 / 2 (50%)
1015
+ Max absolute difference: 2.0
1016
+ Max relative difference: 0.6666666666666666
1017
+ x: torch.ndarray([1., 4.], dtype=float64)
1018
+ y: torch.ndarray(3)
1019
+
1020
+ >>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4])
1021
+ Traceback (most recent call last):
1022
+ ...
1023
+ AssertionError:
1024
+ Arrays are not less-ordered
1025
+ <BLANKLINE>
1026
+ (shapes (3,), (1,) mismatch)
1027
+ x: torch.ndarray([1., 2., 3.], dtype=float64)
1028
+ y: torch.ndarray([4])
1029
+
1030
+ """
1031
+ __tracebackhide__ = True # Hide traceback for py.test
1032
+ assert_array_compare(
1033
+ operator.__lt__,
1034
+ x,
1035
+ y,
1036
+ err_msg=err_msg,
1037
+ verbose=verbose,
1038
+ header="Arrays are not less-ordered",
1039
+ equal_inf=False,
1040
+ )
1041
+
1042
+
1043
+ def assert_string_equal(actual, desired):
1044
+ """
1045
+ Test if two strings are equal.
1046
+
1047
+ If the given strings are equal, `assert_string_equal` does nothing.
1048
+ If they are not equal, an AssertionError is raised, and the diff
1049
+ between the strings is shown.
1050
+
1051
+ Parameters
1052
+ ----------
1053
+ actual : str
1054
+ The string to test for equality against the expected string.
1055
+ desired : str
1056
+ The expected string.
1057
+
1058
+ Examples
1059
+ --------
1060
+ >>> np.testing.assert_string_equal('abc', 'abc') # doctest: +SKIP
1061
+ >>> np.testing.assert_string_equal('abc', 'abcd') # doctest: +SKIP
1062
+ Traceback (most recent call last):
1063
+ File "<stdin>", line 1, in <module>
1064
+ ...
1065
+ AssertionError: Differences in strings:
1066
+ - abc+ abcd? +
1067
+
1068
+ """
1069
+ # delay import of difflib to reduce startup time
1070
+ __tracebackhide__ = True # Hide traceback for py.test
1071
+ import difflib
1072
+
1073
+ if not isinstance(actual, str):
1074
+ raise AssertionError(repr(type(actual)))
1075
+ if not isinstance(desired, str):
1076
+ raise AssertionError(repr(type(desired)))
1077
+ if desired == actual:
1078
+ return
1079
+
1080
+ diff = list(
1081
+ difflib.Differ().compare(actual.splitlines(True), desired.splitlines(True))
1082
+ )
1083
+ diff_list = []
1084
+ while diff:
1085
+ d1 = diff.pop(0)
1086
+ if d1.startswith(" "):
1087
+ continue
1088
+ if d1.startswith("- "):
1089
+ l = [d1]
1090
+ d2 = diff.pop(0)
1091
+ if d2.startswith("? "):
1092
+ l.append(d2)
1093
+ d2 = diff.pop(0)
1094
+ if not d2.startswith("+ "):
1095
+ raise AssertionError(repr(d2))
1096
+ l.append(d2)
1097
+ if diff:
1098
+ d3 = diff.pop(0)
1099
+ if d3.startswith("? "):
1100
+ l.append(d3)
1101
+ else:
1102
+ diff.insert(0, d3)
1103
+ if d2[2:] == d1[2:]:
1104
+ continue
1105
+ diff_list.extend(l)
1106
+ continue
1107
+ raise AssertionError(repr(d1))
1108
+ if not diff_list:
1109
+ return
1110
+ msg = f"Differences in strings:\n{''.join(diff_list).rstrip()}"
1111
+ if actual != desired:
1112
+ raise AssertionError(msg)
1113
+
1114
+
1115
+ import unittest
1116
+
1117
+
1118
+ class _Dummy(unittest.TestCase):
1119
+ def nop(self):
1120
+ pass
1121
+
1122
+
1123
+ _d = _Dummy("nop")
1124
+
1125
+
1126
+ def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs):
1127
+ """
1128
+ assert_raises_regex(exception_class, expected_regexp, callable, *args,
1129
+ **kwargs)
1130
+ assert_raises_regex(exception_class, expected_regexp)
1131
+
1132
+ Fail unless an exception of class exception_class and with message that
1133
+ matches expected_regexp is thrown by callable when invoked with arguments
1134
+ args and keyword arguments kwargs.
1135
+
1136
+ Alternatively, can be used as a context manager like `assert_raises`.
1137
+
1138
+ Notes
1139
+ -----
1140
+ .. versionadded:: 1.9.0
1141
+
1142
+ """
1143
+ __tracebackhide__ = True # Hide traceback for py.test
1144
+ return _d.assertRaisesRegex(exception_class, expected_regexp, *args, **kwargs)
1145
+
1146
+
1147
+ def decorate_methods(cls, decorator, testmatch=None):
1148
+ """
1149
+ Apply a decorator to all methods in a class matching a regular expression.
1150
+
1151
+ The given decorator is applied to all public methods of `cls` that are
1152
+ matched by the regular expression `testmatch`
1153
+ (``testmatch.search(methodname)``). Methods that are private, i.e. start
1154
+ with an underscore, are ignored.
1155
+
1156
+ Parameters
1157
+ ----------
1158
+ cls : class
1159
+ Class whose methods to decorate.
1160
+ decorator : function
1161
+ Decorator to apply to methods
1162
+ testmatch : compiled regexp or str, optional
1163
+ The regular expression. Default value is None, in which case the
1164
+ nose default (``re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)``)
1165
+ is used.
1166
+ If `testmatch` is a string, it is compiled to a regular expression
1167
+ first.
1168
+
1169
+ """
1170
+ if testmatch is None:
1171
+ testmatch = re.compile(r"(?:^|[\\b_\\.%s-])[Tt]est" % os.sep)
1172
+ else:
1173
+ testmatch = re.compile(testmatch)
1174
+ cls_attr = cls.__dict__
1175
+
1176
+ # delayed import to reduce startup time
1177
+ from inspect import isfunction
1178
+
1179
+ methods = [_m for _m in cls_attr.values() if isfunction(_m)]
1180
+ for function in methods:
1181
+ try:
1182
+ if hasattr(function, "compat_func_name"):
1183
+ funcname = function.compat_func_name
1184
+ else:
1185
+ funcname = function.__name__
1186
+ except AttributeError:
1187
+ # not a function
1188
+ continue
1189
+ if testmatch.search(funcname) and not funcname.startswith("_"):
1190
+ setattr(cls, funcname, decorator(function))
1191
+ return
1192
+
1193
+
1194
+ def _assert_valid_refcount(op):
1195
+ """
1196
+ Check that ufuncs don't mishandle refcount of object `1`.
1197
+ Used in a few regression tests.
1198
+ """
1199
+ if not HAS_REFCOUNT:
1200
+ return True
1201
+
1202
+ import gc
1203
+
1204
+ import numpy as np
1205
+
1206
+ b = np.arange(100 * 100).reshape(100, 100)
1207
+ c = b
1208
+ i = 1
1209
+
1210
+ gc.disable()
1211
+ try:
1212
+ rc = sys.getrefcount(i)
1213
+ for j in range(15):
1214
+ d = op(b, c)
1215
+ assert_(sys.getrefcount(i) >= rc)
1216
+ finally:
1217
+ gc.enable()
1218
+ del d # for pyflakes
1219
+
1220
+
1221
+ def assert_allclose(
1222
+ actual,
1223
+ desired,
1224
+ rtol=1e-7,
1225
+ atol=0,
1226
+ equal_nan=True,
1227
+ err_msg="",
1228
+ verbose=True,
1229
+ check_dtype=False,
1230
+ ):
1231
+ """
1232
+ Raises an AssertionError if two objects are not equal up to desired
1233
+ tolerance.
1234
+
1235
+ Given two array_like objects, check that their shapes and all elements
1236
+ are equal (but see the Notes for the special handling of a scalar). An
1237
+ exception is raised if the shapes mismatch or any values conflict. In
1238
+ contrast to the standard usage in numpy, NaNs are compared like numbers,
1239
+ no assertion is raised if both objects have NaNs in the same positions.
1240
+
1241
+ The test is equivalent to ``allclose(actual, desired, rtol, atol)`` (note
1242
+ that ``allclose`` has different default values). It compares the difference
1243
+ between `actual` and `desired` to ``atol + rtol * abs(desired)``.
1244
+
1245
+ .. versionadded:: 1.5.0
1246
+
1247
+ Parameters
1248
+ ----------
1249
+ actual : array_like
1250
+ Array obtained.
1251
+ desired : array_like
1252
+ Array desired.
1253
+ rtol : float, optional
1254
+ Relative tolerance.
1255
+ atol : float, optional
1256
+ Absolute tolerance.
1257
+ equal_nan : bool, optional.
1258
+ If True, NaNs will compare equal.
1259
+ err_msg : str, optional
1260
+ The error message to be printed in case of failure.
1261
+ verbose : bool, optional
1262
+ If True, the conflicting values are appended to the error message.
1263
+
1264
+ Raises
1265
+ ------
1266
+ AssertionError
1267
+ If actual and desired are not equal up to specified precision.
1268
+
1269
+ See Also
1270
+ --------
1271
+ assert_array_almost_equal_nulp, assert_array_max_ulp
1272
+
1273
+ Notes
1274
+ -----
1275
+ When one of `actual` and `desired` is a scalar and the other is
1276
+ array_like, the function checks that each element of the array_like
1277
+ object is equal to the scalar.
1278
+
1279
+ Examples
1280
+ --------
1281
+ >>> x = [1e-5, 1e-3, 1e-1]
1282
+ >>> y = np.arccos(np.cos(x))
1283
+ >>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)
1284
+
1285
+ """
1286
+ __tracebackhide__ = True # Hide traceback for py.test
1287
+
1288
+ def compare(x, y):
1289
+ return np.isclose(x, y, rtol=rtol, atol=atol, equal_nan=equal_nan)
1290
+
1291
+ actual, desired = asanyarray(actual), asanyarray(desired)
1292
+ header = f"Not equal to tolerance rtol={rtol:g}, atol={atol:g}"
1293
+
1294
+ if check_dtype:
1295
+ assert actual.dtype == desired.dtype
1296
+
1297
+ assert_array_compare(
1298
+ compare,
1299
+ actual,
1300
+ desired,
1301
+ err_msg=str(err_msg),
1302
+ verbose=verbose,
1303
+ header=header,
1304
+ equal_nan=equal_nan,
1305
+ )
1306
+
1307
+
1308
+ def assert_array_almost_equal_nulp(x, y, nulp=1):
1309
+ """
1310
+ Compare two arrays relatively to their spacing.
1311
+
1312
+ This is a relatively robust method to compare two arrays whose amplitude
1313
+ is variable.
1314
+
1315
+ Parameters
1316
+ ----------
1317
+ x, y : array_like
1318
+ Input arrays.
1319
+ nulp : int, optional
1320
+ The maximum number of unit in the last place for tolerance (see Notes).
1321
+ Default is 1.
1322
+
1323
+ Returns
1324
+ -------
1325
+ None
1326
+
1327
+ Raises
1328
+ ------
1329
+ AssertionError
1330
+ If the spacing between `x` and `y` for one or more elements is larger
1331
+ than `nulp`.
1332
+
1333
+ See Also
1334
+ --------
1335
+ assert_array_max_ulp : Check that all items of arrays differ in at most
1336
+ N Units in the Last Place.
1337
+ spacing : Return the distance between x and the nearest adjacent number.
1338
+
1339
+ Notes
1340
+ -----
1341
+ An assertion is raised if the following condition is not met::
1342
+
1343
+ abs(x - y) <= nulp * spacing(maximum(abs(x), abs(y)))
1344
+
1345
+ Examples
1346
+ --------
1347
+ >>> x = np.array([1., 1e-10, 1e-20])
1348
+ >>> eps = np.finfo(x.dtype).eps
1349
+ >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x) # doctest: +SKIP
1350
+
1351
+ >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x) # doctest: +SKIP
1352
+ Traceback (most recent call last):
1353
+ ...
1354
+ AssertionError: X and Y are not equal to 1 ULP (max is 2)
1355
+
1356
+ """
1357
+ __tracebackhide__ = True # Hide traceback for py.test
1358
+ import numpy as np
1359
+
1360
+ ax = np.abs(x)
1361
+ ay = np.abs(y)
1362
+ ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
1363
+ if not np.all(np.abs(x - y) <= ref):
1364
+ if np.iscomplexobj(x) or np.iscomplexobj(y):
1365
+ msg = "X and Y are not equal to %d ULP" % nulp
1366
+ else:
1367
+ max_nulp = np.max(nulp_diff(x, y))
1368
+ msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp)
1369
+ raise AssertionError(msg)
1370
+
1371
+
1372
+ def assert_array_max_ulp(a, b, maxulp=1, dtype=None):
1373
+ """
1374
+ Check that all items of arrays differ in at most N Units in the Last Place.
1375
+
1376
+ Parameters
1377
+ ----------
1378
+ a, b : array_like
1379
+ Input arrays to be compared.
1380
+ maxulp : int, optional
1381
+ The maximum number of units in the last place that elements of `a` and
1382
+ `b` can differ. Default is 1.
1383
+ dtype : dtype, optional
1384
+ Data-type to convert `a` and `b` to if given. Default is None.
1385
+
1386
+ Returns
1387
+ -------
1388
+ ret : ndarray
1389
+ Array containing number of representable floating point numbers between
1390
+ items in `a` and `b`.
1391
+
1392
+ Raises
1393
+ ------
1394
+ AssertionError
1395
+ If one or more elements differ by more than `maxulp`.
1396
+
1397
+ Notes
1398
+ -----
1399
+ For computing the ULP difference, this API does not differentiate between
1400
+ various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000
1401
+ is zero).
1402
+
1403
+ See Also
1404
+ --------
1405
+ assert_array_almost_equal_nulp : Compare two arrays relatively to their
1406
+ spacing.
1407
+
1408
+ Examples
1409
+ --------
1410
+ >>> a = np.linspace(0., 1., 100)
1411
+ >>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a))) # doctest: +SKIP
1412
+
1413
+ """
1414
+ __tracebackhide__ = True # Hide traceback for py.test
1415
+ import numpy as np
1416
+
1417
+ ret = nulp_diff(a, b, dtype)
1418
+ if not np.all(ret <= maxulp):
1419
+ raise AssertionError(
1420
+ f"Arrays are not almost equal up to {maxulp:g} "
1421
+ f"ULP (max difference is {np.max(ret):g} ULP)"
1422
+ )
1423
+ return ret
1424
+
1425
+
1426
+ def nulp_diff(x, y, dtype=None):
1427
+ """For each item in x and y, return the number of representable floating
1428
+ points between them.
1429
+
1430
+ Parameters
1431
+ ----------
1432
+ x : array_like
1433
+ first input array
1434
+ y : array_like
1435
+ second input array
1436
+ dtype : dtype, optional
1437
+ Data-type to convert `x` and `y` to if given. Default is None.
1438
+
1439
+ Returns
1440
+ -------
1441
+ nulp : array_like
1442
+ number of representable floating point numbers between each item in x
1443
+ and y.
1444
+
1445
+ Notes
1446
+ -----
1447
+ For computing the ULP difference, this API does not differentiate between
1448
+ various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000
1449
+ is zero).
1450
+
1451
+ Examples
1452
+ --------
1453
+ # By definition, epsilon is the smallest number such as 1 + eps != 1, so
1454
+ # there should be exactly one ULP between 1 and 1 + eps
1455
+ >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps) # doctest: +SKIP
1456
+ 1.0
1457
+ """
1458
+ import numpy as np
1459
+
1460
+ if dtype:
1461
+ x = np.asarray(x, dtype=dtype)
1462
+ y = np.asarray(y, dtype=dtype)
1463
+ else:
1464
+ x = np.asarray(x)
1465
+ y = np.asarray(y)
1466
+
1467
+ t = np.common_type(x, y)
1468
+ if np.iscomplexobj(x) or np.iscomplexobj(y):
1469
+ raise NotImplementedError("_nulp not implemented for complex array")
1470
+
1471
+ x = np.array([x], dtype=t)
1472
+ y = np.array([y], dtype=t)
1473
+
1474
+ x[np.isnan(x)] = np.nan
1475
+ y[np.isnan(y)] = np.nan
1476
+
1477
+ if not x.shape == y.shape:
1478
+ raise ValueError(f"x and y do not have the same shape: {x.shape} - {y.shape}")
1479
+
1480
+ def _diff(rx, ry, vdt):
1481
+ diff = np.asarray(rx - ry, dtype=vdt)
1482
+ return np.abs(diff)
1483
+
1484
+ rx = integer_repr(x)
1485
+ ry = integer_repr(y)
1486
+ return _diff(rx, ry, t)
1487
+
1488
+
1489
+ def _integer_repr(x, vdt, comp):
1490
+ # Reinterpret binary representation of the float as sign-magnitude:
1491
+ # take into account two-complement representation
1492
+ # See also
1493
+ # https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
1494
+ rx = x.view(vdt)
1495
+ if not (rx.size == 1):
1496
+ rx[rx < 0] = comp - rx[rx < 0]
1497
+ else:
1498
+ if rx < 0:
1499
+ rx = comp - rx
1500
+
1501
+ return rx
1502
+
1503
+
1504
+ def integer_repr(x):
1505
+ """Return the signed-magnitude interpretation of the binary representation
1506
+ of x."""
1507
+ import numpy as np
1508
+
1509
+ if x.dtype == np.float16:
1510
+ return _integer_repr(x, np.int16, np.int16(-(2**15)))
1511
+ elif x.dtype == np.float32:
1512
+ return _integer_repr(x, np.int32, np.int32(-(2**31)))
1513
+ elif x.dtype == np.float64:
1514
+ return _integer_repr(x, np.int64, np.int64(-(2**63)))
1515
+ else:
1516
+ raise ValueError(f"Unsupported dtype {x.dtype}")
1517
+
1518
+
1519
+ @contextlib.contextmanager
1520
+ def _assert_warns_context(warning_class, name=None):
1521
+ __tracebackhide__ = True # Hide traceback for py.test
1522
+ with suppress_warnings() as sup:
1523
+ l = sup.record(warning_class)
1524
+ yield
1525
+ if not len(l) > 0:
1526
+ name_str = f" when calling {name}" if name is not None else ""
1527
+ raise AssertionError("No warning raised" + name_str)
1528
+
1529
+
1530
+ def assert_warns(warning_class, *args, **kwargs):
1531
+ """
1532
+ Fail unless the given callable throws the specified warning.
1533
+
1534
+ A warning of class warning_class should be thrown by the callable when
1535
+ invoked with arguments args and keyword arguments kwargs.
1536
+ If a different type of warning is thrown, it will not be caught.
1537
+
1538
+ If called with all arguments other than the warning class omitted, may be
1539
+ used as a context manager:
1540
+
1541
+ with assert_warns(SomeWarning):
1542
+ do_something()
1543
+
1544
+ The ability to be used as a context manager is new in NumPy v1.11.0.
1545
+
1546
+ .. versionadded:: 1.4.0
1547
+
1548
+ Parameters
1549
+ ----------
1550
+ warning_class : class
1551
+ The class defining the warning that `func` is expected to throw.
1552
+ func : callable, optional
1553
+ Callable to test
1554
+ *args : Arguments
1555
+ Arguments for `func`.
1556
+ **kwargs : Kwargs
1557
+ Keyword arguments for `func`.
1558
+
1559
+ Returns
1560
+ -------
1561
+ The value returned by `func`.
1562
+
1563
+ Examples
1564
+ --------
1565
+ >>> import warnings
1566
+ >>> def deprecated_func(num):
1567
+ ... warnings.warn("Please upgrade", DeprecationWarning)
1568
+ ... return num*num
1569
+ >>> with np.testing.assert_warns(DeprecationWarning):
1570
+ ... assert deprecated_func(4) == 16
1571
+ >>> # or passing a func
1572
+ >>> ret = np.testing.assert_warns(DeprecationWarning, deprecated_func, 4)
1573
+ >>> assert ret == 16
1574
+ """
1575
+ if not args:
1576
+ return _assert_warns_context(warning_class)
1577
+
1578
+ func = args[0]
1579
+ args = args[1:]
1580
+ with _assert_warns_context(warning_class, name=func.__name__):
1581
+ return func(*args, **kwargs)
1582
+
1583
+
1584
+ @contextlib.contextmanager
1585
+ def _assert_no_warnings_context(name=None):
1586
+ __tracebackhide__ = True # Hide traceback for py.test
1587
+ with warnings.catch_warnings(record=True) as l:
1588
+ warnings.simplefilter("always")
1589
+ yield
1590
+ if len(l) > 0:
1591
+ name_str = f" when calling {name}" if name is not None else ""
1592
+ raise AssertionError(f"Got warnings{name_str}: {l}")
1593
+
1594
+
1595
+ def assert_no_warnings(*args, **kwargs):
1596
+ """
1597
+ Fail if the given callable produces any warnings.
1598
+
1599
+ If called with all arguments omitted, may be used as a context manager:
1600
+
1601
+ with assert_no_warnings():
1602
+ do_something()
1603
+
1604
+ The ability to be used as a context manager is new in NumPy v1.11.0.
1605
+
1606
+ .. versionadded:: 1.7.0
1607
+
1608
+ Parameters
1609
+ ----------
1610
+ func : callable
1611
+ The callable to test.
1612
+ \\*args : Arguments
1613
+ Arguments passed to `func`.
1614
+ \\*\\*kwargs : Kwargs
1615
+ Keyword arguments passed to `func`.
1616
+
1617
+ Returns
1618
+ -------
1619
+ The value returned by `func`.
1620
+
1621
+ """
1622
+ if not args:
1623
+ return _assert_no_warnings_context()
1624
+
1625
+ func = args[0]
1626
+ args = args[1:]
1627
+ with _assert_no_warnings_context(name=func.__name__):
1628
+ return func(*args, **kwargs)
1629
+
1630
+
1631
+ def _gen_alignment_data(dtype=float32, type="binary", max_size=24):
1632
+ """
1633
+ generator producing data with different alignment and offsets
1634
+ to test simd vectorization
1635
+
1636
+ Parameters
1637
+ ----------
1638
+ dtype : dtype
1639
+ data type to produce
1640
+ type : string
1641
+ 'unary': create data for unary operations, creates one input
1642
+ and output array
1643
+ 'binary': create data for unary operations, creates two input
1644
+ and output array
1645
+ max_size : integer
1646
+ maximum size of data to produce
1647
+
1648
+ Returns
1649
+ -------
1650
+ if type is 'unary' yields one output, one input array and a message
1651
+ containing information on the data
1652
+ if type is 'binary' yields one output array, two input array and a message
1653
+ containing information on the data
1654
+
1655
+ """
1656
+ ufmt = "unary offset=(%d, %d), size=%d, dtype=%r, %s"
1657
+ bfmt = "binary offset=(%d, %d, %d), size=%d, dtype=%r, %s"
1658
+ for o in range(3):
1659
+ for s in range(o + 2, max(o + 3, max_size)):
1660
+ if type == "unary":
1661
+
1662
+ def inp():
1663
+ return arange(s, dtype=dtype)[o:]
1664
+
1665
+ out = empty((s,), dtype=dtype)[o:]
1666
+ yield out, inp(), ufmt % (o, o, s, dtype, "out of place")
1667
+ d = inp()
1668
+ yield d, d, ufmt % (o, o, s, dtype, "in place")
1669
+ yield out[1:], inp()[:-1], ufmt % (
1670
+ o + 1,
1671
+ o,
1672
+ s - 1,
1673
+ dtype,
1674
+ "out of place",
1675
+ )
1676
+ yield out[:-1], inp()[1:], ufmt % (
1677
+ o,
1678
+ o + 1,
1679
+ s - 1,
1680
+ dtype,
1681
+ "out of place",
1682
+ )
1683
+ yield inp()[:-1], inp()[1:], ufmt % (o, o + 1, s - 1, dtype, "aliased")
1684
+ yield inp()[1:], inp()[:-1], ufmt % (o + 1, o, s - 1, dtype, "aliased")
1685
+ if type == "binary":
1686
+
1687
+ def inp1():
1688
+ return arange(s, dtype=dtype)[o:]
1689
+
1690
+ inp2 = inp1
1691
+ out = empty((s,), dtype=dtype)[o:]
1692
+ yield out, inp1(), inp2(), bfmt % (o, o, o, s, dtype, "out of place")
1693
+ d = inp1()
1694
+ yield d, d, inp2(), bfmt % (o, o, o, s, dtype, "in place1")
1695
+ d = inp2()
1696
+ yield d, inp1(), d, bfmt % (o, o, o, s, dtype, "in place2")
1697
+ yield out[1:], inp1()[:-1], inp2()[:-1], bfmt % (
1698
+ o + 1,
1699
+ o,
1700
+ o,
1701
+ s - 1,
1702
+ dtype,
1703
+ "out of place",
1704
+ )
1705
+ yield out[:-1], inp1()[1:], inp2()[:-1], bfmt % (
1706
+ o,
1707
+ o + 1,
1708
+ o,
1709
+ s - 1,
1710
+ dtype,
1711
+ "out of place",
1712
+ )
1713
+ yield out[:-1], inp1()[:-1], inp2()[1:], bfmt % (
1714
+ o,
1715
+ o,
1716
+ o + 1,
1717
+ s - 1,
1718
+ dtype,
1719
+ "out of place",
1720
+ )
1721
+ yield inp1()[1:], inp1()[:-1], inp2()[:-1], bfmt % (
1722
+ o + 1,
1723
+ o,
1724
+ o,
1725
+ s - 1,
1726
+ dtype,
1727
+ "aliased",
1728
+ )
1729
+ yield inp1()[:-1], inp1()[1:], inp2()[:-1], bfmt % (
1730
+ o,
1731
+ o + 1,
1732
+ o,
1733
+ s - 1,
1734
+ dtype,
1735
+ "aliased",
1736
+ )
1737
+ yield inp1()[:-1], inp1()[:-1], inp2()[1:], bfmt % (
1738
+ o,
1739
+ o,
1740
+ o + 1,
1741
+ s - 1,
1742
+ dtype,
1743
+ "aliased",
1744
+ )
1745
+
1746
+
1747
+ class IgnoreException(Exception):
1748
+ "Ignoring this exception due to disabled feature"
1749
+
1750
+
1751
+ @contextlib.contextmanager
1752
+ def tempdir(*args, **kwargs):
1753
+ """Context manager to provide a temporary test folder.
1754
+
1755
+ All arguments are passed as this to the underlying tempfile.mkdtemp
1756
+ function.
1757
+
1758
+ """
1759
+ tmpdir = mkdtemp(*args, **kwargs)
1760
+ try:
1761
+ yield tmpdir
1762
+ finally:
1763
+ shutil.rmtree(tmpdir)
1764
+
1765
+
1766
+ @contextlib.contextmanager
1767
+ def temppath(*args, **kwargs):
1768
+ """Context manager for temporary files.
1769
+
1770
+ Context manager that returns the path to a closed temporary file. Its
1771
+ parameters are the same as for tempfile.mkstemp and are passed directly
1772
+ to that function. The underlying file is removed when the context is
1773
+ exited, so it should be closed at that time.
1774
+
1775
+ Windows does not allow a temporary file to be opened if it is already
1776
+ open, so the underlying file must be closed after opening before it
1777
+ can be opened again.
1778
+
1779
+ """
1780
+ fd, path = mkstemp(*args, **kwargs)
1781
+ os.close(fd)
1782
+ try:
1783
+ yield path
1784
+ finally:
1785
+ os.remove(path)
1786
+
1787
+
1788
+ class clear_and_catch_warnings(warnings.catch_warnings):
1789
+ """Context manager that resets warning registry for catching warnings
1790
+
1791
+ Warnings can be slippery, because, whenever a warning is triggered, Python
1792
+ adds a ``__warningregistry__`` member to the *calling* module. This makes
1793
+ it impossible to retrigger the warning in this module, whatever you put in
1794
+ the warnings filters. This context manager accepts a sequence of `modules`
1795
+ as a keyword argument to its constructor and:
1796
+
1797
+ * stores and removes any ``__warningregistry__`` entries in given `modules`
1798
+ on entry;
1799
+ * resets ``__warningregistry__`` to its previous state on exit.
1800
+
1801
+ This makes it possible to trigger any warning afresh inside the context
1802
+ manager without disturbing the state of warnings outside.
1803
+
1804
+ For compatibility with Python 3.0, please consider all arguments to be
1805
+ keyword-only.
1806
+
1807
+ Parameters
1808
+ ----------
1809
+ record : bool, optional
1810
+ Specifies whether warnings should be captured by a custom
1811
+ implementation of ``warnings.showwarning()`` and be appended to a list
1812
+ returned by the context manager. Otherwise None is returned by the
1813
+ context manager. The objects appended to the list are arguments whose
1814
+ attributes mirror the arguments to ``showwarning()``.
1815
+ modules : sequence, optional
1816
+ Sequence of modules for which to reset warnings registry on entry and
1817
+ restore on exit. To work correctly, all 'ignore' filters should
1818
+ filter by one of these modules.
1819
+
1820
+ Examples
1821
+ --------
1822
+ >>> import warnings
1823
+ >>> with np.testing.clear_and_catch_warnings( # doctest: +SKIP
1824
+ ... modules=[np.core.fromnumeric]):
1825
+ ... warnings.simplefilter('always')
1826
+ ... warnings.filterwarnings('ignore', module='np.core.fromnumeric')
1827
+ ... # do something that raises a warning but ignore those in
1828
+ ... # np.core.fromnumeric
1829
+ """
1830
+
1831
+ class_modules = ()
1832
+
1833
+ def __init__(self, record=False, modules=()):
1834
+ self.modules = set(modules).union(self.class_modules)
1835
+ self._warnreg_copies = {}
1836
+ super().__init__(record=record)
1837
+
1838
+ def __enter__(self):
1839
+ for mod in self.modules:
1840
+ if hasattr(mod, "__warningregistry__"):
1841
+ mod_reg = mod.__warningregistry__
1842
+ self._warnreg_copies[mod] = mod_reg.copy()
1843
+ mod_reg.clear()
1844
+ return super().__enter__()
1845
+
1846
+ def __exit__(self, *exc_info):
1847
+ super().__exit__(*exc_info)
1848
+ for mod in self.modules:
1849
+ if hasattr(mod, "__warningregistry__"):
1850
+ mod.__warningregistry__.clear()
1851
+ if mod in self._warnreg_copies:
1852
+ mod.__warningregistry__.update(self._warnreg_copies[mod])
1853
+
1854
+
1855
+ class suppress_warnings:
1856
+ """
1857
+ Context manager and decorator doing much the same as
1858
+ ``warnings.catch_warnings``.
1859
+
1860
+ However, it also provides a filter mechanism to work around
1861
+ https://bugs.python.org/issue4180.
1862
+
1863
+ This bug causes Python before 3.4 to not reliably show warnings again
1864
+ after they have been ignored once (even within catch_warnings). It
1865
+ means that no "ignore" filter can be used easily, since following
1866
+ tests might need to see the warning. Additionally it allows easier
1867
+ specificity for testing warnings and can be nested.
1868
+
1869
+ Parameters
1870
+ ----------
1871
+ forwarding_rule : str, optional
1872
+ One of "always", "once", "module", or "location". Analogous to
1873
+ the usual warnings module filter mode, it is useful to reduce
1874
+ noise mostly on the outmost level. Unsuppressed and unrecorded
1875
+ warnings will be forwarded based on this rule. Defaults to "always".
1876
+ "location" is equivalent to the warnings "default", match by exact
1877
+ location the warning warning originated from.
1878
+
1879
+ Notes
1880
+ -----
1881
+ Filters added inside the context manager will be discarded again
1882
+ when leaving it. Upon entering all filters defined outside a
1883
+ context will be applied automatically.
1884
+
1885
+ When a recording filter is added, matching warnings are stored in the
1886
+ ``log`` attribute as well as in the list returned by ``record``.
1887
+
1888
+ If filters are added and the ``module`` keyword is given, the
1889
+ warning registry of this module will additionally be cleared when
1890
+ applying it, entering the context, or exiting it. This could cause
1891
+ warnings to appear a second time after leaving the context if they
1892
+ were configured to be printed once (default) and were already
1893
+ printed before the context was entered.
1894
+
1895
+ Nesting this context manager will work as expected when the
1896
+ forwarding rule is "always" (default). Unfiltered and unrecorded
1897
+ warnings will be passed out and be matched by the outer level.
1898
+ On the outmost level they will be printed (or caught by another
1899
+ warnings context). The forwarding rule argument can modify this
1900
+ behaviour.
1901
+
1902
+ Like ``catch_warnings`` this context manager is not threadsafe.
1903
+
1904
+ Examples
1905
+ --------
1906
+
1907
+ With a context manager::
1908
+
1909
+ with np.testing.suppress_warnings() as sup:
1910
+ sup.filter(DeprecationWarning, "Some text")
1911
+ sup.filter(module=np.ma.core)
1912
+ log = sup.record(FutureWarning, "Does this occur?")
1913
+ command_giving_warnings()
1914
+ # The FutureWarning was given once, the filtered warnings were
1915
+ # ignored. All other warnings abide outside settings (may be
1916
+ # printed/error)
1917
+ assert_(len(log) == 1)
1918
+ assert_(len(sup.log) == 1) # also stored in log attribute
1919
+
1920
+ Or as a decorator::
1921
+
1922
+ sup = np.testing.suppress_warnings()
1923
+ sup.filter(module=np.ma.core) # module must match exactly
1924
+ @sup
1925
+ def some_function():
1926
+ # do something which causes a warning in np.ma.core
1927
+ pass
1928
+ """
1929
+
1930
+ def __init__(self, forwarding_rule="always"):
1931
+ self._entered = False
1932
+
1933
+ # Suppressions are either instance or defined inside one with block:
1934
+ self._suppressions = []
1935
+
1936
+ if forwarding_rule not in {"always", "module", "once", "location"}:
1937
+ raise ValueError("unsupported forwarding rule.")
1938
+ self._forwarding_rule = forwarding_rule
1939
+
1940
+ def _clear_registries(self):
1941
+ if hasattr(warnings, "_filters_mutated"):
1942
+ # clearing the registry should not be necessary on new pythons,
1943
+ # instead the filters should be mutated.
1944
+ warnings._filters_mutated()
1945
+ return
1946
+ # Simply clear the registry, this should normally be harmless,
1947
+ # note that on new pythons it would be invalidated anyway.
1948
+ for module in self._tmp_modules:
1949
+ if hasattr(module, "__warningregistry__"):
1950
+ module.__warningregistry__.clear()
1951
+
1952
+ def _filter(self, category=Warning, message="", module=None, record=False):
1953
+ if record:
1954
+ record = [] # The log where to store warnings
1955
+ else:
1956
+ record = None
1957
+ if self._entered:
1958
+ if module is None:
1959
+ warnings.filterwarnings("always", category=category, message=message)
1960
+ else:
1961
+ module_regex = module.__name__.replace(".", r"\.") + "$"
1962
+ warnings.filterwarnings(
1963
+ "always", category=category, message=message, module=module_regex
1964
+ )
1965
+ self._tmp_modules.add(module)
1966
+ self._clear_registries()
1967
+
1968
+ self._tmp_suppressions.append(
1969
+ (category, message, re.compile(message, re.I), module, record)
1970
+ )
1971
+ else:
1972
+ self._suppressions.append(
1973
+ (category, message, re.compile(message, re.I), module, record)
1974
+ )
1975
+
1976
+ return record
1977
+
1978
+ def filter(self, category=Warning, message="", module=None):
1979
+ """
1980
+ Add a new suppressing filter or apply it if the state is entered.
1981
+
1982
+ Parameters
1983
+ ----------
1984
+ category : class, optional
1985
+ Warning class to filter
1986
+ message : string, optional
1987
+ Regular expression matching the warning message.
1988
+ module : module, optional
1989
+ Module to filter for. Note that the module (and its file)
1990
+ must match exactly and cannot be a submodule. This may make
1991
+ it unreliable for external modules.
1992
+
1993
+ Notes
1994
+ -----
1995
+ When added within a context, filters are only added inside
1996
+ the context and will be forgotten when the context is exited.
1997
+ """
1998
+ self._filter(category=category, message=message, module=module, record=False)
1999
+
2000
+ def record(self, category=Warning, message="", module=None):
2001
+ """
2002
+ Append a new recording filter or apply it if the state is entered.
2003
+
2004
+ All warnings matching will be appended to the ``log`` attribute.
2005
+
2006
+ Parameters
2007
+ ----------
2008
+ category : class, optional
2009
+ Warning class to filter
2010
+ message : string, optional
2011
+ Regular expression matching the warning message.
2012
+ module : module, optional
2013
+ Module to filter for. Note that the module (and its file)
2014
+ must match exactly and cannot be a submodule. This may make
2015
+ it unreliable for external modules.
2016
+
2017
+ Returns
2018
+ -------
2019
+ log : list
2020
+ A list which will be filled with all matched warnings.
2021
+
2022
+ Notes
2023
+ -----
2024
+ When added within a context, filters are only added inside
2025
+ the context and will be forgotten when the context is exited.
2026
+ """
2027
+ return self._filter(
2028
+ category=category, message=message, module=module, record=True
2029
+ )
2030
+
2031
+ def __enter__(self):
2032
+ if self._entered:
2033
+ raise RuntimeError("cannot enter suppress_warnings twice.")
2034
+
2035
+ self._orig_show = warnings.showwarning
2036
+ self._filters = warnings.filters
2037
+ warnings.filters = self._filters[:]
2038
+
2039
+ self._entered = True
2040
+ self._tmp_suppressions = []
2041
+ self._tmp_modules = set()
2042
+ self._forwarded = set()
2043
+
2044
+ self.log = [] # reset global log (no need to keep same list)
2045
+
2046
+ for cat, mess, _, mod, log in self._suppressions:
2047
+ if log is not None:
2048
+ del log[:] # clear the log
2049
+ if mod is None:
2050
+ warnings.filterwarnings("always", category=cat, message=mess)
2051
+ else:
2052
+ module_regex = mod.__name__.replace(".", r"\.") + "$"
2053
+ warnings.filterwarnings(
2054
+ "always", category=cat, message=mess, module=module_regex
2055
+ )
2056
+ self._tmp_modules.add(mod)
2057
+ warnings.showwarning = self._showwarning
2058
+ self._clear_registries()
2059
+
2060
+ return self
2061
+
2062
+ def __exit__(self, *exc_info):
2063
+ warnings.showwarning = self._orig_show
2064
+ warnings.filters = self._filters
2065
+ self._clear_registries()
2066
+ self._entered = False
2067
+ del self._orig_show
2068
+ del self._filters
2069
+
2070
+ def _showwarning(
2071
+ self, message, category, filename, lineno, *args, use_warnmsg=None, **kwargs
2072
+ ):
2073
+ for cat, _, pattern, mod, rec in (self._suppressions + self._tmp_suppressions)[
2074
+ ::-1
2075
+ ]:
2076
+ if issubclass(category, cat) and pattern.match(message.args[0]) is not None:
2077
+ if mod is None:
2078
+ # Message and category match, either recorded or ignored
2079
+ if rec is not None:
2080
+ msg = WarningMessage(
2081
+ message, category, filename, lineno, **kwargs
2082
+ )
2083
+ self.log.append(msg)
2084
+ rec.append(msg)
2085
+ return
2086
+ # Use startswith, because warnings strips the c or o from
2087
+ # .pyc/.pyo files.
2088
+ elif mod.__file__.startswith(filename):
2089
+ # The message and module (filename) match
2090
+ if rec is not None:
2091
+ msg = WarningMessage(
2092
+ message, category, filename, lineno, **kwargs
2093
+ )
2094
+ self.log.append(msg)
2095
+ rec.append(msg)
2096
+ return
2097
+
2098
+ # There is no filter in place, so pass to the outside handler
2099
+ # unless we should only pass it once
2100
+ if self._forwarding_rule == "always":
2101
+ if use_warnmsg is None:
2102
+ self._orig_show(message, category, filename, lineno, *args, **kwargs)
2103
+ else:
2104
+ self._orig_showmsg(use_warnmsg)
2105
+ return
2106
+
2107
+ if self._forwarding_rule == "once":
2108
+ signature = (message.args, category)
2109
+ elif self._forwarding_rule == "module":
2110
+ signature = (message.args, category, filename)
2111
+ elif self._forwarding_rule == "location":
2112
+ signature = (message.args, category, filename, lineno)
2113
+
2114
+ if signature in self._forwarded:
2115
+ return
2116
+ self._forwarded.add(signature)
2117
+ if use_warnmsg is None:
2118
+ self._orig_show(message, category, filename, lineno, *args, **kwargs)
2119
+ else:
2120
+ self._orig_showmsg(use_warnmsg)
2121
+
2122
+ def __call__(self, func):
2123
+ """
2124
+ Function decorator to apply certain suppressions to a whole
2125
+ function.
2126
+ """
2127
+
2128
+ @wraps(func)
2129
+ def new_func(*args, **kwargs):
2130
+ with self:
2131
+ return func(*args, **kwargs)
2132
+
2133
+ return new_func
2134
+
2135
+
2136
+ @contextlib.contextmanager
2137
+ def _assert_no_gc_cycles_context(name=None):
2138
+ __tracebackhide__ = True # Hide traceback for py.test
2139
+
2140
+ # not meaningful to test if there is no refcounting
2141
+ if not HAS_REFCOUNT:
2142
+ yield
2143
+ return
2144
+
2145
+ assert_(gc.isenabled())
2146
+ gc.disable()
2147
+ gc_debug = gc.get_debug()
2148
+ try:
2149
+ for i in range(100):
2150
+ if gc.collect() == 0:
2151
+ break
2152
+ else:
2153
+ raise RuntimeError(
2154
+ "Unable to fully collect garbage - perhaps a __del__ method "
2155
+ "is creating more reference cycles?"
2156
+ )
2157
+
2158
+ gc.set_debug(gc.DEBUG_SAVEALL)
2159
+ yield
2160
+ # gc.collect returns the number of unreachable objects in cycles that
2161
+ # were found -- we are checking that no cycles were created in the context
2162
+ n_objects_in_cycles = gc.collect()
2163
+ objects_in_cycles = gc.garbage[:]
2164
+ finally:
2165
+ del gc.garbage[:]
2166
+ gc.set_debug(gc_debug)
2167
+ gc.enable()
2168
+
2169
+ if n_objects_in_cycles:
2170
+ name_str = f" when calling {name}" if name is not None else ""
2171
+ raise AssertionError(
2172
+ "Reference cycles were found{}: {} objects were collected, "
2173
+ "of which {} are shown below:{}".format(
2174
+ name_str,
2175
+ n_objects_in_cycles,
2176
+ len(objects_in_cycles),
2177
+ "".join(
2178
+ "\n {} object with id={}:\n {}".format(
2179
+ type(o).__name__,
2180
+ id(o),
2181
+ pprint.pformat(o).replace("\n", "\n "),
2182
+ )
2183
+ for o in objects_in_cycles
2184
+ ),
2185
+ )
2186
+ )
2187
+
2188
+
2189
+ def assert_no_gc_cycles(*args, **kwargs):
2190
+ """
2191
+ Fail if the given callable produces any reference cycles.
2192
+
2193
+ If called with all arguments omitted, may be used as a context manager:
2194
+
2195
+ with assert_no_gc_cycles():
2196
+ do_something()
2197
+
2198
+ .. versionadded:: 1.15.0
2199
+
2200
+ Parameters
2201
+ ----------
2202
+ func : callable
2203
+ The callable to test.
2204
+ \\*args : Arguments
2205
+ Arguments passed to `func`.
2206
+ \\*\\*kwargs : Kwargs
2207
+ Keyword arguments passed to `func`.
2208
+
2209
+ Returns
2210
+ -------
2211
+ Nothing. The result is deliberately discarded to ensure that all cycles
2212
+ are found.
2213
+
2214
+ """
2215
+ if not args:
2216
+ return _assert_no_gc_cycles_context()
2217
+
2218
+ func = args[0]
2219
+ args = args[1:]
2220
+ with _assert_no_gc_cycles_context(name=func.__name__):
2221
+ func(*args, **kwargs)
2222
+
2223
+
2224
+ def break_cycles():
2225
+ """
2226
+ Break reference cycles by calling gc.collect
2227
+ Objects can call other objects' methods (for instance, another object's
2228
+ __del__) inside their own __del__. On PyPy, the interpreter only runs
2229
+ between calls to gc.collect, so multiple calls are needed to completely
2230
+ release all cycles.
2231
+ """
2232
+
2233
+ gc.collect()
2234
+ if IS_PYPY:
2235
+ # a few more, just to make sure all the finalizers are called
2236
+ gc.collect()
2237
+ gc.collect()
2238
+ gc.collect()
2239
+ gc.collect()
2240
+
2241
+
2242
+ def requires_memory(free_bytes):
2243
+ """Decorator to skip a test if not enough memory is available"""
2244
+ import pytest
2245
+
2246
+ def decorator(func):
2247
+ @wraps(func)
2248
+ def wrapper(*a, **kw):
2249
+ msg = check_free_memory(free_bytes)
2250
+ if msg is not None:
2251
+ pytest.skip(msg)
2252
+
2253
+ try:
2254
+ return func(*a, **kw)
2255
+ except MemoryError:
2256
+ # Probably ran out of memory regardless: don't regard as failure
2257
+ pytest.xfail("MemoryError raised")
2258
+
2259
+ return wrapper
2260
+
2261
+ return decorator
2262
+
2263
+
2264
+ def check_free_memory(free_bytes):
2265
+ """
2266
+ Check whether `free_bytes` amount of memory is currently free.
2267
+ Returns: None if enough memory available, otherwise error message
2268
+ """
2269
+ env_var = "NPY_AVAILABLE_MEM"
2270
+ env_value = os.environ.get(env_var)
2271
+ if env_value is not None:
2272
+ try:
2273
+ mem_free = _parse_size(env_value)
2274
+ except ValueError as exc:
2275
+ raise ValueError( # noqa: TRY200
2276
+ f"Invalid environment variable {env_var}: {exc}"
2277
+ )
2278
+
2279
+ msg = (
2280
+ f"{free_bytes/1e9} GB memory required, but environment variable "
2281
+ f"NPY_AVAILABLE_MEM={env_value} set"
2282
+ )
2283
+ else:
2284
+ mem_free = _get_mem_available()
2285
+
2286
+ if mem_free is None:
2287
+ msg = (
2288
+ "Could not determine available memory; set NPY_AVAILABLE_MEM "
2289
+ "environment variable (e.g. NPY_AVAILABLE_MEM=16GB) to run "
2290
+ "the test."
2291
+ )
2292
+ mem_free = -1
2293
+ else:
2294
+ msg = (
2295
+ f"{free_bytes/1e9} GB memory required, but {mem_free/1e9} GB available"
2296
+ )
2297
+
2298
+ return msg if mem_free < free_bytes else None
2299
+
2300
+
2301
+ def _parse_size(size_str):
2302
+ """Convert memory size strings ('12 GB' etc.) to float"""
2303
+ suffixes = {
2304
+ "": 1,
2305
+ "b": 1,
2306
+ "k": 1000,
2307
+ "m": 1000**2,
2308
+ "g": 1000**3,
2309
+ "t": 1000**4,
2310
+ "kb": 1000,
2311
+ "mb": 1000**2,
2312
+ "gb": 1000**3,
2313
+ "tb": 1000**4,
2314
+ "kib": 1024,
2315
+ "mib": 1024**2,
2316
+ "gib": 1024**3,
2317
+ "tib": 1024**4,
2318
+ }
2319
+
2320
+ size_re = re.compile(
2321
+ r"^\s*(\d+|\d+\.\d+)\s*({})\s*$".format("|".join(suffixes.keys())), re.I
2322
+ )
2323
+
2324
+ m = size_re.match(size_str.lower())
2325
+ if not m or m.group(2) not in suffixes:
2326
+ raise ValueError(f"value {size_str!r} not a valid size")
2327
+ return int(float(m.group(1)) * suffixes[m.group(2)])
2328
+
2329
+
2330
+ def _get_mem_available():
2331
+ """Return available memory in bytes, or None if unknown."""
2332
+ try:
2333
+ import psutil
2334
+
2335
+ return psutil.virtual_memory().available
2336
+ except (ImportError, AttributeError):
2337
+ pass
2338
+
2339
+ if sys.platform.startswith("linux"):
2340
+ info = {}
2341
+ with open("/proc/meminfo") as f:
2342
+ for line in f:
2343
+ p = line.split()
2344
+ info[p[0].strip(":").lower()] = int(p[1]) * 1024
2345
+
2346
+ if "memavailable" in info:
2347
+ # Linux >= 3.14
2348
+ return info["memavailable"]
2349
+ else:
2350
+ return info["memfree"] + info["cached"]
2351
+
2352
+ return None
2353
+
2354
+
2355
+ def _no_tracing(func):
2356
+ """
2357
+ Decorator to temporarily turn off tracing for the duration of a test.
2358
+ Needed in tests that check refcounting, otherwise the tracing itself
2359
+ influences the refcounts
2360
+ """
2361
+ if not hasattr(sys, "gettrace"):
2362
+ return func
2363
+ else:
2364
+
2365
+ @wraps(func)
2366
+ def wrapper(*args, **kwargs):
2367
+ original_trace = sys.gettrace()
2368
+ try:
2369
+ sys.settrace(None)
2370
+ return func(*args, **kwargs)
2371
+ finally:
2372
+ sys.settrace(original_trace)
2373
+
2374
+ return wrapper
2375
+
2376
+
2377
+ def _get_glibc_version():
2378
+ try:
2379
+ ver = os.confstr("CS_GNU_LIBC_VERSION").rsplit(" ")[1]
2380
+ except Exception as inst:
2381
+ ver = "0.0"
2382
+
2383
+ return ver
2384
+
2385
+
2386
+ _glibcver = _get_glibc_version()
2387
+
2388
+
2389
+ def _glibc_older_than(x):
2390
+ return _glibcver != "0.0" and _glibcver < x
shared/package-files/74/74d25b704e4e54363fc07c0dfd4054b5f211775dceaaef910443bbe20e52b010/blob ADDED
Binary file (2.08 kB). View file
 
shared/package-files/74/74d8c4bc58760b7e17328884fd1ee5889bf972bc97533d9647656cc5d9d0763a/blob ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ from gettext import gettext
6
+ import os
7
+ import sys
8
+ from typing import Any
9
+ from typing import Callable
10
+ from typing import cast
11
+ from typing import final
12
+ from typing import List
13
+ from typing import Literal
14
+ from typing import Mapping
15
+ from typing import NoReturn
16
+ from typing import Sequence
17
+
18
+ import _pytest._io
19
+ from _pytest.config.exceptions import UsageError
20
+ from _pytest.deprecated import check_ispytest
21
+
22
+
23
+ FILE_OR_DIR = "file_or_dir"
24
+
25
+
26
+ class NotSet:
27
+ def __repr__(self) -> str:
28
+ return "<notset>"
29
+
30
+
31
+ NOT_SET = NotSet()
32
+
33
+
34
+ @final
35
+ class Parser:
36
+ """Parser for command line arguments and ini-file values.
37
+
38
+ :ivar extra_info: Dict of generic param -> value to display in case
39
+ there's an error processing the command line arguments.
40
+ """
41
+
42
+ prog: str | None = None
43
+
44
+ def __init__(
45
+ self,
46
+ usage: str | None = None,
47
+ processopt: Callable[[Argument], None] | None = None,
48
+ *,
49
+ _ispytest: bool = False,
50
+ ) -> None:
51
+ check_ispytest(_ispytest)
52
+ self._anonymous = OptionGroup("Custom options", parser=self, _ispytest=True)
53
+ self._groups: list[OptionGroup] = []
54
+ self._processopt = processopt
55
+ self._usage = usage
56
+ self._inidict: dict[str, tuple[str, str | None, Any]] = {}
57
+ self._ininames: list[str] = []
58
+ self.extra_info: dict[str, Any] = {}
59
+
60
+ def processoption(self, option: Argument) -> None:
61
+ if self._processopt:
62
+ if option.dest:
63
+ self._processopt(option)
64
+
65
+ def getgroup(
66
+ self, name: str, description: str = "", after: str | None = None
67
+ ) -> OptionGroup:
68
+ """Get (or create) a named option Group.
69
+
70
+ :param name: Name of the option group.
71
+ :param description: Long description for --help output.
72
+ :param after: Name of another group, used for ordering --help output.
73
+ :returns: The option group.
74
+
75
+ The returned group object has an ``addoption`` method with the same
76
+ signature as :func:`parser.addoption <pytest.Parser.addoption>` but
77
+ will be shown in the respective group in the output of
78
+ ``pytest --help``.
79
+ """
80
+ for group in self._groups:
81
+ if group.name == name:
82
+ return group
83
+ group = OptionGroup(name, description, parser=self, _ispytest=True)
84
+ i = 0
85
+ for i, grp in enumerate(self._groups):
86
+ if grp.name == after:
87
+ break
88
+ self._groups.insert(i + 1, group)
89
+ return group
90
+
91
+ def addoption(self, *opts: str, **attrs: Any) -> None:
92
+ """Register a command line option.
93
+
94
+ :param opts:
95
+ Option names, can be short or long options.
96
+ :param attrs:
97
+ Same attributes as the argparse library's :meth:`add_argument()
98
+ <argparse.ArgumentParser.add_argument>` function accepts.
99
+
100
+ After command line parsing, options are available on the pytest config
101
+ object via ``config.option.NAME`` where ``NAME`` is usually set
102
+ by passing a ``dest`` attribute, for example
103
+ ``addoption("--long", dest="NAME", ...)``.
104
+ """
105
+ self._anonymous.addoption(*opts, **attrs)
106
+
107
+ def parse(
108
+ self,
109
+ args: Sequence[str | os.PathLike[str]],
110
+ namespace: argparse.Namespace | None = None,
111
+ ) -> argparse.Namespace:
112
+ from _pytest._argcomplete import try_argcomplete
113
+
114
+ self.optparser = self._getparser()
115
+ try_argcomplete(self.optparser)
116
+ strargs = [os.fspath(x) for x in args]
117
+ return self.optparser.parse_args(strargs, namespace=namespace)
118
+
119
+ def _getparser(self) -> MyOptionParser:
120
+ from _pytest._argcomplete import filescompleter
121
+
122
+ optparser = MyOptionParser(self, self.extra_info, prog=self.prog)
123
+ groups = [*self._groups, self._anonymous]
124
+ for group in groups:
125
+ if group.options:
126
+ desc = group.description or group.name
127
+ arggroup = optparser.add_argument_group(desc)
128
+ for option in group.options:
129
+ n = option.names()
130
+ a = option.attrs()
131
+ arggroup.add_argument(*n, **a)
132
+ file_or_dir_arg = optparser.add_argument(FILE_OR_DIR, nargs="*")
133
+ # bash like autocompletion for dirs (appending '/')
134
+ # Type ignored because typeshed doesn't know about argcomplete.
135
+ file_or_dir_arg.completer = filescompleter # type: ignore
136
+ return optparser
137
+
138
+ def parse_setoption(
139
+ self,
140
+ args: Sequence[str | os.PathLike[str]],
141
+ option: argparse.Namespace,
142
+ namespace: argparse.Namespace | None = None,
143
+ ) -> list[str]:
144
+ parsedoption = self.parse(args, namespace=namespace)
145
+ for name, value in parsedoption.__dict__.items():
146
+ setattr(option, name, value)
147
+ return cast(List[str], getattr(parsedoption, FILE_OR_DIR))
148
+
149
+ def parse_known_args(
150
+ self,
151
+ args: Sequence[str | os.PathLike[str]],
152
+ namespace: argparse.Namespace | None = None,
153
+ ) -> argparse.Namespace:
154
+ """Parse the known arguments at this point.
155
+
156
+ :returns: An argparse namespace object.
157
+ """
158
+ return self.parse_known_and_unknown_args(args, namespace=namespace)[0]
159
+
160
+ def parse_known_and_unknown_args(
161
+ self,
162
+ args: Sequence[str | os.PathLike[str]],
163
+ namespace: argparse.Namespace | None = None,
164
+ ) -> tuple[argparse.Namespace, list[str]]:
165
+ """Parse the known arguments at this point, and also return the
166
+ remaining unknown arguments.
167
+
168
+ :returns:
169
+ A tuple containing an argparse namespace object for the known
170
+ arguments, and a list of the unknown arguments.
171
+ """
172
+ optparser = self._getparser()
173
+ strargs = [os.fspath(x) for x in args]
174
+ return optparser.parse_known_args(strargs, namespace=namespace)
175
+
176
+ def addini(
177
+ self,
178
+ name: str,
179
+ help: str,
180
+ type: Literal["string", "paths", "pathlist", "args", "linelist", "bool"]
181
+ | None = None,
182
+ default: Any = NOT_SET,
183
+ ) -> None:
184
+ """Register an ini-file option.
185
+
186
+ :param name:
187
+ Name of the ini-variable.
188
+ :param type:
189
+ Type of the variable. Can be:
190
+
191
+ * ``string``: a string
192
+ * ``bool``: a boolean
193
+ * ``args``: a list of strings, separated as in a shell
194
+ * ``linelist``: a list of strings, separated by line breaks
195
+ * ``paths``: a list of :class:`pathlib.Path`, separated as in a shell
196
+ * ``pathlist``: a list of ``py.path``, separated as in a shell
197
+
198
+ For ``paths`` and ``pathlist`` types, they are considered relative to the ini-file.
199
+ In case the execution is happening without an ini-file defined,
200
+ they will be considered relative to the current working directory (for example with ``--override-ini``).
201
+
202
+ .. versionadded:: 7.0
203
+ The ``paths`` variable type.
204
+
205
+ .. versionadded:: 8.1
206
+ Use the current working directory to resolve ``paths`` and ``pathlist`` in the absence of an ini-file.
207
+
208
+ Defaults to ``string`` if ``None`` or not passed.
209
+ :param default:
210
+ Default value if no ini-file option exists but is queried.
211
+
212
+ The value of ini-variables can be retrieved via a call to
213
+ :py:func:`config.getini(name) <pytest.Config.getini>`.
214
+ """
215
+ assert type in (None, "string", "paths", "pathlist", "args", "linelist", "bool")
216
+ if default is NOT_SET:
217
+ default = get_ini_default_for_type(type)
218
+
219
+ self._inidict[name] = (help, type, default)
220
+ self._ininames.append(name)
221
+
222
+
223
+ def get_ini_default_for_type(
224
+ type: Literal["string", "paths", "pathlist", "args", "linelist", "bool"] | None,
225
+ ) -> Any:
226
+ """
227
+ Used by addini to get the default value for a given ini-option type, when
228
+ default is not supplied.
229
+ """
230
+ if type is None:
231
+ return ""
232
+ elif type in ("paths", "pathlist", "args", "linelist"):
233
+ return []
234
+ elif type == "bool":
235
+ return False
236
+ else:
237
+ return ""
238
+
239
+
240
+ class ArgumentError(Exception):
241
+ """Raised if an Argument instance is created with invalid or
242
+ inconsistent arguments."""
243
+
244
+ def __init__(self, msg: str, option: Argument | str) -> None:
245
+ self.msg = msg
246
+ self.option_id = str(option)
247
+
248
+ def __str__(self) -> str:
249
+ if self.option_id:
250
+ return f"option {self.option_id}: {self.msg}"
251
+ else:
252
+ return self.msg
253
+
254
+
255
+ class Argument:
256
+ """Class that mimics the necessary behaviour of optparse.Option.
257
+
258
+ It's currently a least effort implementation and ignoring choices
259
+ and integer prefixes.
260
+
261
+ https://docs.python.org/3/library/optparse.html#optparse-standard-option-types
262
+ """
263
+
264
+ def __init__(self, *names: str, **attrs: Any) -> None:
265
+ """Store params in private vars for use in add_argument."""
266
+ self._attrs = attrs
267
+ self._short_opts: list[str] = []
268
+ self._long_opts: list[str] = []
269
+ try:
270
+ self.type = attrs["type"]
271
+ except KeyError:
272
+ pass
273
+ try:
274
+ # Attribute existence is tested in Config._processopt.
275
+ self.default = attrs["default"]
276
+ except KeyError:
277
+ pass
278
+ self._set_opt_strings(names)
279
+ dest: str | None = attrs.get("dest")
280
+ if dest:
281
+ self.dest = dest
282
+ elif self._long_opts:
283
+ self.dest = self._long_opts[0][2:].replace("-", "_")
284
+ else:
285
+ try:
286
+ self.dest = self._short_opts[0][1:]
287
+ except IndexError as e:
288
+ self.dest = "???" # Needed for the error repr.
289
+ raise ArgumentError("need a long or short option", self) from e
290
+
291
+ def names(self) -> list[str]:
292
+ return self._short_opts + self._long_opts
293
+
294
+ def attrs(self) -> Mapping[str, Any]:
295
+ # Update any attributes set by processopt.
296
+ attrs = "default dest help".split()
297
+ attrs.append(self.dest)
298
+ for attr in attrs:
299
+ try:
300
+ self._attrs[attr] = getattr(self, attr)
301
+ except AttributeError:
302
+ pass
303
+ return self._attrs
304
+
305
+ def _set_opt_strings(self, opts: Sequence[str]) -> None:
306
+ """Directly from optparse.
307
+
308
+ Might not be necessary as this is passed to argparse later on.
309
+ """
310
+ for opt in opts:
311
+ if len(opt) < 2:
312
+ raise ArgumentError(
313
+ f"invalid option string {opt!r}: "
314
+ "must be at least two characters long",
315
+ self,
316
+ )
317
+ elif len(opt) == 2:
318
+ if not (opt[0] == "-" and opt[1] != "-"):
319
+ raise ArgumentError(
320
+ f"invalid short option string {opt!r}: "
321
+ "must be of the form -x, (x any non-dash char)",
322
+ self,
323
+ )
324
+ self._short_opts.append(opt)
325
+ else:
326
+ if not (opt[0:2] == "--" and opt[2] != "-"):
327
+ raise ArgumentError(
328
+ f"invalid long option string {opt!r}: "
329
+ "must start with --, followed by non-dash",
330
+ self,
331
+ )
332
+ self._long_opts.append(opt)
333
+
334
+ def __repr__(self) -> str:
335
+ args: list[str] = []
336
+ if self._short_opts:
337
+ args += ["_short_opts: " + repr(self._short_opts)]
338
+ if self._long_opts:
339
+ args += ["_long_opts: " + repr(self._long_opts)]
340
+ args += ["dest: " + repr(self.dest)]
341
+ if hasattr(self, "type"):
342
+ args += ["type: " + repr(self.type)]
343
+ if hasattr(self, "default"):
344
+ args += ["default: " + repr(self.default)]
345
+ return "Argument({})".format(", ".join(args))
346
+
347
+
348
+ class OptionGroup:
349
+ """A group of options shown in its own section."""
350
+
351
+ def __init__(
352
+ self,
353
+ name: str,
354
+ description: str = "",
355
+ parser: Parser | None = None,
356
+ *,
357
+ _ispytest: bool = False,
358
+ ) -> None:
359
+ check_ispytest(_ispytest)
360
+ self.name = name
361
+ self.description = description
362
+ self.options: list[Argument] = []
363
+ self.parser = parser
364
+
365
+ def addoption(self, *opts: str, **attrs: Any) -> None:
366
+ """Add an option to this group.
367
+
368
+ If a shortened version of a long option is specified, it will
369
+ be suppressed in the help. ``addoption('--twowords', '--two-words')``
370
+ results in help showing ``--two-words`` only, but ``--twowords`` gets
371
+ accepted **and** the automatic destination is in ``args.twowords``.
372
+
373
+ :param opts:
374
+ Option names, can be short or long options.
375
+ :param attrs:
376
+ Same attributes as the argparse library's :meth:`add_argument()
377
+ <argparse.ArgumentParser.add_argument>` function accepts.
378
+ """
379
+ conflict = set(opts).intersection(
380
+ name for opt in self.options for name in opt.names()
381
+ )
382
+ if conflict:
383
+ raise ValueError(f"option names {conflict} already added")
384
+ option = Argument(*opts, **attrs)
385
+ self._addoption_instance(option, shortupper=False)
386
+
387
+ def _addoption(self, *opts: str, **attrs: Any) -> None:
388
+ option = Argument(*opts, **attrs)
389
+ self._addoption_instance(option, shortupper=True)
390
+
391
+ def _addoption_instance(self, option: Argument, shortupper: bool = False) -> None:
392
+ if not shortupper:
393
+ for opt in option._short_opts:
394
+ if opt[0] == "-" and opt[1].islower():
395
+ raise ValueError("lowercase shortoptions reserved")
396
+ if self.parser:
397
+ self.parser.processoption(option)
398
+ self.options.append(option)
399
+
400
+
401
+ class MyOptionParser(argparse.ArgumentParser):
402
+ def __init__(
403
+ self,
404
+ parser: Parser,
405
+ extra_info: dict[str, Any] | None = None,
406
+ prog: str | None = None,
407
+ ) -> None:
408
+ self._parser = parser
409
+ super().__init__(
410
+ prog=prog,
411
+ usage=parser._usage,
412
+ add_help=False,
413
+ formatter_class=DropShorterLongHelpFormatter,
414
+ allow_abbrev=False,
415
+ fromfile_prefix_chars="@",
416
+ )
417
+ # extra_info is a dict of (param -> value) to display if there's
418
+ # an usage error to provide more contextual information to the user.
419
+ self.extra_info = extra_info if extra_info else {}
420
+
421
+ def error(self, message: str) -> NoReturn:
422
+ """Transform argparse error message into UsageError."""
423
+ msg = f"{self.prog}: error: {message}"
424
+
425
+ if hasattr(self._parser, "_config_source_hint"):
426
+ msg = f"{msg} ({self._parser._config_source_hint})"
427
+
428
+ raise UsageError(self.format_usage() + msg)
429
+
430
+ # Type ignored because typeshed has a very complex type in the superclass.
431
+ def parse_args( # type: ignore
432
+ self,
433
+ args: Sequence[str] | None = None,
434
+ namespace: argparse.Namespace | None = None,
435
+ ) -> argparse.Namespace:
436
+ """Allow splitting of positional arguments."""
437
+ parsed, unrecognized = self.parse_known_args(args, namespace)
438
+ if unrecognized:
439
+ for arg in unrecognized:
440
+ if arg and arg[0] == "-":
441
+ lines = [
442
+ "unrecognized arguments: {}".format(" ".join(unrecognized))
443
+ ]
444
+ for k, v in sorted(self.extra_info.items()):
445
+ lines.append(f" {k}: {v}")
446
+ self.error("\n".join(lines))
447
+ getattr(parsed, FILE_OR_DIR).extend(unrecognized)
448
+ return parsed
449
+
450
+ if sys.version_info < (3, 9): # pragma: no cover
451
+ # Backport of https://github.com/python/cpython/pull/14316 so we can
452
+ # disable long --argument abbreviations without breaking short flags.
453
+ def _parse_optional(
454
+ self, arg_string: str
455
+ ) -> tuple[argparse.Action | None, str, str | None] | None:
456
+ if not arg_string:
457
+ return None
458
+ if arg_string[0] not in self.prefix_chars:
459
+ return None
460
+ if arg_string in self._option_string_actions:
461
+ action = self._option_string_actions[arg_string]
462
+ return action, arg_string, None
463
+ if len(arg_string) == 1:
464
+ return None
465
+ if "=" in arg_string:
466
+ option_string, explicit_arg = arg_string.split("=", 1)
467
+ if option_string in self._option_string_actions:
468
+ action = self._option_string_actions[option_string]
469
+ return action, option_string, explicit_arg
470
+ if self.allow_abbrev or not arg_string.startswith("--"):
471
+ option_tuples = self._get_option_tuples(arg_string)
472
+ if len(option_tuples) > 1:
473
+ msg = gettext(
474
+ "ambiguous option: %(option)s could match %(matches)s"
475
+ )
476
+ options = ", ".join(option for _, option, _ in option_tuples)
477
+ self.error(msg % {"option": arg_string, "matches": options})
478
+ elif len(option_tuples) == 1:
479
+ (option_tuple,) = option_tuples
480
+ return option_tuple
481
+ if self._negative_number_matcher.match(arg_string):
482
+ if not self._has_negative_number_optionals:
483
+ return None
484
+ if " " in arg_string:
485
+ return None
486
+ return None, arg_string, None
487
+
488
+
489
+ class DropShorterLongHelpFormatter(argparse.HelpFormatter):
490
+ """Shorten help for long options that differ only in extra hyphens.
491
+
492
+ - Collapse **long** options that are the same except for extra hyphens.
493
+ - Shortcut if there are only two options and one of them is a short one.
494
+ - Cache result on the action object as this is called at least 2 times.
495
+ """
496
+
497
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
498
+ # Use more accurate terminal width.
499
+ if "width" not in kwargs:
500
+ kwargs["width"] = _pytest._io.get_terminal_width()
501
+ super().__init__(*args, **kwargs)
502
+
503
+ def _format_action_invocation(self, action: argparse.Action) -> str:
504
+ orgstr = super()._format_action_invocation(action)
505
+ if orgstr and orgstr[0] != "-": # only optional arguments
506
+ return orgstr
507
+ res: str | None = getattr(action, "_formatted_action_invocation", None)
508
+ if res:
509
+ return res
510
+ options = orgstr.split(", ")
511
+ if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
512
+ # a shortcut for '-h, --help' or '--abc', '-a'
513
+ action._formatted_action_invocation = orgstr # type: ignore
514
+ return orgstr
515
+ return_list = []
516
+ short_long: dict[str, str] = {}
517
+ for option in options:
518
+ if len(option) == 2 or option[2] == " ":
519
+ continue
520
+ if not option.startswith("--"):
521
+ raise ArgumentError(
522
+ f'long optional argument without "--": [{option}]', option
523
+ )
524
+ xxoption = option[2:]
525
+ shortened = xxoption.replace("-", "")
526
+ if shortened not in short_long or len(short_long[shortened]) < len(
527
+ xxoption
528
+ ):
529
+ short_long[shortened] = xxoption
530
+ # now short_long has been filled out to the longest with dashes
531
+ # **and** we keep the right option ordering from add_argument
532
+ for option in options:
533
+ if len(option) == 2 or option[2] == " ":
534
+ return_list.append(option)
535
+ if option[2:] == short_long.get(option.replace("-", "")):
536
+ return_list.append(option.replace(" ", "=", 1))
537
+ formatted_action_invocation = ", ".join(return_list)
538
+ action._formatted_action_invocation = formatted_action_invocation # type: ignore
539
+ return formatted_action_invocation
540
+
541
+ def _split_lines(self, text, width):
542
+ """Wrap lines after splitting on original newlines.
543
+
544
+ This allows to have explicit line breaks in the help text.
545
+ """
546
+ import textwrap
547
+
548
+ lines = []
549
+ for line in text.splitlines():
550
+ lines.extend(textwrap.wrap(line.strip(), width))
551
+ return lines
shared/package-files/74/74db386f628321c1b833584f06f0f4f7e561ec20f394f22b16c70e76f2f7a75a/blob ADDED
@@ -0,0 +1,988 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Auxiliary functions for f2py2e.
3
+
4
+ Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
5
+ Copyright 2011 -- present NumPy Developers.
6
+ Permission to use, modify, and distribute this software is given under the
7
+ terms of the NumPy (BSD style) LICENSE.
8
+
9
+ NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
10
+ """
11
+ import pprint
12
+ import sys
13
+ import re
14
+ import types
15
+ from functools import reduce
16
+ from copy import deepcopy
17
+
18
+ from . import __version__
19
+ from . import cfuncs
20
+
21
+ __all__ = [
22
+ 'applyrules', 'debugcapi', 'dictappend', 'errmess', 'gentitle',
23
+ 'getargs2', 'getcallprotoargument', 'getcallstatement',
24
+ 'getfortranname', 'getpymethoddef', 'getrestdoc', 'getusercode',
25
+ 'getusercode1', 'getdimension', 'hasbody', 'hascallstatement', 'hascommon',
26
+ 'hasexternals', 'hasinitvalue', 'hasnote', 'hasresultnote',
27
+ 'isallocatable', 'isarray', 'isarrayofstrings',
28
+ 'ischaracter', 'ischaracterarray', 'ischaracter_or_characterarray',
29
+ 'iscomplex',
30
+ 'iscomplexarray', 'iscomplexfunction', 'iscomplexfunction_warn',
31
+ 'isdouble', 'isdummyroutine', 'isexternal', 'isfunction',
32
+ 'isfunction_wrap', 'isint1', 'isint1array', 'isinteger', 'isintent_aux',
33
+ 'isintent_c', 'isintent_callback', 'isintent_copy', 'isintent_dict',
34
+ 'isintent_hide', 'isintent_in', 'isintent_inout', 'isintent_inplace',
35
+ 'isintent_nothide', 'isintent_out', 'isintent_overwrite', 'islogical',
36
+ 'islogicalfunction', 'islong_complex', 'islong_double',
37
+ 'islong_doublefunction', 'islong_long', 'islong_longfunction',
38
+ 'ismodule', 'ismoduleroutine', 'isoptional', 'isprivate', 'isrequired',
39
+ 'isroutine', 'isscalar', 'issigned_long_longarray', 'isstring',
40
+ 'isstringarray', 'isstring_or_stringarray', 'isstringfunction',
41
+ 'issubroutine', 'get_f2py_modulename',
42
+ 'issubroutine_wrap', 'isthreadsafe', 'isunsigned', 'isunsigned_char',
43
+ 'isunsigned_chararray', 'isunsigned_long_long',
44
+ 'isunsigned_long_longarray', 'isunsigned_short',
45
+ 'isunsigned_shortarray', 'l_and', 'l_not', 'l_or', 'outmess',
46
+ 'replace', 'show', 'stripcomma', 'throw_error', 'isattr_value',
47
+ 'getuseblocks', 'process_f2cmap_dict'
48
+ ]
49
+
50
+
51
+ f2py_version = __version__.version
52
+
53
+
54
+ errmess = sys.stderr.write
55
+ show = pprint.pprint
56
+
57
+ options = {}
58
+ debugoptions = []
59
+ wrapfuncs = 1
60
+
61
+
62
+ def outmess(t):
63
+ if options.get('verbose', 1):
64
+ sys.stdout.write(t)
65
+
66
+
67
+ def debugcapi(var):
68
+ return 'capi' in debugoptions
69
+
70
+
71
+ def _ischaracter(var):
72
+ return 'typespec' in var and var['typespec'] == 'character' and \
73
+ not isexternal(var)
74
+
75
+
76
+ def _isstring(var):
77
+ return 'typespec' in var and var['typespec'] == 'character' and \
78
+ not isexternal(var)
79
+
80
+
81
+ def ischaracter_or_characterarray(var):
82
+ return _ischaracter(var) and 'charselector' not in var
83
+
84
+
85
+ def ischaracter(var):
86
+ return ischaracter_or_characterarray(var) and not isarray(var)
87
+
88
+
89
+ def ischaracterarray(var):
90
+ return ischaracter_or_characterarray(var) and isarray(var)
91
+
92
+
93
+ def isstring_or_stringarray(var):
94
+ return _ischaracter(var) and 'charselector' in var
95
+
96
+
97
+ def isstring(var):
98
+ return isstring_or_stringarray(var) and not isarray(var)
99
+
100
+
101
+ def isstringarray(var):
102
+ return isstring_or_stringarray(var) and isarray(var)
103
+
104
+
105
+ def isarrayofstrings(var): # obsolete?
106
+ # leaving out '*' for now so that `character*(*) a(m)` and `character
107
+ # a(m,*)` are treated differently. Luckily `character**` is illegal.
108
+ return isstringarray(var) and var['dimension'][-1] == '(*)'
109
+
110
+
111
+ def isarray(var):
112
+ return 'dimension' in var and not isexternal(var)
113
+
114
+
115
+ def isscalar(var):
116
+ return not (isarray(var) or isstring(var) or isexternal(var))
117
+
118
+
119
+ def iscomplex(var):
120
+ return isscalar(var) and \
121
+ var.get('typespec') in ['complex', 'double complex']
122
+
123
+
124
+ def islogical(var):
125
+ return isscalar(var) and var.get('typespec') == 'logical'
126
+
127
+
128
+ def isinteger(var):
129
+ return isscalar(var) and var.get('typespec') == 'integer'
130
+
131
+
132
+ def isreal(var):
133
+ return isscalar(var) and var.get('typespec') == 'real'
134
+
135
+
136
+ def get_kind(var):
137
+ try:
138
+ return var['kindselector']['*']
139
+ except KeyError:
140
+ try:
141
+ return var['kindselector']['kind']
142
+ except KeyError:
143
+ pass
144
+
145
+
146
+ def isint1(var):
147
+ return var.get('typespec') == 'integer' \
148
+ and get_kind(var) == '1' and not isarray(var)
149
+
150
+
151
+ def islong_long(var):
152
+ if not isscalar(var):
153
+ return 0
154
+ if var.get('typespec') not in ['integer', 'logical']:
155
+ return 0
156
+ return get_kind(var) == '8'
157
+
158
+
159
+ def isunsigned_char(var):
160
+ if not isscalar(var):
161
+ return 0
162
+ if var.get('typespec') != 'integer':
163
+ return 0
164
+ return get_kind(var) == '-1'
165
+
166
+
167
+ def isunsigned_short(var):
168
+ if not isscalar(var):
169
+ return 0
170
+ if var.get('typespec') != 'integer':
171
+ return 0
172
+ return get_kind(var) == '-2'
173
+
174
+
175
+ def isunsigned(var):
176
+ if not isscalar(var):
177
+ return 0
178
+ if var.get('typespec') != 'integer':
179
+ return 0
180
+ return get_kind(var) == '-4'
181
+
182
+
183
+ def isunsigned_long_long(var):
184
+ if not isscalar(var):
185
+ return 0
186
+ if var.get('typespec') != 'integer':
187
+ return 0
188
+ return get_kind(var) == '-8'
189
+
190
+
191
+ def isdouble(var):
192
+ if not isscalar(var):
193
+ return 0
194
+ if not var.get('typespec') == 'real':
195
+ return 0
196
+ return get_kind(var) == '8'
197
+
198
+
199
+ def islong_double(var):
200
+ if not isscalar(var):
201
+ return 0
202
+ if not var.get('typespec') == 'real':
203
+ return 0
204
+ return get_kind(var) == '16'
205
+
206
+
207
+ def islong_complex(var):
208
+ if not iscomplex(var):
209
+ return 0
210
+ return get_kind(var) == '32'
211
+
212
+
213
+ def iscomplexarray(var):
214
+ return isarray(var) and \
215
+ var.get('typespec') in ['complex', 'double complex']
216
+
217
+
218
+ def isint1array(var):
219
+ return isarray(var) and var.get('typespec') == 'integer' \
220
+ and get_kind(var) == '1'
221
+
222
+
223
+ def isunsigned_chararray(var):
224
+ return isarray(var) and var.get('typespec') in ['integer', 'logical']\
225
+ and get_kind(var) == '-1'
226
+
227
+
228
+ def isunsigned_shortarray(var):
229
+ return isarray(var) and var.get('typespec') in ['integer', 'logical']\
230
+ and get_kind(var) == '-2'
231
+
232
+
233
+ def isunsignedarray(var):
234
+ return isarray(var) and var.get('typespec') in ['integer', 'logical']\
235
+ and get_kind(var) == '-4'
236
+
237
+
238
+ def isunsigned_long_longarray(var):
239
+ return isarray(var) and var.get('typespec') in ['integer', 'logical']\
240
+ and get_kind(var) == '-8'
241
+
242
+
243
+ def issigned_chararray(var):
244
+ return isarray(var) and var.get('typespec') in ['integer', 'logical']\
245
+ and get_kind(var) == '1'
246
+
247
+
248
+ def issigned_shortarray(var):
249
+ return isarray(var) and var.get('typespec') in ['integer', 'logical']\
250
+ and get_kind(var) == '2'
251
+
252
+
253
+ def issigned_array(var):
254
+ return isarray(var) and var.get('typespec') in ['integer', 'logical']\
255
+ and get_kind(var) == '4'
256
+
257
+
258
+ def issigned_long_longarray(var):
259
+ return isarray(var) and var.get('typespec') in ['integer', 'logical']\
260
+ and get_kind(var) == '8'
261
+
262
+
263
+ def isallocatable(var):
264
+ return 'attrspec' in var and 'allocatable' in var['attrspec']
265
+
266
+
267
+ def ismutable(var):
268
+ return not ('dimension' not in var or isstring(var))
269
+
270
+
271
+ def ismoduleroutine(rout):
272
+ return 'modulename' in rout
273
+
274
+
275
+ def ismodule(rout):
276
+ return 'block' in rout and 'module' == rout['block']
277
+
278
+
279
+ def isfunction(rout):
280
+ return 'block' in rout and 'function' == rout['block']
281
+
282
+
283
+ def isfunction_wrap(rout):
284
+ if isintent_c(rout):
285
+ return 0
286
+ return wrapfuncs and isfunction(rout) and (not isexternal(rout))
287
+
288
+
289
+ def issubroutine(rout):
290
+ return 'block' in rout and 'subroutine' == rout['block']
291
+
292
+
293
+ def issubroutine_wrap(rout):
294
+ if isintent_c(rout):
295
+ return 0
296
+ return issubroutine(rout) and hasassumedshape(rout)
297
+
298
+ def isattr_value(var):
299
+ return 'value' in var.get('attrspec', [])
300
+
301
+
302
+ def hasassumedshape(rout):
303
+ if rout.get('hasassumedshape'):
304
+ return True
305
+ for a in rout['args']:
306
+ for d in rout['vars'].get(a, {}).get('dimension', []):
307
+ if d == ':':
308
+ rout['hasassumedshape'] = True
309
+ return True
310
+ return False
311
+
312
+
313
+ def requiresf90wrapper(rout):
314
+ return ismoduleroutine(rout) or hasassumedshape(rout)
315
+
316
+
317
+ def isroutine(rout):
318
+ return isfunction(rout) or issubroutine(rout)
319
+
320
+
321
+ def islogicalfunction(rout):
322
+ if not isfunction(rout):
323
+ return 0
324
+ if 'result' in rout:
325
+ a = rout['result']
326
+ else:
327
+ a = rout['name']
328
+ if a in rout['vars']:
329
+ return islogical(rout['vars'][a])
330
+ return 0
331
+
332
+
333
+ def islong_longfunction(rout):
334
+ if not isfunction(rout):
335
+ return 0
336
+ if 'result' in rout:
337
+ a = rout['result']
338
+ else:
339
+ a = rout['name']
340
+ if a in rout['vars']:
341
+ return islong_long(rout['vars'][a])
342
+ return 0
343
+
344
+
345
+ def islong_doublefunction(rout):
346
+ if not isfunction(rout):
347
+ return 0
348
+ if 'result' in rout:
349
+ a = rout['result']
350
+ else:
351
+ a = rout['name']
352
+ if a in rout['vars']:
353
+ return islong_double(rout['vars'][a])
354
+ return 0
355
+
356
+
357
+ def iscomplexfunction(rout):
358
+ if not isfunction(rout):
359
+ return 0
360
+ if 'result' in rout:
361
+ a = rout['result']
362
+ else:
363
+ a = rout['name']
364
+ if a in rout['vars']:
365
+ return iscomplex(rout['vars'][a])
366
+ return 0
367
+
368
+
369
+ def iscomplexfunction_warn(rout):
370
+ if iscomplexfunction(rout):
371
+ outmess("""\
372
+ **************************************************************
373
+ Warning: code with a function returning complex value
374
+ may not work correctly with your Fortran compiler.
375
+ When using GNU gcc/g77 compilers, codes should work
376
+ correctly for callbacks with:
377
+ f2py -c -DF2PY_CB_RETURNCOMPLEX
378
+ **************************************************************\n""")
379
+ return 1
380
+ return 0
381
+
382
+
383
+ def isstringfunction(rout):
384
+ if not isfunction(rout):
385
+ return 0
386
+ if 'result' in rout:
387
+ a = rout['result']
388
+ else:
389
+ a = rout['name']
390
+ if a in rout['vars']:
391
+ return isstring(rout['vars'][a])
392
+ return 0
393
+
394
+
395
+ def hasexternals(rout):
396
+ return 'externals' in rout and rout['externals']
397
+
398
+
399
+ def isthreadsafe(rout):
400
+ return 'f2pyenhancements' in rout and \
401
+ 'threadsafe' in rout['f2pyenhancements']
402
+
403
+
404
+ def hasvariables(rout):
405
+ return 'vars' in rout and rout['vars']
406
+
407
+
408
+ def isoptional(var):
409
+ return ('attrspec' in var and 'optional' in var['attrspec'] and
410
+ 'required' not in var['attrspec']) and isintent_nothide(var)
411
+
412
+
413
+ def isexternal(var):
414
+ return 'attrspec' in var and 'external' in var['attrspec']
415
+
416
+
417
+ def getdimension(var):
418
+ dimpattern = r"\((.*?)\)"
419
+ if 'attrspec' in var.keys():
420
+ if any('dimension' in s for s in var['attrspec']):
421
+ return [re.findall(dimpattern, v) for v in var['attrspec']][0]
422
+
423
+
424
+ def isrequired(var):
425
+ return not isoptional(var) and isintent_nothide(var)
426
+
427
+
428
+ def isintent_in(var):
429
+ if 'intent' not in var:
430
+ return 1
431
+ if 'hide' in var['intent']:
432
+ return 0
433
+ if 'inplace' in var['intent']:
434
+ return 0
435
+ if 'in' in var['intent']:
436
+ return 1
437
+ if 'out' in var['intent']:
438
+ return 0
439
+ if 'inout' in var['intent']:
440
+ return 0
441
+ if 'outin' in var['intent']:
442
+ return 0
443
+ return 1
444
+
445
+
446
+ def isintent_inout(var):
447
+ return ('intent' in var and ('inout' in var['intent'] or
448
+ 'outin' in var['intent']) and 'in' not in var['intent'] and
449
+ 'hide' not in var['intent'] and 'inplace' not in var['intent'])
450
+
451
+
452
+ def isintent_out(var):
453
+ return 'out' in var.get('intent', [])
454
+
455
+
456
+ def isintent_hide(var):
457
+ return ('intent' in var and ('hide' in var['intent'] or
458
+ ('out' in var['intent'] and 'in' not in var['intent'] and
459
+ (not l_or(isintent_inout, isintent_inplace)(var)))))
460
+
461
+
462
+ def isintent_nothide(var):
463
+ return not isintent_hide(var)
464
+
465
+
466
+ def isintent_c(var):
467
+ return 'c' in var.get('intent', [])
468
+
469
+
470
+ def isintent_cache(var):
471
+ return 'cache' in var.get('intent', [])
472
+
473
+
474
+ def isintent_copy(var):
475
+ return 'copy' in var.get('intent', [])
476
+
477
+
478
+ def isintent_overwrite(var):
479
+ return 'overwrite' in var.get('intent', [])
480
+
481
+
482
+ def isintent_callback(var):
483
+ return 'callback' in var.get('intent', [])
484
+
485
+
486
+ def isintent_inplace(var):
487
+ return 'inplace' in var.get('intent', [])
488
+
489
+
490
+ def isintent_aux(var):
491
+ return 'aux' in var.get('intent', [])
492
+
493
+
494
+ def isintent_aligned4(var):
495
+ return 'aligned4' in var.get('intent', [])
496
+
497
+
498
+ def isintent_aligned8(var):
499
+ return 'aligned8' in var.get('intent', [])
500
+
501
+
502
+ def isintent_aligned16(var):
503
+ return 'aligned16' in var.get('intent', [])
504
+
505
+
506
+ isintent_dict = {isintent_in: 'INTENT_IN', isintent_inout: 'INTENT_INOUT',
507
+ isintent_out: 'INTENT_OUT', isintent_hide: 'INTENT_HIDE',
508
+ isintent_cache: 'INTENT_CACHE',
509
+ isintent_c: 'INTENT_C', isoptional: 'OPTIONAL',
510
+ isintent_inplace: 'INTENT_INPLACE',
511
+ isintent_aligned4: 'INTENT_ALIGNED4',
512
+ isintent_aligned8: 'INTENT_ALIGNED8',
513
+ isintent_aligned16: 'INTENT_ALIGNED16',
514
+ }
515
+
516
+
517
+ def isprivate(var):
518
+ return 'attrspec' in var and 'private' in var['attrspec']
519
+
520
+
521
+ def hasinitvalue(var):
522
+ return '=' in var
523
+
524
+
525
+ def hasinitvalueasstring(var):
526
+ if not hasinitvalue(var):
527
+ return 0
528
+ return var['='][0] in ['"', "'"]
529
+
530
+
531
+ def hasnote(var):
532
+ return 'note' in var
533
+
534
+
535
+ def hasresultnote(rout):
536
+ if not isfunction(rout):
537
+ return 0
538
+ if 'result' in rout:
539
+ a = rout['result']
540
+ else:
541
+ a = rout['name']
542
+ if a in rout['vars']:
543
+ return hasnote(rout['vars'][a])
544
+ return 0
545
+
546
+
547
+ def hascommon(rout):
548
+ return 'common' in rout
549
+
550
+
551
+ def containscommon(rout):
552
+ if hascommon(rout):
553
+ return 1
554
+ if hasbody(rout):
555
+ for b in rout['body']:
556
+ if containscommon(b):
557
+ return 1
558
+ return 0
559
+
560
+
561
+ def containsmodule(block):
562
+ if ismodule(block):
563
+ return 1
564
+ if not hasbody(block):
565
+ return 0
566
+ for b in block['body']:
567
+ if containsmodule(b):
568
+ return 1
569
+ return 0
570
+
571
+
572
+ def hasbody(rout):
573
+ return 'body' in rout
574
+
575
+
576
+ def hascallstatement(rout):
577
+ return getcallstatement(rout) is not None
578
+
579
+
580
+ def istrue(var):
581
+ return 1
582
+
583
+
584
+ def isfalse(var):
585
+ return 0
586
+
587
+
588
+ class F2PYError(Exception):
589
+ pass
590
+
591
+
592
+ class throw_error:
593
+
594
+ def __init__(self, mess):
595
+ self.mess = mess
596
+
597
+ def __call__(self, var):
598
+ mess = '\n\n var = %s\n Message: %s\n' % (var, self.mess)
599
+ raise F2PYError(mess)
600
+
601
+
602
+ def l_and(*f):
603
+ l1, l2 = 'lambda v', []
604
+ for i in range(len(f)):
605
+ l1 = '%s,f%d=f[%d]' % (l1, i, i)
606
+ l2.append('f%d(v)' % (i))
607
+ return eval('%s:%s' % (l1, ' and '.join(l2)))
608
+
609
+
610
+ def l_or(*f):
611
+ l1, l2 = 'lambda v', []
612
+ for i in range(len(f)):
613
+ l1 = '%s,f%d=f[%d]' % (l1, i, i)
614
+ l2.append('f%d(v)' % (i))
615
+ return eval('%s:%s' % (l1, ' or '.join(l2)))
616
+
617
+
618
+ def l_not(f):
619
+ return eval('lambda v,f=f:not f(v)')
620
+
621
+
622
+ def isdummyroutine(rout):
623
+ try:
624
+ return rout['f2pyenhancements']['fortranname'] == ''
625
+ except KeyError:
626
+ return 0
627
+
628
+
629
+ def getfortranname(rout):
630
+ try:
631
+ name = rout['f2pyenhancements']['fortranname']
632
+ if name == '':
633
+ raise KeyError
634
+ if not name:
635
+ errmess('Failed to use fortranname from %s\n' %
636
+ (rout['f2pyenhancements']))
637
+ raise KeyError
638
+ except KeyError:
639
+ name = rout['name']
640
+ return name
641
+
642
+
643
+ def getmultilineblock(rout, blockname, comment=1, counter=0):
644
+ try:
645
+ r = rout['f2pyenhancements'].get(blockname)
646
+ except KeyError:
647
+ return
648
+ if not r:
649
+ return
650
+ if counter > 0 and isinstance(r, str):
651
+ return
652
+ if isinstance(r, list):
653
+ if counter >= len(r):
654
+ return
655
+ r = r[counter]
656
+ if r[:3] == "'''":
657
+ if comment:
658
+ r = '\t/* start ' + blockname + \
659
+ ' multiline (' + repr(counter) + ') */\n' + r[3:]
660
+ else:
661
+ r = r[3:]
662
+ if r[-3:] == "'''":
663
+ if comment:
664
+ r = r[:-3] + '\n\t/* end multiline (' + repr(counter) + ')*/'
665
+ else:
666
+ r = r[:-3]
667
+ else:
668
+ errmess("%s multiline block should end with `'''`: %s\n"
669
+ % (blockname, repr(r)))
670
+ return r
671
+
672
+
673
+ def getcallstatement(rout):
674
+ return getmultilineblock(rout, 'callstatement')
675
+
676
+
677
+ def getcallprotoargument(rout, cb_map={}):
678
+ r = getmultilineblock(rout, 'callprotoargument', comment=0)
679
+ if r:
680
+ return r
681
+ if hascallstatement(rout):
682
+ outmess(
683
+ 'warning: callstatement is defined without callprotoargument\n')
684
+ return
685
+ from .capi_maps import getctype
686
+ arg_types, arg_types2 = [], []
687
+ if l_and(isstringfunction, l_not(isfunction_wrap))(rout):
688
+ arg_types.extend(['char*', 'size_t'])
689
+ for n in rout['args']:
690
+ var = rout['vars'][n]
691
+ if isintent_callback(var):
692
+ continue
693
+ if n in cb_map:
694
+ ctype = cb_map[n] + '_typedef'
695
+ else:
696
+ ctype = getctype(var)
697
+ if l_and(isintent_c, l_or(isscalar, iscomplex))(var):
698
+ pass
699
+ elif isstring(var):
700
+ pass
701
+ else:
702
+ if not isattr_value(var):
703
+ ctype = ctype + '*'
704
+ if ((isstring(var)
705
+ or isarrayofstrings(var) # obsolete?
706
+ or isstringarray(var))):
707
+ arg_types2.append('size_t')
708
+ arg_types.append(ctype)
709
+
710
+ proto_args = ','.join(arg_types + arg_types2)
711
+ if not proto_args:
712
+ proto_args = 'void'
713
+ return proto_args
714
+
715
+
716
+ def getusercode(rout):
717
+ return getmultilineblock(rout, 'usercode')
718
+
719
+
720
+ def getusercode1(rout):
721
+ return getmultilineblock(rout, 'usercode', counter=1)
722
+
723
+
724
+ def getpymethoddef(rout):
725
+ return getmultilineblock(rout, 'pymethoddef')
726
+
727
+
728
+ def getargs(rout):
729
+ sortargs, args = [], []
730
+ if 'args' in rout:
731
+ args = rout['args']
732
+ if 'sortvars' in rout:
733
+ for a in rout['sortvars']:
734
+ if a in args:
735
+ sortargs.append(a)
736
+ for a in args:
737
+ if a not in sortargs:
738
+ sortargs.append(a)
739
+ else:
740
+ sortargs = rout['args']
741
+ return args, sortargs
742
+
743
+
744
+ def getargs2(rout):
745
+ sortargs, args = [], rout.get('args', [])
746
+ auxvars = [a for a in rout['vars'].keys() if isintent_aux(rout['vars'][a])
747
+ and a not in args]
748
+ args = auxvars + args
749
+ if 'sortvars' in rout:
750
+ for a in rout['sortvars']:
751
+ if a in args:
752
+ sortargs.append(a)
753
+ for a in args:
754
+ if a not in sortargs:
755
+ sortargs.append(a)
756
+ else:
757
+ sortargs = auxvars + rout['args']
758
+ return args, sortargs
759
+
760
+
761
+ def getrestdoc(rout):
762
+ if 'f2pymultilines' not in rout:
763
+ return None
764
+ k = None
765
+ if rout['block'] == 'python module':
766
+ k = rout['block'], rout['name']
767
+ return rout['f2pymultilines'].get(k, None)
768
+
769
+
770
+ def gentitle(name):
771
+ ln = (80 - len(name) - 6) // 2
772
+ return '/*%s %s %s*/' % (ln * '*', name, ln * '*')
773
+
774
+
775
+ def flatlist(lst):
776
+ if isinstance(lst, list):
777
+ return reduce(lambda x, y, f=flatlist: x + f(y), lst, [])
778
+ return [lst]
779
+
780
+
781
+ def stripcomma(s):
782
+ if s and s[-1] == ',':
783
+ return s[:-1]
784
+ return s
785
+
786
+
787
+ def replace(str, d, defaultsep=''):
788
+ if isinstance(d, list):
789
+ return [replace(str, _m, defaultsep) for _m in d]
790
+ if isinstance(str, list):
791
+ return [replace(_m, d, defaultsep) for _m in str]
792
+ for k in 2 * list(d.keys()):
793
+ if k == 'separatorsfor':
794
+ continue
795
+ if 'separatorsfor' in d and k in d['separatorsfor']:
796
+ sep = d['separatorsfor'][k]
797
+ else:
798
+ sep = defaultsep
799
+ if isinstance(d[k], list):
800
+ str = str.replace('#%s#' % (k), sep.join(flatlist(d[k])))
801
+ else:
802
+ str = str.replace('#%s#' % (k), d[k])
803
+ return str
804
+
805
+
806
+ def dictappend(rd, ar):
807
+ if isinstance(ar, list):
808
+ for a in ar:
809
+ rd = dictappend(rd, a)
810
+ return rd
811
+ for k in ar.keys():
812
+ if k[0] == '_':
813
+ continue
814
+ if k in rd:
815
+ if isinstance(rd[k], str):
816
+ rd[k] = [rd[k]]
817
+ if isinstance(rd[k], list):
818
+ if isinstance(ar[k], list):
819
+ rd[k] = rd[k] + ar[k]
820
+ else:
821
+ rd[k].append(ar[k])
822
+ elif isinstance(rd[k], dict):
823
+ if isinstance(ar[k], dict):
824
+ if k == 'separatorsfor':
825
+ for k1 in ar[k].keys():
826
+ if k1 not in rd[k]:
827
+ rd[k][k1] = ar[k][k1]
828
+ else:
829
+ rd[k] = dictappend(rd[k], ar[k])
830
+ else:
831
+ rd[k] = ar[k]
832
+ return rd
833
+
834
+
835
+ def applyrules(rules, d, var={}):
836
+ ret = {}
837
+ if isinstance(rules, list):
838
+ for r in rules:
839
+ rr = applyrules(r, d, var)
840
+ ret = dictappend(ret, rr)
841
+ if '_break' in rr:
842
+ break
843
+ return ret
844
+ if '_check' in rules and (not rules['_check'](var)):
845
+ return ret
846
+ if 'need' in rules:
847
+ res = applyrules({'needs': rules['need']}, d, var)
848
+ if 'needs' in res:
849
+ cfuncs.append_needs(res['needs'])
850
+
851
+ for k in rules.keys():
852
+ if k == 'separatorsfor':
853
+ ret[k] = rules[k]
854
+ continue
855
+ if isinstance(rules[k], str):
856
+ ret[k] = replace(rules[k], d)
857
+ elif isinstance(rules[k], list):
858
+ ret[k] = []
859
+ for i in rules[k]:
860
+ ar = applyrules({k: i}, d, var)
861
+ if k in ar:
862
+ ret[k].append(ar[k])
863
+ elif k[0] == '_':
864
+ continue
865
+ elif isinstance(rules[k], dict):
866
+ ret[k] = []
867
+ for k1 in rules[k].keys():
868
+ if isinstance(k1, types.FunctionType) and k1(var):
869
+ if isinstance(rules[k][k1], list):
870
+ for i in rules[k][k1]:
871
+ if isinstance(i, dict):
872
+ res = applyrules({'supertext': i}, d, var)
873
+ if 'supertext' in res:
874
+ i = res['supertext']
875
+ else:
876
+ i = ''
877
+ ret[k].append(replace(i, d))
878
+ else:
879
+ i = rules[k][k1]
880
+ if isinstance(i, dict):
881
+ res = applyrules({'supertext': i}, d)
882
+ if 'supertext' in res:
883
+ i = res['supertext']
884
+ else:
885
+ i = ''
886
+ ret[k].append(replace(i, d))
887
+ else:
888
+ errmess('applyrules: ignoring rule %s.\n' % repr(rules[k]))
889
+ if isinstance(ret[k], list):
890
+ if len(ret[k]) == 1:
891
+ ret[k] = ret[k][0]
892
+ if ret[k] == []:
893
+ del ret[k]
894
+ return ret
895
+
896
+ _f2py_module_name_match = re.compile(r'\s*python\s*module\s*(?P<name>[\w_]+)',
897
+ re.I).match
898
+ _f2py_user_module_name_match = re.compile(r'\s*python\s*module\s*(?P<name>[\w_]*?'
899
+ r'__user__[\w_]*)', re.I).match
900
+
901
+ def get_f2py_modulename(source):
902
+ name = None
903
+ with open(source) as f:
904
+ for line in f:
905
+ m = _f2py_module_name_match(line)
906
+ if m:
907
+ if _f2py_user_module_name_match(line): # skip *__user__* names
908
+ continue
909
+ name = m.group('name')
910
+ break
911
+ return name
912
+
913
+ def getuseblocks(pymod):
914
+ all_uses = []
915
+ for inner in pymod['body']:
916
+ for modblock in inner['body']:
917
+ if modblock.get('use'):
918
+ all_uses.extend([x for x in modblock.get("use").keys() if "__" not in x])
919
+ return all_uses
920
+
921
+ def process_f2cmap_dict(f2cmap_all, new_map, c2py_map, verbose = False):
922
+ """
923
+ Update the Fortran-to-C type mapping dictionary with new mappings and
924
+ return a list of successfully mapped C types.
925
+
926
+ This function integrates a new mapping dictionary into an existing
927
+ Fortran-to-C type mapping dictionary. It ensures that all keys are in
928
+ lowercase and validates new entries against a given C-to-Python mapping
929
+ dictionary. Redefinitions and invalid entries are reported with a warning.
930
+
931
+ Parameters
932
+ ----------
933
+ f2cmap_all : dict
934
+ The existing Fortran-to-C type mapping dictionary that will be updated.
935
+ It should be a dictionary of dictionaries where the main keys represent
936
+ Fortran types and the nested dictionaries map Fortran type specifiers
937
+ to corresponding C types.
938
+
939
+ new_map : dict
940
+ A dictionary containing new type mappings to be added to `f2cmap_all`.
941
+ The structure should be similar to `f2cmap_all`, with keys representing
942
+ Fortran types and values being dictionaries of type specifiers and their
943
+ C type equivalents.
944
+
945
+ c2py_map : dict
946
+ A dictionary used for validating the C types in `new_map`. It maps C
947
+ types to corresponding Python types and is used to ensure that the C
948
+ types specified in `new_map` are valid.
949
+
950
+ verbose : boolean
951
+ A flag used to provide information about the types mapped
952
+
953
+ Returns
954
+ -------
955
+ tuple of (dict, list)
956
+ The updated Fortran-to-C type mapping dictionary and a list of
957
+ successfully mapped C types.
958
+ """
959
+ f2cmap_mapped = []
960
+
961
+ new_map_lower = {}
962
+ for k, d1 in new_map.items():
963
+ d1_lower = {k1.lower(): v1 for k1, v1 in d1.items()}
964
+ new_map_lower[k.lower()] = d1_lower
965
+
966
+ for k, d1 in new_map_lower.items():
967
+ if k not in f2cmap_all:
968
+ f2cmap_all[k] = {}
969
+
970
+ for k1, v1 in d1.items():
971
+ if v1 in c2py_map:
972
+ if k1 in f2cmap_all[k]:
973
+ outmess(
974
+ "\tWarning: redefinition of {'%s':{'%s':'%s'->'%s'}}\n"
975
+ % (k, k1, f2cmap_all[k][k1], v1)
976
+ )
977
+ f2cmap_all[k][k1] = v1
978
+ if verbose:
979
+ outmess('\tMapping "%s(kind=%s)" to "%s"\n' % (k, k1, v1))
980
+ f2cmap_mapped.append(v1)
981
+ else:
982
+ if verbose:
983
+ errmess(
984
+ "\tIgnoring map {'%s':{'%s':'%s'}}: '%s' must be in %s\n"
985
+ % (k, k1, v1, v1, list(c2py_map.keys()))
986
+ )
987
+
988
+ return f2cmap_all, f2cmap_mapped
shared/package-files/74/74dfbdd489c7257280129e4310ebc2f1baa5ee71feac829ef373bc0d40f3d15a/blob ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 bartlett_window(int64_t window_length, c10::optional<at::ScalarType> dtype={}, c10::optional<at::Layout> layout={}, c10::optional<at::Device> device={}, c10::optional<bool> pin_memory={});
20
+ TORCH_API at::Tensor & bartlett_window_out(int64_t window_length, at::Tensor & out);
21
+ TORCH_API at::Tensor bartlett_window(int64_t window_length, bool periodic, c10::optional<at::ScalarType> dtype={}, c10::optional<at::Layout> layout={}, c10::optional<at::Device> device={}, c10::optional<bool> pin_memory={});
22
+ TORCH_API at::Tensor & bartlett_window_periodic_out(int64_t window_length, bool periodic, at::Tensor & out);
23
+ } // namespace native
24
+ } // namespace at
shared/package-files/74/74e2d737140952e364e42db839d1c1aef4e603493ae640b9d73ddd0f98163b30/blob ADDED
Binary file (1.33 kB). View file
 
shared/package-files/74/74e2d8d3c19397adbd9941224533e5fe224ed877384e632ee23fe65f7851fd38/blob 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 cpu {
19
+
20
+ TORCH_API at::Tensor special_modified_bessel_k1(const at::Tensor & self);
21
+ TORCH_API at::Tensor & special_modified_bessel_k1_out(at::Tensor & out, const at::Tensor & self);
22
+ TORCH_API at::Tensor & special_modified_bessel_k1_outf(const at::Tensor & self, at::Tensor & out);
23
+
24
+ } // namespace cpu
25
+ } // namespace at
shared/package-files/74/74ed196010d4867d7f963ce3724114d8b52f26ee4bb73bf988c1c08dc85343f8/blob ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *** Tue, 21 Jun 2016 11:30:21 ***
2
+ VECM MODEL STATISTICS
3
+ sample range: [1973 Q2, 1998 Q4], T = 103
4
+
5
+ Log Likelihood: 7.940801e+02
6
+ Determinant (Cov): 5.929254e-10
7
+
8
+ Covariance: 2.303948e-05 -1.480276e-06
9
+ -1.480276e-06 2.583030e-05
10
+
11
+ Correlation: 1.000000e+00 -6.067946e-02
12
+ -6.067946e-02 1.000000e+00
13
+
14
+
shared/package-files/74/74ed1bf4c7053d42d37e786969414fcb4dfc648f22430a361720ed8f877d3293/blob ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import builtins
2
+ import keyword
3
+ import re
4
+ import time
5
+
6
+ from idlelib.config import idleConf
7
+ from idlelib.delegator import Delegator
8
+
9
+ DEBUG = False
10
+
11
+
12
+ def any(name, alternates):
13
+ "Return a named group pattern matching list of alternates."
14
+ return "(?P<%s>" % name + "|".join(alternates) + ")"
15
+
16
+
17
+ def make_pat():
18
+ kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b"
19
+ match_softkw = (
20
+ r"^[ \t]*" + # at beginning of line + possible indentation
21
+ r"(?P<MATCH_SOFTKW>match)\b" +
22
+ r"(?![ \t]*(?:" + "|".join([ # not followed by ...
23
+ r"[:,;=^&|@~)\]}]", # a character which means it can't be a
24
+ # pattern-matching statement
25
+ r"\b(?:" + r"|".join(keyword.kwlist) + r")\b", # a keyword
26
+ ]) +
27
+ r"))"
28
+ )
29
+ case_default = (
30
+ r"^[ \t]*" + # at beginning of line + possible indentation
31
+ r"(?P<CASE_SOFTKW>case)" +
32
+ r"[ \t]+(?P<CASE_DEFAULT_UNDERSCORE>_\b)"
33
+ )
34
+ case_softkw_and_pattern = (
35
+ r"^[ \t]*" + # at beginning of line + possible indentation
36
+ r"(?P<CASE_SOFTKW2>case)\b" +
37
+ r"(?![ \t]*(?:" + "|".join([ # not followed by ...
38
+ r"_\b", # a lone underscore
39
+ r"[:,;=^&|@~)\]}]", # a character which means it can't be a
40
+ # pattern-matching case
41
+ r"\b(?:" + r"|".join(keyword.kwlist) + r")\b", # a keyword
42
+ ]) +
43
+ r"))"
44
+ )
45
+ builtinlist = [str(name) for name in dir(builtins)
46
+ if not name.startswith('_') and
47
+ name not in keyword.kwlist]
48
+ builtin = r"([^.'\"\\#]\b|^)" + any("BUILTIN", builtinlist) + r"\b"
49
+ comment = any("COMMENT", [r"#[^\n]*"])
50
+ stringprefix = r"(?i:r|u|f|fr|rf|b|br|rb)?"
51
+ sqstring = stringprefix + r"'[^'\\\n]*(\\.[^'\\\n]*)*'?"
52
+ dqstring = stringprefix + r'"[^"\\\n]*(\\.[^"\\\n]*)*"?'
53
+ sq3string = stringprefix + r"'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?"
54
+ dq3string = stringprefix + r'"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?'
55
+ string = any("STRING", [sq3string, dq3string, sqstring, dqstring])
56
+ prog = re.compile("|".join([
57
+ builtin, comment, string, kw,
58
+ match_softkw, case_default,
59
+ case_softkw_and_pattern,
60
+ any("SYNC", [r"\n"]),
61
+ ]),
62
+ re.DOTALL | re.MULTILINE)
63
+ return prog
64
+
65
+
66
+ prog = make_pat()
67
+ idprog = re.compile(r"\s+(\w+)")
68
+ prog_group_name_to_tag = {
69
+ "MATCH_SOFTKW": "KEYWORD",
70
+ "CASE_SOFTKW": "KEYWORD",
71
+ "CASE_DEFAULT_UNDERSCORE": "KEYWORD",
72
+ "CASE_SOFTKW2": "KEYWORD",
73
+ }
74
+
75
+
76
+ def matched_named_groups(re_match):
77
+ "Get only the non-empty named groups from an re.Match object."
78
+ return ((k, v) for (k, v) in re_match.groupdict().items() if v)
79
+
80
+
81
+ def color_config(text):
82
+ """Set color options of Text widget.
83
+
84
+ If ColorDelegator is used, this should be called first.
85
+ """
86
+ # Called from htest, TextFrame, Editor, and Turtledemo.
87
+ # Not automatic because ColorDelegator does not know 'text'.
88
+ theme = idleConf.CurrentTheme()
89
+ normal_colors = idleConf.GetHighlight(theme, 'normal')
90
+ cursor_color = idleConf.GetHighlight(theme, 'cursor')['foreground']
91
+ select_colors = idleConf.GetHighlight(theme, 'hilite')
92
+ text.config(
93
+ foreground=normal_colors['foreground'],
94
+ background=normal_colors['background'],
95
+ insertbackground=cursor_color,
96
+ selectforeground=select_colors['foreground'],
97
+ selectbackground=select_colors['background'],
98
+ inactiveselectbackground=select_colors['background'], # new in 8.5
99
+ )
100
+
101
+
102
+ class ColorDelegator(Delegator):
103
+ """Delegator for syntax highlighting (text coloring).
104
+
105
+ Instance variables:
106
+ delegate: Delegator below this one in the stack, meaning the
107
+ one this one delegates to.
108
+
109
+ Used to track state:
110
+ after_id: Identifier for scheduled after event, which is a
111
+ timer for colorizing the text.
112
+ allow_colorizing: Boolean toggle for applying colorizing.
113
+ colorizing: Boolean flag when colorizing is in process.
114
+ stop_colorizing: Boolean flag to end an active colorizing
115
+ process.
116
+ """
117
+
118
+ def __init__(self):
119
+ Delegator.__init__(self)
120
+ self.init_state()
121
+ self.prog = prog
122
+ self.idprog = idprog
123
+ self.LoadTagDefs()
124
+
125
+ def init_state(self):
126
+ "Initialize variables that track colorizing state."
127
+ self.after_id = None
128
+ self.allow_colorizing = True
129
+ self.stop_colorizing = False
130
+ self.colorizing = False
131
+
132
+ def setdelegate(self, delegate):
133
+ """Set the delegate for this instance.
134
+
135
+ A delegate is an instance of a Delegator class and each
136
+ delegate points to the next delegator in the stack. This
137
+ allows multiple delegators to be chained together for a
138
+ widget. The bottom delegate for a colorizer is a Text
139
+ widget.
140
+
141
+ If there is a delegate, also start the colorizing process.
142
+ """
143
+ if self.delegate is not None:
144
+ self.unbind("<<toggle-auto-coloring>>")
145
+ Delegator.setdelegate(self, delegate)
146
+ if delegate is not None:
147
+ self.config_colors()
148
+ self.bind("<<toggle-auto-coloring>>", self.toggle_colorize_event)
149
+ self.notify_range("1.0", "end")
150
+ else:
151
+ # No delegate - stop any colorizing.
152
+ self.stop_colorizing = True
153
+ self.allow_colorizing = False
154
+
155
+ def config_colors(self):
156
+ "Configure text widget tags with colors from tagdefs."
157
+ for tag, cnf in self.tagdefs.items():
158
+ self.tag_configure(tag, **cnf)
159
+ self.tag_raise('sel')
160
+
161
+ def LoadTagDefs(self):
162
+ "Create dictionary of tag names to text colors."
163
+ theme = idleConf.CurrentTheme()
164
+ self.tagdefs = {
165
+ "COMMENT": idleConf.GetHighlight(theme, "comment"),
166
+ "KEYWORD": idleConf.GetHighlight(theme, "keyword"),
167
+ "BUILTIN": idleConf.GetHighlight(theme, "builtin"),
168
+ "STRING": idleConf.GetHighlight(theme, "string"),
169
+ "DEFINITION": idleConf.GetHighlight(theme, "definition"),
170
+ "SYNC": {'background': None, 'foreground': None},
171
+ "TODO": {'background': None, 'foreground': None},
172
+ "ERROR": idleConf.GetHighlight(theme, "error"),
173
+ # "hit" is used by ReplaceDialog to mark matches. It shouldn't be changed by Colorizer, but
174
+ # that currently isn't technically possible. This should be moved elsewhere in the future
175
+ # when fixing the "hit" tag's visibility, or when the replace dialog is replaced with a
176
+ # non-modal alternative.
177
+ "hit": idleConf.GetHighlight(theme, "hit"),
178
+ }
179
+ if DEBUG: print('tagdefs', self.tagdefs)
180
+
181
+ def insert(self, index, chars, tags=None):
182
+ "Insert chars into widget at index and mark for colorizing."
183
+ index = self.index(index)
184
+ self.delegate.insert(index, chars, tags)
185
+ self.notify_range(index, index + "+%dc" % len(chars))
186
+
187
+ def delete(self, index1, index2=None):
188
+ "Delete chars between indexes and mark for colorizing."
189
+ index1 = self.index(index1)
190
+ self.delegate.delete(index1, index2)
191
+ self.notify_range(index1)
192
+
193
+ def notify_range(self, index1, index2=None):
194
+ "Mark text changes for processing and restart colorizing, if active."
195
+ self.tag_add("TODO", index1, index2)
196
+ if self.after_id:
197
+ if DEBUG: print("colorizing already scheduled")
198
+ return
199
+ if self.colorizing:
200
+ self.stop_colorizing = True
201
+ if DEBUG: print("stop colorizing")
202
+ if self.allow_colorizing:
203
+ if DEBUG: print("schedule colorizing")
204
+ self.after_id = self.after(1, self.recolorize)
205
+ return
206
+
207
+ def close(self):
208
+ if self.after_id:
209
+ after_id = self.after_id
210
+ self.after_id = None
211
+ if DEBUG: print("cancel scheduled recolorizer")
212
+ self.after_cancel(after_id)
213
+ self.allow_colorizing = False
214
+ self.stop_colorizing = True
215
+
216
+ def toggle_colorize_event(self, event=None):
217
+ """Toggle colorizing on and off.
218
+
219
+ When toggling off, if colorizing is scheduled or is in
220
+ process, it will be cancelled and/or stopped.
221
+
222
+ When toggling on, colorizing will be scheduled.
223
+ """
224
+ if self.after_id:
225
+ after_id = self.after_id
226
+ self.after_id = None
227
+ if DEBUG: print("cancel scheduled recolorizer")
228
+ self.after_cancel(after_id)
229
+ if self.allow_colorizing and self.colorizing:
230
+ if DEBUG: print("stop colorizing")
231
+ self.stop_colorizing = True
232
+ self.allow_colorizing = not self.allow_colorizing
233
+ if self.allow_colorizing and not self.colorizing:
234
+ self.after_id = self.after(1, self.recolorize)
235
+ if DEBUG:
236
+ print("auto colorizing turned",
237
+ "on" if self.allow_colorizing else "off")
238
+ return "break"
239
+
240
+ def recolorize(self):
241
+ """Timer event (every 1ms) to colorize text.
242
+
243
+ Colorizing is only attempted when the text widget exists,
244
+ when colorizing is toggled on, and when the colorizing
245
+ process is not already running.
246
+
247
+ After colorizing is complete, some cleanup is done to
248
+ make sure that all the text has been colorized.
249
+ """
250
+ self.after_id = None
251
+ if not self.delegate:
252
+ if DEBUG: print("no delegate")
253
+ return
254
+ if not self.allow_colorizing:
255
+ if DEBUG: print("auto colorizing is off")
256
+ return
257
+ if self.colorizing:
258
+ if DEBUG: print("already colorizing")
259
+ return
260
+ try:
261
+ self.stop_colorizing = False
262
+ self.colorizing = True
263
+ if DEBUG: print("colorizing...")
264
+ t0 = time.perf_counter()
265
+ self.recolorize_main()
266
+ t1 = time.perf_counter()
267
+ if DEBUG: print("%.3f seconds" % (t1-t0))
268
+ finally:
269
+ self.colorizing = False
270
+ if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"):
271
+ if DEBUG: print("reschedule colorizing")
272
+ self.after_id = self.after(1, self.recolorize)
273
+
274
+ def recolorize_main(self):
275
+ "Evaluate text and apply colorizing tags."
276
+ next = "1.0"
277
+ while todo_tag_range := self.tag_nextrange("TODO", next):
278
+ self.tag_remove("SYNC", todo_tag_range[0], todo_tag_range[1])
279
+ sync_tag_range = self.tag_prevrange("SYNC", todo_tag_range[0])
280
+ head = sync_tag_range[1] if sync_tag_range else "1.0"
281
+
282
+ chars = ""
283
+ next = head
284
+ lines_to_get = 1
285
+ ok = False
286
+ while not ok:
287
+ mark = next
288
+ next = self.index(mark + "+%d lines linestart" %
289
+ lines_to_get)
290
+ lines_to_get = min(lines_to_get * 2, 100)
291
+ ok = "SYNC" in self.tag_names(next + "-1c")
292
+ line = self.get(mark, next)
293
+ ##print head, "get", mark, next, "->", repr(line)
294
+ if not line:
295
+ return
296
+ for tag in self.tagdefs:
297
+ self.tag_remove(tag, mark, next)
298
+ chars += line
299
+ self._add_tags_in_section(chars, head)
300
+ if "SYNC" in self.tag_names(next + "-1c"):
301
+ head = next
302
+ chars = ""
303
+ else:
304
+ ok = False
305
+ if not ok:
306
+ # We're in an inconsistent state, and the call to
307
+ # update may tell us to stop. It may also change
308
+ # the correct value for "next" (since this is a
309
+ # line.col string, not a true mark). So leave a
310
+ # crumb telling the next invocation to resume here
311
+ # in case update tells us to leave.
312
+ self.tag_add("TODO", next)
313
+ self.update()
314
+ if self.stop_colorizing:
315
+ if DEBUG: print("colorizing stopped")
316
+ return
317
+
318
+ def _add_tag(self, start, end, head, matched_group_name):
319
+ """Add a tag to a given range in the text widget.
320
+
321
+ This is a utility function, receiving the range as `start` and
322
+ `end` positions, each of which is a number of characters
323
+ relative to the given `head` index in the text widget.
324
+
325
+ The tag to add is determined by `matched_group_name`, which is
326
+ the name of a regular expression "named group" as matched by
327
+ by the relevant highlighting regexps.
328
+ """
329
+ tag = prog_group_name_to_tag.get(matched_group_name,
330
+ matched_group_name)
331
+ self.tag_add(tag,
332
+ f"{head}+{start:d}c",
333
+ f"{head}+{end:d}c")
334
+
335
+ def _add_tags_in_section(self, chars, head):
336
+ """Parse and add highlighting tags to a given part of the text.
337
+
338
+ `chars` is a string with the text to parse and to which
339
+ highlighting is to be applied.
340
+
341
+ `head` is the index in the text widget where the text is found.
342
+ """
343
+ for m in self.prog.finditer(chars):
344
+ for name, matched_text in matched_named_groups(m):
345
+ a, b = m.span(name)
346
+ self._add_tag(a, b, head, name)
347
+ if matched_text in ("def", "class"):
348
+ if m1 := self.idprog.match(chars, b):
349
+ a, b = m1.span(1)
350
+ self._add_tag(a, b, head, "DEFINITION")
351
+
352
+ def removecolors(self):
353
+ "Remove all colorizing tags."
354
+ for tag in self.tagdefs:
355
+ self.tag_remove(tag, "1.0", "end")
356
+
357
+
358
+ def _color_delegator(parent): # htest #
359
+ from tkinter import Toplevel, Text
360
+ from idlelib.idle_test.test_colorizer import source
361
+ from idlelib.percolator import Percolator
362
+
363
+ top = Toplevel(parent)
364
+ top.title("Test ColorDelegator")
365
+ x, y = map(int, parent.geometry().split('+')[1:])
366
+ top.geometry("700x550+%d+%d" % (x + 20, y + 175))
367
+
368
+ text = Text(top, background="white")
369
+ text.pack(expand=1, fill="both")
370
+ text.insert("insert", source)
371
+ text.focus_set()
372
+
373
+ color_config(text)
374
+ p = Percolator(text)
375
+ d = ColorDelegator()
376
+ p.insertfilter(d)
377
+
378
+
379
+ if __name__ == "__main__":
380
+ from unittest import main
381
+ main('idlelib.idle_test.test_colorizer', verbosity=2, exit=False)
382
+
383
+ from idlelib.idle_test.htest import run
384
+ run(_color_delegator)
shared/package-files/74/74f228e0ec0e77185c65426ce5789f97edc5f0c8ac4e864aae98922d988c150d/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:74f228e0ec0e77185c65426ce5789f97edc5f0c8ac4e864aae98922d988c150d
3
+ size 208346
shared/package-files/74/74f50ae63bf42c71641bdc954f8cf4faf960782063c74ef0d05c2be39b62fb76/blob 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 cpu {
19
+
20
+ TORCH_API at::Tensor empty_strided(at::IntArrayRef size, at::IntArrayRef stride, at::TensorOptions options={});
21
+ TORCH_API at::Tensor empty_strided(at::IntArrayRef size, at::IntArrayRef stride, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
22
+ TORCH_API at::Tensor empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::TensorOptions options={});
23
+ TORCH_API at::Tensor empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
24
+
25
+ } // namespace cpu
26
+ } // namespace at
shared/package-files/74/74f6ebb9d073af2e826b07d157521b6c5ed21c6bd26baa038c625ac842e71732/blob ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union
2
+
3
+ from django.contrib.sites.models import Site
4
+ from django.contrib.sites.requests import RequestSite
5
+ from django.http.request import HttpRequest
6
+
7
+ def get_current_site(request: Optional[HttpRequest]) -> Union[Site, RequestSite]: ...
shared/package-files/74/74f937df87bb310c25ef5f9abcdc911016155ae15341c54a7e5b65461ae5469c/blob ADDED
Binary file (369 Bytes). View file
 
shared/package-files/74/74f9be00518ea6c3d0a8651ec053f14fa9a337dbb1bcbde3a410f753bc970bc9/blob 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 cpu {
19
+
20
+ TORCH_API at::Tensor _ctc_loss_backward(const at::Tensor & grad, const at::Tensor & log_probs, const at::Tensor & targets, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, const at::Tensor & neg_log_likelihood, const at::Tensor & log_alpha, int64_t blank, bool zero_infinity=false);
21
+ TORCH_API at::Tensor _ctc_loss_backward(const at::Tensor & grad, const at::Tensor & log_probs, const at::Tensor & targets, const at::Tensor & input_lengths, const at::Tensor & target_lengths, const at::Tensor & neg_log_likelihood, const at::Tensor & log_alpha, int64_t blank, bool zero_infinity=false);
22
+
23
+ } // namespace cpu
24
+ } // namespace at
shared/package-files/74/74fb5a1e5668b133d0182c5320a46ae4e8f30aa24f575a3a182210b22e5aa05c/blob ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/Tensor.h>
3
+ #include <ATen/cuda/CUDAContext.h>
4
+ #include <c10/cuda/CUDAGuard.h>
5
+ #include <ATen/native/cuda/Loops.cuh>
6
+ #include <ATen/native/cuda/MemoryAccess.cuh>
7
+ #include <vector>
8
+
9
+ namespace at::native {
10
+
11
+ namespace {
12
+
13
+ static constexpr int64_t kILP = 4;
14
+ static constexpr int64_t kChunkSize = 65536;
15
+ static constexpr int64_t kBlockSize = 512;
16
+
17
+ // TODO(crcrpar): Add `n>5` for `low prec params & their higher prec copy`
18
+ // TensorListMetadata has to be < 4KB - the limit for kernel launch argument
19
+ static constexpr int depth_to_max_tensors[5] = {110, 64, 48, 36, 30};
20
+ static constexpr int depth_to_max_blocks[5] = {320, 320, 320, 320, 320};
21
+ static constexpr int depth_to_max_tensors_scalarlist[5] = {96, 64, 48, 36, 30};
22
+ static constexpr int depth_to_max_tensors_scalarlist_of_complex_double[2] = {
23
+ 72,
24
+ 60};
25
+
26
+ template <typename T>
27
+ __device__ __forceinline__ bool is_aligned(T* p) {
28
+ return ((uint64_t)p) % (kILP * sizeof(T)) == 0;
29
+ }
30
+
31
+ template <typename T>
32
+ __device__ __forceinline__ void load_store(
33
+ T* dst,
34
+ T* src,
35
+ int64_t dst_offset,
36
+ int64_t src_offset) {
37
+ using LT = at::native::memory::aligned_vector<T, kILP>;
38
+ ((LT*)dst)[dst_offset] = ((LT*)src)[src_offset];
39
+ }
40
+
41
+ template <int n>
42
+ struct TensorListMetadata {
43
+ const void* addresses[n][depth_to_max_tensors[n - 1]];
44
+ int64_t numel_for_tensor[depth_to_max_tensors[n - 1]];
45
+ unsigned char block_to_tensor[depth_to_max_blocks[n - 1]];
46
+ int block_to_chunk[depth_to_max_blocks[n - 1]];
47
+ int start_tensor_this_launch;
48
+ };
49
+
50
+ template <typename scalar_vals_t, int n>
51
+ struct TensorListScalarListMetadata {
52
+ const void* addresses[n][depth_to_max_tensors_scalarlist[n - 1]];
53
+ int64_t numel_for_tensor[depth_to_max_tensors_scalarlist[n - 1]];
54
+ scalar_vals_t scalar_vals[depth_to_max_tensors_scalarlist[n - 1]];
55
+ unsigned char block_to_tensor[depth_to_max_blocks[n - 1]];
56
+ int block_to_chunk[depth_to_max_blocks[n - 1]];
57
+ };
58
+
59
+ // note(mkozuki): `n` of 1&2 violate the limit of cuda kernel argument size of
60
+ // 4kb with `c10::complex<double>`
61
+ template <>
62
+ struct TensorListScalarListMetadata<c10::complex<double>, 1> {
63
+ const void* addresses[1]
64
+ [depth_to_max_tensors_scalarlist_of_complex_double[0]];
65
+ int64_t
66
+ numel_for_tensor[depth_to_max_tensors_scalarlist_of_complex_double[0]];
67
+ c10::complex<double>
68
+ scalar_vals[depth_to_max_tensors_scalarlist_of_complex_double[0]];
69
+ unsigned char block_to_tensor[depth_to_max_blocks[1 - 1]];
70
+ int block_to_chunk[depth_to_max_blocks[1 - 1]];
71
+ };
72
+
73
+ template <>
74
+ struct TensorListScalarListMetadata<c10::complex<double>, 2> {
75
+ const void* addresses[2]
76
+ [depth_to_max_tensors_scalarlist_of_complex_double[1]];
77
+ int64_t
78
+ numel_for_tensor[depth_to_max_tensors_scalarlist_of_complex_double[1]];
79
+ c10::complex<double>
80
+ scalar_vals[depth_to_max_tensors_scalarlist_of_complex_double[1]];
81
+ unsigned char block_to_tensor[depth_to_max_blocks[2 - 1]];
82
+ int block_to_chunk[depth_to_max_blocks[2 - 1]];
83
+ };
84
+
85
+ // NOTE(crcrpar): This is a conservative resolution to handle `state_steps`
86
+ // whose each element is `at::Tensor` of 1 element representing the number of
87
+ // `step`s called so far.
88
+ template <int n>
89
+ struct FusedOptimizerTensorListMetadata {
90
+ const void* addresses[n][depth_to_max_tensors[n - 1]];
91
+ int64_t numel_for_tensor[depth_to_max_tensors[n - 1]];
92
+ const void* state_steps_addresses[depth_to_max_tensors_scalarlist[n - 1]];
93
+ unsigned char block_to_tensor[depth_to_max_blocks[n - 1]];
94
+ int block_to_chunk[depth_to_max_blocks[n - 1]];
95
+ int start_tensor_this_launch;
96
+ };
97
+
98
+ template <typename T, typename U, typename... ArgTypes>
99
+ C10_LAUNCH_BOUNDS_1(kBlockSize)
100
+ __global__ void multi_tensor_apply_kernel(
101
+ T tensorListMeta,
102
+ U callable,
103
+ ArgTypes... args) {
104
+ // Hand the chunk information to the user-supplied functor to process however
105
+ // it likes.
106
+ callable(kChunkSize, tensorListMeta, args...);
107
+ }
108
+
109
+ } // namespace
110
+
111
+ // multi_tensor_apply enables horizontal fusion across lists of tensors.
112
+ // For example, whereas you once had a for-loop of a + b = c, where a, b,
113
+ // and c are individual tensors in lists as, bs, and cs, you can now with
114
+ // fewer kernel launches compute as + bs = cs.
115
+ //
116
+ // You can also imagine bs to be a scalar list vs a tensor list.
117
+ //
118
+ // The function below takes in tensor lists, scalars, and a callable and
119
+ // chunks up the computation to launch as few kernels as possible by iterating
120
+ // through every "chunk" in every tensor (thus the nested for loops). In the
121
+ // simplest case, everything gets bundled into just one kernel launch, but
122
+ // due to blocksize constraints, we may need to launch multiple kernels.
123
+ // Each kernel launch is defined by one tensorListMeta construct, which we
124
+ // use to track and reset the necessary metadata for each launch.
125
+ template <int depth, typename scalar_T, typename T, typename... ArgTypes>
126
+ void multi_tensor_apply(
127
+ std::vector<std::vector<at::Tensor>>& tensor_lists,
128
+ at::ArrayRef<Scalar> scalars,
129
+ T callable,
130
+ ArgTypes... args) {
131
+ TORCH_CHECK(
132
+ tensor_lists.size() == depth,
133
+ "Number of tensor lists has to match the depth.");
134
+ const size_t n_tensors = tensor_lists[0].size();
135
+ using scalar_vals_t = typename T::opmath_t;
136
+ TensorListScalarListMetadata<scalar_vals_t, depth> tensorListMeta;
137
+
138
+ int loc_block_info = 0;
139
+ int loc_tensor_info = 0;
140
+ for (size_t t = 0; t < n_tensors; t++) {
141
+ // short-circuit to avoid adding empty tensors to tensorListMeta
142
+ if (tensor_lists[0][t].numel() == 0) {
143
+ continue;
144
+ }
145
+ tensorListMeta.scalar_vals[loc_tensor_info] = scalars[t].to<scalar_T>();
146
+ tensorListMeta.numel_for_tensor[loc_tensor_info] =
147
+ tensor_lists[0][t].numel();
148
+ for (int d = 0; d < depth; d++) {
149
+ tensorListMeta.addresses[d][loc_tensor_info] =
150
+ tensor_lists[d][t].const_data_ptr();
151
+ }
152
+ loc_tensor_info++;
153
+
154
+ // now we enter [chunking territory].
155
+ // we will launch a kernel when EITHER the blocks get filled up OR
156
+ // the tensors get filled up. There will always be at least one block
157
+ // per tensor since the zero-sized ones will not enter the loop, so
158
+ // the nested forloop within represents iterating through the chunks
159
+ // of a single tensor.
160
+ const auto numel = tensor_lists[0][t].numel();
161
+ const auto chunks = numel / kChunkSize + (numel % kChunkSize != 0);
162
+ for (auto chunk = 0; chunk < chunks; chunk++) {
163
+ tensorListMeta.block_to_tensor[loc_block_info] = loc_tensor_info - 1;
164
+ tensorListMeta.block_to_chunk[loc_block_info] = chunk;
165
+ loc_block_info++;
166
+
167
+ // a tensor is not considered full unless all its chunks have been
168
+ // processed
169
+ const bool tensors_full =
170
+ (loc_tensor_info == depth_to_max_tensors_scalarlist[depth - 1] &&
171
+ chunk == chunks - 1);
172
+ const bool blocks_full =
173
+ (loc_block_info == depth_to_max_blocks[depth - 1]);
174
+
175
+ if (tensors_full || blocks_full) {
176
+ multi_tensor_apply_kernel<<<
177
+ loc_block_info,
178
+ kBlockSize,
179
+ 0,
180
+ at::cuda::getCurrentCUDAStream()>>>(
181
+ tensorListMeta, callable, args...);
182
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
183
+
184
+ // Reset.
185
+ loc_block_info = 0;
186
+ // all chunks have already been handled in the kernel
187
+ if (chunk == chunks - 1) {
188
+ loc_tensor_info = 0;
189
+ } else { // blocks were full and tensor chunks remain
190
+ tensorListMeta.numel_for_tensor[0] =
191
+ tensorListMeta.numel_for_tensor[loc_tensor_info - 1];
192
+ tensorListMeta.scalar_vals[0] =
193
+ tensorListMeta.scalar_vals[loc_tensor_info - 1];
194
+ for (int d = 0; d < depth; d++) {
195
+ tensorListMeta.addresses[d][0] =
196
+ tensorListMeta.addresses[d][loc_tensor_info - 1];
197
+ }
198
+ loc_tensor_info = 1;
199
+ }
200
+ }
201
+ }
202
+ }
203
+
204
+ // note: [finishing what we started]
205
+ // if there's remaining work to be done but the tensors/blocks aren't full
206
+ // yet we are at the end, submit the kernel to do the work!
207
+ if (loc_block_info != 0) {
208
+ multi_tensor_apply_kernel<<<
209
+ loc_block_info,
210
+ kBlockSize,
211
+ 0,
212
+ at::cuda::getCurrentCUDAStream()>>>(tensorListMeta, callable, args...);
213
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
214
+ }
215
+ }
216
+
217
+ template <int depth, typename T, typename... ArgTypes>
218
+ void multi_tensor_apply(
219
+ std::vector<std::vector<at::Tensor>>& tensor_lists,
220
+ T callable,
221
+ ArgTypes... args) {
222
+ TORCH_CHECK(
223
+ tensor_lists.size() == depth,
224
+ "Number of tensor lists has to match the depth.");
225
+ const size_t n_tensors = tensor_lists[0].size();
226
+ TensorListMetadata<depth> tensorListMeta;
227
+ tensorListMeta.start_tensor_this_launch = 0;
228
+
229
+ int loc_block_info = 0;
230
+ int loc_tensor_info = 0;
231
+ for (size_t t = 0; t < n_tensors; t++) {
232
+ // short-circuit to avoid adding empty tensors to tensorListMeta
233
+ if (tensor_lists[0][t].numel() == 0) {
234
+ continue;
235
+ }
236
+ tensorListMeta.numel_for_tensor[loc_tensor_info] =
237
+ tensor_lists[0][t].numel();
238
+ for (int d = 0; d < depth; d++) {
239
+ tensorListMeta.addresses[d][loc_tensor_info] =
240
+ tensor_lists[d][t].const_data_ptr();
241
+ }
242
+ loc_tensor_info++;
243
+
244
+ // see note: [chunking territory].
245
+ const auto numel = tensor_lists[0][t].numel();
246
+ const auto chunks = numel / kChunkSize + (numel % kChunkSize != 0);
247
+ for (auto chunk = 0; chunk < chunks; chunk++) {
248
+ tensorListMeta.block_to_tensor[loc_block_info] = loc_tensor_info - 1;
249
+ tensorListMeta.block_to_chunk[loc_block_info] = chunk;
250
+ loc_block_info++;
251
+
252
+ const bool tensors_full =
253
+ (loc_tensor_info == depth_to_max_tensors[depth - 1] &&
254
+ chunk == chunks - 1);
255
+ const bool blocks_full =
256
+ (loc_block_info == depth_to_max_blocks[depth - 1]);
257
+
258
+ if (tensors_full || blocks_full) {
259
+ multi_tensor_apply_kernel<<<
260
+ loc_block_info,
261
+ kBlockSize,
262
+ 0,
263
+ at::cuda::getCurrentCUDAStream()>>>(
264
+ tensorListMeta, callable, args...);
265
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
266
+
267
+ // Reset.
268
+ loc_block_info = 0;
269
+ if (chunk == chunks - 1) {
270
+ loc_tensor_info = 0;
271
+ tensorListMeta.start_tensor_this_launch = t + 1;
272
+ } else {
273
+ tensorListMeta.numel_for_tensor[0] =
274
+ tensorListMeta.numel_for_tensor[loc_tensor_info - 1];
275
+ for (int d = 0; d < depth; d++) {
276
+ tensorListMeta.addresses[d][0] =
277
+ tensorListMeta.addresses[d][loc_tensor_info - 1];
278
+ }
279
+ loc_tensor_info = 1;
280
+ tensorListMeta.start_tensor_this_launch = t;
281
+ }
282
+ }
283
+ }
284
+ }
285
+
286
+ // see note: [finishing what we started]
287
+ if (loc_block_info != 0) {
288
+ multi_tensor_apply_kernel<<<
289
+ loc_block_info,
290
+ kBlockSize,
291
+ 0,
292
+ at::cuda::getCurrentCUDAStream()>>>(tensorListMeta, callable, args...);
293
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
294
+ }
295
+ }
296
+
297
+ template <int depth, typename T, typename... ArgTypes>
298
+ void multi_tensor_apply_for_fused_optimizer(
299
+ std::vector<std::vector<at::Tensor>>& tensor_lists,
300
+ at::TensorList state_steps,
301
+ T callable,
302
+ ArgTypes... args) {
303
+ TORCH_CHECK(
304
+ tensor_lists.size() == depth,
305
+ "Number of tensor lists has to match the depth");
306
+ const auto num_tensors = tensor_lists[0].size();
307
+ FusedOptimizerTensorListMetadata<depth> tensorListMeta;
308
+
309
+ int loc_block_info = 0;
310
+ int loc_tensor_info = 0;
311
+ for (const auto& tensor_index : c10::irange(num_tensors)) {
312
+ // short-circuit to avoid adding empty tensors to tensorListMeta
313
+ if (tensor_lists[0][tensor_index].numel() == 0) {
314
+ continue;
315
+ }
316
+ tensorListMeta.state_steps_addresses[loc_tensor_info] =
317
+ state_steps[tensor_index].const_data_ptr();
318
+ tensorListMeta.numel_for_tensor[loc_tensor_info] =
319
+ tensor_lists[0][tensor_index].numel();
320
+ for (const auto& d : c10::irange(depth)) {
321
+ tensorListMeta.addresses[d][loc_tensor_info] =
322
+ tensor_lists[d][tensor_index].const_data_ptr();
323
+ }
324
+ loc_tensor_info++;
325
+
326
+ // see above note: [chunking territory]
327
+ const auto numel = tensor_lists[0][tensor_index].numel();
328
+ const auto chunks = numel / kChunkSize + (numel % kChunkSize != 0);
329
+ TORCH_CHECK(chunks > -1);
330
+ for (const auto& chunk : c10::irange(chunks)) {
331
+ tensorListMeta.block_to_tensor[loc_block_info] = loc_tensor_info - 1;
332
+ tensorListMeta.block_to_chunk[loc_block_info] = chunk;
333
+ loc_block_info++;
334
+
335
+ const auto tensor_full =
336
+ (loc_tensor_info == depth_to_max_tensors[depth - 1] &&
337
+ chunk == chunks - 1);
338
+ const auto blocks_full = loc_block_info == depth_to_max_blocks[depth - 1];
339
+
340
+ if (tensor_full || blocks_full) {
341
+ multi_tensor_apply_kernel<<<
342
+ loc_block_info,
343
+ kBlockSize,
344
+ 0,
345
+ at::cuda::getCurrentCUDAStream()>>>(
346
+ tensorListMeta, callable, args...);
347
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
348
+
349
+ // Reset.
350
+ loc_block_info = 0;
351
+ if (chunk == chunks - 1) {
352
+ loc_tensor_info = 0;
353
+ } else {
354
+ tensorListMeta.numel_for_tensor[0] =
355
+ tensorListMeta.numel_for_tensor[loc_tensor_info - 1];
356
+ tensorListMeta.state_steps_addresses[0] =
357
+ tensorListMeta.state_steps_addresses[loc_tensor_info - 1];
358
+ for (const auto& d : c10::irange(depth)) {
359
+ tensorListMeta.addresses[d][0] =
360
+ tensorListMeta.addresses[d][loc_tensor_info - 1];
361
+ }
362
+ loc_tensor_info = 1;
363
+ }
364
+ }
365
+ }
366
+ }
367
+
368
+ // see above note: [finishing what we've started]
369
+ if (loc_block_info != 0) {
370
+ multi_tensor_apply_kernel<<<
371
+ loc_block_info,
372
+ kBlockSize,
373
+ 0,
374
+ at::cuda::getCurrentCUDAStream()>>>(tensorListMeta, callable, args...);
375
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
376
+ }
377
+ }
378
+
379
+ } // namespace at::native
shared/package-files/74/74fe34d648c99426271d3dc899c19024a79fd139a0c353fad1b920824b84463f/blob ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Allocator.h>
4
+ #include <torch/csrc/jit/frontend/source_range.h>
5
+ #include <torch/csrc/jit/ir/scope.h>
6
+
7
+ #include <ATen/core/ivalue.h>
8
+
9
+ #include <vector>
10
+
11
+ #include <c10/util/flat_hash_map.h>
12
+
13
+ namespace c10 {
14
+ struct IValue;
15
+ }
16
+
17
+ namespace torch {
18
+ namespace jit {
19
+
20
+ class Pickler;
21
+ class InlinedCallStackSerializer {
22
+ public:
23
+ // Serialize InlinedCallStack as
24
+ // SerializedInlinedCallStack =
25
+ // [module_info, source range tag, SerializedInlinedCallStack]
26
+ // module_info = [ClassType.qualifiedName, instance_name]
27
+ // source_range_tag = unique source range id
28
+ c10::IValue serialize(
29
+ const InlinedCallStackPtr& cs_ptr,
30
+ const SourceRangeTagMap& source_range_tags);
31
+
32
+ private:
33
+ // module_info = [ClassType.qualifiedName, instance_name]
34
+ c10::IValue serialize_module_instance_info(
35
+ const c10::optional<ModuleInstanceInfo>& m);
36
+
37
+ // This caches serialized inlined callstack ptr, since many
38
+ // InlinedCallStackPtr can refer to the same one.
39
+ ska::flat_hash_map<InlinedCallStackPtr, c10::IValue>
40
+ serialized_inlined_callstack_;
41
+ // This caches serialized module instance info.
42
+ // There might be many nodes that are part of the same
43
+ // parent, grandparent etc. module.
44
+ ska::flat_hash_map<std::string, c10::IValue> serialized_module_instance_info_;
45
+ };
46
+
47
+ class TORCH_API CallStackDebugInfoPickler {
48
+ public:
49
+ CallStackDebugInfoPickler() = default;
50
+
51
+ std::vector<char> pickle(
52
+ const std::unordered_map<int64_t, DebugInfoTuple>& callstack_ptrs,
53
+ const SourceRangeTagMap& source_range_tags);
54
+
55
+ private:
56
+ InlinedCallStackSerializer css_;
57
+ };
58
+
59
+ class InlinedCallStackDeserializer {
60
+ public:
61
+ InlinedCallStackPtr deserialize(
62
+ const c10::IValue& iv,
63
+ const ska::flat_hash_map<int64_t, SourceRange>& source_range_map,
64
+ const std::shared_ptr<CompilationUnit>& cu);
65
+
66
+ private:
67
+ c10::optional<ModuleInstanceInfo> deserialize_module_instance_info(
68
+ const c10::IValue& iv,
69
+ const std::shared_ptr<CompilationUnit>& cu);
70
+
71
+ ska::
72
+ flat_hash_map<c10::intrusive_ptr<c10::ivalue::Tuple>, InlinedCallStackPtr>
73
+ cached_inlined_callstacks_;
74
+ ska::flat_hash_map<c10::intrusive_ptr<c10::ivalue::Tuple>, ModuleInstanceInfo>
75
+ cached_module_instance_info_;
76
+ };
77
+
78
+ class TORCH_API CallStackDebugInfoUnpickler {
79
+ public:
80
+ ska::flat_hash_map<int64_t, DebugInfoTuple> unpickle(
81
+ at::DataPtr&& data,
82
+ size_t size,
83
+ const ska::flat_hash_map<int64_t, SourceRange>& source_range_map,
84
+ const std::shared_ptr<CompilationUnit>& cu);
85
+
86
+ private:
87
+ InlinedCallStackDeserializer csds_;
88
+ };
89
+
90
+ } // namespace jit
91
+ } // namespace torch
shared/package-files/75/750007a61b9a86c49e4ee516cc31667b7c969861748dee48a2d81cd32b8da07e/blob ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API void _amp_foreach_non_finite_check_and_unscale_(at::TensorList self, at::Tensor & found_inf, const at::Tensor & inv_scale);
21
+
22
+ } // namespace cuda
23
+ } // namespace at
shared/package-files/75/7501011389a364fb724632972ba67e6cc1c9745aa9c21233c431f8c74e2b2989/blob ADDED
Binary file (1.5 kB). View file
 
shared/package-files/75/7502587d52e7810228f2ecb45ac4319ea0f5c008b7ac91053b920010dc6ddf94/blob ADDED
@@ -0,0 +1,690 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Encoding file: shiftjis, multi-byte
2
+ M
3
+ 003F 0 40
4
+ 00
5
+ 0000000100020003000400050006000700080009000A000B000C000D000E000F
6
+ 0010001100120013001400150016001700180019001A001B001C001D001E001F
7
+ 0020002100220023002400250026002700280029002A002B002C002D002E002F
8
+ 0030003100320033003400350036003700380039003A003B003C003D003E003F
9
+ 0040004100420043004400450046004700480049004A004B004C004D004E004F
10
+ 0050005100520053005400550056005700580059005A005B005C005D005E005F
11
+ 0060006100620063006400650066006700680069006A006B006C006D006E006F
12
+ 0070007100720073007400750076007700780079007A007B007C007D007E007F
13
+ 0080000000000000000000850086008700000000000000000000000000000000
14
+ 0000000000000000000000000000000000000000000000000000000000000000
15
+ 0000FF61FF62FF63FF64FF65FF66FF67FF68FF69FF6AFF6BFF6CFF6DFF6EFF6F
16
+ FF70FF71FF72FF73FF74FF75FF76FF77FF78FF79FF7AFF7BFF7CFF7DFF7EFF7F
17
+ FF80FF81FF82FF83FF84FF85FF86FF87FF88FF89FF8AFF8BFF8CFF8DFF8EFF8F
18
+ FF90FF91FF92FF93FF94FF95FF96FF97FF98FF99FF9AFF9BFF9CFF9DFF9EFF9F
19
+ 0000000000000000000000000000000000000000000000000000000000000000
20
+ 0000000000000000000000000000000000000000000000000000000000000000
21
+ 81
22
+ 0000000000000000000000000000000000000000000000000000000000000000
23
+ 0000000000000000000000000000000000000000000000000000000000000000
24
+ 0000000000000000000000000000000000000000000000000000000000000000
25
+ 0000000000000000000000000000000000000000000000000000000000000000
26
+ 300030013002FF0CFF0E30FBFF1AFF1BFF1FFF01309B309C00B4FF4000A8FF3E
27
+ FFE3FF3F30FD30FE309D309E30034EDD30053006300730FC20152010FF0FFF3C
28
+ 301C2016FF5C2026202520182019201C201DFF08FF0930143015FF3BFF3DFF5B
29
+ FF5D30083009300A300B300C300D300E300F30103011FF0B221200B100D70000
30
+ 00F7FF1D2260FF1CFF1E22662267221E22342642264000B0203220332103FFE5
31
+ FF0400A200A3FF05FF03FF06FF0AFF2000A72606260525CB25CF25CE25C725C6
32
+ 25A125A025B325B225BD25BC203B301221922190219121933013000000000000
33
+ 000000000000000000000000000000002208220B2286228722822283222A2229
34
+ 000000000000000000000000000000002227222800AC21D221D4220022030000
35
+ 0000000000000000000000000000000000000000222022A52312220222072261
36
+ 2252226A226B221A223D221D2235222B222C0000000000000000000000000000
37
+ 212B2030266F266D266A2020202100B6000000000000000025EF000000000000
38
+ 82
39
+ 0000000000000000000000000000000000000000000000000000000000000000
40
+ 0000000000000000000000000000000000000000000000000000000000000000
41
+ 0000000000000000000000000000000000000000000000000000000000000000
42
+ 0000000000000000000000000000000000000000000000000000000000000000
43
+ 000000000000000000000000000000000000000000000000000000000000FF10
44
+ FF11FF12FF13FF14FF15FF16FF17FF18FF190000000000000000000000000000
45
+ FF21FF22FF23FF24FF25FF26FF27FF28FF29FF2AFF2BFF2CFF2DFF2EFF2FFF30
46
+ FF31FF32FF33FF34FF35FF36FF37FF38FF39FF3A000000000000000000000000
47
+ 0000FF41FF42FF43FF44FF45FF46FF47FF48FF49FF4AFF4BFF4CFF4DFF4EFF4F
48
+ FF50FF51FF52FF53FF54FF55FF56FF57FF58FF59FF5A00000000000000003041
49
+ 30423043304430453046304730483049304A304B304C304D304E304F30503051
50
+ 30523053305430553056305730583059305A305B305C305D305E305F30603061
51
+ 30623063306430653066306730683069306A306B306C306D306E306F30703071
52
+ 30723073307430753076307730783079307A307B307C307D307E307F30803081
53
+ 30823083308430853086308730883089308A308B308C308D308E308F30903091
54
+ 3092309300000000000000000000000000000000000000000000000000000000
55
+ 83
56
+ 0000000000000000000000000000000000000000000000000000000000000000
57
+ 0000000000000000000000000000000000000000000000000000000000000000
58
+ 0000000000000000000000000000000000000000000000000000000000000000
59
+ 0000000000000000000000000000000000000000000000000000000000000000
60
+ 30A130A230A330A430A530A630A730A830A930AA30AB30AC30AD30AE30AF30B0
61
+ 30B130B230B330B430B530B630B730B830B930BA30BB30BC30BD30BE30BF30C0
62
+ 30C130C230C330C430C530C630C730C830C930CA30CB30CC30CD30CE30CF30D0
63
+ 30D130D230D330D430D530D630D730D830D930DA30DB30DC30DD30DE30DF0000
64
+ 30E030E130E230E330E430E530E630E730E830E930EA30EB30EC30ED30EE30EF
65
+ 30F030F130F230F330F430F530F6000000000000000000000000000000000391
66
+ 03920393039403950396039703980399039A039B039C039D039E039F03A003A1
67
+ 03A303A403A503A603A703A803A90000000000000000000000000000000003B1
68
+ 03B203B303B403B503B603B703B803B903BA03BB03BC03BD03BE03BF03C003C1
69
+ 03C303C403C503C603C703C803C9000000000000000000000000000000000000
70
+ 0000000000000000000000000000000000000000000000000000000000000000
71
+ 0000000000000000000000000000000000000000000000000000000000000000
72
+ 84
73
+ 0000000000000000000000000000000000000000000000000000000000000000
74
+ 0000000000000000000000000000000000000000000000000000000000000000
75
+ 0000000000000000000000000000000000000000000000000000000000000000
76
+ 0000000000000000000000000000000000000000000000000000000000000000
77
+ 04100411041204130414041504010416041704180419041A041B041C041D041E
78
+ 041F0420042104220423042404250426042704280429042A042B042C042D042E
79
+ 042F000000000000000000000000000000000000000000000000000000000000
80
+ 04300431043204330434043504510436043704380439043A043B043C043D0000
81
+ 043E043F0440044104420443044404450446044704480449044A044B044C044D
82
+ 044E044F00000000000000000000000000000000000000000000000000002500
83
+ 2502250C251025182514251C252C25242534253C25012503250F2513251B2517
84
+ 25232533252B253B254B2520252F25282537253F251D25302525253825420000
85
+ 0000000000000000000000000000000000000000000000000000000000000000
86
+ 0000000000000000000000000000000000000000000000000000000000000000
87
+ 0000000000000000000000000000000000000000000000000000000000000000
88
+ 0000000000000000000000000000000000000000000000000000000000000000
89
+ 88
90
+ 0000000000000000000000000000000000000000000000000000000000000000
91
+ 0000000000000000000000000000000000000000000000000000000000000000
92
+ 0000000000000000000000000000000000000000000000000000000000000000
93
+ 0000000000000000000000000000000000000000000000000000000000000000
94
+ 0000000000000000000000000000000000000000000000000000000000000000
95
+ 0000000000000000000000000000000000000000000000000000000000000000
96
+ 0000000000000000000000000000000000000000000000000000000000000000
97
+ 0000000000000000000000000000000000000000000000000000000000000000
98
+ 0000000000000000000000000000000000000000000000000000000000000000
99
+ 0000000000000000000000000000000000000000000000000000000000004E9C
100
+ 55165A03963F54C0611B632859F690228475831C7A5060AA63E16E2565ED8466
101
+ 82A69BF56893572765A162715B9B59D0867B98F47D627DBE9B8E62167C9F88B7
102
+ 5B895EB563096697684895C7978D674F4EE54F0A4F4D4F9D504956F2593759D4
103
+ 5A015C0960DF610F61706613690570BA754F757079FB7DAD7DEF80C3840E8863
104
+ 8B029055907A533B4E954EA557DF80B290C178EF4E0058F16EA290387A328328
105
+ 828B9C2F5141537054BD54E156E059FB5F1598F26DEB80E4852D000000000000
106
+ 89
107
+ 0000000000000000000000000000000000000000000000000000000000000000
108
+ 0000000000000000000000000000000000000000000000000000000000000000
109
+ 0000000000000000000000000000000000000000000000000000000000000000
110
+ 0000000000000000000000000000000000000000000000000000000000000000
111
+ 9662967096A097FB540B53F35B8770CF7FBD8FC296E8536F9D5C7ABA4E117893
112
+ 81FC6E26561855046B1D851A9C3B59E553A96D6674DC958F56424E91904B96F2
113
+ 834F990C53E155B65B305F71662066F368046C386CF36D29745B76C87A4E9834
114
+ 82F1885B8A6092ED6DB275AB76CA99C560A68B018D8A95B2698E53AD51860000
115
+ 5712583059445BB45EF6602863A963F46CBF6F14708E7114715971D5733F7E01
116
+ 827682D185979060925B9D1B586965BC6C5A752551F9592E59655F805FDC62BC
117
+ 65FA6A2A6B276BB4738B7FC189569D2C9D0E9EC45CA16C96837B51045C4B61B6
118
+ 81C6687672614E594FFA537860696E297A4F97F34E0B53164EEE4F554F3D4FA1
119
+ 4F7352A053EF5609590F5AC15BB65BE179D16687679C67B66B4C6CB3706B73C2
120
+ 798D79BE7A3C7B8782B182DB8304837783EF83D387668AB256298CA88FE6904E
121
+ 971E868A4FC45CE862117259753B81E582BD86FE8CC096C5991399D54ECB4F1A
122
+ 89E356DE584A58CA5EFB5FEB602A6094606261D0621262D06539000000000000
123
+ 8A
124
+ 0000000000000000000000000000000000000000000000000000000000000000
125
+ 0000000000000000000000000000000000000000000000000000000000000000
126
+ 0000000000000000000000000000000000000000000000000000000000000000
127
+ 0000000000000000000000000000000000000000000000000000000000000000
128
+ 9B41666668B06D777070754C76867D7582A587F9958B968E8C9D51F152BE5916
129
+ 54B35BB35D16616869826DAF788D84CB88578A7293A79AB86D6C99A886D957A3
130
+ 67FF86CE920E5283568754045ED362E164B9683C68386BBB737278BA7A6B899A
131
+ 89D28D6B8F0390ED95A3969497695B665CB3697D984D984E639B7B206A2B0000
132
+ 6A7F68B69C0D6F5F5272559D607062EC6D3B6E076ED1845B89108F444E149C39
133
+ 53F6691B6A3A9784682A515C7AC384B291DC938C565B9D286822830584317CA5
134
+ 520882C574E64E7E4F8351A05BD2520A52D852E75DFB559A582A59E65B8C5B98
135
+ 5BDB5E725E7960A3611F616361BE63DB656267D1685368FA6B3E6B536C576F22
136
+ 6F976F4574B0751876E3770B7AFF7BA17C217DE97F367FF0809D8266839E89B3
137
+ 8ACC8CAB908494519593959195A2966597D3992882184E38542B5CB85DCC73A9
138
+ 764C773C5CA97FEB8D0B96C19811985498584F014F0E5371559C566857FA5947
139
+ 5B095BC45C905E0C5E7E5FCC63EE673A65D765E2671F68CB68C4000000000000
140
+ 8B
141
+ 0000000000000000000000000000000000000000000000000000000000000000
142
+ 0000000000000000000000000000000000000000000000000000000000000000
143
+ 0000000000000000000000000000000000000000000000000000000000000000
144
+ 0000000000000000000000000000000000000000000000000000000000000000
145
+ 6A5F5E306BC56C176C7D757F79485B637A007D005FBD898F8A188CB48D778ECC
146
+ 8F1D98E29A0E9B3C4E80507D510059935B9C622F628064EC6B3A72A075917947
147
+ 7FA987FB8ABC8B7063AC83CA97A05409540355AB68546A588A70782767759ECD
148
+ 53745BA2811A865090064E184E454EC74F1153CA54385BAE5F13602565510000
149
+ 673D6C426C726CE3707874037A767AAE7B087D1A7CFE7D6665E7725B53BB5C45
150
+ 5DE862D262E063196E20865A8A318DDD92F86F0179A69B5A4EA84EAB4EAC4F9B
151
+ 4FA050D151477AF6517151F653545321537F53EB55AC58835CE15F375F4A602F
152
+ 6050606D631F65596A4B6CC172C272ED77EF80F881058208854E90F793E197FF
153
+ 99579A5A4EF051DD5C2D6681696D5C4066F26975738968507C8150C552E45747
154
+ 5DFE932665A46B236B3D7434798179BD7B4B7DCA82B983CC887F895F8B398FD1
155
+ 91D1541F92804E5D503653E5533A72D7739677E982E68EAF99C699C899D25177
156
+ 611A865E55B07A7A50765BD3904796854E326ADB91E75C515C48000000000000
157
+ 8C
158
+ 0000000000000000000000000000000000000000000000000000000000000000
159
+ 0000000000000000000000000000000000000000000000000000000000000000
160
+ 0000000000000000000000000000000000000000000000000000000000000000
161
+ 0000000000000000000000000000000000000000000000000000000000000000
162
+ 63987A9F6C9397748F617AAA718A96887C8268177E706851936C52F2541B85AB
163
+ 8A137FA48ECD90E15366888879414FC250BE521151445553572D73EA578B5951
164
+ 5F625F8460756176616761A963B2643A656C666F68426E1375667A3D7CFB7D4C
165
+ 7D997E4B7F6B830E834A86CD8A088A638B668EFD981A9D8F82B88FCE9BE80000
166
+ 5287621F64836FC09699684150916B206C7A6F547A747D5088408A2367084EF6
167
+ 503950265065517C5238526355A7570F58055ACC5EFA61B261F862F36372691C
168
+ 6A29727D72AC732E7814786F7D79770C80A9898B8B198CE28ED290639375967A
169
+ 98559A139E785143539F53B35E7B5F266E1B6E90738473FE7D4382378A008AFA
170
+ 96504E4E500B53E4547C56FA59D15B645DF15EAB5F276238654567AF6E5672D0
171
+ 7CCA88B480A180E183F0864E8A878DE8923796C798679F134E944E924F0D5348
172
+ 5449543E5A2F5F8C5FA1609F68A76A8E745A78818A9E8AA48B7791904E5E9BC9
173
+ 4EA44F7C4FAF501950165149516C529F52B952FE539A53E35411000000000000
174
+ 8D
175
+ 0000000000000000000000000000000000000000000000000000000000000000
176
+ 0000000000000000000000000000000000000000000000000000000000000000
177
+ 0000000000000000000000000000000000000000000000000000000000000000
178
+ 0000000000000000000000000000000000000000000000000000000000000000
179
+ 540E5589575157A2597D5B545B5D5B8F5DE55DE75DF75E785E835E9A5EB75F18
180
+ 6052614C629762D863A7653B6602664366F4676D6821689769CB6C5F6D2A6D69
181
+ 6E2F6E9D75327687786C7A3F7CE07D057D187D5E7DB18015800380AF80B18154
182
+ 818F822A8352884C88618B1B8CA28CFC90CA91759271783F92FC95A4964D0000
183
+ 980599999AD89D3B525B52AB53F7540858D562F76FE08C6A8F5F9EB9514B523B
184
+ 544A56FD7A4091779D609ED273446F09817075115FFD60DA9AA872DB8FBC6B64
185
+ 98034ECA56F0576458BE5A5A606861C7660F6606683968B16DF775D57D3A826E
186
+ 9B424E9B4F5053C955065D6F5DE65DEE67FB6C99747378028A50939688DF5750
187
+ 5EA7632B50B550AC518D670054C9585E59BB5BB05F69624D63A1683D6B736E08
188
+ 707D91C7728078157826796D658E7D3083DC88C18F09969B5264572867507F6A
189
+ 8CA151B45742962A583A698A80B454B25D0E57FC78959DFA4F5C524A548B643E
190
+ 6628671467F57A847B567D22932F685C9BAD7B395319518A5237000000000000
191
+ 8E
192
+ 0000000000000000000000000000000000000000000000000000000000000000
193
+ 0000000000000000000000000000000000000000000000000000000000000000
194
+ 0000000000000000000000000000000000000000000000000000000000000000
195
+ 0000000000000000000000000000000000000000000000000000000000000000
196
+ 5BDF62F664AE64E6672D6BBA85A996D176909BD6634C93069BAB76BF66524E09
197
+ 509853C25C7160E864926563685F71E673CA75237B977E8286958B838CDB9178
198
+ 991065AC66AB6B8B4ED54ED44F3A4F7F523A53F853F255E356DB58EB59CB59C9
199
+ 59FF5B505C4D5E025E2B5FD7601D6307652F5B5C65AF65BD65E8679D6B620000
200
+ 6B7B6C0F7345794979C17CF87D197D2B80A2810281F389968A5E8A698A668A8C
201
+ 8AEE8CC78CDC96CC98FC6B6F4E8B4F3C4F8D51505B575BFA6148630166426B21
202
+ 6ECB6CBB723E74BD75D478C1793A800C803381EA84948F9E6C509E7F5F0F8B58
203
+ 9D2B7AFA8EF85B8D96EB4E0353F157F759315AC95BA460896E7F6F0675BE8CEA
204
+ 5B9F85007BE0507267F4829D5C61854A7E1E820E51995C0463688D66659C716E
205
+ 793E7D1780058B1D8ECA906E86C790AA501F52FA5C3A6753707C7235914C91C8
206
+ 932B82E55BC25F3160F94E3B53D65B88624B67316B8A72E973E07A2E816B8DA3
207
+ 91529996511253D7546A5BFF63886A397DAC970056DA53CE5468000000000000
208
+ 8F
209
+ 0000000000000000000000000000000000000000000000000000000000000000
210
+ 0000000000000000000000000000000000000000000000000000000000000000
211
+ 0000000000000000000000000000000000000000000000000000000000000000
212
+ 0000000000000000000000000000000000000000000000000000000000000000
213
+ 5B975C315DDE4FEE610162FE6D3279C079CB7D427E4D7FD281ED821F84908846
214
+ 89728B908E748F2F9031914B916C96C6919C4EC04F4F514553415F93620E67D4
215
+ 6C416E0B73637E2691CD928353D459195BBF6DD1795D7E2E7C9B587E719F51FA
216
+ 88538FF04FCA5CFB662577AC7AE3821C99FF51C65FAA65EC696F6B896DF30000
217
+ 6E966F6476FE7D145DE190759187980651E6521D6240669166D96E1A5EB67DD2
218
+ 7F7266F885AF85F78AF852A953D959735E8F5F90605592E4966450B7511F52DD
219
+ 5320534753EC54E8554655315617596859BE5A3C5BB55C065C0F5C115C1A5E84
220
+ 5E8A5EE05F70627F628462DB638C63776607660C662D6676677E68A26A1F6A35
221
+ 6CBC6D886E096E58713C7126716775C77701785D7901796579F07AE07B117CA7
222
+ 7D39809683D6848B8549885D88F38A1F8A3C8A548A738C618CDE91A49266937E
223
+ 9418969C97984E0A4E084E1E4E575197527057CE583458CC5B225E3860C564FE
224
+ 676167566D4472B675737A6384B88B7291B89320563157F498FE000000000000
225
+ 90
226
+ 0000000000000000000000000000000000000000000000000000000000000000
227
+ 0000000000000000000000000000000000000000000000000000000000000000
228
+ 0000000000000000000000000000000000000000000000000000000000000000
229
+ 0000000000000000000000000000000000000000000000000000000000000000
230
+ 62ED690D6B9671ED7E548077827289E698DF87558FB15C3B4F384FE14FB55507
231
+ 5A205BDD5BE95FC3614E632F65B0664B68EE699B6D786DF1753375B9771F795E
232
+ 79E67D3381E382AF85AA89AA8A3A8EAB8F9B903291DD97074EBA4EC152035875
233
+ 58EC5C0B751A5C3D814E8A0A8FC59663976D7B258ACF9808916256F353A80000
234
+ 9017543957825E2563A86C34708A77617C8B7FE088709042915493109318968F
235
+ 745E9AC45D075D69657067A28DA896DB636E6749691983C5981796C088FE6F84
236
+ 647A5BF84E16702C755D662F51C4523652E259D35F8160276210653F6574661F
237
+ 667468F268166B636E057272751F76DB7CBE805658F088FD897F8AA08A938ACB
238
+ 901D91929752975965897A0E810696BB5E2D60DC621A65A56614679077F37A4D
239
+ 7C4D7E3E810A8CAC8D648DE18E5F78A9520762D963A5644262988A2D7A837BC0
240
+ 8AAC96EA7D76820C87494ED95148534353605BA35C025C165DDD6226624764B0
241
+ 681368346CC96D456D1767D36F5C714E717D65CB7A7F7BAD7DDA000000000000
242
+ 91
243
+ 0000000000000000000000000000000000000000000000000000000000000000
244
+ 0000000000000000000000000000000000000000000000000000000000000000
245
+ 0000000000000000000000000000000000000000000000000000000000000000
246
+ 0000000000000000000000000000000000000000000000000000000000000000
247
+ 7E4A7FA8817A821B823985A68A6E8CCE8DF59078907792AD929195839BAE524D
248
+ 55846F387136516879857E5581B37CCE564C58515CA863AA66FE66FD695A72D9
249
+ 758F758E790E795679DF7C977D207D4486078A34963B90619F2050E7527553CC
250
+ 53E2500955AA58EE594F723D5B8B5C64531D60E360F3635C6383633F63BB0000
251
+ 64CD65E966F95DE369CD69FD6F1571E54E8975E976F87A937CDF7DCF7D9C8061
252
+ 83498358846C84BC85FB88C58D709001906D9397971C9A1250CF5897618E81D3
253
+ 85358D0890204FC3507452475373606F6349675F6E2C8DB3901F4FD75C5E8CCA
254
+ 65CF7D9A53528896517663C35B585B6B5C0A640D6751905C4ED6591A592A6C70
255
+ 8A51553E581559A560F0625367C182356955964099C49A284F5358065BFE8010
256
+ 5CB15E2F5F856020614B623466FF6CF06EDE80CE817F82D4888B8CB89000902E
257
+ 968A9EDB9BDB4EE353F059277B2C918D984C9DF96EDD7027535355445B856258
258
+ 629E62D36CA26FEF74228A1794386FC18AFE833851E786F853EA000000000000
259
+ 92
260
+ 0000000000000000000000000000000000000000000000000000000000000000
261
+ 0000000000000000000000000000000000000000000000000000000000000000
262
+ 0000000000000000000000000000000000000000000000000000000000000000
263
+ 0000000000000000000000000000000000000000000000000000000000000000
264
+ 53E94F4690548FB0596A81315DFD7AEA8FBF68DA8C3772F89C486A3D8AB04E39
265
+ 53585606576662C563A265E66B4E6DE16E5B70AD77ED7AEF7BAA7DBB803D80C6
266
+ 86CB8A95935B56E358C75F3E65AD66966A806BB575378AC7502477E557305F1B
267
+ 6065667A6C6075F47A1A7F6E81F48718904599B37BC9755C7AF97B5184C40000
268
+ 901079E97A9283365AE177404E2D4EF25B995FE062BD663C67F16CE8866B8877
269
+ 8A3B914E92F399D06A177026732A82E784578CAF4E01514651CB558B5BF55E16
270
+ 5E335E815F145F355F6B5FB461F2631166A2671D6F6E7252753A773A80748139
271
+ 817887768ABF8ADC8D858DF3929A957798029CE552C5635776F467156C8873CD
272
+ 8CC393AE96736D25589C690E69CC8FFD939A75DB901A585A680263B469FB4F43
273
+ 6F2C67D88FBB85267DB49354693F6F70576A58F75B2C7D2C722A540A91E39DB4
274
+ 4EAD4F4E505C507552438C9E544858245B9A5E1D5E955EAD5EF75F1F608C62B5
275
+ 633A63D068AF6C407887798E7A0B7DE082478A028AE68E449013000000000000
276
+ 93
277
+ 0000000000000000000000000000000000000000000000000000000000000000
278
+ 0000000000000000000000000000000000000000000000000000000000000000
279
+ 0000000000000000000000000000000000000000000000000000000000000000
280
+ 0000000000000000000000000000000000000000000000000000000000000000
281
+ 90B8912D91D89F0E6CE5645864E265756EF476847B1B906993D16EBA54F25FB9
282
+ 64A48F4D8FED92445178586B59295C555E976DFB7E8F751C8CBC8EE2985B70B9
283
+ 4F1D6BBF6FB1753096FB514E54105835585759AC5C605F926597675C6E21767B
284
+ 83DF8CED901490FD934D7825783A52AA5EA6571F597460125012515A51AC0000
285
+ 51CD520055105854585859575B955CF65D8B60BC6295642D6771684368BC68DF
286
+ 76D76DD86E6F6D9B706F71C85F5375D879777B497B547B527CD67D7152308463
287
+ 856985E48A0E8B048C468E0F9003900F94199676982D9A3095D850CD52D5540C
288
+ 58025C0E61A7649E6D1E77B37AE580F48404905392855CE09D07533F5F975FB3
289
+ 6D9C7279776379BF7BE46BD272EC8AAD68036A6151F87A8169345C4A9CF682EB
290
+ 5BC59149701E56785C6F60C765666C8C8C5A90419813545166C7920D594890A3
291
+ 51854E4D51EA85998B0E7058637A934B696299B47E047577535769608EDF96E3
292
+ 6C5D4E8C5C3C5F108FE953028CD1808986795EFF65E54E735165000000000000
293
+ 94
294
+ 0000000000000000000000000000000000000000000000000000000000000000
295
+ 0000000000000000000000000000000000000000000000000000000000000000
296
+ 0000000000000000000000000000000000000000000000000000000000000000
297
+ 0000000000000000000000000000000000000000000000000000000000000000
298
+ 59825C3F97EE4EFB598A5FCD8A8D6FE179B079625BE78471732B71B15E745FF5
299
+ 637B649A71C37C984E435EFC4E4B57DC56A260A96FC37D0D80FD813381BF8FB2
300
+ 899786A45DF4628A64AD898767776CE26D3E743678345A467F7582AD99AC4FF3
301
+ 5EC362DD63926557676F76C3724C80CC80BA8F29914D500D57F95A9268850000
302
+ 6973716472FD8CB758F28CE0966A9019877F79E477E784294F2F5265535A62CD
303
+ 67CF6CCA767D7B947C95823685848FEB66DD6F2072067E1B83AB99C19EA651FD
304
+ 7BB178727BB880877B486AE85E61808C75517560516B92626E8C767A91979AEA
305
+ 4F107F70629C7B4F95A59CE9567A585986E496BC4F345224534A53CD53DB5E06
306
+ 642C6591677F6C3E6C4E724872AF73ED75547E41822C85E98CA97BC491C67169
307
+ 981298EF633D6669756A76E478D0854386EE532A5351542659835E875F7C60B2
308
+ 6249627962AB65906BD46CCC75B276AE789179D87DCB7F7780A588AB8AB98CBB
309
+ 907F975E98DB6A0B7C3850995C3E5FAE67876BD8743577097F8E000000000000
310
+ 95
311
+ 0000000000000000000000000000000000000000000000000000000000000000
312
+ 0000000000000000000000000000000000000000000000000000000000000000
313
+ 0000000000000000000000000000000000000000000000000000000000000000
314
+ 0000000000000000000000000000000000000000000000000000000000000000
315
+ 9F3B67CA7A175339758B9AED5F66819D83F180985F3C5FC575627B46903C6867
316
+ 59EB5A9B7D10767E8B2C4FF55F6A6A196C376F0274E2796888688A558C795EDF
317
+ 63CF75C579D282D7932892F2849C86ED9C2D54C15F6C658C6D5C70158CA78CD3
318
+ 983B654F74F64E0D4ED857E0592B5A665BCC51A85E035E9C6016627665770000
319
+ 65A7666E6D6E72367B268150819A82998B5C8CA08CE68D74961C96444FAE64AB
320
+ 6B66821E8461856A90E85C01695398A8847A85574F0F526F5FA95E45670D798F
321
+ 8179890789866DF55F1762556CB84ECF72699B925206543B567458B361A4626E
322
+ 711A596E7C897CDE7D1B96F06587805E4E194F75517558405E635E735F0A67C4
323
+ 4E26853D9589965B7C73980150FB58C1765678A7522577A585117B86504F5909
324
+ 72477BC77DE88FBA8FD4904D4FBF52C95A295F0197AD4FDD821792EA57036355
325
+ 6B69752B88DC8F147A4252DF58936155620A66AE6BCD7C3F83E950234FF85305
326
+ 5446583159495B9D5CF05CEF5D295E9662B16367653E65B9670B000000000000
327
+ 96
328
+ 0000000000000000000000000000000000000000000000000000000000000000
329
+ 0000000000000000000000000000000000000000000000000000000000000000
330
+ 0000000000000000000000000000000000000000000000000000000000000000
331
+ 0000000000000000000000000000000000000000000000000000000000000000
332
+ 6CD56CE170F978327E2B80DE82B3840C84EC870289128A2A8C4A90A692D298FD
333
+ 9CF39D6C4E4F4EA1508D5256574A59A85E3D5FD85FD9623F66B4671B67D068D2
334
+ 51927D2180AA81A88B008C8C8CBF927E96325420982C531750D5535C58A864B2
335
+ 6734726777667A4691E652C36CA16B8658005E4C5954672C7FFB51E176C60000
336
+ 646978E89B549EBB57CB59B96627679A6BCE54E969D95E55819C67959BAA67FE
337
+ 9C52685D4EA64FE353C862B9672B6CAB8FC44FAD7E6D9EBF4E0761626E806F2B
338
+ 85135473672A9B455DF37B955CAC5BC6871C6E4A84D17A14810859997C8D6C11
339
+ 772052D959227121725F77DB97279D61690B5A7F5A1851A5540D547D660E76DF
340
+ 8FF792989CF459EA725D6EC5514D68C97DBF7DEC97629EBA64786A2183025984
341
+ 5B5F6BDB731B76F27DB280178499513267289ED976EE676252FF99055C24623B
342
+ 7C7E8CB0554F60B67D0B958053014E5F51B6591C723A803691CE5F2577E25384
343
+ 5F797D0485AC8A338E8D975667F385AE9453610961086CB9765200000000FF5E
344
+ 97
345
+ 0000000000000000000000000000000000000000000000000000000000000000
346
+ 0000000000000000000000000000000000000000000000000000000000000000
347
+ 0000000000000000000000000000000000000000000000000000000000000000
348
+ 0000000000000000000000000000000000000000000000000000000000000000
349
+ 8AED8F38552F4F51512A52C753CB5BA55E7D60A0618263D6670967DA6E676D8C
350
+ 733673377531795088D58A98904A909190F596C4878D59154E884F594E0E8A89
351
+ 8F3F981050AD5E7C59965BB95EB863DA63FA64C166DC694A69D86D0B6EB67194
352
+ 75287AAF7F8A8000844984C989818B218E0A9065967D990A617E62916B320000
353
+ 6C836D747FCC7FFC6DC07F8587BA88F8676583B1983C96F76D1B7D61843D916A
354
+ 4E7153755D506B046FEB85CD862D89A75229540F5C65674E68A87406748375E2
355
+ 88CF88E191CC96E296785F8B73877ACB844E63A0756552896D416E9C74097559
356
+ 786B7C9296867ADC9F8D4FB6616E65C5865C4E864EAE50DA4E2151CC5BEE6599
357
+ 68816DBC731F764277AD7A1C7CE7826F8AD2907C91CF96759818529B7DD1502B
358
+ 539867976DCB71D0743381E88F2A96A39C579E9F746058416D997D2F985E4EE4
359
+ 4F364F8B51B752B15DBA601C73B2793C82D3923496B796F6970A9E979F6266A6
360
+ 6B74521752A370C888C25EC9604B61906F2371497C3E7DF4806F000000000000
361
+ 98
362
+ 0000000000000000000000000000000000000000000000000000000000000000
363
+ 0000000000000000000000000000000000000000000000000000000000000000
364
+ 0000000000000000000000000000000000000000000000000000000000000000
365
+ 0000000000000000000000000000000000000000000000000000000000000000
366
+ 84EE9023932C54429B6F6AD370898CC28DEF973252B45A415ECA5F046717697C
367
+ 69946D6A6F0F726272FC7BED8001807E874B90CE516D9E937984808B93328AD6
368
+ 502D548C8A716B6A8CC4810760D167A09DF24E994E989C108A6B85C185686900
369
+ 6E7E789781550000000000000000000000000000000000000000000000000000
370
+ 0000000000000000000000000000000000000000000000000000000000000000
371
+ 0000000000000000000000000000000000000000000000000000000000005F0C
372
+ 4E104E154E2A4E314E364E3C4E3F4E424E564E584E824E858C6B4E8A82125F0D
373
+ 4E8E4E9E4E9F4EA04EA24EB04EB34EB64ECE4ECD4EC44EC64EC24ED74EDE4EED
374
+ 4EDF4EF74F094F5A4F304F5B4F5D4F574F474F764F884F8F4F984F7B4F694F70
375
+ 4F914F6F4F864F9651184FD44FDF4FCE4FD84FDB4FD14FDA4FD04FE44FE5501A
376
+ 50285014502A502550054F1C4FF650215029502C4FFE4FEF5011500650435047
377
+ 6703505550505048505A5056506C50785080509A508550B450B2000000000000
378
+ 99
379
+ 0000000000000000000000000000000000000000000000000000000000000000
380
+ 0000000000000000000000000000000000000000000000000000000000000000
381
+ 0000000000000000000000000000000000000000000000000000000000000000
382
+ 0000000000000000000000000000000000000000000000000000000000000000
383
+ 50C950CA50B350C250D650DE50E550ED50E350EE50F950F55109510151025116
384
+ 51155114511A5121513A5137513C513B513F51405152514C515451627AF85169
385
+ 516A516E5180518256D8518C5189518F519151935195519651A451A651A251A9
386
+ 51AA51AB51B351B151B251B051B551BD51C551C951DB51E0865551E951ED0000
387
+ 51F051F551FE5204520B5214520E5227522A522E52335239524F5244524B524C
388
+ 525E5254526A527452695273527F527D528D529452925271528852918FA88FA7
389
+ 52AC52AD52BC52B552C152CD52D752DE52E352E698ED52E052F352F552F852F9
390
+ 530653087538530D5310530F5315531A5323532F533153335338534053465345
391
+ 4E175349534D51D6535E5369536E5918537B53775382539653A053A653A553AE
392
+ 53B053B653C37C1296D953DF66FC71EE53EE53E853ED53FA5401543D5440542C
393
+ 542D543C542E54365429541D544E548F5475548E545F5471547754705492547B
394
+ 5480547654845490548654C754A254B854A554AC54C454C854A8000000000000
395
+ 9A
396
+ 0000000000000000000000000000000000000000000000000000000000000000
397
+ 0000000000000000000000000000000000000000000000000000000000000000
398
+ 0000000000000000000000000000000000000000000000000000000000000000
399
+ 0000000000000000000000000000000000000000000000000000000000000000
400
+ 54AB54C254A454BE54BC54D854E554E6550F551454FD54EE54ED54FA54E25539
401
+ 55405563554C552E555C55455556555755385533555D5599558054AF558A559F
402
+ 557B557E5598559E55AE557C558355A9558755A855DA55C555DF55C455DC55E4
403
+ 55D4561455F7561655FE55FD561B55F9564E565071DF56345636563256380000
404
+ 566B5664562F566C566A56865680568A56A05694568F56A556AE56B656B456C2
405
+ 56BC56C156C356C056C856CE56D156D356D756EE56F9570056FF570457095708
406
+ 570B570D57135718571655C7571C572657375738574E573B5740574F576957C0
407
+ 57885761577F5789579357A057B357A457AA57B057C357C657D457D257D3580A
408
+ 57D657E3580B5819581D587258215862584B58706BC05852583D5879588558B9
409
+ 589F58AB58BA58DE58BB58B858AE58C558D358D158D758D958D858E558DC58E4
410
+ 58DF58EF58FA58F958FB58FC58FD5902590A5910591B68A65925592C592D5932
411
+ 5938593E7AD259555950594E595A5958596259605967596C5969000000000000
412
+ 9B
413
+ 0000000000000000000000000000000000000000000000000000000000000000
414
+ 0000000000000000000000000000000000000000000000000000000000000000
415
+ 0000000000000000000000000000000000000000000000000000000000000000
416
+ 0000000000000000000000000000000000000000000000000000000000000000
417
+ 59785981599D4F5E4FAB59A359B259C659E859DC598D59D959DA5A255A1F5A11
418
+ 5A1C5A095A1A5A405A6C5A495A355A365A625A6A5A9A5ABC5ABE5ACB5AC25ABD
419
+ 5AE35AD75AE65AE95AD65AFA5AFB5B0C5B0B5B165B325AD05B2A5B365B3E5B43
420
+ 5B455B405B515B555B5A5B5B5B655B695B705B735B755B7865885B7A5B800000
421
+ 5B835BA65BB85BC35BC75BC95BD45BD05BE45BE65BE25BDE5BE55BEB5BF05BF6
422
+ 5BF35C055C075C085C0D5C135C205C225C285C385C395C415C465C4E5C535C50
423
+ 5C4F5B715C6C5C6E4E625C765C795C8C5C915C94599B5CAB5CBB5CB65CBC5CB7
424
+ 5CC55CBE5CC75CD95CE95CFD5CFA5CED5D8C5CEA5D0B5D155D175D5C5D1F5D1B
425
+ 5D115D145D225D1A5D195D185D4C5D525D4E5D4B5D6C5D735D765D875D845D82
426
+ 5DA25D9D5DAC5DAE5DBD5D905DB75DBC5DC95DCD5DD35DD25DD65DDB5DEB5DF2
427
+ 5DF55E0B5E1A5E195E115E1B5E365E375E445E435E405E4E5E575E545E5F5E62
428
+ 5E645E475E755E765E7A9EBC5E7F5EA05EC15EC25EC85ED05ECF000000000000
429
+ 9C
430
+ 0000000000000000000000000000000000000000000000000000000000000000
431
+ 0000000000000000000000000000000000000000000000000000000000000000
432
+ 0000000000000000000000000000000000000000000000000000000000000000
433
+ 0000000000000000000000000000000000000000000000000000000000000000
434
+ 5ED65EE35EDD5EDA5EDB5EE25EE15EE85EE95EEC5EF15EF35EF05EF45EF85EFE
435
+ 5F035F095F5D5F5C5F0B5F115F165F295F2D5F385F415F485F4C5F4E5F2F5F51
436
+ 5F565F575F595F615F6D5F735F775F835F825F7F5F8A5F885F915F875F9E5F99
437
+ 5F985FA05FA85FAD5FBC5FD65FFB5FE45FF85FF15FDD60B35FFF602160600000
438
+ 601960106029600E6031601B6015602B6026600F603A605A6041606A6077605F
439
+ 604A6046604D6063604360646042606C606B60596081608D60E76083609A6084
440
+ 609B60966097609260A7608B60E160B860E060D360B45FF060BD60C660B560D8
441
+ 614D6115610660F660F7610060F460FA6103612160FB60F1610D610E6147613E
442
+ 61286127614A613F613C612C6134613D614261446173617761586159615A616B
443
+ 6174616F61656171615F615D6153617561996196618761AC6194619A618A6191
444
+ 61AB61AE61CC61CA61C961F761C861C361C661BA61CB7F7961CD61E661E361F6
445
+ 61FA61F461FF61FD61FC61FE620062086209620D620C6214621B000000000000
446
+ 9D
447
+ 0000000000000000000000000000000000000000000000000000000000000000
448
+ 0000000000000000000000000000000000000000000000000000000000000000
449
+ 0000000000000000000000000000000000000000000000000000000000000000
450
+ 0000000000000000000000000000000000000000000000000000000000000000
451
+ 621E6221622A622E6230623262336241624E625E6263625B62606268627C6282
452
+ 6289627E62926293629662D46283629462D762D162BB62CF62FF62C664D462C8
453
+ 62DC62CC62CA62C262C7629B62C9630C62EE62F163276302630862EF62F56350
454
+ 633E634D641C634F6396638E638063AB637663A3638F6389639F63B5636B0000
455
+ 636963BE63E963C063C663E363C963D263F663C4641664346406641364266436
456
+ 651D64176428640F6467646F6476644E652A6495649364A564A9648864BC64DA
457
+ 64D264C564C764BB64D864C264F164E7820964E064E162AC64E364EF652C64F6
458
+ 64F464F264FA650064FD6518651C650565246523652B65346535653765366538
459
+ 754B654865566555654D6558655E655D65726578658265838B8A659B659F65AB
460
+ 65B765C365C665C165C465CC65D265DB65D965E065E165F16772660A660365FB
461
+ 6773663566366634661C664F664466496641665E665D666466676668665F6662
462
+ 667066836688668E668966846698669D66C166B966C966BE66BC000000000000
463
+ 9E
464
+ 0000000000000000000000000000000000000000000000000000000000000000
465
+ 0000000000000000000000000000000000000000000000000000000000000000
466
+ 0000000000000000000000000000000000000000000000000000000000000000
467
+ 0000000000000000000000000000000000000000000000000000000000000000
468
+ 66C466B866D666DA66E0663F66E666E966F066F566F7670F6716671E67266727
469
+ 9738672E673F67366741673867376746675E67606759676367646789677067A9
470
+ 677C676A678C678B67A667A1678567B767EF67B467EC67B367E967B867E467DE
471
+ 67DD67E267EE67B967CE67C667E76A9C681E684668296840684D6832684E0000
472
+ 68B3682B685968636877687F689F688F68AD6894689D689B68836AAE68B96874
473
+ 68B568A068BA690F688D687E690168CA690868D86922692668E1690C68CD68D4
474
+ 68E768D569366912690468D768E3692568F968E068EF6928692A691A69236921
475
+ 68C669796977695C6978696B6954697E696E69396974693D695969306961695E
476
+ 695D6981696A69B269AE69D069BF69C169D369BE69CE5BE869CA69DD69BB69C3
477
+ 69A76A2E699169A0699C699569B469DE69E86A026A1B69FF6B0A69F969F269E7
478
+ 6A0569B16A1E69ED6A1469EB6A0A6A126AC16A236A136A446A0C6A726A366A78
479
+ 6A476A626A596A666A486A386A226A906A8D6AA06A846AA26AA3000000000000
480
+ 9F
481
+ 0000000000000000000000000000000000000000000000000000000000000000
482
+ 0000000000000000000000000000000000000000000000000000000000000000
483
+ 0000000000000000000000000000000000000000000000000000000000000000
484
+ 0000000000000000000000000000000000000000000000000000000000000000
485
+ 6A9786176ABB6AC36AC26AB86AB36AAC6ADE6AD16ADF6AAA6ADA6AEA6AFB6B05
486
+ 86166AFA6B126B169B316B1F6B386B3776DC6B3998EE6B476B436B496B506B59
487
+ 6B546B5B6B5F6B616B786B796B7F6B806B846B836B8D6B986B956B9E6BA46BAA
488
+ 6BAB6BAF6BB26BB16BB36BB76BBC6BC66BCB6BD36BDF6BEC6BEB6BF36BEF0000
489
+ 9EBE6C086C136C146C1B6C246C236C5E6C556C626C6A6C826C8D6C9A6C816C9B
490
+ 6C7E6C686C736C926C906CC46CF16CD36CBD6CD76CC56CDD6CAE6CB16CBE6CBA
491
+ 6CDB6CEF6CD96CEA6D1F884D6D366D2B6D3D6D386D196D356D336D126D0C6D63
492
+ 6D936D646D5A6D796D596D8E6D956FE46D856DF96E156E0A6DB56DC76DE66DB8
493
+ 6DC66DEC6DDE6DCC6DE86DD26DC56DFA6DD96DE46DD56DEA6DEE6E2D6E6E6E2E
494
+ 6E196E726E5F6E3E6E236E6B6E2B6E766E4D6E1F6E436E3A6E4E6E246EFF6E1D
495
+ 6E386E826EAA6E986EC96EB76ED36EBD6EAF6EC46EB26ED46ED56E8F6EA56EC2
496
+ 6E9F6F416F11704C6EEC6EF86EFE6F3F6EF26F316EEF6F326ECC000000000000
497
+ E0
498
+ 0000000000000000000000000000000000000000000000000000000000000000
499
+ 0000000000000000000000000000000000000000000000000000000000000000
500
+ 0000000000000000000000000000000000000000000000000000000000000000
501
+ 0000000000000000000000000000000000000000000000000000000000000000
502
+ 6F3E6F136EF76F866F7A6F786F816F806F6F6F5B6FF36F6D6F826F7C6F586F8E
503
+ 6F916FC26F666FB36FA36FA16FA46FB96FC66FAA6FDF6FD56FEC6FD46FD86FF1
504
+ 6FEE6FDB7009700B6FFA70117001700F6FFE701B701A6F74701D7018701F7030
505
+ 703E7032705170637099709270AF70F170AC70B870B370AE70DF70CB70DD0000
506
+ 70D9710970FD711C711971657155718871667162714C7156716C718F71FB7184
507
+ 719571A871AC71D771B971BE71D271C971D471CE71E071EC71E771F571FC71F9
508
+ 71FF720D7210721B7228722D722C72307232723B723C723F72407246724B7258
509
+ 7274727E7282728172877292729672A272A772B972B272C372C672C472CE72D2
510
+ 72E272E072E172F972F7500F7317730A731C7316731D7334732F73297325733E
511
+ 734E734F9ED87357736A7368737073787375737B737A73C873B373CE73BB73C0
512
+ 73E573EE73DE74A27405746F742573F87432743A7455743F745F74597441745C
513
+ 746974707463746A7476747E748B749E74A774CA74CF74D473F1000000000000
514
+ E1
515
+ 0000000000000000000000000000000000000000000000000000000000000000
516
+ 0000000000000000000000000000000000000000000000000000000000000000
517
+ 0000000000000000000000000000000000000000000000000000000000000000
518
+ 0000000000000000000000000000000000000000000000000000000000000000
519
+ 74E074E374E774E974EE74F274F074F174F874F7750475037505750C750E750D
520
+ 75157513751E7526752C753C7544754D754A7549755B7546755A756975647567
521
+ 756B756D75787576758675877574758A758975827594759A759D75A575A375C2
522
+ 75B375C375B575BD75B875BC75B175CD75CA75D275D975E375DE75FE75FF0000
523
+ 75FC760175F075FA75F275F3760B760D7609761F762776207621762276247634
524
+ 7630763B764776487646765C76587661766276687669766A7667766C76707672
525
+ 76767678767C768076837688768B768E769676937699769A76B076B476B876B9
526
+ 76BA76C276CD76D676D276DE76E176E576E776EA862F76FB7708770777047729
527
+ 7724771E77257726771B773777387747775A7768776B775B7765777F777E7779
528
+ 778E778B779177A0779E77B077B677B977BF77BC77BD77BB77C777CD77D777DA
529
+ 77DC77E377EE77FC780C781279267820792A7845788E78747886787C789A788C
530
+ 78A378B578AA78AF78D178C678CB78D478BE78BC78C578CA78EC000000000000
531
+ E2
532
+ 0000000000000000000000000000000000000000000000000000000000000000
533
+ 0000000000000000000000000000000000000000000000000000000000000000
534
+ 0000000000000000000000000000000000000000000000000000000000000000
535
+ 0000000000000000000000000000000000000000000000000000000000000000
536
+ 78E778DA78FD78F47907791279117919792C792B794079607957795F795A7955
537
+ 7953797A797F798A799D79A79F4B79AA79AE79B379B979BA79C979D579E779EC
538
+ 79E179E37A087A0D7A187A197A207A1F79807A317A3B7A3E7A377A437A577A49
539
+ 7A617A627A699F9D7A707A797A7D7A887A977A957A987A967AA97AC87AB00000
540
+ 7AB67AC57AC47ABF90837AC77ACA7ACD7ACF7AD57AD37AD97ADA7ADD7AE17AE2
541
+ 7AE67AED7AF07B027B0F7B0A7B067B337B187B197B1E7B357B287B367B507B7A
542
+ 7B047B4D7B0B7B4C7B457B757B657B747B677B707B717B6C7B6E7B9D7B987B9F
543
+ 7B8D7B9C7B9A7B8B7B927B8F7B5D7B997BCB7BC17BCC7BCF7BB47BC67BDD7BE9
544
+ 7C117C147BE67BE57C607C007C077C137BF37BF77C177C0D7BF67C237C277C2A
545
+ 7C1F7C377C2B7C3D7C4C7C437C547C4F7C407C507C587C5F7C647C567C657C6C
546
+ 7C757C837C907CA47CAD7CA27CAB7CA17CA87CB37CB27CB17CAE7CB97CBD7CC0
547
+ 7CC57CC27CD87CD27CDC7CE29B3B7CEF7CF27CF47CF67CFA7D06000000000000
548
+ E3
549
+ 0000000000000000000000000000000000000000000000000000000000000000
550
+ 0000000000000000000000000000000000000000000000000000000000000000
551
+ 0000000000000000000000000000000000000000000000000000000000000000
552
+ 0000000000000000000000000000000000000000000000000000000000000000
553
+ 7D027D1C7D157D0A7D457D4B7D2E7D327D3F7D357D467D737D567D4E7D727D68
554
+ 7D6E7D4F7D637D937D897D5B7D8F7D7D7D9B7DBA7DAE7DA37DB57DC77DBD7DAB
555
+ 7E3D7DA27DAF7DDC7DB87D9F7DB07DD87DDD7DE47DDE7DFB7DF27DE17E057E0A
556
+ 7E237E217E127E317E1F7E097E0B7E227E467E667E3B7E357E397E437E370000
557
+ 7E327E3A7E677E5D7E567E5E7E597E5A7E797E6A7E697E7C7E7B7E837DD57E7D
558
+ 8FAE7E7F7E887E897E8C7E927E907E937E947E967E8E7E9B7E9C7F387F3A7F45
559
+ 7F4C7F4D7F4E7F507F517F557F547F587F5F7F607F687F697F677F787F827F86
560
+ 7F837F887F877F8C7F947F9E7F9D7F9A7FA37FAF7FB27FB97FAE7FB67FB88B71
561
+ 7FC57FC67FCA7FD57FD47FE17FE67FE97FF37FF998DC80068004800B80128018
562
+ 8019801C80218028803F803B804A804680528058805A805F8062806880738072
563
+ 807080768079807D807F808480868085809B8093809A80AD519080AC80DB80E5
564
+ 80D980DD80C480DA80D6810980EF80F1811B81298123812F814B000000000000
565
+ E4
566
+ 0000000000000000000000000000000000000000000000000000000000000000
567
+ 0000000000000000000000000000000000000000000000000000000000000000
568
+ 0000000000000000000000000000000000000000000000000000000000000000
569
+ 0000000000000000000000000000000000000000000000000000000000000000
570
+ 968B8146813E8153815180FC8171816E81658166817481838188818A81808182
571
+ 81A0819581A481A3815F819381A981B081B581BE81B881BD81C081C281BA81C9
572
+ 81CD81D181D981D881C881DA81DF81E081E781FA81FB81FE8201820282058207
573
+ 820A820D821082168229822B82388233824082598258825D825A825F82640000
574
+ 82628268826A826B822E827182778278827E828D829282AB829F82BB82AC82E1
575
+ 82E382DF82D282F482F382FA8393830382FB82F982DE830682DC830982D98335
576
+ 83348316833283318340833983508345832F832B831783188385839A83AA839F
577
+ 83A283968323838E8387838A837C83B58373837583A0838983A883F4841383EB
578
+ 83CE83FD840383D8840B83C183F7840783E083F2840D8422842083BD84388506
579
+ 83FB846D842A843C855A84848477846B84AD846E848284698446842C846F8479
580
+ 843584CA846284B984BF849F84D984CD84BB84DA84D084C184C684D684A18521
581
+ 84FF84F485178518852C851F8515851484FC8540856385588548000000000000
582
+ E5
583
+ 0000000000000000000000000000000000000000000000000000000000000000
584
+ 0000000000000000000000000000000000000000000000000000000000000000
585
+ 0000000000000000000000000000000000000000000000000000000000000000
586
+ 0000000000000000000000000000000000000000000000000000000000000000
587
+ 85418602854B8555858085A485888591858A85A8856D8594859B85EA8587859C
588
+ 8577857E859085C985BA85CF85B985D085D585DD85E585DC85F9860A8613860B
589
+ 85FE85FA86068622861A8630863F864D4E558654865F86678671869386A386A9
590
+ 86AA868B868C86B686AF86C486C686B086C9882386AB86D486DE86E986EC0000
591
+ 86DF86DB86EF8712870687088700870386FB87118709870D86F9870A8734873F
592
+ 8737873B87258729871A8760875F8778874C874E877487578768876E87598753
593
+ 8763876A880587A2879F878287AF87CB87BD87C087D096D687AB87C487B387C7
594
+ 87C687BB87EF87F287E0880F880D87FE87F687F7880E87D28811881688158822
595
+ 88218831883688398827883B8844884288528859885E8862886B8881887E889E
596
+ 8875887D88B5887288828897889288AE889988A2888D88A488B088BF88B188C3
597
+ 88C488D488D888D988DD88F9890288FC88F488E888F28904890C890A89138943
598
+ 891E8925892A892B89418944893B89368938894C891D8960895E000000000000
599
+ E6
600
+ 0000000000000000000000000000000000000000000000000000000000000000
601
+ 0000000000000000000000000000000000000000000000000000000000000000
602
+ 0000000000000000000000000000000000000000000000000000000000000000
603
+ 0000000000000000000000000000000000000000000000000000000000000000
604
+ 89668964896D896A896F89748977897E89838988898A8993899889A189A989A6
605
+ 89AC89AF89B289BA89BD89BF89C089DA89DC89DD89E789F489F88A038A168A10
606
+ 8A0C8A1B8A1D8A258A368A418A5B8A528A468A488A7C8A6D8A6C8A628A858A82
607
+ 8A848AA88AA18A918AA58AA68A9A8AA38AC48ACD8AC28ADA8AEB8AF38AE70000
608
+ 8AE48AF18B148AE08AE28AF78ADE8ADB8B0C8B078B1A8AE18B168B108B178B20
609
+ 8B3397AB8B268B2B8B3E8B288B418B4C8B4F8B4E8B498B568B5B8B5A8B6B8B5F
610
+ 8B6C8B6F8B748B7D8B808B8C8B8E8B928B938B968B998B9A8C3A8C418C3F8C48
611
+ 8C4C8C4E8C508C558C628C6C8C788C7A8C828C898C858C8A8C8D8C8E8C948C7C
612
+ 8C98621D8CAD8CAA8CBD8CB28CB38CAE8CB68CC88CC18CE48CE38CDA8CFD8CFA
613
+ 8CFB8D048D058D0A8D078D0F8D0D8D109F4E8D138CCD8D148D168D678D6D8D71
614
+ 8D738D818D998DC28DBE8DBA8DCF8DDA8DD68DCC8DDB8DCB8DEA8DEB8DDF8DE3
615
+ 8DFC8E088E098DFF8E1D8E1E8E108E1F8E428E358E308E348E4A000000000000
616
+ E7
617
+ 0000000000000000000000000000000000000000000000000000000000000000
618
+ 0000000000000000000000000000000000000000000000000000000000000000
619
+ 0000000000000000000000000000000000000000000000000000000000000000
620
+ 0000000000000000000000000000000000000000000000000000000000000000
621
+ 8E478E498E4C8E508E488E598E648E608E2A8E638E558E768E728E7C8E818E87
622
+ 8E858E848E8B8E8A8E938E918E948E998EAA8EA18EAC8EB08EC68EB18EBE8EC5
623
+ 8EC88ECB8EDB8EE38EFC8EFB8EEB8EFE8F0A8F058F158F128F198F138F1C8F1F
624
+ 8F1B8F0C8F268F338F3B8F398F458F428F3E8F4C8F498F468F4E8F578F5C0000
625
+ 8F628F638F648F9C8F9F8FA38FAD8FAF8FB78FDA8FE58FE28FEA8FEF90878FF4
626
+ 90058FF98FFA901190159021900D901E9016900B90279036903590398FF8904F
627
+ 905090519052900E9049903E90569058905E9068906F907696A890729082907D
628
+ 90819080908A9089908F90A890AF90B190B590E290E4624890DB910291129119
629
+ 91329130914A9156915891639165916991739172918B9189918291A291AB91AF
630
+ 91AA91B591B491BA91C091C191C991CB91D091D691DF91E191DB91FC91F591F6
631
+ 921E91FF9214922C92159211925E925792459249926492489295923F924B9250
632
+ 929C92969293929B925A92CF92B992B792E9930F92FA9344932E000000000000
633
+ E8
634
+ 0000000000000000000000000000000000000000000000000000000000000000
635
+ 0000000000000000000000000000000000000000000000000000000000000000
636
+ 0000000000000000000000000000000000000000000000000000000000000000
637
+ 0000000000000000000000000000000000000000000000000000000000000000
638
+ 93199322931A9323933A9335933B935C9360937C936E935693B093AC93AD9394
639
+ 93B993D693D793E893E593D893C393DD93D093C893E4941A9414941394039407
640
+ 94109436942B94359421943A944194529444945B94609462945E946A92299470
641
+ 94759477947D945A947C947E9481947F95829587958A95949596959895990000
642
+ 95A095A895A795AD95BC95BB95B995BE95CA6FF695C395CD95CC95D595D495D6
643
+ 95DC95E195E595E296219628962E962F9642964C964F964B9677965C965E965D
644
+ 965F96669672966C968D96989695969796AA96A796B196B296B096B496B696B8
645
+ 96B996CE96CB96C996CD894D96DC970D96D596F99704970697089713970E9711
646
+ 970F971697199724972A97309739973D973E97449746974897429749975C9760
647
+ 97649766976852D2976B977197799785977C9781977A9786978B978F9790979C
648
+ 97A897A697A397B397B497C397C697C897CB97DC97ED9F4F97F27ADF97F697F5
649
+ 980F980C9838982498219837983D9846984F984B986B986F9870000000000000
650
+ E9
651
+ 0000000000000000000000000000000000000000000000000000000000000000
652
+ 0000000000000000000000000000000000000000000000000000000000000000
653
+ 0000000000000000000000000000000000000000000000000000000000000000
654
+ 0000000000000000000000000000000000000000000000000000000000000000
655
+ 98719874987398AA98AF98B198B698C498C398C698E998EB9903990999129914
656
+ 99189921991D991E99249920992C992E993D993E9942994999459950994B9951
657
+ 9952994C99559997999899A599AD99AE99BC99DF99DB99DD99D899D199ED99EE
658
+ 99F199F299FB99F89A019A0F9A0599E29A199A2B9A379A459A429A409A430000
659
+ 9A3E9A559A4D9A5B9A579A5F9A629A659A649A699A6B9A6A9AAD9AB09ABC9AC0
660
+ 9ACF9AD19AD39AD49ADE9ADF9AE29AE39AE69AEF9AEB9AEE9AF49AF19AF79AFB
661
+ 9B069B189B1A9B1F9B229B239B259B279B289B299B2A9B2E9B2F9B329B449B43
662
+ 9B4F9B4D9B4E9B519B589B749B939B839B919B969B979B9F9BA09BA89BB49BC0
663
+ 9BCA9BB99BC69BCF9BD19BD29BE39BE29BE49BD49BE19C3A9BF29BF19BF09C15
664
+ 9C149C099C139C0C9C069C089C129C0A9C049C2E9C1B9C259C249C219C309C47
665
+ 9C329C469C3E9C5A9C609C679C769C789CE79CEC9CF09D099D089CEB9D039D06
666
+ 9D2A9D269DAF9D239D1F9D449D159D129D419D3F9D3E9D469D48000000000000
667
+ EA
668
+ 0000000000000000000000000000000000000000000000000000000000000000
669
+ 0000000000000000000000000000000000000000000000000000000000000000
670
+ 0000000000000000000000000000000000000000000000000000000000000000
671
+ 0000000000000000000000000000000000000000000000000000000000000000
672
+ 9D5D9D5E9D649D519D509D599D729D899D879DAB9D6F9D7A9D9A9DA49DA99DB2
673
+ 9DC49DC19DBB9DB89DBA9DC69DCF9DC29DD99DD39DF89DE69DED9DEF9DFD9E1A
674
+ 9E1B9E1E9E759E799E7D9E819E889E8B9E8C9E929E959E919E9D9EA59EA99EB8
675
+ 9EAA9EAD97619ECC9ECE9ECF9ED09ED49EDC9EDE9EDD9EE09EE59EE89EEF0000
676
+ 9EF49EF69EF79EF99EFB9EFC9EFD9F079F0876B79F159F219F2C9F3E9F4A9F52
677
+ 9F549F639F5F9F609F619F669F679F6C9F6A9F779F729F769F959F9C9FA0582F
678
+ 69C79059746451DC719900000000000000000000000000000000000000000000
679
+ 0000000000000000000000000000000000000000000000000000000000000000
680
+ 0000000000000000000000000000000000000000000000000000000000000000
681
+ 0000000000000000000000000000000000000000000000000000000000000000
682
+ 0000000000000000000000000000000000000000000000000000000000000000
683
+ 0000000000000000000000000000000000000000000000000000000000000000
684
+ R
685
+ 8160 301C FF5E
686
+ 8161 2016 2225
687
+ 817C 2212 FF0D
688
+ 8191 00A2 FFE0
689
+ 8192 00A3 FFE1
690
+ 81CA 00AC FFE2
shared/package-files/75/75038d5b2a5bcdfbf31820ed769dccfcd25ac12709bccd838876f1d64fb0c3b8/blob ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.svg
3
+ ~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for SVG output.
6
+
7
+ :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ from pip._vendor.pygments.formatter import Formatter
12
+ from pip._vendor.pygments.token import Comment
13
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt
14
+
15
+ __all__ = ['SvgFormatter']
16
+
17
+
18
+ def escape_html(text):
19
+ """Escape &, <, > as well as single and double quotes for HTML."""
20
+ return text.replace('&', '&amp;'). \
21
+ replace('<', '&lt;'). \
22
+ replace('>', '&gt;'). \
23
+ replace('"', '&quot;'). \
24
+ replace("'", '&#39;')
25
+
26
+
27
+ class2style = {}
28
+
29
+ class SvgFormatter(Formatter):
30
+ """
31
+ Format tokens as an SVG graphics file. This formatter is still experimental.
32
+ Each line of code is a ``<text>`` element with explicit ``x`` and ``y``
33
+ coordinates containing ``<tspan>`` elements with the individual token styles.
34
+
35
+ By default, this formatter outputs a full SVG document including doctype
36
+ declaration and the ``<svg>`` root element.
37
+
38
+ .. versionadded:: 0.9
39
+
40
+ Additional options accepted:
41
+
42
+ `nowrap`
43
+ Don't wrap the SVG ``<text>`` elements in ``<svg><g>`` elements and
44
+ don't add a XML declaration and a doctype. If true, the `fontfamily`
45
+ and `fontsize` options are ignored. Defaults to ``False``.
46
+
47
+ `fontfamily`
48
+ The value to give the wrapping ``<g>`` element's ``font-family``
49
+ attribute, defaults to ``"monospace"``.
50
+
51
+ `fontsize`
52
+ The value to give the wrapping ``<g>`` element's ``font-size``
53
+ attribute, defaults to ``"14px"``.
54
+
55
+ `linenos`
56
+ If ``True``, add line numbers (default: ``False``).
57
+
58
+ `linenostart`
59
+ The line number for the first line (default: ``1``).
60
+
61
+ `linenostep`
62
+ If set to a number n > 1, only every nth line number is printed.
63
+
64
+ `linenowidth`
65
+ Maximum width devoted to line numbers (default: ``3*ystep``, sufficient
66
+ for up to 4-digit line numbers. Increase width for longer code blocks).
67
+
68
+ `xoffset`
69
+ Starting offset in X direction, defaults to ``0``.
70
+
71
+ `yoffset`
72
+ Starting offset in Y direction, defaults to the font size if it is given
73
+ in pixels, or ``20`` else. (This is necessary since text coordinates
74
+ refer to the text baseline, not the top edge.)
75
+
76
+ `ystep`
77
+ Offset to add to the Y coordinate for each subsequent line. This should
78
+ roughly be the text size plus 5. It defaults to that value if the text
79
+ size is given in pixels, or ``25`` else.
80
+
81
+ `spacehack`
82
+ Convert spaces in the source to ``&#160;``, which are non-breaking
83
+ spaces. SVG provides the ``xml:space`` attribute to control how
84
+ whitespace inside tags is handled, in theory, the ``preserve`` value
85
+ could be used to keep all whitespace as-is. However, many current SVG
86
+ viewers don't obey that rule, so this option is provided as a workaround
87
+ and defaults to ``True``.
88
+ """
89
+ name = 'SVG'
90
+ aliases = ['svg']
91
+ filenames = ['*.svg']
92
+
93
+ def __init__(self, **options):
94
+ Formatter.__init__(self, **options)
95
+ self.nowrap = get_bool_opt(options, 'nowrap', False)
96
+ self.fontfamily = options.get('fontfamily', 'monospace')
97
+ self.fontsize = options.get('fontsize', '14px')
98
+ self.xoffset = get_int_opt(options, 'xoffset', 0)
99
+ fs = self.fontsize.strip()
100
+ if fs.endswith('px'): fs = fs[:-2].strip()
101
+ try:
102
+ int_fs = int(fs)
103
+ except:
104
+ int_fs = 20
105
+ self.yoffset = get_int_opt(options, 'yoffset', int_fs)
106
+ self.ystep = get_int_opt(options, 'ystep', int_fs + 5)
107
+ self.spacehack = get_bool_opt(options, 'spacehack', True)
108
+ self.linenos = get_bool_opt(options,'linenos',False)
109
+ self.linenostart = get_int_opt(options,'linenostart',1)
110
+ self.linenostep = get_int_opt(options,'linenostep',1)
111
+ self.linenowidth = get_int_opt(options,'linenowidth', 3*self.ystep)
112
+ self._stylecache = {}
113
+
114
+ def format_unencoded(self, tokensource, outfile):
115
+ """
116
+ Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``
117
+ tuples and write it into ``outfile``.
118
+
119
+ For our implementation we put all lines in their own 'line group'.
120
+ """
121
+ x = self.xoffset
122
+ y = self.yoffset
123
+ if not self.nowrap:
124
+ if self.encoding:
125
+ outfile.write('<?xml version="1.0" encoding="%s"?>\n' %
126
+ self.encoding)
127
+ else:
128
+ outfile.write('<?xml version="1.0"?>\n')
129
+ outfile.write('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" '
130
+ '"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/'
131
+ 'svg10.dtd">\n')
132
+ outfile.write('<svg xmlns="http://www.w3.org/2000/svg">\n')
133
+ outfile.write('<g font-family="%s" font-size="%s">\n' %
134
+ (self.fontfamily, self.fontsize))
135
+
136
+ counter = self.linenostart
137
+ counter_step = self.linenostep
138
+ counter_style = self._get_style(Comment)
139
+ line_x = x
140
+
141
+ if self.linenos:
142
+ if counter % counter_step == 0:
143
+ outfile.write('<text x="%s" y="%s" %s text-anchor="end">%s</text>' %
144
+ (x+self.linenowidth,y,counter_style,counter))
145
+ line_x += self.linenowidth + self.ystep
146
+ counter += 1
147
+
148
+ outfile.write('<text x="%s" y="%s" xml:space="preserve">' % (line_x, y))
149
+ for ttype, value in tokensource:
150
+ style = self._get_style(ttype)
151
+ tspan = style and '<tspan' + style + '>' or ''
152
+ tspanend = tspan and '</tspan>' or ''
153
+ value = escape_html(value)
154
+ if self.spacehack:
155
+ value = value.expandtabs().replace(' ', '&#160;')
156
+ parts = value.split('\n')
157
+ for part in parts[:-1]:
158
+ outfile.write(tspan + part + tspanend)
159
+ y += self.ystep
160
+ outfile.write('</text>\n')
161
+ if self.linenos and counter % counter_step == 0:
162
+ outfile.write('<text x="%s" y="%s" text-anchor="end" %s>%s</text>' %
163
+ (x+self.linenowidth,y,counter_style,counter))
164
+
165
+ counter += 1
166
+ outfile.write('<text x="%s" y="%s" ' 'xml:space="preserve">' % (line_x,y))
167
+ outfile.write(tspan + parts[-1] + tspanend)
168
+ outfile.write('</text>')
169
+
170
+ if not self.nowrap:
171
+ outfile.write('</g></svg>\n')
172
+
173
+ def _get_style(self, tokentype):
174
+ if tokentype in self._stylecache:
175
+ return self._stylecache[tokentype]
176
+ otokentype = tokentype
177
+ while not self.style.styles_token(tokentype):
178
+ tokentype = tokentype.parent
179
+ value = self.style.style_for_token(tokentype)
180
+ result = ''
181
+ if value['color']:
182
+ result = ' fill="#' + value['color'] + '"'
183
+ if value['bold']:
184
+ result += ' font-weight="bold"'
185
+ if value['italic']:
186
+ result += ' font-style="italic"'
187
+ self._stylecache[otokentype] = result
188
+ return result
shared/package-files/75/7505076b53c6a49b0d136c7f490171b4e5fe8e8bac12aa65c07d5b76c93a9a71/blob ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # file generated by setuptools_scm
2
+ # don't change, don't track in version control
3
+ __version__ = version = '0.2.0'
4
+ __version_tuple__ = version_tuple = (0, 2, 0)
shared/package-files/75/7505f48f7ae32af9c3cce082d4d3c7d4adc28018d428e52968dd27b50b586edf/blob 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 at::Tensor & _mkldnn_reshape_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef shape);
21
+ TORCH_API at::Tensor & _mkldnn_reshape_outf(const at::Tensor & self, at::IntArrayRef shape, at::Tensor & out);
22
+
23
+ } // namespace compositeexplicitautograd
24
+ } // namespace at
shared/package-files/75/750a5404fadd8bddb13c09751eacd776c431166e124a0e2dd0d01bd9b8fb2314/blob ADDED
@@ -0,0 +1,590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: disable-error-code="type-arg"
2
+ from datetime import timedelta
3
+ from enum import Enum
4
+ from typing import Any, Dict, List, Optional, overload, Tuple, Union
5
+
6
+ import torch
7
+ from torch import Tensor
8
+ from torch._C import ScriptObject
9
+ from torch.futures import Future
10
+
11
+ # This module is defined in torch/csrc/distributed/c10d/init.cpp
12
+
13
+ _DEFAULT_FIRST_BUCKET_BYTES: int
14
+ _DEFAULT_NO_TIMEOUT: timedelta
15
+ _DEFAULT_PG_TIMEOUT: timedelta
16
+ _DEFAULT_PG_NCCL_TIMEOUT: timedelta
17
+
18
+ class BuiltinCommHookType(Enum):
19
+ ALLREDUCE = ...
20
+ FP16_COMPRESS = ...
21
+
22
+ def _register_comm_hook(reducer: Reducer, state: Any, comm_hook: Any): ...
23
+ def _register_builtin_comm_hook(
24
+ reducer: Reducer,
25
+ comm_hook_type: BuiltinCommHookType,
26
+ ): ...
27
+ def _set_global_rank(rank: int) -> None: ...
28
+ def _hash_tensors(tensors: List[Tensor]) -> int: ...
29
+
30
+ class GradBucket:
31
+ def index(self) -> int: ...
32
+ def buffer(self) -> Tensor: ...
33
+ def gradients(self) -> List[Tensor]: ...
34
+ def is_last(self) -> bool: ...
35
+ def set_buffer(self, tensor: Tensor) -> None: ...
36
+ def parameters(self) -> List[Tensor]: ...
37
+
38
+ class Reducer:
39
+ def __init__(
40
+ self,
41
+ params: List[Tensor],
42
+ bucket_indices: List[List[int]],
43
+ per_bucket_size_limits: List[int],
44
+ process_group: ProcessGroup,
45
+ expect_sparse_gradients: List[bool] = ...,
46
+ bucket_bytes_cap: int = ..., # kDefaultBucketBytesCap in reducer.hpp
47
+ find_unused_parameters: bool = ...,
48
+ gradient_as_bucket_view: bool = ...,
49
+ param_to_name_mapping: Dict[int, str] = ...,
50
+ first_bucket_types_cap: int = ..., # kDefaultFirstBucketBytes in reducer.hpp
51
+ ): ...
52
+ def prepare_for_forward(self) -> None: ...
53
+ def prepare_for_backward(self, output: List[Tensor]) -> None: ...
54
+ def get_backward_stats(self) -> List[int]: ...
55
+ def _install_post_backward_futures(self, futures: List[Future]) -> None: ...
56
+ def _rebuild_buckets(self) -> bool: ...
57
+ def _get_zeros_like_grad_buckets(self) -> List[GradBucket]: ...
58
+ def _push_all_rebuilt_params(self) -> None: ...
59
+ def _set_forward_pass_work_handle(
60
+ self,
61
+ work: Work,
62
+ use_static_world_size: bool,
63
+ ): ...
64
+ def _get_local_used_map(self) -> Tensor: ...
65
+ def _set_ddp_runtime_logging_sample_rate(self, sample_rate: int) -> None: ...
66
+ def _set_static_graph(self) -> None: ...
67
+ def _run_comm_hook(self, bucket: GradBucket) -> Future: ...
68
+ def set_logger(self, logger: Logger) -> None: ...
69
+ def _remove_autograd_hooks(self) -> None: ...
70
+ def _check_reducer_finalized(self) -> None: ...
71
+ def _set_sparse_metadata(self, global_unique_ids: Dict[str, Tensor]) -> None: ...
72
+ def _reset_state(self) -> None: ...
73
+ def _update_process_group(self, new_process_group: ProcessGroup) -> None: ...
74
+
75
+ class DDPLoggingData:
76
+ strs_map: Dict[str, str]
77
+ ints_map: Dict[str, int]
78
+
79
+ class Logger:
80
+ def __init__(self, reducer: Reducer): ...
81
+ def set_construction_data_and_log(
82
+ self,
83
+ module_name: str,
84
+ device_ids: List[int],
85
+ output_device: int,
86
+ broadcast_buffers: bool,
87
+ has_sync_bn: bool,
88
+ static_graph: bool,
89
+ ): ...
90
+ def set_runtime_stats_and_log(self) -> None: ...
91
+ def set_error_and_log(self, error: str) -> None: ...
92
+ def _get_ddp_logging_data(self) -> DDPLoggingData: ...
93
+ def _set_comm_hook_name(self, comm_hook: str) -> None: ...
94
+ def _set_uneven_input_join(self) -> None: ...
95
+ def _set_static_graph(self) -> None: ...
96
+
97
+ def get_debug_level(): ...
98
+ def set_debug_level(): ...
99
+ def set_debug_level_from_env(): ...
100
+
101
+ class DebugLevel(Enum):
102
+ OFF = ...
103
+ INFO = ...
104
+ DETAIL = ...
105
+
106
+ class ReduceOp:
107
+ def __init__(self, op: RedOpType): ...
108
+
109
+ SUM: RedOpType = ...
110
+ AVG: RedOpType = ...
111
+ PRODUCT: RedOpType = ...
112
+ MIN: RedOpType = ...
113
+ MAX: RedOpType = ...
114
+ BAND: RedOpType = ...
115
+ BOR: RedOpType = ...
116
+ BXOR: RedOpType = ...
117
+ PREMUL_SUM: RedOpType = ...
118
+ UNUSED: RedOpType = ...
119
+
120
+ class RedOpType(Enum): ...
121
+
122
+ class BroadcastOptions:
123
+ rootRank: int
124
+ rootTensor: int
125
+ timeout: timedelta
126
+ asyncOp: bool
127
+
128
+ class AllreduceOptions:
129
+ reduceOp: ReduceOp
130
+ timeout: timedelta
131
+
132
+ class AllreduceCoalescedOptions(AllreduceOptions): ...
133
+
134
+ class ReduceOptions:
135
+ reduceOp: ReduceOp
136
+ rootRank: int
137
+ rootTensor: int
138
+ timeout: timedelta
139
+
140
+ class AllgatherOptions:
141
+ timeout: timedelta
142
+ asyncOp: bool
143
+
144
+ class GatherOptions:
145
+ rootRank: int
146
+ timeout: timedelta
147
+
148
+ class ScatterOptions:
149
+ rootRank: int
150
+ timeout: timedelta
151
+ asyncOp: bool
152
+
153
+ class ReduceScatterOptions:
154
+ reduceOp: ReduceOp
155
+ timeout: timedelta
156
+ asyncOp: bool
157
+
158
+ class BarrierOptions:
159
+ device_ids: List[int]
160
+ device: torch.device
161
+ timeout: timedelta
162
+
163
+ class AllToAllOptions:
164
+ timeout: timedelta
165
+
166
+ class Store:
167
+ def set(self, key: str, value: str): ...
168
+ def get(self, key: str) -> bytes: ...
169
+ def add(self, key: str, value: int) -> int: ...
170
+ def compare_set(
171
+ self,
172
+ key: str,
173
+ expected_value: str,
174
+ desired_value: str,
175
+ ) -> bytes: ...
176
+ def delete_key(self, key: str) -> bool: ...
177
+ def num_keys(self) -> int: ...
178
+ def set_timeout(self, timeout: timedelta): ...
179
+ @overload
180
+ def wait(self, keys: List[str]): ...
181
+ @overload
182
+ def wait(self, keys: List[str], timeout: timedelta): ...
183
+
184
+ class FileStore(Store):
185
+ def __init__(self, path: str, numWorkers: int = ...): ...
186
+
187
+ class HashStore(Store):
188
+ def __init__(self): ...
189
+
190
+ class TCPStore(Store):
191
+ def __init__(
192
+ self,
193
+ host_name: str,
194
+ port: int,
195
+ world_size: Optional[int] = ...,
196
+ is_master: bool = ...,
197
+ timeout: timedelta = ...,
198
+ wait_for_workers: bool = ...,
199
+ multi_tenant: bool = ...,
200
+ master_listen_fd: Optional[int] = ...,
201
+ use_libuv: Optional[bool] = ...,
202
+ ): ...
203
+ @property
204
+ def host(self) -> str: ...
205
+ @property
206
+ def port(self) -> int: ...
207
+
208
+ class PrefixStore(Store):
209
+ def __init__(self, prefix: str, store: Store): ...
210
+ @property
211
+ def underlying_store(self) -> Store: ...
212
+
213
+ class _DistributedBackendOptions:
214
+ def __init__(self): ...
215
+ @property
216
+ def store(self) -> Store: ...
217
+ @store.setter
218
+ def store(self, store: Store) -> None: ...
219
+ @property
220
+ def group_rank(self) -> int: ...
221
+ @group_rank.setter
222
+ def group_rank(self, rank: int) -> None: ...
223
+ @property
224
+ def group_size(self) -> int: ...
225
+ @group_size.setter
226
+ def group_size(self, size: int) -> None: ...
227
+ @property
228
+ def timeout(self) -> timedelta: ...
229
+ @timeout.setter
230
+ def timeout(self, timeout: timedelta) -> None: ...
231
+ @property
232
+ def group_id(self) -> str: ...
233
+ @group_id.setter
234
+ def group_id(self, group_id: str) -> None: ...
235
+ @property
236
+ def global_ranks_in_group(self) -> List[int]: ...
237
+ @global_ranks_in_group.setter
238
+ def global_ranks_in_group(self, ranks: List[int]) -> None: ...
239
+
240
+ class Work:
241
+ def is_completed(self) -> bool: ...
242
+ def is_success(self) -> bool: ...
243
+ def exception(self) -> Any: ...
244
+ def wait(self, timeout: timedelta = ...) -> bool: ...
245
+ def get_future(self) -> Future: ...
246
+ def source_rank(self) -> int: ...
247
+ def _source_rank(self) -> int: ...
248
+ def result(self) -> List[Tensor]: ...
249
+ def synchronize(self): ...
250
+ def boxed(self) -> ScriptObject: ...
251
+ @staticmethod
252
+ def unbox(obj: ScriptObject) -> Work: ...
253
+
254
+ class Backend:
255
+ def __init__(
256
+ self,
257
+ rank: int,
258
+ size: int,
259
+ ): ...
260
+ @property
261
+ def supports_splitting(self) -> bool: ...
262
+ def rank(self) -> int: ...
263
+ def size(self) -> int: ...
264
+ def eager_connect_single_device(self, device: Optional[torch.device]) -> None: ...
265
+ def _set_sequence_number_for_group(self) -> None: ...
266
+
267
+ class ProcessGroup:
268
+ class Options:
269
+ def __init__(self, backend: str, timeout: timedelta = ...): ...
270
+ @property
271
+ def backend(self) -> str: ...
272
+ @property
273
+ def _timeout(self) -> timedelta: ...
274
+ @_timeout.setter
275
+ def _timeout(self, val: timedelta) -> None: ...
276
+
277
+ class BackendType(Enum):
278
+ UNDEFINED = ...
279
+ GLOO = ...
280
+ NCCL = ...
281
+ UCC = ...
282
+ MPI = ...
283
+ CUSTOM = ...
284
+ def __init__(self, store: Store, rank: int, size: int, options: Options): ...
285
+ def rank(self) -> int: ...
286
+ def size(self) -> int: ...
287
+ @overload
288
+ def broadcast(
289
+ self,
290
+ tensors: List[Tensor],
291
+ opts=...,
292
+ ) -> Work: ...
293
+ @overload
294
+ def broadcast(
295
+ self,
296
+ tensor: Tensor,
297
+ root: int,
298
+ ) -> Work: ...
299
+ @overload
300
+ def allreduce(
301
+ self,
302
+ tensors: List[Tensor],
303
+ opts: AllreduceOptions = ...,
304
+ ) -> Work: ...
305
+ @overload
306
+ def allreduce(
307
+ self,
308
+ tensors: List[Tensor],
309
+ op=...,
310
+ ) -> Work: ...
311
+ @overload
312
+ def allreduce(
313
+ self,
314
+ tensor: Tensor,
315
+ op=...,
316
+ ) -> Work: ...
317
+ def allreduce_coalesced(
318
+ self,
319
+ tensors: List[Tensor],
320
+ opts=...,
321
+ ) -> Work: ...
322
+ def reduce_scatter_tensor_coalesced(
323
+ self,
324
+ outputTensors: List[Tensor],
325
+ inputTensors: List[Tensor],
326
+ opts: Optional[ReduceScatterOptions] = None,
327
+ ) -> Work: ...
328
+ @overload
329
+ def reduce(
330
+ self,
331
+ tensors: List[Tensor],
332
+ opts=...,
333
+ ) -> Work: ...
334
+ @overload
335
+ def reduce(
336
+ self,
337
+ tensor: Tensor,
338
+ root: int,
339
+ op=...,
340
+ ) -> Work: ...
341
+ @overload
342
+ def allgather(
343
+ self,
344
+ output_tensors: List[List[Tensor]],
345
+ input_tensors: List[Tensor],
346
+ opts=...,
347
+ ) -> Work: ...
348
+ @overload
349
+ def allgather(
350
+ self,
351
+ output_tensors: List[Tensor],
352
+ input_tensor: Tensor,
353
+ ) -> Work: ...
354
+ def _allgather_base(
355
+ self,
356
+ output: Tensor,
357
+ input: Tensor,
358
+ opts=...,
359
+ ) -> Work: ...
360
+ def allgather_coalesced(
361
+ self,
362
+ output_lists: List[List[Tensor]],
363
+ input_list: List[Tensor],
364
+ opts=...,
365
+ ) -> Work: ...
366
+ def allgather_into_tensor_coalesced(
367
+ self,
368
+ output_lists: List[Tensor],
369
+ input_list: List[Tensor],
370
+ opts=...,
371
+ ) -> Work: ...
372
+ @overload
373
+ def gather(
374
+ self,
375
+ output_tensors: List[List[Tensor]],
376
+ input_tensors: List[Tensor],
377
+ opts=...,
378
+ ) -> Work: ...
379
+ @overload
380
+ def gather(
381
+ self,
382
+ output_tensors: List[Tensor],
383
+ input_tensor: Tensor,
384
+ root: int,
385
+ ) -> Work: ...
386
+ @overload
387
+ def scatter(
388
+ self,
389
+ output_tensors: List[Tensor],
390
+ input_tensors: List[List[Tensor]],
391
+ opts=...,
392
+ ) -> Work: ...
393
+ @overload
394
+ def scatter(
395
+ self,
396
+ output_tensor: Tensor,
397
+ input_tensors: List[Tensor],
398
+ root: int,
399
+ ) -> Work: ...
400
+ @overload
401
+ def reduce_scatter(
402
+ self,
403
+ output_tensors: List[Tensor],
404
+ input_tensors: List[List[Tensor]],
405
+ opts=...,
406
+ ) -> Work: ...
407
+ @overload
408
+ def reduce_scatter(
409
+ self,
410
+ output_tensors: Tensor,
411
+ input_tensor: List[Tensor],
412
+ ) -> Work: ...
413
+ def _reduce_scatter_base(
414
+ self,
415
+ outputTensor: Tensor,
416
+ inputTensor: Tensor,
417
+ opts: Optional[ReduceScatterOptions],
418
+ ) -> Work: ...
419
+ @overload
420
+ def alltoall_base(
421
+ self,
422
+ output_tensor: Tensor,
423
+ input_tensor: Tensor,
424
+ output_split_sizes: List[int],
425
+ input_split_sizes: List[int],
426
+ opts=...,
427
+ ) -> Work: ...
428
+ @overload
429
+ def alltoall_base(
430
+ self,
431
+ output: Tensor,
432
+ input: Tensor,
433
+ output_split_sizes: List[int],
434
+ input_split_sizes: List[int],
435
+ ) -> Work: ...
436
+ @overload
437
+ def alltoall(
438
+ self,
439
+ output_tensor: List[Tensor],
440
+ input_tensor: List[Tensor],
441
+ opts=...,
442
+ ) -> Work: ...
443
+ @overload
444
+ def alltoall(
445
+ self,
446
+ output: List[Tensor],
447
+ input: List[Tensor],
448
+ ) -> Work: ...
449
+ def send(
450
+ self,
451
+ tensors: List[Tensor],
452
+ dstRank: int,
453
+ tag: int,
454
+ ) -> Work: ...
455
+ def recv(
456
+ self,
457
+ tensors: List[Tensor],
458
+ srcRank: int,
459
+ tag: int,
460
+ ) -> Work: ...
461
+ def recv_anysource(self, tensors: List[Tensor], tag: int) -> Work: ...
462
+ def barrier(self, opts=...) -> Work: ...
463
+ def boxed(self) -> ScriptObject: ...
464
+ @staticmethod
465
+ def unbox(obj: ScriptObject) -> ProcessGroup: ...
466
+ def _start_coalescing(self, device: torch.device) -> None: ...
467
+ def _end_coalescing(self, device: torch.device) -> Work: ...
468
+ def _get_backend_name(self) -> str: ...
469
+ def _backend_id(self, backend_type: BackendType) -> int: ...
470
+ @property
471
+ def _device_types(self) -> List[torch.device]: ...
472
+ def _get_backend(self, device: torch.device) -> Backend: ...
473
+ def _register_backend(
474
+ self,
475
+ device: torch.device,
476
+ backend_type: BackendType,
477
+ backend: Optional[Backend],
478
+ ) -> None: ...
479
+ def _set_group_name(self, name: str) -> None: ...
480
+ def name(self) -> str: ...
481
+ def _has_hooks(self) -> bool: ...
482
+ def _wait_for_pending_works(self) -> None: ...
483
+ def _set_sequence_number_for_group(self) -> None: ...
484
+ @property
485
+ def bound_device_id(self) -> Optional[torch.device]: ...
486
+ @bound_device_id.setter
487
+ def bound_device_id(self, device: Optional[torch.device]) -> None: ...
488
+ @property
489
+ def group_name(self) -> str: ...
490
+
491
+ class ProcessGroupRoundRobin(ProcessGroup): ...
492
+
493
+ def _round_robin_process_groups(
494
+ process_groups: List[ProcessGroup],
495
+ ) -> ProcessGroupRoundRobin: ...
496
+
497
+ class ProcessGroupGloo(Backend):
498
+ class Device: ...
499
+ class Options: ...
500
+
501
+ def __init__(
502
+ self,
503
+ store: Store,
504
+ rank: int,
505
+ size: int,
506
+ timeout: timedelta,
507
+ ): ...
508
+ @staticmethod
509
+ def create_device(hostname="", interface="") -> Device: ...
510
+ @staticmethod
511
+ def create_default_device() -> Device: ...
512
+ def _set_default_timeout(self, timeout) -> None: ...
513
+
514
+ class _ProcessGroupWrapper(Backend):
515
+ def __init__(self, pg: Backend, gloo_pg: ProcessGroupGloo): ...
516
+ wrapped_pg: Backend
517
+
518
+ class ProcessGroupNCCL(Backend):
519
+ class Options:
520
+ def __init__(self, timeout: Optional[timedelta] = None): ...
521
+ @property
522
+ def backend(self) -> str: ...
523
+ @property
524
+ def _timeout(self) -> timedelta: ...
525
+ @_timeout.setter
526
+ def _timeout(self, val: timedelta) -> None: ...
527
+ @property
528
+ def _is_high_priority_stream(self) -> bool: ...
529
+ @_is_high_priority_stream.setter
530
+ def _is_high_priority_stream(self, val: bool) -> None: ...
531
+
532
+ def __init__(
533
+ self,
534
+ store: Store,
535
+ rank: int,
536
+ size: int,
537
+ timeout: timedelta,
538
+ ): ...
539
+ def _group_start(self) -> None: ...
540
+ def _group_end(self) -> None: ...
541
+ def _set_default_timeout(self, timeout) -> None: ...
542
+ def _shutdown(self) -> None: ...
543
+ @property
544
+ def uid(self) -> int: ...
545
+
546
+ class ProcessGroupUCC(Backend):
547
+ def __init__(
548
+ self,
549
+ store: Store,
550
+ rank: int,
551
+ size: int,
552
+ timeout: timedelta,
553
+ ): ...
554
+
555
+ class ProcessGroupMPI(Backend):
556
+ def __init__(
557
+ self,
558
+ rank: int,
559
+ size: int,
560
+ pgComm: int,
561
+ ): ...
562
+ @staticmethod
563
+ def create(ranks: List[int]) -> ProcessGroupMPI: ...
564
+
565
+ def _compute_bucket_assignment_by_size(
566
+ tensors: List[Tensor],
567
+ bucket_size_limits: List[int],
568
+ expect_sparse_gradient: List[bool] = ...,
569
+ tensor_indices: List[int] = ...,
570
+ ) -> Tuple[List[List[int]], List[int]]: ...
571
+ def _broadcast_coalesced(
572
+ process_group: ProcessGroup,
573
+ tensors: List[Tensor],
574
+ buffer_size: int,
575
+ src: int,
576
+ ): ...
577
+ def _test_python_store(store: Store): ...
578
+ def _verify_params_across_processes(
579
+ process_group: ProcessGroup,
580
+ params: List[Tensor],
581
+ logger: Optional[Logger],
582
+ ): ...
583
+ def _make_nccl_premul_sum(factor: Union[float, List[Tensor]]) -> ReduceOp: ...
584
+ def _register_process_group(
585
+ group_name: str,
586
+ process_group: ProcessGroup,
587
+ ) -> None: ...
588
+ def _resolve_process_group(group_name: str) -> ProcessGroup: ...
589
+ def _unregister_all_process_groups() -> None: ...
590
+ def _unregister_process_group(group_name: str) -> None: ...
shared/package-files/75/750aa994ff806563d944a8a8f0b9938d85a5098cfd5665bebac52bb5a2e977fc/blob ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <functional>
21
+ #include <memory>
22
+ #include <vector>
23
+
24
+ #include "arrow/acero/options.h"
25
+ #include "arrow/record_batch.h"
26
+ #include "arrow/result.h"
27
+ #include "arrow/status.h"
28
+ #include "arrow/type.h"
29
+
30
+ namespace arrow {
31
+
32
+ using compute::ExecContext;
33
+
34
+ namespace acero {
35
+
36
+ class OrderByImpl {
37
+ public:
38
+ virtual ~OrderByImpl() = default;
39
+
40
+ virtual void InputReceived(const std::shared_ptr<RecordBatch>& batch) = 0;
41
+
42
+ virtual Result<Datum> DoFinish() = 0;
43
+
44
+ virtual std::string ToString() const = 0;
45
+
46
+ static Result<std::unique_ptr<OrderByImpl>> MakeSort(
47
+ ExecContext* ctx, const std::shared_ptr<Schema>& output_schema,
48
+ const SortOptions& options);
49
+
50
+ static Result<std::unique_ptr<OrderByImpl>> MakeSelectK(
51
+ ExecContext* ctx, const std::shared_ptr<Schema>& output_schema,
52
+ const SelectKOptions& options);
53
+ };
54
+
55
+ } // namespace acero
56
+ } // namespace arrow
shared/package-files/75/750c6b9abcaee83e2a1cacaa7e5c588e87c4a28cfac5707dae39edb908087b84/blob ADDED
@@ -0,0 +1,1113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import re
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas._libs import lib
8
+ from pandas.errors import UnsupportedFunctionCall
9
+
10
+ import pandas as pd
11
+ from pandas import (
12
+ DataFrame,
13
+ NamedAgg,
14
+ Series,
15
+ )
16
+ import pandas._testing as tm
17
+ from pandas.core.indexes.datetimes import date_range
18
+
19
+
20
+ @pytest.fixture
21
+ def dti():
22
+ return date_range(start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq="Min")
23
+
24
+
25
+ @pytest.fixture
26
+ def _test_series(dti):
27
+ return Series(np.random.default_rng(2).random(len(dti)), dti)
28
+
29
+
30
+ @pytest.fixture
31
+ def test_frame(dti, _test_series):
32
+ return DataFrame({"A": _test_series, "B": _test_series, "C": np.arange(len(dti))})
33
+
34
+
35
+ def test_str(_test_series):
36
+ r = _test_series.resample("h")
37
+ assert (
38
+ "DatetimeIndexResampler [freq=<Hour>, axis=0, closed=left, "
39
+ "label=left, convention=start, origin=start_day]" in str(r)
40
+ )
41
+
42
+ r = _test_series.resample("h", origin="2000-01-01")
43
+ assert (
44
+ "DatetimeIndexResampler [freq=<Hour>, axis=0, closed=left, "
45
+ "label=left, convention=start, origin=2000-01-01 00:00:00]" in str(r)
46
+ )
47
+
48
+
49
+ def test_api(_test_series):
50
+ r = _test_series.resample("h")
51
+ result = r.mean()
52
+ assert isinstance(result, Series)
53
+ assert len(result) == 217
54
+
55
+ r = _test_series.to_frame().resample("h")
56
+ result = r.mean()
57
+ assert isinstance(result, DataFrame)
58
+ assert len(result) == 217
59
+
60
+
61
+ def test_groupby_resample_api():
62
+ # GH 12448
63
+ # .groupby(...).resample(...) hitting warnings
64
+ # when appropriate
65
+ df = DataFrame(
66
+ {
67
+ "date": date_range(start="2016-01-01", periods=4, freq="W"),
68
+ "group": [1, 1, 2, 2],
69
+ "val": [5, 6, 7, 8],
70
+ }
71
+ ).set_index("date")
72
+
73
+ # replication step
74
+ i = (
75
+ date_range("2016-01-03", periods=8).tolist()
76
+ + date_range("2016-01-17", periods=8).tolist()
77
+ )
78
+ index = pd.MultiIndex.from_arrays([[1] * 8 + [2] * 8, i], names=["group", "date"])
79
+ expected = DataFrame({"val": [5] * 7 + [6] + [7] * 7 + [8]}, index=index)
80
+ msg = "DataFrameGroupBy.apply operated on the grouping columns"
81
+ with tm.assert_produces_warning(FutureWarning, match=msg):
82
+ result = df.groupby("group").apply(lambda x: x.resample("1D").ffill())[["val"]]
83
+ tm.assert_frame_equal(result, expected)
84
+
85
+
86
+ def test_groupby_resample_on_api():
87
+ # GH 15021
88
+ # .groupby(...).resample(on=...) results in an unexpected
89
+ # keyword warning.
90
+ df = DataFrame(
91
+ {
92
+ "key": ["A", "B"] * 5,
93
+ "dates": date_range("2016-01-01", periods=10),
94
+ "values": np.random.default_rng(2).standard_normal(10),
95
+ }
96
+ )
97
+
98
+ expected = df.set_index("dates").groupby("key").resample("D").mean()
99
+ result = df.groupby("key").resample("D", on="dates").mean()
100
+ tm.assert_frame_equal(result, expected)
101
+
102
+
103
+ def test_resample_group_keys():
104
+ df = DataFrame({"A": 1, "B": 2}, index=date_range("2000", periods=10))
105
+ expected = df.copy()
106
+
107
+ # group_keys=False
108
+ g = df.resample("5D", group_keys=False)
109
+ result = g.apply(lambda x: x)
110
+ tm.assert_frame_equal(result, expected)
111
+
112
+ # group_keys defaults to False
113
+ g = df.resample("5D")
114
+ result = g.apply(lambda x: x)
115
+ tm.assert_frame_equal(result, expected)
116
+
117
+ # group_keys=True
118
+ expected.index = pd.MultiIndex.from_arrays(
119
+ [
120
+ pd.to_datetime(["2000-01-01", "2000-01-06"]).as_unit("ns").repeat(5),
121
+ expected.index,
122
+ ]
123
+ )
124
+ g = df.resample("5D", group_keys=True)
125
+ result = g.apply(lambda x: x)
126
+ tm.assert_frame_equal(result, expected)
127
+
128
+
129
+ def test_pipe(test_frame, _test_series):
130
+ # GH17905
131
+
132
+ # series
133
+ r = _test_series.resample("h")
134
+ expected = r.max() - r.mean()
135
+ result = r.pipe(lambda x: x.max() - x.mean())
136
+ tm.assert_series_equal(result, expected)
137
+
138
+ # dataframe
139
+ r = test_frame.resample("h")
140
+ expected = r.max() - r.mean()
141
+ result = r.pipe(lambda x: x.max() - x.mean())
142
+ tm.assert_frame_equal(result, expected)
143
+
144
+
145
+ def test_getitem(test_frame):
146
+ r = test_frame.resample("h")
147
+ tm.assert_index_equal(r._selected_obj.columns, test_frame.columns)
148
+
149
+ r = test_frame.resample("h")["B"]
150
+ assert r._selected_obj.name == test_frame.columns[1]
151
+
152
+ # technically this is allowed
153
+ r = test_frame.resample("h")["A", "B"]
154
+ tm.assert_index_equal(r._selected_obj.columns, test_frame.columns[[0, 1]])
155
+
156
+ r = test_frame.resample("h")["A", "B"]
157
+ tm.assert_index_equal(r._selected_obj.columns, test_frame.columns[[0, 1]])
158
+
159
+
160
+ @pytest.mark.parametrize("key", [["D"], ["A", "D"]])
161
+ def test_select_bad_cols(key, test_frame):
162
+ g = test_frame.resample("h")
163
+ # 'A' should not be referenced as a bad column...
164
+ # will have to rethink regex if you change message!
165
+ msg = r"^\"Columns not found: 'D'\"$"
166
+ with pytest.raises(KeyError, match=msg):
167
+ g[key]
168
+
169
+
170
+ def test_attribute_access(test_frame):
171
+ r = test_frame.resample("h")
172
+ tm.assert_series_equal(r.A.sum(), r["A"].sum())
173
+
174
+
175
+ @pytest.mark.parametrize("attr", ["groups", "ngroups", "indices"])
176
+ def test_api_compat_before_use(attr):
177
+ # make sure that we are setting the binner
178
+ # on these attributes
179
+ rng = date_range("1/1/2012", periods=100, freq="s")
180
+ ts = Series(np.arange(len(rng)), index=rng)
181
+ rs = ts.resample("30s")
182
+
183
+ # before use
184
+ getattr(rs, attr)
185
+
186
+ # after grouper is initialized is ok
187
+ rs.mean()
188
+ getattr(rs, attr)
189
+
190
+
191
+ def tests_raises_on_nuisance(test_frame, using_infer_string):
192
+ df = test_frame
193
+ df["D"] = "foo"
194
+ r = df.resample("h")
195
+ result = r[["A", "B"]].mean()
196
+ expected = pd.concat([r.A.mean(), r.B.mean()], axis=1)
197
+ tm.assert_frame_equal(result, expected)
198
+
199
+ expected = r[["A", "B", "C"]].mean()
200
+ msg = re.escape("agg function failed [how->mean,dtype->")
201
+ if using_infer_string:
202
+ msg = "dtype 'str' does not support operation 'mean'"
203
+ with pytest.raises(TypeError, match=msg):
204
+ r.mean()
205
+ result = r.mean(numeric_only=True)
206
+ tm.assert_frame_equal(result, expected)
207
+
208
+
209
+ def test_downsample_but_actually_upsampling():
210
+ # this is reindex / asfreq
211
+ rng = date_range("1/1/2012", periods=100, freq="s")
212
+ ts = Series(np.arange(len(rng), dtype="int64"), index=rng)
213
+ result = ts.resample("20s").asfreq()
214
+ expected = Series(
215
+ [0, 20, 40, 60, 80],
216
+ index=date_range("2012-01-01 00:00:00", freq="20s", periods=5),
217
+ )
218
+ tm.assert_series_equal(result, expected)
219
+
220
+
221
+ def test_combined_up_downsampling_of_irregular():
222
+ # since we are really doing an operation like this
223
+ # ts2.resample('2s').mean().ffill()
224
+ # preserve these semantics
225
+
226
+ rng = date_range("1/1/2012", periods=100, freq="s")
227
+ ts = Series(np.arange(len(rng)), index=rng)
228
+ ts2 = ts.iloc[[0, 1, 2, 3, 5, 7, 11, 15, 16, 25, 30]]
229
+
230
+ result = ts2.resample("2s").mean().ffill()
231
+ expected = Series(
232
+ [
233
+ 0.5,
234
+ 2.5,
235
+ 5.0,
236
+ 7.0,
237
+ 7.0,
238
+ 11.0,
239
+ 11.0,
240
+ 15.0,
241
+ 16.0,
242
+ 16.0,
243
+ 16.0,
244
+ 16.0,
245
+ 25.0,
246
+ 25.0,
247
+ 25.0,
248
+ 30.0,
249
+ ],
250
+ index=pd.DatetimeIndex(
251
+ [
252
+ "2012-01-01 00:00:00",
253
+ "2012-01-01 00:00:02",
254
+ "2012-01-01 00:00:04",
255
+ "2012-01-01 00:00:06",
256
+ "2012-01-01 00:00:08",
257
+ "2012-01-01 00:00:10",
258
+ "2012-01-01 00:00:12",
259
+ "2012-01-01 00:00:14",
260
+ "2012-01-01 00:00:16",
261
+ "2012-01-01 00:00:18",
262
+ "2012-01-01 00:00:20",
263
+ "2012-01-01 00:00:22",
264
+ "2012-01-01 00:00:24",
265
+ "2012-01-01 00:00:26",
266
+ "2012-01-01 00:00:28",
267
+ "2012-01-01 00:00:30",
268
+ ],
269
+ dtype="datetime64[ns]",
270
+ freq="2s",
271
+ ),
272
+ )
273
+ tm.assert_series_equal(result, expected)
274
+
275
+
276
+ def test_transform_series(_test_series):
277
+ r = _test_series.resample("20min")
278
+ expected = _test_series.groupby(pd.Grouper(freq="20min")).transform("mean")
279
+ result = r.transform("mean")
280
+ tm.assert_series_equal(result, expected)
281
+
282
+
283
+ @pytest.mark.parametrize("on", [None, "date"])
284
+ def test_transform_frame(on):
285
+ # GH#47079
286
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
287
+ index.name = "date"
288
+ df = DataFrame(
289
+ np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index
290
+ )
291
+ expected = df.groupby(pd.Grouper(freq="20min")).transform("mean")
292
+ if on == "date":
293
+ # Move date to being a column; result will then have a RangeIndex
294
+ expected = expected.reset_index(drop=True)
295
+ df = df.reset_index()
296
+
297
+ r = df.resample("20min", on=on)
298
+ result = r.transform("mean")
299
+ tm.assert_frame_equal(result, expected)
300
+
301
+
302
+ def test_fillna():
303
+ # need to upsample here
304
+ rng = date_range("1/1/2012", periods=10, freq="2s")
305
+ ts = Series(np.arange(len(rng), dtype="int64"), index=rng)
306
+ r = ts.resample("s")
307
+
308
+ expected = r.ffill()
309
+ msg = "DatetimeIndexResampler.fillna is deprecated"
310
+ with tm.assert_produces_warning(FutureWarning, match=msg):
311
+ result = r.fillna(method="ffill")
312
+ tm.assert_series_equal(result, expected)
313
+
314
+ expected = r.bfill()
315
+ with tm.assert_produces_warning(FutureWarning, match=msg):
316
+ result = r.fillna(method="bfill")
317
+ tm.assert_series_equal(result, expected)
318
+
319
+ msg2 = (
320
+ r"Invalid fill method\. Expecting pad \(ffill\), backfill "
321
+ r"\(bfill\) or nearest\. Got 0"
322
+ )
323
+ with pytest.raises(ValueError, match=msg2):
324
+ with tm.assert_produces_warning(FutureWarning, match=msg):
325
+ r.fillna(0)
326
+
327
+
328
+ @pytest.mark.parametrize(
329
+ "func",
330
+ [
331
+ lambda x: x.resample("20min", group_keys=False),
332
+ lambda x: x.groupby(pd.Grouper(freq="20min"), group_keys=False),
333
+ ],
334
+ ids=["resample", "groupby"],
335
+ )
336
+ def test_apply_without_aggregation(func, _test_series):
337
+ # both resample and groupby should work w/o aggregation
338
+ t = func(_test_series)
339
+ result = t.apply(lambda x: x)
340
+ tm.assert_series_equal(result, _test_series)
341
+
342
+
343
+ def test_apply_without_aggregation2(_test_series):
344
+ grouped = _test_series.to_frame(name="foo").resample("20min", group_keys=False)
345
+ result = grouped["foo"].apply(lambda x: x)
346
+ tm.assert_series_equal(result, _test_series.rename("foo"))
347
+
348
+
349
+ def test_agg_consistency():
350
+ # make sure that we are consistent across
351
+ # similar aggregations with and w/o selection list
352
+ df = DataFrame(
353
+ np.random.default_rng(2).standard_normal((1000, 3)),
354
+ index=date_range("1/1/2012", freq="s", periods=1000),
355
+ columns=["A", "B", "C"],
356
+ )
357
+
358
+ r = df.resample("3min")
359
+
360
+ msg = r"Column\(s\) \['r1', 'r2'\] do not exist"
361
+ with pytest.raises(KeyError, match=msg):
362
+ r.agg({"r1": "mean", "r2": "sum"})
363
+
364
+
365
+ def test_agg_consistency_int_str_column_mix():
366
+ # GH#39025
367
+ df = DataFrame(
368
+ np.random.default_rng(2).standard_normal((1000, 2)),
369
+ index=date_range("1/1/2012", freq="s", periods=1000),
370
+ columns=[1, "a"],
371
+ )
372
+
373
+ r = df.resample("3min")
374
+
375
+ msg = r"Column\(s\) \[2, 'b'\] do not exist"
376
+ with pytest.raises(KeyError, match=msg):
377
+ r.agg({2: "mean", "b": "sum"})
378
+
379
+
380
+ # TODO(GH#14008): once GH 14008 is fixed, move these tests into
381
+ # `Base` test class
382
+
383
+
384
+ @pytest.fixture
385
+ def index():
386
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
387
+ index.name = "date"
388
+ return index
389
+
390
+
391
+ @pytest.fixture
392
+ def df(index):
393
+ frame = DataFrame(
394
+ np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index
395
+ )
396
+ return frame
397
+
398
+
399
+ @pytest.fixture
400
+ def df_col(df):
401
+ return df.reset_index()
402
+
403
+
404
+ @pytest.fixture
405
+ def df_mult(df_col, index):
406
+ df_mult = df_col.copy()
407
+ df_mult.index = pd.MultiIndex.from_arrays(
408
+ [range(10), index], names=["index", "date"]
409
+ )
410
+ return df_mult
411
+
412
+
413
+ @pytest.fixture
414
+ def a_mean(df):
415
+ return df.resample("2D")["A"].mean()
416
+
417
+
418
+ @pytest.fixture
419
+ def a_std(df):
420
+ return df.resample("2D")["A"].std()
421
+
422
+
423
+ @pytest.fixture
424
+ def a_sum(df):
425
+ return df.resample("2D")["A"].sum()
426
+
427
+
428
+ @pytest.fixture
429
+ def b_mean(df):
430
+ return df.resample("2D")["B"].mean()
431
+
432
+
433
+ @pytest.fixture
434
+ def b_std(df):
435
+ return df.resample("2D")["B"].std()
436
+
437
+
438
+ @pytest.fixture
439
+ def b_sum(df):
440
+ return df.resample("2D")["B"].sum()
441
+
442
+
443
+ @pytest.fixture
444
+ def df_resample(df):
445
+ return df.resample("2D")
446
+
447
+
448
+ @pytest.fixture
449
+ def df_col_resample(df_col):
450
+ return df_col.resample("2D", on="date")
451
+
452
+
453
+ @pytest.fixture
454
+ def df_mult_resample(df_mult):
455
+ return df_mult.resample("2D", level="date")
456
+
457
+
458
+ @pytest.fixture
459
+ def df_grouper_resample(df):
460
+ return df.groupby(pd.Grouper(freq="2D"))
461
+
462
+
463
+ @pytest.fixture(
464
+ params=["df_resample", "df_col_resample", "df_mult_resample", "df_grouper_resample"]
465
+ )
466
+ def cases(request):
467
+ return request.getfixturevalue(request.param)
468
+
469
+
470
+ def test_agg_mixed_column_aggregation(cases, a_mean, a_std, b_mean, b_std, request):
471
+ expected = pd.concat([a_mean, a_std, b_mean, b_std], axis=1)
472
+ expected.columns = pd.MultiIndex.from_product([["A", "B"], ["mean", "std"]])
473
+ msg = "using SeriesGroupBy.[mean|std]"
474
+ # "date" is an index and a column, so get included in the agg
475
+ if "df_mult" in request.node.callspec.id:
476
+ date_mean = cases["date"].mean()
477
+ date_std = cases["date"].std()
478
+ expected = pd.concat([date_mean, date_std, expected], axis=1)
479
+ expected.columns = pd.MultiIndex.from_product(
480
+ [["date", "A", "B"], ["mean", "std"]]
481
+ )
482
+ with tm.assert_produces_warning(FutureWarning, match=msg):
483
+ result = cases.aggregate([np.mean, np.std])
484
+ tm.assert_frame_equal(result, expected)
485
+
486
+
487
+ @pytest.mark.parametrize(
488
+ "agg",
489
+ [
490
+ {"func": {"A": np.mean, "B": np.std}},
491
+ {"A": ("A", np.mean), "B": ("B", np.std)},
492
+ {"A": NamedAgg("A", np.mean), "B": NamedAgg("B", np.std)},
493
+ ],
494
+ )
495
+ def test_agg_both_mean_std_named_result(cases, a_mean, b_std, agg):
496
+ msg = "using SeriesGroupBy.[mean|std]"
497
+ expected = pd.concat([a_mean, b_std], axis=1)
498
+ with tm.assert_produces_warning(FutureWarning, match=msg):
499
+ result = cases.aggregate(**agg)
500
+ tm.assert_frame_equal(result, expected, check_like=True)
501
+
502
+
503
+ def test_agg_both_mean_std_dict_of_list(cases, a_mean, a_std):
504
+ expected = pd.concat([a_mean, a_std], axis=1)
505
+ expected.columns = pd.MultiIndex.from_tuples([("A", "mean"), ("A", "std")])
506
+ result = cases.aggregate({"A": ["mean", "std"]})
507
+ tm.assert_frame_equal(result, expected)
508
+
509
+
510
+ @pytest.mark.parametrize(
511
+ "agg", [{"func": ["mean", "sum"]}, {"mean": "mean", "sum": "sum"}]
512
+ )
513
+ def test_agg_both_mean_sum(cases, a_mean, a_sum, agg):
514
+ expected = pd.concat([a_mean, a_sum], axis=1)
515
+ expected.columns = ["mean", "sum"]
516
+ result = cases["A"].aggregate(**agg)
517
+ tm.assert_frame_equal(result, expected)
518
+
519
+
520
+ @pytest.mark.parametrize(
521
+ "agg",
522
+ [
523
+ {"A": {"mean": "mean", "sum": "sum"}},
524
+ {
525
+ "A": {"mean": "mean", "sum": "sum"},
526
+ "B": {"mean2": "mean", "sum2": "sum"},
527
+ },
528
+ ],
529
+ )
530
+ def test_agg_dict_of_dict_specificationerror(cases, agg):
531
+ msg = "nested renamer is not supported"
532
+ with pytest.raises(pd.errors.SpecificationError, match=msg):
533
+ cases.aggregate(agg)
534
+
535
+
536
+ def test_agg_dict_of_lists(cases, a_mean, a_std, b_mean, b_std):
537
+ expected = pd.concat([a_mean, a_std, b_mean, b_std], axis=1)
538
+ expected.columns = pd.MultiIndex.from_tuples(
539
+ [("A", "mean"), ("A", "std"), ("B", "mean"), ("B", "std")]
540
+ )
541
+ result = cases.aggregate({"A": ["mean", "std"], "B": ["mean", "std"]})
542
+ tm.assert_frame_equal(result, expected, check_like=True)
543
+
544
+
545
+ @pytest.mark.parametrize(
546
+ "agg",
547
+ [
548
+ {"func": {"A": np.sum, "B": lambda x: np.std(x, ddof=1)}},
549
+ {"A": ("A", np.sum), "B": ("B", lambda x: np.std(x, ddof=1))},
550
+ {"A": NamedAgg("A", np.sum), "B": NamedAgg("B", lambda x: np.std(x, ddof=1))},
551
+ ],
552
+ )
553
+ def test_agg_with_lambda(cases, agg):
554
+ # passed lambda
555
+ msg = "using SeriesGroupBy.sum"
556
+ rcustom = cases["B"].apply(lambda x: np.std(x, ddof=1))
557
+ expected = pd.concat([cases["A"].sum(), rcustom], axis=1)
558
+ with tm.assert_produces_warning(FutureWarning, match=msg):
559
+ result = cases.agg(**agg)
560
+ tm.assert_frame_equal(result, expected, check_like=True)
561
+
562
+
563
+ @pytest.mark.parametrize(
564
+ "agg",
565
+ [
566
+ {"func": {"result1": np.sum, "result2": np.mean}},
567
+ {"A": ("result1", np.sum), "B": ("result2", np.mean)},
568
+ {"A": NamedAgg("result1", np.sum), "B": NamedAgg("result2", np.mean)},
569
+ ],
570
+ )
571
+ def test_agg_no_column(cases, agg):
572
+ msg = r"Column\(s\) \['result1', 'result2'\] do not exist"
573
+ with pytest.raises(KeyError, match=msg):
574
+ cases[["A", "B"]].agg(**agg)
575
+
576
+
577
+ @pytest.mark.parametrize(
578
+ "cols, agg",
579
+ [
580
+ [None, {"A": ["sum", "std"], "B": ["mean", "std"]}],
581
+ [
582
+ [
583
+ "A",
584
+ "B",
585
+ ],
586
+ {"A": ["sum", "std"], "B": ["mean", "std"]},
587
+ ],
588
+ ],
589
+ )
590
+ def test_agg_specificationerror_nested(cases, cols, agg, a_sum, a_std, b_mean, b_std):
591
+ # agg with different hows
592
+ # equivalent of using a selection list / or not
593
+ expected = pd.concat([a_sum, a_std, b_mean, b_std], axis=1)
594
+ expected.columns = pd.MultiIndex.from_tuples(
595
+ [("A", "sum"), ("A", "std"), ("B", "mean"), ("B", "std")]
596
+ )
597
+ if cols is not None:
598
+ obj = cases[cols]
599
+ else:
600
+ obj = cases
601
+
602
+ result = obj.agg(agg)
603
+ tm.assert_frame_equal(result, expected, check_like=True)
604
+
605
+
606
+ @pytest.mark.parametrize(
607
+ "agg", [{"A": ["sum", "std"]}, {"A": ["sum", "std"], "B": ["mean", "std"]}]
608
+ )
609
+ def test_agg_specificationerror_series(cases, agg):
610
+ msg = "nested renamer is not supported"
611
+
612
+ # series like aggs
613
+ with pytest.raises(pd.errors.SpecificationError, match=msg):
614
+ cases["A"].agg(agg)
615
+
616
+
617
+ def test_agg_specificationerror_invalid_names(cases):
618
+ # errors
619
+ # invalid names in the agg specification
620
+ msg = r"Column\(s\) \['B'\] do not exist"
621
+ with pytest.raises(KeyError, match=msg):
622
+ cases[["A"]].agg({"A": ["sum", "std"], "B": ["mean", "std"]})
623
+
624
+
625
+ @pytest.mark.parametrize(
626
+ "func", [["min"], ["mean", "max"], {"A": "sum"}, {"A": "prod", "B": "median"}]
627
+ )
628
+ def test_multi_agg_axis_1_raises(func):
629
+ # GH#46904
630
+
631
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
632
+ index.name = "date"
633
+ df = DataFrame(
634
+ np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index
635
+ ).T
636
+ warning_msg = "DataFrame.resample with axis=1 is deprecated."
637
+ with tm.assert_produces_warning(FutureWarning, match=warning_msg):
638
+ res = df.resample("ME", axis=1)
639
+ with pytest.raises(
640
+ NotImplementedError, match="axis other than 0 is not supported"
641
+ ):
642
+ res.agg(func)
643
+
644
+
645
+ def test_agg_nested_dicts():
646
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
647
+ index.name = "date"
648
+ df = DataFrame(
649
+ np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index
650
+ )
651
+ df_col = df.reset_index()
652
+ df_mult = df_col.copy()
653
+ df_mult.index = pd.MultiIndex.from_arrays(
654
+ [range(10), df.index], names=["index", "date"]
655
+ )
656
+ r = df.resample("2D")
657
+ cases = [
658
+ r,
659
+ df_col.resample("2D", on="date"),
660
+ df_mult.resample("2D", level="date"),
661
+ df.groupby(pd.Grouper(freq="2D")),
662
+ ]
663
+
664
+ msg = "nested renamer is not supported"
665
+ for t in cases:
666
+ with pytest.raises(pd.errors.SpecificationError, match=msg):
667
+ t.aggregate({"r1": {"A": ["mean", "sum"]}, "r2": {"B": ["mean", "sum"]}})
668
+
669
+ for t in cases:
670
+ with pytest.raises(pd.errors.SpecificationError, match=msg):
671
+ t[["A", "B"]].agg(
672
+ {"A": {"ra": ["mean", "std"]}, "B": {"rb": ["mean", "std"]}}
673
+ )
674
+
675
+ with pytest.raises(pd.errors.SpecificationError, match=msg):
676
+ t.agg({"A": {"ra": ["mean", "std"]}, "B": {"rb": ["mean", "std"]}})
677
+
678
+
679
+ def test_try_aggregate_non_existing_column():
680
+ # GH 16766
681
+ data = [
682
+ {"dt": datetime(2017, 6, 1, 0), "x": 1.0, "y": 2.0},
683
+ {"dt": datetime(2017, 6, 1, 1), "x": 2.0, "y": 2.0},
684
+ {"dt": datetime(2017, 6, 1, 2), "x": 3.0, "y": 1.5},
685
+ ]
686
+ df = DataFrame(data).set_index("dt")
687
+
688
+ # Error as we don't have 'z' column
689
+ msg = r"Column\(s\) \['z'\] do not exist"
690
+ with pytest.raises(KeyError, match=msg):
691
+ df.resample("30min").agg({"x": ["mean"], "y": ["median"], "z": ["sum"]})
692
+
693
+
694
+ def test_agg_list_like_func_with_args():
695
+ # 50624
696
+ df = DataFrame(
697
+ {"x": [1, 2, 3]}, index=date_range("2020-01-01", periods=3, freq="D")
698
+ )
699
+
700
+ def foo1(x, a=1, c=0):
701
+ return x + a + c
702
+
703
+ def foo2(x, b=2, c=0):
704
+ return x + b + c
705
+
706
+ msg = r"foo1\(\) got an unexpected keyword argument 'b'"
707
+ with pytest.raises(TypeError, match=msg):
708
+ df.resample("D").agg([foo1, foo2], 3, b=3, c=4)
709
+
710
+ result = df.resample("D").agg([foo1, foo2], 3, c=4)
711
+ expected = DataFrame(
712
+ [[8, 8], [9, 9], [10, 10]],
713
+ index=date_range("2020-01-01", periods=3, freq="D"),
714
+ columns=pd.MultiIndex.from_tuples([("x", "foo1"), ("x", "foo2")]),
715
+ )
716
+ tm.assert_frame_equal(result, expected)
717
+
718
+
719
+ def test_selection_api_validation():
720
+ # GH 13500
721
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
722
+
723
+ rng = np.arange(len(index), dtype=np.int64)
724
+ df = DataFrame(
725
+ {"date": index, "a": rng},
726
+ index=pd.MultiIndex.from_arrays([rng, index], names=["v", "d"]),
727
+ )
728
+ df_exp = DataFrame({"a": rng}, index=index)
729
+
730
+ # non DatetimeIndex
731
+ msg = (
732
+ "Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, "
733
+ "but got an instance of 'Index'"
734
+ )
735
+ with pytest.raises(TypeError, match=msg):
736
+ df.resample("2D", level="v")
737
+
738
+ msg = "The Grouper cannot specify both a key and a level!"
739
+ with pytest.raises(ValueError, match=msg):
740
+ df.resample("2D", on="date", level="d")
741
+
742
+ msg = "unhashable type: 'list'"
743
+ with pytest.raises(TypeError, match=msg):
744
+ df.resample("2D", on=["a", "date"])
745
+
746
+ msg = r"\"Level \['a', 'date'\] not found\""
747
+ with pytest.raises(KeyError, match=msg):
748
+ df.resample("2D", level=["a", "date"])
749
+
750
+ # upsampling not allowed
751
+ msg = (
752
+ "Upsampling from level= or on= selection is not supported, use "
753
+ r"\.set_index\(\.\.\.\) to explicitly set index to datetime-like"
754
+ )
755
+ with pytest.raises(ValueError, match=msg):
756
+ df.resample("2D", level="d").asfreq()
757
+ with pytest.raises(ValueError, match=msg):
758
+ df.resample("2D", on="date").asfreq()
759
+
760
+ exp = df_exp.resample("2D").sum()
761
+ exp.index.name = "date"
762
+ result = df.resample("2D", on="date").sum()
763
+ tm.assert_frame_equal(exp, result)
764
+
765
+ exp.index.name = "d"
766
+ with pytest.raises(TypeError, match="datetime64 type does not support sum"):
767
+ df.resample("2D", level="d").sum()
768
+ result = df.resample("2D", level="d").sum(numeric_only=True)
769
+ tm.assert_frame_equal(exp, result)
770
+
771
+
772
+ @pytest.mark.parametrize(
773
+ "col_name", ["t2", "t2x", "t2q", "T_2M", "t2p", "t2m", "t2m1", "T2M"]
774
+ )
775
+ def test_agg_with_datetime_index_list_agg_func(col_name):
776
+ # GH 22660
777
+ # The parametrized column names would get converted to dates by our
778
+ # date parser. Some would result in OutOfBoundsError (ValueError) while
779
+ # others would result in OverflowError when passed into Timestamp.
780
+ # We catch these errors and move on to the correct branch.
781
+ df = DataFrame(
782
+ list(range(200)),
783
+ index=date_range(
784
+ start="2017-01-01", freq="15min", periods=200, tz="Europe/Berlin"
785
+ ),
786
+ columns=[col_name],
787
+ )
788
+ result = df.resample("1d").aggregate(["mean"])
789
+ expected = DataFrame(
790
+ [47.5, 143.5, 195.5],
791
+ index=date_range(start="2017-01-01", freq="D", periods=3, tz="Europe/Berlin"),
792
+ columns=pd.MultiIndex(levels=[[col_name], ["mean"]], codes=[[0], [0]]),
793
+ )
794
+ tm.assert_frame_equal(result, expected)
795
+
796
+
797
+ def test_resample_agg_readonly():
798
+ # GH#31710 cython needs to allow readonly data
799
+ index = date_range("2020-01-01", "2020-01-02", freq="1h")
800
+ arr = np.zeros_like(index)
801
+ arr.setflags(write=False)
802
+
803
+ ser = Series(arr, index=index)
804
+ rs = ser.resample("1D")
805
+
806
+ expected = Series([pd.Timestamp(0), pd.Timestamp(0)], index=index[::24])
807
+
808
+ result = rs.agg("last")
809
+ tm.assert_series_equal(result, expected)
810
+
811
+ result = rs.agg("first")
812
+ tm.assert_series_equal(result, expected)
813
+
814
+ result = rs.agg("max")
815
+ tm.assert_series_equal(result, expected)
816
+
817
+ result = rs.agg("min")
818
+ tm.assert_series_equal(result, expected)
819
+
820
+
821
+ @pytest.mark.parametrize(
822
+ "start,end,freq,data,resample_freq,origin,closed,exp_data,exp_end,exp_periods",
823
+ [
824
+ (
825
+ "2000-10-01 23:30:00",
826
+ "2000-10-02 00:26:00",
827
+ "7min",
828
+ [0, 3, 6, 9, 12, 15, 18, 21, 24],
829
+ "17min",
830
+ "end",
831
+ None,
832
+ [0, 18, 27, 63],
833
+ "20001002 00:26:00",
834
+ 4,
835
+ ),
836
+ (
837
+ "20200101 8:26:35",
838
+ "20200101 9:31:58",
839
+ "77s",
840
+ [1] * 51,
841
+ "7min",
842
+ "end",
843
+ "right",
844
+ [1, 6, 5, 6, 5, 6, 5, 6, 5, 6],
845
+ "2020-01-01 09:30:45",
846
+ 10,
847
+ ),
848
+ (
849
+ "2000-10-01 23:30:00",
850
+ "2000-10-02 00:26:00",
851
+ "7min",
852
+ [0, 3, 6, 9, 12, 15, 18, 21, 24],
853
+ "17min",
854
+ "end",
855
+ "left",
856
+ [0, 18, 27, 39, 24],
857
+ "20001002 00:43:00",
858
+ 5,
859
+ ),
860
+ (
861
+ "2000-10-01 23:30:00",
862
+ "2000-10-02 00:26:00",
863
+ "7min",
864
+ [0, 3, 6, 9, 12, 15, 18, 21, 24],
865
+ "17min",
866
+ "end_day",
867
+ None,
868
+ [3, 15, 45, 45],
869
+ "2000-10-02 00:29:00",
870
+ 4,
871
+ ),
872
+ ],
873
+ )
874
+ def test_end_and_end_day_origin(
875
+ start,
876
+ end,
877
+ freq,
878
+ data,
879
+ resample_freq,
880
+ origin,
881
+ closed,
882
+ exp_data,
883
+ exp_end,
884
+ exp_periods,
885
+ ):
886
+ rng = date_range(start, end, freq=freq)
887
+ ts = Series(data, index=rng)
888
+
889
+ res = ts.resample(resample_freq, origin=origin, closed=closed).sum()
890
+ expected = Series(
891
+ exp_data,
892
+ index=date_range(end=exp_end, freq=resample_freq, periods=exp_periods),
893
+ )
894
+
895
+ tm.assert_series_equal(res, expected)
896
+
897
+
898
+ @pytest.mark.parametrize(
899
+ # expected_data is a string when op raises a ValueError
900
+ "method, numeric_only, expected_data",
901
+ [
902
+ ("sum", True, {"num": [25]}),
903
+ ("sum", False, {"cat": ["cat_1cat_2"], "num": [25]}),
904
+ ("sum", lib.no_default, {"cat": ["cat_1cat_2"], "num": [25]}),
905
+ ("prod", True, {"num": [100]}),
906
+ ("prod", False, "can't multiply sequence"),
907
+ ("prod", lib.no_default, "can't multiply sequence"),
908
+ ("min", True, {"num": [5]}),
909
+ ("min", False, {"cat": ["cat_1"], "num": [5]}),
910
+ ("min", lib.no_default, {"cat": ["cat_1"], "num": [5]}),
911
+ ("max", True, {"num": [20]}),
912
+ ("max", False, {"cat": ["cat_2"], "num": [20]}),
913
+ ("max", lib.no_default, {"cat": ["cat_2"], "num": [20]}),
914
+ ("first", True, {"num": [5]}),
915
+ ("first", False, {"cat": ["cat_1"], "num": [5]}),
916
+ ("first", lib.no_default, {"cat": ["cat_1"], "num": [5]}),
917
+ ("last", True, {"num": [20]}),
918
+ ("last", False, {"cat": ["cat_2"], "num": [20]}),
919
+ ("last", lib.no_default, {"cat": ["cat_2"], "num": [20]}),
920
+ ("mean", True, {"num": [12.5]}),
921
+ ("mean", False, "Could not convert"),
922
+ ("mean", lib.no_default, "Could not convert"),
923
+ ("median", True, {"num": [12.5]}),
924
+ ("median", False, r"Cannot convert \['cat_1' 'cat_2'\] to numeric"),
925
+ ("median", lib.no_default, r"Cannot convert \['cat_1' 'cat_2'\] to numeric"),
926
+ ("std", True, {"num": [10.606601717798213]}),
927
+ ("std", False, "could not convert string to float"),
928
+ ("std", lib.no_default, "could not convert string to float"),
929
+ ("var", True, {"num": [112.5]}),
930
+ ("var", False, "could not convert string to float"),
931
+ ("var", lib.no_default, "could not convert string to float"),
932
+ ("sem", True, {"num": [7.5]}),
933
+ ("sem", False, "could not convert string to float"),
934
+ ("sem", lib.no_default, "could not convert string to float"),
935
+ ],
936
+ )
937
+ def test_frame_downsample_method(
938
+ method, numeric_only, expected_data, using_infer_string
939
+ ):
940
+ # GH#46442 test if `numeric_only` behave as expected for DataFrameGroupBy
941
+
942
+ index = date_range("2018-01-01", periods=2, freq="D")
943
+ expected_index = date_range("2018-12-31", periods=1, freq="YE")
944
+ df = DataFrame({"cat": ["cat_1", "cat_2"], "num": [5, 20]}, index=index)
945
+ resampled = df.resample("YE")
946
+ if numeric_only is lib.no_default:
947
+ kwargs = {}
948
+ else:
949
+ kwargs = {"numeric_only": numeric_only}
950
+
951
+ func = getattr(resampled, method)
952
+ if isinstance(expected_data, str):
953
+ if method in ("var", "mean", "median", "prod"):
954
+ klass = TypeError
955
+ msg = re.escape(f"agg function failed [how->{method},dtype->")
956
+ if using_infer_string:
957
+ msg = f"dtype 'str' does not support operation '{method}'"
958
+ elif method in ["sum", "std", "sem"] and using_infer_string:
959
+ klass = TypeError
960
+ msg = f"dtype 'str' does not support operation '{method}'"
961
+ else:
962
+ klass = ValueError
963
+ msg = expected_data
964
+ with pytest.raises(klass, match=msg):
965
+ _ = func(**kwargs)
966
+ else:
967
+ result = func(**kwargs)
968
+ expected = DataFrame(expected_data, index=expected_index)
969
+ tm.assert_frame_equal(result, expected)
970
+
971
+
972
+ @pytest.mark.parametrize(
973
+ "method, numeric_only, expected_data",
974
+ [
975
+ ("sum", True, ()),
976
+ ("sum", False, ["cat_1cat_2"]),
977
+ ("sum", lib.no_default, ["cat_1cat_2"]),
978
+ ("prod", True, ()),
979
+ ("prod", False, ()),
980
+ ("prod", lib.no_default, ()),
981
+ ("min", True, ()),
982
+ ("min", False, ["cat_1"]),
983
+ ("min", lib.no_default, ["cat_1"]),
984
+ ("max", True, ()),
985
+ ("max", False, ["cat_2"]),
986
+ ("max", lib.no_default, ["cat_2"]),
987
+ ("first", True, ()),
988
+ ("first", False, ["cat_1"]),
989
+ ("first", lib.no_default, ["cat_1"]),
990
+ ("last", True, ()),
991
+ ("last", False, ["cat_2"]),
992
+ ("last", lib.no_default, ["cat_2"]),
993
+ ],
994
+ )
995
+ def test_series_downsample_method(
996
+ method, numeric_only, expected_data, using_infer_string
997
+ ):
998
+ # GH#46442 test if `numeric_only` behave as expected for SeriesGroupBy
999
+
1000
+ index = date_range("2018-01-01", periods=2, freq="D")
1001
+ expected_index = date_range("2018-12-31", periods=1, freq="YE")
1002
+ df = Series(["cat_1", "cat_2"], index=index)
1003
+ resampled = df.resample("YE")
1004
+ kwargs = {} if numeric_only is lib.no_default else {"numeric_only": numeric_only}
1005
+
1006
+ func = getattr(resampled, method)
1007
+ if numeric_only and numeric_only is not lib.no_default:
1008
+ msg = rf"Cannot use numeric_only=True with SeriesGroupBy\.{method}"
1009
+ with pytest.raises(TypeError, match=msg):
1010
+ func(**kwargs)
1011
+ elif method == "prod":
1012
+ msg = re.escape("agg function failed [how->prod,dtype->")
1013
+ if using_infer_string:
1014
+ msg = "dtype 'str' does not support operation 'prod'"
1015
+ with pytest.raises(TypeError, match=msg):
1016
+ func(**kwargs)
1017
+
1018
+ else:
1019
+ result = func(**kwargs)
1020
+ expected = Series(expected_data, index=expected_index)
1021
+ tm.assert_series_equal(result, expected)
1022
+
1023
+
1024
+ @pytest.mark.parametrize(
1025
+ "method, raises",
1026
+ [
1027
+ ("sum", True),
1028
+ ("prod", True),
1029
+ ("min", True),
1030
+ ("max", True),
1031
+ ("first", False),
1032
+ ("last", False),
1033
+ ("median", False),
1034
+ ("mean", True),
1035
+ ("std", True),
1036
+ ("var", True),
1037
+ ("sem", False),
1038
+ ("ohlc", False),
1039
+ ("nunique", False),
1040
+ ],
1041
+ )
1042
+ def test_args_kwargs_depr(method, raises):
1043
+ index = date_range("20180101", periods=3, freq="h")
1044
+ df = Series([2, 4, 6], index=index)
1045
+ resampled = df.resample("30min")
1046
+ args = ()
1047
+
1048
+ func = getattr(resampled, method)
1049
+
1050
+ error_msg = "numpy operations are not valid with resample."
1051
+ error_msg_type = "too many arguments passed in"
1052
+ warn_msg = f"Passing additional args to DatetimeIndexResampler.{method}"
1053
+
1054
+ if raises:
1055
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
1056
+ with pytest.raises(UnsupportedFunctionCall, match=error_msg):
1057
+ func(*args, 1, 2, 3, 4)
1058
+ else:
1059
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
1060
+ with pytest.raises(TypeError, match=error_msg_type):
1061
+ func(*args, 1, 2, 3, 4)
1062
+
1063
+
1064
+ def test_df_axis_param_depr():
1065
+ index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D")
1066
+ index.name = "date"
1067
+ df = DataFrame(
1068
+ np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index
1069
+ ).T
1070
+
1071
+ # Deprecation error when axis=1 is explicitly passed
1072
+ warning_msg = "DataFrame.resample with axis=1 is deprecated."
1073
+ with tm.assert_produces_warning(FutureWarning, match=warning_msg):
1074
+ df.resample("ME", axis=1)
1075
+
1076
+ # Deprecation error when axis=0 is explicitly passed
1077
+ df = df.T
1078
+ warning_msg = (
1079
+ "The 'axis' keyword in DataFrame.resample is deprecated and "
1080
+ "will be removed in a future version."
1081
+ )
1082
+ with tm.assert_produces_warning(FutureWarning, match=warning_msg):
1083
+ df.resample("ME", axis=0)
1084
+
1085
+
1086
+ def test_series_axis_param_depr(_test_series):
1087
+ warning_msg = (
1088
+ "The 'axis' keyword in Series.resample is "
1089
+ "deprecated and will be removed in a future version."
1090
+ )
1091
+ with tm.assert_produces_warning(FutureWarning, match=warning_msg):
1092
+ _test_series.resample("h", axis=0)
1093
+
1094
+
1095
+ def test_resample_empty():
1096
+ # GH#52484
1097
+ df = DataFrame(
1098
+ index=pd.to_datetime(
1099
+ ["2018-01-01 00:00:00", "2018-01-01 12:00:00", "2018-01-02 00:00:00"]
1100
+ )
1101
+ )
1102
+ expected = DataFrame(
1103
+ index=pd.to_datetime(
1104
+ [
1105
+ "2018-01-01 00:00:00",
1106
+ "2018-01-01 08:00:00",
1107
+ "2018-01-01 16:00:00",
1108
+ "2018-01-02 00:00:00",
1109
+ ]
1110
+ )
1111
+ )
1112
+ result = df.resample("8h").mean()
1113
+ tm.assert_frame_equal(result, expected)
shared/package-files/75/750d3bcc9d7ebe5a45a96041bbf734707c53d325dc192bbba3b2f10c2132077b/blob ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helper functions for writing to terminals and files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import sys
8
+ from typing import final
9
+ from typing import Literal
10
+ from typing import Sequence
11
+ from typing import TextIO
12
+ from typing import TYPE_CHECKING
13
+
14
+ from ..compat import assert_never
15
+ from .wcwidth import wcswidth
16
+
17
+
18
+ if TYPE_CHECKING:
19
+ from pygments.formatter import Formatter
20
+ from pygments.lexer import Lexer
21
+
22
+
23
+ # This code was initially copied from py 1.8.1, file _io/terminalwriter.py.
24
+
25
+
26
+ def get_terminal_width() -> int:
27
+ width, _ = shutil.get_terminal_size(fallback=(80, 24))
28
+
29
+ # The Windows get_terminal_size may be bogus, let's sanify a bit.
30
+ if width < 40:
31
+ width = 80
32
+
33
+ return width
34
+
35
+
36
+ def should_do_markup(file: TextIO) -> bool:
37
+ if os.environ.get("PY_COLORS") == "1":
38
+ return True
39
+ if os.environ.get("PY_COLORS") == "0":
40
+ return False
41
+ if os.environ.get("NO_COLOR"):
42
+ return False
43
+ if os.environ.get("FORCE_COLOR"):
44
+ return True
45
+ return (
46
+ hasattr(file, "isatty") and file.isatty() and os.environ.get("TERM") != "dumb"
47
+ )
48
+
49
+
50
+ @final
51
+ class TerminalWriter:
52
+ _esctable = dict(
53
+ black=30,
54
+ red=31,
55
+ green=32,
56
+ yellow=33,
57
+ blue=34,
58
+ purple=35,
59
+ cyan=36,
60
+ white=37,
61
+ Black=40,
62
+ Red=41,
63
+ Green=42,
64
+ Yellow=43,
65
+ Blue=44,
66
+ Purple=45,
67
+ Cyan=46,
68
+ White=47,
69
+ bold=1,
70
+ light=2,
71
+ blink=5,
72
+ invert=7,
73
+ )
74
+
75
+ def __init__(self, file: TextIO | None = None) -> None:
76
+ if file is None:
77
+ file = sys.stdout
78
+ if hasattr(file, "isatty") and file.isatty() and sys.platform == "win32":
79
+ try:
80
+ import colorama
81
+ except ImportError:
82
+ pass
83
+ else:
84
+ file = colorama.AnsiToWin32(file).stream
85
+ assert file is not None
86
+ self._file = file
87
+ self.hasmarkup = should_do_markup(file)
88
+ self._current_line = ""
89
+ self._terminal_width: int | None = None
90
+ self.code_highlight = True
91
+
92
+ @property
93
+ def fullwidth(self) -> int:
94
+ if self._terminal_width is not None:
95
+ return self._terminal_width
96
+ return get_terminal_width()
97
+
98
+ @fullwidth.setter
99
+ def fullwidth(self, value: int) -> None:
100
+ self._terminal_width = value
101
+
102
+ @property
103
+ def width_of_current_line(self) -> int:
104
+ """Return an estimate of the width so far in the current line."""
105
+ return wcswidth(self._current_line)
106
+
107
+ def markup(self, text: str, **markup: bool) -> str:
108
+ for name in markup:
109
+ if name not in self._esctable:
110
+ raise ValueError(f"unknown markup: {name!r}")
111
+ if self.hasmarkup:
112
+ esc = [self._esctable[name] for name, on in markup.items() if on]
113
+ if esc:
114
+ text = "".join(f"\x1b[{cod}m" for cod in esc) + text + "\x1b[0m"
115
+ return text
116
+
117
+ def sep(
118
+ self,
119
+ sepchar: str,
120
+ title: str | None = None,
121
+ fullwidth: int | None = None,
122
+ **markup: bool,
123
+ ) -> None:
124
+ if fullwidth is None:
125
+ fullwidth = self.fullwidth
126
+ # The goal is to have the line be as long as possible
127
+ # under the condition that len(line) <= fullwidth.
128
+ if sys.platform == "win32":
129
+ # If we print in the last column on windows we are on a
130
+ # new line but there is no way to verify/neutralize this
131
+ # (we may not know the exact line width).
132
+ # So let's be defensive to avoid empty lines in the output.
133
+ fullwidth -= 1
134
+ if title is not None:
135
+ # we want 2 + 2*len(fill) + len(title) <= fullwidth
136
+ # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth
137
+ # 2*len(sepchar)*N <= fullwidth - len(title) - 2
138
+ # N <= (fullwidth - len(title) - 2) // (2*len(sepchar))
139
+ N = max((fullwidth - len(title) - 2) // (2 * len(sepchar)), 1)
140
+ fill = sepchar * N
141
+ line = f"{fill} {title} {fill}"
142
+ else:
143
+ # we want len(sepchar)*N <= fullwidth
144
+ # i.e. N <= fullwidth // len(sepchar)
145
+ line = sepchar * (fullwidth // len(sepchar))
146
+ # In some situations there is room for an extra sepchar at the right,
147
+ # in particular if we consider that with a sepchar like "_ " the
148
+ # trailing space is not important at the end of the line.
149
+ if len(line) + len(sepchar.rstrip()) <= fullwidth:
150
+ line += sepchar.rstrip()
151
+
152
+ self.line(line, **markup)
153
+
154
+ def write(self, msg: str, *, flush: bool = False, **markup: bool) -> None:
155
+ if msg:
156
+ current_line = msg.rsplit("\n", 1)[-1]
157
+ if "\n" in msg:
158
+ self._current_line = current_line
159
+ else:
160
+ self._current_line += current_line
161
+
162
+ msg = self.markup(msg, **markup)
163
+
164
+ try:
165
+ self._file.write(msg)
166
+ except UnicodeEncodeError:
167
+ # Some environments don't support printing general Unicode
168
+ # strings, due to misconfiguration or otherwise; in that case,
169
+ # print the string escaped to ASCII.
170
+ # When the Unicode situation improves we should consider
171
+ # letting the error propagate instead of masking it (see #7475
172
+ # for one brief attempt).
173
+ msg = msg.encode("unicode-escape").decode("ascii")
174
+ self._file.write(msg)
175
+
176
+ if flush:
177
+ self.flush()
178
+
179
+ def line(self, s: str = "", **markup: bool) -> None:
180
+ self.write(s, **markup)
181
+ self.write("\n")
182
+
183
+ def flush(self) -> None:
184
+ self._file.flush()
185
+
186
+ def _write_source(self, lines: Sequence[str], indents: Sequence[str] = ()) -> None:
187
+ """Write lines of source code possibly highlighted.
188
+
189
+ Keeping this private for now because the API is clunky. We should discuss how
190
+ to evolve the terminal writer so we can have more precise color support, for example
191
+ being able to write part of a line in one color and the rest in another, and so on.
192
+ """
193
+ if indents and len(indents) != len(lines):
194
+ raise ValueError(
195
+ f"indents size ({len(indents)}) should have same size as lines ({len(lines)})"
196
+ )
197
+ if not indents:
198
+ indents = [""] * len(lines)
199
+ source = "\n".join(lines)
200
+ new_lines = self._highlight(source).splitlines()
201
+ for indent, new_line in zip(indents, new_lines):
202
+ self.line(indent + new_line)
203
+
204
+ def _get_pygments_lexer(self, lexer: Literal["python", "diff"]) -> Lexer | None:
205
+ try:
206
+ if lexer == "python":
207
+ from pygments.lexers.python import PythonLexer
208
+
209
+ return PythonLexer()
210
+ elif lexer == "diff":
211
+ from pygments.lexers.diff import DiffLexer
212
+
213
+ return DiffLexer()
214
+ else:
215
+ assert_never(lexer)
216
+ except ModuleNotFoundError:
217
+ return None
218
+
219
+ def _get_pygments_formatter(self) -> Formatter | None:
220
+ try:
221
+ import pygments.util
222
+ except ModuleNotFoundError:
223
+ return None
224
+
225
+ from _pytest.config.exceptions import UsageError
226
+
227
+ theme = os.getenv("PYTEST_THEME")
228
+ theme_mode = os.getenv("PYTEST_THEME_MODE", "dark")
229
+
230
+ try:
231
+ from pygments.formatters.terminal import TerminalFormatter
232
+
233
+ return TerminalFormatter(bg=theme_mode, style=theme)
234
+
235
+ except pygments.util.ClassNotFound as e:
236
+ raise UsageError(
237
+ f"PYTEST_THEME environment variable has an invalid value: '{theme}'. "
238
+ "Hint: See available pygments styles with `pygmentize -L styles`."
239
+ ) from e
240
+ except pygments.util.OptionError as e:
241
+ raise UsageError(
242
+ f"PYTEST_THEME_MODE environment variable has an invalid value: '{theme_mode}'. "
243
+ "The allowed values are 'dark' (default) and 'light'."
244
+ ) from e
245
+
246
+ def _highlight(
247
+ self, source: str, lexer: Literal["diff", "python"] = "python"
248
+ ) -> str:
249
+ """Highlight the given source if we have markup support."""
250
+ if not source or not self.hasmarkup or not self.code_highlight:
251
+ return source
252
+
253
+ pygments_lexer = self._get_pygments_lexer(lexer)
254
+ if pygments_lexer is None:
255
+ return source
256
+
257
+ pygments_formatter = self._get_pygments_formatter()
258
+ if pygments_formatter is None:
259
+ return source
260
+
261
+ from pygments import highlight
262
+
263
+ highlighted: str = highlight(source, pygments_lexer, pygments_formatter)
264
+ # pygments terminal formatter may add a newline when there wasn't one.
265
+ # We don't want this, remove.
266
+ if highlighted[-1] == "\n" and source[-1] != "\n":
267
+ highlighted = highlighted[:-1]
268
+
269
+ # Some lexers will not set the initial color explicitly
270
+ # which may lead to the previous color being propagated to the
271
+ # start of the expression, so reset first.
272
+ highlighted = "\x1b[0m" + highlighted
273
+
274
+ return highlighted
shared/package-files/75/750dae72b20664681807a852e202c8cc5283118a5f00135b3f9e254bb1fa0084/blob ADDED
@@ -0,0 +1,747 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ C code printer
3
+
4
+ The C89CodePrinter & C99CodePrinter converts single SymPy expressions into
5
+ single C expressions, using the functions defined in math.h where possible.
6
+
7
+ A complete code generator, which uses ccode extensively, can be found in
8
+ sympy.utilities.codegen. The codegen module can be used to generate complete
9
+ source code files that are compilable without further modifications.
10
+
11
+
12
+ """
13
+
14
+ from __future__ import annotations
15
+ from typing import Any
16
+
17
+ from functools import wraps
18
+ from itertools import chain
19
+
20
+ from sympy.core import S
21
+ from sympy.core.numbers import equal_valued
22
+ from sympy.codegen.ast import (
23
+ Assignment, Pointer, Variable, Declaration, Type,
24
+ real, complex_, integer, bool_, float32, float64, float80,
25
+ complex64, complex128, intc, value_const, pointer_const,
26
+ int8, int16, int32, int64, uint8, uint16, uint32, uint64, untyped,
27
+ none
28
+ )
29
+ from sympy.printing.codeprinter import CodePrinter, requires
30
+ from sympy.printing.precedence import precedence, PRECEDENCE
31
+ from sympy.sets.fancysets import Range
32
+
33
+ # These are defined in the other file so we can avoid importing sympy.codegen
34
+ # from the top-level 'import sympy'. Export them here as well.
35
+ from sympy.printing.codeprinter import ccode, print_ccode # noqa:F401
36
+
37
+ # dictionary mapping SymPy function to (argument_conditions, C_function).
38
+ # Used in C89CodePrinter._print_Function(self)
39
+ known_functions_C89 = {
40
+ "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")],
41
+ "sin": "sin",
42
+ "cos": "cos",
43
+ "tan": "tan",
44
+ "asin": "asin",
45
+ "acos": "acos",
46
+ "atan": "atan",
47
+ "atan2": "atan2",
48
+ "exp": "exp",
49
+ "log": "log",
50
+ "sinh": "sinh",
51
+ "cosh": "cosh",
52
+ "tanh": "tanh",
53
+ "floor": "floor",
54
+ "ceiling": "ceil",
55
+ "sqrt": "sqrt", # To enable automatic rewrites
56
+ }
57
+
58
+ known_functions_C99 = dict(known_functions_C89, **{
59
+ 'exp2': 'exp2',
60
+ 'expm1': 'expm1',
61
+ 'log10': 'log10',
62
+ 'log2': 'log2',
63
+ 'log1p': 'log1p',
64
+ 'Cbrt': 'cbrt',
65
+ 'hypot': 'hypot',
66
+ 'fma': 'fma',
67
+ 'loggamma': 'lgamma',
68
+ 'erfc': 'erfc',
69
+ 'Max': 'fmax',
70
+ 'Min': 'fmin',
71
+ "asinh": "asinh",
72
+ "acosh": "acosh",
73
+ "atanh": "atanh",
74
+ "erf": "erf",
75
+ "gamma": "tgamma",
76
+ })
77
+
78
+ # These are the core reserved words in the C language. Taken from:
79
+ # https://en.cppreference.com/w/c/keyword
80
+
81
+ reserved_words = [
82
+ 'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
83
+ 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'int',
84
+ 'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static',
85
+ 'struct', 'entry', # never standardized, we'll leave it here anyway
86
+ 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'
87
+ ]
88
+
89
+ reserved_words_c99 = ['inline', 'restrict']
90
+
91
+ def get_math_macros():
92
+ """ Returns a dictionary with math-related macros from math.h/cmath
93
+
94
+ Note that these macros are not strictly required by the C/C++-standard.
95
+ For MSVC they are enabled by defining "_USE_MATH_DEFINES" (preferably
96
+ via a compilation flag).
97
+
98
+ Returns
99
+ =======
100
+
101
+ Dictionary mapping SymPy expressions to strings (macro names)
102
+
103
+ """
104
+ from sympy.codegen.cfunctions import log2, Sqrt
105
+ from sympy.functions.elementary.exponential import log
106
+ from sympy.functions.elementary.miscellaneous import sqrt
107
+
108
+ return {
109
+ S.Exp1: 'M_E',
110
+ log2(S.Exp1): 'M_LOG2E',
111
+ 1/log(2): 'M_LOG2E',
112
+ log(2): 'M_LN2',
113
+ log(10): 'M_LN10',
114
+ S.Pi: 'M_PI',
115
+ S.Pi/2: 'M_PI_2',
116
+ S.Pi/4: 'M_PI_4',
117
+ 1/S.Pi: 'M_1_PI',
118
+ 2/S.Pi: 'M_2_PI',
119
+ 2/sqrt(S.Pi): 'M_2_SQRTPI',
120
+ 2/Sqrt(S.Pi): 'M_2_SQRTPI',
121
+ sqrt(2): 'M_SQRT2',
122
+ Sqrt(2): 'M_SQRT2',
123
+ 1/sqrt(2): 'M_SQRT1_2',
124
+ 1/Sqrt(2): 'M_SQRT1_2'
125
+ }
126
+
127
+
128
+ def _as_macro_if_defined(meth):
129
+ """ Decorator for printer methods
130
+
131
+ When a Printer's method is decorated using this decorator the expressions printed
132
+ will first be looked for in the attribute ``math_macros``, and if present it will
133
+ print the macro name in ``math_macros`` followed by a type suffix for the type
134
+ ``real``. e.g. printing ``sympy.pi`` would print ``M_PIl`` if real is mapped to float80.
135
+
136
+ """
137
+ @wraps(meth)
138
+ def _meth_wrapper(self, expr, **kwargs):
139
+ if expr in self.math_macros:
140
+ return '%s%s' % (self.math_macros[expr], self._get_math_macro_suffix(real))
141
+ else:
142
+ return meth(self, expr, **kwargs)
143
+
144
+ return _meth_wrapper
145
+
146
+
147
+ class C89CodePrinter(CodePrinter):
148
+ """A printer to convert Python expressions to strings of C code"""
149
+ printmethod = "_ccode"
150
+ language = "C"
151
+ standard = "C89"
152
+ reserved_words = set(reserved_words)
153
+
154
+ _default_settings: dict[str, Any] = {
155
+ 'order': None,
156
+ 'full_prec': 'auto',
157
+ 'precision': 17,
158
+ 'user_functions': {},
159
+ 'human': True,
160
+ 'allow_unknown_functions': False,
161
+ 'contract': True,
162
+ 'dereference': set(),
163
+ 'error_on_reserved': False,
164
+ 'reserved_word_suffix': '_',
165
+ }
166
+
167
+ type_aliases = {
168
+ real: float64,
169
+ complex_: complex128,
170
+ integer: intc
171
+ }
172
+
173
+ type_mappings: dict[Type, Any] = {
174
+ real: 'double',
175
+ intc: 'int',
176
+ float32: 'float',
177
+ float64: 'double',
178
+ integer: 'int',
179
+ bool_: 'bool',
180
+ int8: 'int8_t',
181
+ int16: 'int16_t',
182
+ int32: 'int32_t',
183
+ int64: 'int64_t',
184
+ uint8: 'int8_t',
185
+ uint16: 'int16_t',
186
+ uint32: 'int32_t',
187
+ uint64: 'int64_t',
188
+ }
189
+
190
+ type_headers = {
191
+ bool_: {'stdbool.h'},
192
+ int8: {'stdint.h'},
193
+ int16: {'stdint.h'},
194
+ int32: {'stdint.h'},
195
+ int64: {'stdint.h'},
196
+ uint8: {'stdint.h'},
197
+ uint16: {'stdint.h'},
198
+ uint32: {'stdint.h'},
199
+ uint64: {'stdint.h'},
200
+ }
201
+
202
+ # Macros needed to be defined when using a Type
203
+ type_macros: dict[Type, tuple[str, ...]] = {}
204
+
205
+ type_func_suffixes = {
206
+ float32: 'f',
207
+ float64: '',
208
+ float80: 'l'
209
+ }
210
+
211
+ type_literal_suffixes = {
212
+ float32: 'F',
213
+ float64: '',
214
+ float80: 'L'
215
+ }
216
+
217
+ type_math_macro_suffixes = {
218
+ float80: 'l'
219
+ }
220
+
221
+ math_macros = None
222
+
223
+ _ns = '' # namespace, C++ uses 'std::'
224
+ # known_functions-dict to copy
225
+ _kf: dict[str, Any] = known_functions_C89
226
+
227
+ def __init__(self, settings=None):
228
+ settings = settings or {}
229
+ if self.math_macros is None:
230
+ self.math_macros = settings.pop('math_macros', get_math_macros())
231
+ self.type_aliases = dict(chain(self.type_aliases.items(),
232
+ settings.pop('type_aliases', {}).items()))
233
+ self.type_mappings = dict(chain(self.type_mappings.items(),
234
+ settings.pop('type_mappings', {}).items()))
235
+ self.type_headers = dict(chain(self.type_headers.items(),
236
+ settings.pop('type_headers', {}).items()))
237
+ self.type_macros = dict(chain(self.type_macros.items(),
238
+ settings.pop('type_macros', {}).items()))
239
+ self.type_func_suffixes = dict(chain(self.type_func_suffixes.items(),
240
+ settings.pop('type_func_suffixes', {}).items()))
241
+ self.type_literal_suffixes = dict(chain(self.type_literal_suffixes.items(),
242
+ settings.pop('type_literal_suffixes', {}).items()))
243
+ self.type_math_macro_suffixes = dict(chain(self.type_math_macro_suffixes.items(),
244
+ settings.pop('type_math_macro_suffixes', {}).items()))
245
+ super().__init__(settings)
246
+ self.known_functions = dict(self._kf, **settings.get('user_functions', {}))
247
+ self._dereference = set(settings.get('dereference', []))
248
+ self.headers = set()
249
+ self.libraries = set()
250
+ self.macros = set()
251
+
252
+ def _rate_index_position(self, p):
253
+ return p*5
254
+
255
+ def _get_statement(self, codestring):
256
+ """ Get code string as a statement - i.e. ending with a semicolon. """
257
+ return codestring if codestring.endswith(';') else codestring + ';'
258
+
259
+ def _get_comment(self, text):
260
+ return "/* {} */".format(text)
261
+
262
+ def _declare_number_const(self, name, value):
263
+ type_ = self.type_aliases[real]
264
+ var = Variable(name, type=type_, value=value.evalf(type_.decimal_dig), attrs={value_const})
265
+ decl = Declaration(var)
266
+ return self._get_statement(self._print(decl))
267
+
268
+ def _format_code(self, lines):
269
+ return self.indent_code(lines)
270
+
271
+ def _traverse_matrix_indices(self, mat):
272
+ rows, cols = mat.shape
273
+ return ((i, j) for i in range(rows) for j in range(cols))
274
+
275
+ @_as_macro_if_defined
276
+ def _print_Mul(self, expr, **kwargs):
277
+ return super()._print_Mul(expr, **kwargs)
278
+
279
+ @_as_macro_if_defined
280
+ def _print_Pow(self, expr):
281
+ if "Pow" in self.known_functions:
282
+ return self._print_Function(expr)
283
+ PREC = precedence(expr)
284
+ suffix = self._get_func_suffix(real)
285
+ if equal_valued(expr.exp, -1):
286
+ literal_suffix = self._get_literal_suffix(real)
287
+ return '1.0%s/%s' % (literal_suffix, self.parenthesize(expr.base, PREC))
288
+ elif equal_valued(expr.exp, 0.5):
289
+ return '%ssqrt%s(%s)' % (self._ns, suffix, self._print(expr.base))
290
+ elif expr.exp == S.One/3 and self.standard != 'C89':
291
+ return '%scbrt%s(%s)' % (self._ns, suffix, self._print(expr.base))
292
+ else:
293
+ return '%spow%s(%s, %s)' % (self._ns, suffix, self._print(expr.base),
294
+ self._print(expr.exp))
295
+
296
+ def _print_Mod(self, expr):
297
+ num, den = expr.args
298
+ if num.is_integer and den.is_integer:
299
+ PREC = precedence(expr)
300
+ snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args]
301
+ # % is remainder (same sign as numerator), not modulo (same sign as
302
+ # denominator), in C. Hence, % only works as modulo if both numbers
303
+ # have the same sign
304
+ if (num.is_nonnegative and den.is_nonnegative or
305
+ num.is_nonpositive and den.is_nonpositive):
306
+ return f"{snum} % {sden}"
307
+ return f"(({snum} % {sden}) + {sden}) % {sden}"
308
+ # Not guaranteed integer
309
+ return self._print_math_func(expr, known='fmod')
310
+
311
+ def _print_Rational(self, expr):
312
+ p, q = int(expr.p), int(expr.q)
313
+ suffix = self._get_literal_suffix(real)
314
+ return '%d.0%s/%d.0%s' % (p, suffix, q, suffix)
315
+
316
+ def _print_Indexed(self, expr):
317
+ # calculate index for 1d array
318
+ offset = getattr(expr.base, 'offset', S.Zero)
319
+ strides = getattr(expr.base, 'strides', None)
320
+ indices = expr.indices
321
+
322
+ if strides is None or isinstance(strides, str):
323
+ dims = expr.shape
324
+ shift = S.One
325
+ temp = ()
326
+ if strides == 'C' or strides is None:
327
+ traversal = reversed(range(expr.rank))
328
+ indices = indices[::-1]
329
+ elif strides == 'F':
330
+ traversal = range(expr.rank)
331
+
332
+ for i in traversal:
333
+ temp += (shift,)
334
+ shift *= dims[i]
335
+ strides = temp
336
+ flat_index = sum([x[0]*x[1] for x in zip(indices, strides)]) + offset
337
+ return "%s[%s]" % (self._print(expr.base.label),
338
+ self._print(flat_index))
339
+
340
+ def _print_Idx(self, expr):
341
+ return self._print(expr.label)
342
+
343
+ @_as_macro_if_defined
344
+ def _print_NumberSymbol(self, expr):
345
+ return super()._print_NumberSymbol(expr)
346
+
347
+ def _print_Infinity(self, expr):
348
+ return 'HUGE_VAL'
349
+
350
+ def _print_NegativeInfinity(self, expr):
351
+ return '-HUGE_VAL'
352
+
353
+ def _print_Piecewise(self, expr):
354
+ if expr.args[-1].cond != True:
355
+ # We need the last conditional to be a True, otherwise the resulting
356
+ # function may not return a result.
357
+ raise ValueError("All Piecewise expressions must contain an "
358
+ "(expr, True) statement to be used as a default "
359
+ "condition. Without one, the generated "
360
+ "expression may not evaluate to anything under "
361
+ "some condition.")
362
+ lines = []
363
+ if expr.has(Assignment):
364
+ for i, (e, c) in enumerate(expr.args):
365
+ if i == 0:
366
+ lines.append("if (%s) {" % self._print(c))
367
+ elif i == len(expr.args) - 1 and c == True:
368
+ lines.append("else {")
369
+ else:
370
+ lines.append("else if (%s) {" % self._print(c))
371
+ code0 = self._print(e)
372
+ lines.append(code0)
373
+ lines.append("}")
374
+ return "\n".join(lines)
375
+ else:
376
+ # The piecewise was used in an expression, need to do inline
377
+ # operators. This has the downside that inline operators will
378
+ # not work for statements that span multiple lines (Matrix or
379
+ # Indexed expressions).
380
+ ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c),
381
+ self._print(e))
382
+ for e, c in expr.args[:-1]]
383
+ last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
384
+ return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
385
+
386
+ def _print_ITE(self, expr):
387
+ from sympy.functions import Piecewise
388
+ return self._print(expr.rewrite(Piecewise, deep=False))
389
+
390
+ def _print_MatrixElement(self, expr):
391
+ return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"],
392
+ strict=True), expr.j + expr.i*expr.parent.shape[1])
393
+
394
+ def _print_Symbol(self, expr):
395
+ name = super()._print_Symbol(expr)
396
+ if expr in self._settings['dereference']:
397
+ return '(*{})'.format(name)
398
+ else:
399
+ return name
400
+
401
+ def _print_Relational(self, expr):
402
+ lhs_code = self._print(expr.lhs)
403
+ rhs_code = self._print(expr.rhs)
404
+ op = expr.rel_op
405
+ return "{} {} {}".format(lhs_code, op, rhs_code)
406
+
407
+ def _print_For(self, expr):
408
+ target = self._print(expr.target)
409
+ if isinstance(expr.iterable, Range):
410
+ start, stop, step = expr.iterable.args
411
+ else:
412
+ raise NotImplementedError("Only iterable currently supported is Range")
413
+ body = self._print(expr.body)
414
+ return ('for ({target} = {start}; {target} < {stop}; {target} += '
415
+ '{step}) {{\n{body}\n}}').format(target=target, start=start,
416
+ stop=stop, step=step, body=body)
417
+
418
+ def _print_sign(self, func):
419
+ return '((({0}) > 0) - (({0}) < 0))'.format(self._print(func.args[0]))
420
+
421
+ def _print_Max(self, expr):
422
+ if "Max" in self.known_functions:
423
+ return self._print_Function(expr)
424
+ def inner_print_max(args): # The more natural abstraction of creating
425
+ if len(args) == 1: # and printing smaller Max objects is slow
426
+ return self._print(args[0]) # when there are many arguments.
427
+ half = len(args) // 2
428
+ return "((%(a)s > %(b)s) ? %(a)s : %(b)s)" % {
429
+ 'a': inner_print_max(args[:half]),
430
+ 'b': inner_print_max(args[half:])
431
+ }
432
+ return inner_print_max(expr.args)
433
+
434
+ def _print_Min(self, expr):
435
+ if "Min" in self.known_functions:
436
+ return self._print_Function(expr)
437
+ def inner_print_min(args): # The more natural abstraction of creating
438
+ if len(args) == 1: # and printing smaller Min objects is slow
439
+ return self._print(args[0]) # when there are many arguments.
440
+ half = len(args) // 2
441
+ return "((%(a)s < %(b)s) ? %(a)s : %(b)s)" % {
442
+ 'a': inner_print_min(args[:half]),
443
+ 'b': inner_print_min(args[half:])
444
+ }
445
+ return inner_print_min(expr.args)
446
+
447
+ def indent_code(self, code):
448
+ """Accepts a string of code or a list of code lines"""
449
+
450
+ if isinstance(code, str):
451
+ code_lines = self.indent_code(code.splitlines(True))
452
+ return ''.join(code_lines)
453
+
454
+ tab = " "
455
+ inc_token = ('{', '(', '{\n', '(\n')
456
+ dec_token = ('}', ')')
457
+
458
+ code = [line.lstrip(' \t') for line in code]
459
+
460
+ increase = [int(any(map(line.endswith, inc_token))) for line in code]
461
+ decrease = [int(any(map(line.startswith, dec_token))) for line in code]
462
+
463
+ pretty = []
464
+ level = 0
465
+ for n, line in enumerate(code):
466
+ if line in ('', '\n'):
467
+ pretty.append(line)
468
+ continue
469
+ level -= decrease[n]
470
+ pretty.append("%s%s" % (tab*level, line))
471
+ level += increase[n]
472
+ return pretty
473
+
474
+ def _get_func_suffix(self, type_):
475
+ return self.type_func_suffixes[self.type_aliases.get(type_, type_)]
476
+
477
+ def _get_literal_suffix(self, type_):
478
+ return self.type_literal_suffixes[self.type_aliases.get(type_, type_)]
479
+
480
+ def _get_math_macro_suffix(self, type_):
481
+ alias = self.type_aliases.get(type_, type_)
482
+ dflt = self.type_math_macro_suffixes.get(alias, '')
483
+ return self.type_math_macro_suffixes.get(type_, dflt)
484
+
485
+ def _print_Tuple(self, expr):
486
+ return '{'+', '.join(self._print(e) for e in expr)+'}'
487
+
488
+ _print_List = _print_Tuple
489
+
490
+ def _print_Type(self, type_):
491
+ self.headers.update(self.type_headers.get(type_, set()))
492
+ self.macros.update(self.type_macros.get(type_, set()))
493
+ return self._print(self.type_mappings.get(type_, type_.name))
494
+
495
+ def _print_Declaration(self, decl):
496
+ from sympy.codegen.cnodes import restrict
497
+ var = decl.variable
498
+ val = var.value
499
+ if var.type == untyped:
500
+ raise ValueError("C does not support untyped variables")
501
+
502
+ if isinstance(var, Pointer):
503
+ result = '{vc}{t} *{pc} {r}{s}'.format(
504
+ vc='const ' if value_const in var.attrs else '',
505
+ t=self._print(var.type),
506
+ pc=' const' if pointer_const in var.attrs else '',
507
+ r='restrict ' if restrict in var.attrs else '',
508
+ s=self._print(var.symbol)
509
+ )
510
+ elif isinstance(var, Variable):
511
+ result = '{vc}{t} {s}'.format(
512
+ vc='const ' if value_const in var.attrs else '',
513
+ t=self._print(var.type),
514
+ s=self._print(var.symbol)
515
+ )
516
+ else:
517
+ raise NotImplementedError("Unknown type of var: %s" % type(var))
518
+ if val != None: # Must be "!= None", cannot be "is not None"
519
+ result += ' = %s' % self._print(val)
520
+ return result
521
+
522
+ def _print_Float(self, flt):
523
+ type_ = self.type_aliases.get(real, real)
524
+ self.macros.update(self.type_macros.get(type_, set()))
525
+ suffix = self._get_literal_suffix(type_)
526
+ num = str(flt.evalf(type_.decimal_dig))
527
+ if 'e' not in num and '.' not in num:
528
+ num += '.0'
529
+ num_parts = num.split('e')
530
+ num_parts[0] = num_parts[0].rstrip('0')
531
+ if num_parts[0].endswith('.'):
532
+ num_parts[0] += '0'
533
+ return 'e'.join(num_parts) + suffix
534
+
535
+ @requires(headers={'stdbool.h'})
536
+ def _print_BooleanTrue(self, expr):
537
+ return 'true'
538
+
539
+ @requires(headers={'stdbool.h'})
540
+ def _print_BooleanFalse(self, expr):
541
+ return 'false'
542
+
543
+ def _print_Element(self, elem):
544
+ if elem.strides == None: # Must be "== None", cannot be "is None"
545
+ if elem.offset != None: # Must be "!= None", cannot be "is not None"
546
+ raise ValueError("Expected strides when offset is given")
547
+ idxs = ']['.join((self._print(arg) for arg in elem.indices))
548
+ else:
549
+ global_idx = sum([i*s for i, s in zip(elem.indices, elem.strides)])
550
+ if elem.offset != None: # Must be "!= None", cannot be "is not None"
551
+ global_idx += elem.offset
552
+ idxs = self._print(global_idx)
553
+
554
+ return "{symb}[{idxs}]".format(
555
+ symb=self._print(elem.symbol),
556
+ idxs=idxs
557
+ )
558
+
559
+ def _print_CodeBlock(self, expr):
560
+ """ Elements of code blocks printed as statements. """
561
+ return '\n'.join([self._get_statement(self._print(i)) for i in expr.args])
562
+
563
+ def _print_While(self, expr):
564
+ return 'while ({condition}) {{\n{body}\n}}'.format(**expr.kwargs(
565
+ apply=lambda arg: self._print(arg)))
566
+
567
+ def _print_Scope(self, expr):
568
+ return '{\n%s\n}' % self._print_CodeBlock(expr.body)
569
+
570
+ @requires(headers={'stdio.h'})
571
+ def _print_Print(self, expr):
572
+ return 'printf({fmt}, {pargs})'.format(
573
+ fmt=self._print(expr.format_string),
574
+ pargs=', '.join((self._print(arg) for arg in expr.print_args))
575
+ )
576
+
577
+ def _print_FunctionPrototype(self, expr):
578
+ pars = ', '.join((self._print(Declaration(arg)) for arg in expr.parameters))
579
+ return "%s %s(%s)" % (
580
+ tuple((self._print(arg) for arg in (expr.return_type, expr.name))) + (pars,)
581
+ )
582
+
583
+ def _print_FunctionDefinition(self, expr):
584
+ return "%s%s" % (self._print_FunctionPrototype(expr),
585
+ self._print_Scope(expr))
586
+
587
+ def _print_Return(self, expr):
588
+ arg, = expr.args
589
+ return 'return %s' % self._print(arg)
590
+
591
+ def _print_CommaOperator(self, expr):
592
+ return '(%s)' % ', '.join((self._print(arg) for arg in expr.args))
593
+
594
+ def _print_Label(self, expr):
595
+ if expr.body == none:
596
+ return '%s:' % str(expr.name)
597
+ if len(expr.body.args) == 1:
598
+ return '%s:\n%s' % (str(expr.name), self._print_CodeBlock(expr.body))
599
+ return '%s:\n{\n%s\n}' % (str(expr.name), self._print_CodeBlock(expr.body))
600
+
601
+ def _print_goto(self, expr):
602
+ return 'goto %s' % expr.label.name
603
+
604
+ def _print_PreIncrement(self, expr):
605
+ arg, = expr.args
606
+ return '++(%s)' % self._print(arg)
607
+
608
+ def _print_PostIncrement(self, expr):
609
+ arg, = expr.args
610
+ return '(%s)++' % self._print(arg)
611
+
612
+ def _print_PreDecrement(self, expr):
613
+ arg, = expr.args
614
+ return '--(%s)' % self._print(arg)
615
+
616
+ def _print_PostDecrement(self, expr):
617
+ arg, = expr.args
618
+ return '(%s)--' % self._print(arg)
619
+
620
+ def _print_struct(self, expr):
621
+ return "%(keyword)s %(name)s {\n%(lines)s}" % {
622
+ "keyword": expr.__class__.__name__, "name": expr.name, "lines": ';\n'.join(
623
+ [self._print(decl) for decl in expr.declarations] + [''])
624
+ }
625
+
626
+ def _print_BreakToken(self, _):
627
+ return 'break'
628
+
629
+ def _print_ContinueToken(self, _):
630
+ return 'continue'
631
+
632
+ _print_union = _print_struct
633
+
634
+ class C99CodePrinter(C89CodePrinter):
635
+ standard = 'C99'
636
+ reserved_words = set(reserved_words + reserved_words_c99)
637
+ type_mappings=dict(chain(C89CodePrinter.type_mappings.items(), {
638
+ complex64: 'float complex',
639
+ complex128: 'double complex',
640
+ }.items()))
641
+ type_headers = dict(chain(C89CodePrinter.type_headers.items(), {
642
+ complex64: {'complex.h'},
643
+ complex128: {'complex.h'}
644
+ }.items()))
645
+
646
+ # known_functions-dict to copy
647
+ _kf: dict[str, Any] = known_functions_C99
648
+
649
+ # functions with versions with 'f' and 'l' suffixes:
650
+ _prec_funcs = ('fabs fmod remainder remquo fma fmax fmin fdim nan exp exp2'
651
+ ' expm1 log log10 log2 log1p pow sqrt cbrt hypot sin cos tan'
652
+ ' asin acos atan atan2 sinh cosh tanh asinh acosh atanh erf'
653
+ ' erfc tgamma lgamma ceil floor trunc round nearbyint rint'
654
+ ' frexp ldexp modf scalbn ilogb logb nextafter copysign').split()
655
+
656
+ def _print_Infinity(self, expr):
657
+ return 'INFINITY'
658
+
659
+ def _print_NegativeInfinity(self, expr):
660
+ return '-INFINITY'
661
+
662
+ def _print_NaN(self, expr):
663
+ return 'NAN'
664
+
665
+ # tgamma was already covered by 'known_functions' dict
666
+
667
+ @requires(headers={'math.h'}, libraries={'m'})
668
+ @_as_macro_if_defined
669
+ def _print_math_func(self, expr, nest=False, known=None):
670
+ if known is None:
671
+ known = self.known_functions[expr.__class__.__name__]
672
+ if not isinstance(known, str):
673
+ for cb, name in known:
674
+ if cb(*expr.args):
675
+ known = name
676
+ break
677
+ else:
678
+ raise ValueError("No matching printer")
679
+ try:
680
+ return known(self, *expr.args)
681
+ except TypeError:
682
+ suffix = self._get_func_suffix(real) if self._ns + known in self._prec_funcs else ''
683
+
684
+ if nest:
685
+ args = self._print(expr.args[0])
686
+ if len(expr.args) > 1:
687
+ paren_pile = ''
688
+ for curr_arg in expr.args[1:-1]:
689
+ paren_pile += ')'
690
+ args += ', {ns}{name}{suffix}({next}'.format(
691
+ ns=self._ns,
692
+ name=known,
693
+ suffix=suffix,
694
+ next = self._print(curr_arg)
695
+ )
696
+ args += ', %s%s' % (
697
+ self._print(expr.func(expr.args[-1])),
698
+ paren_pile
699
+ )
700
+ else:
701
+ args = ', '.join((self._print(arg) for arg in expr.args))
702
+ return '{ns}{name}{suffix}({args})'.format(
703
+ ns=self._ns,
704
+ name=known,
705
+ suffix=suffix,
706
+ args=args
707
+ )
708
+
709
+ def _print_Max(self, expr):
710
+ return self._print_math_func(expr, nest=True)
711
+
712
+ def _print_Min(self, expr):
713
+ return self._print_math_func(expr, nest=True)
714
+
715
+ def _get_loop_opening_ending(self, indices):
716
+ open_lines = []
717
+ close_lines = []
718
+ loopstart = "for (int %(var)s=%(start)s; %(var)s<%(end)s; %(var)s++){" # C99
719
+ for i in indices:
720
+ # C arrays start at 0 and end at dimension-1
721
+ open_lines.append(loopstart % {
722
+ 'var': self._print(i.label),
723
+ 'start': self._print(i.lower),
724
+ 'end': self._print(i.upper + 1)})
725
+ close_lines.append("}")
726
+ return open_lines, close_lines
727
+
728
+
729
+ for k in ('Abs Sqrt exp exp2 expm1 log log10 log2 log1p Cbrt hypot fma'
730
+ ' loggamma sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh '
731
+ 'atanh erf erfc loggamma gamma ceiling floor').split():
732
+ setattr(C99CodePrinter, '_print_%s' % k, C99CodePrinter._print_math_func)
733
+
734
+
735
+ class C11CodePrinter(C99CodePrinter):
736
+
737
+ @requires(headers={'stdalign.h'})
738
+ def _print_alignof(self, expr):
739
+ arg, = expr.args
740
+ return 'alignof(%s)' % self._print(arg)
741
+
742
+
743
+ c_code_printers = {
744
+ 'c89': C89CodePrinter,
745
+ 'c99': C99CodePrinter,
746
+ 'c11': C11CodePrinter
747
+ }
shared/package-files/75/7510eeb3ef2a9159b938104fdf56be45d49a85872b9fd1c66097204dafcb3c12/blob ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Iterable, Optional
2
+
3
+ def smart_truncate(
4
+ string: str, max_length: int = ..., word_boundary: bool = ..., separator: str = ..., save_order: bool = ...
5
+ ) -> str: ...
6
+ def slugify(
7
+ text: str,
8
+ entities: bool = ...,
9
+ decimal: bool = ...,
10
+ hexadecimal: bool = ...,
11
+ max_length: int = ...,
12
+ word_boundary: bool = ...,
13
+ separator: str = ...,
14
+ save_order: bool = ...,
15
+ stopwords: Iterable[str] = ...,
16
+ regex_pattern: Optional[str] = ...,
17
+ lowercase: bool = ...,
18
+ replacements: Iterable[str] = ...,
19
+ ) -> str: ...
shared/package-files/75/7513950e2f6446f91b49dca77772f4f6da7dfdec7343842a1b7c67371efc25e5/blob ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """ FFT backend using pypocketfft """
2
+
3
+ from .basic import *
4
+ from .realtransforms import *
5
+ from .helper import *
6
+
7
+ from scipy._lib._testutils import PytestTester
8
+ test = PytestTester(__name__)
9
+ del PytestTester
shared/package-files/75/7513a174b46308686a1fb6c8dffc946cf06beda20a04cd4ab3f8968beec73aad/blob ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import Optional
3
+
4
+ if sys.version_info >= (3, 8):
5
+ class CancelledError(BaseException): ...
6
+ class TimeoutError(Exception): ...
7
+ class InvalidStateError(Exception): ...
8
+ class SendfileNotAvailableError(RuntimeError): ...
9
+ class IncompleteReadError(EOFError):
10
+ expected: Optional[int]
11
+ partial: bytes
12
+ def __init__(self, partial: bytes, expected: Optional[int]) -> None: ...
13
+ class LimitOverrunError(Exception):
14
+ consumed: int
15
+ def __init__(self, message: str, consumed: int) -> None: ...
shared/package-files/75/7514b45c9d86e1bc0b74146328c929c82a4119882e52205043d8fe3f70423c93/blob ADDED
Binary file (15 kB). View file
 
shared/package-files/75/75173baf355b7493185b2268dc65617e6e061b18fb10cff224171db108ca7600/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:75173baf355b7493185b2268dc65617e6e061b18fb10cff224171db108ca7600
3
+ size 15822785
shared/package-files/75/7518c360c036ef0b0fdaebdaec9f8a81dcb952fba4354a7a21f42d8629b35de1/blob 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 cpu {
19
+
20
+ TORCH_API at::Tensor sign(const at::Tensor & self);
21
+ TORCH_API at::Tensor & sign_out(at::Tensor & out, const at::Tensor & self);
22
+ TORCH_API at::Tensor & sign_outf(const at::Tensor & self, at::Tensor & out);
23
+ TORCH_API at::Tensor & sign_(at::Tensor & self);
24
+
25
+ } // namespace cpu
26
+ } // namespace at
shared/package-files/75/75193016ad610ad89daf29e4b2bc84b3c2f8e3667b445c314e3cb0c24d2b6546/blob ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API at::Tensor cat(const at::ITensorListRef & tensors, int64_t dim=0);
21
+
22
+ } // namespace compositeexplicitautogradnonfunctional
23
+ } // namespace at
shared/package-files/75/751945c08fd2c7ac7b49d0be092622eafa5ac58e60d92f99a59b4f8bdc307c33/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:751945c08fd2c7ac7b49d0be092622eafa5ac58e60d92f99a59b4f8bdc307c33
3
+ size 1411784
shared/package-files/75/751c6320bf926c5558d2adc88d232b7e00531eb9b52d90e02ceca0541c226197/blob ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rich text and beautiful formatting in the terminal."""
2
+
3
+ import os
4
+ from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union
5
+
6
+ from ._extension import load_ipython_extension # noqa: F401
7
+
8
+ __all__ = ["get_console", "reconfigure", "print", "inspect", "print_json"]
9
+
10
+ if TYPE_CHECKING:
11
+ from .console import Console
12
+
13
+ # Global console used by alternative print
14
+ _console: Optional["Console"] = None
15
+
16
+ try:
17
+ _IMPORT_CWD = os.path.abspath(os.getcwd())
18
+ except FileNotFoundError:
19
+ # Can happen if the cwd has been deleted
20
+ _IMPORT_CWD = ""
21
+
22
+
23
+ def get_console() -> "Console":
24
+ """Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console,
25
+ and hasn't been explicitly given one.
26
+
27
+ Returns:
28
+ Console: A console instance.
29
+ """
30
+ global _console
31
+ if _console is None:
32
+ from .console import Console
33
+
34
+ _console = Console()
35
+
36
+ return _console
37
+
38
+
39
+ def reconfigure(*args: Any, **kwargs: Any) -> None:
40
+ """Reconfigures the global console by replacing it with another.
41
+
42
+ Args:
43
+ *args (Any): Positional arguments for the replacement :class:`~rich.console.Console`.
44
+ **kwargs (Any): Keyword arguments for the replacement :class:`~rich.console.Console`.
45
+ """
46
+ from pip._vendor.rich.console import Console
47
+
48
+ new_console = Console(*args, **kwargs)
49
+ _console = get_console()
50
+ _console.__dict__ = new_console.__dict__
51
+
52
+
53
+ def print(
54
+ *objects: Any,
55
+ sep: str = " ",
56
+ end: str = "\n",
57
+ file: Optional[IO[str]] = None,
58
+ flush: bool = False,
59
+ ) -> None:
60
+ r"""Print object(s) supplied via positional arguments.
61
+ This function has an identical signature to the built-in print.
62
+ For more advanced features, see the :class:`~rich.console.Console` class.
63
+
64
+ Args:
65
+ sep (str, optional): Separator between printed objects. Defaults to " ".
66
+ end (str, optional): Character to write at end of output. Defaults to "\\n".
67
+ file (IO[str], optional): File to write to, or None for stdout. Defaults to None.
68
+ flush (bool, optional): Has no effect as Rich always flushes output. Defaults to False.
69
+
70
+ """
71
+ from .console import Console
72
+
73
+ write_console = get_console() if file is None else Console(file=file)
74
+ return write_console.print(*objects, sep=sep, end=end)
75
+
76
+
77
+ def print_json(
78
+ json: Optional[str] = None,
79
+ *,
80
+ data: Any = None,
81
+ indent: Union[None, int, str] = 2,
82
+ highlight: bool = True,
83
+ skip_keys: bool = False,
84
+ ensure_ascii: bool = False,
85
+ check_circular: bool = True,
86
+ allow_nan: bool = True,
87
+ default: Optional[Callable[[Any], Any]] = None,
88
+ sort_keys: bool = False,
89
+ ) -> None:
90
+ """Pretty prints JSON. Output will be valid JSON.
91
+
92
+ Args:
93
+ json (str): A string containing JSON.
94
+ data (Any): If json is not supplied, then encode this data.
95
+ indent (int, optional): Number of spaces to indent. Defaults to 2.
96
+ highlight (bool, optional): Enable highlighting of output: Defaults to True.
97
+ skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
98
+ ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
99
+ check_circular (bool, optional): Check for circular references. Defaults to True.
100
+ allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
101
+ default (Callable, optional): A callable that converts values that can not be encoded
102
+ in to something that can be JSON encoded. Defaults to None.
103
+ sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
104
+ """
105
+
106
+ get_console().print_json(
107
+ json,
108
+ data=data,
109
+ indent=indent,
110
+ highlight=highlight,
111
+ skip_keys=skip_keys,
112
+ ensure_ascii=ensure_ascii,
113
+ check_circular=check_circular,
114
+ allow_nan=allow_nan,
115
+ default=default,
116
+ sort_keys=sort_keys,
117
+ )
118
+
119
+
120
+ def inspect(
121
+ obj: Any,
122
+ *,
123
+ console: Optional["Console"] = None,
124
+ title: Optional[str] = None,
125
+ help: bool = False,
126
+ methods: bool = False,
127
+ docs: bool = True,
128
+ private: bool = False,
129
+ dunder: bool = False,
130
+ sort: bool = True,
131
+ all: bool = False,
132
+ value: bool = True,
133
+ ) -> None:
134
+ """Inspect any Python object.
135
+
136
+ * inspect(<OBJECT>) to see summarized info.
137
+ * inspect(<OBJECT>, methods=True) to see methods.
138
+ * inspect(<OBJECT>, help=True) to see full (non-abbreviated) help.
139
+ * inspect(<OBJECT>, private=True) to see private attributes (single underscore).
140
+ * inspect(<OBJECT>, dunder=True) to see attributes beginning with double underscore.
141
+ * inspect(<OBJECT>, all=True) to see all attributes.
142
+
143
+ Args:
144
+ obj (Any): An object to inspect.
145
+ title (str, optional): Title to display over inspect result, or None use type. Defaults to None.
146
+ help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.
147
+ methods (bool, optional): Enable inspection of callables. Defaults to False.
148
+ docs (bool, optional): Also render doc strings. Defaults to True.
149
+ private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.
150
+ dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.
151
+ sort (bool, optional): Sort attributes alphabetically. Defaults to True.
152
+ all (bool, optional): Show all attributes. Defaults to False.
153
+ value (bool, optional): Pretty print value. Defaults to True.
154
+ """
155
+ _console = console or get_console()
156
+ from pip._vendor.rich._inspect import Inspect
157
+
158
+ # Special case for inspect(inspect)
159
+ is_inspect = obj is inspect
160
+
161
+ _inspect = Inspect(
162
+ obj,
163
+ title=title,
164
+ help=is_inspect or help,
165
+ methods=is_inspect or methods,
166
+ docs=is_inspect or docs,
167
+ private=private,
168
+ dunder=dunder,
169
+ sort=sort,
170
+ all=all,
171
+ value=value,
172
+ )
173
+ _console.print(_inspect)
174
+
175
+
176
+ if __name__ == "__main__": # pragma: no cover
177
+ print("Hello, **World**")
shared/package-files/75/751d9124f157e3907b0ed61ac19ec07444db9edec14cebd0e486f7095d4abe08/blob ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import datetime
8
+ import random
9
+ import time
10
+ from base64 import b64decode, b64encode
11
+ from typing import Optional
12
+
13
+ import etcd # type: ignore[import]
14
+
15
+ # pyre-ignore[21]: Could not find name `Store` in `torch.distributed`.
16
+ from torch.distributed import Store
17
+
18
+
19
+ # Delay (sleep) for a small random amount to reduce CAS failures.
20
+ # This does not affect correctness, but will reduce requests to etcd server.
21
+ def cas_delay():
22
+ time.sleep(random.uniform(0, 0.1))
23
+
24
+
25
+ # pyre-fixme[11]: Annotation `Store` is not defined as a type.
26
+ class EtcdStore(Store):
27
+ """
28
+ Implement a c10 Store interface by piggybacking on the rendezvous etcd instance.
29
+
30
+ This is the store object returned by ``EtcdRendezvous``.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ etcd_client,
36
+ etcd_store_prefix,
37
+ # Default timeout same as in c10d/Store.hpp
38
+ timeout: Optional[datetime.timedelta] = None,
39
+ ):
40
+ super().__init__() # required for pybind trampoline.
41
+
42
+ self.client = etcd_client
43
+ self.prefix = etcd_store_prefix
44
+
45
+ if timeout is not None:
46
+ self.set_timeout(timeout)
47
+
48
+ if not self.prefix.endswith("/"):
49
+ self.prefix += "/"
50
+
51
+ def set(self, key, value):
52
+ """
53
+ Write a key/value pair into ``EtcdStore``.
54
+
55
+ Both key and value may be either Python ``str`` or ``bytes``.
56
+ """
57
+ self.client.set(key=self.prefix + self._encode(key), value=self._encode(value))
58
+
59
+ def get(self, key) -> bytes:
60
+ """
61
+ Get a value by key, possibly doing a blocking wait.
62
+
63
+ If key is not immediately present, will do a blocking wait
64
+ for at most ``timeout`` duration or until the key is published.
65
+
66
+
67
+ Returns:
68
+ value ``(bytes)``
69
+
70
+ Raises:
71
+ LookupError - If key still not published after timeout
72
+ """
73
+ b64_key = self.prefix + self._encode(key)
74
+ kvs = self._try_wait_get([b64_key])
75
+
76
+ if kvs is None:
77
+ raise LookupError(f"Key {key} not found in EtcdStore")
78
+
79
+ return self._decode(kvs[b64_key])
80
+
81
+ def add(self, key, num: int) -> int:
82
+ """
83
+ Atomically increment a value by an integer amount.
84
+
85
+ The integer is represented as a string using base 10. If key is not present,
86
+ a default value of ``0`` will be assumed.
87
+
88
+ Returns:
89
+ the new (incremented) value
90
+
91
+
92
+ """
93
+ b64_key = self._encode(key)
94
+ # c10d Store assumes value is an integer represented as a decimal string
95
+ try:
96
+ # Assume default value "0", if this key didn't yet:
97
+ node = self.client.write(
98
+ key=self.prefix + b64_key,
99
+ value=self._encode(str(num)), # i.e. 0 + num
100
+ prevExist=False,
101
+ )
102
+ return int(self._decode(node.value))
103
+ except etcd.EtcdAlreadyExist:
104
+ pass
105
+
106
+ while True:
107
+ # Note: c10d Store does not have a method to delete keys, so we
108
+ # can be sure it's still there.
109
+ node = self.client.get(key=self.prefix + b64_key)
110
+ new_value = self._encode(str(int(self._decode(node.value)) + num))
111
+ try:
112
+ node = self.client.test_and_set(
113
+ key=node.key, value=new_value, prev_value=node.value
114
+ )
115
+ return int(self._decode(node.value))
116
+ except etcd.EtcdCompareFailed:
117
+ cas_delay()
118
+
119
+ def wait(self, keys, override_timeout: Optional[datetime.timedelta] = None):
120
+ """
121
+ Wait until all of the keys are published, or until timeout.
122
+
123
+ Raises:
124
+ LookupError - if timeout occurs
125
+ """
126
+ b64_keys = [self.prefix + self._encode(key) for key in keys]
127
+ kvs = self._try_wait_get(b64_keys, override_timeout)
128
+ if kvs is None:
129
+ raise LookupError("Timeout while waiting for keys in EtcdStore")
130
+ # No return value on success
131
+
132
+ def check(self, keys) -> bool:
133
+ """Check if all of the keys are immediately present (without waiting)."""
134
+ b64_keys = [self.prefix + self._encode(key) for key in keys]
135
+ kvs = self._try_wait_get(
136
+ b64_keys,
137
+ override_timeout=datetime.timedelta(microseconds=1), # as if no wait
138
+ )
139
+ return kvs is not None
140
+
141
+ #
142
+ # Encode key/value data in base64, so we can store arbitrary binary data
143
+ # in EtcdStore. Input can be `str` or `bytes`.
144
+ # In case of `str`, utf-8 encoding is assumed.
145
+ #
146
+ def _encode(self, value) -> str:
147
+ if type(value) == bytes:
148
+ return b64encode(value).decode()
149
+ elif type(value) == str:
150
+ return b64encode(value.encode()).decode()
151
+ raise ValueError("Value must be of type str or bytes")
152
+
153
+ #
154
+ # Decode a base64 string (of type `str` or `bytes`).
155
+ # Return type is `bytes`, which is more convenient with the Store interface.
156
+ #
157
+ def _decode(self, value) -> bytes:
158
+ if type(value) == bytes:
159
+ return b64decode(value)
160
+ elif type(value) == str:
161
+ return b64decode(value.encode())
162
+ raise ValueError("Value must be of type str or bytes")
163
+
164
+ #
165
+ # Get all of the (base64-encoded) etcd keys at once, or wait until all the keys
166
+ # are published or timeout occurs.
167
+ # This is a helper method for the public interface methods.
168
+ #
169
+ # On success, a dictionary of {etcd key -> etcd value} is returned.
170
+ # On timeout, None is returned.
171
+ #
172
+ def _try_wait_get(self, b64_keys, override_timeout=None):
173
+ timeout = self.timeout if override_timeout is None else override_timeout # type: ignore[attr-defined]
174
+ deadline = time.time() + timeout.total_seconds()
175
+
176
+ while True:
177
+ # Read whole directory (of keys), filter only the ones waited for
178
+ all_nodes = self.client.get(key=self.prefix)
179
+ req_nodes = {
180
+ node.key: node.value for node in all_nodes.children if node.key in b64_keys
181
+ }
182
+
183
+ if len(req_nodes) == len(b64_keys):
184
+ # All keys are available
185
+ return req_nodes
186
+
187
+ watch_timeout = deadline - time.time()
188
+ if watch_timeout <= 0:
189
+ return None
190
+
191
+ try:
192
+ self.client.watch(
193
+ key=self.prefix,
194
+ recursive=True,
195
+ timeout=watch_timeout,
196
+ index=all_nodes.etcd_index + 1,
197
+ )
198
+ except etcd.EtcdWatchTimedOut:
199
+ if time.time() >= deadline:
200
+ return None
201
+ else:
202
+ continue
203
+ except etcd.EtcdEventIndexCleared:
204
+ continue
shared/package-files/75/752297e4e2cef56804b28cb461cfbd7bd8dfcd455b2d42a2797f5a1ced4b692a/blob ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable, Mapping
4
+ from typing import Any
5
+
6
+ from formulaic.materializers.types.evaluated_factor import EvaluatedFactor
7
+ from formulaic.utils.variables import Variable
8
+
9
+ from .scoped_factor import ScopedFactor
10
+
11
+
12
+ class ScopedTerm:
13
+ """
14
+ A representation of a `Term` where scopes have been applied to the factors.
15
+ Recall that "scopes" in this context refer to whether or not the factor
16
+ values have been reduced in rank or not.
17
+
18
+ Attributes:
19
+ factors: The `ScopedFactor` instances.
20
+ scale: The global factor associated with the term that should be applied
21
+ during column materialization.
22
+ """
23
+
24
+ __slots__ = ("factors", "scale")
25
+
26
+ def __init__(self, factors: Iterable[ScopedFactor], scale: float = 1):
27
+ self.factors = tuple(dict.fromkeys(factors))
28
+ self.scale = scale
29
+
30
+ def __hash__(self) -> int:
31
+ return hash(tuple(sorted(self.factors)))
32
+
33
+ def __eq__(self, other: Any) -> bool:
34
+ if isinstance(other, ScopedTerm):
35
+ return sorted(self.factors) == sorted(other.factors)
36
+ return NotImplemented
37
+
38
+ def __repr__(self) -> str:
39
+ factor_repr = (
40
+ ":".join(f.__repr__() for f in self.factors) if self.factors else "1"
41
+ )
42
+ if self.scale is not None and self.scale != 1:
43
+ return f"{self.scale}*{factor_repr}"
44
+ return factor_repr
45
+
46
+ def copy(self, *, without_values: bool = False) -> ScopedTerm:
47
+ """
48
+ Return a copy of this `ScopedTerm` instance, potentially without the
49
+ materialized values attached. This is used during the generation of
50
+ model specs in order to reduce the size of the serialized specs.
51
+
52
+ Args:
53
+ without_values: Whether the materialized values should be omitted
54
+ from the copy.
55
+ """
56
+ factors: Iterable[ScopedFactor] = self.factors
57
+ if without_values:
58
+ factors = [
59
+ ScopedFactor(
60
+ factor=factor.factor.replace(values=None),
61
+ reduced=factor.reduced,
62
+ )
63
+ for factor in factors
64
+ ]
65
+ return ScopedTerm(factors, scale=self.scale)
66
+
67
+ def rehydrate(self, factor_values: Mapping[str, EvaluatedFactor]) -> ScopedTerm:
68
+ """
69
+ Rehydrate the `ScopedTerm` instance with new `EvaluatedFactor` instances
70
+ that have been computed for each factor. An exception will be raised if
71
+ any required factor is missing from the `factor_values` mapping. This is
72
+ used to allow the reuse of serialized `ScopedTerm` structure that have
73
+ had their factor values excised using `.copy(without_values=True)`.
74
+
75
+ Args:
76
+ factor_values: A mapping from factor expressions to `EvaluatedFactor`
77
+ instances. This mapping should contain all factors in the term.
78
+ """
79
+ return ScopedTerm(
80
+ [
81
+ ScopedFactor(
82
+ factor=factor_values[factor.factor.expr],
83
+ reduced=factor.reduced,
84
+ )
85
+ for factor in self.factors
86
+ ],
87
+ scale=self.scale,
88
+ )
89
+
90
+ @property
91
+ def variables(self) -> set[Variable]:
92
+ return Variable.union(
93
+ *(
94
+ factor.factor.variables
95
+ for factor in self.factors
96
+ if factor.factor.variables is not None
97
+ )
98
+ )
shared/package-files/75/75235d661a1cf1ae21e74c11b5b3b12f0a668148ae305a5eeb2b532d445ca656/blob ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # conceal the implicit import from the code quality tester
2
+ from sympy.core.numbers import (oo, pi)
3
+ from sympy.core.symbol import (Symbol, symbols)
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.special.bessel import besseli
7
+ from sympy.functions.special.gamma_functions import gamma
8
+ from sympy.integrals.integrals import integrate
9
+ from sympy.integrals.transforms import (mellin_transform,
10
+ inverse_fourier_transform, inverse_mellin_transform,
11
+ laplace_transform, inverse_laplace_transform, fourier_transform)
12
+
13
+ LT = laplace_transform
14
+ FT = fourier_transform
15
+ MT = mellin_transform
16
+ IFT = inverse_fourier_transform
17
+ ILT = inverse_laplace_transform
18
+ IMT = inverse_mellin_transform
19
+
20
+ from sympy.abc import x, y
21
+ nu, beta, rho = symbols('nu beta rho')
22
+
23
+ apos, bpos, cpos, dpos, posk, p = symbols('a b c d k p', positive=True)
24
+ k = Symbol('k', real=True)
25
+ negk = Symbol('k', negative=True)
26
+
27
+ mu1, mu2 = symbols('mu1 mu2', real=True, nonzero=True, finite=True)
28
+ sigma1, sigma2 = symbols('sigma1 sigma2', real=True, nonzero=True,
29
+ finite=True, positive=True)
30
+ rate = Symbol('lambda', positive=True)
31
+
32
+
33
+ def normal(x, mu, sigma):
34
+ return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2)
35
+
36
+
37
+ def exponential(x, rate):
38
+ return rate*exp(-rate*x)
39
+ alpha, beta = symbols('alpha beta', positive=True)
40
+ betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \
41
+ /gamma(alpha)/gamma(beta)
42
+ kint = Symbol('k', integer=True, positive=True)
43
+ chi = 2**(1 - kint/2)*x**(kint - 1)*exp(-x**2/2)/gamma(kint/2)
44
+ chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2)
45
+ dagum = apos*p/x*(x/bpos)**(apos*p)/(1 + x**apos/bpos**apos)**(p + 1)
46
+ d1, d2 = symbols('d1 d2', positive=True)
47
+ f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \
48
+ /gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2)
49
+ nupos, sigmapos = symbols('nu sigma', positive=True)
50
+ rice = x/sigmapos**2*exp(-(x**2 + nupos**2)/2/sigmapos**2)*besseli(0, x*
51
+ nupos/sigmapos**2)
52
+ mu = Symbol('mu', real=True)
53
+ laplace = exp(-abs(x - mu)/bpos)/2/bpos
54
+
55
+ u = Symbol('u', polar=True)
56
+ tpos = Symbol('t', positive=True)
57
+
58
+
59
+ def E(expr):
60
+ integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
61
+ (x, 0, oo), (y, -oo, oo), meijerg=True)
62
+ integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
63
+ (y, -oo, oo), (x, 0, oo), meijerg=True)
64
+
65
+ bench = [
66
+ 'MT(x**nu*Heaviside(x - 1), x, s)',
67
+ 'MT(x**nu*Heaviside(1 - x), x, s)',
68
+ 'MT((1-x)**(beta - 1)*Heaviside(1-x), x, s)',
69
+ 'MT((x-1)**(beta - 1)*Heaviside(x-1), x, s)',
70
+ 'MT((1+x)**(-rho), x, s)',
71
+ 'MT(abs(1-x)**(-rho), x, s)',
72
+ 'MT((1-x)**(beta-1)*Heaviside(1-x) + a*(x-1)**(beta-1)*Heaviside(x-1), x, s)',
73
+ 'MT((x**a-b**a)/(x-b), x, s)',
74
+ 'MT((x**a-bpos**a)/(x-bpos), x, s)',
75
+ 'MT(exp(-x), x, s)',
76
+ 'MT(exp(-1/x), x, s)',
77
+ 'MT(log(x)**4*Heaviside(1-x), x, s)',
78
+ 'MT(log(x)**3*Heaviside(x-1), x, s)',
79
+ 'MT(log(x + 1), x, s)',
80
+ 'MT(log(1/x + 1), x, s)',
81
+ 'MT(log(abs(1 - x)), x, s)',
82
+ 'MT(log(abs(1 - 1/x)), x, s)',
83
+ 'MT(log(x)/(x+1), x, s)',
84
+ 'MT(log(x)**2/(x+1), x, s)',
85
+ 'MT(log(x)/(x+1)**2, x, s)',
86
+ 'MT(erf(sqrt(x)), x, s)',
87
+
88
+ 'MT(besselj(a, 2*sqrt(x)), x, s)',
89
+ 'MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s)',
90
+ 'MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s)',
91
+ 'MT(besselj(a, sqrt(x))**2, x, s)',
92
+ 'MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s)',
93
+ 'MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s)',
94
+ 'MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s)',
95
+ 'MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)',
96
+ 'MT(bessely(a, 2*sqrt(x)), x, s)',
97
+ 'MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s)',
98
+ 'MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s)',
99
+ 'MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s)',
100
+ 'MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s)',
101
+ 'MT(bessely(a, sqrt(x))**2, x, s)',
102
+
103
+ 'MT(besselk(a, 2*sqrt(x)), x, s)',
104
+ 'MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk(a, 2*sqrt(2*sqrt(x))), x, s)',
105
+ 'MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s)',
106
+ 'MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s)',
107
+ 'MT(exp(-x/2)*besselk(a, x/2), x, s)',
108
+
109
+ # later: ILT, IMT
110
+
111
+ 'LT((t-apos)**bpos*exp(-cpos*(t-apos))*Heaviside(t-apos), t, s)',
112
+ 'LT(t**apos, t, s)',
113
+ 'LT(Heaviside(t), t, s)',
114
+ 'LT(Heaviside(t - apos), t, s)',
115
+ 'LT(1 - exp(-apos*t), t, s)',
116
+ 'LT((exp(2*t)-1)*exp(-bpos - t)*Heaviside(t)/2, t, s, noconds=True)',
117
+ 'LT(exp(t), t, s)',
118
+ 'LT(exp(2*t), t, s)',
119
+ 'LT(exp(apos*t), t, s)',
120
+ 'LT(log(t/apos), t, s)',
121
+ 'LT(erf(t), t, s)',
122
+ 'LT(sin(apos*t), t, s)',
123
+ 'LT(cos(apos*t), t, s)',
124
+ 'LT(exp(-apos*t)*sin(bpos*t), t, s)',
125
+ 'LT(exp(-apos*t)*cos(bpos*t), t, s)',
126
+ 'LT(besselj(0, t), t, s, noconds=True)',
127
+ 'LT(besselj(1, t), t, s, noconds=True)',
128
+
129
+ 'FT(Heaviside(1 - abs(2*apos*x)), x, k)',
130
+ 'FT(Heaviside(1-abs(apos*x))*(1-abs(apos*x)), x, k)',
131
+ 'FT(exp(-apos*x)*Heaviside(x), x, k)',
132
+ 'IFT(1/(apos + 2*pi*I*x), x, posk, noconds=False)',
133
+ 'IFT(1/(apos + 2*pi*I*x), x, -posk, noconds=False)',
134
+ 'IFT(1/(apos + 2*pi*I*x), x, negk)',
135
+ 'FT(x*exp(-apos*x)*Heaviside(x), x, k)',
136
+ 'FT(exp(-apos*x)*sin(bpos*x)*Heaviside(x), x, k)',
137
+ 'FT(exp(-apos*x**2), x, k)',
138
+ 'IFT(sqrt(pi/apos)*exp(-(pi*k)**2/apos), k, x)',
139
+ 'FT(exp(-apos*abs(x)), x, k)',
140
+
141
+ 'integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
142
+ 'integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
143
+ 'integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
144
+ 'integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
145
+ 'integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
146
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
147
+ 'integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
148
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
149
+ 'integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
150
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
151
+ 'integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
152
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
153
+ 'integrate((x+y+1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
154
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
155
+ 'integrate((x+y-1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
156
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
157
+ 'integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
158
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
159
+ 'integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
160
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
161
+ 'integrate(exponential(x, rate), (x, 0, oo), meijerg=True)',
162
+ 'integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True)',
163
+ 'integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True)',
164
+ 'E(1)',
165
+ 'E(x*y)',
166
+ 'E(x*y**2)',
167
+ 'E((x+y+1)**2)',
168
+ 'E(x+y+1)',
169
+ 'E((x+y-1)**2)',
170
+ 'integrate(betadist, (x, 0, oo), meijerg=True)',
171
+ 'integrate(x*betadist, (x, 0, oo), meijerg=True)',
172
+ 'integrate(x**2*betadist, (x, 0, oo), meijerg=True)',
173
+ 'integrate(chi, (x, 0, oo), meijerg=True)',
174
+ 'integrate(x*chi, (x, 0, oo), meijerg=True)',
175
+ 'integrate(x**2*chi, (x, 0, oo), meijerg=True)',
176
+ 'integrate(chisquared, (x, 0, oo), meijerg=True)',
177
+ 'integrate(x*chisquared, (x, 0, oo), meijerg=True)',
178
+ 'integrate(x**2*chisquared, (x, 0, oo), meijerg=True)',
179
+ 'integrate(((x-k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)',
180
+ 'integrate(dagum, (x, 0, oo), meijerg=True)',
181
+ 'integrate(x*dagum, (x, 0, oo), meijerg=True)',
182
+ 'integrate(x**2*dagum, (x, 0, oo), meijerg=True)',
183
+ 'integrate(f, (x, 0, oo), meijerg=True)',
184
+ 'integrate(x*f, (x, 0, oo), meijerg=True)',
185
+ 'integrate(x**2*f, (x, 0, oo), meijerg=True)',
186
+ 'integrate(rice, (x, 0, oo), meijerg=True)',
187
+ 'integrate(laplace, (x, -oo, oo), meijerg=True)',
188
+ 'integrate(x*laplace, (x, -oo, oo), meijerg=True)',
189
+ 'integrate(x**2*laplace, (x, -oo, oo), meijerg=True)',
190
+ 'integrate(log(x) * x**(k-1) * exp(-x) / gamma(k), (x, 0, oo))',
191
+
192
+ 'integrate(sin(z*x)*(x**2-1)**(-(y+S(1)/2)), (x, 1, oo), meijerg=True)',
193
+ 'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)',
194
+ 'integrate(besselj(0,x)*besselj(1,x)*besselk(0,x), (x, 0, oo), meijerg=True)',
195
+ 'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)',
196
+ 'integrate(besselj(a,x)*besselj(b,x)/x, (x,0,oo), meijerg=True)',
197
+
198
+ 'hyperexpand(meijerg((-s - a/2 + 1, -s + a/2 + 1), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), (a/2, -a/2), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), 1))',
199
+ "gammasimp(S('2**(2*s)*(-pi*gamma(-a + 1)*gamma(a + 1)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 3/2)*gamma(a + s + 1)/(a*(a + s)) - gamma(-a - 1/2)*gamma(-a + 1)*gamma(a + 1)*gamma(a + 3/2)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a + s + 1)*gamma(a - s + 1)/(a*(-a + s)))*gamma(-2*s + 1)*gamma(s + 1)/(pi*s*gamma(-a - 1/2)*gamma(a + 3/2)*gamma(-s + 1)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 1)*gamma(a - s + 3/2))'))",
200
+
201
+ 'mellin_transform(E1(x), x, s)',
202
+ 'inverse_mellin_transform(gamma(s)/s, s, x, (0, oo))',
203
+ 'mellin_transform(expint(a, x), x, s)',
204
+ 'mellin_transform(Si(x), x, s)',
205
+ 'inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2)/(2*s*gamma(-s/2 + 1)), s, x, (-1, 0))',
206
+ 'mellin_transform(Ci(sqrt(x)), x, s)',
207
+ 'inverse_mellin_transform(-4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S(1)/2)),s, u, (0, 1))',
208
+ 'laplace_transform(Ci(x), x, s)',
209
+ 'laplace_transform(expint(a, x), x, s)',
210
+ 'laplace_transform(expint(1, x), x, s)',
211
+ 'laplace_transform(expint(2, x), x, s)',
212
+ 'inverse_laplace_transform(-log(1 + s**2)/2/s, s, u)',
213
+ 'inverse_laplace_transform(log(s + 1)/s, s, x)',
214
+ 'inverse_laplace_transform((s - log(s + 1))/s**2, s, x)',
215
+ 'laplace_transform(Chi(x), x, s)',
216
+ 'laplace_transform(Shi(x), x, s)',
217
+
218
+ 'integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds="none")',
219
+ 'integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds="none")',
220
+ 'integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True,conds="none")',
221
+ 'integrate(-cos(x)/x, (x, tpos, oo), meijerg=True)',
222
+ 'integrate(-sin(x)/x, (x, tpos, oo), meijerg=True)',
223
+ 'integrate(sin(x)/x, (x, 0, z), meijerg=True)',
224
+ 'integrate(sinh(x)/x, (x, 0, z), meijerg=True)',
225
+ 'integrate(exp(-x)/x, x, meijerg=True)',
226
+ 'integrate(exp(-x)/x**2, x, meijerg=True)',
227
+ 'integrate(cos(u)/u, u, meijerg=True)',
228
+ 'integrate(cosh(u)/u, u, meijerg=True)',
229
+ 'integrate(expint(1, x), x, meijerg=True)',
230
+ 'integrate(expint(2, x), x, meijerg=True)',
231
+ 'integrate(Si(x), x, meijerg=True)',
232
+ 'integrate(Ci(u), u, meijerg=True)',
233
+ 'integrate(Shi(x), x, meijerg=True)',
234
+ 'integrate(Chi(u), u, meijerg=True)',
235
+ 'integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True)',
236
+ 'integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True)'
237
+ ]
238
+
239
+ from time import time
240
+ from sympy.core.cache import clear_cache
241
+ import sys
242
+
243
+ timings = []
244
+
245
+ if __name__ == '__main__':
246
+ for n, string in enumerate(bench):
247
+ clear_cache()
248
+ _t = time()
249
+ exec(string)
250
+ _t = time() - _t
251
+ timings += [(_t, string)]
252
+ sys.stdout.write('.')
253
+ sys.stdout.flush()
254
+ if n % (len(bench) // 10) == 0:
255
+ sys.stdout.write('%s' % (10*n // len(bench)))
256
+ print()
257
+
258
+ timings.sort(key=lambda x: -x[0])
259
+
260
+ for ti, string in timings:
261
+ print('%.2fs %s' % (ti, string))
shared/package-files/75/7523f6f7746da075be73a707f55468cd1afcd73c2a2f6e03062f7063fa2952ec/blob ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor _cast_Long(const at::Tensor & self, bool non_blocking=false);
20
+ } // namespace native
21
+ } // namespace at
shared/package-files/75/75240f0a25da63a2c532ae50653cce37807e98e2384f232cf1deabff30686c63/blob ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API logical_xor {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logical_xor")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_xor(Tensor self, Tensor other) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & other);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other);
26
+ };
27
+
28
+ struct TORCH_API logical_xor_ {
29
+ using schema = at::Tensor & (at::Tensor &, const at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logical_xor_")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_xor_(Tensor(a!) self, Tensor other) -> Tensor(a!)")
35
+ static at::Tensor & call(at::Tensor & self, const at::Tensor & other);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other);
37
+ };
38
+
39
+ struct TORCH_API logical_xor_out {
40
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logical_xor")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_xor.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)")
46
+ static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
47
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
48
+ };
49
+
50
+ }} // namespace at::_ops
shared/package-files/75/7524540714554e1f9d5ccacc47fa10dd9212bb64127e1499962934dcc8dbbb7d/blob ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ """
4
+ Classes Without Boilerplate
5
+ """
6
+
7
+ from functools import partial
8
+ from typing import Callable
9
+
10
+ from . import converters, exceptions, filters, setters, validators
11
+ from ._cmp import cmp_using
12
+ from ._config import get_run_validators, set_run_validators
13
+ from ._funcs import asdict, assoc, astuple, evolve, has, resolve_types
14
+ from ._make import (
15
+ NOTHING,
16
+ Attribute,
17
+ Factory,
18
+ attrib,
19
+ attrs,
20
+ fields,
21
+ fields_dict,
22
+ make_class,
23
+ validate,
24
+ )
25
+ from ._next_gen import define, field, frozen, mutable
26
+ from ._version_info import VersionInfo
27
+
28
+
29
+ s = attributes = attrs
30
+ ib = attr = attrib
31
+ dataclass = partial(attrs, auto_attribs=True) # happy Easter ;)
32
+
33
+
34
+ class AttrsInstance:
35
+ pass
36
+
37
+
38
+ __all__ = [
39
+ "Attribute",
40
+ "AttrsInstance",
41
+ "Factory",
42
+ "NOTHING",
43
+ "asdict",
44
+ "assoc",
45
+ "astuple",
46
+ "attr",
47
+ "attrib",
48
+ "attributes",
49
+ "attrs",
50
+ "cmp_using",
51
+ "converters",
52
+ "define",
53
+ "evolve",
54
+ "exceptions",
55
+ "field",
56
+ "fields",
57
+ "fields_dict",
58
+ "filters",
59
+ "frozen",
60
+ "get_run_validators",
61
+ "has",
62
+ "ib",
63
+ "make_class",
64
+ "mutable",
65
+ "resolve_types",
66
+ "s",
67
+ "set_run_validators",
68
+ "setters",
69
+ "validate",
70
+ "validators",
71
+ ]
72
+
73
+
74
+ def _make_getattr(mod_name: str) -> Callable:
75
+ """
76
+ Create a metadata proxy for packaging information that uses *mod_name* in
77
+ its warnings and errors.
78
+ """
79
+
80
+ def __getattr__(name: str) -> str:
81
+ dunder_to_metadata = {
82
+ "__title__": "Name",
83
+ "__copyright__": "",
84
+ "__version__": "version",
85
+ "__version_info__": "version",
86
+ "__description__": "summary",
87
+ "__uri__": "",
88
+ "__url__": "",
89
+ "__author__": "",
90
+ "__email__": "",
91
+ "__license__": "license",
92
+ }
93
+ if name not in dunder_to_metadata.keys():
94
+ raise AttributeError(f"module {mod_name} has no attribute {name}")
95
+
96
+ import sys
97
+ import warnings
98
+
99
+ if sys.version_info < (3, 8):
100
+ from importlib_metadata import metadata
101
+ else:
102
+ from importlib.metadata import metadata
103
+
104
+ if name != "__version_info__":
105
+ warnings.warn(
106
+ f"Accessing {mod_name}.{name} is deprecated and will be "
107
+ "removed in a future release. Use importlib.metadata directly "
108
+ "to query for attrs's packaging metadata.",
109
+ DeprecationWarning,
110
+ stacklevel=2,
111
+ )
112
+
113
+ meta = metadata("attrs")
114
+ if name == "__license__":
115
+ return "MIT"
116
+ elif name == "__copyright__":
117
+ return "Copyright (c) 2015 Hynek Schlawack"
118
+ elif name in ("__uri__", "__url__"):
119
+ return meta["Project-URL"].split(" ", 1)[-1]
120
+ elif name == "__version_info__":
121
+ return VersionInfo._from_version_string(meta["version"])
122
+ elif name == "__author__":
123
+ return meta["Author-email"].rsplit(" ", 1)[0]
124
+ elif name == "__email__":
125
+ return meta["Author-email"].rsplit("<", 1)[1][:-1]
126
+
127
+ return meta[dunder_to_metadata[name]]
128
+
129
+ return __getattr__
130
+
131
+
132
+ __getattr__ = _make_getattr(__name__)
shared/package-files/75/752560d1d1de753f70d503b617502f5a87a5e3f87cc26b984b882e11a2fee4a9/blob ADDED
Binary file (502 Bytes). View file
 
shared/package-files/75/752571886a9d351ea06c5e34578276b46850f93e110ef4b21b2a47bd870f0d83/blob ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from sympy.core.relational import Eq
4
+ from sympy.core.symbol import Symbol
5
+ from sympy.functions.elementary.piecewise import Piecewise
6
+ from sympy.printing.preview import preview
7
+
8
+ from io import BytesIO
9
+
10
+
11
+ def test_preview():
12
+ x = Symbol('x')
13
+ obj = BytesIO()
14
+ try:
15
+ preview(x, output='png', viewer='BytesIO', outputbuffer=obj)
16
+ except RuntimeError:
17
+ pass # latex not installed on CI server
18
+
19
+
20
+ def test_preview_unicode_symbol():
21
+ # issue 9107
22
+ a = Symbol('α')
23
+ obj = BytesIO()
24
+ try:
25
+ preview(a, output='png', viewer='BytesIO', outputbuffer=obj)
26
+ except RuntimeError:
27
+ pass # latex not installed on CI server
28
+
29
+
30
+ def test_preview_latex_construct_in_expr():
31
+ # see PR 9801
32
+ x = Symbol('x')
33
+ pw = Piecewise((1, Eq(x, 0)), (0, True))
34
+ obj = BytesIO()
35
+ try:
36
+ preview(pw, output='png', viewer='BytesIO', outputbuffer=obj)
37
+ except RuntimeError:
38
+ pass # latex not installed on CI server
shared/package-files/75/75292a923cfe979435cef921f0a15ecc2ff9cd1cf0f0137544e28f8d8f78acdc/blob ADDED
The diff for this file is too large to render. See raw diff
 
shared/package-files/75/7529f3512586bcbd947268aa68f79cf9d6d344c2063d4ed38fbfafa859751314/blob ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ import torch.ao.nn.intrinsic
4
+ import torch.ao.nn.intrinsic.qat
5
+ import torch.ao.nn.quantized as nnq
6
+
7
+ __all__ = [
8
+ "BNReLU2d",
9
+ "BNReLU3d"
10
+ ]
11
+
12
+ class BNReLU2d(nnq.BatchNorm2d):
13
+ r"""
14
+ A BNReLU2d module is a fused module of BatchNorm2d and ReLU
15
+
16
+ We adopt the same interface as :class:`torch.ao.nn.quantized.BatchNorm2d`.
17
+
18
+ Attributes:
19
+ Same as torch.ao.nn.quantized.BatchNorm2d
20
+
21
+ """
22
+ _FLOAT_MODULE = torch.ao.nn.intrinsic.BNReLU2d
23
+
24
+ def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None):
25
+ super().__init__(num_features, eps=eps, momentum=momentum, device=device, dtype=dtype)
26
+
27
+ def forward(self, input):
28
+ # Temporarily using len(shape) instead of ndim due to JIT issue
29
+ # https://github.com/pytorch/pytorch/issues/23890
30
+ if len(input.shape) != 4:
31
+ raise ValueError("Input shape must be `(N, C, H, W)`!")
32
+ return torch.ops.quantized.batch_norm2d_relu(
33
+ input, self.weight, self.bias, self.running_mean,
34
+ self.running_var, self.eps, self.scale, self.zero_point)
35
+
36
+ def _get_name(self):
37
+ return 'QuantizedBNReLU2d'
38
+
39
+ @classmethod
40
+ def from_float(cls, mod):
41
+ # TODO: Add qat support for BNReLU2d
42
+ return super().from_float(mod)
43
+
44
+ @classmethod
45
+ def from_reference(cls, bn_relu, output_scale, output_zero_point):
46
+ return super().from_reference(bn_relu[0], output_scale, output_zero_point)
47
+
48
+ class BNReLU3d(nnq.BatchNorm3d):
49
+ r"""
50
+ A BNReLU3d module is a fused module of BatchNorm3d and ReLU
51
+
52
+ We adopt the same interface as :class:`torch.ao.nn.quantized.BatchNorm3d`.
53
+
54
+ Attributes:
55
+ Same as torch.ao.nn.quantized.BatchNorm3d
56
+
57
+ """
58
+ _FLOAT_MODULE = torch.ao.nn.intrinsic.BNReLU3d
59
+
60
+ def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None):
61
+ super().__init__(num_features, eps=eps, momentum=momentum, device=device, dtype=dtype)
62
+
63
+ def forward(self, input):
64
+ # Temporarily using len(shape) instead of ndim due to JIT issue
65
+ # https://github.com/pytorch/pytorch/issues/23890
66
+ if len(input.shape) != 5:
67
+ raise ValueError("Input shape must be `(N, C, D, H, W)`!")
68
+ return torch.ops.quantized.batch_norm3d_relu(
69
+ input, self.weight, self.bias, self.running_mean,
70
+ self.running_var, self.eps, self.scale, self.zero_point)
71
+
72
+ def _get_name(self):
73
+ return 'QuantizedBNReLU3d'
74
+
75
+ @classmethod
76
+ def from_float(cls, mod):
77
+ # TODO: Add qat support for BNReLU3d
78
+ return super().from_float(mod)
79
+
80
+ @classmethod
81
+ def from_reference(cls, bn_relu, output_scale, output_zero_point):
82
+ return super().from_reference(bn_relu[0], output_scale, output_zero_point)
shared/package-files/75/752ad8827ddb5678e68114cca31f7830a5881b91aeaf8dce47113f2be51df840/blob 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 cuda {
19
+
20
+ TORCH_API at::Tensor miopen_convolution_relu(const at::Tensor & self, const at::Tensor & weight, const c10::optional<at::Tensor> & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups);
21
+ TORCH_API at::Tensor miopen_convolution_relu_symint(const at::Tensor & self, const at::Tensor & weight, const c10::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups);
22
+
23
+ } // namespace cuda
24
+ } // namespace at
shared/package-files/75/7531be245e6cf3693e2ebb502ccc7558d65e7f756b6466bfb016ef4d2027938f/blob ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _values_copy {
18
+ using schema = at::Tensor (const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_values_copy")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_values_copy(Tensor self) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
26
+ };
27
+
28
+ struct TORCH_API _values_copy_out {
29
+ using schema = at::Tensor & (const at::Tensor &, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_values_copy")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_values_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & self, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops