Publish 11 evaluated Astra histories with reproducible checkpoint artifacts (part 17)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +19 -0
- shared/package-files/31/31c4764f0f8f37496ced933d462379f544a8c499c3d8822c7c6642cb3c33ac22/blob +25 -0
- shared/package-files/31/31c4850d453892009abd4d6edfebaa04697351988b1b1339a8f7c11603d3a9d1/blob +22 -0
- shared/package-files/31/31d1e0b9b3bb131716829f12f823fd07851f27f6912e02dab74cb3d295d011d8/blob +434 -0
- shared/package-files/31/31d3fcccd95241e794ee9b0e5f0194750d7ef172b360297998a30872930288df/blob +643 -0
- shared/package-files/31/31d72adad79910126b22a5579ec9e179eee86674ecebe3fcff6f76916193af0e/blob +342 -0
- shared/package-files/31/31d7376ec16989846d88c976c3e615f3b4e26178b65f009901ac786a713bc170/blob +0 -0
- shared/package-files/31/31d8f1a50dbaf2ecc9ed9c7566ba0552d454c2ab09e85ff263701857d157c352/blob +0 -0
- shared/package-files/31/31dda61e64849ebf334f5965cf81ea18bf3e7ac057f316cf84a3a50022d503d2/blob +1575 -0
- shared/package-files/31/31ddedd22e89ab666068c076cb95a18d5c62e82350fc7173a0d4e87c01ebb1cc/blob +47 -0
- shared/package-files/31/31e1e3cf08b04fc4f64182d1123bd4a38ad46e9b757f1f4bd40ed7bc8adcbea1/blob +0 -0
- shared/package-files/31/31e3a1164bfdd402e278a26d187aa487180eeca241cf9de607cb51718097df19/blob +158 -0
- shared/package-files/31/31e6182e61583cd1b8d31359b26ecead2dba2ae003a7714c16afc1795bdbeceb/blob +1400 -0
- shared/package-files/31/31e7e018f6c9649bce8616fcd3284843c23c853b4b56c4b152cf561c29c5fd1b/blob +0 -0
- shared/package-files/31/31e99ec2d7580af332a37c64d2d373457f17f593627bf7c41368a96afde2e74f/blob +0 -0
- shared/package-files/31/31ea913829659f4a9cf5bcbe83458d7c0c765a518c6d9b6808e5a2b10da79019/blob +335 -0
- shared/package-files/31/31eb31c6083704bc6178b671f9d49fdf46fa80aa4e81d557c3a5befae1d2b334/blob +88 -0
- shared/package-files/31/31f0728acd86ea4539fb2e058e18514d00f90d068fe4e385adcf9c882f4988a1/blob +139 -0
- shared/package-files/31/31f09bc8966ed57b0224e092c3abef86ce1e88fe0b64f705f9ef61b8f996fb2b/blob +101 -0
- shared/package-files/31/31f16bfef90158d13d4fc249e83459165a1edab89273841343d613b0571729c2/blob +21 -0
- shared/package-files/31/31f6496511a73ae245863ac284927466508fa6c2b64a9aab69f57b5649c0afc0/blob +164 -0
- shared/package-files/31/31f721de5fe36cae5740d7da2e15e9e8e72fa391d42a118db10cc771f2cf1b0d/blob +26 -0
- shared/package-files/31/31f7e08f7c79b45c2c2968a1c3691b8529a1bc634481073fa498ba0b79844317/blob +407 -0
- shared/package-files/31/31fe7b070a21467f727ba8b126a8cd1272b480aaa754f13d1b2f2f2beebfcf1a/blob +338 -0
- shared/package-files/32/32027eb7f7fb836922cdcad667f12b725c791e049ac7d269bda12429a39e9d48/blob +13 -0
- shared/package-files/32/3204305af3d1b1a4fa532c1b68e8ec5d331c02add9f6d6a1772f39ff0ee47c16/blob +4 -0
- shared/package-files/32/3208279bebd7d83b14c1360f25f93cd40048e904280d52b3b8549b05f0e3ae71/blob +63 -0
- shared/package-files/32/3209ff37311d53ba8ccea59c7e6c7fe0579a3eb10c185ff6b115b15e859aa149/blob +0 -0
- shared/package-files/32/320b3d7ae0eb563e60d7a62387de282960b1ab1a94b376935691bb8cc4967ed0/blob +1194 -0
- shared/package-files/32/320cceeab3e51f6f4515bee7920fbb652418523bd0f769be82a892f9bab9676c/blob +33 -0
- shared/package-files/32/320de8e22b5d74767e87fabe35eacbdff562c3ae498f6fcec9628f7fc895e0e9/blob +493 -0
- shared/package-files/32/320e1d8e583d6c7c1f5a26bb913b1315d62a8ec594ca23ff52b9a517218214c9/blob +30 -0
- shared/package-files/32/320f996f1f43e0a3bf44729c901672b9a07966798be64ff26f0f953aff41021a/blob +23 -0
- shared/package-files/32/32108975cdae6500033fd995ff28642facdcfabeb25e22f82894d3f488d0c868/blob +39 -0
- shared/package-files/32/3211959beba2d9a5e95409567047d8ff854d4f9e77d8e623d030a34943ac516e/blob +3 -0
- shared/package-files/32/321245e3a66997b61f2214325015e61b9a64398230c37092ae487220afc52f9f/blob +136 -0
- shared/package-files/32/3212543684feef77fea9442b687e6b7f67d93e5144135aa44fd5f0180e4c0591/blob +91 -0
- shared/package-files/32/3212bc4d893d7ebbc7cddea573d04eb8b5a6d7319c5658bf1154d70c5f28a16e/blob +0 -0
- shared/package-files/32/321333b3eaad9ecbf633186bc625d4a60c4c736def0fa00665add2ab899eecb1/blob +294 -0
- shared/package-files/32/32142548019430c5f8baba4dab0f88e8d2b663c846343045d375f7749dce490b/blob +0 -0
- shared/package-files/32/3216fd20e5c0bf873a9e4936e10438cd135dbfc15c60a373707cc7d98e35312f/blob +39 -0
- shared/package-files/32/32183bd6f9e38dbe1f9b48d98230e8596f2b0093017a1f1a0c233be608c4a4a4/blob +228 -0
- shared/package-files/32/32191fb149da315122ea846b71f4e0a7a875ff54024bc6efc6dc2813a6ea652e/blob +22 -0
- shared/package-files/32/3219b2a5be56cf119d05a429c9269ef4d6e21499659047b3762b631da8dded10/blob +87 -0
- shared/package-files/32/321f0293b95d07de6fd2df7c9da5fee13bd9bbb8ae47241731c526ba427c1e2f/blob +3 -0
- shared/package-files/32/3221d56abebe6de504615129a97391217e1ff06dbd238ec3dfa92b7a5b5d7e84/blob +33 -0
- shared/package-files/32/32258d53e28c9d2c075b977388a296199f18363315d016297765aac4f57cec8f/blob +30 -0
- shared/package-files/32/322745165c7c739c69422e50ecd36bf6e1b991115dc19348c6dec887aba48817/blob +28 -0
- shared/package-files/32/3227f4f6071f45f20edae842a8d37d382fcd5e080a8b36eec1acfa49c1b33141/blob +125 -0
- shared/package-files/32/322a98cc2207bcd6cc1fe2dd4582effb84f410803b8432ade462d1d084532dd2/blob +75 -0
.gitattributes
CHANGED
|
@@ -271,3 +271,22 @@ shared/package-files/30/30e2c5853b7762551f32be245e79fd9d06e52a7cfdfd9c31bfece834
|
|
| 271 |
shared/package-files/31/3196378de7c8f842481203abc471a1e1b5f231b4c1da26fd6812cc90df38e012/blob filter=lfs diff=lfs merge=lfs -text
|
| 272 |
shared/package-files/31/31977145330b3a430a9088dcab494e4598947e5084b79e19958f694840c249e6/blob filter=lfs diff=lfs merge=lfs -text
|
| 273 |
shared/package-files/31/31b8c3d177e2f59d9cff0198d08c057aafd81f9098b9ad34eae9d7a4a7b10120/blob filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
shared/package-files/31/3196378de7c8f842481203abc471a1e1b5f231b4c1da26fd6812cc90df38e012/blob filter=lfs diff=lfs merge=lfs -text
|
| 272 |
shared/package-files/31/31977145330b3a430a9088dcab494e4598947e5084b79e19958f694840c249e6/blob filter=lfs diff=lfs merge=lfs -text
|
| 273 |
shared/package-files/31/31b8c3d177e2f59d9cff0198d08c057aafd81f9098b9ad34eae9d7a4a7b10120/blob filter=lfs diff=lfs merge=lfs -text
|
| 274 |
+
shared/package-files/32/3211959beba2d9a5e95409567047d8ff854d4f9e77d8e623d030a34943ac516e/blob filter=lfs diff=lfs merge=lfs -text
|
| 275 |
+
shared/package-files/32/321f0293b95d07de6fd2df7c9da5fee13bd9bbb8ae47241731c526ba427c1e2f/blob filter=lfs diff=lfs merge=lfs -text
|
| 276 |
+
shared/package-files/32/324cceb2911a13bad228b62b2793776ce4300df1ec710cd805611eceaf81ba62/blob filter=lfs diff=lfs merge=lfs -text
|
| 277 |
+
shared/package-files/32/3269b056aff788416a4cddb0c57e2d6a2a34b8df4616a35447eab204eb9c9bc3/blob filter=lfs diff=lfs merge=lfs -text
|
| 278 |
+
shared/package-files/32/326f7950937ae1bdd50169bf8a604bde6c2e1a758b32d015a4dc5996eac1e9e2/blob filter=lfs diff=lfs merge=lfs -text
|
| 279 |
+
shared/package-files/32/3270fc5dca024bd4ca78976d961dff9407e839dcbb5ba317488005aa1a93b536/blob filter=lfs diff=lfs merge=lfs -text
|
| 280 |
+
shared/package-files/32/328316a05d5defc85baed3f1d18a527c088052a6c6f362585079d151f9f3f0bf/blob filter=lfs diff=lfs merge=lfs -text
|
| 281 |
+
shared/package-files/32/329f191d3dd5e6ed6bc66411d23bd13f8e2f2d5bc9d98a7f5aa77aaf74249ab0/blob filter=lfs diff=lfs merge=lfs -text
|
| 282 |
+
shared/package-files/32/32e7cfd5f4833a6be03bad36850b5796ec579fc31fe7ecd1aa8eb14f54115923/blob filter=lfs diff=lfs merge=lfs -text
|
| 283 |
+
shared/package-files/33/330bff9279f9946aa1f8182ee01c15e4c597b1df891a3b275190476e62de1951/blob filter=lfs diff=lfs merge=lfs -text
|
| 284 |
+
shared/package-files/33/332a9f4d6e7755c6d1ccec4271e9030f60ac334ae014fddfb6a7c54c3d46373d/blob filter=lfs diff=lfs merge=lfs -text
|
| 285 |
+
shared/package-files/33/335d55a6d02ea00f200aaa54dad20546a1b88c5d8b2f599a2b0a5ffd7e920314/blob filter=lfs diff=lfs merge=lfs -text
|
| 286 |
+
shared/package-files/33/336152fee45ad772ba030b300474de581db48777c2c0857c72ce230c5a91a45b/blob filter=lfs diff=lfs merge=lfs -text
|
| 287 |
+
shared/package-files/33/33ba4d691a4e44278747073f1eb3e3540c6a24bf31c857ba1ecec3092987f1ef/blob filter=lfs diff=lfs merge=lfs -text
|
| 288 |
+
shared/package-files/33/33d569c599044397f4ee75e13b3c373cb452fb876e8f7e8bf8ec4485d537bf47/blob filter=lfs diff=lfs merge=lfs -text
|
| 289 |
+
shared/package-files/34/34048a84478aee7a9955cbe83bfff8581662b1119da716f1a3c9ddfca78eba6f/blob filter=lfs diff=lfs merge=lfs -text
|
| 290 |
+
shared/package-files/34/342b2c16a3e7682eb34e6655dec0bc6b086c3d4c9b6b21f52ccf3a91ad82f734/blob filter=lfs diff=lfs merge=lfs -text
|
| 291 |
+
shared/package-files/34/3434fdb0ee99663ee112a8bfd7f9378eb1c3d36e6f75519e4378b446e77d38c9/blob filter=lfs diff=lfs merge=lfs -text
|
| 292 |
+
shared/package-files/34/347c4ca3bb09091c12653f0d4a4796363333def1ffb7650a503222ffb4f7c522/blob filter=lfs diff=lfs merge=lfs -text
|
shared/package-files/31/31c4764f0f8f37496ced933d462379f544a8c499c3d8822c7c6642cb3c33ac22/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_entr(const at::Tensor & self);
|
| 21 |
+
TORCH_API at::Tensor & special_entr_out(at::Tensor & out, const at::Tensor & self);
|
| 22 |
+
TORCH_API at::Tensor & special_entr_outf(const at::Tensor & self, at::Tensor & out);
|
| 23 |
+
|
| 24 |
+
} // namespace cpu
|
| 25 |
+
} // namespace at
|
shared/package-files/31/31c4850d453892009abd4d6edfebaa04697351988b1b1339a8f7c11603d3a9d1/blob
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numpy.testing import assert_allclose
|
| 2 |
+
from scipy.linalg import cython_lapack as cython_lapack
|
| 3 |
+
from scipy.linalg import lapack
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestLamch:
|
| 7 |
+
|
| 8 |
+
def test_slamch(self):
|
| 9 |
+
for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']:
|
| 10 |
+
assert_allclose(cython_lapack._test_slamch(c),
|
| 11 |
+
lapack.slamch(c))
|
| 12 |
+
|
| 13 |
+
def test_dlamch(self):
|
| 14 |
+
for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']:
|
| 15 |
+
assert_allclose(cython_lapack._test_dlamch(c),
|
| 16 |
+
lapack.dlamch(c))
|
| 17 |
+
|
| 18 |
+
def test_complex_ladiv(self):
|
| 19 |
+
cx = .5 + 1.j
|
| 20 |
+
cy = .875 + 2.j
|
| 21 |
+
assert_allclose(cython_lapack._test_zladiv(cy, cx), 1.95+0.1j)
|
| 22 |
+
assert_allclose(cython_lapack._test_cladiv(cy, cx), 1.95+0.1j)
|
shared/package-files/31/31d1e0b9b3bb131716829f12f823fd07851f27f6912e02dab74cb3d295d011d8/blob
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
/// \brief Implementation of Flight RPC client.
|
| 19 |
+
|
| 20 |
+
#pragma once
|
| 21 |
+
|
| 22 |
+
#include <chrono>
|
| 23 |
+
#include <memory>
|
| 24 |
+
#include <string>
|
| 25 |
+
#include <utility>
|
| 26 |
+
#include <variant>
|
| 27 |
+
#include <vector>
|
| 28 |
+
|
| 29 |
+
#include "arrow/ipc/options.h"
|
| 30 |
+
#include "arrow/ipc/reader.h"
|
| 31 |
+
#include "arrow/ipc/writer.h"
|
| 32 |
+
#include "arrow/result.h"
|
| 33 |
+
#include "arrow/status.h"
|
| 34 |
+
#include "arrow/util/cancel.h"
|
| 35 |
+
|
| 36 |
+
#include "arrow/flight/type_fwd.h"
|
| 37 |
+
#include "arrow/flight/types.h" // IWYU pragma: keep
|
| 38 |
+
#include "arrow/flight/visibility.h"
|
| 39 |
+
|
| 40 |
+
namespace arrow {
|
| 41 |
+
|
| 42 |
+
class RecordBatch;
|
| 43 |
+
class Schema;
|
| 44 |
+
|
| 45 |
+
namespace flight {
|
| 46 |
+
|
| 47 |
+
/// \brief A duration type for Flight call timeouts.
|
| 48 |
+
typedef std::chrono::duration<double, std::chrono::seconds::period> TimeoutDuration;
|
| 49 |
+
|
| 50 |
+
/// \brief Hints to the underlying RPC layer for Arrow Flight calls.
|
| 51 |
+
class ARROW_FLIGHT_EXPORT FlightCallOptions {
|
| 52 |
+
public:
|
| 53 |
+
/// Create a default set of call options.
|
| 54 |
+
FlightCallOptions();
|
| 55 |
+
|
| 56 |
+
/// \brief An optional timeout for this call. Negative durations
|
| 57 |
+
/// mean an implementation-defined default behavior will be used
|
| 58 |
+
/// instead. This is the default value.
|
| 59 |
+
TimeoutDuration timeout;
|
| 60 |
+
|
| 61 |
+
/// \brief IPC reader options, if applicable for the call.
|
| 62 |
+
ipc::IpcReadOptions read_options;
|
| 63 |
+
|
| 64 |
+
/// \brief IPC writer options, if applicable for the call.
|
| 65 |
+
ipc::IpcWriteOptions write_options;
|
| 66 |
+
|
| 67 |
+
/// \brief Headers for client to add to context.
|
| 68 |
+
std::vector<std::pair<std::string, std::string>> headers;
|
| 69 |
+
|
| 70 |
+
/// \brief A token to enable interactive user cancellation of long-running requests.
|
| 71 |
+
StopToken stop_token;
|
| 72 |
+
|
| 73 |
+
/// \brief An optional memory manager to control where to allocate incoming data.
|
| 74 |
+
std::shared_ptr<MemoryManager> memory_manager;
|
| 75 |
+
};
|
| 76 |
+
|
| 77 |
+
/// \brief Indicate that the client attempted to write a message
|
| 78 |
+
/// larger than the soft limit set via write_size_limit_bytes.
|
| 79 |
+
class ARROW_FLIGHT_EXPORT FlightWriteSizeStatusDetail : public arrow::StatusDetail {
|
| 80 |
+
public:
|
| 81 |
+
explicit FlightWriteSizeStatusDetail(int64_t limit, int64_t actual)
|
| 82 |
+
: limit_(limit), actual_(actual) {}
|
| 83 |
+
const char* type_id() const override;
|
| 84 |
+
std::string ToString() const override;
|
| 85 |
+
int64_t limit() const { return limit_; }
|
| 86 |
+
int64_t actual() const { return actual_; }
|
| 87 |
+
|
| 88 |
+
/// \brief Extract this status detail from a status, or return
|
| 89 |
+
/// nullptr if the status doesn't contain this status detail.
|
| 90 |
+
static std::shared_ptr<FlightWriteSizeStatusDetail> UnwrapStatus(
|
| 91 |
+
const arrow::Status& status);
|
| 92 |
+
|
| 93 |
+
private:
|
| 94 |
+
int64_t limit_;
|
| 95 |
+
int64_t actual_;
|
| 96 |
+
};
|
| 97 |
+
|
| 98 |
+
struct ARROW_FLIGHT_EXPORT FlightClientOptions {
|
| 99 |
+
/// \brief Root certificates to use for validating server
|
| 100 |
+
/// certificates.
|
| 101 |
+
std::string tls_root_certs;
|
| 102 |
+
/// \brief Override the hostname checked by TLS. Use with caution.
|
| 103 |
+
std::string override_hostname;
|
| 104 |
+
/// \brief The client certificate to use if using Mutual TLS
|
| 105 |
+
std::string cert_chain;
|
| 106 |
+
/// \brief The private key associated with the client certificate for Mutual TLS
|
| 107 |
+
std::string private_key;
|
| 108 |
+
/// \brief A list of client middleware to apply.
|
| 109 |
+
std::vector<std::shared_ptr<ClientMiddlewareFactory>> middleware;
|
| 110 |
+
/// \brief A soft limit on the number of bytes to write in a single
|
| 111 |
+
/// batch when sending Arrow data to a server.
|
| 112 |
+
///
|
| 113 |
+
/// Used to help limit server memory consumption. Only enabled if
|
| 114 |
+
/// positive. When enabled, FlightStreamWriter.Write* may yield a
|
| 115 |
+
/// IOError with error detail FlightWriteSizeStatusDetail.
|
| 116 |
+
int64_t write_size_limit_bytes = 0;
|
| 117 |
+
|
| 118 |
+
/// \brief Generic connection options, passed to the underlying
|
| 119 |
+
/// transport; interpretation is implementation-dependent.
|
| 120 |
+
std::vector<std::pair<std::string, std::variant<int, std::string>>> generic_options;
|
| 121 |
+
|
| 122 |
+
/// \brief Use TLS without validating the server certificate. Use with caution.
|
| 123 |
+
bool disable_server_verification = false;
|
| 124 |
+
|
| 125 |
+
/// \brief Get default options.
|
| 126 |
+
static FlightClientOptions Defaults();
|
| 127 |
+
};
|
| 128 |
+
|
| 129 |
+
/// \brief A RecordBatchReader exposing Flight metadata and cancel
|
| 130 |
+
/// operations.
|
| 131 |
+
class ARROW_FLIGHT_EXPORT FlightStreamReader : public MetadataRecordBatchReader {
|
| 132 |
+
public:
|
| 133 |
+
/// \brief Try to cancel the call.
|
| 134 |
+
virtual void Cancel() = 0;
|
| 135 |
+
|
| 136 |
+
using MetadataRecordBatchReader::ToRecordBatches;
|
| 137 |
+
/// \brief Consume entire stream as a vector of record batches
|
| 138 |
+
virtual arrow::Result<std::vector<std::shared_ptr<RecordBatch>>> ToRecordBatches(
|
| 139 |
+
const StopToken& stop_token) = 0;
|
| 140 |
+
|
| 141 |
+
using MetadataRecordBatchReader::ToTable;
|
| 142 |
+
/// \brief Consume entire stream as a Table
|
| 143 |
+
arrow::Result<std::shared_ptr<Table>> ToTable(const StopToken& stop_token);
|
| 144 |
+
|
| 145 |
+
using MetadataRecordBatchReader::stats;
|
| 146 |
+
/// \brief Return current read statistics
|
| 147 |
+
virtual arrow::ipc::ReadStats stats() const = 0;
|
| 148 |
+
};
|
| 149 |
+
|
| 150 |
+
// Silence warning
|
| 151 |
+
// "non dll-interface class RecordBatchReader used as base for dll-interface class"
|
| 152 |
+
#ifdef _MSC_VER
|
| 153 |
+
# pragma warning(push)
|
| 154 |
+
# pragma warning(disable : 4275)
|
| 155 |
+
#endif
|
| 156 |
+
|
| 157 |
+
/// \brief A RecordBatchWriter that also allows sending
|
| 158 |
+
/// application-defined metadata via the Flight protocol.
|
| 159 |
+
class ARROW_FLIGHT_EXPORT FlightStreamWriter : public MetadataRecordBatchWriter {
|
| 160 |
+
public:
|
| 161 |
+
/// \brief Indicate that the application is done writing to this stream.
|
| 162 |
+
///
|
| 163 |
+
/// The application may not write to this stream after calling
|
| 164 |
+
/// this. This differs from closing the stream because this writer
|
| 165 |
+
/// may represent only one half of a readable and writable stream.
|
| 166 |
+
virtual Status DoneWriting() = 0;
|
| 167 |
+
};
|
| 168 |
+
|
| 169 |
+
#ifdef _MSC_VER
|
| 170 |
+
# pragma warning(pop)
|
| 171 |
+
#endif
|
| 172 |
+
|
| 173 |
+
/// \brief A reader for application-specific metadata sent back to the
|
| 174 |
+
/// client during an upload.
|
| 175 |
+
class ARROW_FLIGHT_EXPORT FlightMetadataReader {
|
| 176 |
+
public:
|
| 177 |
+
virtual ~FlightMetadataReader();
|
| 178 |
+
/// \brief Read a message from the server.
|
| 179 |
+
virtual Status ReadMetadata(std::shared_ptr<Buffer>* out) = 0;
|
| 180 |
+
};
|
| 181 |
+
|
| 182 |
+
/// \brief Client class for Arrow Flight RPC services.
|
| 183 |
+
class ARROW_FLIGHT_EXPORT FlightClient {
|
| 184 |
+
public:
|
| 185 |
+
~FlightClient();
|
| 186 |
+
|
| 187 |
+
/// \brief Connect to an unauthenticated flight service
|
| 188 |
+
/// \param[in] location the URI
|
| 189 |
+
/// \return Arrow result with the created FlightClient, OK status may not indicate that
|
| 190 |
+
/// the connection was successful
|
| 191 |
+
static arrow::Result<std::unique_ptr<FlightClient>> Connect(const Location& location);
|
| 192 |
+
|
| 193 |
+
/// \brief Connect to an unauthenticated flight service
|
| 194 |
+
/// \param[in] location the URI
|
| 195 |
+
/// \param[in] options Other options for setting up the client
|
| 196 |
+
/// \return Arrow result with the created FlightClient, OK status may not indicate that
|
| 197 |
+
/// the connection was successful
|
| 198 |
+
static arrow::Result<std::unique_ptr<FlightClient>> Connect(
|
| 199 |
+
const Location& location, const FlightClientOptions& options);
|
| 200 |
+
|
| 201 |
+
/// \brief Authenticate to the server using the given handler.
|
| 202 |
+
/// \param[in] options Per-RPC options
|
| 203 |
+
/// \param[in] auth_handler The authentication mechanism to use
|
| 204 |
+
/// \return Status OK if the client authenticated successfully
|
| 205 |
+
Status Authenticate(const FlightCallOptions& options,
|
| 206 |
+
std::unique_ptr<ClientAuthHandler> auth_handler);
|
| 207 |
+
|
| 208 |
+
/// \brief Authenticate to the server using basic HTTP style authentication.
|
| 209 |
+
/// \param[in] options Per-RPC options
|
| 210 |
+
/// \param[in] username Username to use
|
| 211 |
+
/// \param[in] password Password to use
|
| 212 |
+
/// \return Arrow result with bearer token and status OK if client authenticated
|
| 213 |
+
/// successfully
|
| 214 |
+
arrow::Result<std::pair<std::string, std::string>> AuthenticateBasicToken(
|
| 215 |
+
const FlightCallOptions& options, const std::string& username,
|
| 216 |
+
const std::string& password);
|
| 217 |
+
|
| 218 |
+
/// \brief Perform the indicated action, returning an iterator to the stream
|
| 219 |
+
/// of results, if any
|
| 220 |
+
/// \param[in] options Per-RPC options
|
| 221 |
+
/// \param[in] action the action to be performed
|
| 222 |
+
/// \return Arrow result with an iterator object for reading the returned results
|
| 223 |
+
arrow::Result<std::unique_ptr<ResultStream>> DoAction(const FlightCallOptions& options,
|
| 224 |
+
const Action& action);
|
| 225 |
+
arrow::Result<std::unique_ptr<ResultStream>> DoAction(const Action& action) {
|
| 226 |
+
return DoAction({}, action);
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
/// \brief Perform the CancelFlightInfo action, returning a
|
| 230 |
+
/// CancelFlightInfoResult
|
| 231 |
+
///
|
| 232 |
+
/// \param[in] options Per-RPC options
|
| 233 |
+
/// \param[in] request The CancelFlightInfoRequest
|
| 234 |
+
/// \return Arrow result with a CancelFlightInfoResult
|
| 235 |
+
arrow::Result<CancelFlightInfoResult> CancelFlightInfo(
|
| 236 |
+
const FlightCallOptions& options, const CancelFlightInfoRequest& request);
|
| 237 |
+
arrow::Result<CancelFlightInfoResult> CancelFlightInfo(
|
| 238 |
+
const CancelFlightInfoRequest& request) {
|
| 239 |
+
return CancelFlightInfo({}, request);
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
/// \brief Perform the RenewFlightEndpoint action, returning a renewed
|
| 243 |
+
/// FlightEndpoint
|
| 244 |
+
///
|
| 245 |
+
/// \param[in] options Per-RPC options
|
| 246 |
+
/// \param[in] request The RenewFlightEndpointRequest
|
| 247 |
+
/// \return Arrow result with a renewed FlightEndpoint
|
| 248 |
+
arrow::Result<FlightEndpoint> RenewFlightEndpoint(
|
| 249 |
+
const FlightCallOptions& options, const RenewFlightEndpointRequest& request);
|
| 250 |
+
arrow::Result<FlightEndpoint> RenewFlightEndpoint(
|
| 251 |
+
const RenewFlightEndpointRequest& request) {
|
| 252 |
+
return RenewFlightEndpoint({}, request);
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
/// \brief Retrieve a list of available Action types
|
| 256 |
+
/// \param[in] options Per-RPC options
|
| 257 |
+
/// \return Arrow result with the available actions
|
| 258 |
+
arrow::Result<std::vector<ActionType>> ListActions(const FlightCallOptions& options);
|
| 259 |
+
arrow::Result<std::vector<ActionType>> ListActions() {
|
| 260 |
+
return ListActions(FlightCallOptions());
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
/// \brief Request access plan for a single flight, which may be an existing
|
| 264 |
+
/// dataset or a command to be executed
|
| 265 |
+
/// \param[in] options Per-RPC options
|
| 266 |
+
/// \param[in] descriptor the dataset request, whether a named dataset or
|
| 267 |
+
/// command
|
| 268 |
+
/// \return Arrow result with the FlightInfo describing where to access the dataset
|
| 269 |
+
arrow::Result<std::unique_ptr<FlightInfo>> GetFlightInfo(
|
| 270 |
+
const FlightCallOptions& options, const FlightDescriptor& descriptor);
|
| 271 |
+
arrow::Result<std::unique_ptr<FlightInfo>> GetFlightInfo(
|
| 272 |
+
const FlightDescriptor& descriptor) {
|
| 273 |
+
return GetFlightInfo({}, descriptor);
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
/// \brief Asynchronous GetFlightInfo.
|
| 277 |
+
/// \param[in] options Per-RPC options
|
| 278 |
+
/// \param[in] descriptor the dataset request
|
| 279 |
+
/// \param[in] listener Callbacks for response and RPC completion
|
| 280 |
+
void GetFlightInfoAsync(const FlightCallOptions& options,
|
| 281 |
+
const FlightDescriptor& descriptor,
|
| 282 |
+
std::shared_ptr<AsyncListener<FlightInfo>> listener);
|
| 283 |
+
void GetFlightInfoAsync(const FlightDescriptor& descriptor,
|
| 284 |
+
std::shared_ptr<AsyncListener<FlightInfo>> listener) {
|
| 285 |
+
return GetFlightInfoAsync({}, descriptor, std::move(listener));
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
/// \brief Asynchronous GetFlightInfo returning a Future.
|
| 289 |
+
/// \param[in] options Per-RPC options
|
| 290 |
+
/// \param[in] descriptor the dataset request
|
| 291 |
+
arrow::Future<FlightInfo> GetFlightInfoAsync(const FlightCallOptions& options,
|
| 292 |
+
const FlightDescriptor& descriptor);
|
| 293 |
+
arrow::Future<FlightInfo> GetFlightInfoAsync(const FlightDescriptor& descriptor) {
|
| 294 |
+
return GetFlightInfoAsync({}, descriptor);
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
/// \brief Request and poll a long running query
|
| 298 |
+
/// \param[in] options Per-RPC options
|
| 299 |
+
/// \param[in] descriptor the dataset request or a descriptor returned by a
|
| 300 |
+
/// prior PollFlightInfo call
|
| 301 |
+
/// \return Arrow result with the PollInfo describing the status of
|
| 302 |
+
/// the requested query
|
| 303 |
+
arrow::Result<std::unique_ptr<PollInfo>> PollFlightInfo(
|
| 304 |
+
const FlightCallOptions& options, const FlightDescriptor& descriptor);
|
| 305 |
+
arrow::Result<std::unique_ptr<PollInfo>> PollFlightInfo(
|
| 306 |
+
const FlightDescriptor& descriptor) {
|
| 307 |
+
return PollFlightInfo({}, descriptor);
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
/// \brief Request schema for a single flight, which may be an existing
|
| 311 |
+
/// dataset or a command to be executed
|
| 312 |
+
/// \param[in] options Per-RPC options
|
| 313 |
+
/// \param[in] descriptor the dataset request, whether a named dataset or
|
| 314 |
+
/// command
|
| 315 |
+
/// \return Arrow result with the SchemaResult describing the dataset schema
|
| 316 |
+
arrow::Result<std::unique_ptr<SchemaResult>> GetSchema(
|
| 317 |
+
const FlightCallOptions& options, const FlightDescriptor& descriptor);
|
| 318 |
+
|
| 319 |
+
arrow::Result<std::unique_ptr<SchemaResult>> GetSchema(
|
| 320 |
+
const FlightDescriptor& descriptor) {
|
| 321 |
+
return GetSchema({}, descriptor);
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
/// \brief List all available flights known to the server
|
| 325 |
+
/// \return Arrow result with an iterator that returns a FlightInfo for each flight
|
| 326 |
+
arrow::Result<std::unique_ptr<FlightListing>> ListFlights();
|
| 327 |
+
|
| 328 |
+
/// \brief List available flights given indicated filter criteria
|
| 329 |
+
/// \param[in] options Per-RPC options
|
| 330 |
+
/// \param[in] criteria the filter criteria (opaque)
|
| 331 |
+
/// \return Arrow result with an iterator that returns a FlightInfo for each flight
|
| 332 |
+
arrow::Result<std::unique_ptr<FlightListing>> ListFlights(
|
| 333 |
+
const FlightCallOptions& options, const Criteria& criteria);
|
| 334 |
+
|
| 335 |
+
/// \brief Given a flight ticket and schema, request to be sent the
|
| 336 |
+
/// stream. Returns record batch stream reader
|
| 337 |
+
/// \param[in] options Per-RPC options
|
| 338 |
+
/// \param[in] ticket The flight ticket to use
|
| 339 |
+
/// \return Arrow result with the returned RecordBatchReader
|
| 340 |
+
arrow::Result<std::unique_ptr<FlightStreamReader>> DoGet(
|
| 341 |
+
const FlightCallOptions& options, const Ticket& ticket);
|
| 342 |
+
arrow::Result<std::unique_ptr<FlightStreamReader>> DoGet(const Ticket& ticket) {
|
| 343 |
+
return DoGet({}, ticket);
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
/// \brief DoPut return value
|
| 347 |
+
struct DoPutResult {
|
| 348 |
+
/// \brief a writer to write record batches to
|
| 349 |
+
std::unique_ptr<FlightStreamWriter> writer;
|
| 350 |
+
/// \brief a reader for application metadata from the server
|
| 351 |
+
std::unique_ptr<FlightMetadataReader> reader;
|
| 352 |
+
};
|
| 353 |
+
/// \brief Upload data to a Flight described by the given
|
| 354 |
+
/// descriptor. The caller must call Close() on the returned stream
|
| 355 |
+
/// once they are done writing.
|
| 356 |
+
///
|
| 357 |
+
/// The reader and writer are linked; closing the writer will also
|
| 358 |
+
/// close the reader. Use \a DoneWriting to only close the write
|
| 359 |
+
/// side of the channel.
|
| 360 |
+
///
|
| 361 |
+
/// \param[in] options Per-RPC options
|
| 362 |
+
/// \param[in] descriptor the descriptor of the stream
|
| 363 |
+
/// \param[in] schema the schema for the data to upload
|
| 364 |
+
/// \return Arrow result with a DoPutResult struct holding a reader and a writer
|
| 365 |
+
arrow::Result<DoPutResult> DoPut(const FlightCallOptions& options,
|
| 366 |
+
const FlightDescriptor& descriptor,
|
| 367 |
+
const std::shared_ptr<Schema>& schema);
|
| 368 |
+
|
| 369 |
+
arrow::Result<DoPutResult> DoPut(const FlightDescriptor& descriptor,
|
| 370 |
+
const std::shared_ptr<Schema>& schema) {
|
| 371 |
+
return DoPut({}, descriptor, schema);
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
struct DoExchangeResult {
|
| 375 |
+
std::unique_ptr<FlightStreamWriter> writer;
|
| 376 |
+
std::unique_ptr<FlightStreamReader> reader;
|
| 377 |
+
};
|
| 378 |
+
arrow::Result<DoExchangeResult> DoExchange(const FlightCallOptions& options,
|
| 379 |
+
const FlightDescriptor& descriptor);
|
| 380 |
+
arrow::Result<DoExchangeResult> DoExchange(const FlightDescriptor& descriptor) {
|
| 381 |
+
return DoExchange({}, descriptor);
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
/// \brief Set server session option(s) by name/value. Sessions are generally
|
| 385 |
+
/// persisted via HTTP cookies.
|
| 386 |
+
/// \param[in] options Per-RPC options
|
| 387 |
+
/// \param[in] request The server session options to set
|
| 388 |
+
::arrow::Result<SetSessionOptionsResult> SetSessionOptions(
|
| 389 |
+
const FlightCallOptions& options, const SetSessionOptionsRequest& request);
|
| 390 |
+
|
| 391 |
+
/// \brief Get the current server session options. The session is generally
|
| 392 |
+
/// accessed via an HTTP cookie.
|
| 393 |
+
/// \param[in] options Per-RPC options
|
| 394 |
+
/// \param[in] request The (empty) GetSessionOptions request object.
|
| 395 |
+
::arrow::Result<GetSessionOptionsResult> GetSessionOptions(
|
| 396 |
+
const FlightCallOptions& options, const GetSessionOptionsRequest& request);
|
| 397 |
+
|
| 398 |
+
/// \brief Close/invalidate the current server session. The session is generally
|
| 399 |
+
/// accessed via an HTTP cookie.
|
| 400 |
+
/// \param[in] options Per-RPC options
|
| 401 |
+
/// \param[in] request The (empty) CloseSession request object.
|
| 402 |
+
::arrow::Result<CloseSessionResult> CloseSession(const FlightCallOptions& options,
|
| 403 |
+
const CloseSessionRequest& request);
|
| 404 |
+
|
| 405 |
+
/// \brief Explicitly shut down and clean up the client.
|
| 406 |
+
///
|
| 407 |
+
/// For backwards compatibility, this will be implicitly called by
|
| 408 |
+
/// the destructor if not already called, but this gives the
|
| 409 |
+
/// application no chance to handle errors, so it is recommended to
|
| 410 |
+
/// explicitly close the client.
|
| 411 |
+
///
|
| 412 |
+
/// \since 8.0.0
|
| 413 |
+
Status Close();
|
| 414 |
+
|
| 415 |
+
/// \brief Whether this client supports asynchronous methods.
|
| 416 |
+
bool supports_async() const;
|
| 417 |
+
|
| 418 |
+
/// \brief Check whether this client supports asynchronous methods.
|
| 419 |
+
///
|
| 420 |
+
/// This is like supports_async(), except that a detailed error message
|
| 421 |
+
/// is returned if async support is not available. If async support is
|
| 422 |
+
/// available, this function returns successfully.
|
| 423 |
+
Status CheckAsyncSupport() const;
|
| 424 |
+
|
| 425 |
+
private:
|
| 426 |
+
FlightClient();
|
| 427 |
+
Status CheckOpen() const;
|
| 428 |
+
std::unique_ptr<internal::ClientTransport> transport_;
|
| 429 |
+
bool closed_;
|
| 430 |
+
int64_t write_size_limit_bytes_;
|
| 431 |
+
};
|
| 432 |
+
|
| 433 |
+
} // namespace flight
|
| 434 |
+
} // namespace arrow
|
shared/package-files/31/31d3fcccd95241e794ee9b0e5f0194750d7ef172b360297998a30872930288df/blob
ADDED
|
@@ -0,0 +1,643 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
datetimelike delegation
|
| 3 |
+
"""
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import (
|
| 7 |
+
TYPE_CHECKING,
|
| 8 |
+
cast,
|
| 9 |
+
)
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
from pandas._libs import lib
|
| 15 |
+
from pandas.util._exceptions import find_stack_level
|
| 16 |
+
|
| 17 |
+
from pandas.core.dtypes.common import (
|
| 18 |
+
is_integer_dtype,
|
| 19 |
+
is_list_like,
|
| 20 |
+
)
|
| 21 |
+
from pandas.core.dtypes.dtypes import (
|
| 22 |
+
ArrowDtype,
|
| 23 |
+
CategoricalDtype,
|
| 24 |
+
DatetimeTZDtype,
|
| 25 |
+
PeriodDtype,
|
| 26 |
+
)
|
| 27 |
+
from pandas.core.dtypes.generic import ABCSeries
|
| 28 |
+
|
| 29 |
+
from pandas.core.accessor import (
|
| 30 |
+
PandasDelegate,
|
| 31 |
+
delegate_names,
|
| 32 |
+
)
|
| 33 |
+
from pandas.core.arrays import (
|
| 34 |
+
DatetimeArray,
|
| 35 |
+
PeriodArray,
|
| 36 |
+
TimedeltaArray,
|
| 37 |
+
)
|
| 38 |
+
from pandas.core.arrays.arrow.array import ArrowExtensionArray
|
| 39 |
+
from pandas.core.base import (
|
| 40 |
+
NoNewAttributesMixin,
|
| 41 |
+
PandasObject,
|
| 42 |
+
)
|
| 43 |
+
from pandas.core.indexes.datetimes import DatetimeIndex
|
| 44 |
+
from pandas.core.indexes.timedeltas import TimedeltaIndex
|
| 45 |
+
|
| 46 |
+
if TYPE_CHECKING:
|
| 47 |
+
from pandas import (
|
| 48 |
+
DataFrame,
|
| 49 |
+
Series,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin):
|
| 54 |
+
_hidden_attrs = PandasObject._hidden_attrs | {
|
| 55 |
+
"orig",
|
| 56 |
+
"name",
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
def __init__(self, data: Series, orig) -> None:
|
| 60 |
+
if not isinstance(data, ABCSeries):
|
| 61 |
+
raise TypeError(
|
| 62 |
+
f"cannot convert an object of type {type(data)} to a datetimelike index"
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
self._parent = data
|
| 66 |
+
self.orig = orig
|
| 67 |
+
self.name = getattr(data, "name", None)
|
| 68 |
+
self._freeze()
|
| 69 |
+
|
| 70 |
+
def _get_values(self):
|
| 71 |
+
data = self._parent
|
| 72 |
+
if lib.is_np_dtype(data.dtype, "M"):
|
| 73 |
+
return DatetimeIndex(data, copy=False, name=self.name)
|
| 74 |
+
|
| 75 |
+
elif isinstance(data.dtype, DatetimeTZDtype):
|
| 76 |
+
return DatetimeIndex(data, copy=False, name=self.name)
|
| 77 |
+
|
| 78 |
+
elif lib.is_np_dtype(data.dtype, "m"):
|
| 79 |
+
return TimedeltaIndex(data, copy=False, name=self.name)
|
| 80 |
+
|
| 81 |
+
elif isinstance(data.dtype, PeriodDtype):
|
| 82 |
+
return PeriodArray(data, copy=False)
|
| 83 |
+
|
| 84 |
+
raise TypeError(
|
| 85 |
+
f"cannot convert an object of type {type(data)} to a datetimelike index"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
def _delegate_property_get(self, name: str):
|
| 89 |
+
from pandas import Series
|
| 90 |
+
|
| 91 |
+
values = self._get_values()
|
| 92 |
+
|
| 93 |
+
result = getattr(values, name)
|
| 94 |
+
|
| 95 |
+
# maybe need to upcast (ints)
|
| 96 |
+
if isinstance(result, np.ndarray):
|
| 97 |
+
if is_integer_dtype(result):
|
| 98 |
+
result = result.astype("int64")
|
| 99 |
+
elif not is_list_like(result):
|
| 100 |
+
return result
|
| 101 |
+
|
| 102 |
+
result = np.asarray(result)
|
| 103 |
+
|
| 104 |
+
if self.orig is not None:
|
| 105 |
+
index = self.orig.index
|
| 106 |
+
else:
|
| 107 |
+
index = self._parent.index
|
| 108 |
+
# return the result as a Series
|
| 109 |
+
result = Series(result, index=index, name=self.name).__finalize__(self._parent)
|
| 110 |
+
|
| 111 |
+
# setting this object will show a SettingWithCopyWarning/Error
|
| 112 |
+
result._is_copy = (
|
| 113 |
+
"modifications to a property of a datetimelike "
|
| 114 |
+
"object are not supported and are discarded. "
|
| 115 |
+
"Change values on the original."
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
return result
|
| 119 |
+
|
| 120 |
+
def _delegate_property_set(self, name: str, value, *args, **kwargs):
|
| 121 |
+
raise ValueError(
|
| 122 |
+
"modifications to a property of a datetimelike object are not supported. "
|
| 123 |
+
"Change values on the original."
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
def _delegate_method(self, name: str, *args, **kwargs):
|
| 127 |
+
from pandas import Series
|
| 128 |
+
|
| 129 |
+
values = self._get_values()
|
| 130 |
+
|
| 131 |
+
method = getattr(values, name)
|
| 132 |
+
result = method(*args, **kwargs)
|
| 133 |
+
|
| 134 |
+
if not is_list_like(result):
|
| 135 |
+
return result
|
| 136 |
+
|
| 137 |
+
result = Series(result, index=self._parent.index, name=self.name).__finalize__(
|
| 138 |
+
self._parent
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
# setting this object will show a SettingWithCopyWarning/Error
|
| 142 |
+
result._is_copy = (
|
| 143 |
+
"modifications to a method of a datetimelike "
|
| 144 |
+
"object are not supported and are discarded. "
|
| 145 |
+
"Change values on the original."
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
return result
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@delegate_names(
|
| 152 |
+
delegate=ArrowExtensionArray,
|
| 153 |
+
accessors=TimedeltaArray._datetimelike_ops,
|
| 154 |
+
typ="property",
|
| 155 |
+
accessor_mapping=lambda x: f"_dt_{x}",
|
| 156 |
+
raise_on_missing=False,
|
| 157 |
+
)
|
| 158 |
+
@delegate_names(
|
| 159 |
+
delegate=ArrowExtensionArray,
|
| 160 |
+
accessors=TimedeltaArray._datetimelike_methods,
|
| 161 |
+
typ="method",
|
| 162 |
+
accessor_mapping=lambda x: f"_dt_{x}",
|
| 163 |
+
raise_on_missing=False,
|
| 164 |
+
)
|
| 165 |
+
@delegate_names(
|
| 166 |
+
delegate=ArrowExtensionArray,
|
| 167 |
+
accessors=DatetimeArray._datetimelike_ops,
|
| 168 |
+
typ="property",
|
| 169 |
+
accessor_mapping=lambda x: f"_dt_{x}",
|
| 170 |
+
raise_on_missing=False,
|
| 171 |
+
)
|
| 172 |
+
@delegate_names(
|
| 173 |
+
delegate=ArrowExtensionArray,
|
| 174 |
+
accessors=DatetimeArray._datetimelike_methods,
|
| 175 |
+
typ="method",
|
| 176 |
+
accessor_mapping=lambda x: f"_dt_{x}",
|
| 177 |
+
raise_on_missing=False,
|
| 178 |
+
)
|
| 179 |
+
class ArrowTemporalProperties(PandasDelegate, PandasObject, NoNewAttributesMixin):
|
| 180 |
+
def __init__(self, data: Series, orig) -> None:
|
| 181 |
+
if not isinstance(data, ABCSeries):
|
| 182 |
+
raise TypeError(
|
| 183 |
+
f"cannot convert an object of type {type(data)} to a datetimelike index"
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
self._parent = data
|
| 187 |
+
self._orig = orig
|
| 188 |
+
self._freeze()
|
| 189 |
+
|
| 190 |
+
def _delegate_property_get(self, name: str):
|
| 191 |
+
if not hasattr(self._parent.array, f"_dt_{name}"):
|
| 192 |
+
raise NotImplementedError(
|
| 193 |
+
f"dt.{name} is not supported for {self._parent.dtype}"
|
| 194 |
+
)
|
| 195 |
+
result = getattr(self._parent.array, f"_dt_{name}")
|
| 196 |
+
|
| 197 |
+
if not is_list_like(result):
|
| 198 |
+
return result
|
| 199 |
+
|
| 200 |
+
if self._orig is not None:
|
| 201 |
+
index = self._orig.index
|
| 202 |
+
else:
|
| 203 |
+
index = self._parent.index
|
| 204 |
+
# return the result as a Series, which is by definition a copy
|
| 205 |
+
result = type(self._parent)(
|
| 206 |
+
result, index=index, name=self._parent.name
|
| 207 |
+
).__finalize__(self._parent)
|
| 208 |
+
|
| 209 |
+
return result
|
| 210 |
+
|
| 211 |
+
def _delegate_method(self, name: str, *args, **kwargs):
|
| 212 |
+
if not hasattr(self._parent.array, f"_dt_{name}"):
|
| 213 |
+
raise NotImplementedError(
|
| 214 |
+
f"dt.{name} is not supported for {self._parent.dtype}"
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
result = getattr(self._parent.array, f"_dt_{name}")(*args, **kwargs)
|
| 218 |
+
|
| 219 |
+
if self._orig is not None:
|
| 220 |
+
index = self._orig.index
|
| 221 |
+
else:
|
| 222 |
+
index = self._parent.index
|
| 223 |
+
# return the result as a Series, which is by definition a copy
|
| 224 |
+
result = type(self._parent)(
|
| 225 |
+
result, index=index, name=self._parent.name
|
| 226 |
+
).__finalize__(self._parent)
|
| 227 |
+
|
| 228 |
+
return result
|
| 229 |
+
|
| 230 |
+
def to_pytimedelta(self):
|
| 231 |
+
return cast(ArrowExtensionArray, self._parent.array)._dt_to_pytimedelta()
|
| 232 |
+
|
| 233 |
+
def to_pydatetime(self):
|
| 234 |
+
# GH#20306
|
| 235 |
+
warnings.warn(
|
| 236 |
+
f"The behavior of {type(self).__name__}.to_pydatetime is deprecated, "
|
| 237 |
+
"in a future version this will return a Series containing python "
|
| 238 |
+
"datetime objects instead of an ndarray. To retain the old behavior, "
|
| 239 |
+
"call `np.array` on the result",
|
| 240 |
+
FutureWarning,
|
| 241 |
+
stacklevel=find_stack_level(),
|
| 242 |
+
)
|
| 243 |
+
return cast(ArrowExtensionArray, self._parent.array)._dt_to_pydatetime()
|
| 244 |
+
|
| 245 |
+
def isocalendar(self) -> DataFrame:
|
| 246 |
+
from pandas import DataFrame
|
| 247 |
+
|
| 248 |
+
result = (
|
| 249 |
+
cast(ArrowExtensionArray, self._parent.array)
|
| 250 |
+
._dt_isocalendar()
|
| 251 |
+
._pa_array.combine_chunks()
|
| 252 |
+
)
|
| 253 |
+
iso_calendar_df = DataFrame(
|
| 254 |
+
{
|
| 255 |
+
col: type(self._parent.array)(result.field(i)) # type: ignore[call-arg]
|
| 256 |
+
for i, col in enumerate(["year", "week", "day"])
|
| 257 |
+
}
|
| 258 |
+
)
|
| 259 |
+
return iso_calendar_df
|
| 260 |
+
|
| 261 |
+
@property
|
| 262 |
+
def components(self) -> DataFrame:
|
| 263 |
+
from pandas import DataFrame
|
| 264 |
+
|
| 265 |
+
components_df = DataFrame(
|
| 266 |
+
{
|
| 267 |
+
col: getattr(self._parent.array, f"_dt_{col}")
|
| 268 |
+
for col in [
|
| 269 |
+
"days",
|
| 270 |
+
"hours",
|
| 271 |
+
"minutes",
|
| 272 |
+
"seconds",
|
| 273 |
+
"milliseconds",
|
| 274 |
+
"microseconds",
|
| 275 |
+
"nanoseconds",
|
| 276 |
+
]
|
| 277 |
+
}
|
| 278 |
+
)
|
| 279 |
+
return components_df
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
@delegate_names(
|
| 283 |
+
delegate=DatetimeArray,
|
| 284 |
+
accessors=DatetimeArray._datetimelike_ops + ["unit"],
|
| 285 |
+
typ="property",
|
| 286 |
+
)
|
| 287 |
+
@delegate_names(
|
| 288 |
+
delegate=DatetimeArray,
|
| 289 |
+
accessors=DatetimeArray._datetimelike_methods + ["as_unit"],
|
| 290 |
+
typ="method",
|
| 291 |
+
)
|
| 292 |
+
class DatetimeProperties(Properties):
|
| 293 |
+
"""
|
| 294 |
+
Accessor object for datetimelike properties of the Series values.
|
| 295 |
+
|
| 296 |
+
Examples
|
| 297 |
+
--------
|
| 298 |
+
>>> seconds_series = pd.Series(pd.date_range("2000-01-01", periods=3, freq="s"))
|
| 299 |
+
>>> seconds_series
|
| 300 |
+
0 2000-01-01 00:00:00
|
| 301 |
+
1 2000-01-01 00:00:01
|
| 302 |
+
2 2000-01-01 00:00:02
|
| 303 |
+
dtype: datetime64[ns]
|
| 304 |
+
>>> seconds_series.dt.second
|
| 305 |
+
0 0
|
| 306 |
+
1 1
|
| 307 |
+
2 2
|
| 308 |
+
dtype: int32
|
| 309 |
+
|
| 310 |
+
>>> hours_series = pd.Series(pd.date_range("2000-01-01", periods=3, freq="h"))
|
| 311 |
+
>>> hours_series
|
| 312 |
+
0 2000-01-01 00:00:00
|
| 313 |
+
1 2000-01-01 01:00:00
|
| 314 |
+
2 2000-01-01 02:00:00
|
| 315 |
+
dtype: datetime64[ns]
|
| 316 |
+
>>> hours_series.dt.hour
|
| 317 |
+
0 0
|
| 318 |
+
1 1
|
| 319 |
+
2 2
|
| 320 |
+
dtype: int32
|
| 321 |
+
|
| 322 |
+
>>> quarters_series = pd.Series(pd.date_range("2000-01-01", periods=3, freq="QE"))
|
| 323 |
+
>>> quarters_series
|
| 324 |
+
0 2000-03-31
|
| 325 |
+
1 2000-06-30
|
| 326 |
+
2 2000-09-30
|
| 327 |
+
dtype: datetime64[ns]
|
| 328 |
+
>>> quarters_series.dt.quarter
|
| 329 |
+
0 1
|
| 330 |
+
1 2
|
| 331 |
+
2 3
|
| 332 |
+
dtype: int32
|
| 333 |
+
|
| 334 |
+
Returns a Series indexed like the original Series.
|
| 335 |
+
Raises TypeError if the Series does not contain datetimelike values.
|
| 336 |
+
"""
|
| 337 |
+
|
| 338 |
+
def to_pydatetime(self) -> np.ndarray:
|
| 339 |
+
"""
|
| 340 |
+
Return the data as an array of :class:`datetime.datetime` objects.
|
| 341 |
+
|
| 342 |
+
.. deprecated:: 2.1.0
|
| 343 |
+
|
| 344 |
+
The current behavior of dt.to_pydatetime is deprecated.
|
| 345 |
+
In a future version this will return a Series containing python
|
| 346 |
+
datetime objects instead of a ndarray.
|
| 347 |
+
|
| 348 |
+
Timezone information is retained if present.
|
| 349 |
+
|
| 350 |
+
.. warning::
|
| 351 |
+
|
| 352 |
+
Python's datetime uses microsecond resolution, which is lower than
|
| 353 |
+
pandas (nanosecond). The values are truncated.
|
| 354 |
+
|
| 355 |
+
Returns
|
| 356 |
+
-------
|
| 357 |
+
numpy.ndarray
|
| 358 |
+
Object dtype array containing native Python datetime objects.
|
| 359 |
+
|
| 360 |
+
See Also
|
| 361 |
+
--------
|
| 362 |
+
datetime.datetime : Standard library value for a datetime.
|
| 363 |
+
|
| 364 |
+
Examples
|
| 365 |
+
--------
|
| 366 |
+
>>> s = pd.Series(pd.date_range('20180310', periods=2))
|
| 367 |
+
>>> s
|
| 368 |
+
0 2018-03-10
|
| 369 |
+
1 2018-03-11
|
| 370 |
+
dtype: datetime64[ns]
|
| 371 |
+
|
| 372 |
+
>>> s.dt.to_pydatetime()
|
| 373 |
+
array([datetime.datetime(2018, 3, 10, 0, 0),
|
| 374 |
+
datetime.datetime(2018, 3, 11, 0, 0)], dtype=object)
|
| 375 |
+
|
| 376 |
+
pandas' nanosecond precision is truncated to microseconds.
|
| 377 |
+
|
| 378 |
+
>>> s = pd.Series(pd.date_range('20180310', periods=2, freq='ns'))
|
| 379 |
+
>>> s
|
| 380 |
+
0 2018-03-10 00:00:00.000000000
|
| 381 |
+
1 2018-03-10 00:00:00.000000001
|
| 382 |
+
dtype: datetime64[ns]
|
| 383 |
+
|
| 384 |
+
>>> s.dt.to_pydatetime()
|
| 385 |
+
array([datetime.datetime(2018, 3, 10, 0, 0),
|
| 386 |
+
datetime.datetime(2018, 3, 10, 0, 0)], dtype=object)
|
| 387 |
+
"""
|
| 388 |
+
# GH#20306
|
| 389 |
+
warnings.warn(
|
| 390 |
+
f"The behavior of {type(self).__name__}.to_pydatetime is deprecated, "
|
| 391 |
+
"in a future version this will return a Series containing python "
|
| 392 |
+
"datetime objects instead of an ndarray. To retain the old behavior, "
|
| 393 |
+
"call `np.array` on the result",
|
| 394 |
+
FutureWarning,
|
| 395 |
+
stacklevel=find_stack_level(),
|
| 396 |
+
)
|
| 397 |
+
return self._get_values().to_pydatetime()
|
| 398 |
+
|
| 399 |
+
@property
|
| 400 |
+
def freq(self):
|
| 401 |
+
return self._get_values().inferred_freq
|
| 402 |
+
|
| 403 |
+
def isocalendar(self) -> DataFrame:
|
| 404 |
+
"""
|
| 405 |
+
Calculate year, week, and day according to the ISO 8601 standard.
|
| 406 |
+
|
| 407 |
+
Returns
|
| 408 |
+
-------
|
| 409 |
+
DataFrame
|
| 410 |
+
With columns year, week and day.
|
| 411 |
+
|
| 412 |
+
See Also
|
| 413 |
+
--------
|
| 414 |
+
Timestamp.isocalendar : Function return a 3-tuple containing ISO year,
|
| 415 |
+
week number, and weekday for the given Timestamp object.
|
| 416 |
+
datetime.date.isocalendar : Return a named tuple object with
|
| 417 |
+
three components: year, week and weekday.
|
| 418 |
+
|
| 419 |
+
Examples
|
| 420 |
+
--------
|
| 421 |
+
>>> ser = pd.to_datetime(pd.Series(["2010-01-01", pd.NaT]))
|
| 422 |
+
>>> ser.dt.isocalendar()
|
| 423 |
+
year week day
|
| 424 |
+
0 2009 53 5
|
| 425 |
+
1 <NA> <NA> <NA>
|
| 426 |
+
>>> ser.dt.isocalendar().week
|
| 427 |
+
0 53
|
| 428 |
+
1 <NA>
|
| 429 |
+
Name: week, dtype: UInt32
|
| 430 |
+
"""
|
| 431 |
+
return self._get_values().isocalendar().set_index(self._parent.index)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
@delegate_names(
|
| 435 |
+
delegate=TimedeltaArray, accessors=TimedeltaArray._datetimelike_ops, typ="property"
|
| 436 |
+
)
|
| 437 |
+
@delegate_names(
|
| 438 |
+
delegate=TimedeltaArray,
|
| 439 |
+
accessors=TimedeltaArray._datetimelike_methods,
|
| 440 |
+
typ="method",
|
| 441 |
+
)
|
| 442 |
+
class TimedeltaProperties(Properties):
|
| 443 |
+
"""
|
| 444 |
+
Accessor object for datetimelike properties of the Series values.
|
| 445 |
+
|
| 446 |
+
Returns a Series indexed like the original Series.
|
| 447 |
+
Raises TypeError if the Series does not contain datetimelike values.
|
| 448 |
+
|
| 449 |
+
Examples
|
| 450 |
+
--------
|
| 451 |
+
>>> seconds_series = pd.Series(
|
| 452 |
+
... pd.timedelta_range(start="1 second", periods=3, freq="s")
|
| 453 |
+
... )
|
| 454 |
+
>>> seconds_series
|
| 455 |
+
0 0 days 00:00:01
|
| 456 |
+
1 0 days 00:00:02
|
| 457 |
+
2 0 days 00:00:03
|
| 458 |
+
dtype: timedelta64[ns]
|
| 459 |
+
>>> seconds_series.dt.seconds
|
| 460 |
+
0 1
|
| 461 |
+
1 2
|
| 462 |
+
2 3
|
| 463 |
+
dtype: int32
|
| 464 |
+
"""
|
| 465 |
+
|
| 466 |
+
def to_pytimedelta(self) -> np.ndarray:
|
| 467 |
+
"""
|
| 468 |
+
Return an array of native :class:`datetime.timedelta` objects.
|
| 469 |
+
|
| 470 |
+
Python's standard `datetime` library uses a different representation
|
| 471 |
+
timedelta's. This method converts a Series of pandas Timedeltas
|
| 472 |
+
to `datetime.timedelta` format with the same length as the original
|
| 473 |
+
Series.
|
| 474 |
+
|
| 475 |
+
Returns
|
| 476 |
+
-------
|
| 477 |
+
numpy.ndarray
|
| 478 |
+
Array of 1D containing data with `datetime.timedelta` type.
|
| 479 |
+
|
| 480 |
+
See Also
|
| 481 |
+
--------
|
| 482 |
+
datetime.timedelta : A duration expressing the difference
|
| 483 |
+
between two date, time, or datetime.
|
| 484 |
+
|
| 485 |
+
Examples
|
| 486 |
+
--------
|
| 487 |
+
>>> s = pd.Series(pd.to_timedelta(np.arange(5), unit="d"))
|
| 488 |
+
>>> s
|
| 489 |
+
0 0 days
|
| 490 |
+
1 1 days
|
| 491 |
+
2 2 days
|
| 492 |
+
3 3 days
|
| 493 |
+
4 4 days
|
| 494 |
+
dtype: timedelta64[ns]
|
| 495 |
+
|
| 496 |
+
>>> s.dt.to_pytimedelta()
|
| 497 |
+
array([datetime.timedelta(0), datetime.timedelta(days=1),
|
| 498 |
+
datetime.timedelta(days=2), datetime.timedelta(days=3),
|
| 499 |
+
datetime.timedelta(days=4)], dtype=object)
|
| 500 |
+
"""
|
| 501 |
+
return self._get_values().to_pytimedelta()
|
| 502 |
+
|
| 503 |
+
@property
|
| 504 |
+
def components(self):
|
| 505 |
+
"""
|
| 506 |
+
Return a Dataframe of the components of the Timedeltas.
|
| 507 |
+
|
| 508 |
+
Returns
|
| 509 |
+
-------
|
| 510 |
+
DataFrame
|
| 511 |
+
|
| 512 |
+
Examples
|
| 513 |
+
--------
|
| 514 |
+
>>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='s'))
|
| 515 |
+
>>> s
|
| 516 |
+
0 0 days 00:00:00
|
| 517 |
+
1 0 days 00:00:01
|
| 518 |
+
2 0 days 00:00:02
|
| 519 |
+
3 0 days 00:00:03
|
| 520 |
+
4 0 days 00:00:04
|
| 521 |
+
dtype: timedelta64[ns]
|
| 522 |
+
>>> s.dt.components
|
| 523 |
+
days hours minutes seconds milliseconds microseconds nanoseconds
|
| 524 |
+
0 0 0 0 0 0 0 0
|
| 525 |
+
1 0 0 0 1 0 0 0
|
| 526 |
+
2 0 0 0 2 0 0 0
|
| 527 |
+
3 0 0 0 3 0 0 0
|
| 528 |
+
4 0 0 0 4 0 0 0
|
| 529 |
+
"""
|
| 530 |
+
return (
|
| 531 |
+
self._get_values()
|
| 532 |
+
.components.set_index(self._parent.index)
|
| 533 |
+
.__finalize__(self._parent)
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
@property
|
| 537 |
+
def freq(self):
|
| 538 |
+
return self._get_values().inferred_freq
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
@delegate_names(
|
| 542 |
+
delegate=PeriodArray, accessors=PeriodArray._datetimelike_ops, typ="property"
|
| 543 |
+
)
|
| 544 |
+
@delegate_names(
|
| 545 |
+
delegate=PeriodArray, accessors=PeriodArray._datetimelike_methods, typ="method"
|
| 546 |
+
)
|
| 547 |
+
class PeriodProperties(Properties):
|
| 548 |
+
"""
|
| 549 |
+
Accessor object for datetimelike properties of the Series values.
|
| 550 |
+
|
| 551 |
+
Returns a Series indexed like the original Series.
|
| 552 |
+
Raises TypeError if the Series does not contain datetimelike values.
|
| 553 |
+
|
| 554 |
+
Examples
|
| 555 |
+
--------
|
| 556 |
+
>>> seconds_series = pd.Series(
|
| 557 |
+
... pd.period_range(
|
| 558 |
+
... start="2000-01-01 00:00:00", end="2000-01-01 00:00:03", freq="s"
|
| 559 |
+
... )
|
| 560 |
+
... )
|
| 561 |
+
>>> seconds_series
|
| 562 |
+
0 2000-01-01 00:00:00
|
| 563 |
+
1 2000-01-01 00:00:01
|
| 564 |
+
2 2000-01-01 00:00:02
|
| 565 |
+
3 2000-01-01 00:00:03
|
| 566 |
+
dtype: period[s]
|
| 567 |
+
>>> seconds_series.dt.second
|
| 568 |
+
0 0
|
| 569 |
+
1 1
|
| 570 |
+
2 2
|
| 571 |
+
3 3
|
| 572 |
+
dtype: int64
|
| 573 |
+
|
| 574 |
+
>>> hours_series = pd.Series(
|
| 575 |
+
... pd.period_range(start="2000-01-01 00:00", end="2000-01-01 03:00", freq="h")
|
| 576 |
+
... )
|
| 577 |
+
>>> hours_series
|
| 578 |
+
0 2000-01-01 00:00
|
| 579 |
+
1 2000-01-01 01:00
|
| 580 |
+
2 2000-01-01 02:00
|
| 581 |
+
3 2000-01-01 03:00
|
| 582 |
+
dtype: period[h]
|
| 583 |
+
>>> hours_series.dt.hour
|
| 584 |
+
0 0
|
| 585 |
+
1 1
|
| 586 |
+
2 2
|
| 587 |
+
3 3
|
| 588 |
+
dtype: int64
|
| 589 |
+
|
| 590 |
+
>>> quarters_series = pd.Series(
|
| 591 |
+
... pd.period_range(start="2000-01-01", end="2000-12-31", freq="Q-DEC")
|
| 592 |
+
... )
|
| 593 |
+
>>> quarters_series
|
| 594 |
+
0 2000Q1
|
| 595 |
+
1 2000Q2
|
| 596 |
+
2 2000Q3
|
| 597 |
+
3 2000Q4
|
| 598 |
+
dtype: period[Q-DEC]
|
| 599 |
+
>>> quarters_series.dt.quarter
|
| 600 |
+
0 1
|
| 601 |
+
1 2
|
| 602 |
+
2 3
|
| 603 |
+
3 4
|
| 604 |
+
dtype: int64
|
| 605 |
+
"""
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
class CombinedDatetimelikeProperties(
|
| 609 |
+
DatetimeProperties, TimedeltaProperties, PeriodProperties
|
| 610 |
+
):
|
| 611 |
+
def __new__(cls, data: Series): # pyright: ignore[reportInconsistentConstructor]
|
| 612 |
+
# CombinedDatetimelikeProperties isn't really instantiated. Instead
|
| 613 |
+
# we need to choose which parent (datetime or timedelta) is
|
| 614 |
+
# appropriate. Since we're checking the dtypes anyway, we'll just
|
| 615 |
+
# do all the validation here.
|
| 616 |
+
|
| 617 |
+
if not isinstance(data, ABCSeries):
|
| 618 |
+
raise TypeError(
|
| 619 |
+
f"cannot convert an object of type {type(data)} to a datetimelike index"
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
orig = data if isinstance(data.dtype, CategoricalDtype) else None
|
| 623 |
+
if orig is not None:
|
| 624 |
+
data = data._constructor(
|
| 625 |
+
orig.array,
|
| 626 |
+
name=orig.name,
|
| 627 |
+
copy=False,
|
| 628 |
+
dtype=orig._values.categories.dtype,
|
| 629 |
+
index=orig.index,
|
| 630 |
+
)
|
| 631 |
+
|
| 632 |
+
if isinstance(data.dtype, ArrowDtype) and data.dtype.kind in "Mm":
|
| 633 |
+
return ArrowTemporalProperties(data, orig)
|
| 634 |
+
if lib.is_np_dtype(data.dtype, "M"):
|
| 635 |
+
return DatetimeProperties(data, orig)
|
| 636 |
+
elif isinstance(data.dtype, DatetimeTZDtype):
|
| 637 |
+
return DatetimeProperties(data, orig)
|
| 638 |
+
elif lib.is_np_dtype(data.dtype, "m"):
|
| 639 |
+
return TimedeltaProperties(data, orig)
|
| 640 |
+
elif isinstance(data.dtype, PeriodDtype):
|
| 641 |
+
return PeriodProperties(data, orig)
|
| 642 |
+
|
| 643 |
+
raise AttributeError("Can only use .dt accessor with datetimelike values")
|
shared/package-files/31/31d72adad79910126b22a5579ec9e179eee86674ecebe3fcff6f76916193af0e/blob
AD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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
StartFontMetrics 4.1
|
| 2 |
+
Comment Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.
|
| 3 |
+
Comment Creation Date: Thu May 1 17:27:09 1997
|
| 4 |
+
Comment UniqueID 43050
|
| 5 |
+
Comment VMusage 39754 50779
|
| 6 |
+
FontName Courier
|
| 7 |
+
FullName Courier
|
| 8 |
+
FamilyName Courier
|
| 9 |
+
Weight Medium
|
| 10 |
+
ItalicAngle 0
|
| 11 |
+
IsFixedPitch true
|
| 12 |
+
CharacterSet ExtendedRoman
|
| 13 |
+
FontBBox -23 -250 715 805
|
| 14 |
+
UnderlinePosition -100
|
| 15 |
+
UnderlineThickness 50
|
| 16 |
+
Version 003.000
|
| 17 |
+
Notice Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.
|
| 18 |
+
EncodingScheme AdobeStandardEncoding
|
| 19 |
+
CapHeight 562
|
| 20 |
+
XHeight 426
|
| 21 |
+
Ascender 629
|
| 22 |
+
Descender -157
|
| 23 |
+
StdHW 51
|
| 24 |
+
StdVW 51
|
| 25 |
+
StartCharMetrics 315
|
| 26 |
+
C 32 ; WX 600 ; N space ; B 0 0 0 0 ;
|
| 27 |
+
C 33 ; WX 600 ; N exclam ; B 236 -15 364 572 ;
|
| 28 |
+
C 34 ; WX 600 ; N quotedbl ; B 187 328 413 562 ;
|
| 29 |
+
C 35 ; WX 600 ; N numbersign ; B 93 -32 507 639 ;
|
| 30 |
+
C 36 ; WX 600 ; N dollar ; B 105 -126 496 662 ;
|
| 31 |
+
C 37 ; WX 600 ; N percent ; B 81 -15 518 622 ;
|
| 32 |
+
C 38 ; WX 600 ; N ampersand ; B 63 -15 538 543 ;
|
| 33 |
+
C 39 ; WX 600 ; N quoteright ; B 213 328 376 562 ;
|
| 34 |
+
C 40 ; WX 600 ; N parenleft ; B 269 -108 440 622 ;
|
| 35 |
+
C 41 ; WX 600 ; N parenright ; B 160 -108 331 622 ;
|
| 36 |
+
C 42 ; WX 600 ; N asterisk ; B 116 257 484 607 ;
|
| 37 |
+
C 43 ; WX 600 ; N plus ; B 80 44 520 470 ;
|
| 38 |
+
C 44 ; WX 600 ; N comma ; B 181 -112 344 122 ;
|
| 39 |
+
C 45 ; WX 600 ; N hyphen ; B 103 231 497 285 ;
|
| 40 |
+
C 46 ; WX 600 ; N period ; B 229 -15 371 109 ;
|
| 41 |
+
C 47 ; WX 600 ; N slash ; B 125 -80 475 629 ;
|
| 42 |
+
C 48 ; WX 600 ; N zero ; B 106 -15 494 622 ;
|
| 43 |
+
C 49 ; WX 600 ; N one ; B 96 0 505 622 ;
|
| 44 |
+
C 50 ; WX 600 ; N two ; B 70 0 471 622 ;
|
| 45 |
+
C 51 ; WX 600 ; N three ; B 75 -15 466 622 ;
|
| 46 |
+
C 52 ; WX 600 ; N four ; B 78 0 500 622 ;
|
| 47 |
+
C 53 ; WX 600 ; N five ; B 92 -15 497 607 ;
|
| 48 |
+
C 54 ; WX 600 ; N six ; B 111 -15 497 622 ;
|
| 49 |
+
C 55 ; WX 600 ; N seven ; B 82 0 483 607 ;
|
| 50 |
+
C 56 ; WX 600 ; N eight ; B 102 -15 498 622 ;
|
| 51 |
+
C 57 ; WX 600 ; N nine ; B 96 -15 489 622 ;
|
| 52 |
+
C 58 ; WX 600 ; N colon ; B 229 -15 371 385 ;
|
| 53 |
+
C 59 ; WX 600 ; N semicolon ; B 181 -112 371 385 ;
|
| 54 |
+
C 60 ; WX 600 ; N less ; B 41 42 519 472 ;
|
| 55 |
+
C 61 ; WX 600 ; N equal ; B 80 138 520 376 ;
|
| 56 |
+
C 62 ; WX 600 ; N greater ; B 66 42 544 472 ;
|
| 57 |
+
C 63 ; WX 600 ; N question ; B 129 -15 492 572 ;
|
| 58 |
+
C 64 ; WX 600 ; N at ; B 77 -15 533 622 ;
|
| 59 |
+
C 65 ; WX 600 ; N A ; B 3 0 597 562 ;
|
| 60 |
+
C 66 ; WX 600 ; N B ; B 43 0 559 562 ;
|
| 61 |
+
C 67 ; WX 600 ; N C ; B 41 -18 540 580 ;
|
| 62 |
+
C 68 ; WX 600 ; N D ; B 43 0 574 562 ;
|
| 63 |
+
C 69 ; WX 600 ; N E ; B 53 0 550 562 ;
|
| 64 |
+
C 70 ; WX 600 ; N F ; B 53 0 545 562 ;
|
| 65 |
+
C 71 ; WX 600 ; N G ; B 31 -18 575 580 ;
|
| 66 |
+
C 72 ; WX 600 ; N H ; B 32 0 568 562 ;
|
| 67 |
+
C 73 ; WX 600 ; N I ; B 96 0 504 562 ;
|
| 68 |
+
C 74 ; WX 600 ; N J ; B 34 -18 566 562 ;
|
| 69 |
+
C 75 ; WX 600 ; N K ; B 38 0 582 562 ;
|
| 70 |
+
C 76 ; WX 600 ; N L ; B 47 0 554 562 ;
|
| 71 |
+
C 77 ; WX 600 ; N M ; B 4 0 596 562 ;
|
| 72 |
+
C 78 ; WX 600 ; N N ; B 7 -13 593 562 ;
|
| 73 |
+
C 79 ; WX 600 ; N O ; B 43 -18 557 580 ;
|
| 74 |
+
C 80 ; WX 600 ; N P ; B 79 0 558 562 ;
|
| 75 |
+
C 81 ; WX 600 ; N Q ; B 43 -138 557 580 ;
|
| 76 |
+
C 82 ; WX 600 ; N R ; B 38 0 588 562 ;
|
| 77 |
+
C 83 ; WX 600 ; N S ; B 72 -20 529 580 ;
|
| 78 |
+
C 84 ; WX 600 ; N T ; B 38 0 563 562 ;
|
| 79 |
+
C 85 ; WX 600 ; N U ; B 17 -18 583 562 ;
|
| 80 |
+
C 86 ; WX 600 ; N V ; B -4 -13 604 562 ;
|
| 81 |
+
C 87 ; WX 600 ; N W ; B -3 -13 603 562 ;
|
| 82 |
+
C 88 ; WX 600 ; N X ; B 23 0 577 562 ;
|
| 83 |
+
C 89 ; WX 600 ; N Y ; B 24 0 576 562 ;
|
| 84 |
+
C 90 ; WX 600 ; N Z ; B 86 0 514 562 ;
|
| 85 |
+
C 91 ; WX 600 ; N bracketleft ; B 269 -108 442 622 ;
|
| 86 |
+
C 92 ; WX 600 ; N backslash ; B 118 -80 482 629 ;
|
| 87 |
+
C 93 ; WX 600 ; N bracketright ; B 158 -108 331 622 ;
|
| 88 |
+
C 94 ; WX 600 ; N asciicircum ; B 94 354 506 622 ;
|
| 89 |
+
C 95 ; WX 600 ; N underscore ; B 0 -125 600 -75 ;
|
| 90 |
+
C 96 ; WX 600 ; N quoteleft ; B 224 328 387 562 ;
|
| 91 |
+
C 97 ; WX 600 ; N a ; B 53 -15 559 441 ;
|
| 92 |
+
C 98 ; WX 600 ; N b ; B 14 -15 575 629 ;
|
| 93 |
+
C 99 ; WX 600 ; N c ; B 66 -15 529 441 ;
|
| 94 |
+
C 100 ; WX 600 ; N d ; B 45 -15 591 629 ;
|
| 95 |
+
C 101 ; WX 600 ; N e ; B 66 -15 548 441 ;
|
| 96 |
+
C 102 ; WX 600 ; N f ; B 114 0 531 629 ; L i fi ; L l fl ;
|
| 97 |
+
C 103 ; WX 600 ; N g ; B 45 -157 566 441 ;
|
| 98 |
+
C 104 ; WX 600 ; N h ; B 18 0 582 629 ;
|
| 99 |
+
C 105 ; WX 600 ; N i ; B 95 0 505 657 ;
|
| 100 |
+
C 106 ; WX 600 ; N j ; B 82 -157 410 657 ;
|
| 101 |
+
C 107 ; WX 600 ; N k ; B 43 0 580 629 ;
|
| 102 |
+
C 108 ; WX 600 ; N l ; B 95 0 505 629 ;
|
| 103 |
+
C 109 ; WX 600 ; N m ; B -5 0 605 441 ;
|
| 104 |
+
C 110 ; WX 600 ; N n ; B 26 0 575 441 ;
|
| 105 |
+
C 111 ; WX 600 ; N o ; B 62 -15 538 441 ;
|
| 106 |
+
C 112 ; WX 600 ; N p ; B 9 -157 555 441 ;
|
| 107 |
+
C 113 ; WX 600 ; N q ; B 45 -157 591 441 ;
|
| 108 |
+
C 114 ; WX 600 ; N r ; B 60 0 559 441 ;
|
| 109 |
+
C 115 ; WX 600 ; N s ; B 80 -15 513 441 ;
|
| 110 |
+
C 116 ; WX 600 ; N t ; B 87 -15 530 561 ;
|
| 111 |
+
C 117 ; WX 600 ; N u ; B 21 -15 562 426 ;
|
| 112 |
+
C 118 ; WX 600 ; N v ; B 10 -10 590 426 ;
|
| 113 |
+
C 119 ; WX 600 ; N w ; B -4 -10 604 426 ;
|
| 114 |
+
C 120 ; WX 600 ; N x ; B 20 0 580 426 ;
|
| 115 |
+
C 121 ; WX 600 ; N y ; B 7 -157 592 426 ;
|
| 116 |
+
C 122 ; WX 600 ; N z ; B 99 0 502 426 ;
|
| 117 |
+
C 123 ; WX 600 ; N braceleft ; B 182 -108 437 622 ;
|
| 118 |
+
C 124 ; WX 600 ; N bar ; B 275 -250 326 750 ;
|
| 119 |
+
C 125 ; WX 600 ; N braceright ; B 163 -108 418 622 ;
|
| 120 |
+
C 126 ; WX 600 ; N asciitilde ; B 63 197 540 320 ;
|
| 121 |
+
C 161 ; WX 600 ; N exclamdown ; B 236 -157 364 430 ;
|
| 122 |
+
C 162 ; WX 600 ; N cent ; B 96 -49 500 614 ;
|
| 123 |
+
C 163 ; WX 600 ; N sterling ; B 84 -21 521 611 ;
|
| 124 |
+
C 164 ; WX 600 ; N fraction ; B 92 -57 509 665 ;
|
| 125 |
+
C 165 ; WX 600 ; N yen ; B 26 0 574 562 ;
|
| 126 |
+
C 166 ; WX 600 ; N florin ; B 4 -143 539 622 ;
|
| 127 |
+
C 167 ; WX 600 ; N section ; B 113 -78 488 580 ;
|
| 128 |
+
C 168 ; WX 600 ; N currency ; B 73 58 527 506 ;
|
| 129 |
+
C 169 ; WX 600 ; N quotesingle ; B 259 328 341 562 ;
|
| 130 |
+
C 170 ; WX 600 ; N quotedblleft ; B 143 328 471 562 ;
|
| 131 |
+
C 171 ; WX 600 ; N guillemotleft ; B 37 70 563 446 ;
|
| 132 |
+
C 172 ; WX 600 ; N guilsinglleft ; B 149 70 451 446 ;
|
| 133 |
+
C 173 ; WX 600 ; N guilsinglright ; B 149 70 451 446 ;
|
| 134 |
+
C 174 ; WX 600 ; N fi ; B 3 0 597 629 ;
|
| 135 |
+
C 175 ; WX 600 ; N fl ; B 3 0 597 629 ;
|
| 136 |
+
C 177 ; WX 600 ; N endash ; B 75 231 525 285 ;
|
| 137 |
+
C 178 ; WX 600 ; N dagger ; B 141 -78 459 580 ;
|
| 138 |
+
C 179 ; WX 600 ; N daggerdbl ; B 141 -78 459 580 ;
|
| 139 |
+
C 180 ; WX 600 ; N periodcentered ; B 222 189 378 327 ;
|
| 140 |
+
C 182 ; WX 600 ; N paragraph ; B 50 -78 511 562 ;
|
| 141 |
+
C 183 ; WX 600 ; N bullet ; B 172 130 428 383 ;
|
| 142 |
+
C 184 ; WX 600 ; N quotesinglbase ; B 213 -134 376 100 ;
|
| 143 |
+
C 185 ; WX 600 ; N quotedblbase ; B 143 -134 457 100 ;
|
| 144 |
+
C 186 ; WX 600 ; N quotedblright ; B 143 328 457 562 ;
|
| 145 |
+
C 187 ; WX 600 ; N guillemotright ; B 37 70 563 446 ;
|
| 146 |
+
C 188 ; WX 600 ; N ellipsis ; B 37 -15 563 111 ;
|
| 147 |
+
C 189 ; WX 600 ; N perthousand ; B 3 -15 600 622 ;
|
| 148 |
+
C 191 ; WX 600 ; N questiondown ; B 108 -157 471 430 ;
|
| 149 |
+
C 193 ; WX 600 ; N grave ; B 151 497 378 672 ;
|
| 150 |
+
C 194 ; WX 600 ; N acute ; B 242 497 469 672 ;
|
| 151 |
+
C 195 ; WX 600 ; N circumflex ; B 124 477 476 654 ;
|
| 152 |
+
C 196 ; WX 600 ; N tilde ; B 105 489 503 606 ;
|
| 153 |
+
C 197 ; WX 600 ; N macron ; B 120 525 480 565 ;
|
| 154 |
+
C 198 ; WX 600 ; N breve ; B 153 501 447 609 ;
|
| 155 |
+
C 199 ; WX 600 ; N dotaccent ; B 249 537 352 640 ;
|
| 156 |
+
C 200 ; WX 600 ; N dieresis ; B 148 537 453 640 ;
|
| 157 |
+
C 202 ; WX 600 ; N ring ; B 218 463 382 627 ;
|
| 158 |
+
C 203 ; WX 600 ; N cedilla ; B 224 -151 362 10 ;
|
| 159 |
+
C 205 ; WX 600 ; N hungarumlaut ; B 133 497 540 672 ;
|
| 160 |
+
C 206 ; WX 600 ; N ogonek ; B 211 -172 407 4 ;
|
| 161 |
+
C 207 ; WX 600 ; N caron ; B 124 492 476 669 ;
|
| 162 |
+
C 208 ; WX 600 ; N emdash ; B 0 231 600 285 ;
|
| 163 |
+
C 225 ; WX 600 ; N AE ; B 3 0 550 562 ;
|
| 164 |
+
C 227 ; WX 600 ; N ordfeminine ; B 156 249 442 580 ;
|
| 165 |
+
C 232 ; WX 600 ; N Lslash ; B 47 0 554 562 ;
|
| 166 |
+
C 233 ; WX 600 ; N Oslash ; B 43 -80 557 629 ;
|
| 167 |
+
C 234 ; WX 600 ; N OE ; B 7 0 567 562 ;
|
| 168 |
+
C 235 ; WX 600 ; N ordmasculine ; B 157 249 443 580 ;
|
| 169 |
+
C 241 ; WX 600 ; N ae ; B 19 -15 570 441 ;
|
| 170 |
+
C 245 ; WX 600 ; N dotlessi ; B 95 0 505 426 ;
|
| 171 |
+
C 248 ; WX 600 ; N lslash ; B 95 0 505 629 ;
|
| 172 |
+
C 249 ; WX 600 ; N oslash ; B 62 -80 538 506 ;
|
| 173 |
+
C 250 ; WX 600 ; N oe ; B 19 -15 559 441 ;
|
| 174 |
+
C 251 ; WX 600 ; N germandbls ; B 48 -15 588 629 ;
|
| 175 |
+
C -1 ; WX 600 ; N Idieresis ; B 96 0 504 753 ;
|
| 176 |
+
C -1 ; WX 600 ; N eacute ; B 66 -15 548 672 ;
|
| 177 |
+
C -1 ; WX 600 ; N abreve ; B 53 -15 559 609 ;
|
| 178 |
+
C -1 ; WX 600 ; N uhungarumlaut ; B 21 -15 580 672 ;
|
| 179 |
+
C -1 ; WX 600 ; N ecaron ; B 66 -15 548 669 ;
|
| 180 |
+
C -1 ; WX 600 ; N Ydieresis ; B 24 0 576 753 ;
|
| 181 |
+
C -1 ; WX 600 ; N divide ; B 87 48 513 467 ;
|
| 182 |
+
C -1 ; WX 600 ; N Yacute ; B 24 0 576 805 ;
|
| 183 |
+
C -1 ; WX 600 ; N Acircumflex ; B 3 0 597 787 ;
|
| 184 |
+
C -1 ; WX 600 ; N aacute ; B 53 -15 559 672 ;
|
| 185 |
+
C -1 ; WX 600 ; N Ucircumflex ; B 17 -18 583 787 ;
|
| 186 |
+
C -1 ; WX 600 ; N yacute ; B 7 -157 592 672 ;
|
| 187 |
+
C -1 ; WX 600 ; N scommaaccent ; B 80 -250 513 441 ;
|
| 188 |
+
C -1 ; WX 600 ; N ecircumflex ; B 66 -15 548 654 ;
|
| 189 |
+
C -1 ; WX 600 ; N Uring ; B 17 -18 583 760 ;
|
| 190 |
+
C -1 ; WX 600 ; N Udieresis ; B 17 -18 583 753 ;
|
| 191 |
+
C -1 ; WX 600 ; N aogonek ; B 53 -172 587 441 ;
|
| 192 |
+
C -1 ; WX 600 ; N Uacute ; B 17 -18 583 805 ;
|
| 193 |
+
C -1 ; WX 600 ; N uogonek ; B 21 -172 590 426 ;
|
| 194 |
+
C -1 ; WX 600 ; N Edieresis ; B 53 0 550 753 ;
|
| 195 |
+
C -1 ; WX 600 ; N Dcroat ; B 30 0 574 562 ;
|
| 196 |
+
C -1 ; WX 600 ; N commaaccent ; B 198 -250 335 -58 ;
|
| 197 |
+
C -1 ; WX 600 ; N copyright ; B 0 -18 600 580 ;
|
| 198 |
+
C -1 ; WX 600 ; N Emacron ; B 53 0 550 698 ;
|
| 199 |
+
C -1 ; WX 600 ; N ccaron ; B 66 -15 529 669 ;
|
| 200 |
+
C -1 ; WX 600 ; N aring ; B 53 -15 559 627 ;
|
| 201 |
+
C -1 ; WX 600 ; N Ncommaaccent ; B 7 -250 593 562 ;
|
| 202 |
+
C -1 ; WX 600 ; N lacute ; B 95 0 505 805 ;
|
| 203 |
+
C -1 ; WX 600 ; N agrave ; B 53 -15 559 672 ;
|
| 204 |
+
C -1 ; WX 600 ; N Tcommaaccent ; B 38 -250 563 562 ;
|
| 205 |
+
C -1 ; WX 600 ; N Cacute ; B 41 -18 540 805 ;
|
| 206 |
+
C -1 ; WX 600 ; N atilde ; B 53 -15 559 606 ;
|
| 207 |
+
C -1 ; WX 600 ; N Edotaccent ; B 53 0 550 753 ;
|
| 208 |
+
C -1 ; WX 600 ; N scaron ; B 80 -15 513 669 ;
|
| 209 |
+
C -1 ; WX 600 ; N scedilla ; B 80 -151 513 441 ;
|
| 210 |
+
C -1 ; WX 600 ; N iacute ; B 95 0 505 672 ;
|
| 211 |
+
C -1 ; WX 600 ; N lozenge ; B 18 0 443 706 ;
|
| 212 |
+
C -1 ; WX 600 ; N Rcaron ; B 38 0 588 802 ;
|
| 213 |
+
C -1 ; WX 600 ; N Gcommaaccent ; B 31 -250 575 580 ;
|
| 214 |
+
C -1 ; WX 600 ; N ucircumflex ; B 21 -15 562 654 ;
|
| 215 |
+
C -1 ; WX 600 ; N acircumflex ; B 53 -15 559 654 ;
|
| 216 |
+
C -1 ; WX 600 ; N Amacron ; B 3 0 597 698 ;
|
| 217 |
+
C -1 ; WX 600 ; N rcaron ; B 60 0 559 669 ;
|
| 218 |
+
C -1 ; WX 600 ; N ccedilla ; B 66 -151 529 441 ;
|
| 219 |
+
C -1 ; WX 600 ; N Zdotaccent ; B 86 0 514 753 ;
|
| 220 |
+
C -1 ; WX 600 ; N Thorn ; B 79 0 538 562 ;
|
| 221 |
+
C -1 ; WX 600 ; N Omacron ; B 43 -18 557 698 ;
|
| 222 |
+
C -1 ; WX 600 ; N Racute ; B 38 0 588 805 ;
|
| 223 |
+
C -1 ; WX 600 ; N Sacute ; B 72 -20 529 805 ;
|
| 224 |
+
C -1 ; WX 600 ; N dcaron ; B 45 -15 715 629 ;
|
| 225 |
+
C -1 ; WX 600 ; N Umacron ; B 17 -18 583 698 ;
|
| 226 |
+
C -1 ; WX 600 ; N uring ; B 21 -15 562 627 ;
|
| 227 |
+
C -1 ; WX 600 ; N threesuperior ; B 155 240 406 622 ;
|
| 228 |
+
C -1 ; WX 600 ; N Ograve ; B 43 -18 557 805 ;
|
| 229 |
+
C -1 ; WX 600 ; N Agrave ; B 3 0 597 805 ;
|
| 230 |
+
C -1 ; WX 600 ; N Abreve ; B 3 0 597 732 ;
|
| 231 |
+
C -1 ; WX 600 ; N multiply ; B 87 43 515 470 ;
|
| 232 |
+
C -1 ; WX 600 ; N uacute ; B 21 -15 562 672 ;
|
| 233 |
+
C -1 ; WX 600 ; N Tcaron ; B 38 0 563 802 ;
|
| 234 |
+
C -1 ; WX 600 ; N partialdiff ; B 17 -38 459 710 ;
|
| 235 |
+
C -1 ; WX 600 ; N ydieresis ; B 7 -157 592 620 ;
|
| 236 |
+
C -1 ; WX 600 ; N Nacute ; B 7 -13 593 805 ;
|
| 237 |
+
C -1 ; WX 600 ; N icircumflex ; B 94 0 505 654 ;
|
| 238 |
+
C -1 ; WX 600 ; N Ecircumflex ; B 53 0 550 787 ;
|
| 239 |
+
C -1 ; WX 600 ; N adieresis ; B 53 -15 559 620 ;
|
| 240 |
+
C -1 ; WX 600 ; N edieresis ; B 66 -15 548 620 ;
|
| 241 |
+
C -1 ; WX 600 ; N cacute ; B 66 -15 529 672 ;
|
| 242 |
+
C -1 ; WX 600 ; N nacute ; B 26 0 575 672 ;
|
| 243 |
+
C -1 ; WX 600 ; N umacron ; B 21 -15 562 565 ;
|
| 244 |
+
C -1 ; WX 600 ; N Ncaron ; B 7 -13 593 802 ;
|
| 245 |
+
C -1 ; WX 600 ; N Iacute ; B 96 0 504 805 ;
|
| 246 |
+
C -1 ; WX 600 ; N plusminus ; B 87 44 513 558 ;
|
| 247 |
+
C -1 ; WX 600 ; N brokenbar ; B 275 -175 326 675 ;
|
| 248 |
+
C -1 ; WX 600 ; N registered ; B 0 -18 600 580 ;
|
| 249 |
+
C -1 ; WX 600 ; N Gbreve ; B 31 -18 575 732 ;
|
| 250 |
+
C -1 ; WX 600 ; N Idotaccent ; B 96 0 504 753 ;
|
| 251 |
+
C -1 ; WX 600 ; N summation ; B 15 -10 585 706 ;
|
| 252 |
+
C -1 ; WX 600 ; N Egrave ; B 53 0 550 805 ;
|
| 253 |
+
C -1 ; WX 600 ; N racute ; B 60 0 559 672 ;
|
| 254 |
+
C -1 ; WX 600 ; N omacron ; B 62 -15 538 565 ;
|
| 255 |
+
C -1 ; WX 600 ; N Zacute ; B 86 0 514 805 ;
|
| 256 |
+
C -1 ; WX 600 ; N Zcaron ; B 86 0 514 802 ;
|
| 257 |
+
C -1 ; WX 600 ; N greaterequal ; B 98 0 502 710 ;
|
| 258 |
+
C -1 ; WX 600 ; N Eth ; B 30 0 574 562 ;
|
| 259 |
+
C -1 ; WX 600 ; N Ccedilla ; B 41 -151 540 580 ;
|
| 260 |
+
C -1 ; WX 600 ; N lcommaaccent ; B 95 -250 505 629 ;
|
| 261 |
+
C -1 ; WX 600 ; N tcaron ; B 87 -15 530 717 ;
|
| 262 |
+
C -1 ; WX 600 ; N eogonek ; B 66 -172 548 441 ;
|
| 263 |
+
C -1 ; WX 600 ; N Uogonek ; B 17 -172 583 562 ;
|
| 264 |
+
C -1 ; WX 600 ; N Aacute ; B 3 0 597 805 ;
|
| 265 |
+
C -1 ; WX 600 ; N Adieresis ; B 3 0 597 753 ;
|
| 266 |
+
C -1 ; WX 600 ; N egrave ; B 66 -15 548 672 ;
|
| 267 |
+
C -1 ; WX 600 ; N zacute ; B 99 0 502 672 ;
|
| 268 |
+
C -1 ; WX 600 ; N iogonek ; B 95 -172 505 657 ;
|
| 269 |
+
C -1 ; WX 600 ; N Oacute ; B 43 -18 557 805 ;
|
| 270 |
+
C -1 ; WX 600 ; N oacute ; B 62 -15 538 672 ;
|
| 271 |
+
C -1 ; WX 600 ; N amacron ; B 53 -15 559 565 ;
|
| 272 |
+
C -1 ; WX 600 ; N sacute ; B 80 -15 513 672 ;
|
| 273 |
+
C -1 ; WX 600 ; N idieresis ; B 95 0 505 620 ;
|
| 274 |
+
C -1 ; WX 600 ; N Ocircumflex ; B 43 -18 557 787 ;
|
| 275 |
+
C -1 ; WX 600 ; N Ugrave ; B 17 -18 583 805 ;
|
| 276 |
+
C -1 ; WX 600 ; N Delta ; B 6 0 598 688 ;
|
| 277 |
+
C -1 ; WX 600 ; N thorn ; B -6 -157 555 629 ;
|
| 278 |
+
C -1 ; WX 600 ; N twosuperior ; B 177 249 424 622 ;
|
| 279 |
+
C -1 ; WX 600 ; N Odieresis ; B 43 -18 557 753 ;
|
| 280 |
+
C -1 ; WX 600 ; N mu ; B 21 -157 562 426 ;
|
| 281 |
+
C -1 ; WX 600 ; N igrave ; B 95 0 505 672 ;
|
| 282 |
+
C -1 ; WX 600 ; N ohungarumlaut ; B 62 -15 580 672 ;
|
| 283 |
+
C -1 ; WX 600 ; N Eogonek ; B 53 -172 561 562 ;
|
| 284 |
+
C -1 ; WX 600 ; N dcroat ; B 45 -15 591 629 ;
|
| 285 |
+
C -1 ; WX 600 ; N threequarters ; B 8 -56 593 666 ;
|
| 286 |
+
C -1 ; WX 600 ; N Scedilla ; B 72 -151 529 580 ;
|
| 287 |
+
C -1 ; WX 600 ; N lcaron ; B 95 0 533 629 ;
|
| 288 |
+
C -1 ; WX 600 ; N Kcommaaccent ; B 38 -250 582 562 ;
|
| 289 |
+
C -1 ; WX 600 ; N Lacute ; B 47 0 554 805 ;
|
| 290 |
+
C -1 ; WX 600 ; N trademark ; B -23 263 623 562 ;
|
| 291 |
+
C -1 ; WX 600 ; N edotaccent ; B 66 -15 548 620 ;
|
| 292 |
+
C -1 ; WX 600 ; N Igrave ; B 96 0 504 805 ;
|
| 293 |
+
C -1 ; WX 600 ; N Imacron ; B 96 0 504 698 ;
|
| 294 |
+
C -1 ; WX 600 ; N Lcaron ; B 47 0 554 562 ;
|
| 295 |
+
C -1 ; WX 600 ; N onehalf ; B 0 -57 611 665 ;
|
| 296 |
+
C -1 ; WX 600 ; N lessequal ; B 98 0 502 710 ;
|
| 297 |
+
C -1 ; WX 600 ; N ocircumflex ; B 62 -15 538 654 ;
|
| 298 |
+
C -1 ; WX 600 ; N ntilde ; B 26 0 575 606 ;
|
| 299 |
+
C -1 ; WX 600 ; N Uhungarumlaut ; B 17 -18 590 805 ;
|
| 300 |
+
C -1 ; WX 600 ; N Eacute ; B 53 0 550 805 ;
|
| 301 |
+
C -1 ; WX 600 ; N emacron ; B 66 -15 548 565 ;
|
| 302 |
+
C -1 ; WX 600 ; N gbreve ; B 45 -157 566 609 ;
|
| 303 |
+
C -1 ; WX 600 ; N onequarter ; B 0 -57 600 665 ;
|
| 304 |
+
C -1 ; WX 600 ; N Scaron ; B 72 -20 529 802 ;
|
| 305 |
+
C -1 ; WX 600 ; N Scommaaccent ; B 72 -250 529 580 ;
|
| 306 |
+
C -1 ; WX 600 ; N Ohungarumlaut ; B 43 -18 580 805 ;
|
| 307 |
+
C -1 ; WX 600 ; N degree ; B 123 269 477 622 ;
|
| 308 |
+
C -1 ; WX 600 ; N ograve ; B 62 -15 538 672 ;
|
| 309 |
+
C -1 ; WX 600 ; N Ccaron ; B 41 -18 540 802 ;
|
| 310 |
+
C -1 ; WX 600 ; N ugrave ; B 21 -15 562 672 ;
|
| 311 |
+
C -1 ; WX 600 ; N radical ; B 3 -15 597 792 ;
|
| 312 |
+
C -1 ; WX 600 ; N Dcaron ; B 43 0 574 802 ;
|
| 313 |
+
C -1 ; WX 600 ; N rcommaaccent ; B 60 -250 559 441 ;
|
| 314 |
+
C -1 ; WX 600 ; N Ntilde ; B 7 -13 593 729 ;
|
| 315 |
+
C -1 ; WX 600 ; N otilde ; B 62 -15 538 606 ;
|
| 316 |
+
C -1 ; WX 600 ; N Rcommaaccent ; B 38 -250 588 562 ;
|
| 317 |
+
C -1 ; WX 600 ; N Lcommaaccent ; B 47 -250 554 562 ;
|
| 318 |
+
C -1 ; WX 600 ; N Atilde ; B 3 0 597 729 ;
|
| 319 |
+
C -1 ; WX 600 ; N Aogonek ; B 3 -172 608 562 ;
|
| 320 |
+
C -1 ; WX 600 ; N Aring ; B 3 0 597 750 ;
|
| 321 |
+
C -1 ; WX 600 ; N Otilde ; B 43 -18 557 729 ;
|
| 322 |
+
C -1 ; WX 600 ; N zdotaccent ; B 99 0 502 620 ;
|
| 323 |
+
C -1 ; WX 600 ; N Ecaron ; B 53 0 550 802 ;
|
| 324 |
+
C -1 ; WX 600 ; N Iogonek ; B 96 -172 504 562 ;
|
| 325 |
+
C -1 ; WX 600 ; N kcommaaccent ; B 43 -250 580 629 ;
|
| 326 |
+
C -1 ; WX 600 ; N minus ; B 80 232 520 283 ;
|
| 327 |
+
C -1 ; WX 600 ; N Icircumflex ; B 96 0 504 787 ;
|
| 328 |
+
C -1 ; WX 600 ; N ncaron ; B 26 0 575 669 ;
|
| 329 |
+
C -1 ; WX 600 ; N tcommaaccent ; B 87 -250 530 561 ;
|
| 330 |
+
C -1 ; WX 600 ; N logicalnot ; B 87 108 513 369 ;
|
| 331 |
+
C -1 ; WX 600 ; N odieresis ; B 62 -15 538 620 ;
|
| 332 |
+
C -1 ; WX 600 ; N udieresis ; B 21 -15 562 620 ;
|
| 333 |
+
C -1 ; WX 600 ; N notequal ; B 15 -16 540 529 ;
|
| 334 |
+
C -1 ; WX 600 ; N gcommaaccent ; B 45 -157 566 708 ;
|
| 335 |
+
C -1 ; WX 600 ; N eth ; B 62 -15 538 629 ;
|
| 336 |
+
C -1 ; WX 600 ; N zcaron ; B 99 0 502 669 ;
|
| 337 |
+
C -1 ; WX 600 ; N ncommaaccent ; B 26 -250 575 441 ;
|
| 338 |
+
C -1 ; WX 600 ; N onesuperior ; B 172 249 428 622 ;
|
| 339 |
+
C -1 ; WX 600 ; N imacron ; B 95 0 505 565 ;
|
| 340 |
+
C -1 ; WX 600 ; N Euro ; B 0 0 0 0 ;
|
| 341 |
+
EndCharMetrics
|
| 342 |
+
EndFontMetrics
|
shared/package-files/31/31d7376ec16989846d88c976c3e615f3b4e26178b65f009901ac786a713bc170/blob
ADDED
|
Binary file (58 kB). View file
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
import cmath
|
| 3 |
+
import collections.abc
|
| 4 |
+
import contextlib
|
| 5 |
+
import warnings
|
| 6 |
+
from typing import (
|
| 7 |
+
Any,
|
| 8 |
+
Callable,
|
| 9 |
+
Collection,
|
| 10 |
+
Dict,
|
| 11 |
+
List,
|
| 12 |
+
NoReturn,
|
| 13 |
+
Optional,
|
| 14 |
+
Sequence,
|
| 15 |
+
Tuple,
|
| 16 |
+
Type,
|
| 17 |
+
Union,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
NUMPY_AVAILABLE = True
|
| 26 |
+
except ModuleNotFoundError:
|
| 27 |
+
NUMPY_AVAILABLE = False
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ErrorMeta(Exception):
|
| 31 |
+
"""Internal testing exception that makes that carries error metadata."""
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self, type: Type[Exception], msg: str, *, id: Tuple[Any, ...] = ()
|
| 35 |
+
) -> None:
|
| 36 |
+
super().__init__(
|
| 37 |
+
"If you are a user and see this message during normal operation "
|
| 38 |
+
"please file an issue at https://github.com/pytorch/pytorch/issues. "
|
| 39 |
+
"If you are a developer and working on the comparison functions, please `raise ErrorMeta().to_error()` "
|
| 40 |
+
"for user facing errors."
|
| 41 |
+
)
|
| 42 |
+
self.type = type
|
| 43 |
+
self.msg = msg
|
| 44 |
+
self.id = id
|
| 45 |
+
|
| 46 |
+
def to_error(
|
| 47 |
+
self, msg: Optional[Union[str, Callable[[str], str]]] = None
|
| 48 |
+
) -> Exception:
|
| 49 |
+
if not isinstance(msg, str):
|
| 50 |
+
generated_msg = self.msg
|
| 51 |
+
if self.id:
|
| 52 |
+
generated_msg += f"\n\nThe failure occurred for item {''.join(str([item]) for item in self.id)}"
|
| 53 |
+
|
| 54 |
+
msg = msg(generated_msg) if callable(msg) else generated_msg
|
| 55 |
+
|
| 56 |
+
return self.type(msg)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# Some analysis of tolerance by logging tests from test_torch.py can be found in
|
| 60 |
+
# https://github.com/pytorch/pytorch/pull/32538.
|
| 61 |
+
# {dtype: (rtol, atol)}
|
| 62 |
+
_DTYPE_PRECISIONS = {
|
| 63 |
+
torch.float16: (0.001, 1e-5),
|
| 64 |
+
torch.bfloat16: (0.016, 1e-5),
|
| 65 |
+
torch.float32: (1.3e-6, 1e-5),
|
| 66 |
+
torch.float64: (1e-7, 1e-7),
|
| 67 |
+
torch.complex32: (0.001, 1e-5),
|
| 68 |
+
torch.complex64: (1.3e-6, 1e-5),
|
| 69 |
+
torch.complex128: (1e-7, 1e-7),
|
| 70 |
+
}
|
| 71 |
+
# The default tolerances of torch.float32 are used for quantized dtypes, because quantized tensors are compared in
|
| 72 |
+
# their dequantized and floating point representation. For more details see `TensorLikePair._compare_quantized_values`
|
| 73 |
+
_DTYPE_PRECISIONS.update(
|
| 74 |
+
dict.fromkeys(
|
| 75 |
+
(torch.quint8, torch.quint2x4, torch.quint4x2, torch.qint8, torch.qint32),
|
| 76 |
+
_DTYPE_PRECISIONS[torch.float32],
|
| 77 |
+
)
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def default_tolerances(
|
| 82 |
+
*inputs: Union[torch.Tensor, torch.dtype],
|
| 83 |
+
dtype_precisions: Optional[Dict[torch.dtype, Tuple[float, float]]] = None,
|
| 84 |
+
) -> Tuple[float, float]:
|
| 85 |
+
"""Returns the default absolute and relative testing tolerances for a set of inputs based on the dtype.
|
| 86 |
+
|
| 87 |
+
See :func:`assert_close` for a table of the default tolerance for each dtype.
|
| 88 |
+
|
| 89 |
+
Returns:
|
| 90 |
+
(Tuple[float, float]): Loosest tolerances of all input dtypes.
|
| 91 |
+
"""
|
| 92 |
+
dtypes = []
|
| 93 |
+
for input in inputs:
|
| 94 |
+
if isinstance(input, torch.Tensor):
|
| 95 |
+
dtypes.append(input.dtype)
|
| 96 |
+
elif isinstance(input, torch.dtype):
|
| 97 |
+
dtypes.append(input)
|
| 98 |
+
else:
|
| 99 |
+
raise TypeError(
|
| 100 |
+
f"Expected a torch.Tensor or a torch.dtype, but got {type(input)} instead."
|
| 101 |
+
)
|
| 102 |
+
dtype_precisions = dtype_precisions or _DTYPE_PRECISIONS
|
| 103 |
+
rtols, atols = zip(*[dtype_precisions.get(dtype, (0.0, 0.0)) for dtype in dtypes])
|
| 104 |
+
return max(rtols), max(atols)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def get_tolerances(
|
| 108 |
+
*inputs: Union[torch.Tensor, torch.dtype],
|
| 109 |
+
rtol: Optional[float],
|
| 110 |
+
atol: Optional[float],
|
| 111 |
+
id: Tuple[Any, ...] = (),
|
| 112 |
+
) -> Tuple[float, float]:
|
| 113 |
+
"""Gets absolute and relative to be used for numeric comparisons.
|
| 114 |
+
|
| 115 |
+
If both ``rtol`` and ``atol`` are specified, this is a no-op. If both are not specified, the return value of
|
| 116 |
+
:func:`default_tolerances` is used.
|
| 117 |
+
|
| 118 |
+
Raises:
|
| 119 |
+
ErrorMeta: With :class:`ValueError`, if only ``rtol`` or ``atol`` is specified.
|
| 120 |
+
|
| 121 |
+
Returns:
|
| 122 |
+
(Tuple[float, float]): Valid absolute and relative tolerances.
|
| 123 |
+
"""
|
| 124 |
+
if (rtol is None) ^ (atol is None):
|
| 125 |
+
# We require both tolerance to be omitted or specified, because specifying only one might lead to surprising
|
| 126 |
+
# results. Imagine setting atol=0.0 and the tensors still match because rtol>0.0.
|
| 127 |
+
raise ErrorMeta(
|
| 128 |
+
ValueError,
|
| 129 |
+
f"Both 'rtol' and 'atol' must be either specified or omitted, "
|
| 130 |
+
f"but got no {'rtol' if rtol is None else 'atol'}.",
|
| 131 |
+
id=id,
|
| 132 |
+
)
|
| 133 |
+
elif rtol is not None and atol is not None:
|
| 134 |
+
return rtol, atol
|
| 135 |
+
else:
|
| 136 |
+
return default_tolerances(*inputs)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _make_mismatch_msg(
|
| 140 |
+
*,
|
| 141 |
+
default_identifier: str,
|
| 142 |
+
identifier: Optional[Union[str, Callable[[str], str]]] = None,
|
| 143 |
+
extra: Optional[str] = None,
|
| 144 |
+
abs_diff: float,
|
| 145 |
+
abs_diff_idx: Optional[Union[int, Tuple[int, ...]]] = None,
|
| 146 |
+
atol: float,
|
| 147 |
+
rel_diff: float,
|
| 148 |
+
rel_diff_idx: Optional[Union[int, Tuple[int, ...]]] = None,
|
| 149 |
+
rtol: float,
|
| 150 |
+
) -> str:
|
| 151 |
+
"""Makes a mismatch error message for numeric values.
|
| 152 |
+
|
| 153 |
+
Args:
|
| 154 |
+
default_identifier (str): Default description of the compared values, e.g. "Tensor-likes".
|
| 155 |
+
identifier (Optional[Union[str, Callable[[str], str]]]): Optional identifier that overrides
|
| 156 |
+
``default_identifier``. Can be passed as callable in which case it will be called with
|
| 157 |
+
``default_identifier`` to create the description at runtime.
|
| 158 |
+
extra (Optional[str]): Extra information to be placed after the message header and the mismatch statistics.
|
| 159 |
+
abs_diff (float): Absolute difference.
|
| 160 |
+
abs_diff_idx (Optional[Union[int, Tuple[int, ...]]]): Optional index of the absolute difference.
|
| 161 |
+
atol (float): Allowed absolute tolerance. Will only be added to mismatch statistics if it or ``rtol`` are
|
| 162 |
+
``> 0``.
|
| 163 |
+
rel_diff (float): Relative difference.
|
| 164 |
+
rel_diff_idx (Optional[Union[int, Tuple[int, ...]]]): Optional index of the relative difference.
|
| 165 |
+
rtol (float): Allowed relative tolerance. Will only be added to mismatch statistics if it or ``atol`` are
|
| 166 |
+
``> 0``.
|
| 167 |
+
"""
|
| 168 |
+
equality = rtol == 0 and atol == 0
|
| 169 |
+
|
| 170 |
+
def make_diff_msg(
|
| 171 |
+
*,
|
| 172 |
+
type: str,
|
| 173 |
+
diff: float,
|
| 174 |
+
idx: Optional[Union[int, Tuple[int, ...]]],
|
| 175 |
+
tol: float,
|
| 176 |
+
) -> str:
|
| 177 |
+
if idx is None:
|
| 178 |
+
msg = f"{type.title()} difference: {diff}"
|
| 179 |
+
else:
|
| 180 |
+
msg = f"Greatest {type} difference: {diff} at index {idx}"
|
| 181 |
+
if not equality:
|
| 182 |
+
msg += f" (up to {tol} allowed)"
|
| 183 |
+
return msg + "\n"
|
| 184 |
+
|
| 185 |
+
if identifier is None:
|
| 186 |
+
identifier = default_identifier
|
| 187 |
+
elif callable(identifier):
|
| 188 |
+
identifier = identifier(default_identifier)
|
| 189 |
+
|
| 190 |
+
msg = f"{identifier} are not {'equal' if equality else 'close'}!\n\n"
|
| 191 |
+
|
| 192 |
+
if extra:
|
| 193 |
+
msg += f"{extra.strip()}\n"
|
| 194 |
+
|
| 195 |
+
msg += make_diff_msg(type="absolute", diff=abs_diff, idx=abs_diff_idx, tol=atol)
|
| 196 |
+
msg += make_diff_msg(type="relative", diff=rel_diff, idx=rel_diff_idx, tol=rtol)
|
| 197 |
+
|
| 198 |
+
return msg.strip()
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def make_scalar_mismatch_msg(
|
| 202 |
+
actual: Union[bool, int, float, complex],
|
| 203 |
+
expected: Union[bool, int, float, complex],
|
| 204 |
+
*,
|
| 205 |
+
rtol: float,
|
| 206 |
+
atol: float,
|
| 207 |
+
identifier: Optional[Union[str, Callable[[str], str]]] = None,
|
| 208 |
+
) -> str:
|
| 209 |
+
"""Makes a mismatch error message for scalars.
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
actual (Union[bool, int, float, complex]): Actual scalar.
|
| 213 |
+
expected (Union[bool, int, float, complex]): Expected scalar.
|
| 214 |
+
rtol (float): Relative tolerance.
|
| 215 |
+
atol (float): Absolute tolerance.
|
| 216 |
+
identifier (Optional[Union[str, Callable[[str], str]]]): Optional description for the scalars. Can be passed
|
| 217 |
+
as callable in which case it will be called by the default value to create the description at runtime.
|
| 218 |
+
Defaults to "Scalars".
|
| 219 |
+
"""
|
| 220 |
+
abs_diff = abs(actual - expected)
|
| 221 |
+
rel_diff = float("inf") if expected == 0 else abs_diff / abs(expected)
|
| 222 |
+
return _make_mismatch_msg(
|
| 223 |
+
default_identifier="Scalars",
|
| 224 |
+
identifier=identifier,
|
| 225 |
+
extra=f"Expected {expected} but got {actual}.",
|
| 226 |
+
abs_diff=abs_diff,
|
| 227 |
+
atol=atol,
|
| 228 |
+
rel_diff=rel_diff,
|
| 229 |
+
rtol=rtol,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def make_tensor_mismatch_msg(
|
| 234 |
+
actual: torch.Tensor,
|
| 235 |
+
expected: torch.Tensor,
|
| 236 |
+
matches: torch.Tensor,
|
| 237 |
+
*,
|
| 238 |
+
rtol: float,
|
| 239 |
+
atol: float,
|
| 240 |
+
identifier: Optional[Union[str, Callable[[str], str]]] = None,
|
| 241 |
+
):
|
| 242 |
+
"""Makes a mismatch error message for tensors.
|
| 243 |
+
|
| 244 |
+
Args:
|
| 245 |
+
actual (torch.Tensor): Actual tensor.
|
| 246 |
+
expected (torch.Tensor): Expected tensor.
|
| 247 |
+
matches (torch.Tensor): Boolean mask of the same shape as ``actual`` and ``expected`` that indicates the
|
| 248 |
+
location of matches.
|
| 249 |
+
rtol (float): Relative tolerance.
|
| 250 |
+
atol (float): Absolute tolerance.
|
| 251 |
+
identifier (Optional[Union[str, Callable[[str], str]]]): Optional description for the tensors. Can be passed
|
| 252 |
+
as callable in which case it will be called by the default value to create the description at runtime.
|
| 253 |
+
Defaults to "Tensor-likes".
|
| 254 |
+
"""
|
| 255 |
+
|
| 256 |
+
def unravel_flat_index(flat_index: int) -> Tuple[int, ...]:
|
| 257 |
+
if not matches.shape:
|
| 258 |
+
return ()
|
| 259 |
+
|
| 260 |
+
inverse_index = []
|
| 261 |
+
for size in matches.shape[::-1]:
|
| 262 |
+
div, mod = divmod(flat_index, size)
|
| 263 |
+
flat_index = div
|
| 264 |
+
inverse_index.append(mod)
|
| 265 |
+
|
| 266 |
+
return tuple(inverse_index[::-1])
|
| 267 |
+
|
| 268 |
+
number_of_elements = matches.numel()
|
| 269 |
+
total_mismatches = number_of_elements - int(torch.sum(matches))
|
| 270 |
+
extra = (
|
| 271 |
+
f"Mismatched elements: {total_mismatches} / {number_of_elements} "
|
| 272 |
+
f"({total_mismatches / number_of_elements:.1%})"
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
actual_flat = actual.flatten()
|
| 276 |
+
expected_flat = expected.flatten()
|
| 277 |
+
matches_flat = matches.flatten()
|
| 278 |
+
|
| 279 |
+
if not actual.dtype.is_floating_point and not actual.dtype.is_complex:
|
| 280 |
+
# TODO: Instead of always upcasting to int64, it would be sufficient to cast to the next higher dtype to avoid
|
| 281 |
+
# overflow
|
| 282 |
+
actual_flat = actual_flat.to(torch.int64)
|
| 283 |
+
expected_flat = expected_flat.to(torch.int64)
|
| 284 |
+
|
| 285 |
+
abs_diff = torch.abs(actual_flat - expected_flat)
|
| 286 |
+
# Ensure that only mismatches are used for the max_abs_diff computation
|
| 287 |
+
abs_diff[matches_flat] = 0
|
| 288 |
+
max_abs_diff, max_abs_diff_flat_idx = torch.max(abs_diff, 0)
|
| 289 |
+
|
| 290 |
+
rel_diff = abs_diff / torch.abs(expected_flat)
|
| 291 |
+
# Ensure that only mismatches are used for the max_rel_diff computation
|
| 292 |
+
rel_diff[matches_flat] = 0
|
| 293 |
+
max_rel_diff, max_rel_diff_flat_idx = torch.max(rel_diff, 0)
|
| 294 |
+
return _make_mismatch_msg(
|
| 295 |
+
default_identifier="Tensor-likes",
|
| 296 |
+
identifier=identifier,
|
| 297 |
+
extra=extra,
|
| 298 |
+
abs_diff=max_abs_diff.item(),
|
| 299 |
+
abs_diff_idx=unravel_flat_index(int(max_abs_diff_flat_idx)),
|
| 300 |
+
atol=atol,
|
| 301 |
+
rel_diff=max_rel_diff.item(),
|
| 302 |
+
rel_diff_idx=unravel_flat_index(int(max_rel_diff_flat_idx)),
|
| 303 |
+
rtol=rtol,
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
class UnsupportedInputs(Exception): # noqa: B903
|
| 308 |
+
"""Exception to be raised during the construction of a :class:`Pair` in case it doesn't support the inputs."""
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class Pair(abc.ABC):
|
| 312 |
+
"""ABC for all comparison pairs to be used in conjunction with :func:`assert_equal`.
|
| 313 |
+
|
| 314 |
+
Each subclass needs to overwrite :meth:`Pair.compare` that performs the actual comparison.
|
| 315 |
+
|
| 316 |
+
Each pair receives **all** options, so select the ones applicable for the subclass and forward the rest to the
|
| 317 |
+
super class. Raising an :class:`UnsupportedInputs` during constructions indicates that the pair is not able to
|
| 318 |
+
handle the inputs and the next pair type will be tried.
|
| 319 |
+
|
| 320 |
+
All other errors should be raised as :class:`ErrorMeta`. After the instantiation, :meth:`Pair._make_error_meta` can
|
| 321 |
+
be used to automatically handle overwriting the message with a user supplied one and id handling.
|
| 322 |
+
"""
|
| 323 |
+
|
| 324 |
+
def __init__(
|
| 325 |
+
self,
|
| 326 |
+
actual: Any,
|
| 327 |
+
expected: Any,
|
| 328 |
+
*,
|
| 329 |
+
id: Tuple[Any, ...] = (),
|
| 330 |
+
**unknown_parameters: Any,
|
| 331 |
+
) -> None:
|
| 332 |
+
self.actual = actual
|
| 333 |
+
self.expected = expected
|
| 334 |
+
self.id = id
|
| 335 |
+
self._unknown_parameters = unknown_parameters
|
| 336 |
+
|
| 337 |
+
@staticmethod
|
| 338 |
+
def _inputs_not_supported() -> NoReturn:
|
| 339 |
+
raise UnsupportedInputs()
|
| 340 |
+
|
| 341 |
+
@staticmethod
|
| 342 |
+
def _check_inputs_isinstance(*inputs: Any, cls: Union[Type, Tuple[Type, ...]]):
|
| 343 |
+
"""Checks if all inputs are instances of a given class and raise :class:`UnsupportedInputs` otherwise."""
|
| 344 |
+
if not all(isinstance(input, cls) for input in inputs):
|
| 345 |
+
Pair._inputs_not_supported()
|
| 346 |
+
|
| 347 |
+
def _fail(
|
| 348 |
+
self, type: Type[Exception], msg: str, *, id: Tuple[Any, ...] = ()
|
| 349 |
+
) -> NoReturn:
|
| 350 |
+
"""Raises an :class:`ErrorMeta` from a given exception type and message and the stored id.
|
| 351 |
+
|
| 352 |
+
.. warning::
|
| 353 |
+
|
| 354 |
+
If you use this before the ``super().__init__(...)`` call in the constructor, you have to pass the ``id``
|
| 355 |
+
explicitly.
|
| 356 |
+
"""
|
| 357 |
+
raise ErrorMeta(type, msg, id=self.id if not id and hasattr(self, "id") else id)
|
| 358 |
+
|
| 359 |
+
@abc.abstractmethod
|
| 360 |
+
def compare(self) -> None:
|
| 361 |
+
"""Compares the inputs and raises an :class`ErrorMeta` in case they mismatch."""
|
| 362 |
+
|
| 363 |
+
def extra_repr(self) -> Sequence[Union[str, Tuple[str, Any]]]:
|
| 364 |
+
"""Returns extra information that will be included in the representation.
|
| 365 |
+
|
| 366 |
+
Should be overwritten by all subclasses that use additional options. The representation of the object will only
|
| 367 |
+
be surfaced in case we encounter an unexpected error and thus should help debug the issue. Can be a sequence of
|
| 368 |
+
key-value-pairs or attribute names.
|
| 369 |
+
"""
|
| 370 |
+
return []
|
| 371 |
+
|
| 372 |
+
def __repr__(self) -> str:
|
| 373 |
+
head = f"{type(self).__name__}("
|
| 374 |
+
tail = ")"
|
| 375 |
+
body = [
|
| 376 |
+
f" {name}={value!s},"
|
| 377 |
+
for name, value in [
|
| 378 |
+
("id", self.id),
|
| 379 |
+
("actual", self.actual),
|
| 380 |
+
("expected", self.expected),
|
| 381 |
+
*[
|
| 382 |
+
(extra, getattr(self, extra)) if isinstance(extra, str) else extra
|
| 383 |
+
for extra in self.extra_repr()
|
| 384 |
+
],
|
| 385 |
+
]
|
| 386 |
+
]
|
| 387 |
+
return "\n".join((head, *body, *tail))
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
class ObjectPair(Pair):
|
| 391 |
+
"""Pair for any type of inputs that will be compared with the `==` operator.
|
| 392 |
+
|
| 393 |
+
.. note::
|
| 394 |
+
|
| 395 |
+
Since this will instantiate for any kind of inputs, it should only be used as fallback after all other pairs
|
| 396 |
+
couldn't handle the inputs.
|
| 397 |
+
|
| 398 |
+
"""
|
| 399 |
+
|
| 400 |
+
def compare(self) -> None:
|
| 401 |
+
try:
|
| 402 |
+
equal = self.actual == self.expected
|
| 403 |
+
except Exception as error:
|
| 404 |
+
# We are not using `self._raise_error_meta` here since we need the exception chaining
|
| 405 |
+
raise ErrorMeta(
|
| 406 |
+
ValueError,
|
| 407 |
+
f"{self.actual} == {self.expected} failed with:\n{error}.",
|
| 408 |
+
id=self.id,
|
| 409 |
+
) from error
|
| 410 |
+
|
| 411 |
+
if not equal:
|
| 412 |
+
self._fail(AssertionError, f"{self.actual} != {self.expected}")
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
class NonePair(Pair):
|
| 416 |
+
"""Pair for ``None`` inputs."""
|
| 417 |
+
|
| 418 |
+
def __init__(self, actual: Any, expected: Any, **other_parameters: Any) -> None:
|
| 419 |
+
if not (actual is None or expected is None):
|
| 420 |
+
self._inputs_not_supported()
|
| 421 |
+
|
| 422 |
+
super().__init__(actual, expected, **other_parameters)
|
| 423 |
+
|
| 424 |
+
def compare(self) -> None:
|
| 425 |
+
if not (self.actual is None and self.expected is None):
|
| 426 |
+
self._fail(
|
| 427 |
+
AssertionError, f"None mismatch: {self.actual} is not {self.expected}"
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
class BooleanPair(Pair):
|
| 432 |
+
"""Pair for :class:`bool` inputs.
|
| 433 |
+
|
| 434 |
+
.. note::
|
| 435 |
+
|
| 436 |
+
If ``numpy`` is available, also handles :class:`numpy.bool_` inputs.
|
| 437 |
+
|
| 438 |
+
"""
|
| 439 |
+
|
| 440 |
+
def __init__(
|
| 441 |
+
self,
|
| 442 |
+
actual: Any,
|
| 443 |
+
expected: Any,
|
| 444 |
+
*,
|
| 445 |
+
id: Tuple[Any, ...],
|
| 446 |
+
**other_parameters: Any,
|
| 447 |
+
) -> None:
|
| 448 |
+
actual, expected = self._process_inputs(actual, expected, id=id)
|
| 449 |
+
super().__init__(actual, expected, **other_parameters)
|
| 450 |
+
|
| 451 |
+
@property
|
| 452 |
+
def _supported_types(self) -> Tuple[Type, ...]:
|
| 453 |
+
cls: List[Type] = [bool]
|
| 454 |
+
if NUMPY_AVAILABLE:
|
| 455 |
+
cls.append(np.bool_)
|
| 456 |
+
return tuple(cls)
|
| 457 |
+
|
| 458 |
+
def _process_inputs(
|
| 459 |
+
self, actual: Any, expected: Any, *, id: Tuple[Any, ...]
|
| 460 |
+
) -> Tuple[bool, bool]:
|
| 461 |
+
self._check_inputs_isinstance(actual, expected, cls=self._supported_types)
|
| 462 |
+
actual, expected = (
|
| 463 |
+
self._to_bool(bool_like, id=id) for bool_like in (actual, expected)
|
| 464 |
+
)
|
| 465 |
+
return actual, expected
|
| 466 |
+
|
| 467 |
+
def _to_bool(self, bool_like: Any, *, id: Tuple[Any, ...]) -> bool:
|
| 468 |
+
if isinstance(bool_like, bool):
|
| 469 |
+
return bool_like
|
| 470 |
+
elif isinstance(bool_like, np.bool_):
|
| 471 |
+
return bool_like.item()
|
| 472 |
+
else:
|
| 473 |
+
raise ErrorMeta(
|
| 474 |
+
TypeError, f"Unknown boolean type {type(bool_like)}.", id=id
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
def compare(self) -> None:
|
| 478 |
+
if self.actual is not self.expected:
|
| 479 |
+
self._fail(
|
| 480 |
+
AssertionError,
|
| 481 |
+
f"Booleans mismatch: {self.actual} is not {self.expected}",
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
class NumberPair(Pair):
|
| 486 |
+
"""Pair for Python number (:class:`int`, :class:`float`, and :class:`complex`) inputs.
|
| 487 |
+
|
| 488 |
+
.. note::
|
| 489 |
+
|
| 490 |
+
If ``numpy`` is available, also handles :class:`numpy.number` inputs.
|
| 491 |
+
|
| 492 |
+
Kwargs:
|
| 493 |
+
rtol (Optional[float]): Relative tolerance. If specified ``atol`` must also be specified. If omitted, default
|
| 494 |
+
values based on the type are selected with the below table.
|
| 495 |
+
atol (Optional[float]): Absolute tolerance. If specified ``rtol`` must also be specified. If omitted, default
|
| 496 |
+
values based on the type are selected with the below table.
|
| 497 |
+
equal_nan (bool): If ``True``, two ``NaN`` values are considered equal. Defaults to ``False``.
|
| 498 |
+
check_dtype (bool): If ``True``, the type of the inputs will be checked for equality. Defaults to ``False``.
|
| 499 |
+
|
| 500 |
+
The following table displays correspondence between Python number type and the ``torch.dtype``'s. See
|
| 501 |
+
:func:`assert_close` for the corresponding tolerances.
|
| 502 |
+
|
| 503 |
+
+------------------+-------------------------------+
|
| 504 |
+
| ``type`` | corresponding ``torch.dtype`` |
|
| 505 |
+
+==================+===============================+
|
| 506 |
+
| :class:`int` | :attr:`~torch.int64` |
|
| 507 |
+
+------------------+-------------------------------+
|
| 508 |
+
| :class:`float` | :attr:`~torch.float64` |
|
| 509 |
+
+------------------+-------------------------------+
|
| 510 |
+
| :class:`complex` | :attr:`~torch.complex64` |
|
| 511 |
+
+------------------+-------------------------------+
|
| 512 |
+
"""
|
| 513 |
+
|
| 514 |
+
_TYPE_TO_DTYPE = {
|
| 515 |
+
int: torch.int64,
|
| 516 |
+
float: torch.float64,
|
| 517 |
+
complex: torch.complex128,
|
| 518 |
+
}
|
| 519 |
+
_NUMBER_TYPES = tuple(_TYPE_TO_DTYPE.keys())
|
| 520 |
+
|
| 521 |
+
def __init__(
|
| 522 |
+
self,
|
| 523 |
+
actual: Any,
|
| 524 |
+
expected: Any,
|
| 525 |
+
*,
|
| 526 |
+
id: Tuple[Any, ...] = (),
|
| 527 |
+
rtol: Optional[float] = None,
|
| 528 |
+
atol: Optional[float] = None,
|
| 529 |
+
equal_nan: bool = False,
|
| 530 |
+
check_dtype: bool = False,
|
| 531 |
+
**other_parameters: Any,
|
| 532 |
+
) -> None:
|
| 533 |
+
actual, expected = self._process_inputs(actual, expected, id=id)
|
| 534 |
+
super().__init__(actual, expected, id=id, **other_parameters)
|
| 535 |
+
|
| 536 |
+
self.rtol, self.atol = get_tolerances(
|
| 537 |
+
*[self._TYPE_TO_DTYPE[type(input)] for input in (actual, expected)],
|
| 538 |
+
rtol=rtol,
|
| 539 |
+
atol=atol,
|
| 540 |
+
id=id,
|
| 541 |
+
)
|
| 542 |
+
self.equal_nan = equal_nan
|
| 543 |
+
self.check_dtype = check_dtype
|
| 544 |
+
|
| 545 |
+
@property
|
| 546 |
+
def _supported_types(self) -> Tuple[Type, ...]:
|
| 547 |
+
cls = list(self._NUMBER_TYPES)
|
| 548 |
+
if NUMPY_AVAILABLE:
|
| 549 |
+
cls.append(np.number)
|
| 550 |
+
return tuple(cls)
|
| 551 |
+
|
| 552 |
+
def _process_inputs(
|
| 553 |
+
self, actual: Any, expected: Any, *, id: Tuple[Any, ...]
|
| 554 |
+
) -> Tuple[Union[int, float, complex], Union[int, float, complex]]:
|
| 555 |
+
self._check_inputs_isinstance(actual, expected, cls=self._supported_types)
|
| 556 |
+
actual, expected = (
|
| 557 |
+
self._to_number(number_like, id=id) for number_like in (actual, expected)
|
| 558 |
+
)
|
| 559 |
+
return actual, expected
|
| 560 |
+
|
| 561 |
+
def _to_number(
|
| 562 |
+
self, number_like: Any, *, id: Tuple[Any, ...]
|
| 563 |
+
) -> Union[int, float, complex]:
|
| 564 |
+
if NUMPY_AVAILABLE and isinstance(number_like, np.number):
|
| 565 |
+
return number_like.item()
|
| 566 |
+
elif isinstance(number_like, self._NUMBER_TYPES):
|
| 567 |
+
return number_like # type: ignore[return-value]
|
| 568 |
+
else:
|
| 569 |
+
raise ErrorMeta(
|
| 570 |
+
TypeError, f"Unknown number type {type(number_like)}.", id=id
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
def compare(self) -> None:
|
| 574 |
+
if self.check_dtype and type(self.actual) is not type(self.expected):
|
| 575 |
+
self._fail(
|
| 576 |
+
AssertionError,
|
| 577 |
+
f"The (d)types do not match: {type(self.actual)} != {type(self.expected)}.",
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
if self.actual == self.expected:
|
| 581 |
+
return
|
| 582 |
+
|
| 583 |
+
if self.equal_nan and cmath.isnan(self.actual) and cmath.isnan(self.expected):
|
| 584 |
+
return
|
| 585 |
+
|
| 586 |
+
abs_diff = abs(self.actual - self.expected)
|
| 587 |
+
tolerance = self.atol + self.rtol * abs(self.expected)
|
| 588 |
+
|
| 589 |
+
if cmath.isfinite(abs_diff) and abs_diff <= tolerance:
|
| 590 |
+
return
|
| 591 |
+
|
| 592 |
+
self._fail(
|
| 593 |
+
AssertionError,
|
| 594 |
+
make_scalar_mismatch_msg(
|
| 595 |
+
self.actual, self.expected, rtol=self.rtol, atol=self.atol
|
| 596 |
+
),
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
def extra_repr(self) -> Sequence[str]:
|
| 600 |
+
return (
|
| 601 |
+
"rtol",
|
| 602 |
+
"atol",
|
| 603 |
+
"equal_nan",
|
| 604 |
+
"check_dtype",
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
class TensorLikePair(Pair):
|
| 609 |
+
"""Pair for :class:`torch.Tensor`-like inputs.
|
| 610 |
+
|
| 611 |
+
Kwargs:
|
| 612 |
+
allow_subclasses (bool):
|
| 613 |
+
rtol (Optional[float]): Relative tolerance. If specified ``atol`` must also be specified. If omitted, default
|
| 614 |
+
values based on the type are selected. See :func:assert_close: for details.
|
| 615 |
+
atol (Optional[float]): Absolute tolerance. If specified ``rtol`` must also be specified. If omitted, default
|
| 616 |
+
values based on the type are selected. See :func:assert_close: for details.
|
| 617 |
+
equal_nan (bool): If ``True``, two ``NaN`` values are considered equal. Defaults to ``False``.
|
| 618 |
+
check_device (bool): If ``True`` (default), asserts that corresponding tensors are on the same
|
| 619 |
+
:attr:`~torch.Tensor.device`. If this check is disabled, tensors on different
|
| 620 |
+
:attr:`~torch.Tensor.device`'s are moved to the CPU before being compared.
|
| 621 |
+
check_dtype (bool): If ``True`` (default), asserts that corresponding tensors have the same ``dtype``. If this
|
| 622 |
+
check is disabled, tensors with different ``dtype``'s are promoted to a common ``dtype`` (according to
|
| 623 |
+
:func:`torch.promote_types`) before being compared.
|
| 624 |
+
check_layout (bool): If ``True`` (default), asserts that corresponding tensors have the same ``layout``. If this
|
| 625 |
+
check is disabled, tensors with different ``layout``'s are converted to strided tensors before being
|
| 626 |
+
compared.
|
| 627 |
+
check_stride (bool): If ``True`` and corresponding tensors are strided, asserts that they have the same stride.
|
| 628 |
+
"""
|
| 629 |
+
|
| 630 |
+
def __init__(
|
| 631 |
+
self,
|
| 632 |
+
actual: Any,
|
| 633 |
+
expected: Any,
|
| 634 |
+
*,
|
| 635 |
+
id: Tuple[Any, ...] = (),
|
| 636 |
+
allow_subclasses: bool = True,
|
| 637 |
+
rtol: Optional[float] = None,
|
| 638 |
+
atol: Optional[float] = None,
|
| 639 |
+
equal_nan: bool = False,
|
| 640 |
+
check_device: bool = True,
|
| 641 |
+
check_dtype: bool = True,
|
| 642 |
+
check_layout: bool = True,
|
| 643 |
+
check_stride: bool = False,
|
| 644 |
+
**other_parameters: Any,
|
| 645 |
+
):
|
| 646 |
+
actual, expected = self._process_inputs(
|
| 647 |
+
actual, expected, id=id, allow_subclasses=allow_subclasses
|
| 648 |
+
)
|
| 649 |
+
super().__init__(actual, expected, id=id, **other_parameters)
|
| 650 |
+
|
| 651 |
+
self.rtol, self.atol = get_tolerances(
|
| 652 |
+
actual, expected, rtol=rtol, atol=atol, id=self.id
|
| 653 |
+
)
|
| 654 |
+
self.equal_nan = equal_nan
|
| 655 |
+
self.check_device = check_device
|
| 656 |
+
self.check_dtype = check_dtype
|
| 657 |
+
self.check_layout = check_layout
|
| 658 |
+
self.check_stride = check_stride
|
| 659 |
+
|
| 660 |
+
def _process_inputs(
|
| 661 |
+
self, actual: Any, expected: Any, *, id: Tuple[Any, ...], allow_subclasses: bool
|
| 662 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 663 |
+
directly_related = isinstance(actual, type(expected)) or isinstance(
|
| 664 |
+
expected, type(actual)
|
| 665 |
+
)
|
| 666 |
+
if not directly_related:
|
| 667 |
+
self._inputs_not_supported()
|
| 668 |
+
|
| 669 |
+
if not allow_subclasses and type(actual) is not type(expected):
|
| 670 |
+
self._inputs_not_supported()
|
| 671 |
+
|
| 672 |
+
actual, expected = (self._to_tensor(input) for input in (actual, expected))
|
| 673 |
+
for tensor in (actual, expected):
|
| 674 |
+
self._check_supported(tensor, id=id)
|
| 675 |
+
return actual, expected
|
| 676 |
+
|
| 677 |
+
def _to_tensor(self, tensor_like: Any) -> torch.Tensor:
|
| 678 |
+
if isinstance(tensor_like, torch.Tensor):
|
| 679 |
+
return tensor_like
|
| 680 |
+
|
| 681 |
+
try:
|
| 682 |
+
return torch.as_tensor(tensor_like)
|
| 683 |
+
except Exception:
|
| 684 |
+
self._inputs_not_supported()
|
| 685 |
+
|
| 686 |
+
def _check_supported(self, tensor: torch.Tensor, *, id: Tuple[Any, ...]) -> None:
|
| 687 |
+
if tensor.layout not in {
|
| 688 |
+
torch.strided,
|
| 689 |
+
torch.sparse_coo,
|
| 690 |
+
torch.sparse_csr,
|
| 691 |
+
torch.sparse_csc,
|
| 692 |
+
torch.sparse_bsr,
|
| 693 |
+
torch.sparse_bsc,
|
| 694 |
+
}:
|
| 695 |
+
raise ErrorMeta(
|
| 696 |
+
ValueError, f"Unsupported tensor layout {tensor.layout}", id=id
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
def compare(self) -> None:
|
| 700 |
+
actual, expected = self.actual, self.expected
|
| 701 |
+
|
| 702 |
+
self._compare_attributes(actual, expected)
|
| 703 |
+
if any(input.device.type == "meta" for input in (actual, expected)):
|
| 704 |
+
return
|
| 705 |
+
|
| 706 |
+
actual, expected = self._equalize_attributes(actual, expected)
|
| 707 |
+
self._compare_values(actual, expected)
|
| 708 |
+
|
| 709 |
+
def _compare_attributes(
|
| 710 |
+
self,
|
| 711 |
+
actual: torch.Tensor,
|
| 712 |
+
expected: torch.Tensor,
|
| 713 |
+
) -> None:
|
| 714 |
+
"""Checks if the attributes of two tensors match.
|
| 715 |
+
|
| 716 |
+
Always checks
|
| 717 |
+
|
| 718 |
+
- the :attr:`~torch.Tensor.shape`,
|
| 719 |
+
- whether both inputs are quantized or not,
|
| 720 |
+
- and if they use the same quantization scheme.
|
| 721 |
+
|
| 722 |
+
Checks for
|
| 723 |
+
|
| 724 |
+
- :attr:`~torch.Tensor.layout`,
|
| 725 |
+
- :meth:`~torch.Tensor.stride`,
|
| 726 |
+
- :attr:`~torch.Tensor.device`, and
|
| 727 |
+
- :attr:`~torch.Tensor.dtype`
|
| 728 |
+
|
| 729 |
+
are optional and can be disabled through the corresponding ``check_*`` flag during construction of the pair.
|
| 730 |
+
"""
|
| 731 |
+
|
| 732 |
+
def raise_mismatch_error(
|
| 733 |
+
attribute_name: str, actual_value: Any, expected_value: Any
|
| 734 |
+
) -> NoReturn:
|
| 735 |
+
self._fail(
|
| 736 |
+
AssertionError,
|
| 737 |
+
f"The values for attribute '{attribute_name}' do not match: {actual_value} != {expected_value}.",
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
if actual.shape != expected.shape:
|
| 741 |
+
raise_mismatch_error("shape", actual.shape, expected.shape)
|
| 742 |
+
|
| 743 |
+
if actual.is_quantized != expected.is_quantized:
|
| 744 |
+
raise_mismatch_error(
|
| 745 |
+
"is_quantized", actual.is_quantized, expected.is_quantized
|
| 746 |
+
)
|
| 747 |
+
elif actual.is_quantized and actual.qscheme() != expected.qscheme():
|
| 748 |
+
raise_mismatch_error("qscheme()", actual.qscheme(), expected.qscheme())
|
| 749 |
+
|
| 750 |
+
if actual.layout != expected.layout:
|
| 751 |
+
if self.check_layout:
|
| 752 |
+
raise_mismatch_error("layout", actual.layout, expected.layout)
|
| 753 |
+
elif (
|
| 754 |
+
actual.layout == torch.strided
|
| 755 |
+
and self.check_stride
|
| 756 |
+
and actual.stride() != expected.stride()
|
| 757 |
+
):
|
| 758 |
+
raise_mismatch_error("stride()", actual.stride(), expected.stride())
|
| 759 |
+
|
| 760 |
+
if self.check_device and actual.device != expected.device:
|
| 761 |
+
raise_mismatch_error("device", actual.device, expected.device)
|
| 762 |
+
|
| 763 |
+
if self.check_dtype and actual.dtype != expected.dtype:
|
| 764 |
+
raise_mismatch_error("dtype", actual.dtype, expected.dtype)
|
| 765 |
+
|
| 766 |
+
def _equalize_attributes(
|
| 767 |
+
self, actual: torch.Tensor, expected: torch.Tensor
|
| 768 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 769 |
+
"""Equalizes some attributes of two tensors for value comparison.
|
| 770 |
+
|
| 771 |
+
If ``actual`` and ``expected`` are ...
|
| 772 |
+
|
| 773 |
+
- ... not on the same :attr:`~torch.Tensor.device`, they are moved CPU memory.
|
| 774 |
+
- ... not of the same ``dtype``, they are promoted to a common ``dtype`` (according to
|
| 775 |
+
:func:`torch.promote_types`).
|
| 776 |
+
- ... not of the same ``layout``, they are converted to strided tensors.
|
| 777 |
+
|
| 778 |
+
Args:
|
| 779 |
+
actual (Tensor): Actual tensor.
|
| 780 |
+
expected (Tensor): Expected tensor.
|
| 781 |
+
|
| 782 |
+
Returns:
|
| 783 |
+
(Tuple[Tensor, Tensor]): Equalized tensors.
|
| 784 |
+
"""
|
| 785 |
+
# The comparison logic uses operators currently not supported by the MPS backends.
|
| 786 |
+
# See https://github.com/pytorch/pytorch/issues/77144 for details.
|
| 787 |
+
# TODO: Remove this conversion as soon as all operations are supported natively by the MPS backend
|
| 788 |
+
if actual.is_mps or expected.is_mps: # type: ignore[attr-defined]
|
| 789 |
+
actual = actual.cpu()
|
| 790 |
+
expected = expected.cpu()
|
| 791 |
+
|
| 792 |
+
if actual.device != expected.device:
|
| 793 |
+
actual = actual.cpu()
|
| 794 |
+
expected = expected.cpu()
|
| 795 |
+
|
| 796 |
+
if actual.dtype != expected.dtype:
|
| 797 |
+
actual_dtype = actual.dtype
|
| 798 |
+
expected_dtype = expected.dtype
|
| 799 |
+
# For uint64, this is not sound in general, which is why promote_types doesn't
|
| 800 |
+
# allow it, but for easy testing, we're unlikely to get confused
|
| 801 |
+
# by large uint64 overflowing into negative int64
|
| 802 |
+
if actual_dtype in [torch.uint64, torch.uint32, torch.uint16]:
|
| 803 |
+
actual_dtype = torch.int64
|
| 804 |
+
if expected_dtype in [torch.uint64, torch.uint32, torch.uint16]:
|
| 805 |
+
expected_dtype = torch.int64
|
| 806 |
+
dtype = torch.promote_types(actual_dtype, expected_dtype)
|
| 807 |
+
actual = actual.to(dtype)
|
| 808 |
+
expected = expected.to(dtype)
|
| 809 |
+
|
| 810 |
+
if actual.layout != expected.layout:
|
| 811 |
+
# These checks are needed, since Tensor.to_dense() fails on tensors that are already strided
|
| 812 |
+
actual = actual.to_dense() if actual.layout != torch.strided else actual
|
| 813 |
+
expected = (
|
| 814 |
+
expected.to_dense() if expected.layout != torch.strided else expected
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
return actual, expected
|
| 818 |
+
|
| 819 |
+
def _compare_values(self, actual: torch.Tensor, expected: torch.Tensor) -> None:
|
| 820 |
+
if actual.is_quantized:
|
| 821 |
+
compare_fn = self._compare_quantized_values
|
| 822 |
+
elif actual.is_sparse:
|
| 823 |
+
compare_fn = self._compare_sparse_coo_values
|
| 824 |
+
elif actual.layout in {
|
| 825 |
+
torch.sparse_csr,
|
| 826 |
+
torch.sparse_csc,
|
| 827 |
+
torch.sparse_bsr,
|
| 828 |
+
torch.sparse_bsc,
|
| 829 |
+
}:
|
| 830 |
+
compare_fn = self._compare_sparse_compressed_values
|
| 831 |
+
else:
|
| 832 |
+
compare_fn = self._compare_regular_values_close
|
| 833 |
+
|
| 834 |
+
compare_fn(
|
| 835 |
+
actual, expected, rtol=self.rtol, atol=self.atol, equal_nan=self.equal_nan
|
| 836 |
+
)
|
| 837 |
+
|
| 838 |
+
def _compare_quantized_values(
|
| 839 |
+
self,
|
| 840 |
+
actual: torch.Tensor,
|
| 841 |
+
expected: torch.Tensor,
|
| 842 |
+
*,
|
| 843 |
+
rtol: float,
|
| 844 |
+
atol: float,
|
| 845 |
+
equal_nan: bool,
|
| 846 |
+
) -> None:
|
| 847 |
+
"""Compares quantized tensors by comparing the :meth:`~torch.Tensor.dequantize`'d variants for closeness.
|
| 848 |
+
|
| 849 |
+
.. note::
|
| 850 |
+
|
| 851 |
+
A detailed discussion about why only the dequantized variant is checked for closeness rather than checking
|
| 852 |
+
the individual quantization parameters for closeness and the integer representation for equality can be
|
| 853 |
+
found in https://github.com/pytorch/pytorch/issues/68548.
|
| 854 |
+
"""
|
| 855 |
+
return self._compare_regular_values_close(
|
| 856 |
+
actual.dequantize(),
|
| 857 |
+
expected.dequantize(),
|
| 858 |
+
rtol=rtol,
|
| 859 |
+
atol=atol,
|
| 860 |
+
equal_nan=equal_nan,
|
| 861 |
+
identifier=lambda default_identifier: f"Quantized {default_identifier.lower()}",
|
| 862 |
+
)
|
| 863 |
+
|
| 864 |
+
def _compare_sparse_coo_values(
|
| 865 |
+
self,
|
| 866 |
+
actual: torch.Tensor,
|
| 867 |
+
expected: torch.Tensor,
|
| 868 |
+
*,
|
| 869 |
+
rtol: float,
|
| 870 |
+
atol: float,
|
| 871 |
+
equal_nan: bool,
|
| 872 |
+
) -> None:
|
| 873 |
+
"""Compares sparse COO tensors by comparing
|
| 874 |
+
|
| 875 |
+
- the number of sparse dimensions,
|
| 876 |
+
- the number of non-zero elements (nnz) for equality,
|
| 877 |
+
- the indices for equality, and
|
| 878 |
+
- the values for closeness.
|
| 879 |
+
"""
|
| 880 |
+
if actual.sparse_dim() != expected.sparse_dim():
|
| 881 |
+
self._fail(
|
| 882 |
+
AssertionError,
|
| 883 |
+
(
|
| 884 |
+
f"The number of sparse dimensions in sparse COO tensors does not match: "
|
| 885 |
+
f"{actual.sparse_dim()} != {expected.sparse_dim()}"
|
| 886 |
+
),
|
| 887 |
+
)
|
| 888 |
+
|
| 889 |
+
if actual._nnz() != expected._nnz():
|
| 890 |
+
self._fail(
|
| 891 |
+
AssertionError,
|
| 892 |
+
(
|
| 893 |
+
f"The number of specified values in sparse COO tensors does not match: "
|
| 894 |
+
f"{actual._nnz()} != {expected._nnz()}"
|
| 895 |
+
),
|
| 896 |
+
)
|
| 897 |
+
|
| 898 |
+
self._compare_regular_values_equal(
|
| 899 |
+
actual._indices(),
|
| 900 |
+
expected._indices(),
|
| 901 |
+
identifier="Sparse COO indices",
|
| 902 |
+
)
|
| 903 |
+
self._compare_regular_values_close(
|
| 904 |
+
actual._values(),
|
| 905 |
+
expected._values(),
|
| 906 |
+
rtol=rtol,
|
| 907 |
+
atol=atol,
|
| 908 |
+
equal_nan=equal_nan,
|
| 909 |
+
identifier="Sparse COO values",
|
| 910 |
+
)
|
| 911 |
+
|
| 912 |
+
def _compare_sparse_compressed_values(
|
| 913 |
+
self,
|
| 914 |
+
actual: torch.Tensor,
|
| 915 |
+
expected: torch.Tensor,
|
| 916 |
+
*,
|
| 917 |
+
rtol: float,
|
| 918 |
+
atol: float,
|
| 919 |
+
equal_nan: bool,
|
| 920 |
+
) -> None:
|
| 921 |
+
"""Compares sparse compressed tensors by comparing
|
| 922 |
+
|
| 923 |
+
- the number of non-zero elements (nnz) for equality,
|
| 924 |
+
- the plain indices for equality,
|
| 925 |
+
- the compressed indices for equality, and
|
| 926 |
+
- the values for closeness.
|
| 927 |
+
"""
|
| 928 |
+
format_name, compressed_indices_method, plain_indices_method = {
|
| 929 |
+
torch.sparse_csr: (
|
| 930 |
+
"CSR",
|
| 931 |
+
torch.Tensor.crow_indices,
|
| 932 |
+
torch.Tensor.col_indices,
|
| 933 |
+
),
|
| 934 |
+
torch.sparse_csc: (
|
| 935 |
+
"CSC",
|
| 936 |
+
torch.Tensor.ccol_indices,
|
| 937 |
+
torch.Tensor.row_indices,
|
| 938 |
+
),
|
| 939 |
+
torch.sparse_bsr: (
|
| 940 |
+
"BSR",
|
| 941 |
+
torch.Tensor.crow_indices,
|
| 942 |
+
torch.Tensor.col_indices,
|
| 943 |
+
),
|
| 944 |
+
torch.sparse_bsc: (
|
| 945 |
+
"BSC",
|
| 946 |
+
torch.Tensor.ccol_indices,
|
| 947 |
+
torch.Tensor.row_indices,
|
| 948 |
+
),
|
| 949 |
+
}[actual.layout]
|
| 950 |
+
|
| 951 |
+
if actual._nnz() != expected._nnz():
|
| 952 |
+
self._fail(
|
| 953 |
+
AssertionError,
|
| 954 |
+
(
|
| 955 |
+
f"The number of specified values in sparse {format_name} tensors does not match: "
|
| 956 |
+
f"{actual._nnz()} != {expected._nnz()}"
|
| 957 |
+
),
|
| 958 |
+
)
|
| 959 |
+
|
| 960 |
+
# Compressed and plain indices in the CSR / CSC / BSR / BSC sparse formates can be `torch.int32` _or_
|
| 961 |
+
# `torch.int64`. While the same dtype is enforced for the compressed and plain indices of a single tensor, it
|
| 962 |
+
# can be different between two tensors. Thus, we need to convert them to the same dtype, or the comparison will
|
| 963 |
+
# fail.
|
| 964 |
+
actual_compressed_indices = compressed_indices_method(actual)
|
| 965 |
+
expected_compressed_indices = compressed_indices_method(expected)
|
| 966 |
+
indices_dtype = torch.promote_types(
|
| 967 |
+
actual_compressed_indices.dtype, expected_compressed_indices.dtype
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
self._compare_regular_values_equal(
|
| 971 |
+
actual_compressed_indices.to(indices_dtype),
|
| 972 |
+
expected_compressed_indices.to(indices_dtype),
|
| 973 |
+
identifier=f"Sparse {format_name} {compressed_indices_method.__name__}",
|
| 974 |
+
)
|
| 975 |
+
self._compare_regular_values_equal(
|
| 976 |
+
plain_indices_method(actual).to(indices_dtype),
|
| 977 |
+
plain_indices_method(expected).to(indices_dtype),
|
| 978 |
+
identifier=f"Sparse {format_name} {plain_indices_method.__name__}",
|
| 979 |
+
)
|
| 980 |
+
self._compare_regular_values_close(
|
| 981 |
+
actual.values(),
|
| 982 |
+
expected.values(),
|
| 983 |
+
rtol=rtol,
|
| 984 |
+
atol=atol,
|
| 985 |
+
equal_nan=equal_nan,
|
| 986 |
+
identifier=f"Sparse {format_name} values",
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
def _compare_regular_values_equal(
|
| 990 |
+
self,
|
| 991 |
+
actual: torch.Tensor,
|
| 992 |
+
expected: torch.Tensor,
|
| 993 |
+
*,
|
| 994 |
+
equal_nan: bool = False,
|
| 995 |
+
identifier: Optional[Union[str, Callable[[str], str]]] = None,
|
| 996 |
+
) -> None:
|
| 997 |
+
"""Checks if the values of two tensors are equal."""
|
| 998 |
+
self._compare_regular_values_close(
|
| 999 |
+
actual, expected, rtol=0, atol=0, equal_nan=equal_nan, identifier=identifier
|
| 1000 |
+
)
|
| 1001 |
+
|
| 1002 |
+
def _compare_regular_values_close(
|
| 1003 |
+
self,
|
| 1004 |
+
actual: torch.Tensor,
|
| 1005 |
+
expected: torch.Tensor,
|
| 1006 |
+
*,
|
| 1007 |
+
rtol: float,
|
| 1008 |
+
atol: float,
|
| 1009 |
+
equal_nan: bool,
|
| 1010 |
+
identifier: Optional[Union[str, Callable[[str], str]]] = None,
|
| 1011 |
+
) -> None:
|
| 1012 |
+
"""Checks if the values of two tensors are close up to a desired tolerance."""
|
| 1013 |
+
matches = torch.isclose(
|
| 1014 |
+
actual, expected, rtol=rtol, atol=atol, equal_nan=equal_nan
|
| 1015 |
+
)
|
| 1016 |
+
if torch.all(matches):
|
| 1017 |
+
return
|
| 1018 |
+
|
| 1019 |
+
if actual.shape == torch.Size([]):
|
| 1020 |
+
msg = make_scalar_mismatch_msg(
|
| 1021 |
+
actual.item(),
|
| 1022 |
+
expected.item(),
|
| 1023 |
+
rtol=rtol,
|
| 1024 |
+
atol=atol,
|
| 1025 |
+
identifier=identifier,
|
| 1026 |
+
)
|
| 1027 |
+
else:
|
| 1028 |
+
msg = make_tensor_mismatch_msg(
|
| 1029 |
+
actual, expected, matches, rtol=rtol, atol=atol, identifier=identifier
|
| 1030 |
+
)
|
| 1031 |
+
self._fail(AssertionError, msg)
|
| 1032 |
+
|
| 1033 |
+
def extra_repr(self) -> Sequence[str]:
|
| 1034 |
+
return (
|
| 1035 |
+
"rtol",
|
| 1036 |
+
"atol",
|
| 1037 |
+
"equal_nan",
|
| 1038 |
+
"check_device",
|
| 1039 |
+
"check_dtype",
|
| 1040 |
+
"check_layout",
|
| 1041 |
+
"check_stride",
|
| 1042 |
+
)
|
| 1043 |
+
|
| 1044 |
+
|
| 1045 |
+
def originate_pairs(
|
| 1046 |
+
actual: Any,
|
| 1047 |
+
expected: Any,
|
| 1048 |
+
*,
|
| 1049 |
+
pair_types: Sequence[Type[Pair]],
|
| 1050 |
+
sequence_types: Tuple[Type, ...] = (collections.abc.Sequence,),
|
| 1051 |
+
mapping_types: Tuple[Type, ...] = (collections.abc.Mapping,),
|
| 1052 |
+
id: Tuple[Any, ...] = (),
|
| 1053 |
+
**options: Any,
|
| 1054 |
+
) -> List[Pair]:
|
| 1055 |
+
"""Originates pairs from the individual inputs.
|
| 1056 |
+
|
| 1057 |
+
``actual`` and ``expected`` can be possibly nested :class:`~collections.abc.Sequence`'s or
|
| 1058 |
+
:class:`~collections.abc.Mapping`'s. In this case the pairs are originated by recursing through them.
|
| 1059 |
+
|
| 1060 |
+
Args:
|
| 1061 |
+
actual (Any): Actual input.
|
| 1062 |
+
expected (Any): Expected input.
|
| 1063 |
+
pair_types (Sequence[Type[Pair]]): Sequence of pair types that will be tried to construct with the inputs.
|
| 1064 |
+
First successful pair will be used.
|
| 1065 |
+
sequence_types (Tuple[Type, ...]): Optional types treated as sequences that will be checked elementwise.
|
| 1066 |
+
mapping_types (Tuple[Type, ...]): Optional types treated as mappings that will be checked elementwise.
|
| 1067 |
+
id (Tuple[Any, ...]): Optional id of a pair that will be included in an error message.
|
| 1068 |
+
**options (Any): Options passed to each pair during construction.
|
| 1069 |
+
|
| 1070 |
+
Raises:
|
| 1071 |
+
ErrorMeta: With :class`AssertionError`, if the inputs are :class:`~collections.abc.Sequence`'s, but their
|
| 1072 |
+
length does not match.
|
| 1073 |
+
ErrorMeta: With :class`AssertionError`, if the inputs are :class:`~collections.abc.Mapping`'s, but their set of
|
| 1074 |
+
keys do not match.
|
| 1075 |
+
ErrorMeta: With :class`TypeError`, if no pair is able to handle the inputs.
|
| 1076 |
+
ErrorMeta: With any expected exception that happens during the construction of a pair.
|
| 1077 |
+
|
| 1078 |
+
Returns:
|
| 1079 |
+
(List[Pair]): Originated pairs.
|
| 1080 |
+
"""
|
| 1081 |
+
# We explicitly exclude str's here since they are self-referential and would cause an infinite recursion loop:
|
| 1082 |
+
# "a" == "a"[0][0]...
|
| 1083 |
+
if (
|
| 1084 |
+
isinstance(actual, sequence_types)
|
| 1085 |
+
and not isinstance(actual, str)
|
| 1086 |
+
and isinstance(expected, sequence_types)
|
| 1087 |
+
and not isinstance(expected, str)
|
| 1088 |
+
):
|
| 1089 |
+
actual_len = len(actual)
|
| 1090 |
+
expected_len = len(expected)
|
| 1091 |
+
if actual_len != expected_len:
|
| 1092 |
+
raise ErrorMeta(
|
| 1093 |
+
AssertionError,
|
| 1094 |
+
f"The length of the sequences mismatch: {actual_len} != {expected_len}",
|
| 1095 |
+
id=id,
|
| 1096 |
+
)
|
| 1097 |
+
|
| 1098 |
+
pairs = []
|
| 1099 |
+
for idx in range(actual_len):
|
| 1100 |
+
pairs.extend(
|
| 1101 |
+
originate_pairs(
|
| 1102 |
+
actual[idx],
|
| 1103 |
+
expected[idx],
|
| 1104 |
+
pair_types=pair_types,
|
| 1105 |
+
sequence_types=sequence_types,
|
| 1106 |
+
mapping_types=mapping_types,
|
| 1107 |
+
id=(*id, idx),
|
| 1108 |
+
**options,
|
| 1109 |
+
)
|
| 1110 |
+
)
|
| 1111 |
+
return pairs
|
| 1112 |
+
|
| 1113 |
+
elif isinstance(actual, mapping_types) and isinstance(expected, mapping_types):
|
| 1114 |
+
actual_keys = set(actual.keys())
|
| 1115 |
+
expected_keys = set(expected.keys())
|
| 1116 |
+
if actual_keys != expected_keys:
|
| 1117 |
+
missing_keys = expected_keys - actual_keys
|
| 1118 |
+
additional_keys = actual_keys - expected_keys
|
| 1119 |
+
raise ErrorMeta(
|
| 1120 |
+
AssertionError,
|
| 1121 |
+
(
|
| 1122 |
+
f"The keys of the mappings do not match:\n"
|
| 1123 |
+
f"Missing keys in the actual mapping: {sorted(missing_keys)}\n"
|
| 1124 |
+
f"Additional keys in the actual mapping: {sorted(additional_keys)}"
|
| 1125 |
+
),
|
| 1126 |
+
id=id,
|
| 1127 |
+
)
|
| 1128 |
+
|
| 1129 |
+
keys: Collection = actual_keys
|
| 1130 |
+
# Since the origination aborts after the first failure, we try to be deterministic
|
| 1131 |
+
with contextlib.suppress(Exception):
|
| 1132 |
+
keys = sorted(keys)
|
| 1133 |
+
|
| 1134 |
+
pairs = []
|
| 1135 |
+
for key in keys:
|
| 1136 |
+
pairs.extend(
|
| 1137 |
+
originate_pairs(
|
| 1138 |
+
actual[key],
|
| 1139 |
+
expected[key],
|
| 1140 |
+
pair_types=pair_types,
|
| 1141 |
+
sequence_types=sequence_types,
|
| 1142 |
+
mapping_types=mapping_types,
|
| 1143 |
+
id=(*id, key),
|
| 1144 |
+
**options,
|
| 1145 |
+
)
|
| 1146 |
+
)
|
| 1147 |
+
return pairs
|
| 1148 |
+
|
| 1149 |
+
else:
|
| 1150 |
+
for pair_type in pair_types:
|
| 1151 |
+
try:
|
| 1152 |
+
return [pair_type(actual, expected, id=id, **options)]
|
| 1153 |
+
# Raising an `UnsupportedInputs` during origination indicates that the pair type is not able to handle the
|
| 1154 |
+
# inputs. Thus, we try the next pair type.
|
| 1155 |
+
except UnsupportedInputs:
|
| 1156 |
+
continue
|
| 1157 |
+
# Raising an `ErrorMeta` during origination is the orderly way to abort and so we simply re-raise it. This
|
| 1158 |
+
# is only in a separate branch, because the one below would also except it.
|
| 1159 |
+
except ErrorMeta:
|
| 1160 |
+
raise
|
| 1161 |
+
# Raising any other exception during origination is unexpected and will give some extra information about
|
| 1162 |
+
# what happened. If applicable, the exception should be expected in the future.
|
| 1163 |
+
except Exception as error:
|
| 1164 |
+
raise RuntimeError(
|
| 1165 |
+
f"Originating a {pair_type.__name__}() at item {''.join(str([item]) for item in id)} with\n\n"
|
| 1166 |
+
f"{type(actual).__name__}(): {actual}\n\n"
|
| 1167 |
+
f"and\n\n"
|
| 1168 |
+
f"{type(expected).__name__}(): {expected}\n\n"
|
| 1169 |
+
f"resulted in the unexpected exception above. "
|
| 1170 |
+
f"If you are a user and see this message during normal operation "
|
| 1171 |
+
"please file an issue at https://github.com/pytorch/pytorch/issues. "
|
| 1172 |
+
"If you are a developer and working on the comparison functions, "
|
| 1173 |
+
"please except the previous error and raise an expressive `ErrorMeta` instead."
|
| 1174 |
+
) from error
|
| 1175 |
+
else:
|
| 1176 |
+
raise ErrorMeta(
|
| 1177 |
+
TypeError,
|
| 1178 |
+
f"No comparison pair was able to handle inputs of type {type(actual)} and {type(expected)}.",
|
| 1179 |
+
id=id,
|
| 1180 |
+
)
|
| 1181 |
+
|
| 1182 |
+
|
| 1183 |
+
def not_close_error_metas(
|
| 1184 |
+
actual: Any,
|
| 1185 |
+
expected: Any,
|
| 1186 |
+
*,
|
| 1187 |
+
pair_types: Sequence[Type[Pair]] = (ObjectPair,),
|
| 1188 |
+
sequence_types: Tuple[Type, ...] = (collections.abc.Sequence,),
|
| 1189 |
+
mapping_types: Tuple[Type, ...] = (collections.abc.Mapping,),
|
| 1190 |
+
**options: Any,
|
| 1191 |
+
) -> List[ErrorMeta]:
|
| 1192 |
+
"""Asserts that inputs are equal.
|
| 1193 |
+
|
| 1194 |
+
``actual`` and ``expected`` can be possibly nested :class:`~collections.abc.Sequence`'s or
|
| 1195 |
+
:class:`~collections.abc.Mapping`'s. In this case the comparison happens elementwise by recursing through them.
|
| 1196 |
+
|
| 1197 |
+
Args:
|
| 1198 |
+
actual (Any): Actual input.
|
| 1199 |
+
expected (Any): Expected input.
|
| 1200 |
+
pair_types (Sequence[Type[Pair]]): Sequence of :class:`Pair` types that will be tried to construct with the
|
| 1201 |
+
inputs. First successful pair will be used. Defaults to only using :class:`ObjectPair`.
|
| 1202 |
+
sequence_types (Tuple[Type, ...]): Optional types treated as sequences that will be checked elementwise.
|
| 1203 |
+
mapping_types (Tuple[Type, ...]): Optional types treated as mappings that will be checked elementwise.
|
| 1204 |
+
**options (Any): Options passed to each pair during construction.
|
| 1205 |
+
"""
|
| 1206 |
+
# Hide this function from `pytest`'s traceback
|
| 1207 |
+
__tracebackhide__ = True
|
| 1208 |
+
|
| 1209 |
+
try:
|
| 1210 |
+
pairs = originate_pairs(
|
| 1211 |
+
actual,
|
| 1212 |
+
expected,
|
| 1213 |
+
pair_types=pair_types,
|
| 1214 |
+
sequence_types=sequence_types,
|
| 1215 |
+
mapping_types=mapping_types,
|
| 1216 |
+
**options,
|
| 1217 |
+
)
|
| 1218 |
+
except ErrorMeta as error_meta:
|
| 1219 |
+
# Explicitly raising from None to hide the internal traceback
|
| 1220 |
+
raise error_meta.to_error() from None
|
| 1221 |
+
|
| 1222 |
+
error_metas: List[ErrorMeta] = []
|
| 1223 |
+
for pair in pairs:
|
| 1224 |
+
try:
|
| 1225 |
+
pair.compare()
|
| 1226 |
+
except ErrorMeta as error_meta:
|
| 1227 |
+
error_metas.append(error_meta)
|
| 1228 |
+
# Raising any exception besides `ErrorMeta` while comparing is unexpected and will give some extra information
|
| 1229 |
+
# about what happened. If applicable, the exception should be expected in the future.
|
| 1230 |
+
except Exception as error:
|
| 1231 |
+
raise RuntimeError(
|
| 1232 |
+
f"Comparing\n\n"
|
| 1233 |
+
f"{pair}\n\n"
|
| 1234 |
+
f"resulted in the unexpected exception above. "
|
| 1235 |
+
f"If you are a user and see this message during normal operation "
|
| 1236 |
+
"please file an issue at https://github.com/pytorch/pytorch/issues. "
|
| 1237 |
+
"If you are a developer and working on the comparison functions, "
|
| 1238 |
+
"please except the previous error and raise an expressive `ErrorMeta` instead."
|
| 1239 |
+
) from error
|
| 1240 |
+
|
| 1241 |
+
# [ErrorMeta Cycles]
|
| 1242 |
+
# ErrorMeta objects in this list capture
|
| 1243 |
+
# tracebacks that refer to the frame of this function.
|
| 1244 |
+
# The local variable `error_metas` refers to the error meta
|
| 1245 |
+
# objects, creating a reference cycle. Frames in the traceback
|
| 1246 |
+
# would not get freed until cycle collection, leaking cuda memory in tests.
|
| 1247 |
+
# We break the cycle by removing the reference to the error_meta objects
|
| 1248 |
+
# from this frame as it returns.
|
| 1249 |
+
error_metas = [error_metas]
|
| 1250 |
+
return error_metas.pop()
|
| 1251 |
+
|
| 1252 |
+
|
| 1253 |
+
def assert_close(
|
| 1254 |
+
actual: Any,
|
| 1255 |
+
expected: Any,
|
| 1256 |
+
*,
|
| 1257 |
+
allow_subclasses: bool = True,
|
| 1258 |
+
rtol: Optional[float] = None,
|
| 1259 |
+
atol: Optional[float] = None,
|
| 1260 |
+
equal_nan: bool = False,
|
| 1261 |
+
check_device: bool = True,
|
| 1262 |
+
check_dtype: bool = True,
|
| 1263 |
+
check_layout: bool = True,
|
| 1264 |
+
check_stride: bool = False,
|
| 1265 |
+
msg: Optional[Union[str, Callable[[str], str]]] = None,
|
| 1266 |
+
):
|
| 1267 |
+
r"""Asserts that ``actual`` and ``expected`` are close.
|
| 1268 |
+
|
| 1269 |
+
If ``actual`` and ``expected`` are strided, non-quantized, real-valued, and finite, they are considered close if
|
| 1270 |
+
|
| 1271 |
+
.. math::
|
| 1272 |
+
|
| 1273 |
+
\lvert \text{actual} - \text{expected} \rvert \le \texttt{atol} + \texttt{rtol} \cdot \lvert \text{expected} \rvert
|
| 1274 |
+
|
| 1275 |
+
Non-finite values (``-inf`` and ``inf``) are only considered close if and only if they are equal. ``NaN``'s are
|
| 1276 |
+
only considered equal to each other if ``equal_nan`` is ``True``.
|
| 1277 |
+
|
| 1278 |
+
In addition, they are only considered close if they have the same
|
| 1279 |
+
|
| 1280 |
+
- :attr:`~torch.Tensor.device` (if ``check_device`` is ``True``),
|
| 1281 |
+
- ``dtype`` (if ``check_dtype`` is ``True``),
|
| 1282 |
+
- ``layout`` (if ``check_layout`` is ``True``), and
|
| 1283 |
+
- stride (if ``check_stride`` is ``True``).
|
| 1284 |
+
|
| 1285 |
+
If either ``actual`` or ``expected`` is a meta tensor, only the attribute checks will be performed.
|
| 1286 |
+
|
| 1287 |
+
If ``actual`` and ``expected`` are sparse (either having COO, CSR, CSC, BSR, or BSC layout), their strided members are
|
| 1288 |
+
checked individually. Indices, namely ``indices`` for COO, ``crow_indices`` and ``col_indices`` for CSR and BSR,
|
| 1289 |
+
or ``ccol_indices`` and ``row_indices`` for CSC and BSC layouts, respectively,
|
| 1290 |
+
are always checked for equality whereas the values are checked for closeness according to the definition above.
|
| 1291 |
+
|
| 1292 |
+
If ``actual`` and ``expected`` are quantized, they are considered close if they have the same
|
| 1293 |
+
:meth:`~torch.Tensor.qscheme` and the result of :meth:`~torch.Tensor.dequantize` is close according to the
|
| 1294 |
+
definition above.
|
| 1295 |
+
|
| 1296 |
+
``actual`` and ``expected`` can be :class:`~torch.Tensor`'s or any tensor-or-scalar-likes from which
|
| 1297 |
+
:class:`torch.Tensor`'s can be constructed with :func:`torch.as_tensor`. Except for Python scalars the input types
|
| 1298 |
+
have to be directly related. In addition, ``actual`` and ``expected`` can be :class:`~collections.abc.Sequence`'s
|
| 1299 |
+
or :class:`~collections.abc.Mapping`'s in which case they are considered close if their structure matches and all
|
| 1300 |
+
their elements are considered close according to the above definition.
|
| 1301 |
+
|
| 1302 |
+
.. note::
|
| 1303 |
+
|
| 1304 |
+
Python scalars are an exception to the type relation requirement, because their :func:`type`, i.e.
|
| 1305 |
+
:class:`int`, :class:`float`, and :class:`complex`, is equivalent to the ``dtype`` of a tensor-like. Thus,
|
| 1306 |
+
Python scalars of different types can be checked, but require ``check_dtype=False``.
|
| 1307 |
+
|
| 1308 |
+
Args:
|
| 1309 |
+
actual (Any): Actual input.
|
| 1310 |
+
expected (Any): Expected input.
|
| 1311 |
+
allow_subclasses (bool): If ``True`` (default) and except for Python scalars, inputs of directly related types
|
| 1312 |
+
are allowed. Otherwise type equality is required.
|
| 1313 |
+
rtol (Optional[float]): Relative tolerance. If specified ``atol`` must also be specified. If omitted, default
|
| 1314 |
+
values based on the :attr:`~torch.Tensor.dtype` are selected with the below table.
|
| 1315 |
+
atol (Optional[float]): Absolute tolerance. If specified ``rtol`` must also be specified. If omitted, default
|
| 1316 |
+
values based on the :attr:`~torch.Tensor.dtype` are selected with the below table.
|
| 1317 |
+
equal_nan (Union[bool, str]): If ``True``, two ``NaN`` values will be considered equal.
|
| 1318 |
+
check_device (bool): If ``True`` (default), asserts that corresponding tensors are on the same
|
| 1319 |
+
:attr:`~torch.Tensor.device`. If this check is disabled, tensors on different
|
| 1320 |
+
:attr:`~torch.Tensor.device`'s are moved to the CPU before being compared.
|
| 1321 |
+
check_dtype (bool): If ``True`` (default), asserts that corresponding tensors have the same ``dtype``. If this
|
| 1322 |
+
check is disabled, tensors with different ``dtype``'s are promoted to a common ``dtype`` (according to
|
| 1323 |
+
:func:`torch.promote_types`) before being compared.
|
| 1324 |
+
check_layout (bool): If ``True`` (default), asserts that corresponding tensors have the same ``layout``. If this
|
| 1325 |
+
check is disabled, tensors with different ``layout``'s are converted to strided tensors before being
|
| 1326 |
+
compared.
|
| 1327 |
+
check_stride (bool): If ``True`` and corresponding tensors are strided, asserts that they have the same stride.
|
| 1328 |
+
msg (Optional[Union[str, Callable[[str], str]]]): Optional error message to use in case a failure occurs during
|
| 1329 |
+
the comparison. Can also passed as callable in which case it will be called with the generated message and
|
| 1330 |
+
should return the new message.
|
| 1331 |
+
|
| 1332 |
+
Raises:
|
| 1333 |
+
ValueError: If no :class:`torch.Tensor` can be constructed from an input.
|
| 1334 |
+
ValueError: If only ``rtol`` or ``atol`` is specified.
|
| 1335 |
+
AssertionError: If corresponding inputs are not Python scalars and are not directly related.
|
| 1336 |
+
AssertionError: If ``allow_subclasses`` is ``False``, but corresponding inputs are not Python scalars and have
|
| 1337 |
+
different types.
|
| 1338 |
+
AssertionError: If the inputs are :class:`~collections.abc.Sequence`'s, but their length does not match.
|
| 1339 |
+
AssertionError: If the inputs are :class:`~collections.abc.Mapping`'s, but their set of keys do not match.
|
| 1340 |
+
AssertionError: If corresponding tensors do not have the same :attr:`~torch.Tensor.shape`.
|
| 1341 |
+
AssertionError: If ``check_layout`` is ``True``, but corresponding tensors do not have the same
|
| 1342 |
+
:attr:`~torch.Tensor.layout`.
|
| 1343 |
+
AssertionError: If only one of corresponding tensors is quantized.
|
| 1344 |
+
AssertionError: If corresponding tensors are quantized, but have different :meth:`~torch.Tensor.qscheme`'s.
|
| 1345 |
+
AssertionError: If ``check_device`` is ``True``, but corresponding tensors are not on the same
|
| 1346 |
+
:attr:`~torch.Tensor.device`.
|
| 1347 |
+
AssertionError: If ``check_dtype`` is ``True``, but corresponding tensors do not have the same ``dtype``.
|
| 1348 |
+
AssertionError: If ``check_stride`` is ``True``, but corresponding strided tensors do not have the same stride.
|
| 1349 |
+
AssertionError: If the values of corresponding tensors are not close according to the definition above.
|
| 1350 |
+
|
| 1351 |
+
The following table displays the default ``rtol`` and ``atol`` for different ``dtype``'s. In case of mismatching
|
| 1352 |
+
``dtype``'s, the maximum of both tolerances is used.
|
| 1353 |
+
|
| 1354 |
+
+---------------------------+------------+----------+
|
| 1355 |
+
| ``dtype`` | ``rtol`` | ``atol`` |
|
| 1356 |
+
+===========================+============+==========+
|
| 1357 |
+
| :attr:`~torch.float16` | ``1e-3`` | ``1e-5`` |
|
| 1358 |
+
+---------------------------+------------+----------+
|
| 1359 |
+
| :attr:`~torch.bfloat16` | ``1.6e-2`` | ``1e-5`` |
|
| 1360 |
+
+---------------------------+------------+----------+
|
| 1361 |
+
| :attr:`~torch.float32` | ``1.3e-6`` | ``1e-5`` |
|
| 1362 |
+
+---------------------------+------------+----------+
|
| 1363 |
+
| :attr:`~torch.float64` | ``1e-7`` | ``1e-7`` |
|
| 1364 |
+
+---------------------------+------------+----------+
|
| 1365 |
+
| :attr:`~torch.complex32` | ``1e-3`` | ``1e-5`` |
|
| 1366 |
+
+---------------------------+------------+----------+
|
| 1367 |
+
| :attr:`~torch.complex64` | ``1.3e-6`` | ``1e-5`` |
|
| 1368 |
+
+---------------------------+------------+----------+
|
| 1369 |
+
| :attr:`~torch.complex128` | ``1e-7`` | ``1e-7`` |
|
| 1370 |
+
+---------------------------+------------+----------+
|
| 1371 |
+
| :attr:`~torch.quint8` | ``1.3e-6`` | ``1e-5`` |
|
| 1372 |
+
+---------------------------+------------+----------+
|
| 1373 |
+
| :attr:`~torch.quint2x4` | ``1.3e-6`` | ``1e-5`` |
|
| 1374 |
+
+---------------------------+------------+----------+
|
| 1375 |
+
| :attr:`~torch.quint4x2` | ``1.3e-6`` | ``1e-5`` |
|
| 1376 |
+
+---------------------------+------------+----------+
|
| 1377 |
+
| :attr:`~torch.qint8` | ``1.3e-6`` | ``1e-5`` |
|
| 1378 |
+
+---------------------------+------------+----------+
|
| 1379 |
+
| :attr:`~torch.qint32` | ``1.3e-6`` | ``1e-5`` |
|
| 1380 |
+
+---------------------------+------------+----------+
|
| 1381 |
+
| other | ``0.0`` | ``0.0`` |
|
| 1382 |
+
+---------------------------+------------+----------+
|
| 1383 |
+
|
| 1384 |
+
.. note::
|
| 1385 |
+
|
| 1386 |
+
:func:`~torch.testing.assert_close` is highly configurable with strict default settings. Users are encouraged
|
| 1387 |
+
to :func:`~functools.partial` it to fit their use case. For example, if an equality check is needed, one might
|
| 1388 |
+
define an ``assert_equal`` that uses zero tolerances for every ``dtype`` by default:
|
| 1389 |
+
|
| 1390 |
+
>>> import functools
|
| 1391 |
+
>>> assert_equal = functools.partial(torch.testing.assert_close, rtol=0, atol=0)
|
| 1392 |
+
>>> assert_equal(1e-9, 1e-10)
|
| 1393 |
+
Traceback (most recent call last):
|
| 1394 |
+
...
|
| 1395 |
+
AssertionError: Scalars are not equal!
|
| 1396 |
+
<BLANKLINE>
|
| 1397 |
+
Expected 1e-10 but got 1e-09.
|
| 1398 |
+
Absolute difference: 9.000000000000001e-10
|
| 1399 |
+
Relative difference: 9.0
|
| 1400 |
+
|
| 1401 |
+
Examples:
|
| 1402 |
+
>>> # tensor to tensor comparison
|
| 1403 |
+
>>> expected = torch.tensor([1e0, 1e-1, 1e-2])
|
| 1404 |
+
>>> actual = torch.acos(torch.cos(expected))
|
| 1405 |
+
>>> torch.testing.assert_close(actual, expected)
|
| 1406 |
+
|
| 1407 |
+
>>> # scalar to scalar comparison
|
| 1408 |
+
>>> import math
|
| 1409 |
+
>>> expected = math.sqrt(2.0)
|
| 1410 |
+
>>> actual = 2.0 / math.sqrt(2.0)
|
| 1411 |
+
>>> torch.testing.assert_close(actual, expected)
|
| 1412 |
+
|
| 1413 |
+
>>> # numpy array to numpy array comparison
|
| 1414 |
+
>>> import numpy as np
|
| 1415 |
+
>>> expected = np.array([1e0, 1e-1, 1e-2])
|
| 1416 |
+
>>> actual = np.arccos(np.cos(expected))
|
| 1417 |
+
>>> torch.testing.assert_close(actual, expected)
|
| 1418 |
+
|
| 1419 |
+
>>> # sequence to sequence comparison
|
| 1420 |
+
>>> import numpy as np
|
| 1421 |
+
>>> # The types of the sequences do not have to match. They only have to have the same
|
| 1422 |
+
>>> # length and their elements have to match.
|
| 1423 |
+
>>> expected = [torch.tensor([1.0]), 2.0, np.array(3.0)]
|
| 1424 |
+
>>> actual = tuple(expected)
|
| 1425 |
+
>>> torch.testing.assert_close(actual, expected)
|
| 1426 |
+
|
| 1427 |
+
>>> # mapping to mapping comparison
|
| 1428 |
+
>>> from collections import OrderedDict
|
| 1429 |
+
>>> import numpy as np
|
| 1430 |
+
>>> foo = torch.tensor(1.0)
|
| 1431 |
+
>>> bar = 2.0
|
| 1432 |
+
>>> baz = np.array(3.0)
|
| 1433 |
+
>>> # The types and a possible ordering of mappings do not have to match. They only
|
| 1434 |
+
>>> # have to have the same set of keys and their elements have to match.
|
| 1435 |
+
>>> expected = OrderedDict([("foo", foo), ("bar", bar), ("baz", baz)])
|
| 1436 |
+
>>> actual = {"baz": baz, "bar": bar, "foo": foo}
|
| 1437 |
+
>>> torch.testing.assert_close(actual, expected)
|
| 1438 |
+
|
| 1439 |
+
>>> expected = torch.tensor([1.0, 2.0, 3.0])
|
| 1440 |
+
>>> actual = expected.clone()
|
| 1441 |
+
>>> # By default, directly related instances can be compared
|
| 1442 |
+
>>> torch.testing.assert_close(torch.nn.Parameter(actual), expected)
|
| 1443 |
+
>>> # This check can be made more strict with allow_subclasses=False
|
| 1444 |
+
>>> torch.testing.assert_close(
|
| 1445 |
+
... torch.nn.Parameter(actual), expected, allow_subclasses=False
|
| 1446 |
+
... )
|
| 1447 |
+
Traceback (most recent call last):
|
| 1448 |
+
...
|
| 1449 |
+
TypeError: No comparison pair was able to handle inputs of type
|
| 1450 |
+
<class 'torch.nn.parameter.Parameter'> and <class 'torch.Tensor'>.
|
| 1451 |
+
>>> # If the inputs are not directly related, they are never considered close
|
| 1452 |
+
>>> torch.testing.assert_close(actual.numpy(), expected)
|
| 1453 |
+
Traceback (most recent call last):
|
| 1454 |
+
...
|
| 1455 |
+
TypeError: No comparison pair was able to handle inputs of type <class 'numpy.ndarray'>
|
| 1456 |
+
and <class 'torch.Tensor'>.
|
| 1457 |
+
>>> # Exceptions to these rules are Python scalars. They can be checked regardless of
|
| 1458 |
+
>>> # their type if check_dtype=False.
|
| 1459 |
+
>>> torch.testing.assert_close(1.0, 1, check_dtype=False)
|
| 1460 |
+
|
| 1461 |
+
>>> # NaN != NaN by default.
|
| 1462 |
+
>>> expected = torch.tensor(float("Nan"))
|
| 1463 |
+
>>> actual = expected.clone()
|
| 1464 |
+
>>> torch.testing.assert_close(actual, expected)
|
| 1465 |
+
Traceback (most recent call last):
|
| 1466 |
+
...
|
| 1467 |
+
AssertionError: Scalars are not close!
|
| 1468 |
+
<BLANKLINE>
|
| 1469 |
+
Expected nan but got nan.
|
| 1470 |
+
Absolute difference: nan (up to 1e-05 allowed)
|
| 1471 |
+
Relative difference: nan (up to 1.3e-06 allowed)
|
| 1472 |
+
>>> torch.testing.assert_close(actual, expected, equal_nan=True)
|
| 1473 |
+
|
| 1474 |
+
>>> expected = torch.tensor([1.0, 2.0, 3.0])
|
| 1475 |
+
>>> actual = torch.tensor([1.0, 4.0, 5.0])
|
| 1476 |
+
>>> # The default error message can be overwritten.
|
| 1477 |
+
>>> torch.testing.assert_close(actual, expected, msg="Argh, the tensors are not close!")
|
| 1478 |
+
Traceback (most recent call last):
|
| 1479 |
+
...
|
| 1480 |
+
AssertionError: Argh, the tensors are not close!
|
| 1481 |
+
>>> # If msg is a callable, it can be used to augment the generated message with
|
| 1482 |
+
>>> # extra information
|
| 1483 |
+
>>> torch.testing.assert_close(
|
| 1484 |
+
... actual, expected, msg=lambda msg: f"Header\n\n{msg}\n\nFooter"
|
| 1485 |
+
... )
|
| 1486 |
+
Traceback (most recent call last):
|
| 1487 |
+
...
|
| 1488 |
+
AssertionError: Header
|
| 1489 |
+
<BLANKLINE>
|
| 1490 |
+
Tensor-likes are not close!
|
| 1491 |
+
<BLANKLINE>
|
| 1492 |
+
Mismatched elements: 2 / 3 (66.7%)
|
| 1493 |
+
Greatest absolute difference: 2.0 at index (1,) (up to 1e-05 allowed)
|
| 1494 |
+
Greatest relative difference: 1.0 at index (1,) (up to 1.3e-06 allowed)
|
| 1495 |
+
<BLANKLINE>
|
| 1496 |
+
Footer
|
| 1497 |
+
"""
|
| 1498 |
+
# Hide this function from `pytest`'s traceback
|
| 1499 |
+
__tracebackhide__ = True
|
| 1500 |
+
|
| 1501 |
+
error_metas = not_close_error_metas(
|
| 1502 |
+
actual,
|
| 1503 |
+
expected,
|
| 1504 |
+
pair_types=(
|
| 1505 |
+
NonePair,
|
| 1506 |
+
BooleanPair,
|
| 1507 |
+
NumberPair,
|
| 1508 |
+
TensorLikePair,
|
| 1509 |
+
),
|
| 1510 |
+
allow_subclasses=allow_subclasses,
|
| 1511 |
+
rtol=rtol,
|
| 1512 |
+
atol=atol,
|
| 1513 |
+
equal_nan=equal_nan,
|
| 1514 |
+
check_device=check_device,
|
| 1515 |
+
check_dtype=check_dtype,
|
| 1516 |
+
check_layout=check_layout,
|
| 1517 |
+
check_stride=check_stride,
|
| 1518 |
+
msg=msg,
|
| 1519 |
+
)
|
| 1520 |
+
|
| 1521 |
+
if error_metas:
|
| 1522 |
+
# TODO: compose all metas into one AssertionError
|
| 1523 |
+
raise error_metas[0].to_error(msg)
|
| 1524 |
+
|
| 1525 |
+
|
| 1526 |
+
def assert_allclose(
|
| 1527 |
+
actual: Any,
|
| 1528 |
+
expected: Any,
|
| 1529 |
+
rtol: Optional[float] = None,
|
| 1530 |
+
atol: Optional[float] = None,
|
| 1531 |
+
equal_nan: bool = True,
|
| 1532 |
+
msg: str = "",
|
| 1533 |
+
) -> None:
|
| 1534 |
+
"""
|
| 1535 |
+
.. warning::
|
| 1536 |
+
|
| 1537 |
+
:func:`torch.testing.assert_allclose` is deprecated since ``1.12`` and will be removed in a future release.
|
| 1538 |
+
Please use :func:`torch.testing.assert_close` instead. You can find detailed upgrade instructions
|
| 1539 |
+
`here <https://github.com/pytorch/pytorch/issues/61844>`_.
|
| 1540 |
+
"""
|
| 1541 |
+
warnings.warn(
|
| 1542 |
+
"`torch.testing.assert_allclose()` is deprecated since 1.12 and will be removed in a future release. "
|
| 1543 |
+
"Please use `torch.testing.assert_close()` instead. "
|
| 1544 |
+
"You can find detailed upgrade instructions in https://github.com/pytorch/pytorch/issues/61844.",
|
| 1545 |
+
FutureWarning,
|
| 1546 |
+
stacklevel=2,
|
| 1547 |
+
)
|
| 1548 |
+
|
| 1549 |
+
if not isinstance(actual, torch.Tensor):
|
| 1550 |
+
actual = torch.tensor(actual)
|
| 1551 |
+
if not isinstance(expected, torch.Tensor):
|
| 1552 |
+
expected = torch.tensor(expected, dtype=actual.dtype)
|
| 1553 |
+
|
| 1554 |
+
if rtol is None and atol is None:
|
| 1555 |
+
rtol, atol = default_tolerances(
|
| 1556 |
+
actual,
|
| 1557 |
+
expected,
|
| 1558 |
+
dtype_precisions={
|
| 1559 |
+
torch.float16: (1e-3, 1e-3),
|
| 1560 |
+
torch.float32: (1e-4, 1e-5),
|
| 1561 |
+
torch.float64: (1e-5, 1e-8),
|
| 1562 |
+
},
|
| 1563 |
+
)
|
| 1564 |
+
|
| 1565 |
+
torch.testing.assert_close(
|
| 1566 |
+
actual,
|
| 1567 |
+
expected,
|
| 1568 |
+
rtol=rtol,
|
| 1569 |
+
atol=atol,
|
| 1570 |
+
equal_nan=equal_nan,
|
| 1571 |
+
check_device=True,
|
| 1572 |
+
check_dtype=False,
|
| 1573 |
+
check_stride=False,
|
| 1574 |
+
msg=msg or None,
|
| 1575 |
+
)
|
shared/package-files/31/31ddedd22e89ab666068c076cb95a18d5c62e82350fc7173a0d4e87c01ebb1cc/blob
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Python polyfills for common builtins.
|
| 5 |
+
"""
|
| 6 |
+
import math
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def all(iterator):
|
| 12 |
+
for elem in iterator:
|
| 13 |
+
if not elem:
|
| 14 |
+
return False
|
| 15 |
+
return True
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def any(iterator):
|
| 19 |
+
for elem in iterator:
|
| 20 |
+
if elem:
|
| 21 |
+
return True
|
| 22 |
+
return False
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def index(iterator, item, start=0, end=None):
|
| 26 |
+
for i, elem in enumerate(list(iterator))[start:end]:
|
| 27 |
+
if item == elem:
|
| 28 |
+
return i
|
| 29 |
+
# This will not run in dynamo
|
| 30 |
+
raise ValueError(f"{item} is not in {type(iterator)}")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def repeat(item, count):
|
| 34 |
+
for i in range(count):
|
| 35 |
+
yield item
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def radians(x):
|
| 39 |
+
return math.pi / 180.0 * x
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def accumulate_grad(x, new_grad):
|
| 43 |
+
new_grad = torch.clone(new_grad)
|
| 44 |
+
if x.grad is None:
|
| 45 |
+
x.grad = new_grad
|
| 46 |
+
else:
|
| 47 |
+
x.grad.add_(new_grad)
|
shared/package-files/31/31e1e3cf08b04fc4f64182d1123bd4a38ad46e9b757f1f4bd40ed7bc8adcbea1/blob
ADDED
|
Binary file (1.11 kB). View file
|
|
|
shared/package-files/31/31e3a1164bfdd402e278a26d187aa487180eeca241cf9de607cb51718097df19/blob
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
|
| 9 |
+
from ..utils import arbitrary_element
|
| 10 |
+
|
| 11 |
+
__all__ = ["cuthill_mckee_ordering", "reverse_cuthill_mckee_ordering"]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def cuthill_mckee_ordering(G, heuristic=None):
|
| 15 |
+
"""Generate an ordering (permutation) of the graph nodes to make
|
| 16 |
+
a sparse matrix.
|
| 17 |
+
|
| 18 |
+
Uses the Cuthill-McKee heuristic (based on breadth-first search) [1]_.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
G : graph
|
| 23 |
+
A NetworkX graph
|
| 24 |
+
|
| 25 |
+
heuristic : function, optional
|
| 26 |
+
Function to choose starting node for RCM algorithm. If None
|
| 27 |
+
a node from a pseudo-peripheral pair is used. A user-defined function
|
| 28 |
+
can be supplied that takes a graph object and returns a single node.
|
| 29 |
+
|
| 30 |
+
Returns
|
| 31 |
+
-------
|
| 32 |
+
nodes : generator
|
| 33 |
+
Generator of nodes in Cuthill-McKee ordering.
|
| 34 |
+
|
| 35 |
+
Examples
|
| 36 |
+
--------
|
| 37 |
+
>>> from networkx.utils import cuthill_mckee_ordering
|
| 38 |
+
>>> G = nx.path_graph(4)
|
| 39 |
+
>>> rcm = list(cuthill_mckee_ordering(G))
|
| 40 |
+
>>> A = nx.adjacency_matrix(G, nodelist=rcm)
|
| 41 |
+
|
| 42 |
+
Smallest degree node as heuristic function:
|
| 43 |
+
|
| 44 |
+
>>> def smallest_degree(G):
|
| 45 |
+
... return min(G, key=G.degree)
|
| 46 |
+
>>> rcm = list(cuthill_mckee_ordering(G, heuristic=smallest_degree))
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
See Also
|
| 50 |
+
--------
|
| 51 |
+
reverse_cuthill_mckee_ordering
|
| 52 |
+
|
| 53 |
+
Notes
|
| 54 |
+
-----
|
| 55 |
+
The optimal solution the bandwidth reduction is NP-complete [2]_.
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
References
|
| 59 |
+
----------
|
| 60 |
+
.. [1] E. Cuthill and J. McKee.
|
| 61 |
+
Reducing the bandwidth of sparse symmetric matrices,
|
| 62 |
+
In Proc. 24th Nat. Conf. ACM, pages 157-172, 1969.
|
| 63 |
+
http://doi.acm.org/10.1145/800195.805928
|
| 64 |
+
.. [2] Steven S. Skiena. 1997. The Algorithm Design Manual.
|
| 65 |
+
Springer-Verlag New York, Inc., New York, NY, USA.
|
| 66 |
+
"""
|
| 67 |
+
for c in nx.connected_components(G):
|
| 68 |
+
yield from connected_cuthill_mckee_ordering(G.subgraph(c), heuristic)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def reverse_cuthill_mckee_ordering(G, heuristic=None):
|
| 72 |
+
"""Generate an ordering (permutation) of the graph nodes to make
|
| 73 |
+
a sparse matrix.
|
| 74 |
+
|
| 75 |
+
Uses the reverse Cuthill-McKee heuristic (based on breadth-first search)
|
| 76 |
+
[1]_.
|
| 77 |
+
|
| 78 |
+
Parameters
|
| 79 |
+
----------
|
| 80 |
+
G : graph
|
| 81 |
+
A NetworkX graph
|
| 82 |
+
|
| 83 |
+
heuristic : function, optional
|
| 84 |
+
Function to choose starting node for RCM algorithm. If None
|
| 85 |
+
a node from a pseudo-peripheral pair is used. A user-defined function
|
| 86 |
+
can be supplied that takes a graph object and returns a single node.
|
| 87 |
+
|
| 88 |
+
Returns
|
| 89 |
+
-------
|
| 90 |
+
nodes : generator
|
| 91 |
+
Generator of nodes in reverse Cuthill-McKee ordering.
|
| 92 |
+
|
| 93 |
+
Examples
|
| 94 |
+
--------
|
| 95 |
+
>>> from networkx.utils import reverse_cuthill_mckee_ordering
|
| 96 |
+
>>> G = nx.path_graph(4)
|
| 97 |
+
>>> rcm = list(reverse_cuthill_mckee_ordering(G))
|
| 98 |
+
>>> A = nx.adjacency_matrix(G, nodelist=rcm)
|
| 99 |
+
|
| 100 |
+
Smallest degree node as heuristic function:
|
| 101 |
+
|
| 102 |
+
>>> def smallest_degree(G):
|
| 103 |
+
... return min(G, key=G.degree)
|
| 104 |
+
>>> rcm = list(reverse_cuthill_mckee_ordering(G, heuristic=smallest_degree))
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
See Also
|
| 108 |
+
--------
|
| 109 |
+
cuthill_mckee_ordering
|
| 110 |
+
|
| 111 |
+
Notes
|
| 112 |
+
-----
|
| 113 |
+
The optimal solution the bandwidth reduction is NP-complete [2]_.
|
| 114 |
+
|
| 115 |
+
References
|
| 116 |
+
----------
|
| 117 |
+
.. [1] E. Cuthill and J. McKee.
|
| 118 |
+
Reducing the bandwidth of sparse symmetric matrices,
|
| 119 |
+
In Proc. 24th Nat. Conf. ACM, pages 157-72, 1969.
|
| 120 |
+
http://doi.acm.org/10.1145/800195.805928
|
| 121 |
+
.. [2] Steven S. Skiena. 1997. The Algorithm Design Manual.
|
| 122 |
+
Springer-Verlag New York, Inc., New York, NY, USA.
|
| 123 |
+
"""
|
| 124 |
+
return reversed(list(cuthill_mckee_ordering(G, heuristic=heuristic)))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def connected_cuthill_mckee_ordering(G, heuristic=None):
|
| 128 |
+
# the cuthill mckee algorithm for connected graphs
|
| 129 |
+
if heuristic is None:
|
| 130 |
+
start = pseudo_peripheral_node(G)
|
| 131 |
+
else:
|
| 132 |
+
start = heuristic(G)
|
| 133 |
+
visited = {start}
|
| 134 |
+
queue = deque([start])
|
| 135 |
+
while queue:
|
| 136 |
+
parent = queue.popleft()
|
| 137 |
+
yield parent
|
| 138 |
+
nd = sorted(G.degree(set(G[parent]) - visited), key=itemgetter(1))
|
| 139 |
+
children = [n for n, d in nd]
|
| 140 |
+
visited.update(children)
|
| 141 |
+
queue.extend(children)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def pseudo_peripheral_node(G):
|
| 145 |
+
# helper for cuthill-mckee to find a node in a "pseudo peripheral pair"
|
| 146 |
+
# to use as good starting node
|
| 147 |
+
u = arbitrary_element(G)
|
| 148 |
+
lp = 0
|
| 149 |
+
v = u
|
| 150 |
+
while True:
|
| 151 |
+
spl = dict(nx.shortest_path_length(G, v))
|
| 152 |
+
l = max(spl.values())
|
| 153 |
+
if l <= lp:
|
| 154 |
+
break
|
| 155 |
+
lp = l
|
| 156 |
+
farthest = (n for n, dist in spl.items() if dist == l)
|
| 157 |
+
v, deg = min(G.degree(farthest), key=itemgetter(1))
|
| 158 |
+
return v
|
shared/package-files/31/31e6182e61583cd1b8d31359b26ecead2dba2ae003a7714c16afc1795bdbeceb/blob
ADDED
|
@@ -0,0 +1,1400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# FontDame-to-FontTools for OpenType Layout tables
|
| 2 |
+
#
|
| 3 |
+
# Source language spec is available at:
|
| 4 |
+
# http://monotype.github.io/OpenType_Table_Source/otl_source.html
|
| 5 |
+
# https://github.com/Monotype/OpenType_Table_Source/
|
| 6 |
+
|
| 7 |
+
from fontTools import ttLib
|
| 8 |
+
from fontTools.ttLib.tables._c_m_a_p import cmap_classes
|
| 9 |
+
from fontTools.ttLib.tables import otTables as ot
|
| 10 |
+
from fontTools.ttLib.tables.otBase import ValueRecord, valueRecordFormatDict
|
| 11 |
+
from fontTools.otlLib import builder as otl
|
| 12 |
+
from contextlib import contextmanager
|
| 13 |
+
from fontTools.ttLib import newTable
|
| 14 |
+
from fontTools.feaLib.lookupDebugInfo import LOOKUP_DEBUG_ENV_VAR, LOOKUP_DEBUG_INFO_KEY
|
| 15 |
+
from operator import setitem
|
| 16 |
+
import os
|
| 17 |
+
import logging
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class MtiLibError(Exception):
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ReferenceNotFoundError(MtiLibError):
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class FeatureNotFoundError(ReferenceNotFoundError):
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class LookupNotFoundError(ReferenceNotFoundError):
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
log = logging.getLogger("fontTools.mtiLib")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def makeGlyph(s):
|
| 40 |
+
if s[:2] in ["U ", "u "]:
|
| 41 |
+
return ttLib.TTFont._makeGlyphName(int(s[2:], 16))
|
| 42 |
+
elif s[:2] == "# ":
|
| 43 |
+
return "glyph%.5d" % int(s[2:])
|
| 44 |
+
assert s.find(" ") < 0, "Space found in glyph name: %s" % s
|
| 45 |
+
assert s, "Glyph name is empty"
|
| 46 |
+
return s
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def makeGlyphs(l):
|
| 50 |
+
return [makeGlyph(g) for g in l]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def mapLookup(sym, mapping):
|
| 54 |
+
# Lookups are addressed by name. So resolved them using a map if available.
|
| 55 |
+
# Fallback to parsing as lookup index if a map isn't provided.
|
| 56 |
+
if mapping is not None:
|
| 57 |
+
try:
|
| 58 |
+
idx = mapping[sym]
|
| 59 |
+
except KeyError:
|
| 60 |
+
raise LookupNotFoundError(sym)
|
| 61 |
+
else:
|
| 62 |
+
idx = int(sym)
|
| 63 |
+
return idx
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def mapFeature(sym, mapping):
|
| 67 |
+
# Features are referenced by index according the spec. So, if symbol is an
|
| 68 |
+
# integer, use it directly. Otherwise look up in the map if provided.
|
| 69 |
+
try:
|
| 70 |
+
idx = int(sym)
|
| 71 |
+
except ValueError:
|
| 72 |
+
try:
|
| 73 |
+
idx = mapping[sym]
|
| 74 |
+
except KeyError:
|
| 75 |
+
raise FeatureNotFoundError(sym)
|
| 76 |
+
return idx
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def setReference(mapper, mapping, sym, setter, collection, key):
|
| 80 |
+
try:
|
| 81 |
+
mapped = mapper(sym, mapping)
|
| 82 |
+
except ReferenceNotFoundError as e:
|
| 83 |
+
try:
|
| 84 |
+
if mapping is not None:
|
| 85 |
+
mapping.addDeferredMapping(
|
| 86 |
+
lambda ref: setter(collection, key, ref), sym, e
|
| 87 |
+
)
|
| 88 |
+
return
|
| 89 |
+
except AttributeError:
|
| 90 |
+
pass
|
| 91 |
+
raise
|
| 92 |
+
setter(collection, key, mapped)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class DeferredMapping(dict):
|
| 96 |
+
def __init__(self):
|
| 97 |
+
self._deferredMappings = []
|
| 98 |
+
|
| 99 |
+
def addDeferredMapping(self, setter, sym, e):
|
| 100 |
+
log.debug("Adding deferred mapping for symbol '%s' %s", sym, type(e).__name__)
|
| 101 |
+
self._deferredMappings.append((setter, sym, e))
|
| 102 |
+
|
| 103 |
+
def applyDeferredMappings(self):
|
| 104 |
+
for setter, sym, e in self._deferredMappings:
|
| 105 |
+
log.debug(
|
| 106 |
+
"Applying deferred mapping for symbol '%s' %s", sym, type(e).__name__
|
| 107 |
+
)
|
| 108 |
+
try:
|
| 109 |
+
mapped = self[sym]
|
| 110 |
+
except KeyError:
|
| 111 |
+
raise e
|
| 112 |
+
setter(mapped)
|
| 113 |
+
log.debug("Set to %s", mapped)
|
| 114 |
+
self._deferredMappings = []
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def parseScriptList(lines, featureMap=None):
|
| 118 |
+
self = ot.ScriptList()
|
| 119 |
+
records = []
|
| 120 |
+
with lines.between("script table"):
|
| 121 |
+
for line in lines:
|
| 122 |
+
while len(line) < 4:
|
| 123 |
+
line.append("")
|
| 124 |
+
scriptTag, langSysTag, defaultFeature, features = line
|
| 125 |
+
log.debug("Adding script %s language-system %s", scriptTag, langSysTag)
|
| 126 |
+
|
| 127 |
+
langSys = ot.LangSys()
|
| 128 |
+
langSys.LookupOrder = None
|
| 129 |
+
if defaultFeature:
|
| 130 |
+
setReference(
|
| 131 |
+
mapFeature,
|
| 132 |
+
featureMap,
|
| 133 |
+
defaultFeature,
|
| 134 |
+
setattr,
|
| 135 |
+
langSys,
|
| 136 |
+
"ReqFeatureIndex",
|
| 137 |
+
)
|
| 138 |
+
else:
|
| 139 |
+
langSys.ReqFeatureIndex = 0xFFFF
|
| 140 |
+
syms = stripSplitComma(features)
|
| 141 |
+
langSys.FeatureIndex = theList = [3] * len(syms)
|
| 142 |
+
for i, sym in enumerate(syms):
|
| 143 |
+
setReference(mapFeature, featureMap, sym, setitem, theList, i)
|
| 144 |
+
langSys.FeatureCount = len(langSys.FeatureIndex)
|
| 145 |
+
|
| 146 |
+
script = [s for s in records if s.ScriptTag == scriptTag]
|
| 147 |
+
if script:
|
| 148 |
+
script = script[0].Script
|
| 149 |
+
else:
|
| 150 |
+
scriptRec = ot.ScriptRecord()
|
| 151 |
+
scriptRec.ScriptTag = scriptTag + " " * (4 - len(scriptTag))
|
| 152 |
+
scriptRec.Script = ot.Script()
|
| 153 |
+
records.append(scriptRec)
|
| 154 |
+
script = scriptRec.Script
|
| 155 |
+
script.DefaultLangSys = None
|
| 156 |
+
script.LangSysRecord = []
|
| 157 |
+
script.LangSysCount = 0
|
| 158 |
+
|
| 159 |
+
if langSysTag == "default":
|
| 160 |
+
script.DefaultLangSys = langSys
|
| 161 |
+
else:
|
| 162 |
+
langSysRec = ot.LangSysRecord()
|
| 163 |
+
langSysRec.LangSysTag = langSysTag + " " * (4 - len(langSysTag))
|
| 164 |
+
langSysRec.LangSys = langSys
|
| 165 |
+
script.LangSysRecord.append(langSysRec)
|
| 166 |
+
script.LangSysCount = len(script.LangSysRecord)
|
| 167 |
+
|
| 168 |
+
for script in records:
|
| 169 |
+
script.Script.LangSysRecord = sorted(
|
| 170 |
+
script.Script.LangSysRecord, key=lambda rec: rec.LangSysTag
|
| 171 |
+
)
|
| 172 |
+
self.ScriptRecord = sorted(records, key=lambda rec: rec.ScriptTag)
|
| 173 |
+
self.ScriptCount = len(self.ScriptRecord)
|
| 174 |
+
return self
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def parseFeatureList(lines, lookupMap=None, featureMap=None):
|
| 178 |
+
self = ot.FeatureList()
|
| 179 |
+
self.FeatureRecord = []
|
| 180 |
+
with lines.between("feature table"):
|
| 181 |
+
for line in lines:
|
| 182 |
+
name, featureTag, lookups = line
|
| 183 |
+
if featureMap is not None:
|
| 184 |
+
assert name not in featureMap, "Duplicate feature name: %s" % name
|
| 185 |
+
featureMap[name] = len(self.FeatureRecord)
|
| 186 |
+
# If feature name is integer, make sure it matches its index.
|
| 187 |
+
try:
|
| 188 |
+
assert int(name) == len(self.FeatureRecord), "%d %d" % (
|
| 189 |
+
name,
|
| 190 |
+
len(self.FeatureRecord),
|
| 191 |
+
)
|
| 192 |
+
except ValueError:
|
| 193 |
+
pass
|
| 194 |
+
featureRec = ot.FeatureRecord()
|
| 195 |
+
featureRec.FeatureTag = featureTag
|
| 196 |
+
featureRec.Feature = ot.Feature()
|
| 197 |
+
self.FeatureRecord.append(featureRec)
|
| 198 |
+
feature = featureRec.Feature
|
| 199 |
+
feature.FeatureParams = None
|
| 200 |
+
syms = stripSplitComma(lookups)
|
| 201 |
+
feature.LookupListIndex = theList = [None] * len(syms)
|
| 202 |
+
for i, sym in enumerate(syms):
|
| 203 |
+
setReference(mapLookup, lookupMap, sym, setitem, theList, i)
|
| 204 |
+
feature.LookupCount = len(feature.LookupListIndex)
|
| 205 |
+
|
| 206 |
+
self.FeatureCount = len(self.FeatureRecord)
|
| 207 |
+
return self
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def parseLookupFlags(lines):
|
| 211 |
+
flags = 0
|
| 212 |
+
filterset = None
|
| 213 |
+
allFlags = [
|
| 214 |
+
"righttoleft",
|
| 215 |
+
"ignorebaseglyphs",
|
| 216 |
+
"ignoreligatures",
|
| 217 |
+
"ignoremarks",
|
| 218 |
+
"markattachmenttype",
|
| 219 |
+
"markfiltertype",
|
| 220 |
+
]
|
| 221 |
+
while lines.peeks()[0].lower() in allFlags:
|
| 222 |
+
line = next(lines)
|
| 223 |
+
flag = {
|
| 224 |
+
"righttoleft": 0x0001,
|
| 225 |
+
"ignorebaseglyphs": 0x0002,
|
| 226 |
+
"ignoreligatures": 0x0004,
|
| 227 |
+
"ignoremarks": 0x0008,
|
| 228 |
+
}.get(line[0].lower())
|
| 229 |
+
if flag:
|
| 230 |
+
assert line[1].lower() in ["yes", "no"], line[1]
|
| 231 |
+
if line[1].lower() == "yes":
|
| 232 |
+
flags |= flag
|
| 233 |
+
continue
|
| 234 |
+
if line[0].lower() == "markattachmenttype":
|
| 235 |
+
flags |= int(line[1]) << 8
|
| 236 |
+
continue
|
| 237 |
+
if line[0].lower() == "markfiltertype":
|
| 238 |
+
flags |= 0x10
|
| 239 |
+
filterset = int(line[1])
|
| 240 |
+
return flags, filterset
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def parseSingleSubst(lines, font, _lookupMap=None):
|
| 244 |
+
mapping = {}
|
| 245 |
+
for line in lines:
|
| 246 |
+
assert len(line) == 2, line
|
| 247 |
+
line = makeGlyphs(line)
|
| 248 |
+
mapping[line[0]] = line[1]
|
| 249 |
+
return otl.buildSingleSubstSubtable(mapping)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def parseMultiple(lines, font, _lookupMap=None):
|
| 253 |
+
mapping = {}
|
| 254 |
+
for line in lines:
|
| 255 |
+
line = makeGlyphs(line)
|
| 256 |
+
mapping[line[0]] = line[1:]
|
| 257 |
+
return otl.buildMultipleSubstSubtable(mapping)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def parseAlternate(lines, font, _lookupMap=None):
|
| 261 |
+
mapping = {}
|
| 262 |
+
for line in lines:
|
| 263 |
+
line = makeGlyphs(line)
|
| 264 |
+
mapping[line[0]] = line[1:]
|
| 265 |
+
return otl.buildAlternateSubstSubtable(mapping)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def parseLigature(lines, font, _lookupMap=None):
|
| 269 |
+
mapping = {}
|
| 270 |
+
for line in lines:
|
| 271 |
+
assert len(line) >= 2, line
|
| 272 |
+
line = makeGlyphs(line)
|
| 273 |
+
mapping[tuple(line[1:])] = line[0]
|
| 274 |
+
return otl.buildLigatureSubstSubtable(mapping)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def parseSinglePos(lines, font, _lookupMap=None):
|
| 278 |
+
values = {}
|
| 279 |
+
for line in lines:
|
| 280 |
+
assert len(line) == 3, line
|
| 281 |
+
w = line[0].title().replace(" ", "")
|
| 282 |
+
assert w in valueRecordFormatDict
|
| 283 |
+
g = makeGlyph(line[1])
|
| 284 |
+
v = int(line[2])
|
| 285 |
+
if g not in values:
|
| 286 |
+
values[g] = ValueRecord()
|
| 287 |
+
assert not hasattr(values[g], w), (g, w)
|
| 288 |
+
setattr(values[g], w, v)
|
| 289 |
+
return otl.buildSinglePosSubtable(values, font.getReverseGlyphMap())
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def parsePair(lines, font, _lookupMap=None):
|
| 293 |
+
self = ot.PairPos()
|
| 294 |
+
self.ValueFormat1 = self.ValueFormat2 = 0
|
| 295 |
+
typ = lines.peeks()[0].split()[0].lower()
|
| 296 |
+
if typ in ("left", "right"):
|
| 297 |
+
self.Format = 1
|
| 298 |
+
values = {}
|
| 299 |
+
for line in lines:
|
| 300 |
+
assert len(line) == 4, line
|
| 301 |
+
side = line[0].split()[0].lower()
|
| 302 |
+
assert side in ("left", "right"), side
|
| 303 |
+
what = line[0][len(side) :].title().replace(" ", "")
|
| 304 |
+
mask = valueRecordFormatDict[what][0]
|
| 305 |
+
glyph1, glyph2 = makeGlyphs(line[1:3])
|
| 306 |
+
value = int(line[3])
|
| 307 |
+
if not glyph1 in values:
|
| 308 |
+
values[glyph1] = {}
|
| 309 |
+
if not glyph2 in values[glyph1]:
|
| 310 |
+
values[glyph1][glyph2] = (ValueRecord(), ValueRecord())
|
| 311 |
+
rec2 = values[glyph1][glyph2]
|
| 312 |
+
if side == "left":
|
| 313 |
+
self.ValueFormat1 |= mask
|
| 314 |
+
vr = rec2[0]
|
| 315 |
+
else:
|
| 316 |
+
self.ValueFormat2 |= mask
|
| 317 |
+
vr = rec2[1]
|
| 318 |
+
assert not hasattr(vr, what), (vr, what)
|
| 319 |
+
setattr(vr, what, value)
|
| 320 |
+
self.Coverage = makeCoverage(set(values.keys()), font)
|
| 321 |
+
self.PairSet = []
|
| 322 |
+
for glyph1 in self.Coverage.glyphs:
|
| 323 |
+
values1 = values[glyph1]
|
| 324 |
+
pairset = ot.PairSet()
|
| 325 |
+
records = pairset.PairValueRecord = []
|
| 326 |
+
for glyph2 in sorted(values1.keys(), key=font.getGlyphID):
|
| 327 |
+
values2 = values1[glyph2]
|
| 328 |
+
pair = ot.PairValueRecord()
|
| 329 |
+
pair.SecondGlyph = glyph2
|
| 330 |
+
pair.Value1 = values2[0]
|
| 331 |
+
pair.Value2 = values2[1] if self.ValueFormat2 else None
|
| 332 |
+
records.append(pair)
|
| 333 |
+
pairset.PairValueCount = len(pairset.PairValueRecord)
|
| 334 |
+
self.PairSet.append(pairset)
|
| 335 |
+
self.PairSetCount = len(self.PairSet)
|
| 336 |
+
elif typ.endswith("class"):
|
| 337 |
+
self.Format = 2
|
| 338 |
+
classDefs = [None, None]
|
| 339 |
+
while lines.peeks()[0].endswith("class definition begin"):
|
| 340 |
+
typ = lines.peek()[0][: -len("class definition begin")].lower()
|
| 341 |
+
idx, klass = {
|
| 342 |
+
"first": (0, ot.ClassDef1),
|
| 343 |
+
"second": (1, ot.ClassDef2),
|
| 344 |
+
}[typ]
|
| 345 |
+
assert classDefs[idx] is None
|
| 346 |
+
classDefs[idx] = parseClassDef(lines, font, klass=klass)
|
| 347 |
+
self.ClassDef1, self.ClassDef2 = classDefs
|
| 348 |
+
self.Class1Count, self.Class2Count = (
|
| 349 |
+
1 + max(c.classDefs.values()) for c in classDefs
|
| 350 |
+
)
|
| 351 |
+
self.Class1Record = [ot.Class1Record() for i in range(self.Class1Count)]
|
| 352 |
+
for rec1 in self.Class1Record:
|
| 353 |
+
rec1.Class2Record = [ot.Class2Record() for j in range(self.Class2Count)]
|
| 354 |
+
for rec2 in rec1.Class2Record:
|
| 355 |
+
rec2.Value1 = ValueRecord()
|
| 356 |
+
rec2.Value2 = ValueRecord()
|
| 357 |
+
for line in lines:
|
| 358 |
+
assert len(line) == 4, line
|
| 359 |
+
side = line[0].split()[0].lower()
|
| 360 |
+
assert side in ("left", "right"), side
|
| 361 |
+
what = line[0][len(side) :].title().replace(" ", "")
|
| 362 |
+
mask = valueRecordFormatDict[what][0]
|
| 363 |
+
class1, class2, value = (int(x) for x in line[1:4])
|
| 364 |
+
rec2 = self.Class1Record[class1].Class2Record[class2]
|
| 365 |
+
if side == "left":
|
| 366 |
+
self.ValueFormat1 |= mask
|
| 367 |
+
vr = rec2.Value1
|
| 368 |
+
else:
|
| 369 |
+
self.ValueFormat2 |= mask
|
| 370 |
+
vr = rec2.Value2
|
| 371 |
+
assert not hasattr(vr, what), (vr, what)
|
| 372 |
+
setattr(vr, what, value)
|
| 373 |
+
for rec1 in self.Class1Record:
|
| 374 |
+
for rec2 in rec1.Class2Record:
|
| 375 |
+
rec2.Value1 = ValueRecord(self.ValueFormat1, rec2.Value1)
|
| 376 |
+
rec2.Value2 = (
|
| 377 |
+
ValueRecord(self.ValueFormat2, rec2.Value2)
|
| 378 |
+
if self.ValueFormat2
|
| 379 |
+
else None
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
self.Coverage = makeCoverage(set(self.ClassDef1.classDefs.keys()), font)
|
| 383 |
+
else:
|
| 384 |
+
assert 0, typ
|
| 385 |
+
return self
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def parseKernset(lines, font, _lookupMap=None):
|
| 389 |
+
typ = lines.peeks()[0].split()[0].lower()
|
| 390 |
+
if typ in ("left", "right"):
|
| 391 |
+
with lines.until(
|
| 392 |
+
("firstclass definition begin", "secondclass definition begin")
|
| 393 |
+
):
|
| 394 |
+
return parsePair(lines, font)
|
| 395 |
+
return parsePair(lines, font)
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def makeAnchor(data, klass=ot.Anchor):
|
| 399 |
+
assert len(data) <= 2
|
| 400 |
+
anchor = klass()
|
| 401 |
+
anchor.Format = 1
|
| 402 |
+
anchor.XCoordinate, anchor.YCoordinate = intSplitComma(data[0])
|
| 403 |
+
if len(data) > 1 and data[1] != "":
|
| 404 |
+
anchor.Format = 2
|
| 405 |
+
anchor.AnchorPoint = int(data[1])
|
| 406 |
+
return anchor
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def parseCursive(lines, font, _lookupMap=None):
|
| 410 |
+
records = {}
|
| 411 |
+
for line in lines:
|
| 412 |
+
assert len(line) in [3, 4], line
|
| 413 |
+
idx, klass = {
|
| 414 |
+
"entry": (0, ot.EntryAnchor),
|
| 415 |
+
"exit": (1, ot.ExitAnchor),
|
| 416 |
+
}[line[0]]
|
| 417 |
+
glyph = makeGlyph(line[1])
|
| 418 |
+
if glyph not in records:
|
| 419 |
+
records[glyph] = [None, None]
|
| 420 |
+
assert records[glyph][idx] is None, (glyph, idx)
|
| 421 |
+
records[glyph][idx] = makeAnchor(line[2:], klass)
|
| 422 |
+
return otl.buildCursivePosSubtable(records, font.getReverseGlyphMap())
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def makeMarkRecords(data, coverage, c):
|
| 426 |
+
records = []
|
| 427 |
+
for glyph in coverage.glyphs:
|
| 428 |
+
klass, anchor = data[glyph]
|
| 429 |
+
record = c.MarkRecordClass()
|
| 430 |
+
record.Class = klass
|
| 431 |
+
setattr(record, c.MarkAnchor, anchor)
|
| 432 |
+
records.append(record)
|
| 433 |
+
return records
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def makeBaseRecords(data, coverage, c, classCount):
|
| 437 |
+
records = []
|
| 438 |
+
idx = {}
|
| 439 |
+
for glyph in coverage.glyphs:
|
| 440 |
+
idx[glyph] = len(records)
|
| 441 |
+
record = c.BaseRecordClass()
|
| 442 |
+
anchors = [None] * classCount
|
| 443 |
+
setattr(record, c.BaseAnchor, anchors)
|
| 444 |
+
records.append(record)
|
| 445 |
+
for (glyph, klass), anchor in data.items():
|
| 446 |
+
record = records[idx[glyph]]
|
| 447 |
+
anchors = getattr(record, c.BaseAnchor)
|
| 448 |
+
assert anchors[klass] is None, (glyph, klass)
|
| 449 |
+
anchors[klass] = anchor
|
| 450 |
+
return records
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def makeLigatureRecords(data, coverage, c, classCount):
|
| 454 |
+
records = [None] * len(coverage.glyphs)
|
| 455 |
+
idx = {g: i for i, g in enumerate(coverage.glyphs)}
|
| 456 |
+
|
| 457 |
+
for (glyph, klass, compIdx, compCount), anchor in data.items():
|
| 458 |
+
record = records[idx[glyph]]
|
| 459 |
+
if record is None:
|
| 460 |
+
record = records[idx[glyph]] = ot.LigatureAttach()
|
| 461 |
+
record.ComponentCount = compCount
|
| 462 |
+
record.ComponentRecord = [ot.ComponentRecord() for i in range(compCount)]
|
| 463 |
+
for compRec in record.ComponentRecord:
|
| 464 |
+
compRec.LigatureAnchor = [None] * classCount
|
| 465 |
+
assert record.ComponentCount == compCount, (
|
| 466 |
+
glyph,
|
| 467 |
+
record.ComponentCount,
|
| 468 |
+
compCount,
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
anchors = record.ComponentRecord[compIdx - 1].LigatureAnchor
|
| 472 |
+
assert anchors[klass] is None, (glyph, compIdx, klass)
|
| 473 |
+
anchors[klass] = anchor
|
| 474 |
+
return records
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def parseMarkToSomething(lines, font, c):
|
| 478 |
+
self = c.Type()
|
| 479 |
+
self.Format = 1
|
| 480 |
+
markData = {}
|
| 481 |
+
baseData = {}
|
| 482 |
+
Data = {
|
| 483 |
+
"mark": (markData, c.MarkAnchorClass),
|
| 484 |
+
"base": (baseData, c.BaseAnchorClass),
|
| 485 |
+
"ligature": (baseData, c.BaseAnchorClass),
|
| 486 |
+
}
|
| 487 |
+
maxKlass = 0
|
| 488 |
+
for line in lines:
|
| 489 |
+
typ = line[0]
|
| 490 |
+
assert typ in ("mark", "base", "ligature")
|
| 491 |
+
glyph = makeGlyph(line[1])
|
| 492 |
+
data, anchorClass = Data[typ]
|
| 493 |
+
extraItems = 2 if typ == "ligature" else 0
|
| 494 |
+
extras = tuple(int(i) for i in line[2 : 2 + extraItems])
|
| 495 |
+
klass = int(line[2 + extraItems])
|
| 496 |
+
anchor = makeAnchor(line[3 + extraItems :], anchorClass)
|
| 497 |
+
if typ == "mark":
|
| 498 |
+
key, value = glyph, (klass, anchor)
|
| 499 |
+
else:
|
| 500 |
+
key, value = ((glyph, klass) + extras), anchor
|
| 501 |
+
assert key not in data, key
|
| 502 |
+
data[key] = value
|
| 503 |
+
maxKlass = max(maxKlass, klass)
|
| 504 |
+
|
| 505 |
+
# Mark
|
| 506 |
+
markCoverage = makeCoverage(set(markData.keys()), font, c.MarkCoverageClass)
|
| 507 |
+
markArray = c.MarkArrayClass()
|
| 508 |
+
markRecords = makeMarkRecords(markData, markCoverage, c)
|
| 509 |
+
setattr(markArray, c.MarkRecord, markRecords)
|
| 510 |
+
setattr(markArray, c.MarkCount, len(markRecords))
|
| 511 |
+
setattr(self, c.MarkCoverage, markCoverage)
|
| 512 |
+
setattr(self, c.MarkArray, markArray)
|
| 513 |
+
self.ClassCount = maxKlass + 1
|
| 514 |
+
|
| 515 |
+
# Base
|
| 516 |
+
self.classCount = 0 if not baseData else 1 + max(k[1] for k, v in baseData.items())
|
| 517 |
+
baseCoverage = makeCoverage(
|
| 518 |
+
set([k[0] for k in baseData.keys()]), font, c.BaseCoverageClass
|
| 519 |
+
)
|
| 520 |
+
baseArray = c.BaseArrayClass()
|
| 521 |
+
if c.Base == "Ligature":
|
| 522 |
+
baseRecords = makeLigatureRecords(baseData, baseCoverage, c, self.classCount)
|
| 523 |
+
else:
|
| 524 |
+
baseRecords = makeBaseRecords(baseData, baseCoverage, c, self.classCount)
|
| 525 |
+
setattr(baseArray, c.BaseRecord, baseRecords)
|
| 526 |
+
setattr(baseArray, c.BaseCount, len(baseRecords))
|
| 527 |
+
setattr(self, c.BaseCoverage, baseCoverage)
|
| 528 |
+
setattr(self, c.BaseArray, baseArray)
|
| 529 |
+
|
| 530 |
+
return self
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
class MarkHelper(object):
|
| 534 |
+
def __init__(self):
|
| 535 |
+
for Which in ("Mark", "Base"):
|
| 536 |
+
for What in ("Coverage", "Array", "Count", "Record", "Anchor"):
|
| 537 |
+
key = Which + What
|
| 538 |
+
if Which == "Mark" and What in ("Count", "Record", "Anchor"):
|
| 539 |
+
value = key
|
| 540 |
+
else:
|
| 541 |
+
value = getattr(self, Which) + What
|
| 542 |
+
if value == "LigatureRecord":
|
| 543 |
+
value = "LigatureAttach"
|
| 544 |
+
setattr(self, key, value)
|
| 545 |
+
if What != "Count":
|
| 546 |
+
klass = getattr(ot, value)
|
| 547 |
+
setattr(self, key + "Class", klass)
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
class MarkToBaseHelper(MarkHelper):
|
| 551 |
+
Mark = "Mark"
|
| 552 |
+
Base = "Base"
|
| 553 |
+
Type = ot.MarkBasePos
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
class MarkToMarkHelper(MarkHelper):
|
| 557 |
+
Mark = "Mark1"
|
| 558 |
+
Base = "Mark2"
|
| 559 |
+
Type = ot.MarkMarkPos
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
class MarkToLigatureHelper(MarkHelper):
|
| 563 |
+
Mark = "Mark"
|
| 564 |
+
Base = "Ligature"
|
| 565 |
+
Type = ot.MarkLigPos
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def parseMarkToBase(lines, font, _lookupMap=None):
|
| 569 |
+
return parseMarkToSomething(lines, font, MarkToBaseHelper())
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def parseMarkToMark(lines, font, _lookupMap=None):
|
| 573 |
+
return parseMarkToSomething(lines, font, MarkToMarkHelper())
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def parseMarkToLigature(lines, font, _lookupMap=None):
|
| 577 |
+
return parseMarkToSomething(lines, font, MarkToLigatureHelper())
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def stripSplitComma(line):
|
| 581 |
+
return [s.strip() for s in line.split(",")] if line else []
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def intSplitComma(line):
|
| 585 |
+
return [int(i) for i in line.split(",")] if line else []
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
# Copied from fontTools.subset
|
| 589 |
+
class ContextHelper(object):
|
| 590 |
+
def __init__(self, klassName, Format):
|
| 591 |
+
if klassName.endswith("Subst"):
|
| 592 |
+
Typ = "Sub"
|
| 593 |
+
Type = "Subst"
|
| 594 |
+
else:
|
| 595 |
+
Typ = "Pos"
|
| 596 |
+
Type = "Pos"
|
| 597 |
+
if klassName.startswith("Chain"):
|
| 598 |
+
Chain = "Chain"
|
| 599 |
+
InputIdx = 1
|
| 600 |
+
DataLen = 3
|
| 601 |
+
else:
|
| 602 |
+
Chain = ""
|
| 603 |
+
InputIdx = 0
|
| 604 |
+
DataLen = 1
|
| 605 |
+
ChainTyp = Chain + Typ
|
| 606 |
+
|
| 607 |
+
self.Typ = Typ
|
| 608 |
+
self.Type = Type
|
| 609 |
+
self.Chain = Chain
|
| 610 |
+
self.ChainTyp = ChainTyp
|
| 611 |
+
self.InputIdx = InputIdx
|
| 612 |
+
self.DataLen = DataLen
|
| 613 |
+
|
| 614 |
+
self.LookupRecord = Type + "LookupRecord"
|
| 615 |
+
|
| 616 |
+
if Format == 1:
|
| 617 |
+
Coverage = lambda r: r.Coverage
|
| 618 |
+
ChainCoverage = lambda r: r.Coverage
|
| 619 |
+
ContextData = lambda r: (None,)
|
| 620 |
+
ChainContextData = lambda r: (None, None, None)
|
| 621 |
+
SetContextData = None
|
| 622 |
+
SetChainContextData = None
|
| 623 |
+
RuleData = lambda r: (r.Input,)
|
| 624 |
+
ChainRuleData = lambda r: (r.Backtrack, r.Input, r.LookAhead)
|
| 625 |
+
|
| 626 |
+
def SetRuleData(r, d):
|
| 627 |
+
(r.Input,) = d
|
| 628 |
+
(r.GlyphCount,) = (len(x) + 1 for x in d)
|
| 629 |
+
|
| 630 |
+
def ChainSetRuleData(r, d):
|
| 631 |
+
r.Backtrack, r.Input, r.LookAhead = d
|
| 632 |
+
(
|
| 633 |
+
r.BacktrackGlyphCount,
|
| 634 |
+
r.InputGlyphCount,
|
| 635 |
+
r.LookAheadGlyphCount,
|
| 636 |
+
) = (len(d[0]), len(d[1]) + 1, len(d[2]))
|
| 637 |
+
|
| 638 |
+
elif Format == 2:
|
| 639 |
+
Coverage = lambda r: r.Coverage
|
| 640 |
+
ChainCoverage = lambda r: r.Coverage
|
| 641 |
+
ContextData = lambda r: (r.ClassDef,)
|
| 642 |
+
ChainContextData = lambda r: (
|
| 643 |
+
r.BacktrackClassDef,
|
| 644 |
+
r.InputClassDef,
|
| 645 |
+
r.LookAheadClassDef,
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
def SetContextData(r, d):
|
| 649 |
+
(r.ClassDef,) = d
|
| 650 |
+
|
| 651 |
+
def SetChainContextData(r, d):
|
| 652 |
+
r.BacktrackClassDef, r.InputClassDef, r.LookAheadClassDef = d
|
| 653 |
+
|
| 654 |
+
RuleData = lambda r: (r.Class,)
|
| 655 |
+
ChainRuleData = lambda r: (r.Backtrack, r.Input, r.LookAhead)
|
| 656 |
+
|
| 657 |
+
def SetRuleData(r, d):
|
| 658 |
+
(r.Class,) = d
|
| 659 |
+
(r.GlyphCount,) = (len(x) + 1 for x in d)
|
| 660 |
+
|
| 661 |
+
def ChainSetRuleData(r, d):
|
| 662 |
+
r.Backtrack, r.Input, r.LookAhead = d
|
| 663 |
+
(
|
| 664 |
+
r.BacktrackGlyphCount,
|
| 665 |
+
r.InputGlyphCount,
|
| 666 |
+
r.LookAheadGlyphCount,
|
| 667 |
+
) = (len(d[0]), len(d[1]) + 1, len(d[2]))
|
| 668 |
+
|
| 669 |
+
elif Format == 3:
|
| 670 |
+
Coverage = lambda r: r.Coverage[0]
|
| 671 |
+
ChainCoverage = lambda r: r.InputCoverage[0]
|
| 672 |
+
ContextData = None
|
| 673 |
+
ChainContextData = None
|
| 674 |
+
SetContextData = None
|
| 675 |
+
SetChainContextData = None
|
| 676 |
+
RuleData = lambda r: r.Coverage
|
| 677 |
+
ChainRuleData = lambda r: (
|
| 678 |
+
r.BacktrackCoverage + r.InputCoverage + r.LookAheadCoverage
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
def SetRuleData(r, d):
|
| 682 |
+
(r.Coverage,) = d
|
| 683 |
+
(r.GlyphCount,) = (len(x) for x in d)
|
| 684 |
+
|
| 685 |
+
def ChainSetRuleData(r, d):
|
| 686 |
+
r.BacktrackCoverage, r.InputCoverage, r.LookAheadCoverage = d
|
| 687 |
+
(
|
| 688 |
+
r.BacktrackGlyphCount,
|
| 689 |
+
r.InputGlyphCount,
|
| 690 |
+
r.LookAheadGlyphCount,
|
| 691 |
+
) = (len(x) for x in d)
|
| 692 |
+
|
| 693 |
+
else:
|
| 694 |
+
assert 0, "unknown format: %s" % Format
|
| 695 |
+
|
| 696 |
+
if Chain:
|
| 697 |
+
self.Coverage = ChainCoverage
|
| 698 |
+
self.ContextData = ChainContextData
|
| 699 |
+
self.SetContextData = SetChainContextData
|
| 700 |
+
self.RuleData = ChainRuleData
|
| 701 |
+
self.SetRuleData = ChainSetRuleData
|
| 702 |
+
else:
|
| 703 |
+
self.Coverage = Coverage
|
| 704 |
+
self.ContextData = ContextData
|
| 705 |
+
self.SetContextData = SetContextData
|
| 706 |
+
self.RuleData = RuleData
|
| 707 |
+
self.SetRuleData = SetRuleData
|
| 708 |
+
|
| 709 |
+
if Format == 1:
|
| 710 |
+
self.Rule = ChainTyp + "Rule"
|
| 711 |
+
self.RuleCount = ChainTyp + "RuleCount"
|
| 712 |
+
self.RuleSet = ChainTyp + "RuleSet"
|
| 713 |
+
self.RuleSetCount = ChainTyp + "RuleSetCount"
|
| 714 |
+
self.Intersect = lambda glyphs, c, r: [r] if r in glyphs else []
|
| 715 |
+
elif Format == 2:
|
| 716 |
+
self.Rule = ChainTyp + "ClassRule"
|
| 717 |
+
self.RuleCount = ChainTyp + "ClassRuleCount"
|
| 718 |
+
self.RuleSet = ChainTyp + "ClassSet"
|
| 719 |
+
self.RuleSetCount = ChainTyp + "ClassSetCount"
|
| 720 |
+
self.Intersect = lambda glyphs, c, r: (
|
| 721 |
+
c.intersect_class(glyphs, r)
|
| 722 |
+
if c
|
| 723 |
+
else (set(glyphs) if r == 0 else set())
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
self.ClassDef = "InputClassDef" if Chain else "ClassDef"
|
| 727 |
+
self.ClassDefIndex = 1 if Chain else 0
|
| 728 |
+
self.Input = "Input" if Chain else "Class"
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
def parseLookupRecords(items, klassName, lookupMap=None):
|
| 732 |
+
klass = getattr(ot, klassName)
|
| 733 |
+
lst = []
|
| 734 |
+
for item in items:
|
| 735 |
+
rec = klass()
|
| 736 |
+
item = stripSplitComma(item)
|
| 737 |
+
assert len(item) == 2, item
|
| 738 |
+
idx = int(item[0])
|
| 739 |
+
assert idx > 0, idx
|
| 740 |
+
rec.SequenceIndex = idx - 1
|
| 741 |
+
setReference(mapLookup, lookupMap, item[1], setattr, rec, "LookupListIndex")
|
| 742 |
+
lst.append(rec)
|
| 743 |
+
return lst
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
def makeClassDef(classDefs, font, klass=ot.Coverage):
|
| 747 |
+
if not classDefs:
|
| 748 |
+
return None
|
| 749 |
+
self = klass()
|
| 750 |
+
self.classDefs = dict(classDefs)
|
| 751 |
+
return self
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def parseClassDef(lines, font, klass=ot.ClassDef):
|
| 755 |
+
classDefs = {}
|
| 756 |
+
with lines.between("class definition"):
|
| 757 |
+
for line in lines:
|
| 758 |
+
glyph = makeGlyph(line[0])
|
| 759 |
+
assert glyph not in classDefs, glyph
|
| 760 |
+
classDefs[glyph] = int(line[1])
|
| 761 |
+
return makeClassDef(classDefs, font, klass)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
def makeCoverage(glyphs, font, klass=ot.Coverage):
|
| 765 |
+
if not glyphs:
|
| 766 |
+
return None
|
| 767 |
+
if isinstance(glyphs, set):
|
| 768 |
+
glyphs = sorted(glyphs)
|
| 769 |
+
coverage = klass()
|
| 770 |
+
coverage.glyphs = sorted(set(glyphs), key=font.getGlyphID)
|
| 771 |
+
return coverage
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
def parseCoverage(lines, font, klass=ot.Coverage):
|
| 775 |
+
glyphs = []
|
| 776 |
+
with lines.between("coverage definition"):
|
| 777 |
+
for line in lines:
|
| 778 |
+
glyphs.append(makeGlyph(line[0]))
|
| 779 |
+
return makeCoverage(glyphs, font, klass)
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
def bucketizeRules(self, c, rules, bucketKeys):
|
| 783 |
+
buckets = {}
|
| 784 |
+
for seq, recs in rules:
|
| 785 |
+
buckets.setdefault(seq[c.InputIdx][0], []).append(
|
| 786 |
+
(tuple(s[1 if i == c.InputIdx else 0 :] for i, s in enumerate(seq)), recs)
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
rulesets = []
|
| 790 |
+
for firstGlyph in bucketKeys:
|
| 791 |
+
if firstGlyph not in buckets:
|
| 792 |
+
rulesets.append(None)
|
| 793 |
+
continue
|
| 794 |
+
thisRules = []
|
| 795 |
+
for seq, recs in buckets[firstGlyph]:
|
| 796 |
+
rule = getattr(ot, c.Rule)()
|
| 797 |
+
c.SetRuleData(rule, seq)
|
| 798 |
+
setattr(rule, c.Type + "Count", len(recs))
|
| 799 |
+
setattr(rule, c.LookupRecord, recs)
|
| 800 |
+
thisRules.append(rule)
|
| 801 |
+
|
| 802 |
+
ruleset = getattr(ot, c.RuleSet)()
|
| 803 |
+
setattr(ruleset, c.Rule, thisRules)
|
| 804 |
+
setattr(ruleset, c.RuleCount, len(thisRules))
|
| 805 |
+
rulesets.append(ruleset)
|
| 806 |
+
|
| 807 |
+
setattr(self, c.RuleSet, rulesets)
|
| 808 |
+
setattr(self, c.RuleSetCount, len(rulesets))
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
def parseContext(lines, font, Type, lookupMap=None):
|
| 812 |
+
self = getattr(ot, Type)()
|
| 813 |
+
typ = lines.peeks()[0].split()[0].lower()
|
| 814 |
+
if typ == "glyph":
|
| 815 |
+
self.Format = 1
|
| 816 |
+
log.debug("Parsing %s format %s", Type, self.Format)
|
| 817 |
+
c = ContextHelper(Type, self.Format)
|
| 818 |
+
rules = []
|
| 819 |
+
for line in lines:
|
| 820 |
+
assert line[0].lower() == "glyph", line[0]
|
| 821 |
+
while len(line) < 1 + c.DataLen:
|
| 822 |
+
line.append("")
|
| 823 |
+
seq = tuple(makeGlyphs(stripSplitComma(i)) for i in line[1 : 1 + c.DataLen])
|
| 824 |
+
recs = parseLookupRecords(line[1 + c.DataLen :], c.LookupRecord, lookupMap)
|
| 825 |
+
rules.append((seq, recs))
|
| 826 |
+
|
| 827 |
+
firstGlyphs = set(seq[c.InputIdx][0] for seq, recs in rules)
|
| 828 |
+
self.Coverage = makeCoverage(firstGlyphs, font)
|
| 829 |
+
bucketizeRules(self, c, rules, self.Coverage.glyphs)
|
| 830 |
+
elif typ.endswith("class"):
|
| 831 |
+
self.Format = 2
|
| 832 |
+
log.debug("Parsing %s format %s", Type, self.Format)
|
| 833 |
+
c = ContextHelper(Type, self.Format)
|
| 834 |
+
classDefs = [None] * c.DataLen
|
| 835 |
+
while lines.peeks()[0].endswith("class definition begin"):
|
| 836 |
+
typ = lines.peek()[0][: -len("class definition begin")].lower()
|
| 837 |
+
idx, klass = {
|
| 838 |
+
1: {
|
| 839 |
+
"": (0, ot.ClassDef),
|
| 840 |
+
},
|
| 841 |
+
3: {
|
| 842 |
+
"backtrack": (0, ot.BacktrackClassDef),
|
| 843 |
+
"": (1, ot.InputClassDef),
|
| 844 |
+
"lookahead": (2, ot.LookAheadClassDef),
|
| 845 |
+
},
|
| 846 |
+
}[c.DataLen][typ]
|
| 847 |
+
assert classDefs[idx] is None, idx
|
| 848 |
+
classDefs[idx] = parseClassDef(lines, font, klass=klass)
|
| 849 |
+
c.SetContextData(self, classDefs)
|
| 850 |
+
rules = []
|
| 851 |
+
for line in lines:
|
| 852 |
+
assert line[0].lower().startswith("class"), line[0]
|
| 853 |
+
while len(line) < 1 + c.DataLen:
|
| 854 |
+
line.append("")
|
| 855 |
+
seq = tuple(intSplitComma(i) for i in line[1 : 1 + c.DataLen])
|
| 856 |
+
recs = parseLookupRecords(line[1 + c.DataLen :], c.LookupRecord, lookupMap)
|
| 857 |
+
rules.append((seq, recs))
|
| 858 |
+
firstClasses = set(seq[c.InputIdx][0] for seq, recs in rules)
|
| 859 |
+
firstGlyphs = set(
|
| 860 |
+
g for g, c in classDefs[c.InputIdx].classDefs.items() if c in firstClasses
|
| 861 |
+
)
|
| 862 |
+
self.Coverage = makeCoverage(firstGlyphs, font)
|
| 863 |
+
bucketizeRules(self, c, rules, range(max(firstClasses) + 1))
|
| 864 |
+
elif typ.endswith("coverage"):
|
| 865 |
+
self.Format = 3
|
| 866 |
+
log.debug("Parsing %s format %s", Type, self.Format)
|
| 867 |
+
c = ContextHelper(Type, self.Format)
|
| 868 |
+
coverages = tuple([] for i in range(c.DataLen))
|
| 869 |
+
while lines.peeks()[0].endswith("coverage definition begin"):
|
| 870 |
+
typ = lines.peek()[0][: -len("coverage definition begin")].lower()
|
| 871 |
+
idx, klass = {
|
| 872 |
+
1: {
|
| 873 |
+
"": (0, ot.Coverage),
|
| 874 |
+
},
|
| 875 |
+
3: {
|
| 876 |
+
"backtrack": (0, ot.BacktrackCoverage),
|
| 877 |
+
"input": (1, ot.InputCoverage),
|
| 878 |
+
"lookahead": (2, ot.LookAheadCoverage),
|
| 879 |
+
},
|
| 880 |
+
}[c.DataLen][typ]
|
| 881 |
+
coverages[idx].append(parseCoverage(lines, font, klass=klass))
|
| 882 |
+
c.SetRuleData(self, coverages)
|
| 883 |
+
lines = list(lines)
|
| 884 |
+
assert len(lines) == 1
|
| 885 |
+
line = lines[0]
|
| 886 |
+
assert line[0].lower() == "coverage", line[0]
|
| 887 |
+
recs = parseLookupRecords(line[1:], c.LookupRecord, lookupMap)
|
| 888 |
+
setattr(self, c.Type + "Count", len(recs))
|
| 889 |
+
setattr(self, c.LookupRecord, recs)
|
| 890 |
+
else:
|
| 891 |
+
assert 0, typ
|
| 892 |
+
return self
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
def parseContextSubst(lines, font, lookupMap=None):
|
| 896 |
+
return parseContext(lines, font, "ContextSubst", lookupMap=lookupMap)
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
def parseContextPos(lines, font, lookupMap=None):
|
| 900 |
+
return parseContext(lines, font, "ContextPos", lookupMap=lookupMap)
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
def parseChainedSubst(lines, font, lookupMap=None):
|
| 904 |
+
return parseContext(lines, font, "ChainContextSubst", lookupMap=lookupMap)
|
| 905 |
+
|
| 906 |
+
|
| 907 |
+
def parseChainedPos(lines, font, lookupMap=None):
|
| 908 |
+
return parseContext(lines, font, "ChainContextPos", lookupMap=lookupMap)
|
| 909 |
+
|
| 910 |
+
|
| 911 |
+
def parseReverseChainedSubst(lines, font, _lookupMap=None):
|
| 912 |
+
self = ot.ReverseChainSingleSubst()
|
| 913 |
+
self.Format = 1
|
| 914 |
+
coverages = ([], [])
|
| 915 |
+
while lines.peeks()[0].endswith("coverage definition begin"):
|
| 916 |
+
typ = lines.peek()[0][: -len("coverage definition begin")].lower()
|
| 917 |
+
idx, klass = {
|
| 918 |
+
"backtrack": (0, ot.BacktrackCoverage),
|
| 919 |
+
"lookahead": (1, ot.LookAheadCoverage),
|
| 920 |
+
}[typ]
|
| 921 |
+
coverages[idx].append(parseCoverage(lines, font, klass=klass))
|
| 922 |
+
self.BacktrackCoverage = coverages[0]
|
| 923 |
+
self.BacktrackGlyphCount = len(self.BacktrackCoverage)
|
| 924 |
+
self.LookAheadCoverage = coverages[1]
|
| 925 |
+
self.LookAheadGlyphCount = len(self.LookAheadCoverage)
|
| 926 |
+
mapping = {}
|
| 927 |
+
for line in lines:
|
| 928 |
+
assert len(line) == 2, line
|
| 929 |
+
line = makeGlyphs(line)
|
| 930 |
+
mapping[line[0]] = line[1]
|
| 931 |
+
self.Coverage = makeCoverage(set(mapping.keys()), font)
|
| 932 |
+
self.Substitute = [mapping[k] for k in self.Coverage.glyphs]
|
| 933 |
+
self.GlyphCount = len(self.Substitute)
|
| 934 |
+
return self
|
| 935 |
+
|
| 936 |
+
|
| 937 |
+
def parseLookup(lines, tableTag, font, lookupMap=None):
|
| 938 |
+
line = lines.expect("lookup")
|
| 939 |
+
_, name, typ = line
|
| 940 |
+
log.debug("Parsing lookup type %s %s", typ, name)
|
| 941 |
+
lookup = ot.Lookup()
|
| 942 |
+
lookup.LookupFlag, filterset = parseLookupFlags(lines)
|
| 943 |
+
if filterset is not None:
|
| 944 |
+
lookup.MarkFilteringSet = filterset
|
| 945 |
+
lookup.LookupType, parseLookupSubTable = {
|
| 946 |
+
"GSUB": {
|
| 947 |
+
"single": (1, parseSingleSubst),
|
| 948 |
+
"multiple": (2, parseMultiple),
|
| 949 |
+
"alternate": (3, parseAlternate),
|
| 950 |
+
"ligature": (4, parseLigature),
|
| 951 |
+
"context": (5, parseContextSubst),
|
| 952 |
+
"chained": (6, parseChainedSubst),
|
| 953 |
+
"reversechained": (8, parseReverseChainedSubst),
|
| 954 |
+
},
|
| 955 |
+
"GPOS": {
|
| 956 |
+
"single": (1, parseSinglePos),
|
| 957 |
+
"pair": (2, parsePair),
|
| 958 |
+
"kernset": (2, parseKernset),
|
| 959 |
+
"cursive": (3, parseCursive),
|
| 960 |
+
"mark to base": (4, parseMarkToBase),
|
| 961 |
+
"mark to ligature": (5, parseMarkToLigature),
|
| 962 |
+
"mark to mark": (6, parseMarkToMark),
|
| 963 |
+
"context": (7, parseContextPos),
|
| 964 |
+
"chained": (8, parseChainedPos),
|
| 965 |
+
},
|
| 966 |
+
}[tableTag][typ]
|
| 967 |
+
|
| 968 |
+
with lines.until("lookup end"):
|
| 969 |
+
subtables = []
|
| 970 |
+
|
| 971 |
+
while lines.peek():
|
| 972 |
+
with lines.until(("% subtable", "subtable end")):
|
| 973 |
+
while lines.peek():
|
| 974 |
+
subtable = parseLookupSubTable(lines, font, lookupMap)
|
| 975 |
+
assert lookup.LookupType == subtable.LookupType
|
| 976 |
+
subtables.append(subtable)
|
| 977 |
+
if lines.peeks()[0] in ("% subtable", "subtable end"):
|
| 978 |
+
next(lines)
|
| 979 |
+
lines.expect("lookup end")
|
| 980 |
+
|
| 981 |
+
lookup.SubTable = subtables
|
| 982 |
+
lookup.SubTableCount = len(lookup.SubTable)
|
| 983 |
+
if lookup.SubTableCount == 0:
|
| 984 |
+
# Remove this return when following is fixed:
|
| 985 |
+
# https://github.com/fonttools/fonttools/issues/789
|
| 986 |
+
return None
|
| 987 |
+
return lookup
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
def parseGSUBGPOS(lines, font, tableTag):
|
| 991 |
+
container = ttLib.getTableClass(tableTag)()
|
| 992 |
+
lookupMap = DeferredMapping()
|
| 993 |
+
featureMap = DeferredMapping()
|
| 994 |
+
assert tableTag in ("GSUB", "GPOS")
|
| 995 |
+
log.debug("Parsing %s", tableTag)
|
| 996 |
+
self = getattr(ot, tableTag)()
|
| 997 |
+
self.Version = 0x00010000
|
| 998 |
+
fields = {
|
| 999 |
+
"script table begin": (
|
| 1000 |
+
"ScriptList",
|
| 1001 |
+
lambda lines: parseScriptList(lines, featureMap),
|
| 1002 |
+
),
|
| 1003 |
+
"feature table begin": (
|
| 1004 |
+
"FeatureList",
|
| 1005 |
+
lambda lines: parseFeatureList(lines, lookupMap, featureMap),
|
| 1006 |
+
),
|
| 1007 |
+
"lookup": ("LookupList", None),
|
| 1008 |
+
}
|
| 1009 |
+
for attr, parser in fields.values():
|
| 1010 |
+
setattr(self, attr, None)
|
| 1011 |
+
while lines.peek() is not None:
|
| 1012 |
+
typ = lines.peek()[0].lower()
|
| 1013 |
+
if typ not in fields:
|
| 1014 |
+
log.debug("Skipping %s", lines.peek())
|
| 1015 |
+
next(lines)
|
| 1016 |
+
continue
|
| 1017 |
+
attr, parser = fields[typ]
|
| 1018 |
+
if typ == "lookup":
|
| 1019 |
+
if self.LookupList is None:
|
| 1020 |
+
self.LookupList = ot.LookupList()
|
| 1021 |
+
self.LookupList.Lookup = []
|
| 1022 |
+
_, name, _ = lines.peek()
|
| 1023 |
+
lookup = parseLookup(lines, tableTag, font, lookupMap)
|
| 1024 |
+
if lookupMap is not None:
|
| 1025 |
+
assert name not in lookupMap, "Duplicate lookup name: %s" % name
|
| 1026 |
+
lookupMap[name] = len(self.LookupList.Lookup)
|
| 1027 |
+
else:
|
| 1028 |
+
assert int(name) == len(self.LookupList.Lookup), "%d %d" % (
|
| 1029 |
+
name,
|
| 1030 |
+
len(self.Lookup),
|
| 1031 |
+
)
|
| 1032 |
+
self.LookupList.Lookup.append(lookup)
|
| 1033 |
+
else:
|
| 1034 |
+
assert getattr(self, attr) is None, attr
|
| 1035 |
+
setattr(self, attr, parser(lines))
|
| 1036 |
+
if self.LookupList:
|
| 1037 |
+
self.LookupList.LookupCount = len(self.LookupList.Lookup)
|
| 1038 |
+
if lookupMap is not None:
|
| 1039 |
+
lookupMap.applyDeferredMappings()
|
| 1040 |
+
if os.environ.get(LOOKUP_DEBUG_ENV_VAR):
|
| 1041 |
+
if "Debg" not in font:
|
| 1042 |
+
font["Debg"] = newTable("Debg")
|
| 1043 |
+
font["Debg"].data = {}
|
| 1044 |
+
debug = (
|
| 1045 |
+
font["Debg"]
|
| 1046 |
+
.data.setdefault(LOOKUP_DEBUG_INFO_KEY, {})
|
| 1047 |
+
.setdefault(tableTag, {})
|
| 1048 |
+
)
|
| 1049 |
+
for name, lookup in lookupMap.items():
|
| 1050 |
+
debug[str(lookup)] = ["", name, ""]
|
| 1051 |
+
|
| 1052 |
+
featureMap.applyDeferredMappings()
|
| 1053 |
+
container.table = self
|
| 1054 |
+
return container
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
def parseGSUB(lines, font):
|
| 1058 |
+
return parseGSUBGPOS(lines, font, "GSUB")
|
| 1059 |
+
|
| 1060 |
+
|
| 1061 |
+
def parseGPOS(lines, font):
|
| 1062 |
+
return parseGSUBGPOS(lines, font, "GPOS")
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
def parseAttachList(lines, font):
|
| 1066 |
+
points = {}
|
| 1067 |
+
with lines.between("attachment list"):
|
| 1068 |
+
for line in lines:
|
| 1069 |
+
glyph = makeGlyph(line[0])
|
| 1070 |
+
assert glyph not in points, glyph
|
| 1071 |
+
points[glyph] = [int(i) for i in line[1:]]
|
| 1072 |
+
return otl.buildAttachList(points, font.getReverseGlyphMap())
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
def parseCaretList(lines, font):
|
| 1076 |
+
carets = {}
|
| 1077 |
+
with lines.between("carets"):
|
| 1078 |
+
for line in lines:
|
| 1079 |
+
glyph = makeGlyph(line[0])
|
| 1080 |
+
assert glyph not in carets, glyph
|
| 1081 |
+
num = int(line[1])
|
| 1082 |
+
thisCarets = [int(i) for i in line[2:]]
|
| 1083 |
+
assert num == len(thisCarets), line
|
| 1084 |
+
carets[glyph] = thisCarets
|
| 1085 |
+
return otl.buildLigCaretList(carets, {}, font.getReverseGlyphMap())
|
| 1086 |
+
|
| 1087 |
+
|
| 1088 |
+
def makeMarkFilteringSets(sets, font):
|
| 1089 |
+
self = ot.MarkGlyphSetsDef()
|
| 1090 |
+
self.MarkSetTableFormat = 1
|
| 1091 |
+
self.MarkSetCount = 1 + max(sets.keys())
|
| 1092 |
+
self.Coverage = [None] * self.MarkSetCount
|
| 1093 |
+
for k, v in sorted(sets.items()):
|
| 1094 |
+
self.Coverage[k] = makeCoverage(set(v), font)
|
| 1095 |
+
return self
|
| 1096 |
+
|
| 1097 |
+
|
| 1098 |
+
def parseMarkFilteringSets(lines, font):
|
| 1099 |
+
sets = {}
|
| 1100 |
+
with lines.between("set definition"):
|
| 1101 |
+
for line in lines:
|
| 1102 |
+
assert len(line) == 2, line
|
| 1103 |
+
glyph = makeGlyph(line[0])
|
| 1104 |
+
# TODO accept set names
|
| 1105 |
+
st = int(line[1])
|
| 1106 |
+
if st not in sets:
|
| 1107 |
+
sets[st] = []
|
| 1108 |
+
sets[st].append(glyph)
|
| 1109 |
+
return makeMarkFilteringSets(sets, font)
|
| 1110 |
+
|
| 1111 |
+
|
| 1112 |
+
def parseGDEF(lines, font):
|
| 1113 |
+
container = ttLib.getTableClass("GDEF")()
|
| 1114 |
+
log.debug("Parsing GDEF")
|
| 1115 |
+
self = ot.GDEF()
|
| 1116 |
+
fields = {
|
| 1117 |
+
"class definition begin": (
|
| 1118 |
+
"GlyphClassDef",
|
| 1119 |
+
lambda lines, font: parseClassDef(lines, font, klass=ot.GlyphClassDef),
|
| 1120 |
+
),
|
| 1121 |
+
"attachment list begin": ("AttachList", parseAttachList),
|
| 1122 |
+
"carets begin": ("LigCaretList", parseCaretList),
|
| 1123 |
+
"mark attachment class definition begin": (
|
| 1124 |
+
"MarkAttachClassDef",
|
| 1125 |
+
lambda lines, font: parseClassDef(lines, font, klass=ot.MarkAttachClassDef),
|
| 1126 |
+
),
|
| 1127 |
+
"markfilter set definition begin": ("MarkGlyphSetsDef", parseMarkFilteringSets),
|
| 1128 |
+
}
|
| 1129 |
+
for attr, parser in fields.values():
|
| 1130 |
+
setattr(self, attr, None)
|
| 1131 |
+
while lines.peek() is not None:
|
| 1132 |
+
typ = lines.peek()[0].lower()
|
| 1133 |
+
if typ not in fields:
|
| 1134 |
+
log.debug("Skipping %s", typ)
|
| 1135 |
+
next(lines)
|
| 1136 |
+
continue
|
| 1137 |
+
attr, parser = fields[typ]
|
| 1138 |
+
assert getattr(self, attr) is None, attr
|
| 1139 |
+
setattr(self, attr, parser(lines, font))
|
| 1140 |
+
self.Version = 0x00010000 if self.MarkGlyphSetsDef is None else 0x00010002
|
| 1141 |
+
container.table = self
|
| 1142 |
+
return container
|
| 1143 |
+
|
| 1144 |
+
|
| 1145 |
+
def parseCmap(lines, font):
|
| 1146 |
+
container = ttLib.getTableClass("cmap")()
|
| 1147 |
+
log.debug("Parsing cmap")
|
| 1148 |
+
tables = []
|
| 1149 |
+
while lines.peek() is not None:
|
| 1150 |
+
lines.expect("cmap subtable %d" % len(tables))
|
| 1151 |
+
platId, encId, fmt, lang = [
|
| 1152 |
+
parseCmapId(lines, field)
|
| 1153 |
+
for field in ("platformID", "encodingID", "format", "language")
|
| 1154 |
+
]
|
| 1155 |
+
table = cmap_classes[fmt](fmt)
|
| 1156 |
+
table.platformID = platId
|
| 1157 |
+
table.platEncID = encId
|
| 1158 |
+
table.language = lang
|
| 1159 |
+
table.cmap = {}
|
| 1160 |
+
line = next(lines)
|
| 1161 |
+
while line[0] != "end subtable":
|
| 1162 |
+
table.cmap[int(line[0], 16)] = line[1]
|
| 1163 |
+
line = next(lines)
|
| 1164 |
+
tables.append(table)
|
| 1165 |
+
container.tableVersion = 0
|
| 1166 |
+
container.tables = tables
|
| 1167 |
+
return container
|
| 1168 |
+
|
| 1169 |
+
|
| 1170 |
+
def parseCmapId(lines, field):
|
| 1171 |
+
line = next(lines)
|
| 1172 |
+
assert field == line[0]
|
| 1173 |
+
return int(line[1])
|
| 1174 |
+
|
| 1175 |
+
|
| 1176 |
+
def parseTable(lines, font, tableTag=None):
|
| 1177 |
+
log.debug("Parsing table")
|
| 1178 |
+
line = lines.peeks()
|
| 1179 |
+
tag = None
|
| 1180 |
+
if line[0].split()[0] == "FontDame":
|
| 1181 |
+
tag = line[0].split()[1]
|
| 1182 |
+
elif " ".join(line[0].split()[:3]) == "Font Chef Table":
|
| 1183 |
+
tag = line[0].split()[3]
|
| 1184 |
+
if tag is not None:
|
| 1185 |
+
next(lines)
|
| 1186 |
+
tag = tag.ljust(4)
|
| 1187 |
+
if tableTag is None:
|
| 1188 |
+
tableTag = tag
|
| 1189 |
+
else:
|
| 1190 |
+
assert tableTag == tag, (tableTag, tag)
|
| 1191 |
+
|
| 1192 |
+
assert (
|
| 1193 |
+
tableTag is not None
|
| 1194 |
+
), "Don't know what table to parse and data doesn't specify"
|
| 1195 |
+
|
| 1196 |
+
return {
|
| 1197 |
+
"GSUB": parseGSUB,
|
| 1198 |
+
"GPOS": parseGPOS,
|
| 1199 |
+
"GDEF": parseGDEF,
|
| 1200 |
+
"cmap": parseCmap,
|
| 1201 |
+
}[tableTag](lines, font)
|
| 1202 |
+
|
| 1203 |
+
|
| 1204 |
+
class Tokenizer(object):
|
| 1205 |
+
def __init__(self, f):
|
| 1206 |
+
# TODO BytesIO / StringIO as needed? also, figure out whether we work on bytes or unicode
|
| 1207 |
+
lines = iter(f)
|
| 1208 |
+
try:
|
| 1209 |
+
self.filename = f.name
|
| 1210 |
+
except:
|
| 1211 |
+
self.filename = None
|
| 1212 |
+
self.lines = iter(lines)
|
| 1213 |
+
self.line = ""
|
| 1214 |
+
self.lineno = 0
|
| 1215 |
+
self.stoppers = []
|
| 1216 |
+
self.buffer = None
|
| 1217 |
+
|
| 1218 |
+
def __iter__(self):
|
| 1219 |
+
return self
|
| 1220 |
+
|
| 1221 |
+
def _next_line(self):
|
| 1222 |
+
self.lineno += 1
|
| 1223 |
+
line = self.line = next(self.lines)
|
| 1224 |
+
line = [s.strip() for s in line.split("\t")]
|
| 1225 |
+
if len(line) == 1 and not line[0]:
|
| 1226 |
+
del line[0]
|
| 1227 |
+
if line and not line[-1]:
|
| 1228 |
+
log.warning("trailing tab found on line %d: %s" % (self.lineno, self.line))
|
| 1229 |
+
while line and not line[-1]:
|
| 1230 |
+
del line[-1]
|
| 1231 |
+
return line
|
| 1232 |
+
|
| 1233 |
+
def _next_nonempty(self):
|
| 1234 |
+
while True:
|
| 1235 |
+
line = self._next_line()
|
| 1236 |
+
# Skip comments and empty lines
|
| 1237 |
+
if line and line[0] and (line[0][0] != "%" or line[0] == "% subtable"):
|
| 1238 |
+
return line
|
| 1239 |
+
|
| 1240 |
+
def _next_buffered(self):
|
| 1241 |
+
if self.buffer:
|
| 1242 |
+
ret = self.buffer
|
| 1243 |
+
self.buffer = None
|
| 1244 |
+
return ret
|
| 1245 |
+
else:
|
| 1246 |
+
return self._next_nonempty()
|
| 1247 |
+
|
| 1248 |
+
def __next__(self):
|
| 1249 |
+
line = self._next_buffered()
|
| 1250 |
+
if line[0].lower() in self.stoppers:
|
| 1251 |
+
self.buffer = line
|
| 1252 |
+
raise StopIteration
|
| 1253 |
+
return line
|
| 1254 |
+
|
| 1255 |
+
def next(self):
|
| 1256 |
+
return self.__next__()
|
| 1257 |
+
|
| 1258 |
+
def peek(self):
|
| 1259 |
+
if not self.buffer:
|
| 1260 |
+
try:
|
| 1261 |
+
self.buffer = self._next_nonempty()
|
| 1262 |
+
except StopIteration:
|
| 1263 |
+
return None
|
| 1264 |
+
if self.buffer[0].lower() in self.stoppers:
|
| 1265 |
+
return None
|
| 1266 |
+
return self.buffer
|
| 1267 |
+
|
| 1268 |
+
def peeks(self):
|
| 1269 |
+
ret = self.peek()
|
| 1270 |
+
return ret if ret is not None else ("",)
|
| 1271 |
+
|
| 1272 |
+
@contextmanager
|
| 1273 |
+
def between(self, tag):
|
| 1274 |
+
start = tag + " begin"
|
| 1275 |
+
end = tag + " end"
|
| 1276 |
+
self.expectendswith(start)
|
| 1277 |
+
self.stoppers.append(end)
|
| 1278 |
+
yield
|
| 1279 |
+
del self.stoppers[-1]
|
| 1280 |
+
self.expect(tag + " end")
|
| 1281 |
+
|
| 1282 |
+
@contextmanager
|
| 1283 |
+
def until(self, tags):
|
| 1284 |
+
if type(tags) is not tuple:
|
| 1285 |
+
tags = (tags,)
|
| 1286 |
+
self.stoppers.extend(tags)
|
| 1287 |
+
yield
|
| 1288 |
+
del self.stoppers[-len(tags) :]
|
| 1289 |
+
|
| 1290 |
+
def expect(self, s):
|
| 1291 |
+
line = next(self)
|
| 1292 |
+
tag = line[0].lower()
|
| 1293 |
+
assert tag == s, "Expected '%s', got '%s'" % (s, tag)
|
| 1294 |
+
return line
|
| 1295 |
+
|
| 1296 |
+
def expectendswith(self, s):
|
| 1297 |
+
line = next(self)
|
| 1298 |
+
tag = line[0].lower()
|
| 1299 |
+
assert tag.endswith(s), "Expected '*%s', got '%s'" % (s, tag)
|
| 1300 |
+
return line
|
| 1301 |
+
|
| 1302 |
+
|
| 1303 |
+
def build(f, font, tableTag=None):
|
| 1304 |
+
"""Convert a Monotype font layout file to an OpenType layout object
|
| 1305 |
+
|
| 1306 |
+
A font object must be passed, but this may be a "dummy" font; it is only
|
| 1307 |
+
used for sorting glyph sets when making coverage tables and to hold the
|
| 1308 |
+
OpenType layout table while it is being built.
|
| 1309 |
+
|
| 1310 |
+
Args:
|
| 1311 |
+
f: A file object.
|
| 1312 |
+
font (TTFont): A font object.
|
| 1313 |
+
tableTag (string): If provided, asserts that the file contains data for the
|
| 1314 |
+
given OpenType table.
|
| 1315 |
+
|
| 1316 |
+
Returns:
|
| 1317 |
+
An object representing the table. (e.g. ``table_G_S_U_B_``)
|
| 1318 |
+
"""
|
| 1319 |
+
lines = Tokenizer(f)
|
| 1320 |
+
return parseTable(lines, font, tableTag=tableTag)
|
| 1321 |
+
|
| 1322 |
+
|
| 1323 |
+
def main(args=None, font=None):
|
| 1324 |
+
"""Convert a FontDame OTL file to TTX XML
|
| 1325 |
+
|
| 1326 |
+
Writes XML output to stdout.
|
| 1327 |
+
|
| 1328 |
+
Args:
|
| 1329 |
+
args: Command line arguments (``--font``, ``--table``, input files).
|
| 1330 |
+
"""
|
| 1331 |
+
import sys
|
| 1332 |
+
from fontTools import configLogger
|
| 1333 |
+
from fontTools.misc.testTools import MockFont
|
| 1334 |
+
|
| 1335 |
+
if args is None:
|
| 1336 |
+
args = sys.argv[1:]
|
| 1337 |
+
|
| 1338 |
+
# configure the library logger (for >= WARNING)
|
| 1339 |
+
configLogger()
|
| 1340 |
+
# comment this out to enable debug messages from mtiLib's logger
|
| 1341 |
+
# log.setLevel(logging.DEBUG)
|
| 1342 |
+
|
| 1343 |
+
import argparse
|
| 1344 |
+
|
| 1345 |
+
parser = argparse.ArgumentParser(
|
| 1346 |
+
"fonttools mtiLib",
|
| 1347 |
+
description=main.__doc__,
|
| 1348 |
+
)
|
| 1349 |
+
|
| 1350 |
+
parser.add_argument(
|
| 1351 |
+
"--font",
|
| 1352 |
+
"-f",
|
| 1353 |
+
metavar="FILE",
|
| 1354 |
+
dest="font",
|
| 1355 |
+
help="Input TTF files (used for glyph classes and sorting coverage tables)",
|
| 1356 |
+
)
|
| 1357 |
+
parser.add_argument(
|
| 1358 |
+
"--table",
|
| 1359 |
+
"-t",
|
| 1360 |
+
metavar="TABLE",
|
| 1361 |
+
dest="tableTag",
|
| 1362 |
+
help="Table to fill (sniffed from input file if not provided)",
|
| 1363 |
+
)
|
| 1364 |
+
parser.add_argument(
|
| 1365 |
+
"inputs", metavar="FILE", type=str, nargs="+", help="Input FontDame .txt files"
|
| 1366 |
+
)
|
| 1367 |
+
|
| 1368 |
+
args = parser.parse_args(args)
|
| 1369 |
+
|
| 1370 |
+
if font is None:
|
| 1371 |
+
if args.font:
|
| 1372 |
+
font = ttLib.TTFont(args.font)
|
| 1373 |
+
else:
|
| 1374 |
+
font = MockFont()
|
| 1375 |
+
|
| 1376 |
+
for f in args.inputs:
|
| 1377 |
+
log.debug("Processing %s", f)
|
| 1378 |
+
with open(f, "rt", encoding="utf-8-sig") as f:
|
| 1379 |
+
table = build(f, font, tableTag=args.tableTag)
|
| 1380 |
+
blob = table.compile(font) # Make sure it compiles
|
| 1381 |
+
decompiled = table.__class__()
|
| 1382 |
+
decompiled.decompile(blob, font) # Make sure it decompiles!
|
| 1383 |
+
|
| 1384 |
+
# continue
|
| 1385 |
+
from fontTools.misc import xmlWriter
|
| 1386 |
+
|
| 1387 |
+
tag = table.tableTag
|
| 1388 |
+
writer = xmlWriter.XMLWriter(sys.stdout)
|
| 1389 |
+
writer.begintag(tag)
|
| 1390 |
+
writer.newline()
|
| 1391 |
+
# table.toXML(writer, font)
|
| 1392 |
+
decompiled.toXML(writer, font)
|
| 1393 |
+
writer.endtag(tag)
|
| 1394 |
+
writer.newline()
|
| 1395 |
+
|
| 1396 |
+
|
| 1397 |
+
if __name__ == "__main__":
|
| 1398 |
+
import sys
|
| 1399 |
+
|
| 1400 |
+
sys.exit(main())
|
shared/package-files/31/31e7e018f6c9649bce8616fcd3284843c23c853b4b56c4b152cf561c29c5fd1b/blob
ADDED
|
Binary file (1.36 kB). View file
|
|
|
shared/package-files/31/31e99ec2d7580af332a37c64d2d373457f17f593627bf7c41368a96afde2e74f/blob
ADDED
|
Binary file (552 Bytes). View file
|
|
|
shared/package-files/31/31ea913829659f4a9cf5bcbe83458d7c0c765a518c6d9b6808e5a2b10da79019/blob
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Implements Lilliefors corrected Kolmogorov-Smirnov tests for normal and
|
| 3 |
+
exponential distributions.
|
| 4 |
+
|
| 5 |
+
`kstest_fit` is provided as a top-level function to access both tests.
|
| 6 |
+
`kstest_normal` and `kstest_exponential` are provided as convenience functions
|
| 7 |
+
with the appropriate test as the default.
|
| 8 |
+
`lilliefors` is provided as an alias for `kstest_fit`.
|
| 9 |
+
|
| 10 |
+
Created on Sat Oct 01 13:16:49 2011
|
| 11 |
+
|
| 12 |
+
Author: Josef Perktold
|
| 13 |
+
License: BSD-3
|
| 14 |
+
|
| 15 |
+
pvalues for Lilliefors test are based on formula and table in
|
| 16 |
+
|
| 17 |
+
An Analytic Approximation to the Distribution of Lilliefors's Test Statistic
|
| 18 |
+
for Normality
|
| 19 |
+
Author(s): Gerard E. Dallal and Leland Wilkinson
|
| 20 |
+
Source: The American Statistician, Vol. 40, No. 4 (Nov., 1986), pp. 294-296
|
| 21 |
+
Published by: American Statistical Association
|
| 22 |
+
Stable URL: http://www.jstor.org/stable/2684607.
|
| 23 |
+
|
| 24 |
+
On the Kolmogorov-Smirnov Test for Normality with Mean and Variance Unknown
|
| 25 |
+
Hubert W. Lilliefors
|
| 26 |
+
Journal of the American Statistical Association, Vol. 62, No. 318.
|
| 27 |
+
(Jun., 1967), pp. 399-402.
|
| 28 |
+
|
| 29 |
+
---
|
| 30 |
+
|
| 31 |
+
Updated 2017-07-23
|
| 32 |
+
Jacob C. Kimmel
|
| 33 |
+
|
| 34 |
+
Ref:
|
| 35 |
+
Lilliefors, H.W.
|
| 36 |
+
On the Kolmogorov-Smirnov test for the exponential distribution with mean
|
| 37 |
+
unknown. Journal of the American Statistical Association, Vol 64, No. 325.
|
| 38 |
+
(1969), pp. 387-389.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
from functools import cache, partial
|
| 42 |
+
|
| 43 |
+
import numpy as np
|
| 44 |
+
from scipy import stats
|
| 45 |
+
|
| 46 |
+
from statsmodels.tools.validation import string_like
|
| 47 |
+
|
| 48 |
+
from .tabledist import TableDist
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _make_asymptotic_function(params):
|
| 52 |
+
"""
|
| 53 |
+
Generate an asymptotic distribution callable from a param matrix
|
| 54 |
+
|
| 55 |
+
Polynomial is a[0] * x**(-1/2) + a[1] * x**(-1) + a[2] * x**(-3/2)
|
| 56 |
+
|
| 57 |
+
Parameters
|
| 58 |
+
----------
|
| 59 |
+
params : ndarray
|
| 60 |
+
Array with shape (nalpha, 3) where nalpha is the number of
|
| 61 |
+
significance levels.
|
| 62 |
+
|
| 63 |
+
Returns
|
| 64 |
+
-------
|
| 65 |
+
callable
|
| 66 |
+
Function of the sample size that evaluates the asymptotic
|
| 67 |
+
critical value approximation.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def f(n):
|
| 71 |
+
poly = np.array([1, np.log(n), np.log(n) ** 2])
|
| 72 |
+
return np.exp(poly.dot(params.T))
|
| 73 |
+
|
| 74 |
+
return f
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def ksstat(x, cdf, alternative="two-sided", args=()):
|
| 78 |
+
"""
|
| 79 |
+
Calculate statistic for the Kolmogorov-Smirnov test for goodness of fit
|
| 80 |
+
|
| 81 |
+
This calculates the test statistic for a test of the distribution G(x) of
|
| 82 |
+
an observed variable against a given distribution F(x). Under the null
|
| 83 |
+
hypothesis the two distributions are identical, G(x)=F(x). The
|
| 84 |
+
alternative hypothesis can be either 'two-sided' (default), 'lower'
|
| 85 |
+
or 'upper'. The KS test is only valid for continuous distributions.
|
| 86 |
+
|
| 87 |
+
Parameters
|
| 88 |
+
----------
|
| 89 |
+
x : array_like, 1d
|
| 90 |
+
Array of observations.
|
| 91 |
+
cdf : str or callable
|
| 92 |
+
String: name of a distribution in scipy.stats.
|
| 93 |
+
Callable: function to evaluate cdf.
|
| 94 |
+
alternative : {'two-sided', 'lower', 'upper'}, optional
|
| 95 |
+
Defines the alternative hypothesis (see explanation). Default is
|
| 96 |
+
'two-sided'.
|
| 97 |
+
args : tuple, optional
|
| 98 |
+
Distribution parameters for call to cdf.
|
| 99 |
+
|
| 100 |
+
Returns
|
| 101 |
+
-------
|
| 102 |
+
D : float
|
| 103 |
+
KS test statistic, either D, D+ or D-.
|
| 104 |
+
|
| 105 |
+
See Also
|
| 106 |
+
--------
|
| 107 |
+
scipy.stats.kstest
|
| 108 |
+
|
| 109 |
+
Notes
|
| 110 |
+
-----
|
| 111 |
+
In the one-sided test, the alternative is that the empirical
|
| 112 |
+
cumulative distribution function of the random variable is "lower"
|
| 113 |
+
or "upper" than the cumulative distribution function F(x) of the
|
| 114 |
+
hypothesis, G(x)<=F(x), resp. G(x)>=F(x).
|
| 115 |
+
|
| 116 |
+
In contrast to scipy.stats.kstest, this function only calculates the
|
| 117 |
+
statistic which can be used either as distance measure or to implement
|
| 118 |
+
case specific p-values.
|
| 119 |
+
"""
|
| 120 |
+
alternative = string_like(
|
| 121 |
+
alternative,
|
| 122 |
+
"alternative",
|
| 123 |
+
options=("two-sided", "lower", "upper"),
|
| 124 |
+
deprecated={"two_sided": "two-sided", "less": "lower", "greater": "upper"},
|
| 125 |
+
removed_after="0.16",
|
| 126 |
+
)
|
| 127 |
+
nobs = float(len(x))
|
| 128 |
+
|
| 129 |
+
if isinstance(cdf, str):
|
| 130 |
+
cdf = getattr(stats.distributions, cdf).cdf
|
| 131 |
+
elif hasattr(cdf, "cdf"):
|
| 132 |
+
cdf = cdf.cdf
|
| 133 |
+
|
| 134 |
+
x = np.sort(x)
|
| 135 |
+
cdfvals = cdf(x, *args)
|
| 136 |
+
|
| 137 |
+
d_plus = (np.arange(1.0, nobs + 1) / nobs - cdfvals).max()
|
| 138 |
+
d_min = (cdfvals - np.arange(0.0, nobs) / nobs).max()
|
| 139 |
+
if alternative == "upper":
|
| 140 |
+
return d_plus
|
| 141 |
+
elif alternative == "lower":
|
| 142 |
+
return d_min
|
| 143 |
+
|
| 144 |
+
return np.max([d_plus, d_min])
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@cache
|
| 148 |
+
def get_lilliefors_table(dist="norm"):
|
| 149 |
+
"""
|
| 150 |
+
Generates tables for significance levels of Lilliefors test statistics
|
| 151 |
+
|
| 152 |
+
Tables for available normal and exponential distribution testing,
|
| 153 |
+
as specified in Lilliefors references above
|
| 154 |
+
|
| 155 |
+
Parameters
|
| 156 |
+
----------
|
| 157 |
+
dist : str, optional
|
| 158 |
+
Distribution being tested, one of {'norm', 'exp'}.
|
| 159 |
+
|
| 160 |
+
Returns
|
| 161 |
+
-------
|
| 162 |
+
lf : TableDist
|
| 163 |
+
Table of critical values.
|
| 164 |
+
"""
|
| 165 |
+
# function just to keep things together
|
| 166 |
+
# for this test alpha is sf probability, i.e., right tail probability
|
| 167 |
+
|
| 168 |
+
# deferred import: this table is a large, generated module (~380 lines
|
| 169 |
+
# of literal arrays) that is only needed when a Lilliefors test is
|
| 170 |
+
# actually run, so import it lazily and cache the resulting TableDist
|
| 171 |
+
# (via lru_cache on this function) rather than paying the parsing cost
|
| 172 |
+
# at package import time.
|
| 173 |
+
from ._lilliefors_critical_values import (
|
| 174 |
+
PERCENTILES,
|
| 175 |
+
asymp_critical_values,
|
| 176 |
+
critical_values,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
alpha = 1 - np.array(PERCENTILES) / 100.0
|
| 180 |
+
alpha = alpha[::-1]
|
| 181 |
+
dist = "normal" if dist == "norm" else dist
|
| 182 |
+
if dist not in critical_values:
|
| 183 |
+
raise ValueError("Invalid dist parameter. Must be 'norm' or 'exp'")
|
| 184 |
+
cv_data = critical_values[dist]
|
| 185 |
+
acv_data = asymp_critical_values[dist]
|
| 186 |
+
|
| 187 |
+
size = np.array(sorted(cv_data), dtype=float)
|
| 188 |
+
crit_lf = np.array([cv_data[key] for key in sorted(cv_data)])
|
| 189 |
+
crit_lf = crit_lf[:, ::-1]
|
| 190 |
+
|
| 191 |
+
asym_params = np.array([acv_data[key] for key in sorted(acv_data)])
|
| 192 |
+
asymp_fn = _make_asymptotic_function(asym_params[::-1])
|
| 193 |
+
|
| 194 |
+
lf = TableDist(alpha, size, crit_lf, asymptotic=asymp_fn)
|
| 195 |
+
return lf
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def pval_lf(d_max, n):
|
| 199 |
+
"""
|
| 200 |
+
Approximate pvalues for Lilliefors test
|
| 201 |
+
|
| 202 |
+
This is only valid for pvalues smaller than 0.1 which is not checked in
|
| 203 |
+
this function.
|
| 204 |
+
|
| 205 |
+
Parameters
|
| 206 |
+
----------
|
| 207 |
+
d_max : array_like
|
| 208 |
+
two-sided Kolmogorov-Smirnov test statistic
|
| 209 |
+
n : int or float
|
| 210 |
+
sample size
|
| 211 |
+
|
| 212 |
+
Returns
|
| 213 |
+
-------
|
| 214 |
+
p-value : float or ndarray
|
| 215 |
+
pvalue according to approximation formula of Dallal and Wilkinson.
|
| 216 |
+
|
| 217 |
+
Notes
|
| 218 |
+
-----
|
| 219 |
+
This is mainly a helper function where the calling code should dispatch
|
| 220 |
+
on bound violations. Therefore it does not check whether the pvalue is in
|
| 221 |
+
the valid range.
|
| 222 |
+
|
| 223 |
+
Precision for the pvalues is around 2 to 3 decimals. This approximation is
|
| 224 |
+
also used by other statistical packages (e.g., R:fBasics) but might not be
|
| 225 |
+
the most precise available.
|
| 226 |
+
|
| 227 |
+
References
|
| 228 |
+
----------
|
| 229 |
+
DallalWilkinson1986
|
| 230 |
+
"""
|
| 231 |
+
# todo: check boundaries, valid range for n and Dmax
|
| 232 |
+
if n > 100:
|
| 233 |
+
d_max *= (n / 100.0) ** 0.49
|
| 234 |
+
n = 100
|
| 235 |
+
pval = np.exp(
|
| 236 |
+
-7.01256 * d_max**2 * (n + 2.78019)
|
| 237 |
+
+ 2.99587 * d_max * np.sqrt(n + 2.78019)
|
| 238 |
+
- 0.122119
|
| 239 |
+
+ 0.974598 / np.sqrt(n)
|
| 240 |
+
+ 1.67997 / n
|
| 241 |
+
)
|
| 242 |
+
return pval
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def kstest_fit(x, dist="norm", pvalmethod="table"):
|
| 246 |
+
"""
|
| 247 |
+
Test assumed normal or exponential distribution using Lilliefors' test
|
| 248 |
+
|
| 249 |
+
Lilliefors' test is a Kolmogorov-Smirnov test with estimated parameters.
|
| 250 |
+
|
| 251 |
+
Parameters
|
| 252 |
+
----------
|
| 253 |
+
x : array_like, 1d
|
| 254 |
+
Data to test.
|
| 255 |
+
dist : {'norm', 'exp'}, optional
|
| 256 |
+
The assumed distribution.
|
| 257 |
+
pvalmethod : {'approx', 'table'}, optional
|
| 258 |
+
The method used to compute the p-value of the test statistic. In
|
| 259 |
+
general, 'table' is preferred and makes use of a very large simulation.
|
| 260 |
+
'approx' is only valid for normality. If `dist = 'exp'`, `table` is
|
| 261 |
+
always used. 'approx' uses the approximation formula of Dalal and
|
| 262 |
+
Wilkinson, valid for pvalues < 0.1. If the pvalue is larger than 0.1,
|
| 263 |
+
then the result of `table` is returned.
|
| 264 |
+
|
| 265 |
+
Returns
|
| 266 |
+
-------
|
| 267 |
+
ksstat : float
|
| 268 |
+
Kolmogorov-Smirnov test statistic with estimated mean and variance.
|
| 269 |
+
pvalue : float
|
| 270 |
+
If the pvalue is lower than some threshold, e.g., 0.05, then we can
|
| 271 |
+
reject the Null hypothesis that the sample comes from a normal
|
| 272 |
+
distribution.
|
| 273 |
+
|
| 274 |
+
Notes
|
| 275 |
+
-----
|
| 276 |
+
'table' uses an improved table based on 10,000,000 simulations. The
|
| 277 |
+
critical values are approximated using
|
| 278 |
+
log(cv_alpha) = b_alpha + c[0] log(n) + c[1] log(n)**2
|
| 279 |
+
where cv_alpha is the critical value for a test with size alpha,
|
| 280 |
+
b_alpha is an alpha-specific intercept term and c[1] and c[2] are
|
| 281 |
+
coefficients that are shared across all alphas.
|
| 282 |
+
Values in the table are linearly interpolated. Values outside the
|
| 283 |
+
range are returned as bounds, 0.990 for large and 0.001 for small
|
| 284 |
+
pvalues.
|
| 285 |
+
|
| 286 |
+
For implementation details, see lilliefors_critical_value_simulation.py in
|
| 287 |
+
the test directory.
|
| 288 |
+
"""
|
| 289 |
+
dist = string_like(dist, "dist", options=("norm", "exp"))
|
| 290 |
+
pvalmethod = string_like(pvalmethod, "pvalmethod", options=("approx", "table"))
|
| 291 |
+
x = np.asarray(x)
|
| 292 |
+
if x.ndim == 2 and x.shape[1] == 1:
|
| 293 |
+
x = x[:, 0]
|
| 294 |
+
elif x.ndim != 1:
|
| 295 |
+
raise ValueError(
|
| 296 |
+
"Invalid parameter `x`: must be a one-dimensional"
|
| 297 |
+
" array-like or a single-column DataFrame"
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
nobs = len(x)
|
| 301 |
+
|
| 302 |
+
dist = string_like(dist, "dist", options=("norm", "exp"), lower=False)
|
| 303 |
+
if dist == "norm":
|
| 304 |
+
z = (x - x.mean()) / x.std(ddof=1)
|
| 305 |
+
test_d = stats.norm.cdf
|
| 306 |
+
else: # dist == "exp"
|
| 307 |
+
z = x / x.mean()
|
| 308 |
+
test_d = stats.expon.cdf
|
| 309 |
+
pvalmethod = "table"
|
| 310 |
+
# deferred/cached: only builds (and imports) the critical-value table
|
| 311 |
+
# for the distribution actually requested
|
| 312 |
+
lilliefors_table = get_lilliefors_table(dist=dist)
|
| 313 |
+
|
| 314 |
+
min_nobs = 4 if dist == "norm" else 3
|
| 315 |
+
if nobs < min_nobs:
|
| 316 |
+
raise ValueError(
|
| 317 |
+
f"Test for distribution {dist} requires at least {min_nobs} observations"
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
d_ks = ksstat(z, test_d, alternative="two-sided")
|
| 321 |
+
|
| 322 |
+
if pvalmethod == "approx":
|
| 323 |
+
pval = pval_lf(d_ks, nobs)
|
| 324 |
+
# check pval is in desired range
|
| 325 |
+
if pval > 0.1:
|
| 326 |
+
pval = lilliefors_table.prob(d_ks, nobs)
|
| 327 |
+
else: # pvalmethod == 'table'
|
| 328 |
+
pval = lilliefors_table.prob(d_ks, nobs)
|
| 329 |
+
|
| 330 |
+
return d_ks, pval
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
lilliefors = kstest_fit
|
| 334 |
+
kstest_normal = kstest_fit
|
| 335 |
+
kstest_exponential = partial(kstest_fit, dist="exp")
|
shared/package-files/31/31eb31c6083704bc6178b671f9d49fdf46fa80aa4e81d557c3a5befae1d2b334/blob
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
from typing import Optional, Tuple
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def glibc_version_string() -> Optional[str]:
|
| 7 |
+
"Returns glibc version string, or None if not using glibc."
|
| 8 |
+
return glibc_version_string_confstr() or glibc_version_string_ctypes()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def glibc_version_string_confstr() -> Optional[str]:
|
| 12 |
+
"Primary implementation of glibc_version_string using os.confstr."
|
| 13 |
+
# os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
|
| 14 |
+
# to be broken or missing. This strategy is used in the standard library
|
| 15 |
+
# platform module:
|
| 16 |
+
# https://github.com/python/cpython/blob/fcf1d003bf4f0100c9d0921ff3d70e1127ca1b71/Lib/platform.py#L175-L183
|
| 17 |
+
if sys.platform == "win32":
|
| 18 |
+
return None
|
| 19 |
+
try:
|
| 20 |
+
gnu_libc_version = os.confstr("CS_GNU_LIBC_VERSION")
|
| 21 |
+
if gnu_libc_version is None:
|
| 22 |
+
return None
|
| 23 |
+
# os.confstr("CS_GNU_LIBC_VERSION") returns a string like "glibc 2.17":
|
| 24 |
+
_, version = gnu_libc_version.split()
|
| 25 |
+
except (AttributeError, OSError, ValueError):
|
| 26 |
+
# os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
|
| 27 |
+
return None
|
| 28 |
+
return version
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def glibc_version_string_ctypes() -> Optional[str]:
|
| 32 |
+
"Fallback implementation of glibc_version_string using ctypes."
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
import ctypes
|
| 36 |
+
except ImportError:
|
| 37 |
+
return None
|
| 38 |
+
|
| 39 |
+
# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
|
| 40 |
+
# manpage says, "If filename is NULL, then the returned handle is for the
|
| 41 |
+
# main program". This way we can let the linker do the work to figure out
|
| 42 |
+
# which libc our process is actually using.
|
| 43 |
+
process_namespace = ctypes.CDLL(None)
|
| 44 |
+
try:
|
| 45 |
+
gnu_get_libc_version = process_namespace.gnu_get_libc_version
|
| 46 |
+
except AttributeError:
|
| 47 |
+
# Symbol doesn't exist -> therefore, we are not linked to
|
| 48 |
+
# glibc.
|
| 49 |
+
return None
|
| 50 |
+
|
| 51 |
+
# Call gnu_get_libc_version, which returns a string like "2.5"
|
| 52 |
+
gnu_get_libc_version.restype = ctypes.c_char_p
|
| 53 |
+
version_str = gnu_get_libc_version()
|
| 54 |
+
# py2 / py3 compatibility:
|
| 55 |
+
if not isinstance(version_str, str):
|
| 56 |
+
version_str = version_str.decode("ascii")
|
| 57 |
+
|
| 58 |
+
return version_str
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# platform.libc_ver regularly returns completely nonsensical glibc
|
| 62 |
+
# versions. E.g. on my computer, platform says:
|
| 63 |
+
#
|
| 64 |
+
# ~$ python2.7 -c 'import platform; print(platform.libc_ver())'
|
| 65 |
+
# ('glibc', '2.7')
|
| 66 |
+
# ~$ python3.5 -c 'import platform; print(platform.libc_ver())'
|
| 67 |
+
# ('glibc', '2.9')
|
| 68 |
+
#
|
| 69 |
+
# But the truth is:
|
| 70 |
+
#
|
| 71 |
+
# ~$ ldd --version
|
| 72 |
+
# ldd (Debian GLIBC 2.22-11) 2.22
|
| 73 |
+
#
|
| 74 |
+
# This is unfortunate, because it means that the linehaul data on libc
|
| 75 |
+
# versions that was generated by pip 8.1.2 and earlier is useless and
|
| 76 |
+
# misleading. Solution: instead of using platform, use our code that actually
|
| 77 |
+
# works.
|
| 78 |
+
def libc_ver() -> Tuple[str, str]:
|
| 79 |
+
"""Try to determine the glibc version
|
| 80 |
+
|
| 81 |
+
Returns a tuple of strings (lib, version) which default to empty strings
|
| 82 |
+
in case the lookup fails.
|
| 83 |
+
"""
|
| 84 |
+
glibc_version = glibc_version_string()
|
| 85 |
+
if glibc_version is None:
|
| 86 |
+
return ("", "")
|
| 87 |
+
else:
|
| 88 |
+
return ("glibc", glibc_version)
|
shared/package-files/31/31f0728acd86ea4539fb2e058e18514d00f90d068fe4e385adcf9c882f4988a1/blob
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from typing import Any, Dict, Protocol, Text, Union
|
| 3 |
+
|
| 4 |
+
MSG_DISCONNECT: int
|
| 5 |
+
MSG_IGNORE: int
|
| 6 |
+
MSG_UNIMPLEMENTED: int
|
| 7 |
+
MSG_DEBUG: int
|
| 8 |
+
MSG_SERVICE_REQUEST: int
|
| 9 |
+
MSG_SERVICE_ACCEPT: int
|
| 10 |
+
MSG_KEXINIT: int
|
| 11 |
+
MSG_NEWKEYS: int
|
| 12 |
+
MSG_USERAUTH_REQUEST: int
|
| 13 |
+
MSG_USERAUTH_FAILURE: int
|
| 14 |
+
MSG_USERAUTH_SUCCESS: int
|
| 15 |
+
MSG_USERAUTH_BANNER: int
|
| 16 |
+
MSG_USERAUTH_PK_OK: int
|
| 17 |
+
MSG_USERAUTH_INFO_REQUEST: int
|
| 18 |
+
MSG_USERAUTH_INFO_RESPONSE: int
|
| 19 |
+
MSG_USERAUTH_GSSAPI_RESPONSE: int
|
| 20 |
+
MSG_USERAUTH_GSSAPI_TOKEN: int
|
| 21 |
+
MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE: int
|
| 22 |
+
MSG_USERAUTH_GSSAPI_ERROR: int
|
| 23 |
+
MSG_USERAUTH_GSSAPI_ERRTOK: int
|
| 24 |
+
MSG_USERAUTH_GSSAPI_MIC: int
|
| 25 |
+
HIGHEST_USERAUTH_MESSAGE_ID: int
|
| 26 |
+
MSG_GLOBAL_REQUEST: int
|
| 27 |
+
MSG_REQUEST_SUCCESS: int
|
| 28 |
+
MSG_REQUEST_FAILURE: int
|
| 29 |
+
MSG_CHANNEL_OPEN: int
|
| 30 |
+
MSG_CHANNEL_OPEN_SUCCESS: int
|
| 31 |
+
MSG_CHANNEL_OPEN_FAILURE: int
|
| 32 |
+
MSG_CHANNEL_WINDOW_ADJUST: int
|
| 33 |
+
MSG_CHANNEL_DATA: int
|
| 34 |
+
MSG_CHANNEL_EXTENDED_DATA: int
|
| 35 |
+
MSG_CHANNEL_EOF: int
|
| 36 |
+
MSG_CHANNEL_CLOSE: int
|
| 37 |
+
MSG_CHANNEL_REQUEST: int
|
| 38 |
+
MSG_CHANNEL_SUCCESS: int
|
| 39 |
+
MSG_CHANNEL_FAILURE: int
|
| 40 |
+
|
| 41 |
+
cMSG_DISCONNECT: bytes
|
| 42 |
+
cMSG_IGNORE: bytes
|
| 43 |
+
cMSG_UNIMPLEMENTED: bytes
|
| 44 |
+
cMSG_DEBUG: bytes
|
| 45 |
+
cMSG_SERVICE_REQUEST: bytes
|
| 46 |
+
cMSG_SERVICE_ACCEPT: bytes
|
| 47 |
+
cMSG_KEXINIT: bytes
|
| 48 |
+
cMSG_NEWKEYS: bytes
|
| 49 |
+
cMSG_USERAUTH_REQUEST: bytes
|
| 50 |
+
cMSG_USERAUTH_FAILURE: bytes
|
| 51 |
+
cMSG_USERAUTH_SUCCESS: bytes
|
| 52 |
+
cMSG_USERAUTH_BANNER: bytes
|
| 53 |
+
cMSG_USERAUTH_PK_OK: bytes
|
| 54 |
+
cMSG_USERAUTH_INFO_REQUEST: bytes
|
| 55 |
+
cMSG_USERAUTH_INFO_RESPONSE: bytes
|
| 56 |
+
cMSG_USERAUTH_GSSAPI_RESPONSE: bytes
|
| 57 |
+
cMSG_USERAUTH_GSSAPI_TOKEN: bytes
|
| 58 |
+
cMSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE: bytes
|
| 59 |
+
cMSG_USERAUTH_GSSAPI_ERROR: bytes
|
| 60 |
+
cMSG_USERAUTH_GSSAPI_ERRTOK: bytes
|
| 61 |
+
cMSG_USERAUTH_GSSAPI_MIC: bytes
|
| 62 |
+
cMSG_GLOBAL_REQUEST: bytes
|
| 63 |
+
cMSG_REQUEST_SUCCESS: bytes
|
| 64 |
+
cMSG_REQUEST_FAILURE: bytes
|
| 65 |
+
cMSG_CHANNEL_OPEN: bytes
|
| 66 |
+
cMSG_CHANNEL_OPEN_SUCCESS: bytes
|
| 67 |
+
cMSG_CHANNEL_OPEN_FAILURE: bytes
|
| 68 |
+
cMSG_CHANNEL_WINDOW_ADJUST: bytes
|
| 69 |
+
cMSG_CHANNEL_DATA: bytes
|
| 70 |
+
cMSG_CHANNEL_EXTENDED_DATA: bytes
|
| 71 |
+
cMSG_CHANNEL_EOF: bytes
|
| 72 |
+
cMSG_CHANNEL_CLOSE: bytes
|
| 73 |
+
cMSG_CHANNEL_REQUEST: bytes
|
| 74 |
+
cMSG_CHANNEL_SUCCESS: bytes
|
| 75 |
+
cMSG_CHANNEL_FAILURE: bytes
|
| 76 |
+
|
| 77 |
+
MSG_NAMES: Dict[int, str]
|
| 78 |
+
|
| 79 |
+
AUTH_SUCCESSFUL: int
|
| 80 |
+
AUTH_PARTIALLY_SUCCESSFUL: int
|
| 81 |
+
AUTH_FAILED: int
|
| 82 |
+
|
| 83 |
+
OPEN_SUCCEEDED: int
|
| 84 |
+
OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED: int
|
| 85 |
+
OPEN_FAILED_CONNECT_FAILED: int
|
| 86 |
+
OPEN_FAILED_UNKNOWN_CHANNEL_TYPE: int
|
| 87 |
+
OPEN_FAILED_RESOURCE_SHORTAGE: int
|
| 88 |
+
|
| 89 |
+
CONNECTION_FAILED_CODE: Dict[int, str]
|
| 90 |
+
|
| 91 |
+
DISCONNECT_SERVICE_NOT_AVAILABLE: int
|
| 92 |
+
DISCONNECT_AUTH_CANCELLED_BY_USER: int
|
| 93 |
+
DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE: int
|
| 94 |
+
|
| 95 |
+
zero_byte: bytes
|
| 96 |
+
one_byte: bytes
|
| 97 |
+
four_byte: bytes
|
| 98 |
+
max_byte: bytes
|
| 99 |
+
cr_byte: bytes
|
| 100 |
+
linefeed_byte: bytes
|
| 101 |
+
crlf: bytes
|
| 102 |
+
if sys.version_info < (3, 0):
|
| 103 |
+
cr_byte_value: bytes
|
| 104 |
+
linefeed_byte_value: bytes
|
| 105 |
+
else:
|
| 106 |
+
cr_byte_value: int
|
| 107 |
+
linefeed_byte_value: int
|
| 108 |
+
|
| 109 |
+
class _SupportsAsBytes(Protocol):
|
| 110 |
+
def asbytes(self) -> bytes: ...
|
| 111 |
+
|
| 112 |
+
_LikeBytes = Union[bytes, Text, _SupportsAsBytes]
|
| 113 |
+
|
| 114 |
+
def asbytes(s: _LikeBytes) -> bytes: ...
|
| 115 |
+
|
| 116 |
+
xffffffff: int
|
| 117 |
+
x80000000: int
|
| 118 |
+
o666: int
|
| 119 |
+
o660: int
|
| 120 |
+
o644: int
|
| 121 |
+
o600: int
|
| 122 |
+
o777: int
|
| 123 |
+
o700: int
|
| 124 |
+
o70: int
|
| 125 |
+
|
| 126 |
+
DEBUG: int
|
| 127 |
+
INFO: int
|
| 128 |
+
WARNING: int
|
| 129 |
+
ERROR: int
|
| 130 |
+
CRITICAL: int
|
| 131 |
+
|
| 132 |
+
io_sleep: float
|
| 133 |
+
|
| 134 |
+
DEFAULT_WINDOW_SIZE: int
|
| 135 |
+
DEFAULT_MAX_PACKET_SIZE: int
|
| 136 |
+
|
| 137 |
+
MIN_WINDOW_SIZE: int
|
| 138 |
+
MIN_PACKET_SIZE: int
|
| 139 |
+
MAX_WINDOW_SIZE: int
|
shared/package-files/31/31f09bc8966ed57b0224e092c3abef86ce1e88fe0b64f705f9ef61b8f996fb2b/blob
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import traceback
|
| 2 |
+
import threading
|
| 3 |
+
import multiprocessing
|
| 4 |
+
import numpy as np
|
| 5 |
+
from numba import cuda
|
| 6 |
+
from numba.cuda.testing import (skip_on_cudasim, skip_under_cuda_memcheck,
|
| 7 |
+
CUDATestCase)
|
| 8 |
+
import unittest
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 12 |
+
except ImportError:
|
| 13 |
+
has_concurrent_futures = False
|
| 14 |
+
else:
|
| 15 |
+
has_concurrent_futures = True
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
has_mp_get_context = hasattr(multiprocessing, 'get_context')
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def check_concurrent_compiling():
|
| 22 |
+
@cuda.jit
|
| 23 |
+
def foo(x):
|
| 24 |
+
x[0] += 1
|
| 25 |
+
|
| 26 |
+
def use_foo(x):
|
| 27 |
+
foo[1, 1](x)
|
| 28 |
+
return x
|
| 29 |
+
|
| 30 |
+
arrays = [cuda.to_device(np.arange(10)) for i in range(10)]
|
| 31 |
+
expected = np.arange(10)
|
| 32 |
+
expected[0] += 1
|
| 33 |
+
with ThreadPoolExecutor(max_workers=4) as e:
|
| 34 |
+
for ary in e.map(use_foo, arrays):
|
| 35 |
+
np.testing.assert_equal(ary, expected)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def spawn_process_entry(q):
|
| 39 |
+
try:
|
| 40 |
+
check_concurrent_compiling()
|
| 41 |
+
# Catch anything that goes wrong in the threads
|
| 42 |
+
except: # noqa: E722
|
| 43 |
+
msg = traceback.format_exc()
|
| 44 |
+
q.put('\n'.join(['', '=' * 80, msg]))
|
| 45 |
+
else:
|
| 46 |
+
q.put(None)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@skip_under_cuda_memcheck('Hangs cuda-memcheck')
|
| 50 |
+
@skip_on_cudasim('disabled for cudasim')
|
| 51 |
+
class TestMultiThreadCompiling(CUDATestCase):
|
| 52 |
+
|
| 53 |
+
@unittest.skipIf(not has_concurrent_futures, "no concurrent.futures")
|
| 54 |
+
def test_concurrent_compiling(self):
|
| 55 |
+
check_concurrent_compiling()
|
| 56 |
+
|
| 57 |
+
@unittest.skipIf(not has_mp_get_context, "no multiprocessing.get_context")
|
| 58 |
+
def test_spawn_concurrent_compilation(self):
|
| 59 |
+
# force CUDA context init
|
| 60 |
+
cuda.get_current_device()
|
| 61 |
+
# use "spawn" to avoid inheriting the CUDA context
|
| 62 |
+
ctx = multiprocessing.get_context('spawn')
|
| 63 |
+
|
| 64 |
+
q = ctx.Queue()
|
| 65 |
+
p = ctx.Process(target=spawn_process_entry, args=(q,))
|
| 66 |
+
p.start()
|
| 67 |
+
try:
|
| 68 |
+
err = q.get()
|
| 69 |
+
finally:
|
| 70 |
+
p.join()
|
| 71 |
+
if err is not None:
|
| 72 |
+
raise AssertionError(err)
|
| 73 |
+
self.assertEqual(p.exitcode, 0, 'test failed in child process')
|
| 74 |
+
|
| 75 |
+
def test_invalid_context_error_with_d2h(self):
|
| 76 |
+
def d2h(arr, out):
|
| 77 |
+
out[:] = arr.copy_to_host()
|
| 78 |
+
|
| 79 |
+
arr = np.arange(1, 4)
|
| 80 |
+
out = np.zeros_like(arr)
|
| 81 |
+
darr = cuda.to_device(arr)
|
| 82 |
+
th = threading.Thread(target=d2h, args=[darr, out])
|
| 83 |
+
th.start()
|
| 84 |
+
th.join()
|
| 85 |
+
np.testing.assert_equal(arr, out)
|
| 86 |
+
|
| 87 |
+
def test_invalid_context_error_with_d2d(self):
|
| 88 |
+
def d2d(dst, src):
|
| 89 |
+
dst.copy_to_device(src)
|
| 90 |
+
|
| 91 |
+
arr = np.arange(100)
|
| 92 |
+
common = cuda.to_device(arr)
|
| 93 |
+
darr = cuda.to_device(np.zeros(common.shape, dtype=common.dtype))
|
| 94 |
+
th = threading.Thread(target=d2d, args=[darr, common])
|
| 95 |
+
th.start()
|
| 96 |
+
th.join()
|
| 97 |
+
np.testing.assert_equal(darr.copy_to_host(), arr)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == '__main__':
|
| 101 |
+
unittest.main()
|
shared/package-files/31/31f16bfef90158d13d4fc249e83459165a1edab89273841343d613b0571729c2/blob
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API bool is_inference(const at::Tensor & self);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
shared/package-files/31/31f6496511a73ae245863ac284927466508fa6c2b64a9aab69f57b5649c0afc0/blob
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from ..._explanation import Explanation
|
| 4 |
+
from .._explainer import Explainer
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class DeepExplainer(Explainer):
|
| 8 |
+
"""Meant to approximate SHAP values for deep learning models.
|
| 9 |
+
|
| 10 |
+
This is an enhanced version of the DeepLIFT algorithm (Deep SHAP) where, similar to Kernel SHAP, we
|
| 11 |
+
approximate the conditional expectations of SHAP values using a selection of background samples.
|
| 12 |
+
Lundberg and Lee, NIPS 2017 showed that the per node attribution rules in DeepLIFT (Shrikumar,
|
| 13 |
+
Greenside, and Kundaje, arXiv 2017) can be chosen to approximate Shapley values. By integrating
|
| 14 |
+
over many background samples, Deep estimates approximate SHAP values such that they sum
|
| 15 |
+
up to the difference between the expected model output on the passed background samples and the
|
| 16 |
+
current model output (f(x) - E[f(x)]).
|
| 17 |
+
|
| 18 |
+
Examples
|
| 19 |
+
--------
|
| 20 |
+
See :ref:`Deep Explainer Examples <deep_explainer_examples>`
|
| 21 |
+
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, model, data, session=None, learning_phase_flags=None):
|
| 25 |
+
"""An explainer object for a differentiable model using a given background dataset.
|
| 26 |
+
|
| 27 |
+
Note that the complexity of the method scales linearly with the number of background data
|
| 28 |
+
samples. Passing the entire training dataset as `data` will give very accurate expected
|
| 29 |
+
values, but will be unreasonably expensive. The variance of the expectation estimates scales by
|
| 30 |
+
roughly 1/sqrt(N) for N background data samples. So 100 samples will give a good estimate,
|
| 31 |
+
and 1000 samples a very good estimate of the expected values.
|
| 32 |
+
|
| 33 |
+
Parameters
|
| 34 |
+
----------
|
| 35 |
+
model :
|
| 36 |
+
if framework == 'tensorflow', (input : [tf.Tensor], output : tf.Tensor)
|
| 37 |
+
A pair of TensorFlow tensors (or a list and a tensor) that specifies the input and
|
| 38 |
+
output of the model to be explained. Note that SHAP values are specific to a single
|
| 39 |
+
output value, so the output tf.Tensor should be a single dimensional output (,1).
|
| 40 |
+
|
| 41 |
+
if framework == 'pytorch', an nn.Module object (model), or a tuple (model, layer),
|
| 42 |
+
where both are nn.Module objects.
|
| 43 |
+
The model is an nn.Module object which takes as input a tensor (or list of tensors) of
|
| 44 |
+
shape data, and returns a single dimensional output.
|
| 45 |
+
If the input is a tuple, the returned shap values will be for the input of the
|
| 46 |
+
layer argument. layer must be a layer in the model, i.e. model.conv2
|
| 47 |
+
|
| 48 |
+
data :
|
| 49 |
+
if framework == 'tensorflow': [np.array] or [pandas.DataFrame]
|
| 50 |
+
if framework == 'pytorch': [torch.tensor]
|
| 51 |
+
|
| 52 |
+
The background dataset to use for integrating out features. Deep integrates
|
| 53 |
+
over these samples. The data passed here must match the input tensors given in the
|
| 54 |
+
first argument. Note that, since these samples are integrated over for each sample, you
|
| 55 |
+
should only use something like 100 or 1000 random background samples, not the whole
|
| 56 |
+
training dataset.
|
| 57 |
+
|
| 58 |
+
session : None or tensorflow.Session
|
| 59 |
+
The TensorFlow session that has the model we are explaining. If None is passed then
|
| 60 |
+
we do our best to find the right session, first looking for a keras session, then
|
| 61 |
+
falling back to the default TensorFlow session.
|
| 62 |
+
|
| 63 |
+
learning_phase_flags : None or list of tensors
|
| 64 |
+
If you have your own custom learning phase flags, pass them here. When explaining a prediction
|
| 65 |
+
we need to ensure we are not in training mode, since this changes the behavior of ops like
|
| 66 |
+
batch norm or dropout. If None is passed then we look for tensors in the graph that look like
|
| 67 |
+
learning phase flags (this works for Keras models). Note that we assume all the flags should
|
| 68 |
+
have a value of False during predictions (and hence explanations).
|
| 69 |
+
|
| 70 |
+
"""
|
| 71 |
+
# first, we need to find the framework
|
| 72 |
+
if type(model) is tuple:
|
| 73 |
+
a, b = model
|
| 74 |
+
try:
|
| 75 |
+
a.named_parameters()
|
| 76 |
+
framework = "pytorch"
|
| 77 |
+
except Exception:
|
| 78 |
+
framework = "tensorflow"
|
| 79 |
+
else:
|
| 80 |
+
try:
|
| 81 |
+
model.named_parameters()
|
| 82 |
+
framework = "pytorch"
|
| 83 |
+
except Exception:
|
| 84 |
+
framework = "tensorflow"
|
| 85 |
+
|
| 86 |
+
masker = data
|
| 87 |
+
super().__init__(model, masker)
|
| 88 |
+
|
| 89 |
+
self.explainer: TFDeep | PyTorchDeep
|
| 90 |
+
if framework == "tensorflow":
|
| 91 |
+
from .deep_tf import TFDeep
|
| 92 |
+
|
| 93 |
+
self.explainer = TFDeep(model, data, session, learning_phase_flags)
|
| 94 |
+
elif framework == "pytorch":
|
| 95 |
+
from .deep_pytorch import PyTorchDeep
|
| 96 |
+
|
| 97 |
+
self.explainer = PyTorchDeep(model, data)
|
| 98 |
+
|
| 99 |
+
self.expected_value = self.explainer.expected_value
|
| 100 |
+
self.explainer.framework = framework # type: ignore
|
| 101 |
+
|
| 102 |
+
def __call__(self, X: list | np.ndarray | pd.DataFrame | torch.tensor) -> Explanation: # type: ignore # noqa: F821
|
| 103 |
+
"""Return an explanation object for the model applied to X.
|
| 104 |
+
|
| 105 |
+
Parameters
|
| 106 |
+
----------
|
| 107 |
+
X : list,
|
| 108 |
+
if framework == 'tensorflow': numpy.array, or pandas.DataFrame
|
| 109 |
+
if framework == 'pytorch': torch.tensor
|
| 110 |
+
A tensor (or list of tensors) of samples (where X.shape[0] == # samples) on which to
|
| 111 |
+
explain the model's output.
|
| 112 |
+
|
| 113 |
+
Returns
|
| 114 |
+
-------
|
| 115 |
+
shap.Explanation:
|
| 116 |
+
"""
|
| 117 |
+
shap_values = self.shap_values(X)
|
| 118 |
+
return Explanation(values=shap_values, data=X)
|
| 119 |
+
|
| 120 |
+
def shap_values(self, X, ranked_outputs=None, output_rank_order="max", check_additivity=True):
|
| 121 |
+
"""Return approximate SHAP values for the model applied to the data given by X.
|
| 122 |
+
|
| 123 |
+
Parameters
|
| 124 |
+
----------
|
| 125 |
+
X : list,
|
| 126 |
+
if framework == 'tensorflow': np.array, or pandas.DataFrame
|
| 127 |
+
if framework == 'pytorch': torch.tensor
|
| 128 |
+
A tensor (or list of tensors) of samples (where X.shape[0] == # samples) on which to
|
| 129 |
+
explain the model's output.
|
| 130 |
+
|
| 131 |
+
ranked_outputs : None or int
|
| 132 |
+
If ranked_outputs is None then we explain all the outputs in a multi-output model. If
|
| 133 |
+
ranked_outputs is a positive integer then we only explain that many of the top model
|
| 134 |
+
outputs (where "top" is determined by output_rank_order). Note that this causes a pair
|
| 135 |
+
of values to be returned (shap_values, indexes), where shap_values is a list of numpy
|
| 136 |
+
arrays for each of the output ranks, and indexes is a matrix that indicates for each sample
|
| 137 |
+
which output indexes were choses as "top".
|
| 138 |
+
|
| 139 |
+
output_rank_order : "max", "min", or "max_abs"
|
| 140 |
+
How to order the model outputs when using ranked_outputs, either by maximum, minimum, or
|
| 141 |
+
maximum absolute value.
|
| 142 |
+
|
| 143 |
+
Returns
|
| 144 |
+
-------
|
| 145 |
+
np.array or list
|
| 146 |
+
Estimated SHAP values, usually of shape ``(# samples x # features)``.
|
| 147 |
+
|
| 148 |
+
The shape of the returned array depends on the number of model outputs:
|
| 149 |
+
|
| 150 |
+
* one input, one output: matrix of shape ``(#num_samples, *X.shape[1:])``.
|
| 151 |
+
* one input, multiple outputs: matrix of shape ``(#num_samples, *X.shape[1:], #num_outputs)``
|
| 152 |
+
* multiple inputs, one or more outputs: list of matrices, with shapes of one of the above.
|
| 153 |
+
|
| 154 |
+
If ranked_outputs is ``None`` then this list of tensors matches
|
| 155 |
+
the number of model outputs. If ranked_outputs is a positive integer a pair is returned
|
| 156 |
+
(shap_values, indexes), where shap_values is a list of tensors with a length of
|
| 157 |
+
ranked_outputs, and indexes is a matrix that indicates for each sample which output indexes
|
| 158 |
+
were chosen as "top".
|
| 159 |
+
|
| 160 |
+
.. versionchanged:: 0.45.0
|
| 161 |
+
Return type for models with multiple outputs and one input changed from list to np.ndarray.
|
| 162 |
+
|
| 163 |
+
"""
|
| 164 |
+
return self.explainer.shap_values(X, ranked_outputs, output_rank_order, check_additivity=check_additivity)
|
shared/package-files/31/31f721de5fe36cae5740d7da2e15e9e8e72fa391d42a118db10cc771f2cf1b0d/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 cuda {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor __lshift__(const at::Tensor & self, const at::Scalar & other);
|
| 21 |
+
TORCH_API at::Tensor & __ilshift__(at::Tensor & self, const at::Scalar & other);
|
| 22 |
+
TORCH_API at::Tensor __lshift__(const at::Tensor & self, const at::Tensor & other);
|
| 23 |
+
TORCH_API at::Tensor & __ilshift__(at::Tensor & self, const at::Tensor & other);
|
| 24 |
+
|
| 25 |
+
} // namespace cuda
|
| 26 |
+
} // namespace at
|
shared/package-files/31/31f7e08f7c79b45c2c2968a1c3691b8529a1bc634481073fa498ba0b79844317/blob
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.lexers.wgsl
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
Lexer for the WebGPU Shading Language.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from pygments.lexer import RegexLexer, include, bygroups, words, default
|
| 12 |
+
from pygments.token import Comment, Operator, Keyword, Name, \
|
| 13 |
+
Number, Punctuation, Whitespace
|
| 14 |
+
from pygments import unistring as uni
|
| 15 |
+
|
| 16 |
+
__all__ = ['WgslLexer']
|
| 17 |
+
|
| 18 |
+
LF = '\\u000a'
|
| 19 |
+
VT = '\\u000b'
|
| 20 |
+
FF = '\\u000c'
|
| 21 |
+
CR = '\\u000d'
|
| 22 |
+
NextLine = '\\u0085'
|
| 23 |
+
LineSep = '\\u2028'
|
| 24 |
+
ParaSep = '\\u2029'
|
| 25 |
+
LineEndCodePoints = [LF,VT,FF,CR,NextLine,LineSep,ParaSep]
|
| 26 |
+
NotLineEndRE = '[^' + "".join(LineEndCodePoints) + ']'
|
| 27 |
+
LineEndRE = '[' + "".join(LineEndCodePoints) + ']'
|
| 28 |
+
|
| 29 |
+
# https://www.w3.org/TR/WGSL/#syntax-ident_pattern_token
|
| 30 |
+
ident_pattern_token = '([{}][{}]+)|[{}]'.format(uni.xid_start,uni.xid_continue,uni.xid_start)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class WgslLexer(RegexLexer):
|
| 34 |
+
"""
|
| 35 |
+
Lexer for the WebGPU Shading Language.
|
| 36 |
+
|
| 37 |
+
.. versionadded:: 2.15
|
| 38 |
+
"""
|
| 39 |
+
name = 'WebGPU Shading Language'
|
| 40 |
+
url = 'https://www.w3.org/TR/WGSL/'
|
| 41 |
+
aliases = ['wgsl']
|
| 42 |
+
filenames = ['*.wgsl']
|
| 43 |
+
mimetypes = ['text/wgsl']
|
| 44 |
+
|
| 45 |
+
# https://www.w3.org/TR/WGSL/#var-and-value
|
| 46 |
+
keyword_decl = (words('var let const override'.split(),suffix=r'\b'), Keyword.Declaration)
|
| 47 |
+
# https://www.w3.org/TR/WGSL/#keyword-summary
|
| 48 |
+
keywords = (words("""
|
| 49 |
+
alias
|
| 50 |
+
break
|
| 51 |
+
case
|
| 52 |
+
const_assert
|
| 53 |
+
continue
|
| 54 |
+
continuing
|
| 55 |
+
default
|
| 56 |
+
diagnostic
|
| 57 |
+
discard
|
| 58 |
+
else
|
| 59 |
+
enable
|
| 60 |
+
false
|
| 61 |
+
fn
|
| 62 |
+
for
|
| 63 |
+
if
|
| 64 |
+
loop
|
| 65 |
+
requires
|
| 66 |
+
return
|
| 67 |
+
struct
|
| 68 |
+
switch
|
| 69 |
+
true
|
| 70 |
+
while
|
| 71 |
+
""".split(), suffix=r'\b'), Keyword)
|
| 72 |
+
|
| 73 |
+
# https://www.w3.org/TR/WGSL/#reserved-words
|
| 74 |
+
keyword_reserved = (words("""
|
| 75 |
+
NULL
|
| 76 |
+
Self
|
| 77 |
+
abstract
|
| 78 |
+
active
|
| 79 |
+
alignas
|
| 80 |
+
alignof
|
| 81 |
+
as
|
| 82 |
+
asm
|
| 83 |
+
asm_fragment
|
| 84 |
+
async
|
| 85 |
+
attribute
|
| 86 |
+
auto
|
| 87 |
+
await
|
| 88 |
+
become
|
| 89 |
+
binding_array
|
| 90 |
+
cast
|
| 91 |
+
catch
|
| 92 |
+
class
|
| 93 |
+
co_await
|
| 94 |
+
co_return
|
| 95 |
+
co_yield
|
| 96 |
+
coherent
|
| 97 |
+
column_major
|
| 98 |
+
common
|
| 99 |
+
compile
|
| 100 |
+
compile_fragment
|
| 101 |
+
concept
|
| 102 |
+
const_cast
|
| 103 |
+
consteval
|
| 104 |
+
constexpr
|
| 105 |
+
constinit
|
| 106 |
+
crate
|
| 107 |
+
debugger
|
| 108 |
+
decltype
|
| 109 |
+
delete
|
| 110 |
+
demote
|
| 111 |
+
demote_to_helper
|
| 112 |
+
do
|
| 113 |
+
dynamic_cast
|
| 114 |
+
enum
|
| 115 |
+
explicit
|
| 116 |
+
export
|
| 117 |
+
extends
|
| 118 |
+
extern
|
| 119 |
+
external
|
| 120 |
+
fallthrough
|
| 121 |
+
filter
|
| 122 |
+
final
|
| 123 |
+
finally
|
| 124 |
+
friend
|
| 125 |
+
from
|
| 126 |
+
fxgroup
|
| 127 |
+
get
|
| 128 |
+
goto
|
| 129 |
+
groupshared
|
| 130 |
+
highp
|
| 131 |
+
impl
|
| 132 |
+
implements
|
| 133 |
+
import
|
| 134 |
+
inline
|
| 135 |
+
instanceof
|
| 136 |
+
interface
|
| 137 |
+
layout
|
| 138 |
+
lowp
|
| 139 |
+
macro
|
| 140 |
+
macro_rules
|
| 141 |
+
match
|
| 142 |
+
mediump
|
| 143 |
+
meta
|
| 144 |
+
mod
|
| 145 |
+
module
|
| 146 |
+
move
|
| 147 |
+
mut
|
| 148 |
+
mutable
|
| 149 |
+
namespace
|
| 150 |
+
new
|
| 151 |
+
nil
|
| 152 |
+
noexcept
|
| 153 |
+
noinline
|
| 154 |
+
nointerpolation
|
| 155 |
+
noperspective
|
| 156 |
+
null
|
| 157 |
+
nullptr
|
| 158 |
+
of
|
| 159 |
+
operator
|
| 160 |
+
package
|
| 161 |
+
packoffset
|
| 162 |
+
partition
|
| 163 |
+
pass
|
| 164 |
+
patch
|
| 165 |
+
pixelfragment
|
| 166 |
+
precise
|
| 167 |
+
precision
|
| 168 |
+
premerge
|
| 169 |
+
priv
|
| 170 |
+
protected
|
| 171 |
+
pub
|
| 172 |
+
public
|
| 173 |
+
readonly
|
| 174 |
+
ref
|
| 175 |
+
regardless
|
| 176 |
+
register
|
| 177 |
+
reinterpret_cast
|
| 178 |
+
require
|
| 179 |
+
resource
|
| 180 |
+
restrict
|
| 181 |
+
self
|
| 182 |
+
set
|
| 183 |
+
shared
|
| 184 |
+
sizeof
|
| 185 |
+
smooth
|
| 186 |
+
snorm
|
| 187 |
+
static
|
| 188 |
+
static_assert
|
| 189 |
+
static_cast
|
| 190 |
+
std
|
| 191 |
+
subroutine
|
| 192 |
+
super
|
| 193 |
+
target
|
| 194 |
+
template
|
| 195 |
+
this
|
| 196 |
+
thread_local
|
| 197 |
+
throw
|
| 198 |
+
trait
|
| 199 |
+
try
|
| 200 |
+
type
|
| 201 |
+
typedef
|
| 202 |
+
typeid
|
| 203 |
+
typename
|
| 204 |
+
typeof
|
| 205 |
+
union
|
| 206 |
+
unless
|
| 207 |
+
unorm
|
| 208 |
+
unsafe
|
| 209 |
+
unsized
|
| 210 |
+
use
|
| 211 |
+
using
|
| 212 |
+
varying
|
| 213 |
+
virtual
|
| 214 |
+
volatile
|
| 215 |
+
wgsl
|
| 216 |
+
where
|
| 217 |
+
with
|
| 218 |
+
writeonly
|
| 219 |
+
yield
|
| 220 |
+
""".split(), suffix=r'\b'), Keyword.Reserved)
|
| 221 |
+
|
| 222 |
+
# https://www.w3.org/TR/WGSL/#predeclared-enumerants
|
| 223 |
+
predeclared_enums = (words("""
|
| 224 |
+
read write read_write
|
| 225 |
+
function private workgroup uniform storage
|
| 226 |
+
perspective linear flat
|
| 227 |
+
center centroid sample
|
| 228 |
+
vertex_index instance_index position front_facing frag_depth
|
| 229 |
+
local_invocation_id local_invocation_index
|
| 230 |
+
global_invocation_id workgroup_id num_workgroups
|
| 231 |
+
sample_index sample_mask
|
| 232 |
+
rgba8unorm
|
| 233 |
+
rgba8snorm
|
| 234 |
+
rgba8uint
|
| 235 |
+
rgba8sint
|
| 236 |
+
rgba16uint
|
| 237 |
+
rgba16sint
|
| 238 |
+
rgba16float
|
| 239 |
+
r32uint
|
| 240 |
+
r32sint
|
| 241 |
+
r32float
|
| 242 |
+
rg32uint
|
| 243 |
+
rg32sint
|
| 244 |
+
rg32float
|
| 245 |
+
rgba32uint
|
| 246 |
+
rgba32sint
|
| 247 |
+
rgba32float
|
| 248 |
+
bgra8unorm
|
| 249 |
+
""".split(), suffix=r'\b'), Name.Builtin)
|
| 250 |
+
|
| 251 |
+
# https://www.w3.org/TR/WGSL/#predeclared-types
|
| 252 |
+
predeclared_types = (words("""
|
| 253 |
+
bool
|
| 254 |
+
f16
|
| 255 |
+
f32
|
| 256 |
+
i32
|
| 257 |
+
sampler sampler_comparison
|
| 258 |
+
texture_depth_2d
|
| 259 |
+
texture_depth_2d_array
|
| 260 |
+
texture_depth_cube
|
| 261 |
+
texture_depth_cube_array
|
| 262 |
+
texture_depth_multisampled_2d
|
| 263 |
+
texture_external
|
| 264 |
+
texture_external
|
| 265 |
+
u32
|
| 266 |
+
""".split(), suffix=r'\b'), Name.Builtin)
|
| 267 |
+
|
| 268 |
+
# https://www.w3.org/TR/WGSL/#predeclared-types
|
| 269 |
+
predeclared_type_generators = (words("""
|
| 270 |
+
array
|
| 271 |
+
atomic
|
| 272 |
+
mat2x2
|
| 273 |
+
mat2x3
|
| 274 |
+
mat2x4
|
| 275 |
+
mat3x2
|
| 276 |
+
mat3x3
|
| 277 |
+
mat3x4
|
| 278 |
+
mat4x2
|
| 279 |
+
mat4x3
|
| 280 |
+
mat4x4
|
| 281 |
+
ptr
|
| 282 |
+
texture_1d
|
| 283 |
+
texture_2d
|
| 284 |
+
texture_2d_array
|
| 285 |
+
texture_3d
|
| 286 |
+
texture_cube
|
| 287 |
+
texture_cube_array
|
| 288 |
+
texture_multisampled_2d
|
| 289 |
+
texture_storage_1d
|
| 290 |
+
texture_storage_2d
|
| 291 |
+
texture_storage_2d_array
|
| 292 |
+
texture_storage_3d
|
| 293 |
+
vec2
|
| 294 |
+
vec3
|
| 295 |
+
vec4
|
| 296 |
+
""".split(), suffix=r'\b'), Name.Builtin)
|
| 297 |
+
|
| 298 |
+
# Predeclared type aliases for vectors
|
| 299 |
+
# https://www.w3.org/TR/WGSL/#vector-types
|
| 300 |
+
predeclared_type_alias_vectors = (words("""
|
| 301 |
+
vec2i vec3i vec4i
|
| 302 |
+
vec2u vec3u vec4u
|
| 303 |
+
vec2f vec3f vec4f
|
| 304 |
+
vec2h vec3h vec4h
|
| 305 |
+
""".split(), suffix=r'\b'), Name.Builtin)
|
| 306 |
+
|
| 307 |
+
# Predeclared type aliases for matrices
|
| 308 |
+
# https://www.w3.org/TR/WGSL/#matrix-types
|
| 309 |
+
predeclared_type_alias_matrices = (words("""
|
| 310 |
+
mat2x2f mat2x3f mat2x4f
|
| 311 |
+
mat3x2f mat3x3f mat3x4f
|
| 312 |
+
mat4x2f mat4x3f mat4x4f
|
| 313 |
+
mat2x2h mat2x3h mat2x4h
|
| 314 |
+
mat3x2h mat3x3h mat3x4h
|
| 315 |
+
mat4x2h mat4x3h mat4x4h
|
| 316 |
+
""".split(), suffix=r'\b'), Name.Builtin)
|
| 317 |
+
|
| 318 |
+
tokens = {
|
| 319 |
+
'blankspace': [
|
| 320 |
+
# https://www.w3.org/TR/WGSL/#blankspace
|
| 321 |
+
(r'[\u0020\u0009\u000a\u000b\u000c\u000d\u0085\u200e\u200f\u2028\u2029]+', Whitespace),
|
| 322 |
+
],
|
| 323 |
+
'comments': [
|
| 324 |
+
# Line ending comments
|
| 325 |
+
# Match up CR/LF pair first.
|
| 326 |
+
(r'//{}*{}{}'.format(NotLineEndRE,CR,LF), Comment.Single),
|
| 327 |
+
(r'//{}*{}'.format(NotLineEndRE,LineEndRE), Comment.Single),
|
| 328 |
+
(r'/\*', Comment.Multiline, 'block_comment'),
|
| 329 |
+
],
|
| 330 |
+
'attribute': [
|
| 331 |
+
include('blankspace'),
|
| 332 |
+
include('comments'),
|
| 333 |
+
(ident_pattern_token, Name.Decorator,'#pop'),
|
| 334 |
+
default('#pop'),
|
| 335 |
+
],
|
| 336 |
+
'root': [
|
| 337 |
+
include('blankspace'),
|
| 338 |
+
include('comments'),
|
| 339 |
+
|
| 340 |
+
# Attributes.
|
| 341 |
+
# https://www.w3.org/TR/WGSL/#attributes
|
| 342 |
+
# Mark the '@' and the attribute name as a decorator.
|
| 343 |
+
(r'@', Name.Decorator, 'attribute'),
|
| 344 |
+
|
| 345 |
+
# Keywords
|
| 346 |
+
(r'(true|false)\b', Keyword.Constant),
|
| 347 |
+
keyword_decl,
|
| 348 |
+
keywords,
|
| 349 |
+
keyword_reserved,
|
| 350 |
+
|
| 351 |
+
# Predeclared
|
| 352 |
+
predeclared_enums,
|
| 353 |
+
predeclared_types,
|
| 354 |
+
predeclared_type_generators,
|
| 355 |
+
predeclared_type_alias_vectors,
|
| 356 |
+
predeclared_type_alias_matrices,
|
| 357 |
+
|
| 358 |
+
# Decimal float literals
|
| 359 |
+
# https://www.w3.org/TR/WGSL/#syntax-decimal_float_literal
|
| 360 |
+
# 0, with type-specifying suffix.
|
| 361 |
+
(r'0[fh]', Number.Float),
|
| 362 |
+
# Other decimal integer, with type-specifying suffix.
|
| 363 |
+
(r'[1-9][0-9]*[fh]', Number.Float),
|
| 364 |
+
# Has decimal point, at least one digit after decimal.
|
| 365 |
+
(r'[0-9]*\.[0-9]+([eE][+-]?[0-9]+)?[fh]?', Number.Float),
|
| 366 |
+
# Has decimal point, at least one digit before decimal.
|
| 367 |
+
(r'[0-9]+\.[0-9]*([eE][+-]?[0-9]+)?[fh]?', Number.Float),
|
| 368 |
+
# Has at least one digit, and has an exponent.
|
| 369 |
+
(r'[0-9]+[eE][+-]?[0-9]+[fh]?', Number.Float),
|
| 370 |
+
|
| 371 |
+
# Hex float literals
|
| 372 |
+
# https://www.w3.org/TR/WGSL/#syntax-hex_float_literal
|
| 373 |
+
(r'0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+([pP][+-]?[0-9]+[fh]?)?', Number.Float),
|
| 374 |
+
(r'0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*([pP][+-]?[0-9]+[fh]?)?', Number.Float),
|
| 375 |
+
(r'0[xX][0-9a-fA-F]+[pP][+-]?[0-9]+[fh]?', Number.Float),
|
| 376 |
+
|
| 377 |
+
# Hexadecimal integer literals
|
| 378 |
+
# https://www.w3.org/TR/WGSL/#syntax-hex_int_literal
|
| 379 |
+
(r'0[xX][0-9a-fA-F]+[iu]?', Number.Hex),
|
| 380 |
+
# Decimal integer literals
|
| 381 |
+
# https://www.w3.org/TR/WGSL/#syntax-decimal_int_literal
|
| 382 |
+
# We need two rules here because 01 is not valid.
|
| 383 |
+
(r'[1-9][0-9]*[iu]?', Number.Integer),
|
| 384 |
+
(r'0[iu]?', Number.Integer), # Must match last.
|
| 385 |
+
|
| 386 |
+
# Operators and Punctuation
|
| 387 |
+
(r'[{}()\[\],\.;:]', Punctuation),
|
| 388 |
+
(r'->', Punctuation), # Return-type arrow
|
| 389 |
+
(r'[+\-*/%&|<>^!~=]', Operator),
|
| 390 |
+
|
| 391 |
+
# TODO: Treat context-depedendent names specially
|
| 392 |
+
# https://www.w3.org/TR/WGSL/#context-dependent-name
|
| 393 |
+
|
| 394 |
+
# Identifiers
|
| 395 |
+
(ident_pattern_token, Name),
|
| 396 |
+
|
| 397 |
+
# TODO: templates start and end tokens.
|
| 398 |
+
# https://www.w3.org/TR/WGSL/#template-lists-sec
|
| 399 |
+
],
|
| 400 |
+
'block_comment': [
|
| 401 |
+
# https://www.w3.org/TR/WGSL/#block-comment
|
| 402 |
+
(r'[^*/]+', Comment.Multiline),
|
| 403 |
+
(r'/\*', Comment.Multiline, '#push'),
|
| 404 |
+
(r'\*/', Comment.Multiline, '#pop'),
|
| 405 |
+
(r'[*/]', Comment.Multiline),
|
| 406 |
+
],
|
| 407 |
+
}
|
shared/package-files/31/31fe7b070a21467f727ba8b126a8cd1272b480aaa754f13d1b2f2f2beebfcf1a/blob
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A module with various ``typing.Protocol`` subclasses that implement
|
| 3 |
+
the ``__call__`` magic method.
|
| 4 |
+
|
| 5 |
+
See the `Mypy documentation`_ on protocols for more details.
|
| 6 |
+
|
| 7 |
+
.. _`Mypy documentation`: https://mypy.readthedocs.io/en/stable/protocols.html#callback-protocols
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from typing import (
|
| 14 |
+
TypeVar,
|
| 15 |
+
overload,
|
| 16 |
+
Any,
|
| 17 |
+
NoReturn,
|
| 18 |
+
Protocol,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
from numpy import (
|
| 22 |
+
ndarray,
|
| 23 |
+
dtype,
|
| 24 |
+
generic,
|
| 25 |
+
bool_,
|
| 26 |
+
timedelta64,
|
| 27 |
+
number,
|
| 28 |
+
integer,
|
| 29 |
+
unsignedinteger,
|
| 30 |
+
signedinteger,
|
| 31 |
+
int8,
|
| 32 |
+
int_,
|
| 33 |
+
floating,
|
| 34 |
+
float64,
|
| 35 |
+
complexfloating,
|
| 36 |
+
complex128,
|
| 37 |
+
)
|
| 38 |
+
from ._nbit import _NBitInt, _NBitDouble
|
| 39 |
+
from ._scalars import (
|
| 40 |
+
_BoolLike_co,
|
| 41 |
+
_IntLike_co,
|
| 42 |
+
_FloatLike_co,
|
| 43 |
+
_NumberLike_co,
|
| 44 |
+
)
|
| 45 |
+
from . import NBitBase
|
| 46 |
+
from ._array_like import NDArray
|
| 47 |
+
from ._nested_sequence import _NestedSequence
|
| 48 |
+
|
| 49 |
+
_T1 = TypeVar("_T1")
|
| 50 |
+
_T2 = TypeVar("_T2")
|
| 51 |
+
_T1_contra = TypeVar("_T1_contra", contravariant=True)
|
| 52 |
+
_T2_contra = TypeVar("_T2_contra", contravariant=True)
|
| 53 |
+
_2Tuple = tuple[_T1, _T1]
|
| 54 |
+
|
| 55 |
+
_NBit1 = TypeVar("_NBit1", bound=NBitBase)
|
| 56 |
+
_NBit2 = TypeVar("_NBit2", bound=NBitBase)
|
| 57 |
+
|
| 58 |
+
_IntType = TypeVar("_IntType", bound=integer)
|
| 59 |
+
_FloatType = TypeVar("_FloatType", bound=floating)
|
| 60 |
+
_NumberType = TypeVar("_NumberType", bound=number)
|
| 61 |
+
_NumberType_co = TypeVar("_NumberType_co", covariant=True, bound=number)
|
| 62 |
+
_GenericType_co = TypeVar("_GenericType_co", covariant=True, bound=generic)
|
| 63 |
+
|
| 64 |
+
class _BoolOp(Protocol[_GenericType_co]):
|
| 65 |
+
@overload
|
| 66 |
+
def __call__(self, other: _BoolLike_co, /) -> _GenericType_co: ...
|
| 67 |
+
@overload # platform dependent
|
| 68 |
+
def __call__(self, other: int, /) -> int_: ...
|
| 69 |
+
@overload
|
| 70 |
+
def __call__(self, other: float, /) -> float64: ...
|
| 71 |
+
@overload
|
| 72 |
+
def __call__(self, other: complex, /) -> complex128: ...
|
| 73 |
+
@overload
|
| 74 |
+
def __call__(self, other: _NumberType, /) -> _NumberType: ...
|
| 75 |
+
|
| 76 |
+
class _BoolBitOp(Protocol[_GenericType_co]):
|
| 77 |
+
@overload
|
| 78 |
+
def __call__(self, other: _BoolLike_co, /) -> _GenericType_co: ...
|
| 79 |
+
@overload # platform dependent
|
| 80 |
+
def __call__(self, other: int, /) -> int_: ...
|
| 81 |
+
@overload
|
| 82 |
+
def __call__(self, other: _IntType, /) -> _IntType: ...
|
| 83 |
+
|
| 84 |
+
class _BoolSub(Protocol):
|
| 85 |
+
# Note that `other: bool_` is absent here
|
| 86 |
+
@overload
|
| 87 |
+
def __call__(self, other: bool, /) -> NoReturn: ...
|
| 88 |
+
@overload # platform dependent
|
| 89 |
+
def __call__(self, other: int, /) -> int_: ...
|
| 90 |
+
@overload
|
| 91 |
+
def __call__(self, other: float, /) -> float64: ...
|
| 92 |
+
@overload
|
| 93 |
+
def __call__(self, other: complex, /) -> complex128: ...
|
| 94 |
+
@overload
|
| 95 |
+
def __call__(self, other: _NumberType, /) -> _NumberType: ...
|
| 96 |
+
|
| 97 |
+
class _BoolTrueDiv(Protocol):
|
| 98 |
+
@overload
|
| 99 |
+
def __call__(self, other: float | _IntLike_co, /) -> float64: ...
|
| 100 |
+
@overload
|
| 101 |
+
def __call__(self, other: complex, /) -> complex128: ...
|
| 102 |
+
@overload
|
| 103 |
+
def __call__(self, other: _NumberType, /) -> _NumberType: ...
|
| 104 |
+
|
| 105 |
+
class _BoolMod(Protocol):
|
| 106 |
+
@overload
|
| 107 |
+
def __call__(self, other: _BoolLike_co, /) -> int8: ...
|
| 108 |
+
@overload # platform dependent
|
| 109 |
+
def __call__(self, other: int, /) -> int_: ...
|
| 110 |
+
@overload
|
| 111 |
+
def __call__(self, other: float, /) -> float64: ...
|
| 112 |
+
@overload
|
| 113 |
+
def __call__(self, other: _IntType, /) -> _IntType: ...
|
| 114 |
+
@overload
|
| 115 |
+
def __call__(self, other: _FloatType, /) -> _FloatType: ...
|
| 116 |
+
|
| 117 |
+
class _BoolDivMod(Protocol):
|
| 118 |
+
@overload
|
| 119 |
+
def __call__(self, other: _BoolLike_co, /) -> _2Tuple[int8]: ...
|
| 120 |
+
@overload # platform dependent
|
| 121 |
+
def __call__(self, other: int, /) -> _2Tuple[int_]: ...
|
| 122 |
+
@overload
|
| 123 |
+
def __call__(self, other: float, /) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
|
| 124 |
+
@overload
|
| 125 |
+
def __call__(self, other: _IntType, /) -> _2Tuple[_IntType]: ...
|
| 126 |
+
@overload
|
| 127 |
+
def __call__(self, other: _FloatType, /) -> _2Tuple[_FloatType]: ...
|
| 128 |
+
|
| 129 |
+
class _TD64Div(Protocol[_NumberType_co]):
|
| 130 |
+
@overload
|
| 131 |
+
def __call__(self, other: timedelta64, /) -> _NumberType_co: ...
|
| 132 |
+
@overload
|
| 133 |
+
def __call__(self, other: _BoolLike_co, /) -> NoReturn: ...
|
| 134 |
+
@overload
|
| 135 |
+
def __call__(self, other: _FloatLike_co, /) -> timedelta64: ...
|
| 136 |
+
|
| 137 |
+
class _IntTrueDiv(Protocol[_NBit1]):
|
| 138 |
+
@overload
|
| 139 |
+
def __call__(self, other: bool, /) -> floating[_NBit1]: ...
|
| 140 |
+
@overload
|
| 141 |
+
def __call__(self, other: int, /) -> floating[_NBit1 | _NBitInt]: ...
|
| 142 |
+
@overload
|
| 143 |
+
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
|
| 144 |
+
@overload
|
| 145 |
+
def __call__(
|
| 146 |
+
self, other: complex, /,
|
| 147 |
+
) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
|
| 148 |
+
@overload
|
| 149 |
+
def __call__(self, other: integer[_NBit2], /) -> floating[_NBit1 | _NBit2]: ...
|
| 150 |
+
|
| 151 |
+
class _UnsignedIntOp(Protocol[_NBit1]):
|
| 152 |
+
# NOTE: `uint64 + signedinteger -> float64`
|
| 153 |
+
@overload
|
| 154 |
+
def __call__(self, other: bool, /) -> unsignedinteger[_NBit1]: ...
|
| 155 |
+
@overload
|
| 156 |
+
def __call__(
|
| 157 |
+
self, other: int | signedinteger[Any], /
|
| 158 |
+
) -> Any: ...
|
| 159 |
+
@overload
|
| 160 |
+
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
|
| 161 |
+
@overload
|
| 162 |
+
def __call__(
|
| 163 |
+
self, other: complex, /,
|
| 164 |
+
) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
|
| 165 |
+
@overload
|
| 166 |
+
def __call__(
|
| 167 |
+
self, other: unsignedinteger[_NBit2], /
|
| 168 |
+
) -> unsignedinteger[_NBit1 | _NBit2]: ...
|
| 169 |
+
|
| 170 |
+
class _UnsignedIntBitOp(Protocol[_NBit1]):
|
| 171 |
+
@overload
|
| 172 |
+
def __call__(self, other: bool, /) -> unsignedinteger[_NBit1]: ...
|
| 173 |
+
@overload
|
| 174 |
+
def __call__(self, other: int, /) -> signedinteger[Any]: ...
|
| 175 |
+
@overload
|
| 176 |
+
def __call__(self, other: signedinteger[Any], /) -> signedinteger[Any]: ...
|
| 177 |
+
@overload
|
| 178 |
+
def __call__(
|
| 179 |
+
self, other: unsignedinteger[_NBit2], /
|
| 180 |
+
) -> unsignedinteger[_NBit1 | _NBit2]: ...
|
| 181 |
+
|
| 182 |
+
class _UnsignedIntMod(Protocol[_NBit1]):
|
| 183 |
+
@overload
|
| 184 |
+
def __call__(self, other: bool, /) -> unsignedinteger[_NBit1]: ...
|
| 185 |
+
@overload
|
| 186 |
+
def __call__(
|
| 187 |
+
self, other: int | signedinteger[Any], /
|
| 188 |
+
) -> Any: ...
|
| 189 |
+
@overload
|
| 190 |
+
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
|
| 191 |
+
@overload
|
| 192 |
+
def __call__(
|
| 193 |
+
self, other: unsignedinteger[_NBit2], /
|
| 194 |
+
) -> unsignedinteger[_NBit1 | _NBit2]: ...
|
| 195 |
+
|
| 196 |
+
class _UnsignedIntDivMod(Protocol[_NBit1]):
|
| 197 |
+
@overload
|
| 198 |
+
def __call__(self, other: bool, /) -> _2Tuple[signedinteger[_NBit1]]: ...
|
| 199 |
+
@overload
|
| 200 |
+
def __call__(
|
| 201 |
+
self, other: int | signedinteger[Any], /
|
| 202 |
+
) -> _2Tuple[Any]: ...
|
| 203 |
+
@overload
|
| 204 |
+
def __call__(self, other: float, /) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
|
| 205 |
+
@overload
|
| 206 |
+
def __call__(
|
| 207 |
+
self, other: unsignedinteger[_NBit2], /
|
| 208 |
+
) -> _2Tuple[unsignedinteger[_NBit1 | _NBit2]]: ...
|
| 209 |
+
|
| 210 |
+
class _SignedIntOp(Protocol[_NBit1]):
|
| 211 |
+
@overload
|
| 212 |
+
def __call__(self, other: bool, /) -> signedinteger[_NBit1]: ...
|
| 213 |
+
@overload
|
| 214 |
+
def __call__(self, other: int, /) -> signedinteger[_NBit1 | _NBitInt]: ...
|
| 215 |
+
@overload
|
| 216 |
+
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
|
| 217 |
+
@overload
|
| 218 |
+
def __call__(
|
| 219 |
+
self, other: complex, /,
|
| 220 |
+
) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
|
| 221 |
+
@overload
|
| 222 |
+
def __call__(
|
| 223 |
+
self, other: signedinteger[_NBit2], /,
|
| 224 |
+
) -> signedinteger[_NBit1 | _NBit2]: ...
|
| 225 |
+
|
| 226 |
+
class _SignedIntBitOp(Protocol[_NBit1]):
|
| 227 |
+
@overload
|
| 228 |
+
def __call__(self, other: bool, /) -> signedinteger[_NBit1]: ...
|
| 229 |
+
@overload
|
| 230 |
+
def __call__(self, other: int, /) -> signedinteger[_NBit1 | _NBitInt]: ...
|
| 231 |
+
@overload
|
| 232 |
+
def __call__(
|
| 233 |
+
self, other: signedinteger[_NBit2], /,
|
| 234 |
+
) -> signedinteger[_NBit1 | _NBit2]: ...
|
| 235 |
+
|
| 236 |
+
class _SignedIntMod(Protocol[_NBit1]):
|
| 237 |
+
@overload
|
| 238 |
+
def __call__(self, other: bool, /) -> signedinteger[_NBit1]: ...
|
| 239 |
+
@overload
|
| 240 |
+
def __call__(self, other: int, /) -> signedinteger[_NBit1 | _NBitInt]: ...
|
| 241 |
+
@overload
|
| 242 |
+
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
|
| 243 |
+
@overload
|
| 244 |
+
def __call__(
|
| 245 |
+
self, other: signedinteger[_NBit2], /,
|
| 246 |
+
) -> signedinteger[_NBit1 | _NBit2]: ...
|
| 247 |
+
|
| 248 |
+
class _SignedIntDivMod(Protocol[_NBit1]):
|
| 249 |
+
@overload
|
| 250 |
+
def __call__(self, other: bool, /) -> _2Tuple[signedinteger[_NBit1]]: ...
|
| 251 |
+
@overload
|
| 252 |
+
def __call__(self, other: int, /) -> _2Tuple[signedinteger[_NBit1 | _NBitInt]]: ...
|
| 253 |
+
@overload
|
| 254 |
+
def __call__(self, other: float, /) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
|
| 255 |
+
@overload
|
| 256 |
+
def __call__(
|
| 257 |
+
self, other: signedinteger[_NBit2], /,
|
| 258 |
+
) -> _2Tuple[signedinteger[_NBit1 | _NBit2]]: ...
|
| 259 |
+
|
| 260 |
+
class _FloatOp(Protocol[_NBit1]):
|
| 261 |
+
@overload
|
| 262 |
+
def __call__(self, other: bool, /) -> floating[_NBit1]: ...
|
| 263 |
+
@overload
|
| 264 |
+
def __call__(self, other: int, /) -> floating[_NBit1 | _NBitInt]: ...
|
| 265 |
+
@overload
|
| 266 |
+
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
|
| 267 |
+
@overload
|
| 268 |
+
def __call__(
|
| 269 |
+
self, other: complex, /,
|
| 270 |
+
) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
|
| 271 |
+
@overload
|
| 272 |
+
def __call__(
|
| 273 |
+
self, other: integer[_NBit2] | floating[_NBit2], /
|
| 274 |
+
) -> floating[_NBit1 | _NBit2]: ...
|
| 275 |
+
|
| 276 |
+
class _FloatMod(Protocol[_NBit1]):
|
| 277 |
+
@overload
|
| 278 |
+
def __call__(self, other: bool, /) -> floating[_NBit1]: ...
|
| 279 |
+
@overload
|
| 280 |
+
def __call__(self, other: int, /) -> floating[_NBit1 | _NBitInt]: ...
|
| 281 |
+
@overload
|
| 282 |
+
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
|
| 283 |
+
@overload
|
| 284 |
+
def __call__(
|
| 285 |
+
self, other: integer[_NBit2] | floating[_NBit2], /
|
| 286 |
+
) -> floating[_NBit1 | _NBit2]: ...
|
| 287 |
+
|
| 288 |
+
class _FloatDivMod(Protocol[_NBit1]):
|
| 289 |
+
@overload
|
| 290 |
+
def __call__(self, other: bool, /) -> _2Tuple[floating[_NBit1]]: ...
|
| 291 |
+
@overload
|
| 292 |
+
def __call__(self, other: int, /) -> _2Tuple[floating[_NBit1 | _NBitInt]]: ...
|
| 293 |
+
@overload
|
| 294 |
+
def __call__(self, other: float, /) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
|
| 295 |
+
@overload
|
| 296 |
+
def __call__(
|
| 297 |
+
self, other: integer[_NBit2] | floating[_NBit2], /
|
| 298 |
+
) -> _2Tuple[floating[_NBit1 | _NBit2]]: ...
|
| 299 |
+
|
| 300 |
+
class _ComplexOp(Protocol[_NBit1]):
|
| 301 |
+
@overload
|
| 302 |
+
def __call__(self, other: bool, /) -> complexfloating[_NBit1, _NBit1]: ...
|
| 303 |
+
@overload
|
| 304 |
+
def __call__(self, other: int, /) -> complexfloating[_NBit1 | _NBitInt, _NBit1 | _NBitInt]: ...
|
| 305 |
+
@overload
|
| 306 |
+
def __call__(
|
| 307 |
+
self, other: complex, /,
|
| 308 |
+
) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
|
| 309 |
+
@overload
|
| 310 |
+
def __call__(
|
| 311 |
+
self,
|
| 312 |
+
other: (
|
| 313 |
+
integer[_NBit2]
|
| 314 |
+
| floating[_NBit2]
|
| 315 |
+
| complexfloating[_NBit2, _NBit2]
|
| 316 |
+
), /,
|
| 317 |
+
) -> complexfloating[_NBit1 | _NBit2, _NBit1 | _NBit2]: ...
|
| 318 |
+
|
| 319 |
+
class _NumberOp(Protocol):
|
| 320 |
+
def __call__(self, other: _NumberLike_co, /) -> Any: ...
|
| 321 |
+
|
| 322 |
+
class _SupportsLT(Protocol):
|
| 323 |
+
def __lt__(self, other: Any, /) -> object: ...
|
| 324 |
+
|
| 325 |
+
class _SupportsGT(Protocol):
|
| 326 |
+
def __gt__(self, other: Any, /) -> object: ...
|
| 327 |
+
|
| 328 |
+
class _ComparisonOp(Protocol[_T1_contra, _T2_contra]):
|
| 329 |
+
@overload
|
| 330 |
+
def __call__(self, other: _T1_contra, /) -> bool_: ...
|
| 331 |
+
@overload
|
| 332 |
+
def __call__(self, other: _T2_contra, /) -> NDArray[bool_]: ...
|
| 333 |
+
@overload
|
| 334 |
+
def __call__(
|
| 335 |
+
self,
|
| 336 |
+
other: _SupportsLT | _SupportsGT | _NestedSequence[_SupportsLT | _SupportsGT],
|
| 337 |
+
/,
|
| 338 |
+
) -> Any: ...
|
shared/package-files/32/32027eb7f7fb836922cdcad667f12b725c791e049ac7d269bda12429a39e9d48/blob
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# See: man pkg-config
|
| 2 |
+
prefix=/opt/conda
|
| 3 |
+
exec_prefix=${prefix}
|
| 4 |
+
libdir=${exec_prefix}/lib
|
| 5 |
+
includedir=${prefix}/include
|
| 6 |
+
|
| 7 |
+
Name: Python
|
| 8 |
+
Description: Embed Python into an application
|
| 9 |
+
Requires:
|
| 10 |
+
Version: 3.10
|
| 11 |
+
Libs.private: -lcrypt -lpthread -ldl -lutil -lm
|
| 12 |
+
Libs: -L${libdir} -lpython3.10
|
| 13 |
+
Cflags: -I${includedir}/python3.10
|
shared/package-files/32/3204305af3d1b1a4fa532c1b68e8ec5d331c02add9f6d6a1772f39ff0ee47c16/blob
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class ExperimentalWarning(Warning):
|
| 2 |
+
"""Used to manage warning messages for any experimental integrations."""
|
| 3 |
+
|
| 4 |
+
pass
|
shared/package-files/32/3208279bebd7d83b14c1360f25f93cd40048e904280d52b3b8549b05f0e3ae71/blob
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <c10/util/Optional.h>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/_fused_sgd_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::_fused_sgd_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] momentum_buffer_list, *, float weight_decay, float momentum, float lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
|
| 26 |
+
inline void _fused_sgd_(at::TensorList self, at::TensorList grads, at::TensorList momentum_buffer_list, double weight_decay, double momentum, double lr, double dampening, bool nesterov, bool maximize, bool is_first_step, const c10::optional<at::Tensor> & grad_scale={}, const c10::optional<at::Tensor> & found_inf={}) {
|
| 27 |
+
return at::_ops::_fused_sgd_::call(self, grads, momentum_buffer_list, weight_decay, momentum, lr, dampening, nesterov, maximize, is_first_step, grad_scale, found_inf);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// aten::_fused_sgd_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] momentum_buffer_list, *, float weight_decay, float momentum, Tensor lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
|
| 31 |
+
inline void _fused_sgd_(at::TensorList self, at::TensorList grads, at::TensorList momentum_buffer_list, double weight_decay, double momentum, const at::Tensor & lr, double dampening, bool nesterov, bool maximize, bool is_first_step, const c10::optional<at::Tensor> & grad_scale={}, const c10::optional<at::Tensor> & found_inf={}) {
|
| 32 |
+
return at::_ops::_fused_sgd__tensor_lr::call(self, grads, momentum_buffer_list, weight_decay, momentum, lr, dampening, nesterov, maximize, is_first_step, grad_scale, found_inf);
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
// aten::_fused_sgd.out(Tensor[] self, Tensor(b!)[] grads, Tensor(c!)[] momentum_buffer_list, *, float weight_decay, float momentum, float lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None, Tensor(a!)[] out) -> ()
|
| 36 |
+
inline void _fused_sgd_out(at::TensorList out, at::TensorList self, at::TensorList grads, at::TensorList momentum_buffer_list, double weight_decay, double momentum, double lr, double dampening, bool nesterov, bool maximize, bool is_first_step, const c10::optional<at::Tensor> & grad_scale={}, const c10::optional<at::Tensor> & found_inf={}) {
|
| 37 |
+
return at::_ops::_fused_sgd_out::call(self, grads, momentum_buffer_list, weight_decay, momentum, lr, dampening, nesterov, maximize, is_first_step, grad_scale, found_inf, out);
|
| 38 |
+
}
|
| 39 |
+
// aten::_fused_sgd.out(Tensor[] self, Tensor(b!)[] grads, Tensor(c!)[] momentum_buffer_list, *, float weight_decay, float momentum, float lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None, Tensor(a!)[] out) -> ()
|
| 40 |
+
inline void _fused_sgd_outf(at::TensorList self, at::TensorList grads, at::TensorList momentum_buffer_list, double weight_decay, double momentum, double lr, double dampening, bool nesterov, bool maximize, bool is_first_step, const c10::optional<at::Tensor> & grad_scale, const c10::optional<at::Tensor> & found_inf, at::TensorList out) {
|
| 41 |
+
return at::_ops::_fused_sgd_out::call(self, grads, momentum_buffer_list, weight_decay, momentum, lr, dampening, nesterov, maximize, is_first_step, grad_scale, found_inf, out);
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
// aten::_fused_sgd(Tensor[] self, Tensor[] grads, Tensor[] momentum_buffer_list, *, float weight_decay, float momentum, float lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None) -> (Tensor[] self_out, Tensor[] grads_out, Tensor[] momentum_buffer_list_out)
|
| 45 |
+
inline ::std::tuple<::std::vector<at::Tensor>,::std::vector<at::Tensor>,::std::vector<at::Tensor>> _fused_sgd(at::TensorList self, at::TensorList grads, at::TensorList momentum_buffer_list, double weight_decay, double momentum, double lr, double dampening, bool nesterov, bool maximize, bool is_first_step, const c10::optional<at::Tensor> & grad_scale={}, const c10::optional<at::Tensor> & found_inf={}) {
|
| 46 |
+
return at::_ops::_fused_sgd::call(self, grads, momentum_buffer_list, weight_decay, momentum, lr, dampening, nesterov, maximize, is_first_step, grad_scale, found_inf);
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
// aten::_fused_sgd.tensor_lr_out(Tensor[] self, Tensor(b!)[] grads, Tensor(c!)[] momentum_buffer_list, *, float weight_decay, float momentum, Tensor lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None, Tensor(a!)[] out) -> ()
|
| 50 |
+
inline void _fused_sgd_out(at::TensorList out, at::TensorList self, at::TensorList grads, at::TensorList momentum_buffer_list, double weight_decay, double momentum, const at::Tensor & lr, double dampening, bool nesterov, bool maximize, bool is_first_step, const c10::optional<at::Tensor> & grad_scale={}, const c10::optional<at::Tensor> & found_inf={}) {
|
| 51 |
+
return at::_ops::_fused_sgd_tensor_lr_out::call(self, grads, momentum_buffer_list, weight_decay, momentum, lr, dampening, nesterov, maximize, is_first_step, grad_scale, found_inf, out);
|
| 52 |
+
}
|
| 53 |
+
// aten::_fused_sgd.tensor_lr_out(Tensor[] self, Tensor(b!)[] grads, Tensor(c!)[] momentum_buffer_list, *, float weight_decay, float momentum, Tensor lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None, Tensor(a!)[] out) -> ()
|
| 54 |
+
inline void _fused_sgd_outf(at::TensorList self, at::TensorList grads, at::TensorList momentum_buffer_list, double weight_decay, double momentum, const at::Tensor & lr, double dampening, bool nesterov, bool maximize, bool is_first_step, const c10::optional<at::Tensor> & grad_scale, const c10::optional<at::Tensor> & found_inf, at::TensorList out) {
|
| 55 |
+
return at::_ops::_fused_sgd_tensor_lr_out::call(self, grads, momentum_buffer_list, weight_decay, momentum, lr, dampening, nesterov, maximize, is_first_step, grad_scale, found_inf, out);
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
// aten::_fused_sgd.tensor_lr(Tensor[] self, Tensor[] grads, Tensor[] momentum_buffer_list, *, float weight_decay, float momentum, Tensor lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None) -> (Tensor[] self_out, Tensor[] grads_out, Tensor[] momentum_buffer_list_out)
|
| 59 |
+
inline ::std::tuple<::std::vector<at::Tensor>,::std::vector<at::Tensor>,::std::vector<at::Tensor>> _fused_sgd(at::TensorList self, at::TensorList grads, at::TensorList momentum_buffer_list, double weight_decay, double momentum, const at::Tensor & lr, double dampening, bool nesterov, bool maximize, bool is_first_step, const c10::optional<at::Tensor> & grad_scale={}, const c10::optional<at::Tensor> & found_inf={}) {
|
| 60 |
+
return at::_ops::_fused_sgd_tensor_lr::call(self, grads, momentum_buffer_list, weight_decay, momentum, lr, dampening, nesterov, maximize, is_first_step, grad_scale, found_inf);
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
}
|
shared/package-files/32/3209ff37311d53ba8ccea59c7e6c7fe0579a3eb10c185ff6b115b15e859aa149/blob
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
shared/package-files/32/320b3d7ae0eb563e60d7a62387de282960b1ab1a94b376935691bb8cc4967ed0/blob
ADDED
|
@@ -0,0 +1,1194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#############################################################################
|
| 2 |
+
# This code draws from the Python Optimal Transport version of the
|
| 3 |
+
# network simplex algorithm, which in turn was adapted from the LEMON
|
| 4 |
+
# library. The copyrights/comment blocks for those are preserved below.
|
| 5 |
+
# The Python/Numba implementation was adapted by Leland McInnes (2020).
|
| 6 |
+
#
|
| 7 |
+
# * This file has been adapted by Nicolas Bonneel (2013),
|
| 8 |
+
# * from network_simplex.h from LEMON, a generic C++ optimization library,
|
| 9 |
+
# * to implement a lightweight network simplex for mass transport, more
|
| 10 |
+
# * memory efficient that the original file. A previous version of this file
|
| 11 |
+
# * is used as part of the Displacement Interpolation project,
|
| 12 |
+
# * Web: http://www.cs.ubc.ca/labs/imager/tr/2011/DisplacementInterpolation/
|
| 13 |
+
# *
|
| 14 |
+
# *
|
| 15 |
+
# **** Original file Copyright Notice :
|
| 16 |
+
# *
|
| 17 |
+
# * Copyright (C) 2003-2010
|
| 18 |
+
# * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
|
| 19 |
+
# * (Egervary Research Group on Combinatorial Optimization, EGRES).
|
| 20 |
+
# *
|
| 21 |
+
# * Permission to use, modify and distribute this software is granted
|
| 22 |
+
# * provided that this copyright notice appears in all copies. For
|
| 23 |
+
# * precise terms see the accompanying LICENSE file.
|
| 24 |
+
# *
|
| 25 |
+
# * This software is provided "AS IS" with no warranty of any kind,
|
| 26 |
+
# * express or implied, and with no claim as to its suitability for any
|
| 27 |
+
# * purpose.
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import numba
|
| 31 |
+
from collections import namedtuple
|
| 32 |
+
from enum import Enum, IntEnum
|
| 33 |
+
|
| 34 |
+
_mock_identity = np.eye(2, dtype=np.float32)
|
| 35 |
+
_mock_ones = np.ones(2, dtype=np.float32)
|
| 36 |
+
_dummy_cost = np.zeros((2, 2), dtype=np.float64)
|
| 37 |
+
|
| 38 |
+
# Accuracy tolerance and net supply tolerance
|
| 39 |
+
EPSILON = 2.2204460492503131e-15
|
| 40 |
+
NET_SUPPLY_ERROR_TOLERANCE = 1e-8
|
| 41 |
+
|
| 42 |
+
## Defaults to double for everythig in POT
|
| 43 |
+
INFINITY = np.finfo(np.float64).max
|
| 44 |
+
MAX = np.finfo(np.float64).max
|
| 45 |
+
|
| 46 |
+
dummy_cost = np.zeros((2, 2), dtype=np.float64)
|
| 47 |
+
|
| 48 |
+
# Invalid Arc num
|
| 49 |
+
INVALID = -1
|
| 50 |
+
|
| 51 |
+
# Problem Status
|
| 52 |
+
class ProblemStatus(Enum):
|
| 53 |
+
OPTIMAL = 0
|
| 54 |
+
MAX_ITER_REACHED = 1
|
| 55 |
+
UNBOUNDED = 2
|
| 56 |
+
INFEASIBLE = 3
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# Arc States
|
| 60 |
+
class ArcState(IntEnum):
|
| 61 |
+
STATE_UPPER = -1
|
| 62 |
+
STATE_TREE = 0
|
| 63 |
+
STATE_LOWER = 1
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
SpanningTree = namedtuple(
|
| 67 |
+
"SpanningTree",
|
| 68 |
+
[
|
| 69 |
+
"parent", # int array
|
| 70 |
+
"pred", # int array
|
| 71 |
+
"thread", # int array
|
| 72 |
+
"rev_thread", # int array
|
| 73 |
+
"succ_num", # int array
|
| 74 |
+
"last_succ", # int array
|
| 75 |
+
"forward", # bool array
|
| 76 |
+
"state", # state array
|
| 77 |
+
"root", # int
|
| 78 |
+
],
|
| 79 |
+
)
|
| 80 |
+
DiGraph = namedtuple(
|
| 81 |
+
"DiGraph",
|
| 82 |
+
[
|
| 83 |
+
"n_nodes", # int
|
| 84 |
+
"n_arcs", # int
|
| 85 |
+
"n", # int
|
| 86 |
+
"m", # int
|
| 87 |
+
"use_arc_mixing", # bool
|
| 88 |
+
"num_total_big_subsequence_numbers", # int
|
| 89 |
+
"subsequence_length", # int
|
| 90 |
+
"num_big_subsequences", # int
|
| 91 |
+
"mixing_coeff",
|
| 92 |
+
],
|
| 93 |
+
)
|
| 94 |
+
NodeArcData = namedtuple(
|
| 95 |
+
"NodeArcData",
|
| 96 |
+
[
|
| 97 |
+
"cost", # double array
|
| 98 |
+
"supply", # double array
|
| 99 |
+
"flow", # double array
|
| 100 |
+
"pi", # double array
|
| 101 |
+
"source", # unsigned int array
|
| 102 |
+
"target", # unsigned int array
|
| 103 |
+
],
|
| 104 |
+
)
|
| 105 |
+
LeavingArcData = namedtuple(
|
| 106 |
+
"LeavingArcData", ["u_in", "u_out", "v_in", "delta", "change"]
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# Just reproduce a simpler version of numpy isclose (not numba supported yet)
|
| 110 |
+
@numba.njit()
|
| 111 |
+
def isclose(a, b, rtol=1.0e-5, atol=EPSILON):
|
| 112 |
+
diff = np.abs(a - b)
|
| 113 |
+
return diff <= (atol + rtol * np.abs(b))
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# locals: c, min, e, cnt, a
|
| 117 |
+
# modifies _in_arc, _next_arc,
|
| 118 |
+
@numba.njit(locals={"a": numba.uint32, "e": numba.uint32})
|
| 119 |
+
def find_entering_arc(
|
| 120 |
+
pivot_block_size,
|
| 121 |
+
pivot_next_arc,
|
| 122 |
+
search_arc_num,
|
| 123 |
+
state_vector,
|
| 124 |
+
node_arc_data,
|
| 125 |
+
in_arc,
|
| 126 |
+
):
|
| 127 |
+
min = 0
|
| 128 |
+
cnt = pivot_block_size
|
| 129 |
+
|
| 130 |
+
# Pull from tuple for quick reference
|
| 131 |
+
cost = node_arc_data.cost
|
| 132 |
+
pi = node_arc_data.pi
|
| 133 |
+
source = node_arc_data.source
|
| 134 |
+
target = node_arc_data.target
|
| 135 |
+
|
| 136 |
+
for e in range(pivot_next_arc, search_arc_num):
|
| 137 |
+
c = state_vector[e] * (cost[e] + pi[source[e]] - pi[target[e]])
|
| 138 |
+
if c < min:
|
| 139 |
+
min = c
|
| 140 |
+
in_arc = e
|
| 141 |
+
|
| 142 |
+
cnt -= 1
|
| 143 |
+
if cnt == 0:
|
| 144 |
+
if np.fabs(pi[source[in_arc]]) > np.fabs(pi[target[in_arc]]):
|
| 145 |
+
a = np.fabs(pi[source[in_arc]])
|
| 146 |
+
else:
|
| 147 |
+
a = np.fabs(pi[target[in_arc]])
|
| 148 |
+
|
| 149 |
+
if a <= np.fabs(cost[in_arc]):
|
| 150 |
+
a = np.fabs(cost[in_arc])
|
| 151 |
+
|
| 152 |
+
if min < -(EPSILON * a):
|
| 153 |
+
pivot_next_arc = e
|
| 154 |
+
return in_arc, pivot_next_arc
|
| 155 |
+
else:
|
| 156 |
+
cnt = pivot_block_size
|
| 157 |
+
|
| 158 |
+
for e in range(pivot_next_arc):
|
| 159 |
+
c = state_vector[e] * (cost[e] + pi[source[e]] - pi[target[e]])
|
| 160 |
+
if c < min:
|
| 161 |
+
min = c
|
| 162 |
+
in_arc = e
|
| 163 |
+
|
| 164 |
+
cnt -= 1
|
| 165 |
+
if cnt == 0:
|
| 166 |
+
if np.fabs(pi[source[in_arc]]) > np.fabs(pi[target[in_arc]]):
|
| 167 |
+
a = np.fabs(pi[source[in_arc]])
|
| 168 |
+
else:
|
| 169 |
+
a = np.fabs(pi[target[in_arc]])
|
| 170 |
+
|
| 171 |
+
if a <= np.fabs(cost[in_arc]):
|
| 172 |
+
a = np.fabs(cost[in_arc])
|
| 173 |
+
|
| 174 |
+
if min < -(EPSILON * a):
|
| 175 |
+
pivot_next_arc = e
|
| 176 |
+
return in_arc, pivot_next_arc
|
| 177 |
+
else:
|
| 178 |
+
cnt = pivot_block_size
|
| 179 |
+
|
| 180 |
+
# assert(pivot_block.next_arc[0] == 0 or e == pivot_block.next_arc[0] - 1)
|
| 181 |
+
|
| 182 |
+
if np.fabs(pi[source[in_arc]]) > np.fabs(pi[target[in_arc]]):
|
| 183 |
+
a = np.fabs(pi[source[in_arc]])
|
| 184 |
+
else:
|
| 185 |
+
a = np.fabs(pi[target[in_arc]])
|
| 186 |
+
|
| 187 |
+
if a <= np.fabs(cost[in_arc]):
|
| 188 |
+
a = np.fabs(cost[in_arc])
|
| 189 |
+
|
| 190 |
+
if min >= -(EPSILON * a):
|
| 191 |
+
return -1, 0
|
| 192 |
+
|
| 193 |
+
return in_arc, pivot_next_arc
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
# Find the join node
|
| 197 |
+
# Operates with graph (_source, _target) and MST (_succ_num, _parent, in_arc) data
|
| 198 |
+
# locals: u, v
|
| 199 |
+
# modifies: join
|
| 200 |
+
@numba.njit(locals={"u": numba.types.uint16, "v": numba.types.uint16})
|
| 201 |
+
def find_join_node(source, target, succ_num, parent, in_arc):
|
| 202 |
+
u = source[in_arc]
|
| 203 |
+
v = target[in_arc]
|
| 204 |
+
while u != v:
|
| 205 |
+
if succ_num[u] < succ_num[v]:
|
| 206 |
+
u = parent[u]
|
| 207 |
+
else:
|
| 208 |
+
v = parent[v]
|
| 209 |
+
|
| 210 |
+
join = u
|
| 211 |
+
|
| 212 |
+
return join
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# Find the leaving arc of the cycle and returns true if the
|
| 216 |
+
# leaving arc is not the same as the entering arc
|
| 217 |
+
# locals: first, second, result, d, e
|
| 218 |
+
# modifies: u_in, v_in, u_out, delta
|
| 219 |
+
@numba.njit(
|
| 220 |
+
locals={
|
| 221 |
+
"u": numba.uint16,
|
| 222 |
+
"u_in": numba.uint16,
|
| 223 |
+
"u_out": numba.uint16,
|
| 224 |
+
"v_in": numba.uint16,
|
| 225 |
+
"first": numba.uint16,
|
| 226 |
+
"second": numba.uint16,
|
| 227 |
+
"result": numba.uint8,
|
| 228 |
+
"in_arc": numba.uint32,
|
| 229 |
+
}
|
| 230 |
+
)
|
| 231 |
+
def find_leaving_arc(join, in_arc, node_arc_data, spanning_tree):
|
| 232 |
+
source = node_arc_data.source
|
| 233 |
+
target = node_arc_data.target
|
| 234 |
+
flow = node_arc_data.flow
|
| 235 |
+
|
| 236 |
+
state = spanning_tree.state
|
| 237 |
+
forward = spanning_tree.forward
|
| 238 |
+
pred = spanning_tree.pred
|
| 239 |
+
parent = spanning_tree.parent
|
| 240 |
+
|
| 241 |
+
u_out = -1 # May not be set, but we need to return something?
|
| 242 |
+
|
| 243 |
+
# Initialize first and second nodes according to the direction
|
| 244 |
+
# of the cycle
|
| 245 |
+
if state[in_arc] == ArcState.STATE_LOWER:
|
| 246 |
+
first = source[in_arc]
|
| 247 |
+
second = target[in_arc]
|
| 248 |
+
else:
|
| 249 |
+
first = target[in_arc]
|
| 250 |
+
second = source[in_arc]
|
| 251 |
+
|
| 252 |
+
delta = INFINITY
|
| 253 |
+
result = 0
|
| 254 |
+
|
| 255 |
+
# Search the cycle along the path form the first node to the root
|
| 256 |
+
u = first
|
| 257 |
+
while u != join:
|
| 258 |
+
e = pred[u]
|
| 259 |
+
if forward[u]:
|
| 260 |
+
d = flow[e]
|
| 261 |
+
else:
|
| 262 |
+
d = INFINITY
|
| 263 |
+
|
| 264 |
+
if d < delta:
|
| 265 |
+
delta = d
|
| 266 |
+
u_out = u
|
| 267 |
+
result = 1
|
| 268 |
+
|
| 269 |
+
u = parent[u]
|
| 270 |
+
|
| 271 |
+
# Search the cycle along the path form the second node to the root
|
| 272 |
+
u = second
|
| 273 |
+
while u != join:
|
| 274 |
+
e = pred[u]
|
| 275 |
+
if forward[u]:
|
| 276 |
+
d = INFINITY
|
| 277 |
+
else:
|
| 278 |
+
d = flow[e]
|
| 279 |
+
|
| 280 |
+
if d <= delta:
|
| 281 |
+
delta = d
|
| 282 |
+
u_out = u
|
| 283 |
+
result = 2
|
| 284 |
+
|
| 285 |
+
u = parent[u]
|
| 286 |
+
|
| 287 |
+
if result == 1:
|
| 288 |
+
u_in = first
|
| 289 |
+
v_in = second
|
| 290 |
+
else:
|
| 291 |
+
u_in = second
|
| 292 |
+
v_in = first
|
| 293 |
+
|
| 294 |
+
return LeavingArcData(u_in, u_out, v_in, delta, result != 0)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
# Change _flow and _state vectors
|
| 298 |
+
# locals: val, u
|
| 299 |
+
# modifies: _state, _flow
|
| 300 |
+
@numba.njit(locals={"u": numba.uint16, "in_arc": numba.uint32, "val": numba.float64})
|
| 301 |
+
def update_flow(join, leaving_arc_data, node_arc_data, spanning_tree, in_arc):
|
| 302 |
+
source = node_arc_data.source
|
| 303 |
+
target = node_arc_data.target
|
| 304 |
+
flow = node_arc_data.flow
|
| 305 |
+
|
| 306 |
+
state = spanning_tree.state
|
| 307 |
+
pred = spanning_tree.pred
|
| 308 |
+
parent = spanning_tree.parent
|
| 309 |
+
forward = spanning_tree.forward
|
| 310 |
+
|
| 311 |
+
# Augment along the cycle
|
| 312 |
+
if leaving_arc_data.delta > 0:
|
| 313 |
+
val = state[in_arc] * leaving_arc_data.delta
|
| 314 |
+
flow[in_arc] += val
|
| 315 |
+
u = source[in_arc]
|
| 316 |
+
while u != join:
|
| 317 |
+
if forward[u]:
|
| 318 |
+
flow[pred[u]] -= val
|
| 319 |
+
else:
|
| 320 |
+
flow[pred[u]] += val
|
| 321 |
+
|
| 322 |
+
u = parent[u]
|
| 323 |
+
|
| 324 |
+
u = target[in_arc]
|
| 325 |
+
while u != join:
|
| 326 |
+
if forward[u]:
|
| 327 |
+
flow[pred[u]] += val
|
| 328 |
+
else:
|
| 329 |
+
flow[pred[u]] -= val
|
| 330 |
+
|
| 331 |
+
u = parent[u]
|
| 332 |
+
|
| 333 |
+
# Update the state of the entering and leaving arcs
|
| 334 |
+
if leaving_arc_data.change:
|
| 335 |
+
state[in_arc] = ArcState.STATE_TREE
|
| 336 |
+
if flow[pred[leaving_arc_data.u_out]] == 0:
|
| 337 |
+
state[pred[leaving_arc_data.u_out]] = ArcState.STATE_LOWER
|
| 338 |
+
else:
|
| 339 |
+
state[pred[leaving_arc_data.u_out]] = ArcState.STATE_UPPER
|
| 340 |
+
else:
|
| 341 |
+
state[in_arc] = -state[in_arc]
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
# Update the tree structure
|
| 345 |
+
# locals: u, w, old_rev_thread, old_succ_num, old_last_succ, tmp_sc, tmp_ls
|
| 346 |
+
# more locals: up_limit_in, up_limit_out, _dirty_revs
|
| 347 |
+
# modifies: v_out, _thread, _rev_thread, _parent, _last_succ,
|
| 348 |
+
# modifies: _pred, _forward, _succ_num
|
| 349 |
+
@numba.njit(
|
| 350 |
+
locals={
|
| 351 |
+
"u": numba.int32,
|
| 352 |
+
"w": numba.int32,
|
| 353 |
+
"u_in": numba.uint16,
|
| 354 |
+
"u_out": numba.uint16,
|
| 355 |
+
"v_in": numba.uint16,
|
| 356 |
+
"right": numba.uint16,
|
| 357 |
+
"stem": numba.uint16,
|
| 358 |
+
"new_stem": numba.uint16,
|
| 359 |
+
"par_stem": numba.uint16,
|
| 360 |
+
"in_arc": numba.uint32,
|
| 361 |
+
}
|
| 362 |
+
)
|
| 363 |
+
def update_spanning_tree(spanning_tree, leaving_arc_data, join, in_arc, source):
|
| 364 |
+
|
| 365 |
+
parent = spanning_tree.parent
|
| 366 |
+
thread = spanning_tree.thread
|
| 367 |
+
rev_thread = spanning_tree.rev_thread
|
| 368 |
+
succ_num = spanning_tree.succ_num
|
| 369 |
+
last_succ = spanning_tree.last_succ
|
| 370 |
+
forward = spanning_tree.forward
|
| 371 |
+
pred = spanning_tree.pred
|
| 372 |
+
|
| 373 |
+
u_out = leaving_arc_data.u_out
|
| 374 |
+
u_in = leaving_arc_data.u_in
|
| 375 |
+
v_in = leaving_arc_data.v_in
|
| 376 |
+
|
| 377 |
+
old_rev_thread = rev_thread[u_out]
|
| 378 |
+
old_succ_num = succ_num[u_out]
|
| 379 |
+
old_last_succ = last_succ[u_out]
|
| 380 |
+
v_out = parent[u_out]
|
| 381 |
+
|
| 382 |
+
u = last_succ[u_in] # the last successor of u_in
|
| 383 |
+
right = thread[u] # the node after it
|
| 384 |
+
|
| 385 |
+
# Handle the case when old_rev_thread equals to v_in
|
| 386 |
+
# (it also means that join and v_out coincide)
|
| 387 |
+
if old_rev_thread == v_in:
|
| 388 |
+
last = thread[last_succ[u_out]]
|
| 389 |
+
else:
|
| 390 |
+
last = thread[v_in]
|
| 391 |
+
|
| 392 |
+
# Update _thread and _parent along the stem nodes (i.e. the nodes
|
| 393 |
+
# between u_in and u_out, whose parent have to be changed)
|
| 394 |
+
thread[v_in] = stem = u_in
|
| 395 |
+
dirty_revs = []
|
| 396 |
+
dirty_revs.append(v_in)
|
| 397 |
+
par_stem = v_in
|
| 398 |
+
while stem != u_out:
|
| 399 |
+
# Insert the next stem node into the thread list
|
| 400 |
+
new_stem = parent[stem]
|
| 401 |
+
thread[u] = new_stem
|
| 402 |
+
dirty_revs.append(u)
|
| 403 |
+
|
| 404 |
+
# Remove the subtree of stem from the thread list
|
| 405 |
+
w = rev_thread[stem]
|
| 406 |
+
thread[w] = right
|
| 407 |
+
rev_thread[right] = w
|
| 408 |
+
|
| 409 |
+
# Change the parent node and shift stem nodes
|
| 410 |
+
parent[stem] = par_stem
|
| 411 |
+
par_stem = stem
|
| 412 |
+
stem = new_stem
|
| 413 |
+
|
| 414 |
+
# Update u and right
|
| 415 |
+
if last_succ[stem] == last_succ[par_stem]:
|
| 416 |
+
u = rev_thread[par_stem]
|
| 417 |
+
else:
|
| 418 |
+
u = last_succ[stem]
|
| 419 |
+
|
| 420 |
+
right = thread[u]
|
| 421 |
+
|
| 422 |
+
parent[u_out] = par_stem
|
| 423 |
+
thread[u] = last
|
| 424 |
+
rev_thread[last] = u
|
| 425 |
+
last_succ[u_out] = u
|
| 426 |
+
|
| 427 |
+
# Remove the subtree of u_out from the thread list except for
|
| 428 |
+
# the case when old_rev_thread equals to v_in
|
| 429 |
+
# (it also means that join and v_out coincide)
|
| 430 |
+
if old_rev_thread != v_in:
|
| 431 |
+
thread[old_rev_thread] = right
|
| 432 |
+
rev_thread[right] = old_rev_thread
|
| 433 |
+
|
| 434 |
+
# Update _rev_thread using the new _thread values
|
| 435 |
+
for i in range(len(dirty_revs)):
|
| 436 |
+
u = dirty_revs[i]
|
| 437 |
+
rev_thread[thread[u]] = u
|
| 438 |
+
|
| 439 |
+
# Update _pred, _forward, _last_succ and _succ_num for the
|
| 440 |
+
# stem nodes from u_out to u_in
|
| 441 |
+
tmp_sc = 0
|
| 442 |
+
tmp_ls = last_succ[u_out]
|
| 443 |
+
u = u_out
|
| 444 |
+
while u != u_in:
|
| 445 |
+
w = parent[u]
|
| 446 |
+
pred[u] = pred[w]
|
| 447 |
+
forward[u] = not forward[w]
|
| 448 |
+
tmp_sc += succ_num[u] - succ_num[w]
|
| 449 |
+
succ_num[u] = tmp_sc
|
| 450 |
+
last_succ[w] = tmp_ls
|
| 451 |
+
u = w
|
| 452 |
+
|
| 453 |
+
pred[u_in] = in_arc
|
| 454 |
+
forward[u_in] = u_in == source[in_arc]
|
| 455 |
+
succ_num[u_in] = old_succ_num
|
| 456 |
+
|
| 457 |
+
# Set limits for updating _last_succ form v_in and v_out
|
| 458 |
+
# towards the root
|
| 459 |
+
up_limit_in = -1
|
| 460 |
+
up_limit_out = -1
|
| 461 |
+
if last_succ[join] == v_in:
|
| 462 |
+
up_limit_out = join
|
| 463 |
+
else:
|
| 464 |
+
up_limit_in = join
|
| 465 |
+
|
| 466 |
+
# Update _last_succ from v_in towards the root
|
| 467 |
+
u = v_in
|
| 468 |
+
while u != up_limit_in and last_succ[u] == v_in:
|
| 469 |
+
last_succ[u] = last_succ[u_out]
|
| 470 |
+
u = parent[u]
|
| 471 |
+
|
| 472 |
+
# Update _last_succ from v_out towards the root
|
| 473 |
+
if join != old_rev_thread and v_in != old_rev_thread:
|
| 474 |
+
u = v_out
|
| 475 |
+
while u != up_limit_out and last_succ[u] == old_last_succ:
|
| 476 |
+
last_succ[u] = old_rev_thread
|
| 477 |
+
u = parent[u]
|
| 478 |
+
|
| 479 |
+
else:
|
| 480 |
+
u = v_out
|
| 481 |
+
while u != up_limit_out and last_succ[u] == old_last_succ:
|
| 482 |
+
last_succ[u] = last_succ[u_out]
|
| 483 |
+
u = parent[u]
|
| 484 |
+
|
| 485 |
+
# Update _succ_num from v_in to join
|
| 486 |
+
u = v_in
|
| 487 |
+
while u != join:
|
| 488 |
+
succ_num[u] += old_succ_num
|
| 489 |
+
u = parent[u]
|
| 490 |
+
|
| 491 |
+
# Update _succ_num from v_out to join
|
| 492 |
+
u = v_out
|
| 493 |
+
while u != join:
|
| 494 |
+
succ_num[u] -= old_succ_num
|
| 495 |
+
u = parent[u]
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
# Update potentials
|
| 499 |
+
# locals: sigma, end
|
| 500 |
+
# modifies: _pi
|
| 501 |
+
@numba.njit(
|
| 502 |
+
fastmath=True,
|
| 503 |
+
inline="always",
|
| 504 |
+
locals={"u": numba.uint16, "u_in": numba.uint16, "v_in": numba.uint16},
|
| 505 |
+
)
|
| 506 |
+
def update_potential(leaving_arc_data, pi, cost, spanning_tree):
|
| 507 |
+
|
| 508 |
+
thread = spanning_tree.thread
|
| 509 |
+
pred = spanning_tree.pred
|
| 510 |
+
forward = spanning_tree.forward
|
| 511 |
+
last_succ = spanning_tree.last_succ
|
| 512 |
+
|
| 513 |
+
u_in = leaving_arc_data.u_in
|
| 514 |
+
v_in = leaving_arc_data.v_in
|
| 515 |
+
|
| 516 |
+
if forward[u_in]:
|
| 517 |
+
sigma = pi[v_in] - pi[u_in] - cost[pred[u_in]]
|
| 518 |
+
else:
|
| 519 |
+
sigma = pi[v_in] - pi[u_in] + cost[pred[u_in]]
|
| 520 |
+
|
| 521 |
+
# Update potentials in the subtree, which has been moved
|
| 522 |
+
end = thread[last_succ[u_in]]
|
| 523 |
+
u = u_in
|
| 524 |
+
while u != end:
|
| 525 |
+
pi[u] += sigma
|
| 526 |
+
u = thread[u]
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
# If we have mixed arcs (for better random access)
|
| 530 |
+
# we need a more complicated function to get the ID of a given arc
|
| 531 |
+
@numba.njit()
|
| 532 |
+
def arc_id(arc, graph):
|
| 533 |
+
k = graph.n_arcs - arc - 1
|
| 534 |
+
if graph.use_arc_mixing:
|
| 535 |
+
smallv = (k > graph.num_total_big_subsequence_numbers) & 1
|
| 536 |
+
k -= graph.num_total_big_subsequence_numbers * smallv
|
| 537 |
+
subsequence_length2 = graph.subsequence_length - smallv
|
| 538 |
+
subsequence_num = (
|
| 539 |
+
k // subsequence_length2
|
| 540 |
+
) + graph.num_big_subsequences * smallv
|
| 541 |
+
subsequence_offset = (k % subsequence_length2) * graph.mixing_coeff
|
| 542 |
+
|
| 543 |
+
return subsequence_offset + subsequence_num
|
| 544 |
+
else:
|
| 545 |
+
return k
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
# Heuristic initial pivots
|
| 549 |
+
# locals: curr, total, supply_nodes, demand_nodes, u
|
| 550 |
+
# modifies:
|
| 551 |
+
@numba.njit(locals={"i": numba.uint16})
|
| 552 |
+
def construct_initial_pivots(graph, node_arc_data, spanning_tree):
|
| 553 |
+
|
| 554 |
+
cost = node_arc_data.cost
|
| 555 |
+
pi = node_arc_data.pi
|
| 556 |
+
source = node_arc_data.source
|
| 557 |
+
target = node_arc_data.target
|
| 558 |
+
supply = node_arc_data.supply
|
| 559 |
+
|
| 560 |
+
n1 = graph.n
|
| 561 |
+
n2 = graph.m
|
| 562 |
+
n_nodes = graph.n_nodes
|
| 563 |
+
n_arcs = graph.n_arcs
|
| 564 |
+
|
| 565 |
+
state = spanning_tree.state
|
| 566 |
+
|
| 567 |
+
total = 0
|
| 568 |
+
supply_nodes = []
|
| 569 |
+
demand_nodes = []
|
| 570 |
+
|
| 571 |
+
for u in range(n_nodes):
|
| 572 |
+
curr = supply[n_nodes - u - 1] # _node_id(u)
|
| 573 |
+
if curr > 0:
|
| 574 |
+
total += curr
|
| 575 |
+
supply_nodes.append(u)
|
| 576 |
+
elif curr < 0:
|
| 577 |
+
demand_nodes.append(u)
|
| 578 |
+
|
| 579 |
+
arc_vector = []
|
| 580 |
+
if len(supply_nodes) == 1 and len(demand_nodes) == 1:
|
| 581 |
+
# Perform a reverse graph search from the sink to the source
|
| 582 |
+
reached = np.zeros(n_nodes, dtype=np.bool_)
|
| 583 |
+
s = supply_nodes[0]
|
| 584 |
+
t = demand_nodes[0]
|
| 585 |
+
stack = []
|
| 586 |
+
reached[t] = True
|
| 587 |
+
stack.append(t)
|
| 588 |
+
while len(stack) > 0:
|
| 589 |
+
u = stack[-1]
|
| 590 |
+
v = stack[-1]
|
| 591 |
+
stack.pop(-1)
|
| 592 |
+
if v == s:
|
| 593 |
+
break
|
| 594 |
+
|
| 595 |
+
first_arc = n_arcs + v - n_nodes if v >= n1 else -1
|
| 596 |
+
for a in range(first_arc, -1, -n2):
|
| 597 |
+
u = a // n2
|
| 598 |
+
if reached[u]:
|
| 599 |
+
continue
|
| 600 |
+
|
| 601 |
+
j = arc_id(a, graph)
|
| 602 |
+
if INFINITY >= total:
|
| 603 |
+
arc_vector.append(j)
|
| 604 |
+
reached[u] = True
|
| 605 |
+
stack.append(u)
|
| 606 |
+
|
| 607 |
+
else:
|
| 608 |
+
# Find the min. cost incomming arc for each demand node
|
| 609 |
+
for i in range(len(demand_nodes)):
|
| 610 |
+
v = demand_nodes[i]
|
| 611 |
+
c = MAX
|
| 612 |
+
min_cost = MAX
|
| 613 |
+
min_arc = INVALID
|
| 614 |
+
first_arc = n_arcs + v - n_nodes if v >= n1 else -1
|
| 615 |
+
for a in range(first_arc, -1, -n2):
|
| 616 |
+
c = cost[arc_id(a, graph)]
|
| 617 |
+
if c < min_cost:
|
| 618 |
+
min_cost = c
|
| 619 |
+
min_arc = a
|
| 620 |
+
|
| 621 |
+
if min_arc != INVALID:
|
| 622 |
+
arc_vector.append(arc_id(min_arc, graph))
|
| 623 |
+
|
| 624 |
+
# Perform heuristic initial pivots
|
| 625 |
+
in_arc = -1
|
| 626 |
+
for i in range(len(arc_vector)):
|
| 627 |
+
in_arc = arc_vector[i]
|
| 628 |
+
# Bad arcs
|
| 629 |
+
if (
|
| 630 |
+
state[in_arc] * (cost[in_arc] + pi[source[in_arc]] - pi[target[in_arc]])
|
| 631 |
+
>= 0
|
| 632 |
+
):
|
| 633 |
+
continue
|
| 634 |
+
|
| 635 |
+
join = find_join_node(
|
| 636 |
+
source, target, spanning_tree.succ_num, spanning_tree.parent, in_arc
|
| 637 |
+
)
|
| 638 |
+
leaving_arc_data = find_leaving_arc(join, in_arc, node_arc_data, spanning_tree)
|
| 639 |
+
if leaving_arc_data.delta >= MAX:
|
| 640 |
+
return False, in_arc
|
| 641 |
+
|
| 642 |
+
update_flow(join, leaving_arc_data, node_arc_data, spanning_tree, in_arc)
|
| 643 |
+
if leaving_arc_data.change:
|
| 644 |
+
update_spanning_tree(spanning_tree, leaving_arc_data, join, in_arc, source)
|
| 645 |
+
update_potential(leaving_arc_data, pi, cost, spanning_tree)
|
| 646 |
+
|
| 647 |
+
return True, in_arc
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
@numba.njit()
|
| 651 |
+
def allocate_graph_structures(n, m, use_arc_mixing=True):
|
| 652 |
+
|
| 653 |
+
# Size bipartite graph
|
| 654 |
+
n_nodes = n + m
|
| 655 |
+
n_arcs = n * m
|
| 656 |
+
|
| 657 |
+
# Resize vectors
|
| 658 |
+
all_node_num = n_nodes + 1
|
| 659 |
+
max_arc_num = n_arcs + 2 * n_nodes
|
| 660 |
+
root = n_nodes
|
| 661 |
+
|
| 662 |
+
source = np.zeros(max_arc_num, dtype=np.uint16)
|
| 663 |
+
target = np.zeros(max_arc_num, dtype=np.uint16)
|
| 664 |
+
cost = np.ones(max_arc_num, dtype=np.float64)
|
| 665 |
+
supply = np.zeros(all_node_num, dtype=np.float64)
|
| 666 |
+
flow = np.zeros(max_arc_num, dtype=np.float64)
|
| 667 |
+
pi = np.zeros(all_node_num, dtype=np.float64)
|
| 668 |
+
|
| 669 |
+
parent = np.zeros(all_node_num, dtype=np.int32)
|
| 670 |
+
pred = np.zeros(all_node_num, dtype=np.int32)
|
| 671 |
+
forward = np.zeros(all_node_num, dtype=np.bool_)
|
| 672 |
+
thread = np.zeros(all_node_num, dtype=np.int32)
|
| 673 |
+
rev_thread = np.zeros(all_node_num, dtype=np.int32)
|
| 674 |
+
succ_num = np.zeros(all_node_num, dtype=np.int32)
|
| 675 |
+
last_succ = np.zeros(all_node_num, dtype=np.int32)
|
| 676 |
+
state = np.zeros(max_arc_num, dtype=np.int8)
|
| 677 |
+
|
| 678 |
+
if use_arc_mixing:
|
| 679 |
+
# Store the arcs in a mixed order
|
| 680 |
+
k = max(np.int32(np.sqrt(n_arcs)), 10)
|
| 681 |
+
mixing_coeff = k
|
| 682 |
+
subsequence_length = (n_arcs // mixing_coeff) + 1
|
| 683 |
+
num_big_subsequences = n_arcs % mixing_coeff
|
| 684 |
+
num_total_big_subsequence_numbers = subsequence_length * num_big_subsequences
|
| 685 |
+
|
| 686 |
+
i = 0
|
| 687 |
+
j = 0
|
| 688 |
+
for a in range(n_arcs - 1, -1, -1):
|
| 689 |
+
source[i] = n_nodes - (a // m) - 1
|
| 690 |
+
target[i] = n_nodes - ((a % m) + n) - 1
|
| 691 |
+
i += k
|
| 692 |
+
if i >= n_arcs:
|
| 693 |
+
j += 1
|
| 694 |
+
i = j
|
| 695 |
+
|
| 696 |
+
else:
|
| 697 |
+
# dummy values
|
| 698 |
+
subsequence_length = 0
|
| 699 |
+
mixing_coeff = 0
|
| 700 |
+
num_big_subsequences = 0
|
| 701 |
+
num_total_big_subsequence_numbers = 0
|
| 702 |
+
# Store the arcs in the original order
|
| 703 |
+
i = 0
|
| 704 |
+
for a in range(n_arcs - 1, -1, -1):
|
| 705 |
+
source[i] = n_nodes - (a // m) - 1
|
| 706 |
+
target[i] = n_nodes - ((a % m) + n) - 1
|
| 707 |
+
i += 1
|
| 708 |
+
|
| 709 |
+
node_arc_data = NodeArcData(cost, supply, flow, pi, source, target)
|
| 710 |
+
spanning_tree = SpanningTree(
|
| 711 |
+
parent, pred, thread, rev_thread, succ_num, last_succ, forward, state, root
|
| 712 |
+
)
|
| 713 |
+
graph = DiGraph(
|
| 714 |
+
n_nodes,
|
| 715 |
+
n_arcs,
|
| 716 |
+
n,
|
| 717 |
+
m,
|
| 718 |
+
use_arc_mixing,
|
| 719 |
+
num_total_big_subsequence_numbers,
|
| 720 |
+
subsequence_length,
|
| 721 |
+
num_big_subsequences,
|
| 722 |
+
mixing_coeff,
|
| 723 |
+
)
|
| 724 |
+
|
| 725 |
+
return node_arc_data, spanning_tree, graph
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
@numba.njit(locals={"u": numba.uint16, "e": numba.uint32})
|
| 729 |
+
def initialize_graph_structures(graph, node_arc_data, spanning_tree):
|
| 730 |
+
|
| 731 |
+
n_nodes = graph.n_nodes
|
| 732 |
+
n_arcs = graph.n_arcs
|
| 733 |
+
|
| 734 |
+
# unpack arrays
|
| 735 |
+
cost = node_arc_data.cost
|
| 736 |
+
supply = node_arc_data.supply
|
| 737 |
+
flow = node_arc_data.flow
|
| 738 |
+
pi = node_arc_data.pi
|
| 739 |
+
source = node_arc_data.source
|
| 740 |
+
target = node_arc_data.target
|
| 741 |
+
|
| 742 |
+
parent = spanning_tree.parent
|
| 743 |
+
pred = spanning_tree.pred
|
| 744 |
+
thread = spanning_tree.thread
|
| 745 |
+
rev_thread = spanning_tree.rev_thread
|
| 746 |
+
succ_num = spanning_tree.succ_num
|
| 747 |
+
last_succ = spanning_tree.last_succ
|
| 748 |
+
forward = spanning_tree.forward
|
| 749 |
+
state = spanning_tree.state
|
| 750 |
+
|
| 751 |
+
if n_nodes == 0:
|
| 752 |
+
return False
|
| 753 |
+
|
| 754 |
+
# Check the sum of supply values
|
| 755 |
+
net_supply = 0
|
| 756 |
+
for i in range(n_nodes):
|
| 757 |
+
net_supply += supply[i]
|
| 758 |
+
|
| 759 |
+
if np.fabs(net_supply) > NET_SUPPLY_ERROR_TOLERANCE:
|
| 760 |
+
return False
|
| 761 |
+
|
| 762 |
+
# Fix using doubles
|
| 763 |
+
# Initialize artifical cost
|
| 764 |
+
artificial_cost = 0.0
|
| 765 |
+
for i in range(n_arcs):
|
| 766 |
+
if cost[i] > artificial_cost:
|
| 767 |
+
artificial_cost = cost[i]
|
| 768 |
+
# reset flow and state vectors
|
| 769 |
+
if flow[i] != 0:
|
| 770 |
+
flow[i] = 0
|
| 771 |
+
state[i] = ArcState.STATE_LOWER
|
| 772 |
+
|
| 773 |
+
artificial_cost = (artificial_cost + 1) * n_nodes
|
| 774 |
+
|
| 775 |
+
# Set data for the artificial root node
|
| 776 |
+
root = n_nodes
|
| 777 |
+
parent[root] = -1
|
| 778 |
+
pred[root] = -1
|
| 779 |
+
thread[root] = 0
|
| 780 |
+
rev_thread[0] = root
|
| 781 |
+
succ_num[root] = n_nodes + 1
|
| 782 |
+
last_succ[root] = root - 1
|
| 783 |
+
supply[root] = -net_supply
|
| 784 |
+
pi[root] = 0
|
| 785 |
+
|
| 786 |
+
# Add artificial arcs and initialize the spanning tree data structure
|
| 787 |
+
# EQ supply constraints
|
| 788 |
+
e = n_arcs
|
| 789 |
+
for u in range(n_nodes):
|
| 790 |
+
parent[u] = root
|
| 791 |
+
pred[u] = e
|
| 792 |
+
thread[u] = u + 1
|
| 793 |
+
rev_thread[u + 1] = u
|
| 794 |
+
succ_num[u] = 1
|
| 795 |
+
last_succ[u] = u
|
| 796 |
+
state[e] = ArcState.STATE_TREE
|
| 797 |
+
if supply[u] >= 0:
|
| 798 |
+
forward[u] = True
|
| 799 |
+
pi[u] = 0
|
| 800 |
+
source[e] = u
|
| 801 |
+
target[e] = root
|
| 802 |
+
flow[e] = supply[u]
|
| 803 |
+
cost[e] = 0
|
| 804 |
+
else:
|
| 805 |
+
forward[u] = False
|
| 806 |
+
pi[u] = artificial_cost
|
| 807 |
+
source[e] = root
|
| 808 |
+
target[e] = u
|
| 809 |
+
flow[e] = -supply[u]
|
| 810 |
+
cost[e] = artificial_cost
|
| 811 |
+
e += 1
|
| 812 |
+
|
| 813 |
+
return True
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
@numba.njit()
|
| 817 |
+
def initialize_supply(left_node_supply, right_node_supply, graph, supply):
|
| 818 |
+
for n in range(graph.n_nodes):
|
| 819 |
+
if n < graph.n:
|
| 820 |
+
supply[graph.n_nodes - n - 1] = left_node_supply[n]
|
| 821 |
+
else:
|
| 822 |
+
supply[graph.n_nodes - n - 1] = right_node_supply[n - graph.n]
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
@numba.njit(inline="always")
|
| 826 |
+
def set_cost(arc, cost_val, cost, graph):
|
| 827 |
+
cost[arc_id(arc, graph)] = cost_val
|
| 828 |
+
|
| 829 |
+
|
| 830 |
+
@numba.njit(locals={"i": numba.uint16, "j": numba.uint16})
|
| 831 |
+
def initialize_cost(cost_matrix, graph, cost):
|
| 832 |
+
for i in range(cost_matrix.shape[0]):
|
| 833 |
+
for j in range(cost_matrix.shape[1]):
|
| 834 |
+
set_cost(i * cost_matrix.shape[1] + j, cost_matrix[i, j], cost, graph)
|
| 835 |
+
|
| 836 |
+
|
| 837 |
+
@numba.njit(fastmath=True, locals={"i": numba.uint32})
|
| 838 |
+
def total_cost(flow, cost):
|
| 839 |
+
c = 0.0
|
| 840 |
+
for i in range(flow.shape[0]):
|
| 841 |
+
c += flow[i] * cost[i]
|
| 842 |
+
return c
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
@numba.njit(nogil=True)
|
| 846 |
+
def network_simplex_core(node_arc_data, spanning_tree, graph, max_iter):
|
| 847 |
+
|
| 848 |
+
# pivot_block = PivotBlock(
|
| 849 |
+
# max(np.int32(np.sqrt(graph.n_arcs)), 10),
|
| 850 |
+
# np.zeros(1, dtype=np.int32),
|
| 851 |
+
# graph.n_arcs,
|
| 852 |
+
# )
|
| 853 |
+
pivot_block_size = max(np.int32(np.sqrt(graph.n_arcs)), 10)
|
| 854 |
+
search_arc_num = graph.n_arcs
|
| 855 |
+
solution_status = ProblemStatus.OPTIMAL
|
| 856 |
+
|
| 857 |
+
# Perform heuristic initial pivots
|
| 858 |
+
bounded, in_arc = construct_initial_pivots(graph, node_arc_data, spanning_tree)
|
| 859 |
+
if not bounded:
|
| 860 |
+
return ProblemStatus.UNBOUNDED
|
| 861 |
+
|
| 862 |
+
iter_number = 0
|
| 863 |
+
# pivot.setDantzig(true);
|
| 864 |
+
# Execute the Network Simplex algorithm
|
| 865 |
+
in_arc, pivot_next_arc = find_entering_arc(
|
| 866 |
+
pivot_block_size, 0, search_arc_num, spanning_tree.state, node_arc_data, in_arc
|
| 867 |
+
)
|
| 868 |
+
while in_arc >= 0:
|
| 869 |
+
iter_number += 1
|
| 870 |
+
if max_iter > 0 and iter_number >= max_iter:
|
| 871 |
+
solution_status = ProblemStatus.MAX_ITER_REACHED
|
| 872 |
+
break
|
| 873 |
+
|
| 874 |
+
join = find_join_node(
|
| 875 |
+
node_arc_data.source,
|
| 876 |
+
node_arc_data.target,
|
| 877 |
+
spanning_tree.succ_num,
|
| 878 |
+
spanning_tree.parent,
|
| 879 |
+
in_arc,
|
| 880 |
+
)
|
| 881 |
+
leaving_arc_data = find_leaving_arc(join, in_arc, node_arc_data, spanning_tree)
|
| 882 |
+
if leaving_arc_data.delta >= MAX:
|
| 883 |
+
return ProblemStatus.UNBOUNDED
|
| 884 |
+
|
| 885 |
+
update_flow(join, leaving_arc_data, node_arc_data, spanning_tree, in_arc)
|
| 886 |
+
|
| 887 |
+
if leaving_arc_data.change:
|
| 888 |
+
update_spanning_tree(
|
| 889 |
+
spanning_tree, leaving_arc_data, join, in_arc, node_arc_data.source
|
| 890 |
+
)
|
| 891 |
+
update_potential(
|
| 892 |
+
leaving_arc_data, node_arc_data.pi, node_arc_data.cost, spanning_tree
|
| 893 |
+
)
|
| 894 |
+
|
| 895 |
+
in_arc, pivot_next_arc = find_entering_arc(
|
| 896 |
+
pivot_block_size,
|
| 897 |
+
pivot_next_arc,
|
| 898 |
+
search_arc_num,
|
| 899 |
+
spanning_tree.state,
|
| 900 |
+
node_arc_data,
|
| 901 |
+
in_arc,
|
| 902 |
+
)
|
| 903 |
+
|
| 904 |
+
flow = node_arc_data.flow
|
| 905 |
+
pi = node_arc_data.pi
|
| 906 |
+
|
| 907 |
+
# Check feasibility
|
| 908 |
+
if solution_status == ProblemStatus.OPTIMAL:
|
| 909 |
+
for e in range(graph.n_arcs, graph.n_arcs + graph.n_nodes):
|
| 910 |
+
if flow[e] != 0:
|
| 911 |
+
if np.abs(flow[e]) > EPSILON:
|
| 912 |
+
return ProblemStatus.INFEASIBLE
|
| 913 |
+
else:
|
| 914 |
+
flow[e] = 0
|
| 915 |
+
|
| 916 |
+
# Shift potentials to meet the requirements of the GEQ/LEQ type
|
| 917 |
+
# optimality conditions
|
| 918 |
+
max_pot = -INFINITY
|
| 919 |
+
for i in range(graph.n_nodes):
|
| 920 |
+
if pi[i] > max_pot:
|
| 921 |
+
max_pot = pi[i]
|
| 922 |
+
if max_pot > 0:
|
| 923 |
+
for i in range(graph.n_nodes):
|
| 924 |
+
pi[i] -= max_pot
|
| 925 |
+
|
| 926 |
+
return solution_status
|
| 927 |
+
|
| 928 |
+
|
| 929 |
+
#######################################################
|
| 930 |
+
# SINKHORN distances in various variations
|
| 931 |
+
#######################################################
|
| 932 |
+
|
| 933 |
+
|
| 934 |
+
@numba.njit(
|
| 935 |
+
fastmath=True,
|
| 936 |
+
parallel=True,
|
| 937 |
+
locals={"diff": numba.float32, "result": numba.float32},
|
| 938 |
+
cache=False,
|
| 939 |
+
)
|
| 940 |
+
def right_marginal_error(u, K, v, y):
|
| 941 |
+
uK = u @ K
|
| 942 |
+
result = 0.0
|
| 943 |
+
for i in numba.prange(uK.shape[0]):
|
| 944 |
+
diff = y[i] - uK[i] * v[i]
|
| 945 |
+
result += diff * diff
|
| 946 |
+
return np.sqrt(result)
|
| 947 |
+
|
| 948 |
+
|
| 949 |
+
@numba.njit(
|
| 950 |
+
fastmath=True,
|
| 951 |
+
parallel=True,
|
| 952 |
+
locals={"diff": numba.float32, "result": numba.float32},
|
| 953 |
+
cache=False,
|
| 954 |
+
)
|
| 955 |
+
def right_marginal_error_batch(u, K, v, y):
|
| 956 |
+
uK = K.T @ u
|
| 957 |
+
result = 0.0
|
| 958 |
+
for i in numba.prange(uK.shape[0]):
|
| 959 |
+
for j in range(uK.shape[1]):
|
| 960 |
+
diff = y[j, i] - uK[i, j] * v[i, j]
|
| 961 |
+
result += diff * diff
|
| 962 |
+
return np.sqrt(result)
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
@numba.njit(fastmath=True, parallel=True, cache=False)
|
| 966 |
+
def transport_plan(K, u, v):
|
| 967 |
+
i_dim = K.shape[0]
|
| 968 |
+
j_dim = K.shape[1]
|
| 969 |
+
result = np.empty_like(K)
|
| 970 |
+
for i in numba.prange(i_dim):
|
| 971 |
+
for j in range(j_dim):
|
| 972 |
+
result[i, j] = u[i] * K[i, j] * v[j]
|
| 973 |
+
|
| 974 |
+
return result
|
| 975 |
+
|
| 976 |
+
|
| 977 |
+
@numba.njit(fastmath=True, parallel=True, locals={"result": numba.float32}, cache=False)
|
| 978 |
+
def relative_change_in_plan(old_u, old_v, new_u, new_v):
|
| 979 |
+
i_dim = old_u.shape[0]
|
| 980 |
+
j_dim = old_v.shape[0]
|
| 981 |
+
result = 0.0
|
| 982 |
+
for i in numba.prange(i_dim):
|
| 983 |
+
for j in range(j_dim):
|
| 984 |
+
old_uv = old_u[i] * old_v[j]
|
| 985 |
+
result += np.float32(np.abs(old_uv - new_u[i] * new_v[j]) / old_uv)
|
| 986 |
+
|
| 987 |
+
return result / (i_dim * j_dim)
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
@numba.njit(fastmath=True, parallel=True, cache=False)
|
| 991 |
+
def precompute_K_prime(K, x):
|
| 992 |
+
i_dim = K.shape[0]
|
| 993 |
+
j_dim = K.shape[1]
|
| 994 |
+
result = np.empty_like(K)
|
| 995 |
+
for i in numba.prange(i_dim):
|
| 996 |
+
if x[i] > 0.0:
|
| 997 |
+
x_i_inverse = 1.0 / x[i]
|
| 998 |
+
else:
|
| 999 |
+
x_i_inverse = INFINITY
|
| 1000 |
+
for j in range(j_dim):
|
| 1001 |
+
result[i, j] = x_i_inverse * K[i, j]
|
| 1002 |
+
|
| 1003 |
+
return result
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
@numba.njit(fastmath=True, parallel=True, cache=False)
|
| 1007 |
+
def K_from_cost(cost, regularization):
|
| 1008 |
+
i_dim = cost.shape[0]
|
| 1009 |
+
j_dim = cost.shape[1]
|
| 1010 |
+
result = np.empty_like(cost)
|
| 1011 |
+
for i in numba.prange(i_dim):
|
| 1012 |
+
for j in range(j_dim):
|
| 1013 |
+
scaled_cost = cost[i, j] / regularization
|
| 1014 |
+
result[i, j] = np.exp(-scaled_cost)
|
| 1015 |
+
|
| 1016 |
+
return result
|
| 1017 |
+
|
| 1018 |
+
|
| 1019 |
+
@numba.njit(fastmath=True, cache=True)
|
| 1020 |
+
def sinkhorn_iterations(
|
| 1021 |
+
x, y, u, v, K, max_iter=1000, error_tolerance=1e-9, change_tolerance=1e-9
|
| 1022 |
+
):
|
| 1023 |
+
K_prime = precompute_K_prime(K, x)
|
| 1024 |
+
|
| 1025 |
+
prev_u = u
|
| 1026 |
+
prev_v = v
|
| 1027 |
+
|
| 1028 |
+
for iteration in range(max_iter):
|
| 1029 |
+
|
| 1030 |
+
next_v = y / (K.T @ u)
|
| 1031 |
+
|
| 1032 |
+
if np.any(~np.isfinite(next_v)):
|
| 1033 |
+
break
|
| 1034 |
+
|
| 1035 |
+
next_u = 1.0 / (K_prime @ next_v)
|
| 1036 |
+
|
| 1037 |
+
if np.any(~np.isfinite(next_u)):
|
| 1038 |
+
break
|
| 1039 |
+
|
| 1040 |
+
u = next_u
|
| 1041 |
+
v = next_v
|
| 1042 |
+
|
| 1043 |
+
if iteration % 20 == 0:
|
| 1044 |
+
# Check if values in plan have changed significantly since last 20 iterations
|
| 1045 |
+
relative_change = relative_change_in_plan(prev_u, prev_v, next_u, next_v)
|
| 1046 |
+
if relative_change <= change_tolerance:
|
| 1047 |
+
break
|
| 1048 |
+
|
| 1049 |
+
prev_u = u
|
| 1050 |
+
prev_v = v
|
| 1051 |
+
|
| 1052 |
+
if iteration % 10 == 0:
|
| 1053 |
+
# Check if right marginal error is less than tolerance every 10 iterations
|
| 1054 |
+
err = right_marginal_error(u, K, v, y)
|
| 1055 |
+
if err <= error_tolerance:
|
| 1056 |
+
break
|
| 1057 |
+
|
| 1058 |
+
return u, v
|
| 1059 |
+
|
| 1060 |
+
|
| 1061 |
+
@numba.njit(fastmath=True, cache=True)
|
| 1062 |
+
def sinkhorn_iterations_batch(x, y, u, v, K, max_iter=1000, error_tolerance=1e-9):
|
| 1063 |
+
K_prime = precompute_K_prime(K, x)
|
| 1064 |
+
|
| 1065 |
+
for iteration in range(max_iter):
|
| 1066 |
+
|
| 1067 |
+
next_v = y.T / (K.T @ u)
|
| 1068 |
+
|
| 1069 |
+
if np.any(~np.isfinite(next_v)):
|
| 1070 |
+
break
|
| 1071 |
+
|
| 1072 |
+
next_u = 1.0 / (K_prime @ next_v)
|
| 1073 |
+
|
| 1074 |
+
if np.any(~np.isfinite(next_u)):
|
| 1075 |
+
break
|
| 1076 |
+
|
| 1077 |
+
u = next_u
|
| 1078 |
+
v = next_v
|
| 1079 |
+
|
| 1080 |
+
if iteration % 10 == 0:
|
| 1081 |
+
# Check if right marginal error is less than tolerance every 10 iterations
|
| 1082 |
+
err = right_marginal_error_batch(u, K, v, y)
|
| 1083 |
+
if err <= error_tolerance:
|
| 1084 |
+
break
|
| 1085 |
+
|
| 1086 |
+
return u, v
|
| 1087 |
+
|
| 1088 |
+
|
| 1089 |
+
@numba.njit(fastmath=True, cache=True)
|
| 1090 |
+
def sinkhorn_transport_plan(
|
| 1091 |
+
x,
|
| 1092 |
+
y,
|
| 1093 |
+
cost=_dummy_cost,
|
| 1094 |
+
regularization=1.0,
|
| 1095 |
+
max_iter=1000,
|
| 1096 |
+
error_tolerance=1e-9,
|
| 1097 |
+
change_tolerance=1e-9,
|
| 1098 |
+
):
|
| 1099 |
+
dim_x = x.shape[0]
|
| 1100 |
+
dim_y = y.shape[0]
|
| 1101 |
+
u = np.full(dim_x, 1.0 / dim_x, dtype=cost.dtype)
|
| 1102 |
+
v = np.full(dim_y, 1.0 / dim_y, dtype=cost.dtype)
|
| 1103 |
+
|
| 1104 |
+
K = K_from_cost(cost, regularization)
|
| 1105 |
+
u, v = sinkhorn_iterations(
|
| 1106 |
+
x,
|
| 1107 |
+
y,
|
| 1108 |
+
u,
|
| 1109 |
+
v,
|
| 1110 |
+
K,
|
| 1111 |
+
max_iter=max_iter,
|
| 1112 |
+
error_tolerance=error_tolerance,
|
| 1113 |
+
change_tolerance=change_tolerance,
|
| 1114 |
+
)
|
| 1115 |
+
|
| 1116 |
+
return transport_plan(K, u, v)
|
| 1117 |
+
|
| 1118 |
+
|
| 1119 |
+
@numba.njit(fastmath=True, cache=True)
|
| 1120 |
+
def sinkhorn_distance(x, y, cost=_dummy_cost, regularization=1.0):
|
| 1121 |
+
transport_plan = sinkhorn_transport_plan(
|
| 1122 |
+
x, y, cost=cost, regularization=regularization
|
| 1123 |
+
)
|
| 1124 |
+
dim_i = transport_plan.shape[0]
|
| 1125 |
+
dim_j = transport_plan.shape[1]
|
| 1126 |
+
result = 0.0
|
| 1127 |
+
for i in range(dim_i):
|
| 1128 |
+
for j in range(dim_j):
|
| 1129 |
+
result += transport_plan[i, j] * cost[i, j]
|
| 1130 |
+
|
| 1131 |
+
return result
|
| 1132 |
+
|
| 1133 |
+
|
| 1134 |
+
@numba.njit(fastmath=True, parallel=True, cache=False)
|
| 1135 |
+
def sinkhorn_distance_batch(x, y, cost=_dummy_cost, regularization=1.0):
|
| 1136 |
+
dim_x = x.shape[0]
|
| 1137 |
+
dim_y = y.shape[0]
|
| 1138 |
+
|
| 1139 |
+
batch_size = y.shape[1]
|
| 1140 |
+
|
| 1141 |
+
u = np.full((dim_x, batch_size), 1.0 / dim_x, dtype=cost.dtype)
|
| 1142 |
+
v = np.full((dim_y, batch_size), 1.0 / dim_y, dtype=cost.dtype)
|
| 1143 |
+
|
| 1144 |
+
K = K_from_cost(cost, regularization)
|
| 1145 |
+
u, v = sinkhorn_iterations_batch(
|
| 1146 |
+
x,
|
| 1147 |
+
y,
|
| 1148 |
+
u,
|
| 1149 |
+
v,
|
| 1150 |
+
K,
|
| 1151 |
+
)
|
| 1152 |
+
|
| 1153 |
+
i_dim = K.shape[0]
|
| 1154 |
+
j_dim = K.shape[1]
|
| 1155 |
+
result = np.zeros(batch_size)
|
| 1156 |
+
for i in range(i_dim):
|
| 1157 |
+
for j in range(j_dim):
|
| 1158 |
+
K_times_cost = K[i, j] * cost[i, j]
|
| 1159 |
+
for batch in range(batch_size):
|
| 1160 |
+
result[batch] += u[i, batch] * K_times_cost * v[j, batch]
|
| 1161 |
+
|
| 1162 |
+
return result
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
def make_fixed_cost_sinkhorn_distance(cost, regularization=1.0):
|
| 1166 |
+
|
| 1167 |
+
K = K_from_cost(cost, regularization)
|
| 1168 |
+
dim_x = K.shape[0]
|
| 1169 |
+
dim_y = K.shape[1]
|
| 1170 |
+
|
| 1171 |
+
@numba.njit(fastmath=True)
|
| 1172 |
+
def closure(x, y):
|
| 1173 |
+
u = np.full(dim_x, 1.0 / dim_x, dtype=cost.dtype)
|
| 1174 |
+
v = np.full(dim_y, 1.0 / dim_y, dtype=cost.dtype)
|
| 1175 |
+
|
| 1176 |
+
K = K_from_cost(cost, regularization)
|
| 1177 |
+
u, v = sinkhorn_iterations(
|
| 1178 |
+
x,
|
| 1179 |
+
y,
|
| 1180 |
+
u,
|
| 1181 |
+
v,
|
| 1182 |
+
K,
|
| 1183 |
+
)
|
| 1184 |
+
|
| 1185 |
+
current_plan = transport_plan(K, u, v)
|
| 1186 |
+
|
| 1187 |
+
result = 0.0
|
| 1188 |
+
for i in range(dim_x):
|
| 1189 |
+
for j in range(dim_y):
|
| 1190 |
+
result += current_plan[i, j] * cost[i, j]
|
| 1191 |
+
|
| 1192 |
+
return result
|
| 1193 |
+
|
| 1194 |
+
return closure
|
shared/package-files/32/320cceeab3e51f6f4515bee7920fbb652418523bd0f769be82a892f9bab9676c/blob
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import UserList
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from typing import Any, Dict, List, Optional, Sequence, Union
|
| 4 |
+
|
| 5 |
+
from django.core.exceptions import ValidationError
|
| 6 |
+
from django.utils.safestring import SafeText
|
| 7 |
+
|
| 8 |
+
def pretty_name(name: str) -> str: ...
|
| 9 |
+
def flatatt(attrs: Dict[str, Any]) -> SafeText: ...
|
| 10 |
+
|
| 11 |
+
class ErrorDict(dict):
|
| 12 |
+
def as_data(self) -> Dict[str, List[ValidationError]]: ...
|
| 13 |
+
def get_json_data(self, escape_html: bool = ...) -> Dict[str, Any]: ...
|
| 14 |
+
def as_json(self, escape_html: bool = ...) -> str: ...
|
| 15 |
+
def as_ul(self) -> str: ...
|
| 16 |
+
def as_text(self) -> str: ...
|
| 17 |
+
|
| 18 |
+
class ErrorList(UserList):
|
| 19 |
+
data: List[Union[ValidationError, str]]
|
| 20 |
+
error_class: str = ...
|
| 21 |
+
def __init__(
|
| 22 |
+
self,
|
| 23 |
+
initlist: Optional[Union[ErrorList, Sequence[Union[str, Exception]]]] = ...,
|
| 24 |
+
error_class: Optional[str] = ...,
|
| 25 |
+
) -> None: ...
|
| 26 |
+
def as_data(self) -> List[ValidationError]: ...
|
| 27 |
+
def get_json_data(self, escape_html: bool = ...) -> List[Dict[str, str]]: ...
|
| 28 |
+
def as_json(self, escape_html: bool = ...) -> str: ...
|
| 29 |
+
def as_ul(self) -> str: ...
|
| 30 |
+
def as_text(self) -> str: ...
|
| 31 |
+
|
| 32 |
+
def from_current_timezone(value: datetime) -> datetime: ...
|
| 33 |
+
def to_current_timezone(value: datetime) -> datetime: ...
|
shared/package-files/32/320de8e22b5d74767e87fabe35eacbdff562c3ae498f6fcec9628f7fc895e0e9/blob
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
|
|
|
|
|
|
|
|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warnings as _warnings
|
| 10 |
+
from concurrent.futures import Executor, ProcessPoolExecutor, ThreadPoolExecutor
|
| 11 |
+
from errno import EACCES, ENOENT, EPERM, EROFS
|
| 12 |
+
from itertools import chain
|
| 13 |
+
from os.path import (
|
| 14 |
+
abspath,
|
| 15 |
+
basename,
|
| 16 |
+
dirname,
|
| 17 |
+
isdir,
|
| 18 |
+
isfile,
|
| 19 |
+
islink,
|
| 20 |
+
join,
|
| 21 |
+
lexists,
|
| 22 |
+
normpath,
|
| 23 |
+
split,
|
| 24 |
+
)
|
| 25 |
+
from stat import S_IEXEC, S_IMODE, S_ISDIR, S_ISREG, S_IWRITE
|
| 26 |
+
from subprocess import STDOUT, CalledProcessError, check_output, list2cmdline
|
| 27 |
+
from tempfile import NamedTemporaryFile, mkdtemp
|
| 28 |
+
|
| 29 |
+
on_win = sys.platform == "win32"
|
| 30 |
+
log = logging.getLogger(__file__)
|
| 31 |
+
CONDA_TEMP_EXTENSION = ".c~"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def which(executable):
|
| 35 |
+
from distutils.spawn import find_executable
|
| 36 |
+
|
| 37 |
+
return find_executable(executable)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def make_writable(path):
|
| 41 |
+
try:
|
| 42 |
+
mode = os.lstat(path).st_mode
|
| 43 |
+
if S_ISDIR(mode):
|
| 44 |
+
os.chmod(path, S_IMODE(mode) | S_IWRITE | S_IEXEC)
|
| 45 |
+
elif S_ISREG(mode) or islink(path):
|
| 46 |
+
os.chmod(path, S_IMODE(mode) | S_IWRITE)
|
| 47 |
+
else:
|
| 48 |
+
log.debug("path cannot be made writable: %s", path)
|
| 49 |
+
return True
|
| 50 |
+
except Exception as e:
|
| 51 |
+
eno = getattr(e, "errno", None)
|
| 52 |
+
if eno in (ENOENT,):
|
| 53 |
+
log.debug("tried to make writable, but didn't exist: %s", path)
|
| 54 |
+
raise
|
| 55 |
+
elif eno in (EACCES, EPERM, EROFS):
|
| 56 |
+
log.debug("tried make writable but failed: %s\n%r", path, e)
|
| 57 |
+
return False
|
| 58 |
+
else:
|
| 59 |
+
log.warn("Error making path writable: %s\n%r", path, e)
|
| 60 |
+
raise
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class DummyExecutor(Executor):
|
| 64 |
+
def map(self, func, *iterables):
|
| 65 |
+
for iterable in iterables:
|
| 66 |
+
for thing in iterable:
|
| 67 |
+
yield func(thing)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def get_executor(processes):
|
| 71 |
+
return DummyExecutor() if processes == 1 else ProcessPoolExecutor(max_workers=processes)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def recursive_make_writable(path):
|
| 75 |
+
# The need for this function was pointed out at
|
| 76 |
+
# https://github.com/conda/conda/issues/3266#issuecomment-239241915
|
| 77 |
+
# Especially on windows, file removal will often fail because it is marked read-only
|
| 78 |
+
if isdir(path):
|
| 79 |
+
for root, dirs, files in os.walk(path):
|
| 80 |
+
for path in chain.from_iterable((files, dirs)):
|
| 81 |
+
try:
|
| 82 |
+
make_writable(join(root, path))
|
| 83 |
+
except:
|
| 84 |
+
pass
|
| 85 |
+
else:
|
| 86 |
+
try:
|
| 87 |
+
make_writable(path)
|
| 88 |
+
except:
|
| 89 |
+
pass
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def quote_for_shell(arguments, shell=None):
|
| 93 |
+
if not shell:
|
| 94 |
+
shell = "cmd.exe" if on_win else "bash"
|
| 95 |
+
if shell == "cmd.exe":
|
| 96 |
+
return list2cmdline(arguments)
|
| 97 |
+
else:
|
| 98 |
+
# If any multiline argument gets mixed with any other argument (which is true if we've
|
| 99 |
+
# arrived in this function) then we just quote it. This assumes something like:
|
| 100 |
+
# ['python', '-c', 'a\nmultiline\nprogram\n']
|
| 101 |
+
# It may make sense to allow specifying a replacement character for '\n' too? e.g. ';'
|
| 102 |
+
quoted = []
|
| 103 |
+
# This could all be replaced with some regex wizardry but that is less readable and
|
| 104 |
+
# for code like this, readability is very important.
|
| 105 |
+
for arg in arguments:
|
| 106 |
+
if '"' in arg:
|
| 107 |
+
quote = "'"
|
| 108 |
+
elif "'" in arg:
|
| 109 |
+
quote = '"'
|
| 110 |
+
elif not any(_ in arg for _ in (" ", "\n")):
|
| 111 |
+
quote = ""
|
| 112 |
+
else:
|
| 113 |
+
quote = '"'
|
| 114 |
+
quoted.append(quote + arg + quote)
|
| 115 |
+
return " ".join(quoted)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def rmtree(path, *args, **kwargs):
|
| 119 |
+
# subprocessing to delete large folders can be quite a bit faster
|
| 120 |
+
path = normpath(path)
|
| 121 |
+
if on_win:
|
| 122 |
+
try:
|
| 123 |
+
# the fastest way seems to be using DEL to recursively delete files
|
| 124 |
+
# https://www.ghacks.net/2017/07/18/how-to-delete-large-folders-in-windows-super-fast/
|
| 125 |
+
# However, this is not entirely safe, as it can end up following symlinks to folders
|
| 126 |
+
# https://superuser.com/a/306618/184799
|
| 127 |
+
# so, we stick with the slower, but hopefully safer way. Maybe if we figured out how
|
| 128 |
+
# to scan for any possible symlinks, we could do the faster way.
|
| 129 |
+
# out = check_output('DEL /F/Q/S *.* > NUL 2> NUL'.format(path), shell=True,
|
| 130 |
+
# stderr=STDOUT, cwd=path)
|
| 131 |
+
|
| 132 |
+
out = check_output(f'RD /S /Q "{path}" > NUL 2> NUL', shell=True, stderr=STDOUT)
|
| 133 |
+
except:
|
| 134 |
+
try:
|
| 135 |
+
# Try to delete in Unicode
|
| 136 |
+
name = None
|
| 137 |
+
|
| 138 |
+
with NamedTemporaryFile(suffix=".bat", delete=False) as batch_file:
|
| 139 |
+
batch_file.write(f"RD /S {quote_for_shell([path])}\n")
|
| 140 |
+
batch_file.write("chcp 65001\n")
|
| 141 |
+
batch_file.write(f"RD /S {quote_for_shell([path])}\n")
|
| 142 |
+
batch_file.write("EXIT 0\n")
|
| 143 |
+
name = batch_file.name
|
| 144 |
+
# If the above is bugged we can end up deleting hard-drives, so we check
|
| 145 |
+
# that 'path' appears in it. This is not bulletproof but it could save you (me).
|
| 146 |
+
with open(name) as contents:
|
| 147 |
+
content = contents.read()
|
| 148 |
+
assert path in content
|
| 149 |
+
comspec = os.environ["COMSPEC"]
|
| 150 |
+
CREATE_NO_WINDOW = 0x08000000
|
| 151 |
+
# It is essential that we `pass stdout=None, stderr=None, stdin=None` here because
|
| 152 |
+
# if we do not, then the standard console handles get attached and chcp affects the
|
| 153 |
+
# parent process (and any which share those console handles!)
|
| 154 |
+
out = check_output(
|
| 155 |
+
[comspec, "/d", "/c", name],
|
| 156 |
+
shell=False,
|
| 157 |
+
stdout=None,
|
| 158 |
+
stderr=None,
|
| 159 |
+
stdin=None,
|
| 160 |
+
creationflags=CREATE_NO_WINDOW,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
except CalledProcessError as e:
|
| 164 |
+
if e.returncode != 5:
|
| 165 |
+
log.error(f"Removing folder {path} the fast way failed. Output was: {out}")
|
| 166 |
+
raise
|
| 167 |
+
else:
|
| 168 |
+
log.debug(f"removing dir contents the fast way failed. Output was: {out}")
|
| 169 |
+
else:
|
| 170 |
+
try:
|
| 171 |
+
os.makedirs(".empty")
|
| 172 |
+
except:
|
| 173 |
+
pass
|
| 174 |
+
# yes, this looks strange. See
|
| 175 |
+
# https://unix.stackexchange.com/a/79656/34459
|
| 176 |
+
# https://web.archive.org/web/20130929001850/http://linuxnote.net/jianingy/en/linux/a-fast-way-to-remove-huge-number-of-files.html # NOQA
|
| 177 |
+
rsync = which("rsync")
|
| 178 |
+
if rsync and isdir(".empty"):
|
| 179 |
+
try:
|
| 180 |
+
out = check_output(
|
| 181 |
+
[
|
| 182 |
+
rsync,
|
| 183 |
+
"-a",
|
| 184 |
+
"--force",
|
| 185 |
+
"--delete",
|
| 186 |
+
join(os.getcwd(), ".empty") + "/",
|
| 187 |
+
path + "/",
|
| 188 |
+
],
|
| 189 |
+
stderr=STDOUT,
|
| 190 |
+
)
|
| 191 |
+
except CalledProcessError:
|
| 192 |
+
log.debug(f"removing dir contents the fast way failed. Output was: {out}")
|
| 193 |
+
shutil.rmtree(".empty")
|
| 194 |
+
shutil.rmtree(path)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def unlink_or_rename_to_trash(path):
|
| 198 |
+
"""If files are in use, especially on windows, we can't remove them.
|
| 199 |
+
The fallback path is to rename them (but keep their folder the same),
|
| 200 |
+
which maintains the file handle validity. See comments at:
|
| 201 |
+
https://serverfault.com/a/503769
|
| 202 |
+
"""
|
| 203 |
+
try:
|
| 204 |
+
make_writable(path)
|
| 205 |
+
os.unlink(path)
|
| 206 |
+
except OSError:
|
| 207 |
+
try:
|
| 208 |
+
os.rename(path, path + ".conda_trash")
|
| 209 |
+
except OSError:
|
| 210 |
+
if on_win:
|
| 211 |
+
# on windows, it is important to use the rename program, as just using python's
|
| 212 |
+
# rename leads to permission errors when files are in use.
|
| 213 |
+
with NamedTemporaryFile(suffix=".bat") as trash_script:
|
| 214 |
+
with open(trash_script, "w") as f:
|
| 215 |
+
f.write('@pushd "%1"\n')
|
| 216 |
+
f.write("@REM Rename src to dest")
|
| 217 |
+
f.write('@ren "%2" "%3" > NUL 2> NUL")')
|
| 218 |
+
|
| 219 |
+
_dirname, _fn = split(path)
|
| 220 |
+
dest_fn = path + ".conda_trash"
|
| 221 |
+
counter = 1
|
| 222 |
+
while isfile(dest_fn):
|
| 223 |
+
dest_fn = dest_fn.splitext[0] + f".conda_trash_{counter}"
|
| 224 |
+
counter += 1
|
| 225 |
+
out = "< empty >"
|
| 226 |
+
try:
|
| 227 |
+
out = check_output(
|
| 228 |
+
[
|
| 229 |
+
"cmd.exe",
|
| 230 |
+
"/C",
|
| 231 |
+
trash_script,
|
| 232 |
+
_dirname,
|
| 233 |
+
_fn,
|
| 234 |
+
basename(dest_fn),
|
| 235 |
+
],
|
| 236 |
+
stderr=STDOUT,
|
| 237 |
+
)
|
| 238 |
+
except CalledProcessError:
|
| 239 |
+
log.warn(
|
| 240 |
+
"renaming file path {} to trash failed. Output was: {}".format(
|
| 241 |
+
path, out
|
| 242 |
+
)
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
log.warn(
|
| 246 |
+
"Could not remove or rename {}. Please remove this file manually (you "
|
| 247 |
+
"may need to reboot to free file handles)".format(path)
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def remove_empty_parent_paths(path):
|
| 252 |
+
# recurse to clean up empty folders that were created to have a nested hierarchy
|
| 253 |
+
parent_path = dirname(path)
|
| 254 |
+
while isdir(parent_path) and not os.listdir(parent_path):
|
| 255 |
+
rmdir(parent_path)
|
| 256 |
+
parent_path = dirname(parent_path)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def rm_rf(path, clean_empty_parents=False, *args, **kw):
|
| 260 |
+
"""
|
| 261 |
+
Completely delete path
|
| 262 |
+
max_retries is the number of times to retry on failure. The default is 5. This only applies
|
| 263 |
+
to deleting a directory.
|
| 264 |
+
If removing path fails and trash is True, files will be moved to the trash directory.
|
| 265 |
+
"""
|
| 266 |
+
recursive_make_writable(path)
|
| 267 |
+
try:
|
| 268 |
+
path = abspath(path)
|
| 269 |
+
if isdir(path) and not islink(path):
|
| 270 |
+
rmdir(path)
|
| 271 |
+
elif lexists(path):
|
| 272 |
+
unlink_or_rename_to_trash(path)
|
| 273 |
+
else:
|
| 274 |
+
log.debug("rm_rf failed. Not a link, file, or directory: %s", path)
|
| 275 |
+
finally:
|
| 276 |
+
if lexists(path):
|
| 277 |
+
log.info("rm_rf failed for %s", path)
|
| 278 |
+
return False
|
| 279 |
+
if isdir(path):
|
| 280 |
+
delete_trash(path)
|
| 281 |
+
if clean_empty_parents:
|
| 282 |
+
remove_empty_parent_paths(path)
|
| 283 |
+
return True
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
# aliases that all do the same thing (legacy compat)
|
| 287 |
+
try_rmdir_all_empty = move_to_trash = move_path_to_trash = rm_rf
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def delete_trash(prefix):
|
| 291 |
+
if not prefix:
|
| 292 |
+
prefix = sys.prefix
|
| 293 |
+
exclude = {"envs"}
|
| 294 |
+
for root, dirs, files in os.walk(prefix, topdown=True):
|
| 295 |
+
dirs[:] = [d for d in dirs if d not in exclude]
|
| 296 |
+
for fn in files:
|
| 297 |
+
if fnmatch.fnmatch(fn, "*.conda_trash*") or fnmatch.fnmatch(
|
| 298 |
+
fn, "*" + CONDA_TEMP_EXTENSION
|
| 299 |
+
):
|
| 300 |
+
filename = join(root, fn)
|
| 301 |
+
try:
|
| 302 |
+
os.unlink(filename)
|
| 303 |
+
remove_empty_parent_paths(filename)
|
| 304 |
+
except OSError as e:
|
| 305 |
+
log.debug("%r errno %d\nCannot unlink %s.", e, e.errno, filename)
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def rmdir(dirpath):
|
| 309 |
+
if not isdir(dirpath):
|
| 310 |
+
return
|
| 311 |
+
try:
|
| 312 |
+
rmtree(dirpath)
|
| 313 |
+
# we don't really care about errors that much. We'll catch remaining files
|
| 314 |
+
# with slower python logic.
|
| 315 |
+
except:
|
| 316 |
+
pass
|
| 317 |
+
|
| 318 |
+
for root, dirs, files in os.walk(dirpath, topdown=False):
|
| 319 |
+
for f in files:
|
| 320 |
+
unlink_or_rename_to_trash(join(root, f))
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
# we have our own TemporaryDirectory class because it's faster and handles disk issues better.
|
| 324 |
+
class TemporaryDirectory:
|
| 325 |
+
"""Create and return a temporary directory. This has the same
|
| 326 |
+
behavior as mkdtemp but can be used as a context manager. For
|
| 327 |
+
example:
|
| 328 |
+
|
| 329 |
+
with TemporaryDirectory() as tmpdir:
|
| 330 |
+
...
|
| 331 |
+
|
| 332 |
+
Upon exiting the context, the directory and everything contained
|
| 333 |
+
in it are removed.
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
# Handle mkdtemp raising an exception
|
| 337 |
+
name = None
|
| 338 |
+
_closed = False
|
| 339 |
+
|
| 340 |
+
def __init__(self, suffix="", prefix=".cph_tmp", dir=os.getcwd()):
|
| 341 |
+
self.name = mkdtemp(suffix, prefix, dir)
|
| 342 |
+
|
| 343 |
+
def __repr__(self):
|
| 344 |
+
return f"<{self.__class__.__name__} {self.name!r}>"
|
| 345 |
+
|
| 346 |
+
def __enter__(self):
|
| 347 |
+
return self.name
|
| 348 |
+
|
| 349 |
+
def cleanup(self, _warn=False, _warnings=_warnings):
|
| 350 |
+
if self.name and not self._closed:
|
| 351 |
+
try:
|
| 352 |
+
rm_rf(self.name)
|
| 353 |
+
except:
|
| 354 |
+
_warnings.warn(
|
| 355 |
+
'Conda-package-handling says: "I tried to clean up, '
|
| 356 |
+
"but I could not. There is a mess in %s that you might "
|
| 357 |
+
'want to clean up yourself. Sorry..."' % self.name
|
| 358 |
+
)
|
| 359 |
+
self._closed = True
|
| 360 |
+
if _warn and _warnings.warn:
|
| 361 |
+
_warnings.warn(
|
| 362 |
+
f"Implicitly cleaning up {self!r}",
|
| 363 |
+
_warnings.ResourceWarning,
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
def __exit__(self, exc, value, tb):
|
| 367 |
+
self.cleanup()
|
| 368 |
+
|
| 369 |
+
def __del__(self):
|
| 370 |
+
# Issue a ResourceWarning if implicit cleanup needed
|
| 371 |
+
self.cleanup(_warn=True)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
@contextlib.contextmanager
|
| 375 |
+
def tmp_chdir(dest):
|
| 376 |
+
curdir = os.getcwd()
|
| 377 |
+
try:
|
| 378 |
+
os.chdir(dest)
|
| 379 |
+
yield
|
| 380 |
+
finally:
|
| 381 |
+
os.chdir(curdir)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def ensure_list(arg):
|
| 385 |
+
if isinstance(arg, str) or not hasattr(arg, "__iter__"):
|
| 386 |
+
if arg is not None:
|
| 387 |
+
arg = [arg]
|
| 388 |
+
else:
|
| 389 |
+
arg = []
|
| 390 |
+
return arg
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def filter_files(
|
| 394 |
+
files_list,
|
| 395 |
+
prefix,
|
| 396 |
+
filter_patterns=(
|
| 397 |
+
r"(.*[\\\\/])?\.git[\\\\/].*",
|
| 398 |
+
r"(.*[\\\\/])?\.git$",
|
| 399 |
+
r"(.*)?\.DS_Store.*",
|
| 400 |
+
r".*\.la$",
|
| 401 |
+
r"conda-meta.*",
|
| 402 |
+
),
|
| 403 |
+
):
|
| 404 |
+
"""Remove things like the .git directory from the list of files to be copied"""
|
| 405 |
+
for pattern in filter_patterns:
|
| 406 |
+
r = re.compile(pattern)
|
| 407 |
+
files_list = set(files_list) - set(filter(r.match, files_list))
|
| 408 |
+
return [
|
| 409 |
+
f
|
| 410 |
+
for f in files_list
|
| 411 |
+
if
|
| 412 |
+
# `islink` prevents symlinks to directories from being removed
|
| 413 |
+
os.path.islink(os.path.join(prefix, f)) or not os.path.isdir(os.path.join(prefix, f))
|
| 414 |
+
]
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def filter_info_files(files_list, prefix):
|
| 418 |
+
return filter_files(
|
| 419 |
+
files_list,
|
| 420 |
+
prefix,
|
| 421 |
+
filter_patterns=(
|
| 422 |
+
"info[\\\\/]index\\.json",
|
| 423 |
+
"info[\\\\/]files",
|
| 424 |
+
"info[\\\\/]paths\\.json",
|
| 425 |
+
"info[\\\\/]about\\.json",
|
| 426 |
+
"info[\\\\/]has_prefix",
|
| 427 |
+
"info[\\\\/]hash_input_files", # legacy, not used anymore
|
| 428 |
+
"info[\\\\/]hash_input\\.json",
|
| 429 |
+
"info[\\\\/]run_exports\\.yaml", # legacy
|
| 430 |
+
"info[\\\\/]run_exports\\.json", # current
|
| 431 |
+
"info[\\\\/]git",
|
| 432 |
+
"info[\\\\/]recipe[\\\\/].*",
|
| 433 |
+
"info[\\\\/]recipe_log.json",
|
| 434 |
+
"info[\\\\/]recipe.tar",
|
| 435 |
+
"info[\\\\/]test[\\\\/].*",
|
| 436 |
+
"info[\\\\/]LICENSE.*",
|
| 437 |
+
"info[\\\\/]requires",
|
| 438 |
+
"info[\\\\/]meta",
|
| 439 |
+
"info[\\\\/]platform",
|
| 440 |
+
"info[\\\\/]no_link",
|
| 441 |
+
"info[\\\\/]link\\.json",
|
| 442 |
+
"info[\\\\/]icon\\.png",
|
| 443 |
+
),
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def _checksum(fd, algorithm, buffersize=65536):
|
| 448 |
+
hash_impl = getattr(hashlib, algorithm)
|
| 449 |
+
if not hash_impl:
|
| 450 |
+
raise ValueError(f"Unrecognized hash algorithm: {algorithm}")
|
| 451 |
+
else:
|
| 452 |
+
hash_impl = hash_impl()
|
| 453 |
+
for block in iter(lambda: fd.read(buffersize), b""):
|
| 454 |
+
hash_impl.update(block)
|
| 455 |
+
return hash_impl.hexdigest()
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def sha256_checksum(fd):
|
| 459 |
+
return _checksum(fd, "sha256")
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def md5_checksum(fd):
|
| 463 |
+
return _checksum(fd, "md5")
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def checksum(fn, algorithm, buffersize=1 << 18):
|
| 467 |
+
"""
|
| 468 |
+
Calculate a checksum for a filename (not an open file).
|
| 469 |
+
"""
|
| 470 |
+
with open(fn, "rb") as fd:
|
| 471 |
+
return _checksum(fd, algorithm, buffersize)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def checksums(fn, algorithms, buffersize=1 << 18):
|
| 475 |
+
"""
|
| 476 |
+
Calculate multiple checksums for a filename in parallel.
|
| 477 |
+
"""
|
| 478 |
+
with ThreadPoolExecutor(max_workers=len(algorithms)) as e:
|
| 479 |
+
# take care not to share hash_impl between threads
|
| 480 |
+
results = [e.submit(checksum, fn, algorithm, buffersize) for algorithm in algorithms]
|
| 481 |
+
return [result.result() for result in results]
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def anonymize_tarinfo(tarinfo):
|
| 485 |
+
"""
|
| 486 |
+
Remove user id, name from tarinfo.
|
| 487 |
+
"""
|
| 488 |
+
# also remove timestamps?
|
| 489 |
+
tarinfo.uid = 0
|
| 490 |
+
tarinfo.uname = ""
|
| 491 |
+
tarinfo.gid = 0
|
| 492 |
+
tarinfo.gname = ""
|
| 493 |
+
return tarinfo
|
shared/package-files/32/320e1d8e583d6c7c1f5a26bb913b1315d62a8ec594ca23ff52b9a517218214c9/blob
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <c10/util/Optional.h>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/_cslt_compress_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::_cslt_compress(Tensor input) -> Tensor
|
| 26 |
+
inline at::Tensor _cslt_compress(const at::Tensor & input) {
|
| 27 |
+
return at::_ops::_cslt_compress::call(input);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
}
|
shared/package-files/32/320f996f1f43e0a3bf44729c901672b9a07966798be64ff26f0f953aff41021a/blob
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cuda {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor cudnn_affine_grid_generator(const at::Tensor & theta, int64_t N, int64_t C, int64_t H, int64_t W);
|
| 21 |
+
|
| 22 |
+
} // namespace cuda
|
| 23 |
+
} // namespace at
|
shared/package-files/32/32108975cdae6500033fd995ff28642facdcfabeb25e22f82894d3f488d0c868/blob
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <c10/util/Optional.h>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/_sparse_csr_prod_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::_sparse_csr_prod.dim_dtype(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
|
| 26 |
+
inline at::Tensor _sparse_csr_prod(const at::Tensor & self, at::IntArrayRef dim, bool keepdim=false, c10::optional<at::ScalarType> dtype=c10::nullopt) {
|
| 27 |
+
return at::_ops::_sparse_csr_prod_dim_dtype::call(self, dim, keepdim, dtype);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// aten::_sparse_csr_prod.dim_dtype_out(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
|
| 31 |
+
inline at::Tensor & _sparse_csr_prod_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef dim, bool keepdim=false, c10::optional<at::ScalarType> dtype=c10::nullopt) {
|
| 32 |
+
return at::_ops::_sparse_csr_prod_dim_dtype_out::call(self, dim, keepdim, dtype, out);
|
| 33 |
+
}
|
| 34 |
+
// aten::_sparse_csr_prod.dim_dtype_out(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
|
| 35 |
+
inline at::Tensor & _sparse_csr_prod_outf(const at::Tensor & self, at::IntArrayRef dim, bool keepdim, c10::optional<at::ScalarType> dtype, at::Tensor & out) {
|
| 36 |
+
return at::_ops::_sparse_csr_prod_dim_dtype_out::call(self, dim, keepdim, dtype, out);
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
}
|
shared/package-files/32/3211959beba2d9a5e95409567047d8ff854d4f9e77d8e623d030a34943ac516e/blob
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3211959beba2d9a5e95409567047d8ff854d4f9e77d8e623d030a34943ac516e
|
| 3 |
+
size 14798681
|
shared/package-files/32/321245e3a66997b61f2214325015e61b9a64398230c37092ae487220afc52f9f/blob
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
@generated by mypy-protobuf. Do not edit manually!
|
| 3 |
+
isort:skip_file
|
| 4 |
+
"""
|
| 5 |
+
from google.protobuf.descriptor import (
|
| 6 |
+
Descriptor as google___protobuf___descriptor___Descriptor,
|
| 7 |
+
EnumDescriptor as google___protobuf___descriptor___EnumDescriptor,
|
| 8 |
+
FileDescriptor as google___protobuf___descriptor___FileDescriptor,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
from google.protobuf.descriptor_pb2 import (
|
| 12 |
+
FileDescriptorProto as google___protobuf___descriptor_pb2___FileDescriptorProto,
|
| 13 |
+
GeneratedCodeInfo as google___protobuf___descriptor_pb2___GeneratedCodeInfo,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
from google.protobuf.internal.containers import (
|
| 17 |
+
RepeatedCompositeFieldContainer as google___protobuf___internal___containers___RepeatedCompositeFieldContainer,
|
| 18 |
+
RepeatedScalarFieldContainer as google___protobuf___internal___containers___RepeatedScalarFieldContainer,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
from google.protobuf.internal.enum_type_wrapper import (
|
| 22 |
+
_EnumTypeWrapper as google___protobuf___internal___enum_type_wrapper____EnumTypeWrapper,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
from google.protobuf.message import (
|
| 26 |
+
Message as google___protobuf___message___Message,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
from typing import (
|
| 30 |
+
Iterable as typing___Iterable,
|
| 31 |
+
NewType as typing___NewType,
|
| 32 |
+
Optional as typing___Optional,
|
| 33 |
+
Text as typing___Text,
|
| 34 |
+
cast as typing___cast,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
from typing_extensions import (
|
| 38 |
+
Literal as typing_extensions___Literal,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
builtin___bool = bool
|
| 43 |
+
builtin___bytes = bytes
|
| 44 |
+
builtin___float = float
|
| 45 |
+
builtin___int = int
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
DESCRIPTOR: google___protobuf___descriptor___FileDescriptor = ...
|
| 49 |
+
|
| 50 |
+
class Version(google___protobuf___message___Message):
|
| 51 |
+
DESCRIPTOR: google___protobuf___descriptor___Descriptor = ...
|
| 52 |
+
major: builtin___int = ...
|
| 53 |
+
minor: builtin___int = ...
|
| 54 |
+
patch: builtin___int = ...
|
| 55 |
+
suffix: typing___Text = ...
|
| 56 |
+
|
| 57 |
+
def __init__(self,
|
| 58 |
+
*,
|
| 59 |
+
major : typing___Optional[builtin___int] = None,
|
| 60 |
+
minor : typing___Optional[builtin___int] = None,
|
| 61 |
+
patch : typing___Optional[builtin___int] = None,
|
| 62 |
+
suffix : typing___Optional[typing___Text] = None,
|
| 63 |
+
) -> None: ...
|
| 64 |
+
def HasField(self, field_name: typing_extensions___Literal[u"major",b"major",u"minor",b"minor",u"patch",b"patch",u"suffix",b"suffix"]) -> builtin___bool: ...
|
| 65 |
+
def ClearField(self, field_name: typing_extensions___Literal[u"major",b"major",u"minor",b"minor",u"patch",b"patch",u"suffix",b"suffix"]) -> None: ...
|
| 66 |
+
type___Version = Version
|
| 67 |
+
|
| 68 |
+
class CodeGeneratorRequest(google___protobuf___message___Message):
|
| 69 |
+
DESCRIPTOR: google___protobuf___descriptor___Descriptor = ...
|
| 70 |
+
file_to_generate: google___protobuf___internal___containers___RepeatedScalarFieldContainer[typing___Text] = ...
|
| 71 |
+
parameter: typing___Text = ...
|
| 72 |
+
|
| 73 |
+
@property
|
| 74 |
+
def proto_file(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[google___protobuf___descriptor_pb2___FileDescriptorProto]: ...
|
| 75 |
+
|
| 76 |
+
@property
|
| 77 |
+
def compiler_version(self) -> type___Version: ...
|
| 78 |
+
|
| 79 |
+
def __init__(self,
|
| 80 |
+
*,
|
| 81 |
+
file_to_generate : typing___Optional[typing___Iterable[typing___Text]] = None,
|
| 82 |
+
parameter : typing___Optional[typing___Text] = None,
|
| 83 |
+
proto_file : typing___Optional[typing___Iterable[google___protobuf___descriptor_pb2___FileDescriptorProto]] = None,
|
| 84 |
+
compiler_version : typing___Optional[type___Version] = None,
|
| 85 |
+
) -> None: ...
|
| 86 |
+
def HasField(self, field_name: typing_extensions___Literal[u"compiler_version",b"compiler_version",u"parameter",b"parameter"]) -> builtin___bool: ...
|
| 87 |
+
def ClearField(self, field_name: typing_extensions___Literal[u"compiler_version",b"compiler_version",u"file_to_generate",b"file_to_generate",u"parameter",b"parameter",u"proto_file",b"proto_file"]) -> None: ...
|
| 88 |
+
type___CodeGeneratorRequest = CodeGeneratorRequest
|
| 89 |
+
|
| 90 |
+
class CodeGeneratorResponse(google___protobuf___message___Message):
|
| 91 |
+
DESCRIPTOR: google___protobuf___descriptor___Descriptor = ...
|
| 92 |
+
FeatureValue = typing___NewType('FeatureValue', builtin___int)
|
| 93 |
+
type___FeatureValue = FeatureValue
|
| 94 |
+
Feature: _Feature
|
| 95 |
+
class _Feature(google___protobuf___internal___enum_type_wrapper____EnumTypeWrapper[CodeGeneratorResponse.FeatureValue]):
|
| 96 |
+
DESCRIPTOR: google___protobuf___descriptor___EnumDescriptor = ...
|
| 97 |
+
FEATURE_NONE = typing___cast(CodeGeneratorResponse.FeatureValue, 0)
|
| 98 |
+
FEATURE_PROTO3_OPTIONAL = typing___cast(CodeGeneratorResponse.FeatureValue, 1)
|
| 99 |
+
FEATURE_NONE = typing___cast(CodeGeneratorResponse.FeatureValue, 0)
|
| 100 |
+
FEATURE_PROTO3_OPTIONAL = typing___cast(CodeGeneratorResponse.FeatureValue, 1)
|
| 101 |
+
|
| 102 |
+
class File(google___protobuf___message___Message):
|
| 103 |
+
DESCRIPTOR: google___protobuf___descriptor___Descriptor = ...
|
| 104 |
+
name: typing___Text = ...
|
| 105 |
+
insertion_point: typing___Text = ...
|
| 106 |
+
content: typing___Text = ...
|
| 107 |
+
|
| 108 |
+
@property
|
| 109 |
+
def generated_code_info(self) -> google___protobuf___descriptor_pb2___GeneratedCodeInfo: ...
|
| 110 |
+
|
| 111 |
+
def __init__(self,
|
| 112 |
+
*,
|
| 113 |
+
name : typing___Optional[typing___Text] = None,
|
| 114 |
+
insertion_point : typing___Optional[typing___Text] = None,
|
| 115 |
+
content : typing___Optional[typing___Text] = None,
|
| 116 |
+
generated_code_info : typing___Optional[google___protobuf___descriptor_pb2___GeneratedCodeInfo] = None,
|
| 117 |
+
) -> None: ...
|
| 118 |
+
def HasField(self, field_name: typing_extensions___Literal[u"content",b"content",u"generated_code_info",b"generated_code_info",u"insertion_point",b"insertion_point",u"name",b"name"]) -> builtin___bool: ...
|
| 119 |
+
def ClearField(self, field_name: typing_extensions___Literal[u"content",b"content",u"generated_code_info",b"generated_code_info",u"insertion_point",b"insertion_point",u"name",b"name"]) -> None: ...
|
| 120 |
+
type___File = File
|
| 121 |
+
|
| 122 |
+
error: typing___Text = ...
|
| 123 |
+
supported_features: builtin___int = ...
|
| 124 |
+
|
| 125 |
+
@property
|
| 126 |
+
def file(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___CodeGeneratorResponse.File]: ...
|
| 127 |
+
|
| 128 |
+
def __init__(self,
|
| 129 |
+
*,
|
| 130 |
+
error : typing___Optional[typing___Text] = None,
|
| 131 |
+
supported_features : typing___Optional[builtin___int] = None,
|
| 132 |
+
file : typing___Optional[typing___Iterable[type___CodeGeneratorResponse.File]] = None,
|
| 133 |
+
) -> None: ...
|
| 134 |
+
def HasField(self, field_name: typing_extensions___Literal[u"error",b"error",u"supported_features",b"supported_features"]) -> builtin___bool: ...
|
| 135 |
+
def ClearField(self, field_name: typing_extensions___Literal[u"error",b"error",u"file",b"file",u"supported_features",b"supported_features"]) -> None: ...
|
| 136 |
+
type___CodeGeneratorResponse = CodeGeneratorResponse
|
shared/package-files/32/3212543684feef77fea9442b687e6b7f67d93e5144135aa44fd5f0180e4c0591/blob
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <c10/util/Optional.h>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/slice_backward_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::slice_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt start, SymInt end, SymInt step) -> Tensor
|
| 26 |
+
inline at::Tensor slice_backward(const at::Tensor & grad_output, at::IntArrayRef input_sizes, int64_t dim, int64_t start, int64_t end, int64_t step) {
|
| 27 |
+
return at::_ops::slice_backward::call(grad_output, c10::fromIntArrayRefSlow(input_sizes), dim, start, end, step);
|
| 28 |
+
}
|
| 29 |
+
namespace symint {
|
| 30 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
|
| 31 |
+
at::Tensor slice_backward(const at::Tensor & grad_output, at::IntArrayRef input_sizes, int64_t dim, int64_t start, int64_t end, int64_t step) {
|
| 32 |
+
return at::_ops::slice_backward::call(grad_output, c10::fromIntArrayRefSlow(input_sizes), dim, start, end, step);
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
// aten::slice_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt start, SymInt end, SymInt step) -> Tensor
|
| 37 |
+
inline at::Tensor slice_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef input_sizes, int64_t dim, c10::SymInt start, c10::SymInt end, c10::SymInt step) {
|
| 38 |
+
return at::_ops::slice_backward::call(grad_output, input_sizes, dim, start, end, step);
|
| 39 |
+
}
|
| 40 |
+
namespace symint {
|
| 41 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
|
| 42 |
+
at::Tensor slice_backward(const at::Tensor & grad_output, c10::SymIntArrayRef input_sizes, int64_t dim, c10::SymInt start, c10::SymInt end, c10::SymInt step) {
|
| 43 |
+
return at::_ops::slice_backward::call(grad_output, input_sizes, dim, start, end, step);
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// aten::slice_backward.out(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt start, SymInt end, SymInt step, *, Tensor(a!) out) -> Tensor(a!)
|
| 48 |
+
inline at::Tensor & slice_backward_out(at::Tensor & out, const at::Tensor & grad_output, at::IntArrayRef input_sizes, int64_t dim, int64_t start, int64_t end, int64_t step) {
|
| 49 |
+
return at::_ops::slice_backward_out::call(grad_output, c10::fromIntArrayRefSlow(input_sizes), dim, start, end, step, out);
|
| 50 |
+
}
|
| 51 |
+
namespace symint {
|
| 52 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
|
| 53 |
+
at::Tensor & slice_backward_out(at::Tensor & out, const at::Tensor & grad_output, at::IntArrayRef input_sizes, int64_t dim, int64_t start, int64_t end, int64_t step) {
|
| 54 |
+
return at::_ops::slice_backward_out::call(grad_output, c10::fromIntArrayRefSlow(input_sizes), dim, start, end, step, out);
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
// aten::slice_backward.out(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt start, SymInt end, SymInt step, *, Tensor(a!) out) -> Tensor(a!)
|
| 59 |
+
inline at::Tensor & slice_backward_outf(const at::Tensor & grad_output, at::IntArrayRef input_sizes, int64_t dim, int64_t start, int64_t end, int64_t step, at::Tensor & out) {
|
| 60 |
+
return at::_ops::slice_backward_out::call(grad_output, c10::fromIntArrayRefSlow(input_sizes), dim, start, end, step, out);
|
| 61 |
+
}
|
| 62 |
+
namespace symint {
|
| 63 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
|
| 64 |
+
at::Tensor & slice_backward_outf(const at::Tensor & grad_output, at::IntArrayRef input_sizes, int64_t dim, int64_t start, int64_t end, int64_t step, at::Tensor & out) {
|
| 65 |
+
return at::_ops::slice_backward_out::call(grad_output, c10::fromIntArrayRefSlow(input_sizes), dim, start, end, step, out);
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
// aten::slice_backward.out(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt start, SymInt end, SymInt step, *, Tensor(a!) out) -> Tensor(a!)
|
| 70 |
+
inline at::Tensor & slice_backward_symint_out(at::Tensor & out, const at::Tensor & grad_output, c10::SymIntArrayRef input_sizes, int64_t dim, c10::SymInt start, c10::SymInt end, c10::SymInt step) {
|
| 71 |
+
return at::_ops::slice_backward_out::call(grad_output, input_sizes, dim, start, end, step, out);
|
| 72 |
+
}
|
| 73 |
+
namespace symint {
|
| 74 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
|
| 75 |
+
at::Tensor & slice_backward_out(at::Tensor & out, const at::Tensor & grad_output, c10::SymIntArrayRef input_sizes, int64_t dim, c10::SymInt start, c10::SymInt end, c10::SymInt step) {
|
| 76 |
+
return at::_ops::slice_backward_out::call(grad_output, input_sizes, dim, start, end, step, out);
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
// aten::slice_backward.out(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt start, SymInt end, SymInt step, *, Tensor(a!) out) -> Tensor(a!)
|
| 81 |
+
inline at::Tensor & slice_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef input_sizes, int64_t dim, c10::SymInt start, c10::SymInt end, c10::SymInt step, at::Tensor & out) {
|
| 82 |
+
return at::_ops::slice_backward_out::call(grad_output, input_sizes, dim, start, end, step, out);
|
| 83 |
+
}
|
| 84 |
+
namespace symint {
|
| 85 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
|
| 86 |
+
at::Tensor & slice_backward_outf(const at::Tensor & grad_output, c10::SymIntArrayRef input_sizes, int64_t dim, c10::SymInt start, c10::SymInt end, c10::SymInt step, at::Tensor & out) {
|
| 87 |
+
return at::_ops::slice_backward_out::call(grad_output, input_sizes, dim, start, end, step, out);
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
}
|
shared/package-files/32/3212bc4d893d7ebbc7cddea573d04eb8b5a6d7319c5658bf1154d70c5f28a16e/blob
ADDED
|
Binary file (8.68 kB). View file
|
|
|
shared/package-files/32/321333b3eaad9ecbf633186bc625d4a60c4c736def0fa00665add2ab899eecb1/blob
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test replace, coverage 78%."
|
| 2 |
+
|
| 3 |
+
from idlelib.replace import ReplaceDialog
|
| 4 |
+
import unittest
|
| 5 |
+
from test.support import requires
|
| 6 |
+
requires('gui')
|
| 7 |
+
from tkinter import Tk, Text
|
| 8 |
+
|
| 9 |
+
from unittest.mock import Mock
|
| 10 |
+
from idlelib.idle_test.mock_tk import Mbox
|
| 11 |
+
import idlelib.searchengine as se
|
| 12 |
+
|
| 13 |
+
orig_mbox = se.messagebox
|
| 14 |
+
showerror = Mbox.showerror
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class ReplaceDialogTest(unittest.TestCase):
|
| 18 |
+
|
| 19 |
+
@classmethod
|
| 20 |
+
def setUpClass(cls):
|
| 21 |
+
cls.root = Tk()
|
| 22 |
+
cls.root.withdraw()
|
| 23 |
+
se.messagebox = Mbox
|
| 24 |
+
cls.engine = se.SearchEngine(cls.root)
|
| 25 |
+
cls.dialog = ReplaceDialog(cls.root, cls.engine)
|
| 26 |
+
cls.dialog.bell = lambda: None
|
| 27 |
+
cls.dialog.ok = Mock()
|
| 28 |
+
cls.text = Text(cls.root)
|
| 29 |
+
cls.text.undo_block_start = Mock()
|
| 30 |
+
cls.text.undo_block_stop = Mock()
|
| 31 |
+
cls.dialog.text = cls.text
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def tearDownClass(cls):
|
| 35 |
+
se.messagebox = orig_mbox
|
| 36 |
+
del cls.text, cls.dialog, cls.engine
|
| 37 |
+
cls.root.destroy()
|
| 38 |
+
del cls.root
|
| 39 |
+
|
| 40 |
+
def setUp(self):
|
| 41 |
+
self.text.insert('insert', 'This is a sample sTring')
|
| 42 |
+
|
| 43 |
+
def tearDown(self):
|
| 44 |
+
self.engine.patvar.set('')
|
| 45 |
+
self.dialog.replvar.set('')
|
| 46 |
+
self.engine.wordvar.set(False)
|
| 47 |
+
self.engine.casevar.set(False)
|
| 48 |
+
self.engine.revar.set(False)
|
| 49 |
+
self.engine.wrapvar.set(True)
|
| 50 |
+
self.engine.backvar.set(False)
|
| 51 |
+
showerror.title = ''
|
| 52 |
+
showerror.message = ''
|
| 53 |
+
self.text.delete('1.0', 'end')
|
| 54 |
+
|
| 55 |
+
def test_replace_simple(self):
|
| 56 |
+
# Test replace function with all options at default setting.
|
| 57 |
+
# Wrap around - True
|
| 58 |
+
# Regular Expression - False
|
| 59 |
+
# Match case - False
|
| 60 |
+
# Match word - False
|
| 61 |
+
# Direction - Forwards
|
| 62 |
+
text = self.text
|
| 63 |
+
equal = self.assertEqual
|
| 64 |
+
pv = self.engine.patvar
|
| 65 |
+
rv = self.dialog.replvar
|
| 66 |
+
replace = self.dialog.replace_it
|
| 67 |
+
|
| 68 |
+
# test accessor method
|
| 69 |
+
self.engine.setpat('asdf')
|
| 70 |
+
equal(self.engine.getpat(), pv.get())
|
| 71 |
+
|
| 72 |
+
# text found and replaced
|
| 73 |
+
pv.set('a')
|
| 74 |
+
rv.set('asdf')
|
| 75 |
+
replace()
|
| 76 |
+
equal(text.get('1.8', '1.12'), 'asdf')
|
| 77 |
+
|
| 78 |
+
# don't "match word" case
|
| 79 |
+
text.mark_set('insert', '1.0')
|
| 80 |
+
pv.set('is')
|
| 81 |
+
rv.set('hello')
|
| 82 |
+
replace()
|
| 83 |
+
equal(text.get('1.2', '1.7'), 'hello')
|
| 84 |
+
|
| 85 |
+
# don't "match case" case
|
| 86 |
+
pv.set('string')
|
| 87 |
+
rv.set('world')
|
| 88 |
+
replace()
|
| 89 |
+
equal(text.get('1.23', '1.28'), 'world')
|
| 90 |
+
|
| 91 |
+
# without "regular expression" case
|
| 92 |
+
text.mark_set('insert', 'end')
|
| 93 |
+
text.insert('insert', '\nline42:')
|
| 94 |
+
before_text = text.get('1.0', 'end')
|
| 95 |
+
pv.set(r'[a-z][\d]+')
|
| 96 |
+
replace()
|
| 97 |
+
after_text = text.get('1.0', 'end')
|
| 98 |
+
equal(before_text, after_text)
|
| 99 |
+
|
| 100 |
+
# test with wrap around selected and complete a cycle
|
| 101 |
+
text.mark_set('insert', '1.9')
|
| 102 |
+
pv.set('i')
|
| 103 |
+
rv.set('j')
|
| 104 |
+
replace()
|
| 105 |
+
equal(text.get('1.8'), 'i')
|
| 106 |
+
equal(text.get('2.1'), 'j')
|
| 107 |
+
replace()
|
| 108 |
+
equal(text.get('2.1'), 'j')
|
| 109 |
+
equal(text.get('1.8'), 'j')
|
| 110 |
+
before_text = text.get('1.0', 'end')
|
| 111 |
+
replace()
|
| 112 |
+
after_text = text.get('1.0', 'end')
|
| 113 |
+
equal(before_text, after_text)
|
| 114 |
+
|
| 115 |
+
# text not found
|
| 116 |
+
before_text = text.get('1.0', 'end')
|
| 117 |
+
pv.set('foobar')
|
| 118 |
+
replace()
|
| 119 |
+
after_text = text.get('1.0', 'end')
|
| 120 |
+
equal(before_text, after_text)
|
| 121 |
+
|
| 122 |
+
# test access method
|
| 123 |
+
self.dialog.find_it(0)
|
| 124 |
+
|
| 125 |
+
def test_replace_wrap_around(self):
|
| 126 |
+
text = self.text
|
| 127 |
+
equal = self.assertEqual
|
| 128 |
+
pv = self.engine.patvar
|
| 129 |
+
rv = self.dialog.replvar
|
| 130 |
+
replace = self.dialog.replace_it
|
| 131 |
+
self.engine.wrapvar.set(False)
|
| 132 |
+
|
| 133 |
+
# replace candidate found both after and before 'insert'
|
| 134 |
+
text.mark_set('insert', '1.4')
|
| 135 |
+
pv.set('i')
|
| 136 |
+
rv.set('j')
|
| 137 |
+
replace()
|
| 138 |
+
equal(text.get('1.2'), 'i')
|
| 139 |
+
equal(text.get('1.5'), 'j')
|
| 140 |
+
replace()
|
| 141 |
+
equal(text.get('1.2'), 'i')
|
| 142 |
+
equal(text.get('1.20'), 'j')
|
| 143 |
+
replace()
|
| 144 |
+
equal(text.get('1.2'), 'i')
|
| 145 |
+
|
| 146 |
+
# replace candidate found only before 'insert'
|
| 147 |
+
text.mark_set('insert', '1.8')
|
| 148 |
+
pv.set('is')
|
| 149 |
+
before_text = text.get('1.0', 'end')
|
| 150 |
+
replace()
|
| 151 |
+
after_text = text.get('1.0', 'end')
|
| 152 |
+
equal(before_text, after_text)
|
| 153 |
+
|
| 154 |
+
def test_replace_whole_word(self):
|
| 155 |
+
text = self.text
|
| 156 |
+
equal = self.assertEqual
|
| 157 |
+
pv = self.engine.patvar
|
| 158 |
+
rv = self.dialog.replvar
|
| 159 |
+
replace = self.dialog.replace_it
|
| 160 |
+
self.engine.wordvar.set(True)
|
| 161 |
+
|
| 162 |
+
pv.set('is')
|
| 163 |
+
rv.set('hello')
|
| 164 |
+
replace()
|
| 165 |
+
equal(text.get('1.0', '1.4'), 'This')
|
| 166 |
+
equal(text.get('1.5', '1.10'), 'hello')
|
| 167 |
+
|
| 168 |
+
def test_replace_match_case(self):
|
| 169 |
+
equal = self.assertEqual
|
| 170 |
+
text = self.text
|
| 171 |
+
pv = self.engine.patvar
|
| 172 |
+
rv = self.dialog.replvar
|
| 173 |
+
replace = self.dialog.replace_it
|
| 174 |
+
self.engine.casevar.set(True)
|
| 175 |
+
|
| 176 |
+
before_text = self.text.get('1.0', 'end')
|
| 177 |
+
pv.set('this')
|
| 178 |
+
rv.set('that')
|
| 179 |
+
replace()
|
| 180 |
+
after_text = self.text.get('1.0', 'end')
|
| 181 |
+
equal(before_text, after_text)
|
| 182 |
+
|
| 183 |
+
pv.set('This')
|
| 184 |
+
replace()
|
| 185 |
+
equal(text.get('1.0', '1.4'), 'that')
|
| 186 |
+
|
| 187 |
+
def test_replace_regex(self):
|
| 188 |
+
equal = self.assertEqual
|
| 189 |
+
text = self.text
|
| 190 |
+
pv = self.engine.patvar
|
| 191 |
+
rv = self.dialog.replvar
|
| 192 |
+
replace = self.dialog.replace_it
|
| 193 |
+
self.engine.revar.set(True)
|
| 194 |
+
|
| 195 |
+
before_text = text.get('1.0', 'end')
|
| 196 |
+
pv.set(r'[a-z][\d]+')
|
| 197 |
+
rv.set('hello')
|
| 198 |
+
replace()
|
| 199 |
+
after_text = text.get('1.0', 'end')
|
| 200 |
+
equal(before_text, after_text)
|
| 201 |
+
|
| 202 |
+
text.insert('insert', '\nline42')
|
| 203 |
+
replace()
|
| 204 |
+
equal(text.get('2.0', '2.8'), 'linhello')
|
| 205 |
+
|
| 206 |
+
pv.set('')
|
| 207 |
+
replace()
|
| 208 |
+
self.assertIn('error', showerror.title)
|
| 209 |
+
self.assertIn('Empty', showerror.message)
|
| 210 |
+
|
| 211 |
+
pv.set(r'[\d')
|
| 212 |
+
replace()
|
| 213 |
+
self.assertIn('error', showerror.title)
|
| 214 |
+
self.assertIn('Pattern', showerror.message)
|
| 215 |
+
|
| 216 |
+
showerror.title = ''
|
| 217 |
+
showerror.message = ''
|
| 218 |
+
pv.set('[a]')
|
| 219 |
+
rv.set('test\\')
|
| 220 |
+
replace()
|
| 221 |
+
self.assertIn('error', showerror.title)
|
| 222 |
+
self.assertIn('Invalid Replace Expression', showerror.message)
|
| 223 |
+
|
| 224 |
+
# test access method
|
| 225 |
+
self.engine.setcookedpat("?")
|
| 226 |
+
equal(pv.get(), "\\?")
|
| 227 |
+
|
| 228 |
+
def test_replace_backwards(self):
|
| 229 |
+
equal = self.assertEqual
|
| 230 |
+
text = self.text
|
| 231 |
+
pv = self.engine.patvar
|
| 232 |
+
rv = self.dialog.replvar
|
| 233 |
+
replace = self.dialog.replace_it
|
| 234 |
+
self.engine.backvar.set(True)
|
| 235 |
+
|
| 236 |
+
text.insert('insert', '\nis as ')
|
| 237 |
+
|
| 238 |
+
pv.set('is')
|
| 239 |
+
rv.set('was')
|
| 240 |
+
replace()
|
| 241 |
+
equal(text.get('1.2', '1.4'), 'is')
|
| 242 |
+
equal(text.get('2.0', '2.3'), 'was')
|
| 243 |
+
replace()
|
| 244 |
+
equal(text.get('1.5', '1.8'), 'was')
|
| 245 |
+
replace()
|
| 246 |
+
equal(text.get('1.2', '1.5'), 'was')
|
| 247 |
+
|
| 248 |
+
def test_replace_all(self):
|
| 249 |
+
text = self.text
|
| 250 |
+
pv = self.engine.patvar
|
| 251 |
+
rv = self.dialog.replvar
|
| 252 |
+
replace_all = self.dialog.replace_all
|
| 253 |
+
|
| 254 |
+
text.insert('insert', '\n')
|
| 255 |
+
text.insert('insert', text.get('1.0', 'end')*100)
|
| 256 |
+
pv.set('is')
|
| 257 |
+
rv.set('was')
|
| 258 |
+
replace_all()
|
| 259 |
+
self.assertNotIn('is', text.get('1.0', 'end'))
|
| 260 |
+
|
| 261 |
+
self.engine.revar.set(True)
|
| 262 |
+
pv.set('')
|
| 263 |
+
replace_all()
|
| 264 |
+
self.assertIn('error', showerror.title)
|
| 265 |
+
self.assertIn('Empty', showerror.message)
|
| 266 |
+
|
| 267 |
+
pv.set('[s][T]')
|
| 268 |
+
rv.set('\\')
|
| 269 |
+
replace_all()
|
| 270 |
+
|
| 271 |
+
self.engine.revar.set(False)
|
| 272 |
+
pv.set('text which is not present')
|
| 273 |
+
rv.set('foobar')
|
| 274 |
+
replace_all()
|
| 275 |
+
|
| 276 |
+
def test_default_command(self):
|
| 277 |
+
text = self.text
|
| 278 |
+
pv = self.engine.patvar
|
| 279 |
+
rv = self.dialog.replvar
|
| 280 |
+
replace_find = self.dialog.default_command
|
| 281 |
+
equal = self.assertEqual
|
| 282 |
+
|
| 283 |
+
pv.set('This')
|
| 284 |
+
rv.set('was')
|
| 285 |
+
replace_find()
|
| 286 |
+
equal(text.get('sel.first', 'sel.last'), 'was')
|
| 287 |
+
|
| 288 |
+
self.engine.revar.set(True)
|
| 289 |
+
pv.set('')
|
| 290 |
+
replace_find()
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
if __name__ == '__main__':
|
| 294 |
+
unittest.main(verbosity=2)
|
shared/package-files/32/32142548019430c5f8baba4dab0f88e8d2b663c846343045d375f7749dce490b/blob
ADDED
|
Binary file (1.92 kB). View file
|
|
|
shared/package-files/32/3216fd20e5c0bf873a9e4936e10438cd135dbfc15c60a373707cc7d98e35312f/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 binary_cross_entropy_backward {
|
| 18 |
+
using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const c10::optional<at::Tensor> &, int64_t);
|
| 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::binary_cross_entropy_backward")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "binary_cross_entropy_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor")
|
| 24 |
+
static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction);
|
| 25 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API binary_cross_entropy_backward_grad_input {
|
| 29 |
+
using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, const c10::optional<at::Tensor> &, int64_t, 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::binary_cross_entropy_backward")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "grad_input")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "binary_cross_entropy_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) grad_input) -> Tensor(a!)")
|
| 35 |
+
static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, at::Tensor & grad_input);
|
| 36 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, at::Tensor & grad_input);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
}} // namespace at::_ops
|
shared/package-files/32/32183bd6f9e38dbe1f9b48d98230e8596f2b0093017a1f1a0c233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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.add import Add
|
| 2 |
+
from sympy.core.expr import unchanged
|
| 3 |
+
from sympy.core.mul import Mul
|
| 4 |
+
from sympy.core.symbol import symbols
|
| 5 |
+
from sympy.core.relational import Eq
|
| 6 |
+
from sympy.concrete.summations import Sum
|
| 7 |
+
from sympy.functions.elementary.complexes import im, re
|
| 8 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 9 |
+
from sympy.matrices.immutable import ImmutableDenseMatrix
|
| 10 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
| 11 |
+
from sympy.matrices.expressions.matadd import MatAdd
|
| 12 |
+
from sympy.matrices.expressions.special import (
|
| 13 |
+
ZeroMatrix, GenericZeroMatrix, Identity, GenericIdentity, OneMatrix)
|
| 14 |
+
from sympy.matrices.expressions.matmul import MatMul
|
| 15 |
+
from sympy.testing.pytest import raises
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_zero_matrix_creation():
|
| 19 |
+
assert unchanged(ZeroMatrix, 2, 2)
|
| 20 |
+
assert unchanged(ZeroMatrix, 0, 0)
|
| 21 |
+
raises(ValueError, lambda: ZeroMatrix(-1, 2))
|
| 22 |
+
raises(ValueError, lambda: ZeroMatrix(2.0, 2))
|
| 23 |
+
raises(ValueError, lambda: ZeroMatrix(2j, 2))
|
| 24 |
+
raises(ValueError, lambda: ZeroMatrix(2, -1))
|
| 25 |
+
raises(ValueError, lambda: ZeroMatrix(2, 2.0))
|
| 26 |
+
raises(ValueError, lambda: ZeroMatrix(2, 2j))
|
| 27 |
+
|
| 28 |
+
n = symbols('n')
|
| 29 |
+
assert unchanged(ZeroMatrix, n, n)
|
| 30 |
+
n = symbols('n', integer=False)
|
| 31 |
+
raises(ValueError, lambda: ZeroMatrix(n, n))
|
| 32 |
+
n = symbols('n', negative=True)
|
| 33 |
+
raises(ValueError, lambda: ZeroMatrix(n, n))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_generic_zero_matrix():
|
| 37 |
+
z = GenericZeroMatrix()
|
| 38 |
+
n = symbols('n', integer=True)
|
| 39 |
+
A = MatrixSymbol("A", n, n)
|
| 40 |
+
|
| 41 |
+
assert z == z
|
| 42 |
+
assert z != A
|
| 43 |
+
assert A != z
|
| 44 |
+
|
| 45 |
+
assert z.is_ZeroMatrix
|
| 46 |
+
|
| 47 |
+
raises(TypeError, lambda: z.shape)
|
| 48 |
+
raises(TypeError, lambda: z.rows)
|
| 49 |
+
raises(TypeError, lambda: z.cols)
|
| 50 |
+
|
| 51 |
+
assert MatAdd() == z
|
| 52 |
+
assert MatAdd(z, A) == MatAdd(A)
|
| 53 |
+
# Make sure it is hashable
|
| 54 |
+
hash(z)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_identity_matrix_creation():
|
| 58 |
+
assert Identity(2)
|
| 59 |
+
assert Identity(0)
|
| 60 |
+
raises(ValueError, lambda: Identity(-1))
|
| 61 |
+
raises(ValueError, lambda: Identity(2.0))
|
| 62 |
+
raises(ValueError, lambda: Identity(2j))
|
| 63 |
+
|
| 64 |
+
n = symbols('n')
|
| 65 |
+
assert Identity(n)
|
| 66 |
+
n = symbols('n', integer=False)
|
| 67 |
+
raises(ValueError, lambda: Identity(n))
|
| 68 |
+
n = symbols('n', negative=True)
|
| 69 |
+
raises(ValueError, lambda: Identity(n))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_generic_identity():
|
| 73 |
+
I = GenericIdentity()
|
| 74 |
+
n = symbols('n', integer=True)
|
| 75 |
+
A = MatrixSymbol("A", n, n)
|
| 76 |
+
|
| 77 |
+
assert I == I
|
| 78 |
+
assert I != A
|
| 79 |
+
assert A != I
|
| 80 |
+
|
| 81 |
+
assert I.is_Identity
|
| 82 |
+
assert I**-1 == I
|
| 83 |
+
|
| 84 |
+
raises(TypeError, lambda: I.shape)
|
| 85 |
+
raises(TypeError, lambda: I.rows)
|
| 86 |
+
raises(TypeError, lambda: I.cols)
|
| 87 |
+
|
| 88 |
+
assert MatMul() == I
|
| 89 |
+
assert MatMul(I, A) == MatMul(A)
|
| 90 |
+
# Make sure it is hashable
|
| 91 |
+
hash(I)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_one_matrix_creation():
|
| 95 |
+
assert OneMatrix(2, 2)
|
| 96 |
+
assert OneMatrix(0, 0)
|
| 97 |
+
assert Eq(OneMatrix(1, 1), Identity(1))
|
| 98 |
+
raises(ValueError, lambda: OneMatrix(-1, 2))
|
| 99 |
+
raises(ValueError, lambda: OneMatrix(2.0, 2))
|
| 100 |
+
raises(ValueError, lambda: OneMatrix(2j, 2))
|
| 101 |
+
raises(ValueError, lambda: OneMatrix(2, -1))
|
| 102 |
+
raises(ValueError, lambda: OneMatrix(2, 2.0))
|
| 103 |
+
raises(ValueError, lambda: OneMatrix(2, 2j))
|
| 104 |
+
|
| 105 |
+
n = symbols('n')
|
| 106 |
+
assert OneMatrix(n, n)
|
| 107 |
+
n = symbols('n', integer=False)
|
| 108 |
+
raises(ValueError, lambda: OneMatrix(n, n))
|
| 109 |
+
n = symbols('n', negative=True)
|
| 110 |
+
raises(ValueError, lambda: OneMatrix(n, n))
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def test_ZeroMatrix():
|
| 114 |
+
n, m = symbols('n m', integer=True)
|
| 115 |
+
A = MatrixSymbol('A', n, m)
|
| 116 |
+
Z = ZeroMatrix(n, m)
|
| 117 |
+
|
| 118 |
+
assert A + Z == A
|
| 119 |
+
assert A*Z.T == ZeroMatrix(n, n)
|
| 120 |
+
assert Z*A.T == ZeroMatrix(n, n)
|
| 121 |
+
assert A - A == ZeroMatrix(*A.shape)
|
| 122 |
+
|
| 123 |
+
assert Z
|
| 124 |
+
|
| 125 |
+
assert Z.transpose() == ZeroMatrix(m, n)
|
| 126 |
+
assert Z.conjugate() == Z
|
| 127 |
+
assert Z.adjoint() == ZeroMatrix(m, n)
|
| 128 |
+
assert re(Z) == Z
|
| 129 |
+
assert im(Z) == Z
|
| 130 |
+
|
| 131 |
+
assert ZeroMatrix(n, n)**0 == Identity(n)
|
| 132 |
+
assert ZeroMatrix(3, 3).as_explicit() == ImmutableDenseMatrix.zeros(3, 3)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def test_ZeroMatrix_doit():
|
| 136 |
+
n = symbols('n', integer=True)
|
| 137 |
+
Znn = ZeroMatrix(Add(n, n, evaluate=False), n)
|
| 138 |
+
assert isinstance(Znn.rows, Add)
|
| 139 |
+
assert Znn.doit() == ZeroMatrix(2*n, n)
|
| 140 |
+
assert isinstance(Znn.doit().rows, Mul)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_OneMatrix():
|
| 144 |
+
n, m = symbols('n m', integer=True)
|
| 145 |
+
A = MatrixSymbol('A', n, m)
|
| 146 |
+
U = OneMatrix(n, m)
|
| 147 |
+
|
| 148 |
+
assert U.shape == (n, m)
|
| 149 |
+
assert isinstance(A + U, Add)
|
| 150 |
+
assert U.transpose() == OneMatrix(m, n)
|
| 151 |
+
assert U.conjugate() == U
|
| 152 |
+
assert U.adjoint() == OneMatrix(m, n)
|
| 153 |
+
assert re(U) == U
|
| 154 |
+
assert im(U) == ZeroMatrix(n, m)
|
| 155 |
+
|
| 156 |
+
assert OneMatrix(n, n) ** 0 == Identity(n)
|
| 157 |
+
|
| 158 |
+
U = OneMatrix(n, n)
|
| 159 |
+
assert U[1, 2] == 1
|
| 160 |
+
|
| 161 |
+
U = OneMatrix(2, 3)
|
| 162 |
+
assert U.as_explicit() == ImmutableDenseMatrix.ones(2, 3)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def test_OneMatrix_doit():
|
| 166 |
+
n = symbols('n', integer=True)
|
| 167 |
+
Unn = OneMatrix(Add(n, n, evaluate=False), n)
|
| 168 |
+
assert isinstance(Unn.rows, Add)
|
| 169 |
+
assert Unn.doit() == OneMatrix(2 * n, n)
|
| 170 |
+
assert isinstance(Unn.doit().rows, Mul)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def test_OneMatrix_mul():
|
| 174 |
+
n, m, k = symbols('n m k', integer=True)
|
| 175 |
+
w = MatrixSymbol('w', n, 1)
|
| 176 |
+
assert OneMatrix(n, m) * OneMatrix(m, k) == OneMatrix(n, k) * m
|
| 177 |
+
assert w * OneMatrix(1, 1) == w
|
| 178 |
+
assert OneMatrix(1, 1) * w.T == w.T
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def test_Identity():
|
| 182 |
+
n, m = symbols('n m', integer=True)
|
| 183 |
+
A = MatrixSymbol('A', n, m)
|
| 184 |
+
i, j = symbols('i j')
|
| 185 |
+
|
| 186 |
+
In = Identity(n)
|
| 187 |
+
Im = Identity(m)
|
| 188 |
+
|
| 189 |
+
assert A*Im == A
|
| 190 |
+
assert In*A == A
|
| 191 |
+
|
| 192 |
+
assert In.transpose() == In
|
| 193 |
+
assert In.inverse() == In
|
| 194 |
+
assert In.conjugate() == In
|
| 195 |
+
assert In.adjoint() == In
|
| 196 |
+
assert re(In) == In
|
| 197 |
+
assert im(In) == ZeroMatrix(n, n)
|
| 198 |
+
|
| 199 |
+
assert In[i, j] != 0
|
| 200 |
+
assert Sum(In[i, j], (i, 0, n-1), (j, 0, n-1)).subs(n,3).doit() == 3
|
| 201 |
+
assert Sum(Sum(In[i, j], (i, 0, n-1)), (j, 0, n-1)).subs(n,3).doit() == 3
|
| 202 |
+
|
| 203 |
+
# If range exceeds the limit `(0, n-1)`, do not remove `Piecewise`:
|
| 204 |
+
expr = Sum(In[i, j], (i, 0, n-1))
|
| 205 |
+
assert expr.doit() == 1
|
| 206 |
+
expr = Sum(In[i, j], (i, 0, n-2))
|
| 207 |
+
assert expr.doit().dummy_eq(
|
| 208 |
+
Piecewise(
|
| 209 |
+
(1, (j >= 0) & (j <= n-2)),
|
| 210 |
+
(0, True)
|
| 211 |
+
)
|
| 212 |
+
)
|
| 213 |
+
expr = Sum(In[i, j], (i, 1, n-1))
|
| 214 |
+
assert expr.doit().dummy_eq(
|
| 215 |
+
Piecewise(
|
| 216 |
+
(1, (j >= 1) & (j <= n-1)),
|
| 217 |
+
(0, True)
|
| 218 |
+
)
|
| 219 |
+
)
|
| 220 |
+
assert Identity(3).as_explicit() == ImmutableDenseMatrix.eye(3)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def test_Identity_doit():
|
| 224 |
+
n = symbols('n', integer=True)
|
| 225 |
+
Inn = Identity(Add(n, n, evaluate=False))
|
| 226 |
+
assert isinstance(Inn.rows, Add)
|
| 227 |
+
assert Inn.doit() == Identity(2*n)
|
| 228 |
+
assert isinstance(Inn.doit().rows, Mul)
|
shared/package-files/32/32191fb149da315122ea846b71f4e0a7a875ff54024bc6efc6dc2813a6ea652e/blob
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
class AESCCM(object):
|
| 4 |
+
def __init__(self, key: bytes, tag_length: Optional[int]) -> None: ...
|
| 5 |
+
def decrypt(self, nonce: bytes, data: bytes, associated_data: Optional[bytes]) -> bytes: ...
|
| 6 |
+
def encrypt(self, nonce: bytes, data: bytes, associated_data: Optional[bytes]) -> bytes: ...
|
| 7 |
+
@classmethod
|
| 8 |
+
def generate_key(cls, bit_length: int) -> bytes: ...
|
| 9 |
+
|
| 10 |
+
class AESGCM(object):
|
| 11 |
+
def __init__(self, key: bytes) -> None: ...
|
| 12 |
+
def decrypt(self, nonce: bytes, data: bytes, associated_data: Optional[bytes]) -> bytes: ...
|
| 13 |
+
def encrypt(self, nonce: bytes, data: bytes, associated_data: Optional[bytes]) -> bytes: ...
|
| 14 |
+
@classmethod
|
| 15 |
+
def generate_key(cls, bit_length: int) -> bytes: ...
|
| 16 |
+
|
| 17 |
+
class ChaCha20Poly1305(object):
|
| 18 |
+
def __init__(self, key: bytes) -> None: ...
|
| 19 |
+
def decrypt(self, nonce: bytes, data: bytes, associated_data: Optional[bytes]) -> bytes: ...
|
| 20 |
+
def encrypt(self, nonce: bytes, data: bytes, associated_data: Optional[bytes]) -> bytes: ...
|
| 21 |
+
@classmethod
|
| 22 |
+
def generate_key(cls) -> bytes: ...
|
shared/package-files/32/3219b2a5be56cf119d05a429c9269ef4d6e21499659047b3762b631da8dded10/blob
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.lexers.solidity
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
Lexers for Solidity.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from pygments.lexer import RegexLexer, bygroups, include, words
|
| 12 |
+
from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
|
| 13 |
+
Number, Punctuation, Whitespace
|
| 14 |
+
|
| 15 |
+
__all__ = ['SolidityLexer']
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SolidityLexer(RegexLexer):
|
| 19 |
+
"""
|
| 20 |
+
For Solidity source code.
|
| 21 |
+
|
| 22 |
+
.. versionadded:: 2.5
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
name = 'Solidity'
|
| 26 |
+
aliases = ['solidity']
|
| 27 |
+
filenames = ['*.sol']
|
| 28 |
+
mimetypes = []
|
| 29 |
+
|
| 30 |
+
datatype = (
|
| 31 |
+
r'\b(address|bool|(?:(?:bytes|hash|int|string|uint)(?:8|16|24|32|40|48|56|64'
|
| 32 |
+
r'|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208'
|
| 33 |
+
r'|216|224|232|240|248|256)?))\b'
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
tokens = {
|
| 37 |
+
'root': [
|
| 38 |
+
include('whitespace'),
|
| 39 |
+
include('comments'),
|
| 40 |
+
(r'\bpragma\s+solidity\b', Keyword, 'pragma'),
|
| 41 |
+
(r'\b(contract)(\s+)([a-zA-Z_]\w*)',
|
| 42 |
+
bygroups(Keyword, Whitespace, Name.Entity)),
|
| 43 |
+
(datatype + r'(\s+)((?:external|public|internal|private)\s+)?' +
|
| 44 |
+
r'([a-zA-Z_]\w*)',
|
| 45 |
+
bygroups(Keyword.Type, Whitespace, Keyword, Name.Variable)),
|
| 46 |
+
(r'\b(enum|event|function|struct)(\s+)([a-zA-Z_]\w*)',
|
| 47 |
+
bygroups(Keyword.Type, Whitespace, Name.Variable)),
|
| 48 |
+
(r'\b(msg|block|tx)\.([A-Za-z_][a-zA-Z0-9_]*)\b', Keyword),
|
| 49 |
+
(words((
|
| 50 |
+
'block', 'break', 'constant', 'constructor', 'continue',
|
| 51 |
+
'contract', 'do', 'else', 'external', 'false', 'for',
|
| 52 |
+
'function', 'if', 'import', 'inherited', 'internal', 'is',
|
| 53 |
+
'library', 'mapping', 'memory', 'modifier', 'msg', 'new',
|
| 54 |
+
'payable', 'private', 'public', 'require', 'return',
|
| 55 |
+
'returns', 'struct', 'suicide', 'throw', 'this', 'true',
|
| 56 |
+
'tx', 'var', 'while'), prefix=r'\b', suffix=r'\b'),
|
| 57 |
+
Keyword.Type),
|
| 58 |
+
(words(('keccak256',), prefix=r'\b', suffix=r'\b'), Name.Builtin),
|
| 59 |
+
(datatype, Keyword.Type),
|
| 60 |
+
include('constants'),
|
| 61 |
+
(r'[a-zA-Z_]\w*', Text),
|
| 62 |
+
(r'[~!%^&*+=|?:<>/-]', Operator),
|
| 63 |
+
(r'[.;{}(),\[\]]', Punctuation)
|
| 64 |
+
],
|
| 65 |
+
'comments': [
|
| 66 |
+
(r'//(\n|[\w\W]*?[^\\]\n)', Comment.Single),
|
| 67 |
+
(r'/(\\\n)?[*][\w\W]*?[*](\\\n)?/', Comment.Multiline),
|
| 68 |
+
(r'/(\\\n)?[*][\w\W]*', Comment.Multiline)
|
| 69 |
+
],
|
| 70 |
+
'constants': [
|
| 71 |
+
(r'("(\\"|.)*?")', String.Double),
|
| 72 |
+
(r"('(\\'|.)*?')", String.Single),
|
| 73 |
+
(r'\b0[xX][0-9a-fA-F]+\b', Number.Hex),
|
| 74 |
+
(r'\b\d+\b', Number.Decimal),
|
| 75 |
+
],
|
| 76 |
+
'pragma': [
|
| 77 |
+
include('whitespace'),
|
| 78 |
+
include('comments'),
|
| 79 |
+
(r'(\^|>=|<)(\s*)(\d+\.\d+\.\d+)',
|
| 80 |
+
bygroups(Operator, Whitespace, Keyword)),
|
| 81 |
+
(r';', Punctuation, '#pop')
|
| 82 |
+
],
|
| 83 |
+
'whitespace': [
|
| 84 |
+
(r'\s+', Whitespace),
|
| 85 |
+
(r'\n', Whitespace)
|
| 86 |
+
]
|
| 87 |
+
}
|
shared/package-files/32/321f0293b95d07de6fd2df7c9da5fee13bd9bbb8ae47241731c526ba427c1e2f/blob
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:321f0293b95d07de6fd2df7c9da5fee13bd9bbb8ae47241731c526ba427c1e2f
|
| 3 |
+
size 436640
|
shared/package-files/32/3221d56abebe6de504615129a97391217e1ff06dbd238ec3dfa92b7a5b5d7e84/blob
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numpy.distutils.fcompiler import FCompiler
|
| 2 |
+
|
| 3 |
+
compilers = ['PathScaleFCompiler']
|
| 4 |
+
|
| 5 |
+
class PathScaleFCompiler(FCompiler):
|
| 6 |
+
|
| 7 |
+
compiler_type = 'pathf95'
|
| 8 |
+
description = 'PathScale Fortran Compiler'
|
| 9 |
+
version_pattern = r'PathScale\(TM\) Compiler Suite: Version (?P<version>[\d.]+)'
|
| 10 |
+
|
| 11 |
+
executables = {
|
| 12 |
+
'version_cmd' : ["pathf95", "-version"],
|
| 13 |
+
'compiler_f77' : ["pathf95", "-fixedform"],
|
| 14 |
+
'compiler_fix' : ["pathf95", "-fixedform"],
|
| 15 |
+
'compiler_f90' : ["pathf95"],
|
| 16 |
+
'linker_so' : ["pathf95", "-shared"],
|
| 17 |
+
'archiver' : ["ar", "-cr"],
|
| 18 |
+
'ranlib' : ["ranlib"]
|
| 19 |
+
}
|
| 20 |
+
pic_flags = ['-fPIC']
|
| 21 |
+
module_dir_switch = '-module ' # Don't remove ending space!
|
| 22 |
+
module_include_switch = '-I'
|
| 23 |
+
|
| 24 |
+
def get_flags_opt(self):
|
| 25 |
+
return ['-O3']
|
| 26 |
+
def get_flags_debug(self):
|
| 27 |
+
return ['-g']
|
| 28 |
+
|
| 29 |
+
if __name__ == '__main__':
|
| 30 |
+
from distutils import log
|
| 31 |
+
log.set_verbosity(2)
|
| 32 |
+
from numpy.distutils import customized_fcompiler
|
| 33 |
+
print(customized_fcompiler(compiler='pathf95').get_version())
|
shared/package-files/32/32258d53e28c9d2c075b977388a296199f18363315d016297765aac4f57cec8f/blob
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <c10/util/Optional.h>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/_has_same_storage_numel_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::_has_same_storage_numel(Tensor self, Tensor other) -> bool
|
| 26 |
+
inline bool _has_same_storage_numel(const at::Tensor & self, const at::Tensor & other) {
|
| 27 |
+
return at::_ops::_has_same_storage_numel::call(self, other);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
}
|
shared/package-files/32/322745165c7c739c69422e50ecd36bf6e1b991115dc19348c6dec887aba48817/blob
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace compositeimplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor> min(const at::Tensor & self, at::Dimname dim, bool keepdim=false);
|
| 21 |
+
TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> min_out(at::Tensor & min, at::Tensor & min_indices, const at::Tensor & self, at::Dimname dim, bool keepdim=false);
|
| 22 |
+
TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> min_outf(const at::Tensor & self, at::Dimname dim, bool keepdim, at::Tensor & min, at::Tensor & min_indices);
|
| 23 |
+
TORCH_API at::Tensor min(const at::Tensor & self, const at::Tensor & other);
|
| 24 |
+
TORCH_API at::Tensor & min_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other);
|
| 25 |
+
TORCH_API at::Tensor & min_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
|
| 26 |
+
|
| 27 |
+
} // namespace compositeimplicitautograd
|
| 28 |
+
} // namespace at
|
shared/package-files/32/3227f4f6071f45f20edae842a8d37d382fcd5e080a8b36eec1acfa49c1b33141/blob
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas import (
|
| 5 |
+
DatetimeIndex,
|
| 6 |
+
Index,
|
| 7 |
+
date_range,
|
| 8 |
+
factorize,
|
| 9 |
+
)
|
| 10 |
+
import pandas._testing as tm
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestDatetimeIndexFactorize:
|
| 14 |
+
def test_factorize(self):
|
| 15 |
+
idx1 = DatetimeIndex(
|
| 16 |
+
["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"]
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp)
|
| 20 |
+
exp_idx = DatetimeIndex(["2014-01", "2014-02", "2014-03"])
|
| 21 |
+
|
| 22 |
+
arr, idx = idx1.factorize()
|
| 23 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
| 24 |
+
tm.assert_index_equal(idx, exp_idx)
|
| 25 |
+
assert idx.freq == exp_idx.freq
|
| 26 |
+
|
| 27 |
+
arr, idx = idx1.factorize(sort=True)
|
| 28 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
| 29 |
+
tm.assert_index_equal(idx, exp_idx)
|
| 30 |
+
assert idx.freq == exp_idx.freq
|
| 31 |
+
|
| 32 |
+
# tz must be preserved
|
| 33 |
+
idx1 = idx1.tz_localize("Asia/Tokyo")
|
| 34 |
+
exp_idx = exp_idx.tz_localize("Asia/Tokyo")
|
| 35 |
+
|
| 36 |
+
arr, idx = idx1.factorize()
|
| 37 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
| 38 |
+
tm.assert_index_equal(idx, exp_idx)
|
| 39 |
+
assert idx.freq == exp_idx.freq
|
| 40 |
+
|
| 41 |
+
idx2 = DatetimeIndex(
|
| 42 |
+
["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"]
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.intp)
|
| 46 |
+
exp_idx = DatetimeIndex(["2014-01", "2014-02", "2014-03"])
|
| 47 |
+
arr, idx = idx2.factorize(sort=True)
|
| 48 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
| 49 |
+
tm.assert_index_equal(idx, exp_idx)
|
| 50 |
+
assert idx.freq == exp_idx.freq
|
| 51 |
+
|
| 52 |
+
exp_arr = np.array([0, 0, 1, 2, 0, 2], dtype=np.intp)
|
| 53 |
+
exp_idx = DatetimeIndex(["2014-03", "2014-02", "2014-01"])
|
| 54 |
+
arr, idx = idx2.factorize()
|
| 55 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
| 56 |
+
tm.assert_index_equal(idx, exp_idx)
|
| 57 |
+
assert idx.freq == exp_idx.freq
|
| 58 |
+
|
| 59 |
+
def test_factorize_preserves_freq(self):
|
| 60 |
+
# GH#38120 freq should be preserved
|
| 61 |
+
idx3 = date_range("2000-01", periods=4, freq="ME", tz="Asia/Tokyo")
|
| 62 |
+
exp_arr = np.array([0, 1, 2, 3], dtype=np.intp)
|
| 63 |
+
|
| 64 |
+
arr, idx = idx3.factorize()
|
| 65 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
| 66 |
+
tm.assert_index_equal(idx, idx3)
|
| 67 |
+
assert idx.freq == idx3.freq
|
| 68 |
+
|
| 69 |
+
arr, idx = factorize(idx3)
|
| 70 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
| 71 |
+
tm.assert_index_equal(idx, idx3)
|
| 72 |
+
assert idx.freq == idx3.freq
|
| 73 |
+
|
| 74 |
+
def test_factorize_tz(self, tz_naive_fixture, index_or_series):
|
| 75 |
+
tz = tz_naive_fixture
|
| 76 |
+
# GH#13750
|
| 77 |
+
base = date_range("2016-11-05", freq="h", periods=100, tz=tz)
|
| 78 |
+
idx = base.repeat(5)
|
| 79 |
+
|
| 80 |
+
exp_arr = np.arange(100, dtype=np.intp).repeat(5)
|
| 81 |
+
|
| 82 |
+
obj = index_or_series(idx)
|
| 83 |
+
|
| 84 |
+
arr, res = obj.factorize()
|
| 85 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
| 86 |
+
expected = base._with_freq(None)
|
| 87 |
+
tm.assert_index_equal(res, expected)
|
| 88 |
+
assert res.freq == expected.freq
|
| 89 |
+
|
| 90 |
+
def test_factorize_dst(self, index_or_series):
|
| 91 |
+
# GH#13750
|
| 92 |
+
idx = date_range("2016-11-06", freq="h", periods=12, tz="US/Eastern")
|
| 93 |
+
obj = index_or_series(idx)
|
| 94 |
+
|
| 95 |
+
arr, res = obj.factorize()
|
| 96 |
+
tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp))
|
| 97 |
+
tm.assert_index_equal(res, idx)
|
| 98 |
+
if index_or_series is Index:
|
| 99 |
+
assert res.freq == idx.freq
|
| 100 |
+
|
| 101 |
+
idx = date_range("2016-06-13", freq="h", periods=12, tz="US/Eastern")
|
| 102 |
+
obj = index_or_series(idx)
|
| 103 |
+
|
| 104 |
+
arr, res = obj.factorize()
|
| 105 |
+
tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp))
|
| 106 |
+
tm.assert_index_equal(res, idx)
|
| 107 |
+
if index_or_series is Index:
|
| 108 |
+
assert res.freq == idx.freq
|
| 109 |
+
|
| 110 |
+
@pytest.mark.parametrize("sort", [True, False])
|
| 111 |
+
def test_factorize_no_freq_non_nano(self, tz_naive_fixture, sort):
|
| 112 |
+
# GH#51978 case that does not go through the fastpath based on
|
| 113 |
+
# non-None freq
|
| 114 |
+
tz = tz_naive_fixture
|
| 115 |
+
idx = date_range("2016-11-06", freq="h", periods=5, tz=tz)[[0, 4, 1, 3, 2]]
|
| 116 |
+
exp_codes, exp_uniques = idx.factorize(sort=sort)
|
| 117 |
+
|
| 118 |
+
res_codes, res_uniques = idx.as_unit("s").factorize(sort=sort)
|
| 119 |
+
|
| 120 |
+
tm.assert_numpy_array_equal(res_codes, exp_codes)
|
| 121 |
+
tm.assert_index_equal(res_uniques, exp_uniques.as_unit("s"))
|
| 122 |
+
|
| 123 |
+
res_codes, res_uniques = idx.as_unit("s").to_series().factorize(sort=sort)
|
| 124 |
+
tm.assert_numpy_array_equal(res_codes, exp_codes)
|
| 125 |
+
tm.assert_index_equal(res_uniques, exp_uniques.as_unit("s"))
|
shared/package-files/32/322a98cc2207bcd6cc1fe2dd4582effb84f410803b8432ade462d1d084532dd2/blob
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
import tempfile
|
| 4 |
+
import shutil
|
| 5 |
+
import json
|
| 6 |
+
from subprocess import check_call, check_output
|
| 7 |
+
from tarfile import TarFile
|
| 8 |
+
|
| 9 |
+
from dateutil.zoneinfo import METADATA_FN, ZONEFILENAME
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None):
|
| 13 |
+
"""Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar*
|
| 14 |
+
|
| 15 |
+
filename is the timezone tarball from ``ftp.iana.org/tz``.
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
tmpdir = tempfile.mkdtemp()
|
| 19 |
+
zonedir = os.path.join(tmpdir, "zoneinfo")
|
| 20 |
+
moduledir = os.path.dirname(__file__)
|
| 21 |
+
try:
|
| 22 |
+
with TarFile.open(filename) as tf:
|
| 23 |
+
for name in zonegroups:
|
| 24 |
+
tf.extract(name, tmpdir)
|
| 25 |
+
filepaths = [os.path.join(tmpdir, n) for n in zonegroups]
|
| 26 |
+
|
| 27 |
+
_run_zic(zonedir, filepaths)
|
| 28 |
+
|
| 29 |
+
# write metadata file
|
| 30 |
+
with open(os.path.join(zonedir, METADATA_FN), 'w') as f:
|
| 31 |
+
json.dump(metadata, f, indent=4, sort_keys=True)
|
| 32 |
+
target = os.path.join(moduledir, ZONEFILENAME)
|
| 33 |
+
with TarFile.open(target, "w:%s" % format) as tf:
|
| 34 |
+
for entry in os.listdir(zonedir):
|
| 35 |
+
entrypath = os.path.join(zonedir, entry)
|
| 36 |
+
tf.add(entrypath, entry)
|
| 37 |
+
finally:
|
| 38 |
+
shutil.rmtree(tmpdir)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _run_zic(zonedir, filepaths):
|
| 42 |
+
"""Calls the ``zic`` compiler in a compatible way to get a "fat" binary.
|
| 43 |
+
|
| 44 |
+
Recent versions of ``zic`` default to ``-b slim``, while older versions
|
| 45 |
+
don't even have the ``-b`` option (but default to "fat" binaries). The
|
| 46 |
+
current version of dateutil does not support Version 2+ TZif files, which
|
| 47 |
+
causes problems when used in conjunction with "slim" binaries, so this
|
| 48 |
+
function is used to ensure that we always get a "fat" binary.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
help_text = check_output(["zic", "--help"])
|
| 53 |
+
except OSError as e:
|
| 54 |
+
_print_on_nosuchfile(e)
|
| 55 |
+
raise
|
| 56 |
+
|
| 57 |
+
if b"-b " in help_text:
|
| 58 |
+
bloat_args = ["-b", "fat"]
|
| 59 |
+
else:
|
| 60 |
+
bloat_args = []
|
| 61 |
+
|
| 62 |
+
check_call(["zic"] + bloat_args + ["-d", zonedir] + filepaths)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _print_on_nosuchfile(e):
|
| 66 |
+
"""Print helpful troubleshooting message
|
| 67 |
+
|
| 68 |
+
e is an exception raised by subprocess.check_call()
|
| 69 |
+
|
| 70 |
+
"""
|
| 71 |
+
if e.errno == 2:
|
| 72 |
+
logging.error(
|
| 73 |
+
"Could not find zic. Perhaps you need to install "
|
| 74 |
+
"libc-bin or some other package that provides it, "
|
| 75 |
+
"or it's not in your PATH?")
|