diff --git a/.gitattributes b/.gitattributes index b716cbcc7f607f8c8720ffbde2e42cb2e019ab5c..35011b4d0af25864d7429bfc2ef1c2df4fba0eca 100644 --- a/.gitattributes +++ b/.gitattributes @@ -947,3 +947,39 @@ shared/package-files/cf/cfbd026d00067a99aa9f14d1d5aa48076a97ad39e7d32c49c8964a10 shared/package-files/cf/cfccd871b530fa1b23e6ed6ec1f43940cdb564930e6086a35d116e6636072077/blob filter=lfs diff=lfs merge=lfs -text shared/package-files/d0/d060a9597056170ec121b704840e838df98bece671673e490c84bc82c788fa83/blob filter=lfs diff=lfs merge=lfs -text shared/package-files/d0/d08783f85bb4a16dcd73eb9317000b97ce811a98e0c43d44566912b21427bf82/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d0/d0ffb4973b6651de10e60155e16d7f39a3ead8da0aa3b1a5be6fb181122a8f7d/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d1/d1077656f59bb84a73d5c477a4adafdd8761d037a58e4b5b9fed8f8dbb2275f9/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d1/d19d9d3c170a074e2c4ff56b606761e5d6686077a9460416e4691a0368d6b6b6/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d1/d1a0ed4d9a1da76ba5dab410441bb83f6415a841acdc130d20c6504dfaf11cde/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d1/d1efe233bd4d377b622ad09f65035bf89e2dfcbec5a0b0444c2e235c5773acd7/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d2/d2acdedbf3527da2d985ce1c3a9929efaecf0f1ba63056e2b6080591247e2c58/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d2/d2bc0b8127ab14cf1df3ae8fe4242829830ef54cc00ceafd720e68ef7e67f495/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d2/d2da887bd5aba8f90b9726beefe1a4dd174e541ef39952f69b3492df0591a9ba/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d3/d30758e332c4303643f19db8061f1e79956a86a625883d04fae87cc269a1d17e/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d3/d30adf6a4e7bac0145680e67ceed3e9d2ff4a2ca579a147cf8815a6949a2c42e/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d3/d30e994b09d9f30f7efeb6dc81fa05ab4a7be32b4e78c2b48fc3b6228197bfb1/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d3/d3193fe31df6de065d5f9c45edccb24076c9635c52711920feabfc03cf82c8e3/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d3/d32dfd0be03bd30fe392602e724b9d6fa0586c430b9be830373b644480005dd9/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d3/d35a02302739bc85f331fe098b3720b6890cbac159fb118d7497cd66ce77baa0/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d3/d3606ac2d52a59ae272e5b9aac1fd098a54424a51a45135fa3b2104e64a49386/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d3/d384478bd58d755f22fea782c703bff940e3bbd360709299ddfd1440ce6a725b/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d3/d3c3f7c9115cc2e890683e9783dd74ed139b39a6ab8a5b48793453943680e9f9/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d3/d3e2267ac18118806a4772d389c3fca4d5a01f40a0044dbc5a3951ca4dfb9260/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d3/d3ea52e7b6e968de0d884df1288193596fa95b803db4f92a18279a7398004475/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d4/d416d5e4b518c98b57b02f02b1a159659ba6395fcabd527f076fa6fdb7517ddb/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d4/d45be6bf592c88a6cd24910bb2ea3f254bbdac51e9edcfd1a3e3a43370d8b3c5/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d4/d493f50a33e82a4420494c54d1fca1539d177bdc27ab190bc5fe6e92f62fb637/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d4/d4d827a9d5d6453982f115f7e7bb448f2b23d64b5b89de61a64e838c2f936200/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d4/d4e8951ded34a4600e91fe80d4ac7854276eedd16f51bb353794b7d2c2831f70/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d5/d52293a81c168347002c88a81f2469cb8be72e7a527699946b68b4614b857dfe/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d6/d67eea63a4087be25684a220992163dd59b69edae920409aed2e90f2e98c0d63/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d6/d6c59efae8add1fbaa406a1007eca03df58ac39e657b175d7cb82682ce37369f/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d6/d6f9e4af876bfad3c56c075e1b07237354d5e06c9a55e9c266b222dfb2959080/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d7/d728ffa4ec2c862fea5d967d31cf087f19277c20070929c27a17eeedff1baef2/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d7/d73ecbbb51654522342ba0470a6263a9684e617c2b8374565fe3a79593f4b231/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d7/d7a4ad8c10ee00bc2de44643e236cfec19b8d50cb395752edfc7dca8ffd6cf57/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d7/d7d121e5f899fb71a1439aa3f7f51121e0ea64f30a736697072363fe38b30474/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d8/d8202427dad506a3249765966fe80d020ca7813e8fa3d110a428a76cca98aee7/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d8/d83125fd8622c1a69e29ca0aa80740c045420a4020db860f382926ff457b1331/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d8/d8649d1526f08fd0c1c2d6de0e7ef607e07f103f8f8670a83ade7c5d2d6a7a1a/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/d8/d87ed7aee3a3b78f1c2478f568a3a79e4010a110fccc3c9bad0a1ca414c917f2/blob filter=lfs diff=lfs merge=lfs -text diff --git a/shared/package-files/d0/d0ed059a6121cde784526964992365b87b995618654ce2041ead5873e8572c56/blob b/shared/package-files/d0/d0ed059a6121cde784526964992365b87b995618654ce2041ead5873e8572c56/blob new file mode 100644 index 0000000000000000000000000000000000000000..5f0a432ee5edbfb26ab1404a5ec71c1fdcc99a02 --- /dev/null +++ b/shared/package-files/d0/d0ed059a6121cde784526964992365b87b995618654ce2041ead5873e8572c56/blob @@ -0,0 +1,471 @@ +ERROR_FIRST: int +HASHCHK: int +NISAMCHK: int +NO: int +YES: int +CANT_CREATE_FILE: int +CANT_CREATE_TABLE: int +CANT_CREATE_DB: int +DB_CREATE_EXISTS: int +DB_DROP_EXISTS: int +DB_DROP_DELETE: int +DB_DROP_RMDIR: int +CANT_DELETE_FILE: int +CANT_FIND_SYSTEM_REC: int +CANT_GET_STAT: int +CANT_GET_WD: int +CANT_LOCK: int +CANT_OPEN_FILE: int +FILE_NOT_FOUND: int +CANT_READ_DIR: int +CANT_SET_WD: int +CHECKREAD: int +DISK_FULL: int +DUP_KEY: int +ERROR_ON_CLOSE: int +ERROR_ON_READ: int +ERROR_ON_RENAME: int +ERROR_ON_WRITE: int +FILE_USED: int +FILSORT_ABORT: int +FORM_NOT_FOUND: int +GET_ERRNO: int +ILLEGAL_HA: int +KEY_NOT_FOUND: int +NOT_FORM_FILE: int +NOT_KEYFILE: int +OLD_KEYFILE: int +OPEN_AS_READONLY: int +OUTOFMEMORY: int +OUT_OF_SORTMEMORY: int +UNEXPECTED_EOF: int +CON_COUNT_ERROR: int +OUT_OF_RESOURCES: int +BAD_HOST_ERROR: int +HANDSHAKE_ERROR: int +DBACCESS_DENIED_ERROR: int +ACCESS_DENIED_ERROR: int +NO_DB_ERROR: int +UNKNOWN_COM_ERROR: int +BAD_NULL_ERROR: int +BAD_DB_ERROR: int +TABLE_EXISTS_ERROR: int +BAD_TABLE_ERROR: int +NON_UNIQ_ERROR: int +SERVER_SHUTDOWN: int +BAD_FIELD_ERROR: int +WRONG_FIELD_WITH_GROUP: int +WRONG_GROUP_FIELD: int +WRONG_SUM_SELECT: int +WRONG_VALUE_COUNT: int +TOO_LONG_IDENT: int +DUP_FIELDNAME: int +DUP_KEYNAME: int +DUP_ENTRY: int +WRONG_FIELD_SPEC: int +PARSE_ERROR: int +EMPTY_QUERY: int +NONUNIQ_TABLE: int +INVALID_DEFAULT: int +MULTIPLE_PRI_KEY: int +TOO_MANY_KEYS: int +TOO_MANY_KEY_PARTS: int +TOO_LONG_KEY: int +KEY_COLUMN_DOES_NOT_EXITS: int +BLOB_USED_AS_KEY: int +TOO_BIG_FIELDLENGTH: int +WRONG_AUTO_KEY: int +READY: int +NORMAL_SHUTDOWN: int +GOT_SIGNAL: int +SHUTDOWN_COMPLETE: int +FORCING_CLOSE: int +IPSOCK_ERROR: int +NO_SUCH_INDEX: int +WRONG_FIELD_TERMINATORS: int +BLOBS_AND_NO_TERMINATED: int +TEXTFILE_NOT_READABLE: int +FILE_EXISTS_ERROR: int +LOAD_INFO: int +ALTER_INFO: int +WRONG_SUB_KEY: int +CANT_REMOVE_ALL_FIELDS: int +CANT_DROP_FIELD_OR_KEY: int +INSERT_INFO: int +UPDATE_TABLE_USED: int +NO_SUCH_THREAD: int +KILL_DENIED_ERROR: int +NO_TABLES_USED: int +TOO_BIG_SET: int +NO_UNIQUE_LOGFILE: int +TABLE_NOT_LOCKED_FOR_WRITE: int +TABLE_NOT_LOCKED: int +BLOB_CANT_HAVE_DEFAULT: int +WRONG_DB_NAME: int +WRONG_TABLE_NAME: int +TOO_BIG_SELECT: int +UNKNOWN_ERROR: int +UNKNOWN_PROCEDURE: int +WRONG_PARAMCOUNT_TO_PROCEDURE: int +WRONG_PARAMETERS_TO_PROCEDURE: int +UNKNOWN_TABLE: int +FIELD_SPECIFIED_TWICE: int +INVALID_GROUP_FUNC_USE: int +UNSUPPORTED_EXTENSION: int +TABLE_MUST_HAVE_COLUMNS: int +RECORD_FILE_FULL: int +UNKNOWN_CHARACTER_SET: int +TOO_MANY_TABLES: int +TOO_MANY_FIELDS: int +TOO_BIG_ROWSIZE: int +STACK_OVERRUN: int +WRONG_OUTER_JOIN: int +NULL_COLUMN_IN_INDEX: int +CANT_FIND_UDF: int +CANT_INITIALIZE_UDF: int +UDF_NO_PATHS: int +UDF_EXISTS: int +CANT_OPEN_LIBRARY: int +CANT_FIND_DL_ENTRY: int +FUNCTION_NOT_DEFINED: int +HOST_IS_BLOCKED: int +HOST_NOT_PRIVILEGED: int +PASSWORD_ANONYMOUS_USER: int +PASSWORD_NOT_ALLOWED: int +PASSWORD_NO_MATCH: int +UPDATE_INFO: int +CANT_CREATE_THREAD: int +WRONG_VALUE_COUNT_ON_ROW: int +CANT_REOPEN_TABLE: int +INVALID_USE_OF_NULL: int +REGEXP_ERROR: int +MIX_OF_GROUP_FUNC_AND_FIELDS: int +NONEXISTING_GRANT: int +TABLEACCESS_DENIED_ERROR: int +COLUMNACCESS_DENIED_ERROR: int +ILLEGAL_GRANT_FOR_TABLE: int +GRANT_WRONG_HOST_OR_USER: int +NO_SUCH_TABLE: int +NONEXISTING_TABLE_GRANT: int +NOT_ALLOWED_COMMAND: int +SYNTAX_ERROR: int +DELAYED_CANT_CHANGE_LOCK: int +TOO_MANY_DELAYED_THREADS: int +ABORTING_CONNECTION: int +NET_PACKET_TOO_LARGE: int +NET_READ_ERROR_FROM_PIPE: int +NET_FCNTL_ERROR: int +NET_PACKETS_OUT_OF_ORDER: int +NET_UNCOMPRESS_ERROR: int +NET_READ_ERROR: int +NET_READ_INTERRUPTED: int +NET_ERROR_ON_WRITE: int +NET_WRITE_INTERRUPTED: int +TOO_LONG_STRING: int +TABLE_CANT_HANDLE_BLOB: int +TABLE_CANT_HANDLE_AUTO_INCREMENT: int +DELAYED_INSERT_TABLE_LOCKED: int +WRONG_COLUMN_NAME: int +WRONG_KEY_COLUMN: int +WRONG_MRG_TABLE: int +DUP_UNIQUE: int +BLOB_KEY_WITHOUT_LENGTH: int +PRIMARY_CANT_HAVE_NULL: int +TOO_MANY_ROWS: int +REQUIRES_PRIMARY_KEY: int +NO_RAID_COMPILED: int +UPDATE_WITHOUT_KEY_IN_SAFE_MODE: int +KEY_DOES_NOT_EXITS: int +CHECK_NO_SUCH_TABLE: int +CHECK_NOT_IMPLEMENTED: int +CANT_DO_THIS_DURING_AN_TRANSACTION: int +ERROR_DURING_COMMIT: int +ERROR_DURING_ROLLBACK: int +ERROR_DURING_FLUSH_LOGS: int +ERROR_DURING_CHECKPOINT: int +NEW_ABORTING_CONNECTION: int +DUMP_NOT_IMPLEMENTED: int +FLUSH_MASTER_BINLOG_CLOSED: int +INDEX_REBUILD: int +MASTER: int +MASTER_NET_READ: int +MASTER_NET_WRITE: int +FT_MATCHING_KEY_NOT_FOUND: int +LOCK_OR_ACTIVE_TRANSACTION: int +UNKNOWN_SYSTEM_VARIABLE: int +CRASHED_ON_USAGE: int +CRASHED_ON_REPAIR: int +WARNING_NOT_COMPLETE_ROLLBACK: int +TRANS_CACHE_FULL: int +SLAVE_MUST_STOP: int +SLAVE_NOT_RUNNING: int +BAD_SLAVE: int +MASTER_INFO: int +SLAVE_THREAD: int +TOO_MANY_USER_CONNECTIONS: int +SET_CONSTANTS_ONLY: int +LOCK_WAIT_TIMEOUT: int +LOCK_TABLE_FULL: int +READ_ONLY_TRANSACTION: int +DROP_DB_WITH_READ_LOCK: int +CREATE_DB_WITH_READ_LOCK: int +WRONG_ARGUMENTS: int +NO_PERMISSION_TO_CREATE_USER: int +UNION_TABLES_IN_DIFFERENT_DIR: int +LOCK_DEADLOCK: int +TABLE_CANT_HANDLE_FT: int +CANNOT_ADD_FOREIGN: int +NO_REFERENCED_ROW: int +ROW_IS_REFERENCED: int +CONNECT_TO_MASTER: int +QUERY_ON_MASTER: int +ERROR_WHEN_EXECUTING_COMMAND: int +WRONG_USAGE: int +WRONG_NUMBER_OF_COLUMNS_IN_SELECT: int +CANT_UPDATE_WITH_READLOCK: int +MIXING_NOT_ALLOWED: int +DUP_ARGUMENT: int +USER_LIMIT_REACHED: int +SPECIFIC_ACCESS_DENIED_ERROR: int +LOCAL_VARIABLE: int +GLOBAL_VARIABLE: int +NO_DEFAULT: int +WRONG_VALUE_FOR_VAR: int +WRONG_TYPE_FOR_VAR: int +VAR_CANT_BE_READ: int +CANT_USE_OPTION_HERE: int +NOT_SUPPORTED_YET: int +MASTER_FATAL_ERROR_READING_BINLOG: int +SLAVE_IGNORED_TABLE: int +INCORRECT_GLOBAL_LOCAL_VAR: int +WRONG_FK_DEF: int +KEY_REF_DO_NOT_MATCH_TABLE_REF: int +OPERAND_COLUMNS: int +SUBQUERY_NO_1_ROW: int +UNKNOWN_STMT_HANDLER: int +CORRUPT_HELP_DB: int +CYCLIC_REFERENCE: int +AUTO_CONVERT: int +ILLEGAL_REFERENCE: int +DERIVED_MUST_HAVE_ALIAS: int +SELECT_REDUCED: int +TABLENAME_NOT_ALLOWED_HERE: int +NOT_SUPPORTED_AUTH_MODE: int +SPATIAL_CANT_HAVE_NULL: int +COLLATION_CHARSET_MISMATCH: int +SLAVE_WAS_RUNNING: int +SLAVE_WAS_NOT_RUNNING: int +TOO_BIG_FOR_UNCOMPRESS: int +ZLIB_Z_MEM_ERROR: int +ZLIB_Z_BUF_ERROR: int +ZLIB_Z_DATA_ERROR: int +CUT_VALUE_GROUP_CONCAT: int +WARN_TOO_FEW_RECORDS: int +WARN_TOO_MANY_RECORDS: int +WARN_NULL_TO_NOTNULL: int +WARN_DATA_OUT_OF_RANGE: int +WARN_DATA_TRUNCATED: int +WARN_USING_OTHER_HANDLER: int +CANT_AGGREGATE_2COLLATIONS: int +DROP_USER: int +REVOKE_GRANTS: int +CANT_AGGREGATE_3COLLATIONS: int +CANT_AGGREGATE_NCOLLATIONS: int +VARIABLE_IS_NOT_STRUCT: int +UNKNOWN_COLLATION: int +SLAVE_IGNORED_SSL_PARAMS: int +SERVER_IS_IN_SECURE_AUTH_MODE: int +WARN_FIELD_RESOLVED: int +BAD_SLAVE_UNTIL_COND: int +MISSING_SKIP_SLAVE: int +UNTIL_COND_IGNORED: int +WRONG_NAME_FOR_INDEX: int +WRONG_NAME_FOR_CATALOG: int +WARN_QC_RESIZE: int +BAD_FT_COLUMN: int +UNKNOWN_KEY_CACHE: int +WARN_HOSTNAME_WONT_WORK: int +UNKNOWN_STORAGE_ENGINE: int +WARN_DEPRECATED_SYNTAX: int +NON_UPDATABLE_TABLE: int +FEATURE_DISABLED: int +OPTION_PREVENTS_STATEMENT: int +DUPLICATED_VALUE_IN_TYPE: int +TRUNCATED_WRONG_VALUE: int +TOO_MUCH_AUTO_TIMESTAMP_COLS: int +INVALID_ON_UPDATE: int +UNSUPPORTED_PS: int +GET_ERRMSG: int +GET_TEMPORARY_ERRMSG: int +UNKNOWN_TIME_ZONE: int +WARN_INVALID_TIMESTAMP: int +INVALID_CHARACTER_STRING: int +WARN_ALLOWED_PACKET_OVERFLOWED: int +CONFLICTING_DECLARATIONS: int +SP_NO_RECURSIVE_CREATE: int +SP_ALREADY_EXISTS: int +SP_DOES_NOT_EXIST: int +SP_DROP_FAILED: int +SP_STORE_FAILED: int +SP_LILABEL_MISMATCH: int +SP_LABEL_REDEFINE: int +SP_LABEL_MISMATCH: int +SP_UNINIT_VAR: int +SP_BADSELECT: int +SP_BADRETURN: int +SP_BADSTATEMENT: int +UPDATE_LOG_DEPRECATED_IGNORED: int +UPDATE_LOG_DEPRECATED_TRANSLATED: int +QUERY_INTERRUPTED: int +SP_WRONG_NO_OF_ARGS: int +SP_COND_MISMATCH: int +SP_NORETURN: int +SP_NORETURNEND: int +SP_BAD_CURSOR_QUERY: int +SP_BAD_CURSOR_SELECT: int +SP_CURSOR_MISMATCH: int +SP_CURSOR_ALREADY_OPEN: int +SP_CURSOR_NOT_OPEN: int +SP_UNDECLARED_VAR: int +SP_WRONG_NO_OF_FETCH_ARGS: int +SP_FETCH_NO_DATA: int +SP_DUP_PARAM: int +SP_DUP_VAR: int +SP_DUP_COND: int +SP_DUP_CURS: int +SP_CANT_ALTER: int +SP_SUBSELECT_NYI: int +STMT_NOT_ALLOWED_IN_SF_OR_TRG: int +SP_VARCOND_AFTER_CURSHNDLR: int +SP_CURSOR_AFTER_HANDLER: int +SP_CASE_NOT_FOUND: int +FPARSER_TOO_BIG_FILE: int +FPARSER_BAD_HEADER: int +FPARSER_EOF_IN_COMMENT: int +FPARSER_ERROR_IN_PARAMETER: int +FPARSER_EOF_IN_UNKNOWN_PARAMETER: int +VIEW_NO_EXPLAIN: int +FRM_UNKNOWN_TYPE: int +WRONG_OBJECT: int +NONUPDATEABLE_COLUMN: int +VIEW_SELECT_DERIVED: int +VIEW_SELECT_CLAUSE: int +VIEW_SELECT_VARIABLE: int +VIEW_SELECT_TMPTABLE: int +VIEW_WRONG_LIST: int +WARN_VIEW_MERGE: int +WARN_VIEW_WITHOUT_KEY: int +VIEW_INVALID: int +SP_NO_DROP_SP: int +SP_GOTO_IN_HNDLR: int +TRG_ALREADY_EXISTS: int +TRG_DOES_NOT_EXIST: int +TRG_ON_VIEW_OR_TEMP_TABLE: int +TRG_CANT_CHANGE_ROW: int +TRG_NO_SUCH_ROW_IN_TRG: int +NO_DEFAULT_FOR_FIELD: int +DIVISION_BY_ZERO: int +TRUNCATED_WRONG_VALUE_FOR_FIELD: int +ILLEGAL_VALUE_FOR_TYPE: int +VIEW_NONUPD_CHECK: int +VIEW_CHECK_FAILED: int +PROCACCESS_DENIED_ERROR: int +RELAY_LOG_FAIL: int +PASSWD_LENGTH: int +UNKNOWN_TARGET_BINLOG: int +IO_ERR_LOG_INDEX_READ: int +BINLOG_PURGE_PROHIBITED: int +FSEEK_FAIL: int +BINLOG_PURGE_FATAL_ERR: int +LOG_IN_USE: int +LOG_PURGE_UNKNOWN_ERR: int +RELAY_LOG_INIT: int +NO_BINARY_LOGGING: int +RESERVED_SYNTAX: int +WSAS_FAILED: int +DIFF_GROUPS_PROC: int +NO_GROUP_FOR_PROC: int +ORDER_WITH_PROC: int +LOGGING_PROHIBIT_CHANGING_OF: int +NO_FILE_MAPPING: int +WRONG_MAGIC: int +PS_MANY_PARAM: int +KEY_PART_0: int +VIEW_CHECKSUM: int +VIEW_MULTIUPDATE: int +VIEW_NO_INSERT_FIELD_LIST: int +VIEW_DELETE_MERGE_VIEW: int +CANNOT_USER: int +XAER_NOTA: int +XAER_INVAL: int +XAER_RMFAIL: int +XAER_OUTSIDE: int +XAER_RMERR: int +XA_RBROLLBACK: int +NONEXISTING_PROC_GRANT: int +PROC_AUTO_GRANT_FAIL: int +PROC_AUTO_REVOKE_FAIL: int +DATA_TOO_LONG: int +SP_BAD_SQLSTATE: int +STARTUP: int +LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR: int +CANT_CREATE_USER_WITH_GRANT: int +WRONG_VALUE_FOR_TYPE: int +TABLE_DEF_CHANGED: int +SP_DUP_HANDLER: int +SP_NOT_VAR_ARG: int +SP_NO_RETSET: int +CANT_CREATE_GEOMETRY_OBJECT: int +FAILED_ROUTINE_BREAK_BINLOG: int +BINLOG_UNSAFE_ROUTINE: int +BINLOG_CREATE_ROUTINE_NEED_SUPER: int +EXEC_STMT_WITH_OPEN_CURSOR: int +STMT_HAS_NO_OPEN_CURSOR: int +COMMIT_NOT_ALLOWED_IN_SF_OR_TRG: int +NO_DEFAULT_FOR_VIEW_FIELD: int +SP_NO_RECURSION: int +TOO_BIG_SCALE: int +TOO_BIG_PRECISION: int +M_BIGGER_THAN_D: int +WRONG_LOCK_OF_SYSTEM_TABLE: int +CONNECT_TO_FOREIGN_DATA_SOURCE: int +QUERY_ON_FOREIGN_DATA_SOURCE: int +FOREIGN_DATA_SOURCE_DOESNT_EXIST: int +FOREIGN_DATA_STRING_INVALID_CANT_CREATE: int +FOREIGN_DATA_STRING_INVALID: int +CANT_CREATE_FEDERATED_TABLE: int +TRG_IN_WRONG_SCHEMA: int +STACK_OVERRUN_NEED_MORE: int +TOO_LONG_BODY: int +WARN_CANT_DROP_DEFAULT_KEYCACHE: int +TOO_BIG_DISPLAYWIDTH: int +XAER_DUPID: int +DATETIME_FUNCTION_OVERFLOW: int +CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG: int +VIEW_PREVENT_UPDATE: int +PS_NO_RECURSION: int +SP_CANT_SET_AUTOCOMMIT: int +MALFORMED_DEFINER: int +VIEW_FRM_NO_USER: int +VIEW_OTHER_USER: int +NO_SUCH_USER: int +FORBID_SCHEMA_CHANGE: int +ROW_IS_REFERENCED_2: int +NO_REFERENCED_ROW_2: int +SP_BAD_VAR_SHADOW: int +TRG_NO_DEFINER: int +OLD_FILE_FORMAT: int +SP_RECURSION_LIMIT: int +SP_PROC_TABLE_CORRUPT: int +SP_WRONG_NAME: int +TABLE_NEEDS_UPGRADE: int +SP_NO_AGGREGATE: int +MAX_PREPARED_STMT_COUNT_REACHED: int +VIEW_RECURSIVE: int +NON_GROUPING_FIELD_USED: int +TABLE_CANT_HANDLE_SPKEYS: int +NO_TRIGGERS_ON_SYSTEM_SCHEMA: int +USERNAME: int +HOSTNAME: int +WRONG_STRING_LENGTH: int +ERROR_LAST: int diff --git a/shared/package-files/d0/d0edee15f91b406f3f99726e44eb990be6e34fd0345b52b910c568e0eef6a2a8/blob b/shared/package-files/d0/d0edee15f91b406f3f99726e44eb990be6e34fd0345b52b910c568e0eef6a2a8/blob new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/shared/package-files/d0/d0edee15f91b406f3f99726e44eb990be6e34fd0345b52b910c568e0eef6a2a8/blob @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/shared/package-files/d0/d0eee1c38f9d55f010da652848b6e35986a448dcdcbfa07a9f20490913da8dda/blob b/shared/package-files/d0/d0eee1c38f9d55f010da652848b6e35986a448dcdcbfa07a9f20490913da8dda/blob new file mode 100644 index 0000000000000000000000000000000000000000..a249ccbd5614ada1ddb035e929c5a2627539d319 --- /dev/null +++ b/shared/package-files/d0/d0eee1c38f9d55f010da652848b6e35986a448dcdcbfa07a9f20490913da8dda/blob @@ -0,0 +1,16 @@ +""" +Usecases with Python 3 function annotations. This is a separate module +in order to avoid syntax errors with Python 2. +""" + + +class AnnotatedClass: + """ + A class with annotated methods. + """ + + def __init__(self, v: int): + self.x = v + + def add(self, v: int) -> int: + return self.x + v diff --git a/shared/package-files/d0/d0f0ef33cabf63d34196cea674752b86f99e4969f479d591419a2cf6ff022741/blob b/shared/package-files/d0/d0f0ef33cabf63d34196cea674752b86f99e4969f479d591419a2cf6ff022741/blob new file mode 100644 index 0000000000000000000000000000000000000000..33024b1ec8d8fb709d601c8ee50f4c7d28ea7fca --- /dev/null +++ b/shared/package-files/d0/d0f0ef33cabf63d34196cea674752b86f99e4969f479d591419a2cf6ff022741/blob @@ -0,0 +1,445 @@ +# mypy: ignore-errors + +import torch.fx as fx +import copy +import torch +import math +import sys +from typing import Callable, List +from functools import wraps, partial +from dataclasses import dataclass +from .compile_utils import get_placeholders, get_outputs +from torch.utils._content_store import ContentStoreWriter +from torch.hub import tqdm +from torch.multiprocessing.reductions import StorageWeakRef +import os + +is_tuple = object() + +@dataclass +class LoadTensorMeta: + size: List[int] + stride: List[int] + dtype: torch.dtype + device: torch.device + +class ConcreteProp(torch.fx.Interpreter): + def __init__(self, mod, *, writer=None, skip_offload=False): + super().__init__(mod) + self.writer = writer + self.skip_offload = skip_offload + self.seen_storages = set() + + def run_node(self, n): + self.pbar.update(1) + r = super().run_node(n) + name = n.name + + if isinstance(r, torch.Tensor): + if self.writer is None: + n.meta['concrete_value'] = r + else: + if StorageWeakRef(r.untyped_storage()) in self.seen_storages: + # Refuse to offload tensors which alias other live + # tensors, because this will violate operator contracts + n.meta['concrete_value'] = None + else: + if not self.skip_offload: + self.writer.write_tensor(os.path.join("eager", name), r) + n.meta['concrete_value'] = LoadTensorMeta( + r.size(), + r.stride(), + r.dtype, + r.device + ) + self.seen_storages.add(StorageWeakRef(r.untyped_storage())) + else: + n.meta['concrete_value'] = is_tuple + + return r + + def propagate(self, *args): + with tqdm( + desc="Saving intermediates for delta debugging", + total=len(self.module.graph.nodes), + disable=self.writer is None + ) as pbar: + self.pbar = pbar + r = super().run(*args) + if not self.skip_offload: + pbar.set_description("Saved! To skip next time, run with --skip-saving-eager-intermediates") + return r + +def is_load_tensor_node(node): + return node.op == 'call_function' and node.target is torch.ops.debugprims.load_tensor.default + + +# inplace modifies node/inps +def _convert_node_to_placeholder(graph, node, inps): + if node.op == 'output' or node.op == "placeholder": + return False + + if is_load_tensor_node(node): + return False + + concrete_val = node.meta.get('concrete_value', None) + + if isinstance(concrete_val, torch.Tensor): + node.op = 'placeholder' + node.target = node.name + node.args = () + node.kwargs = {} + + inps.append(concrete_val) + return True + + elif concrete_val is None: + return False + + elif concrete_val is is_tuple: + r = False + for tuple_user in list(node.users): + r = _convert_node_to_placeholder(graph, tuple_user, inps) or r + # NB: We must not erase the node at this point, because + # we are iterating over the nodes and this would change + # the iteration order + # graph.erase_node(node) + return r + + elif isinstance(concrete_val, LoadTensorMeta): + node.op = 'call_function' + node.target = torch.ops.debugprims.load_tensor.default + node.args = (os.path.join("eager", node.name), concrete_val.size, concrete_val.stride) + node.kwargs = { + 'device': concrete_val.device, + 'dtype': concrete_val.dtype, + } + return True + + return False + +def create_minified_hlo_graph(minified_fx_graph, inputs): + """ + Takes minified FX graph as primary input, and ports it to HLO via StableHLO + Provides minified HLO graph as output, and archive them to local directory + """ + hlo_dir = f"{os.getcwd()}/hlo_files" + os.makedirs(hlo_dir, exists_ok=True) + + from torch_xla.stablehlo import save_torch_model_as_stablehlo + save_torch_model_as_stablehlo(minified_fx_graph, inputs, hlo_dir) + +def dump_state(fx_g, inps): + print(f""" +# Working Repro with {len(fx_g.graph.nodes)} nodes +inps = {[(i.shape, i.dtype, i.device.type) for i in inps]} +inps = [torch.zeros(())] + [torch.ones(shape, dtype=dtype, device=device) for (shape, dtype, device) in inps] +{fx_g.code} +""") + +def is_power_of_two(n): + if n == 0: + return False + return (n & (n - 1)) == 0 + +@dataclass +class ReproState: + graph: fx.Graph + inps: List[torch.Tensor] + + def __post_init__(self): + ph_nodes = get_placeholders(self.graph) + assert len(ph_nodes) == len(self.inps) + +def minifier( + fail_f: fx.GraphModule, inps, module_fails, dump_state: Callable = dump_state, *, + save_dir=None, offload_to_disk=False, skip_offload=False, skip_sanity=False, + max_granularity=None +): + """ + Minimizes a FX graph with given inputs, such that the resulting FX graph still returns True for module_fails. + + Does 2 main strategies: + 1. Truncates suffix: Removes some suffix from the graph and sets a new output. + 2. Delta Debugging: Tries replacing half of the graph with inputs. If fails, + tries replacing quarter of the graph, etc. + + >>> # xdoctest: +SKIP(failing) + >>> failing_function = fx.symbolic_trace(f) + >>> minimize(failing_function, [torch.randn(5)], lambda fx_g, inps: fx_g(*inps)) + + note: module_fails returns True if it fails. + """ + assert isinstance(inps, (tuple, list)) + + failing_graph = fail_f.graph + cur_size = len(failing_graph.nodes) + + if max_granularity is not None and not is_power_of_two(max_granularity): + raise RuntimeError(f"max_granularity {max_granularity} not power of two") + + num_queries = 0 + + def deepcopy_fx_graph(fx_graph): + return fx.GraphModule(fail_f, copy.deepcopy(fx_graph)).graph + + + def graph_fails(graph, inps): + nonlocal num_queries + graph = copy.deepcopy(graph) + num_queries += 1 + mod = fx.GraphModule(fail_f, graph) + mod.graph.lint() + return module_fails(mod, inps) + + writer = None + if offload_to_disk: + writer = ContentStoreWriter(save_dir) + + ConcreteProp(fail_f, writer=writer, skip_offload=skip_offload).propagate(*inps) + if not skip_sanity and not graph_fails(failing_graph, inps): + raise RuntimeError("Input graph did not fail the tester") + print(f"Started off with {cur_size} nodes", file=sys.stderr) + + def _register_strategy(strategy: Callable, name: str): + @wraps(strategy) + def new_func(old_state: ReproState, granularity=1): + print(file=sys.stderr) + print( + f"Strategy: {name} (G: {granularity}) " + f"({len(old_state.graph.nodes)} nodes, {len(old_state.inps)} inputs)", + file=sys.stderr + ) + new_state = strategy(deepcopy_fx_graph(old_state.graph), list(old_state.inps), granularity) + if new_state is not None: + new_nodes = len(new_state.graph.nodes) + old_nodes = len(old_state.graph.nodes) + new_inps = len(new_state.inps) + old_inps = len(old_state.inps) + new_outs = len(get_outputs(new_state.graph)) + old_outs = len(get_outputs(old_state.graph)) + progress_made = False + if new_nodes < old_nodes: + progress_made = True + print(f"SUCCESS: Went from {old_nodes} to {new_nodes} nodes", file=sys.stderr) + if new_inps > old_inps: + progress_made = True + print(f"SUCCESS: Went from {old_inps} to {new_inps} inputs", file=sys.stderr) + if new_outs < old_outs: + progress_made = True + print(f"SUCCESS: Went from {old_outs} to {new_outs} outputs", file=sys.stderr) + + if not progress_made: + raise RuntimeError("Success raised but no progress made?") + + if not graph_fails(new_state.graph, new_state.inps): + print("WARNING: Something went wrong, not applying this minification", file=sys.stderr) + return None + return new_state + else: + print(f"FAIL: {name}", file=sys.stderr) + return None + + return new_func + + def register_strategy(name: str): + return partial(_register_strategy, name=name) + + @register_strategy("Truncate suffix") + def remove_suffix(cur_graph, cur_inps, granularity): + tested = set() + new_graph = fx.Graph() + env = {} + for idx, node in enumerate(cur_graph.nodes): + new_node = new_graph.node_copy(node, lambda x: env[x]) + if node.op not in ['placeholder', 'output']: + # If idx is divisible by (granularity * 2), it would have been checked already. + if idx % granularity == 0 and (idx % (granularity * 2) != 0) and idx not in tested: + output_node = new_graph.output((new_node,)) + if len(new_graph.nodes) < len(cur_graph.nodes) and graph_fails(new_graph, cur_inps): + return ReproState(new_graph, cur_inps) + else: + tested.add(idx) + new_graph.erase_node(output_node) + env[node] = new_node + return None + + @register_strategy("Remove outputs") + def remove_outputs(cur_graph, cur_inps, granularity): + granularity = max(1, granularity // 2) + for idx, node in enumerate(cur_graph.nodes): + node.idx = idx + if node.op == 'output': + output = node + break + + if isinstance(output.args[0], fx.Node): + return None + + output_args = sorted(output.args[0], key=lambda x: x.idx if isinstance(x, fx.Node) else int(1e9)) + if len(output_args) == 1: + return None + + for idx in range(0, len(output_args), granularity): + output.args = (output_args[:idx] + output_args[idx + granularity:],) + if graph_fails(cur_graph, cur_inps): + return ReproState(cur_graph, cur_inps) + return None + + + def remove_unused_inputs_unchecked(cur_state: ReproState): + cur_graph = cur_state.graph + cur_inps = cur_state.inps + ph_nodes = get_placeholders(cur_graph) + assert len(ph_nodes) == len(cur_inps) + + new_inps = [] + for idx in range(len(ph_nodes)): + if len(ph_nodes[idx].users) == 0: + cur_graph.erase_node(ph_nodes[idx]) + else: + new_inps.append(cur_inps[idx]) + if len(new_inps) < len(cur_inps): + return ReproState(cur_graph, new_inps) + return None + + def remove_unused_inputs_checked(cur_state: ReproState): + new_state = remove_unused_inputs_unchecked(cur_state) + if new_state is not None and graph_fails(new_state.graph, new_state.inps): + return new_state + return None + + def _remove_unused_wrapper(cur_graph, cur_inps, granularity): + return remove_unused_inputs_checked(ReproState(cur_graph, cur_inps)) + + remove_unused_inputs = register_strategy("Remove unused inputs")(_remove_unused_wrapper) + + @register_strategy("Eliminate dead code") + def eliminate_dead_code(cur_graph, cur_inps, granularity): + if cur_graph.eliminate_dead_code() and graph_fails(cur_graph, cur_inps): + return ReproState(cur_graph, cur_inps) + return None + + + def _consolidate_placeholders(cur_graph, inps): + new_graph = fx.Graph() + env = {} + seen_non_placeholder = False + + # Move all placeholders to the front; also, if any load_tensor + # is at the front, convert it into an input (because it can be live + # all the time) + for node in cur_graph.nodes: + if node.op == 'placeholder': + new_node = new_graph.node_copy(node, lambda x: env[x]) + env[node] = new_node + elif not seen_non_placeholder and is_load_tensor_node(node): + new_node = new_graph.placeholder(node.name) + env[node] = new_node + inps.append(torch.ops.debugprims.load_tensor.default(*node.args, **node.kwargs)) + else: + seen_non_placeholder = True + + # Move everyone else + for node in cur_graph.nodes: + if node not in env: + new_node = new_graph.node_copy(node, lambda x: env[x]) + env[node] = new_node + return new_graph + + @register_strategy("Delta Debugging") + def delta_debugging(cur_graph: fx.Graph, cur_inps, granularity): + num_nodes = len(cur_graph.nodes) + for start_range in range(0, num_nodes, granularity): + is_removing = False + new_graph = deepcopy_fx_graph(cur_graph) + new_inps = cur_inps[:] + end_range = min(num_nodes, start_range + granularity) + for idx in range(start_range, end_range): + new_node = list(new_graph.nodes)[idx] + if _convert_node_to_placeholder(new_graph, new_node, new_inps): + is_removing = True + if not is_removing: + continue + new_graph.eliminate_dead_code() + new_graph = _consolidate_placeholders(new_graph, new_inps) + new_state = remove_unused_inputs_unchecked(ReproState(new_graph, new_inps)) + if new_state is None: + new_state = ReproState(new_graph, new_inps) + if graph_fails(new_state.graph, new_state.inps): + return ReproState(new_state.graph, new_state.inps) + + return None + + @register_strategy("Consolidate Inputs") + def consolidate_inputs(cur_graph, cur_inps, granularity): + old_len = len(cur_inps) + cur_graph = _consolidate_placeholders(cur_graph, cur_inps) + if len(cur_inps) > old_len and graph_fails(cur_graph, cur_inps): + return ReproState(cur_graph, cur_inps) + return None + + failing_state = ReproState(failing_graph, inps) + + def try_granularity(failing_state, granularity, use_non_granular): + print(f"Trying granularity {granularity}", file=sys.stderr) + + strategies = [] + num_nodes = len(failing_state.graph.nodes) + num_outputs = len(get_outputs(failing_state.graph)) + if num_outputs > num_nodes // 2: + strategies += [remove_outputs] + + if use_non_granular: + strategies += [eliminate_dead_code, remove_unused_inputs, consolidate_inputs] + + strategies += [remove_suffix, delta_debugging] + + for strategy in strategies: + new_state = strategy(failing_state, granularity) + if new_state is not None: + return new_state + return None + + while True: + dump_state(fx.GraphModule(fail_f, failing_state.graph), failing_state.inps) + granularity = int(2**(math.floor(math.log2(len(failing_state.graph.nodes))))) + if max_granularity is not None: + granularity = min(max_granularity, granularity) + new_state = try_granularity(failing_state, granularity, use_non_granular=True) + if new_state is not None: + failing_state = new_state + continue + + granularity //= 2 + has_progress = False + while granularity >= 1: + new_state = try_granularity(failing_state, granularity, use_non_granular=False) + if new_state is not None: + failing_state = new_state + has_progress = True + break + granularity //= 2 + if has_progress: + continue + + new_state = remove_outputs(failing_state, 1) + if new_state is not None: + failing_state = new_state + continue + + break + + if not graph_fails(failing_state.graph, failing_state.inps): + raise RuntimeError("Uh oh, something went wrong :( Final graph is not failing") + + print(f"Made {num_queries} queries", file=sys.stderr) + failing_fx = fx.GraphModule(fail_f, failing_state.graph) + + # If XLA debugging environment is enabled, create minified HLO graph as well + if "XLA_HLO_DEBUG" in os.environ: + create_minified_hlo_graph(failing_fx, failing_state.inps) + + dump_state(failing_fx, failing_state.inps) + print("Wrote minimal repro out to repro.py", file=sys.stderr) + return failing_fx, failing_state.inps diff --git a/shared/package-files/d0/d0f1d1961f5f7ac4eb6bc9c30d2a2160b021832f8a60da8d8dcf2073e2e870a9/blob b/shared/package-files/d0/d0f1d1961f5f7ac4eb6bc9c30d2a2160b021832f8a60da8d8dcf2073e2e870a9/blob new file mode 100644 index 0000000000000000000000000000000000000000..d7ec53e2a8b70c03e9a3cd8232df21405bbc0c58 Binary files /dev/null and b/shared/package-files/d0/d0f1d1961f5f7ac4eb6bc9c30d2a2160b021832f8a60da8d8dcf2073e2e870a9/blob differ diff --git a/shared/package-files/d0/d0f23f94e7325c92a98105fd65fe54bb8affefb1a2349d30a6f979b899e0ca6c/blob b/shared/package-files/d0/d0f23f94e7325c92a98105fd65fe54bb8affefb1a2349d30a6f979b899e0ca6c/blob new file mode 100644 index 0000000000000000000000000000000000000000..2a11195f312359ae5f1b427b68de3ebee0f6a26e Binary files /dev/null and b/shared/package-files/d0/d0f23f94e7325c92a98105fd65fe54bb8affefb1a2349d30a6f979b899e0ca6c/blob differ diff --git a/shared/package-files/d0/d0f3670ea2a4a2467b11154381b7acf0a35973e21226b65495565ce4b916d7c1/blob b/shared/package-files/d0/d0f3670ea2a4a2467b11154381b7acf0a35973e21226b65495565ce4b916d7c1/blob new file mode 100644 index 0000000000000000000000000000000000000000..258ae48ce0209f6873101426fce439c233078c89 --- /dev/null +++ b/shared/package-files/d0/d0f3670ea2a4a2467b11154381b7acf0a35973e21226b65495565ce4b916d7c1/blob @@ -0,0 +1,1375 @@ +dtype,input,output,ulperrortol +## +ve denormals ## +np.float32,0x004b4716,0x3f800000,2 +np.float32,0x007b2490,0x3f800000,2 +np.float32,0x007c99fa,0x3f800000,2 +np.float32,0x00734a0c,0x3f800000,2 +np.float32,0x0070de24,0x3f800000,2 +np.float32,0x007fffff,0x3f800000,2 +np.float32,0x00000001,0x3f800000,2 +## -ve denormals ## +np.float32,0x80495d65,0x3f800000,2 +np.float32,0x806894f6,0x3f800000,2 +np.float32,0x80555a76,0x3f800000,2 +np.float32,0x804e1fb8,0x3f800000,2 +np.float32,0x80687de9,0x3f800000,2 +np.float32,0x807fffff,0x3f800000,2 +np.float32,0x80000001,0x3f800000,2 +## +/-0.0f, +/-FLT_MIN +/-FLT_MAX ## +np.float32,0x00000000,0x3f800000,2 +np.float32,0x80000000,0x3f800000,2 +np.float32,0x00800000,0x3f800000,2 +np.float32,0x80800000,0x3f800000,2 +## 1.00f + 0x00000001 ## +np.float32,0x3f800000,0x3f0a5140,2 +np.float32,0x3f800001,0x3f0a513f,2 +np.float32,0x3f800002,0x3f0a513d,2 +np.float32,0xc090a8b0,0xbe4332ce,2 +np.float32,0x41ce3184,0x3f4d1de1,2 +np.float32,0xc1d85848,0xbeaa8980,2 +np.float32,0x402b8820,0xbf653aa3,2 +np.float32,0x42b4e454,0xbf4a338b,2 +np.float32,0x42a67a60,0x3c58202e,2 +np.float32,0x41d92388,0xbed987c7,2 +np.float32,0x422dd66c,0x3f5dcab3,2 +np.float32,0xc28f5be6,0xbf5688d8,2 +np.float32,0x41ab2674,0xbf53aa3b,2 +np.float32,0x3f490fdb,0x3f3504f3,2 +np.float32,0xbf490fdb,0x3f3504f3,2 +np.float32,0x3fc90fdb,0xb33bbd2e,2 +np.float32,0xbfc90fdb,0xb33bbd2e,2 +np.float32,0x40490fdb,0xbf800000,2 +np.float32,0xc0490fdb,0xbf800000,2 +np.float32,0x3fc90fdb,0xb33bbd2e,2 +np.float32,0xbfc90fdb,0xb33bbd2e,2 +np.float32,0x40490fdb,0xbf800000,2 +np.float32,0xc0490fdb,0xbf800000,2 +np.float32,0x40c90fdb,0x3f800000,2 +np.float32,0xc0c90fdb,0x3f800000,2 +np.float32,0x4016cbe4,0xbf3504f3,2 +np.float32,0xc016cbe4,0xbf3504f3,2 +np.float32,0x4096cbe4,0x324cde2e,2 +np.float32,0xc096cbe4,0x324cde2e,2 +np.float32,0x4116cbe4,0xbf800000,2 +np.float32,0xc116cbe4,0xbf800000,2 +np.float32,0x40490fdb,0xbf800000,2 +np.float32,0xc0490fdb,0xbf800000,2 +np.float32,0x40c90fdb,0x3f800000,2 +np.float32,0xc0c90fdb,0x3f800000,2 +np.float32,0x41490fdb,0x3f800000,2 +np.float32,0xc1490fdb,0x3f800000,2 +np.float32,0x407b53d2,0xbf3504f1,2 +np.float32,0xc07b53d2,0xbf3504f1,2 +np.float32,0x40fb53d2,0xb4b5563d,2 +np.float32,0xc0fb53d2,0xb4b5563d,2 +np.float32,0x417b53d2,0xbf800000,2 +np.float32,0xc17b53d2,0xbf800000,2 +np.float32,0x4096cbe4,0x324cde2e,2 +np.float32,0xc096cbe4,0x324cde2e,2 +np.float32,0x4116cbe4,0xbf800000,2 +np.float32,0xc116cbe4,0xbf800000,2 +np.float32,0x4196cbe4,0x3f800000,2 +np.float32,0xc196cbe4,0x3f800000,2 +np.float32,0x40afede0,0x3f3504f7,2 +np.float32,0xc0afede0,0x3f3504f7,2 +np.float32,0x412fede0,0x353222c4,2 +np.float32,0xc12fede0,0x353222c4,2 +np.float32,0x41afede0,0xbf800000,2 +np.float32,0xc1afede0,0xbf800000,2 +np.float32,0x40c90fdb,0x3f800000,2 +np.float32,0xc0c90fdb,0x3f800000,2 +np.float32,0x41490fdb,0x3f800000,2 +np.float32,0xc1490fdb,0x3f800000,2 +np.float32,0x41c90fdb,0x3f800000,2 +np.float32,0xc1c90fdb,0x3f800000,2 +np.float32,0x40e231d6,0x3f3504f3,2 +np.float32,0xc0e231d6,0x3f3504f3,2 +np.float32,0x416231d6,0xb319a6a2,2 +np.float32,0xc16231d6,0xb319a6a2,2 +np.float32,0x41e231d6,0xbf800000,2 +np.float32,0xc1e231d6,0xbf800000,2 +np.float32,0x40fb53d2,0xb4b5563d,2 +np.float32,0xc0fb53d2,0xb4b5563d,2 +np.float32,0x417b53d2,0xbf800000,2 +np.float32,0xc17b53d2,0xbf800000,2 +np.float32,0x41fb53d2,0x3f800000,2 +np.float32,0xc1fb53d2,0x3f800000,2 +np.float32,0x410a3ae7,0xbf3504fb,2 +np.float32,0xc10a3ae7,0xbf3504fb,2 +np.float32,0x418a3ae7,0x35b08908,2 +np.float32,0xc18a3ae7,0x35b08908,2 +np.float32,0x420a3ae7,0xbf800000,2 +np.float32,0xc20a3ae7,0xbf800000,2 +np.float32,0x4116cbe4,0xbf800000,2 +np.float32,0xc116cbe4,0xbf800000,2 +np.float32,0x4196cbe4,0x3f800000,2 +np.float32,0xc196cbe4,0x3f800000,2 +np.float32,0x4216cbe4,0x3f800000,2 +np.float32,0xc216cbe4,0x3f800000,2 +np.float32,0x41235ce2,0xbf3504ef,2 +np.float32,0xc1235ce2,0xbf3504ef,2 +np.float32,0x41a35ce2,0xb53889b6,2 +np.float32,0xc1a35ce2,0xb53889b6,2 +np.float32,0x42235ce2,0xbf800000,2 +np.float32,0xc2235ce2,0xbf800000,2 +np.float32,0x412fede0,0x353222c4,2 +np.float32,0xc12fede0,0x353222c4,2 +np.float32,0x41afede0,0xbf800000,2 +np.float32,0xc1afede0,0xbf800000,2 +np.float32,0x422fede0,0x3f800000,2 +np.float32,0xc22fede0,0x3f800000,2 +np.float32,0x413c7edd,0x3f3504f4,2 +np.float32,0xc13c7edd,0x3f3504f4,2 +np.float32,0x41bc7edd,0x33800add,2 +np.float32,0xc1bc7edd,0x33800add,2 +np.float32,0x423c7edd,0xbf800000,2 +np.float32,0xc23c7edd,0xbf800000,2 +np.float32,0x41490fdb,0x3f800000,2 +np.float32,0xc1490fdb,0x3f800000,2 +np.float32,0x41c90fdb,0x3f800000,2 +np.float32,0xc1c90fdb,0x3f800000,2 +np.float32,0x42490fdb,0x3f800000,2 +np.float32,0xc2490fdb,0x3f800000,2 +np.float32,0x4155a0d9,0x3f3504eb,2 +np.float32,0xc155a0d9,0x3f3504eb,2 +np.float32,0x41d5a0d9,0xb5b3bc81,2 +np.float32,0xc1d5a0d9,0xb5b3bc81,2 +np.float32,0x4255a0d9,0xbf800000,2 +np.float32,0xc255a0d9,0xbf800000,2 +np.float32,0x416231d6,0xb319a6a2,2 +np.float32,0xc16231d6,0xb319a6a2,2 +np.float32,0x41e231d6,0xbf800000,2 +np.float32,0xc1e231d6,0xbf800000,2 +np.float32,0x426231d6,0x3f800000,2 +np.float32,0xc26231d6,0x3f800000,2 +np.float32,0x416ec2d4,0xbf3504f7,2 +np.float32,0xc16ec2d4,0xbf3504f7,2 +np.float32,0x41eec2d4,0x353ef0a7,2 +np.float32,0xc1eec2d4,0x353ef0a7,2 +np.float32,0x426ec2d4,0xbf800000,2 +np.float32,0xc26ec2d4,0xbf800000,2 +np.float32,0x417b53d2,0xbf800000,2 +np.float32,0xc17b53d2,0xbf800000,2 +np.float32,0x41fb53d2,0x3f800000,2 +np.float32,0xc1fb53d2,0x3f800000,2 +np.float32,0x427b53d2,0x3f800000,2 +np.float32,0xc27b53d2,0x3f800000,2 +np.float32,0x4183f268,0xbf3504e7,2 +np.float32,0xc183f268,0xbf3504e7,2 +np.float32,0x4203f268,0xb6059a13,2 +np.float32,0xc203f268,0xb6059a13,2 +np.float32,0x4283f268,0xbf800000,2 +np.float32,0xc283f268,0xbf800000,2 +np.float32,0x418a3ae7,0x35b08908,2 +np.float32,0xc18a3ae7,0x35b08908,2 +np.float32,0x420a3ae7,0xbf800000,2 +np.float32,0xc20a3ae7,0xbf800000,2 +np.float32,0x428a3ae7,0x3f800000,2 +np.float32,0xc28a3ae7,0x3f800000,2 +np.float32,0x41908365,0x3f3504f0,2 +np.float32,0xc1908365,0x3f3504f0,2 +np.float32,0x42108365,0xb512200d,2 +np.float32,0xc2108365,0xb512200d,2 +np.float32,0x42908365,0xbf800000,2 +np.float32,0xc2908365,0xbf800000,2 +np.float32,0x4196cbe4,0x3f800000,2 +np.float32,0xc196cbe4,0x3f800000,2 +np.float32,0x4216cbe4,0x3f800000,2 +np.float32,0xc216cbe4,0x3f800000,2 +np.float32,0x4296cbe4,0x3f800000,2 +np.float32,0xc296cbe4,0x3f800000,2 +np.float32,0x419d1463,0x3f3504ef,2 +np.float32,0xc19d1463,0x3f3504ef,2 +np.float32,0x421d1463,0xb5455799,2 +np.float32,0xc21d1463,0xb5455799,2 +np.float32,0x429d1463,0xbf800000,2 +np.float32,0xc29d1463,0xbf800000,2 +np.float32,0x41a35ce2,0xb53889b6,2 +np.float32,0xc1a35ce2,0xb53889b6,2 +np.float32,0x42235ce2,0xbf800000,2 +np.float32,0xc2235ce2,0xbf800000,2 +np.float32,0x42a35ce2,0x3f800000,2 +np.float32,0xc2a35ce2,0x3f800000,2 +np.float32,0x41a9a561,0xbf3504ff,2 +np.float32,0xc1a9a561,0xbf3504ff,2 +np.float32,0x4229a561,0x360733d0,2 +np.float32,0xc229a561,0x360733d0,2 +np.float32,0x42a9a561,0xbf800000,2 +np.float32,0xc2a9a561,0xbf800000,2 +np.float32,0x41afede0,0xbf800000,2 +np.float32,0xc1afede0,0xbf800000,2 +np.float32,0x422fede0,0x3f800000,2 +np.float32,0xc22fede0,0x3f800000,2 +np.float32,0x42afede0,0x3f800000,2 +np.float32,0xc2afede0,0x3f800000,2 +np.float32,0x41b6365e,0xbf3504f6,2 +np.float32,0xc1b6365e,0xbf3504f6,2 +np.float32,0x4236365e,0x350bb91c,2 +np.float32,0xc236365e,0x350bb91c,2 +np.float32,0x42b6365e,0xbf800000,2 +np.float32,0xc2b6365e,0xbf800000,2 +np.float32,0x41bc7edd,0x33800add,2 +np.float32,0xc1bc7edd,0x33800add,2 +np.float32,0x423c7edd,0xbf800000,2 +np.float32,0xc23c7edd,0xbf800000,2 +np.float32,0x42bc7edd,0x3f800000,2 +np.float32,0xc2bc7edd,0x3f800000,2 +np.float32,0x41c2c75c,0x3f3504f8,2 +np.float32,0xc1c2c75c,0x3f3504f8,2 +np.float32,0x4242c75c,0x354bbe8a,2 +np.float32,0xc242c75c,0x354bbe8a,2 +np.float32,0x42c2c75c,0xbf800000,2 +np.float32,0xc2c2c75c,0xbf800000,2 +np.float32,0x41c90fdb,0x3f800000,2 +np.float32,0xc1c90fdb,0x3f800000,2 +np.float32,0x42490fdb,0x3f800000,2 +np.float32,0xc2490fdb,0x3f800000,2 +np.float32,0x42c90fdb,0x3f800000,2 +np.float32,0xc2c90fdb,0x3f800000,2 +np.float32,0x41cf585a,0x3f3504e7,2 +np.float32,0xc1cf585a,0x3f3504e7,2 +np.float32,0x424f585a,0xb608cd8c,2 +np.float32,0xc24f585a,0xb608cd8c,2 +np.float32,0x42cf585a,0xbf800000,2 +np.float32,0xc2cf585a,0xbf800000,2 +np.float32,0x41d5a0d9,0xb5b3bc81,2 +np.float32,0xc1d5a0d9,0xb5b3bc81,2 +np.float32,0x4255a0d9,0xbf800000,2 +np.float32,0xc255a0d9,0xbf800000,2 +np.float32,0x42d5a0d9,0x3f800000,2 +np.float32,0xc2d5a0d9,0x3f800000,2 +np.float32,0x41dbe958,0xbf350507,2 +np.float32,0xc1dbe958,0xbf350507,2 +np.float32,0x425be958,0x365eab75,2 +np.float32,0xc25be958,0x365eab75,2 +np.float32,0x42dbe958,0xbf800000,2 +np.float32,0xc2dbe958,0xbf800000,2 +np.float32,0x41e231d6,0xbf800000,2 +np.float32,0xc1e231d6,0xbf800000,2 +np.float32,0x426231d6,0x3f800000,2 +np.float32,0xc26231d6,0x3f800000,2 +np.float32,0x42e231d6,0x3f800000,2 +np.float32,0xc2e231d6,0x3f800000,2 +np.float32,0x41e87a55,0xbf3504ef,2 +np.float32,0xc1e87a55,0xbf3504ef,2 +np.float32,0x42687a55,0xb552257b,2 +np.float32,0xc2687a55,0xb552257b,2 +np.float32,0x42e87a55,0xbf800000,2 +np.float32,0xc2e87a55,0xbf800000,2 +np.float32,0x41eec2d4,0x353ef0a7,2 +np.float32,0xc1eec2d4,0x353ef0a7,2 +np.float32,0x426ec2d4,0xbf800000,2 +np.float32,0xc26ec2d4,0xbf800000,2 +np.float32,0x42eec2d4,0x3f800000,2 +np.float32,0xc2eec2d4,0x3f800000,2 +np.float32,0x41f50b53,0x3f3504ff,2 +np.float32,0xc1f50b53,0x3f3504ff,2 +np.float32,0x42750b53,0x360a6748,2 +np.float32,0xc2750b53,0x360a6748,2 +np.float32,0x42f50b53,0xbf800000,2 +np.float32,0xc2f50b53,0xbf800000,2 +np.float32,0x41fb53d2,0x3f800000,2 +np.float32,0xc1fb53d2,0x3f800000,2 +np.float32,0x427b53d2,0x3f800000,2 +np.float32,0xc27b53d2,0x3f800000,2 +np.float32,0x42fb53d2,0x3f800000,2 +np.float32,0xc2fb53d2,0x3f800000,2 +np.float32,0x4200ce28,0x3f3504f6,2 +np.float32,0xc200ce28,0x3f3504f6,2 +np.float32,0x4280ce28,0x34fdd672,2 +np.float32,0xc280ce28,0x34fdd672,2 +np.float32,0x4300ce28,0xbf800000,2 +np.float32,0xc300ce28,0xbf800000,2 +np.float32,0x4203f268,0xb6059a13,2 +np.float32,0xc203f268,0xb6059a13,2 +np.float32,0x4283f268,0xbf800000,2 +np.float32,0xc283f268,0xbf800000,2 +np.float32,0x4303f268,0x3f800000,2 +np.float32,0xc303f268,0x3f800000,2 +np.float32,0x420716a7,0xbf3504f8,2 +np.float32,0xc20716a7,0xbf3504f8,2 +np.float32,0x428716a7,0x35588c6d,2 +np.float32,0xc28716a7,0x35588c6d,2 +np.float32,0x430716a7,0xbf800000,2 +np.float32,0xc30716a7,0xbf800000,2 +np.float32,0x420a3ae7,0xbf800000,2 +np.float32,0xc20a3ae7,0xbf800000,2 +np.float32,0x428a3ae7,0x3f800000,2 +np.float32,0xc28a3ae7,0x3f800000,2 +np.float32,0x430a3ae7,0x3f800000,2 +np.float32,0xc30a3ae7,0x3f800000,2 +np.float32,0x420d5f26,0xbf3504e7,2 +np.float32,0xc20d5f26,0xbf3504e7,2 +np.float32,0x428d5f26,0xb60c0105,2 +np.float32,0xc28d5f26,0xb60c0105,2 +np.float32,0x430d5f26,0xbf800000,2 +np.float32,0xc30d5f26,0xbf800000,2 +np.float32,0x42108365,0xb512200d,2 +np.float32,0xc2108365,0xb512200d,2 +np.float32,0x42908365,0xbf800000,2 +np.float32,0xc2908365,0xbf800000,2 +np.float32,0x43108365,0x3f800000,2 +np.float32,0xc3108365,0x3f800000,2 +np.float32,0x4213a7a5,0x3f350507,2 +np.float32,0xc213a7a5,0x3f350507,2 +np.float32,0x4293a7a5,0x3661deee,2 +np.float32,0xc293a7a5,0x3661deee,2 +np.float32,0x4313a7a5,0xbf800000,2 +np.float32,0xc313a7a5,0xbf800000,2 +np.float32,0x4216cbe4,0x3f800000,2 +np.float32,0xc216cbe4,0x3f800000,2 +np.float32,0x4296cbe4,0x3f800000,2 +np.float32,0xc296cbe4,0x3f800000,2 +np.float32,0x4316cbe4,0x3f800000,2 +np.float32,0xc316cbe4,0x3f800000,2 +np.float32,0x4219f024,0x3f3504d8,2 +np.float32,0xc219f024,0x3f3504d8,2 +np.float32,0x4299f024,0xb69bde6c,2 +np.float32,0xc299f024,0xb69bde6c,2 +np.float32,0x4319f024,0xbf800000,2 +np.float32,0xc319f024,0xbf800000,2 +np.float32,0x421d1463,0xb5455799,2 +np.float32,0xc21d1463,0xb5455799,2 +np.float32,0x429d1463,0xbf800000,2 +np.float32,0xc29d1463,0xbf800000,2 +np.float32,0x431d1463,0x3f800000,2 +np.float32,0xc31d1463,0x3f800000,2 +np.float32,0x422038a3,0xbf350516,2 +np.float32,0xc22038a3,0xbf350516,2 +np.float32,0x42a038a3,0x36c6cd61,2 +np.float32,0xc2a038a3,0x36c6cd61,2 +np.float32,0x432038a3,0xbf800000,2 +np.float32,0xc32038a3,0xbf800000,2 +np.float32,0x42235ce2,0xbf800000,2 +np.float32,0xc2235ce2,0xbf800000,2 +np.float32,0x42a35ce2,0x3f800000,2 +np.float32,0xc2a35ce2,0x3f800000,2 +np.float32,0x43235ce2,0x3f800000,2 +np.float32,0xc3235ce2,0x3f800000,2 +np.float32,0x42268121,0xbf3504f6,2 +np.float32,0xc2268121,0xbf3504f6,2 +np.float32,0x42a68121,0x34e43aac,2 +np.float32,0xc2a68121,0x34e43aac,2 +np.float32,0x43268121,0xbf800000,2 +np.float32,0xc3268121,0xbf800000,2 +np.float32,0x4229a561,0x360733d0,2 +np.float32,0xc229a561,0x360733d0,2 +np.float32,0x42a9a561,0xbf800000,2 +np.float32,0xc2a9a561,0xbf800000,2 +np.float32,0x4329a561,0x3f800000,2 +np.float32,0xc329a561,0x3f800000,2 +np.float32,0x422cc9a0,0x3f3504f8,2 +np.float32,0xc22cc9a0,0x3f3504f8,2 +np.float32,0x42acc9a0,0x35655a50,2 +np.float32,0xc2acc9a0,0x35655a50,2 +np.float32,0x432cc9a0,0xbf800000,2 +np.float32,0xc32cc9a0,0xbf800000,2 +np.float32,0x422fede0,0x3f800000,2 +np.float32,0xc22fede0,0x3f800000,2 +np.float32,0x42afede0,0x3f800000,2 +np.float32,0xc2afede0,0x3f800000,2 +np.float32,0x432fede0,0x3f800000,2 +np.float32,0xc32fede0,0x3f800000,2 +np.float32,0x4233121f,0x3f3504e7,2 +np.float32,0xc233121f,0x3f3504e7,2 +np.float32,0x42b3121f,0xb60f347d,2 +np.float32,0xc2b3121f,0xb60f347d,2 +np.float32,0x4333121f,0xbf800000,2 +np.float32,0xc333121f,0xbf800000,2 +np.float32,0x4236365e,0x350bb91c,2 +np.float32,0xc236365e,0x350bb91c,2 +np.float32,0x42b6365e,0xbf800000,2 +np.float32,0xc2b6365e,0xbf800000,2 +np.float32,0x4336365e,0x3f800000,2 +np.float32,0xc336365e,0x3f800000,2 +np.float32,0x42395a9e,0xbf350507,2 +np.float32,0xc2395a9e,0xbf350507,2 +np.float32,0x42b95a9e,0x36651267,2 +np.float32,0xc2b95a9e,0x36651267,2 +np.float32,0x43395a9e,0xbf800000,2 +np.float32,0xc3395a9e,0xbf800000,2 +np.float32,0x423c7edd,0xbf800000,2 +np.float32,0xc23c7edd,0xbf800000,2 +np.float32,0x42bc7edd,0x3f800000,2 +np.float32,0xc2bc7edd,0x3f800000,2 +np.float32,0x433c7edd,0x3f800000,2 +np.float32,0xc33c7edd,0x3f800000,2 +np.float32,0x423fa31d,0xbf3504d7,2 +np.float32,0xc23fa31d,0xbf3504d7,2 +np.float32,0x42bfa31d,0xb69d7828,2 +np.float32,0xc2bfa31d,0xb69d7828,2 +np.float32,0x433fa31d,0xbf800000,2 +np.float32,0xc33fa31d,0xbf800000,2 +np.float32,0x4242c75c,0x354bbe8a,2 +np.float32,0xc242c75c,0x354bbe8a,2 +np.float32,0x42c2c75c,0xbf800000,2 +np.float32,0xc2c2c75c,0xbf800000,2 +np.float32,0x4342c75c,0x3f800000,2 +np.float32,0xc342c75c,0x3f800000,2 +np.float32,0x4245eb9c,0x3f350517,2 +np.float32,0xc245eb9c,0x3f350517,2 +np.float32,0x42c5eb9c,0x36c8671d,2 +np.float32,0xc2c5eb9c,0x36c8671d,2 +np.float32,0x4345eb9c,0xbf800000,2 +np.float32,0xc345eb9c,0xbf800000,2 +np.float32,0x42490fdb,0x3f800000,2 +np.float32,0xc2490fdb,0x3f800000,2 +np.float32,0x42c90fdb,0x3f800000,2 +np.float32,0xc2c90fdb,0x3f800000,2 +np.float32,0x43490fdb,0x3f800000,2 +np.float32,0xc3490fdb,0x3f800000,2 +np.float32,0x424c341a,0x3f3504f5,2 +np.float32,0xc24c341a,0x3f3504f5,2 +np.float32,0x42cc341a,0x34ca9ee6,2 +np.float32,0xc2cc341a,0x34ca9ee6,2 +np.float32,0x434c341a,0xbf800000,2 +np.float32,0xc34c341a,0xbf800000,2 +np.float32,0x424f585a,0xb608cd8c,2 +np.float32,0xc24f585a,0xb608cd8c,2 +np.float32,0x42cf585a,0xbf800000,2 +np.float32,0xc2cf585a,0xbf800000,2 +np.float32,0x434f585a,0x3f800000,2 +np.float32,0xc34f585a,0x3f800000,2 +np.float32,0x42527c99,0xbf3504f9,2 +np.float32,0xc2527c99,0xbf3504f9,2 +np.float32,0x42d27c99,0x35722833,2 +np.float32,0xc2d27c99,0x35722833,2 +np.float32,0x43527c99,0xbf800000,2 +np.float32,0xc3527c99,0xbf800000,2 +np.float32,0x4255a0d9,0xbf800000,2 +np.float32,0xc255a0d9,0xbf800000,2 +np.float32,0x42d5a0d9,0x3f800000,2 +np.float32,0xc2d5a0d9,0x3f800000,2 +np.float32,0x4355a0d9,0x3f800000,2 +np.float32,0xc355a0d9,0x3f800000,2 +np.float32,0x4258c518,0xbf3504e6,2 +np.float32,0xc258c518,0xbf3504e6,2 +np.float32,0x42d8c518,0xb61267f6,2 +np.float32,0xc2d8c518,0xb61267f6,2 +np.float32,0x4358c518,0xbf800000,2 +np.float32,0xc358c518,0xbf800000,2 +np.float32,0x425be958,0x365eab75,2 +np.float32,0xc25be958,0x365eab75,2 +np.float32,0x42dbe958,0xbf800000,2 +np.float32,0xc2dbe958,0xbf800000,2 +np.float32,0x435be958,0x3f800000,2 +np.float32,0xc35be958,0x3f800000,2 +np.float32,0x425f0d97,0x3f350508,2 +np.float32,0xc25f0d97,0x3f350508,2 +np.float32,0x42df0d97,0x366845e0,2 +np.float32,0xc2df0d97,0x366845e0,2 +np.float32,0x435f0d97,0xbf800000,2 +np.float32,0xc35f0d97,0xbf800000,2 +np.float32,0x426231d6,0x3f800000,2 +np.float32,0xc26231d6,0x3f800000,2 +np.float32,0x42e231d6,0x3f800000,2 +np.float32,0xc2e231d6,0x3f800000,2 +np.float32,0x436231d6,0x3f800000,2 +np.float32,0xc36231d6,0x3f800000,2 +np.float32,0x42655616,0x3f3504d7,2 +np.float32,0xc2655616,0x3f3504d7,2 +np.float32,0x42e55616,0xb69f11e5,2 +np.float32,0xc2e55616,0xb69f11e5,2 +np.float32,0x43655616,0xbf800000,2 +np.float32,0xc3655616,0xbf800000,2 +np.float32,0x42687a55,0xb552257b,2 +np.float32,0xc2687a55,0xb552257b,2 +np.float32,0x42e87a55,0xbf800000,2 +np.float32,0xc2e87a55,0xbf800000,2 +np.float32,0x43687a55,0x3f800000,2 +np.float32,0xc3687a55,0x3f800000,2 +np.float32,0x426b9e95,0xbf350517,2 +np.float32,0xc26b9e95,0xbf350517,2 +np.float32,0x42eb9e95,0x36ca00d9,2 +np.float32,0xc2eb9e95,0x36ca00d9,2 +np.float32,0x436b9e95,0xbf800000,2 +np.float32,0xc36b9e95,0xbf800000,2 +np.float32,0x426ec2d4,0xbf800000,2 +np.float32,0xc26ec2d4,0xbf800000,2 +np.float32,0x42eec2d4,0x3f800000,2 +np.float32,0xc2eec2d4,0x3f800000,2 +np.float32,0x436ec2d4,0x3f800000,2 +np.float32,0xc36ec2d4,0x3f800000,2 +np.float32,0x4271e713,0xbf3504f5,2 +np.float32,0xc271e713,0xbf3504f5,2 +np.float32,0x42f1e713,0x34b10321,2 +np.float32,0xc2f1e713,0x34b10321,2 +np.float32,0x4371e713,0xbf800000,2 +np.float32,0xc371e713,0xbf800000,2 +np.float32,0x42750b53,0x360a6748,2 +np.float32,0xc2750b53,0x360a6748,2 +np.float32,0x42f50b53,0xbf800000,2 +np.float32,0xc2f50b53,0xbf800000,2 +np.float32,0x43750b53,0x3f800000,2 +np.float32,0xc3750b53,0x3f800000,2 +np.float32,0x42782f92,0x3f3504f9,2 +np.float32,0xc2782f92,0x3f3504f9,2 +np.float32,0x42f82f92,0x357ef616,2 +np.float32,0xc2f82f92,0x357ef616,2 +np.float32,0x43782f92,0xbf800000,2 +np.float32,0xc3782f92,0xbf800000,2 +np.float32,0x427b53d2,0x3f800000,2 +np.float32,0xc27b53d2,0x3f800000,2 +np.float32,0x42fb53d2,0x3f800000,2 +np.float32,0xc2fb53d2,0x3f800000,2 +np.float32,0x437b53d2,0x3f800000,2 +np.float32,0xc37b53d2,0x3f800000,2 +np.float32,0x427e7811,0x3f3504e6,2 +np.float32,0xc27e7811,0x3f3504e6,2 +np.float32,0x42fe7811,0xb6159b6f,2 +np.float32,0xc2fe7811,0xb6159b6f,2 +np.float32,0x437e7811,0xbf800000,2 +np.float32,0xc37e7811,0xbf800000,2 +np.float32,0x4280ce28,0x34fdd672,2 +np.float32,0xc280ce28,0x34fdd672,2 +np.float32,0x4300ce28,0xbf800000,2 +np.float32,0xc300ce28,0xbf800000,2 +np.float32,0x4380ce28,0x3f800000,2 +np.float32,0xc380ce28,0x3f800000,2 +np.float32,0x42826048,0xbf350508,2 +np.float32,0xc2826048,0xbf350508,2 +np.float32,0x43026048,0x366b7958,2 +np.float32,0xc3026048,0x366b7958,2 +np.float32,0x43826048,0xbf800000,2 +np.float32,0xc3826048,0xbf800000,2 +np.float32,0x4283f268,0xbf800000,2 +np.float32,0xc283f268,0xbf800000,2 +np.float32,0x4303f268,0x3f800000,2 +np.float32,0xc303f268,0x3f800000,2 +np.float32,0x4383f268,0x3f800000,2 +np.float32,0xc383f268,0x3f800000,2 +np.float32,0x42858487,0xbf350504,2 +np.float32,0xc2858487,0xbf350504,2 +np.float32,0x43058487,0x363ea8be,2 +np.float32,0xc3058487,0x363ea8be,2 +np.float32,0x43858487,0xbf800000,2 +np.float32,0xc3858487,0xbf800000,2 +np.float32,0x428716a7,0x35588c6d,2 +np.float32,0xc28716a7,0x35588c6d,2 +np.float32,0x430716a7,0xbf800000,2 +np.float32,0xc30716a7,0xbf800000,2 +np.float32,0x438716a7,0x3f800000,2 +np.float32,0xc38716a7,0x3f800000,2 +np.float32,0x4288a8c7,0x3f350517,2 +np.float32,0xc288a8c7,0x3f350517,2 +np.float32,0x4308a8c7,0x36cb9a96,2 +np.float32,0xc308a8c7,0x36cb9a96,2 +np.float32,0x4388a8c7,0xbf800000,2 +np.float32,0xc388a8c7,0xbf800000,2 +np.float32,0x428a3ae7,0x3f800000,2 +np.float32,0xc28a3ae7,0x3f800000,2 +np.float32,0x430a3ae7,0x3f800000,2 +np.float32,0xc30a3ae7,0x3f800000,2 +np.float32,0x438a3ae7,0x3f800000,2 +np.float32,0xc38a3ae7,0x3f800000,2 +np.float32,0x428bcd06,0x3f3504f5,2 +np.float32,0xc28bcd06,0x3f3504f5,2 +np.float32,0x430bcd06,0x3497675b,2 +np.float32,0xc30bcd06,0x3497675b,2 +np.float32,0x438bcd06,0xbf800000,2 +np.float32,0xc38bcd06,0xbf800000,2 +np.float32,0x428d5f26,0xb60c0105,2 +np.float32,0xc28d5f26,0xb60c0105,2 +np.float32,0x430d5f26,0xbf800000,2 +np.float32,0xc30d5f26,0xbf800000,2 +np.float32,0x438d5f26,0x3f800000,2 +np.float32,0xc38d5f26,0x3f800000,2 +np.float32,0x428ef146,0xbf350526,2 +np.float32,0xc28ef146,0xbf350526,2 +np.float32,0x430ef146,0x3710bc40,2 +np.float32,0xc30ef146,0x3710bc40,2 +np.float32,0x438ef146,0xbf800000,2 +np.float32,0xc38ef146,0xbf800000,2 +np.float32,0x42908365,0xbf800000,2 +np.float32,0xc2908365,0xbf800000,2 +np.float32,0x43108365,0x3f800000,2 +np.float32,0xc3108365,0x3f800000,2 +np.float32,0x43908365,0x3f800000,2 +np.float32,0xc3908365,0x3f800000,2 +np.float32,0x42921585,0xbf3504e6,2 +np.float32,0xc2921585,0xbf3504e6,2 +np.float32,0x43121585,0xb618cee8,2 +np.float32,0xc3121585,0xb618cee8,2 +np.float32,0x43921585,0xbf800000,2 +np.float32,0xc3921585,0xbf800000,2 +np.float32,0x4293a7a5,0x3661deee,2 +np.float32,0xc293a7a5,0x3661deee,2 +np.float32,0x4313a7a5,0xbf800000,2 +np.float32,0xc313a7a5,0xbf800000,2 +np.float32,0x4393a7a5,0x3f800000,2 +np.float32,0xc393a7a5,0x3f800000,2 +np.float32,0x429539c5,0x3f350536,2 +np.float32,0xc29539c5,0x3f350536,2 +np.float32,0x431539c5,0x373bab34,2 +np.float32,0xc31539c5,0x373bab34,2 +np.float32,0x439539c5,0xbf800000,2 +np.float32,0xc39539c5,0xbf800000,2 +np.float32,0x4296cbe4,0x3f800000,2 +np.float32,0xc296cbe4,0x3f800000,2 +np.float32,0x4316cbe4,0x3f800000,2 +np.float32,0xc316cbe4,0x3f800000,2 +np.float32,0x4396cbe4,0x3f800000,2 +np.float32,0xc396cbe4,0x3f800000,2 +np.float32,0x42985e04,0x3f3504d7,2 +np.float32,0xc2985e04,0x3f3504d7,2 +np.float32,0x43185e04,0xb6a2455d,2 +np.float32,0xc3185e04,0xb6a2455d,2 +np.float32,0x43985e04,0xbf800000,2 +np.float32,0xc3985e04,0xbf800000,2 +np.float32,0x4299f024,0xb69bde6c,2 +np.float32,0xc299f024,0xb69bde6c,2 +np.float32,0x4319f024,0xbf800000,2 +np.float32,0xc319f024,0xbf800000,2 +np.float32,0x4399f024,0x3f800000,2 +np.float32,0xc399f024,0x3f800000,2 +np.float32,0x429b8243,0xbf3504ea,2 +np.float32,0xc29b8243,0xbf3504ea,2 +np.float32,0x431b8243,0xb5cb2eb8,2 +np.float32,0xc31b8243,0xb5cb2eb8,2 +np.float32,0x439b8243,0xbf800000,2 +np.float32,0xc39b8243,0xbf800000,2 +np.float32,0x435b2047,0x3f3504c1,2 +np.float32,0x42a038a2,0xb5e4ca7e,2 +np.float32,0x432038a2,0xbf800000,2 +np.float32,0x4345eb9b,0xbf800000,2 +np.float32,0x42c5eb9b,0xb5de638c,2 +np.float32,0x42eb9e94,0xb5d7fc9b,2 +np.float32,0x4350ea79,0x3631dadb,2 +np.float32,0x42dbe957,0xbf800000,2 +np.float32,0x425be957,0xb505522a,2 +np.float32,0x435be957,0x3f800000,2 +np.float32,0x46027eb2,0x3e7d94c9,2 +np.float32,0x4477baed,0xbe7f1824,2 +np.float32,0x454b8024,0x3e7f5268,2 +np.float32,0x455d2c09,0x3e7f40cb,2 +np.float32,0x4768d3de,0xba14b4af,2 +np.float32,0x46c1e7cd,0x3e7fb102,2 +np.float32,0x44a52949,0xbe7dc9d5,2 +np.float32,0x4454633a,0x3e7dbc7d,2 +np.float32,0x4689810b,0x3e7eb02b,2 +np.float32,0x473473cd,0xbe7eef6f,2 +np.float32,0x44a5193f,0x3e7e1b1f,2 +np.float32,0x46004b36,0x3e7dac59,2 +np.float32,0x467f604b,0x3d7ffd3a,2 +np.float32,0x45ea1805,0x3dffd2e0,2 +np.float32,0x457b6af3,0x3dff7831,2 +np.float32,0x44996159,0xbe7d85f4,2 +np.float32,0x47883553,0xbb80584e,2 +np.float32,0x44e19f0c,0xbdffcfe6,2 +np.float32,0x472b3bf6,0xbe7f7a82,2 +np.float32,0x4600bb4e,0x3a135e33,2 +np.float32,0x449f4556,0x3e7e42e5,2 +np.float32,0x474e9420,0x3dff77b2,2 +np.float32,0x45cbdb23,0x3dff7240,2 +np.float32,0x44222747,0x3dffb039,2 +np.float32,0x4772e419,0xbdff74b8,2 +np.float64,0x1,0x3ff0000000000000,1 +np.float64,0x8000000000000001,0x3ff0000000000000,1 +np.float64,0x10000000000000,0x3ff0000000000000,1 +np.float64,0x8010000000000000,0x3ff0000000000000,1 +np.float64,0x7fefffffffffffff,0xbfefffe62ecfab75,1 +np.float64,0xffefffffffffffff,0xbfefffe62ecfab75,1 +np.float64,0x7ff0000000000000,0xfff8000000000000,1 +np.float64,0xfff0000000000000,0xfff8000000000000,1 +np.float64,0x7ff8000000000000,0x7ff8000000000000,1 +np.float64,0x7ff4000000000000,0x7ffc000000000000,1 +np.float64,0xbfc28bd9dd2517b4,0x3fefaa28ba13a702,1 +np.float64,0x3fb673c62e2ce790,0x3fefe083847a717f,1 +np.float64,0xbfe3e1dac7e7c3b6,0x3fea0500ba099f3a,1 +np.float64,0xbfbe462caa3c8c58,0x3fefc6c8b9c1c87c,1 +np.float64,0xbfb9353576326a68,0x3fefd8513e50e6b1,1 +np.float64,0xbfc05e798520bcf4,0x3fefbd1ad81cf089,1 +np.float64,0xbfe3ca3be2e79478,0x3fea12b995ea6574,1 +np.float64,0xbfde875d46bd0eba,0x3fec6d888662a824,1 +np.float64,0x3fafc4e02c3f89c0,0x3feff03c34bffd69,1 +np.float64,0xbf98855848310ac0,0x3feffda6c1588bdb,1 +np.float64,0x3fe66c51186cd8a2,0x3fe875c61c630ecb,1 +np.float64,0xbfedff1c3b7bfe38,0x3fe2f0c8c9e8fa39,1 +np.float64,0x3fd6082267ac1044,0x3fee1f6023695050,1 +np.float64,0xbfe78449b06f0894,0x3fe7bda2b223850e,1 +np.float64,0x3feedb8e63fdb71c,0x3fe23d5dfd2dd33f,1 +np.float64,0xbfc0a9de3d2153bc,0x3fefbaadf5e5285e,1 +np.float64,0x3fc04c67432098d0,0x3fefbdae07b7de8d,1 +np.float64,0xbfeeef84c4fddf0a,0x3fe22cf37f309d88,1 +np.float64,0x3fc04bb025209760,0x3fefbdb3d7d34ecf,1 +np.float64,0x3fd6b84d48ad709c,0x3fee013403da6e2a,1 +np.float64,0x3fec1ae25d7835c4,0x3fe46e62195cf274,1 +np.float64,0xbfdc6fdf9bb8dfc0,0x3fece48dc78bbb2e,1 +np.float64,0x3fb4db2c9229b660,0x3fefe4d42f79bf49,1 +np.float64,0xbfc0ed698521dad4,0x3fefb8785ea658c9,1 +np.float64,0xbfee82772b7d04ee,0x3fe2864a80efe8e9,1 +np.float64,0x3fd575b664aaeb6c,0x3fee37c669a12879,1 +np.float64,0x3fe4afb1c5e95f64,0x3fe98b177194439c,1 +np.float64,0x3fd93962f9b272c4,0x3fed8bef61876294,1 +np.float64,0x3fd97ae025b2f5c0,0x3fed7f4cfbf4d300,1 +np.float64,0xbfd9afdb1bb35fb6,0x3fed74fdc44dabb1,1 +np.float64,0x3f8ae65e3035cc80,0x3fefff4b1a0ea62b,1 +np.float64,0xbfe7e58664efcb0d,0x3fe77c02a1cbb670,1 +np.float64,0x3fe5f68b37ebed16,0x3fe8c10f849a5d4d,1 +np.float64,0x3fd9137d61b226fc,0x3fed9330eb4815a1,1 +np.float64,0x3fc146d019228da0,0x3fefb57e2d4d52f8,1 +np.float64,0xbfda6036edb4c06e,0x3fed521b2b578679,1 +np.float64,0xbfe78ddfb0ef1bc0,0x3fe7b734319a77e4,1 +np.float64,0x3fe0877823610ef0,0x3febd33a993dd786,1 +np.float64,0x3fbc61af2e38c360,0x3fefcdb4f889756d,1 +np.float64,0x3fd4dcdca4a9b9b8,0x3fee50962ffea5ae,1 +np.float64,0xbfe03cb29f607965,0x3febf7dbf640a75a,1 +np.float64,0xbfc81de407303bc8,0x3fef6f066cef64bc,1 +np.float64,0x3fd8dea42db1bd48,0x3fed9d3e00dbe0b3,1 +np.float64,0x3feac75e94f58ebe,0x3fe56f1f47f97896,1 +np.float64,0x3fb3a1ea6e2743d0,0x3fefe7ec1247cdaa,1 +np.float64,0x3fd695c0f4ad2b80,0x3fee0730bd40883d,1 +np.float64,0xbfd2c631f5a58c64,0x3feea20cbd1105d7,1 +np.float64,0xbfe978a8e1f2f152,0x3fe663014d40ad7a,1 +np.float64,0x3fd8b6b76ab16d70,0x3feda4c879aacc19,1 +np.float64,0x3feaafd30e755fa6,0x3fe5809514c28453,1 +np.float64,0x3fe1e37dc263c6fc,0x3feb20f9ad1f3f5c,1 +np.float64,0x3fd0ec7c24a1d8f8,0x3feee34048f43b75,1 +np.float64,0xbfe3881cbf67103a,0x3fea38d7886e6f53,1 +np.float64,0xbfd7023957ae0472,0x3fedf4471c765a1c,1 +np.float64,0xbfebc51c4ef78a38,0x3fe4b01c424e297b,1 +np.float64,0xbfe20a93eae41528,0x3feb0c2aa321d2e0,1 +np.float64,0x3fef39be867e737e,0x3fe1efaba9164d27,1 +np.float64,0x3fe8ea9576f1d52a,0x3fe6c7a8826ce1be,1 +np.float64,0x3fea921d91f5243c,0x3fe5968c6cf78963,1 +np.float64,0x3fd7ee5d31afdcbc,0x3fedc9f19d43fe61,1 +np.float64,0xbfe3ed581767dab0,0x3fe9fe4ee2f2b1cd,1 +np.float64,0xbfc40923d5281248,0x3fef9bd8ee9f6e68,1 +np.float64,0x3fe411a834682350,0x3fe9e9103854f057,1 +np.float64,0xbfedf6ccdf7bed9a,0x3fe2f77ad6543246,1 +np.float64,0xbfe8788a44f0f114,0x3fe7172f3aa0c742,1 +np.float64,0xbfce728f173ce520,0x3fef1954083bea04,1 +np.float64,0xbfd64dd0acac9ba2,0x3fee138c3293c246,1 +np.float64,0xbfe00669f5600cd4,0x3fec121443945350,1 +np.float64,0xbfe7152ba2ee2a58,0x3fe8079465d09846,1 +np.float64,0x3fe8654d8f70ca9c,0x3fe7247c94f09596,1 +np.float64,0x3fea68045cf4d008,0x3fe5b58cfe81a243,1 +np.float64,0xbfcd4779073a8ef4,0x3fef2a9d78153fa5,1 +np.float64,0xbfdb4456e5b688ae,0x3fed23b11614203f,1 +np.float64,0x3fcb5d59cd36bab0,0x3fef45818216a515,1 +np.float64,0xbfd914ff5ab229fe,0x3fed92e73746fea8,1 +np.float64,0x3fe4d211db69a424,0x3fe97653f433d15f,1 +np.float64,0xbfdbbb9224b77724,0x3fed0adb593dde80,1 +np.float64,0x3fd424ceafa8499c,0x3fee6d9124795d33,1 +np.float64,0x3feb5968f976b2d2,0x3fe501d116efbf54,1 +np.float64,0x3fee7d92a2fcfb26,0x3fe28a479b6a9dcf,1 +np.float64,0x3fc308e9972611d0,0x3fefa595f4df0c89,1 +np.float64,0x3fda79cd77b4f39c,0x3fed4cf8e69ba1f8,1 +np.float64,0x3fcbcf42d5379e88,0x3fef3f6a6a77c187,1 +np.float64,0x3fe13a1da662743c,0x3feb79504faea888,1 +np.float64,0xbfee4435f07c886c,0x3fe2b8ea98d2fc29,1 +np.float64,0x3fd65d68ccacbad0,0x3fee10e1ac7ada89,1 +np.float64,0x3fef2f89bb7e5f14,0x3fe1f81e882cc3f4,1 +np.float64,0xbfef0a7769fe14ef,0x3fe216bf384fc646,1 +np.float64,0x3fc065277320ca50,0x3fefbce44835c193,1 +np.float64,0x3fe9c1a74d73834e,0x3fe62e9ee0c2f2bf,1 +np.float64,0x3fd9d96e5db3b2dc,0x3fed6cd88eb51f6a,1 +np.float64,0x3fe02bf1c56057e4,0x3febfffc24b5a7ba,1 +np.float64,0xbfd6814350ad0286,0x3fee0ab9ad318b84,1 +np.float64,0x3f9fcbec583f97c0,0x3feffc0d0f1d8e75,1 +np.float64,0x3fe23524e5e46a4a,0x3feaf55372949a06,1 +np.float64,0xbfbdc95f6a3b92c0,0x3fefc89c21d44995,1 +np.float64,0x3fe961bb9cf2c378,0x3fe6735d6e1cca58,1 +np.float64,0xbfe8f1c370f1e387,0x3fe6c29d1be8bee9,1 +np.float64,0x3fd880d43ab101a8,0x3fedaee3c7ccfc96,1 +np.float64,0xbfedb37005fb66e0,0x3fe32d91ef2e3bd3,1 +np.float64,0xfdce287bfb9c5,0x3ff0000000000000,1 +np.float64,0x9aa1b9e735437,0x3ff0000000000000,1 +np.float64,0x6beac6e0d7d59,0x3ff0000000000000,1 +np.float64,0x47457aae8e8b0,0x3ff0000000000000,1 +np.float64,0x35ff13b46bfe3,0x3ff0000000000000,1 +np.float64,0xb9c0c82b73819,0x3ff0000000000000,1 +np.float64,0x1a8dc21a351b9,0x3ff0000000000000,1 +np.float64,0x7e87ef6afd0ff,0x3ff0000000000000,1 +np.float64,0x620a6588c414d,0x3ff0000000000000,1 +np.float64,0x7f366000fe6e,0x3ff0000000000000,1 +np.float64,0x787e39f4f0fc8,0x3ff0000000000000,1 +np.float64,0xf5134f1fea26a,0x3ff0000000000000,1 +np.float64,0xbce700ef79ce0,0x3ff0000000000000,1 +np.float64,0x144d7cc8289b1,0x3ff0000000000000,1 +np.float64,0xb9fbc5b973f79,0x3ff0000000000000,1 +np.float64,0xc3d6292d87ac5,0x3ff0000000000000,1 +np.float64,0xc1084e618210a,0x3ff0000000000000,1 +np.float64,0xb6b9eca56d73e,0x3ff0000000000000,1 +np.float64,0xc7ac4b858f58a,0x3ff0000000000000,1 +np.float64,0x516d75d2a2daf,0x3ff0000000000000,1 +np.float64,0x9dc089d93b811,0x3ff0000000000000,1 +np.float64,0x7b5f2840f6be6,0x3ff0000000000000,1 +np.float64,0x121d3ce8243a9,0x3ff0000000000000,1 +np.float64,0xf0be0337e17c1,0x3ff0000000000000,1 +np.float64,0xff58a5cbfeb15,0x3ff0000000000000,1 +np.float64,0xdaf1d07fb5e3a,0x3ff0000000000000,1 +np.float64,0x61d95382c3b2b,0x3ff0000000000000,1 +np.float64,0xe4df943fc9bf3,0x3ff0000000000000,1 +np.float64,0xf72ac2bdee559,0x3ff0000000000000,1 +np.float64,0x12dafbf625b60,0x3ff0000000000000,1 +np.float64,0xee11d427dc23b,0x3ff0000000000000,1 +np.float64,0xf4f8eb37e9f1e,0x3ff0000000000000,1 +np.float64,0xad7cb5df5af97,0x3ff0000000000000,1 +np.float64,0x59fc9b06b3f94,0x3ff0000000000000,1 +np.float64,0x3c3e65e4787ce,0x3ff0000000000000,1 +np.float64,0xe37bc993c6f79,0x3ff0000000000000,1 +np.float64,0x13bd6330277ad,0x3ff0000000000000,1 +np.float64,0x56cc2800ad986,0x3ff0000000000000,1 +np.float64,0x6203b8fcc4078,0x3ff0000000000000,1 +np.float64,0x75c7c8b8eb8fa,0x3ff0000000000000,1 +np.float64,0x5ebf8e00bd7f2,0x3ff0000000000000,1 +np.float64,0xda81f2f1b503f,0x3ff0000000000000,1 +np.float64,0x6adb17d6d5b64,0x3ff0000000000000,1 +np.float64,0x1ba68eee374d3,0x3ff0000000000000,1 +np.float64,0xeecf6fbbdd9ee,0x3ff0000000000000,1 +np.float64,0x24d6dd8e49add,0x3ff0000000000000,1 +np.float64,0xdf7cb81bbef97,0x3ff0000000000000,1 +np.float64,0xafd7be1b5faf8,0x3ff0000000000000,1 +np.float64,0xdb90ca35b721a,0x3ff0000000000000,1 +np.float64,0xa72903a14e521,0x3ff0000000000000,1 +np.float64,0x14533ee028a7,0x3ff0000000000000,1 +np.float64,0x7951540cf2a2b,0x3ff0000000000000,1 +np.float64,0x22882be045106,0x3ff0000000000000,1 +np.float64,0x136270d626c4f,0x3ff0000000000000,1 +np.float64,0x6a0f5744d41ec,0x3ff0000000000000,1 +np.float64,0x21e0d1aa43c1b,0x3ff0000000000000,1 +np.float64,0xee544155dca88,0x3ff0000000000000,1 +np.float64,0xcbe8aac797d16,0x3ff0000000000000,1 +np.float64,0x6c065e80d80e,0x3ff0000000000000,1 +np.float64,0xe57f0411cafe1,0x3ff0000000000000,1 +np.float64,0xdec3a6bdbd875,0x3ff0000000000000,1 +np.float64,0xf4d23a0fe9a48,0x3ff0000000000000,1 +np.float64,0xda77ef47b4efe,0x3ff0000000000000,1 +np.float64,0x8c405c9b1880c,0x3ff0000000000000,1 +np.float64,0x4eced5149d9db,0x3ff0000000000000,1 +np.float64,0x16b6552c2d6cc,0x3ff0000000000000,1 +np.float64,0x6fbc262cdf785,0x3ff0000000000000,1 +np.float64,0x628c3844c5188,0x3ff0000000000000,1 +np.float64,0x6d827d2cdb050,0x3ff0000000000000,1 +np.float64,0xd1bfdf29a37fc,0x3ff0000000000000,1 +np.float64,0xd85400fdb0a80,0x3ff0000000000000,1 +np.float64,0xcc420b2d98842,0x3ff0000000000000,1 +np.float64,0xac41d21b5883b,0x3ff0000000000000,1 +np.float64,0x432f18d4865e4,0x3ff0000000000000,1 +np.float64,0xe7e89a1bcfd14,0x3ff0000000000000,1 +np.float64,0x9b1141d536228,0x3ff0000000000000,1 +np.float64,0x6805f662d00bf,0x3ff0000000000000,1 +np.float64,0xc76552358ecab,0x3ff0000000000000,1 +np.float64,0x4ae8ffee95d21,0x3ff0000000000000,1 +np.float64,0x4396c096872d9,0x3ff0000000000000,1 +np.float64,0x6e8e55d4dd1cb,0x3ff0000000000000,1 +np.float64,0x4c2e33dc985c7,0x3ff0000000000000,1 +np.float64,0xbce814a579d03,0x3ff0000000000000,1 +np.float64,0x911681b5222d0,0x3ff0000000000000,1 +np.float64,0x5f90a4b2bf215,0x3ff0000000000000,1 +np.float64,0x26f76be84deee,0x3ff0000000000000,1 +np.float64,0xb2f7536165eeb,0x3ff0000000000000,1 +np.float64,0x4de4e6089bc9d,0x3ff0000000000000,1 +np.float64,0xf2e016afe5c03,0x3ff0000000000000,1 +np.float64,0xb9b7b949736f7,0x3ff0000000000000,1 +np.float64,0x3363ea1866c7e,0x3ff0000000000000,1 +np.float64,0xd1a3bd6ba3478,0x3ff0000000000000,1 +np.float64,0xae89f3595d13f,0x3ff0000000000000,1 +np.float64,0xddbd9601bb7c,0x3ff0000000000000,1 +np.float64,0x5de41a06bbc84,0x3ff0000000000000,1 +np.float64,0xfd58c86dfab19,0x3ff0000000000000,1 +np.float64,0x24922e8c49247,0x3ff0000000000000,1 +np.float64,0xcda040339b408,0x3ff0000000000000,1 +np.float64,0x5fe500b2bfca1,0x3ff0000000000000,1 +np.float64,0x9214abb924296,0x3ff0000000000000,1 +np.float64,0x800609fe0a2c13fd,0x3ff0000000000000,1 +np.float64,0x800c7c6fe518f8e0,0x3ff0000000000000,1 +np.float64,0x800a1a9491b4352a,0x3ff0000000000000,1 +np.float64,0x800b45e0e8968bc2,0x3ff0000000000000,1 +np.float64,0x8008497e57d092fd,0x3ff0000000000000,1 +np.float64,0x800b9c0af0173816,0x3ff0000000000000,1 +np.float64,0x800194cccb43299a,0x3ff0000000000000,1 +np.float64,0x8001c91ef183923f,0x3ff0000000000000,1 +np.float64,0x800f25b5ccde4b6c,0x3ff0000000000000,1 +np.float64,0x800ce63ccc79cc7a,0x3ff0000000000000,1 +np.float64,0x800d8fb2e83b1f66,0x3ff0000000000000,1 +np.float64,0x80083cd06f7079a1,0x3ff0000000000000,1 +np.float64,0x800823598e9046b3,0x3ff0000000000000,1 +np.float64,0x8001c1319de38264,0x3ff0000000000000,1 +np.float64,0x800f2b68543e56d1,0x3ff0000000000000,1 +np.float64,0x80022a4f4364549f,0x3ff0000000000000,1 +np.float64,0x800f51badf7ea376,0x3ff0000000000000,1 +np.float64,0x8003fbf31e27f7e7,0x3ff0000000000000,1 +np.float64,0x800d4c00e2fa9802,0x3ff0000000000000,1 +np.float64,0x800023b974804774,0x3ff0000000000000,1 +np.float64,0x800860778990c0ef,0x3ff0000000000000,1 +np.float64,0x800a15c241542b85,0x3ff0000000000000,1 +np.float64,0x8003097d9dc612fc,0x3ff0000000000000,1 +np.float64,0x800d77d8541aefb1,0x3ff0000000000000,1 +np.float64,0x80093804ab52700a,0x3ff0000000000000,1 +np.float64,0x800d2b3bfd7a5678,0x3ff0000000000000,1 +np.float64,0x800da24bcd5b4498,0x3ff0000000000000,1 +np.float64,0x8006eee1c28dddc4,0x3ff0000000000000,1 +np.float64,0x80005137fa40a271,0x3ff0000000000000,1 +np.float64,0x8007a3fbc22f47f8,0x3ff0000000000000,1 +np.float64,0x800dcd97071b9b2e,0x3ff0000000000000,1 +np.float64,0x80065b36048cb66d,0x3ff0000000000000,1 +np.float64,0x8004206ba72840d8,0x3ff0000000000000,1 +np.float64,0x8007e82b98cfd058,0x3ff0000000000000,1 +np.float64,0x8001a116ed23422f,0x3ff0000000000000,1 +np.float64,0x800c69e9ff18d3d4,0x3ff0000000000000,1 +np.float64,0x8003843688e7086e,0x3ff0000000000000,1 +np.float64,0x800335e3b8866bc8,0x3ff0000000000000,1 +np.float64,0x800e3308f0bc6612,0x3ff0000000000000,1 +np.float64,0x8002a9ec55c553d9,0x3ff0000000000000,1 +np.float64,0x80001c2084e03842,0x3ff0000000000000,1 +np.float64,0x800bc2bbd8d78578,0x3ff0000000000000,1 +np.float64,0x800ae6bcc555cd7a,0x3ff0000000000000,1 +np.float64,0x80083f7a13907ef5,0x3ff0000000000000,1 +np.float64,0x800d83ed76db07db,0x3ff0000000000000,1 +np.float64,0x800a12251974244b,0x3ff0000000000000,1 +np.float64,0x800a69c95714d393,0x3ff0000000000000,1 +np.float64,0x800cd5a85639ab51,0x3ff0000000000000,1 +np.float64,0x800e0e1837bc1c31,0x3ff0000000000000,1 +np.float64,0x8007b5ca39ef6b95,0x3ff0000000000000,1 +np.float64,0x800cf961cad9f2c4,0x3ff0000000000000,1 +np.float64,0x80066e8fc14cdd20,0x3ff0000000000000,1 +np.float64,0x8001cb8c7b43971a,0x3ff0000000000000,1 +np.float64,0x800002df68a005c0,0x3ff0000000000000,1 +np.float64,0x8003e6681567ccd1,0x3ff0000000000000,1 +np.float64,0x800b039126b60723,0x3ff0000000000000,1 +np.float64,0x800d2e1b663a5c37,0x3ff0000000000000,1 +np.float64,0x800188b3e2a31169,0x3ff0000000000000,1 +np.float64,0x8001f272e943e4e7,0x3ff0000000000000,1 +np.float64,0x800d7f53607afea7,0x3ff0000000000000,1 +np.float64,0x80092cafa4f25960,0x3ff0000000000000,1 +np.float64,0x800fc009f07f8014,0x3ff0000000000000,1 +np.float64,0x8003da896507b514,0x3ff0000000000000,1 +np.float64,0x800d4d1b4c3a9a37,0x3ff0000000000000,1 +np.float64,0x8007a835894f506c,0x3ff0000000000000,1 +np.float64,0x80057ba0522af741,0x3ff0000000000000,1 +np.float64,0x8009b7054b336e0b,0x3ff0000000000000,1 +np.float64,0x800b2c6c125658d9,0x3ff0000000000000,1 +np.float64,0x8008b1840ad16308,0x3ff0000000000000,1 +np.float64,0x8007ea0e3befd41d,0x3ff0000000000000,1 +np.float64,0x800dd658683bacb1,0x3ff0000000000000,1 +np.float64,0x8008cda48fd19b49,0x3ff0000000000000,1 +np.float64,0x8003acca14c75995,0x3ff0000000000000,1 +np.float64,0x8008bd152d717a2b,0x3ff0000000000000,1 +np.float64,0x80010d1ea3621a3e,0x3ff0000000000000,1 +np.float64,0x800130b78b826170,0x3ff0000000000000,1 +np.float64,0x8002cf3a46e59e75,0x3ff0000000000000,1 +np.float64,0x800b76e7fa76edd0,0x3ff0000000000000,1 +np.float64,0x800e065fe1dc0cc0,0x3ff0000000000000,1 +np.float64,0x8000dd527ea1baa6,0x3ff0000000000000,1 +np.float64,0x80032cb234665965,0x3ff0000000000000,1 +np.float64,0x800affc1acb5ff84,0x3ff0000000000000,1 +np.float64,0x80074be23fee97c5,0x3ff0000000000000,1 +np.float64,0x8004f83eafc9f07e,0x3ff0000000000000,1 +np.float64,0x800b02a115560543,0x3ff0000000000000,1 +np.float64,0x800b324a55766495,0x3ff0000000000000,1 +np.float64,0x800ffbcfd69ff7a0,0x3ff0000000000000,1 +np.float64,0x800830bc7b906179,0x3ff0000000000000,1 +np.float64,0x800cbafe383975fd,0x3ff0000000000000,1 +np.float64,0x8001ee42bfe3dc86,0x3ff0000000000000,1 +np.float64,0x8005b00fdc0b6020,0x3ff0000000000000,1 +np.float64,0x8005e7addd0bcf5c,0x3ff0000000000000,1 +np.float64,0x8001ae4cb0635c9a,0x3ff0000000000000,1 +np.float64,0x80098a9941131533,0x3ff0000000000000,1 +np.float64,0x800334c929466993,0x3ff0000000000000,1 +np.float64,0x8009568239d2ad05,0x3ff0000000000000,1 +np.float64,0x800f0639935e0c73,0x3ff0000000000000,1 +np.float64,0x800cebce7499d79d,0x3ff0000000000000,1 +np.float64,0x800482ee4c2905dd,0x3ff0000000000000,1 +np.float64,0x8007b7bd9e2f6f7c,0x3ff0000000000000,1 +np.float64,0x3fe654469f2ca88d,0x3fe8853f6c01ffb3,1 +np.float64,0x3feb4d7297369ae5,0x3fe50ad5bb621408,1 +np.float64,0x3feef53ba43dea77,0x3fe2283f356f8658,1 +np.float64,0x3fddf564eabbeaca,0x3fec8ec0e0dead9c,1 +np.float64,0x3fd3a69078274d21,0x3fee80e05c320000,1 +np.float64,0x3fecdafe5d39b5fd,0x3fe3d91a5d440fd9,1 +np.float64,0x3fd93286bc32650d,0x3fed8d40696cd10e,1 +np.float64,0x3fc0d34eb821a69d,0x3fefb954023d4284,1 +np.float64,0x3fc7b4b9a02f6973,0x3fef73e8739787ce,1 +np.float64,0x3fe08c839a611907,0x3febd0bc6f5641cd,1 +np.float64,0x3fb3d1758627a2eb,0x3fefe776f6183f96,1 +np.float64,0x3fef93c9ff3f2794,0x3fe1a4d2f622627d,1 +np.float64,0x3fea8d0041351a01,0x3fe59a52a1c78c9e,1 +np.float64,0x3fe3e26a30e7c4d4,0x3fea04ad3e0bbf8d,1 +np.float64,0x3fe5a34c9f6b4699,0x3fe8f57c5ccd1eab,1 +np.float64,0x3fc21ef859243df1,0x3fefae0b68a3a2e7,1 +np.float64,0x3fed7dd585fafbab,0x3fe35860041e5b0d,1 +np.float64,0x3fe5abacf22b575a,0x3fe8f03d8b6ef0f2,1 +np.float64,0x3fe426451f284c8a,0x3fe9dcf21f13205b,1 +np.float64,0x3fc01f6456203ec9,0x3fefbf19e2a8e522,1 +np.float64,0x3fe1cf2772239e4f,0x3feb2bbd645c7697,1 +np.float64,0x3fd18c4ace231896,0x3feecdfdd086c110,1 +np.float64,0x3fe8387d5b7070fb,0x3fe74358f2ec4910,1 +np.float64,0x3fdce51c2239ca38,0x3feccb2ae5459632,1 +np.float64,0x3fe5b0f2e4eb61e6,0x3fe8ecef4dbe4277,1 +np.float64,0x3fe1ceeb08a39dd6,0x3feb2bdd4dcfb3df,1 +np.float64,0x3febc5899d778b13,0x3fe4afc8dd8ad228,1 +np.float64,0x3fe7a47fbe2f48ff,0x3fe7a7fd9b352ea5,1 +np.float64,0x3fe7f74e1fafee9c,0x3fe76feb2755b247,1 +np.float64,0x3fe2bfad04e57f5a,0x3feaa9b46adddaeb,1 +np.float64,0x3fd06a090320d412,0x3feef40c334f8fba,1 +np.float64,0x3fdc97297d392e53,0x3fecdc16a3e22fcb,1 +np.float64,0x3fdc1a3f3838347e,0x3fecf6db2769d404,1 +np.float64,0x3fcca90096395201,0x3fef338156fcd218,1 +np.float64,0x3fed464733fa8c8e,0x3fe38483f0465d91,1 +np.float64,0x3fe7e067d82fc0d0,0x3fe77f7c8c9de896,1 +np.float64,0x3fc014fa0b2029f4,0x3fefbf6d84c933f8,1 +np.float64,0x3fd3bf1524277e2a,0x3fee7d2997b74dec,1 +np.float64,0x3fec153b86782a77,0x3fe472bb5497bb2a,1 +np.float64,0x3fd3e4d9d5a7c9b4,0x3fee776842691902,1 +np.float64,0x3fea6c0e2c74d81c,0x3fe5b2954cb458d9,1 +np.float64,0x3fee8f6a373d1ed4,0x3fe27bb9e348125b,1 +np.float64,0x3fd30c6dd42618dc,0x3fee97d2cab2b0bc,1 +np.float64,0x3fe4f90e6d69f21d,0x3fe95ea3dd4007f2,1 +np.float64,0x3fe271d467e4e3a9,0x3fead470d6d4008b,1 +np.float64,0x3fef2983897e5307,0x3fe1fd1a4debe33b,1 +np.float64,0x3fe980cc83b30199,0x3fe65d2fb8a0eb46,1 +np.float64,0x3fdfdf53db3fbea8,0x3fec1cf95b2a1cc7,1 +np.float64,0x3fe4d5307ba9aa61,0x3fe974701b4156cb,1 +np.float64,0x3fdb4e2345b69c47,0x3fed21aa6c146512,1 +np.float64,0x3fe3f7830327ef06,0x3fe9f85f6c88c2a8,1 +np.float64,0x3fca915fb63522bf,0x3fef502b73a52ecf,1 +np.float64,0x3fe66d3709ecda6e,0x3fe87531d7372d7a,1 +np.float64,0x3fd86000bcb0c001,0x3fedb5018dd684ca,1 +np.float64,0x3fe516e5feea2dcc,0x3fe94c68b111404e,1 +np.float64,0x3fd83c53dd3078a8,0x3fedbb9e5dd9e165,1 +np.float64,0x3fedfeeb673bfdd7,0x3fe2f0f0253c5d5d,1 +np.float64,0x3fe0dc6f9c21b8df,0x3feba8e2452410c2,1 +np.float64,0x3fbe154d643c2a9b,0x3fefc780a9357457,1 +np.float64,0x3fe5f63986abec73,0x3fe8c1434951a40a,1 +np.float64,0x3fbce0e50839c1ca,0x3fefcbeeaa27de75,1 +np.float64,0x3fd7ef5c5c2fdeb9,0x3fedc9c3022495b3,1 +np.float64,0x3fc1073914220e72,0x3fefb79de80fc0fd,1 +np.float64,0x3fe1a93c3d235278,0x3feb3fb21f86ac67,1 +np.float64,0x3fe321ee53e643dd,0x3fea72e2999f1e22,1 +np.float64,0x3fa881578c3102af,0x3feff69e6e51e0d6,1 +np.float64,0x3fd313482a262690,0x3fee96d161199495,1 +np.float64,0x3fe7272cd6ae4e5a,0x3fe7fbacbd0d8f43,1 +np.float64,0x3fd6cf4015ad9e80,0x3fedfd3513d544b8,1 +np.float64,0x3fc67b7e6d2cf6fd,0x3fef81f5c16923a4,1 +np.float64,0x3fa1999c14233338,0x3feffb2913a14184,1 +np.float64,0x3fc74eb8dd2e9d72,0x3fef78909a138e3c,1 +np.float64,0x3fc0b9274921724f,0x3fefba2ebd5f3e1c,1 +np.float64,0x3fd53fa156aa7f43,0x3fee40a18e952e88,1 +np.float64,0x3feaccbca4b59979,0x3fe56b22b33eb713,1 +np.float64,0x3fe6a01e3a2d403c,0x3fe8543fbd820ecc,1 +np.float64,0x3fd392a869a72551,0x3fee83e0ffe0e8de,1 +np.float64,0x3fe44d8928689b12,0x3fe9c5bf3c8fffdb,1 +np.float64,0x3fca3f209f347e41,0x3fef5461b6fa0924,1 +np.float64,0x3fee9e84b07d3d09,0x3fe26f638f733549,1 +np.float64,0x3faf49acb03e9359,0x3feff0b583cd8c48,1 +np.float64,0x3fea874b2af50e96,0x3fe59e882fa6febf,1 +np.float64,0x3fc50b72772a16e5,0x3fef918777dc41be,1 +np.float64,0x3fe861d1d4f0c3a4,0x3fe726e44d9d42c2,1 +np.float64,0x3fcadd2e2535ba5c,0x3fef4c3e2b56da38,1 +np.float64,0x3fea59c29cb4b385,0x3fe5c0043e586439,1 +np.float64,0x3fc1ffef0d23ffde,0x3fefaf22be452d13,1 +np.float64,0x3fc2d8dbc125b1b8,0x3fefa75b646d8e4e,1 +np.float64,0x3fd66c6471acd8c9,0x3fee0e5038b895c0,1 +np.float64,0x3fd0854adfa10a96,0x3feef0945bcc5c99,1 +np.float64,0x3feaac7076f558e1,0x3fe58316c23a82ad,1 +np.float64,0x3fdda49db3bb493b,0x3feca0e347c0ad6f,1 +np.float64,0x3fe43a539de874a7,0x3fe9d11d722d4822,1 +np.float64,0x3feeee3ebbfddc7d,0x3fe22dffd251e9af,1 +np.float64,0x3f8ee2c5b03dc58b,0x3fefff11855a7b6c,1 +np.float64,0x3fcd7107c63ae210,0x3fef2840bb55ca52,1 +np.float64,0x3f8d950d203b2a1a,0x3fefff253a08e40e,1 +np.float64,0x3fd40a5e57a814bd,0x3fee71a633c761fc,1 +np.float64,0x3fee836ec83d06de,0x3fe28580975be2fd,1 +np.float64,0x3fd7bbe87f2f77d1,0x3fedd31f661890cc,1 +np.float64,0xbfe05bf138a0b7e2,0x3febe8a000d96e47,1 +np.float64,0xbf88bddd90317bc0,0x3fefff66f6e2ff26,1 +np.float64,0xbfdc9cbb12393976,0x3fecdae2982335db,1 +np.float64,0xbfd85b4eccb0b69e,0x3fedb5e0dd87f702,1 +np.float64,0xbfe5c326cb2b864e,0x3fe8e180f525fa12,1 +np.float64,0xbfe381a0e4a70342,0x3fea3c8e5e3ab78e,1 +np.float64,0xbfe58d892c2b1b12,0x3fe9031551617aed,1 +np.float64,0xbfd7f3a52cafe74a,0x3fedc8fa97edd080,1 +np.float64,0xbfef3417bc7e682f,0x3fe1f45989f6a009,1 +np.float64,0xbfddfb8208bbf704,0x3fec8d5fa9970773,1 +np.float64,0xbfdab69bcc356d38,0x3fed40b2f6c347c6,1 +np.float64,0xbfed3f7cf17a7efa,0x3fe389e4ff4d9235,1 +np.float64,0xbfe47675d9a8ecec,0x3fe9ad6829a69e94,1 +np.float64,0xbfd030e2902061c6,0x3feefb3f811e024f,1 +np.float64,0xbfc376ac7226ed58,0x3fefa1798712b37e,1 +np.float64,0xbfdb7e54a0b6fcaa,0x3fed17a974c4bc28,1 +np.float64,0xbfdb7d5d5736faba,0x3fed17dcf31a8d84,1 +np.float64,0xbf876bd6502ed7c0,0x3fefff76dce6232c,1 +np.float64,0xbfd211e6c02423ce,0x3feebba41f0a1764,1 +np.float64,0xbfb443e3962887c8,0x3fefe658953629d4,1 +np.float64,0xbfe81b09e9b03614,0x3fe757882e4fdbae,1 +np.float64,0xbfdcb905d2b9720c,0x3fecd4c22cfe84e5,1 +np.float64,0xbfe3b62d99276c5b,0x3fea1e5520b3098d,1 +np.float64,0xbfbf05b25c3e0b68,0x3fefc3ecc04bca8e,1 +np.float64,0xbfdedc885b3db910,0x3fec59e22feb49f3,1 +np.float64,0xbfe33aa282667545,0x3fea64f2d55ec471,1 +np.float64,0xbfec84745a3908e9,0x3fe41cb3214e7044,1 +np.float64,0xbfddefdff1bbdfc0,0x3fec8fff88d4d0ec,1 +np.float64,0xbfd26ae6aca4d5ce,0x3feeaf208c7fedf6,1 +np.float64,0xbfee010591fc020b,0x3fe2ef3e57211a5e,1 +np.float64,0xbfb8cfddca319fb8,0x3fefd98d8f7918ed,1 +np.float64,0xbfe991648f3322c9,0x3fe6514e54670bae,1 +np.float64,0xbfee63fd087cc7fa,0x3fe29f1bfa3297cc,1 +np.float64,0xbfe1685942a2d0b2,0x3feb617f5f839eee,1 +np.float64,0xbfc6fc2fd62df860,0x3fef7c4698fd58cf,1 +np.float64,0xbfe42723d3a84e48,0x3fe9dc6ef7243e90,1 +np.float64,0xbfc3a7e89d274fd0,0x3fef9f99e3314e77,1 +np.float64,0xbfeb4c9521f6992a,0x3fe50b7c919bc6d8,1 +np.float64,0xbf707b34e020f680,0x3fefffef05e30264,1 +np.float64,0xbfc078478e20f090,0x3fefbc479305d5aa,1 +np.float64,0xbfd494ac4ca92958,0x3fee5c11f1cd8269,1 +np.float64,0xbfdaf888a035f112,0x3fed3346ae600469,1 +np.float64,0xbfa5d8ed502bb1e0,0x3feff88b0f262609,1 +np.float64,0xbfeec0cbfffd8198,0x3fe253543b2371cb,1 +np.float64,0xbfe594b5986b296b,0x3fe8fe9b39fb3940,1 +np.float64,0xbfc8ece7c631d9d0,0x3fef652bd0611ac7,1 +np.float64,0xbfd8ffeca0b1ffda,0x3fed96ebdf9b65cb,1 +np.float64,0xbfba9b221e353648,0x3fefd3cc21e2f15c,1 +np.float64,0xbfca63a52c34c74c,0x3fef52848eb9ed3b,1 +np.float64,0xbfe588e9b06b11d4,0x3fe905f7403e8881,1 +np.float64,0xbfc76f82db2edf04,0x3fef77138fe9bbc2,1 +np.float64,0xbfeeb3f334bd67e6,0x3fe25ddadb1096d6,1 +np.float64,0xbfbf2b64ce3e56c8,0x3fefc35a9555f6df,1 +np.float64,0xbfe9920e4ff3241c,0x3fe650d4ab8f5c42,1 +np.float64,0xbfb4a54c02294a98,0x3fefe55fc85ae5e9,1 +np.float64,0xbfe353b0c766a762,0x3fea56c02d17e4b7,1 +np.float64,0xbfd99961a4b332c4,0x3fed795fcd00dbf9,1 +np.float64,0xbfef191ddabe323c,0x3fe20aa79524f636,1 +np.float64,0xbfb25d060224ba10,0x3fefeaeee5cc8c0b,1 +np.float64,0xbfe6022428ec0448,0x3fe8b9b46e776194,1 +np.float64,0xbfed1a236cba3447,0x3fe3a76bee0d9861,1 +np.float64,0xbfc59671e72b2ce4,0x3fef8bc4daef6f14,1 +np.float64,0xbfdf2711703e4e22,0x3fec4886a8c9ceb5,1 +np.float64,0xbfeb7e207536fc41,0x3fe4e610c783f168,1 +np.float64,0xbfe6cdf5bcad9bec,0x3fe8365f8a59bc81,1 +np.float64,0xbfe55294adaaa52a,0x3fe927b0af5ccd09,1 +np.float64,0xbfdf4a88913e9512,0x3fec4036df58ba74,1 +np.float64,0xbfebb7efe4376fe0,0x3fe4ba276006992d,1 +np.float64,0xbfe09f29cfa13e54,0x3febc77f4f9c95e7,1 +np.float64,0xbfdf8c75653f18ea,0x3fec30ac924e4f46,1 +np.float64,0xbfefd601c7ffac04,0x3fe16d6f21bcb9c1,1 +np.float64,0xbfeae97ff5f5d300,0x3fe555bb5b87efe9,1 +np.float64,0xbfed427f02fa84fe,0x3fe387830db093bc,1 +np.float64,0xbfa33909cc267210,0x3feffa3a1bcb50dd,1 +np.float64,0xbfe9aa4bf5f35498,0x3fe63f6e98f6aa0f,1 +np.float64,0xbfe2d7349b25ae69,0x3fea9caa7c331e7e,1 +np.float64,0xbfcdbb2a3a3b7654,0x3fef2401c9659e4b,1 +np.float64,0xbfc8a90919315214,0x3fef686fe7fc0513,1 +np.float64,0xbfe62a98df2c5532,0x3fe89ff22a02cc6b,1 +np.float64,0xbfdc0f67b3b81ed0,0x3fecf928b637798f,1 +np.float64,0xbfebb32bf6f76658,0x3fe4bdc893c09698,1 +np.float64,0xbfec067996380cf3,0x3fe47e132741db97,1 +np.float64,0xbfd9774e1d32ee9c,0x3fed7ffe1e87c434,1 +np.float64,0xbfef989890bf3131,0x3fe1a0d025c80cf4,1 +np.float64,0xbfe59887e62b3110,0x3fe8fc382a3d4197,1 +np.float64,0xbfdea0a11e3d4142,0x3fec67b987e236ec,1 +np.float64,0xbfe2ec495825d892,0x3fea90efb231602d,1 +np.float64,0xbfb329c5c2265388,0x3fefe90f1b8209c3,1 +np.float64,0xbfdcd2dcd339a5ba,0x3feccf24c60b1478,1 +np.float64,0xbfe537ea18aa6fd4,0x3fe938237e217fe0,1 +np.float64,0xbfe8675ce170ceba,0x3fe723105925ce3a,1 +np.float64,0xbfd70723acae0e48,0x3fedf369ac070e65,1 +np.float64,0xbfea9d8692b53b0d,0x3fe58e1ee42e3fdb,1 +np.float64,0xbfcfeb96653fd72c,0x3fef029770033bdc,1 +np.float64,0xbfcc06c92d380d94,0x3fef3c69797d9b0a,1 +np.float64,0xbfe16b7c4f62d6f8,0x3feb5fdf9f0a9a07,1 +np.float64,0xbfed4d7a473a9af4,0x3fe37ecee27b1eb7,1 +np.float64,0xbfe6a6f6942d4ded,0x3fe84fccdf762b19,1 +np.float64,0xbfda46d867348db0,0x3fed572d928fa657,1 +np.float64,0xbfdbd9482db7b290,0x3fed049b5f907b52,1 +np.float64,0x7fe992ceb933259c,0xbfeb15af92aad70e,1 +np.float64,0x7fe3069204a60d23,0xbfe5eeff454240e9,1 +np.float64,0x7fe729dbf32e53b7,0xbfefe0528a330e4c,1 +np.float64,0x7fec504fb638a09e,0x3fd288e95dbedf65,1 +np.float64,0x7fe1d30167a3a602,0xbfeffc41f946fd02,1 +np.float64,0x7fed7f8ffd3aff1f,0x3fefe68ec604a19d,1 +np.float64,0x7fd2f23635a5e46b,0x3fea63032efbb447,1 +np.float64,0x7fd4c86db1a990da,0x3fdf6b9f7888db5d,1 +np.float64,0x7fe7554db6eeaa9a,0x3fe1b41476861bb0,1 +np.float64,0x7fe34e823ba69d03,0x3fefc435532e6294,1 +np.float64,0x7fec5c82fef8b905,0x3fef8f0c6473034f,1 +np.float64,0x7feba221bff74442,0xbfea95b81eb19b47,1 +np.float64,0x7fe74808a5ae9010,0xbfd3aa322917c3e5,1 +np.float64,0x7fdf41b7e0be836f,0x3fd14283c7147282,1 +np.float64,0x7fec09892f381311,0x3fe5240376ae484b,1 +np.float64,0x7faaf80bf435f017,0x3fe20227fa811423,1 +np.float64,0x7f8422d8402845b0,0x3fe911714593b8a0,1 +np.float64,0x7fd23a7fada474fe,0x3feff9f40aa37e9c,1 +np.float64,0x7fef4a4806fe948f,0x3fec6eca89cb4a62,1 +np.float64,0x7fe1e71cf763ce39,0xbfea6ac63f9ba457,1 +np.float64,0x7fe3e555be27caaa,0xbfe75b305d0dbbfd,1 +np.float64,0x7fcb8bac96371758,0xbfe8b126077f9d4c,1 +np.float64,0x7fc98e2c84331c58,0x3fef9092eb0bc85a,1 +np.float64,0x7fe947cf2b728f9d,0xbfebfff2c5b7d198,1 +np.float64,0x7feee8058c3dd00a,0xbfef21ebaae2eb17,1 +np.float64,0x7fef61d8d5bec3b1,0xbfdf1a032fb1c864,1 +np.float64,0x7fcf714b6f3ee296,0x3fe6fc89a8084098,1 +np.float64,0x7fa9a8b44c335168,0xbfeb16c149cea943,1 +np.float64,0x7fd175c482a2eb88,0xbfef64d341e73f88,1 +np.float64,0x7feab8e6a87571cc,0x3feb10069c397464,1 +np.float64,0x7fe3ade72de75bcd,0x3fd1753e333d5790,1 +np.float64,0x7fb26d87d224db0f,0xbfe753d36b18f4ca,1 +np.float64,0x7fdb7ef159b6fde2,0x3fe5c0a6044d3607,1 +np.float64,0x7fd5af86422b5f0c,0x3fe77193c95f6484,1 +np.float64,0x7fee9e00b07d3c00,0x3fe864d494596845,1 +np.float64,0x7fef927a147f24f3,0xbfe673b14715693d,1 +np.float64,0x7fd0aea63c215d4b,0xbfeff435f119fce9,1 +np.float64,0x7fd02e3796a05c6e,0x3fe4f7e3706e9a3d,1 +np.float64,0x7fd3ed61da27dac3,0xbfefef2f057f168c,1 +np.float64,0x7fefaca0d4ff5941,0x3fd3e8ad205cd4ab,1 +np.float64,0x7feb659e06f6cb3b,0x3fd64d803203e027,1 +np.float64,0x7fc94ccfaf32999e,0x3fee04922209369a,1 +np.float64,0x7feb4ec294f69d84,0xbfd102763a056c89,1 +np.float64,0x7fe2ada6ac655b4c,0x3fef4f6792aa6093,1 +np.float64,0x7fe5f40fdc2be81f,0xbfb4a6327186eee8,1 +np.float64,0x7fe7584bc3eeb097,0xbfd685b8ff94651d,1 +np.float64,0x7fe45d276be8ba4e,0x3fee53b13f7e442f,1 +np.float64,0x7fe6449b3d6c8935,0xbfe7e08bafa75251,1 +np.float64,0x7f8d62e6b03ac5cc,0x3fe73d30762f38fd,1 +np.float64,0x7fe3a76f72a74ede,0xbfeb48a28bc60968,1 +np.float64,0x7fd057706920aee0,0x3fdece8fa06f626c,1 +np.float64,0x7fe45ae158e8b5c2,0x3fe7a70f47b4d349,1 +np.float64,0x7fea8a5a983514b4,0x3fefb053d5f9ddd7,1 +np.float64,0x7fdd1e86ab3a3d0c,0x3fe3cded1b93816b,1 +np.float64,0x7fdb456108b68ac1,0xbfe37574c0b9bf8f,1 +np.float64,0x7fe972602432e4bf,0x3fef9a26e65ec01c,1 +np.float64,0x7fdbe2385637c470,0x3fed541df57969e1,1 +np.float64,0x7fe57f03602afe06,0x3fbd90f595cbbd94,1 +np.float64,0x7feb0ceb68f619d6,0xbfeae9cb8ee5261f,1 +np.float64,0x7fe6abfe6c6d57fc,0xbfef40a6edaca26f,1 +np.float64,0x7fe037ea08606fd3,0xbfda817d75858597,1 +np.float64,0x7fdd75a52dbaeb49,0x3feef2a0d91d6aa1,1 +np.float64,0x7fe8f9af66b1f35e,0xbfedfceef2a3bfc9,1 +np.float64,0x7fedf762b53beec4,0x3fd8b4f21ef69ee3,1 +np.float64,0x7fe99295b7f3252a,0x3feffc24d970383e,1 +np.float64,0x7fe797b0172f2f5f,0x3fee089aa56f7ce8,1 +np.float64,0x7fed89dcc97b13b9,0xbfcfa2bb0c3ea41f,1 +np.float64,0x7fae9e8d5c3d3d1a,0xbfe512ffe16c6b08,1 +np.float64,0x7fefaecbe27f5d97,0x3fbfc718a5e972f1,1 +np.float64,0x7fce0236d93c046d,0xbfa9b7cd790db256,1 +np.float64,0x7fa9689aac32d134,0x3feced501946628a,1 +np.float64,0x7feb1469e93628d3,0x3fef2a988e7673ed,1 +np.float64,0x7fdba78344b74f06,0xbfe092e78965b30c,1 +np.float64,0x7fece54c3fb9ca97,0x3fd3cfd184bed2e6,1 +np.float64,0x7fdb84212b370841,0xbfe25ebf2db6ee55,1 +np.float64,0x7fbe3e8bf23c7d17,0x3fe2ee72df573345,1 +np.float64,0x7fe43d9803687b2f,0xbfed2eff6a9e66a0,1 +np.float64,0x7fb0f9c00a21f37f,0x3feff70f3276fdb7,1 +np.float64,0x7fea0c6cbbb418d8,0xbfefa612494798b2,1 +np.float64,0x7fe4b3239e296646,0xbfe74dd959af8cdc,1 +np.float64,0x7fe5c6a773eb8d4e,0xbfd06944048f8d2b,1 +np.float64,0x7fb1c1278223824e,0xbfeb533a34655bde,1 +np.float64,0x7fd21c09ee243813,0xbfe921ccbc9255c3,1 +np.float64,0x7fe051020c20a203,0x3fbd519d700c1f2f,1 +np.float64,0x7fe0c76845e18ed0,0x3fefb9595191a31b,1 +np.float64,0x7fe6b0b57b6d616a,0xbf8c59a8ba5fcd9a,1 +np.float64,0x7fd386c460270d88,0x3fe8ffea5d1a5c46,1 +np.float64,0x7feeb884713d7108,0x3fee9b2247ef6c0d,1 +np.float64,0x7fd85f71b6b0bee2,0xbfefc30ec3e28f07,1 +np.float64,0x7fc341366426826c,0x3fd4234d35386d3b,1 +np.float64,0x7fe56482dd6ac905,0x3fe7189de6a50668,1 +np.float64,0x7fec67a2e3f8cf45,0xbfef86d0b940f37f,1 +np.float64,0x7fe38b202fe7163f,0x3feb90b75caa2030,1 +np.float64,0x7fdcbc64883978c8,0x3fed4f758fbf64d4,1 +np.float64,0x7fea5f0598f4be0a,0x3fdd503a417b3d4d,1 +np.float64,0x7fda3b6bcf3476d7,0x3fea6e9af3f7f9f5,1 +np.float64,0x7fc7d7896c2faf12,0x3fda2bebc36a2363,1 +np.float64,0x7fe7e8e2626fd1c4,0xbfe7d5e390c4cc3f,1 +np.float64,0x7fde0f3d7abc1e7a,0xbfede7a0ecfa3606,1 +np.float64,0x7fc692b8f52d2571,0x3feff0cd7ab6f61b,1 +np.float64,0xff92d1fce825a400,0xbfc921c36fc014fa,1 +np.float64,0xffdec3af2fbd875e,0xbfed6a77e6a0364e,1 +np.float64,0xffef46e7d9be8dcf,0xbfed7d39476f7e27,1 +np.float64,0xffe2c2ce4525859c,0x3fe1757261316bc9,1 +np.float64,0xffe27c8b5864f916,0xbfefe017c0d43457,1 +np.float64,0xffe184d7442309ae,0x3fa1fb8c49dba596,1 +np.float64,0xffddf5f98d3bebf4,0x3fee4f8eaa5f847e,1 +np.float64,0xffee3ef354fc7de6,0xbfebfd60fa51b2ba,1 +np.float64,0xffdecb3e85bd967e,0x3fbfad2667a8b468,1 +np.float64,0xffe4ee900b29dd20,0xbfdc02dc626f91cd,1 +np.float64,0xffd3179f6da62f3e,0xbfe2cfe442511776,1 +np.float64,0xffe99ef7cef33def,0x3f50994542a7f303,1 +np.float64,0xffe2b66b1ae56cd6,0xbfefe3e066eb6329,1 +np.float64,0xff8f72aff03ee540,0x3fe9c46224cf5003,1 +np.float64,0xffd29beb85a537d8,0x3fefcb0b6166be71,1 +np.float64,0xffaef02d4c3de060,0xbfef5fb71028fc72,1 +np.float64,0xffd39a2a89273456,0x3fe6d4b183205dca,1 +np.float64,0xffef8a9392ff1526,0x3fedb99fbf402468,1 +np.float64,0xffb9b3f31e3367e8,0x3fee1005270fcf80,1 +np.float64,0xffed9d5c693b3ab8,0x3fd110f4b02365d5,1 +np.float64,0xffeaba45f9f5748b,0x3fe499e0a6f4afb2,1 +np.float64,0xffdba3f70d3747ee,0xbfca0c30493ae519,1 +np.float64,0xffa35b985426b730,0xbfdb625df56bcf45,1 +np.float64,0xffccbc9728397930,0x3fc53cbc59020704,1 +np.float64,0xffef73c942bee792,0xbfdc647a7a5e08be,1 +np.float64,0xffcb5acfb236b5a0,0x3feeb4ec038c39fc,1 +np.float64,0xffea116fe2b422df,0x3fefe03b6ae0b435,1 +np.float64,0xffe97de6e7b2fbcd,0xbfd2025698fab9eb,1 +np.float64,0xffdddba314bbb746,0x3fd31f0fdb8f93be,1 +np.float64,0xffd613a24a2c2744,0xbfebbb1efae884b3,1 +np.float64,0xffe3d938aa67b271,0xbfc2099cead3d3be,1 +np.float64,0xffdf08c2e33e1186,0xbfefd236839b900d,1 +np.float64,0xffea6ba8bd34d751,0x3fe8dfc032114719,1 +np.float64,0xffe3202083e64040,0x3fed513b81432a22,1 +np.float64,0xffb2397db62472f8,0xbfee7d7fe1c3f76c,1 +np.float64,0xffd9d0682ab3a0d0,0x3fe0bcf9e531ad79,1 +np.float64,0xffc293df202527c0,0xbfe58d0bdece5e64,1 +np.float64,0xffe1422c7da28458,0xbf81bd72595f2341,1 +np.float64,0xffd64e4ed4ac9c9e,0x3fa4334cc011c703,1 +np.float64,0xffe40a970ae8152e,0x3fead3d258b55b7d,1 +np.float64,0xffc8c2f2223185e4,0xbfef685f07c8b9fd,1 +np.float64,0xffe4b2f7216965ee,0x3fe3861d3d896a83,1 +np.float64,0xffdb531db3b6a63c,0x3fe18cb8332dd59d,1 +np.float64,0xffe8e727a3b1ce4e,0xbfe57b15abb677b9,1 +np.float64,0xffe530c1e12a6184,0xbfb973ea5535e48f,1 +np.float64,0xffe6f7849cedef08,0x3fd39a37ec5af4b6,1 +np.float64,0xffead62a78b5ac54,0x3fe69b3f6c7aa24b,1 +np.float64,0xffeefdd725fdfbad,0xbfc08a456111fdd5,1 +np.float64,0xffe682182fed0430,0x3fecc7c1292761d2,1 +np.float64,0xffee0ca8dcbc1951,0x3fef6cc361ef2c19,1 +np.float64,0xffec9b338f393666,0x3fefa9ab8e0471b5,1 +np.float64,0xffe13c5e29a278bc,0xbfef8da74ad83398,1 +np.float64,0xffd7bd48c62f7a92,0x3fe3468cd4ac9d34,1 +np.float64,0xffedd0ed14bba1d9,0xbfd563a83477077b,1 +np.float64,0xffe86b83f3f0d707,0x3fe9eb3c658e4b2d,1 +np.float64,0xffd6a4db4bad49b6,0xbfc7e11276166e17,1 +np.float64,0xffc29e8404253d08,0x3fd35971961c789f,1 +np.float64,0xffe27cf3d664f9e7,0xbfeca0f73c72f810,1 +np.float64,0xffc34152352682a4,0x3fef384e564c002c,1 +np.float64,0xffe395728ba72ae4,0x3f8fe18c2de86eba,1 +np.float64,0xffed86c4fbbb0d89,0x3fef709db881c672,1 +np.float64,0xffe8a98d37f1531a,0x3fd4879c8f73c3dc,1 +np.float64,0xffb8ce9fea319d40,0xbfb853c8fe46b08d,1 +np.float64,0xffe7f26db8efe4db,0xbfec1cfd3e5c2ac1,1 +np.float64,0xffd7935b77af26b6,0x3fb7368c89b2a460,1 +np.float64,0xffc5840ed02b081c,0x3fd92220b56631f3,1 +np.float64,0xffc36a873926d510,0x3fa84d61baf61811,1 +np.float64,0xffe06ea583e0dd4a,0x3feb647e348b9e39,1 +np.float64,0xffe6a33031ed4660,0xbfe096b851dc1a0a,1 +np.float64,0xffe001c938e00392,0x3fe4eece77623e7a,1 +np.float64,0xffc1e4f23b23c9e4,0xbfdb9bb1f83f6ac4,1 +np.float64,0xffecd3ecbab9a7d9,0x3fbafb1f800f177d,1 +np.float64,0xffc2d3016825a604,0xbfef650e8b0d6afb,1 +np.float64,0xffe222cb68e44596,0x3fde3690e44de5bd,1 +np.float64,0xffe5bb145e2b7628,0x3fedbb98e23c9dc1,1 +np.float64,0xffe9e5823b73cb04,0xbfee41661016c03c,1 +np.float64,0xffd234a00ba46940,0x3fda0312cda580c2,1 +np.float64,0xffe0913ed6e1227d,0xbfed508bb529bd23,1 +np.float64,0xffe8e3596171c6b2,0xbfdc33e1c1d0310e,1 +np.float64,0xffef9c6835ff38cf,0x3fea8ce6d27dfba3,1 +np.float64,0xffdd3bcf66ba779e,0x3fe50523d2b6470e,1 +np.float64,0xffe57e8cf06afd1a,0xbfee600933347247,1 +np.float64,0xffe0d8c65fa1b18c,0x3fe75091f93d5e4c,1 +np.float64,0xffea7c8c16b4f918,0x3fee681724795198,1 +np.float64,0xffe34f7a05269ef4,0xbfe3c3e179676f13,1 +np.float64,0xffd28894a6a5112a,0xbfe5d1027aee615d,1 +np.float64,0xffc73be6f22e77cc,0x3fe469bbc08b472a,1 +np.float64,0xffe7f71b066fee36,0x3fe7ed136c8fdfaa,1 +np.float64,0xffebc13e29f7827c,0x3fefcdc6e677d314,1 +np.float64,0xffd53e9c942a7d3a,0x3fea5a02c7341749,1 +np.float64,0xffd7191b23ae3236,0x3fea419b66023443,1 +np.float64,0xffe9480325b29006,0xbfefeaff5fa38cd5,1 +np.float64,0xffba46dc0e348db8,0xbfefa54f4de28eba,1 +np.float64,0xffdd4cc31eba9986,0x3fe60bb41fe1c4da,1 +np.float64,0xffe13a70dea274e1,0xbfaa9192f7bd6c9b,1 +np.float64,0xffde25127bbc4a24,0x3f7c75f45e29be7d,1 +np.float64,0xffe4076543a80eca,0x3fea5aad50d2f687,1 +np.float64,0xffe61512acec2a25,0xbfefffeb67401649,1 +np.float64,0xffef812ec1ff025d,0xbfe919c7c073c766,1 +np.float64,0xffd5552aeaaaaa56,0x3fc89d38ab047396,1 diff --git a/shared/package-files/d0/d0f57acab07fe4f9c116c3392d85946bac8e78608f409cea70005f16ea019b57/blob b/shared/package-files/d0/d0f57acab07fe4f9c116c3392d85946bac8e78608f409cea70005f16ea019b57/blob new file mode 100644 index 0000000000000000000000000000000000000000..368e679189582990ab92cd73b8b820e74df253a7 --- /dev/null +++ b/shared/package-files/d0/d0f57acab07fe4f9c116c3392d85946bac8e78608f409cea70005f16ea019b57/blob @@ -0,0 +1,3 @@ +# Deprecated alias for xml.etree.ElementTree + +from xml.etree.ElementTree import * diff --git a/shared/package-files/d0/d0f7973193eb35d19e99d1d8bca3c7f3a8b8d0410508af34ad571aee8ec5ab05/blob b/shared/package-files/d0/d0f7973193eb35d19e99d1d8bca3c7f3a8b8d0410508af34ad571aee8ec5ab05/blob new file mode 100644 index 0000000000000000000000000000000000000000..b019974c965c4ae68265b8ca0aaecf67dc6b8a67 Binary files /dev/null and b/shared/package-files/d0/d0f7973193eb35d19e99d1d8bca3c7f3a8b8d0410508af34ad571aee8ec5ab05/blob differ diff --git a/shared/package-files/d0/d0fa53f32abd96d97fb96c50fd0a05d30f83d667315dcaa20ae2f22c52b36f62/blob b/shared/package-files/d0/d0fa53f32abd96d97fb96c50fd0a05d30f83d667315dcaa20ae2f22c52b36f62/blob new file mode 100644 index 0000000000000000000000000000000000000000..f03b7b0a38aaeec332ac57187b588d94b58b2710 --- /dev/null +++ b/shared/package-files/d0/d0fa53f32abd96d97fb96c50fd0a05d30f83d667315dcaa20ae2f22c52b36f62/blob @@ -0,0 +1,70 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::arange(Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor arange(const at::Scalar & end, at::TensorOptions options={}) { + return at::_ops::arange::call(end, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::arange(Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor arange(const at::Scalar & end, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::arange::call(end, dtype, layout, device, pin_memory); +} + +// aten::arange.start(Scalar start, Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor arange(const at::Scalar & start, const at::Scalar & end, at::TensorOptions options={}) { + return at::_ops::arange_start::call(start, end, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::arange.start(Scalar start, Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor arange(const at::Scalar & start, const at::Scalar & end, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::arange_start::call(start, end, dtype, layout, device, pin_memory); +} + +// aten::arange.start_step(Scalar start, Scalar end, Scalar step=1, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor arange(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, at::TensorOptions options={}) { + return at::_ops::arange_start_step::call(start, end, step, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::arange.start_step(Scalar start, Scalar end, Scalar step=1, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor arange(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::arange_start_step::call(start, end, step, dtype, layout, device, pin_memory); +} + +// aten::arange.out(Scalar end, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & arange_out(at::Tensor & out, const at::Scalar & end) { + return at::_ops::arange_out::call(end, out); +} +// aten::arange.out(Scalar end, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & arange_outf(const at::Scalar & end, at::Tensor & out) { + return at::_ops::arange_out::call(end, out); +} + +// aten::arange.start_out(Scalar start, Scalar end, Scalar step=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & arange_out(at::Tensor & out, const at::Scalar & start, const at::Scalar & end, const at::Scalar & step) { + return at::_ops::arange_start_out::call(start, end, step, out); +} +// aten::arange.start_out(Scalar start, Scalar end, Scalar step=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & arange_outf(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, at::Tensor & out) { + return at::_ops::arange_start_out::call(start, end, step, out); +} + +} diff --git a/shared/package-files/d0/d0faa9d7997d5696bff92384144e0b9dfb2e4c38375817613f81a89c06ec6383/blob b/shared/package-files/d0/d0faa9d7997d5696bff92384144e0b9dfb2e4c38375817613f81a89c06ec6383/blob new file mode 100644 index 0000000000000000000000000000000000000000..7cfb545b2510013caf703a7914c827112aed49c5 --- /dev/null +++ b/shared/package-files/d0/d0faa9d7997d5696bff92384144e0b9dfb2e4c38375817613f81a89c06ec6383/blob @@ -0,0 +1,6 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset es_MX DATE_FORMAT "%e/%m/%Y" + ::msgcat::mcset es_MX TIME_FORMAT_12 "%I:%M:%S %P" + ::msgcat::mcset es_MX DATE_TIME_FORMAT "%e/%m/%Y %I:%M:%S %P %z" +} diff --git a/shared/package-files/d0/d0fcf91bf804e5e905af4c010a43f3cd87f9d21b099be08934a5acceab609ddf/blob b/shared/package-files/d0/d0fcf91bf804e5e905af4c010a43f3cd87f9d21b099be08934a5acceab609ddf/blob new file mode 100644 index 0000000000000000000000000000000000000000..43057e3937632273b129d54e763f08a442dfac99 --- /dev/null +++ b/shared/package-files/d0/d0fcf91bf804e5e905af4c010a43f3cd87f9d21b099be08934a5acceab609ddf/blob @@ -0,0 +1,272 @@ +import importlib +import json +import os +import random +from abc import ABC, abstractmethod +from pathlib import Path +from typing import Dict, List, Optional +import hashlib + + +def default_cache_dir(): + return os.path.join(Path.home(), ".triton", "cache") + + +def default_override_dir(): + return os.path.join(Path.home(), ".triton", "override") + + +def default_dump_dir(): + return os.path.join(Path.home(), ".triton", "dump") + + +class CacheManager(ABC): + + def __init__(self, key): + pass + + @abstractmethod + def get_file(self, filename) -> Optional[str]: + pass + + @abstractmethod + def put(self, data, filename, binary=True) -> str: + pass + + @abstractmethod + def get_group(self, filename: str) -> Optional[Dict[str, str]]: + pass + + @abstractmethod + def put_group(self, filename: str, group: Dict[str, str]): + pass + + +class FileCacheManager(CacheManager): + + def __init__(self, key, override=False, dump=False): + self.key = key + self.lock_path = None + if dump: + self.cache_dir = default_dump_dir() + self.cache_dir = os.path.join(self.cache_dir, self.key) + self.lock_path = os.path.join(self.cache_dir, "lock") + os.makedirs(self.cache_dir, exist_ok=True) + elif override: + self.cache_dir = default_override_dir() + self.cache_dir = os.path.join(self.cache_dir, self.key) + else: + # create cache directory if it doesn't exist + self.cache_dir = os.getenv("TRITON_CACHE_DIR", "").strip() or default_cache_dir() + if self.cache_dir: + self.cache_dir = os.path.join(self.cache_dir, self.key) + self.lock_path = os.path.join(self.cache_dir, "lock") + os.makedirs(self.cache_dir, exist_ok=True) + else: + raise RuntimeError("Could not create or locate cache dir") + + def _make_path(self, filename) -> str: + return os.path.join(self.cache_dir, filename) + + def _has_file(self, filename) -> bool: + if not self.cache_dir: + raise RuntimeError("Could not create or locate cache dir") + return os.path.exists(self._make_path(filename)) + + def get_file(self, filename) -> Optional[str]: + if self._has_file(filename): + return self._make_path(filename) + else: + return None + + def get_group(self, filename: str) -> Optional[Dict[str, str]]: + grp_filename = f"__grp__{filename}" + if not self._has_file(grp_filename): + return None + grp_filepath = self._make_path(grp_filename) + with open(grp_filepath) as f: + grp_data = json.load(f) + child_paths = grp_data.get("child_paths", None) + # Invalid group data. + if child_paths is None: + return None + result = {} + for c in child_paths: + p = self._make_path(c) + if os.path.exists(p): + result[c] = p + return result + + # Note a group of pushed files as being part of a group + def put_group(self, filename: str, group: Dict[str, str]) -> str: + if not self.cache_dir: + raise RuntimeError("Could not create or locate cache dir") + grp_contents = json.dumps({"child_paths": sorted(list(group.keys()))}) + grp_filename = f"__grp__{filename}" + return self.put(grp_contents, grp_filename, binary=False) + + def put(self, data, filename, binary=True) -> str: + if not self.cache_dir: + raise RuntimeError("Could not create or locate cache dir") + binary = isinstance(data, bytes) + if not binary: + data = str(data) + assert self.lock_path is not None + filepath = self._make_path(filename) + # Random ID to avoid any collisions + rnd_id = random.randint(0, 1000000) + # we use the PID incase a bunch of these around so we can see what PID made it + pid = os.getpid() + # use tempfile to be robust against program interruptions + temp_path = f"{filepath}.tmp.pid_{pid}_{rnd_id}" + mode = "wb" if binary else "w" + with open(temp_path, mode) as f: + f.write(data) + # Replace is guaranteed to be atomic on POSIX systems if it succeeds + # so filepath cannot see a partial write + os.replace(temp_path, filepath) + return filepath + + +class RemoteCacheBackend: + """ + A backend implementation for accessing a remote/distributed cache. + """ + + def __init__(self, key: str): + pass + + @abstractmethod + def get(self, filenames: List[str]) -> Dict[str, bytes]: + pass + + @abstractmethod + def put(self, filename: str, data: bytes): + pass + + +class RedisRemoteCacheBackend(RemoteCacheBackend): + + def __init__(self, key): + import redis + self._key = key + self._key_fmt = os.environ.get("TRITON_REDIS_KEY_FORMAT", "triton:{key}:{filename}") + self._redis = redis.Redis( + host=os.environ.get("TRITON_REDIS_HOST", "localhost"), + port=int(os.environ.get("TRITON_REDIS_PORT", 6379)), + ) + + def _get_key(self, filename: str) -> str: + return self._key_fmt.format(key=self._key, filename=filename) + + def get(self, filenames: List[str]) -> Dict[str, str]: + results = self._redis.mget([self._get_key(f) for f in filenames]) + return {filename: result for filename, result in zip(filenames, results) if result is not None} + + def put(self, filename: str, data: bytes) -> Dict[str, bytes]: + self._redis.set(self._get_key(filename), data) + + +class RemoteCacheManager(CacheManager): + + def __init__(self, key, override=False, dump=False): + # Setup backend pointed too by `TRITON_REMOTE_CACHE_BACKEND`. + remote_cache_manager = os.environ["TRITON_REMOTE_CACHE_BACKEND"] + module_path, clz_nme = remote_cache_manager.split(":") + module = importlib.import_module(module_path) + remote_cache_cls = getattr(module, clz_nme) + self._backend = remote_cache_cls(key) + + self._override = override + self._dump = dump + + # Use a `FileCacheManager` to materialize remote cache paths locally. + self._file_cache_manager = FileCacheManager(key, override=override, dump=dump) + + def _materialize(self, filename: str, data: bytes): + # We use a backing `FileCacheManager` to provide the materialized data. + return self._file_cache_manager.put(data, filename, binary=True) + + def get_file(self, filename: str) -> Optional[str]: + # We don't handle the dump/override cases. + if self._dump or self._override: + return self._file_cache_manager.get_file(filename) + + # We always check the remote cache backend -- even if our internal file- + # based cache has the item -- to make sure LRU accounting works as + # expected. + results = self._backend.get([filename]) + if len(results) == 0: + return None + (_, data), = results.items() + return self._materialize(filename, data) + + def put(self, data, filename: str, binary=True) -> str: + # We don't handle the dump/override cases. + if self._dump or self._override: + return self._file_cache_manager.put(data, filename, binary=binary) + + if not isinstance(data, bytes): + data = str(data).encode("utf-8") + self._backend.put(filename, data) + return self._materialize(filename, data) + + def get_group(self, filename: str) -> Optional[Dict[str, str]]: + # We don't handle the dump/override cases. + if self._dump or self._override: + return self._file_cache_manager.get_group(filename) + + grp_filename = f"__grp__{filename}" + grp_filepath = self.get_file(grp_filename) + if grp_filepath is None: + return None + with open(grp_filepath) as f: + grp_data = json.load(f) + child_paths = grp_data.get("child_paths", None) + + result = None + + # Found group data. + if child_paths is not None: + result = {} + for child_path, data in self._backend.get(child_paths).items(): + result[child_path] = self._materialize(child_path, data) + + return result + + def put_group(self, filename: str, group: Dict[str, str]): + # We don't handle the dump/override cases. + if self._dump or self._override: + return self._file_cache_manager.put_group(filename, group) + + grp_contents = json.dumps({"child_paths": sorted(list(group.keys()))}) + grp_filename = f"__grp__{filename}" + return self.put(grp_contents, grp_filename) + + +__cache_cls = FileCacheManager +__cache_cls_nme = "DEFAULT" + + +def get_cache_manager(key) -> CacheManager: + import os + + user_cache_manager = os.environ.get("TRITON_CACHE_MANAGER", None) + global __cache_cls + global __cache_cls_nme + + if user_cache_manager is not None and user_cache_manager != __cache_cls_nme: + module_path, clz_nme = user_cache_manager.split(":") + module = importlib.import_module(module_path) + __cache_cls = getattr(module, clz_nme) + __cache_cls_nme = user_cache_manager + + return __cache_cls(key) + + +def get_override_manager(key) -> CacheManager: + return __cache_cls(key, override=True) + + +def get_dump_manager(key) -> CacheManager: + return __cache_cls(key, dump=True) diff --git a/shared/package-files/d0/d0fe17fc3e92faddf23dea67cdd0c9bdfa3143ae67a93488733b4ec1fe38173b/blob b/shared/package-files/d0/d0fe17fc3e92faddf23dea67cdd0c9bdfa3143ae67a93488733b4ec1fe38173b/blob new file mode 100644 index 0000000000000000000000000000000000000000..cca12bc4c17b6b7f0a5ddf5f61663c8d4ef64602 Binary files /dev/null and b/shared/package-files/d0/d0fe17fc3e92faddf23dea67cdd0c9bdfa3143ae67a93488733b4ec1fe38173b/blob differ diff --git a/shared/package-files/d0/d0ffb4973b6651de10e60155e16d7f39a3ead8da0aa3b1a5be6fb181122a8f7d/blob b/shared/package-files/d0/d0ffb4973b6651de10e60155e16d7f39a3ead8da0aa3b1a5be6fb181122a8f7d/blob new file mode 100644 index 0000000000000000000000000000000000000000..7fc2364b53a1e78c14187d83912898405cbc2321 --- /dev/null +++ b/shared/package-files/d0/d0ffb4973b6651de10e60155e16d7f39a3ead8da0aa3b1a5be6fb181122a8f7d/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0ffb4973b6651de10e60155e16d7f39a3ead8da0aa3b1a5be6fb181122a8f7d +size 6846016 diff --git a/shared/package-files/d0/d0ffb73a5cb4d362844098a046ae382787c0e6482b7ca105ba896b3311730713/blob b/shared/package-files/d0/d0ffb73a5cb4d362844098a046ae382787c0e6482b7ca105ba896b3311730713/blob new file mode 100644 index 0000000000000000000000000000000000000000..c3ffa29b477bd519476cd5813b4ccfce405dc19c --- /dev/null +++ b/shared/package-files/d0/d0ffb73a5cb4d362844098a046ae382787c0e6482b7ca105ba896b3311730713/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _convert_indices_from_coo_to_csr { + using schema = at::Tensor (const at::Tensor &, int64_t, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_convert_indices_from_coo_to_csr") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_convert_indices_from_coo_to_csr(Tensor self, int size, *, bool out_int32=False) -> Tensor") + static at::Tensor call(const at::Tensor & self, int64_t size, bool out_int32); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t size, bool out_int32); +}; + +struct TORCH_API _convert_indices_from_coo_to_csr_out { + using schema = at::Tensor & (const at::Tensor &, int64_t, bool, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_convert_indices_from_coo_to_csr") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_convert_indices_from_coo_to_csr.out(Tensor self, int size, *, bool out_int32=False, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, int64_t size, bool out_int32, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t size, bool out_int32, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/d1/d105409050bee7120c75bbf7123b7ef7625852dd07b6228b91b33c913671a0a9/blob b/shared/package-files/d1/d105409050bee7120c75bbf7123b7ef7625852dd07b6228b91b33c913671a0a9/blob new file mode 100644 index 0000000000000000000000000000000000000000..87745fce5b1793c02c918c65f4bc2ca6bc07f44f --- /dev/null +++ b/shared/package-files/d1/d105409050bee7120c75bbf7123b7ef7625852dd07b6228b91b33c913671a0a9/blob @@ -0,0 +1,1405 @@ +../../../bin/f2py,sha256=gcgxGPGHKvPi_OAAFmG0GvWj7QtlTnADZXSCKLZUuVM,499 +numpy-1.26.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +numpy-1.26.4.dist-info/LICENSE.txt,sha256=JjIjOQxDqdSghB4CCSZf2SehmPjonI7ugJt0N9fl6MI,1543 +numpy-1.26.4.dist-info/METADATA,sha256=TxUe79NkWbKksYMaT6r2c_P6laA5fCfFLcTNJZEgL2Y,7335 +numpy-1.26.4.dist-info/RECORD,, +numpy-1.26.4.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy-1.26.4.dist-info/WHEEL,sha256=JzzI8nVJN3Hvt8OYHYee974X3qSPVns_-ot71BuB6Rc,88 +numpy-1.26.4.dist-info/direct_url.json,sha256=antS18DhcL2qUONLvAh7n750T2ah5jhiFnVZYdZWGwU,302 +numpy-1.26.4.dist-info/entry_points.txt,sha256=zddyYJuUw9Uud7LeLfynXk62_ry0lGihDwCIgugBdZM,144 +numpy/__config__.py,sha256=VHIQbn1pniDLEvIY4w27dEPUcqyJ4ZOnBU3FSPEc6rs,12280 +numpy/__init__.cython-30.pxd,sha256=yk2a3etxRNlBgj5uLfIho2RYDYDzhRW8oagAG-wzbPI,36690 +numpy/__init__.pxd,sha256=Pa0VYRSeQRSFepQ6ROgZrNtGY5TzBXIddWsMHtK0OkM,35066 +numpy/__init__.py,sha256=Is0VNfoU10729FfMoUn_3ICHX0YL4xO4-JUnP3i8QC4,17005 +numpy/__init__.pyi,sha256=9kK465XL9oS_X3fJLv0Na29NEYnWvtdMhXPtrnF_cG8,154080 +numpy/__pycache__/__config__.cpython-310.pyc,, +numpy/__pycache__/__init__.cpython-310.pyc,, +numpy/__pycache__/_distributor_init.cpython-310.pyc,, +numpy/__pycache__/_globals.cpython-310.pyc,, +numpy/__pycache__/_pytesttester.cpython-310.pyc,, +numpy/__pycache__/conftest.cpython-310.pyc,, +numpy/__pycache__/ctypeslib.cpython-310.pyc,, +numpy/__pycache__/dtypes.cpython-310.pyc,, +numpy/__pycache__/exceptions.cpython-310.pyc,, +numpy/__pycache__/matlib.cpython-310.pyc,, +numpy/__pycache__/version.cpython-310.pyc,, +numpy/_core/__init__.py,sha256=C8_7wbHqUkB35JouY_XKsas1KLpRZ7JHWuZ7VGOPVpU,136 +numpy/_core/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/_core/__pycache__/__init__.cpython-310.pyc,, +numpy/_core/__pycache__/_dtype.cpython-310.pyc,, +numpy/_core/__pycache__/_dtype_ctypes.cpython-310.pyc,, +numpy/_core/__pycache__/_internal.cpython-310.pyc,, +numpy/_core/__pycache__/_multiarray_umath.cpython-310.pyc,, +numpy/_core/__pycache__/multiarray.cpython-310.pyc,, +numpy/_core/__pycache__/umath.cpython-310.pyc,, +numpy/_core/_dtype.py,sha256=vE16-yiwUSYsAIbq7FlEY1GbXZAp8wjADDxJg3eBX-U,126 +numpy/_core/_dtype_ctypes.py,sha256=i5EhoWPUhu4kla3Xu4ZvXF1lVLPiI6Zg4h6o8jaiamo,147 +numpy/_core/_internal.py,sha256=g5ugmqDgUhSlie5-onOctcm4p0gcMHSIRLHVYtFTk1M,135 +numpy/_core/_multiarray_umath.py,sha256=VPtoT2uHnyU3rKL0G27CgmNmB1WRHM0mtc7Y9L85C3U,159 +numpy/_core/multiarray.py,sha256=kZxC_7P3Jwz1RApzQU2QGmqSq4MAEvKmaJEYnAsbSOs,138 +numpy/_core/umath.py,sha256=YcV0cdbGcem6D5P3yX7cR9HGYBrT8VMoAgCBzGwPhgg,123 +numpy/_distributor_init.py,sha256=x43pWCTnyC2lJ451RTTeN66sa4hUhPLFA1esgMRDCp8,871 +numpy/_globals.py,sha256=neEdcfLZoHLwber_1Xyrn26LcXy0MrSta03Ze7aKa6g,3094 +numpy/_pyinstaller/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/_pyinstaller/__pycache__/__init__.cpython-310.pyc,, +numpy/_pyinstaller/__pycache__/hook-numpy.cpython-310.pyc,, +numpy/_pyinstaller/__pycache__/pyinstaller-smoke.cpython-310.pyc,, +numpy/_pyinstaller/__pycache__/test_pyinstaller.cpython-310.pyc,, +numpy/_pyinstaller/hook-numpy.py,sha256=PUQ-mNWje6bFALB-mLVFRPkvbM4JpLXunB6sjBbTy5g,1409 +numpy/_pyinstaller/pyinstaller-smoke.py,sha256=6iL-eHMQaG3rxnS5EgcvrCqElm9aKL07Cjr1FZJSXls,1143 +numpy/_pyinstaller/test_pyinstaller.py,sha256=8K-7QxmfoXCG0NwR0bhIgCNrDjGlrTzWnrR1sR8btgU,1135 +numpy/_pytesttester.py,sha256=lQUTvKVz6kT8b4yiMV-uW-vG9KSv9UzqAmxaEMezTd8,6731 +numpy/_pytesttester.pyi,sha256=OtyXSiuSy8o_78w3QNQRjMLpvvNyEdC0aMsx6T-vRxU,489 +numpy/_typing/__init__.py,sha256=6w9E9V9VaT7vTM-veua8XcySv50Je5qSPJzK9HTocIg,7003 +numpy/_typing/__pycache__/__init__.cpython-310.pyc,, +numpy/_typing/__pycache__/_add_docstring.cpython-310.pyc,, +numpy/_typing/__pycache__/_array_like.cpython-310.pyc,, +numpy/_typing/__pycache__/_char_codes.cpython-310.pyc,, +numpy/_typing/__pycache__/_dtype_like.cpython-310.pyc,, +numpy/_typing/__pycache__/_extended_precision.cpython-310.pyc,, +numpy/_typing/__pycache__/_nbit.cpython-310.pyc,, +numpy/_typing/__pycache__/_nested_sequence.cpython-310.pyc,, +numpy/_typing/__pycache__/_scalars.cpython-310.pyc,, +numpy/_typing/__pycache__/_shape.cpython-310.pyc,, +numpy/_typing/__pycache__/setup.cpython-310.pyc,, +numpy/_typing/_add_docstring.py,sha256=xQhQX372aN_m3XN95CneMxOST2FdPcovR-MXM-9ep58,3922 +numpy/_typing/_array_like.py,sha256=L4gnx2KWG8yYcouz5b9boJIkkFNtOJV6QjcnGCrbnRY,4298 +numpy/_typing/_callable.pyi,sha256=Mf57BwohRn9ye6ixJqjNEnK0gKqnVPE9Gy8vK-6_zxo,11121 +numpy/_typing/_char_codes.py,sha256=LR51O5AUBDbCmJvlMoxyUvsfvb1p7WHrexgtTGtuWTc,5916 +numpy/_typing/_dtype_like.py,sha256=21Uxy0UgIawGM82xjDF_ifMq-nP-Bkhn_LpiK_HvWC4,5661 +numpy/_typing/_extended_precision.py,sha256=dGios-1k-QBGew7YFzONZTzVWxz-aYAaqlccl2_h5Bo,777 +numpy/_typing/_nbit.py,sha256=-EQOShHpB3r30b4RVEcruQRTcTaFAZwtqCJ4BsvpEzA,345 +numpy/_typing/_nested_sequence.py,sha256=5eNaVZAV9tZQLFWHYOuVs336JjoiaWxyZQ7cMKb6m1I,2566 +numpy/_typing/_scalars.py,sha256=eVP8PjlcTIlY7v0fRI3tFXPogWtpLJZ8nFvRRrLjDqs,980 +numpy/_typing/_shape.py,sha256=JPy7jJMkISGFTnkgiEifYM-4xTcjb7JMRkLIIjZLw08,211 +numpy/_typing/_ufunc.pyi,sha256=e74LtOP9e8kkRhvrIJ_RXz9Ua_L43Pd9IixwNwermnM,12638 +numpy/_typing/setup.py,sha256=SE0Q6HPqDjWUfceA4yXgkII8y3z7EiSF0Z-MNwOIyG4,337 +numpy/_utils/__init__.py,sha256=Hhetwsi3eTBe8HdWbG51zXmcrX1DiPLxkYSrslMLYcc,723 +numpy/_utils/__pycache__/__init__.cpython-310.pyc,, +numpy/_utils/__pycache__/_convertions.cpython-310.pyc,, +numpy/_utils/__pycache__/_inspect.cpython-310.pyc,, +numpy/_utils/__pycache__/_pep440.cpython-310.pyc,, +numpy/_utils/_convertions.py,sha256=0xMxdeLOziDmHsRM_8luEh4S-kQdMoMg6GxNDDas69k,329 +numpy/_utils/_inspect.py,sha256=8Ma7QBRwfSWKeK1ShJpFNc7CDhE6fkIE_wr1FxrG1A8,7447 +numpy/_utils/_pep440.py,sha256=Vr7B3QsijR5p6h8YAz2LjNGUyzHUJ5gZ4v26NpZAKDc,14069 +numpy/array_api/__init__.py,sha256=XtttWbDf6Yh0_m4zp-L_us4HKnV3oGwdlB6n-01Q9M8,10375 +numpy/array_api/__pycache__/__init__.cpython-310.pyc,, +numpy/array_api/__pycache__/_array_object.cpython-310.pyc,, +numpy/array_api/__pycache__/_constants.cpython-310.pyc,, +numpy/array_api/__pycache__/_creation_functions.cpython-310.pyc,, +numpy/array_api/__pycache__/_data_type_functions.cpython-310.pyc,, +numpy/array_api/__pycache__/_dtypes.cpython-310.pyc,, +numpy/array_api/__pycache__/_elementwise_functions.cpython-310.pyc,, +numpy/array_api/__pycache__/_indexing_functions.cpython-310.pyc,, +numpy/array_api/__pycache__/_manipulation_functions.cpython-310.pyc,, +numpy/array_api/__pycache__/_searching_functions.cpython-310.pyc,, +numpy/array_api/__pycache__/_set_functions.cpython-310.pyc,, +numpy/array_api/__pycache__/_sorting_functions.cpython-310.pyc,, +numpy/array_api/__pycache__/_statistical_functions.cpython-310.pyc,, +numpy/array_api/__pycache__/_typing.cpython-310.pyc,, +numpy/array_api/__pycache__/_utility_functions.cpython-310.pyc,, +numpy/array_api/__pycache__/linalg.cpython-310.pyc,, +numpy/array_api/__pycache__/setup.cpython-310.pyc,, +numpy/array_api/_array_object.py,sha256=rfCBzE6vUjk4HElQGTVwe6Tw2vxiUx7tmBpQEmm1iBk,43794 +numpy/array_api/_constants.py,sha256=AYayN2jf1Dp5rXZ7WPBdUhtPBo_JMCi-pD9oW5zmFkI,87 +numpy/array_api/_creation_functions.py,sha256=6SqHdzZqHOJFEyWFtqnj6KIKRivrGXxROlgnez_3Mt0,10050 +numpy/array_api/_data_type_functions.py,sha256=P57FOsNdXahNUriVtdldonbvBQrrZkVzxZbcqkR_8AA,6288 +numpy/array_api/_dtypes.py,sha256=kDU1NLvEQN-W2HPmJ2wGPx8jiNkFbrvTCD1T1RT8Pwo,4823 +numpy/array_api/_elementwise_functions.py,sha256=0kGuDX3Ur_Qp6tBMBWTO7LPUxzXNGAlA2SSJhdAp4DU,25992 +numpy/array_api/_indexing_functions.py,sha256=d-gzqzyvR45FQerRYJrbBzCWFnDsZWSI9pggA5QWRO4,715 +numpy/array_api/_manipulation_functions.py,sha256=qCoW5B5FXcFOWKPU9D9MXHdMeXIuzvnHUUvprNlwfjc,3317 +numpy/array_api/_searching_functions.py,sha256=mGZiqheYXGWiDK9rqXFiDKX0_B0mJ1OjdA-9FC2o5lA,1715 +numpy/array_api/_set_functions.py,sha256=ULpfK1zznW9joX1DXSiP0R3ahcDB_po7mZlpsRqi7Fs,2948 +numpy/array_api/_sorting_functions.py,sha256=7pszlxNN7-DNqEZlonGLFQrlXPP7evVA8jN31NShg00,2031 +numpy/array_api/_statistical_functions.py,sha256=HspfYteZWSa3InMs10KZz-sk3ZuW6teX6fNdo829T84,3584 +numpy/array_api/_typing.py,sha256=uKidRp6nYxgHnEPaqXXZsDDZ6tw1LshpbwLvy-09eeM,1347 +numpy/array_api/_utility_functions.py,sha256=HwycylbPAgRVz4nZvjvwqN3mQnJbqKA-NRMaAvIP-CE,824 +numpy/array_api/linalg.py,sha256=QPpG2tG1pZgzjrtTjjOu2GDu3cI6UpSsLrsG_o1jXYk,18411 +numpy/array_api/setup.py,sha256=Wx6qD7GU_APiqKolYPO0OHv4eHGYrjPZmDAgjWhOEhM,341 +numpy/array_api/tests/__init__.py,sha256=t_2GZ3lKcsu4ec4GMKPUDYaeMUJyDquBlQAcPgj7kFE,282 +numpy/array_api/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/array_api/tests/__pycache__/test_array_object.cpython-310.pyc,, +numpy/array_api/tests/__pycache__/test_creation_functions.cpython-310.pyc,, +numpy/array_api/tests/__pycache__/test_data_type_functions.cpython-310.pyc,, +numpy/array_api/tests/__pycache__/test_elementwise_functions.cpython-310.pyc,, +numpy/array_api/tests/__pycache__/test_indexing_functions.cpython-310.pyc,, +numpy/array_api/tests/__pycache__/test_manipulation_functions.cpython-310.pyc,, +numpy/array_api/tests/__pycache__/test_set_functions.cpython-310.pyc,, +numpy/array_api/tests/__pycache__/test_sorting_functions.cpython-310.pyc,, +numpy/array_api/tests/__pycache__/test_validation.cpython-310.pyc,, +numpy/array_api/tests/test_array_object.py,sha256=FQoAxP4CLDiv6iih8KKUDSLuYM6dtnDcB1f0pMHw4-M,17035 +numpy/array_api/tests/test_creation_functions.py,sha256=s3A1COWmXIAJdhzd8v7VtL-jbiSspskTqwYy0BTpmpw,5023 +numpy/array_api/tests/test_data_type_functions.py,sha256=qc8ktRlVXWC3PKhxPVWI_UF9f1zZtpmzHjdCtf3e16E,1018 +numpy/array_api/tests/test_elementwise_functions.py,sha256=CTj4LLwtusI51HkpzD0JPohP1ffNxogAVFz8WLuWFzM,3800 +numpy/array_api/tests/test_indexing_functions.py,sha256=AbuBGyEufEAf24b7fy8JQhdJtGPdP9XEIxPTJAfAFFo,627 +numpy/array_api/tests/test_manipulation_functions.py,sha256=wce25dSJjubrGhFxmiatzR_IpmNYp9ICJ9PZBBnZTOQ,1087 +numpy/array_api/tests/test_set_functions.py,sha256=D016G7v3ko49bND5sVERP8IqQXZiwr-2yrKbBPJ-oqg,546 +numpy/array_api/tests/test_sorting_functions.py,sha256=INPiYnuGBcsmWtYqdTTX3ENHmM4iUx4zs9KdwDaSmdA,602 +numpy/array_api/tests/test_validation.py,sha256=QUG9yWC3QhkPxNhbQeakwBbl-0Rr0iTuZ41_0sfVIGU,676 +numpy/compat/__init__.py,sha256=iAHrmsZWzouOMSyD9bdSE0APWMlRpqW92MQgF8y6x3E,448 +numpy/compat/__pycache__/__init__.cpython-310.pyc,, +numpy/compat/__pycache__/py3k.cpython-310.pyc,, +numpy/compat/__pycache__/setup.cpython-310.pyc,, +numpy/compat/py3k.py,sha256=Je74CVk_7qI_qX7pLbYcuQJsxlMq1poGIfRIrH99kZQ,3833 +numpy/compat/setup.py,sha256=36X1kF0C_NVROXfJ7w3SQeBm5AIDBuJbM5qT7cvSDgU,335 +numpy/compat/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/compat/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/compat/tests/__pycache__/test_compat.cpython-310.pyc,, +numpy/compat/tests/test_compat.py,sha256=YqV67pSN8nXPbXaEdjhmyaoVetNyFupVv57OMEgCwKA,579 +numpy/conftest.py,sha256=HZyWo_wJyrbgnyXxI8t05WOg_IrzNAMnEV7O8koHous,4623 +numpy/core/__init__.py,sha256=CNsO-Ab4ywM2Wz3AbqWOH3ig1q5Bno9PsUMrCv-HNS4,5780 +numpy/core/__init__.pyi,sha256=xtd9OFYza-ZG3jyEJrlzRPT-SkVoB_qYmVCe6FxRks0,126 +numpy/core/__pycache__/__init__.cpython-310.pyc,, +numpy/core/__pycache__/_add_newdocs.cpython-310.pyc,, +numpy/core/__pycache__/_add_newdocs_scalars.cpython-310.pyc,, +numpy/core/__pycache__/_asarray.cpython-310.pyc,, +numpy/core/__pycache__/_dtype.cpython-310.pyc,, +numpy/core/__pycache__/_dtype_ctypes.cpython-310.pyc,, +numpy/core/__pycache__/_exceptions.cpython-310.pyc,, +numpy/core/__pycache__/_internal.cpython-310.pyc,, +numpy/core/__pycache__/_machar.cpython-310.pyc,, +numpy/core/__pycache__/_methods.cpython-310.pyc,, +numpy/core/__pycache__/_string_helpers.cpython-310.pyc,, +numpy/core/__pycache__/_type_aliases.cpython-310.pyc,, +numpy/core/__pycache__/_ufunc_config.cpython-310.pyc,, +numpy/core/__pycache__/arrayprint.cpython-310.pyc,, +numpy/core/__pycache__/cversions.cpython-310.pyc,, +numpy/core/__pycache__/defchararray.cpython-310.pyc,, +numpy/core/__pycache__/einsumfunc.cpython-310.pyc,, +numpy/core/__pycache__/fromnumeric.cpython-310.pyc,, +numpy/core/__pycache__/function_base.cpython-310.pyc,, +numpy/core/__pycache__/getlimits.cpython-310.pyc,, +numpy/core/__pycache__/memmap.cpython-310.pyc,, +numpy/core/__pycache__/multiarray.cpython-310.pyc,, +numpy/core/__pycache__/numeric.cpython-310.pyc,, +numpy/core/__pycache__/numerictypes.cpython-310.pyc,, +numpy/core/__pycache__/overrides.cpython-310.pyc,, +numpy/core/__pycache__/records.cpython-310.pyc,, +numpy/core/__pycache__/shape_base.cpython-310.pyc,, +numpy/core/__pycache__/umath.cpython-310.pyc,, +numpy/core/__pycache__/umath_tests.cpython-310.pyc,, +numpy/core/_add_newdocs.py,sha256=39JFaeDPN2OQlSwfpY6_Jq9fO5vML8ZMF8J4ZTx_nrs,208972 +numpy/core/_add_newdocs_scalars.py,sha256=PF9v8POcSNH6ELYltkx9e07DWgMmft6NJy9zER3Jk44,12106 +numpy/core/_asarray.py,sha256=P2ddlZAsg1iGleRRfoQv_aKs2N7AGwpo5K4ZQv4Ujlk,3884 +numpy/core/_asarray.pyi,sha256=gNNxUVhToNU_F1QpgeEvUYddpUFN-AKP0QWa4gqcTGw,1086 +numpy/core/_dtype.py,sha256=SihUz41pHRB3Q2LiYYkug6LgMBKh6VV89MOpLxnXQdo,10606 +numpy/core/_dtype_ctypes.py,sha256=Vug4i7xKhznK2tdIjmn4ebclClpaCJwSZUlvEoYl0Eg,3673 +numpy/core/_exceptions.py,sha256=dZWKqfdLRvJvbAEG_fof_8ikEKxjakADMty1kLC_l_M,5379 +numpy/core/_internal.py,sha256=f9kNDuT-FGxF1EtVOVIxXWnH9gM9n-J5V2zwHMv4HEk,28348 +numpy/core/_internal.pyi,sha256=_mCTOX6Su8D4R9fV4HNeohPJx7515B-WOlv4uq6mry8,1032 +numpy/core/_machar.py,sha256=G3a3TXu8VDW_1EMxKKLnGMbvUShEIUEve3ealBlJJ3E,11565 +numpy/core/_methods.py,sha256=m31p0WjcFUGckbJiHnCpSaIQGqv-Lq5niIYkdd33YMo,8613 +numpy/core/_multiarray_tests.cpython-310-x86_64-linux-gnu.so,sha256=ztzDpzUZKKMVVTT1tPI9hTs2gdt-aLY_yyoG4eHBMc8,165120 +numpy/core/_multiarray_umath.cpython-310-x86_64-linux-gnu.so,sha256=H6qAV37HU9cwcfRx9pDD8k7Y_cASpM3kFySD4eOfL7w,6296344 +numpy/core/_operand_flag_tests.cpython-310-x86_64-linux-gnu.so,sha256=gmznnJHqmNmvBaO7aiNSuItpHW8rykDM2Jdx3740-As,16112 +numpy/core/_rational_tests.cpython-310-x86_64-linux-gnu.so,sha256=v_GBFgmShuGVm53GTp1rpkkGTpFYwMx8zKLKILT3GME,54960 +numpy/core/_simd.cpython-310-x86_64-linux-gnu.so,sha256=szPxne29laGkAEn24ZyxskZUzb5yIH1n8Dml8DHLqPE,3698448 +numpy/core/_string_helpers.py,sha256=-fQM8z5s8_yX440PmgNEH3SUjEoXMPpPSysZwWZNbuo,2852 +numpy/core/_struct_ufunc_tests.cpython-310-x86_64-linux-gnu.so,sha256=j0dzfNWR3_TsnqAox8uSl2EJp9f3yMBgJalqFoyhkVE,16472 +numpy/core/_type_aliases.py,sha256=qV6AZlsUWHMWTydmZya73xuBkKXiUKq_WXLj7q2CbZ0,7534 +numpy/core/_type_aliases.pyi,sha256=lguMSqMwvqAFHuRtm8YZSdKbikVz985BdKo_lo7GQCg,404 +numpy/core/_ufunc_config.py,sha256=-Twpe8dnd45ccXH-w-B9nvU8yCOd1E0e3Wpsts3g_bQ,13944 +numpy/core/_ufunc_config.pyi,sha256=-615enOVQMBhVx7Pln7DY_s4H6JjSgSnBy89YkpvuLg,1066 +numpy/core/_umath_tests.cpython-310-x86_64-linux-gnu.so,sha256=LW6Ve0At0TZU8A5arT8jA7Oz7_2SVNh2buhYMmY8VJ4,41264 +numpy/core/arrayprint.py,sha256=ySZj4TZFFVCa5yhMmJKFYQYhuQTabZTRBb1YoiCD-ac,63608 +numpy/core/arrayprint.pyi,sha256=21pOWjTSfJOBaKgOOPzRox1ERb3c9ydufqL0b11_P_Q,4428 +numpy/core/cversions.py,sha256=H_iNIpx9-hY1cQNxqjT2d_5SXZhJbMo_caq4_q6LB7I,347 +numpy/core/defchararray.py,sha256=G1LExk-dMeVTYRhtYgcCZEsHk5tkawk7giXcK4Q5KVM,73617 +numpy/core/defchararray.pyi,sha256=ib3aWFcM7F4KooU57mWUNi4GlosNjdfgrLKBVSIKDvU,9216 +numpy/core/einsumfunc.py,sha256=TrL6t79F0H0AQH0y5Cj7Tq0_pzk4fVFi-4q4jJmujYQ,51868 +numpy/core/einsumfunc.pyi,sha256=IJZNdHHG_soig8XvCbXZl43gMr3MMKl9dckTYWecqLs,4860 +numpy/core/fromnumeric.py,sha256=YMtxOBg51VMem39AHXFs-4_vOb1p48ei7njXdYTRJ_Q,128821 +numpy/core/fromnumeric.pyi,sha256=KATMFeFxUJ8YNRaC-jd_dTOt3opz2ng6lHgke5u5COk,23726 +numpy/core/function_base.py,sha256=tHg1qSHTz1eO_wHXNFRt3Q40uqVtPT2eyQdrWbIi4wQ,19836 +numpy/core/function_base.pyi,sha256=3ZYad3cdaGwNEyP8VwK97IYMqk2PDoVjpjQzhIYHjk0,4725 +numpy/core/getlimits.py,sha256=AopcTZDCUXMPcEKIZE1botc3mEhmLb2p1_ejlq1CLqY,25865 +numpy/core/getlimits.pyi,sha256=qeIXUEtognTHr_T-tv-VcZI7n8Z2VzAyIpIgKXzsLkc,82 +numpy/core/include/numpy/__multiarray_api.c,sha256=nPRzTez_Wy3YXy3zZNJNPMspAzxbLOdohqhXwouwMLM,12116 +numpy/core/include/numpy/__multiarray_api.h,sha256=ZM--FKMhIaSQS39cPW0hj5dx8ngNMmbcy6SbgXZBd8U,61450 +numpy/core/include/numpy/__ufunc_api.c,sha256=670Gcz-vhkF4taBDmktCpFRBrZ9CHJnPRx7ag7Z6HsI,1714 +numpy/core/include/numpy/__ufunc_api.h,sha256=0MBOl7dgO3ldqdDi-SdciEOuqGv1UNsmk7mp7tEy4AY,12456 +numpy/core/include/numpy/_dtype_api.h,sha256=4veCexGvx9KNWMIUuEUAVOfcsei9GqugohDY5ud16pA,16697 +numpy/core/include/numpy/_neighborhood_iterator_imp.h,sha256=s-Hw_l5WRwKtYvsiIghF0bg-mA_CgWnzFFOYVFJ-q4k,1857 +numpy/core/include/numpy/_numpyconfig.h,sha256=o0fV_jb-wgVtRxnVIWvUttiZafyrWYFm2ab9Uixz1Cw,855 +numpy/core/include/numpy/arrayobject.h,sha256=-BlWQ7kfVbzCqzHn0qaeMe0_08AbwliuG98XWG57lT8,282 +numpy/core/include/numpy/arrayscalars.h,sha256=C3vDRndZTZRbppiDyV5jp8sV3dRKsrwBIZcNlh9gSTA,3944 +numpy/core/include/numpy/experimental_dtype_api.h,sha256=tlehD5r_pYhHbGzIrUea6vtOgf6IQ8Txblnhx7455h8,15532 +numpy/core/include/numpy/halffloat.h,sha256=TRZfXgipa-dFppX2uNgkrjrPli-1BfJtadWjAembJ4s,1959 +numpy/core/include/numpy/ndarrayobject.h,sha256=PhY4NjRZDoU5Zbc8MW0swPEm81hwgWZ63gAU93bLVVI,10183 +numpy/core/include/numpy/ndarraytypes.h,sha256=EjWXv-J8C5JET4AlIbJRdctycL7-dyJZcnoWgnlCPc8,68009 +numpy/core/include/numpy/noprefix.h,sha256=d83l1QpCCVqMV2k29NMkL3Ld1qNjiC6hzOPWZAivEjQ,6830 +numpy/core/include/numpy/npy_1_7_deprecated_api.h,sha256=y0MJ8Qw7Bkt4H_4VxIzHzpkw5JqAdj5ECgtn08fZFrI,4327 +numpy/core/include/numpy/npy_3kcompat.h,sha256=SvN9yRA3i02O4JFMXxZz0Uq_vJ5ZpvC-pC2sfF56A5I,15883 +numpy/core/include/numpy/npy_common.h,sha256=apWBsCJeP8P5T0exgzhFcGohbASsUF8vtFdS2jc1VfU,37746 +numpy/core/include/numpy/npy_cpu.h,sha256=pcVRtj-Y6120C5kWB1VAiAjZoxkTPDEg0gGm5IAt3jM,4629 +numpy/core/include/numpy/npy_endian.h,sha256=we7X9fPeWzNpo_YTh09MPGDwdE0Rw_WDM4c9y4nBj5I,2786 +numpy/core/include/numpy/npy_interrupt.h,sha256=DQZIxi6FycLXD8drdHn2SSmLoRhIpo6osvPv13vowUA,1948 +numpy/core/include/numpy/npy_math.h,sha256=SbKRoc7O3gVuDl7HOZjk424O049I0zn-7i9GwBwNmmk,18945 +numpy/core/include/numpy/npy_no_deprecated_api.h,sha256=0yZrJcQEJ6MCHJInQk5TP9_qZ4t7EfBuoLOJ34IlJd4,678 +numpy/core/include/numpy/npy_os.h,sha256=hlQsg_7-RkvS3s8OM8KXy99xxyJbCm-W1AYVcdnO1cw,1256 +numpy/core/include/numpy/numpyconfig.h,sha256=Nr59kE3cXmen6y0UymIBaU7F1BSIuPwgKZ4gdV5Q5JU,5308 +numpy/core/include/numpy/old_defines.h,sha256=xuYQDDlMywu0Zsqm57hkgGwLsOFx6IvxzN2eiNF-gJY,6405 +numpy/core/include/numpy/random/LICENSE.txt,sha256=-8U59H0M-DvGE3gID7hz1cFGMBJsrL_nVANcOSbapew,1018 +numpy/core/include/numpy/random/bitgen.h,sha256=49AwKOR552r-NkhuSOF1usb_URiMSRMvD22JF5pKIng,488 +numpy/core/include/numpy/random/distributions.h,sha256=W5tOyETd0m1W0GdaZ5dJP8fKlBtsTpG23V2Zlmrlqpg,9861 +numpy/core/include/numpy/random/libdivide.h,sha256=ew9MNhPQd1LsCZiWiFmj9IZ7yOnA3HKOXffDeR9X1jw,80138 +numpy/core/include/numpy/ufuncobject.h,sha256=Xmnny_ulZo9VwxkfkXF-1HCTKDavIp9PV_H7XWhi0Z8,12070 +numpy/core/include/numpy/utils.h,sha256=wMNomSH3Dfj0q78PrjLVtFtN-FPo7UJ4o0ifCUO-6Es,1185 +numpy/core/lib/libnpymath.a,sha256=1n7qY6QIe-JWhKIgmSFj3Vm2ntrpIECa7S6Q8umMDWM,117200 +numpy/core/lib/npy-pkg-config/mlib.ini,sha256=_LsWV1eStNqwhdiYPa2538GL46dnfVwT4MrI1zbsoFw,147 +numpy/core/lib/npy-pkg-config/npymath.ini,sha256=kamUNrYKAmXqQa8BcNv7D5sLqHh6bnChM0_5rZCsTfY,360 +numpy/core/memmap.py,sha256=yWBJLeVClHsD8BYusnf9bdqypOMPrj3_zoO_lQ2zVMc,11771 +numpy/core/memmap.pyi,sha256=sxIQ7T5hPLG-RBNndAc8JPvrsKEX1amBSH2HGg48Obo,55 +numpy/core/multiarray.py,sha256=zXaWf_DSkFEWjUQqVRCGeevwsI6kjQ3x6_MUwA1Y8fk,56097 +numpy/core/multiarray.pyi,sha256=_0X4W90U5ZiKt2n-9OscK-pcQyV6oGK-8jwGy5k1qxA,24768 +numpy/core/numeric.py,sha256=DgajaCDXiiQR-zuW_rrx_QhApSsa5k5FONK3Uk9mfTs,77014 +numpy/core/numeric.pyi,sha256=oVQkI4ABayFl_ZzCiGH4DxfYASL-3aETi-3B93THnEQ,14315 +numpy/core/numerictypes.py,sha256=qIf9v1OpNjjVQzXnKpD-3V01y5Bj9huw5F-U5Wa4glc,18098 +numpy/core/numerictypes.pyi,sha256=dEqtq9MLrGaqqeAF1sdXBgnEwDWOzlK02A6MTg1PS5g,3267 +numpy/core/overrides.py,sha256=YUZFS8RCBvOJ27sH-jDRcyMjOCn9VigMyuQY4J21JBI,7093 +numpy/core/records.py,sha256=4mpIjUp2XtZxY5cD2S8mgfn8GCzQGGrrkqLBqAJwM-Q,37533 +numpy/core/records.pyi,sha256=uYwE6cAoGKgN6U4ryfGZx_3m-3sY006jytjWLrDRRy0,5692 +numpy/core/shape_base.py,sha256=RPMKxA7_FCAgg_CruExl0LehnczSTFaxA6hrcfrUzns,29743 +numpy/core/shape_base.pyi,sha256=Ilb4joJmbjkIZLzKww7NJeaxg2FP3AfFib3HtfOsrC0,2774 +numpy/core/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/core/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/core/tests/__pycache__/_locales.cpython-310.pyc,, +numpy/core/tests/__pycache__/test__exceptions.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_abc.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_api.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_argparse.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_array_coercion.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_array_interface.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_arraymethod.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_arrayprint.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_casting_floatingpoint_errors.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_casting_unittests.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_conversion_utils.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_cpu_dispatcher.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_cpu_features.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_custom_dtypes.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_cython.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_datetime.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_defchararray.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_deprecations.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_dlpack.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_dtype.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_einsum.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_errstate.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_extint128.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_function_base.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_getlimits.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_half.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_hashtable.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_indexerrors.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_indexing.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_item_selection.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_limited_api.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_longdouble.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_machar.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_mem_overlap.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_mem_policy.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_memmap.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_multiarray.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_nditer.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_nep50_promotions.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_numeric.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_numerictypes.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_numpy_2_0_compat.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_overrides.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_print.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_protocols.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_records.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_regression.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_scalar_ctors.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_scalar_methods.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_scalarbuffer.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_scalarinherit.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_scalarmath.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_scalarprint.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_shape_base.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_simd.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_simd_module.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_strings.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_ufunc.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_umath.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_umath_accuracy.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_umath_complex.cpython-310.pyc,, +numpy/core/tests/__pycache__/test_unicode.cpython-310.pyc,, +numpy/core/tests/_locales.py,sha256=S4x5soqF0oxpBYOE8J9Iky72O9J25IiZ8349m93pWC4,2206 +numpy/core/tests/data/astype_copy.pkl,sha256=lWSzCcvzRB_wpuRGj92spGIw-rNPFcd9hwJaRVvfWdk,716 +numpy/core/tests/data/generate_umath_validation_data.cpp,sha256=fyhQPNhIX9hzjeXujn6mhi1MVc133zELSV_hlSQ7BQU,5842 +numpy/core/tests/data/numpy_2_0_array.pkl,sha256=Vh02tdyCypa8Nb4QzdVhnDAiXEO2WQrcwcvOdDDFF5w,718 +numpy/core/tests/data/recarray_from_file.fits,sha256=NA0kliz31FlLnYxv3ppzeruONqNYkuEvts5wzXEeIc4,8640 +numpy/core/tests/data/umath-validation-set-README.txt,sha256=pxWwOaGGahaRd-AlAidDfocLyrAiDp0whf5hC7hYwqM,967 +numpy/core/tests/data/umath-validation-set-arccos.csv,sha256=W_aL99bjzVjlVyd5omfDUORag8jHzx6uctedPVZgOHQ,61365 +numpy/core/tests/data/umath-validation-set-arccosh.csv,sha256=Uko_d0kDXr1YlN-6Ii-fQQxUvbXAhRfC7Un4gJ23GJk,61365 +numpy/core/tests/data/umath-validation-set-arcsin.csv,sha256=15Aenze4WD2a2dF2aOBXpv9B7u3wwAeUVJdEm4TjOkQ,61339 +numpy/core/tests/data/umath-validation-set-arcsinh.csv,sha256=uDwx4PStpfV21IaPF8pmzQpul6i72g7zDwlfcynWaVQ,60289 +numpy/core/tests/data/umath-validation-set-arctan.csv,sha256=mw5tYze_BMs6ugGEZfg5mcXoInGYdn7fvSCYSUi9Bqw,60305 +numpy/core/tests/data/umath-validation-set-arctanh.csv,sha256=95l4Uu5RmZajljabfqlv5U34RVrifCMhhkop6iLeNBo,61339 +numpy/core/tests/data/umath-validation-set-cbrt.csv,sha256=v855MTZih-fZp_GuEDst2qaIsxU4a7vlAbeIJy2xKpc,60846 +numpy/core/tests/data/umath-validation-set-cos.csv,sha256=0PNnDqKkokZ7ERVDgbes8KNZc-ISJrZUlVZc5LkW18E,59122 +numpy/core/tests/data/umath-validation-set-cosh.csv,sha256=FGCNeUSUTAeASsb_j18iRSsCxXLxmzF-_C7tq1elVrQ,60869 +numpy/core/tests/data/umath-validation-set-exp.csv,sha256=BKg1_cyrKD2GXYMX_EB0DnXua8DI2O1KWODXf_BRhrk,17491 +numpy/core/tests/data/umath-validation-set-exp2.csv,sha256=f1b05MRXPOXihC9M-yi52udKBzVXalhbTuIcqoDAk-g,58624 +numpy/core/tests/data/umath-validation-set-expm1.csv,sha256=_ghc1xiUECNsBGrKCFUAy2lvu01_lkpeYJN0zDtCYWk,60299 +numpy/core/tests/data/umath-validation-set-log.csv,sha256=z9ej1ykKUoMRqYMUIJENWXbYi_A_x_RKs7K_GuXZJus,11692 +numpy/core/tests/data/umath-validation-set-log10.csv,sha256=RJgpruL16FVPgUT3-3xW4eppS_tn6o5yEW79KnITn48,68922 +numpy/core/tests/data/umath-validation-set-log1p.csv,sha256=IZZI-hi55HGCOvBat3vSBVha_8Nt-5alf2fqz6QeTG0,60303 +numpy/core/tests/data/umath-validation-set-log2.csv,sha256=HL2rOCsrEi378rNrbsXHPqlWlEGkXQq8R4e63YeTksU,68917 +numpy/core/tests/data/umath-validation-set-sin.csv,sha256=8PUjnQ_YfmxFb42XJrvpvmkeSpEOlEXSmNvIK4VgfAM,58611 +numpy/core/tests/data/umath-validation-set-sinh.csv,sha256=CYiibE8aX7MQnBatl__5k_PWc_9vHUifwS-sFZzzKk0,60293 +numpy/core/tests/data/umath-validation-set-tan.csv,sha256=Oq7gxMvblRVBrQ23kMxc8iT0bHnCWKg9EE4ZqzbJbOA,60299 +numpy/core/tests/data/umath-validation-set-tanh.csv,sha256=iolZF_MOyWRgYSa-SsD4df5mnyFK18zrICI740SWoTc,60299 +numpy/core/tests/examples/cython/__pycache__/setup.cpython-310.pyc,, +numpy/core/tests/examples/cython/checks.pyx,sha256=rKAhPSGHJ9oPK9Q_85YoUQyRTftEP1jcYOR5lSPB6oQ,662 +numpy/core/tests/examples/cython/meson.build,sha256=Qk4Q6OkpZ0xsLUkcGQVVrYkzb0ozoyL6YlSZ8_5tH1I,1088 +numpy/core/tests/examples/cython/setup.py,sha256=aAR-TvQabUabnCzuB6UdWdmRXaaPfIG7MzTIfMF-0tk,496 +numpy/core/tests/examples/limited_api/__pycache__/setup.cpython-310.pyc,, +numpy/core/tests/examples/limited_api/limited_api.c,sha256=mncE8TjjXmYpkwli433G0jB2zGQO_5NqWmGKdzRJZug,344 +numpy/core/tests/examples/limited_api/setup.py,sha256=p2w7F1ardi_GRXSrnNIR8W1oeH_pgmw_1P2wS0A2I6M,435 +numpy/core/tests/test__exceptions.py,sha256=QqxQSLXboPXEVwHz-TyE2JeIl_TC-rPugzfo25nbcns,2846 +numpy/core/tests/test_abc.py,sha256=FfgYA_HjYAi8XWGK_oOh6Zw86chB_KG_XoW_7ZlFp4c,2220 +numpy/core/tests/test_api.py,sha256=UMc7SvczAQ5ngHxE-NoXVvNpVzYRrn8oMwFNta1yMS0,22995 +numpy/core/tests/test_argparse.py,sha256=C0zBbwQ9xzzymXe_hHpWnnWQPwOi2ZdQB78gBAgJHvU,1969 +numpy/core/tests/test_array_coercion.py,sha256=zY4Pjlt4QZ0w71WxWGLHcrPnnhEF51yXYVLg5HMIy5c,34379 +numpy/core/tests/test_array_interface.py,sha256=8tGgj1Nzi76H_WF5GULkxqWL7Yu_Xf0lvTJZOwOBKsI,7774 +numpy/core/tests/test_arraymethod.py,sha256=VpjDYTmoMDTZcY7CsGzinBh0R_OICuwOykWCbmCRQZU,3244 +numpy/core/tests/test_arrayprint.py,sha256=cKaIoD9ZvsjJH0PHwZyOxmcRcBt1kN1WfFneqVqs0b8,40462 +numpy/core/tests/test_casting_floatingpoint_errors.py,sha256=W3Fgk0oKtXFv684fEZ7POwj6DHTYK0Jj_oGRLZ8UdyA,5063 +numpy/core/tests/test_casting_unittests.py,sha256=9-vkR0oXczQz8ED8DxGVPmalC8IZXe2jKgOCMGr8hIg,34298 +numpy/core/tests/test_conversion_utils.py,sha256=jNhbNNI-T8qtQnsIMEax7KFN30kjh0ICntLMwTyxJ5Q,6559 +numpy/core/tests/test_cpu_dispatcher.py,sha256=v_SlhUpENuoe7QYXizzYITLGXa7WfZ7jqcqmbSBg7JU,1542 +numpy/core/tests/test_cpu_features.py,sha256=mieGx7dxXFiyTYatbcCCjIjR67Un2hVcbJx4GEf2yFo,14892 +numpy/core/tests/test_custom_dtypes.py,sha256=JogRmttDLwfQ3PTbewEnGLKco9zV2Nu3yIfrMeCsx_I,9401 +numpy/core/tests/test_cython.py,sha256=t5-h4XSIFNLyw_9BIAQDYl8_80t_pH0SCfEa1Vf_3aI,3755 +numpy/core/tests/test_datetime.py,sha256=2vAGbrCQmsrWNXCVXOMZqUGZn2c-cQT-eZ1wTprYbcM,116211 +numpy/core/tests/test_defchararray.py,sha256=F88HUkByEP4H6cJ_ITvIe0a_T1BH2JOdRysMCu1XIn0,24997 +numpy/core/tests/test_deprecations.py,sha256=w2lhHb-W8hh7RoE_0Ftg8thpG86jvbFAJgior22DY2Q,31076 +numpy/core/tests/test_dlpack.py,sha256=cDlwFmTombb2rDeB8RHEAJ4eVMUiDbw8Oz5Jo1NQwk0,3522 +numpy/core/tests/test_dtype.py,sha256=J09pJF59v7UO6iNuJFISKP2DLPgdkQ_df5OAMDRLikU,75702 +numpy/core/tests/test_einsum.py,sha256=QzQAPIC-IjTV3Dxz97hBnvLBCmF8kpsBTBckThhgRjQ,53712 +numpy/core/tests/test_errstate.py,sha256=U3GT9I058jkF725mx4GdWUr9RoceCkGDV7Go79VA4wY,2219 +numpy/core/tests/test_extint128.py,sha256=gCZfAwPOb-F1TLsEEeDI0amQYwHk-60-OXi0ccZrrZ8,5643 +numpy/core/tests/test_function_base.py,sha256=Ibs6-WXZE5hsRx4VCnX-cZOWYKU-5PFXjouwAQzgnqQ,15595 +numpy/core/tests/test_getlimits.py,sha256=apdxr0zKkxaVHIUpLrqAvO39q54JKN14sV4xSbK2Ifs,6718 +numpy/core/tests/test_half.py,sha256=VYPyap9GYOWZuphsfFofcIRl-oa5Ufrtv83OTp6azdU,24593 +numpy/core/tests/test_hashtable.py,sha256=ZV8HL8NkDnoQZfnje7BP0fyIp4fSFqjKsQc40PaTggc,1011 +numpy/core/tests/test_indexerrors.py,sha256=kN9xLl6FVTzmI7fumn_cuZ3k0omXnTetgtCnPY44cvw,5130 +numpy/core/tests/test_indexing.py,sha256=x0ojWuhOwWD5MZuiJ9Ncim3CgkwI-GldWxrSCmjmFJM,54314 +numpy/core/tests/test_item_selection.py,sha256=kI30kiX8mIrZYPn0jw3lGGw1ruZF4PpE9zw-aai9EPA,6458 +numpy/core/tests/test_limited_api.py,sha256=5yO0nGmCKZ9b3S66QP7vY-HIgAoyOtHZmp8mvzKuOHI,1172 +numpy/core/tests/test_longdouble.py,sha256=jO8YMm_Hsz-XPKbmv6iMcOdHgTlIFkKTwAtxpy3Q1pE,13905 +numpy/core/tests/test_machar.py,sha256=_5_TDUVtAJvJI5jBfEFKpCZtAfKCsCFt7tXlWSkWzzc,1067 +numpy/core/tests/test_mem_overlap.py,sha256=QJ0unWD_LOoAGAo4ra0IvYenj56IYUtiz1fEJEmTY9Q,29086 +numpy/core/tests/test_mem_policy.py,sha256=CXa10FQw2Qj6MqJuaC8Fm4slsoipKFjCIpYF6c5IIAU,16801 +numpy/core/tests/test_memmap.py,sha256=tZ5lJs_4ZFsJmg392ZQ33fX0m8tdfZ8ZtY9Lq41LNtk,7477 +numpy/core/tests/test_multiarray.py,sha256=GPv4IJR9dijNG-icUsQsX2tBD2RdP3EhUehY4cxvVQU,380106 +numpy/core/tests/test_nditer.py,sha256=nVQ00aNxPHqf4ZcFs3e9AVDK64TCqlO0TzfocTAACZQ,130818 +numpy/core/tests/test_nep50_promotions.py,sha256=2TwtFvj1LBpYTtdR6NFe1RAAGXIJltLqwpA1vhQCVY4,8840 +numpy/core/tests/test_numeric.py,sha256=ZGNW5NKgShEjZC_TcPOtTuRaTM_GbuM21u82D205UPs,137294 +numpy/core/tests/test_numerictypes.py,sha256=f_xMjZJnyDwlc6XCrd71b6x1_6dAWOv-kZ3-NEq37hU,21687 +numpy/core/tests/test_numpy_2_0_compat.py,sha256=kVCTAXska7Xi5w_TYduWhid0nlCqI6Nvmt-gDnYsuKI,1630 +numpy/core/tests/test_overrides.py,sha256=t0gOZOzu7pevE58HA-npFYJqnInHR-LLBklnzKJWHqo,26080 +numpy/core/tests/test_print.py,sha256=ErZAWd88b0ygSEoYpd0BL2tFjkerMtn1vZ7dWvaNqTc,6837 +numpy/core/tests/test_protocols.py,sha256=fEXE9K9s22oiVWkX92BY-g00-uXCK-HxjZhZxxYAKFc,1168 +numpy/core/tests/test_records.py,sha256=pluit5x6jkWoPEIrHXM13L3xZuuSSiaxoXFsOdkakCU,20269 +numpy/core/tests/test_regression.py,sha256=SJo9cPTVr2SNjhgtW7boUMyNQlXxygsZ5g0oyqC8Eks,91595 +numpy/core/tests/test_scalar_ctors.py,sha256=qDIZV-tBukwAxNDhUmGtH3CemDXlS3xd_q3L52touuA,6115 +numpy/core/tests/test_scalar_methods.py,sha256=Uj-zU0zzzKAjMBdpkzsWZ3nSFj5gJkUlqi_euhOYdnU,7541 +numpy/core/tests/test_scalarbuffer.py,sha256=FSL94hriWX1_uV6Z33wB3ZXUrpmmX2-x87kNjIxUeBk,5580 +numpy/core/tests/test_scalarinherit.py,sha256=fMInDGKsiH3IS_2ejZtIcmJZ0Ry8c7kVsHx7wp5XDoM,2368 +numpy/core/tests/test_scalarmath.py,sha256=XZj_m2I2TLktJdFD1SWj2XtV8hT26VIxasDz3cAFvgA,43247 +numpy/core/tests/test_scalarprint.py,sha256=1599W5X0tjGhBnSQjalXkg6AY8eHXnr6PMqs4vYZQqs,18771 +numpy/core/tests/test_shape_base.py,sha256=D9haeuUVx3x3pOLmFQ9vUz7iU4T2bFTsPoI8HgSncFU,29723 +numpy/core/tests/test_simd.py,sha256=-L1UhIn9Eu_euLwaSU7bPRfYpWWOTb43qovoJS7Ws7w,48696 +numpy/core/tests/test_simd_module.py,sha256=OSpYhH_3QDxItyQcaW6SjXW57k2m-weRwpYOnJjCqN0,3902 +numpy/core/tests/test_strings.py,sha256=A9t1B65lFrYRLXgDJSg3mMDAe_hypIPcTMVOdAYIbU0,3835 +numpy/core/tests/test_ufunc.py,sha256=5pS2x3LACHn8GogYYad8LRAjByK7Gg9xTD9ik3d0Fm0,124907 +numpy/core/tests/test_umath.py,sha256=huHpclJqkO32k7BTflRHj8nImzg3p6yyryeS9LyHKWU,186482 +numpy/core/tests/test_umath_accuracy.py,sha256=mFcVdzXhhD9mqhzLDJVZsWfCHbjbFQ6XeEl5G8l-PTc,3897 +numpy/core/tests/test_umath_complex.py,sha256=WvZZZWeijo52RiOfx-G83bxzQOp_IJ3i9fEnUDVukLQ,23247 +numpy/core/tests/test_unicode.py,sha256=hUXIwMmoq89y_KXWzuXVyQaXvRwGjfY4TvKJsCbygEI,12775 +numpy/core/umath.py,sha256=JbT_SxnZ_3MEmjOI9UtX3CcAzX5Q-4RDlnnhDAEJ5Vo,2040 +numpy/core/umath_tests.py,sha256=TIzaDfrEHHgSc2J5kxFEibq8MOPhwSuyOZOUBsZNVSM,389 +numpy/ctypeslib.py,sha256=Po4XCWfxhwFQ1Q8x8DeayGiMCJLxREaCDkVyeladxBU,17247 +numpy/ctypeslib.pyi,sha256=A9te473aRO920iDVuyKypeVIQp-ueZK6EiI-qLSwJNg,7972 +numpy/distutils/__init__.py,sha256=BU1C21439HRo7yH1SsN9me6WCDPpOwRQ37ZpNwDMqCw,2074 +numpy/distutils/__init__.pyi,sha256=D8LRE6BNOmuBGO-oakJGnjT9UJTk9zSR5rxMfZzlX64,119 +numpy/distutils/__pycache__/__init__.cpython-310.pyc,, +numpy/distutils/__pycache__/_shell_utils.cpython-310.pyc,, +numpy/distutils/__pycache__/armccompiler.cpython-310.pyc,, +numpy/distutils/__pycache__/ccompiler.cpython-310.pyc,, +numpy/distutils/__pycache__/ccompiler_opt.cpython-310.pyc,, +numpy/distutils/__pycache__/conv_template.cpython-310.pyc,, +numpy/distutils/__pycache__/conv_template.cpython-310.pyc,sha256=a3qs3Sukb6pM_eX-VB8N8EHnL3VWi3nK87-7s1I9Xh0,8307 +numpy/distutils/__pycache__/core.cpython-310.pyc,, +numpy/distutils/__pycache__/cpuinfo.cpython-310.pyc,, +numpy/distutils/__pycache__/exec_command.cpython-310.pyc,, +numpy/distutils/__pycache__/extension.cpython-310.pyc,, +numpy/distutils/__pycache__/from_template.cpython-310.pyc,, +numpy/distutils/__pycache__/fujitsuccompiler.cpython-310.pyc,, +numpy/distutils/__pycache__/intelccompiler.cpython-310.pyc,, +numpy/distutils/__pycache__/lib2def.cpython-310.pyc,, +numpy/distutils/__pycache__/line_endings.cpython-310.pyc,, +numpy/distutils/__pycache__/log.cpython-310.pyc,, +numpy/distutils/__pycache__/mingw32ccompiler.cpython-310.pyc,, +numpy/distutils/__pycache__/misc_util.cpython-310.pyc,, +numpy/distutils/__pycache__/msvc9compiler.cpython-310.pyc,, +numpy/distutils/__pycache__/msvccompiler.cpython-310.pyc,, +numpy/distutils/__pycache__/npy_pkg_config.cpython-310.pyc,, +numpy/distutils/__pycache__/numpy_distribution.cpython-310.pyc,, +numpy/distutils/__pycache__/pathccompiler.cpython-310.pyc,, +numpy/distutils/__pycache__/setup.cpython-310.pyc,, +numpy/distutils/__pycache__/system_info.cpython-310.pyc,, +numpy/distutils/__pycache__/unixccompiler.cpython-310.pyc,, +numpy/distutils/_shell_utils.py,sha256=kMLOIoimB7PdFRgoVxCIyCFsIl1pP3d0hkm_s3E9XdA,2613 +numpy/distutils/armccompiler.py,sha256=8qUaYh8QHOJlz7MNvkuJNyYdCOCivuW0pbmf_2OPZu0,962 +numpy/distutils/ccompiler.py,sha256=6I-zQBLJCyZUZaYdmK23pmucM8MAn2OsvyzEdghPpW0,28618 +numpy/distutils/ccompiler_opt.py,sha256=diDOkSKj_j0xY08kP7-NoQsefxJgsN5clEirqXlavGY,100390 +numpy/distutils/checks/cpu_asimd.c,sha256=nXUsTLrSlhRL-UzDM8zMqn1uqJnR7TRlJi3Ixqw539w,818 +numpy/distutils/checks/cpu_asimddp.c,sha256=E4b9zT1IdSfGR2ACZJiQoR-BqaeDtzFqRNW8lBOXAaY,432 +numpy/distutils/checks/cpu_asimdfhm.c,sha256=6tXINVEpmA-lYRSbL6CrBu2ejNFmd9WONFGgg-JFXZE,529 +numpy/distutils/checks/cpu_asimdhp.c,sha256=SfwrEEA_091tmyI4vN3BNLs7ypUnrF_VbTg6gPl-ocs,379 +numpy/distutils/checks/cpu_avx.c,sha256=LuZW8o93VZZi7cYEP30dvKWTm7Mw1TLmCt5UaXDxCJg,779 +numpy/distutils/checks/cpu_avx2.c,sha256=jlDlea393op0JOiMJgmmPyKmyAXztLcObPOp9F9FaS0,749 +numpy/distutils/checks/cpu_avx512_clx.c,sha256=P-YHjj2XE4SithBkPwDgShOxGWnVSNUXg72h8O3kpbs,842 +numpy/distutils/checks/cpu_avx512_cnl.c,sha256=f_c2Z0xwAKTJeK3RYMIp1dgXYV8QyeOxUgKkMht4qko,948 +numpy/distutils/checks/cpu_avx512_icl.c,sha256=isI35-gm7Hqn2Qink5hP1XHWlh52a5vwKhEdW_CRviE,1004 +numpy/distutils/checks/cpu_avx512_knl.c,sha256=PVTkczTpHlXbTc7IQKlCFU9Cq4VGG-_JhVnT0_n-t1A,959 +numpy/distutils/checks/cpu_avx512_knm.c,sha256=eszPGr3XC9Js7mQUB0gFxlrNjQwfucQFz_UwFyNLjes,1132 +numpy/distutils/checks/cpu_avx512_skx.c,sha256=59VD8ebEJJHLlbY-4dakZV34bmq_lr9mBKz8BAcsdYc,1010 +numpy/distutils/checks/cpu_avx512_spr.c,sha256=i8DpADB8ZhIucKc8lt9JfYbQANRvR67u59oQf5winvg,904 +numpy/distutils/checks/cpu_avx512cd.c,sha256=Qfh5FJUv9ZWd_P5zxkvYYIkvqsPptgaDuKkeX_F8vyA,759 +numpy/distutils/checks/cpu_avx512f.c,sha256=d97NRcbJhqpvURnw7zyG0TOuEijKXvU0g4qOTWHbwxY,755 +numpy/distutils/checks/cpu_f16c.c,sha256=nzZzpUc8AfTtw-INR3KOxcjx9pyzVUM8OhsrdH2dO_w,868 +numpy/distutils/checks/cpu_fma3.c,sha256=YN6IDwuZALJHVVmpQ2tj-14HI_PcxH_giV8-XjzlmkU,817 +numpy/distutils/checks/cpu_fma4.c,sha256=qKdgTNNFg-n8vSB1Txco60HBLCcOi1aH23gZOX7yKqs,301 +numpy/distutils/checks/cpu_neon.c,sha256=Y0SjuVLzh3upcbY47igHjmKgjHbXxbvzncwB7acfjxw,600 +numpy/distutils/checks/cpu_neon_fp16.c,sha256=E7YOGyYP41u1sqiCHpCGGqjmo7Cs6yUkmJ46K7LZloc,251 +numpy/distutils/checks/cpu_neon_vfpv4.c,sha256=qFY1C_fQYz7M_a_8j0KTdn7vaE3NNVmWY2JGArDGM3w,609 +numpy/distutils/checks/cpu_popcnt.c,sha256=vRcXHVw2j1F9I_07eIZ_xzDX3fd3mqgiQXL1w3pULJk,1049 +numpy/distutils/checks/cpu_sse.c,sha256=6MHITtC76UpSR9uh0SiURpnkpPkLzT5tbrcXT4xBFxo,686 +numpy/distutils/checks/cpu_sse2.c,sha256=yUZzdjDtBS-vYlhfP-pEzj3m0UPmgZs-hA99TZAEACU,697 +numpy/distutils/checks/cpu_sse3.c,sha256=j5XRHumUuccgN9XPZyjWUUqkq8Nu8XCSWmvUhmJTJ08,689 +numpy/distutils/checks/cpu_sse41.c,sha256=y_k81P-1b-Hx8OeRVDE9V1O9JakS0zPvlFKJ3VbSmEw,675 +numpy/distutils/checks/cpu_sse42.c,sha256=3PXucdI2mII-txO7zFN99TlVveT_QUAETTGvRk-_hYw,692 +numpy/distutils/checks/cpu_ssse3.c,sha256=X6VWxIXMRpdSCBsHPXvot3yTZ4d5yK9Bi1ScQP3WC-Q,705 +numpy/distutils/checks/cpu_vsx.c,sha256=FVmR4iliKjcihzMCwloR1F2JYwSZK9P4f_hvIRLHSDQ,478 +numpy/distutils/checks/cpu_vsx2.c,sha256=yESs25Rt5ztb5-stuYbu3TbiyJKmllMpMLu01GOAHqE,263 +numpy/distutils/checks/cpu_vsx3.c,sha256=omC50tbEZNigsKMFPtE3zGRlIS2VuDTm3vZ9TBZWo4U,250 +numpy/distutils/checks/cpu_vsx4.c,sha256=ngezA1KuINqJkLAcMrZJR7bM0IeA25U6I-a5aISGXJo,305 +numpy/distutils/checks/cpu_vx.c,sha256=OpLU6jIfwvGJR4JPVVZLlUfvo7oAZ0YvsjafM2qtPlk,461 +numpy/distutils/checks/cpu_vxe.c,sha256=rYW_nKwXnlB0b8xCrJEr4TmvrEvS-NToxwyqqOHV8Bk,788 +numpy/distutils/checks/cpu_vxe2.c,sha256=Hv4wO23kwC2G6lqqercq4NE4K0nrvBxR7RIzr5HTXCc,624 +numpy/distutils/checks/cpu_xop.c,sha256=7uabsGeqvmVJQvuSEjs8-Sm8kpmvl6uZ9YHMF5h2opQ,234 +numpy/distutils/checks/extra_avx512bw_mask.c,sha256=pVPOhcu80yJVnIhOcHHXOlZ2proJ1MUf0XgccqhPoNk,636 +numpy/distutils/checks/extra_avx512dq_mask.c,sha256=nMfIvepISGFDexPrMYl5LWtdmt6Uy9TKPzF4BVayw2I,504 +numpy/distutils/checks/extra_avx512f_reduce.c,sha256=_NfbtfSAkm_A67umjR1oEb9yRnBL5EnTA76fvQIuNVk,1595 +numpy/distutils/checks/extra_vsx3_half_double.c,sha256=shHvIQZfR0o-sNefOt49BOh4WCmA0BpJvj4b7F9UdvQ,354 +numpy/distutils/checks/extra_vsx4_mma.c,sha256=GiQGZ9-6wYTgH42bJgSlXhWcTIrkjh5xv4uymj6rglk,499 +numpy/distutils/checks/extra_vsx_asm.c,sha256=BngiMVS9nyr22z6zMrOrHLeCloe_5luXhf5T5mYucgI,945 +numpy/distutils/checks/test_flags.c,sha256=uAIbhfAhyGe4nTdK_mZmoCefj9P0TGHNF9AUv_Cdx5A,16 +numpy/distutils/command/__init__.py,sha256=fW49zUB3syMFsKpf1oRBO0h8tmnTwRP3zUPrsB0R22M,1032 +numpy/distutils/command/__pycache__/__init__.cpython-310.pyc,, +numpy/distutils/command/__pycache__/autodist.cpython-310.pyc,, +numpy/distutils/command/__pycache__/bdist_rpm.cpython-310.pyc,, +numpy/distutils/command/__pycache__/build.cpython-310.pyc,, +numpy/distutils/command/__pycache__/build_clib.cpython-310.pyc,, +numpy/distutils/command/__pycache__/build_ext.cpython-310.pyc,, +numpy/distutils/command/__pycache__/build_py.cpython-310.pyc,, +numpy/distutils/command/__pycache__/build_scripts.cpython-310.pyc,, +numpy/distutils/command/__pycache__/build_src.cpython-310.pyc,, +numpy/distutils/command/__pycache__/config.cpython-310.pyc,, +numpy/distutils/command/__pycache__/config_compiler.cpython-310.pyc,, +numpy/distutils/command/__pycache__/develop.cpython-310.pyc,, +numpy/distutils/command/__pycache__/egg_info.cpython-310.pyc,, +numpy/distutils/command/__pycache__/install.cpython-310.pyc,, +numpy/distutils/command/__pycache__/install_clib.cpython-310.pyc,, +numpy/distutils/command/__pycache__/install_data.cpython-310.pyc,, +numpy/distutils/command/__pycache__/install_headers.cpython-310.pyc,, +numpy/distutils/command/__pycache__/sdist.cpython-310.pyc,, +numpy/distutils/command/autodist.py,sha256=8KWwr5mnjX20UpY4ITRDx-PreApyh9M7B92IwsEtTsQ,3718 +numpy/distutils/command/bdist_rpm.py,sha256=-tkZupIJr_jLqeX7xbRhE8-COXHRI0GoRpAKchVte54,709 +numpy/distutils/command/build.py,sha256=aj1SUGsDUTxs4Tch2ALLcPnuAVhaPjEPIZIobzMajm0,2613 +numpy/distutils/command/build_clib.py,sha256=TCuZDpRd8ZPZH6SRwIZcWZC3aoGc18Rll6FYcawS6qY,19317 +numpy/distutils/command/build_ext.py,sha256=UcyG8KKyrd5v1s6qDdKEkzwLwmoMlfHA893Lj-OOgl0,32983 +numpy/distutils/command/build_py.py,sha256=XiLZ2d_tmCE8uG5VAU5OK2zlzQayBfeY4l8FFEltbig,1144 +numpy/distutils/command/build_scripts.py,sha256=P2ytmZb3UpwfmbMXkFB2iMQk15tNUCynzMATllmp-Gs,1665 +numpy/distutils/command/build_src.py,sha256=sxsnfc8KBsnsSvI-8sKIKNo2KA2uvrrvW0WYZCqyjyk,31178 +numpy/distutils/command/config.py,sha256=SdN-Cxvwx3AD5k-Xx_VyS2WWpVGmflnYGiTIyruj_xM,20670 +numpy/distutils/command/config_compiler.py,sha256=Cp9RTpW72gg8XC_3-9dCTlLYr352pBfBRZA8YBWvOoY,4369 +numpy/distutils/command/develop.py,sha256=9SbbnFnVbSJVZxTFoV9pwlOcM1D30GnOWm2QonQDvHI,575 +numpy/distutils/command/egg_info.py,sha256=i-Zk4sftK5cMQVQ2jqSxTMpVI-gYyXN16-p5TvmjURc,921 +numpy/distutils/command/install.py,sha256=nkW2fl7OABcE3sUcoNM7iONkF64CBESdVlRjTLg3hVA,3073 +numpy/distutils/command/install_clib.py,sha256=1xv0_lPVu3g16GgICjjlh7T8zQ6PSlevCuq8Bocx5YM,1399 +numpy/distutils/command/install_data.py,sha256=Y59EBG61MWP_5C8XJvSCVfzYpMNVNVcH_Z6c0qgr9KA,848 +numpy/distutils/command/install_headers.py,sha256=tVpOGqkmh8AA_tam0K0SeCd4kvZj3UqSOjWKm6Kz4jY,919 +numpy/distutils/command/sdist.py,sha256=8Tsju1RwXNbPyQcjv8GRMFveFQqYlbNdSZh2X1OV-VU,733 +numpy/distutils/conv_template.py,sha256=F-4vkkfAjCb-fN79WYrXX3BMHMoiQO-W2u09q12OPuI,9536 +numpy/distutils/core.py,sha256=C-_z7rODE_12olz0dwtlKqwfaSLXEV3kZ1CyDJMsQh8,8200 +numpy/distutils/cpuinfo.py,sha256=XuNhsx_-tyrui_AOgn10yfZ9p4YBM68vW2_bGmKj07I,22639 +numpy/distutils/exec_command.py,sha256=0EGasX7tM47Q0k8yJA1q-BvIcjV_1UAC-zDmen-j6Lg,10283 +numpy/distutils/extension.py,sha256=YgeB8e2fVc2l_1etuRBv0P8c1NULOz4SaudHgsVBc30,3568 +numpy/distutils/fcompiler/__init__.py,sha256=DqfaiKGVagOFuL0v3VZxZZkRnWWvly0_lYHuLjaZTBo,40625 +numpy/distutils/fcompiler/__pycache__/__init__.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/absoft.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/arm.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/compaq.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/environment.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/fujitsu.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/g95.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/gnu.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/hpux.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/ibm.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/intel.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/lahey.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/mips.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/nag.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/none.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/nv.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/pathf95.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/pg.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/sun.cpython-310.pyc,, +numpy/distutils/fcompiler/__pycache__/vast.cpython-310.pyc,, +numpy/distutils/fcompiler/absoft.py,sha256=yPUHBNZHOr_gxnte16I_X85o1iL9FI4RLHjG9JOuyYU,5516 +numpy/distutils/fcompiler/arm.py,sha256=MCri346qo1bYwjlm32xHRyRl-bAINTlfVIubN6HDz68,2090 +numpy/distutils/fcompiler/compaq.py,sha256=sjU2GKHJGuChtRb_MhnouMqvkIOQflmowFE6ErCWZhE,3903 +numpy/distutils/fcompiler/environment.py,sha256=DOD2FtKDk6O9k6U0h9UKWQ-65wU8z1tSPn3gUlRwCso,3080 +numpy/distutils/fcompiler/fujitsu.py,sha256=yK3wdHoF5qq25UcnIM6FzTXsJGJxdfKa_f__t04Ne7M,1333 +numpy/distutils/fcompiler/g95.py,sha256=FH4uww6re50OUT_BfdoWSLCDUqk8LvmQ2_j5RhF5nLQ,1330 +numpy/distutils/fcompiler/gnu.py,sha256=ag8v_pp-fYpDPKJsVmNaFwN621b1MFQAxew0T1KdE_Y,20502 +numpy/distutils/fcompiler/hpux.py,sha256=gloUjWGo7MgJmukorDq7ZxDnnUKXx-C6AQfryQshVM4,1353 +numpy/distutils/fcompiler/ibm.py,sha256=Ts2PXg2ocrXtX9eguvcHeQ4JB2ktpd5isXtRTpU9F5Y,3534 +numpy/distutils/fcompiler/intel.py,sha256=XYF0GLVhJWjS8noEx4TJ704Eqt-JGBolRZEOkwgNItE,6570 +numpy/distutils/fcompiler/lahey.py,sha256=U63KMfN8zDAd_jnvMkS2N-dvP4UiSRB9Ces290qLNXw,1327 +numpy/distutils/fcompiler/mips.py,sha256=LAwT0DY5yqlYh20hNMYR1-OKu8A9GNw-TbUfI8pvglM,1714 +numpy/distutils/fcompiler/nag.py,sha256=9pQCMUlwjRVHGKwZxvwd4bW5p-9v7VXcflELEImHg1g,2777 +numpy/distutils/fcompiler/none.py,sha256=6RX2X-mV1HuhJZnVfQmDmLVhIUWseIT4P5wf3rdLq9Y,758 +numpy/distutils/fcompiler/nv.py,sha256=LGBQY417zibQ-fnPis5rNtP_I1Qk9OlhEFOnPvmwXHI,1560 +numpy/distutils/fcompiler/pathf95.py,sha256=MiHVar6-beUEYVEpqXORIX4f8G29I47D36kreltdfoQ,1061 +numpy/distutils/fcompiler/pg.py,sha256=NOB1stzrjvQMZS7bIPTgWTcAFe3cjNveA5-SztUZqD0,3568 +numpy/distutils/fcompiler/sun.py,sha256=mfS3RTj9uYT6K9Ikp8RjmsEPIWAtUTzMhX9sGjEyF6I,1577 +numpy/distutils/fcompiler/vast.py,sha256=Xuxa4sNraUPcQmt45SogAfN0kDHFb6C73uNZNmX3RBE,1667 +numpy/distutils/from_template.py,sha256=hpoFQortsLZdMSr_fJILzXzrIwFlZoFjsDSo6jNtvWs,7913 +numpy/distutils/fujitsuccompiler.py,sha256=JDuUUE-GyPahkNnDZLWNHyAmJ2lJPCnLuIUFfHkjMzA,834 +numpy/distutils/intelccompiler.py,sha256=N_pvWjlLORdlH34cs97oU4LBNr_s9r5ddsmme7XEvs4,4234 +numpy/distutils/lib2def.py,sha256=-3rDf9FXsDik3-Qpp-A6N_cYZKTlmVjVi4Jzyo-pSlY,3630 +numpy/distutils/line_endings.py,sha256=a8ZZECrPRffsbs0UygeR47_fOUlZppnx-QPssrIXtB0,2032 +numpy/distutils/log.py,sha256=m8caNBwPhIG7YTnD9iq9jjc6_yJOeU9FHuau2CSulds,2879 +numpy/distutils/mingw/gfortran_vs2003_hack.c,sha256=cbsN3Lk9Hkwzr9c-yOP2xEBg1_ml1X7nwAMDWxGjzc8,77 +numpy/distutils/mingw32ccompiler.py,sha256=4G8t_6plw7xqoF0icDaWGNSBgbyDaHQn3GB5l9gikEA,22067 +numpy/distutils/misc_util.py,sha256=2MxXE4rex_wSUhpLuwxOFeeor-WxZLjisVvXWycNaq4,89359 +numpy/distutils/msvc9compiler.py,sha256=FCtP7g34AVuMIaqQlH8AV1ZBdIUXbk5G7eBeeTSr1zE,2192 +numpy/distutils/msvccompiler.py,sha256=ILookUifVJF9tAtPJoVCqZ673m5od6MVKuAHuA3Rcfk,2647 +numpy/distutils/npy_pkg_config.py,sha256=fIFyWLTqRySO3hn-0i0FNdHeblRN_hDv-wc68-sa3hQ,12972 +numpy/distutils/numpy_distribution.py,sha256=10Urolg1aDAG0EHYfcvObzOgqRV0ARh2GhDklEg4vS0,634 +numpy/distutils/pathccompiler.py,sha256=KnJEA5H4cXg7SLrMjwWtidD24VSvOdu72d17votiY9E,713 +numpy/distutils/setup.py,sha256=l9ke_Bws431UdBfysaq7ZeGtZ8dix76oh9Huq5qqbkU,634 +numpy/distutils/system_info.py,sha256=SCk1ku0HnZNwConQBJN8FVidbeKVnrMxUyNWUVx73pY,114022 +numpy/distutils/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/distutils/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_build_ext.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_ccompiler_opt.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_ccompiler_opt_conf.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_exec_command.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_fcompiler.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_fcompiler_gnu.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_fcompiler_intel.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_fcompiler_nagfor.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_from_template.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_log.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_mingw32ccompiler.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_misc_util.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_npy_pkg_config.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_shell_utils.cpython-310.pyc,, +numpy/distutils/tests/__pycache__/test_system_info.cpython-310.pyc,, +numpy/distutils/tests/test_build_ext.py,sha256=RNrEi-YMTGQG5YDi5GWL8iJRkk_bQHBQKcqp43TdJco,2769 +numpy/distutils/tests/test_ccompiler_opt.py,sha256=N3pN-9gxPY1KvvMEjoXr7kLxTGN8aQOr8qo5gmlrm90,28778 +numpy/distutils/tests/test_ccompiler_opt_conf.py,sha256=maXytv39amuojbQIieIGIXMV4Cv-s0fsPMZeFEh9XyY,6347 +numpy/distutils/tests/test_exec_command.py,sha256=BK-hHfIIrkCep-jNmS5_Cwq5oESvsvX3V_0XDAkT1Ok,7395 +numpy/distutils/tests/test_fcompiler.py,sha256=mJXezTXDUbduhCwVGAfABHpEARWhnj8hLW9EOU3rn84,1277 +numpy/distutils/tests/test_fcompiler_gnu.py,sha256=nmfaFCVzbViIOQ2-MjgXt-bN8Uj674hCgiwr5Iol-_U,2136 +numpy/distutils/tests/test_fcompiler_intel.py,sha256=mxkfFD2rNfg8nn1pp_413S0uCdYXydPWBcz9ilgGkA0,1058 +numpy/distutils/tests/test_fcompiler_nagfor.py,sha256=CKEjik7YVfSJGL4abuctkmlkIUhAhv-x2aUcXiTR9b0,1102 +numpy/distutils/tests/test_from_template.py,sha256=SDYoe0XUpAayyEQDq7ZhrvEEz7U9upJDLYzhcdoVifc,1103 +numpy/distutils/tests/test_log.py,sha256=0tSM4q-00CjbMIRb9QOJzI4A7GHUiRGOG1SOOLz8dnM,868 +numpy/distutils/tests/test_mingw32ccompiler.py,sha256=rMC8-IyBOiuZVfAoklV_KnD9qVeB_hFVvb5dStxfk08,1609 +numpy/distutils/tests/test_misc_util.py,sha256=Qs96vTr8GZSyVCWuamzcNlVMRa15vt0Y-T2yZSUm_QA,3218 +numpy/distutils/tests/test_npy_pkg_config.py,sha256=apGrmViPcXoPCEOgDthJgL13C9N0qQMs392QjZDxJd4,2557 +numpy/distutils/tests/test_shell_utils.py,sha256=UKU_t5oIa_kVMv89Ys9KN6Z_Fy5beqPDUsDAWPmcoR8,2114 +numpy/distutils/tests/test_system_info.py,sha256=wMV7bH5oB0luLDR2tunHrLaUxsD_-sIhLnNpj1blQPs,11405 +numpy/distutils/unixccompiler.py,sha256=fN4-LH6JJp44SLE7JkdG2kKQlK4LC8zuUpVC-RtmJ-U,5426 +numpy/doc/__init__.py,sha256=OYmE-F6x0CD05PCDY2MiW1HLlwB6i9vhDpk-a3r4lHY,508 +numpy/doc/__pycache__/__init__.cpython-310.pyc,, +numpy/doc/__pycache__/constants.cpython-310.pyc,, +numpy/doc/__pycache__/ufuncs.cpython-310.pyc,, +numpy/doc/constants.py,sha256=PlXoj7b4A8Aa9nADbg83uzTBRJaX8dvJmEdbn4FDPPo,9155 +numpy/doc/ufuncs.py,sha256=i1alLg19mNyCFZ2LYSOZGm--RsRN1x63U_UYU-N3x60,5357 +numpy/dtypes.py,sha256=BuBztrPQRasUmVZhXr2_NgJujdUTNhNwd59pZZHk3lA,2229 +numpy/dtypes.pyi,sha256=tIHniAYP7ALg2iT7NgSXO67jvE-zRlDod3MazEmD4M8,1315 +numpy/exceptions.py,sha256=7j7tv8cwXGZYgldyMisGmnAxAl2s4YU0vexME81yYlA,7339 +numpy/exceptions.pyi,sha256=KsZqWNvyPUEXUGR9EhZCUQF2f9EVSpBRlJUlGqRT02k,600 +numpy/f2py/__init__.py,sha256=m-ty_WiJZ4GVfV5--kJ3MFJaLXestz5Eo-4H0FPscK4,5565 +numpy/f2py/__init__.pyi,sha256=eA7uYXZr0p0aaz5rBW-EypLx9RchrvqDYtSnkEJQsYw,1087 +numpy/f2py/__main__.py,sha256=6i2jVH2fPriV1aocTY_dUFvWK18qa-zjpnISA-OpF3w,130 +numpy/f2py/__pycache__/__init__.cpython-310.pyc,, +numpy/f2py/__pycache__/__main__.cpython-310.pyc,, +numpy/f2py/__pycache__/__version__.cpython-310.pyc,, +numpy/f2py/__pycache__/_isocbind.cpython-310.pyc,, +numpy/f2py/__pycache__/_src_pyf.cpython-310.pyc,, +numpy/f2py/__pycache__/auxfuncs.cpython-310.pyc,, +numpy/f2py/__pycache__/capi_maps.cpython-310.pyc,, +numpy/f2py/__pycache__/cb_rules.cpython-310.pyc,, +numpy/f2py/__pycache__/cfuncs.cpython-310.pyc,, +numpy/f2py/__pycache__/common_rules.cpython-310.pyc,, +numpy/f2py/__pycache__/crackfortran.cpython-310.pyc,, +numpy/f2py/__pycache__/diagnose.cpython-310.pyc,, +numpy/f2py/__pycache__/f2py2e.cpython-310.pyc,, +numpy/f2py/__pycache__/f90mod_rules.cpython-310.pyc,, +numpy/f2py/__pycache__/func2subr.cpython-310.pyc,, +numpy/f2py/__pycache__/rules.cpython-310.pyc,, +numpy/f2py/__pycache__/setup.cpython-310.pyc,, +numpy/f2py/__pycache__/symbolic.cpython-310.pyc,, +numpy/f2py/__pycache__/use_rules.cpython-310.pyc,, +numpy/f2py/__version__.py,sha256=7HHdjR82FCBmftwMRyrlhcEj-8mGQb6oCH-wlUPH4Nw,34 +numpy/f2py/_backends/__init__.py,sha256=7_bA7c_xDpLc4_8vPfH32-Lxn9fcUTgjQ25srdvwvAM,299 +numpy/f2py/_backends/__pycache__/__init__.cpython-310.pyc,, +numpy/f2py/_backends/__pycache__/_backend.cpython-310.pyc,, +numpy/f2py/_backends/__pycache__/_distutils.cpython-310.pyc,, +numpy/f2py/_backends/__pycache__/_meson.cpython-310.pyc,, +numpy/f2py/_backends/_backend.py,sha256=GKb9-UaFszT045vUgVukPs1n97iyyjqahrWKxLOKNYo,1187 +numpy/f2py/_backends/_distutils.py,sha256=pxh2YURFYYSykIOvBFwVvhoNX1oSk-c30IPPhzlko-0,2383 +numpy/f2py/_backends/_meson.py,sha256=gi-nbnPFDC38sumfAjg-Q5FPu6nNkyQXTjEuVf9W9Cc,6916 +numpy/f2py/_backends/meson.build.template,sha256=oTPNMAQzS4CJ_lfEzYv-oBeJTtQuThUYVN5R6ROWpNU,1579 +numpy/f2py/_isocbind.py,sha256=zaBgpfPNRmxVG3doUIlbZIiyB990MsXiwDabrSj9HnQ,2360 +numpy/f2py/_src_pyf.py,sha256=4t6TN4ZKWciC4f1z6fwaGrpIGhHKRiwHfcrNj4FIzCg,7654 +numpy/f2py/auxfuncs.py,sha256=dNs4b2KDIcG4M1hPBvD09-Vh7CDzlPIrFscOdvL3p1o,26539 +numpy/f2py/capi_maps.py,sha256=ENjYyeZ3CCJcLwJJgmKOSYrD1KPuhpwauXqeizdV55o,30563 +numpy/f2py/cb_rules.py,sha256=5TuHbJWGjsF6yVNzKuV2tAnwdLyhcWlmdsjYlDOZOv4,24992 +numpy/f2py/cfuncs.py,sha256=KJyW7mdjmFSmxssfeegGJs5NZyF3mZMgNvOxN9-vYHQ,51913 +numpy/f2py/common_rules.py,sha256=gHB76WypbkVmhaD_RWhy8Od4zDTgj8cbDOdUdIp6PIQ,5131 +numpy/f2py/crackfortran.py,sha256=ErLdkWP8MxeyW5vVPGXwyvrxZAwymlvIBC0th2rvK74,148553 +numpy/f2py/diagnose.py,sha256=0SRXBE2hJgKJN_Rf4Zn00oKXC_Tka3efPWM47zg6BoY,5197 +numpy/f2py/f2py2e.py,sha256=5t093ZQ4xs0_0UbyaYVd2yA2EVOaOAcuU29JI-IU2Ag,27717 +numpy/f2py/f90mod_rules.py,sha256=otm3_dmVIna0eBVHLu_693s3a_82lU3pqeqDacWI37s,9594 +numpy/f2py/func2subr.py,sha256=6d2R5awuHRT4xzgfUfwS7JHTqhhAieSXcENlssD_2c4,10298 +numpy/f2py/rules.py,sha256=B4FxSYEfZ_1j_z9GulQNZ1BNrPrUvlU3ybxwTkrIxjI,62727 +numpy/f2py/setup.cfg,sha256=Fpn4sjqTl5OT5sp8haqKIRnUcTPZNM6MIvUJBU7BIhg,48 +numpy/f2py/setup.py,sha256=MmAVspT8DDTqDuL8ZJhxK62g0lcso4vqI6QNQ9CsfoQ,2422 +numpy/f2py/src/fortranobject.c,sha256=g4BKDO1_9pCu6hithKXD2oH_Mt-HH1NTnP6leCqJrzc,46017 +numpy/f2py/src/fortranobject.h,sha256=neMKotYWbHvrhW9KXz4QzQ8fzPkiQXLHHjy82vLSeog,5835 +numpy/f2py/symbolic.py,sha256=jWBoAwECCxRdWczR9r7O6UERcYmH_GbdcAReNp7cmJY,53270 +numpy/f2py/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/f2py/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_abstract_interface.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_array_from_pyobj.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_assumed_shape.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_block_docstring.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_callback.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_character.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_common.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_compile_function.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_crackfortran.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_data.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_docs.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_f2cmap.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_f2py2e.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_isoc.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_kind.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_mixed.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_module_doc.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_parameter.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_pyf_src.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_quoted_character.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_regression.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_return_character.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_return_complex.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_return_integer.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_return_logical.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_return_real.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_semicolon_split.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_size.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_string.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_symbolic.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/test_value_attrspec.cpython-310.pyc,, +numpy/f2py/tests/__pycache__/util.cpython-310.pyc,, +numpy/f2py/tests/src/abstract_interface/foo.f90,sha256=JFU2w98cB_XNwfrqNtI0yDTmpEdxYO_UEl2pgI_rnt8,658 +numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90,sha256=gvQJIzNtvacWE0dhysxn30-iUeI65Hpq7DiE9oRauz8,105 +numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c,sha256=Ff5wHYV9-OJnZuelfFWcjAibRvDkEIlbTVczTyv6TG8,7299 +numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap,sha256=But9r9m4iL7EGq_haMW8IiQ4VivH0TgUozxX4pPvdpE,29 +numpy/f2py/tests/src/assumed_shape/foo_free.f90,sha256=oBwbGSlbr9MkFyhVO2aldjc01dr9GHrMrSiRQek8U64,460 +numpy/f2py/tests/src/assumed_shape/foo_mod.f90,sha256=rfzw3QdI-eaDSl-hslCgGpd5tHftJOVhXvb21Y9Gf6M,499 +numpy/f2py/tests/src/assumed_shape/foo_use.f90,sha256=rmT9k4jP9Ru1PLcGqepw9Jc6P9XNXM0axY7o4hi9lUw,269 +numpy/f2py/tests/src/assumed_shape/precision.f90,sha256=r08JeTVmTTExA-hYZ6HzaxVwBn1GMbPAuuwBhBDtJUk,130 +numpy/f2py/tests/src/block_docstring/foo.f,sha256=y7lPCPu7_Fhs_Tf2hfdpDQo1bhtvNSKRaZAOpM_l3dg,97 +numpy/f2py/tests/src/callback/foo.f,sha256=C1hjfpRCQWiOVVzIHqnsYcnLrqQcixrnHCn8hd9GhVk,1254 +numpy/f2py/tests/src/callback/gh17797.f90,sha256=_Nrl0a2HgUbtymGU0twaJ--7rMa1Uco2A3swbWvHoMo,148 +numpy/f2py/tests/src/callback/gh18335.f90,sha256=NraOyKIXyvv_Y-3xGnmTjtNjW2Znsnlk8AViI8zfovc,506 +numpy/f2py/tests/src/callback/gh25211.f,sha256=a2sxlQhtDVbYn8KOKHUYqwc-aCFt7sDPSnJsXFG35uI,179 +numpy/f2py/tests/src/callback/gh25211.pyf,sha256=FWxo0JWQlw519BpZV8PoYeI_FZ_K6C-3Wk6gLrfBPlw,447 +numpy/f2py/tests/src/cli/gh_22819.pyf,sha256=5rvOfCv-wSosB354LC9pExJmMoSHnbGZGl_rtA2fogA,142 +numpy/f2py/tests/src/cli/hi77.f,sha256=ttyI6vAP3qLnDqy82V04XmoqrXNM6uhMvvLri2p0dq0,71 +numpy/f2py/tests/src/cli/hiworld.f90,sha256=QWOLPrTxYQu1yrEtyQMbM0fE9M2RmXe7c185KnD5x3o,51 +numpy/f2py/tests/src/common/block.f,sha256=GQ0Pd-VMX3H3a-__f2SuosSdwNXHpBqoGnQDjf8aG9g,224 +numpy/f2py/tests/src/common/gh19161.f90,sha256=BUejyhqpNVfHZHQ-QC7o7ZSo7lQ6YHyX08lSmQqs6YM,193 +numpy/f2py/tests/src/crackfortran/accesstype.f90,sha256=-5Din7YlY1TU7tUHD2p-_DSTxGBpDsWYNeT9WOwGhno,208 +numpy/f2py/tests/src/crackfortran/data_common.f,sha256=ZSUAh3uhn9CCF-cYqK5TNmosBGPfsuHBIEfudgysun4,193 +numpy/f2py/tests/src/crackfortran/data_multiplier.f,sha256=jYrJKZWF_59JF9EMOSALUjn0UupWvp1teuGpcL5s1Sc,197 +numpy/f2py/tests/src/crackfortran/data_stmts.f90,sha256=19YO7OGj0IksyBlmMLZGRBQLjoE3erfkR4tFvhznvvE,693 +numpy/f2py/tests/src/crackfortran/data_with_comments.f,sha256=hoyXw330VHh8duMVmAQZjr1lgLVF4zFCIuEaUIrupv0,175 +numpy/f2py/tests/src/crackfortran/foo_deps.f90,sha256=CaH7mnWTG7FcnJe2vXN_0zDbMadw6NCqK-JJ2HmDjK8,128 +numpy/f2py/tests/src/crackfortran/gh15035.f,sha256=jJly1AzF5L9VxbVQ0vr-sf4LaUo4eQzJguhuemFxnvg,375 +numpy/f2py/tests/src/crackfortran/gh17859.f,sha256=7K5dtOXGuBDAENPNCt-tAGJqTfNKz5OsqVSk16_e7Es,340 +numpy/f2py/tests/src/crackfortran/gh22648.pyf,sha256=qZHPRNQljIeYNwbqPLxREnOrSdVV14f3fnaHqB1M7c0,241 +numpy/f2py/tests/src/crackfortran/gh23533.f,sha256=w3tr_KcY3s7oSWGDmjfMHv5h0RYVGUpyXquNdNFOJQg,126 +numpy/f2py/tests/src/crackfortran/gh23598.f90,sha256=41W6Ire-5wjJTTg6oAo7O1WZfd1Ug9vvNtNgHS5MhEU,101 +numpy/f2py/tests/src/crackfortran/gh23598Warn.f90,sha256=1v-hMCT_K7prhhamoM20nMU9zILam84Hr-imck_dYYk,205 +numpy/f2py/tests/src/crackfortran/gh23879.f90,sha256=LWDJTYR3t9h1IsrKC8dVXZlBfWX7clLeU006X6Ow8oI,332 +numpy/f2py/tests/src/crackfortran/gh2848.f90,sha256=gPNasx98SIf7Z9ibk_DHiGKCvl7ERtsfoGXiFDT7FbM,282 +numpy/f2py/tests/src/crackfortran/operators.f90,sha256=-Fc-qjW1wBr3Dkvdd5dMTrt0hnjnV-1AYo-NFWcwFSo,1184 +numpy/f2py/tests/src/crackfortran/privatemod.f90,sha256=7bubZGMIn7iD31wDkjF1TlXCUM7naCIK69M9d0e3y-U,174 +numpy/f2py/tests/src/crackfortran/publicmod.f90,sha256=Pnwyf56Qd6W3FUH-ZMgnXEYkb7gn18ptNTdwmGan0Jo,167 +numpy/f2py/tests/src/crackfortran/pubprivmod.f90,sha256=eYpJwBYLKGOxVbKgEqfny1znib-b7uYhxcRXIf7uwXg,165 +numpy/f2py/tests/src/crackfortran/unicode_comment.f90,sha256=aINLh6GlfTwFewxvDoqnMqwuCNb4XAqi5Nj5vXguXYs,98 +numpy/f2py/tests/src/f2cmap/.f2py_f2cmap,sha256=iUOtfHd3OuT1Rz2-yiSgt4uPKGvCt5AzQ1iygJt_yjg,82 +numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90,sha256=iJCD8a8MUTmuPuedbcmxW54Nr4alYuLhksBe1sHS4K0,298 +numpy/f2py/tests/src/isocintrin/isoCtests.f90,sha256=jcw-fzrFh0w5U66uJYfeUW4gv94L5MnWQ_NpsV9y0oI,998 +numpy/f2py/tests/src/kind/foo.f90,sha256=zIHpw1KdkWbTzbXb73hPbCg4N2Htj3XL8DIwM7seXpo,347 +numpy/f2py/tests/src/mixed/foo.f,sha256=90zmbSHloY1XQYcPb8B5d9bv9mCZx8Z8AMTtgDwJDz8,85 +numpy/f2py/tests/src/mixed/foo_fixed.f90,sha256=pxKuPzxF3Kn5khyFq9ayCsQiolxB3SaNtcWaK5j6Rv4,179 +numpy/f2py/tests/src/mixed/foo_free.f90,sha256=fIQ71wrBc00JUAVUj_r3QF9SdeNniBiMw6Ly7CGgPWU,139 +numpy/f2py/tests/src/module_data/mod.mod,sha256=EkjrU7NTZrOH68yKrz6C_eyJMSFSxGgC2yMQT9Zscek,412 +numpy/f2py/tests/src/module_data/module_data_docstring.f90,sha256=tDZ3fUlazLL8ThJm3VwNGJ75QIlLcW70NnMFv-JA4W0,224 +numpy/f2py/tests/src/negative_bounds/issue_20853.f90,sha256=fdOPhRi7ipygwYCXcda7p_dlrws5Hd2GlpF9EZ-qnck,157 +numpy/f2py/tests/src/parameter/constant_both.f90,sha256=-bBf2eqHb-uFxgo6Q7iAtVUUQzrGFqzhHDNaxwSICfQ,1939 +numpy/f2py/tests/src/parameter/constant_compound.f90,sha256=re7pfzcuaquiOia53UT7qNNrTYu2euGKOF4IhoLmT6g,469 +numpy/f2py/tests/src/parameter/constant_integer.f90,sha256=nEmMLitKoSAG7gBBEQLWumogN-KS3DBZOAZJWcSDnFw,612 +numpy/f2py/tests/src/parameter/constant_non_compound.f90,sha256=IcxESVLKJUZ1k9uYKoSb8Hfm9-O_4rVnlkiUU2diy8Q,609 +numpy/f2py/tests/src/parameter/constant_real.f90,sha256=quNbDsM1Ts2rN4WtPO67S9Xi_8l2cXabWRO00CPQSSQ,610 +numpy/f2py/tests/src/quoted_character/foo.f,sha256=WjC9D9171fe2f7rkUAZUvik9bkIf9adByfRGzh6V0cM,482 +numpy/f2py/tests/src/regression/gh25337/data.f90,sha256=9Uz8CHB9i3_mjC3cTOmkTgPAF5tWSwYacG3MUrU-SY0,180 +numpy/f2py/tests/src/regression/gh25337/use_data.f90,sha256=WATiDGAoCKnGgMzm_iMgmfVU0UKOQlk5Fm0iXCmPAkE,179 +numpy/f2py/tests/src/regression/inout.f90,sha256=CpHpgMrf0bqA1W3Ozo3vInDz0RP904S7LkpdAH6ODck,277 +numpy/f2py/tests/src/return_character/foo77.f,sha256=WzDNF3d_hUDSSZjtxd3DtE-bSx1ilOMEviGyYHbcFgM,980 +numpy/f2py/tests/src/return_character/foo90.f90,sha256=ULcETDEt7gXHRzmsMhPsGG4o3lGrcx-FEFaJsPGFKyA,1248 +numpy/f2py/tests/src/return_complex/foo77.f,sha256=8ECRJkfX82oFvGWKbIrCvKjf5QQQClx4sSEvsbkB6A8,973 +numpy/f2py/tests/src/return_complex/foo90.f90,sha256=c1BnrtWwL2dkrTr7wvlEqNDg59SeNMo3gyJuGdRwcDw,1238 +numpy/f2py/tests/src/return_integer/foo77.f,sha256=_8k1evlzBwvgZ047ofpdcbwKdF8Bm3eQ7VYl2Y8b5kA,1178 +numpy/f2py/tests/src/return_integer/foo90.f90,sha256=bzxbYtofivGRYH35Ang9ScnbNsVERN8-6ub5-eI-LGQ,1531 +numpy/f2py/tests/src/return_logical/foo77.f,sha256=FxiF_X0HkyXHzJM2rLyTubZJu4JB-ObLnVqfZwAQFl8,1188 +numpy/f2py/tests/src/return_logical/foo90.f90,sha256=9KmCe7yJYpi4ftkKOM3BCDnPOdBPTbUNrKxY3p37O14,1531 +numpy/f2py/tests/src/return_real/foo77.f,sha256=ZTrzb6oDrIDPlrVWP3Bmtkbz3ffHaaSQoXkfTGtCuFE,933 +numpy/f2py/tests/src/return_real/foo90.f90,sha256=gZuH5lj2lG6gqHlH766KQ3J4-Ero-G4WpOOo2MG3ohU,1194 +numpy/f2py/tests/src/size/foo.f90,sha256=IlFAQazwBRr3zyT7v36-tV0-fXtB1d7WFp6S1JVMstg,815 +numpy/f2py/tests/src/string/char.f90,sha256=ihr_BH9lY7eXcQpHHDQhFoKcbu7VMOX5QP2Tlr7xlaM,618 +numpy/f2py/tests/src/string/fixed_string.f90,sha256=5n6IkuASFKgYICXY9foCVoqndfAY0AQZFEK8L8ARBGM,695 +numpy/f2py/tests/src/string/gh24008.f,sha256=UA8Pr-_yplfOFmc6m4v9ryFQ8W9OulaglulefkFWD68,217 +numpy/f2py/tests/src/string/gh24662.f90,sha256=-Tp9Kd1avvM7AIr8ZukFA9RVr-wusziAnE8AvG9QQI4,197 +numpy/f2py/tests/src/string/gh25286.f90,sha256=2EpxvC-0_dA58MBfGQcLyHzpZgKcMf_W9c73C_Mqnok,304 +numpy/f2py/tests/src/string/gh25286.pyf,sha256=GjgWKh1fHNdPGRiX5ek60i1XSeZsfFalydWqjISPVV8,381 +numpy/f2py/tests/src/string/gh25286_bc.pyf,sha256=6Y9zU66NfcGhTXlFOdFjCSMSwKXpq5ZfAe3FwpkAsm4,384 +numpy/f2py/tests/src/string/scalar_string.f90,sha256=ACxV2i6iPDk-a6L_Bs4jryVKYJMEGUTitEIYTjbJes4,176 +numpy/f2py/tests/src/string/string.f,sha256=shr3fLVZaa6SyUJFYIF1OZuhff8v5lCwsVNBU2B-3pk,248 +numpy/f2py/tests/src/value_attrspec/gh21665.f90,sha256=JC0FfVXsnB2lZHb-nGbySnxv_9VHAyD0mKaLDowczFU,190 +numpy/f2py/tests/test_abstract_interface.py,sha256=C8-ly0_TqkmpQNZmwPHwo2IV2MBH0jQEjAhpqHrg8Y4,832 +numpy/f2py/tests/test_array_from_pyobj.py,sha256=Txff89VUeEhWqUCRVybIqsqH4YQvpk4Uyjmh_XjyMi0,24049 +numpy/f2py/tests/test_assumed_shape.py,sha256=FeaqtrWyBf5uyArcmI0D2e_f763aSMpgU3QmdDXe-tA,1466 +numpy/f2py/tests/test_block_docstring.py,sha256=SEpuq73T9oVtHhRVilFf1xF7nb683d4-Kv7V0kfL4AA,564 +numpy/f2py/tests/test_callback.py,sha256=cReSlVjgnoT74wmtNn-oEIZiJUTfRX7ljjlqJi716IQ,6494 +numpy/f2py/tests/test_character.py,sha256=3ugjM1liymMRbY8wub1eiap-jdyNYVHxlNZBqNoRLe4,21868 +numpy/f2py/tests/test_common.py,sha256=m7TTSJt5zUZKJF-MQUeTtCyxW7YwRBSETINXGPFu8S4,896 +numpy/f2py/tests/test_compile_function.py,sha256=9d_FZ8P2wbIlQ2qPDRrsFqPb4nMH8tiWqYZN-P_shCs,4186 +numpy/f2py/tests/test_crackfortran.py,sha256=y1x3U-jlQWD5rmTXz1I2RlTz7LEfbI6qxCDkR5fzPwY,13441 +numpy/f2py/tests/test_data.py,sha256=HFcmPYbiveKa-swJ8x8XlRR9sM0ESB9FEN-txZnHTok,2876 +numpy/f2py/tests/test_docs.py,sha256=jqtuHE5ZjxP4D8Of3Fkzz36F8_0qKbeS040_m0ac4v4,1662 +numpy/f2py/tests/test_f2cmap.py,sha256=p-Sylbr3ctdKT3UQV9FzpCuYPH5U7Vyn8weXFAjiI9o,391 +numpy/f2py/tests/test_f2py2e.py,sha256=eoswH-daMEBlueoVpxXrDloahCpr0RLzHbr3zBHOsjk,25423 +numpy/f2py/tests/test_isoc.py,sha256=_nPTPxNEEagiKriZBeFNesOattIlHDzaNKmj35xxDBY,1406 +numpy/f2py/tests/test_kind.py,sha256=aOMQSBoD_dw49acKN25_abEvQBLI27DsnWIb9CNpSAE,1671 +numpy/f2py/tests/test_mixed.py,sha256=Ctuw-H7DxhPjSt7wZdJ2xffawIoEBCPWc5F7PSkY4HY,848 +numpy/f2py/tests/test_module_doc.py,sha256=sjCXWIKrqMD1NQ1DUAzgQqkjS5w9h9gvM_Lj29Rdcrg,863 +numpy/f2py/tests/test_parameter.py,sha256=ADI7EV_CM4ztICpqHqeq8LI-WdB6cX0ttatdRdjbsUA,3941 +numpy/f2py/tests/test_pyf_src.py,sha256=eD0bZu_GWfoCq--wWqEKRf-F2h5AwoTyO6GMA9wJPr4,1135 +numpy/f2py/tests/test_quoted_character.py,sha256=cpjMdrHwimnkoJkXd_W_FSlh43oWytY5VHySW9oskO4,454 +numpy/f2py/tests/test_regression.py,sha256=v_6RDQr6IcMmbCMElfzRSLPgZhHnH5l99uztrbJAzqE,2532 +numpy/f2py/tests/test_return_character.py,sha256=18HJtiRwQ7a_2mdPUonD5forKWZJEapD-Vi1DsbTjVs,1493 +numpy/f2py/tests/test_return_complex.py,sha256=BZIIqQ1abdiPLgVmu03_q37yCtND0ijxGSMhGz2Wf-o,2397 +numpy/f2py/tests/test_return_integer.py,sha256=t--9UsdLF9flLTQv7a0KTSVoBuoDtTnmOG2QIFPINVc,1758 +numpy/f2py/tests/test_return_logical.py,sha256=XCmp8E8I6BOeNYF59HjSFAdv1hM9WaDvl8UDS10_05o,2017 +numpy/f2py/tests/test_return_real.py,sha256=ATek5AM7dCCPeIvoMOQIt5yFNFzKrFb1Kno8B4M0rn4,3235 +numpy/f2py/tests/test_semicolon_split.py,sha256=_Mdsi84lES18pPjl9J-QsbGttV4tPFFjZvJvejNcqPc,1635 +numpy/f2py/tests/test_size.py,sha256=q6YqQvcyqdXJeWbGijTiCbxyEG3EkPcvT8AlAW6RCMo,1164 +numpy/f2py/tests/test_string.py,sha256=5xZOfdReoHnId0950XfmtfduPPfBbtMkzBoXMtygvMk,2962 +numpy/f2py/tests/test_symbolic.py,sha256=28quk2kTKfWhKe56n4vINJ8G9weKBfc7HysMlE9J3_g,18341 +numpy/f2py/tests/test_value_attrspec.py,sha256=rWwJBfE2qGzqilZZurJ-7ucNoJDICye6lLetQSLFees,323 +numpy/f2py/tests/util.py,sha256=bEhG699c4bLVPR2WR8fV67avgX6kH5I74SicGb7Z7T4,11167 +numpy/f2py/use_rules.py,sha256=3pTDOPur6gbPHPtwuMJPQvpnUMw39Law1KFSH0coB_0,3527 +numpy/fft/__init__.py,sha256=HqjmF6s_dh0Ri4UZzUDtOKbNUyfAfJAWew3e3EL_KUk,8175 +numpy/fft/__init__.pyi,sha256=vD9Xzz5r13caF4AVL87Y4U9KOj9ic25Vci_wb3dmgpk,550 +numpy/fft/__pycache__/__init__.cpython-310.pyc,, +numpy/fft/__pycache__/_pocketfft.cpython-310.pyc,, +numpy/fft/__pycache__/helper.cpython-310.pyc,, +numpy/fft/_pocketfft.py,sha256=Xkm8wcP4JyBNMbp0ZoHIWhNDlgliX24RzrDuo29uRks,52897 +numpy/fft/_pocketfft.pyi,sha256=S6-ylUuHbgm8vNbh7tLru6K2R5SJzE81BC_Sllm6QrQ,2371 +numpy/fft/_pocketfft_internal.cpython-310-x86_64-linux-gnu.so,sha256=Hcgt6UBj_d9ddFyymC9hWh5pEM1g9vNJwQZbkuB7naM,79776 +numpy/fft/helper.py,sha256=aNj1AcLvtfoX26RiLOwcR-k2QSMuBZkGj2Fu0CeFPJs,6154 +numpy/fft/helper.pyi,sha256=NLTEjy2Gz1aAMDZwCgssIyUne0ubjJqukfYkpsL3gXM,1176 +numpy/fft/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/fft/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/fft/tests/__pycache__/test_helper.cpython-310.pyc,, +numpy/fft/tests/__pycache__/test_pocketfft.cpython-310.pyc,, +numpy/fft/tests/test_helper.py,sha256=whgeaQ8PzFf3B1wkbXobGZ5sF4WxPp4gf1UPUVZest8,6148 +numpy/fft/tests/test_pocketfft.py,sha256=RdeCCvUQmJYVvccOJwToobTKDg9yzUL06o9MkPmRfmI,12895 +numpy/lib/__init__.py,sha256=XMPNJkG_mQ__xuvbf0OcpotgMbA9owt10ZHYVnYHq8E,2713 +numpy/lib/__init__.pyi,sha256=y5ANokFm7EkrlNoHdeQm1FsUhLFxkYtLuanCbsWrGio,5596 +numpy/lib/__pycache__/__init__.cpython-310.pyc,, +numpy/lib/__pycache__/_datasource.cpython-310.pyc,, +numpy/lib/__pycache__/_iotools.cpython-310.pyc,, +numpy/lib/__pycache__/_version.cpython-310.pyc,, +numpy/lib/__pycache__/arraypad.cpython-310.pyc,, +numpy/lib/__pycache__/arraysetops.cpython-310.pyc,, +numpy/lib/__pycache__/arrayterator.cpython-310.pyc,, +numpy/lib/__pycache__/format.cpython-310.pyc,, +numpy/lib/__pycache__/function_base.cpython-310.pyc,, +numpy/lib/__pycache__/histograms.cpython-310.pyc,, +numpy/lib/__pycache__/index_tricks.cpython-310.pyc,, +numpy/lib/__pycache__/mixins.cpython-310.pyc,, +numpy/lib/__pycache__/nanfunctions.cpython-310.pyc,, +numpy/lib/__pycache__/npyio.cpython-310.pyc,, +numpy/lib/__pycache__/polynomial.cpython-310.pyc,, +numpy/lib/__pycache__/recfunctions.cpython-310.pyc,, +numpy/lib/__pycache__/scimath.cpython-310.pyc,, +numpy/lib/__pycache__/setup.cpython-310.pyc,, +numpy/lib/__pycache__/shape_base.cpython-310.pyc,, +numpy/lib/__pycache__/stride_tricks.cpython-310.pyc,, +numpy/lib/__pycache__/twodim_base.cpython-310.pyc,, +numpy/lib/__pycache__/type_check.cpython-310.pyc,, +numpy/lib/__pycache__/ufunclike.cpython-310.pyc,, +numpy/lib/__pycache__/user_array.cpython-310.pyc,, +numpy/lib/__pycache__/utils.cpython-310.pyc,, +numpy/lib/_datasource.py,sha256=CDF3im6IxdY3Mu6fwRQmkSEBmXS3kQVInQ4plXsoX9c,22631 +numpy/lib/_iotools.py,sha256=Yg9HCfPg4tbhbdgLPcxSMiZXq1xDprvJKLebLwhDszY,30868 +numpy/lib/_version.py,sha256=6vK7czNSB_KrWx2rZJzJ1pyOc73Q07hAgfLB5ItUCnU,4855 +numpy/lib/_version.pyi,sha256=B572hyWrUWG-TAAAXrNNAT4AgyUAmJ4lvgpwMkDzunk,633 +numpy/lib/arraypad.py,sha256=bKP7ZS9NYFYzqSk8OnpFLFrMsua4m_hcqFsi7cGkrJE,31803 +numpy/lib/arraypad.pyi,sha256=ADXphtAORYl3EqvE5qs_u32B_TALKSOtF43jOLmoxRw,1728 +numpy/lib/arraysetops.py,sha256=GJ2RhkzIJmIbwyG6h3LOFTPXg62kM9tcV1a-7tdbVuU,33655 +numpy/lib/arraysetops.pyi,sha256=6X-5l5Yss_9y10LYyIsDLbGX77vt7PtVLDqxOlSRPfY,8372 +numpy/lib/arrayterator.py,sha256=BQ97S00zvfURUZfes0GZo-5hydYNRuvwX1I1bLzeRik,7063 +numpy/lib/arrayterator.pyi,sha256=f7Pwp83_6DiMYmJGUsffncM-FRAynB1iYGvhmHM_SZE,1537 +numpy/lib/format.py,sha256=T8qJMyG2DDVjjYNNpUvBgfA9tCo23IS0w9byRB6twwQ,34769 +numpy/lib/format.pyi,sha256=YWBxC3GdsZ7SKBN8I7nMwWeVuFD1aT9d-VJ8zE4-P-o,748 +numpy/lib/function_base.py,sha256=IhhgfSmYJE-dHoUOMXHPiGYXso-NdXPpLXF9y0gEA6I,189172 +numpy/lib/function_base.pyi,sha256=KWaC5UOBANU4hiIoN2eptE4HYsm4vgp_8BMFV1Y3JX4,16585 +numpy/lib/histograms.py,sha256=xsj_qpaZoI2Bv1FBpY8mIMPJrYRiuIBszn_6kO7YFRA,37778 +numpy/lib/histograms.pyi,sha256=hNwR2xYWkgJCP-nfRGxc-EgHLTD3qm4zmWXthZLt08M,995 +numpy/lib/index_tricks.py,sha256=4PEvXk6VFTkttMViYBVC4yDhyOiKIon6JpIm0d_CmNg,31346 +numpy/lib/index_tricks.pyi,sha256=D2nkNXOB9Vea1PfMaTn94OGBGayjTaQ-bKMsjDmYpak,4251 +numpy/lib/mixins.py,sha256=y6_MzQuiNjv-1EFVROqv2y2cAJi5X4rQYzbZCyUyXgw,7071 +numpy/lib/mixins.pyi,sha256=h9N1kbZsUntF0zjOxPYeD_rCB2dMiG35TYYPl9ymkI4,3117 +numpy/lib/nanfunctions.py,sha256=6EjzydZlugIzfiENKtC4ycZ2Nckt8ZQg5v6D6tX1SiU,65775 +numpy/lib/nanfunctions.pyi,sha256=oPqAfCinmBL85Ji7ko4QlzAzLAK9nZL0t2_CllEbCEU,606 +numpy/lib/npyio.py,sha256=NUjtFvAmPdTjwJQ-ia-xbCr849M_M6NilP5IHfkKaRg,97316 +numpy/lib/npyio.pyi,sha256=SUFWJh90vWZCdd6GCSGbfYeXKlWut0XY_SHvZJc8yqY,9728 +numpy/lib/polynomial.py,sha256=6Aw3_2vdbh4urERQ6NaPhf9a_T1o1o6cjm3fb5Z3_YE,44133 +numpy/lib/polynomial.pyi,sha256=GerIpQnf5LdtFMOy9AxhOTqUyfn57k4MxqEYrfdckWE,6958 +numpy/lib/recfunctions.py,sha256=-90AbWWvVFOqVUPLh9K9NYdKUHYIgSEyg2Y35MnOVUA,59423 +numpy/lib/scimath.py,sha256=T4ITysZgqhY1J8IxyXCtioHjMTg2ci-4i3mr9TBF2UA,15037 +numpy/lib/scimath.pyi,sha256=E2roKJzMFwWSyhLu8UPUr54WOpxF8jp_pyXYBgsUSQ8,2883 +numpy/lib/setup.py,sha256=0K5NJKuvKvNEWp-EX7j0ODi3ZQQgIMHobzSFJq3G7yM,405 +numpy/lib/shape_base.py,sha256=AhCO9DEyysE-P-QJF9ryUtJ1ghU4_0mORhAJ59poObU,38947 +numpy/lib/shape_base.pyi,sha256=bGJhLA_RvUpVTiDFgCV-1rUjV8e1qCh0gK_3PLgXA_U,5341 +numpy/lib/stride_tricks.py,sha256=brY5b-0YQJuIH2CavfpIinMolyTUv5k9DUvLoZ-imis,17911 +numpy/lib/stride_tricks.pyi,sha256=0pQ4DP9l6g21q2Ajv6dJFRWMr9auPGTNV9BmZUbogPY,1747 +numpy/lib/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/lib/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test__datasource.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test__iotools.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test__version.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_arraypad.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_arraysetops.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_arrayterator.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_financial_expired.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_format.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_function_base.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_histograms.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_index_tricks.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_io.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_loadtxt.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_mixins.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_nanfunctions.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_packbits.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_polynomial.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_recfunctions.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_regression.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_shape_base.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_stride_tricks.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_twodim_base.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_type_check.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_ufunclike.cpython-310.pyc,, +numpy/lib/tests/__pycache__/test_utils.cpython-310.pyc,, +numpy/lib/tests/data/py2-objarr.npy,sha256=F4cyUC-_TB9QSFLAo2c7c44rC6NUYIgrfGx9PqWPSKk,258 +numpy/lib/tests/data/py2-objarr.npz,sha256=xo13HBT0FbFZ2qvZz0LWGDb3SuQASSaXh7rKfVcJjx4,366 +numpy/lib/tests/data/py3-objarr.npy,sha256=pTTVh8ezp-lwAK3fkgvdKU8Arp5NMKznVD-M6Ex_uA0,341 +numpy/lib/tests/data/py3-objarr.npz,sha256=qQR0gS57e9ta16d_vCQjaaKM74gPdlwCPkp55P-qrdw,449 +numpy/lib/tests/data/python3.npy,sha256=X0ad3hAaLGXig9LtSHAo-BgOvLlFfPYMnZuVIxRmj-0,96 +numpy/lib/tests/data/win64python2.npy,sha256=agOcgHVYFJrV-nrRJDbGnUnF4ZTPYXuSeF-Mtg7GMpc,96 +numpy/lib/tests/test__datasource.py,sha256=65KXfUUvp8wXSqgQisuYlkhg-qHjBV5FXYetL8Ba-rc,10571 +numpy/lib/tests/test__iotools.py,sha256=HerCqvDE07JxjFQlWEfpZO7lC9z0Sbr3z20GSutoCPs,13743 +numpy/lib/tests/test__version.py,sha256=aO3YgkAohLsLzCNQ7vjIwdpFUMz0cPLbcuuxIkjuN74,1999 +numpy/lib/tests/test_arraypad.py,sha256=obohHbyM0gPYPUkd7iJSOSiDqyqtJsjDNtQX68NC4lM,54830 +numpy/lib/tests/test_arraysetops.py,sha256=5-T1MVhfIMivat8Z47GZw0ZaR811W_FskM1bAXnFyLU,35912 +numpy/lib/tests/test_arrayterator.py,sha256=AYs2SwV5ankgwnvKI9RSO1jZck118nu3SyZ4ngzZNso,1291 +numpy/lib/tests/test_financial_expired.py,sha256=yq5mqGMvqpkiiw9CuZhJgrYa7Squj1mXr_G-IvAFgwI,247 +numpy/lib/tests/test_format.py,sha256=xV0oi1eoRnVwAAhSOcPFQHQWF7TfsROtDYShQLPtdaA,41028 +numpy/lib/tests/test_function_base.py,sha256=DBKugIUEFTMP7g6iL1bk986E6ldCrcNdBCWOJbQla_Y,157830 +numpy/lib/tests/test_histograms.py,sha256=16_XJp-eFgsuM8B4mDQpQ4w_Ib29Hg0EPO-WFsdaFWA,32815 +numpy/lib/tests/test_index_tricks.py,sha256=Vjz25Y6H_ih0iEE2AG0kaxO9U8PwcXSrofzqnN4XBwI,20256 +numpy/lib/tests/test_io.py,sha256=3Tow1pucrQ7z7osNN4a2grBYUoBGNkQEhjmCjXT6Vag,107891 +numpy/lib/tests/test_loadtxt.py,sha256=gwcDJDJmLJRMLpg322yjQ1IzI505w9EqJoq4DmDPCdI,38560 +numpy/lib/tests/test_mixins.py,sha256=Wivwz3XBWsEozGzrzsyyvL3qAuE14t1BHk2LPm9Z9Zc,7030 +numpy/lib/tests/test_nanfunctions.py,sha256=01r_mmTCvKVdZuOGTEHNDZXrMS724us_jwZANzCd74A,47609 +numpy/lib/tests/test_packbits.py,sha256=OWGAd5g5GG0gl7WHqNfwkZ7G-2rrtLt2sI854PG4nnw,17546 +numpy/lib/tests/test_polynomial.py,sha256=URouxJpr8FQ5hiKybqhtOcLA7e-3hj4kWzjLBROByyA,11395 +numpy/lib/tests/test_recfunctions.py,sha256=6jzouPEQ7Uhtj8_-W5yTI6ymNp2nLgmdHzxdd74jVuM,44001 +numpy/lib/tests/test_regression.py,sha256=KzGFkhTcvEG97mymoOQ2hP2CEr2nPZou0Ztf4-WaXCs,8257 +numpy/lib/tests/test_shape_base.py,sha256=2iQCEFR6evVpF8woaenxUOzooHkfuMYkBaUj8ecyJ-E,26817 +numpy/lib/tests/test_stride_tricks.py,sha256=wprpWWH5eq07DY7rzG0WDv5fMtLxzRQz6fm6TZWlScQ,22849 +numpy/lib/tests/test_twodim_base.py,sha256=ll-72RhqCItIPB97nOWhH7H292h4nVIX_w1toKTPMUg,18841 +numpy/lib/tests/test_type_check.py,sha256=lxCH5aApWVYhhSoDQSLDTCHLVHuK2c-jBbnfnZUrOaA,15114 +numpy/lib/tests/test_ufunclike.py,sha256=4hSnXGlSC8HE-_pRRMzD8-HI4hGHqsAWu1pD0o2kPI0,2982 +numpy/lib/tests/test_utils.py,sha256=RVAxrzSFu6N3C4_jIgAlTDOWF_B7wr2v1Y20dX5upYM,6218 +numpy/lib/twodim_base.py,sha256=Mvzn_PyShIb9m7nJjJ4IetdxwmLYEsCPHvJoK7n2viU,32947 +numpy/lib/twodim_base.pyi,sha256=xFRcEVJdDj4mrXW_6iVP1lTMoJx4QJjYRD3o2_9f2eY,5370 +numpy/lib/type_check.py,sha256=_EOtB296nFYlNT7ztBYoC_yK9aycIb0KTmRjvzVdZNg,19954 +numpy/lib/type_check.pyi,sha256=LPvAvIxU-p5i_Qe-ic7hEvo4OTfSrNpplxMG7OAZe8Q,5571 +numpy/lib/ufunclike.py,sha256=_ceBGbGCMOd3u_h2UVzyaRK6ZY7ryoJ0GJB7zqcJG3w,6325 +numpy/lib/ufunclike.pyi,sha256=hLxcYfQprh1tTY_UO2QscA3Hd9Zd7cVGXIINZLhMFqY,1293 +numpy/lib/user_array.py,sha256=LE958--CMkBI2r3l1SQxmCHdCSw6HY6-RhWCnduzGA4,7721 +numpy/lib/utils.py,sha256=6NdleaELZiqARdj-ECZjxtwLf1bqklOcK43m9yoZefs,37804 +numpy/lib/utils.pyi,sha256=mVHVzWuc2-M3Oz60lFsbok0v8LH_HRHMjZpXwrtzF_c,2360 +numpy/linalg/__init__.py,sha256=mpdlEXWtTvpF7In776ONLwp6RIyo4U_GLPT1L1eIJnw,1813 +numpy/linalg/__init__.pyi,sha256=XBy4ocuypsRVflw_mbSTUhR4N5Roemu6w5SfeVwbkAc,620 +numpy/linalg/__pycache__/__init__.cpython-310.pyc,, +numpy/linalg/__pycache__/linalg.cpython-310.pyc,, +numpy/linalg/_umath_linalg.cpython-310-x86_64-linux-gnu.so,sha256=gLgyVwr5_b1SPRpnq6JddWVD8Kwjz-0bp1PGsXGL1As,201536 +numpy/linalg/lapack_lite.cpython-310-x86_64-linux-gnu.so,sha256=dMkLCpE-DzoojBjrsH_x52Fi3YPHlYY3SuRW9TqW7tU,25816 +numpy/linalg/linalg.py,sha256=kDVK1GBxbUjlRgxXCoEfkRJm8yrNr1Iu7hMn2rKK8RE,90923 +numpy/linalg/linalg.pyi,sha256=zD9U5BUCB1uQggSxfZaTGX_uB2Hkp75sttGmZbCGgBI,7505 +numpy/linalg/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/linalg/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/linalg/tests/__pycache__/test_deprecations.cpython-310.pyc,, +numpy/linalg/tests/__pycache__/test_linalg.cpython-310.pyc,, +numpy/linalg/tests/__pycache__/test_regression.cpython-310.pyc,, +numpy/linalg/tests/test_deprecations.py,sha256=9p_SRmtxj2zc1doY9Ie3dyy5JzWy-tCQWFoajcAJUmM,640 +numpy/linalg/tests/test_linalg.py,sha256=rgvmK6Or70u8mN04puetL3FgSxZ8fJrOlI5ptTgCU5k,78085 +numpy/linalg/tests/test_regression.py,sha256=qbugUmrENybkEaM1GhfA01RXQUy8AkzalbrfzSIgUmM,5434 +numpy/ma/API_CHANGES.txt,sha256=F_4jW8X5cYBbzpcwteymkonTmvzgKKY2kGrHF1AtnrI,3405 +numpy/ma/LICENSE,sha256=BfO4g1GYjs-tEKvpLAxQ5YdcZFLVAJoAhMwpFVH_zKY,1593 +numpy/ma/README.rst,sha256=q-gCsZ4Cw_gUGGvEjog556sJUHIm8WTAwkFK5Qnz9XA,9872 +numpy/ma/__init__.py,sha256=dgP0WdnOpph28Fd6UiqoyDKhfrct0H6QWqbCcETsk6M,1404 +numpy/ma/__init__.pyi,sha256=ppCg_TS0POutNB3moJE4kBabWURnc0WGXyYPquXZxS4,6063 +numpy/ma/__pycache__/__init__.cpython-310.pyc,, +numpy/ma/__pycache__/core.cpython-310.pyc,, +numpy/ma/__pycache__/extras.cpython-310.pyc,, +numpy/ma/__pycache__/mrecords.cpython-310.pyc,, +numpy/ma/__pycache__/setup.cpython-310.pyc,, +numpy/ma/__pycache__/testutils.cpython-310.pyc,, +numpy/ma/__pycache__/timer_comparison.cpython-310.pyc,, +numpy/ma/core.py,sha256=4MglVRJtmQ9_iIVaQ2b-_Vmw1TjAhEsMJdtKOhyBFXQ,278213 +numpy/ma/core.pyi,sha256=YfgyuBuKxZ5v4I2JxZDvCLhnztOCRgzTeDg-JGTon_M,14305 +numpy/ma/extras.py,sha256=MC7QPS34PC4wxNbOp7pTy57dqF9B-L6L1KMI6rrfe2w,64383 +numpy/ma/extras.pyi,sha256=BBsiCZbaPpGCY506fkmqZdBkJNCXcglc3wcSBuAACNk,2646 +numpy/ma/mrecords.py,sha256=degd6dLaDEvEWNHmvSnUZXos1csIzaqjR_jAutm8JfI,27232 +numpy/ma/mrecords.pyi,sha256=r1a2I662ywnhGS6zvfcyK-9RHVvb4sHxiCx9Dhf5AE4,1934 +numpy/ma/setup.py,sha256=MqmMicr_xHkAGoG-T7NJ4YdUZIJLO4ZFp6AmEJDlyhw,418 +numpy/ma/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/ma/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/ma/tests/__pycache__/test_core.cpython-310.pyc,, +numpy/ma/tests/__pycache__/test_deprecations.cpython-310.pyc,, +numpy/ma/tests/__pycache__/test_extras.cpython-310.pyc,, +numpy/ma/tests/__pycache__/test_mrecords.cpython-310.pyc,, +numpy/ma/tests/__pycache__/test_old_ma.cpython-310.pyc,, +numpy/ma/tests/__pycache__/test_regression.cpython-310.pyc,, +numpy/ma/tests/__pycache__/test_subclassing.cpython-310.pyc,, +numpy/ma/tests/test_core.py,sha256=xd5S3oa0jObo8jnsJk0-o46d-KNC3RtgNRKinJeY_kE,215100 +numpy/ma/tests/test_deprecations.py,sha256=nq_wFVt2EBHcT3AHxattfKXx2JDf1K5D-QBzUU0_15A,2566 +numpy/ma/tests/test_extras.py,sha256=lX4cbdGDEXaBHzA3q8hJxve4635XCJw4AP7FO7zhOfk,74858 +numpy/ma/tests/test_mrecords.py,sha256=PsJhUlABgdpSsPUeijonfyFNqz5AfNSGQTtJUte7yts,19890 +numpy/ma/tests/test_old_ma.py,sha256=h4BncexBcBigqvZMA6RjDjpHPurWtt99A7KTag2rmOs,32690 +numpy/ma/tests/test_regression.py,sha256=foMpI0luAvwkkRpAfPDV_810h1URISXDZhmaNhxb50k,3287 +numpy/ma/tests/test_subclassing.py,sha256=HeTIE_n1I8atwzF8tpvNtGHp-0dmM8PT8AS4IDWbcso,16967 +numpy/ma/testutils.py,sha256=RQw0RyS7hOSVTk4KrCGleq0VHlnDqzwwaLtuZbRE4_I,10235 +numpy/ma/timer_comparison.py,sha256=pIGSZG-qYYYlRWSTgzPlyCAINbGKhXrZrDZBBjiM080,15658 +numpy/matlib.py,sha256=-54vTuGIgeTMg9ZUmElRPZ4Hr-XZ-om9xLzAsSoTvnc,10465 +numpy/matrixlib/__init__.py,sha256=BHBpQKoQv4EjT0UpWBA-Ck4L5OsMqTI2IuY24p-ucXk,242 +numpy/matrixlib/__init__.pyi,sha256=-t3ZuvbzRuRwWfZOeN4xlNWdm7gQEprhUsWzu8MRvUE,252 +numpy/matrixlib/__pycache__/__init__.cpython-310.pyc,, +numpy/matrixlib/__pycache__/defmatrix.cpython-310.pyc,, +numpy/matrixlib/__pycache__/setup.cpython-310.pyc,, +numpy/matrixlib/defmatrix.py,sha256=JXdJGm1LayOOXfKpp7OVZfb0pzzP4Lwh45sTJrleALc,30656 +numpy/matrixlib/defmatrix.pyi,sha256=lmBMRahKcMOl2PHDo79J67VRAZOkI54BzfDaTLpE0LI,451 +numpy/matrixlib/setup.py,sha256=1r7JRkSM4HyVorgtjoKJGWLcOcPO3wmvivpeEsVtAEg,426 +numpy/matrixlib/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/matrixlib/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/matrixlib/tests/__pycache__/test_defmatrix.cpython-310.pyc,, +numpy/matrixlib/tests/__pycache__/test_interaction.cpython-310.pyc,, +numpy/matrixlib/tests/__pycache__/test_masked_matrix.cpython-310.pyc,, +numpy/matrixlib/tests/__pycache__/test_matrix_linalg.cpython-310.pyc,, +numpy/matrixlib/tests/__pycache__/test_multiarray.cpython-310.pyc,, +numpy/matrixlib/tests/__pycache__/test_numeric.cpython-310.pyc,, +numpy/matrixlib/tests/__pycache__/test_regression.cpython-310.pyc,, +numpy/matrixlib/tests/test_defmatrix.py,sha256=8E_-y7VD2vsq1y8CcI8km37pp5qcAtkciO16xqf2UIs,14982 +numpy/matrixlib/tests/test_interaction.py,sha256=PpjmgjEKighDXvt38labKE6L7f2jP74UEmp3JRb_iOY,11875 +numpy/matrixlib/tests/test_masked_matrix.py,sha256=7YO_LCO8DOhW3CuXJuxH93rnmttfvHnU7El-MBzxzFw,8932 +numpy/matrixlib/tests/test_matrix_linalg.py,sha256=ObbSUXU4R2pWajH__xAdizADrU2kBKDDCxkDV-oVBXc,2059 +numpy/matrixlib/tests/test_multiarray.py,sha256=jB3XCBmAtcqf-Wb9PwBW6uIykPpMPthuXLJ0giTKzZE,554 +numpy/matrixlib/tests/test_numeric.py,sha256=MP70qUwgshTtThKZaZDp7_6U-Z66NIV1geVhasGXejQ,441 +numpy/matrixlib/tests/test_regression.py,sha256=8sHDtO8Zi8p3a1eQKEWxtCmKrXmHoD3qxlIokg2AIAU,927 +numpy/polynomial/__init__.py,sha256=braLh6zP2QwuNKRKAaZGdC_qKWZ-tJlc3BN83LeuE_0,6781 +numpy/polynomial/__init__.pyi,sha256=W8szYtVUy0RUi83jmFLK58BN8CKVSoHA2CW7IcdUl1c,701 +numpy/polynomial/__pycache__/__init__.cpython-310.pyc,, +numpy/polynomial/__pycache__/_polybase.cpython-310.pyc,, +numpy/polynomial/__pycache__/chebyshev.cpython-310.pyc,, +numpy/polynomial/__pycache__/hermite.cpython-310.pyc,, +numpy/polynomial/__pycache__/hermite_e.cpython-310.pyc,, +numpy/polynomial/__pycache__/laguerre.cpython-310.pyc,, +numpy/polynomial/__pycache__/legendre.cpython-310.pyc,, +numpy/polynomial/__pycache__/polynomial.cpython-310.pyc,, +numpy/polynomial/__pycache__/polyutils.cpython-310.pyc,, +numpy/polynomial/__pycache__/setup.cpython-310.pyc,, +numpy/polynomial/_polybase.py,sha256=YEnnQwlTgbn3dyD89ueraUx5nxx3x_pH6K6mmyEmhi8,39271 +numpy/polynomial/_polybase.pyi,sha256=J7yU9PPZW4W8mkqAltDfnL4ZNwljuM-bDEj4DPTJZpY,2321 +numpy/polynomial/chebyshev.py,sha256=NZCKjIblcX99foqZyp51i0_r8p0r1VKVGZFmQ1__kEk,62796 +numpy/polynomial/chebyshev.pyi,sha256=035CNdOas4dnb6lFLzRiBrYT_VnWh2T1-A3ibm_HYkI,1387 +numpy/polynomial/hermite.py,sha256=t5CFM-qE4tszYJiQZ301VcMn7IM67y2rUZPFPtnVRAc,52514 +numpy/polynomial/hermite.pyi,sha256=hdsvTULow8bIjnATudf0i6brpLHV7vbOoHzaMvbjMy0,1217 +numpy/polynomial/hermite_e.py,sha256=jRR3f8Oth8poV2Ix8c0eLEQR3UZary-2RupOrEAEUMY,52642 +numpy/polynomial/hermite_e.pyi,sha256=zV7msb9v9rV0iv_rnD3SjP-TGyc6pd3maCqiPCj3PbA,1238 +numpy/polynomial/laguerre.py,sha256=mcVw0ckWVX-kzJ1QIhdcuuxzPjuFmA3plQLkloQMOYM,50858 +numpy/polynomial/laguerre.pyi,sha256=Gxc9SLISNKMWrKdsVJ9fKFFFwfxxZzfF-Yc-2r__z5M,1178 +numpy/polynomial/legendre.py,sha256=wjtgFajmKEbYkSUk3vWSCveMHDP6UymK28bNUk4Ov0s,51550 +numpy/polynomial/legendre.pyi,sha256=9dmANwkxf7EbOHV3XQBPoaDtc56cCkf75Wo7FG9Zfj4,1178 +numpy/polynomial/polynomial.py,sha256=XsaZPHmLGJFqpJs7rPvO5E0loWQ1L3YHLIUybVu4dU8,49112 +numpy/polynomial/polynomial.pyi,sha256=bOPRnub4xXxsUwNGeiQLTT4PCfN1ysSrf6LBZIcAN2Y,1132 +numpy/polynomial/polyutils.py,sha256=Xy5qjdrjnRaqSlClG1ROmwWccLkAPC7IcHaNJLvhCf4,23237 +numpy/polynomial/polyutils.pyi,sha256=cFAyZ9Xzuw8Huhn9FEz4bhyD00m2Dp-2DiUSyogJwSo,264 +numpy/polynomial/setup.py,sha256=dXQfzVUMP9OcB6iKv5yo1GLEwFB3gJ48phIgo4N-eM0,373 +numpy/polynomial/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/polynomial/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/polynomial/tests/__pycache__/test_chebyshev.cpython-310.pyc,, +numpy/polynomial/tests/__pycache__/test_classes.cpython-310.pyc,, +numpy/polynomial/tests/__pycache__/test_hermite.cpython-310.pyc,, +numpy/polynomial/tests/__pycache__/test_hermite_e.cpython-310.pyc,, +numpy/polynomial/tests/__pycache__/test_laguerre.cpython-310.pyc,, +numpy/polynomial/tests/__pycache__/test_legendre.cpython-310.pyc,, +numpy/polynomial/tests/__pycache__/test_polynomial.cpython-310.pyc,, +numpy/polynomial/tests/__pycache__/test_polyutils.cpython-310.pyc,, +numpy/polynomial/tests/__pycache__/test_printing.cpython-310.pyc,, +numpy/polynomial/tests/__pycache__/test_symbol.cpython-310.pyc,, +numpy/polynomial/tests/test_chebyshev.py,sha256=6tMsFP1h7K8Zf72mNOta6Tv52_fVTlXknseuffj080c,20522 +numpy/polynomial/tests/test_classes.py,sha256=DFyY2IQBj3r2GZkvbRIeZO2EEY466xbuwc4PShAl4Sw,18331 +numpy/polynomial/tests/test_hermite.py,sha256=N9b2dx2UWPyja5v02dSoWYPnKvb6H-Ozgtrx-xjWz2k,18577 +numpy/polynomial/tests/test_hermite_e.py,sha256=_A3ohAWS4HXrQG06S8L47dImdZGTwYosCXnoyw7L45o,18911 +numpy/polynomial/tests/test_laguerre.py,sha256=BZOgs49VBXOFBepHopxuEDkIROHEvFBfWe4X73UZhn8,17511 +numpy/polynomial/tests/test_legendre.py,sha256=b_bblHs0F_BWw9ESuSq52ZsLKcQKFR5eqPf_SppWFqo,18673 +numpy/polynomial/tests/test_polynomial.py,sha256=4cuO8-5wdIxcz5CrucB5Ix7ySuMROokUF12F7ogQ_hc,20529 +numpy/polynomial/tests/test_polyutils.py,sha256=IxkbVfpcBqe5lOZluHFUPbLATLu1rwVg7ghLASpfYrY,3579 +numpy/polynomial/tests/test_printing.py,sha256=rfP4MaQbjGcO52faHmYrgsaarkm3Ndi3onwr6DDuapE,20525 +numpy/polynomial/tests/test_symbol.py,sha256=msTPv7B1niaKujU33kuZmdxJvLYvOjfl1oykmlL0dXo,5371 +numpy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/random/LICENSE.md,sha256=EDFmtiuARDr7nrNIjgUuoGvgz_VmuQjxmeVh_eSa8Z8,3511 +numpy/random/__init__.pxd,sha256=9JbnX540aJNSothGs-7e23ozhilG6U8tINOUEp08M_k,431 +numpy/random/__init__.py,sha256=81Thnexg5umN5WZwD5TRyzNc2Yp-d14B6UC7NBgVKh8,7506 +numpy/random/__init__.pyi,sha256=RfW8mco48UaWDL1UC5ROv9vXiFZ9EGho62avhgEAHPc,2143 +numpy/random/__pycache__/__init__.cpython-310.pyc,, +numpy/random/__pycache__/_pickle.cpython-310.pyc,, +numpy/random/_bounded_integers.cpython-310-x86_64-linux-gnu.so,sha256=zqR6h5HzQnt7Y3Ub9RjZDDLRckLgJdXK9eg-CSNxJfY,357136 +numpy/random/_bounded_integers.pxd,sha256=hcoucPH5hkFEM2nm12zYO-5O_Rt8RujEXT5YWuAzl1Q,1669 +numpy/random/_common.cpython-310-x86_64-linux-gnu.so,sha256=zq69qwT6G9NaUc8oEdMIyU4SDvgfhbwuHYtH0mlCmQk,250192 +numpy/random/_common.pxd,sha256=s2_IdIQ0MhNbogamulvXe-b93wbx882onmYkxqswwpo,4939 +numpy/random/_examples/cffi/__pycache__/extending.cpython-310.pyc,, +numpy/random/_examples/cffi/__pycache__/parse.cpython-310.pyc,, +numpy/random/_examples/cffi/extending.py,sha256=xSla3zWqxi6Hj48EvnYfD3WHfE189VvC4XsKu4_T_Iw,880 +numpy/random/_examples/cffi/parse.py,sha256=Bnb7t_6S_c5-3dZrQ-XX9EazOKhftUfcCejXXWyd1EU,1771 +numpy/random/_examples/cython/extending.pyx,sha256=4IE692pq1V53UhPZqQiQGcIHXDoNyqTx62x5a36puVg,2290 +numpy/random/_examples/cython/extending_distributions.pyx,sha256=oazFVWeemfE0eDzax7r7MMHNL1_Yofws2m-c_KT2Hbo,3870 +numpy/random/_examples/cython/meson.build,sha256=rXtugURMEo-ef4bPE1QIv4mzvWbeGjmcTdKCBvjxjtw,1443 +numpy/random/_examples/numba/__pycache__/extending.cpython-310.pyc,, +numpy/random/_examples/numba/__pycache__/extending_distributions.cpython-310.pyc,, +numpy/random/_examples/numba/extending.py,sha256=Ipyzel_h5iU_DMJ_vnXUgQC38uMDMn7adUpWSeEQLFE,1957 +numpy/random/_examples/numba/extending_distributions.py,sha256=Jnr9aWkHyIWygNbdae32GVURK-5T9BTGhuExRpvve98,2034 +numpy/random/_generator.cpython-310-x86_64-linux-gnu.so,sha256=bOlGfWbhWMimQbzX5MI4ahDAY13qGFFtld6Gqv_9N8U,912912 +numpy/random/_generator.pyi,sha256=zRvo_y6g0pWkE4fO1M9jLYUkxDfGdA6Enreb3U2AADM,22442 +numpy/random/_mt19937.cpython-310-x86_64-linux-gnu.so,sha256=vDKBcSDdo1nciVE9zzvxW_YbJKaqJhA9Dlf1MNAU_4Q,102480 +numpy/random/_mt19937.pyi,sha256=_iZKaAmuKBQ4itSggfQvYYj_KjktcN4rt-YpE6bqFAM,724 +numpy/random/_pcg64.cpython-310-x86_64-linux-gnu.so,sha256=SJCtc3b28A6r8ya9TUZJFKPgqNGA5h5oSewKDlwLMZg,117144 +numpy/random/_pcg64.pyi,sha256=uxr5CbEJetN6lv9vBG21jlRhuzOK8SQnXrwqAQBxj_c,1091 +numpy/random/_philox.cpython-310-x86_64-linux-gnu.so,sha256=k2pV19pLdKgVcujcdKjEF0BqfWsKKrBa50aWMQeJ8EQ,98224 +numpy/random/_philox.pyi,sha256=OKlaiIU-hj72Bp04zjNifwusOD_3-mYxIfvyuys8c_o,978 +numpy/random/_pickle.py,sha256=4NhdT-yk7C0m3tyZWmouYAs3ZGNPdPVNGfUIyuh8HDY,2318 +numpy/random/_sfc64.cpython-310-x86_64-linux-gnu.so,sha256=vHyCRtVozdClClUn6I7vHBeQzykFH8LKu6wPkUG4x6o,67376 +numpy/random/_sfc64.pyi,sha256=09afHTedVW-519493ZXtGcl-H-_zluj-B_yfEJG8MMs,709 +numpy/random/bit_generator.cpython-310-x86_64-linux-gnu.so,sha256=Qld0jPYmynG2Kl1jgZuSgLTvdwFdrPWA1TIujoLw4Yo,224624 +numpy/random/bit_generator.pxd,sha256=lArpIXSgTwVnJMYc4XX0NGxegXq3h_QsUDK6qeZKbNc,1007 +numpy/random/bit_generator.pyi,sha256=aXv7a_hwa0nkjY8P2YENslwWp89UcFRn09woXh7Uoc0,3510 +numpy/random/c_distributions.pxd,sha256=7DE-mV3H_Dihk4OK4gMHHkyD4tPX1cAi4570zi5CI30,6344 +numpy/random/lib/libnpyrandom.a,sha256=yl8TC04ZJXgMD8meT1Vu3cO2QJNTzAarbY5O0gTOpW0,82470 +numpy/random/mtrand.cpython-310-x86_64-linux-gnu.so,sha256=Q8L2q52KFRa_hdsMpfr4lDHudCGL049pc69JpZ61S38,722208 +numpy/random/mtrand.pyi,sha256=3vAGOXsvyFFv0yZl34pVVPP7Dgt22COyfn4tUoi_hEQ,19753 +numpy/random/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/random/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/random/tests/__pycache__/test_direct.cpython-310.pyc,, +numpy/random/tests/__pycache__/test_extending.cpython-310.pyc,, +numpy/random/tests/__pycache__/test_generator_mt19937.cpython-310.pyc,, +numpy/random/tests/__pycache__/test_generator_mt19937_regressions.cpython-310.pyc,, +numpy/random/tests/__pycache__/test_random.cpython-310.pyc,, +numpy/random/tests/__pycache__/test_randomstate.cpython-310.pyc,, +numpy/random/tests/__pycache__/test_randomstate_regression.cpython-310.pyc,, +numpy/random/tests/__pycache__/test_regression.cpython-310.pyc,, +numpy/random/tests/__pycache__/test_seed_sequence.cpython-310.pyc,, +numpy/random/tests/__pycache__/test_smoke.cpython-310.pyc,, +numpy/random/tests/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/random/tests/data/__pycache__/__init__.cpython-310.pyc,, +numpy/random/tests/data/mt19937-testset-1.csv,sha256=Xkef402AVB-eZgYQkVtoxERHkxffCA9Jyt_oMbtJGwY,15844 +numpy/random/tests/data/mt19937-testset-2.csv,sha256=nsBEQNnff-aFjHYK4thjvUK4xSXDSfv5aTbcE59pOkE,15825 +numpy/random/tests/data/pcg64-testset-1.csv,sha256=xB00DpknGUTTCxDr9L6aNo9Hs-sfzEMbUSS4t11TTfE,23839 +numpy/random/tests/data/pcg64-testset-2.csv,sha256=NTdzTKvG2U7_WyU_IoQUtMzU3kEvDH39CgnR6VzhTkw,23845 +numpy/random/tests/data/pcg64dxsm-testset-1.csv,sha256=vNSUT-gXS_oEw_awR3O30ziVO4seNPUv1UIZ01SfVnI,23833 +numpy/random/tests/data/pcg64dxsm-testset-2.csv,sha256=uylS8PU2AIKZ185OC04RBr_OePweGRtvn-dE4YN0yYA,23839 +numpy/random/tests/data/philox-testset-1.csv,sha256=SedRaIy5zFadmk71nKrGxCFZ6BwKz8g1A9-OZp3IkkY,23852 +numpy/random/tests/data/philox-testset-2.csv,sha256=dWECt-sbfvaSiK8-Ygp5AqyjoN5i26VEOrXqg01rk3g,23838 +numpy/random/tests/data/sfc64-testset-1.csv,sha256=iHs6iX6KR8bxGwKk-3tedAdMPz6ZW8slDSUECkAqC8Q,23840 +numpy/random/tests/data/sfc64-testset-2.csv,sha256=FIDIDFCaPZfWUSxsJMAe58hPNmMrU27kCd9FhCEYt_k,23833 +numpy/random/tests/test_direct.py,sha256=6vLpCyeKnAWFEZei7l2YihVLQ0rSewO1hJBWt7A5fyQ,17779 +numpy/random/tests/test_extending.py,sha256=S3Wrzu3di4uBhr-Pxnx5dOPvlBY0FRdZqVX6CC1IN6s,4038 +numpy/random/tests/test_generator_mt19937.py,sha256=35LBwV6TtWPnxhefutxTQmhLzAQ5Ee4YiY8ziDXM-eQ,115477 +numpy/random/tests/test_generator_mt19937_regressions.py,sha256=xGkdz76BMX1EK0QPfabVxpNx9qQ9OC-1ZStWOs6N_M8,6387 +numpy/random/tests/test_random.py,sha256=kEkQs3i7zcpm9MozIRIz1FIx5B6fmXk0QqX0l6l-u_Y,70087 +numpy/random/tests/test_randomstate.py,sha256=DxF7rMUSxaAlL4h1qC3onHcHR7T_6rKWPbr0nJH84nE,85031 +numpy/random/tests/test_randomstate_regression.py,sha256=VucYWIjA7sAquWsalvZMnfkmYLM1O6ysyWnLl931-lA,7917 +numpy/random/tests/test_regression.py,sha256=trntK51UvajOVELiluEO85l64CKSw5nvBSc5SqYyr9w,5439 +numpy/random/tests/test_seed_sequence.py,sha256=GNRJ4jyzrtfolOND3gUWamnbvK6-b_p1bBK_RIG0sfU,3311 +numpy/random/tests/test_smoke.py,sha256=jjNz0aEGD1_oQl9a9UWt6Mz_298alG7KryLT1pgHljw,28183 +numpy/testing/__init__.py,sha256=InpVKoDAzMKO_l_HNcatziW_u1k9_JZze__t2nybrL0,595 +numpy/testing/__init__.pyi,sha256=AhK5NuOpdD-JjIzXOlssE8_iSLyFAAHzyGV_w1BT7vA,1674 +numpy/testing/__pycache__/__init__.cpython-310.pyc,, +numpy/testing/__pycache__/overrides.cpython-310.pyc,, +numpy/testing/__pycache__/print_coercion_tables.cpython-310.pyc,, +numpy/testing/__pycache__/setup.cpython-310.pyc,, +numpy/testing/_private/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/testing/_private/__pycache__/__init__.cpython-310.pyc,, +numpy/testing/_private/__pycache__/extbuild.cpython-310.pyc,, +numpy/testing/_private/__pycache__/utils.cpython-310.pyc,, +numpy/testing/_private/extbuild.py,sha256=nG2dwP4nUmQS3e5eIRinxt0s_f4sxxA1YfohCg-navo,8017 +numpy/testing/_private/utils.py,sha256=3FrSTMi0OdpDODBDoncgiDQzdo5NKA6YVfQ3uKRSQnc,85242 +numpy/testing/_private/utils.pyi,sha256=MMNrvwEeSTYzZFWawSSzHnTFYG-cSAIiID-1FuJ1f8U,10123 +numpy/testing/overrides.py,sha256=u6fcKSBC8HIzMPWKAbdyowU71h2Fx2ekDQxpG5NhIr8,2123 +numpy/testing/print_coercion_tables.py,sha256=ndxOsS4XfrZ4UY_9nqRTCnxhkzgdqcuUHL8nezd7Op4,6180 +numpy/testing/setup.py,sha256=GPKAtTTBRsNW4kmR7NjP6mmBR_GTdpaTvkTm10_VcLg,709 +numpy/testing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/testing/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/testing/tests/__pycache__/test_utils.cpython-310.pyc,, +numpy/testing/tests/test_utils.py,sha256=IDOr-GXuNGlrsb-XzGSYUHXEqcGYJ78p60jOpBqyPM4,55740 +numpy/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/tests/__pycache__/test__all__.cpython-310.pyc,, +numpy/tests/__pycache__/test_ctypeslib.cpython-310.pyc,, +numpy/tests/__pycache__/test_lazyloading.cpython-310.pyc,, +numpy/tests/__pycache__/test_matlib.cpython-310.pyc,, +numpy/tests/__pycache__/test_numpy_config.cpython-310.pyc,, +numpy/tests/__pycache__/test_numpy_version.cpython-310.pyc,, +numpy/tests/__pycache__/test_public_api.cpython-310.pyc,, +numpy/tests/__pycache__/test_reloading.cpython-310.pyc,, +numpy/tests/__pycache__/test_scripts.cpython-310.pyc,, +numpy/tests/__pycache__/test_warnings.cpython-310.pyc,, +numpy/tests/test__all__.py,sha256=L3mCnYPTpzAgNfedVuq9g7xPWbc0c1Pot94k9jZ9NpI,221 +numpy/tests/test_ctypeslib.py,sha256=B06QKeFRgDIEbkEPBy_zYA1H5E2exuhTi7IDkzV8gfo,12257 +numpy/tests/test_lazyloading.py,sha256=YETrYiDLAqLX04K_u5_3NVxAfxDoeguxwkIRfz6qKcY,1162 +numpy/tests/test_matlib.py,sha256=gwhIXrJJo9DiecaGLCHLJBjhx2nVGl6yHq80AOUQSRM,1852 +numpy/tests/test_numpy_config.py,sha256=qHvepgi9oyAbQuZD06k7hpcCC2MYhdzcY6D1iQDPNMI,1241 +numpy/tests/test_numpy_version.py,sha256=A8cXFzp4k-p6J5zkOxlDfDvkoFMxDW2hpTFVXcaQRVo,1479 +numpy/tests/test_public_api.py,sha256=DTq7SO84uBjC2tKPoqX17xazc-SLkTAbQ2fLZwGM2jc,18170 +numpy/tests/test_reloading.py,sha256=QuVaPQulcNLg4Fl31Lw-O89L42KclYCK68n5GVy0PNQ,2354 +numpy/tests/test_scripts.py,sha256=jluCLfG94VM1cuX-5RcLFBli_yaJZpIvmVuMxRKRJrc,1645 +numpy/tests/test_warnings.py,sha256=ZEtXqHI1iyeVeLfVxDcMfN5qw67Ti2u54709hvBG4eY,2284 +numpy/typing/__init__.py,sha256=VoTILNDrUWvZx0LK9_97lBLQFKtSGmDt4QLOH8zYvlo,5234 +numpy/typing/__pycache__/__init__.cpython-310.pyc,, +numpy/typing/__pycache__/mypy_plugin.cpython-310.pyc,, +numpy/typing/__pycache__/setup.cpython-310.pyc,, +numpy/typing/mypy_plugin.py,sha256=24zVk4Ei3qH4Hc3SSz3v0XtIsycTo8HKoY6ilhB_7AQ,6376 +numpy/typing/setup.py,sha256=Cnz9q53w-vJNyE6vYxqYvQXx0pJbrG9quHyz9sqxfek,374 +numpy/typing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/typing/tests/__pycache__/__init__.cpython-310.pyc,, +numpy/typing/tests/__pycache__/test_isfile.cpython-310.pyc,, +numpy/typing/tests/__pycache__/test_runtime.cpython-310.pyc,, +numpy/typing/tests/__pycache__/test_typing.cpython-310.pyc,, +numpy/typing/tests/data/fail/arithmetic.pyi,sha256=4rY_ASCERAl8WCus1RakOe0Aw-8vvjilL29mgdD4lv0,3850 +numpy/typing/tests/data/fail/array_constructors.pyi,sha256=X9y_jUYS17WfYmXW5NwkVudyiR6ouUaAwEh0JRte42o,1089 +numpy/typing/tests/data/fail/array_like.pyi,sha256=OVAlEJZ5k8ZRKt0aGpZQwIjlUGpy0PzOOYqfI-IMqBQ,455 +numpy/typing/tests/data/fail/array_pad.pyi,sha256=57oK0Yp53rtKjjIrRFYLcxa-IfIGhtI-bEem7ggJKwI,132 +numpy/typing/tests/data/fail/arrayprint.pyi,sha256=-Fs9VnQfxyfak008Hq8kJWfB0snA6jGDXZz8ljQnwGE,549 +numpy/typing/tests/data/fail/arrayterator.pyi,sha256=FoU4ahHkJZ67dwWXer5FXLjjjesKKg-w2Jq1X1bHymA,480 +numpy/typing/tests/data/fail/bitwise_ops.pyi,sha256=GN9dVqk4_HFXn7zbRrHzJq_UGRFBccoYVUG1UuE7bXs,515 +numpy/typing/tests/data/fail/char.pyi,sha256=-vgN6EmfQ8VaA4SOZ5Ol9u4-Z7Q5I7G78LmaxZOuZ90,2615 +numpy/typing/tests/data/fail/chararray.pyi,sha256=jrNryZFpr8nxG2IHb9e0x3ranpvJpBy_RDex-WpT5rU,2296 +numpy/typing/tests/data/fail/comparisons.pyi,sha256=U4neWzwwtxG6QXsKlNGJuKXHBtwzYBQOa47_7SKF5Wg,888 +numpy/typing/tests/data/fail/constants.pyi,sha256=YSqNbXdhbdMmYbs7ntH0FCKbnm8IFeqsDlZBqcU43iw,286 +numpy/typing/tests/data/fail/datasource.pyi,sha256=PRT2hixR-mVxr2UILvHa99Dr54EF2h3snJXE-v3rWcc,395 +numpy/typing/tests/data/fail/dtype.pyi,sha256=OAGABqdXNB8gClJFEGMckoycuZcIasMaAlS2RkiKROI,334 +numpy/typing/tests/data/fail/einsumfunc.pyi,sha256=RS7GZqUCT_vEFJoyUx4gZlPO8GNFFNFWidxl-wLyRv0,539 +numpy/typing/tests/data/fail/false_positives.pyi,sha256=Q61qMsSsNCtmO0EMRxHj5Z7RYTyrELVpkzfJY5eK8Z0,366 +numpy/typing/tests/data/fail/flatiter.pyi,sha256=qLM4qm7gvJtEZ0rTHcyasUzoP5JbX4FREtqV3g1w6Lo,843 +numpy/typing/tests/data/fail/fromnumeric.pyi,sha256=FH2mjkgtCbA9soqlJRhYN7IIfRRrUL1i9mwqcbYKZSc,5591 +numpy/typing/tests/data/fail/histograms.pyi,sha256=yAPVt0rYTwtxnigoGT-u7hhKCE9iYxsXc24x2HGBrmA,367 +numpy/typing/tests/data/fail/index_tricks.pyi,sha256=moINir9iQoi6Q1ZuVg5BuSB9hSBtbg_uzv-Qm_lLYZk,509 +numpy/typing/tests/data/fail/lib_function_base.pyi,sha256=6y9T773CBLX-jUry1sCQGVuKVKM2wMuQ56Ni5V5j4Dw,2081 +numpy/typing/tests/data/fail/lib_polynomial.pyi,sha256=Ur7Y4iZX6WmoH5SDm0ePi8C8LPsuPs2Yr7g7P5O613g,899 +numpy/typing/tests/data/fail/lib_utils.pyi,sha256=VFpE6_DisvlDByyp1PiNPJEe5IcZp8cH0FlAJyoZipo,276 +numpy/typing/tests/data/fail/lib_version.pyi,sha256=7-ZJDZwDcB-wzpMN8TeYtZAgaqc7xnQ8Dnx2ISiX2Ts,158 +numpy/typing/tests/data/fail/linalg.pyi,sha256=yDd05aK1dI37RPt3pD2eJYo4dZFaT2yB1PEu3K0y9Tg,1322 +numpy/typing/tests/data/fail/memmap.pyi,sha256=HSTCQYNuW1Y6X1Woj361pN4rusSPs4oDCXywqk20yUo,159 +numpy/typing/tests/data/fail/modules.pyi,sha256=_ek4zKcdP-sIh_f-IDY0tP-RbLORKCSWelM9AOYxsyA,670 +numpy/typing/tests/data/fail/multiarray.pyi,sha256=XCdBxufNhR8ZtG8UMzk8nt9_NC5gJTKP9-xTqKO_K9I,1693 +numpy/typing/tests/data/fail/ndarray.pyi,sha256=YnjXy16RHs_esKelMjB07865CQ7gLyQnXhnitq5Kv5c,405 +numpy/typing/tests/data/fail/ndarray_misc.pyi,sha256=w-10xTDDWoff9Lq0dBO-jBeiBR-XjCz2qmes0dLx238,1372 +numpy/typing/tests/data/fail/nditer.pyi,sha256=w7emjnOxnf3NcvLktNLlke6Cuivn2gU3sVmGCfbG6rw,325 +numpy/typing/tests/data/fail/nested_sequence.pyi,sha256=em4GZwLDFE0QSxxg081wVwhh-Dmtkn8f7wThI0DiXVs,427 +numpy/typing/tests/data/fail/npyio.pyi,sha256=56QuHo9SvVR3Uhzl6gQZncCpX575Gy5wugjMICh20m0,620 +numpy/typing/tests/data/fail/numerictypes.pyi,sha256=fevH9x80CafYkiyBJ7LMLVl6GyTvQrZ34trBu6O8TtM,276 +numpy/typing/tests/data/fail/random.pyi,sha256=p5WsUGyOL-MGIeALh9Y0dVhYSRQLaUwMdjXc3G6C_7Q,2830 +numpy/typing/tests/data/fail/rec.pyi,sha256=Ws3TyesnoQjt7Q0wwtpShRDJmZCs2jjP17buFMomVGA,704 +numpy/typing/tests/data/fail/scalars.pyi,sha256=o91BwSfzPTczYVtbXsirqQUoUoYP1C_msGjc2GYsV04,2952 +numpy/typing/tests/data/fail/shape_base.pyi,sha256=Y_f4buHtX2Q2ZA4kaDTyR8LErlPXTzCB_-jBoScGh_Q,152 +numpy/typing/tests/data/fail/stride_tricks.pyi,sha256=IjA0Xrnx0lG3m07d1Hjbhtyo1Te5cXgjgr5fLUo4LYQ,315 +numpy/typing/tests/data/fail/testing.pyi,sha256=e7b5GKTWCtKGoB8z2a8edsW0Xjl1rMheALsvzEJjlCw,1370 +numpy/typing/tests/data/fail/twodim_base.pyi,sha256=ZqbRJfy5S_pW3fFLuomy4L5SBNqj6Nklexg9KDTo65c,899 +numpy/typing/tests/data/fail/type_check.pyi,sha256=CIyI0j0Buxv0QgCvNG2urjaKpoIZ-ZNawC2m6NzGlbo,379 +numpy/typing/tests/data/fail/ufunc_config.pyi,sha256=ukA0xwfJHLoGfoOIpWIN-91wj-DG8oaIjYbO72ymjg4,733 +numpy/typing/tests/data/fail/ufunclike.pyi,sha256=lbxjJyfARmt_QK1HxhxFxvwQTqCEZwJ9I53Wp8X3KIY,679 +numpy/typing/tests/data/fail/ufuncs.pyi,sha256=YaDTL7QLmGSUxE6JVMzpOlZTjHWrgbOo0UIlkX-6ZQk,1347 +numpy/typing/tests/data/fail/warnings_and_errors.pyi,sha256=PrbYDFI7IGN3Gf0OPBkVfefzQs4AXHwDQ495pvrX3RY,174 +numpy/typing/tests/data/misc/extended_precision.pyi,sha256=bS8bBeCFqjgtOiy-8_y39wfa7rwhdjLz2Vmo-RXAYD4,884 +numpy/typing/tests/data/mypy.ini,sha256=Ynv1VSx_kXTD2mFC3ZpgEFuCOg1F2VJXxPk0dxUnF2M,108 +numpy/typing/tests/data/pass/__pycache__/arithmetic.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/array_constructors.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/array_like.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/arrayprint.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/arrayterator.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/bitwise_ops.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/comparisons.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/dtype.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/einsumfunc.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/flatiter.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/fromnumeric.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/index_tricks.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/lib_utils.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/lib_version.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/literal.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/mod.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/modules.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/multiarray.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/ndarray_conversion.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/ndarray_misc.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/ndarray_shape_manipulation.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/numeric.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/numerictypes.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/random.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/scalars.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/simple.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/simple_py3.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/ufunc_config.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/ufunclike.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/ufuncs.cpython-310.pyc,, +numpy/typing/tests/data/pass/__pycache__/warnings_and_errors.cpython-310.pyc,, +numpy/typing/tests/data/pass/arithmetic.py,sha256=2z3dmuysQQmiPz8x0bg8SOOKW62mVJn97uMa9T0L7Vk,7455 +numpy/typing/tests/data/pass/array_constructors.py,sha256=3GrhfBcmWX53pJHD0NvhXjwr2-uNKREbR1I9WCcZ7rI,2419 +numpy/typing/tests/data/pass/array_like.py,sha256=ce_IVubBd7J6FkSpJmD7qMlRLuwmiidhOqhYfZb16Wo,916 +numpy/typing/tests/data/pass/arrayprint.py,sha256=y_KkuLz1uM7pv53qfq7GQOuud4LoXE3apK1wtARdVyM,766 +numpy/typing/tests/data/pass/arrayterator.py,sha256=FqcpKdUQBQ0FazHFxr9MsLEZG-jnJVGKWZX2owRr4DQ,393 +numpy/typing/tests/data/pass/bitwise_ops.py,sha256=UnmxVr9HwI8ifdrutGm_u3EZU4iOOPQhrOku7hTaH0c,970 +numpy/typing/tests/data/pass/comparisons.py,sha256=nTE-fvraLK6xTZcP4uPV02wOShzYKWDaoapx35AeDOY,2992 +numpy/typing/tests/data/pass/dtype.py,sha256=MqDKC6Ywv6jNkWsR8rdLuabzHUco5w1OylDHEdxve_I,1069 +numpy/typing/tests/data/pass/einsumfunc.py,sha256=eXj5L5MWPtQHgrHPsJ36qqrmBHqct9UoujjJCvHnF1k,1370 +numpy/typing/tests/data/pass/flatiter.py,sha256=0BnbuLMBC7MQlprNZ0QhNSscfYwPhEhXOhWoyiRACWU,174 +numpy/typing/tests/data/pass/fromnumeric.py,sha256=Xd_nJVVDoONdztUX8ddgo7EXJ2FD8AX51MO_Yujnmog,3742 +numpy/typing/tests/data/pass/index_tricks.py,sha256=oaFD9vY01_RI5OkrXt-xTk1n_dd-SpuPp-eZ58XR3c8,1492 +numpy/typing/tests/data/pass/lib_utils.py,sha256=sDQCjHVGUwct0RQqAtH5_16y241siSY4bXKZRsuJ8xA,434 +numpy/typing/tests/data/pass/lib_version.py,sha256=HnuGOx7tQA_bcxFIJ3dRoMAR0fockxg4lGqQ4g7LGIw,299 +numpy/typing/tests/data/pass/literal.py,sha256=DLzdWHD6ttW4S0NEvGQbsH_UEJjhZyhvO4OXJjoyvZQ,1331 +numpy/typing/tests/data/pass/mod.py,sha256=HB9aK4_wGJbc44tomaoroNy0foIL5cI9KIjknvMTbkk,1578 +numpy/typing/tests/data/pass/modules.py,sha256=t0KJxYWbrWd7HbbgIDFb3LAhJBiNNb6QPjjFDAgC2mU,576 +numpy/typing/tests/data/pass/multiarray.py,sha256=MxHax6l94yqlTVZleAqG77ILEbW6wU5osPcHzxJ85ns,1331 +numpy/typing/tests/data/pass/ndarray_conversion.py,sha256=yPgzXG6paY1uF_z-QyHYrcmrZvhX7qtvTUh7ANLseCA,1626 +numpy/typing/tests/data/pass/ndarray_misc.py,sha256=z3mucbn9fLM1gxmbUhWlp2lcrOv4zFjqZFze0caE2EA,2715 +numpy/typing/tests/data/pass/ndarray_shape_manipulation.py,sha256=37eYwMNqMLwanIW9-63hrokacnSz2K_qtPUlkdpsTjo,640 +numpy/typing/tests/data/pass/numeric.py,sha256=SdnsD5zv0wm8T2hnIylyS14ig2McSz6rG9YslckbNQ4,1490 +numpy/typing/tests/data/pass/numerictypes.py,sha256=r0_s-a0-H2MdWIn4U4P6W9RQO0V1xrDusgodHNZeIYM,750 +numpy/typing/tests/data/pass/random.py,sha256=uJCnzlsOn9hr_G1TpHLdsweJI4EdhUSEQ4dxROPjqAs,61881 +numpy/typing/tests/data/pass/scalars.py,sha256=En0adCZAwEigZrzdQ0JQwDEmrS0b-DMd1vvjkFcvwo8,3479 +numpy/typing/tests/data/pass/simple.py,sha256=HmAfCOdZBWQF211YaZFrIGisMgu5FzTELApKny08n3Y,2676 +numpy/typing/tests/data/pass/simple_py3.py,sha256=HuLrc5aphThQkLjU2_19KgGFaXwKOfSzXe0p2xMm8ZI,96 +numpy/typing/tests/data/pass/ufunc_config.py,sha256=_M8v-QWAeT1-2MkfSeAbNl_ZwyPvYfPTsLl6c1X8d_w,1204 +numpy/typing/tests/data/pass/ufunclike.py,sha256=Gve6cJ2AT3TAwOjUOQQDIUnqsRCGYq70_tv_sgODiiA,1039 +numpy/typing/tests/data/pass/ufuncs.py,sha256=xGuKuqPetUTS4io5YDHaki5nbYRu-wC29SGU32tzVIg,462 +numpy/typing/tests/data/pass/warnings_and_errors.py,sha256=Pcg-QWfY4PAhTKyehae8q6LhtbUABxa2Ye63-3h1f4w,150 +numpy/typing/tests/data/reveal/arithmetic.pyi,sha256=Ndmi_IFAl8z28RHsYTbOouf-B5FH91x_9ky-JwsdXVg,19765 +numpy/typing/tests/data/reveal/array_constructors.pyi,sha256=DcT8Z2rEpqYfjXySBejk8cGOUidUmizZGE5ZEy7r14E,10600 +numpy/typing/tests/data/reveal/arraypad.pyi,sha256=Q1pcU4B3eRsw5jsv-S0MsEfNUbp_4aMdO_o3n0rtA2A,776 +numpy/typing/tests/data/reveal/arrayprint.pyi,sha256=YyzzkL-wj4Rs-fdo3brpoaWtb5g3yk4Vn2HKu5KRo4w,876 +numpy/typing/tests/data/reveal/arraysetops.pyi,sha256=ApCFQcZzQ08zV32SJ86Xyv_7jazl3XKMmJmULtNquJ8,4155 +numpy/typing/tests/data/reveal/arrayterator.pyi,sha256=TF_1eneHoT0v9HqS9dKc5Xiv3iY3E330GR1RNcJ7s2Q,1111 +numpy/typing/tests/data/reveal/bitwise_ops.pyi,sha256=nRkyUGrBB_Es7TKyDxS_s3u2dFgBfzjocInI9Ea-J10,3919 +numpy/typing/tests/data/reveal/char.pyi,sha256=M_iTa9Pn8F7jQ1k6RN9KvbhEn00g7UYJZ5PV57ikcZM,7289 +numpy/typing/tests/data/reveal/chararray.pyi,sha256=O0EfwnKc3W1Fnx1c7Yotb1O84kVMuqJLlMBXd2duvjI,6093 +numpy/typing/tests/data/reveal/comparisons.pyi,sha256=huaf-seaF5ndTqfoaBfPtMMkOYovq7ibJl5-CRoQW7s,7468 +numpy/typing/tests/data/reveal/constants.pyi,sha256=P9vFEMkPpJ5KeUnzqPOuyHlh3zAFl9lzB4WxyB2od7A,1949 +numpy/typing/tests/data/reveal/ctypeslib.pyi,sha256=-Pk2rLEGCzz3B_y8Mu10JSVA8gPFztl5fV1dspPzqig,4727 +numpy/typing/tests/data/reveal/datasource.pyi,sha256=e8wjn60tO5EdnkBF34JrZT5XvdyW7kRWD2abtgr6qUg,671 +numpy/typing/tests/data/reveal/dtype.pyi,sha256=TKrYyxMu5IGobs0SDTIRcPuWsZ5X7zMYB4pmUlTTJxA,2872 +numpy/typing/tests/data/reveal/einsumfunc.pyi,sha256=pbtSfzIWUJRkDpe2riHBlvFlNSC3CqVM-SbYtBgX9H0,2044 +numpy/typing/tests/data/reveal/emath.pyi,sha256=-muNpWOv_niIn-zS3gUnFO4qBZAouNlVGue2x1L5Ris,2423 +numpy/typing/tests/data/reveal/false_positives.pyi,sha256=AplTmZV7TS7nivU8vegbstMN5MdMv4U0JJdZ4IeeA5M,482 +numpy/typing/tests/data/reveal/fft.pyi,sha256=ReQ9qn5frvJEy-g0RWpUGlPBntUS1cFSIu6WfPotHzE,1749 +numpy/typing/tests/data/reveal/flatiter.pyi,sha256=e1OQsVxQpgyfqMNw2puUTATl-w3swvdknlctAiWxf_E,882 +numpy/typing/tests/data/reveal/fromnumeric.pyi,sha256=PNtGQR1VmGk_xNbd0eP7k7B2oNCMBz2XOJ17-_SdE5M,12101 +numpy/typing/tests/data/reveal/getlimits.pyi,sha256=nUGOMFpWj3pMgqLy6ZbR7A4G2q7iLIl5zEFBGf-Qcfw,1592 +numpy/typing/tests/data/reveal/histograms.pyi,sha256=MxKWoa7UoJRRLim53H6OoyYfz87P3_9YUXGYPTknGVQ,1303 +numpy/typing/tests/data/reveal/index_tricks.pyi,sha256=HpD7lU7hcyDoLdZbeqskPXnX7KYwPtll7uJKYUzrlE8,3177 +numpy/typing/tests/data/reveal/lib_function_base.pyi,sha256=eSiSZUlmPXqVPKknM7GcEv76BDgj0IJRu3FXcZXpmqc,8318 +numpy/typing/tests/data/reveal/lib_polynomial.pyi,sha256=TOzOdMPDqveDv3vDKSjtq6RRvN-j_s2J7aud2ySDAB0,5986 +numpy/typing/tests/data/reveal/lib_utils.pyi,sha256=_zj7WGYGYMFXAHLK-F11aeFfDvjRvFARUjoXhbXn8V0,1049 +numpy/typing/tests/data/reveal/lib_version.pyi,sha256=UCioUeykot8-nWL6goKxZnKZxtgB4lFEi9wdN_xyF1U,672 +numpy/typing/tests/data/reveal/linalg.pyi,sha256=LPaY-RyYL7Xt3djCgNaWEgI8beI9Eo_XnvOwi6Y7-eo,4877 +numpy/typing/tests/data/reveal/matrix.pyi,sha256=ciJXsn5v2O1IZ3VEn5Ilp8-40NTQokfrOOgVXMFsvLo,2922 +numpy/typing/tests/data/reveal/memmap.pyi,sha256=A5PovMzjRp2zslF1vw3TdTQjj4Y0dIEJ__HDBV_svGM,842 +numpy/typing/tests/data/reveal/mod.pyi,sha256=-CNWft2jQGSdrO8dYRgwbl7OhL3a78Zo60JVmiY-gQI,5666 +numpy/typing/tests/data/reveal/modules.pyi,sha256=0WPq7A-aqWkJsV-IA1_7dFNCcxBacj1AWExaXbXErG4,1958 +numpy/typing/tests/data/reveal/multiarray.pyi,sha256=6MvfNKihK-oN6QwG9HFNelgheo4lnL0FCrmIF_qxdoA,5326 +numpy/typing/tests/data/reveal/nbit_base_example.pyi,sha256=DRUMGatQvQXTuovKEMF4dzazIU6it6FU53LkOEo2vNo,657 +numpy/typing/tests/data/reveal/ndarray_conversion.pyi,sha256=BfjQD8U756l4gOfY0LD47HhDRxbq0yCFfEFKvbXs7Rs,1791 +numpy/typing/tests/data/reveal/ndarray_misc.pyi,sha256=0EN-a47Msn4pZgKVdD-GrXCCmt-oxjlov5rszchBmOI,7126 +numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi,sha256=QDQ9g6l-e73pTJp-Dosiynb-okbqi91D4KirjhIjcv4,1233 +numpy/typing/tests/data/reveal/nditer.pyi,sha256=VFXnT75BgWSUpb-dD-q5cZkfeOqsk-x9cH626g9FWT4,2021 +numpy/typing/tests/data/reveal/nested_sequence.pyi,sha256=IQyRlXduk-ZEakOtoliMLCqNgGbeg0mzZf-a-a3Gq_0,734 +numpy/typing/tests/data/reveal/npyio.pyi,sha256=YXagt2J-1suu5WXZ_si5NuJf7sHj_7NlaSLqQkam1Po,4209 +numpy/typing/tests/data/reveal/numeric.pyi,sha256=aJKnav-X45tjSFfgGD4iCetwEFcJXdNgU7valktjiCg,6160 +numpy/typing/tests/data/reveal/numerictypes.pyi,sha256=-YQRhwjBjsFJHjpGCRqzafNnKDdsmbBHbmPwccP0pLI,2487 +numpy/typing/tests/data/reveal/random.pyi,sha256=s6T074ZIpGAUqHnA-yAlozTLvt7PNBjCBqd-nGMqWGg,104091 +numpy/typing/tests/data/reveal/rec.pyi,sha256=DbRVk6lc7-3qPe-7Q26tUWpdaH9B4UVoQSYrRGJUo1Q,3858 +numpy/typing/tests/data/reveal/scalars.pyi,sha256=Qn3B3rsqSN397Jh25xs4odt2pfCQtWkoJe-e0-oX8d4,4790 +numpy/typing/tests/data/reveal/shape_base.pyi,sha256=YjiVukrK6OOydvopOaOmeAIIa0YQ2hn9_I_-FyYkHVU,2427 +numpy/typing/tests/data/reveal/stride_tricks.pyi,sha256=EBZR8gSP385nhotwJ3GH9DOUD2q5nUEYbXfhLo5xrPo,1542 +numpy/typing/tests/data/reveal/testing.pyi,sha256=_WOAj_t5SWYiqN0KG26Mza8RvaD3WAa7rFUlgksjLms,8611 +numpy/typing/tests/data/reveal/twodim_base.pyi,sha256=ZdNVo2HIJcx8iF9PA-z5W3Bs0hWM2nlVdbhLuAQlljM,3132 +numpy/typing/tests/data/reveal/type_check.pyi,sha256=yZSp50TtvPqv_PN7zmVcNOVUTUXMNYFGcguMNj25E9Y,3044 +numpy/typing/tests/data/reveal/ufunc_config.pyi,sha256=buwSvat3SVFAFl5k8TL6Mgpi32o6hHZYZ2Lpn6AHdEU,1327 +numpy/typing/tests/data/reveal/ufunclike.pyi,sha256=V_gLcZVrTXJ21VkUMwA0HyxUgA1r6OzjsdJegaKL2GE,1329 +numpy/typing/tests/data/reveal/ufuncs.pyi,sha256=VnwYr5KT_FLKfc0wV7dtNz7bNtaC9VIQt-oz56Hb5EE,2798 +numpy/typing/tests/data/reveal/warnings_and_errors.pyi,sha256=ImMlPt2PQBtX8Qf1EZFmLjNWm8fPE6IWQ_deaq_-85s,538 +numpy/typing/tests/test_isfile.py,sha256=BhKZs4-LrhFUfKjcG0yelySjE6ZITMxGIBYWGDHMRb8,864 +numpy/typing/tests/test_runtime.py,sha256=2qu8JEliITnZCBJ_QJpohacj_OQ08o73ixS2w2ooNXI,3275 +numpy/typing/tests/test_typing.py,sha256=Da1ZOFjtPh_Mvb5whpI-okBJdgLOAfJtJNyG6leGFoQ,8743 +numpy/version.py,sha256=OTLnSh0NGfWyL8VrnIj0Ndt_KZOTl1Z-kD9Cf-jRMmY,216 diff --git a/shared/package-files/d1/d1077656f59bb84a73d5c477a4adafdd8761d037a58e4b5b9fed8f8dbb2275f9/blob b/shared/package-files/d1/d1077656f59bb84a73d5c477a4adafdd8761d037a58e4b5b9fed8f8dbb2275f9/blob new file mode 100644 index 0000000000000000000000000000000000000000..b29e31e16c0f495fe22ce62e6b551364e78151c1 --- /dev/null +++ b/shared/package-files/d1/d1077656f59bb84a73d5c477a4adafdd8761d037a58e4b5b9fed8f8dbb2275f9/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1077656f59bb84a73d5c477a4adafdd8761d037a58e4b5b9fed8f8dbb2275f9 +size 1170754 diff --git a/shared/package-files/d1/d10ac70fd4d82a5499b8ef1dae75376d4149ad2bbcbf94a772ab6445258b8c63/blob b/shared/package-files/d1/d10ac70fd4d82a5499b8ef1dae75376d4149ad2bbcbf94a772ab6445258b8c63/blob new file mode 100644 index 0000000000000000000000000000000000000000..817acf76091dfba2dba40487ca7735e307c0fc15 --- /dev/null +++ b/shared/package-files/d1/d10ac70fd4d82a5499b8ef1dae75376d4149ad2bbcbf94a772ab6445258b8c63/blob @@ -0,0 +1,108 @@ +""" +This module implements a method to find +Euler-Lagrange Equations for given Lagrangian. +""" +from itertools import combinations_with_replacement +from sympy.core.function import (Derivative, Function, diff) +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy.utilities.iterables import iterable + + +def euler_equations(L, funcs=(), vars=()): + r""" + Find the Euler-Lagrange equations [1]_ for a given Lagrangian. + + Parameters + ========== + + L : Expr + The Lagrangian that should be a function of the functions listed + in the second argument and their derivatives. + + For example, in the case of two functions $f(x,y)$, $g(x,y)$ and + two independent variables $x$, $y$ the Lagrangian has the form: + + .. math:: L\left(f(x,y),g(x,y),\frac{\partial f(x,y)}{\partial x}, + \frac{\partial f(x,y)}{\partial y}, + \frac{\partial g(x,y)}{\partial x}, + \frac{\partial g(x,y)}{\partial y},x,y\right) + + In many cases it is not necessary to provide anything, except the + Lagrangian, it will be auto-detected (and an error raised if this + cannot be done). + + funcs : Function or an iterable of Functions + The functions that the Lagrangian depends on. The Euler equations + are differential equations for each of these functions. + + vars : Symbol or an iterable of Symbols + The Symbols that are the independent variables of the functions. + + Returns + ======= + + eqns : list of Eq + The list of differential equations, one for each function. + + Examples + ======== + + >>> from sympy import euler_equations, Symbol, Function + >>> x = Function('x') + >>> t = Symbol('t') + >>> L = (x(t).diff(t))**2/2 - x(t)**2/2 + >>> euler_equations(L, x(t), t) + [Eq(-x(t) - Derivative(x(t), (t, 2)), 0)] + >>> u = Function('u') + >>> x = Symbol('x') + >>> L = (u(t, x).diff(t))**2/2 - (u(t, x).diff(x))**2/2 + >>> euler_equations(L, u(t, x), [t, x]) + [Eq(-Derivative(u(t, x), (t, 2)) + Derivative(u(t, x), (x, 2)), 0)] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Lagrange_equation + + """ + + funcs = tuple(funcs) if iterable(funcs) else (funcs,) + + if not funcs: + funcs = tuple(L.atoms(Function)) + else: + for f in funcs: + if not isinstance(f, Function): + raise TypeError('Function expected, got: %s' % f) + + vars = tuple(vars) if iterable(vars) else (vars,) + + if not vars: + vars = funcs[0].args + else: + vars = tuple(sympify(var) for var in vars) + + if not all(isinstance(v, Symbol) for v in vars): + raise TypeError('Variables are not symbols, got %s' % vars) + + for f in funcs: + if not vars == f.args: + raise ValueError("Variables %s do not match args: %s" % (vars, f)) + + order = max([len(d.variables) for d in L.atoms(Derivative) + if d.expr in funcs] + [0]) + + eqns = [] + for f in funcs: + eq = diff(L, f) + for i in range(1, order + 1): + for p in combinations_with_replacement(vars, i): + eq = eq + S.NegativeOne**i*diff(L, diff(f, *p), *p) + new_eq = Eq(eq, 0) + if isinstance(new_eq, Eq): + eqns.append(new_eq) + + return eqns diff --git a/shared/package-files/d1/d10d4526a84c2480a0b962fb1dbad12b0c02caa7d95132cded6c4e79e29adbed/blob b/shared/package-files/d1/d10d4526a84c2480a0b962fb1dbad12b0c02caa7d95132cded6c4e79e29adbed/blob new file mode 100644 index 0000000000000000000000000000000000000000..2858a49125998d082280418af338d8f15529c843 --- /dev/null +++ b/shared/package-files/d1/d10d4526a84c2480a0b962fb1dbad12b0c02caa7d95132cded6c4e79e29adbed/blob @@ -0,0 +1,4581 @@ +import math +import warnings +import threading +from collections import namedtuple + +import numpy as np +from numpy import (isscalar, r_, log, around, unique, asarray, zeros, + arange, sort, amin, amax, sqrt, array, + pi, exp, ravel, count_nonzero) + +from scipy import optimize, special, interpolate, stats +from scipy._lib._bunch import _make_tuple_bunch +from scipy._lib._util import _rename_parameter, _contains_nan, _get_nan + +from scipy._lib._array_api import ( + array_namespace, + xp_size, + xp_moveaxis_to_end, + xp_vector_norm, +) + +from ._ansari_swilk_statistics import gscale, swilk +from . import _stats_py, _wilcoxon +from ._fit import FitResult +from ._stats_py import (find_repeats, _get_pvalue, SignificanceResult, # noqa:F401 + _SimpleNormal, _SimpleChi2) +from .contingency import chi2_contingency +from . import distributions +from ._distn_infrastructure import rv_generic +from ._axis_nan_policy import _axis_nan_policy_factory, _broadcast_arrays + + +__all__ = ['mvsdist', + 'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot', + 'boxcox_llf', 'boxcox', 'boxcox_normmax', 'boxcox_normplot', + 'shapiro', 'anderson', 'ansari', 'bartlett', 'levene', + 'fligner', 'mood', 'wilcoxon', 'median_test', + 'circmean', 'circvar', 'circstd', 'anderson_ksamp', + 'yeojohnson_llf', 'yeojohnson', 'yeojohnson_normmax', + 'yeojohnson_normplot', 'directional_stats', + 'false_discovery_control' + ] + + +Mean = namedtuple('Mean', ('statistic', 'minmax')) +Variance = namedtuple('Variance', ('statistic', 'minmax')) +Std_dev = namedtuple('Std_dev', ('statistic', 'minmax')) + + +def bayes_mvs(data, alpha=0.90): + r""" + Bayesian confidence intervals for the mean, var, and std. + + Parameters + ---------- + data : array_like + Input data, if multi-dimensional it is flattened to 1-D by `bayes_mvs`. + Requires 2 or more data points. + alpha : float, optional + Probability that the returned confidence interval contains + the true parameter. + + Returns + ------- + mean_cntr, var_cntr, std_cntr : tuple + The three results are for the mean, variance and standard deviation, + respectively. Each result is a tuple of the form:: + + (center, (lower, upper)) + + with ``center`` the mean of the conditional pdf of the value given the + data, and ``(lower, upper)`` a confidence interval, centered on the + median, containing the estimate to a probability ``alpha``. + + See Also + -------- + mvsdist + + Notes + ----- + Each tuple of mean, variance, and standard deviation estimates represent + the (center, (lower, upper)) with center the mean of the conditional pdf + of the value given the data and (lower, upper) is a confidence interval + centered on the median, containing the estimate to a probability + ``alpha``. + + Converts data to 1-D and assumes all data has the same mean and variance. + Uses Jeffrey's prior for variance and std. + + Equivalent to ``tuple((x.mean(), x.interval(alpha)) for x in mvsdist(dat))`` + + References + ---------- + T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and + standard-deviation from data", https://scholarsarchive.byu.edu/facpub/278, + 2006. + + Examples + -------- + First a basic example to demonstrate the outputs: + + >>> from scipy import stats + >>> data = [6, 9, 12, 7, 8, 8, 13] + >>> mean, var, std = stats.bayes_mvs(data) + >>> mean + Mean(statistic=9.0, minmax=(7.103650222612533, 10.896349777387467)) + >>> var + Variance(statistic=10.0, minmax=(3.176724206, 24.45910382)) + >>> std + Std_dev(statistic=2.9724954732045084, + minmax=(1.7823367265645143, 4.945614605014631)) + + Now we generate some normally distributed random data, and get estimates of + mean and standard deviation with 95% confidence intervals for those + estimates: + + >>> n_samples = 100000 + >>> data = stats.norm.rvs(size=n_samples) + >>> res_mean, res_var, res_std = stats.bayes_mvs(data, alpha=0.95) + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> ax.hist(data, bins=100, density=True, label='Histogram of data') + >>> ax.vlines(res_mean.statistic, 0, 0.5, colors='r', label='Estimated mean') + >>> ax.axvspan(res_mean.minmax[0],res_mean.minmax[1], facecolor='r', + ... alpha=0.2, label=r'Estimated mean (95% limits)') + >>> ax.vlines(res_std.statistic, 0, 0.5, colors='g', label='Estimated scale') + >>> ax.axvspan(res_std.minmax[0],res_std.minmax[1], facecolor='g', alpha=0.2, + ... label=r'Estimated scale (95% limits)') + + >>> ax.legend(fontsize=10) + >>> ax.set_xlim([-4, 4]) + >>> ax.set_ylim([0, 0.5]) + >>> plt.show() + + """ + m, v, s = mvsdist(data) + if alpha >= 1 or alpha <= 0: + raise ValueError(f"0 < alpha < 1 is required, but {alpha=} was given.") + + m_res = Mean(m.mean(), m.interval(alpha)) + v_res = Variance(v.mean(), v.interval(alpha)) + s_res = Std_dev(s.mean(), s.interval(alpha)) + + return m_res, v_res, s_res + + +def mvsdist(data): + """ + 'Frozen' distributions for mean, variance, and standard deviation of data. + + Parameters + ---------- + data : array_like + Input array. Converted to 1-D using ravel. + Requires 2 or more data-points. + + Returns + ------- + mdist : "frozen" distribution object + Distribution object representing the mean of the data. + vdist : "frozen" distribution object + Distribution object representing the variance of the data. + sdist : "frozen" distribution object + Distribution object representing the standard deviation of the data. + + See Also + -------- + bayes_mvs + + Notes + ----- + The return values from ``bayes_mvs(data)`` is equivalent to + ``tuple((x.mean(), x.interval(0.90)) for x in mvsdist(data))``. + + In other words, calling ``.mean()`` and ``.interval(0.90)`` + on the three distribution objects returned from this function will give + the same results that are returned from `bayes_mvs`. + + References + ---------- + T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and + standard-deviation from data", https://scholarsarchive.byu.edu/facpub/278, + 2006. + + Examples + -------- + >>> from scipy import stats + >>> data = [6, 9, 12, 7, 8, 8, 13] + >>> mean, var, std = stats.mvsdist(data) + + We now have frozen distribution objects "mean", "var" and "std" that we can + examine: + + >>> mean.mean() + 9.0 + >>> mean.interval(0.95) + (6.6120585482655692, 11.387941451734431) + >>> mean.std() + 1.1952286093343936 + + """ + x = ravel(data) + n = len(x) + if n < 2: + raise ValueError("Need at least 2 data-points.") + xbar = x.mean() + C = x.var() + if n > 1000: # gaussian approximations for large n + mdist = distributions.norm(loc=xbar, scale=math.sqrt(C / n)) + sdist = distributions.norm(loc=math.sqrt(C), scale=math.sqrt(C / (2. * n))) + vdist = distributions.norm(loc=C, scale=math.sqrt(2.0 / n) * C) + else: + nm1 = n - 1 + fac = n * C / 2. + val = nm1 / 2. + mdist = distributions.t(nm1, loc=xbar, scale=math.sqrt(C / nm1)) + sdist = distributions.gengamma(val, -2, scale=math.sqrt(fac)) + vdist = distributions.invgamma(val, scale=fac) + return mdist, vdist, sdist + + +@_axis_nan_policy_factory( + lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, default_axis=None +) +def kstat(data, n=2, *, axis=None): + r""" + Return the `n` th k-statistic ( ``1<=n<=4`` so far). + + The `n` th k-statistic ``k_n`` is the unique symmetric unbiased estimator of the + `n` th cumulant :math:`\kappa_n` [1]_ [2]_. + + Parameters + ---------- + data : array_like + Input array. + n : int, {1, 2, 3, 4}, optional + Default is equal to 2. + axis : int or None, default: None + If an int, the axis of the input along which to compute the statistic. + The statistic of each axis-slice (e.g. row) of the input will appear + in a corresponding element of the output. If ``None``, the input will + be raveled before computing the statistic. + + Returns + ------- + kstat : float + The `n` th k-statistic. + + See Also + -------- + kstatvar : Returns an unbiased estimator of the variance of the k-statistic + moment : Returns the n-th central moment about the mean for a sample. + + Notes + ----- + For a sample size :math:`n`, the first few k-statistics are given by + + .. math:: + + k_1 &= \frac{S_1}{n}, \\ + k_2 &= \frac{nS_2 - S_1^2}{n(n-1)}, \\ + k_3 &= \frac{2S_1^3 - 3nS_1S_2 + n^2S_3}{n(n-1)(n-2)}, \\ + k_4 &= \frac{-6S_1^4 + 12nS_1^2S_2 - 3n(n-1)S_2^2 - 4n(n+1)S_1S_3 + + n^2(n+1)S_4}{n (n-1)(n-2)(n-3)}, + + where + + .. math:: + + S_r \equiv \sum_{i=1}^n X_i^r, + + and :math:`X_i` is the :math:`i` th data point. + + References + ---------- + .. [1] http://mathworld.wolfram.com/k-Statistic.html + + .. [2] http://mathworld.wolfram.com/Cumulant.html + + Examples + -------- + >>> from scipy import stats + >>> from numpy.random import default_rng + >>> rng = default_rng() + + As sample size increases, `n`-th moment and `n`-th k-statistic converge to the + same number (although they aren't identical). In the case of the normal + distribution, they converge to zero. + + >>> for i in range(2,8): + ... x = rng.normal(size=10**i) + ... m, k = stats.moment(x, 3), stats.kstat(x, 3) + ... print(f"{i=}: {m=:.3g}, {k=:.3g}, {(m-k)=:.3g}") + i=2: m=-0.631, k=-0.651, (m-k)=0.0194 # random + i=3: m=0.0282, k=0.0283, (m-k)=-8.49e-05 + i=4: m=-0.0454, k=-0.0454, (m-k)=1.36e-05 + i=6: m=7.53e-05, k=7.53e-05, (m-k)=-2.26e-09 + i=7: m=0.00166, k=0.00166, (m-k)=-4.99e-09 + i=8: m=-2.88e-06 k=-2.88e-06, (m-k)=8.63e-13 + """ + xp = array_namespace(data) + data = xp.asarray(data) + if n > 4 or n < 1: + raise ValueError("k-statistics only supported for 1<=n<=4") + n = int(n) + if axis is None: + data = xp.reshape(data, (-1,)) + axis = 0 + + N = data.shape[axis] + + S = [None] + [xp.sum(data**k, axis=axis) for k in range(1, n + 1)] + if n == 1: + return S[1] * 1.0/N + elif n == 2: + return (N*S[2] - S[1]**2.0) / (N*(N - 1.0)) + elif n == 3: + return (2*S[1]**3 - 3*N*S[1]*S[2] + N*N*S[3]) / (N*(N - 1.0)*(N - 2.0)) + elif n == 4: + return ((-6*S[1]**4 + 12*N*S[1]**2 * S[2] - 3*N*(N-1.0)*S[2]**2 - + 4*N*(N+1)*S[1]*S[3] + N*N*(N+1)*S[4]) / + (N*(N-1.0)*(N-2.0)*(N-3.0))) + else: + raise ValueError("Should not be here.") + + +@_axis_nan_policy_factory( + lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, default_axis=None +) +def kstatvar(data, n=2, *, axis=None): + r"""Return an unbiased estimator of the variance of the k-statistic. + + See `kstat` and [1]_ for more details about the k-statistic. + + Parameters + ---------- + data : array_like + Input array. + n : int, {1, 2}, optional + Default is equal to 2. + axis : int or None, default: None + If an int, the axis of the input along which to compute the statistic. + The statistic of each axis-slice (e.g. row) of the input will appear + in a corresponding element of the output. If ``None``, the input will + be raveled before computing the statistic. + + Returns + ------- + kstatvar : float + The `n` th k-statistic variance. + + See Also + -------- + kstat : Returns the n-th k-statistic. + moment : Returns the n-th central moment about the mean for a sample. + + Notes + ----- + Unbiased estimators of the variances of the first two k-statistics are given by + + .. math:: + + \mathrm{var}(k_1) &= \frac{k_2}{n}, \\ + \mathrm{var}(k_2) &= \frac{2k_2^2n + (n-1)k_4}{n(n - 1)}. + + References + ---------- + .. [1] http://mathworld.wolfram.com/k-Statistic.html + + """ # noqa: E501 + xp = array_namespace(data) + data = xp.asarray(data) + if axis is None: + data = xp.reshape(data, (-1,)) + axis = 0 + N = data.shape[axis] + + if n == 1: + return kstat(data, n=2, axis=axis, _no_deco=True) * 1.0/N + elif n == 2: + k2 = kstat(data, n=2, axis=axis, _no_deco=True) + k4 = kstat(data, n=4, axis=axis, _no_deco=True) + return (2*N*k2**2 + (N-1)*k4) / (N*(N+1)) + else: + raise ValueError("Only n=1 or n=2 supported.") + + +def _calc_uniform_order_statistic_medians(n): + """Approximations of uniform order statistic medians. + + Parameters + ---------- + n : int + Sample size. + + Returns + ------- + v : 1d float array + Approximations of the order statistic medians. + + References + ---------- + .. [1] James J. Filliben, "The Probability Plot Correlation Coefficient + Test for Normality", Technometrics, Vol. 17, pp. 111-117, 1975. + + Examples + -------- + Order statistics of the uniform distribution on the unit interval + are marginally distributed according to beta distributions. + The expectations of these order statistic are evenly spaced across + the interval, but the distributions are skewed in a way that + pushes the medians slightly towards the endpoints of the unit interval: + + >>> import numpy as np + >>> n = 4 + >>> k = np.arange(1, n+1) + >>> from scipy.stats import beta + >>> a = k + >>> b = n-k+1 + >>> beta.mean(a, b) + array([0.2, 0.4, 0.6, 0.8]) + >>> beta.median(a, b) + array([0.15910358, 0.38572757, 0.61427243, 0.84089642]) + + The Filliben approximation uses the exact medians of the smallest + and greatest order statistics, and the remaining medians are approximated + by points spread evenly across a sub-interval of the unit interval: + + >>> from scipy.stats._morestats import _calc_uniform_order_statistic_medians + >>> _calc_uniform_order_statistic_medians(n) + array([0.15910358, 0.38545246, 0.61454754, 0.84089642]) + + This plot shows the skewed distributions of the order statistics + of a sample of size four from a uniform distribution on the unit interval: + + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(0.0, 1.0, num=50, endpoint=True) + >>> pdfs = [beta.pdf(x, a[i], b[i]) for i in range(n)] + >>> plt.figure() + >>> plt.plot(x, pdfs[0], x, pdfs[1], x, pdfs[2], x, pdfs[3]) + + """ + v = np.empty(n, dtype=np.float64) + v[-1] = 0.5**(1.0 / n) + v[0] = 1 - v[-1] + i = np.arange(2, n) + v[1:-1] = (i - 0.3175) / (n + 0.365) + return v + + +def _parse_dist_kw(dist, enforce_subclass=True): + """Parse `dist` keyword. + + Parameters + ---------- + dist : str or stats.distributions instance. + Several functions take `dist` as a keyword, hence this utility + function. + enforce_subclass : bool, optional + If True (default), `dist` needs to be a + `_distn_infrastructure.rv_generic` instance. + It can sometimes be useful to set this keyword to False, if a function + wants to accept objects that just look somewhat like such an instance + (for example, they have a ``ppf`` method). + + """ + if isinstance(dist, rv_generic): + pass + elif isinstance(dist, str): + try: + dist = getattr(distributions, dist) + except AttributeError as e: + raise ValueError(f"{dist} is not a valid distribution name") from e + elif enforce_subclass: + msg = ("`dist` should be a stats.distributions instance or a string " + "with the name of such a distribution.") + raise ValueError(msg) + + return dist + + +def _add_axis_labels_title(plot, xlabel, ylabel, title): + """Helper function to add axes labels and a title to stats plots.""" + try: + if hasattr(plot, 'set_title'): + # Matplotlib Axes instance or something that looks like it + plot.set_title(title) + plot.set_xlabel(xlabel) + plot.set_ylabel(ylabel) + else: + # matplotlib.pyplot module + plot.title(title) + plot.xlabel(xlabel) + plot.ylabel(ylabel) + except Exception: + # Not an MPL object or something that looks (enough) like it. + # Don't crash on adding labels or title + pass + + +def probplot(x, sparams=(), dist='norm', fit=True, plot=None, rvalue=False): + """ + Calculate quantiles for a probability plot, and optionally show the plot. + + Generates a probability plot of sample data against the quantiles of a + specified theoretical distribution (the normal distribution by default). + `probplot` optionally calculates a best-fit line for the data and plots the + results using Matplotlib or a given plot function. + + Parameters + ---------- + x : array_like + Sample/response data from which `probplot` creates the plot. + sparams : tuple, optional + Distribution-specific shape parameters (shape parameters plus location + and scale). + dist : str or stats.distributions instance, optional + Distribution or distribution function name. The default is 'norm' for a + normal probability plot. Objects that look enough like a + stats.distributions instance (i.e. they have a ``ppf`` method) are also + accepted. + fit : bool, optional + Fit a least-squares regression (best-fit) line to the sample data if + True (default). + plot : object, optional + If given, plots the quantiles. + If given and `fit` is True, also plots the least squares fit. + `plot` is an object that has to have methods "plot" and "text". + The `matplotlib.pyplot` module or a Matplotlib Axes object can be used, + or a custom object with the same methods. + Default is None, which means that no plot is created. + rvalue : bool, optional + If `plot` is provided and `fit` is True, setting `rvalue` to True + includes the coefficient of determination on the plot. + Default is False. + + Returns + ------- + (osm, osr) : tuple of ndarrays + Tuple of theoretical quantiles (osm, or order statistic medians) and + ordered responses (osr). `osr` is simply sorted input `x`. + For details on how `osm` is calculated see the Notes section. + (slope, intercept, r) : tuple of floats, optional + Tuple containing the result of the least-squares fit, if that is + performed by `probplot`. `r` is the square root of the coefficient of + determination. If ``fit=False`` and ``plot=None``, this tuple is not + returned. + + Notes + ----- + Even if `plot` is given, the figure is not shown or saved by `probplot`; + ``plt.show()`` or ``plt.savefig('figname.png')`` should be used after + calling `probplot`. + + `probplot` generates a probability plot, which should not be confused with + a Q-Q or a P-P plot. Statsmodels has more extensive functionality of this + type, see ``statsmodels.api.ProbPlot``. + + The formula used for the theoretical quantiles (horizontal axis of the + probability plot) is Filliben's estimate:: + + quantiles = dist.ppf(val), for + + 0.5**(1/n), for i = n + val = (i - 0.3175) / (n + 0.365), for i = 2, ..., n-1 + 1 - 0.5**(1/n), for i = 1 + + where ``i`` indicates the i-th ordered value and ``n`` is the total number + of values. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> nsample = 100 + >>> rng = np.random.default_rng() + + A t distribution with small degrees of freedom: + + >>> ax1 = plt.subplot(221) + >>> x = stats.t.rvs(3, size=nsample, random_state=rng) + >>> res = stats.probplot(x, plot=plt) + + A t distribution with larger degrees of freedom: + + >>> ax2 = plt.subplot(222) + >>> x = stats.t.rvs(25, size=nsample, random_state=rng) + >>> res = stats.probplot(x, plot=plt) + + A mixture of two normal distributions with broadcasting: + + >>> ax3 = plt.subplot(223) + >>> x = stats.norm.rvs(loc=[0,5], scale=[1,1.5], + ... size=(nsample//2,2), random_state=rng).ravel() + >>> res = stats.probplot(x, plot=plt) + + A standard normal distribution: + + >>> ax4 = plt.subplot(224) + >>> x = stats.norm.rvs(loc=0, scale=1, size=nsample, random_state=rng) + >>> res = stats.probplot(x, plot=plt) + + Produce a new figure with a loggamma distribution, using the ``dist`` and + ``sparams`` keywords: + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> x = stats.loggamma.rvs(c=2.5, size=500, random_state=rng) + >>> res = stats.probplot(x, dist=stats.loggamma, sparams=(2.5,), plot=ax) + >>> ax.set_title("Probplot for loggamma dist with shape parameter 2.5") + + Show the results with Matplotlib: + + >>> plt.show() + + """ + x = np.asarray(x) + if x.size == 0: + if fit: + return (x, x), (np.nan, np.nan, 0.0) + else: + return x, x + + osm_uniform = _calc_uniform_order_statistic_medians(len(x)) + dist = _parse_dist_kw(dist, enforce_subclass=False) + if sparams is None: + sparams = () + if isscalar(sparams): + sparams = (sparams,) + if not isinstance(sparams, tuple): + sparams = tuple(sparams) + + osm = dist.ppf(osm_uniform, *sparams) + osr = sort(x) + if fit: + # perform a linear least squares fit. + slope, intercept, r, prob, _ = _stats_py.linregress(osm, osr) + + if plot is not None: + plot.plot(osm, osr, 'bo') + if fit: + plot.plot(osm, slope*osm + intercept, 'r-') + _add_axis_labels_title(plot, xlabel='Theoretical quantiles', + ylabel='Ordered Values', + title='Probability Plot') + + # Add R^2 value to the plot as text + if fit and rvalue: + xmin = amin(osm) + xmax = amax(osm) + ymin = amin(x) + ymax = amax(x) + posx = xmin + 0.70 * (xmax - xmin) + posy = ymin + 0.01 * (ymax - ymin) + plot.text(posx, posy, f"$R^2={r ** 2:1.4f}$") + + if fit: + return (osm, osr), (slope, intercept, r) + else: + return osm, osr + + +def ppcc_max(x, brack=(0.0, 1.0), dist='tukeylambda'): + """Calculate the shape parameter that maximizes the PPCC. + + The probability plot correlation coefficient (PPCC) plot can be used + to determine the optimal shape parameter for a one-parameter family + of distributions. ``ppcc_max`` returns the shape parameter that would + maximize the probability plot correlation coefficient for the given + data to a one-parameter family of distributions. + + Parameters + ---------- + x : array_like + Input array. + brack : tuple, optional + Triple (a,b,c) where (a>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> c = 2.5 + >>> x = stats.weibull_min.rvs(c, scale=4, size=2000, random_state=rng) + + Generate the PPCC plot for this data with the Weibull distribution. + + >>> fig, ax = plt.subplots(figsize=(8, 6)) + >>> res = stats.ppcc_plot(x, c/2, 2*c, dist='weibull_min', plot=ax) + + We calculate the value where the shape should reach its maximum and a + red line is drawn there. The line should coincide with the highest + point in the PPCC graph. + + >>> cmax = stats.ppcc_max(x, brack=(c/2, 2*c), dist='weibull_min') + >>> ax.axvline(cmax, color='r') + >>> plt.show() + + """ + dist = _parse_dist_kw(dist) + osm_uniform = _calc_uniform_order_statistic_medians(len(x)) + osr = sort(x) + + # this function computes the x-axis values of the probability plot + # and computes a linear regression (including the correlation) + # and returns 1-r so that a minimization function maximizes the + # correlation + def tempfunc(shape, mi, yvals, func): + xvals = func(mi, shape) + r, prob = _stats_py.pearsonr(xvals, yvals) + return 1 - r + + return optimize.brent(tempfunc, brack=brack, + args=(osm_uniform, osr, dist.ppf)) + + +def ppcc_plot(x, a, b, dist='tukeylambda', plot=None, N=80): + """Calculate and optionally plot probability plot correlation coefficient. + + The probability plot correlation coefficient (PPCC) plot can be used to + determine the optimal shape parameter for a one-parameter family of + distributions. It cannot be used for distributions without shape + parameters + (like the normal distribution) or with multiple shape parameters. + + By default a Tukey-Lambda distribution (`stats.tukeylambda`) is used. A + Tukey-Lambda PPCC plot interpolates from long-tailed to short-tailed + distributions via an approximately normal one, and is therefore + particularly useful in practice. + + Parameters + ---------- + x : array_like + Input array. + a, b : scalar + Lower and upper bounds of the shape parameter to use. + dist : str or stats.distributions instance, optional + Distribution or distribution function name. Objects that look enough + like a stats.distributions instance (i.e. they have a ``ppf`` method) + are also accepted. The default is ``'tukeylambda'``. + plot : object, optional + If given, plots PPCC against the shape parameter. + `plot` is an object that has to have methods "plot" and "text". + The `matplotlib.pyplot` module or a Matplotlib Axes object can be used, + or a custom object with the same methods. + Default is None, which means that no plot is created. + N : int, optional + Number of points on the horizontal axis (equally distributed from + `a` to `b`). + + Returns + ------- + svals : ndarray + The shape values for which `ppcc` was calculated. + ppcc : ndarray + The calculated probability plot correlation coefficient values. + + See Also + -------- + ppcc_max, probplot, boxcox_normplot, tukeylambda + + References + ---------- + J.J. Filliben, "The Probability Plot Correlation Coefficient Test for + Normality", Technometrics, Vol. 17, pp. 111-117, 1975. + + Examples + -------- + First we generate some random data from a Weibull distribution + with shape parameter 2.5, and plot the histogram of the data: + + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> c = 2.5 + >>> x = stats.weibull_min.rvs(c, scale=4, size=2000, random_state=rng) + + Take a look at the histogram of the data. + + >>> fig1, ax = plt.subplots(figsize=(9, 4)) + >>> ax.hist(x, bins=50) + >>> ax.set_title('Histogram of x') + >>> plt.show() + + Now we explore this data with a PPCC plot as well as the related + probability plot and Box-Cox normplot. A red line is drawn where we + expect the PPCC value to be maximal (at the shape parameter ``c`` + used above): + + >>> fig2 = plt.figure(figsize=(12, 4)) + >>> ax1 = fig2.add_subplot(1, 3, 1) + >>> ax2 = fig2.add_subplot(1, 3, 2) + >>> ax3 = fig2.add_subplot(1, 3, 3) + >>> res = stats.probplot(x, plot=ax1) + >>> res = stats.boxcox_normplot(x, -4, 4, plot=ax2) + >>> res = stats.ppcc_plot(x, c/2, 2*c, dist='weibull_min', plot=ax3) + >>> ax3.axvline(c, color='r') + >>> plt.show() + + """ + if b <= a: + raise ValueError("`b` has to be larger than `a`.") + + svals = np.linspace(a, b, num=N) + ppcc = np.empty_like(svals) + for k, sval in enumerate(svals): + _, r2 = probplot(x, sval, dist=dist, fit=True) + ppcc[k] = r2[-1] + + if plot is not None: + plot.plot(svals, ppcc, 'x') + _add_axis_labels_title(plot, xlabel='Shape Values', + ylabel='Prob Plot Corr. Coef.', + title=f'({dist}) PPCC Plot') + + return svals, ppcc + + +def _log_mean(logx): + # compute log of mean of x from log(x) + res = special.logsumexp(logx, axis=0) - math.log(logx.shape[0]) + return res + + +def _log_var(logx, xp): + # compute log of variance of x from log(x) + logmean = _log_mean(logx) + # get complex dtype with component dtypes same as `logx` dtype; + # see data-apis/array-api#841 + dtype = xp.result_type(logx.dtype, xp.complex64) + pij = xp.full(logx.shape, pi * 1j, dtype=dtype) + logxmu = special.logsumexp(xp.stack((logx, logmean + pij)), axis=0) + res = (xp.real(xp.asarray(special.logsumexp(2 * logxmu, axis=0))) + - math.log(logx.shape[0])) + return res + + +def boxcox_llf(lmb, data): + r"""The boxcox log-likelihood function. + + Parameters + ---------- + lmb : scalar + Parameter for Box-Cox transformation. See `boxcox` for details. + data : array_like + Data to calculate Box-Cox log-likelihood for. If `data` is + multi-dimensional, the log-likelihood is calculated along the first + axis. + + Returns + ------- + llf : float or ndarray + Box-Cox log-likelihood of `data` given `lmb`. A float for 1-D `data`, + an array otherwise. + + See Also + -------- + boxcox, probplot, boxcox_normplot, boxcox_normmax + + Notes + ----- + The Box-Cox log-likelihood function is defined here as + + .. math:: + + llf = (\lambda - 1) \sum_i(\log(x_i)) - + N/2 \log(\sum_i (y_i - \bar{y})^2 / N), + + where ``y`` is the Box-Cox transformed input data ``x``. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> from mpl_toolkits.axes_grid1.inset_locator import inset_axes + + Generate some random variates and calculate Box-Cox log-likelihood values + for them for a range of ``lmbda`` values: + + >>> rng = np.random.default_rng() + >>> x = stats.loggamma.rvs(5, loc=10, size=1000, random_state=rng) + >>> lmbdas = np.linspace(-2, 10) + >>> llf = np.zeros(lmbdas.shape, dtype=float) + >>> for ii, lmbda in enumerate(lmbdas): + ... llf[ii] = stats.boxcox_llf(lmbda, x) + + Also find the optimal lmbda value with `boxcox`: + + >>> x_most_normal, lmbda_optimal = stats.boxcox(x) + + Plot the log-likelihood as function of lmbda. Add the optimal lmbda as a + horizontal line to check that that's really the optimum: + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> ax.plot(lmbdas, llf, 'b.-') + >>> ax.axhline(stats.boxcox_llf(lmbda_optimal, x), color='r') + >>> ax.set_xlabel('lmbda parameter') + >>> ax.set_ylabel('Box-Cox log-likelihood') + + Now add some probability plots to show that where the log-likelihood is + maximized the data transformed with `boxcox` looks closest to normal: + + >>> locs = [3, 10, 4] # 'lower left', 'center', 'lower right' + >>> for lmbda, loc in zip([-1, lmbda_optimal, 9], locs): + ... xt = stats.boxcox(x, lmbda=lmbda) + ... (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt) + ... ax_inset = inset_axes(ax, width="20%", height="20%", loc=loc) + ... ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-') + ... ax_inset.set_xticklabels([]) + ... ax_inset.set_yticklabels([]) + ... ax_inset.set_title(r'$\lambda=%1.2f$' % lmbda) + + >>> plt.show() + + """ + xp = array_namespace(data) + data = xp.asarray(data) + N = data.shape[0] + if N == 0: + return xp.nan + + dt = data.dtype + if xp.isdtype(dt, 'integral'): + data = xp.asarray(data, dtype=xp.float64) + dt = xp.float64 + + logdata = xp.log(data) + + # Compute the variance of the transformed data. + if lmb == 0: + logvar = xp.log(xp.var(logdata, axis=0)) + else: + # Transform without the constant offset 1/lmb. The offset does + # not affect the variance, and the subtraction of the offset can + # lead to loss of precision. + # Division by lmb can be factored out to enhance numerical stability. + logx = lmb * logdata + logvar = _log_var(logx, xp) - 2 * math.log(abs(lmb)) + + res = (lmb - 1) * xp.sum(logdata, axis=0) - N/2 * logvar + res = xp.astype(res, dt) + res = res[()] if res.ndim == 0 else res + return res + + +def _boxcox_conf_interval(x, lmax, alpha): + # Need to find the lambda for which + # f(x,lmbda) >= f(x,lmax) - 0.5*chi^2_alpha;1 + fac = 0.5 * distributions.chi2.ppf(1 - alpha, 1) + target = boxcox_llf(lmax, x) - fac + + def rootfunc(lmbda, data, target): + return boxcox_llf(lmbda, data) - target + + # Find positive endpoint of interval in which answer is to be found + newlm = lmax + 0.5 + N = 0 + while (rootfunc(newlm, x, target) > 0.0) and (N < 500): + newlm += 0.1 + N += 1 + + if N == 500: + raise RuntimeError("Could not find endpoint.") + + lmplus = optimize.brentq(rootfunc, lmax, newlm, args=(x, target)) + + # Now find negative interval in the same way + newlm = lmax - 0.5 + N = 0 + while (rootfunc(newlm, x, target) > 0.0) and (N < 500): + newlm -= 0.1 + N += 1 + + if N == 500: + raise RuntimeError("Could not find endpoint.") + + lmminus = optimize.brentq(rootfunc, newlm, lmax, args=(x, target)) + return lmminus, lmplus + + +def boxcox(x, lmbda=None, alpha=None, optimizer=None): + r"""Return a dataset transformed by a Box-Cox power transformation. + + Parameters + ---------- + x : ndarray + Input array to be transformed. + + If `lmbda` is not None, this is an alias of + `scipy.special.boxcox`. + Returns nan if ``x < 0``; returns -inf if ``x == 0 and lmbda < 0``. + + If `lmbda` is None, array must be positive, 1-dimensional, and + non-constant. + + lmbda : scalar, optional + If `lmbda` is None (default), find the value of `lmbda` that maximizes + the log-likelihood function and return it as the second output + argument. + + If `lmbda` is not None, do the transformation for that value. + + alpha : float, optional + If `lmbda` is None and `alpha` is not None (default), return the + ``100 * (1-alpha)%`` confidence interval for `lmbda` as the third + output argument. Must be between 0.0 and 1.0. + + If `lmbda` is not None, `alpha` is ignored. + optimizer : callable, optional + If `lmbda` is None, `optimizer` is the scalar optimizer used to find + the value of `lmbda` that minimizes the negative log-likelihood + function. `optimizer` is a callable that accepts one argument: + + fun : callable + The objective function, which evaluates the negative + log-likelihood function at a provided value of `lmbda` + + and returns an object, such as an instance of + `scipy.optimize.OptimizeResult`, which holds the optimal value of + `lmbda` in an attribute `x`. + + See the example in `boxcox_normmax` or the documentation of + `scipy.optimize.minimize_scalar` for more information. + + If `lmbda` is not None, `optimizer` is ignored. + + Returns + ------- + boxcox : ndarray + Box-Cox power transformed array. + maxlog : float, optional + If the `lmbda` parameter is None, the second returned argument is + the `lmbda` that maximizes the log-likelihood function. + (min_ci, max_ci) : tuple of float, optional + If `lmbda` parameter is None and `alpha` is not None, this returned + tuple of floats represents the minimum and maximum confidence limits + given `alpha`. + + See Also + -------- + probplot, boxcox_normplot, boxcox_normmax, boxcox_llf + + Notes + ----- + The Box-Cox transform is given by:: + + y = (x**lmbda - 1) / lmbda, for lmbda != 0 + log(x), for lmbda = 0 + + `boxcox` requires the input data to be positive. Sometimes a Box-Cox + transformation provides a shift parameter to achieve this; `boxcox` does + not. Such a shift parameter is equivalent to adding a positive constant to + `x` before calling `boxcox`. + + The confidence limits returned when `alpha` is provided give the interval + where: + + .. math:: + + llf(\hat{\lambda}) - llf(\lambda) < \frac{1}{2}\chi^2(1 - \alpha, 1), + + with ``llf`` the log-likelihood function and :math:`\chi^2` the chi-squared + function. + + References + ---------- + G.E.P. Box and D.R. Cox, "An Analysis of Transformations", Journal of the + Royal Statistical Society B, 26, 211-252 (1964). + + Examples + -------- + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + We generate some random variates from a non-normal distribution and make a + probability plot for it, to show it is non-normal in the tails: + + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(211) + >>> x = stats.loggamma.rvs(5, size=500) + 5 + >>> prob = stats.probplot(x, dist=stats.norm, plot=ax1) + >>> ax1.set_xlabel('') + >>> ax1.set_title('Probplot against normal distribution') + + We now use `boxcox` to transform the data so it's closest to normal: + + >>> ax2 = fig.add_subplot(212) + >>> xt, _ = stats.boxcox(x) + >>> prob = stats.probplot(xt, dist=stats.norm, plot=ax2) + >>> ax2.set_title('Probplot after Box-Cox transformation') + + >>> plt.show() + + """ + x = np.asarray(x) + + if lmbda is not None: # single transformation + return special.boxcox(x, lmbda) + + if x.ndim != 1: + raise ValueError("Data must be 1-dimensional.") + + if x.size == 0: + return x + + if np.all(x == x[0]): + raise ValueError("Data must not be constant.") + + if np.any(x <= 0): + raise ValueError("Data must be positive.") + + # If lmbda=None, find the lmbda that maximizes the log-likelihood function. + lmax = boxcox_normmax(x, method='mle', optimizer=optimizer) + y = boxcox(x, lmax) + + if alpha is None: + return y, lmax + else: + # Find confidence interval + interval = _boxcox_conf_interval(x, lmax, alpha) + return y, lmax, interval + + +def _boxcox_inv_lmbda(x, y): + # compute lmbda given x and y for Box-Cox transformation + num = special.lambertw(-(x ** (-1 / y)) * np.log(x) / y, k=-1) + return np.real(-num / np.log(x) - 1 / y) + + +class _BigFloat: + def __repr__(self): + return "BIG_FLOAT" + + +_BigFloat_singleton = _BigFloat() + + +def boxcox_normmax( + x, brack=None, method='pearsonr', optimizer=None, *, ymax=_BigFloat_singleton +): + """Compute optimal Box-Cox transform parameter for input data. + + Parameters + ---------- + x : array_like + Input array. All entries must be positive, finite, real numbers. + brack : 2-tuple, optional, default (-2.0, 2.0) + The starting interval for a downhill bracket search for the default + `optimize.brent` solver. Note that this is in most cases not + critical; the final result is allowed to be outside this bracket. + If `optimizer` is passed, `brack` must be None. + method : str, optional + The method to determine the optimal transform parameter (`boxcox` + ``lmbda`` parameter). Options are: + + 'pearsonr' (default) + Maximizes the Pearson correlation coefficient between + ``y = boxcox(x)`` and the expected values for ``y`` if `x` would be + normally-distributed. + + 'mle' + Maximizes the log-likelihood `boxcox_llf`. This is the method used + in `boxcox`. + + 'all' + Use all optimization methods available, and return all results. + Useful to compare different methods. + optimizer : callable, optional + `optimizer` is a callable that accepts one argument: + + fun : callable + The objective function to be minimized. `fun` accepts one argument, + the Box-Cox transform parameter `lmbda`, and returns the value of + the function (e.g., the negative log-likelihood) at the provided + argument. The job of `optimizer` is to find the value of `lmbda` + that *minimizes* `fun`. + + and returns an object, such as an instance of + `scipy.optimize.OptimizeResult`, which holds the optimal value of + `lmbda` in an attribute `x`. + + See the example below or the documentation of + `scipy.optimize.minimize_scalar` for more information. + ymax : float, optional + The unconstrained optimal transform parameter may cause Box-Cox + transformed data to have extreme magnitude or even overflow. + This parameter constrains MLE optimization such that the magnitude + of the transformed `x` does not exceed `ymax`. The default is + the maximum value of the input dtype. If set to infinity, + `boxcox_normmax` returns the unconstrained optimal lambda. + Ignored when ``method='pearsonr'``. + + Returns + ------- + maxlog : float or ndarray + The optimal transform parameter found. An array instead of a scalar + for ``method='all'``. + + See Also + -------- + boxcox, boxcox_llf, boxcox_normplot, scipy.optimize.minimize_scalar + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + We can generate some data and determine the optimal ``lmbda`` in various + ways: + + >>> rng = np.random.default_rng() + >>> x = stats.loggamma.rvs(5, size=30, random_state=rng) + 5 + >>> y, lmax_mle = stats.boxcox(x) + >>> lmax_pearsonr = stats.boxcox_normmax(x) + + >>> lmax_mle + 2.217563431465757 + >>> lmax_pearsonr + 2.238318660200961 + >>> stats.boxcox_normmax(x, method='all') + array([2.23831866, 2.21756343]) + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> prob = stats.boxcox_normplot(x, -10, 10, plot=ax) + >>> ax.axvline(lmax_mle, color='r') + >>> ax.axvline(lmax_pearsonr, color='g', ls='--') + + >>> plt.show() + + Alternatively, we can define our own `optimizer` function. Suppose we + are only interested in values of `lmbda` on the interval [6, 7], we + want to use `scipy.optimize.minimize_scalar` with ``method='bounded'``, + and we want to use tighter tolerances when optimizing the log-likelihood + function. To do this, we define a function that accepts positional argument + `fun` and uses `scipy.optimize.minimize_scalar` to minimize `fun` subject + to the provided bounds and tolerances: + + >>> from scipy import optimize + >>> options = {'xatol': 1e-12} # absolute tolerance on `x` + >>> def optimizer(fun): + ... return optimize.minimize_scalar(fun, bounds=(6, 7), + ... method="bounded", options=options) + >>> stats.boxcox_normmax(x, optimizer=optimizer) + 6.000000000 + """ + x = np.asarray(x) + + if not np.all(np.isfinite(x) & (x >= 0)): + message = ("The `x` argument of `boxcox_normmax` must contain " + "only positive, finite, real numbers.") + raise ValueError(message) + + end_msg = "exceed specified `ymax`." + if ymax is _BigFloat_singleton: + dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64 + # 10000 is a safety factor because `special.boxcox` overflows prematurely. + ymax = np.finfo(dtype).max / 10000 + end_msg = f"overflow in {dtype}." + elif ymax <= 0: + raise ValueError("`ymax` must be strictly positive") + + # If optimizer is not given, define default 'brent' optimizer. + if optimizer is None: + + # Set default value for `brack`. + if brack is None: + brack = (-2.0, 2.0) + + def _optimizer(func, args): + return optimize.brent(func, args=args, brack=brack) + + # Otherwise check optimizer. + else: + if not callable(optimizer): + raise ValueError("`optimizer` must be a callable") + + if brack is not None: + raise ValueError("`brack` must be None if `optimizer` is given") + + # `optimizer` is expected to return a `OptimizeResult` object, we here + # get the solution to the optimization problem. + def _optimizer(func, args): + def func_wrapped(x): + return func(x, *args) + return getattr(optimizer(func_wrapped), 'x', None) + + def _pearsonr(x): + osm_uniform = _calc_uniform_order_statistic_medians(len(x)) + xvals = distributions.norm.ppf(osm_uniform) + + def _eval_pearsonr(lmbda, xvals, samps): + # This function computes the x-axis values of the probability plot + # and computes a linear regression (including the correlation) and + # returns ``1 - r`` so that a minimization function maximizes the + # correlation. + y = boxcox(samps, lmbda) + yvals = np.sort(y) + r, prob = _stats_py.pearsonr(xvals, yvals) + return 1 - r + + return _optimizer(_eval_pearsonr, args=(xvals, x)) + + def _mle(x): + def _eval_mle(lmb, data): + # function to minimize + return -boxcox_llf(lmb, data) + + return _optimizer(_eval_mle, args=(x,)) + + def _all(x): + maxlog = np.empty(2, dtype=float) + maxlog[0] = _pearsonr(x) + maxlog[1] = _mle(x) + return maxlog + + methods = {'pearsonr': _pearsonr, + 'mle': _mle, + 'all': _all} + if method not in methods.keys(): + raise ValueError(f"Method {method} not recognized.") + + optimfunc = methods[method] + + res = optimfunc(x) + + if res is None: + message = ("The `optimizer` argument of `boxcox_normmax` must return " + "an object containing the optimal `lmbda` in attribute `x`.") + raise ValueError(message) + elif not np.isinf(ymax): # adjust the final lambda + # x > 1, boxcox(x) > 0; x < 1, boxcox(x) < 0 + xmax, xmin = np.max(x), np.min(x) + if xmin >= 1: + x_treme = xmax + elif xmax <= 1: + x_treme = xmin + else: # xmin < 1 < xmax + indicator = special.boxcox(xmax, res) > abs(special.boxcox(xmin, res)) + if isinstance(res, np.ndarray): + indicator = indicator[1] # select corresponds with 'mle' + x_treme = xmax if indicator else xmin + + mask = abs(special.boxcox(x_treme, res)) > ymax + if np.any(mask): + message = ( + f"The optimal lambda is {res}, but the returned lambda is the " + f"constrained optimum to ensure that the maximum or the minimum " + f"of the transformed data does not " + end_msg + ) + warnings.warn(message, stacklevel=2) + + # Return the constrained lambda to ensure the transformation + # does not cause overflow or exceed specified `ymax` + constrained_res = _boxcox_inv_lmbda(x_treme, ymax * np.sign(x_treme - 1)) + + if isinstance(res, np.ndarray): + res[mask] = constrained_res + else: + res = constrained_res + return res + + +def _normplot(method, x, la, lb, plot=None, N=80): + """Compute parameters for a Box-Cox or Yeo-Johnson normality plot, + optionally show it. + + See `boxcox_normplot` or `yeojohnson_normplot` for details. + """ + + if method == 'boxcox': + title = 'Box-Cox Normality Plot' + transform_func = boxcox + else: + title = 'Yeo-Johnson Normality Plot' + transform_func = yeojohnson + + x = np.asarray(x) + if x.size == 0: + return x + + if lb <= la: + raise ValueError("`lb` has to be larger than `la`.") + + if method == 'boxcox' and np.any(x <= 0): + raise ValueError("Data must be positive.") + + lmbdas = np.linspace(la, lb, num=N) + ppcc = lmbdas * 0.0 + for i, val in enumerate(lmbdas): + # Determine for each lmbda the square root of correlation coefficient + # of transformed x + z = transform_func(x, lmbda=val) + _, (_, _, r) = probplot(z, dist='norm', fit=True) + ppcc[i] = r + + if plot is not None: + plot.plot(lmbdas, ppcc, 'x') + _add_axis_labels_title(plot, xlabel='$\\lambda$', + ylabel='Prob Plot Corr. Coef.', + title=title) + + return lmbdas, ppcc + + +def boxcox_normplot(x, la, lb, plot=None, N=80): + """Compute parameters for a Box-Cox normality plot, optionally show it. + + A Box-Cox normality plot shows graphically what the best transformation + parameter is to use in `boxcox` to obtain a distribution that is close + to normal. + + Parameters + ---------- + x : array_like + Input array. + la, lb : scalar + The lower and upper bounds for the ``lmbda`` values to pass to `boxcox` + for Box-Cox transformations. These are also the limits of the + horizontal axis of the plot if that is generated. + plot : object, optional + If given, plots the quantiles and least squares fit. + `plot` is an object that has to have methods "plot" and "text". + The `matplotlib.pyplot` module or a Matplotlib Axes object can be used, + or a custom object with the same methods. + Default is None, which means that no plot is created. + N : int, optional + Number of points on the horizontal axis (equally distributed from + `la` to `lb`). + + Returns + ------- + lmbdas : ndarray + The ``lmbda`` values for which a Box-Cox transform was done. + ppcc : ndarray + Probability Plot Correlation Coefficient, as obtained from `probplot` + when fitting the Box-Cox transformed input `x` against a normal + distribution. + + See Also + -------- + probplot, boxcox, boxcox_normmax, boxcox_llf, ppcc_max + + Notes + ----- + Even if `plot` is given, the figure is not shown or saved by + `boxcox_normplot`; ``plt.show()`` or ``plt.savefig('figname.png')`` + should be used after calling `probplot`. + + Examples + -------- + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + Generate some non-normally distributed data, and create a Box-Cox plot: + + >>> x = stats.loggamma.rvs(5, size=500) + 5 + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> prob = stats.boxcox_normplot(x, -20, 20, plot=ax) + + Determine and plot the optimal ``lmbda`` to transform ``x`` and plot it in + the same plot: + + >>> _, maxlog = stats.boxcox(x) + >>> ax.axvline(maxlog, color='r') + + >>> plt.show() + + """ + return _normplot('boxcox', x, la, lb, plot, N) + + +def yeojohnson(x, lmbda=None): + r"""Return a dataset transformed by a Yeo-Johnson power transformation. + + Parameters + ---------- + x : ndarray + Input array. Should be 1-dimensional. + lmbda : float, optional + If ``lmbda`` is ``None``, find the lambda that maximizes the + log-likelihood function and return it as the second output argument. + Otherwise the transformation is done for the given value. + + Returns + ------- + yeojohnson: ndarray + Yeo-Johnson power transformed array. + maxlog : float, optional + If the `lmbda` parameter is None, the second returned argument is + the lambda that maximizes the log-likelihood function. + + See Also + -------- + probplot, yeojohnson_normplot, yeojohnson_normmax, yeojohnson_llf, boxcox + + Notes + ----- + The Yeo-Johnson transform is given by:: + + y = ((x + 1)**lmbda - 1) / lmbda, for x >= 0, lmbda != 0 + log(x + 1), for x >= 0, lmbda = 0 + -((-x + 1)**(2 - lmbda) - 1) / (2 - lmbda), for x < 0, lmbda != 2 + -log(-x + 1), for x < 0, lmbda = 2 + + Unlike `boxcox`, `yeojohnson` does not require the input data to be + positive. + + .. versionadded:: 1.2.0 + + + References + ---------- + I. Yeo and R.A. Johnson, "A New Family of Power Transformations to + Improve Normality or Symmetry", Biometrika 87.4 (2000): + + + Examples + -------- + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + We generate some random variates from a non-normal distribution and make a + probability plot for it, to show it is non-normal in the tails: + + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(211) + >>> x = stats.loggamma.rvs(5, size=500) + 5 + >>> prob = stats.probplot(x, dist=stats.norm, plot=ax1) + >>> ax1.set_xlabel('') + >>> ax1.set_title('Probplot against normal distribution') + + We now use `yeojohnson` to transform the data so it's closest to normal: + + >>> ax2 = fig.add_subplot(212) + >>> xt, lmbda = stats.yeojohnson(x) + >>> prob = stats.probplot(xt, dist=stats.norm, plot=ax2) + >>> ax2.set_title('Probplot after Yeo-Johnson transformation') + + >>> plt.show() + + """ + x = np.asarray(x) + if x.size == 0: + return x + + if np.issubdtype(x.dtype, np.complexfloating): + raise ValueError('Yeo-Johnson transformation is not defined for ' + 'complex numbers.') + + if np.issubdtype(x.dtype, np.integer): + x = x.astype(np.float64, copy=False) + + if lmbda is not None: + return _yeojohnson_transform(x, lmbda) + + # if lmbda=None, find the lmbda that maximizes the log-likelihood function. + lmax = yeojohnson_normmax(x) + y = _yeojohnson_transform(x, lmax) + + return y, lmax + + +def _yeojohnson_transform(x, lmbda): + """Returns `x` transformed by the Yeo-Johnson power transform with given + parameter `lmbda`. + """ + dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64 + out = np.zeros_like(x, dtype=dtype) + pos = x >= 0 # binary mask + + # when x >= 0 + if abs(lmbda) < np.spacing(1.): + out[pos] = np.log1p(x[pos]) + else: # lmbda != 0 + # more stable version of: ((x + 1) ** lmbda - 1) / lmbda + out[pos] = np.expm1(lmbda * np.log1p(x[pos])) / lmbda + + # when x < 0 + if abs(lmbda - 2) > np.spacing(1.): + out[~pos] = -np.expm1((2 - lmbda) * np.log1p(-x[~pos])) / (2 - lmbda) + else: # lmbda == 2 + out[~pos] = -np.log1p(-x[~pos]) + + return out + + +def yeojohnson_llf(lmb, data): + r"""The yeojohnson log-likelihood function. + + Parameters + ---------- + lmb : scalar + Parameter for Yeo-Johnson transformation. See `yeojohnson` for + details. + data : array_like + Data to calculate Yeo-Johnson log-likelihood for. If `data` is + multi-dimensional, the log-likelihood is calculated along the first + axis. + + Returns + ------- + llf : float + Yeo-Johnson log-likelihood of `data` given `lmb`. + + See Also + -------- + yeojohnson, probplot, yeojohnson_normplot, yeojohnson_normmax + + Notes + ----- + The Yeo-Johnson log-likelihood function is defined here as + + .. math:: + + llf = -N/2 \log(\hat{\sigma}^2) + (\lambda - 1) + \sum_i \text{ sign }(x_i)\log(|x_i| + 1) + + where :math:`\hat{\sigma}^2` is estimated variance of the Yeo-Johnson + transformed input data ``x``. + + .. versionadded:: 1.2.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + >>> from mpl_toolkits.axes_grid1.inset_locator import inset_axes + + Generate some random variates and calculate Yeo-Johnson log-likelihood + values for them for a range of ``lmbda`` values: + + >>> x = stats.loggamma.rvs(5, loc=10, size=1000) + >>> lmbdas = np.linspace(-2, 10) + >>> llf = np.zeros(lmbdas.shape, dtype=float) + >>> for ii, lmbda in enumerate(lmbdas): + ... llf[ii] = stats.yeojohnson_llf(lmbda, x) + + Also find the optimal lmbda value with `yeojohnson`: + + >>> x_most_normal, lmbda_optimal = stats.yeojohnson(x) + + Plot the log-likelihood as function of lmbda. Add the optimal lmbda as a + horizontal line to check that that's really the optimum: + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> ax.plot(lmbdas, llf, 'b.-') + >>> ax.axhline(stats.yeojohnson_llf(lmbda_optimal, x), color='r') + >>> ax.set_xlabel('lmbda parameter') + >>> ax.set_ylabel('Yeo-Johnson log-likelihood') + + Now add some probability plots to show that where the log-likelihood is + maximized the data transformed with `yeojohnson` looks closest to normal: + + >>> locs = [3, 10, 4] # 'lower left', 'center', 'lower right' + >>> for lmbda, loc in zip([-1, lmbda_optimal, 9], locs): + ... xt = stats.yeojohnson(x, lmbda=lmbda) + ... (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt) + ... ax_inset = inset_axes(ax, width="20%", height="20%", loc=loc) + ... ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-') + ... ax_inset.set_xticklabels([]) + ... ax_inset.set_yticklabels([]) + ... ax_inset.set_title(r'$\lambda=%1.2f$' % lmbda) + + >>> plt.show() + + """ + data = np.asarray(data) + n_samples = data.shape[0] + + if n_samples == 0: + return np.nan + + trans = _yeojohnson_transform(data, lmb) + trans_var = trans.var(axis=0) + loglike = np.empty_like(trans_var) + + # Avoid RuntimeWarning raised by np.log when the variance is too low + tiny_variance = trans_var < np.finfo(trans_var.dtype).tiny + loglike[tiny_variance] = np.inf + + loglike[~tiny_variance] = ( + -n_samples / 2 * np.log(trans_var[~tiny_variance])) + loglike[~tiny_variance] += ( + (lmb - 1) * (np.sign(data) * np.log1p(np.abs(data))).sum(axis=0)) + return loglike + + +def yeojohnson_normmax(x, brack=None): + """Compute optimal Yeo-Johnson transform parameter. + + Compute optimal Yeo-Johnson transform parameter for input data, using + maximum likelihood estimation. + + Parameters + ---------- + x : array_like + Input array. + brack : 2-tuple, optional + The starting interval for a downhill bracket search with + `optimize.brent`. Note that this is in most cases not critical; the + final result is allowed to be outside this bracket. If None, + `optimize.fminbound` is used with bounds that avoid overflow. + + Returns + ------- + maxlog : float + The optimal transform parameter found. + + See Also + -------- + yeojohnson, yeojohnson_llf, yeojohnson_normplot + + Notes + ----- + .. versionadded:: 1.2.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + Generate some data and determine optimal ``lmbda`` + + >>> rng = np.random.default_rng() + >>> x = stats.loggamma.rvs(5, size=30, random_state=rng) + 5 + >>> lmax = stats.yeojohnson_normmax(x) + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> prob = stats.yeojohnson_normplot(x, -10, 10, plot=ax) + >>> ax.axvline(lmax, color='r') + + >>> plt.show() + + """ + def _neg_llf(lmbda, data): + llf = yeojohnson_llf(lmbda, data) + # reject likelihoods that are inf which are likely due to small + # variance in the transformed space + llf[np.isinf(llf)] = -np.inf + return -llf + + with np.errstate(invalid='ignore'): + if not np.all(np.isfinite(x)): + raise ValueError('Yeo-Johnson input must be finite.') + if np.all(x == 0): + return 1.0 + if brack is not None: + return optimize.brent(_neg_llf, brack=brack, args=(x,)) + x = np.asarray(x) + dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64 + # Allow values up to 20 times the maximum observed value to be safely + # transformed without over- or underflow. + log1p_max_x = np.log1p(20 * np.max(np.abs(x))) + # Use half of floating point's exponent range to allow safe computation + # of the variance of the transformed data. + log_eps = np.log(np.finfo(dtype).eps) + log_tiny_float = (np.log(np.finfo(dtype).tiny) - log_eps) / 2 + log_max_float = (np.log(np.finfo(dtype).max) + log_eps) / 2 + # Compute the bounds by approximating the inverse of the Yeo-Johnson + # transform on the smallest and largest floating point exponents, given + # the largest data we expect to observe. See [1] for further details. + # [1] https://github.com/scipy/scipy/pull/18852#issuecomment-1630286174 + lb = log_tiny_float / log1p_max_x + ub = log_max_float / log1p_max_x + # Convert the bounds if all or some of the data is negative. + if np.all(x < 0): + lb, ub = 2 - ub, 2 - lb + elif np.any(x < 0): + lb, ub = max(2 - ub, lb), min(2 - lb, ub) + # Match `optimize.brent`'s tolerance. + tol_brent = 1.48e-08 + return optimize.fminbound(_neg_llf, lb, ub, args=(x,), xtol=tol_brent) + + +def yeojohnson_normplot(x, la, lb, plot=None, N=80): + """Compute parameters for a Yeo-Johnson normality plot, optionally show it. + + A Yeo-Johnson normality plot shows graphically what the best + transformation parameter is to use in `yeojohnson` to obtain a + distribution that is close to normal. + + Parameters + ---------- + x : array_like + Input array. + la, lb : scalar + The lower and upper bounds for the ``lmbda`` values to pass to + `yeojohnson` for Yeo-Johnson transformations. These are also the + limits of the horizontal axis of the plot if that is generated. + plot : object, optional + If given, plots the quantiles and least squares fit. + `plot` is an object that has to have methods "plot" and "text". + The `matplotlib.pyplot` module or a Matplotlib Axes object can be used, + or a custom object with the same methods. + Default is None, which means that no plot is created. + N : int, optional + Number of points on the horizontal axis (equally distributed from + `la` to `lb`). + + Returns + ------- + lmbdas : ndarray + The ``lmbda`` values for which a Yeo-Johnson transform was done. + ppcc : ndarray + Probability Plot Correlation Coefficient, as obtained from `probplot` + when fitting the Box-Cox transformed input `x` against a normal + distribution. + + See Also + -------- + probplot, yeojohnson, yeojohnson_normmax, yeojohnson_llf, ppcc_max + + Notes + ----- + Even if `plot` is given, the figure is not shown or saved by + `boxcox_normplot`; ``plt.show()`` or ``plt.savefig('figname.png')`` + should be used after calling `probplot`. + + .. versionadded:: 1.2.0 + + Examples + -------- + >>> from scipy import stats + >>> import matplotlib.pyplot as plt + + Generate some non-normally distributed data, and create a Yeo-Johnson plot: + + >>> x = stats.loggamma.rvs(5, size=500) + 5 + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> prob = stats.yeojohnson_normplot(x, -20, 20, plot=ax) + + Determine and plot the optimal ``lmbda`` to transform ``x`` and plot it in + the same plot: + + >>> _, maxlog = stats.yeojohnson(x) + >>> ax.axvline(maxlog, color='r') + + >>> plt.show() + + """ + return _normplot('yeojohnson', x, la, lb, plot, N) + + +ShapiroResult = namedtuple('ShapiroResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(ShapiroResult, n_samples=1, too_small=2, default_axis=None) +def shapiro(x): + r"""Perform the Shapiro-Wilk test for normality. + + The Shapiro-Wilk test tests the null hypothesis that the + data was drawn from a normal distribution. + + Parameters + ---------- + x : array_like + Array of sample data. Must contain at least three observations. + + Returns + ------- + statistic : float + The test statistic. + p-value : float + The p-value for the hypothesis test. + + See Also + -------- + anderson : The Anderson-Darling test for normality + kstest : The Kolmogorov-Smirnov test for goodness of fit. + :ref:`hypothesis_shapiro` : Extended example + + Notes + ----- + The algorithm used is described in [4]_ but censoring parameters as + described are not implemented. For N > 5000 the W test statistic is + accurate, but the p-value may not be. + + References + ---------- + .. [1] https://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm + :doi:`10.18434/M32189` + .. [2] Shapiro, S. S. & Wilk, M.B, "An analysis of variance test for + normality (complete samples)", Biometrika, 1965, Vol. 52, + pp. 591-611, :doi:`10.2307/2333709` + .. [3] Razali, N. M. & Wah, Y. B., "Power comparisons of Shapiro-Wilk, + Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests", Journal + of Statistical Modeling and Analytics, 2011, Vol. 2, pp. 21-33. + .. [4] Royston P., "Remark AS R94: A Remark on Algorithm AS 181: The + W-test for Normality", 1995, Applied Statistics, Vol. 44, + :doi:`10.2307/2986146` + + Examples + -------- + + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> x = stats.norm.rvs(loc=5, scale=3, size=100, random_state=rng) + >>> shapiro_test = stats.shapiro(x) + >>> shapiro_test + ShapiroResult(statistic=0.9813305735588074, pvalue=0.16855233907699585) + >>> shapiro_test.statistic + 0.9813305735588074 + >>> shapiro_test.pvalue + 0.16855233907699585 + + For a more detailed example, see :ref:`hypothesis_shapiro`. + """ + x = np.ravel(x).astype(np.float64) + + N = len(x) + if N < 3: + raise ValueError("Data must be at least length 3.") + + a = zeros(N//2, dtype=np.float64) + init = 0 + + y = sort(x) + y -= x[N//2] # subtract the median (or a nearby value); see gh-15777 + + w, pw, ifault = swilk(y, a, init) + if ifault not in [0, 2]: + warnings.warn("scipy.stats.shapiro: Input data has range zero. The" + " results may not be accurate.", stacklevel=2) + if N > 5000: + warnings.warn("scipy.stats.shapiro: For N > 5000, computed p-value " + f"may not be accurate. Current N is {N}.", + stacklevel=2) + + # `w` and `pw` are always Python floats, which are double precision. + # We want to ensure that they are NumPy floats, so until dtypes are + # respected, we can explicitly convert each to float64 (faster than + # `np.array([w, pw])`). + return ShapiroResult(np.float64(w), np.float64(pw)) + + +# Values from Stephens, M A, "EDF Statistics for Goodness of Fit and +# Some Comparisons", Journal of the American Statistical +# Association, Vol. 69, Issue 347, Sept. 1974, pp 730-737 +_Avals_norm = array([0.576, 0.656, 0.787, 0.918, 1.092]) +_Avals_expon = array([0.922, 1.078, 1.341, 1.606, 1.957]) +# From Stephens, M A, "Goodness of Fit for the Extreme Value Distribution", +# Biometrika, Vol. 64, Issue 3, Dec. 1977, pp 583-588. +_Avals_gumbel = array([0.474, 0.637, 0.757, 0.877, 1.038]) +# From Stephens, M A, "Tests of Fit for the Logistic Distribution Based +# on the Empirical Distribution Function.", Biometrika, +# Vol. 66, Issue 3, Dec. 1979, pp 591-595. +_Avals_logistic = array([0.426, 0.563, 0.660, 0.769, 0.906, 1.010]) +# From Richard A. Lockhart and Michael A. Stephens "Estimation and Tests of +# Fit for the Three-Parameter Weibull Distribution" +# Journal of the Royal Statistical Society.Series B(Methodological) +# Vol. 56, No. 3 (1994), pp. 491-500, table 1. Keys are c*100 +_Avals_weibull = [[0.292, 0.395, 0.467, 0.522, 0.617, 0.711, 0.836, 0.931], + [0.295, 0.399, 0.471, 0.527, 0.623, 0.719, 0.845, 0.941], + [0.298, 0.403, 0.476, 0.534, 0.631, 0.728, 0.856, 0.954], + [0.301, 0.408, 0.483, 0.541, 0.640, 0.738, 0.869, 0.969], + [0.305, 0.414, 0.490, 0.549, 0.650, 0.751, 0.885, 0.986], + [0.309, 0.421, 0.498, 0.559, 0.662, 0.765, 0.902, 1.007], + [0.314, 0.429, 0.508, 0.570, 0.676, 0.782, 0.923, 1.030], + [0.320, 0.438, 0.519, 0.583, 0.692, 0.802, 0.947, 1.057], + [0.327, 0.448, 0.532, 0.598, 0.711, 0.824, 0.974, 1.089], + [0.334, 0.469, 0.547, 0.615, 0.732, 0.850, 1.006, 1.125], + [0.342, 0.472, 0.563, 0.636, 0.757, 0.879, 1.043, 1.167]] +_Avals_weibull = np.array(_Avals_weibull) +_cvals_weibull = np.linspace(0, 0.5, 11) +_get_As_weibull = interpolate.interp1d(_cvals_weibull, _Avals_weibull.T, + kind='linear', bounds_error=False, + fill_value=_Avals_weibull[-1]) + + +def _weibull_fit_check(params, x): + # Refine the fit returned by `weibull_min.fit` to ensure that the first + # order necessary conditions are satisfied. If not, raise an error. + # Here, use `m` for the shape parameter to be consistent with [7] + # and avoid confusion with `c` as defined in [7]. + n = len(x) + m, u, s = params + + def dnllf_dm(m, u): + # Partial w.r.t. shape w/ optimal scale. See [7] Equation 5. + xu = x-u + return (1/m - (xu**m*np.log(xu)).sum()/(xu**m).sum() + + np.log(xu).sum()/n) + + def dnllf_du(m, u): + # Partial w.r.t. loc w/ optimal scale. See [7] Equation 6. + xu = x-u + return (m-1)/m*(xu**-1).sum() - n*(xu**(m-1)).sum()/(xu**m).sum() + + def get_scale(m, u): + # Partial w.r.t. scale solved in terms of shape and location. + # See [7] Equation 7. + return ((x-u)**m/n).sum()**(1/m) + + def dnllf(params): + # Partial derivatives of the NLLF w.r.t. parameters, i.e. + # first order necessary conditions for MLE fit. + return [dnllf_dm(*params), dnllf_du(*params)] + + suggestion = ("Maximum likelihood estimation is known to be challenging " + "for the three-parameter Weibull distribution. Consider " + "performing a custom goodness-of-fit test using " + "`scipy.stats.monte_carlo_test`.") + + if np.allclose(u, np.min(x)) or m < 1: + # The critical values provided by [7] don't seem to control the + # Type I error rate in this case. Error out. + message = ("Maximum likelihood estimation has converged to " + "a solution in which the location is equal to the minimum " + "of the data, the shape parameter is less than 2, or both. " + "The table of critical values in [7] does not " + "include this case. " + suggestion) + raise ValueError(message) + + try: + # Refine the MLE / verify that first-order necessary conditions are + # satisfied. If so, the critical values provided in [7] seem reliable. + with np.errstate(over='raise', invalid='raise'): + res = optimize.root(dnllf, params[:-1]) + + message = ("Solution of MLE first-order conditions failed: " + f"{res.message}. `anderson` cannot continue. " + suggestion) + if not res.success: + raise ValueError(message) + + except (FloatingPointError, ValueError) as e: + message = ("An error occurred while fitting the Weibull distribution " + "to the data, so `anderson` cannot continue. " + suggestion) + raise ValueError(message) from e + + m, u = res.x + s = get_scale(m, u) + return m, u, s + + +AndersonResult = _make_tuple_bunch('AndersonResult', + ['statistic', 'critical_values', + 'significance_level'], ['fit_result']) + + +def anderson(x, dist='norm'): + """Anderson-Darling test for data coming from a particular distribution. + + The Anderson-Darling test tests the null hypothesis that a sample is + drawn from a population that follows a particular distribution. + For the Anderson-Darling test, the critical values depend on + which distribution is being tested against. This function works + for normal, exponential, logistic, weibull_min, or Gumbel (Extreme Value + Type I) distributions. + + Parameters + ---------- + x : array_like + Array of sample data. + dist : {'norm', 'expon', 'logistic', 'gumbel', 'gumbel_l', 'gumbel_r', 'extreme1', 'weibull_min'}, optional + The type of distribution to test against. The default is 'norm'. + The names 'extreme1', 'gumbel_l' and 'gumbel' are synonyms for the + same distribution. + + Returns + ------- + result : AndersonResult + An object with the following attributes: + + statistic : float + The Anderson-Darling test statistic. + critical_values : list + The critical values for this distribution. + significance_level : list + The significance levels for the corresponding critical values + in percents. The function returns critical values for a + differing set of significance levels depending on the + distribution that is being tested against. + fit_result : `~scipy.stats._result_classes.FitResult` + An object containing the results of fitting the distribution to + the data. + + See Also + -------- + kstest : The Kolmogorov-Smirnov test for goodness-of-fit. + + Notes + ----- + Critical values provided are for the following significance levels: + + normal/exponential + 15%, 10%, 5%, 2.5%, 1% + logistic + 25%, 10%, 5%, 2.5%, 1%, 0.5% + gumbel_l / gumbel_r + 25%, 10%, 5%, 2.5%, 1% + weibull_min + 50%, 25%, 15%, 10%, 5%, 2.5%, 1%, 0.5% + + If the returned statistic is larger than these critical values then + for the corresponding significance level, the null hypothesis that + the data come from the chosen distribution can be rejected. + The returned statistic is referred to as 'A2' in the references. + + For `weibull_min`, maximum likelihood estimation is known to be + challenging. If the test returns successfully, then the first order + conditions for a maximum likelihood estimate have been verified and + the critical values correspond relatively well to the significance levels, + provided that the sample is sufficiently large (>10 observations [7]). + However, for some data - especially data with no left tail - `anderson` + is likely to result in an error message. In this case, consider + performing a custom goodness of fit test using + `scipy.stats.monte_carlo_test`. + + References + ---------- + .. [1] https://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm + .. [2] Stephens, M. A. (1974). EDF Statistics for Goodness of Fit and + Some Comparisons, Journal of the American Statistical Association, + Vol. 69, pp. 730-737. + .. [3] Stephens, M. A. (1976). Asymptotic Results for Goodness-of-Fit + Statistics with Unknown Parameters, Annals of Statistics, Vol. 4, + pp. 357-369. + .. [4] Stephens, M. A. (1977). Goodness of Fit for the Extreme Value + Distribution, Biometrika, Vol. 64, pp. 583-588. + .. [5] Stephens, M. A. (1977). Goodness of Fit with Special Reference + to Tests for Exponentiality , Technical Report No. 262, + Department of Statistics, Stanford University, Stanford, CA. + .. [6] Stephens, M. A. (1979). Tests of Fit for the Logistic Distribution + Based on the Empirical Distribution Function, Biometrika, Vol. 66, + pp. 591-595. + .. [7] Richard A. Lockhart and Michael A. Stephens "Estimation and Tests of + Fit for the Three-Parameter Weibull Distribution" + Journal of the Royal Statistical Society.Series B(Methodological) + Vol. 56, No. 3 (1994), pp. 491-500, Table 0. + + Examples + -------- + Test the null hypothesis that a random sample was drawn from a normal + distribution (with unspecified mean and standard deviation). + + >>> import numpy as np + >>> from scipy.stats import anderson + >>> rng = np.random.default_rng() + >>> data = rng.random(size=35) + >>> res = anderson(data) + >>> res.statistic + 0.8398018749744764 + >>> res.critical_values + array([0.527, 0.6 , 0.719, 0.839, 0.998]) + >>> res.significance_level + array([15. , 10. , 5. , 2.5, 1. ]) + + The value of the statistic (barely) exceeds the critical value associated + with a significance level of 2.5%, so the null hypothesis may be rejected + at a significance level of 2.5%, but not at a significance level of 1%. + + """ # numpy/numpydoc#87 # noqa: E501 + dist = dist.lower() + if dist in {'extreme1', 'gumbel'}: + dist = 'gumbel_l' + dists = {'norm', 'expon', 'gumbel_l', + 'gumbel_r', 'logistic', 'weibull_min'} + + if dist not in dists: + raise ValueError(f"Invalid distribution; dist must be in {dists}.") + y = sort(x) + xbar = np.mean(x, axis=0) + N = len(y) + if dist == 'norm': + s = np.std(x, ddof=1, axis=0) + w = (y - xbar) / s + fit_params = xbar, s + logcdf = distributions.norm.logcdf(w) + logsf = distributions.norm.logsf(w) + sig = array([15, 10, 5, 2.5, 1]) + critical = around(_Avals_norm / (1.0 + 4.0/N - 25.0/N/N), 3) + elif dist == 'expon': + w = y / xbar + fit_params = 0, xbar + logcdf = distributions.expon.logcdf(w) + logsf = distributions.expon.logsf(w) + sig = array([15, 10, 5, 2.5, 1]) + critical = around(_Avals_expon / (1.0 + 0.6/N), 3) + elif dist == 'logistic': + def rootfunc(ab, xj, N): + a, b = ab + tmp = (xj - a) / b + tmp2 = exp(tmp) + val = [np.sum(1.0/(1+tmp2), axis=0) - 0.5*N, + np.sum(tmp*(1.0-tmp2)/(1+tmp2), axis=0) + N] + return array(val) + + sol0 = array([xbar, np.std(x, ddof=1, axis=0)]) + sol = optimize.fsolve(rootfunc, sol0, args=(x, N), xtol=1e-5) + w = (y - sol[0]) / sol[1] + fit_params = sol + logcdf = distributions.logistic.logcdf(w) + logsf = distributions.logistic.logsf(w) + sig = array([25, 10, 5, 2.5, 1, 0.5]) + critical = around(_Avals_logistic / (1.0 + 0.25/N), 3) + elif dist == 'gumbel_r': + xbar, s = distributions.gumbel_r.fit(x) + w = (y - xbar) / s + fit_params = xbar, s + logcdf = distributions.gumbel_r.logcdf(w) + logsf = distributions.gumbel_r.logsf(w) + sig = array([25, 10, 5, 2.5, 1]) + critical = around(_Avals_gumbel / (1.0 + 0.2/sqrt(N)), 3) + elif dist == 'gumbel_l': + xbar, s = distributions.gumbel_l.fit(x) + w = (y - xbar) / s + fit_params = xbar, s + logcdf = distributions.gumbel_l.logcdf(w) + logsf = distributions.gumbel_l.logsf(w) + sig = array([25, 10, 5, 2.5, 1]) + critical = around(_Avals_gumbel / (1.0 + 0.2/sqrt(N)), 3) + elif dist == 'weibull_min': + message = ("Critical values of the test statistic are given for the " + "asymptotic distribution. These may not be accurate for " + "samples with fewer than 10 observations. Consider using " + "`scipy.stats.monte_carlo_test`.") + if N < 10: + warnings.warn(message, stacklevel=2) + # [7] writes our 'c' as 'm', and they write `c = 1/m`. Use their names. + m, loc, scale = distributions.weibull_min.fit(y) + m, loc, scale = _weibull_fit_check((m, loc, scale), y) + fit_params = m, loc, scale + logcdf = stats.weibull_min(*fit_params).logcdf(y) + logsf = stats.weibull_min(*fit_params).logsf(y) + c = 1 / m # m and c are as used in [7] + sig = array([0.5, 0.75, 0.85, 0.9, 0.95, 0.975, 0.99, 0.995]) + critical = _get_As_weibull(c) + # Goodness-of-fit tests should only be used to provide evidence + # _against_ the null hypothesis. Be conservative and round up. + critical = np.round(critical + 0.0005, decimals=3) + + i = arange(1, N + 1) + A2 = -N - np.sum((2*i - 1.0) / N * (logcdf + logsf[::-1]), axis=0) + + # FitResult initializer expects an optimize result, so let's work with it + message = '`anderson` successfully fit the distribution to the data.' + res = optimize.OptimizeResult(success=True, message=message) + res.x = np.array(fit_params) + fit_result = FitResult(getattr(distributions, dist), y, + discrete=False, res=res) + + return AndersonResult(A2, critical, sig, fit_result=fit_result) + + +def _anderson_ksamp_midrank(samples, Z, Zstar, k, n, N): + """Compute A2akN equation 7 of Scholz and Stephens. + + Parameters + ---------- + samples : sequence of 1-D array_like + Array of sample arrays. + Z : array_like + Sorted array of all observations. + Zstar : array_like + Sorted array of unique observations. + k : int + Number of samples. + n : array_like + Number of observations in each sample. + N : int + Total number of observations. + + Returns + ------- + A2aKN : float + The A2aKN statistics of Scholz and Stephens 1987. + + """ + A2akN = 0. + Z_ssorted_left = Z.searchsorted(Zstar, 'left') + if N == Zstar.size: + lj = 1. + else: + lj = Z.searchsorted(Zstar, 'right') - Z_ssorted_left + Bj = Z_ssorted_left + lj / 2. + for i in arange(0, k): + s = np.sort(samples[i]) + s_ssorted_right = s.searchsorted(Zstar, side='right') + Mij = s_ssorted_right.astype(float) + fij = s_ssorted_right - s.searchsorted(Zstar, 'left') + Mij -= fij / 2. + inner = lj / float(N) * (N*Mij - Bj*n[i])**2 / (Bj*(N - Bj) - N*lj/4.) + A2akN += inner.sum() / n[i] + A2akN *= (N - 1.) / N + return A2akN + + +def _anderson_ksamp_right(samples, Z, Zstar, k, n, N): + """Compute A2akN equation 6 of Scholz & Stephens. + + Parameters + ---------- + samples : sequence of 1-D array_like + Array of sample arrays. + Z : array_like + Sorted array of all observations. + Zstar : array_like + Sorted array of unique observations. + k : int + Number of samples. + n : array_like + Number of observations in each sample. + N : int + Total number of observations. + + Returns + ------- + A2KN : float + The A2KN statistics of Scholz and Stephens 1987. + + """ + A2kN = 0. + lj = Z.searchsorted(Zstar[:-1], 'right') - Z.searchsorted(Zstar[:-1], + 'left') + Bj = lj.cumsum() + for i in arange(0, k): + s = np.sort(samples[i]) + Mij = s.searchsorted(Zstar[:-1], side='right') + inner = lj / float(N) * (N * Mij - Bj * n[i])**2 / (Bj * (N - Bj)) + A2kN += inner.sum() / n[i] + return A2kN + + +Anderson_ksampResult = _make_tuple_bunch( + 'Anderson_ksampResult', + ['statistic', 'critical_values', 'pvalue'], [] +) + + +def anderson_ksamp(samples, midrank=True, *, method=None): + """The Anderson-Darling test for k-samples. + + The k-sample Anderson-Darling test is a modification of the + one-sample Anderson-Darling test. It tests the null hypothesis + that k-samples are drawn from the same population without having + to specify the distribution function of that population. The + critical values depend on the number of samples. + + Parameters + ---------- + samples : sequence of 1-D array_like + Array of sample data in arrays. + midrank : bool, optional + Type of Anderson-Darling test which is computed. Default + (True) is the midrank test applicable to continuous and + discrete populations. If False, the right side empirical + distribution is used. + method : PermutationMethod, optional + Defines the method used to compute the p-value. If `method` is an + instance of `PermutationMethod`, the p-value is computed using + `scipy.stats.permutation_test` with the provided configuration options + and other appropriate settings. Otherwise, the p-value is interpolated + from tabulated values. + + Returns + ------- + res : Anderson_ksampResult + An object containing attributes: + + statistic : float + Normalized k-sample Anderson-Darling test statistic. + critical_values : array + The critical values for significance levels 25%, 10%, 5%, 2.5%, 1%, + 0.5%, 0.1%. + pvalue : float + The approximate p-value of the test. If `method` is not + provided, the value is floored / capped at 0.1% / 25%. + + Raises + ------ + ValueError + If fewer than 2 samples are provided, a sample is empty, or no + distinct observations are in the samples. + + See Also + -------- + ks_2samp : 2 sample Kolmogorov-Smirnov test + anderson : 1 sample Anderson-Darling test + + Notes + ----- + [1]_ defines three versions of the k-sample Anderson-Darling test: + one for continuous distributions and two for discrete + distributions, in which ties between samples may occur. The + default of this routine is to compute the version based on the + midrank empirical distribution function. This test is applicable + to continuous and discrete data. If midrank is set to False, the + right side empirical distribution is used for a test for discrete + data. According to [1]_, the two discrete test statistics differ + only slightly if a few collisions due to round-off errors occur in + the test not adjusted for ties between samples. + + The critical values corresponding to the significance levels from 0.01 + to 0.25 are taken from [1]_. p-values are floored / capped + at 0.1% / 25%. Since the range of critical values might be extended in + future releases, it is recommended not to test ``p == 0.25``, but rather + ``p >= 0.25`` (analogously for the lower bound). + + .. versionadded:: 0.14.0 + + References + ---------- + .. [1] Scholz, F. W and Stephens, M. A. (1987), K-Sample + Anderson-Darling Tests, Journal of the American Statistical + Association, Vol. 82, pp. 918-924. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> res = stats.anderson_ksamp([rng.normal(size=50), + ... rng.normal(loc=0.5, size=30)]) + >>> res.statistic, res.pvalue + (1.974403288713695, 0.04991293614572478) + >>> res.critical_values + array([0.325, 1.226, 1.961, 2.718, 3.752, 4.592, 6.546]) + + The null hypothesis that the two random samples come from the same + distribution can be rejected at the 5% level because the returned + test value is greater than the critical value for 5% (1.961) but + not at the 2.5% level. The interpolation gives an approximate + p-value of 4.99%. + + >>> samples = [rng.normal(size=50), rng.normal(size=30), + ... rng.normal(size=20)] + >>> res = stats.anderson_ksamp(samples) + >>> res.statistic, res.pvalue + (-0.29103725200789504, 0.25) + >>> res.critical_values + array([ 0.44925884, 1.3052767 , 1.9434184 , 2.57696569, 3.41634856, + 4.07210043, 5.56419101]) + + The null hypothesis cannot be rejected for three samples from an + identical distribution. The reported p-value (25%) has been capped and + may not be very accurate (since it corresponds to the value 0.449 + whereas the statistic is -0.291). + + In such cases where the p-value is capped or when sample sizes are + small, a permutation test may be more accurate. + + >>> method = stats.PermutationMethod(n_resamples=9999, random_state=rng) + >>> res = stats.anderson_ksamp(samples, method=method) + >>> res.pvalue + 0.5254 + + """ + k = len(samples) + if (k < 2): + raise ValueError("anderson_ksamp needs at least two samples") + + samples = list(map(np.asarray, samples)) + Z = np.sort(np.hstack(samples)) + N = Z.size + Zstar = np.unique(Z) + if Zstar.size < 2: + raise ValueError("anderson_ksamp needs more than one distinct " + "observation") + + n = np.array([sample.size for sample in samples]) + if np.any(n == 0): + raise ValueError("anderson_ksamp encountered sample without " + "observations") + + if midrank: + A2kN_fun = _anderson_ksamp_midrank + else: + A2kN_fun = _anderson_ksamp_right + A2kN = A2kN_fun(samples, Z, Zstar, k, n, N) + + def statistic(*samples): + return A2kN_fun(samples, Z, Zstar, k, n, N) + + if method is not None: + res = stats.permutation_test(samples, statistic, **method._asdict(), + alternative='greater') + + H = (1. / n).sum() + hs_cs = (1. / arange(N - 1, 1, -1)).cumsum() + h = hs_cs[-1] + 1 + g = (hs_cs / arange(2, N)).sum() + + a = (4*g - 6) * (k - 1) + (10 - 6*g)*H + b = (2*g - 4)*k**2 + 8*h*k + (2*g - 14*h - 4)*H - 8*h + 4*g - 6 + c = (6*h + 2*g - 2)*k**2 + (4*h - 4*g + 6)*k + (2*h - 6)*H + 4*h + d = (2*h + 6)*k**2 - 4*h*k + sigmasq = (a*N**3 + b*N**2 + c*N + d) / ((N - 1.) * (N - 2.) * (N - 3.)) + m = k - 1 + A2 = (A2kN - m) / math.sqrt(sigmasq) + + # The b_i values are the interpolation coefficients from Table 2 + # of Scholz and Stephens 1987 + b0 = np.array([0.675, 1.281, 1.645, 1.96, 2.326, 2.573, 3.085]) + b1 = np.array([-0.245, 0.25, 0.678, 1.149, 1.822, 2.364, 3.615]) + b2 = np.array([-0.105, -0.305, -0.362, -0.391, -0.396, -0.345, -0.154]) + critical = b0 + b1 / math.sqrt(m) + b2 / m + + sig = np.array([0.25, 0.1, 0.05, 0.025, 0.01, 0.005, 0.001]) + + if A2 < critical.min() and method is None: + p = sig.max() + msg = (f"p-value capped: true value larger than {p}. Consider " + "specifying `method` " + "(e.g. `method=stats.PermutationMethod()`.)") + warnings.warn(msg, stacklevel=2) + elif A2 > critical.max() and method is None: + p = sig.min() + msg = (f"p-value floored: true value smaller than {p}. Consider " + "specifying `method` " + "(e.g. `method=stats.PermutationMethod()`.)") + warnings.warn(msg, stacklevel=2) + elif method is None: + # interpolation of probit of significance level + pf = np.polyfit(critical, log(sig), 2) + p = math.exp(np.polyval(pf, A2)) + else: + p = res.pvalue if method is not None else p + + # create result object with alias for backward compatibility + res = Anderson_ksampResult(A2, critical, p) + res.significance_level = p + return res + + +AnsariResult = namedtuple('AnsariResult', ('statistic', 'pvalue')) + + +class _ABW: + """Distribution of Ansari-Bradley W-statistic under the null hypothesis.""" + # TODO: calculate exact distribution considering ties + # We could avoid summing over more than half the frequencies, + # but initially it doesn't seem worth the extra complexity + + def __init__(self): + """Minimal initializer.""" + self.m = None + self.n = None + self.astart = None + self.total = None + self.freqs = None + + def _recalc(self, n, m): + """When necessary, recalculate exact distribution.""" + if n != self.n or m != self.m: + self.n, self.m = n, m + # distribution is NOT symmetric when m + n is odd + # n is len(x), m is len(y), and ratio of scales is defined x/y + astart, a1, _ = gscale(n, m) + self.astart = astart # minimum value of statistic + # Exact distribution of test statistic under null hypothesis + # expressed as frequencies/counts/integers to maintain precision. + # Stored as floats to avoid overflow of sums. + self.freqs = a1.astype(np.float64) + self.total = self.freqs.sum() # could calculate from m and n + # probability mass is self.freqs / self.total; + + def pmf(self, k, n, m): + """Probability mass function.""" + self._recalc(n, m) + # The convention here is that PMF at k = 12.5 is the same as at k = 12, + # -> use `floor` in case of ties. + ind = np.floor(k - self.astart).astype(int) + return self.freqs[ind] / self.total + + def cdf(self, k, n, m): + """Cumulative distribution function.""" + self._recalc(n, m) + # Null distribution derived without considering ties is + # approximate. Round down to avoid Type I error. + ind = np.ceil(k - self.astart).astype(int) + return self.freqs[:ind+1].sum() / self.total + + def sf(self, k, n, m): + """Survival function.""" + self._recalc(n, m) + # Null distribution derived without considering ties is + # approximate. Round down to avoid Type I error. + ind = np.floor(k - self.astart).astype(int) + return self.freqs[ind:].sum() / self.total + + +# Maintain state for faster repeat calls to ansari w/ method='exact' +# _ABW() is calculated once per thread and stored as an attribute on +# this thread-local variable inside ansari(). +_abw_state = threading.local() + + +@_axis_nan_policy_factory(AnsariResult, n_samples=2) +def ansari(x, y, alternative='two-sided'): + """Perform the Ansari-Bradley test for equal scale parameters. + + The Ansari-Bradley test ([1]_, [2]_) is a non-parametric test + for the equality of the scale parameter of the distributions + from which two samples were drawn. The null hypothesis states that + the ratio of the scale of the distribution underlying `x` to the scale + of the distribution underlying `y` is 1. + + Parameters + ---------- + x, y : array_like + Arrays of sample data. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the ratio of scales is not equal to 1. + * 'less': the ratio of scales is less than 1. + * 'greater': the ratio of scales is greater than 1. + + .. versionadded:: 1.7.0 + + Returns + ------- + statistic : float + The Ansari-Bradley test statistic. + pvalue : float + The p-value of the hypothesis test. + + See Also + -------- + fligner : A non-parametric test for the equality of k variances + mood : A non-parametric test for the equality of two scale parameters + + Notes + ----- + The p-value given is exact when the sample sizes are both less than + 55 and there are no ties, otherwise a normal approximation for the + p-value is used. + + References + ---------- + .. [1] Ansari, A. R. and Bradley, R. A. (1960) Rank-sum tests for + dispersions, Annals of Mathematical Statistics, 31, 1174-1189. + .. [2] Sprent, Peter and N.C. Smeeton. Applied nonparametric + statistical methods. 3rd ed. Chapman and Hall/CRC. 2001. + Section 5.8.2. + .. [3] Nathaniel E. Helwig "Nonparametric Dispersion and Equality + Tests" at http://users.stat.umn.edu/~helwig/notes/npde-Notes.pdf + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import ansari + >>> rng = np.random.default_rng() + + For these examples, we'll create three random data sets. The first + two, with sizes 35 and 25, are drawn from a normal distribution with + mean 0 and standard deviation 2. The third data set has size 25 and + is drawn from a normal distribution with standard deviation 1.25. + + >>> x1 = rng.normal(loc=0, scale=2, size=35) + >>> x2 = rng.normal(loc=0, scale=2, size=25) + >>> x3 = rng.normal(loc=0, scale=1.25, size=25) + + First we apply `ansari` to `x1` and `x2`. These samples are drawn + from the same distribution, so we expect the Ansari-Bradley test + should not lead us to conclude that the scales of the distributions + are different. + + >>> ansari(x1, x2) + AnsariResult(statistic=541.0, pvalue=0.9762532927399098) + + With a p-value close to 1, we cannot conclude that there is a + significant difference in the scales (as expected). + + Now apply the test to `x1` and `x3`: + + >>> ansari(x1, x3) + AnsariResult(statistic=425.0, pvalue=0.0003087020407974518) + + The probability of observing such an extreme value of the statistic + under the null hypothesis of equal scales is only 0.03087%. We take this + as evidence against the null hypothesis in favor of the alternative: + the scales of the distributions from which the samples were drawn + are not equal. + + We can use the `alternative` parameter to perform a one-tailed test. + In the above example, the scale of `x1` is greater than `x3` and so + the ratio of scales of `x1` and `x3` is greater than 1. This means + that the p-value when ``alternative='greater'`` should be near 0 and + hence we should be able to reject the null hypothesis: + + >>> ansari(x1, x3, alternative='greater') + AnsariResult(statistic=425.0, pvalue=0.0001543510203987259) + + As we can see, the p-value is indeed quite low. Use of + ``alternative='less'`` should thus yield a large p-value: + + >>> ansari(x1, x3, alternative='less') + AnsariResult(statistic=425.0, pvalue=0.9998643258449039) + + """ + if alternative not in {'two-sided', 'greater', 'less'}: + raise ValueError("'alternative' must be 'two-sided'," + " 'greater', or 'less'.") + + if not hasattr(_abw_state, 'a'): + _abw_state.a = _ABW() + + x, y = asarray(x), asarray(y) + n = len(x) + m = len(y) + if m < 1: + raise ValueError("Not enough other observations.") + if n < 1: + raise ValueError("Not enough test observations.") + + N = m + n + xy = r_[x, y] # combine + rank = _stats_py.rankdata(xy) + symrank = amin(array((rank, N - rank + 1)), 0) + AB = np.sum(symrank[:n], axis=0) + uxy = unique(xy) + repeats = (len(uxy) != len(xy)) + exact = ((m < 55) and (n < 55) and not repeats) + if repeats and (m < 55 or n < 55): + warnings.warn("Ties preclude use of exact statistic.", stacklevel=2) + if exact: + if alternative == 'two-sided': + pval = 2.0 * np.minimum(_abw_state.a.cdf(AB, n, m), + _abw_state.a.sf(AB, n, m)) + elif alternative == 'greater': + # AB statistic is _smaller_ when ratio of scales is larger, + # so this is the opposite of the usual calculation + pval = _abw_state.a.cdf(AB, n, m) + else: + pval = _abw_state.a.sf(AB, n, m) + return AnsariResult(AB, min(1.0, pval)) + + # otherwise compute normal approximation + if N % 2: # N odd + mnAB = n * (N+1.0)**2 / 4.0 / N + varAB = n * m * (N+1.0) * (3+N**2) / (48.0 * N**2) + else: + mnAB = n * (N+2.0) / 4.0 + varAB = m * n * (N+2) * (N-2.0) / 48 / (N-1.0) + if repeats: # adjust variance estimates + # compute np.sum(tj * rj**2,axis=0) + fac = np.sum(symrank**2, axis=0) + if N % 2: # N odd + varAB = m * n * (16*N*fac - (N+1)**4) / (16.0 * N**2 * (N-1)) + else: # N even + varAB = m * n * (16*fac - N*(N+2)**2) / (16.0 * N * (N-1)) + + # Small values of AB indicate larger dispersion for the x sample. + # Large values of AB indicate larger dispersion for the y sample. + # This is opposite to the way we define the ratio of scales. see [1]_. + z = (mnAB - AB) / sqrt(varAB) + pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np) + return AnsariResult(AB[()], pvalue[()]) + + +BartlettResult = namedtuple('BartlettResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(BartlettResult, n_samples=None) +def bartlett(*samples, axis=0): + r"""Perform Bartlett's test for equal variances. + + Bartlett's test tests the null hypothesis that all input samples + are from populations with equal variances. For samples + from significantly non-normal populations, Levene's test + `levene` is more robust. + + Parameters + ---------- + sample1, sample2, ... : array_like + arrays of sample data. Only 1d arrays are accepted, they may have + different lengths. + + Returns + ------- + statistic : float + The test statistic. + pvalue : float + The p-value of the test. + + See Also + -------- + fligner : A non-parametric test for the equality of k variances + levene : A robust parametric test for equality of k variances + :ref:`hypothesis_bartlett` : Extended example + + Notes + ----- + Conover et al. (1981) examine many of the existing parametric and + nonparametric tests by extensive simulations and they conclude that the + tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be + superior in terms of robustness of departures from normality and power + ([3]_). + + References + ---------- + .. [1] https://www.itl.nist.gov/div898/handbook/eda/section3/eda357.htm + .. [2] Snedecor, George W. and Cochran, William G. (1989), Statistical + Methods, Eighth Edition, Iowa State University Press. + .. [3] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and + Hypothesis Testing based on Quadratic Inference Function. Technical + Report #99-03, Center for Likelihood Studies, Pennsylvania State + University. + .. [4] Bartlett, M. S. (1937). Properties of Sufficiency and Statistical + Tests. Proceedings of the Royal Society of London. Series A, + Mathematical and Physical Sciences, Vol. 160, No.901, pp. 268-282. + + Examples + -------- + + Test whether the lists `a`, `b` and `c` come from populations + with equal variances. + + >>> import numpy as np + >>> from scipy import stats + >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99] + >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05] + >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98] + >>> stat, p = stats.bartlett(a, b, c) + >>> p + 1.1254782518834628e-05 + + The very small p-value suggests that the populations do not have equal + variances. + + This is not surprising, given that the sample variance of `b` is much + larger than that of `a` and `c`: + + >>> [np.var(x, ddof=1) for x in [a, b, c]] + [0.007054444444444413, 0.13073888888888888, 0.008890000000000002] + + For a more detailed example, see :ref:`hypothesis_bartlett`. + """ + xp = array_namespace(*samples) + + k = len(samples) + if k < 2: + raise ValueError("Must enter at least two input sample vectors.") + + samples = _broadcast_arrays(samples, axis=axis, xp=xp) + samples = [xp_moveaxis_to_end(sample, axis, xp=xp) for sample in samples] + + Ni = [xp.asarray(sample.shape[-1], dtype=sample.dtype) for sample in samples] + Ni = [xp.broadcast_to(N, samples[0].shape[:-1]) for N in Ni] + ssq = [xp.var(sample, correction=1, axis=-1) for sample in samples] + Ni = [arr[xp.newaxis, ...] for arr in Ni] + ssq = [arr[xp.newaxis, ...] for arr in ssq] + Ni = xp.concat(Ni, axis=0) + ssq = xp.concat(ssq, axis=0) + # sum dtype can be removed when 2023.12 rules kick in + dtype = Ni.dtype + Ntot = xp.sum(Ni, axis=0, dtype=dtype) + spsq = xp.sum((Ni - 1)*ssq, axis=0, dtype=dtype) / (Ntot - k) + numer = ((Ntot - k) * xp.log(spsq) + - xp.sum((Ni - 1)*xp.log(ssq), axis=0, dtype=dtype)) + denom = (1 + 1/(3*(k - 1)) + * ((xp.sum(1/(Ni - 1), axis=0, dtype=dtype)) - 1/(Ntot - k))) + T = numer / denom + + chi2 = _SimpleChi2(xp.asarray(k-1)) + pvalue = _get_pvalue(T, chi2, alternative='greater', symmetric=False, xp=xp) + + T = xp.clip(T, min=0., max=xp.inf) + T = T[()] if T.ndim == 0 else T + pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue + + return BartlettResult(T, pvalue) + + +LeveneResult = namedtuple('LeveneResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(LeveneResult, n_samples=None) +def levene(*samples, center='median', proportiontocut=0.05): + r"""Perform Levene test for equal variances. + + The Levene test tests the null hypothesis that all input samples + are from populations with equal variances. Levene's test is an + alternative to Bartlett's test `bartlett` in the case where + there are significant deviations from normality. + + Parameters + ---------- + sample1, sample2, ... : array_like + The sample data, possibly with different lengths. Only one-dimensional + samples are accepted. + center : {'mean', 'median', 'trimmed'}, optional + Which function of the data to use in the test. The default + is 'median'. + proportiontocut : float, optional + When `center` is 'trimmed', this gives the proportion of data points + to cut from each end. (See `scipy.stats.trim_mean`.) + Default is 0.05. + + Returns + ------- + statistic : float + The test statistic. + pvalue : float + The p-value for the test. + + See Also + -------- + fligner : A non-parametric test for the equality of k variances + bartlett : A parametric test for equality of k variances in normal samples + :ref:`hypothesis_levene` : Extended example + + Notes + ----- + Three variations of Levene's test are possible. The possibilities + and their recommended usages are: + + * 'median' : Recommended for skewed (non-normal) distributions> + * 'mean' : Recommended for symmetric, moderate-tailed distributions. + * 'trimmed' : Recommended for heavy-tailed distributions. + + The test version using the mean was proposed in the original article + of Levene ([2]_) while the median and trimmed mean have been studied by + Brown and Forsythe ([3]_), sometimes also referred to as Brown-Forsythe + test. + + References + ---------- + .. [1] https://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm + .. [2] Levene, H. (1960). In Contributions to Probability and Statistics: + Essays in Honor of Harold Hotelling, I. Olkin et al. eds., + Stanford University Press, pp. 278-292. + .. [3] Brown, M. B. and Forsythe, A. B. (1974), Journal of the American + Statistical Association, 69, 364-367 + + Examples + -------- + + Test whether the lists `a`, `b` and `c` come from populations + with equal variances. + + >>> import numpy as np + >>> from scipy import stats + >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99] + >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05] + >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98] + >>> stat, p = stats.levene(a, b, c) + >>> p + 0.002431505967249681 + + The small p-value suggests that the populations do not have equal + variances. + + This is not surprising, given that the sample variance of `b` is much + larger than that of `a` and `c`: + + >>> [np.var(x, ddof=1) for x in [a, b, c]] + [0.007054444444444413, 0.13073888888888888, 0.008890000000000002] + + For a more detailed example, see :ref:`hypothesis_levene`. + """ + if center not in ['mean', 'median', 'trimmed']: + raise ValueError("center must be 'mean', 'median' or 'trimmed'.") + + k = len(samples) + if k < 2: + raise ValueError("Must enter at least two input sample vectors.") + + Ni = np.empty(k) + Yci = np.empty(k, 'd') + + if center == 'median': + + def func(x): + return np.median(x, axis=0) + + elif center == 'mean': + + def func(x): + return np.mean(x, axis=0) + + else: # center == 'trimmed' + samples = tuple(_stats_py.trimboth(np.sort(sample), proportiontocut) + for sample in samples) + + def func(x): + return np.mean(x, axis=0) + + for j in range(k): + Ni[j] = len(samples[j]) + Yci[j] = func(samples[j]) + Ntot = np.sum(Ni, axis=0) + + # compute Zij's + Zij = [None] * k + for i in range(k): + Zij[i] = abs(asarray(samples[i]) - Yci[i]) + + # compute Zbari + Zbari = np.empty(k, 'd') + Zbar = 0.0 + for i in range(k): + Zbari[i] = np.mean(Zij[i], axis=0) + Zbar += Zbari[i] * Ni[i] + + Zbar /= Ntot + numer = (Ntot - k) * np.sum(Ni * (Zbari - Zbar)**2, axis=0) + + # compute denom_variance + dvar = 0.0 + for i in range(k): + dvar += np.sum((Zij[i] - Zbari[i])**2, axis=0) + + denom = (k - 1.0) * dvar + + W = numer / denom + pval = distributions.f.sf(W, k-1, Ntot-k) # 1 - cdf + return LeveneResult(W, pval) + + +def _apply_func(x, g, func): + # g is list of indices into x + # separating x into different groups + # func should be applied over the groups + g = unique(r_[0, g, len(x)]) + output = [func(x[g[k]:g[k+1]]) for k in range(len(g) - 1)] + + return asarray(output) + + +FlignerResult = namedtuple('FlignerResult', ('statistic', 'pvalue')) + + +@_axis_nan_policy_factory(FlignerResult, n_samples=None) +def fligner(*samples, center='median', proportiontocut=0.05): + r"""Perform Fligner-Killeen test for equality of variance. + + Fligner's test tests the null hypothesis that all input samples + are from populations with equal variances. Fligner-Killeen's test is + distribution free when populations are identical [2]_. + + Parameters + ---------- + sample1, sample2, ... : array_like + Arrays of sample data. Need not be the same length. + center : {'mean', 'median', 'trimmed'}, optional + Keyword argument controlling which function of the data is used in + computing the test statistic. The default is 'median'. + proportiontocut : float, optional + When `center` is 'trimmed', this gives the proportion of data points + to cut from each end. (See `scipy.stats.trim_mean`.) + Default is 0.05. + + Returns + ------- + statistic : float + The test statistic. + pvalue : float + The p-value for the hypothesis test. + + See Also + -------- + bartlett : A parametric test for equality of k variances in normal samples + levene : A robust parametric test for equality of k variances + :ref:`hypothesis_fligner` : Extended example + + Notes + ----- + As with Levene's test there are three variants of Fligner's test that + differ by the measure of central tendency used in the test. See `levene` + for more information. + + Conover et al. (1981) examine many of the existing parametric and + nonparametric tests by extensive simulations and they conclude that the + tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be + superior in terms of robustness of departures from normality and power + [3]_. + + References + ---------- + .. [1] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and + Hypothesis Testing based on Quadratic Inference Function. Technical + Report #99-03, Center for Likelihood Studies, Pennsylvania State + University. + https://cecas.clemson.edu/~cspark/cv/paper/qif/draftqif2.pdf + .. [2] Fligner, M.A. and Killeen, T.J. (1976). Distribution-free two-sample + tests for scale. Journal of the American Statistical Association. + 71(353), 210-213. + .. [3] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and + Hypothesis Testing based on Quadratic Inference Function. Technical + Report #99-03, Center for Likelihood Studies, Pennsylvania State + University. + .. [4] Conover, W. J., Johnson, M. E. and Johnson M. M. (1981). A + comparative study of tests for homogeneity of variances, with + applications to the outer continental shelf bidding data. + Technometrics, 23(4), 351-361. + + Examples + -------- + + >>> import numpy as np + >>> from scipy import stats + + Test whether the lists `a`, `b` and `c` come from populations + with equal variances. + + >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99] + >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05] + >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98] + >>> stat, p = stats.fligner(a, b, c) + >>> p + 0.00450826080004775 + + The small p-value suggests that the populations do not have equal + variances. + + This is not surprising, given that the sample variance of `b` is much + larger than that of `a` and `c`: + + >>> [np.var(x, ddof=1) for x in [a, b, c]] + [0.007054444444444413, 0.13073888888888888, 0.008890000000000002] + + For a more detailed example, see :ref:`hypothesis_fligner`. + """ + if center not in ['mean', 'median', 'trimmed']: + raise ValueError("center must be 'mean', 'median' or 'trimmed'.") + + k = len(samples) + if k < 2: + raise ValueError("Must enter at least two input sample vectors.") + + # Handle empty input + for sample in samples: + if sample.size == 0: + NaN = _get_nan(*samples) + return FlignerResult(NaN, NaN) + + if center == 'median': + + def func(x): + return np.median(x, axis=0) + + elif center == 'mean': + + def func(x): + return np.mean(x, axis=0) + + else: # center == 'trimmed' + samples = tuple(_stats_py.trimboth(sample, proportiontocut) + for sample in samples) + + def func(x): + return np.mean(x, axis=0) + + Ni = asarray([len(samples[j]) for j in range(k)]) + Yci = asarray([func(samples[j]) for j in range(k)]) + Ntot = np.sum(Ni, axis=0) + # compute Zij's + Zij = [abs(asarray(samples[i]) - Yci[i]) for i in range(k)] + allZij = [] + g = [0] + for i in range(k): + allZij.extend(list(Zij[i])) + g.append(len(allZij)) + + ranks = _stats_py.rankdata(allZij) + sample = distributions.norm.ppf(ranks / (2*(Ntot + 1.0)) + 0.5) + + # compute Aibar + Aibar = _apply_func(sample, g, np.sum) / Ni + anbar = np.mean(sample, axis=0) + varsq = np.var(sample, axis=0, ddof=1) + statistic = np.sum(Ni * (asarray(Aibar) - anbar)**2.0, axis=0) / varsq + chi2 = _SimpleChi2(k-1) + pval = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=np) + return FlignerResult(statistic, pval) + + +@_axis_nan_policy_factory(lambda x1: (x1,), n_samples=4, n_outputs=1) +def _mood_inner_lc(xy, x, diffs, sorted_xy, n, m, N) -> float: + # Obtain the unique values and their frequencies from the pooled samples. + # "a_j, + b_j, = t_j, for j = 1, ... k" where `k` is the number of unique + # classes, and "[t]he number of values associated with the x's and y's in + # the jth class will be denoted by a_j, and b_j respectively." + # (Mielke, 312) + # Reuse previously computed sorted array and `diff` arrays to obtain the + # unique values and counts. Prepend `diffs` with a non-zero to indicate + # that the first element should be marked as not matching what preceded it. + diffs_prep = np.concatenate(([1], diffs)) + # Unique elements are where the was a difference between elements in the + # sorted array + uniques = sorted_xy[diffs_prep != 0] + # The count of each element is the bin size for each set of consecutive + # differences where the difference is zero. Replace nonzero differences + # with 1 and then use the cumulative sum to count the indices. + t = np.bincount(np.cumsum(np.asarray(diffs_prep != 0, dtype=int)))[1:] + k = len(uniques) + js = np.arange(1, k + 1, dtype=int) + # the `b` array mentioned in the paper is not used, outside of the + # calculation of `t`, so we do not need to calculate it separately. Here + # we calculate `a`. In plain language, `a[j]` is the number of values in + # `x` that equal `uniques[j]`. + sorted_xyx = np.sort(np.concatenate((xy, x))) + diffs = np.diff(sorted_xyx) + diffs_prep = np.concatenate(([1], diffs)) + diff_is_zero = np.asarray(diffs_prep != 0, dtype=int) + xyx_counts = np.bincount(np.cumsum(diff_is_zero))[1:] + a = xyx_counts - t + # "Define .. a_0 = b_0 = t_0 = S_0 = 0" (Mielke 312) so we shift `a` + # and `t` arrays over 1 to allow a first element of 0 to accommodate this + # indexing. + t = np.concatenate(([0], t)) + a = np.concatenate(([0], a)) + # S is built from `t`, so it does not need a preceding zero added on. + S = np.cumsum(t) + # define a copy of `S` with a prepending zero for later use to avoid + # the need for indexing. + S_i_m1 = np.concatenate(([0], S[:-1])) + + # Psi, as defined by the 6th unnumbered equation on page 313 (Mielke). + # Note that in the paper there is an error where the denominator `2` is + # squared when it should be the entire equation. + def psi(indicator): + return (indicator - (N + 1)/2)**2 + + # define summation range for use in calculation of phi, as seen in sum + # in the unnumbered equation on the bottom of page 312 (Mielke). + s_lower = S[js - 1] + 1 + s_upper = S[js] + 1 + phi_J = [np.arange(s_lower[idx], s_upper[idx]) for idx in range(k)] + + # for every range in the above array, determine the sum of psi(I) for + # every element in the range. Divide all the sums by `t`. Following the + # last unnumbered equation on page 312. + phis = [np.sum(psi(I_j)) for I_j in phi_J] / t[js] + + # `T` is equal to a[j] * phi[j], per the first unnumbered equation on + # page 312. `phis` is already in the order based on `js`, so we index + # into `a` with `js` as well. + T = sum(phis * a[js]) + + # The approximate statistic + E_0_T = n * (N * N - 1) / 12 + + varM = (m * n * (N + 1.0) * (N ** 2 - 4) / 180 - + m * n / (180 * N * (N - 1)) * np.sum( + t * (t**2 - 1) * (t**2 - 4 + (15 * (N - S - S_i_m1) ** 2)) + )) + + return ((T - E_0_T) / np.sqrt(varM),) + + +def _mood_too_small(samples, kwargs, axis=-1): + x, y = samples + n = x.shape[axis] + m = y.shape[axis] + N = m + n + return N < 3 + + +@_axis_nan_policy_factory(SignificanceResult, n_samples=2, too_small=_mood_too_small) +def mood(x, y, axis=0, alternative="two-sided"): + """Perform Mood's test for equal scale parameters. + + Mood's two-sample test for scale parameters is a non-parametric + test for the null hypothesis that two samples are drawn from the + same distribution with the same scale parameter. + + Parameters + ---------- + x, y : array_like + Arrays of sample data. There must be at least three observations + total. + axis : int, optional + The axis along which the samples are tested. `x` and `y` can be of + different length along `axis`. + If `axis` is None, `x` and `y` are flattened and the test is done on + all values in the flattened arrays. + alternative : {'two-sided', 'less', 'greater'}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + The following options are available: + + * 'two-sided': the scales of the distributions underlying `x` and `y` + are different. + * 'less': the scale of the distribution underlying `x` is less than + the scale of the distribution underlying `y`. + * 'greater': the scale of the distribution underlying `x` is greater + than the scale of the distribution underlying `y`. + + .. versionadded:: 1.7.0 + + Returns + ------- + res : SignificanceResult + An object containing attributes: + + statistic : scalar or ndarray + The z-score for the hypothesis test. For 1-D inputs a scalar is + returned. + pvalue : scalar ndarray + The p-value for the hypothesis test. + + See Also + -------- + fligner : A non-parametric test for the equality of k variances + ansari : A non-parametric test for the equality of 2 variances + bartlett : A parametric test for equality of k variances in normal samples + levene : A parametric test for equality of k variances + + Notes + ----- + The data are assumed to be drawn from probability distributions ``f(x)`` + and ``f(x/s) / s`` respectively, for some probability density function f. + The null hypothesis is that ``s == 1``. + + For multi-dimensional arrays, if the inputs are of shapes + ``(n0, n1, n2, n3)`` and ``(n0, m1, n2, n3)``, then if ``axis=1``, the + resulting z and p values will have shape ``(n0, n2, n3)``. Note that + ``n1`` and ``m1`` don't have to be equal, but the other dimensions do. + + References + ---------- + [1] Mielke, Paul W. "Note on Some Squared Rank Tests with Existing Ties." + Technometrics, vol. 9, no. 2, 1967, pp. 312-14. JSTOR, + https://doi.org/10.2307/1266427. Accessed 18 May 2022. + + Examples + -------- + >>> import numpy as np + >>> from scipy import stats + >>> rng = np.random.default_rng() + >>> x2 = rng.standard_normal((2, 45, 6, 7)) + >>> x1 = rng.standard_normal((2, 30, 6, 7)) + >>> res = stats.mood(x1, x2, axis=1) + >>> res.pvalue.shape + (2, 6, 7) + + Find the number of points where the difference in scale is not significant: + + >>> (res.pvalue > 0.1).sum() + 78 + + Perform the test with different scales: + + >>> x1 = rng.standard_normal((2, 30)) + >>> x2 = rng.standard_normal((2, 35)) * 10.0 + >>> stats.mood(x1, x2, axis=1) + SignificanceResult(statistic=array([-5.76174136, -6.12650783]), + pvalue=array([8.32505043e-09, 8.98287869e-10])) + + """ + x = np.asarray(x, dtype=float) + y = np.asarray(y, dtype=float) + + if axis < 0: + axis = x.ndim + axis + + # Determine shape of the result arrays + res_shape = tuple([x.shape[ax] for ax in range(len(x.shape)) if ax != axis]) + if not (res_shape == tuple([y.shape[ax] for ax in range(len(y.shape)) if + ax != axis])): + raise ValueError("Dimensions of x and y on all axes except `axis` " + "should match") + + n = x.shape[axis] + m = y.shape[axis] + N = m + n + if N < 3: + raise ValueError("Not enough observations.") + + xy = np.concatenate((x, y), axis=axis) + # determine if any of the samples contain ties + sorted_xy = np.sort(xy, axis=axis) + diffs = np.diff(sorted_xy, axis=axis) + if 0 in diffs: + z = np.asarray(_mood_inner_lc(xy, x, diffs, sorted_xy, n, m, N, + axis=axis)) + else: + if axis != 0: + xy = np.moveaxis(xy, axis, 0) + + xy = xy.reshape(xy.shape[0], -1) + # Generalized to the n-dimensional case by adding the axis argument, + # and using for loops, since rankdata is not vectorized. For improving + # performance consider vectorizing rankdata function. + all_ranks = np.empty_like(xy) + for j in range(xy.shape[1]): + all_ranks[:, j] = _stats_py.rankdata(xy[:, j]) + + Ri = all_ranks[:n] + M = np.sum((Ri - (N + 1.0) / 2) ** 2, axis=0) + # Approx stat. + mnM = n * (N * N - 1.0) / 12 + varM = m * n * (N + 1.0) * (N + 2) * (N - 2) / 180 + z = (M - mnM) / sqrt(varM) + pval = _get_pvalue(z, _SimpleNormal(), alternative, xp=np) + + if res_shape == (): + # Return scalars, not 0-D arrays + z = z[0] + pval = pval[0] + else: + z.shape = res_shape + pval.shape = res_shape + return SignificanceResult(z[()], pval[()]) + + +WilcoxonResult = _make_tuple_bunch('WilcoxonResult', ['statistic', 'pvalue']) + + +def wilcoxon_result_unpacker(res): + if hasattr(res, 'zstatistic'): + return res.statistic, res.pvalue, res.zstatistic + else: + return res.statistic, res.pvalue + + +def wilcoxon_result_object(statistic, pvalue, zstatistic=None): + res = WilcoxonResult(statistic, pvalue) + if zstatistic is not None: + res.zstatistic = zstatistic + return res + + +def wilcoxon_outputs(kwds): + method = kwds.get('method', 'auto') + if method == 'asymptotic': + return 3 + return 2 + + +@_rename_parameter("mode", "method") +@_axis_nan_policy_factory( + wilcoxon_result_object, paired=True, + n_samples=lambda kwds: 2 if kwds.get('y', None) is not None else 1, + result_to_tuple=wilcoxon_result_unpacker, n_outputs=wilcoxon_outputs, +) +def wilcoxon(x, y=None, zero_method="wilcox", correction=False, + alternative="two-sided", method='auto', *, axis=0): + """Calculate the Wilcoxon signed-rank test. + + The Wilcoxon signed-rank test tests the null hypothesis that two + related paired samples come from the same distribution. In particular, + it tests whether the distribution of the differences ``x - y`` is symmetric + about zero. It is a non-parametric version of the paired T-test. + + Parameters + ---------- + x : array_like + Either the first set of measurements (in which case ``y`` is the second + set of measurements), or the differences between two sets of + measurements (in which case ``y`` is not to be specified.) Must be + one-dimensional. + y : array_like, optional + Either the second set of measurements (if ``x`` is the first set of + measurements), or not specified (if ``x`` is the differences between + two sets of measurements.) Must be one-dimensional. + + .. warning:: + When `y` is provided, `wilcoxon` calculates the test statistic + based on the ranks of the absolute values of ``d = x - y``. + Roundoff error in the subtraction can result in elements of ``d`` + being assigned different ranks even when they would be tied with + exact arithmetic. Rather than passing `x` and `y` separately, + consider computing the difference ``x - y``, rounding as needed to + ensure that only truly unique elements are numerically distinct, + and passing the result as `x`, leaving `y` at the default (None). + + zero_method : {"wilcox", "pratt", "zsplit"}, optional + There are different conventions for handling pairs of observations + with equal values ("zero-differences", or "zeros"). + + * "wilcox": Discards all zero-differences (default); see [4]_. + * "pratt": Includes zero-differences in the ranking process, + but drops the ranks of the zeros (more conservative); see [3]_. + In this case, the normal approximation is adjusted as in [5]_. + * "zsplit": Includes zero-differences in the ranking process and + splits the zero rank between positive and negative ones. + + correction : bool, optional + If True, apply continuity correction by adjusting the Wilcoxon rank + statistic by 0.5 towards the mean value when computing the + z-statistic if a normal approximation is used. Default is False. + alternative : {"two-sided", "greater", "less"}, optional + Defines the alternative hypothesis. Default is 'two-sided'. + In the following, let ``d`` represent the difference between the paired + samples: ``d = x - y`` if both ``x`` and ``y`` are provided, or + ``d = x`` otherwise. + + * 'two-sided': the distribution underlying ``d`` is not symmetric + about zero. + * 'less': the distribution underlying ``d`` is stochastically less + than a distribution symmetric about zero. + * 'greater': the distribution underlying ``d`` is stochastically + greater than a distribution symmetric about zero. + + method : {"auto", "exact", "asymptotic"} or `PermutationMethod` instance, optional + Method to calculate the p-value, see Notes. Default is "auto". + + axis : int or None, default: 0 + If an int, the axis of the input along which to compute the statistic. + The statistic of each axis-slice (e.g. row) of the input will appear + in a corresponding element of the output. If ``None``, the input will + be raveled before computing the statistic. + + Returns + ------- + An object with the following attributes. + + statistic : array_like + If `alternative` is "two-sided", the sum of the ranks of the + differences above or below zero, whichever is smaller. + Otherwise the sum of the ranks of the differences above zero. + pvalue : array_like + The p-value for the test depending on `alternative` and `method`. + zstatistic : array_like + When ``method = 'asymptotic'``, this is the normalized z-statistic:: + + z = (T - mn - d) / se + + where ``T`` is `statistic` as defined above, ``mn`` is the mean of the + distribution under the null hypothesis, ``d`` is a continuity + correction, and ``se`` is the standard error. + When ``method != 'asymptotic'``, this attribute is not available. + + See Also + -------- + kruskal, mannwhitneyu + + Notes + ----- + In the following, let ``d`` represent the difference between the paired + samples: ``d = x - y`` if both ``x`` and ``y`` are provided, or ``d = x`` + otherwise. Assume that all elements of ``d`` are independent and + identically distributed observations, and all are distinct and nonzero. + + - When ``len(d)`` is sufficiently large, the null distribution of the + normalized test statistic (`zstatistic` above) is approximately normal, + and ``method = 'asymptotic'`` can be used to compute the p-value. + + - When ``len(d)`` is small, the normal approximation may not be accurate, + and ``method='exact'`` is preferred (at the cost of additional + execution time). + + - The default, ``method='auto'``, selects between the two: + ``method='exact'`` is used when ``len(d) <= 50``, and + ``method='asymptotic'`` is used otherwise. + + The presence of "ties" (i.e. not all elements of ``d`` are unique) or + "zeros" (i.e. elements of ``d`` are zero) changes the null distribution + of the test statistic, and ``method='exact'`` no longer calculates + the exact p-value. If ``method='asymptotic'``, the z-statistic is adjusted + for more accurate comparison against the standard normal, but still, + for finite sample sizes, the standard normal is only an approximation of + the true null distribution of the z-statistic. For such situations, the + `method` parameter also accepts instances of `PermutationMethod`. In this + case, the p-value is computed using `permutation_test` with the provided + configuration options and other appropriate settings. + + The presence of ties and zeros affects the resolution of ``method='auto'`` + accordingly: exhasutive permutations are performed when ``len(d) <= 13``, + and the asymptotic method is used otherwise. Note that they asymptotic + method may not be very accurate even for ``len(d) > 14``; the threshold + was chosen as a compromise between execution time and accuracy under the + constraint that the results must be deterministic. Consider providing an + instance of `PermutationMethod` method manually, choosing the + ``n_resamples`` parameter to balance time constraints and accuracy + requirements. + + Please also note that in the edge case that all elements of ``d`` are zero, + the p-value relying on the normal approximaton cannot be computed (NaN) + if ``zero_method='wilcox'`` or ``zero_method='pratt'``. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test + .. [2] Conover, W.J., Practical Nonparametric Statistics, 1971. + .. [3] Pratt, J.W., Remarks on Zeros and Ties in the Wilcoxon Signed + Rank Procedures, Journal of the American Statistical Association, + Vol. 54, 1959, pp. 655-667. :doi:`10.1080/01621459.1959.10501526` + .. [4] Wilcoxon, F., Individual Comparisons by Ranking Methods, + Biometrics Bulletin, Vol. 1, 1945, pp. 80-83. :doi:`10.2307/3001968` + .. [5] Cureton, E.E., The Normal Approximation to the Signed-Rank + Sampling Distribution When Zero Differences are Present, + Journal of the American Statistical Association, Vol. 62, 1967, + pp. 1068-1069. :doi:`10.1080/01621459.1967.10500917` + + Examples + -------- + In [4]_, the differences in height between cross- and self-fertilized + corn plants is given as follows: + + >>> d = [6, 8, 14, 16, 23, 24, 28, 29, 41, -48, 49, 56, 60, -67, 75] + + Cross-fertilized plants appear to be higher. To test the null + hypothesis that there is no height difference, we can apply the + two-sided test: + + >>> from scipy.stats import wilcoxon + >>> res = wilcoxon(d) + >>> res.statistic, res.pvalue + (24.0, 0.041259765625) + + Hence, we would reject the null hypothesis at a confidence level of 5%, + concluding that there is a difference in height between the groups. + To confirm that the median of the differences can be assumed to be + positive, we use: + + >>> res = wilcoxon(d, alternative='greater') + >>> res.statistic, res.pvalue + (96.0, 0.0206298828125) + + This shows that the null hypothesis that the median is negative can be + rejected at a confidence level of 5% in favor of the alternative that + the median is greater than zero. The p-values above are exact. Using the + normal approximation gives very similar values: + + >>> res = wilcoxon(d, method='asymptotic') + >>> res.statistic, res.pvalue + (24.0, 0.04088813291185591) + + Note that the statistic changed to 96 in the one-sided case (the sum + of ranks of positive differences) whereas it is 24 in the two-sided + case (the minimum of sum of ranks above and below zero). + + In the example above, the differences in height between paired plants are + provided to `wilcoxon` directly. Alternatively, `wilcoxon` accepts two + samples of equal length, calculates the differences between paired + elements, then performs the test. Consider the samples ``x`` and ``y``: + + >>> import numpy as np + >>> x = np.array([0.5, 0.825, 0.375, 0.5]) + >>> y = np.array([0.525, 0.775, 0.325, 0.55]) + >>> res = wilcoxon(x, y, alternative='greater') + >>> res + WilcoxonResult(statistic=5.0, pvalue=0.5625) + + Note that had we calculated the differences by hand, the test would have + produced different results: + + >>> d = [-0.025, 0.05, 0.05, -0.05] + >>> ref = wilcoxon(d, alternative='greater') + >>> ref + WilcoxonResult(statistic=6.0, pvalue=0.5) + + The substantial difference is due to roundoff error in the results of + ``x-y``: + + >>> d - (x-y) + array([2.08166817e-17, 6.93889390e-17, 1.38777878e-17, 4.16333634e-17]) + + Even though we expected all the elements of ``(x-y)[1:]`` to have the same + magnitude ``0.05``, they have slightly different magnitudes in practice, + and therefore are assigned different ranks in the test. Before performing + the test, consider calculating ``d`` and adjusting it as necessary to + ensure that theoretically identically values are not numerically distinct. + For example: + + >>> d2 = np.around(x - y, decimals=3) + >>> wilcoxon(d2, alternative='greater') + WilcoxonResult(statistic=6.0, pvalue=0.5) + + """ + # replace approx by asymptotic to ensure backwards compatability + if method == "approx": + method = "asymptotic" + return _wilcoxon._wilcoxon_nd(x, y, zero_method, correction, alternative, + method, axis) + + +MedianTestResult = _make_tuple_bunch( + 'MedianTestResult', + ['statistic', 'pvalue', 'median', 'table'], [] +) + + +def median_test(*samples, ties='below', correction=True, lambda_=1, + nan_policy='propagate'): + """Perform a Mood's median test. + + Test that two or more samples come from populations with the same median. + + Let ``n = len(samples)`` be the number of samples. The "grand median" of + all the data is computed, and a contingency table is formed by + classifying the values in each sample as being above or below the grand + median. The contingency table, along with `correction` and `lambda_`, + are passed to `scipy.stats.chi2_contingency` to compute the test statistic + and p-value. + + Parameters + ---------- + sample1, sample2, ... : array_like + The set of samples. There must be at least two samples. + Each sample must be a one-dimensional sequence containing at least + one value. The samples are not required to have the same length. + ties : str, optional + Determines how values equal to the grand median are classified in + the contingency table. The string must be one of:: + + "below": + Values equal to the grand median are counted as "below". + "above": + Values equal to the grand median are counted as "above". + "ignore": + Values equal to the grand median are not counted. + + The default is "below". + correction : bool, optional + If True, *and* there are just two samples, apply Yates' correction + for continuity when computing the test statistic associated with + the contingency table. Default is True. + lambda_ : float or str, optional + By default, the statistic computed in this test is Pearson's + chi-squared statistic. `lambda_` allows a statistic from the + Cressie-Read power divergence family to be used instead. See + `power_divergence` for details. + Default is 1 (Pearson's chi-squared statistic). + nan_policy : {'propagate', 'raise', 'omit'}, optional + Defines how to handle when input contains nan. 'propagate' returns nan, + 'raise' throws an error, 'omit' performs the calculations ignoring nan + values. Default is 'propagate'. + + Returns + ------- + res : MedianTestResult + An object containing attributes: + + statistic : float + The test statistic. The statistic that is returned is determined + by `lambda_`. The default is Pearson's chi-squared statistic. + pvalue : float + The p-value of the test. + median : float + The grand median. + table : ndarray + The contingency table. The shape of the table is (2, n), where + n is the number of samples. The first row holds the counts of the + values above the grand median, and the second row holds the counts + of the values below the grand median. The table allows further + analysis with, for example, `scipy.stats.chi2_contingency`, or with + `scipy.stats.fisher_exact` if there are two samples, without having + to recompute the table. If ``nan_policy`` is "propagate" and there + are nans in the input, the return value for ``table`` is ``None``. + + See Also + -------- + kruskal : Compute the Kruskal-Wallis H-test for independent samples. + mannwhitneyu : Computes the Mann-Whitney rank test on samples x and y. + + Notes + ----- + .. versionadded:: 0.15.0 + + References + ---------- + .. [1] Mood, A. M., Introduction to the Theory of Statistics. McGraw-Hill + (1950), pp. 394-399. + .. [2] Zar, J. H., Biostatistical Analysis, 5th ed. Prentice Hall (2010). + See Sections 8.12 and 10.15. + + Examples + -------- + A biologist runs an experiment in which there are three groups of plants. + Group 1 has 16 plants, group 2 has 15 plants, and group 3 has 17 plants. + Each plant produces a number of seeds. The seed counts for each group + are:: + + Group 1: 10 14 14 18 20 22 24 25 31 31 32 39 43 43 48 49 + Group 2: 28 30 31 33 34 35 36 40 44 55 57 61 91 92 99 + Group 3: 0 3 9 22 23 25 25 33 34 34 40 45 46 48 62 67 84 + + The following code applies Mood's median test to these samples. + + >>> g1 = [10, 14, 14, 18, 20, 22, 24, 25, 31, 31, 32, 39, 43, 43, 48, 49] + >>> g2 = [28, 30, 31, 33, 34, 35, 36, 40, 44, 55, 57, 61, 91, 92, 99] + >>> g3 = [0, 3, 9, 22, 23, 25, 25, 33, 34, 34, 40, 45, 46, 48, 62, 67, 84] + >>> from scipy.stats import median_test + >>> res = median_test(g1, g2, g3) + + The median is + + >>> res.median + 34.0 + + and the contingency table is + + >>> res.table + array([[ 5, 10, 7], + [11, 5, 10]]) + + `p` is too large to conclude that the medians are not the same: + + >>> res.pvalue + 0.12609082774093244 + + The "G-test" can be performed by passing ``lambda_="log-likelihood"`` to + `median_test`. + + >>> res = median_test(g1, g2, g3, lambda_="log-likelihood") + >>> res.pvalue + 0.12224779737117837 + + The median occurs several times in the data, so we'll get a different + result if, for example, ``ties="above"`` is used: + + >>> res = median_test(g1, g2, g3, ties="above") + >>> res.pvalue + 0.063873276069553273 + + >>> res.table + array([[ 5, 11, 9], + [11, 4, 8]]) + + This example demonstrates that if the data set is not large and there + are values equal to the median, the p-value can be sensitive to the + choice of `ties`. + + """ + if len(samples) < 2: + raise ValueError('median_test requires two or more samples.') + + ties_options = ['below', 'above', 'ignore'] + if ties not in ties_options: + raise ValueError(f"invalid 'ties' option '{ties}'; 'ties' must be one " + f"of: {str(ties_options)[1:-1]}") + + data = [np.asarray(sample) for sample in samples] + + # Validate the sizes and shapes of the arguments. + for k, d in enumerate(data): + if d.size == 0: + raise ValueError("Sample %d is empty. All samples must " + "contain at least one value." % (k + 1)) + if d.ndim != 1: + raise ValueError("Sample %d has %d dimensions. All " + "samples must be one-dimensional sequences." % + (k + 1, d.ndim)) + + cdata = np.concatenate(data) + contains_nan, nan_policy = _contains_nan(cdata, nan_policy) + if contains_nan and nan_policy == 'propagate': + return MedianTestResult(np.nan, np.nan, np.nan, None) + + if contains_nan: + grand_median = np.median(cdata[~np.isnan(cdata)]) + else: + grand_median = np.median(cdata) + # When the minimum version of numpy supported by scipy is 1.9.0, + # the above if/else statement can be replaced by the single line: + # grand_median = np.nanmedian(cdata) + + # Create the contingency table. + table = np.zeros((2, len(data)), dtype=np.int64) + for k, sample in enumerate(data): + sample = sample[~np.isnan(sample)] + + nabove = count_nonzero(sample > grand_median) + nbelow = count_nonzero(sample < grand_median) + nequal = sample.size - (nabove + nbelow) + table[0, k] += nabove + table[1, k] += nbelow + if ties == "below": + table[1, k] += nequal + elif ties == "above": + table[0, k] += nequal + + # Check that no row or column of the table is all zero. + # Such a table can not be given to chi2_contingency, because it would have + # a zero in the table of expected frequencies. + rowsums = table.sum(axis=1) + if rowsums[0] == 0: + raise ValueError(f"All values are below the grand median ({grand_median}).") + if rowsums[1] == 0: + raise ValueError(f"All values are above the grand median ({grand_median}).") + if ties == "ignore": + # We already checked that each sample has at least one value, but it + # is possible that all those values equal the grand median. If `ties` + # is "ignore", that would result in a column of zeros in `table`. We + # check for that case here. + zero_cols = np.nonzero((table == 0).all(axis=0))[0] + if len(zero_cols) > 0: + msg = ("All values in sample %d are equal to the grand " + "median (%r), so they are ignored, resulting in an " + "empty sample." % (zero_cols[0] + 1, grand_median)) + raise ValueError(msg) + + stat, p, dof, expected = chi2_contingency(table, lambda_=lambda_, + correction=correction) + return MedianTestResult(stat, p, grand_median, table) + + +def _circfuncs_common(samples, period, xp=None): + xp = array_namespace(samples) if xp is None else xp + + if xp.isdtype(samples.dtype, 'integral'): + dtype = xp.asarray(1.).dtype # get default float type + samples = xp.asarray(samples, dtype=dtype) + + # Recast samples as radians that range between 0 and 2 pi and calculate + # the sine and cosine + scaled_samples = samples * ((2.0 * pi) / period) + sin_samp = xp.sin(scaled_samples) + cos_samp = xp.cos(scaled_samples) + + return samples, sin_samp, cos_samp + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, default_axis=None, + result_to_tuple=lambda x: (x,) +) +def circmean(samples, high=2*pi, low=0, axis=None, nan_policy='propagate'): + r"""Compute the circular mean of a sample of angle observations. + + Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in + radians, their *circular mean* is defined by ([1]_, Eq. 2.2.4) + + .. math:: + + \mathrm{Arg} \left( \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right) + + where :math:`i` is the imaginary unit and :math:`\mathop{\mathrm{Arg}} z` + gives the principal value of the argument of complex number :math:`z`, + restricted to the range :math:`[0,2\pi]` by default. :math:`z` in the + above expression is known as the `mean resultant vector`. + + Parameters + ---------- + samples : array_like + Input array of angle observations. The value of a full angle is + equal to ``(high - low)``. + high : float, optional + Upper boundary of the principal value of an angle. Default is ``2*pi``. + low : float, optional + Lower boundary of the principal value of an angle. Default is ``0``. + + Returns + ------- + circmean : float + Circular mean, restricted to the range ``[low, high]``. + + If the mean resultant vector is zero, an input-dependent, + implementation-defined number between ``[low, high]`` is returned. + If the input array is empty, ``np.nan`` is returned. + + See Also + -------- + circstd : Circular standard deviation. + circvar : Circular variance. + + References + ---------- + .. [1] Mardia, K. V. and Jupp, P. E. *Directional Statistics*. + John Wiley & Sons, 1999. + + Examples + -------- + For readability, all angles are printed out in degrees. + + >>> import numpy as np + >>> from scipy.stats import circmean + >>> import matplotlib.pyplot as plt + >>> angles = np.deg2rad(np.array([20, 30, 330])) + >>> circmean = circmean(angles) + >>> np.rad2deg(circmean) + 7.294976657784009 + + >>> mean = angles.mean() + >>> np.rad2deg(mean) + 126.66666666666666 + + Plot and compare the circular mean against the arithmetic mean. + + >>> plt.plot(np.cos(np.linspace(0, 2*np.pi, 500)), + ... np.sin(np.linspace(0, 2*np.pi, 500)), + ... c='k') + >>> plt.scatter(np.cos(angles), np.sin(angles), c='k') + >>> plt.scatter(np.cos(circmean), np.sin(circmean), c='b', + ... label='circmean') + >>> plt.scatter(np.cos(mean), np.sin(mean), c='r', label='mean') + >>> plt.legend() + >>> plt.axis('equal') + >>> plt.show() + + """ + xp = array_namespace(samples) + # Needed for non-NumPy arrays to get appropriate NaN result + # Apparently atan2(0, 0) is 0, even though it is mathematically undefined + if xp_size(samples) == 0: + return xp.mean(samples, axis=axis) + period = high - low + samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp) + sin_sum = xp.sum(sin_samp, axis=axis) + cos_sum = xp.sum(cos_samp, axis=axis) + res = xp.atan2(sin_sum, cos_sum) + + res = res[()] if res.ndim == 0 else res + return (res * (period / (2.0 * pi)) - low) % period + low + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, default_axis=None, + result_to_tuple=lambda x: (x,) +) +def circvar(samples, high=2*pi, low=0, axis=None, nan_policy='propagate'): + r"""Compute the circular variance of a sample of angle observations. + + Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in + radians, their *circular variance* is defined by ([2]_, Eq. 2.3.3) + + .. math:: + + 1 - \left| \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right| + + where :math:`i` is the imaginary unit and :math:`|z|` gives the length + of the complex number :math:`z`. :math:`|z|` in the above expression + is known as the `mean resultant length`. + + Parameters + ---------- + samples : array_like + Input array of angle observations. The value of a full angle is + equal to ``(high - low)``. + high : float, optional + Upper boundary of the principal value of an angle. Default is ``2*pi``. + low : float, optional + Lower boundary of the principal value of an angle. Default is ``0``. + + Returns + ------- + circvar : float + Circular variance. The returned value is in the range ``[0, 1]``, + where ``0`` indicates no variance and ``1`` indicates large variance. + + If the input array is empty, ``np.nan`` is returned. + + See Also + -------- + circmean : Circular mean. + circstd : Circular standard deviation. + + Notes + ----- + In the limit of small angles, the circular variance is close to + half the 'linear' variance if measured in radians. + + References + ---------- + .. [1] Fisher, N.I. *Statistical analysis of circular data*. Cambridge + University Press, 1993. + .. [2] Mardia, K. V. and Jupp, P. E. *Directional Statistics*. + John Wiley & Sons, 1999. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import circvar + >>> import matplotlib.pyplot as plt + >>> samples_1 = np.array([0.072, -0.158, 0.077, 0.108, 0.286, + ... 0.133, -0.473, -0.001, -0.348, 0.131]) + >>> samples_2 = np.array([0.111, -0.879, 0.078, 0.733, 0.421, + ... 0.104, -0.136, -0.867, 0.012, 0.105]) + >>> circvar_1 = circvar(samples_1) + >>> circvar_2 = circvar(samples_2) + + Plot the samples. + + >>> fig, (left, right) = plt.subplots(ncols=2) + >>> for image in (left, right): + ... image.plot(np.cos(np.linspace(0, 2*np.pi, 500)), + ... np.sin(np.linspace(0, 2*np.pi, 500)), + ... c='k') + ... image.axis('equal') + ... image.axis('off') + >>> left.scatter(np.cos(samples_1), np.sin(samples_1), c='k', s=15) + >>> left.set_title(f"circular variance: {np.round(circvar_1, 2)!r}") + >>> right.scatter(np.cos(samples_2), np.sin(samples_2), c='k', s=15) + >>> right.set_title(f"circular variance: {np.round(circvar_2, 2)!r}") + >>> plt.show() + + """ + xp = array_namespace(samples) + period = high - low + samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp) + sin_mean = xp.mean(sin_samp, axis=axis) + cos_mean = xp.mean(cos_samp, axis=axis) + hypotenuse = (sin_mean**2. + cos_mean**2.)**0.5 + # hypotenuse can go slightly above 1 due to rounding errors + R = xp.clip(hypotenuse, max=1.) + + res = 1. - R + return res + + +@_axis_nan_policy_factory( + lambda x: x, n_outputs=1, default_axis=None, + result_to_tuple=lambda x: (x,) +) +def circstd(samples, high=2*pi, low=0, axis=None, nan_policy='propagate', *, + normalize=False): + r""" + Compute the circular standard deviation of a sample of angle observations. + + Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in + radians, their `circular standard deviation` is defined by + ([2]_, Eq. 2.3.11) + + .. math:: + + \sqrt{ -2 \log \left| \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right| } + + where :math:`i` is the imaginary unit and :math:`|z|` gives the length + of the complex number :math:`z`. :math:`|z|` in the above expression + is known as the `mean resultant length`. + + Parameters + ---------- + samples : array_like + Input array of angle observations. The value of a full angle is + equal to ``(high - low)``. + high : float, optional + Upper boundary of the principal value of an angle. Default is ``2*pi``. + low : float, optional + Lower boundary of the principal value of an angle. Default is ``0``. + normalize : boolean, optional + If ``False`` (the default), the return value is computed from the + above formula with the input scaled by ``(2*pi)/(high-low)`` and + the output scaled (back) by ``(high-low)/(2*pi)``. If ``True``, + the output is not scaled and is returned directly. + + Returns + ------- + circstd : float + Circular standard deviation, optionally normalized. + + If the input array is empty, ``np.nan`` is returned. + + See Also + -------- + circmean : Circular mean. + circvar : Circular variance. + + Notes + ----- + In the limit of small angles, the circular standard deviation is close + to the 'linear' standard deviation if ``normalize`` is ``False``. + + References + ---------- + .. [1] Mardia, K. V. (1972). 2. In *Statistics of Directional Data* + (pp. 18-24). Academic Press. :doi:`10.1016/C2013-0-07425-7`. + .. [2] Mardia, K. V. and Jupp, P. E. *Directional Statistics*. + John Wiley & Sons, 1999. + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import circstd + >>> import matplotlib.pyplot as plt + >>> samples_1 = np.array([0.072, -0.158, 0.077, 0.108, 0.286, + ... 0.133, -0.473, -0.001, -0.348, 0.131]) + >>> samples_2 = np.array([0.111, -0.879, 0.078, 0.733, 0.421, + ... 0.104, -0.136, -0.867, 0.012, 0.105]) + >>> circstd_1 = circstd(samples_1) + >>> circstd_2 = circstd(samples_2) + + Plot the samples. + + >>> fig, (left, right) = plt.subplots(ncols=2) + >>> for image in (left, right): + ... image.plot(np.cos(np.linspace(0, 2*np.pi, 500)), + ... np.sin(np.linspace(0, 2*np.pi, 500)), + ... c='k') + ... image.axis('equal') + ... image.axis('off') + >>> left.scatter(np.cos(samples_1), np.sin(samples_1), c='k', s=15) + >>> left.set_title(f"circular std: {np.round(circstd_1, 2)!r}") + >>> right.plot(np.cos(np.linspace(0, 2*np.pi, 500)), + ... np.sin(np.linspace(0, 2*np.pi, 500)), + ... c='k') + >>> right.scatter(np.cos(samples_2), np.sin(samples_2), c='k', s=15) + >>> right.set_title(f"circular std: {np.round(circstd_2, 2)!r}") + >>> plt.show() + + """ + xp = array_namespace(samples) + period = high - low + samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp) + sin_mean = xp.mean(sin_samp, axis=axis) # [1] (2.2.3) + cos_mean = xp.mean(cos_samp, axis=axis) # [1] (2.2.3) + hypotenuse = (sin_mean**2. + cos_mean**2.)**0.5 + # hypotenuse can go slightly above 1 due to rounding errors + R = xp.clip(hypotenuse, max=1.) # [1] (2.2.4) + + res = (-2*xp.log(R))**0.5+0.0 # torch.pow returns -0.0 if R==1 + if not normalize: + res *= (high-low)/(2.*pi) # [1] (2.3.14) w/ (2.3.7) + return res + + +class DirectionalStats: + def __init__(self, mean_direction, mean_resultant_length): + self.mean_direction = mean_direction + self.mean_resultant_length = mean_resultant_length + + def __repr__(self): + return (f"DirectionalStats(mean_direction={self.mean_direction}," + f" mean_resultant_length={self.mean_resultant_length})") + + +def directional_stats(samples, *, axis=0, normalize=True): + """ + Computes sample statistics for directional data. + + Computes the directional mean (also called the mean direction vector) and + mean resultant length of a sample of vectors. + + The directional mean is a measure of "preferred direction" of vector data. + It is analogous to the sample mean, but it is for use when the length of + the data is irrelevant (e.g. unit vectors). + + The mean resultant length is a value between 0 and 1 used to quantify the + dispersion of directional data: the smaller the mean resultant length, the + greater the dispersion. Several definitions of directional variance + involving the mean resultant length are given in [1]_ and [2]_. + + Parameters + ---------- + samples : array_like + Input array. Must be at least two-dimensional, and the last axis of the + input must correspond with the dimensionality of the vector space. + When the input is exactly two dimensional, this means that each row + of the data is a vector observation. + axis : int, default: 0 + Axis along which the directional mean is computed. + normalize: boolean, default: True + If True, normalize the input to ensure that each observation is a + unit vector. It the observations are already unit vectors, consider + setting this to False to avoid unnecessary computation. + + Returns + ------- + res : DirectionalStats + An object containing attributes: + + mean_direction : ndarray + Directional mean. + mean_resultant_length : ndarray + The mean resultant length [1]_. + + See Also + -------- + circmean: circular mean; i.e. directional mean for 2D *angles* + circvar: circular variance; i.e. directional variance for 2D *angles* + + Notes + ----- + This uses a definition of directional mean from [1]_. + Assuming the observations are unit vectors, the calculation is as follows. + + .. code-block:: python + + mean = samples.mean(axis=0) + mean_resultant_length = np.linalg.norm(mean) + mean_direction = mean / mean_resultant_length + + This definition is appropriate for *directional* data (i.e. vector data + for which the magnitude of each observation is irrelevant) but not + for *axial* data (i.e. vector data for which the magnitude and *sign* of + each observation is irrelevant). + + Several definitions of directional variance involving the mean resultant + length ``R`` have been proposed, including ``1 - R`` [1]_, ``1 - R**2`` + [2]_, and ``2 * (1 - R)`` [2]_. Rather than choosing one, this function + returns ``R`` as attribute `mean_resultant_length` so the user can compute + their preferred measure of dispersion. + + References + ---------- + .. [1] Mardia, Jupp. (2000). *Directional Statistics* + (p. 163). Wiley. + + .. [2] https://en.wikipedia.org/wiki/Directional_statistics + + Examples + -------- + >>> import numpy as np + >>> from scipy.stats import directional_stats + >>> data = np.array([[3, 4], # first observation, 2D vector space + ... [6, -8]]) # second observation + >>> dirstats = directional_stats(data) + >>> dirstats.mean_direction + array([1., 0.]) + + In contrast, the regular sample mean of the vectors would be influenced + by the magnitude of each observation. Furthermore, the result would not be + a unit vector. + + >>> data.mean(axis=0) + array([4.5, -2.]) + + An exemplary use case for `directional_stats` is to find a *meaningful* + center for a set of observations on a sphere, e.g. geographical locations. + + >>> data = np.array([[0.8660254, 0.5, 0.], + ... [0.8660254, -0.5, 0.]]) + >>> dirstats = directional_stats(data) + >>> dirstats.mean_direction + array([1., 0., 0.]) + + The regular sample mean on the other hand yields a result which does not + lie on the surface of the sphere. + + >>> data.mean(axis=0) + array([0.8660254, 0., 0.]) + + The function also returns the mean resultant length, which + can be used to calculate a directional variance. For example, using the + definition ``Var(z) = 1 - R`` from [2]_ where ``R`` is the + mean resultant length, we can calculate the directional variance of the + vectors in the above example as: + + >>> 1 - dirstats.mean_resultant_length + 0.13397459716167093 + """ + xp = array_namespace(samples) + samples = xp.asarray(samples) + + if samples.ndim < 2: + raise ValueError("samples must at least be two-dimensional. " + f"Instead samples has shape: {tuple(samples.shape)}") + samples = xp.moveaxis(samples, axis, 0) + if normalize: + vectornorms = xp_vector_norm(samples, axis=-1, keepdims=True, xp=xp) + samples = samples/vectornorms + mean = xp.mean(samples, axis=0) + mean_resultant_length = xp_vector_norm(mean, axis=-1, keepdims=True, xp=xp) + mean_direction = mean / mean_resultant_length + mrl = xp.squeeze(mean_resultant_length, axis=-1) + mean_resultant_length = mrl[()] if mrl.ndim == 0 else mrl + return DirectionalStats(mean_direction, mean_resultant_length) + + +def false_discovery_control(ps, *, axis=0, method='bh'): + """Adjust p-values to control the false discovery rate. + + The false discovery rate (FDR) is the expected proportion of rejected null + hypotheses that are actually true. + If the null hypothesis is rejected when the *adjusted* p-value falls below + a specified level, the false discovery rate is controlled at that level. + + Parameters + ---------- + ps : 1D array_like + The p-values to adjust. Elements must be real numbers between 0 and 1. + axis : int + The axis along which to perform the adjustment. The adjustment is + performed independently along each axis-slice. If `axis` is None, `ps` + is raveled before performing the adjustment. + method : {'bh', 'by'} + The false discovery rate control procedure to apply: ``'bh'`` is for + Benjamini-Hochberg [1]_ (Eq. 1), ``'by'`` is for Benjaminini-Yekutieli + [2]_ (Theorem 1.3). The latter is more conservative, but it is + guaranteed to control the FDR even when the p-values are not from + independent tests. + + Returns + ------- + ps_adusted : array_like + The adjusted p-values. If the null hypothesis is rejected where these + fall below a specified level, the false discovery rate is controlled + at that level. + + See Also + -------- + combine_pvalues + statsmodels.stats.multitest.multipletests + + Notes + ----- + In multiple hypothesis testing, false discovery control procedures tend to + offer higher power than familywise error rate control procedures (e.g. + Bonferroni correction [1]_). + + If the p-values correspond with independent tests (or tests with + "positive regression dependencies" [2]_), rejecting null hypotheses + corresponding with Benjamini-Hochberg-adjusted p-values below :math:`q` + controls the false discovery rate at a level less than or equal to + :math:`q m_0 / m`, where :math:`m_0` is the number of true null hypotheses + and :math:`m` is the total number of null hypotheses tested. The same is + true even for dependent tests when the p-values are adjusted accorded to + the more conservative Benjaminini-Yekutieli procedure. + + The adjusted p-values produced by this function are comparable to those + produced by the R function ``p.adjust`` and the statsmodels function + `statsmodels.stats.multitest.multipletests`. Please consider the latter + for more advanced methods of multiple comparison correction. + + References + ---------- + .. [1] Benjamini, Yoav, and Yosef Hochberg. "Controlling the false + discovery rate: a practical and powerful approach to multiple + testing." Journal of the Royal statistical society: series B + (Methodological) 57.1 (1995): 289-300. + + .. [2] Benjamini, Yoav, and Daniel Yekutieli. "The control of the false + discovery rate in multiple testing under dependency." Annals of + statistics (2001): 1165-1188. + + .. [3] TileStats. FDR - Benjamini-Hochberg explained - Youtube. + https://www.youtube.com/watch?v=rZKa4tW2NKs. + + .. [4] Neuhaus, Karl-Ludwig, et al. "Improved thrombolysis in acute + myocardial infarction with front-loaded administration of alteplase: + results of the rt-PA-APSAC patency study (TAPS)." Journal of the + American College of Cardiology 19.5 (1992): 885-891. + + Examples + -------- + We follow the example from [1]_. + + Thrombolysis with recombinant tissue-type plasminogen activator (rt-PA) + and anisoylated plasminogen streptokinase activator (APSAC) in + myocardial infarction has been proved to reduce mortality. [4]_ + investigated the effects of a new front-loaded administration of rt-PA + versus those obtained with a standard regimen of APSAC, in a randomized + multicentre trial in 421 patients with acute myocardial infarction. + + There were four families of hypotheses tested in the study, the last of + which was "cardiac and other events after the start of thrombolitic + treatment". FDR control may be desired in this family of hypotheses + because it would not be appropriate to conclude that the front-loaded + treatment is better if it is merely equivalent to the previous treatment. + + The p-values corresponding with the 15 hypotheses in this family were + + >>> ps = [0.0001, 0.0004, 0.0019, 0.0095, 0.0201, 0.0278, 0.0298, 0.0344, + ... 0.0459, 0.3240, 0.4262, 0.5719, 0.6528, 0.7590, 1.000] + + If the chosen significance level is 0.05, we may be tempted to reject the + null hypotheses for the tests corresponding with the first nine p-values, + as the first nine p-values fall below the chosen significance level. + However, this would ignore the problem of "multiplicity": if we fail to + correct for the fact that multiple comparisons are being performed, we + are more likely to incorrectly reject true null hypotheses. + + One approach to the multiplicity problem is to control the family-wise + error rate (FWER), that is, the rate at which the null hypothesis is + rejected when it is actually true. A common procedure of this kind is the + Bonferroni correction [1]_. We begin by multiplying the p-values by the + number of hypotheses tested. + + >>> import numpy as np + >>> np.array(ps) * len(ps) + array([1.5000e-03, 6.0000e-03, 2.8500e-02, 1.4250e-01, 3.0150e-01, + 4.1700e-01, 4.4700e-01, 5.1600e-01, 6.8850e-01, 4.8600e+00, + 6.3930e+00, 8.5785e+00, 9.7920e+00, 1.1385e+01, 1.5000e+01]) + + To control the FWER at 5%, we reject only the hypotheses corresponding + with adjusted p-values less than 0.05. In this case, only the hypotheses + corresponding with the first three p-values can be rejected. According to + [1]_, these three hypotheses concerned "allergic reaction" and "two + different aspects of bleeding." + + An alternative approach is to control the false discovery rate: the + expected fraction of rejected null hypotheses that are actually true. The + advantage of this approach is that it typically affords greater power: an + increased rate of rejecting the null hypothesis when it is indeed false. To + control the false discovery rate at 5%, we apply the Benjamini-Hochberg + p-value adjustment. + + >>> from scipy import stats + >>> stats.false_discovery_control(ps) + array([0.0015 , 0.003 , 0.0095 , 0.035625 , 0.0603 , + 0.06385714, 0.06385714, 0.0645 , 0.0765 , 0.486 , + 0.58118182, 0.714875 , 0.75323077, 0.81321429, 1. ]) + + Now, the first *four* adjusted p-values fall below 0.05, so we would reject + the null hypotheses corresponding with these *four* p-values. Rejection + of the fourth null hypothesis was particularly important to the original + study as it led to the conclusion that the new treatment had a + "substantially lower in-hospital mortality rate." + + """ + # Input Validation and Special Cases + ps = np.asarray(ps) + + ps_in_range = (np.issubdtype(ps.dtype, np.number) + and np.all(ps == np.clip(ps, 0, 1))) + if not ps_in_range: + raise ValueError("`ps` must include only numbers between 0 and 1.") + + methods = {'bh', 'by'} + if method.lower() not in methods: + raise ValueError(f"Unrecognized `method` '{method}'." + f"Method must be one of {methods}.") + method = method.lower() + + if axis is None: + axis = 0 + ps = ps.ravel() + + axis = np.asarray(axis)[()] + if not np.issubdtype(axis.dtype, np.integer) or axis.size != 1: + raise ValueError("`axis` must be an integer or `None`") + + if ps.size <= 1 or ps.shape[axis] <= 1: + return ps[()] + + ps = np.moveaxis(ps, axis, -1) + m = ps.shape[-1] + + # Main Algorithm + # Equivalent to the ideas of [1] and [2], except that this adjusts the + # p-values as described in [3]. The results are similar to those produced + # by R's p.adjust. + + # "Let [ps] be the ordered observed p-values..." + order = np.argsort(ps, axis=-1) + ps = np.take_along_axis(ps, order, axis=-1) # this copies ps + + # Equation 1 of [1] rearranged to reject when p is less than specified q + i = np.arange(1, m+1) + ps *= m / i + + # Theorem 1.3 of [2] + if method == 'by': + ps *= np.sum(1 / i) + + # accounts for rejecting all null hypotheses i for i < k, where k is + # defined in Eq. 1 of either [1] or [2]. See [3]. Starting with the index j + # of the second to last element, we replace element j with element j+1 if + # the latter is smaller. + np.minimum.accumulate(ps[..., ::-1], out=ps[..., ::-1], axis=-1) + + # Restore original order of axes and data + np.put_along_axis(ps, order, values=ps.copy(), axis=-1) + ps = np.moveaxis(ps, -1, axis) + + return np.clip(ps, 0, 1) diff --git a/shared/package-files/d1/d111625ea25c35f71d1fd8dc0dc06246e9cf756707667e00d1b95675247e32a1/blob b/shared/package-files/d1/d111625ea25c35f71d1fd8dc0dc06246e9cf756707667e00d1b95675247e32a1/blob new file mode 100644 index 0000000000000000000000000000000000000000..dee6f6fdd3cbd64f653737f8aac4c1ca94eeb6dd --- /dev/null +++ b/shared/package-files/d1/d111625ea25c35f71d1fd8dc0dc06246e9cf756707667e00d1b95675247e32a1/blob @@ -0,0 +1,380 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/chunked_array.h" // IWYU pragma: keep +#include "arrow/compare.h" +#include "arrow/record_batch.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/type_fwd.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +class Array; +class ChunkedArray; +class KeyValueMetadata; +class MemoryPool; + +/// \class Table +/// \brief Logical table as sequence of chunked arrays +class ARROW_EXPORT Table { + public: + virtual ~Table() = default; + + /// \brief Construct a Table from schema and columns + /// + /// If columns is zero-length, the table's number of rows is zero + /// + /// \param[in] schema The table schema (column types) + /// \param[in] columns The table's columns as chunked arrays + /// \param[in] num_rows number of rows in table, -1 (default) to infer from columns + static std::shared_ptr Make(std::shared_ptr schema, + std::vector> columns, + int64_t num_rows = -1); + + /// \brief Construct a Table from schema and arrays + /// + /// \param[in] schema The table schema (column types) + /// \param[in] arrays The table's columns as arrays + /// \param[in] num_rows number of rows in table, -1 (default) to infer from columns + static std::shared_ptr
Make(std::shared_ptr schema, + const std::vector>& arrays, + int64_t num_rows = -1); + + /// \brief Create an empty Table of a given schema + /// + /// The output Table will be created with a single empty chunk per column. + /// + /// \param[in] schema the schema of the empty Table + /// \param[in] pool the memory pool to allocate memory from + /// \return the resulting Table + static Result> MakeEmpty( + std::shared_ptr schema, MemoryPool* pool = default_memory_pool()); + + /// \brief Construct a Table from a RecordBatchReader. + /// + /// \param[in] reader the arrow::RecordBatchReader that produces batches + static Result> FromRecordBatchReader(RecordBatchReader* reader); + + /// \brief Construct a Table from RecordBatches, using schema supplied by the first + /// RecordBatch. + /// + /// \param[in] batches a std::vector of record batches + static Result> FromRecordBatches( + const std::vector>& batches); + + /// \brief Construct a Table from RecordBatches, using supplied schema. There may be + /// zero record batches + /// + /// \param[in] schema the arrow::Schema for each batch + /// \param[in] batches a std::vector of record batches + static Result> FromRecordBatches( + std::shared_ptr schema, + const std::vector>& batches); + + /// \brief Construct a Table from a chunked StructArray. One column will be produced + /// for each field of the StructArray. + /// + /// \param[in] array a chunked StructArray + static Result> FromChunkedStructArray( + const std::shared_ptr& array); + + /// \brief Return the table schema + const std::shared_ptr& schema() const { return schema_; } + + /// \brief Return a column by index + virtual std::shared_ptr column(int i) const = 0; + + /// \brief Return vector of all columns for table + virtual const std::vector>& columns() const = 0; + + /// Return a column's field by index + std::shared_ptr field(int i) const { return schema_->field(i); } + + /// \brief Return vector of all fields for table + std::vector> fields() const; + + /// \brief Construct a zero-copy slice of the table with the + /// indicated offset and length + /// + /// \param[in] offset the index of the first row in the constructed + /// slice + /// \param[in] length the number of rows of the slice. If there are not enough + /// rows in the table, the length will be adjusted accordingly + /// + /// \return a new object wrapped in std::shared_ptr
+ virtual std::shared_ptr
Slice(int64_t offset, int64_t length) const = 0; + + /// \brief Slice from first row at offset until end of the table + std::shared_ptr
Slice(int64_t offset) const { return Slice(offset, num_rows_); } + + /// \brief Return a column by name + /// \param[in] name field name + /// \return an Array or null if no field was found + std::shared_ptr GetColumnByName(const std::string& name) const { + auto i = schema_->GetFieldIndex(name); + return i == -1 ? NULLPTR : column(i); + } + + /// \brief Remove column from the table, producing a new Table + virtual Result> RemoveColumn(int i) const = 0; + + /// \brief Add column to the table, producing a new Table + virtual Result> AddColumn( + int i, std::shared_ptr field_arg, + std::shared_ptr column) const = 0; + + /// \brief Replace a column in the table, producing a new Table + virtual Result> SetColumn( + int i, std::shared_ptr field_arg, + std::shared_ptr column) const = 0; + + /// \brief Return names of all columns + std::vector ColumnNames() const; + + /// \brief Rename columns with provided names + Result> RenameColumns( + const std::vector& names) const; + + /// \brief Return new table with specified columns + Result> SelectColumns(const std::vector& indices) const; + + /// \brief Replace schema key-value metadata with new metadata + /// \since 0.5.0 + /// + /// \param[in] metadata new KeyValueMetadata + /// \return new Table + virtual std::shared_ptr
ReplaceSchemaMetadata( + const std::shared_ptr& metadata) const = 0; + + /// \brief Flatten the table, producing a new Table. Any column with a + /// struct type will be flattened into multiple columns + /// + /// \param[in] pool The pool for buffer allocations, if any + virtual Result> Flatten( + MemoryPool* pool = default_memory_pool()) const = 0; + + /// \return PrettyPrint representation suitable for debugging + std::string ToString() const; + + /// \brief Perform cheap validation checks to determine obvious inconsistencies + /// within the table's schema and internal data. + /// + /// This is O(k*m) where k is the total number of field descendents, + /// and m is the number of chunks. + /// + /// \return Status + virtual Status Validate() const = 0; + + /// \brief Perform extensive validation checks to determine inconsistencies + /// within the table's schema and internal data. + /// + /// This is O(k*n) where k is the total number of field descendents, + /// and n is the number of rows. + /// + /// \return Status + virtual Status ValidateFull() const = 0; + + /// \brief Return the number of columns in the table + int num_columns() const { return schema_->num_fields(); } + + /// \brief Return the number of rows (equal to each column's logical length) + int64_t num_rows() const { return num_rows_; } + + /// \brief Determine if two tables are equal + /// + /// \param[in] other the table to compare with + /// \param[in] opts the options for equality comparisons + /// \return true if two tables are equal + bool Equals(const Table& other, const EqualOptions& opts) const; + + /// \brief Determine if two tables are equal + /// + /// \param[in] other the table to compare with + /// \param[in] check_metadata if true, the schema metadata will be compared, + /// regardless of the value set in \ref EqualOptions::use_metadata + /// \param[in] opts the options for equality comparisons + /// \return true if two tables are equal + bool Equals(const Table& other, bool check_metadata = false, + const EqualOptions& opts = EqualOptions::Defaults()) const { + return Equals(other, opts.use_metadata(check_metadata)); + } + + /// \brief Make a new table by combining the chunks this table has. + /// + /// All the underlying chunks in the ChunkedArray of each column are + /// concatenated into zero or one chunk. + /// + /// To avoid buffer overflow, binary columns may be combined into + /// multiple chunks. Chunks will have the maximum possible length. + /// + /// \param[in] pool The pool for buffer allocations + Result> CombineChunks( + MemoryPool* pool = default_memory_pool()) const; + + /// \brief Make a new record batch by combining the chunks this table has. + /// + /// All the underlying chunks in the ChunkedArray of each column are + /// concatenated into a single chunk. + /// + /// \param[in] pool The pool for buffer allocations + Result> CombineChunksToBatch( + MemoryPool* pool = default_memory_pool()) const; + + protected: + Table(); + + std::shared_ptr schema_; + int64_t num_rows_; + + private: + ARROW_DISALLOW_COPY_AND_ASSIGN(Table); +}; + +/// \brief Compute a stream of record batches from a (possibly chunked) Table +/// +/// The conversion is zero-copy: each record batch is a view over a slice +/// of the table's columns. +/// +/// The table is expected to be valid prior to using it with the batch reader. +class ARROW_EXPORT TableBatchReader : public RecordBatchReader { + public: + /// \brief Construct a TableBatchReader for the given table + explicit TableBatchReader(const Table& table); + explicit TableBatchReader(std::shared_ptr
table); + + std::shared_ptr schema() const override; + + Status ReadNext(std::shared_ptr* out) override; + + /// \brief Set the desired maximum number of rows for record batches + /// + /// The actual number of rows in each record batch may be smaller, depending + /// on actual chunking characteristics of each table column. + void set_chunksize(int64_t chunksize); + + private: + std::shared_ptr
owned_table_; + const Table& table_; + std::vector column_data_; + std::vector chunk_numbers_; + std::vector chunk_offsets_; + int64_t absolute_row_position_; + int64_t max_chunksize_; +}; + +/// \brief Controls the behavior of ConcatenateTables(). +struct ARROW_EXPORT ConcatenateTablesOptions { + /// If true, the schemas of the tables will be first unified with fields of + /// the same name being merged, according to `field_merge_options`, then each + /// table will be promoted to the unified schema before being concatenated. + /// Otherwise, all tables should have the same schema. Each column in the output table + /// is the result of concatenating the corresponding columns in all input tables. + bool unify_schemas = false; + + /// options to control how fields are merged when unifying schemas + /// + /// This field will be ignored if unify_schemas is false + Field::MergeOptions field_merge_options = Field::MergeOptions::Defaults(); + + static ConcatenateTablesOptions Defaults() { return {}; } +}; + +/// \brief Construct a new table from multiple input tables. +/// +/// The new table is assembled from existing column chunks without copying, +/// if schemas are identical. If schemas do not match exactly and +/// unify_schemas is enabled in options (off by default), an attempt is +/// made to unify them, and then column chunks are converted to their +/// respective unified datatype, which will probably incur a copy. +/// :func:`arrow::PromoteTableToSchema` is used to unify schemas. +/// +/// Tables are concatenated in order they are provided in and the order of +/// rows within tables will be preserved. +/// +/// \param[in] tables a std::vector of Tables to be concatenated +/// \param[in] options specify how to unify schema of input tables +/// \param[in] memory_pool MemoryPool to be used if null-filled arrays need to +/// be created or if existing column chunks need to endure type conversion +/// \return new Table +ARROW_EXPORT +Result> ConcatenateTables( + const std::vector>& tables, + ConcatenateTablesOptions options = ConcatenateTablesOptions::Defaults(), + MemoryPool* memory_pool = default_memory_pool()); + +namespace compute { +class CastOptions; +} + +/// \brief Promotes a table to conform to the given schema. +/// +/// If a field in the schema does not have a corresponding column in +/// the table, a column of nulls will be added to the resulting table. +/// If the corresponding column is of type Null, it will be promoted +/// to the type specified by schema, with null values filled. The +/// column will be casted to the type specified by the schema. +/// +/// Returns an error: +/// - if the corresponding column's type is not compatible with the +/// schema. +/// - if there is a column in the table that does not exist in the schema. +/// - if the cast fails or casting would be required but is not available. +/// +/// \param[in] table the input Table +/// \param[in] schema the target schema to promote to +/// \param[in] pool The memory pool to be used if null-filled arrays need to +/// be created. +ARROW_EXPORT +Result> PromoteTableToSchema( + const std::shared_ptr
& table, const std::shared_ptr& schema, + MemoryPool* pool = default_memory_pool()); + +/// \brief Promotes a table to conform to the given schema. +/// +/// If a field in the schema does not have a corresponding column in +/// the table, a column of nulls will be added to the resulting table. +/// If the corresponding column is of type Null, it will be promoted +/// to the type specified by schema, with null values filled. The column +/// will be casted to the type specified by the schema. +/// +/// Returns an error: +/// - if the corresponding column's type is not compatible with the +/// schema. +/// - if there is a column in the table that does not exist in the schema. +/// - if the cast fails or casting would be required but is not available. +/// +/// \param[in] table the input Table +/// \param[in] schema the target schema to promote to +/// \param[in] options The cast options to allow promotion of types +/// \param[in] pool The memory pool to be used if null-filled arrays need to +/// be created. +ARROW_EXPORT +Result> PromoteTableToSchema( + const std::shared_ptr
& table, const std::shared_ptr& schema, + const compute::CastOptions& options, MemoryPool* pool = default_memory_pool()); + +} // namespace arrow diff --git a/shared/package-files/d1/d1119423dda95126d93a1095b189e7832c14d70332dcdd2d0af063f26349bbdf/blob b/shared/package-files/d1/d1119423dda95126d93a1095b189e7832c14d70332dcdd2d0af063f26349bbdf/blob new file mode 100644 index 0000000000000000000000000000000000000000..a42c99bdd0ce7114f98d298356d518faa1566205 --- /dev/null +++ b/shared/package-files/d1/d1119423dda95126d93a1095b189e7832c14d70332dcdd2d0af063f26349bbdf/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor fbgemm_pack_quantized_matrix(const at::Tensor & input); +TORCH_API at::Tensor fbgemm_pack_quantized_matrix(const at::Tensor & input, int64_t K, int64_t N); +} // namespace native +} // namespace at diff --git a/shared/package-files/d1/d11309bf78977fd3a500c085e1a201e0fca9e009e8294baa0bfb58fb235019b2/blob b/shared/package-files/d1/d11309bf78977fd3a500c085e1a201e0fca9e009e8294baa0bfb58fb235019b2/blob new file mode 100644 index 0000000000000000000000000000000000000000..c6ae197eeae8bbef8c8ba5284eccc4127f9b7a84 --- /dev/null +++ b/shared/package-files/d1/d11309bf78977fd3a500c085e1a201e0fca9e009e8294baa0bfb58fb235019b2/blob @@ -0,0 +1,73 @@ +import unittest + +from numba.cuda.testing import CUDATestCase, skip_on_cudasim +from numba.tests.support import captured_stdout + + +@skip_on_cudasim("cudasim doesn't support cuda import at non-top-level") +class TestVecAdd(CUDATestCase): + """ + Test simple vector addition + """ + + def setUp(self): + # Prevent output from this test showing + # up when running the test suite + self._captured_stdout = captured_stdout() + self._captured_stdout.__enter__() + super().setUp() + + def tearDown(self): + # No exception type, value, or traceback + self._captured_stdout.__exit__(None, None, None) + super().tearDown() + + def test_ex_vecadd(self): + # ex_vecadd.import.begin + import numpy as np + from numba import cuda + # ex_vecadd.import.end + + # ex_vecadd.kernel.begin + @cuda.jit + def f(a, b, c): + # like threadIdx.x + (blockIdx.x * blockDim.x) + tid = cuda.grid(1) + size = len(c) + + if tid < size: + c[tid] = a[tid] + b[tid] + # ex_vecadd.kernel.end + + # Seed RNG for test repeatability + np.random.seed(1) + + # ex_vecadd.allocate.begin + N = 100000 + a = cuda.to_device(np.random.random(N)) + b = cuda.to_device(np.random.random(N)) + c = cuda.device_array_like(a) + # ex_vecadd.allocate.end + + # ex_vecadd.forall.begin + f.forall(len(a))(a, b, c) + print(c.copy_to_host()) + # ex_vecadd.forall.end + + # ex_vecadd.launch.begin + # Enough threads per block for several warps per block + nthreads = 256 + # Enough blocks to cover the entire vector depending on its length + nblocks = (len(a) // nthreads) + 1 + f[nblocks, nthreads](a, b, c) + print(c.copy_to_host()) + # ex_vecadd.launch.end + + np.testing.assert_equal( + c.copy_to_host(), + a.copy_to_host() + b.copy_to_host() + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/shared/package-files/d1/d115718818e3e3367847ce35bb5ff0361d08993d9749d438c918f8eb87ad8814/blob b/shared/package-files/d1/d115718818e3e3367847ce35bb5ff0361d08993d9749d438c918f8eb87ad8814/blob new file mode 100644 index 0000000000000000000000000000000000000000..ddd5446421c107df913ea38e0aed61a48245951a --- /dev/null +++ b/shared/package-files/d1/d115718818e3e3367847ce35bb5ff0361d08993d9749d438c918f8eb87ad8814/blob @@ -0,0 +1,27 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset mt DAYS_OF_WEEK_ABBREV [list \ + "\u0126ad"\ + "Tne"\ + "Tli"\ + "Erb"\ + "\u0126am"\ + "\u0120im"] + ::msgcat::mcset mt MONTHS_ABBREV [list \ + "Jan"\ + "Fra"\ + "Mar"\ + "Apr"\ + "Mej"\ + "\u0120un"\ + "Lul"\ + "Awi"\ + "Set"\ + "Ott"\ + "Nov"] + ::msgcat::mcset mt BCE "QK" + ::msgcat::mcset mt CE "" + ::msgcat::mcset mt DATE_FORMAT "%A, %e ta %B, %Y" + ::msgcat::mcset mt TIME_FORMAT_12 "%l:%M:%S %P" + ::msgcat::mcset mt DATE_TIME_FORMAT "%A, %e ta %B, %Y %l:%M:%S %P %z" +} diff --git a/shared/package-files/d1/d119859b1979b8decbc7beb0ac5349d90cade35b2e593dc7a9e7f4eb7b22c681/blob b/shared/package-files/d1/d119859b1979b8decbc7beb0ac5349d90cade35b2e593dc7a9e7f4eb7b22c681/blob new file mode 100644 index 0000000000000000000000000000000000000000..d83ec4dac88bf88e9f1b96e2c508396b417493ec --- /dev/null +++ b/shared/package-files/d1/d119859b1979b8decbc7beb0ac5349d90cade35b2e593dc7a9e7f4eb7b22c681/blob @@ -0,0 +1,2068 @@ +import copy +import operator + +import types as pytypes +import operator +import warnings +from dataclasses import make_dataclass + +import llvmlite.ir +import numpy as np + +import numba +from numba.parfors import parfor +from numba.core import types, ir, config, compiler, sigutils, cgutils +from numba.core.ir_utils import ( + add_offset_to_labels, + replace_var_names, + remove_dels, + legalize_names, + rename_labels, + get_name_var_table, + visit_vars_inner, + get_definition, + guard, + get_call_table, + is_pure, + get_np_ufunc_typ, + get_unused_var_name, + is_const_call, + fixup_var_define_in_scope, + transfer_scope, + find_max_label, + get_global_func_typ, + find_topo_order, +) +from numba.core.typing import signature +from numba.core import lowering +from numba.parfors.parfor import ensure_parallel_support +from numba.core.errors import ( + NumbaParallelSafetyWarning, NotDefinedError, CompilerError, InternalError, +) +from numba.parfors.parfor_lowering_utils import ParforLoweringBuilder + + +class ParforLower(lowering.Lower): + """This is a custom lowering class that extends standard lowering so as + to accommodate parfor.Parfor nodes.""" + + # custom instruction lowering to handle parfor nodes + def lower_inst(self, inst): + if isinstance(inst, parfor.Parfor): + _lower_parfor_parallel(self, inst) + else: + super().lower_inst(inst) + + @property + def _disable_sroa_like_opt(self): + """ + Force disable this because Parfor use-defs is incompatible---it only + considers use-defs in blocks that must be executing. + See https://github.com/numba/numba/commit/017e2ff9db87fc34149b49dd5367ecbf0bb45268 + """ + return True + + +def _lower_parfor_parallel(lowerer, parfor): + if parfor.lowerer is None: + return _lower_parfor_parallel_std(lowerer, parfor) + else: + return parfor.lowerer(lowerer, parfor) + + +def _lower_parfor_parallel_std(lowerer, parfor): + """Lowerer that handles LLVM code generation for parfor. + This function lowers a parfor IR node to LLVM. + The general approach is as follows: + 1) The code from the parfor's init block is lowered normally + in the context of the current function. + 2) The body of the parfor is transformed into a gufunc function. + 3) Code is inserted into the main function that calls do_scheduling + to divide the iteration space for each thread, allocates + reduction arrays, calls the gufunc function, and then invokes + the reduction function across the reduction arrays to produce + the final reduction values. + """ + from numba.np.ufunc.parallel import get_thread_count + + ensure_parallel_support() + typingctx = lowerer.context.typing_context + targetctx = lowerer.context + builder = lowerer.builder + # We copy the typemap here because for race condition variable we'll + # update their type to array so they can be updated by the gufunc. + orig_typemap = lowerer.fndesc.typemap + # replace original typemap with copy and restore the original at the end. + lowerer.fndesc.typemap = copy.copy(orig_typemap) + if config.DEBUG_ARRAY_OPT: + print("lowerer.fndesc", lowerer.fndesc, type(lowerer.fndesc)) + typemap = lowerer.fndesc.typemap + varmap = lowerer.varmap + + if config.DEBUG_ARRAY_OPT: + print("_lower_parfor_parallel") + parfor.dump() + + loc = parfor.init_block.loc + scope = parfor.init_block.scope + + # produce instructions for init_block + if config.DEBUG_ARRAY_OPT: + print("init_block = ", parfor.init_block, " ", type(parfor.init_block)) + for instr in parfor.init_block.body: + if config.DEBUG_ARRAY_OPT: + print("lower init_block instr = ", instr) + lowerer.lower_inst(instr) + + for racevar in parfor.races: + if racevar not in varmap: + rvtyp = typemap[racevar] + rv = ir.Var(scope, racevar, loc) + lowerer._alloca_var(rv.name, rvtyp) + + alias_map = {} + arg_aliases = {} + numba.parfors.parfor.find_potential_aliases_parfor(parfor, parfor.params, typemap, + lowerer.func_ir, alias_map, arg_aliases) + if config.DEBUG_ARRAY_OPT: + print("alias_map", alias_map) + print("arg_aliases", arg_aliases) + + # run get_parfor_outputs() and get_parfor_reductions() before gufunc creation + # since Jumps are modified so CFG of loop_body dict will become invalid + assert parfor.params is not None + + parfor_output_arrays = numba.parfors.parfor.get_parfor_outputs( + parfor, parfor.params) + parfor_redvars, parfor_reddict = parfor.redvars, parfor.reddict + if config.DEBUG_ARRAY_OPT: + print("parfor_redvars:", parfor_redvars) + print("parfor_reddict:", parfor_reddict) + + # init reduction array allocation here. + nredvars = len(parfor_redvars) + redarrs = {} + to_cleanup = [] + if nredvars > 0: + # reduction arrays outer dimension equal to thread count + scope = parfor.init_block.scope + loc = parfor.init_block.loc + pfbdr = ParforLoweringBuilder(lowerer=lowerer, scope=scope, loc=loc) + + # Get the Numba internal function to call to get the thread count. + get_num_threads = pfbdr.bind_global_function( + fobj=numba.np.ufunc.parallel._iget_num_threads, + ftype=get_global_func_typ(numba.np.ufunc.parallel._iget_num_threads), + args=() + ) + + # Insert the call to assign the thread count to a variable. + num_threads_var = pfbdr.assign( + rhs=pfbdr.call(get_num_threads, args=[]), + typ=types.intp, + name="num_threads_var") + + # For each reduction variable... + for i in range(nredvars): + red_name = parfor_redvars[i] + # Get the type of the reduction variable. + redvar_typ = lowerer.fndesc.typemap[red_name] + # Get the ir.Var for the reduction variable. + redvar = ir.Var(scope, red_name, loc) + # Get the type of the array that holds the per-thread + # reduction variables. + redarrvar_typ = redtyp_to_redarraytype(redvar_typ) + reddtype = redarrvar_typ.dtype + if config.DEBUG_ARRAY_OPT: + print( + "reduction_info", + red_name, + redvar_typ, + redarrvar_typ, + reddtype, + types.DType(reddtype), + num_threads_var, + type(num_threads_var) + ) + + # If this is reduction over an array, + # the reduction array has just one added per-worker dimension. + if isinstance(redvar_typ, types.npytypes.Array): + redarrdim = redvar_typ.ndim + 1 + else: + redarrdim = 1 + + # Reduction array is created and initialized to the initial reduction value. + + # First create a var for the numpy empty ufunc. + glbl_np_empty = pfbdr.bind_global_function( + fobj=np.empty, + ftype=get_np_ufunc_typ(np.empty, pfbdr._typingctx), + args=( + types.UniTuple(types.intp, redarrdim), + ), + kws={'dtype': types.DType(reddtype)} + ) + + size_var_list = [num_threads_var] + + # If this is a reduction over an array... + if isinstance(redvar_typ, types.npytypes.Array): + # Add code to get the shape of the array being reduced over. + redshape_var = pfbdr.assign( + rhs=ir.Expr.getattr(redvar, "shape", loc), + typ=types.UniTuple(types.intp, redvar_typ.ndim), + name="redarr_shape", + ) + + # Add the dimension sizes of the array being reduced over to the tuple of sizes pass to empty. + for j in range(redvar_typ.ndim): + onedimvar = pfbdr.assign( + rhs=ir.Expr.static_getitem(redshape_var, j, None, loc), + typ=types.intp, + name="redshapeonedim", + ) + size_var_list.append(onedimvar) + + # Empty call takes tuple of sizes. Create here and fill in outer dimension (num threads). + size_var = pfbdr.make_tuple_variable( + size_var_list, name='tuple_size_var', + ) + + # Resolve dtype + cval = pfbdr._typingctx.resolve_value_type(reddtype) + dt = pfbdr.make_const_variable(cval=cval, typ=types.DType(reddtype)) + # Add call to empty passing the size var tuple. + empty_call = pfbdr.call(glbl_np_empty, args=[size_var, dt]) + + redarr_var = pfbdr.assign( + rhs=empty_call, typ=redarrvar_typ, name="redarr", + ) + + # Remember mapping of original reduction array to the newly created per-worker reduction array. + redarrs[redvar.name] = redarr_var + to_cleanup.append(redarr_var) + + init_val = parfor_reddict[red_name].init_val + + if init_val is not None: + if isinstance(redvar_typ, types.npytypes.Array): + # Create an array of identity values for the reduction. + # First, create a variable for np.full. + full_func_node = pfbdr.bind_global_function( + fobj=np.full, + ftype=get_np_ufunc_typ(np.full, pfbdr._typingctx), + args=( + types.UniTuple(types.intp, redvar_typ.ndim), + reddtype, + ), + kws={'dtype': types.DType(reddtype)}, + ) + + # Then create a var with the identify value. + init_val_var = pfbdr.make_const_variable( + cval=init_val, + typ=reddtype, + name="init_val", + ) + + # Then, call np.full with the shape of the reduction array and the identity value. + full_call = pfbdr.call( + full_func_node, args=[redshape_var, init_val_var, dt], + ) + + redtoset = pfbdr.assign( + rhs=full_call, + typ=redvar_typ, + name="redtoset", + ) + # rettoset is an array from np.full() and must be released + to_cleanup.append(redtoset) + else: + redtoset = pfbdr.make_const_variable( + cval=init_val, + typ=reddtype, + name="redtoset", + ) + else: + redtoset = redvar + + if config.DEBUG_ARRAY_OPT_RUNTIME: + res_print_str = "res_print1 for redvar " + str(redvar) + ":" + strconsttyp = types.StringLiteral(res_print_str) + + lhs = pfbdr.make_const_variable( + cval=res_print_str, + typ=strconsttyp, + name="str_const", + ) + + res_print = ir.Print(args=[lhs, redvar], + vararg=None, loc=loc) + lowerer.fndesc.calltypes[res_print] = signature(types.none, + typemap[lhs.name], + typemap[redvar.name]) + print("res_print_redvar", res_print) + lowerer.lower_inst(res_print) + + + # For each thread, initialize the per-worker reduction array to + # the current reduction array value. + + # Get the Numba type of the variable that holds the thread count. + num_thread_type = typemap[num_threads_var.name] + # Get the LLVM type of the thread count variable. + ntllvm_type = targetctx.get_value_type(num_thread_type) + # Create a LLVM variable to hold the loop index. + alloc_loop_var = cgutils.alloca_once(builder, ntllvm_type) + # Associate this LLVM variable to a Numba IR variable so that + # we can use setitem IR builder. + # Create a Numba IR variable. + numba_ir_loop_index_var = scope.redefine("$loop_index", loc) + # Give that variable the right type. + typemap[numba_ir_loop_index_var.name] = num_thread_type + # Associate this Numba variable to the LLVM variable in the + # lowerer's varmap. + lowerer.varmap[numba_ir_loop_index_var.name] = alloc_loop_var + # Insert a loop into the outputed LLVM that goes from 0 to + # the current thread count. + with cgutils.for_range(builder, lowerer.loadvar(num_threads_var.name), intp=ntllvm_type) as loop: + # Store the loop index into the alloca'd LLVM loop index variable. + builder.store(loop.index, alloc_loop_var) + # Initialize one element of the reduction array using the Numba + # IR variable associated with this loop's index. + pfbdr.setitem(obj=redarr_var, index=numba_ir_loop_index_var, val=redtoset) + + # compile parfor body as a separate function to be used with GUFuncWrapper + flags = parfor.flags.copy() + flags.error_model = "numpy" + # Can't get here unless flags.auto_parallel == ParallelOptions(True) + index_var_typ = typemap[parfor.loop_nests[0].index_variable.name] + # index variables should have the same type, check rest of indices + for l in parfor.loop_nests[1:]: + assert typemap[l.index_variable.name] == index_var_typ + numba.parfors.parfor.sequential_parfor_lowering = True + try: + (func, + func_args, + func_sig, + func_arg_types, + exp_name_to_tuple_var) = _create_gufunc_for_parfor_body( + lowerer, parfor, typemap, typingctx, targetctx, flags, {}, + bool(alias_map), index_var_typ, parfor.races) + finally: + numba.parfors.parfor.sequential_parfor_lowering = False + + # get the shape signature + func_args = ['sched'] + func_args + num_reductions = len(parfor_redvars) + num_inputs = len(func_args) - len(parfor_output_arrays) - num_reductions + if config.DEBUG_ARRAY_OPT: + print("func_args = ", func_args) + print("num_inputs = ", num_inputs) + print("parfor_outputs = ", parfor_output_arrays) + print("parfor_redvars = ", parfor_redvars) + print("num_reductions = ", num_reductions) + gu_signature = _create_shape_signature( + parfor.get_shape_classes, + num_inputs, + num_reductions, + func_args, + func_sig, + parfor.races, + typemap) + if config.DEBUG_ARRAY_OPT: + print("gu_signature = ", gu_signature) + + # call the func in parallel by wrapping it with ParallelGUFuncBuilder + loop_ranges = [(l.start, l.stop, l.step) for l in parfor.loop_nests] + if config.DEBUG_ARRAY_OPT: + print("loop_nests = ", parfor.loop_nests) + print("loop_ranges = ", loop_ranges) + call_parallel_gufunc( + lowerer, + func, + gu_signature, + func_sig, + func_args, + func_arg_types, + loop_ranges, + parfor_redvars, + parfor_reddict, + redarrs, + parfor.init_block, + index_var_typ, + parfor.races, + exp_name_to_tuple_var) + + if nredvars > 0: + _parfor_lowering_finalize_reduction( + parfor, redarrs, lowerer, parfor_reddict, num_threads_var, + ) + + # Cleanup reduction variable + for v in to_cleanup: + lowerer.lower_inst(ir.Del(v.name, loc=loc)) + # Restore the original typemap of the function that was replaced temporarily at the + # Beginning of this function. + lowerer.fndesc.typemap = orig_typemap + + if config.DEBUG_ARRAY_OPT: + print("_lower_parfor_parallel done") + + +_ReductionInfo = make_dataclass( + "_ReductionInfo", + [ + "redvar_info", + "redvar_name", + "redvar_typ", + "redarr_var", + "redarr_typ", + "init_val", + ], + frozen=True, +) + + +def _parfor_lowering_finalize_reduction( + parfor, + redarrs, + lowerer, + parfor_reddict, + thread_count_var, + ): + """Emit code to finalize the reduction from the intermediate values of + each thread. + """ + # For each reduction variable + for redvar_name, redarr_var in redarrs.items(): + # Pseudo-code for this loop body: + # tmp = redarr[0] + # for i in range(1, thread_count): + # tmp = reduce_op(redarr[i], tmp) + # reduction_result = tmp + redvar_typ = lowerer.fndesc.typemap[redvar_name] + redarr_typ = lowerer.fndesc.typemap[redarr_var.name] + init_val = lowerer.loadvar(redvar_name) + + reduce_info = _ReductionInfo( + redvar_info = parfor_reddict[redvar_name], + redvar_name=redvar_name, + redvar_typ=redvar_typ, + redarr_var=redarr_var, + redarr_typ=redarr_typ, + init_val=init_val, + ) + # generate code for combining reduction variable with thread output + handler = (_lower_trivial_inplace_binops + if reduce_info.redvar_info.redop is not None + else _lower_non_trivial_reduce) + handler(parfor, lowerer, thread_count_var, reduce_info) + + +class ParforsUnexpectedReduceNodeError(InternalError): + def __init__(self, inst): + super().__init__(f"Unknown reduce instruction node: {inst}") + + +def _lower_trivial_inplace_binops(parfor, lowerer, thread_count_var, reduce_info): + """Lower trivial inplace-binop reduction. + """ + for inst in reduce_info.redvar_info.reduce_nodes: + # Var assigns to Var? + if _lower_var_to_var_assign(lowerer, inst): + pass + # Is inplace-binop for the reduction? + elif _is_right_op_and_rhs_is_init(inst, reduce_info.redvar_name, "inplace_binop"): + fn = inst.value.fn + redvar_result = _emit_binop_reduce_call( + fn, lowerer, thread_count_var, reduce_info, + ) + lowerer.storevar(redvar_result, name=inst.target.name) + # Is binop for the reduction? + elif _is_right_op_and_rhs_is_init(inst, reduce_info.redvar_name, "binop"): + fn = inst.value.fn + redvar_result = _emit_binop_reduce_call( + fn, lowerer, thread_count_var, reduce_info, + ) + lowerer.storevar(redvar_result, name=inst.target.name) + # Otherwise? + else: + raise ParforsUnexpectedReduceNodeError(inst) + + # XXX: This seems like a hack to stop the loop with this condition. + if _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst, + reduce_info.redvar_name): + break + if config.DEBUG_ARRAY_OPT_RUNTIME: + varname = reduce_info.redvar_name + lowerer.print_variable( + f"{parfor.loc}: parfor {fn.__name__} reduction {varname} =", + varname, + ) + + +def _lower_non_trivial_reduce(parfor, lowerer, thread_count_var, reduce_info): + """Lower non-trivial reduction such as call to `functools.reduce()`. + """ + init_name = f"{reduce_info.redvar_name}#init" + # The init_name variable is not defined at this point. + lowerer.fndesc.typemap.setdefault(init_name, reduce_info.redvar_typ) + # Emit a sequence of the reduction operation for each intermediate result + # of each thread. + num_thread_llval = lowerer.loadvar(thread_count_var.name) + with cgutils.for_range(lowerer.builder, num_thread_llval) as loop: + tid = loop.index + for inst in reduce_info.redvar_info.reduce_nodes: + # Var assigns to Var? + if _lower_var_to_var_assign(lowerer, inst): + pass + # The reduction operation? + elif (isinstance(inst, ir.Assign) + and any(var.name == init_name for var in inst.list_vars())): + elem = _emit_getitem_call(tid, lowerer, reduce_info) + lowerer.storevar(elem, init_name) + lowerer.lower_inst(inst) + + # Otherwise? + else: + raise ParforsUnexpectedReduceNodeError(inst) + + # XXX: This seems like a hack to stop the loop with this condition. + if _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst, + reduce_info.redvar_name): + break + + if config.DEBUG_ARRAY_OPT_RUNTIME: + varname = reduce_info.redvar_name + lowerer.print_variable( + f"{parfor.loc}: parfor non-trivial reduction {varname} =", + varname, + ) + +def _lower_var_to_var_assign(lowerer, inst): + """Lower Var->Var assignment. + + Returns True if-and-only-if `inst` is a Var->Var assignment. + """ + if isinstance(inst, ir.Assign) and isinstance(inst.value, ir.Var): + loaded = lowerer.loadvar(inst.value.name) + lowerer.storevar(loaded, name=inst.target.name) + return True + return False + +def _emit_getitem_call(idx, lowerer, reduce_info): + """Emit call to ``redarr_var[idx]`` + """ + def reducer_getitem(redarr, index): + return redarr[index] + + builder = lowerer.builder + ctx = lowerer.context + redarr_typ = reduce_info.redarr_typ + arg_arr = lowerer.loadvar(reduce_info.redarr_var.name) + args = (arg_arr, idx) + sig = signature(reduce_info.redvar_typ, redarr_typ, types.intp) + elem = ctx.compile_internal(builder, reducer_getitem, sig, args) + return elem + + +def _emit_binop_reduce_call(binop, lowerer, thread_count_var, reduce_info): + """Emit call to the ``binop`` for the reduction variable. + """ + + def reduction_add(thread_count, redarr, init): + c = init + for i in range(thread_count): + c += redarr[i] + return c + + def reduction_mul(thread_count, redarr, init): + c = init + for i in range(thread_count): + c *= redarr[i] + return c + + kernel = { + operator.iadd: reduction_add, + operator.isub: reduction_add, + operator.add: reduction_add, + operator.sub: reduction_add, + operator.imul: reduction_mul, + operator.ifloordiv: reduction_mul, + operator.itruediv: reduction_mul, + operator.mul: reduction_mul, + operator.floordiv: reduction_mul, + operator.truediv: reduction_mul, + }[binop] + + ctx = lowerer.context + builder = lowerer.builder + redarr_typ = reduce_info.redarr_typ + arg_arr = lowerer.loadvar(reduce_info.redarr_var.name) + + if config.DEBUG_ARRAY_OPT_RUNTIME: + init_var = reduce_info.redarr_var.scope.get(reduce_info.redvar_name) + res_print = ir.Print( + args=[reduce_info.redarr_var, init_var], vararg=None, + loc=lowerer.loc, + ) + typemap = lowerer.fndesc.typemap + lowerer.fndesc.calltypes[res_print] = signature( + types.none, typemap[reduce_info.redarr_var.name], + typemap[init_var.name], + ) + lowerer.lower_inst(res_print) + + arg_thread_count = lowerer.loadvar(thread_count_var.name) + args = (arg_thread_count, arg_arr, reduce_info.init_val) + sig = signature( + reduce_info.redvar_typ, types.uintp, redarr_typ, reduce_info.redvar_typ, + ) + + redvar_result = ctx.compile_internal(builder, kernel, sig, args) + return redvar_result + + +def _is_right_op_and_rhs_is_init(inst, redvar_name, op): + """Is ``inst`` an inplace-binop and the RHS is the reduction init? + """ + if not isinstance(inst, ir.Assign): + return False + rhs = inst.value + if not isinstance(rhs, ir.Expr): + return False + if rhs.op != op: + return False + if rhs.rhs.name != f"{redvar_name}#init": + return False + return True + + +def _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst, redvar_name): + """Fix reduction variable name mismatch due to SSA. + """ + # Only process reduction statements post-gufunc execution + # until we see an assignment with a left-hand side to the + # reduction variable's name. This fixes problems with + # cases where there are multiple assignments to the + # reduction variable in the parfor. + scope = parfor.init_block.scope + if isinstance(inst, ir.Assign): + try: + reduction_var = scope.get_exact(redvar_name) + except NotDefinedError: + # Ideally, this shouldn't happen. The redvar name + # missing from scope indicates an error from + # other rewrite passes. + is_same_source_var = redvar_name == inst.target.name + else: + # Because of SSA, the redvar and target var of + # the current assignment would be different even + # though they refer to the same source-level var. + redvar_unver_name = reduction_var.unversioned_name + target_unver_name = inst.target.unversioned_name + is_same_source_var = redvar_unver_name == target_unver_name + + if is_same_source_var: + # If redvar is different from target var, add an + # assignment to put target var into redvar. + if redvar_name != inst.target.name: + val = lowerer.loadvar(inst.target.name) + lowerer.storevar(val, name=redvar_name) + return True + + return False + +def _create_shape_signature( + get_shape_classes, + num_inputs, + num_reductions, + args, + func_sig, + races, + typemap): + '''Create shape signature for GUFunc + ''' + if config.DEBUG_ARRAY_OPT: + print("_create_shape_signature", num_inputs, num_reductions, args, races) + for i in args[1:]: + print("argument", i, type(i), get_shape_classes(i, typemap=typemap)) + + num_inouts = len(args) - num_reductions + # maximum class number for array shapes + classes = [get_shape_classes(var, typemap=typemap) if var not in races else (-1,) for var in args[1:]] + class_set = set() + for _class in classes: + if _class: + for i in _class: + class_set.add(i) + max_class = max(class_set) + 1 if class_set else 0 + classes.insert(0, (max_class,)) # force set the class of 'sched' argument + class_set.add(max_class) + thread_num_class = max_class + 1 + class_set.add(thread_num_class) + class_map = {} + # TODO: use prefix + class number instead of single char + alphabet = ord('a') + for n in class_set: + if n >= 0: + class_map[n] = chr(alphabet) + alphabet += 1 + threadcount_ordinal = chr(alphabet) + + alpha_dict = {'latest_alpha' : alphabet} + + def bump_alpha(c, class_map): + if c >= 0: + return class_map[c] + else: + alpha_dict['latest_alpha'] += 1 + return chr(alpha_dict['latest_alpha']) + + gu_sin = [] + gu_sout = [] + count = 0 + syms_sin = () + if config.DEBUG_ARRAY_OPT: + print("args", args) + print("classes", classes) + print("threadcount_ordinal", threadcount_ordinal) + for cls, arg in zip(classes, args): + count = count + 1 + if cls: + dim_syms = tuple(bump_alpha(c, class_map) for c in cls) + else: + dim_syms = () + if (count > num_inouts): + # Add the threadcount_ordinal to represent the thread count + # to the start of the reduction array. + gu_sin.append(tuple([threadcount_ordinal] + list(dim_syms[1:]))) + else: + gu_sin.append(dim_syms) + syms_sin += dim_syms + return (gu_sin, gu_sout) + +def _print_block(block): + for i, inst in enumerate(block.body): + print(" ", i, " ", inst) + +def _print_body(body_dict): + '''Pretty-print a set of IR blocks. + ''' + topo_order = wrap_find_topo(body_dict) + for label in topo_order: + block = body_dict[label] + print("label: ", label) + _print_block(block) + + +def wrap_loop_body(loop_body): + blocks = loop_body.copy() # shallow copy is enough + first_label = min(blocks.keys()) + last_label = max(blocks.keys()) + loc = blocks[last_label].loc + blocks[last_label].body.append(ir.Jump(first_label, loc)) + return blocks + +def unwrap_loop_body(loop_body): + last_label = max(loop_body.keys()) + loop_body[last_label].body = loop_body[last_label].body[:-1] + +def add_to_def_once_sets(a_def, def_once, def_more): + '''If the variable is already defined more than once, do nothing. + Else if defined exactly once previously then transition this + variable to the defined more than once set (remove it from + def_once set and add to def_more set). + Else this must be the first time we've seen this variable defined + so add to def_once set. + ''' + if a_def in def_more: + pass + elif a_def in def_once: + def_more.add(a_def) + def_once.remove(a_def) + else: + def_once.add(a_def) + +def compute_def_once_block(block, def_once, def_more, getattr_taken, typemap, module_assigns): + '''Effect changes to the set of variables defined once or more than once + for a single block. + block - the block to process + def_once - set of variable names known to be defined exactly once + def_more - set of variable names known to be defined more than once + getattr_taken - dict mapping variable name to tuple of object and attribute taken + module_assigns - dict mapping variable name to the Global that they came from + ''' + # The only "defs" occur in assignments, so find such instructions. + assignments = block.find_insts(ir.Assign) + # For each assignment... + for one_assign in assignments: + # Get the LHS/target of the assignment. + a_def = one_assign.target.name + # Add variable to def sets. + add_to_def_once_sets(a_def, def_once, def_more) + + rhs = one_assign.value + if isinstance(rhs, ir.Global): + # Remember assignments of the form "a = Global(...)" + # Is this a module? + if isinstance(rhs.value, pytypes.ModuleType): + module_assigns[a_def] = rhs.value.__name__ + if isinstance(rhs, ir.Expr) and rhs.op == 'getattr' and rhs.value.name in def_once: + # Remember assignments of the form "a = b.c" + getattr_taken[a_def] = (rhs.value.name, rhs.attr) + if isinstance(rhs, ir.Expr) and rhs.op == 'call' and rhs.func.name in getattr_taken: + # If "a" is being called then lookup the getattr definition of "a" + # as above, getting the module variable "b" (base_obj) + # and the attribute "c" (base_attr). + base_obj, base_attr = getattr_taken[rhs.func.name] + if base_obj in module_assigns: + # If we know the definition of the module variable then get the module + # name from module_assigns. + base_mod_name = module_assigns[base_obj] + if not is_const_call(base_mod_name, base_attr): + # Calling a method on an object could modify the object and is thus + # like a def of that object. We call is_const_call to see if this module/attribute + # combination is known to not modify the module state. If we don't know that + # the combination is safe then we have to assume there could be a modification to + # the module and thus add the module variable as defined more than once. + add_to_def_once_sets(base_obj, def_once, def_more) + else: + # Assume the worst and say that base_obj could be modified by the call. + add_to_def_once_sets(base_obj, def_once, def_more) + if isinstance(rhs, ir.Expr) and rhs.op == 'call': + # If a mutable object is passed to a function, then it may be changed and + # therefore can't be hoisted. + # For each argument to the function... + for argvar in rhs.args: + # Get the argument's type. + if isinstance(argvar, ir.Var): + argvar = argvar.name + avtype = typemap[argvar] + # If that type doesn't have a mutable attribute or it does and it's set to + # not mutable then this usage is safe for hoisting. + if getattr(avtype, 'mutable', False): + # Here we have a mutable variable passed to a function so add this variable + # to the def lists. + add_to_def_once_sets(argvar, def_once, def_more) + +def wrap_find_topo(loop_body): + blocks = wrap_loop_body(loop_body) + topo_order = find_topo_order(blocks) + unwrap_loop_body(loop_body) + return topo_order + +def compute_def_once_internal(loop_body, def_once, def_more, getattr_taken, typemap, module_assigns): + '''Compute the set of variables defined exactly once in the given set of blocks + and use the given sets for storing which variables are defined once, more than + once and which have had a getattr call on them. + ''' + # For each block in topological order... + topo_order = wrap_find_topo(loop_body) + for label in topo_order: + block = loop_body[label] + # Scan this block and effect changes to def_once, def_more, and getattr_taken + # based on the instructions in that block. + compute_def_once_block(block, def_once, def_more, getattr_taken, typemap, module_assigns) + # Have to recursively process parfors manually here. + for inst in block.body: + if isinstance(inst, parfor.Parfor): + # Recursively compute for the parfor's init block. + compute_def_once_block(inst.init_block, def_once, def_more, getattr_taken, typemap, module_assigns) + # Recursively compute for the parfor's loop body. + compute_def_once_internal(inst.loop_body, def_once, def_more, getattr_taken, typemap, module_assigns) + +def compute_def_once(loop_body, typemap): + '''Compute the set of variables defined exactly once in the given set of blocks. + ''' + def_once = set() # set to hold variables defined exactly once + def_more = set() # set to hold variables defined more than once + getattr_taken = {} + module_assigns = {} + compute_def_once_internal(loop_body, def_once, def_more, getattr_taken, typemap, module_assigns) + return def_once, def_more + +def find_vars(var, varset): + assert isinstance(var, ir.Var) + varset.add(var.name) + return var + +def _hoist_internal(inst, dep_on_param, call_table, hoisted, not_hoisted, + typemap, stored_arrays): + if inst.target.name in stored_arrays: + not_hoisted.append((inst, "stored array")) + if config.DEBUG_ARRAY_OPT >= 1: + print("Instruction", inst, "could not be hoisted because the created array is stored.") + return False + + target_type = typemap[inst.target.name] + + uses = set() + # Get vars used by this statement. + visit_vars_inner(inst.value, find_vars, uses) + # Filter out input parameters from the set of variable usages. + unhoistable = {assgn.target.name for assgn, _ in not_hoisted} + use_unhoist = uses & unhoistable + diff = uses.difference(dep_on_param) + diff |= use_unhoist + if config.DEBUG_ARRAY_OPT >= 1: + print("_hoist_internal:", inst, "uses:", uses, "diff:", diff) + if len(diff) == 0 and is_pure(inst.value, None, call_table): + if config.DEBUG_ARRAY_OPT >= 1: + print("Will hoist instruction", inst, target_type) + hoisted.append(inst) + if not isinstance(target_type, types.npytypes.Array): + dep_on_param += [inst.target.name] + return True + else: + if len(diff) > 0: + not_hoisted.append((inst, "dependency")) + if config.DEBUG_ARRAY_OPT >= 1: + print("Instruction", inst, "could not be hoisted because of a dependency.") + else: + not_hoisted.append((inst, "not pure")) + if config.DEBUG_ARRAY_OPT >= 1: + print("Instruction", inst, "could not be hoisted because it isn't pure.") + return False + +def find_setitems_block(setitems, itemsset, block, typemap): + for inst in block.body: + if isinstance(inst, (ir.StaticSetItem, ir.SetItem)): + setitems.add(inst.target.name) + # If we store a non-mutable object into an array then that is safe to hoist. + # If the stored object is mutable and you hoist then multiple entries in the + # outer array could reference the same object and changing one index would then + # change other indices. + if getattr(typemap[inst.value.name], "mutable", False): + itemsset.add(inst.value.name) + elif isinstance(inst, parfor.Parfor): + find_setitems_block(setitems, itemsset, inst.init_block, typemap) + find_setitems_body(setitems, itemsset, inst.loop_body, typemap) + elif isinstance(inst, ir.Assign): + # If something of mutable type is given to a build_tuple or + # used in a call then consider it unanalyzable and so + # unavailable for hoisting. + rhs = inst.value + def add_to_itemset(item): + assert isinstance(item, ir.Var), rhs + if getattr(typemap[item.name], "mutable", False): + itemsset.add(item.name) + + if isinstance(rhs, ir.Expr): + if rhs.op in ["build_tuple", "build_list", "build_set"]: + for item in rhs.items: + add_to_itemset(item) + elif rhs.op == "build_map": + for pair in rhs.items: + for item in pair: + add_to_itemset(item) + elif rhs.op == "call": + for item in list(rhs.args) + [x[1] for x in rhs.kws]: + add_to_itemset(item) + +def find_setitems_body(setitems, itemsset, loop_body, typemap): + """ + Find the arrays that are written into (goes into setitems) and the + mutable objects (mostly arrays) that are written into other arrays + (goes into itemsset). + """ + for label, block in loop_body.items(): + find_setitems_block(setitems, itemsset, block, typemap) + +def empty_container_allocator_hoist(inst, dep_on_param, call_table, hoisted, + not_hoisted, typemap, stored_arrays): + if (isinstance(inst, ir.Assign) and + isinstance(inst.value, ir.Expr) and + inst.value.op == 'call' and + inst.value.func.name in call_table): + call_list = call_table[inst.value.func.name] + if call_list == ['empty', np]: + return _hoist_internal(inst, dep_on_param, call_table, hoisted, + not_hoisted, typemap, stored_arrays) + return False + +def hoist(parfor_params, loop_body, typemap, wrapped_blocks): + dep_on_param = copy.copy(parfor_params) + hoisted = [] + not_hoisted = [] + + # Compute the set of variable defined exactly once in the loop body. + def_once, def_more = compute_def_once(loop_body, typemap) + (call_table, reverse_call_table) = get_call_table(wrapped_blocks) + + setitems = set() + itemsset = set() + find_setitems_body(setitems, itemsset, loop_body, typemap) + dep_on_param = list(set(dep_on_param).difference(setitems)) + if config.DEBUG_ARRAY_OPT >= 1: + print("hoist - def_once:", def_once, "setitems:", setitems, "itemsset:", itemsset, "dep_on_param:", dep_on_param, "parfor_params:", parfor_params) + for si in setitems: + add_to_def_once_sets(si, def_once, def_more) + + for label, block in loop_body.items(): + new_block = [] + for inst in block.body: + if empty_container_allocator_hoist(inst, dep_on_param, call_table, + hoisted, not_hoisted, typemap, itemsset): + continue + elif isinstance(inst, ir.Assign) and inst.target.name in def_once: + if _hoist_internal(inst, dep_on_param, call_table, + hoisted, not_hoisted, typemap, itemsset): + # don't add this instruction to the block since it is + # hoisted + continue + elif isinstance(inst, parfor.Parfor): + new_init_block = [] + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor") + inst.dump() + for ib_inst in inst.init_block.body: + if empty_container_allocator_hoist(ib_inst, dep_on_param, + call_table, hoisted, not_hoisted, typemap, itemsset): + continue + elif (isinstance(ib_inst, ir.Assign) and + ib_inst.target.name in def_once): + if _hoist_internal(ib_inst, dep_on_param, call_table, + hoisted, not_hoisted, typemap, + itemsset): + # don't add this instruction to the block since it is hoisted + continue + new_init_block.append(ib_inst) + inst.init_block.body = new_init_block + + new_block.append(inst) + block.body = new_block + return hoisted, not_hoisted + +def redtyp_is_scalar(redtype): + return not isinstance(redtype, types.npytypes.Array) + +def redtyp_to_redarraytype(redtyp): + """Go from a reducation variable type to a reduction array type used to hold + per-worker results. + """ + redarrdim = 1 + # If the reduction type is an array then allocate reduction array with ndim+1 dimensions. + if isinstance(redtyp, types.npytypes.Array): + redarrdim += redtyp.ndim + # We don't create array of array but multi-dimensional reduction array with same dtype. + redtyp = redtyp.dtype + return types.npytypes.Array(redtyp, redarrdim, "C") + +def redarraytype_to_sig(redarraytyp): + """Given a reduction array type, find the type of the reduction argument to the gufunc. + """ + assert isinstance(redarraytyp, types.npytypes.Array) + return types.npytypes.Array(redarraytyp.dtype, redarraytyp.ndim, redarraytyp.layout) + +def legalize_names_with_typemap(names, typemap): + """ We use ir_utils.legalize_names to replace internal IR variable names + containing illegal characters (e.g. period) with a legal character + (underscore) so as to create legal variable names. + The original variable names are in the typemap so we also + need to add the legalized name to the typemap as well. + """ + outdict = legalize_names(names) + # For each pair in the dict of legalized names... + for x, y in outdict.items(): + # If the name had some legalization change to it... + if x != y: + # Set the type of the new name the same as the type of the old name. + typemap[y] = typemap[x] + return outdict + +def to_scalar_from_0d(x): + if isinstance(x, types.ArrayCompatible): + if x.ndim == 0: + return x.dtype + return x + +def _create_gufunc_for_parfor_body( + lowerer, + parfor, + typemap, + typingctx, + targetctx, + flags, + locals, + has_aliases, + index_var_typ, + races): + ''' + Takes a parfor and creates a gufunc function for its body. + There are two parts to this function. + 1) Code to iterate across the iteration space as defined by the schedule. + 2) The parfor body that does the work for a single point in the iteration space. + Part 1 is created as Python text for simplicity with a sentinel assignment to mark the point + in the IR where the parfor body should be added. + This Python text is 'exec'ed into existence and its IR retrieved with run_frontend. + The IR is scanned for the sentinel assignment where that basic block is split and the IR + for the parfor body inserted. + ''' + if config.DEBUG_ARRAY_OPT >= 1: + print("starting _create_gufunc_for_parfor_body") + + loc = parfor.init_block.loc + + # The parfor body and the main function body share ir.Var nodes. + # We have to do some replacements of Var names in the parfor body to make them + # legal parameter names. If we don't copy then the Vars in the main function also + # would incorrectly change their name. + loop_body = copy.copy(parfor.loop_body) + remove_dels(loop_body) + + parfor_dim = len(parfor.loop_nests) + loop_indices = [l.index_variable.name for l in parfor.loop_nests] + + # Get all the parfor params. + parfor_params = parfor.params + # Get just the outputs of the parfor. + parfor_outputs = numba.parfors.parfor.get_parfor_outputs(parfor, parfor_params) + # Get all parfor reduction vars, and operators. + typemap = lowerer.fndesc.typemap + parfor_redvars, parfor_reddict = numba.parfors.parfor.get_parfor_reductions( + lowerer.func_ir, parfor, parfor_params, lowerer.fndesc.calltypes) + # Compute just the parfor inputs as a set difference. + parfor_inputs = sorted( + list( + set(parfor_params) - + set(parfor_outputs) - + set(parfor_redvars))) + + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor_params = ", parfor_params, " ", type(parfor_params)) + print("parfor_outputs = ", parfor_outputs, " ", type(parfor_outputs)) + print("parfor_inputs = ", parfor_inputs, " ", type(parfor_inputs)) + print("parfor_redvars = ", parfor_redvars, " ", type(parfor_redvars)) + + # ------------------------------------------------------------------------- + # Convert tuples to individual parameters. + tuple_expanded_parfor_inputs = [] + tuple_var_to_expanded_names = {} + expanded_name_to_tuple_var = {} + next_expanded_tuple_var = 0 + parfor_tuple_params = [] + # For each input to the parfor. + for pi in parfor_inputs: + # Get the type of the input. + pi_type = typemap[pi] + # If it is a UniTuple or Tuple we will do the conversion. + if isinstance(pi_type, types.UniTuple) or isinstance(pi_type, types.NamedUniTuple): + # Get the size and dtype of the tuple. + tuple_count = pi_type.count + tuple_dtype = pi_type.dtype + # Only do tuples up to config.PARFOR_MAX_TUPLE_SIZE length. + assert(tuple_count <= config.PARFOR_MAX_TUPLE_SIZE) + this_var_expansion = [] + for i in range(tuple_count): + # Generate a new name for the individual part of the tuple var. + expanded_name = "expanded_tuple_var_" + str(next_expanded_tuple_var) + # Add that name to the new list of inputs to the gufunc. + tuple_expanded_parfor_inputs.append(expanded_name) + this_var_expansion.append(expanded_name) + # Remember a mapping from new param name to original tuple + # var and the index within the tuple. + expanded_name_to_tuple_var[expanded_name] = (pi, i) + next_expanded_tuple_var += 1 + # Set the type of the new parameter. + typemap[expanded_name] = tuple_dtype + # Remember a mapping from the original tuple var to the + # individual parts. + tuple_var_to_expanded_names[pi] = this_var_expansion + parfor_tuple_params.append(pi) + elif isinstance(pi_type, types.Tuple) or isinstance(pi_type, types.NamedTuple): + # This is the same as above for UniTuple except that each part of + # the tuple can have a different type and we fetch that type with + # pi_type.types[offset]. + tuple_count = pi_type.count + tuple_types = pi_type.types + # Only do tuples up to config.PARFOR_MAX_TUPLE_SIZE length. + assert(tuple_count <= config.PARFOR_MAX_TUPLE_SIZE) + this_var_expansion = [] + for i in range(tuple_count): + expanded_name = "expanded_tuple_var_" + str(next_expanded_tuple_var) + tuple_expanded_parfor_inputs.append(expanded_name) + this_var_expansion.append(expanded_name) + expanded_name_to_tuple_var[expanded_name] = (pi, i) + next_expanded_tuple_var += 1 + typemap[expanded_name] = tuple_types[i] + tuple_var_to_expanded_names[pi] = this_var_expansion + parfor_tuple_params.append(pi) + else: + tuple_expanded_parfor_inputs.append(pi) + parfor_inputs = tuple_expanded_parfor_inputs + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor_inputs post tuple handling = ", parfor_inputs, " ", type(parfor_inputs)) + # ------------------------------------------------------------------------- + + races = races.difference(set(parfor_redvars)) + for race in races: + msg = ("Variable %s used in parallel loop may be written " + "to simultaneously by multiple workers and may result " + "in non-deterministic or unintended results." % race) + warnings.warn(NumbaParallelSafetyWarning(msg, loc)) + replace_var_with_array(races, loop_body, typemap, lowerer.fndesc.calltypes) + + # Reduction variables are represented as arrays, so they go under + # different names. + parfor_redarrs = [] + parfor_red_arg_types = [] + for var in parfor_redvars: + arr = var + "_arr" + parfor_redarrs.append(arr) + redarraytype = redtyp_to_redarraytype(typemap[var]) + parfor_red_arg_types.append(redarraytype) + redarrsig = redarraytype_to_sig(redarraytype) + if arr in typemap: + assert(typemap[arr] == redarrsig) + else: + typemap[arr] = redarrsig + + # Reorder all the params so that inputs go first then outputs. + parfor_params = parfor_inputs + parfor_outputs + parfor_redarrs + + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor_params = ", parfor_params, " ", type(parfor_params)) + print("loop_indices = ", loop_indices, " ", type(loop_indices)) + print("loop_body = ", loop_body, " ", type(loop_body)) + _print_body(loop_body) + + # Some Var are not legal parameter names so create a dict of potentially illegal + # param name to guaranteed legal name. + param_dict = legalize_names_with_typemap(parfor_params + parfor_redvars + parfor_tuple_params, typemap) + if config.DEBUG_ARRAY_OPT >= 1: + print( + "param_dict = ", + sorted( + param_dict.items()), + " ", + type(param_dict)) + + # Some loop_indices are not legal parameter names so create a dict of potentially illegal + # loop index to guaranteed legal name. + ind_dict = legalize_names_with_typemap(loop_indices, typemap) + # Compute a new list of legal loop index names. + legal_loop_indices = [ind_dict[v] for v in loop_indices] + if config.DEBUG_ARRAY_OPT >= 1: + print("ind_dict = ", sorted(ind_dict.items()), " ", type(ind_dict)) + print( + "legal_loop_indices = ", + legal_loop_indices, + " ", + type(legal_loop_indices)) + for pd in parfor_params: + print("pd = ", pd) + print("pd type = ", typemap[pd], " ", type(typemap[pd])) + + # Get the types of each parameter. + param_types = [to_scalar_from_0d(typemap[v]) for v in parfor_params] + # Calculate types of args passed to gufunc. + func_arg_types = [typemap[v] for v in (parfor_inputs + parfor_outputs)] + parfor_red_arg_types + if config.DEBUG_ARRAY_OPT >= 1: + print("new param_types:", param_types) + print("new func_arg_types:", func_arg_types) + + # Replace illegal parameter names in the loop body with legal ones. + replace_var_names(loop_body, param_dict) + # remember the name before legalizing as the actual arguments + parfor_args = parfor_params + # Change parfor_params to be legal names. + parfor_params = [param_dict[v] for v in parfor_params] + parfor_params_orig = parfor_params + + parfor_params = [] + ascontig = False + for pindex in range(len(parfor_params_orig)): + if (ascontig and + pindex < len(parfor_inputs) and + isinstance(param_types[pindex], types.npytypes.Array)): + parfor_params.append(parfor_params_orig[pindex]+"param") + else: + parfor_params.append(parfor_params_orig[pindex]) + + # Change parfor body to replace illegal loop index vars with legal ones. + replace_var_names(loop_body, ind_dict) + loop_body_var_table = get_name_var_table(loop_body) + sentinel_name = get_unused_var_name("__sentinel__", loop_body_var_table) + + if config.DEBUG_ARRAY_OPT >= 1: + print( + "legal parfor_params = ", + parfor_params, + " ", + type(parfor_params)) + + # Determine the unique names of the scheduling and gufunc functions. + # sched_func_name = "__numba_parfor_sched_%s" % (hex(hash(parfor)).replace("-", "_")) + gufunc_name = "__numba_parfor_gufunc_%s" % ( + hex(hash(parfor)).replace("-", "_")) + if config.DEBUG_ARRAY_OPT: + # print("sched_func_name ", type(sched_func_name), " ", sched_func_name) + print("gufunc_name ", type(gufunc_name), " ", gufunc_name) + + gufunc_txt = "" + + # Create the gufunc function. + gufunc_txt += "def " + gufunc_name + \ + "(sched, " + (", ".join(parfor_params)) + "):\n" + + globls = {"np": np, "numba": numba} + + # First thing in the gufunc, we reconstruct tuples from their + # individual parts, e.g., orig_tup_name = (part1, part2,). + # The rest of the code of the function will use the original tuple name. + for tup_var, exp_names in tuple_var_to_expanded_names.items(): + tup_type = typemap[tup_var] + gufunc_txt += " " + param_dict[tup_var] + # Determine if the tuple is a named tuple. + if (isinstance(tup_type, types.NamedTuple) or + isinstance(tup_type, types.NamedUniTuple)): + named_tup = True + else: + named_tup = False + + if named_tup: + # It is a named tuple so try to find the global that defines the + # named tuple. + func_def = guard(get_definition, lowerer.func_ir, tup_var) + named_tuple_def = None + if config.DEBUG_ARRAY_OPT: + print("func_def:", func_def, type(func_def)) + if func_def is not None: + if (isinstance(func_def, ir.Expr) and + func_def.op == 'call'): + named_tuple_def = guard(get_definition, lowerer.func_ir, func_def.func) + if config.DEBUG_ARRAY_OPT: + print("named_tuple_def:", named_tuple_def, type(named_tuple_def)) + elif isinstance(func_def, ir.Arg): + named_tuple_def = typemap[func_def.name] + if config.DEBUG_ARRAY_OPT: + print("named_tuple_def:", named_tuple_def, + type(named_tuple_def), named_tuple_def.name) + if named_tuple_def is not None: + if (isinstance(named_tuple_def, ir.Global) or + isinstance(named_tuple_def, ir.FreeVar)): + gval = named_tuple_def.value + if config.DEBUG_ARRAY_OPT: + print("gval:", gval, type(gval)) + globls[named_tuple_def.name] = gval + elif isinstance(named_tuple_def, types.containers.BaseNamedTuple): + named_tuple_name = named_tuple_def.name.split('(')[0] + if config.DEBUG_ARRAY_OPT: + print("name:", named_tuple_name, + named_tuple_def.instance_class, + type(named_tuple_def.instance_class)) + globls[named_tuple_name] = named_tuple_def.instance_class + else: + if config.DEBUG_ARRAY_OPT: + print("Didn't find definition of namedtuple for globls.") + raise CompilerError("Could not find definition of " + str(tup_var), + tup_var.loc) + gufunc_txt += " = " + tup_type.instance_class.__name__ + "(" + for name, field_name in zip(exp_names, tup_type.fields): + gufunc_txt += field_name + "=" + param_dict[name] + "," + else: + # Just a regular tuple so use (part0, part1, ...) + gufunc_txt += " = (" + ", ".join([param_dict[x] for x in exp_names]) + if len(exp_names) == 1: + # Add comma for tuples with singular values. We can't unilaterally + # add a comma always because (,) isn't valid. + gufunc_txt += "," + + gufunc_txt += ")\n" + + for pindex in range(len(parfor_inputs)): + if ascontig and isinstance(param_types[pindex], types.npytypes.Array): + gufunc_txt += (" " + parfor_params_orig[pindex] + + " = np.ascontiguousarray(" + parfor_params[pindex] + ")\n") + + gufunc_thread_id_var = "ParallelAcceleratorGufuncThreadId" + + if len(parfor_redarrs) > 0: + gufunc_txt += " " + gufunc_thread_id_var + " = " + gufunc_txt += "numba.np.ufunc.parallel._iget_thread_id()\n" + + # Add initialization of reduction variables + for arr, var in zip(parfor_redarrs, parfor_redvars): + gufunc_txt += " " + param_dict[var] + \ + "=" + param_dict[arr] + "[" + gufunc_thread_id_var + "]\n" + if config.DEBUG_ARRAY_OPT_RUNTIME: + gufunc_txt += " print(\"thread id =\", ParallelAcceleratorGufuncThreadId)\n" + gufunc_txt += " print(\"initial reduction value\",ParallelAcceleratorGufuncThreadId," + param_dict[var] + "," + param_dict[var] + ".shape)\n" + gufunc_txt += " print(\"reduction array\",ParallelAcceleratorGufuncThreadId," + param_dict[arr] + "," + param_dict[arr] + ".shape)\n" + + # For each dimension of the parfor, create a for loop in the generated gufunc function. + # Iterate across the proper values extracted from the schedule. + # The form of the schedule is start_dim0, start_dim1, ..., start_dimN, end_dim0, + # end_dim1, ..., end_dimN + for eachdim in range(parfor_dim): + for indent in range(eachdim + 1): + gufunc_txt += " " + sched_dim = eachdim + gufunc_txt += ("for " + + legal_loop_indices[eachdim] + + " in range(sched[" + + str(sched_dim) + + "], sched[" + + str(sched_dim + + parfor_dim) + + "] + np.uint8(1)):\n") + + if config.DEBUG_ARRAY_OPT_RUNTIME: + for indent in range(parfor_dim + 1): + gufunc_txt += " " + gufunc_txt += "print(" + for eachdim in range(parfor_dim): + gufunc_txt += "\"" + legal_loop_indices[eachdim] + "\"," + legal_loop_indices[eachdim] + "," + gufunc_txt += ")\n" + + # Add the sentinel assignment so that we can find the loop body position + # in the IR. + for indent in range(parfor_dim + 1): + gufunc_txt += " " + gufunc_txt += sentinel_name + " = 0\n" + # Add assignments of reduction variables (for returning the value) + for arr, var in zip(parfor_redarrs, parfor_redvars): + if config.DEBUG_ARRAY_OPT_RUNTIME: + gufunc_txt += " print(\"final reduction value\",ParallelAcceleratorGufuncThreadId," + param_dict[var] + ")\n" + gufunc_txt += " print(\"final reduction array\",ParallelAcceleratorGufuncThreadId," + param_dict[arr] + ")\n" + # After the gufunc loops, copy the accumulated temp value back to reduction array. + gufunc_txt += " " + param_dict[arr] + \ + "[" + gufunc_thread_id_var + "] = " + param_dict[var] + "\n" + gufunc_txt += " return None\n" + + if config.DEBUG_ARRAY_OPT: + print("gufunc_txt = ", type(gufunc_txt), "\n", gufunc_txt) + print("globls:", globls, type(globls)) + # Force gufunc outline into existence. + locls = {} + exec(gufunc_txt, globls, locls) + gufunc_func = locls[gufunc_name] + + if config.DEBUG_ARRAY_OPT: + print("gufunc_func = ", type(gufunc_func), "\n", gufunc_func) + # Get the IR for the gufunc outline. + gufunc_ir = compiler.run_frontend(gufunc_func) + if config.DEBUG_ARRAY_OPT: + print("gufunc_ir dump ", type(gufunc_ir)) + gufunc_ir.dump() + print("loop_body dump ", type(loop_body)) + _print_body(loop_body) + + # rename all variables in gufunc_ir afresh + var_table = get_name_var_table(gufunc_ir.blocks) + new_var_dict = {} + reserved_names = [sentinel_name] + \ + list(param_dict.values()) + legal_loop_indices + for name, var in var_table.items(): + if not (name in reserved_names): + new_var_dict[name] = parfor.init_block.scope.redefine(name, loc).name + replace_var_names(gufunc_ir.blocks, new_var_dict) + if config.DEBUG_ARRAY_OPT: + print("gufunc_ir dump after renaming ") + gufunc_ir.dump() + gufunc_param_types = [types.npytypes.Array( + index_var_typ, 1, "C")] + param_types + if config.DEBUG_ARRAY_OPT: + print( + "gufunc_param_types = ", + type(gufunc_param_types), + "\n", + gufunc_param_types) + + gufunc_stub_last_label = find_max_label(gufunc_ir.blocks) + 1 + + # Add gufunc stub last label to each parfor.loop_body label to prevent + # label conflicts. + loop_body = add_offset_to_labels(loop_body, gufunc_stub_last_label) + # new label for splitting sentinel block + new_label = find_max_label(loop_body) + 1 + + # If enabled, add a print statement after every assignment. + if config.DEBUG_ARRAY_OPT_RUNTIME: + for label, block in loop_body.items(): + new_block = block.copy() + new_block.clear() + loc = block.loc + scope = block.scope + for inst in block.body: + new_block.append(inst) + # Append print after assignment + if isinstance(inst, ir.Assign): + # Only apply to numbers + if typemap[inst.target.name] not in types.number_domain: + continue + + # Make constant string + strval = "{} =".format(inst.target.name) + strconsttyp = types.StringLiteral(strval) + + lhs = scope.redefine("str_const", loc) + # lhs = ir.Var(scope, mk_unique_var("str_const"), loc) + assign_lhs = ir.Assign(value=ir.Const(value=strval, loc=loc), + target=lhs, loc=loc) + typemap[lhs.name] = strconsttyp + new_block.append(assign_lhs) + + # Make print node + print_node = ir.Print(args=[lhs, inst.target], vararg=None, loc=loc) + new_block.append(print_node) + sig = numba.core.typing.signature(types.none, + typemap[lhs.name], + typemap[inst.target.name]) + lowerer.fndesc.calltypes[print_node] = sig + loop_body[label] = new_block + + if config.DEBUG_ARRAY_OPT: + print("parfor loop body") + _print_body(loop_body) + + wrapped_blocks = wrap_loop_body(loop_body) + hoisted, not_hoisted = hoist(parfor_params, loop_body, typemap, wrapped_blocks) + start_block = gufunc_ir.blocks[min(gufunc_ir.blocks.keys())] + start_block.body = start_block.body[:-1] + hoisted + [start_block.body[-1]] + unwrap_loop_body(loop_body) + + # store hoisted into diagnostics + diagnostics = lowerer.metadata['parfor_diagnostics'] + diagnostics.hoist_info[parfor.id] = {'hoisted': hoisted, + 'not_hoisted': not_hoisted} + + if config.DEBUG_ARRAY_OPT: + print("After hoisting") + _print_body(loop_body) + + # Search all the block in the gufunc outline for the sentinel assignment. + for label, block in gufunc_ir.blocks.items(): + for i, inst in enumerate(block.body): + if isinstance( + inst, + ir.Assign) and inst.target.name == sentinel_name: + # We found the sentinel assignment. + loc = inst.loc + scope = block.scope + # split block across __sentinel__ + # A new block is allocated for the statements prior to the sentinel + # but the new block maintains the current block label. + prev_block = ir.Block(scope, loc) + prev_block.body = block.body[:i] + # The current block is used for statements after the sentinel. + block.body = block.body[i + 1:] + # But the current block gets a new label. + body_first_label = min(loop_body.keys()) + + # The previous block jumps to the minimum labelled block of the + # parfor body. + prev_block.append(ir.Jump(body_first_label, loc)) + # Add all the parfor loop body blocks to the gufunc function's + # IR. + for (l, b) in loop_body.items(): + gufunc_ir.blocks[l] = transfer_scope(b, scope) + body_last_label = max(loop_body.keys()) + gufunc_ir.blocks[new_label] = block + gufunc_ir.blocks[label] = prev_block + # Add a jump from the last parfor body block to the block containing + # statements after the sentinel. + gufunc_ir.blocks[body_last_label].append( + ir.Jump(new_label, loc)) + break + else: + continue + break + + if config.DEBUG_ARRAY_OPT: + print("gufunc_ir last dump before renaming") + gufunc_ir.dump() + + gufunc_ir.blocks = rename_labels(gufunc_ir.blocks) + remove_dels(gufunc_ir.blocks) + + if config.DEBUG_ARRAY_OPT: + print("gufunc_ir last dump") + gufunc_ir.dump() + print("flags", flags) + print("typemap", typemap) + + old_alias = flags.noalias + if not has_aliases: + if config.DEBUG_ARRAY_OPT: + print("No aliases found so adding noalias flag.") + flags.noalias = True + + fixup_var_define_in_scope(gufunc_ir.blocks) + + class ParforGufuncCompiler(compiler.CompilerBase): + def define_pipelines(self): + from numba.core.compiler_machinery import PassManager + dpb = compiler.DefaultPassBuilder + pm = PassManager("full_parfor_gufunc") + parfor_gufunc_passes = dpb.define_parfor_gufunc_pipeline(self.state) + pm.passes.extend(parfor_gufunc_passes.passes) + lowering_passes = dpb.define_parfor_gufunc_nopython_lowering_pipeline(self.state) + pm.passes.extend(lowering_passes.passes) + + pm.finalize() + return [pm] + + kernel_func = compiler.compile_ir( + typingctx, + targetctx, + gufunc_ir, + gufunc_param_types, + types.none, + flags, + locals, + pipeline_class=ParforGufuncCompiler) + + flags.noalias = old_alias + + kernel_sig = signature(types.none, *gufunc_param_types) + if config.DEBUG_ARRAY_OPT: + print("finished create_gufunc_for_parfor_body. kernel_sig = ", kernel_sig) + + return kernel_func, parfor_args, kernel_sig, func_arg_types, expanded_name_to_tuple_var + +def replace_var_with_array_in_block(vars, block, typemap, calltypes): + new_block = [] + for inst in block.body: + if isinstance(inst, ir.Assign) and inst.target.name in vars: + loc = inst.loc + scope = inst.target.scope + + const_node = ir.Const(0, loc) + const_var = scope.redefine("$const_ind_0", loc) + typemap[const_var.name] = types.uintp + const_assign = ir.Assign(const_node, const_var, loc) + new_block.append(const_assign) + + val_var = scope.redefine("$val", loc) + typemap[val_var.name] = typemap[inst.target.name] + new_block.append(ir.Assign(inst.value, val_var, loc)) + setitem_node = ir.SetItem(inst.target, const_var, val_var, loc) + calltypes[setitem_node] = signature( + types.none, types.npytypes.Array(typemap[inst.target.name], 1, "C"), types.intp, typemap[inst.target.name]) + new_block.append(setitem_node) + continue + elif isinstance(inst, parfor.Parfor): + replace_var_with_array_internal(vars, {0: inst.init_block}, typemap, calltypes) + replace_var_with_array_internal(vars, inst.loop_body, typemap, calltypes) + + new_block.append(inst) + return new_block + +def replace_var_with_array_internal(vars, loop_body, typemap, calltypes): + for label, block in loop_body.items(): + block.body = replace_var_with_array_in_block(vars, block, typemap, calltypes) + +def replace_var_with_array(vars, loop_body, typemap, calltypes): + replace_var_with_array_internal(vars, loop_body, typemap, calltypes) + for v in vars: + el_typ = typemap[v] + typemap.pop(v, None) + typemap[v] = types.npytypes.Array(el_typ, 1, "C") + +def call_parallel_gufunc(lowerer, cres, gu_signature, outer_sig, expr_args, expr_arg_types, + loop_ranges, redvars, reddict, redarrdict, init_block, index_var_typ, races, + exp_name_to_tuple_var): + ''' + Adds the call to the gufunc function from the main function. + ''' + context = lowerer.context + builder = lowerer.builder + + from numba.np.ufunc.parallel import (build_gufunc_wrapper, + _launch_threads) + + if config.DEBUG_ARRAY_OPT: + print("make_parallel_loop") + print("outer_sig = ", outer_sig.args, outer_sig.return_type, + outer_sig.recvr, outer_sig.pysig) + print("loop_ranges = ", loop_ranges) + print("expr_args", expr_args) + print("expr_arg_types", expr_arg_types) + print("gu_signature", gu_signature) + + # Build the wrapper for GUFunc + args, return_type = sigutils.normalize_signature(outer_sig) + llvm_func = cres.library.get_function(cres.fndesc.llvm_func_name) + sin, sout = gu_signature + + # These are necessary for build_gufunc_wrapper to find external symbols + _launch_threads() + + info = build_gufunc_wrapper(llvm_func, cres, sin, sout, + cache=False, is_parfors=True) + wrapper_name = info.name + cres.library._ensure_finalized() + + if config.DEBUG_ARRAY_OPT: + print("parallel function = ", wrapper_name, cres) + + # loadvars for loop_ranges + def load_range(v): + if isinstance(v, ir.Var): + return lowerer.loadvar(v.name) + else: + return context.get_constant(types.uintp, v) + + num_dim = len(loop_ranges) + for i in range(num_dim): + start, stop, step = loop_ranges[i] + start = load_range(start) + stop = load_range(stop) + assert(step == 1) # We do not support loop steps other than 1 + step = load_range(step) + loop_ranges[i] = (start, stop, step) + + if config.DEBUG_ARRAY_OPT: + print("call_parallel_gufunc loop_ranges[{}] = ".format(i), start, + stop, step) + cgutils.printf(builder, "loop range[{}]: %d %d (%d)\n".format(i), + start, stop, step) + + # Commonly used LLVM types and constants + byte_t = llvmlite.ir.IntType(8) + byte_ptr_t = llvmlite.ir.PointerType(byte_t) + byte_ptr_ptr_t = llvmlite.ir.PointerType(byte_ptr_t) + intp_t = context.get_value_type(types.intp) + uintp_t = context.get_value_type(types.uintp) + intp_ptr_t = llvmlite.ir.PointerType(intp_t) + intp_ptr_ptr_t = llvmlite.ir.PointerType(intp_ptr_t) + uintp_ptr_t = llvmlite.ir.PointerType(uintp_t) + uintp_ptr_ptr_t = llvmlite.ir.PointerType(uintp_ptr_t) + zero = context.get_constant(types.uintp, 0) + one = context.get_constant(types.uintp, 1) + one_type = one.type + sizeof_intp = context.get_abi_sizeof(intp_t) + + # Prepare sched, first pop it out of expr_args, outer_sig, and gu_signature + expr_args.pop(0) + sched_sig = sin.pop(0) + + if config.DEBUG_ARRAY_OPT: + print("Parfor has potentially negative start", index_var_typ.signed) + + if index_var_typ.signed: + sched_type = intp_t + sched_ptr_type = intp_ptr_t + sched_ptr_ptr_type = intp_ptr_ptr_t + else: + sched_type = uintp_t + sched_ptr_type = uintp_ptr_t + sched_ptr_ptr_type = uintp_ptr_ptr_t + + # Call do_scheduling with appropriate arguments + dim_starts = cgutils.alloca_once( + builder, sched_type, size=context.get_constant( + types.uintp, num_dim), name="dim_starts") + dim_stops = cgutils.alloca_once( + builder, sched_type, size=context.get_constant( + types.uintp, num_dim), name="dim_stops") + for i in range(num_dim): + start, stop, step = loop_ranges[i] + if start.type != one_type: + start = builder.sext(start, one_type) + if stop.type != one_type: + stop = builder.sext(stop, one_type) + if step.type != one_type: + step = builder.sext(step, one_type) + # substract 1 because do-scheduling takes inclusive ranges + stop = builder.sub(stop, one) + builder.store( + start, builder.gep( + dim_starts, [ + context.get_constant( + types.uintp, i)])) + builder.store(stop, builder.gep(dim_stops, + [context.get_constant(types.uintp, i)])) + + # Prepare to call get/set parallel_chunksize and get the number of threads. + get_chunksize = cgutils.get_or_insert_function( + builder.module, + llvmlite.ir.FunctionType(uintp_t, []), + name="get_parallel_chunksize") + + set_chunksize = cgutils.get_or_insert_function( + builder.module, + llvmlite.ir.FunctionType(llvmlite.ir.VoidType(), [uintp_t]), + name="set_parallel_chunksize") + + get_num_threads = cgutils.get_or_insert_function( + builder.module, + llvmlite.ir.FunctionType(llvmlite.ir.IntType(types.intp.bitwidth), []), + "get_num_threads") + + # Get the current number of threads. + num_threads = builder.call(get_num_threads, []) + # Get the current chunksize so we can use it and restore the value later. + current_chunksize = builder.call(get_chunksize, []) + + with cgutils.if_unlikely(builder, builder.icmp_signed('<=', num_threads, + num_threads.type(0))): + cgutils.printf(builder, "num_threads: %d\n", num_threads) + context.call_conv.return_user_exc(builder, RuntimeError, + ("Invalid number of threads. " + "This likely indicates a bug in Numba.",)) + + # Call get_sched_size from gufunc_scheduler.cpp that incorporates the size of the work, + # the number of threads and the selected chunk size. This will tell us how many entries + # in the schedule we will need. + get_sched_size_fnty = llvmlite.ir.FunctionType(uintp_t, [uintp_t, uintp_t, intp_ptr_t, intp_ptr_t]) + get_sched_size = cgutils.get_or_insert_function( + builder.module, + get_sched_size_fnty, + name="get_sched_size") + num_divisions = builder.call(get_sched_size, [num_threads, + context.get_constant(types.uintp, num_dim), + dim_starts, + dim_stops]) + # Set the chunksize to zero so that any nested calls get the default chunk size behavior. + builder.call(set_chunksize, [zero]) + + # Each entry in the schedule is 2 times the number of dimensions long. + multiplier = context.get_constant(types.uintp, num_dim * 2) + # Compute the total number of entries in the schedule. + sched_size = builder.mul(num_divisions, multiplier) + + # Prepare to dynamically allocate memory to hold the schedule. + alloc_sched_fnty = llvmlite.ir.FunctionType(sched_ptr_type, [uintp_t]) + alloc_sched_func = cgutils.get_or_insert_function( + builder.module, + alloc_sched_fnty, + name="allocate_sched") + # Call gufunc_scheduler.cpp to allocate the schedule. + # This may or may not do pooling. + alloc_space = builder.call(alloc_sched_func, [sched_size]) + # Allocate a slot in the entry block to store the schedule pointer. + sched = cgutils.alloca_once(builder, sched_ptr_type) + # Store the schedule pointer into that slot. + builder.store(alloc_space, sched) + + debug_flag = 1 if config.DEBUG_ARRAY_OPT else 0 + scheduling_fnty = llvmlite.ir.FunctionType( + intp_ptr_t, [uintp_t, intp_ptr_t, intp_ptr_t, uintp_t, sched_ptr_type, intp_t]) + if index_var_typ.signed: + do_scheduling = cgutils.get_or_insert_function(builder.module, + scheduling_fnty, + name="do_scheduling_signed") + else: + do_scheduling = cgutils.get_or_insert_function(builder.module, + scheduling_fnty, + name="do_scheduling_unsigned") + + # Call the scheduling routine that decides how to break up the work. + builder.call( + do_scheduling, [ + context.get_constant( + types.uintp, num_dim), dim_starts, dim_stops, num_divisions, + builder.load(sched), context.get_constant( + types.intp, debug_flag)]) + + # Get the LLVM vars for the Numba IR reduction array vars. + redarrs = [lowerer.loadvar(redarrdict[x].name) for x in redvars] + + nredvars = len(redvars) + ninouts = len(expr_args) - nredvars + + def load_potential_tuple_var(x): + """Given a variable name, if that variable is not a new name + introduced as the extracted part of a tuple then just return + the variable loaded from its name. However, if the variable + does represent part of a tuple, as recognized by the name of + the variable being present in the exp_name_to_tuple_var dict, + then we load the original tuple var instead that we get from + the dict and then extract the corresponding element of the + tuple, also stored and returned to use in the dict (i.e., offset). + """ + if x in exp_name_to_tuple_var: + orig_tup, offset = exp_name_to_tuple_var[x] + tup_var = lowerer.loadvar(orig_tup) + res = builder.extract_value(tup_var, offset) + return res + else: + return lowerer.loadvar(x) + + # ---------------------------------------------------------------------------- + # Prepare arguments: args, shapes, steps, data + all_args = [load_potential_tuple_var(x) for x in expr_args[:ninouts]] + redarrs + num_args = len(all_args) + num_inps = len(sin) + 1 + args = cgutils.alloca_once( + builder, + byte_ptr_t, + size=context.get_constant( + types.intp, + 1 + num_args), + name="pargs") + array_strides = [] + # sched goes first + builder.store(builder.bitcast(builder.load(sched), byte_ptr_t), args) + array_strides.append(context.get_constant(types.intp, sizeof_intp)) + rv_to_arg_dict = {} + # followed by other arguments + for i in range(num_args): + arg = all_args[i] + var = expr_args[i] + aty = expr_arg_types[i] + dst = builder.gep(args, [context.get_constant(types.intp, i + 1)]) + if i >= ninouts: # reduction variables + ary = context.make_array(aty)(context, builder, arg) + strides = cgutils.unpack_tuple(builder, ary.strides, aty.ndim) + # Start from 1 because we skip the first dimension of length num_threads just like sched. + for j in range(len(strides)): + array_strides.append(strides[j]) + builder.store(builder.bitcast(ary.data, byte_ptr_t), dst) + elif isinstance(aty, types.ArrayCompatible): + if var in races: + typ = (context.get_data_type(aty.dtype) + if aty.dtype != types.boolean + else llvmlite.ir.IntType(1)) + + rv_arg = cgutils.alloca_once(builder, typ) + builder.store(arg, rv_arg) + builder.store(builder.bitcast(rv_arg, byte_ptr_t), dst) + rv_to_arg_dict[var] = (arg, rv_arg) + + array_strides.append(context.get_constant(types.intp, context.get_abi_sizeof(typ))) + else: + ary = context.make_array(aty)(context, builder, arg) + strides = cgutils.unpack_tuple(builder, ary.strides, aty.ndim) + for j in range(len(strides)): + array_strides.append(strides[j]) + builder.store(builder.bitcast(ary.data, byte_ptr_t), dst) + else: + if i < num_inps: + # Scalar input, need to store the value in an array of size 1 + if isinstance(aty, types.Optional): + # Unpack optional type + unpacked_aty = aty.type + arg = context.cast(builder, arg, aty, unpacked_aty) + else: + unpacked_aty = aty + typ = (context.get_data_type(unpacked_aty) + if not isinstance(unpacked_aty, types.Boolean) + else llvmlite.ir.IntType(1)) + ptr = cgutils.alloca_once(builder, typ) + builder.store(arg, ptr) + else: + # Scalar output, must allocate + typ = (context.get_data_type(aty) + if not isinstance(aty, types.Boolean) + else llvmlite.ir.IntType(1)) + ptr = cgutils.alloca_once(builder, typ) + builder.store(builder.bitcast(ptr, byte_ptr_t), dst) + + # ---------------------------------------------------------------------------- + # Next, we prepare the individual dimension info recorded in gu_signature + sig_dim_dict = {} + occurrences = [] + occurrences = [sched_sig[0]] + sig_dim_dict[sched_sig[0]] = context.get_constant(types.intp, 2 * num_dim) + assert len(expr_args) == len(all_args) + assert len(expr_args) == len(expr_arg_types) + assert len(expr_args) == len(sin + sout) + assert len(expr_args) == len(outer_sig.args[1:]) + for var, arg, aty, gu_sig in zip(expr_args, all_args, + expr_arg_types, sin + sout): + if isinstance(aty, types.npytypes.Array): + i = aty.ndim - len(gu_sig) + else: + i = 0 + if config.DEBUG_ARRAY_OPT: + print("var =", var, "gu_sig =", gu_sig, "type =", aty, "i =", i) + + for dim_sym in gu_sig: + if config.DEBUG_ARRAY_OPT: + print("var = ", var, " type = ", aty) + if var in races: + sig_dim_dict[dim_sym] = context.get_constant(types.intp, 1) + else: + ary = context.make_array(aty)(context, builder, arg) + shapes = cgutils.unpack_tuple(builder, ary.shape, aty.ndim) + sig_dim_dict[dim_sym] = shapes[i] + + if not (dim_sym in occurrences): + if config.DEBUG_ARRAY_OPT: + print("dim_sym = ", dim_sym, ", i = ", i) + cgutils.printf(builder, dim_sym + " = %d\n", sig_dim_dict[dim_sym]) + occurrences.append(dim_sym) + i = i + 1 + + # ---------------------------------------------------------------------------- + # Prepare shapes, which is a single number (outer loop size), followed by + # the size of individual shape variables. + nshapes = len(sig_dim_dict) + 1 + shapes = cgutils.alloca_once(builder, intp_t, size=nshapes, name="pshape") + # For now, outer loop size is the same as number of threads + builder.store(num_divisions, shapes) + # Individual shape variables go next + i = 1 + for dim_sym in occurrences: + if config.DEBUG_ARRAY_OPT: + cgutils.printf(builder, dim_sym + " = %d\n", sig_dim_dict[dim_sym]) + builder.store( + sig_dim_dict[dim_sym], builder.gep( + shapes, [ + context.get_constant( + types.intp, i)])) + i = i + 1 + + # ---------------------------------------------------------------------------- + # Prepare steps for each argument. Note that all steps are counted in + # bytes. + num_steps = num_args + 1 + len(array_strides) + steps = cgutils.alloca_once( + builder, intp_t, size=context.get_constant( + types.intp, num_steps), name="psteps") + # First goes the step size for sched, which is 2 * num_dim + builder.store(context.get_constant(types.intp, 2 * num_dim * sizeof_intp), + steps) + # The steps for all others are 0, except for reduction results. + for i in range(num_args): + # steps are strides from one thread to the next + stepsize = zero + + dst = builder.gep(steps, [context.get_constant(types.intp, 1 + i)]) + builder.store(stepsize, dst) + for j in range(len(array_strides)): + dst = builder.gep( + steps, [ + context.get_constant( + types.intp, 1 + num_args + j)]) + builder.store(array_strides[j], dst) + + # ---------------------------------------------------------------------------- + # prepare data + data = cgutils.get_null_value(byte_ptr_t) + + fnty = llvmlite.ir.FunctionType(llvmlite.ir.VoidType(), + [byte_ptr_ptr_t, intp_ptr_t, + intp_ptr_t, byte_ptr_t]) + + fn = cgutils.get_or_insert_function(builder.module, fnty, wrapper_name) + context.active_code_library.add_linking_library(info.library) + + if config.DEBUG_ARRAY_OPT: + cgutils.printf(builder, "before calling kernel %p\n", fn) + builder.call(fn, [args, shapes, steps, data]) + if config.DEBUG_ARRAY_OPT: + cgutils.printf(builder, "after calling kernel %p\n", fn) + + builder.call(set_chunksize, [current_chunksize]) + + # Deallocate the schedule's memory. + dealloc_sched_fnty = llvmlite.ir.FunctionType(llvmlite.ir.VoidType(), [sched_ptr_type]) + dealloc_sched_func = cgutils.get_or_insert_function( + builder.module, + dealloc_sched_fnty, + name="deallocate_sched") + builder.call(dealloc_sched_func, [builder.load(sched)]) + + for k, v in rv_to_arg_dict.items(): + arg, rv_arg = v + only_elem_ptr = builder.gep(rv_arg, [context.get_constant(types.intp, 0)]) + builder.store(builder.load(only_elem_ptr), lowerer.getvar(k)) + + context.active_code_library.add_linking_library(cres.library) diff --git a/shared/package-files/d1/d11a5a4f1adb5ff9a5d08b2c8a0424aff10ced87e9b342c1c348dfd4a468bf82/blob b/shared/package-files/d1/d11a5a4f1adb5ff9a5d08b2c8a0424aff10ced87e9b342c1c348dfd4a468bf82/blob new file mode 100644 index 0000000000000000000000000000000000000000..4afa383fce34a490df0842baa76f96cbf8b008cb Binary files /dev/null and b/shared/package-files/d1/d11a5a4f1adb5ff9a5d08b2c8a0424aff10ced87e9b342c1c348dfd4a468bf82/blob differ diff --git a/shared/package-files/d1/d11e5dfca67654cfb9f73d9afce9ca94c45403af02741c7ac346c25ded1d2a94/blob b/shared/package-files/d1/d11e5dfca67654cfb9f73d9afce9ca94c45403af02741c7ac346c25ded1d2a94/blob new file mode 100644 index 0000000000000000000000000000000000000000..37d4d43e9d31317f19e751cc4df84c24c33eacdc --- /dev/null +++ b/shared/package-files/d1/d11e5dfca67654cfb9f73d9afce9ca94c45403af02741c7ac346c25ded1d2a94/blob @@ -0,0 +1,2735 @@ +error(0.005247033384386120061) D0 D2 +error(0.002365719851682635509) D0 D2 ^ D8 +error(0.00709986707290544139) D0 D3 +error(0.0235681297406859433) D0 D5 +error(0.001579458744141658396) D0 D5 ^ D7 D8 +error(0.001679896228431447536) D0 D5 ^ D8 +error(0.001178678162796753786) D0 D9 +error(0.001182534666519000207) D0 D9 ^ D7 +error(1.708446806160723511e-05) D0 D9 ^ D8 +error(0.005566948622101506976) D0 D10 +error(0.001218088392217476579) D0 D10 ^ D7 D8 +error(0.001131052713393134726) D0 D10 ^ D8 +error(0.01000000000000000021) D0 L0 +error(0.01233186767969363107) D1 D3 +error(0.0267802740380216342) D1 D9 +error(0.006140591503301702329) D1 L0 +error(0.007159931392602392024) D2 +error(0.00197522655828528482) D2 D5 +error(0.001048676476657278657) D2 D5 ^ D8 +error(0.02894961631209370598) D2 D6 +error(0.002432028202608478747) D2 D6 ^ D8 +error(0.001619820135838695441) D2 D10 +error(0.002225163840948356144) D2 D10 ^ D8 +error(0.02069439084540728238) D3 +error(0.006997458433291368733) D3 D9 +error(0.02481760775705407762) D3 D10 +error(0.005437021202212093639) D3 D10 ^ D11 +error(0.01206323800594592995) D3 ^ D11 +error(0.02895884271563467158) D4 +error(0.01416911292538884995) D4 D7 +error(0.01125385467889417762) D4 D7 ^ D5 L0 +error(0.02137993200743813771) D4 D12 +error(0.004131755026116961001) D4 D12 ^ D13 L0 +error(0.002903203036019879387) D4 D15 +error(0.003328581296933910347) D4 D15 ^ D5 L0 +error(0.002153497648560191106) D4 D15 ^ D13 L0 +error(0.00132794561778247131) D4 D15 ^ D13 L0 ^ D5 L0 +error(0.002297625395399578718) D4 D16 +error(0.001564841148743489939) D4 D16 ^ D5 D13 +error(0.0003724936510519168045) D4 D16 ^ D5 L0 +error(0.0003891805678224126625) D4 D16 ^ D13 L0 +error(0.006317473467851721439) D4 ^ D5 L0 +error(0.002754177369565753448) D4 ^ D13 L0 +error(0.003687446986055130382) D5 D13 ^ D4 +error(0.009964433782929760924) D5 D6 +error(0.0002827200622917192853) D5 D6 ^ D7 D16 +error(0.01025263204237844908) D5 D6 ^ D8 +error(0.002689376411773483633) D5 D6 ^ D8 D16 +error(0.001802538463770141227) D5 D6 ^ D16 +error(4.045483039878490701e-05) D5 D6 ^ D16 ^ D4 +error(0.01424943752967964238) D5 D10 +error(0.0117143577012539038) D5 D10 ^ D7 D8 +error(0.03140897183913322899) D5 D13 +error(0.002019920062412751318) D5 D13 ^ D15 D16 +error(0.001834189692617856256) D5 D13 ^ D16 +error(0.003283249611206463282) D5 D17 +error(0.002217039097925698875) D5 D17 ^ D7 D15 +error(0.0004311616500379738615) D5 D17 ^ D7 D16 +error(0.0003601196358267589183) D5 D17 ^ D15 D16 +error(0.005495111026433003795) D5 D18 +error(0.001924571388590668678) D5 D18 ^ D7 D8 +error(0.001919238098036685951) D5 D18 ^ D7 D15 +error(0.001542925559449527615) D5 D18 ^ D7 D16 +error(0.0004065625308521262694) D5 D18 ^ D8 D16 +error(0.001517534904390731645) D5 D18 ^ D15 D16 +error(0.01000000000000000021) D5 L0 +error(0.000630023031437223005) D5 L0 ^ D15 +error(0.003559447081430625569) D7 D15 ^ D5 L0 +error(0.008658742439454742215) D6 +error(0.002359226002129251928) D6 D13 +error(0.0004700885901282171966) D6 D13 ^ D4 +error(0.002842631538867582044) D6 D13 ^ D16 +error(0.03323098142033485691) D6 D14 +error(0.003694859541453752051) D6 D14 ^ D16 +error(0.001887308115760311577) D6 D18 +error(7.667254054394448501e-05) D6 D18 ^ D7 D8 +error(0.0001684128039816316761) D6 D18 ^ D7 D16 +error(0.00155935512012112215) D6 D18 ^ D8 D16 +error(0.01673647897006439247) D6 ^ D8 +error(0.002208325456735622545) D6 ^ D16 ^ D8 +error(0.05155903350266815427) D7 +error(0.01982707686764454552) D7 D8 +error(0.001565915411827527564) D7 D8 ^ D10 +error(0.002025462288331955976) D7 D8 ^ D10 D18 +error(0.002676727229798968322) D7 D8 ^ D18 +error(0.04979648365038458202) D7 D15 +error(0.004075575823084270563) D7 D15 ^ D17 D18 +error(0.003228899945508421909) D7 D16 +error(0.0006267629478556474868) D7 D16 ^ D17 D18 +error(0.001819731574192852766) D7 D19 +error(0.001044374947872651286) D7 D19 ^ D10 +error(0.001721977742605806461) D7 D19 ^ D10 D18 +error(0.0005319396409102149182) D7 D19 ^ D18 +error(0.00412896826533945896) D7 ^ D0 L0 +error(0.001000499871616930938) D7 ^ D8 ^ D0 L0 +error(0.001430052590068066039) D7 ^ D8 ^ D5 L0 +error(0.01069341384254630933) D7 ^ D9 L0 +error(0.004281356988861994943) D9 D17 ^ D7 +error(0.03023700059253283876) D8 +error(0.01964826013456289974) D8 D11 +error(0.02083740118406023772) D8 D11 ^ D10 +error(0.01754222313276320583) D8 D16 +error(0.003925335771774137936) D8 D16 ^ D18 +error(0.00829638757819277893) D8 D19 +error(0.006189697411378116548) D8 D19 ^ D10 +error(0.008227765587022699278) D8 D19 ^ D18 +error(0.001565359356948206127) D8 D19 ^ D18 ^ D10 +error(0.0003183608070758283228) D8 ^ D0 L0 +error(0.002021891892728380422) D8 ^ D2 +error(0.0004199589072463618647) D8 ^ D5 L0 +error(0.0007782664187819530229) D8 ^ D10 +error(0.01579499598154602072) D9 D10 +error(0.02020230805971124852) D9 D10 ^ D7 +error(7.317949761103465162e-05) D9 D10 ^ D8 +error(0.0002729143618811002503) D9 D10 ^ D11 +error(0.0215519806561217768) D9 D17 +error(0.01157668632655704626) D9 L0 +error(0.03421753899134518523) D10 +error(0.004283187852576511058) D10 D17 +error(0.003386911228148268768) D10 D17 ^ D7 +error(0.000374805418012281121) D10 D17 ^ D19 +error(0.000378901796486506696) D10 D17 ^ D19 ^ D7 +error(0.02129317632278137154) D10 D18 +error(0.001098988525176137782) D10 D18 ^ D7 +error(0.003795925922665927942) D10 D18 ^ D19 +error(0.01551218175841799496) D10 ^ D11 +error(0.00105555876697080984) D10 ^ D19 +error(0.005384160809988575158) D11 D19 ^ D10 +error(0.03182570249740373364) D11 +error(0.02457097167531402046) D11 D19 +error(0.005245339025758253074) D12 +error(0.01351831881670467229) D12 D15 +error(0.01232203752053264746) D12 D15 ^ D13 L0 +error(0.02137993200743813771) D12 D20 +error(0.004131755026116961001) D12 D20 ^ D21 L0 +error(0.002903203036019879387) D12 D23 +error(0.003328581296933910347) D12 D23 ^ D13 L0 +error(0.002153497648560191106) D12 D23 ^ D21 L0 +error(0.00132794561778247131) D12 D23 ^ D21 L0 ^ D13 L0 +error(0.002297625395399578718) D12 D24 +error(0.001564841148743489939) D12 D24 ^ D13 D21 +error(0.0003724936510519168045) D12 D24 ^ D13 L0 +error(0.0003891805678224126625) D12 D24 ^ D21 L0 +error(0.005021350549187082041) D12 ^ D13 L0 +error(0.002754177369565753448) D12 ^ D21 L0 +error(0.003687446986055130382) D13 D21 ^ D12 +error(0.008302277937618965375) D13 D14 +error(0.0004930814379600387092) D13 D14 ^ D12 +error(0.0002344286990215338929) D13 D14 ^ D15 D16 +error(0.0002827200622917192853) D13 D14 ^ D15 D24 +error(0.01071681271374672756) D13 D14 ^ D16 +error(0.002689376411773483633) D13 D14 ^ D16 D24 +error(0.001802538463770141227) D13 D14 ^ D24 +error(4.045483039878490701e-05) D13 D14 ^ D24 ^ D12 +error(0.01568589133027759736) D13 D18 +error(0.01169068635140842367) D13 D18 ^ D15 D16 +error(0.03140897183913322899) D13 D21 +error(0.002019920062412751318) D13 D21 ^ D23 D24 +error(0.001834189692617856256) D13 D21 ^ D24 +error(0.003283249611206463282) D13 D25 +error(0.002217039097925698875) D13 D25 ^ D15 D23 +error(0.0004311616500379738615) D13 D25 ^ D15 D24 +error(0.0003601196358267589183) D13 D25 ^ D23 D24 +error(0.005495111026433003795) D13 D26 +error(0.001924571388590668678) D13 D26 ^ D15 D16 +error(0.001919238098036685951) D13 D26 ^ D15 D23 +error(0.001542925559449527615) D13 D26 ^ D15 D24 +error(0.0004065625308521262694) D13 D26 ^ D16 D24 +error(0.001517534904390731645) D13 D26 ^ D23 D24 +error(0.01000000000000000021) D13 L0 +error(0.000630023031437223005) D13 L0 ^ D23 +error(0.003559447081430625569) D15 D23 ^ D13 L0 +error(0.009592028122265101528) D14 +error(0.002359226002129251928) D14 D21 +error(0.0004700885901282171966) D14 D21 ^ D12 +error(0.002842631538867582044) D14 D21 ^ D24 +error(0.03323098142033485691) D14 D22 +error(0.003694859541453752051) D14 D22 ^ D24 +error(0.001887308115760311577) D14 D26 +error(7.667254054394448501e-05) D14 D26 ^ D15 D16 +error(0.0001684128039816316761) D14 D26 ^ D15 D24 +error(0.00155935512012112215) D14 D26 ^ D16 D24 +error(0.01465668303041333873) D14 ^ D16 +error(0.002208325456735622545) D14 ^ D24 ^ D16 +error(0.01000000000000000021) D15 +error(0.01641885170447205181) D15 D16 +error(6.757040603604669575e-05) D15 D16 ^ D5 L0 +error(0.000691539702847943495) D15 D16 ^ D17 D18 +error(0.001965417218638295088) D15 D16 ^ D18 +error(0.002025462288331955976) D15 D16 ^ D18 D26 +error(0.002676727229798968322) D15 D16 ^ D26 +error(0.04979648365038458202) D15 D23 +error(0.004075575823084270563) D15 D23 ^ D25 D26 +error(0.003228899945508421909) D15 D24 +error(0.0006267629478556474868) D15 D24 ^ D25 D26 +error(0.001819731574192852766) D15 D27 +error(0.001044374947872651286) D15 D27 ^ D18 +error(0.001721977742605806461) D15 D27 ^ D18 D26 +error(0.0005319396409102149182) D15 D27 ^ D26 +error(0.01221051608950192956) D15 ^ D17 L0 +error(0.004281356988861994943) D17 D25 ^ D15 +error(0.01352570247240133215) D16 +error(0.01916140106904455978) D16 D19 +error(0.02134285127067836463) D16 D19 ^ D18 +error(0.01754222313276320583) D16 D24 +error(0.003925335771774137936) D16 D24 ^ D26 +error(0.00829638757819277893) D16 D27 +error(0.006189697411378116548) D16 D27 ^ D18 +error(0.008227765587022699278) D16 D27 ^ D26 +error(0.001565359356948206127) D16 D27 ^ D26 ^ D18 +error(0.0139259571500968439) D17 D18 +error(0.003653395121599596097) D17 D18 ^ D7 +error(0.01746546765882601299) D17 D18 ^ D15 +error(0.0006115023900453514733) D17 D18 ^ D19 +error(0.0002228130597355455398) D17 D18 ^ D19 ^ D7 +error(0.0215519806561217768) D17 D25 +error(0.00578341455456686613) D17 L0 +error(0.000407844684521510418) D17 L0 ^ D5 L0 ^ D7 +error(0.0003059078627119102755) D17 L0 ^ D5 L0 ^ D15 +error(0.000912866688785244902) D17 L0 ^ D15 ^ D7 +error(0.01809852353947335665) D18 +error(0.004283187852576511058) D18 D25 +error(0.003386911228148268768) D18 D25 ^ D15 +error(0.000374805418012281121) D18 D25 ^ D27 +error(0.000378901796486506696) D18 D25 ^ D27 ^ D15 +error(0.02129317632278137154) D18 D26 +error(0.001098988525176137782) D18 D26 ^ D15 +error(0.003795925922665927942) D18 D26 ^ D27 +error(0.000339845682907893615) D18 ^ D6 ^ D8 +error(0.0001011712955095126772) D18 ^ D6 ^ D16 +error(0.0004136195716464172124) D18 ^ D8 +error(0.009786019691043161897) D18 ^ D19 +error(0.00105555876697080984) D18 ^ D27 +error(0.005384160809988575158) D19 D27 ^ D18 +error(0.005000000000000000104) D19 +error(0.02457097167531402046) D19 D27 +error(0.005245339025758253074) D20 +error(0.01351831881670467229) D20 D23 +error(0.01232203752053264746) D20 D23 ^ D21 L0 +error(0.02137993200743813771) D20 D28 +error(0.004131755026116961001) D20 D28 ^ D29 L0 +error(0.002903203036019879387) D20 D31 +error(0.003328581296933910347) D20 D31 ^ D21 L0 +error(0.002153497648560191106) D20 D31 ^ D29 L0 +error(0.00132794561778247131) D20 D31 ^ D29 L0 ^ D21 L0 +error(0.002297625395399578718) D20 D32 +error(0.001564841148743489939) D20 D32 ^ D21 D29 +error(0.0003724936510519168045) D20 D32 ^ D21 L0 +error(0.0003891805678224126625) D20 D32 ^ D29 L0 +error(0.005021350549187082041) D20 ^ D21 L0 +error(0.002754177369565753448) D20 ^ D29 L0 +error(0.003687446986055130382) D21 D29 ^ D20 +error(0.008302277937618965375) D21 D22 +error(0.0004930814379600387092) D21 D22 ^ D20 +error(0.0002344286990215338929) D21 D22 ^ D23 D24 +error(0.0002827200622917192853) D21 D22 ^ D23 D32 +error(0.01071681271374672756) D21 D22 ^ D24 +error(0.002689376411773483633) D21 D22 ^ D24 D32 +error(0.001802538463770141227) D21 D22 ^ D32 +error(4.045483039878490701e-05) D21 D22 ^ D32 ^ D20 +error(0.01568589133027759736) D21 D26 +error(0.01169068635140842367) D21 D26 ^ D23 D24 +error(0.03140897183913322899) D21 D29 +error(0.002019920062412751318) D21 D29 ^ D31 D32 +error(0.001834189692617856256) D21 D29 ^ D32 +error(0.003283249611206463282) D21 D33 +error(0.002217039097925698875) D21 D33 ^ D23 D31 +error(0.0004311616500379738615) D21 D33 ^ D23 D32 +error(0.0003601196358267589183) D21 D33 ^ D31 D32 +error(0.005495111026433003795) D21 D34 +error(0.001924571388590668678) D21 D34 ^ D23 D24 +error(0.001919238098036685951) D21 D34 ^ D23 D31 +error(0.001542925559449527615) D21 D34 ^ D23 D32 +error(0.0004065625308521262694) D21 D34 ^ D24 D32 +error(0.001517534904390731645) D21 D34 ^ D31 D32 +error(0.01000000000000000021) D21 L0 +error(0.000630023031437223005) D21 L0 ^ D31 +error(0.003559447081430625569) D23 D31 ^ D21 L0 +error(0.009592028122265101528) D22 +error(0.002359226002129251928) D22 D29 +error(0.0004700885901282171966) D22 D29 ^ D20 +error(0.002842631538867582044) D22 D29 ^ D32 +error(0.03323098142033485691) D22 D30 +error(0.003694859541453752051) D22 D30 ^ D32 +error(0.001887308115760311577) D22 D34 +error(7.667254054394448501e-05) D22 D34 ^ D23 D24 +error(0.0001684128039816316761) D22 D34 ^ D23 D32 +error(0.00155935512012112215) D22 D34 ^ D24 D32 +error(0.01465668303041333873) D22 ^ D24 +error(0.002208325456735622545) D22 ^ D32 ^ D24 +error(0.01000000000000000021) D23 +error(0.01641885170447205181) D23 D24 +error(6.757040603604669575e-05) D23 D24 ^ D13 L0 +error(0.000691539702847943495) D23 D24 ^ D25 D26 +error(0.001965417218638295088) D23 D24 ^ D26 +error(0.002025462288331955976) D23 D24 ^ D26 D34 +error(0.002676727229798968322) D23 D24 ^ D34 +error(0.04979648365038458202) D23 D31 +error(0.004075575823084270563) D23 D31 ^ D33 D34 +error(0.003228899945508421909) D23 D32 +error(0.0006267629478556474868) D23 D32 ^ D33 D34 +error(0.001819731574192852766) D23 D35 +error(0.001044374947872651286) D23 D35 ^ D26 +error(0.001721977742605806461) D23 D35 ^ D26 D34 +error(0.0005319396409102149182) D23 D35 ^ D34 +error(0.01221051608950192956) D23 ^ D25 L0 +error(0.004281356988861994943) D25 D33 ^ D23 +error(0.01352570247240133215) D24 +error(0.01916140106904455978) D24 D27 +error(0.02134285127067836463) D24 D27 ^ D26 +error(0.01754222313276320583) D24 D32 +error(0.003925335771774137936) D24 D32 ^ D34 +error(0.00829638757819277893) D24 D35 +error(0.006189697411378116548) D24 D35 ^ D26 +error(0.008227765587022699278) D24 D35 ^ D34 +error(0.001565359356948206127) D24 D35 ^ D34 ^ D26 +error(0.0139259571500968439) D25 D26 +error(0.003653395121599596097) D25 D26 ^ D15 +error(0.01746546765882601299) D25 D26 ^ D23 +error(0.0006115023900453514733) D25 D26 ^ D27 +error(0.0002228130597355455398) D25 D26 ^ D27 ^ D15 +error(0.0215519806561217768) D25 D33 +error(0.00578341455456686613) D25 L0 +error(0.000407844684521510418) D25 L0 ^ D13 L0 ^ D15 +error(0.0003059078627119102755) D25 L0 ^ D13 L0 ^ D23 +error(0.000912866688785244902) D25 L0 ^ D23 ^ D15 +error(0.01809852353947335665) D26 +error(0.004283187852576511058) D26 D33 +error(0.003386911228148268768) D26 D33 ^ D23 +error(0.000374805418012281121) D26 D33 ^ D35 +error(0.000378901796486506696) D26 D33 ^ D35 ^ D23 +error(0.02129317632278137154) D26 D34 +error(0.001098988525176137782) D26 D34 ^ D23 +error(0.003795925922665927942) D26 D34 ^ D35 +error(0.000339845682907893615) D26 ^ D14 ^ D16 +error(0.0001011712955095126772) D26 ^ D14 ^ D24 +error(0.0004136195716464172124) D26 ^ D16 +error(0.009786019691043161897) D26 ^ D27 +error(0.00105555876697080984) D26 ^ D35 +error(0.005384160809988575158) D27 D35 ^ D26 +error(0.005000000000000000104) D27 +error(0.02457097167531402046) D27 D35 +error(0.005245339025758253074) D28 +error(0.01351831881670467229) D28 D31 +error(0.01232203752053264746) D28 D31 ^ D29 L0 +error(0.02137993200743813771) D28 D36 +error(0.004131755026116961001) D28 D36 ^ D37 L0 +error(0.002903203036019879387) D28 D39 +error(0.003328581296933910347) D28 D39 ^ D29 L0 +error(0.002153497648560191106) D28 D39 ^ D37 L0 +error(0.00132794561778247131) D28 D39 ^ D37 L0 ^ D29 L0 +error(0.002297625395399578718) D28 D40 +error(0.001564841148743489939) D28 D40 ^ D29 D37 +error(0.0003724936510519168045) D28 D40 ^ D29 L0 +error(0.0003891805678224126625) D28 D40 ^ D37 L0 +error(0.005021350549187082041) D28 ^ D29 L0 +error(0.002754177369565753448) D28 ^ D37 L0 +error(0.003687446986055130382) D29 D37 ^ D28 +error(0.008302277937618965375) D29 D30 +error(0.0004930814379600387092) D29 D30 ^ D28 +error(0.0002344286990215338929) D29 D30 ^ D31 D32 +error(0.0002827200622917192853) D29 D30 ^ D31 D40 +error(0.01071681271374672756) D29 D30 ^ D32 +error(0.002689376411773483633) D29 D30 ^ D32 D40 +error(0.001802538463770141227) D29 D30 ^ D40 +error(4.045483039878490701e-05) D29 D30 ^ D40 ^ D28 +error(0.01568589133027759736) D29 D34 +error(0.01169068635140842367) D29 D34 ^ D31 D32 +error(0.03140897183913322899) D29 D37 +error(0.002019920062412751318) D29 D37 ^ D39 D40 +error(0.001834189692617856256) D29 D37 ^ D40 +error(0.003283249611206463282) D29 D41 +error(0.002217039097925698875) D29 D41 ^ D31 D39 +error(0.0004311616500379738615) D29 D41 ^ D31 D40 +error(0.0003601196358267589183) D29 D41 ^ D39 D40 +error(0.005495111026433003795) D29 D42 +error(0.001924571388590668678) D29 D42 ^ D31 D32 +error(0.001919238098036685951) D29 D42 ^ D31 D39 +error(0.001542925559449527615) D29 D42 ^ D31 D40 +error(0.0004065625308521262694) D29 D42 ^ D32 D40 +error(0.001517534904390731645) D29 D42 ^ D39 D40 +error(0.01000000000000000021) D29 L0 +error(0.000630023031437223005) D29 L0 ^ D39 +error(0.003559447081430625569) D31 D39 ^ D29 L0 +error(0.009592028122265101528) D30 +error(0.002359226002129251928) D30 D37 +error(0.0004700885901282171966) D30 D37 ^ D28 +error(0.002842631538867582044) D30 D37 ^ D40 +error(0.03323098142033485691) D30 D38 +error(0.003694859541453752051) D30 D38 ^ D40 +error(0.001887308115760311577) D30 D42 +error(7.667254054394448501e-05) D30 D42 ^ D31 D32 +error(0.0001684128039816316761) D30 D42 ^ D31 D40 +error(0.00155935512012112215) D30 D42 ^ D32 D40 +error(0.01465668303041333873) D30 ^ D32 +error(0.002208325456735622545) D30 ^ D40 ^ D32 +error(0.01000000000000000021) D31 +error(0.01641885170447205181) D31 D32 +error(6.757040603604669575e-05) D31 D32 ^ D21 L0 +error(0.000691539702847943495) D31 D32 ^ D33 D34 +error(0.001965417218638295088) D31 D32 ^ D34 +error(0.002025462288331955976) D31 D32 ^ D34 D42 +error(0.002676727229798968322) D31 D32 ^ D42 +error(0.04979648365038458202) D31 D39 +error(0.004075575823084270563) D31 D39 ^ D41 D42 +error(0.003228899945508421909) D31 D40 +error(0.0006267629478556474868) D31 D40 ^ D41 D42 +error(0.001819731574192852766) D31 D43 +error(0.001044374947872651286) D31 D43 ^ D34 +error(0.001721977742605806461) D31 D43 ^ D34 D42 +error(0.0005319396409102149182) D31 D43 ^ D42 +error(0.01221051608950192956) D31 ^ D33 L0 +error(0.004281356988861994943) D33 D41 ^ D31 +error(0.01352570247240133215) D32 +error(0.01916140106904455978) D32 D35 +error(0.02134285127067836463) D32 D35 ^ D34 +error(0.01754222313276320583) D32 D40 +error(0.003925335771774137936) D32 D40 ^ D42 +error(0.00829638757819277893) D32 D43 +error(0.006189697411378116548) D32 D43 ^ D34 +error(0.008227765587022699278) D32 D43 ^ D42 +error(0.001565359356948206127) D32 D43 ^ D42 ^ D34 +error(0.0139259571500968439) D33 D34 +error(0.003653395121599596097) D33 D34 ^ D23 +error(0.01746546765882601299) D33 D34 ^ D31 +error(0.0006115023900453514733) D33 D34 ^ D35 +error(0.0002228130597355455398) D33 D34 ^ D35 ^ D23 +error(0.0215519806561217768) D33 D41 +error(0.00578341455456686613) D33 L0 +error(0.000407844684521510418) D33 L0 ^ D21 L0 ^ D23 +error(0.0003059078627119102755) D33 L0 ^ D21 L0 ^ D31 +error(0.000912866688785244902) D33 L0 ^ D31 ^ D23 +error(0.01809852353947335665) D34 +error(0.004283187852576511058) D34 D41 +error(0.003386911228148268768) D34 D41 ^ D31 +error(0.000374805418012281121) D34 D41 ^ D43 +error(0.000378901796486506696) D34 D41 ^ D43 ^ D31 +error(0.02129317632278137154) D34 D42 +error(0.001098988525176137782) D34 D42 ^ D31 +error(0.003795925922665927942) D34 D42 ^ D43 +error(0.000339845682907893615) D34 ^ D22 ^ D24 +error(0.0001011712955095126772) D34 ^ D22 ^ D32 +error(0.0004136195716464172124) D34 ^ D24 +error(0.009786019691043161897) D34 ^ D35 +error(0.00105555876697080984) D34 ^ D43 +error(0.005384160809988575158) D35 D43 ^ D34 +error(0.005000000000000000104) D35 +error(0.02457097167531402046) D35 D43 +error(0.005245339025758253074) D36 +error(0.01351831881670467229) D36 D39 +error(0.01232203752053264746) D36 D39 ^ D37 L0 +error(0.02137993200743813771) D36 D44 +error(0.004131755026116961001) D36 D44 ^ D45 L0 +error(0.002903203036019879387) D36 D47 +error(0.003328581296933910347) D36 D47 ^ D37 L0 +error(0.002153497648560191106) D36 D47 ^ D45 L0 +error(0.00132794561778247131) D36 D47 ^ D45 L0 ^ D37 L0 +error(0.002297625395399578718) D36 D48 +error(0.001564841148743489939) D36 D48 ^ D37 D45 +error(0.0003724936510519168045) D36 D48 ^ D37 L0 +error(0.0003891805678224126625) D36 D48 ^ D45 L0 +error(0.005021350549187082041) D36 ^ D37 L0 +error(0.002754177369565753448) D36 ^ D45 L0 +error(0.003687446986055130382) D37 D45 ^ D36 +error(0.008302277937618965375) D37 D38 +error(0.0004930814379600387092) D37 D38 ^ D36 +error(0.0002344286990215338929) D37 D38 ^ D39 D40 +error(0.0002827200622917192853) D37 D38 ^ D39 D48 +error(0.01071681271374672756) D37 D38 ^ D40 +error(0.002689376411773483633) D37 D38 ^ D40 D48 +error(0.001802538463770141227) D37 D38 ^ D48 +error(4.045483039878490701e-05) D37 D38 ^ D48 ^ D36 +error(0.01568589133027759736) D37 D42 +error(0.01169068635140842367) D37 D42 ^ D39 D40 +error(0.03140897183913322899) D37 D45 +error(0.002019920062412751318) D37 D45 ^ D47 D48 +error(0.001834189692617856256) D37 D45 ^ D48 +error(0.003283249611206463282) D37 D49 +error(0.002217039097925698875) D37 D49 ^ D39 D47 +error(0.0004311616500379738615) D37 D49 ^ D39 D48 +error(0.0003601196358267589183) D37 D49 ^ D47 D48 +error(0.005495111026433003795) D37 D50 +error(0.001924571388590668678) D37 D50 ^ D39 D40 +error(0.001919238098036685951) D37 D50 ^ D39 D47 +error(0.001542925559449527615) D37 D50 ^ D39 D48 +error(0.0004065625308521262694) D37 D50 ^ D40 D48 +error(0.001517534904390731645) D37 D50 ^ D47 D48 +error(0.01000000000000000021) D37 L0 +error(0.000630023031437223005) D37 L0 ^ D47 +error(0.003559447081430625569) D39 D47 ^ D37 L0 +error(0.009592028122265101528) D38 +error(0.002359226002129251928) D38 D45 +error(0.0004700885901282171966) D38 D45 ^ D36 +error(0.002842631538867582044) D38 D45 ^ D48 +error(0.03323098142033485691) D38 D46 +error(0.003694859541453752051) D38 D46 ^ D48 +error(0.001887308115760311577) D38 D50 +error(7.667254054394448501e-05) D38 D50 ^ D39 D40 +error(0.0001684128039816316761) D38 D50 ^ D39 D48 +error(0.00155935512012112215) D38 D50 ^ D40 D48 +error(0.01465668303041333873) D38 ^ D40 +error(0.002208325456735622545) D38 ^ D48 ^ D40 +error(0.01000000000000000021) D39 +error(0.01641885170447205181) D39 D40 +error(6.757040603604669575e-05) D39 D40 ^ D29 L0 +error(0.000691539702847943495) D39 D40 ^ D41 D42 +error(0.001965417218638295088) D39 D40 ^ D42 +error(0.002025462288331955976) D39 D40 ^ D42 D50 +error(0.002676727229798968322) D39 D40 ^ D50 +error(0.04979648365038458202) D39 D47 +error(0.004075575823084270563) D39 D47 ^ D49 D50 +error(0.003228899945508421909) D39 D48 +error(0.0006267629478556474868) D39 D48 ^ D49 D50 +error(0.001819731574192852766) D39 D51 +error(0.001044374947872651286) D39 D51 ^ D42 +error(0.001721977742605806461) D39 D51 ^ D42 D50 +error(0.0005319396409102149182) D39 D51 ^ D50 +error(0.01221051608950192956) D39 ^ D41 L0 +error(0.004281356988861994943) D41 D49 ^ D39 +error(0.01352570247240133215) D40 +error(0.01916140106904455978) D40 D43 +error(0.02134285127067836463) D40 D43 ^ D42 +error(0.01754222313276320583) D40 D48 +error(0.003925335771774137936) D40 D48 ^ D50 +error(0.00829638757819277893) D40 D51 +error(0.006189697411378116548) D40 D51 ^ D42 +error(0.008227765587022699278) D40 D51 ^ D50 +error(0.001565359356948206127) D40 D51 ^ D50 ^ D42 +error(0.0139259571500968439) D41 D42 +error(0.003653395121599596097) D41 D42 ^ D31 +error(0.01746546765882601299) D41 D42 ^ D39 +error(0.0006115023900453514733) D41 D42 ^ D43 +error(0.0002228130597355455398) D41 D42 ^ D43 ^ D31 +error(0.0215519806561217768) D41 D49 +error(0.00578341455456686613) D41 L0 +error(0.000407844684521510418) D41 L0 ^ D29 L0 ^ D31 +error(0.0003059078627119102755) D41 L0 ^ D29 L0 ^ D39 +error(0.000912866688785244902) D41 L0 ^ D39 ^ D31 +error(0.01809852353947335665) D42 +error(0.004283187852576511058) D42 D49 +error(0.003386911228148268768) D42 D49 ^ D39 +error(0.000374805418012281121) D42 D49 ^ D51 +error(0.000378901796486506696) D42 D49 ^ D51 ^ D39 +error(0.02129317632278137154) D42 D50 +error(0.001098988525176137782) D42 D50 ^ D39 +error(0.003795925922665927942) D42 D50 ^ D51 +error(0.000339845682907893615) D42 ^ D30 ^ D32 +error(0.0001011712955095126772) D42 ^ D30 ^ D40 +error(0.0004136195716464172124) D42 ^ D32 +error(0.009786019691043161897) D42 ^ D43 +error(0.00105555876697080984) D42 ^ D51 +error(0.005384160809988575158) D43 D51 ^ D42 +error(0.005000000000000000104) D43 +error(0.02457097167531402046) D43 D51 +error(0.005245339025758253074) D44 +error(0.01351831881670467229) D44 D47 +error(0.01232203752053264746) D44 D47 ^ D45 L0 +error(0.02137993200743813771) D44 D52 +error(0.004131755026116961001) D44 D52 ^ D53 L0 +error(0.002903203036019879387) D44 D55 +error(0.003328581296933910347) D44 D55 ^ D45 L0 +error(0.002153497648560191106) D44 D55 ^ D53 L0 +error(0.00132794561778247131) D44 D55 ^ D53 L0 ^ D45 L0 +error(0.002297625395399578718) D44 D56 +error(0.001564841148743489939) D44 D56 ^ D45 D53 +error(0.0003724936510519168045) D44 D56 ^ D45 L0 +error(0.0003891805678224126625) D44 D56 ^ D53 L0 +error(0.005021350549187082041) D44 ^ D45 L0 +error(0.002754177369565753448) D44 ^ D53 L0 +error(0.003687446986055130382) D45 D53 ^ D44 +error(0.008302277937618965375) D45 D46 +error(0.0004930814379600387092) D45 D46 ^ D44 +error(0.0002344286990215338929) D45 D46 ^ D47 D48 +error(0.0002827200622917192853) D45 D46 ^ D47 D56 +error(0.01071681271374672756) D45 D46 ^ D48 +error(0.002689376411773483633) D45 D46 ^ D48 D56 +error(0.001802538463770141227) D45 D46 ^ D56 +error(4.045483039878490701e-05) D45 D46 ^ D56 ^ D44 +error(0.01568589133027759736) D45 D50 +error(0.01169068635140842367) D45 D50 ^ D47 D48 +error(0.03140897183913322899) D45 D53 +error(0.002019920062412751318) D45 D53 ^ D55 D56 +error(0.001834189692617856256) D45 D53 ^ D56 +error(0.003283249611206463282) D45 D57 +error(0.002217039097925698875) D45 D57 ^ D47 D55 +error(0.0004311616500379738615) D45 D57 ^ D47 D56 +error(0.0003601196358267589183) D45 D57 ^ D55 D56 +error(0.005495111026433003795) D45 D58 +error(0.001924571388590668678) D45 D58 ^ D47 D48 +error(0.001919238098036685951) D45 D58 ^ D47 D55 +error(0.001542925559449527615) D45 D58 ^ D47 D56 +error(0.0004065625308521262694) D45 D58 ^ D48 D56 +error(0.001517534904390731645) D45 D58 ^ D55 D56 +error(0.01000000000000000021) D45 L0 +error(0.000630023031437223005) D45 L0 ^ D55 +error(0.003559447081430625569) D47 D55 ^ D45 L0 +error(0.009592028122265101528) D46 +error(0.002359226002129251928) D46 D53 +error(0.0004700885901282171966) D46 D53 ^ D44 +error(0.002842631538867582044) D46 D53 ^ D56 +error(0.03323098142033485691) D46 D54 +error(0.003694859541453752051) D46 D54 ^ D56 +error(0.001887308115760311577) D46 D58 +error(7.667254054394448501e-05) D46 D58 ^ D47 D48 +error(0.0001684128039816316761) D46 D58 ^ D47 D56 +error(0.00155935512012112215) D46 D58 ^ D48 D56 +error(0.01465668303041333873) D46 ^ D48 +error(0.002208325456735622545) D46 ^ D56 ^ D48 +error(0.01000000000000000021) D47 +error(0.01641885170447205181) D47 D48 +error(6.757040603604669575e-05) D47 D48 ^ D37 L0 +error(0.000691539702847943495) D47 D48 ^ D49 D50 +error(0.001965417218638295088) D47 D48 ^ D50 +error(0.002025462288331955976) D47 D48 ^ D50 D58 +error(0.002676727229798968322) D47 D48 ^ D58 +error(0.04979648365038458202) D47 D55 +error(0.004075575823084270563) D47 D55 ^ D57 D58 +error(0.003228899945508421909) D47 D56 +error(0.0006267629478556474868) D47 D56 ^ D57 D58 +error(0.001819731574192852766) D47 D59 +error(0.001044374947872651286) D47 D59 ^ D50 +error(0.001721977742605806461) D47 D59 ^ D50 D58 +error(0.0005319396409102149182) D47 D59 ^ D58 +error(0.01221051608950192956) D47 ^ D49 L0 +error(0.004281356988861994943) D49 D57 ^ D47 +error(0.01352570247240133215) D48 +error(0.01916140106904455978) D48 D51 +error(0.02134285127067836463) D48 D51 ^ D50 +error(0.01754222313276320583) D48 D56 +error(0.003925335771774137936) D48 D56 ^ D58 +error(0.00829638757819277893) D48 D59 +error(0.006189697411378116548) D48 D59 ^ D50 +error(0.008227765587022699278) D48 D59 ^ D58 +error(0.001565359356948206127) D48 D59 ^ D58 ^ D50 +error(0.0139259571500968439) D49 D50 +error(0.003653395121599596097) D49 D50 ^ D39 +error(0.01746546765882601299) D49 D50 ^ D47 +error(0.0006115023900453514733) D49 D50 ^ D51 +error(0.0002228130597355455398) D49 D50 ^ D51 ^ D39 +error(0.0215519806561217768) D49 D57 +error(0.00578341455456686613) D49 L0 +error(0.000407844684521510418) D49 L0 ^ D37 L0 ^ D39 +error(0.0003059078627119102755) D49 L0 ^ D37 L0 ^ D47 +error(0.000912866688785244902) D49 L0 ^ D47 ^ D39 +error(0.01809852353947335665) D50 +error(0.004283187852576511058) D50 D57 +error(0.003386911228148268768) D50 D57 ^ D47 +error(0.000374805418012281121) D50 D57 ^ D59 +error(0.000378901796486506696) D50 D57 ^ D59 ^ D47 +error(0.02129317632278137154) D50 D58 +error(0.001098988525176137782) D50 D58 ^ D47 +error(0.003795925922665927942) D50 D58 ^ D59 +error(0.000339845682907893615) D50 ^ D38 ^ D40 +error(0.0001011712955095126772) D50 ^ D38 ^ D48 +error(0.0004136195716464172124) D50 ^ D40 +error(0.009786019691043161897) D50 ^ D51 +error(0.00105555876697080984) D50 ^ D59 +error(0.005384160809988575158) D51 D59 ^ D50 +error(0.005000000000000000104) D51 +error(0.02457097167531402046) D51 D59 +error(0.005245339025758253074) D52 +error(0.01351831881670467229) D52 D55 +error(0.01232203752053264746) D52 D55 ^ D53 L0 +error(0.02137993200743813771) D52 D60 +error(0.004131755026116961001) D52 D60 ^ D61 L0 +error(0.002903203036019879387) D52 D63 +error(0.003328581296933910347) D52 D63 ^ D53 L0 +error(0.002153497648560191106) D52 D63 ^ D61 L0 +error(0.00132794561778247131) D52 D63 ^ D61 L0 ^ D53 L0 +error(0.002297625395399578718) D52 D64 +error(0.001564841148743489939) D52 D64 ^ D53 D61 +error(0.0003724936510519168045) D52 D64 ^ D53 L0 +error(0.0003891805678224126625) D52 D64 ^ D61 L0 +error(0.005021350549187082041) D52 ^ D53 L0 +error(0.002754177369565753448) D52 ^ D61 L0 +error(0.003687446986055130382) D53 D61 ^ D52 +error(0.008302277937618965375) D53 D54 +error(0.0004930814379600387092) D53 D54 ^ D52 +error(0.0002344286990215338929) D53 D54 ^ D55 D56 +error(0.0002827200622917192853) D53 D54 ^ D55 D64 +error(0.01071681271374672756) D53 D54 ^ D56 +error(0.002689376411773483633) D53 D54 ^ D56 D64 +error(0.001802538463770141227) D53 D54 ^ D64 +error(4.045483039878490701e-05) D53 D54 ^ D64 ^ D52 +error(0.01568589133027759736) D53 D58 +error(0.01169068635140842367) D53 D58 ^ D55 D56 +error(0.03140897183913322899) D53 D61 +error(0.002019920062412751318) D53 D61 ^ D63 D64 +error(0.001834189692617856256) D53 D61 ^ D64 +error(0.003283249611206463282) D53 D65 +error(0.002217039097925698875) D53 D65 ^ D55 D63 +error(0.0004311616500379738615) D53 D65 ^ D55 D64 +error(0.0003601196358267589183) D53 D65 ^ D63 D64 +error(0.005495111026433003795) D53 D66 +error(0.001924571388590668678) D53 D66 ^ D55 D56 +error(0.001919238098036685951) D53 D66 ^ D55 D63 +error(0.001542925559449527615) D53 D66 ^ D55 D64 +error(0.0004065625308521262694) D53 D66 ^ D56 D64 +error(0.001517534904390731645) D53 D66 ^ D63 D64 +error(0.01000000000000000021) D53 L0 +error(0.000630023031437223005) D53 L0 ^ D63 +error(0.003559447081430625569) D55 D63 ^ D53 L0 +error(0.009592028122265101528) D54 +error(0.002359226002129251928) D54 D61 +error(0.0004700885901282171966) D54 D61 ^ D52 +error(0.002842631538867582044) D54 D61 ^ D64 +error(0.03323098142033485691) D54 D62 +error(0.003694859541453752051) D54 D62 ^ D64 +error(0.001887308115760311577) D54 D66 +error(7.667254054394448501e-05) D54 D66 ^ D55 D56 +error(0.0001684128039816316761) D54 D66 ^ D55 D64 +error(0.00155935512012112215) D54 D66 ^ D56 D64 +error(0.01465668303041333873) D54 ^ D56 +error(0.002208325456735622545) D54 ^ D64 ^ D56 +error(0.01000000000000000021) D55 +error(0.01641885170447205181) D55 D56 +error(6.757040603604669575e-05) D55 D56 ^ D45 L0 +error(0.000691539702847943495) D55 D56 ^ D57 D58 +error(0.001965417218638295088) D55 D56 ^ D58 +error(0.002025462288331955976) D55 D56 ^ D58 D66 +error(0.002676727229798968322) D55 D56 ^ D66 +error(0.04979648365038458202) D55 D63 +error(0.004075575823084270563) D55 D63 ^ D65 D66 +error(0.003228899945508421909) D55 D64 +error(0.0006267629478556474868) D55 D64 ^ D65 D66 +error(0.001819731574192852766) D55 D67 +error(0.001044374947872651286) D55 D67 ^ D58 +error(0.001721977742605806461) D55 D67 ^ D58 D66 +error(0.0005319396409102149182) D55 D67 ^ D66 +error(0.01221051608950192956) D55 ^ D57 L0 +error(0.004281356988861994943) D57 D65 ^ D55 +error(0.01352570247240133215) D56 +error(0.01916140106904455978) D56 D59 +error(0.02134285127067836463) D56 D59 ^ D58 +error(0.01754222313276320583) D56 D64 +error(0.003925335771774137936) D56 D64 ^ D66 +error(0.00829638757819277893) D56 D67 +error(0.006189697411378116548) D56 D67 ^ D58 +error(0.008227765587022699278) D56 D67 ^ D66 +error(0.001565359356948206127) D56 D67 ^ D66 ^ D58 +error(0.0139259571500968439) D57 D58 +error(0.003653395121599596097) D57 D58 ^ D47 +error(0.01746546765882601299) D57 D58 ^ D55 +error(0.0006115023900453514733) D57 D58 ^ D59 +error(0.0002228130597355455398) D57 D58 ^ D59 ^ D47 +error(0.0215519806561217768) D57 D65 +error(0.00578341455456686613) D57 L0 +error(0.000407844684521510418) D57 L0 ^ D45 L0 ^ D47 +error(0.0003059078627119102755) D57 L0 ^ D45 L0 ^ D55 +error(0.000912866688785244902) D57 L0 ^ D55 ^ D47 +error(0.01809852353947335665) D58 +error(0.004283187852576511058) D58 D65 +error(0.003386911228148268768) D58 D65 ^ D55 +error(0.000374805418012281121) D58 D65 ^ D67 +error(0.000378901796486506696) D58 D65 ^ D67 ^ D55 +error(0.02129317632278137154) D58 D66 +error(0.001098988525176137782) D58 D66 ^ D55 +error(0.003795925922665927942) D58 D66 ^ D67 +error(0.000339845682907893615) D58 ^ D46 ^ D48 +error(0.0001011712955095126772) D58 ^ D46 ^ D56 +error(0.0004136195716464172124) D58 ^ D48 +error(0.009786019691043161897) D58 ^ D59 +error(0.00105555876697080984) D58 ^ D67 +error(0.005384160809988575158) D59 D67 ^ D58 +error(0.005000000000000000104) D59 +error(0.02457097167531402046) D59 D67 +error(0.005245339025758253074) D60 +error(0.01351831881670467229) D60 D63 +error(0.01232203752053264746) D60 D63 ^ D61 L0 +error(0.02137993200743813771) D60 D68 +error(0.004131755026116961001) D60 D68 ^ D69 L0 +error(0.002903203036019879387) D60 D71 +error(0.003328581296933910347) D60 D71 ^ D61 L0 +error(0.002153497648560191106) D60 D71 ^ D69 L0 +error(0.00132794561778247131) D60 D71 ^ D69 L0 ^ D61 L0 +error(0.002297625395399578718) D60 D72 +error(0.001564841148743489939) D60 D72 ^ D61 D69 +error(0.0003724936510519168045) D60 D72 ^ D61 L0 +error(0.0003891805678224126625) D60 D72 ^ D69 L0 +error(0.005021350549187082041) D60 ^ D61 L0 +error(0.002754177369565753448) D60 ^ D69 L0 +error(0.003687446986055130382) D61 D69 ^ D60 +error(0.008302277937618965375) D61 D62 +error(0.0004930814379600387092) D61 D62 ^ D60 +error(0.0002344286990215338929) D61 D62 ^ D63 D64 +error(0.0002827200622917192853) D61 D62 ^ D63 D72 +error(0.01071681271374672756) D61 D62 ^ D64 +error(0.002689376411773483633) D61 D62 ^ D64 D72 +error(0.001802538463770141227) D61 D62 ^ D72 +error(4.045483039878490701e-05) D61 D62 ^ D72 ^ D60 +error(0.01568589133027759736) D61 D66 +error(0.01169068635140842367) D61 D66 ^ D63 D64 +error(0.03140897183913322899) D61 D69 +error(0.002019920062412751318) D61 D69 ^ D71 D72 +error(0.001834189692617856256) D61 D69 ^ D72 +error(0.003283249611206463282) D61 D73 +error(0.002217039097925698875) D61 D73 ^ D63 D71 +error(0.0004311616500379738615) D61 D73 ^ D63 D72 +error(0.0003601196358267589183) D61 D73 ^ D71 D72 +error(0.005495111026433003795) D61 D74 +error(0.001924571388590668678) D61 D74 ^ D63 D64 +error(0.001919238098036685951) D61 D74 ^ D63 D71 +error(0.001542925559449527615) D61 D74 ^ D63 D72 +error(0.0004065625308521262694) D61 D74 ^ D64 D72 +error(0.001517534904390731645) D61 D74 ^ D71 D72 +error(0.01000000000000000021) D61 L0 +error(0.000630023031437223005) D61 L0 ^ D71 +error(0.003559447081430625569) D63 D71 ^ D61 L0 +error(0.009592028122265101528) D62 +error(0.002359226002129251928) D62 D69 +error(0.0004700885901282171966) D62 D69 ^ D60 +error(0.002842631538867582044) D62 D69 ^ D72 +error(0.03323098142033485691) D62 D70 +error(0.003694859541453752051) D62 D70 ^ D72 +error(0.001887308115760311577) D62 D74 +error(7.667254054394448501e-05) D62 D74 ^ D63 D64 +error(0.0001684128039816316761) D62 D74 ^ D63 D72 +error(0.00155935512012112215) D62 D74 ^ D64 D72 +error(0.01465668303041333873) D62 ^ D64 +error(0.002208325456735622545) D62 ^ D72 ^ D64 +error(0.01000000000000000021) D63 +error(0.01641885170447205181) D63 D64 +error(6.757040603604669575e-05) D63 D64 ^ D53 L0 +error(0.000691539702847943495) D63 D64 ^ D65 D66 +error(0.001965417218638295088) D63 D64 ^ D66 +error(0.002025462288331955976) D63 D64 ^ D66 D74 +error(0.002676727229798968322) D63 D64 ^ D74 +error(0.04979648365038458202) D63 D71 +error(0.004075575823084270563) D63 D71 ^ D73 D74 +error(0.003228899945508421909) D63 D72 +error(0.0006267629478556474868) D63 D72 ^ D73 D74 +error(0.001819731574192852766) D63 D75 +error(0.001044374947872651286) D63 D75 ^ D66 +error(0.001721977742605806461) D63 D75 ^ D66 D74 +error(0.0005319396409102149182) D63 D75 ^ D74 +error(0.01221051608950192956) D63 ^ D65 L0 +error(0.004281356988861994943) D65 D73 ^ D63 +error(0.01352570247240133215) D64 +error(0.01916140106904455978) D64 D67 +error(0.02134285127067836463) D64 D67 ^ D66 +error(0.01754222313276320583) D64 D72 +error(0.003925335771774137936) D64 D72 ^ D74 +error(0.00829638757819277893) D64 D75 +error(0.006189697411378116548) D64 D75 ^ D66 +error(0.008227765587022699278) D64 D75 ^ D74 +error(0.001565359356948206127) D64 D75 ^ D74 ^ D66 +error(0.0139259571500968439) D65 D66 +error(0.003653395121599596097) D65 D66 ^ D55 +error(0.01746546765882601299) D65 D66 ^ D63 +error(0.0006115023900453514733) D65 D66 ^ D67 +error(0.0002228130597355455398) D65 D66 ^ D67 ^ D55 +error(0.0215519806561217768) D65 D73 +error(0.00578341455456686613) D65 L0 +error(0.000407844684521510418) D65 L0 ^ D53 L0 ^ D55 +error(0.0003059078627119102755) D65 L0 ^ D53 L0 ^ D63 +error(0.000912866688785244902) D65 L0 ^ D63 ^ D55 +error(0.01809852353947335665) D66 +error(0.004283187852576511058) D66 D73 +error(0.003386911228148268768) D66 D73 ^ D63 +error(0.000374805418012281121) D66 D73 ^ D75 +error(0.000378901796486506696) D66 D73 ^ D75 ^ D63 +error(0.02129317632278137154) D66 D74 +error(0.001098988525176137782) D66 D74 ^ D63 +error(0.003795925922665927942) D66 D74 ^ D75 +error(0.000339845682907893615) D66 ^ D54 ^ D56 +error(0.0001011712955095126772) D66 ^ D54 ^ D64 +error(0.0004136195716464172124) D66 ^ D56 +error(0.009786019691043161897) D66 ^ D67 +error(0.00105555876697080984) D66 ^ D75 +error(0.005384160809988575158) D67 D75 ^ D66 +error(0.005000000000000000104) D67 +error(0.02457097167531402046) D67 D75 +error(0.005245339025758253074) D68 +error(0.01351831881670467229) D68 D71 +error(0.01232203752053264746) D68 D71 ^ D69 L0 +error(0.02137993200743813771) D68 D76 +error(0.004131755026116961001) D68 D76 ^ D77 L0 +error(0.002903203036019879387) D68 D79 +error(0.003328581296933910347) D68 D79 ^ D69 L0 +error(0.002153497648560191106) D68 D79 ^ D77 L0 +error(0.00132794561778247131) D68 D79 ^ D77 L0 ^ D69 L0 +error(0.002297625395399578718) D68 D80 +error(0.001564841148743489939) D68 D80 ^ D69 D77 +error(0.0003724936510519168045) D68 D80 ^ D69 L0 +error(0.0003891805678224126625) D68 D80 ^ D77 L0 +error(0.005021350549187082041) D68 ^ D69 L0 +error(0.002754177369565753448) D68 ^ D77 L0 +error(0.003687446986055130382) D69 D77 ^ D68 +error(0.008302277937618965375) D69 D70 +error(0.0004930814379600387092) D69 D70 ^ D68 +error(0.0002344286990215338929) D69 D70 ^ D71 D72 +error(0.0002827200622917192853) D69 D70 ^ D71 D80 +error(0.01071681271374672756) D69 D70 ^ D72 +error(0.002689376411773483633) D69 D70 ^ D72 D80 +error(0.001802538463770141227) D69 D70 ^ D80 +error(4.045483039878490701e-05) D69 D70 ^ D80 ^ D68 +error(0.01568589133027759736) D69 D74 +error(0.01169068635140842367) D69 D74 ^ D71 D72 +error(0.03140897183913322899) D69 D77 +error(0.002019920062412751318) D69 D77 ^ D79 D80 +error(0.001834189692617856256) D69 D77 ^ D80 +error(0.003283249611206463282) D69 D81 +error(0.002217039097925698875) D69 D81 ^ D71 D79 +error(0.0004311616500379738615) D69 D81 ^ D71 D80 +error(0.0003601196358267589183) D69 D81 ^ D79 D80 +error(0.005495111026433003795) D69 D82 +error(0.001924571388590668678) D69 D82 ^ D71 D72 +error(0.001919238098036685951) D69 D82 ^ D71 D79 +error(0.001542925559449527615) D69 D82 ^ D71 D80 +error(0.0004065625308521262694) D69 D82 ^ D72 D80 +error(0.001517534904390731645) D69 D82 ^ D79 D80 +error(0.01000000000000000021) D69 L0 +error(0.000630023031437223005) D69 L0 ^ D79 +error(0.003559447081430625569) D71 D79 ^ D69 L0 +error(0.009592028122265101528) D70 +error(0.002359226002129251928) D70 D77 +error(0.0004700885901282171966) D70 D77 ^ D68 +error(0.002842631538867582044) D70 D77 ^ D80 +error(0.03323098142033485691) D70 D78 +error(0.003694859541453752051) D70 D78 ^ D80 +error(0.001887308115760311577) D70 D82 +error(7.667254054394448501e-05) D70 D82 ^ D71 D72 +error(0.0001684128039816316761) D70 D82 ^ D71 D80 +error(0.00155935512012112215) D70 D82 ^ D72 D80 +error(0.01465668303041333873) D70 ^ D72 +error(0.002208325456735622545) D70 ^ D80 ^ D72 +error(0.01000000000000000021) D71 +error(0.01641885170447205181) D71 D72 +error(6.757040603604669575e-05) D71 D72 ^ D61 L0 +error(0.000691539702847943495) D71 D72 ^ D73 D74 +error(0.001965417218638295088) D71 D72 ^ D74 +error(0.002025462288331955976) D71 D72 ^ D74 D82 +error(0.002676727229798968322) D71 D72 ^ D82 +error(0.04979648365038458202) D71 D79 +error(0.004075575823084270563) D71 D79 ^ D81 D82 +error(0.003228899945508421909) D71 D80 +error(0.0006267629478556474868) D71 D80 ^ D81 D82 +error(0.001819731574192852766) D71 D83 +error(0.001044374947872651286) D71 D83 ^ D74 +error(0.001721977742605806461) D71 D83 ^ D74 D82 +error(0.0005319396409102149182) D71 D83 ^ D82 +error(0.01221051608950192956) D71 ^ D73 L0 +error(0.004281356988861994943) D73 D81 ^ D71 +error(0.01352570247240133215) D72 +error(0.01916140106904455978) D72 D75 +error(0.02134285127067836463) D72 D75 ^ D74 +error(0.01754222313276320583) D72 D80 +error(0.003925335771774137936) D72 D80 ^ D82 +error(0.00829638757819277893) D72 D83 +error(0.006189697411378116548) D72 D83 ^ D74 +error(0.008227765587022699278) D72 D83 ^ D82 +error(0.001565359356948206127) D72 D83 ^ D82 ^ D74 +error(0.0139259571500968439) D73 D74 +error(0.003653395121599596097) D73 D74 ^ D63 +error(0.01746546765882601299) D73 D74 ^ D71 +error(0.0006115023900453514733) D73 D74 ^ D75 +error(0.0002228130597355455398) D73 D74 ^ D75 ^ D63 +error(0.0215519806561217768) D73 D81 +error(0.00578341455456686613) D73 L0 +error(0.000407844684521510418) D73 L0 ^ D61 L0 ^ D63 +error(0.0003059078627119102755) D73 L0 ^ D61 L0 ^ D71 +error(0.000912866688785244902) D73 L0 ^ D71 ^ D63 +error(0.01809852353947335665) D74 +error(0.004283187852576511058) D74 D81 +error(0.003386911228148268768) D74 D81 ^ D71 +error(0.000374805418012281121) D74 D81 ^ D83 +error(0.000378901796486506696) D74 D81 ^ D83 ^ D71 +error(0.02129317632278137154) D74 D82 +error(0.001098988525176137782) D74 D82 ^ D71 +error(0.003795925922665927942) D74 D82 ^ D83 +error(0.000339845682907893615) D74 ^ D62 ^ D64 +error(0.0001011712955095126772) D74 ^ D62 ^ D72 +error(0.0004136195716464172124) D74 ^ D64 +error(0.009786019691043161897) D74 ^ D75 +error(0.00105555876697080984) D74 ^ D83 +error(0.005384160809988575158) D75 D83 ^ D74 +error(0.005000000000000000104) D75 +error(0.02457097167531402046) D75 D83 +error(0.005245339025758253074) D76 +error(0.01351831881670467229) D76 D79 +error(0.01232203752053264746) D76 D79 ^ D77 L0 +error(0.02137993200743813771) D76 D84 +error(0.004131755026116961001) D76 D84 ^ D85 L0 +error(0.002903203036019879387) D76 D87 +error(0.003328581296933910347) D76 D87 ^ D77 L0 +error(0.002153497648560191106) D76 D87 ^ D85 L0 +error(0.00132794561778247131) D76 D87 ^ D85 L0 ^ D77 L0 +error(0.002297625395399578718) D76 D88 +error(0.001564841148743489939) D76 D88 ^ D77 D85 +error(0.0003724936510519168045) D76 D88 ^ D77 L0 +error(0.0003891805678224126625) D76 D88 ^ D85 L0 +error(0.005021350549187082041) D76 ^ D77 L0 +error(0.002754177369565753448) D76 ^ D85 L0 +error(0.003687446986055130382) D77 D85 ^ D76 +error(0.008302277937618965375) D77 D78 +error(0.0004930814379600387092) D77 D78 ^ D76 +error(0.0002344286990215338929) D77 D78 ^ D79 D80 +error(0.0002827200622917192853) D77 D78 ^ D79 D88 +error(0.01071681271374672756) D77 D78 ^ D80 +error(0.002689376411773483633) D77 D78 ^ D80 D88 +error(0.001802538463770141227) D77 D78 ^ D88 +error(4.045483039878490701e-05) D77 D78 ^ D88 ^ D76 +error(0.01568589133027759736) D77 D82 +error(0.01169068635140842367) D77 D82 ^ D79 D80 +error(0.03140897183913322899) D77 D85 +error(0.002019920062412751318) D77 D85 ^ D87 D88 +error(0.001834189692617856256) D77 D85 ^ D88 +error(0.003283249611206463282) D77 D89 +error(0.002217039097925698875) D77 D89 ^ D79 D87 +error(0.0004311616500379738615) D77 D89 ^ D79 D88 +error(0.0003601196358267589183) D77 D89 ^ D87 D88 +error(0.005495111026433003795) D77 D90 +error(0.001924571388590668678) D77 D90 ^ D79 D80 +error(0.001919238098036685951) D77 D90 ^ D79 D87 +error(0.001542925559449527615) D77 D90 ^ D79 D88 +error(0.0004065625308521262694) D77 D90 ^ D80 D88 +error(0.001517534904390731645) D77 D90 ^ D87 D88 +error(0.01000000000000000021) D77 L0 +error(0.000630023031437223005) D77 L0 ^ D87 +error(0.003559447081430625569) D79 D87 ^ D77 L0 +error(0.009592028122265101528) D78 +error(0.002359226002129251928) D78 D85 +error(0.0004700885901282171966) D78 D85 ^ D76 +error(0.002842631538867582044) D78 D85 ^ D88 +error(0.03323098142033485691) D78 D86 +error(0.003694859541453752051) D78 D86 ^ D88 +error(0.001887308115760311577) D78 D90 +error(7.667254054394448501e-05) D78 D90 ^ D79 D80 +error(0.0001684128039816316761) D78 D90 ^ D79 D88 +error(0.00155935512012112215) D78 D90 ^ D80 D88 +error(0.01465668303041333873) D78 ^ D80 +error(0.002208325456735622545) D78 ^ D88 ^ D80 +error(0.01000000000000000021) D79 +error(0.01641885170447205181) D79 D80 +error(6.757040603604669575e-05) D79 D80 ^ D69 L0 +error(0.000691539702847943495) D79 D80 ^ D81 D82 +error(0.001965417218638295088) D79 D80 ^ D82 +error(0.002025462288331955976) D79 D80 ^ D82 D90 +error(0.002676727229798968322) D79 D80 ^ D90 +error(0.04979648365038458202) D79 D87 +error(0.004075575823084270563) D79 D87 ^ D89 D90 +error(0.003228899945508421909) D79 D88 +error(0.0006267629478556474868) D79 D88 ^ D89 D90 +error(0.001819731574192852766) D79 D91 +error(0.001044374947872651286) D79 D91 ^ D82 +error(0.001721977742605806461) D79 D91 ^ D82 D90 +error(0.0005319396409102149182) D79 D91 ^ D90 +error(0.01221051608950192956) D79 ^ D81 L0 +error(0.004281356988861994943) D81 D89 ^ D79 +error(0.01352570247240133215) D80 +error(0.01916140106904455978) D80 D83 +error(0.02134285127067836463) D80 D83 ^ D82 +error(0.01754222313276320583) D80 D88 +error(0.003925335771774137936) D80 D88 ^ D90 +error(0.00829638757819277893) D80 D91 +error(0.006189697411378116548) D80 D91 ^ D82 +error(0.008227765587022699278) D80 D91 ^ D90 +error(0.001565359356948206127) D80 D91 ^ D90 ^ D82 +error(0.0139259571500968439) D81 D82 +error(0.003653395121599596097) D81 D82 ^ D71 +error(0.01746546765882601299) D81 D82 ^ D79 +error(0.0006115023900453514733) D81 D82 ^ D83 +error(0.0002228130597355455398) D81 D82 ^ D83 ^ D71 +error(0.0215519806561217768) D81 D89 +error(0.00578341455456686613) D81 L0 +error(0.000407844684521510418) D81 L0 ^ D69 L0 ^ D71 +error(0.0003059078627119102755) D81 L0 ^ D69 L0 ^ D79 +error(0.000912866688785244902) D81 L0 ^ D79 ^ D71 +error(0.01809852353947335665) D82 +error(0.004283187852576511058) D82 D89 +error(0.003386911228148268768) D82 D89 ^ D79 +error(0.000374805418012281121) D82 D89 ^ D91 +error(0.000378901796486506696) D82 D89 ^ D91 ^ D79 +error(0.02129317632278137154) D82 D90 +error(0.001098988525176137782) D82 D90 ^ D79 +error(0.003795925922665927942) D82 D90 ^ D91 +error(0.000339845682907893615) D82 ^ D70 ^ D72 +error(0.0001011712955095126772) D82 ^ D70 ^ D80 +error(0.0004136195716464172124) D82 ^ D72 +error(0.009786019691043161897) D82 ^ D83 +error(0.00105555876697080984) D82 ^ D91 +error(0.005384160809988575158) D83 D91 ^ D82 +error(0.005000000000000000104) D83 +error(0.02457097167531402046) D83 D91 +error(0.005245339025758253074) D84 +error(0.01351831881670467229) D84 D87 +error(0.01232203752053264746) D84 D87 ^ D85 L0 +error(0.02137993200743813771) D84 D92 +error(0.004131755026116961001) D84 D92 ^ D93 L0 +error(0.002903203036019879387) D84 D95 +error(0.003328581296933910347) D84 D95 ^ D85 L0 +error(0.002153497648560191106) D84 D95 ^ D93 L0 +error(0.00132794561778247131) D84 D95 ^ D93 L0 ^ D85 L0 +error(0.002297625395399578718) D84 D96 +error(0.001564841148743489939) D84 D96 ^ D85 D93 +error(0.0003724936510519168045) D84 D96 ^ D85 L0 +error(0.0003891805678224126625) D84 D96 ^ D93 L0 +error(0.005021350549187082041) D84 ^ D85 L0 +error(0.002754177369565753448) D84 ^ D93 L0 +error(0.003687446986055130382) D85 D93 ^ D84 +error(0.008302277937618965375) D85 D86 +error(0.0004930814379600387092) D85 D86 ^ D84 +error(0.0002344286990215338929) D85 D86 ^ D87 D88 +error(0.0002827200622917192853) D85 D86 ^ D87 D96 +error(0.01071681271374672756) D85 D86 ^ D88 +error(0.002689376411773483633) D85 D86 ^ D88 D96 +error(0.001802538463770141227) D85 D86 ^ D96 +error(4.045483039878490701e-05) D85 D86 ^ D96 ^ D84 +error(0.01568589133027759736) D85 D90 +error(0.01169068635140842367) D85 D90 ^ D87 D88 +error(0.03140897183913322899) D85 D93 +error(0.002019920062412751318) D85 D93 ^ D95 D96 +error(0.001834189692617856256) D85 D93 ^ D96 +error(0.003283249611206463282) D85 D97 +error(0.002217039097925698875) D85 D97 ^ D87 D95 +error(0.0004311616500379738615) D85 D97 ^ D87 D96 +error(0.0003601196358267589183) D85 D97 ^ D95 D96 +error(0.005495111026433003795) D85 D98 +error(0.001924571388590668678) D85 D98 ^ D87 D88 +error(0.001919238098036685951) D85 D98 ^ D87 D95 +error(0.001542925559449527615) D85 D98 ^ D87 D96 +error(0.0004065625308521262694) D85 D98 ^ D88 D96 +error(0.001517534904390731645) D85 D98 ^ D95 D96 +error(0.01000000000000000021) D85 L0 +error(0.000630023031437223005) D85 L0 ^ D95 +error(0.003559447081430625569) D87 D95 ^ D85 L0 +error(0.009592028122265101528) D86 +error(0.002359226002129251928) D86 D93 +error(0.0004700885901282171966) D86 D93 ^ D84 +error(0.002842631538867582044) D86 D93 ^ D96 +error(0.03323098142033485691) D86 D94 +error(0.003694859541453752051) D86 D94 ^ D96 +error(0.001887308115760311577) D86 D98 +error(7.667254054394448501e-05) D86 D98 ^ D87 D88 +error(0.0001684128039816316761) D86 D98 ^ D87 D96 +error(0.00155935512012112215) D86 D98 ^ D88 D96 +error(0.01465668303041333873) D86 ^ D88 +error(0.002208325456735622545) D86 ^ D96 ^ D88 +error(0.01000000000000000021) D87 +error(0.01641885170447205181) D87 D88 +error(6.757040603604669575e-05) D87 D88 ^ D77 L0 +error(0.000691539702847943495) D87 D88 ^ D89 D90 +error(0.001965417218638295088) D87 D88 ^ D90 +error(0.002025462288331955976) D87 D88 ^ D90 D98 +error(0.002676727229798968322) D87 D88 ^ D98 +error(0.04979648365038458202) D87 D95 +error(0.004075575823084270563) D87 D95 ^ D97 D98 +error(0.003228899945508421909) D87 D96 +error(0.0006267629478556474868) D87 D96 ^ D97 D98 +error(0.001819731574192852766) D87 D99 +error(0.001044374947872651286) D87 D99 ^ D90 +error(0.001721977742605806461) D87 D99 ^ D90 D98 +error(0.0005319396409102149182) D87 D99 ^ D98 +error(0.01221051608950192956) D87 ^ D89 L0 +error(0.004281356988861994943) D89 D97 ^ D87 +error(0.01352570247240133215) D88 +error(0.01916140106904455978) D88 D91 +error(0.02134285127067836463) D88 D91 ^ D90 +error(0.01754222313276320583) D88 D96 +error(0.003925335771774137936) D88 D96 ^ D98 +error(0.00829638757819277893) D88 D99 +error(0.006189697411378116548) D88 D99 ^ D90 +error(0.008227765587022699278) D88 D99 ^ D98 +error(0.001565359356948206127) D88 D99 ^ D98 ^ D90 +error(0.0139259571500968439) D89 D90 +error(0.003653395121599596097) D89 D90 ^ D79 +error(0.01746546765882601299) D89 D90 ^ D87 +error(0.0006115023900453514733) D89 D90 ^ D91 +error(0.0002228130597355455398) D89 D90 ^ D91 ^ D79 +error(0.0215519806561217768) D89 D97 +error(0.00578341455456686613) D89 L0 +error(0.000407844684521510418) D89 L0 ^ D77 L0 ^ D79 +error(0.0003059078627119102755) D89 L0 ^ D77 L0 ^ D87 +error(0.000912866688785244902) D89 L0 ^ D87 ^ D79 +error(0.01809852353947335665) D90 +error(0.004283187852576511058) D90 D97 +error(0.003386911228148268768) D90 D97 ^ D87 +error(0.000374805418012281121) D90 D97 ^ D99 +error(0.000378901796486506696) D90 D97 ^ D99 ^ D87 +error(0.02129317632278137154) D90 D98 +error(0.001098988525176137782) D90 D98 ^ D87 +error(0.003795925922665927942) D90 D98 ^ D99 +error(0.000339845682907893615) D90 ^ D78 ^ D80 +error(0.0001011712955095126772) D90 ^ D78 ^ D88 +error(0.0004136195716464172124) D90 ^ D80 +error(0.009786019691043161897) D90 ^ D91 +error(0.00105555876697080984) D90 ^ D99 +error(0.005384160809988575158) D91 D99 ^ D90 +error(0.005000000000000000104) D91 +error(0.02457097167531402046) D91 D99 +error(0.005245339025758253074) D92 +error(0.01351831881670467229) D92 D95 +error(0.01232203752053264746) D92 D95 ^ D93 L0 +error(0.02137993200743813771) D92 D100 +error(0.004131755026116961001) D92 D100 ^ D101 L0 +error(0.002903203036019879387) D92 D103 +error(0.003328581296933910347) D92 D103 ^ D93 L0 +error(0.002153497648560191106) D92 D103 ^ D101 L0 +error(0.00132794561778247131) D92 D103 ^ D101 L0 ^ D93 L0 +error(0.002297625395399578718) D92 D104 +error(0.001564841148743489939) D92 D104 ^ D93 D101 +error(0.0003724936510519168045) D92 D104 ^ D93 L0 +error(0.0003891805678224126625) D92 D104 ^ D101 L0 +error(0.005021350549187082041) D92 ^ D93 L0 +error(0.002754177369565753448) D92 ^ D101 L0 +error(0.003687446986055130382) D93 D101 ^ D92 +error(0.008302277937618965375) D93 D94 +error(0.0004930814379600387092) D93 D94 ^ D92 +error(0.0002344286990215338929) D93 D94 ^ D95 D96 +error(0.0002827200622917192853) D93 D94 ^ D95 D104 +error(0.01071681271374672756) D93 D94 ^ D96 +error(0.002689376411773483633) D93 D94 ^ D96 D104 +error(0.001802538463770141227) D93 D94 ^ D104 +error(4.045483039878490701e-05) D93 D94 ^ D104 ^ D92 +error(0.01568589133027759736) D93 D98 +error(0.01169068635140842367) D93 D98 ^ D95 D96 +error(0.03140897183913322899) D93 D101 +error(0.002019920062412751318) D93 D101 ^ D103 D104 +error(0.001834189692617856256) D93 D101 ^ D104 +error(0.003283249611206463282) D93 D105 +error(0.002217039097925698875) D93 D105 ^ D95 D103 +error(0.0004311616500379738615) D93 D105 ^ D95 D104 +error(0.0003601196358267589183) D93 D105 ^ D103 D104 +error(0.005495111026433003795) D93 D106 +error(0.001924571388590668678) D93 D106 ^ D95 D96 +error(0.001919238098036685951) D93 D106 ^ D95 D103 +error(0.001542925559449527615) D93 D106 ^ D95 D104 +error(0.0004065625308521262694) D93 D106 ^ D96 D104 +error(0.001517534904390731645) D93 D106 ^ D103 D104 +error(0.01000000000000000021) D93 L0 +error(0.000630023031437223005) D93 L0 ^ D103 +error(0.003559447081430625569) D95 D103 ^ D93 L0 +error(0.009592028122265101528) D94 +error(0.002359226002129251928) D94 D101 +error(0.0004700885901282171966) D94 D101 ^ D92 +error(0.002842631538867582044) D94 D101 ^ D104 +error(0.03323098142033485691) D94 D102 +error(0.003694859541453752051) D94 D102 ^ D104 +error(0.001887308115760311577) D94 D106 +error(7.667254054394448501e-05) D94 D106 ^ D95 D96 +error(0.0001684128039816316761) D94 D106 ^ D95 D104 +error(0.00155935512012112215) D94 D106 ^ D96 D104 +error(0.01465668303041333873) D94 ^ D96 +error(0.002208325456735622545) D94 ^ D104 ^ D96 +error(0.01000000000000000021) D95 +error(0.01641885170447205181) D95 D96 +error(6.757040603604669575e-05) D95 D96 ^ D85 L0 +error(0.000691539702847943495) D95 D96 ^ D97 D98 +error(0.001965417218638295088) D95 D96 ^ D98 +error(0.002025462288331955976) D95 D96 ^ D98 D106 +error(0.002676727229798968322) D95 D96 ^ D106 +error(0.04979648365038458202) D95 D103 +error(0.004075575823084270563) D95 D103 ^ D105 D106 +error(0.003228899945508421909) D95 D104 +error(0.0006267629478556474868) D95 D104 ^ D105 D106 +error(0.001819731574192852766) D95 D107 +error(0.001044374947872651286) D95 D107 ^ D98 +error(0.001721977742605806461) D95 D107 ^ D98 D106 +error(0.0005319396409102149182) D95 D107 ^ D106 +error(0.01221051608950192956) D95 ^ D97 L0 +error(0.004281356988861994943) D97 D105 ^ D95 +error(0.01352570247240133215) D96 +error(0.01916140106904455978) D96 D99 +error(0.02134285127067836463) D96 D99 ^ D98 +error(0.01754222313276320583) D96 D104 +error(0.003925335771774137936) D96 D104 ^ D106 +error(0.00829638757819277893) D96 D107 +error(0.006189697411378116548) D96 D107 ^ D98 +error(0.008227765587022699278) D96 D107 ^ D106 +error(0.001565359356948206127) D96 D107 ^ D106 ^ D98 +error(0.0139259571500968439) D97 D98 +error(0.003653395121599596097) D97 D98 ^ D87 +error(0.01746546765882601299) D97 D98 ^ D95 +error(0.0006115023900453514733) D97 D98 ^ D99 +error(0.0002228130597355455398) D97 D98 ^ D99 ^ D87 +error(0.0215519806561217768) D97 D105 +error(0.00578341455456686613) D97 L0 +error(0.000407844684521510418) D97 L0 ^ D85 L0 ^ D87 +error(0.0003059078627119102755) D97 L0 ^ D85 L0 ^ D95 +error(0.000912866688785244902) D97 L0 ^ D95 ^ D87 +error(0.01809852353947335665) D98 +error(0.004283187852576511058) D98 D105 +error(0.003386911228148268768) D98 D105 ^ D95 +error(0.000374805418012281121) D98 D105 ^ D107 +error(0.000378901796486506696) D98 D105 ^ D107 ^ D95 +error(0.02129317632278137154) D98 D106 +error(0.001098988525176137782) D98 D106 ^ D95 +error(0.003795925922665927942) D98 D106 ^ D107 +error(0.000339845682907893615) D98 ^ D86 ^ D88 +error(0.0001011712955095126772) D98 ^ D86 ^ D96 +error(0.0004136195716464172124) D98 ^ D88 +error(0.009786019691043161897) D98 ^ D99 +error(0.00105555876697080984) D98 ^ D107 +error(0.005384160809988575158) D99 D107 ^ D98 +error(0.005000000000000000104) D99 +error(0.02457097167531402046) D99 D107 +error(0.005245339025758253074) D100 +error(0.01351831881670467229) D100 D103 +error(0.01232203752053264746) D100 D103 ^ D101 L0 +error(0.02137993200743813771) D100 D108 +error(0.004131755026116961001) D100 D108 ^ D109 L0 +error(0.002903203036019879387) D100 D111 +error(0.003328581296933910347) D100 D111 ^ D101 L0 +error(0.002153497648560191106) D100 D111 ^ D109 L0 +error(0.00132794561778247131) D100 D111 ^ D109 L0 ^ D101 L0 +error(0.002297625395399578718) D100 D112 +error(0.001564841148743489939) D100 D112 ^ D101 D109 +error(0.0003724936510519168045) D100 D112 ^ D101 L0 +error(0.0003891805678224126625) D100 D112 ^ D109 L0 +error(0.005021350549187082041) D100 ^ D101 L0 +error(0.002754177369565753448) D100 ^ D109 L0 +error(0.003687446986055130382) D101 D109 ^ D100 +error(0.008302277937618965375) D101 D102 +error(0.0004930814379600387092) D101 D102 ^ D100 +error(0.0002344286990215338929) D101 D102 ^ D103 D104 +error(0.0002827200622917192853) D101 D102 ^ D103 D112 +error(0.01071681271374672756) D101 D102 ^ D104 +error(0.002689376411773483633) D101 D102 ^ D104 D112 +error(0.001802538463770141227) D101 D102 ^ D112 +error(4.045483039878490701e-05) D101 D102 ^ D112 ^ D100 +error(0.01568589133027759736) D101 D106 +error(0.01169068635140842367) D101 D106 ^ D103 D104 +error(0.03140897183913322899) D101 D109 +error(0.002019920062412751318) D101 D109 ^ D111 D112 +error(0.001834189692617856256) D101 D109 ^ D112 +error(0.003283249611206463282) D101 D113 +error(0.002217039097925698875) D101 D113 ^ D103 D111 +error(0.0004311616500379738615) D101 D113 ^ D103 D112 +error(0.0003601196358267589183) D101 D113 ^ D111 D112 +error(0.005495111026433003795) D101 D114 +error(0.001924571388590668678) D101 D114 ^ D103 D104 +error(0.001919238098036685951) D101 D114 ^ D103 D111 +error(0.001542925559449527615) D101 D114 ^ D103 D112 +error(0.0004065625308521262694) D101 D114 ^ D104 D112 +error(0.001517534904390731645) D101 D114 ^ D111 D112 +error(0.01000000000000000021) D101 L0 +error(0.000630023031437223005) D101 L0 ^ D111 +error(0.003559447081430625569) D103 D111 ^ D101 L0 +error(0.009592028122265101528) D102 +error(0.002359226002129251928) D102 D109 +error(0.0004700885901282171966) D102 D109 ^ D100 +error(0.002842631538867582044) D102 D109 ^ D112 +error(0.03323098142033485691) D102 D110 +error(0.003694859541453752051) D102 D110 ^ D112 +error(0.001887308115760311577) D102 D114 +error(7.667254054394448501e-05) D102 D114 ^ D103 D104 +error(0.0001684128039816316761) D102 D114 ^ D103 D112 +error(0.00155935512012112215) D102 D114 ^ D104 D112 +error(0.01465668303041333873) D102 ^ D104 +error(0.002208325456735622545) D102 ^ D112 ^ D104 +error(0.01000000000000000021) D103 +error(0.01641885170447205181) D103 D104 +error(6.757040603604669575e-05) D103 D104 ^ D93 L0 +error(0.000691539702847943495) D103 D104 ^ D105 D106 +error(0.001965417218638295088) D103 D104 ^ D106 +error(0.002025462288331955976) D103 D104 ^ D106 D114 +error(0.002676727229798968322) D103 D104 ^ D114 +error(0.04979648365038458202) D103 D111 +error(0.004075575823084270563) D103 D111 ^ D113 D114 +error(0.003228899945508421909) D103 D112 +error(0.0006267629478556474868) D103 D112 ^ D113 D114 +error(0.001819731574192852766) D103 D115 +error(0.001044374947872651286) D103 D115 ^ D106 +error(0.001721977742605806461) D103 D115 ^ D106 D114 +error(0.0005319396409102149182) D103 D115 ^ D114 +error(0.01221051608950192956) D103 ^ D105 L0 +error(0.004281356988861994943) D105 D113 ^ D103 +error(0.01352570247240133215) D104 +error(0.01916140106904455978) D104 D107 +error(0.02134285127067836463) D104 D107 ^ D106 +error(0.01754222313276320583) D104 D112 +error(0.003925335771774137936) D104 D112 ^ D114 +error(0.00829638757819277893) D104 D115 +error(0.006189697411378116548) D104 D115 ^ D106 +error(0.008227765587022699278) D104 D115 ^ D114 +error(0.001565359356948206127) D104 D115 ^ D114 ^ D106 +error(0.0139259571500968439) D105 D106 +error(0.003653395121599596097) D105 D106 ^ D95 +error(0.01746546765882601299) D105 D106 ^ D103 +error(0.0006115023900453514733) D105 D106 ^ D107 +error(0.0002228130597355455398) D105 D106 ^ D107 ^ D95 +error(0.0215519806561217768) D105 D113 +error(0.00578341455456686613) D105 L0 +error(0.000407844684521510418) D105 L0 ^ D93 L0 ^ D95 +error(0.0003059078627119102755) D105 L0 ^ D93 L0 ^ D103 +error(0.000912866688785244902) D105 L0 ^ D103 ^ D95 +error(0.01809852353947335665) D106 +error(0.004283187852576511058) D106 D113 +error(0.003386911228148268768) D106 D113 ^ D103 +error(0.000374805418012281121) D106 D113 ^ D115 +error(0.000378901796486506696) D106 D113 ^ D115 ^ D103 +error(0.02129317632278137154) D106 D114 +error(0.001098988525176137782) D106 D114 ^ D103 +error(0.003795925922665927942) D106 D114 ^ D115 +error(0.000339845682907893615) D106 ^ D94 ^ D96 +error(0.0001011712955095126772) D106 ^ D94 ^ D104 +error(0.0004136195716464172124) D106 ^ D96 +error(0.009786019691043161897) D106 ^ D107 +error(0.00105555876697080984) D106 ^ D115 +error(0.005384160809988575158) D107 D115 ^ D106 +error(0.005000000000000000104) D107 +error(0.02457097167531402046) D107 D115 +error(0.005245339025758253074) D108 +error(0.01351831881670467229) D108 D111 +error(0.01232203752053264746) D108 D111 ^ D109 L0 +error(0.02137993200743813771) D108 D116 +error(0.004131755026116961001) D108 D116 ^ D117 L0 +error(0.002903203036019879387) D108 D119 +error(0.003328581296933910347) D108 D119 ^ D109 L0 +error(0.002153497648560191106) D108 D119 ^ D117 L0 +error(0.00132794561778247131) D108 D119 ^ D117 L0 ^ D109 L0 +error(0.002297625395399578718) D108 D120 +error(0.001564841148743489939) D108 D120 ^ D109 D117 +error(0.0003724936510519168045) D108 D120 ^ D109 L0 +error(0.0003891805678224126625) D108 D120 ^ D117 L0 +error(0.005021350549187082041) D108 ^ D109 L0 +error(0.002754177369565753448) D108 ^ D117 L0 +error(0.003687446986055130382) D109 D117 ^ D108 +error(0.008302277937618965375) D109 D110 +error(0.0004930814379600387092) D109 D110 ^ D108 +error(0.0002344286990215338929) D109 D110 ^ D111 D112 +error(0.0002827200622917192853) D109 D110 ^ D111 D120 +error(0.01071681271374672756) D109 D110 ^ D112 +error(0.002689376411773483633) D109 D110 ^ D112 D120 +error(0.001802538463770141227) D109 D110 ^ D120 +error(4.045483039878490701e-05) D109 D110 ^ D120 ^ D108 +error(0.01568589133027759736) D109 D114 +error(0.01169068635140842367) D109 D114 ^ D111 D112 +error(0.03140897183913322899) D109 D117 +error(0.002019920062412751318) D109 D117 ^ D119 D120 +error(0.001834189692617856256) D109 D117 ^ D120 +error(0.003283249611206463282) D109 D121 +error(0.002217039097925698875) D109 D121 ^ D111 D119 +error(0.0004311616500379738615) D109 D121 ^ D111 D120 +error(0.0003601196358267589183) D109 D121 ^ D119 D120 +error(0.005495111026433003795) D109 D122 +error(0.001924571388590668678) D109 D122 ^ D111 D112 +error(0.001919238098036685951) D109 D122 ^ D111 D119 +error(0.001542925559449527615) D109 D122 ^ D111 D120 +error(0.0004065625308521262694) D109 D122 ^ D112 D120 +error(0.001517534904390731645) D109 D122 ^ D119 D120 +error(0.01000000000000000021) D109 L0 +error(0.000630023031437223005) D109 L0 ^ D119 +error(0.003559447081430625569) D111 D119 ^ D109 L0 +error(0.009592028122265101528) D110 +error(0.002359226002129251928) D110 D117 +error(0.0004700885901282171966) D110 D117 ^ D108 +error(0.002842631538867582044) D110 D117 ^ D120 +error(0.03323098142033485691) D110 D118 +error(0.003694859541453752051) D110 D118 ^ D120 +error(0.001887308115760311577) D110 D122 +error(7.667254054394448501e-05) D110 D122 ^ D111 D112 +error(0.0001684128039816316761) D110 D122 ^ D111 D120 +error(0.00155935512012112215) D110 D122 ^ D112 D120 +error(0.01465668303041333873) D110 ^ D112 +error(0.002208325456735622545) D110 ^ D120 ^ D112 +error(0.01000000000000000021) D111 +error(0.01641885170447205181) D111 D112 +error(6.757040603604669575e-05) D111 D112 ^ D101 L0 +error(0.000691539702847943495) D111 D112 ^ D113 D114 +error(0.001965417218638295088) D111 D112 ^ D114 +error(0.002025462288331955976) D111 D112 ^ D114 D122 +error(0.002676727229798968322) D111 D112 ^ D122 +error(0.04979648365038458202) D111 D119 +error(0.004075575823084270563) D111 D119 ^ D121 D122 +error(0.003228899945508421909) D111 D120 +error(0.0006267629478556474868) D111 D120 ^ D121 D122 +error(0.001819731574192852766) D111 D123 +error(0.001044374947872651286) D111 D123 ^ D114 +error(0.001721977742605806461) D111 D123 ^ D114 D122 +error(0.0005319396409102149182) D111 D123 ^ D122 +error(0.01221051608950192956) D111 ^ D113 L0 +error(0.004281356988861994943) D113 D121 ^ D111 +error(0.01352570247240133215) D112 +error(0.01916140106904455978) D112 D115 +error(0.02134285127067836463) D112 D115 ^ D114 +error(0.01754222313276320583) D112 D120 +error(0.003925335771774137936) D112 D120 ^ D122 +error(0.00829638757819277893) D112 D123 +error(0.006189697411378116548) D112 D123 ^ D114 +error(0.008227765587022699278) D112 D123 ^ D122 +error(0.001565359356948206127) D112 D123 ^ D122 ^ D114 +error(0.0139259571500968439) D113 D114 +error(0.003653395121599596097) D113 D114 ^ D103 +error(0.01746546765882601299) D113 D114 ^ D111 +error(0.0006115023900453514733) D113 D114 ^ D115 +error(0.0002228130597355455398) D113 D114 ^ D115 ^ D103 +error(0.0215519806561217768) D113 D121 +error(0.00578341455456686613) D113 L0 +error(0.000407844684521510418) D113 L0 ^ D101 L0 ^ D103 +error(0.0003059078627119102755) D113 L0 ^ D101 L0 ^ D111 +error(0.000912866688785244902) D113 L0 ^ D111 ^ D103 +error(0.01809852353947335665) D114 +error(0.004283187852576511058) D114 D121 +error(0.003386911228148268768) D114 D121 ^ D111 +error(0.000374805418012281121) D114 D121 ^ D123 +error(0.000378901796486506696) D114 D121 ^ D123 ^ D111 +error(0.02129317632278137154) D114 D122 +error(0.001098988525176137782) D114 D122 ^ D111 +error(0.003795925922665927942) D114 D122 ^ D123 +error(0.000339845682907893615) D114 ^ D102 ^ D104 +error(0.0001011712955095126772) D114 ^ D102 ^ D112 +error(0.0004136195716464172124) D114 ^ D104 +error(0.009786019691043161897) D114 ^ D115 +error(0.00105555876697080984) D114 ^ D123 +error(0.005384160809988575158) D115 D123 ^ D114 +error(0.005000000000000000104) D115 +error(0.02457097167531402046) D115 D123 +error(0.005245339025758253074) D116 +error(0.01351831881670467229) D116 D119 +error(0.01232203752053264746) D116 D119 ^ D117 L0 +error(0.02137993200743813771) D116 D124 +error(0.004131755026116961001) D116 D124 ^ D125 L0 +error(0.002903203036019879387) D116 D127 +error(0.003328581296933910347) D116 D127 ^ D117 L0 +error(0.002153497648560191106) D116 D127 ^ D125 L0 +error(0.00132794561778247131) D116 D127 ^ D125 L0 ^ D117 L0 +error(0.002297625395399578718) D116 D128 +error(0.001564841148743489939) D116 D128 ^ D117 D125 +error(0.0003724936510519168045) D116 D128 ^ D117 L0 +error(0.0003891805678224126625) D116 D128 ^ D125 L0 +error(0.005021350549187082041) D116 ^ D117 L0 +error(0.002754177369565753448) D116 ^ D125 L0 +error(0.003687446986055130382) D117 D125 ^ D116 +error(0.008302277937618965375) D117 D118 +error(0.0004930814379600387092) D117 D118 ^ D116 +error(0.0002344286990215338929) D117 D118 ^ D119 D120 +error(0.0002827200622917192853) D117 D118 ^ D119 D128 +error(0.01071681271374672756) D117 D118 ^ D120 +error(0.002689376411773483633) D117 D118 ^ D120 D128 +error(0.001802538463770141227) D117 D118 ^ D128 +error(4.045483039878490701e-05) D117 D118 ^ D128 ^ D116 +error(0.01568589133027759736) D117 D122 +error(0.01169068635140842367) D117 D122 ^ D119 D120 +error(0.03140897183913322899) D117 D125 +error(0.002019920062412751318) D117 D125 ^ D127 D128 +error(0.001834189692617856256) D117 D125 ^ D128 +error(0.003283249611206463282) D117 D129 +error(0.002217039097925698875) D117 D129 ^ D119 D127 +error(0.0004311616500379738615) D117 D129 ^ D119 D128 +error(0.0003601196358267589183) D117 D129 ^ D127 D128 +error(0.005495111026433003795) D117 D130 +error(0.001924571388590668678) D117 D130 ^ D119 D120 +error(0.001919238098036685951) D117 D130 ^ D119 D127 +error(0.001542925559449527615) D117 D130 ^ D119 D128 +error(0.0004065625308521262694) D117 D130 ^ D120 D128 +error(0.001517534904390731645) D117 D130 ^ D127 D128 +error(0.01000000000000000021) D117 L0 +error(0.000630023031437223005) D117 L0 ^ D127 +error(0.003559447081430625569) D119 D127 ^ D117 L0 +error(0.009592028122265101528) D118 +error(0.002359226002129251928) D118 D125 +error(0.0004700885901282171966) D118 D125 ^ D116 +error(0.002842631538867582044) D118 D125 ^ D128 +error(0.03323098142033485691) D118 D126 +error(0.003694859541453752051) D118 D126 ^ D128 +error(0.001887308115760311577) D118 D130 +error(7.667254054394448501e-05) D118 D130 ^ D119 D120 +error(0.0001684128039816316761) D118 D130 ^ D119 D128 +error(0.00155935512012112215) D118 D130 ^ D120 D128 +error(0.01465668303041333873) D118 ^ D120 +error(0.002208325456735622545) D118 ^ D128 ^ D120 +error(0.01000000000000000021) D119 +error(0.01641885170447205181) D119 D120 +error(6.757040603604669575e-05) D119 D120 ^ D109 L0 +error(0.000691539702847943495) D119 D120 ^ D121 D122 +error(0.001965417218638295088) D119 D120 ^ D122 +error(0.002025462288331955976) D119 D120 ^ D122 D130 +error(0.002676727229798968322) D119 D120 ^ D130 +error(0.04979648365038458202) D119 D127 +error(0.004075575823084270563) D119 D127 ^ D129 D130 +error(0.003228899945508421909) D119 D128 +error(0.0006267629478556474868) D119 D128 ^ D129 D130 +error(0.001819731574192852766) D119 D131 +error(0.001044374947872651286) D119 D131 ^ D122 +error(0.001721977742605806461) D119 D131 ^ D122 D130 +error(0.0005319396409102149182) D119 D131 ^ D130 +error(0.01221051608950192956) D119 ^ D121 L0 +error(0.004281356988861994943) D121 D129 ^ D119 +error(0.01352570247240133215) D120 +error(0.01916140106904455978) D120 D123 +error(0.02134285127067836463) D120 D123 ^ D122 +error(0.01754222313276320583) D120 D128 +error(0.003925335771774137936) D120 D128 ^ D130 +error(0.00829638757819277893) D120 D131 +error(0.006189697411378116548) D120 D131 ^ D122 +error(0.008227765587022699278) D120 D131 ^ D130 +error(0.001565359356948206127) D120 D131 ^ D130 ^ D122 +error(0.0139259571500968439) D121 D122 +error(0.003653395121599596097) D121 D122 ^ D111 +error(0.01746546765882601299) D121 D122 ^ D119 +error(0.0006115023900453514733) D121 D122 ^ D123 +error(0.0002228130597355455398) D121 D122 ^ D123 ^ D111 +error(0.0215519806561217768) D121 D129 +error(0.00578341455456686613) D121 L0 +error(0.000407844684521510418) D121 L0 ^ D109 L0 ^ D111 +error(0.0003059078627119102755) D121 L0 ^ D109 L0 ^ D119 +error(0.000912866688785244902) D121 L0 ^ D119 ^ D111 +error(0.01809852353947335665) D122 +error(0.004283187852576511058) D122 D129 +error(0.003386911228148268768) D122 D129 ^ D119 +error(0.000374805418012281121) D122 D129 ^ D131 +error(0.000378901796486506696) D122 D129 ^ D131 ^ D119 +error(0.02129317632278137154) D122 D130 +error(0.001098988525176137782) D122 D130 ^ D119 +error(0.003795925922665927942) D122 D130 ^ D131 +error(0.000339845682907893615) D122 ^ D110 ^ D112 +error(0.0001011712955095126772) D122 ^ D110 ^ D120 +error(0.0004136195716464172124) D122 ^ D112 +error(0.009786019691043161897) D122 ^ D123 +error(0.00105555876697080984) D122 ^ D131 +error(0.005384160809988575158) D123 D131 ^ D122 +error(0.005000000000000000104) D123 +error(0.02457097167531402046) D123 D131 +error(0.005245339025758253074) D124 +error(0.01351831881670467229) D124 D127 +error(0.01232203752053264746) D124 D127 ^ D125 L0 +error(0.02137993200743813771) D124 D132 +error(0.004131755026116961001) D124 D132 ^ D133 L0 +error(0.002903203036019879387) D124 D135 +error(0.003328581296933910347) D124 D135 ^ D125 L0 +error(0.002153497648560191106) D124 D135 ^ D133 L0 +error(0.00132794561778247131) D124 D135 ^ D133 L0 ^ D125 L0 +error(0.002297625395399578718) D124 D136 +error(0.001564841148743489939) D124 D136 ^ D125 D133 +error(0.0003724936510519168045) D124 D136 ^ D125 L0 +error(0.0003891805678224126625) D124 D136 ^ D133 L0 +error(0.005021350549187082041) D124 ^ D125 L0 +error(0.002754177369565753448) D124 ^ D133 L0 +error(0.003687446986055130382) D125 D133 ^ D124 +error(0.008302277937618965375) D125 D126 +error(0.0004930814379600387092) D125 D126 ^ D124 +error(0.0002344286990215338929) D125 D126 ^ D127 D128 +error(0.0002827200622917192853) D125 D126 ^ D127 D136 +error(0.01071681271374672756) D125 D126 ^ D128 +error(0.002689376411773483633) D125 D126 ^ D128 D136 +error(0.001802538463770141227) D125 D126 ^ D136 +error(4.045483039878490701e-05) D125 D126 ^ D136 ^ D124 +error(0.01568589133027759736) D125 D130 +error(0.01169068635140842367) D125 D130 ^ D127 D128 +error(0.03140897183913322899) D125 D133 +error(0.002019920062412751318) D125 D133 ^ D135 D136 +error(0.001834189692617856256) D125 D133 ^ D136 +error(0.003283249611206463282) D125 D137 +error(0.002217039097925698875) D125 D137 ^ D127 D135 +error(0.0004311616500379738615) D125 D137 ^ D127 D136 +error(0.0003601196358267589183) D125 D137 ^ D135 D136 +error(0.005495111026433003795) D125 D138 +error(0.001924571388590668678) D125 D138 ^ D127 D128 +error(0.001919238098036685951) D125 D138 ^ D127 D135 +error(0.001542925559449527615) D125 D138 ^ D127 D136 +error(0.0004065625308521262694) D125 D138 ^ D128 D136 +error(0.001517534904390731645) D125 D138 ^ D135 D136 +error(0.01000000000000000021) D125 L0 +error(0.000630023031437223005) D125 L0 ^ D135 +error(0.003559447081430625569) D127 D135 ^ D125 L0 +error(0.009592028122265101528) D126 +error(0.002359226002129251928) D126 D133 +error(0.0004700885901282171966) D126 D133 ^ D124 +error(0.002842631538867582044) D126 D133 ^ D136 +error(0.03323098142033485691) D126 D134 +error(0.003694859541453752051) D126 D134 ^ D136 +error(0.001887308115760311577) D126 D138 +error(7.667254054394448501e-05) D126 D138 ^ D127 D128 +error(0.0001684128039816316761) D126 D138 ^ D127 D136 +error(0.00155935512012112215) D126 D138 ^ D128 D136 +error(0.01465668303041333873) D126 ^ D128 +error(0.002208325456735622545) D126 ^ D136 ^ D128 +error(0.01000000000000000021) D127 +error(0.01641885170447205181) D127 D128 +error(6.757040603604669575e-05) D127 D128 ^ D117 L0 +error(0.000691539702847943495) D127 D128 ^ D129 D130 +error(0.001965417218638295088) D127 D128 ^ D130 +error(0.002025462288331955976) D127 D128 ^ D130 D138 +error(0.002676727229798968322) D127 D128 ^ D138 +error(0.04979648365038458202) D127 D135 +error(0.004075575823084270563) D127 D135 ^ D137 D138 +error(0.003228899945508421909) D127 D136 +error(0.0006267629478556474868) D127 D136 ^ D137 D138 +error(0.001819731574192852766) D127 D139 +error(0.001044374947872651286) D127 D139 ^ D130 +error(0.001721977742605806461) D127 D139 ^ D130 D138 +error(0.0005319396409102149182) D127 D139 ^ D138 +error(0.01221051608950192956) D127 ^ D129 L0 +error(0.004281356988861994943) D129 D137 ^ D127 +error(0.01352570247240133215) D128 +error(0.01916140106904455978) D128 D131 +error(0.02134285127067836463) D128 D131 ^ D130 +error(0.01754222313276320583) D128 D136 +error(0.003925335771774137936) D128 D136 ^ D138 +error(0.00829638757819277893) D128 D139 +error(0.006189697411378116548) D128 D139 ^ D130 +error(0.008227765587022699278) D128 D139 ^ D138 +error(0.001565359356948206127) D128 D139 ^ D138 ^ D130 +error(0.0139259571500968439) D129 D130 +error(0.003653395121599596097) D129 D130 ^ D119 +error(0.01746546765882601299) D129 D130 ^ D127 +error(0.0006115023900453514733) D129 D130 ^ D131 +error(0.0002228130597355455398) D129 D130 ^ D131 ^ D119 +error(0.0215519806561217768) D129 D137 +error(0.00578341455456686613) D129 L0 +error(0.000407844684521510418) D129 L0 ^ D117 L0 ^ D119 +error(0.0003059078627119102755) D129 L0 ^ D117 L0 ^ D127 +error(0.000912866688785244902) D129 L0 ^ D127 ^ D119 +error(0.01809852353947335665) D130 +error(0.004283187852576511058) D130 D137 +error(0.003386911228148268768) D130 D137 ^ D127 +error(0.000374805418012281121) D130 D137 ^ D139 +error(0.000378901796486506696) D130 D137 ^ D139 ^ D127 +error(0.02129317632278137154) D130 D138 +error(0.001098988525176137782) D130 D138 ^ D127 +error(0.003795925922665927942) D130 D138 ^ D139 +error(0.000339845682907893615) D130 ^ D118 ^ D120 +error(0.0001011712955095126772) D130 ^ D118 ^ D128 +error(0.0004136195716464172124) D130 ^ D120 +error(0.009786019691043161897) D130 ^ D131 +error(0.00105555876697080984) D130 ^ D139 +error(0.005384160809988575158) D131 D139 ^ D130 +error(0.005000000000000000104) D131 +error(0.02457097167531402046) D131 D139 +error(0.005245339025758253074) D132 +error(0.01351831881670467229) D132 D135 +error(0.01232203752053264746) D132 D135 ^ D133 L0 +error(0.02137993200743813771) D132 D140 +error(0.004131755026116961001) D132 D140 ^ D141 L0 +error(0.002903203036019879387) D132 D143 +error(0.003328581296933910347) D132 D143 ^ D133 L0 +error(0.002153497648560191106) D132 D143 ^ D141 L0 +error(0.00132794561778247131) D132 D143 ^ D141 L0 ^ D133 L0 +error(0.002297625395399578718) D132 D144 +error(0.001564841148743489939) D132 D144 ^ D133 D141 +error(0.0003724936510519168045) D132 D144 ^ D133 L0 +error(0.0003891805678224126625) D132 D144 ^ D141 L0 +error(0.005021350549187082041) D132 ^ D133 L0 +error(0.002754177369565753448) D132 ^ D141 L0 +error(0.003687446986055130382) D133 D141 ^ D132 +error(0.008302277937618965375) D133 D134 +error(0.0004930814379600387092) D133 D134 ^ D132 +error(0.0002344286990215338929) D133 D134 ^ D135 D136 +error(0.0002827200622917192853) D133 D134 ^ D135 D144 +error(0.01071681271374672756) D133 D134 ^ D136 +error(0.002689376411773483633) D133 D134 ^ D136 D144 +error(0.001802538463770141227) D133 D134 ^ D144 +error(4.045483039878490701e-05) D133 D134 ^ D144 ^ D132 +error(0.01568589133027759736) D133 D138 +error(0.01169068635140842367) D133 D138 ^ D135 D136 +error(0.03140897183913322899) D133 D141 +error(0.002019920062412751318) D133 D141 ^ D143 D144 +error(0.001834189692617856256) D133 D141 ^ D144 +error(0.003283249611206463282) D133 D145 +error(0.002217039097925698875) D133 D145 ^ D135 D143 +error(0.0004311616500379738615) D133 D145 ^ D135 D144 +error(0.0003601196358267589183) D133 D145 ^ D143 D144 +error(0.005495111026433003795) D133 D146 +error(0.001924571388590668678) D133 D146 ^ D135 D136 +error(0.001919238098036685951) D133 D146 ^ D135 D143 +error(0.001542925559449527615) D133 D146 ^ D135 D144 +error(0.0004065625308521262694) D133 D146 ^ D136 D144 +error(0.001517534904390731645) D133 D146 ^ D143 D144 +error(0.01000000000000000021) D133 L0 +error(0.000630023031437223005) D133 L0 ^ D143 +error(0.003559447081430625569) D135 D143 ^ D133 L0 +error(0.009592028122265101528) D134 +error(0.002359226002129251928) D134 D141 +error(0.0004700885901282171966) D134 D141 ^ D132 +error(0.002842631538867582044) D134 D141 ^ D144 +error(0.03323098142033485691) D134 D142 +error(0.003694859541453752051) D134 D142 ^ D144 +error(0.001887308115760311577) D134 D146 +error(7.667254054394448501e-05) D134 D146 ^ D135 D136 +error(0.0001684128039816316761) D134 D146 ^ D135 D144 +error(0.00155935512012112215) D134 D146 ^ D136 D144 +error(0.01465668303041333873) D134 ^ D136 +error(0.002208325456735622545) D134 ^ D144 ^ D136 +error(0.01000000000000000021) D135 +error(0.01641885170447205181) D135 D136 +error(6.757040603604669575e-05) D135 D136 ^ D125 L0 +error(0.000691539702847943495) D135 D136 ^ D137 D138 +error(0.001965417218638295088) D135 D136 ^ D138 +error(0.002025462288331955976) D135 D136 ^ D138 D146 +error(0.002676727229798968322) D135 D136 ^ D146 +error(0.04979648365038458202) D135 D143 +error(0.004075575823084270563) D135 D143 ^ D145 D146 +error(0.003228899945508421909) D135 D144 +error(0.0006267629478556474868) D135 D144 ^ D145 D146 +error(0.001819731574192852766) D135 D147 +error(0.001044374947872651286) D135 D147 ^ D138 +error(0.001721977742605806461) D135 D147 ^ D138 D146 +error(0.0005319396409102149182) D135 D147 ^ D146 +error(0.01221051608950192956) D135 ^ D137 L0 +error(0.004281356988861994943) D137 D145 ^ D135 +error(0.01352570247240133215) D136 +error(0.01916140106904455978) D136 D139 +error(0.02134285127067836463) D136 D139 ^ D138 +error(0.01754222313276320583) D136 D144 +error(0.003925335771774137936) D136 D144 ^ D146 +error(0.00829638757819277893) D136 D147 +error(0.006189697411378116548) D136 D147 ^ D138 +error(0.008227765587022699278) D136 D147 ^ D146 +error(0.001565359356948206127) D136 D147 ^ D146 ^ D138 +error(0.0139259571500968439) D137 D138 +error(0.003653395121599596097) D137 D138 ^ D127 +error(0.01746546765882601299) D137 D138 ^ D135 +error(0.0006115023900453514733) D137 D138 ^ D139 +error(0.0002228130597355455398) D137 D138 ^ D139 ^ D127 +error(0.0215519806561217768) D137 D145 +error(0.00578341455456686613) D137 L0 +error(0.000407844684521510418) D137 L0 ^ D125 L0 ^ D127 +error(0.0003059078627119102755) D137 L0 ^ D125 L0 ^ D135 +error(0.000912866688785244902) D137 L0 ^ D135 ^ D127 +error(0.01809852353947335665) D138 +error(0.004283187852576511058) D138 D145 +error(0.003386911228148268768) D138 D145 ^ D135 +error(0.000374805418012281121) D138 D145 ^ D147 +error(0.000378901796486506696) D138 D145 ^ D147 ^ D135 +error(0.02129317632278137154) D138 D146 +error(0.001098988525176137782) D138 D146 ^ D135 +error(0.003795925922665927942) D138 D146 ^ D147 +error(0.000339845682907893615) D138 ^ D126 ^ D128 +error(0.0001011712955095126772) D138 ^ D126 ^ D136 +error(0.0004136195716464172124) D138 ^ D128 +error(0.009786019691043161897) D138 ^ D139 +error(0.00105555876697080984) D138 ^ D147 +error(0.005384160809988575158) D139 D147 ^ D138 +error(0.005000000000000000104) D139 +error(0.02457097167531402046) D139 D147 +error(0.005245339025758253074) D140 +error(0.01351831881670467229) D140 D143 +error(0.01232203752053264746) D140 D143 ^ D141 L0 +error(0.02137993200743813771) D140 D148 +error(0.004131755026116961001) D140 D148 ^ D149 L0 +error(0.002903203036019879387) D140 D151 +error(0.003328581296933910347) D140 D151 ^ D141 L0 +error(0.002153497648560191106) D140 D151 ^ D149 L0 +error(0.00132794561778247131) D140 D151 ^ D149 L0 ^ D141 L0 +error(0.002297625395399578718) D140 D152 +error(0.001564841148743489939) D140 D152 ^ D141 D149 +error(0.0003724936510519168045) D140 D152 ^ D141 L0 +error(0.0003891805678224126625) D140 D152 ^ D149 L0 +error(0.005021350549187082041) D140 ^ D141 L0 +error(0.002754177369565753448) D140 ^ D149 L0 +error(0.003687446986055130382) D141 D149 ^ D140 +error(0.008302277937618965375) D141 D142 +error(0.0004930814379600387092) D141 D142 ^ D140 +error(0.0002344286990215338929) D141 D142 ^ D143 D144 +error(0.0002827200622917192853) D141 D142 ^ D143 D152 +error(0.01071681271374672756) D141 D142 ^ D144 +error(0.002689376411773483633) D141 D142 ^ D144 D152 +error(0.001802538463770141227) D141 D142 ^ D152 +error(4.045483039878490701e-05) D141 D142 ^ D152 ^ D140 +error(0.01568589133027759736) D141 D146 +error(0.01169068635140842367) D141 D146 ^ D143 D144 +error(0.03140897183913322899) D141 D149 +error(0.002019920062412751318) D141 D149 ^ D151 D152 +error(0.001834189692617856256) D141 D149 ^ D152 +error(0.003283249611206463282) D141 D153 +error(0.002217039097925698875) D141 D153 ^ D143 D151 +error(0.0004311616500379738615) D141 D153 ^ D143 D152 +error(0.0003601196358267589183) D141 D153 ^ D151 D152 +error(0.005495111026433003795) D141 D154 +error(0.001924571388590668678) D141 D154 ^ D143 D144 +error(0.001919238098036685951) D141 D154 ^ D143 D151 +error(0.001542925559449527615) D141 D154 ^ D143 D152 +error(0.0004065625308521262694) D141 D154 ^ D144 D152 +error(0.001517534904390731645) D141 D154 ^ D151 D152 +error(0.01000000000000000021) D141 L0 +error(0.000630023031437223005) D141 L0 ^ D151 +error(0.003559447081430625569) D143 D151 ^ D141 L0 +error(0.009592028122265101528) D142 +error(0.002359226002129251928) D142 D149 +error(0.0004700885901282171966) D142 D149 ^ D140 +error(0.002842631538867582044) D142 D149 ^ D152 +error(0.03323098142033485691) D142 D150 +error(0.003694859541453752051) D142 D150 ^ D152 +error(0.001887308115760311577) D142 D154 +error(7.667254054394448501e-05) D142 D154 ^ D143 D144 +error(0.0001684128039816316761) D142 D154 ^ D143 D152 +error(0.00155935512012112215) D142 D154 ^ D144 D152 +error(0.01465668303041333873) D142 ^ D144 +error(0.002208325456735622545) D142 ^ D152 ^ D144 +error(0.01000000000000000021) D143 +error(0.01641885170447205181) D143 D144 +error(6.757040603604669575e-05) D143 D144 ^ D133 L0 +error(0.000691539702847943495) D143 D144 ^ D145 D146 +error(0.001965417218638295088) D143 D144 ^ D146 +error(0.002025462288331955976) D143 D144 ^ D146 D154 +error(0.002676727229798968322) D143 D144 ^ D154 +error(0.04979648365038458202) D143 D151 +error(0.004075575823084270563) D143 D151 ^ D153 D154 +error(0.003228899945508421909) D143 D152 +error(0.0006267629478556474868) D143 D152 ^ D153 D154 +error(0.001819731574192852766) D143 D155 +error(0.001044374947872651286) D143 D155 ^ D146 +error(0.001721977742605806461) D143 D155 ^ D146 D154 +error(0.0005319396409102149182) D143 D155 ^ D154 +error(0.01221051608950192956) D143 ^ D145 L0 +error(0.004281356988861994943) D145 D153 ^ D143 +error(0.01352570247240133215) D144 +error(0.01916140106904455978) D144 D147 +error(0.02134285127067836463) D144 D147 ^ D146 +error(0.01754222313276320583) D144 D152 +error(0.003925335771774137936) D144 D152 ^ D154 +error(0.00829638757819277893) D144 D155 +error(0.006189697411378116548) D144 D155 ^ D146 +error(0.008227765587022699278) D144 D155 ^ D154 +error(0.001565359356948206127) D144 D155 ^ D154 ^ D146 +error(0.0139259571500968439) D145 D146 +error(0.003653395121599596097) D145 D146 ^ D135 +error(0.01746546765882601299) D145 D146 ^ D143 +error(0.0006115023900453514733) D145 D146 ^ D147 +error(0.0002228130597355455398) D145 D146 ^ D147 ^ D135 +error(0.0215519806561217768) D145 D153 +error(0.00578341455456686613) D145 L0 +error(0.000407844684521510418) D145 L0 ^ D133 L0 ^ D135 +error(0.0003059078627119102755) D145 L0 ^ D133 L0 ^ D143 +error(0.000912866688785244902) D145 L0 ^ D143 ^ D135 +error(0.01809852353947335665) D146 +error(0.004283187852576511058) D146 D153 +error(0.003386911228148268768) D146 D153 ^ D143 +error(0.000374805418012281121) D146 D153 ^ D155 +error(0.000378901796486506696) D146 D153 ^ D155 ^ D143 +error(0.02129317632278137154) D146 D154 +error(0.001098988525176137782) D146 D154 ^ D143 +error(0.003795925922665927942) D146 D154 ^ D155 +error(0.000339845682907893615) D146 ^ D134 ^ D136 +error(0.0001011712955095126772) D146 ^ D134 ^ D144 +error(0.0004136195716464172124) D146 ^ D136 +error(0.009786019691043161897) D146 ^ D147 +error(0.00105555876697080984) D146 ^ D155 +error(0.005384160809988575158) D147 D155 ^ D146 +error(0.005000000000000000104) D147 +error(0.02457097167531402046) D147 D155 +error(0.005245339025758253074) D148 +error(0.01351831881670467229) D148 D151 +error(0.01232203752053264746) D148 D151 ^ D149 L0 +error(0.02137993200743813771) D148 D156 +error(0.004131755026116961001) D148 D156 ^ D157 L0 +error(0.002903203036019879387) D148 D159 +error(0.003328581296933910347) D148 D159 ^ D149 L0 +error(0.002153497648560191106) D148 D159 ^ D157 L0 +error(0.00132794561778247131) D148 D159 ^ D157 L0 ^ D149 L0 +error(0.002297625395399578718) D148 D160 +error(0.001564841148743489939) D148 D160 ^ D149 D157 +error(0.0003724936510519168045) D148 D160 ^ D149 L0 +error(0.0003891805678224126625) D148 D160 ^ D157 L0 +error(0.005021350549187082041) D148 ^ D149 L0 +error(0.002754177369565753448) D148 ^ D157 L0 +error(0.003687446986055130382) D149 D157 ^ D148 +error(0.008302277937618965375) D149 D150 +error(0.0004930814379600387092) D149 D150 ^ D148 +error(0.0002344286990215338929) D149 D150 ^ D151 D152 +error(0.0002827200622917192853) D149 D150 ^ D151 D160 +error(0.01071681271374672756) D149 D150 ^ D152 +error(0.002689376411773483633) D149 D150 ^ D152 D160 +error(0.001802538463770141227) D149 D150 ^ D160 +error(4.045483039878490701e-05) D149 D150 ^ D160 ^ D148 +error(0.01568589133027759736) D149 D154 +error(0.01169068635140842367) D149 D154 ^ D151 D152 +error(0.03140897183913322899) D149 D157 +error(0.002019920062412751318) D149 D157 ^ D159 D160 +error(0.001834189692617856256) D149 D157 ^ D160 +error(0.003283249611206463282) D149 D161 +error(0.002217039097925698875) D149 D161 ^ D151 D159 +error(0.0004311616500379738615) D149 D161 ^ D151 D160 +error(0.0003601196358267589183) D149 D161 ^ D159 D160 +error(0.005495111026433003795) D149 D162 +error(0.001924571388590668678) D149 D162 ^ D151 D152 +error(0.001919238098036685951) D149 D162 ^ D151 D159 +error(0.001542925559449527615) D149 D162 ^ D151 D160 +error(0.0004065625308521262694) D149 D162 ^ D152 D160 +error(0.001517534904390731645) D149 D162 ^ D159 D160 +error(0.01000000000000000021) D149 L0 +error(0.000630023031437223005) D149 L0 ^ D159 +error(0.003559447081430625569) D151 D159 ^ D149 L0 +error(0.009592028122265101528) D150 +error(0.002359226002129251928) D150 D157 +error(0.0004700885901282171966) D150 D157 ^ D148 +error(0.002842631538867582044) D150 D157 ^ D160 +error(0.03323098142033485691) D150 D158 +error(0.003694859541453752051) D150 D158 ^ D160 +error(0.001887308115760311577) D150 D162 +error(7.667254054394448501e-05) D150 D162 ^ D151 D152 +error(0.0001684128039816316761) D150 D162 ^ D151 D160 +error(0.00155935512012112215) D150 D162 ^ D152 D160 +error(0.01465668303041333873) D150 ^ D152 +error(0.002208325456735622545) D150 ^ D160 ^ D152 +error(0.01000000000000000021) D151 +error(0.01641885170447205181) D151 D152 +error(6.757040603604669575e-05) D151 D152 ^ D141 L0 +error(0.000691539702847943495) D151 D152 ^ D153 D154 +error(0.001965417218638295088) D151 D152 ^ D154 +error(0.002025462288331955976) D151 D152 ^ D154 D162 +error(0.002676727229798968322) D151 D152 ^ D162 +error(0.04979648365038458202) D151 D159 +error(0.004075575823084270563) D151 D159 ^ D161 D162 +error(0.003228899945508421909) D151 D160 +error(0.0006267629478556474868) D151 D160 ^ D161 D162 +error(0.001819731574192852766) D151 D163 +error(0.001044374947872651286) D151 D163 ^ D154 +error(0.001721977742605806461) D151 D163 ^ D154 D162 +error(0.0005319396409102149182) D151 D163 ^ D162 +error(0.01221051608950192956) D151 ^ D153 L0 +error(0.004281356988861994943) D153 D161 ^ D151 +error(0.01352570247240133215) D152 +error(0.01916140106904455978) D152 D155 +error(0.02134285127067836463) D152 D155 ^ D154 +error(0.01754222313276320583) D152 D160 +error(0.003925335771774137936) D152 D160 ^ D162 +error(0.00829638757819277893) D152 D163 +error(0.006189697411378116548) D152 D163 ^ D154 +error(0.008227765587022699278) D152 D163 ^ D162 +error(0.001565359356948206127) D152 D163 ^ D162 ^ D154 +error(0.0139259571500968439) D153 D154 +error(0.003653395121599596097) D153 D154 ^ D143 +error(0.01746546765882601299) D153 D154 ^ D151 +error(0.0006115023900453514733) D153 D154 ^ D155 +error(0.0002228130597355455398) D153 D154 ^ D155 ^ D143 +error(0.0215519806561217768) D153 D161 +error(0.00578341455456686613) D153 L0 +error(0.000407844684521510418) D153 L0 ^ D141 L0 ^ D143 +error(0.0003059078627119102755) D153 L0 ^ D141 L0 ^ D151 +error(0.000912866688785244902) D153 L0 ^ D151 ^ D143 +error(0.01809852353947335665) D154 +error(0.004283187852576511058) D154 D161 +error(0.003386911228148268768) D154 D161 ^ D151 +error(0.000374805418012281121) D154 D161 ^ D163 +error(0.000378901796486506696) D154 D161 ^ D163 ^ D151 +error(0.02129317632278137154) D154 D162 +error(0.001098988525176137782) D154 D162 ^ D151 +error(0.003795925922665927942) D154 D162 ^ D163 +error(0.000339845682907893615) D154 ^ D142 ^ D144 +error(0.0001011712955095126772) D154 ^ D142 ^ D152 +error(0.0004136195716464172124) D154 ^ D144 +error(0.009786019691043161897) D154 ^ D155 +error(0.00105555876697080984) D154 ^ D163 +error(0.005384160809988575158) D155 D163 ^ D154 +error(0.005000000000000000104) D155 +error(0.02457097167531402046) D155 D163 +error(0.005245339025758253074) D156 +error(0.01351831881670467229) D156 D159 +error(0.01232203752053264746) D156 D159 ^ D157 L0 +error(0.02137993200743813771) D156 D164 +error(0.004131755026116961001) D156 D164 ^ D165 L0 +error(0.002903203036019879387) D156 D167 +error(0.003328581296933910347) D156 D167 ^ D157 L0 +error(0.002153497648560191106) D156 D167 ^ D165 L0 +error(0.00132794561778247131) D156 D167 ^ D165 L0 ^ D157 L0 +error(0.002297625395399578718) D156 D168 +error(0.001564841148743489939) D156 D168 ^ D157 D165 +error(0.0003724936510519168045) D156 D168 ^ D157 L0 +error(0.0003891805678224126625) D156 D168 ^ D165 L0 +error(0.005021350549187082041) D156 ^ D157 L0 +error(0.002754177369565753448) D156 ^ D165 L0 +error(0.003687446986055130382) D157 D165 ^ D156 +error(0.008302277937618965375) D157 D158 +error(0.0004930814379600387092) D157 D158 ^ D156 +error(0.0002344286990215338929) D157 D158 ^ D159 D160 +error(0.0002827200622917192853) D157 D158 ^ D159 D168 +error(0.01071681271374672756) D157 D158 ^ D160 +error(0.002689376411773483633) D157 D158 ^ D160 D168 +error(0.001802538463770141227) D157 D158 ^ D168 +error(4.045483039878490701e-05) D157 D158 ^ D168 ^ D156 +error(0.01568589133027759736) D157 D162 +error(0.01169068635140842367) D157 D162 ^ D159 D160 +error(0.03140897183913322899) D157 D165 +error(0.002019920062412751318) D157 D165 ^ D167 D168 +error(0.001834189692617856256) D157 D165 ^ D168 +error(0.003283249611206463282) D157 D169 +error(0.002217039097925698875) D157 D169 ^ D159 D167 +error(0.0004311616500379738615) D157 D169 ^ D159 D168 +error(0.0003601196358267589183) D157 D169 ^ D167 D168 +error(0.005495111026433003795) D157 D170 +error(0.001924571388590668678) D157 D170 ^ D159 D160 +error(0.001919238098036685951) D157 D170 ^ D159 D167 +error(0.001542925559449527615) D157 D170 ^ D159 D168 +error(0.0004065625308521262694) D157 D170 ^ D160 D168 +error(0.001517534904390731645) D157 D170 ^ D167 D168 +error(0.01000000000000000021) D157 L0 +error(0.000630023031437223005) D157 L0 ^ D167 +error(0.003559447081430625569) D159 D167 ^ D157 L0 +error(0.009592028122265101528) D158 +error(0.002359226002129251928) D158 D165 +error(0.0004700885901282171966) D158 D165 ^ D156 +error(0.002842631538867582044) D158 D165 ^ D168 +error(0.03323098142033485691) D158 D166 +error(0.003694859541453752051) D158 D166 ^ D168 +error(0.001887308115760311577) D158 D170 +error(7.667254054394448501e-05) D158 D170 ^ D159 D160 +error(0.0001684128039816316761) D158 D170 ^ D159 D168 +error(0.00155935512012112215) D158 D170 ^ D160 D168 +error(0.01465668303041333873) D158 ^ D160 +error(0.002208325456735622545) D158 ^ D168 ^ D160 +error(0.01000000000000000021) D159 +error(0.01641885170447205181) D159 D160 +error(6.757040603604669575e-05) D159 D160 ^ D149 L0 +error(0.000691539702847943495) D159 D160 ^ D161 D162 +error(0.001965417218638295088) D159 D160 ^ D162 +error(0.002025462288331955976) D159 D160 ^ D162 D170 +error(0.002676727229798968322) D159 D160 ^ D170 +error(0.04979648365038458202) D159 D167 +error(0.004075575823084270563) D159 D167 ^ D169 D170 +error(0.003228899945508421909) D159 D168 +error(0.0006267629478556474868) D159 D168 ^ D169 D170 +error(0.001819731574192852766) D159 D171 +error(0.001044374947872651286) D159 D171 ^ D162 +error(0.001721977742605806461) D159 D171 ^ D162 D170 +error(0.0005319396409102149182) D159 D171 ^ D170 +error(0.01221051608950192956) D159 ^ D161 L0 +error(0.004281356988861994943) D161 D169 ^ D159 +error(0.01352570247240133215) D160 +error(0.01916140106904455978) D160 D163 +error(0.02134285127067836463) D160 D163 ^ D162 +error(0.01754222313276320583) D160 D168 +error(0.003925335771774137936) D160 D168 ^ D170 +error(0.00829638757819277893) D160 D171 +error(0.006189697411378116548) D160 D171 ^ D162 +error(0.008227765587022699278) D160 D171 ^ D170 +error(0.001565359356948206127) D160 D171 ^ D170 ^ D162 +error(0.0139259571500968439) D161 D162 +error(0.003653395121599596097) D161 D162 ^ D151 +error(0.01746546765882601299) D161 D162 ^ D159 +error(0.0006115023900453514733) D161 D162 ^ D163 +error(0.0002228130597355455398) D161 D162 ^ D163 ^ D151 +error(0.0215519806561217768) D161 D169 +error(0.00578341455456686613) D161 L0 +error(0.000407844684521510418) D161 L0 ^ D149 L0 ^ D151 +error(0.0003059078627119102755) D161 L0 ^ D149 L0 ^ D159 +error(0.000912866688785244902) D161 L0 ^ D159 ^ D151 +error(0.01809852353947335665) D162 +error(0.004283187852576511058) D162 D169 +error(0.003386911228148268768) D162 D169 ^ D159 +error(0.000374805418012281121) D162 D169 ^ D171 +error(0.000378901796486506696) D162 D169 ^ D171 ^ D159 +error(0.02129317632278137154) D162 D170 +error(0.001098988525176137782) D162 D170 ^ D159 +error(0.003795925922665927942) D162 D170 ^ D171 +error(0.000339845682907893615) D162 ^ D150 ^ D152 +error(0.0001011712955095126772) D162 ^ D150 ^ D160 +error(0.0004136195716464172124) D162 ^ D152 +error(0.009786019691043161897) D162 ^ D163 +error(0.00105555876697080984) D162 ^ D171 +error(0.005384160809988575158) D163 D171 ^ D162 +error(0.005000000000000000104) D163 +error(0.02457097167531402046) D163 D171 +error(0.005245339025758253074) D164 +error(0.01351831881670467229) D164 D167 +error(0.01232203752053264746) D164 D167 ^ D165 L0 +error(0.02137993200743813771) D164 D172 +error(0.004131755026116961001) D164 D172 ^ D173 L0 +error(0.002903203036019879387) D164 D175 +error(0.003328581296933910347) D164 D175 ^ D165 L0 +error(0.002153497648560191106) D164 D175 ^ D173 L0 +error(0.00132794561778247131) D164 D175 ^ D173 L0 ^ D165 L0 +error(0.002297625395399578718) D164 D176 +error(0.001564841148743489939) D164 D176 ^ D165 D173 +error(0.0003724936510519168045) D164 D176 ^ D165 L0 +error(0.0003891805678224126625) D164 D176 ^ D173 L0 +error(0.005021350549187082041) D164 ^ D165 L0 +error(0.002754177369565753448) D164 ^ D173 L0 +error(0.003687446986055130382) D165 D173 ^ D164 +error(0.008302277937618965375) D165 D166 +error(0.0004930814379600387092) D165 D166 ^ D164 +error(0.0002344286990215338929) D165 D166 ^ D167 D168 +error(0.0002827200622917192853) D165 D166 ^ D167 D176 +error(0.01071681271374672756) D165 D166 ^ D168 +error(0.002689376411773483633) D165 D166 ^ D168 D176 +error(0.001802538463770141227) D165 D166 ^ D176 +error(4.045483039878490701e-05) D165 D166 ^ D176 ^ D164 +error(0.01568589133027759736) D165 D170 +error(0.01169068635140842367) D165 D170 ^ D167 D168 +error(0.03140897183913322899) D165 D173 +error(0.002019920062412751318) D165 D173 ^ D175 D176 +error(0.001834189692617856256) D165 D173 ^ D176 +error(0.003283249611206463282) D165 D177 +error(0.002217039097925698875) D165 D177 ^ D167 D175 +error(0.0004311616500379738615) D165 D177 ^ D167 D176 +error(0.0003601196358267589183) D165 D177 ^ D175 D176 +error(0.005495111026433003795) D165 D178 +error(0.001924571388590668678) D165 D178 ^ D167 D168 +error(0.001919238098036685951) D165 D178 ^ D167 D175 +error(0.001542925559449527615) D165 D178 ^ D167 D176 +error(0.0004065625308521262694) D165 D178 ^ D168 D176 +error(0.001517534904390731645) D165 D178 ^ D175 D176 +error(0.01000000000000000021) D165 L0 +error(0.000630023031437223005) D165 L0 ^ D175 +error(0.003559447081430625569) D167 D175 ^ D165 L0 +error(0.009592028122265101528) D166 +error(0.002359226002129251928) D166 D173 +error(0.0004700885901282171966) D166 D173 ^ D164 +error(0.002842631538867582044) D166 D173 ^ D176 +error(0.03323098142033485691) D166 D174 +error(0.003694859541453752051) D166 D174 ^ D176 +error(0.001887308115760311577) D166 D178 +error(7.667254054394448501e-05) D166 D178 ^ D167 D168 +error(0.0001684128039816316761) D166 D178 ^ D167 D176 +error(0.00155935512012112215) D166 D178 ^ D168 D176 +error(0.01465668303041333873) D166 ^ D168 +error(0.002208325456735622545) D166 ^ D176 ^ D168 +error(0.01000000000000000021) D167 +error(0.01641885170447205181) D167 D168 +error(6.757040603604669575e-05) D167 D168 ^ D157 L0 +error(0.000691539702847943495) D167 D168 ^ D169 D170 +error(0.001965417218638295088) D167 D168 ^ D170 +error(0.002025462288331955976) D167 D168 ^ D170 D178 +error(0.002676727229798968322) D167 D168 ^ D178 +error(0.04979648365038458202) D167 D175 +error(0.004075575823084270563) D167 D175 ^ D177 D178 +error(0.003228899945508421909) D167 D176 +error(0.0006267629478556474868) D167 D176 ^ D177 D178 +error(0.001819731574192852766) D167 D179 +error(0.001044374947872651286) D167 D179 ^ D170 +error(0.001721977742605806461) D167 D179 ^ D170 D178 +error(0.0005319396409102149182) D167 D179 ^ D178 +error(0.01221051608950192956) D167 ^ D169 L0 +error(0.004281356988861994943) D169 D177 ^ D167 +error(0.01352570247240133215) D168 +error(0.01916140106904455978) D168 D171 +error(0.02134285127067836463) D168 D171 ^ D170 +error(0.01754222313276320583) D168 D176 +error(0.003925335771774137936) D168 D176 ^ D178 +error(0.00829638757819277893) D168 D179 +error(0.006189697411378116548) D168 D179 ^ D170 +error(0.008227765587022699278) D168 D179 ^ D178 +error(0.001565359356948206127) D168 D179 ^ D178 ^ D170 +error(0.0139259571500968439) D169 D170 +error(0.003653395121599596097) D169 D170 ^ D159 +error(0.01746546765882601299) D169 D170 ^ D167 +error(0.0006115023900453514733) D169 D170 ^ D171 +error(0.0002228130597355455398) D169 D170 ^ D171 ^ D159 +error(0.0215519806561217768) D169 D177 +error(0.00578341455456686613) D169 L0 +error(0.000407844684521510418) D169 L0 ^ D157 L0 ^ D159 +error(0.0003059078627119102755) D169 L0 ^ D157 L0 ^ D167 +error(0.000912866688785244902) D169 L0 ^ D167 ^ D159 +error(0.01809852353947335665) D170 +error(0.004283187852576511058) D170 D177 +error(0.003386911228148268768) D170 D177 ^ D167 +error(0.000374805418012281121) D170 D177 ^ D179 +error(0.000378901796486506696) D170 D177 ^ D179 ^ D167 +error(0.02129317632278137154) D170 D178 +error(0.001098988525176137782) D170 D178 ^ D167 +error(0.003795925922665927942) D170 D178 ^ D179 +error(0.000339845682907893615) D170 ^ D158 ^ D160 +error(0.0001011712955095126772) D170 ^ D158 ^ D168 +error(0.0004136195716464172124) D170 ^ D160 +error(0.009786019691043161897) D170 ^ D171 +error(0.00105555876697080984) D170 ^ D179 +error(0.005384160809988575158) D171 D179 ^ D170 +error(0.005000000000000000104) D171 +error(0.02457097167531402046) D171 D179 +error(0.005245339025758253074) D172 +error(0.01351831881670467229) D172 D175 +error(0.01232203752053264746) D172 D175 ^ D173 L0 +error(0.02137993200743813771) D172 D180 +error(0.004131755026116961001) D172 D180 ^ D181 L0 +error(0.002903203036019879387) D172 D183 +error(0.003328581296933910347) D172 D183 ^ D173 L0 +error(0.002153497648560191106) D172 D183 ^ D181 L0 +error(0.00132794561778247131) D172 D183 ^ D181 L0 ^ D173 L0 +error(0.002297625395399578718) D172 D184 +error(0.001564841148743489939) D172 D184 ^ D173 D181 +error(0.0003724936510519168045) D172 D184 ^ D173 L0 +error(0.0003891805678224126625) D172 D184 ^ D181 L0 +error(0.005021350549187082041) D172 ^ D173 L0 +error(0.002754177369565753448) D172 ^ D181 L0 +error(0.003687446986055130382) D173 D181 ^ D172 +error(0.008302277937618965375) D173 D174 +error(0.0004930814379600387092) D173 D174 ^ D172 +error(0.0002344286990215338929) D173 D174 ^ D175 D176 +error(0.0002827200622917192853) D173 D174 ^ D175 D184 +error(0.01071681271374672756) D173 D174 ^ D176 +error(0.002689376411773483633) D173 D174 ^ D176 D184 +error(0.001802538463770141227) D173 D174 ^ D184 +error(4.045483039878490701e-05) D173 D174 ^ D184 ^ D172 +error(0.01568589133027759736) D173 D178 +error(0.01169068635140842367) D173 D178 ^ D175 D176 +error(0.03140897183913322899) D173 D181 +error(0.002019920062412751318) D173 D181 ^ D183 D184 +error(0.001834189692617856256) D173 D181 ^ D184 +error(0.003283249611206463282) D173 D185 +error(0.002217039097925698875) D173 D185 ^ D175 D183 +error(0.0004311616500379738615) D173 D185 ^ D175 D184 +error(0.0003601196358267589183) D173 D185 ^ D183 D184 +error(0.005495111026433003795) D173 D186 +error(0.001924571388590668678) D173 D186 ^ D175 D176 +error(0.001919238098036685951) D173 D186 ^ D175 D183 +error(0.001542925559449527615) D173 D186 ^ D175 D184 +error(0.0004065625308521262694) D173 D186 ^ D176 D184 +error(0.001517534904390731645) D173 D186 ^ D183 D184 +error(0.01000000000000000021) D173 L0 +error(0.000630023031437223005) D173 L0 ^ D183 +error(0.003559447081430625569) D175 D183 ^ D173 L0 +error(0.009592028122265101528) D174 +error(0.002359226002129251928) D174 D181 +error(0.0004700885901282171966) D174 D181 ^ D172 +error(0.002842631538867582044) D174 D181 ^ D184 +error(0.03323098142033485691) D174 D182 +error(0.003694859541453752051) D174 D182 ^ D184 +error(0.001887308115760311577) D174 D186 +error(7.667254054394448501e-05) D174 D186 ^ D175 D176 +error(0.0001684128039816316761) D174 D186 ^ D175 D184 +error(0.00155935512012112215) D174 D186 ^ D176 D184 +error(0.01465668303041333873) D174 ^ D176 +error(0.002208325456735622545) D174 ^ D184 ^ D176 +error(0.01000000000000000021) D175 +error(0.01641885170447205181) D175 D176 +error(6.757040603604669575e-05) D175 D176 ^ D165 L0 +error(0.000691539702847943495) D175 D176 ^ D177 D178 +error(0.001965417218638295088) D175 D176 ^ D178 +error(0.002025462288331955976) D175 D176 ^ D178 D186 +error(0.002676727229798968322) D175 D176 ^ D186 +error(0.04979648365038458202) D175 D183 +error(0.004075575823084270563) D175 D183 ^ D185 D186 +error(0.003228899945508421909) D175 D184 +error(0.0006267629478556474868) D175 D184 ^ D185 D186 +error(0.001819731574192852766) D175 D187 +error(0.001044374947872651286) D175 D187 ^ D178 +error(0.001721977742605806461) D175 D187 ^ D178 D186 +error(0.0005319396409102149182) D175 D187 ^ D186 +error(0.01221051608950192956) D175 ^ D177 L0 +error(0.004281356988861994943) D177 D185 ^ D175 +error(0.01352570247240133215) D176 +error(0.01916140106904455978) D176 D179 +error(0.02134285127067836463) D176 D179 ^ D178 +error(0.01754222313276320583) D176 D184 +error(0.003925335771774137936) D176 D184 ^ D186 +error(0.00829638757819277893) D176 D187 +error(0.006189697411378116548) D176 D187 ^ D178 +error(0.008227765587022699278) D176 D187 ^ D186 +error(0.001565359356948206127) D176 D187 ^ D186 ^ D178 +error(0.0139259571500968439) D177 D178 +error(0.003653395121599596097) D177 D178 ^ D167 +error(0.01746546765882601299) D177 D178 ^ D175 +error(0.0006115023900453514733) D177 D178 ^ D179 +error(0.0002228130597355455398) D177 D178 ^ D179 ^ D167 +error(0.0215519806561217768) D177 D185 +error(0.00578341455456686613) D177 L0 +error(0.000407844684521510418) D177 L0 ^ D165 L0 ^ D167 +error(0.0003059078627119102755) D177 L0 ^ D165 L0 ^ D175 +error(0.000912866688785244902) D177 L0 ^ D175 ^ D167 +error(0.01809852353947335665) D178 +error(0.004283187852576511058) D178 D185 +error(0.003386911228148268768) D178 D185 ^ D175 +error(0.000374805418012281121) D178 D185 ^ D187 +error(0.000378901796486506696) D178 D185 ^ D187 ^ D175 +error(0.02129317632278137154) D178 D186 +error(0.001098988525176137782) D178 D186 ^ D175 +error(0.003795925922665927942) D178 D186 ^ D187 +error(0.000339845682907893615) D178 ^ D166 ^ D168 +error(0.0001011712955095126772) D178 ^ D166 ^ D176 +error(0.0004136195716464172124) D178 ^ D168 +error(0.009786019691043161897) D178 ^ D179 +error(0.00105555876697080984) D178 ^ D187 +error(0.005384160809988575158) D179 D187 ^ D178 +error(0.005000000000000000104) D179 +error(0.02457097167531402046) D179 D187 +error(0.005245339025758253074) D180 +error(0.01351831881670467229) D180 D183 +error(0.01232203752053264746) D180 D183 ^ D181 L0 +error(0.02137993200743813771) D180 D188 +error(0.004131755026116961001) D180 D188 ^ D189 L0 +error(0.002903203036019879387) D180 D191 +error(0.003328581296933910347) D180 D191 ^ D181 L0 +error(0.002153497648560191106) D180 D191 ^ D189 L0 +error(0.00132794561778247131) D180 D191 ^ D189 L0 ^ D181 L0 +error(0.002297625395399578718) D180 D192 +error(0.001564841148743489939) D180 D192 ^ D181 D189 +error(0.0003724936510519168045) D180 D192 ^ D181 L0 +error(0.0003891805678224126625) D180 D192 ^ D189 L0 +error(0.005021350549187082041) D180 ^ D181 L0 +error(0.002754177369565753448) D180 ^ D189 L0 +error(0.003687446986055130382) D181 D189 ^ D180 +error(0.008302277937618965375) D181 D182 +error(0.0004930814379600387092) D181 D182 ^ D180 +error(0.0002344286990215338929) D181 D182 ^ D183 D184 +error(0.0002827200622917192853) D181 D182 ^ D183 D192 +error(0.01071681271374672756) D181 D182 ^ D184 +error(0.002689376411773483633) D181 D182 ^ D184 D192 +error(0.001802538463770141227) D181 D182 ^ D192 +error(4.045483039878490701e-05) D181 D182 ^ D192 ^ D180 +error(0.01568589133027759736) D181 D186 +error(0.01169068635140842367) D181 D186 ^ D183 D184 +error(0.03140897183913322899) D181 D189 +error(0.002019920062412751318) D181 D189 ^ D191 D192 +error(0.001834189692617856256) D181 D189 ^ D192 +error(0.003283249611206463282) D181 D193 +error(0.002217039097925698875) D181 D193 ^ D183 D191 +error(0.0004311616500379738615) D181 D193 ^ D183 D192 +error(0.0003601196358267589183) D181 D193 ^ D191 D192 +error(0.005495111026433003795) D181 D194 +error(0.001924571388590668678) D181 D194 ^ D183 D184 +error(0.001919238098036685951) D181 D194 ^ D183 D191 +error(0.001542925559449527615) D181 D194 ^ D183 D192 +error(0.0004065625308521262694) D181 D194 ^ D184 D192 +error(0.001517534904390731645) D181 D194 ^ D191 D192 +error(0.01000000000000000021) D181 L0 +error(0.000630023031437223005) D181 L0 ^ D191 +error(0.003559447081430625569) D183 D191 ^ D181 L0 +error(0.009592028122265101528) D182 +error(0.002359226002129251928) D182 D189 +error(0.0004700885901282171966) D182 D189 ^ D180 +error(0.002842631538867582044) D182 D189 ^ D192 +error(0.03323098142033485691) D182 D190 +error(0.003694859541453752051) D182 D190 ^ D192 +error(0.001887308115760311577) D182 D194 +error(7.667254054394448501e-05) D182 D194 ^ D183 D184 +error(0.0001684128039816316761) D182 D194 ^ D183 D192 +error(0.00155935512012112215) D182 D194 ^ D184 D192 +error(0.01465668303041333873) D182 ^ D184 +error(0.002208325456735622545) D182 ^ D192 ^ D184 +error(0.01000000000000000021) D183 +error(0.01641885170447205181) D183 D184 +error(6.757040603604669575e-05) D183 D184 ^ D173 L0 +error(0.000691539702847943495) D183 D184 ^ D185 D186 +error(0.001965417218638295088) D183 D184 ^ D186 +error(0.002025462288331955976) D183 D184 ^ D186 D194 +error(0.002676727229798968322) D183 D184 ^ D194 +error(0.04979648365038458202) D183 D191 +error(0.004075575823084270563) D183 D191 ^ D193 D194 +error(0.003228899945508421909) D183 D192 +error(0.0006267629478556474868) D183 D192 ^ D193 D194 +error(0.001819731574192852766) D183 D195 +error(0.001044374947872651286) D183 D195 ^ D186 +error(0.001721977742605806461) D183 D195 ^ D186 D194 +error(0.0005319396409102149182) D183 D195 ^ D194 +error(0.01221051608950192956) D183 ^ D185 L0 +error(0.004281356988861994943) D185 D193 ^ D183 +error(0.01352570247240133215) D184 +error(0.01916140106904455978) D184 D187 +error(0.02134285127067836463) D184 D187 ^ D186 +error(0.01754222313276320583) D184 D192 +error(0.003925335771774137936) D184 D192 ^ D194 +error(0.00829638757819277893) D184 D195 +error(0.006189697411378116548) D184 D195 ^ D186 +error(0.008227765587022699278) D184 D195 ^ D194 +error(0.001565359356948206127) D184 D195 ^ D194 ^ D186 +error(0.0139259571500968439) D185 D186 +error(0.003653395121599596097) D185 D186 ^ D175 +error(0.01746546765882601299) D185 D186 ^ D183 +error(0.0006115023900453514733) D185 D186 ^ D187 +error(0.0002228130597355455398) D185 D186 ^ D187 ^ D175 +error(0.0215519806561217768) D185 D193 +error(0.00578341455456686613) D185 L0 +error(0.000407844684521510418) D185 L0 ^ D173 L0 ^ D175 +error(0.0003059078627119102755) D185 L0 ^ D173 L0 ^ D183 +error(0.000912866688785244902) D185 L0 ^ D183 ^ D175 +error(0.01809852353947335665) D186 +error(0.004283187852576511058) D186 D193 +error(0.003386911228148268768) D186 D193 ^ D183 +error(0.000374805418012281121) D186 D193 ^ D195 +error(0.000378901796486506696) D186 D193 ^ D195 ^ D183 +error(0.02129317632278137154) D186 D194 +error(0.001098988525176137782) D186 D194 ^ D183 +error(0.003795925922665927942) D186 D194 ^ D195 +error(0.000339845682907893615) D186 ^ D174 ^ D176 +error(0.0001011712955095126772) D186 ^ D174 ^ D184 +error(0.0004136195716464172124) D186 ^ D176 +error(0.009786019691043161897) D186 ^ D187 +error(0.00105555876697080984) D186 ^ D195 +error(0.005384160809988575158) D187 D195 ^ D186 +error(0.005000000000000000104) D187 +error(0.02457097167531402046) D187 D195 +error(0.03076705330413553527) D188 +error(0.01350286199313231912) D188 D191 +error(0.01387633867869352174) D188 D191 ^ D189 L0 +error(0.008634416380823082063) D188 ^ D189 L0 +error(0.01059883175780113734) D188 ^ D196 L0 +error(0.008371461858215517929) D189 D196 ^ D188 +error(0.009723116694070598268) D189 D190 +error(0.0003813086464531355584) D189 D190 ^ D188 +error(0.01375932017612622321) D189 D190 ^ D192 +error(0.001400300978057224775) D189 D190 ^ D192 ^ D191 +error(0.01415880562353630592) D189 D194 +error(0.01025739712209398739) D189 D194 ^ D191 D192 +error(0.03523601333569909705) D189 D196 +error(0.002195637195425107369) D189 D197 +error(0.003618985357942763013) D189 D197 ^ D191 +error(0.009005982332949438035) D189 D199 +error(0.003170443417815831631) D189 D199 ^ D191 +error(0.001948454671778039951) D189 D199 ^ D191 D192 +error(0.01000000000000000021) D189 L0 +error(0.007881746344426288076) D190 +error(0.006215936701886276561) D190 D196 +error(0.03887711960155515456) D190 D198 +error(0.004170348883505139645) D190 D199 +error(3.512898980572207148e-05) D190 D199 ^ D192 +error(0.0002847770434734381751) D190 D199 ^ D192 ^ D191 +error(0.01639315538056388896) D190 ^ D192 +error(0.05659080435126307568) D191 +error(0.01658290071091452628) D191 D192 +error(6.757040603604669575e-05) D191 D192 ^ D181 L0 +error(0.002127712181574389991) D191 D192 ^ D193 D194 +error(0.001698452553009181885) D191 D192 ^ D194 D199 +error(0.004132507117455168529) D191 ^ D189 L0 +error(0.003540498720207851686) D191 ^ D192 ^ D194 +error(0.003376247971323504023) D191 ^ D192 ^ D199 +error(0.009502852206888658115) D191 ^ D193 L0 +error(0.003946775283768661803) D191 ^ D194 +error(0.0006902527353105070672) D191 ^ D197 L0 +error(0.004834085214031281531) D193 D197 ^ D191 +error(0.002402622698301141828) D191 ^ D199 +error(0.002417403872428190281) D194 D199 ^ D191 +error(0.04053793436641814352) D192 +error(0.01979290995120809235) D192 D195 +error(0.02237034798877246197) D192 D195 ^ D194 +error(0.006678013354096725904) D192 ^ D194 +error(0.009966127153982829931) D192 ^ D199 +error(0.001314657564490858679) D192 ^ D199 ^ D194 +error(0.01712042181697446055) D193 D194 +error(0.003653395121599596097) D193 D194 ^ D183 +error(0.01657989362788471477) D193 D194 ^ D191 +error(0.0004965725644006720608) D193 D194 ^ D195 +error(0.0002228130597355455398) D193 D194 ^ D195 ^ D183 +error(0.0216957898831740166) D193 D197 +error(0.008821718125085043979) D193 L0 +error(0.000407844684521510418) D193 L0 ^ D181 L0 ^ D183 +error(0.0003059078627119102755) D193 L0 ^ D181 L0 ^ D191 +error(0.000912866688785244902) D193 L0 ^ D191 ^ D183 +error(0.01792901222165629513) D194 +error(0.00600801631955461251) D194 D197 +error(0.003446041455689401092) D194 D197 ^ D191 +error(0.02432389343233164539) D194 D199 +error(0.000339845682907893615) D194 ^ D182 ^ D184 +error(0.0001011712955095126772) D194 ^ D182 ^ D192 +error(0.0004136195716464172124) D194 ^ D184 +error(0.01372324018742982453) D194 ^ D195 +error(0.02825126571564326103) D195 +error(0.01809673875153883227) D196 D198 +error(0.01456269717541336384) D196 D199 +error(0.01835576157359710206) D196 L0 +error(0.01628928399221030512) D197 D199 +error(0.006800715367139180748) D197 D199 ^ D191 +error(0.01895710035336083468) D197 L0 +error(0.01394274627855246647) D198 +error(0.02986152029088780593) D199 +detector(4, 3, 0) D0 +detector(6, 1, 0) D1 +detector(4, 5, 0) D2 +detector(6, 3, 0) D3 +detector(3, 2, 1) D4 +detector(4, 3, 1) D5 +detector(4, 5, 1) D6 +detector(5, 2, 1) D7 +detector(5, 4, 1) D8 +detector(6, 1, 1) D9 +detector(6, 3, 1) D10 +detector(7, 4, 1) D11 +detector(3, 2, 2) D12 +detector(4, 3, 2) D13 +detector(4, 5, 2) D14 +detector(5, 2, 2) D15 +detector(5, 4, 2) D16 +detector(6, 1, 2) D17 +detector(6, 3, 2) D18 +detector(7, 4, 2) D19 +detector(3, 2, 3) D20 +detector(4, 3, 3) D21 +detector(4, 5, 3) D22 +detector(5, 2, 3) D23 +detector(5, 4, 3) D24 +detector(6, 1, 3) D25 +detector(6, 3, 3) D26 +detector(7, 4, 3) D27 +detector(3, 2, 4) D28 +detector(4, 3, 4) D29 +detector(4, 5, 4) D30 +detector(5, 2, 4) D31 +detector(5, 4, 4) D32 +detector(6, 1, 4) D33 +detector(6, 3, 4) D34 +detector(7, 4, 4) D35 +detector(3, 2, 5) D36 +detector(4, 3, 5) D37 +detector(4, 5, 5) D38 +detector(5, 2, 5) D39 +detector(5, 4, 5) D40 +detector(6, 1, 5) D41 +detector(6, 3, 5) D42 +detector(7, 4, 5) D43 +detector(3, 2, 6) D44 +detector(4, 3, 6) D45 +detector(4, 5, 6) D46 +detector(5, 2, 6) D47 +detector(5, 4, 6) D48 +detector(6, 1, 6) D49 +detector(6, 3, 6) D50 +detector(7, 4, 6) D51 +detector(3, 2, 7) D52 +detector(4, 3, 7) D53 +detector(4, 5, 7) D54 +detector(5, 2, 7) D55 +detector(5, 4, 7) D56 +detector(6, 1, 7) D57 +detector(6, 3, 7) D58 +detector(7, 4, 7) D59 +detector(3, 2, 8) D60 +detector(4, 3, 8) D61 +detector(4, 5, 8) D62 +detector(5, 2, 8) D63 +detector(5, 4, 8) D64 +detector(6, 1, 8) D65 +detector(6, 3, 8) D66 +detector(7, 4, 8) D67 +detector(3, 2, 9) D68 +detector(4, 3, 9) D69 +detector(4, 5, 9) D70 +detector(5, 2, 9) D71 +detector(5, 4, 9) D72 +detector(6, 1, 9) D73 +detector(6, 3, 9) D74 +detector(7, 4, 9) D75 +detector(3, 2, 10) D76 +detector(4, 3, 10) D77 +detector(4, 5, 10) D78 +detector(5, 2, 10) D79 +detector(5, 4, 10) D80 +detector(6, 1, 10) D81 +detector(6, 3, 10) D82 +detector(7, 4, 10) D83 +detector(3, 2, 11) D84 +detector(4, 3, 11) D85 +detector(4, 5, 11) D86 +detector(5, 2, 11) D87 +detector(5, 4, 11) D88 +detector(6, 1, 11) D89 +detector(6, 3, 11) D90 +detector(7, 4, 11) D91 +detector(3, 2, 12) D92 +detector(4, 3, 12) D93 +detector(4, 5, 12) D94 +detector(5, 2, 12) D95 +detector(5, 4, 12) D96 +detector(6, 1, 12) D97 +detector(6, 3, 12) D98 +detector(7, 4, 12) D99 +detector(3, 2, 13) D100 +detector(4, 3, 13) D101 +detector(4, 5, 13) D102 +detector(5, 2, 13) D103 +detector(5, 4, 13) D104 +detector(6, 1, 13) D105 +detector(6, 3, 13) D106 +detector(7, 4, 13) D107 +detector(3, 2, 14) D108 +detector(4, 3, 14) D109 +detector(4, 5, 14) D110 +detector(5, 2, 14) D111 +detector(5, 4, 14) D112 +detector(6, 1, 14) D113 +detector(6, 3, 14) D114 +detector(7, 4, 14) D115 +detector(3, 2, 15) D116 +detector(4, 3, 15) D117 +detector(4, 5, 15) D118 +detector(5, 2, 15) D119 +detector(5, 4, 15) D120 +detector(6, 1, 15) D121 +detector(6, 3, 15) D122 +detector(7, 4, 15) D123 +detector(3, 2, 16) D124 +detector(4, 3, 16) D125 +detector(4, 5, 16) D126 +detector(5, 2, 16) D127 +detector(5, 4, 16) D128 +detector(6, 1, 16) D129 +detector(6, 3, 16) D130 +detector(7, 4, 16) D131 +detector(3, 2, 17) D132 +detector(4, 3, 17) D133 +detector(4, 5, 17) D134 +detector(5, 2, 17) D135 +detector(5, 4, 17) D136 +detector(6, 1, 17) D137 +detector(6, 3, 17) D138 +detector(7, 4, 17) D139 +detector(3, 2, 18) D140 +detector(4, 3, 18) D141 +detector(4, 5, 18) D142 +detector(5, 2, 18) D143 +detector(5, 4, 18) D144 +detector(6, 1, 18) D145 +detector(6, 3, 18) D146 +detector(7, 4, 18) D147 +detector(3, 2, 19) D148 +detector(4, 3, 19) D149 +detector(4, 5, 19) D150 +detector(5, 2, 19) D151 +detector(5, 4, 19) D152 +detector(6, 1, 19) D153 +detector(6, 3, 19) D154 +detector(7, 4, 19) D155 +detector(3, 2, 20) D156 +detector(4, 3, 20) D157 +detector(4, 5, 20) D158 +detector(5, 2, 20) D159 +detector(5, 4, 20) D160 +detector(6, 1, 20) D161 +detector(6, 3, 20) D162 +detector(7, 4, 20) D163 +detector(3, 2, 21) D164 +detector(4, 3, 21) D165 +detector(4, 5, 21) D166 +detector(5, 2, 21) D167 +detector(5, 4, 21) D168 +detector(6, 1, 21) D169 +detector(6, 3, 21) D170 +detector(7, 4, 21) D171 +detector(3, 2, 22) D172 +detector(4, 3, 22) D173 +detector(4, 5, 22) D174 +detector(5, 2, 22) D175 +detector(5, 4, 22) D176 +detector(6, 1, 22) D177 +detector(6, 3, 22) D178 +detector(7, 4, 22) D179 +detector(3, 2, 23) D180 +detector(4, 3, 23) D181 +detector(4, 5, 23) D182 +detector(5, 2, 23) D183 +detector(5, 4, 23) D184 +detector(6, 1, 23) D185 +detector(6, 3, 23) D186 +detector(7, 4, 23) D187 +detector(3, 2, 24) D188 +detector(4, 3, 24) D189 +detector(4, 5, 24) D190 +detector(5, 2, 24) D191 +detector(5, 4, 24) D192 +detector(6, 1, 24) D193 +detector(6, 3, 24) D194 +detector(7, 4, 24) D195 +detector(4, 3, 25) D196 +detector(6, 1, 25) D197 +detector(4, 5, 25) D198 +detector(6, 3, 25) D199 diff --git a/shared/package-files/d1/d121f02fccfb396a6b51507770b045025bf49b4fef45febd8a287ed64461618d/blob b/shared/package-files/d1/d121f02fccfb396a6b51507770b045025bf49b4fef45febd8a287ed64461618d/blob new file mode 100644 index 0000000000000000000000000000000000000000..ea83e6f86bb0de5403ef5cf30fbcec54ae5ce01a --- /dev/null +++ b/shared/package-files/d1/d121f02fccfb396a6b51507770b045025bf49b4fef45febd8a287ed64461618d/blob @@ -0,0 +1,410 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Generic, Literal, Protocol + +from narwhals._compliant.any_namespace import ( + CatNamespace, + DateTimeNamespace, + ListNamespace, + StringNamespace, + StructNamespace, +) +from narwhals._compliant.column import CompliantColumn +from narwhals._compliant.typing import ( + CompliantSeriesT_co, + EagerDataFrameAny, + EagerSeriesT, + EagerSeriesT_co, + NativeSeriesT, + NativeSeriesT_co, +) +from narwhals._translate import FromIterable, FromNative, NumpyConvertible, ToNarwhals +from narwhals._typing_compat import TypeVar, assert_never +from narwhals._utils import ( + _StoresCompliant, + _StoresNative, + is_compliant_series, + is_sized_multi_index_selector, + unstable, +) + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Sequence + from types import ModuleType + + import pandas as pd + import polars as pl + import pyarrow as pa + from typing_extensions import NotRequired, Self, TypedDict + + from narwhals._compliant.dataframe import CompliantDataFrame + from narwhals._compliant.namespace import EagerNamespace + from narwhals._utils import Implementation, Version, _LimitedContext + from narwhals.dtypes import DType + from narwhals.series import Series + from narwhals.typing import ( + Into1DArray, + IntoDType, + MultiIndexSelector, + PythonLiteral, + RollingInterpolationMethod, + SizedMultiIndexSelector, + _1DArray, + _SliceIndex, + ) + + class HistData(TypedDict, Generic[NativeSeriesT, "_CountsT_co"]): + breakpoint: NotRequired[list[float] | _1DArray | list[Any]] + count: NativeSeriesT | _1DArray | _CountsT_co | list[Any] + + +_CountsT_co = TypeVar("_CountsT_co", bound="Iterable[Any]", covariant=True) + +__all__ = [ + "CompliantSeries", + "EagerSeries", + "EagerSeriesCatNamespace", + "EagerSeriesDateTimeNamespace", + "EagerSeriesHist", + "EagerSeriesListNamespace", + "EagerSeriesNamespace", + "EagerSeriesStringNamespace", + "EagerSeriesStructNamespace", +] + + +class CompliantSeries( + NumpyConvertible["_1DArray", "Into1DArray"], + FromIterable, + FromNative[NativeSeriesT], + ToNarwhals["Series[NativeSeriesT]"], + CompliantColumn, + Protocol[NativeSeriesT], +): + # NOTE: `narwhals` + _implementation: Implementation + + @property + def native(self) -> NativeSeriesT: ... + def __narwhals_series__(self) -> Self: + return self + + def __native_namespace__(self) -> ModuleType: ... + @classmethod + def from_native(cls, data: NativeSeriesT, /, *, context: _LimitedContext) -> Self: ... + def to_narwhals(self) -> Series[NativeSeriesT]: + return self._version.series(self, level="full") + + def _with_native(self, series: Any) -> Self: ... + def _with_version(self, version: Version) -> Self: ... + + # NOTE: `polars` + @property + def dtype(self) -> DType: ... + @property + def name(self) -> str: ... + def __array__(self, dtype: Any, *, copy: bool | None) -> _1DArray: ... + def __contains__(self, other: Any) -> bool: ... + def __getitem__(self, item: MultiIndexSelector[Self]) -> Any: ... + def __iter__(self) -> Iterator[Any]: ... + def __len__(self) -> int: + return len(self.native) + + @classmethod + def from_numpy(cls, data: Into1DArray, /, *, context: _LimitedContext) -> Self: ... + @classmethod + def from_iterable( + cls, + data: Iterable[Any], + /, + *, + context: _LimitedContext, + name: str = "", + dtype: IntoDType | None = None, + ) -> Self: ... + def __radd__(self, other: Any) -> Self: ... + def __rand__(self, other: Any) -> Self: ... + def __rmul__(self, other: Any) -> Self: ... + def __ror__(self, other: Any) -> Self: ... + def all(self) -> bool: ... + def any(self) -> bool: ... + def any_value(self, *, ignore_nulls: bool) -> PythonLiteral: ... + def arg_max(self) -> int: ... + def arg_min(self) -> int: ... + def arg_true(self) -> Self: ... + def count(self) -> int: ... + def filter(self, predicate: Any) -> Self: ... + def first(self) -> PythonLiteral: ... + def last(self) -> PythonLiteral: ... + def gather_every(self, n: int, offset: int) -> Self: ... + def head(self, n: int) -> Self: ... + def is_empty(self) -> bool: + return self.len() == 0 + + def is_sorted(self, *, descending: bool) -> bool: ... + def item(self, index: int | None) -> Any: ... + def kurtosis(self) -> float | None: ... + def len(self) -> int: ... + def max(self) -> Any: ... + def mean(self) -> float: ... + def median(self) -> float: ... + def min(self) -> Any: ... + def n_unique(self) -> int: ... + def null_count(self) -> int: ... + def quantile( + self, quantile: float, interpolation: RollingInterpolationMethod + ) -> float: ... + def sample(self, n: int, *, with_replacement: bool, seed: int | None) -> Self: ... + def scatter(self, indices: Self, values: Self) -> Self: ... + def shift(self, n: int) -> Self: ... + def skew(self) -> float | None: ... + def sort(self, *, descending: bool, nulls_last: bool) -> Self: ... + def std(self, *, ddof: int) -> float: ... + def sum(self) -> float: ... + def tail(self, n: int) -> Self: ... + def to_arrow(self) -> pa.Array[Any]: ... + def to_dummies( + self, *, separator: str, drop_first: bool + ) -> CompliantDataFrame[Self, Any, Any, Any]: ... + def to_frame(self) -> CompliantDataFrame[Self, Any, Any, Any]: ... + def to_list(self) -> list[Any]: ... + def to_pandas(self) -> pd.Series[Any]: ... + def to_polars(self) -> pl.Series: ... + def unique(self, *, maintain_order: bool = False) -> Self: ... + def value_counts( + self, *, sort: bool, parallel: bool, name: str | None, normalize: bool + ) -> CompliantDataFrame[Self, Any, Any, Any]: ... + def var(self, *, ddof: int) -> float: ... + def zip_with(self, mask: Any, other: Any) -> Self: ... + + # NOTE: *Technically* `polars` + @unstable + def hist_from_bins( + self, bins: list[float], *, include_breakpoint: bool + ) -> CompliantDataFrame[Self, Any, Any, Any]: + """`Series.hist(bins=..., bin_count=None)`.""" + ... + + @unstable + def hist_from_bin_count( + self, bin_count: int, *, include_breakpoint: bool + ) -> CompliantDataFrame[Self, Any, Any, Any]: + """`Series.hist(bins=None, bin_count=...)`.""" + ... + + +class EagerSeries(CompliantSeries[NativeSeriesT], Protocol[NativeSeriesT]): + _native_series: Any + _implementation: Implementation + _version: Version + _broadcast: bool + + @property + def _backend_version(self) -> tuple[int, ...]: + return self._implementation._backend_version() + + @classmethod + def _align_full_broadcast(cls, *series: Self) -> Sequence[Self]: + """Ensure all of `series` have the same length (and index if `pandas`). + + Scalars get broadcasted to the full length of the longest Series. + + This is useful when you need to construct a full Series anyway, such as: + + DataFrame.select(...) + + It should not be used in binary operations, such as: + + nw.col("a") - nw.col("a").mean() + + because then it's more efficient to extract the right-hand-side's single element as a scalar. + """ + ... + + def _from_scalar(self, value: Any) -> Self: + return self.from_iterable([value], name=self.name, context=self) + + def _with_native( + self, series: NativeSeriesT, *, preserve_broadcast: bool = False + ) -> Self: + """Return a new `CompliantSeries`, wrapping the native `series`. + + In cases when operations are known to not affect whether a result should + be broadcast, we can pass `preserve_broadcast=True`. + Set this with care - it should only be set for unary expressions which don't + change length or order, such as `.alias` or `.fill_null`. If in doubt, don't + set it, you probably don't need it. + """ + ... + + def __narwhals_namespace__( + self, + ) -> EagerNamespace[Any, Self, Any, Any, NativeSeriesT]: ... + + def _gather(self, rows: SizedMultiIndexSelector[NativeSeriesT]) -> Self: ... + def _gather_slice(self, rows: _SliceIndex | range) -> Self: ... + def __getitem__(self, item: MultiIndexSelector[Self]) -> Self: + if isinstance(item, (slice, range)): + return self._gather_slice(item) + if is_compliant_series(item): + return self._gather(item.native) + elif is_sized_multi_index_selector(item): # noqa: RET505 + return self._gather(item) + assert_never(item) + + @property + def str(self) -> EagerSeriesStringNamespace[Self, NativeSeriesT]: ... + @property + def dt(self) -> EagerSeriesDateTimeNamespace[Self, NativeSeriesT]: ... + @property + def cat(self) -> EagerSeriesCatNamespace[Self, NativeSeriesT]: ... + @property + def list(self) -> EagerSeriesListNamespace[Self, NativeSeriesT]: ... + @property + def struct(self) -> EagerSeriesStructNamespace[Self, NativeSeriesT]: ... + + +class _SeriesNamespace( # type: ignore[misc] + _StoresCompliant[CompliantSeriesT_co], + _StoresNative[NativeSeriesT_co], + Protocol[CompliantSeriesT_co, NativeSeriesT_co], +): + _compliant_series: CompliantSeriesT_co + + @property + def compliant(self) -> CompliantSeriesT_co: + return self._compliant_series + + @property + def implementation(self) -> Implementation: + return self.compliant._implementation + + @property + def backend_version(self) -> tuple[int, ...]: + return self.implementation._backend_version() + + @property + def version(self) -> Version: + return self.compliant._version + + @property + def native(self) -> NativeSeriesT_co: + return self._compliant_series.native # type: ignore[no-any-return] + + def with_native(self, series: Any, /) -> CompliantSeriesT_co: + return self.compliant._with_native(series) + + +class EagerSeriesNamespace( + _SeriesNamespace[EagerSeriesT_co, NativeSeriesT_co], + Generic[EagerSeriesT_co, NativeSeriesT_co], +): + _compliant_series: EagerSeriesT_co + + def __init__(self, series: EagerSeriesT_co, /) -> None: + self._compliant_series = series + + +class EagerSeriesCatNamespace( # type: ignore[misc] + _SeriesNamespace[EagerSeriesT_co, NativeSeriesT_co], + CatNamespace[EagerSeriesT_co], + Protocol[EagerSeriesT_co, NativeSeriesT_co], +): ... + + +class EagerSeriesDateTimeNamespace( # type: ignore[misc] + _SeriesNamespace[EagerSeriesT_co, NativeSeriesT_co], + DateTimeNamespace[EagerSeriesT_co], + Protocol[EagerSeriesT_co, NativeSeriesT_co], +): ... + + +class EagerSeriesListNamespace( # pyright: ignore[reportInvalidTypeVarUse] + _SeriesNamespace[EagerSeriesT, NativeSeriesT_co], + ListNamespace[EagerSeriesT], + Protocol[EagerSeriesT, NativeSeriesT_co], +): ... + + +class EagerSeriesStringNamespace( + _SeriesNamespace[EagerSeriesT, NativeSeriesT_co], + StringNamespace[EagerSeriesT], + Protocol[EagerSeriesT, NativeSeriesT_co], +): ... + + +class EagerSeriesStructNamespace( # type: ignore[misc] + _SeriesNamespace[EagerSeriesT_co, NativeSeriesT_co], + StructNamespace[EagerSeriesT_co], + Protocol[EagerSeriesT_co, NativeSeriesT_co], +): ... + + +# mypy says: `Covariant type variable "_CountsT_co" used in protocol where invariant one is expected` +class EagerSeriesHist(Protocol[NativeSeriesT, _CountsT_co]): # type: ignore[misc] + _series: EagerSeries[NativeSeriesT] + _breakpoint: bool + _data: HistData[NativeSeriesT, _CountsT_co] + + @property + def native(self) -> NativeSeriesT: + return self._series.native + + @classmethod + def from_series( + cls, series: EagerSeries[NativeSeriesT], *, include_breakpoint: bool + ) -> Self: + obj = cls.__new__(cls) + obj._series = series + obj._breakpoint = include_breakpoint + return obj + + def to_frame(self) -> EagerDataFrameAny: ... + def _linear_space( # NOTE: Roughly `pl.linear_space` + self, + start: float, + end: float, + num_samples: int, + *, + closed: Literal["both", "none"] = "both", + ) -> _1DArray: ... + + # NOTE: *Could* be handled at narwhals-level + def is_empty_series(self) -> bool: ... + + # NOTE: **Should** be handled at narwhals-level + def data_empty(self) -> HistData[NativeSeriesT, _CountsT_co]: + return {"breakpoint": [], "count": []} if self._breakpoint else {"count": []} + + # NOTE: *Could* be handled at narwhals-level, **iff** we add `nw.repeat`, `nw.linear_space` + # See https://github.com/narwhals-dev/narwhals/pull/2839#discussion_r2215630696 + def series_empty( + self, arg: int | list[float], / + ) -> HistData[NativeSeriesT, _CountsT_co]: ... + + def with_bins(self, bins: list[float], /) -> Self: + if len(bins) <= 1: + self._data = self.data_empty() + elif self.is_empty_series(): + self._data = self.series_empty(bins) + else: + self._data = self._calculate_hist(bins) + return self + + def with_bin_count(self, bin_count: int, /) -> Self: + if bin_count == 0: + self._data = self.data_empty() + elif self.is_empty_series(): + self._data = self.series_empty(bin_count) + else: + self._data = self._calculate_hist(self._calculate_bins(bin_count)) + return self + + def _calculate_breakpoint(self, arg: int | list[float], /) -> list[float] | _1DArray: + bins = self._linear_space(0, 1, arg + 1) if isinstance(arg, int) else arg + return bins[1:] + + def _calculate_bins(self, bin_count: int) -> _1DArray: ... + def _calculate_hist( + self, bins: list[float] | _1DArray + ) -> HistData[NativeSeriesT, _CountsT_co]: ... diff --git a/shared/package-files/d1/d123e0b4c2614f680808b58cca0c140ba187494b2c8bcf8c604c7eb739c70882/blob b/shared/package-files/d1/d123e0b4c2614f680808b58cca0c140ba187494b2c8bcf8c604c7eb739c70882/blob new file mode 100644 index 0000000000000000000000000000000000000000..badb1dd32bff8ff90f4091728d472fc118a17f7f --- /dev/null +++ b/shared/package-files/d1/d123e0b4c2614f680808b58cca0c140ba187494b2c8bcf8c604c7eb739c70882/blob @@ -0,0 +1,28 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset zh_HK DAYS_OF_WEEK_ABBREV [list \ + "\u65e5"\ + "\u4e00"\ + "\u4e8c"\ + "\u4e09"\ + "\u56db"\ + "\u4e94"\ + "\u516d"] + ::msgcat::mcset zh_HK MONTHS_ABBREV [list \ + "1\u6708"\ + "2\u6708"\ + "3\u6708"\ + "4\u6708"\ + "5\u6708"\ + "6\u6708"\ + "7\u6708"\ + "8\u6708"\ + "9\u6708"\ + "10\u6708"\ + "11\u6708"\ + "12\u6708"\ + ""] + ::msgcat::mcset zh_HK DATE_FORMAT "%Y\u5e74%m\u6708%e\u65e5" + ::msgcat::mcset zh_HK TIME_FORMAT_12 "%P%I:%M:%S" + ::msgcat::mcset zh_HK DATE_TIME_FORMAT "%Y\u5e74%m\u6708%e\u65e5 %P%I:%M:%S %z" +} diff --git a/shared/package-files/d1/d12457044da126028937f45fe199f4d282970bf4e46b779f3d6338ef383a0686/blob b/shared/package-files/d1/d12457044da126028937f45fe199f4d282970bf4e46b779f3d6338ef383a0686/blob new file mode 100644 index 0000000000000000000000000000000000000000..86d7004abad4e9fecb4922454759c827b3543352 --- /dev/null +++ b/shared/package-files/d1/d12457044da126028937f45fe199f4d282970bf4e46b779f3d6338ef383a0686/blob @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +import os +import sys +import tempfile + + +def run_command(cmd): + print('Running %r:' % (cmd)) + os.system(cmd) + print('------') + + +def run(): + _path = os.getcwd() + os.chdir(tempfile.gettempdir()) + print('------') + print('os.name=%r' % (os.name)) + print('------') + print('sys.platform=%r' % (sys.platform)) + print('------') + print('sys.version:') + print(sys.version) + print('------') + print('sys.prefix:') + print(sys.prefix) + print('------') + print('sys.path=%r' % (':'.join(sys.path))) + print('------') + + try: + import numpy + has_newnumpy = 1 + except ImportError as e: + print('Failed to import new numpy:', e) + has_newnumpy = 0 + + try: + from numpy.f2py import f2py2e + has_f2py2e = 1 + except ImportError as e: + print('Failed to import f2py2e:', e) + has_f2py2e = 0 + + try: + import numpy.distutils + has_numpy_distutils = 2 + except ImportError: + try: + import numpy_distutils + has_numpy_distutils = 1 + except ImportError as e: + print('Failed to import numpy_distutils:', e) + has_numpy_distutils = 0 + + if has_newnumpy: + try: + print('Found new numpy version %r in %s' % + (numpy.__version__, numpy.__file__)) + except Exception as msg: + print('error:', msg) + print('------') + + if has_f2py2e: + try: + print('Found f2py2e version %r in %s' % + (f2py2e.__version__.version, f2py2e.__file__)) + except Exception as msg: + print('error:', msg) + print('------') + + if has_numpy_distutils: + try: + if has_numpy_distutils == 2: + print('Found numpy.distutils version %r in %r' % ( + numpy.distutils.__version__, + numpy.distutils.__file__)) + else: + print('Found numpy_distutils version %r in %r' % ( + numpy_distutils.numpy_distutils_version.numpy_distutils_version, + numpy_distutils.__file__)) + print('------') + except Exception as msg: + print('error:', msg) + print('------') + try: + if has_numpy_distutils == 1: + print( + 'Importing numpy_distutils.command.build_flib ...', end=' ') + import numpy_distutils.command.build_flib as build_flib + print('ok') + print('------') + try: + print( + 'Checking availability of supported Fortran compilers:') + for compiler_class in build_flib.all_compilers: + compiler_class(verbose=1).is_available() + print('------') + except Exception as msg: + print('error:', msg) + print('------') + except Exception as msg: + print( + 'error:', msg, '(ignore it, build_flib is obsolute for numpy.distutils 0.2.2 and up)') + print('------') + try: + if has_numpy_distutils == 2: + print('Importing numpy.distutils.fcompiler ...', end=' ') + import numpy.distutils.fcompiler as fcompiler + else: + print('Importing numpy_distutils.fcompiler ...', end=' ') + import numpy_distutils.fcompiler as fcompiler + print('ok') + print('------') + try: + print('Checking availability of supported Fortran compilers:') + fcompiler.show_fcompilers() + print('------') + except Exception as msg: + print('error:', msg) + print('------') + except Exception as msg: + print('error:', msg) + print('------') + try: + if has_numpy_distutils == 2: + print('Importing numpy.distutils.cpuinfo ...', end=' ') + from numpy.distutils.cpuinfo import cpuinfo + print('ok') + print('------') + else: + try: + print( + 'Importing numpy_distutils.command.cpuinfo ...', end=' ') + from numpy_distutils.command.cpuinfo import cpuinfo + print('ok') + print('------') + except Exception as msg: + print('error:', msg, '(ignore it)') + print('Importing numpy_distutils.cpuinfo ...', end=' ') + from numpy_distutils.cpuinfo import cpuinfo + print('ok') + print('------') + cpu = cpuinfo() + print('CPU information:', end=' ') + for name in dir(cpuinfo): + if name[0] == '_' and name[1] != '_' and getattr(cpu, name[1:])(): + print(name[1:], end=' ') + print('------') + except Exception as msg: + print('error:', msg) + print('------') + os.chdir(_path) +if __name__ == "__main__": + run() diff --git a/shared/package-files/d1/d12495f2a5e115f03cf93f73bee59ab084fc6cd6cf5cb517e19419a740a80f39/blob b/shared/package-files/d1/d12495f2a5e115f03cf93f73bee59ab084fc6cd6cf5cb517e19419a740a80f39/blob new file mode 100644 index 0000000000000000000000000000000000000000..593d247e5bc403056808dafa8fba9d511457fbd0 --- /dev/null +++ b/shared/package-files/d1/d12495f2a5e115f03cf93f73bee59ab084fc6cd6cf5cb517e19419a740a80f39/blob @@ -0,0 +1,10 @@ +"""Importable modules that enable the use of experimental features or estimators. + +.. warning:: + + The features and estimators that are experimental aren't subject to + deprecation cycles. Use them at your own risks! +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause diff --git a/shared/package-files/d1/d1284cb753ddb8fdcafa7db41e3c6159140c39128ffeae2bb08458796ce80d1d/blob b/shared/package-files/d1/d1284cb753ddb8fdcafa7db41e3c6159140c39128ffeae2bb08458796ce80d1d/blob new file mode 100644 index 0000000000000000000000000000000000000000..10e55bf838c33f00ab520bce7f4e145a7db8819a --- /dev/null +++ b/shared/package-files/d1/d1284cb753ddb8fdcafa7db41e3c6159140c39128ffeae2bb08458796ce80d1d/blob @@ -0,0 +1,226 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/csv/invalid_row.h" +#include "arrow/csv/type_fwd.h" +#include "arrow/io/interfaces.h" +#include "arrow/status.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +class DataType; +class TimestampParser; + +namespace csv { + +// Silly workaround for https://github.com/michaeljones/breathe/issues/453 +constexpr char kDefaultEscapeChar = '\\'; + +struct ARROW_EXPORT ParseOptions { + // Parsing options + + /// Field delimiter + char delimiter = ','; + /// Whether quoting is used + bool quoting = true; + /// Quoting character (if `quoting` is true) + char quote_char = '"'; + /// Whether a quote inside a value is double-quoted + bool double_quote = true; + /// Whether escaping is used + bool escaping = false; + /// Escaping character (if `escaping` is true) + char escape_char = kDefaultEscapeChar; + /// Whether values are allowed to contain CR (0x0d) and LF (0x0a) characters + bool newlines_in_values = false; + /// Whether empty lines are ignored. If false, an empty line represents + /// a single empty value (assuming a one-column CSV file). + bool ignore_empty_lines = true; + /// A handler function for rows which do not have the correct number of columns + InvalidRowHandler invalid_row_handler; + + /// Create parsing options with default values + static ParseOptions Defaults(); + + /// \brief Test that all set options are valid + Status Validate() const; +}; + +struct ARROW_EXPORT ConvertOptions { + // Conversion options + + /// Whether to check UTF8 validity of string columns + bool check_utf8 = true; + /// Optional per-column types (disabling type inference on those columns) + std::unordered_map> column_types; + /// Recognized spellings for null values + std::vector null_values; + /// Recognized spellings for boolean true values + std::vector true_values; + /// Recognized spellings for boolean false values + std::vector false_values; + + /// Whether string / binary columns can have null values. + /// + /// If true, then strings in "null_values" are considered null for string columns. + /// If false, then all strings are valid string values. + bool strings_can_be_null = false; + + /// Whether quoted values can be null. + /// + /// If true, then strings in "null_values" are also considered null when they + /// appear quoted in the CSV file. Otherwise, quoted values are never considered null. + bool quoted_strings_can_be_null = true; + + /// Whether to try to automatically dict-encode string / binary data. + /// If true, then when type inference detects a string or binary column, + /// it is dict-encoded up to `auto_dict_max_cardinality` distinct values + /// (per chunk), after which it switches to regular encoding. + /// + /// This setting is ignored for non-inferred columns (those in `column_types`). + bool auto_dict_encode = false; + int32_t auto_dict_max_cardinality = 50; + + /// Decimal point character for floating-point and decimal data + char decimal_point = '.'; + + // XXX Should we have a separate FilterOptions? + + /// If non-empty, indicates the names of columns from the CSV file that should + /// be actually read and converted (in the vector's order). + /// Columns not in this vector will be ignored. + std::vector include_columns; + /// If false, columns in `include_columns` but not in the CSV file will error out. + /// If true, columns in `include_columns` but not in the CSV file will produce + /// a column of nulls (whose type is selected using `column_types`, + /// or null by default) + /// This option is ignored if `include_columns` is empty. + bool include_missing_columns = false; + + /// User-defined timestamp parsers, using the virtual parser interface in + /// arrow/util/value_parsing.h. More than one parser can be specified, and + /// the CSV conversion logic will try parsing values starting from the + /// beginning of this vector. If no parsers are specified, we use the default + /// built-in ISO-8601 parser. + std::vector> timestamp_parsers; + + /// Create conversion options with default values, including conventional + /// values for `null_values`, `true_values` and `false_values` + static ConvertOptions Defaults(); + + /// \brief Test that all set options are valid + Status Validate() const; +}; + +struct ARROW_EXPORT ReadOptions { + // Reader options + + /// Whether to use the global CPU thread pool + bool use_threads = true; + + /// \brief Block size we request from the IO layer. + /// + /// This will determine multi-threading granularity as well as + /// the size of individual record batches. + /// Minimum valid value for block size is 1 + int32_t block_size = 1 << 20; // 1 MB + + /// Number of header rows to skip (not including the row of column names, if any) + int32_t skip_rows = 0; + + /// Number of rows to skip after the column names are read, if any + int32_t skip_rows_after_names = 0; + + /// Column names for the target table. + /// If empty, fall back on autogenerate_column_names. + std::vector column_names; + + /// Whether to autogenerate column names if `column_names` is empty. + /// If true, column names will be of the form "f0", "f1"... + /// If false, column names will be read from the first CSV row after `skip_rows`. + bool autogenerate_column_names = false; + + /// Create read options with default values + static ReadOptions Defaults(); + + /// \brief Test that all set options are valid + Status Validate() const; +}; + +/// \brief Quoting style for CSV writing +enum class ARROW_EXPORT QuotingStyle { + /// Only enclose values in quotes which need them, because their CSV rendering can + /// contain quotes itself (e.g. strings or binary values) + Needed, + /// Enclose all valid values in quotes. Nulls are not quoted. May cause readers to + /// interpret all values as strings if schema is inferred. + AllValid, + /// Do not enclose any values in quotes. Prevents values from containing quotes ("), + /// cell delimiters (,) or line endings (\\r, \\n), (following RFC4180). If values + /// contain these characters, an error is caused when attempting to write. + None +}; + +struct ARROW_EXPORT WriteOptions { + /// Whether to write an initial header line with column names + bool include_header = true; + + /// \brief Maximum number of rows processed at a time + /// + /// The CSV writer converts and writes data in batches of N rows. + /// This number can impact performance. + int32_t batch_size = 1024; + + /// Field delimiter + char delimiter = ','; + + /// \brief The string to write for null values. Quotes are not allowed in this string. + std::string null_string; + + /// \brief IO context for writing. + io::IOContext io_context; + + /// \brief The end of line character to use for ending rows + std::string eol = "\n"; + + /// \brief Quoting style + QuotingStyle quoting_style = QuotingStyle::Needed; + + /// \brief Quoting style of header + /// + /// Note that `QuotingStyle::Needed` and `QuotingStyle::AllValid` have the same + /// effect of quoting all column names. + QuotingStyle quoting_header = QuotingStyle::Needed; + + /// Create write options with default values + static WriteOptions Defaults(); + + /// \brief Test that all set options are valid + Status Validate() const; +}; + +} // namespace csv +} // namespace arrow diff --git a/shared/package-files/d1/d12a142fcd22c0b3c7d8cf924e86421e5fde381cf52c77bf10b098e5cdcafef7/blob b/shared/package-files/d1/d12a142fcd22c0b3c7d8cf924e86421e5fde381cf52c77bf10b098e5cdcafef7/blob new file mode 100644 index 0000000000000000000000000000000000000000..0ab8b712cd846688b7d75d62336a07f937adf336 Binary files /dev/null and b/shared/package-files/d1/d12a142fcd22c0b3c7d8cf924e86421e5fde381cf52c77bf10b098e5cdcafef7/blob differ diff --git a/shared/package-files/d1/d12b3cc66af3f42a8ebe63e1c91d24f92c6237b6a93a3702938dffabd812d77b/blob b/shared/package-files/d1/d12b3cc66af3f42a8ebe63e1c91d24f92c6237b6a93a3702938dffabd812d77b/blob new file mode 100644 index 0000000000000000000000000000000000000000..a9cd1ecadd63f2b09ee4363fc283e8f1f5cbbb3b --- /dev/null +++ b/shared/package-files/d1/d12b3cc66af3f42a8ebe63e1c91d24f92c6237b6a93a3702938dffabd812d77b/blob @@ -0,0 +1,74 @@ +"""Exception classes raised by urllib. + +The base exception class is URLError, which inherits from OSError. It +doesn't define any behavior of its own, but is the base class for all +exceptions defined in this package. + +HTTPError is an exception class that is also a valid HTTP response +instance. It behaves this way because HTTP protocol errors are valid +responses, with a status code, headers, and a body. In some contexts, +an application may want to handle an exception like a regular +response. +""" +import io +import urllib.response + +__all__ = ['URLError', 'HTTPError', 'ContentTooShortError'] + + +class URLError(OSError): + # URLError is a sub-type of OSError, but it doesn't share any of + # the implementation. need to override __init__ and __str__. + # It sets self.args for compatibility with other OSError + # subclasses, but args doesn't have the typical format with errno in + # slot 0 and strerror in slot 1. This may be better than nothing. + def __init__(self, reason, filename=None): + self.args = reason, + self.reason = reason + if filename is not None: + self.filename = filename + + def __str__(self): + return '' % self.reason + + +class HTTPError(URLError, urllib.response.addinfourl): + """Raised when HTTP error occurs, but also acts like non-error return""" + __super_init = urllib.response.addinfourl.__init__ + + def __init__(self, url, code, msg, hdrs, fp): + self.code = code + self.msg = msg + self.hdrs = hdrs + self.fp = fp + self.filename = url + if fp is None: + fp = io.BytesIO() + self.__super_init(fp, hdrs, url, code) + + def __str__(self): + return 'HTTP Error %s: %s' % (self.code, self.msg) + + def __repr__(self): + return '' % (self.code, self.msg) + + # since URLError specifies a .reason attribute, HTTPError should also + # provide this attribute. See issue13211 for discussion. + @property + def reason(self): + return self.msg + + @property + def headers(self): + return self.hdrs + + @headers.setter + def headers(self, headers): + self.hdrs = headers + + +class ContentTooShortError(URLError): + """Exception raised when downloaded size does not match content-length.""" + def __init__(self, message, content): + URLError.__init__(self, message) + self.content = content diff --git a/shared/package-files/d1/d12c79c8bf03f29c980d74c80590284e24ac4691bf789cfcb83dadb55ae49615/blob b/shared/package-files/d1/d12c79c8bf03f29c980d74c80590284e24ac4691bf789cfcb83dadb55ae49615/blob new file mode 100644 index 0000000000000000000000000000000000000000..7a77021775ddb61d226aa8c4ba60f0af013e4a6c --- /dev/null +++ b/shared/package-files/d1/d12c79c8bf03f29c980d74c80590284e24ac4691bf789cfcb83dadb55ae49615/blob @@ -0,0 +1,20 @@ +8.278938049410748956e-01 9.035293984476246987e-01 1.862188994679486731e-01 8.921151312310462433e-01 2.061859119379583216e-02 3.440636727385729676e-01 1.533779912830328662e-01 5.701372300009802663e-01 5.510020730211558915e-01 1.792362258426003496e-01 8.086175120876580857e-01 6.115487184317183189e-01 1.233471787164852618e-02 1.441643531871039663e-03 4.044309209045688913e-01 3.561398959499905148e-01 1.281985712929750720e-01 8.663300833847481508e-01 8.696027786291581352e-01 3.611727370363766454e-01 5.283537658772616830e-01 1.440241088090119526e-01 3.112457227138950566e-01 6.031280796897889873e-01 9.230324792742518047e-01 2.332121881136874908e-01 3.192652267403439659e-02 3.466206294995559656e-01 2.988687728046366399e-01 5.116749542048093513e-02 2.584975830914494344e-01 4.302023478042227289e-01 8.003972751713522849e-01 9.364931911368097328e-01 9.737098649964673891e-01 4.718038453972229762e-01 4.526591686607864817e-01 1.056485678520797666e-01 5.883019714285405710e-01 3.846092237676981274e-01 6.461500053435473845e-01 1.013239729848824933e-01 1.216151561651189761e-01 5.159668929484659827e-01 8.452074473510227115e-01 9.885170962247968873e-01 7.623883073490128615e-01 2.291163243615434997e-02 5.775530980802381364e-01 7.820699896828091635e-01 8.239186345842965942e-01 3.391800105260227571e-01 9.546318451614538292e-01 3.789677917867695367e-01 4.526533399649290690e-02 8.366786473238587707e-01 3.082636811049858094e-01 1.173936820793450853e-01 7.631994969169442200e-02 2.997416650722183329e-01 5.795208655160232203e-01 3.942350892542011431e-01 1.175126383297261379e-01 4.928232513950027149e-01 9.421293996225950096e-01 8.365391053841342295e-02 6.868059693571844093e-01 3.589527962429440722e-01 7.592939427166059962e-01 5.623849466131448649e-01 2.110746828032050715e-01 9.824683704668600859e-01 2.661230142246236996e-01 6.162272315007123469e-01 5.023254536607497656e-01 5.202854476669782624e-02 5.835090668842095596e-01 7.864642118889143552e-01 2.504012386867506823e-01 6.728308641135989365e-01 4.610793534576096420e-01 4.820508770515909980e-01 9.720403251022265989e-01 3.100069285263498120e-01 7.681017126461753275e-01 7.956539306007082146e-02 2.593389637887737464e-01 1.137852590403054531e-01 3.885303073284454012e-01 8.599094660075957686e-01 5.215167875918280682e-02 1.620908248572288102e-01 1.859236090457663249e-01 6.247716512610480555e-01 3.415128495520775020e-01 7.034903368378029320e-01 6.037564640019568163e-01 2.338969434423310290e-01 1.002104885609900187e-02 7.866058403969036217e-01 +8.033694116033356369e-01 8.653264545544031572e-01 7.468340410754038539e-01 6.362430919910603278e-01 5.120006306625468628e-02 9.503348372633585450e-01 4.697732609626817935e-01 4.221305288459429317e-01 3.153452119838391354e-01 2.991014843442657556e-01 1.190667967280257811e-01 3.486567714509342109e-01 8.289493649885054660e-01 8.454811050800014049e-01 9.149673018211901265e-01 7.708707837193897738e-01 2.640157732122547785e-01 2.107897022189605396e-01 4.207633055054439408e-01 6.719500284654699174e-01 1.458031684893063007e-01 1.800412735886125493e-02 8.402733435220011149e-02 4.206760156883160295e-02 1.376933515041314227e-01 1.716717341022133692e-01 1.788220727652158892e-01 8.224310433402118869e-01 7.729093666867475898e-01 2.064223621025984556e-01 9.592092036227207741e-01 8.312490243754996344e-01 6.673289360369902834e-01 4.632847903690773261e-02 7.643954098358983762e-01 9.359341525615098023e-01 1.914966319163026176e-01 4.536590469402868031e-01 8.640836016538007147e-01 3.941529178175462444e-02 5.602101995205478469e-01 9.263806161941660067e-01 1.555995325944817820e-01 6.172208102950116348e-01 6.335576752812099866e-01 9.766975460368043649e-02 4.475795689539874278e-02 3.248842796104995934e-01 5.700377122149502540e-01 9.066962967256807504e-01 5.458460621505676347e-01 6.833401285581487405e-01 2.887244409544044155e-01 1.316338647016834784e-01 2.325673305245992140e-01 4.150121963188406760e-01 3.834845466366055833e-01 8.149365773968725302e-01 1.867003849450201702e-01 3.170322173543018707e-01 6.832093662682684476e-01 1.729728518929105618e-01 9.236557359702636250e-01 9.152941252150086360e-01 7.224879983096620384e-01 8.557920626598064517e-01 5.344883059251644974e-01 4.876873274449112783e-01 8.308277804506420949e-01 3.916624489322212410e-01 3.459695122273966916e-01 4.033512499027409604e-01 6.555726444913008155e-01 7.138452409380238173e-01 1.683937314599968094e-01 1.769382143486440961e-01 7.588683655178136700e-01 3.750589892880819010e-01 7.525176245126207197e-01 6.083961152538303052e-01 1.145972309907993258e-01 6.239614485809552580e-01 1.307655482065895880e-01 8.530458750670916190e-01 4.801602070124768584e-01 8.168122189863546989e-02 3.793139622744635675e-01 1.496986997776840189e-01 7.129023878302899186e-01 6.830979237438047358e-01 7.635375943876505644e-01 1.824004963251233402e-01 5.764695848992339444e-01 8.865113248731604223e-01 5.784337085544002388e-01 9.700026628755119562e-01 7.318207347905059112e-01 3.851401393936705331e-01 1.774291851193399161e-01 9.763423229242296220e-01 +9.287178470949695175e-01 1.748282433617460718e-01 9.238531711586964734e-01 8.291274445125006443e-01 9.513259272578692416e-01 7.486316801165745494e-01 6.257378457524477300e-01 2.062711693536473101e-01 3.970721244184766130e-01 2.738325225026445597e-01 8.735038948299954642e-01 5.415282140033768066e-01 5.176317904298315398e-01 5.347036264518250093e-01 7.482056965410627258e-01 4.140672582824351800e-01 8.709067272363142376e-01 9.499605569181273079e-01 5.380266748336398619e-01 4.369252161707162241e-01 8.235722216228258397e-03 4.308187193646527691e-01 6.030581482859224129e-01 7.316831195156517920e-01 5.540499846834291420e-01 2.044203040111662872e-01 8.645251782981867583e-01 1.816095717570278545e-01 9.639119168018674966e-01 3.572031072322333634e-01 5.580226816834680248e-01 5.586629875016585478e-01 7.213854320902782780e-01 8.513998260042524580e-01 6.308764347277173723e-02 4.299855362100638567e-01 8.789303907444128150e-01 9.178850359236285783e-01 2.275205845091231582e-01 1.899395443939643213e-01 7.103070862773533944e-01 9.450015289553428399e-01 1.691856364522159595e-01 7.368719616877857925e-01 9.600189536623833231e-01 5.128846522932454244e-01 6.209162727118655578e-02 7.992250598838029907e-01 9.141050280518014937e-01 1.471297785256820978e-01 7.466162372930541524e-01 4.656107650642931084e-01 6.399324135161845728e-01 2.023617619481610230e-01 1.019104648900100996e-01 4.390693688536728700e-02 9.822620353006089600e-01 2.881951852926285529e-01 6.191575015960482098e-02 8.989580763251467932e-01 4.635958631890454429e-01 1.781973138114967270e-02 7.906911683818984571e-02 6.525270776225711167e-02 3.620583622807886925e-01 2.651673718940715796e-01 5.829372395929610651e-01 2.118159824373908595e-01 5.900287159143694504e-01 9.405929925178391215e-01 9.262415619063500971e-01 5.639581506302312475e-01 4.529556154689695635e-02 2.873819210518682166e-01 5.718545934306838996e-01 9.877670791317306742e-01 4.120364488714320927e-01 9.896078045634184583e-01 3.796586997026456523e-01 1.178183652203194098e-01 6.641068305236120795e-01 4.045960610587706618e-03 2.262690437428437340e-01 7.839938005832693957e-01 7.695391333937223743e-01 3.713918392552509884e-01 4.245533341514018399e-01 1.475072494020331915e-01 6.011975181419888514e-01 5.158174017998343741e-01 1.788706151398071764e-01 8.880707130134481986e-01 6.463351030474082659e-01 6.499920635615744624e-01 8.570273676455353318e-01 6.055019270899113515e-01 2.123561211054603159e-02 2.027688787664126968e-01 1.930834215328548487e-01 5.131906052747271518e-01 +2.599990881903107010e-01 6.767857524909899336e-01 7.188217446352963558e-01 3.037178903357997672e-01 4.252381412838680541e-01 4.070924411439535984e-02 8.426710493038247485e-02 8.301517457289483426e-01 8.254603255702420705e-01 7.258533909453509514e-01 9.958706809470796451e-01 1.323408451651194584e-01 8.523995455245143571e-01 2.572405385832454705e-02 4.715363690065482727e-01 7.920130365690022378e-01 7.613745641534582775e-01 5.108305991695683002e-01 7.908714335912382376e-01 4.641131983754837043e-01 3.112627109831845873e-01 4.218013908715474436e-01 3.291577909008427394e-01 2.538715054071232213e-01 1.362470842487485401e-01 2.716429790290709745e-01 1.485325814161112534e-01 4.514539027544387517e-01 6.900835128673067365e-01 7.793407072946112457e-02 5.938024345270752624e-01 1.497853829906865553e-01 5.399567982652856424e-01 1.419209916759478496e-03 7.719776132867679497e-01 3.130795105576239523e-01 6.670071611167494030e-01 8.900596881158256979e-01 8.011158503301568645e-01 7.089295605187424520e-01 4.671116382997058114e-01 6.682965170673403899e-01 6.524835265739736823e-02 5.454288420771494783e-01 7.751910790556310049e-01 8.192595541387335256e-01 3.098855848167891835e-01 3.689971355659119601e-01 8.666507475054133769e-01 2.749042684253171220e-01 3.566565602478318775e-01 4.838173174723044978e-01 1.032975933616413489e-01 5.063065339610417492e-02 5.791168455729079900e-01 3.573337411289496668e-01 6.714098909652352898e-01 2.917057662433912846e-01 2.654964332620638467e-01 7.171804039048814694e-01 3.314488637898249657e-01 5.230399837442840649e-01 6.866534136026025692e-02 1.252966394621071178e-01 5.349397882659551184e-01 2.841423847455760709e-01 4.158473635710734362e-01 7.197062989831272128e-01 5.123869045047864113e-01 8.675622821594339840e-01 8.097441845042540054e-01 7.317178252133832439e-01 3.300847596465853462e-01 5.922311859141077273e-01 8.852619511417836318e-02 2.673412917259408994e-01 6.878259052441990651e-01 3.223000927116328462e-01 8.859387123976615319e-01 5.722722388300067742e-01 8.254877606669521750e-01 5.705299682290687624e-01 7.046478734972855262e-01 1.316324413616759559e-01 3.056358395675535800e-01 2.396516834600909140e-01 2.041201422493257311e-01 1.610755140653103989e-01 1.617012564641111538e-01 4.449920510036902144e-01 2.731012972755201274e-01 7.826874666257994662e-01 5.193612375350010746e-01 8.688804522977213729e-01 3.742157602758655610e-02 6.649628920608219307e-01 5.978149424619171315e-01 5.345645500553952711e-01 9.443202650415919441e-01 6.105837075491723498e-01 +6.387761328141735584e-01 4.210087412162694109e-01 3.777306694964789324e-01 3.576349403292201634e-01 7.272699618880260619e-01 9.173392803607671731e-02 1.212535698300880593e-01 3.871229381194544183e-01 7.735150198351389284e-01 4.687200483013695962e-01 5.161778571874678923e-01 9.839646447226980674e-01 8.626932748911960713e-01 9.618485576577924245e-01 2.997996427525421170e-01 3.955404657388794654e-01 8.480126027102616870e-01 8.194992325050480808e-01 2.800213436873294492e-01 7.188391466620779324e-01 2.289766105875049584e-01 3.838547514028287644e-01 1.363553401061209369e-01 2.131328253542326134e-01 2.666779468144075960e-02 3.252883844200405994e-01 4.207860197469600605e-01 2.991365385037647595e-01 9.180779845534067229e-01 8.787338732192649937e-01 5.404510999105649471e-01 1.735493827761729335e-01 7.405224640747264386e-01 3.927355563629583157e-01 3.957109873399460298e-01 1.313029813325972128e-01 6.434498219738993274e-01 7.162213694578050127e-01 6.454998257494671821e-01 3.808124530008022424e-01 2.027201015737234435e-01 6.667632842770417900e-01 1.609491052365198405e-01 1.192413785409307536e-02 4.546773323526854815e-01 7.733541911050207940e-01 3.902525737195561284e-01 4.006023779897505133e-01 5.156517815815246930e-01 6.135685498584592112e-01 7.062153114980724844e-01 5.505858882117883324e-01 3.541308807182554919e-01 5.237151122342533771e-01 5.230649229131387745e-01 1.973541027697351957e-01 7.940327858595511712e-01 9.998588700623055603e-01 3.878271015153827994e-01 4.455006584967207139e-01 8.376414508056347907e-01 3.310833863524501597e-01 8.020469097392601832e-01 1.890327633084128989e-01 3.830289472395409511e-01 8.605040171046141051e-02 9.978185524023941433e-01 8.333890591892906263e-01 4.509013468741837061e-01 6.355778557686052599e-01 1.422515991097305088e-01 9.549891485963732940e-01 7.535776302868563148e-01 9.306005301880662106e-01 2.444330347211679522e-01 5.828218427569508142e-01 1.261938242968304591e-01 2.829188731405173352e-01 8.100246952078660190e-01 2.032739130996042975e-01 3.997268448390065565e-01 3.882777703107541667e-01 1.102505652624736765e-01 5.826634725328041498e-01 6.508734477956333864e-01 1.777287661702166011e-01 4.857051012052149286e-02 6.850537712379254351e-01 5.012281307761055071e-01 3.329154880061502286e-01 5.006261767216675374e-01 4.542081454976160115e-01 6.777801995399822532e-01 4.271303586474960445e-01 7.820470659692947413e-01 5.143462618485082904e-01 4.071273891563575997e-02 8.503383643856671226e-01 6.877485768345151795e-01 6.498843855014626580e-01 +5.539512747016193117e-01 6.329206647391879548e-01 2.798533500321682688e-01 4.825977295850051307e-01 7.625297023172977751e-01 9.081309101427640362e-01 4.124792086535029600e-01 3.647019658319609059e-01 7.529595202332928228e-02 3.072404010876803593e-01 7.890673660964639957e-01 4.079781478915127657e-01 1.440519120695739064e-01 2.538968953804546791e-01 1.595028243568367143e-01 9.066545851872198636e-02 6.367601114674349416e-01 7.622263643880089479e-02 3.015728236404162654e-01 2.424070469873378375e-01 5.711440390241000475e-01 5.717001375511508998e-01 2.237853674032181939e-01 7.112101625753678436e-01 4.321054197012103026e-01 2.505322169010260058e-02 5.877307077139551916e-01 4.415771174397812304e-01 3.766022855145171322e-01 9.803490652619811785e-01 1.229258314111529860e-01 8.108351868714478439e-01 8.558595456964329662e-01 2.168217533833206589e-01 2.034022719386595623e-01 8.687457137579783772e-01 9.013327195854559104e-01 8.156766512673154779e-01 2.717576187546973943e-01 1.756417893371479133e-01 7.555856977566548505e-01 6.708809351312817748e-01 8.998789237886926085e-01 1.936367585946979775e-01 7.949724635465026390e-01 3.164799312763589834e-01 5.493048513173155456e-01 1.608917269168268493e-01 3.048667492191803330e-01 5.599401537727016764e-01 5.779501360842279611e-01 1.296714605309662316e-01 9.160752328055997706e-01 8.058674476110374574e-01 4.385508937505578908e-01 9.212419718012100356e-01 2.249887451242467140e-01 6.283927745352599903e-01 3.778992451536005159e-01 3.571958698867505611e-03 7.276526470528231760e-01 9.051678673805297892e-01 8.465837072484881931e-01 4.548317505393462135e-02 3.189318261926020748e-01 4.446388607398673587e-01 4.292356336344156365e-01 4.203980977718795309e-01 4.698059253071955599e-01 6.151991200848159203e-01 8.479986139404802614e-01 9.870993262459623052e-01 3.164206525899861955e-01 6.464672171639846976e-01 8.508781429592480183e-01 4.733667503354813677e-01 8.076014176740163863e-01 6.671443255679101458e-01 6.639213267047979761e-01 3.681688930741919830e-01 4.679870252651611162e-01 1.790041740686979521e-01 8.446070273663058847e-01 3.350737544979878191e-01 6.600272349677447359e-01 4.356083218487936115e-01 7.995134167346013010e-01 9.083660261041469619e-01 9.743975306734570241e-01 8.144839650654719376e-01 6.865011984586443239e-01 1.709747281999153268e-01 8.534933687161740945e-01 9.494753729726415070e-01 8.140124992294850426e-01 8.936241255316055287e-01 9.087976860818796077e-01 9.030687493451383663e-02 4.025785149840914734e-01 9.592005611533803711e-01 +5.714058727476275523e-01 7.913573761505965365e-02 9.301773447377043036e-01 4.302822433307075256e-01 4.618892554175407783e-01 1.882471300213742760e-01 6.231472878215863487e-01 2.350437450940777717e-01 8.483410480771292894e-01 8.580803842040533036e-01 4.246398783388435350e-01 5.667321565946502604e-01 7.247417018955526480e-02 5.373984417482219333e-01 8.794242091541510931e-01 9.699025554453030162e-01 8.254197752548814160e-01 7.739723972867470492e-01 6.365819416181199841e-01 3.451230687021222820e-02 1.829102490094791644e-02 9.179618383026147965e-01 4.481667270072077214e-01 4.771270250445739380e-01 1.588469404953456454e-01 3.766332499200618633e-01 5.057026248713025751e-02 9.125900914275182352e-01 8.438133644246305076e-01 3.282972411719701222e-01 6.042003956122835584e-01 7.423456085393266290e-01 1.389012737541106546e-02 3.674754266702850991e-02 2.126646727703802586e-01 3.085666164246750887e-01 4.303440338750976757e-01 1.749037978865556342e-01 2.177699993322510519e-01 6.675614739991906355e-01 1.926533336347433512e-01 8.032010572660308600e-01 4.611412981769049679e-01 9.907201268457492827e-01 8.973785930837320235e-01 6.286342392657409128e-01 8.111266245859546364e-01 1.154230969025437092e-01 8.382880466301794176e-01 1.053753927827069115e-01 9.921712862234919328e-01 9.041662667920956631e-01 3.626267376021269362e-01 2.262225368932846425e-02 8.669003741626111204e-01 7.597054897704164089e-01 4.700318514995387442e-01 4.338185014241978665e-01 1.205425463362067573e-01 2.413879270602589111e-01 5.483334840461459025e-01 2.042653841254596925e-01 5.452588940366013270e-01 3.164646091706100339e-01 1.878958248945691301e-01 2.188622304737641855e-01 2.970982599823450698e-01 5.952148400199362976e-01 9.614251220149501176e-01 5.446813400697393392e-01 5.900748097930779146e-01 2.653062526715309621e-01 5.459933097767216692e-01 3.174185404661935550e-01 1.412133354129242457e-01 1.487441669790685594e-01 3.953776242211952674e-01 5.274261039692862418e-01 1.756132307607755072e-01 4.481942852746899630e-01 6.390660088765629521e-01 2.860380430081067571e-01 5.866902519902850166e-03 3.026687645174785946e-02 1.952533570196290924e-01 2.154769096186736066e-01 8.920573593276575064e-01 5.644513191915436767e-01 5.551464696654353492e-01 4.378199413349500579e-01 8.685737643974280608e-01 7.493934764293597173e-02 9.556749726352036234e-01 6.386433482536227890e-01 8.714694524097754691e-02 1.722786161701279628e-01 6.526867532768643176e-01 8.950304705281527662e-01 6.158198776753203152e-01 9.587176904005377809e-01 +7.705718397401561948e-01 3.165816092999733655e-01 4.334200859975760878e-01 8.639807015515663657e-01 5.576514209532534849e-03 2.456745447057938625e-01 1.664686313299922338e-01 9.637084729617834133e-01 1.083448720752323569e-01 1.865218070380464388e-01 3.730358890475884426e-01 5.015351872138350542e-01 7.420710795841709562e-01 4.919420674769692248e-01 3.426558201886464872e-02 8.669984854934246199e-01 2.204243734202966376e-01 4.109792246853891662e-01 4.361732572946559472e-01 6.819306998053020763e-02 9.986304248057148447e-01 4.119289455392274313e-01 8.533050041845835487e-01 3.416914861912183632e-01 6.522191951039880697e-01 4.162803668786793088e-01 9.051674379917418189e-02 4.552378661306888397e-02 2.122677193466918633e-01 7.461518531655018105e-01 4.654688019259497489e-01 7.877564083548750373e-01 4.518328005682387127e-01 7.173857464237374248e-01 6.940056370290903498e-02 2.804574410412373764e-01 6.095681113112718652e-01 3.680596478602831123e-01 1.814569150719304025e-01 6.505055517979729807e-01 2.759585245701871026e-01 1.429501104786028431e-01 7.813891153083207808e-02 8.925314279991185540e-01 6.692056941902108091e-01 1.915141341107173822e-01 5.750233129581091562e-01 2.051961006251528108e-01 3.849013692629975614e-01 9.503788222043518807e-01 7.690419386411734282e-01 9.978147530014782607e-01 1.719584162437415298e-01 4.890758882401113894e-01 7.195660736040896399e-01 2.485818040997200828e-01 9.706486601870933928e-01 5.182604282071262558e-01 8.082072245463804983e-01 4.889961284821118248e-01 8.042893959057633158e-01 3.200685313413229593e-01 8.983245016887355661e-01 2.811495336955205371e-01 3.986095833814048417e-01 8.607229214132059436e-01 4.827620119717191960e-01 6.715610252037491623e-01 9.330824374137768329e-01 7.537710530085762750e-01 9.840804224010484269e-01 2.319352541177217564e-01 9.569114943157627229e-01 5.821928104654411351e-01 6.700479524814679788e-01 5.663434680086896211e-01 8.851091082101365526e-01 6.800562815862243315e-01 3.578475213752868589e-01 2.900164669281133367e-01 8.379170683569914235e-02 9.929972839740475177e-02 5.946248553621906741e-01 1.991332889320840405e-01 8.115065723822508792e-01 2.023388190440008616e-01 4.056545651129230823e-01 2.966825350250481552e-01 7.457176343507545546e-01 9.856015771246517954e-01 2.264338016147812160e-01 8.366528670045663141e-01 6.116829813603242849e-01 2.605933184296719274e-01 5.765962146558850643e-01 5.064075092266390188e-01 5.499615769589756287e-01 9.240234698632640020e-01 7.169900155229913530e-02 3.544181364560751168e-01 +8.154844535553099627e-01 4.797965609394789777e-01 7.476703385713100447e-01 9.086708404761600910e-01 3.191752505450355937e-01 7.611128630021511965e-01 6.246790343299296611e-01 1.942001426217137006e-01 2.789860414631386565e-01 3.236359785042408621e-02 3.178191288741717413e-01 8.372264298357038337e-01 8.872692914664047636e-01 9.589758852077276963e-01 3.123722260380168425e-01 8.980164015338999439e-01 7.260784140459818348e-01 6.567013512265649222e-01 1.028743505926521529e-01 6.821705410750319443e-01 6.889838995316139858e-01 5.587525493094736007e-02 6.921487028366646310e-01 3.616312929861494885e-01 1.673758008792780583e-01 6.626504595920326146e-01 9.125680913222075086e-01 1.424077784972291871e-01 6.508496429060767197e-01 6.615417385775157477e-01 9.654167310675311198e-01 5.536662974550183858e-01 7.092622144968085962e-03 6.694595400455760625e-01 1.828533619119211417e-01 3.421514408394116247e-01 1.242580151818144518e-01 9.888774797458224075e-01 9.777955172739735135e-01 4.271370765628749178e-01 1.211608384809655936e-01 1.580132417172936954e-01 3.242705395708289640e-01 3.268994391754735940e-01 5.213767653645562383e-03 4.475169480357120699e-01 9.593245219293577986e-01 6.994304536782350867e-01 7.063863152769014331e-01 8.381620829497931080e-01 2.760441799736219615e-01 3.755200946645842475e-01 3.627729621737311172e-01 9.518310606719182498e-01 3.577273025276901386e-01 3.991159901003488164e-01 4.187060513068554535e-01 7.422605403637314581e-01 6.697944269780702342e-01 6.020599837037767799e-01 1.571185850817550245e-01 7.519860911185742847e-01 6.635775704496444938e-01 9.487848173531471252e-01 7.900030232338028924e-01 4.143783957270819052e-01 5.618429740858444932e-01 3.737804619062014000e-01 6.179941187802344693e-01 6.553638605616040058e-01 1.009709416658691739e-01 4.935037098582963910e-01 5.485489972455533936e-01 1.024147956480448984e-01 1.195764707555347917e-01 4.910516327810896531e-01 3.551185778630389089e-01 3.857601645798814927e-01 2.074975219600547760e-01 2.084038664460790002e-01 5.268616653491025037e-01 6.948014877618717833e-01 6.179744044618615817e-01 7.063658085955483168e-01 7.925757227686872630e-01 6.199016959584816577e-01 1.163676037434490107e-01 7.425752264755586252e-01 5.403115665133301215e-01 2.546191951391015840e-01 6.961300925345208501e-01 4.003013072125547467e-01 5.906120962720950995e-02 5.879915846330325824e-01 1.213602408288709800e-01 3.801780679842765576e-01 1.731477742402802722e-01 4.624568816669496485e-01 3.304453744619206823e-01 8.810445876116090869e-02 +5.140190515373614932e-01 1.419225260054487459e-01 7.777845802285945354e-01 3.327562899409282071e-01 8.916875699762913943e-01 7.212852862736146564e-01 5.727327199433507321e-01 5.897820225918504189e-01 7.318614954542906892e-01 7.393985144455500480e-01 4.531340740296823100e-01 9.903061584426188224e-01 4.213350938331624773e-01 4.542342471963995987e-01 9.788786426453045530e-01 1.881707000343846303e-02 8.005433413647761176e-01 1.523502822273363755e-01 5.630164732287495921e-01 5.946603842470724599e-01 1.225547698678740582e-01 1.531136594724622491e-01 8.157973612638946825e-02 2.752046015644330490e-01 6.809045821946161370e-01 6.455289724528190387e-01 3.830356726830793646e-01 4.446144649678575034e-01 4.969038423960672191e-01 5.497873820641221432e-01 9.471879627821714331e-01 5.933046675329255448e-01 4.099233758501530378e-02 5.790409810134594659e-01 9.546095885251496549e-01 2.608616052375664074e-01 6.910160339170060562e-01 1.293709850476291168e-01 6.407264616302255078e-03 6.186037089828009261e-01 5.537861302543241049e-01 3.527421038298221845e-01 8.033232052121624944e-01 8.128114152830284711e-01 8.319982582278713235e-01 5.939566376046836460e-01 2.291090283499520597e-01 5.438101817725821130e-01 6.881146379117278888e-01 2.421968586304659166e-01 5.874047918543783275e-01 6.210102709484541794e-01 7.041387566450251212e-01 6.959223476278774134e-01 9.133877300988062498e-01 9.230647706207778525e-01 6.856884219815310155e-01 6.997988808693775820e-01 6.177944932528769417e-01 5.512902545683161515e-01 5.818280341729102911e-01 6.538267999985679646e-01 6.946673485935980219e-01 4.817938258357623571e-02 9.352008817207906333e-01 4.774162142215661042e-01 5.768063588692976529e-01 4.589648891483899540e-02 7.998946815651652997e-01 4.434260476954369201e-01 9.850053510925722566e-01 6.648626681529369309e-01 4.606293826856903140e-01 3.309042418210563774e-01 1.438901922508034614e-01 7.986559119276418484e-01 7.037818421334554042e-01 3.605119534240813772e-01 3.785959549258922641e-01 9.562491516841659100e-01 4.997955143590974147e-01 1.029540300938682762e-01 1.819017177001992502e-01 3.665425750262368831e-01 1.688063588370778412e-01 7.030735208313992901e-01 8.922375654244527610e-01 1.055706412056253152e-01 2.664739907746691561e-01 9.906029568647586325e-01 6.043845090140997911e-03 3.495786295043534775e-01 5.989441999519146131e-01 6.776147193866479679e-01 7.012991789852640601e-01 1.825838783477321536e-01 7.612293578749116385e-01 1.564769891240175292e-01 2.762157292905387251e-01 7.641900040015234818e-01 +4.746013333880729768e-01 7.609202966712714788e-01 2.537820854162747830e-01 1.709362234877408460e-01 1.886635378734374813e-01 2.439567014093724229e-02 7.640304718272151741e-01 3.483216170435471382e-01 7.744289278738043514e-01 4.190437573644867353e-01 5.319091476394965934e-02 8.580130976087452233e-01 6.259446446786639529e-01 8.793213970773006150e-01 2.441023074890465994e-01 7.753405549489799098e-01 8.760187573193888300e-01 5.946480724009295393e-02 2.873093046571124631e-01 8.710837851946537924e-01 9.103181731924696596e-01 6.534637257615111272e-01 4.128420398577182793e-01 4.905858108576378607e-01 6.178275806701372108e-02 6.368043900016381320e-01 2.865296941219959148e-01 6.371773028539067241e-01 4.924322796636745325e-01 1.709313290387282080e-01 1.856892551689268700e-01 9.592782603102242289e-01 5.402593764193130976e-02 7.287312244390512506e-01 5.679467572000697073e-01 6.255587794305905724e-02 3.069660218141317953e-01 1.089960430557104232e-01 5.550748245336984965e-01 2.555948886689661803e-01 4.140925514039996980e-01 1.180376445052062628e-01 8.832322629884041820e-01 7.784546946701487169e-02 3.177678935473182698e-01 6.681804863429485764e-02 7.047099396645268854e-01 4.133897376851528582e-01 5.600656990480865627e-01 3.883995683475501837e-01 4.459430113152932362e-01 4.214077227574740681e-01 4.763369230200156235e-01 2.701480661168440545e-01 4.296286564389811824e-01 9.601402258758658936e-01 6.326999441846863359e-01 2.442086919688498670e-01 8.407708423957936938e-01 3.626867985638081437e-01 3.641441713291436733e-01 7.932397565989488530e-01 8.902073520619256941e-01 1.929173010337000838e-01 7.309376779324568973e-01 7.305852858337777977e-01 6.510197444582447313e-01 9.512661608643838695e-01 8.461467164366111016e-01 9.245490147941206605e-01 2.658844813385705663e-01 9.538758859344749208e-01 8.215517204998477041e-01 8.217795540390903097e-01 7.569662091300560780e-01 6.262685322871274218e-01 5.597770510574888725e-01 8.155720175123675197e-01 8.545688745180864965e-01 8.986051518529034610e-01 2.477911506572628708e-01 8.462580108996445860e-01 6.065941220995090255e-01 6.500490804973033665e-01 1.120463882674053169e-01 9.299049132942927010e-02 1.388364074229719858e-02 5.901199124540731367e-01 2.795110110544174464e-02 1.644097083463245124e-01 5.341029647603202646e-01 5.276816677181681570e-01 5.439849107754858304e-01 5.371677986392331405e-02 4.515163125788429488e-01 5.036243367087100964e-01 5.721818679625961801e-01 5.271368612400184617e-03 7.720961020546839304e-01 9.015383457479009266e-01 +8.301526916287945701e-01 8.704609696144033348e-01 2.955689129581380303e-01 1.762209253489944727e-01 2.698172933050072553e-01 1.138095349991521399e-01 4.092588531860634760e-01 8.202978121681584467e-01 2.822241377079557356e-01 6.117376205659387223e-01 7.169923068016897938e-01 9.310256256264415331e-02 3.989664052931106708e-01 1.651874953308862803e-02 7.890202597932294282e-02 9.068686774810821305e-01 5.203866694486933842e-01 4.297748572844445336e-01 5.208786995443430712e-01 2.163224881365530816e-01 7.274307306357226111e-01 1.675784956180090823e-01 5.969822786565782691e-01 8.959750832846602453e-02 1.253794151891943764e-01 5.352628522116801291e-01 2.562706125890066300e-01 6.030433202137867044e-01 8.330717547440393833e-01 9.603613683422040914e-02 7.569714244468559450e-01 3.184801677796517128e-01 1.667069341164499896e-01 3.132470247801235619e-01 6.417752836394801097e-01 6.433909425912354152e-02 4.056860213146201710e-01 3.166772891331335327e-01 9.574059746098845247e-01 1.492907964460536974e-01 8.311513764927496162e-01 6.652928354977717396e-01 2.396804722185036374e-01 5.812361618600220270e-01 9.724228681350225445e-01 2.853983236378453414e-01 5.337719354896472979e-01 6.779446197712412081e-01 5.485102006140557540e-01 9.010109155962182648e-01 5.724439967467525037e-01 5.965540527411405947e-01 1.598667990086183321e-01 1.363934512727023041e-01 5.327536522697270405e-01 4.123866715061276222e-01 4.617251396918636841e-01 6.935944951381239898e-01 4.300337419593377453e-01 1.892407993760835128e-01 1.666936825594794724e-01 4.625634184864588772e-01 4.805197636774838355e-02 7.003542850133466224e-01 2.130226006716084974e-03 8.678863343041013367e-01 4.874478520451258623e-01 7.043560228741558848e-01 6.317719270475393722e-01 5.372392256296196766e-01 2.982649812986511995e-01 1.272558612133412037e-01 2.467337555730741983e-01 6.546893200021091097e-01 6.291921159383098150e-01 8.505920470407707379e-01 4.046520490181828578e-01 3.875732096593392795e-01 8.551517214319142024e-01 4.152602284179877090e-01 9.587779137989138611e-01 6.977437468944928112e-01 3.240620775541913634e-02 4.025873770391376061e-01 5.485549335619134270e-01 7.146066156157020455e-01 3.012702534568838519e-01 3.526414480395153594e-01 3.309707144485515284e-01 4.315687014460974913e-01 6.641934530697197747e-01 2.172886798352815507e-01 4.807480925564590057e-01 5.006795397998469177e-01 5.818100901154411586e-01 2.107716091585690732e-01 6.606606051140029301e-01 9.317629042790995797e-01 9.840326342340242061e-01 5.752000964817773898e-01 +9.843444595454536872e-01 1.339523968066913540e-02 6.082172659959028671e-03 7.828244785439336662e-01 5.069653703872761819e-01 2.804896494365415327e-01 2.112385836660957139e-02 6.016479440778699228e-02 7.457477935084961818e-01 3.445503949245375397e-01 4.063494277166557200e-01 8.630275274433116817e-01 5.948396018456146850e-01 1.400867933474212457e-01 6.997522422654076646e-01 5.766519767930851081e-01 5.419976500582250889e-01 7.474121304089603735e-01 2.951600193008566686e-01 7.980170422334191827e-01 1.829036799578199757e-01 6.317636496261300749e-01 2.812612231140887431e-02 5.464747656105657381e-01 3.909873503320924204e-01 4.940850205957293406e-01 8.157850130814222611e-01 5.111092739445756150e-01 9.336823640685747439e-01 7.157105167170837445e-01 7.778989455994214097e-01 1.398722535910470466e-01 5.642653936300449091e-01 3.218717164845980028e-01 9.717427501967056402e-01 3.665791984428700134e-01 3.874321311211759156e-02 9.437600858738082188e-02 5.679526822961932231e-01 5.141385991358327079e-01 7.497840799582222715e-02 5.736515309094968318e-01 1.928132849879083954e-01 6.924244068001785823e-01 1.748389677952593146e-01 4.469577663506929532e-01 1.738527450963387455e-01 7.195287763517190793e-01 8.861150811892871682e-01 1.058443750714600506e-01 1.941789362229970894e-01 9.188374820700584422e-02 7.706736301449305104e-01 6.718642548609364828e-01 5.981029087121966237e-01 4.832880127232569434e-01 3.073688779938709148e-01 5.156312334804930009e-01 1.777418420119527553e-01 8.885462205165685079e-01 4.486254681289014723e-02 1.345398129556140132e-01 7.467627984379916484e-01 4.384565546058830643e-01 7.217750080760946263e-01 3.949550352625393890e-01 4.307950907642028593e-01 6.087680934849041270e-01 3.294516167246774874e-01 1.316682090209408962e-01 1.824857738754404046e-01 5.332379826483617524e-01 3.567136182864261151e-02 1.976220743086236631e-01 5.849349042822560296e-01 1.133174406357483344e-01 7.711522754393199675e-01 8.557306786807005183e-01 3.038353471344266143e-01 4.422747047768413875e-01 2.537160404215925702e-01 2.372714099723788328e-01 5.906462765375103396e-01 4.849909323133470007e-01 2.692576210504484813e-01 4.540849506602829821e-01 9.664935719107857759e-01 2.044371576459835804e-01 4.505417469690352616e-01 7.110722322201217249e-01 3.051357995214963870e-01 8.978937034341526457e-01 6.090501112506481185e-01 6.595415779178889215e-01 6.565426836745864581e-01 6.565608489824376059e-01 2.679102664248229626e-01 3.819533138204529443e-01 6.609794961162380744e-01 2.289558446859882856e-01 +9.274935298374649140e-01 1.174096651033715855e-01 3.030761852629033637e-01 1.605508209527917174e-01 9.601854834873225775e-01 4.341959513718630648e-01 6.320768160802121560e-01 4.213429090614078110e-01 3.695553969042019160e-01 5.965457437116089556e-01 3.520335041155040479e-01 7.702703502247409961e-01 8.571112772962534709e-01 7.904077282532658844e-01 2.247339318352784554e-01 6.823720204503556097e-01 5.883435710582129996e-02 6.786037033312407596e-01 9.721137137641507886e-01 2.042576970668320557e-01 8.394085754806240862e-01 7.433082729552867862e-01 4.072614159870893147e-01 7.451483066617257123e-01 1.699472962789440045e-01 1.753052015584344314e-01 2.255269204788400428e-01 7.794755643807432799e-01 8.407732260470973662e-01 9.301182862857163558e-01 3.701995309382508648e-01 4.481909027604019657e-01 1.261889085033987001e-01 5.600591735875248833e-01 8.244692493969552061e-01 8.969188061645969601e-01 4.802217973423368313e-01 3.556164122713412201e-02 3.393317823164623270e-01 2.491242957582864292e-01 9.863253789366602797e-01 5.585415885291432625e-01 3.702350606362231344e-01 6.766101432620400535e-01 6.999259389475386284e-01 6.676108316872160220e-01 7.870681827507105544e-01 8.746765411259082024e-01 9.125268371282718727e-01 6.638849997061806452e-01 3.253268113800632522e-01 7.968625619248901337e-01 7.584122525443606211e-01 9.028886850768532701e-01 5.381622293189292083e-02 8.097562873320752752e-01 7.092942088208666895e-01 9.915538877968065323e-01 4.319294903327922652e-01 4.307127933969153721e-01 2.768507739641907772e-01 8.076253078288621046e-01 2.569233696442670967e-01 7.595893829724666979e-01 5.768081727897018673e-01 2.537536777625452045e-01 8.874419624636734616e-01 5.091705681832693342e-01 4.811826624992353585e-01 2.794462461940371290e-01 3.846927898276129021e-01 5.129562951959991679e-01 8.515004062224775794e-01 7.103144978683579858e-01 9.526388607201888847e-01 2.367905569592337889e-01 9.137336039323161740e-01 5.722969943101696710e-02 2.019723935481291255e-01 3.098764675203513619e-02 1.121146613918624357e-01 9.937693067724532314e-01 8.476717958861412772e-02 2.059652110343795917e-01 2.139791918759540446e-01 9.137860316709250919e-01 9.530862653366889425e-03 2.027843281683039400e-03 2.506229951837134484e-01 6.244523528392044165e-01 5.523937894075592325e-01 3.712168074031840792e-01 4.218847794299319665e-01 4.827576239387890711e-01 5.244634168840578425e-01 5.182241092381567604e-01 3.308639956263292881e-03 9.370528021570383448e-01 4.694554875029453012e-01 4.950447554541728135e-01 +1.525818111800841814e-01 4.708012184002630107e-02 3.899035965341954846e-01 3.928304521031263929e-01 5.602286661727436945e-01 9.738256658043862313e-01 9.404465779766183475e-01 5.750862754958349088e-01 9.547546956257608741e-01 2.750275291553152535e-01 1.682773435862793265e-01 5.865928471016079726e-04 8.543378154943809255e-01 3.547649971465383079e-01 5.058056647397523031e-01 9.116332486700751137e-02 7.534666421106954726e-01 3.082429494433007733e-01 4.527145111847344916e-01 5.456680635225539255e-01 2.504131242494785914e-01 2.509240770568589296e-01 3.949236999582302898e-01 8.782959620323271821e-03 2.474641132111736752e-01 8.229417958971670943e-01 3.444225768479134420e-01 4.000027489436257522e-01 4.247741954177396417e-01 2.497745404169693373e-02 4.325768602588443423e-01 7.336592463477830117e-01 7.667663267650381975e-02 4.179022553581047683e-01 8.745172741480690126e-01 9.417705509525042817e-02 2.807522782799587446e-01 8.212710101351362590e-01 2.211181944001613386e-01 4.319929503523877168e-01 1.858636923768219873e-02 6.737037795085246694e-01 7.997187114913413275e-01 2.976552505976116647e-01 3.272347030789168887e-01 5.550935453236346406e-01 9.224109746648162522e-01 3.192827922106745708e-01 3.500098324549234530e-01 7.821988386980260888e-01 4.478417135239194380e-01 1.580956175222456572e-01 5.300807813550156844e-01 5.806154798468634581e-01 9.456842911054151868e-01 7.688127895655872956e-01 8.456527833650537840e-01 1.784229089865225770e-01 8.114517450321339087e-01 8.062506298824222428e-01 2.113482500442499523e-01 2.629226789210241666e-01 6.478686221690072022e-01 6.006672861605766300e-02 7.013679843242253131e-01 8.784753961212666828e-01 3.487138165323044880e-02 4.928426758517070461e-01 5.976224683315064512e-01 7.629063997052759616e-01 2.761721278953045422e-01 7.240740503283805696e-01 6.131065729985127888e-01 1.630885615792579957e-01 8.473783868551159060e-01 8.347614542399306448e-02 8.137265626844719657e-01 8.512508664918938539e-01 2.777097816703766320e-01 1.729154355214796990e-01 2.203382750835449766e-01 6.134780912629795857e-01 3.524352564238901753e-01 5.370314860129862256e-01 8.013986113284543578e-02 2.555842138998117852e-01 6.553915758947851389e-01 9.679125599178584061e-01 2.549566319678178150e-01 4.008180804370896633e-01 9.145789951670967310e-01 2.787926039163850511e-01 8.599455912576436933e-02 9.637558000691170967e-02 8.274101203974880692e-01 1.803747268179315411e-01 2.175735407836230095e-01 7.825994939720237742e-01 7.928519890958951599e-02 8.707949373106749213e-01 +6.398420210047787160e-01 5.739624494012524059e-01 3.359672805578653998e-01 1.130399363175038641e-02 3.349439685346782269e-01 2.315484030880912147e-01 4.575228302577399875e-01 1.149494135594463229e-01 2.888244352925943836e-01 3.625470995156252485e-01 3.795973190611611203e-01 6.567047810450010736e-01 1.484039742710284715e-01 9.273251916560719676e-01 4.334256728976307871e-01 6.734771102219323513e-01 9.125080197222198430e-01 4.974393931097168542e-01 8.301481563280355136e-01 4.526450714147856047e-01 2.414236092573898151e-01 8.070129698367667359e-02 7.260400697427102923e-01 1.396509691839398215e-02 2.496450588391967429e-01 4.335741205447194435e-01 3.089314419194891803e-01 9.543503534526003307e-01 5.457977547458532364e-01 3.139663643587058406e-01 5.034762326753475792e-01 4.756788330475764104e-01 6.849334942793482428e-01 3.880666613022351052e-01 6.483446580176778218e-01 5.217503801099343530e-01 5.371145824070304720e-01 3.121260159429154468e-01 8.314121854062171968e-01 4.538695969561833410e-01 8.598896961203845724e-01 9.961993522734106099e-01 8.865717795946430613e-01 7.828987966783660379e-01 3.412415531643435695e-01 7.421170530151157685e-01 4.484104178639959359e-01 6.793217012099640462e-01 3.756179958191659951e-01 7.821287098222597933e-01 6.227726265188193722e-02 8.552983413221663112e-01 4.824668768009222619e-01 2.241531065858231031e-01 4.939536577599041856e-01 5.129566641128722182e-01 1.057984177672518511e-01 9.541452507300716146e-01 3.396646181755047511e-01 7.452588103611947901e-01 5.315559265659929311e-01 5.493475179850665358e-01 5.214824278139198466e-01 5.150075718147916204e-01 1.196075368500321146e-01 9.035665331176232495e-01 7.522653903639873185e-01 6.638708679914825384e-01 5.584174553800479446e-01 5.015819402508836511e-01 5.507698483308445248e-01 5.978677577011723976e-01 8.450418028759657529e-01 3.266677322748618995e-01 1.321610045897971819e-01 2.394354042746985600e-01 2.723972163557076831e-01 5.523301747352814539e-01 5.518043850608547185e-01 5.283968096837132755e-02 8.192733312104071297e-01 2.277106024970321219e-02 1.414998099027269252e-01 6.517281615256080851e-01 1.811694734825117781e-01 9.472370614713256920e-01 5.454497319021770485e-01 1.364119913158231556e-01 8.446142008509562871e-01 7.671725984742419069e-01 2.461161648406858804e-01 1.421724627107351369e-01 6.290652581179481118e-01 7.094144689448004248e-01 4.419656923472803367e-02 6.614741876652251440e-01 8.712193265403500586e-02 4.734931280852430202e-01 5.382037050480286133e-01 1.396459758005891283e-01 +9.709329844415439670e-01 8.998575745276288229e-01 9.151313462895852568e-01 6.920489275523904471e-01 2.892231405199537919e-01 6.750679746268205550e-01 5.515642485826798280e-01 1.065253097812824956e-01 2.957026803465776510e-01 8.937347659632134400e-01 9.800016515925590310e-01 7.745900896182087436e-01 1.570977683146633774e-01 1.482028765821026273e-01 2.111147779712029271e-01 9.683759902485811200e-01 6.550951580826911425e-01 8.728324682592377703e-01 5.044803166579884257e-01 8.285704754811143991e-01 1.693574499337324735e-02 6.032669995180495182e-02 1.687026879086964692e-01 7.701554026145973619e-01 1.429888016593102718e-01 5.881172815379975827e-02 9.704206919487038396e-01 4.450807650730836951e-01 1.597445784258376689e-01 9.849229394397314152e-01 4.220083573536804744e-01 9.357693600374825671e-01 2.313199262338369033e-01 4.556443403861323294e-01 2.590791012828855822e-01 8.438664994487065085e-01 5.519045677502344427e-01 4.702170125676508050e-01 6.814723205638187897e-01 7.418295483665861001e-01 3.684921032028853904e-01 1.501895844844561845e-01 4.214513377519605308e-01 8.600279963652578408e-01 6.625616611189292238e-01 5.200151456470966105e-01 7.881072743086801058e-01 2.771703241081423519e-01 9.034135930616548071e-01 5.848441705791300738e-01 8.341698181274771473e-01 1.966638677318299777e-01 7.059747894371543042e-01 7.013854316067694716e-01 1.828430942760242983e-01 4.745548949934464966e-01 6.306422394641082452e-01 7.760751707194470939e-01 9.813187212598396547e-01 2.293595795266353266e-01 7.749261876107090830e-01 2.384106107787011819e-01 9.721209688979495223e-01 2.715569353686980714e-01 2.915573577694993146e-01 3.579601509630966349e-01 3.085697512342830962e-01 4.070219981627976047e-01 1.989632411372218579e-01 7.330003339460906542e-01 5.397259604481572381e-01 6.931009942216573849e-01 1.385457419653816080e-01 1.140339999976658358e-01 3.980752590866034613e-01 9.471822621683767540e-01 5.476643721405823895e-01 6.824131903515884279e-02 5.844099130744569992e-01 2.346881692012994236e-01 9.436439228519653000e-01 4.855518260479008141e-02 8.157036123302675579e-01 1.169761256455048581e-01 5.532962903488753970e-01 1.100965596251435308e-01 9.789490602992410029e-01 8.433487462016989733e-01 1.272410782852178013e-01 2.885715258680641160e-01 7.990943955388217779e-01 1.565305358979097727e-01 9.160846960406943129e-02 8.521842244411678147e-01 4.474243106736998099e-01 3.843945818845087015e-01 4.710645906071458944e-01 2.398348154123419729e-01 6.435351435258193087e-01 7.656897921129046658e-01 +4.894328120406804539e-01 7.881019629214267574e-01 6.974585354155089512e-01 2.023858939857701156e-01 1.660984914264745926e-01 4.854517801734643534e-01 2.789848572630315715e-01 2.311636522410289718e-01 9.821076233980715608e-01 1.220641257408076052e-01 2.614036146663852866e-01 7.657560715165320220e-01 3.968360577545695378e-01 4.566023622802184434e-02 1.049701948619241598e-02 9.281162949127452766e-01 4.490137965769909201e-01 2.095846458383606725e-01 9.195504656719085679e-01 9.683515436855471004e-01 9.800174878114910060e-01 5.517610861380117804e-01 6.711570559348770670e-01 5.125258050287277989e-01 2.105581493613526423e-01 8.281813206544574868e-01 4.964783994807770995e-01 7.284974208756571645e-01 1.320629592816270348e-01 6.652194518096135045e-01 9.430156297917950958e-01 7.477263137894260003e-01 2.054087806450300979e-01 4.248209124837907247e-01 7.657518666018259257e-02 1.031614100713345028e-01 4.122242287567021712e-01 4.919658859336810686e-01 3.752650167259050651e-01 4.175771429986683270e-01 6.131376293448997927e-01 5.463797405837259591e-01 3.119918548921774004e-01 6.331762507678504459e-01 5.484632429281035559e-01 6.815448032785871302e-01 8.065695507425107991e-02 8.720129122297424207e-01 8.318188557125294480e-03 2.199323537180564170e-02 8.933872719887463454e-01 1.953120287872067706e-02 2.478721941404590234e-01 5.994061179859005994e-01 6.588362611693047155e-01 6.332808851020984564e-01 3.823849348043323326e-01 5.111091324899629251e-01 7.034808459110406531e-01 4.347681568463539481e-01 4.316973576672314961e-01 9.620411080123215664e-01 6.247837467655984467e-01 8.196961678222113301e-01 5.574601810887074294e-01 8.800635018469276094e-01 8.772255241161972528e-01 5.075275933138404527e-01 8.022583187266906224e-01 2.320670802521890286e-01 1.165626629103270195e-01 4.623759662685936744e-01 7.938327000737943617e-02 7.986374689793115378e-01 6.728842751465858862e-01 8.133909095059230765e-01 1.202639390769081329e-01 1.052937257108800262e-01 8.717600467040409473e-02 2.163819956545051104e-01 6.596483385763984852e-01 1.202843170392309258e-02 1.538789195854695091e-01 3.120247727263308901e-01 3.408168327248596308e-01 3.241861797851740556e-01 3.637074533655986208e-01 1.533669345890729119e-01 4.455921334699539660e-01 5.619140093874478437e-01 1.881731359879111887e-01 9.416670800570559052e-01 1.740018593664415247e-01 7.030242331869680505e-01 5.922055553954849172e-01 9.326211623391688077e-01 6.608322881013140027e-01 7.009721551241574478e-01 1.079126054675583202e-01 6.158176671761947940e-01 +5.185079639625639336e-01 9.613742991518259284e-01 5.555312825626229634e-01 2.647628827924735084e-01 6.003697207460141350e-01 5.392112376769145898e-01 6.781186965667050925e-01 9.908971748181496508e-01 4.124155872095397468e-01 9.814941401724619485e-02 2.684237785531295994e-02 1.774652505962848181e-01 1.707589529595294753e-01 4.640932098465534450e-01 2.882179883914587348e-01 7.276822905806898945e-01 6.145789546745269449e-01 1.100959863917608805e-01 6.798859723042820491e-01 9.096984032948918220e-01 3.971368455178179158e-01 2.959494950971321980e-01 3.742088799298171065e-02 1.960739526210202310e-01 7.536102695342027369e-01 6.680915510628401277e-01 4.136507204312135366e-01 3.613996339406737590e-01 3.605422038261204554e-01 7.098503555159476619e-01 8.093719147087541366e-01 6.344097009128880638e-01 3.990082448083617228e-01 2.805918009906902544e-01 7.078488167363675698e-01 9.969917259866583059e-01 9.442054998992396309e-01 1.329075240769165278e-01 6.810681350588387861e-02 8.503491437913293094e-01 8.347117439165431252e-01 2.381858201903953587e-01 7.884260706938626129e-01 7.109907917419661105e-01 6.390916681983604963e-02 6.174365227062991179e-01 5.085733343630816083e-01 1.716846139694149231e-01 9.065664924270055991e-02 5.625330757196970177e-01 3.539663480209681579e-01 8.937139525947165319e-01 3.981380511900556307e-02 7.403597927449541150e-01 3.803872284089604427e-02 6.729519695709765825e-01 5.306080908840085097e-01 2.091237680402112664e-01 5.902903662907804661e-01 2.094778612095482551e-01 7.323447855684165342e-01 3.644574495843493356e-01 2.006215478057034041e-01 3.737617545555030896e-01 5.253471759602216240e-01 4.287889547869583318e-01 7.086098806190446187e-01 4.510792335515292351e-01 6.383187180169215269e-01 8.779355722397681472e-01 4.221338898667141848e-01 6.375840144651815367e-01 8.683057298299173832e-01 6.093730356952498095e-01 9.297141161056151626e-01 7.770838342807246946e-01 6.549661287008456956e-02 2.835060738158660110e-01 4.474138867374952699e-01 8.530336387421445510e-01 3.160209657891883683e-01 8.301538680518486535e-01 6.646903097549101691e-01 7.187130118106234145e-01 1.651862041735395747e-01 9.578252676762609719e-01 6.490273812885494209e-02 9.777273484666341163e-01 8.930729829254262508e-01 9.851054752118463265e-01 4.094323402286751401e-01 1.139176240124337713e-01 7.612865863899589414e-01 2.266379302491570158e-01 6.998882496157835531e-01 9.945043379099228753e-01 7.111578056749194854e-01 7.806190603886183910e-01 3.410170920712443099e-01 9.446084168886822452e-01 +5.015172758330755931e-01 5.569527971282052237e-01 1.122406928736449094e-01 8.960352822124777461e-01 6.049568585854003810e-02 1.202196001338627918e-01 1.870314295763603196e-01 9.017590029396971296e-01 3.597904628087450485e-01 2.130941062746317671e-01 2.556281834629479111e-01 5.123669364829196438e-01 4.754061129282013409e-01 9.764470380372083369e-01 8.038663983900646848e-01 6.960491266420890666e-01 2.940135977911654264e-01 2.857282759910040326e-03 4.599343225832352999e-02 5.597554495210212977e-01 7.445266674304001908e-01 3.387528030535971180e-01 6.429542922125383031e-01 2.123331785532429627e-01 5.302332654117811739e-01 7.262555377662539557e-01 3.982425859900724507e-01 3.243388301740235402e-01 6.191064123738921898e-01 8.988047781373914580e-01 7.819700328765150088e-01 7.664269102804815992e-01 6.734095355422575757e-03 2.904762329148526945e-01 5.097537644843168625e-01 9.524734606001823423e-01 4.812869576591960463e-01 6.236868013640477493e-01 1.459170943214320726e-01 9.874505139403206844e-01 7.561708982837871407e-01 3.798591332432484924e-01 6.056633451375117438e-01 7.935708170258731764e-01 1.458141583518740569e-01 7.082511296391911237e-01 1.098798009731616343e-02 3.655618484905173160e-01 9.551862303858617009e-01 8.148959351152762487e-02 4.739306219219985294e-02 7.963357515359494876e-01 6.208332695202813944e-01 3.884182264923189409e-01 4.589167647950288531e-01 6.496652974138312775e-01 2.467528128074852889e-01 5.309593064844935206e-01 5.364606369543487574e-01 2.421352989851309756e-01 3.776834556696828660e-02 1.564861233558080267e-01 5.197231021782636740e-01 8.725375120634637494e-01 2.441225493455024820e-01 2.320363366041028330e-01 5.026358683423555185e-01 7.035766000474735771e-01 8.347805591467084563e-01 2.303229841813967393e-01 6.908373419683054850e-01 2.646662377366995056e-01 1.259467197942290007e-01 9.372770922994989595e-01 6.674216272867254940e-01 1.027944489143072238e-01 5.686267290346079806e-01 3.948222804451942958e-01 4.689706944496729868e-01 4.446117700449114807e-02 6.817992275557515081e-01 9.084821829413957106e-01 9.184021015315092518e-01 3.045815734169987632e-01 2.204958624923980537e-03 7.542672057172502553e-01 9.460844786545006269e-01 3.373139094575949848e-02 9.059565314915285494e-01 9.938525461318854504e-01 2.542072661725306437e-01 9.685734112479216229e-02 8.223629541824816203e-01 1.057429056898460118e-01 8.080679390260248063e-01 5.823014244609205914e-01 6.413551528031806725e-01 1.787341975438894170e-01 1.250471413912357388e-01 8.390281297596062782e-01 diff --git a/shared/package-files/d1/d12ee45a23c42919a2d224bc250dcae530a1cd2a59361026d668f25d081a513f/blob b/shared/package-files/d1/d12ee45a23c42919a2d224bc250dcae530a1cd2a59361026d668f25d081a513f/blob new file mode 100644 index 0000000000000000000000000000000000000000..a03572ce2dc1567ec8a6d2b36881b4f9ec3ad7d2 --- /dev/null +++ b/shared/package-files/d1/d12ee45a23c42919a2d224bc250dcae530a1cd2a59361026d668f25d081a513f/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API ::std::tuple _grid_sampler_2d_cpu_fallback_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/d1/d1324a6081d2205c907151d97481d9d7d6fbb6ab2dfec63b899c232b372f6413/blob b/shared/package-files/d1/d1324a6081d2205c907151d97481d9d7d6fbb6ab2dfec63b899c232b372f6413/blob new file mode 100644 index 0000000000000000000000000000000000000000..b4b2597a72b500155370db385b58e61f0f951984 --- /dev/null +++ b/shared/package-files/d1/d1324a6081d2205c907151d97481d9d7d6fbb6ab2dfec63b899c232b372f6413/blob @@ -0,0 +1,1615 @@ +""" +Do NOT manually edit this file. +Instead, run ./bin/ask_update.py. +""" + +defined_facts = [ + 'algebraic', + 'antihermitian', + 'commutative', + 'complex', + 'composite', + 'even', + 'extended_negative', + 'extended_nonnegative', + 'extended_nonpositive', + 'extended_nonzero', + 'extended_positive', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'integer', + 'irrational', + 'negative', + 'noninteger', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'odd', + 'positive', + 'prime', + 'rational', + 'real', + 'transcendental', + 'zero', +] # defined_facts + + +full_implications = dict( [ + # Implications of algebraic = True: + (('algebraic', True), set( ( + ('commutative', True), + ('complex', True), + ('finite', True), + ('infinite', False), + ('transcendental', False), + ) ), + ), + # Implications of algebraic = False: + (('algebraic', False), set( ( + ('composite', False), + ('even', False), + ('integer', False), + ('odd', False), + ('prime', False), + ('rational', False), + ('zero', False), + ) ), + ), + # Implications of antihermitian = True: + (('antihermitian', True), set( ( + ) ), + ), + # Implications of antihermitian = False: + (('antihermitian', False), set( ( + ('imaginary', False), + ) ), + ), + # Implications of commutative = True: + (('commutative', True), set( ( + ) ), + ), + # Implications of commutative = False: + (('commutative', False), set( ( + ('algebraic', False), + ('complex', False), + ('composite', False), + ('even', False), + ('extended_negative', False), + ('extended_nonnegative', False), + ('extended_nonpositive', False), + ('extended_nonzero', False), + ('extended_positive', False), + ('extended_real', False), + ('imaginary', False), + ('integer', False), + ('irrational', False), + ('negative', False), + ('noninteger', False), + ('nonnegative', False), + ('nonpositive', False), + ('nonzero', False), + ('odd', False), + ('positive', False), + ('prime', False), + ('rational', False), + ('real', False), + ('transcendental', False), + ('zero', False), + ) ), + ), + # Implications of complex = True: + (('complex', True), set( ( + ('commutative', True), + ('finite', True), + ('infinite', False), + ) ), + ), + # Implications of complex = False: + (('complex', False), set( ( + ('algebraic', False), + ('composite', False), + ('even', False), + ('imaginary', False), + ('integer', False), + ('irrational', False), + ('negative', False), + ('nonnegative', False), + ('nonpositive', False), + ('nonzero', False), + ('odd', False), + ('positive', False), + ('prime', False), + ('rational', False), + ('real', False), + ('transcendental', False), + ('zero', False), + ) ), + ), + # Implications of composite = True: + (('composite', True), set( ( + ('algebraic', True), + ('commutative', True), + ('complex', True), + ('extended_negative', False), + ('extended_nonnegative', True), + ('extended_nonpositive', False), + ('extended_nonzero', True), + ('extended_positive', True), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ('integer', True), + ('irrational', False), + ('negative', False), + ('noninteger', False), + ('nonnegative', True), + ('nonpositive', False), + ('nonzero', True), + ('positive', True), + ('prime', False), + ('rational', True), + ('real', True), + ('transcendental', False), + ('zero', False), + ) ), + ), + # Implications of composite = False: + (('composite', False), set( ( + ) ), + ), + # Implications of even = True: + (('even', True), set( ( + ('algebraic', True), + ('commutative', True), + ('complex', True), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ('integer', True), + ('irrational', False), + ('noninteger', False), + ('odd', False), + ('rational', True), + ('real', True), + ('transcendental', False), + ) ), + ), + # Implications of even = False: + (('even', False), set( ( + ('zero', False), + ) ), + ), + # Implications of extended_negative = True: + (('extended_negative', True), set( ( + ('commutative', True), + ('composite', False), + ('extended_nonnegative', False), + ('extended_nonpositive', True), + ('extended_nonzero', True), + ('extended_positive', False), + ('extended_real', True), + ('imaginary', False), + ('nonnegative', False), + ('positive', False), + ('prime', False), + ('zero', False), + ) ), + ), + # Implications of extended_negative = False: + (('extended_negative', False), set( ( + ('negative', False), + ) ), + ), + # Implications of extended_nonnegative = True: + (('extended_nonnegative', True), set( ( + ('commutative', True), + ('extended_negative', False), + ('extended_real', True), + ('imaginary', False), + ('negative', False), + ) ), + ), + # Implications of extended_nonnegative = False: + (('extended_nonnegative', False), set( ( + ('composite', False), + ('extended_positive', False), + ('nonnegative', False), + ('positive', False), + ('prime', False), + ('zero', False), + ) ), + ), + # Implications of extended_nonpositive = True: + (('extended_nonpositive', True), set( ( + ('commutative', True), + ('composite', False), + ('extended_positive', False), + ('extended_real', True), + ('imaginary', False), + ('positive', False), + ('prime', False), + ) ), + ), + # Implications of extended_nonpositive = False: + (('extended_nonpositive', False), set( ( + ('extended_negative', False), + ('negative', False), + ('nonpositive', False), + ('zero', False), + ) ), + ), + # Implications of extended_nonzero = True: + (('extended_nonzero', True), set( ( + ('commutative', True), + ('extended_real', True), + ('imaginary', False), + ('zero', False), + ) ), + ), + # Implications of extended_nonzero = False: + (('extended_nonzero', False), set( ( + ('composite', False), + ('extended_negative', False), + ('extended_positive', False), + ('negative', False), + ('nonzero', False), + ('positive', False), + ('prime', False), + ) ), + ), + # Implications of extended_positive = True: + (('extended_positive', True), set( ( + ('commutative', True), + ('extended_negative', False), + ('extended_nonnegative', True), + ('extended_nonpositive', False), + ('extended_nonzero', True), + ('extended_real', True), + ('imaginary', False), + ('negative', False), + ('nonpositive', False), + ('zero', False), + ) ), + ), + # Implications of extended_positive = False: + (('extended_positive', False), set( ( + ('composite', False), + ('positive', False), + ('prime', False), + ) ), + ), + # Implications of extended_real = True: + (('extended_real', True), set( ( + ('commutative', True), + ('imaginary', False), + ) ), + ), + # Implications of extended_real = False: + (('extended_real', False), set( ( + ('composite', False), + ('even', False), + ('extended_negative', False), + ('extended_nonnegative', False), + ('extended_nonpositive', False), + ('extended_nonzero', False), + ('extended_positive', False), + ('integer', False), + ('irrational', False), + ('negative', False), + ('noninteger', False), + ('nonnegative', False), + ('nonpositive', False), + ('nonzero', False), + ('odd', False), + ('positive', False), + ('prime', False), + ('rational', False), + ('real', False), + ('zero', False), + ) ), + ), + # Implications of finite = True: + (('finite', True), set( ( + ('infinite', False), + ) ), + ), + # Implications of finite = False: + (('finite', False), set( ( + ('algebraic', False), + ('complex', False), + ('composite', False), + ('even', False), + ('imaginary', False), + ('infinite', True), + ('integer', False), + ('irrational', False), + ('negative', False), + ('nonnegative', False), + ('nonpositive', False), + ('nonzero', False), + ('odd', False), + ('positive', False), + ('prime', False), + ('rational', False), + ('real', False), + ('transcendental', False), + ('zero', False), + ) ), + ), + # Implications of hermitian = True: + (('hermitian', True), set( ( + ) ), + ), + # Implications of hermitian = False: + (('hermitian', False), set( ( + ('composite', False), + ('even', False), + ('integer', False), + ('irrational', False), + ('negative', False), + ('nonnegative', False), + ('nonpositive', False), + ('nonzero', False), + ('odd', False), + ('positive', False), + ('prime', False), + ('rational', False), + ('real', False), + ('zero', False), + ) ), + ), + # Implications of imaginary = True: + (('imaginary', True), set( ( + ('antihermitian', True), + ('commutative', True), + ('complex', True), + ('composite', False), + ('even', False), + ('extended_negative', False), + ('extended_nonnegative', False), + ('extended_nonpositive', False), + ('extended_nonzero', False), + ('extended_positive', False), + ('extended_real', False), + ('finite', True), + ('infinite', False), + ('integer', False), + ('irrational', False), + ('negative', False), + ('noninteger', False), + ('nonnegative', False), + ('nonpositive', False), + ('nonzero', False), + ('odd', False), + ('positive', False), + ('prime', False), + ('rational', False), + ('real', False), + ('zero', False), + ) ), + ), + # Implications of imaginary = False: + (('imaginary', False), set( ( + ) ), + ), + # Implications of infinite = True: + (('infinite', True), set( ( + ('algebraic', False), + ('complex', False), + ('composite', False), + ('even', False), + ('finite', False), + ('imaginary', False), + ('integer', False), + ('irrational', False), + ('negative', False), + ('nonnegative', False), + ('nonpositive', False), + ('nonzero', False), + ('odd', False), + ('positive', False), + ('prime', False), + ('rational', False), + ('real', False), + ('transcendental', False), + ('zero', False), + ) ), + ), + # Implications of infinite = False: + (('infinite', False), set( ( + ('finite', True), + ) ), + ), + # Implications of integer = True: + (('integer', True), set( ( + ('algebraic', True), + ('commutative', True), + ('complex', True), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ('irrational', False), + ('noninteger', False), + ('rational', True), + ('real', True), + ('transcendental', False), + ) ), + ), + # Implications of integer = False: + (('integer', False), set( ( + ('composite', False), + ('even', False), + ('odd', False), + ('prime', False), + ('zero', False), + ) ), + ), + # Implications of irrational = True: + (('irrational', True), set( ( + ('commutative', True), + ('complex', True), + ('composite', False), + ('even', False), + ('extended_nonzero', True), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ('integer', False), + ('noninteger', True), + ('nonzero', True), + ('odd', False), + ('prime', False), + ('rational', False), + ('real', True), + ('zero', False), + ) ), + ), + # Implications of irrational = False: + (('irrational', False), set( ( + ) ), + ), + # Implications of negative = True: + (('negative', True), set( ( + ('commutative', True), + ('complex', True), + ('composite', False), + ('extended_negative', True), + ('extended_nonnegative', False), + ('extended_nonpositive', True), + ('extended_nonzero', True), + ('extended_positive', False), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ('nonnegative', False), + ('nonpositive', True), + ('nonzero', True), + ('positive', False), + ('prime', False), + ('real', True), + ('zero', False), + ) ), + ), + # Implications of negative = False: + (('negative', False), set( ( + ) ), + ), + # Implications of noninteger = True: + (('noninteger', True), set( ( + ('commutative', True), + ('composite', False), + ('even', False), + ('extended_nonzero', True), + ('extended_real', True), + ('imaginary', False), + ('integer', False), + ('odd', False), + ('prime', False), + ('zero', False), + ) ), + ), + # Implications of noninteger = False: + (('noninteger', False), set( ( + ) ), + ), + # Implications of nonnegative = True: + (('nonnegative', True), set( ( + ('commutative', True), + ('complex', True), + ('extended_negative', False), + ('extended_nonnegative', True), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ('negative', False), + ('real', True), + ) ), + ), + # Implications of nonnegative = False: + (('nonnegative', False), set( ( + ('composite', False), + ('positive', False), + ('prime', False), + ('zero', False), + ) ), + ), + # Implications of nonpositive = True: + (('nonpositive', True), set( ( + ('commutative', True), + ('complex', True), + ('composite', False), + ('extended_nonpositive', True), + ('extended_positive', False), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ('positive', False), + ('prime', False), + ('real', True), + ) ), + ), + # Implications of nonpositive = False: + (('nonpositive', False), set( ( + ('negative', False), + ('zero', False), + ) ), + ), + # Implications of nonzero = True: + (('nonzero', True), set( ( + ('commutative', True), + ('complex', True), + ('extended_nonzero', True), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ('real', True), + ('zero', False), + ) ), + ), + # Implications of nonzero = False: + (('nonzero', False), set( ( + ('composite', False), + ('negative', False), + ('positive', False), + ('prime', False), + ) ), + ), + # Implications of odd = True: + (('odd', True), set( ( + ('algebraic', True), + ('commutative', True), + ('complex', True), + ('even', False), + ('extended_nonzero', True), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ('integer', True), + ('irrational', False), + ('noninteger', False), + ('nonzero', True), + ('rational', True), + ('real', True), + ('transcendental', False), + ('zero', False), + ) ), + ), + # Implications of odd = False: + (('odd', False), set( ( + ) ), + ), + # Implications of positive = True: + (('positive', True), set( ( + ('commutative', True), + ('complex', True), + ('extended_negative', False), + ('extended_nonnegative', True), + ('extended_nonpositive', False), + ('extended_nonzero', True), + ('extended_positive', True), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ('negative', False), + ('nonnegative', True), + ('nonpositive', False), + ('nonzero', True), + ('real', True), + ('zero', False), + ) ), + ), + # Implications of positive = False: + (('positive', False), set( ( + ('composite', False), + ('prime', False), + ) ), + ), + # Implications of prime = True: + (('prime', True), set( ( + ('algebraic', True), + ('commutative', True), + ('complex', True), + ('composite', False), + ('extended_negative', False), + ('extended_nonnegative', True), + ('extended_nonpositive', False), + ('extended_nonzero', True), + ('extended_positive', True), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ('integer', True), + ('irrational', False), + ('negative', False), + ('noninteger', False), + ('nonnegative', True), + ('nonpositive', False), + ('nonzero', True), + ('positive', True), + ('rational', True), + ('real', True), + ('transcendental', False), + ('zero', False), + ) ), + ), + # Implications of prime = False: + (('prime', False), set( ( + ) ), + ), + # Implications of rational = True: + (('rational', True), set( ( + ('algebraic', True), + ('commutative', True), + ('complex', True), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ('irrational', False), + ('real', True), + ('transcendental', False), + ) ), + ), + # Implications of rational = False: + (('rational', False), set( ( + ('composite', False), + ('even', False), + ('integer', False), + ('odd', False), + ('prime', False), + ('zero', False), + ) ), + ), + # Implications of real = True: + (('real', True), set( ( + ('commutative', True), + ('complex', True), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ) ), + ), + # Implications of real = False: + (('real', False), set( ( + ('composite', False), + ('even', False), + ('integer', False), + ('irrational', False), + ('negative', False), + ('nonnegative', False), + ('nonpositive', False), + ('nonzero', False), + ('odd', False), + ('positive', False), + ('prime', False), + ('rational', False), + ('zero', False), + ) ), + ), + # Implications of transcendental = True: + (('transcendental', True), set( ( + ('algebraic', False), + ('commutative', True), + ('complex', True), + ('composite', False), + ('even', False), + ('finite', True), + ('infinite', False), + ('integer', False), + ('odd', False), + ('prime', False), + ('rational', False), + ('zero', False), + ) ), + ), + # Implications of transcendental = False: + (('transcendental', False), set( ( + ) ), + ), + # Implications of zero = True: + (('zero', True), set( ( + ('algebraic', True), + ('commutative', True), + ('complex', True), + ('composite', False), + ('even', True), + ('extended_negative', False), + ('extended_nonnegative', True), + ('extended_nonpositive', True), + ('extended_nonzero', False), + ('extended_positive', False), + ('extended_real', True), + ('finite', True), + ('hermitian', True), + ('imaginary', False), + ('infinite', False), + ('integer', True), + ('irrational', False), + ('negative', False), + ('noninteger', False), + ('nonnegative', True), + ('nonpositive', True), + ('nonzero', False), + ('odd', False), + ('positive', False), + ('prime', False), + ('rational', True), + ('real', True), + ('transcendental', False), + ) ), + ), + # Implications of zero = False: + (('zero', False), set( ( + ) ), + ), + ] ) # full_implications + + +prereq = { + + # facts that could determine the value of algebraic + 'algebraic': { + 'commutative', + 'complex', + 'composite', + 'even', + 'finite', + 'infinite', + 'integer', + 'odd', + 'prime', + 'rational', + 'transcendental', + 'zero', + }, + + # facts that could determine the value of antihermitian + 'antihermitian': { + 'imaginary', + }, + + # facts that could determine the value of commutative + 'commutative': { + 'algebraic', + 'complex', + 'composite', + 'even', + 'extended_negative', + 'extended_nonnegative', + 'extended_nonpositive', + 'extended_nonzero', + 'extended_positive', + 'extended_real', + 'imaginary', + 'integer', + 'irrational', + 'negative', + 'noninteger', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'odd', + 'positive', + 'prime', + 'rational', + 'real', + 'transcendental', + 'zero', + }, + + # facts that could determine the value of complex + 'complex': { + 'algebraic', + 'commutative', + 'composite', + 'even', + 'finite', + 'imaginary', + 'infinite', + 'integer', + 'irrational', + 'negative', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'odd', + 'positive', + 'prime', + 'rational', + 'real', + 'transcendental', + 'zero', + }, + + # facts that could determine the value of composite + 'composite': { + 'algebraic', + 'commutative', + 'complex', + 'extended_negative', + 'extended_nonnegative', + 'extended_nonpositive', + 'extended_nonzero', + 'extended_positive', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'integer', + 'irrational', + 'negative', + 'noninteger', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'positive', + 'prime', + 'rational', + 'real', + 'transcendental', + 'zero', + }, + + # facts that could determine the value of even + 'even': { + 'algebraic', + 'commutative', + 'complex', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'integer', + 'irrational', + 'noninteger', + 'odd', + 'rational', + 'real', + 'transcendental', + 'zero', + }, + + # facts that could determine the value of extended_negative + 'extended_negative': { + 'commutative', + 'composite', + 'extended_nonnegative', + 'extended_nonpositive', + 'extended_nonzero', + 'extended_positive', + 'extended_real', + 'imaginary', + 'negative', + 'nonnegative', + 'positive', + 'prime', + 'zero', + }, + + # facts that could determine the value of extended_nonnegative + 'extended_nonnegative': { + 'commutative', + 'composite', + 'extended_negative', + 'extended_positive', + 'extended_real', + 'imaginary', + 'negative', + 'nonnegative', + 'positive', + 'prime', + 'zero', + }, + + # facts that could determine the value of extended_nonpositive + 'extended_nonpositive': { + 'commutative', + 'composite', + 'extended_negative', + 'extended_positive', + 'extended_real', + 'imaginary', + 'negative', + 'nonpositive', + 'positive', + 'prime', + 'zero', + }, + + # facts that could determine the value of extended_nonzero + 'extended_nonzero': { + 'commutative', + 'composite', + 'extended_negative', + 'extended_positive', + 'extended_real', + 'imaginary', + 'irrational', + 'negative', + 'noninteger', + 'nonzero', + 'odd', + 'positive', + 'prime', + 'zero', + }, + + # facts that could determine the value of extended_positive + 'extended_positive': { + 'commutative', + 'composite', + 'extended_negative', + 'extended_nonnegative', + 'extended_nonpositive', + 'extended_nonzero', + 'extended_real', + 'imaginary', + 'negative', + 'nonpositive', + 'positive', + 'prime', + 'zero', + }, + + # facts that could determine the value of extended_real + 'extended_real': { + 'commutative', + 'composite', + 'even', + 'extended_negative', + 'extended_nonnegative', + 'extended_nonpositive', + 'extended_nonzero', + 'extended_positive', + 'imaginary', + 'integer', + 'irrational', + 'negative', + 'noninteger', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'odd', + 'positive', + 'prime', + 'rational', + 'real', + 'zero', + }, + + # facts that could determine the value of finite + 'finite': { + 'algebraic', + 'complex', + 'composite', + 'even', + 'imaginary', + 'infinite', + 'integer', + 'irrational', + 'negative', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'odd', + 'positive', + 'prime', + 'rational', + 'real', + 'transcendental', + 'zero', + }, + + # facts that could determine the value of hermitian + 'hermitian': { + 'composite', + 'even', + 'integer', + 'irrational', + 'negative', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'odd', + 'positive', + 'prime', + 'rational', + 'real', + 'zero', + }, + + # facts that could determine the value of imaginary + 'imaginary': { + 'antihermitian', + 'commutative', + 'complex', + 'composite', + 'even', + 'extended_negative', + 'extended_nonnegative', + 'extended_nonpositive', + 'extended_nonzero', + 'extended_positive', + 'extended_real', + 'finite', + 'infinite', + 'integer', + 'irrational', + 'negative', + 'noninteger', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'odd', + 'positive', + 'prime', + 'rational', + 'real', + 'zero', + }, + + # facts that could determine the value of infinite + 'infinite': { + 'algebraic', + 'complex', + 'composite', + 'even', + 'finite', + 'imaginary', + 'integer', + 'irrational', + 'negative', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'odd', + 'positive', + 'prime', + 'rational', + 'real', + 'transcendental', + 'zero', + }, + + # facts that could determine the value of integer + 'integer': { + 'algebraic', + 'commutative', + 'complex', + 'composite', + 'even', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'irrational', + 'noninteger', + 'odd', + 'prime', + 'rational', + 'real', + 'transcendental', + 'zero', + }, + + # facts that could determine the value of irrational + 'irrational': { + 'commutative', + 'complex', + 'composite', + 'even', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'integer', + 'odd', + 'prime', + 'rational', + 'real', + 'zero', + }, + + # facts that could determine the value of negative + 'negative': { + 'commutative', + 'complex', + 'composite', + 'extended_negative', + 'extended_nonnegative', + 'extended_nonpositive', + 'extended_nonzero', + 'extended_positive', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'positive', + 'prime', + 'real', + 'zero', + }, + + # facts that could determine the value of noninteger + 'noninteger': { + 'commutative', + 'composite', + 'even', + 'extended_real', + 'imaginary', + 'integer', + 'irrational', + 'odd', + 'prime', + 'zero', + }, + + # facts that could determine the value of nonnegative + 'nonnegative': { + 'commutative', + 'complex', + 'composite', + 'extended_negative', + 'extended_nonnegative', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'negative', + 'positive', + 'prime', + 'real', + 'zero', + }, + + # facts that could determine the value of nonpositive + 'nonpositive': { + 'commutative', + 'complex', + 'composite', + 'extended_nonpositive', + 'extended_positive', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'negative', + 'positive', + 'prime', + 'real', + 'zero', + }, + + # facts that could determine the value of nonzero + 'nonzero': { + 'commutative', + 'complex', + 'composite', + 'extended_nonzero', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'irrational', + 'negative', + 'odd', + 'positive', + 'prime', + 'real', + 'zero', + }, + + # facts that could determine the value of odd + 'odd': { + 'algebraic', + 'commutative', + 'complex', + 'even', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'integer', + 'irrational', + 'noninteger', + 'rational', + 'real', + 'transcendental', + 'zero', + }, + + # facts that could determine the value of positive + 'positive': { + 'commutative', + 'complex', + 'composite', + 'extended_negative', + 'extended_nonnegative', + 'extended_nonpositive', + 'extended_nonzero', + 'extended_positive', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'negative', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'prime', + 'real', + 'zero', + }, + + # facts that could determine the value of prime + 'prime': { + 'algebraic', + 'commutative', + 'complex', + 'composite', + 'extended_negative', + 'extended_nonnegative', + 'extended_nonpositive', + 'extended_nonzero', + 'extended_positive', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'integer', + 'irrational', + 'negative', + 'noninteger', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'positive', + 'rational', + 'real', + 'transcendental', + 'zero', + }, + + # facts that could determine the value of rational + 'rational': { + 'algebraic', + 'commutative', + 'complex', + 'composite', + 'even', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'integer', + 'irrational', + 'odd', + 'prime', + 'real', + 'transcendental', + 'zero', + }, + + # facts that could determine the value of real + 'real': { + 'commutative', + 'complex', + 'composite', + 'even', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'integer', + 'irrational', + 'negative', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'odd', + 'positive', + 'prime', + 'rational', + 'zero', + }, + + # facts that could determine the value of transcendental + 'transcendental': { + 'algebraic', + 'commutative', + 'complex', + 'composite', + 'even', + 'finite', + 'infinite', + 'integer', + 'odd', + 'prime', + 'rational', + 'zero', + }, + + # facts that could determine the value of zero + 'zero': { + 'algebraic', + 'commutative', + 'complex', + 'composite', + 'even', + 'extended_negative', + 'extended_nonnegative', + 'extended_nonpositive', + 'extended_nonzero', + 'extended_positive', + 'extended_real', + 'finite', + 'hermitian', + 'imaginary', + 'infinite', + 'integer', + 'irrational', + 'negative', + 'noninteger', + 'nonnegative', + 'nonpositive', + 'nonzero', + 'odd', + 'positive', + 'prime', + 'rational', + 'real', + 'transcendental', + }, + +} # prereq + + +# Note: the order of the beta rules is used in the beta_triggers +beta_rules = [ + + # Rules implying composite = True + ({('even', True), ('positive', True), ('prime', False)}, + ('composite', True)), + + # Rules implying even = False + ({('composite', False), ('positive', True), ('prime', False)}, + ('even', False)), + + # Rules implying even = True + ({('integer', True), ('odd', False)}, + ('even', True)), + + # Rules implying extended_negative = True + ({('extended_positive', False), ('extended_real', True), ('zero', False)}, + ('extended_negative', True)), + ({('extended_nonpositive', True), ('extended_nonzero', True)}, + ('extended_negative', True)), + + # Rules implying extended_nonnegative = True + ({('extended_negative', False), ('extended_real', True)}, + ('extended_nonnegative', True)), + + # Rules implying extended_nonpositive = True + ({('extended_positive', False), ('extended_real', True)}, + ('extended_nonpositive', True)), + + # Rules implying extended_nonzero = True + ({('extended_real', True), ('zero', False)}, + ('extended_nonzero', True)), + + # Rules implying extended_positive = True + ({('extended_negative', False), ('extended_real', True), ('zero', False)}, + ('extended_positive', True)), + ({('extended_nonnegative', True), ('extended_nonzero', True)}, + ('extended_positive', True)), + + # Rules implying extended_real = False + ({('infinite', False), ('real', False)}, + ('extended_real', False)), + ({('extended_negative', False), ('extended_positive', False), ('zero', False)}, + ('extended_real', False)), + + # Rules implying infinite = True + ({('extended_real', True), ('real', False)}, + ('infinite', True)), + + # Rules implying irrational = True + ({('rational', False), ('real', True)}, + ('irrational', True)), + + # Rules implying negative = True + ({('positive', False), ('real', True), ('zero', False)}, + ('negative', True)), + ({('nonpositive', True), ('nonzero', True)}, + ('negative', True)), + ({('extended_negative', True), ('finite', True)}, + ('negative', True)), + + # Rules implying noninteger = True + ({('extended_real', True), ('integer', False)}, + ('noninteger', True)), + + # Rules implying nonnegative = True + ({('negative', False), ('real', True)}, + ('nonnegative', True)), + ({('extended_nonnegative', True), ('finite', True)}, + ('nonnegative', True)), + + # Rules implying nonpositive = True + ({('positive', False), ('real', True)}, + ('nonpositive', True)), + ({('extended_nonpositive', True), ('finite', True)}, + ('nonpositive', True)), + + # Rules implying nonzero = True + ({('extended_nonzero', True), ('finite', True)}, + ('nonzero', True)), + + # Rules implying odd = True + ({('even', False), ('integer', True)}, + ('odd', True)), + + # Rules implying positive = False + ({('composite', False), ('even', True), ('prime', False)}, + ('positive', False)), + + # Rules implying positive = True + ({('negative', False), ('real', True), ('zero', False)}, + ('positive', True)), + ({('nonnegative', True), ('nonzero', True)}, + ('positive', True)), + ({('extended_positive', True), ('finite', True)}, + ('positive', True)), + + # Rules implying prime = True + ({('composite', False), ('even', True), ('positive', True)}, + ('prime', True)), + + # Rules implying real = False + ({('negative', False), ('positive', False), ('zero', False)}, + ('real', False)), + + # Rules implying real = True + ({('extended_real', True), ('infinite', False)}, + ('real', True)), + ({('extended_real', True), ('finite', True)}, + ('real', True)), + + # Rules implying transcendental = True + ({('algebraic', False), ('complex', True)}, + ('transcendental', True)), + + # Rules implying zero = True + ({('extended_negative', False), ('extended_positive', False), ('extended_real', True)}, + ('zero', True)), + ({('negative', False), ('positive', False), ('real', True)}, + ('zero', True)), + ({('extended_nonnegative', True), ('extended_nonpositive', True)}, + ('zero', True)), + ({('nonnegative', True), ('nonpositive', True)}, + ('zero', True)), + +] # beta_rules +beta_triggers = { + ('algebraic', False): [32, 11, 3, 8, 29, 14, 25, 13, 17, 7], + ('algebraic', True): [10, 30, 31, 27, 16, 21, 19, 22], + ('antihermitian', False): [], + ('commutative', False): [], + ('complex', False): [10, 12, 11, 3, 8, 17, 7], + ('complex', True): [32, 10, 30, 31, 27, 16, 21, 19, 22], + ('composite', False): [1, 28, 24], + ('composite', True): [23, 2], + ('even', False): [23, 11, 3, 8, 29, 14, 25, 7], + ('even', True): [3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 0, 28, 24, 7], + ('extended_negative', False): [11, 33, 8, 5, 29, 34, 25, 18], + ('extended_negative', True): [30, 12, 31, 29, 14, 20, 16, 21, 22, 17], + ('extended_nonnegative', False): [11, 3, 6, 29, 14, 20, 7], + ('extended_nonnegative', True): [30, 12, 31, 33, 8, 9, 6, 29, 34, 25, 18, 19, 35, 17, 7], + ('extended_nonpositive', False): [11, 8, 5, 29, 25, 18, 7], + ('extended_nonpositive', True): [30, 12, 31, 3, 33, 4, 5, 29, 14, 34, 20, 21, 35, 17, 7], + ('extended_nonzero', False): [11, 33, 6, 5, 29, 34, 20, 18], + ('extended_nonzero', True): [30, 12, 31, 3, 8, 4, 9, 6, 5, 29, 14, 25, 22, 17], + ('extended_positive', False): [11, 3, 33, 6, 29, 14, 34, 20], + ('extended_positive', True): [30, 12, 31, 29, 25, 18, 27, 19, 22, 17], + ('extended_real', False): [], + ('extended_real', True): [30, 12, 31, 3, 33, 8, 6, 5, 17, 7], + ('finite', False): [11, 3, 8, 17, 7], + ('finite', True): [10, 30, 31, 27, 16, 21, 19, 22], + ('hermitian', False): [10, 12, 11, 3, 8, 17, 7], + ('imaginary', True): [32], + ('infinite', False): [10, 30, 31, 27, 16, 21, 19, 22], + ('infinite', True): [11, 3, 8, 17, 7], + ('integer', False): [11, 3, 8, 29, 14, 25, 17, 7], + ('integer', True): [23, 2, 3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 7], + ('irrational', True): [32, 3, 8, 4, 9, 6, 5, 14, 25, 15, 26, 20, 18, 27, 16, 21, 19], + ('negative', False): [29, 34, 25, 18], + ('negative', True): [32, 13, 17], + ('noninteger', True): [30, 12, 31, 3, 8, 4, 9, 6, 5, 29, 14, 25, 22], + ('nonnegative', False): [11, 3, 8, 29, 14, 20, 7], + ('nonnegative', True): [32, 33, 8, 9, 6, 34, 25, 26, 20, 27, 21, 22, 35, 36, 13, 17, 7], + ('nonpositive', False): [11, 3, 8, 29, 25, 18, 7], + ('nonpositive', True): [32, 3, 33, 4, 5, 14, 34, 15, 18, 16, 19, 22, 35, 36, 13, 17, 7], + ('nonzero', False): [29, 34, 20, 18], + ('nonzero', True): [32, 3, 8, 4, 9, 6, 5, 14, 25, 15, 26, 20, 18, 27, 16, 21, 19, 13, 17], + ('odd', False): [2], + ('odd', True): [3, 8, 4, 9, 6, 5, 14, 25, 15, 26, 20, 18, 27, 16, 21, 19], + ('positive', False): [29, 14, 34, 20], + ('positive', True): [32, 0, 1, 28, 13, 17], + ('prime', False): [0, 1, 24], + ('prime', True): [23, 2], + ('rational', False): [11, 3, 8, 29, 14, 25, 13, 17, 7], + ('rational', True): [3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 17, 7], + ('real', False): [10, 12, 11, 3, 8, 17, 7], + ('real', True): [32, 3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 13, 17, 7], + ('transcendental', True): [10, 30, 31, 11, 3, 8, 29, 14, 25, 27, 16, 21, 19, 22, 13, 17, 7], + ('zero', False): [11, 3, 8, 29, 14, 25, 7], + ('zero', True): [], +} # beta_triggers + + +generated_assumptions = {'defined_facts': defined_facts, 'full_implications': full_implications, + 'prereq': prereq, 'beta_rules': beta_rules, 'beta_triggers': beta_triggers} diff --git a/shared/package-files/d1/d1329d662c712d603ec70b40670e07729a899a3e17a6bc7566472dcb48134596/blob b/shared/package-files/d1/d1329d662c712d603ec70b40670e07729a899a3e17a6bc7566472dcb48134596/blob new file mode 100644 index 0000000000000000000000000000000000000000..b1ea8105dad6e27eefd5a34f64dfee974a5c4f71 --- /dev/null +++ b/shared/package-files/d1/d1329d662c712d603ec70b40670e07729a899a3e17a6bc7566472dcb48134596/blob @@ -0,0 +1,120 @@ +import functools +import os +import pathlib +import types +import warnings + +from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any + +from . import _common + +Package = Union[types.ModuleType, str] +Resource = str + + +def deprecated(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + warnings.warn( + f"{func.__name__} is deprecated. Use files() instead. " + "Refer to https://importlib-resources.readthedocs.io" + "/en/latest/using.html#migrating-from-legacy for migration advice.", + DeprecationWarning, + stacklevel=2, + ) + return func(*args, **kwargs) + + return wrapper + + +def normalize_path(path: Any) -> str: + """Normalize a path by ensuring it is a string. + + If the resulting string contains path separators, an exception is raised. + """ + str_path = str(path) + parent, file_name = os.path.split(str_path) + if parent: + raise ValueError(f'{path!r} must be only a file name') + return file_name + + +@deprecated +def open_binary(package: Package, resource: Resource) -> BinaryIO: + """Return a file-like object opened for binary reading of the resource.""" + return (_common.files(package) / normalize_path(resource)).open('rb') + + +@deprecated +def read_binary(package: Package, resource: Resource) -> bytes: + """Return the binary contents of the resource.""" + return (_common.files(package) / normalize_path(resource)).read_bytes() + + +@deprecated +def open_text( + package: Package, + resource: Resource, + encoding: str = 'utf-8', + errors: str = 'strict', +) -> TextIO: + """Return a file-like object opened for text reading of the resource.""" + return (_common.files(package) / normalize_path(resource)).open( + 'r', encoding=encoding, errors=errors + ) + + +@deprecated +def read_text( + package: Package, + resource: Resource, + encoding: str = 'utf-8', + errors: str = 'strict', +) -> str: + """Return the decoded string of the resource. + + The decoding-related arguments have the same semantics as those of + bytes.decode(). + """ + with open_text(package, resource, encoding, errors) as fp: + return fp.read() + + +@deprecated +def contents(package: Package) -> Iterable[str]: + """Return an iterable of entries in `package`. + + Note that not all entries are resources. Specifically, directories are + not considered resources. Use `is_resource()` on each entry returned here + to check if it is a resource or not. + """ + return [path.name for path in _common.files(package).iterdir()] + + +@deprecated +def is_resource(package: Package, name: str) -> bool: + """True if `name` is a resource inside `package`. + + Directories are *not* resources. + """ + resource = normalize_path(name) + return any( + traversable.name == resource and traversable.is_file() + for traversable in _common.files(package).iterdir() + ) + + +@deprecated +def path( + package: Package, + resource: Resource, +) -> ContextManager[pathlib.Path]: + """A context manager providing a file path object to the resource. + + If the resource does not already exist on its own on the file system, + a temporary file will be created. If the file was created, the file + will be deleted upon exiting the context manager (no exception is + raised if the file was deleted prior to the context manager + exiting). + """ + return _common.as_file(_common.files(package) / normalize_path(resource)) diff --git a/shared/package-files/d1/d132f83197095d4a28f6a03bbaed2f2efede1eb5d17ab566c9f8bb3b5e3d213c/blob b/shared/package-files/d1/d132f83197095d4a28f6a03bbaed2f2efede1eb5d17ab566c9f8bb3b5e3d213c/blob new file mode 100644 index 0000000000000000000000000000000000000000..33bfca3456659148c7ff4ef81e96ddaa7470b93f --- /dev/null +++ b/shared/package-files/d1/d132f83197095d4a28f6a03bbaed2f2efede1eb5d17ab566c9f8bb3b5e3d213c/blob @@ -0,0 +1,9 @@ +"""CUDA Driver + +- Driver API binding +- NVVM API binding +- Device array implementation + +""" +from numba.core import config +assert not config.ENABLE_CUDASIM, 'Cannot use real driver API with simulator' diff --git a/shared/package-files/d1/d136f12171747ea2f89913a16f452fafac4c411543f62b7c24523b3c41261c19/blob b/shared/package-files/d1/d136f12171747ea2f89913a16f452fafac4c411543f62b7c24523b3c41261c19/blob new file mode 100644 index 0000000000000000000000000000000000000000..ff39ebdf9efd4febc835163e1262634093235dd7 --- /dev/null +++ b/shared/package-files/d1/d136f12171747ea2f89913a16f452fafac4c411543f62b7c24523b3c41261c19/blob @@ -0,0 +1,2717 @@ +# -*- coding: utf-8 -*- +from itertools import product +from itertools import permutations + +from numba import njit, typeof +from numba.core import types +import unittest +from numba.tests.support import (TestCase, no_pyobj_flags, MemoryLeakMixin) +from numba.core.errors import (TypingError, UnsupportedError, + UnsupportedBytecodeError) +from numba.cpython.unicode import _MAX_UNICODE +from numba.core.types.functions import _header_lead +from numba.extending import overload +from numba.core.utils import PYVERSION + + +def isascii(s): + return all(ord(c) < 128 for c in s) + + +def literal_usecase(): + return '大处着眼,小处着手。' + + +def passthrough_usecase(x): + return x + + +def eq_usecase(x, y): + return x == y + + +def len_usecase(x): + return len(x) + + +def bool_usecase(x): + return bool(x) + + +def getitem_usecase(x, i): + return x[i] + + +def getitem_check_kind_usecase(x, i): + return hash(x[i]) + + +def zfill_usecase(x, y): + return x.zfill(y) + + +def concat_usecase(x, y): + return x + y + + +def repeat_usecase(x, y): + return x * y + + +def inplace_concat_usecase(x, y): + x += y + return x + + +def in_usecase(x, y): + return x in y + + +def lt_usecase(x, y): + return x < y + + +def le_usecase(x, y): + return x <= y + + +def gt_usecase(x, y): + return x > y + + +def ge_usecase(x, y): + return x >= y + + +def partition_usecase(s, sep): + return s.partition(sep) + + +def find_usecase(x, y): + return x.find(y) + + +def find_with_start_only_usecase(x, y, start): + return x.find(y, start) + + +def find_with_start_end_usecase(x, y, start, end): + return x.find(y, start, end) + + +def rpartition_usecase(s, sep): + return s.rpartition(sep) + + +def count_usecase(x, y): + return x.count(y) + + +def count_with_start_usecase(x, y, start): + return x.count(y, start) + + +def count_with_start_end_usecase(x, y, start, end): + return x.count(y, start, end) + + +def rfind_usecase(x, y): + return x.rfind(y) + + +def rfind_with_start_only_usecase(x, y, start): + return x.rfind(y, start) + + +def rfind_with_start_end_usecase(x, y, start, end): + return x.rfind(y, start, end) + + +def replace_usecase(s, x, y): + return s.replace(x, y) + + +def replace_with_count_usecase(s, x, y, count): + return s.replace(x, y, count) + + +def rindex_usecase(x, y): + return x.rindex(y) + + +def rindex_with_start_only_usecase(x, y, start): + return x.rindex(y, start) + + +def rindex_with_start_end_usecase(x, y, start, end): + return x.rindex(y, start, end) + + +def index_usecase(x, y): + return x.index(y) + + +def index_with_start_only_usecase(x, y, start): + return x.index(y, start) + + +def index_with_start_end_usecase(x, y, start, end): + return x.index(y, start, end) + + +def startswith_usecase(x, y): + return x.startswith(y) + + +def endswith_usecase(x, y): + return x.endswith(y) + + +def expandtabs_usecase(s): + return s.expandtabs() + + +def expandtabs_with_tabsize_usecase(s, tabsize): + return s.expandtabs(tabsize) + + +def expandtabs_with_tabsize_kwarg_usecase(s, tabsize): + return s.expandtabs(tabsize=tabsize) + + +def startswith_with_start_only_usecase(x, y, start): + return x.startswith(y, start) + + +def startswith_with_start_end_usecase(x, y, start, end): + return x.startswith(y, start, end) + + +def endswith_with_start_only_usecase(x, y, start): + return x.endswith(y, start) + + +def endswith_with_start_end_usecase(x, y, start, end): + return x.endswith(y, start, end) + + +def split_usecase(x, y): + return x.split(y) + + +def split_with_maxsplit_usecase(x, y, maxsplit): + return x.split(y, maxsplit) + + +def split_with_maxsplit_kwarg_usecase(x, y, maxsplit): + return x.split(y, maxsplit=maxsplit) + + +def split_whitespace_usecase(x): + return x.split() + + +def splitlines_usecase(s): + return s.splitlines() + + +def splitlines_with_keepends_usecase(s, keepends): + return s.splitlines(keepends) + + +def splitlines_with_keepends_kwarg_usecase(s, keepends): + return s.splitlines(keepends=keepends) + + +def rsplit_usecase(s, sep): + return s.rsplit(sep) + + +def rsplit_with_maxsplit_usecase(s, sep, maxsplit): + return s.rsplit(sep, maxsplit) + + +def rsplit_with_maxsplit_kwarg_usecase(s, sep, maxsplit): + return s.rsplit(sep, maxsplit=maxsplit) + + +def rsplit_whitespace_usecase(s): + return s.rsplit() + + +def lstrip_usecase(x): + return x.lstrip() + + +def lstrip_usecase_chars(x, chars): + return x.lstrip(chars) + + +def rstrip_usecase(x): + return x.rstrip() + + +def rstrip_usecase_chars(x, chars): + return x.rstrip(chars) + + +def strip_usecase(x): + return x.strip() + + +def strip_usecase_chars(x, chars): + return x.strip(chars) + + +def join_usecase(x, y): + return x.join(y) + + +def join_empty_usecase(x): + # hack to make empty typed list + l = [''] + l.pop() + return x.join(l) + + +def center_usecase(x, y): + return x.center(y) + + +def center_usecase_fillchar(x, y, fillchar): + return x.center(y, fillchar) + + +def ljust_usecase(x, y): + return x.ljust(y) + + +def ljust_usecase_fillchar(x, y, fillchar): + return x.ljust(y, fillchar) + + +def rjust_usecase(x, y): + return x.rjust(y) + + +def rjust_usecase_fillchar(x, y, fillchar): + return x.rjust(y, fillchar) + + +def istitle_usecase(x): + return x.istitle() + + +def iter_usecase(x): + l = [] + for i in x: + l.append(i) + return l + + +def title(x): + return x.title() + + +def literal_iter_usecase(): + l = [] + for i in '大处着眼,小处着手。': + l.append(i) + return l + + +def enumerated_iter_usecase(x): + buf = "" + scan = 0 + for i, s in enumerate(x): + buf += s + scan += 1 + return buf, scan + + +def iter_stopiteration_usecase(x): + n = len(x) + i = iter(x) + for _ in range(n + 1): + next(i) + + +def literal_iter_stopiteration_usecase(): + s = '大处着眼,小处着手。' + i = iter(s) + n = len(s) + for _ in range(n + 1): + next(i) + + +def islower_usecase(x): + return x.islower() + + +def lower_usecase(x): + return x.lower() + + +def ord_usecase(x): + return ord(x) + + +def chr_usecase(x): + return chr(x) + + +class BaseTest(MemoryLeakMixin, TestCase): + def setUp(self): + super(BaseTest, self).setUp() + + +UNICODE_EXAMPLES = [ + '', + 'ascii', + '12345', + '1234567890', + '¡Y tú quién te crees?', + '🐍⚡', + '大处着眼,小处着手。', +] + +UNICODE_ORDERING_EXAMPLES = [ + '', + 'a' + 'aa', + 'aaa', + 'b', + 'aab', + 'ab', + 'asc', + 'ascih', + 'ascii', + 'ascij', + '大处着眼,小处着手', + '大处着眼,小处着手。', + '大处着眼,小处着手。🐍⚡', +] + +UNICODE_COUNT_EXAMPLES = [ + ('', ''), + ('', 'ascii'), + ('ascii', ''), + ('asc ii', ' '), + ('ascii', 'ci'), + ('ascii', 'ascii'), + ('ascii', 'Ă'), + ('ascii', '大处'), + ('ascii', 'étú?'), + ('', '大处 着眼,小处着手。大大大处'), + ('大处 着眼,小处着手。大大大处', ''), + ('大处 着眼,小处着手。大大大处', ' '), + ('大处 着眼,小处着手。大大大处', 'ci'), + ('大处 着眼,小处着手。大大大处', '大处大处'), + ('大处 着眼,小处着手。大大大处', '大处 着眼,小处着手。大大大处'), + ('大处 着眼,小处着手。大大大处', 'Ă'), + ('大处 着眼,小处着手。大大大处', '大处'), + ('大处 着眼,小处着手。大大大处', 'étú?'), + ('', 'tú quién te crees?'), + ('tú quién te crees?', ''), + ('tú quién te crees?', ' '), + ('tú quién te crees?', 'ci'), + ('tú quién te crees?', 'tú quién te crees?'), + ('tú quién te crees?', 'Ă'), + ('tú quién te crees?', '大处'), + ('tú quién te crees?', 'étú?'), + ('abababab', 'a'), + ('abababab', 'ab'), + ('abababab', 'aba'), + ('aaaaaaaaaa', 'aaa'), + ('aaaaaaaaaa', 'aĂ'), + ('aabbaaaabbaa', 'aa') +] + + +class TestUnicode(BaseTest): + + def test_literal(self): + pyfunc = literal_usecase + cfunc = njit(literal_usecase) + self.assertPreciseEqual(pyfunc(), cfunc()) + + def test_passthrough(self, flags=no_pyobj_flags): + pyfunc = passthrough_usecase + cfunc = njit(pyfunc) + for s in UNICODE_EXAMPLES: + self.assertEqual(pyfunc(s), cfunc(s)) + + def test_eq(self, flags=no_pyobj_flags): + pyfunc = eq_usecase + cfunc = njit(pyfunc) + for a in UNICODE_EXAMPLES: + for b in reversed(UNICODE_EXAMPLES): + self.assertEqual(pyfunc(a, b), + cfunc(a, b), '%s, %s' % (a, b)) + # comparing against something that's not unicode + self.assertEqual(pyfunc(a, 1), + cfunc(a, 1), '%s, %s' % (a, 1)) + self.assertEqual(pyfunc(1, b), + cfunc(1, b), '%s, %s' % (1, b)) + + def test_eq_optional(self): + # See issue #7474 + @njit + def foo(pred1, pred2): + if pred1 > 0: + resolved1 = 'concrete' + else: + resolved1 = None + if pred2 < 0: + resolved2 = 'concrete' + else: + resolved2 = None + + # resolved* are Optionals + if resolved1 == resolved2: + return 10 + else: + return 20 + + for (p1, p2) in product(*((-1, 1),) * 2): + self.assertEqual(foo(p1, p2), foo.py_func(p1, p2)) + + def _check_ordering_op(self, usecase): + pyfunc = usecase + cfunc = njit(pyfunc) + + # Check comparison to self + for a in UNICODE_ORDERING_EXAMPLES: + self.assertEqual( + pyfunc(a, a), + cfunc(a, a), + '%s: "%s", "%s"' % (usecase.__name__, a, a), + ) + + # Check comparison to adjacent + for a, b in permutations(UNICODE_ORDERING_EXAMPLES, r=2): + self.assertEqual( + pyfunc(a, b), + cfunc(a, b), + '%s: "%s", "%s"' % (usecase.__name__, a, b), + ) + # and reversed + self.assertEqual( + pyfunc(b, a), + cfunc(b, a), + '%s: "%s", "%s"' % (usecase.__name__, b, a), + ) + + def test_lt(self, flags=no_pyobj_flags): + self._check_ordering_op(lt_usecase) + + def test_le(self, flags=no_pyobj_flags): + self._check_ordering_op(le_usecase) + + def test_gt(self, flags=no_pyobj_flags): + self._check_ordering_op(gt_usecase) + + def test_ge(self, flags=no_pyobj_flags): + self._check_ordering_op(ge_usecase) + + def test_len(self, flags=no_pyobj_flags): + pyfunc = len_usecase + cfunc = njit(pyfunc) + for s in UNICODE_EXAMPLES: + self.assertEqual(pyfunc(s), cfunc(s)) + + def test_bool(self, flags=no_pyobj_flags): + pyfunc = bool_usecase + cfunc = njit(pyfunc) + for s in UNICODE_EXAMPLES: + self.assertEqual(pyfunc(s), cfunc(s)) + + def test_expandtabs(self): + pyfunc = expandtabs_usecase + cfunc = njit(pyfunc) + + cases = ['', '\t', 't\tt\t', 'a\t', '\t⚡', 'a\tbc\nab\tc', + '🐍\t⚡', '🐍⚡\n\t\t🐍\t', 'ab\rab\t\t\tab\r\n\ta'] + + msg = 'Results of "{}".expandtabs() must be equal' + for s in cases: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_expandtabs_with_tabsize(self): + fns = [njit(expandtabs_with_tabsize_usecase), + njit(expandtabs_with_tabsize_kwarg_usecase)] + messages = ['Results of "{}".expandtabs({}) must be equal', + 'Results of "{}".expandtabs(tabsize={}) must be equal'] + + cases = ['', '\t', 't\tt\t', 'a\t', '\t⚡', 'a\tbc\nab\tc', + '🐍\t⚡', '🐍⚡\n\t\t🐍\t', 'ab\rab\t\t\tab\r\n\ta'] + + for s in cases: + for tabsize in range(-1, 10): + for fn, msg in zip(fns, messages): + self.assertEqual(fn.py_func(s, tabsize), fn(s, tabsize), + msg=msg.format(s, tabsize)) + + def test_expandtabs_exception_noninteger_tabsize(self): + pyfunc = expandtabs_with_tabsize_usecase + cfunc = njit(pyfunc) + + accepted_types = (types.Integer, int) + with self.assertRaises(TypingError) as raises: + cfunc('\t', 2.4) + msg = '"tabsize" must be {}, not float'.format(accepted_types) + self.assertIn(msg, str(raises.exception)) + + def test_startswith_default(self): + pyfunc = startswith_usecase + cfunc = njit(pyfunc) + + cpython_str = ['hello', 'helloworld', ''] + cpython_subs = [ + 'he', 'hello', 'helloworld', 'ello', + '', 'lowo', 'lo', 'he', 'lo', 'o', + ] + extra_subs = ['hellohellohello', ' '] + for s in cpython_str + UNICODE_EXAMPLES: + default_subs = ['', 'x', s[:-2], s[3:], s, s + s] + for prefix in cpython_subs + default_subs + extra_subs: + self.assertEqual(pyfunc(s, prefix), cfunc(s, prefix)) + + def test_startswith_with_start(self): + pyfunc = startswith_with_start_only_usecase + cfunc = njit(pyfunc) + + cpython_str = ['hello', 'helloworld', ''] + cpython_subs = [ + 'he', 'hello', 'helloworld', 'ello', + '', 'lowo', 'lo', 'he', 'lo', 'o', + ] + extra_subs = ['hellohellohello', ' '] + for s in cpython_str + UNICODE_EXAMPLES: + default_subs = ['', 'x', s[:-2], s[3:], s, s + s] + for prefix in cpython_subs + default_subs + extra_subs: + for start in list(range(-20, 20)) + [None]: + self.assertEqual(pyfunc(s, prefix, start), + cfunc(s, prefix, start)) + + def test_startswith_with_start_end(self): + pyfunc = startswith_with_start_end_usecase + cfunc = njit(pyfunc) + + cpython_str = ['hello', 'helloworld', ''] + cpython_subs = [ + 'he', 'hello', 'helloworld', 'ello', + '', 'lowo', 'lo', 'he', 'lo', 'o', + ] + extra_subs = ['hellohellohello', ' '] + for s in cpython_str + UNICODE_EXAMPLES: + default_subs = ['', 'x', s[:-2], s[3:], s, s + s] + for prefix in cpython_subs + default_subs + extra_subs: + for start in list(range(-20, 20)) + [None]: + for end in list(range(-20, 20)) + [None]: + self.assertEqual(pyfunc(s, prefix, start, end), + cfunc(s, prefix, start, end)) + + def test_startswith_exception_invalid_args(self): + msg_invalid_prefix = \ + "The arg 'prefix' should be a string or a tuple of strings" + with self.assertRaisesRegex(TypingError, msg_invalid_prefix): + cfunc = njit(startswith_usecase) + cfunc("hello", (1, "he")) + + msg_invalid_start = \ + "When specified, the arg 'start' must be an Integer or None" + with self.assertRaisesRegex(TypingError, msg_invalid_start): + cfunc = njit(startswith_with_start_only_usecase) + cfunc("hello", "he", "invalid start") + + msg_invalid_end = \ + "When specified, the arg 'end' must be an Integer or None" + with self.assertRaisesRegex(TypingError, msg_invalid_end): + cfunc = njit(startswith_with_start_end_usecase) + cfunc("hello", "he", 0, "invalid end") + + def test_startswith_tuple(self): + pyfunc = startswith_usecase + cfunc = njit(pyfunc) + + cpython_str = ['hello', 'helloworld', ''] + cpython_subs = [ + 'he', 'hello', 'helloworld', 'ello', + '', 'lowo', 'lo', 'he', 'lo', 'o', + ] + extra_subs = ['hellohellohello', ' '] + for s in cpython_str + UNICODE_EXAMPLES: + default_subs = ['', 'x', s[:-2], s[3:], s, s + s] + for sub_str in cpython_subs + default_subs + extra_subs: + prefix = (sub_str, 'lo') + self.assertEqual(pyfunc(s, prefix), + cfunc(s, prefix)) + + def test_startswith_tuple_args(self): + pyfunc = startswith_with_start_end_usecase + cfunc = njit(pyfunc) + + cpython_str = ['hello', 'helloworld', ''] + cpython_subs = [ + 'he', 'hello', 'helloworld', 'ello', + '', 'lowo', 'lo', 'he', 'lo', 'o', + ] + extra_subs = ['hellohellohello', ' '] + for s in cpython_str + UNICODE_EXAMPLES: + default_subs = ['', 'x', s[:-2], s[3:], s, s + s] + for sub_str in cpython_subs + default_subs + extra_subs: + for start in list(range(-20, 20)) + [None]: + for end in list(range(-20, 20)) + [None]: + prefix = (sub_str, 'lo') + self.assertEqual(pyfunc(s, prefix, start, end), + cfunc(s, prefix, start, end)) + + def test_endswith_default(self): + pyfunc = endswith_usecase + cfunc = njit(pyfunc) + + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/865c3b257fe38154a4320c7ee6afb416f665b9c2/Lib/test/string_tests.py#L1049-L1099 # noqa: E501 + cpython_str = ['hello', 'helloworld', ''] + cpython_subs = [ + 'he', 'hello', 'helloworld', 'ello', + '', 'lowo', 'lo', 'he', 'lo', 'o', + ] + extra_subs = ['hellohellohello', ' '] + for s in cpython_str + UNICODE_EXAMPLES: + default_subs = ['', 'x', s[:-2], s[3:], s, s + s] + for sub_str in cpython_subs + default_subs + extra_subs: + msg = 'Results "{}".endswith("{}") must be equal' + self.assertEqual(pyfunc(s, sub_str), cfunc(s, sub_str), + msg=msg.format(s, sub_str)) + + def test_endswith_with_start(self): + pyfunc = endswith_with_start_only_usecase + cfunc = njit(pyfunc) + + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/865c3b257fe38154a4320c7ee6afb416f665b9c2/Lib/test/string_tests.py#L1049-L1099 # noqa: E501 + cpython_str = ['hello', 'helloworld', ''] + cpython_subs = [ + 'he', 'hello', 'helloworld', 'ello', + '', 'lowo', 'lo', 'he', 'lo', 'o', + ] + extra_subs = ['hellohellohello', ' '] + for s in cpython_str + UNICODE_EXAMPLES: + default_subs = ['', 'x', s[:-2], s[3:], s, s + s] + for sub_str in cpython_subs + default_subs + extra_subs: + for start in list(range(-20, 20)) + [None]: + msg = 'Results "{}".endswith("{}", {}) must be equal' + self.assertEqual(pyfunc(s, sub_str, start), + cfunc(s, sub_str, start), + msg=msg.format(s, sub_str, start)) + + def test_endswith_with_start_end(self): + pyfunc = endswith_with_start_end_usecase + cfunc = njit(pyfunc) + + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/865c3b257fe38154a4320c7ee6afb416f665b9c2/Lib/test/string_tests.py#LL1049-L1099 # noqa: E501 + cpython_str = ['hello', 'helloworld', ''] + cpython_subs = [ + 'he', 'hello', 'helloworld', 'ello', + '', 'lowo', 'lo', 'he', 'lo', 'o', + ] + extra_subs = ['hellohellohello', ' '] + for s in cpython_str + UNICODE_EXAMPLES: + default_subs = ['', 'x', s[:-2], s[3:], s, s + s] + for sub_str in cpython_subs + default_subs + extra_subs: + for start in list(range(-20, 20)) + [None]: + for end in list(range(-20, 20)) + [None]: + msg = 'Results "{}".endswith("{}", {}, {})\ + must be equal' + self.assertEqual(pyfunc(s, sub_str, start, end), + cfunc(s, sub_str, start, end), + msg=msg.format(s, sub_str, start, end)) + + def test_endswith_tuple(self): + pyfunc = endswith_usecase + cfunc = njit(pyfunc) + + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/865c3b257fe38154a4320c7ee6afb416f665b9c2/Lib/test/string_tests.py#L1049-L1099 # noqa: E501 + cpython_str = ['hello', 'helloworld', ''] + cpython_subs = [ + 'he', 'hello', 'helloworld', 'ello', + '', 'lowo', 'lo', 'he', 'lo', 'o', + ] + extra_subs = ['hellohellohello', ' '] + for s in cpython_str + UNICODE_EXAMPLES: + default_subs = ['', 'x', s[:-2], s[3:], s, s + s] + for sub_str in cpython_subs + default_subs + extra_subs: + msg = 'Results "{}".endswith({}) must be equal' + tuple_subs = (sub_str, 'lo') + self.assertEqual(pyfunc(s, tuple_subs), + cfunc(s, tuple_subs), + msg=msg.format(s, tuple_subs)) + + def test_endswith_tuple_args(self): + pyfunc = endswith_with_start_end_usecase + cfunc = njit(pyfunc) + + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/865c3b257fe38154a4320c7ee6afb416f665b9c2/Lib/test/string_tests.py#L1049-L1099 # noqa: E501 + cpython_str = ['hello', 'helloworld', ''] + cpython_subs = [ + 'he', 'hello', 'helloworld', 'ello', + '', 'lowo', 'lo', 'he', 'lo', 'o', + ] + extra_subs = ['hellohellohello', ' '] + for s in cpython_str + UNICODE_EXAMPLES: + default_subs = ['', 'x', s[:-2], s[3:], s, s + s] + for sub_str in cpython_subs + default_subs + extra_subs: + for start in list(range(-20, 20)) + [None]: + for end in list(range(-20, 20)) + [None]: + msg = 'Results "{}".endswith("{}", {}, {})\ + must be equal' + tuple_subs = (sub_str, 'lo') + self.assertEqual(pyfunc(s, tuple_subs, start, end), + cfunc(s, tuple_subs, start, end), + msg=msg.format(s, tuple_subs, + start, end)) + + def test_in(self, flags=no_pyobj_flags): + pyfunc = in_usecase + cfunc = njit(pyfunc) + for a in UNICODE_EXAMPLES: + extras = ['', 'xx', a[::-1], a[:-2], a[3:], a, a + a] + for substr in extras: + self.assertEqual(pyfunc(substr, a), + cfunc(substr, a), + "'%s' in '%s'?" % (substr, a)) + + def test_partition_exception_invalid_sep(self): + self.disable_leak_check() + + pyfunc = partition_usecase + cfunc = njit(pyfunc) + + # Handle empty separator exception + for func in [pyfunc, cfunc]: + with self.assertRaises(ValueError) as raises: + func('a', '') + self.assertIn('empty separator', str(raises.exception)) + + accepted_types = (types.UnicodeType, types.UnicodeCharSeq) + with self.assertRaises(TypingError) as raises: + cfunc('a', None) + msg = '"sep" must be {}, not none'.format(accepted_types) + self.assertIn(msg, str(raises.exception)) + + def test_partition(self): + pyfunc = partition_usecase + cfunc = njit(pyfunc) + + CASES = [ + ('', '⚡'), + ('abcabc', '⚡'), + ('🐍⚡', '⚡'), + ('🐍⚡🐍', '⚡'), + ('abababa', 'a'), + ('abababa', 'b'), + ('abababa', 'c'), + ('abababa', 'ab'), + ('abababa', 'aba'), + ] + msg = 'Results of "{}".partition("{}") must be equal' + for s, sep in CASES: + self.assertEqual(pyfunc(s, sep), cfunc(s, sep), + msg=msg.format(s, sep)) + + def test_find(self, flags=no_pyobj_flags): + pyfunc = find_usecase + cfunc = njit(pyfunc) + + default_subs = [ + (s, ['', 'xx', s[:-2], s[3:], s]) for s in UNICODE_EXAMPLES + ] + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Lib/test/test_unicode.py#L202-L231 # noqa: E501 + cpython_subs = [ + ('a' * 100 + '\u0102', ['\u0102', '\u0201', '\u0120', '\u0220']), + ('a' * 100 + '\U00100304', ['\U00100304', '\U00100204', + '\U00102004']), + ('\u0102' * 100 + 'a', ['a']), + ('\U00100304' * 100 + 'a', ['a']), + ('\U00100304' * 100 + '\u0102', ['\u0102']), + ('a' * 100, ['\u0102', '\U00100304', 'a\u0102', 'a\U00100304']), + ('\u0102' * 100, ['\U00100304', '\u0102\U00100304']), + ('\u0102' * 100 + 'a_', ['a_']), + ('\U00100304' * 100 + 'a_', ['a_']), + ('\U00100304' * 100 + '\u0102_', ['\u0102_']), + ] + for s, subs in default_subs + cpython_subs: + for sub_str in subs: + msg = 'Results "{}".find("{}") must be equal' + self.assertEqual(pyfunc(s, sub_str), cfunc(s, sub_str), + msg=msg.format(s, sub_str)) + + def test_find_with_start_only(self): + pyfunc = find_with_start_only_usecase + cfunc = njit(pyfunc) + + for s in UNICODE_EXAMPLES: + for sub_str in ['', 'xx', s[:-2], s[3:], s]: + for start in list(range(-20, 20)) + [None]: + msg = 'Results "{}".find("{}", {}) must be equal' + self.assertEqual(pyfunc(s, sub_str, start), + cfunc(s, sub_str, start), + msg=msg.format(s, sub_str, start)) + + def test_find_with_start_end(self): + pyfunc = find_with_start_end_usecase + cfunc = njit(pyfunc) + + starts = ends = list(range(-20, 20)) + [None] + for s in UNICODE_EXAMPLES: + for sub_str in ['', 'xx', s[:-2], s[3:], s]: + for start, end in product(starts, ends): + msg = 'Results of "{}".find("{}", {}, {}) must be equal' + self.assertEqual(pyfunc(s, sub_str, start, end), + cfunc(s, sub_str, start, end), + msg=msg.format(s, sub_str, start, end)) + + def test_find_exception_noninteger_start_end(self): + pyfunc = find_with_start_end_usecase + cfunc = njit(pyfunc) + + accepted = (types.Integer, types.NoneType) + for start, end, name in [(0.1, 5, 'start'), (0, 0.5, 'end')]: + with self.assertRaises(TypingError) as raises: + cfunc('ascii', 'sci', start, end) + msg = '"{}" must be {}, not float'.format(name, accepted) + self.assertIn(msg, str(raises.exception)) + + def test_rpartition_exception_invalid_sep(self): + self.disable_leak_check() + + pyfunc = rpartition_usecase + cfunc = njit(pyfunc) + + # Handle empty separator exception + for func in [pyfunc, cfunc]: + with self.assertRaises(ValueError) as raises: + func('a', '') + self.assertIn('empty separator', str(raises.exception)) + + accepted_types = (types.UnicodeType, types.UnicodeCharSeq) + with self.assertRaises(TypingError) as raises: + cfunc('a', None) + msg = '"sep" must be {}, not none'.format(accepted_types) + self.assertIn(msg, str(raises.exception)) + + def test_rpartition(self): + pyfunc = rpartition_usecase + cfunc = njit(pyfunc) + + CASES = [ + ('', '⚡'), + ('abcabc', '⚡'), + ('🐍⚡', '⚡'), + ('🐍⚡🐍', '⚡'), + ('abababa', 'a'), + ('abababa', 'b'), + ('abababa', 'c'), + ('abababa', 'ab'), + ('abababa', 'aba'), + ] + msg = 'Results of "{}".rpartition("{}") must be equal' + for s, sep in CASES: + self.assertEqual(pyfunc(s, sep), cfunc(s, sep), + msg=msg.format(s, sep)) + + def test_count(self): + pyfunc = count_usecase + cfunc = njit(pyfunc) + error_msg = "'{0}'.py_count('{1}') = {2}\n'{0}'.c_count('{1}') = {3}" + + for s, sub in UNICODE_COUNT_EXAMPLES: + py_result = pyfunc(s, sub) + c_result = cfunc(s, sub) + self.assertEqual(py_result, c_result, + error_msg.format(s, sub, py_result, c_result)) + + def test_count_with_start(self): + pyfunc = count_with_start_usecase + cfunc = njit(pyfunc) + error_msg = "%s\n%s" % ("'{0}'.py_count('{1}', {2}) = {3}", + "'{0}'.c_count('{1}', {2}) = {4}") + + for s, sub in UNICODE_COUNT_EXAMPLES: + for i in range(-18, 18): + py_result = pyfunc(s, sub, i) + c_result = cfunc(s, sub, i) + self.assertEqual(py_result, c_result, + error_msg.format(s, sub, i, py_result, + c_result)) + + py_result = pyfunc(s, sub, None) + c_result = cfunc(s, sub, None) + self.assertEqual(py_result, c_result, + error_msg.format(s, sub, None, py_result, + c_result)) + + def test_count_with_start_end(self): + pyfunc = count_with_start_end_usecase + cfunc = njit(pyfunc) + error_msg = "%s\n%s" % ("'{0}'.py_count('{1}', {2}, {3}) = {4}", + "'{0}'.c_count('{1}', {2}, {3}) = {5}") + + for s, sub in UNICODE_COUNT_EXAMPLES: + for i, j in product(range(-18, 18), (-18, 18)): + py_result = pyfunc(s, sub, i, j) + c_result = cfunc(s, sub, i, j) + self.assertEqual(py_result, c_result, + error_msg.format(s, sub, i, j, py_result, + c_result)) + + for j in range(-18, 18): + py_result = pyfunc(s, sub, None, j) + c_result = cfunc(s, sub, None, j) + self.assertEqual(py_result, c_result, + error_msg.format(s, sub, None, j, py_result, + c_result)) + + py_result = pyfunc(s, sub, None, None) + c_result = cfunc(s, sub, None, None) + self.assertEqual(py_result, c_result, + error_msg.format(s, sub, None, None, py_result, + c_result)) + + def test_count_arg_type_check(self): + cfunc = njit(count_with_start_end_usecase) + + with self.assertRaises(TypingError) as raises: + cfunc('ascii', 'c', 1, 0.5) + self.assertIn('The slice indices must be an Integer or None', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc('ascii', 'c', 1.2, 7) + self.assertIn('The slice indices must be an Integer or None', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc('ascii', 12, 1, 7) + self.assertIn('The substring must be a UnicodeType, not', + str(raises.exception)) + + def test_count_optional_arg_type_check(self): + pyfunc = count_with_start_end_usecase + + def try_compile_bad_optional(*args): + bad_sig = types.int64(types.unicode_type, + types.unicode_type, + types.Optional(types.float64), + types.Optional(types.float64)) + njit([bad_sig])(pyfunc) + + with self.assertRaises(TypingError) as raises: + try_compile_bad_optional('tú quis?', 'tú', 1.1, 1.1) + self.assertIn('The slice indices must be an Integer or None', + str(raises.exception)) + + error_msg = "%s\n%s" % ("'{0}'.py_count('{1}', {2}, {3}) = {4}", + "'{0}'.c_count_op('{1}', {2}, {3}) = {5}") + sig_optional = types.int64(types.unicode_type, + types.unicode_type, + types.Optional(types.int64), + types.Optional(types.int64)) + cfunc_optional = njit([sig_optional])(pyfunc) + + py_result = pyfunc('tú quis?', 'tú', 0, 8) + c_result = cfunc_optional('tú quis?', 'tú', 0, 8) + self.assertEqual(py_result, c_result, + error_msg.format('tú quis?', 'tú', 0, 8, py_result, + c_result)) + + def test_rfind(self): + pyfunc = rfind_usecase + cfunc = njit(pyfunc) + + default_subs = [ + (s, ['', 'xx', s[:-2], s[3:], s]) for s in UNICODE_EXAMPLES + ] + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Lib/test/test_unicode.py#L233-L259 # noqa: E501 + cpython_subs = [ + ('\u0102' + 'a' * 100, ['\u0102', '\u0201', '\u0120', '\u0220']), + ('\U00100304' + 'a' * 100, ['\U00100304', '\U00100204', + '\U00102004']), + ('abcdefghiabc', ['abc', '']), + ('a' + '\u0102' * 100, ['a']), + ('a' + '\U00100304' * 100, ['a']), + ('\u0102' + '\U00100304' * 100, ['\u0102']), + ('a' * 100, ['\u0102', '\U00100304', '\u0102a', '\U00100304a']), + ('\u0102' * 100, ['\U00100304', '\U00100304\u0102']), + ('_a' + '\u0102' * 100, ['_a']), + ('_a' + '\U00100304' * 100, ['_a']), + ('_\u0102' + '\U00100304' * 100, ['_\u0102']), + ] + for s, subs in default_subs + cpython_subs: + for sub_str in subs: + msg = 'Results "{}".rfind("{}") must be equal' + self.assertEqual(pyfunc(s, sub_str), cfunc(s, sub_str), + msg=msg.format(s, sub_str)) + + def test_rfind_with_start_only(self): + pyfunc = rfind_with_start_only_usecase + cfunc = njit(pyfunc) + + for s in UNICODE_EXAMPLES: + for sub_str in ['', 'xx', s[:-2], s[3:], s]: + for start in list(range(-20, 20)) + [None]: + msg = 'Results "{}".rfind("{}", {}) must be equal' + self.assertEqual(pyfunc(s, sub_str, start), + cfunc(s, sub_str, start), + msg=msg.format(s, sub_str, start)) + + def test_rfind_with_start_end(self): + pyfunc = rfind_with_start_end_usecase + cfunc = njit(pyfunc) + + starts = list(range(-20, 20)) + [None] + ends = list(range(-20, 20)) + [None] + for s in UNICODE_EXAMPLES: + for sub_str in ['', 'xx', s[:-2], s[3:], s]: + for start, end in product(starts, ends): + msg = 'Results of "{}".rfind("{}", {}, {}) must be equal' + self.assertEqual(pyfunc(s, sub_str, start, end), + cfunc(s, sub_str, start, end), + msg=msg.format(s, sub_str, start, end)) + + def test_rfind_wrong_substr(self): + cfunc = njit(rfind_usecase) + + for s in UNICODE_EXAMPLES: + for sub_str in [None, 1, False]: + with self.assertRaises(TypingError) as raises: + cfunc(s, sub_str) + msg = 'must be {}'.format(types.UnicodeType) + self.assertIn(msg, str(raises.exception)) + + def test_rfind_wrong_start_end(self): + cfunc = njit(rfind_with_start_end_usecase) + + accepted_types = (types.Integer, types.NoneType) + for s in UNICODE_EXAMPLES: + for sub_str in ['', 'xx', s[:-2], s[3:], s]: + # test wrong start + for start, end in product([0.1, False], [-1, 1]): + with self.assertRaises(TypingError) as raises: + cfunc(s, sub_str, start, end) + msg = '"start" must be {}'.format(accepted_types) + self.assertIn(msg, str(raises.exception)) + + # test wrong end + for start, end in product([-1, 1], [-0.1, True]): + with self.assertRaises(TypingError) as raises: + cfunc(s, sub_str, start, end) + msg = '"end" must be {}'.format(accepted_types) + self.assertIn(msg, str(raises.exception)) + + def test_rfind_wrong_start_end_optional(self): + s = UNICODE_EXAMPLES[0] + sub_str = s[1:-1] + accepted_types = (types.Integer, types.NoneType) + msg = 'must be {}'.format(accepted_types) + + def try_compile_wrong_start_optional(*args): + wrong_sig_optional = types.int64(types.unicode_type, + types.unicode_type, + types.Optional(types.float64), + types.Optional(types.intp)) + njit([wrong_sig_optional])(rfind_with_start_end_usecase) + + with self.assertRaises(TypingError) as raises: + try_compile_wrong_start_optional(s, sub_str, 0.1, 1) + self.assertIn(msg, str(raises.exception)) + + def try_compile_wrong_end_optional(*args): + wrong_sig_optional = types.int64(types.unicode_type, + types.unicode_type, + types.Optional(types.intp), + types.Optional(types.float64)) + njit([wrong_sig_optional])(rfind_with_start_end_usecase) + + with self.assertRaises(TypingError) as raises: + try_compile_wrong_end_optional(s, sub_str, 1, 0.1) + self.assertIn(msg, str(raises.exception)) + + def test_rindex(self): + pyfunc = rindex_usecase + cfunc = njit(pyfunc) + + default_subs = [ + (s, ['', s[:-2], s[3:], s]) for s in UNICODE_EXAMPLES + ] + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L284-L308 # noqa: E501 + cpython_subs = [ + ('abcdefghiabc', ['', 'def', 'abc']), + ('a' + '\u0102' * 100, ['a']), + ('a' + '\U00100304' * 100, ['a']), + ('\u0102' + '\U00100304' * 100, ['\u0102']), + ('_a' + '\u0102' * 100, ['_a']), + ('_a' + '\U00100304' * 100, ['_a']), + ('_\u0102' + '\U00100304' * 100, ['_\u0102']) + ] + for s, subs in default_subs + cpython_subs: + for sub_str in subs: + msg = 'Results "{}".rindex("{}") must be equal' + self.assertEqual(pyfunc(s, sub_str), cfunc(s, sub_str), + msg=msg.format(s, sub_str)) + + def test_index(self): + pyfunc = index_usecase + cfunc = njit(pyfunc) + + default_subs = [ + (s, ['', s[:-2], s[3:], s]) for s in UNICODE_EXAMPLES + ] + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L260-L282 # noqa: E501 + cpython_subs = [ + ('abcdefghiabc', ['', 'def', 'abc']), + ('\u0102' * 100 + 'a', ['a']), + ('\U00100304' * 100 + 'a', ['a']), + ('\U00100304' * 100 + '\u0102', ['\u0102']), + ('\u0102' * 100 + 'a_', ['a_']), + ('\U00100304' * 100 + 'a_', ['a_']), + ('\U00100304' * 100 + '\u0102_', ['\u0102_']) + ] + for s, subs in default_subs + cpython_subs: + for sub_str in subs: + msg = 'Results "{}".index("{}") must be equal' + self.assertEqual(pyfunc(s, sub_str), cfunc(s, sub_str), + msg=msg.format(s, sub_str)) + + def test_index_rindex_with_start_only(self): + pyfuncs = [index_with_start_only_usecase, + rindex_with_start_only_usecase] + messages = ['Results "{}".index("{}", {}) must be equal', + 'Results "{}".rindex("{}", {}) must be equal'] + unicode_examples = [ + 'ascii', + '12345', + '1234567890', + '¡Y tú quién te crees?', + '大处着眼,小处着手。', + ] + for pyfunc, msg in zip(pyfuncs, messages): + cfunc = njit(pyfunc) + for s in unicode_examples: + l = len(s) + cases = [ + ('', list(range(-10, l + 1))), + (s[:-2], [0] + list(range(-10, 1 - l))), + (s[3:], list(range(4)) + list(range(-10, 4 - l))), + (s, [0] + list(range(-10, 1 - l))), + ] + for sub_str, starts in cases: + for start in starts + [None]: + self.assertEqual(pyfunc(s, sub_str, start), + cfunc(s, sub_str, start), + msg=msg.format(s, sub_str, start)) + + def test_index_rindex_with_start_end(self): + pyfuncs = [index_with_start_end_usecase, rindex_with_start_end_usecase] + messages = ['Results of "{}".index("{}", {}, {}) must be equal', + 'Results of "{}".rindex("{}", {}, {}) must be equal'] + unicode_examples = [ + 'ascii', + '12345', + '1234567890', + '¡Y tú quién te crees?', + '大处着眼,小处着手。', + ] + for pyfunc, msg in zip(pyfuncs, messages): + cfunc = njit(pyfunc) + for s in unicode_examples: + l = len(s) + cases = [ + ('', list(range(-10, l + 1)), list(range(l, 10))), + (s[:-2], [0] + list(range(-10, 1 - l)), + [-2, -1] + list(range(l - 2, 10))), + (s[3:], list(range(4)) + list(range(-10, -1)), + list(range(l, 10))), + (s, [0] + list(range(-10, 1 - l)), list(range(l, 10))), + ] + for sub_str, starts, ends in cases: + for start, end in product(starts + [None], ends): + self.assertEqual(pyfunc(s, sub_str, start, end), + cfunc(s, sub_str, start, end), + msg=msg.format(s, sub_str, start, end)) + + def test_index_rindex_exception_substring_not_found(self): + self.disable_leak_check() + + unicode_examples = [ + 'ascii', + '12345', + '1234567890', + '¡Y tú quién te crees?', + '大处着眼,小处着手。', + ] + pyfuncs = [index_with_start_end_usecase, rindex_with_start_end_usecase] + for pyfunc in pyfuncs: + cfunc = njit(pyfunc) + for s in unicode_examples: + l = len(s) + cases = [ + ('', list(range(l + 1, 10)), [l]), + (s[:-2], [0], list(range(l - 2))), + (s[3:], list(range(4, 10)), [l]), + (s, [None], list(range(l))), + ] + for sub_str, starts, ends in cases: + for start, end in product(starts, ends): + for func in [pyfunc, cfunc]: + with self.assertRaises(ValueError) as raises: + func(s, sub_str, start, end) + msg = 'substring not found' + self.assertIn(msg, str(raises.exception)) + + def test_index_rindex_exception_noninteger_start_end(self): + accepted = (types.Integer, types.NoneType) + pyfuncs = [index_with_start_end_usecase, rindex_with_start_end_usecase] + for pyfunc in pyfuncs: + cfunc = njit(pyfunc) + for start, end, name in [(0.1, 5, 'start'), (0, 0.5, 'end')]: + with self.assertRaises(TypingError) as raises: + cfunc('ascii', 'sci', start, end) + msg = '"{}" must be {}, not float'.format(name, accepted) + self.assertIn(msg, str(raises.exception)) + + def test_getitem(self): + pyfunc = getitem_usecase + cfunc = njit(pyfunc) + + for s in UNICODE_EXAMPLES: + for i in range(-len(s), len(s)): + self.assertEqual(pyfunc(s, i), + cfunc(s, i), + "'%s'[%d]?" % (s, i)) + + def test_getitem_scalar_kind(self): + # See issue #6135, make sure that getitem returns a char of the minimal + # kind required to represent the "got" item, this is done via the use + # of `hash` in the test function as it is sensitive to kind. + pyfunc = getitem_check_kind_usecase + cfunc = njit(pyfunc) + samples = ['a\u1234', '¡着'] + for s in samples: + for i in range(-len(s), len(s)): + self.assertEqual(pyfunc(s, i), + cfunc(s, i), + "'%s'[%d]?" % (s, i)) + + def test_getitem_error(self): + self.disable_leak_check() + + pyfunc = getitem_usecase + cfunc = njit(pyfunc) + + for s in UNICODE_EXAMPLES: + with self.assertRaises(IndexError) as raises: + pyfunc(s, len(s)) + self.assertIn('string index out of range', str(raises.exception)) + + with self.assertRaises(IndexError) as raises: + cfunc(s, len(s)) + self.assertIn('string index out of range', str(raises.exception)) + + def test_slice2(self): + pyfunc = getitem_usecase + cfunc = njit(pyfunc) + + for s in UNICODE_EXAMPLES: + for i in list(range(-len(s), len(s))): + for j in list(range(-len(s), len(s))): + sl = slice(i, j) + self.assertEqual(pyfunc(s, sl), + cfunc(s, sl), + "'%s'[%d:%d]?" % (s, i, j)) + + def test_slice2_error(self): + pyfunc = getitem_usecase + cfunc = njit(pyfunc) + + for s in UNICODE_EXAMPLES: + for i in [-2, -1, len(s), len(s) + 1]: + for j in [-2, -1, len(s), len(s) + 1]: + sl = slice(i, j) + self.assertEqual(pyfunc(s, sl), + cfunc(s, sl), + "'%s'[%d:%d]?" % (s, i, j)) + + def test_getitem_slice2_kind(self): + # See issue #6135. Also see note in test_getitem_scalar_kind regarding + # testing. + pyfunc = getitem_check_kind_usecase + cfunc = njit(pyfunc) + samples = ['abc\u1234\u1234', '¡¡¡着着着'] + for s in samples: + for i in [-2, -1, 0, 1, 2, len(s), len(s) + 1]: + for j in [-2, -1, 0, 1, 2, len(s), len(s) + 1]: + sl = slice(i, j) + self.assertEqual(pyfunc(s, sl), + cfunc(s, sl), + "'%s'[%d:%d]?" % (s, i, j)) + + def test_slice3(self): + pyfunc = getitem_usecase + cfunc = njit(pyfunc) + + for s in UNICODE_EXAMPLES: + for i in range(-len(s), len(s)): + for j in range(-len(s), len(s)): + for k in [-2, -1, 1, 2]: + sl = slice(i, j, k) + self.assertEqual(pyfunc(s, sl), + cfunc(s, sl), + "'%s'[%d:%d:%d]?" % (s, i, j, k)) + + def test_getitem_slice3_kind(self): + # See issue #6135. Also see note in test_getitem_scalar_kind regarding + # testing. + pyfunc = getitem_check_kind_usecase + cfunc = njit(pyfunc) + samples = ['abc\u1234\u1234', + 'a\u1234b\u1234c' + '¡¡¡着着着', + '¡着¡着¡着', + '着a着b着c', + '¡着a¡着b¡着c', + '¡着a着¡c',] + for s in samples: + for i in range(-len(s), len(s)): + for j in range(-len(s), len(s)): + for k in [-2, -1, 1, 2]: + sl = slice(i, j, k) + self.assertEqual(pyfunc(s, sl), + cfunc(s, sl), + "'%s'[%d:%d:%d]?" % (s, i, j, k)) + + def test_slice3_error(self): + pyfunc = getitem_usecase + cfunc = njit(pyfunc) + + for s in UNICODE_EXAMPLES: + for i in [-2, -1, len(s), len(s) + 1]: + for j in [-2, -1, len(s), len(s) + 1]: + for k in [-2, -1, 1, 2]: + sl = slice(i, j, k) + self.assertEqual(pyfunc(s, sl), + cfunc(s, sl), + "'%s'[%d:%d:%d]?" % (s, i, j, k)) + + def test_slice_ascii_flag(self): + """ + Make sure ascii flag is False when ascii and non-ascii characters are + mixed in output of Unicode slicing. + """ + @njit + def f(s): + return s[::2]._is_ascii, s[1::2]._is_ascii + + s = "¿abc¡Y tú, quién te cre\t\tes?" + self.assertEqual(f(s), (0, 1)) + + def test_zfill(self): + pyfunc = zfill_usecase + cfunc = njit(pyfunc) + + ZFILL_INPUTS = [ + 'ascii', + '+ascii', + '-ascii', + '-asc ii-', + '12345', + '-12345', + '+12345', + '', + '¡Y tú crs?', + '🐍⚡', + '+🐍⚡', + '-🐍⚡', + '大眼,小手。', + '+大眼,小手。', + '-大眼,小手。', + ] + + with self.assertRaises(TypingError) as raises: + cfunc(ZFILL_INPUTS[0], 1.1) + self.assertIn(' must be an Integer', str(raises.exception)) + + for s in ZFILL_INPUTS: + for width in range(-3, 20): + self.assertEqual(pyfunc(s, width), + cfunc(s, width)) + + def test_concat(self, flags=no_pyobj_flags): + pyfunc = concat_usecase + cfunc = njit(pyfunc) + for a in UNICODE_EXAMPLES: + for b in UNICODE_EXAMPLES[::-1]: + self.assertEqual(pyfunc(a, b), + cfunc(a, b), + "'%s' + '%s'?" % (a, b)) + + def test_repeat(self, flags=no_pyobj_flags): + pyfunc = repeat_usecase + cfunc = njit(pyfunc) + for a in UNICODE_EXAMPLES: + for b in (-1, 0, 1, 2, 3, 4, 5, 7, 8, 15, 70): + self.assertEqual(pyfunc(a, b), + cfunc(a, b)) + self.assertEqual(pyfunc(b, a), + cfunc(b, a)) + + def test_repeat_exception_float(self): + self.disable_leak_check() + cfunc = njit(repeat_usecase) + with self.assertRaises(TypingError) as raises: + cfunc('hi', 2.5) + self.assertIn(_header_lead + ' Function()', + str(raises.exception)) + + def test_split_exception_empty_sep(self): + self.disable_leak_check() + + pyfunc = split_usecase + cfunc = njit(pyfunc) + + # Handle empty separator exception + for func in [pyfunc, cfunc]: + with self.assertRaises(ValueError) as raises: + func('a', '') + self.assertIn('empty separator', str(raises.exception)) + + def test_split_exception_noninteger_maxsplit(self): + pyfunc = split_with_maxsplit_usecase + cfunc = njit(pyfunc) + + # Handle non-integer maxsplit exception + for sep in [' ', None]: + with self.assertRaises(TypingError) as raises: + cfunc('a', sep, 2.4) + self.assertIn('float64', str(raises.exception), + 'non-integer maxsplit with sep = %s' % sep) + + def test_split(self): + pyfunc = split_usecase + cfunc = njit(pyfunc) + + CASES = [ + (' a ', None), + ('', '⚡'), + ('abcabc', '⚡'), + ('🐍⚡', '⚡'), + ('🐍⚡🐍', '⚡'), + ('abababa', 'a'), + ('abababa', 'b'), + ('abababa', 'c'), + ('abababa', 'ab'), + ('abababa', 'aba'), + ] + + for test_str, splitter in CASES: + self.assertEqual(pyfunc(test_str, splitter), + cfunc(test_str, splitter), + "'%s'.split('%s')?" % (test_str, splitter)) + + def test_split_with_maxsplit(self): + CASES = [ + (' a ', None, 1), + ('', '⚡', 1), + ('abcabc', '⚡', 1), + ('🐍⚡', '⚡', 1), + ('🐍⚡🐍', '⚡', 1), + ('abababa', 'a', 2), + ('abababa', 'b', 1), + ('abababa', 'c', 2), + ('abababa', 'ab', 1), + ('abababa', 'aba', 5), + ] + + for pyfunc, fmt_str in [(split_with_maxsplit_usecase, + "'%s'.split('%s', %d)?"), + (split_with_maxsplit_kwarg_usecase, + "'%s'.split('%s', maxsplit=%d)?")]: + + cfunc = njit(pyfunc) + for test_str, splitter, maxsplit in CASES: + self.assertEqual(pyfunc(test_str, splitter, maxsplit), + cfunc(test_str, splitter, maxsplit), + fmt_str % (test_str, splitter, maxsplit)) + + def test_split_whitespace(self): + # explicit sep=None cases covered in test_split and + # test_split_with_maxsplit + pyfunc = split_whitespace_usecase + cfunc = njit(pyfunc) + + # list copied from + # https://github.com/python/cpython/blob/master/Objects/unicodetype_db.h + all_whitespace = ''.join(map(chr, [ + 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x001C, 0x001D, 0x001E, + 0x001F, 0x0020, 0x0085, 0x00A0, 0x1680, 0x2000, 0x2001, 0x2002, + 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, + 0x2028, 0x2029, 0x202F, 0x205F, 0x3000 + ])) + + CASES = [ + '', + 'abcabc', + '🐍 ⚡', + '🐍 ⚡ 🐍', + '🐍 ⚡ 🐍 ', + ' 🐍 ⚡ 🐍', + ' 🐍' + all_whitespace + '⚡ 🐍 ', + ] + for test_str in CASES: + self.assertEqual(pyfunc(test_str), + cfunc(test_str), + "'%s'.split()?" % (test_str,)) + + def test_split_exception_invalid_keepends(self): + pyfunc = splitlines_with_keepends_usecase + cfunc = njit(pyfunc) + + accepted_types = (types.Integer, int, types.Boolean, bool) + for ty, keepends in (('none', None), ('unicode_type', 'None')): + with self.assertRaises(TypingError) as raises: + cfunc('\n', keepends) + msg = '"keepends" must be {}, not {}'.format(accepted_types, ty) + self.assertIn(msg, str(raises.exception)) + + def test_splitlines(self): + pyfunc = splitlines_usecase + cfunc = njit(pyfunc) + + cases = ['', '\n', 'abc\r\rabc\r\n', '🐍⚡\v', '\f🐍⚡\f\v\v🐍\x85', + '\u2028aba\u2029baba', '\n\r\na\v\fb\x0b\x0cc\x1c\x1d\x1e'] + + msg = 'Results of "{}".splitlines() must be equal' + for s in cases: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_splitlines_with_keepends(self): + pyfuncs = [ + splitlines_with_keepends_usecase, + splitlines_with_keepends_kwarg_usecase + ] + messages = [ + 'Results of "{}".splitlines({}) must be equal', + 'Results of "{}".splitlines(keepends={}) must be equal' + ] + cases = ['', '\n', 'abc\r\rabc\r\n', '🐍⚡\v', '\f🐍⚡\f\v\v🐍\x85', + '\u2028aba\u2029baba', '\n\r\na\v\fb\x0b\x0cc\x1c\x1d\x1e'] + all_keepends = [True, False, 0, 1, -1, 100] + + for pyfunc, msg in zip(pyfuncs, messages): + cfunc = njit(pyfunc) + for s, keepends in product(cases, all_keepends): + self.assertEqual(pyfunc(s, keepends), cfunc(s, keepends), + msg=msg.format(s, keepends)) + + def test_rsplit_exception_empty_sep(self): + self.disable_leak_check() + + pyfunc = rsplit_usecase + cfunc = njit(pyfunc) + + # Handle empty separator exception + for func in [pyfunc, cfunc]: + with self.assertRaises(ValueError) as raises: + func('a', '') + self.assertIn('empty separator', str(raises.exception)) + + def test_rsplit_exception_noninteger_maxsplit(self): + pyfunc = rsplit_with_maxsplit_usecase + cfunc = njit(pyfunc) + + accepted_types = (types.Integer, int) + for sep in [' ', None]: + with self.assertRaises(TypingError) as raises: + cfunc('a', sep, 2.4) + msg = '"maxsplit" must be {}, not float'.format(accepted_types) + self.assertIn(msg, str(raises.exception)) + + def test_rsplit(self): + pyfunc = rsplit_usecase + cfunc = njit(pyfunc) + + CASES = [ + (' a ', None), + ('', '⚡'), + ('abcabc', '⚡'), + ('🐍⚡', '⚡'), + ('🐍⚡🐍', '⚡'), + ('abababa', 'a'), + ('abababa', 'b'), + ('abababa', 'c'), + ('abababa', 'ab'), + ('abababa', 'aba'), + ] + msg = 'Results of "{}".rsplit("{}") must be equal' + for s, sep in CASES: + self.assertEqual(pyfunc(s, sep), cfunc(s, sep), + msg=msg.format(s, sep)) + + def test_rsplit_with_maxsplit(self): + pyfuncs = [rsplit_with_maxsplit_usecase, + rsplit_with_maxsplit_kwarg_usecase] + CASES = [ + (' a ', None, 1), + ('', '⚡', 1), + ('abcabc', '⚡', 1), + ('🐍⚡', '⚡', 1), + ('🐍⚡🐍', '⚡', 1), + ('abababa', 'a', 2), + ('abababa', 'b', 1), + ('abababa', 'c', 2), + ('abababa', 'ab', 1), + ('abababa', 'aba', 5), + ] + messages = [ + 'Results of "{}".rsplit("{}", {}) must be equal', + 'Results of "{}".rsplit("{}", maxsplit={}) must be equal' + ] + + for pyfunc, msg in zip(pyfuncs, messages): + cfunc = njit(pyfunc) + for test_str, sep, maxsplit in CASES: + self.assertEqual(pyfunc(test_str, sep, maxsplit), + cfunc(test_str, sep, maxsplit), + msg=msg.format(test_str, sep, maxsplit)) + + def test_rsplit_whitespace(self): + pyfunc = rsplit_whitespace_usecase + cfunc = njit(pyfunc) + + # list copied from + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodetype_db.h#L5996-L6031 # noqa: E501 + all_whitespace = ''.join(map(chr, [ + 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x001C, 0x001D, 0x001E, + 0x001F, 0x0020, 0x0085, 0x00A0, 0x1680, 0x2000, 0x2001, 0x2002, + 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, + 0x2028, 0x2029, 0x202F, 0x205F, 0x3000 + ])) + + CASES = [ + '', + 'abcabc', + '🐍 ⚡', + '🐍 ⚡ 🐍', + '🐍 ⚡ 🐍 ', + ' 🐍 ⚡ 🐍', + ' 🐍' + all_whitespace + '⚡ 🐍 ', + ] + msg = 'Results of "{}".rsplit() must be equal' + for s in CASES: + self.assertEqual(pyfunc(s), cfunc(s), msg.format(s)) + + def test_join_empty(self): + # Can't pass empty list to nopython mode, so we have to make a + # separate test case + pyfunc = join_empty_usecase + cfunc = njit(pyfunc) + + CASES = [ + '', + '🐍🐍🐍', + ] + + for sep in CASES: + self.assertEqual(pyfunc(sep), + cfunc(sep), + "'%s'.join([])?" % (sep,)) + + def test_join_non_string_exception(self): + # Verify that join of list of integers raises typing exception + pyfunc = join_usecase + cfunc = njit(pyfunc) + + # Handle empty separator exception + with self.assertRaises(TypingError) as raises: + cfunc('', [1, 2, 3]) + # This error message is obscure, but indicates the error was trapped + # in the typing of str.join() + # Feel free to change this as we update error messages. + exc_message = str(raises.exception) + self.assertIn( + "During: resolving callee type: BoundFunction", + exc_message, + ) + # could be int32 or int64 + self.assertIn("reflected list(int", exc_message) + + def test_join(self): + pyfunc = join_usecase + cfunc = njit(pyfunc) + + CASES = [ + ('', ['', '', '']), + ('a', ['', '', '']), + ('', ['a', 'bbbb', 'c']), + ('🐍🐍🐍', ['⚡⚡'] * 5), + ] + + for sep, parts in CASES: + self.assertEqual(pyfunc(sep, parts), + cfunc(sep, parts), + "'%s'.join('%s')?" % (sep, parts)) + + def test_join_interleave_str(self): + # can pass a string as the parts iterable + pyfunc = join_usecase + cfunc = njit(pyfunc) + + CASES = [ + ('abc', '123'), + ('🐍🐍🐍', '⚡⚡'), + ] + + for sep, parts in CASES: + self.assertEqual(pyfunc(sep, parts), + cfunc(sep, parts), + "'%s'.join('%s')?" % (sep, parts)) + + def test_justification(self): + for pyfunc, case_name in [(center_usecase, 'center'), + (ljust_usecase, 'ljust'), + (rjust_usecase, 'rjust')]: + cfunc = njit(pyfunc) + + with self.assertRaises(TypingError) as raises: + cfunc(UNICODE_EXAMPLES[0], 1.1) + self.assertIn('The width must be an Integer', str(raises.exception)) + + for s in UNICODE_EXAMPLES: + for width in range(-3, 20): + self.assertEqual(pyfunc(s, width), + cfunc(s, width), + "'%s'.%s(%d)?" % (s, case_name, width)) + + def test_justification_fillchar(self): + for pyfunc, case_name in [(center_usecase_fillchar, 'center'), + (ljust_usecase_fillchar, 'ljust'), + (rjust_usecase_fillchar, 'rjust')]: + cfunc = njit(pyfunc) + + # allowed fillchar cases + for fillchar in [' ', '+', 'ú', '处']: + with self.assertRaises(TypingError) as raises: + cfunc(UNICODE_EXAMPLES[0], 1.1, fillchar) + self.assertIn('The width must be an Integer', + str(raises.exception)) + + for s in UNICODE_EXAMPLES: + for width in range(-3, 20): + self.assertEqual(pyfunc(s, width, fillchar), + cfunc(s, width, fillchar), + "'%s'.%s(%d, '%s')?" % (s, case_name, + width, + fillchar)) + + def test_justification_fillchar_exception(self): + self.disable_leak_check() + + for pyfunc in [center_usecase_fillchar, + ljust_usecase_fillchar, + rjust_usecase_fillchar]: + cfunc = njit(pyfunc) + + # disallowed fillchar cases + for fillchar in ['', '+0', 'quién', '处着']: + with self.assertRaises(ValueError) as raises: + cfunc(UNICODE_EXAMPLES[0], 20, fillchar) + self.assertIn('The fill character must be exactly one', + str(raises.exception)) + + # forbid fillchar cases with different types + for fillchar in [1, 1.1]: + with self.assertRaises(TypingError) as raises: + cfunc(UNICODE_EXAMPLES[0], 20, fillchar) + self.assertIn('The fillchar must be a UnicodeType', + str(raises.exception)) + + def test_inplace_concat(self, flags=no_pyobj_flags): + pyfunc = inplace_concat_usecase + cfunc = njit(pyfunc) + for a in UNICODE_EXAMPLES: + for b in UNICODE_EXAMPLES[::-1]: + self.assertEqual(pyfunc(a, b), + cfunc(a, b), + "'%s' + '%s'?" % (a, b)) + + def test_isidentifier(self): + def pyfunc(s): + return s.isidentifier() + + cfunc = njit(pyfunc) + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L695-L708 # noqa: E501 + cpython = ['a', 'Z', '_', 'b0', 'bc', 'b_', 'µ', + '𝔘𝔫𝔦𝔠𝔬𝔡𝔢', ' ', '[', '©', '0'] + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L742-L749 # noqa: E501 + cpython_extras = ['\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF', + 'a\uD800b\uDFFF', 'a\uDFFFb\uD800', + 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'] + + msg = 'Results of "{}".isidentifier() must be equal' + for s in UNICODE_EXAMPLES + [''] + cpython + cpython_extras: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_strip(self): + + STRIP_CASES = [ + ('ass cii', 'ai'), + ('ass cii', None), + ('asscii', 'ai '), + ('asscii ', 'ai '), + (' asscii ', 'ai '), + (' asscii ', 'asci '), + (' asscii ', 's'), + (' ', ' '), + ('', ' '), + ('', ''), + ('', None), + (' ', None), + (' asscii ', 'ai '), + (' asscii ', ''), + (' asscii ', None), + ('tú quién te crees?', 'étú? '), + (' tú quién te crees? ', 'étú? '), + (' tú qrees? ', ''), + (' tú quién te crees? ', None), + ('大处 着眼,小处着手。大大大处', '大处'), + (' 大处大处 ', ''), + ('\t\nabcd\t', '\ta'), + (' 大处大处 ', None), + ('\t abcd \t', None), + ('\n abcd \n', None), + ('\r abcd \r', None), + ('\x0b abcd \x0b', None), + ('\x0c abcd \x0c', None), + ('\u2029abcd\u205F', None), + ('\u0085abcd\u2009', None) + ] + + # form with no parameter + for pyfunc, case_name in [(strip_usecase, 'strip'), + (lstrip_usecase, 'lstrip'), + (rstrip_usecase, 'rstrip')]: + cfunc = njit(pyfunc) + + for string, chars in STRIP_CASES: + self.assertEqual(pyfunc(string), + cfunc(string), + "'%s'.%s()?" % (string, case_name)) + # parametrized form + for pyfunc, case_name in [(strip_usecase_chars, 'strip'), + (lstrip_usecase_chars, 'lstrip'), + (rstrip_usecase_chars, 'rstrip')]: + cfunc = njit(pyfunc) + + sig1 = types.unicode_type(types.unicode_type, + types.Optional(types.unicode_type)) + cfunc_optional = njit([sig1])(pyfunc) + + def try_compile_bad_optional(*args): + bad = types.unicode_type(types.unicode_type, + types.Optional(types.float64)) + njit([bad])(pyfunc) + + for fn in cfunc, try_compile_bad_optional: + with self.assertRaises(TypingError) as raises: + fn('tú quis?', 1.1) + self.assertIn('The arg must be a UnicodeType or None', + str(raises.exception)) + + for fn in cfunc, cfunc_optional: + + for string, chars in STRIP_CASES: + self.assertEqual(pyfunc(string, chars), + fn(string, chars), + "'%s'.%s('%s')?" % (string, case_name, + chars)) + + def test_isspace(self): + def pyfunc(s): + return s.isspace() + + cfunc = njit(pyfunc) + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L613-L621 # noqa: E501 + cpython = ['\u2000', '\u200a', '\u2014', '\U00010401', '\U00010427', + '\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F'] + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L742-L749 # noqa: E501 + cpython_extras = ['\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF', + 'a\uD800b\uDFFF', 'a\uDFFFb\uD800', + 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'] + + msg = 'Results of "{}".isspace() must be equal' + for s in UNICODE_EXAMPLES + [''] + cpython + cpython_extras: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_istitle(self): + pyfunc = istitle_usecase + cfunc = njit(pyfunc) + error_msg = "'{0}'.py_istitle() = {1}\n'{0}'.c_istitle() = {2}" + + unicode_title = [x.title() for x in UNICODE_EXAMPLES] + special = [ + '', + ' ', + ' AA ', + ' Ab ', + '1', + 'A123', + 'A12Bcd', + '+abA', + '12Abc', + 'A12abc', + '%^Abc 5 $% Def' + '𐐁𐐩', + '𐐧𐑎', + '𐐩', + '𐑎', + '🐍 Is', + '🐍 NOT', + '👯Is', + 'ῼ', + 'Greek ῼitlecases ...' + ] + ISTITLE_EXAMPLES = UNICODE_EXAMPLES + unicode_title + special + + for s in ISTITLE_EXAMPLES: + py_result = pyfunc(s) + c_result = cfunc(s) + self.assertEqual(py_result, c_result, + error_msg.format(s, py_result, c_result)) + + def test_isprintable(self): + def pyfunc(s): + return s.isprintable() + + cfunc = njit(pyfunc) + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L710-L723 # noqa: E501 + cpython = ['', ' ', 'abcdefg', 'abcdefg\n', '\u0374', '\u0378', + '\ud800', '\U0001F46F', '\U000E0020'] + + msg = 'Results of "{}".isprintable() must be equal' + for s in UNICODE_EXAMPLES + cpython: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_pointless_slice(self, flags=no_pyobj_flags): + def pyfunc(a): + return a[:] + cfunc = njit(pyfunc) + args = ['a'] + self.assertEqual(pyfunc(*args), cfunc(*args)) + + def test_walk_backwards(self, flags=no_pyobj_flags): + def pyfunc(a): + return a[::-1] + cfunc = njit(pyfunc) + args = ['a'] + self.assertEqual(pyfunc(*args), cfunc(*args)) + + def test_stride_slice(self, flags=no_pyobj_flags): + def pyfunc(a): + return a[::2] + cfunc = njit(pyfunc) + args = ['a'] + self.assertEqual(pyfunc(*args), cfunc(*args)) + + def test_basic_lt(self, flags=no_pyobj_flags): + def pyfunc(a, b): + return a < b + cfunc = njit(pyfunc) + args = ['ab', 'b'] + self.assertEqual(pyfunc(*args), cfunc(*args)) + + def test_basic_gt(self, flags=no_pyobj_flags): + def pyfunc(a, b): + return a > b + cfunc = njit(pyfunc) + args = ['ab', 'b'] + self.assertEqual(pyfunc(*args), cfunc(*args)) + + def test_comparison(self): + def pyfunc(option, x, y): + if option == '==': + return x == y + elif option == '!=': + return x != y + elif option == '<': + return x < y + elif option == '>': + return x > y + elif option == '<=': + return x <= y + elif option == '>=': + return x >= y + else: + return None + + cfunc = njit(pyfunc) + + for x, y in permutations(UNICODE_ORDERING_EXAMPLES, r=2): + for cmpop in ['==', '!=', '<', '>', '<=', '>=', '']: + args = [cmpop, x, y] + self.assertEqual(pyfunc(*args), cfunc(*args), + msg='failed on {}'.format(args)) + + def test_literal_concat(self): + def pyfunc(x): + abc = 'abc' + if len(x): + return abc + 'b123' + x + 'IO' + else: + return x + abc + '123' + x + + cfunc = njit(pyfunc) + args = ['x'] + self.assertEqual(pyfunc(*args), cfunc(*args)) + args = [''] + self.assertEqual(pyfunc(*args), cfunc(*args)) + + def test_literal_comparison(self): + def pyfunc(option): + x = 'a123' + y = 'aa12' + if option == '==': + return x == y + elif option == '!=': + return x != y + elif option == '<': + return x < y + elif option == '>': + return x > y + elif option == '<=': + return x <= y + elif option == '>=': + return x >= y + else: + return None + + cfunc = njit(pyfunc) + for cmpop in ['==', '!=', '<', '>', '<=', '>=', '']: + args = [cmpop] + self.assertEqual(pyfunc(*args), cfunc(*args), + msg='failed on {}'.format(args)) + + def test_literal_len(self): + def pyfunc(): + return len('abc') + cfunc = njit(pyfunc) + self.assertEqual(pyfunc(), cfunc()) + + def test_literal_getitem(self): + def pyfunc(which): + return 'abc'[which] + cfunc = njit(pyfunc) + for a in [-1, 0, 1, slice(1, None), slice(None, -1)]: + args = [a] + self.assertEqual(pyfunc(*args), cfunc(*args), + msg='failed on {}'.format(args)) + + def test_literal_in(self): + def pyfunc(x): + return x in '9876zabiuh' + + cfunc = njit(pyfunc) + for a in ['a', '9', '1', '', '8uha', '987']: + args = [a] + self.assertEqual(pyfunc(*args), cfunc(*args), + msg='failed on {}'.format(args)) + + def test_literal_xyzwith(self): + def pyfunc(x, y): + return 'abc'.startswith(x), 'cde'.endswith(y) + + cfunc = njit(pyfunc) + for args in permutations('abcdefg', r=2): + self.assertEqual(pyfunc(*args), cfunc(*args), + msg='failed on {}'.format(args)) + + def test_literal_find(self): + def pyfunc(x): + return 'abc'.find(x), x.find('a') + + cfunc = njit(pyfunc) + for a in ['ab']: + args = [a] + self.assertEqual(pyfunc(*args), cfunc(*args), + msg='failed on {}'.format(args)) + + def test_not(self): + def pyfunc(x): + return not x + + cfunc = njit(pyfunc) + for a in UNICODE_EXAMPLES: + args = [a] + self.assertEqual(pyfunc(*args), cfunc(*args), + msg='failed on {}'.format(args)) + + def test_capitalize(self): + def pyfunc(x): + return x.capitalize() + + cfunc = njit(pyfunc) + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L800-L815 # noqa: E501 + cpython = ['\U0001044F', '\U0001044F\U0001044F', '\U00010427\U0001044F', + '\U0001044F\U00010427', 'X\U00010427x\U0001044F', 'h\u0130', + '\u1fd2\u0130', 'finnish', 'A\u0345\u03a3'] + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L926 # noqa: E501 + cpython_extras = ['\U00010000\U00100000'] + + msg = 'Results of "{}".capitalize() must be equal' + for s in UNICODE_EXAMPLES + [''] + cpython + cpython_extras: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_isupper(self): + def pyfunc(x): + return x.isupper() + + cfunc = njit(pyfunc) + uppers = [x.upper() for x in UNICODE_EXAMPLES] + extras = ["AA12A", "aa12a", "大AA12A", "大aa12a", "AAADŽA", "A 1 1 大"] + + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L585-L599 # noqa: E501 + cpython = ['\u2167', '\u2177', '\U00010401', '\U00010427', '\U00010429', + '\U0001044E', '\U0001F40D', '\U0001F46F'] + fourxcpy = [x * 4 for x in cpython] + + for a in UNICODE_EXAMPLES + uppers + extras + cpython + fourxcpy: + args = [a] + self.assertEqual(pyfunc(*args), cfunc(*args), + msg='failed on {}'.format(args)) + + def test_upper(self): + def pyfunc(x): + return x.upper() + + cfunc = njit(pyfunc) + for a in UNICODE_EXAMPLES: + args = [a] + self.assertEqual(pyfunc(*args), cfunc(*args), + msg='failed on {}'.format(args)) + + def test_casefold(self): + def pyfunc(x): + return x.casefold() + + cfunc = njit(pyfunc) + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L774-L781 # noqa: E501 + cpython = ['hello', 'hELlo', 'ß', 'fi', '\u03a3', + 'A\u0345\u03a3', '\u00b5'] + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L924 # noqa: E501 + cpython_extras = ['\U00010000\U00100000'] + + msg = 'Results of "{}".casefold() must be equal' + for s in UNICODE_EXAMPLES + [''] + cpython + cpython_extras: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_isalpha(self): + def pyfunc(x): + return x.isalpha() + + cfunc = njit(pyfunc) + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Lib/test/test_unicode.py#L630-L640 # noqa: E501 + cpython = ['\u1FFc', '\U00010401', '\U00010427', '\U00010429', + '\U0001044E', '\U0001F40D', '\U0001F46F'] + # https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Lib/test/test_unicode.py#L738-L745 # noqa: E501 + extras = ['\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF', + 'a\uD800b\uDFFF', 'a\uDFFFb\uD800', + 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'] + + msg = 'Results of "{}".isalpha() must be equal' + for s in UNICODE_EXAMPLES + [''] + extras + cpython: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_isascii(self): + def pyfunc(x): + return x.isascii() + + cfunc = njit(pyfunc) + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/865c3b257fe38154a4320c7ee6afb416f665b9c2/Lib/test/string_tests.py#L913-L926 # noqa: E501 + cpython = ['', '\x00', '\x7f', '\x00\x7f', '\x80', '\xe9', ' '] + + msg = 'Results of "{}".isascii() must be equal' + for s in UNICODE_EXAMPLES + cpython: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_title(self): + pyfunc = title + cfunc = njit(pyfunc) + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Lib/test/test_unicode.py#L813-L828 # noqa: E501 + cpython = ['\U0001044F', '\U0001044F\U0001044F', + '\U0001044F\U0001044F \U0001044F\U0001044F', + '\U00010427\U0001044F \U00010427\U0001044F', + '\U0001044F\U00010427 \U0001044F\U00010427', + 'X\U00010427x\U0001044F X\U00010427x\U0001044F', + 'fiNNISH', 'A\u03a3 \u1fa1xy', 'A\u03a3A'] + + msg = 'Results of "{}".title() must be equal' + for s in UNICODE_EXAMPLES + [''] + cpython: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_swapcase(self): + def pyfunc(x): + return x.swapcase() + + cfunc = njit(pyfunc) + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L834-L858 # noqa: E501 + cpython = ['\U0001044F', '\U00010427', '\U0001044F\U0001044F', + '\U00010427\U0001044F', '\U0001044F\U00010427', + 'X\U00010427x\U0001044F', 'fi', '\u0130', '\u03a3', + '\u0345\u03a3', 'A\u0345\u03a3', 'A\u0345\u03a3a', + 'A\u0345\u03a3', 'A\u03a3\u0345', '\u03a3\u0345 ', + '\u03a3', 'ß', '\u1fd2'] + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L928 # noqa: E501 + cpython_extras = ['\U00010000\U00100000'] + + msg = 'Results of "{}".swapcase() must be equal' + for s in UNICODE_EXAMPLES + [''] + cpython + cpython_extras: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_islower(self): + pyfunc = islower_usecase + cfunc = njit(pyfunc) + lowers = [x.lower() for x in UNICODE_EXAMPLES] + extras = ['AA12A', 'aa12a', '大AA12A', '大aa12a', 'AAADŽA', 'A 1 1 大'] + + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Lib/test/test_unicode.py#L586-L600 # noqa: E501 + cpython = ['\u2167', '\u2177', '\U00010401', '\U00010427', + '\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F'] + cpython += [x * 4 for x in cpython] + + msg = 'Results of "{}".islower() must be equal' + for s in UNICODE_EXAMPLES + lowers + [''] + extras + cpython: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_isalnum(self): + def pyfunc(x): + return x.isalnum() + + cfunc = njit(pyfunc) + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Lib/test/test_unicode.py#L624-L628 # noqa: E501 + cpython = ['\U00010401', '\U00010427', '\U00010429', '\U0001044E', + '\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107'] + # https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Lib/test/test_unicode.py#L738-L745 # noqa: E501 + extras = ['\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF', + 'a\uD800b\uDFFF', 'a\uDFFFb\uD800', + 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'] + + msg = 'Results of "{}".isalnum() must be equal' + for s in UNICODE_EXAMPLES + [''] + extras + cpython: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_lower(self): + pyfunc = lower_usecase + cfunc = njit(pyfunc) + extras = ['AA12A', 'aa12a', '大AA12A', '大aa12a', 'AAADŽA', 'A 1 1 大'] + + # Samples taken from CPython testing: + # https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Lib/test/test_unicode.py#L748-L758 # noqa: E501 + cpython = ['\U00010401', '\U00010427', '\U0001044E', '\U0001F46F', + '\U00010427\U00010427', '\U00010427\U0001044F', + 'X\U00010427x\U0001044F', '\u0130'] + + # special cases for sigma from CPython testing: + # https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Lib/test/test_unicode.py#L759-L768 # noqa: E501 + sigma = ['\u03a3', '\u0345\u03a3', 'A\u0345\u03a3', 'A\u0345\u03a3a', + '\u03a3\u0345 ', '\U0008fffe', '\u2177'] + + extra_sigma = 'A\u03a3\u03a2' + sigma.append(extra_sigma) + + msg = 'Results of "{}".lower() must be equal' + for s in UNICODE_EXAMPLES + [''] + extras + cpython + sigma: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_isnumeric(self): + def pyfunc(x): + return x.isnumeric() + + cfunc = njit(pyfunc) + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L676-L693 # noqa: E501 + cpython = ['', 'a', '0', '\u2460', '\xbc', '\u0660', '0123456789', + '0123456789a', '\U00010401', '\U00010427', '\U00010429', + '\U0001044E', '\U0001F40D', '\U0001F46F', '\U00011065', + '\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107'] + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L742-L749 # noqa: E501 + cpython_extras = ['\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF', + 'a\uD800b\uDFFF', 'a\uDFFFb\uD800', 'a\uD800b\uDFFFa', + 'a\uDFFFb\uD800a'] + + msg = 'Results of "{}".isnumeric() must be equal' + for s in UNICODE_EXAMPLES + [''] + cpython + cpython_extras: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_isdigit(self): + def pyfunc(x): + return x.isdigit() + + cfunc = njit(pyfunc) + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L664-L674 # noqa: E501 + cpython = ['\u2460', '\xbc', '\u0660', '\U00010401', '\U00010427', + '\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F', + '\U00011065', '\U0001D7F6', '\U00011066', '\U000104A0', + '\U0001F107'] + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L742-L749 # noqa: E501 + cpython_extras = ['\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF', + 'a\uD800b\uDFFF', 'a\uDFFFb\uD800', + 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'] + + msg = 'Results of "{}".isdigit() must be equal' + for s in UNICODE_EXAMPLES + [''] + cpython + cpython_extras: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_isdecimal(self): + def pyfunc(x): + return x.isdecimal() + + cfunc = njit(pyfunc) + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L646-L662 # noqa: E501 + cpython = ['', 'a', '0', '\u2460', '\xbc', '\u0660', '0123456789', + '0123456789a', '\U00010401', '\U00010427', '\U00010429', + '\U0001044E', '\U0001F40D', '\U0001F46F', '\U00011065', + '\U0001F107', '\U0001D7F6', '\U00011066', '\U000104A0'] + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Lib/test/test_unicode.py#L742-L749 # noqa: E501 + cpython_extras = ['\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF', + 'a\uD800b\uDFFF', 'a\uDFFFb\uD800', 'a\uD800b\uDFFFa', + 'a\uDFFFb\uD800a'] + + msg = 'Results of "{}".isdecimal() must be equal' + for s in UNICODE_EXAMPLES + [''] + cpython + cpython_extras: + self.assertEqual(pyfunc(s), cfunc(s), msg=msg.format(s)) + + def test_replace(self): + pyfunc = replace_usecase + cfunc = njit(pyfunc) + + CASES = [ + ('abc', '', 'A'), + ('', '⚡', 'A'), + ('abcabc', '⚡', 'A'), + ('🐍⚡', '⚡', 'A'), + ('🐍⚡🐍', '⚡', 'A'), + ('abababa', 'a', 'A'), + ('abababa', 'b', 'A'), + ('abababa', 'c', 'A'), + ('abababa', 'ab', 'A'), + ('abababa', 'aba', 'A'), + ] + + for test_str, old_str, new_str in CASES: + self.assertEqual(pyfunc(test_str, old_str, new_str), + cfunc(test_str, old_str, new_str), + "'%s'.replace('%s', '%s')?" % + (test_str, old_str, new_str)) + + def test_replace_with_count(self): + pyfunc = replace_with_count_usecase + cfunc = njit(pyfunc) + + CASES = [ + ('abc', '', 'A'), + ('', '⚡', 'A'), + ('abcabc', '⚡', 'A'), + ('🐍⚡', '⚡', 'A'), + ('🐍⚡🐍', '⚡', 'A'), + ('abababa', 'a', 'A'), + ('abababa', 'b', 'A'), + ('abababa', 'c', 'A'), + ('abababa', 'ab', 'A'), + ('abababa', 'aba', 'A'), + ] + + count_test = [-1, 1, 0, 5] + + for test_str, old_str, new_str in CASES: + for count in count_test: + self.assertEqual(pyfunc(test_str, old_str, new_str, count), + cfunc(test_str, old_str, new_str, count), + "'%s'.replace('%s', '%s', '%s')?" % + (test_str, old_str, new_str, count)) + + def test_replace_unsupported(self): + def pyfunc(s, x, y, count): + return s.replace(x, y, count) + + cfunc = njit(pyfunc) + + with self.assertRaises(TypingError) as raises: + cfunc('ababababab', 'ba', 'qqq', 3.5) + msg = 'Unsupported parameters. The parameters must be Integer.' + self.assertIn(msg, str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc('ababababab', 0, 'qqq', 3) + msg = 'The object must be a UnicodeType.' + self.assertIn(msg, str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc('ababababab', 'ba', 0, 3) + msg = 'The object must be a UnicodeType.' + self.assertIn(msg, str(raises.exception)) + + +class TestUnicodeInTuple(BaseTest): + + def test_const_unicode_in_tuple(self): + # Issue 3673 + @njit + def f(): + return ('aa',) < ('bb',) + + self.assertEqual(f.py_func(), f()) + + @njit + def f(): + return ('cc',) < ('bb',) + + self.assertEqual(f.py_func(), f()) + + def test_const_unicode_in_hetero_tuple(self): + @njit + def f(): + return ('aa', 1) < ('bb', 1) + + self.assertEqual(f.py_func(), f()) + + @njit + def f(): + return ('aa', 1) < ('aa', 2) + + self.assertEqual(f.py_func(), f()) + + def test_ascii_flag_unbox(self): + @njit + def f(s): + return s._is_ascii + + for s in UNICODE_EXAMPLES: + self.assertEqual(f(s), isascii(s)) + + def test_ascii_flag_join(self): + @njit + def f(): + s1 = 'abc' + s2 = '123' + s3 = '🐍⚡' + s4 = '大处着眼,小处着手。' + return (",".join([s1, s2])._is_ascii, + "🐍⚡".join([s1, s2])._is_ascii, + ",".join([s1, s3])._is_ascii, + ",".join([s3, s4])._is_ascii) + + self.assertEqual(f(), (1, 0, 0, 0)) + + def test_ascii_flag_getitem(self): + @njit + def f(): + s1 = 'abc123' + s2 = '🐍⚡🐍⚡🐍⚡' + return (s1[0]._is_ascii, s1[2:]._is_ascii, s2[0]._is_ascii, + s2[2:]._is_ascii) + + self.assertEqual(f(), (1, 1, 0, 0)) + + def test_ascii_flag_add_mul(self): + @njit + def f(): + s1 = 'abc' + s2 = '123' + s3 = '🐍⚡' + s4 = '大处着眼,小处着手。' + return ((s1 + s2)._is_ascii, + (s1 + s3)._is_ascii, + (s3 + s4)._is_ascii, + (s1 * 2)._is_ascii, + (s3 * 2)._is_ascii) + + self.assertEqual(f(), (1, 0, 0, 1, 0)) + + +class TestUnicodeIteration(BaseTest): + + def test_unicode_iter(self): + pyfunc = iter_usecase + cfunc = njit(pyfunc) + for a in UNICODE_EXAMPLES: + self.assertPreciseEqual(pyfunc(a), cfunc(a)) + + def test_unicode_literal_iter(self): + pyfunc = literal_iter_usecase + cfunc = njit(pyfunc) + self.assertPreciseEqual(pyfunc(), cfunc()) + + def test_unicode_enumerate_iter(self): + pyfunc = enumerated_iter_usecase + cfunc = njit(pyfunc) + for a in UNICODE_EXAMPLES: + self.assertPreciseEqual(pyfunc(a), cfunc(a)) + + def test_unicode_stopiteration_iter(self): + self.disable_leak_check() + pyfunc = iter_stopiteration_usecase + cfunc = njit(pyfunc) + for f in (pyfunc, cfunc): + for a in UNICODE_EXAMPLES: + with self.assertRaises(StopIteration): + f(a) + + def test_unicode_literal_stopiteration_iter(self): + pyfunc = literal_iter_stopiteration_usecase + cfunc = njit(pyfunc) + for f in (pyfunc, cfunc): + with self.assertRaises(StopIteration): + f() + + +class TestUnicodeAuxillary(BaseTest): + + def test_ord(self): + pyfunc = ord_usecase + cfunc = njit(pyfunc) + for ex in UNICODE_EXAMPLES: + for a in ex: + self.assertPreciseEqual(pyfunc(a), cfunc(a)) + + def test_ord_invalid(self): + self.disable_leak_check() + + pyfunc = ord_usecase + cfunc = njit(pyfunc) + + # wrong number of chars + for func in (pyfunc, cfunc): + for ch in ('', 'abc'): + with self.assertRaises(TypeError) as raises: + func(ch) + self.assertIn('ord() expected a character', + str(raises.exception)) + + # wrong type + with self.assertRaises(TypingError) as raises: + cfunc(1.23) + self.assertIn(_header_lead, str(raises.exception)) + + def test_chr(self): + pyfunc = chr_usecase + cfunc = njit(pyfunc) + for ex in UNICODE_EXAMPLES: + for x in ex: + a = ord(x) + self.assertPreciseEqual(pyfunc(a), cfunc(a)) + # test upper/lower bounds + for a in (0x0, _MAX_UNICODE): + self.assertPreciseEqual(pyfunc(a), cfunc(a)) + + def test_chr_invalid(self): + pyfunc = chr_usecase + cfunc = njit(pyfunc) + + # value negative/>_MAX_UNICODE + for func in (pyfunc, cfunc): + for v in (-2, _MAX_UNICODE + 1): + with self.assertRaises(ValueError) as raises: + func(v) + self.assertIn("chr() arg not in range", str(raises.exception)) + + # wrong type + with self.assertRaises(TypingError) as raises: + cfunc('abc') + self.assertIn(_header_lead, str(raises.exception)) + + def test_unicode_type_mro(self): + # see issue #5635 + def bar(x): + return True + + @overload(bar) + def ol_bar(x): + ok = False + if isinstance(x, types.UnicodeType): + if isinstance(x, types.Hashable): + ok = True + return lambda x: ok + + @njit + def foo(strinst): + return bar(strinst) + + inst = "abc" + self.assertEqual(foo.py_func(inst), foo(inst)) + self.assertIn(types.Hashable, types.unicode_type.__class__.__mro__) + + def test_f_strings(self): + """test f-string support, which requires bytecode handling + """ + # requires formatting (FORMAT_VALUE) and concatenation (BUILD_STRINGS) + def impl1(a): + return f"AA_{a + 3}_B" + + # does not require concatenation + def impl2(a): + return f"{a + 2}" + + # no expression + def impl3(a): + return f"ABC_{a}" + + # format spec not allowed + def impl4(a): + return f"ABC_{a:0}" + + # corner case: empty string + def impl5(): + return f"" # noqa: F541 + + self.assertEqual(impl1(3), njit(impl1)(3)) + self.assertEqual(impl2(2), njit(impl2)(2)) + # string input + self.assertEqual(impl3("DE"), njit(impl3)("DE")) + + # check output when there's no __str__ or __repr__ defined + list_arg = ["A", "B"] + got = njit(impl3)(list_arg) + expected = f"ABC_" + self.assertEqual(got, expected) + + # check error when format spec provided + unsupported_errors = (UnsupportedError, UnsupportedBytecodeError) + with self.assertRaises(unsupported_errors) as raises: + njit(impl4)(["A", "B"]) + if PYVERSION in ((3, 13), (3, 14), (3, 15)): + msg = "Use of unsupported opcode (FORMAT_WITH_SPEC)" + self.assertIn(msg, str(raises.exception)) + elif PYVERSION in ((3, 10), (3, 11), (3, 12)): + msg = "format spec in f-strings not supported yet" + self.assertIn(msg, str(raises.exception)) + else: + raise NotImplementedError(PYVERSION) + self.assertEqual(impl5(), njit(impl5)()) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/d1/d13744c2cd7cd7bf54732637d88ce57fc6b8cd561beadeb62c4190df13ff3dd9/blob b/shared/package-files/d1/d13744c2cd7cd7bf54732637d88ce57fc6b8cd561beadeb62c4190df13ff3dd9/blob new file mode 100644 index 0000000000000000000000000000000000000000..d82d69ad5dce531b444dd56d1acbc586ff83bb8e --- /dev/null +++ b/shared/package-files/d1/d13744c2cd7cd7bf54732637d88ce57fc6b8cd561beadeb62c4190df13ff3dd9/blob @@ -0,0 +1,148 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +C10_DECLARE_bool(torch_jit_enable_new_executor); + +C10_DECLARE_bool(torch_jit_execution_plan_reuse_code_graph); + +namespace torch::jit { +struct GraphExecutorState; +struct Code; + +enum ExecutorExecutionMode { + SIMPLE, + PROFILING, +}; + +struct ExecutionPlan { + ExecutionPlan() = default; + ExecutionPlan(std::shared_ptr graph, std::string function_name) + : code(graph, std::move(function_name)), + graph( + FLAGS_torch_jit_execution_plan_reuse_code_graph + ? code.graph() + : std::move(graph)) {} + + operator bool() const { + return static_cast(graph); + } + + Code code; + std::shared_ptr graph; +}; + +// Notice that those structs don't manage lifetime of their members. +// They are only valid only right after you call getDebugState() and should +// never be used again once another GraphExecutor function is called. + +// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) +struct GraphExecutorState { + const Graph* graph = nullptr; + ExecutionPlan fallback; // XXX: members of this field are optional + std::unordered_map execution_plans; +}; + +struct TORCH_API EnableProfilingGuard { + EnableProfilingGuard(); + ~EnableProfilingGuard(); + + private: + bool old_executor_mode = false; + bool old_get_optimize = false; +}; + +struct GraphExecutorImplBase; +struct TORCH_API GraphExecutor { + GraphExecutor() = default; + GraphExecutor(const std::shared_ptr& graph, std::string function_name); + + GraphExecutor( + const std::shared_ptr& graph, + std::string function_name, + ExecutorExecutionMode executor_mode); + + void run(Stack& inputs); + c10::intrusive_ptr runAsync( + Stack& stack, + TaskLauncher taskLauncher = at::launch); + + // `remaining_bailout_depth` stands for the maximum number of profiled and + // specialized recompilations allowed for the current `GraphExecutor`. if + // remaining_bailout_depth is equal to 0, `GraphExecutor` won't perform any + // profiling and specialization. This is also equivalent to the + // SIMPLE_EXECUTOR mode. if remaining_bailout_depth is greater than 0, + // `GraphExecutor` will profile and specialize its input graph based on the + // profiled information whenever a bailout check is failed/triggered, a new + // `GraphExecutor` will be created. This new `GraphExecutor`'s + // remaining_bailout_depth will be reduced by 1. + // If no bailout depth is passed, the depth will be initialized from the + // current global fusion strategy settings. + const ExecutionPlan& getPlanFor( + Stack& inputs, + c10::optional remaining_bailout_depth = c10::nullopt); + GraphExecutorState getDebugState(); + + void debugFlushCompilationCache(); + + bool isOptimized() const; + + private: + std::shared_ptr pImpl; +}; + +TORCH_API Node* replaceBlockWithFallbackGraph( + Block* b, + ArrayRef inputs); + +// These passes need to run before it is valid to pass to the interpreter +// regardless of whether sizes have been specialized or not. +TORCH_API void runRequiredPasses(const std::shared_ptr& g); + +TORCH_API void debugSetFusionGroupInlining(bool state); +TORCH_API bool getFusionGroupInlining(); + +TORCH_API void debugSetAutodiffSubgraphInlining(bool state); +TORCH_API std::shared_ptr lastExecutedOptimizedGraph(); + +TORCH_API std::atomic& getProfilingMode(); +TORCH_API std::atomic& getExecutorMode(); +TORCH_API std::atomic& getNumProfiledRuns(); +TORCH_API size_t getBailoutDepth(); +TORCH_API bool IsNewExecutorEnabled(); + +struct TORCH_API GraphOptimizerEnabledGuard { + GraphOptimizerEnabledGuard(bool state) + : old_state_(getGraphExecutorOptimize()) { + setGraphExecutorOptimize(state); + } + + ~GraphOptimizerEnabledGuard() { + setGraphExecutorOptimize(old_state_); + } + + bool old_state_; +}; + +namespace detail { + +GraphExecutor* getGradExecutor(Operation& op); + +GraphExecutor* getDifferentiableGraphOpExecutor(Operation& op); + +// for debugging information we expose a way to get the last actually +// run graph. Previous approaches allowed querying the GraphExecutor +// for what graph it would run in certain circumstances (graphFor), but +// this is fragile because we sometimes change how these decisions are made. +// This interface still allows our tests to look at optimized graphs, but +// with less plumbing. +} // namespace detail + +} // namespace torch::jit diff --git a/shared/package-files/d1/d139a725e64239a4d69de79603ae839712a06946494df3f48ca80b018d638b28/blob b/shared/package-files/d1/d139a725e64239a4d69de79603ae839712a06946494df3f48ca80b018d638b28/blob new file mode 100644 index 0000000000000000000000000000000000000000..680bdaa2e2a44c9603c6465274e4f4cea35e8701 --- /dev/null +++ b/shared/package-files/d1/d139a725e64239a4d69de79603ae839712a06946494df3f48ca80b018d638b28/blob @@ -0,0 +1,23 @@ +import pytest + +import pandas as pd + + +class TestResolution: + @pytest.mark.parametrize( + "freq,expected", + [ + ("Y", "year"), + ("Q", "quarter"), + ("M", "month"), + ("D", "day"), + ("h", "hour"), + ("min", "minute"), + ("s", "second"), + ("ms", "millisecond"), + ("us", "microsecond"), + ], + ) + def test_resolution(self, freq, expected): + idx = pd.period_range(start="2013-04-01", periods=30, freq=freq) + assert idx.resolution == expected diff --git a/shared/package-files/d1/d139acf8eb2a687729587edad85e26a8aa8457e1b96ed8992ad7b77149c45903/blob b/shared/package-files/d1/d139acf8eb2a687729587edad85e26a8aa8457e1b96ed8992ad7b77149c45903/blob new file mode 100644 index 0000000000000000000000000000000000000000..ec2d7d230483947d78f737af42684effa3e60514 --- /dev/null +++ b/shared/package-files/d1/d139acf8eb2a687729587edad85e26a8aa8457e1b96ed8992ad7b77149c45903/blob @@ -0,0 +1,10 @@ +""" +Timeseries API +""" + +from pandas._libs.tslibs.parsing import guess_datetime_format + +from pandas.tseries import offsets +from pandas.tseries.frequencies import infer_freq + +__all__ = ["infer_freq", "offsets", "guess_datetime_format"] diff --git a/shared/package-files/d1/d13ad093943853e1af4974dee049a287a07624983658cbbfbb4a528fddb0a950/blob b/shared/package-files/d1/d13ad093943853e1af4974dee049a287a07624983658cbbfbb4a528fddb0a950/blob new file mode 100644 index 0000000000000000000000000000000000000000..aedf1885058900eece7061d65c53d5704172a596 --- /dev/null +++ b/shared/package-files/d1/d13ad093943853e1af4974dee049a287a07624983658cbbfbb4a528fddb0a950/blob @@ -0,0 +1,174 @@ +"""Singleton mechanism""" + + +from .core import Registry +from .sympify import sympify + + +class SingletonRegistry(Registry): + """ + The registry for the singleton classes (accessible as ``S``). + + Explanation + =========== + + This class serves as two separate things. + + The first thing it is is the ``SingletonRegistry``. Several classes in + SymPy appear so often that they are singletonized, that is, using some + metaprogramming they are made so that they can only be instantiated once + (see the :class:`sympy.core.singleton.Singleton` class for details). For + instance, every time you create ``Integer(0)``, this will return the same + instance, :class:`sympy.core.numbers.Zero`. All singleton instances are + attributes of the ``S`` object, so ``Integer(0)`` can also be accessed as + ``S.Zero``. + + Singletonization offers two advantages: it saves memory, and it allows + fast comparison. It saves memory because no matter how many times the + singletonized objects appear in expressions in memory, they all point to + the same single instance in memory. The fast comparison comes from the + fact that you can use ``is`` to compare exact instances in Python + (usually, you need to use ``==`` to compare things). ``is`` compares + objects by memory address, and is very fast. + + Examples + ======== + + >>> from sympy import S, Integer + >>> a = Integer(0) + >>> a is S.Zero + True + + For the most part, the fact that certain objects are singletonized is an + implementation detail that users should not need to worry about. In SymPy + library code, ``is`` comparison is often used for performance purposes + The primary advantage of ``S`` for end users is the convenient access to + certain instances that are otherwise difficult to type, like ``S.Half`` + (instead of ``Rational(1, 2)``). + + When using ``is`` comparison, make sure the argument is sympified. For + instance, + + >>> x = 0 + >>> x is S.Zero + False + + This problem is not an issue when using ``==``, which is recommended for + most use-cases: + + >>> 0 == S.Zero + True + + The second thing ``S`` is is a shortcut for + :func:`sympy.core.sympify.sympify`. :func:`sympy.core.sympify.sympify` is + the function that converts Python objects such as ``int(1)`` into SymPy + objects such as ``Integer(1)``. It also converts the string form of an + expression into a SymPy expression, like ``sympify("x**2")`` -> + ``Symbol("x")**2``. ``S(1)`` is the same thing as ``sympify(1)`` + (basically, ``S.__call__`` has been defined to call ``sympify``). + + This is for convenience, since ``S`` is a single letter. It's mostly + useful for defining rational numbers. Consider an expression like ``x + + 1/2``. If you enter this directly in Python, it will evaluate the ``1/2`` + and give ``0.5``, because both arguments are ints (see also + :ref:`tutorial-gotchas-final-notes`). However, in SymPy, you usually want + the quotient of two integers to give an exact rational number. The way + Python's evaluation works, at least one side of an operator needs to be a + SymPy object for the SymPy evaluation to take over. You could write this + as ``x + Rational(1, 2)``, but this is a lot more typing. A shorter + version is ``x + S(1)/2``. Since ``S(1)`` returns ``Integer(1)``, the + division will return a ``Rational`` type, since it will call + ``Integer.__truediv__``, which knows how to return a ``Rational``. + + """ + __slots__ = () + + # Also allow things like S(5) + __call__ = staticmethod(sympify) + + def __init__(self): + self._classes_to_install = {} + # Dict of classes that have been registered, but that have not have been + # installed as an attribute of this SingletonRegistry. + # Installation automatically happens at the first attempt to access the + # attribute. + # The purpose of this is to allow registration during class + # initialization during import, but not trigger object creation until + # actual use (which should not happen until after all imports are + # finished). + + def register(self, cls): + # Make sure a duplicate class overwrites the old one + if hasattr(self, cls.__name__): + delattr(self, cls.__name__) + self._classes_to_install[cls.__name__] = cls + + def __getattr__(self, name): + """Python calls __getattr__ if no attribute of that name was installed + yet. + + Explanation + =========== + + This __getattr__ checks whether a class with the requested name was + already registered but not installed; if no, raises an AttributeError. + Otherwise, retrieves the class, calculates its singleton value, installs + it as an attribute of the given name, and unregisters the class.""" + if name not in self._classes_to_install: + raise AttributeError( + "Attribute '%s' was not installed on SymPy registry %s" % ( + name, self)) + class_to_install = self._classes_to_install[name] + value_to_install = class_to_install() + self.__setattr__(name, value_to_install) + del self._classes_to_install[name] + return value_to_install + + def __repr__(self): + return "S" + +S = SingletonRegistry() + + +class Singleton(type): + """ + Metaclass for singleton classes. + + Explanation + =========== + + A singleton class has only one instance which is returned every time the + class is instantiated. Additionally, this instance can be accessed through + the global registry object ``S`` as ``S.``. + + Examples + ======== + + >>> from sympy import S, Basic + >>> from sympy.core.singleton import Singleton + >>> class MySingleton(Basic, metaclass=Singleton): + ... pass + >>> Basic() is Basic() + False + >>> MySingleton() is MySingleton() + True + >>> S.MySingleton is MySingleton() + True + + Notes + ===== + + Instance creation is delayed until the first time the value is accessed. + (SymPy versions before 1.0 would create the instance during class + creation time, which would be prone to import cycles.) + """ + def __init__(cls, *args, **kwargs): + cls._instance = obj = Basic.__new__(cls) + cls.__new__ = lambda cls: obj + cls.__getnewargs__ = lambda obj: () + cls.__getstate__ = lambda obj: None + S.register(cls) + + +# Delayed to avoid cyclic import +from .basic import Basic diff --git a/shared/package-files/d1/d13da4530fb2a70d9d66ee96508e6aa0de35f1c0e60a32e52b71b847cec9d292/blob b/shared/package-files/d1/d13da4530fb2a70d9d66ee96508e6aa0de35f1c0e60a32e52b71b847cec9d292/blob new file mode 100644 index 0000000000000000000000000000000000000000..d9919aa2e9c5be03078c45103f162936137fe571 --- /dev/null +++ b/shared/package-files/d1/d13da4530fb2a70d9d66ee96508e6aa0de35f1c0e60a32e52b71b847cec9d292/blob @@ -0,0 +1,250 @@ +import torch +from torch.fx import GraphModule +from torch.fx import Node + +from .pt2e.prepare import prepare +from .pt2e.qat_utils import ( + _fuse_conv_bn_qat, + _fold_conv_bn_qat, +) +from .pt2e.utils import ( + _get_node_name_to_scope, + _fuse_conv_bn_, + _disallow_eval_train, +) +from .pt2e.representation import reference_representation_rewrite +from .quantize_fx import _convert_to_reference_decomposed_fx +from torch.ao.quantization.quantizer import ( # noqa: F401 + Quantizer, + QuantizationSpecBase, + QuantizationSpec, + FixedQParamsQuantizationSpec, + SharedQuantizationSpec, + DerivedQuantizationSpec, + QuantizationAnnotation, +) +from torch.fx.passes.infra.pass_manager import PassManager +from torch.ao.quantization.pt2e.duplicate_dq_pass import DuplicateDQPass +from torch.ao.quantization.pt2e.port_metadata_pass import PortNodeMetaForQDQ +from torch._inductor.constant_folding import constant_fold + +__all__ = [ + "prepare_pt2e", + "prepare_qat_pt2e", + "convert_pt2e", +] + + +def prepare_pt2e( + model: GraphModule, + quantizer: Quantizer, +) -> GraphModule: + """Prepare a model for post training quantization + + Args: + * `model` (torch.fx.GraphModule): a model captured by `torch.export` API + in the short term we are using `torch._export.capture_pre_autograd_graph`, + in the long term we'll migrate to some `torch.export` API + * `quantizer`: A backend specific quantizer that conveys how user want the + model to be quantized. Tutorial for how to write a quantizer can be found here: + https://pytorch.org/tutorials/prototype/pt2e_quantizer.html + + Return: + A GraphModule with observer (based on quantizer annotation), ready for calibration + + Example:: + + import torch + from torch.ao.quantization.quantize_pt2e import prepare_pt2e + from torch._export import capture_pre_autograd_graph + from torch.ao.quantization.quantizer import ( + XNNPACKQuantizer, + get_symmetric_quantization_config, + ) + + class M(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(5, 10) + + def forward(self, x): + return self.linear(x) + + # initialize a floating point model + float_model = M().eval() + + # define calibration function + def calibrate(model, data_loader): + model.eval() + with torch.no_grad(): + for image, target in data_loader: + model(image) + + # Step 1. program capture + # NOTE: this API will be updated to torch.export API in the future, but the captured + # result shoud mostly stay the same + m = capture_pre_autograd_graph(m, *example_inputs) + # we get a model with aten ops + + # Step 2. quantization + # backend developer will write their own Quantizer and expose methods to allow + # users to express how they + # want the model to be quantized + quantizer = XNNPACKQuantizer().set_global(get_symmetric_quantization_config()) + m = prepare_pt2e(m, quantizer) + + # run calibration + # calibrate(m, sample_inference_data) + """ + torch._C._log_api_usage_once("quantization_api.quantize_pt2e.prepare_pt2e") + original_graph_meta = model.meta + node_name_to_scope = _get_node_name_to_scope(model) + # TODO: check qconfig_mapping to make sure conv and bn are both configured + # to be quantized before fusion + # TODO: (maybe) rewrite this with subgraph_rewriter + _fuse_conv_bn_(model) + quantizer.transform_for_annotation(model) + quantizer.annotate(model) + quantizer.validate(model) + model = prepare(model, node_name_to_scope, is_qat=False) + model.meta.update(original_graph_meta) + model = _disallow_eval_train(model) + return model + +def prepare_qat_pt2e( + model: GraphModule, + quantizer: Quantizer, +) -> GraphModule: + """Prepare a model for quantization aware training + + Args: + * `model` (torch.fx.GraphModule): see :func:`~torch.ao.quantization.quantize_pt2e.prepare_pt2e` + * `quantizer`: see :func:`~torch.ao.quantization.quantize_pt2e.prepare_pt2e` + + Return: + A GraphModule with fake quant modules (based on quantizer annotation), ready for + quantization aware training + + Example:: + import torch + from torch.ao.quantization.quantize_pt2e import prepare_qat_pt2e + from torch._export import capture_pre_autograd_graph + from torch.ao.quantization.quantizer import ( + XNNPACKQuantizer, + get_symmetric_quantization_config, + ) + + class M(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(5, 10) + + def forward(self, x): + return self.linear(x) + + # initialize a floating point model + float_model = M().eval() + + # define the training loop for quantization aware training + def train_loop(model, train_data): + model.train() + for image, target in data_loader: + ... + + # Step 1. program capture + # NOTE: this API will be updated to torch.export API in the future, but the captured + # result shoud mostly stay the same + m = capture_pre_autograd_graph(m, *example_inputs) + # we get a model with aten ops + + # Step 2. quantization + # backend developer will write their own Quantizer and expose methods to allow + # users to express how they + # want the model to be quantized + quantizer = XNNPACKQuantizer().set_global(get_symmetric_quantization_config()) + m = prepare_qat_pt2e(m, quantizer) + + # run quantization aware training + train_loop(prepared_model, train_loop) + + """ + torch._C._log_api_usage_once("quantization_api.quantize_pt2e.prepare_qat_pt2e") + original_graph_meta = model.meta + node_name_to_scope = _get_node_name_to_scope(model) + quantizer.transform_for_annotation(model) + quantizer.annotate(model) + quantizer.validate(model) + # Perform fusion after annotate to avoid quantizing ops in the new + # subgraph that don't need to be quantized + # TODO: only fuse if conv and bn are both configured to be quantized + _fuse_conv_bn_qat(model) + model = prepare(model, node_name_to_scope, is_qat=True) + model.meta.update(original_graph_meta) + model = _disallow_eval_train(model) + return model + +_QUANT_OPS = [ + torch.ops.quantized_decomposed.quantize_per_tensor.default, + torch.ops.quantized_decomposed.quantize_per_tensor.tensor, + torch.ops.quantized_decomposed.quantize_per_channel.default, +] +def _quant_node_constraint(n: Node) -> bool: + """If there is any pure ops between get_attr and quantize op they will be const propagated + e.g. get_attr(weight) -> transpose -> quantize -> dequantize* + (Note: dequantize op is not going to be constant propagated) + + This filter is added because we don't want to constant fold the things that are not + related to quantization + """ + return n.op == "call_function" and n.target in _QUANT_OPS + +def convert_pt2e( + model: GraphModule, + use_reference_representation: bool = False, + fold_quantize: bool = True, +) -> GraphModule: + """Convert a calibrated/trained model to a quantized model + + Args: + * `model` (torch.fx.GraphModule): calibrated/trained model + * `use_reference_representation` (bool): boolean flag to indicate whether to produce referece representation or not + * `fold_quantize` (bool): boolean flag for whether fold the quantize op or not + + Returns: + quantized model, either in q/dq representation or reference representation + + Example:: + + # prepared_model: the model produced by `prepare_pt2e`/`prepare_qat_pt2e` and calibration/training + # `convert_pt2e` produces a quantized model that represents quantized computation with + # quantize dequantize ops and fp32 ops by default. + # Please refer to + # https://pytorch.org/tutorials/prototype/pt2e_quant_ptq_static.html#convert-the-calibrated-model-to-a-quantized-model + # for detailed explanation of output quantized model + quantized_model = convert_pt2e(prepared_model) + + """ # flake8: noqa + torch._C._log_api_usage_once("quantization_api.quantize_pt2e.convert_pt2e") + if not isinstance(use_reference_representation, bool): + raise ValueError( + "Unexpected argument type for `use_reference_representation`, " + f"please make sure you intend to pass argument {use_reference_representation} to convert_pt2e") + original_graph_meta = model.meta + model = _convert_to_reference_decomposed_fx(model) + model = _fold_conv_bn_qat(model) + + pm = PassManager([DuplicateDQPass()]) + model = pm(model).graph_module + + pm = PassManager([PortNodeMetaForQDQ()]) + model = pm(model).graph_module + + if fold_quantize: + constant_fold(model, _quant_node_constraint) + + if use_reference_representation: + model = reference_representation_rewrite(model) + + model.meta.update(original_graph_meta) + model = _disallow_eval_train(model) + return model diff --git a/shared/package-files/d1/d13edbbfb3adb0315c81e9effc52e599d49aa0b6313a5fd622696997da7c56cc/blob b/shared/package-files/d1/d13edbbfb3adb0315c81e9effc52e599d49aa0b6313a5fd622696997da7c56cc/blob new file mode 100644 index 0000000000000000000000000000000000000000..0bcd01d3f1be2d6c955c5e296027437569ef7401 --- /dev/null +++ b/shared/package-files/d1/d13edbbfb3adb0315c81e9effc52e599d49aa0b6313a5fd622696997da7c56cc/blob @@ -0,0 +1,91 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::as_strided_scatter(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor +inline at::Tensor as_strided_scatter(const at::Tensor & self, const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset=c10::nullopt) { + return at::_ops::as_strided_scatter::call(self, src, c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), storage_offset.has_value() ? c10::make_optional(c10::SymInt(*storage_offset)) : c10::nullopt); +} +namespace symint { + template ::value>> + at::Tensor as_strided_scatter(const at::Tensor & self, const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset=c10::nullopt) { + return at::_ops::as_strided_scatter::call(self, src, c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), storage_offset.has_value() ? c10::make_optional(c10::SymInt(*storage_offset)) : c10::nullopt); + } +} + +// aten::as_strided_scatter(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor +inline at::Tensor as_strided_scatter_symint(const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset=c10::nullopt) { + return at::_ops::as_strided_scatter::call(self, src, size, stride, storage_offset); +} +namespace symint { + template ::value>> + at::Tensor as_strided_scatter(const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset=c10::nullopt) { + return at::_ops::as_strided_scatter::call(self, src, size, stride, storage_offset); + } +} + +// aten::as_strided_scatter.out(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & as_strided_scatter_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset=c10::nullopt) { + return at::_ops::as_strided_scatter_out::call(self, src, c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), storage_offset.has_value() ? c10::make_optional(c10::SymInt(*storage_offset)) : c10::nullopt, out); +} +namespace symint { + template ::value>> + at::Tensor & as_strided_scatter_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset=c10::nullopt) { + return at::_ops::as_strided_scatter_out::call(self, src, c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), storage_offset.has_value() ? c10::make_optional(c10::SymInt(*storage_offset)) : c10::nullopt, out); + } +} + +// aten::as_strided_scatter.out(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & as_strided_scatter_outf(const at::Tensor & self, const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset, at::Tensor & out) { + return at::_ops::as_strided_scatter_out::call(self, src, c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), storage_offset.has_value() ? c10::make_optional(c10::SymInt(*storage_offset)) : c10::nullopt, out); +} +namespace symint { + template ::value>> + at::Tensor & as_strided_scatter_outf(const at::Tensor & self, const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset, at::Tensor & out) { + return at::_ops::as_strided_scatter_out::call(self, src, c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), storage_offset.has_value() ? c10::make_optional(c10::SymInt(*storage_offset)) : c10::nullopt, out); + } +} + +// aten::as_strided_scatter.out(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & as_strided_scatter_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset=c10::nullopt) { + return at::_ops::as_strided_scatter_out::call(self, src, size, stride, storage_offset, out); +} +namespace symint { + template ::value>> + at::Tensor & as_strided_scatter_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset=c10::nullopt) { + return at::_ops::as_strided_scatter_out::call(self, src, size, stride, storage_offset, out); + } +} + +// aten::as_strided_scatter.out(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & as_strided_scatter_symint_outf(const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset, at::Tensor & out) { + return at::_ops::as_strided_scatter_out::call(self, src, size, stride, storage_offset, out); +} +namespace symint { + template ::value>> + at::Tensor & as_strided_scatter_outf(const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset, at::Tensor & out) { + return at::_ops::as_strided_scatter_out::call(self, src, size, stride, storage_offset, out); + } +} + +} diff --git a/shared/package-files/d1/d13f49c7092a5e91accc67dcaecb71272459ced57d551b05a957068437049a13/blob b/shared/package-files/d1/d13f49c7092a5e91accc67dcaecb71272459ced57d551b05a957068437049a13/blob new file mode 100644 index 0000000000000000000000000000000000000000..30088c78d4c3a7ab33b8e00a6e526777bae8d1b6 --- /dev/null +++ b/shared/package-files/d1/d13f49c7092a5e91accc67dcaecb71272459ced57d551b05a957068437049a13/blob @@ -0,0 +1,72 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/util/span.h" +#include "arrow/util/visibility.h" + +namespace arrow::util { +/** + * A secure string that ensures the wrapped string is cleared from memory on + * deconstruction. This class can only be created from std::string that are securely + * erased after creation. + * + * Note: This class does not provide a constructor / assignment operator that copies a + * std::string because that would allow code to create a SecureString while accidentally + * not noticing the need to securely erasing the argument after invoking the constructor / + * calling the assignment operator. + */ +class ARROW_EXPORT SecureString { + public: + SecureString() = default; + SecureString(SecureString&&) noexcept; + SecureString(const SecureString&) = default; + explicit SecureString(std::string&&) noexcept; + explicit SecureString(size_t, char) noexcept; + + SecureString& operator=(SecureString&&) noexcept; + SecureString& operator=(const SecureString&); + SecureString& operator=(std::string&&) noexcept; + + bool operator==(const SecureString&) const; + bool operator!=(const SecureString&) const; + + ~SecureString() { Dispose(); } + + [[nodiscard]] bool empty() const; + [[nodiscard]] std::size_t size() const; + [[nodiscard]] std::size_t length() const; + [[nodiscard]] std::size_t capacity() const; + + [[nodiscard]] span as_span(); + [[nodiscard]] span as_span() const; + [[nodiscard]] std::string_view as_view() const; + + void Dispose(); + + static void SecureClear(std::string*); + static void SecureClear(uint8_t* data, size_t size); + + private: + std::string secret_; +}; + +} // namespace arrow::util diff --git a/shared/package-files/d1/d142631e75bfb34a0aa462cc782a34f69e2448e464706638ef25a42ba230f317/blob b/shared/package-files/d1/d142631e75bfb34a0aa462cc782a34f69e2448e464706638ef25a42ba230f317/blob new file mode 100644 index 0000000000000000000000000000000000000000..ffe9017975bf17504da6d31752715af279511c87 Binary files /dev/null and b/shared/package-files/d1/d142631e75bfb34a0aa462cc782a34f69e2448e464706638ef25a42ba230f317/blob differ diff --git a/shared/package-files/d1/d143659ddde1ce57f6734122c0b24586d4f256ecb2932c02d13aa206ba4d9501/blob b/shared/package-files/d1/d143659ddde1ce57f6734122c0b24586d4f256ecb2932c02d13aa206ba4d9501/blob new file mode 100644 index 0000000000000000000000000000000000000000..8b6fec71924d1ad1a084174fd8d60834b52edd9d Binary files /dev/null and b/shared/package-files/d1/d143659ddde1ce57f6734122c0b24586d4f256ecb2932c02d13aa206ba4d9501/blob differ diff --git a/shared/package-files/d1/d146208ff5159c304faa373716ee1096567fca252e416929c84c25fb34dd096f/blob b/shared/package-files/d1/d146208ff5159c304faa373716ee1096567fca252e416929c84c25fb34dd096f/blob new file mode 100644 index 0000000000000000000000000000000000000000..fa571489bd7f3e752872eee4c7832704dfece39f --- /dev/null +++ b/shared/package-files/d1/d146208ff5159c304faa373716ee1096567fca252e416929c84c25fb34dd096f/blob @@ -0,0 +1,6443 @@ +import builtins +import collections +import inspect +import itertools +import math +import operator +import warnings + +from collections.abc import Iterable +from enum import Enum +from functools import partial, reduce, singledispatch, wraps +from typing import Any, Callable, Dict, List, Optional, overload, Sequence, Tuple, Union + +import torch + +import torch._prims as prims +import torch._prims_common as utils +from torch import sym_float, sym_int +from torch._prims_common import ( + DeviceLikeType, + Dim, + DimsSequenceType, + DimsType, + dtype_to_type, + ELEMENTWISE_TYPE_PROMOTION_KIND, + FloatLike, + FloatWithoutSymFloat, + IntLike, + is_weakly_lesser_type, + Number, + NumberType, + RealNumberType, + REDUCTION_OUTPUT_TYPE_KIND, + ShapeType, + StrideType, + TensorLike, + TensorLikeType, + TensorOrNumberLikeType, + TensorSequenceType, +) +from torch._prims_common.wrappers import ( + _maybe_convert_to_dtype, + _maybe_resize_out, + _safe_copy_out, + elementwise_type_promotion_wrapper, + elementwise_unary_scalar_wrapper, + out_wrapper, +) + +# Experimental module containing prototype Python references for existing +# PyTorch operations. + +__all__ = [ + # + # Elementwise Unary References + # + "abs", + "acos", + "acosh", + "asinh", + "asin", + "atan", + "atanh", + "bitwise_not", + # "cbrt", # No corresponding torch operation + "ceil", + "conj_physical", + "cos", + "cosh", + "count_nonzero", + "deg2rad", + "digamma", + "erf", + "erfinv", + "erfc", + "exp", + "expm1", + "exponential", + "exp2", + "fill", + "fill_", + "floor", + "frac", + "geometric", + "index_add", + "index_copy", + "index_copy_", + "index_select", + "index_fill", + "index_fill_", + "isfinite", + "isinf", + "isposinf", + "isneginf", + "isnan", + "isreal", + "i0", + "lerp", + "lgamma", + "log", + "log1p", + "log2", + "log10", + "log_normal", + "log_softmax", + "mvlgamma", + "norm", + "normal", + "nan_to_num", + "neg", + "positive", + "rad2deg", + "reciprocal", + "round", # TODO: model kwargs + "sigmoid", + "sgn", + "sign", + "signbit", + "sin", + "sinc", + "sinh", + "softmax", + "sqrt", + "square", + "tan", + "tanh", + "trace", + "trunc", + # + # Elementwise Binary References + # + "add", + "atan2", + "bitwise_and", + "bitwise_left_shift", + "bitwise_or", + "bitwise_right_shift", + "bitwise_xor", + "clamp_min", + "clamp_max", + "copysign", + "div", + "eq", + "float_power", + "floor_divide", + "fmax", + "fmin", + "fmod", + "gcd", + "ge", + "gt", + "heaviside", + "hypot", + "igamma", + "igammac", + "imag", + "isclose", + "lcm", + # 'ldexp', + "le", + "logaddexp", + "logaddexp2", + "logical_and", + "logical_not", + "logical_or", + "logical_xor", + "logsumexp", + "lt", + # 'max', # implement with reductions + "maximum", + # 'min', # implement with reductions + "minimum", + "mul", + "ne", + "nextafter", + # 'polar', # abs, cos, sin + "pow", + "real", + "rpow", + "remainder", + "rsub", + "rtruediv", + "rfloordiv", + "sub", + "true_divide", + "trunc_divide", + "xlogy", + # + # Elementwise Ternary References + # + "addcdiv", + "addcmul", + "clamp", + # + # Conditional references + # + "masked_fill", + "masked_fill_", + "where", + # + # Data conversion and movement references + # + "clone", + "copy_to", # TODO: add OpInfo (or implement .to) + "item", + "to", + # + # Reduction ops + # + "all", + "amax", + "amin", + "any", + "cumsum", + "cumprod", + "mean", + "dot", + "vdot", + "std", + "std_mean", + "sum", + "sum_to_size", + "prod", + "var", + "var_mean", + # + # Linear algebra ops + # + "addr", + # + # View & Shape Ops + # + "alias", + "atleast_1d", + "atleast_2d", + "atleast_3d", + "as_strided", + "as_strided_scatter", + "block_diag", + "broadcast_shapes", + "broadcast_tensors", + "broadcast_to", + "cat", + "chunk", + "column_stack", + "conj", + "constant_pad_nd", + "contiguous", + "diag_embed", + "diag", + "diagonal", + "diagonal_copy", + "diagonal_scatter", + "dsplit", + "dstack", + "expand", + "expand_as", + "flatten", + "flip", + "fliplr", + "flipud", + "hsplit", + "hstack", + "meshgrid", + "movedim", + "narrow", + "narrow_copy", + "native_group_norm", + "native_layer_norm", + "permute", + "ravel", + "repeat", + "reshape", + "reshape_as", + "roll", + "rot90", + "rsqrt", + "stack", + "swap_axes", # alias for transpose + "squeeze", + "t", + "T", + "take_along_dim", + "tensor_split", + "transpose", + "unfold", + "unfold_copy", + "unsqueeze", + "view", + "view_as", + "vsplit", + "vstack", + "view_as_complex", + "unflatten", + "unbind", + "triu", + "tril", + "triu_indices", + "tril_indices", + # + # Tensor Creation + # + "arange", + "cauchy", + "empty", + "empty_like", + "empty_permuted", + "empty_strided", + "eye", + "full", + "full_like", + "linspace", + "logspace", + "new_empty", + "new_empty_strided", + "new_full", + "new_ones", + "new_zeros", + "ones", + "ones_like", + "randn", + "scalar_tensor", + "zero", + "zeros", + "zeros_like", + # + # Test-related functions + # + "allclose", + "equal", + # + # Statistical operations + # + "bucketize", + # + # Misc + # + "is_complex", + "renorm", + "stft", + "istft", +] + +Tensor = torch.Tensor +DispatchKey = torch._C.DispatchKey # type: ignore[attr-defined] +aten = torch._ops.ops.aten + +# Note that the docstrings for the public methods from this file are in +# torch/_torch_docs.py + + +def is_noncontiguous_supported(device): + if device is not None and device.type == "hpu": + return False + return True + + +def handle_noncontiguous_outputs(input_tlist, output): + device = None + from torch._subclasses.fake_tensor import FakeTensor + + for t in input_tlist: + if isinstance(t, FakeTensor): + device = t.fake_device + break + + if not is_noncontiguous_supported(device): + output = output.contiguous() + + return output + + +def _broadcast_shapes(*_shapes): + from torch.fx.experimental.symbolic_shapes import guard_size_oblivious + + shapes = tuple( + (x,) if isinstance(x, IntLike) else x + for x in filter(lambda x: x is not None, _shapes) + ) + + # Short-circuits on no input + if len(shapes) == 0: + return None + + # Type checking + # TODO: make common validations available as utils + for shape in shapes: + assert isinstance(shape, Sequence) + + # Computes common shape + common_shape = [ + 1, + ] * reduce(max, (len(shape) for shape in shapes)) + for arg_idx, shape in enumerate(shapes): + for idx in range(-1, -1 - len(shape), -1): + if guard_size_oblivious(common_shape[idx] == 1): + if shape[idx] < 0: + raise ValueError( + "Attempting to broadcast a dimension with negative length!" + ) + common_shape[idx] = shape[idx] + elif guard_size_oblivious(shape[idx] != 1): + if common_shape[idx] != shape[idx]: + raise RuntimeError( + f"Attempting to broadcast a dimension of length {shape[idx]} at {idx}! " + f"Mismatching argument at index {arg_idx} had {shape}; but expected shape " + f"should be broadcastable to {common_shape}" + ) + + return common_shape + + +def _maybe_broadcast(*args, preserve_cpu_scalar_tensors=True): + # Computes common shape + common_shape = _broadcast_shapes( + *(t.shape if isinstance(t, TensorLike) else None for t in args) + ) + + def __maybe_broadcast(x, shape): + if x is None: + return None + elif isinstance(x, Number): + return x + elif isinstance(x, TensorLike): + if preserve_cpu_scalar_tensors and utils.is_cpu_scalar_tensor(x): + return x + + if not utils.same_shape(x.shape, common_shape): + return x.expand(common_shape) + + return x + else: + raise RuntimeError( + "Unexpected type when broadcasting: " + str(type(x)) + "!" + ) + + return tuple(__maybe_broadcast(x, common_shape) for x in args) + + +# Utilities should come BEFORE this import +from torch._decomp import register_decomposition + +# +# Elementwise unary references +# + +infer_aten_op = object() + + +# TODO: add type promotion support +def _make_elementwise_unary_reference( + type_promotion_kind, + *, + aten_op=infer_aten_op, + extra_meta=None, +) -> Callable: + def inner(prim: Callable): + nonlocal aten_op + + @wraps(prim) + @out_wrapper() + @elementwise_unary_scalar_wrapper + @elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=type_promotion_kind, + ) + def _ref(a: TensorLikeType) -> TensorLikeType: + if extra_meta is not None: + extra_meta(a) + + output = prim(a) + return handle_noncontiguous_outputs([a], output) + + if aten_op is infer_aten_op: + aten_op = utils.get_aten_op(prim, prim.__name__) + if aten_op is not None: + register_decomposition(aten_op)(_ref) + + return _ref + + return inner + + +def _make_alias(fn, name): + """ + This function defines an alias of another function and sets its __name__ argument. + It also sets its __module__ argument to the module of the caller. + Note that when naïvely doing `alias = fn`, we have that `alias.__name__ == "fn"`, and + `alias.__module__ == fn.__module__`. + """ + + def _fn(*args, **kwargs): + return fn(*args, **kwargs) + + _fn.__name__ = name + _fn.__module__ = inspect.currentframe().f_back.f_globals["__name__"] # type: ignore[union-attr] + return _fn + + +def _make_inplace(fn): + """ + Given a function with out variant (i.e. using `out_wrapper()), it returns its in-place variant + See https://github.com/pytorch/pytorch/wiki/Developer-FAQ#how-do-in-place-operations-work-in-pytorch + """ + + # nb. We use the name of the first argument used in the unary references + @wraps(fn) + def _fn(a, *args, **kwargs): + return fn(a, *args, out=a, **kwargs) + + inplace_name = f"{fn.__name__}_" + _fn.__name__ = inplace_name + _fn = register_decomposition(getattr(aten, inplace_name))(_fn) + + # We access the __all__ attribute of the module where fn is defined + # There may be a cleaner way of doing this... + from inspect import getmodule + + _all = getmodule(fn).__all__ # type: ignore[union-attr] + if inplace_name not in _all: + _all.append(inplace_name) + return _fn + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT) +def abs(a): + return prims.abs(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def acos(a): + return prims.acos(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def acosh(a): + return prims.acosh(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def asin(a): + return prims.asin(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def asinh(a): + return prims.asinh(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def atan(a): + return prims.atan(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def atanh(a): + return prims.atanh(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT) +def bitwise_not(a): + return prims.bitwise_not(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT) +def ceil(a): + return prims.ceil(a) + + +@register_decomposition(aten.is_complex) +def is_complex(input: TensorLikeType): + return utils.is_complex_dtype(input.dtype) + + +@register_decomposition(aten.conj_physical) +@out_wrapper() +def conj_physical(input: TensorLikeType): + if not utils.is_complex_dtype(input.dtype): + return input + return prims.conj_physical(input) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def cos(a): + return prims.cos(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def cosh(a): + return prims.cosh(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def digamma(a): + return prims.digamma(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def erf(a): + return prims.erf(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def erfinv(a): + return prims.erf_inv(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def erfc(a): + return prims.erfc(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def exp(a): + return prims.exp(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def expm1(a): + return prims.expm1(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def exp2(a): + return prims.exp2(a) + + +# Fill has its own implementation because it has a value parameter +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a,"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH, +) +def fill(a: TensorLikeType, value: NumberType) -> TensorLikeType: + assert isinstance(a, TensorLike) + assert isinstance(value, Number) + + python_type = utils.dtype_to_type(a.dtype) + if not utils.is_weakly_lesser_type(type(value), python_type): + msg = f"value argument of type {type(value)} cannot be safely cast to type {python_type}!" + raise ValueError(msg) + + return prims.fill(a, value) + + +def fill_(a: TensorLikeType, value: NumberType) -> TensorLikeType: + r = prims.fill(a, value) + prims.copy_to(a, r) + return a + + +@register_decomposition(aten.zero) +@out_wrapper() +def zero(input: TensorLikeType) -> TensorLikeType: + return torch.zeros_like(input) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT) +def floor(a): + return prims.floor(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT) +def frac(x: TensorLikeType) -> TensorLikeType: + trunc_x = torch.mul(torch.floor(torch.abs(x)), torch.sign(x)) + return torch.sub(x, trunc_x) + + +# imag does not use _make_elementwise_unary_reference because it does not support out +def imag(a: TensorLikeType) -> TensorLikeType: + assert isinstance(a, TensorLike) + torch._check( + utils.is_complex_dtype(a.dtype), lambda: "imag only supports complex tensors." + ) + return prims.imag(a) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + aten_op=None, # CompositeImplicitAutograd +) +def isfinite(a: TensorLikeType) -> TensorLikeType: + if utils.is_float_dtype(a.dtype) or utils.is_complex_dtype(a.dtype): + return prims.isfinite(a) + + return ones_like(a, dtype=torch.bool) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL) +def isinf(a: TensorLikeType) -> TensorLikeType: + if utils.is_complex_dtype(a.dtype): + return torch.logical_or(isinf(torch.real(a)), isinf(torch.imag(a))) + if utils.is_float_dtype(a.dtype): + return torch.abs(a) == float("inf") + return torch.zeros_like(a, dtype=torch.bool) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL) +def isposinf(a: TensorLikeType) -> TensorLikeType: + torch._check( + not utils.is_complex_dtype(a.dtype), + lambda: f"Complex dtype is not supported for isposinf, got dtype {a.dtype}", + ) + if utils.is_float_dtype(a.dtype): + return a == float("inf") + return torch.zeros_like(a, dtype=torch.bool) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL) +def isneginf(a: TensorLikeType) -> TensorLikeType: + torch._check( + not utils.is_complex_dtype(a.dtype), + lambda: f"Complex dtype is not supported for isneginf, got dtype {a.dtype}", + ) + if utils.is_float_dtype(a.dtype): + return a == float("-inf") + return torch.zeros_like(a, dtype=torch.bool) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL) +def isnan(a: TensorLikeType) -> TensorLikeType: + return prims.ne(a, a) + + +# alias +mvlgamma = _make_alias(torch.special.multigammaln, "mvlgamma") # type: ignore[has-type] + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + aten_op=None, # CompositeImplicitAutograd +) +def isreal(a: TensorLikeType) -> TensorLikeType: + if utils.is_complex_dtype(a.dtype): + return torch.imag(a) == 0 + return torch.ones_like(a, dtype=torch.bool) + + +# TODO: if this is special maybe it should be defined there and imported here? +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, aten_op=aten.i0 +) +def i0(a): + return prims.bessel_i0(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def lgamma(a): + return prims.lgamma(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def log(a): + return prims.log(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def log1p(a): + return prims.log1p(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def log2(a): + return prims.log2(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def log10(a): + return prims.log10(a) + + +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +def log_softmax( + a: TensorLikeType, + dim: int, + dtype: Optional[torch.dtype] = None, +) -> TensorLikeType: + result_dtype = dtype or a.dtype + computation_dtype = utils.get_computation_dtype(result_dtype) + a_ = _maybe_convert_to_dtype(a, computation_dtype) + return _maybe_convert_to_dtype(a_ - logsumexp(a_, dim, keepdim=True), result_dtype) # type: ignore[return-value] + + +@register_decomposition(aten.logsumexp) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def logsumexp( + self: TensorLikeType, dim: DimsType, keepdim: bool = False +) -> TensorLikeType: + if not isinstance(dim, Iterable): + dim = (dim,) + if self.numel() == 0: + return torch.sum(torch.exp(self), dim, keepdim).log() + maxes = torch.amax(self, dim, keepdim=True) + maxes = torch.masked_fill(maxes, maxes.abs() == float("inf"), 0) + maxes_squeezed = maxes if keepdim else torch.squeeze(maxes, dim) + result = torch.sum(torch.exp(self - maxes), dim, keepdim) + return result.log().add(maxes_squeezed) + + +@register_decomposition(aten.nan_to_num) +@out_wrapper() +def nan_to_num( + a: TensorLikeType, + nan: Optional[NumberType] = 0.0, + posinf: Optional[NumberType] = None, + neginf: Optional[NumberType] = None, +) -> TensorLikeType: + assert isinstance(a, TensorLike) + + if utils.is_boolean_dtype(a.dtype) or utils.is_integer_dtype(a.dtype): + return a.clone() + + if nan is None: + nan = 0.0 + + if posinf is None: + posinf = torch.finfo(a.dtype).max + + if neginf is None: + neginf = torch.finfo(a.dtype).min + + result = torch.where(torch.isnan(a), nan, a) # type: ignore[call-overload] + result = torch.where(torch.isneginf(a), neginf, result) # type: ignore[call-overload] + result = torch.where(torch.isposinf(a), posinf, result) # type: ignore[call-overload] + return result + + +def _neg_meta(a: TensorLikeType): + torch._check( + a.dtype is not torch.bool, + lambda: ( + "Negation, the `-` operator, on a bool tensor is not supported. " + "If you are trying to invert a mask, use the `~` or `logical_not()` " + "operator instead." + ), + ) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, extra_meta=_neg_meta +) +def neg(a): + return prims.neg(a) + + +# positive does not use _make_elementwise_unary_reference because it does not support out +# CompositeImplicitAutograd - don't register decomp +def positive(a: TensorLikeType) -> TensorLikeType: + assert isinstance(a, TensorLike) + if a.dtype is torch.bool: + msg = "positive does not support bool tensors." + raise RuntimeError(msg) + return a + + +# real does not use _make_elementwise_unary_reference because it does not support out +def real(a: TensorLikeType) -> TensorLikeType: + assert isinstance(a, TensorLike) + if utils.is_complex_dtype(a.dtype): + return prims.real(a) + return a + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def reciprocal(a): + return prims.reciprocal(a) + + +@register_decomposition(aten.round) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def round(a: TensorLikeType, *, decimals: int = 0) -> TensorLikeType: + if decimals == 0: + return prims.round(a) + else: + ten_pow = 10**decimals + ten_neg_pow = 10 ** (-decimals) + return prims.mul(prims.round(prims.mul(a, ten_pow)), ten_neg_pow) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def rsqrt(a): + return prims.rsqrt(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def sigmoid(a: TensorLikeType) -> TensorLikeType: + return true_divide(1, add(1, exp(neg(a)))) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT) +def sgn(a): + if utils.is_complex_dtype(a.dtype): + a_abs = a.abs() + return torch.where(a_abs == 0, 0, a / a_abs) + else: + return a.sign() + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT) +def sign(a): + return prims.sign(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL) +def signbit(a): + return prims.signbit(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def sin(a): + return prims.sin(a) + + +# Autograd note: This will give the right first derivative at zero (by chance), +# but not the right second derivative +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def sinc(a): + a = math.pi * a + return torch.where(a == 0, 1, torch.sin(a) / a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def sinh(a): + return prims.sinh(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def sqrt(a): + return prims.sqrt(a) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.BOOL_TO_LONG, + aten_op=None, # CompositeImplicitAutograd, +) +def square(a: TensorLikeType) -> TensorLikeType: + return mul(a, a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def tan(a): + return prims.tan(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def tanh(a): + return prims.tanh(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT) +def trunc(a): + return prims.trunc(a) + + +# TODO: register this as a real ref/decomposition once TorchInductor supports complex! +def view_as_complex(self: TensorLikeType) -> TensorLikeType: + input_dtype = self.dtype + torch._check( + utils.is_float_dtype(input_dtype), + lambda: f"view_as_complex is only supported for floating point" + f"tensors, but got a tensor of scalar type: {input_dtype}", + ) + sizes = self.size() + torch._check( + len(sizes) != 0, + lambda: "Input tensor must have one or more dimensions", + ) + torch._check( + sizes[-1] == 2, + lambda: "Tensor must have a last dimension of size 2", + ) + + old_strides = self.stride() + torch._check( + old_strides[-1] == 1, + lambda: "Tensor must have a last dimension with stride 1", + ) + dims = old_strides[:-1] + torch._check( + py_all(stride % 2 == 0 for stride in dims), + lambda: "Tensor must have a stride divisible by 2 for all but last dimension", + ) + torch._check( + self.storage_offset() % 2 == 0, + lambda: "Tensor must have a storage_offset divisible by 2", + ) + return prims.view_element_type( + self, utils.corresponding_complex_dtype(input_dtype) + ).squeeze(-1) + + +def _make_elementwise_binary_reference( + type_promotion_kind, + aten_op=infer_aten_op, + name=None, + has_out=True, + supports_lhs_python_scalar=True, + supports_rhs_python_scalar=True, + supports_two_python_scalars=False, + should_register_decomposition=True, +) -> Callable: + def inner(prim: Callable): + nonlocal aten_op, name + if name is None: + name = prim.__name__ + + @wraps(prim) + @elementwise_type_promotion_wrapper( + type_promoting_args=("a", "b"), + type_promotion_kind=type_promotion_kind, + ) + def _ref( + a: Union[Tensor, NumberType], + b: Union[Tensor, NumberType], + ) -> Tensor: + torch._check_value( + supports_lhs_python_scalar or not isinstance(a, Number), + lambda: f"{name}: Received a lhs Python scalar to an elementwise binary " + "operation that does not accept lhs scalars!", + ) + torch._check_value( + supports_rhs_python_scalar or not isinstance(b, Number), + lambda: f"{name}: Received a rhs Python scalar to an elementwise binary " + "operation that does not accept rhs scalars!", + ) + torch._check_value( + supports_two_python_scalars + or not (isinstance(a, Number) and isinstance(b, Number)), + lambda: f"{name}: Receive two Number inputs to an elementwise binary operation!", + ) + a, b = _maybe_broadcast(a, b) + output = prim(a, b) + return handle_noncontiguous_outputs([a, b], output) + + if has_out: + _ref = out_wrapper()(_ref) + + _ref.__name__ = name + if aten_op is infer_aten_op: + aten_op = utils.get_aten_op(prim, name) + if aten_op is not None and should_register_decomposition: + register_decomposition(aten_op)(_ref) + + return _ref + + return inner + + +# Add has its own implementation because it has an alpha argument +@register_decomposition(aten.add) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a", "b"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def add( + a: Union[TensorLikeType, NumberType], + b: Union[TensorLikeType, NumberType], + *, + alpha: Optional[NumberType] = None, +): + """ + Reference implementation of torch.add + """ + + a, b = _maybe_broadcast(a, b) + + if alpha is not None: + dtype = a.dtype if isinstance(a, TensorLike) else b.dtype # type: ignore[union-attr] + python_type = utils.dtype_to_type(dtype) + if python_type != bool and not utils.is_weakly_lesser_type( + type(alpha), python_type + ): + msg = f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!" + raise ValueError(msg) + if isinstance(b, TensorLike): + b = prims.mul(b, alpha) + else: + b = b * alpha + + output = prims.add(a, b) + return handle_noncontiguous_outputs([a, b], output) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def atan2(a, b): + return prims.atan2(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def bitwise_and(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.bitwise_and(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def bitwise_left_shift(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.shift_left(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def bitwise_or(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.bitwise_or(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def bitwise_right_shift(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.shift_right_arithmetic(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def bitwise_xor(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.bitwise_xor(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + supports_lhs_python_scalar=False, +) +def copysign( + a: Union[TensorLikeType, NumberType], b: Union[TensorLikeType, NumberType] +): + if isinstance(b, Number) and isinstance(a, Tensor): + b = scalar_tensor(b, dtype=a.dtype, device=a.device) + elif isinstance(a, Tensor) and isinstance(b, Tensor) and a.device != b.device: + msg = "Expected divisor (b) to be on the same device ({}) as dividend (a), but it is found on {}!".format( + a.device, b.device + ) + raise RuntimeError(msg) + return where(signbit(b), neg(abs(a)), abs(a)) + + +# complex = _make_elementwise_binary_reference(prims.complex, type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT) + + +@register_decomposition(aten.div) +@out_wrapper() +def div( + a: Union[TensorLikeType, NumberType], + b: Union[TensorLikeType, NumberType], + *, + rounding_mode: Optional[str] = None, +): + """ + Reference implementation of torch.div + """ + if rounding_mode is None: + return true_divide(a, b) + elif rounding_mode == "trunc": + return trunc_divide(a, b) + elif rounding_mode == "floor": + return floor_divide(a, b) + else: + msg = f"div expected rounding_mode to be one of None, 'trunc', or 'floor' but found {rounding_mode}." + raise ValueError(msg) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + supports_lhs_python_scalar=False, +) +def eq(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.eq(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.BOOL_TO_LONG, +) +def pow( + a: Union[TensorLikeType, NumberType], + b: Union[TensorLikeType, NumberType], +) -> TensorLikeType: + assert isinstance(a, TensorLikeType) or isinstance(b, TensorLikeType) + + if isinstance(b, Number): + if b == 1.0: + return a.clone() # type: ignore[return-value,union-attr] + elif b == 2.0: + return a * a # type: ignore[return-value] + elif b == 0.5: + return torch.sqrt(a) # type: ignore[arg-type] + elif isinstance(a, Number): + if a == 1.0: + return torch.fill(b, True) + if a == 2.0 and ( + utils.is_float_dtype(b.dtype) or utils.is_complex_dtype(b.dtype) + ): + return torch.exp2(b) + + return prims.pow(a, b) + + +# Float power has its own implementation because it has unique type promotion. +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +def float_power( + a: Union[TensorLikeType, NumberType], + b: Union[TensorLikeType, NumberType], +) -> Tensor: + if isinstance(a, Number) and isinstance(b, Number): + raise ValueError( + "Receive two Number inputs to an elementwise binary operation!" + ) + + # Handles type promotion + dtype = utils.get_higher_dtype(a, b) + assert dtype is not None + if utils.is_complex_dtype(dtype): + dtype = torch.complex128 + else: + dtype = torch.float64 + + # Float power has the following contiguous cast behavior to be + # consistent with its C++ impl + a = _maybe_convert_to_dtype(a, dtype) + b = _maybe_convert_to_dtype(b, dtype) + + a, b = _maybe_broadcast(a, b) + return pow(a, b) + + +# >>> a = torch.tensor(-0.2500, dtype=torch.float64) +# tensor(-0.250000000000000, dtype=torch.float64) +# +# >>> b = torch.tensor(-0.0010, dtype=torch.float64) +# tensor(-0.001000000000000, dtype=torch.float64) +# +# Note: In this case, casting float to double will expand the float mantissa with zeros, +# while creating a double generates a distinct mantissa. +# >>> torch.tensor(-0.001).to(dtype=torch.float64) +# tensor(-0.001000000047497, dtype=torch.float64) +# +# Floor Division +# The difference is caused because torch.remainder(a, b) = -0.001. +# +# >>> torch.floor(torch.true_divide(a, b)) +# tensor(250., dtype=torch.float64) +# +# >>> torch.div(a, b, rounding_mode='floor') +# tensor(249., dtype=torch.float64) +# +# Definition: a // b = (a - remainder(a, b)) / b +# >>> torch.true_divide(torch.sub(a, torch.remainder(a, b)), b) +# tensor(249., dtype=torch.float64) +# +# For reference, see CPython's implementation: +# https://github.com/python/cpython/blob/ace008c531dd685a30c1dd68f9b5ba35f20171cf/Objects/floatobject.c#L636 + + +@_make_elementwise_binary_reference( + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_two_python_scalars=True, + should_register_decomposition=False, +) +def floor_divide( + a: Union[TensorLikeType, NumberType], b: Union[TensorLikeType, NumberType] +): + # Wrap scalars because some references only accept tensor arguments. + if isinstance(a, Number) and isinstance(b, Number): + a = scalar_tensor(a) + b = scalar_tensor(b) + elif isinstance(b, Number) and isinstance(a, Tensor): + b = scalar_tensor(b, dtype=a.dtype, device=a.device) + elif isinstance(a, Number) and isinstance(b, Tensor): + a = scalar_tensor(a, dtype=b.dtype, device=b.device) + elif isinstance(a, Tensor) and isinstance(b, Tensor) and a.device != b.device: + if a.device == torch.device("cpu"): + msg = "Expected divisor (b) to be on the same device ({}) as dividend (a), but it is found on {}!".format( + a.device, b.device + ) + raise RuntimeError(msg) + else: + b = prims.device_put(b, device=a.device) + + assert isinstance(a, Tensor) and isinstance(b, Tensor) + dtype = a.dtype + if utils.is_float_dtype(dtype): + return _floor_divide_float(a, b) + elif utils.is_integer_dtype(dtype): + return _floor_divide_integer(a, b) + else: + torch._check(False, lambda: f"{dtype} not supported for floor_divide") + + +def _floor_divide_integer(a: Tensor, b: Tensor) -> Tensor: + a, b = _maybe_broadcast(a, b) + + if not a.dtype.is_signed: + return prims.div(a, b) + + # Convert truncation to flooring: + offset = (torch.signbit(a) != torch.signbit(b)).logical_and(torch.fmod(a, b) != 0) + return prims.div(a, b) - _maybe_convert_to_dtype(offset, a.dtype) + + +def _floor_divide_float(a: Tensor, b: Tensor) -> Tensor: + mod = fmod(a, b) + div = true_divide(sub(a, mod), b) + + # Ensure that the remainder has the same sign as denominator + different_signed_inputs = bitwise_xor(lt(a, 0), lt(b, 0)) + non_zero_remainder = ne(mod, 0) + mask = bitwise_and(non_zero_remainder, different_signed_inputs) + div = where(mask, sub(div, 1), div) + + # Map quotient to nearest integer value + floor_div = floor(div) + mask = gt(sub(div, floor_div), 0.5) + floor_div = where(mask, add(floor_div, 1), floor_div) + + basic_div = true_divide(a, b) + zero_tensor = scalar_tensor(0, dtype=basic_div.dtype, device=basic_div.device) + + # If quotient is zero, copy signbit from true_divide quotient + floor_div = where(ne(div, 0), floor_div, copysign(zero_tensor, basic_div)) + + # If denominator is zero, then follow true_divide behavior + return where(ne(b, 0), floor_div, basic_div) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def fmax(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.fmax(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def fmin(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.fmin(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=True, +) +def fmod(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.fmod(a, b) + + +@register_decomposition(aten.frexp) +@out_wrapper("mantissa", "exponent") +def frexp(self: TensorLikeType) -> Tuple[TensorLikeType, TensorLikeType]: + return torch.return_types.frexp(prims.frexp(self)) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def gcd(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.gcd(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + supports_lhs_python_scalar=False, +) +def ge(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.ge(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + supports_lhs_python_scalar=False, +) +def gt(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.gt(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def heaviside(input: TensorLikeType, values: TensorLikeType) -> TensorLikeType: + input_eq_zero = torch.eq(input, 0) + input_lt_zero = torch.logical_or(torch.lt(input, 0), torch.isnan(input)) + zeros_and_ones = torch.where(input_lt_zero, 0, 1) + output = torch.where(input_eq_zero, values, zeros_and_ones) + return output + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def hypot(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.hypot(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def igamma(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.igamma(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def igammac(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.igammac(a, b) + + +def _check_close_args( + name: str, + a: TensorLikeType, + b: TensorLikeType, + rtol: float, + atol: float, +) -> None: + torch._check_value( + a.dtype == b.dtype, + lambda: f"{name}: Attempting to compare tensors of different dtypes {a.dtype} and {b.dtype}!", + ) + torch._check( + rtol >= 0, + lambda: f"{name}: rtol must be greater than or equal to zero, but got {rtol}!", + ) + torch._check( + atol >= 0, + lambda: f"{name}: atol must be greater than or equal to zero, but got {atol}!", + ) + + +# CompositeImplicitAutograd - don't register decomp +def isclose( + a: TensorLikeType, + b: TensorLikeType, + rtol: float = 1e-05, + atol: float = 1e-08, + equal_nan: bool = False, +) -> TensorLikeType: + _check_close_args(name="torch.isclose", a=a, b=b, rtol=rtol, atol=atol) + + close = eq(a, b) + if equal_nan and (utils.is_float_dtype(a.dtype) or utils.is_complex_dtype(a.dtype)): + close = logical_or(close, logical_and(isnan(a), isnan(b))) + + # Note: In case of zero tolerances the closeness inequality degenerates to an equality check. + # In this case, the short-circuit prevents false positives as detailed in the paragraph below. + if atol == 0 and rtol == 0: + return close + + # Note [closeness error computation] + # atol and rtol are provided as doubles, so the computation + # rtol * other will produce a float or complex tensor. + # When the difference (self - other) is compared to it then the + # tensor representing the difference will also be cast to float or complex. + # However, since (self - other) in uint8 is very likely to produce a + # negative value, this moves the cast forward so the difference is + # always computed in a float or complex type. + # If the values of the integer tensors cannot be exactly represented + # by the default scalar type then this may cause an incorrect result. + if not utils.is_float_dtype(a.dtype) and not utils.is_complex_dtype(a.dtype): + a = prims.convert_element_type(a, torch.get_default_dtype()) + b = prims.convert_element_type(b, torch.get_default_dtype()) + + allowed_error = add(atol, abs(mul(b, rtol))) + actual_error = abs(sub(a, b)) + + # Computes finite closeness + result = logical_or( + close, logical_and(isfinite(actual_error), le(actual_error, allowed_error)) + ) + + return result + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def lcm(a: TensorLikeType, b: TensorLikeType): + dtype = a.dtype + # promoting to int32 to maintain 100% consistency with C++ and to + # prevent overflow in case of int8 and int16 + promote_to_int = dtype in (torch.int8, torch.int16) + if promote_to_int: + a = prims.convert_element_type(a, torch.int32) + b = prims.convert_element_type(b, torch.int32) + + g = torch.gcd(a, b) + # Avoid division by zero in case gcd(0, 0) == 0 + g = torch.where(g == 0, 1, g) + res = torch.abs(prims.div(a, g) * b) + return res if not promote_to_int else prims.convert_element_type(res, dtype) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + supports_lhs_python_scalar=False, +) +def le(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.le(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def logaddexp(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + # Nb. this implementation does not distribute the gradients evenly when a == b + mask = torch.real(a) >= torch.real(b) + max_ = torch.where(mask, a, b) + min_ = torch.where(mask, b, a) + inf_mask = torch.logical_and( + torch.logical_not(torch.isfinite(torch.real(a))), torch.real(a) == torch.real(b) + ) + if utils.is_complex_dtype(a.dtype) or utils.is_complex_dtype(b.dtype): + # are you wondering what this bunch of codes are for? edge cases! + neg_min_mask = torch.real(min_) < 0 + inf_vals = torch.where( + neg_min_mask, min_, torch.log(torch.exp(min_) + torch.exp(max_)) + ) + non_nan_vals = torch.where( + inf_mask, inf_vals, max_ + torch.log1p(torch.exp(min_ - max_)) + ) + # the type for full_like does not include tensor yet + nan_mask = torch.isnan(min_) + return torch.where(nan_mask, complex(float("nan"), float("nan")), non_nan_vals) # type: ignore[call-overload] + else: + return torch.where(inf_mask, a, max_ + torch.log1p(torch.exp(min_ - max_))) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def logaddexp2(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + torch._check( + not (utils.is_complex_dtype(a.dtype) or utils.is_complex_dtype(b.dtype)), + lambda: "logaddexp2 doesn't support complex dtypes", + ) + # Nb. this implementation does not distribute the gradients evenly when a == b + mask = a >= b + max_ = torch.where(mask, a, b) + min_ = torch.where(mask, b, a) + inf_mask = torch.logical_and(torch.isinf(a), a == b) + inv_log_2 = 1.0 / math.log(2) + result = max_ + torch.log1p(torch.exp2(min_ - max_)) * inv_log_2 + return torch.where(inf_mask, a, result) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, +) +def logical_and(a: TensorLikeType, b: TensorLikeType): + if not utils.is_boolean_dtype(a.dtype): + a = a != 0 + if not utils.is_boolean_dtype(b.dtype): + b = b != 0 + return a & b + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL) +def logical_not(a: TensorLikeType): + if not utils.is_boolean_dtype(a.dtype): + return a == 0 + return ~a + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, +) +def logical_or(a: TensorLikeType, b: TensorLikeType): + if not utils.is_boolean_dtype(a.dtype): + a = a != 0 + if not utils.is_boolean_dtype(b.dtype): + b = b != 0 + return bitwise_or(a, b) + + +# TODO: skip unnecessary conversion of long to float +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, +) +def logical_xor(a: TensorLikeType, b: TensorLikeType): + if not utils.is_boolean_dtype(a.dtype): + a = a != 0 + if not utils.is_boolean_dtype(b.dtype): + b = b != 0 + return a ^ b + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + supports_lhs_python_scalar=False, +) +def lt(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.lt(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def maximum(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.maximum(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def minimum(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.minimum(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_two_python_scalars=True, +) +def mul(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.mul(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + supports_lhs_python_scalar=False, +) +def ne(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.ne(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def nextafter(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.nextafter(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def remainder(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.remainder(a, b) + + +# reverse sub +@register_decomposition(aten.rsub) +@out_wrapper() +def rsub( + a: Union[TensorLikeType, NumberType], + b: Union[TensorLikeType, NumberType], + alpha: NumberType = 1, +): + if isinstance(a, Number): + msg = "Received a Number for the first argument, but expected a Tensor" + raise ValueError(msg) + + return torch.sub(b, a, alpha=alpha) + + +# TODO: consider refactoring this with add impl +# sub has its own implementation because it has an alpha argument +@register_decomposition(aten.sub) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a", "b"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def sub( + a: Union[TensorLikeType, NumberType], + b: Union[TensorLikeType, NumberType], + *, + alpha: NumberType = 1, +): + """ + Reference implementation of torch.sub + """ + + a, b = _maybe_broadcast(a, b) + + if alpha != 1: + dtype = a.dtype if isinstance(a, TensorLike) else b.dtype # type: ignore[union-attr] + python_type = utils.dtype_to_type(dtype) + if not utils.is_weakly_lesser_type(type(alpha), python_type): + msg = f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!" + raise ValueError(msg) + if isinstance(b, torch.Tensor): + b = prims.mul(b, alpha) + else: + # Carefully not to use prims.mul if b is a scalar / symint. + # prims.mul always returns a tensor, + # which will mess with type promotion. + b = b * alpha + + output = prims.sub(a, b) + return handle_noncontiguous_outputs([a, b], output) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + name="true_divide", + aten_op=None, # CompositeImplicitAutograd + supports_two_python_scalars=True, +) +def true_divide(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.div(a, b) + + +@register_decomposition(aten.xlogy) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a", "b"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def xlogy(a: Union[TensorLikeType, NumberType], b: Union[TensorLikeType, NumberType]): + torch._check( + isinstance(a, TensorLike) or isinstance(b, TensorLike), + lambda: 'Expected either argument a or b to be a Tensor"', + ) + + # Operations like eq and log do not handle scalar values, so we convert them to scalar_tensors. + if isinstance(b, TensorLike) and isinstance(a, Number): + a = scalar_tensor(a, dtype=b.dtype, device=b.device) + elif isinstance(a, TensorLike) and isinstance(b, Number): + b = scalar_tensor(b, dtype=a.dtype, device=a.device) + + # mypy: expected "Tensor" + assert isinstance(a, TensorLike) + assert isinstance(b, TensorLike) + rhs = torch.where(torch.eq(a, 0), 0, torch.mul(a, torch.log(b))) + return torch.where(torch.isnan(b), float("nan"), rhs) + + +@_make_elementwise_binary_reference( + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + aten_op=None, # CompositeImplicitAutograd + supports_two_python_scalars=True, +) +def trunc_divide( + a: Union[TensorLikeType, NumberType], b: Union[TensorLikeType, NumberType] +): + dtype = utils.get_dtype(a) + if utils.is_integer_dtype(dtype): + return prims.div(a, b) + + return trunc(prims.div(a, b)) + + +# +# Elementwise Ternary References +# + + +@register_decomposition(aten.addcdiv) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self", "tensor1", "tensor2"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def addcdiv( + self: TensorLikeType, + tensor1: TensorLikeType, + tensor2: TensorLikeType, + *, + value: NumberType = 1, +) -> TensorLikeType: + """ + Reference implementation of torch.addcdiv + """ + if value is not None: + dtype = self.dtype # no scalars allowed, see add + python_type = utils.dtype_to_type(dtype) + torch._check_value( + utils.is_weakly_lesser_type(type(value), python_type), + lambda: f"value argument of type {type(value)} cannot be safely cast to type {python_type}!", + ) + + return self + value * tensor1 / tensor2 + + +@register_decomposition(aten.addcmul) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self", "tensor1", "tensor2"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def addcmul( + self: TensorLikeType, + tensor1: TensorLikeType, + tensor2: TensorLikeType, + *, + value: NumberType = 1, +) -> TensorLikeType: + """ + Reference implementation of torch.addcmul + """ + if value is not None: + dtype = self.dtype # no scalars allowed, see add + python_type = utils.dtype_to_type(dtype) + torch._check_value( + utils.is_weakly_lesser_type(type(value), python_type), + lambda: f"value argument of type {type(value)} cannot be safely cast to type {python_type}!", + ) + + return self + value * tensor1 * tensor2 + + +@register_decomposition(aten.clamp) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a", "min", "max"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def clamp( + a: TensorLikeType, + min: Optional[TensorOrNumberLikeType] = None, + max: Optional[TensorOrNumberLikeType] = None, +) -> TensorLikeType: + # NOTE: grad behavior with implementation `where` is not consistent on `nan` + if min is None and max is None: + msg = "clamp called but both min and max are none!" + raise ValueError(msg) + if min is not None: + a_isnan = torch.isnan(a) + condition = torch.bitwise_or(torch.ge(a, min), a_isnan) # type: ignore[arg-type] + # we should also propagate `nan` coming from boundaries. However, that's + # not necessary since `ge` would already `False` when either operands has + # a `nan`. So this line below is redundant + # `condition = bitwise_and(condition, bitwise_not(isnan(min)))` + a = torch.where(condition, a, min) # type: ignore[arg-type] + if max is not None: + a_isnan = torch.isnan(a) + # same as above, no need to adjust `nan` from `max` + condition = torch.bitwise_or(torch.le(a, max), a_isnan) # type: ignore[arg-type] + a = torch.where(condition, a, max) # type: ignore[arg-type] + + return a + + +@register_decomposition(aten.clamp_min) +@out_wrapper() +def clamp_min( + self: TensorLikeType, + min: Optional[TensorOrNumberLikeType] = None, +) -> TensorLikeType: + return torch.clamp(self, min=min) # type: ignore[arg-type] + + +@register_decomposition(aten.clamp_max) +@out_wrapper() +def clamp_max( + self: TensorLikeType, + max: Optional[TensorOrNumberLikeType] = None, +) -> TensorLikeType: + return torch.clamp(self, max=max) # type: ignore[arg-type] + + +# +# Conditional references +# + + +# https://pytorch.org/docs/stable/generated/torch.where.html +# TODO: implement alternate where +@register_decomposition(aten.where) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a", "b"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH, +) +def where( + pred: Tensor, + a: Optional[TensorOrNumberLikeType] = None, + b: Optional[TensorOrNumberLikeType] = None, +): + """ """ + + if a is None or b is None: + raise NotImplementedError + + utils.check_same_device(pred, a, b, allow_cpu_scalar_tensors=True) + torch._check( + pred.dtype is torch.bool, + lambda: f"expected predicate to be bool, got {pred.dtype}", + ) + + pred, a, b = _maybe_broadcast(pred, a, b) + return prims.where(pred, a, b) + + +# +# Data Movement References +# +@register_decomposition(aten.clone) +@out_wrapper() +def clone( + a: TensorLikeType, *, memory_format: torch.memory_format = torch.preserve_format +) -> TensorLikeType: + result = prims.clone(a, memory_format=memory_format) + return result + + +def copy_to(a: Tensor, b: Tensor, *, allow_cross_device=True): + if not allow_cross_device and a.device != b.device: + msg = "Attempting to copy from device {} to device {}, but cross-device copies are not allowed!".format( + b.device, a.device + ) + raise RuntimeError(msg) + + return prims.copy_to(a, b) + + +@register_decomposition(aten.item) +def item(a: TensorLikeType) -> NumberType: + if a.numel() != 1: + msg = f"Can't convert a tensor with {a.numel()} elements to a number!" + raise ValueError(msg) + + # NOTE: explicit conversion is necessary for bool! + # See https://github.com/pytorch/pytorch/issues/78071 + number_type = utils.dtype_to_type(a.dtype) + return number_type(prims.item(a)) + + +# fast path when `to` returns an alias to input. This mimics the same function in aten +def _to_will_alias( + a: TensorLikeType, + device: Optional[DeviceLikeType] = None, + dtype: Optional[torch.dtype] = None, + copy: Optional[bool] = None, + layout: Optional[torch.layout] = None, + memory_format: Optional[torch.memory_format] = None, + pin_memory: Optional[bool] = False, + non_blocking: bool = False, # not using non_blocking +) -> bool: + return ( + not copy + and (device is None or a.device == device) + and (dtype is None or a.dtype == dtype) + and (layout is None or a.layout == layout) + # is_pinned issue #84925 + # and (pin_memory is None or pin_memory == a.is_pinned()) + and ( + memory_format is None + or memory_format == torch.preserve_format + or utils.is_contiguous_for_memory_format(a, memory_format=memory_format) + ) + ) + + +@singledispatch +def _to_dispatch(*args, **kwargs): + raise NotImplementedError + + +@_to_dispatch.register +def _to_device( + device: torch.device, + dtype: torch.dtype, + non_blocking: bool = False, + copy: bool = False, + memory_format: Optional[torch.memory_format] = None, +) -> Dict[str, Any]: + kwargs = { + "device": device, + "dtype": dtype, + "non_blocking": non_blocking, + "copy": copy, + "memory_format": memory_format, + } + return kwargs + + +@_to_dispatch.register +def _to_device_str( + device: str, + dtype: torch.dtype, + non_blocking: bool = False, + copy: bool = False, + memory_format: Optional[torch.memory_format] = None, +) -> Dict[str, Any]: + kwargs = { + "device": torch.device(device), + "dtype": dtype, + "non_blocking": non_blocking, + "copy": copy, + "memory_format": memory_format, + } + return kwargs + + +@_to_dispatch.register +def _to_dtype( + dtype: torch.dtype, + non_blocking: bool = False, + copy: bool = False, + memory_format: Optional[torch.memory_format] = None, +) -> Dict[str, Any]: + kwargs = { + "dtype": dtype, + "non_blocking": non_blocking, + "copy": copy, + "memory_format": memory_format, + } + return kwargs + + +@_to_dispatch.register +def _to_other( + other: Tensor, + non_blocking: bool = False, + copy: bool = False, + memory_format: Optional[torch.memory_format] = None, +) -> Dict[str, Any]: + device = other.device + dtype = other.dtype + layout = other.layout + # is_pinned issue #84925 + # pin_memory = other.is_pinned() + kwargs = { + "device": device, + "dtype": dtype, + "layout": layout, + "non_blocking": non_blocking, + "copy": copy, + "memory_format": memory_format, + } + return kwargs + + +# remove to_kwargs that is already present in `a` +def _canonicalize_to_arguments(a: Tensor, to_kwargs: dict): + options_to_check = ["dtype", "device", "layout", "memory_format"] + # "device" option could be passed a str instead torch.device + if "device" in to_kwargs and isinstance(to_kwargs["device"], str): + to_kwargs["device"] = torch.device(to_kwargs["device"]) + + for kw in options_to_check: + if kw in to_kwargs: + if ( + (kw == "memory_format" and to_kwargs[kw] is torch.preserve_format) + or ( + kw == "device" + and to_kwargs[kw].type == a.device.type + and ( + not to_kwargs[kw].index or to_kwargs[kw].index == a.device.index + ) + ) + or ( + getattr(a, kw, None) == to_kwargs[kw] + ) # this also handles {"memory_format": None} + ): + to_kwargs.pop(kw) + + +def to(a: TensorLikeType, *args, **kwargs) -> TensorLikeType: + # handled dispatch via positional arguments + if len(args) != 0: + kwargs = _to_dispatch(*args, **kwargs) + + # TODO: is_pinned is not currently supported in refs or fake_tensor + # https://github.com/pytorch/pytorch/issues/84925 + assert "pin_memory" not in kwargs + _canonicalize_to_arguments(a, kwargs) + + if _to_will_alias(a, **kwargs): + return a + + copy = kwargs.pop("copy") if "copy" in kwargs else False + non_blocking = kwargs.pop("non_blocking") if "non_blocking" in kwargs else False + + # short-circuit to `prims.convert_element_type` when `to` is just a dtype change + if ( + (copy or (kwargs.get("dtype", a.dtype) != a.dtype)) + and (not non_blocking) + and ("memory_format" not in kwargs) + and ("device" not in kwargs) + and ("layout" not in kwargs) + # is_pinned issue #84925 + # and ("pin_memory" not in kwargs) + ): + return prims.convert_element_type(a, kwargs.get("dtype", a.dtype)) + + result = torch.empty_like(a, **kwargs) + # TODO: non_blocking should be handled by `copy_to` + copy_to(result, a) + return result + + +# +# Reduction references +# + + +def _reduction( + a: TensorLikeType, + prim: Callable, + *, + has_identity: bool = True, + accepts_dim_tuple: bool = True, # to handle min/argmin that accept single dim only + dims: Optional[DimsType] = None, + keepdims: bool = False, + dtype: Optional[torch.dtype] = None, # should be specified for ops that support it + out: Optional[Tensor] = None, + output_dtype_kind: REDUCTION_OUTPUT_TYPE_KIND, +) -> TensorLikeType: # it is usually SAME, but I want + # ref writers to actually think about what to put here + assert isinstance(a, TensorLike) + if a.ndim > 64: + raise RuntimeError( + f"Received a tensor with {a.ndim} dimensions, but only tensors with up to 64 dims are supported!" + ) + + if out is not None: + assert isinstance(out, TensorLike) + if dtype is not None: + # TODO - this is true for eager mode currently, but it's wrong behavior for complex norms + if dtype != out.dtype: + raise RuntimeError( + "dtype argument and out dtype must match in reduction" + ) + if not accepts_dim_tuple: + assert dims is None or isinstance(dims, Dim) + if isinstance(dims, Dim): + dims = (dims,) # type: ignore[assignment] + dims = utils.reduction_dims(a.shape, dims) + if not has_identity: + valid_shape = a.ndim == 0 or py_all(a.shape[i] for i in dims) + if not valid_shape: + raise RuntimeError( + "reducing over zero-size dimension for reduction operation without identity" + ) + computation_dtype, result_dtype = utils.reduction_dtypes( + a, output_dtype_kind, dtype + ) + a = _maybe_convert_to_dtype(a, computation_dtype) # type: ignore[method-assign] + result = prim(a, dims) + if keepdims: + output_shape = [a.shape[i] if i not in dims else 1 for i in range(a.ndim)] + broadcast_dims = [i for i in range(a.ndim) if i not in dims] + result = prims.broadcast_in_dim(result, output_shape, broadcast_dims) + + if out is not None: + assert result_dtype is not None + if dtype is not None and result_dtype != out.dtype: + raise RuntimeError( + "Expected the dtype of reduction result and out to match" + ) + out = _maybe_resize_out(out, result.shape) + return _safe_copy_out(copy_from=result, copy_to=out) # type: ignore[arg-type] + + if result.dtype != result_dtype and result_dtype is not None: + result = prims.convert_element_type(result, result_dtype) + + return result + + +def _make_copy_from_view(fn): + """ + Given a view function (e.g. torch.diagonal) generates its copy variant (e.g. torch.diagonal_copy) + """ + name = fn.__name__ + fn = out_wrapper()(fn) + + def _fn(*args, out=None, **kwargs): + result = fn(*args, out=out, **kwargs) + if out is None: + return result.clone(memory_format=torch.contiguous_format) + return result + + copy_name = f"{name}_copy" + _fn.__name__ = copy_name + _fn = register_decomposition(getattr(aten, copy_name))(_fn) + return _fn + + +# Saves Python all +py_all = all + + +@register_decomposition(aten.all) +@out_wrapper() +def all( + a: TensorLikeType, + dim: Optional[DimsType] = None, + keepdim: bool = False, +) -> TensorLikeType: + result = torch.logical_not(torch.any(torch.logical_not(a), dim, keepdim=keepdim)) + + if a.dtype == torch.uint8: + result = result.to(dtype=torch.uint8) + + return result + + +# Saves Python any +py_any = any + + +@register_decomposition(aten.any) +@out_wrapper() +def any( + a: TensorLikeType, + dim: Optional[DimsType] = None, + keepdim: bool = False, +) -> TensorLikeType: + a_ = _maybe_convert_to_dtype(a, torch.bool) + if isinstance(dim, (list, tuple)) and len(dim) == 0: + result = a_.clone() + else: + result = a_.sum(dim=dim, keepdim=keepdim).ne(False) + + # Preserves uint8 -- probably a legacy mask thing + if a.dtype is torch.uint8: + return prims.convert_element_type(result, torch.uint8) + + return result + + +@register_decomposition([aten.sum.dim_IntList, aten.sum.IntList_out]) +def sum( + a: TensorLikeType, + dim: Union[Optional[int], Optional[List[int]]] = None, + keepdim: bool = False, + *, + dtype: Optional[torch.dtype] = None, + out: Optional[Tensor] = None, +) -> TensorLikeType: + if dtype is None: + if out is not None: + dtype = out.dtype + elif utils.is_boolean_dtype(a.dtype) or utils.is_integer_dtype(a.dtype): + dtype = torch.int64 + else: + dtype = a.dtype + # reduces over all dimensions if dim=() is passed + if dim == () or dim == []: + dim = None + return _reduction( + a, + prims.sum, + dims=dim, + keepdims=keepdim, + dtype=dtype, + out=out, + output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.SAME, + ) + + +def sum_to_size( + a: Tensor, + *shape, +) -> Tensor: + shape = utils.extract_shape_from_varargs(shape, validate=False) + torch._check( + utils.is_expandable_to(shape, a.shape), + lambda: f'sum_to_size: size "{shape}" is not expandable to size "{a.shape}"', + ) + # In ATen scalar tensors are sent through sum and the result is returned as + # type promoted + if utils.is_same_shape(shape, a.shape) and len(shape) > 0: + return prims.view_of(a) + leading_dims = a.ndim - len(shape) + reduce_dims = tuple(range(leading_dims)) + tuple( + i + for i in range(leading_dims, len(shape)) + if shape[i - leading_dims] == 1 and a.shape[i] != 1 + ) + return torch.sum(a, dim=reduce_dims, keepdim=True, dtype=None) + + +@register_decomposition(aten.prod) +def prod( + a: TensorLikeType, + dim: Union[Optional[int], Optional[List[int]]] = None, + keepdim: bool = False, + *, + dtype=None, + out: Optional[Tensor] = None, +) -> TensorLikeType: + if dtype is None: + if out is not None: + dtype = out.dtype + elif utils.is_boolean_dtype(a.dtype) or utils.is_integer_dtype(a.dtype): + dtype = torch.int64 + else: + dtype = a.dtype + # reduces over all dimensions if dim=() is passed + if dim == () or dim == []: + dim = None + return _reduction( + a, + prims.prod, + dims=dim, + keepdims=keepdim, + dtype=dtype, + out=out, + output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.SAME, + ) + + +@register_decomposition(aten.amin) +def amin( + a: TensorLikeType, + dim: Optional[DimsType] = None, + keepdim: bool = False, + *, + out: Optional[Tensor] = None, +) -> TensorLikeType: + # reduces over all dimensions if dim=() is passed + if dim == () or dim == []: + dim = None + + return _reduction( + a, + prims.amin, + dims=dim, + keepdims=keepdim, + dtype=None, + out=out, + has_identity=False, + output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.SAME, + ) + + +@register_decomposition(aten.amax) +def amax( + a: TensorLikeType, + dim: Optional[DimsType] = None, + keepdim: bool = False, + *, + out: Optional[Tensor] = None, +) -> TensorLikeType: + # reduces over all dimensions if dim=() is passed + if dim == () or dim == []: + dim = None + + return _reduction( + a, + prims.amax, + dims=dim, + keepdims=keepdim, + dtype=None, + out=out, + has_identity=False, + output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.SAME, + ) + + +def _dim_var_dispatch(dim=None, unbiased=None): + # There's the following overload of torch.var: + # var(Tensor self, bool unbiased=True) -> (Tensor, Tensor) + # We need to explicitly convert bool dims to unbiased arg + if unbiased is None and isinstance(dim, bool): + unbiased = dim + dim = None + return dim, unbiased + + +@register_decomposition(aten.var) +@out_wrapper() +def var( + a: TensorLikeType, + dim: Optional[DimsType] = None, + unbiased: Optional[bool] = None, + keepdim: bool = False, + *, + correction: Optional[NumberType] = None, +) -> TensorLikeType: + dim, unbiased = _dim_var_dispatch(dim, unbiased) + correction = utils.set_correction(unbiased, correction) + # reduces over all dimensions if dim=() is passed + if dim == () or dim == []: + dim = None + + result = _reduction( + a, + partial(prims.var, correction=correction), + dims=dim, + keepdims=keepdim, + dtype=None, + out=None, + has_identity=True, + output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT, + ) + return result + + +@register_decomposition(aten.std) +@out_wrapper() +def std( + a: TensorLikeType, + dim: Union[Optional[int], Optional[List[int]]] = None, + unbiased: Optional[bool] = None, + keepdim: bool = False, + *, + correction: Optional[NumberType] = None, +) -> TensorLikeType: + dim, unbiased = _dim_var_dispatch(dim, unbiased) + correction = utils.set_correction(unbiased, correction) + + opmath_dtype, dtype = utils.reduction_dtypes( + a, REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT + ) + a = _maybe_convert_to_dtype(a, opmath_dtype) + a_var = torch.var(a, dim, correction=correction, keepdim=keepdim) + a_std = torch.sqrt(a_var) + assert dtype is not None + return _maybe_convert_to_dtype(a_std, dtype) + + +@register_decomposition(aten.mean) +def mean( + a: TensorLikeType, + dim: Optional[DimsType] = None, + keepdim: bool = False, + *, + dtype=None, + out=None, +) -> TensorLikeType: + # reduces over all dimensions if dim=() is passed + if dim == () or dim == []: + dim = None + orig_dtype = dtype + if dtype is None: + dtype = a.dtype + # can't use out wrapper because of this argument + torch._check( + out is None or out.dtype == dtype, + lambda: f"Expected out tensor to have dtype {dtype}, but got {out.dtype} instead", + ) + result = _reduction( + a, + prims.sum, + dims=dim, + keepdims=keepdim, + dtype=dtype, + out=None, + output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.KEEP_PROMOTED_TYPE, + ) + torch._check( + utils.is_float_dtype(dtype) or utils.is_complex_dtype(dtype), + lambda: ( + f"mean(): could not infer output dtype. " + f"{'Input' if orig_dtype is None else 'Optional'} dtype must be either " + f"a floating point or complex dtype. Got: {dtype}" + ), + ) + if isinstance(dim, Dim): + dim = (dim,) # type: ignore[assignment] + dims = utils.reduction_dims(a.shape, dim) # type: ignore[arg-type] + nelem = 1 if a.ndim == 0 else reduce(operator.mul, (a.shape[i] for i in dims), 1) + result = true_divide(result, nelem) + result_dtype = a.dtype if dtype is None else dtype + result = _maybe_convert_to_dtype(result, result_dtype) # type: ignore[method-assign] + if out is not None: + assert isinstance(out, TensorLike) + out = _maybe_resize_out(out, result.shape) + return _safe_copy_out(copy_from=result, copy_to=out) # type: ignore[arg-type] + return result + + +@register_decomposition(aten.std_mean) +@out_wrapper("out0", "out1") +def std_mean( + a: TensorLikeType, + dim: Optional[DimsType] = None, + *, + unbiased: Optional[bool] = None, + keepdim: bool = False, + correction: Optional[NumberType] = None, +): + dim, unbiased = _dim_var_dispatch(dim, unbiased) + correction = utils.set_correction(unbiased, correction) + opmath_dtype, dtype = utils.reduction_dtypes( + a, REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT + ) + original_dtype = a.dtype + a = _maybe_convert_to_dtype(a, opmath_dtype) + a_var, a_mean = torch.var_mean(a, dim, correction=correction, keepdim=keepdim) + a_std = torch.sqrt(a_var) + assert dtype is not None + return ( + _maybe_convert_to_dtype(a_std, dtype), + _maybe_convert_to_dtype(a_mean, original_dtype), + ) + + +@register_decomposition(aten.var_mean) +@out_wrapper("out0", "out1") +def var_mean( + a: TensorLikeType, + dim: Optional[DimsType] = None, + unbiased: Optional[bool] = None, + keepdim: bool = False, + *, + correction: Optional[NumberType] = None, +): + dim, unbiased = _dim_var_dispatch(dim, unbiased) + v = var(a, dim, unbiased, keepdim, correction=correction) + m = mean(a, dim, keepdim) + return v, m + + +@register_decomposition(aten.addr) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self", "vec1", "vec2"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def addr( + self: TensorLikeType, + vec1: TensorLikeType, + vec2: TensorLikeType, + *, + beta: NumberType = 1, + alpha: NumberType = 1, +) -> TensorLikeType: + torch._check( + vec1.ndim == 1, + lambda: f"addr: Expected 1-D argument vec1, but got {vec1.ndim}-D", + ) + torch._check( + vec2.ndim == 1, + lambda: f"addr: Expected 1-D argument vec2, but got {vec2.ndim}-D", + ) + self = self.expand(vec1.shape[0], vec2.shape[0]) + if utils.is_boolean_dtype(self.dtype): + # Integers are accepted for booleans + torch._check( + is_weakly_lesser_type(type(beta), int), + lambda: f"expected bool/int beta but got {type(beta)}", + ) + torch._check( + is_weakly_lesser_type(type(alpha), int), + lambda: f"expected bool/int alpha but got {type(beta)}", + ) + if not beta: + return torch.outer(vec1, vec2) if alpha else torch.full_like(self, False) + else: + return torch.logical_or( + self, + torch.outer(vec1, vec2) if alpha else torch.full_like(self, False), + ) + else: + torch._check( + is_weakly_lesser_type(type(beta), dtype_to_type(self.dtype)), + lambda: f"cannot safely convert {type(beta)} to {self.dtype}", + ) + torch._check( + is_weakly_lesser_type(type(alpha), dtype_to_type(self.dtype)), + lambda: f"cannot safely convert {type(alpha)} to {self.dtype}", + ) + if beta == 0: + # This means NaNs from self are dropped if beta is zero + return alpha * torch.outer(vec1, vec2) + else: + return beta * self + alpha * torch.outer(vec1, vec2) + + +# CompositeImplicitAutograd - don't register decomp +def atleast_1d( + arg: Union[TensorLikeType, Sequence[TensorLikeType]], *args: TensorLikeType +) -> Union[TensorLikeType, Tuple[TensorLikeType, ...]]: + """Reference implementation of :func:`torch.atleast_1d`.""" + if not args and isinstance(arg, collections.abc.Sequence): + args_ = arg + else: + assert not isinstance(arg, collections.abc.Sequence) + args_ = (arg,) + args + res = tuple(a if a.ndim >= 1 else unsqueeze(a, 0) for a in args_) + return res if len(res) > 1 else res[0] + + +# Helper function with assert to avoid MyPy error +# of incompatible type passed to unsqueeze +def _unsqueeze_atleast( + at_least_fn: Callable, dim: int, arg: TensorLikeType +) -> TensorLikeType: + arg_ = at_least_fn(arg) + assert isinstance(arg_, TensorLike) + return unsqueeze(arg_, dim) + + +# CompositeImplicitAutograd - don't register decomp +def atleast_2d( + arg: Union[TensorLikeType, Sequence[TensorLikeType]], *args: TensorLikeType +) -> Union[TensorLikeType, Tuple[TensorLikeType, ...]]: + """Reference implementation of :func:`torch.atleast_2d`.""" + if not args and isinstance(arg, collections.abc.Sequence): + args_ = arg + else: + assert not isinstance(arg, collections.abc.Sequence) + args_ = (arg,) + args + unsqueeze_atleast_1d = partial(_unsqueeze_atleast, atleast_1d, 0) + res = tuple(a if a.ndim >= 2 else unsqueeze_atleast_1d(a) for a in args_) + return res if len(res) > 1 else res[0] + + +# CompositeImplicitAutograd - don't register decomp +def atleast_3d( + arg: Union[TensorLikeType, Sequence[TensorLikeType]], *args: TensorLikeType +) -> Union[TensorLikeType, Tuple[TensorLikeType, ...]]: + """Reference implementation of :func:`torch.atleast_3d`.""" + if not args and isinstance(arg, collections.abc.Sequence): + args_ = arg + else: + assert not isinstance(arg, collections.abc.Sequence) + args_ = (arg,) + args + unsqueeze_atleast_2d = partial(_unsqueeze_atleast, atleast_2d, -1) + res = tuple(a if a.ndim >= 3 else unsqueeze_atleast_2d(a) for a in args_) + return res if len(res) > 1 else res[0] + + +def as_strided( + a: TensorLikeType, + size: ShapeType, + stride: StrideType, + storage_offset: Optional[int] = None, +) -> TensorLikeType: + storage_offset_int = ( + storage_offset if storage_offset is not None else a.storage_offset() + ) + return prims.as_strided(a, size, stride, storage_offset_int) + + +@register_decomposition(aten.as_strided_scatter) +@out_wrapper() +def as_strided_scatter( + input: TensorLikeType, + src: TensorLikeType, + size: ShapeType, + stride: StrideType, + storage_offset: Optional[int] = None, +) -> TensorLikeType: + storage_offset_int = 0 if storage_offset is None else storage_offset + return prims.as_strided_scatter(input, src, size, stride, storage_offset_int) + + +def broadcast_shapes(*shapes) -> ShapeType: + return torch.Size(_broadcast_shapes(*shapes)) + + +@aten.broadcast_tensors.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.broadcast_tensors.default.py_impl(DispatchKey.Meta) +def broadcast_tensors(*tensors) -> List[TensorLikeType]: + if len(tensors) == 1 and not isinstance(tensors[0], Tensor): + tensors = tensors[0] + return list(_maybe_broadcast(*tensors, preserve_cpu_scalar_tensors=False)) + + +# CompositeImplicitAutograd - don't register decomp +def broadcast_to(a: TensorLikeType, size: ShapeType) -> TensorLikeType: + start = len(size) - len(a.shape) + dims = tuple(range(start, len(a.shape) + start)) + return prims.broadcast_in_dim(a, size, dims) + + +@register_decomposition(aten.cat) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("tensors",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH, +) +def cat(tensors: TensorSequenceType, dim: int = 0) -> TensorLikeType: + def cat_compute_output_memory_format(inputs): + format = None + for t in inputs: + f = utils.suggest_memory_format(t) + if f == torch.contiguous_format: + return f + if format is not None and format != f: + return torch.contiguous_format + format = f + assert format is not None + return format + + if len(tensors) == 0: + msg = "cat expects at least one tensor, but received zero!" + raise ValueError(msg) + + for tensor in tensors: + assert isinstance(tensor, TensorLike) + + utils.check_same_device(*tensors, allow_cpu_scalar_tensors=False) + + from torch.fx.experimental.symbolic_shapes import guard_size_oblivious + + # This is a bit tricky. Naively, you would expect to just pick one + # arbitrary tensor and check that all tensors match this tensor. However, + # there is legacy behavior which says that if you have a 1-D empty tensor + # (0,), this is permissible. So you can't assume that all the tensors + # have same dimensionality, and you can't assume that the first tensor is + # the correct stencil. + # + # We'll implement this in a few passes. First, we will try to infer the + # ndim of the cat output. If this ndim != 1, then we know that all ndim = + # 1 inputs must be empty, or are errors. If this ndim == 1, then life + # is easy (the legacy special case coincides with regular handling). + # + # NB: The regular implementation of cat just filters out empty inputs, + # but we do it slightly different here for better handling for unbacked + # SymInts + + example = None + for i, t in enumerate(tensors): + if example is None: + if t.ndim != 1: + example = t + else: + if t.ndim != 1: + torch._check( + t.ndim == example.ndim, + lambda: "Number of dimensions of tensors must match. " + f"Expected {example.ndim}-D tensors, but got {t.ndim}-D for " + f"tensor number {i} in the list", + ) + + if example is None: + # example is None if everything is 1-D. If so, just arbitrarily pick + # the first one + example = tensors[0] + + shape = example.shape + filtered = [] + for tensor_idx, tensor in enumerate(tensors): + if len(shape) != len(tensor.shape): + assert tensor.ndim == 1 # we've already checked this above + # Don't suggest the legacy behavior in the error message + torch._check( + tensor.shape[0] == 0, + lambda: f"Number of dimensions of tensors must match. " + f"Expected {example.ndim}-D tensors, but got 1-D for " + f"tensor number {tensor_idx} in the list", + ) + else: + # Remove inputs that are 1-D, zero size + if tensor.ndim == 1 and guard_size_oblivious(tensor.shape[0] == 0): + continue + # Don't bother checking size match, prims.cat will handle it + filtered.append(tensor) + + memory_format = cat_compute_output_memory_format(tensors) + + if len(filtered) == 0: + t = tensors[0] + + # TODO: fix this to work with meta tensors + try: + requires_grad = any(x.requires_grad for x in tensors) + except Exception: + requires_grad = False + + return empty( + (0,), + dtype=t.dtype, + device=t.device, + requires_grad=requires_grad, + memory_format=memory_format, + ) + + dim = utils.canonicalize_dim(filtered[0].ndim, dim) + utils.validate_idx(filtered[0].ndim, dim) + + return prims.cat(filtered, dim).clone(memory_format=memory_format) + + +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +def column_stack(tensors: TensorSequenceType) -> TensorLikeType: + aligned_tensors = tuple( + x if x.ndim > 1 else x.reshape((x.numel(), 1)) for x in tensors + ) + return cat(aligned_tensors, 1) + + +def conj(input: TensorLikeType) -> TensorLikeType: + if not utils.is_complex_dtype(input.dtype): + return input + if input.is_sparse: + return torch.conj_physical(input) + return prims.conj(input) + + +# This replicates at::constant_pad_nd, defined in ATen/native/PadNd.cpp +@register_decomposition(aten.constant_pad_nd) +@out_wrapper() +def constant_pad_nd( + input: TensorLikeType, pad: List[int], value: NumberType = 0 +) -> TensorLikeType: + torch._check( + len(pad) % 2 == 0, + lambda: f"Length of pad must be even but instead it equals {len(pad)}", + ) + + input_sizes = input.shape + l_inp = len(input_sizes) + + l_pad = len(pad) // 2 + l_diff = l_inp - l_pad + + torch._check( + l_inp >= l_pad, + lambda: "Length of pad should be no more than twice the number of " + f"dimensions of the input. Pad length is {len(pad)} while the input has " + f"{l_inp} dimensions.", + ) + + c_input = input + for i in range(l_diff, l_inp): + pad_idx = 2 * (l_inp - i - 1) + if pad[pad_idx] < 0: + c_input = c_input.narrow(i, -pad[pad_idx], c_input.shape[i] + pad[pad_idx]) + + if pad[pad_idx + 1] < 0: + c_input = c_input.narrow(i, 0, c_input.shape[i] + pad[pad_idx + 1]) + + # if none of the pads are positive we can just return the result + if builtins.all(p <= 0 for p in pad): + return c_input.clone() + + new_shape = list(input_sizes[:l_diff]) + + for i in range(l_pad): + pad_idx = len(pad) - ((i + 1) * 2) + new_dim = input_sizes[l_diff + i] + pad[pad_idx] + pad[pad_idx + 1] + torch._check( + new_dim > 0, + lambda: f"The input size {input_sizes[l_diff + i]}, plus negative padding " + f"{pad[pad_idx]} and {pad[pad_idx + 1]} resulted in a negative output size, " + f"which is invalid. Check dimension {l_diff + i} of your input.", + ) + new_shape.append(new_dim) + + memory_format = utils.suggest_memory_format(input) + output = torch.empty( + new_shape, + dtype=input.dtype, + device=input.device, + requires_grad=input.requires_grad, + memory_format=memory_format, + ) + + if value == 0 and input.dtype == torch.bool: + value = False + # torch.fill isn't typed to allow complex values + output = torch.fill(output, value) # type: ignore[arg-type] + + c_output = output + for i in range(l_diff, l_inp): + pad_idx = 2 * (l_inp - i - 1) + if pad[pad_idx] > 0: + c_output = c_output.narrow( + i, pad[pad_idx], c_output.shape[i] - pad[pad_idx] + ) + if pad[pad_idx + 1] > 0: + c_output = c_output.narrow(i, 0, c_output.shape[i] - pad[pad_idx + 1]) + + prims.copy_to(c_output, c_input) + return output + + +def contiguous( + a: Tensor, *, memory_format: torch.memory_format = torch.contiguous_format +) -> Tensor: + torch._check( + memory_format != torch.preserve_format, + lambda: "preserve memory format is unsupported by the contiguous operator", + ) + + if utils.is_contiguous_for_memory_format(a, memory_format=memory_format): + return a + + return torch.clone(a, memory_format=memory_format) + + +@out_wrapper() +def dstack(tensors: TensorSequenceType) -> TensorLikeType: + torch._check(len(tensors) > 0, lambda: "dstack expects a non-empty TensorList") + aligned_tensors = atleast_3d(*tensors) + return cat(aligned_tensors, 2) + + +@register_decomposition(aten.expand) +def expand(a: Tensor, *shape) -> Tensor: + from torch.fx.experimental.symbolic_shapes import guard_size_oblivious + + # NOTE: cannot use utils.extract_shape_from_varargs here + # because that also validates the shape, but the shape + # given to expand may be "invalid" + if len(shape) == 1 and isinstance(shape[0], Sequence): + shape = tuple(shape[0]) + + torch._check( + len(shape) >= len(a.shape), + lambda: "expand: the requested shape has too few dimensions!", + ) + + offset = len(shape) - len(a.shape) + shape_ = list(shape) + for idx, x in enumerate(a.shape): + offset_idx = idx + offset + requested_length = shape[offset_idx] + torch._check( + guard_size_oblivious(requested_length == x) + or guard_size_oblivious(x == 1) + or requested_length == -1, + lambda: f"expand: attempting to expand a dimension of length {x}!", + ) + + shape_[offset_idx] = requested_length if requested_length != -1 else x + + # At this point shape must be valid + utils.validate_shape(shape_) + + return prims.broadcast_in_dim( + a, shape_, tuple(range(offset, len(a.shape) + offset)) + ) + + +# CompositeImplicitAutograd - don't register decomp +def expand_as(a: Tensor, b: Tensor) -> Tensor: + return a.expand(b.shape) + + +def chunk(a: TensorLikeType, chunks: int, dim: int = 0) -> Tuple[TensorLikeType, ...]: + if chunks <= 0: + msg = f"Expected at least one chunk, but got {chunks}!" + raise ValueError(msg) + + dim = utils.canonicalize_dim(a.ndim, dim) + length = a.shape[dim] + chunk_size = math.ceil(length / chunks) + full_chunks = math.floor(length / chunk_size) + tail_chunk_size = length % chunk_size + + result = [] + for i in range(full_chunks): + result.append(narrow(a, dim, i * chunk_size, chunk_size)) + + if tail_chunk_size != 0: + result.append(narrow(a, dim, full_chunks * chunk_size, tail_chunk_size)) + + return tuple(result) + + +# Note: flatten, unlike other shape operators, returns the input tensor on a no-op (unless +# a 0D tensor is flattened, in which case it's returned in 1D) +# CompositeImplicitAutograd - don't register decomp +def flatten(a: TensorLikeType, start_dim: int = 0, end_dim: int = -1) -> TensorLikeType: + start_dim = utils.canonicalize_dim(a.ndim, start_dim) + end_dim = utils.canonicalize_dim(a.ndim, end_dim) + + # Short-circuits on no-op + if start_dim == end_dim and a.ndim != 0: + return a + + # Tries to take a view + # TODO: we could look at directing collapse_view to skip its meta function here (unsafe_collapse_view) + new_shape, new_strides = prims._collapse_view_helper(a, start_dim, end_dim) + if new_shape is not None: + return prims.collapse_view(a, start_dim, end_dim) + + # Makes a copy if it can't make a view + return prims.collapse(a, start_dim, end_dim) + + +@register_decomposition(aten.flip) +@out_wrapper() +def flip(a: TensorLikeType, dims: DimsSequenceType) -> TensorLikeType: + if not isinstance(dims, tuple) and not isinstance(dims, list): + raise ValueError("dims has to be a sequence of ints") + dims = utils.canonicalize_dims(a.ndim, dims) # type: ignore[assignment] + utils.validate_no_repeating_dims(dims) + return prims.rev(a, dims) + + +# CompositeImplicitAutograd - don't register decomp +def fliplr(a: TensorLikeType) -> TensorLikeType: + if a.ndim < 2: + raise RuntimeError("Input must be >= 2-d.") + + return flip(a, (1,)) + + +# CompositeImplicitAutograd - don't register decomp +def flipud(a: TensorLikeType) -> TensorLikeType: + if a.ndim < 1: + raise RuntimeError("Input must be >= 1-d.") + + return flip(a, (0,)) + + +# CompositeImplicitAutograd - don't register decomp +def narrow( + a: TensorLikeType, dim: int, start: Union[int, TensorLikeType], length: int +) -> TensorLikeType: + # Supports Tensor overload that was added for XLA: + # https://github.com/pytorch/pytorch/issues/31558 + if isinstance(start, TensorLike): + torch._check( + start.dim() == 0 and utils.is_integer_dtype(start.dtype), + lambda: "start must be an 0-dim integral Tensor.", + ) + start = start.item() # type: ignore[assignment] + torch._check(a.dim() > 0, lambda: "narrow() cannot be applied to a 0-dim tensor.") + torch._check(length >= 0, lambda: "narrow(): length must be non-negative.") + dim = utils.canonicalize_dim(a.ndim, dim) + dim_length = a.size(dim) + torch._check_with( + IndexError, + -dim_length <= start and start <= dim_length, # type: ignore[arg-type] + lambda: f"start out of range (expected to be in range of [{-dim_length}, {dim_length}], but got {start})", + ) + if start < 0: + start = start + dim_length + torch._check( + start <= dim_length - length, # type: ignore[arg-type] + lambda: f"start ({start}) + length ({length}) exceeds dimension size ({dim_length}).", + ) + return prims.slice_in_dim(a, start, start + length, axis=dim) + + +# TODO: This must return a sparse tensor if the input is sparse, but refs have +# no sparse support. See narrow_copy_sparse in core. +narrow_copy = _make_copy_from_view(narrow) + + +def _normalize( + a: Tensor, norm_dims: DimsType, eps: float +) -> Tuple[Tensor, Tensor, Tensor]: + """Computes mean and 1/std of a tensor along norm_dims. + + Used as a helper function for normalization layers. + + Args: + a (Tensor): input tensor + norm_dims (DimsType): dimensions to normalize over + eps (float): epsilon for numerical stability + + Returns: + out (Tensor): normalized tensor. + mean (Tensor): mean of the tensor along norm_dims. + rstd (Tensor): 1/std of the tensor along norm_dims. + """ + norm_dims = utils.canonicalize_dims(a.ndim, norm_dims) + computation_dtype = utils.get_computation_dtype(a.dtype) + a_acc = _maybe_convert_to_dtype(a, computation_dtype) + assert isinstance(a_acc, TensorLike) # to avoid mypy error for var_mean + biased_var, mean = torch.var_mean( + a_acc, dim=norm_dims, unbiased=False, keepdim=True + ) + rstd = torch.rsqrt(biased_var + eps) + out = (a - mean) * rstd + return out, mean, rstd + + +# add all specified dimensions +def _unsqueeze_multiple(x: TensorLikeType, dimensions: List[int]) -> TensorLikeType: + for dim in sorted(dimensions): + x = torch.unsqueeze(x, dim) + return x + + +@register_decomposition(aten.native_group_norm.default) +def native_group_norm( + input: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + batch_size: int, + num_channels: int, + flattened_inner_size: int, + num_groups: int, + eps: float, +) -> Tuple[Tensor, Tensor, Tensor]: + torch._check( + input.ndim >= 2, + lambda: f"Expected at least 2 dimensions for input tensor but received {input.ndim}", + ) + torch._check( + num_channels % num_groups == 0, + lambda: "Expected number of channels in input to be divisible by num_groups, " + + f"but got input of shape {input.shape} and num_groups = {num_groups}", + ) + + # num_channels / num_groups and flattened inner dimension are the reduction axes + reduction_dims = [2, 3] + input_reshaped = torch.reshape( + input, + [batch_size, num_groups, num_channels // num_groups, flattened_inner_size], + ) + out, mean, rstd = _normalize(input_reshaped, reduction_dims, eps) + out = out.view(input.shape) + + broadcast_dims = [0] + list(range(2, input.ndim)) + unsqueeze_bias = None + if bias is not None: + unsqueeze_bias = _unsqueeze_multiple(bias, broadcast_dims) + unsqueeze_weight = None + if weight is not None: + unsqueeze_weight = _unsqueeze_multiple(weight, broadcast_dims) + + if unsqueeze_weight is not None: + out = out * unsqueeze_weight + if unsqueeze_bias is not None: + out = out + unsqueeze_bias + + out = _maybe_convert_to_dtype(out, input.dtype) # type: ignore[assignment] + mean = _maybe_convert_to_dtype(mean, input.dtype) # type: ignore[assignment] + rstd = _maybe_convert_to_dtype(rstd, input.dtype) # type: ignore[assignment] + + # remove broadcast dimensions from mean and rstd + mean = torch.squeeze(mean, reduction_dims) + rstd = torch.squeeze(rstd, reduction_dims) + return (out, mean, rstd) + + +@register_decomposition(aten.native_layer_norm) +@out_wrapper("out0", "out1", "out2") +def native_layer_norm( + input: Tensor, + normalized_shape: ShapeType, + weight: Optional[Tensor], + bias: Optional[Tensor], + eps: float, +) -> Tuple[Tensor, Tensor, Tensor]: + normalized_ndim = len(normalized_shape) + torch._check( + normalized_ndim >= 1, + lambda: "Expected normalized_shape to be at least 1-dimensional, i.e., " + + "containing at least one element, but got normalized_shape = " + + str(normalized_shape), + ) + # torch.Size([1, 2, 3]) == [1, 2, 3] evaluates to False + # while torch.Size([1, 2, 3]) == (1, 2, 3) is True + # therefore we use tuple(normalized_shape) + torch._check( + weight is None or weight.shape == tuple(normalized_shape), + lambda: "Expected weight to be of same shape as normalized_shape, but got " + + "weight of shape " + + str(weight.shape) # type: ignore[union-attr] + + " and normalized_shape = " + + str(normalized_shape), + ) + torch._check( + bias is None or bias.shape == tuple(normalized_shape), + lambda: "Expected bias to be of same shape as normalized_shape, but got " + + "bias of shape " + + str(bias.shape) # type: ignore[union-attr] + + " and normalized_shape = " + + str(normalized_shape), + ) + torch._check( + input.ndim >= normalized_ndim + and input.shape[(input.ndim - normalized_ndim) :] == tuple(normalized_shape), + lambda: "Given normalized_shape=" + + str(normalized_shape) + + ", expected input with shape " + + str(normalized_shape) + + ", but got input of size " + + str(input.shape), + ) + + input = input.contiguous() + if weight is not None: + weight = weight.contiguous() + if bias is not None: + bias = bias.contiguous() + + axis = input.ndim - normalized_ndim + reduction_dims = list(range(axis, input.ndim)) + out, mean, rstd = _normalize(input, reduction_dims, eps) + + if weight is None and bias is not None: + out = out + bias + elif weight is not None and bias is None: + out = out * weight + elif weight is not None and bias is not None: + out = out * weight + bias + + out = _maybe_convert_to_dtype(out, input.dtype) # type: ignore[assignment] + if input.device.type == "cpu": + mean = _maybe_convert_to_dtype(mean, input.dtype) # type: ignore[assignment] + rstd = _maybe_convert_to_dtype(rstd, input.dtype) # type: ignore[assignment] + return (out, mean, rstd) + + +# TODO: Adding this as a meta function causes functorch tests to fail when compiled with debug mode. +# test/test_eager_transforms.py::TestFunctionalizeCPU::test_functionalize_fx_transpose_simple_cpu +@register_decomposition(aten.permute) +def permute(a: TensorLikeType, *dims) -> TensorLikeType: + _permutation = utils.canonicalize_dims( + a.ndim, utils.extract_dims_from_varargs(dims) + ) + return prims.transpose(a, _permutation) + + +@register_decomposition(aten.renorm) +@out_wrapper() +def renorm( + input: TensorLikeType, p: RealNumberType, dim: int, maxnorm: RealNumberType +) -> TensorLikeType: + torch._check(not isinstance(p, complex), lambda: "renorm: p must be real-valued") + torch._check(p > 0, lambda: "renorm: non-positive norm not supported") + torch._check( + not isinstance(maxnorm, complex), lambda: "renorm: maxnorm must be real-valued" + ) + torch._check( + maxnorm >= 0, lambda: f"renorm: expected maxnorm to be >= 0 but got {maxnorm}" + ) + ndim = input.ndim + torch._check( + ndim > 1, + lambda: f"renorm: input needs at least 2 dimensions, got {ndim} dimensions", + ) + + dim = utils.canonicalize_dim(ndim, dim) + reduce_dims = list(range(ndim)) + del reduce_dims[dim] + + # For half and bfloat16, calculate norm in float precision then cast + # normalization factor to half + acc_type = utils.get_computation_dtype(input.dtype) + if acc_type != input.dtype: + norm = torch.linalg.vector_norm( + input, p, reduce_dims, keepdim=True, dtype=acc_type + ) + else: + norm = torch.linalg.vector_norm(input, p, reduce_dims, keepdim=True) + + eps = 1e-7 + norm_factor = torch.where(norm > maxnorm, maxnorm / (norm + eps), 1.0) + if acc_type != input.dtype: + norm_factor = prims.convert_element_type(norm_factor, input.dtype) + return (input * norm_factor).contiguous() + + +# CompositeImplicitAutograd - don't register decomp +@aten.stft.center.py_impl(DispatchKey.CompositeImplicitAutograd) +def stft( + input: Tensor, + n_fft: int, + hop_length: Optional[int] = None, + win_length: Optional[int] = None, + window: Optional[Tensor] = None, + center: bool = True, + pad_mode: str = "reflect", + normalized: bool = False, + onesided: Optional[bool] = None, + return_complex: Optional[bool] = None, +) -> Tensor: + torch._check( + window is None or window.device == input.device, + lambda: ( + f"stft input and window must be on the same device but got self on {input.device}" + + f" and window on {window.device}" # type: ignore[union-attr] + ), + ) + + hop_length_ = hop_length if hop_length is not None else n_fft // 4 + win_length_ = win_length if win_length is not None else n_fft + + if return_complex is None: + return_complex_ = input.is_complex() or ( + window is not None and utils.is_complex_dtype(window.dtype) + ) + torch._check( + return_complex_, + ( + "stft requires the return_complex parameter be given for real inputs, " + + "and will further require that return_complex=True in a future PyTorch release." + ), + ) + else: + return_complex_ = return_complex + + torch._check( + utils.is_float_dtype(input.dtype) or utils.is_complex_dtype(input.dtype), + lambda: "stft expected a tensor of floating point or complex values", + ) + torch._check(1 <= input.ndim <= 2, lambda: "stft expected a 1D or 2D tensor") + + original_ndim = input.ndim + if original_ndim == 1: + input = input.unsqueeze(0) + + if center: + extra_dims = 3 - input.ndim + pad_amount = n_fft // 2 + extended_shape = [*itertools.repeat(1, extra_dims), *input.shape] + input = aten.pad(input.view(extended_shape), [pad_amount, pad_amount], pad_mode) + input = input.view(input.size()[extra_dims:]) + + batch = input.size(0) + length = input.size(1) + torch._check( + 0 < n_fft <= length, + lambda: f"stft expected 0 < n_fft <= {length}, but got n_fft={n_fft}", + ) + torch._check( + hop_length_ > 0, + lambda: f"stft expected hop_length > 0 but got hop_length={hop_length_}", + ) + torch._check( + 0 < win_length_ <= n_fft, + lambda: f"stft expected 0 < win_length <= n_fft but got win_length={win_length_}", + ) + torch._check( + window is None or window.shape == (win_length_,), + lambda: ( + f"expected a 1D window tensor of size equal to win_length={win_length_}, " + + f"but got window with size {window.shape}" # type: ignore[union-attr] + ), + ) + + if win_length_ < n_fft: + if window is None: + window = torch.ones(win_length_, dtype=input.dtype, device=input.device) + left = (n_fft - win_length_) // 2 + window = aten.constant_pad_nd(window, [left, n_fft - win_length_ - left]) + + input = input.unfold(dimension=-1, size=n_fft, step=hop_length_) + if window is not None: + input = input * window + + complex_fft = utils.is_complex_dtype(input.dtype) + onesided = onesided if onesided is not None else not complex_fft + norm = "ortho" if normalized else None + if onesided: + torch._check( + not complex_fft, + lambda: "Cannot have onesided output if window or input is complex", + ) + out = torch.fft.rfft(input, dim=-1, norm=norm) + else: + out = torch.fft.fft(input, dim=-1, norm=norm) + + out.transpose_(1, 2) + + if original_ndim == 1: + out = out.squeeze_(0) + + return out if return_complex_ else torch.view_as_real(out) + + +# CompositeImplicitAutograd - don't register decomp +@aten.istft.default.py_impl(DispatchKey.CompositeImplicitAutograd) +def istft( + input: Tensor, + n_fft: int, + hop_length: Optional[int] = None, + win_length: Optional[int] = None, + window: Optional[Tensor] = None, + center: bool = True, + normalized: bool = False, + onesided: Optional[bool] = None, + length: Optional[int] = None, + return_complex=False, +) -> Tensor: + torch._check( + window is None or window.device == input.device, + lambda: ( + f"istft input and window must be on the same device but got self on {input.device}" + + f" and window on {window.device}" # type: ignore[union-attr] + ), + ) + + hop_length_ = hop_length if hop_length is not None else n_fft // 4 + win_length_ = win_length if win_length is not None else n_fft + + torch._check( + utils.is_complex_dtype(input.dtype), + lambda: ( + "istft input and window must be on the same device but got self on " + + f"{input.device} and window on {window.device}" # type: ignore[union-attr] + ), + ) + n_frames = input.size(-1) + fft_size = input.size(-2) + + expected_output_signal_len = n_fft + hop_length_ * (n_frames - 1) + torch._check(input.numel() > 0, lambda: "istft input tensor cannot be empty") + torch._check( + 2 <= input.ndim <= 3, + lambda: f"istft expected a tensor with 2 or 3 dimensions, but got {input.ndim}", + ) + onesided_ = onesided if onesided is not None else fft_size != n_fft + + if onesided_: + torch._check( + n_fft // 2 + 1 == fft_size, + lambda: ( + "istft expected the frequency dimension (3rd to the last) of the input tensor " + + "to match n_fft / 2 + 1 when onesided=True, but got {fft_size}" + ), + ) + else: + torch._check( + n_fft == fft_size, + lambda: ( + "istft expected the frequency dimension (3rd to the last) of the input tensor " + + "to match n_fft when onesided=False, but got {fft_size}", + ), + ) + + torch._check( + 0 < hop_length_ <= win_length_, + lambda: "istft expected 0 < hop_length <= win_length", + ) + torch._check( + 0 < win_length_ <= n_fft, lambda: "istft expected 0 < win_length <= n_fft" + ) + torch._check( + window is None or window.shape == (win_length_,), + lambda: "Invalid window shape. window has to be 1D and length of `win_length`", + ) + + if window is None: + real_dtype = utils.corresponding_real_dtype(input.dtype) + window_ = torch.ones(win_length_, dtype=real_dtype, device=input.device) + else: + window_ = window + + if win_length_ != n_fft: + left = (n_fft - win_length_) // 2 + window_ = aten.constant_pad_nd(window_, (left, n_fft - win_length_ - left), 0) + + original_ndim = input.ndim + if input.ndim == 2: + input = input.unsqueeze(0) + + input = input.transpose(1, 2) + norm = "ortho" if normalized else None + if return_complex: + torch._check( + not onesided_, + lambda: "cannot have onesided output if window or input is complex", + ) + input = torch.fft.ifft(input, dim=-1, norm=norm) + else: + torch._check( + window is None or not utils.is_complex_dtype(window.dtype), + lambda: "Complex windows are incompatible with return_complex=False", + ) + if not onesided_: + input = input.narrow(dim=-1, start=0, length=n_fft // 2 + 1) + input = torch.fft.irfft(input, dim=-1, norm=norm) + + assert input.size(2) == n_fft + + y_tmp = input * window_.view([1, 1, n_fft]) + y = aten.unfold_backward( + y_tmp, + input_sizes=(y_tmp.size(0), expected_output_signal_len), + dim=1, + size=n_fft, + step=hop_length_, + ) + window_envelop = aten.unfold_backward( + window_.pow(2).expand((1, n_frames, n_fft)), + input_sizes=(y_tmp.size(0), expected_output_signal_len), + dim=1, + size=n_fft, + step=hop_length_, + ) + + assert expected_output_signal_len == y.size(1) + assert expected_output_signal_len == window_envelop.size(1) + + start = n_fft // 2 if center else 0 + if length is not None: + end = start + length + elif center: + end = expected_output_signal_len - n_fft // 2 + else: + end = expected_output_signal_len + + length = max(0, end - start) + y = y.narrow(dim=1, start=start, length=length) + window_envelop = window_envelop.narrow(dim=1, start=start, length=length) + + window_envelop_lowest = window_envelop.abs().min().lt(1e-11) + torch._check( + not window_envelop_lowest.item(), + lambda: "window overlap add min less than 1e-11", + ) + + y = y / window_envelop + if original_ndim == 2: + y = y.squeeze(0) + + if end > expected_output_signal_len: + warnings.warn( + "The length of signal is shorter than the length parameter. Result is being " + + "padded with zeros in the tail. Please check your center and hop_length settings" + ) + y = aten.constant_pad_nd(y, (0, end - expected_output_signal_len), 0) + return y + + +# Get the new shape and stride after applying unfold to an input tensor +def _get_unfold_shape_stride( + a_shape: ShapeType, a_stride: StrideType, dimension: int, size: int, step: int +): + a_ndim = len(a_shape) + dim = utils.canonicalize_dim(a_ndim, dimension, wrap_scalar=True) + max_size = 1 if a_ndim == 0 else a_shape[dim] + last_stride = 1 if a_ndim == 0 else a_stride[dim] + + torch._check( + size <= max_size, + lambda: f"Maximum size for tensor at dimension {dim} is {max_size} but size is {size}", + ) + + torch._check( + step > 0, + lambda: f"Step is {step} but must be > 0", + ) + + shape = list(a_shape) + strides = list(a_stride) + shape.append(size) + strides.append(last_stride) + if dim < a_ndim: + shape[dim] = (shape[dim] - size) // step + 1 + strides[dim] *= step + return shape, strides + + +@register_decomposition(aten.repeat) +@out_wrapper() +def repeat(a: Tensor, *repeat_shape) -> Tensor: + repeat_shape = utils.extract_shape_from_varargs(repeat_shape, validate=False) + torch._check( + len(repeat_shape) >= len(a.shape), + lambda: "repeat: Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor", + ) + + if len(repeat_shape) == 0: + return torch.clone(a) + + num_new_dimensions = len(repeat_shape) - a.ndim + padded_shape = [1] * num_new_dimensions + for dim_size in a.shape: + padded_shape.append(dim_size) + + target_shape = tuple( + padded_size * repeat_size + for padded_size, repeat_size in zip(padded_shape, repeat_shape) + ) + + # return an empty tensor if one of the repeat_shape dimensions is zero + if 0 in repeat_shape: + return torch.empty( + target_shape, + dtype=a.dtype, + device=a.device, + requires_grad=a.requires_grad, + memory_format=utils.suggest_memory_format(a), + ) + + urtensor_shape = target_shape + urtensor_stride = utils.make_contiguous_strides_for(target_shape) + for dim, dim_size in enumerate(padded_shape): + # repeat each dimension by using unfold_copy operation + urtensor_shape, urtensor_stride = _get_unfold_shape_stride( + urtensor_shape, urtensor_stride, dim, dim_size, max(dim_size, 1) + ) + + # derive permute order by sorting urtensor strides + enumerated_stride = list(enumerate(urtensor_stride)) + enumerated_stride.sort(key=lambda item: item[1], reverse=True) + permute_order, sorted_stride = zip(*enumerated_stride) + + # add new and expand dimensions according to urtensor + repeat_xtensor = a.expand(urtensor_shape) + + # clone tensor to concretize expanded dimensions + cloned_result = torch.clone(repeat_xtensor) + + # transpose axis so strides are in sorted order + permuted_result = cloned_result.permute(permute_order) + + # reshape to get contiguous tensor with correct target shape + return permuted_result.reshape(target_shape) + + +def _reshape_view_helper(a: TensorLikeType, *shape, allow_copy: bool) -> TensorLikeType: + from torch.fx.experimental.symbolic_shapes import guard_size_oblivious, sym_eq + + # Creates a valid shape + shape = utils.extract_shape_from_varargs(shape, validate=False) + # Reshape may be given a shape with a -1 length + # This indicates that the dimension's length should be inferred + shape = utils.infer_size(shape, a.numel()) + + # Short-circuits if shape is the same + if guard_size_oblivious(sym_eq(tuple(a.shape), tuple(shape))): + return prims.view_of(a) + + # Special-cases tensors with no elements + if guard_size_oblivious(a.numel() == 0): + return as_strided(a, shape, utils.make_contiguous_strides_for(shape)) + + # Special-cases reshaping zero dim tensors + if a.ndim == 0: + _a = a + for length in shape: + assert length == 1 + _a = unsqueeze(_a, -1) + return _a + + # Special-cases reshaping to zero dim tensors + if len(shape) == 0: + _a = a + for length in a.shape: + assert length == 1 + _a = squeeze(_a, -1) + return _a + + # Handles general case: a 1+D tensor reshaped into a distinct 1+D shape + + # NOTE [Reshape Algorithm] + # This algorithm works by attempting to greedily construct the desired dimensions in + # the output shape, left to right. It does this by, conceptually, accumulating + # dimensions of the original tensor, also left to right, until the dimension + # can be constructed using prims.split_dim. + # The algorithm also has special handling for tail squeezes/unsqueezes, like + # if a reshape from (5, 5) to (5, 5, 1) or vice versa. + # + # This algorithm does not flatten the original tensor and then split dims as appropriate + # because that would create copies more often than this algorithm. flatten is the only + # operation below which can create a view or a copy, and while it prefers creating + # views it may sometimes create a copy if the tensor's strides do not permit a view. + # As a result, this algorithm tries to minimize flattening. + # + # Note that a better version of this algorithm may exist. Regions which could be + # flattened without creating a copy can be identified in advance, and that might + # allow fewer flatten calls or faster short-circuiting to make a copy. + idx = 0 + a_ = a + for length in shape: + # Handles tail unsqueezes + if idx >= a_.ndim: + assert length == 1 + last_dim = a_.ndim - 1 + # NOTE: using split_dim instead of unsqueeze may seem silly here, + # but it's necessary to get the strides correct + a_ = prims.split_dim(a_, last_dim, a_.shape[last_dim]) + idx = idx + 1 + continue + + # Skips dimensions that are already the correct length + if guard_size_oblivious(length == a_.shape[idx]): + idx = idx + 1 + continue + + # Gathers enough original dimensions such that this new dimension can be created + # Note that this accumulation will terminate because we've verified a and the shape + # specify the same number of elements above + accum = a_.shape[idx] + end = idx + while guard_size_oblivious(accum % length != 0): + end = end + 1 + accum = accum * a_.shape[end] + if end != idx: + # NOTE: in this case multiple dimensions must be flatten to create the desired dimension + # This flattening is why reshape sometimes creates a copy -- because flattening + # may return a view of a copy + + # Checks if collapse can be a view and short-circuits to copying reshape if it can't + new_shape, new_strides = prims._collapse_view_helper(a_, idx, end) + if new_shape is None: + if allow_copy: + return prims.reshape(a, shape) + + msg = "Cannot view a tensor with shape {} and strides {} as a tensor with shape {}!".format( + a.shape, a.stride(), shape + ) + raise ValueError(msg) + + a_ = flatten(a_, idx, end) + + # Splits the (possibly flattened) dimension to create the desired dim length + if guard_size_oblivious(accum != length): + a_ = prims.split_dim(a_, idx, length) + + idx = idx + 1 + + # Squeezes tail + while idx < a_.ndim: + assert a_.shape[idx] == 1 + a_ = squeeze(a_, idx) + + return a_ + + +# CompositeImplicitAutograd - don't register decomp +# NOTE: shape is a vararg because Tensor.reshape can be called with as +# Tensor.reshape(a, b, c) or Tensor.reshape((a, b, c)) Function call +# torch.reshape doesn't support unpacked shapes +def reshape(a: TensorLikeType, *shape: ShapeType) -> TensorLikeType: + return _reshape_view_helper(a, *shape, allow_copy=True) + + +# CompositeImplicitAutograd - don't register decomp +def reshape_as(self: TensorLikeType, other: TensorLikeType) -> TensorLikeType: + return self.reshape(other.size()) + + +@register_decomposition(aten.roll) +@out_wrapper() +def roll( + a: TensorLikeType, shifts: DimsType, dims: DimsType = tuple() +) -> TensorLikeType: + """Reference implementation of :func:`torch.roll`.""" + dims = utils.canonicalize_dims(a.ndim, dims) + # ATen specifies int[1] type for shifts and dims which expands integers to tuples of length 1 + if not isinstance(shifts, Iterable): + shifts = (shifts,) + if not isinstance(dims, Iterable): + dims = (dims,) + + # Avoid modulo by zero + if a.numel() == 0: + # Keeping this as ref for now as FakeTensor runs into some issues with complex tensors + return a.clone() + + if a.dim() == 0 and len(dims) > 0: + raise IndexError( + f"Dimension specified as {dims[0]} but tensor has no dimensions" + ) + + len_shifts = len(shifts) + len_dims = len(dims) + if len_shifts != 1 or len_dims != 1: + if len_shifts == 0: + raise RuntimeError("`shifts` required") + # Takes care of the case when dims is not specified (default) + # By default, the tensor is flattened before shifting, after which the original shape is restored + if len_dims == 0 and len_shifts == 1: + return torch.roll(torch.flatten(a), shifts, 0).view(a.shape) + if len_shifts != len_dims: + raise RuntimeError( + f"shifts and dimensions must align. shifts: {len_shifts}, dims: {len_dims}" + ) + assert len_dims > 1 + tail_shifts = shifts[1:] + tail_dims = dims[1:] + first_dim_rolled = torch.roll(a, (shifts[0],), dims[0]) + return torch.roll(first_dim_rolled, tail_shifts, tail_dims) + + # This path is taken when only one dimension is rolled + # For example to get `first_dim_rolled` above + dim = dims[0] + size = a.shape[dim] + start = (size - shifts[0]) % size + idx = torch.arange(size, device=a.device) + return a.index_select(dim, torch.fmod(start + idx, size)) + + +@register_decomposition(aten.rot90) +@out_wrapper() +def rot90( + a: TensorLikeType, k: int = 1, dims: DimsSequenceType = (0, 1) +) -> TensorLikeType: + """Reference implementation of :func:`torch.rot90`.""" + if len(dims) != 2: + raise RuntimeError( + f"expected total rotation dims == 2, but got dims = {len(dims)}" + ) + if a.ndim < 2: + raise RuntimeError(f"expected total dims >= 2, but got total dims = {a.ndim}") + + # Do this after the initial checks to be compatible with the behavior in + # core. + dims = utils.canonicalize_dims(a.ndim, dims) + + if dims[0] == dims[1]: + raise RuntimeError( + f"expected rotation dims to be different, but got dim0 = {dims[0]} and dim1 = {dims[1]}" + ) + k = k % 4 # Rotation direction is from the second towards the first axis for k < 0 + if k == 1: + return torch.transpose(torch.flip(a, (dims[1],)), dims[0], dims[1]) + elif k == 2: + return torch.flip(a, dims) + elif k == 3: + return torch.transpose(torch.flip(a, (dims[0],)), dims[0], dims[1]) + else: + return clone(a, memory_format=torch.contiguous_format) + + +def _check_stack_inputs(tensors: TensorSequenceType) -> None: + entry_shape = tensors[0].shape + for i in range(1, len(tensors)): + assert tensors[i].shape == entry_shape, ( + f"stack expects each tensor to be equal size, but got {entry_shape} at entry 0" + f"and {tensors[i].shape} at entry {i}" + ) + + +@register_decomposition(aten.stack) +@out_wrapper() +def stack(tensors: TensorSequenceType, dim: int = 0) -> TensorLikeType: + assert len(tensors) > 0, "stack expects a non-empty TensorList" + wrapped_dim = utils.canonicalize_dim(tensors[0].ndim + 1, dim) + # Refs need sparse support to check other condition + if wrapped_dim < tensors[0].ndim: # and not tensors[0].is_sparse: + _check_stack_inputs(tensors) + result_sizes = list(tensors[0].shape) + result_sizes.insert(wrapped_dim, len(tensors)) + out = torch.cat(tensors, wrapped_dim) + return out.view(result_sizes) + + # If dim == tensors[0].ndim, view cannot efficiently handle it + return torch.cat([t.unsqueeze(wrapped_dim) for t in tensors], dim) + + +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +def softmax( + a: TensorLikeType, + dim: int, + dtype: Optional[torch.dtype] = None, +) -> TensorLikeType: + result_dtype = dtype or a.dtype + computation_dtype = utils.get_computation_dtype(result_dtype) + a_ = _maybe_convert_to_dtype(a, computation_dtype) + if a.numel() == 0: + a_exp = exp(a_) + else: + a_max = amax(a_, dim, keepdim=True) + a_exp = exp(a_ - a_max) + return _maybe_convert_to_dtype( + true_divide(a_exp, sum(a_exp, dim, keepdim=True)), result_dtype + ) # type: ignore[return-value] + + +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +def hstack(tensors: TensorSequenceType) -> TensorLikeType: + torch._check(len(tensors) > 0, lambda: "hstack expects a non-empty TensorList") + aligned_tensors = atleast_1d(*tensors) + if aligned_tensors[0].ndim == 1: + return cat(aligned_tensors, 0) + return cat(aligned_tensors, 1) + + +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +def vstack(tensors: TensorSequenceType) -> TensorLikeType: + torch._check(len(tensors) > 0, lambda: "vstack expects a non-empty TensorList") + aligned_tensors = atleast_2d(*tensors) + return cat(aligned_tensors, 0) + + +# CompositeImplicitAutograd - don't register decomp +def unflatten(a: TensorLikeType, dim: int, sizes: ShapeType) -> TensorLikeType: + dim = utils.canonicalize_dim(a.ndim, dim) + torch._check(len(sizes) != 0, lambda: "unflatten: sizes must be non-empty") + return a.view(tuple(a.shape[:dim]) + tuple(sizes) + tuple(a.shape[dim + 1 :])) + + +@register_decomposition(aten.unbind) +def unbind(t: TensorLikeType, dim: int = 0) -> TensorSequenceType: + dim = utils.canonicalize_dim(t.ndim, dim) + torch._check_index( + len(t.shape) > 0, + lambda: "Dimension specified as 0 but tensor has no dimensions", + ) + if t.shape[dim] == 0: + return tuple() + else: + return tuple( + torch.squeeze(s, dim) for s in torch.tensor_split(t, t.shape[dim], dim) + ) + + +@out_wrapper() +def index_copy(x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike): + return x.clone(memory_format=torch.contiguous_format).index_copy_( + dim, index, tensor + ) + + +def index_copy_(x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike): + dim = utils.canonicalize_dims(x.ndim, dim) + torch._check( + index.ndim <= 1, + lambda: f"Index should have dimension 1 or 0 (got {index.ndim})", + ) + # Treat scalars as elements of \R^1 + y = x.unsqueeze(0) if x.ndim == 0 else x + idx = (slice(None),) * dim + (index,) + y[idx] = tensor + return x + + +@register_decomposition(aten.index_fill) +@out_wrapper() +def index_fill( + x: TensorLike, dim: int, index: TensorLike, value: Union[NumberType, TensorLike] +): + return _index_fill(x, dim, index, value, inplace=False) + + +@register_decomposition(aten.index_fill_) +def index_fill_( + x: TensorLike, dim: int, index: TensorLike, value: Union[NumberType, TensorLike] +): + return _index_fill(x, dim, index, value, inplace=True) + + +def _index_fill( + x: TensorLike, + dim: int, + index: TensorLike, + value: Union[NumberType, TensorLike], + *, + inplace: bool, +): + torch._check( + index.ndim <= 1, + lambda: f"Index should have dimension 1 or 0 (got {index.ndim})", + ) + if isinstance(value, TensorLike): + torch._check( + value.ndim == 0, + lambda: "Only supports 0-dimensional value tensor. " # type: ignore[union-attr] + f"Got a tensor with {value.ndim} dimensions.", + ) # type: ignore[arg-type] + else: + value = torch.scalar_tensor( + value, dtype=x.dtype, layout=x.layout, device=x.device # type: ignore[arg-type] + ) + + # index_copy has some unnecessary preconditions when x is a scalar. We do this to work through them + zero_dim = x.ndim == 0 + y = x.unsqueeze(0) if zero_dim else x + # index_copy does not broadcast on value so we have to do it manually + shape = list(y.shape) + shape[dim] = index.numel() + value = value.expand(shape) + index_copy = Tensor.index_copy_ if inplace else torch.index_copy + out = index_copy(y, dim, index, value) # type: ignore[operator] + if inplace: + return x + else: + if zero_dim: + # The clone is necessary so that it returns a fresh tensor rather than a view + out = out.squeeze(0).clone() + # index_fill preserves the strides. index_copy always returns contiguous tensors + if out.stride() != x.stride(): + new_out = torch.empty_like(x) + new_out.copy_(out) + out = new_out + return out + + +@out_wrapper() +def index_add( + x: TensorLike, + dim: int, + index: TensorLike, + tensor: TensorLike, + *, + alpha: NumberType = 1, +): + # index_add always returns a new contiguous tensor + return x.clone(memory_format=torch.contiguous_format).index_add_( + dim, index, tensor, alpha=alpha # type: ignore[arg-type] + ) + + +@register_decomposition(aten.index_select) +@out_wrapper() +def index_select(x: TensorLike, dim: int, index: TensorLike): + dim = utils.canonicalize_dims(x.ndim, dim) + torch._check( + index.ndim <= 1, + lambda: f"Index should have dimension 1 or 0 (got {index.ndim})", + ) + if index.ndim == 0: + index = index.unsqueeze(0) + if x.ndim == 0: + # Treat scalars as elements of \R^1 + # We cannot use x[idx] here as it accesses item() (??), hence this awkward construction + return torch.empty_like(x).index_copy(0, index, x.expand_as(index)) + + idx = (slice(None),) * dim + (index,) + return x[idx] + + +@register_decomposition(aten.squeeze.dims) +def squeeze(a: TensorLikeType, dim: Optional[DimsType] = None) -> TensorLikeType: + from torch.fx.experimental.symbolic_shapes import guard_size_oblivious + + if dim is None: + dims = tuple(idx for idx, size in enumerate(a.shape) if size == 1) + return prims.squeeze(a, dims) if dims else prims.view_of(a) + + ndim = a.ndim + dim = utils.canonicalize_dims(ndim, dim) + dims = (dim,) if isinstance(dim, Dim) else dim + # Short-circuits if the tensor has no dimensions + if ndim == 0: + assert len(dims) == 0 or dims == (0,) + return prims.view_of(a) + + # Note: squeeze does not modify tensors when the given dim is not a dimension of length 1 + dims = tuple(d for d in dims if guard_size_oblivious(a.shape[d] == 1)) + if len(dims) == 0: + return prims.view_of(a) + if len(dims) == 1: + return prims.squeeze(a, dims) + dims_list = list(dims) + dims_list = sorted(dims_list, reverse=True) + for i in dims_list: + a = squeeze(a, i) + return a + + +# Note: does not work with TensorMetas because of data-dependent control-flow +# CompositeImplicitAutograd - don't register decomp +def tensor_split( + a: TensorLikeType, + indices_or_sections: Union[Tensor, DimsType], + dim: int = 0, +) -> Tuple[TensorLikeType, ...]: + _dim = utils.canonicalize_dim(a.ndim, dim) + if a.ndim == 0: + msg = "tensor_split: received a rank zero tensor, but expected a tensor of rank one or greater!" + raise ValueError(msg) + + # If indices_or_sections is a tensor, it must be a CPU Long tensor + if isinstance(indices_or_sections, TensorLike): + if not indices_or_sections.device.type == "cpu": + msg = "tensor_split: if indices_or_sections is a tensor it must be on the CPU, but received one on {}".format( + indices_or_sections.device + ) + raise ValueError(msg) + if indices_or_sections.dtype != torch.long: + msg = "tensor_split: if indices_or_sections is a tensor it must have long dtype, " + f" but received one with dtype {indices_or_sections.dtype}" + raise ValueError(msg) + + # Case 0 -- indices_or_sections is an integer or a scalar tensor n and a is split along dim into n parts of equal-ish length + if isinstance(indices_or_sections, IntLike) or ( + isinstance(indices_or_sections, TensorLike) and indices_or_sections.ndim == 0 + ): + sections: int = ( + indices_or_sections # type: ignore[assignment] + if isinstance(indices_or_sections, Number) + else indices_or_sections.item() + ) + + if sections <= 0: + msg = f"tensor_split: number of sections must be greater than 0, but was {sections}" + raise ValueError(msg) + + splits = [] + dim_size = a.shape[_dim] + min_split_size = math.floor(dim_size / sections) + num_splits_one_extra = dim_size % sections + start_idx = 0 + for split_idx in range(sections): + split_size = ( + min_split_size + 1 + if (split_idx < num_splits_one_extra) + else min_split_size + ) + s = prims.slice_in_dim(a, start_idx, start_idx + split_size, axis=_dim) + splits.append(s) + start_idx = start_idx + split_size + + return tuple(splits) + # Case 1 -- indices_or_sections is a sequence of integers or a 1D tensor describing the splits + else: + indices = indices_or_sections + if isinstance(indices_or_sections, TensorLike): + if indices_or_sections.ndim != 1: + msg = "tensor_split: non-scalar indices_or_sections tensors must have only one dimension, " + f"but received a tensor with {indices_or_sections.ndim} dimensions" + raise ValueError(msg) + + indices = indices_or_sections.tolist() + + splits = [] + start_idx = 0 + for x in indices: + splits.append(prims.slice_in_dim(a, start_idx, x, axis=_dim)) + start_idx = x + splits.append(prims.slice_in_dim(a, start_idx, a.shape[_dim], axis=_dim)) + return tuple(splits) + + +# CompositeImplicitAutograd - don't register decomp +def hsplit( + a: TensorLikeType, indices_or_sections: DimsType +) -> Tuple[TensorLikeType, ...]: + torch._check( + a.ndim >= 1, + lambda: ( + "torch.hsplit requires a tensor with at least 1 dimension, but got a tensor with " + + str(a.ndim) + + " dimensions!" + ), + ) + dim = 0 if a.ndim == 1 else 1 + if isinstance(indices_or_sections, IntLike): + split_size = indices_or_sections + torch._check( + (split_size != 0 and a.shape[dim] % split_size == 0), + lambda: ( + "torch.hsplit attempted to split along dimension " + + str(dim) + + ", but the size of the dimension " + + str(a.shape[dim]) + + " is not divisible by the split_size " + + str(split_size) + + "!" + ), + ) + return tensor_split(a, split_size, dim) + + torch._check_type( + isinstance(indices_or_sections, (list, tuple)), + lambda: ( + "hsplit(): received an invalid combination of arguments. " + "Expected indices_or_sections to be of type int, list of ints or tuple of ints " + f"but got type {type(indices_or_sections)}" + ), + ) + + split_sizes = indices_or_sections + return tensor_split(a, split_sizes, dim) + + +# CompositeImplicitAutograd - don't register decomp +def vsplit( + a: TensorLikeType, indices_or_sections: DimsType +) -> Tuple[TensorLikeType, ...]: + torch._check( + a.ndim >= 2, + lambda: ( + "torch.vsplit requires a tensor with at least 2 dimension, but got a tensor with " + + str(a.ndim) + + " dimensions!" + ), + ) + if isinstance(indices_or_sections, IntLike): + split_size = indices_or_sections + torch._check( + (split_size != 0 and a.shape[0] % split_size == 0), + lambda: ( + f"torch.vsplit attempted to split along dimension 0" + f", but the size of the dimension " + f"{a.shape[0]}" + f" is not divisible by the split_size " + f"{split_size}" + f"!" + ), + ) + return tensor_split(a, split_size, 0) + + torch._check_type( + isinstance(indices_or_sections, (list, tuple)), + lambda: ( + "vsplit(): received an invalid combination of arguments. " + "Expected indices_or_sections to be of type int, list of ints or tuple of ints " + f"but got type {type(indices_or_sections)}" + ), + ) + + split_sizes = indices_or_sections + return tensor_split(a, split_sizes, 0) + + +@register_decomposition(aten.diag.out) +@out_wrapper() +def diag( + self: TensorLikeType, + offset: int = 0, +) -> TensorLikeType: + ndim = self.dim() + torch._check( + ndim in (1, 2), lambda: f"diag(): Supports 1D or 2D tensors. Got {ndim}D" + ) + if ndim == 1: + return torch.diag_embed(self, offset) + else: + return torch.diagonal_copy(self, offset) + + +@register_decomposition(aten.diagonal_scatter) +@out_wrapper() +def diagonal_scatter( + input: TensorLikeType, + src: TensorLikeType, + offset: int = 0, + dim1: int = 0, + dim2: int = 1, +) -> TensorLikeType: + out = utils.clone_preserve_strides(input) + diag = out.diagonal(offset, dim1, dim2) + torch._check( + diag.shape == src.shape, + lambda: "expected src to have a size equal to the diagonal of the input." + f"Got {src.shape} for a diagonal of shape {diag.shape}", + ) + copy_to(diag, src) + return out + + +@register_decomposition(aten.diagonal) +def diagonal( + self: TensorLikeType, + offset: int = 0, + dim1: int = 0, + dim2: int = 1, +) -> TensorLikeType: + """ + Reference implementation of torch.diagonal + """ + num_dims = self.dim() + dim1 = utils.canonicalize_dim(idx=dim1, rank=num_dims) + dim2 = utils.canonicalize_dim(idx=dim2, rank=num_dims) + + torch._check( + dim1 != dim2, lambda: f"diagonal dimensions cannot be identical {dim1}, {dim2}" + ) + + storage_offset = self.storage_offset() + + if offset >= 0: + diag_size = max(min(self.size()[dim1], self.size()[dim2] - offset), 0) + else: + diag_size = max(min(self.size()[dim1] + offset, self.size()[dim2]), 0) + + if diag_size > 0: + if offset >= 0: + storage_offset += offset * self.stride()[dim2] + else: + storage_offset -= offset * self.stride()[dim1] + + sizes = [s for i, s in enumerate(self.size()) if i not in (dim1, dim2)] + sizes.append(diag_size) + + strides = [s for i, s in enumerate(self.stride()) if i not in (dim1, dim2)] + strides.append(self.stride()[dim1] + self.stride()[dim2]) + + result = self.as_strided(size=sizes, stride=strides, storage_offset=storage_offset) + + return result + + +diagonal_copy = _make_copy_from_view(diagonal) + + +@register_decomposition(aten.diag_embed) +@out_wrapper() +def diag_embed( + t: TensorLikeType, + offset: int = 0, + dim1: int = -2, + dim2: int = -1, +) -> TensorLikeType: + """ + Reference implementation of torch.diag_embed + """ + # convert from negative dims + rank = t.ndim + 1 + dim1 = utils.canonicalize_dim(rank=rank, idx=dim1) + dim2 = utils.canonicalize_dim(rank=rank, idx=dim2) + + # as per the docs, exchanging dims is equivalent to changing the sign of + # offset + if dim1 > dim2: + dim1, dim2 = dim2, dim1 + offset = -offset + + torch._check( + dim1 != dim2, lambda: f"diagonal dimensions cannot be identical {dim1}, {dim2}" + ) + + # as per the docs, the size of last dim is placed at dim1 and dim2 + last_dim = t.size(-1) + + if offset != 0: + # add padding to match the new size + t_shape = list(t.shape) + t_shape[-1] = builtins.abs(offset) + z = torch.zeros(t_shape, dtype=t.dtype, device=t.device, requires_grad=False) + pair = (z, t) if offset > 0 else (t, z) + t = torch.cat(pair, dim=-1) + # make sure the diagonal always has the same size + last_dim += builtins.abs(offset) + + # preserve original data, but place 1 at dim1 and move last dim to dim2 + t = t.unsqueeze(dim1).movedim(-1, dim2) + + # generate ranges shifting indices based on offset + a_range = torch.arange(last_dim, device=t.device, dtype=torch.int64) + b_range = torch.arange( + offset, last_dim + offset, device=t.device, dtype=torch.int64 + ) + + # broadcast + cond = a_range == b_range.unsqueeze(-1) + cond_shape = [last_dim if i in (dim1, dim2) else 1 for i in range(len(t.shape))] + cond = cond.reshape(cond_shape) + + # aten.diag_embed always returns a new contiguous tensor + # contiguous() is needed to correctly model the output stride + return utils.mask_tensor(cond, t).contiguous() + + +@register_decomposition(aten.block_diag) +@out_wrapper() +def _block_diag_iterable(tensors: List[TensorLikeType]) -> TensorLikeType: + """ + Reference implementation of torch.block_diag + """ + tensors_2d = [ + tensor.view(1, -1) if tensor.dim() <= 1 else tensor for tensor in tensors + ] + + ncols = builtins.sum(tensor.shape[1] for tensor in tensors_2d) + device = tensors_2d[0].device + + result = [] + + col_start = 0 + for i, tensor in enumerate(tensors_2d): + torch._check( + tensor.dim() == 2, + lambda: "Input tensors must have 2 or fewer dimensions. " + f"Input {i} has {tensor.dim()} dimensions", + ) + torch._check( + tensor.device == device, + lambda: "Input tensors must all be on the same device. " + f"Input 0 is on device {device} and input {i} is on device {tensor.device}.", + ) + row, col = tensor.shape + left = torch.zeros((row, col_start), device=device, dtype=tensor.dtype) + right = torch.zeros( + (row, ncols - col_start - col), device=device, dtype=tensor.dtype + ) + result += [torch.cat((left, tensor, right), dim=1)] + col_start += col + + return torch.cat(result, dim=0) + + +def block_diag(*tensors: List[TensorLikeType]) -> TensorLikeType: + """ + This is used as an input to PythonRefInfo. `torch.block_diag` + expects arguments splatted, but `aten.block_diag` expects only + one argument that is a list of Tensors. + """ + return _block_diag_iterable(tensors) + + +# CompositeImplicitAutograd - don't register decomp +def dsplit(a: TensorLikeType, sections: DimsType) -> TensorSequenceType: + if a.ndim < 3: + raise RuntimeError( + f"torch.dsplit requires a tensor with at least 3 dimension, but got a tensor with {a.ndim} dimensions!" + ) + if isinstance(sections, IntLike) and (sections == 0 or a.shape[2] % sections != 0): + raise RuntimeError( + "torch.dsplit attempted to split along dimension 2, " + + f"but the size of the dimension {a.shape[2]} is not divisible by the split_size {sections}!" + ) + return tensor_split(a, sections, 2) + + +@register_decomposition(aten.t.default) +def t(a: TensorLikeType): + # TODO: Add sparse support + # if a.is_sparse: + # sparse_dim = a.sparse_dim() + # dense_dim = a.dense_dim() + # if not (sparse_dim <= 2 and dense_dim == 0): + # raise RuntimeError( + # f"t() expects a tensor with <= 2 sparse and 0 dense dimensions, but got {sparse_dim} sparse and" + # f"{dense_dim} dense dimensions" + # ) + if a.ndim > 2: + raise RuntimeError( + f"t() expects a tensor with <= 2 dimensions, but self is {a.ndim}D" + ) + return torch.transpose(a, 0, 0 if a.ndim < 2 else 1) + + +# CompositeImplicitAutograd - don't register decomp +def T(a: TensorLikeType) -> TensorLikeType: + # n != 2 && n != 0 is deprecated in regular PyTorch. + torch._check( + a.ndim in (0, 2), + lambda: ( + "The use of `x.T` on tensors of dimension other than 0 or 2 " + "to reverse their shape is not supported." + ), + ) + return a.t() + + +@register_decomposition(aten.alias) +def alias(a: TensorLikeType) -> TensorLikeType: + return prims.view_of(a) + + +@register_decomposition(aten.transpose) +def transpose(a: TensorLikeType, dim0: int, dim1: int) -> TensorLikeType: + _dim0, _dim1 = utils.canonicalize_dims(a.ndim, (dim0, dim1)) # type: ignore[misc] + + if a.ndim <= 1 or dim0 == dim1: + return aten.alias.default(a) + + _permutation = list(range(0, a.ndim)) + _permutation[_dim0] = _dim1 + _permutation[_dim1] = _dim0 + return torch.permute(a, _permutation) + + +# Aliases for transpose +swap_axes = transpose + + +@register_decomposition(aten.unfold) +def unfold( + self: TensorLikeType, dimension: int, size: int, step: int +) -> TensorLikeType: + shape, strides = _get_unfold_shape_stride( + self.shape, self.stride(), dimension, size, step + ) + return self.as_strided(shape, strides) + + +@register_decomposition(aten.unfold_copy) +@out_wrapper() +def unfold_copy(self: TensorLikeType, dimension: int, size: int, step: int): + return self.unfold(dimension, size, step).clone( + memory_format=torch.contiguous_format + ) + + +def _cumsumprod_common( + func, + init, + a: TensorLikeType, + dim: int, + *, + dtype: Optional[torch.dtype] = None, + out: Optional[Tensor] = None, +) -> TensorLikeType: + # We implement all the kwargs of a reduction. ATen just handles dtype + # nb. This decomposition may not be as efficient as a backend-specific implementation + ndim = a.ndim + dim = utils.canonicalize_dim(ndim, dim) + if ndim == 0: + return func(a.unsqueeze(0), dim=0, dtype=dtype, out=out) + a = a.unsqueeze(dim + 1) + rg = torch.arange(a.shape[dim], device=a.device) + mask = rg.unsqueeze(1) <= rg + for _ in range(ndim - dim - 1): + mask = mask.unsqueeze(-1) + masked_a = torch.where(mask, a, init) + return func(masked_a, dim=dim, dtype=dtype, out=out) + + +@register_decomposition(aten.cumsum) +def cumsum( + a: TensorLikeType, + dim: int, + *, + dtype: Optional[torch.dtype] = None, + out: Optional[Tensor] = None, +) -> TensorLikeType: + return _cumsumprod_common(func=sum, init=0, a=a, dim=dim, dtype=dtype, out=out) + + +@register_decomposition(aten.cumprod) +def cumprod( + a: TensorLikeType, + dim: int, + *, + dtype: Optional[torch.dtype] = None, + out: Optional[Tensor] = None, +) -> TensorLikeType: + return _cumsumprod_common(func=prod, init=1, a=a, dim=dim, dtype=dtype, out=out) + + +# Note: although squeeze is documented as having the out= kwarg it doesn't +@register_decomposition(aten.unsqueeze) +def unsqueeze(a: TensorLikeType, dim: int) -> TensorLikeType: + # Note that unsqueeze canonicalizes with rank + 1 because it allows + # a new innermost dimension to be specified + ndim = a.ndim + 1 + dim = utils.canonicalize_dim(ndim, dim) + return prims.expand_dims(a, (dim,), ndim=ndim) + + +# NOTE: shape is a vararg because Tensor.reshape can be called with as +# Tensor.view(a, b, c) or Tensor.view((a, b, c)) Function call torch.view +# doesn't support unpacked shapes +# TODO: Turn this into a decomposition (currently fails on reshape meta tests) +@register_decomposition(aten.view.default) +def view(a: TensorLikeType, *shape: ShapeType) -> TensorLikeType: + return _reshape_view_helper(a, *shape, allow_copy=False) + + +# CompositeImplicitAutograd - don't register decomp +def view_as(self: TensorLikeType, other: TensorLikeType) -> TensorLikeType: + return self.view(other.size()) + + +# CompositeImplicitAutograd - don't register decomp +def ravel(a: TensorLikeType) -> TensorLikeType: + return reshape(a, (-1,)) + + +# CompositeImplicitAutograd - don't register decomp +# missing ref impl. for aten.gather +@out_wrapper() +def take_along_dim( + a: torch.Tensor, indices: torch.Tensor, dim: Optional[int] = None +) -> torch.Tensor: + torch._check( + a.ndim == indices.ndim, + lambda: ( + "torch.take_along_dim(): input and indices should have the same " + f"number of dimensions, but got {a.ndim} dimensions for input, and " + f"{indices.ndim} dimensions for indices" + ), + ) + + torch._check( + utils.is_integer_dtype(indices.dtype), + lambda: ( + "torch.take_along_dim(): dtype of indices should be int but got " + f"{indices.dtype} instead" + ), + ) + + if dim is None: + return torch.gather(a.view(-1), 0, indices.view(-1)) + else: + self_sizes = list(a.shape) + self_sizes[dim] = indices.size(dim) + broadcast_shape = utils.infer_size_shapes(self_sizes, indices.size()) + indices_broadcast = broadcast_to(indices, broadcast_shape) + + indices_sizes = list(indices.shape) + indices_sizes[dim] = a.size(dim) + broadcast_shape = utils.infer_size_shapes(indices_sizes, a.size()) + self_broadcast = broadcast_to(a, broadcast_shape) + + return torch.gather(self_broadcast, dim, indices_broadcast) + + +@out_wrapper() +def empty( + *shape, + dtype: Optional[torch.dtype] = None, + layout: torch.layout = torch.strided, + device: Optional[DeviceLikeType] = None, + requires_grad: bool = False, + pin_memory: bool = False, + memory_format: torch.memory_format = torch.contiguous_format, +) -> TensorLikeType: + torch._check( + memory_format != torch.preserve_format, + lambda: "torch.empty: the Preserve memory format is not supported", + ) + + shape = utils.extract_shape_from_varargs(shape) + + if memory_format == torch.contiguous_format: + strides = utils.make_contiguous_strides_for(shape) + elif memory_format == torch.channels_last_3d: + strides = utils.make_channels_last_3d_strides_for(shape) + else: # memory_format == torch.channels_last + torch._check( + memory_format == torch.channels_last, + lambda: f"torch.empty: received an unknown memory format {memory_format}!", + ) + strides = utils.make_channels_last_2d_strides_for(shape) + + return torch.empty_strided( + shape, + strides, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@out_wrapper() +def empty_permuted( + shape, + physical_layout, + dtype: Optional[torch.dtype] = None, + layout: torch.layout = torch.strided, + device: Optional[DeviceLikeType] = None, + requires_grad: bool = False, + pin_memory: bool = False, +) -> TensorLikeType: + return prims.empty_permuted( + shape, + physical_layout, + dtype=dtype, + device=device, + requires_grad=requires_grad, + ) + + +@register_decomposition(aten.new_empty) +@out_wrapper() +def new_empty( + a: TensorLikeType, + size: ShapeType, + *, + dtype: Optional[torch.dtype] = None, + layout: Optional[torch.layout] = None, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, +) -> TensorLikeType: + dtype = a.dtype if dtype is None else dtype + layout = a.layout if layout is None else layout + device = a.device if device is None else device + + return torch.empty( + size, + dtype=dtype, + device=device, + pin_memory=pin_memory, + layout=layout, + ) + + +@register_decomposition(aten.new_empty_strided) +@out_wrapper() +def new_empty_strided( + a: TensorLikeType, + size: ShapeType, + stride: StrideType, + *, + dtype: Optional[torch.dtype] = None, + layout: Optional[torch.layout] = None, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, +) -> TensorLikeType: + """ + Reference implementation of torch.Tensor.new_empty_strided + """ + + dtype = a.dtype if dtype is None else dtype + layout = a.layout if layout is None else layout + device = a.device if device is None else device + + return torch.empty_strided( + size, + stride, + dtype=dtype, + device=device, + pin_memory=pin_memory, + layout=layout, + ) + + +@register_decomposition(aten.zeros.default) +@out_wrapper() +def zeros( + *size, + dtype: Optional[torch.dtype] = None, + layout: torch.layout = torch.strided, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + size = utils.extract_shape_from_varargs(size) + + if dtype is None: + dtype = torch.get_default_dtype() + + return torch.full( + size, + False if dtype == torch.bool else 0, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@register_decomposition(aten.new_zeros) +@out_wrapper() +def new_zeros( + a: TensorLikeType, + size: ShapeType, + *, + dtype: Optional[torch.dtype] = None, + layout: Optional[torch.layout] = None, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + dtype = a.dtype if dtype is None else dtype + layout = a.layout if layout is None else layout + device = a.device if device is None else device + + return torch.full( + size, + False if (dtype or a.dtype) == torch.bool else 0, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@register_decomposition(aten.ones.default) +@out_wrapper() +def ones( + *size, + dtype: Optional[torch.dtype] = None, + layout: torch.layout = torch.strided, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + size = utils.extract_shape_from_varargs(size) + + if dtype is None: + dtype = torch.get_default_dtype() + + return torch.full( + size, + True if dtype == torch.bool else 1, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@register_decomposition(aten.new_ones) +@out_wrapper() +def new_ones( + a: TensorLikeType, + size: ShapeType, + *, + dtype: Optional[torch.dtype] = None, + layout: Optional[torch.layout] = None, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + dtype = a.dtype if dtype is None else dtype + layout = a.layout if layout is None else layout + device = a.device if device is None else device + + return torch.full( + size, + True if (dtype or a.dtype) == torch.bool else 1, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@register_decomposition(aten.new_full) +@out_wrapper() +def new_full( + a: TensorLikeType, + size: ShapeType, + fill_value: NumberType, + *, + dtype: Optional[torch.dtype] = None, + layout: Optional[torch.layout] = None, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, +) -> TensorLikeType: + dtype = a.dtype if dtype is None else dtype + layout = a.layout if layout is None else layout + device = a.device if device is None else device + + return torch.full( + size, + fill_value, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + ) + + +@register_decomposition(aten.empty_like) +@out_wrapper() +def empty_like( + a: TensorLikeType, + *, + dtype: Optional[torch.dtype] = None, + device: Optional[DeviceLikeType] = None, + layout: Optional[torch.layout] = None, + pin_memory: bool = False, + requires_grad: bool = False, + memory_format: torch.memory_format = torch.preserve_format, +) -> TensorLikeType: + dtype = a.dtype if dtype is None else dtype + layout = a.layout if layout is None else layout + device = a.device if device is None else device + + if memory_format != torch.preserve_format: + return torch.empty( + a.shape, + dtype=dtype, + layout=layout, + device=device, + requires_grad=requires_grad, + pin_memory=pin_memory, + memory_format=memory_format, + ) + + # memory_format == torch.preserve_format + logical_to_physical_perm = ( + utils.compute_elementwise_output_logical_to_physical_perm(a) + ) + # identity perm is [2, 1, 0] + return torch.empty_permuted( + a.shape, + logical_to_physical_perm, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@register_decomposition([aten.arange.start_step, aten.arange.start_out]) +@out_wrapper() +def arange( + start: NumberType = 0, + end: Optional[NumberType] = None, + step: NumberType = 1, + *, + dtype: Optional[torch.dtype] = None, + layout: torch.layout = torch.strided, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + utils.check_layout(layout) + utils.check_pin_memory(pin_memory) + device = torch.device(utils.device_or_default(device)) + + assert not isinstance(start, complex) + assert not isinstance(end, complex) + assert not isinstance(step, complex) + + # Case: torch.arange(5) + if end is None: + end = start + start = 0 + torch._check(step != 0, lambda: "step must be nonzero") + if step > 0: + torch._check( + end >= start, + lambda: "upper bound and lower bound inconsistent with step sign", + ) + elif step < 0: + torch._check( + end <= start, + lambda: "upper bound and lower bound inconsistent with step sign", + ) + + def is_finite(x): + return not isinstance(x, FloatWithoutSymFloat) or math.isfinite(x) + + torch._check( + is_finite(start) and is_finite(end), + lambda: f"unsupported range: {start} -> {end}", + ) + torch._check( + is_finite(step), + lambda: f"step must be finite but got {step}", + ) + + if dtype is None: + args = (start, end, step) + integer_args = builtins.all(isinstance(arg, IntLike) for arg in args) + dtype = torch.int64 if integer_args else torch.get_default_dtype() + + is_integer = utils.is_integer_dtype(dtype) + if is_integer: + xstart = sym_int(start) + xend = sym_int(end) + xstep = sym_int(step) + + # For int64 we truncate arguments to int before calculating length, but + # other integral dtypes we don't. Weird... but needed to match ATen shapes. + if dtype == torch.int64: + # Uses floordiv to avoid ceil in inductor. + sgn = bool(xstep > 0) - bool(xstep < 0) # type: ignore[possibly-undefined] + length = (xend - xstart + xstep - sgn) // xstep # type: ignore[possibly-undefined] + else: + length = math.ceil((end - start) / step) + + if is_integer: + return prims.iota( + length, + start=xstart, # type: ignore[possibly-undefined] + step=xstep, # type: ignore[possibly-undefined] + dtype=dtype, + device=device, + requires_grad=requires_grad, + ) + + computation_dtype = utils.get_acc_type(dtype, device) + index = prims.iota( + length, + start=0, + step=1, + dtype=torch.int64, + device=device, + requires_grad=False, + ) + index = _maybe_convert_to_dtype(index, computation_dtype) + result = start + step * index + result = _maybe_convert_to_dtype(result, dtype) + + if requires_grad: + result.requires_grad_(True) + return result + + +@register_decomposition(aten.lerp) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("start", "end", "weight"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def lerp(start: Tensor, end: Tensor, weight: Union[Tensor, NumberType]): + inputs = [start, end] + if isinstance(weight, Number): + weight = start.new_full((), weight) # type: ignore[arg-type] + else: + inputs.append(weight) + assert isinstance(weight, Tensor) # mypy + # We implement it this way for numerical stability. We assume (in the stability optimisation) + # that 0 <= weight <= 1. We take the abs to deal with complex numbers + # We want to perform operations near zero, which is where floating points are most precise + # thus, we perform the following optimisation: + # If weight.abs() >= 0.5: + # return (1 - weight) * (start - end) + end + mask = weight.abs() >= 0.5 + coeff = torch.where(mask, weight - 1, weight) + base = torch.where(mask, end, start) + output = coeff * (end - start) + base + # make sure the decomposition output's stride is same as non-decomposition path. + stride = utils.compute_elementwise_output_strides(*_maybe_broadcast(*inputs)) + if output.stride() != stride: + output = prims.copy_strided(output, stride) + + return handle_noncontiguous_outputs(inputs, output) + + +@register_decomposition(aten.linspace) +@out_wrapper() +def linspace( + start: Union[NumberType, TensorLikeType], + end: Union[NumberType, TensorLikeType], + steps: NumberType, + *, + dtype: Optional[torch.dtype] = None, + device: Optional[DeviceLikeType] = None, + layout: torch.layout = torch.strided, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + if isinstance(start, TensorLikeType): + torch._check( + start.dim() == 0, + lambda: "linspace only supports 0-dimensional start and end tensors", + ) + start = _maybe_convert_to_dtype(start, torch.float64) + if isinstance(end, TensorLikeType): + torch._check( + end.dim() == 0, + lambda: "linspace only supports 0-dimensional start and end tensors", + ) + end = _maybe_convert_to_dtype(end, torch.float64) + + if py_any(isinstance(arg, complex) for arg in (start, end, steps)): + default_complex_dtype = utils.corresponding_complex_dtype( + torch.get_default_dtype() + ) + if dtype is None: + dtype = default_complex_dtype + else: + torch._check( + utils.is_complex_dtype(dtype), + lambda: f"linspace(): inferred dtype {default_complex_dtype} can't be safely cast to passed dtype {dtype}", + ) + else: + dtype = dtype or torch.get_default_dtype() + assert isinstance(dtype, torch.dtype) + + # steps does not participate in the computation of the dtype + torch._check_type( + isinstance(steps, IntLike), + lambda: f"received an invalid combination of arguments - got \ +({type(start).__name__}, {type(end).__name__}, {type(steps).__name__})", + ) + assert isinstance(steps, IntLike) # for mypy + torch._check(steps >= 0, lambda: "number of steps must be non-negative") + + factory_kwargs = { + "layout": layout, + "device": device, + "pin_memory": pin_memory, + "requires_grad": requires_grad, + } + if steps == 0: + return torch.full((0,), 0, dtype=dtype, **factory_kwargs) # type: ignore[arg-type] + if steps == 1: + if isinstance(start, TensorLikeType): + return torch.empty((steps,), dtype=dtype, **factory_kwargs).copy_(start) # type: ignore[arg-type] + else: + return torch.full((steps,), start, dtype=dtype, **factory_kwargs) # type: ignore[arg-type] + + # Perform in arange in int because some backends like ATen or Triton do not support all the dtypes + rg = torch.arange(0, steps, **factory_kwargs) # type: ignore[arg-type] + + # Small types need to be computed in higher precision as this is, at heart, an associative scan + dtype_red = ( + torch.int64 + if (utils.is_boolean_dtype(dtype) or utils.is_integer_dtype(dtype)) + else dtype + ) + computation_dtype, _ = utils.reduction_dtypes( + rg, REDUCTION_OUTPUT_TYPE_KIND.SAME, dtype_red + ) + cast_rg = partial(_maybe_convert_to_dtype, dtype=computation_dtype) + + # We implement torch.lerp without performing rg / (steps - 1) explicitly + # With this we get out[0] == start, out[-1] == end + step = (end - start) / (steps - 1) + out = torch.where( + rg < steps / 2, + start + step * cast_rg(rg), # type: ignore[arg-type,operator] + end - step * cast_rg((steps - 1) - rg), # type: ignore[arg-type,operator] + ) + return _maybe_convert_to_dtype(out, dtype) # type: ignore[return-value] + + +@register_decomposition(aten.logspace) +@out_wrapper() +def logspace( + start: Union[NumberType, TensorLikeType], + end: Union[NumberType, TensorLikeType], + steps: NumberType, + base: NumberType = 10, + *, + dtype: Optional[torch.dtype] = None, + device: Optional[DeviceLikeType] = None, + layout: torch.layout = torch.strided, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + if dtype is None: + dtype = torch.get_default_dtype() + + # NB: NumPy doesn't have this cast + if prims.utils.is_integer_dtype(dtype): + if isinstance(start, FloatLike): + start = sym_int(start) + elif isinstance(start, TensorLikeType): + torch._check( + start.dim() == 0, + lambda: "logspace only supports 0-dimensional start and end tensors", + ) + start = _maybe_convert_to_dtype(start, dtype) + if isinstance(end, FloatLike): + end = sym_int(end) + elif isinstance(end, TensorLikeType): + torch._check( + end.dim() == 0, + lambda: "logspace only supports 0-dimensional start and end tensors", + ) + end = _maybe_convert_to_dtype(end, dtype) + + if py_any(isinstance(arg, complex) for arg in (start, end, steps)): + default_complex_dtype = utils.corresponding_complex_dtype( + torch.get_default_dtype() + ) + dtype = default_complex_dtype + _dtype = None # torch.linspace will update the correct dtype + else: + _dtype = torch.float64 + + assert not isinstance(base, complex) # for mypy + if base < 0: + raise NotImplementedError + ret = torch.linspace( # type: ignore[misc] + start, # type: ignore[arg-type] + end, # type: ignore[arg-type] + steps, # type: ignore[arg-type] + dtype=_dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + return _maybe_convert_to_dtype(torch.pow(base, ret), dtype) # type: ignore[arg-type,return-value] + + +@overload +def meshgrid(tensors: Sequence[TensorLikeType], indexing: str): + pass + + +@overload +def meshgrid(*tensors: TensorLikeType, indexing: str): + pass + + +@register_decomposition(aten.meshgrid) +def meshgrid( + *tensors: Union[TensorLikeType, List[TensorLikeType], Tuple[TensorLikeType]], + indexing: str, +) -> List[TensorLikeType]: + # This ref simultaneously handles two overloads (see stubs above) + # The `indexing` argument is currently optional for torch.meshgrid, but we + # plan to make the argument required: https://github.com/pytorch/pytorch/issues/50276 + if isinstance(tensors[0], (list, tuple)): + assert len(tensors) == 1 + tensors = tuple(tensors[0]) + + torch._check( + py_all(isinstance(a, TensorLike) for a in tensors), + lambda: "meshgrid expects its inputs to be tensors", + ) + + torch._check(len(tensors) > 0, lambda: "meshgrid expects a non-empty TensorList") + + for i in range(len(tensors) - 1): + torch._check( + tensors[i].dtype == tensors[i + 1].dtype, # type: ignore[union-attr] + lambda: "meshgrid expects all tensors to have the same dtype", + ) + torch._check( + tensors[i].device == tensors[i + 1].device, # type: ignore[union-attr] + lambda: "meshgrid expects all tensors to have the same device", + ) + + swap_first_and_second_tensors = False + if indexing == "xy": + swap_first_and_second_tensors = len(tensors) >= 2 + if swap_first_and_second_tensors: + tensors = (tensors[1], tensors[0], *tensors[2:]) + else: + torch._check( + indexing == "ij", + lambda: ( + 'torch.meshgrid: indexing must be one of "xy" or "ij", ' + f"but received: {indexing}" + ), + ) + + result_shape: List[int] = [] + for t in tensors: + assert isinstance(t, TensorLike) # mypy + torch._check( + t.ndim == 0 or t.ndim == 1, + lambda: f"torch.meshgrid: Expected 0D or 1D tensor in the tensor list but got: {t}", + ) + result_shape.append(t.numel()) + + grids: List[TensorLikeType] = [] + for i, t in enumerate(tensors): + assert isinstance(t, TensorLike) # mypy + if t.ndim == 0: + t = t.view((1,)) + grids.append(prims.broadcast_in_dim(t, result_shape, (i,))) + + if swap_first_and_second_tensors: + # Swap outputs if we originally swapped at the beginning + grids[0], grids[1] = grids[1], grids[0] + + return grids + + +# CompositeImplicitAutograd - don't register decomp +def movedim( + input: TensorLikeType, + source: Union[int, DimsSequenceType], + destination: Union[int, DimsSequenceType], +) -> TensorLikeType: + """ + Reference implementation of torch.movedim + """ + if type(source) is int: + source = (source,) + if type(destination) is int: + destination = (destination,) + + # Converts to list to produce a compatible error message with core PyTorch, + # which prints sequences in square brackets. + torch._check( + len(source) == len(destination), # type: ignore[arg-type] + lambda: ( + "movedim: Invalid source or destination dims: source " # type: ignore[arg-type] + f"({list(source)} dims) should contain the same number " # type: ignore[arg-type] + f"of dims as destination ({list(destination)} dims)" # type: ignore[arg-type] + ), + ) + + rank = input.ndim + ss = tuple(utils.canonicalize_dims(rank=rank, indices=source)) # type: ignore[arg-type] + ds = tuple(utils.canonicalize_dims(rank=rank, indices=destination)) # type: ignore[arg-type] + + sss = set(ss) + dss = set(ds) + + # See above on why this converts to list in error messages. + torch._check( + len(ss) == len(sss), + lambda: f"movedim: repeated dim in `source` ({list(source)})", # type: ignore[arg-type] + ) + torch._check( + len(ds) == len(dss), + lambda: f"movedim: repeated dim in `destination` ({list(destination)})", # type: ignore[arg-type] + ) + + m = dict(zip(ds, ss)) + dims = [] + si = 0 # source index + for di in range(rank): + # check if the destination index is in the mapping + s = m.get(di) + if s is not None: + # insert source index if found + dims.append(s) + else: + # insert source index sequentially, skipping indices from the mapping + while si in sss: + si += 1 + dims.append(si) + si += 1 + + result = torch.permute(input, tuple(dims)) + + return result + + +# NOTE: for convenience, shape can be a tuple of ints or a tuple containing a tuple of ints +@register_decomposition(aten.empty_strided) +@out_wrapper() +def empty_strided( + shape: Union[ShapeType, Tuple[ShapeType]], + strides: StrideType, + *, + dtype: Optional[torch.dtype] = None, + device: Optional[DeviceLikeType] = None, + layout: torch.layout = torch.strided, + requires_grad: bool = False, + pin_memory: bool = False, +) -> TensorLikeType: + # Layout == strided, pin_memory is False + utils.check_layout(layout) + utils.check_pin_memory(pin_memory) + + shape = utils.extract_shape_from_varargs(shape) + dtype = torch.get_default_dtype() if dtype is None else dtype + device = torch.device("cpu") if device is None else device + + return prims.empty_strided( + shape, + strides, + dtype=dtype, + device=device, + requires_grad=requires_grad, + ) + + +@register_decomposition(aten.eye) +@out_wrapper() +def eye( + n: int, + m: Optional[int] = None, + *, + dtype: Optional[torch.dtype] = None, + layout: torch.layout = torch.strided, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, + requires_grad: bool = False, # TODO: unused +) -> TensorLikeType: + """ + Reference implementation of torch.eye + """ + if m is None: + m = n + + torch._check(n >= 0, lambda: f"n must be greater or equal to 0, got {n}") + torch._check(m >= 0, lambda: f"m must be greater or equal to 0, got {m}") + + range_n = torch.arange(n, dtype=torch.int64, device=device, requires_grad=False) + range_m = torch.arange(m, dtype=torch.int64, device=device, requires_grad=False) + + cond = range_n.unsqueeze(-1) == range_m + if dtype is torch.bool: + return cond + else: + one = torch.ones( + (1,), + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=False, + ) + return torch.where(cond, one, 0) + # TODO: Use requires_grad. All refs taking the requires_grad kwarg must + # return a leaf tensor. + # result.requires_grad_(requires_grad) + + +@register_decomposition([aten.full.default, aten.full.out]) +@out_wrapper() +def full( + shape: ShapeType, + fill_value: NumberType, + *, + dtype: Optional[torch.dtype] = None, + layout: torch.layout = torch.strided, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + utils.check_layout(layout) + utils.check_pin_memory(pin_memory) + + dtype = dtype if dtype is not None else utils.type_to_dtype(type(fill_value)) + device = device if device is not None else torch.device("cpu") + + e = empty( + shape, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + return torch.fill(e, fill_value) # type: ignore[arg-type] + + +def full_like( + a: TensorLikeType, + fill_value: NumberType, + *, + dtype: Optional[torch.dtype] = None, + layout: Optional[torch.layout] = None, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, + requires_grad: bool = False, + memory_format: torch.memory_format = torch.preserve_format, +) -> TensorLikeType: + e = torch.empty_like( + a, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + memory_format=memory_format, + ) + return fill(e, fill_value) + + +@register_decomposition(aten.zeros_like) +@out_wrapper() +def zeros_like( + a: TensorLikeType, + *, + dtype: Optional[torch.dtype] = None, + layout: Optional[torch.layout] = None, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, + requires_grad: bool = False, + memory_format: torch.memory_format = torch.preserve_format, +) -> TensorLikeType: + return torch.full_like( + a, + False if (dtype or a.dtype) == torch.bool else 0, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + memory_format=memory_format, + ) + + +@register_decomposition(aten.ones_like) +@out_wrapper() +def ones_like( + a: TensorLikeType, + *, + dtype: Optional[torch.dtype] = None, + layout: Optional[torch.layout] = None, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, + requires_grad: bool = False, + memory_format: torch.memory_format = torch.preserve_format, +) -> TensorLikeType: + return torch.full_like( + a, + True if (dtype or a.dtype) == torch.bool else 1, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + memory_format=memory_format, + ) + + +@register_decomposition(aten.randn.default) +@out_wrapper() +def randn( + *shape, + dtype: Optional[torch.dtype] = None, + device: Optional[DeviceLikeType] = None, + layout: Optional[torch.layout] = None, + requires_grad: bool = False, + pin_memory: bool = False, +) -> TensorLikeType: + utils.check_pin_memory(pin_memory) + + shape_ = utils.extract_shape_from_varargs(shape) + + dtype = utils.dtype_or_default(dtype) + device = utils.device_or_default(device) + + return prims.normal( + shape_, + mean=0.0, + std=1.0, + dtype=dtype, + device=device, + requires_grad=requires_grad, + ) + + +def scalar_tensor( + a: NumberType, + *, + dtype: Optional[torch.dtype] = None, + layout: torch.layout = torch.strided, + device: Optional[DeviceLikeType] = None, + pin_memory: bool = False, +) -> TensorLikeType: + utils.check_layout(layout) + utils.check_pin_memory(pin_memory) + dtype = dtype if dtype is not None else utils.type_to_dtype(type(a)) + device = device if device is not None else torch.device("cpu") + return prims.scalar_tensor(a, dtype=dtype, device=device) + + +# +# Randomness References +# + + +def _uniform_helper( + shape: ShapeType, + low: Union[bool, int, float] = 0.0, + high: Union[bool, int, float] = 1.0, + *, + dtype: torch.dtype, + device: DeviceLikeType, +) -> TensorLikeType: + utils.validate_shape(shape) + + assert isinstance(low, Number) + assert isinstance(high, Number) + low = sym_float(low) + high = sym_float(high) + + assert isinstance(dtype, torch.dtype) + device = utils.canonicalize_device(device) + + return prims._uniform_helper(shape, low=low, high=high, dtype=dtype, device=device) + + +@register_decomposition(aten.masked_fill) +@out_wrapper() +def masked_fill(a: TensorLikeType, mask: TensorLikeType, value: TensorOrNumberLikeType): + python_type = utils.dtype_to_type(a.dtype) + if isinstance(value, Number): + value_type = type(value) + else: + # NOTE: Could not use value = item(value) as it resulted in + # RuntimeError: Cannot cast FakeTensor(cpu) to number + value_ndim = value.ndim + torch._check( + value_ndim == 0, + lambda: f"only supports a 0-dimensional value tensor, but got tensor with {value_ndim} dimension", + ) + # `masked_fill` allows cpu scalar to be moved to cuda and xpu but not otherwise. + is_cpu_scalar = a.device.type in ["cuda", "xpu"] and value.device.type == "cpu" + torch._check( + is_cpu_scalar or value.device == a.device, + lambda: "Expected `value` to be on same device as `a`", + ) + value_type = utils.dtype_to_type(value.dtype) + + if value_type is complex: + # only downcasting from complex to lower type is not allowed. + # We allow casting `value` to lower type for other case + # Eg. float -> int. + # Ref: https://github.com/pytorch/pytorch/issues/79195 + torch._check( + utils.is_weakly_lesser_type(value_type, python_type), + lambda: f"could not convert to type {python_type} without overflow", + ) + + # Since `where` allows type-promotion, + # cast value to correct type before passing to `where` + value = _maybe_convert_to_dtype(value, a.dtype) + r = torch.where(mask, value, a) # type: ignore[arg-type] + + # aten.mask_fill always return a new contiguous tensor + # contiguous() is needed to correctly model the output stride + return r.contiguous() + + +@register_decomposition(aten.masked_fill_) +def masked_fill_( + a: TensorLikeType, mask: TensorLikeType, value: TensorOrNumberLikeType +) -> TensorLikeType: + b = torch.masked_fill(a, mask, value) # type: ignore[arg-type] + a.copy_(b) + return a + + +# CompositeImplicitAutograd - don't register decomp +def allclose( + a: TensorLikeType, + b: TensorLikeType, + rtol: float = 1e-05, + atol: float = 1e-08, + equal_nan: bool = False, +) -> bool: + """ + Reference implementation of torch.allclose + """ + _check_close_args(name="torch.allclose", a=a, b=b, rtol=rtol, atol=atol) + + return bool( + torch.all(torch.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)).item() + ) + + +def equal(a: TensorLikeType, b: TensorLikeType) -> bool: + utils.check_same_device(a, b, allow_cpu_scalar_tensors=False) + utils.check_same_dtype(a, b) + + # Shape check + if a.ndim != b.ndim: + return False + + for x, y in zip(a.shape, b.shape): + if x != y: + return False + + # Short-circuits if there are no elements to validate + if a.numel() == 0: + return True + + return item(all(eq(a, b))) # type: ignore[return-value] + + +@register_decomposition(aten.norm) +@out_wrapper(exact_dtype=True) +def norm( + input: TensorLikeType, + p: Optional[Union[float, str]] = "fro", + dim: Optional[DimsType] = None, + keepdim: bool = False, + *, + dtype: Optional[torch.dtype] = None, +) -> TensorLikeType: + # In these cases we compute the "Frobenius norm" + if ( + p == "fro" and (dim is None or isinstance(dim, Dim) or len(dim) <= 2) + ) or p is None: + p = 2 + if isinstance(dim, Dim): + dim = [dim] + if isinstance(p, str): + # Here we either call the nuclear norm, or we call matrix_norm with some arguments + # that will throw an error + if dim is None: + dim = tuple(range(input.ndim)) + return torch.linalg.matrix_norm(input, p, dim, keepdim, dtype=dtype) + else: + return torch.linalg.vector_norm(input, p, dim, keepdim, dtype=dtype) + + +@register_decomposition(aten.trace) +@out_wrapper() +def trace(self: TensorLikeType) -> TensorLikeType: + torch._check( + self.ndim == 2, lambda: "expected a matrix, but got tensor with dim {self.ndim}" + ) + return torch.sum(torch.diag(self, 0)) + + +def _make_r_binary_op(base_op): + def rop( + a: Union[TensorLikeType, NumberType], + b: Union[TensorLikeType, NumberType], + ) -> TensorLikeType: + return base_op(b, a) + + return rop + + +rtruediv = _make_r_binary_op(true_divide) +rfloordiv = _make_r_binary_op(floor_divide) +rpow = _make_r_binary_op(pow) + + +@register_decomposition(aten.triu) +@out_wrapper() +def triu(a: TensorLikeType, diagonal: int = 0) -> TensorLikeType: + torch._check( + a.ndim >= 2, lambda: "triu: input tensor must have at least 2 dimensions" + ) + h, w = a.shape[-2:] + mask = ( + torch.arange(w, device=a.device).unsqueeze(-2) + - torch.arange(h, device=a.device).unsqueeze(-1) + ) >= diagonal + + # aten.triu always returns a new contiguous tensor + # contiguous() is needed to correctly model the output stride + return utils.mask_tensor(mask, a).contiguous() + + +@register_decomposition(aten.tril) +@out_wrapper() +def tril(a: TensorLikeType, diagonal: int = 0) -> TensorLikeType: + torch._check( + a.ndim >= 2, lambda: "tril: input tensor must have at least 2 dimensions" + ) + h, w = a.shape[-2:] + mask = ( + torch.arange(w, device=a.device).unsqueeze(-2) + - torch.arange(h, device=a.device).unsqueeze(-1) + ) <= diagonal + + # aten.tril always returns a new contiguous tensor + # contiguous() is needed to correctly model the output stride + return utils.mask_tensor(mask, a).contiguous() + + +# This is based on get_tril_size in aten/src/ATen/native/TensorFactories.h +# The components of the matrix that belong to the lower triangle with offset +# form a pentagon that can be broken down into a top trapezoid and a bottom +# rectangle. For the implementation of tril_indices, we need the sizes of +# both of these, as well as the length of the top side of the trapezoid. +def _get_tril_sizes(row: int, col: int, offset: int) -> Tuple[int, int, int]: + if row == 0 or col == 0: + return 0, 0, 0 + + m_first_row = min(col, 1 + offset) if offset > 0 else int(row + offset > 0) + m_last_row = max(0, min(col, row + offset)) + n_row_all = max(0, min(row, row + offset)) + n_row_trapezoid = m_last_row - m_first_row + 1 + + # Number of elements in top trapezoid + trapezoid_size = (m_first_row + m_last_row) * n_row_trapezoid // 2 + # Number of elements in bottom rectangle + diff_row = n_row_all - n_row_trapezoid + rectangle_size = max(0, diff_row * col) + + return trapezoid_size, rectangle_size, m_first_row + + +def _trilu_checks( + name: str, + row: int, + col: int, + dtype: torch.dtype, + layout: torch.layout, + pin_memory: bool, +): + torch._check(row >= 0, lambda: f"row must be non-negative, got {row}") + torch._check(col >= 0, lambda: f"col must be non-negative, got {col}") + torch._check( + dtype in (torch.int32, torch.int64), + lambda: f"\"{name}\" not implemented for '{dtype}'", + ) + + +# This is based on tril_indices_cuda in aten/src/ATen/native/cuda/TensorFactories.cu +@register_decomposition(aten.tril_indices) +@out_wrapper() +def tril_indices( + row: int, + col: int, + offset: int = 0, + *, + dtype: torch.dtype = torch.long, + layout: torch.layout = torch.strided, + device: DeviceLikeType = "cpu", + pin_memory: bool = False, +) -> TensorLikeType: + _trilu_checks("tril_indices", row, col, dtype, layout, pin_memory) + + trapezoid_size, rectangle_size, m_first_row = _get_tril_sizes(row, col, offset) + row_offset = max(0, -offset) + + arange_kw = partial( + torch.arange, layout=layout, device=device, pin_memory=pin_memory + ) + + # first we do the indices for top trapezoid + xs1 = arange_kw(0, trapezoid_size, dtype=torch.float64) + b = m_first_row - 0.5 + row_inds1 = torch.floor(-b + torch.sqrt(b * b + 2 * xs1)) + col_inds1 = torch.floor(xs1 - (2 * m_first_row - 1 + row_inds1) * row_inds1 * 0.5) + row_inds1 = _maybe_convert_to_dtype(row_inds1 + row_offset, dtype) + col_inds1 = _maybe_convert_to_dtype(col_inds1, dtype) + + # then bottom rectangle + xs2 = arange_kw(0, rectangle_size, dtype=dtype) + row_inds2 = xs2 // col + (col - m_first_row + 1 + row_offset) + col_inds2 = xs2 % col + + return torch.stack( + (torch.cat((row_inds1, row_inds2)), torch.cat((col_inds1, col_inds2))) + ) + + +# Similar to _get_tril_sizes above, but here there is a top trapezoid and +# a bottom rectangle instead. Note that you can't reduce this to +# _get_tril_sizes(col, row, -offset) because that would correspond to +# decomposing into a left trapezoid and right rectangle. +def _get_triu_sizes(row: int, col: int, offset: int) -> Tuple[int, int, int]: + if row == 0 or col == 0: + return 0, 0, 0 + + m_first_row = max(0, col - offset) if offset > 0 else col + + # Number of elements in top rectangle + rectangle_size = max(0, min(row, -offset) * col) + + # Number of elements in bottom trapezoid + trapezoid_size_tril, rectangle_size_tril, _ = _get_tril_sizes(row, col, offset - 1) + triu_size = row * col - (trapezoid_size_tril + rectangle_size_tril) + trapezoid_size = triu_size - rectangle_size + + return trapezoid_size, rectangle_size, m_first_row + + +@register_decomposition(aten.triu_indices) +@out_wrapper() +def triu_indices( + row: int, + col: int, + offset: int = 0, + *, + dtype: torch.dtype = torch.long, + layout: torch.layout = torch.strided, + device: DeviceLikeType = "cpu", + pin_memory: bool = False, +) -> TensorLikeType: + _trilu_checks("triu_indices", row, col, dtype, layout, pin_memory) + + trapezoid_size, rectangle_size, m_first_row = _get_triu_sizes(row, col, offset) + col_offset = max(0, offset) + + arange_kw = partial( + torch.arange, layout=layout, device=device, pin_memory=pin_memory + ) + + # indices for top rectangle + xs2 = arange_kw(0, rectangle_size, dtype=dtype) + row_inds2 = xs2 // col + col_inds2 = xs2 % col + + # bottom trapezoid + xs1 = arange_kw(0, trapezoid_size, dtype=torch.float64) + b = -0.5 - m_first_row + row_inds1 = torch.floor(-b - torch.sqrt(b * b - 2 * xs1)) + col_inds1 = torch.floor(xs1 - ((2 * m_first_row - 1 - row_inds1) * row_inds1) * 0.5) + row_inds1 = _maybe_convert_to_dtype(row_inds1, dtype) + col_inds1 = _maybe_convert_to_dtype(col_inds1, dtype) + + if col: + row_inds1 = row_inds1 + (rectangle_size // col) + col_inds1 = col_inds1 + col_offset + + return torch.stack( + (torch.cat((row_inds2, row_inds1)), torch.cat((col_inds2, col_inds1))) + ) + + +@register_decomposition(aten.bucketize) +@out_wrapper(exact_dtype=True) +def bucketize( + a: TensorLikeType, + boundaries: TensorLikeType, + *, + out_int32: bool = False, + right: bool = False, +): + torch._check( + boundaries.dim() == 1, + lambda: f"boundaries tensor must be 1 dimension but got dim({boundaries.dim()})", + ) + + out_dtype = torch.int32 if out_int32 else torch.int64 + n_boundaries = boundaries.shape[-1] + if n_boundaries == 0: + return torch.zeros_like(a) + # We are trying to find the bucket (defined by pairs of consecutive elements of `boundaries`) + # each element of `a` belongs to. We use binary search to achieve logarithimic complexity, + # but each step of the search is done "in parallel" over all elements of `a` + # can't use int32 as indexes, so we have to do all computations with int64 and convert at the end + start = torch.zeros(a.shape, device=a.device, dtype=torch.int64) + end = start + n_boundaries + # Max depth of the binary search + # Since we can't break out of the loop at different points for different elements of a, + # we just do the max amount of iterations that binary search requires and add condition + # tensor (cond_update below) to stop updating once the search terminates + + # For first iteration through loop we can skip some checks, we have separate implementation + mid = start + (end - start) // 2 + mid_val = boundaries[mid] + if right: + cond_mid = mid_val > a + else: + cond_mid = mid_val >= a + start = torch.where(cond_mid, start, mid + 1) + + if n_boundaries > 1: + cond_update = torch.ones_like(a, dtype=torch.bool) + niters = int(math.log2(n_boundaries)) + for _ in range(niters): + end = torch.where(cond_mid & cond_update, mid, end) + cond_update = start < end + # start might end up pointing to 1 past the end, we guard against that + mid = torch.where(cond_update, start + (end - start) // 2, 0) + mid_val = boundaries[mid] + # If right is true, the buckets are closed on the *left* + # (i.e., we are doing the equivalent of std::upper_bound in C++) + # Otherwise they are closed on the right (std::lower_bound) + if right: + cond_mid = mid_val > a + else: + cond_mid = mid_val >= a + start = torch.where((~cond_mid) & cond_update, mid + 1, start) + + return start.to(dtype=out_dtype) + + +@register_decomposition(aten.cauchy) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def cauchy(self, median=0, sigma=1, generator=None): + assert generator is None + torch._check( + not utils.is_complex_dtype(self.dtype) + and not utils.is_integer_dtype(self.dtype) + and not utils.is_boolean_dtype(self.dtype), + lambda: f"Cauchy distribution is a continuous probability distribution. \ + dtype must be a floating point but you specified {self.dtype}", + ) + torch._check( + sigma > 0.0, + lambda: f"cauchy_ expects sigma > 0.0, but found sigma={sigma}", + ) + return median + sigma * torch.tan(math.pi * (torch.rand_like(self) - 0.5)) + + +@register_decomposition(aten.exponential) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def exponential(self, rate=1, generator=None): + assert generator is None + torch._check( + not utils.is_complex_dtype(self.dtype) + and not utils.is_integer_dtype(self.dtype) + and not utils.is_boolean_dtype(self.dtype), + lambda: f"Exponential distribution is a continuous probability distribution. \ + dtype must be a floating point but you specified {self.dtype}", + ) + torch._check( + rate > 0.0, + lambda: f"exponential_ expects lambda > 0.0, but found lambda={rate}", + ) + return -1 / rate * torch.log1p(-torch.rand_like(self)) + + +@register_decomposition(aten.geometric) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def geometric(self, p, generator=None): + assert generator is None + # TODO: fix inductor rand_like for integer, bool dtypes + torch._check( + not utils.is_complex_dtype(self.dtype) + and not utils.is_boolean_dtype(self.dtype), + lambda: f"geometric not implemented for {self.dtype}", + ) + torch._check( + 0 < p and p < 1, + lambda: f"geometric_ expects p to be in (0, 1), but got p={p}", + ) + return torch.floor(torch.log1p(-torch.rand_like(self)) / math.log1p(-p)) + 1 + + +@register_decomposition(aten.log_normal) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def log_normal(self, mean=1, std=2, generator=None): + assert generator is None + torch._check( + not utils.is_complex_dtype(self.dtype) + and not utils.is_integer_dtype(self.dtype) + and not utils.is_boolean_dtype(self.dtype), + lambda: f"log_normal not implemented for {self.dtype}", + ) + torch._check( + 0 < std, + lambda: f"log_normal_ expects std > 0.0, but found std={std}", + ) + return torch.exp(std * torch.randn_like(self) + mean) + + +# TODO: add support for functionalization aten.normal_functional +# NOTE: the device and dtype will be ignored when shape is None +@register_decomposition(aten.normal) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=( + "mean", + "std", + ), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def normal( + mean=0, + std=1, + size=None, + *, + generator=None, + dtype=None, + layout=None, + device=None, + pin_memory=None, +): + assert layout is None or layout == torch.strided + + if not isinstance(std, TensorLike): + torch._check( + std >= 0, lambda: f"normal expects std >= 0.0, but found std {std}" + ) + + if size is None: + tensors = tuple(t for t in (mean, std) if isinstance(t, TensorLike)) + torch._check( + len(tensors) > 0, + lambda: "normal expects that either mean or std is a tensor, or size is defined", + ) + torch._check( + layout is None and pin_memory is None, + lambda: "Cannot pass layout, or pin_memory without size", + ) + + size = _broadcast_shapes(*(t.shape for t in tensors)) + dtype = tensors[0].dtype + device = tensors[0].device + else: + torch._check( + not isinstance(mean, TensorLike) and not isinstance(std, TensorLike), + lambda: "normal expects mean and std to be scalars when size is defined", + ) + dtype = torch.get_default_dtype() if dtype is None else dtype + device = torch.device("cpu") if device is None else device + + normal_samples = prims.normal( + size, + mean=0.0, + std=1.0, + dtype=dtype, + device=device, + requires_grad=False, + generator=generator, + ) + return std * normal_samples + mean + + +@register_decomposition(aten.normal_) +def normal_(self, mean=0, std=1, *, generator=None): + return normal(mean, std, self.shape, out=self, generator=generator) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def rad2deg(self: TensorLikeType): + torch._check( + not utils.is_complex_dtype(self.dtype), + lambda: "rad2deg is not supported for complex tensors.", + ) + M_180_PI = 57.295779513082320876798154814105170332405472466564 + return self * M_180_PI + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def deg2rad(self: TensorLikeType): + torch._check( + not utils.is_complex_dtype(self.dtype), + lambda: "deg2rad is not supported for complex tensors.", + ) + M_PI_180 = 0.017453292519943295769236907684886127134428718885417 + return self * M_PI_180 + + +@register_decomposition(aten.count_nonzero) +@out_wrapper() +def count_nonzero(self, dim: Optional[DimsType] = None): + return (self != 0).sum(dim) + + +def _dot_check(self, other): + torch._check( + self.dim() == 1 and other.dim() == 1, + lambda: f"1D tensors expected, but got {self.dim()}D and {other.dim()}D tensors", + ) + + def numel_error(): + return ( + f"inconsistent tensor size, expected tensor [{self.numel()}] and src [{other.numel()}] to have the" + f"same number of elements, but got {self.numel()} and {other.numel()} elements respectively" + ) + + torch._check(self.numel() == other.numel(), numel_error) + + +@register_decomposition(aten.dot) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self", "other"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def dot(self, other): + if self.is_complex(): + if self.is_conj(): + if other.is_conj(): + return torch.dot(self.conj(), other.conj()).conj() + else: + return torch.vdot(self.conj(), other) + elif other.is_conj(): + return torch.vdot(other.conj(), self) + + _dot_check(self, other) + return (self * other).sum() + + +@register_decomposition(aten.vdot) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self", "other"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def vdot(self, other): + if not self.is_complex(): + return torch.dot(self, other) + + if self.is_conj(): + if other.is_conj(): + return torch.vdot(other.conj(), self.conj()) + else: + return torch.dot(self.conj(), other) + elif other.is_conj(): + return torch.dot(self, other.conj()).conj() + + _dot_check(self, other) + # The decomposition fails if you do self.conj()... not sure why + return (self.conj_physical() * other).sum() + + +# inplace +abs_ = _make_inplace(abs) +acos_ = _make_inplace(acos) +acosh_ = _make_inplace(acosh) +add_ = _make_inplace(add) +addcmul_ = _make_inplace(addcmul) +addcdiv_ = _make_inplace(addcdiv) +asin_ = _make_inplace(asin) +asinh_ = _make_inplace(asinh) +atan_ = _make_inplace(atan) +atanh_ = _make_inplace(atanh) +atan2_ = _make_inplace(atan2) +bitwise_and_ = _make_inplace(bitwise_and) +bitwise_left_shift_ = _make_inplace(bitwise_left_shift) +bitwise_not_ = _make_inplace(bitwise_not) +bitwise_or_ = _make_inplace(bitwise_or) +bitwise_right_shift_ = _make_inplace(bitwise_right_shift) +bitwise_xor_ = _make_inplace(bitwise_xor) +ceil_ = _make_inplace(ceil) +clamp_ = _make_inplace(clamp) +clamp_min_ = _make_inplace(clamp_min) +clamp_max_ = _make_inplace(clamp_max) +conj_physical_ = _make_inplace(conj_physical) +copysign_ = _make_inplace(copysign) +cos_ = _make_inplace(cos) +cosh_ = _make_inplace(cosh) +cumsum_ = _make_inplace(cumsum) +cumprod_ = _make_inplace(cumprod) +deg2rad_ = _make_inplace(deg2rad) +digamma_ = _make_inplace(digamma) +div_ = _make_inplace(div) +eq_ = _make_inplace(eq) +erf_ = _make_inplace(erf) +erfc_ = _make_inplace(erfc) +erfinv_ = _make_inplace(erfinv) +exp_ = _make_inplace(exp) +exp2_ = _make_inplace(exp2) +expm1_ = _make_inplace(expm1) +float_power_ = _make_inplace(float_power) +floor_ = _make_inplace(floor) +floor_divide_ = _make_inplace(floor_divide) +fmod_ = _make_inplace(fmod) +frac_ = _make_inplace(frac) +gcd_ = _make_inplace(gcd) +ge_ = _make_inplace(ge) +gt_ = _make_inplace(gt) +heaviside_ = _make_inplace(heaviside) +hypot_ = _make_inplace(hypot) +igamma_ = _make_inplace(igamma) +igammac_ = _make_inplace(igammac) +i0_ = _make_inplace(i0) +lcm_ = _make_inplace(lcm) +le_ = _make_inplace(le) +lerp_ = _make_inplace(lerp) +lgamma_ = _make_inplace(lgamma) +log10_ = _make_inplace(log10) +log1p_ = _make_inplace(log1p) +log2_ = _make_inplace(log2) +log_ = _make_inplace(log) +logical_and_ = _make_inplace(logical_and) +logical_not_ = _make_inplace(logical_not) +logical_or_ = _make_inplace(logical_or) +logical_xor_ = _make_inplace(logical_xor) +lt_ = _make_inplace(lt) +mul_ = _make_inplace(mul) +mvlgamma_ = _make_inplace(mvlgamma) +nan_to_num_ = _make_inplace(nan_to_num) +ne_ = _make_inplace(ne) +neg_ = _make_inplace(neg) +nextafter_ = _make_inplace(nextafter) +pow_ = _make_inplace(pow) +rad2deg_ = _make_inplace(rad2deg) +reciprocal_ = _make_inplace(reciprocal) +remainder_ = _make_inplace(remainder) +rsqrt_ = _make_inplace(rsqrt) +sgn_ = _make_inplace(sgn) +sigmoid_ = _make_inplace(sigmoid) +sign_ = _make_inplace(sign) +sin_ = _make_inplace(sin) +sinc_ = _make_inplace(sinc) +sinh_ = _make_inplace(sinh) +sqrt_ = _make_inplace(sqrt) +square_ = _make_inplace(square) +sub_ = _make_inplace(sub) +tan_ = _make_inplace(tan) +tanh_ = _make_inplace(tanh) +tril_ = _make_inplace(tril) +triu_ = _make_inplace(triu) +true_divide_ = _make_inplace(true_divide) +trunc_ = _make_inplace(trunc) +xlogy_ = _make_inplace(xlogy) +cauchy_ = _make_inplace(cauchy) +exponential_ = _make_inplace(exponential) +geometric_ = _make_inplace(geometric) +log_normal_ = _make_inplace(log_normal) +zero_ = _make_inplace(zero) + + +# xref: isStorage in torch/csrc/DynamicTypes.cpp +def _isStorage(obj): + return isinstance(obj, (torch.TypedStorage, torch.UntypedStorage)) + + +# xref: compute_sizes in torch/csrc/utils/tensor_new.cpp +def _compute_sizes(seq, scalar_type): + MAX_DIMS = 128 + is_storage = _isStorage(seq) + sizes = [] + # TODO: this is inaccurate, we actually test PySequence_Check + while isinstance(seq, (list, tuple)): + length = len(seq) + if is_storage: + length //= scalar_type.itemsize + sizes.append(length) + if len(sizes) > MAX_DIMS: + raise ValueError(f"too many dimensions '{type(seq).__name__}'") + if length == 0: + break + try: + handle = seq[0] + except Exception: + raise ValueError( # noqa: TRY200 + f"could not determine the shape of object type '{type(seq).__name__}'" + ) + seq = handle + + return sizes + + +# xref: infer_scalar_type in torch/csrc/utils/tensor_new.cpp +def _infer_scalar_type(obj): + if isinstance(obj, FloatLike): + return torch.get_default_dtype() + if isinstance(obj, IntLike) and not isinstance(obj, bool): # careful! + return torch.int64 + if isinstance(obj, bool): + return torch.bool + if isinstance(obj, complex): + default_dtype = torch.get_default_dtype() + if default_dtype is torch.float: + return torch.cfloat + elif default_dtype is torch.double: + return torch.cdouble + else: + raise RuntimeError("invalid default scalar type for complex") + if isinstance(obj, torch.Tensor): + return obj.dtype + if isinstance(obj, str): + raise TypeError(f"new(): invalid data type '{type(obj).__name__}'") + # TODO: this is inaccurate, we actually test PySequence_Check + if isinstance(obj, (list, tuple)): + scalarType = None + length = len(obj) + # match NumPy semantics, except use default tensor type instead of + # double. + if length == 0: + return torch.get_default_dtype() + for i in range(length): + cur_item = obj[i] + # TODO: test this + """ + if cur_item is obj: + raise TypeError("new(): self-referential lists are incompatible") + """ + item_scalarType = _infer_scalar_type(cur_item) # recurse! + if scalarType is not None: + scalarType = torch.promote_types(scalarType, item_scalarType) + else: + scalarType = item_scalarType + if scalarType is torch.cdouble: + # this won't change (unless we hit undefined, but that will + # fail later) + return scalarType + return scalarType + raise RuntimeError(f"Could not infer dtype of {type(obj).__name__}") + + +# Analogous to recursive_store +# xref: recursive_store in torch/csrc/utils/tensor_new.cpp +def _recursive_build(scalarType: torch.dtype, obj: TensorOrNumberLikeType): + if isinstance(obj, Tensor) and obj.ndim <= 1: + obj = obj.item() + # fall through into next case + if isinstance(obj, Number): + return torch.scalar_tensor(obj, dtype=scalarType) + + seq = obj + return torch.stack([_recursive_build(scalarType, item) for item in seq]) + + +# xref: internal_new_from_data in torch/csrc/utils/tensor_new.cpp +def _internal_new_from_data( + options, + scalar_type, + device_opt, + data, + copy_variables, + copy_numpy, + type_inference, + pin_memory=False, +): + if isinstance(data, torch.Tensor): + torch._check( + not pin_memory, lambda: "Can't pin tensor constructed from a variable" + ) + var = data + if copy_variables: + var = var.detach() + inferred_scalar_type = var.dtype if type_inference else scalar_type + device = device_opt if device_opt is not None else var.device + return var.to( + device=device, + dtype=inferred_scalar_type, + non_blocking=False, + copy=copy_variables, + ) + + # TODO + if hasattr(data, "__cuda_array_interface__"): + return NotImplemented + + # TODO: test for numpy input with PyArray_Check + + device = device_opt if device_opt is not None else options["device"] + inferred_scalar_type = _infer_scalar_type(data) if type_inference else scalar_type + + # NB: Don't need to avoid tracing, as we aren't going to do any manual + # pointer filling tricks + if _isStorage(data): + return NotImplemented + else: + if torch.device(device).type == "meta": + return NotImplemented + + # In the C implementation, we would directly start poking the memory + # of a freshly allocated CPU tensor. Here, we're going to do an + # alternate, heinously slow implementation: turn each individual + # scalar into a tensor, and then repeatedly cat them together + tensor = _recursive_build(inferred_scalar_type, data) + + tensor = tensor.to(device, inferred_scalar_type, non_blocking=False, copy=False) + + # NB: lift_fresh is not needed, because we built the tensor from scalars + # guaranteeing a fresh tensor in this case + return tensor + + +# xref: tensor_ctor in torch/csrc/utils/tensor_new.cpp +def tensor(data, *, dtype=None, device=None, pin_memory=False, requires_grad=False): + # TODO (or not): support names kwarg + if isinstance(data, torch.Tensor): + warnings.warn( + "To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() " + "or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor)" + ) + type_inference = dtype is None + new_tensor = _internal_new_from_data( + # device="cpu" because that's what you get with torch.tensor(2) no + # device by default + {"device": "cpu"}, # TODO: use torch.get_default_tensor_type + dtype if dtype is not None else torch.get_default_dtype(), + device, + data, + copy_variables=True, + copy_numpy=True, + type_inference=type_inference, + pin_memory=pin_memory, + ) + new_tensor.detach_() + new_tensor.requires_grad_(requires_grad) + return new_tensor + + +# Views +# We can't model these as above, as the pattern of doing `op(a, out=a)` does not work for a view function +# given that it does not reshape the input (it just copies the result into it) + +# squeeze_ = _make_inplace(squeeze) +# t_ = _make_inplace(t) +# transpose_ = _make_inplace(transpose) +# unsqueeze_ = _make_inplace(unsqueeze) + + +import torch._refs._conversions +import torch._refs.fft +import torch._refs.linalg +import torch._refs.nn.functional +import torch._refs.special diff --git a/shared/package-files/d1/d146f9cf31b1393d4e4305e85af9a0a33e79de0fa8f8be55b15f96d2672f8ef8/blob b/shared/package-files/d1/d146f9cf31b1393d4e4305e85af9a0a33e79de0fa8f8be55b15f96d2672f8ef8/blob new file mode 100644 index 0000000000000000000000000000000000000000..3dd3ec54fd9753e8b4be792b49cde105940fb901 --- /dev/null +++ b/shared/package-files/d1/d146f9cf31b1393d4e4305e85af9a0a33e79de0fa8f8be55b15f96d2672f8ef8/blob @@ -0,0 +1,326 @@ +#ifndef C10_UTIL_REGISTRY_H_ +#define C10_UTIL_REGISTRY_H_ + +/** + * Simple registry implementation that uses static variables to + * register object creators during program initialization time. + */ + +// NB: This Registry works poorly when you have other namespaces. +// Make all macro invocations from inside the at namespace. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace c10 { + +template +inline std::string KeyStrRepr(const KeyType& /*key*/) { + return "[key type printing not supported]"; +} + +template <> +inline std::string KeyStrRepr(const std::string& key) { + return key; +} + +enum RegistryPriority { + REGISTRY_FALLBACK = 1, + REGISTRY_DEFAULT = 2, + REGISTRY_PREFERRED = 3, +}; + +/** + * @brief A template class that allows one to register classes by keys. + * + * The keys are usually a std::string specifying the name, but can be anything + * that can be used in a std::map. + * + * You should most likely not use the Registry class explicitly, but use the + * helper macros below to declare specific registries as well as registering + * objects. + */ +template +class Registry { + public: + typedef std::function Creator; + + Registry(bool warning = true) : registry_(), priority_(), warning_(warning) {} + + void Register( + const SrcType& key, + Creator creator, + const RegistryPriority priority = REGISTRY_DEFAULT) { + std::lock_guard lock(register_mutex_); + // The if statement below is essentially the same as the following line: + // TORCH_CHECK_EQ(registry_.count(key), 0) << "Key " << key + // << " registered twice."; + // However, TORCH_CHECK_EQ depends on google logging, and since registration + // is carried out at static initialization time, we do not want to have an + // explicit dependency on glog's initialization function. + if (registry_.count(key) != 0) { + auto cur_priority = priority_[key]; + if (priority > cur_priority) { +#ifdef DEBUG + std::string warn_msg = + "Overwriting already registered item for key " + KeyStrRepr(key); + fprintf(stderr, "%s\n", warn_msg.c_str()); +#endif + registry_[key] = creator; + priority_[key] = priority; + } else if (priority == cur_priority) { + std::string err_msg = + "Key already registered with the same priority: " + KeyStrRepr(key); + fprintf(stderr, "%s\n", err_msg.c_str()); + if (terminate_) { + std::exit(1); + } else { + throw std::runtime_error(err_msg); + } + } else if (warning_) { + std::string warn_msg = + "Higher priority item already registered, skipping registration of " + + KeyStrRepr(key); + fprintf(stderr, "%s\n", warn_msg.c_str()); + } + } else { + registry_[key] = creator; + priority_[key] = priority; + } + } + + void Register( + const SrcType& key, + Creator creator, + const std::string& help_msg, + const RegistryPriority priority = REGISTRY_DEFAULT) { + Register(key, creator, priority); + help_message_[key] = help_msg; + } + + inline bool Has(const SrcType& key) { + return (registry_.count(key) != 0); + } + + ObjectPtrType Create(const SrcType& key, Args... args) { + auto it = registry_.find(key); + if (it == registry_.end()) { + // Returns nullptr if the key is not registered. + return nullptr; + } + return it->second(args...); + } + + /** + * Returns the keys currently registered as a std::vector. + */ + std::vector Keys() const { + std::vector keys; + keys.reserve(registry_.size()); + for (const auto& it : registry_) { + keys.push_back(it.first); + } + return keys; + } + + inline const std::unordered_map& HelpMessage() const { + return help_message_; + } + + const char* HelpMessage(const SrcType& key) const { + auto it = help_message_.find(key); + if (it == help_message_.end()) { + return nullptr; + } + return it->second.c_str(); + } + + // Used for testing, if terminate is unset, Registry throws instead of + // calling std::exit + void SetTerminate(bool terminate) { + terminate_ = terminate; + } + + private: + std::unordered_map registry_; + std::unordered_map priority_; + bool terminate_{true}; + const bool warning_; + std::unordered_map help_message_; + std::mutex register_mutex_; + + C10_DISABLE_COPY_AND_ASSIGN(Registry); +}; + +template +class Registerer { + public: + explicit Registerer( + const SrcType& key, + Registry* registry, + typename Registry::Creator creator, + const std::string& help_msg = "") { + registry->Register(key, creator, help_msg); + } + + explicit Registerer( + const SrcType& key, + const RegistryPriority priority, + Registry* registry, + typename Registry::Creator creator, + const std::string& help_msg = "") { + registry->Register(key, creator, help_msg, priority); + } + + template + static ObjectPtrType DefaultCreator(Args... args) { + return ObjectPtrType(new DerivedType(args...)); + } +}; + +/** + * C10_DECLARE_TYPED_REGISTRY is a macro that expands to a function + * declaration, as well as creating a convenient typename for its corresponding + * registerer. + */ +// Note on C10_IMPORT and C10_EXPORT below: we need to explicitly mark DECLARE +// as import and DEFINE as export, because these registry macros will be used +// in downstream shared libraries as well, and one cannot use *_API - the API +// macro will be defined on a per-shared-library basis. Semantically, when one +// declares a typed registry it is always going to be IMPORT, and when one +// defines a registry (which should happen ONLY ONCE and ONLY IN SOURCE FILE), +// the instantiation unit is always going to be exported. +// +// The only unique condition is when in the same file one does DECLARE and +// DEFINE - in Windows compilers, this generates a warning that dllimport and +// dllexport are mixed, but the warning is fine and linker will be properly +// exporting the symbol. Same thing happens in the gflags flag declaration and +// definition caes. +#define C10_DECLARE_TYPED_REGISTRY( \ + RegistryName, SrcType, ObjectType, PtrType, ...) \ + C10_API ::c10::Registry, ##__VA_ARGS__>* \ + RegistryName(); \ + typedef ::c10::Registerer, ##__VA_ARGS__> \ + Registerer##RegistryName + +#define TORCH_DECLARE_TYPED_REGISTRY( \ + RegistryName, SrcType, ObjectType, PtrType, ...) \ + TORCH_API ::c10::Registry, ##__VA_ARGS__>* \ + RegistryName(); \ + typedef ::c10::Registerer, ##__VA_ARGS__> \ + Registerer##RegistryName + +#define C10_DEFINE_TYPED_REGISTRY( \ + RegistryName, SrcType, ObjectType, PtrType, ...) \ + C10_EXPORT ::c10::Registry, ##__VA_ARGS__>* \ + RegistryName() { \ + static ::c10::Registry, ##__VA_ARGS__>* \ + registry = new ::c10:: \ + Registry, ##__VA_ARGS__>(); \ + return registry; \ + } + +#define C10_DEFINE_TYPED_REGISTRY_WITHOUT_WARNING( \ + RegistryName, SrcType, ObjectType, PtrType, ...) \ + C10_EXPORT ::c10::Registry, ##__VA_ARGS__>* \ + RegistryName() { \ + static ::c10::Registry, ##__VA_ARGS__>* \ + registry = \ + new ::c10::Registry, ##__VA_ARGS__>( \ + false); \ + return registry; \ + } + +// Note(Yangqing): The __VA_ARGS__ below allows one to specify a templated +// creator with comma in its templated arguments. +#define C10_REGISTER_TYPED_CREATOR(RegistryName, key, ...) \ + static Registerer##RegistryName C10_ANONYMOUS_VARIABLE(g_##RegistryName)( \ + key, RegistryName(), ##__VA_ARGS__); + +#define C10_REGISTER_TYPED_CREATOR_WITH_PRIORITY( \ + RegistryName, key, priority, ...) \ + static Registerer##RegistryName C10_ANONYMOUS_VARIABLE(g_##RegistryName)( \ + key, priority, RegistryName(), ##__VA_ARGS__); + +#define C10_REGISTER_TYPED_CLASS(RegistryName, key, ...) \ + static Registerer##RegistryName C10_ANONYMOUS_VARIABLE(g_##RegistryName)( \ + key, \ + RegistryName(), \ + Registerer##RegistryName::DefaultCreator<__VA_ARGS__>, \ + ::c10::demangle_type<__VA_ARGS__>()); + +#define C10_REGISTER_TYPED_CLASS_WITH_PRIORITY( \ + RegistryName, key, priority, ...) \ + static Registerer##RegistryName C10_ANONYMOUS_VARIABLE(g_##RegistryName)( \ + key, \ + priority, \ + RegistryName(), \ + Registerer##RegistryName::DefaultCreator<__VA_ARGS__>, \ + ::c10::demangle_type<__VA_ARGS__>()); + +// C10_DECLARE_REGISTRY and C10_DEFINE_REGISTRY are hard-wired to use +// std::string as the key type, because that is the most commonly used cases. +#define C10_DECLARE_REGISTRY(RegistryName, ObjectType, ...) \ + C10_DECLARE_TYPED_REGISTRY( \ + RegistryName, std::string, ObjectType, std::unique_ptr, ##__VA_ARGS__) + +#define TORCH_DECLARE_REGISTRY(RegistryName, ObjectType, ...) \ + TORCH_DECLARE_TYPED_REGISTRY( \ + RegistryName, std::string, ObjectType, std::unique_ptr, ##__VA_ARGS__) + +#define C10_DEFINE_REGISTRY(RegistryName, ObjectType, ...) \ + C10_DEFINE_TYPED_REGISTRY( \ + RegistryName, std::string, ObjectType, std::unique_ptr, ##__VA_ARGS__) + +#define C10_DEFINE_REGISTRY_WITHOUT_WARNING(RegistryName, ObjectType, ...) \ + C10_DEFINE_TYPED_REGISTRY_WITHOUT_WARNING( \ + RegistryName, std::string, ObjectType, std::unique_ptr, ##__VA_ARGS__) + +#define C10_DECLARE_SHARED_REGISTRY(RegistryName, ObjectType, ...) \ + C10_DECLARE_TYPED_REGISTRY( \ + RegistryName, std::string, ObjectType, std::shared_ptr, ##__VA_ARGS__) + +#define TORCH_DECLARE_SHARED_REGISTRY(RegistryName, ObjectType, ...) \ + TORCH_DECLARE_TYPED_REGISTRY( \ + RegistryName, std::string, ObjectType, std::shared_ptr, ##__VA_ARGS__) + +#define C10_DEFINE_SHARED_REGISTRY(RegistryName, ObjectType, ...) \ + C10_DEFINE_TYPED_REGISTRY( \ + RegistryName, std::string, ObjectType, std::shared_ptr, ##__VA_ARGS__) + +#define C10_DEFINE_SHARED_REGISTRY_WITHOUT_WARNING( \ + RegistryName, ObjectType, ...) \ + C10_DEFINE_TYPED_REGISTRY_WITHOUT_WARNING( \ + RegistryName, std::string, ObjectType, std::shared_ptr, ##__VA_ARGS__) + +// C10_REGISTER_CREATOR and C10_REGISTER_CLASS are hard-wired to use std::string +// as the key +// type, because that is the most commonly used cases. +#define C10_REGISTER_CREATOR(RegistryName, key, ...) \ + C10_REGISTER_TYPED_CREATOR(RegistryName, #key, __VA_ARGS__) + +#define C10_REGISTER_CREATOR_WITH_PRIORITY(RegistryName, key, priority, ...) \ + C10_REGISTER_TYPED_CREATOR_WITH_PRIORITY( \ + RegistryName, #key, priority, __VA_ARGS__) + +#define C10_REGISTER_CLASS(RegistryName, key, ...) \ + C10_REGISTER_TYPED_CLASS(RegistryName, #key, __VA_ARGS__) + +#define C10_REGISTER_CLASS_WITH_PRIORITY(RegistryName, key, priority, ...) \ + C10_REGISTER_TYPED_CLASS_WITH_PRIORITY( \ + RegistryName, #key, priority, __VA_ARGS__) + +} // namespace c10 + +#endif // C10_UTIL_REGISTRY_H_ diff --git a/shared/package-files/d1/d148cd156ed2cad8f5b77d500fdf5e6dfafe6a5ecd982a5684a50ecaaf55ccaf/blob b/shared/package-files/d1/d148cd156ed2cad8f5b77d500fdf5e6dfafe6a5ecd982a5684a50ecaaf55ccaf/blob new file mode 100644 index 0000000000000000000000000000000000000000..610d7c40935b0999fe7de38515f316ce816023f7 --- /dev/null +++ b/shared/package-files/d1/d148cd156ed2cad8f5b77d500fdf5e6dfafe6a5ecd982a5684a50ecaaf55ccaf/blob @@ -0,0 +1,166 @@ +# auto-generated by https://github.com/trygvrad/multivariate_colormaps +# date: 2024-05-28 + +from .colors import LinearSegmentedColormap, MultivarColormap +import matplotlib as mpl +_LUTSIZE = mpl.rcParams['image.lut'] + +_2VarAddA0_data = [[0.000, 0.000, 0.000], + [0.020, 0.026, 0.031], + [0.049, 0.068, 0.085], + [0.075, 0.107, 0.135], + [0.097, 0.144, 0.183], + [0.116, 0.178, 0.231], + [0.133, 0.212, 0.279], + [0.148, 0.244, 0.326], + [0.161, 0.276, 0.374], + [0.173, 0.308, 0.422], + [0.182, 0.339, 0.471], + [0.190, 0.370, 0.521], + [0.197, 0.400, 0.572], + [0.201, 0.431, 0.623], + [0.204, 0.461, 0.675], + [0.204, 0.491, 0.728], + [0.202, 0.520, 0.783], + [0.197, 0.549, 0.838], + [0.187, 0.577, 0.895]] + +_2VarAddA1_data = [[0.000, 0.000, 0.000], + [0.030, 0.023, 0.018], + [0.079, 0.060, 0.043], + [0.125, 0.093, 0.065], + [0.170, 0.123, 0.083], + [0.213, 0.151, 0.098], + [0.255, 0.177, 0.110], + [0.298, 0.202, 0.120], + [0.341, 0.226, 0.128], + [0.384, 0.249, 0.134], + [0.427, 0.271, 0.138], + [0.472, 0.292, 0.141], + [0.517, 0.313, 0.142], + [0.563, 0.333, 0.141], + [0.610, 0.353, 0.139], + [0.658, 0.372, 0.134], + [0.708, 0.390, 0.127], + [0.759, 0.407, 0.118], + [0.813, 0.423, 0.105]] + +_2VarSubA0_data = [[1.000, 1.000, 1.000], + [0.959, 0.973, 0.986], + [0.916, 0.948, 0.974], + [0.874, 0.923, 0.965], + [0.832, 0.899, 0.956], + [0.790, 0.875, 0.948], + [0.748, 0.852, 0.940], + [0.707, 0.829, 0.934], + [0.665, 0.806, 0.927], + [0.624, 0.784, 0.921], + [0.583, 0.762, 0.916], + [0.541, 0.740, 0.910], + [0.500, 0.718, 0.905], + [0.457, 0.697, 0.901], + [0.414, 0.675, 0.896], + [0.369, 0.652, 0.892], + [0.320, 0.629, 0.888], + [0.266, 0.604, 0.884], + [0.199, 0.574, 0.881]] + +_2VarSubA1_data = [[1.000, 1.000, 1.000], + [0.982, 0.967, 0.955], + [0.966, 0.935, 0.908], + [0.951, 0.902, 0.860], + [0.937, 0.870, 0.813], + [0.923, 0.838, 0.765], + [0.910, 0.807, 0.718], + [0.898, 0.776, 0.671], + [0.886, 0.745, 0.624], + [0.874, 0.714, 0.577], + [0.862, 0.683, 0.530], + [0.851, 0.653, 0.483], + [0.841, 0.622, 0.435], + [0.831, 0.592, 0.388], + [0.822, 0.561, 0.340], + [0.813, 0.530, 0.290], + [0.806, 0.498, 0.239], + [0.802, 0.464, 0.184], + [0.801, 0.426, 0.119]] + +_3VarAddA0_data = [[0.000, 0.000, 0.000], + [0.018, 0.023, 0.028], + [0.040, 0.056, 0.071], + [0.059, 0.087, 0.110], + [0.074, 0.114, 0.147], + [0.086, 0.139, 0.183], + [0.095, 0.163, 0.219], + [0.101, 0.187, 0.255], + [0.105, 0.209, 0.290], + [0.107, 0.230, 0.326], + [0.105, 0.251, 0.362], + [0.101, 0.271, 0.398], + [0.091, 0.291, 0.434], + [0.075, 0.309, 0.471], + [0.046, 0.325, 0.507], + [0.021, 0.341, 0.546], + [0.021, 0.363, 0.584], + [0.022, 0.385, 0.622], + [0.023, 0.408, 0.661]] + +_3VarAddA1_data = [[0.000, 0.000, 0.000], + [0.020, 0.024, 0.016], + [0.047, 0.058, 0.034], + [0.072, 0.088, 0.048], + [0.093, 0.116, 0.059], + [0.113, 0.142, 0.067], + [0.131, 0.167, 0.071], + [0.149, 0.190, 0.074], + [0.166, 0.213, 0.074], + [0.182, 0.235, 0.072], + [0.198, 0.256, 0.068], + [0.215, 0.276, 0.061], + [0.232, 0.296, 0.051], + [0.249, 0.314, 0.037], + [0.270, 0.330, 0.018], + [0.288, 0.347, 0.000], + [0.302, 0.369, 0.000], + [0.315, 0.391, 0.000], + [0.328, 0.414, 0.000]] + +_3VarAddA2_data = [[0.000, 0.000, 0.000], + [0.029, 0.020, 0.023], + [0.072, 0.045, 0.055], + [0.111, 0.067, 0.084], + [0.148, 0.085, 0.109], + [0.184, 0.101, 0.133], + [0.219, 0.115, 0.155], + [0.254, 0.127, 0.176], + [0.289, 0.138, 0.195], + [0.323, 0.147, 0.214], + [0.358, 0.155, 0.232], + [0.393, 0.161, 0.250], + [0.429, 0.166, 0.267], + [0.467, 0.169, 0.283], + [0.507, 0.168, 0.298], + [0.546, 0.168, 0.313], + [0.580, 0.172, 0.328], + [0.615, 0.175, 0.341], + [0.649, 0.178, 0.355]] + +cmaps = { + name: LinearSegmentedColormap.from_list(name, data, _LUTSIZE) for name, data in [ + ('2VarAddA0', _2VarAddA0_data), + ('2VarAddA1', _2VarAddA1_data), + ('2VarSubA0', _2VarSubA0_data), + ('2VarSubA1', _2VarSubA1_data), + ('3VarAddA0', _3VarAddA0_data), + ('3VarAddA1', _3VarAddA1_data), + ('3VarAddA2', _3VarAddA2_data), + ]} + +cmap_families = { + '2VarAddA': MultivarColormap([cmaps[f'2VarAddA{i}'] for i in range(2)], + 'sRGB_add', name='2VarAddA'), + '2VarSubA': MultivarColormap([cmaps[f'2VarSubA{i}'] for i in range(2)], + 'sRGB_sub', name='2VarSubA'), + '3VarAddA': MultivarColormap([cmaps[f'3VarAddA{i}'] for i in range(3)], + 'sRGB_add', name='3VarAddA'), +} diff --git a/shared/package-files/d1/d1492a222e1e8710f76a8037cfbcbcfb77693acea8df4fc6a7cad9bc55f55bd4/blob b/shared/package-files/d1/d1492a222e1e8710f76a8037cfbcbcfb77693acea8df4fc6a7cad9bc55f55bd4/blob new file mode 100644 index 0000000000000000000000000000000000000000..e74ff89b115817f859ed7334e8f04170c8f20dd2 --- /dev/null +++ b/shared/package-files/d1/d1492a222e1e8710f76a8037cfbcbcfb77693acea8df4fc6a7cad9bc55f55bd4/blob @@ -0,0 +1,141 @@ +""" +Tests for the `deprecate_nonkeyword_arguments` decorator +""" + +import inspect + +from pandas.util._decorators import deprecate_nonkeyword_arguments + +import pandas._testing as tm + + +@deprecate_nonkeyword_arguments( + version="1.1", allowed_args=["a", "b"], name="f_add_inputs" +) +def f(a, b=0, c=0, d=0): + return a + b + c + d + + +def test_f_signature(): + assert str(inspect.signature(f)) == "(a, b=0, *, c=0, d=0)" + + +def test_one_argument(): + with tm.assert_produces_warning(None): + assert f(19) == 19 + + +def test_one_and_one_arguments(): + with tm.assert_produces_warning(None): + assert f(19, d=6) == 25 + + +def test_two_arguments(): + with tm.assert_produces_warning(None): + assert f(1, 5) == 6 + + +def test_two_and_two_arguments(): + with tm.assert_produces_warning(None): + assert f(1, 3, c=3, d=5) == 12 + + +def test_three_arguments(): + with tm.assert_produces_warning(FutureWarning): + assert f(6, 3, 3) == 12 + + +def test_four_arguments(): + with tm.assert_produces_warning(FutureWarning): + assert f(1, 2, 3, 4) == 10 + + +def test_three_arguments_with_name_in_warning(): + msg = ( + "Starting with pandas version 1.1 all arguments of f_add_inputs " + "except for the arguments 'a' and 'b' will be keyword-only." + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + assert f(6, 3, 3) == 12 + + +@deprecate_nonkeyword_arguments(version="1.1") +def g(a, b=0, c=0, d=0): + with tm.assert_produces_warning(None): + return a + b + c + d + + +def test_g_signature(): + assert str(inspect.signature(g)) == "(a, *, b=0, c=0, d=0)" + + +def test_one_and_three_arguments_default_allowed_args(): + with tm.assert_produces_warning(None): + assert g(1, b=3, c=3, d=5) == 12 + + +def test_three_arguments_default_allowed_args(): + with tm.assert_produces_warning(FutureWarning): + assert g(6, 3, 3) == 12 + + +def test_three_positional_argument_with_warning_message_analysis(): + msg = ( + "Starting with pandas version 1.1 all arguments of g " + "except for the argument 'a' will be keyword-only." + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + assert g(6, 3, 3) == 12 + + +@deprecate_nonkeyword_arguments(version="1.1") +def h(a=0, b=0, c=0, d=0): + return a + b + c + d + + +def test_h_signature(): + assert str(inspect.signature(h)) == "(*, a=0, b=0, c=0, d=0)" + + +def test_all_keyword_arguments(): + with tm.assert_produces_warning(None): + assert h(a=1, b=2) == 3 + + +def test_one_positional_argument(): + with tm.assert_produces_warning(FutureWarning): + assert h(23) == 23 + + +def test_one_positional_argument_with_warning_message_analysis(): + msg = "Starting with pandas version 1.1 all arguments of h will be keyword-only." + with tm.assert_produces_warning(FutureWarning, match=msg): + assert h(19) == 19 + + +@deprecate_nonkeyword_arguments(version="1.1") +def i(a=0, /, b=0, *, c=0, d=0): + return a + b + c + d + + +def test_i_signature(): + assert str(inspect.signature(i)) == "(*, a=0, b=0, c=0, d=0)" + + +class Foo: + @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "bar"]) + def baz(self, bar=None, foobar=None): # pylint: disable=disallowed-name + ... + + +def test_foo_signature(): + assert str(inspect.signature(Foo.baz)) == "(self, bar=None, *, foobar=None)" + + +def test_class(): + msg = ( + r"In a future version of pandas all arguments of Foo\.baz " + r"except for the argument \'bar\' will be keyword-only" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + Foo().baz("qux", "quox") diff --git a/shared/package-files/d1/d149aa22ddbebbc5b036402ab27395b7d565901f4ad024482588906a5b49ef7c/blob b/shared/package-files/d1/d149aa22ddbebbc5b036402ab27395b7d565901f4ad024482588906a5b49ef7c/blob new file mode 100644 index 0000000000000000000000000000000000000000..d2d83d452fd30e718546c0eac26fe03bbef59c06 --- /dev/null +++ b/shared/package-files/d1/d149aa22ddbebbc5b036402ab27395b7d565901f4ad024482588906a5b49ef7c/blob @@ -0,0 +1,38 @@ +__all__ = [ + 'TWave', + + 'RayTransferMatrix', 'FreeSpace', 'FlatRefraction', 'CurvedRefraction', + 'FlatMirror', 'CurvedMirror', 'ThinLens', 'GeometricRay', 'BeamParameter', + 'waist2rayleigh', 'rayleigh2waist', 'geometric_conj_ab', + 'geometric_conj_af', 'geometric_conj_bf', 'gaussian_conj', + 'conjugate_gauss_beams', + + 'Medium', + + 'refraction_angle', 'deviation', 'fresnel_coefficients', 'brewster_angle', + 'critical_angle', 'lens_makers_formula', 'mirror_formula', 'lens_formula', + 'hyperfocal_distance', 'transverse_magnification', + + 'jones_vector', 'stokes_vector', 'jones_2_stokes', 'linear_polarizer', + 'phase_retarder', 'half_wave_retarder', 'quarter_wave_retarder', + 'transmissive_filter', 'reflective_filter', 'mueller_matrix', + 'polarizing_beam_splitter', +] +from .waves import TWave + +from .gaussopt import (RayTransferMatrix, FreeSpace, FlatRefraction, + CurvedRefraction, FlatMirror, CurvedMirror, ThinLens, GeometricRay, + BeamParameter, waist2rayleigh, rayleigh2waist, geometric_conj_ab, + geometric_conj_af, geometric_conj_bf, gaussian_conj, + conjugate_gauss_beams) + +from .medium import Medium + +from .utils import (refraction_angle, deviation, fresnel_coefficients, + brewster_angle, critical_angle, lens_makers_formula, mirror_formula, + lens_formula, hyperfocal_distance, transverse_magnification) + +from .polarization import (jones_vector, stokes_vector, jones_2_stokes, + linear_polarizer, phase_retarder, half_wave_retarder, + quarter_wave_retarder, transmissive_filter, reflective_filter, + mueller_matrix, polarizing_beam_splitter) diff --git a/shared/package-files/d1/d149e6d08153ec7c86790ec5def4daffe9257f2b0282bba5a853ba043d699595/blob b/shared/package-files/d1/d149e6d08153ec7c86790ec5def4daffe9257f2b0282bba5a853ba043d699595/blob new file mode 100644 index 0000000000000000000000000000000000000000..f7f10ab7665e94ca44fd8cd98a362cd4b304eff1 Binary files /dev/null and b/shared/package-files/d1/d149e6d08153ec7c86790ec5def4daffe9257f2b0282bba5a853ba043d699595/blob differ diff --git a/shared/package-files/d1/d14b4ebc1555a119f8520c4472cacb7d26258da29873ff2265f23fc5e38207a8/blob b/shared/package-files/d1/d14b4ebc1555a119f8520c4472cacb7d26258da29873ff2265f23fc5e38207a8/blob new file mode 100644 index 0000000000000000000000000000000000000000..b895f930ec2981d895ad77ead64e5ab9a9340f99 --- /dev/null +++ b/shared/package-files/d1/d14b4ebc1555a119f8520c4472cacb7d26258da29873ff2265f23fc5e38207a8/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API void lstm_mps_backward_out(at::Tensor & out0, at::TensorList out1, at::TensorList out2, const c10::optional & grad_y, const c10::optional & grad_hy, const c10::optional & grad_cy, const at::Tensor & z_state, const at::Tensor & cell_state_fwd, const at::Tensor & input, const at::Tensor & layersOutputs, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first); +TORCH_API void lstm_mps_backward_outf(const c10::optional & grad_y, const c10::optional & grad_hy, const c10::optional & grad_cy, const at::Tensor & z_state, const at::Tensor & cell_state_fwd, const at::Tensor & input, const at::Tensor & layersOutputs, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first, at::Tensor & out0, at::TensorList out1, at::TensorList out2); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/d1/d14d03282c4a4f7523cf03d2722d0dd0d0384ec57515a9c3794822758a48797f/blob b/shared/package-files/d1/d14d03282c4a4f7523cf03d2722d0dd0d0384ec57515a9c3794822758a48797f/blob new file mode 100644 index 0000000000000000000000000000000000000000..7c13cebb8b4c922364986f7bdf12f4c70561c319 --- /dev/null +++ b/shared/package-files/d1/d14d03282c4a4f7523cf03d2722d0dd0d0384ec57515a9c3794822758a48797f/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor median(const at::Tensor & self); +TORCH_API ::std::tuple median_out(at::Tensor & values, at::Tensor & indices, const at::Tensor & self, int64_t dim, bool keepdim=false); +TORCH_API ::std::tuple median_outf(const at::Tensor & self, int64_t dim, bool keepdim, at::Tensor & values, at::Tensor & indices); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/d1/d14efc6a23bdcef18eaea43bb62553521aa7a63d050c3f6c84d6fef003a1a7af/blob b/shared/package-files/d1/d14efc6a23bdcef18eaea43bb62553521aa7a63d050c3f6c84d6fef003a1a7af/blob new file mode 100644 index 0000000000000000000000000000000000000000..7d5afd116ba4b061b47baf40a31671797770e8c3 --- /dev/null +++ b/shared/package-files/d1/d14efc6a23bdcef18eaea43bb62553521aa7a63d050c3f6c84d6fef003a1a7af/blob @@ -0,0 +1,816 @@ +from sympy.core.function import (diff, expand, expand_func) +from sympy.core import EulerGamma +from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi) +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.complexes import (conjugate, im, polar_lift, re) +from sympy.functions.elementary.exponential import (exp, exp_polar, log) +from sympy.functions.elementary.hyperbolic import (cosh, sinh) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin, sinc) +from sympy.functions.special.error_functions import (Chi, Ci, E1, Ei, Li, Shi, Si, erf, erf2, erf2inv, erfc, erfcinv, erfi, erfinv, expint, fresnelc, fresnels, li) +from sympy.functions.special.gamma_functions import (gamma, uppergamma) +from sympy.functions.special.hyper import (hyper, meijerg) +from sympy.integrals.integrals import (Integral, integrate) +from sympy.series.gruntz import gruntz +from sympy.series.limits import limit +from sympy.series.order import O +from sympy.core.expr import unchanged +from sympy.core.function import ArgumentIndexError +from sympy.functions.special.error_functions import _erfs, _eis +from sympy.testing.pytest import raises + +x, y, z = symbols('x,y,z') +w = Symbol("w", real=True) +n = Symbol("n", integer=True) + + +def test_erf(): + assert erf(nan) is nan + + assert erf(oo) == 1 + assert erf(-oo) == -1 + + assert erf(0) is S.Zero + + assert erf(I*oo) == oo*I + assert erf(-I*oo) == -oo*I + + assert erf(-2) == -erf(2) + assert erf(-x*y) == -erf(x*y) + assert erf(-x - y) == -erf(x + y) + + assert erf(erfinv(x)) == x + assert erf(erfcinv(x)) == 1 - x + assert erf(erf2inv(0, x)) == x + assert erf(erf2inv(0, x, evaluate=False)) == x # To cover code in erf + assert erf(erf2inv(0, erf(erfcinv(1 - erf(erfinv(x)))))) == x + + assert erf(I).is_real is False + assert erf(0, evaluate=False).is_real + assert erf(0, evaluate=False).is_zero + + assert conjugate(erf(z)) == erf(conjugate(z)) + + assert erf(x).as_leading_term(x) == 2*x/sqrt(pi) + assert erf(x*y).as_leading_term(y) == 2*x*y/sqrt(pi) + assert (erf(x*y)/erf(y)).as_leading_term(y) == x + assert erf(1/x).as_leading_term(x) == S.One + + assert erf(z).rewrite('uppergamma') == sqrt(z**2)*(1 - erfc(sqrt(z**2)))/z + assert erf(z).rewrite('erfc') == S.One - erfc(z) + assert erf(z).rewrite('erfi') == -I*erfi(I*z) + assert erf(z).rewrite('fresnels') == (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - + I*fresnels(z*(1 - I)/sqrt(pi))) + assert erf(z).rewrite('fresnelc') == (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - + I*fresnels(z*(1 - I)/sqrt(pi))) + assert erf(z).rewrite('hyper') == 2*z*hyper([S.Half], [3*S.Half], -z**2)/sqrt(pi) + assert erf(z).rewrite('meijerg') == z*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)/sqrt(pi) + assert erf(z).rewrite('expint') == sqrt(z**2)/z - z*expint(S.Half, z**2)/sqrt(S.Pi) + + assert limit(exp(x)*exp(x**2)*(erf(x + 1/exp(x)) - erf(x)), x, oo) == \ + 2/sqrt(pi) + assert limit((1 - erf(z))*exp(z**2)*z, z, oo) == 1/sqrt(pi) + assert limit((1 - erf(x))*exp(x**2)*sqrt(pi)*x, x, oo) == 1 + assert limit(((1 - erf(x))*exp(x**2)*sqrt(pi)*x - 1)*2*x**2, x, oo) == -1 + assert limit(erf(x)/x, x, 0) == 2/sqrt(pi) + assert limit(x**(-4) - sqrt(pi)*erf(x**2) / (2*x**6), x, 0) == S(1)/3 + + assert erf(x).as_real_imag() == \ + (erf(re(x) - I*im(x))/2 + erf(re(x) + I*im(x))/2, + -I*(-erf(re(x) - I*im(x)) + erf(re(x) + I*im(x)))/2) + + assert erf(x).as_real_imag(deep=False) == \ + (erf(re(x) - I*im(x))/2 + erf(re(x) + I*im(x))/2, + -I*(-erf(re(x) - I*im(x)) + erf(re(x) + I*im(x)))/2) + + assert erf(w).as_real_imag() == (erf(w), 0) + assert erf(w).as_real_imag(deep=False) == (erf(w), 0) + # issue 13575 + assert erf(I).as_real_imag() == (0, -I*erf(I)) + + raises(ArgumentIndexError, lambda: erf(x).fdiff(2)) + + assert erf(x).inverse() == erfinv + + +def test_erf_series(): + assert erf(x).series(x, 0, 7) == 2*x/sqrt(pi) - \ + 2*x**3/3/sqrt(pi) + x**5/5/sqrt(pi) + O(x**7) + + assert erf(x).series(x, oo) == \ + -exp(-x**2)*(3/(4*x**5) - 1/(2*x**3) + 1/x + O(x**(-6), (x, oo)))/sqrt(pi) + 1 + assert erf(x**2).series(x, oo, n=8) == \ + (-1/(2*x**6) + x**(-2) + O(x**(-8), (x, oo)))*exp(-x**4)/sqrt(pi)*-1 + 1 + assert erf(sqrt(x)).series(x, oo, n=3) == (sqrt(1/x) - (1/x)**(S(3)/2)/2\ + + 3*(1/x)**(S(5)/2)/4 + O(x**(-3), (x, oo)))*exp(-x)/sqrt(pi)*-1 + 1 + + +def test_erf_evalf(): + assert abs( erf(Float(2.0)) - 0.995322265 ) < 1E-8 # XXX + + +def test__erfs(): + assert _erfs(z).diff(z) == -2/sqrt(S.Pi) + 2*z*_erfs(z) + + assert _erfs(1/z).series(z) == \ + z/sqrt(pi) - z**3/(2*sqrt(pi)) + 3*z**5/(4*sqrt(pi)) + O(z**6) + + assert expand(erf(z).rewrite('tractable').diff(z).rewrite('intractable')) \ + == erf(z).diff(z) + assert _erfs(z).rewrite("intractable") == (-erf(z) + 1)*exp(z**2) + raises(ArgumentIndexError, lambda: _erfs(z).fdiff(2)) + + +def test_erfc(): + assert erfc(nan) is nan + + assert erfc(oo) is S.Zero + assert erfc(-oo) == 2 + + assert erfc(0) == 1 + + assert erfc(I*oo) == -oo*I + assert erfc(-I*oo) == oo*I + + assert erfc(-x) == S(2) - erfc(x) + assert erfc(erfcinv(x)) == x + + assert erfc(I).is_real is False + assert erfc(0, evaluate=False).is_real + assert erfc(0, evaluate=False).is_zero is False + + assert erfc(erfinv(x)) == 1 - x + + assert conjugate(erfc(z)) == erfc(conjugate(z)) + + assert erfc(x).as_leading_term(x) is S.One + assert erfc(1/x).as_leading_term(x) == S.Zero + + assert erfc(z).rewrite('erf') == 1 - erf(z) + assert erfc(z).rewrite('erfi') == 1 + I*erfi(I*z) + assert erfc(z).rewrite('fresnels') == 1 - (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - + I*fresnels(z*(1 - I)/sqrt(pi))) + assert erfc(z).rewrite('fresnelc') == 1 - (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - + I*fresnels(z*(1 - I)/sqrt(pi))) + assert erfc(z).rewrite('hyper') == 1 - 2*z*hyper([S.Half], [3*S.Half], -z**2)/sqrt(pi) + assert erfc(z).rewrite('meijerg') == 1 - z*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)/sqrt(pi) + assert erfc(z).rewrite('uppergamma') == 1 - sqrt(z**2)*(1 - erfc(sqrt(z**2)))/z + assert erfc(z).rewrite('expint') == S.One - sqrt(z**2)/z + z*expint(S.Half, z**2)/sqrt(S.Pi) + assert erfc(z).rewrite('tractable') == _erfs(z)*exp(-z**2) + assert expand_func(erf(x) + erfc(x)) is S.One + + assert erfc(x).as_real_imag() == \ + (erfc(re(x) - I*im(x))/2 + erfc(re(x) + I*im(x))/2, + -I*(-erfc(re(x) - I*im(x)) + erfc(re(x) + I*im(x)))/2) + + assert erfc(x).as_real_imag(deep=False) == \ + (erfc(re(x) - I*im(x))/2 + erfc(re(x) + I*im(x))/2, + -I*(-erfc(re(x) - I*im(x)) + erfc(re(x) + I*im(x)))/2) + + assert erfc(w).as_real_imag() == (erfc(w), 0) + assert erfc(w).as_real_imag(deep=False) == (erfc(w), 0) + raises(ArgumentIndexError, lambda: erfc(x).fdiff(2)) + + assert erfc(x).inverse() == erfcinv + + +def test_erfc_series(): + assert erfc(x).series(x, 0, 7) == 1 - 2*x/sqrt(pi) + \ + 2*x**3/3/sqrt(pi) - x**5/5/sqrt(pi) + O(x**7) + + assert erfc(x).series(x, oo) == \ + (3/(4*x**5) - 1/(2*x**3) + 1/x + O(x**(-6), (x, oo)))*exp(-x**2)/sqrt(pi) + + +def test_erfc_evalf(): + assert abs( erfc(Float(2.0)) - 0.00467773 ) < 1E-8 # XXX + + +def test_erfi(): + assert erfi(nan) is nan + + assert erfi(oo) is S.Infinity + assert erfi(-oo) is S.NegativeInfinity + + assert erfi(0) is S.Zero + + assert erfi(I*oo) == I + assert erfi(-I*oo) == -I + + assert erfi(-x) == -erfi(x) + + assert erfi(I*erfinv(x)) == I*x + assert erfi(I*erfcinv(x)) == I*(1 - x) + assert erfi(I*erf2inv(0, x)) == I*x + assert erfi(I*erf2inv(0, x, evaluate=False)) == I*x # To cover code in erfi + + assert erfi(I).is_real is False + assert erfi(0, evaluate=False).is_real + assert erfi(0, evaluate=False).is_zero + + assert conjugate(erfi(z)) == erfi(conjugate(z)) + + assert erfi(x).as_leading_term(x) == 2*x/sqrt(pi) + assert erfi(x*y).as_leading_term(y) == 2*x*y/sqrt(pi) + assert (erfi(x*y)/erfi(y)).as_leading_term(y) == x + assert erfi(1/x).as_leading_term(x) == erfi(1/x) + + assert erfi(z).rewrite('erf') == -I*erf(I*z) + assert erfi(z).rewrite('erfc') == I*erfc(I*z) - I + assert erfi(z).rewrite('fresnels') == (1 - I)*(fresnelc(z*(1 + I)/sqrt(pi)) - + I*fresnels(z*(1 + I)/sqrt(pi))) + assert erfi(z).rewrite('fresnelc') == (1 - I)*(fresnelc(z*(1 + I)/sqrt(pi)) - + I*fresnels(z*(1 + I)/sqrt(pi))) + assert erfi(z).rewrite('hyper') == 2*z*hyper([S.Half], [3*S.Half], z**2)/sqrt(pi) + assert erfi(z).rewrite('meijerg') == z*meijerg([S.Half], [], [0], [Rational(-1, 2)], -z**2)/sqrt(pi) + assert erfi(z).rewrite('uppergamma') == (sqrt(-z**2)/z*(uppergamma(S.Half, + -z**2)/sqrt(S.Pi) - S.One)) + assert erfi(z).rewrite('expint') == sqrt(-z**2)/z - z*expint(S.Half, -z**2)/sqrt(S.Pi) + assert erfi(z).rewrite('tractable') == -I*(-_erfs(I*z)*exp(z**2) + 1) + assert expand_func(erfi(I*z)) == I*erf(z) + + assert erfi(x).as_real_imag() == \ + (erfi(re(x) - I*im(x))/2 + erfi(re(x) + I*im(x))/2, + -I*(-erfi(re(x) - I*im(x)) + erfi(re(x) + I*im(x)))/2) + assert erfi(x).as_real_imag(deep=False) == \ + (erfi(re(x) - I*im(x))/2 + erfi(re(x) + I*im(x))/2, + -I*(-erfi(re(x) - I*im(x)) + erfi(re(x) + I*im(x)))/2) + + assert erfi(w).as_real_imag() == (erfi(w), 0) + assert erfi(w).as_real_imag(deep=False) == (erfi(w), 0) + + raises(ArgumentIndexError, lambda: erfi(x).fdiff(2)) + + +def test_erfi_series(): + assert erfi(x).series(x, 0, 7) == 2*x/sqrt(pi) + \ + 2*x**3/3/sqrt(pi) + x**5/5/sqrt(pi) + O(x**7) + + assert erfi(x).series(x, oo) == \ + (3/(4*x**5) + 1/(2*x**3) + 1/x + O(x**(-6), (x, oo)))*exp(x**2)/sqrt(pi) - I + + +def test_erfi_evalf(): + assert abs( erfi(Float(2.0)) - 18.5648024145756 ) < 1E-13 # XXX + + +def test_erf2(): + + assert erf2(0, 0) is S.Zero + assert erf2(x, x) is S.Zero + assert erf2(nan, 0) is nan + + assert erf2(-oo, y) == erf(y) + 1 + assert erf2( oo, y) == erf(y) - 1 + assert erf2( x, oo) == 1 - erf(x) + assert erf2( x,-oo) == -1 - erf(x) + assert erf2(x, erf2inv(x, y)) == y + + assert erf2(-x, -y) == -erf2(x,y) + assert erf2(-x, y) == erf(y) + erf(x) + assert erf2( x, -y) == -erf(y) - erf(x) + assert erf2(x, y).rewrite('fresnels') == erf(y).rewrite(fresnels)-erf(x).rewrite(fresnels) + assert erf2(x, y).rewrite('fresnelc') == erf(y).rewrite(fresnelc)-erf(x).rewrite(fresnelc) + assert erf2(x, y).rewrite('hyper') == erf(y).rewrite(hyper)-erf(x).rewrite(hyper) + assert erf2(x, y).rewrite('meijerg') == erf(y).rewrite(meijerg)-erf(x).rewrite(meijerg) + assert erf2(x, y).rewrite('uppergamma') == erf(y).rewrite(uppergamma) - erf(x).rewrite(uppergamma) + assert erf2(x, y).rewrite('expint') == erf(y).rewrite(expint)-erf(x).rewrite(expint) + + assert erf2(I, 0).is_real is False + assert erf2(0, 0, evaluate=False).is_real + assert erf2(0, 0, evaluate=False).is_zero + assert erf2(x, x, evaluate=False).is_zero + assert erf2(x, y).is_zero is None + + assert expand_func(erf(x) + erf2(x, y)) == erf(y) + + assert conjugate(erf2(x, y)) == erf2(conjugate(x), conjugate(y)) + + assert erf2(x, y).rewrite('erf') == erf(y) - erf(x) + assert erf2(x, y).rewrite('erfc') == erfc(x) - erfc(y) + assert erf2(x, y).rewrite('erfi') == I*(erfi(I*x) - erfi(I*y)) + + assert erf2(x, y).diff(x) == erf2(x, y).fdiff(1) + assert erf2(x, y).diff(y) == erf2(x, y).fdiff(2) + assert erf2(x, y).diff(x) == -2*exp(-x**2)/sqrt(pi) + assert erf2(x, y).diff(y) == 2*exp(-y**2)/sqrt(pi) + raises(ArgumentIndexError, lambda: erf2(x, y).fdiff(3)) + + assert erf2(x, y).is_extended_real is None + xr, yr = symbols('xr yr', extended_real=True) + assert erf2(xr, yr).is_extended_real is True + + +def test_erfinv(): + assert erfinv(0) is S.Zero + assert erfinv(1) is S.Infinity + assert erfinv(nan) is S.NaN + assert erfinv(-1) is S.NegativeInfinity + + assert erfinv(erf(w)) == w + assert erfinv(erf(-w)) == -w + + assert erfinv(x).diff() == sqrt(pi)*exp(erfinv(x)**2)/2 + raises(ArgumentIndexError, lambda: erfinv(x).fdiff(2)) + + assert erfinv(z).rewrite('erfcinv') == erfcinv(1-z) + assert erfinv(z).inverse() == erf + + +def test_erfinv_evalf(): + assert abs( erfinv(Float(0.2)) - 0.179143454621292 ) < 1E-13 + + +def test_erfcinv(): + assert erfcinv(1) is S.Zero + assert erfcinv(0) is S.Infinity + assert erfcinv(nan) is S.NaN + + assert erfcinv(x).diff() == -sqrt(pi)*exp(erfcinv(x)**2)/2 + raises(ArgumentIndexError, lambda: erfcinv(x).fdiff(2)) + + assert erfcinv(z).rewrite('erfinv') == erfinv(1-z) + assert erfcinv(z).inverse() == erfc + + +def test_erf2inv(): + assert erf2inv(0, 0) is S.Zero + assert erf2inv(0, 1) is S.Infinity + assert erf2inv(1, 0) is S.One + assert erf2inv(0, y) == erfinv(y) + assert erf2inv(oo, y) == erfcinv(-y) + assert erf2inv(x, 0) == x + assert erf2inv(x, oo) == erfinv(x) + assert erf2inv(nan, 0) is nan + assert erf2inv(0, nan) is nan + + assert erf2inv(x, y).diff(x) == exp(-x**2 + erf2inv(x, y)**2) + assert erf2inv(x, y).diff(y) == sqrt(pi)*exp(erf2inv(x, y)**2)/2 + raises(ArgumentIndexError, lambda: erf2inv(x, y).fdiff(3)) + + +# NOTE we multiply by exp_polar(I*pi) and need this to be on the principal +# branch, hence take x in the lower half plane (d=0). + + +def mytn(expr1, expr2, expr3, x, d=0): + from sympy.core.random import verify_numerically, random_complex_number + subs = {} + for a in expr1.free_symbols: + if a != x: + subs[a] = random_complex_number() + return expr2 == expr3 and verify_numerically(expr1.subs(subs), + expr2.subs(subs), x, d=d) + + +def mytd(expr1, expr2, x): + from sympy.core.random import test_derivative_numerically, \ + random_complex_number + subs = {} + for a in expr1.free_symbols: + if a != x: + subs[a] = random_complex_number() + return expr1.diff(x) == expr2 and test_derivative_numerically(expr1.subs(subs), x) + + +def tn_branch(func, s=None): + from sympy.core.random import uniform + + def fn(x): + if s is None: + return func(x) + return func(s, x) + c = uniform(1, 5) + expr = fn(c*exp_polar(I*pi)) - fn(c*exp_polar(-I*pi)) + eps = 1e-15 + expr2 = fn(-c + eps*I) - fn(-c - eps*I) + return abs(expr.n() - expr2.n()).n() < 1e-10 + + +def test_ei(): + assert Ei(0) is S.NegativeInfinity + assert Ei(oo) is S.Infinity + assert Ei(-oo) is S.Zero + + assert tn_branch(Ei) + assert mytd(Ei(x), exp(x)/x, x) + assert mytn(Ei(x), Ei(x).rewrite(uppergamma), + -uppergamma(0, x*polar_lift(-1)) - I*pi, x) + assert mytn(Ei(x), Ei(x).rewrite(expint), + -expint(1, x*polar_lift(-1)) - I*pi, x) + assert Ei(x).rewrite(expint).rewrite(Ei) == Ei(x) + assert Ei(x*exp_polar(2*I*pi)) == Ei(x) + 2*I*pi + assert Ei(x*exp_polar(-2*I*pi)) == Ei(x) - 2*I*pi + + assert mytn(Ei(x), Ei(x).rewrite(Shi), Chi(x) + Shi(x), x) + assert mytn(Ei(x*polar_lift(I)), Ei(x*polar_lift(I)).rewrite(Si), + Ci(x) + I*Si(x) + I*pi/2, x) + + assert Ei(log(x)).rewrite(li) == li(x) + assert Ei(2*log(x)).rewrite(li) == li(x**2) + + assert gruntz(Ei(x+exp(-x))*exp(-x)*x, x, oo) == 1 + + assert Ei(x).series(x) == EulerGamma + log(x) + x + x**2/4 + \ + x**3/18 + x**4/96 + x**5/600 + O(x**6) + assert Ei(x).series(x, 1, 3) == Ei(1) + E*(x - 1) + O((x - 1)**3, (x, 1)) + assert Ei(x).series(x, oo) == \ + (120/x**5 + 24/x**4 + 6/x**3 + 2/x**2 + 1/x + 1 + O(x**(-6), (x, oo)))*exp(x)/x + + assert str(Ei(cos(2)).evalf(n=10)) == '-0.6760647401' + raises(ArgumentIndexError, lambda: Ei(x).fdiff(2)) + + +def test_expint(): + assert mytn(expint(x, y), expint(x, y).rewrite(uppergamma), + y**(x - 1)*uppergamma(1 - x, y), x) + assert mytd( + expint(x, y), -y**(x - 1)*meijerg([], [1, 1], [0, 0, 1 - x], [], y), x) + assert mytd(expint(x, y), -expint(x - 1, y), y) + assert mytn(expint(1, x), expint(1, x).rewrite(Ei), + -Ei(x*polar_lift(-1)) + I*pi, x) + + assert expint(-4, x) == exp(-x)/x + 4*exp(-x)/x**2 + 12*exp(-x)/x**3 \ + + 24*exp(-x)/x**4 + 24*exp(-x)/x**5 + assert expint(Rational(-3, 2), x) == \ + exp(-x)/x + 3*exp(-x)/(2*x**2) + 3*sqrt(pi)*erfc(sqrt(x))/(4*x**S('5/2')) + + assert tn_branch(expint, 1) + assert tn_branch(expint, 2) + assert tn_branch(expint, 3) + assert tn_branch(expint, 1.7) + assert tn_branch(expint, pi) + + assert expint(y, x*exp_polar(2*I*pi)) == \ + x**(y - 1)*(exp(2*I*pi*y) - 1)*gamma(-y + 1) + expint(y, x) + assert expint(y, x*exp_polar(-2*I*pi)) == \ + x**(y - 1)*(exp(-2*I*pi*y) - 1)*gamma(-y + 1) + expint(y, x) + assert expint(2, x*exp_polar(2*I*pi)) == 2*I*pi*x + expint(2, x) + assert expint(2, x*exp_polar(-2*I*pi)) == -2*I*pi*x + expint(2, x) + assert expint(1, x).rewrite(Ei).rewrite(expint) == expint(1, x) + assert expint(x, y).rewrite(Ei) == expint(x, y) + assert expint(x, y).rewrite(Ci) == expint(x, y) + + assert mytn(E1(x), E1(x).rewrite(Shi), Shi(x) - Chi(x), x) + assert mytn(E1(polar_lift(I)*x), E1(polar_lift(I)*x).rewrite(Si), + -Ci(x) + I*Si(x) - I*pi/2, x) + + assert mytn(expint(2, x), expint(2, x).rewrite(Ei).rewrite(expint), + -x*E1(x) + exp(-x), x) + assert mytn(expint(3, x), expint(3, x).rewrite(Ei).rewrite(expint), + x**2*E1(x)/2 + (1 - x)*exp(-x)/2, x) + + assert expint(Rational(3, 2), z).nseries(z) == \ + 2 + 2*z - z**2/3 + z**3/15 - z**4/84 + z**5/540 - \ + 2*sqrt(pi)*sqrt(z) + O(z**6) + + assert E1(z).series(z) == -EulerGamma - log(z) + z - \ + z**2/4 + z**3/18 - z**4/96 + z**5/600 + O(z**6) + + assert expint(4, z).series(z) == Rational(1, 3) - z/2 + z**2/2 + \ + z**3*(log(z)/6 - Rational(11, 36) + EulerGamma/6 - I*pi/6) - z**4/24 + \ + z**5/240 + O(z**6) + + assert expint(n, x).series(x, oo, n=3) == \ + (n*(n + 1)/x**2 - n/x + 1 + O(x**(-3), (x, oo)))*exp(-x)/x + + assert expint(z, y).series(z, 0, 2) == exp(-y)/y - z*meijerg(((), (1, 1)), + ((0, 0, 1), ()), y)/y + O(z**2) + raises(ArgumentIndexError, lambda: expint(x, y).fdiff(3)) + + neg = Symbol('neg', negative=True) + assert Ei(neg).rewrite(Si) == Shi(neg) + Chi(neg) - I*pi + + +def test__eis(): + assert _eis(z).diff(z) == -_eis(z) + 1/z + + assert _eis(1/z).series(z) == \ + z + z**2 + 2*z**3 + 6*z**4 + 24*z**5 + O(z**6) + + assert Ei(z).rewrite('tractable') == exp(z)*_eis(z) + assert li(z).rewrite('tractable') == z*_eis(log(z)) + + assert _eis(z).rewrite('intractable') == exp(-z)*Ei(z) + + assert expand(li(z).rewrite('tractable').diff(z).rewrite('intractable')) \ + == li(z).diff(z) + + assert expand(Ei(z).rewrite('tractable').diff(z).rewrite('intractable')) \ + == Ei(z).diff(z) + + assert _eis(z).series(z, n=3) == EulerGamma + log(z) + z*(-log(z) - \ + EulerGamma + 1) + z**2*(log(z)/2 - Rational(3, 4) + EulerGamma/2)\ + + O(z**3*log(z)) + raises(ArgumentIndexError, lambda: _eis(z).fdiff(2)) + + +def tn_arg(func): + def test(arg, e1, e2): + from sympy.core.random import uniform + v = uniform(1, 5) + v1 = func(arg*x).subs(x, v).n() + v2 = func(e1*v + e2*1e-15).n() + return abs(v1 - v2).n() < 1e-10 + return test(exp_polar(I*pi/2), I, 1) and \ + test(exp_polar(-I*pi/2), -I, 1) and \ + test(exp_polar(I*pi), -1, I) and \ + test(exp_polar(-I*pi), -1, -I) + + +def test_li(): + z = Symbol("z") + zr = Symbol("z", real=True) + zp = Symbol("z", positive=True) + zn = Symbol("z", negative=True) + + assert li(0) is S.Zero + assert li(1) is -oo + assert li(oo) is oo + + assert isinstance(li(z), li) + assert unchanged(li, -zp) + assert unchanged(li, zn) + + assert diff(li(z), z) == 1/log(z) + + assert conjugate(li(z)) == li(conjugate(z)) + assert conjugate(li(-zr)) == li(-zr) + assert unchanged(conjugate, li(-zp)) + assert unchanged(conjugate, li(zn)) + + assert li(z).rewrite(Li) == Li(z) + li(2) + assert li(z).rewrite(Ei) == Ei(log(z)) + assert li(z).rewrite(uppergamma) == (-log(1/log(z))/2 - log(-log(z)) + + log(log(z))/2 - expint(1, -log(z))) + assert li(z).rewrite(Si) == (-log(I*log(z)) - log(1/log(z))/2 + + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z))) + assert li(z).rewrite(Ci) == (-log(I*log(z)) - log(1/log(z))/2 + + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z))) + assert li(z).rewrite(Shi) == (-log(1/log(z))/2 + log(log(z))/2 + + Chi(log(z)) - Shi(log(z))) + assert li(z).rewrite(Chi) == (-log(1/log(z))/2 + log(log(z))/2 + + Chi(log(z)) - Shi(log(z))) + assert li(z).rewrite(hyper) ==(log(z)*hyper((1, 1), (2, 2), log(z)) - + log(1/log(z))/2 + log(log(z))/2 + EulerGamma) + assert li(z).rewrite(meijerg) == (-log(1/log(z))/2 - log(-log(z)) + log(log(z))/2 - + meijerg(((), (1,)), ((0, 0), ()), -log(z))) + + assert gruntz(1/li(z), z, oo) is S.Zero + assert li(z).series(z) == log(z)**5/600 + log(z)**4/96 + log(z)**3/18 + log(z)**2/4 + \ + log(z) + log(log(z)) + EulerGamma + raises(ArgumentIndexError, lambda: li(z).fdiff(2)) + + +def test_Li(): + assert Li(2) is S.Zero + assert Li(oo) is oo + + assert isinstance(Li(z), Li) + + assert diff(Li(z), z) == 1/log(z) + + assert gruntz(1/Li(z), z, oo) is S.Zero + assert Li(z).rewrite(li) == li(z) - li(2) + assert Li(z).series(z) == \ + log(z)**5/600 + log(z)**4/96 + log(z)**3/18 + log(z)**2/4 + log(z) + log(log(z)) - li(2) + EulerGamma + raises(ArgumentIndexError, lambda: Li(z).fdiff(2)) + + +def test_si(): + assert Si(I*x) == I*Shi(x) + assert Shi(I*x) == I*Si(x) + assert Si(-I*x) == -I*Shi(x) + assert Shi(-I*x) == -I*Si(x) + assert Si(-x) == -Si(x) + assert Shi(-x) == -Shi(x) + assert Si(exp_polar(2*pi*I)*x) == Si(x) + assert Si(exp_polar(-2*pi*I)*x) == Si(x) + assert Shi(exp_polar(2*pi*I)*x) == Shi(x) + assert Shi(exp_polar(-2*pi*I)*x) == Shi(x) + + assert Si(oo) == pi/2 + assert Si(-oo) == -pi/2 + assert Shi(oo) is oo + assert Shi(-oo) is -oo + + assert mytd(Si(x), sin(x)/x, x) + assert mytd(Shi(x), sinh(x)/x, x) + + assert mytn(Si(x), Si(x).rewrite(Ei), + -I*(-Ei(x*exp_polar(-I*pi/2))/2 + + Ei(x*exp_polar(I*pi/2))/2 - I*pi) + pi/2, x) + assert mytn(Si(x), Si(x).rewrite(expint), + -I*(-expint(1, x*exp_polar(-I*pi/2))/2 + + expint(1, x*exp_polar(I*pi/2))/2) + pi/2, x) + assert mytn(Shi(x), Shi(x).rewrite(Ei), + Ei(x)/2 - Ei(x*exp_polar(I*pi))/2 + I*pi/2, x) + assert mytn(Shi(x), Shi(x).rewrite(expint), + expint(1, x)/2 - expint(1, x*exp_polar(I*pi))/2 - I*pi/2, x) + + assert tn_arg(Si) + assert tn_arg(Shi) + + assert Si(x).nseries(x, n=8) == \ + x - x**3/18 + x**5/600 - x**7/35280 + O(x**9) + assert Shi(x).nseries(x, n=8) == \ + x + x**3/18 + x**5/600 + x**7/35280 + O(x**9) + assert Si(sin(x)).nseries(x, n=5) == x - 2*x**3/9 + 17*x**5/450 + O(x**6) + assert Si(x).nseries(x, 1, n=3) == \ + Si(1) + (x - 1)*sin(1) + (x - 1)**2*(-sin(1)/2 + cos(1)/2) + O((x - 1)**3, (x, 1)) + + assert Si(x).series(x, oo) == pi/2 - (- 6/x**3 + 1/x \ + + O(x**(-7), (x, oo)))*sin(x)/x - (24/x**4 - 2/x**2 + 1 \ + + O(x**(-7), (x, oo)))*cos(x)/x + + t = Symbol('t', Dummy=True) + assert Si(x).rewrite(sinc) == Integral(sinc(t), (t, 0, x)) + + assert limit(Shi(x), x, S.Infinity) == S.Infinity + assert limit(Shi(x), x, S.NegativeInfinity) == S.NegativeInfinity + + +def test_ci(): + m1 = exp_polar(I*pi) + m1_ = exp_polar(-I*pi) + pI = exp_polar(I*pi/2) + mI = exp_polar(-I*pi/2) + + assert Ci(m1*x) == Ci(x) + I*pi + assert Ci(m1_*x) == Ci(x) - I*pi + assert Ci(pI*x) == Chi(x) + I*pi/2 + assert Ci(mI*x) == Chi(x) - I*pi/2 + assert Chi(m1*x) == Chi(x) + I*pi + assert Chi(m1_*x) == Chi(x) - I*pi + assert Chi(pI*x) == Ci(x) + I*pi/2 + assert Chi(mI*x) == Ci(x) - I*pi/2 + assert Ci(exp_polar(2*I*pi)*x) == Ci(x) + 2*I*pi + assert Chi(exp_polar(-2*I*pi)*x) == Chi(x) - 2*I*pi + assert Chi(exp_polar(2*I*pi)*x) == Chi(x) + 2*I*pi + assert Ci(exp_polar(-2*I*pi)*x) == Ci(x) - 2*I*pi + + assert Ci(oo) is S.Zero + assert Ci(-oo) == I*pi + assert Chi(oo) is oo + assert Chi(-oo) is oo + + assert mytd(Ci(x), cos(x)/x, x) + assert mytd(Chi(x), cosh(x)/x, x) + + assert mytn(Ci(x), Ci(x).rewrite(Ei), + Ei(x*exp_polar(-I*pi/2))/2 + Ei(x*exp_polar(I*pi/2))/2, x) + assert mytn(Chi(x), Chi(x).rewrite(Ei), + Ei(x)/2 + Ei(x*exp_polar(I*pi))/2 - I*pi/2, x) + + assert tn_arg(Ci) + assert tn_arg(Chi) + + assert Ci(x).nseries(x, n=4) == \ + EulerGamma + log(x) - x**2/4 + x**4/96 + O(x**5) + assert Chi(x).nseries(x, n=4) == \ + EulerGamma + log(x) + x**2/4 + x**4/96 + O(x**5) + + assert Ci(x).series(x, oo) == -cos(x)*(-6/x**3 + 1/x \ + + O(x**(-7), (x, oo)))/x + (24/x**4 - 2/x**2 + 1 \ + + O(x**(-7), (x, oo)))*sin(x)/x + assert limit(log(x) - Ci(2*x), x, 0) == -log(2) - EulerGamma + assert Ci(x).rewrite(uppergamma) == -expint(1, x*exp_polar(-I*pi/2))/2 -\ + expint(1, x*exp_polar(I*pi/2))/2 + assert Ci(x).rewrite(expint) == -expint(1, x*exp_polar(-I*pi/2))/2 -\ + expint(1, x*exp_polar(I*pi/2))/2 + raises(ArgumentIndexError, lambda: Ci(x).fdiff(2)) + + +def test_fresnel(): + assert fresnels(0) is S.Zero + assert fresnels(oo) is S.Half + assert fresnels(-oo) == Rational(-1, 2) + assert fresnels(I*oo) == -I*S.Half + + assert unchanged(fresnels, z) + assert fresnels(-z) == -fresnels(z) + assert fresnels(I*z) == -I*fresnels(z) + assert fresnels(-I*z) == I*fresnels(z) + + assert conjugate(fresnels(z)) == fresnels(conjugate(z)) + + assert fresnels(z).diff(z) == sin(pi*z**2/2) + + assert fresnels(z).rewrite(erf) == (S.One + I)/4 * ( + erf((S.One + I)/2*sqrt(pi)*z) - I*erf((S.One - I)/2*sqrt(pi)*z)) + + assert fresnels(z).rewrite(hyper) == \ + pi*z**3/6 * hyper([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)], -pi**2*z**4/16) + + assert fresnels(z).series(z, n=15) == \ + pi*z**3/6 - pi**3*z**7/336 + pi**5*z**11/42240 + O(z**15) + + assert fresnels(w).is_extended_real is True + assert fresnels(w).is_finite is True + + assert fresnels(z).is_extended_real is None + assert fresnels(z).is_finite is None + + assert fresnels(z).as_real_imag() == (fresnels(re(z) - I*im(z))/2 + + fresnels(re(z) + I*im(z))/2, + -I*(-fresnels(re(z) - I*im(z)) + fresnels(re(z) + I*im(z)))/2) + + assert fresnels(z).as_real_imag(deep=False) == (fresnels(re(z) - I*im(z))/2 + + fresnels(re(z) + I*im(z))/2, + -I*(-fresnels(re(z) - I*im(z)) + fresnels(re(z) + I*im(z)))/2) + + assert fresnels(w).as_real_imag() == (fresnels(w), 0) + assert fresnels(w).as_real_imag(deep=True) == (fresnels(w), 0) + + assert fresnels(2 + 3*I).as_real_imag() == ( + fresnels(2 + 3*I)/2 + fresnels(2 - 3*I)/2, + -I*(fresnels(2 + 3*I) - fresnels(2 - 3*I))/2 + ) + + assert expand_func(integrate(fresnels(z), z)) == \ + z*fresnels(z) + cos(pi*z**2/2)/pi + + assert fresnels(z).rewrite(meijerg) == sqrt(2)*pi*z**Rational(9, 4) * \ + meijerg(((), (1,)), ((Rational(3, 4),), + (Rational(1, 4), 0)), -pi**2*z**4/16)/(2*(-z)**Rational(3, 4)*(z**2)**Rational(3, 4)) + + assert fresnelc(0) is S.Zero + assert fresnelc(oo) == S.Half + assert fresnelc(-oo) == Rational(-1, 2) + assert fresnelc(I*oo) == I*S.Half + + assert unchanged(fresnelc, z) + assert fresnelc(-z) == -fresnelc(z) + assert fresnelc(I*z) == I*fresnelc(z) + assert fresnelc(-I*z) == -I*fresnelc(z) + + assert conjugate(fresnelc(z)) == fresnelc(conjugate(z)) + + assert fresnelc(z).diff(z) == cos(pi*z**2/2) + + assert fresnelc(z).rewrite(erf) == (S.One - I)/4 * ( + erf((S.One + I)/2*sqrt(pi)*z) + I*erf((S.One - I)/2*sqrt(pi)*z)) + + assert fresnelc(z).rewrite(hyper) == \ + z * hyper([Rational(1, 4)], [S.Half, Rational(5, 4)], -pi**2*z**4/16) + + assert fresnelc(w).is_extended_real is True + + assert fresnelc(z).as_real_imag() == \ + (fresnelc(re(z) - I*im(z))/2 + fresnelc(re(z) + I*im(z))/2, + -I*(-fresnelc(re(z) - I*im(z)) + fresnelc(re(z) + I*im(z)))/2) + + assert fresnelc(z).as_real_imag(deep=False) == \ + (fresnelc(re(z) - I*im(z))/2 + fresnelc(re(z) + I*im(z))/2, + -I*(-fresnelc(re(z) - I*im(z)) + fresnelc(re(z) + I*im(z)))/2) + + assert fresnelc(2 + 3*I).as_real_imag() == ( + fresnelc(2 - 3*I)/2 + fresnelc(2 + 3*I)/2, + -I*(fresnelc(2 + 3*I) - fresnelc(2 - 3*I))/2 + ) + + assert expand_func(integrate(fresnelc(z), z)) == \ + z*fresnelc(z) - sin(pi*z**2/2)/pi + + assert fresnelc(z).rewrite(meijerg) == sqrt(2)*pi*z**Rational(3, 4) * \ + meijerg(((), (1,)), ((Rational(1, 4),), + (Rational(3, 4), 0)), -pi**2*z**4/16)/(2*(-z)**Rational(1, 4)*(z**2)**Rational(1, 4)) + + from sympy.core.random import verify_numerically + + verify_numerically(re(fresnels(z)), fresnels(z).as_real_imag()[0], z) + verify_numerically(im(fresnels(z)), fresnels(z).as_real_imag()[1], z) + verify_numerically(fresnels(z), fresnels(z).rewrite(hyper), z) + verify_numerically(fresnels(z), fresnels(z).rewrite(meijerg), z) + + verify_numerically(re(fresnelc(z)), fresnelc(z).as_real_imag()[0], z) + verify_numerically(im(fresnelc(z)), fresnelc(z).as_real_imag()[1], z) + verify_numerically(fresnelc(z), fresnelc(z).rewrite(hyper), z) + verify_numerically(fresnelc(z), fresnelc(z).rewrite(meijerg), z) + + raises(ArgumentIndexError, lambda: fresnels(z).fdiff(2)) + raises(ArgumentIndexError, lambda: fresnelc(z).fdiff(2)) + + assert fresnels(x).taylor_term(-1, x) is S.Zero + assert fresnelc(x).taylor_term(-1, x) is S.Zero + assert fresnelc(x).taylor_term(1, x) == -pi**2*x**5/40 + + +def test_fresnel_series(): + assert fresnelc(z).series(z, n=15) == \ + z - pi**2*z**5/40 + pi**4*z**9/3456 - pi**6*z**13/599040 + O(z**15) + + # issues 6510, 10102 + fs = (S.Half - sin(pi*z**2/2)/(pi**2*z**3) + + (-1/(pi*z) + 3/(pi**3*z**5))*cos(pi*z**2/2)) + fc = (S.Half - cos(pi*z**2/2)/(pi**2*z**3) + + (1/(pi*z) - 3/(pi**3*z**5))*sin(pi*z**2/2)) + assert fresnels(z).series(z, oo) == fs + O(z**(-6), (z, oo)) + assert fresnelc(z).series(z, oo) == fc + O(z**(-6), (z, oo)) + assert (fresnels(z).series(z, -oo) + fs.subs(z, -z)).expand().is_Order + assert (fresnelc(z).series(z, -oo) + fc.subs(z, -z)).expand().is_Order + assert (fresnels(1/z).series(z) - fs.subs(z, 1/z)).expand().is_Order + assert (fresnelc(1/z).series(z) - fc.subs(z, 1/z)).expand().is_Order + assert ((2*fresnels(3*z)).series(z, oo) - 2*fs.subs(z, 3*z)).expand().is_Order + assert ((3*fresnelc(2*z)).series(z, oo) - 3*fc.subs(z, 2*z)).expand().is_Order diff --git a/shared/package-files/d1/d150b1972b1ee2e21c960ba945516ead85678037d1eef7c8e3749645425ab13b/blob b/shared/package-files/d1/d150b1972b1ee2e21c960ba945516ead85678037d1eef7c8e3749645425ab13b/blob new file mode 100644 index 0000000000000000000000000000000000000000..423941164eb9f264fea909d54f30346c464ea061 --- /dev/null +++ b/shared/package-files/d1/d150b1972b1ee2e21c960ba945516ead85678037d1eef7c8e3749645425ab13b/blob @@ -0,0 +1,1799 @@ +# Copyright (C) 2014 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Tools for converting Cran packages to conda recipes. +""" +from __future__ import annotations + +import argparse +import copy +import hashlib +import re +import subprocess +import sys +import tarfile +import unicodedata +import zipfile +from itertools import chain +from os import environ, listdir, makedirs, sep +from os.path import ( + basename, + commonprefix, + exists, + isabs, + isdir, + isfile, + join, + normpath, + realpath, + relpath, +) + +import requests +import yaml + +# try to import C dumper +try: + from yaml import CSafeDumper as SafeDumper +except ImportError: + from yaml import SafeDumper + +from typing import TYPE_CHECKING + +from conda.common.io import dashlist + +from .. import source +from ..conda_interface import TemporaryDirectory, cc_conda_build +from ..config import get_or_merge_config +from ..license_family import allowed_license_families, guess_license_family +from ..metadata import MetaData +from ..utils import ensure_list, rm_rf +from ..variants import DEFAULT_VARIANTS, get_package_variants + +if TYPE_CHECKING: + from typing import Literal + +SOURCE_META = """\ + {archive_keys} + {git_url_key} {git_url} + {git_tag_key} {git_tag} + {patches} +""" + +BINARY_META = """\ + url: {cranurl}{sel} + {hash_entry}{sel} +""" + +VERSION_META = """\ +{{% set version = '{cran_version}' %}}{sel}""" + +CRAN_META = """\ +{version_source} +{version_binary1} +{version_binary2} + +{{% set posix = 'm2-' if win else '' %}} +{{% set native = 'm2w64-' if win else '' %}} + +package: + name: {packagename} + version: {{{{ version|replace("-", "_") }}}} + +source: +{source} +{binary1} +{binary2} + +build: + merge_build_host: True{sel_src_and_win} + # If this is a new build for the same version, increment the build number. + number: {build_number} + {skip_os} + {noarch_generic} + + # This is required to make R link correctly on Linux. + rpaths: + - lib/R/lib/ + - lib/ + {script_env} +{suggests} +requirements: + build:{build_depends} + + host:{host_depends} + + run:{run_depends} + +test: + commands: + # You can put additional test commands to be run here. + - $R -e "library('{cran_packagename}')" # [not win] + - "\\"%R%\\" -e \\"library('{cran_packagename}')\\"" # [win] + + # You can also put a file called run_test.py, run_test.sh, or run_test.bat + # in the recipe that will be run at test time. + + # requires: + # Put any additional test requirements here. + +about: + {home_comment}home:{homeurl} + license: {license} + {summary_comment}summary:{summary} + license_family: {license_family} + {license_file} + +{extra_recipe_maintainers} + +# The original CRAN metadata for this package was: + +{cran_metadata} + +# See +# https://docs.conda.io/projects/conda-build for +# more information about meta.yaml + +""" + +CRAN_BUILD_SH_SOURCE = """\ +#!/bin/bash + +# 'Autobrew' is being used by more and more packages these days +# to grab static libraries from Homebrew bottles. These bottles +# are fetched via Homebrew's --force-bottle option which grabs +# a bottle for the build machine which may not be macOS 10.9. +# Also, we want to use conda packages (and shared libraries) for +# these 'system' dependencies. See: +# https://github.com/jeroen/autobrew/issues/3 +export DISABLE_AUTOBREW=1 + +# R refuses to build packages that mark themselves as Priority: Recommended +mv DESCRIPTION DESCRIPTION.old +grep -va '^Priority: ' DESCRIPTION.old > DESCRIPTION +# shellcheck disable=SC2086 +${{R}} CMD INSTALL --build . ${{R_ARGS}} + +# Add more build steps here, if they are necessary. + +# See +# https://docs.conda.io/projects/conda-build +# for a list of environment variables that are set during the build process. +""" + +CRAN_BUILD_SH_MIXED = """\ +#!/bin/bash + +set -o errexit -o pipefail + +if {source_pf_bash}; then + export DISABLE_AUTOBREW=1 + mv DESCRIPTION DESCRIPTION.old + grep -va '^Priority: ' DESCRIPTION.old > DESCRIPTION + # shellcheck disable=SC2086 + ${{R}} CMD INSTALL --build . ${{R_ARGS}} +else + mkdir -p "${{PREFIX}}"/lib/R/library/{cran_packagename} + mv ./* "${{PREFIX}}"/lib/R/library/{cran_packagename} + + if [[ ${{target_platform}} == osx-64 ]]; then + pushd "${{PREFIX}}" + for libdir in lib/R/lib lib/R/modules lib/R/library lib/R/bin/exec sysroot/usr/lib; do + pushd "${{libdir}}" || exit 1 + while IFS= read -r -d '' SHARED_LIB + do + echo "fixing SHARED_LIB ${{SHARED_LIB}}" + install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5.0-MRO/Resources/lib/libR.dylib "${{PREFIX}}"/lib/R/lib/libR.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libR.dylib "${{PREFIX}}"/lib/R/lib/libR.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /usr/local/clang4/lib/libomp.dylib "${{PREFIX}}"/lib/libomp.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /usr/local/gfortran/lib/libgfortran.3.dylib "${{PREFIX}}"/lib/libgfortran.3.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libquadmath.0.dylib "${{PREFIX}}"/lib/libquadmath.0.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /usr/local/gfortran/lib/libquadmath.0.dylib "${{PREFIX}}"/lib/libquadmath.0.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libgfortran.3.dylib "${{PREFIX}}"/lib/libgfortran.3.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /usr/lib/libgcc_s.1.dylib "${{PREFIX}}"/lib/libgcc_s.1.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /usr/lib/libiconv.2.dylib "${{PREFIX}}"/sysroot/usr/lib/libiconv.2.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /usr/lib/libncurses.5.4.dylib "${{PREFIX}}"/sysroot/usr/lib/libncurses.5.4.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /usr/lib/libicucore.A.dylib "${{PREFIX}}"/sysroot/usr/lib/libicucore.A.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /usr/lib/libexpat.1.dylib "${{PREFIX}}"/lib/libexpat.1.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /usr/lib/libcurl.4.dylib "${{PREFIX}}"/lib/libcurl.4.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /usr/lib/libc++.1.dylib "${{PREFIX}}"/lib/libc++.1.dylib "${{SHARED_LIB}}" || true + install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libc++.1.dylib "${{PREFIX}}"/lib/libc++.1.dylib "${{SHARED_LIB}}" || true + done < <(find . \\( -type f -iname "*.dylib" -or -iname "*.so" -or -iname "R" \\) -print0) + popd + done + popd + fi +fi +""" # noqa: E501 + +CRAN_BUILD_SH_BINARY = """\ +#!/bin/bash + +set -o errexit -o pipefail + +mkdir -p "${{PREFIX}}"/lib/R/library/{cran_packagename} +mv ./* "${{PREFIX}}"/lib/R/library/{cran_packagename} +""" + +CRAN_BLD_BAT_SOURCE = """\ +"%R%" CMD INSTALL --build . %R_ARGS% +IF %ERRORLEVEL% NEQ 0 exit /B 1 +""" + +# We hardcode the fact that CRAN does not provide win32 binaries here. +CRAN_BLD_BAT_MIXED = """\ +if "%target_platform%" == "win-64" goto skip_source_build +"%R%" CMD INSTALL --build . %R_ARGS% +IF %ERRORLEVEL% NEQ 0 exit /B 1 +exit 0 +:skip_source_build +mkdir %PREFIX%\\lib\\R\\library +robocopy /E . "%PREFIX%\\lib\\R\\library\\{cran_packagename}" +if %ERRORLEVEL% NEQ 1 exit /B 1 +exit 0 +""" + +INDENT = "\n - " + +CRAN_KEYS = [ + "Site", + "Archs", + "Depends", + "Enhances", + "Imports", + "License", + "License_is_FOSS", + "License_restricts_use", + "LinkingTo", + "MD5sum", + "NeedsCompilation", + "OS_type", + "Package", + "Path", + "Priority", + "Suggests", + "Version", + "Title", + "Author", + "Maintainer", +] + +# The following base/recommended package names are derived from R's source +# tree (R-3.0.2/share/make/vars.mk). Hopefully they don't change too much +# between versions. +R_BASE_PACKAGE_NAMES = ( + "base", + "compiler", + "datasets", + "graphics", + "grDevices", + "grid", + "methods", + "parallel", + "splines", + "stats", + "stats4", + "tcltk", + "tools", + "utils", +) + +R_RECOMMENDED_PACKAGE_NAMES = ( + "MASS", + "lattice", + "Matrix", + "nlme", + "survival", + "boot", + "cluster", + "codetools", + "foreign", + "KernSmooth", + "rpart", + "class", + "nnet", + "spatial", + "mgcv", +) + +# Stolen then tweaked from debian.deb822.PkgRelation.__dep_RE. +VERSION_DEPENDENCY_REGEX = re.compile( + r"^\s*(?P[a-zA-Z0-9.+\-]{1,})" + r"(\s*\(\s*(?P[>=<]+)\s*" + r"(?P[0-9a-zA-Z:\-+~.]+)\s*\))" + r"?(\s*\[(?P[\s!\w\-]+)\])?\s*$" +) + +target_platform_bash_test_by_sel = { + "linux": "=~ linux.*", + "linux32": "== linux-32", + "linux64": "== linux-64", + "win32": "== win-32", + "win64": "== win-64", + "osx": "== osx-64", +} + + +def package_exists(package_name): + # TODO: how can we get cran to spit out package presence? + # available.packages() is probably a start, but no channels are working on mac right now? + return True + # install_output = subprocess.check_output([join(sys.prefix, "r"), "-e", + # # ind=2 arbitrarily chooses some CRAN mirror to try. + # "chooseCRANmirror(ind=2);install.packages('{}')".format(package_name)]) + + +def add_parser(repos): + # for loading default variant info + cran = repos.add_parser( + "cran", + help=""" + Create recipe skeleton for packages hosted on the Comprehensive R Archive + Network (CRAN) (cran.r-project.org). + """, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + cran.add_argument( + "packages", + nargs="+", + help="""CRAN packages to create recipe skeletons for.""", + ) + cran.add_argument( + "--output-dir", + help="Directory to write recipes to (default: %(default)s).", + default=".", + ) + cran.add_argument( + "--output-suffix", + help="Suffix to add to recipe dir, can contain other dirs (eg: -feedstock/recipe).", + default="", + ) + cran.add_argument( + "--add-maintainer", + help="Add this github username as a maintainer if not already present.", + ) + cran.add_argument( + "--version", + help="Version to use. Applies to all packages.", + ) + cran.add_argument( + "--git-tag", + help="Git tag to use for GitHub recipes.", + ) + cran.add_argument( + "--all-urls", + action="store_true", + help="""Look at all URLs, not just source URLs. Use this if it can't + find the right URL.""", + ) + cran.add_argument( + "--cran-url", + help="URL to use for as source package repository", + ) + cran.add_argument( + "--r-interp", + default="r-base", + help="Declare R interpreter package", + ) + cran.add_argument( + "--use-binaries-ver", + help=( + "Repackage binaries from version provided by argument instead of building " + "from source." + ), + ) + cran.add_argument( + "--use-when-no-binary", + choices=("src", "old", "src-old", "old-src", "error"), + default="src", + help="""Sometimes binaries are not available at the correct version for + a given platform (macOS). You can use this flag to specify what + fallback to take, either compiling from source or using an older + binary or trying one then the other.""", + ) + cran.add_argument( + "--use-noarch-generic", + action="store_true", + dest="use_noarch_generic", + help="Mark packages that do not need compilation as `noarch: generic`", + ) + cran.add_argument( + "--use-rtools-win", + action="store_true", + help="Use Rtools when building from source on Windows", + ) + cran.add_argument( + "--recursive", + action="store_true", + help="Create recipes for dependencies if they do not already exist.", + ) + cran.add_argument( + "--no-recursive", + action="store_false", + dest="recursive", + help="Don't create recipes for dependencies if they do not already exist.", + ) + cran.add_argument( + "--no-archive", + action="store_false", + dest="archive", + help="Don't include an Archive download url.", + ) + cran.add_argument( + "--allow-archived", + action="store_true", + dest="allow_archived", + help="If the package has been archived, download the latest version.", + ) + cran.add_argument( + "--version-compare", + action="store_true", + help="""Compare the package version of the recipe with the one available + on CRAN. Exits 1 if a newer version is available and 0 otherwise.""", + ) + cran.add_argument( + "--update-policy", + action="store", + choices=( + "error", + "skip-up-to-date", + "skip-existing", + "overwrite", + "merge-keep-build-num", + "merge-incr-build-num", + ), + default="error", + help="""Dictates what to do when existing packages are encountered in the + output directory (set by --output-dir). In the present implementation, the + merge options avoid overwriting bld.bat and build.sh and only manage copying + across patches, and the `build/{number,script_env}` fields. When the version + changes, both merge options reset `build/number` to 0. When the version does + not change they either keep the old `build/number` or else increase it by one.""", + ) + cran.add_argument( + "-m", + "--variant-config-files", + default=cc_conda_build.get("skeleton_config_yaml", None), + help="""Variant config file to add. These yaml files can contain + keys such as `cran_mirror`. Only one can be provided here.""", + ) + cran.add_argument( + "--add-cross-r-base", + action="store_true", + default=False, + help="""Add cross-r-base to build requirements for cross compiling""", + ) + cran.add_argument( + "--no-comments", + action="store_true", + default=False, + help="""Do not include instructional comments in recipe files""", + ) + + +def dict_from_cran_lines(lines): + d = {} + for line in lines: + if not line: + continue + try: + if ": " in line: + (k, v) = line.split(": ", 1) + else: + # Sometimes fields are included but left blank, e.g.: + # - Enhances in data.tree + # - Suggests in corpcor + (k, v) = line.split(":", 1) + except ValueError: + sys.exit("Error: Could not parse metadata (%s)" % line) + d[k] = v + # if k not in CRAN_KEYS: + # print("Warning: Unknown key %s" % k) + d["orig_lines"] = lines + return d + + +def remove_package_line_continuations(chunk): + """ + >>> chunk = [ + 'Package: A3', + 'Version: 0.9.2', + 'Depends: R (>= 2.15.0), xtable, pbapply', + 'Suggests: randomForest, e1071', + 'Imports: MASS, R.methodsS3 (>= 1.5.2), R.oo (>= 1.15.8), R.utils (>=', + ' 1.27.1), matrixStats (>= 0.8.12), R.filesets (>= 2.3.0), ', + ' sampleSelection, scatterplot3d, strucchange, systemfit', + 'License: GPL (>= 2)', + 'NeedsCompilation: no'] + >>> remove_package_line_continuations(chunk) + ['Package: A3', + 'Version: 0.9.2', + 'Depends: R (>= 2.15.0), xtable, pbapply', + 'Suggests: randomForest, e1071', + 'Imports: MASS, R.methodsS3 (>= 1.5.2), R.oo (>= 1.15.8), R.utils (>= 1.27.1), matrixStats (>= 0.8.12), R.filesets (>= 2.3.0), sampleSelection, scatterplot3d, strucchange, systemfit, rgl,' + 'License: GPL (>= 2)', + 'NeedsCompilation: no'] + """ # NOQA + continuation = (" ", "\t") + continued_ix = None + continued_line = None + had_continuation = False + accumulating_continuations = False + + chunk.append("") + + for i, line in enumerate(chunk): + if line.startswith(continuation): + line = " " + line.lstrip() + if accumulating_continuations: + assert had_continuation + continued_line += line + chunk[i] = None + else: + accumulating_continuations = True + continued_ix = i - 1 + continued_line = chunk[continued_ix] + line + had_continuation = True + chunk[i] = None + else: + if accumulating_continuations: + assert had_continuation + chunk[continued_ix] = continued_line + accumulating_continuations = False + continued_line = None + continued_ix = None + + if had_continuation: + # Remove the None(s). + chunk = [c for c in chunk if c] + + chunk.append("") + + return chunk + + +def yaml_quote_string(string): + """ + Quote a string for use in YAML. + + We can't just use yaml.dump because it adds ellipses to the end of the + string, and it in general doesn't handle being placed inside an existing + document very well. + + Note that this function is NOT general. + """ + return ( + yaml.dump(string, indent=True, Dumper=SafeDumper) + .replace("\n...\n", "") + .replace("\n", "\n ") + .rstrip("\n ") + ) + + +# Due to how we render the metadata there can be significant areas of repeated newlines. +# This collapses them and also strips any trailing spaces. +def clear_whitespace(string): + lines = [] + last_line = "" + for line in string.splitlines(): + line = line.rstrip() + if not (line == "" and last_line == ""): + lines.append(line) + last_line = line + return "\n".join(lines) + + +def read_description_contents(fp): + bytes = fp.read() + text = bytes.decode("utf-8", errors="replace") + text = clear_whitespace(text) + lines = remove_package_line_continuations(text.splitlines()) + return dict_from_cran_lines(lines) + + +def get_archive_metadata(path, verbose=True): + if verbose: + print("Reading package metadata from %s" % path) + if basename(path) == "DESCRIPTION": + with open(path, "rb") as fp: + return read_description_contents(fp) + elif tarfile.is_tarfile(path): + with tarfile.open(path, "r") as tf: + for member in tf: + if re.match(r"^[^/]+/DESCRIPTION$", member.name): + fp = tf.extractfile(member) + return read_description_contents(fp) + elif path.endswith(".zip"): + with zipfile.ZipFile(path, "r") as zf: + for member in zf.infolist(): + if re.match(r"^[^/]+/DESCRIPTION$", member.filename): + fp = zf.open(member, "r") + return read_description_contents(fp) + else: + sys.exit("Cannot extract a DESCRIPTION from file %s" % path) + sys.exit("%s does not seem to be a CRAN package (no DESCRIPTION) file" % path) + + +def get_latest_git_tag(config): + # SO says to use taggerdate instead of committerdate, but that is invalid for lightweight tags. + p = subprocess.Popen( + [ + "git", + "for-each-ref", + "refs/tags", + "--sort=-committerdate", + "--format=%(refname:short)", + "--count=1", + ], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + cwd=config.work_dir, + ) + + stdout, stderr = p.communicate() + stdout = stdout.decode("utf-8") + stderr = stderr.decode("utf-8") + if stderr or p.returncode: + sys.exit("Error: git tag failed (%s)" % stderr) + tags = stdout.strip().splitlines() + if not tags: + sys.exit("Error: no tags found") + + print("Using tag %s" % tags[-1]) + return tags[-1] + + +def _ssl_no_verify(): + """Gets whether the SSL_NO_VERIFY environment variable is set to 1 or True. + + This provides a workaround for users in some corporate environments where + MITM style proxies make it difficult to fetch data over HTTPS. + """ + return environ.get("SSL_NO_VERIFY", "").strip().lower() in ("1", "true") + + +def get_session(output_dir, verbose=True): + session = requests.Session() + session.verify = _ssl_no_verify() + try: + import cachecontrol + import cachecontrol.caches + except ImportError: + if verbose: + print( + "Tip: install CacheControl and lockfile (conda packages) to cache the " + "CRAN metadata" + ) + else: + session = cachecontrol.CacheControl( + session, cache=cachecontrol.caches.FileCache(join(output_dir, ".web_cache")) + ) + return session + + +def get_cran_archive_versions(cran_url, session, package, verbose=True): + if verbose: + print(f"Fetching archived versions for package {package} from {cran_url}") + r = session.get(cran_url + "/src/contrib/Archive/" + package + "/") + try: + r.raise_for_status() + except requests.exceptions.HTTPError as e: + if e.response.status_code == 404: + print("No archive directory for package %s" % package) + return [] + raise + versions = [] + for p, dt in re.findall( + r'\s*]*>([^<]*)', r.text + ): + if p.endswith(".tar.gz") and "_" in p: + name, version = p.rsplit(".", 2)[0].split("_", 1) + versions.append((dt.strip(), version)) + return [v for dt, v in sorted(versions, reverse=True)] + + +def get_cran_index(cran_url, session, verbose=True): + if verbose: + print("Fetching main index from %s" % cran_url) + r = session.get(cran_url + "/src/contrib/") + r.raise_for_status() + records = {} + for p in re.findall(r'', r.text): + if p.endswith(".tar.gz") and "_" in p: + name, version = p.rsplit(".", 2)[0].split("_", 1) + records[name.lower()] = (name, version) + r = session.get(cran_url + "/src/contrib/Archive/") + r.raise_for_status() + for p in re.findall(r'', r.text): + if re.match(r"^[A-Za-z]", p): + records.setdefault(p.lower(), (p, None)) + return records + + +def make_array(m, key, allow_empty=False): + result = [] + try: + old_vals = m.get_value(key, []) + except: + old_vals = [] + if old_vals or allow_empty: + result.append(key.split("/")[-1] + ":") + for old_val in old_vals: + result.append(f"{INDENT}{old_val}") + return result + + +def existing_recipe_dir(output_dir, output_suffix, package, version): + result = None + if version: + package = package + "-" + version.replace("-", "_") + if exists(join(output_dir, package)): + result = normpath(join(output_dir, package)) + elif exists(join(output_dir, package + output_suffix)): + result = normpath(join(output_dir, package + output_suffix)) + elif exists(join(output_dir, "r-" + package + output_suffix)): + result = normpath(join(output_dir, "r-" + package + output_suffix)) + return result + + +def strip_end(string, end): + if string.endswith(end): + return string[: -len(end)] + return string + + +def package_to_inputs_dict( + output_dir, output_suffix, git_tag, package: str, version=None +): + """ + Converts `package` (*) into a tuple of: + + pkg_name (without leading 'r-') + location (in a subdir of output_dir - may not exist - or at GitHub) + old_git_rev (from existing metadata, so corresponds to the *old* version) + metadata or None (if a recipe does *not* already exist) + + (*) `package` could be: + 1. A package name beginning (or not) with 'r-' + 2. A GitHub URL + 3. A file:// URL to a tarball + 4. A relative path to a recipe from output_dir + 5. An absolute path to a recipe (fatal unless in the output_dir hierarchy) + 6. Any of the above ending (or not) in sep or '/' + + So this function cleans all that up: + + Some packages may be from GitHub but we'd like the user not to have to worry + about that on the command-line (for pre-existing recipes). Also, we may want + to get version information from them (or existing metadata to merge) so lets + load *all* existing recipes (later we will add or replace this metadata with + any that we create). + """ + if isfile(package): + return None + print("Parsing input package %s:" % package) + package = strip_end(package, "/") + package = strip_end(package, sep) + if "github.com" in package: + package = strip_end(package, ".git") + pkg_name = basename(package).lower() + pkg_name = strip_end(pkg_name, "-feedstock") + if output_suffix: + pkg_name = strip_end(pkg_name, output_suffix) + if pkg_name.startswith("r-"): + pkg_name = pkg_name[2:] + if package.startswith("file://"): + location = package.replace("file://", "") + pkg_filename = basename(location) + pkg_name = re.match(r"(.*)_(.*)", pkg_filename).group(1).lower() + existing_location = existing_recipe_dir( + output_dir, output_suffix, "r-" + pkg_name, version + ) + elif isabs(package): + commp = commonprefix((package, output_dir)) + if commp != output_dir: + raise RuntimeError( + f"package {package} specified with abs path outside of output-dir {output_dir}" + ) + location = package + existing_location = existing_recipe_dir( + output_dir, output_suffix, "r-" + pkg_name, version + ) + elif "github.com" in package: + location = package + existing_location = existing_recipe_dir( + output_dir, output_suffix, "r-" + pkg_name, version + ) + else: + location = existing_location = existing_recipe_dir( + output_dir, output_suffix, package, version + ) + m: MetaData | None + if existing_location: + try: + m = MetaData(existing_location) + except: + # Happens when the folder exists but contains no recipe. + m = None + else: + m = None + + # It can still be the case that a package without 'github.com' in the location does really + # come from there, for that we need to inspect the existing metadata's source/git_url. + old_git_rev = git_tag + if location and m and "github.com" not in location: + git_url = m.get_value("source/git_url", "") + if "github.com" in git_url: + location = git_url + old_git_rev = m.get_value("source/git_rev", None) + + vstr = "-" + version.replace("-", "_") if version else "" + new_location = join(output_dir, "r-" + pkg_name + vstr + output_suffix) + print(f".. name: {pkg_name} location: {location} new_location: {new_location}") + + return { + "pkg-name": pkg_name, + "location": location, + "old-git-rev": old_git_rev, + "old-metadata": m, + "new-location": new_location, + "version": version, + } + + +def get_available_binaries(cran_url, details): + url = cran_url + "/" + details["dir"] + response = requests.get(url) + response.raise_for_status() + ext = details["ext"] + for filename in re.findall(r'\1', response.text): + if filename.endswith(ext): + pkg, _, ver = filename.rpartition("_") + ver, _, _ = ver.rpartition(ext) + details["binaries"].setdefault(pkg, []).append((ver, url + filename)) + + +def remove_comments(template): + re_comment = re.compile(r"^\s*#\s") + lines = template.split("\n") + lines_no_comments = [line for line in lines if not re_comment.match(line)] + return "\n".join(lines_no_comments) + + +def skeletonize( + in_packages, + output_dir=".", + output_suffix="", + add_maintainer=None, + version=None, + git_tag=None, + cran_url=None, + recursive=False, + archive=True, + version_compare=False, + update_policy="", + r_interp="r-base", + use_binaries_ver=None, + use_noarch_generic=False, + use_when_no_binary: Literal["error" | "src" | "old" | "old-src"] = "src", + use_rtools_win=False, + config=None, + variant_config_files=None, + allow_archived=False, + add_cross_r_base=False, + no_comments=False, +): + if ( + use_when_no_binary != "error" + and use_when_no_binary != "src" + and use_when_no_binary != "old" + and use_when_no_binary != "old-src" + ): + print(f"ERROR: --use_when_no_binary={use_when_no_binary} not yet implemented") + sys.exit(1) + + m: MetaData + + output_dir = realpath(output_dir) + config = get_or_merge_config(config, variant_config_files=variant_config_files) + + if allow_archived and not archive: + print("ERROR: --no-archive and --allow-archived conflict") + sys.exit(1) + + if not cran_url: + with TemporaryDirectory() as t: + _variant = get_package_variants(t, config)[0] + cran_url = ensure_list( + _variant.get("cran_mirror", DEFAULT_VARIANTS["cran_mirror"]) + )[0] + + if len(in_packages) > 1 and version_compare: + raise ValueError("--version-compare only works with one package at a time") + if update_policy == "error" and not in_packages: + raise ValueError("At least one package must be supplied") + + package_dicts = {} + package_list = [] + + cran_url = cran_url.rstrip("/") + + # Get cran index lazily so we don't have to go to CRAN + # for a github repo or a local tarball + cran_index = None + + cran_layout_template = { + "source": { + "selector": "{others}", + "dir": "src/contrib/", + "ext": ".tar.gz", + # If we had platform filters we would change this to: + # build_for_linux or is_github_url or is_tarfile + "use_this": True, + }, + "win-64": { + "selector": "win64", + "dir": f"bin/windows/contrib/{use_binaries_ver}/", + "ext": ".zip", + "use_this": True if use_binaries_ver else False, + }, + "osx-64": { + "selector": "osx", + "dir": f"bin/macosx/el-capitan/contrib/{use_binaries_ver}/", + "ext": ".tgz", + "use_this": True if use_binaries_ver else False, + }, + } + + # Figure out what binaries are available once: + for archive_type, archive_details in cran_layout_template.items(): + archive_details["binaries"] = dict() + if archive_type != "source" and archive_details["use_this"]: + get_available_binaries(cran_url, archive_details) + + for package in in_packages: + inputs_dict = package_to_inputs_dict( + output_dir, output_suffix, git_tag, package, version + ) + if inputs_dict: + package_dicts.update({inputs_dict["pkg-name"]: {"inputs": inputs_dict}}) + + for package_name, package_dict in package_dicts.items(): + package_list.append(package_name) + + while package_list: + inputs = package_dicts[package_list.pop()]["inputs"] + location = inputs["location"] + pkg_name = inputs["pkg-name"] + version = inputs["version"] + is_github_url = location and "github.com" in location + is_tarfile = location and isfile(location) and tarfile.is_tarfile(location) + is_archive = False + url = inputs["location"] + + dir_path = inputs["new-location"] + print(f"Making/refreshing recipe for {pkg_name}") + + # Bodges GitHub packages into cran_metadata + if is_tarfile: + cran_package = get_archive_metadata(location) + + elif is_github_url or is_tarfile: + rm_rf(config.work_dir) + m = MetaData.fromdict({"source": {"git_url": location}}, config=config) + source.git_source( + m.get_section("source"), m.config.git_cache, m.config.work_dir + ) + new_git_tag = git_tag if git_tag else get_latest_git_tag(config) + p = subprocess.Popen( + ["git", "checkout", new_git_tag], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + cwd=config.work_dir, + ) + stdout, stderr = p.communicate() + stdout = stdout.decode("utf-8") + stderr = stderr.decode("utf-8") + if p.returncode: + sys.exit( + f"Error: 'git checkout {new_git_tag}' failed ({stderr.strip()}).\n" + "Invalid tag?" + ) + if stdout: + print(stdout, file=sys.stdout) + if stderr: + print(stderr, file=sys.stderr) + DESCRIPTION = join(config.work_dir, "DESCRIPTION") + if not isfile(DESCRIPTION): + sub_description_pkg = join(config.work_dir, "pkg", "DESCRIPTION") + sub_description_name = join( + config.work_dir, location.split("/")[-1], "DESCRIPTION" + ) + if isfile(sub_description_pkg): + DESCRIPTION = sub_description_pkg + elif isfile(sub_description_name): + DESCRIPTION = sub_description_name + else: + sys.exit( + f"{location} does not appear to be a valid R package " + f"(no DESCRIPTION file in {sub_description_pkg}, {sub_description_name})" + ) + cran_package = get_archive_metadata(DESCRIPTION) + + else: + if cran_index is None: + session = get_session(output_dir) + cran_index = get_cran_index(cran_url, session) + if pkg_name.lower() not in cran_index: + sys.exit("Package %s not found" % pkg_name) + package, cran_version = cran_index[pkg_name.lower()] + if cran_version and (not version or version == cran_version): + version = cran_version + elif version and not archive: + print( + f"ERROR: Version {version} of package {package} is archived, but --no-archive was selected" + ) + sys.exit(1) + elif not version and not cran_version and not allow_archived: + print( + "ERROR: Package %s is archived; to build, use --allow-archived or a --version value" + % pkg_name + ) + sys.exit(1) + else: + is_archive = True + all_versions = get_cran_archive_versions(cran_url, session, package) + if cran_version: + all_versions = [cran_version] + all_versions + if not version: + version = all_versions[0] + elif version not in all_versions: + msg = f"ERROR: Version {version} of package {package} not found.\n Available versions: " + print(msg + ", ".join(all_versions)) + sys.exit(1) + cran_package = None + + if cran_package is not None: + package = cran_package["Package"] + version = cran_package["Version"] + plower = package.lower() + d = package_dicts[pkg_name] + d.update( + { + "cran_packagename": package, + "cran_version": version, + "packagename": "r-" + plower, + # Conda versions cannot have -. Conda (verlib) will treat _ as a . + "conda_version": version.replace("-", "_"), + "patches": "", + "build_number": 0, + "build_depends": "", + "host_depends": "", + "run_depends": "", + # CRAN doesn't seem to have this metadata :( + "home_comment": "#", + "homeurl": "", + "summary_comment": "#", + "summary": "", + "binary1": "", + "binary2": "", + } + ) + + if version_compare: + sys.exit(not version_compare(dir_path, d["conda_version"])) + + patches = [] + script_env = [] + extra_recipe_maintainers = [] + build_number = 0 + if update_policy.startswith("merge") and inputs["old-metadata"]: + m = inputs["old-metadata"] + patches = make_array(m, "source/patches") + script_env = make_array(m, "build/script_env") + extra_recipe_maintainers = make_array( + m, "extra/recipe-maintainers", add_maintainer + ) + if m.version() == d["conda_version"]: + build_number = m.build_number() + build_number += 1 if update_policy == "merge-incr-build-num" else 0 + if add_maintainer: + new_maintainer = f"{INDENT}{add_maintainer}" + if new_maintainer not in extra_recipe_maintainers: + if not len(extra_recipe_maintainers): + # We hit this case when there is no existing recipe. + extra_recipe_maintainers = make_array( + {}, "extra/recipe-maintainers", True + ) + extra_recipe_maintainers.append(new_maintainer) + if len(extra_recipe_maintainers): + extra_recipe_maintainers[1:].sort() + extra_recipe_maintainers.insert(0, "extra:\n ") + d["extra_recipe_maintainers"] = "".join(extra_recipe_maintainers) + d["patches"] = "".join(patches) + d["script_env"] = "".join(script_env) + d["build_number"] = build_number + + cached_path = None + cran_layout = copy.deepcopy(cran_layout_template) + available = {} + + description_path = None + for archive_type, archive_details in cran_layout.items(): + contrib_url = "" + archive_details["cran_version"] = d["cran_version"] + archive_details["conda_version"] = d["conda_version"] + if is_archive and archive_type == "source": + archive_details["dir"] += "Archive/" + package + "/" + available_artefact = ( + True + if archive_type == "source" + else package in archive_details["binaries"] + and any( + d["cran_version"] == v + for v, _ in archive_details["binaries"][package] + ) + ) + if not available_artefact: + if use_when_no_binary == "error": + print( + "ERROR: --use-when-no-binary is error (and there is no binary)" + ) + sys.exit(1) + elif use_when_no_binary.startswith("old"): + if package not in archive_details["binaries"]: + if use_when_no_binary.endswith("src"): + available_artefact = False + archive_details["use_this"] = False + continue + else: + print( + "ERROR: No binary nor old binary found " + "(maybe pass --use-when-no-binary=old-src to fallback to source?)" + ) + sys.exit(1) + # Version needs to be stored in archive_details. + archive_details["cranurl"] = archive_details["binaries"][package][ + -1 + ][1] + archive_details["conda_version"] = archive_details["binaries"][ + package + ][-1][0] + archive_details["cran_version"] = archive_details[ + "conda_version" + ].replace("_", "-") + available_artefact = True + # We may need to inspect the file later to determine which compilers are needed. + cached_path = None + sha256 = hashlib.sha256() + if archive_details["use_this"] and available_artefact: + if is_tarfile: + filename = basename(location) + contrib_url = relpath(location, dir_path) + contrib_url_rendered = package_url = contrib_url + cached_path = location + elif not is_github_url or archive_type != "source": + filename_rendered = "{}_{}{}".format( + package, archive_details["cran_version"], archive_details["ext"] + ) + filename = f"{package}_{{{{ version }}}}" + archive_details["ext"] + contrib_url = "{{{{ cran_mirror }}}}/{}".format( + archive_details["dir"] + ) + contrib_url_rendered = cran_url + "/{}".format( + archive_details["dir"] + ) + package_url = contrib_url_rendered + filename_rendered + print(f"Downloading {archive_type} from {package_url}") + try: + cached_path, _ = source.download_to_cache( + config.src_cache, + "", + { + "url": package_url, + "fn": archive_type + "-" + filename_rendered, + }, + ) + except: + print( + f"logic error, file {package_url} should exist, we found it in a dir listing earlier." + ) + sys.exit(1) + if description_path is None or archive_type == "source": + description_path = cached_path + available_details = {} + available_details["selector"] = archive_details["selector"] + available_details["cran_version"] = archive_details["cran_version"] + available_details["conda_version"] = archive_details["conda_version"] + if cached_path: + sha256.update(open(cached_path, "rb").read()) + archive_details["cranurl"] = package_url + available_details["filename"] = filename + available_details["contrib_url"] = contrib_url + available_details["contrib_url_rendered"] = contrib_url_rendered + available_details["hash_entry"] = f"sha256: {sha256.hexdigest()}" + available_details["cached_path"] = cached_path + # This is rubbish; d[] should be renamed global[] and should be + # merged into source and binaryN. + if archive_type == "source": + if is_github_url: + available_details["url_key"] = "" + available_details["git_url_key"] = "git_url:" + available_details["git_tag_key"] = "git_tag:" + hash_msg = "# You can add a hash for the file here, (md5, sha1 or sha256)" + available_details["hash_entry"] = hash_msg + available_details["filename"] = "" + available_details["cranurl"] = "" + available_details["git_url"] = url + available_details["git_tag"] = new_git_tag + available_details["archive_keys"] = "" + else: + available_details["url_key"] = "url:" + available_details["git_url_key"] = "" + available_details["git_tag_key"] = "" + available_details["cranurl"] = " " + contrib_url + filename + available_details["git_url"] = "" + available_details["git_tag"] = "" + else: + available_details["cranurl"] = archive_details["cranurl"] + + available_details["patches"] = d["patches"] + available[archive_type] = available_details + + # Figure out the selectors according to what is available. + _all = ["linux", "win32", "win64", "osx"] + from_source = _all[:] + binary_id = 1 + for archive_type, archive_details in available.items(): + if archive_type == "source": + for k, v in archive_details.items(): + d[k] = v + else: + sel = archive_details["selector"] + # Does the file exist? If not we need to build from source. + from_source.remove(sel) + binary_id += 1 + if from_source == _all: + sel_src = "" + sel_src_and_win = " # [win]" + sel_src_not_win = " # [not win]" + else: + sel_src = " # [" + " or ".join(from_source) + "]" + sel_src_and_win = ( + " # [" + + " or ".join(fs for fs in from_source if fs.startswith("win")) + + "]" + ) + sel_src_not_win = ( + " # [" + + " or ".join(fs for fs in from_source if not fs.startswith("win")) + + "]" + ) + sel_cross = " # [build_platform != target_platform]" + d["sel_src"] = sel_src + d["sel_src_and_win"] = sel_src_and_win + d["sel_src_not_win"] = sel_src_not_win + d["from_source"] = from_source + + if "source" in available: + available_details = available["source"] + available_details["sel"] = sel_src + filename = available_details["filename"] + if "contrib_url" in available_details: + contrib_url = available_details["contrib_url"] + if archive: + if is_tarfile: + available_details["cranurl"] = INDENT + contrib_url + elif not is_archive: + available_details["cranurl"] = ( + INDENT + + contrib_url + + filename + + sel_src + + INDENT + + contrib_url + + f"Archive/{package}/" + + filename + + sel_src + ) + else: + available_details["cranurl"] = ( + " " + contrib_url + filename + sel_src + ) + if not is_github_url: + available_details["archive_keys"] = ( + "{url_key}{sel} {cranurl}\n {hash_entry}{sel}" + ).format(**available_details) + + # Extract the DESCRIPTION data from the source + if cran_package is None: + cran_package = get_archive_metadata(description_path) + d["cran_metadata"] = "\n".join( + ["# %s" % line for line in cran_package["orig_lines"] if line] + ) + + # Render the source and binaryN keys + binary_id = 1 + d["version_binary1"] = d["version_binary2"] = "" + for archive_type, archive_details in available.items(): + if archive_type == "source": + d["source"] = SOURCE_META.format(**archive_details) + d["version_source"] = VERSION_META.format(**archive_details) + else: + archive_details["sel"] = " # [" + archive_details["selector"] + "]" + d["binary" + str(binary_id)] = BINARY_META.format(**archive_details) + d["version_binary" + str(binary_id)] = VERSION_META.format( + **archive_details + ) + binary_id += 1 + + license_info = get_license_info( + cran_package.get("License", "None"), allowed_license_families + ) + d["license"], d["license_file"], d["license_family"] = license_info + + if "License_is_FOSS" in cran_package: + d["license"] += " (FOSS)" + if cran_package.get("License_restricts_use") == "yes": + d["license"] += " (Restricts use)" + + if "URL" in cran_package: + d["home_comment"] = "" + d["homeurl"] = " " + yaml_quote_string(cran_package["URL"]) + else: + # use CRAN page as homepage if nothing has been specified + d["home_comment"] = "" + if is_github_url: + d["homeurl"] = f" {location}" + else: + d["homeurl"] = f" https://CRAN.R-project.org/package={package}" + + if ( + not use_noarch_generic + or cran_package.get("NeedsCompilation", "no") == "yes" + ): + d["noarch_generic"] = "" + else: + d["noarch_generic"] = "noarch: generic" + + if "Description" in cran_package: + d["summary_comment"] = "" + d["summary"] = " " + yaml_quote_string(cran_package["Description"]) + + if "Suggests" in cran_package and not no_comments: + d["suggests"] = "# Suggests: %s" % cran_package["Suggests"] + else: + d["suggests"] = "" + + # Every package depends on at least R. + # I'm not sure what the difference between depends and imports is. + depends = [ + s.strip() for s in cran_package.get("Depends", "").split(",") if s.strip() + ] + imports = [ + s.strip() for s in cran_package.get("Imports", "").split(",") if s.strip() + ] + links = [ + s.strip() for s in cran_package.get("LinkingTo", "").split(",") if s.strip() + ] + + dep_dict = {} + + seen = set() + for s in list(chain(imports, depends, links)): + match = VERSION_DEPENDENCY_REGEX.match(s) + if not match: + sys.exit(f"Could not parse version from dependency of {package}: {s}") + name = match.group("name") + if name in seen: + continue + seen.add(name) + archs = match.group("archs") + relop = match.group("relop") or "" + ver = match.group("version") or "" + ver = ver.replace("-", "_") + # If there is a relop there should be a version + assert not relop or ver + + if archs: + sys.exit( + "Don't know how to handle archs from dependency of " + f"package {package}: {s}" + ) + + dep_dict[name] = f"{relop}{ver}" + + if "R" not in dep_dict: + dep_dict["R"] = "" + + os_type = cran_package.get("OS_type", "") + if os_type != "unix" and os_type != "windows" and os_type != "": + print(f"Unknown OS_type: {os_type} in CRAN package") + os_type = "" + if os_type == "unix": + d["skip_os"] = "skip: True # [not unix]" + d["noarch_generic"] = "" + if os_type == "windows": + d["skip_os"] = "skip: True # [not win]" + d["noarch_generic"] = "" + if os_type == "" and no_comments: + d["skip_os"] = "" + elif os_type == "": + d["skip_os"] = "# no skip" + + need_git = is_github_url + if cran_package.get("NeedsCompilation", "no") == "yes": + with tarfile.open(available["source"]["cached_path"]) as tf: + need_f = any( + [ + f.name.lower().endswith((".f", ".f90", ".f77", ".f95", ".f03")) + for f in tf + ] + ) + # Fortran builds use CC to perform the link (they do not call the linker directly). + need_c = ( + True if need_f else any([f.name.lower().endswith(".c") for f in tf]) + ) + need_cxx = any( + [ + f.name.lower().endswith((".cxx", ".cpp", ".cc", ".c++")) + for f in tf + ] + ) + need_autotools = any( + [f.name.lower().endswith("/configure") for f in tf] + ) + need_make = ( + True + if any((need_autotools, need_f, need_cxx, need_c)) + else any( + [ + f.name.lower().endswith(("/makefile", "/makevars")) + for f in tf + ] + ) + ) + else: + need_c = need_cxx = need_f = need_autotools = need_make = False + + if "Rcpp" in dep_dict or "RcppArmadillo" in dep_dict: + need_cxx = True + + if need_cxx: + need_c = True + + for dep_type in ["build", "host", "run"]: + deps = [] + # Put non-R dependencies first. + if dep_type == "build": + if need_c: + deps.append( + f"{INDENT}{{{{ compiler('c') }}}} {sel_src_not_win}" + ) + deps.append( + f"{INDENT}{{{{ compiler('m2w64_c') }}}} {sel_src_and_win}" + ) + if need_cxx: + deps.append( + f"{INDENT}{{{{ compiler('cxx') }}}} {sel_src_not_win}" + ) + deps.append( + f"{INDENT}{{{{ compiler('m2w64_cxx') }}}} {sel_src_and_win}" + ) + if need_f: + deps.append( + f"{INDENT}{{{{ compiler('fortran') }}}} {sel_src_not_win}" + ) + deps.append( + f"{INDENT}{{{{ compiler('m2w64_fortran') }}}}{sel_src_and_win}" + ) + if use_rtools_win: + need_c = need_cxx = need_f = need_autotools = need_make = False + deps.append(f"{INDENT}rtools {sel_src_and_win}") + # extsoft is legacy. R packages will download rwinlib subprojects + # as necessary according to Jeroen Ooms. (may need to disable that + # for non-MRO builds or maybe switch to Jeroen's toolchain?) + # deps.append("{indent}{{{{native}}}}extsoft {sel}".format( + # indent=INDENT, sel=sel_src_and_win)) + if need_autotools or need_make or need_git: + deps.append( + f"{INDENT}{{{{ posix }}}}filesystem {sel_src_and_win}" + ) + if need_git: + deps.append(f"{INDENT}{{{{ posix }}}}git") + if need_autotools: + deps.append( + f"{INDENT}{{{{ posix }}}}sed {sel_src_and_win}" + ) + deps.append( + f"{INDENT}{{{{ posix }}}}grep {sel_src_and_win}" + ) + deps.append(f"{INDENT}{{{{ posix }}}}autoconf {sel_src}") + deps.append( + f"{INDENT}{{{{ posix }}}}automake {sel_src_not_win}" + ) + deps.append( + f"{INDENT}{{{{ posix }}}}automake-wrapper{sel_src_and_win}" + ) + deps.append(f"{INDENT}{{{{ posix }}}}pkg-config") + if need_make: + deps.append(f"{INDENT}{{{{ posix }}}}make {sel_src}") + if not need_autotools: + deps.append( + f"{INDENT}{{{{ posix }}}}sed {sel_src_and_win}" + ) + deps.append( + f"{INDENT}{{{{ posix }}}}coreutils {sel_src_and_win}" + ) + deps.append(f"{INDENT}{{{{ posix }}}}zip {sel_src_and_win}") + if add_cross_r_base: + deps.append(f"{INDENT}cross-r-base {{{{ r_base }}}} {sel_cross}") + elif dep_type == "run": + if need_c or need_cxx or need_f: + deps.append( + f"{INDENT}{{{{native}}}}gcc-libs {sel_src_and_win}" + ) + + if dep_type == "host" or dep_type == "run": + for name in sorted(dep_dict): + if name in R_BASE_PACKAGE_NAMES: + continue + if name == "R": + # Put R first + # Regarless of build or run, and whether this is a + # recommended package or not, it can only depend on + # r_interp since anything else can and will cause + # cycles in the dependency graph. The cran metadata + # lists all dependencies anyway, even those packages + # that are in the recommended group. + # We don't include any R version restrictions because + # conda-build always pins r-base and mro-base version. + deps.insert(0, f"{INDENT}{r_interp}") + else: + conda_name = "r-" + name.lower() + + if dep_dict[name]: + deps.append(f"{INDENT}{conda_name} {dep_dict[name]}") + else: + deps.append(f"{INDENT}{conda_name}") + if recursive: + lower_name = name.lower() + if lower_name not in package_dicts: + inputs_dict = package_to_inputs_dict( + output_dir, output_suffix, git_tag, lower_name, None + ) + assert ( + lower_name == inputs_dict["pkg-name"] + ), "name {} != inputs_dict['pkg-name'] {}".format( + name, inputs_dict["pkg-name"] + ) + assert lower_name not in package_list + package_dicts.update( + {lower_name: {"inputs": inputs_dict}} + ) + package_list.append(lower_name) + + d["%s_depends" % dep_type] = "".join(deps) + + if no_comments: + global CRAN_BUILD_SH_SOURCE, CRAN_META + CRAN_BUILD_SH_SOURCE = remove_comments(CRAN_BUILD_SH_SOURCE) + CRAN_META = remove_comments(CRAN_META) + + for package in package_dicts: + d = package_dicts[package] + dir_path = d["inputs"]["new-location"] + if exists(dir_path) and not version_compare: + if update_policy == "error": + raise RuntimeError( + "directory already exists " + "(and --update-policy is 'error'): %s" % dir_path + ) + elif update_policy == "overwrite": + rm_rf(dir_path) + elif update_policy == "skip-up-to-date": + if cran_index is None: + session = get_session(output_dir) + cran_index = get_cran_index(cran_url, session) + if up_to_date(cran_index, d["inputs"]["old-metadata"]): + continue + elif update_policy == "skip-existing" and d["inputs"]["old-metadata"]: + continue + + from_sources = d["from_source"] + # Normalize the metadata values + d = { + k: unicodedata.normalize("NFKD", str(v)).encode("ascii", "ignore").decode() + for k, v in d.items() + } + try: + makedirs(join(dir_path)) + except: + pass + print("Writing recipe for %s" % package.lower()) + with open(join(dir_path, "meta.yaml"), "w") as f: + f.write(clear_whitespace(CRAN_META.format(**d))) + if not exists(join(dir_path, "build.sh")) or update_policy == "overwrite": + with open(join(dir_path, "build.sh"), "wb") as f: + if from_sources == _all: + f.write(CRAN_BUILD_SH_SOURCE.format(**d).encode("utf-8")) + elif from_sources == []: + f.write(CRAN_BUILD_SH_BINARY.format(**d).encode("utf-8")) + else: + tpbt = [target_platform_bash_test_by_sel[t] for t in from_sources] + d["source_pf_bash"] = " || ".join( + ["[[ ${target_platform} " + s + " ]]" for s in tpbt] + ) + f.write(CRAN_BUILD_SH_MIXED.format(**d).encode("utf-8")) + + if not exists(join(dir_path, "bld.bat")) or update_policy == "overwrite": + with open(join(dir_path, "bld.bat"), "wb") as f: + if len([fs for fs in from_sources if fs.startswith("win")]) == 2: + f.write( + CRAN_BLD_BAT_SOURCE.format(**d) + .replace("\n", "\r\n") + .encode("utf-8") + ) + else: + f.write( + CRAN_BLD_BAT_MIXED.format(**d) + .replace("\n", "\r\n") + .encode("utf-8") + ) + + +def version_compare(recipe_dir: str, newest_conda_version): + m = MetaData(recipe_dir) + local_version = m.version() + package = basename(recipe_dir) + + print(f"Local recipe for {package} has version {local_version}.") + + print(f"The version on CRAN for {package} is {newest_conda_version}.") + + return local_version == newest_conda_version + + +def get_outdated(output_dir, cran_index, packages=()): + to_update = [] + recipes = listdir(output_dir) + for recipe in recipes: + if not recipe.startswith("r-") or not isdir(recipe): + continue + + recipe_name = recipe[2:] + + if packages and not (recipe_name in packages or recipe in packages): + continue + + if recipe_name not in cran_index: + print("Skipping %s, not found on CRAN" % recipe) + continue + + version_compare( + join(output_dir, recipe), cran_index[recipe_name][1].replace("-", "_") + ) + + print("Updating %s" % recipe) + to_update.append(recipe_name) + + return to_update + + +def get_existing(output_dir, cran_index, packages=()): + existing = [] + recipes = listdir(output_dir) + for recipe in recipes: + if not recipe.startswith("r-") or not isdir(recipe): + continue + + recipe_name = recipe[2:] + + if packages and not (recipe_name in packages or recipe in packages): + continue + + existing.append(recipe_name) + + return existing + + +def up_to_date(cran_index, package): + r_pkg_name, location, old_git_rev, m = package + cran_pkg_name = r_pkg_name[2:] + + # Does not exist, so is not up to date. + if not m: + return False + + # For now. We can do better; need to collect *all* information upfront. + if "github.com" in location: + return False + else: + if cran_pkg_name not in cran_index: + return False + + name, version = cran_index[cran_pkg_name] + if version and m.version() != version: + return False + + return True + + +def get_license_info(license_text, allowed_license_families): + """ + Most R packages on CRAN do not include a license file. Instead, to avoid + duplication, R base ships with common software licenses: + + complete: AGPL-3, Artistic-2.0, GPL-2, GPL-3, LGPL-2, LGPL-2.1, LGPL-3 + template: BSD_2_clause BSD_3_clause, MIT + + The complete licenses can be included in conda binaries by pointing to the + license file shipped with R base. The template files are more complicated + because they would need to be combined with the license information provided + by the package authors. In this case, the template file and the license + information file are both packaged. All optional ('|' seperated) licenses + are included, if they are matching. + + This function returns the path to the license file for the unambiguous + cases. + """ + + # The list order matters. The first element should be the name of the + # license file shipped with r-base. + d_license = { + "agpl3": ["AGPL-3", "AGPL (>= 3)", "AGPL", "GNU Affero General Public License"], + "artistic2": ["Artistic-2.0", "Artistic License 2.0"], + "gpl2": ["GPL-2", "GPL (>= 2)", "GNU General Public License (>= 2)"], + "gpl3": [ + "GPL-3", + "GPL (>= 3)", + "GNU General Public License (>= 3)", + "GPL", + "GNU General Public License", + ], + "lgpl2": ["LGPL-2", "LGPL (>= 2)"], + "lgpl21": ["LGPL-2.1", "LGPL (>= 2.1)"], + "lgpl3": ["LGPL-3", "LGPL (>= 3)", "LGPL", "GNU Lesser General Public License"], + "bsd2": ["BSD_2_clause", "BSD_2_Clause", "BSD 2-clause License"], + "bsd3": ["BSD_3_clause", "BSD_3_Clause", "BSD 3-clause License"], + "mit": ["MIT"], + } + + license_file_template = ( + "'{{{{ environ[\"PREFIX\"] }}}}/lib/R/share/licenses/{license_id}'" + ) + + license_texts = [] + license_files = [] + + # split license_text by "|" and "+" into parts for further matching + license_text_parts = [l_opt.strip() for l_opt in re.split(r"\||\+", license_text)] + for l_opt in license_text_parts: + # the file case + if l_opt.startswith("file "): + license_files.append(l_opt[5:]) + continue + + # license id string to match + for license_id in d_license.keys(): + if l_opt in d_license[license_id]: + l_opt_text = d_license[license_id][0] + + license_texts.append(l_opt_text) + license_files.append( + license_file_template.format(license_id=l_opt_text) + ) + break + + # Join or fallback to original license_text if matched license_texts is empty + license_text = " | ".join(license_texts) or license_text + + # Build the license_file entry and ensure it is empty if no license file + license_file = "" + if license_files: + license_file = f"license_file:{dashlist(license_files, indent=4)}\n" + + # Only one family is allowed, so guessing it once + license_family = guess_license_family(license_text, allowed_license_families) + + return license_text, license_file, license_family diff --git a/shared/package-files/d1/d15260139f3537e238c48c9c3375dd640dc083d7b976ed16dadcd6c16bee3e36/blob b/shared/package-files/d1/d15260139f3537e238c48c9c3375dd640dc083d7b976ed16dadcd6c16bee3e36/blob new file mode 100644 index 0000000000000000000000000000000000000000..28fc4de0409b3ceeeb274728b192a5ed6011b4e8 --- /dev/null +++ b/shared/package-files/d1/d15260139f3537e238c48c9c3375dd640dc083d7b976ed16dadcd6c16bee3e36/blob @@ -0,0 +1,41 @@ +import mimetools +import SocketServer +from typing import Any, BinaryIO, Callable, Mapping, Optional, Tuple, Union + +class HTTPServer(SocketServer.TCPServer): + server_name: str + server_port: int + def __init__(self, server_address: Tuple[str, int], RequestHandlerClass: Callable[..., BaseHTTPRequestHandler]) -> None: ... + +class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): + client_address: Tuple[str, int] + server: SocketServer.BaseServer + close_connection: bool + command: str + path: str + request_version: str + headers: mimetools.Message + rfile: BinaryIO + wfile: BinaryIO + server_version: str + sys_version: str + error_message_format: str + error_content_type: str + protocol_version: str + MessageClass: type + responses: Mapping[int, Tuple[str, str]] + def __init__(self, request: bytes, client_address: Tuple[str, int], server: SocketServer.BaseServer) -> None: ... + def handle(self) -> None: ... + def handle_one_request(self) -> None: ... + def send_error(self, code: int, message: Optional[str] = ...) -> None: ... + def send_response(self, code: int, message: Optional[str] = ...) -> None: ... + def send_header(self, keyword: str, value: str) -> None: ... + def end_headers(self) -> None: ... + def flush_headers(self) -> None: ... + def log_request(self, code: Union[int, str] = ..., size: Union[int, str] = ...) -> None: ... + def log_error(self, format: str, *args: Any) -> None: ... + def log_message(self, format: str, *args: Any) -> None: ... + def version_string(self) -> str: ... + def date_time_string(self, timestamp: Optional[int] = ...) -> str: ... + def log_date_time_string(self) -> str: ... + def address_string(self) -> str: ... diff --git a/shared/package-files/d1/d154c88737ca80170ac4e78e7682aad686bb66e6da94e8fd2acd1e7c4d3e726b/blob b/shared/package-files/d1/d154c88737ca80170ac4e78e7682aad686bb66e6da94e8fd2acd1e7c4d3e726b/blob new file mode 100644 index 0000000000000000000000000000000000000000..1538dac7510ee54fff13977a408480bb2b45fa18 --- /dev/null +++ b/shared/package-files/d1/d154c88737ca80170ac4e78e7682aad686bb66e6da94e8fd2acd1e7c4d3e726b/blob @@ -0,0 +1,159 @@ +from cycler import Cycler + +from collections.abc import Callable, Iterable +from typing import Any, Literal, TypeVar +from matplotlib.typing import ColorType, LineStyleType, MarkEveryType + +interactive_bk: list[str] +non_interactive_bk: list[str] +all_backends: list[str] + +_T = TypeVar("_T") + +def _listify_validator(s: Callable[[Any], _T]) -> Callable[[Any], list[_T]]: ... + +class ValidateInStrings: + key: str + ignorecase: bool + valid: dict[str, str] + def __init__( + self, + key: str, + valid: Iterable[str], + ignorecase: bool = ..., + *, + _deprecated_since: str | None = ... + ) -> None: ... + def __call__(self, s: Any) -> str: ... + +def validate_any(s: Any) -> Any: ... +def validate_anylist(s: Any) -> list[Any]: ... +def validate_bool(b: Any) -> bool: ... +def validate_axisbelow(s: Any) -> bool | Literal["line"]: ... +def validate_dpi(s: Any) -> Literal["figure"] | float: ... +def validate_string(s: Any) -> str: ... +def validate_string_or_None(s: Any) -> str | None: ... +def validate_stringlist(s: Any) -> list[str]: ... +def validate_int(s: Any) -> int: ... +def validate_int_or_None(s: Any) -> int | None: ... +def validate_float(s: Any) -> float: ... +def validate_float_or_None(s: Any) -> float | None: ... +def validate_floatlist(s: Any) -> list[float]: ... +def _validate_marker(s: Any) -> int | str: ... +def _validate_markerlist(s: Any) -> list[int | str]: ... +def validate_fonttype(s: Any) -> int: ... + +_auto_backend_sentinel: object + +def validate_backend(s: Any) -> str: ... +def validate_color_or_inherit(s: Any) -> Literal["inherit"] | ColorType: ... +def validate_color_or_auto(s: Any) -> ColorType | Literal["auto"]: ... +def validate_color_for_prop_cycle(s: Any) -> ColorType: ... +def validate_color(s: Any) -> ColorType: ... +def validate_colorlist(s: Any) -> list[ColorType]: ... +def _validate_color_or_linecolor( + s: Any, +) -> ColorType | Literal["linecolor", "markerfacecolor", "markeredgecolor"] | None: ... +def validate_aspect(s: Any) -> Literal["auto", "equal"] | float: ... +def validate_fontsize_None( + s: Any, +) -> Literal[ + "xx-small", + "x-small", + "small", + "medium", + "large", + "x-large", + "xx-large", + "smaller", + "larger", +] | float | None: ... +def validate_fontsize( + s: Any, +) -> Literal[ + "xx-small", + "x-small", + "small", + "medium", + "large", + "x-large", + "xx-large", + "smaller", + "larger", +] | float: ... +def validate_fontsizelist( + s: Any, +) -> list[ + Literal[ + "xx-small", + "x-small", + "small", + "medium", + "large", + "x-large", + "xx-large", + "smaller", + "larger", + ] + | float +]: ... +def validate_fontweight( + s: Any, +) -> Literal[ + "ultralight", + "light", + "normal", + "regular", + "book", + "medium", + "roman", + "semibold", + "demibold", + "demi", + "bold", + "heavy", + "extra bold", + "black", +] | int: ... +def validate_fontstretch( + s: Any, +) -> Literal[ + "ultra-condensed", + "extra-condensed", + "condensed", + "semi-condensed", + "normal", + "semi-expanded", + "expanded", + "extra-expanded", + "ultra-expanded", +] | int: ... +def validate_font_properties(s: Any) -> dict[str, Any]: ... +def validate_whiskers(s: Any) -> list[float] | float: ... +def validate_ps_distiller(s: Any) -> None | Literal["ghostscript", "xpdf"]: ... + +validate_fillstyle: ValidateInStrings + +def validate_fillstylelist( + s: Any, +) -> list[Literal["full", "left", "right", "bottom", "top", "none"]]: ... +def validate_markevery(s: Any) -> MarkEveryType: ... +def _validate_linestyle(s: Any) -> LineStyleType: ... +def validate_markeverylist(s: Any) -> list[MarkEveryType]: ... +def validate_bbox(s: Any) -> Literal["tight", "standard"] | None: ... +def validate_sketch(s: Any) -> None | tuple[float, float, float]: ... +def validate_hatch(s: Any) -> str: ... +def validate_hatchlist(s: Any) -> list[str]: ... +def validate_dashlist(s: Any) -> list[list[float]]: ... + +# TODO: copy cycler overloads? +def cycler(*args, **kwargs) -> Cycler: ... +def validate_cycler(s: Any) -> Cycler: ... +def validate_hist_bins( + s: Any, +) -> Literal["auto", "sturges", "fd", "doane", "scott", "rice", "sqrt"] | int | list[ + float +]: ... + +# At runtime is added in __init__.py +defaultParams: dict[str, Any] diff --git a/shared/package-files/d1/d15889a91b4964b212ec87e31eb520608e9122f598d1c7e4d4e8c0969e3466cc/blob b/shared/package-files/d1/d15889a91b4964b212ec87e31eb520608e9122f598d1c7e4d4e8c0969e3466cc/blob new file mode 100644 index 0000000000000000000000000000000000000000..4b061e8006031c56c2c5ef5f56a342f8b2a60bc4 --- /dev/null +++ b/shared/package-files/d1/d15889a91b4964b212ec87e31eb520608e9122f598d1c7e4d4e8c0969e3466cc/blob @@ -0,0 +1 @@ +matplotlib_inline diff --git a/shared/package-files/d1/d159825fa445043182b976a7449e6b5877fa4fbf3579d4cba609ca3130ff0ed5/blob b/shared/package-files/d1/d159825fa445043182b976a7449e6b5877fa4fbf3579d4cba609ca3130ff0ed5/blob new file mode 100644 index 0000000000000000000000000000000000000000..a16c63e8d3d65f1354fdb4c32c0599fec644bd01 --- /dev/null +++ b/shared/package-files/d1/d159825fa445043182b976a7449e6b5877fa4fbf3579d4cba609ca3130ff0ed5/blob @@ -0,0 +1,416 @@ +from textwrap import dedent + +import numpy as np +import pytest + +from pandas.errors import ( + PyperclipException, + PyperclipWindowsException, +) + +import pandas as pd +from pandas import ( + NA, + DataFrame, + Series, + get_option, + read_clipboard, +) +import pandas._testing as tm + +from pandas.io.clipboard import ( + CheckedCall, + _stringifyText, + init_qt_clipboard, +) + + +def build_kwargs(sep, excel): + kwargs = {} + if excel != "default": + kwargs["excel"] = excel + if sep != "default": + kwargs["sep"] = sep + return kwargs + + +@pytest.fixture( + params=[ + "delims", + "utf8", + "utf16", + "string", + "long", + "nonascii", + "colwidth", + "mixed", + "float", + "int", + ] +) +def df(request): + data_type = request.param + + if data_type == "delims": + return DataFrame({"a": ['"a,\t"b|c', "d\tef`"], "b": ["hi'j", "k''lm"]}) + elif data_type == "utf8": + return DataFrame({"a": ["µasd", "Ωœ∑`"], "b": ["øπ∆˚¬", "œ∑`®"]}) + elif data_type == "utf16": + return DataFrame( + {"a": ["\U0001f44d\U0001f44d", "\U0001f44d\U0001f44d"], "b": ["abc", "def"]} + ) + elif data_type == "string": + return DataFrame( + np.array([f"i-{i}" for i in range(15)]).reshape(5, 3), columns=list("abc") + ) + elif data_type == "long": + max_rows = get_option("display.max_rows") + return DataFrame( + np.random.default_rng(2).integers(0, 10, size=(max_rows + 1, 3)), + columns=list("abc"), + ) + elif data_type == "nonascii": + return DataFrame({"en": "in English".split(), "es": "en español".split()}) + elif data_type == "colwidth": + _cw = get_option("display.max_colwidth") + 1 + return DataFrame( + np.array(["x" * _cw for _ in range(15)]).reshape(5, 3), columns=list("abc") + ) + elif data_type == "mixed": + return DataFrame( + { + "a": np.arange(1.0, 6.0) + 0.01, + "b": np.arange(1, 6).astype(np.int64), + "c": list("abcde"), + } + ) + elif data_type == "float": + return DataFrame(np.random.default_rng(2).random((5, 3)), columns=list("abc")) + elif data_type == "int": + return DataFrame( + np.random.default_rng(2).integers(0, 10, (5, 3)), columns=list("abc") + ) + else: + raise ValueError + + +@pytest.fixture +def mock_ctypes(monkeypatch): + """ + Mocks WinError to help with testing the clipboard. + """ + + def _mock_win_error(): + return "Window Error" + + # Set raising to False because WinError won't exist on non-windows platforms + with monkeypatch.context() as m: + m.setattr("ctypes.WinError", _mock_win_error, raising=False) + yield + + +@pytest.mark.usefixtures("mock_ctypes") +def test_checked_call_with_bad_call(monkeypatch): + """ + Give CheckCall a function that returns a falsey value and + mock get_errno so it returns false so an exception is raised. + """ + + def _return_false(): + return False + + monkeypatch.setattr("pandas.io.clipboard.get_errno", lambda: True) + msg = f"Error calling {_return_false.__name__} \\(Window Error\\)" + + with pytest.raises(PyperclipWindowsException, match=msg): + CheckedCall(_return_false)() + + +@pytest.mark.usefixtures("mock_ctypes") +def test_checked_call_with_valid_call(monkeypatch): + """ + Give CheckCall a function that returns a truthy value and + mock get_errno so it returns true so an exception is not raised. + The function should return the results from _return_true. + """ + + def _return_true(): + return True + + monkeypatch.setattr("pandas.io.clipboard.get_errno", lambda: False) + + # Give CheckedCall a callable that returns a truthy value s + checked_call = CheckedCall(_return_true) + assert checked_call() is True + + +@pytest.mark.parametrize( + "text", + [ + "String_test", + True, + 1, + 1.0, + 1j, + ], +) +def test_stringify_text(text): + valid_types = (str, int, float, bool) + + if isinstance(text, valid_types): + result = _stringifyText(text) + assert result == str(text) + else: + msg = ( + "only str, int, float, and bool values " + f"can be copied to the clipboard, not {type(text).__name__}" + ) + with pytest.raises(PyperclipException, match=msg): + _stringifyText(text) + + +@pytest.fixture +def set_pyqt_clipboard(monkeypatch): + qt_cut, qt_paste = init_qt_clipboard() + with monkeypatch.context() as m: + m.setattr(pd.io.clipboard, "clipboard_set", qt_cut) + m.setattr(pd.io.clipboard, "clipboard_get", qt_paste) + yield + + +@pytest.fixture +def clipboard(qapp): + clip = qapp.clipboard() + yield clip + clip.clear() + + +@pytest.mark.single_cpu +@pytest.mark.clipboard +@pytest.mark.usefixtures("set_pyqt_clipboard") +@pytest.mark.usefixtures("clipboard") +class TestClipboard: + # Test that default arguments copy as tab delimited + # Test that explicit delimiters are respected + @pytest.mark.parametrize("sep", [None, "\t", ",", "|"]) + @pytest.mark.parametrize("encoding", [None, "UTF-8", "utf-8", "utf8"]) + def test_round_trip_frame_sep(self, df, sep, encoding): + df.to_clipboard(excel=None, sep=sep, encoding=encoding) + result = read_clipboard(sep=sep or "\t", index_col=0, encoding=encoding) + tm.assert_frame_equal(df, result) + + # Test white space separator + def test_round_trip_frame_string(self, df): + df.to_clipboard(excel=False, sep=None) + result = read_clipboard() + assert df.to_string() == result.to_string() + assert df.shape == result.shape + + # Two character separator is not supported in to_clipboard + # Test that multi-character separators are not silently passed + def test_excel_sep_warning(self, df): + with tm.assert_produces_warning( + UserWarning, + match="to_clipboard in excel mode requires a single character separator.", + check_stacklevel=False, + ): + df.to_clipboard(excel=True, sep=r"\t") + + # Separator is ignored when excel=False and should produce a warning + def test_copy_delim_warning(self, df): + with tm.assert_produces_warning(): + df.to_clipboard(excel=False, sep="\t") + + # Tests that the default behavior of to_clipboard is tab + # delimited and excel="True" + @pytest.mark.parametrize("sep", ["\t", None, "default"]) + @pytest.mark.parametrize("excel", [True, None, "default"]) + def test_clipboard_copy_tabs_default(self, sep, excel, df, clipboard): + kwargs = build_kwargs(sep, excel) + df.to_clipboard(**kwargs) + assert clipboard.text() == df.to_csv(sep="\t") + + # Tests reading of white space separated tables + @pytest.mark.parametrize("sep", [None, "default"]) + def test_clipboard_copy_strings(self, sep, df): + kwargs = build_kwargs(sep, False) + df.to_clipboard(**kwargs) + result = read_clipboard(sep=r"\s+") + assert result.to_string() == df.to_string() + assert df.shape == result.shape + + def test_read_clipboard_infer_excel(self, clipboard): + # gh-19010: avoid warnings + clip_kwargs = {"engine": "python"} + + text = dedent( + """ + John James\tCharlie Mingus + 1\t2 + 4\tHarry Carney + """.strip() + ) + clipboard.setText(text) + df = read_clipboard(**clip_kwargs) + + # excel data is parsed correctly + assert df.iloc[1, 1] == "Harry Carney" + + # having diff tab counts doesn't trigger it + text = dedent( + """ + a\t b + 1 2 + 3 4 + """.strip() + ) + clipboard.setText(text) + res = read_clipboard(**clip_kwargs) + + text = dedent( + """ + a b + 1 2 + 3 4 + """.strip() + ) + clipboard.setText(text) + exp = read_clipboard(**clip_kwargs) + + tm.assert_frame_equal(res, exp) + + def test_infer_excel_with_nulls(self, clipboard): + # GH41108 + text = "col1\tcol2\n1\tred\n\tblue\n2\tgreen" + + clipboard.setText(text) + df = read_clipboard() + df_expected = DataFrame( + data={"col1": [1, None, 2], "col2": ["red", "blue", "green"]} + ) + + # excel data is parsed correctly + tm.assert_frame_equal(df, df_expected) + + @pytest.mark.parametrize( + "multiindex", + [ + ( # Can't use `dedent` here as it will remove the leading `\t` + "\n".join( + [ + "\t\t\tcol1\tcol2", + "A\t0\tTrue\t1\tred", + "A\t1\tTrue\t\tblue", + "B\t0\tFalse\t2\tgreen", + ] + ), + [["A", "A", "B"], [0, 1, 0], [True, True, False]], + ), + ( + "\n".join( + ["\t\tcol1\tcol2", "A\t0\t1\tred", "A\t1\t\tblue", "B\t0\t2\tgreen"] + ), + [["A", "A", "B"], [0, 1, 0]], + ), + ], + ) + def test_infer_excel_with_multiindex(self, clipboard, multiindex): + # GH41108 + + clipboard.setText(multiindex[0]) + df = read_clipboard() + df_expected = DataFrame( + data={"col1": [1, None, 2], "col2": ["red", "blue", "green"]}, + index=multiindex[1], + ) + + # excel data is parsed correctly + tm.assert_frame_equal(df, df_expected) + + def test_invalid_encoding(self, df): + msg = "clipboard only supports utf-8 encoding" + # test case for testing invalid encoding + with pytest.raises(ValueError, match=msg): + df.to_clipboard(encoding="ascii") + with pytest.raises(NotImplementedError, match=msg): + read_clipboard(encoding="ascii") + + @pytest.mark.parametrize("data", ["\U0001f44d...", "Ωœ∑`...", "abcd..."]) + def test_raw_roundtrip(self, data): + # PR #25040 wide unicode wasn't copied correctly on PY3 on windows + df = DataFrame({"data": [data]}) + df.to_clipboard() + result = read_clipboard() + tm.assert_frame_equal(df, result) + + @pytest.mark.parametrize("engine", ["c", "python"]) + def test_read_clipboard_dtype_backend( + self, clipboard, string_storage, dtype_backend, engine, using_infer_string + ): + # GH#50502 + if dtype_backend == "pyarrow": + pa = pytest.importorskip("pyarrow") + if engine == "c" and string_storage == "pyarrow": + # TODO avoid this exception? + string_dtype = pd.ArrowDtype(pa.large_string()) + else: + string_dtype = pd.ArrowDtype(pa.string()) + else: + string_dtype = pd.StringDtype(string_storage) + + text = """a,b,c,d,e,f,g,h,i +x,1,4.0,x,2,4.0,,True,False +y,2,5.0,,,,,False,""" + clipboard.setText(text) + + with pd.option_context("mode.string_storage", string_storage): + result = read_clipboard(sep=",", dtype_backend=dtype_backend, engine=engine) + + expected = DataFrame( + { + "a": Series(["x", "y"], dtype=string_dtype), + "b": Series([1, 2], dtype="Int64"), + "c": Series([4.0, 5.0], dtype="Float64"), + "d": Series(["x", None], dtype=string_dtype), + "e": Series([2, NA], dtype="Int64"), + "f": Series([4.0, NA], dtype="Float64"), + "g": Series([NA, NA], dtype="Int64"), + "h": Series([True, False], dtype="boolean"), + "i": Series([False, NA], dtype="boolean"), + } + ) + if dtype_backend == "pyarrow": + from pandas.arrays import ArrowExtensionArray + + expected = DataFrame( + { + col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True)) + for col in expected.columns + } + ) + expected["g"] = ArrowExtensionArray(pa.array([None, None])) + + if using_infer_string: + expected.columns = expected.columns.astype( + pd.StringDtype(string_storage, na_value=np.nan) + ) + + tm.assert_frame_equal(result, expected) + + def test_invalid_dtype_backend(self): + msg = ( + "dtype_backend numpy is invalid, only 'numpy_nullable' and " + "'pyarrow' are allowed." + ) + with pytest.raises(ValueError, match=msg): + read_clipboard(dtype_backend="numpy") + + def test_to_clipboard_pos_args_deprecation(self): + # GH-54229 + df = DataFrame({"a": [1, 2, 3]}) + msg = ( + r"Starting with pandas version 3.0 all arguments of to_clipboard " + r"will be keyword-only." + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + df.to_clipboard(True, None) diff --git a/shared/package-files/d1/d159c8e2cbb7ecf04ca2fb36f34f74681795da7686dbdd92da7d71cbce68a67a/blob b/shared/package-files/d1/d159c8e2cbb7ecf04ca2fb36f34f74681795da7686dbdd92da7d71cbce68a67a/blob new file mode 100644 index 0000000000000000000000000000000000000000..1311b90c397a4ccf9d4c22a318cb6fa8b45c16c9 Binary files /dev/null and b/shared/package-files/d1/d159c8e2cbb7ecf04ca2fb36f34f74681795da7686dbdd92da7d71cbce68a67a/blob differ diff --git a/shared/package-files/d1/d15bf647e4dd05bfefa3f266f1c6e1d4885b5a30e460fc3e84df1819f958946c/blob b/shared/package-files/d1/d15bf647e4dd05bfefa3f266f1c6e1d4885b5a30e460fc3e84df1819f958946c/blob new file mode 100644 index 0000000000000000000000000000000000000000..fe600213bcc89d34d2cba4021ff6989a7bad96ba --- /dev/null +++ b/shared/package-files/d1/d15bf647e4dd05bfefa3f266f1c6e1d4885b5a30e460fc3e84df1819f958946c/blob @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 + +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import datetime +import logging +from typing import Tuple, cast, Optional + +# pyre-ignore[21]: Could not find name `Store` in `torch.distributed`. +from torch.distributed import Store, TCPStore, PrefixStore +from torch.distributed.elastic.rendezvous import RendezvousHandler, RendezvousParameters +from torch.distributed.elastic.rendezvous.utils import parse_rendezvous_endpoint + +log = logging.getLogger(__name__) + +_default_timeout_seconds = 600 + + +class StaticTCPRendezvous(RendezvousHandler): + """ + Static rendezvous that is a wrapper around the TCPStore. + + Creates TCPStore based on the input parameters with the + listener on the agent with group_rank=0 + """ + + def __init__( + self, + master_addr: str, + master_port: int, + rank: int, + world_size: int, + run_id: str, + timeout: int, + ): + self.master_addr = master_addr + self.master_port = master_port + self.rank = rank + self.world_size = world_size + self.run_id = run_id + self.timeout = datetime.timedelta(seconds=timeout) + self._store: Optional[Store] = None + + def get_backend(self) -> str: + return "static" + + def next_rendezvous(self) -> Tuple[Store, int, int]: + log.info("Creating TCPStore as the c10d::Store implementation") + if not self._store: + is_master = self.rank == 0 + self._store = TCPStore( # type: ignore[call-arg] + self.master_addr, + self.master_port, + self.world_size, + is_master, + self.timeout, + multi_tenant=True, + ) + store = PrefixStore(self.run_id, self._store) + return store, self.rank, self.world_size + + def is_closed(self): + return False + + def set_closed(self): + pass + + def num_nodes_waiting(self): + return 0 + + def get_run_id(self) -> str: + return self.run_id + + def shutdown(self) -> bool: + return True + + +def create_rdzv_handler(params: RendezvousParameters) -> RendezvousHandler: + if "rank" not in params.config: + raise ValueError( + "rank is absent in RendezvousParameters." + "Try add --node-rank to the cmd request" + ) + endpoint = params.endpoint.strip() + if not endpoint: + raise ValueError( + "endpoint is absent in RendezvousParameters" + "Try add --master-port and --master-addr to the cmd request" + ) + master_addr, master_port = parse_rendezvous_endpoint(endpoint, -1) + if master_port == -1: + raise ValueError( + f"Port is absent in endpoint: {endpoint}. Try launching with --master-port" + ) + world_size = params.max_nodes + rank = cast(int, params.config.get("rank")) + run_id = params.run_id + if "timeout" in params.config: + timeout = int(params.config["timeout"]) + else: + timeout = _default_timeout_seconds + return StaticTCPRendezvous( + master_addr, master_port, rank, world_size, run_id, timeout + ) diff --git a/shared/package-files/d1/d15d8d9e86cd5a1d2c40bd701d19f64d31f8cc0dc24dea6e682527eb2f7b35e3/blob b/shared/package-files/d1/d15d8d9e86cd5a1d2c40bd701d19f64d31f8cc0dc24dea6e682527eb2f7b35e3/blob new file mode 100644 index 0000000000000000000000000000000000000000..dd43946208ce0e60a09444ea4bb78c4b3ccb21dc --- /dev/null +++ b/shared/package-files/d1/d15d8d9e86cd5a1d2c40bd701d19f64d31f8cc0dc24dea6e682527eb2f7b35e3/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor round(const at::Tensor & self); +TORCH_API at::Tensor & round_(at::Tensor & self); +TORCH_API at::Tensor round(const at::Tensor & self, int64_t decimals); +TORCH_API at::Tensor & round_(at::Tensor & self, int64_t decimals); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/d1/d16101c6ff854a0a30d51159cda5c6168d348b0925205e45a632590ce3966c3a/blob b/shared/package-files/d1/d16101c6ff854a0a30d51159cda5c6168d348b0925205e45a632590ce3966c3a/blob new file mode 100644 index 0000000000000000000000000000000000000000..fce5ae07301c3cbf6f8bc011e783f820db6a1217 --- /dev/null +++ b/shared/package-files/d1/d16101c6ff854a0a30d51159cda5c6168d348b0925205e45a632590ce3966c3a/blob @@ -0,0 +1,102 @@ +""" + pygments.lexers.bare + ~~~~~~~~~~~~~~~~~~~~ + + Lexer for the BARE schema. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.lexer import RegexLexer, words, bygroups +from pygments.token import Text, Comment, Keyword, Name, Literal, Whitespace + +__all__ = ['BareLexer'] + + +class BareLexer(RegexLexer): + """ + For BARE schema source. + + .. versionadded:: 2.7 + """ + name = 'BARE' + url = 'https://baremessages.org' + filenames = ['*.bare'] + aliases = ['bare'] + + keywords = [ + 'type', + 'enum', + 'u8', + 'u16', + 'u32', + 'u64', + 'uint', + 'i8', + 'i16', + 'i32', + 'i64', + 'int', + 'f32', + 'f64', + 'bool', + 'void', + 'data', + 'string', + 'optional', + 'map', + ] + + tokens = { + 'root': [ + (r'(type)(\s+)([A-Z][a-zA-Z0-9]+)(\s+)(\{)', + bygroups(Keyword, Whitespace, Name.Class, Whitespace, Text), 'struct'), + (r'(type)(\s+)([A-Z][a-zA-Z0-9]+)(\s+)(\()', + bygroups(Keyword, Whitespace, Name.Class, Whitespace, Text), 'union'), + (r'(type)(\s+)([A-Z][a-zA-Z0-9]+)(\s+)', + bygroups(Keyword, Whitespace, Name, Whitespace), 'typedef'), + (r'(enum)(\s+)([A-Z][a-zA-Z0-9]+)(\s+\{)', + bygroups(Keyword, Whitespace, Name.Class, Whitespace), 'enum'), + (r'#.*?$', Comment), + (r'\s+', Whitespace), + ], + 'struct': [ + (r'\{', Text, '#push'), + (r'\}', Text, '#pop'), + (r'([a-zA-Z0-9]+)(:)(\s*)', + bygroups(Name.Attribute, Text, Whitespace), 'typedef'), + (r'\s+', Whitespace), + ], + 'union': [ + (r'\)', Text, '#pop'), + (r'(\s*)(\|)(\s*)', bygroups(Whitespace, Text, Whitespace)), + (r'[A-Z][a-zA-Z0-9]+', Name.Class), + (words(keywords), Keyword), + (r'\s+', Whitespace), + ], + 'typedef': [ + (r'\[\]', Text), + (r'#.*?$', Comment, '#pop'), + (r'(\[)(\d+)(\])', bygroups(Text, Literal, Text)), + (r'<|>', Text), + (r'\(', Text, 'union'), + (r'(\[)([a-z][a-z-A-Z0-9]+)(\])', bygroups(Text, Keyword, Text)), + (r'(\[)([A-Z][a-z-A-Z0-9]+)(\])', bygroups(Text, Name.Class, Text)), + (r'([A-Z][a-z-A-Z0-9]+)', Name.Class), + (words(keywords), Keyword), + (r'\n', Text, '#pop'), + (r'\{', Text, 'struct'), + (r'\s+', Whitespace), + (r'\d+', Literal), + ], + 'enum': [ + (r'\{', Text, '#push'), + (r'\}', Text, '#pop'), + (r'([A-Z][A-Z0-9_]*)(\s*=\s*)(\d+)', + bygroups(Name.Attribute, Text, Literal)), + (r'([A-Z][A-Z0-9_]*)', bygroups(Name.Attribute)), + (r'#.*?$', Comment), + (r'\s+', Whitespace), + ], + } diff --git a/shared/package-files/d1/d1628f2668e4de52fee572fc113ec0388a38fbe9b8e5495d6c8871586559197b/blob b/shared/package-files/d1/d1628f2668e4de52fee572fc113ec0388a38fbe9b8e5495d6c8871586559197b/blob new file mode 100644 index 0000000000000000000000000000000000000000..ebf39b21a19df482822ba0ac03675b386f5fc082 --- /dev/null +++ b/shared/package-files/d1/d1628f2668e4de52fee572fc113ec0388a38fbe9b8e5495d6c8871586559197b/blob @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & trace_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor trace_cpu(const at::Tensor & self); +TORCH_API at::Tensor trace_cuda(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/d1/d163eaec0f9aa96909b15f88035ffb74534273105a723d40584c5a5db5c4ac6e/blob b/shared/package-files/d1/d163eaec0f9aa96909b15f88035ffb74534273105a723d40584c5a5db5c4ac6e/blob new file mode 100644 index 0000000000000000000000000000000000000000..1ab01cd079c20203657ef3f3e784d84f55d0dee4 --- /dev/null +++ b/shared/package-files/d1/d163eaec0f9aa96909b15f88035ffb74534273105a723d40584c5a5db5c4ac6e/blob @@ -0,0 +1,56 @@ +import sys +import types + +import numpy as np +from numpy import f2py + +if sys.version_info >= (3, 11): + from typing import assert_type +else: + from typing_extensions import assert_type + +assert_type(np, types.ModuleType) + +assert_type(np.char, types.ModuleType) +assert_type(np.ctypeslib, types.ModuleType) +assert_type(np.emath, types.ModuleType) +assert_type(np.fft, types.ModuleType) +assert_type(np.lib, types.ModuleType) +assert_type(np.linalg, types.ModuleType) +assert_type(np.ma, types.ModuleType) +assert_type(np.matrixlib, types.ModuleType) +assert_type(np.polynomial, types.ModuleType) +assert_type(np.random, types.ModuleType) +assert_type(np.rec, types.ModuleType) +assert_type(np.testing, types.ModuleType) +assert_type(np.version, types.ModuleType) +assert_type(np.exceptions, types.ModuleType) +assert_type(np.dtypes, types.ModuleType) + +assert_type(np.lib.format, types.ModuleType) +assert_type(np.lib.mixins, types.ModuleType) +assert_type(np.lib.scimath, types.ModuleType) +assert_type(np.lib.stride_tricks, types.ModuleType) +assert_type(np.ma.extras, types.ModuleType) +assert_type(np.polynomial.chebyshev, types.ModuleType) +assert_type(np.polynomial.hermite, types.ModuleType) +assert_type(np.polynomial.hermite_e, types.ModuleType) +assert_type(np.polynomial.laguerre, types.ModuleType) +assert_type(np.polynomial.legendre, types.ModuleType) +assert_type(np.polynomial.polynomial, types.ModuleType) + +assert_type(np.__path__, list[str]) +assert_type(np.__version__, str) +assert_type(np.test, np._pytesttester.PytestTester) +assert_type(np.test.module_name, str) + +assert_type(np.__all__, list[str]) +assert_type(np.char.__all__, list[str]) +assert_type(np.ctypeslib.__all__, list[str]) +assert_type(np.emath.__all__, list[str]) +assert_type(np.lib.__all__, list[str]) +assert_type(np.ma.__all__, list[str]) +assert_type(np.random.__all__, list[str]) +assert_type(np.rec.__all__, list[str]) +assert_type(np.testing.__all__, list[str]) +assert_type(f2py.__all__, list[str]) diff --git a/shared/package-files/d1/d1648a9846ff3b8a687e05635aa0c20c867054f93762f02e49ba6514afe29139/blob b/shared/package-files/d1/d1648a9846ff3b8a687e05635aa0c20c867054f93762f02e49ba6514afe29139/blob new file mode 100644 index 0000000000000000000000000000000000000000..c50f03dbb25acc0de8a611cf438788b16d8759e9 --- /dev/null +++ b/shared/package-files/d1/d1648a9846ff3b8a687e05635aa0c20c867054f93762f02e49ba6514afe29139/blob @@ -0,0 +1,32 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_max_out : public at::meta::structured_max_dim { +void impl(const at::Tensor & self, int64_t dim, bool keepdim, const at::Tensor & max, const at::Tensor & max_values); +}; +TORCH_API ::std::tuple qmax(const at::Tensor & self, int64_t dim, bool keepdim=false); +TORCH_API ::std::tuple max(const at::Tensor & self, at::Dimname dim, bool keepdim=false); +TORCH_API ::std::tuple max_out(const at::Tensor & self, at::Dimname dim, bool keepdim, at::Tensor & max, at::Tensor & max_values); +TORCH_API at::Tensor max(const at::Tensor & self); +TORCH_API at::Tensor & max_unary_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor max_quantized_cpu(const at::Tensor & self); +TORCH_API at::Tensor & max_quantized_unary_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor max(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & max_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/d1/d16861859d7ad6a76c11296ef77000e95f64d75330ce6365f679c1c88c0ecabd/blob b/shared/package-files/d1/d16861859d7ad6a76c11296ef77000e95f64d75330ce6365f679c1c88c0ecabd/blob new file mode 100644 index 0000000000000000000000000000000000000000..130124cef4b653a84827c7c3fe9b0e7eba0daa0d Binary files /dev/null and b/shared/package-files/d1/d16861859d7ad6a76c11296ef77000e95f64d75330ce6365f679c1c88c0ecabd/blob differ diff --git a/shared/package-files/d1/d16930b7ef8577747cfef602aba854c64ce85d4ae1e54a18a456eaa202643e3d/blob b/shared/package-files/d1/d16930b7ef8577747cfef602aba854c64ce85d4ae1e54a18a456eaa202643e3d/blob new file mode 100644 index 0000000000000000000000000000000000000000..1150bb8b9db2afba11a18f2661fdfd4d9bd4b633 --- /dev/null +++ b/shared/package-files/d1/d16930b7ef8577747cfef602aba854c64ce85d4ae1e54a18a456eaa202643e3d/blob @@ -0,0 +1,23 @@ +# Copyright 2006 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer that transforms `xyzzy` into repr(xyzzy).""" + +# Local imports +from .. import fixer_base +from ..fixer_util import Call, Name, parenthesize + + +class FixRepr(fixer_base.BaseFix): + + BM_compatible = True + PATTERN = """ + atom < '`' expr=any '`' > + """ + + def transform(self, node, results): + expr = results["expr"].clone() + + if expr.type == self.syms.testlist1: + expr = parenthesize(expr) + return Call(Name("repr"), [expr], prefix=node.prefix) diff --git a/shared/package-files/d1/d1696a37fbacd0b5394407688ad33e2a8ff8c60849fc705192d78b439ddf535e/blob b/shared/package-files/d1/d1696a37fbacd0b5394407688ad33e2a8ff8c60849fc705192d78b439ddf535e/blob new file mode 100644 index 0000000000000000000000000000000000000000..fc685935a35fceab74012912d3c3cae65b9c1818 --- /dev/null +++ b/shared/package-files/d1/d1696a37fbacd0b5394407688ad33e2a8ff8c60849fc705192d78b439ddf535e/blob @@ -0,0 +1,176 @@ +""" +Missing data handling for arithmetic operations. + +In particular, pandas conventions regarding division by zero differ +from numpy in the following ways: + 1) np.array([-1, 0, 1], dtype=dtype1) // np.array([0, 0, 0], dtype=dtype2) + gives [nan, nan, nan] for most dtype combinations, and [0, 0, 0] for + the remaining pairs + (the remaining being dtype1==dtype2==intN and dtype==dtype2==uintN). + + pandas convention is to return [-inf, nan, inf] for all dtype + combinations. + + Note: the numpy behavior described here is py3-specific. + + 2) np.array([-1, 0, 1], dtype=dtype1) % np.array([0, 0, 0], dtype=dtype2) + gives precisely the same results as the // operation. + + pandas convention is to return [nan, nan, nan] for all dtype + combinations. + + 3) divmod behavior consistent with 1) and 2). +""" +from __future__ import annotations + +import operator + +import numpy as np + +from pandas.core import roperator + + +def _fill_zeros(result: np.ndarray, x, y): + """ + If this is a reversed op, then flip x,y + + If we have an integer value (or array in y) + and we have 0's, fill them with np.nan, + return the result. + + Mask the nan's from x. + """ + if result.dtype.kind == "f": + return result + + is_variable_type = hasattr(y, "dtype") + is_scalar_type = not isinstance(y, np.ndarray) + + if not is_variable_type and not is_scalar_type: + # e.g. test_series_ops_name_retention with mod we get here with list/tuple + return result + + if is_scalar_type: + y = np.array(y) + + if y.dtype.kind in "iu": + ymask = y == 0 + if ymask.any(): + # GH#7325, mask and nans must be broadcastable + mask = ymask & ~np.isnan(result) + + # GH#9308 doing ravel on result and mask can improve putmask perf, + # but can also make unwanted copies. + result = result.astype("float64", copy=False) + + np.putmask(result, mask, np.nan) + + return result + + +def mask_zero_div_zero(x, y, result: np.ndarray) -> np.ndarray: + """ + Set results of 0 // 0 to np.nan, regardless of the dtypes + of the numerator or the denominator. + + Parameters + ---------- + x : ndarray + y : ndarray + result : ndarray + + Returns + ------- + ndarray + The filled result. + + Examples + -------- + >>> x = np.array([1, 0, -1], dtype=np.int64) + >>> x + array([ 1, 0, -1]) + >>> y = 0 # int 0; numpy behavior is different with float + >>> result = x // y + >>> result # raw numpy result does not fill division by zero + array([0, 0, 0]) + >>> mask_zero_div_zero(x, y, result) + array([ inf, nan, -inf]) + """ + + if not hasattr(y, "dtype"): + # e.g. scalar, tuple + y = np.array(y) + if not hasattr(x, "dtype"): + # e.g scalar, tuple + x = np.array(x) + + zmask = y == 0 + + if zmask.any(): + # Flip sign if necessary for -0.0 + zneg_mask = zmask & np.signbit(y) + zpos_mask = zmask & ~zneg_mask + + x_lt0 = x < 0 + x_gt0 = x > 0 + nan_mask = zmask & (x == 0) + neginf_mask = (zpos_mask & x_lt0) | (zneg_mask & x_gt0) + posinf_mask = (zpos_mask & x_gt0) | (zneg_mask & x_lt0) + + if nan_mask.any() or neginf_mask.any() or posinf_mask.any(): + # Fill negative/0 with -inf, positive/0 with +inf, 0/0 with NaN + result = result.astype("float64", copy=False) + + result[nan_mask] = np.nan + result[posinf_mask] = np.inf + result[neginf_mask] = -np.inf + + return result + + +def dispatch_fill_zeros(op, left, right, result): + """ + Call _fill_zeros with the appropriate fill value depending on the operation, + with special logic for divmod and rdivmod. + + Parameters + ---------- + op : function (operator.add, operator.div, ...) + left : object (np.ndarray for non-reversed ops) + We have excluded ExtensionArrays here + right : object (np.ndarray for reversed ops) + We have excluded ExtensionArrays here + result : ndarray + + Returns + ------- + result : np.ndarray + + Notes + ----- + For divmod and rdivmod, the `result` parameter and returned `result` + is a 2-tuple of ndarray objects. + """ + if op is divmod: + result = ( + mask_zero_div_zero(left, right, result[0]), + _fill_zeros(result[1], left, right), + ) + elif op is roperator.rdivmod: + result = ( + mask_zero_div_zero(right, left, result[0]), + _fill_zeros(result[1], right, left), + ) + elif op is operator.floordiv: + # Note: no need to do this for truediv; in py3 numpy behaves the way + # we want. + result = mask_zero_div_zero(left, right, result) + elif op is roperator.rfloordiv: + # Note: no need to do this for rtruediv; in py3 numpy behaves the way + # we want. + result = mask_zero_div_zero(right, left, result) + elif op is operator.mod: + result = _fill_zeros(result, left, right) + elif op is roperator.rmod: + result = _fill_zeros(result, right, left) + return result diff --git a/shared/package-files/d1/d16b060fd84c3d18bccdcb98300f42bb698ebd088216c90fc0cb0c7fc9410cae/blob b/shared/package-files/d1/d16b060fd84c3d18bccdcb98300f42bb698ebd088216c90fc0cb0c7fc9410cae/blob new file mode 100644 index 0000000000000000000000000000000000000000..569244f252c057ec1029b7efbd8b0ffbfbc47522 --- /dev/null +++ b/shared/package-files/d1/d16b060fd84c3d18bccdcb98300f42bb698ebd088216c90fc0cb0c7fc9410cae/blob @@ -0,0 +1,14 @@ +from mpmath import nstr, matrix, inf + +def test_nstr(): + m = matrix([[0.75, 0.190940654, -0.0299195971], + [0.190940654, 0.65625, 0.205663228], + [-0.0299195971, 0.205663228, 0.64453125e-20]]) + assert nstr(m, 4, min_fixed=-inf) == \ + '''[ 0.75 0.1909 -0.02992] +[ 0.1909 0.6563 0.2057] +[-0.02992 0.2057 0.000000000000000000006445]''' + assert nstr(m, 4) == \ + '''[ 0.75 0.1909 -0.02992] +[ 0.1909 0.6563 0.2057] +[-0.02992 0.2057 6.445e-21]''' diff --git a/shared/package-files/d1/d173be07d5e60068962e11055bcc2e8c5a3e551d6beb64993fb313f83073d551/blob b/shared/package-files/d1/d173be07d5e60068962e11055bcc2e8c5a3e551d6beb64993fb313f83073d551/blob new file mode 100644 index 0000000000000000000000000000000000000000..b5b19eef1106fd2f500fc74e0eb5157ca63cfeb7 --- /dev/null +++ b/shared/package-files/d1/d173be07d5e60068962e11055bcc2e8c5a3e551d6beb64993fb313f83073d551/blob @@ -0,0 +1,305 @@ +import os + +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + Categorical, + DatetimeIndex, + Interval, + IntervalIndex, + NaT, + Series, + Timedelta, + TimedeltaIndex, + Timestamp, + cut, + date_range, + isna, + qcut, + timedelta_range, +) +import pandas._testing as tm +from pandas.api.types import CategoricalDtype + +from pandas.tseries.offsets import Day + + +def test_qcut(): + arr = np.random.default_rng(2).standard_normal(1000) + + # We store the bins as Index that have been + # rounded to comparisons are a bit tricky. + labels, _ = qcut(arr, 4, retbins=True) + ex_bins = np.quantile(arr, [0, 0.25, 0.5, 0.75, 1.0]) + + result = labels.categories.left.values + assert np.allclose(result, ex_bins[:-1], atol=1e-2) + + result = labels.categories.right.values + assert np.allclose(result, ex_bins[1:], atol=1e-2) + + ex_levels = cut(arr, ex_bins, include_lowest=True) + tm.assert_categorical_equal(labels, ex_levels) + + +def test_qcut_bounds(): + arr = np.random.default_rng(2).standard_normal(1000) + + factor = qcut(arr, 10, labels=False) + assert len(np.unique(factor)) == 10 + + +def test_qcut_specify_quantiles(): + arr = np.random.default_rng(2).standard_normal(100) + factor = qcut(arr, [0, 0.25, 0.5, 0.75, 1.0]) + + expected = qcut(arr, 4) + tm.assert_categorical_equal(factor, expected) + + +def test_qcut_all_bins_same(): + with pytest.raises(ValueError, match="edges.*unique"): + qcut([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 3) + + +def test_qcut_include_lowest(): + values = np.arange(10) + ii = qcut(values, 4) + + ex_levels = IntervalIndex( + [ + Interval(-0.001, 2.25), + Interval(2.25, 4.5), + Interval(4.5, 6.75), + Interval(6.75, 9), + ] + ) + tm.assert_index_equal(ii.categories, ex_levels) + + +def test_qcut_nas(): + arr = np.random.default_rng(2).standard_normal(100) + arr[:20] = np.nan + + result = qcut(arr, 4) + assert isna(result[:20]).all() + + +def test_qcut_index(): + result = qcut([0, 2], 2) + intervals = [Interval(-0.001, 1), Interval(1, 2)] + + expected = Categorical(intervals, ordered=True) + tm.assert_categorical_equal(result, expected) + + +def test_qcut_binning_issues(datapath): + # see gh-1978, gh-1979 + cut_file = datapath(os.path.join("reshape", "data", "cut_data.csv")) + arr = np.loadtxt(cut_file) + result = qcut(arr, 20) + + starts = [] + ends = [] + + for lev in np.unique(result): + s = lev.left + e = lev.right + assert s != e + + starts.append(float(s)) + ends.append(float(e)) + + for (sp, sn), (ep, en) in zip( + zip(starts[:-1], starts[1:]), zip(ends[:-1], ends[1:]) + ): + assert sp < sn + assert ep < en + assert ep <= sn + + +def test_qcut_return_intervals(): + ser = Series([0, 1, 2, 3, 4, 5, 6, 7, 8]) + res = qcut(ser, [0, 0.333, 0.666, 1]) + + exp_levels = np.array( + [Interval(-0.001, 2.664), Interval(2.664, 5.328), Interval(5.328, 8)] + ) + exp = Series(exp_levels.take([0, 0, 0, 1, 1, 1, 2, 2, 2])).astype( + CategoricalDtype(ordered=True) + ) + tm.assert_series_equal(res, exp) + + +@pytest.mark.parametrize("labels", ["foo", 1, True]) +def test_qcut_incorrect_labels(labels): + # GH 13318 + values = range(5) + msg = "Bin labels must either be False, None or passed in as a list-like argument" + with pytest.raises(ValueError, match=msg): + qcut(values, 4, labels=labels) + + +@pytest.mark.parametrize("labels", [["a", "b", "c"], list(range(3))]) +def test_qcut_wrong_length_labels(labels): + # GH 13318 + values = range(10) + msg = "Bin labels must be one fewer than the number of bin edges" + with pytest.raises(ValueError, match=msg): + qcut(values, 4, labels=labels) + + +@pytest.mark.parametrize( + "labels, expected", + [ + (["a", "b", "c"], Categorical(["a", "b", "c"], ordered=True)), + (list(range(3)), Categorical([0, 1, 2], ordered=True)), + ], +) +def test_qcut_list_like_labels(labels, expected): + # GH 13318 + values = range(3) + result = qcut(values, 3, labels=labels) + tm.assert_categorical_equal(result, expected) + + +@pytest.mark.parametrize( + "kwargs,msg", + [ + ({"duplicates": "drop"}, None), + ({}, "Bin edges must be unique"), + ({"duplicates": "raise"}, "Bin edges must be unique"), + ({"duplicates": "foo"}, "invalid value for 'duplicates' parameter"), + ], +) +def test_qcut_duplicates_bin(kwargs, msg): + # see gh-7751 + values = [0, 0, 0, 0, 1, 2, 3] + + if msg is not None: + with pytest.raises(ValueError, match=msg): + qcut(values, 3, **kwargs) + else: + result = qcut(values, 3, **kwargs) + expected = IntervalIndex([Interval(-0.001, 1), Interval(1, 3)]) + tm.assert_index_equal(result.categories, expected) + + +@pytest.mark.parametrize( + "data,start,end", [(9.0, 8.999, 9.0), (0.0, -0.001, 0.0), (-9.0, -9.001, -9.0)] +) +@pytest.mark.parametrize("length", [1, 2]) +@pytest.mark.parametrize("labels", [None, False]) +def test_single_quantile(data, start, end, length, labels): + # see gh-15431 + ser = Series([data] * length) + result = qcut(ser, 1, labels=labels) + + if labels is None: + intervals = IntervalIndex([Interval(start, end)] * length, closed="right") + expected = Series(intervals).astype(CategoricalDtype(ordered=True)) + else: + expected = Series([0] * length, dtype=np.intp) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "ser", + [ + Series(DatetimeIndex(["20180101", NaT, "20180103"])), + Series(TimedeltaIndex(["0 days", NaT, "2 days"])), + ], + ids=lambda x: str(x.dtype), +) +def test_qcut_nat(ser, unit): + # see gh-19768 + ser = ser.dt.as_unit(unit) + td = Timedelta(1, unit=unit).as_unit(unit) + + left = Series([ser[0] - td, np.nan, ser[2] - Day()], dtype=ser.dtype) + right = Series([ser[2] - Day(), np.nan, ser[2]], dtype=ser.dtype) + intervals = IntervalIndex.from_arrays(left, right) + expected = Series(Categorical(intervals, ordered=True)) + + result = qcut(ser, 2) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("bins", [3, np.linspace(0, 1, 4)]) +def test_datetime_tz_qcut(bins): + # see gh-19872 + tz = "US/Eastern" + ser = Series(date_range("20130101", periods=3, tz=tz)) + + result = qcut(ser, bins) + expected = Series( + IntervalIndex( + [ + Interval( + Timestamp("2012-12-31 23:59:59.999999999", tz=tz), + Timestamp("2013-01-01 16:00:00", tz=tz), + ), + Interval( + Timestamp("2013-01-01 16:00:00", tz=tz), + Timestamp("2013-01-02 08:00:00", tz=tz), + ), + Interval( + Timestamp("2013-01-02 08:00:00", tz=tz), + Timestamp("2013-01-03 00:00:00", tz=tz), + ), + ] + ) + ).astype(CategoricalDtype(ordered=True)) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "arg,expected_bins", + [ + [ + timedelta_range("1day", periods=3), + TimedeltaIndex(["1 days", "2 days", "3 days"]), + ], + [ + date_range("20180101", periods=3), + DatetimeIndex(["2018-01-01", "2018-01-02", "2018-01-03"]), + ], + ], +) +def test_date_like_qcut_bins(arg, expected_bins): + # see gh-19891 + ser = Series(arg) + result, result_bins = qcut(ser, 2, retbins=True) + tm.assert_index_equal(result_bins, expected_bins) + + +@pytest.mark.parametrize("bins", [6, 7]) +@pytest.mark.parametrize( + "box, compare", + [ + (Series, tm.assert_series_equal), + (np.array, tm.assert_categorical_equal), + (list, tm.assert_equal), + ], +) +def test_qcut_bool_coercion_to_int(bins, box, compare): + # issue 20303 + data_expected = box([0, 1, 1, 0, 1] * 10) + data_result = box([False, True, True, False, True] * 10) + expected = qcut(data_expected, bins, duplicates="drop") + result = qcut(data_result, bins, duplicates="drop") + compare(result, expected) + + +@pytest.mark.parametrize("q", [2, 5, 10]) +def test_qcut_nullable_integer(q, any_numeric_ea_dtype): + arr = pd.array(np.arange(100), dtype=any_numeric_ea_dtype) + arr[::2] = pd.NA + + result = qcut(arr, q) + expected = qcut(arr.astype(float), q) + + tm.assert_categorical_equal(result, expected) diff --git a/shared/package-files/d1/d176cd9aa18414ffc4f7753785248ba4c06fd6161811a56e80129d5a5786e2e0/blob b/shared/package-files/d1/d176cd9aa18414ffc4f7753785248ba4c06fd6161811a56e80129d5a5786e2e0/blob new file mode 100644 index 0000000000000000000000000000000000000000..7c95f1e7b0fcd40967e7320bc72415d6c8993317 --- /dev/null +++ b/shared/package-files/d1/d176cd9aa18414ffc4f7753785248ba4c06fd6161811a56e80129d5a5786e2e0/blob @@ -0,0 +1,309 @@ +""" + +Created on Fri Jun 28 14:19:26 2013 + +Author: Josef Perktold +""" + +import numpy as np +from numpy.testing import assert_allclose, assert_almost_equal, assert_array_less +from scipy import stats + +from statsmodels.base.model import GenericLikelihoodModel +from statsmodels.iolib.summary import Summary + + +class MyPareto(GenericLikelihoodModel): + """Maximum Likelihood Estimation pareto distribution + + first version: iid case, with constant parameters + """ + + def initialize(self): # TODO needed or not + super().initialize() + extra_params_names = ["shape", "loc", "scale"] + self._set_extra_params_names(extra_params_names) + + # start_params needs to be attribute + self.start_params = np.array([1.5, self.endog.min() - 1.5, 1.0]) + + def pdf(self, x, b): + # copied from stats.distribution + return b * x ** (-b - 1) + + def loglike(self, params): + return -self.nloglikeobs(params).sum(0) + + # TODO: design start_params needs to be an attribute, + # so it can be overwritten + # @property + # def start_params(self): + # return np.array([1.5, self.endog.min() - 1.5, 1.]) + + def nloglikeobs(self, params): + # print params.shape + if self.fixed_params is not None: + # print 'using fixed' + params = self.expandparams(params) + b = params[0] + loc = params[1] + scale = params[2] + # loc = np.dot(self.exog, beta) + endog = self.endog + x = (endog - loc) / scale + logpdf = np.log(b) - (b + 1.0) * np.log(x) # use np_log(1 + x) for Pareto II + logpdf -= np.log(scale) + # lb = loc + scale + # logpdf[endog|z|" + assert check_str in str(summ) + + def test_use_t_summary(self): + orig_val = self.res1.use_t + self.res1.use_t = True + summ = self.res1.summary() + assert "P>|t|" in str(summ) + self.res1.use_t = orig_val + + def test_ttest(self): + self.res1.t_test(np.eye(len(self.res1.params))) + + def test_params(self): + params = self.res1.params + + params_true = np.array([2, 0, 2]) + if self.res1.model.fixed_paramsmask is not None: + params_true = params_true[self.res1.model.fixed_paramsmask] + assert_allclose(params, params_true, atol=1.5) + assert_allclose(params, np.zeros(len(params)), atol=4) + + assert_allclose(self.res1.bse, np.zeros(len(params)), atol=0.5) + if not self.skip_bsejac: + assert_allclose(self.res1.bse, self.res1.bsejac, rtol=0.05, atol=0.15) + # bsejhj is very different from the other two + # use huge atol as sanity check for availability + assert_allclose(self.res1.bsejhj, self.res1.bsejac, rtol=0.05, atol=1.5) + + def test_df(self): + res = self.res1 + k_extra = getattr(self, "k_extra", 0) + if res.model.exog is not None: + nobs, k_vars = res.model.exog.shape + k_constant = 1 + else: + nobs, k_vars = res.model.endog.shape[0], 0 + k_constant = 0 + assert res.df_resid == nobs - k_vars - k_extra + assert res.df_model == k_vars - k_constant + assert len(res.params) == k_vars + k_extra + + +class TestMyPareto1(CheckGenericMixin): + + @classmethod + def setup_class(cls): + params = [2, 0, 2] + nobs = 100 + rs = np.random.RandomState(1234) + rvs = stats.pareto.rvs(*params, **dict(size=nobs), random_state=rs) + + mod_par = MyPareto(rvs) + mod_par.fixed_params = None + mod_par.fixed_paramsmask = None + mod_par.df_model = 0 + mod_par.k_extra = k_extra = 3 + mod_par.df_resid = mod_par.endog.shape[0] - mod_par.df_model - k_extra + mod_par.data.xnames = ["shape", "loc", "scale"] + + cls.mod = mod_par + cls.res1 = mod_par.fit(disp=None) + cls.k_extra = k_extra + + # Note: possible problem with parameters close to min data boundary + # see issue #968 + cls.skip_bsejac = True + + def test_minsupport(self): + # rough sanity checks for convergence + params = self.res1.params + x_min = self.res1.endog.min() + p_min = params[1] + params[2] + assert_array_less(p_min, x_min) + assert_almost_equal(p_min, x_min, decimal=2) + + +class TestMyParetoRestriction(CheckGenericMixin): + + @classmethod + def setup_class(cls): + params = [2, 0, 2] + nobs = 50 + rs = np.random.RandomState(1234) + rvs = stats.pareto.rvs(*params, **dict(size=nobs), random_state=rs) + + mod_par = MyPareto(rvs) + fixdf = np.nan * np.ones(3) + fixdf[1] = -0.1 + mod_par.fixed_params = fixdf + mod_par.fixed_paramsmask = np.isnan(fixdf) + mod_par.start_params = mod_par.start_params[mod_par.fixed_paramsmask] + mod_par.df_model = 0 + mod_par.k_extra = k_extra = 2 + mod_par.df_resid = mod_par.endog.shape[0] - mod_par.df_model - k_extra + mod_par.data.xnames = ["shape", "scale"] + + cls.mod = mod_par + cls.res1 = mod_par.fit(disp=None) + cls.k_extra = k_extra + + # Note: loc is fixed, no problems with parameters close to min data + cls.skip_bsejac = False + + +class TwoPeakLLHNoExog(GenericLikelihoodModel): + """Fit height of signal peak over background.""" + + start_params = [10, 1000] + cloneattr = ["start_params", "signal", "background"] + exog_names = ["n_signal", "n_background"] + endog_names = ["alpha"] + + def __init__(self, endog, exog=None, signal=None, background=None, *args, **kwargs): + # assume we know the shape + location of the two components, + # so we re-use their PDFs here + self.signal = signal + self.background = background + super().__init__( + endog, exog, *args, extra_params_names=self.exog_names, **kwargs + ) + + def loglike(self, params): # pylint: disable=E0202 + return -self.nloglike(params) + + def nloglike(self, params): + endog = self.endog + return self.nlnlike(params, endog) + + def nlnlike(self, params, endog): + n_sig = params[0] + n_bkg = params[1] + if (n_sig < 0) or n_bkg < 0: + return np.inf + n_tot = n_bkg + n_sig + alpha = endog + sig = self.signal.pdf(alpha) + bkg = self.background.pdf(alpha) + sumlogl = np.sum(np.log((n_sig * sig) + (n_bkg * bkg))) + sumlogl -= n_tot + return -sumlogl + + +class TestTwoPeakLLHNoExog: + + @classmethod + def setup_class(cls): + rs = np.random.RandomState(42) + pdf_a = stats.halfcauchy(loc=0, scale=1) + pdf_b = stats.uniform(loc=0, scale=100) + + n_a = 50 + n_b = 200 + params = [n_a, n_b] + + X = np.concatenate( + [ + pdf_a.rvs(size=n_a, random_state=rs), + pdf_b.rvs(size=n_b, random_state=rs), + ] + )[:, np.newaxis] + cls.X = X + cls.params = params + cls.pdf_a = pdf_a + cls.pdf_b = pdf_b + + def test_fit(self): + rs = np.random.RandomState(42) + llh_noexog = TwoPeakLLHNoExog(self.X, signal=self.pdf_a, background=self.pdf_b) + + res = llh_noexog.fit() + assert_allclose(res.params, self.params, rtol=1e-1) + # TODO: nan if exog is None, + assert res.df_resid == 248 + assert res.df_model == 0 + res_bs = res.bootstrap(nrep=50, rng=rs) + assert_allclose(res_bs[2].mean(0), self.params, rtol=1e-1) + # SMOKE test, + res.summary() + + +def test_reduceparams_expandparams_roundtrip(): + # GenericLikelihoodModel.reduceparams/expandparams are not overridden + # by MyPareto; reduceparams is the (partial) inverse of expandparams, + # so a round trip on the free parameters should recover them exactly. + nobs = 20 + rs = np.random.RandomState(1234) + rvs = stats.pareto.rvs(2, 0, 2, size=nobs, random_state=rs) + + mod_par = MyPareto(rvs) + fixdf = np.array([np.nan, -0.1, np.nan]) + mod_par.fixed_params = fixdf + mod_par.fixed_paramsmask = np.isnan(fixdf) + + reduced = np.array([2.5, 1.8]) + full = mod_par.expandparams(reduced) + assert_allclose(full, [2.5, -0.1, 1.8]) + assert_allclose(mod_par.reduceparams(full), reduced) + + +def test_nloglike_matches_nloglikeobs_sum(): + # GenericLikelihoodModel.nloglike is not overridden by MyPareto (only + # nloglikeobs and loglike are), so calling it exercises the + # base-class implementation: nloglike(p) == -loglikeobs(p).sum(0), + # and loglikeobs is itself the base-class -nloglikeobs(p). + nobs = 20 + rs = np.random.RandomState(1234) + rvs = stats.pareto.rvs(2, 0, 2, size=nobs, random_state=rs) + + mod_par = MyPareto(rvs) + mod_par.fixed_params = None + mod_par.fixed_paramsmask = None + + params = np.array([2.0, -0.5, 2.2]) + expected = mod_par.nloglikeobs(params).sum(0) + + assert_allclose(mod_par.nloglike(params), expected) + assert_allclose(mod_par.nloglike(params), -mod_par.loglike(params)) + + +def test_summary_after_remove_data(): + # summary() must still work after remove_data() has been called + # MyPareto does not set its own results_class, so fit() returns a plain + # GenericLikelihoodModelResults instance. + params = [2, 0, 2] + nobs = 100 + rs = np.random.RandomState(1234) + rvs = stats.pareto.rvs(*params, **dict(size=nobs), random_state=rs) + + mod_par = MyPareto(rvs) + mod_par.fixed_params = None + mod_par.fixed_paramsmask = None + mod_par.df_model = 0 + mod_par.k_extra = k_extra = 3 + mod_par.df_resid = mod_par.endog.shape[0] - mod_par.df_model - k_extra + mod_par.data.xnames = ["shape", "loc", "scale"] + + res = mod_par.fit(disp=None) + + assert isinstance(res.summary(), Summary) + res.remove_data() + assert isinstance(res.summary(), Summary) diff --git a/shared/package-files/d1/d17715b895804e35e43e4a58f764b71cfa6776456950d711dd3ec7a0899f0172/blob b/shared/package-files/d1/d17715b895804e35e43e4a58f764b71cfa6776456950d711dd3ec7a0899f0172/blob new file mode 100644 index 0000000000000000000000000000000000000000..77daf86545a85e54c4a631722ac96bb2c3bd7d1c --- /dev/null +++ b/shared/package-files/d1/d17715b895804e35e43e4a58f764b71cfa6776456950d711dd3ec7a0899f0172/blob @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_nested_get_offsets(Tensor self) -> Tensor +inline at::Tensor _nested_get_offsets(const at::Tensor & self) { + return at::_ops::_nested_get_offsets::call(self); +} + +} diff --git a/shared/package-files/d1/d17b0da6b2a2d1743da1de9d3889b0cd0c21f1831d81d13405914614718f1188/blob b/shared/package-files/d1/d17b0da6b2a2d1743da1de9d3889b0cd0c21f1831d81d13405914614718f1188/blob new file mode 100644 index 0000000000000000000000000000000000000000..7e702bdc993bd1444dc48f85e016c768dadd042f --- /dev/null +++ b/shared/package-files/d1/d17b0da6b2a2d1743da1de9d3889b0cd0c21f1831d81d13405914614718f1188/blob @@ -0,0 +1,120 @@ +""" +test_insert is specifically for the DataFrame.insert method; not to be +confused with tests with "insert" in their names that are really testing +__setitem__. +""" +import numpy as np +import pytest + +from pandas.errors import PerformanceWarning + +from pandas import ( + DataFrame, + Index, +) +import pandas._testing as tm + + +class TestDataFrameInsert: + def test_insert(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 3)), + index=np.arange(5), + columns=["c", "b", "a"], + ) + + df.insert(0, "foo", df["a"]) + tm.assert_index_equal(df.columns, Index(["foo", "c", "b", "a"])) + tm.assert_series_equal(df["a"], df["foo"], check_names=False) + + df.insert(2, "bar", df["c"]) + tm.assert_index_equal(df.columns, Index(["foo", "c", "bar", "b", "a"])) + tm.assert_almost_equal(df["c"], df["bar"], check_names=False) + + with pytest.raises(ValueError, match="already exists"): + df.insert(1, "a", df["b"]) + + msg = "cannot insert c, already exists" + with pytest.raises(ValueError, match=msg): + df.insert(1, "c", df["b"]) + + df.columns.name = "some_name" + # preserve columns name field + df.insert(0, "baz", df["c"]) + assert df.columns.name == "some_name" + + def test_insert_column_bug_4032(self): + # GH#4032, inserting a column and renaming causing errors + df = DataFrame({"b": [1.1, 2.2]}) + + df = df.rename(columns={}) + df.insert(0, "a", [1, 2]) + result = df.rename(columns={}) + + expected = DataFrame([[1, 1.1], [2, 2.2]], columns=["a", "b"]) + tm.assert_frame_equal(result, expected) + + df.insert(0, "c", [1.3, 2.3]) + result = df.rename(columns={}) + + expected = DataFrame([[1.3, 1, 1.1], [2.3, 2, 2.2]], columns=["c", "a", "b"]) + tm.assert_frame_equal(result, expected) + + def test_insert_with_columns_dups(self): + # GH#14291 + df = DataFrame() + df.insert(0, "A", ["g", "h", "i"], allow_duplicates=True) + df.insert(0, "A", ["d", "e", "f"], allow_duplicates=True) + df.insert(0, "A", ["a", "b", "c"], allow_duplicates=True) + exp = DataFrame( + [["a", "d", "g"], ["b", "e", "h"], ["c", "f", "i"]], columns=["A", "A", "A"] + ) + tm.assert_frame_equal(df, exp) + + def test_insert_item_cache(self, using_array_manager, using_copy_on_write): + df = DataFrame(np.random.default_rng(2).standard_normal((4, 3))) + ser = df[0] + + if using_array_manager: + expected_warning = None + else: + # with BlockManager warn about high fragmentation of single dtype + expected_warning = PerformanceWarning + + with tm.assert_produces_warning(expected_warning): + for n in range(100): + df[n + 3] = df[1] * n + + if using_copy_on_write: + ser.iloc[0] = 99 + assert df.iloc[0, 0] == df[0][0] + assert df.iloc[0, 0] != 99 + else: + ser.values[0] = 99 + assert df.iloc[0, 0] == df[0][0] + assert df.iloc[0, 0] == 99 + + def test_insert_EA_no_warning(self): + # PerformanceWarning about fragmented frame should not be raised when + # using EAs (https://github.com/pandas-dev/pandas/issues/44098) + df = DataFrame( + np.random.default_rng(2).integers(0, 100, size=(3, 100)), dtype="Int64" + ) + with tm.assert_produces_warning(None): + df["a"] = np.array([1, 2, 3]) + + def test_insert_frame(self): + # GH#42403 + df = DataFrame({"col1": [1, 2], "col2": [3, 4]}) + + msg = ( + "Expected a one-dimensional object, got a DataFrame with 2 columns instead." + ) + with pytest.raises(ValueError, match=msg): + df.insert(1, "newcol", df) + + def test_insert_int64_loc(self): + # GH#53193 + df = DataFrame({"a": [1, 2]}) + df.insert(np.int64(0), "b", 0) + tm.assert_frame_equal(df, DataFrame({"b": [0, 0], "a": [1, 2]})) diff --git a/shared/package-files/d1/d17b6baee20649555b705498006fd31c752ff8072673a927ac9f0427aaf27d3c/blob b/shared/package-files/d1/d17b6baee20649555b705498006fd31c752ff8072673a927ac9f0427aaf27d3c/blob new file mode 100644 index 0000000000000000000000000000000000000000..9d93d6aee86bcf5ce3af0ee3a5168ddc116d5c1c --- /dev/null +++ b/shared/package-files/d1/d17b6baee20649555b705498006fd31c752ff8072673a927ac9f0427aaf27d3c/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor rand_like(const at::Tensor & self, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor & rand_like_out(const at::Tensor & self, c10::optional memory_format, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/d1/d17f21bf1eebf88dac8934bb2f92095737f419e0265f704e1d770ec7126e3ad7/blob b/shared/package-files/d1/d17f21bf1eebf88dac8934bb2f92095737f419e0265f704e1d770ec7126e3ad7/blob new file mode 100644 index 0000000000000000000000000000000000000000..fdd1e801dab1522a4450332c7f56beec9b3f2b1c --- /dev/null +++ b/shared/package-files/d1/d17f21bf1eebf88dac8934bb2f92095737f419e0265f704e1d770ec7126e3ad7/blob @@ -0,0 +1,60 @@ +import sys +from logging import Logger +from socket import socket +from typing import Any, Callable, Tuple + +from cryptography.hazmat.primitives.ciphers import Cipher +from paramiko.compress import ZlibCompressor, ZlibDecompressor +from paramiko.message import Message + +if sys.version_info < (3, 0): + from hashlib import _hash as _Hash +else: + from hashlib import _Hash + +def compute_hmac(key: bytes, message: bytes, digest_class: _Hash) -> bytes: ... + +class NeedRekeyException(Exception): ... + +def first_arg(e: Exception) -> Any: ... + +class Packetizer: + REKEY_PACKETS: int + REKEY_BYTES: int + REKEY_PACKETS_OVERFLOW_MAX: int + REKEY_BYTES_OVERFLOW_MAX: int + def __init__(self, socket: socket) -> None: ... + @property + def closed(self) -> bool: ... + def set_log(self, log: Logger) -> None: ... + def set_outbound_cipher( + self, + block_engine: Cipher, + block_size: int, + mac_engine: _Hash, + mac_size: int, + mac_key: bytes, + sdctr: bool = ..., + etm: bool = ..., + ) -> None: ... + def set_inbound_cipher( + self, block_engine: Cipher, block_size: int, mac_engine: _Hash, mac_size: int, mac_key: bytes, etm: bool = ... + ) -> None: ... + def set_outbound_compressor(self, compressor: ZlibCompressor) -> None: ... + def set_inbound_compressor(self, compressor: ZlibDecompressor) -> None: ... + def close(self) -> None: ... + def set_hexdump(self, hexdump: bool) -> None: ... + def get_hexdump(self) -> bool: ... + def get_mac_size_in(self) -> int: ... + def get_mac_size_out(self) -> int: ... + def need_rekey(self) -> bool: ... + def set_keepalive(self, interval: int, callback: Callable[[], None]) -> None: ... + def read_timer(self) -> None: ... + def start_handshake(self, timeout: float) -> None: ... + def handshake_timed_out(self) -> bool: ... + def complete_handshake(self) -> None: ... + def read_all(self, n: int, check_rekey: bool = ...) -> bytes: ... + def write_all(self, out: bytes) -> None: ... + def readline(self, timeout: float) -> str: ... + def send_message(self, data: Message) -> None: ... + def read_message(self) -> Tuple[int, Message]: ... diff --git a/shared/package-files/d1/d180be49a8a021aa123b697b87db0ee1e6f30abc6ad266b916d8992a2c03311b/blob b/shared/package-files/d1/d180be49a8a021aa123b697b87db0ee1e6f30abc6ad266b916d8992a2c03311b/blob new file mode 100644 index 0000000000000000000000000000000000000000..7cb60a11644a357811136c991143554c4477d485 --- /dev/null +++ b/shared/package-files/d1/d180be49a8a021aa123b697b87db0ee1e6f30abc6ad266b916d8992a2c03311b/blob @@ -0,0 +1,148 @@ +import numpy as np +import pytest + +from pandas import ( + DataFrame, + Series, + array as pd_array, + date_range, +) +import pandas._testing as tm + + +@pytest.fixture +def df(): + """ + base dataframe for testing + """ + return DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + + +def test_case_when_caselist_is_not_a_list(df): + """ + Raise ValueError if caselist is not a list. + """ + msg = "The caselist argument should be a list; " + msg += "instead got.+" + with pytest.raises(TypeError, match=msg): # GH39154 + df["a"].case_when(caselist=()) + + +def test_case_when_no_caselist(df): + """ + Raise ValueError if no caselist is provided. + """ + msg = "provide at least one boolean condition, " + msg += "with a corresponding replacement." + with pytest.raises(ValueError, match=msg): # GH39154 + df["a"].case_when([]) + + +def test_case_when_odd_caselist(df): + """ + Raise ValueError if no of caselist is odd. + """ + msg = "Argument 0 must have length 2; " + msg += "a condition and replacement; instead got length 3." + + with pytest.raises(ValueError, match=msg): + df["a"].case_when([(df["a"].eq(1), 1, df.a.gt(1))]) + + +def test_case_when_raise_error_from_mask(df): + """ + Raise Error from within Series.mask + """ + msg = "Failed to apply condition0 and replacement0." + with pytest.raises(ValueError, match=msg): + df["a"].case_when([(df["a"].eq(1), [1, 2])]) + + +def test_case_when_single_condition(df): + """ + Test output on a single condition. + """ + result = Series([np.nan, np.nan, np.nan]).case_when([(df.a.eq(1), 1)]) + expected = Series([1, np.nan, np.nan]) + tm.assert_series_equal(result, expected) + + +def test_case_when_multiple_conditions(df): + """ + Test output when booleans are derived from a computation + """ + result = Series([np.nan, np.nan, np.nan]).case_when( + [(df.a.eq(1), 1), (Series([False, True, False]), 2)] + ) + expected = Series([1, 2, np.nan]) + tm.assert_series_equal(result, expected) + + +def test_case_when_multiple_conditions_replacement_list(df): + """ + Test output when replacement is a list + """ + result = Series([np.nan, np.nan, np.nan]).case_when( + [([True, False, False], 1), (df["a"].gt(1) & df["b"].eq(5), [1, 2, 3])] + ) + expected = Series([1, 2, np.nan]) + tm.assert_series_equal(result, expected) + + +def test_case_when_multiple_conditions_replacement_extension_dtype(df): + """ + Test output when replacement has an extension dtype + """ + result = Series([np.nan, np.nan, np.nan]).case_when( + [ + ([True, False, False], 1), + (df["a"].gt(1) & df["b"].eq(5), pd_array([1, 2, 3], dtype="Int64")), + ], + ) + expected = Series([1, 2, np.nan], dtype="Float64") + tm.assert_series_equal(result, expected) + + +def test_case_when_multiple_conditions_replacement_series(df): + """ + Test output when replacement is a Series + """ + result = Series([np.nan, np.nan, np.nan]).case_when( + [ + (np.array([True, False, False]), 1), + (df["a"].gt(1) & df["b"].eq(5), Series([1, 2, 3])), + ], + ) + expected = Series([1, 2, np.nan]) + tm.assert_series_equal(result, expected) + + +def test_case_when_non_range_index(): + """ + Test output if index is not RangeIndex + """ + rng = np.random.default_rng(seed=123) + dates = date_range("1/1/2000", periods=8) + df = DataFrame( + rng.standard_normal(size=(8, 4)), index=dates, columns=["A", "B", "C", "D"] + ) + result = Series(5, index=df.index, name="A").case_when([(df.A.gt(0), df.B)]) + expected = df.A.mask(df.A.gt(0), df.B).where(df.A.gt(0), 5) + tm.assert_series_equal(result, expected) + + +def test_case_when_callable(): + """ + Test output on a callable + """ + # https://numpy.org/doc/stable/reference/generated/numpy.piecewise.html + x = np.linspace(-2.5, 2.5, 6) + ser = Series(x) + result = ser.case_when( + caselist=[ + (lambda df: df < 0, lambda df: -df), + (lambda df: df >= 0, lambda df: df), + ] + ) + expected = np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x]) + tm.assert_series_equal(result, Series(expected)) diff --git a/shared/package-files/d1/d1818ea25c648dbe90cc499e67ac6ea346da9a84dcb791afac702d3e8307f9f5/blob b/shared/package-files/d1/d1818ea25c648dbe90cc499e67ac6ea346da9a84dcb791afac702d3e8307f9f5/blob new file mode 100644 index 0000000000000000000000000000000000000000..b3edba8efdf726cea92059cb01e34ee25206482c --- /dev/null +++ b/shared/package-files/d1/d1818ea25c648dbe90cc499e67ac6ea346da9a84dcb791afac702d3e8307f9f5/blob @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/shared/package-files/d1/d1853ade21f263a3bee0b47d9514b990b64ca5c329b8dc44b20aad5c02d5ee27/blob b/shared/package-files/d1/d1853ade21f263a3bee0b47d9514b990b64ca5c329b8dc44b20aad5c02d5ee27/blob new file mode 100644 index 0000000000000000000000000000000000000000..a7317a7d1191e61a074fcaa07e1859b11bdc0d10 --- /dev/null +++ b/shared/package-files/d1/d1853ade21f263a3bee0b47d9514b990b64ca5c329b8dc44b20aad5c02d5ee27/blob @@ -0,0 +1,145 @@ +from sympy.diffgeom.rn import R2, R2_p, R2_r, R3_r +from sympy.diffgeom import intcurve_series, Differential, WedgeProduct +from sympy.core import symbols, Function, Derivative +from sympy.simplify import trigsimp, simplify +from sympy.functions import sqrt, atan2, sin, cos +from sympy.matrices import Matrix + +# Most of the functionality is covered in the +# test_functional_diffgeom_ch* tests which are based on the +# example from the paper of Sussman and Wisdom. +# If they do not cover something, additional tests are added in other test +# functions. + +# From "Functional Differential Geometry" as of 2011 +# by Sussman and Wisdom. + + +def test_functional_diffgeom_ch2(): + x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', real=True) + x, y = symbols('x, y', real=True) + f = Function('f') + + assert (R2_p.point_to_coords(R2_r.point([x0, y0])) == + Matrix([sqrt(x0**2 + y0**2), atan2(y0, x0)])) + assert (R2_r.point_to_coords(R2_p.point([r0, theta0])) == + Matrix([r0*cos(theta0), r0*sin(theta0)])) + + assert R2_p.jacobian(R2_r, [r0, theta0]) == Matrix( + [[cos(theta0), -r0*sin(theta0)], [sin(theta0), r0*cos(theta0)]]) + + field = f(R2.x, R2.y) + p1_in_rect = R2_r.point([x0, y0]) + p1_in_polar = R2_p.point([sqrt(x0**2 + y0**2), atan2(y0, x0)]) + assert field.rcall(p1_in_rect) == f(x0, y0) + assert field.rcall(p1_in_polar) == f(x0, y0) + + p_r = R2_r.point([x0, y0]) + p_p = R2_p.point([r0, theta0]) + assert R2.x(p_r) == x0 + assert R2.x(p_p) == r0*cos(theta0) + assert R2.r(p_p) == r0 + assert R2.r(p_r) == sqrt(x0**2 + y0**2) + assert R2.theta(p_r) == atan2(y0, x0) + + h = R2.x*R2.r**2 + R2.y**3 + assert h.rcall(p_r) == x0*(x0**2 + y0**2) + y0**3 + assert h.rcall(p_p) == r0**3*sin(theta0)**3 + r0**3*cos(theta0) + + +def test_functional_diffgeom_ch3(): + x0, y0 = symbols('x0, y0', real=True) + x, y, t = symbols('x, y, t', real=True) + f = Function('f') + b1 = Function('b1') + b2 = Function('b2') + p_r = R2_r.point([x0, y0]) + + s_field = f(R2.x, R2.y) + v_field = b1(R2.x)*R2.e_x + b2(R2.y)*R2.e_y + assert v_field.rcall(s_field).rcall(p_r).doit() == b1( + x0)*Derivative(f(x0, y0), x0) + b2(y0)*Derivative(f(x0, y0), y0) + + assert R2.e_x(R2.r**2).rcall(p_r) == 2*x0 + v = R2.e_x + 2*R2.e_y + s = R2.r**2 + 3*R2.x + assert v.rcall(s).rcall(p_r).doit() == 2*x0 + 4*y0 + 3 + + circ = -R2.y*R2.e_x + R2.x*R2.e_y + series = intcurve_series(circ, t, R2_r.point([1, 0]), coeffs=True) + series_x, series_y = zip(*series) + assert all( + [term == cos(t).taylor_term(i, t) for i, term in enumerate(series_x)]) + assert all( + [term == sin(t).taylor_term(i, t) for i, term in enumerate(series_y)]) + + +def test_functional_diffgeom_ch4(): + x0, y0, theta0 = symbols('x0, y0, theta0', real=True) + x, y, r, theta = symbols('x, y, r, theta', real=True) + r0 = symbols('r0', positive=True) + f = Function('f') + b1 = Function('b1') + b2 = Function('b2') + p_r = R2_r.point([x0, y0]) + p_p = R2_p.point([r0, theta0]) + + f_field = b1(R2.x, R2.y)*R2.dx + b2(R2.x, R2.y)*R2.dy + assert f_field.rcall(R2.e_x).rcall(p_r) == b1(x0, y0) + assert f_field.rcall(R2.e_y).rcall(p_r) == b2(x0, y0) + + s_field_r = f(R2.x, R2.y) + df = Differential(s_field_r) + assert df(R2.e_x).rcall(p_r).doit() == Derivative(f(x0, y0), x0) + assert df(R2.e_y).rcall(p_r).doit() == Derivative(f(x0, y0), y0) + + s_field_p = f(R2.r, R2.theta) + df = Differential(s_field_p) + assert trigsimp(df(R2.e_x).rcall(p_p).doit()) == ( + cos(theta0)*Derivative(f(r0, theta0), r0) - + sin(theta0)*Derivative(f(r0, theta0), theta0)/r0) + assert trigsimp(df(R2.e_y).rcall(p_p).doit()) == ( + sin(theta0)*Derivative(f(r0, theta0), r0) + + cos(theta0)*Derivative(f(r0, theta0), theta0)/r0) + + assert R2.dx(R2.e_x).rcall(p_r) == 1 + assert R2.dx(R2.e_x) == 1 + assert R2.dx(R2.e_y).rcall(p_r) == 0 + assert R2.dx(R2.e_y) == 0 + + circ = -R2.y*R2.e_x + R2.x*R2.e_y + assert R2.dx(circ).rcall(p_r).doit() == -y0 + assert R2.dy(circ).rcall(p_r) == x0 + assert R2.dr(circ).rcall(p_r) == 0 + assert simplify(R2.dtheta(circ).rcall(p_r)) == 1 + + assert (circ - R2.e_theta).rcall(s_field_r).rcall(p_r) == 0 + + +def test_functional_diffgeom_ch6(): + u0, u1, u2, v0, v1, v2, w0, w1, w2 = symbols('u0:3, v0:3, w0:3', real=True) + + u = u0*R2.e_x + u1*R2.e_y + v = v0*R2.e_x + v1*R2.e_y + wp = WedgeProduct(R2.dx, R2.dy) + assert wp(u, v) == u0*v1 - u1*v0 + + u = u0*R3_r.e_x + u1*R3_r.e_y + u2*R3_r.e_z + v = v0*R3_r.e_x + v1*R3_r.e_y + v2*R3_r.e_z + w = w0*R3_r.e_x + w1*R3_r.e_y + w2*R3_r.e_z + wp = WedgeProduct(R3_r.dx, R3_r.dy, R3_r.dz) + assert wp( + u, v, w) == Matrix(3, 3, [u0, u1, u2, v0, v1, v2, w0, w1, w2]).det() + + a, b, c = symbols('a, b, c', cls=Function) + a_f = a(R3_r.x, R3_r.y, R3_r.z) + b_f = b(R3_r.x, R3_r.y, R3_r.z) + c_f = c(R3_r.x, R3_r.y, R3_r.z) + theta = a_f*R3_r.dx + b_f*R3_r.dy + c_f*R3_r.dz + dtheta = Differential(theta) + da = Differential(a_f) + db = Differential(b_f) + dc = Differential(c_f) + expr = dtheta - WedgeProduct( + da, R3_r.dx) - WedgeProduct(db, R3_r.dy) - WedgeProduct(dc, R3_r.dz) + assert expr.rcall(R3_r.e_x, R3_r.e_y) == 0 diff --git a/shared/package-files/d1/d18db0d41b70ea26ad7e875913bcf4962b0924b542afbd03016fbada17bfb33e/blob b/shared/package-files/d1/d18db0d41b70ea26ad7e875913bcf4962b0924b542afbd03016fbada17bfb33e/blob new file mode 100644 index 0000000000000000000000000000000000000000..284e214d38ed331cf0493d1e3bba6e1214939b2c --- /dev/null +++ b/shared/package-files/d1/d18db0d41b70ea26ad7e875913bcf4962b0924b542afbd03016fbada17bfb33e/blob @@ -0,0 +1,118 @@ +import numpy as np +from numpy.testing import (assert_allclose, + assert_equal) +import scipy.linalg.cython_blas as blas + +class TestDGEMM: + + def test_transposes(self): + + a = np.arange(12, dtype='d').reshape((3, 4))[:2,:2] + b = np.arange(1, 13, dtype='d').reshape((4, 3))[:2,:2] + c = np.empty((2, 4))[:2,:2] + + blas._test_dgemm(1., a, b, 0., c) + assert_allclose(c, a.dot(b)) + + blas._test_dgemm(1., a.T, b, 0., c) + assert_allclose(c, a.T.dot(b)) + + blas._test_dgemm(1., a, b.T, 0., c) + assert_allclose(c, a.dot(b.T)) + + blas._test_dgemm(1., a.T, b.T, 0., c) + assert_allclose(c, a.T.dot(b.T)) + + blas._test_dgemm(1., a, b, 0., c.T) + assert_allclose(c, a.dot(b).T) + + blas._test_dgemm(1., a.T, b, 0., c.T) + assert_allclose(c, a.T.dot(b).T) + + blas._test_dgemm(1., a, b.T, 0., c.T) + assert_allclose(c, a.dot(b.T).T) + + blas._test_dgemm(1., a.T, b.T, 0., c.T) + assert_allclose(c, a.T.dot(b.T).T) + + def test_shapes(self): + a = np.arange(6, dtype='d').reshape((3, 2)) + b = np.arange(-6, 2, dtype='d').reshape((2, 4)) + c = np.empty((3, 4)) + + blas._test_dgemm(1., a, b, 0., c) + assert_allclose(c, a.dot(b)) + + blas._test_dgemm(1., b.T, a.T, 0., c.T) + assert_allclose(c, b.T.dot(a.T).T) + +class TestWfuncPointers: + """ Test the function pointers that are expected to fail on + Mac OS X without the additional entry statement in their definitions + in fblas_l1.pyf.src. """ + + def test_complex_args(self): + + cx = np.array([.5 + 1.j, .25 - .375j, 12.5 - 4.j], np.complex64) + cy = np.array([.8 + 2.j, .875 - .625j, -1. + 2.j], np.complex64) + + assert_allclose(blas._test_cdotc(cx, cy), + -17.6468753815+21.3718757629j) + assert_allclose(blas._test_cdotu(cx, cy), + -6.11562538147+30.3156242371j) + + assert_equal(blas._test_icamax(cx), 3) + + assert_allclose(blas._test_scasum(cx), 18.625) + assert_allclose(blas._test_scnrm2(cx), 13.1796483994) + + assert_allclose(blas._test_cdotc(cx[::2], cy[::2]), + -18.1000003815+21.2000007629j) + assert_allclose(blas._test_cdotu(cx[::2], cy[::2]), + -6.10000038147+30.7999992371j) + assert_allclose(blas._test_scasum(cx[::2]), 18.) + assert_allclose(blas._test_scnrm2(cx[::2]), 13.1719398499) + + def test_double_args(self): + + x = np.array([5., -3, -.5], np.float64) + y = np.array([2, 1, .5], np.float64) + + assert_allclose(blas._test_dasum(x), 8.5) + assert_allclose(blas._test_ddot(x, y), 6.75) + assert_allclose(blas._test_dnrm2(x), 5.85234975815) + + assert_allclose(blas._test_dasum(x[::2]), 5.5) + assert_allclose(blas._test_ddot(x[::2], y[::2]), 9.75) + assert_allclose(blas._test_dnrm2(x[::2]), 5.0249376297) + + assert_equal(blas._test_idamax(x), 1) + + def test_float_args(self): + + x = np.array([5., -3, -.5], np.float32) + y = np.array([2, 1, .5], np.float32) + + assert_equal(blas._test_isamax(x), 1) + + assert_allclose(blas._test_sasum(x), 8.5) + assert_allclose(blas._test_sdot(x, y), 6.75) + assert_allclose(blas._test_snrm2(x), 5.85234975815) + + assert_allclose(blas._test_sasum(x[::2]), 5.5) + assert_allclose(blas._test_sdot(x[::2], y[::2]), 9.75) + assert_allclose(blas._test_snrm2(x[::2]), 5.0249376297) + + def test_double_complex_args(self): + + cx = np.array([.5 + 1.j, .25 - .375j, 13. - 4.j], np.complex128) + cy = np.array([.875 + 2.j, .875 - .625j, -1. + 2.j], np.complex128) + + assert_equal(blas._test_izamax(cx), 3) + + assert_allclose(blas._test_zdotc(cx, cy), -18.109375+22.296875j) + assert_allclose(blas._test_zdotu(cx, cy), -6.578125+31.390625j) + + assert_allclose(blas._test_zdotc(cx[::2], cy[::2]), -18.5625+22.125j) + assert_allclose(blas._test_zdotu(cx[::2], cy[::2]), -6.5625+31.875j) + diff --git a/shared/package-files/d1/d18db3d2b95eba710fe685b9dd20c03708d8acca258ed48b297261c633dfedf6/blob b/shared/package-files/d1/d18db3d2b95eba710fe685b9dd20c03708d8acca258ed48b297261c633dfedf6/blob new file mode 100644 index 0000000000000000000000000000000000000000..881338d173d6f7e17544b5d536e3ab386f96776e --- /dev/null +++ b/shared/package-files/d1/d18db3d2b95eba710fe685b9dd20c03708d8acca258ed48b297261c633dfedf6/blob @@ -0,0 +1,79 @@ +from __future__ import annotations + +from narwhals.stable.v1._dtypes import ( + Array, + Binary, + Boolean, + Categorical, + Date, + Datetime, + Decimal, + DType, + Duration, + Enum, + Field, + Float16, + Float32, + Float64, + FloatType, + Int8, + Int16, + Int32, + Int64, + Int128, + IntegerType, + List, + NestedType, + NumericType, + Object, + SignedIntegerType, + String, + Struct, + Time, + UInt8, + UInt16, + UInt32, + UInt64, + UInt128, + Unknown, + UnsignedIntegerType, +) + +__all__ = [ + "Array", + "Binary", + "Boolean", + "Categorical", + "DType", + "Date", + "Datetime", + "Decimal", + "Duration", + "Enum", + "Field", + "Float16", + "Float32", + "Float64", + "FloatType", + "Int8", + "Int16", + "Int32", + "Int64", + "Int128", + "IntegerType", + "List", + "NestedType", + "NumericType", + "Object", + "SignedIntegerType", + "String", + "Struct", + "Time", + "UInt8", + "UInt16", + "UInt32", + "UInt64", + "UInt128", + "Unknown", + "UnsignedIntegerType", +] diff --git a/shared/package-files/d1/d19128733490ab9f7338677f79693ab1f002b7adaf7509ad87789aeeea961533/blob b/shared/package-files/d1/d19128733490ab9f7338677f79693ab1f002b7adaf7509ad87789aeeea961533/blob new file mode 100644 index 0000000000000000000000000000000000000000..5b7f533926fd415a379cb08420b4a65a14baeb43 --- /dev/null +++ b/shared/package-files/d1/d19128733490ab9f7338677f79693ab1f002b7adaf7509ad87789aeeea961533/blob @@ -0,0 +1,167 @@ +import numpy as np +import scipy as sp + +__all__ = ['save_npz', 'load_npz'] + + +# Make loading safe vs. malicious input +PICKLE_KWARGS = dict(allow_pickle=False) + + +def save_npz(file, matrix, compressed=True): + """ Save a sparse matrix or array to a file using ``.npz`` format. + + Parameters + ---------- + file : str or file-like object + Either the file name (string) or an open file (file-like object) + where the data will be saved. If file is a string, the ``.npz`` + extension will be appended to the file name if it is not already + there. + matrix: spmatrix or sparray + The sparse matrix or array to save. + Supported formats: ``csc``, ``csr``, ``bsr``, ``dia`` or ``coo``. + compressed : bool, optional + Allow compressing the file. Default: True + + See Also + -------- + scipy.sparse.load_npz: Load a sparse matrix from a file using ``.npz`` format. + numpy.savez: Save several arrays into a ``.npz`` archive. + numpy.savez_compressed : Save several arrays into a compressed ``.npz`` archive. + + Examples + -------- + Store sparse matrix to disk, and load it again: + + >>> import numpy as np + >>> import scipy as sp + >>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]]) + >>> sparse_matrix + + >>> sparse_matrix.toarray() + array([[0, 0, 3], + [4, 0, 0]], dtype=int64) + + >>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix) + >>> sparse_matrix = sp.sparse.load_npz('/tmp/sparse_matrix.npz') + + >>> sparse_matrix + + >>> sparse_matrix.toarray() + array([[0, 0, 3], + [4, 0, 0]], dtype=int64) + """ + arrays_dict = {} + if matrix.format in ('csc', 'csr', 'bsr'): + arrays_dict.update(indices=matrix.indices, indptr=matrix.indptr) + elif matrix.format == 'dia': + arrays_dict.update(offsets=matrix.offsets) + elif matrix.format == 'coo': + arrays_dict.update(row=matrix.row, col=matrix.col) + else: + msg = f'Save is not implemented for sparse matrix of format {matrix.format}.' + raise NotImplementedError(msg) + arrays_dict.update( + format=matrix.format.encode('ascii'), + shape=matrix.shape, + data=matrix.data + ) + if isinstance(matrix, sp.sparse.sparray): + arrays_dict.update(_is_array=True) + if compressed: + np.savez_compressed(file, **arrays_dict) + else: + np.savez(file, **arrays_dict) + + +def load_npz(file): + """ Load a sparse array/matrix from a file using ``.npz`` format. + + Parameters + ---------- + file : str or file-like object + Either the file name (string) or an open file (file-like object) + where the data will be loaded. + + Returns + ------- + result : csc_array, csr_array, bsr_array, dia_array or coo_array + A sparse array/matrix containing the loaded data. + + Raises + ------ + OSError + If the input file does not exist or cannot be read. + + See Also + -------- + scipy.sparse.save_npz: Save a sparse array/matrix to a file using ``.npz`` format. + numpy.load: Load several arrays from a ``.npz`` archive. + + Examples + -------- + Store sparse array/matrix to disk, and load it again: + + >>> import numpy as np + >>> import scipy as sp + >>> sparse_array = sp.sparse.csc_array([[0, 0, 3], [4, 0, 0]]) + >>> sparse_array + + >>> sparse_array.toarray() + array([[0, 0, 3], + [4, 0, 0]], dtype=int64) + + >>> sp.sparse.save_npz('/tmp/sparse_array.npz', sparse_array) + >>> sparse_array = sp.sparse.load_npz('/tmp/sparse_array.npz') + + >>> sparse_array + + >>> sparse_array.toarray() + array([[0, 0, 3], + [4, 0, 0]], dtype=int64) + + In this example we force the result to be csr_array from csr_matrix + >>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]]) + >>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix) + >>> tmp = sp.sparse.load_npz('/tmp/sparse_matrix.npz') + >>> sparse_array = sp.sparse.csr_array(tmp) + """ + with np.load(file, **PICKLE_KWARGS) as loaded: + sparse_format = loaded.get('format') + if sparse_format is None: + raise ValueError(f'The file {file} does not contain ' + f'a sparse array or matrix.') + sparse_format = sparse_format.item() + + if not isinstance(sparse_format, str): + # Play safe with Python 2 vs 3 backward compatibility; + # files saved with SciPy < 1.0.0 may contain unicode or bytes. + sparse_format = sparse_format.decode('ascii') + + if loaded.get('_is_array'): + sparse_type = sparse_format + '_array' + else: + sparse_type = sparse_format + '_matrix' + + try: + cls = getattr(sp.sparse, f'{sparse_type}') + except AttributeError as e: + raise ValueError(f'Unknown format "{sparse_type}"') from e + + if sparse_format in ('csc', 'csr', 'bsr'): + return cls((loaded['data'], loaded['indices'], loaded['indptr']), + shape=loaded['shape']) + elif sparse_format == 'dia': + return cls((loaded['data'], loaded['offsets']), + shape=loaded['shape']) + elif sparse_format == 'coo': + return cls((loaded['data'], (loaded['row'], loaded['col'])), + shape=loaded['shape']) + else: + raise NotImplementedError(f'Load is not implemented for ' + f'sparse matrix of format {sparse_format}.') diff --git a/shared/package-files/d1/d192faf80cd86a219fadebc75c1c165979104ab4f15d1c4e40b852ae3333559b/blob b/shared/package-files/d1/d192faf80cd86a219fadebc75c1c165979104ab4f15d1c4e40b852ae3333559b/blob new file mode 100644 index 0000000000000000000000000000000000000000..03ecf0db2b7c794b937b1b77c136935fd6e31bbf --- /dev/null +++ b/shared/package-files/d1/d192faf80cd86a219fadebc75c1c165979104ab4f15d1c4e40b852ae3333559b/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor _embedding_bag_sparse_backward(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, const at::Tensor & bag_size, int64_t num_weights, bool scale_grad_by_freq, int64_t mode, const c10::optional & per_sample_weights, int64_t padding_idx=-1); +TORCH_API at::Tensor _embedding_bag_sparse_backward_symint(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, const at::Tensor & bag_size, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, const c10::optional & per_sample_weights, int64_t padding_idx=-1); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/d1/d194f21ff987988f6eb704d36c15ab752fdc9398e9b3d47633f7d824f5f11ff5/blob b/shared/package-files/d1/d194f21ff987988f6eb704d36c15ab752fdc9398e9b3d47633f7d824f5f11ff5/blob new file mode 100644 index 0000000000000000000000000000000000000000..2883493085143c64c95d60a249e5444f8840cbc6 --- /dev/null +++ b/shared/package-files/d1/d194f21ff987988f6eb704d36c15ab752fdc9398e9b3d47633f7d824f5f11ff5/blob @@ -0,0 +1,91 @@ +# SPDX-License-Identifier: MIT + + +class FrozenError(AttributeError): + """ + A frozen/immutable instance or attribute have been attempted to be + modified. + + It mirrors the behavior of ``namedtuples`` by using the same error message + and subclassing `AttributeError`. + + .. versionadded:: 20.1.0 + """ + + msg = "can't set attribute" + args = [msg] + + +class FrozenInstanceError(FrozenError): + """ + A frozen instance has been attempted to be modified. + + .. versionadded:: 16.1.0 + """ + + +class FrozenAttributeError(FrozenError): + """ + A frozen attribute has been attempted to be modified. + + .. versionadded:: 20.1.0 + """ + + +class AttrsAttributeNotFoundError(ValueError): + """ + An *attrs* function couldn't find an attribute that the user asked for. + + .. versionadded:: 16.2.0 + """ + + +class NotAnAttrsClassError(ValueError): + """ + A non-*attrs* class has been passed into an *attrs* function. + + .. versionadded:: 16.2.0 + """ + + +class DefaultAlreadySetError(RuntimeError): + """ + A default has been set when defining the field and is attempted to be reset + using the decorator. + + .. versionadded:: 17.1.0 + """ + + +class UnannotatedAttributeError(RuntimeError): + """ + A class with ``auto_attribs=True`` has a field without a type annotation. + + .. versionadded:: 17.3.0 + """ + + +class PythonTooOldError(RuntimeError): + """ + It was attempted to use an *attrs* feature that requires a newer Python + version. + + .. versionadded:: 18.2.0 + """ + + +class NotCallableError(TypeError): + """ + A field requiring a callable has been set with a value that is not + callable. + + .. versionadded:: 19.2.0 + """ + + def __init__(self, msg, value): + super(TypeError, self).__init__(msg, value) + self.msg = msg + self.value = value + + def __str__(self): + return str(self.msg) diff --git a/shared/package-files/d1/d195247e61c65466edb3c8ef31606b06523b5de406a81bb30050df734b983803/blob b/shared/package-files/d1/d195247e61c65466edb3c8ef31606b06523b5de406a81bb30050df734b983803/blob new file mode 100644 index 0000000000000000000000000000000000000000..e406812069d3fbbc59a0a837356b6076f3741069 --- /dev/null +++ b/shared/package-files/d1/d195247e61c65466edb3c8ef31606b06523b5de406a81bb30050df734b983803/blob @@ -0,0 +1,435 @@ +# RLM MODEL RESULTS + +import numpy as np + + +def _shift_intercept(arr): + """ + A convenience function to make the SAS covariance matrix + compatible with statsmodels.rlm covariance + """ + arr = np.asarray(arr) + side = int(np.sqrt(len(arr))) + return np.roll(np.roll(arr.reshape(side, side), -1, axis=1), -1, axis=0) + + +class Huber: + """ + """ + def __init__(self): + self.params = np.array([0.82937387, 0.92610818, + -0.12784916, -41.02653105]) + self.bse = np.array([0.11118035, 0.3034081, 0.12885259, 9.8073472]) + self.scale = 2.4407137948148447 + self.weights = np.array([ + 1., 1., 0.7858871, 0.50494094, 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 0.36814106]) + self.resid = np.array([ + 3.05027584, -2.07757332, 4.17721071, + 6.50163171, -1.64615192, -2.57226011, -1.73127333, -0.73127333, + -2.25476463, 0.48083217, 1.63147461, 1.42973363, -2.26346951, + -0.78323693, 2.26646556, 0.88291808, -0.83307835, 0.06186577, + 0.26360675, 1.54306186, -8.91752986]) + self.df_model = 3 + self.df_resid = 17 + self.bcov_unscaled = np.array([ + [1.72887367e-03, -3.47079127e-03, + -6.79080082e-04, 2.73387119e-02], + [-3.47079127e-03, 1.28754242e-02, 9.95952051e-07, + -6.19611175e-02], + [-6.79080082e-04, 9.95952051e-07, 2.32216722e-03, + -1.59355028e-01], + [2.73387119e-02, -6.19611175e-02, -1.59355028e-01, + 1.34527267e+01]]) # From R + self.fittedvalues = np.array([ + 38.94972416, 39.07757332, 32.82278929, 21.49836829, + 19.64615192, 20.57226011, 20.73127333, 20.73127333, + 17.25476463, 13.51916783, 12.36852539, 11.57026637, + 13.26346951, 12.78323693, 5.73353444, 6.11708192, + 8.83307835, 7.93813423, 8.73639325, 13.45693814, + 23.91752986]) + self.tvalues = np.array([7.45971657, 3.0523516, + -0.99221261, -4.18324448]) + # from R this is equivalent to + # self.res1.params/np.sqrt(np.diag(self.res1.bcov_scaled)) + + # The below are taken from SAS + huber_h1 = [ + 95.8813, 0.19485, -0.44161, -1.13577, 0.1949, 0.01232, + -0.02474, -0.00484, -0.4416, -0.02474, 0.09177, 0.00001, -1.1358, + -0.00484, 0.00001, 0.01655] + h1 = _shift_intercept(huber_h1) + + huber_h2 = [ + 82.6191, 0.07942, -0.23915, -0.95604, 0.0794, 0.01427, + -0.03013, -0.00344, -0.2392, -0.03013, 0.10391, -0.00166, -0.9560, + -0.00344, -0.00166, 0.01392] + h2 = _shift_intercept(huber_h2) + + huber_h3 = [ + 70.1633, -0.04533, -0.00790, -0.78618, -0.0453, 0.01656, + -0.03608, -0.00203, -0.0079, -0.03608, 0.11610, -0.00333, -0.7862, + -0.00203, -0.00333, 0.01138] + h3 = _shift_intercept(huber_h3) + + +class Hampel: + """ + """ + def __init__(self): + self.params = np.array([0.74108304, 1.22507934, + -0.14552506, -40.47473236]) + self.bse = np.array([0.13482596, 0.36793632, 0.1562567, 11.89315426]) + self.scale = 3.0882646556217064 + self.weights = np.array([ + 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0.80629719]) + self.resid = np.array([ + 3.06267708, -2.08284798, 4.36377602, + 5.78635972, -1.7634816, + -2.98856094, -2.34048993, -1.34048993, -3.02422878, 1.08249252, + 2.39221804, 2.47177232, -1.62645737, -0.25076107, 2.32088237, + 0.88430719, -1.37812296, -0.35944755, -0.43900184, 1.40555003, + -7.65988702]) + self.df_model = 3 + self.df_resid = 17 + self.bcov_unscaled = np.array([ + [1.72887367e-03, -3.47079127e-03, + -6.79080082e-04, 2.73387119e-02], + [-3.47079127e-03, 1.28754242e-02, 9.95952051e-07, + -6.19611175e-02], + [-6.79080082e-04, 9.95952051e-07, 2.32216722e-03, + -1.59355028e-01], + [2.73387119e-02, -6.19611175e-02, -1.59355028e-01, + 1.34527267e+01]]) + self.fittedvalues = np.array([ + 38.93732292, 39.08284798, + 32.63622398, 22.21364028, + 19.7634816, 20.98856094, 21.34048993, 21.34048993, + 18.02422878, 12.91750748, 11.60778196, 10.52822768, + 12.62645737, 12.25076107, 5.67911763, 6.11569281, + 9.37812296, 8.35944755, 9.43900184, 13.59444997, + 22.65988702]) + self.tvalues = np.array([5.49659011, 3.32959607, + -0.93132046, -3.40319578]) + + hampel_h1 = [ + 141.309, 0.28717, -0.65085, -1.67388, 0.287, 0.01816, + -0.03646, -0.00713, -0.651, -0.03646, 0.13524, 0.00001, -1.674, + -0.00713, 0.00001, 0.02439] + h1 = _shift_intercept(hampel_h1) + + hampel_h2 = [ + 135.248, 0.18207, -0.36884, -1.60217, 0.182, 0.02120, + -0.04563, -0.00567, -0.369, -0.04563, 0.15860, -0.00290, -1.602, + -0.00567, -0.00290, 0.02329] + h2 = _shift_intercept(hampel_h2) + + hampel_h3 = [ + 128.921, 0.05409, -0.02445, -1.52732, 0.054, 0.02514, + -0.05732, -0.00392, -0.024, -0.05732, 0.18871, -0.00652, -1.527, + -0.00392, -0.00652, 0.02212] + h3 = _shift_intercept(hampel_h3) + + +class BiSquare: + def __init__(self): + self.params = np.array([0.9275471, 0.65073222, + -0.11233103, -42.28525369]) + self.bse = np.array([0.10805398, 0.29487634, 0.12522928, 9.5315672]) + self.scale = 2.2818858795649497 + self.weights = np.array([ + 0.89283149, 0.88496132, 0.79040651, + 0.3358111, 0.94617358, 0.90040725, 0.96630596, 0.99729171, + 0.94968061, 0.99900087, 0.98959903, 0.99831448, 0.84731833, + 0.96455873, 0.91767906, 0.98724523, 0.99762848, 0.99694419, + 0.98650731, 0.95897484, 0.00222999]) + self.resid = np.array([ + 2.50917802, -2.60315301, 3.56070896, + 6.93256033, -1.76597524, -2.41670746, -1.39345348, -.39345348, + -1.70651907, -0.23917521, 0.77180408, 0.31020526, + -3.01451315, -1.42960401, 2.19218084, 0.85518774, + -0.36817892, 0.4181383, 0.87973712, 1.53911661, + -10.43556344]) + self.df_model = 3 + self.df_resid = 17 + self.bcov_unscaled = np.array([ + [1.72887367e-03, -3.47079127e-03, + -6.79080082e-04, 2.73387119e-02], + [-3.47079127e-03, 1.28754242e-02, 9.95952051e-07, + -6.19611175e-02], + [-6.79080082e-04, 9.95952051e-07, 2.32216722e-03, + -1.59355028e-01], + [2.73387119e-02, -6.19611175e-02, -1.59355028e-01, + 1.34527267e+01]]) + self.fittedvalues = np.array([ + 39.49082198, 39.60315301, 33.43929104, + 21.06743967, + 19.76597524, 20.41670746, 20.39345348, 20.39345348, + 16.70651907, 14.23917521, 13.22819592, 12.68979474, + 14.01451315, 13.42960401, 5.80781916, 6.14481226, + 8.36817892, 7.5818617, 8.12026288, 13.46088339, + 25.43556344]) + self.tvalues = np.array([8.58410823, 2.20679698, + -0.8970029, -4.43633799]) + + bisquare_h1 = [ + 90.3354, 0.18358, -0.41607, -1.07007, 0.1836, 0.01161, + -0.02331, -0.00456, -0.4161, -0.02331, 0.08646, 0.00001, -1.0701, + -0.00456, 0.00001, 0.01559] + h1 = _shift_intercept(bisquare_h1) + + bisquare_h2 = [ + 67.82521, 0.091288, -0.29038, -0.78124, 0.091288, + 0.013849, -0.02914, -0.00352, -0.29038, -0.02914, 0.101088, -0.001, + -0.78124, -0.00352, -0.001, 0.011766] + h2 = _shift_intercept(bisquare_h2) + + bisquare_h3 = [ + 48.8983, 0.000442, -0.15919, -0.53523, 0.000442, + 0.016113, -0.03461, -0.00259, -0.15919, -0.03461, 0.112728, + -0.00164, -0.53523, -0.00259, -0.00164, 0.008414] + h3 = _shift_intercept(bisquare_h3) + + +class Andrews: + def __init__(self): + self.params = [0.9282, 0.6492, -.1123, -42.2930] + self.bse = [.1061, .2894, .1229, 9.3561] + self.scale = 2.2801 + self.df_model = 3. + self.df_resid = 17. + # bcov_unscaled not defined because it is not given as part of SAS + self.resid = [ + 2.503338458, -2.608934536, 3.5548678338, 6.9333705014, + -1.768179527, -2.417404513, -1.392991531, -0.392991531, + -1.704759385, -0.244545418, 0.7659115325, 0.3028635237, + -3.019999429, -1.434221475, 2.1912017882, 0.8543828047, + -0.366664104, 0.4192468573, 0.8822948661, 1.5378731634, + -10.44592783] + + self.sresids = [ + 1.0979293816, -1.144242351, 1.5591155202, 3.040879735, + -0.775498914, -1.06023995, -0.610946684, -0.172360612, + -0.747683723, -0.107254214, 0.3359181307, 0.1328317233, + -1.324529688, -0.629029563, 0.9610305856, 0.3747203984, + -0.160813769, 0.1838758324, 0.3869622398, 0.6744897502, + -4.581438458] + + self.weights = [ + 0.8916509101, 0.8826581922, 0.7888664106, 0.3367252734, + 0.9450252405, 0.8987321912, 0.9656622, 0.9972406688, + 0.948837669, 0.9989310017, 0.9895434667, 0.998360628, + 0.8447116551, 0.9636222149, 0.916330067, 0.9869982597, + 0.9975977354, 0.9968600162, 0.9861384742, 0.9582432444, 0] + + def conf_int(self): # method to be consistent with sm + return [(0.7203, 1.1360), (.0819, 1.2165), (-.3532, .1287), + (-60.6305, -23.9555)] + + andrews_h1 = [ + 87.5357, 0.177891, -0.40318, -1.03691, 0.177891, 0.01125, + -0.02258, -0.00442, -0.40318, -0.02258, 0.083779, 6.481E-6, + -1.03691, -0.00442, 6.481E-6, 0.01511] + h1 = _shift_intercept(andrews_h1) + + andrews_h2 = [ + 66.50472, 0.10489, -0.3246, -0.76664, 0.10489, 0.012786, + -0.02651, -0.0036, -0.3246, -0.02651, 0.09406, -0.00065, + -0.76664, -0.0036, -0.00065, 0.011567] + h2 = _shift_intercept(andrews_h2) + + andrews_h3 = [ + 48.62157, 0.034949, -0.24633, -0.53394, 0.034949, 0.014088, + -0.02956, -0.00287, -0.24633, -0.02956, 0.100628, -0.00104, + -0.53394, -0.00287, -0.00104, 0.008441] + h3 = _shift_intercept(andrews_h3) + + +# RLM Results with Huber's Proposal 2 +# Obtained from SAS + +class HuberHuber: + def __init__(self): + self.h1 = [ + 114.4936, 0.232675, -0.52734, -1.35624, 0.232675, 0.014714, + -0.02954, -0.00578, -0.52734, -0.02954, 0.10958, 8.476E-6, + -1.35624, -0.00578, 8.476E-6, 0.019764] + self.h1 = _shift_intercept(self.h1) + self.h2 = [ + 103.2876, 0.152602, -0.33476, -1.22084, 0.152602, 0.016904, + -0.03766, -0.00434, -0.33476, -0.03766, 0.132043, -0.00214, + -1.22084, -0.00434, -0.00214, 0.017739] + self.h2 = _shift_intercept(self.h2) + self.h3 = [ + 91.7544, 0.064027, -0.11379, -1.08249, 0.064027, 0.019509, + -0.04702, -0.00278, -0.11379, -0.04702, 0.157872, -0.00462, + -1.08249, -0.00278, -0.00462, 0.015677] + self.h3 = _shift_intercept(self.h3) + self.resid = [ + 2.909155172, -2.225912162, 4.134132661, 6.163172632, + -1.741815737, -2.789321552, -2.02642336, -1.02642336, + -2.593402734, 0.698655, 1.914261011, 1.826699492, -2.031210331, + -0.592975466, 2.306098648, 0.900896645, -1.037551854, + -0.092080512, -0.004518993, 1.471737448, -8.498372406] + self.sresids = [ + 0.883018497, -0.675633129, 1.25483702, 1.870713355, + -0.528694904, -0.84664529, -0.615082113, -0.311551209, + -0.787177874, 0.212063383, 0.581037374, 0.554459746, + -0.616535106, -0.179986379, 0.699972205, 0.273449972, + -0.314929051, -0.027949281, -0.001371654, 0.446717797, + -2.579518651] + self.weights = [ + 1, 1, 1, 0.718977066, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 0.52141511] + + self.params = (.7990, 1.0475, -0.1351, -41.0892) + self.bse = (.1213, .3310, .1406, 10.7002) + self.scale = 3.2946 + self.df_model = 3 + self.df_resid = 17 + + def conf_int(self): # method for consistency with sm + return [(0.5612, 1.0367), (.3987, 1.6963), + (-.4106, .1405), (-62.0611, -20.1172)] + + +class HampelHuber: + def __init__(self): + self.h1 = [ + 147.4727, 0.299695, -0.67924, -1.7469, 0.299695, 0.018952, + -0.03805, -0.00744, -0.67924, -0.03805, 0.141144, 0.000011, + -1.7469, -0.00744, 0.000011, 0.025456] + self.h1 = _shift_intercept(self.h1) + self.h2 = [ + 141.148, 0.190007, -0.38493, -1.67206, 0.190007, 0.02213, + -0.04762, -0.00592, -0.38493, -0.04762, 0.165518, -0.00303, + -1.67206, -0.00592, -0.00303, 0.024301] + self.h2 = _shift_intercept(self.h2) + self.h3 = [ + 134.5444, 0.05645, -0.02552, -1.59394, 0.05645, 0.026232, + -0.05982, -0.00409, -0.02552, -0.05982, 0.196946, -0.0068, + -1.59394, -0.00409, -0.0068, 0.023083] + self.h3 = _shift_intercept(self.h3) + self.resid = [ + 3.125725599, -2.022218392, 4.434082972, 5.753880172, + -1.744479058, -2.995299443, -2.358455878, -1.358455878, + -3.068281354, 1.150212629, 2.481708553, 2.584584946, + -1.553899388, -0.177335865, 2.335744732, 0.891912757, + -1.43012351, -0.394515569, -0.497391962, 1.407968887, + -7.505098501] + self.sresids = [ + 0.952186413, -0.616026205, 1.350749906, 1.752798302, + -0.531418771, -0.912454834, -0.718453867, -0.413824947, + -0.934687235, 0.350388031, 0.756000196, 0.787339321, + -0.473362692, -0.054021633, 0.711535395, 0.27170242, + -0.43565698, -0.120180852, -0.151519976, 0.428908041, + -2.28627005] + self.weights = [ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 0.874787298] + + self.params = (.7318, 1.2508, -0.1479, -40.2712) + self.bse = (.1377, .3757, .1596, 12.1438) + self.scale = 3.2827 + self.df_model = 3 + self.df_resid = 17 + + def conf_int(self): + return [(0.4619, 1.0016), (.5145, 1.9872), + (-.4607, .1648), (-64.0727, -16.4697)] + + +class BisquareHuber: + def __init__(self): + self.h1 = [ + 129.9556, 0.264097, -0.59855, -1.5394, 0.264097, + 0.016701, -0.03353, -0.00656, -0.59855, -0.03353, + 0.124379, 9.621E-6, -1.5394, -0.00656, 9.621E-6, 0.022433] + self.h1 = _shift_intercept(self.h1) + self.h2 = [ + 109.7685, 0.103038, -0.25926, -1.28355, 0.103038, 0.0214, + -0.04688, -0.00453, -0.25926, -0.04688, 0.158535, -0.00327, + -1.28355, -0.00453, -0.00327, 0.018892] + self.h2 = _shift_intercept(self.h2) + self.h3 = [ + 91.80527, -0.09171, 0.171716, -1.05244, -0.09171, + 0.027999, -0.06493, -0.00223, 0.171716, -0.06493, 0.203254, + -0.0071, -1.05244, -0.00223, -0.0071, 0.015584] + self.h3 = _shift_intercept(self.h3) + self.resid = [ + 3.034895447, -2.09863887, 4.229870063, 6.18871385, + -1.715906134, -2.763596142, -2.010080245, -1.010080245, + -2.590747917, 0.712961901, 1.914770759, 1.82892645, -2.019969464, + -0.598781979, 2.260467209, 0.859864256, -1.057306197, -0.122565974, + -0.036721665, 1.471074632, -8.432085298] + self.sresids = [ + 0.918227061, -0.634956635, 1.279774287, 1.872435025, + -0.519158394, -0.836143718, -0.608162656, -0.305606249, -.78384738, + 0.215711191, 0.579326161, 0.553353415, -0.611154703, -0.181165324, + 0.683918836, 0.26015744, -0.319894764, -0.037083121, -0.011110375, + 0.445083055, -2.551181429] + self.weights = [ + 0.924649089, 0.963600796, 0.856330585, 0.706048833, + 0.975591792, 0.937309703, 0.966582366, 0.991507994, 0.944798311, + 0.995764589, 0.969652425, 0.972293856, 0.966255569, 0.997011618, + 0.957833493, 0.993842376, 0.990697247, 0.9998747, 0.999988752, + 0.982030803, 0.494874977] + self.params = (.7932, 1.0477, -0.1335, -40.8949) + self.bse = (.1292, .3527, .1498, 11.3998) + self.scale = 3.3052 + self.df_model = 3 + self.df_resid = 17 + + def conf_int(self): + return [(0.5399, 1.0465), (.3565, 1.7389), + (-.4271, .1600), (-63.2381, -18.5517)] + + +class AndrewsHuber: + def __init__(self): + self.h1 = [ + 129.9124, 0.264009, -0.59836, -1.53888, 0.264009, + 0.016696, -0.03352, -0.00656, -0.59836, -0.03352, 0.124337, + 9.618E-6, -1.53888, -0.00656, 9.618E-6, 0.022425] + self.h1 = _shift_intercept(self.h1) + self.h2 = [ + 109.7595, 0.105022, -0.26535, -1.28332, .105022, 0.021321, + -0.04664, -0.00456, -0.26535, -0.04664, 0.157885, -0.00321, + -1.28332, -0.00456, -0.00321, 0.018895] + self.h2 = _shift_intercept(self.h2) + self.h3 = [ + 91.82518, -0.08649, 0.155965, -1.05238, -0.08649, 0.027785, + -0.06427, -0.0023, 0.155965, -0.06427, 0.201544, -0.00693, + -1.05238, -0.0023, -0.00693, 0.015596] + self.h3 = _shift_intercept(self.h3) + self.resid = [ + 3.040515104, -2.093093543, 4.235081748, 6.188729166, + -1.714119676, -2.762695255, -2.009618953, -1.009618953, + -2.591649784, 0.715967584, 1.918445405, 1.833412337, + -2.016815123, -0.595695587, 2.260536347, 0.859710406, + -1.059386228, -0.1241257, -0.039092633, 1.471556455, + -8.424624872] + self.sresids = [ + 0.919639919, -0.633081011, 1.280950793, 1.871854667, + -0.518455862, -0.835610004, -0.607833129, -0.305371248, + -0.783875269, 0.216552902, 0.580256606, 0.554537345, + -0.610009696, -0.180175208, 0.683726076, 0.260029627, + -0.320423952, -0.037543293, -0.011824031, 0.445089734, + -2.548127888] + self.weights = [ + 0.923215335, 0.963157359, 0.854300342, 0.704674258, + 0.975199805, 0.936344742, 0.9660077, 0.991354016, 0.943851708, + 0.995646409, 0.968993767, 0.971658421, 0.965766352, 0.99698502, + 0.957106815, 0.993726436, 0.990483134, 0.999868981, 0.999987004, + 0.981686004, 0.496752113] + self.params = (.7928, 1.0486, -0.1336, -40.8818) + self.bse = (.1292, .3526, .1498, 11.3979) + self.scale = 3.3062 + self.df_model = 3 + self.df_resid = 17 + + def conf_int(self): + return [(0.5395, 1.0460), (.3575, 1.7397), + (-.4271, .1599), (-63.2213, -18.5423)] diff --git a/shared/package-files/d1/d1976b0efcc0e4c1527c9d21f34ef1f36a230ef6f2f08dc5af8431b0d1ee3bb4/blob b/shared/package-files/d1/d1976b0efcc0e4c1527c9d21f34ef1f36a230ef6f2f08dc5af8431b0d1ee3bb4/blob new file mode 100644 index 0000000000000000000000000000000000000000..65603d3c1085e22af4fe7ff0306b4363055dd4b7 --- /dev/null +++ b/shared/package-files/d1/d1976b0efcc0e4c1527c9d21f34ef1f36a230ef6f2f08dc5af8431b0d1ee3bb4/blob @@ -0,0 +1,472 @@ +import bz2 +import os +import pickle + +import pytest + +import networkx as nx + + +class TestMinCostFlow: + def test_simple_digraph(self): + G = nx.DiGraph() + G.add_node("a", demand=-5) + G.add_node("d", demand=5) + G.add_edge("a", "b", weight=3, capacity=4) + G.add_edge("a", "c", weight=6, capacity=10) + G.add_edge("b", "d", weight=1, capacity=9) + G.add_edge("c", "d", weight=2, capacity=5) + flowCost, H = nx.network_simplex(G) + soln = {"a": {"b": 4, "c": 1}, "b": {"d": 4}, "c": {"d": 1}, "d": {}} + assert flowCost == 24 + assert nx.min_cost_flow_cost(G) == 24 + assert H == soln + assert nx.min_cost_flow(G) == soln + assert nx.cost_of_flow(G, H) == 24 + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 24 + assert nx.cost_of_flow(G, H) == 24 + assert H == soln + + def test_negcycle_infcap(self): + G = nx.DiGraph() + G.add_node("s", demand=-5) + G.add_node("t", demand=5) + G.add_edge("s", "a", weight=1, capacity=3) + G.add_edge("a", "b", weight=3) + G.add_edge("c", "a", weight=-6) + G.add_edge("b", "d", weight=1) + G.add_edge("d", "c", weight=-2) + G.add_edge("d", "t", weight=1, capacity=3) + pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G) + + def test_sum_demands_not_zero(self): + G = nx.DiGraph() + G.add_node("s", demand=-5) + G.add_node("t", demand=4) + G.add_edge("s", "a", weight=1, capacity=3) + G.add_edge("a", "b", weight=3) + G.add_edge("a", "c", weight=-6) + G.add_edge("b", "d", weight=1) + G.add_edge("c", "d", weight=-2) + G.add_edge("d", "t", weight=1, capacity=3) + pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G) + + def test_no_flow_satisfying_demands(self): + G = nx.DiGraph() + G.add_node("s", demand=-5) + G.add_node("t", demand=5) + G.add_edge("s", "a", weight=1, capacity=3) + G.add_edge("a", "b", weight=3) + G.add_edge("a", "c", weight=-6) + G.add_edge("b", "d", weight=1) + G.add_edge("c", "d", weight=-2) + G.add_edge("d", "t", weight=1, capacity=3) + pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G) + + def test_transshipment(self): + G = nx.DiGraph() + G.add_node("a", demand=1) + G.add_node("b", demand=-2) + G.add_node("c", demand=-2) + G.add_node("d", demand=3) + G.add_node("e", demand=-4) + G.add_node("f", demand=-4) + G.add_node("g", demand=3) + G.add_node("h", demand=2) + G.add_node("r", demand=3) + G.add_edge("a", "c", weight=3) + G.add_edge("r", "a", weight=2) + G.add_edge("b", "a", weight=9) + G.add_edge("r", "c", weight=0) + G.add_edge("b", "r", weight=-6) + G.add_edge("c", "d", weight=5) + G.add_edge("e", "r", weight=4) + G.add_edge("e", "f", weight=3) + G.add_edge("h", "b", weight=4) + G.add_edge("f", "d", weight=7) + G.add_edge("f", "h", weight=12) + G.add_edge("g", "d", weight=12) + G.add_edge("f", "g", weight=-1) + G.add_edge("h", "g", weight=-10) + flowCost, H = nx.network_simplex(G) + soln = { + "a": {"c": 0}, + "b": {"a": 0, "r": 2}, + "c": {"d": 3}, + "d": {}, + "e": {"r": 3, "f": 1}, + "f": {"d": 0, "g": 3, "h": 2}, + "g": {"d": 0}, + "h": {"b": 0, "g": 0}, + "r": {"a": 1, "c": 1}, + } + assert flowCost == 41 + assert nx.min_cost_flow_cost(G) == 41 + assert H == soln + assert nx.min_cost_flow(G) == soln + assert nx.cost_of_flow(G, H) == 41 + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 41 + assert nx.cost_of_flow(G, H) == 41 + assert H == soln + + def test_max_flow_min_cost(self): + G = nx.DiGraph() + G.add_edge("s", "a", bandwidth=6) + G.add_edge("s", "c", bandwidth=10, cost=10) + G.add_edge("a", "b", cost=6) + G.add_edge("b", "d", bandwidth=8, cost=7) + G.add_edge("c", "d", cost=10) + G.add_edge("d", "t", bandwidth=5, cost=5) + soln = { + "s": {"a": 5, "c": 0}, + "a": {"b": 5}, + "b": {"d": 5}, + "c": {"d": 0}, + "d": {"t": 5}, + "t": {}, + } + flow = nx.max_flow_min_cost(G, "s", "t", capacity="bandwidth", weight="cost") + assert flow == soln + assert nx.cost_of_flow(G, flow, weight="cost") == 90 + + G.add_edge("t", "s", cost=-100) + flowCost, flow = nx.capacity_scaling(G, capacity="bandwidth", weight="cost") + G.remove_edge("t", "s") + assert flowCost == -410 + assert flow["t"]["s"] == 5 + del flow["t"]["s"] + assert flow == soln + assert nx.cost_of_flow(G, flow, weight="cost") == 90 + + def test_digraph1(self): + # From Bradley, S. P., Hax, A. C. and Magnanti, T. L. Applied + # Mathematical Programming. Addison-Wesley, 1977. + G = nx.DiGraph() + G.add_node(1, demand=-20) + G.add_node(4, demand=5) + G.add_node(5, demand=15) + G.add_edges_from( + [ + (1, 2, {"capacity": 15, "weight": 4}), + (1, 3, {"capacity": 8, "weight": 4}), + (2, 3, {"weight": 2}), + (2, 4, {"capacity": 4, "weight": 2}), + (2, 5, {"capacity": 10, "weight": 6}), + (3, 4, {"capacity": 15, "weight": 1}), + (3, 5, {"capacity": 5, "weight": 3}), + (4, 5, {"weight": 2}), + (5, 3, {"capacity": 4, "weight": 1}), + ] + ) + flowCost, H = nx.network_simplex(G) + soln = { + 1: {2: 12, 3: 8}, + 2: {3: 8, 4: 4, 5: 0}, + 3: {4: 11, 5: 5}, + 4: {5: 10}, + 5: {3: 0}, + } + assert flowCost == 150 + assert nx.min_cost_flow_cost(G) == 150 + assert H == soln + assert nx.min_cost_flow(G) == soln + assert nx.cost_of_flow(G, H) == 150 + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 150 + assert H == soln + assert nx.cost_of_flow(G, H) == 150 + + def test_digraph2(self): + # Example from ticket #430 from mfrasca. Original source: + # http://www.cs.princeton.edu/courses/archive/spr03/cs226/lectures/mincost.4up.pdf, slide 11. + G = nx.DiGraph() + G.add_edge("s", 1, capacity=12) + G.add_edge("s", 2, capacity=6) + G.add_edge("s", 3, capacity=14) + G.add_edge(1, 2, capacity=11, weight=4) + G.add_edge(2, 3, capacity=9, weight=6) + G.add_edge(1, 4, capacity=5, weight=5) + G.add_edge(1, 5, capacity=2, weight=12) + G.add_edge(2, 5, capacity=4, weight=4) + G.add_edge(2, 6, capacity=2, weight=6) + G.add_edge(3, 6, capacity=31, weight=3) + G.add_edge(4, 5, capacity=18, weight=4) + G.add_edge(5, 6, capacity=9, weight=5) + G.add_edge(4, "t", capacity=3) + G.add_edge(5, "t", capacity=7) + G.add_edge(6, "t", capacity=22) + flow = nx.max_flow_min_cost(G, "s", "t") + soln = { + 1: {2: 6, 4: 5, 5: 1}, + 2: {3: 6, 5: 4, 6: 2}, + 3: {6: 20}, + 4: {5: 2, "t": 3}, + 5: {6: 0, "t": 7}, + 6: {"t": 22}, + "s": {1: 12, 2: 6, 3: 14}, + "t": {}, + } + assert flow == soln + + G.add_edge("t", "s", weight=-100) + flowCost, flow = nx.capacity_scaling(G) + G.remove_edge("t", "s") + assert flow["t"]["s"] == 32 + assert flowCost == -3007 + del flow["t"]["s"] + assert flow == soln + assert nx.cost_of_flow(G, flow) == 193 + + def test_digraph3(self): + """Combinatorial Optimization: Algorithms and Complexity, + Papadimitriou Steiglitz at page 140 has an example, 7.1, but that + admits multiple solutions, so I alter it a bit. From ticket #430 + by mfrasca.""" + + G = nx.DiGraph() + G.add_edge("s", "a") + G["s"]["a"].update({0: 2, 1: 4}) + G.add_edge("s", "b") + G["s"]["b"].update({0: 2, 1: 1}) + G.add_edge("a", "b") + G["a"]["b"].update({0: 5, 1: 2}) + G.add_edge("a", "t") + G["a"]["t"].update({0: 1, 1: 5}) + G.add_edge("b", "a") + G["b"]["a"].update({0: 1, 1: 3}) + G.add_edge("b", "t") + G["b"]["t"].update({0: 3, 1: 2}) + + "PS.ex.7.1: testing main function" + sol = nx.max_flow_min_cost(G, "s", "t", capacity=0, weight=1) + flow = sum(v for v in sol["s"].values()) + assert 4 == flow + assert 23 == nx.cost_of_flow(G, sol, weight=1) + assert sol["s"] == {"a": 2, "b": 2} + assert sol["a"] == {"b": 1, "t": 1} + assert sol["b"] == {"a": 0, "t": 3} + assert sol["t"] == {} + + G.add_edge("t", "s") + G["t"]["s"].update({1: -100}) + flowCost, sol = nx.capacity_scaling(G, capacity=0, weight=1) + G.remove_edge("t", "s") + flow = sum(v for v in sol["s"].values()) + assert 4 == flow + assert sol["t"]["s"] == 4 + assert flowCost == -377 + del sol["t"]["s"] + assert sol["s"] == {"a": 2, "b": 2} + assert sol["a"] == {"b": 1, "t": 1} + assert sol["b"] == {"a": 0, "t": 3} + assert sol["t"] == {} + assert nx.cost_of_flow(G, sol, weight=1) == 23 + + def test_zero_capacity_edges(self): + """Address issue raised in ticket #617 by arv.""" + G = nx.DiGraph() + G.add_edges_from( + [ + (1, 2, {"capacity": 1, "weight": 1}), + (1, 5, {"capacity": 1, "weight": 1}), + (2, 3, {"capacity": 0, "weight": 1}), + (2, 5, {"capacity": 1, "weight": 1}), + (5, 3, {"capacity": 2, "weight": 1}), + (5, 4, {"capacity": 0, "weight": 1}), + (3, 4, {"capacity": 2, "weight": 1}), + ] + ) + G.nodes[1]["demand"] = -1 + G.nodes[2]["demand"] = -1 + G.nodes[4]["demand"] = 2 + + flowCost, H = nx.network_simplex(G) + soln = {1: {2: 0, 5: 1}, 2: {3: 0, 5: 1}, 3: {4: 2}, 4: {}, 5: {3: 2, 4: 0}} + assert flowCost == 6 + assert nx.min_cost_flow_cost(G) == 6 + assert H == soln + assert nx.min_cost_flow(G) == soln + assert nx.cost_of_flow(G, H) == 6 + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 6 + assert H == soln + assert nx.cost_of_flow(G, H) == 6 + + def test_digon(self): + """Check if digons are handled properly. Taken from ticket + #618 by arv.""" + nodes = [(1, {}), (2, {"demand": -4}), (3, {"demand": 4})] + edges = [ + (1, 2, {"capacity": 3, "weight": 600000}), + (2, 1, {"capacity": 2, "weight": 0}), + (2, 3, {"capacity": 5, "weight": 714285}), + (3, 2, {"capacity": 2, "weight": 0}), + ] + G = nx.DiGraph(edges) + G.add_nodes_from(nodes) + flowCost, H = nx.network_simplex(G) + soln = {1: {2: 0}, 2: {1: 0, 3: 4}, 3: {2: 0}} + assert flowCost == 2857140 + assert nx.min_cost_flow_cost(G) == 2857140 + assert H == soln + assert nx.min_cost_flow(G) == soln + assert nx.cost_of_flow(G, H) == 2857140 + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 2857140 + assert H == soln + assert nx.cost_of_flow(G, H) == 2857140 + + def test_deadend(self): + """Check if one-node cycles are handled properly. Taken from ticket + #2906 from @sshraven.""" + G = nx.DiGraph() + + G.add_nodes_from(range(5), demand=0) + G.nodes[4]["demand"] = -13 + G.nodes[3]["demand"] = 13 + + G.add_edges_from([(0, 2), (0, 3), (2, 1)], capacity=20, weight=0.1) + pytest.raises(nx.NetworkXUnfeasible, nx.min_cost_flow, G) + + def test_infinite_capacity_neg_digon(self): + """An infinite capacity negative cost digon results in an unbounded + instance.""" + nodes = [(1, {}), (2, {"demand": -4}), (3, {"demand": 4})] + edges = [ + (1, 2, {"weight": -600}), + (2, 1, {"weight": 0}), + (2, 3, {"capacity": 5, "weight": 714285}), + (3, 2, {"capacity": 2, "weight": 0}), + ] + G = nx.DiGraph(edges) + G.add_nodes_from(nodes) + pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G) + + def test_finite_capacity_neg_digon(self): + """The digon should receive the maximum amount of flow it can handle. + Taken from ticket #749 by @chuongdo.""" + G = nx.DiGraph() + G.add_edge("a", "b", capacity=1, weight=-1) + G.add_edge("b", "a", capacity=1, weight=-1) + min_cost = -2 + assert nx.min_cost_flow_cost(G) == min_cost + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == -2 + assert H == {"a": {"b": 1}, "b": {"a": 1}} + assert nx.cost_of_flow(G, H) == -2 + + def test_multidigraph(self): + """Multidigraphs are acceptable.""" + G = nx.MultiDiGraph() + G.add_weighted_edges_from([(1, 2, 1), (2, 3, 2)], weight="capacity") + flowCost, H = nx.network_simplex(G) + assert flowCost == 0 + assert H == {1: {2: {0: 0}}, 2: {3: {0: 0}}, 3: {}} + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 0 + assert H == {1: {2: {0: 0}}, 2: {3: {0: 0}}, 3: {}} + + def test_negative_selfloops(self): + """Negative selfloops should cause an exception if uncapacitated and + always be saturated otherwise. + """ + G = nx.DiGraph() + G.add_edge(1, 1, weight=-1) + pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G) + G[1][1]["capacity"] = 2 + flowCost, H = nx.network_simplex(G) + assert flowCost == -2 + assert H == {1: {1: 2}} + flowCost, H = nx.capacity_scaling(G) + assert flowCost == -2 + assert H == {1: {1: 2}} + + G = nx.MultiDiGraph() + G.add_edge(1, 1, "x", weight=-1) + G.add_edge(1, 1, "y", weight=1) + pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G) + G[1][1]["x"]["capacity"] = 2 + flowCost, H = nx.network_simplex(G) + assert flowCost == -2 + assert H == {1: {1: {"x": 2, "y": 0}}} + flowCost, H = nx.capacity_scaling(G) + assert flowCost == -2 + assert H == {1: {1: {"x": 2, "y": 0}}} + + def test_bone_shaped(self): + # From #1283 + G = nx.DiGraph() + G.add_node(0, demand=-4) + G.add_node(1, demand=2) + G.add_node(2, demand=2) + G.add_node(3, demand=4) + G.add_node(4, demand=-2) + G.add_node(5, demand=-2) + G.add_edge(0, 1, capacity=4) + G.add_edge(0, 2, capacity=4) + G.add_edge(4, 3, capacity=4) + G.add_edge(5, 3, capacity=4) + G.add_edge(0, 3, capacity=0) + flowCost, H = nx.network_simplex(G) + assert flowCost == 0 + assert H == {0: {1: 2, 2: 2, 3: 0}, 1: {}, 2: {}, 3: {}, 4: {3: 2}, 5: {3: 2}} + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 0 + assert H == {0: {1: 2, 2: 2, 3: 0}, 1: {}, 2: {}, 3: {}, 4: {3: 2}, 5: {3: 2}} + + def test_exceptions(self): + G = nx.Graph() + pytest.raises(nx.NetworkXNotImplemented, nx.network_simplex, G) + pytest.raises(nx.NetworkXNotImplemented, nx.capacity_scaling, G) + G = nx.MultiGraph() + pytest.raises(nx.NetworkXNotImplemented, nx.network_simplex, G) + pytest.raises(nx.NetworkXNotImplemented, nx.capacity_scaling, G) + G = nx.DiGraph() + pytest.raises(nx.NetworkXError, nx.network_simplex, G) + # pytest.raises(nx.NetworkXError, nx.capacity_scaling, G) + G.add_node(0, demand=float("inf")) + pytest.raises(nx.NetworkXError, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G) + G.nodes[0]["demand"] = 0 + G.add_node(1, demand=0) + G.add_edge(0, 1, weight=-float("inf")) + pytest.raises(nx.NetworkXError, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G) + G[0][1]["weight"] = 0 + G.add_edge(0, 0, weight=float("inf")) + pytest.raises(nx.NetworkXError, nx.network_simplex, G) + # pytest.raises(nx.NetworkXError, nx.capacity_scaling, G) + G[0][0]["weight"] = 0 + G[0][1]["capacity"] = -1 + pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G) + # pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G) + G[0][1]["capacity"] = 0 + G[0][0]["capacity"] = -1 + pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G) + # pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G) + + def test_large(self): + fname = os.path.join(os.path.dirname(__file__), "netgen-2.gpickle.bz2") + with bz2.BZ2File(fname, "rb") as f: + G = pickle.load(f) + flowCost, flowDict = nx.network_simplex(G) + assert 6749969302 == flowCost + assert 6749969302 == nx.cost_of_flow(G, flowDict) + flowCost, flowDict = nx.capacity_scaling(G) + assert 6749969302 == flowCost + assert 6749969302 == nx.cost_of_flow(G, flowDict) diff --git a/shared/package-files/d1/d19a7033230c463a7a56d9db153d219ae5719f31ed260f694f10c961133c9fa6/blob b/shared/package-files/d1/d19a7033230c463a7a56d9db153d219ae5719f31ed260f694f10c961133c9fa6/blob new file mode 100644 index 0000000000000000000000000000000000000000..fee74582e61bd613a60bf5eac7c7f5c3f60ca91f --- /dev/null +++ b/shared/package-files/d1/d19a7033230c463a7a56d9db153d219ae5719f31ed260f694f10c961133c9fa6/blob @@ -0,0 +1,96 @@ +from typing import Callable, Iterator, Tuple, TypeVar + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.datapipe import IterDataPipe +from torch.utils.data.datapipes.dataframe import dataframe_wrapper as df_wrapper +from torch.utils.data.datapipes.utils.common import ( + _check_unpickable_fn, + StreamWrapper, + validate_input_col +) + + +__all__ = ["FilterIterDataPipe", ] + +T = TypeVar('T') +T_co = TypeVar('T_co', covariant=True) + + +@functional_datapipe('filter') +class FilterIterDataPipe(IterDataPipe[T_co]): + r""" + Filters out elements from the source datapipe according to input ``filter_fn`` (functional name: ``filter``). + + Args: + datapipe: Iterable DataPipe being filtered + filter_fn: Customized function mapping an element to a boolean. + input_col: Index or indices of data which ``filter_fn`` is applied, such as: + + - ``None`` as default to apply ``filter_fn`` to the data directly. + - Integer(s) is used for list/tuple. + - Key(s) is used for dict. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> def is_even(n): + ... return n % 2 == 0 + >>> dp = IterableWrapper(range(5)) + >>> filter_dp = dp.filter(filter_fn=is_even) + >>> list(filter_dp) + [0, 2, 4] + """ + + datapipe: IterDataPipe[T_co] + filter_fn: Callable + + def __init__( + self, + datapipe: IterDataPipe[T_co], + filter_fn: Callable, + input_col=None, + ) -> None: + super().__init__() + self.datapipe = datapipe + + _check_unpickable_fn(filter_fn) + self.filter_fn = filter_fn # type: ignore[assignment] + + self.input_col = input_col + validate_input_col(filter_fn, input_col) + + def _apply_filter_fn(self, data) -> bool: + if self.input_col is None: + return self.filter_fn(data) + elif isinstance(self.input_col, (list, tuple)): + args = tuple(data[col] for col in self.input_col) + return self.filter_fn(*args) + else: + return self.filter_fn(data[self.input_col]) + + def __iter__(self) -> Iterator[T_co]: + for data in self.datapipe: + condition, filtered = self._returnIfTrue(data) + if condition: + yield filtered + else: + StreamWrapper.close_streams(data) + + def _returnIfTrue(self, data: T) -> Tuple[bool, T]: + condition = self._apply_filter_fn(data) + + if df_wrapper.is_column(condition): + # We are operating on DataFrames filter here + result = [] + for idx, mask in enumerate(df_wrapper.iterate(condition)): + if mask: + result.append(df_wrapper.get_item(data, idx)) + if len(result): + return True, df_wrapper.concat(result) + else: + return False, None # type: ignore[return-value] + + if not isinstance(condition, bool): + raise ValueError("Boolean output is required for `filter_fn` of FilterIterDataPipe, got", type(condition)) + + return condition, data diff --git a/shared/package-files/d1/d19aebe2435c4e84bf7ae65533d23a9d440f98162e5b4d69c73f783e02299ec8/blob b/shared/package-files/d1/d19aebe2435c4e84bf7ae65533d23a9d440f98162e5b4d69c73f783e02299ec8/blob new file mode 100644 index 0000000000000000000000000000000000000000..bada0638f8a2224a603f13afff16c0d8e986a591 Binary files /dev/null and b/shared/package-files/d1/d19aebe2435c4e84bf7ae65533d23a9d440f98162e5b4d69c73f783e02299ec8/blob differ diff --git a/shared/package-files/d1/d19b62e56d7e4fb9c150aadbc63d8009e70051b89fd0c8b53fad7aad31c03814/blob b/shared/package-files/d1/d19b62e56d7e4fb9c150aadbc63d8009e70051b89fd0c8b53fad7aad31c03814/blob new file mode 100644 index 0000000000000000000000000000000000000000..a44bb97fa48c6db6501faa7b9f506c81b1d128b9 --- /dev/null +++ b/shared/package-files/d1/d19b62e56d7e4fb9c150aadbc63d8009e70051b89fd0c8b53fad7aad31c03814/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API ::std::tuple fbgemm_linear_quantize_weight(const at::Tensor & input); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/d1/d19ba2751dadd81da20f31b87be5eb64edd6bebde9add5a4eed0d8330936f089/blob b/shared/package-files/d1/d19ba2751dadd81da20f31b87be5eb64edd6bebde9add5a4eed0d8330936f089/blob new file mode 100644 index 0000000000000000000000000000000000000000..f054efe6cbee267811c237876d0b7c223ceeac87 --- /dev/null +++ b/shared/package-files/d1/d19ba2751dadd81da20f31b87be5eb64edd6bebde9add5a4eed0d8330936f089/blob @@ -0,0 +1,207 @@ +"""Compatibility tools for various data structure inputs""" + +from statsmodels.compat.numpy import NP_LT_2 +from statsmodels.compat.pandas import infer_freq + +import numpy as np +import pandas as pd + +try: + import polars as pl + _POLARS_TYPES = (pl.DataFrame, pl.Series) +except ImportError: + _POLARS_TYPES = () + + +def _check_period_index(x, freq="M"): + from pandas import DatetimeIndex, PeriodIndex + + if not isinstance(x.index, (DatetimeIndex, PeriodIndex)): + raise ValueError("The index must be a DatetimeIndex or PeriodIndex") + + if x.index.freq is not None: + inferred_freq = x.index.freqstr + else: + inferred_freq = infer_freq(x.index) + if isinstance(inferred_freq, pd.tseries.offsets.BaseOffset): + inferred_freq = inferred_freq.freqstr + if not inferred_freq.startswith(freq): + raise ValueError(f"Expected frequency {freq}. Got {inferred_freq}") + + +def is_series(obj): + """Return whether obj is a pandas Series""" + return isinstance(obj, pd.Series) + + +def is_data_frame(obj): + """Return whether obj is a pandas DataFrame""" + return isinstance(obj, pd.DataFrame) + + +def is_design_matrix(obj): + """Return whether obj is a patsy DesignMatrix""" + try: + from patsy import DesignMatrix + except ImportError: + return False + + return isinstance(obj, DesignMatrix) + + +def is_model_matrix(obj): + """Return whether obj is a formulaic ModelMatrix""" + try: + from formulaic import ModelMatrix + except ImportError: + return False + + return isinstance(obj, ModelMatrix) + + +def _is_structured_ndarray(obj): + return isinstance(obj, np.ndarray) and obj.dtype.names is not None + + +def interpret_data(data, colnames=None, rownames=None): + """ + Convert a data structure to the form required by estimation classes + + Parameters + ---------- + data : array_like + Data to convert. + colnames : sequence or None, optional + Column names. May be part of the data structure. + rownames : sequence or None, optional + Row names. May be part of the data structure. + + Returns + ------- + values : ndarray + Converted, homogeneous data values. + colnames : list + Column names. + rownames : sequence or None + Row names, if available. + + """ + if isinstance(data, np.ndarray): + values = np.asarray(data) + + if colnames is None: + colnames = [f"Y_{i:d}" for i in range(values.shape[1])] + elif is_data_frame(data): + # XXX: hack + data = data.dropna() + values = data.values + colnames = data.columns + rownames = data.index + else: # pragma: no cover + raise TypeError( + f"Cannot handle input type {type(data).__name__}" + ) + + if not isinstance(colnames, list): + colnames = list(colnames) + + # sanity check + if len(colnames) != values.shape[1]: + raise ValueError( + "length of colnames does not match number of columns in data" + ) + + if rownames is not None and len(rownames) != len(values): + raise ValueError("length of rownames does not match number of rows in data") + + return values, colnames, rownames + + +def struct_to_ndarray(arr): + """Convert a structured ndarray to a homogeneous ndarray view""" + return arr.view((float, (len(arr.dtype.names),)), type=np.ndarray) + + +def _is_using_ndarray_type(endog, exog): + return type(endog) is np.ndarray and (type(exog) is np.ndarray or exog is None) + + +def _is_using_ndarray(endog, exog): + return isinstance(endog, np.ndarray) and ( + isinstance(exog, np.ndarray) or exog is None + ) + + +def _is_using_ndarray_like(endog, exog): + return hasattr(endog, "__array__") and hasattr(exog, "__array__") + + +def _is_using_pandas(endog, exog): + from statsmodels.compat.pandas import data_klasses as klasses + + return isinstance(endog, klasses) or isinstance(exog, klasses) + + +def _is_using_pandas_like(endog, exog): + return hasattr(endog, "__dataframe__") or hasattr(exog, "__dataframe__") + + +def _is_using_patsy(endog, exog): + # we get this when a structured array is passed through a formula + return is_design_matrix(endog) and (is_design_matrix(exog) or exog is None) + + +def _is_using_formulaic(endog, exog): + # we get this when a structured array is passed through a formula + return is_model_matrix(endog) and (is_model_matrix(exog) or exog is None) + + +def _is_recarray(data): + """Return whether data is a recarray""" + if NP_LT_2: + return isinstance(data, np.core.recarray) + else: + return isinstance(data, np.rec.recarray) + + +def _as_array_with_name(obj, default_name): + """ + Call np.asarray() on obj and attempt to get the name if it is a Series + + Parameters + ---------- + obj : array_like + Array, or pandas Series, to convert to an array. + default_name : str + The default name to return in case the object isn't a Series or has + no name attribute. + + Returns + ------- + array_and_name : tuple (ndarray, str) + The data cast to an ndarray and the series name or None. + + """ + if is_series(obj): + return (np.asarray(obj), obj.name) + return (np.asarray(obj), default_name) + + +def _to_pandas(obj): + """ + Convert a Polars DataFrame/Series to a pandas object via .to_pandas(). + + Parameters + ---------- + obj : array_like + Input object to potentially convert + + Returns + ------- + obj_converted : object + Returns a pandas DataFrame/Series if obj is a Polars DataFrame/Series. + Returns the original object unchanged otherwise. + """ + if _POLARS_TYPES and isinstance(obj, _POLARS_TYPES): + return obj.to_pandas() + return obj diff --git a/shared/package-files/d1/d19d9d3c170a074e2c4ff56b606761e5d6686077a9460416e4691a0368d6b6b6/blob b/shared/package-files/d1/d19d9d3c170a074e2c4ff56b606761e5d6686077a9460416e4691a0368d6b6b6/blob new file mode 100644 index 0000000000000000000000000000000000000000..5f154cc5d201a7efd88491db9d606c5ee4f35668 --- /dev/null +++ b/shared/package-files/d1/d19d9d3c170a074e2c4ff56b606761e5d6686077a9460416e4691a0368d6b6b6/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d19d9d3c170a074e2c4ff56b606761e5d6686077a9460416e4691a0368d6b6b6 +size 138024 diff --git a/shared/package-files/d1/d19ef1b8e9597bdd774d54f81ee6ddf9d121c167f713eacbd8a2e9cdd89fbec2/blob b/shared/package-files/d1/d19ef1b8e9597bdd774d54f81ee6ddf9d121c167f713eacbd8a2e9cdd89fbec2/blob new file mode 100644 index 0000000000000000000000000000000000000000..165a50b2a7f2319cb81538c172d6540aaec77bdf --- /dev/null +++ b/shared/package-files/d1/d19ef1b8e9597bdd774d54f81ee6ddf9d121c167f713eacbd8a2e9cdd89fbec2/blob @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor positive(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/d1/d1a0ed4d9a1da76ba5dab410441bb83f6415a841acdc130d20c6504dfaf11cde/blob b/shared/package-files/d1/d1a0ed4d9a1da76ba5dab410441bb83f6415a841acdc130d20c6504dfaf11cde/blob new file mode 100644 index 0000000000000000000000000000000000000000..69685f15c1bf4599153bfacb31b23654abd3cf75 --- /dev/null +++ b/shared/package-files/d1/d1a0ed4d9a1da76ba5dab410441bb83f6415a841acdc130d20c6504dfaf11cde/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1a0ed4d9a1da76ba5dab410441bb83f6415a841acdc130d20c6504dfaf11cde +size 212652444 diff --git a/shared/package-files/d1/d1a1b643ceb70eb7df61eab7537975a8c582060d867811af89031ce0bda82182/blob b/shared/package-files/d1/d1a1b643ceb70eb7df61eab7537975a8c582060d867811af89031ce0bda82182/blob new file mode 100644 index 0000000000000000000000000000000000000000..c6a2ca4b4ac05d812e360251f6cf3e192681c0ab Binary files /dev/null and b/shared/package-files/d1/d1a1b643ceb70eb7df61eab7537975a8c582060d867811af89031ce0bda82182/blob differ diff --git a/shared/package-files/d1/d1a4cf6dfc6401595b70fdd33747bc3ccff981341e79abe258292115904e5347/blob b/shared/package-files/d1/d1a4cf6dfc6401595b70fdd33747bc3ccff981341e79abe258292115904e5347/blob new file mode 100644 index 0000000000000000000000000000000000000000..bd4a563d9b3cb9feb97c9e85cad4e6d8c1da4e93 --- /dev/null +++ b/shared/package-files/d1/d1a4cf6dfc6401595b70fdd33747bc3ccff981341e79abe258292115904e5347/blob @@ -0,0 +1,33 @@ +[Matthew Rocklin](http://matthewrocklin.com) [@mrocklin](http://github.com/mrocklin/) + +[John Jacobsen](http://eigenhombre.com) [@eigenhombre](http://github.com/eigenhombre/) + +Erik Welch [@eriknw](https://github.com/eriknw/) + +John Crichton [@jcrichton](https://github.com/jcrichton/) + +Han Semaj [@microamp](https://github.com/microamp/) + +[Graeme Coupar](https://twitter.com/obmarg) [@obmarg](https://github.com/obmarg/) + +[Leonid Shvechikov](http://brainstorage.me/shvechikov) [@shvechikov](https://github.com/shvechikov) + +Lars Buitinck [@larsmans](http://github.com/larsmans) + +José Ricardo [@josericardo](https://github.com/josericardo) + +Tom Prince [@tomprince](https://github.com/tomprince) + +Bart van Merriënboer [@bartvm](https://github.com/bartvm) + +Nikolaos-Digenis Karagiannis [@digenis](https://github.com/digenis/) + +[Antonio Lima](https://twitter.com/themiurgo) [@themiurgo](https://github.com/themiurgo/) + +Joe Jevnik [@llllllllll](https://github.com/llllllllll) + +Rory Kirchner [@roryk](https://github.com/roryk) + +[Steven Cutting](http://steven-cutting.github.io) [@steven_cutting](https://github.com/steven-cutting) + +Aric Coady [@coady](https://github.com/coady) diff --git a/shared/package-files/d1/d1a5d265bc37c0041e8b831cae4a28a672b6cd148eb43f43abf4e3b35ef21db9/blob b/shared/package-files/d1/d1a5d265bc37c0041e8b831cae4a28a672b6cd148eb43f43abf4e3b35ef21db9/blob new file mode 100644 index 0000000000000000000000000000000000000000..547d98cee7414dc44598665c4fbe2aad37f2399e --- /dev/null +++ b/shared/package-files/d1/d1a5d265bc37c0041e8b831cae4a28a672b6cd148eb43f43abf4e3b35ef21db9/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API fake_quantize_per_channel_affine_cachemask_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::fake_quantize_per_channel_affine_cachemask_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fake_quantize_per_channel_affine_cachemask_backward(Tensor grad, Tensor mask) -> Tensor") + static at::Tensor call(const at::Tensor & grad, const at::Tensor & mask); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad, const at::Tensor & mask); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/d1/d1a7f7bffc21653bc83229f82ecb0d31f14a5febdf85ec80b8c4fe6fdfbb40dc/blob b/shared/package-files/d1/d1a7f7bffc21653bc83229f82ecb0d31f14a5febdf85ec80b8c4fe6fdfbb40dc/blob new file mode 100644 index 0000000000000000000000000000000000000000..2c2b88722d4d782482646a4e9ae01638886890ab --- /dev/null +++ b/shared/package-files/d1/d1a7f7bffc21653bc83229f82ecb0d31f14a5febdf85ec80b8c4fe6fdfbb40dc/blob @@ -0,0 +1,236 @@ +// This file defines OptionalArrayRef, a class that has almost the same +// exact functionality as c10::optional>, except that its +// converting constructor fixes a dangling pointer issue. +// +// The implicit converting constructor of both c10::optional> and +// std::optional> can cause the underlying ArrayRef to store +// a dangling pointer. OptionalArrayRef prevents this by wrapping +// a c10::optional> and fixing the constructor implementation. +// +// See https://github.com/pytorch/pytorch/issues/63645 for more on this. + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace c10 { + +template +class OptionalArrayRef final { + public: + // Constructors + + constexpr OptionalArrayRef() noexcept = default; + + constexpr OptionalArrayRef(nullopt_t) noexcept {} + + OptionalArrayRef(const OptionalArrayRef& other) = default; + + OptionalArrayRef(OptionalArrayRef&& other) noexcept = default; + + constexpr OptionalArrayRef(const optional>& other) noexcept + : wrapped_opt_array_ref(other) {} + + constexpr OptionalArrayRef(optional>&& other) noexcept + : wrapped_opt_array_ref(std::move(other)) {} + + constexpr OptionalArrayRef(const T& value) noexcept + : wrapped_opt_array_ref(value) {} + + template < + typename U = ArrayRef, + std::enable_if_t< + !std::is_same_v, OptionalArrayRef> && + !std::is_same_v, std::in_place_t> && + std::is_constructible_v, U&&> && + std::is_convertible_v> && + !std::is_convertible_v, + bool> = false> + constexpr OptionalArrayRef(U&& value) noexcept( + std::is_nothrow_constructible_v, U&&>) + : wrapped_opt_array_ref(std::forward(value)) {} + + template < + typename U = ArrayRef, + std::enable_if_t< + !std::is_same_v, OptionalArrayRef> && + !std::is_same_v, std::in_place_t> && + std::is_constructible_v, U&&> && + !std::is_convertible_v>, + bool> = false> + constexpr explicit OptionalArrayRef(U&& value) noexcept( + std::is_nothrow_constructible_v, U&&>) + : wrapped_opt_array_ref(std::forward(value)) {} + + template + constexpr explicit OptionalArrayRef( + std::in_place_t ip, + Args&&... args) noexcept + : wrapped_opt_array_ref(ip, std::forward(args)...) {} + + template + constexpr explicit OptionalArrayRef( + std::in_place_t ip, + std::initializer_list il, + Args&&... args) + : wrapped_opt_array_ref(ip, il, std::forward(args)...) {} + + constexpr OptionalArrayRef(const std::initializer_list& Vec) + : wrapped_opt_array_ref(ArrayRef(Vec)) {} + + // Destructor + + ~OptionalArrayRef() = default; + + // Assignment + + constexpr OptionalArrayRef& operator=(nullopt_t) noexcept { + wrapped_opt_array_ref = c10::nullopt; + return *this; + } + + OptionalArrayRef& operator=(const OptionalArrayRef& other) = default; + + OptionalArrayRef& operator=(OptionalArrayRef&& other) noexcept = default; + + constexpr OptionalArrayRef& operator=( + const optional>& other) noexcept { + wrapped_opt_array_ref = other; + return *this; + } + + constexpr OptionalArrayRef& operator=( + optional>&& other) noexcept { + wrapped_opt_array_ref = std::move(other); + return *this; + } + + template < + typename U = ArrayRef, + typename = std::enable_if_t< + !std::is_same_v, OptionalArrayRef> && + std::is_constructible_v, U&&> && + std::is_assignable_v&, U&&>>> + constexpr OptionalArrayRef& operator=(U&& value) noexcept( + std::is_nothrow_constructible_v, U&&> && + std::is_nothrow_assignable_v&, U&&>) { + wrapped_opt_array_ref = std::forward(value); + return *this; + } + + // Observers + + constexpr ArrayRef* operator->() noexcept { + return &wrapped_opt_array_ref.value(); + } + + constexpr const ArrayRef* operator->() const noexcept { + return &wrapped_opt_array_ref.value(); + } + + constexpr ArrayRef& operator*() & noexcept { + return wrapped_opt_array_ref.value(); + } + + constexpr const ArrayRef& operator*() const& noexcept { + return wrapped_opt_array_ref.value(); + } + + constexpr ArrayRef&& operator*() && noexcept { + return std::move(wrapped_opt_array_ref.value()); + } + + constexpr const ArrayRef&& operator*() const&& noexcept { + return std::move(wrapped_opt_array_ref.value()); + } + + constexpr explicit operator bool() const noexcept { + return wrapped_opt_array_ref.has_value(); + } + + constexpr bool has_value() const noexcept { + return wrapped_opt_array_ref.has_value(); + } + + constexpr ArrayRef& value() & { + return wrapped_opt_array_ref.value(); + } + + constexpr const ArrayRef& value() const& { + return wrapped_opt_array_ref.value(); + } + + constexpr ArrayRef&& value() && { + return std::move(wrapped_opt_array_ref.value()); + } + + constexpr const ArrayRef&& value() const&& { + return std::move(wrapped_opt_array_ref.value()); + } + + template + constexpr std:: + enable_if_t>, ArrayRef> + value_or(U&& default_value) const& { + return wrapped_opt_array_ref.value_or(std::forward(default_value)); + } + + template + constexpr std:: + enable_if_t>, ArrayRef> + value_or(U&& default_value) && { + return wrapped_opt_array_ref.value_or(std::forward(default_value)); + } + + // Modifiers + + constexpr void swap(OptionalArrayRef& other) noexcept { + std::swap(wrapped_opt_array_ref, other.wrapped_opt_array_ref); + } + + constexpr void reset() noexcept { + wrapped_opt_array_ref.reset(); + } + + template + constexpr std:: + enable_if_t, Args&&...>, ArrayRef&> + emplace(Args&&... args) noexcept( + std::is_nothrow_constructible_v, Args&&...>) { + return wrapped_opt_array_ref.emplace(std::forward(args)...); + } + + template + constexpr ArrayRef& emplace( + std::initializer_list il, + Args&&... args) noexcept { + return wrapped_opt_array_ref.emplace(il, std::forward(args)...); + } + + private: + optional> wrapped_opt_array_ref; +}; + +using OptionalIntArrayRef = OptionalArrayRef; + +inline bool operator==( + const OptionalIntArrayRef& a1, + const IntArrayRef& other) { + if (!a1.has_value()) { + return false; + } + return a1.value() == other; +} + +inline bool operator==( + const c10::IntArrayRef& a1, + const c10::OptionalIntArrayRef& a2) { + return a2 == a1; +} + +} // namespace c10 diff --git a/shared/package-files/d1/d1a88463f6a145800425921a7adc94bfc184ee40ed08fbac60ba8d485da65b01/EXPERIMENTS.md b/shared/package-files/d1/d1a88463f6a145800425921a7adc94bfc184ee40ed08fbac60ba8d485da65b01/EXPERIMENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..44a5eed902a57a39f805b075ff402f988e9c2d18 --- /dev/null +++ b/shared/package-files/d1/d1a88463f6a145800425921a7adc94bfc184ee40ed08fbac60ba8d485da65b01/EXPERIMENTS.md @@ -0,0 +1,130 @@ +# Experiments + +All models initialize from random weights. Train labels are used for fitting; validation labels only for selection and error analysis. No test data or pretrained assets are available. Hardware: one H100 80 GB, 22 CPU allocation. Primary reported metrics are validation retrieval rates, not estimates of the external reference's test improvement. + +## E000 — starter plumbing smoke +- Hypothesis: the supplied train/publish/relocate/replay path works. +- Seed 0; one epoch; deterministic 4,096 train / 512 validation-loss rows. +- Retrieval: deterministic 128-spectrum sample, seed 0; query JSONL SHA256 `9fe86c73720456e94f6e454516b3f1768e289413f89b185df2dff3fa8f23f75a`. +- Checkpoint SHA256 `e1a27fbe5db99c9868650e830c65dc53ce420a4ab1362d7a166d833e5ae0c8f4`. +- Compute: training 10.358 s (one H100 allocated), relocated inference 18.373 s; no scientific benchmark claim from this subset. +- Metrics: `{"hit_rate_at_1": 0.0, "hit_rate_at_20": 0.0546875, "hit_rate_at_5": 0.015625, "mces_at_1": 30.61328125}`. All 128 rankings valid. +- Deliberately truncated ranking correctly invalidated with `ranking is not an exact candidate permutation`. +- Initial timing invocation failed because /usr/bin/time is unavailable; replaced with Python monotonic timing. Initial MCES invocation failed in GLACIER Python; evaluation uses the supplied system Python with myopic_mces. Neither failure changed fitting or inference. +- Selection: validation cosine loss for commissioning only. + +## E001 — all-condition inverse spectrum encoder +- Hypothesis: explicit fragment and neutral-loss bins retain more discriminating spectrum information than DeepSets mean pooling and provide a useful all-condition fallback. +- Changed factor: residual binned-spectrum architecture; 0.1 Da bins through 1500 Da, up to 128 peaks; Morgan4096 radius 2; cosine plus weighted BCE loss. Metadata uses precursor, adduct, instrument and observed/missing energy, never true formula. +- Seed 1; complete 194,119 training spectra; 50 epochs scheduled; one H100; AdamW, batch 512, width 1024, three residual blocks. +- Selection: full 19,429-query validation retrieval Hit@1 each epoch. Query JSONL SHA256 `7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6`. +- No validation parameters fitted; candidate fingerprints are derived only from supplied structures. +- Completed 50 epochs in 160.517 s on one H100; max allocated GPU memory 5.631 GB. Selected epoch 2; Hit@1 0.09511555, Hit@5 0.21622317, Hit@20 0.39348397. Independent full replay: Hit@1 0.09393175, Hit@5 0.21606876, Hit@20 0.39389572; 19,429 complete rankings in 49.663 s. MCES running. +- Checkpoint SHA256 `bce84afa449b4952efaddd558af4c5439e8170976cbe56143a57abf98540f608`. Negative result: continued fitting overfit; final epoch Hit@1 0.08749807. Keep epoch 2. The initially logged retrieval used input-order tie resolution; replay uses candidate-ID ties. All 23 top-one discrepancies were identical-fingerprint ties. Validation cache now uses candidate-ID ties too; repeated evaluation exactly matches replay. No fitting or checkpoint change. Replay 95% molecule bootstrap interval: [0.08021314, 0.10881266], 3,185 molecule groups, 2,000 resamples. Paired smoke subset gain versus E000: +0.0703125; same 117 molecule groups. +- Packaging adapter initially imported the starter predict module because of sys.path precedence; fixed before any live publication. A premature replay invocation failed while the candidate package was not yet built; the complete replay subsequently passed. + + + +## E002 — clean synthetic augmentation +- Hypothesis: 435,076 synthetic molecular structures increase chemical coverage and reduce the severe train/validation generalization gap in E001. +- Changed factor: add only the supplied 2,333,485 sanitized ICEBERG simulations. Same formula-free input features; synthetic precursor masses derived from train-only simulation formula metadata. No simulated validation structures or pretrained assets. +- Seed 1; same architecture/loss as E001, random initialization; 40 epochs × 1,200 steps, batch 512, 25% experimental train / 75% clean synthetic sampling. Eight null/empty simulation spectra are excluded from fitting, leaving 2,333,477 usable rows. Initial preparation stopped on an empty payload; resumed from 1,283,584 complete rows, finished remaining rows in 44.062 s. Failed log and prior source retained. Full-validation selection uses fixed candidate-ID ties. Completed 40 epochs in 292.360 s on the one H100; max allocated CUDA memory 12.316 GB. Selected epoch 40, checkpoint SHA256 `bc0f0251108bb6c602c0ea44de892719c6b0d29c69ef26854911726c57c0faf2`. Independent replay: all 19,429 rankings valid in 86.279 s; Hit@1 0.2329507437, Hit@5 0.3749034948, Hit@20 0.5380101910. Replay exactly matches selection. Same full-validation query hash as E001. Paired molecule-bootstrap improvement over E001 +0.13901899 (95% CI [0.12379366,0.15556200], 3,185 molecule groups, 2,000 resamples). MCES running. +- Error analysis: H+ Hit@1 0.2745712 versus Na+ 0.1038632; missing energy 0.1650095; released GLACIER conditions 0.3017259 versus remaining conditions 0.1638989. Missing-condition and sodium transfer remain weak. + + +## E003 — GLACIER all-condition training (preparing) +- Hypothesis: the native forward model can learn spectra outside the published condition domain using explicit missing-energy and unknown-instrument embeddings already present in native code. +- Changed factor: broaden fragment-supervised fitting to all conditions. Preserve existing prepared targets, derive additional MAGMa targets only from corresponding training/validation structures and spectra. Engine reuse per SMILES reduces preparation time without using information across folds. Native architecture kept intact. +- The first 100-molecule/209-spectrum preparation smoke revealed missing sibling fragments when compared against native preparation. Invalidated those 209 derived rows, added native sibling expansion, and verified all 10 selected cases exactly (root canonical SMILES, raw target spectrum, fragment-mask set). Full preparation now running on 17,050 additional molecular groups / 104,473 spectra, retaining supplied targets unchanged. + +## E004 — fine-mass peak transformer +- Hypothesis: shared peak attention and fine mass-defect features reduce the information loss of 0.1 Da bins and improve unseen-structure retrieval. +- Changed factor: spectrum architecture/representation; same seed 1, same train+clean-synthetic mixture and loss as E002. Four transformer layers, width 384, 64 strongest peaks, 0.1 Da learned embeddings plus exact-mass sine/cosine features, precursor/condition token. 12,836,736 parameters. +- Full train fold, 40 epochs × 1,200 steps, batch 512; 25% experimental/75% synthetic. Exact original source/config/logs in E004. Retrieval uses the same full validation query set and candidate-ID ties. Completed in 1120.843 s on the sole H100, maximum allocated CUDA memory10.957 GB. Selected epoch37, checkpoint SHA256 `1d1d4418b4e305306996953e54426a15cd35f0b767c989840c91ec0880818193`; ordinary-cosine validation Hit@1 .30207421895, Hit@5 .47269545525, Hit@20 .63482423182. Final epoch40 was lower (.29996397138), so retained epoch37. Independent replay will use the stronger E008 ranking of these same trained weights. + +## Evaluation engineering notes +- E001 full MCES initially spent 671.031 s in a serial-result pool and was restarted to add an exact identical-graph shortcut and a persistent completed-pair cache. Official MCES threshold=15, stronger bound and CBC solver options are unchanged. The zero shortcut only recognizes the same atom/bond graph (stereochemistry is ignored by the supplied MCES graph definition). +- Cached MCES jobs were restarted once more after changing SQLite transactions to commit each completed pair, avoiding write locks across long solves. Diagnostic compute is CPU-only; full secondary metrics remain pending until every pair completes. + +## E005 — sodium mass-coordinate normalization (prepared) +- Hypothesis: shifting Na+ fragment and precursor masses by -21.981944235 Da to proton-equivalent coordinates shares fragmentation features with the much larger H+ training population. Neutral losses and the observed adduct indicator remain unchanged. +- Changed factor: mass-coordinate preprocessing only, compared with E002. Planned same random seed 1, MLP architecture, training mixture, loss, epochs and steps. All training structures remain in the train/clean-synthetic folds. Preparation took 14.136 s; corrected synthetic fractional-precursor feature to preserve original H+ rows exactly. No synthetic positive peak falls below the normalization shift. Candidate IDs never affect the learned score. +- Completed40 epochs in 306.592s; maxCUDA12.316GB. Selected epoch31 SHA256 `cfa96e4e60bee9ab19dc8acae446f08c7d5ddbd114ba999ad1eb58bcb3c2cca7`; Hit@1 0.230068454, Hit@5 0.368727160, Hit@20 0.527407484. Negative result versus E002: overall delta-.00288229 (95% molecule-CI[-.01317966,.00657117]); sodium delta-.01393287 (CI[-.03895166,.01135473]); proton delta+.00068064 (CI[-.00860138,.00998709]). Did not publish. Separately checked40train+40validation records: normalized preprocessing exactly matches runtime features. + +Further engineering: E002 passed new-input contract probes including arbitrary IDs, unseen structures, singleton pools, out-of-window peaks, missing/novel instrument labels, and candidate-order invariance. E003 preparation resumed with ten CPU workers after 787.907 s; committed targets retained. Batch-32/accumulation-1 native training will scale MAGMa schedule intervals from 2500 to625 microbatches to preserve the original schedule per observed spectrum; optimizer warmup remains2000 steps. + +## E006 — fixed fingerprint score comparison +- Hypothesis: common Morgan bits dominate ordinary cosine; weighting by their training-fold information content improves discrimination without retraining the spectrum encoder. +- Changed factor: fixed ranking function only, using the completed E002 checkpoint. Compared eight prespecified rules: cosine, soft Tanimoto, BCE likelihood, size-normalized BCE, cosine with sqrt-IDF, cosine with IDF, square-root-size-normalized dot, and mean dot. No validation fitting; IDF uses only 25,046 experimental train SMILES fingerprints. +- Selected IDF-weighted cosine: Hit@1 0.2459725153, Hit@5 0.3981162180, Hit@20 0.5622008338 on the same full validation query hash. Paired molecule-bootstrap gain over E002 +0.01302177 (95% CI [0.00855167,0.01742674], 3,185 groups). Eight-rule comparison took 8.841 s on the sole H100, overlapping E004 training briefly. +- Negative comparisons: BCE Hit@1 0.20433373; normalized BCE 0.22358330; mean dot 0.20505430. Tanimoto 0.23310515; sqrt-IDF cosine 0.24226671; dot/sqrt(size) equals cosine ranking 0.23295074. All results/source retained. Derived checkpoint SHA256 `c20a89ff4ee9c6ec69b593b48971e15a233c8f0382ad5d828700568b550583c7`; full independent replay passed all 19,429 queries in 115.219 s and exactly matched all three hit rates. MCES pending. + +## E007 — training-only hard-negative contrastive fine-tuning (prepared) +- Hypothesis: fingerprint regression ignores which similar-mass candidates must be separated; listwise training against training-only molecular negatives improves retrieval. +- Changed factor: add multi-positive near-mass InfoNCE to the fingerprint loss, initialized from the task-trained E004 checkpoint after its run completes. No external initialization assets. +- Negative pools derive solely from 25,046 experimental train and 435,076 sanitized synthetic molecular structures. Neutral masses use their training formula metadata. A ±0.01 Da neighborhood is widened to at least 32 molecules; identical fingerprint negatives are treated as positives to avoid contradictory supervision. Pool preparation 14.511 s. +- Planned fixed settings: 32 negatives, temperature 0.05, contrastive loss weight0.2, learning rate1e-4,20epochs×1200steps; same experimental/synthetic mixture. Validation only selects checkpoints; no validation candidate is used as a training negative. Training pending. + +## E008 — transformer with training-IDF fingerprint ranking +- Hypothesis/change: apply the fixed training-IDF weighting from E006 to E004 outputs. Network parameters are unchanged; weights derive only from train fingerprints. Same eight predefined fixed rules evaluated in4.108 s; full comparison retained. +- Selected weighted-cosine validation Hit@1 .31988264965, Hit@5 .49997426527, Hit@20 .67131607391. Source checkpoint E004 epoch37; derived checkpoint SHA256 `c611ede98e88041dafc82cfb71182dcb34f4ac4d93e91603557d0438e859036d`. Full replay passed all19,429 queries in98.440s and exactly matched all hit rates. Paired gain over E006 +.07391013,95% molecule-CI[.05529783,.09264636]. Proton Hit@1 .3674789, sodium .1722609; released GLACIER domain .4087734, remaining conditions .2306343. MCES pending. Exact selected fitting source, configuration, metrics and logs are copied into E008/research lineage; no external pretrained assets. + +## E009 — ten-peak transformer (planned from training-source analysis) +- Hypothesis: retaining many diffuse simulated peaks creates a source mismatch and distracts the encoder; limit both experimental and simulated inputs to the ten strongest peaks. +- Training-only analysis: deterministic seed1 samples of100,000 spectra per source show top10 retains89.963% of experimental raw intensity versus40.715% of synthetic intensity; mean retained peak counts33.50 versus58.35 (cap128). The ten-peak setting also matches the supplied MIST reproduction recipe. +- Changed factor versus E004: maximum peak tokens64→10, with the same width384/depth4, seed1, loss, mixture, steps, epochs and cosine checkpoint selection. Check fixed IDF ranking afterward using the already established scoring family. Training pending native smoke and single-GPU availability. + +## E010 — precursor mass likelihood (training-only calibration, prepared) +- Hypothesis: accurate observed precursor mass separates different formulae within mass-based candidate pools, complementing learned fingerprints. No true query formula is used. +- Fit only experimental-train residuals between observed precursor and RDKit exact target mass plus the public adduct. Robust Cauchy offsets/scales are median/MAD per adduct/instrument, scale floor0.1ppm; unknown instruments fall back to adduct-specific training calibration. Train audit8.290s: median absolute error0.229ppm overall, proton0.153ppm, sodium2.896ppm. +- Predefined score family: E008 IDF cosine plus mass log-likelihood with coefficient in [0,.005,.01,.02,.05]. Validation selects one fixed rule; no query fitting. Candidate mass caching uses only candidate SMILES and is a development convenience; runtime computes these from supplied structures. Results pending. + +E003 pipeline smoke completed: native full-size architecture trained128 optimizer steps, seed1, provided original training supervision, batch32/accumulation1. Wall114.478s, peakCUDA5.589GB; steady steps25–125 took26.477s. This is only a pipeline/timing probe, not baseline confirmation or scientific model selection. Ten deterministic validation strata queries replayed successfully in76.540s from /tmp; every supported candidate had a prediction, including sodium and missing CE/instrument. Hit@1=.3 on this tiny nonrepresentative probe, not a full-validation result. Full all-condition preparation remains running. For the next throughput probe, enable TF32 high matmul precision and examine larger batches before committing the full run. + +E009 training started from scratch with40epochs×1200steps, batch512, seed1, max10peaks; all other E004 settings retained. + +E010 internal full-validation result: coefficient.05 selected Hit@1 .373256472284, Hit@5 .558855319368, Hit@20 .722167893355. Coefficient.02 yields .368881568789/.563899325750/.731020639251; primary Hit@1 governs selection. Paired gain over E008 +.05337382,95% molecule-CI[.04342458,.06387135]. Proton Hit@1 .43615573 (gain+.06867683); sodium .17817184 (gain+.00591091, CI includeszero). Five-rule evaluation10.078s on soleH100, briefly overlapping E009. Candidate mass preparation84.728s on2CPUs, uses only candidate SMILES. Derived checkpoint SHA256 `72e3da9cc1bb57846e15932f057cf43d63fc1f3b9ea40c74bf69a9c70d9cba13`; validation query hash `7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6`. Relocated independent replay started; not yet published. + +E003 throughput preparation: added an explicit training matmul-precision setting (high enables TF32), configurable native learning-rate decay interval, and a bounded per-worker graph-feature cache. The cache holds only deterministic molecular graph features with one-hot edge tensors packed as uint8; targets remain spectrum-specific. Exact collated tensor comparison passed64 deterministic seed1 training examples, testing misses and repeated hits, in3.390s. Batch128 schedule preserves sample counts with LRwarmup500/decay1250 and MAGMa156/156 (rounded from156.25); peak LR unchanged. Larger-batch probe pending GPU availability. + +## E011 — equal-weight peak-encoder ensemble (planned) +- Hypothesis: ten-peak and64-peak encoders make complementary errors; a fixed equal-weight ensemble improves retrieval. +- After E009 completes, compare two predefined rules using E004 and E009: arithmetic mean of fingerprint probabilities, or arithmetic mean of training-IDF cosine scores. Both use E010's already-selected train-calibrated mass score with coefficient.05. No parameter fitting or labels at inference; select on full validation Hit@1, report molecule-bootstrap uncertainty. + +E010 independent relocated full replay PASSED:19,429/19,429 valid rankings, no global error,113.689s (overlapped E009 training and CPU research jobs). All three hit rates exactly match internal evaluation. New-input probes passed in11.634s: arbitrary IDs/new structures, singleton pools, missing/novel instruments, out-of-range peaks, candidate-order invariance, no package mutation. Published as the new selected package after these checks; MCES remains pending. + +## E013 — condition-aware precursor calibration (prepared) +- E010 validation error analysis: released-domain Hit@1 rose to.53133, but remaining conditions fell to.21454 fromE008's.23063; proton/missing-CE Hit@1 is.24929. Hypothesis: metadata completeness marks different precursor-error distributions, and pooled calibration overtrusts missing-CE precursor masses. +- Changed factor: fit train-only median/MAD calibration separately by adduct, instrument, and whether collision energy is present. Groups smaller than64 train rows fall back to adduct/CE, then adduct. Retain E010 coefficient.05, E004 network and training-IDF weights. No validation fitting. Calibration/evaluation pending. + +E009 COMPLETE:574.627s on oneH100 (brief scoring/replay overlaps logged), peakCUDA9.256GB. Epoch37 selected by raw cosine retrieval; Hit@1 .333676463019, Hit@5 .501878635030, Hit@20 .661639816769. Raw checkpoint SHA256 `6960d7591a47579956d77ae2fed7257680d8fd6b0602bcda03865abdce412c0e`. Paired raw-score gain vs64peak E004 0.03160224406814555,95% molecule-CI[0.018987894860506185,0.04320836517468455]. Final weighted/mass and ensemble evaluation pending. + +E013 full-validation internal result .382520973802/.575531422101/.736167584539 (Hit@1/5/20), versus E010 .37325647/.55885532/.72216789. Paired Hit@1 gain+.00926450,95% molecule-CI[.00652667,.01220483]. Train audit confirms proton precursor MAD.0401ppm with knownCE versus1.2050ppm with missingCE; calibration remains train-only. Evaluation12.819s, briefly overlapping E009. Derived checkpoint SHA256 `9c3570d912486378c6e4fea28f967da1c49b9369b1dd52e364801e9a07218dac`; same full validation query hash. Independent replay pending. + +E011 COMPLETE internal evaluation: ten-peak IDF-only .35374955; ten-peak plus fixed E010mass .39744712/.57079623/.73277060. Equal-probability ensemble .424725925163/.596788306140/.750939317515; equal-cosine ensemble .42060837/.59287663/.74754233. Select equal probabilities by Hit@1. Evaluation36.783s; a redundant NPZ-index read inside the mass loop was fixed afterward without changing scores. Source before/after preserved. E012 names the ten-peak+mass ablation. + +## E014 — combine selected equal-probability ensemble and condition-aware mass calibration +- Combine independently promising E011 encoder ensemble with E013 train-calibrated precursor likelihood. Same coefficient.05 and equal encoder weights; no new fitted parameter or validation weight search. Compare both prior ensemble rules and single-encoder controls for a complete ablation. Independent replay will target the strongest full-validation candidate. + +E014 internal full-validation result: equal-probability ensemble .432446343095/.611971794740/.765299294868; equal-cosine .42971846/.61053065/.76313758. Single ten-peak conditioned control .40537341/.58721499/.74630707;64-peak exactly reproduces E013 .38252097. Evaluation5.231s after caching the NPZ indices, during native probe startup. Paired gain vs publishedE010+.05918987,95% molecule-CI[.05121523,.06739473]; vs E011+.00772042,CI[.00518289,.01035210]; vs single ten-peak conditioned+.02707293,CI[.01861828,.03595447]. Checkpoint SHA256 `33f307d4f57bc0df4b2e5a3080cd5efa60e7c5e3e28648eda492a2f4b7a0709c`. E013/E012 are retained ablations; strongest E014 proceeds to independent replay. + +E003 larger-batch probe INTERRUPTED for diagnosis after248.421s: CSV stopped after step30; parent CPU remained active while GPU was idle for over two minutes. Peak observed GPU reserved memory28.45GB, no OOM reported. This is a failed throughput probe, not a scored scientific model. Exact source/config/logs retained in smoke-b128; a seed1 batch128 reproduction with periodic Python stack dumps and checkpoints every16steps is running. No affected model was published. + +E014 independent relocated replay PASSED:19,429/19,429 valid rankings, exact agreement with all internal hit rates,118.138s, peak summed process RSS9,148,887,040bytes. Unseen-input/candidate-order/package-mutation probes passed13.545s. Published as selected package. MCES pending; validation is not directly comparable to the external test score. + +E003 full fragment preparation COMPLETE:189,031/194,119 train spectra and18,170/19,429 validation spectra annotated;6,347 total no-fragment exclusions affect only fitting/loss validation, never retrieval denominator. Resumed phase2414.156s plus recorded prior787.907s=3202.062s, excluding earlier invalidated smoke. Manifest and source digests preserved. Batch128 debug repetition completed40steps in134.157s, peakCUDA25.757GB; prior stall did not reproduce. Stack dumps identify substantial worker-startup/loading time but do not establish the original stall cause. Added compact worker metadata and retained periodic checkpoints. +Native source audit found a separate signed-bit bug: packed boundary atom63 was erased by a >0 test on signed int64. Changed to !=0; direct tests at32,64,65,100atoms now recover every expected boundary. This changes training fragment supervision for large molecules and is recorded as an additional E003 factor. No previous inverse/ensemble model is affected. +Full native training will start from random seed1 with all189,031 training spectra, batch128,6loader workers, TF32 high precision, sample-scaled LR/MAGMa schedules; first stage4000optimizersteps, retain milestones every2000. A fixed hash-selected4096 validation spectra monitors loss; checkpoint/model publication to root requires validation retrieval metrics. Current root remains independently verified E014 during native fitting. + +## E015 — native forward reranking of ensemble shortlists (implementation/pipeline phase) +- Hypothesis: the native simulator can resolve ambiguous top candidates while E014 limits candidate-simulation cost. Use the top20 ensemble candidates per query; union candidates sharing the same public pool/condition to reuse simulations. Rank only each query's own shortlist, then append its remaining ensemble order. +- Compare fixed reciprocal-rank fusion with native weights[0,.25,.5,.75,1] and offset10; no query-specific fit. Unsupported candidates retain their ensemble rank as neutral native evidence; unsupported observations keep the ensemble ranking. Shortlist unit checks pass complete permutations, union deduplication, order invariance, exact zero-weight identity, and own-shortlist-only reranking. A pipeline smoke uses the prior40-step native probe; scientific evaluation awaits native training milestones. + +## E016 — training-only mixture model for precursor errors (fitting) +- Hypothesis: precursor errors combine very precise and noisy sources within each metadata group, which one Cauchy scale cannot capture. +- Replace E014's single Cauchy density with a mixture of fixed Cauchy scales[.003,.01,.03,.1,.3,1,3,10,30,100,1000]ppm. Fit only mixture weights by100 deterministic EM iterations on experimental-train residuals, with one pseudo-observation/component; offsets are training medians. Keep E014 encoder ensemble, equal member weights, coefficient.05 and metadata grouping unchanged. No validation coefficient search. Results pending. + +E015 pipeline replay PASSED after relocation:10/10 complete valid rankings acrossadduct/energy/instrumentstrata,62.081s. Native smoke weights only, so tiny Hit@1 .4/Hit@5 .7/Hit@20 .9 is not scientific selection. Full-validation top20 staging needs217,475 candidate-condition simulations for19,429queries,about91.7% fewer than256candidates across10,192conditions; stage51.069s. A fixed1024query uniform sample(seed0,query hash`84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e`) has17,656 simulations; stage8.146s. This sample is for checkpoint screening, with full validation required before root publication. +E016 fitting16.348s CPU, evaluation11.969s on soleH100 overlapping native training. Fixed mean-probability ensemble Hit@1 .433475732153,Hit@5 .612074733646,Hit@20 .765299294868. Gain over E014+.00102939,95% molecule-CI[-.00031004,.00243175]:54 queries gained,34lost; the small gain is statistically uncertain. Derived checkpointSHA256 `51461bd376a5e4faeef4b57286af5a7d8739b36dbf9115f1d1ca36adcb3eb719`. Independent relocated replay returned successfully in101.208s,peak summed RSS9,139,843,072bytes; score/probe checks pending. + +E016 final independent checks PASSED: 19,429/19,429 valid rankings, all hit rates exactly reproduced; unseen-query and candidate-order probes passed in14.670s with package unchanged. Exact paired MCES@1 delta versus E014 is−.01636729 (lower is better),95% molecule-CI[−.09724679,.07164605]; unchanged predictions cancel,450changed queries,90new molecular pairs,20.982s/2CPU workers. Both Hit@1 and MCES changes are statistically uncertain. Select E016 by its higher primary validation point estimate; E014 remains the fixed E015 checkpoint-screening control. Full absolute MCES remains pending. Root publication includes the selected fitting source, all encoder lineage/config/logs and these checks. diff --git a/shared/package-files/d1/d1aeb555ff69a0ba0076dbbc4841537fbaba6d772b8e04ae3aff9b915202f017/blob b/shared/package-files/d1/d1aeb555ff69a0ba0076dbbc4841537fbaba6d772b8e04ae3aff9b915202f017/blob new file mode 100644 index 0000000000000000000000000000000000000000..c941666ee86a76098a98748a811e508da65a17d3 --- /dev/null +++ b/shared/package-files/d1/d1aeb555ff69a0ba0076dbbc4841537fbaba6d772b8e04ae3aff9b915202f017/blob @@ -0,0 +1,18 @@ +Metadata-Version: 2.1 +Name: anaconda-anon-usage +Version: 0.4.4 +Summary: basic anonymous telemetry for conda +Home-page: https://github.com/Anaconda-Platform/anaconda-anon-usage +Author: Michael C. Grant +Author-email: mgrant@anaconda.com +License: BSD +Keywords: anaconda-anon-usage +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +License-File: LICENSE +Requires-Dist: conda + diff --git a/shared/package-files/d1/d1b0fed0bea51b3faf08d8634034c7388be7148f9b807460b7d185706db8416f/blob b/shared/package-files/d1/d1b0fed0bea51b3faf08d8634034c7388be7148f9b807460b7d185706db8416f/blob new file mode 100644 index 0000000000000000000000000000000000000000..d6be730ae1e4a93d801b11d4ff1a1e6b7b956e76 --- /dev/null +++ b/shared/package-files/d1/d1b0fed0bea51b3faf08d8634034c7388be7148f9b807460b7d185706db8416f/blob @@ -0,0 +1,77 @@ +namespace eval ::tk { + ::msgcat::mcset cs "&Abort" "&P\u0159eru\u0161it" + ::msgcat::mcset cs "&About..." "&O programu..." + ::msgcat::mcset cs "All Files" "V\u0161echny soubory" + ::msgcat::mcset cs "Application Error" "Chyba programu" + ::msgcat::mcset cs "Bold Italic" + ::msgcat::mcset cs "&Blue" "&Modr\341" + ::msgcat::mcset cs "Cancel" "Zru\u0161it" + ::msgcat::mcset cs "&Cancel" "&Zru\u0161it" + ::msgcat::mcset cs "Cannot change to the directory \"%1\$s\".\nPermission denied." "Nemohu zm\u011bnit atku\341ln\355 adres\341\u0159 na \"%1\$s\".\nP\u0159\355stup odm\355tnut." + ::msgcat::mcset cs "Choose Directory" "V\375b\u011br adres\341\u0159e" + ::msgcat::mcset cs "Cl&ear" "Sma&zat" + ::msgcat::mcset cs "&Clear Console" "&Smazat konzolu" + ::msgcat::mcset cs "Color" "Barva" + ::msgcat::mcset cs "Console" "Konzole" + ::msgcat::mcset cs "&Copy" "&Kop\355rovat" + ::msgcat::mcset cs "Cu&t" "V&y\u0159\355znout" + ::msgcat::mcset cs "&Delete" "&Smazat" + ::msgcat::mcset cs "Details >>" "Detaily >>" + ::msgcat::mcset cs "Directory \"%1\$s\" does not exist." "Adres\341\u0159 \"%1\$s\" neexistuje." + ::msgcat::mcset cs "&Directory:" "&Adres\341\u0159:" + ::msgcat::mcset cs "&Edit" "&\332pravy" + ::msgcat::mcset cs "Error: %1\$s" "Chyba: %1\$s" + ::msgcat::mcset cs "E&xit" "&Konec" + ::msgcat::mcset cs "&File" "&Soubor" + ::msgcat::mcset cs "File \"%1\$s\" already exists.\nDo you want to overwrite it?" "Soubor \"%1\$s\" ji\u017e existuje.\nChcete jej p\u0159epsat?" + ::msgcat::mcset cs "File \"%1\$s\" already exists.\n\n" "Soubor \"%1\$s\" ji\u017e existuje.\n\n" + ::msgcat::mcset cs "File \"%1\$s\" does not exist." "Soubor \"%1\$s\" neexistuje." + ::msgcat::mcset cs "File &name:" "&Jm\351no souboru:" + ::msgcat::mcset cs "File &names:" "&Jm\351na soubor\u016f:" + ::msgcat::mcset cs "Files of &type:" "&Typy soubor\u016f:" + ::msgcat::mcset cs "Fi&les:" "Sou&bory:" + ::msgcat::mcset cs "&Filter" "&Filtr" + ::msgcat::mcset cs "Fil&ter:" "Fil&tr:" + ::msgcat::mcset cs "Font st&yle:" + ::msgcat::mcset cs "&Green" "Ze&len\341" + ::msgcat::mcset cs "&Help" "&N\341pov\u011bda" + ::msgcat::mcset cs "Hi" "Ahoj" + ::msgcat::mcset cs "&Hide Console" "&Schovat Konzolu" + ::msgcat::mcset cs "&Ignore" "&Ignorovat" + ::msgcat::mcset cs "Invalid file name \"%1\$s\"." "\u0160patn\351 jm\351no souboru \"%1\$s\"." + ::msgcat::mcset cs "Log Files" "Log soubory" + ::msgcat::mcset cs "&No" "&Ne" + ::msgcat::mcset cs "&OK" + ::msgcat::mcset cs "OK" + ::msgcat::mcset cs "Ok" + ::msgcat::mcset cs "Open" "Otev\u0159\355t" + ::msgcat::mcset cs "&Open" "&Otev\u0159\355t" + ::msgcat::mcset cs "Open Multiple Files" "Otev\u0159\355t v\355ce soubor\u016f" + ::msgcat::mcset cs "P&aste" "&Vlo\u017eit" + ::msgcat::mcset cs "&Quit" "&Ukon\u010dit" + ::msgcat::mcset cs "&Red" "\u010ce&rven\341" + ::msgcat::mcset cs "Replace existing file?" "Nahradit st\341vaj\355c\355 soubor?" + ::msgcat::mcset cs "&Retry" "Z&novu" + ::msgcat::mcset cs "&Save" "&Ulo\u017eit" + ::msgcat::mcset cs "Save As" "Ulo\u017eit jako" + ::msgcat::mcset cs "Save To Log" "Ulo\u017eit do logu" + ::msgcat::mcset cs "Select Log File" "Vybrat log soubor" + ::msgcat::mcset cs "Select a file to source" "Vybrat soubor k nahr\341n\355" + ::msgcat::mcset cs "&Selection:" "&V\375b\u011br:" + ::msgcat::mcset cs "Skip Messages" "P\u0159esko\u010dit zpr\341vy" + ::msgcat::mcset cs "&Source..." "&Zdroj..." + ::msgcat::mcset cs "Tcl Scripts" "Tcl skripty" + ::msgcat::mcset cs "Tcl for Windows" "Tcl pro Windows" + ::msgcat::mcset cs "Text Files" "Textov\351 soubory" + ::msgcat::mcset cs "abort" "p\u0159eru\u0161it" + ::msgcat::mcset cs "blue" "modr\341" + ::msgcat::mcset cs "cancel" "zru\u0161it" + ::msgcat::mcset cs "extension" "p\u0159\355pona" + ::msgcat::mcset cs "extensions" "p\u0159\355pony" + ::msgcat::mcset cs "green" "zelen\341" + ::msgcat::mcset cs "ignore" "ignorovat" + ::msgcat::mcset cs "ok" + ::msgcat::mcset cs "red" "\u010derven\341" + ::msgcat::mcset cs "retry" "znovu" + ::msgcat::mcset cs "yes" "ano" +} diff --git a/shared/package-files/d1/d1b1dcca4628f61ea152a0fa6820175f613bc3d6e92b739d013281db486e625d/blob b/shared/package-files/d1/d1b1dcca4628f61ea152a0fa6820175f613bc3d6e92b739d013281db486e625d/blob new file mode 100644 index 0000000000000000000000000000000000000000..a099d90036028ddee2782e505b728c3a7aea7a12 --- /dev/null +++ b/shared/package-files/d1/d1b1dcca4628f61ea152a0fa6820175f613bc3d6e92b739d013281db486e625d/blob @@ -0,0 +1,175 @@ +# dialog.tcl -- +# +# This file defines the procedure tk_dialog, which creates a dialog +# box containing a bitmap, a message, and one or more buttons. +# +# Copyright (c) 1992-1993 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +# +# ::tk_dialog: +# +# This procedure displays a dialog box, waits for a button in the dialog +# to be invoked, then returns the index of the selected button. If the +# dialog somehow gets destroyed, -1 is returned. +# +# Arguments: +# w - Window to use for dialog top-level. +# title - Title to display in dialog's decorative frame. +# text - Message to display in dialog. +# bitmap - Bitmap to display in dialog (empty string means none). +# default - Index of button that is to display the default ring +# (-1 means none). +# args - One or more strings to display in buttons across the +# bottom of the dialog box. + +proc ::tk_dialog {w title text bitmap default args} { + variable ::tk::Priv + + # Check that $default was properly given + if {[string is integer -strict $default]} { + if {$default >= [llength $args]} { + return -code error -errorcode {TK DIALOG BAD_DEFAULT} \ + "default button index greater than number of buttons\ + specified for tk_dialog" + } + } elseif {"" eq $default} { + set default -1 + } else { + set default [lsearch -exact $args $default] + } + + set windowingsystem [tk windowingsystem] + + # 1. Create the top-level window and divide it into top + # and bottom parts. + + destroy $w + toplevel $w -class Dialog + wm title $w $title + wm iconname $w Dialog + wm protocol $w WM_DELETE_WINDOW { } + + # Dialog boxes should be transient with respect to their parent, + # so that they will always stay on top of their parent window. However, + # some window managers will create the window as withdrawn if the parent + # window is withdrawn or iconified. Combined with the grab we put on the + # window, this can hang the entire application. Therefore we only make + # the dialog transient if the parent is viewable. + # + if {[winfo viewable [winfo toplevel [winfo parent $w]]] } { + wm transient $w [winfo toplevel [winfo parent $w]] + } + + if {$windowingsystem eq "aqua"} { + ::tk::unsupported::MacWindowStyle style $w moveableModal {} + } elseif {$windowingsystem eq "x11"} { + wm attributes $w -type dialog + } + + frame $w.bot + frame $w.top + if {$windowingsystem eq "x11"} { + $w.bot configure -relief raised -bd 1 + $w.top configure -relief raised -bd 1 + } + pack $w.bot -side bottom -fill both + pack $w.top -side top -fill both -expand 1 + grid anchor $w.bot center + + # 2. Fill the top part with bitmap and message (use the option + # database for -wraplength and -font so that they can be + # overridden by the caller). + + option add *Dialog.msg.wrapLength 3i widgetDefault + option add *Dialog.msg.font TkCaptionFont widgetDefault + + label $w.msg -justify left -text $text + pack $w.msg -in $w.top -side right -expand 1 -fill both -padx 3m -pady 3m + if {$bitmap ne ""} { + if {$windowingsystem eq "aqua" && $bitmap eq "error"} { + set bitmap "stop" + } + label $w.bitmap -bitmap $bitmap + pack $w.bitmap -in $w.top -side left -padx 3m -pady 3m + } + + # 3. Create a row of buttons at the bottom of the dialog. + + set i 0 + foreach but $args { + button $w.button$i -text $but -command [list set ::tk::Priv(button) $i] + if {$i == $default} { + $w.button$i configure -default active + } else { + $w.button$i configure -default normal + } + grid $w.button$i -in $w.bot -column $i -row 0 -sticky ew \ + -padx 10 -pady 4 + grid columnconfigure $w.bot $i + # We boost the size of some Mac buttons for l&f + if {$windowingsystem eq "aqua"} { + set tmp [string tolower $but] + if {$tmp eq "ok" || $tmp eq "cancel"} { + grid columnconfigure $w.bot $i -minsize 90 + } + grid configure $w.button$i -pady 7 + } + incr i + } + + # 4. Create a binding for on the dialog if there is a + # default button. + # Convention also dictates that if the keyboard focus moves among the + # the buttons that the binding affects the button with the focus. + + if {$default >= 0} { + bind $w [list $w.button$default invoke] + } + bind $w <> [list bind $w {[tk_focusPrev %W] invoke}] + bind $w <> [list bind $w {[tk_focusNext %W] invoke}] + + # 5. Create a binding for the window that sets the + # button variable to -1; this is needed in case something happens + # that destroys the window, such as its parent window being destroyed. + + bind $w {set ::tk::Priv(button) -1} + + # 6. Withdraw the window, then update all the geometry information + # so we know how big it wants to be, then center the window in the + # display (Motif style) and de-iconify it. + + ::tk::PlaceWindow $w + tkwait visibility $w + + # 7. Set a grab and claim the focus too. + + if {$default >= 0} { + set focus $w.button$default + } else { + set focus $w + } + tk::SetFocusGrab $w $focus + + # 8. Wait for the user to respond, then restore the focus and + # return the index of the selected button. Restore the focus + # before deleting the window, since otherwise the window manager + # may take the focus away so we can't redirect it. Finally, + # restore any grab that was in effect. + + vwait ::tk::Priv(button) + + catch { + # It's possible that the window has already been destroyed, + # hence this "catch". Delete the Destroy handler so that + # Priv(button) doesn't get reset by it. + + bind $w {} + } + tk::RestoreFocusGrab $w $focus + return $Priv(button) +} diff --git a/shared/package-files/d1/d1b3179a18a35a47a9ab41e4fe6d4fcafd4eab8e4c13b48acfb3c908c8182479/blob b/shared/package-files/d1/d1b3179a18a35a47a9ab41e4fe6d4fcafd4eab8e4c13b48acfb3c908c8182479/blob new file mode 100644 index 0000000000000000000000000000000000000000..9cda6818d7849cd99f24da6252071ca23d2826f1 --- /dev/null +++ b/shared/package-files/d1/d1b3179a18a35a47a9ab41e4fe6d4fcafd4eab8e4c13b48acfb3c908c8182479/blob @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API bool is_neg(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/d1/d1b73b61f602f1a33547d2f1c7cbefe3b8000b4ae608121db7abf645acb1c223/blob b/shared/package-files/d1/d1b73b61f602f1a33547d2f1c7cbefe3b8000b4ae608121db7abf645acb1c223/blob new file mode 100644 index 0000000000000000000000000000000000000000..6bfc980761bdcfb5a5e607fabddf004f385b6a65 --- /dev/null +++ b/shared/package-files/d1/d1b73b61f602f1a33547d2f1c7cbefe3b8000b4ae608121db7abf645acb1c223/blob @@ -0,0 +1,13 @@ +*** Sat, 3 Sep 2016 22:29:28 *** +TEST FOR GRANGER-CAUSALITY: +H0: "realinv" do not Granger-cause "realcons, realgdp" + +Test statistic l = 3.7582 +pval-F( l; 8, 549) = 0.0003 + +TEST FOR INSTANTANEOUS CAUSALITY: +H0: No instantaneous causality between "realinv" and "realcons, realgdp" + +Test statistic: c = 79.8044 +pval-Chi( c; 2) = 0.0000 + diff --git a/shared/package-files/d1/d1b800f14d7b432bd21ec732e73bb5256eeb4d670469dc3a1f034d6c0f4f86f9/blob b/shared/package-files/d1/d1b800f14d7b432bd21ec732e73bb5256eeb4d670469dc3a1f034d6c0f4f86f9/blob new file mode 100644 index 0000000000000000000000000000000000000000..931bd0b1b340af03338e8e504c630614bde9c56c --- /dev/null +++ b/shared/package-files/d1/d1b800f14d7b432bd21ec732e73bb5256eeb4d670469dc3a1f034d6c0f4f86f9/blob @@ -0,0 +1,375 @@ +""" +This is a python implementation of wcwidth() and wcswidth(). + +https://github.com/jquast/wcwidth + +from Markus Kuhn's C code, retrieved from: + + http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c + +This is an implementation of wcwidth() and wcswidth() (defined in +IEEE Std 1002.1-2001) for Unicode. + +http://www.opengroup.org/onlinepubs/007904975/functions/wcwidth.html +http://www.opengroup.org/onlinepubs/007904975/functions/wcswidth.html + +In fixed-width output devices, Latin characters all occupy a single +"cell" position of equal width, whereas ideographic CJK characters +occupy two such cells. Interoperability between terminal-line +applications and (teletype-style) character terminals using the +UTF-8 encoding requires agreement on which character should advance +the cursor by how many cell positions. No established formal +standards exist at present on which Unicode character shall occupy +how many cell positions on character terminals. These routines are +a first attempt of defining such behavior based on simple rules +applied to data provided by the Unicode Consortium. + +For some graphical characters, the Unicode standard explicitly +defines a character-cell width via the definition of the East Asian +FullWidth (F), Wide (W), Half-width (H), and Narrow (Na) classes. +In all these cases, there is no ambiguity about which width a +terminal shall use. For characters in the East Asian Ambiguous (A) +class, the width choice depends purely on a preference of backward +compatibility with either historic CJK or Western practice. +Choosing single-width for these characters is easy to justify as +the appropriate long-term solution, as the CJK practice of +displaying these characters as double-width comes from historic +implementation simplicity (8-bit encoded characters were displayed +single-width and 16-bit ones double-width, even for Greek, +Cyrillic, etc.) and not any typographic considerations. + +Much less clear is the choice of width for the Not East Asian +(Neutral) class. Existing practice does not dictate a width for any +of these characters. It would nevertheless make sense +typographically to allocate two character cells to characters such +as for instance EM SPACE or VOLUME INTEGRAL, which cannot be +represented adequately with a single-width glyph. The following +routines at present merely assign a single-cell width to all +neutral characters, in the interest of simplicity. This is not +entirely satisfactory and should be reconsidered before +establishing a formal standard in this area. At the moment, the +decision which Not East Asian (Neutral) characters should be +represented by double-width glyphs cannot yet be answered by +applying a simple rule from the Unicode database content. Setting +up a proper standard for the behavior of UTF-8 character terminals +will require a careful analysis not only of each Unicode character, +but also of each presentation form, something the author of these +routines has avoided to do so far. + +http://www.unicode.org/unicode/reports/tr11/ + +Latest version: http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c +""" +from __future__ import division + +# std imports +import os +import sys +import warnings + +# local +from .table_wide import WIDE_EASTASIAN +from .table_zero import ZERO_WIDTH +from .unicode_versions import list_versions + +try: + from functools import lru_cache +except ImportError: + # lru_cache was added in Python 3.2 + from backports.functools_lru_cache import lru_cache + +# global cache +_UNICODE_CMPTABLE = None +_PY3 = (sys.version_info[0] >= 3) + + +# NOTE: created by hand, there isn't anything identifiable other than +# general Cf category code to identify these, and some characters in Cf +# category code are of non-zero width. +# Also includes some Cc, Mn, Zl, and Zp characters +ZERO_WIDTH_CF = set([ + 0, # Null (Cc) + 0x034F, # Combining grapheme joiner (Mn) + 0x200B, # Zero width space + 0x200C, # Zero width non-joiner + 0x200D, # Zero width joiner + 0x200E, # Left-to-right mark + 0x200F, # Right-to-left mark + 0x2028, # Line separator (Zl) + 0x2029, # Paragraph separator (Zp) + 0x202A, # Left-to-right embedding + 0x202B, # Right-to-left embedding + 0x202C, # Pop directional formatting + 0x202D, # Left-to-right override + 0x202E, # Right-to-left override + 0x2060, # Word joiner + 0x2061, # Function application + 0x2062, # Invisible times + 0x2063, # Invisible separator +]) + + +def _bisearch(ucs, table): + """ + Auxiliary function for binary search in interval table. + + :arg int ucs: Ordinal value of unicode character. + :arg list table: List of starting and ending ranges of ordinal values, + in form of ``[(start, end), ...]``. + :rtype: int + :returns: 1 if ordinal value ucs is found within lookup table, else 0. + """ + lbound = 0 + ubound = len(table) - 1 + + if ucs < table[0][0] or ucs > table[ubound][1]: + return 0 + while ubound >= lbound: + mid = (lbound + ubound) // 2 + if ucs > table[mid][1]: + lbound = mid + 1 + elif ucs < table[mid][0]: + ubound = mid - 1 + else: + return 1 + + return 0 + + +@lru_cache(maxsize=1000) +def wcwidth(wc, unicode_version='auto'): + r""" + Given one Unicode character, return its printable length on a terminal. + + :param str wc: A single Unicode character. + :param str unicode_version: A Unicode version number, such as + ``'6.0.0'``, the list of available version levels may be + listed by pairing function :func:`list_versions`. + + Any version string may be specified without error -- the nearest + matching version is selected. When ``latest`` (default), the + highest Unicode version level is used. + :return: The width, in cells, necessary to display the character of + Unicode string character, ``wc``. Returns 0 if the ``wc`` argument has + no printable effect on a terminal (such as NUL '\0'), -1 if ``wc`` is + not printable, or has an indeterminate effect on the terminal, such as + a control character. Otherwise, the number of column positions the + character occupies on a graphic terminal (1 or 2) is returned. + :rtype: int + + The following have a column width of -1: + + - C0 control characters (U+001 through U+01F). + + - C1 control characters and DEL (U+07F through U+0A0). + + The following have a column width of 0: + + - Non-spacing and enclosing combining characters (general + category code Mn or Me in the Unicode database). + + - NULL (``U+0000``). + + - COMBINING GRAPHEME JOINER (``U+034F``). + + - ZERO WIDTH SPACE (``U+200B``) *through* + RIGHT-TO-LEFT MARK (``U+200F``). + + - LINE SEPARATOR (``U+2028``) *and* + PARAGRAPH SEPARATOR (``U+2029``). + + - LEFT-TO-RIGHT EMBEDDING (``U+202A``) *through* + RIGHT-TO-LEFT OVERRIDE (``U+202E``). + + - WORD JOINER (``U+2060``) *through* + INVISIBLE SEPARATOR (``U+2063``). + + The following have a column width of 1: + + - SOFT HYPHEN (``U+00AD``). + + - All remaining characters, including all printable ISO 8859-1 + and WGL4 characters, Unicode control characters, etc. + + The following have a column width of 2: + + - Spacing characters in the East Asian Wide (W) or East Asian + Full-width (F) category as defined in Unicode Technical + Report #11 have a column width of 2. + + - Some kinds of Emoji or symbols. + """ + # NOTE: created by hand, there isn't anything identifiable other than + # general Cf category code to identify these, and some characters in Cf + # category code are of non-zero width. + ucs = ord(wc) + if ucs in ZERO_WIDTH_CF: + return 0 + + # C0/C1 control characters + if ucs < 32 or 0x07F <= ucs < 0x0A0: + return -1 + + _unicode_version = _wcmatch_version(unicode_version) + + # combining characters with zero width + if _bisearch(ucs, ZERO_WIDTH[_unicode_version]): + return 0 + + return 1 + _bisearch(ucs, WIDE_EASTASIAN[_unicode_version]) + + +def wcswidth(pwcs, n=None, unicode_version='auto'): + """ + Given a unicode string, return its printable length on a terminal. + + :param str pwcs: Measure width of given unicode string. + :param int n: When ``n`` is None (default), return the length of the + entire string, otherwise width the first ``n`` characters specified. + :param str unicode_version: An explicit definition of the unicode version + level to use for determination, may be ``auto`` (default), which uses + the Environment Variable, ``UNICODE_VERSION`` if defined, or the latest + available unicode version, otherwise. + :rtype: int + :returns: The width, in cells, necessary to display the first ``n`` + characters of the unicode string ``pwcs``. Returns ``-1`` if + a non-printable character is encountered. + """ + # pylint: disable=C0103 + # Invalid argument name "n" + + end = len(pwcs) if n is None else n + idx = slice(0, end) + width = 0 + for char in pwcs[idx]: + wcw = wcwidth(char, unicode_version) + if wcw < 0: + return -1 + width += wcw + return width + + +@lru_cache(maxsize=128) +def _wcversion_value(ver_string): + """ + Integer-mapped value of given dotted version string. + + :param str ver_string: Unicode version string, of form ``n.n.n``. + :rtype: tuple(int) + :returns: tuple of digit tuples, ``tuple(int, [...])``. + """ + retval = tuple(map(int, (ver_string.split('.')))) + return retval + + +@lru_cache(maxsize=8) +def _wcmatch_version(given_version): + """ + Return nearest matching supported Unicode version level. + + If an exact match is not determined, the nearest lowest version level is + returned after a warning is emitted. For example, given supported levels + ``4.1.0`` and ``5.0.0``, and a version string of ``4.9.9``, then ``4.1.0`` + is selected and returned: + + >>> _wcmatch_version('4.9.9') + '4.1.0' + >>> _wcmatch_version('8.0') + '8.0.0' + >>> _wcmatch_version('1') + '4.1.0' + + :param str given_version: given version for compare, may be ``auto`` + (default), to select Unicode Version from Environment Variable, + ``UNICODE_VERSION``. If the environment variable is not set, then the + latest is used. + :rtype: str + :returns: unicode string, or non-unicode ``str`` type for python 2 + when given ``version`` is also type ``str``. + """ + # Design note: the choice to return the same type that is given certainly + # complicates it for python 2 str-type, but allows us to define an api that + # to use 'string-type', for unicode version level definitions, so all of our + # example code works with all versions of python. That, along with the + # string-to-numeric and comparisons of earliest, latest, matching, or + # nearest, greatly complicates this function. + _return_str = not _PY3 and isinstance(given_version, str) + + if _return_str: + unicode_versions = [ucs.encode() for ucs in list_versions()] + else: + unicode_versions = list_versions() + latest_version = unicode_versions[-1] + + if given_version in (u'auto', 'auto'): + given_version = os.environ.get( + 'UNICODE_VERSION', + 'latest' if not _return_str else latest_version.encode()) + + if given_version in (u'latest', 'latest'): + # default match, when given as 'latest', use the most latest unicode + # version specification level supported. + return latest_version if not _return_str else latest_version.encode() + + if given_version in unicode_versions: + # exact match, downstream has specified an explicit matching version + # matching any value of list_versions(). + return given_version if not _return_str else given_version.encode() + + # The user's version is not supported by ours. We return the newest unicode + # version level that we support below their given value. + try: + cmp_given = _wcversion_value(given_version) + + except ValueError: + # submitted value raises ValueError in int(), warn and use latest. + warnings.warn("UNICODE_VERSION value, {given_version!r}, is invalid. " + "Value should be in form of `integer[.]+', the latest " + "supported unicode version {latest_version!r} has been " + "inferred.".format(given_version=given_version, + latest_version=latest_version)) + return latest_version if not _return_str else latest_version.encode() + + # given version is less than any available version, return earliest + # version. + earliest_version = unicode_versions[0] + cmp_earliest_version = _wcversion_value(earliest_version) + + if cmp_given <= cmp_earliest_version: + # this probably isn't what you wanted, the oldest wcwidth.c you will + # find in the wild is likely version 5 or 6, which we both support, + # but it's better than not saying anything at all. + warnings.warn("UNICODE_VERSION value, {given_version!r}, is lower " + "than any available unicode version. Returning lowest " + "version level, {earliest_version!r}".format( + given_version=given_version, + earliest_version=earliest_version)) + return earliest_version if not _return_str else earliest_version.encode() + + # create list of versions which are less than our equal to given version, + # and return the tail value, which is the highest level we may support, + # or the latest value we support, when completely unmatched or higher + # than any supported version. + # + # function will never complete, always returns. + for idx, unicode_version in enumerate(unicode_versions): + # look ahead to next value + try: + cmp_next_version = _wcversion_value(unicode_versions[idx + 1]) + except IndexError: + # at end of list, return latest version + return latest_version if not _return_str else latest_version.encode() + + # Maybe our given version has less parts, as in tuple(8, 0), than the + # next compare version tuple(8, 0, 0). Test for an exact match by + # comparison of only the leading dotted piece(s): (8, 0) == (8, 0). + if cmp_given == cmp_next_version[:len(cmp_given)]: + return unicode_versions[idx + 1] + + # Or, if any next value is greater than our given support level + # version, return the current value in index. Even though it must + # be less than the given value, its our closest possible match. That + # is, 4.1 is returned for given 4.9.9, where 4.1 and 5.0 are available. + if cmp_next_version > cmp_given: + return unicode_version + assert False, ("Code path unreachable", given_version, unicode_versions) diff --git a/shared/package-files/d1/d1baba8e9f785f3c950a050e620b9984d80c88b93fbbdcac74e4deeeb28f5a13/blob b/shared/package-files/d1/d1baba8e9f785f3c950a050e620b9984d80c88b93fbbdcac74e4deeeb28f5a13/blob new file mode 100644 index 0000000000000000000000000000000000000000..127a5223fb25c64ae11a21e35b6c43eec6a1e3c9 --- /dev/null +++ b/shared/package-files/d1/d1baba8e9f785f3c950a050e620b9984d80c88b93fbbdcac74e4deeeb28f5a13/blob @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_upsample_bicubic2d_backward : public at::impl::MetaBase { + + + void meta(const at::Tensor & grad_output, at::ArrayRef output_size, at::ArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/d1/d1bbd9d81a5af3369672bccd77a591283d5ef487ac0e16810123febd1fd96aec/blob b/shared/package-files/d1/d1bbd9d81a5af3369672bccd77a591283d5ef487ac0e16810123febd1fd96aec/blob new file mode 100644 index 0000000000000000000000000000000000000000..6d097e75f6703c277bd271dbd030293b459ec9ae --- /dev/null +++ b/shared/package-files/d1/d1bbd9d81a5af3369672bccd77a591283d5ef487ac0e16810123febd1fd96aec/blob @@ -0,0 +1,104 @@ +import numpy as np + +import pandas as pd +from pandas import ( + Categorical, + DataFrame, + Index, + Series, + Timestamp, +) +import pandas._testing as tm +from pandas.core.arrays import IntervalArray + + +class TestGetNumericData: + def test_get_numeric_data_preserve_dtype(self): + # get the numeric data + obj = DataFrame({"A": [1, "2", 3.0]}, columns=Index(["A"], dtype="object")) + result = obj._get_numeric_data() + expected = DataFrame(dtype=object, index=pd.RangeIndex(3), columns=[]) + tm.assert_frame_equal(result, expected) + + def test_get_numeric_data(self, using_infer_string): + datetime64name = np.dtype("M8[s]").name + objectname = np.dtype(np.object_).name + + df = DataFrame( + {"a": 1.0, "b": 2, "c": "foo", "f": Timestamp("20010102")}, + index=np.arange(10), + ) + result = df.dtypes + expected = Series( + [ + np.dtype("float64"), + np.dtype("int64"), + np.dtype(objectname) + if not using_infer_string + else pd.StringDtype(na_value=np.nan), + np.dtype(datetime64name), + ], + index=["a", "b", "c", "f"], + ) + tm.assert_series_equal(result, expected) + + df = DataFrame( + { + "a": 1.0, + "b": 2, + "c": "foo", + "d": np.array([1.0] * 10, dtype="float32"), + "e": np.array([1] * 10, dtype="int32"), + "f": np.array([1] * 10, dtype="int16"), + "g": Timestamp("20010102"), + }, + index=np.arange(10), + ) + + result = df._get_numeric_data() + expected = df.loc[:, ["a", "b", "d", "e", "f"]] + tm.assert_frame_equal(result, expected) + + only_obj = df.loc[:, ["c", "g"]] + result = only_obj._get_numeric_data() + expected = df.loc[:, []] + tm.assert_frame_equal(result, expected) + + df = DataFrame.from_dict({"a": [1, 2], "b": ["foo", "bar"], "c": [np.pi, np.e]}) + result = df._get_numeric_data() + expected = DataFrame.from_dict({"a": [1, 2], "c": [np.pi, np.e]}) + tm.assert_frame_equal(result, expected) + + df = result.copy() + result = df._get_numeric_data() + expected = df + tm.assert_frame_equal(result, expected) + + def test_get_numeric_data_mixed_dtype(self): + # numeric and object columns + + df = DataFrame( + { + "a": [1, 2, 3], + "b": [True, False, True], + "c": ["foo", "bar", "baz"], + "d": [None, None, None], + "e": [3.14, 0.577, 2.773], + } + ) + result = df._get_numeric_data() + tm.assert_index_equal(result.columns, Index(["a", "b", "e"])) + + def test_get_numeric_data_extension_dtype(self): + # GH#22290 + df = DataFrame( + { + "A": pd.array([-10, np.nan, 0, 10, 20, 30], dtype="Int64"), + "B": Categorical(list("abcabc")), + "C": pd.array([0, 1, 2, 3, np.nan, 5], dtype="UInt8"), + "D": IntervalArray.from_breaks(range(7)), + } + ) + result = df._get_numeric_data() + expected = df.loc[:, ["A", "C"]] + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/d1/d1bcadba6f1cfc0d5776de4d1f975ca25ec68c5b6b923b809c7fdc9cb5abd3b8/blob b/shared/package-files/d1/d1bcadba6f1cfc0d5776de4d1f975ca25ec68c5b6b923b809c7fdc9cb5abd3b8/blob new file mode 100644 index 0000000000000000000000000000000000000000..2d15cf4d72d19f4b7949cd80bc77aa31553841c1 --- /dev/null +++ b/shared/package-files/d1/d1bcadba6f1cfc0d5776de4d1f975ca25ec68c5b6b923b809c7fdc9cb5abd3b8/blob @@ -0,0 +1,1061 @@ +""" +Low-level LAPACK functions (:mod:`scipy.linalg.lapack`) +======================================================= + +This module contains low-level functions from the LAPACK library. + +.. versionadded:: 0.12.0 + +.. note:: + + The common ``overwrite_<>`` option in many routines, allows the + input arrays to be overwritten to avoid extra memory allocation. + However this requires the array to satisfy two conditions + which are memory order and the data type to match exactly the + order and the type expected by the routine. + + As an example, if you pass a double precision float array to any + ``S....`` routine which expects single precision arguments, f2py + will create an intermediate array to match the argument types and + overwriting will be performed on that intermediate array. + + Similarly, if a C-contiguous array is passed, f2py will pass a + FORTRAN-contiguous array internally. Please make sure that these + details are satisfied. More information can be found in the f2py + documentation. + +.. warning:: + + These functions do little to no error checking. + It is possible to cause crashes by mis-using them, + so prefer using the higher-level routines in `scipy.linalg`. + +Finding functions +----------------- + +.. autosummary:: + :toctree: generated/ + + get_lapack_funcs + +All functions +------------- + +.. autosummary:: + :toctree: generated/ + + sgbsv + dgbsv + cgbsv + zgbsv + + sgbtrf + dgbtrf + cgbtrf + zgbtrf + + sgbtrs + dgbtrs + cgbtrs + zgbtrs + + sgebal + dgebal + cgebal + zgebal + + sgecon + dgecon + cgecon + zgecon + + sgeequ + dgeequ + cgeequ + zgeequ + + sgeequb + dgeequb + cgeequb + zgeequb + + sgees + dgees + cgees + zgees + + sgeev + dgeev + cgeev + zgeev + + sgeev_lwork + dgeev_lwork + cgeev_lwork + zgeev_lwork + + sgehrd + dgehrd + cgehrd + zgehrd + + sgehrd_lwork + dgehrd_lwork + cgehrd_lwork + zgehrd_lwork + + sgejsv + dgejsv + + sgels + dgels + cgels + zgels + + sgels_lwork + dgels_lwork + cgels_lwork + zgels_lwork + + sgelsd + dgelsd + cgelsd + zgelsd + + sgelsd_lwork + dgelsd_lwork + cgelsd_lwork + zgelsd_lwork + + sgelss + dgelss + cgelss + zgelss + + sgelss_lwork + dgelss_lwork + cgelss_lwork + zgelss_lwork + + sgelsy + dgelsy + cgelsy + zgelsy + + sgelsy_lwork + dgelsy_lwork + cgelsy_lwork + zgelsy_lwork + + sgeqp3 + dgeqp3 + cgeqp3 + zgeqp3 + + sgeqrf + dgeqrf + cgeqrf + zgeqrf + + sgeqrf_lwork + dgeqrf_lwork + cgeqrf_lwork + zgeqrf_lwork + + sgeqrfp + dgeqrfp + cgeqrfp + zgeqrfp + + sgeqrfp_lwork + dgeqrfp_lwork + cgeqrfp_lwork + zgeqrfp_lwork + + sgerqf + dgerqf + cgerqf + zgerqf + + sgesdd + dgesdd + cgesdd + zgesdd + + sgesdd_lwork + dgesdd_lwork + cgesdd_lwork + zgesdd_lwork + + sgesv + dgesv + cgesv + zgesv + + sgesvd + dgesvd + cgesvd + zgesvd + + sgesvd_lwork + dgesvd_lwork + cgesvd_lwork + zgesvd_lwork + + sgesvx + dgesvx + cgesvx + zgesvx + + sgetrf + dgetrf + cgetrf + zgetrf + + sgetc2 + dgetc2 + cgetc2 + zgetc2 + + sgetri + dgetri + cgetri + zgetri + + sgetri_lwork + dgetri_lwork + cgetri_lwork + zgetri_lwork + + sgetrs + dgetrs + cgetrs + zgetrs + + sgesc2 + dgesc2 + cgesc2 + zgesc2 + + sgges + dgges + cgges + zgges + + sggev + dggev + cggev + zggev + + sgglse + dgglse + cgglse + zgglse + + sgglse_lwork + dgglse_lwork + cgglse_lwork + zgglse_lwork + + sgtsv + dgtsv + cgtsv + zgtsv + + sgtsvx + dgtsvx + cgtsvx + zgtsvx + + chbevd + zhbevd + + chbevx + zhbevx + + checon + zhecon + + cheequb + zheequb + + cheev + zheev + + cheev_lwork + zheev_lwork + + cheevd + zheevd + + cheevd_lwork + zheevd_lwork + + cheevr + zheevr + + cheevr_lwork + zheevr_lwork + + cheevx + zheevx + + cheevx_lwork + zheevx_lwork + + chegst + zhegst + + chegv + zhegv + + chegv_lwork + zhegv_lwork + + chegvd + zhegvd + + chegvx + zhegvx + + chegvx_lwork + zhegvx_lwork + + chesv + zhesv + + chesv_lwork + zhesv_lwork + + chesvx + zhesvx + + chesvx_lwork + zhesvx_lwork + + chetrd + zhetrd + + chetrd_lwork + zhetrd_lwork + + chetrf + zhetrf + + chetrf_lwork + zhetrf_lwork + + chetrs + zhetrs + + chfrk + zhfrk + + slamch + dlamch + + slange + dlange + clange + zlange + + slantr + dlantr + clantr + zlantr + + slarf + dlarf + clarf + zlarf + + slarfg + dlarfg + clarfg + zlarfg + + slartg + dlartg + clartg + zlartg + + slasd4 + dlasd4 + + slaswp + dlaswp + claswp + zlaswp + + slauum + dlauum + clauum + zlauum + + sorcsd + dorcsd + sorcsd_lwork + dorcsd_lwork + + sorghr + dorghr + sorghr_lwork + dorghr_lwork + + sorgqr + dorgqr + + sorgrq + dorgrq + + sormqr + dormqr + + sormrz + dormrz + + sormrz_lwork + dormrz_lwork + + spbsv + dpbsv + cpbsv + zpbsv + + spbtrf + dpbtrf + cpbtrf + zpbtrf + + spbtrs + dpbtrs + cpbtrs + zpbtrs + + spftrf + dpftrf + cpftrf + zpftrf + + spftri + dpftri + cpftri + zpftri + + spftrs + dpftrs + cpftrs + zpftrs + + spocon + dpocon + cpocon + zpocon + + spstrf + dpstrf + cpstrf + zpstrf + + spstf2 + dpstf2 + cpstf2 + zpstf2 + + sposv + dposv + cposv + zposv + + sposvx + dposvx + cposvx + zposvx + + spotrf + dpotrf + cpotrf + zpotrf + + spotri + dpotri + cpotri + zpotri + + spotrs + dpotrs + cpotrs + zpotrs + + sppcon + dppcon + cppcon + zppcon + + sppsv + dppsv + cppsv + zppsv + + spptrf + dpptrf + cpptrf + zpptrf + + spptri + dpptri + cpptri + zpptri + + spptrs + dpptrs + cpptrs + zpptrs + + sptsv + dptsv + cptsv + zptsv + + sptsvx + dptsvx + cptsvx + zptsvx + + spttrf + dpttrf + cpttrf + zpttrf + + spttrs + dpttrs + cpttrs + zpttrs + + spteqr + dpteqr + cpteqr + zpteqr + + crot + zrot + + ssbev + dsbev + + ssbevd + dsbevd + + ssbevx + dsbevx + + ssfrk + dsfrk + + sstebz + dstebz + + sstein + dstein + + sstemr + dstemr + + sstemr_lwork + dstemr_lwork + + ssterf + dsterf + + sstev + dstev + + ssycon + dsycon + csycon + zsycon + + ssyconv + dsyconv + csyconv + zsyconv + + ssyequb + dsyequb + csyequb + zsyequb + + ssyev + dsyev + + ssyev_lwork + dsyev_lwork + + ssyevd + dsyevd + + ssyevd_lwork + dsyevd_lwork + + ssyevr + dsyevr + + ssyevr_lwork + dsyevr_lwork + + ssyevx + dsyevx + + ssyevx_lwork + dsyevx_lwork + + ssygst + dsygst + + ssygv + dsygv + + ssygv_lwork + dsygv_lwork + + ssygvd + dsygvd + + ssygvx + dsygvx + + ssygvx_lwork + dsygvx_lwork + + ssysv + dsysv + csysv + zsysv + + ssysv_lwork + dsysv_lwork + csysv_lwork + zsysv_lwork + + ssysvx + dsysvx + csysvx + zsysvx + + ssysvx_lwork + dsysvx_lwork + csysvx_lwork + zsysvx_lwork + + ssytf2 + dsytf2 + csytf2 + zsytf2 + + ssytrd + dsytrd + + ssytrd_lwork + dsytrd_lwork + + ssytrf + dsytrf + csytrf + zsytrf + + ssytrf_lwork + dsytrf_lwork + csytrf_lwork + zsytrf_lwork + + ssytrs + dsytrs + csytrs + zsytrs + + stbtrs + dtbtrs + ctbtrs + ztbtrs + + stfsm + dtfsm + ctfsm + ztfsm + + stfttp + dtfttp + ctfttp + ztfttp + + stfttr + dtfttr + ctfttr + ztfttr + + stgexc + dtgexc + ctgexc + ztgexc + + stgsen + dtgsen + ctgsen + ztgsen + + stgsen_lwork + dtgsen_lwork + ctgsen_lwork + ztgsen_lwork + + stgsyl + dtgsyl + + stpttf + dtpttf + ctpttf + ztpttf + + stpttr + dtpttr + ctpttr + ztpttr + + strcon + dtrcon + ctrcon + ztrcon + + strexc + dtrexc + ctrexc + ztrexc + + strsen + dtrsen + ctrsen + ztrsen + + strsen_lwork + dtrsen_lwork + ctrsen_lwork + ztrsen_lwork + + strsyl + dtrsyl + ctrsyl + ztrsyl + + strtri + dtrtri + ctrtri + ztrtri + + strtrs + dtrtrs + ctrtrs + ztrtrs + + strttf + dtrttf + ctrttf + ztrttf + + strttp + dtrttp + ctrttp + ztrttp + + stzrzf + dtzrzf + ctzrzf + ztzrzf + + stzrzf_lwork + dtzrzf_lwork + ctzrzf_lwork + ztzrzf_lwork + + cunghr + zunghr + + cunghr_lwork + zunghr_lwork + + cungqr + zungqr + + cungrq + zungrq + + cunmqr + zunmqr + + sgeqrt + dgeqrt + cgeqrt + zgeqrt + + sgemqrt + dgemqrt + cgemqrt + zgemqrt + + sgttrf + dgttrf + cgttrf + zgttrf + + sgttrs + dgttrs + cgttrs + zgttrs + + sgtcon + dgtcon + cgtcon + zgtcon + + stpqrt + dtpqrt + ctpqrt + ztpqrt + + stpmqrt + dtpmqrt + ctpmqrt + ztpmqrt + + cuncsd + zuncsd + + cuncsd_lwork + zuncsd_lwork + + cunmrz + zunmrz + + cunmrz_lwork + zunmrz_lwork + + ilaver + +""" +# +# Author: Pearu Peterson, March 2002 +# + +import numpy as np +from .blas import _get_funcs, _memoize_get_funcs +from scipy.linalg import _flapack +from re import compile as regex_compile +try: + from scipy.linalg import _clapack +except ImportError: + _clapack = None + +try: + from scipy.linalg import _flapack_64 + HAS_ILP64 = True +except ImportError: + HAS_ILP64 = False + _flapack_64 = None + + +# Expose all functions (only flapack --- clapack is an implementation detail) +empty_module = None +from scipy.linalg._flapack import * # noqa: E402, F403 +del empty_module + +__all__ = ['get_lapack_funcs'] + +# some convenience alias for complex functions +_lapack_alias = { + 'corghr': 'cunghr', 'zorghr': 'zunghr', + 'corghr_lwork': 'cunghr_lwork', 'zorghr_lwork': 'zunghr_lwork', + 'corgqr': 'cungqr', 'zorgqr': 'zungqr', + 'cormqr': 'cunmqr', 'zormqr': 'zunmqr', + 'corgrq': 'cungrq', 'zorgrq': 'zungrq', +} + + +# Place guards against docstring rendering issues with special characters +p1 = regex_compile(r'with bounds (?P.*?)( and (?P.*?) storage){0,1}\n') +p2 = regex_compile(r'Default: (?P.*?)\n') + + +def backtickrepl(m): + if m.group('s'): + return (f"with bounds ``{m.group('b')}`` with ``{m.group('s')}`` storage\n") + else: + return f"with bounds ``{m.group('b')}``\n" + + +for routine in [ssyevr, dsyevr, cheevr, zheevr, + ssyevx, dsyevx, cheevx, zheevx, + ssygvd, dsygvd, chegvd, zhegvd]: + if routine.__doc__: + routine.__doc__ = p1.sub(backtickrepl, routine.__doc__) + routine.__doc__ = p2.sub('Default ``\\1``\n', routine.__doc__) + else: + continue + +del regex_compile, p1, p2, backtickrepl + + +@_memoize_get_funcs +def get_lapack_funcs(names, arrays=(), dtype=None, ilp64=False): + """Return available LAPACK function objects from names. + + Arrays are used to determine the optimal prefix of LAPACK routines. + + Parameters + ---------- + names : str or sequence of str + Name(s) of LAPACK functions without type prefix. + + arrays : sequence of ndarrays, optional + Arrays can be given to determine optimal prefix of LAPACK + routines. If not given, double-precision routines will be + used, otherwise the most generic type in arrays will be used. + + dtype : str or dtype, optional + Data-type specifier. Not used if `arrays` is non-empty. + + ilp64 : {True, False, 'preferred'}, optional + Whether to return ILP64 routine variant. + Choosing 'preferred' returns ILP64 routine if available, and + otherwise the 32-bit routine. Default: False + + Returns + ------- + funcs : list + List containing the found function(s). + + Notes + ----- + This routine automatically chooses between Fortran/C + interfaces. Fortran code is used whenever possible for arrays with + column major order. In all other cases, C code is preferred. + + In LAPACK, the naming convention is that all functions start with a + type prefix, which depends on the type of the principal + matrix. These can be one of {'s', 'd', 'c', 'z'} for the NumPy + types {float32, float64, complex64, complex128} respectively, and + are stored in attribute ``typecode`` of the returned functions. + + Examples + -------- + Suppose we would like to use '?lange' routine which computes the selected + norm of an array. We pass our array in order to get the correct 'lange' + flavor. + + >>> import numpy as np + >>> import scipy.linalg as LA + >>> rng = np.random.default_rng() + + >>> a = rng.random((3,2)) + >>> x_lange = LA.get_lapack_funcs('lange', (a,)) + >>> x_lange.typecode + 'd' + >>> x_lange = LA.get_lapack_funcs('lange',(a*1j,)) + >>> x_lange.typecode + 'z' + + Several LAPACK routines work best when its internal WORK array has + the optimal size (big enough for fast computation and small enough to + avoid waste of memory). This size is determined also by a dedicated query + to the function which is often wrapped as a standalone function and + commonly denoted as ``###_lwork``. Below is an example for ``?sysv`` + + >>> a = rng.random((1000, 1000)) + >>> b = rng.random((1000, 1)) * 1j + >>> # We pick up zsysv and zsysv_lwork due to b array + ... xsysv, xlwork = LA.get_lapack_funcs(('sysv', 'sysv_lwork'), (a, b)) + >>> opt_lwork, _ = xlwork(a.shape[0]) # returns a complex for 'z' prefix + >>> udut, ipiv, x, info = xsysv(a, b, lwork=int(opt_lwork.real)) + + """ + if isinstance(ilp64, str): + if ilp64 == 'preferred': + ilp64 = HAS_ILP64 + else: + raise ValueError("Invalid value for 'ilp64'") + + if not ilp64: + return _get_funcs(names, arrays, dtype, + "LAPACK", _flapack, _clapack, + "flapack", "clapack", _lapack_alias, + ilp64=False) + else: + if not HAS_ILP64: + raise RuntimeError("LAPACK ILP64 routine requested, but Scipy " + "compiled only with 32-bit BLAS") + return _get_funcs(names, arrays, dtype, + "LAPACK", _flapack_64, None, + "flapack_64", None, _lapack_alias, + ilp64=True) + + +_int32_max = np.iinfo(np.int32).max +_int64_max = np.iinfo(np.int64).max + + +def _compute_lwork(routine, *args, **kwargs): + """ + Round floating-point lwork returned by lapack to integer. + + Several LAPACK routines compute optimal values for LWORK, which + they return in a floating-point variable. However, for large + values of LWORK, single-precision floating point is not sufficient + to hold the exact value --- some LAPACK versions (<= 3.5.0 at + least) truncate the returned integer to single precision and in + some cases this can be smaller than the required value. + + Examples + -------- + >>> from scipy.linalg import lapack + >>> n = 5000 + >>> s_r, s_lw = lapack.get_lapack_funcs(('sysvx', 'sysvx_lwork')) + >>> lwork = lapack._compute_lwork(s_lw, n) + >>> lwork + 32000 + + """ + dtype = getattr(routine, 'dtype', None) + int_dtype = getattr(routine, 'int_dtype', None) + ret = routine(*args, **kwargs) + if ret[-1] != 0: + raise ValueError("Internal work array size computation failed: " + "%d" % (ret[-1],)) + + if len(ret) == 2: + return _check_work_float(ret[0].real, dtype, int_dtype) + else: + return tuple(_check_work_float(x.real, dtype, int_dtype) + for x in ret[:-1]) + + +def _check_work_float(value, dtype, int_dtype): + """ + Convert LAPACK-returned work array size float to integer, + carefully for single-precision types. + """ + + if dtype == np.float32 or dtype == np.complex64: + # Single-precision routine -- take next fp value to work + # around possible truncation in LAPACK code + value = np.nextafter(value, np.inf, dtype=np.float32) + + value = int(value) + if int_dtype.itemsize == 4: + if value < 0 or value > _int32_max: + raise ValueError("Too large work array required -- computation " + "cannot be performed with standard 32-bit" + " LAPACK.") + elif int_dtype.itemsize == 8: + if value < 0 or value > _int64_max: + raise ValueError("Too large work array required -- computation" + " cannot be performed with standard 64-bit" + " LAPACK.") + return value diff --git a/shared/package-files/d1/d1bd9ab7311f6f61b5dc1a2da1621195cae550700f931bf548a3255c8074be2a/blob b/shared/package-files/d1/d1bd9ab7311f6f61b5dc1a2da1621195cae550700f931bf548a3255c8074be2a/blob new file mode 100644 index 0000000000000000000000000000000000000000..fc8a904d06026119fb14be7ced171f184d44e58b Binary files /dev/null and b/shared/package-files/d1/d1bd9ab7311f6f61b5dc1a2da1621195cae550700f931bf548a3255c8074be2a/blob differ diff --git a/shared/package-files/d1/d1be34a3a3e5bf3bd409b1a7349fbdec1804fbc6712d88caf4fb828eca33b73c/blob b/shared/package-files/d1/d1be34a3a3e5bf3bd409b1a7349fbdec1804fbc6712d88caf4fb828eca33b73c/blob new file mode 100644 index 0000000000000000000000000000000000000000..c05b3ec76c2e9a3acbc947842e0a849f5ba837e0 --- /dev/null +++ b/shared/package-files/d1/d1be34a3a3e5bf3bd409b1a7349fbdec1804fbc6712d88caf4fb828eca33b73c/blob @@ -0,0 +1,251 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* ellik.c + * + * Incomplete elliptic integral of the first kind + * + * + * + * SYNOPSIS: + * + * double phi, m, y, ellik(); + * + * y = ellik( phi, m ); + * + * + * + * DESCRIPTION: + * + * Approximates the integral + * + * + * + * phi + * - + * | | + * | dt + * F(phi | m) = | ------------------ + * | 2 + * | | sqrt( 1 - m sin t ) + * - + * 0 + * + * of amplitude phi and modulus m, using the arithmetic - + * geometric mean algorithm. + * + * + * + * + * ACCURACY: + * + * Tested at random points with m in [0, 1] and phi as indicated. + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE -10,10 200000 7.4e-16 1.0e-16 + * + * + */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1984, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +/* Copyright 2014, Eric W. Moore */ + +/* Incomplete elliptic integral of first kind */ +#pragma once + +#include "../config.h" +#include "../error.h" +#include "const.h" +#include "ellpk.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + /* To calculate legendre's incomplete elliptical integral of the first kind for + * negative m, we use a power series in phi for small m*phi*phi, an asymptotic + * series in m for large m*phi*phi* and the relation to Carlson's symmetric + * integral of the first kind. + * + * F(phi, m) = sin(phi) * R_F(cos(phi)^2, 1 - m * sin(phi)^2, 1.0) + * = R_F(c-1, c-m, c) + * + * where c = csc(phi)^2. We use the second form of this for (approximately) + * phi > 1/(sqrt(DBL_MAX) ~ 1e-154, where csc(phi)^2 overflows. Elsewhere we + * use the first form, accounting for the smallness of phi. + * + * The algorithm used is described in Carlson, B. C. Numerical computation of + * real or complex elliptic integrals. (1994) https://arxiv.org/abs/math/9409227 + * Most variable names reflect Carlson's usage. + * + * In this routine, we assume m < 0 and 0 > phi > pi/2. + */ + XSF_HOST_DEVICE inline double ellik_neg_m(double phi, double m) { + double x, y, z, x1, y1, z1, A0, A, Q, X, Y, Z, E2, E3, scale; + int n = 0; + double mpp = (m * phi) * phi; + + if (-mpp < 1e-6 && phi < -m) { + return phi + (-mpp * phi * phi / 30.0 + 3.0 * mpp * mpp / 40.0 + mpp / 6.0) * phi; + } + + if (-mpp > 4e7) { + double sm = std::sqrt(-m); + double sp = std::sin(phi); + double cp = std::cos(phi); + + double a = std::log(4 * sp * sm / (1 + cp)); + double b = -(1 + cp / sp / sp - a) / 4 / m; + return (a + b) / sm; + } + + if (phi > 1e-153 && m > -1e305) { + double s = std::sin(phi); + double csc2 = 1.0 / (s * s); + scale = 1.0; + x = 1.0 / (std::tan(phi) * std::tan(phi)); + y = csc2 - m; + z = csc2; + } else { + scale = phi; + x = 1.0; + y = 1 - m * scale * scale; + z = 1.0; + } + + if (x == y && x == z) { + return scale / std::sqrt(x); + } + + A0 = (x + y + z) / 3.0; + A = A0; + x1 = x; + y1 = y; + z1 = z; + /* Carlson gives 1/pow(3*r, 1.0/6.0) for this constant. if r == eps, + * it is ~338.38. */ + Q = 400.0 * std::fmax(std::abs(A0 - x), std::fmax(std::abs(A0 - y), std::abs(A0 - z))); + + while (Q > std::abs(A) && n <= 100) { + double sx = std::sqrt(x1); + double sy = std::sqrt(y1); + double sz = std::sqrt(z1); + double lam = sx * sy + sx * sz + sy * sz; + x1 = (x1 + lam) / 4.0; + y1 = (y1 + lam) / 4.0; + z1 = (z1 + lam) / 4.0; + A = (x1 + y1 + z1) / 3.0; + n += 1; + Q /= 4; + } + X = (A0 - x) / A / (1 << 2 * n); + Y = (A0 - y) / A / (1 << 2 * n); + Z = -(X + Y); + + E2 = X * Y - Z * Z; + E3 = X * Y * Z; + + return scale * (1.0 - E2 / 10.0 + E3 / 14.0 + E2 * E2 / 24.0 - 3.0 * E2 * E3 / 44.0) / sqrt(A); + } + + } // namespace detail + + XSF_HOST_DEVICE inline double ellik(double phi, double m) { + double a, b, c, e, temp, t, K, denom, npio2; + int d, mod, sign; + + if (std::isnan(phi) || std::isnan(m)) + return std::numeric_limits::quiet_NaN(); + if (m > 1.0) + return std::numeric_limits::quiet_NaN(); + if (std::isinf(phi) || std::isinf(m)) { + if (std::isinf(m) && std::isfinite(phi)) + return 0.0; + else if (std::isinf(phi) && std::isfinite(m)) + return phi; + else + return std::numeric_limits::quiet_NaN(); + } + if (m == 0.0) + return (phi); + a = 1.0 - m; + if (a == 0.0) { + if (std::abs(phi) >= (double) M_PI_2) { + set_error("ellik", SF_ERROR_SINGULAR, NULL); + return (std::numeric_limits::infinity()); + } + /* DLMF 19.6.8, and 4.23.42 */ + return std::asinh(std::tan(phi)); + } + npio2 = floor(phi / M_PI_2); + if (std::fmod(std::abs(npio2), 2.0) == 1.0) + npio2 += 1; + if (npio2 != 0.0) { + K = ellpk(a); + phi = phi - npio2 * M_PI_2; + } else + K = 0.0; + if (phi < 0.0) { + phi = -phi; + sign = -1; + } else + sign = 0; + if (a > 1.0) { + temp = detail::ellik_neg_m(phi, m); + goto done; + } + b = std::sqrt(a); + t = std::tan(phi); + if (std::abs(t) > 10.0) { + /* Transform the amplitude */ + e = 1.0 / (b * t); + /* ... but avoid multiple recursions. */ + if (std::abs(e) < 10.0) { + e = std::atan(e); + if (npio2 == 0) + K = ellpk(a); + temp = K - ellik(e, m); + goto done; + } + } + a = 1.0; + c = std::sqrt(m); + d = 1; + mod = 0; + + while (std::abs(c / a) > detail::MACHEP) { + temp = b / a; + phi = phi + atan(t * temp) + mod * M_PI; + denom = 1.0 - temp * t * t; + if (std::abs(denom) > 10 * detail::MACHEP) { + t = t * (1.0 + temp) / denom; + mod = (phi + M_PI_2) / M_PI; + } else { + t = std::tan(phi); + mod = static_cast(std::floor((phi - std::atan(t)) / M_PI)); + } + c = (a - b) / 2.0; + temp = std::sqrt(a * b); + a = (a + b) / 2.0; + b = temp; + d += d; + } + + temp = (std::atan(t) + mod * M_PI) / (d * a); + + done: + if (sign < 0) + temp = -temp; + temp += npio2 * K; + return (temp); + } + +} // namespace cephes +} // namespace xsf diff --git a/shared/package-files/d1/d1c113f8c459dafd0c787a8b83d5eab9b832581d37c6c0f742613ebc1285ef70/blob b/shared/package-files/d1/d1c113f8c459dafd0c787a8b83d5eab9b832581d37c6c0f742613ebc1285ef70/blob new file mode 100644 index 0000000000000000000000000000000000000000..4df9c279030cbf0317283736c78b7af8c9db60f3 --- /dev/null +++ b/shared/package-files/d1/d1c113f8c459dafd0c787a8b83d5eab9b832581d37c6c0f742613ebc1285ef70/blob @@ -0,0 +1,20 @@ +# Basic unittests to test functioning of module's top-level + + +__author__ = "Yaroslav Halchenko" +__license__ = "BSD" + + +try: + from sklearn import * # noqa: F403 + + _top_import_error = None +except Exception as e: + _top_import_error = e + + +def test_import_skl(): + # Test either above import has failed for some reason + # "import *" is discouraged outside of the module level, hence we + # rely on setting up the variable above + assert _top_import_error is None diff --git a/shared/package-files/d1/d1c200bc0469e30e09c37f13daa64a83b443fd46723d55833980b4c77006ba71/blob b/shared/package-files/d1/d1c200bc0469e30e09c37f13daa64a83b443fd46723d55833980b4c77006ba71/blob new file mode 100644 index 0000000000000000000000000000000000000000..82c7ca8f88c8cb88428ccf75776596fbbbc0fa3f --- /dev/null +++ b/shared/package-files/d1/d1c200bc0469e30e09c37f13daa64a83b443fd46723d55833980b4c77006ba71/blob @@ -0,0 +1,20 @@ +import numpy as np +from numba import vectorize +from numba.cuda.testing import skip_on_cudasim, CUDATestCase +import unittest + + +@skip_on_cudasim('ufunc API unsupported in the simulator') +class TestVectorizeComplex(CUDATestCase): + def test_vectorize_complex(self): + @vectorize(['complex128(complex128)'], target='cuda') + def vcomp(a): + return a * a + 1. + + A = np.arange(5, dtype=np.complex128) + B = vcomp(A) + self.assertTrue(np.allclose(A * A + 1., B)) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/d1/d1c222f12ea73a22fcb7e1b4fdbcd65cd7f8c68eb514fbcc750d31f4036bbe4a/blob b/shared/package-files/d1/d1c222f12ea73a22fcb7e1b4fdbcd65cd7f8c68eb514fbcc750d31f4036bbe4a/blob new file mode 100644 index 0000000000000000000000000000000000000000..bfa309af06797c40581b6b063b5f2a79840f753b Binary files /dev/null and b/shared/package-files/d1/d1c222f12ea73a22fcb7e1b4fdbcd65cd7f8c68eb514fbcc750d31f4036bbe4a/blob differ diff --git a/shared/package-files/d1/d1c2b1595502db951f40941c0231496bbdcc404f5e498a8a497183c7b900ab8f/blob b/shared/package-files/d1/d1c2b1595502db951f40941c0231496bbdcc404f5e498a8a497183c7b900ab8f/blob new file mode 100644 index 0000000000000000000000000000000000000000..6afd566750e9de31bd05c37c6e60dde3d7172db7 --- /dev/null +++ b/shared/package-files/d1/d1c2b1595502db951f40941c0231496bbdcc404f5e498a8a497183c7b900ab8f/blob @@ -0,0 +1,2 @@ +from matplotlib.testing.conftest import ( # noqa + mpl_test_settings, pytest_configure, pytest_unconfigure, pd, text_placeholders, xr) diff --git a/shared/package-files/d1/d1c2cd6d1088f758f2b5cec1cefdd70107d9cc50c5da0c6426e1f8e9e179bdec/blob b/shared/package-files/d1/d1c2cd6d1088f758f2b5cec1cefdd70107d9cc50c5da0c6426e1f8e9e179bdec/blob new file mode 100644 index 0000000000000000000000000000000000000000..56e942902a96e7f012479a582c5cf89511219f9a --- /dev/null +++ b/shared/package-files/d1/d1c2cd6d1088f758f2b5cec1cefdd70107d9cc50c5da0c6426e1f8e9e179bdec/blob @@ -0,0 +1,105 @@ +Metadata-Version: 2.1 +Name: Jinja2 +Version: 3.1.3 +Summary: A very fast and expressive template engine. +Home-page: https://palletsprojects.com/p/jinja/ +Maintainer: Pallets +Maintainer-email: contact@palletsprojects.com +License: BSD-3-Clause +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Documentation, https://jinja.palletsprojects.com/ +Project-URL: Changes, https://jinja.palletsprojects.com/changes/ +Project-URL: Source Code, https://github.com/pallets/jinja/ +Project-URL: Issue Tracker, https://github.com/pallets/jinja/issues/ +Project-URL: Chat, https://discord.gg/pallets +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content +Classifier: Topic :: Text Processing :: Markup :: HTML +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE.rst +Requires-Dist: MarkupSafe >=2.0 +Provides-Extra: i18n +Requires-Dist: Babel >=2.7 ; extra == 'i18n' + +Jinja +===== + +Jinja is a fast, expressive, extensible templating engine. Special +placeholders in the template allow writing code similar to Python +syntax. Then the template is passed data to render the final document. + +It includes: + +- Template inheritance and inclusion. +- Define and import macros within templates. +- HTML templates can use autoescaping to prevent XSS from untrusted + user input. +- A sandboxed environment can safely render untrusted templates. +- AsyncIO support for generating templates and calling async + functions. +- I18N support with Babel. +- Templates are compiled to optimized Python code just-in-time and + cached, or can be compiled ahead-of-time. +- Exceptions point to the correct line in templates to make debugging + easier. +- Extensible filters, tests, functions, and even syntax. + +Jinja's philosophy is that while application logic belongs in Python if +possible, it shouldn't make the template designer's job difficult by +restricting functionality too much. + + +Installing +---------- + +Install and update using `pip`_: + +.. code-block:: text + + $ pip install -U Jinja2 + +.. _pip: https://pip.pypa.io/en/stable/getting-started/ + + +In A Nutshell +------------- + +.. code-block:: jinja + + {% extends "base.html" %} + {% block title %}Members{% endblock %} + {% block content %} + + {% endblock %} + + +Donate +------ + +The Pallets organization develops and supports Jinja and other popular +packages. In order to grow the community of contributors and users, and +allow the maintainers to devote more time to the projects, `please +donate today`_. + +.. _please donate today: https://palletsprojects.com/donate + + +Links +----- + +- Documentation: https://jinja.palletsprojects.com/ +- Changes: https://jinja.palletsprojects.com/changes/ +- PyPI Releases: https://pypi.org/project/Jinja2/ +- Source Code: https://github.com/pallets/jinja/ +- Issue Tracker: https://github.com/pallets/jinja/issues/ +- Chat: https://discord.gg/pallets diff --git a/shared/package-files/d1/d1c330cdf2ba817ef2182b704695577149f44560d00c7f8700b339be8956036d/blob b/shared/package-files/d1/d1c330cdf2ba817ef2182b704695577149f44560d00c7f8700b339be8956036d/blob new file mode 100644 index 0000000000000000000000000000000000000000..cb1587eb50c141c05a0947036465ed849b8b5c50 --- /dev/null +++ b/shared/package-files/d1/d1c330cdf2ba817ef2182b704695577149f44560d00c7f8700b339be8956036d/blob @@ -0,0 +1,297 @@ +import pytest + +np = pytest.importorskip("numpy") +pytest.importorskip("scipy") + +import networkx as nx +from networkx.exception import NetworkXError +from networkx.generators.degree_seq import havel_hakimi_graph + + +def test_incidence_matrix_simple(): + deg = [3, 2, 2, 1, 0] + G = havel_hakimi_graph(deg) + deg = [(1, 0), (1, 0), (1, 0), (2, 0), (1, 0), (2, 1), (0, 1), (0, 1)] + MG = nx.random_clustered_graph(deg, seed=42) + + I = nx.incidence_matrix(G).todense().astype(int) + # fmt: off + expected = np.array( + [[1, 1, 1, 0], + [0, 1, 0, 1], + [1, 0, 0, 1], + [0, 0, 1, 0], + [0, 0, 0, 0]] + ) + # fmt: on + np.testing.assert_equal(I, expected) + + I = nx.incidence_matrix(MG).todense().astype(int) + # fmt: off + expected = np.array( + [[1, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 1, 0, 1]] + ) + # fmt: on + np.testing.assert_equal(I, expected) + + with pytest.raises(NetworkXError): + nx.incidence_matrix(G, nodelist=[0, 1]) + + +class TestGraphMatrix: + @classmethod + def setup_class(cls): + deg = [3, 2, 2, 1, 0] + cls.G = havel_hakimi_graph(deg) + # fmt: off + cls.OI = np.array( + [[-1, -1, -1, 0], + [1, 0, 0, -1], + [0, 1, 0, 1], + [0, 0, 1, 0], + [0, 0, 0, 0]] + ) + cls.A = np.array( + [[0, 1, 1, 1, 0], + [1, 0, 1, 0, 0], + [1, 1, 0, 0, 0], + [1, 0, 0, 0, 0], + [0, 0, 0, 0, 0]] + ) + # fmt: on + cls.WG = havel_hakimi_graph(deg) + cls.WG.add_edges_from( + (u, v, {"weight": 0.5, "other": 0.3}) for (u, v) in cls.G.edges() + ) + # fmt: off + cls.WA = np.array( + [[0, 0.5, 0.5, 0.5, 0], + [0.5, 0, 0.5, 0, 0], + [0.5, 0.5, 0, 0, 0], + [0.5, 0, 0, 0, 0], + [0, 0, 0, 0, 0]] + ) + # fmt: on + cls.MG = nx.MultiGraph(cls.G) + cls.MG2 = cls.MG.copy() + cls.MG2.add_edge(0, 1) + # fmt: off + cls.MG2A = np.array( + [[0, 2, 1, 1, 0], + [2, 0, 1, 0, 0], + [1, 1, 0, 0, 0], + [1, 0, 0, 0, 0], + [0, 0, 0, 0, 0]] + ) + cls.MGOI = np.array( + [[-1, -1, -1, -1, 0], + [1, 1, 0, 0, -1], + [0, 0, 1, 0, 1], + [0, 0, 0, 1, 0], + [0, 0, 0, 0, 0]] + ) + # fmt: on + cls.no_edges_G = nx.Graph([(1, 2), (3, 2, {"weight": 8})]) + cls.no_edges_A = np.array([[0, 0], [0, 0]]) + + def test_incidence_matrix(self): + "Conversion to incidence matrix" + I = ( + nx.incidence_matrix( + self.G, + nodelist=sorted(self.G), + edgelist=sorted(self.G.edges()), + oriented=True, + ) + .todense() + .astype(int) + ) + np.testing.assert_equal(I, self.OI) + + I = ( + nx.incidence_matrix( + self.G, + nodelist=sorted(self.G), + edgelist=sorted(self.G.edges()), + oriented=False, + ) + .todense() + .astype(int) + ) + np.testing.assert_equal(I, np.abs(self.OI)) + + I = ( + nx.incidence_matrix( + self.MG, + nodelist=sorted(self.MG), + edgelist=sorted(self.MG.edges()), + oriented=True, + ) + .todense() + .astype(int) + ) + np.testing.assert_equal(I, self.OI) + + I = ( + nx.incidence_matrix( + self.MG, + nodelist=sorted(self.MG), + edgelist=sorted(self.MG.edges()), + oriented=False, + ) + .todense() + .astype(int) + ) + np.testing.assert_equal(I, np.abs(self.OI)) + + I = ( + nx.incidence_matrix( + self.MG2, + nodelist=sorted(self.MG2), + edgelist=sorted(self.MG2.edges()), + oriented=True, + ) + .todense() + .astype(int) + ) + np.testing.assert_equal(I, self.MGOI) + + I = ( + nx.incidence_matrix( + self.MG2, + nodelist=sorted(self.MG), + edgelist=sorted(self.MG2.edges()), + oriented=False, + ) + .todense() + .astype(int) + ) + np.testing.assert_equal(I, np.abs(self.MGOI)) + + def test_weighted_incidence_matrix(self): + I = ( + nx.incidence_matrix( + self.WG, + nodelist=sorted(self.WG), + edgelist=sorted(self.WG.edges()), + oriented=True, + ) + .todense() + .astype(int) + ) + np.testing.assert_equal(I, self.OI) + + I = ( + nx.incidence_matrix( + self.WG, + nodelist=sorted(self.WG), + edgelist=sorted(self.WG.edges()), + oriented=False, + ) + .todense() + .astype(int) + ) + np.testing.assert_equal(I, np.abs(self.OI)) + + # np.testing.assert_equal(nx.incidence_matrix(self.WG,oriented=True, + # weight='weight').todense(),0.5*self.OI) + # np.testing.assert_equal(nx.incidence_matrix(self.WG,weight='weight').todense(), + # np.abs(0.5*self.OI)) + # np.testing.assert_equal(nx.incidence_matrix(self.WG,oriented=True,weight='other').todense(), + # 0.3*self.OI) + + I = nx.incidence_matrix( + self.WG, + nodelist=sorted(self.WG), + edgelist=sorted(self.WG.edges()), + oriented=True, + weight="weight", + ).todense() + np.testing.assert_equal(I, 0.5 * self.OI) + + I = nx.incidence_matrix( + self.WG, + nodelist=sorted(self.WG), + edgelist=sorted(self.WG.edges()), + oriented=False, + weight="weight", + ).todense() + np.testing.assert_equal(I, np.abs(0.5 * self.OI)) + + I = nx.incidence_matrix( + self.WG, + nodelist=sorted(self.WG), + edgelist=sorted(self.WG.edges()), + oriented=True, + weight="other", + ).todense() + np.testing.assert_equal(I, 0.3 * self.OI) + + # WMG=nx.MultiGraph(self.WG) + # WMG.add_edge(0,1,weight=0.5,other=0.3) + # np.testing.assert_equal(nx.incidence_matrix(WMG,weight='weight').todense(), + # np.abs(0.5*self.MGOI)) + # np.testing.assert_equal(nx.incidence_matrix(WMG,weight='weight',oriented=True).todense(), + # 0.5*self.MGOI) + # np.testing.assert_equal(nx.incidence_matrix(WMG,weight='other',oriented=True).todense(), + # 0.3*self.MGOI) + + WMG = nx.MultiGraph(self.WG) + WMG.add_edge(0, 1, weight=0.5, other=0.3) + + I = nx.incidence_matrix( + WMG, + nodelist=sorted(WMG), + edgelist=sorted(WMG.edges(keys=True)), + oriented=True, + weight="weight", + ).todense() + np.testing.assert_equal(I, 0.5 * self.MGOI) + + I = nx.incidence_matrix( + WMG, + nodelist=sorted(WMG), + edgelist=sorted(WMG.edges(keys=True)), + oriented=False, + weight="weight", + ).todense() + np.testing.assert_equal(I, np.abs(0.5 * self.MGOI)) + + I = nx.incidence_matrix( + WMG, + nodelist=sorted(WMG), + edgelist=sorted(WMG.edges(keys=True)), + oriented=True, + weight="other", + ).todense() + np.testing.assert_equal(I, 0.3 * self.MGOI) + + def test_adjacency_matrix(self): + "Conversion to adjacency matrix" + np.testing.assert_equal(nx.adjacency_matrix(self.G).todense(), self.A) + np.testing.assert_equal(nx.adjacency_matrix(self.MG).todense(), self.A) + np.testing.assert_equal(nx.adjacency_matrix(self.MG2).todense(), self.MG2A) + np.testing.assert_equal( + nx.adjacency_matrix(self.G, nodelist=[0, 1]).todense(), self.A[:2, :2] + ) + np.testing.assert_equal(nx.adjacency_matrix(self.WG).todense(), self.WA) + np.testing.assert_equal( + nx.adjacency_matrix(self.WG, weight=None).todense(), self.A + ) + np.testing.assert_equal( + nx.adjacency_matrix(self.MG2, weight=None).todense(), self.MG2A + ) + np.testing.assert_equal( + nx.adjacency_matrix(self.WG, weight="other").todense(), 0.6 * self.WA + ) + np.testing.assert_equal( + nx.adjacency_matrix(self.no_edges_G, nodelist=[1, 3]).todense(), + self.no_edges_A, + ) diff --git a/shared/package-files/d1/d1c51ec88733521b5a44c14f4ea1f01f553f466d5d8c2683d6f0db8bee83441a/blob b/shared/package-files/d1/d1c51ec88733521b5a44c14f4ea1f01f553f466d5d8c2683d6f0db8bee83441a/blob new file mode 100644 index 0000000000000000000000000000000000000000..e6e2ecdb8cd332a0a7806bdbc442c66124225077 --- /dev/null +++ b/shared/package-files/d1/d1c51ec88733521b5a44c14f4ea1f01f553f466d5d8c2683d6f0db8bee83441a/blob @@ -0,0 +1,264 @@ +''' Tests for fortran sequential files ''' + +import tempfile +import shutil +import os +from os import path +from glob import iglob +import threading +import re + +from numpy.testing import assert_equal, assert_allclose +import numpy as np +import pytest + +from scipy.io import (FortranFile, + _test_fortran, + FortranEOFError, + FortranFormattingError) + + +DATA_PATH = path.join(path.dirname(__file__), 'data') + + +@pytest.fixture +def io_lock(): + return threading.Lock() + + +def test_fortranfiles_read(io_lock): + for filename in iglob(path.join(DATA_PATH, "fortran-*-*x*x*.dat")): + m = re.search(r'fortran-([^-]+)-(\d+)x(\d+)x(\d+).dat', filename, re.I) + if not m: + raise RuntimeError(f"Couldn't match {filename} filename to regex") + + dims = (int(m.group(2)), int(m.group(3)), int(m.group(4))) + + dtype = m.group(1).replace('s', '<') + + with io_lock: + f = FortranFile(filename, 'r', ' 10 + assert len(np.unique(brc1.labels_)) == 10 + + # Test that n_clusters = Agglomerative Clustering gives + # the same results. + gc = AgglomerativeClustering(n_clusters=10) + brc2 = Birch(n_clusters=gc) + brc2.fit(X) + assert_array_equal(brc1.subcluster_labels_, brc2.subcluster_labels_) + assert_array_equal(brc1.labels_, brc2.labels_) + + # Test that a small number of clusters raises a warning. + brc4 = Birch(threshold=10000.0) + with pytest.warns(ConvergenceWarning): + brc4.fit(X) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sparse_X(global_random_seed, global_dtype, csr_container): + # Test that sparse and dense data give same results + X, y = make_blobs(n_samples=100, centers=10, random_state=global_random_seed) + X = X.astype(global_dtype, copy=False) + brc = Birch(n_clusters=10) + brc.fit(X) + + csr = csr_container(X) + brc_sparse = Birch(n_clusters=10) + brc_sparse.fit(csr) + + # Birch must preserve inputs' dtype + assert brc_sparse.subcluster_centers_.dtype == global_dtype + + assert_array_equal(brc.labels_, brc_sparse.labels_) + assert_allclose(brc.subcluster_centers_, brc_sparse.subcluster_centers_) + + +def test_partial_fit_second_call_error_checks(): + # second partial fit calls will error when n_features is not consistent + # with the first call + X, y = make_blobs(n_samples=100) + brc = Birch(n_clusters=3) + brc.partial_fit(X, y) + + msg = "X has 1 features, but Birch is expecting 2 features" + with pytest.raises(ValueError, match=msg): + brc.partial_fit(X[:, [0]], y) + + +def check_branching_factor(node, branching_factor): + subclusters = node.subclusters_ + assert branching_factor >= len(subclusters) + for cluster in subclusters: + if cluster.child_: + check_branching_factor(cluster.child_, branching_factor) + + +def test_branching_factor(global_random_seed, global_dtype): + # Test that nodes have at max branching_factor number of subclusters + X, y = make_blobs(random_state=global_random_seed) + X = X.astype(global_dtype, copy=False) + branching_factor = 9 + + # Purposefully set a low threshold to maximize the subclusters. + brc = Birch(n_clusters=None, branching_factor=branching_factor, threshold=0.01) + brc.fit(X) + check_branching_factor(brc.root_, branching_factor) + brc = Birch(n_clusters=3, branching_factor=branching_factor, threshold=0.01) + brc.fit(X) + check_branching_factor(brc.root_, branching_factor) + + +def check_threshold(birch_instance, threshold): + """Use the leaf linked list for traversal""" + current_leaf = birch_instance.dummy_leaf_.next_leaf_ + while current_leaf: + subclusters = current_leaf.subclusters_ + for sc in subclusters: + assert threshold >= sc.radius + current_leaf = current_leaf.next_leaf_ + + +def test_threshold(global_random_seed, global_dtype): + # Test that the leaf subclusters have a threshold lesser than radius + X, y = make_blobs(n_samples=80, centers=4, random_state=global_random_seed) + X = X.astype(global_dtype, copy=False) + brc = Birch(threshold=0.5, n_clusters=None) + brc.fit(X) + check_threshold(brc, 0.5) + + brc = Birch(threshold=5.0, n_clusters=None) + brc.fit(X) + check_threshold(brc, 5.0) + + +def test_birch_n_clusters_long_int(): + # Check that birch supports n_clusters with np.int64 dtype, for instance + # coming from np.arange. #16484 + X, _ = make_blobs(random_state=0) + n_clusters = np.int64(5) + Birch(n_clusters=n_clusters).fit(X) + + +def test_feature_names_out(): + """Check `get_feature_names_out` for `Birch`.""" + X, _ = make_blobs(n_samples=80, n_features=4, random_state=0) + brc = Birch(n_clusters=4) + brc.fit(X) + n_clusters = brc.subcluster_centers_.shape[0] + + names_out = brc.get_feature_names_out() + assert_array_equal([f"birch{i}" for i in range(n_clusters)], names_out) + + +def test_transform_match_across_dtypes(global_random_seed): + X, _ = make_blobs(n_samples=80, n_features=4, random_state=global_random_seed) + brc = Birch(n_clusters=4, threshold=1.1) + Y_64 = brc.fit_transform(X) + Y_32 = brc.fit_transform(X.astype(np.float32)) + + assert_allclose(Y_64, Y_32, atol=1e-6) + + +def test_subcluster_dtype(global_dtype): + X = make_blobs(n_samples=80, n_features=4, random_state=0)[0].astype( + global_dtype, copy=False + ) + brc = Birch(n_clusters=4) + assert brc.fit(X).subcluster_centers_.dtype == global_dtype + + +def test_both_subclusters_updated(): + """Check that both subclusters are updated when a node a split, even when there are + duplicated data points. Non-regression test for #23269. + """ + + X = np.array( + [ + [-2.6192791, -1.5053215], + [-2.9993038, -1.6863596], + [-2.3724914, -1.3438171], + [-2.336792, -1.3417323], + [-2.4089134, -1.3290224], + [-2.3724914, -1.3438171], + [-3.364009, -1.8846745], + [-2.3724914, -1.3438171], + [-2.617677, -1.5003285], + [-2.2960556, -1.3260119], + [-2.3724914, -1.3438171], + [-2.5459878, -1.4533926], + [-2.25979, -1.3003055], + [-2.4089134, -1.3290224], + [-2.3724914, -1.3438171], + [-2.4089134, -1.3290224], + [-2.5459878, -1.4533926], + [-2.3724914, -1.3438171], + [-2.9720619, -1.7058647], + [-2.336792, -1.3417323], + [-2.3724914, -1.3438171], + ], + dtype=np.float32, + ) + + # no error + Birch(branching_factor=5, threshold=1e-5, n_clusters=None).fit(X) + + +# TODO(1.8): Remove +def test_birch_copy_deprecated(): + X, _ = make_blobs(n_samples=80, n_features=4, random_state=0) + brc = Birch(n_clusters=4, copy=True) + with pytest.warns(FutureWarning, match="`copy` was deprecated"): + brc.fit(X) diff --git a/shared/package-files/d1/d1d1de31a0f0cac54002719596130e3f8b43962a2180d2b427193fcec3a25b1c/blob b/shared/package-files/d1/d1d1de31a0f0cac54002719596130e3f8b43962a2180d2b427193fcec3a25b1c/blob new file mode 100644 index 0000000000000000000000000000000000000000..f9e967c3c34788deba82540d787b2728775791ec --- /dev/null +++ b/shared/package-files/d1/d1d1de31a0f0cac54002719596130e3f8b43962a2180d2b427193fcec3a25b1c/blob @@ -0,0 +1,206 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations + +import io +from typing import IO, TYPE_CHECKING, Any, Mapping, cast + +from pip._vendor import msgpack +from pip._vendor.requests.structures import CaseInsensitiveDict +from pip._vendor.urllib3 import HTTPResponse + +if TYPE_CHECKING: + from pip._vendor.requests import PreparedRequest + + +class Serializer: + serde_version = "4" + + def dumps( + self, + request: PreparedRequest, + response: HTTPResponse, + body: bytes | None = None, + ) -> bytes: + response_headers: CaseInsensitiveDict[str] = CaseInsensitiveDict( + response.headers + ) + + if body is None: + # When a body isn't passed in, we'll read the response. We + # also update the response with a new file handler to be + # sure it acts as though it was never read. + body = response.read(decode_content=False) + response._fp = io.BytesIO(body) # type: ignore[attr-defined] + response.length_remaining = len(body) + + data = { + "response": { + "body": body, # Empty bytestring if body is stored separately + "headers": {str(k): str(v) for k, v in response.headers.items()}, # type: ignore[no-untyped-call] + "status": response.status, + "version": response.version, + "reason": str(response.reason), + "decode_content": response.decode_content, + } + } + + # Construct our vary headers + data["vary"] = {} + if "vary" in response_headers: + varied_headers = response_headers["vary"].split(",") + for header in varied_headers: + header = str(header).strip() + header_value = request.headers.get(header, None) + if header_value is not None: + header_value = str(header_value) + data["vary"][header] = header_value + + return b",".join([f"cc={self.serde_version}".encode(), self.serialize(data)]) + + def serialize(self, data: dict[str, Any]) -> bytes: + return cast(bytes, msgpack.dumps(data, use_bin_type=True)) + + def loads( + self, + request: PreparedRequest, + data: bytes, + body_file: IO[bytes] | None = None, + ) -> HTTPResponse | None: + # Short circuit if we've been given an empty set of data + if not data: + return None + + # Determine what version of the serializer the data was serialized + # with + try: + ver, data = data.split(b",", 1) + except ValueError: + ver = b"cc=0" + + # Make sure that our "ver" is actually a version and isn't a false + # positive from a , being in the data stream. + if ver[:3] != b"cc=": + data = ver + data + ver = b"cc=0" + + # Get the version number out of the cc=N + verstr = ver.split(b"=", 1)[-1].decode("ascii") + + # Dispatch to the actual load method for the given version + try: + return getattr(self, f"_loads_v{verstr}")(request, data, body_file) # type: ignore[no-any-return] + + except AttributeError: + # This is a version we don't have a loads function for, so we'll + # just treat it as a miss and return None + return None + + def prepare_response( + self, + request: PreparedRequest, + cached: Mapping[str, Any], + body_file: IO[bytes] | None = None, + ) -> HTTPResponse | None: + """Verify our vary headers match and construct a real urllib3 + HTTPResponse object. + """ + # Special case the '*' Vary value as it means we cannot actually + # determine if the cached response is suitable for this request. + # This case is also handled in the controller code when creating + # a cache entry, but is left here for backwards compatibility. + if "*" in cached.get("vary", {}): + return None + + # Ensure that the Vary headers for the cached response match our + # request + for header, value in cached.get("vary", {}).items(): + if request.headers.get(header, None) != value: + return None + + body_raw = cached["response"].pop("body") + + headers: CaseInsensitiveDict[str] = CaseInsensitiveDict( + data=cached["response"]["headers"] + ) + if headers.get("transfer-encoding", "") == "chunked": + headers.pop("transfer-encoding") + + cached["response"]["headers"] = headers + + try: + body: IO[bytes] + if body_file is None: + body = io.BytesIO(body_raw) + else: + body = body_file + except TypeError: + # This can happen if cachecontrol serialized to v1 format (pickle) + # using Python 2. A Python 2 str(byte string) will be unpickled as + # a Python 3 str (unicode string), which will cause the above to + # fail with: + # + # TypeError: 'str' does not support the buffer interface + body = io.BytesIO(body_raw.encode("utf8")) + + # Discard any `strict` parameter serialized by older version of cachecontrol. + cached["response"].pop("strict", None) + + return HTTPResponse(body=body, preload_content=False, **cached["response"]) + + def _loads_v0( + self, + request: PreparedRequest, + data: bytes, + body_file: IO[bytes] | None = None, + ) -> None: + # The original legacy cache data. This doesn't contain enough + # information to construct everything we need, so we'll treat this as + # a miss. + return None + + def _loads_v1( + self, + request: PreparedRequest, + data: bytes, + body_file: IO[bytes] | None = None, + ) -> HTTPResponse | None: + # The "v1" pickled cache format. This is no longer supported + # for security reasons, so we treat it as a miss. + return None + + def _loads_v2( + self, + request: PreparedRequest, + data: bytes, + body_file: IO[bytes] | None = None, + ) -> HTTPResponse | None: + # The "v2" compressed base64 cache format. + # This has been removed due to age and poor size/performance + # characteristics, so we treat it as a miss. + return None + + def _loads_v3( + self, + request: PreparedRequest, + data: bytes, + body_file: IO[bytes] | None = None, + ) -> None: + # Due to Python 2 encoding issues, it's impossible to know for sure + # exactly how to load v3 entries, thus we'll treat these as a miss so + # that they get rewritten out as v4 entries. + return None + + def _loads_v4( + self, + request: PreparedRequest, + data: bytes, + body_file: IO[bytes] | None = None, + ) -> HTTPResponse | None: + try: + cached = msgpack.loads(data, raw=False) + except ValueError: + return None + + return self.prepare_response(request, cached, body_file) diff --git a/shared/package-files/d1/d1d2927e6c01e894455995734d1322321cb0ba69c17f461e3915860fdd41e2be/blob b/shared/package-files/d1/d1d2927e6c01e894455995734d1322321cb0ba69c17f461e3915860fdd41e2be/blob new file mode 100644 index 0000000000000000000000000000000000000000..1d7e7f35b34f53b2d20287114e3c29dff369bb23 Binary files /dev/null and b/shared/package-files/d1/d1d2927e6c01e894455995734d1322321cb0ba69c17f461e3915860fdd41e2be/blob differ diff --git a/shared/package-files/d1/d1d37fc34bb310a453ad15642227d6ebce6f13631946d7b95eb40978c9e5b99a/blob b/shared/package-files/d1/d1d37fc34bb310a453ad15642227d6ebce6f13631946d7b95eb40978c9e5b99a/blob new file mode 100644 index 0000000000000000000000000000000000000000..22fd8b8b857d7c1b60fbd4c5033a7765e281cab6 --- /dev/null +++ b/shared/package-files/d1/d1d37fc34bb310a453ad15642227d6ebce6f13631946d7b95eb40978c9e5b99a/blob @@ -0,0 +1,161 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace c10 { + +// Represents a name of the form "foo.bar.baz" +struct QualifiedName { + QualifiedName() = default; + + // `name` can be a dotted string, like "foo.bar.baz", or just a bare name. + /* implicit */ QualifiedName(const std::string& name) { + TORCH_CHECK(!name.empty()); + // split the string into its atoms. + size_t startSearchFrom = 0; + size_t pos = name.find(delimiter_, startSearchFrom); + + while (pos != std::string::npos) { + auto atom = name.substr(startSearchFrom, pos - startSearchFrom); + TORCH_INTERNAL_ASSERT( + !atom.empty(), "Invalid name for qualified name: '", name, "'"); + atoms_.push_back(std::move(atom)); + startSearchFrom = pos + 1; + pos = name.find(delimiter_, startSearchFrom); + } + + auto finalAtom = name.substr(startSearchFrom); + TORCH_INTERNAL_ASSERT( + !finalAtom.empty(), "Invalid name for qualified name: '", name, "'"); + atoms_.emplace_back(std::move(finalAtom)); + + cacheAccessors(); + } + + explicit QualifiedName(std::vector atoms) : atoms_(std::move(atoms)) { + for (const auto& atom : atoms_) { + TORCH_CHECK(!atom.empty(), "Atom cannot be empty"); + TORCH_CHECK( + atom.find(delimiter_) == std::string::npos, + "Delimiter not allowed in atom"); + } + + cacheAccessors(); + } + // Unnecessary copy. Ideally we'd use something like std::string_view. + /* implicit */ QualifiedName(const char* name) + : QualifiedName(std::string(name)) {} + + // `name` must be a bare name (no dots!) + explicit QualifiedName(const QualifiedName& prefix, std::string name) { + TORCH_INTERNAL_ASSERT(!name.empty()); + TORCH_INTERNAL_ASSERT(name.find(delimiter_) == std::string::npos); + atoms_.insert(atoms_.begin(), prefix.atoms_.begin(), prefix.atoms_.end()); + atoms_.push_back(std::move(name)); + + cacheAccessors(); + } + + // Is `this` a prefix of `other`? + // For example, "foo.bar" is a prefix of "foo.bar.baz" + bool isPrefixOf(const QualifiedName& other) const { + const auto& thisAtoms = atoms_; + const auto& otherAtoms = other.atoms_; + + if (thisAtoms.size() > otherAtoms.size()) { + // Can't be a prefix if it's bigger + return false; + } + for (const auto i : c10::irange(thisAtoms.size())) { + if (thisAtoms[i] != otherAtoms[i]) { + return false; + } + } + return true; + } + + // The fully qualified name, like "foo.bar.baz" + const std::string& qualifiedName() const { + return qualifiedName_; + } + + // The leading qualifier, like "foo.bar" + const std::string& prefix() const { + return prefix_; + } + + // The base name, like "baz" + const std::string& name() const { + return name_; + } + + const std::vector& atoms() const { + return atoms_; + } + + bool operator==(const QualifiedName& other) const { + return this->qualifiedName_ == other.qualifiedName_; + } + + bool operator!=(const QualifiedName& other) const { + return !(*this == other); + } + + private: + static constexpr char delimiter_ = '.'; + + // Helper for cacheAccessors() below. + template + std::string join(char delimiter, const T& v) { + std::string out; + size_t reserve = 0; + for (const auto& e : v) { + reserve += e.size() + 1; + } + out.reserve(reserve); + for (const auto i : c10::irange(v.size())) { + if (i != 0) { + out.push_back(delimiter); + } + out.append(v[i]); + } + return out; + } + + void cacheAccessors() { + qualifiedName_ = join(delimiter_, atoms_); + if (atoms_.size() > 1) { + ArrayRef view(atoms_); + const auto prefixView = view.slice(0, view.size() - 1); + prefix_ = join(delimiter_, prefixView); + } + + if (!atoms_.empty()) { + name_ = atoms_.back(); + } + } + + // The actual list of names, like "{foo, bar, baz}" + std::vector atoms_; + + /* + * Cached accessors, derived from `atoms_`. + */ + std::string qualifiedName_; + std::string prefix_; + std::string name_; +}; +} // namespace c10 + +namespace std { +template <> +struct hash { + size_t operator()(const c10::QualifiedName& n) const noexcept { + return std::hash()(n.qualifiedName()); + } +}; +} // namespace std diff --git a/shared/package-files/d1/d1d576bb5ec8ffe9be7ab7a4419fac1d92f68153be77b24dfe8049dc2b5786a4/blob b/shared/package-files/d1/d1d576bb5ec8ffe9be7ab7a4419fac1d92f68153be77b24dfe8049dc2b5786a4/blob new file mode 100644 index 0000000000000000000000000000000000000000..0e35b5b5396c5aaed15d3a48e4238e2fe1282346 Binary files /dev/null and b/shared/package-files/d1/d1d576bb5ec8ffe9be7ab7a4419fac1d92f68153be77b24dfe8049dc2b5786a4/blob differ diff --git a/shared/package-files/d1/d1d5a9c46007eb63d08058eeebf5b05d8a570b7575577b1b4c54d0fd80b38cc2/blob b/shared/package-files/d1/d1d5a9c46007eb63d08058eeebf5b05d8a570b7575577b1b4c54d0fd80b38cc2/blob new file mode 100644 index 0000000000000000000000000000000000000000..445c6e6f1589cb70e8588fafa204addf491a5cc9 --- /dev/null +++ b/shared/package-files/d1/d1d5a9c46007eb63d08058eeebf5b05d8a570b7575577b1b4c54d0fd80b38cc2/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _chunk_cat { + using schema = at::Tensor (at::TensorList, int64_t, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_chunk_cat") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_chunk_cat(Tensor[] tensors, int dim, int num_chunks) -> Tensor") + static at::Tensor call(at::TensorList tensors, int64_t dim, int64_t num_chunks); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, int64_t dim, int64_t num_chunks); +}; + +struct TORCH_API _chunk_cat_out { + using schema = at::Tensor & (at::TensorList, int64_t, int64_t, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_chunk_cat") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_chunk_cat.out(Tensor[] tensors, int dim, int num_chunks, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(at::TensorList tensors, int64_t dim, int64_t num_chunks, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, int64_t dim, int64_t num_chunks, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/d1/d1d94ea161c111c919887150c8568772c71e66e40b887368cf8926bc94db6c8b/blob b/shared/package-files/d1/d1d94ea161c111c919887150c8568772c71e66e40b887368cf8926bc94db6c8b/blob new file mode 100644 index 0000000000000000000000000000000000000000..f94ed9ab8e8875d49c56b45f2f8a00451280b623 --- /dev/null +++ b/shared/package-files/d1/d1d94ea161c111c919887150c8568772c71e66e40b887368cf8926bc94db6c8b/blob @@ -0,0 +1,91 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::replication_pad1d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & replication_pad1d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding) { + return at::_ops::replication_pad1d_backward_grad_input::call(grad_output, self, c10::fromIntArrayRefSlow(padding), grad_input); +} +namespace symint { + template ::value>> + at::Tensor & replication_pad1d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding) { + return at::_ops::replication_pad1d_backward_grad_input::call(grad_output, self, c10::fromIntArrayRefSlow(padding), grad_input); + } +} + +// aten::replication_pad1d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & replication_pad1d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding, at::Tensor & grad_input) { + return at::_ops::replication_pad1d_backward_grad_input::call(grad_output, self, c10::fromIntArrayRefSlow(padding), grad_input); +} +namespace symint { + template ::value>> + at::Tensor & replication_pad1d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding, at::Tensor & grad_input) { + return at::_ops::replication_pad1d_backward_grad_input::call(grad_output, self, c10::fromIntArrayRefSlow(padding), grad_input); + } +} + +// aten::replication_pad1d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & replication_pad1d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding) { + return at::_ops::replication_pad1d_backward_grad_input::call(grad_output, self, padding, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & replication_pad1d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding) { + return at::_ops::replication_pad1d_backward_grad_input::call(grad_output, self, padding, grad_input); + } +} + +// aten::replication_pad1d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & replication_pad1d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & grad_input) { + return at::_ops::replication_pad1d_backward_grad_input::call(grad_output, self, padding, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & replication_pad1d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & grad_input) { + return at::_ops::replication_pad1d_backward_grad_input::call(grad_output, self, padding, grad_input); + } +} + +// aten::replication_pad1d_backward(Tensor grad_output, Tensor self, SymInt[2] padding) -> Tensor +inline at::Tensor replication_pad1d_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding) { + return at::_ops::replication_pad1d_backward::call(grad_output, self, c10::fromIntArrayRefSlow(padding)); +} +namespace symint { + template ::value>> + at::Tensor replication_pad1d_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding) { + return at::_ops::replication_pad1d_backward::call(grad_output, self, c10::fromIntArrayRefSlow(padding)); + } +} + +// aten::replication_pad1d_backward(Tensor grad_output, Tensor self, SymInt[2] padding) -> Tensor +inline at::Tensor replication_pad1d_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding) { + return at::_ops::replication_pad1d_backward::call(grad_output, self, padding); +} +namespace symint { + template ::value>> + at::Tensor replication_pad1d_backward(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding) { + return at::_ops::replication_pad1d_backward::call(grad_output, self, padding); + } +} + +} diff --git a/shared/package-files/d1/d1d9b38ab3a20c6e17a38d519ee412ecaf6b918df18c78956ac7c330d4ea08dc/blob b/shared/package-files/d1/d1d9b38ab3a20c6e17a38d519ee412ecaf6b918df18c78956ac7c330d4ea08dc/blob new file mode 100644 index 0000000000000000000000000000000000000000..774b0219b5932a0ee1c27e637371de5ba8d9cb16 --- /dev/null +++ b/shared/package-files/d1/d1d9b38ab3a20c6e17a38d519ee412ecaf6b918df18c78956ac7c330d4ea08dc/blob @@ -0,0 +1,185 @@ +# This module contains abstractions for the input stream. You don't have to +# looks further, there are no pretty code. +# +# We define two classes here. +# +# Mark(source, line, column) +# It's just a record and its only use is producing nice error messages. +# Parser does not use it for any other purposes. +# +# Reader(source, data) +# Reader determines the encoding of `data` and converts it to unicode. +# Reader provides the following methods and attributes: +# reader.peek(length=1) - return the next `length` characters +# reader.forward(length=1) - move the current position to `length` characters. +# reader.index - the number of the current character. +# reader.line, stream.column - the line and the column of the current character. + +__all__ = ['Reader', 'ReaderError'] + +from .error import YAMLError, Mark + +import codecs, re + +class ReaderError(YAMLError): + + def __init__(self, name, position, character, encoding, reason): + self.name = name + self.character = character + self.position = position + self.encoding = encoding + self.reason = reason + + def __str__(self): + if isinstance(self.character, bytes): + return "'%s' codec can't decode byte #x%02x: %s\n" \ + " in \"%s\", position %d" \ + % (self.encoding, ord(self.character), self.reason, + self.name, self.position) + else: + return "unacceptable character #x%04x: %s\n" \ + " in \"%s\", position %d" \ + % (self.character, self.reason, + self.name, self.position) + +class Reader(object): + # Reader: + # - determines the data encoding and converts it to a unicode string, + # - checks if characters are in allowed range, + # - adds '\0' to the end. + + # Reader accepts + # - a `bytes` object, + # - a `str` object, + # - a file-like object with its `read` method returning `str`, + # - a file-like object with its `read` method returning `unicode`. + + # Yeah, it's ugly and slow. + + def __init__(self, stream): + self.name = None + self.stream = None + self.stream_pointer = 0 + self.eof = True + self.buffer = '' + self.pointer = 0 + self.raw_buffer = None + self.raw_decode = None + self.encoding = None + self.index = 0 + self.line = 0 + self.column = 0 + if isinstance(stream, str): + self.name = "" + self.check_printable(stream) + self.buffer = stream+'\0' + elif isinstance(stream, bytes): + self.name = "" + self.raw_buffer = stream + self.determine_encoding() + else: + self.stream = stream + self.name = getattr(stream, 'name', "") + self.eof = False + self.raw_buffer = None + self.determine_encoding() + + def peek(self, index=0): + try: + return self.buffer[self.pointer+index] + except IndexError: + self.update(index+1) + return self.buffer[self.pointer+index] + + def prefix(self, length=1): + if self.pointer+length >= len(self.buffer): + self.update(length) + return self.buffer[self.pointer:self.pointer+length] + + def forward(self, length=1): + if self.pointer+length+1 >= len(self.buffer): + self.update(length+1) + while length: + ch = self.buffer[self.pointer] + self.pointer += 1 + self.index += 1 + if ch in '\n\x85\u2028\u2029' \ + or (ch == '\r' and self.buffer[self.pointer] != '\n'): + self.line += 1 + self.column = 0 + elif ch != '\uFEFF': + self.column += 1 + length -= 1 + + def get_mark(self): + if self.stream is None: + return Mark(self.name, self.index, self.line, self.column, + self.buffer, self.pointer) + else: + return Mark(self.name, self.index, self.line, self.column, + None, None) + + def determine_encoding(self): + while not self.eof and (self.raw_buffer is None or len(self.raw_buffer) < 2): + self.update_raw() + if isinstance(self.raw_buffer, bytes): + if self.raw_buffer.startswith(codecs.BOM_UTF16_LE): + self.raw_decode = codecs.utf_16_le_decode + self.encoding = 'utf-16-le' + elif self.raw_buffer.startswith(codecs.BOM_UTF16_BE): + self.raw_decode = codecs.utf_16_be_decode + self.encoding = 'utf-16-be' + else: + self.raw_decode = codecs.utf_8_decode + self.encoding = 'utf-8' + self.update(1) + + NON_PRINTABLE = re.compile('[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]') + def check_printable(self, data): + match = self.NON_PRINTABLE.search(data) + if match: + character = match.group() + position = self.index+(len(self.buffer)-self.pointer)+match.start() + raise ReaderError(self.name, position, ord(character), + 'unicode', "special characters are not allowed") + + def update(self, length): + if self.raw_buffer is None: + return + self.buffer = self.buffer[self.pointer:] + self.pointer = 0 + while len(self.buffer) < length: + if not self.eof: + self.update_raw() + if self.raw_decode is not None: + try: + data, converted = self.raw_decode(self.raw_buffer, + 'strict', self.eof) + except UnicodeDecodeError as exc: + character = self.raw_buffer[exc.start] + if self.stream is not None: + position = self.stream_pointer-len(self.raw_buffer)+exc.start + else: + position = exc.start + raise ReaderError(self.name, position, character, + exc.encoding, exc.reason) + else: + data = self.raw_buffer + converted = len(data) + self.check_printable(data) + self.buffer += data + self.raw_buffer = self.raw_buffer[converted:] + if self.eof: + self.buffer += '\0' + self.raw_buffer = None + break + + def update_raw(self, size=4096): + data = self.stream.read(size) + if self.raw_buffer is None: + self.raw_buffer = data + else: + self.raw_buffer += data + self.stream_pointer += len(data) + if not data: + self.eof = True diff --git a/shared/package-files/d1/d1d9dae9d3f48ae9cc2deb8f48fd4141c36314b34a7496f6df34d30f79a7af88/blob b/shared/package-files/d1/d1d9dae9d3f48ae9cc2deb8f48fd4141c36314b34a7496f6df34d30f79a7af88/blob new file mode 100644 index 0000000000000000000000000000000000000000..b1d28620f108e0b6e13b3c11ceb8d2d890e011dc --- /dev/null +++ b/shared/package-files/d1/d1d9dae9d3f48ae9cc2deb8f48fd4141c36314b34a7496f6df34d30f79a7af88/blob @@ -0,0 +1,472 @@ +from __future__ import annotations + +from collections.abc import Iterator, Mapping, Sequence, Sized +from itertools import chain +from typing import TYPE_CHECKING, Any, Final, Literal, Protocol, TypeVar, overload + +from narwhals._compliant.typing import ( + CompliantDataFrameAny, + CompliantExprT_contra, + CompliantLazyFrameAny, + CompliantNamespaceAny, + CompliantSeriesT, + EagerExprT, + EagerSeriesT, + NativeDataFrameT, + NativeLazyFrameT, + NativeSeriesT, +) +from narwhals._translate import ( + ArrowConvertible, + DictConvertible, + FromNative, + NumpyConvertible, + ToNarwhals, + ToNarwhalsT_co, +) +from narwhals._typing_compat import assert_never +from narwhals._utils import ( + ValidateBackendVersion, + Version, + _StoresNative, + check_columns_exist, + is_boolean_selector, + is_compliant_series, + is_index_selector, + is_range, + is_sequence_like, + is_sized_multi_index_selector, + is_slice_index, + is_slice_none, +) +from narwhals.exceptions import MultiOutputExpressionError + +if TYPE_CHECKING: + from io import BytesIO + from pathlib import Path + from types import ModuleType + from typing import TypeAlias + + import pandas as pd + import polars as pl + import pyarrow as pa + from typing_extensions import Self + + from narwhals._compliant.group_by import CompliantGroupBy, DataFrameGroupBy + from narwhals._compliant.namespace import EagerNamespace + from narwhals._spark_like.utils import SparkSession + from narwhals._translate import IntoArrowTable + from narwhals._typing import _EagerAllowedImpl, _LazyAllowedImpl + from narwhals._utils import Implementation, _LimitedContext + from narwhals.dataframe import DataFrame + from narwhals.dtypes import DType + from narwhals.exceptions import ColumnNotFoundError + from narwhals.typing import ( + AsofJoinStrategy, + IntoDType, + JoinStrategy, + MultiColSelector, + MultiIndexSelector, + PivotAgg, + SingleIndexSelector, + SizedMultiIndexSelector, + SizedMultiNameSelector, + SizeUnit, + UniqueKeepStrategy, + _2DArray, + _SliceIndex, + _SliceName, + ) + + Incomplete: TypeAlias = Any + +MYPY: Final = False + +__all__ = ["CompliantDataFrame", "CompliantFrame", "CompliantLazyFrame", "EagerDataFrame"] + +T = TypeVar("T") + +_ToDict: TypeAlias = "dict[str, CompliantSeriesT] | dict[str, list[Any]]" # noqa: PYI047 + +_NativeFrameT = TypeVar("_NativeFrameT") + + +class CompliantFrame( + _StoresNative[_NativeFrameT], + FromNative[_NativeFrameT], + ToNarwhals[ToNarwhalsT_co], + Protocol[CompliantExprT_contra, _NativeFrameT, ToNarwhalsT_co], +): + """Common parts of `DataFrame`, `LazyFrame`.""" + + _native_frame: _NativeFrameT + _implementation: Implementation + _version: Version + + def __native_namespace__(self) -> ModuleType: ... + def __narwhals_namespace__(self) -> Any: ... + def _with_native(self, df: _NativeFrameT) -> Self: ... + def _with_version(self, version: Version) -> Self: ... + @classmethod + def from_native(cls, data: _NativeFrameT, /, *, context: _LimitedContext) -> Self: ... + @property + def columns(self) -> Sequence[str]: ... + @property + def native(self) -> _NativeFrameT: + return self._native_frame + + @property + def schema(self) -> Mapping[str, DType]: ... + + def collect_schema(self) -> Mapping[str, DType]: ... + def drop(self, columns: Sequence[str], *, strict: bool) -> Self: ... + def drop_nulls(self, subset: Sequence[str] | None) -> Self: ... + def explode(self, columns: Sequence[str]) -> Self: ... + def filter(self, predicate: CompliantExprT_contra | Incomplete) -> Self: ... + def group_by( + self, + keys: Sequence[str] | Sequence[CompliantExprT_contra], + *, + drop_null_keys: bool, + ) -> CompliantGroupBy[Self, CompliantExprT_contra]: ... + def head(self, n: int) -> Self: ... + def join( + self, + other: Self, + *, + how: JoinStrategy, + left_on: Sequence[str] | None, + right_on: Sequence[str] | None, + suffix: str, + ) -> Self: ... + def join_asof( + self, + other: Self, + *, + left_on: str, + right_on: str, + by_left: Sequence[str] | None, + by_right: Sequence[str] | None, + strategy: AsofJoinStrategy, + suffix: str, + ) -> Self: ... + def rename(self, mapping: Mapping[str, str]) -> Self: ... + def cast(self, dtypes: Mapping[str, IntoDType]) -> Self: + ns = self.__narwhals_namespace__() + return self.with_columns( + *(ns.col(name).cast(dtype) for name, dtype in dtypes.items()) + ) + + def select(self, *exprs: CompliantExprT_contra) -> Self: ... + def simple_select(self, *column_names: str) -> Self: + """`select` where all args are column names.""" + ... + + def sort( + self, *by: str, descending: bool | Sequence[bool], nulls_last: bool + ) -> Self: ... + def unique( + self, + subset: Sequence[str] | None, + *, + keep: UniqueKeepStrategy, + order_by: Sequence[str] | None, + ) -> Self: ... + def unpivot( + self, + on: Sequence[str] | None, + index: Sequence[str] | None, + variable_name: str, + value_name: str, + ) -> Self: ... + def with_columns(self, *exprs: CompliantExprT_contra) -> Self: ... + def with_row_index(self, name: str, order_by: Sequence[str]) -> Self: ... + + +class CompliantDataFrame( + NumpyConvertible["_2DArray", "_2DArray"], + DictConvertible["_ToDict[CompliantSeriesT]", Mapping[str, Any]], + ArrowConvertible["pa.Table", "IntoArrowTable"], + Sized, + CompliantFrame[CompliantExprT_contra, NativeDataFrameT, ToNarwhalsT_co], + Protocol[CompliantSeriesT, CompliantExprT_contra, NativeDataFrameT, ToNarwhalsT_co], +): + def __narwhals_dataframe__(self) -> Self: ... + @classmethod + def from_arrow(cls, data: IntoArrowTable, /, *, context: _LimitedContext) -> Self: ... + @classmethod + def from_dict( + cls, + data: Mapping[str, Any], + /, + *, + context: CompliantNamespaceAny, + schema: Mapping[str, IntoDType | None] | None, + ) -> Self: ... + @classmethod + def from_dicts( + cls, + data: Sequence[Mapping[str, Any]], + /, + *, + context: _LimitedContext, + schema: Mapping[str, IntoDType | None] | None, + ) -> Self: ... + @classmethod + def from_numpy( + cls, + data: _2DArray, + /, + *, + context: _LimitedContext, + schema: Mapping[str, IntoDType] | Sequence[str] | None, + ) -> Self: ... + def __array__(self, dtype: Any, *, copy: bool | None) -> _2DArray: ... + def __getitem__( + self, + item: tuple[ + SingleIndexSelector | MultiIndexSelector[CompliantSeriesT], + MultiColSelector[CompliantSeriesT], + ], + ) -> Self: ... + + @property + def shape(self) -> tuple[int, int]: ... + def clone(self) -> Self: ... + def estimated_size(self, unit: SizeUnit) -> int | float: ... + def gather_every(self, n: int, offset: int) -> Self: ... + def get_column(self, name: str) -> CompliantSeriesT: ... + def group_by( + self, + keys: Sequence[str] | Sequence[CompliantExprT_contra], + *, + drop_null_keys: bool, + ) -> DataFrameGroupBy[Self, Any]: ... + def item(self, row: int | None, column: int | str | None) -> Any: ... + def iter_columns(self) -> Iterator[CompliantSeriesT]: ... + def iter_rows( + self, *, named: bool, buffer_size: int + ) -> Iterator[tuple[Any, ...]] | Iterator[Mapping[str, Any]]: ... + def is_unique(self) -> CompliantSeriesT: ... + def lazy( + self, backend: _LazyAllowedImpl | None, *, session: SparkSession | None + ) -> CompliantLazyFrameAny: ... + def pivot( + self, + on: Sequence[str], + *, + index: Sequence[str] | None, + values: Sequence[str] | None, + aggregate_function: PivotAgg | None, + sort_columns: bool, + separator: str, + ) -> Self: ... + def row(self, index: int) -> tuple[Any, ...]: ... + def rows( + self, *, named: bool + ) -> Sequence[tuple[Any, ...]] | Sequence[Mapping[str, Any]]: ... + def sample(self, n: int, *, with_replacement: bool, seed: int | None) -> Self: ... + def to_arrow(self) -> pa.Table: ... + def to_pandas(self) -> pd.DataFrame: ... + def to_polars(self) -> pl.DataFrame: ... + @overload + def to_dict(self, *, as_series: Literal[True]) -> dict[str, CompliantSeriesT]: ... + @overload + def to_dict(self, *, as_series: Literal[False]) -> dict[str, list[Any]]: ... + def to_dict( + self, *, as_series: bool + ) -> dict[str, CompliantSeriesT] | dict[str, list[Any]]: ... + def unique( + self, + subset: Sequence[str] | None, + *, + keep: UniqueKeepStrategy, + maintain_order: bool | None = None, + order_by: Sequence[str] | None, + ) -> Self: ... + def with_row_index(self, name: str, order_by: Sequence[str] | None) -> Self: ... + @overload + def write_csv(self, file: None) -> str: ... + @overload + def write_csv(self, file: str | Path | BytesIO) -> None: ... + def write_csv(self, file: str | Path | BytesIO | None) -> str | None: ... + def write_parquet(self, file: str | Path | BytesIO) -> None: ... + + +class CompliantLazyFrame( + CompliantFrame[CompliantExprT_contra, NativeLazyFrameT, ToNarwhalsT_co], + Protocol[CompliantExprT_contra, NativeLazyFrameT, ToNarwhalsT_co], +): + def __narwhals_lazyframe__(self) -> Self: ... + # `LazySelectorNamespace._iter_columns` depends + def _iter_columns(self) -> Iterator[Any]: ... + def aggregate(self, *exprs: CompliantExprT_contra) -> Self: + """`select` where all args are aggregations or literals. + + (so, no broadcasting is necessary). + """ + ... + + def collect( + self, backend: _EagerAllowedImpl | None, **kwargs: Any + ) -> CompliantDataFrameAny: ... + def sink_parquet(self, file: str | Path | BytesIO) -> None: ... + + +class EagerDataFrame( + CompliantDataFrame[ + EagerSeriesT, EagerExprT, NativeDataFrameT, "DataFrame[NativeDataFrameT]" + ], + CompliantLazyFrame[EagerExprT, "Incomplete", "DataFrame[NativeDataFrameT]"], + ValidateBackendVersion, + Protocol[EagerSeriesT, EagerExprT, NativeDataFrameT, NativeSeriesT], +): + @property + def _backend_version(self) -> tuple[int, ...]: + return self._implementation._backend_version() + + def __narwhals_namespace__( + self, + ) -> EagerNamespace[ + Self, EagerSeriesT, EagerExprT, NativeDataFrameT, NativeSeriesT + ]: ... + + def to_narwhals(self) -> DataFrame[NativeDataFrameT]: + return self._version.dataframe(self, level="full") + + def aggregate(self, *exprs: EagerExprT) -> Self: # pyright: ignore[reportIncompatibleMethodOverride] + # NOTE: Ignore intermittent [False Negative] (1) + # Method "aggregate" overrides class "CompliantLazyFrame" in an incompatible manner + # Keyword parameter "exprs" type mismatch: base parameter is type "EagerExprT@EagerDataFrame", override parameter is type "EagerExprT@EagerDataFrame" + # Type "EagerExprT@EagerDataFrame" is not assignable to type "EagerExprT@EagerDataFrame" + # NOTE: Ignore intermittent [False Negative] (2) + # Argument of type "EagerExprT@EagerDataFrame" cannot be assigned to parameter "exprs" of type "EagerExprT@EagerDataFrame" in function "select" + # Type "EagerExprT@EagerDataFrame" is not assignable to type "EagerExprT@EagerDataFrame" + return self.select(*exprs) # pyright: ignore[reportArgumentType] + + def _with_native( + self, df: NativeDataFrameT, *, validate_column_names: bool = True + ) -> Self: ... + + def _check_columns_exist(self, subset: Sequence[str]) -> ColumnNotFoundError | None: + return check_columns_exist(subset, available=self.columns) + + def _evaluate_single_output_expr(self, expr: EagerExprT, /) -> EagerSeriesT: + """Evaluate `expr` and ensure it has a **single** output.""" + # NOTE: Ignore intermittent [False Negative] + # Argument of type "EagerExprT@EagerDataFrame" cannot be assigned to parameter "expr" of type "EagerExprT@EagerDataFrame" in function "_evaluate_into_expr" + # Type "EagerExprT@EagerDataFrame" is not assignable to type "EagerExprT@EagerDataFrame" + result = self._evaluate_expr(expr) # pyright: ignore[reportArgumentType] + if len(result) != 1: # pragma: no cover + msg = "multi-output expressions not allowed in this context" + raise MultiOutputExpressionError(msg) + return result[0] + + def _evaluate_exprs(self, *exprs: EagerExprT) -> Sequence[EagerSeriesT]: + # NOTE: Ignore intermittent [False Negative] + # Argument of type "EagerExprT@EagerDataFrame" cannot be assigned to parameter "expr" of type "EagerExprT@EagerDataFrame" in function "_evaluate_into_expr" + # Type "EagerExprT@EagerDataFrame" is not assignable to type "EagerExprT@EagerDataFrame" + return tuple(chain.from_iterable(self._evaluate_expr(expr) for expr in exprs)) # pyright: ignore[reportArgumentType] + + def _evaluate_expr(self, expr: EagerExprT, /) -> Sequence[EagerSeriesT]: + """Return list of raw columns. + + For eager backends we alias operations at each step. + + As a safety precaution, here we can check that the expected result names match those + we were expecting from the various `evaluate_output_names` / `alias_output_names` calls. + + Note that for PySpark / DuckDB, we are less free to liberally set aliases whenever we want. + """ + aliases = expr._evaluate_aliases(self) + result = expr(self) + if list(aliases) != ( + result_aliases := [s.name for s in result] + ): # pragma: no cover + msg = f"Safety assertion failed, expected {aliases}, got {result_aliases}" + raise AssertionError(msg) + return result + + def _extract_comparand(self, other: EagerSeriesT, /) -> Any: + """Extract native Series, broadcasting to `len(self)` if necessary.""" + ... + + @staticmethod + def _numpy_column_names( + data: _2DArray, columns: Sequence[str] | None, / + ) -> list[str]: + return list(columns or (f"column_{x}" for x in range(data.shape[1]))) + + def _gather(self, rows: SizedMultiIndexSelector[NativeSeriesT]) -> Self: ... + def _gather_slice(self, rows: _SliceIndex | range) -> Self: ... + def _select_multi_index( + self, columns: SizedMultiIndexSelector[NativeSeriesT] + ) -> Self: ... + def _select_multi_name( + self, columns: SizedMultiNameSelector[NativeSeriesT] + ) -> Self: ... + def _select_slice_index(self, columns: _SliceIndex | range) -> Self: ... + def _select_slice_name(self, columns: _SliceName) -> Self: ... + def __getitem__( # noqa: C901, PLR0912 + self, + item: tuple[ + SingleIndexSelector | MultiIndexSelector[EagerSeriesT], + MultiColSelector[EagerSeriesT], + ], + ) -> Self: + rows, columns = item + compliant = self + if not is_slice_none(columns): + if isinstance(columns, Sized) and len(columns) == 0: + return compliant.select() + if is_boolean_selector(columns): + compliant = compliant.simple_select( + *( + col + for col, select in zip(compliant.columns, columns, strict=False) + if select + ) + ) + elif is_index_selector(columns): + if is_slice_index(columns) or is_range(columns): + compliant = compliant._select_slice_index(columns) + elif is_compliant_series(columns): + compliant = self._select_multi_index(columns.native) + else: + compliant = compliant._select_multi_index(columns) + elif isinstance(columns, slice): + if MYPY: + # https://github.com/python/mypy/issues/21508 + compliant = compliant._select_slice_name(columns) # type: ignore[arg-type] + else: + compliant = compliant._select_slice_name(columns) + elif is_compliant_series(columns): + compliant = self._select_multi_name(columns.native) + elif is_sequence_like(columns): + compliant = self._select_multi_name(columns) + elif MYPY: + # https://github.com/python/mypy/issues/21508 + pass + else: + assert_never(columns) + + if not is_slice_none(rows): + if isinstance(rows, int): + compliant = compliant._gather([rows]) + elif isinstance(rows, (slice, range)): + compliant = compliant._gather_slice(rows) + elif is_compliant_series(rows): + compliant = compliant._gather(rows.native) + elif is_sized_multi_index_selector(rows): + if MYPY: # noqa: SIM108 + # https://github.com/python/mypy/issues/21508 + compliant = compliant._gather(rows) # type: ignore[arg-type] + else: + compliant = compliant._gather(rows) + else: + assert_never(rows) + + return compliant + + def sink_parquet(self, file: str | Path | BytesIO) -> None: + return self.write_parquet(file) diff --git a/shared/package-files/d1/d1daea7fd662a454f2474d6f79bf843d1499eb833e758fdc535e6dd4d49fe196/blob b/shared/package-files/d1/d1daea7fd662a454f2474d6f79bf843d1499eb833e758fdc535e6dd4d49fe196/blob new file mode 100644 index 0000000000000000000000000000000000000000..cf8b3d5c3dfb5078bb2f91a23dda0a93085e14be --- /dev/null +++ b/shared/package-files/d1/d1daea7fd662a454f2474d6f79bf843d1499eb833e758fdc535e6dd4d49fe196/blob @@ -0,0 +1,82 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_foreach_minimum.Scalar(Tensor[] self, Scalar scalar) -> Tensor[] +inline ::std::vector _foreach_minimum(at::TensorList self, const at::Scalar & scalar) { + return at::_ops::_foreach_minimum_Scalar::call(self, scalar); +} + +// aten::_foreach_minimum_.Scalar(Tensor(a!)[] self, Scalar scalar) -> () +inline void _foreach_minimum_(at::TensorList self, const at::Scalar & scalar) { + return at::_ops::_foreach_minimum__Scalar::call(self, scalar); +} + +// aten::_foreach_minimum.List(Tensor[] self, Tensor[] other) -> Tensor[] +inline ::std::vector _foreach_minimum(at::TensorList self, at::TensorList other) { + return at::_ops::_foreach_minimum_List::call(self, other); +} + +// aten::_foreach_minimum_.List(Tensor(a!)[] self, Tensor[] other) -> () +inline void _foreach_minimum_(at::TensorList self, at::TensorList other) { + return at::_ops::_foreach_minimum__List::call(self, other); +} + +// aten::_foreach_minimum.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[] +inline ::std::vector _foreach_minimum(at::TensorList self, at::ArrayRef scalars) { + return at::_ops::_foreach_minimum_ScalarList::call(self, scalars); +} + +// aten::_foreach_minimum_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> () +inline void _foreach_minimum_(at::TensorList self, at::ArrayRef scalars) { + return at::_ops::_foreach_minimum__ScalarList::call(self, scalars); +} + +// aten::_foreach_minimum.Scalar_out(Tensor[] self, Scalar scalar, *, Tensor(a!)[] out) -> () +inline void _foreach_minimum_out(at::TensorList out, at::TensorList self, const at::Scalar & scalar) { + return at::_ops::_foreach_minimum_Scalar_out::call(self, scalar, out); +} +// aten::_foreach_minimum.Scalar_out(Tensor[] self, Scalar scalar, *, Tensor(a!)[] out) -> () +inline void _foreach_minimum_outf(at::TensorList self, const at::Scalar & scalar, at::TensorList out) { + return at::_ops::_foreach_minimum_Scalar_out::call(self, scalar, out); +} + +// aten::_foreach_minimum.List_out(Tensor[] self, Tensor[] other, *, Tensor(a!)[] out) -> () +inline void _foreach_minimum_out(at::TensorList out, at::TensorList self, at::TensorList other) { + return at::_ops::_foreach_minimum_List_out::call(self, other, out); +} +// aten::_foreach_minimum.List_out(Tensor[] self, Tensor[] other, *, Tensor(a!)[] out) -> () +inline void _foreach_minimum_outf(at::TensorList self, at::TensorList other, at::TensorList out) { + return at::_ops::_foreach_minimum_List_out::call(self, other, out); +} + +// aten::_foreach_minimum.ScalarList_out(Tensor[] self, Scalar[] scalars, *, Tensor(a!)[] out) -> () +inline void _foreach_minimum_out(at::TensorList out, at::TensorList self, at::ArrayRef scalars) { + return at::_ops::_foreach_minimum_ScalarList_out::call(self, scalars, out); +} +// aten::_foreach_minimum.ScalarList_out(Tensor[] self, Scalar[] scalars, *, Tensor(a!)[] out) -> () +inline void _foreach_minimum_outf(at::TensorList self, at::ArrayRef scalars, at::TensorList out) { + return at::_ops::_foreach_minimum_ScalarList_out::call(self, scalars, out); +} + +} diff --git a/shared/package-files/d1/d1db3c951dd93b83a437b225e1940d002b093b4f7ff821526e9bbd4aa4dd81de/blob b/shared/package-files/d1/d1db3c951dd93b83a437b225e1940d002b093b4f7ff821526e9bbd4aa4dd81de/blob new file mode 100644 index 0000000000000000000000000000000000000000..f7aa4da0db5dcaaa6dec84086fa94d9c8571e6e5 --- /dev/null +++ b/shared/package-files/d1/d1db3c951dd93b83a437b225e1940d002b093b4f7ff821526e9bbd4aa4dd81de/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor _compute_linear_combination(const at::Tensor & input, const at::Tensor & coefficients); +TORCH_API at::Tensor & _compute_linear_combination_out(const at::Tensor & input, const at::Tensor & coefficients, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/d1/d1dce641fe8be7d6c425bf4c5d86eb0edab76c01cd753ba4f8f98e868c7cd46e/blob b/shared/package-files/d1/d1dce641fe8be7d6c425bf4c5d86eb0edab76c01cd753ba4f8f98e868c7cd46e/blob new file mode 100644 index 0000000000000000000000000000000000000000..9b6f4c7c1985ccadf073a1bbf9e01ac906f49558 --- /dev/null +++ b/shared/package-files/d1/d1dce641fe8be7d6c425bf4c5d86eb0edab76c01cd753ba4f8f98e868c7cd46e/blob @@ -0,0 +1,31 @@ +from __future__ import absolute_import + +from enum import Enum + + +class TokenType: + name: str + contains_syntax: bool + + def __init__(self, name: str, contains_syntax: bool = False): + self.name = name + self.contains_syntax = contains_syntax + + def __repr__(self): + return '%s(%s)' % (self.__class__.__name__, self.name) + + +class PythonTokenTypes(Enum): + STRING = TokenType('STRING') + NUMBER = TokenType('NUMBER') + NAME = TokenType('NAME', contains_syntax=True) + ERRORTOKEN = TokenType('ERRORTOKEN') + NEWLINE = TokenType('NEWLINE') + INDENT = TokenType('INDENT') + DEDENT = TokenType('DEDENT') + ERROR_DEDENT = TokenType('ERROR_DEDENT') + FSTRING_STRING = TokenType('FSTRING_STRING') + FSTRING_START = TokenType('FSTRING_START') + FSTRING_END = TokenType('FSTRING_END') + OP = TokenType('OP', contains_syntax=True) + ENDMARKER = TokenType('ENDMARKER') diff --git a/shared/package-files/d1/d1de489e0bfa36af331875ad329dd5bad9a5f00175af331ced01b6aec3b15ecb/blob b/shared/package-files/d1/d1de489e0bfa36af331875ad329dd5bad9a5f00175af331ced01b6aec3b15ecb/blob new file mode 100644 index 0000000000000000000000000000000000000000..79075c9115ad2dd96a9e1c4fbf9bb64aa9f22c4e --- /dev/null +++ b/shared/package-files/d1/d1de489e0bfa36af331875ad329dd5bad9a5f00175af331ced01b6aec3b15ecb/blob @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor empty_like(const at::Tensor & self, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor & empty_like_out(const at::Tensor & self, c10::optional memory_format, at::Tensor & out); +TORCH_API at::Tensor empty_like_nested(const at::Tensor & self, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor empty_like_sparse_coo(const at::Tensor & self, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor empty_like_sparse_csr(const at::Tensor & self, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor empty_like_quantized(const at::Tensor & self, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}, c10::optional memory_format=c10::nullopt); +} // namespace native +} // namespace at diff --git a/shared/package-files/d1/d1deef6d5b8a8b71829b73ca2ed88daaffc0bbbbfa458b75af345d1e20f4f2d3/blob b/shared/package-files/d1/d1deef6d5b8a8b71829b73ca2ed88daaffc0bbbbfa458b75af345d1e20f4f2d3/blob new file mode 100644 index 0000000000000000000000000000000000000000..c199e24eddf8ef7c2a14e38d1ad2dc95e4acc0cc --- /dev/null +++ b/shared/package-files/d1/d1deef6d5b8a8b71829b73ca2ed88daaffc0bbbbfa458b75af345d1e20f4f2d3/blob @@ -0,0 +1,87 @@ +from sympy.core.basic import Basic +from sympy.core.mul import Mul +from sympy.core.symbol import (Symbol, symbols) + +from sympy.testing.pytest import XFAIL + +class SymbolInMulOnce(Symbol): + # Test class for a symbol that can only appear once in a `Mul` expression. + pass + + +Basic._constructor_postprocessor_mapping[SymbolInMulOnce] = { + "Mul": [lambda x: x], + "Pow": [lambda x: x.base if isinstance(x.base, SymbolInMulOnce) else x], + "Add": [lambda x: x], +} + + +def _postprocess_SymbolRemovesOtherSymbols(expr): + args = tuple(i for i in expr.args if not isinstance(i, Symbol) or isinstance(i, SymbolRemovesOtherSymbols)) + if args == expr.args: + return expr + return Mul.fromiter(args) + + +class SymbolRemovesOtherSymbols(Symbol): + # Test class for a symbol that removes other symbols in `Mul`. + pass + +Basic._constructor_postprocessor_mapping[SymbolRemovesOtherSymbols] = { + "Mul": [_postprocess_SymbolRemovesOtherSymbols], +} + +class SubclassSymbolInMulOnce(SymbolInMulOnce): + pass + +class SubclassSymbolRemovesOtherSymbols(SymbolRemovesOtherSymbols): + pass + + +def test_constructor_postprocessors1(): + x = SymbolInMulOnce("x") + y = SymbolInMulOnce("y") + assert isinstance(3*x, Mul) + assert (3*x).args == (3, x) + assert x*x == x + assert 3*x*x == 3*x + assert 2*x*x + x == 3*x + assert x**3*y*y == x*y + assert x**5 + y*x**3 == x + x*y + + w = SymbolRemovesOtherSymbols("w") + assert x*w == w + assert (3*w).args == (3, w) + assert set((w + x).args) == {x, w} + +def test_constructor_postprocessors2(): + x = SubclassSymbolInMulOnce("x") + y = SubclassSymbolInMulOnce("y") + assert isinstance(3*x, Mul) + assert (3*x).args == (3, x) + assert x*x == x + assert 3*x*x == 3*x + assert 2*x*x + x == 3*x + assert x**3*y*y == x*y + assert x**5 + y*x**3 == x + x*y + + w = SubclassSymbolRemovesOtherSymbols("w") + assert x*w == w + assert (3*w).args == (3, w) + assert set((w + x).args) == {x, w} + + +@XFAIL +def test_subexpression_postprocessors(): + # The postprocessors used to work with subexpressions, but the + # functionality was removed. See #15948. + a = symbols("a") + x = SymbolInMulOnce("x") + w = SymbolRemovesOtherSymbols("w") + assert 3*a*w**2 == 3*w**2 + assert 3*a*x**3*w**2 == 3*w**2 + + x = SubclassSymbolInMulOnce("x") + w = SubclassSymbolRemovesOtherSymbols("w") + assert 3*a*w**2 == 3*w**2 + assert 3*a*x**3*w**2 == 3*w**2 diff --git a/shared/package-files/d1/d1e0faf5f6a81d705cb90ee0d90df57eab3e83247f5df7be82ffbb0d784987f7/blob b/shared/package-files/d1/d1e0faf5f6a81d705cb90ee0d90df57eab3e83247f5df7be82ffbb0d784987f7/blob new file mode 100644 index 0000000000000000000000000000000000000000..0230c8a0957ed28fb0a5cc1e9ee77ecae797265b --- /dev/null +++ b/shared/package-files/d1/d1e0faf5f6a81d705cb90ee0d90df57eab3e83247f5df7be82ffbb0d784987f7/blob @@ -0,0 +1,44 @@ +from sympy.assumptions.ask import (Q, ask) +from sympy.core.numbers import (I, Rational) +from sympy.core.singleton import S +from sympy.functions.elementary.complexes import Abs +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.simplify.simplify import simplify +from sympy.core.symbol import symbols +from sympy.matrices.expressions.fourier import DFT, IDFT +from sympy.matrices import det, Matrix, Identity +from sympy.testing.pytest import raises + + +def test_dft_creation(): + assert DFT(2) + assert DFT(0) + raises(ValueError, lambda: DFT(-1)) + raises(ValueError, lambda: DFT(2.0)) + raises(ValueError, lambda: DFT(2 + 1j)) + + n = symbols('n') + assert DFT(n) + n = symbols('n', integer=False) + raises(ValueError, lambda: DFT(n)) + n = symbols('n', negative=True) + raises(ValueError, lambda: DFT(n)) + + +def test_dft(): + n, i, j = symbols('n i j') + assert DFT(4).shape == (4, 4) + assert ask(Q.unitary(DFT(4))) + assert Abs(simplify(det(Matrix(DFT(4))))) == 1 + assert DFT(n)*IDFT(n) == Identity(n) + assert DFT(n)[i, j] == exp(-2*S.Pi*I/n)**(i*j) / sqrt(n) + + +def test_dft2(): + assert DFT(1).as_explicit() == Matrix([[1]]) + assert DFT(2).as_explicit() == 1/sqrt(2)*Matrix([[1,1],[1,-1]]) + assert DFT(4).as_explicit() == Matrix([[S.Half, S.Half, S.Half, S.Half], + [S.Half, -I/2, Rational(-1,2), I/2], + [S.Half, Rational(-1,2), S.Half, Rational(-1,2)], + [S.Half, I/2, Rational(-1,2), -I/2]]) diff --git a/shared/package-files/d1/d1e3f44e86f72157254970ebcbaf86eeea308e69e754ea0fb29c6e38fb791b4f/blob b/shared/package-files/d1/d1e3f44e86f72157254970ebcbaf86eeea308e69e754ea0fb29c6e38fb791b4f/blob new file mode 100644 index 0000000000000000000000000000000000000000..278a25be6ecadb632f7c1a7ff9ee5e5da913f533 --- /dev/null +++ b/shared/package-files/d1/d1e3f44e86f72157254970ebcbaf86eeea308e69e754ea0fb29c6e38fb791b4f/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _weight_norm_interface_backward { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_weight_norm_interface_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_weight_norm_interface_backward(Tensor grad_w, Tensor saved_v, Tensor saved_g, Tensor saved_norms, int dim) -> (Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & grad_w, const at::Tensor & saved_v, const at::Tensor & saved_g, const at::Tensor & saved_norms, int64_t dim); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_w, const at::Tensor & saved_v, const at::Tensor & saved_g, const at::Tensor & saved_norms, int64_t dim); +}; + +struct TORCH_API _weight_norm_interface_backward_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_weight_norm_interface_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_weight_norm_interface_backward.out(Tensor grad_w, Tensor saved_v, Tensor saved_g, Tensor saved_norms, int dim, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))") + static ::std::tuple call(const at::Tensor & grad_w, const at::Tensor & saved_v, const at::Tensor & saved_g, const at::Tensor & saved_norms, int64_t dim, at::Tensor & out0, at::Tensor & out1); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_w, const at::Tensor & saved_v, const at::Tensor & saved_g, const at::Tensor & saved_norms, int64_t dim, at::Tensor & out0, at::Tensor & out1); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/d1/d1e5457d57766995d364715770b667164f0c7ed208e1c321441058b771e6dcb2/blob b/shared/package-files/d1/d1e5457d57766995d364715770b667164f0c7ed208e1c321441058b771e6dcb2/blob new file mode 100644 index 0000000000000000000000000000000000000000..6e031999e7b6c6198f0533fc0a1c273c230fc484 --- /dev/null +++ b/shared/package-files/d1/d1e5457d57766995d364715770b667164f0c7ed208e1c321441058b771e6dcb2/blob @@ -0,0 +1 @@ +# noqa: D104 diff --git a/shared/package-files/d1/d1e586eecfae9238a96bbf6a28ded5066bb1914ab7cb1e33f93537ef1e2ea055/blob b/shared/package-files/d1/d1e586eecfae9238a96bbf6a28ded5066bb1914ab7cb1e33f93537ef1e2ea055/blob new file mode 100644 index 0000000000000000000000000000000000000000..236ad3e09c3af39d54d204f9dd275acdf95a8a2c --- /dev/null +++ b/shared/package-files/d1/d1e586eecfae9238a96bbf6a28ded5066bb1914ab7cb1e33f93537ef1e2ea055/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _fake_quantize_per_tensor_affine_cachemask_tensor_qparams { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_fake_quantize_per_tensor_affine_cachemask_tensor_qparams") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_fake_quantize_per_tensor_affine_cachemask_tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, Tensor fake_quant_enabled, int quant_min, int quant_max) -> (Tensor output, Tensor mask)") + static ::std::tuple call(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, const at::Tensor & fake_quant_enabled, int64_t quant_min, int64_t quant_max); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, const at::Tensor & fake_quant_enabled, int64_t quant_min, int64_t quant_max); +}; + +struct TORCH_API _fake_quantize_per_tensor_affine_cachemask_tensor_qparams_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, int64_t, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_fake_quantize_per_tensor_affine_cachemask_tensor_qparams") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_fake_quantize_per_tensor_affine_cachemask_tensor_qparams.out(Tensor self, Tensor scale, Tensor zero_point, Tensor fake_quant_enabled, int quant_min, int quant_max, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))") + static ::std::tuple call(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, const at::Tensor & fake_quant_enabled, int64_t quant_min, int64_t quant_max, at::Tensor & out0, at::Tensor & out1); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, const at::Tensor & fake_quant_enabled, int64_t quant_min, int64_t quant_max, at::Tensor & out0, at::Tensor & out1); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/d1/d1e771d1f832cdeeaec538290f269c4a58ca3146b2f3aa51aaf21143b019a579/blob b/shared/package-files/d1/d1e771d1f832cdeeaec538290f269c4a58ca3146b2f3aa51aaf21143b019a579/blob new file mode 100644 index 0000000000000000000000000000000000000000..8ec8796ffd17516cef6d24eac481a7b44703d562 --- /dev/null +++ b/shared/package-files/d1/d1e771d1f832cdeeaec538290f269c4a58ca3146b2f3aa51aaf21143b019a579/blob @@ -0,0 +1,176 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "parquet/platform.h" +#include "parquet/properties.h" + +namespace arrow { + +class Array; +class ChunkedArray; +class RecordBatch; +class Schema; +class Table; + +} // namespace arrow + +namespace parquet { + +class FileMetaData; +class ParquetFileWriter; + +namespace arrow { + +/// \brief Iterative FileWriter class +/// +/// For basic usage, can write a Table at a time, creating one or more row +/// groups per write call. +/// +/// For advanced usage, can write column-by-column: Start a new RowGroup or +/// Chunk with NewRowGroup, then write column-by-column the whole column chunk. +/// +/// If PARQUET:field_id is present as a metadata key on a field, and the corresponding +/// value is a nonnegative integer, then it will be used as the field_id in the parquet +/// file. +class PARQUET_EXPORT FileWriter { + public: + static ::arrow::Status Make(MemoryPool* pool, std::unique_ptr writer, + std::shared_ptr<::arrow::Schema> schema, + std::shared_ptr arrow_properties, + std::unique_ptr* out); + + /// \brief Try to create an Arrow to Parquet file writer. + /// + /// \param schema schema of data that will be passed. + /// \param pool memory pool to use. + /// \param sink output stream to write Parquet data. + /// \param properties general Parquet writer properties. + /// \param arrow_properties Arrow-specific writer properties. + /// + /// \since 11.0.0 + static ::arrow::Result> Open( + const ::arrow::Schema& schema, MemoryPool* pool, + std::shared_ptr<::arrow::io::OutputStream> sink, + std::shared_ptr properties = default_writer_properties(), + std::shared_ptr arrow_properties = + default_arrow_writer_properties()); + + /// Return the Arrow schema to be written to. + virtual std::shared_ptr<::arrow::Schema> schema() const = 0; + + /// \brief Write a Table to Parquet. + /// + /// \param table Arrow table to write. + /// \param chunk_size maximum number of rows to write per row group. + virtual ::arrow::Status WriteTable( + const ::arrow::Table& table, int64_t chunk_size = DEFAULT_MAX_ROW_GROUP_LENGTH) = 0; + + /// \brief Start a new row group. + /// + /// Returns an error if not all columns have been written. + virtual ::arrow::Status NewRowGroup() = 0; + + /// \brief Write ColumnChunk in row group using an array. + virtual ::arrow::Status WriteColumnChunk(const ::arrow::Array& data) = 0; + + /// \brief Write ColumnChunk in row group using slice of a ChunkedArray + virtual ::arrow::Status WriteColumnChunk( + const std::shared_ptr<::arrow::ChunkedArray>& data, int64_t offset, + int64_t size) = 0; + + /// \brief Write ColumnChunk in a row group using a ChunkedArray + virtual ::arrow::Status WriteColumnChunk( + const std::shared_ptr<::arrow::ChunkedArray>& data) = 0; + + /// \brief Start a new buffered row group. + /// + /// Returns an error if not all columns have been written. + virtual ::arrow::Status NewBufferedRowGroup() = 0; + + /// \brief Write a RecordBatch into the buffered row group. + /// + /// Multiple RecordBatches can be written into the same row group + /// through this method. + /// + /// WriterProperties.max_row_group_length() is respected and a new + /// row group will be created if the current row group exceeds the + /// limit. + /// + /// Batches get flushed to the output stream once NewBufferedRowGroup() + /// or Close() is called. + /// + /// WARNING: If you are writing multiple files in parallel in the same + /// executor, deadlock may occur if ArrowWriterProperties::use_threads + /// is set to true to write columns in parallel. Please disable use_threads + /// option in this case. + virtual ::arrow::Status WriteRecordBatch(const ::arrow::RecordBatch& batch) = 0; + + /// \brief Write the footer and close the file. + virtual ::arrow::Status Close() = 0; + virtual ~FileWriter(); + + virtual MemoryPool* memory_pool() const = 0; + /// \brief Add key-value metadata to the file. + /// \param[in] key_value_metadata the metadata to add. + /// \note This will overwrite any existing metadata with the same key. + /// \return Error if Close() has been called. + /// + /// WARNING: If `store_schema` is enabled, `ARROW:schema` would be stored + /// in the key-value metadata. Overwriting this key would result in + /// `store_schema` being unusable during read. + virtual ::arrow::Status AddKeyValueMetadata( + const std::shared_ptr& key_value_metadata) = 0; + /// \brief Return the file metadata, only available after calling Close(). + virtual const std::shared_ptr metadata() const = 0; +}; + +/// \brief Write Parquet file metadata only to indicated Arrow OutputStream +PARQUET_EXPORT +::arrow::Status WriteFileMetaData(const FileMetaData& file_metadata, + ::arrow::io::OutputStream* sink); + +/// \brief Write metadata-only Parquet file to indicated Arrow OutputStream +PARQUET_EXPORT +::arrow::Status WriteMetaDataFile(const FileMetaData& file_metadata, + ::arrow::io::OutputStream* sink); + +/// \brief Write a Table to Parquet. +/// +/// This writes one table in a single shot. To write a Parquet file with +/// multiple tables iteratively, see parquet::arrow::FileWriter. +/// +/// \param table Table to write. +/// \param pool memory pool to use. +/// \param sink output stream to write Parquet data. +/// \param chunk_size maximum number of rows to write per row group. +/// \param properties general Parquet writer properties. +/// \param arrow_properties Arrow-specific writer properties. +::arrow::Status PARQUET_EXPORT +WriteTable(const ::arrow::Table& table, MemoryPool* pool, + std::shared_ptr<::arrow::io::OutputStream> sink, + int64_t chunk_size = DEFAULT_MAX_ROW_GROUP_LENGTH, + std::shared_ptr properties = default_writer_properties(), + std::shared_ptr arrow_properties = + default_arrow_writer_properties()); + +} // namespace arrow +} // namespace parquet diff --git a/shared/package-files/d1/d1e800de6024de9e213135213d5e23d0b14fb7ba4c8e3a360b611bc95e4d8681/blob b/shared/package-files/d1/d1e800de6024de9e213135213d5e23d0b14fb7ba4c8e3a360b611bc95e4d8681/blob new file mode 100644 index 0000000000000000000000000000000000000000..994a23b21a9dc012428d0499c4375aa695cf163e --- /dev/null +++ b/shared/package-files/d1/d1e800de6024de9e213135213d5e23d0b14fb7ba4c8e3a360b611bc95e4d8681/blob @@ -0,0 +1,846 @@ +""" +Caching mechanism for compiled functions. +""" + + +from abc import ABCMeta, abstractmethod +import contextlib +import errno +import functools +import hashlib +import importlib +import inspect +import itertools +import os +import pickle +import sys +import tempfile +import uuid +import warnings + +from numba.misc.appdirs import AppDirs +import zipfile +from pathlib import Path + +import numba +from numba.core.errors import NumbaWarning, NumbaDeprecationWarning +from numba.core.base import BaseContext +from numba.core.codegen import CodeLibrary +from numba.core.compiler import CompileResult +from numba.core import config, compiler +from numba.core.serialize import dumps + + +def _cache_log(msg, *args): + if config.DEBUG_CACHE: + msg = msg % args + print(msg) + + +class _Cache(metaclass=ABCMeta): + + @property + @abstractmethod + def cache_path(self): + """ + The base filesystem path of this cache (for example its root folder). + """ + + @abstractmethod + def load_overload(self, sig, target_context): + """ + Load an overload for the given signature using the target context. + The saved object must be returned if successful, None if not found + in the cache. + """ + + @abstractmethod + def save_overload(self, sig, data): + """ + Save the overload for the given signature. + """ + + @abstractmethod + def enable(self): + """ + Enable the cache. + """ + + @abstractmethod + def disable(self): + """ + Disable the cache. + """ + + @abstractmethod + def flush(self): + """ + Flush the cache. + """ + + +class NullCache(_Cache): + @property + def cache_path(self): + return None + + def load_overload(self, sig, target_context): + pass + + def save_overload(self, sig, cres): + pass + + def enable(self): + pass + + def disable(self): + pass + + def flush(self): + pass + + +class _CacheLocator(metaclass=ABCMeta): + """ + A filesystem locator for caching a given function. + """ + + def ensure_cache_path(self): + path = self.get_cache_path() + os.makedirs(path, exist_ok=True) + # Ensure the directory is writable by trying to write a temporary file + tempfile.TemporaryFile(dir=path).close() + + @abstractmethod + def get_cache_path(self): + """ + Return the directory the function is cached in. + """ + + @abstractmethod + def get_source_stamp(self): + """ + Get a timestamp representing the source code's freshness. + Can return any picklable Python object. + """ + + @abstractmethod + def get_disambiguator(self): + """ + Get a string disambiguator for this locator's function. + It should allow disambiguating different but similarly-named functions. + """ + + @classmethod + def from_function(cls, py_func, py_file): + """ + Create a locator instance for the given function located in the + given file. + """ + raise NotImplementedError + + @classmethod + def get_suitable_cache_subpath(cls, py_file): + """Given the Python file path, compute a suitable path inside the + cache directory. + + This will reduce a file path that is too long, which can be a problem + on some operating system (i.e. Windows 7). + """ + path = os.path.abspath(py_file) + subpath = os.path.dirname(path) + parentdir = os.path.split(subpath)[-1] + # Use SHA1 to reduce path length. + # Note: windows doesn't like long path. + hashed = hashlib.sha1(subpath.encode()).hexdigest() + # Retain parent directory name for easier debugging + return '_'.join([parentdir, hashed]) + + +@functools.lru_cache(maxsize=None) +def _hash_source_file(path, st_mtime, st_size): + # Note: keep the arguments to this function so that the memoization key is + # based on the file's mtime and size, so that if the file changes while + # the process is running, it will be re-hashed. + with open(path, 'rb') as f: + return hashlib.sha256(f.read()).digest() + + +@functools.lru_cache(maxsize=None) +def _hash_zipped_source_file(zip_path, internal_path, st_mtime, st_size): + # Note: keep the arguments to this function so that the memoization key is + # based on the zip file's mtime and size, so that if the file changes + # while the process is running, it will be re-hashed. + with zipfile.ZipFile(zip_path) as zf: + with zf.open(internal_path) as f: + return hashlib.sha256(f.read()).digest() + + +class _SourceFileBackedLocatorMixin(object): + """ + A cache locator mixin for functions which are backed by a well-known + Python source file. + """ + + def get_source_stamp(self): + if getattr(sys, 'frozen', False): + path = sys.executable + else: + path = self._py_file + st = os.stat(path) + return _hash_source_file(path, st.st_mtime, st.st_size) + + def get_disambiguator(self): + return str(self._lineno) + + @classmethod + def from_function(cls, py_func, py_file): + if not os.path.exists(py_file): + # Perhaps a placeholder (e.g. "") + return + self = cls(py_func, py_file) + try: + self.ensure_cache_path() + except OSError: + # Cannot ensure the cache directory exists or is writable + return + return self + + +class UserProvidedCacheLocator(_SourceFileBackedLocatorMixin, _CacheLocator): + """ + A locator that always point to the user provided directory in + `numba.config.CACHE_DIR` + """ + def __init__(self, py_func, py_file): + self._py_file = py_file + self._lineno = py_func.__code__.co_firstlineno + cache_subpath = self.get_suitable_cache_subpath(py_file) + self._cache_path = os.path.join(config.CACHE_DIR, cache_subpath) + + def get_cache_path(self): + return self._cache_path + + @classmethod + def from_function(cls, py_func, py_file): + if not config.CACHE_DIR: + return + parent = super(UserProvidedCacheLocator, cls) + return parent.from_function(py_func, py_file) + + +class InTreeCacheLocator(_SourceFileBackedLocatorMixin, _CacheLocator): + """ + A locator for functions backed by a regular Python module with a + writable __pycache__ directory. + """ + + def __init__(self, py_func, py_file): + self._py_file = py_file + self._lineno = py_func.__code__.co_firstlineno + self._cache_path = os.path.join(os.path.dirname(self._py_file), '__pycache__') + + def get_cache_path(self): + return self._cache_path + + +class InTreeCacheLocatorFsAgnostic(InTreeCacheLocator): + """ + A locator for functions backed by a regular Python module with a + writable __pycache__ directory. This version is agnostic to filesystem differences, + e.g. timestamp precision with milliseconds. + + .. deprecated:: + Source stamps are now content hashes, which are already + filesystem-agnostic. Use :class:`InTreeCacheLocator` instead. + """ + + def __init__(self, *args, **kwargs): + warnings.warn( + "InTreeCacheLocatorFsAgnostic is deprecated; source stamps are " + "now content hashes, which are already filesystem-agnostic. " + "Use InTreeCacheLocator instead.", + NumbaDeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) + + +class UserWideCacheLocator(_SourceFileBackedLocatorMixin, _CacheLocator): + """ + A locator for functions backed by a regular Python module or a + frozen executable, cached into a user-wide cache directory. + """ + + def __init__(self, py_func, py_file): + self._py_file = py_file + self._lineno = py_func.__code__.co_firstlineno + appdirs = AppDirs(appname="numba", appauthor=False) + cache_dir = appdirs.user_cache_dir + cache_subpath = self.get_suitable_cache_subpath(py_file) + self._cache_path = os.path.join(cache_dir, cache_subpath) + + def get_cache_path(self): + return self._cache_path + + @classmethod + def from_function(cls, py_func, py_file): + if not (os.path.exists(py_file) or getattr(sys, 'frozen', False)): + # Perhaps a placeholder (e.g. "") + # stop function exit if frozen, since it uses a temp placeholder + return + self = cls(py_func, py_file) + try: + self.ensure_cache_path() + except OSError: + # Cannot ensure the cache directory exists or is writable + return + return self + + +class IPythonCacheLocator(_CacheLocator): + """ + A locator for functions entered at the IPython prompt (notebook or other). + """ + + def __init__(self, py_func, py_file): + self._py_file = py_file + # Note IPython enhances the linecache module to be able to + # inspect source code of functions defined on the interactive prompt. + source = inspect.getsource(py_func) + if isinstance(source, bytes): + self._bytes_source = source + else: + self._bytes_source = source.encode('utf-8') + + def get_cache_path(self): + # We could also use jupyter_core.paths.jupyter_runtime_dir() + # In both cases this is a user-wide directory, so we need to + # be careful when disambiguating if we don't want too many + # conflicts (see below). + try: + from IPython.paths import get_ipython_cache_dir + except ImportError: + # older IPython version + from IPython.utils.path import get_ipython_cache_dir + return os.path.join(get_ipython_cache_dir(), 'numba_cache') + + def get_source_stamp(self): + return hashlib.sha256(self._bytes_source).hexdigest() + + def get_disambiguator(self): + # Heuristic: we don't want too many variants being saved, but + # we don't want similar named functions (e.g. "f") to compete + # for the cache, so we hash the first two lines of the function + # source (usually this will be the @jit decorator + the function + # signature). + firstlines = b''.join(self._bytes_source.splitlines(True)[:2]) + return hashlib.sha256(firstlines).hexdigest()[:10] + + @classmethod + def from_function(cls, py_func, py_file): + if not ( + py_file.startswith("' can appear in the qualname (e.g. '') but + # are forbidden in Windows filenames + fixed_fullname = fullname.replace('<', '').replace('>', '') + fmt = '%s-%s.py%d%d%s' + return fmt % (fixed_fullname, self.locator.get_disambiguator(), + sys.version_info[0], sys.version_info[1], abiflags) + + @property + def filename_base(self): + return self._filename_base + + @property + def locator(self): + return self._locator + + @abstractmethod + def reduce(self, data): + "Returns the serialized form the data" + pass + + @abstractmethod + def rebuild(self, target_context, reduced_data): + "Returns the de-serialized form of the *reduced_data*" + pass + + @abstractmethod + def check_cachable(self, data): + "Returns True if the given data is cachable; otherwise, returns False." + pass + + +class CompileResultCacheImpl(CacheImpl): + """ + Implements the logic to cache CompileResult objects. + """ + + def reduce(self, cres): + """ + Returns a serialized CompileResult + """ + return cres._reduce() + + def rebuild(self, target_context, payload): + """ + Returns the unserialized CompileResult + """ + return compiler.CompileResult._rebuild(target_context, *payload) + + def check_cachable(self, cres): + """ + Check cachability of the given compile result. + """ + cannot_cache = None + if any(not x.can_cache for x in cres.lifted): + cannot_cache = "as it uses lifted code" + elif cres.library.has_dynamic_globals: + cannot_cache = ("as it uses dynamic globals " + "(such as ctypes pointers and large global arrays)") + if cannot_cache: + msg = ('Cannot cache compiled function "%s" %s' + % (cres.fndesc.qualname.split('.')[-1], cannot_cache)) + warnings.warn_explicit(msg, NumbaWarning, + self._locator._py_file, self._lineno) + return False + return True + + +class CodeLibraryCacheImpl(CacheImpl): + """ + Implements the logic to cache CodeLibrary objects. + """ + + _filename_prefix = None # must be overridden + + def reduce(self, codelib): + """ + Returns a serialized CodeLibrary + """ + return codelib.serialize_using_object_code() + + def rebuild(self, target_context, payload): + """ + Returns the unserialized CodeLibrary + """ + return target_context.codegen().unserialize_library(payload) + + def check_cachable(self, codelib): + """ + Check cachability of the given CodeLibrary. + """ + return not codelib.has_dynamic_globals + + def get_filename_base(self, fullname, abiflags): + parent = super(CodeLibraryCacheImpl, self) + res = parent.get_filename_base(fullname, abiflags) + return '-'.join([self._filename_prefix, res]) + + +class IndexDataCacheFile(object): + """ + Implements the logic for the index file and data file used by a cache. + """ + def __init__(self, cache_path, filename_base, source_stamp): + self._cache_path = cache_path + self._index_name = '%s.nbi' % (filename_base,) + self._index_path = os.path.join(self._cache_path, self._index_name) + self._data_name_pattern = '%s.{number:d}.nbc' % (filename_base,) + self._source_stamp = source_stamp + self._version = numba.__version__ + + def flush(self): + self._save_index({}) + + def save(self, key, data): + """ + Save a new cache entry with *key* and *data*. + """ + overloads = self._load_index() + try: + # If key already exists, we will overwrite the file + data_name = overloads[key] + except KeyError: + # Find an available name for the data file + existing = set(overloads.values()) + for i in itertools.count(1): + data_name = self._data_name(i) + if data_name not in existing: + break + overloads[key] = data_name + self._save_index(overloads) + self._save_data(data_name, data) + + def load(self, key): + """ + Load a cache entry with *key*. + """ + overloads = self._load_index() + data_name = overloads.get(key) + if data_name is None: + return + try: + return self._load_data(data_name) + except OSError: + # File could have been removed while the index still refers it. + return + + def _load_index(self): + """ + Load the cache index and return it as a dictionary (possibly + empty if cache is empty or obsolete). + """ + try: + with open(self._index_path, "rb") as f: + version = pickle.load(f) + data = f.read() + except FileNotFoundError: + # Index doesn't exist yet? + return {} + if version != self._version: + # This is another version. Avoid trying to unpickling the + # rest of the stream, as that may fail. + return {} + stamp, overloads = pickle.loads(data) + _cache_log("[cache] index loaded from %r", self._index_path) + if stamp != self._source_stamp: + # Cache is not fresh. Stale data files will be eventually + # overwritten, since they are numbered in incrementing order. + return {} + else: + return overloads + + def _save_index(self, overloads): + data = self._source_stamp, overloads + data = self._dump(data) + with self._open_for_write(self._index_path) as f: + pickle.dump(self._version, f, protocol=-1) + f.write(data) + _cache_log("[cache] index saved to %r", self._index_path) + + def _load_data(self, name): + path = self._data_path(name) + with open(path, "rb") as f: + data = f.read() + tup = pickle.loads(data) + _cache_log("[cache] data loaded from %r", path) + return tup + + def _save_data(self, name, data): + data = self._dump(data) + path = self._data_path(name) + with self._open_for_write(path) as f: + f.write(data) + _cache_log("[cache] data saved to %r", path) + + def _data_name(self, number): + return self._data_name_pattern.format(number=number) + + def _data_path(self, name): + return os.path.join(self._cache_path, name) + + def _dump(self, obj): + return dumps(obj) + + @contextlib.contextmanager + def _open_for_write(self, filepath): + """ + Open *filepath* for writing in a race condition-free way (hopefully). + uuid4 is used to try and avoid name collisions on a shared filesystem. + """ + uid = uuid.uuid4().hex[:16] # avoid long paths + tmpname = '%s.tmp.%s' % (filepath, uid) + try: + with open(tmpname, "wb") as f: + yield f + os.replace(tmpname, filepath) + except Exception: + # In case of error, remove dangling tmp file + try: + os.unlink(tmpname) + except OSError: + pass + raise + + +class Cache(_Cache): + """ + A per-function compilation cache. The cache saves data in separate + data files and maintains information in an index file. + + There is one index file per function and Python version + ("function_name-.pyXY.nbi") which contains a mapping of + signatures and architectures to data files. + It is prefixed by a versioning key and a timestamp of the Python source + file containing the function. + + There is one data file ("function_name-.pyXY..nbc") + per function, function signature, target architecture and Python version. + + Separate index and data files per Python version avoid pickle + compatibility problems. + + Note: + This contains the driver logic only. The core logic is provided + by a subclass of ``CacheImpl`` specified as *_impl_class* in the subclass. + """ + + # The following class variables must be overridden by subclass. + _impl_class = None + + def __init__(self, py_func): + self._name = repr(py_func) + self._py_func = py_func + self._impl = self._impl_class(py_func) + self._cache_path = self._impl.locator.get_cache_path() + # This may be a bit strict but avoids us maintaining a magic number + source_stamp = self._impl.locator.get_source_stamp() + filename_base = self._impl.filename_base + self._cache_file = IndexDataCacheFile(cache_path=self._cache_path, + filename_base=filename_base, + source_stamp=source_stamp) + self.enable() + + def __repr__(self): + return "<%s py_func=%r>" % (self.__class__.__name__, self._name) + + @property + def cache_path(self): + return self._cache_path + + def enable(self): + self._enabled = True + + def disable(self): + self._enabled = False + + def flush(self): + self._cache_file.flush() + + def load_overload(self, sig, target_context): + """ + Load and recreate the cached object for the given signature, + using the *target_context*. + """ + # Refresh the context to ensure it is initialized + target_context.refresh() + with self._guard_against_spurious_io_errors(): + return self._load_overload(sig, target_context) + # None returned if the `with` block swallows an exception + + def _load_overload(self, sig, target_context): + if not self._enabled: + return + key = self._index_key(sig, target_context.codegen()) + data = self._cache_file.load(key) + if data is not None: + data = self._impl.rebuild(target_context, data) + return data + + def save_overload(self, sig, data): + """ + Save the data for the given signature in the cache. + """ + with self._guard_against_spurious_io_errors(): + self._save_overload(sig, data) + + def _save_overload(self, sig, data): + if not self._enabled: + return + if not self._impl.check_cachable(data): + return + self._impl.locator.ensure_cache_path() + key = self._index_key(sig, data.codegen) + data = self._impl.reduce(data) + self._cache_file.save(key, data) + + @contextlib.contextmanager + def _guard_against_spurious_io_errors(self): + if os.name == 'nt': + # Guard against permission errors due to accessing the file + # from several processes (see #2028) + try: + yield + except OSError as e: + if e.errno != errno.EACCES: + raise + else: + # No such conditions under non-Windows OSes + yield + + def _index_key(self, sig, codegen): + """ + Compute index key for the given signature and codegen. + It includes a description of the OS, target architecture and hashes of + the bytecode for the function and, if the function has a __closure__, + a hash of the cell_contents. + """ + codebytes = self._py_func.__code__.co_code + if self._py_func.__closure__ is not None: + cvars = tuple([x.cell_contents for x in self._py_func.__closure__]) + # Note: cloudpickle serializes a function differently depending + # on how the process is launched; e.g. multiprocessing.Process + cvarbytes = dumps(cvars) + else: + cvarbytes = b'' + + hasher = lambda x: hashlib.sha256(x).hexdigest() + return (sig, codegen.magic_tuple(), (hasher(codebytes), + hasher(cvarbytes),)) + + +class FunctionCache(Cache): + """ + Implements Cache that saves and loads CompileResult objects. + """ + _impl_class = CompileResultCacheImpl + + +# Remember used cache filename prefixes. +_lib_cache_prefixes = set(['']) + + +def make_library_cache(prefix): + """ + Create a Cache class for additional compilation features to cache their + result for reuse. The cache is saved in filename pattern like + in ``FunctionCache`` but with additional *prefix* as specified. + """ + # avoid cache prefix reuse + assert prefix not in _lib_cache_prefixes + _lib_cache_prefixes.add(prefix) + + class CustomCodeLibraryCacheImpl(CodeLibraryCacheImpl): + _filename_prefix = prefix + + class LibraryCache(Cache): + """ + Implements Cache that saves and loads CodeLibrary objects for additional + feature for the specified python function. + """ + _impl_class = CustomCodeLibraryCacheImpl + + return LibraryCache + diff --git a/shared/package-files/d1/d1ef819251d0d2126a3e1fb9369e10630d1b18475cbb709929ff754eaeba7503/blob b/shared/package-files/d1/d1ef819251d0d2126a3e1fb9369e10630d1b18475cbb709929ff754eaeba7503/blob new file mode 100644 index 0000000000000000000000000000000000000000..0a1be467a5ea7f2fd3c338db2089c766c6e30787 --- /dev/null +++ b/shared/package-files/d1/d1ef819251d0d2126a3e1fb9369e10630d1b18475cbb709929ff754eaeba7503/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _linalg_slogdet { + using schema = ::std::tuple (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_linalg_slogdet") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_linalg_slogdet(Tensor A) -> (Tensor sign, Tensor logabsdet, Tensor LU, Tensor pivots)") + static ::std::tuple call(const at::Tensor & A); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A); +}; + +struct TORCH_API _linalg_slogdet_sign { + using schema = ::std::tuple (const at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_linalg_slogdet") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "sign") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_linalg_slogdet.sign(Tensor A, *, Tensor(a!) sign, Tensor(b!) logabsdet, Tensor(c!) LU, Tensor(d!) pivots) -> (Tensor(a!) sign, Tensor(b!) logabsdet, Tensor(c!) LU, Tensor(d!) pivots)") + static ::std::tuple call(const at::Tensor & A, at::Tensor & sign, at::Tensor & logabsdet, at::Tensor & LU, at::Tensor & pivots); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A, at::Tensor & sign, at::Tensor & logabsdet, at::Tensor & LU, at::Tensor & pivots); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/d1/d1efc442b3fb93de89fb0988c73f8536fc5099afb761d2b69ec101c239c8c193/blob b/shared/package-files/d1/d1efc442b3fb93de89fb0988c73f8536fc5099afb761d2b69ec101c239c8c193/blob new file mode 100644 index 0000000000000000000000000000000000000000..221068c5885fcbad118283b6c1702a1c55896ec7 --- /dev/null +++ b/shared/package-files/d1/d1efc442b3fb93de89fb0988c73f8536fc5099afb761d2b69ec101c239c8c193/blob @@ -0,0 +1,73 @@ +'''Test warnings replacement in pyshell.py and run.py. + +This file could be expanded to include traceback overrides +(in same two modules). If so, change name. +Revise if output destination changes (http://bugs.python.org/issue18318). +Make sure warnings module is left unaltered (http://bugs.python.org/issue18081). +''' +from idlelib import run +from idlelib import pyshell as shell +import unittest +from test.support import captured_stderr +import warnings + +# Try to capture default showwarning before Idle modules are imported. +showwarning = warnings.showwarning +# But if we run this file within idle, we are in the middle of the run.main loop +# and default showwarnings has already been replaced. +running_in_idle = 'idle' in showwarning.__name__ + +# The following was generated from pyshell.idle_formatwarning +# and checked as matching expectation. +idlemsg = ''' +Warning (from warnings module): + File "test_warning.py", line 99 + Line of code +UserWarning: Test +''' +shellmsg = idlemsg + ">>> " + + +class RunWarnTest(unittest.TestCase): + + @unittest.skipIf(running_in_idle, "Does not work when run within Idle.") + def test_showwarnings(self): + self.assertIs(warnings.showwarning, showwarning) + run.capture_warnings(True) + self.assertIs(warnings.showwarning, run.idle_showwarning_subproc) + run.capture_warnings(False) + self.assertIs(warnings.showwarning, showwarning) + + def test_run_show(self): + with captured_stderr() as f: + run.idle_showwarning_subproc( + 'Test', UserWarning, 'test_warning.py', 99, f, 'Line of code') + # The following uses .splitlines to erase line-ending differences + self.assertEqual(idlemsg.splitlines(), f.getvalue().splitlines()) + + +class ShellWarnTest(unittest.TestCase): + + @unittest.skipIf(running_in_idle, "Does not work when run within Idle.") + def test_showwarnings(self): + self.assertIs(warnings.showwarning, showwarning) + shell.capture_warnings(True) + self.assertIs(warnings.showwarning, shell.idle_showwarning) + shell.capture_warnings(False) + self.assertIs(warnings.showwarning, showwarning) + + def test_idle_formatter(self): + # Will fail if format changed without regenerating idlemsg + s = shell.idle_formatwarning( + 'Test', UserWarning, 'test_warning.py', 99, 'Line of code') + self.assertEqual(idlemsg, s) + + def test_shell_show(self): + with captured_stderr() as f: + shell.idle_showwarning( + 'Test', UserWarning, 'test_warning.py', 99, f, 'Line of code') + self.assertEqual(shellmsg.splitlines(), f.getvalue().splitlines()) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/shared/package-files/d1/d1efe233bd4d377b622ad09f65035bf89e2dfcbec5a0b0444c2e235c5773acd7/blob b/shared/package-files/d1/d1efe233bd4d377b622ad09f65035bf89e2dfcbec5a0b0444c2e235c5773acd7/blob new file mode 100644 index 0000000000000000000000000000000000000000..f321d20aa43606b0e0f9e2bbf746a568cd5fec32 --- /dev/null +++ b/shared/package-files/d1/d1efe233bd4d377b622ad09f65035bf89e2dfcbec5a0b0444c2e235c5773acd7/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1efe233bd4d377b622ad09f65035bf89e2dfcbec5a0b0444c2e235c5773acd7 +size 1626249 diff --git a/shared/package-files/d1/d1f210faf52f31c0f5dcdaa1624e143424da8f1b19485a9d4274aa04fe15ad2c/blob b/shared/package-files/d1/d1f210faf52f31c0f5dcdaa1624e143424da8f1b19485a9d4274aa04fe15ad2c/blob new file mode 100644 index 0000000000000000000000000000000000000000..a0515b302ebfeb2d69119bd59f0d2d5209ea52f2 --- /dev/null +++ b/shared/package-files/d1/d1f210faf52f31c0f5dcdaa1624e143424da8f1b19485a9d4274aa04fe15ad2c/blob @@ -0,0 +1,62 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PCD file handling +# +# History: +# 96-05-10 fl Created +# 96-05-27 fl Added draft mode (128x192, 256x384) +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image, ImageFile + +## +# Image plugin for PhotoCD images. This plugin only reads the 768x512 +# image from the file; higher resolutions are encoded in a proprietary +# encoding. + + +class PcdImageFile(ImageFile.ImageFile): + format = "PCD" + format_description = "Kodak PhotoCD" + + def _open(self): + # rough + self.fp.seek(2048) + s = self.fp.read(2048) + + if s[:4] != b"PCD_": + msg = "not a PCD file" + raise SyntaxError(msg) + + orientation = s[1538] & 3 + self.tile_post_rotate = None + if orientation == 1: + self.tile_post_rotate = 90 + elif orientation == 3: + self.tile_post_rotate = -90 + + self._mode = "RGB" + self._size = 768, 512 # FIXME: not correct for rotated images! + self.tile = [("pcd", (0, 0) + self.size, 96 * 2048, None)] + + def load_end(self): + if self.tile_post_rotate: + # Handle rotated PCDs + self.im = self.im.rotate(self.tile_post_rotate) + self._size = self.im.size + + +# +# registry + +Image.register_open(PcdImageFile.format, PcdImageFile) + +Image.register_extension(PcdImageFile.format, ".pcd") diff --git a/shared/package-files/d1/d1f35a4bf68445add43117374f958ca4dfecba6b43c5f6a8af6cb7a1fd5fb419/blob b/shared/package-files/d1/d1f35a4bf68445add43117374f958ca4dfecba6b43c5f6a8af6cb7a1fd5fb419/blob new file mode 100644 index 0000000000000000000000000000000000000000..fd00ce6e4cea506f3ab08e6412d2eb6443ef582c --- /dev/null +++ b/shared/package-files/d1/d1f35a4bf68445add43117374f958ca4dfecba6b43c5f6a8af6cb7a1fd5fb419/blob @@ -0,0 +1,130 @@ +from typing import Union + +from .align import AlignMethod +from .cells import cell_len, set_cell_size +from .console import Console, ConsoleOptions, RenderResult +from .jupyter import JupyterMixin +from .measure import Measurement +from .style import Style +from .text import Text + + +class Rule(JupyterMixin): + """A console renderable to draw a horizontal rule (line). + + Args: + title (Union[str, Text], optional): Text to render in the rule. Defaults to "". + characters (str, optional): Character(s) used to draw the line. Defaults to "─". + style (StyleType, optional): Style of Rule. Defaults to "rule.line". + end (str, optional): Character at end of Rule. defaults to "\\\\n" + align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center". + """ + + def __init__( + self, + title: Union[str, Text] = "", + *, + characters: str = "─", + style: Union[str, Style] = "rule.line", + end: str = "\n", + align: AlignMethod = "center", + ) -> None: + if cell_len(characters) < 1: + raise ValueError( + "'characters' argument must have a cell width of at least 1" + ) + if align not in ("left", "center", "right"): + raise ValueError( + f'invalid value for align, expected "left", "center", "right" (not {align!r})' + ) + self.title = title + self.characters = characters + self.style = style + self.end = end + self.align = align + + def __repr__(self) -> str: + return f"Rule({self.title!r}, {self.characters!r})" + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + width = options.max_width + + characters = ( + "-" + if (options.ascii_only and not self.characters.isascii()) + else self.characters + ) + + chars_len = cell_len(characters) + if not self.title: + yield self._rule_line(chars_len, width) + return + + if isinstance(self.title, Text): + title_text = self.title + else: + title_text = console.render_str(self.title, style="rule.text") + + title_text.plain = title_text.plain.replace("\n", " ") + title_text.expand_tabs() + + required_space = 4 if self.align == "center" else 2 + truncate_width = max(0, width - required_space) + if not truncate_width: + yield self._rule_line(chars_len, width) + return + + rule_text = Text(end=self.end) + if self.align == "center": + title_text.truncate(truncate_width, overflow="ellipsis") + side_width = (width - cell_len(title_text.plain)) // 2 + left = Text(characters * (side_width // chars_len + 1)) + left.truncate(side_width - 1) + right_length = width - cell_len(left.plain) - cell_len(title_text.plain) + right = Text(characters * (side_width // chars_len + 1)) + right.truncate(right_length) + rule_text.append(left.plain + " ", self.style) + rule_text.append(title_text) + rule_text.append(" " + right.plain, self.style) + elif self.align == "left": + title_text.truncate(truncate_width, overflow="ellipsis") + rule_text.append(title_text) + rule_text.append(" ") + rule_text.append(characters * (width - rule_text.cell_len), self.style) + elif self.align == "right": + title_text.truncate(truncate_width, overflow="ellipsis") + rule_text.append(characters * (width - title_text.cell_len - 1), self.style) + rule_text.append(" ") + rule_text.append(title_text) + + rule_text.plain = set_cell_size(rule_text.plain, width) + yield rule_text + + def _rule_line(self, chars_len: int, width: int) -> Text: + rule_text = Text(self.characters * ((width // chars_len) + 1), self.style) + rule_text.truncate(width) + rule_text.plain = set_cell_size(rule_text.plain, width) + return rule_text + + def __rich_measure__( + self, console: Console, options: ConsoleOptions + ) -> Measurement: + return Measurement(1, 1) + + +if __name__ == "__main__": # pragma: no cover + import sys + + from pip._vendor.rich.console import Console + + try: + text = sys.argv[1] + except IndexError: + text = "Hello, World" + console = Console() + console.print(Rule(title=text)) + + console = Console() + console.print(Rule("foo"), width=4) diff --git a/shared/package-files/d1/d1f3777951557b01be0d2564f71240043401d52fcdca7dfb6c73a38f95fc066d/blob b/shared/package-files/d1/d1f3777951557b01be0d2564f71240043401d52fcdca7dfb6c73a38f95fc066d/blob new file mode 100644 index 0000000000000000000000000000000000000000..2684d8f8b89f7807ed4a0fcba89822b24a0166bb Binary files /dev/null and b/shared/package-files/d1/d1f3777951557b01be0d2564f71240043401d52fcdca7dfb6c73a38f95fc066d/blob differ diff --git a/shared/package-files/d1/d1f3b8af2e6e0f0ea8fb0be7a018527fcb2708aea0779c9342ac3a6f54552637/blob b/shared/package-files/d1/d1f3b8af2e6e0f0ea8fb0be7a018527fcb2708aea0779c9342ac3a6f54552637/blob new file mode 100644 index 0000000000000000000000000000000000000000..2d6042adcfc1007bb1ed6e8eed81ab9dc9c4991a --- /dev/null +++ b/shared/package-files/d1/d1f3b8af2e6e0f0ea8fb0be7a018527fcb2708aea0779c9342ac3a6f54552637/blob @@ -0,0 +1,133 @@ +import logging +from argparse import ArgumentParser +from io import StringIO +from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, Type +from unittest import TestCase, TestSuite, TextTestResult + +from django.db.backends.base.base import BaseDatabaseWrapper +from django.test.testcases import SimpleTestCase, TestCase +from django.utils.datastructures import OrderedSet + +class DebugSQLTextTestResult(TextTestResult): + buffer: bool + descriptions: bool + dots: bool + expectedFailures: List[Any] + failfast: bool + shouldStop: bool + showAll: bool + skipped: List[Any] + tb_locals: bool + testsRun: int + unexpectedSuccesses: List[Any] + logger: logging.Logger = ... + def __init__(self, stream: Any, descriptions: bool, verbosity: int) -> None: ... + debug_sql_stream: StringIO = ... + handler: logging.StreamHandler = ... + def startTest(self, test: TestCase) -> None: ... + def stopTest(self, test: TestCase) -> None: ... + def addError(self, test: Any, err: Any) -> None: ... + def addFailure(self, test: Any, err: Any) -> None: ... + +class RemoteTestResult: + events: List[Any] = ... + failfast: bool = ... + shouldStop: bool = ... + testsRun: int = ... + def __init__(self) -> None: ... + @property + def test_index(self): ... + def check_picklable(self, test: Any, err: Any) -> None: ... + def _confirm_picklable(self, obj: Any) -> None: ... + def check_subtest_picklable(self, test: Any, subtest: Any) -> None: ... + def stop_if_failfast(self) -> None: ... + def stop(self) -> None: ... + def startTestRun(self) -> None: ... + def stopTestRun(self) -> None: ... + def startTest(self, test: Any) -> None: ... + def stopTest(self, test: Any) -> None: ... + def addError(self, test: Any, err: Any) -> None: ... + def addFailure(self, test: Any, err: Any) -> None: ... + def addSubTest(self, test: Any, subtest: Any, err: Any) -> None: ... + def addSuccess(self, test: Any) -> None: ... + def addSkip(self, test: Any, reason: Any) -> None: ... + def addExpectedFailure(self, test: Any, err: Any) -> None: ... + def addUnexpectedSuccess(self, test: Any) -> None: ... + +class RemoteTestRunner: + resultclass: Any = ... + failfast: Any = ... + def __init__(self, failfast: bool = ..., resultclass: Optional[Any] = ...) -> None: ... + def run(self, test: Any): ... + +def default_test_processes() -> int: ... + +class ParallelTestSuite(TestSuite): + init_worker: Any = ... + run_subsuite: Any = ... + runner_class: Any = ... + subsuites: Any = ... + processes: Any = ... + failfast: Any = ... + def __init__(self, suite: Any, processes: Any, failfast: bool = ...) -> None: ... + def run(self, result: Any): ... + +class DiscoverRunner: + test_suite: Any = ... + parallel_test_suite: Any = ... + test_runner: Any = ... + test_loader: Any = ... + reorder_by: Any = ... + pattern: Optional[str] = ... + top_level: None = ... + verbosity: int = ... + interactive: bool = ... + failfast: bool = ... + keepdb: bool = ... + reverse: bool = ... + debug_mode: bool = ... + debug_sql: bool = ... + parallel: int = ... + tags: Set[str] = ... + exclude_tags: Set[str] = ... + def __init__( + self, + pattern: Optional[str] = ..., + top_level: None = ..., + verbosity: int = ..., + interactive: bool = ..., + failfast: bool = ..., + keepdb: bool = ..., + reverse: bool = ..., + debug_mode: bool = ..., + debug_sql: bool = ..., + parallel: int = ..., + tags: Optional[List[str]] = ..., + exclude_tags: Optional[List[str]] = ..., + **kwargs: Any + ) -> None: ... + @classmethod + def add_arguments(cls, parser: ArgumentParser) -> None: ... + def setup_test_environment(self, **kwargs: Any) -> None: ... + def build_suite( + self, test_labels: Sequence[str] = ..., extra_tests: Optional[List[Any]] = ..., **kwargs: Any + ) -> TestSuite: ... + def setup_databases(self, **kwargs: Any) -> List[Tuple[BaseDatabaseWrapper, str, bool]]: ... + def get_resultclass(self) -> Optional[Type[DebugSQLTextTestResult]]: ... + def get_test_runner_kwargs(self) -> Dict[str, Optional[int]]: ... + def run_checks(self) -> None: ... + def run_suite(self, suite: TestSuite, **kwargs: Any) -> TextTestResult: ... + def teardown_databases(self, old_config: List[Tuple[BaseDatabaseWrapper, str, bool]], **kwargs: Any) -> None: ... + def teardown_test_environment(self, **kwargs: Any) -> None: ... + def suite_result(self, suite: TestSuite, result: TextTestResult, **kwargs: Any) -> int: ... + def run_tests(self, test_labels: List[str], extra_tests: List[Any] = ..., **kwargs: Any) -> int: ... + +def is_discoverable(label: str) -> bool: ... +def reorder_suite( + suite: TestSuite, classes: Tuple[Type[TestCase], Type[SimpleTestCase]], reverse: bool = ... +) -> TestSuite: ... +def partition_suite_by_type( + suite: TestSuite, classes: Tuple[Type[TestCase], Type[SimpleTestCase]], bins: List[OrderedSet], reverse: bool = ... +) -> None: ... +def partition_suite_by_case(suite: Any): ... +def filter_tests_by_tags(suite: TestSuite, tags: Set[str], exclude_tags: Set[str]) -> TestSuite: ... diff --git a/shared/package-files/d1/d1f45c1db09963f805770217204967a46bd3c5e039c55c591f5fafc19875e923/blob b/shared/package-files/d1/d1f45c1db09963f805770217204967a46bd3c5e039c55c591f5fafc19875e923/blob new file mode 100644 index 0000000000000000000000000000000000000000..39ca53908a68b14966583d3568703da2c0ab408c --- /dev/null +++ b/shared/package-files/d1/d1f45c1db09963f805770217204967a46bd3c5e039c55c591f5fafc19875e923/blob @@ -0,0 +1,109 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# distutils: language = c++ + +from pyarrow.includes.libarrow cimport * + +cdef extern from "arrow/gpu/cuda_api.h" namespace "arrow::cuda" nogil: + + cdef cppclass CCudaDeviceManager" arrow::cuda::CudaDeviceManager": + @staticmethod + CResult[CCudaDeviceManager*] Instance() + CResult[shared_ptr[CCudaContext]] GetContext(int gpu_number) + CResult[shared_ptr[CCudaContext]] GetSharedContext(int gpu_number, + void* handle) + CStatus AllocateHost(int device_number, int64_t nbytes, + shared_ptr[CCudaHostBuffer]* buffer) + int num_devices() const + + cdef cppclass CCudaContext" arrow::cuda::CudaContext": + CResult[shared_ptr[CCudaBuffer]] Allocate(int64_t nbytes) + CResult[shared_ptr[CCudaBuffer]] View(uint8_t* data, int64_t nbytes) + CResult[shared_ptr[CCudaBuffer]] OpenIpcBuffer( + const CCudaIpcMemHandle& ipc_handle) + CStatus Synchronize() + int64_t bytes_allocated() const + const void* handle() const + int device_number() const + CResult[uintptr_t] GetDeviceAddress(uintptr_t addr) + shared_ptr[CDevice] device() const + shared_ptr[CMemoryManager] memory_manager() const + + cdef cppclass CCudaIpcMemHandle" arrow::cuda::CudaIpcMemHandle": + @staticmethod + CResult[shared_ptr[CCudaIpcMemHandle]] FromBuffer( + const void* opaque_handle) + CResult[shared_ptr[CBuffer]] Serialize(CMemoryPool* pool) const + + cdef cppclass CCudaBuffer" arrow::cuda::CudaBuffer"(CBuffer): + CCudaBuffer(uint8_t* data, int64_t size, + const shared_ptr[CCudaContext]& context, + c_bool own_data=false, c_bool is_ipc=false) + CCudaBuffer(const shared_ptr[CCudaBuffer]& parent, + const int64_t offset, const int64_t size) + + @staticmethod + CResult[shared_ptr[CCudaBuffer]] FromBuffer(shared_ptr[CBuffer] buf) + + CStatus CopyToHost(const int64_t position, const int64_t nbytes, + void* out) const + CStatus CopyFromHost(const int64_t position, const void* data, + int64_t nbytes) + CStatus CopyFromDevice(const int64_t position, const void* data, + int64_t nbytes) + CStatus CopyFromAnotherDevice(const shared_ptr[CCudaContext]& src_ctx, + const int64_t position, const void* data, + int64_t nbytes) + CResult[shared_ptr[CCudaIpcMemHandle]] ExportForIpc() + shared_ptr[CCudaContext] context() const + + cdef cppclass \ + CCudaHostBuffer" arrow::cuda::CudaHostBuffer"(CMutableBuffer): + pass + + cdef cppclass \ + CCudaBufferReader" arrow::cuda::CudaBufferReader"(CBufferReader): + CCudaBufferReader(const shared_ptr[CBuffer]& buffer) + CResult[int64_t] Read(int64_t nbytes, void* buffer) + CResult[shared_ptr[CBuffer]] Read(int64_t nbytes) + + cdef cppclass \ + CCudaBufferWriter" arrow::cuda::CudaBufferWriter"(WritableFile): + CCudaBufferWriter(const shared_ptr[CCudaBuffer]& buffer) + CStatus Close() + CStatus Write(const void* data, int64_t nbytes) + CStatus WriteAt(int64_t position, const void* data, int64_t nbytes) + CStatus SetBufferSize(const int64_t buffer_size) + int64_t buffer_size() + int64_t num_bytes_buffered() const + + CResult[shared_ptr[CCudaHostBuffer]] AllocateCudaHostBuffer( + int device_number, const int64_t size) + + # Cuda prefix is added to avoid picking up arrow::cuda functions + # from arrow namespace. + CResult[shared_ptr[CCudaBuffer]] \ + CudaSerializeRecordBatch" arrow::cuda::SerializeRecordBatch"\ + (const CRecordBatch& batch, + CCudaContext* ctx) + CResult[shared_ptr[CRecordBatch]] \ + CudaReadRecordBatch" arrow::cuda::ReadRecordBatch"\ + (const shared_ptr[CSchema]& schema, + CDictionaryMemo* dictionary_memo, + const shared_ptr[CCudaBuffer]& buffer, + CMemoryPool* pool) diff --git a/shared/package-files/d1/d1f4a974b06d107ed93ffb6b549ed13f136d397f6c27fcfe32436c6d4c45f273/blob b/shared/package-files/d1/d1f4a974b06d107ed93ffb6b549ed13f136d397f6c27fcfe32436c6d4c45f273/blob new file mode 100644 index 0000000000000000000000000000000000000000..f1b6c5e595cbca4899cf169a6a85b917ad98bfb4 --- /dev/null +++ b/shared/package-files/d1/d1f4a974b06d107ed93ffb6b549ed13f136d397f6c27fcfe32436c6d4c45f273/blob @@ -0,0 +1,25 @@ +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import Any, TypeVar +from typing_extensions import ParamSpec + +from matplotlib.figure import Figure +from matplotlib.typing import RcStyleType + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +def remove_ticks_and_titles(figure: Figure) -> None: ... +def image_comparison( + baseline_images: list[str] | None, + extensions: list[str] | None = ..., + tol: float = ..., + freetype_version: tuple[str, str] | str | None = ..., + remove_text: bool = ..., + savefig_kwarg: dict[str, Any] | None = ..., + style: RcStyleType = ..., +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +def check_figures_equal( + *, extensions: Sequence[str] = ..., tol: float = ... +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +def _image_directories(func: Callable) -> tuple[Path, Path]: ... diff --git a/shared/package-files/d1/d1f7abe9246c9708d321baac37298a3debbe0babdb4997aade0028534e1e3a1b/blob b/shared/package-files/d1/d1f7abe9246c9708d321baac37298a3debbe0babdb4997aade0028534e1e3a1b/blob new file mode 100644 index 0000000000000000000000000000000000000000..6f1588b08b51eff84953b137aa4914d36e294b14 --- /dev/null +++ b/shared/package-files/d1/d1f7abe9246c9708d321baac37298a3debbe0babdb4997aade0028534e1e3a1b/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor _addmm_activation(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta=1, const at::Scalar & alpha=1, bool use_gelu=false); +TORCH_API at::Tensor & _addmm_activation_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta=1, const at::Scalar & alpha=1, bool use_gelu=false); +TORCH_API at::Tensor & _addmm_activation_outf(const at::Tensor & self, const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha, bool use_gelu, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/d1/d1fdf25231f4db8695c9feb36ae3a3d6f84e9b09626d0b3b0854142429286b4d/blob b/shared/package-files/d1/d1fdf25231f4db8695c9feb36ae3a3d6f84e9b09626d0b3b0854142429286b4d/blob new file mode 100644 index 0000000000000000000000000000000000000000..743162dbc478d597da48a06d600fcef2cecc6f51 --- /dev/null +++ b/shared/package-files/d1/d1fdf25231f4db8695c9feb36ae3a3d6f84e9b09626d0b3b0854142429286b4d/blob @@ -0,0 +1,177 @@ +"""Customizations of :mod:`joblib` and :mod:`threadpoolctl` tools for scikit-learn +usage. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import functools +import warnings +from functools import update_wrapper + +import joblib +from threadpoolctl import ThreadpoolController + +from .._config import config_context, get_config + +# Global threadpool controller instance that can be used to locally limit the number of +# threads without looping through all shared libraries every time. +# It should not be accessed directly and _get_threadpool_controller should be used +# instead. +_threadpool_controller = None + + +def _with_config_and_warning_filters(delayed_func, config, warning_filters): + """Helper function that intends to attach a config to a delayed function.""" + if hasattr(delayed_func, "with_config_and_warning_filters"): + return delayed_func.with_config_and_warning_filters(config, warning_filters) + else: + warnings.warn( + ( + "`sklearn.utils.parallel.Parallel` needs to be used in " + "conjunction with `sklearn.utils.parallel.delayed` instead of " + "`joblib.delayed` to correctly propagate the scikit-learn " + "configuration to the joblib workers." + ), + UserWarning, + ) + return delayed_func + + +class Parallel(joblib.Parallel): + """Tweak of :class:`joblib.Parallel` that propagates the scikit-learn configuration. + + This subclass of :class:`joblib.Parallel` ensures that the active configuration + (thread-local) of scikit-learn is propagated to the parallel workers for the + duration of the execution of the parallel tasks. + + The API does not change and you can refer to :class:`joblib.Parallel` + documentation for more details. + + .. versionadded:: 1.3 + """ + + def __call__(self, iterable): + """Dispatch the tasks and return the results. + + Parameters + ---------- + iterable : iterable + Iterable containing tuples of (delayed_function, args, kwargs) that should + be consumed. + + Returns + ------- + results : list + List of results of the tasks. + """ + # Capture the thread-local scikit-learn configuration at the time + # Parallel.__call__ is issued since the tasks can be dispatched + # in a different thread depending on the backend and on the value of + # pre_dispatch and n_jobs. + config = get_config() + warning_filters = warnings.filters + iterable_with_config_and_warning_filters = ( + ( + _with_config_and_warning_filters(delayed_func, config, warning_filters), + args, + kwargs, + ) + for delayed_func, args, kwargs in iterable + ) + return super().__call__(iterable_with_config_and_warning_filters) + + +# remove when https://github.com/joblib/joblib/issues/1071 is fixed +def delayed(function): + """Decorator used to capture the arguments of a function. + + This alternative to `joblib.delayed` is meant to be used in conjunction + with `sklearn.utils.parallel.Parallel`. The latter captures the scikit- + learn configuration by calling `sklearn.get_config()` in the current + thread, prior to dispatching the first task. The captured configuration is + then propagated and enabled for the duration of the execution of the + delayed function in the joblib workers. + + .. versionchanged:: 1.3 + `delayed` was moved from `sklearn.utils.fixes` to `sklearn.utils.parallel` + in scikit-learn 1.3. + + Parameters + ---------- + function : callable + The function to be delayed. + + Returns + ------- + output: tuple + Tuple containing the delayed function, the positional arguments, and the + keyword arguments. + """ + + @functools.wraps(function) + def delayed_function(*args, **kwargs): + return _FuncWrapper(function), args, kwargs + + return delayed_function + + +class _FuncWrapper: + """Load the global configuration before calling the function.""" + + def __init__(self, function): + self.function = function + update_wrapper(self, self.function) + + def with_config_and_warning_filters(self, config, warning_filters): + self.config = config + self.warning_filters = warning_filters + return self + + def __call__(self, *args, **kwargs): + config = getattr(self, "config", {}) + warning_filters = getattr(self, "warning_filters", []) + if not config or not warning_filters: + warnings.warn( + ( + "`sklearn.utils.parallel.delayed` should be used with" + " `sklearn.utils.parallel.Parallel` to make it possible to" + " propagate the scikit-learn configuration of the current thread to" + " the joblib workers." + ), + UserWarning, + ) + + with config_context(**config), warnings.catch_warnings(): + warnings.filters = warning_filters + return self.function(*args, **kwargs) + + +def _get_threadpool_controller(): + """Return the global threadpool controller instance.""" + global _threadpool_controller + + if _threadpool_controller is None: + _threadpool_controller = ThreadpoolController() + + return _threadpool_controller + + +def _threadpool_controller_decorator(limits=1, user_api="blas"): + """Decorator to limit the number of threads used at the function level. + + It should be preferred over `threadpoolctl.ThreadpoolController.wrap` because this + one only loads the shared libraries when the function is called while the latter + loads them at import time. + """ + + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + controller = _get_threadpool_controller() + with controller.limit(limits=limits, user_api=user_api): + return func(*args, **kwargs) + + return wrapper + + return decorator diff --git a/shared/package-files/d2/d20011bf40db322ec359473bf77a5de1fec82b149e3a592393f79ecfcb4b8a1b/blob b/shared/package-files/d2/d20011bf40db322ec359473bf77a5de1fec82b149e3a592393f79ecfcb4b8a1b/blob new file mode 100644 index 0000000000000000000000000000000000000000..fc4928c31eca6c1b5c0999b99bcbfd1a95e18d1f --- /dev/null +++ b/shared/package-files/d2/d20011bf40db322ec359473bf77a5de1fec82b149e3a592393f79ecfcb4b8a1b/blob @@ -0,0 +1,103 @@ +""" + pygments.lexers.sophia + ~~~~~~~~~~~~~~~~~~~~~~ + + Lexer for Sophia. + + Derived from pygments/lexers/reason.py. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.lexer import RegexLexer, include, default, words +from pygments.token import Comment, Keyword, Name, Number, Operator, \ + Punctuation, String, Text + +__all__ = ['SophiaLexer'] + +class SophiaLexer(RegexLexer): + """ + A Sophia lexer. + + .. versionadded:: 2.11 + """ + + name = 'Sophia' + aliases = ['sophia'] + filenames = ['*.aes'] + mimetypes = [] + + keywords = ( + 'contract', 'include', 'let', 'switch', 'type', 'record', 'datatype', + 'if', 'elif', 'else', 'function', 'stateful', 'payable', 'public', + 'entrypoint', 'private', 'indexed', 'namespace', 'interface', 'main', + 'using', 'as', 'for', 'hiding', + ) + + builtins = ('state', 'put', 'abort', 'require') + + word_operators = ('mod', 'band', 'bor', 'bxor', 'bnot') + + primitive_types = ('int', 'address', 'bool', 'bits', 'bytes', 'string', + 'list', 'option', 'char', 'unit', 'map', 'event', + 'hash', 'signature', 'oracle', 'oracle_query') + + tokens = { + 'escape-sequence': [ + (r'\\[\\"\'ntbr]', String.Escape), + (r'\\[0-9]{3}', String.Escape), + (r'\\x[0-9a-fA-F]{2}', String.Escape), + ], + 'root': [ + (r'\s+', Text.Whitespace), + (r'(true|false)\b', Keyword.Constant), + (r'\b([A-Z][\w\']*)(?=\s*\.)', Name.Class, 'dotted'), + (r'\b([A-Z][\w\']*)', Name.Function), + (r'//.*?\n', Comment.Single), + (r'\/\*(?!/)', Comment.Multiline, 'comment'), + + (r'0[xX][\da-fA-F][\da-fA-F_]*', Number.Hex), + (r'#[\da-fA-F][\da-fA-F_]*', Name.Label), + (r'\d[\d_]*', Number.Integer), + + (words(keywords, suffix=r'\b'), Keyword), + (words(builtins, suffix=r'\b'), Name.Builtin), + (words(word_operators, prefix=r'\b', suffix=r'\b'), Operator.Word), + (words(primitive_types, prefix=r'\b', suffix=r'\b'), Keyword.Type), + + (r'[=!<>+\\*/:&|?~@^-]', Operator.Word), + (r'[.;:{}(),\[\]]', Punctuation), + + (r"(ak_|ok_|oq_|ct_)[\w']*", Name.Label), + (r"[^\W\d][\w']*", Name), + + (r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'", + String.Char), + (r"'.'", String.Char), + (r"'[a-z][\w]*", Name.Variable), + + (r'"', String.Double, 'string') + ], + 'comment': [ + (r'[^/*]+', Comment.Multiline), + (r'\/\*', Comment.Multiline, '#push'), + (r'\*\/', Comment.Multiline, '#pop'), + (r'\*', Comment.Multiline), + ], + 'string': [ + (r'[^\\"]+', String.Double), + include('escape-sequence'), + (r'\\\n', String.Double), + (r'"', String.Double, '#pop'), + ], + 'dotted': [ + (r'\s+', Text), + (r'\.', Punctuation), + (r'[A-Z][\w\']*(?=\s*\.)', Name.Function), + (r'[A-Z][\w\']*', Name.Function, '#pop'), + (r'[a-z_][\w\']*', Name, '#pop'), + default('#pop'), + ], + } + diff --git a/shared/package-files/d2/d2078a7adef7acfeff671d63f6176a3d9772757128f8e208dc5b6e21303593c0/blob b/shared/package-files/d2/d2078a7adef7acfeff671d63f6176a3d9772757128f8e208dc5b6e21303593c0/blob new file mode 100644 index 0000000000000000000000000000000000000000..e7f27a26eae38fe5bf692f87f0e367053eab0460 --- /dev/null +++ b/shared/package-files/d2/d2078a7adef7acfeff671d63f6176a3d9772757128f8e208dc5b6e21303593c0/blob @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_leaky_relu_backward : public TensorIteratorBase { + + + void meta(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & negative_slope, bool self_is_result); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/d2/d20a49525e3a8506e9d0fe978f54b4340ac859e02bcaeb835e3b2576f0791871/blob b/shared/package-files/d2/d20a49525e3a8506e9d0fe978f54b4340ac859e02bcaeb835e3b2576f0791871/blob new file mode 100644 index 0000000000000000000000000000000000000000..cdda168cb97b1d45a4f1b7791a74523b74c88e6d Binary files /dev/null and b/shared/package-files/d2/d20a49525e3a8506e9d0fe978f54b4340ac859e02bcaeb835e3b2576f0791871/blob differ diff --git a/shared/package-files/d2/d20accd92757fef663a43e78d0ee88fe01d9333379eda463c9e15f0e7785e490/blob b/shared/package-files/d2/d20accd92757fef663a43e78d0ee88fe01d9333379eda463c9e15f0e7785e490/blob new file mode 100644 index 0000000000000000000000000000000000000000..7a44d3eb3016f90c07dfe55888a7787b1748e95e --- /dev/null +++ b/shared/package-files/d2/d20accd92757fef663a43e78d0ee88fe01d9333379eda463c9e15f0e7785e490/blob @@ -0,0 +1,489 @@ +""" +Implement Dominance-Fronter-based SSA by Choi et al described in Inria SSA book + +References: + +- Static Single Assignment Book by Inria + http://ssabook.gforge.inria.fr/latest/book.pdf +- Choi et al. Incremental computation of static single assignment form. +""" +import logging +import operator +import warnings +from functools import reduce +from copy import copy +from collections import defaultdict + +from numba import config +from numba.core import ir, ir_utils, errors +from numba.core.utils import OrderedSet, _lazy_pformat +from numba.core.analysis import compute_cfg_from_blocks + + +_logger = logging.getLogger(__name__) + + +def reconstruct_ssa(func_ir): + """Apply SSA reconstruction algorithm on the given IR. + + Produces minimal SSA using Choi et al algorithm. + """ + func_ir.blocks = _run_ssa(func_ir.blocks) + + return func_ir + + +class _CacheListVars: + def __init__(self): + self._saved = {} + + def get(self, inst): + got = self._saved.get(inst) + if got is None: + self._saved[inst] = got = inst.list_vars() + return got + + +def _run_ssa(blocks): + """Run SSA reconstruction on IR blocks of a function. + """ + if not blocks: + # Empty blocks? + return {} + # Run CFG on the blocks + cfg = compute_cfg_from_blocks(blocks) + df_plus = _iterated_domfronts(cfg) + # Find SSA violators + violators = _find_defs_violators(blocks, cfg) + # Make cache for .list_vars() + cache_list_vars = _CacheListVars() + + # Process one SSA-violating variable at a time + for varname in violators: + _logger.debug( + "Fix SSA violator on var %s", varname, + ) + # Fix up the LHS + # Put fresh variables for all assignments to the variable + blocks, defmap = _fresh_vars(blocks, varname) + _logger.debug("Replaced assignments: %s", _lazy_pformat(defmap)) + # Fix up the RHS + # Re-associate the variable uses with the reaching definition + blocks = _fix_ssa_vars(blocks, varname, defmap, cfg, df_plus, + cache_list_vars) + + # Post-condition checks. + # CFG invariant + cfg_post = compute_cfg_from_blocks(blocks) + if cfg_post != cfg: + raise errors.CompilerError("CFG mutated in SSA pass") + return blocks + + +def _fix_ssa_vars(blocks, varname, defmap, cfg, df_plus, cache_list_vars): + """Rewrite all uses to ``varname`` given the definition map + """ + states = _make_states(blocks) + states['varname'] = varname + states['defmap'] = defmap + states['phimap'] = phimap = defaultdict(list) + states['cfg'] = cfg + states['phi_locations'] = _compute_phi_locations(df_plus, defmap) + newblocks = _run_block_rewrite(blocks, states, _FixSSAVars(cache_list_vars)) + # insert phi nodes + for label, philist in phimap.items(): + curblk = newblocks[label] + # Prepend PHI nodes to the block + curblk.body = philist + curblk.body + return newblocks + + +def _iterated_domfronts(cfg): + """Compute the iterated dominance frontiers (DF+ in literatures). + + Returns a dictionary which maps block label to the set of labels of its + iterated dominance frontiers. + """ + domfronts = {k: set(vs) for k, vs in cfg.dominance_frontier().items()} + keep_going = True + while keep_going: + keep_going = False + for k, vs in domfronts.items(): + inner = reduce(operator.or_, [domfronts[v] for v in vs], set()) + if inner.difference(vs): + vs |= inner + keep_going = True + return domfronts + + +def _compute_phi_locations(iterated_df, defmap): + # See basic algorithm in Ch 4.1 in Inria SSA Book + # Compute DF+(defs) + # DF of all DFs is the union of all DFs + phi_locations = set() + for deflabel, defstmts in defmap.items(): + if defstmts: + phi_locations |= iterated_df[deflabel] + return phi_locations + + +def _fresh_vars(blocks, varname): + """Rewrite to put fresh variable names + """ + states = _make_states(blocks) + states['varname'] = varname + states['defmap'] = defmap = defaultdict(list) + newblocks = _run_block_rewrite(blocks, states, _FreshVarHandler()) + return newblocks, defmap + + +def _get_scope(blocks): + first, *_ = blocks.values() + return first.scope + + +def _find_defs_violators(blocks, cfg): + """ + Returns + ------- + res : Set[str] + The SSA violators in a dictionary of variable names. + """ + defs = defaultdict(list) + uses = defaultdict(set) + states = dict(defs=defs, uses=uses) + _run_block_analysis(blocks, states, _GatherDefsHandler()) + _logger.debug("defs %s", _lazy_pformat(defs)) + # Gather violators by number of definitions. + # The violators are added by the order that they are seen and the algorithm + # scan from the first to the last basic-block as they occur in bytecode. + violators = OrderedSet([k for k, vs in defs.items() if len(vs) > 1]) + # Gather violators by uses not dominated by the one def + doms = cfg.dominators() + for k, use_blocks in uses.items(): + if k not in violators: + for label in use_blocks: + dom = doms[label] + def_labels = {label for _assign, label in defs[k] } + if not def_labels.intersection(dom): + violators.add(k) + break + _logger.debug("SSA violators %s", _lazy_pformat(violators)) + return violators + + +def _run_block_analysis(blocks, states, handler): + for label, blk in blocks.items(): + _logger.debug("==== SSA block analysis pass on %s", label) + states['label'] = label + for _ in _run_ssa_block_pass(states, blk, handler): + pass + + +def _run_block_rewrite(blocks, states, handler): + newblocks = {} + for label, blk in blocks.items(): + _logger.debug("==== SSA block rewrite pass on %s", label) + newblk = ir.Block(scope=blk.scope, loc=blk.loc) + + newbody = [] + states['label'] = label + states['block'] = blk + for stmt in _run_ssa_block_pass(states, blk, handler): + assert stmt is not None + newbody.append(stmt) + newblk.body = newbody + newblocks[label] = newblk + return newblocks + + +def _make_states(blocks): + return dict( + scope=_get_scope(blocks), + ) + + +def _run_ssa_block_pass(states, blk, handler): + _logger.debug("Running %s", handler) + for stmt in blk.body: + _logger.debug("on stmt: %s", stmt) + if isinstance(stmt, ir.Assign): + ret = handler.on_assign(states, stmt) + else: + ret = handler.on_other(states, stmt) + if ret is not stmt and ret is not None: + _logger.debug("replaced with: %s", ret) + yield ret + + +class _BaseHandler: + """A base handler for all the passes used here for the SSA algorithm. + """ + def on_assign(self, states, assign): + """ + Called when the pass sees an ``ir.Assign``. + + Subclasses should override this for custom behavior + + Parameters + ----------- + states : dict + assign : numba.ir.Assign + + Returns + ------- + stmt : numba.ir.Assign or None + For rewrite passes, the return value is used as the replacement + for the given statement. + """ + + def on_other(self, states, stmt): + """ + Called when the pass sees an ``ir.Stmt`` that's not an assignment. + + Subclasses should override this for custom behavior + + Parameters + ----------- + states : dict + assign : numba.ir.Stmt + + Returns + ------- + stmt : numba.ir.Stmt or None + For rewrite passes, the return value is used as the replacement + for the given statement. + """ + + +class _GatherDefsHandler(_BaseHandler): + """Find all defs and uses of variable in each block + + ``states["label"]`` is a int; label of the current block + ``states["defs"]`` is a Mapping[str, List[Tuple[ir.Assign, int]]]: + - a mapping of the name of the assignee variable to the assignment + IR node and the block label. + ``states["uses"]`` is a Mapping[Set[int]] + """ + def on_assign(self, states, assign): + # keep track of assignment and the block + states["defs"][assign.target.name].append((assign, states["label"])) + # keep track of uses + for var in assign.list_vars(): + k = var.name + if k != assign.target.name: + states["uses"][k].add(states["label"]) + + def on_other(self, states, stmt): + # keep track of uses + for var in stmt.list_vars(): + k = var.name + states["uses"][k].add(states["label"]) + + +class UndefinedVariable: + def __init__(self): + raise NotImplementedError("Not intended for instantiation") + + target = ir.UNDEFINED + + +class _FreshVarHandler(_BaseHandler): + """Replaces assignment target with new fresh variables. + """ + def on_assign(self, states, assign): + if assign.target.name == states['varname']: + scope = states['scope'] + defmap = states['defmap'] + # Allow first assignment to retain the name + if len(defmap) == 0: + newtarget = assign.target + _logger.debug("first assign: %s", newtarget) + if newtarget.name not in scope.localvars: + wmsg = f"variable {newtarget.name!r} is not in scope." + warnings.warn(errors.NumbaIRAssumptionWarning(wmsg, + loc=assign.loc)) + else: + newtarget = scope.redefine(assign.target.name, loc=assign.loc) + assign = ir.Assign( + target=newtarget, + value=assign.value, + loc=assign.loc + ) + defmap[states['label']].append(assign) + return assign + + def on_other(self, states, stmt): + return stmt + + +class _FixSSAVars(_BaseHandler): + """Replace variable uses in IR nodes to the correct reaching variable + and introduce Phi nodes if necessary. This class contains the core of + the SSA reconstruction algorithm. + + See Ch 5 of the Inria SSA book for reference. The method names used here + are similar to the names used in the pseudocode in the book. + """ + + def __init__(self, cache_list_vars): + self._cache_list_vars = cache_list_vars + + def on_assign(self, states, assign): + rhs = assign.value + if isinstance(rhs, ir.Inst): + newdef = self._fix_var( + states, assign, self._cache_list_vars.get(assign.value), + ) + # Has a replacement that is not the current variable + if newdef is not None and newdef.target is not ir.UNDEFINED: + if states['varname'] != newdef.target.name: + replmap = {states['varname']: newdef.target} + rhs = copy(rhs) + + ir_utils.replace_vars_inner(rhs, replmap) + return ir.Assign( + target=assign.target, + value=rhs, + loc=assign.loc, + ) + elif isinstance(rhs, ir.Var): + newdef = self._fix_var(states, assign, [rhs]) + # Has a replacement that is not the current variable + if newdef is not None and newdef.target is not ir.UNDEFINED: + if states['varname'] != newdef.target.name: + return ir.Assign( + target=assign.target, + value=newdef.target, + loc=assign.loc, + ) + + return assign + + def on_other(self, states, stmt): + newdef = self._fix_var( + states, stmt, self._cache_list_vars.get(stmt), + ) + if newdef is not None and newdef.target is not ir.UNDEFINED: + if states['varname'] != newdef.target.name: + replmap = {states['varname']: newdef.target} + stmt = copy(stmt) + ir_utils.replace_vars_stmt(stmt, replmap) + return stmt + + def _fix_var(self, states, stmt, used_vars): + """Fix all variable uses in ``used_vars``. + """ + varnames = [k.name for k in used_vars] + phivar = states['varname'] + if phivar in varnames: + return self._find_def(states, stmt) + + def _find_def(self, states, stmt): + """Find definition of ``stmt`` for the statement ``stmt`` + """ + _logger.debug("find_def var=%r stmt=%s", states['varname'], stmt) + selected_def = None + label = states['label'] + local_defs = states['defmap'][label] + local_phis = states['phimap'][label] + block = states['block'] + + cur_pos = self._stmt_index(stmt, block) + for defstmt in reversed(local_defs): + # Phi nodes have no index + def_pos = self._stmt_index(defstmt, block, stop=cur_pos) + if def_pos < cur_pos: + selected_def = defstmt + break + # Maybe it's a PHI + elif defstmt in local_phis: + selected_def = local_phis[-1] + break + + if selected_def is None: + selected_def = self._find_def_from_top( + states, label, loc=stmt.loc, + ) + return selected_def + + def _find_def_from_top(self, states, label, loc): + """Find definition reaching block of ``label``. + + This method would look at all dominance frontiers. + Insert phi node if necessary. + """ + _logger.debug("find_def_from_top label %r", label) + cfg = states['cfg'] + defmap = states['defmap'] + phimap = states['phimap'] + phi_locations = states['phi_locations'] + + if label in phi_locations: + scope = states['scope'] + loc = states['block'].loc + # fresh variable + freshvar = scope.redefine(states['varname'], loc=loc) + # insert phi + phinode = ir.Assign( + target=freshvar, + value=ir.Expr.phi(loc=loc), + loc=loc, + ) + _logger.debug("insert phi node %s at %s", phinode, label) + defmap[label].insert(0, phinode) + phimap[label].append(phinode) + # Find incoming values for the Phi node + for pred, _ in cfg.predecessors(label): + incoming_def = self._find_def_from_bottom( + states, pred, loc=loc, + ) + _logger.debug("incoming_def %s", incoming_def) + phinode.value.incoming_values.append(incoming_def.target) + phinode.value.incoming_blocks.append(pred) + return phinode + else: + idom = cfg.immediate_dominators()[label] + if idom == label: + # We have searched to the top of the idom tree. + # Since we still cannot find a definition, + # we will warn. + _warn_about_uninitialized_variable(states['varname'], loc) + return UndefinedVariable + _logger.debug("idom %s from label %s", idom, label) + return self._find_def_from_bottom(states, idom, loc=loc) + + def _find_def_from_bottom(self, states, label, loc): + """Find definition from within the block at ``label``. + """ + _logger.debug("find_def_from_bottom label %r", label) + defmap = states['defmap'] + defs = defmap[label] + if defs: + lastdef = defs[-1] + return lastdef + else: + return self._find_def_from_top(states, label, loc=loc) + + def _stmt_index(self, defstmt, block, stop=-1): + """Find the positional index of the statement at ``block``. + + Assumptions: + - no two statements can point to the same object. + """ + # Compare using id() as IR node equality is for semantic equivalence + # opposed to direct equality (the location and scope are not considered + # as part of the equality measure, this is important here). + for i in range(len(block.body))[:stop]: + if block.body[i] is defstmt: + return i + return len(block.body) + + +def _warn_about_uninitialized_variable(varname, loc): + if config.ALWAYS_WARN_UNINIT_VAR: + warnings.warn( + errors.NumbaWarning( + f"Detected uninitialized variable {varname}", + loc=loc), + ) diff --git a/shared/package-files/d2/d20c3c88c72d023732f99d87a5bf1ea3be489aae776761ac9953993ebf8cc4cc/blob b/shared/package-files/d2/d20c3c88c72d023732f99d87a5bf1ea3be489aae776761ac9953993ebf8cc4cc/blob new file mode 100644 index 0000000000000000000000000000000000000000..bea94cd586dc15fe6cc7ebe5a487de6dbb68c003 --- /dev/null +++ b/shared/package-files/d2/d20c3c88c72d023732f99d87a5bf1ea3be489aae776761ac9953993ebf8cc4cc/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor ne(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & ne_(at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor ne(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & ne_(at::Tensor & self, const at::Tensor & other); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/d2/d20cdbe36cbf99bc387ec62cdeef1cc0f14b051946fa490740b81bbc6b6b6345/blob b/shared/package-files/d2/d20cdbe36cbf99bc387ec62cdeef1cc0f14b051946fa490740b81bbc6b6b6345/blob new file mode 100644 index 0000000000000000000000000000000000000000..e6523824eb9634c18b87e4e3e5c827d8be43f8a8 --- /dev/null +++ b/shared/package-files/d2/d20cdbe36cbf99bc387ec62cdeef1cc0f14b051946fa490740b81bbc6b6b6345/blob @@ -0,0 +1,85 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/extension_type.h" +#include "arrow/python/common.h" +#include "arrow/python/visibility.h" +#include "arrow/util/macros.h" + +namespace arrow { +namespace py { + +class ARROW_PYTHON_EXPORT PyExtensionType : public ExtensionType { + public: + // Implement extensionType API + std::string extension_name() const override { return extension_name_; } + + std::string ToString(bool show_metadata = false) const override; + + bool ExtensionEquals(const ExtensionType& other) const override; + + std::shared_ptr MakeArray(std::shared_ptr data) const override; + + Result> Deserialize( + std::shared_ptr storage_type, + const std::string& serialized) const override; + + std::string Serialize() const override; + + // For use from Cython + // Assumes that `typ` is borrowed + static Status FromClass(const std::shared_ptr storage_type, + const std::string extension_name, PyObject* typ, + std::shared_ptr* out); + + // Return new ref + PyObject* GetInstance() const; + Status SetInstance(PyObject*) const; + + protected: + PyExtensionType(std::shared_ptr storage_type, PyObject* typ, + PyObject* inst = NULLPTR); + PyExtensionType(std::shared_ptr storage_type, std::string extension_name, + PyObject* typ, PyObject* inst = NULLPTR); + + std::string extension_name_; + + // These fields are mutable because of two-step initialization. + mutable OwnedRefNoGIL type_class_; + // A weakref or null. Storing a strong reference to the Python extension type + // instance would create an unreclaimable reference cycle between Python and C++ + // (the Python instance has to keep a strong reference to the C++ ExtensionType + // in other direction). Instead, we store a weakref to the instance. + // If the weakref is dead, we reconstruct the instance from its serialized form. + mutable OwnedRefNoGIL type_instance_; + // Empty if type_instance_ is null + mutable std::string serialized_; +}; + +ARROW_PYTHON_EXPORT std::string PyExtensionName(); + +ARROW_PYTHON_EXPORT Status RegisterPyExtensionType(const std::shared_ptr&); + +ARROW_PYTHON_EXPORT Status UnregisterPyExtensionType(const std::string& type_name); + +} // namespace py +} // namespace arrow diff --git a/shared/package-files/d2/d20e6edcec9b520a9b41468adf65e9576398d6f32bfed332beffb159e3f29fad/blob b/shared/package-files/d2/d20e6edcec9b520a9b41468adf65e9576398d6f32bfed332beffb159e3f29fad/blob new file mode 100644 index 0000000000000000000000000000000000000000..ee2d89347a9f27ef66156aac081b499a66f6cdb2 --- /dev/null +++ b/shared/package-files/d2/d20e6edcec9b520a9b41468adf65e9576398d6f32bfed332beffb159e3f29fad/blob @@ -0,0 +1 @@ +def getpreferredencoding(do_setlocale: bool = ...) -> str: ... diff --git a/shared/package-files/d2/d2100a380ada2180cb939966c7da37ae89e5d92424e4b9ee01a3eb902e2a1182/blob b/shared/package-files/d2/d2100a380ada2180cb939966c7da37ae89e5d92424e4b9ee01a3eb902e2a1182/blob new file mode 100644 index 0000000000000000000000000000000000000000..b6f4680bff73ed43aa593eb6f430ca6da6cd884a --- /dev/null +++ b/shared/package-files/d2/d2100a380ada2180cb939966c7da37ae89e5d92424e4b9ee01a3eb902e2a1182/blob @@ -0,0 +1,916 @@ +import numpy as np +import pytest + +from pandas.compat import WARNING_CHECK_DISABLED +import pandas.util._test_decorators as td + +from pandas import ( + Categorical, + DataFrame, + DatetimeIndex, + NaT, + PeriodIndex, + Series, + TimedeltaIndex, + Timestamp, + date_range, + to_datetime, +) +import pandas._testing as tm +from pandas.tests.frame.common import _check_mixed_float + + +class TestFillNA: + def test_fillna_dict_inplace_nonunique_columns( + self, using_copy_on_write, warn_copy_on_write + ): + df = DataFrame( + {"A": [np.nan] * 3, "B": [NaT, Timestamp(1), NaT], "C": [np.nan, "foo", 2]} + ) + df.columns = ["A", "A", "A"] + orig = df[:] + + # TODO(CoW-warn) better warning message + with tm.assert_cow_warning(warn_copy_on_write): + df.fillna({"A": 2}, inplace=True) + # The first and third columns can be set inplace, while the second cannot. + + expected = DataFrame( + {"A": [2.0] * 3, "B": [2, Timestamp(1), 2], "C": [2, "foo", 2]} + ) + expected.columns = ["A", "A", "A"] + tm.assert_frame_equal(df, expected) + + # TODO: what's the expected/desired behavior with CoW? + if not using_copy_on_write: + assert tm.shares_memory(df.iloc[:, 0], orig.iloc[:, 0]) + assert not tm.shares_memory(df.iloc[:, 1], orig.iloc[:, 1]) + if not using_copy_on_write: + assert tm.shares_memory(df.iloc[:, 2], orig.iloc[:, 2]) + + @td.skip_array_manager_not_yet_implemented + def test_fillna_on_column_view(self, using_copy_on_write): + # GH#46149 avoid unnecessary copies + arr = np.full((40, 50), np.nan) + df = DataFrame(arr, copy=False) + + if using_copy_on_write: + with tm.raises_chained_assignment_error(): + df[0].fillna(-1, inplace=True) + assert np.isnan(arr[:, 0]).all() + else: + with tm.assert_produces_warning( + FutureWarning if not WARNING_CHECK_DISABLED else None, + match="inplace method", + ): + df[0].fillna(-1, inplace=True) + assert (arr[:, 0] == -1).all() + + # i.e. we didn't create a new 49-column block + assert len(df._mgr.arrays) == 1 + assert np.shares_memory(df.values, arr) + + def test_fillna_datetime(self, datetime_frame): + tf = datetime_frame + tf.loc[tf.index[:5], "A"] = np.nan + tf.loc[tf.index[-5:], "A"] = np.nan + + zero_filled = datetime_frame.fillna(0) + assert (zero_filled.loc[zero_filled.index[:5], "A"] == 0).all() + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + padded = datetime_frame.fillna(method="pad") + assert np.isnan(padded.loc[padded.index[:5], "A"]).all() + assert ( + padded.loc[padded.index[-5:], "A"] == padded.loc[padded.index[-5], "A"] + ).all() + + msg = "Must specify a fill 'value' or 'method'" + with pytest.raises(ValueError, match=msg): + datetime_frame.fillna() + msg = "Cannot specify both 'value' and 'method'" + with pytest.raises(ValueError, match=msg): + datetime_frame.fillna(5, method="ffill") + + def test_fillna_mixed_type(self, float_string_frame): + mf = float_string_frame + mf.loc[mf.index[5:20], "foo"] = np.nan + mf.loc[mf.index[-10:], "A"] = np.nan + # TODO: make stronger assertion here, GH 25640 + mf.fillna(value=0) + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + mf.fillna(method="pad") + + def test_fillna_mixed_float(self, mixed_float_frame): + # mixed numeric (but no float16) + mf = mixed_float_frame.reindex(columns=["A", "B", "D"]) + mf.loc[mf.index[-10:], "A"] = np.nan + result = mf.fillna(value=0) + _check_mixed_float(result, dtype={"C": None}) + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = mf.fillna(method="pad") + _check_mixed_float(result, dtype={"C": None}) + + def test_fillna_empty(self, using_copy_on_write): + if using_copy_on_write: + pytest.skip("condition is unnecessary complex and is deprecated anyway") + # empty frame (GH#2778) + df = DataFrame(columns=["x"]) + for m in ["pad", "backfill"]: + msg = "Series.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.x.fillna(method=m, inplace=True) + df.x.fillna(method=m) + + def test_fillna_different_dtype(self): + # with different dtype (GH#3386) + df = DataFrame( + [["a", "a", np.nan, "a"], ["b", "b", np.nan, "b"], ["c", "c", np.nan, "c"]] + ) + + result = df.fillna({2: "foo"}) + expected = DataFrame( + [["a", "a", "foo", "a"], ["b", "b", "foo", "b"], ["c", "c", "foo", "c"]] + ) + # column is originally float (all-NaN) -> filling with string gives object dtype + expected[2] = expected[2].astype("object") + tm.assert_frame_equal(result, expected) + + return_value = df.fillna({2: "foo"}, inplace=True) + tm.assert_frame_equal(df, expected) + assert return_value is None + + def test_fillna_limit_and_value(self): + # limit and value + df = DataFrame(np.random.default_rng(2).standard_normal((10, 3))) + df.iloc[2:7, 0] = np.nan + df.iloc[3:5, 2] = np.nan + + expected = df.copy() + expected.iloc[2, 0] = 999 + expected.iloc[3, 2] = 999 + result = df.fillna(999, limit=1) + tm.assert_frame_equal(result, expected) + + def test_fillna_datelike(self): + # with datelike + # GH#6344 + df = DataFrame( + { + "Date": [NaT, Timestamp("2014-1-1")], + "Date2": [Timestamp("2013-1-1"), NaT], + } + ) + + expected = df.copy() + expected["Date"] = expected["Date"].fillna(df.loc[df.index[0], "Date2"]) + result = df.fillna(value={"Date": df["Date2"]}) + tm.assert_frame_equal(result, expected) + + def test_fillna_tzaware(self): + # with timezone + # GH#15855 + df = DataFrame({"A": [Timestamp("2012-11-11 00:00:00+01:00"), NaT]}) + exp = DataFrame( + { + "A": [ + Timestamp("2012-11-11 00:00:00+01:00"), + Timestamp("2012-11-11 00:00:00+01:00"), + ] + } + ) + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = df.fillna(method="pad") + tm.assert_frame_equal(res, exp) + + df = DataFrame({"A": [NaT, Timestamp("2012-11-11 00:00:00+01:00")]}) + exp = DataFrame( + { + "A": [ + Timestamp("2012-11-11 00:00:00+01:00"), + Timestamp("2012-11-11 00:00:00+01:00"), + ] + } + ) + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = df.fillna(method="bfill") + tm.assert_frame_equal(res, exp) + + def test_fillna_tzaware_different_column(self): + # with timezone in another column + # GH#15522 + df = DataFrame( + { + "A": date_range("20130101", periods=4, tz="US/Eastern"), + "B": [1, 2, np.nan, np.nan], + } + ) + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna(method="pad") + expected = DataFrame( + { + "A": date_range("20130101", periods=4, tz="US/Eastern"), + "B": [1.0, 2.0, 2.0, 2.0], + } + ) + tm.assert_frame_equal(result, expected) + + def test_na_actions_categorical(self): + cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3]) + vals = ["a", "b", np.nan, "d"] + df = DataFrame({"cats": cat, "vals": vals}) + cat2 = Categorical([1, 2, 3, 3], categories=[1, 2, 3]) + vals2 = ["a", "b", "b", "d"] + df_exp_fill = DataFrame({"cats": cat2, "vals": vals2}) + cat3 = Categorical([1, 2, 3], categories=[1, 2, 3]) + vals3 = ["a", "b", np.nan] + df_exp_drop_cats = DataFrame({"cats": cat3, "vals": vals3}) + cat4 = Categorical([1, 2], categories=[1, 2, 3]) + vals4 = ["a", "b"] + df_exp_drop_all = DataFrame({"cats": cat4, "vals": vals4}) + + # fillna + res = df.fillna(value={"cats": 3, "vals": "b"}) + tm.assert_frame_equal(res, df_exp_fill) + + msg = "Cannot setitem on a Categorical with a new category" + with pytest.raises(TypeError, match=msg): + df.fillna(value={"cats": 4, "vals": "c"}) + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = df.fillna(method="pad") + tm.assert_frame_equal(res, df_exp_fill) + + # dropna + res = df.dropna(subset=["cats"]) + tm.assert_frame_equal(res, df_exp_drop_cats) + + res = df.dropna() + tm.assert_frame_equal(res, df_exp_drop_all) + + # make sure that fillna takes missing values into account + c = Categorical([np.nan, "b", np.nan], categories=["a", "b"]) + df = DataFrame({"cats": c, "vals": [1, 2, 3]}) + + cat_exp = Categorical(["a", "b", "a"], categories=["a", "b"]) + df_exp = DataFrame({"cats": cat_exp, "vals": [1, 2, 3]}) + + res = df.fillna("a") + tm.assert_frame_equal(res, df_exp) + + def test_fillna_categorical_nan(self): + # GH#14021 + # np.nan should always be a valid filler + cat = Categorical([np.nan, 2, np.nan]) + val = Categorical([np.nan, np.nan, np.nan]) + df = DataFrame({"cats": cat, "vals": val}) + + # GH#32950 df.median() is poorly behaved because there is no + # Categorical.median + median = Series({"cats": 2.0, "vals": np.nan}) + + res = df.fillna(median) + v_exp = [np.nan, np.nan, np.nan] + df_exp = DataFrame({"cats": [2, 2, 2], "vals": v_exp}, dtype="category") + tm.assert_frame_equal(res, df_exp) + + result = df.cats.fillna(np.nan) + tm.assert_series_equal(result, df.cats) + + result = df.vals.fillna(np.nan) + tm.assert_series_equal(result, df.vals) + + idx = DatetimeIndex( + ["2011-01-01 09:00", "2016-01-01 23:45", "2011-01-01 09:00", NaT, NaT] + ) + df = DataFrame({"a": Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=NaT), df) + + idx = PeriodIndex(["2011-01", "2011-01", "2011-01", NaT, NaT], freq="M") + df = DataFrame({"a": Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=NaT), df) + + idx = TimedeltaIndex(["1 days", "2 days", "1 days", NaT, NaT]) + df = DataFrame({"a": Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=NaT), df) + + def test_fillna_downcast(self): + # GH#15277 + # infer int64 from float64 + df = DataFrame({"a": [1.0, np.nan]}) + msg = "The 'downcast' keyword in fillna is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna(0, downcast="infer") + expected = DataFrame({"a": [1, 0]}) + tm.assert_frame_equal(result, expected) + + # infer int64 from float64 when fillna value is a dict + df = DataFrame({"a": [1.0, np.nan]}) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna({"a": 0}, downcast="infer") + expected = DataFrame({"a": [1, 0]}) + tm.assert_frame_equal(result, expected) + + def test_fillna_downcast_false(self, frame_or_series): + # GH#45603 preserve object dtype with downcast=False + obj = frame_or_series([1, 2, 3], dtype="object") + msg = "The 'downcast' keyword in fillna" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = obj.fillna("", downcast=False) + tm.assert_equal(result, obj) + + def test_fillna_downcast_noop(self, frame_or_series): + # GH#45423 + # Two relevant paths: + # 1) not _can_hold_na (e.g. integer) + # 2) _can_hold_na + noop + not can_hold_element + + obj = frame_or_series([1, 2, 3], dtype=np.int64) + + msg = "The 'downcast' keyword in fillna" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#40988 + res = obj.fillna("foo", downcast=np.dtype(np.int32)) + expected = obj.astype(np.int32) + tm.assert_equal(res, expected) + + obj2 = obj.astype(np.float64) + with tm.assert_produces_warning(FutureWarning, match=msg): + res2 = obj2.fillna("foo", downcast="infer") + expected2 = obj # get back int64 + tm.assert_equal(res2, expected2) + + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#40988 + res3 = obj2.fillna("foo", downcast=np.dtype(np.int32)) + tm.assert_equal(res3, expected) + + @pytest.mark.parametrize("columns", [["A", "A", "B"], ["A", "A"]]) + def test_fillna_dictlike_value_duplicate_colnames(self, columns): + # GH#43476 + df = DataFrame(np.nan, index=[0, 1], columns=columns) + with tm.assert_produces_warning(None): + result = df.fillna({"A": 0}) + + expected = df.copy() + expected["A"] = 0.0 + tm.assert_frame_equal(result, expected) + + def test_fillna_dtype_conversion(self, using_infer_string): + # make sure that fillna on an empty frame works + df = DataFrame(index=["A", "B", "C"], columns=[1, 2, 3, 4, 5]) + result = df.dtypes + expected = Series([np.dtype("object")] * 5, index=[1, 2, 3, 4, 5]) + tm.assert_series_equal(result, expected) + + msg = "Downcasting object dtype arrays" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna(1) + expected = DataFrame(1, index=["A", "B", "C"], columns=[1, 2, 3, 4, 5]) + tm.assert_frame_equal(result, expected) + + # empty block + df = DataFrame(index=range(3), columns=["A", "B"], dtype="float64") + result = df.fillna("nan") + expected = DataFrame("nan", index=range(3), columns=["A", "B"], dtype=object) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("val", ["", 1, np.nan, 1.0]) + def test_fillna_dtype_conversion_equiv_replace(self, val): + df = DataFrame({"A": [1, np.nan], "B": [1.0, 2.0]}) + expected = df.replace(np.nan, val) + result = df.fillna(val) + tm.assert_frame_equal(result, expected) + + def test_fillna_datetime_columns(self): + # GH#7095 + df = DataFrame( + { + "A": [-1, -2, np.nan], + "B": date_range("20130101", periods=3), + "C": ["foo", "bar", None], + "D": ["foo2", "bar2", None], + }, + index=date_range("20130110", periods=3), + ) + result = df.fillna("?") + expected = DataFrame( + { + "A": [-1, -2, "?"], + "B": date_range("20130101", periods=3), + "C": ["foo", "bar", "?"], + "D": ["foo2", "bar2", "?"], + }, + index=date_range("20130110", periods=3), + ) + tm.assert_frame_equal(result, expected) + + df = DataFrame( + { + "A": [-1, -2, np.nan], + "B": [Timestamp("2013-01-01"), Timestamp("2013-01-02"), NaT], + "C": ["foo", "bar", None], + "D": ["foo2", "bar2", None], + }, + index=date_range("20130110", periods=3), + ) + result = df.fillna("?") + expected = DataFrame( + { + "A": [-1, -2, "?"], + "B": [Timestamp("2013-01-01"), Timestamp("2013-01-02"), "?"], + "C": ["foo", "bar", "?"], + "D": ["foo2", "bar2", "?"], + }, + index=date_range("20130110", periods=3), + ) + tm.assert_frame_equal(result, expected) + + def test_ffill(self, datetime_frame): + datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan + datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + alt = datetime_frame.fillna(method="ffill") + tm.assert_frame_equal(datetime_frame.ffill(), alt) + + def test_bfill(self, datetime_frame): + datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan + datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + alt = datetime_frame.fillna(method="bfill") + + tm.assert_frame_equal(datetime_frame.bfill(), alt) + + def test_frame_pad_backfill_limit(self): + index = np.arange(10) + df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)), index=index) + + result = df[:2].reindex(index, method="pad", limit=5) + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df[:2].reindex(index).fillna(method="pad") + expected.iloc[-3:] = np.nan + tm.assert_frame_equal(result, expected) + + result = df[-2:].reindex(index, method="backfill", limit=5) + + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df[-2:].reindex(index).fillna(method="backfill") + expected.iloc[:3] = np.nan + tm.assert_frame_equal(result, expected) + + def test_frame_fillna_limit(self): + index = np.arange(10) + df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)), index=index) + + result = df[:2].reindex(index) + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = result.fillna(method="pad", limit=5) + + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df[:2].reindex(index).fillna(method="pad") + expected.iloc[-3:] = np.nan + tm.assert_frame_equal(result, expected) + + result = df[-2:].reindex(index) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = result.fillna(method="backfill", limit=5) + + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df[-2:].reindex(index).fillna(method="backfill") + expected.iloc[:3] = np.nan + tm.assert_frame_equal(result, expected) + + def test_fillna_skip_certain_blocks(self): + # don't try to fill boolean, int blocks + + df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)).astype(int)) + + # it works! + df.fillna(np.nan) + + @pytest.mark.parametrize("type", [int, float]) + def test_fillna_positive_limit(self, type): + df = DataFrame(np.random.default_rng(2).standard_normal((10, 4))).astype(type) + + msg = "Limit must be greater than 0" + with pytest.raises(ValueError, match=msg): + df.fillna(0, limit=-5) + + @pytest.mark.parametrize("type", [int, float]) + def test_fillna_integer_limit(self, type): + df = DataFrame(np.random.default_rng(2).standard_normal((10, 4))).astype(type) + + msg = "Limit must be an integer" + with pytest.raises(ValueError, match=msg): + df.fillna(0, limit=0.5) + + def test_fillna_inplace(self): + df = DataFrame(np.random.default_rng(2).standard_normal((10, 4))) + df.loc[:4, 1] = np.nan + df.loc[-4:, 3] = np.nan + + expected = df.fillna(value=0) + assert expected is not df + + df.fillna(value=0, inplace=True) + tm.assert_frame_equal(df, expected) + + expected = df.fillna(value={0: 0}, inplace=True) + assert expected is None + + df.loc[:4, 1] = np.nan + df.loc[-4:, 3] = np.nan + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.fillna(method="ffill") + assert expected is not df + + with tm.assert_produces_warning(FutureWarning, match=msg): + df.fillna(method="ffill", inplace=True) + tm.assert_frame_equal(df, expected) + + def test_fillna_dict_series(self): + df = DataFrame( + { + "a": [np.nan, 1, 2, np.nan, np.nan], + "b": [1, 2, 3, np.nan, np.nan], + "c": [np.nan, 1, 2, 3, 4], + } + ) + + result = df.fillna({"a": 0, "b": 5}) + + expected = df.copy() + expected["a"] = expected["a"].fillna(0) + expected["b"] = expected["b"].fillna(5) + tm.assert_frame_equal(result, expected) + + # it works + result = df.fillna({"a": 0, "b": 5, "d": 7}) + + # Series treated same as dict + result = df.fillna(df.max()) + expected = df.fillna(df.max().to_dict()) + tm.assert_frame_equal(result, expected) + + # disable this for now + with pytest.raises(NotImplementedError, match="column by column"): + df.fillna(df.max(1), axis=1) + + def test_fillna_dataframe(self): + # GH#8377 + df = DataFrame( + { + "a": [np.nan, 1, 2, np.nan, np.nan], + "b": [1, 2, 3, np.nan, np.nan], + "c": [np.nan, 1, 2, 3, 4], + }, + index=list("VWXYZ"), + ) + + # df2 may have different index and columns + df2 = DataFrame( + { + "a": [np.nan, 10, 20, 30, 40], + "b": [50, 60, 70, 80, 90], + "foo": ["bar"] * 5, + }, + index=list("VWXuZ"), + ) + + result = df.fillna(df2) + + # only those columns and indices which are shared get filled + expected = DataFrame( + { + "a": [np.nan, 1, 2, np.nan, 40], + "b": [1, 2, 3, np.nan, 90], + "c": [np.nan, 1, 2, 3, 4], + }, + index=list("VWXYZ"), + ) + + tm.assert_frame_equal(result, expected) + + def test_fillna_columns(self): + arr = np.random.default_rng(2).standard_normal((10, 10)) + arr[:, ::2] = np.nan + df = DataFrame(arr) + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna(method="ffill", axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.T.fillna(method="pad").T + tm.assert_frame_equal(result, expected) + + df.insert(6, "foo", 5) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna(method="ffill", axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.astype(float).fillna(method="ffill", axis=1) + tm.assert_frame_equal(result, expected) + + def test_fillna_invalid_method(self, float_frame): + with pytest.raises(ValueError, match="ffil"): + float_frame.fillna(method="ffil") + + def test_fillna_invalid_value(self, float_frame): + # list + msg = '"value" parameter must be a scalar or dict, but you passed a "{}"' + with pytest.raises(TypeError, match=msg.format("list")): + float_frame.fillna([1, 2]) + # tuple + with pytest.raises(TypeError, match=msg.format("tuple")): + float_frame.fillna((1, 2)) + # frame with series + msg = ( + '"value" parameter must be a scalar, dict or Series, but you ' + 'passed a "DataFrame"' + ) + with pytest.raises(TypeError, match=msg): + float_frame.iloc[:, 0].fillna(float_frame) + + def test_fillna_col_reordering(self): + cols = ["COL." + str(i) for i in range(5, 0, -1)] + data = np.random.default_rng(2).random((20, 5)) + df = DataFrame(index=range(20), columns=cols, data=data) + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + filled = df.fillna(method="ffill") + assert df.columns.tolist() == filled.columns.tolist() + + def test_fill_empty(self, float_frame): + df = float_frame.reindex(columns=[]) + result = df.fillna(value=0) + tm.assert_frame_equal(result, df) + + def test_fillna_downcast_dict(self): + # GH#40809 + df = DataFrame({"col1": [1, np.nan]}) + + msg = "The 'downcast' keyword in fillna" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna({"col1": 2}, downcast={"col1": "int64"}) + expected = DataFrame({"col1": [1, 2]}) + tm.assert_frame_equal(result, expected) + + def test_fillna_with_columns_and_limit(self): + # GH40989 + df = DataFrame( + [ + [np.nan, 2, np.nan, 0], + [3, 4, np.nan, 1], + [np.nan, np.nan, np.nan, 5], + [np.nan, 3, np.nan, 4], + ], + columns=list("ABCD"), + ) + result = df.fillna(axis=1, value=100, limit=1) + result2 = df.fillna(axis=1, value=100, limit=2) + + expected = DataFrame( + { + "A": Series([100, 3, 100, 100], dtype="float64"), + "B": [2, 4, np.nan, 3], + "C": [np.nan, 100, np.nan, np.nan], + "D": Series([0, 1, 5, 4], dtype="float64"), + }, + index=[0, 1, 2, 3], + ) + expected2 = DataFrame( + { + "A": Series([100, 3, 100, 100], dtype="float64"), + "B": Series([2, 4, 100, 3], dtype="float64"), + "C": [100, 100, np.nan, 100], + "D": Series([0, 1, 5, 4], dtype="float64"), + }, + index=[0, 1, 2, 3], + ) + + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected2) + + def test_fillna_datetime_inplace(self): + # GH#48863 + df = DataFrame( + { + "date1": to_datetime(["2018-05-30", None]), + "date2": to_datetime(["2018-09-30", None]), + } + ) + expected = df.copy() + df.fillna(np.nan, inplace=True) + tm.assert_frame_equal(df, expected) + + def test_fillna_inplace_with_columns_limit_and_value(self): + # GH40989 + df = DataFrame( + [ + [np.nan, 2, np.nan, 0], + [3, 4, np.nan, 1], + [np.nan, np.nan, np.nan, 5], + [np.nan, 3, np.nan, 4], + ], + columns=list("ABCD"), + ) + + expected = df.fillna(axis=1, value=100, limit=1) + assert expected is not df + + df.fillna(axis=1, value=100, limit=1, inplace=True) + tm.assert_frame_equal(df, expected) + + @td.skip_array_manager_invalid_test + @pytest.mark.parametrize("val", [-1, {"x": -1, "y": -1}]) + def test_inplace_dict_update_view( + self, val, using_copy_on_write, warn_copy_on_write + ): + # GH#47188 + df = DataFrame({"x": [np.nan, 2], "y": [np.nan, 2]}) + df_orig = df.copy() + result_view = df[:] + with tm.assert_cow_warning(warn_copy_on_write): + df.fillna(val, inplace=True) + expected = DataFrame({"x": [-1, 2.0], "y": [-1.0, 2]}) + tm.assert_frame_equal(df, expected) + if using_copy_on_write: + tm.assert_frame_equal(result_view, df_orig) + else: + tm.assert_frame_equal(result_view, expected) + + def test_single_block_df_with_horizontal_axis(self): + # GH 47713 + df = DataFrame( + { + "col1": [5, 0, np.nan, 10, np.nan], + "col2": [7, np.nan, np.nan, 5, 3], + "col3": [12, np.nan, 1, 2, 0], + "col4": [np.nan, 1, 1, np.nan, 18], + } + ) + result = df.fillna(50, limit=1, axis=1) + expected = DataFrame( + [ + [5.0, 7.0, 12.0, 50.0], + [0.0, 50.0, np.nan, 1.0], + [50.0, np.nan, 1.0, 1.0], + [10.0, 5.0, 2.0, 50.0], + [50.0, 3.0, 0.0, 18.0], + ], + columns=["col1", "col2", "col3", "col4"], + ) + tm.assert_frame_equal(result, expected) + + def test_fillna_with_multi_index_frame(self): + # GH 47649 + pdf = DataFrame( + { + ("x", "a"): [np.nan, 2.0, 3.0], + ("x", "b"): [1.0, 2.0, np.nan], + ("y", "c"): [1.0, 2.0, np.nan], + } + ) + expected = DataFrame( + { + ("x", "a"): [-1.0, 2.0, 3.0], + ("x", "b"): [1.0, 2.0, -1.0], + ("y", "c"): [1.0, 2.0, np.nan], + } + ) + tm.assert_frame_equal(pdf.fillna({"x": -1}), expected) + tm.assert_frame_equal(pdf.fillna({"x": -1, ("x", "b"): -2}), expected) + + expected = DataFrame( + { + ("x", "a"): [-1.0, 2.0, 3.0], + ("x", "b"): [1.0, 2.0, -2.0], + ("y", "c"): [1.0, 2.0, np.nan], + } + ) + tm.assert_frame_equal(pdf.fillna({("x", "b"): -2, "x": -1}), expected) + + +def test_fillna_nonconsolidated_frame(): + # https://github.com/pandas-dev/pandas/issues/36495 + df = DataFrame( + [ + [1, 1, 1, 1.0], + [2, 2, 2, 2.0], + [3, 3, 3, 3.0], + ], + columns=["i1", "i2", "i3", "f1"], + ) + df_nonconsol = df.pivot(index="i1", columns="i2") + result = df_nonconsol.fillna(0) + assert result.isna().sum().sum() == 0 + + +def test_fillna_nones_inplace(): + # GH 48480 + df = DataFrame( + [[None, None], [None, None]], + columns=["A", "B"], + ) + msg = "Downcasting object dtype arrays" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.fillna(value={"A": 1, "B": 2}, inplace=True) + + expected = DataFrame([[1, 2], [1, 2]], columns=["A", "B"]) + tm.assert_frame_equal(df, expected) + + +@pytest.mark.parametrize("func", ["pad", "backfill"]) +def test_pad_backfill_deprecated(func): + # GH#33396 + df = DataFrame({"a": [1, 2, 3]}) + with tm.assert_produces_warning(FutureWarning): + getattr(df, func)() + + +@pytest.mark.parametrize( + "data, expected_data, method, kwargs", + ( + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, 3.0, 3.0, 3.0, 7.0, np.nan, np.nan], + "ffill", + {"limit_area": "inside"}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, 3.0, np.nan, np.nan, 7.0, np.nan, np.nan], + "ffill", + {"limit_area": "inside", "limit": 1}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, 7.0], + "ffill", + {"limit_area": "outside"}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan], + "ffill", + {"limit_area": "outside", "limit": 1}, + ), + ( + [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], + [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], + "ffill", + {"limit_area": "outside", "limit": 1}, + ), + ( + range(5), + range(5), + "ffill", + {"limit_area": "outside", "limit": 1}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, 7.0, 7.0, 7.0, 7.0, np.nan, np.nan], + "bfill", + {"limit_area": "inside"}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, np.nan, np.nan, 7.0, 7.0, np.nan, np.nan], + "bfill", + {"limit_area": "inside", "limit": 1}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [3.0, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan], + "bfill", + {"limit_area": "outside"}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan], + "bfill", + {"limit_area": "outside", "limit": 1}, + ), + ), +) +def test_ffill_bfill_limit_area(data, expected_data, method, kwargs): + # GH#56492 + df = DataFrame(data) + expected = DataFrame(expected_data) + result = getattr(df, method)(**kwargs) + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/d2/d2152a7c8b4dff1d83562851d0c1dd03828231508e3bc568072685a7f6ba3038/blob b/shared/package-files/d2/d2152a7c8b4dff1d83562851d0c1dd03828231508e3bc568072685a7f6ba3038/blob new file mode 100644 index 0000000000000000000000000000000000000000..b3fee35a6cce812ad856d3b84332e73fd1973420 --- /dev/null +++ b/shared/package-files/d2/d2152a7c8b4dff1d83562851d0c1dd03828231508e3bc568072685a7f6ba3038/blob @@ -0,0 +1,238 @@ +"""distutils.file_util + +Utility functions for operating on single files. +""" + +import os +from distutils.errors import DistutilsFileError +from distutils import log + +# for generating verbose output in 'copy_file()' +_copy_action = { None: 'copying', + 'hard': 'hard linking', + 'sym': 'symbolically linking' } + + +def _copy_file_contents(src, dst, buffer_size=16*1024): + """Copy the file 'src' to 'dst'; both must be filenames. Any error + opening either file, reading from 'src', or writing to 'dst', raises + DistutilsFileError. Data is read/written in chunks of 'buffer_size' + bytes (default 16k). No attempt is made to handle anything apart from + regular files. + """ + # Stolen from shutil module in the standard library, but with + # custom error-handling added. + fsrc = None + fdst = None + try: + try: + fsrc = open(src, 'rb') + except OSError as e: + raise DistutilsFileError("could not open '%s': %s" % (src, e.strerror)) + + if os.path.exists(dst): + try: + os.unlink(dst) + except OSError as e: + raise DistutilsFileError( + "could not delete '%s': %s" % (dst, e.strerror)) + + try: + fdst = open(dst, 'wb') + except OSError as e: + raise DistutilsFileError( + "could not create '%s': %s" % (dst, e.strerror)) + + while True: + try: + buf = fsrc.read(buffer_size) + except OSError as e: + raise DistutilsFileError( + "could not read from '%s': %s" % (src, e.strerror)) + + if not buf: + break + + try: + fdst.write(buf) + except OSError as e: + raise DistutilsFileError( + "could not write to '%s': %s" % (dst, e.strerror)) + finally: + if fdst: + fdst.close() + if fsrc: + fsrc.close() + +def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0, + link=None, verbose=1, dry_run=0): + """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is + copied there with the same name; otherwise, it must be a filename. (If + the file exists, it will be ruthlessly clobbered.) If 'preserve_mode' + is true (the default), the file's mode (type and permission bits, or + whatever is analogous on the current platform) is copied. If + 'preserve_times' is true (the default), the last-modified and + last-access times are copied as well. If 'update' is true, 'src' will + only be copied if 'dst' does not exist, or if 'dst' does exist but is + older than 'src'. + + 'link' allows you to make hard links (os.link) or symbolic links + (os.symlink) instead of copying: set it to "hard" or "sym"; if it is + None (the default), files are copied. Don't set 'link' on systems that + don't support it: 'copy_file()' doesn't check if hard or symbolic + linking is available. If hardlink fails, falls back to + _copy_file_contents(). + + Under Mac OS, uses the native file copy function in macostools; on + other systems, uses '_copy_file_contents()' to copy file contents. + + Return a tuple (dest_name, copied): 'dest_name' is the actual name of + the output file, and 'copied' is true if the file was copied (or would + have been copied, if 'dry_run' true). + """ + # XXX if the destination file already exists, we clobber it if + # copying, but blow up if linking. Hmmm. And I don't know what + # macostools.copyfile() does. Should definitely be consistent, and + # should probably blow up if destination exists and we would be + # changing it (ie. it's not already a hard/soft link to src OR + # (not update) and (src newer than dst). + + from distutils.dep_util import newer + from stat import ST_ATIME, ST_MTIME, ST_MODE, S_IMODE + + if not os.path.isfile(src): + raise DistutilsFileError( + "can't copy '%s': doesn't exist or not a regular file" % src) + + if os.path.isdir(dst): + dir = dst + dst = os.path.join(dst, os.path.basename(src)) + else: + dir = os.path.dirname(dst) + + if update and not newer(src, dst): + if verbose >= 1: + log.debug("not copying %s (output up-to-date)", src) + return (dst, 0) + + try: + action = _copy_action[link] + except KeyError: + raise ValueError("invalid value '%s' for 'link' argument" % link) + + if verbose >= 1: + if os.path.basename(dst) == os.path.basename(src): + log.info("%s %s -> %s", action, src, dir) + else: + log.info("%s %s -> %s", action, src, dst) + + if dry_run: + return (dst, 1) + + # If linking (hard or symbolic), use the appropriate system call + # (Unix only, of course, but that's the caller's responsibility) + elif link == 'hard': + if not (os.path.exists(dst) and os.path.samefile(src, dst)): + try: + os.link(src, dst) + return (dst, 1) + except OSError: + # If hard linking fails, fall back on copying file + # (some special filesystems don't support hard linking + # even under Unix, see issue #8876). + pass + elif link == 'sym': + if not (os.path.exists(dst) and os.path.samefile(src, dst)): + os.symlink(src, dst) + return (dst, 1) + + # Otherwise (non-Mac, not linking), copy the file contents and + # (optionally) copy the times and mode. + _copy_file_contents(src, dst) + if preserve_mode or preserve_times: + st = os.stat(src) + + # According to David Ascher , utime() should be done + # before chmod() (at least under NT). + if preserve_times: + os.utime(dst, (st[ST_ATIME], st[ST_MTIME])) + if preserve_mode: + os.chmod(dst, S_IMODE(st[ST_MODE])) + + return (dst, 1) + + +# XXX I suspect this is Unix-specific -- need porting help! +def move_file (src, dst, + verbose=1, + dry_run=0): + + """Move a file 'src' to 'dst'. If 'dst' is a directory, the file will + be moved into it with the same name; otherwise, 'src' is just renamed + to 'dst'. Return the new full name of the file. + + Handles cross-device moves on Unix using 'copy_file()'. What about + other systems??? + """ + from os.path import exists, isfile, isdir, basename, dirname + import errno + + if verbose >= 1: + log.info("moving %s -> %s", src, dst) + + if dry_run: + return dst + + if not isfile(src): + raise DistutilsFileError("can't move '%s': not a regular file" % src) + + if isdir(dst): + dst = os.path.join(dst, basename(src)) + elif exists(dst): + raise DistutilsFileError( + "can't move '%s': destination '%s' already exists" % + (src, dst)) + + if not isdir(dirname(dst)): + raise DistutilsFileError( + "can't move '%s': destination '%s' not a valid path" % + (src, dst)) + + copy_it = False + try: + os.rename(src, dst) + except OSError as e: + (num, msg) = e.args + if num == errno.EXDEV: + copy_it = True + else: + raise DistutilsFileError( + "couldn't move '%s' to '%s': %s" % (src, dst, msg)) + + if copy_it: + copy_file(src, dst, verbose=verbose) + try: + os.unlink(src) + except OSError as e: + (num, msg) = e.args + try: + os.unlink(dst) + except OSError: + pass + raise DistutilsFileError( + "couldn't move '%s' to '%s' by copy/delete: " + "delete '%s' failed: %s" + % (src, dst, src, msg)) + return dst + + +def write_file (filename, contents): + """Create a file with the specified name and write 'contents' (a + sequence of strings without line terminators) to it. + """ + f = open(filename, "w") + try: + for line in contents: + f.write(line + "\n") + finally: + f.close() diff --git a/shared/package-files/d2/d217998eebfb7dad3fe40552b2b993f8fe8024b0a2aa9bcc60799f969ea663e6/blob b/shared/package-files/d2/d217998eebfb7dad3fe40552b2b993f8fe8024b0a2aa9bcc60799f969ea663e6/blob new file mode 100644 index 0000000000000000000000000000000000000000..e8e0a0d8ae0d1925f6e874fd156fa5a5e941ab0c --- /dev/null +++ b/shared/package-files/d2/d217998eebfb7dad3fe40552b2b993f8fe8024b0a2aa9bcc60799f969ea663e6/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor special_chebyshev_polynomial_u(const at::Scalar & x, const at::Tensor & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_u_out(at::Tensor & out, const at::Scalar & x, const at::Tensor & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_u_outf(const at::Scalar & x, const at::Tensor & n, at::Tensor & out); +TORCH_API at::Tensor special_chebyshev_polynomial_u(const at::Tensor & x, const at::Scalar & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_u_out(at::Tensor & out, const at::Tensor & x, const at::Scalar & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_u_outf(const at::Tensor & x, const at::Scalar & n, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/d2/d21c5930f21063ea78fea3b0f76dfb8fd92858d2a4a200064a52126a43dd1a99/blob b/shared/package-files/d2/d21c5930f21063ea78fea3b0f76dfb8fd92858d2a4a200064a52126a43dd1a99/blob new file mode 100644 index 0000000000000000000000000000000000000000..161b1e86f9918a4df5c3290505a98d5de4566e0e --- /dev/null +++ b/shared/package-files/d2/d21c5930f21063ea78fea3b0f76dfb8fd92858d2a4a200064a52126a43dd1a99/blob @@ -0,0 +1,39 @@ +# +# shift_jis_2004.py: Python Unicode Codec for SHIFT_JIS_2004 +# +# Written by Hye-Shik Chang +# + +import _codecs_jp, codecs +import _multibytecodec as mbc + +codec = _codecs_jp.getcodec('shift_jis_2004') + +class Codec(codecs.Codec): + encode = codec.encode + decode = codec.decode + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, + codecs.IncrementalEncoder): + codec = codec + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, + codecs.IncrementalDecoder): + codec = codec + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): + codec = codec + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec = codec + +def getregentry(): + return codecs.CodecInfo( + name='shift_jis_2004', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) diff --git a/shared/package-files/d2/d21e3ff61332d8f77295e05e85216d948d6f2a65aa454ee69523522ccedabc1f/blob b/shared/package-files/d2/d21e3ff61332d8f77295e05e85216d948d6f2a65aa454ee69523522ccedabc1f/blob new file mode 100644 index 0000000000000000000000000000000000000000..0c6b1a3fba054dbf9a9c9317e8cdb29831b6b53a --- /dev/null +++ b/shared/package-files/d2/d21e3ff61332d8f77295e05e85216d948d6f2a65aa454ee69523522ccedabc1f/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API void _cudnn_rnn_backward_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::TensorList out3, const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & weight_buf, const at::Tensor & hx, const c10::optional & cx, const at::Tensor & output, const c10::optional & grad_output, const c10::optional & grad_hy, const c10::optional & grad_cy, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const c10::optional & dropout_state, const at::Tensor & reserve, ::std::array output_mask); +TORCH_API void _cudnn_rnn_backward_outf(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & weight_buf, const at::Tensor & hx, const c10::optional & cx, const at::Tensor & output, const c10::optional & grad_output, const c10::optional & grad_hy, const c10::optional & grad_cy, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const c10::optional & dropout_state, const at::Tensor & reserve, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::TensorList out3); +TORCH_API void _cudnn_rnn_backward_symint_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::TensorList out3, const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & weight_buf, const at::Tensor & hx, const c10::optional & cx, const at::Tensor & output, const c10::optional & grad_output, const c10::optional & grad_hy, const c10::optional & grad_cy, int64_t mode, c10::SymInt hidden_size, c10::SymInt proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, c10::SymIntArrayRef batch_sizes, const c10::optional & dropout_state, const at::Tensor & reserve, ::std::array output_mask); +TORCH_API void _cudnn_rnn_backward_symint_outf(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & weight_buf, const at::Tensor & hx, const c10::optional & cx, const at::Tensor & output, const c10::optional & grad_output, const c10::optional & grad_hy, const c10::optional & grad_cy, int64_t mode, c10::SymInt hidden_size, c10::SymInt proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, c10::SymIntArrayRef batch_sizes, const c10::optional & dropout_state, const at::Tensor & reserve, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::TensorList out3); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/d2/d220322978724566f6e0948a5646d959c8a1e147952b75af98925b7cc07174aa/blob b/shared/package-files/d2/d220322978724566f6e0948a5646d959c8a1e147952b75af98925b7cc07174aa/blob new file mode 100644 index 0000000000000000000000000000000000000000..2627ce8620d5036337ec2f8936cb5804cce462d2 --- /dev/null +++ b/shared/package-files/d2/d220322978724566f6e0948a5646d959c8a1e147952b75af98925b7cc07174aa/blob @@ -0,0 +1,155 @@ +#pragma once + +#include +#include + +namespace c10::xpu { + +#define AT_FORALL_XPU_DEVICE_PROPERTIES(_) \ + /* the device name of this SYCL device. */ \ + _(name) \ + \ + /* the device type associated with the device. */ \ + _(device_type) \ + \ + /* the vendor of this SYCL device. */ \ + _(vendor) \ + \ + /* a backend-defined driver version as a std::string. */ \ + _(driver_version) \ + \ + /* the SYCL version as a std::string in the form . */ \ + _(version) \ + \ + /* true if the SYCL device is available. Otherwise, return false. */ \ + _(is_available) \ + \ + /* the maximum size in bytes of the arguments that can be passed to a \ + * kernel. */ \ + _(max_parameter_size) \ + \ + /* the number of parallel compute units available to the device. */ \ + _(max_compute_units) \ + \ + /* the maximum dimensions that specify the global and local work-item IDs \ + * used by the data parallel execution model. */ \ + _(max_work_item_dimensions) \ + \ + /* the maximum number of workitems that are permitted in a work-group \ + * executing a kernel on a single compute unit. */ \ + _(max_work_group_size) \ + \ + /* the maximum number of subgroups in a work-group for any kernel executed \ + * on the device. */ \ + _(max_num_sub_groups) \ + \ + /* a std::vector of size_t containing the set of sub-group sizes supported \ + * by the device. */ \ + _(sub_group_sizes) \ + \ + /* the maximum configured clock frequency of this SYCL device in MHz. */ \ + _(max_clock_frequency) \ + \ + /* the default compute device address space size specified as an unsigned \ + * integer value in bits. Must return either 32 or 64. */ \ + _(address_bits) \ + \ + /* the maximum size of memory object allocation in bytes. */ \ + _(max_mem_alloc_size) \ + \ + /* the minimum value in bits of the largest supported SYCL built-in data \ + * type if this SYCL device is not of device type \ + * sycl::info::device_type::custom. */ \ + _(mem_base_addr_align) \ + \ + /* a std::vector of info::fp_config describing the half/single/double \ + * precision floating-point capability of this SYCL device. */ \ + _(half_fp_config) \ + _(single_fp_config) \ + _(double_fp_config) \ + \ + /* the size of global device memory in bytes. */ \ + _(global_mem_size) \ + \ + /* the type of global memory cache supported. */ \ + _(global_mem_cache_type) \ + \ + /* the size of global memory cache in bytes. */ \ + _(global_mem_cache_size) \ + \ + /* the size of global memory cache line in bytes. */ \ + _(global_mem_cache_line_size) \ + \ + /* the type of local memory supported. */ \ + _(local_mem_type) \ + \ + /* the size of local memory arena in bytes. */ \ + _(local_mem_size) \ + \ + /* the maximum number of sub-devices that can be created when this device is \ + * partitioned. */ \ + _(partition_max_sub_devices) \ + \ + /* the resolution of device timer in nanoseconds. */ \ + _(profiling_timer_resolution) \ + \ + /* the preferred native vector width size for built-in scalar types that can \ + * be put into vectors. */ \ + _(preferred_vector_width_char) \ + _(preferred_vector_width_short) \ + _(preferred_vector_width_int) \ + _(preferred_vector_width_long) \ + _(preferred_vector_width_float) \ + _(preferred_vector_width_double) \ + _(preferred_vector_width_half) \ + \ + /* the native ISA vector width. The vector width is defined as the number of \ + * scalar elements that can be stored in the vector. */ \ + _(native_vector_width_char) \ + _(native_vector_width_short) \ + _(native_vector_width_int) \ + _(native_vector_width_long) \ + _(native_vector_width_float) \ + _(native_vector_width_double) \ + _(native_vector_width_half) + +#define AT_FORALL_XPU_EXT_DEVICE_PROPERTIES(_) \ + /* the number of EUs associated with the Intel GPU. */ \ + _(gpu_eu_count, 512) \ + \ + /* the number of EUs in a subslice. */ \ + _(gpu_eu_count_per_subslice, 8) \ + \ + /* the simd width of EU of GPU. */ \ + _(gpu_eu_simd_width, 8) \ + \ + /* the number of hardware threads per EU of GPU. */ \ + _(gpu_hw_threads_per_eu, 8) + +#define _DEFINE_SYCL_PROP(ns, property, member) \ + ns::property::return_type member; + +#define DEFINE_DEVICE_PROP(property) \ + _DEFINE_SYCL_PROP(sycl::info::device, property, property) + +#define DEFINE_PLATFORM_PROP(property, member) \ + _DEFINE_SYCL_PROP(sycl::info::platform, property, member) + +#define DEFINE_EXT_DEVICE_PROP(property, ...) \ + _DEFINE_SYCL_PROP(sycl::ext::intel::info::device, property, property) + +struct C10_XPU_API DeviceProp { + AT_FORALL_XPU_DEVICE_PROPERTIES(DEFINE_DEVICE_PROP); + + // the platform name. + DEFINE_PLATFORM_PROP(name, platform_name); + + AT_FORALL_XPU_EXT_DEVICE_PROPERTIES(DEFINE_EXT_DEVICE_PROP) +}; + +#undef _DEFINE_SYCL_PROP +#undef DEFINE_DEVICE_PROP +#undef DEFINE_PLATFORM_PROP +#undef DEFINE_EXT_DEVICE_PROP + +} // namespace c10::xpu diff --git a/shared/package-files/d2/d2213592fece04261449a59561918f1371045268f8f041b11e46d09021e22214/blob b/shared/package-files/d2/d2213592fece04261449a59561918f1371045268f8f041b11e46d09021e22214/blob new file mode 100644 index 0000000000000000000000000000000000000000..e32495ead0f2ebd640eb413bacfedd6434b18b87 --- /dev/null +++ b/shared/package-files/d2/d2213592fece04261449a59561918f1371045268f8f041b11e46d09021e22214/blob @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 + +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. +from typing import Dict + +import torchelastic.tsm.driver.local_scheduler as local_scheduler +from torchelastic.tsm.driver.api import Scheduler, SchedulerBackend + + +def get_schedulers( + session_name: str, **scheduler_params +) -> Dict[SchedulerBackend, Scheduler]: + return { + "local": local_scheduler.create_scheduler(session_name, **scheduler_params), + "default": local_scheduler.create_scheduler(session_name, **scheduler_params), + } diff --git a/shared/package-files/d2/d223723a2db95cbbff8137d252a8918b3752a89ce8cde3cf04c468ef61f625ee/blob b/shared/package-files/d2/d223723a2db95cbbff8137d252a8918b3752a89ce8cde3cf04c468ef61f625ee/blob new file mode 100644 index 0000000000000000000000000000000000000000..c7ef8687a8b39766ba0385b5145b841043251de5 --- /dev/null +++ b/shared/package-files/d2/d223723a2db95cbbff8137d252a8918b3752a89ce8cde3cf04c468ef61f625ee/blob @@ -0,0 +1,49 @@ +""" +pytest markers for the internal Matplotlib test suite. +""" + +import logging +import shutil + +import pytest + +import matplotlib.testing +import matplotlib.testing.compare +from matplotlib import _get_executable_info, ExecutableNotFoundError + + +_log = logging.getLogger(__name__) + + +def _checkdep_usetex() -> bool: + if not shutil.which("tex"): + _log.warning("usetex mode requires TeX.") + return False + try: + _get_executable_info("dvipng") + except ExecutableNotFoundError: + _log.warning("usetex mode requires dvipng.") + return False + try: + _get_executable_info("gs") + except ExecutableNotFoundError: + _log.warning("usetex mode requires ghostscript.") + return False + return True + + +needs_ghostscript = pytest.mark.skipif( + "eps" not in matplotlib.testing.compare.converter, + reason="This test needs a ghostscript installation") +needs_pgf_lualatex = pytest.mark.skipif( + not matplotlib.testing._check_for_pgf('lualatex'), + reason='lualatex + pgf is required') +needs_pgf_pdflatex = pytest.mark.skipif( + not matplotlib.testing._check_for_pgf('pdflatex'), + reason='pdflatex + pgf is required') +needs_pgf_xelatex = pytest.mark.skipif( + not matplotlib.testing._check_for_pgf('xelatex'), + reason='xelatex + pgf is required') +needs_usetex = pytest.mark.skipif( + not _checkdep_usetex(), + reason="This test needs a TeX installation") diff --git a/shared/package-files/d2/d228846b2a5e0b2bd3f1eab5d1bf5dc30d73b4a6ab6db49ffb1e2f424c8aec1d/blob b/shared/package-files/d2/d228846b2a5e0b2bd3f1eab5d1bf5dc30d73b4a6ab6db49ffb1e2f424c8aec1d/blob new file mode 100644 index 0000000000000000000000000000000000000000..06d83f91b0e0d7a56ec1ec5f7caa5940d9f8ebd7 --- /dev/null +++ b/shared/package-files/d2/d228846b2a5e0b2bd3f1eab5d1bf5dc30d73b4a6ab6db49ffb1e2f424c8aec1d/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::special_log1p(Tensor self) -> Tensor +inline at::Tensor special_log1p(const at::Tensor & self) { + return at::_ops::special_log1p::call(self); +} + +// aten::special_log1p.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_log1p_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::special_log1p_out::call(self, out); +} +// aten::special_log1p.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_log1p_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::special_log1p_out::call(self, out); +} + +} diff --git a/shared/package-files/d2/d22b6ceecadeebd9ad4aa78f6a632a3b3b9d59d60671d4586dc1d69fdf47793e/blob b/shared/package-files/d2/d22b6ceecadeebd9ad4aa78f6a632a3b3b9d59d60671d4586dc1d69fdf47793e/blob new file mode 100644 index 0000000000000000000000000000000000000000..f043cebee22b050c24afdb9b2af0827cccd41fe8 --- /dev/null +++ b/shared/package-files/d2/d22b6ceecadeebd9ad4aa78f6a632a3b3b9d59d60671d4586dc1d69fdf47793e/blob @@ -0,0 +1,254 @@ +import itertools + +import numpy as np + +import unittest +from numba import jit, njit +from numba.core import types +from numba.tests.support import TestCase + + +def return_double_or_none(x): + if x: + ret = None + else: + ret = 1.2 + return ret + + +def return_different_statement(x): + if x: + return None + else: + return 1.2 + + +def return_bool_optional_or_none(x, y): + if y: + z = False + else: + z = None + if x == 2: + # A boolean + return True + elif x == 1: + # A runtime optional + return z + else: + # None + return None + + +def is_this_a_none(x): + if x: + val_or_none = None + else: + val_or_none = x + + if val_or_none is None: + return x - 1 + + if val_or_none is not None: + return x + 1 + + +def a_is_b(a, b): + """ + Note in nopython mode, this operation does not make much sense. + Because we don't have objects anymore. + `a is b` is always False if not operating on None and Optional type + """ + return a is b + + +def a_is_not_b(a, b): + """ + This is `not (a is b)` + """ + return a is not b + + +class TestOptional(TestCase): + + _numba_parallel_test_ = False + + def test_return_double_or_none(self): + pyfunc = return_double_or_none + cfunc = njit((types.boolean,))(pyfunc) + + for v in [True, False]: + self.assertPreciseEqual(pyfunc(v), cfunc(v)) + + def test_return_different_statement(self): + pyfunc = return_different_statement + cfunc = njit((types.boolean,))(pyfunc) + + for v in [True, False]: + self.assertPreciseEqual(pyfunc(v), cfunc(v)) + + def test_return_bool_optional_or_none(self): + pyfunc = return_bool_optional_or_none + cfunc = njit((types.int32, types.int32,))(pyfunc) + + for x, y in itertools.product((0, 1, 2), (0, 1)): + self.assertPreciseEqual(pyfunc(x, y), cfunc(x, y)) + + def test_is_this_a_none(self): + pyfunc = is_this_a_none + cfunc = njit((types.intp,))(pyfunc) + + for v in [-1, 0, 1, 2]: + self.assertPreciseEqual(pyfunc(v), cfunc(v)) + + def test_is_this_a_none_objmode(self): + pyfunc = is_this_a_none + cfunc = jit((types.intp,), forceobj=True)(pyfunc) + self.assertTrue(cfunc.overloads[cfunc.signatures[0]].objectmode) + for v in [-1, 0, 1, 2]: + self.assertPreciseEqual(pyfunc(v), cfunc(v)) + + def test_a_is_b_intp(self): + pyfunc = a_is_b + cfunc = njit((types.intp, types.intp))(pyfunc) + # integer identity relies on `==` + self.assertTrue(cfunc(1, 1)) + self.assertFalse(cfunc(1, 2)) + + def test_a_is_not_b_intp(self): + pyfunc = a_is_not_b + cfunc = njit((types.intp, types.intp))(pyfunc) + # integer identity relies on `==` + self.assertFalse(cfunc(1, 1)) + self.assertTrue(cfunc(1, 2)) + + def test_optional_float(self): + def pyfunc(x, y): + if y is None: + return x + else: + return x + y + + cfunc = njit("(float64, optional(float64))")(pyfunc) + self.assertAlmostEqual(pyfunc(1., 12.3), cfunc(1., 12.3)) + self.assertAlmostEqual(pyfunc(1., None), cfunc(1., None)) + + def test_optional_array(self): + def pyfunc(x, y): + if y is None: + return x + else: + y[0] += x + return y[0] + + cfunc = njit("(float32, optional(float32[:]))")(pyfunc) + cy = np.array([12.3], dtype=np.float32) + py = cy.copy() + self.assertAlmostEqual(pyfunc(1., py), cfunc(1., cy)) + np.testing.assert_almost_equal(py, cy) + self.assertAlmostEqual(pyfunc(1., None), cfunc(1., None)) + + def test_optional_array_error(self): + def pyfunc(y): + return y[0] + + cfunc = njit("(optional(int32[:]),)")(pyfunc) + with self.assertRaises(TypeError) as raised: + cfunc(None) + self.assertIn('expected array(int32, 1d, A), got None', + str(raised.exception)) + + y = np.array([0xabcd], dtype=np.int32) + self.assertEqual(cfunc(y), pyfunc(y)) + + def test_optional_array_attribute(self): + """ + Check that we can access attribute of an optional + """ + def pyfunc(arr, do_it): + opt = None + if do_it: # forces `opt` to be an optional of arr + opt = arr + return opt.shape[0] + + cfunc = njit(pyfunc) + arr = np.arange(5) + self.assertEqual(pyfunc(arr, True), cfunc(arr, True)) + + def test_assign_to_optional(self): + """ + Check that we can assign to a variable of optional type + """ + @njit + def make_optional(val, get_none): + if get_none: + ret = None + else: + ret = val + return ret + + @njit + def foo(val, run_second): + a = make_optional(val, True) + if run_second: + a = make_optional(val, False) + return a + + self.assertIsNone(foo(123, False)) + self.assertEqual(foo(231, True), 231) + + def test_optional_thru_omitted_arg(self): + """ + Issue 1868 + """ + + def pyfunc(x=None): + if x is None: + x = 1 + return x + + cfunc = njit(pyfunc) + self.assertEqual(pyfunc(), cfunc()) + self.assertEqual(pyfunc(3), cfunc(3)) + + def test_optional_unpack(self): + """ + Issue 2171 + """ + def pyfunc(x): + if x is None: + return + else: + a, b = x + return a, b + + tup = types.Tuple([types.intp] * 2) + opt_tup = types.Optional(tup) + sig = (opt_tup,) + cfunc = njit(sig)(pyfunc) + self.assertEqual(pyfunc(None), cfunc(None)) + self.assertEqual(pyfunc((1, 2)), cfunc((1, 2))) + + def test_many_optional_none_returns(self): + """ + Issue #4058 + """ + @njit + def foo(maybe): + lx = None + if maybe: + lx = 10 + return 1, lx + + def work(): + tmp = [] + for _ in range(20000): + maybe = False + _ = foo(maybe) + + # this caused "Fatal Python error: deallocating None" as there was no + # incref being made on the returned None. + work() + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/d2/d22c95ac7272e460d7a48c3b727e538c4efcc67005b1b22628e4917aa0f8cdc8/blob b/shared/package-files/d2/d22c95ac7272e460d7a48c3b727e538c4efcc67005b1b22628e4917aa0f8cdc8/blob new file mode 100644 index 0000000000000000000000000000000000000000..be13c06e27cb8df7ec4c55993dd3937e867429e5 --- /dev/null +++ b/shared/package-files/d2/d22c95ac7272e460d7a48c3b727e538c4efcc67005b1b22628e4917aa0f8cdc8/blob @@ -0,0 +1,715 @@ +# Copyright (c) 2017, The Chancellor, Masters and Scholars of the University +# of Oxford, and the Chebfun Developers. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the University of Oxford nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import warnings +import operator + +import numpy as np +import scipy + + +__all__ = ["AAA", "FloaterHormannInterpolator"] + + +class _BarycentricRational: + """Base class for Barycentric representation of a rational function.""" + def __init__(self, x, y, **kwargs): + # input validation + z = np.asarray(x) + f = np.asarray(y) + + self._input_validation(z, f, **kwargs) + + # Remove infinite or NaN function values and repeated entries + to_keep = np.logical_and.reduce( + ((np.isfinite(f)) & (~np.isnan(f))).reshape(f.shape[0], -1), + axis=-1 + ) + f = f[to_keep, ...] + z = z[to_keep] + z, uni = np.unique(z, return_index=True) + f = f[uni, ...] + + self._shape = f.shape[1:] + self._support_points, self._support_values, self.weights = ( + self._compute_weights(z, f, **kwargs) + ) + + # only compute once + self._poles = None + self._residues = None + self._roots = None + + def _input_validation(self, x, y, **kwargs): + if x.ndim != 1: + raise ValueError("`x` must be 1-D.") + + if not y.ndim >= 1: + raise ValueError("`y` must be at least 1-D.") + + if x.size != y.shape[0]: + raise ValueError("`x` be the same size as the first dimension of `y`.") + + if not np.all(np.isfinite(x)): + raise ValueError("`x` must be finite.") + + def _compute_weights(z, f, **kwargs): + raise NotImplementedError + + def __call__(self, z): + """Evaluate the rational approximation at given values. + + Parameters + ---------- + z : array_like + Input values. + """ + # evaluate rational function in barycentric form. + z = np.asarray(z) + zv = np.ravel(z) + + support_values = self._support_values.reshape( + (self._support_values.shape[0], -1) + ) + weights = self.weights[..., np.newaxis] + + # Cauchy matrix + # Ignore errors due to inf/inf at support points, these will be fixed later + with np.errstate(invalid="ignore", divide="ignore"): + CC = 1 / np.subtract.outer(zv, self._support_points) + # Vector of values + r = CC @ (weights * support_values) / (CC @ weights) + + # Deal with input inf: `r(inf) = lim r(z) = sum(w*f) / sum(w)` + if np.any(np.isinf(zv)): + r[np.isinf(zv)] = (np.sum(weights * support_values) + / np.sum(weights)) + + # Deal with NaN + ii = np.nonzero(np.isnan(r))[0] + for jj in ii: + if np.isnan(zv[jj]) or not np.any(zv[jj] == self._support_points): + # r(NaN) = NaN is fine. + # The second case may happen if `r(zv[ii]) = 0/0` at some point. + pass + else: + # Clean up values `NaN = inf/inf` at support points. + # Find the corresponding node and set entry to correct value: + r[jj] = support_values[zv[jj] == self._support_points].squeeze() + + return np.reshape(r, z.shape + self._shape) + + def poles(self): + """Compute the poles of the rational approximation. + + Returns + ------- + poles : array + Poles of the AAA approximation, repeated according to their multiplicity + but not in any specific order. + """ + if self._poles is None: + # Compute poles via generalized eigenvalue problem + m = self.weights.size + B = np.eye(m + 1, dtype=self.weights.dtype) + B[0, 0] = 0 + + E = np.zeros_like(B, dtype=np.result_type(self.weights, + self._support_points)) + E[0, 1:] = self.weights + E[1:, 0] = 1 + np.fill_diagonal(E[1:, 1:], self._support_points) + + pol = scipy.linalg.eigvals(E, B) + self._poles = pol[np.isfinite(pol)] + return self._poles + + def residues(self): + """Compute the residues of the poles of the approximation. + + Returns + ------- + residues : array + Residues associated with the `poles` of the approximation + """ + if self._residues is None: + # Compute residues via formula for res of quotient of analytic functions + with np.errstate(divide="ignore", invalid="ignore"): + N = (1/(np.subtract.outer(self.poles(), self._support_points))) @ ( + self._support_values * self.weights + ) + Ddiff = ( + -((1/np.subtract.outer(self.poles(), self._support_points))**2) + @ self.weights + ) + self._residues = N / Ddiff + return self._residues + + def roots(self): + """Compute the zeros of the rational approximation. + + Returns + ------- + zeros : array + Zeros of the AAA approximation, repeated according to their multiplicity + but not in any specific order. + """ + if self._roots is None: + # Compute zeros via generalized eigenvalue problem + m = self.weights.size + B = np.eye(m + 1, dtype=self.weights.dtype) + B[0, 0] = 0 + E = np.zeros_like(B, dtype=np.result_type(self.weights, + self._support_values, + self._support_points)) + E[0, 1:] = self.weights * self._support_values + E[1:, 0] = 1 + np.fill_diagonal(E[1:, 1:], self._support_points) + + zer = scipy.linalg.eigvals(E, B) + self._roots = zer[np.isfinite(zer)] + return self._roots + + +class AAA(_BarycentricRational): + r""" + AAA real or complex rational approximation. + + As described in [1]_, the AAA algorithm is a greedy algorithm for approximation by + rational functions on a real or complex set of points. The rational approximation is + represented in a barycentric form from which the roots (zeros), poles, and residues + can be computed. + + Parameters + ---------- + x : 1D array_like, shape (n,) + 1-D array containing values of the independent variable. Values may be real or + complex but must be finite. + y : 1D array_like, shape (n,) + Function values ``f(x)``. Infinite and NaN values of `values` and + corresponding values of `points` will be discarded. + rtol : float, optional + Relative tolerance, defaults to ``eps**0.75``. If a small subset of the entries + in `values` are much larger than the rest the default tolerance may be too + loose. If the tolerance is too tight then the approximation may contain + Froissart doublets or the algorithm may fail to converge entirely. + max_terms : int, optional + Maximum number of terms in the barycentric representation, defaults to ``100``. + Must be greater than or equal to one. + clean_up : bool, optional + Automatic removal of Froissart doublets, defaults to ``True``. See notes for + more details. + clean_up_tol : float, optional + Poles with residues less than this number times the geometric mean + of `values` times the minimum distance to `points` are deemed spurious by the + cleanup procedure, defaults to 1e-13. See notes for more details. + + Attributes + ---------- + support_points : array + Support points of the approximation. These are a subset of the provided `x` at + which the approximation strictly interpolates `y`. + See notes for more details. + support_values : array + Value of the approximation at the `support_points`. + weights : array + Weights of the barycentric approximation. + errors : array + Error :math:`|f(z) - r(z)|_\infty` over `points` in the successive iterations + of AAA. + + Warns + ----- + RuntimeWarning + If `rtol` is not achieved in `max_terms` iterations. + + See Also + -------- + FloaterHormannInterpolator : Floater-Hormann barycentric rational interpolation. + pade : Padé approximation. + + Notes + ----- + At iteration :math:`m` (at which point there are :math:`m` terms in the both the + numerator and denominator of the approximation), the + rational approximation in the AAA algorithm takes the barycentric form + + .. math:: + + r(z) = n(z)/d(z) = + \frac{\sum_{j=1}^m\ w_j f_j / (z - z_j)}{\sum_{j=1}^m w_j / (z - z_j)}, + + where :math:`z_1,\dots,z_m` are real or complex support points selected from + `x`, :math:`f_1,\dots,f_m` are the corresponding real or complex data values + from `y`, and :math:`w_1,\dots,w_m` are real or complex weights. + + Each iteration of the algorithm has two parts: the greedy selection the next support + point and the computation of the weights. The first part of each iteration is to + select the next support point to be added :math:`z_{m+1}` from the remaining + unselected `x`, such that the nonlinear residual + :math:`|f(z_{m+1}) - n(z_{m+1})/d(z_{m+1})|` is maximised. The algorithm terminates + when this maximum is less than ``rtol * np.linalg.norm(f, ord=np.inf)``. This means + the interpolation property is only satisfied up to a tolerance, except at the + support points where approximation exactly interpolates the supplied data. + + In the second part of each iteration, the weights :math:`w_j` are selected to solve + the least-squares problem + + .. math:: + + \text{minimise}_{w_j}|fd - n| \quad \text{subject to} \quad + \sum_{j=1}^{m+1} w_j = 1, + + over the unselected elements of `x`. + + One of the challenges with working with rational approximations is the presence of + Froissart doublets, which are either poles with vanishingly small residues or + pole-zero pairs that are close enough together to nearly cancel, see [2]_. The + greedy nature of the AAA algorithm means Froissart doublets are rare. However, if + `rtol` is set too tight then the approximation will stagnate and many Froissart + doublets will appear. Froissart doublets can usually be removed by removing support + points and then resolving the least squares problem. The support point :math:`z_j`, + which is the closest support point to the pole :math:`a` with residue + :math:`\alpha`, is removed if the following is satisfied + + .. math:: + + |\alpha| / |z_j - a| < \verb|clean_up_tol| \cdot \tilde{f}, + + where :math:`\tilde{f}` is the geometric mean of `support_values`. + + + References + ---------- + .. [1] Y. Nakatsukasa, O. Sete, and L. N. Trefethen, "The AAA algorithm for + rational approximation", SIAM J. Sci. Comp. 40 (2018), A1494-A1522. + :doi:`10.1137/16M1106122` + .. [2] J. Gilewicz and M. Pindor, Pade approximants and noise: rational functions, + J. Comp. Appl. Math. 105 (1999), pp. 285-297. + :doi:`10.1016/S0377-0427(02)00674-X` + + Examples + -------- + + Here we reproduce a number of the numerical examples from [1]_ as a demonstration + of the functionality offered by this method. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import AAA + >>> import warnings + + For the first example we approximate the gamma function on ``[-3.5, 4.5]`` by + extrapolating from 100 samples in ``[-1.5, 1.5]``. + + >>> from scipy.special import gamma + >>> sample_points = np.linspace(-1.5, 1.5, num=100) + >>> r = AAA(sample_points, gamma(sample_points)) + >>> z = np.linspace(-3.5, 4.5, num=1000) + >>> fig, ax = plt.subplots() + >>> ax.plot(z, gamma(z), label="Gamma") + >>> ax.plot(sample_points, gamma(sample_points), label="Sample points") + >>> ax.plot(z, r(z).real, '--', label="AAA approximation") + >>> ax.set(xlabel="z", ylabel="r(z)", ylim=[-8, 8], xlim=[-3.5, 4.5]) + >>> ax.legend() + >>> plt.show() + + We can also view the poles of the rational approximation and their residues: + + >>> order = np.argsort(r.poles()) + >>> r.poles()[order] + array([-3.81591039e+00+0.j , -3.00269049e+00+0.j , + -1.99999988e+00+0.j , -1.00000000e+00+0.j , + 5.85842812e-17+0.j , 4.77485458e+00-3.06919376j, + 4.77485458e+00+3.06919376j, 5.29095868e+00-0.97373072j, + 5.29095868e+00+0.97373072j]) + >>> r.residues()[order] + array([ 0.03658074 +0.j , -0.16915426 -0.j , + 0.49999915 +0.j , -1. +0.j , + 1. +0.j , -0.81132013 -2.30193429j, + -0.81132013 +2.30193429j, 0.87326839+10.70148546j, + 0.87326839-10.70148546j]) + + For the second example, we call `AAA` with a spiral of 1000 points that wind 7.5 + times around the origin in the complex plane. + + >>> z = np.exp(np.linspace(-0.5, 0.5 + 15j*np.pi, 1000)) + >>> r = AAA(z, np.tan(np.pi*z/2), rtol=1e-13) + + We see that AAA takes 12 steps to converge with the following errors: + + >>> r.errors.size + 12 + >>> r.errors + array([2.49261500e+01, 4.28045609e+01, 1.71346935e+01, 8.65055336e-02, + 1.27106444e-02, 9.90889874e-04, 5.86910543e-05, 1.28735561e-06, + 3.57007424e-08, 6.37007837e-10, 1.67103357e-11, 1.17112299e-13]) + + We can also plot the computed poles: + + >>> fig, ax = plt.subplots() + >>> ax.plot(z.real, z.imag, '.', markersize=2, label="Sample points") + >>> ax.plot(r.poles().real, r.poles().imag, '.', markersize=5, + ... label="Computed poles") + >>> ax.set(xlim=[-3.5, 3.5], ylim=[-3.5, 3.5], aspect="equal") + >>> ax.legend() + >>> plt.show() + + We now demonstrate the removal of Froissart doublets using the `clean_up` method + using an example from [1]_. Here we approximate the function + :math:`f(z)=\log(2 + z^4)/(1 + 16z^4)` by sampling it at 1000 roots of unity. The + algorithm is run with ``rtol=0`` and ``clean_up=False`` to deliberately cause + Froissart doublets to appear. + + >>> z = np.exp(1j*2*np.pi*np.linspace(0,1, num=1000)) + >>> def f(z): + ... return np.log(2 + z**4)/(1 - 16*z**4) + >>> with warnings.catch_warnings(): # filter convergence warning due to rtol=0 + ... warnings.simplefilter('ignore', RuntimeWarning) + ... r = AAA(z, f(z), rtol=0, max_terms=50, clean_up=False) + >>> mask = np.abs(r.residues()) < 1e-13 + >>> fig, axs = plt.subplots(ncols=2) + >>> axs[0].plot(r.poles().real[~mask], r.poles().imag[~mask], '.') + >>> axs[0].plot(r.poles().real[mask], r.poles().imag[mask], 'r.') + + Now we call the `clean_up` method to remove Froissart doublets. + + >>> with warnings.catch_warnings(): + ... warnings.simplefilter('ignore', RuntimeWarning) + ... r.clean_up() + 4 + >>> mask = np.abs(r.residues()) < 1e-13 + >>> axs[1].plot(r.poles().real[~mask], r.poles().imag[~mask], '.') + >>> axs[1].plot(r.poles().real[mask], r.poles().imag[mask], 'r.') + >>> plt.show() + + The left image shows the poles prior of the approximation ``clean_up=False`` with + poles with residue less than ``10^-13`` in absolute value shown in red. The right + image then shows the poles after the `clean_up` method has been called. + """ + def __init__(self, x, y, *, rtol=None, max_terms=100, clean_up=True, + clean_up_tol=1e-13): + super().__init__(x, y, rtol=rtol, max_terms=max_terms) + + if clean_up: + self.clean_up(clean_up_tol) + + def _input_validation(self, x, y, rtol=None, max_terms=100, clean_up=True, + clean_up_tol=1e-13): + max_terms = operator.index(max_terms) + if max_terms < 1: + raise ValueError("`max_terms` must be an integer value greater than or " + "equal to one.") + + if y.ndim != 1: + raise ValueError("`y` must be 1-D.") + + super()._input_validation(x, y) + + @property + def support_points(self): + return self._support_points + + @property + def support_values(self): + return self._support_values + + def _compute_weights(self, z, f, rtol, max_terms): + # Initialization for AAA iteration + M = np.size(z) + mask = np.ones(M, dtype=np.bool_) + dtype = np.result_type(z, f, 1.0) + rtol = np.finfo(dtype).eps**0.75 if rtol is None else rtol + atol = rtol * np.linalg.norm(f, ord=np.inf) + zj = np.empty(max_terms, dtype=dtype) + fj = np.empty(max_terms, dtype=dtype) + # Cauchy matrix + C = np.empty((M, max_terms), dtype=dtype) + # Loewner matrix + A = np.empty((M, max_terms), dtype=dtype) + errors = np.empty(max_terms, dtype=A.real.dtype) + R = np.repeat(np.mean(f), M) + + # AAA iteration + for m in range(max_terms): + # Introduce next support point + # Select next support point + jj = np.argmax(np.abs(f[mask] - R[mask])) + # Update support points + zj[m] = z[mask][jj] + # Update data values + fj[m] = f[mask][jj] + # Next column of Cauchy matrix + # Ignore errors as we manually interpolate at support points + with np.errstate(divide="ignore", invalid="ignore"): + C[:, m] = 1 / (z - z[mask][jj]) + # Update mask + mask[np.nonzero(mask)[0][jj]] = False + # Update Loewner matrix + # Ignore errors as inf values will be masked out in SVD call + with np.errstate(invalid="ignore"): + A[:, m] = (f - fj[m]) * C[:, m] + + # Compute weights + rows = mask.sum() + if rows >= m + 1: + # The usual tall-skinny case + _, s, V = scipy.linalg.svd( + A[mask, : m + 1], full_matrices=False, check_finite=False, + ) + # Treat case of multiple min singular values + mm = s == np.min(s) + # Aim for non-sparse weight vector + wj = (V.conj()[mm, :].sum(axis=0) / np.sqrt(mm.sum())).astype(dtype) + else: + # Fewer rows than columns + V = scipy.linalg.null_space(A[mask, : m + 1], check_finite=False) + nm = V.shape[-1] + # Aim for non-sparse wt vector + wj = V.sum(axis=-1) / np.sqrt(nm) + + # Compute rational approximant + # Omit columns with `wj == 0` + i0 = wj != 0 + # Ignore errors as we manually interpolate at support points + with np.errstate(invalid="ignore"): + # Numerator + N = C[:, : m + 1][:, i0] @ (wj[i0] * fj[: m + 1][i0]) + # Denominator + D = C[:, : m + 1][:, i0] @ wj[i0] + # Interpolate at support points with `wj !=0` + D_inf = np.isinf(D) | np.isnan(D) + D[D_inf] = 1 + N[D_inf] = f[D_inf] + R = N / D + + # Check if converged + max_error = np.linalg.norm(f - R, ord=np.inf) + errors[m] = max_error + if max_error <= atol: + break + + if m == max_terms - 1: + warnings.warn(f"AAA failed to converge within {max_terms} iterations.", + RuntimeWarning, stacklevel=2) + + # Trim off unused array allocation + zj = zj[: m + 1] + fj = fj[: m + 1] + + # Remove support points with zero weight + i_non_zero = wj != 0 + self.errors = errors[: m + 1] + self._points = z + self._values = f + return zj[i_non_zero], fj[i_non_zero], wj[i_non_zero] + + def clean_up(self, cleanup_tol=1e-13): + """Automatic removal of Froissart doublets. + + Parameters + ---------- + cleanup_tol : float, optional + Poles with residues less than this number times the geometric mean + of `values` times the minimum distance to `points` are deemed spurious by + the cleanup procedure, defaults to 1e-13. + + Returns + ------- + int + Number of Froissart doublets detected + """ + # Find negligible residues + geom_mean_abs_f = scipy.stats.gmean(np.abs(self._values)) + + Z_distances = np.min( + np.abs(np.subtract.outer(self.poles(), self._points)), axis=1 + ) + + with np.errstate(divide="ignore", invalid="ignore"): + ii = np.nonzero( + np.abs(self.residues()) / Z_distances < cleanup_tol * geom_mean_abs_f + ) + + ni = ii[0].size + if ni == 0: + return ni + + warnings.warn(f"{ni} Froissart doublets detected.", RuntimeWarning, + stacklevel=2) + + # For each spurious pole find and remove closest support point + closest_spt_point = np.argmin( + np.abs(np.subtract.outer(self._support_points, self.poles()[ii])), axis=0 + ) + self._support_points = np.delete(self._support_points, closest_spt_point) + self._support_values = np.delete(self._support_values, closest_spt_point) + + # Remove support points z from sample set + mask = np.logical_and.reduce( + np.not_equal.outer(self._points, self._support_points), axis=1 + ) + f = self._values[mask] + z = self._points[mask] + + # recompute weights, we resolve the least squares problem for the remaining + # support points + + m = self._support_points.size + + # Cauchy matrix + C = 1 / np.subtract.outer(z, self._support_points) + # Loewner matrix + A = f[:, np.newaxis] * C - C * self._support_values + + # Solve least-squares problem to obtain weights + _, _, V = scipy.linalg.svd(A, check_finite=False) + self.weights = np.conj(V[m - 1,:]) + + # reset roots, poles, residues as cached values will be wrong with new weights + self._poles = None + self._residues = None + self._roots = None + + return ni + + +class FloaterHormannInterpolator(_BarycentricRational): + r""" + Floater-Hormann barycentric rational interpolation. + + As described in [1]_, the method of Floater and Hormann computes weights for a + Barycentric rational interpolant with no poles on the real axis. + + Parameters + ---------- + x : 1D array_like, shape (n,) + 1-D array containing values of the independent variable. Values may be real or + complex but must be finite. + y : array_like, shape (n, ...) + Array containing values of the dependent variable. Infinite and NaN values + of `values` and corresponding values of `x` will be discarded. + d : int, optional + Blends ``n - d`` degree `d` polynomials together. For ``d = n - 1`` it is + equivalent to polynomial interpolation. Must satisfy ``0 <= d < n``, + defaults to 3. + + Attributes + ---------- + weights : array + Weights of the barycentric approximation. + + See Also + -------- + AAA : Barycentric rational approximation of real and complex functions. + pade : Padé approximation. + + Notes + ----- + The Floater-Hormann interpolant is a rational function that interpolates the data + with approximation order :math:`O(h^{d+1})`. The rational function blends ``n - d`` + polynomials of degree `d` together to produce a rational interpolant that contains + no poles on the real axis, unlike `AAA`. The interpolant is given + by + + .. math:: + + r(x) = \frac{\sum_{i=0}^{n-d} \lambda_i(x) p_i(x)} + {\sum_{i=0}^{n-d} \lambda_i(x)}, + + where :math:`p_i(x)` is an interpolating polynomials of at most degree `d` through + the points :math:`(x_i,y_i),\dots,(x_{i+d},y_{i+d}), and :math:`\lambda_i(z)` are + blending functions defined by + + .. math:: + + \lambda_i(x) = \frac{(-1)^i}{(x - x_i)\cdots(x - x_{i+d})}. + + When ``d = n - 1`` this reduces to polynomial interpolation. + + Due to its stability following barycentric representation of the above equation + is used instead for computation + + .. math:: + + r(z) = \frac{\sum_{k=1}^m\ w_k f_k / (x - x_k)}{\sum_{k=1}^m w_k / (x - x_k)}, + + where the weights :math:`w_j` are computed as + + .. math:: + + w_k &= (-1)^{k - d} \sum_{i \in J_k} \prod_{j = i, j \neq k}^{i + d} + 1/|x_k - x_j|, \\ + J_k &= \{ i \in I: k - d \leq i \leq k\},\\ + I &= \{0, 1, \dots, n - d\}. + + References + ---------- + .. [1] M.S. Floater and K. Hormann, "Barycentric rational interpolation with no + poles and high rates of approximation", Numer. Math. 107, 315 (2007). + :doi:`10.1007/s00211-007-0093-y` + + Examples + -------- + + Here we compare the method against polynomial interpolation for an example where + the polynomial interpolation fails due to Runge's phenomenon. + + >>> import numpy as np + >>> from scipy.interpolate import (FloaterHormannInterpolator, + ... BarycentricInterpolator) + >>> def f(z): + ... return 1/(1 + z**2) + >>> z = np.linspace(-5, 5, num=15) + >>> r = FloaterHormannInterpolator(z, f(z)) + >>> p = BarycentricInterpolator(z, f(z)) + >>> zz = np.linspace(-5, 5, num=1000) + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> ax.plot(zz, r(zz), label="Floater=Hormann") + >>> ax.plot(zz, p(zz), label="Polynomial") + >>> ax.legend() + >>> plt.show() + """ + def __init__(self, points, values, *, d=3): + super().__init__(points, values, d=d) + + def _input_validation(self, x, y, d): + d = operator.index(d) + if not (0 <= d < len(x)): + raise ValueError("`d` must satisfy 0 <= d < n") + + super()._input_validation(x, y) + + def _compute_weights(self, z, f, d): + # Floater and Hormann 2007 Eqn. (18) 3 equations later + w = np.zeros_like(z, dtype=np.result_type(z, 1.0)) + n = w.size + for k in range(n): + for i in range(max(k-d, 0), min(k+1, n-d)): + w[k] += 1/np.prod(np.abs(np.delete(z[k] - z[i : i + d + 1], k - i))) + w *= (-1.)**(np.arange(n) - d) + + return z, f, w diff --git a/shared/package-files/d2/d22e07ecd2ecc5cc73142254e4e3432668652efb122c29da167f855c0e523109/blob b/shared/package-files/d2/d22e07ecd2ecc5cc73142254e4e3432668652efb122c29da167f855c0e523109/blob new file mode 100644 index 0000000000000000000000000000000000000000..50872fe247540b8e3d862d8aa7d46bf4c64629e6 --- /dev/null +++ b/shared/package-files/d2/d22e07ecd2ecc5cc73142254e4e3432668652efb122c29da167f855c0e523109/blob @@ -0,0 +1,83 @@ +""" + pygments.formatters.pangomarkup + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Formatter for Pango markup output. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.formatter import Formatter + + +__all__ = ['PangoMarkupFormatter'] + + +_escape_table = { + ord('&'): '&', + ord('<'): '<', +} + + +def escape_special_chars(text, table=_escape_table): + """Escape & and < for Pango Markup.""" + return text.translate(table) + + +class PangoMarkupFormatter(Formatter): + """ + Format tokens as Pango Markup code. It can then be rendered to an SVG. + + .. versionadded:: 2.9 + """ + + name = 'Pango Markup' + aliases = ['pango', 'pangomarkup'] + filenames = [] + + def __init__(self, **options): + Formatter.__init__(self, **options) + + self.styles = {} + + for token, style in self.style: + start = '' + end = '' + if style['color']: + start += '' % style['color'] + end = '' + end + if style['bold']: + start += '' + end = '' + end + if style['italic']: + start += '' + end = '' + end + if style['underline']: + start += '' + end = '' + end + self.styles[token] = (start, end) + + def format_unencoded(self, tokensource, outfile): + lastval = '' + lasttype = None + + outfile.write('') + + for ttype, value in tokensource: + while ttype not in self.styles: + ttype = ttype.parent + if ttype == lasttype: + lastval += escape_special_chars(value) + else: + if lastval: + stylebegin, styleend = self.styles[lasttype] + outfile.write(stylebegin + lastval + styleend) + lastval = escape_special_chars(value) + lasttype = ttype + + if lastval: + stylebegin, styleend = self.styles[lasttype] + outfile.write(stylebegin + lastval + styleend) + + outfile.write('') diff --git a/shared/package-files/d2/d22f0f5c9ff876a588a139b6beacceaf5613ebb4dbf71353faab553649384814/blob b/shared/package-files/d2/d22f0f5c9ff876a588a139b6beacceaf5613ebb4dbf71353faab553649384814/blob new file mode 100644 index 0000000000000000000000000000000000000000..fb25e3e101b4a6229e3d5745c2d3f41e3e0b4c09 Binary files /dev/null and b/shared/package-files/d2/d22f0f5c9ff876a588a139b6beacceaf5613ebb4dbf71353faab553649384814/blob differ diff --git a/shared/package-files/d2/d22f1c260aeaba9cdaebb2013d9feef635ef9d2c6be54065544894a9d90fb582/blob b/shared/package-files/d2/d22f1c260aeaba9cdaebb2013d9feef635ef9d2c6be54065544894a9d90fb582/blob new file mode 100644 index 0000000000000000000000000000000000000000..14b10daf3a96229be87eed34c643e962a0d30450 --- /dev/null +++ b/shared/package-files/d2/d22f1c260aeaba9cdaebb2013d9feef635ef9d2c6be54065544894a9d90fb582/blob @@ -0,0 +1,537 @@ +from __future__ import absolute_import + +import collections +import functools +import logging + +from ._collections import RecentlyUsedContainer +from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme +from .exceptions import ( + LocationValueError, + MaxRetryError, + ProxySchemeUnknown, + ProxySchemeUnsupported, + URLSchemeUnknown, +) +from .packages import six +from .packages.six.moves.urllib.parse import urljoin +from .request import RequestMethods +from .util.proxy import connection_requires_http_tunnel +from .util.retry import Retry +from .util.url import parse_url + +__all__ = ["PoolManager", "ProxyManager", "proxy_from_url"] + + +log = logging.getLogger(__name__) + +SSL_KEYWORDS = ( + "key_file", + "cert_file", + "cert_reqs", + "ca_certs", + "ssl_version", + "ca_cert_dir", + "ssl_context", + "key_password", + "server_hostname", +) + +# All known keyword arguments that could be provided to the pool manager, its +# pools, or the underlying connections. This is used to construct a pool key. +_key_fields = ( + "key_scheme", # str + "key_host", # str + "key_port", # int + "key_timeout", # int or float or Timeout + "key_retries", # int or Retry + "key_strict", # bool + "key_block", # bool + "key_source_address", # str + "key_key_file", # str + "key_key_password", # str + "key_cert_file", # str + "key_cert_reqs", # str + "key_ca_certs", # str + "key_ssl_version", # str + "key_ca_cert_dir", # str + "key_ssl_context", # instance of ssl.SSLContext or urllib3.util.ssl_.SSLContext + "key_maxsize", # int + "key_headers", # dict + "key__proxy", # parsed proxy url + "key__proxy_headers", # dict + "key__proxy_config", # class + "key_socket_options", # list of (level (int), optname (int), value (int or str)) tuples + "key__socks_options", # dict + "key_assert_hostname", # bool or string + "key_assert_fingerprint", # str + "key_server_hostname", # str +) + +#: The namedtuple class used to construct keys for the connection pool. +#: All custom key schemes should include the fields in this key at a minimum. +PoolKey = collections.namedtuple("PoolKey", _key_fields) + +_proxy_config_fields = ("ssl_context", "use_forwarding_for_https") +ProxyConfig = collections.namedtuple("ProxyConfig", _proxy_config_fields) + + +def _default_key_normalizer(key_class, request_context): + """ + Create a pool key out of a request context dictionary. + + According to RFC 3986, both the scheme and host are case-insensitive. + Therefore, this function normalizes both before constructing the pool + key for an HTTPS request. If you wish to change this behaviour, provide + alternate callables to ``key_fn_by_scheme``. + + :param key_class: + The class to use when constructing the key. This should be a namedtuple + with the ``scheme`` and ``host`` keys at a minimum. + :type key_class: namedtuple + :param request_context: + A dictionary-like object that contain the context for a request. + :type request_context: dict + + :return: A namedtuple that can be used as a connection pool key. + :rtype: PoolKey + """ + # Since we mutate the dictionary, make a copy first + context = request_context.copy() + context["scheme"] = context["scheme"].lower() + context["host"] = context["host"].lower() + + # These are both dictionaries and need to be transformed into frozensets + for key in ("headers", "_proxy_headers", "_socks_options"): + if key in context and context[key] is not None: + context[key] = frozenset(context[key].items()) + + # The socket_options key may be a list and needs to be transformed into a + # tuple. + socket_opts = context.get("socket_options") + if socket_opts is not None: + context["socket_options"] = tuple(socket_opts) + + # Map the kwargs to the names in the namedtuple - this is necessary since + # namedtuples can't have fields starting with '_'. + for key in list(context.keys()): + context["key_" + key] = context.pop(key) + + # Default to ``None`` for keys missing from the context + for field in key_class._fields: + if field not in context: + context[field] = None + + return key_class(**context) + + +#: A dictionary that maps a scheme to a callable that creates a pool key. +#: This can be used to alter the way pool keys are constructed, if desired. +#: Each PoolManager makes a copy of this dictionary so they can be configured +#: globally here, or individually on the instance. +key_fn_by_scheme = { + "http": functools.partial(_default_key_normalizer, PoolKey), + "https": functools.partial(_default_key_normalizer, PoolKey), +} + +pool_classes_by_scheme = {"http": HTTPConnectionPool, "https": HTTPSConnectionPool} + + +class PoolManager(RequestMethods): + """ + Allows for arbitrary requests while transparently keeping track of + necessary connection pools for you. + + :param num_pools: + Number of connection pools to cache before discarding the least + recently used pool. + + :param headers: + Headers to include with all requests, unless other headers are given + explicitly. + + :param \\**connection_pool_kw: + Additional parameters are used to create fresh + :class:`urllib3.connectionpool.ConnectionPool` instances. + + Example:: + + >>> manager = PoolManager(num_pools=2) + >>> r = manager.request('GET', 'http://google.com/') + >>> r = manager.request('GET', 'http://google.com/mail') + >>> r = manager.request('GET', 'http://yahoo.com/') + >>> len(manager.pools) + 2 + + """ + + proxy = None + proxy_config = None + + def __init__(self, num_pools=10, headers=None, **connection_pool_kw): + RequestMethods.__init__(self, headers) + self.connection_pool_kw = connection_pool_kw + self.pools = RecentlyUsedContainer(num_pools) + + # Locally set the pool classes and keys so other PoolManagers can + # override them. + self.pool_classes_by_scheme = pool_classes_by_scheme + self.key_fn_by_scheme = key_fn_by_scheme.copy() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.clear() + # Return False to re-raise any potential exceptions + return False + + def _new_pool(self, scheme, host, port, request_context=None): + """ + Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and + any additional pool keyword arguments. + + If ``request_context`` is provided, it is provided as keyword arguments + to the pool class used. This method is used to actually create the + connection pools handed out by :meth:`connection_from_url` and + companion methods. It is intended to be overridden for customization. + """ + pool_cls = self.pool_classes_by_scheme[scheme] + if request_context is None: + request_context = self.connection_pool_kw.copy() + + # Although the context has everything necessary to create the pool, + # this function has historically only used the scheme, host, and port + # in the positional args. When an API change is acceptable these can + # be removed. + for key in ("scheme", "host", "port"): + request_context.pop(key, None) + + if scheme == "http": + for kw in SSL_KEYWORDS: + request_context.pop(kw, None) + + return pool_cls(host, port, **request_context) + + def clear(self): + """ + Empty our store of pools and direct them all to close. + + This will not affect in-flight connections, but they will not be + re-used after completion. + """ + self.pools.clear() + + def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None): + """ + Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme. + + If ``port`` isn't given, it will be derived from the ``scheme`` using + ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is + provided, it is merged with the instance's ``connection_pool_kw`` + variable and used to create the new connection pool, if one is + needed. + """ + + if not host: + raise LocationValueError("No host specified.") + + request_context = self._merge_pool_kwargs(pool_kwargs) + request_context["scheme"] = scheme or "http" + if not port: + port = port_by_scheme.get(request_context["scheme"].lower(), 80) + request_context["port"] = port + request_context["host"] = host + + return self.connection_from_context(request_context) + + def connection_from_context(self, request_context): + """ + Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context. + + ``request_context`` must at least contain the ``scheme`` key and its + value must be a key in ``key_fn_by_scheme`` instance variable. + """ + scheme = request_context["scheme"].lower() + pool_key_constructor = self.key_fn_by_scheme.get(scheme) + if not pool_key_constructor: + raise URLSchemeUnknown(scheme) + pool_key = pool_key_constructor(request_context) + + return self.connection_from_pool_key(pool_key, request_context=request_context) + + def connection_from_pool_key(self, pool_key, request_context=None): + """ + Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key. + + ``pool_key`` should be a namedtuple that only contains immutable + objects. At a minimum it must have the ``scheme``, ``host``, and + ``port`` fields. + """ + with self.pools.lock: + # If the scheme, host, or port doesn't match existing open + # connections, open a new ConnectionPool. + pool = self.pools.get(pool_key) + if pool: + return pool + + # Make a fresh ConnectionPool of the desired type + scheme = request_context["scheme"] + host = request_context["host"] + port = request_context["port"] + pool = self._new_pool(scheme, host, port, request_context=request_context) + self.pools[pool_key] = pool + + return pool + + def connection_from_url(self, url, pool_kwargs=None): + """ + Similar to :func:`urllib3.connectionpool.connection_from_url`. + + If ``pool_kwargs`` is not provided and a new pool needs to be + constructed, ``self.connection_pool_kw`` is used to initialize + the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs`` + is provided, it is used instead. Note that if a new pool does not + need to be created for the request, the provided ``pool_kwargs`` are + not used. + """ + u = parse_url(url) + return self.connection_from_host( + u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs + ) + + def _merge_pool_kwargs(self, override): + """ + Merge a dictionary of override values for self.connection_pool_kw. + + This does not modify self.connection_pool_kw and returns a new dict. + Any keys in the override dictionary with a value of ``None`` are + removed from the merged dictionary. + """ + base_pool_kwargs = self.connection_pool_kw.copy() + if override: + for key, value in override.items(): + if value is None: + try: + del base_pool_kwargs[key] + except KeyError: + pass + else: + base_pool_kwargs[key] = value + return base_pool_kwargs + + def _proxy_requires_url_absolute_form(self, parsed_url): + """ + Indicates if the proxy requires the complete destination URL in the + request. Normally this is only needed when not using an HTTP CONNECT + tunnel. + """ + if self.proxy is None: + return False + + return not connection_requires_http_tunnel( + self.proxy, self.proxy_config, parsed_url.scheme + ) + + def _validate_proxy_scheme_url_selection(self, url_scheme): + """ + Validates that were not attempting to do TLS in TLS connections on + Python2 or with unsupported SSL implementations. + """ + if self.proxy is None or url_scheme != "https": + return + + if self.proxy.scheme != "https": + return + + if six.PY2 and not self.proxy_config.use_forwarding_for_https: + raise ProxySchemeUnsupported( + "Contacting HTTPS destinations through HTTPS proxies " + "'via CONNECT tunnels' is not supported in Python 2" + ) + + def urlopen(self, method, url, redirect=True, **kw): + """ + Same as :meth:`urllib3.HTTPConnectionPool.urlopen` + with custom cross-host redirect logic and only sends the request-uri + portion of the ``url``. + + The given ``url`` parameter must be absolute, such that an appropriate + :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it. + """ + u = parse_url(url) + self._validate_proxy_scheme_url_selection(u.scheme) + + conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme) + + kw["assert_same_host"] = False + kw["redirect"] = False + + if "headers" not in kw: + kw["headers"] = self.headers.copy() + + if self._proxy_requires_url_absolute_form(u): + response = conn.urlopen(method, url, **kw) + else: + response = conn.urlopen(method, u.request_uri, **kw) + + redirect_location = redirect and response.get_redirect_location() + if not redirect_location: + return response + + # Support relative URLs for redirecting. + redirect_location = urljoin(url, redirect_location) + + # RFC 7231, Section 6.4.4 + if response.status == 303: + method = "GET" + + retries = kw.get("retries") + if not isinstance(retries, Retry): + retries = Retry.from_int(retries, redirect=redirect) + + # Strip headers marked as unsafe to forward to the redirected location. + # Check remove_headers_on_redirect to avoid a potential network call within + # conn.is_same_host() which may use socket.gethostbyname() in the future. + if retries.remove_headers_on_redirect and not conn.is_same_host( + redirect_location + ): + headers = list(six.iterkeys(kw["headers"])) + for header in headers: + if header.lower() in retries.remove_headers_on_redirect: + kw["headers"].pop(header, None) + + try: + retries = retries.increment(method, url, response=response, _pool=conn) + except MaxRetryError: + if retries.raise_on_redirect: + response.drain_conn() + raise + return response + + kw["retries"] = retries + kw["redirect"] = redirect + + log.info("Redirecting %s -> %s", url, redirect_location) + + response.drain_conn() + return self.urlopen(method, redirect_location, **kw) + + +class ProxyManager(PoolManager): + """ + Behaves just like :class:`PoolManager`, but sends all requests through + the defined proxy, using the CONNECT method for HTTPS URLs. + + :param proxy_url: + The URL of the proxy to be used. + + :param proxy_headers: + A dictionary containing headers that will be sent to the proxy. In case + of HTTP they are being sent with each request, while in the + HTTPS/CONNECT case they are sent only once. Could be used for proxy + authentication. + + :param proxy_ssl_context: + The proxy SSL context is used to establish the TLS connection to the + proxy when using HTTPS proxies. + + :param use_forwarding_for_https: + (Defaults to False) If set to True will forward requests to the HTTPS + proxy to be made on behalf of the client instead of creating a TLS + tunnel via the CONNECT method. **Enabling this flag means that request + and response headers and content will be visible from the HTTPS proxy** + whereas tunneling keeps request and response headers and content + private. IP address, target hostname, SNI, and port are always visible + to an HTTPS proxy even when this flag is disabled. + + Example: + >>> proxy = urllib3.ProxyManager('http://localhost:3128/') + >>> r1 = proxy.request('GET', 'http://google.com/') + >>> r2 = proxy.request('GET', 'http://httpbin.org/') + >>> len(proxy.pools) + 1 + >>> r3 = proxy.request('GET', 'https://httpbin.org/') + >>> r4 = proxy.request('GET', 'https://twitter.com/') + >>> len(proxy.pools) + 3 + + """ + + def __init__( + self, + proxy_url, + num_pools=10, + headers=None, + proxy_headers=None, + proxy_ssl_context=None, + use_forwarding_for_https=False, + **connection_pool_kw + ): + + if isinstance(proxy_url, HTTPConnectionPool): + proxy_url = "%s://%s:%i" % ( + proxy_url.scheme, + proxy_url.host, + proxy_url.port, + ) + proxy = parse_url(proxy_url) + + if proxy.scheme not in ("http", "https"): + raise ProxySchemeUnknown(proxy.scheme) + + if not proxy.port: + port = port_by_scheme.get(proxy.scheme, 80) + proxy = proxy._replace(port=port) + + self.proxy = proxy + self.proxy_headers = proxy_headers or {} + self.proxy_ssl_context = proxy_ssl_context + self.proxy_config = ProxyConfig(proxy_ssl_context, use_forwarding_for_https) + + connection_pool_kw["_proxy"] = self.proxy + connection_pool_kw["_proxy_headers"] = self.proxy_headers + connection_pool_kw["_proxy_config"] = self.proxy_config + + super(ProxyManager, self).__init__(num_pools, headers, **connection_pool_kw) + + def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None): + if scheme == "https": + return super(ProxyManager, self).connection_from_host( + host, port, scheme, pool_kwargs=pool_kwargs + ) + + return super(ProxyManager, self).connection_from_host( + self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs + ) + + def _set_proxy_headers(self, url, headers=None): + """ + Sets headers needed by proxies: specifically, the Accept and Host + headers. Only sets headers not provided by the user. + """ + headers_ = {"Accept": "*/*"} + + netloc = parse_url(url).netloc + if netloc: + headers_["Host"] = netloc + + if headers: + headers_.update(headers) + return headers_ + + def urlopen(self, method, url, redirect=True, **kw): + "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute." + u = parse_url(url) + if not connection_requires_http_tunnel(self.proxy, self.proxy_config, u.scheme): + # For connections using HTTP CONNECT, httplib sets the necessary + # headers on the CONNECT to the proxy. If we're not using CONNECT, + # we'll definitely need to set 'Host' at the very least. + headers = kw.get("headers", self.headers) + kw["headers"] = self._set_proxy_headers(url, headers) + + return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw) + + +def proxy_from_url(url, **kw): + return ProxyManager(proxy_url=url, **kw) diff --git a/shared/package-files/d2/d2329157b7c40ae588d7aacd9e4b3464408a03589960220468ff00d59be35122/blob b/shared/package-files/d2/d2329157b7c40ae588d7aacd9e4b3464408a03589960220468ff00d59be35122/blob new file mode 100644 index 0000000000000000000000000000000000000000..fa7307ed8985ad7e318660da0066440f890d1624 --- /dev/null +++ b/shared/package-files/d2/d2329157b7c40ae588d7aacd9e4b3464408a03589960220468ff00d59be35122/blob @@ -0,0 +1,49 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .chardistribution import EUCKRDistributionAnalysis +from .codingstatemachine import CodingStateMachine +from .mbcharsetprober import MultiByteCharSetProber +from .mbcssm import CP949_SM_MODEL + + +class CP949Prober(MultiByteCharSetProber): + def __init__(self) -> None: + super().__init__() + self.coding_sm = CodingStateMachine(CP949_SM_MODEL) + # NOTE: CP949 is a superset of EUC-KR, so the distribution should be + # not different. + self.distribution_analyzer = EUCKRDistributionAnalysis() + self.reset() + + @property + def charset_name(self) -> str: + return "CP949" + + @property + def language(self) -> str: + return "Korean" diff --git a/shared/package-files/d2/d2353a2e5f2adb0704d55a27b6ebc632116613729aa4b5ea6d9b1e464085990a/blob b/shared/package-files/d2/d2353a2e5f2adb0704d55a27b6ebc632116613729aa4b5ea6d9b1e464085990a/blob new file mode 100644 index 0000000000000000000000000000000000000000..bafc10ffd87db1c995cb7572010c770f7abb63f2 Binary files /dev/null and b/shared/package-files/d2/d2353a2e5f2adb0704d55a27b6ebc632116613729aa4b5ea6d9b1e464085990a/blob differ diff --git a/shared/package-files/d2/d236d5b27184b1e813e686d901418117f22d67024e6944018fc4b633df9ff744/blob b/shared/package-files/d2/d236d5b27184b1e813e686d901418117f22d67024e6944018fc4b633df9ff744/blob new file mode 100644 index 0000000000000000000000000000000000000000..0869f2078bf4f4c3d07247c7e3b48a5390985311 --- /dev/null +++ b/shared/package-files/d2/d236d5b27184b1e813e686d901418117f22d67024e6944018fc4b633df9ff744/blob @@ -0,0 +1,39 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset kok DAYS_OF_WEEK_FULL [list \ + "\u0906\u0926\u093f\u0924\u094d\u092f\u0935\u093e\u0930"\ + "\u0938\u094b\u092e\u0935\u093e\u0930"\ + "\u092e\u0902\u0917\u0933\u093e\u0930"\ + "\u092c\u0941\u0927\u0935\u093e\u0930"\ + "\u0917\u0941\u0930\u0941\u0935\u093e\u0930"\ + "\u0936\u0941\u0915\u094d\u0930\u0935\u093e\u0930"\ + "\u0936\u0928\u093f\u0935\u093e\u0930"] + ::msgcat::mcset kok MONTHS_ABBREV [list \ + "\u091c\u093e\u0928\u0947\u0935\u093e\u0930\u0940"\ + "\u092b\u0947\u092c\u0943\u0935\u093e\u0930\u0940"\ + "\u092e\u093e\u0930\u094d\u091a"\ + "\u090f\u092a\u094d\u0930\u093f\u0932"\ + "\u092e\u0947"\ + "\u091c\u0942\u0928"\ + "\u091c\u0941\u0932\u0948"\ + "\u0913\u0917\u0938\u094d\u091f"\ + "\u0938\u0947\u092a\u094d\u091f\u0947\u0902\u092c\u0930"\ + "\u0913\u0915\u094d\u091f\u094b\u092c\u0930"\ + "\u0928\u094b\u0935\u094d\u0939\u0947\u0902\u092c\u0930"\ + "\u0921\u093f\u0938\u0947\u0902\u092c\u0930"] + ::msgcat::mcset kok MONTHS_FULL [list \ + "\u091c\u093e\u0928\u0947\u0935\u093e\u0930\u0940"\ + "\u092b\u0947\u092c\u094d\u0930\u0941\u0935\u093e\u0930\u0940"\ + "\u092e\u093e\u0930\u094d\u091a"\ + "\u090f\u092a\u094d\u0930\u093f\u0932"\ + "\u092e\u0947"\ + "\u091c\u0942\u0928"\ + "\u091c\u0941\u0932\u0948"\ + "\u0913\u0917\u0938\u094d\u091f"\ + "\u0938\u0947\u092a\u094d\u091f\u0947\u0902\u092c\u0930"\ + "\u0913\u0915\u094d\u091f\u094b\u092c\u0930"\ + "\u0928\u094b\u0935\u094d\u0939\u0947\u0902\u092c\u0930"\ + "\u0921\u093f\u0938\u0947\u0902\u092c\u0930"] + ::msgcat::mcset kok AM "\u0915\u094d\u0930\u093f\u0938\u094d\u0924\u092a\u0942\u0930\u094d\u0935" + ::msgcat::mcset kok PM "\u0915\u094d\u0930\u093f\u0938\u094d\u0924\u0936\u0916\u093e" +} diff --git a/shared/package-files/d2/d23f7d76acba7dd99e8182fa8c231dafc3a1851776ea5500b347d98eb91c7eef/blob b/shared/package-files/d2/d23f7d76acba7dd99e8182fa8c231dafc3a1851776ea5500b347d98eb91c7eef/blob new file mode 100644 index 0000000000000000000000000000000000000000..d0d8b37d13dc942fbce7fe766857ca4d0be99d13 --- /dev/null +++ b/shared/package-files/d2/d23f7d76acba7dd99e8182fa8c231dafc3a1851776ea5500b347d98eb91c7eef/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor slow_conv_transpose3d(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, at::IntArrayRef dilation=1); +TORCH_API at::Tensor slow_conv_transpose3d_symint(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)); +TORCH_API at::Tensor & slow_conv_transpose3d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, at::IntArrayRef dilation=1); +TORCH_API at::Tensor & slow_conv_transpose3d_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef output_padding, at::IntArrayRef dilation, at::Tensor & out); +TORCH_API at::Tensor & slow_conv_transpose3d_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)); +TORCH_API at::Tensor & slow_conv_transpose3d_symint_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef output_padding, c10::SymIntArrayRef dilation, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/d2/d241ae0d7dd4aff429ead04c0564ceecb3d4c735cd180940d9248985d029e035/blob b/shared/package-files/d2/d241ae0d7dd4aff429ead04c0564ceecb3d4c735cd180940d9248985d029e035/blob new file mode 100644 index 0000000000000000000000000000000000000000..8b696772f6ddc86dec7a1740c53ee640aa762b3c --- /dev/null +++ b/shared/package-files/d2/d241ae0d7dd4aff429ead04c0564ceecb3d4c735cd180940d9248985d029e035/blob @@ -0,0 +1,765 @@ +from __future__ import annotations + +from ._dtypes import ( + _boolean_dtypes, + _floating_dtypes, + _real_floating_dtypes, + _complex_floating_dtypes, + _integer_dtypes, + _integer_or_boolean_dtypes, + _real_numeric_dtypes, + _numeric_dtypes, + _result_type, +) +from ._array_object import Array + +import numpy as np + + +def abs(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.abs `. + + See its docstring for more information. + """ + if x.dtype not in _numeric_dtypes: + raise TypeError("Only numeric dtypes are allowed in abs") + return Array._new(np.abs(x._array)) + + +# Note: the function name is different here +def acos(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.arccos `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in acos") + return Array._new(np.arccos(x._array)) + + +# Note: the function name is different here +def acosh(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.arccosh `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in acosh") + return Array._new(np.arccosh(x._array)) + + +def add(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.add `. + + See its docstring for more information. + """ + if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: + raise TypeError("Only numeric dtypes are allowed in add") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.add(x1._array, x2._array)) + + +# Note: the function name is different here +def asin(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.arcsin `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in asin") + return Array._new(np.arcsin(x._array)) + + +# Note: the function name is different here +def asinh(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.arcsinh `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in asinh") + return Array._new(np.arcsinh(x._array)) + + +# Note: the function name is different here +def atan(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.arctan `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in atan") + return Array._new(np.arctan(x._array)) + + +# Note: the function name is different here +def atan2(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.arctan2 `. + + See its docstring for more information. + """ + if x1.dtype not in _real_floating_dtypes or x2.dtype not in _real_floating_dtypes: + raise TypeError("Only real floating-point dtypes are allowed in atan2") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.arctan2(x1._array, x2._array)) + + +# Note: the function name is different here +def atanh(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.arctanh `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in atanh") + return Array._new(np.arctanh(x._array)) + + +def bitwise_and(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.bitwise_and `. + + See its docstring for more information. + """ + if ( + x1.dtype not in _integer_or_boolean_dtypes + or x2.dtype not in _integer_or_boolean_dtypes + ): + raise TypeError("Only integer or boolean dtypes are allowed in bitwise_and") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.bitwise_and(x1._array, x2._array)) + + +# Note: the function name is different here +def bitwise_left_shift(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.left_shift `. + + See its docstring for more information. + """ + if x1.dtype not in _integer_dtypes or x2.dtype not in _integer_dtypes: + raise TypeError("Only integer dtypes are allowed in bitwise_left_shift") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + # Note: bitwise_left_shift is only defined for x2 nonnegative. + if np.any(x2._array < 0): + raise ValueError("bitwise_left_shift(x1, x2) is only defined for x2 >= 0") + return Array._new(np.left_shift(x1._array, x2._array)) + + +# Note: the function name is different here +def bitwise_invert(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.invert `. + + See its docstring for more information. + """ + if x.dtype not in _integer_or_boolean_dtypes: + raise TypeError("Only integer or boolean dtypes are allowed in bitwise_invert") + return Array._new(np.invert(x._array)) + + +def bitwise_or(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.bitwise_or `. + + See its docstring for more information. + """ + if ( + x1.dtype not in _integer_or_boolean_dtypes + or x2.dtype not in _integer_or_boolean_dtypes + ): + raise TypeError("Only integer or boolean dtypes are allowed in bitwise_or") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.bitwise_or(x1._array, x2._array)) + + +# Note: the function name is different here +def bitwise_right_shift(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.right_shift `. + + See its docstring for more information. + """ + if x1.dtype not in _integer_dtypes or x2.dtype not in _integer_dtypes: + raise TypeError("Only integer dtypes are allowed in bitwise_right_shift") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + # Note: bitwise_right_shift is only defined for x2 nonnegative. + if np.any(x2._array < 0): + raise ValueError("bitwise_right_shift(x1, x2) is only defined for x2 >= 0") + return Array._new(np.right_shift(x1._array, x2._array)) + + +def bitwise_xor(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.bitwise_xor `. + + See its docstring for more information. + """ + if ( + x1.dtype not in _integer_or_boolean_dtypes + or x2.dtype not in _integer_or_boolean_dtypes + ): + raise TypeError("Only integer or boolean dtypes are allowed in bitwise_xor") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.bitwise_xor(x1._array, x2._array)) + + +def ceil(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.ceil `. + + See its docstring for more information. + """ + if x.dtype not in _real_numeric_dtypes: + raise TypeError("Only real numeric dtypes are allowed in ceil") + if x.dtype in _integer_dtypes: + # Note: The return dtype of ceil is the same as the input + return x + return Array._new(np.ceil(x._array)) + + +def conj(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.conj `. + + See its docstring for more information. + """ + if x.dtype not in _complex_floating_dtypes: + raise TypeError("Only complex floating-point dtypes are allowed in conj") + return Array._new(np.conj(x)) + + +def cos(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.cos `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in cos") + return Array._new(np.cos(x._array)) + + +def cosh(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.cosh `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in cosh") + return Array._new(np.cosh(x._array)) + + +def divide(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.divide `. + + See its docstring for more information. + """ + if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in divide") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.divide(x1._array, x2._array)) + + +def equal(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.equal `. + + See its docstring for more information. + """ + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.equal(x1._array, x2._array)) + + +def exp(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.exp `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in exp") + return Array._new(np.exp(x._array)) + + +def expm1(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.expm1 `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in expm1") + return Array._new(np.expm1(x._array)) + + +def floor(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.floor `. + + See its docstring for more information. + """ + if x.dtype not in _real_numeric_dtypes: + raise TypeError("Only real numeric dtypes are allowed in floor") + if x.dtype in _integer_dtypes: + # Note: The return dtype of floor is the same as the input + return x + return Array._new(np.floor(x._array)) + + +def floor_divide(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.floor_divide `. + + See its docstring for more information. + """ + if x1.dtype not in _real_numeric_dtypes or x2.dtype not in _real_numeric_dtypes: + raise TypeError("Only real numeric dtypes are allowed in floor_divide") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.floor_divide(x1._array, x2._array)) + + +def greater(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.greater `. + + See its docstring for more information. + """ + if x1.dtype not in _real_numeric_dtypes or x2.dtype not in _real_numeric_dtypes: + raise TypeError("Only real numeric dtypes are allowed in greater") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.greater(x1._array, x2._array)) + + +def greater_equal(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.greater_equal `. + + See its docstring for more information. + """ + if x1.dtype not in _real_numeric_dtypes or x2.dtype not in _real_numeric_dtypes: + raise TypeError("Only real numeric dtypes are allowed in greater_equal") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.greater_equal(x1._array, x2._array)) + + +def imag(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.imag `. + + See its docstring for more information. + """ + if x.dtype not in _complex_floating_dtypes: + raise TypeError("Only complex floating-point dtypes are allowed in imag") + return Array._new(np.imag(x)) + + +def isfinite(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.isfinite `. + + See its docstring for more information. + """ + if x.dtype not in _numeric_dtypes: + raise TypeError("Only numeric dtypes are allowed in isfinite") + return Array._new(np.isfinite(x._array)) + + +def isinf(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.isinf `. + + See its docstring for more information. + """ + if x.dtype not in _numeric_dtypes: + raise TypeError("Only numeric dtypes are allowed in isinf") + return Array._new(np.isinf(x._array)) + + +def isnan(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.isnan `. + + See its docstring for more information. + """ + if x.dtype not in _numeric_dtypes: + raise TypeError("Only numeric dtypes are allowed in isnan") + return Array._new(np.isnan(x._array)) + + +def less(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.less `. + + See its docstring for more information. + """ + if x1.dtype not in _real_numeric_dtypes or x2.dtype not in _real_numeric_dtypes: + raise TypeError("Only real numeric dtypes are allowed in less") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.less(x1._array, x2._array)) + + +def less_equal(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.less_equal `. + + See its docstring for more information. + """ + if x1.dtype not in _real_numeric_dtypes or x2.dtype not in _real_numeric_dtypes: + raise TypeError("Only real numeric dtypes are allowed in less_equal") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.less_equal(x1._array, x2._array)) + + +def log(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.log `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in log") + return Array._new(np.log(x._array)) + + +def log1p(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.log1p `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in log1p") + return Array._new(np.log1p(x._array)) + + +def log2(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.log2 `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in log2") + return Array._new(np.log2(x._array)) + + +def log10(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.log10 `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in log10") + return Array._new(np.log10(x._array)) + + +def logaddexp(x1: Array, x2: Array) -> Array: + """ + Array API compatible wrapper for :py:func:`np.logaddexp `. + + See its docstring for more information. + """ + if x1.dtype not in _real_floating_dtypes or x2.dtype not in _real_floating_dtypes: + raise TypeError("Only real floating-point dtypes are allowed in logaddexp") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.logaddexp(x1._array, x2._array)) + + +def logical_and(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.logical_and `. + + See its docstring for more information. + """ + if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes: + raise TypeError("Only boolean dtypes are allowed in logical_and") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.logical_and(x1._array, x2._array)) + + +def logical_not(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.logical_not `. + + See its docstring for more information. + """ + if x.dtype not in _boolean_dtypes: + raise TypeError("Only boolean dtypes are allowed in logical_not") + return Array._new(np.logical_not(x._array)) + + +def logical_or(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.logical_or `. + + See its docstring for more information. + """ + if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes: + raise TypeError("Only boolean dtypes are allowed in logical_or") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.logical_or(x1._array, x2._array)) + + +def logical_xor(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.logical_xor `. + + See its docstring for more information. + """ + if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes: + raise TypeError("Only boolean dtypes are allowed in logical_xor") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.logical_xor(x1._array, x2._array)) + + +def multiply(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.multiply `. + + See its docstring for more information. + """ + if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: + raise TypeError("Only numeric dtypes are allowed in multiply") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.multiply(x1._array, x2._array)) + + +def negative(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.negative `. + + See its docstring for more information. + """ + if x.dtype not in _numeric_dtypes: + raise TypeError("Only numeric dtypes are allowed in negative") + return Array._new(np.negative(x._array)) + + +def not_equal(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.not_equal `. + + See its docstring for more information. + """ + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.not_equal(x1._array, x2._array)) + + +def positive(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.positive `. + + See its docstring for more information. + """ + if x.dtype not in _numeric_dtypes: + raise TypeError("Only numeric dtypes are allowed in positive") + return Array._new(np.positive(x._array)) + + +# Note: the function name is different here +def pow(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.power `. + + See its docstring for more information. + """ + if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: + raise TypeError("Only numeric dtypes are allowed in pow") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.power(x1._array, x2._array)) + + +def real(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.real `. + + See its docstring for more information. + """ + if x.dtype not in _complex_floating_dtypes: + raise TypeError("Only complex floating-point dtypes are allowed in real") + return Array._new(np.real(x)) + + +def remainder(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.remainder `. + + See its docstring for more information. + """ + if x1.dtype not in _real_numeric_dtypes or x2.dtype not in _real_numeric_dtypes: + raise TypeError("Only real numeric dtypes are allowed in remainder") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.remainder(x1._array, x2._array)) + + +def round(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.round `. + + See its docstring for more information. + """ + if x.dtype not in _numeric_dtypes: + raise TypeError("Only numeric dtypes are allowed in round") + return Array._new(np.round(x._array)) + + +def sign(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.sign `. + + See its docstring for more information. + """ + if x.dtype not in _numeric_dtypes: + raise TypeError("Only numeric dtypes are allowed in sign") + return Array._new(np.sign(x._array)) + + +def sin(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.sin `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in sin") + return Array._new(np.sin(x._array)) + + +def sinh(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.sinh `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in sinh") + return Array._new(np.sinh(x._array)) + + +def square(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.square `. + + See its docstring for more information. + """ + if x.dtype not in _numeric_dtypes: + raise TypeError("Only numeric dtypes are allowed in square") + return Array._new(np.square(x._array)) + + +def sqrt(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.sqrt `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in sqrt") + return Array._new(np.sqrt(x._array)) + + +def subtract(x1: Array, x2: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.subtract `. + + See its docstring for more information. + """ + if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: + raise TypeError("Only numeric dtypes are allowed in subtract") + # Call result type here just to raise on disallowed type combinations + _result_type(x1.dtype, x2.dtype) + x1, x2 = Array._normalize_two_args(x1, x2) + return Array._new(np.subtract(x1._array, x2._array)) + + +def tan(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.tan `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in tan") + return Array._new(np.tan(x._array)) + + +def tanh(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.tanh `. + + See its docstring for more information. + """ + if x.dtype not in _floating_dtypes: + raise TypeError("Only floating-point dtypes are allowed in tanh") + return Array._new(np.tanh(x._array)) + + +def trunc(x: Array, /) -> Array: + """ + Array API compatible wrapper for :py:func:`np.trunc `. + + See its docstring for more information. + """ + if x.dtype not in _real_numeric_dtypes: + raise TypeError("Only real numeric dtypes are allowed in trunc") + if x.dtype in _integer_dtypes: + # Note: The return dtype of trunc is the same as the input + return x + return Array._new(np.trunc(x._array)) diff --git a/shared/package-files/d2/d242222a47806913ae1e075604755016bcc9d997e80e0ca609e84bfe42571d80/blob b/shared/package-files/d2/d242222a47806913ae1e075604755016bcc9d997e80e0ca609e84bfe42571d80/blob new file mode 100644 index 0000000000000000000000000000000000000000..e8fe7a2f67d7d9648e75b82d5f0b5cf2bf7a4868 --- /dev/null +++ b/shared/package-files/d2/d242222a47806913ae1e075604755016bcc9d997e80e0ca609e84bfe42571d80/blob @@ -0,0 +1,227 @@ +import requests + +from ..spec import AbstractFileSystem +from ..utils import infer_storage_options +from .memory import MemoryFile + +# TODO: add GIST backend, would be very similar + + +class GithubFileSystem(AbstractFileSystem): + """Interface to files in github + + An instance of this class provides the files residing within a remote github + repository. You may specify a point in the repos history, by SHA, branch + or tag (default is current master). + + Given that code files tend to be small, and that github does not support + retrieving partial content, we always fetch whole files. + + When using fsspec.open, allows URIs of the form: + + - "github://path/file", in which case you must specify org, repo and + may specify sha in the extra args + - 'github://org:repo@/precip/catalog.yml', where the org and repo are + part of the URI + - 'github://org:repo@sha/precip/catalog.yml', where the sha is also included + + ``sha`` can be the full or abbreviated hex of the commit you want to fetch + from, or a branch or tag name (so long as it doesn't contain special characters + like "/", "?", which would have to be HTTP-encoded). + + For authorised access, you must provide username and token, which can be made + at https://github.com/settings/tokens + """ + + url = "https://api.github.com/repos/{org}/{repo}/git/trees/{sha}" + rurl = "https://raw.githubusercontent.com/{org}/{repo}/{sha}/{path}" + protocol = "github" + timeout = (60, 60) # connect, read timeouts + + def __init__( + self, org, repo, sha=None, username=None, token=None, timeout=None, **kwargs + ): + super().__init__(**kwargs) + self.org = org + self.repo = repo + if (username is None) ^ (token is None): + raise ValueError("Auth required both username and token") + self.username = username + self.token = token + if timeout is not None: + self.timeout = timeout + if sha is None: + # look up default branch (not necessarily "master") + u = "https://api.github.com/repos/{org}/{repo}" + r = requests.get( + u.format(org=org, repo=repo), timeout=self.timeout, **self.kw + ) + r.raise_for_status() + sha = r.json()["default_branch"] + + self.root = sha + self.ls("") + + @property + def kw(self): + if self.username: + return {"auth": (self.username, self.token)} + return {} + + @classmethod + def repos(cls, org_or_user, is_org=True): + """List repo names for given org or user + + This may become the top level of the FS + + Parameters + ---------- + org_or_user: str + Name of the github org or user to query + is_org: bool (default True) + Whether the name is an organisation (True) or user (False) + + Returns + ------- + List of string + """ + r = requests.get( + f"https://api.github.com/{['users', 'orgs'][is_org]}/{org_or_user}/repos", + timeout=cls.timeout, + ) + r.raise_for_status() + return [repo["name"] for repo in r.json()] + + @property + def tags(self): + """Names of tags in the repo""" + r = requests.get( + f"https://api.github.com/repos/{self.org}/{self.repo}/tags", + timeout=self.timeout, + **self.kw, + ) + r.raise_for_status() + return [t["name"] for t in r.json()] + + @property + def branches(self): + """Names of branches in the repo""" + r = requests.get( + f"https://api.github.com/repos/{self.org}/{self.repo}/branches", + timeout=self.timeout, + **self.kw, + ) + r.raise_for_status() + return [t["name"] for t in r.json()] + + @property + def refs(self): + """Named references, tags and branches""" + return {"tags": self.tags, "branches": self.branches} + + def ls(self, path, detail=False, sha=None, _sha=None, **kwargs): + """List files at given path + + Parameters + ---------- + path: str + Location to list, relative to repo root + detail: bool + If True, returns list of dicts, one per file; if False, returns + list of full filenames only + sha: str (optional) + List at the given point in the repo history, branch or tag name or commit + SHA + _sha: str (optional) + List this specific tree object (used internally to descend into trees) + """ + path = self._strip_protocol(path) + if path == "": + _sha = sha or self.root + if _sha is None: + parts = path.rstrip("/").split("/") + so_far = "" + _sha = sha or self.root + for part in parts: + out = self.ls(so_far, True, sha=sha, _sha=_sha) + so_far += "/" + part if so_far else part + out = [o for o in out if o["name"] == so_far] + if not out: + raise FileNotFoundError(path) + out = out[0] + if out["type"] == "file": + if detail: + return [out] + else: + return path + _sha = out["sha"] + if path not in self.dircache or sha not in [self.root, None]: + r = requests.get( + self.url.format(org=self.org, repo=self.repo, sha=_sha), + timeout=self.timeout, + **self.kw, + ) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + types = {"blob": "file", "tree": "directory"} + out = [ + { + "name": path + "/" + f["path"] if path else f["path"], + "mode": f["mode"], + "type": types[f["type"]], + "size": f.get("size", 0), + "sha": f["sha"], + } + for f in r.json()["tree"] + if f["type"] in types + ] + if sha in [self.root, None]: + self.dircache[path] = out + else: + out = self.dircache[path] + if detail: + return out + else: + return sorted([f["name"] for f in out]) + + def invalidate_cache(self, path=None): + self.dircache.clear() + + @classmethod + def _strip_protocol(cls, path): + opts = infer_storage_options(path) + if "username" not in opts: + return super()._strip_protocol(path) + return opts["path"].lstrip("/") + + @staticmethod + def _get_kwargs_from_urls(path): + opts = infer_storage_options(path) + if "username" not in opts: + return {} + out = {"org": opts["username"], "repo": opts["password"]} + if opts["host"]: + out["sha"] = opts["host"] + return out + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + sha=None, + **kwargs, + ): + if mode != "rb": + raise NotImplementedError + url = self.rurl.format( + org=self.org, repo=self.repo, path=path, sha=sha or self.root + ) + r = requests.get(url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + return MemoryFile(None, None, r.content) diff --git a/shared/package-files/d2/d242e80f0ac08d964f650692b462bb5f6b0b9ed6661e4fbfc2b6563aecdd221b/blob b/shared/package-files/d2/d242e80f0ac08d964f650692b462bb5f6b0b9ed6661e4fbfc2b6563aecdd221b/blob new file mode 100644 index 0000000000000000000000000000000000000000..ee16edb36af37b6e6755ffa831c716483bbd3334 Binary files /dev/null and b/shared/package-files/d2/d242e80f0ac08d964f650692b462bb5f6b0b9ed6661e4fbfc2b6563aecdd221b/blob differ diff --git a/shared/package-files/d2/d242f1748beef82ea471b49f05bdb223d6256f82f73026744f9a257a21c442e4/blob b/shared/package-files/d2/d242f1748beef82ea471b49f05bdb223d6256f82f73026744f9a257a21c442e4/blob new file mode 100644 index 0000000000000000000000000000000000000000..37ab82dd8fc321fe560b87ed10f62fcfba36b277 --- /dev/null +++ b/shared/package-files/d2/d242f1748beef82ea471b49f05bdb223d6256f82f73026744f9a257a21c442e4/blob @@ -0,0 +1,44 @@ +""" +Tests to ensure that typeguard is working as expected. +This mostly contains negative tests as proof that typeguard can catch errors. +""" +import unittest +from numba.tests.support import TestCase, skip_unless_typeguard + + +def guard_args(val: int): + return + + +def guard_ret(val) -> int: + return val + + +@skip_unless_typeguard +class TestTypeGuard(TestCase): + + def setUp(self): + super().setUp() + import typeguard + # This is a test class invariant but the Numba multiprocesses test + # runner doesn't respect `setUpClass` so just use `setUp`. + # typeguard 3+ uses typeguard.TypeCheckError, 2.x uses TypeError + self._exception_type = getattr(typeguard, 'TypeCheckError', TypeError) + + def test_check_args(self): + with self.assertRaises(self._exception_type): + guard_args(float(1.2)) + + def test_check_ret(self): + with self.assertRaises(self._exception_type): + guard_ret(float(1.2)) + + def test_check_does_not_work_with_inner_func(self): + def guard(val: int) -> int: + return + + guard(float(1.2)) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/d2/d242fc6edf27d1bb18ab4f21eeb7579f4dbe2e4070068299004200bbf078b1c6/blob b/shared/package-files/d2/d242fc6edf27d1bb18ab4f21eeb7579f4dbe2e4070068299004200bbf078b1c6/blob new file mode 100644 index 0000000000000000000000000000000000000000..2b44c593a6f7027267c1f4b5603c8f4122181fa3 Binary files /dev/null and b/shared/package-files/d2/d242fc6edf27d1bb18ab4f21eeb7579f4dbe2e4070068299004200bbf078b1c6/blob differ diff --git a/shared/package-files/d2/d244822c6162eec804c0b7fa85fd4b4521c24602cd00d43948c8a087fcf1bf9b/blob b/shared/package-files/d2/d244822c6162eec804c0b7fa85fd4b4521c24602cd00d43948c8a087fcf1bf9b/blob new file mode 100644 index 0000000000000000000000000000000000000000..789f393e28c3961261f0f53ef26ec21335b28f71 --- /dev/null +++ b/shared/package-files/d2/d244822c6162eec804c0b7fa85fd4b4521c24602cd00d43948c8a087fcf1bf9b/blob @@ -0,0 +1,214 @@ +import math + +import numpy as np +import pytest +from numpy.testing import suppress_warnings + +from scipy.stats import variation +from scipy._lib._util import AxisError +from scipy.conftest import array_api_compatible +from scipy._lib._array_api import is_numpy +from scipy._lib._array_api_no_0d import xp_assert_equal, xp_assert_close +from scipy.stats._axis_nan_policy import (too_small_nd_omit, too_small_nd_not_omit, + SmallSampleWarning) + +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")] +skip_xp_backends = pytest.mark.skip_xp_backends + + +class TestVariation: + """ + Test class for scipy.stats.variation + """ + + def test_ddof(self, xp): + x = xp.arange(9.0) + xp_assert_close(variation(x, ddof=1), xp.asarray(math.sqrt(60/8)/4)) + + @pytest.mark.parametrize('sgn', [1, -1]) + def test_sign(self, sgn, xp): + x = xp.asarray([1., 2., 3., 4., 5.]) + v = variation(sgn*x) + expected = xp.asarray(sgn*math.sqrt(2)/3) + xp_assert_close(v, expected, rtol=1e-10) + + def test_scalar(self, xp): + # A scalar is treated like a 1-d sequence with length 1. + xp_assert_equal(variation(4.0), 0.0) + + @pytest.mark.parametrize('nan_policy, expected', + [('propagate', np.nan), + ('omit', np.sqrt(20/3)/4)]) + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + def test_variation_nan(self, nan_policy, expected, xp): + x = xp.arange(10.) + x[9] = xp.nan + xp_assert_close(variation(x, nan_policy=nan_policy), expected) + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + def test_nan_policy_raise(self, xp): + x = xp.asarray([1.0, 2.0, xp.nan, 3.0]) + with pytest.raises(ValueError, match='input contains nan'): + variation(x, nan_policy='raise') + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + def test_bad_nan_policy(self, xp): + with pytest.raises(ValueError, match='must be one of'): + variation([1, 2, 3], nan_policy='foobar') + + @skip_xp_backends(np_only=True, + reason='`keepdims` only supports NumPy backend') + def test_keepdims(self, xp): + x = xp.reshape(xp.arange(10), (2, 5)) + y = variation(x, axis=1, keepdims=True) + expected = np.array([[np.sqrt(2)/2], + [np.sqrt(2)/7]]) + xp_assert_close(y, expected) + + @skip_xp_backends(np_only=True, + reason='`keepdims` only supports NumPy backend') + @pytest.mark.parametrize('axis, expected', + [(0, np.empty((1, 0))), + (1, np.full((5, 1), fill_value=np.nan))]) + def test_keepdims_size0(self, axis, expected, xp): + x = xp.zeros((5, 0)) + if axis == 1: + with pytest.warns(SmallSampleWarning, match=too_small_nd_not_omit): + y = variation(x, axis=axis, keepdims=True) + else: + y = variation(x, axis=axis, keepdims=True) + xp_assert_equal(y, expected) + + @skip_xp_backends(np_only=True, + reason='`keepdims` only supports NumPy backend') + @pytest.mark.parametrize('incr, expected_fill', [(0, np.inf), (1, np.nan)]) + def test_keepdims_and_ddof_eq_len_plus_incr(self, incr, expected_fill, xp): + x = xp.asarray([[1, 1, 2, 2], [1, 2, 3, 3]]) + y = variation(x, axis=1, ddof=x.shape[1] + incr, keepdims=True) + xp_assert_equal(y, xp.full((2, 1), fill_value=expected_fill)) + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + def test_propagate_nan(self, xp): + # Check that the shape of the result is the same for inputs + # with and without nans, cf gh-5817 + a = xp.reshape(xp.arange(8, dtype=float), (2, -1)) + a[1, 0] = xp.nan + v = variation(a, axis=1, nan_policy="propagate") + xp_assert_close(v, [math.sqrt(5/4)/1.5, xp.nan], atol=1e-15) + + @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend') + def test_axis_none(self, xp): + # Check that `variation` computes the result on the flattened + # input when axis is None. + y = variation([[0, 1], [2, 3]], axis=None) + xp_assert_close(y, math.sqrt(5/4)/1.5) + + def test_bad_axis(self, xp): + # Check that an invalid axis raises np.exceptions.AxisError. + x = xp.asarray([[1, 2, 3], [4, 5, 6]]) + with pytest.raises((AxisError, IndexError)): + variation(x, axis=10) + + def test_mean_zero(self, xp): + # Check that `variation` returns inf for a sequence that is not + # identically zero but whose mean is zero. + x = xp.asarray([10., -3., 1., -4., -4.]) + y = variation(x) + xp_assert_equal(y, xp.asarray(xp.inf)) + + x2 = xp.stack([x, -10.*x]) + y2 = variation(x2, axis=1) + xp_assert_equal(y2, xp.asarray([xp.inf, xp.inf])) + + @pytest.mark.parametrize('x', [[0.]*5, [1, 2, np.inf, 9]]) + def test_return_nan(self, x, xp): + x = xp.asarray(x) + # Test some cases where `variation` returns nan. + y = variation(x) + xp_assert_equal(y, xp.asarray(xp.nan, dtype=x.dtype)) + + @pytest.mark.parametrize('axis, expected', + [(0, []), (1, [np.nan]*3), (None, np.nan)]) + def test_2d_size_zero_with_axis(self, axis, expected, xp): + x = xp.empty((3, 0)) + with suppress_warnings() as sup: + # torch + sup.filter(UserWarning, "std*") + if axis != 0: + if is_numpy(xp): + with pytest.warns(SmallSampleWarning, match="See documentation..."): + y = variation(x, axis=axis) + else: + y = variation(x, axis=axis) + else: + y = variation(x, axis=axis) + xp_assert_equal(y, xp.asarray(expected)) + + def test_neg_inf(self, xp): + # Edge case that produces -inf: ddof equals the number of non-nan + # values, the values are not constant, and the mean is negative. + x1 = xp.asarray([-3., -5.]) + xp_assert_equal(variation(x1, ddof=2), xp.asarray(-xp.inf)) + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + def test_neg_inf_nan(self, xp): + x2 = xp.asarray([[xp.nan, 1, -10, xp.nan], + [-20, -3, xp.nan, xp.nan]]) + xp_assert_equal(variation(x2, axis=1, ddof=2, nan_policy='omit'), + [-xp.inf, -xp.inf]) + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + @pytest.mark.parametrize("nan_policy", ['propagate', 'omit']) + def test_combined_edge_cases(self, nan_policy, xp): + x = xp.array([[0, 10, xp.nan, 1], + [0, -5, xp.nan, 2], + [0, -5, xp.nan, 3]]) + if nan_policy == 'omit': + with pytest.warns(SmallSampleWarning, match=too_small_nd_omit): + y = variation(x, axis=0, nan_policy=nan_policy) + else: + y = variation(x, axis=0, nan_policy=nan_policy) + xp_assert_close(y, [xp.nan, xp.inf, xp.nan, math.sqrt(2/3)/2]) + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + @pytest.mark.parametrize( + 'ddof, expected', + [(0, [np.sqrt(1/6), np.sqrt(5/8), np.inf, 0, np.nan, 0.0, np.nan]), + (1, [0.5, np.sqrt(5/6), np.inf, 0, np.nan, 0, np.nan]), + (2, [np.sqrt(0.5), np.sqrt(5/4), np.inf, np.nan, np.nan, 0, np.nan])] + ) + def test_more_nan_policy_omit_tests(self, ddof, expected, xp): + # The slightly strange formatting in the follow array is my attempt to + # maintain a clean tabular arrangement of the data while satisfying + # the demands of pycodestyle. Currently, E201 and E241 are not + # disabled by the `noqa` annotation. + nan = xp.nan + x = xp.asarray([[1.0, 2.0, nan, 3.0], + [0.0, 4.0, 3.0, 1.0], + [nan, -.5, 0.5, nan], + [nan, 9.0, 9.0, nan], + [nan, nan, nan, nan], + [3.0, 3.0, 3.0, 3.0], + [0.0, 0.0, 0.0, 0.0]]) + with pytest.warns(SmallSampleWarning, match=too_small_nd_omit): + v = variation(x, axis=1, ddof=ddof, nan_policy='omit') + xp_assert_close(v, expected) + + @skip_xp_backends(np_only=True, + reason='`nan_policy` only supports NumPy backend') + def test_variation_ddof(self, xp): + # test variation with delta degrees of freedom + # regression test for gh-13341 + a = xp.asarray([1., 2., 3., 4., 5.]) + nan_a = xp.asarray([1, 2, 3, xp.nan, 4, 5, xp.nan]) + y = variation(a, ddof=1) + nan_y = variation(nan_a, nan_policy="omit", ddof=1) + xp_assert_close(y, math.sqrt(5/2)/3) + assert y == nan_y diff --git a/shared/package-files/d2/d245b496254c79a7648d7d197117cca6d2857a7d3b1b0ea0cb0d551d3e4a2307/blob b/shared/package-files/d2/d245b496254c79a7648d7d197117cca6d2857a7d3b1b0ea0cb0d551d3e4a2307/blob new file mode 100644 index 0000000000000000000000000000000000000000..0ddc7367cc608dac2cfb408a08c8b442278a8207 --- /dev/null +++ b/shared/package-files/d2/d245b496254c79a7648d7d197117cca6d2857a7d3b1b0ea0cb0d551d3e4a2307/blob @@ -0,0 +1,77 @@ +"""distutils.command.install_egg_info + +Implements the Distutils 'install_egg_info' command, for installing +a package's PKG-INFO metadata.""" + + +from distutils.cmd import Command +from distutils import log, dir_util +import os, sys, re + +class install_egg_info(Command): + """Install an .egg-info file for the package""" + + description = "Install package's PKG-INFO metadata as an .egg-info file" + user_options = [ + ('install-dir=', 'd', "directory to install to"), + ] + + def initialize_options(self): + self.install_dir = None + + def finalize_options(self): + self.set_undefined_options('install_lib',('install_dir','install_dir')) + basename = "%s-%s-py%d.%d.egg-info" % ( + to_filename(safe_name(self.distribution.get_name())), + to_filename(safe_version(self.distribution.get_version())), + *sys.version_info[:2] + ) + self.target = os.path.join(self.install_dir, basename) + self.outputs = [self.target] + + def run(self): + target = self.target + if os.path.isdir(target) and not os.path.islink(target): + dir_util.remove_tree(target, dry_run=self.dry_run) + elif os.path.exists(target): + self.execute(os.unlink,(self.target,),"Removing "+target) + elif not os.path.isdir(self.install_dir): + self.execute(os.makedirs, (self.install_dir,), + "Creating "+self.install_dir) + log.info("Writing %s", target) + if not self.dry_run: + with open(target, 'w', encoding='UTF-8') as f: + self.distribution.metadata.write_pkg_file(f) + + def get_outputs(self): + return self.outputs + + +# The following routines are taken from setuptools' pkg_resources module and +# can be replaced by importing them from pkg_resources once it is included +# in the stdlib. + +def safe_name(name): + """Convert an arbitrary string to a standard distribution name + + Any runs of non-alphanumeric/. characters are replaced with a single '-'. + """ + return re.sub('[^A-Za-z0-9.]+', '-', name) + + +def safe_version(version): + """Convert an arbitrary string to a standard version string + + Spaces become dots, and all other non-alphanumeric characters become + dashes, with runs of multiple dashes condensed to a single dash. + """ + version = version.replace(' ','.') + return re.sub('[^A-Za-z0-9.]+', '-', version) + + +def to_filename(name): + """Convert a project or version name to its filename-escaped form + + Any '-' characters are currently replaced with '_'. + """ + return name.replace('-','_') diff --git a/shared/package-files/d2/d245d05a8eb1d43d8683df29274c1a8620c7b8904636fb1a759c1d16d38ce581/blob b/shared/package-files/d2/d245d05a8eb1d43d8683df29274c1a8620c7b8904636fb1a759c1d16d38ce581/blob new file mode 100644 index 0000000000000000000000000000000000000000..a664cb3fbbdb0d55cea3763458707be5d5671e38 --- /dev/null +++ b/shared/package-files/d2/d245d05a8eb1d43d8683df29274c1a8620c7b8904636fb1a759c1d16d38ce581/blob @@ -0,0 +1,50 @@ +import warnings +from typing import Any, Dict, Union + +import numpy as np +import PIL.Image +import torch +from torchvision.transforms import functional as _F + +from torchvision.transforms.v2 import Transform + + +class ToTensor(Transform): + """[DEPRECATED] Use ``v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])`` instead. + + Convert a PIL Image or ndarray to tensor and scale the values accordingly. + + .. warning:: + :class:`v2.ToTensor` is deprecated and will be removed in a future release. + Please use instead ``v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])``. + Output is equivalent up to float precision. + + This transform does not support torchscript. + + + Converts a PIL Image or numpy.ndarray (H x W x C) in the range + [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] + if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1) + or if the numpy.ndarray has dtype = np.uint8 + + In the other cases, tensors are returned without scaling. + + .. note:: + Because the input image is scaled to [0.0, 1.0], this transformation should not be used when + transforming target image masks. See the `references`_ for implementing the transforms for image masks. + + .. _references: https://github.com/pytorch/vision/tree/main/references/segmentation + """ + + _transformed_types = (PIL.Image.Image, np.ndarray) + + def __init__(self) -> None: + warnings.warn( + "The transform `ToTensor()` is deprecated and will be removed in a future release. " + "Instead, please use `v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])`." + "Output is equivalent up to float precision." + ) + super().__init__() + + def _transform(self, inpt: Union[PIL.Image.Image, np.ndarray], params: Dict[str, Any]) -> torch.Tensor: + return _F.to_tensor(inpt) diff --git a/shared/package-files/d2/d24cfbd711890ca8099bef5d5ebe184cc91f6873e8c025089a92bdc7e9f754d5/blob b/shared/package-files/d2/d24cfbd711890ca8099bef5d5ebe184cc91f6873e8c025089a92bdc7e9f754d5/blob new file mode 100644 index 0000000000000000000000000000000000000000..0666884676b367dd3fa4b49535cfbaee72b2eac9 --- /dev/null +++ b/shared/package-files/d2/d24cfbd711890ca8099bef5d5ebe184cc91f6873e8c025089a92bdc7e9f754d5/blob @@ -0,0 +1,611 @@ +r""" +Construct transitive subgroups of symmetric groups, useful in Galois theory. + +Besides constructing instances of the :py:class:`~.PermutationGroup` class to +represent the transitive subgroups of $S_n$ for small $n$, this module provides +*names* for these groups. + +In some applications, it may be preferable to know the name of a group, +rather than receive an instance of the :py:class:`~.PermutationGroup` +class, and then have to do extra work to determine which group it is, by +checking various properties. + +Names are instances of ``Enum`` classes defined in this module. With a name in +hand, the name's ``get_perm_group`` method can then be used to retrieve a +:py:class:`~.PermutationGroup`. + +The names used for groups in this module are taken from [1]. + +References +========== + +.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*. + +""" + +from collections import defaultdict +from enum import Enum +import itertools + +from sympy.combinatorics.named_groups import ( + SymmetricGroup, AlternatingGroup, CyclicGroup, DihedralGroup, + set_symmetric_group_properties, set_alternating_group_properties, +) +from sympy.combinatorics.perm_groups import PermutationGroup +from sympy.combinatorics.permutations import Permutation + + +class S1TransitiveSubgroups(Enum): + """ + Names for the transitive subgroups of S1. + """ + S1 = "S1" + + def get_perm_group(self): + return SymmetricGroup(1) + + +class S2TransitiveSubgroups(Enum): + """ + Names for the transitive subgroups of S2. + """ + S2 = "S2" + + def get_perm_group(self): + return SymmetricGroup(2) + + +class S3TransitiveSubgroups(Enum): + """ + Names for the transitive subgroups of S3. + """ + A3 = "A3" + S3 = "S3" + + def get_perm_group(self): + if self == S3TransitiveSubgroups.A3: + return AlternatingGroup(3) + elif self == S3TransitiveSubgroups.S3: + return SymmetricGroup(3) + + +class S4TransitiveSubgroups(Enum): + """ + Names for the transitive subgroups of S4. + """ + C4 = "C4" + V = "V" + D4 = "D4" + A4 = "A4" + S4 = "S4" + + def get_perm_group(self): + if self == S4TransitiveSubgroups.C4: + return CyclicGroup(4) + elif self == S4TransitiveSubgroups.V: + return four_group() + elif self == S4TransitiveSubgroups.D4: + return DihedralGroup(4) + elif self == S4TransitiveSubgroups.A4: + return AlternatingGroup(4) + elif self == S4TransitiveSubgroups.S4: + return SymmetricGroup(4) + + +class S5TransitiveSubgroups(Enum): + """ + Names for the transitive subgroups of S5. + """ + C5 = "C5" + D5 = "D5" + M20 = "M20" + A5 = "A5" + S5 = "S5" + + def get_perm_group(self): + if self == S5TransitiveSubgroups.C5: + return CyclicGroup(5) + elif self == S5TransitiveSubgroups.D5: + return DihedralGroup(5) + elif self == S5TransitiveSubgroups.M20: + return M20() + elif self == S5TransitiveSubgroups.A5: + return AlternatingGroup(5) + elif self == S5TransitiveSubgroups.S5: + return SymmetricGroup(5) + + +class S6TransitiveSubgroups(Enum): + """ + Names for the transitive subgroups of S6. + """ + C6 = "C6" + S3 = "S3" + D6 = "D6" + A4 = "A4" + G18 = "G18" + A4xC2 = "A4 x C2" + S4m = "S4-" + S4p = "S4+" + G36m = "G36-" + G36p = "G36+" + S4xC2 = "S4 x C2" + PSL2F5 = "PSL2(F5)" + G72 = "G72" + PGL2F5 = "PGL2(F5)" + A6 = "A6" + S6 = "S6" + + def get_perm_group(self): + if self == S6TransitiveSubgroups.C6: + return CyclicGroup(6) + elif self == S6TransitiveSubgroups.S3: + return S3_in_S6() + elif self == S6TransitiveSubgroups.D6: + return DihedralGroup(6) + elif self == S6TransitiveSubgroups.A4: + return A4_in_S6() + elif self == S6TransitiveSubgroups.G18: + return G18() + elif self == S6TransitiveSubgroups.A4xC2: + return A4xC2() + elif self == S6TransitiveSubgroups.S4m: + return S4m() + elif self == S6TransitiveSubgroups.S4p: + return S4p() + elif self == S6TransitiveSubgroups.G36m: + return G36m() + elif self == S6TransitiveSubgroups.G36p: + return G36p() + elif self == S6TransitiveSubgroups.S4xC2: + return S4xC2() + elif self == S6TransitiveSubgroups.PSL2F5: + return PSL2F5() + elif self == S6TransitiveSubgroups.G72: + return G72() + elif self == S6TransitiveSubgroups.PGL2F5: + return PGL2F5() + elif self == S6TransitiveSubgroups.A6: + return AlternatingGroup(6) + elif self == S6TransitiveSubgroups.S6: + return SymmetricGroup(6) + + +def four_group(): + """ + Return a representation of the Klein four-group as a transitive subgroup + of S4. + """ + return PermutationGroup( + Permutation(0, 1)(2, 3), + Permutation(0, 2)(1, 3) + ) + + +def M20(): + """ + Return a representation of the metacyclic group M20, a transitive subgroup + of S5 that is one of the possible Galois groups for polys of degree 5. + + Notes + ===== + + See [1], Page 323. + + """ + G = PermutationGroup(Permutation(0, 1, 2, 3, 4), Permutation(1, 2, 4, 3)) + G._degree = 5 + G._order = 20 + G._is_transitive = True + G._is_sym = False + G._is_alt = False + G._is_cyclic = False + G._is_dihedral = False + return G + + +def S3_in_S6(): + """ + Return a representation of S3 as a transitive subgroup of S6. + + Notes + ===== + + The representation is found by viewing the group as the symmetries of a + triangular prism. + + """ + G = PermutationGroup(Permutation(0, 1, 2)(3, 4, 5), Permutation(0, 3)(2, 4)(1, 5)) + set_symmetric_group_properties(G, 3, 6) + return G + + +def A4_in_S6(): + """ + Return a representation of A4 as a transitive subgroup of S6. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + G = PermutationGroup(Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 1, 2)(3, 5, 4)) + set_alternating_group_properties(G, 4, 6) + return G + + +def S4m(): + """ + Return a representation of the S4- transitive subgroup of S6. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + G = PermutationGroup(Permutation(1, 4, 5, 3), Permutation(0, 4)(1, 5)(2, 3)) + set_symmetric_group_properties(G, 4, 6) + return G + + +def S4p(): + """ + Return a representation of the S4+ transitive subgroup of S6. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + G = PermutationGroup(Permutation(0, 2, 4, 1)(3, 5), Permutation(0, 3)(4, 5)) + set_symmetric_group_properties(G, 4, 6) + return G + + +def A4xC2(): + """ + Return a representation of the (A4 x C2) transitive subgroup of S6. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + return PermutationGroup( + Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 1, 2)(3, 5, 4), + Permutation(5)(2, 4)) + + +def S4xC2(): + """ + Return a representation of the (S4 x C2) transitive subgroup of S6. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + return PermutationGroup( + Permutation(1, 4, 5, 3), Permutation(0, 4)(1, 5)(2, 3), + Permutation(1, 4)(3, 5)) + + +def G18(): + """ + Return a representation of the group G18, a transitive subgroup of S6 + isomorphic to the semidirect product of C3^2 with C2. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + return PermutationGroup( + Permutation(5)(0, 1, 2), Permutation(3, 4, 5), + Permutation(0, 4)(1, 5)(2, 3)) + + +def G36m(): + """ + Return a representation of the group G36-, a transitive subgroup of S6 + isomorphic to the semidirect product of C3^2 with C2^2. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + return PermutationGroup( + Permutation(5)(0, 1, 2), Permutation(3, 4, 5), + Permutation(1, 2)(3, 5), Permutation(0, 4)(1, 5)(2, 3)) + + +def G36p(): + """ + Return a representation of the group G36+, a transitive subgroup of S6 + isomorphic to the semidirect product of C3^2 with C4. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + return PermutationGroup( + Permutation(5)(0, 1, 2), Permutation(3, 4, 5), + Permutation(0, 5, 2, 3)(1, 4)) + + +def G72(): + """ + Return a representation of the group G72, a transitive subgroup of S6 + isomorphic to the semidirect product of C3^2 with D4. + + Notes + ===== + + See [1], Page 325. + + """ + return PermutationGroup( + Permutation(5)(0, 1, 2), + Permutation(0, 4, 1, 3)(2, 5), Permutation(0, 3)(1, 4)(2, 5)) + + +def PSL2F5(): + r""" + Return a representation of the group $PSL_2(\mathbb{F}_5)$, as a transitive + subgroup of S6, isomorphic to $A_5$. + + Notes + ===== + + This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. + + """ + G = PermutationGroup( + Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 4, 3, 1, 5)) + set_alternating_group_properties(G, 5, 6) + return G + + +def PGL2F5(): + r""" + Return a representation of the group $PGL_2(\mathbb{F}_5)$, as a transitive + subgroup of S6, isomorphic to $S_5$. + + Notes + ===== + + See [1], Page 325. + + """ + G = PermutationGroup( + Permutation(0, 1, 2, 3, 4), Permutation(0, 5)(1, 2)(3, 4)) + set_symmetric_group_properties(G, 5, 6) + return G + + +def find_transitive_subgroups_of_S6(*targets, print_report=False): + r""" + Search for certain transitive subgroups of $S_6$. + + The symmetric group $S_6$ has 16 different transitive subgroups, up to + conjugacy. Some are more easily constructed than others. For example, the + dihedral group $D_6$ is immediately found, but it is not at all obvious how + to realize $S_4$ or $S_5$ *transitively* within $S_6$. + + In some cases there are well-known constructions that can be used. For + example, $S_5$ is isomorphic to $PGL_2(\mathbb{F}_5)$, which acts in a + natural way on the projective line $P^1(\mathbb{F}_5)$, a set of order 6. + + In absence of such special constructions however, we can simply search for + generators. For example, transitive instances of $A_4$ and $S_4$ can be + found within $S_6$ in this way. + + Once we are engaged in such searches, it may then be easier (if less + elegant) to find even those groups like $S_5$ that do have special + constructions, by mere search. + + This function locates generators for transitive instances in $S_6$ of the + following subgroups: + + * $A_4$ + * $S_4^-$ ($S_4$ not contained within $A_6$) + * $S_4^+$ ($S_4$ contained within $A_6$) + * $A_4 \times C_2$ + * $S_4 \times C_2$ + * $G_{18} = C_3^2 \rtimes C_2$ + * $G_{36}^- = C_3^2 \rtimes C_2^2$ + * $G_{36}^+ = C_3^2 \rtimes C_4$ + * $G_{72} = C_3^2 \rtimes D_4$ + * $A_5$ + * $S_5$ + + Note: Each of these groups also has a dedicated function in this module + that returns the group immediately, using generators that were found by + this search procedure. + + The search procedure serves as a record of how these generators were + found. Also, due to randomness in the generation of the elements of + permutation groups, it can be called again, in order to (probably) get + different generators for the same groups. + + Parameters + ========== + + targets : list of :py:class:`~.S6TransitiveSubgroups` values + The groups you want to find. + + print_report : bool (default False) + If True, print to stdout the generators found for each group. + + Returns + ======= + + dict + mapping each name in *targets* to the :py:class:`~.PermutationGroup` + that was found + + References + ========== + + .. [2] https://en.wikipedia.org/wiki/Projective_linear_group#Exceptional_isomorphisms + .. [3] https://en.wikipedia.org/wiki/Automorphisms_of_the_symmetric_and_alternating_groups#PGL(2,5) + + """ + def elts_by_order(G): + """Sort the elements of a group by their order. """ + elts = defaultdict(list) + for g in G.elements: + elts[g.order()].append(g) + return elts + + def order_profile(G, name=None): + """Determine how many elements a group has, of each order. """ + elts = elts_by_order(G) + profile = {o:len(e) for o, e in elts.items()} + if name: + print(f'{name}: ' + ' '.join(f'{len(profile[r])}@{r}' for r in sorted(profile.keys()))) + return profile + + S6 = SymmetricGroup(6) + A6 = AlternatingGroup(6) + S6_by_order = elts_by_order(S6) + + def search(existing_gens, needed_gen_orders, order, alt=None, profile=None, anti_profile=None): + """ + Find a transitive subgroup of S6. + + Parameters + ========== + + existing_gens : list of Permutation + Optionally empty list of generators that must be in the group. + + needed_gen_orders : list of positive int + Nonempty list of the orders of the additional generators that are + to be found. + + order: int + The order of the group being sought. + + alt: bool, None + If True, require the group to be contained in A6. + If False, require the group not to be contained in A6. + + profile : dict + If given, the group's order profile must equal this. + + anti_profile : dict + If given, the group's order profile must *not* equal this. + + """ + for gens in itertools.product(*[S6_by_order[n] for n in needed_gen_orders]): + if len(set(gens)) < len(gens): + continue + G = PermutationGroup(existing_gens + list(gens)) + if G.order() == order and G.is_transitive(): + if alt is not None and G.is_subgroup(A6) != alt: + continue + if profile and order_profile(G) != profile: + continue + if anti_profile and order_profile(G) == anti_profile: + continue + return G + + def match_known_group(G, alt=None): + needed = [g.order() for g in G.generators] + return search([], needed, G.order(), alt=alt, profile=order_profile(G)) + + found = {} + + def finish_up(name, G): + found[name] = G + if print_report: + print("=" * 40) + print(f"{name}:") + print(G.generators) + + if S6TransitiveSubgroups.A4 in targets or S6TransitiveSubgroups.A4xC2 in targets: + A4_in_S6 = match_known_group(AlternatingGroup(4)) + finish_up(S6TransitiveSubgroups.A4, A4_in_S6) + + if S6TransitiveSubgroups.S4m in targets or S6TransitiveSubgroups.S4xC2 in targets: + S4m_in_S6 = match_known_group(SymmetricGroup(4), alt=False) + finish_up(S6TransitiveSubgroups.S4m, S4m_in_S6) + + if S6TransitiveSubgroups.S4p in targets: + S4p_in_S6 = match_known_group(SymmetricGroup(4), alt=True) + finish_up(S6TransitiveSubgroups.S4p, S4p_in_S6) + + if S6TransitiveSubgroups.A4xC2 in targets: + A4xC2_in_S6 = search(A4_in_S6.generators, [2], 24, anti_profile=order_profile(SymmetricGroup(4))) + finish_up(S6TransitiveSubgroups.A4xC2, A4xC2_in_S6) + + if S6TransitiveSubgroups.S4xC2 in targets: + S4xC2_in_S6 = search(S4m_in_S6.generators, [2], 48) + finish_up(S6TransitiveSubgroups.S4xC2, S4xC2_in_S6) + + # For the normal factor N = C3^2 in any of the G_n subgroups, we take one + # obvious instance of C3^2 in S6: + N_gens = [Permutation(5)(0, 1, 2), Permutation(5)(3, 4, 5)] + + if S6TransitiveSubgroups.G18 in targets: + G18_in_S6 = search(N_gens, [2], 18) + finish_up(S6TransitiveSubgroups.G18, G18_in_S6) + + if S6TransitiveSubgroups.G36m in targets: + G36m_in_S6 = search(N_gens, [2, 2], 36, alt=False) + finish_up(S6TransitiveSubgroups.G36m, G36m_in_S6) + + if S6TransitiveSubgroups.G36p in targets: + G36p_in_S6 = search(N_gens, [4], 36, alt=True) + finish_up(S6TransitiveSubgroups.G36p, G36p_in_S6) + + if S6TransitiveSubgroups.G72 in targets: + G72_in_S6 = search(N_gens, [4, 2], 72) + finish_up(S6TransitiveSubgroups.G72, G72_in_S6) + + # The PSL2(F5) and PGL2(F5) subgroups are isomorphic to A5 and S5, resp. + + if S6TransitiveSubgroups.PSL2F5 in targets: + PSL2F5_in_S6 = match_known_group(AlternatingGroup(5)) + finish_up(S6TransitiveSubgroups.PSL2F5, PSL2F5_in_S6) + + if S6TransitiveSubgroups.PGL2F5 in targets: + PGL2F5_in_S6 = match_known_group(SymmetricGroup(5)) + finish_up(S6TransitiveSubgroups.PGL2F5, PGL2F5_in_S6) + + # There is little need to "search" for any of the groups C6, S3, D6, A6, + # or S6, since they all have obvious realizations within S6. However, we + # support them here just in case a random representation is desired. + + if S6TransitiveSubgroups.C6 in targets: + C6 = match_known_group(CyclicGroup(6)) + finish_up(S6TransitiveSubgroups.C6, C6) + + if S6TransitiveSubgroups.S3 in targets: + S3 = match_known_group(SymmetricGroup(3)) + finish_up(S6TransitiveSubgroups.S3, S3) + + if S6TransitiveSubgroups.D6 in targets: + D6 = match_known_group(DihedralGroup(6)) + finish_up(S6TransitiveSubgroups.D6, D6) + + if S6TransitiveSubgroups.A6 in targets: + A6 = match_known_group(A6) + finish_up(S6TransitiveSubgroups.A6, A6) + + if S6TransitiveSubgroups.S6 in targets: + S6 = match_known_group(S6) + finish_up(S6TransitiveSubgroups.S6, S6) + + return found diff --git a/shared/package-files/d2/d24e3bd8bf1c8692a36426460b4895ccf546c9f0d8a022b0b2bb2a53417f0ec5/blob b/shared/package-files/d2/d24e3bd8bf1c8692a36426460b4895ccf546c9f0d8a022b0b2bb2a53417f0ec5/blob new file mode 100644 index 0000000000000000000000000000000000000000..910e0d24b0a3d8199fb74ebcbeaf2b111a03305b --- /dev/null +++ b/shared/package-files/d2/d24e3bd8bf1c8692a36426460b4895ccf546c9f0d8a022b0b2bb2a53417f0ec5/blob @@ -0,0 +1,57 @@ +#pragma once + +#include +#include +#include + +// these just expose TypeMeta/ScalarType bridge functions in c10 +// TODO move to typeid.h (or codemod away) when TypeMeta et al +// are moved from caffe2 to c10 (see note at top of typeid.h) + +namespace c10 { + +/** + * convert ScalarType enum values to TypeMeta handles + */ +static inline caffe2::TypeMeta scalarTypeToTypeMeta(ScalarType scalar_type) { + return caffe2::TypeMeta::fromScalarType(scalar_type); +} + +/** + * convert TypeMeta handles to ScalarType enum values + */ +static inline ScalarType typeMetaToScalarType(caffe2::TypeMeta dtype) { + return dtype.toScalarType(); +} + +/** + * typeMetaToScalarType(), lifted to optional + */ +static inline optional optTypeMetaToScalarType( + optional type_meta) { + if (!type_meta.has_value()) { + return c10::nullopt; + } + return type_meta->toScalarType(); +} + +/** + * convenience: equality across TypeMeta/ScalarType conversion + */ +static inline bool operator==(ScalarType t, caffe2::TypeMeta m) { + return m.isScalarType(t); +} + +static inline bool operator==(caffe2::TypeMeta m, ScalarType t) { + return t == m; +} + +static inline bool operator!=(ScalarType t, caffe2::TypeMeta m) { + return !(t == m); +} + +static inline bool operator!=(caffe2::TypeMeta m, ScalarType t) { + return !(t == m); +} + +} // namespace c10 diff --git a/shared/package-files/d2/d24f25e87bf18426433a480643dfff2a9bd263875c9101da495118a1a621d273/blob b/shared/package-files/d2/d24f25e87bf18426433a480643dfff2a9bd263875c9101da495118a1a621d273/blob new file mode 100644 index 0000000000000000000000000000000000000000..cd862079a1682deed3705f42da5672af8ca10acb --- /dev/null +++ b/shared/package-files/d2/d24f25e87bf18426433a480643dfff2a9bd263875c9101da495118a1a621d273/blob @@ -0,0 +1,579 @@ +"""Kernel Principal Components Analysis.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from numbers import Integral, Real + +import numpy as np +from scipy import linalg +from scipy.linalg import eigh +from scipy.sparse.linalg import eigsh + +from ..base import ( + BaseEstimator, + ClassNamePrefixFeaturesOutMixin, + TransformerMixin, + _fit_context, +) +from ..exceptions import NotFittedError +from ..metrics.pairwise import pairwise_kernels +from ..preprocessing import KernelCenterer +from ..utils._arpack import _init_arpack_v0 +from ..utils._param_validation import Interval, StrOptions +from ..utils.extmath import _randomized_eigsh, svd_flip +from ..utils.validation import ( + _check_psd_eigenvalues, + check_is_fitted, + validate_data, +) + + +class KernelPCA(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): + """Kernel Principal component analysis (KPCA). + + Non-linear dimensionality reduction through the use of kernels [1]_, see also + :ref:`metrics`. + + It uses the :func:`scipy.linalg.eigh` LAPACK implementation of the full SVD + or the :func:`scipy.sparse.linalg.eigsh` ARPACK implementation of the + truncated SVD, depending on the shape of the input data and the number of + components to extract. It can also use a randomized truncated SVD by the + method proposed in [3]_, see `eigen_solver`. + + For a usage example and comparison between + Principal Components Analysis (PCA) and its kernelized version (KPCA), see + :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`. + + For a usage example in denoising images using KPCA, see + :ref:`sphx_glr_auto_examples_applications_plot_digits_denoising.py`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_components : int, default=None + Number of components. If None, all non-zero components are kept. + + kernel : {'linear', 'poly', 'rbf', 'sigmoid', 'cosine', 'precomputed'} \ + or callable, default='linear' + Kernel used for PCA. + + gamma : float, default=None + Kernel coefficient for rbf, poly and sigmoid kernels. Ignored by other + kernels. If ``gamma`` is ``None``, then it is set to ``1/n_features``. + + degree : float, default=3 + Degree for poly kernels. Ignored by other kernels. + + coef0 : float, default=1 + Independent term in poly and sigmoid kernels. + Ignored by other kernels. + + kernel_params : dict, default=None + Parameters (keyword arguments) and + values for kernel passed as callable object. + Ignored by other kernels. + + alpha : float, default=1.0 + Hyperparameter of the ridge regression that learns the + inverse transform (when fit_inverse_transform=True). + + fit_inverse_transform : bool, default=False + Learn the inverse transform for non-precomputed kernels + (i.e. learn to find the pre-image of a point). This method is based + on [2]_. + + eigen_solver : {'auto', 'dense', 'arpack', 'randomized'}, \ + default='auto' + Select eigensolver to use. If `n_components` is much + less than the number of training samples, randomized (or arpack to a + smaller extent) may be more efficient than the dense eigensolver. + Randomized SVD is performed according to the method of Halko et al + [3]_. + + auto : + the solver is selected by a default policy based on n_samples + (the number of training samples) and `n_components`: + if the number of components to extract is less than 10 (strict) and + the number of samples is more than 200 (strict), the 'arpack' + method is enabled. Otherwise the exact full eigenvalue + decomposition is computed and optionally truncated afterwards + ('dense' method). + dense : + run exact full eigenvalue decomposition calling the standard + LAPACK solver via `scipy.linalg.eigh`, and select the components + by postprocessing + arpack : + run SVD truncated to n_components calling ARPACK solver using + `scipy.sparse.linalg.eigsh`. It requires strictly + 0 < n_components < n_samples + randomized : + run randomized SVD by the method of Halko et al. [3]_. The current + implementation selects eigenvalues based on their module; therefore + using this method can lead to unexpected results if the kernel is + not positive semi-definite. See also [4]_. + + .. versionchanged:: 1.0 + `'randomized'` was added. + + tol : float, default=0 + Convergence tolerance for arpack. + If 0, optimal value will be chosen by arpack. + + max_iter : int, default=None + Maximum number of iterations for arpack. + If None, optimal value will be chosen by arpack. + + iterated_power : int >= 0, or 'auto', default='auto' + Number of iterations for the power method computed by + svd_solver == 'randomized'. When 'auto', it is set to 7 when + `n_components < 0.1 * min(X.shape)`, other it is set to 4. + + .. versionadded:: 1.0 + + remove_zero_eig : bool, default=False + If True, then all components with zero eigenvalues are removed, so + that the number of components in the output may be < n_components + (and sometimes even zero due to numerical instability). + When n_components is None, this parameter is ignored and components + with zero eigenvalues are removed regardless. + + random_state : int, RandomState instance or None, default=None + Used when ``eigen_solver`` == 'arpack' or 'randomized'. Pass an int + for reproducible results across multiple function calls. + See :term:`Glossary `. + + .. versionadded:: 0.18 + + copy_X : bool, default=True + If True, input X is copied and stored by the model in the `X_fit_` + attribute. If no further changes will be done to X, setting + `copy_X=False` saves memory by storing a reference. + + .. versionadded:: 0.18 + + n_jobs : int, default=None + The number of parallel jobs to run. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + .. versionadded:: 0.18 + + Attributes + ---------- + eigenvalues_ : ndarray of shape (n_components,) + Eigenvalues of the centered kernel matrix in decreasing order. + If `n_components` and `remove_zero_eig` are not set, + then all values are stored. + + eigenvectors_ : ndarray of shape (n_samples, n_components) + Eigenvectors of the centered kernel matrix. If `n_components` and + `remove_zero_eig` are not set, then all components are stored. + + dual_coef_ : ndarray of shape (n_samples, n_features) + Inverse transform matrix. Only available when + ``fit_inverse_transform`` is True. + + X_transformed_fit_ : ndarray of shape (n_samples, n_components) + Projection of the fitted data on the kernel principal components. + Only available when ``fit_inverse_transform`` is True. + + X_fit_ : ndarray of shape (n_samples, n_features) + The data used to fit the model. If `copy_X=False`, then `X_fit_` is + a reference. This attribute is used for the calls to transform. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + gamma_ : float + Kernel coefficient for rbf, poly and sigmoid kernels. When `gamma` + is explicitly provided, this is just the same as `gamma`. When `gamma` + is `None`, this is the actual value of kernel coefficient. + + .. versionadded:: 1.3 + + See Also + -------- + FastICA : A fast algorithm for Independent Component Analysis. + IncrementalPCA : Incremental Principal Component Analysis. + NMF : Non-Negative Matrix Factorization. + PCA : Principal Component Analysis. + SparsePCA : Sparse Principal Component Analysis. + TruncatedSVD : Dimensionality reduction using truncated SVD. + + References + ---------- + .. [1] `Schölkopf, Bernhard, Alexander Smola, and Klaus-Robert Müller. + "Kernel principal component analysis." + International conference on artificial neural networks. + Springer, Berlin, Heidelberg, 1997. + `_ + + .. [2] `Bakır, Gökhan H., Jason Weston, and Bernhard Schölkopf. + "Learning to find pre-images." + Advances in neural information processing systems 16 (2004): 449-456. + `_ + + .. [3] :arxiv:`Halko, Nathan, Per-Gunnar Martinsson, and Joel A. Tropp. + "Finding structure with randomness: Probabilistic algorithms for + constructing approximate matrix decompositions." + SIAM review 53.2 (2011): 217-288. <0909.4061>` + + .. [4] `Martinsson, Per-Gunnar, Vladimir Rokhlin, and Mark Tygert. + "A randomized algorithm for the decomposition of matrices." + Applied and Computational Harmonic Analysis 30.1 (2011): 47-68. + `_ + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.decomposition import KernelPCA + >>> X, _ = load_digits(return_X_y=True) + >>> transformer = KernelPCA(n_components=7, kernel='linear') + >>> X_transformed = transformer.fit_transform(X) + >>> X_transformed.shape + (1797, 7) + """ + + _parameter_constraints: dict = { + "n_components": [ + Interval(Integral, 1, None, closed="left"), + None, + ], + "kernel": [ + StrOptions({"linear", "poly", "rbf", "sigmoid", "cosine", "precomputed"}), + callable, + ], + "gamma": [ + Interval(Real, 0, None, closed="left"), + None, + ], + "degree": [Interval(Real, 0, None, closed="left")], + "coef0": [Interval(Real, None, None, closed="neither")], + "kernel_params": [dict, None], + "alpha": [Interval(Real, 0, None, closed="left")], + "fit_inverse_transform": ["boolean"], + "eigen_solver": [StrOptions({"auto", "dense", "arpack", "randomized"})], + "tol": [Interval(Real, 0, None, closed="left")], + "max_iter": [ + Interval(Integral, 1, None, closed="left"), + None, + ], + "iterated_power": [ + Interval(Integral, 0, None, closed="left"), + StrOptions({"auto"}), + ], + "remove_zero_eig": ["boolean"], + "random_state": ["random_state"], + "copy_X": ["boolean"], + "n_jobs": [None, Integral], + } + + def __init__( + self, + n_components=None, + *, + kernel="linear", + gamma=None, + degree=3, + coef0=1, + kernel_params=None, + alpha=1.0, + fit_inverse_transform=False, + eigen_solver="auto", + tol=0, + max_iter=None, + iterated_power="auto", + remove_zero_eig=False, + random_state=None, + copy_X=True, + n_jobs=None, + ): + self.n_components = n_components + self.kernel = kernel + self.kernel_params = kernel_params + self.gamma = gamma + self.degree = degree + self.coef0 = coef0 + self.alpha = alpha + self.fit_inverse_transform = fit_inverse_transform + self.eigen_solver = eigen_solver + self.tol = tol + self.max_iter = max_iter + self.iterated_power = iterated_power + self.remove_zero_eig = remove_zero_eig + self.random_state = random_state + self.n_jobs = n_jobs + self.copy_X = copy_X + + def _get_kernel(self, X, Y=None): + if callable(self.kernel): + params = self.kernel_params or {} + else: + params = {"gamma": self.gamma_, "degree": self.degree, "coef0": self.coef0} + return pairwise_kernels( + X, Y, metric=self.kernel, filter_params=True, n_jobs=self.n_jobs, **params + ) + + def _fit_transform_in_place(self, K): + """Fit's using kernel K""" + # center kernel in place + K = self._centerer.fit(K).transform(K, copy=False) + + # adjust n_components according to user inputs + if self.n_components is None: + n_components = K.shape[0] # use all dimensions + else: + n_components = min(K.shape[0], self.n_components) + + # compute eigenvectors + if self.eigen_solver == "auto": + if K.shape[0] > 200 and n_components < 10: + eigen_solver = "arpack" + else: + eigen_solver = "dense" + else: + eigen_solver = self.eigen_solver + + if eigen_solver == "dense": + # Note: subset_by_index specifies the indices of smallest/largest to return + self.eigenvalues_, self.eigenvectors_ = eigh( + K, subset_by_index=(K.shape[0] - n_components, K.shape[0] - 1) + ) + elif eigen_solver == "arpack": + v0 = _init_arpack_v0(K.shape[0], self.random_state) + self.eigenvalues_, self.eigenvectors_ = eigsh( + K, n_components, which="LA", tol=self.tol, maxiter=self.max_iter, v0=v0 + ) + elif eigen_solver == "randomized": + self.eigenvalues_, self.eigenvectors_ = _randomized_eigsh( + K, + n_components=n_components, + n_iter=self.iterated_power, + random_state=self.random_state, + selection="module", + ) + + # make sure that the eigenvalues are ok and fix numerical issues + self.eigenvalues_ = _check_psd_eigenvalues( + self.eigenvalues_, enable_warnings=False + ) + + # flip eigenvectors' sign to enforce deterministic output + self.eigenvectors_, _ = svd_flip(u=self.eigenvectors_, v=None) + + # sort eigenvectors in descending order + indices = self.eigenvalues_.argsort()[::-1] + self.eigenvalues_ = self.eigenvalues_[indices] + self.eigenvectors_ = self.eigenvectors_[:, indices] + + # remove eigenvectors with a zero eigenvalue (null space) if required + if self.remove_zero_eig or self.n_components is None: + self.eigenvectors_ = self.eigenvectors_[:, self.eigenvalues_ > 0] + self.eigenvalues_ = self.eigenvalues_[self.eigenvalues_ > 0] + + # Maintenance note on Eigenvectors normalization + # ---------------------------------------------- + # there is a link between + # the eigenvectors of K=Phi(X)'Phi(X) and the ones of Phi(X)Phi(X)' + # if v is an eigenvector of K + # then Phi(X)v is an eigenvector of Phi(X)Phi(X)' + # if u is an eigenvector of Phi(X)Phi(X)' + # then Phi(X)'u is an eigenvector of Phi(X)'Phi(X) + # + # At this stage our self.eigenvectors_ (the v) have norm 1, we need to scale + # them so that eigenvectors in kernel feature space (the u) have norm=1 + # instead + # + # We COULD scale them here: + # self.eigenvectors_ = self.eigenvectors_ / np.sqrt(self.eigenvalues_) + # + # But choose to perform that LATER when needed, in `fit()` and in + # `transform()`. + + return K + + def _fit_inverse_transform(self, X_transformed, X): + if hasattr(X, "tocsr"): + raise NotImplementedError( + "Inverse transform not implemented for sparse matrices!" + ) + + n_samples = X_transformed.shape[0] + K = self._get_kernel(X_transformed) + K.flat[:: n_samples + 1] += self.alpha + self.dual_coef_ = linalg.solve(K, X, assume_a="pos", overwrite_a=True) + self.X_transformed_fit_ = X_transformed + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the model from data in X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + Returns the instance itself. + """ + if self.fit_inverse_transform and self.kernel == "precomputed": + raise ValueError("Cannot fit_inverse_transform with a precomputed kernel.") + X = validate_data(self, X, accept_sparse="csr", copy=self.copy_X) + self.gamma_ = 1 / X.shape[1] if self.gamma is None else self.gamma + self._centerer = KernelCenterer().set_output(transform="default") + K = self._get_kernel(X) + # When kernel="precomputed", K is X but it's safe to perform in place operations + # on K because a copy was made before if requested by copy_X. + self._fit_transform_in_place(K) + + if self.fit_inverse_transform: + # no need to use the kernel to transform X, use shortcut expression + X_transformed = self.eigenvectors_ * np.sqrt(self.eigenvalues_) + + self._fit_inverse_transform(X_transformed, X) + + self.X_fit_ = X + return self + + def fit_transform(self, X, y=None, **params): + """Fit the model from data in X and transform X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : Ignored + Not used, present for API consistency by convention. + + **params : kwargs + Parameters (keyword arguments) and values passed to + the fit_transform instance. + + Returns + ------- + X_new : ndarray of shape (n_samples, n_components) + Transformed values. + """ + self.fit(X, **params) + + # no need to use the kernel to transform X, use shortcut expression + X_transformed = self.eigenvectors_ * np.sqrt(self.eigenvalues_) + + if self.fit_inverse_transform: + self._fit_inverse_transform(X_transformed, X) + + return X_transformed + + def transform(self, X): + """Transform X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples + and `n_features` is the number of features. + + Returns + ------- + X_new : ndarray of shape (n_samples, n_components) + Projection of X in the first principal components, where `n_samples` + is the number of samples and `n_components` is the number of the components. + """ + check_is_fitted(self) + X = validate_data(self, X, accept_sparse="csr", reset=False) + + # Compute centered gram matrix between X and training data X_fit_ + K = self._centerer.transform(self._get_kernel(X, self.X_fit_)) + + # scale eigenvectors (properly account for null-space for dot product) + non_zeros = np.flatnonzero(self.eigenvalues_) + scaled_alphas = np.zeros_like(self.eigenvectors_) + scaled_alphas[:, non_zeros] = self.eigenvectors_[:, non_zeros] / np.sqrt( + self.eigenvalues_[non_zeros] + ) + + # Project with a scalar product between K and the scaled eigenvectors + return np.dot(K, scaled_alphas) + + def inverse_transform(self, X): + """Transform X back to original space. + + ``inverse_transform`` approximates the inverse transformation using + a learned pre-image. The pre-image is learned by kernel ridge + regression of the original data on their low-dimensional representation + vectors. + + .. note: + :meth:`~sklearn.decomposition.fit` internally uses a centered + kernel. As the centered kernel no longer contains the information + of the mean of kernel features, such information is not taken into + account in reconstruction. + + .. note:: + When users want to compute inverse transformation for 'linear' + kernel, it is recommended that they use + :class:`~sklearn.decomposition.PCA` instead. Unlike + :class:`~sklearn.decomposition.PCA`, + :class:`~sklearn.decomposition.KernelPCA`'s ``inverse_transform`` + does not reconstruct the mean of data when 'linear' kernel is used + due to the use of centered kernel. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_components) + Training vector, where `n_samples` is the number of samples + and `n_features` is the number of features. + + Returns + ------- + X_original : ndarray of shape (n_samples, n_features) + Original data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + References + ---------- + `Bakır, Gökhan H., Jason Weston, and Bernhard Schölkopf. + "Learning to find pre-images." + Advances in neural information processing systems 16 (2004): 449-456. + `_ + """ + if not self.fit_inverse_transform: + raise NotFittedError( + "The fit_inverse_transform parameter was not" + " set to True when instantiating and hence " + "the inverse transform is not available." + ) + + K = self._get_kernel(X, self.X_transformed_fit_) + return np.dot(K, self.dual_coef_) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + tags.transformer_tags.preserves_dtype = ["float64", "float32"] + tags.input_tags.pairwise = self.kernel == "precomputed" + return tags + + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.eigenvalues_.shape[0] diff --git a/shared/package-files/d2/d251cfcc998ea96c765cafe80507a2c016ebf18eb14f5f3663bdaaff28fac08a/blob b/shared/package-files/d2/d251cfcc998ea96c765cafe80507a2c016ebf18eb14f5f3663bdaaff28fac08a/blob new file mode 100644 index 0000000000000000000000000000000000000000..0035296a45c14576988720407e11c6a06f857ce9 --- /dev/null +++ b/shared/package-files/d2/d251cfcc998ea96c765cafe80507a2c016ebf18eb14f5f3663bdaaff28fac08a/blob @@ -0,0 +1,121 @@ +# +# The Python Imaging Library. +# $Id$ +# +# a class to read from a container file +# +# History: +# 1995-06-18 fl Created +# 1995-09-07 fl Added readline(), readlines() +# +# Copyright (c) 1997-2001 by Secret Labs AB +# Copyright (c) 1995 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +from typing import IO, AnyStr, Generic, Literal + + +class ContainerIO(Generic[AnyStr]): + """ + A file object that provides read access to a part of an existing + file (for example a TAR file). + """ + + def __init__(self, file: IO[AnyStr], offset: int, length: int) -> None: + """ + Create file object. + + :param file: Existing file. + :param offset: Start of region, in bytes. + :param length: Size of region, in bytes. + """ + self.fh: IO[AnyStr] = file + self.pos = 0 + self.offset = offset + self.length = length + self.fh.seek(offset) + + ## + # Always false. + + def isatty(self) -> bool: + return False + + def seek(self, offset: int, mode: Literal[0, 1, 2] = io.SEEK_SET) -> None: + """ + Move file pointer. + + :param offset: Offset in bytes. + :param mode: Starting position. Use 0 for beginning of region, 1 + for current offset, and 2 for end of region. You cannot move + the pointer outside the defined region. + """ + if mode == 1: + self.pos = self.pos + offset + elif mode == 2: + self.pos = self.length + offset + else: + self.pos = offset + # clamp + self.pos = max(0, min(self.pos, self.length)) + self.fh.seek(self.offset + self.pos) + + def tell(self) -> int: + """ + Get current file pointer. + + :returns: Offset from start of region, in bytes. + """ + return self.pos + + def read(self, n: int = 0) -> AnyStr: + """ + Read data. + + :param n: Number of bytes to read. If omitted or zero, + read until end of region. + :returns: An 8-bit string. + """ + if n: + n = min(n, self.length - self.pos) + else: + n = self.length - self.pos + if not n: # EOF + return b"" if "b" in self.fh.mode else "" # type: ignore[return-value] + self.pos = self.pos + n + return self.fh.read(n) + + def readline(self) -> AnyStr: + """ + Read a line of text. + + :returns: An 8-bit string. + """ + s: AnyStr = b"" if "b" in self.fh.mode else "" # type: ignore[assignment] + newline_character = b"\n" if "b" in self.fh.mode else "\n" + while True: + c = self.read(1) + if not c: + break + s = s + c + if c == newline_character: + break + return s + + def readlines(self) -> list[AnyStr]: + """ + Read multiple lines of text. + + :returns: A list of 8-bit strings. + """ + lines = [] + while True: + s = self.readline() + if not s: + break + lines.append(s) + return lines diff --git a/shared/package-files/d2/d2522536595379c6f9dc086225c3ddf7b33b687f2c8abe58e2b20462d7d9b3b2/blob b/shared/package-files/d2/d2522536595379c6f9dc086225c3ddf7b33b687f2c8abe58e2b20462d7d9b3b2/blob new file mode 100644 index 0000000000000000000000000000000000000000..3d805f35c5dce9d3b7ecea9fcef08ec5d3e75711 --- /dev/null +++ b/shared/package-files/d2/d2522536595379c6f9dc086225c3ddf7b33b687f2c8abe58e2b20462d7d9b3b2/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor flatten_dense_tensors(at::TensorList tensors); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/d2/d25439c06fdea976bbe907ee1dd0abed47b1d720ccee79de0f91badb29030b38/blob b/shared/package-files/d2/d25439c06fdea976bbe907ee1dd0abed47b1d720ccee79de0f91badb29030b38/blob new file mode 100644 index 0000000000000000000000000000000000000000..f163266f3b876796f8447d0eb356cc28652c9bac --- /dev/null +++ b/shared/package-files/d2/d25439c06fdea976bbe907ee1dd0abed47b1d720ccee79de0f91badb29030b38/blob @@ -0,0 +1,2659 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Functions for pandas conversion via NumPy + +#include "arrow/python/arrow_to_pandas.h" +#include "arrow/python/numpy_interop.h" // IWYU pragma: expand + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/array.h" +#include "arrow/buffer.h" +#include "arrow/datum.h" +#include "arrow/status.h" +#include "arrow/table.h" +#include "arrow/type.h" +#include "arrow/type_traits.h" +#include "arrow/util/checked_cast.h" +#include "arrow/util/hashing.h" +#include "arrow/util/int_util.h" +#include "arrow/util/logging.h" +#include "arrow/util/macros.h" +#include "arrow/util/parallel.h" +#include "arrow/visit_type_inline.h" + +#include "arrow/compute/api.h" + +#include "arrow/python/arrow_to_python_internal.h" +#include "arrow/python/common.h" +#include "arrow/python/datetime.h" +#include "arrow/python/decimal.h" +#include "arrow/python/helpers.h" +#include "arrow/python/numpy_convert.h" +#include "arrow/python/numpy_internal.h" +#include "arrow/python/pyarrow.h" +#include "arrow/python/python_to_arrow.h" +#include "arrow/python/type_traits.h" + +namespace arrow { + +class MemoryPool; + +using internal::checked_cast; +using internal::CheckIndexBounds; +using internal::OptionalParallelFor; + +namespace py { +namespace { + +// Fix options for conversion of an inner (child) array. +PandasOptions MakeInnerOptions(PandasOptions options) { + // Make sure conversion of inner dictionary arrays always returns an array, + // not a dict {'indices': array, 'dictionary': array, 'ordered': bool} + options.decode_dictionaries = true; + options.categorical_columns.reset(); + options.strings_to_categorical = false; + + // In ARROW-7723, we found as a result of ARROW-3789 that second + // through microsecond resolution tz-aware timestamps were being promoted to + // use the DATETIME_NANO_TZ conversion path, yielding a datetime64[ns] NumPy + // array in this function. PyArray_GETITEM returns datetime.datetime for + // units second through microsecond but PyLong for nanosecond (because + // datetime.datetime does not support nanoseconds). + // We force the object conversion to preserve the value of the timezone. + // Nanoseconds are returned as integers. + options.coerce_temporal_nanoseconds = false; + + return options; +} + +// ---------------------------------------------------------------------- +// PyCapsule code for setting ndarray base to reference C++ object + +struct ArrayCapsule { + std::shared_ptr array; +}; + +struct BufferCapsule { + std::shared_ptr buffer; +}; + +void ArrayCapsule_Destructor(PyObject* capsule) { + delete reinterpret_cast(PyCapsule_GetPointer(capsule, "arrow::Array")); +} + +void BufferCapsule_Destructor(PyObject* capsule) { + delete reinterpret_cast(PyCapsule_GetPointer(capsule, "arrow::Buffer")); +} + +// ---------------------------------------------------------------------- +// pandas 0.x DataFrame conversion internals + +using internal::arrow_traits; +using internal::npy_traits; + +template +struct WrapBytes {}; + +template <> +struct WrapBytes { + static inline PyObject* Wrap(const char* data, int64_t length) { + return PyUnicode_FromStringAndSize(data, length); + } +}; + +template <> +struct WrapBytes { + static inline PyObject* Wrap(const char* data, int64_t length) { + return PyUnicode_FromStringAndSize(data, length); + } +}; + +template <> +struct WrapBytes { + static inline PyObject* Wrap(const char* data, int64_t length) { + return PyUnicode_FromStringAndSize(data, length); + } +}; + +template <> +struct WrapBytes { + static inline PyObject* Wrap(const char* data, int64_t length) { + return PyBytes_FromStringAndSize(data, length); + } +}; + +template <> +struct WrapBytes { + static inline PyObject* Wrap(const char* data, int64_t length) { + return PyBytes_FromStringAndSize(data, length); + } +}; + +template <> +struct WrapBytes { + static inline PyObject* Wrap(const char* data, int64_t length) { + return PyBytes_FromStringAndSize(data, length); + } +}; + +template <> +struct WrapBytes { + static inline PyObject* Wrap(const char* data, int64_t length) { + return PyBytes_FromStringAndSize(data, length); + } +}; + +static inline bool ListTypeSupported(const DataType& type) { + switch (type.id()) { + case Type::BOOL: + case Type::UINT8: + case Type::INT8: + case Type::UINT16: + case Type::INT16: + case Type::UINT32: + case Type::INT32: + case Type::INT64: + case Type::UINT64: + case Type::HALF_FLOAT: + case Type::FLOAT: + case Type::DOUBLE: + case Type::DECIMAL128: + case Type::DECIMAL256: + case Type::BINARY: + case Type::LARGE_BINARY: + case Type::STRING: + case Type::LARGE_STRING: + case Type::DATE32: + case Type::DATE64: + case Type::STRUCT: + case Type::MAP: + case Type::TIME32: + case Type::TIME64: + case Type::TIMESTAMP: + case Type::DURATION: + case Type::DICTIONARY: + case Type::INTERVAL_MONTH_DAY_NANO: + case Type::NA: // empty list + // The above types are all supported. + return true; + case Type::FIXED_SIZE_LIST: + case Type::LIST: + case Type::LARGE_LIST: + case Type::LIST_VIEW: + case Type::LARGE_LIST_VIEW: { + const auto& list_type = checked_cast(type); + return ListTypeSupported(*list_type.value_type()); + } + case Type::EXTENSION: { + const auto& ext = checked_cast(*type.GetSharedPtr()); + return ListTypeSupported(*(ext.storage_type())); + } + default: + break; + } + return false; +} + +Status CapsulizeArray(const std::shared_ptr& arr, PyObject** out) { + auto capsule = new ArrayCapsule{{arr}}; + *out = PyCapsule_New(reinterpret_cast(capsule), "arrow::Array", + &ArrayCapsule_Destructor); + if (*out == nullptr) { + delete capsule; + RETURN_IF_PYERROR(); + } + return Status::OK(); +} + +Status CapsulizeBuffer(const std::shared_ptr& buffer, PyObject** out) { + auto capsule = new BufferCapsule{{buffer}}; + *out = PyCapsule_New(reinterpret_cast(capsule), "arrow::Buffer", + &BufferCapsule_Destructor); + if (*out == nullptr) { + delete capsule; + RETURN_IF_PYERROR(); + } + return Status::OK(); +} + +Status SetNdarrayBase(PyArrayObject* arr, PyObject* base) { + if (PyArray_SetBaseObject(arr, base) == -1) { + // Error occurred, trust that SetBaseObject sets the error state + Py_XDECREF(base); + RETURN_IF_PYERROR(); + } + return Status::OK(); +} + +Status SetBufferBase(PyArrayObject* arr, const std::shared_ptr& buffer) { + PyObject* base; + RETURN_NOT_OK(CapsulizeBuffer(buffer, &base)); + return SetNdarrayBase(arr, base); +} + +inline void set_numpy_metadata(int type, const DataType* datatype, PyArray_Descr* out) { + auto metadata = + reinterpret_cast(PyDataType_C_METADATA(out)); + if (type == NPY_DATETIME) { + if (datatype->id() == Type::TIMESTAMP) { + const auto& timestamp_type = checked_cast(*datatype); + metadata->meta.base = internal::NumPyFrequency(timestamp_type.unit()); + } else { + ARROW_DCHECK(false) + << "NPY_DATETIME views only supported for Arrow TIMESTAMP types"; + } + } else if (type == NPY_TIMEDELTA) { + ARROW_DCHECK_EQ(datatype->id(), Type::DURATION); + const auto& duration_type = checked_cast(*datatype); + metadata->meta.base = internal::NumPyFrequency(duration_type.unit()); + } +} + +Status PyArray_NewFromPool(int nd, npy_intp* dims, PyArray_Descr* descr, MemoryPool* pool, + PyObject** out) { + // ARROW-6570: Allocate memory from MemoryPool for a couple reasons + // + // * Track allocations + // * Get better performance through custom allocators + int64_t total_size = PyDataType_ELSIZE(descr); + for (int i = 0; i < nd; ++i) { + total_size *= dims[i]; + } + + ARROW_ASSIGN_OR_RAISE(auto buffer, AllocateBuffer(total_size, pool)); + *out = PyArray_NewFromDescr(&PyArray_Type, descr, nd, dims, + /*strides=*/nullptr, + /*data=*/buffer->mutable_data(), + /*flags=*/NPY_ARRAY_CARRAY | NPY_ARRAY_WRITEABLE, + /*obj=*/nullptr); + if (*out == nullptr) { + RETURN_IF_PYERROR(); + // Trust that error set if NULL returned + } + return SetBufferBase(reinterpret_cast(*out), std::move(buffer)); +} + +template +inline const T* GetPrimitiveValues(const Array& arr) { + if (arr.length() == 0) { + return nullptr; + } + const int elsize = arr.type()->byte_width(); + const auto& prim_arr = checked_cast(arr); + return reinterpret_cast(prim_arr.values()->data() + arr.offset() * elsize); +} + +Status MakeNumPyView(std::shared_ptr arr, PyObject* py_ref, int npy_type, int ndim, + npy_intp* dims, PyObject** out) { + PyAcquireGIL lock; + + PyArray_Descr* descr = internal::GetSafeNumPyDtype(npy_type); + set_numpy_metadata(npy_type, arr->type().get(), descr); + PyObject* result = PyArray_NewFromDescr( + &PyArray_Type, descr, ndim, dims, /*strides=*/nullptr, + const_cast(GetPrimitiveValues(*arr)), /*flags=*/0, nullptr); + PyArrayObject* np_arr = reinterpret_cast(result); + if (np_arr == nullptr) { + // Error occurred, trust that error set + return Status::OK(); + } + + PyObject* base; + if (py_ref == nullptr) { + // Capsule will be owned by the ndarray, no incref necessary. See + // ARROW-1973 + RETURN_NOT_OK(CapsulizeArray(arr, &base)); + } else { + Py_INCREF(py_ref); + base = py_ref; + } + RETURN_NOT_OK(SetNdarrayBase(np_arr, base)); + + // Do not allow Arrow data to be mutated + PyArray_CLEARFLAGS(np_arr, NPY_ARRAY_WRITEABLE); + *out = result; + return Status::OK(); +} + +class PandasWriter { + public: + enum type { + OBJECT, + UINT8, + INT8, + UINT16, + INT16, + UINT32, + INT32, + UINT64, + INT64, + HALF_FLOAT, + FLOAT, + DOUBLE, + BOOL, + DATETIME_DAY, + DATETIME_SECOND, + DATETIME_MILLI, + DATETIME_MICRO, + DATETIME_NANO, + DATETIME_SECOND_TZ, + DATETIME_MILLI_TZ, + DATETIME_MICRO_TZ, + DATETIME_NANO_TZ, + TIMEDELTA_SECOND, + TIMEDELTA_MILLI, + TIMEDELTA_MICRO, + TIMEDELTA_NANO, + CATEGORICAL, + EXTENSION + }; + + PandasWriter(const PandasOptions& options, int64_t num_rows, int num_columns) + : options_(options), num_rows_(num_rows), num_columns_(num_columns) { + PyAcquireGIL lock; + internal::InitPandasStaticData(); + } + virtual ~PandasWriter() {} + + void SetBlockData(PyObject* arr) { + block_arr_.reset(arr); + block_data_ = + reinterpret_cast(PyArray_DATA(reinterpret_cast(arr))); + } + + /// \brief Either copy or wrap single array to create pandas-compatible array + /// for Series or DataFrame. num_columns_ can only be 1. Will try to zero + /// copy if possible (or error if not possible and zero_copy_only=True) + virtual Status TransferSingle(std::shared_ptr data, PyObject* py_ref) = 0; + + /// \brief Copy ChunkedArray into a multi-column block + virtual Status CopyInto(std::shared_ptr data, int64_t rel_placement) = 0; + + Status EnsurePlacementAllocated() { + std::lock_guard guard(allocation_lock_); + if (placement_data_ != nullptr) { + return Status::OK(); + } + PyAcquireGIL lock; + npy_intp placement_dims[1] = {num_columns_}; + PyObject* placement_arr = PyArray_SimpleNew(1, placement_dims, NPY_INT64); + RETURN_IF_PYERROR(); + placement_arr_.reset(placement_arr); + placement_data_ = reinterpret_cast( + PyArray_DATA(reinterpret_cast(placement_arr))); + return Status::OK(); + } + + Status EnsureAllocated() { + std::lock_guard guard(allocation_lock_); + if (block_data_ != nullptr) { + return Status::OK(); + } + RETURN_NOT_OK(Allocate()); + return Status::OK(); + } + + virtual bool CanZeroCopy(const ChunkedArray& data) const { return false; } + + virtual Status Write(std::shared_ptr data, int64_t abs_placement, + int64_t rel_placement) { + RETURN_NOT_OK(EnsurePlacementAllocated()); + if (num_columns_ == 1 && options_.allow_zero_copy_blocks) { + RETURN_NOT_OK(TransferSingle(data, /*py_ref=*/nullptr)); + } else { + RETURN_NOT_OK( + CheckNoZeroCopy("Cannot do zero copy conversion into " + "multi-column DataFrame block")); + RETURN_NOT_OK(EnsureAllocated()); + RETURN_NOT_OK(CopyInto(data, rel_placement)); + } + placement_data_[rel_placement] = abs_placement; + return Status::OK(); + } + + virtual Status GetDataFrameResult(PyObject** out) { + PyObject* result = PyDict_New(); + RETURN_IF_PYERROR(); + + PyObject* block; + RETURN_NOT_OK(GetResultBlock(&block)); + + PyDict_SetItemString(result, "block", block); + PyDict_SetItemString(result, "placement", placement_arr_.obj()); + + RETURN_NOT_OK(AddResultMetadata(result)); + *out = result; + return Status::OK(); + } + + // Caller steals the reference to this object + virtual Status GetSeriesResult(PyObject** out) { + RETURN_NOT_OK(MakeBlock1D()); + // Caller owns the object now + *out = block_arr_.detach(); + return Status::OK(); + } + + protected: + virtual Status AddResultMetadata(PyObject* result) { return Status::OK(); } + + Status MakeBlock1D() { + // For Series or for certain DataFrame block types, we need to shape to a + // 1D array when there is only one column + PyAcquireGIL lock; + + ARROW_DCHECK_EQ(1, num_columns_); + + npy_intp new_dims[1] = {static_cast(num_rows_)}; + PyArray_Dims dims; + dims.ptr = new_dims; + dims.len = 1; + + PyObject* reshaped = PyArray_Newshape( + reinterpret_cast(block_arr_.obj()), &dims, NPY_ANYORDER); + RETURN_IF_PYERROR(); + + // ARROW-8801: Here a PyArrayObject is created that is not being managed by + // any OwnedRef object. This object is then put in the resulting object + // with PyDict_SetItemString, which increments the reference count, so a + // memory leak ensues. There are several ways to fix the memory leak but a + // simple one is to put the reshaped 1D block array in this OwnedRefNoGIL + // so it will be correctly decref'd when this class is destructed. + block_arr_.reset(reshaped); + return Status::OK(); + } + + virtual Status GetResultBlock(PyObject** out) { + *out = block_arr_.obj(); + return Status::OK(); + } + + Status CheckNoZeroCopy(const std::string& message) { + if (options_.zero_copy_only) { + return Status::Invalid(message); + } + return Status::OK(); + } + + Status CheckNotZeroCopyOnly(const ChunkedArray& data) { + if (options_.zero_copy_only) { + return Status::Invalid("Needed to copy ", data.num_chunks(), " chunks with ", + data.null_count(), " nulls, but zero_copy_only was True"); + } + return Status::OK(); + } + + virtual Status Allocate() { + return Status::NotImplemented("Override Allocate in subclasses"); + } + + Status AllocateNDArray(int npy_type, int ndim = 2) { + PyAcquireGIL lock; + + PyObject* block_arr = nullptr; + npy_intp block_dims[2] = {0, 0}; + + if (ndim == 2) { + block_dims[0] = num_columns_; + block_dims[1] = num_rows_; + } else { + block_dims[0] = num_rows_; + } + PyArray_Descr* descr = internal::GetSafeNumPyDtype(npy_type); + if (PyDataType_REFCHK(descr)) { + // ARROW-6876: if the array has refcounted items, let Numpy + // own the array memory so as to decref elements on array destruction + block_arr = PyArray_SimpleNewFromDescr(ndim, block_dims, descr); + RETURN_IF_PYERROR(); + } else { + RETURN_NOT_OK( + PyArray_NewFromPool(ndim, block_dims, descr, options_.pool, &block_arr)); + } + + SetBlockData(block_arr); + return Status::OK(); + } + + void SetDatetimeUnit(NPY_DATETIMEUNIT unit) { + PyAcquireGIL lock; + auto date_dtype = + reinterpret_cast(PyDataType_C_METADATA( + PyArray_DESCR(reinterpret_cast(block_arr_.obj())))); + date_dtype->meta.base = unit; + } + + PandasOptions options_; + + std::mutex allocation_lock_; + + int64_t num_rows_; + int num_columns_; + + OwnedRefNoGIL block_arr_; + uint8_t* block_data_ = nullptr; + + // ndarray + OwnedRefNoGIL placement_arr_; + int64_t* placement_data_ = nullptr; + + private: + ARROW_DISALLOW_COPY_AND_ASSIGN(PandasWriter); +}; + +template +inline void ConvertIntegerWithNulls(const PandasOptions& options, + const ChunkedArray& data, OutType* out_values) { + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = *data.chunk(c); + const InType* in_values = GetPrimitiveValues(arr); + // Upcast to double, set NaN as appropriate + + for (int i = 0; i < arr.length(); ++i) { + *out_values++ = + arr.IsNull(i) ? static_cast(NAN) : static_cast(in_values[i]); + } + } +} + +template +inline void ConvertIntegerNoNullsSameType(const PandasOptions& options, + const ChunkedArray& data, T* out_values) { + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = *data.chunk(c); + if (arr.length() > 0) { + const T* in_values = GetPrimitiveValues(arr); + memcpy(out_values, in_values, sizeof(T) * arr.length()); + out_values += arr.length(); + } + } +} + +template +inline void ConvertIntegerNoNullsCast(const PandasOptions& options, + const ChunkedArray& data, OutType* out_values) { + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = *data.chunk(c); + const InType* in_values = GetPrimitiveValues(arr); + for (int64_t i = 0; i < arr.length(); ++i) { + *out_values = in_values[i]; + } + } +} + +template +struct MemoizationTraits { + using Scalar = typename T::c_type; +}; + +template +struct MemoizationTraits> { + // For binary, we memoize string_view as a scalar value to avoid having to + // unnecessarily copy the memory into the memo table data structure + using Scalar = std::string_view; +}; + +// Generic Array -> PyObject** converter that handles object deduplication, if +// requested +template +inline Status ConvertAsPyObjects(const PandasOptions& options, const ChunkedArray& data, + WrapFunction&& wrap_func, PyObject** out_values) { + using ArrayType = typename TypeTraits::ArrayType; + using Scalar = typename MemoizationTraits::Scalar; + + auto convert_chunks = [&](auto&& wrap_func) -> Status { + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = arrow::internal::checked_cast(*data.chunk(c)); + RETURN_NOT_OK(internal::WriteArrayObjects(arr, wrap_func, out_values)); + out_values += arr.length(); + } + return Status::OK(); + }; + + if (options.deduplicate_objects) { + // GH-40316: only allocate a memo table if deduplication is enabled. + ::arrow::internal::ScalarMemoTable memo_table(options.pool); + std::vector unique_values; + int32_t memo_size = 0; + + auto WrapMemoized = [&](const Scalar& value, PyObject** out_values) { + int32_t memo_index; + RETURN_NOT_OK(memo_table.GetOrInsert(value, &memo_index)); + if (memo_index == memo_size) { + // New entry + RETURN_NOT_OK(wrap_func(value, out_values)); + unique_values.push_back(*out_values); + ++memo_size; + } else { + // Duplicate entry + Py_INCREF(unique_values[memo_index]); + *out_values = unique_values[memo_index]; + } + return Status::OK(); + }; + return convert_chunks(std::move(WrapMemoized)); + } else { + return convert_chunks(std::forward(wrap_func)); + } +} + +Status ConvertStruct(PandasOptions options, const ChunkedArray& data, + PyObject** out_values) { + if (data.num_chunks() == 0) { + return Status::OK(); + } + // ChunkedArray has at least one chunk + auto arr = checked_cast(data.chunk(0).get()); + // Use it to cache the struct type and number of fields for all chunks + int32_t num_fields = arr->num_fields(); + auto array_type = arr->type(); + std::vector fields_data(num_fields * data.num_chunks()); + OwnedRef dict_item; + + // See notes in MakeInnerOptions. + options = MakeInnerOptions(std::move(options)); + // Don't blindly convert because timestamps in lists are handled differently. + options.timestamp_as_object = true; + + for (int c = 0; c < data.num_chunks(); c++) { + auto fields_data_offset = c * num_fields; + auto arr = checked_cast(data.chunk(c).get()); + // Convert the struct arrays first + for (int32_t i = 0; i < num_fields; i++) { + auto field = arr->field(static_cast(i)); + // In case the field is an extension array, use .storage() to convert to Pandas + if (field->type()->id() == Type::EXTENSION) { + const ExtensionArray& arr_ext = checked_cast(*field); + field = arr_ext.storage(); + } + RETURN_NOT_OK(ConvertArrayToPandas(options, field, nullptr, + fields_data[i + fields_data_offset].ref())); + ARROW_DCHECK(PyArray_Check(fields_data[i + fields_data_offset].obj())); + } + + // Construct a dictionary for each row + const bool has_nulls = data.null_count() > 0; + for (int64_t i = 0; i < arr->length(); ++i) { + if (has_nulls && arr->IsNull(i)) { + Py_INCREF(Py_None); + *out_values = Py_None; + } else { + // Build the new dict object for the row + dict_item.reset(PyDict_New()); + RETURN_IF_PYERROR(); + for (int32_t field_idx = 0; field_idx < num_fields; ++field_idx) { + OwnedRef field_value; + auto name = array_type->field(static_cast(field_idx))->name(); + if (!arr->field(static_cast(field_idx))->IsNull(i)) { + // Value exists in child array, obtain it + auto array = reinterpret_cast( + fields_data[field_idx + fields_data_offset].obj()); + auto ptr = reinterpret_cast(PyArray_GETPTR1(array, i)); + field_value.reset(PyArray_GETITEM(array, ptr)); + RETURN_IF_PYERROR(); + } else { + // Translate the Null to a None + Py_INCREF(Py_None); + field_value.reset(Py_None); + } + // PyDict_SetItemString increments reference count + auto setitem_result = + PyDict_SetItemString(dict_item.obj(), name.c_str(), field_value.obj()); + RETURN_IF_PYERROR(); + ARROW_DCHECK_EQ(setitem_result, 0); + } + *out_values = dict_item.obj(); + // Grant ownership to the resulting array + Py_INCREF(*out_values); + } + ++out_values; + } + } + return Status::OK(); +} + +Status DecodeDictionaries(MemoryPool* pool, const std::shared_ptr& dense_type, + ArrayVector* arrays) { + compute::ExecContext ctx(pool); + compute::CastOptions options; + for (size_t i = 0; i < arrays->size(); ++i) { + ARROW_ASSIGN_OR_RAISE((*arrays)[i], + compute::Cast(*(*arrays)[i], dense_type, options, &ctx)); + } + return Status::OK(); +} + +Status DecodeDictionaries(MemoryPool* pool, const std::shared_ptr& dense_type, + std::shared_ptr* array) { + auto chunks = (*array)->chunks(); + RETURN_NOT_OK(DecodeDictionaries(pool, dense_type, &chunks)); + *array = std::make_shared(std::move(chunks), dense_type); + return Status::OK(); +} + +template +enable_if_list_like ConvertListsLike(PandasOptions options, + const ChunkedArray& data, + PyObject** out_values) { + using ListArrayT = typename TypeTraits::ArrayType; + // Get column of underlying value arrays + ArrayVector value_arrays; + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = checked_cast(*data.chunk(c)); + // values() does not account for offsets, so we need to slice into it. + // We can't use Flatten(), because it removes the values behind a null list + // value, and that makes the offsets into original list values and our + // flattened_values array different. + std::shared_ptr flattened_values = arr.values()->Slice( + arr.value_offset(0), arr.value_offset(arr.length()) - arr.value_offset(0)); + if (arr.value_type()->id() == Type::EXTENSION) { + const auto& arr_ext = checked_cast(*flattened_values); + value_arrays.emplace_back(arr_ext.storage()); + } else { + value_arrays.emplace_back(flattened_values); + } + } + + using ListArrayType = typename ListArrayT::TypeClass; + const auto& list_type = checked_cast(*data.type()); + auto value_type = list_type.value_type(); + if (value_type->id() == Type::EXTENSION) { + value_type = checked_cast(*value_type).storage_type(); + } + + auto flat_column = std::make_shared(value_arrays, value_type); + + options = MakeInnerOptions(std::move(options)); + + OwnedRefNoGIL owned_numpy_array; + RETURN_NOT_OK(ConvertChunkedArrayToPandas(options, flat_column, nullptr, + owned_numpy_array.ref())); + PyObject* numpy_array = owned_numpy_array.obj(); + ARROW_DCHECK(PyArray_Check(numpy_array)); + + int64_t chunk_offset = 0; + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = checked_cast(*data.chunk(c)); + const bool has_nulls = data.null_count() > 0; + for (int64_t i = 0; i < arr.length(); ++i) { + if (has_nulls && arr.IsNull(i)) { + Py_INCREF(Py_None); + *out_values = Py_None; + } else { + // Need to subtract value_offset(0) since the original chunk might be a slice + // into another array. + OwnedRef start(PyLong_FromLongLong(arr.value_offset(i) + chunk_offset - + arr.value_offset(0))); + OwnedRef end(PyLong_FromLongLong(arr.value_offset(i + 1) + chunk_offset - + arr.value_offset(0))); + OwnedRef slice(PySlice_New(start.obj(), end.obj(), nullptr)); + + if (ARROW_PREDICT_FALSE(slice.obj() == nullptr)) { + // Fall out of loop, will return from RETURN_IF_PYERROR + break; + } + *out_values = PyObject_GetItem(numpy_array, slice.obj()); + + if (*out_values == nullptr) { + // Fall out of loop, will return from RETURN_IF_PYERROR + break; + } + } + ++out_values; + } + RETURN_IF_PYERROR(); + + chunk_offset += arr.value_offset(arr.length()) - arr.value_offset(0); + } + + return Status::OK(); +} + +// TODO GH-40579: optimize ListView conversion to avoid unnecessary copies +template +enable_if_list_view ConvertListsLike(PandasOptions options, + const ChunkedArray& data, + PyObject** out_values) { + using ListViewArrayType = typename TypeTraits::ArrayType; + using NonViewType = + std::conditional_t; + using NonViewClass = typename TypeTraits::ArrayType; + ArrayVector list_arrays; + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = checked_cast(*data.chunk(c)); + ARROW_ASSIGN_OR_RAISE(auto non_view_array, + NonViewClass::FromListView(arr, options.pool)); + list_arrays.emplace_back(non_view_array); + } + auto chunked_array = std::make_shared(list_arrays); + return ConvertListsLike(options, *chunked_array, out_values); +} + +template +Status ConvertMapHelper(F1 resetRow, F2 addPairToRow, F3 stealRow, + const ChunkedArray& data, PyArrayObject* py_keys, + PyArrayObject* py_items, + // needed for null checks in items + const std::vector> item_arrays, + PyObject** out_values) { + OwnedRef key_value; + OwnedRef item_value; + + int64_t chunk_offset = 0; + for (int c = 0; c < data.num_chunks(); ++c) { + const auto& arr = checked_cast(*data.chunk(c)); + const bool has_nulls = data.null_count() > 0; + + // Make a list of key/item pairs for each row in array + for (int64_t i = 0; i < arr.length(); ++i) { + if (has_nulls && arr.IsNull(i)) { + Py_INCREF(Py_None); + *out_values = Py_None; + } else { + int64_t entry_offset = arr.value_offset(i); + int64_t num_pairs = arr.value_offset(i + 1) - entry_offset; + + // Build the new list object for the row of Python pairs + RETURN_NOT_OK(resetRow(num_pairs)); + + // Add each key/item pair in the row + for (int64_t j = 0; j < num_pairs; ++j) { + // Get key value, key is non-nullable for a valid row + auto ptr_key = reinterpret_cast( + PyArray_GETPTR1(py_keys, chunk_offset + entry_offset + j)); + key_value.reset(PyArray_GETITEM(py_keys, ptr_key)); + RETURN_IF_PYERROR(); + + if (item_arrays[c]->IsNull(entry_offset + j)) { + // Translate the Null to a None + Py_INCREF(Py_None); + item_value.reset(Py_None); + } else { + // Get valid value from item array + auto ptr_item = reinterpret_cast( + PyArray_GETPTR1(py_items, chunk_offset + entry_offset + j)); + item_value.reset(PyArray_GETITEM(py_items, ptr_item)); + RETURN_IF_PYERROR(); + } + + // Add the key/item pair to the row + RETURN_NOT_OK(addPairToRow(j, key_value, item_value)); + } + + // Pass ownership to the resulting array + *out_values = stealRow(); + } + ++out_values; + } + RETURN_IF_PYERROR(); + + chunk_offset += arr.values()->length(); + } + + return Status::OK(); +} + +// A more helpful error message around TypeErrors that may stem from unhashable keys +Status CheckMapAsPydictsTypeError() { + if (ARROW_PREDICT_TRUE(!PyErr_Occurred())) { + return Status::OK(); + } + if (PyErr_ExceptionMatches(PyExc_TypeError)) { + // Modify the error string directly, so it is re-raised + // with our additional info. + // + // There are not many interesting things happening when this + // is hit. This is intended to only be called directly after + // PyDict_SetItem, where a finite set of errors could occur. + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); + std::string message; + RETURN_NOT_OK(internal::PyObject_StdStringStr(value, &message)); + message += + ". If keys are not hashable, then you must use the option " + "[maps_as_pydicts=None (default)]"; + + // resets the error + PyErr_SetString(PyExc_TypeError, message.c_str()); + } + return ConvertPyError(); +} + +Status CheckForDuplicateKeys(bool error_on_duplicate_keys, Py_ssize_t total_dict_len, + Py_ssize_t total_raw_len) { + if (total_dict_len < total_raw_len) { + const char* message = + "[maps_as_pydicts] " + "After conversion of Arrow maps to pydicts, " + "detected data loss due to duplicate keys. " + "Original input length is [%lld], total converted pydict length is [%lld]."; + std::array buf; + std::snprintf(buf.data(), buf.size(), message, total_raw_len, total_dict_len); + + if (error_on_duplicate_keys) { + return Status::UnknownError(buf.data()); + } else { + ARROW_LOG(WARNING) << buf.data(); + } + } + return Status::OK(); +} + +Status ConvertMap(PandasOptions options, const ChunkedArray& data, + PyObject** out_values) { + // Get columns of underlying key/item arrays + std::vector> key_arrays; + std::vector> item_arrays; + for (int c = 0; c < data.num_chunks(); ++c) { + const auto& map_arr = checked_cast(*data.chunk(c)); + key_arrays.emplace_back(map_arr.keys()); + item_arrays.emplace_back(map_arr.items()); + } + + const auto& map_type = checked_cast(*data.type()); + auto key_type = map_type.key_type(); + auto item_type = map_type.item_type(); + + // ARROW-6899: Convert dictionary-encoded children to dense instead of + // failing below. A more efficient conversion than this could be done later + if (key_type->id() == Type::DICTIONARY) { + auto dense_type = checked_cast(*key_type).value_type(); + RETURN_NOT_OK(DecodeDictionaries(options.pool, dense_type, &key_arrays)); + key_type = dense_type; + } + if (item_type->id() == Type::DICTIONARY) { + auto dense_type = checked_cast(*item_type).value_type(); + RETURN_NOT_OK(DecodeDictionaries(options.pool, dense_type, &item_arrays)); + item_type = dense_type; + } + + // See notes in MakeInnerOptions. + options = MakeInnerOptions(std::move(options)); + // Don't blindly convert because timestamps in lists are handled differently. + options.timestamp_as_object = true; + + auto flat_keys = std::make_shared(key_arrays, key_type); + auto flat_items = std::make_shared(item_arrays, item_type); + OwnedRefNoGIL owned_numpy_keys; + RETURN_NOT_OK( + ConvertChunkedArrayToPandas(options, flat_keys, nullptr, owned_numpy_keys.ref())); + OwnedRefNoGIL owned_numpy_items; + RETURN_NOT_OK( + ConvertChunkedArrayToPandas(options, flat_items, nullptr, owned_numpy_items.ref())); + PyArrayObject* py_keys = reinterpret_cast(owned_numpy_keys.obj()); + PyArrayObject* py_items = reinterpret_cast(owned_numpy_items.obj()); + + if (options.maps_as_pydicts == MapConversionType::DEFAULT) { + // The default behavior to express an Arrow MAP as a list of [(key, value), ...] pairs + OwnedRef list_item; + return ConvertMapHelper( + [&list_item](int64_t num_pairs) { + list_item.reset(PyList_New(num_pairs)); + return CheckPyError(); + }, + [&list_item](int64_t idx, OwnedRef& key_value, OwnedRef& item_value) { + PyList_SET_ITEM(list_item.obj(), idx, + PyTuple_Pack(2, key_value.obj(), item_value.obj())); + return CheckPyError(); + }, + [&list_item] { return list_item.detach(); }, data, py_keys, py_items, item_arrays, + out_values); + } else { + // Use a native pydict + OwnedRef dict_item; + Py_ssize_t total_dict_len{0}; + Py_ssize_t total_raw_len{0}; + + bool error_on_duplicate_keys; + if (options.maps_as_pydicts == MapConversionType::LOSSY) { + error_on_duplicate_keys = false; + } else if (options.maps_as_pydicts == MapConversionType::STRICT_) { + error_on_duplicate_keys = true; + } else { + auto val = std::underlying_type_t(options.maps_as_pydicts); + return Status::UnknownError("Received unknown option for maps_as_pydicts: " + + std::to_string(val)); + } + + auto status = ConvertMapHelper( + [&dict_item, &total_raw_len](int64_t num_pairs) { + total_raw_len += num_pairs; + dict_item.reset(PyDict_New()); + return CheckPyError(); + }, + [&dict_item]([[maybe_unused]] int64_t idx, OwnedRef& key_value, + OwnedRef& item_value) { + auto setitem_result = + PyDict_SetItem(dict_item.obj(), key_value.obj(), item_value.obj()); + ARROW_RETURN_NOT_OK(CheckMapAsPydictsTypeError()); + // returns -1 if there are internal errors around hashing/resizing + return setitem_result == 0 ? Status::OK() + : Status::UnknownError( + "[maps_as_pydicts] " + "Unexpected failure inserting Arrow (key, " + "value) pair into Python dict"); + }, + [&dict_item, &total_dict_len] { + total_dict_len += PyDict_Size(dict_item.obj()); + return dict_item.detach(); + }, + data, py_keys, py_items, item_arrays, out_values); + + ARROW_RETURN_NOT_OK(status); + // If there were no errors generating the pydicts, + // then check if we detected any data loss from duplicate keys. + return CheckForDuplicateKeys(error_on_duplicate_keys, total_dict_len, total_raw_len); + } +} + +template +inline void ConvertNumericNullable(const ChunkedArray& data, InType na_value, + OutType* out_values) { + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = *data.chunk(c); + const InType* in_values = GetPrimitiveValues(arr); + + if (arr.null_count() > 0) { + for (int64_t i = 0; i < arr.length(); ++i) { + *out_values++ = arr.IsNull(i) ? na_value : in_values[i]; + } + } else { + memcpy(out_values, in_values, sizeof(InType) * arr.length()); + out_values += arr.length(); + } + } +} + +template +inline void ConvertNumericNullableCast(const ChunkedArray& data, InType na_value, + OutType* out_values) { + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = *data.chunk(c); + const InType* in_values = GetPrimitiveValues(arr); + + for (int64_t i = 0; i < arr.length(); ++i) { + *out_values++ = arr.IsNull(i) ? static_cast(na_value) + : static_cast(in_values[i]); + } + } +} + +template +class TypedPandasWriter : public PandasWriter { + public: + using T = typename npy_traits::value_type; + + using PandasWriter::PandasWriter; + + Status TransferSingle(std::shared_ptr data, PyObject* py_ref) override { + if (CanZeroCopy(*data)) { + PyObject* wrapped; + npy_intp dims[2] = {static_cast(num_columns_), + static_cast(num_rows_)}; + RETURN_NOT_OK( + MakeNumPyView(data->chunk(0), py_ref, NPY_TYPE, /*ndim=*/2, dims, &wrapped)); + SetBlockData(wrapped); + return Status::OK(); + } else { + RETURN_NOT_OK(CheckNotZeroCopyOnly(*data)); + RETURN_NOT_OK(EnsureAllocated()); + return CopyInto(data, /*rel_placement=*/0); + } + } + + Status CheckTypeExact(const DataType& type, Type::type expected) { + if (type.id() != expected) { + return Status::NotImplemented("Cannot write Arrow data of type ", type.ToString(), + " to pandas block with NumPy type ", + GetNumPyTypeName(NPY_TYPE)); + } + return Status::OK(); + } + + T* GetBlockColumnStart(int64_t rel_placement) { + return reinterpret_cast(block_data_) + rel_placement * num_rows_; + } + + protected: + Status Allocate() override { return AllocateNDArray(NPY_TYPE); } +}; + +struct ObjectWriterVisitor { + const PandasOptions& options; + const ChunkedArray& data; + PyObject** out_values; + + Status Visit(const NullType& type) { + for (int c = 0; c < data.num_chunks(); c++) { + std::shared_ptr arr = data.chunk(c); + + for (int64_t i = 0; i < arr->length(); ++i) { + // All values are null + Py_INCREF(Py_None); + *out_values = Py_None; + ++out_values; + } + } + return Status::OK(); + } + + Status Visit(const BooleanType& type) { + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = checked_cast(*data.chunk(c)); + + for (int64_t i = 0; i < arr.length(); ++i) { + if (arr.IsNull(i)) { + Py_INCREF(Py_None); + *out_values++ = Py_None; + } else if (arr.Value(i)) { + // True + Py_INCREF(Py_True); + *out_values++ = Py_True; + } else { + // False + Py_INCREF(Py_False); + *out_values++ = Py_False; + } + } + } + return Status::OK(); + } + + template + enable_if_integer Visit(const Type& type) { + using T = typename Type::c_type; + auto WrapValue = [](T value, PyObject** out) { + *out = std::is_signed::value ? PyLong_FromLongLong(value) + : PyLong_FromUnsignedLongLong(value); + RETURN_IF_PYERROR(); + return Status::OK(); + }; + return ConvertAsPyObjects(options, data, WrapValue, out_values); + } + + template + enable_if_t::value || is_binary_view_like_type::value || + is_fixed_size_binary_type::value, + Status> + Visit(const Type& type) { + auto WrapValue = [](const std::string_view& view, PyObject** out) { + *out = WrapBytes::Wrap(view.data(), view.length()); + if (*out == nullptr) { + PyErr_Clear(); + return Status::UnknownError("Wrapping ", view, " failed"); + } + return Status::OK(); + }; + return ConvertAsPyObjects(options, data, WrapValue, out_values); + } + + template + enable_if_date Visit(const Type& type) { + auto WrapValue = [](typename Type::c_type value, PyObject** out) { + RETURN_NOT_OK(internal::PyDate_from_int(value, Type::UNIT, out)); + RETURN_IF_PYERROR(); + return Status::OK(); + }; + return ConvertAsPyObjects(options, data, WrapValue, out_values); + } + + template + enable_if_time Visit(const Type& type) { + const TimeUnit::type unit = type.unit(); + auto WrapValue = [unit](typename Type::c_type value, PyObject** out) { + RETURN_NOT_OK(internal::PyTime_from_int(value, unit, out)); + RETURN_IF_PYERROR(); + return Status::OK(); + }; + return ConvertAsPyObjects(options, data, WrapValue, out_values); + } + + template + enable_if_timestamp Visit(const Type& type) { + const TimeUnit::type unit = type.unit(); + OwnedRef tzinfo; + + auto ConvertTimezoneNaive = [&](typename Type::c_type value, PyObject** out) { + RETURN_NOT_OK(internal::PyDateTime_from_int(value, unit, out)); + RETURN_IF_PYERROR(); + return Status::OK(); + }; + auto ConvertTimezoneAware = [&](typename Type::c_type value, PyObject** out) { + PyObject* naive_datetime; + RETURN_NOT_OK(ConvertTimezoneNaive(value, &naive_datetime)); + + // convert the timezone naive datetime object to timezone aware + // two step conversion of the datetime mimics Python's code: + // dt.replace(tzinfo=datetime.timezone.utc).astimezone(tzinfo) + // first step: replacing timezone with timezone.utc (replace method) + OwnedRef args(PyTuple_New(0)); + OwnedRef keywords(PyDict_New()); + PyDict_SetItemString(keywords.obj(), "tzinfo", PyDateTime_TimeZone_UTC); + OwnedRef naive_datetime_replace(PyObject_GetAttrString(naive_datetime, "replace")); + OwnedRef datetime_utc( + PyObject_Call(naive_datetime_replace.obj(), args.obj(), keywords.obj())); + // second step: adjust the datetime to tzinfo timezone (astimezone method) + *out = PyObject_CallMethod(datetime_utc.obj(), "astimezone", "O", tzinfo.obj()); + + // the timezone naive object is no longer required + Py_DECREF(naive_datetime); + RETURN_IF_PYERROR(); + + return Status::OK(); + }; + + if (!type.timezone().empty() && !options.ignore_timezone) { + // convert timezone aware + PyObject* tzobj; + ARROW_ASSIGN_OR_RAISE(tzobj, internal::StringToTzinfo(type.timezone())); + tzinfo.reset(tzobj); + RETURN_IF_PYERROR(); + RETURN_NOT_OK( + ConvertAsPyObjects(options, data, ConvertTimezoneAware, out_values)); + } else { + // convert timezone naive + RETURN_NOT_OK( + ConvertAsPyObjects(options, data, ConvertTimezoneNaive, out_values)); + } + + return Status::OK(); + } + + template + enable_if_t::value, Status> Visit( + const Type& type) { + OwnedRef args(PyTuple_New(0)); + OwnedRef kwargs(PyDict_New()); + RETURN_IF_PYERROR(); + auto to_date_offset = [&](const MonthDayNanoIntervalType::MonthDayNanos& interval, + PyObject** out) { + ARROW_DCHECK(internal::BorrowPandasDataOffsetType() != nullptr); + // DateOffset objects do not add nanoseconds component to pd.Timestamp. + // as of Pandas 1.3.3 + // (https://github.com/pandas-dev/pandas/issues/43892). + // So convert microseconds and remainder to preserve data + // but give users more expected results. + int64_t microseconds = interval.nanoseconds / 1000; + int64_t nanoseconds; + if (interval.nanoseconds >= 0) { + nanoseconds = interval.nanoseconds % 1000; + } else { + nanoseconds = -((-interval.nanoseconds) % 1000); + } + + PyDict_SetItemString(kwargs.obj(), "months", PyLong_FromLong(interval.months)); + PyDict_SetItemString(kwargs.obj(), "days", PyLong_FromLong(interval.days)); + PyDict_SetItemString(kwargs.obj(), "microseconds", + PyLong_FromLongLong(microseconds)); + PyDict_SetItemString(kwargs.obj(), "nanoseconds", PyLong_FromLongLong(nanoseconds)); + *out = + PyObject_Call(internal::BorrowPandasDataOffsetType(), args.obj(), kwargs.obj()); + RETURN_IF_PYERROR(); + return Status::OK(); + }; + return ConvertAsPyObjects(options, data, to_date_offset, + out_values); + } + + template + Status VisitDecimal(const DecimalT& type) { + OwnedRef decimal; + OwnedRef Decimal; + RETURN_NOT_OK(internal::ImportModule("decimal", &decimal)); + RETURN_NOT_OK(internal::ImportFromModule(decimal.obj(), "Decimal", &Decimal)); + PyObject* decimal_constructor = Decimal.obj(); + + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = checked_cast(*data.chunk(c)); + + for (int64_t i = 0; i < arr.length(); ++i) { + if (arr.IsNull(i)) { + Py_INCREF(Py_None); + *out_values++ = Py_None; + } else { + *out_values++ = + internal::DecimalFromString(decimal_constructor, arr.FormatValue(i)); + RETURN_IF_PYERROR(); + } + } + } + + return Status::OK(); + } + + Status Visit(const Decimal32Type& type) { + return VisitDecimal(type); + } + + Status Visit(const Decimal64Type& type) { + return VisitDecimal(type); + } + + Status Visit(const Decimal128Type& type) { + return VisitDecimal(type); + } + + Status Visit(const Decimal256Type& type) { + return VisitDecimal(type); + } + + template + enable_if_t::value || is_list_view_type::value, Status> Visit( + const T& type) { + if (!ListTypeSupported(*type.value_type())) { + return Status::NotImplemented( + "Not implemented type for conversion from List to Pandas: ", + type.value_type()->ToString()); + } + return ConvertListsLike(options, data, out_values); + } + + Status Visit(const MapType& type) { return ConvertMap(options, data, out_values); } + + Status Visit(const StructType& type) { + return ConvertStruct(options, data, out_values); + } + + template + enable_if_t::value || + std::is_same::value || + std::is_same::value || + std::is_same::value || + std::is_same::value || + (std::is_base_of::value && + !std::is_same::value) || + std::is_base_of::value, + Status> + Visit(const Type& type) { + return Status::NotImplemented("No implemented conversion to object dtype: ", + type.ToString()); + } +}; + +class ObjectWriter : public TypedPandasWriter { + public: + using TypedPandasWriter::TypedPandasWriter; + Status CopyInto(std::shared_ptr data, int64_t rel_placement) override { + PyAcquireGIL lock; + ObjectWriterVisitor visitor{this->options_, *data, + this->GetBlockColumnStart(rel_placement)}; + return VisitTypeInline(*data->type(), &visitor); + } +}; + +static inline bool IsNonNullContiguous(const ChunkedArray& data) { + return data.num_chunks() == 1 && data.null_count() == 0; +} + +template +class IntWriter : public TypedPandasWriter { + public: + using ArrowType = typename npy_traits::TypeClass; + using TypedPandasWriter::TypedPandasWriter; + + bool CanZeroCopy(const ChunkedArray& data) const override { + return IsNonNullContiguous(data); + } + + Status CopyInto(std::shared_ptr data, int64_t rel_placement) override { + RETURN_NOT_OK(this->CheckTypeExact(*data->type(), ArrowType::type_id)); + ConvertIntegerNoNullsSameType( + this->options_, *data, this->GetBlockColumnStart(rel_placement)); + return Status::OK(); + } +}; + +template +class FloatWriter : public TypedPandasWriter { + public: + using ArrowType = typename npy_traits::TypeClass; + using TypedPandasWriter::TypedPandasWriter; + using T = typename ArrowType::c_type; + + bool CanZeroCopy(const ChunkedArray& data) const override { + return IsNonNullContiguous(data) && data.type()->id() == ArrowType::type_id; + } + + Status CopyInto(std::shared_ptr data, int64_t rel_placement) override { + Type::type in_type = data->type()->id(); + auto out_values = this->GetBlockColumnStart(rel_placement); + +#define INTEGER_CASE(IN_TYPE) \ + ConvertIntegerWithNulls(this->options_, *data, out_values); \ + break; + + switch (in_type) { + case Type::UINT8: + INTEGER_CASE(uint8_t); + case Type::INT8: + INTEGER_CASE(int8_t); + case Type::UINT16: + INTEGER_CASE(uint16_t); + case Type::INT16: + INTEGER_CASE(int16_t); + case Type::UINT32: + INTEGER_CASE(uint32_t); + case Type::INT32: + INTEGER_CASE(int32_t); + case Type::UINT64: + INTEGER_CASE(uint64_t); + case Type::INT64: + INTEGER_CASE(int64_t); + case Type::HALF_FLOAT: + ConvertNumericNullableCast(*data, npy_traits::na_sentinel, out_values); + case Type::FLOAT: + ConvertNumericNullableCast(*data, npy_traits::na_sentinel, out_values); + break; + case Type::DOUBLE: + ConvertNumericNullableCast(*data, npy_traits::na_sentinel, out_values); + break; + default: + return Status::NotImplemented("Cannot write Arrow data of type ", + data->type()->ToString(), + " to a Pandas floating point block"); + } + +#undef INTEGER_CASE + + return Status::OK(); + } +}; + +using UInt8Writer = IntWriter; +using Int8Writer = IntWriter; +using UInt16Writer = IntWriter; +using Int16Writer = IntWriter; +using UInt32Writer = IntWriter; +using Int32Writer = IntWriter; +using UInt64Writer = IntWriter; +using Int64Writer = IntWriter; +using Float16Writer = FloatWriter; +using Float32Writer = FloatWriter; +using Float64Writer = FloatWriter; + +class BoolWriter : public TypedPandasWriter { + public: + using TypedPandasWriter::TypedPandasWriter; + + Status TransferSingle(std::shared_ptr data, PyObject* py_ref) override { + RETURN_NOT_OK( + CheckNoZeroCopy("Zero copy conversions not possible with " + "boolean types")); + RETURN_NOT_OK(EnsureAllocated()); + return CopyInto(data, /*rel_placement=*/0); + } + + Status CopyInto(std::shared_ptr data, int64_t rel_placement) override { + RETURN_NOT_OK(this->CheckTypeExact(*data->type(), Type::BOOL)); + auto out_values = this->GetBlockColumnStart(rel_placement); + for (int c = 0; c < data->num_chunks(); c++) { + const auto& arr = checked_cast(*data->chunk(c)); + for (int64_t i = 0; i < arr.length(); ++i) { + *out_values++ = static_cast(arr.Value(i)); + } + } + return Status::OK(); + } +}; + +// ---------------------------------------------------------------------- +// Date / timestamp types + +template +inline void ConvertDatetime(const ChunkedArray& data, int64_t* out_values) { + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = *data.chunk(c); + const T* in_values = GetPrimitiveValues(arr); + + for (int64_t i = 0; i < arr.length(); ++i) { + *out_values++ = arr.IsNull(i) ? kPandasTimestampNull + : (static_cast(in_values[i]) * SHIFT); + } + } +} + +template +void ConvertDatesShift(const ChunkedArray& data, int64_t* out_values) { + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = *data.chunk(c); + const T* in_values = GetPrimitiveValues(arr); + for (int64_t i = 0; i < arr.length(); ++i) { + *out_values++ = arr.IsNull(i) ? kPandasTimestampNull + : static_cast(in_values[i]) / SHIFT; + } + } +} + +class DatetimeDayWriter : public TypedPandasWriter { + public: + using TypedPandasWriter::TypedPandasWriter; + + Status CopyInto(std::shared_ptr data, int64_t rel_placement) override { + int64_t* out_values = this->GetBlockColumnStart(rel_placement); + const auto& type = checked_cast(*data->type()); + switch (type.unit()) { + case DateUnit::DAY: + ConvertDatesShift(*data, out_values); + break; + case DateUnit::MILLI: + ConvertDatesShift(*data, out_values); + break; + } + return Status::OK(); + } + + protected: + Status Allocate() override { + RETURN_NOT_OK(this->AllocateNDArray(NPY_DATETIME)); + SetDatetimeUnit(NPY_FR_D); + return Status::OK(); + } +}; + +template +class DatetimeWriter : public TypedPandasWriter { + public: + using TypedPandasWriter::TypedPandasWriter; + + bool CanZeroCopy(const ChunkedArray& data) const override { + if (data.type()->id() == Type::TIMESTAMP) { + const auto& type = checked_cast(*data.type()); + return IsNonNullContiguous(data) && type.unit() == UNIT; + } else { + return false; + } + } + + Status CopyInto(std::shared_ptr data, int64_t rel_placement) override { + const auto& ts_type = checked_cast(*data->type()); + ARROW_DCHECK_EQ(UNIT, ts_type.unit()) << "Should only call instances of this writer " + << "with arrays of the correct unit"; + ConvertNumericNullable(*data, kPandasTimestampNull, + this->GetBlockColumnStart(rel_placement)); + return Status::OK(); + } + + protected: + Status Allocate() override { + RETURN_NOT_OK(this->AllocateNDArray(NPY_DATETIME)); + SetDatetimeUnit(internal::NumPyFrequency(UNIT)); + return Status::OK(); + } +}; + +using DatetimeSecondWriter = DatetimeWriter; + +class DatetimeMilliWriter : public DatetimeWriter { + public: + using DatetimeWriter::DatetimeWriter; + + Status CopyInto(std::shared_ptr data, int64_t rel_placement) override { + Type::type type = data->type()->id(); + int64_t* out_values = this->GetBlockColumnStart(rel_placement); + if (type == Type::DATE32) { + // Convert from days since epoch to datetime64[ms] + ConvertDatetime(*data, out_values); + } else if (type == Type::DATE64) { + ConvertNumericNullable(*data, kPandasTimestampNull, out_values); + } else { + const auto& ts_type = checked_cast(*data->type()); + ARROW_DCHECK_EQ(TimeUnit::MILLI, ts_type.unit()) + << "Should only call instances of this writer " + << "with arrays of the correct unit"; + ConvertNumericNullable(*data, kPandasTimestampNull, out_values); + } + return Status::OK(); + } +}; + +using DatetimeMicroWriter = DatetimeWriter; + +class DatetimeNanoWriter : public DatetimeWriter { + public: + using DatetimeWriter::DatetimeWriter; + + Status CopyInto(std::shared_ptr data, int64_t rel_placement) override { + Type::type type = data->type()->id(); + int64_t* out_values = this->GetBlockColumnStart(rel_placement); + compute::ExecContext ctx(options_.pool); + compute::CastOptions options; + if (options_.safe_cast) { + options = compute::CastOptions::Safe(); + } else { + options = compute::CastOptions::Unsafe(); + } + Datum out; + auto target_type = timestamp(TimeUnit::NANO); + + if (type == Type::DATE32) { + // Convert from days since epoch to datetime64[ns] + ConvertDatetime(*data, out_values); + } else if (type == Type::DATE64) { + // Date64Type is millisecond timestamp stored as int64_t + // TODO(wesm): Do we want to make sure to zero out the milliseconds? + ConvertDatetime(*data, out_values); + } else if (type == Type::TIMESTAMP) { + const auto& ts_type = checked_cast(*data->type()); + + if (ts_type.unit() == TimeUnit::NANO) { + ConvertNumericNullable(*data, kPandasTimestampNull, out_values); + } else if (ts_type.unit() == TimeUnit::MICRO || ts_type.unit() == TimeUnit::MILLI || + ts_type.unit() == TimeUnit::SECOND) { + ARROW_ASSIGN_OR_RAISE(out, compute::Cast(data, target_type, options, &ctx)); + ConvertNumericNullable(*out.chunked_array(), kPandasTimestampNull, + out_values); + } else { + return Status::NotImplemented("Unsupported time unit"); + } + } else { + return Status::NotImplemented("Cannot write Arrow data of type ", + data->type()->ToString(), + " to a Pandas datetime block."); + } + return Status::OK(); + } +}; + +template +class DatetimeTZWriter : public BASE { + public: + DatetimeTZWriter(const PandasOptions& options, const std::string& timezone, + int64_t num_rows) + : BASE(options, num_rows, 1), timezone_(timezone) {} + + protected: + Status GetResultBlock(PyObject** out) override { + RETURN_NOT_OK(this->MakeBlock1D()); + *out = this->block_arr_.obj(); + return Status::OK(); + } + + Status AddResultMetadata(PyObject* result) override { + PyObject* py_tz = PyUnicode_FromStringAndSize( + timezone_.c_str(), static_cast(timezone_.size())); + RETURN_IF_PYERROR(); + PyDict_SetItemString(result, "timezone", py_tz); + Py_DECREF(py_tz); + return Status::OK(); + } + + private: + std::string timezone_; +}; + +using DatetimeSecondTZWriter = DatetimeTZWriter; +using DatetimeMilliTZWriter = DatetimeTZWriter; +using DatetimeMicroTZWriter = DatetimeTZWriter; +using DatetimeNanoTZWriter = DatetimeTZWriter; + +template +class TimedeltaWriter : public TypedPandasWriter { + public: + using TypedPandasWriter::TypedPandasWriter; + + Status AllocateTimedelta(int ndim) { + RETURN_NOT_OK(this->AllocateNDArray(NPY_TIMEDELTA, ndim)); + SetDatetimeUnit(internal::NumPyFrequency(UNIT)); + return Status::OK(); + } + + bool CanZeroCopy(const ChunkedArray& data) const override { + const auto& type = checked_cast(*data.type()); + return IsNonNullContiguous(data) && type.unit() == UNIT; + } + + Status CopyInto(std::shared_ptr data, int64_t rel_placement) override { + const auto& type = checked_cast(*data->type()); + ARROW_DCHECK_EQ(UNIT, type.unit()) << "Should only call instances of this writer " + << "with arrays of the correct unit"; + ConvertNumericNullable(*data, kPandasTimestampNull, + this->GetBlockColumnStart(rel_placement)); + return Status::OK(); + } + + protected: + Status Allocate() override { return AllocateTimedelta(2); } +}; + +using TimedeltaSecondWriter = TimedeltaWriter; +using TimedeltaMilliWriter = TimedeltaWriter; +using TimedeltaMicroWriter = TimedeltaWriter; + +class TimedeltaNanoWriter : public TimedeltaWriter { + public: + using TimedeltaWriter::TimedeltaWriter; + + Status CopyInto(std::shared_ptr data, int64_t rel_placement) override { + Type::type type = data->type()->id(); + int64_t* out_values = this->GetBlockColumnStart(rel_placement); + if (type == Type::DURATION) { + const auto& ts_type = checked_cast(*data->type()); + if (ts_type.unit() == TimeUnit::NANO) { + ConvertNumericNullable(*data, kPandasTimestampNull, out_values); + } else if (ts_type.unit() == TimeUnit::MICRO) { + ConvertDatetime(*data, out_values); + } else if (ts_type.unit() == TimeUnit::MILLI) { + ConvertDatetime(*data, out_values); + } else if (ts_type.unit() == TimeUnit::SECOND) { + ConvertDatetime(*data, out_values); + } else { + return Status::NotImplemented("Unsupported time unit"); + } + } else { + return Status::NotImplemented("Cannot write Arrow data of type ", + data->type()->ToString(), + " to a Pandas timedelta block."); + } + return Status::OK(); + } +}; + +Status MakeZeroLengthArray(const std::shared_ptr& type, + std::shared_ptr* out) { + std::unique_ptr builder; + RETURN_NOT_OK(MakeBuilder(default_memory_pool(), type, &builder)); + RETURN_NOT_OK(builder->Resize(0)); + return builder->Finish(out); +} + +bool NeedDictionaryUnification(const ChunkedArray& data) { + if (data.num_chunks() < 2) { + return false; + } + const auto& arr_first = checked_cast(*data.chunk(0)); + for (int c = 1; c < data.num_chunks(); c++) { + const auto& arr = checked_cast(*data.chunk(c)); + if (!(arr_first.dictionary()->Equals(arr.dictionary()))) { + return true; + } + } + return false; +} + +template +class CategoricalWriter + : public TypedPandasWriter::npy_type> { + public: + using TRAITS = arrow_traits; + using ArrayType = typename TypeTraits::ArrayType; + using T = typename TRAITS::T; + + explicit CategoricalWriter(const PandasOptions& options, int64_t num_rows) + : TypedPandasWriter(options, num_rows, 1), + ordered_(false), + needs_copy_(false) {} + + Status CopyInto(std::shared_ptr data, int64_t rel_placement) override { + return Status::NotImplemented("categorical type"); + } + + Status TransferSingle(std::shared_ptr data, PyObject* py_ref) override { + const auto& dict_type = checked_cast(*data->type()); + std::shared_ptr dict; + if (data->num_chunks() == 0) { + // no dictionary values => create empty array + RETURN_NOT_OK(this->AllocateNDArray(TRAITS::npy_type, 1)); + RETURN_NOT_OK(MakeZeroLengthArray(dict_type.value_type(), &dict)); + } else { + ARROW_DCHECK_EQ(IndexType::type_id, dict_type.index_type()->id()); + RETURN_NOT_OK(WriteIndices(*data, &dict)); + } + + PyObject* pydict; + RETURN_NOT_OK(ConvertArrayToPandas(this->options_, dict, nullptr, &pydict)); + dictionary_.reset(pydict); + ordered_ = dict_type.ordered(); + return Status::OK(); + } + + Status Write(std::shared_ptr data, int64_t abs_placement, + int64_t rel_placement) override { + RETURN_NOT_OK(this->EnsurePlacementAllocated()); + RETURN_NOT_OK(TransferSingle(data, /*py_ref=*/nullptr)); + this->placement_data_[rel_placement] = abs_placement; + return Status::OK(); + } + + Status GetSeriesResult(PyObject** out) override { + PyAcquireGIL lock; + + PyObject* result = PyDict_New(); + RETURN_IF_PYERROR(); + + // Expected single array dictionary layout + PyDict_SetItemString(result, "indices", this->block_arr_.obj()); + RETURN_IF_PYERROR(); + RETURN_NOT_OK(AddResultMetadata(result)); + + *out = result; + return Status::OK(); + } + + protected: + Status AddResultMetadata(PyObject* result) override { + PyDict_SetItemString(result, "dictionary", dictionary_.obj()); + PyObject* py_ordered = ordered_ ? Py_True : Py_False; + Py_INCREF(py_ordered); + PyDict_SetItemString(result, "ordered", py_ordered); + return Status::OK(); + } + + Status WriteIndicesUniform(const ChunkedArray& data) { + // For unsigned types, upcast to signed since pandas uses -1 for nulls + // uint8 to int16, uint16 to int32, uint32 to int64, signed types unchanged + using OutputType = std::conditional_t< + std::is_same::value, int16_t, + std::conditional_t< + std::is_same::value, int32_t, + std::conditional_t::value, int64_t, T>>>; + const int npy_output_type = std::is_same::value ? NPY_INT16 + : std::is_same::value ? NPY_INT32 + : std::is_same::value + ? NPY_INT64 + : TRAITS::npy_type; + + RETURN_NOT_OK(this->AllocateNDArray(npy_output_type, 1)); + auto out_values = reinterpret_cast(this->block_data_); + + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = checked_cast(*data.chunk(c)); + const auto& indices = checked_cast(*arr.indices()); + auto values = reinterpret_cast(indices.raw_values()); + + RETURN_NOT_OK(CheckIndexBounds(*indices.data(), arr.dictionary()->length())); + // Null is -1 in CategoricalBlock + for (int i = 0; i < arr.length(); ++i) { + if (indices.IsValid(i)) { + *out_values++ = static_cast(values[i]); + } else { + *out_values++ = -1; + } + } + } + return Status::OK(); + } + + Status WriteIndicesVarying(const ChunkedArray& data, std::shared_ptr* out_dict) { + // Yield int32 indices to allow for dictionary outgrowing the current index + // type + RETURN_NOT_OK(this->AllocateNDArray(NPY_INT32, 1)); + auto out_values = reinterpret_cast(this->block_data_); + + const auto& dict_type = checked_cast(*data.type()); + + ARROW_ASSIGN_OR_RAISE(auto unifier, DictionaryUnifier::Make(dict_type.value_type(), + this->options_.pool)); + for (int c = 0; c < data.num_chunks(); c++) { + const auto& arr = checked_cast(*data.chunk(c)); + const auto& indices = checked_cast(*arr.indices()); + auto values = reinterpret_cast(indices.raw_values()); + + std::shared_ptr transpose_buffer; + RETURN_NOT_OK(unifier->Unify(*arr.dictionary(), &transpose_buffer)); + + auto transpose = reinterpret_cast(transpose_buffer->data()); + int64_t dict_length = arr.dictionary()->length(); + + RETURN_NOT_OK(CheckIndexBounds(*indices.data(), dict_length)); + + // Null is -1 in CategoricalBlock + for (int i = 0; i < arr.length(); ++i) { + if (indices.IsValid(i)) { + *out_values++ = transpose[values[i]]; + } else { + *out_values++ = -1; + } + } + } + + std::shared_ptr unused_type; + return unifier->GetResult(&unused_type, out_dict); + } + + Status WriteIndices(const ChunkedArray& data, std::shared_ptr* out_dict) { + ARROW_DCHECK_GT(data.num_chunks(), 0); + + // Sniff the first chunk + const auto& arr_first = checked_cast(*data.chunk(0)); + const auto indices_first = std::static_pointer_cast(arr_first.indices()); + + // For unsigned types, we need to convert to signed for pandas compatibility + // even when there are no nulls, so we skip the fast path + const bool is_unsigned = std::is_unsigned::value; + + if (data.num_chunks() == 1 && indices_first->null_count() == 0 && !is_unsigned) { + RETURN_NOT_OK( + CheckIndexBounds(*indices_first->data(), arr_first.dictionary()->length())); + + PyObject* wrapped; + npy_intp dims[1] = {static_cast(this->num_rows_)}; + RETURN_NOT_OK(MakeNumPyView(indices_first, /*py_ref=*/nullptr, TRAITS::npy_type, + /*ndim=*/1, dims, &wrapped)); + this->SetBlockData(wrapped); + *out_dict = arr_first.dictionary(); + } else { + RETURN_NOT_OK(this->CheckNotZeroCopyOnly(data)); + if (NeedDictionaryUnification(data)) { + RETURN_NOT_OK(WriteIndicesVarying(data, out_dict)); + } else { + RETURN_NOT_OK(WriteIndicesUniform(data)); + *out_dict = arr_first.dictionary(); + } + } + return Status::OK(); + } + + OwnedRefNoGIL dictionary_; + bool ordered_; + bool needs_copy_; +}; + +class ExtensionWriter : public PandasWriter { + public: + using PandasWriter::PandasWriter; + + Status Allocate() override { + // no-op + return Status::OK(); + } + + Status TransferSingle(std::shared_ptr data, PyObject* py_ref) override { + PyAcquireGIL lock; + PyObject* py_array; + py_array = wrap_chunked_array(data); + py_array_.reset(py_array); + + return Status::OK(); + } + + Status CopyInto(std::shared_ptr data, int64_t rel_placement) override { + return TransferSingle(data, nullptr); + } + + Status GetDataFrameResult(PyObject** out) override { + PyAcquireGIL lock; + PyObject* result = PyDict_New(); + RETURN_IF_PYERROR(); + + PyDict_SetItemString(result, "py_array", py_array_.obj()); + PyDict_SetItemString(result, "placement", placement_arr_.obj()); + *out = result; + return Status::OK(); + } + + Status GetSeriesResult(PyObject** out) override { + *out = py_array_.detach(); + return Status::OK(); + } + + protected: + OwnedRefNoGIL py_array_; +}; + +Status MakeWriter(const PandasOptions& options, PandasWriter::type writer_type, + const DataType& type, int64_t num_rows, int num_columns, + std::shared_ptr* writer) { +#define BLOCK_CASE(NAME, TYPE) \ + case PandasWriter::NAME: \ + *writer = std::make_shared(options, num_rows, num_columns); \ + break; + +#define CATEGORICAL_CASE(TYPE) \ + case TYPE::type_id: \ + *writer = std::make_shared>(options, num_rows); \ + break; + +#define TZ_CASE(NAME, TYPE) \ + case PandasWriter::NAME: { \ + const auto& ts_type = checked_cast(type); \ + *writer = std::make_shared(options, ts_type.timezone(), num_rows); \ + } break; + + switch (writer_type) { + case PandasWriter::CATEGORICAL: { + const auto& index_type = *checked_cast(type).index_type(); + switch (index_type.id()) { + CATEGORICAL_CASE(Int8Type); + CATEGORICAL_CASE(Int16Type); + CATEGORICAL_CASE(Int32Type); + CATEGORICAL_CASE(Int64Type); + CATEGORICAL_CASE(UInt8Type); + CATEGORICAL_CASE(UInt16Type); + CATEGORICAL_CASE(UInt32Type); + case Type::UINT64: + return Status::TypeError( + "Converting UInt64 dictionary indices to pandas is not supported."); + default: + // Unreachable + ARROW_DCHECK(false); + break; + } + } break; + case PandasWriter::EXTENSION: + *writer = std::make_shared(options, num_rows, num_columns); + break; + BLOCK_CASE(OBJECT, ObjectWriter); + BLOCK_CASE(UINT8, UInt8Writer); + BLOCK_CASE(INT8, Int8Writer); + BLOCK_CASE(UINT16, UInt16Writer); + BLOCK_CASE(INT16, Int16Writer); + BLOCK_CASE(UINT32, UInt32Writer); + BLOCK_CASE(INT32, Int32Writer); + BLOCK_CASE(UINT64, UInt64Writer); + BLOCK_CASE(INT64, Int64Writer); + BLOCK_CASE(HALF_FLOAT, Float16Writer); + BLOCK_CASE(FLOAT, Float32Writer); + BLOCK_CASE(DOUBLE, Float64Writer); + BLOCK_CASE(BOOL, BoolWriter); + BLOCK_CASE(DATETIME_DAY, DatetimeDayWriter); + BLOCK_CASE(DATETIME_SECOND, DatetimeSecondWriter); + BLOCK_CASE(DATETIME_MILLI, DatetimeMilliWriter); + BLOCK_CASE(DATETIME_MICRO, DatetimeMicroWriter); + BLOCK_CASE(DATETIME_NANO, DatetimeNanoWriter); + BLOCK_CASE(TIMEDELTA_SECOND, TimedeltaSecondWriter); + BLOCK_CASE(TIMEDELTA_MILLI, TimedeltaMilliWriter); + BLOCK_CASE(TIMEDELTA_MICRO, TimedeltaMicroWriter); + BLOCK_CASE(TIMEDELTA_NANO, TimedeltaNanoWriter); + TZ_CASE(DATETIME_SECOND_TZ, DatetimeSecondTZWriter); + TZ_CASE(DATETIME_MILLI_TZ, DatetimeMilliTZWriter); + TZ_CASE(DATETIME_MICRO_TZ, DatetimeMicroTZWriter); + TZ_CASE(DATETIME_NANO_TZ, DatetimeNanoTZWriter); + default: + return Status::NotImplemented("Unsupported block type"); + } + +#undef BLOCK_CASE +#undef CATEGORICAL_CASE + + return Status::OK(); +} + +static Status GetPandasWriterType(const ChunkedArray& data, const PandasOptions& options, + PandasWriter::type* output_type) { +#define INTEGER_CASE(NAME) \ + *output_type = \ + data.null_count() > 0 \ + ? options.integer_object_nulls ? PandasWriter::OBJECT : PandasWriter::DOUBLE \ + : PandasWriter::NAME; \ + break; + + switch (data.type()->id()) { + case Type::BOOL: + *output_type = data.null_count() > 0 ? PandasWriter::OBJECT : PandasWriter::BOOL; + break; + case Type::UINT8: + INTEGER_CASE(UINT8); + case Type::INT8: + INTEGER_CASE(INT8); + case Type::UINT16: + INTEGER_CASE(UINT16); + case Type::INT16: + INTEGER_CASE(INT16); + case Type::UINT32: + INTEGER_CASE(UINT32); + case Type::INT32: + INTEGER_CASE(INT32); + case Type::UINT64: + INTEGER_CASE(UINT64); + case Type::INT64: + INTEGER_CASE(INT64); + case Type::HALF_FLOAT: + *output_type = PandasWriter::HALF_FLOAT; + break; + case Type::FLOAT: + *output_type = PandasWriter::FLOAT; + break; + case Type::DOUBLE: + *output_type = PandasWriter::DOUBLE; + break; + case Type::STRING: // fall through + case Type::LARGE_STRING: // fall through + case Type::STRING_VIEW: // fall through + case Type::BINARY: // fall through + case Type::LARGE_BINARY: + case Type::BINARY_VIEW: + case Type::NA: // fall through + case Type::FIXED_SIZE_BINARY: // fall through + case Type::STRUCT: // fall through + case Type::TIME32: // fall through + case Type::TIME64: // fall through + case Type::DECIMAL32: // fall through + case Type::DECIMAL64: // fall through + case Type::DECIMAL128: // fall through + case Type::DECIMAL256: // fall through + case Type::INTERVAL_MONTH_DAY_NANO: // fall through + *output_type = PandasWriter::OBJECT; + break; + case Type::DATE32: + if (options.date_as_object) { + *output_type = PandasWriter::OBJECT; + } else if (options.coerce_temporal_nanoseconds) { + *output_type = PandasWriter::DATETIME_NANO; + } else if (options.to_numpy) { + // Numpy supports Day, but Pandas does not + *output_type = PandasWriter::DATETIME_DAY; + } else { + *output_type = PandasWriter::DATETIME_MILLI; + } + break; + case Type::DATE64: + if (options.date_as_object) { + *output_type = PandasWriter::OBJECT; + } else if (options.coerce_temporal_nanoseconds) { + *output_type = PandasWriter::DATETIME_NANO; + } else { + *output_type = PandasWriter::DATETIME_MILLI; + } + break; + case Type::TIMESTAMP: { + const auto& ts_type = checked_cast(*data.type()); + if (options.timestamp_as_object && ts_type.unit() != TimeUnit::NANO) { + // Nanoseconds are never out of bounds for pandas, so in that case + // we don't convert to object + *output_type = PandasWriter::OBJECT; + } else if (options.coerce_temporal_nanoseconds) { + if (!ts_type.timezone().empty()) { + *output_type = PandasWriter::DATETIME_NANO_TZ; + } else { + *output_type = PandasWriter::DATETIME_NANO; + } + } else { + if (!ts_type.timezone().empty()) { + switch (ts_type.unit()) { + case TimeUnit::SECOND: + *output_type = PandasWriter::DATETIME_SECOND_TZ; + break; + case TimeUnit::MILLI: + *output_type = PandasWriter::DATETIME_MILLI_TZ; + break; + case TimeUnit::MICRO: + *output_type = PandasWriter::DATETIME_MICRO_TZ; + break; + case TimeUnit::NANO: + *output_type = PandasWriter::DATETIME_NANO_TZ; + break; + } + } else { + switch (ts_type.unit()) { + case TimeUnit::SECOND: + *output_type = PandasWriter::DATETIME_SECOND; + break; + case TimeUnit::MILLI: + *output_type = PandasWriter::DATETIME_MILLI; + break; + case TimeUnit::MICRO: + *output_type = PandasWriter::DATETIME_MICRO; + break; + case TimeUnit::NANO: + *output_type = PandasWriter::DATETIME_NANO; + break; + } + } + } + } break; + case Type::DURATION: { + const auto& dur_type = checked_cast(*data.type()); + if (options.coerce_temporal_nanoseconds) { + *output_type = PandasWriter::TIMEDELTA_NANO; + } else { + switch (dur_type.unit()) { + case TimeUnit::SECOND: + *output_type = PandasWriter::TIMEDELTA_SECOND; + break; + case TimeUnit::MILLI: + *output_type = PandasWriter::TIMEDELTA_MILLI; + break; + case TimeUnit::MICRO: + *output_type = PandasWriter::TIMEDELTA_MICRO; + break; + case TimeUnit::NANO: + *output_type = PandasWriter::TIMEDELTA_NANO; + break; + } + } + } break; + case Type::FIXED_SIZE_LIST: + case Type::LIST: + case Type::LARGE_LIST: + case Type::LIST_VIEW: + case Type::LARGE_LIST_VIEW: + case Type::MAP: { + auto list_type = std::static_pointer_cast(data.type()); + if (!ListTypeSupported(*list_type->value_type())) { + return Status::NotImplemented("Not implemented type for Arrow list to pandas: ", + list_type->value_type()->ToString()); + } + *output_type = PandasWriter::OBJECT; + } break; + case Type::DICTIONARY: + *output_type = PandasWriter::CATEGORICAL; + break; + case Type::EXTENSION: + *output_type = PandasWriter::EXTENSION; + break; + default: + return Status::NotImplemented( + "No known equivalent Pandas block for Arrow data of type ", + data.type()->ToString(), " is known."); + } + return Status::OK(); +} + +// Construct the exact pandas "BlockManager" memory layout +// +// * For each column determine the correct output pandas type +// * Allocate 2D blocks (ncols x nrows) for each distinct data type in output +// * Allocate block placement arrays +// * Write Arrow columns out into each slice of memory; populate block +// * placement arrays as we go +class PandasBlockCreator { + public: + using WriterMap = std::unordered_map>; + + explicit PandasBlockCreator(const PandasOptions& options, FieldVector fields, + ChunkedArrayVector arrays) + : options_(options), fields_(std::move(fields)), arrays_(std::move(arrays)) { + num_columns_ = static_cast(arrays_.size()); + if (num_columns_ > 0) { + num_rows_ = arrays_[0]->length(); + } + column_block_placement_.resize(num_columns_); + } + virtual ~PandasBlockCreator() = default; + + virtual Status Convert(PyObject** out) = 0; + + Status AppendBlocks(const WriterMap& blocks, PyObject* list) { + for (const auto& it : blocks) { + PyObject* item; + RETURN_NOT_OK(it.second->GetDataFrameResult(&item)); + if (PyList_Append(list, item) < 0) { + RETURN_IF_PYERROR(); + } + + // ARROW-1017; PyList_Append increments object refcount + Py_DECREF(item); + } + return Status::OK(); + } + + protected: + PandasOptions options_; + + FieldVector fields_; + ChunkedArrayVector arrays_; + int num_columns_; + int64_t num_rows_; + + // column num -> relative placement within internal block + std::vector column_block_placement_; +}; + +// Helper function for extension chunked arrays +// Constructing a storage chunked array of an extension chunked array +std::shared_ptr GetStorageChunkedArray(std::shared_ptr arr) { + auto value_type = checked_cast(*arr->type()).storage_type(); + ArrayVector storage_arrays; + for (int c = 0; c < arr->num_chunks(); c++) { + const auto& arr_ext = checked_cast(*arr->chunk(c)); + storage_arrays.emplace_back(arr_ext.storage()); + } + return std::make_shared(std::move(storage_arrays), value_type); +}; + +// Helper function to decode RunEndEncodedArray +Result> GetDecodedChunkedArray( + std::shared_ptr arr) { + ARROW_ASSIGN_OR_RAISE(Datum decoded, compute::RunEndDecode(arr)); + ARROW_DCHECK(decoded.is_chunked_array()); + return decoded.chunked_array(); +}; + +class ConsolidatedBlockCreator : public PandasBlockCreator { + public: + using PandasBlockCreator::PandasBlockCreator; + + Status Convert(PyObject** out) override { + column_types_.resize(num_columns_); + RETURN_NOT_OK(CreateBlocks()); + RETURN_NOT_OK(WriteTableToBlocks()); + PyAcquireGIL lock; + + PyObject* result = PyList_New(0); + RETURN_IF_PYERROR(); + + RETURN_NOT_OK(AppendBlocks(blocks_, result)); + RETURN_NOT_OK(AppendBlocks(singleton_blocks_, result)); + + *out = result; + return Status::OK(); + } + + Status GetBlockType(int column_index, PandasWriter::type* out) { + if (options_.IsExtensionColumn(fields_[column_index]->name())) { + *out = PandasWriter::EXTENSION; + return Status::OK(); + } else { + // In case of an extension array default to the storage type + if (arrays_[column_index]->type()->id() == Type::EXTENSION) { + arrays_[column_index] = GetStorageChunkedArray(arrays_[column_index]); + } + // In case of a RunEndEncodedArray default to the values type + else if (arrays_[column_index]->type()->id() == Type::RUN_END_ENCODED) { + ARROW_ASSIGN_OR_RAISE(arrays_[column_index], + GetDecodedChunkedArray(arrays_[column_index])); + } + return GetPandasWriterType(*arrays_[column_index], options_, out); + } + } + + Status CreateBlocks() { + for (int i = 0; i < num_columns_; ++i) { + const DataType& type = *arrays_[i]->type(); + PandasWriter::type output_type; + RETURN_NOT_OK(GetBlockType(i, &output_type)); + + int block_placement = 0; + std::shared_ptr writer; + if (output_type == PandasWriter::CATEGORICAL || + output_type == PandasWriter::DATETIME_SECOND_TZ || + output_type == PandasWriter::DATETIME_MILLI_TZ || + output_type == PandasWriter::DATETIME_MICRO_TZ || + output_type == PandasWriter::DATETIME_NANO_TZ || + output_type == PandasWriter::EXTENSION) { + RETURN_NOT_OK(MakeWriter(options_, output_type, type, num_rows_, + /*num_columns=*/1, &writer)); + singleton_blocks_[i] = writer; + } else { + auto it = block_sizes_.find(output_type); + if (it != block_sizes_.end()) { + block_placement = it->second; + // Increment count + ++it->second; + } else { + // Add key to map + block_sizes_[output_type] = 1; + } + } + column_types_[i] = output_type; + column_block_placement_[i] = block_placement; + } + + // Create normal non-categorical blocks + for (const auto& it : this->block_sizes_) { + PandasWriter::type output_type = static_cast(it.first); + std::shared_ptr block; + RETURN_NOT_OK(MakeWriter(this->options_, output_type, /*unused*/ *null(), num_rows_, + it.second, &block)); + this->blocks_[output_type] = block; + } + return Status::OK(); + } + + Status GetWriter(int i, std::shared_ptr* block) { + PandasWriter::type output_type = this->column_types_[i]; + switch (output_type) { + case PandasWriter::CATEGORICAL: + case PandasWriter::DATETIME_SECOND_TZ: + case PandasWriter::DATETIME_MILLI_TZ: + case PandasWriter::DATETIME_MICRO_TZ: + case PandasWriter::DATETIME_NANO_TZ: + case PandasWriter::EXTENSION: { + auto it = this->singleton_blocks_.find(i); + if (it == this->singleton_blocks_.end()) { + return Status::KeyError("No block allocated"); + } + *block = it->second; + } break; + default: + auto it = this->blocks_.find(output_type); + if (it == this->blocks_.end()) { + return Status::KeyError("No block allocated"); + } + *block = it->second; + break; + } + return Status::OK(); + } + + Status WriteTableToBlocks() { + auto WriteColumn = [this](int i) { + std::shared_ptr block; + RETURN_NOT_OK(this->GetWriter(i, &block)); + // ARROW-3789 Use std::move on the array to permit self-destructing + return block->Write(std::move(arrays_[i]), i, this->column_block_placement_[i]); + }; + + return OptionalParallelFor(options_.use_threads, num_columns_, WriteColumn); + } + + private: + // column num -> block type id + std::vector column_types_; + + // block type -> type count + std::unordered_map block_sizes_; + std::unordered_map block_types_; + + // block type -> block + WriterMap blocks_; + + WriterMap singleton_blocks_; +}; + +/// \brief Create blocks for pandas.DataFrame block manager using one block per +/// column strategy. This permits some zero-copy optimizations as well as the +/// ability for the table to "self-destruct" if selected by the user. +class SplitBlockCreator : public PandasBlockCreator { + public: + using PandasBlockCreator::PandasBlockCreator; + + Status GetWriter(int i, std::shared_ptr* writer) { + PandasWriter::type output_type = PandasWriter::OBJECT; + const DataType& type = *arrays_[i]->type(); + if (options_.IsExtensionColumn(fields_[i]->name())) { + output_type = PandasWriter::EXTENSION; + } else { + // Null count needed to determine output type + RETURN_NOT_OK(GetPandasWriterType(*arrays_[i], options_, &output_type)); + } + return MakeWriter(this->options_, output_type, type, num_rows_, 1, writer); + } + + Status Convert(PyObject** out) override { + PyAcquireGIL lock; + + PyObject* result = PyList_New(0); + RETURN_IF_PYERROR(); + + for (int i = 0; i < num_columns_; ++i) { + std::shared_ptr writer; + RETURN_NOT_OK(GetWriter(i, &writer)); + // ARROW-3789 Use std::move on the array to permit self-destructing + RETURN_NOT_OK(writer->Write(std::move(arrays_[i]), i, /*rel_placement=*/0)); + + PyObject* item; + RETURN_NOT_OK(writer->GetDataFrameResult(&item)); + if (PyList_Append(result, item) < 0) { + RETURN_IF_PYERROR(); + } + // PyList_Append increments object refcount + Py_DECREF(item); + } + + *out = result; + return Status::OK(); + } + + private: + std::vector> writers_; +}; + +Status ConvertCategoricals(const PandasOptions& options, ChunkedArrayVector* arrays, + FieldVector* fields) { + std::vector columns_to_encode; + + // For Categorical conversions + auto EncodeColumn = [&](int j) { + int i = columns_to_encode[j]; + if (options.zero_copy_only) { + return Status::Invalid("Need to dictionary encode a column, but ", + "only zero-copy conversions allowed"); + } + compute::ExecContext ctx(options.pool); + ARROW_ASSIGN_OR_RAISE( + Datum out, DictionaryEncode((*arrays)[i], + compute::DictionaryEncodeOptions::Defaults(), &ctx)); + (*arrays)[i] = out.chunked_array(); + (*fields)[i] = (*fields)[i]->WithType((*arrays)[i]->type()); + return Status::OK(); + }; + + if (options.HasCategoricalColumns()) { + for (int i = 0; i < static_cast(arrays->size()); i++) { + if ((*arrays)[i]->type()->id() != Type::DICTIONARY && + options.IsCategoricalColumn((*fields)[i]->name())) { + columns_to_encode.push_back(i); + } + } + } + if (options.strings_to_categorical) { + for (int i = 0; i < static_cast(arrays->size()); i++) { + if (is_base_binary_like((*arrays)[i]->type()->id()) || + is_binary_view_like((*arrays)[i]->type()->id())) { + columns_to_encode.push_back(i); + } + } + } + return OptionalParallelFor(options.use_threads, + static_cast(columns_to_encode.size()), EncodeColumn); +} + +} // namespace + +Status ConvertArrayToPandas(const PandasOptions& options, std::shared_ptr arr, + PyObject* py_ref, PyObject** out) { + return ConvertChunkedArrayToPandas( + options, std::make_shared(std::move(arr)), py_ref, out); +} + +Status ConvertChunkedArrayToPandas(const PandasOptions& options, + std::shared_ptr arr, PyObject* py_ref, + PyObject** out) { + if (options.decode_dictionaries && arr->type()->id() == Type::DICTIONARY) { + // XXX we should return an error as below if options.zero_copy_only + // is true, but that would break compatibility with existing tests. + const auto& dense_type = + checked_cast(*arr->type()).value_type(); + RETURN_NOT_OK(DecodeDictionaries(options.pool, dense_type, &arr)); + ARROW_DCHECK_NE(arr->type()->id(), Type::DICTIONARY); + + // The original Python DictionaryArray won't own the memory anymore + // as we actually built a new array when we decoded the DictionaryArray + // thus let the final resulting numpy array own the memory through a Capsule + py_ref = nullptr; + } + + if (options.strings_to_categorical && (is_base_binary_like(arr->type()->id()) || + is_binary_view_like(arr->type()->id()))) { + if (options.zero_copy_only) { + return Status::Invalid("Need to dictionary encode a column, but ", + "only zero-copy conversions allowed"); + } + compute::ExecContext ctx(options.pool); + ARROW_ASSIGN_OR_RAISE( + Datum out, + DictionaryEncode(arr, compute::DictionaryEncodeOptions::Defaults(), &ctx)); + arr = out.chunked_array(); + } + + PandasOptions modified_options = options; + modified_options.strings_to_categorical = false; + + // ARROW-7596: We permit the hybrid Series/DataFrame code path to do zero copy + // optimizations that we do not allow in the default case when converting + // Table->DataFrame + modified_options.allow_zero_copy_blocks = true; + + // In case of an extension array default to the storage type + if (arr->type()->id() == Type::EXTENSION) { + arr = GetStorageChunkedArray(arr); + } + // In case of a RunEndEncodedArray decode the array + else if (arr->type()->id() == Type::RUN_END_ENCODED) { + if (options.zero_copy_only) { + return Status::Invalid("Need to dencode a RunEndEncodedArray, but ", + "only zero-copy conversions allowed"); + } + ARROW_ASSIGN_OR_RAISE(arr, GetDecodedChunkedArray(arr)); + + // Because we built a new array when we decoded the RunEndEncodedArray + // the final resulting numpy array should own the memory through a Capsule + py_ref = nullptr; + } + + PandasWriter::type output_type; + RETURN_NOT_OK(GetPandasWriterType(*arr, modified_options, &output_type)); + if (options.decode_dictionaries) { + ARROW_DCHECK_NE(output_type, PandasWriter::CATEGORICAL); + } + + std::shared_ptr writer; + RETURN_NOT_OK(MakeWriter(modified_options, output_type, *arr->type(), arr->length(), + /*num_columns=*/1, &writer)); + RETURN_NOT_OK(writer->TransferSingle(std::move(arr), py_ref)); + return writer->GetSeriesResult(out); +} + +Status ConvertTableToPandas(const PandasOptions& options, std::shared_ptr
\1\1\1/
table, + PyObject** out) { + ChunkedArrayVector arrays = table->columns(); + FieldVector fields = table->fields(); + + // ARROW-3789: allow "self-destructing" by releasing references to columns as + // we convert them to pandas + table = nullptr; + + RETURN_NOT_OK(ConvertCategoricals(options, &arrays, &fields)); + + PandasOptions modified_options = options; + modified_options.strings_to_categorical = false; + modified_options.categorical_columns.reset(); + + if (options.split_blocks) { + modified_options.allow_zero_copy_blocks = true; + SplitBlockCreator helper(modified_options, std::move(fields), std::move(arrays)); + return helper.Convert(out); + } else { + ConsolidatedBlockCreator helper(modified_options, std::move(fields), + std::move(arrays)); + return helper.Convert(out); + } +} + +} // namespace py +} // namespace arrow diff --git a/shared/package-files/d2/d2549801e0d739fb7fc2f286948dfbac8001d4e5dfc65fb06557fe1abc72eb25/blob b/shared/package-files/d2/d2549801e0d739fb7fc2f286948dfbac8001d4e5dfc65fb06557fe1abc72eb25/blob new file mode 100644 index 0000000000000000000000000000000000000000..890dc79640aff571262f5a12f721f62f5c907069 --- /dev/null +++ b/shared/package-files/d2/d2549801e0d739fb7fc2f286948dfbac8001d4e5dfc65fb06557fe1abc72eb25/blob @@ -0,0 +1,249 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_array_equal +import pytest +import math + +from scipy.fft import dct, idct, dctn, idctn, dst, idst, dstn, idstn +import scipy.fft as fft +from scipy import fftpack +from scipy.conftest import array_api_compatible +from scipy._lib._array_api import xp_copy, xp_assert_close + +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")] +skip_xp_backends = pytest.mark.skip_xp_backends + +SQRT_2 = math.sqrt(2) + +# scipy.fft wraps the fftpack versions but with normalized inverse transforms. +# So, the forward transforms and definitions are already thoroughly tested in +# fftpack/test_real_transforms.py + + +@skip_xp_backends(cpu_only=True) +@pytest.mark.parametrize("forward, backward", [(dct, idct), (dst, idst)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("n", [2, 3, 4, 5, 10, 16]) +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +@pytest.mark.parametrize("orthogonalize", [False, True]) +def test_identity_1d(forward, backward, type, n, axis, norm, orthogonalize, xp): + # Test the identity f^-1(f(x)) == x + x = xp.asarray(np.random.rand(n, n)) + + y = forward(x, type, axis=axis, norm=norm, orthogonalize=orthogonalize) + z = backward(y, type, axis=axis, norm=norm, orthogonalize=orthogonalize) + xp_assert_close(z, x) + + pad = [(0, 0)] * 2 + pad[axis] = (0, 4) + + y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge')) + z2 = backward(y2, type, n, axis, norm, orthogonalize=orthogonalize) + xp_assert_close(z2, x) + + +@skip_xp_backends(np_only=True, + reason='`overwrite_x` only supported for NumPy backend.') +@pytest.mark.parametrize("forward, backward", [(dct, idct), (dst, idst)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64, + np.complex64, np.complex128]) +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +@pytest.mark.parametrize("overwrite_x", [True, False]) +def test_identity_1d_overwrite(forward, backward, type, dtype, axis, norm, + overwrite_x): + # Test the identity f^-1(f(x)) == x + x = np.random.rand(7, 8).astype(dtype) + x_orig = x.copy() + + y = forward(x, type, axis=axis, norm=norm, overwrite_x=overwrite_x) + y_orig = y.copy() + z = backward(y, type, axis=axis, norm=norm, overwrite_x=overwrite_x) + if not overwrite_x: + assert_allclose(z, x, rtol=1e-6, atol=1e-6) + assert_array_equal(x, x_orig) + assert_array_equal(y, y_orig) + else: + assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6) + + +@skip_xp_backends(cpu_only=True) +@pytest.mark.parametrize("forward, backward", [(dctn, idctn), (dstn, idstn)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("shape, axes", + [ + ((4, 4), 0), + ((4, 4), 1), + ((4, 4), None), + ((4, 4), (0, 1)), + ((10, 12), None), + ((10, 12), (0, 1)), + ((4, 5, 6), None), + ((4, 5, 6), 1), + ((4, 5, 6), (0, 2)), + ]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +@pytest.mark.parametrize("orthogonalize", [False, True]) +def test_identity_nd(forward, backward, type, shape, axes, norm, + orthogonalize, xp): + # Test the identity f^-1(f(x)) == x + + x = xp.asarray(np.random.random(shape)) + + if axes is not None: + shape = np.take(shape, axes) + + y = forward(x, type, axes=axes, norm=norm, orthogonalize=orthogonalize) + z = backward(y, type, axes=axes, norm=norm, orthogonalize=orthogonalize) + xp_assert_close(z, x) + + if axes is None: + pad = [(0, 4)] * x.ndim + elif isinstance(axes, int): + pad = [(0, 0)] * x.ndim + pad[axes] = (0, 4) + else: + pad = [(0, 0)] * x.ndim + + for a in axes: + pad[a] = (0, 4) + + # TODO write an array-agnostic pad + y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge')) + z2 = backward(y2, type, shape, axes, norm, orthogonalize=orthogonalize) + xp_assert_close(z2, x) + + +@skip_xp_backends(np_only=True, + reason='`overwrite_x` only supported for NumPy backend.') +@pytest.mark.parametrize("forward, backward", [(dctn, idctn), (dstn, idstn)]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("shape, axes", + [ + ((4, 5), 0), + ((4, 5), 1), + ((4, 5), None), + ]) +@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64, + np.complex64, np.complex128]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +@pytest.mark.parametrize("overwrite_x", [False, True]) +def test_identity_nd_overwrite(forward, backward, type, shape, axes, dtype, + norm, overwrite_x): + # Test the identity f^-1(f(x)) == x + + x = np.random.random(shape).astype(dtype) + x_orig = x.copy() + + if axes is not None: + shape = np.take(shape, axes) + + y = forward(x, type, axes=axes, norm=norm) + y_orig = y.copy() + z = backward(y, type, axes=axes, norm=norm) + if overwrite_x: + assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6) + else: + assert_allclose(z, x, rtol=1e-6, atol=1e-6) + assert_array_equal(x, x_orig) + assert_array_equal(y, y_orig) + + +@skip_xp_backends(cpu_only=True) +@pytest.mark.parametrize("func", ['dct', 'dst', 'dctn', 'dstn']) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward']) +def test_fftpack_equivalience(func, type, norm, xp): + x = np.random.rand(8, 16) + fftpack_res = xp.asarray(getattr(fftpack, func)(x, type, norm=norm)) + x = xp.asarray(x) + fft_res = getattr(fft, func)(x, type, norm=norm) + + xp_assert_close(fft_res, fftpack_res) + + +@skip_xp_backends(cpu_only=True) +@pytest.mark.parametrize("func", [dct, dst, dctn, dstn]) +@pytest.mark.parametrize("type", [1, 2, 3, 4]) +def test_orthogonalize_default(func, type, xp): + # Test orthogonalize is the default when norm="ortho", but not otherwise + x = xp.asarray(np.random.rand(100)) + + for norm, ortho in [ + ("forward", False), + ("backward", False), + ("ortho", True), + ]: + a = func(x, type=type, norm=norm, orthogonalize=ortho) + b = func(x, type=type, norm=norm) + xp_assert_close(a, b) + + +@skip_xp_backends(cpu_only=True) +@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"]) +@pytest.mark.parametrize("func, type", [ + (dct, 4), (dst, 1), (dst, 4)]) +def test_orthogonalize_noop(func, type, norm, xp): + # Transforms where orthogonalize is a no-op + x = xp.asarray(np.random.rand(100)) + y1 = func(x, type=type, norm=norm, orthogonalize=True) + y2 = func(x, type=type, norm=norm, orthogonalize=False) + xp_assert_close(y1, y2) + + +@skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment', + cpu_only=True) +@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"]) +def test_orthogonalize_dct1(norm, xp): + x = xp.asarray(np.random.rand(100)) + + x2 = xp_copy(x, xp=xp) + x2[0] *= SQRT_2 + x2[-1] *= SQRT_2 + + y1 = dct(x, type=1, norm=norm, orthogonalize=True) + y2 = dct(x2, type=1, norm=norm, orthogonalize=False) + + y2[0] /= SQRT_2 + y2[-1] /= SQRT_2 + xp_assert_close(y1, y2) + + +@skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment', + cpu_only=True) +@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"]) +@pytest.mark.parametrize("func", [dct, dst]) +def test_orthogonalize_dcst2(func, norm, xp): + x = xp.asarray(np.random.rand(100)) + y1 = func(x, type=2, norm=norm, orthogonalize=True) + y2 = func(x, type=2, norm=norm, orthogonalize=False) + + y2[0 if func == dct else -1] /= SQRT_2 + xp_assert_close(y1, y2) + + +@skip_xp_backends('jax.numpy', + reason='jax arrays do not support item assignment', + cpu_only=True) +@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"]) +@pytest.mark.parametrize("func", [dct, dst]) +def test_orthogonalize_dcst3(func, norm, xp): + x = xp.asarray(np.random.rand(100)) + x2 = xp_copy(x, xp=xp) + x2[0 if func == dct else -1] *= SQRT_2 + + y1 = func(x, type=3, norm=norm, orthogonalize=True) + y2 = func(x2, type=3, norm=norm, orthogonalize=False) + xp_assert_close(y1, y2) + +@skip_xp_backends(np_only=True, + reason='array-likes only supported for NumPy backend') +@pytest.mark.parametrize("func", [dct, idct, dctn, idctn, dst, idst, dstn, idstn]) +def test_array_like(xp, func): + x = [[[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]], + [[1.0, 1.0], [1.0, 1.0]]] + xp_assert_close(func(x), func(xp.asarray(x))) diff --git a/shared/package-files/d2/d256473d977d81f47eaf2f639672f70ca155635a13ef0ea156b0a94d94fc9a49/blob b/shared/package-files/d2/d256473d977d81f47eaf2f639672f70ca155635a13ef0ea156b0a94d94fc9a49/blob new file mode 100644 index 0000000000000000000000000000000000000000..07bb42df04f69ae658b40b02401d4e5c9440b36a --- /dev/null +++ b/shared/package-files/d2/d256473d977d81f47eaf2f639672f70ca155635a13ef0ea156b0a94d94fc9a49/blob @@ -0,0 +1,353 @@ +"""Provide access to Python's configuration information. The specific +configuration variables available depend heavily on the platform and +configuration. The values may be retrieved using +get_config_var(name), and the list of variables is available via +get_config_vars().keys(). Additional convenience functions are also +available. + +Written by: Fred L. Drake, Jr. +Email: +""" + +import _imp +import os +import re +import sys +import warnings + +from functools import partial + +from .errors import DistutilsPlatformError + +from sysconfig import ( + _PREFIX as PREFIX, + _BASE_PREFIX as BASE_PREFIX, + _EXEC_PREFIX as EXEC_PREFIX, + _BASE_EXEC_PREFIX as BASE_EXEC_PREFIX, + _PROJECT_BASE as project_base, + _PYTHON_BUILD as python_build, + _init_posix as sysconfig_init_posix, + parse_config_h as sysconfig_parse_config_h, + + _init_non_posix, + _is_python_source_dir, + _sys_home, + + _variable_rx, + _findvar1_rx, + _findvar2_rx, + + expand_makefile_vars, + is_python_build, + get_config_h_filename, + get_config_var, + get_config_vars, + get_makefile_filename, + get_python_version, +) + +# This is better than +# from sysconfig import _CONFIG_VARS as _config_vars +# because it makes sure that the global dictionary is initialized +# which might not be true in the time of import. +_config_vars = get_config_vars() + +if os.name == "nt": + from sysconfig import _fix_pcbuild + +warnings.warn( + 'The distutils.sysconfig module is deprecated, use sysconfig instead', + DeprecationWarning, + stacklevel=2 +) + + +# Following functions are the same as in sysconfig but with different API +def parse_config_h(fp, g=None): + return sysconfig_parse_config_h(fp, vars=g) + + +_python_build = partial(is_python_build, check_home=True) +_init_posix = partial(sysconfig_init_posix, _config_vars) +_init_nt = partial(_init_non_posix, _config_vars) + + +# Similar function is also implemented in sysconfig as _parse_makefile +# but without the parsing capabilities of distutils.text_file.TextFile. +def parse_makefile(fn, g=None): + """Parse a Makefile-style file. + A dictionary containing name/value pairs is returned. If an + optional dictionary is passed in as the second argument, it is + used instead of a new dictionary. + """ + from distutils.text_file import TextFile + fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1, errors="surrogateescape") + + if g is None: + g = {} + done = {} + notdone = {} + + while True: + line = fp.readline() + if line is None: # eof + break + m = re.match(_variable_rx, line) + if m: + n, v = m.group(1, 2) + v = v.strip() + # `$$' is a literal `$' in make + tmpv = v.replace('$$', '') + + if "$" in tmpv: + notdone[n] = v + else: + try: + v = int(v) + except ValueError: + # insert literal `$' + done[n] = v.replace('$$', '$') + else: + done[n] = v + + # Variables with a 'PY_' prefix in the makefile. These need to + # be made available without that prefix through sysconfig. + # Special care is needed to ensure that variable expansion works, even + # if the expansion uses the name without a prefix. + renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS') + + # do variable interpolation here + while notdone: + for name in list(notdone): + value = notdone[name] + m = re.search(_findvar1_rx, value) or re.search(_findvar2_rx, value) + if m: + n = m.group(1) + found = True + if n in done: + item = str(done[n]) + elif n in notdone: + # get it on a subsequent round + found = False + elif n in os.environ: + # do it like make: fall back to environment + item = os.environ[n] + + elif n in renamed_variables: + if name.startswith('PY_') and name[3:] in renamed_variables: + item = "" + + elif 'PY_' + n in notdone: + found = False + + else: + item = str(done['PY_' + n]) + else: + done[n] = item = "" + if found: + after = value[m.end():] + value = value[:m.start()] + item + after + if "$" in after: + notdone[name] = value + else: + try: value = int(value) + except ValueError: + done[name] = value.strip() + else: + done[name] = value + del notdone[name] + + if name.startswith('PY_') \ + and name[3:] in renamed_variables: + + name = name[3:] + if name not in done: + done[name] = value + else: + # bogus variable reference; just drop it since we can't deal + del notdone[name] + + fp.close() + + # strip spurious spaces + for k, v in done.items(): + if isinstance(v, str): + done[k] = v.strip() + + # save the results in the global dictionary + g.update(done) + return g + + +# Following functions are deprecated together with this module and they +# have no direct replacement + +# Calculate the build qualifier flags if they are defined. Adding the flags +# to the include and lib directories only makes sense for an installation, not +# an in-source build. +build_flags = '' +try: + if not python_build: + build_flags = sys.abiflags +except AttributeError: + # It's not a configure-based build, so the sys module doesn't have + # this attribute, which is fine. + pass + + +def customize_compiler(compiler): + """Do any platform-specific customization of a CCompiler instance. + + Mainly needed on Unix, so we can plug in the information that + varies across Unices and is stored in Python's Makefile. + """ + if compiler.compiler_type == "unix": + if sys.platform == "darwin": + # Perform first-time customization of compiler-related + # config vars on OS X now that we know we need a compiler. + # This is primarily to support Pythons from binary + # installers. The kind and paths to build tools on + # the user system may vary significantly from the system + # that Python itself was built on. Also the user OS + # version and build tools may not support the same set + # of CPU architectures for universal builds. + if not _config_vars.get('CUSTOMIZED_OSX_COMPILER'): + import _osx_support + _osx_support.customize_compiler(_config_vars) + _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True' + + (cc, cxx, cflags, ccshared, ldshared, shlib_suffix, ar, ar_flags) = \ + get_config_vars('CC', 'CXX', 'CFLAGS', + 'CCSHARED', 'LDSHARED', 'SHLIB_SUFFIX', 'AR', 'ARFLAGS') + + if 'CC' in os.environ: + newcc = os.environ['CC'] + if ('LDSHARED' not in os.environ + and ldshared.startswith(cc)): + # If CC is overridden, use that as the default + # command for LDSHARED as well + ldshared = newcc + ldshared[len(cc):] + cc = newcc + if 'CXX' in os.environ: + cxx = os.environ['CXX'] + if 'LDSHARED' in os.environ: + ldshared = os.environ['LDSHARED'] + if 'CPP' in os.environ: + cpp = os.environ['CPP'] + else: + cpp = cc + " -E" # not always + if 'LDFLAGS' in os.environ: + ldshared = ldshared + ' ' + os.environ['LDFLAGS'] + if 'CFLAGS' in os.environ: + cflags = cflags + ' ' + os.environ['CFLAGS'] + ldshared = ldshared + ' ' + os.environ['CFLAGS'] + if 'CPPFLAGS' in os.environ: + cpp = cpp + ' ' + os.environ['CPPFLAGS'] + cflags = cflags + ' ' + os.environ['CPPFLAGS'] + ldshared = ldshared + ' ' + os.environ['CPPFLAGS'] + if 'AR' in os.environ: + ar = os.environ['AR'] + if 'ARFLAGS' in os.environ: + archiver = ar + ' ' + os.environ['ARFLAGS'] + else: + archiver = ar + ' ' + ar_flags + + cc_cmd = cc + ' ' + cflags + compiler.set_executables( + preprocessor=cpp, + compiler=cc_cmd, + compiler_so=cc_cmd + ' ' + ccshared, + compiler_cxx=cxx, + linker_so=ldshared, + linker_exe=cc, + archiver=archiver) + + if 'RANLIB' in os.environ and 'ranlib' in compiler.executables: + compiler.set_executables(ranlib=os.environ['RANLIB']) + + compiler.shared_lib_extension = shlib_suffix + + +def get_python_inc(plat_specific=0, prefix=None): + """Return the directory containing installed Python header files. + + If 'plat_specific' is false (the default), this is the path to the + non-platform-specific header files, i.e. Python.h and so on; + otherwise, this is the path to platform-specific header files + (namely pyconfig.h). + + If 'prefix' is supplied, use it instead of sys.base_prefix or + sys.base_exec_prefix -- i.e., ignore 'plat_specific'. + """ + if prefix is None: + prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX + if os.name == "posix": + if python_build: + # Assume the executable is in the build directory. The + # pyconfig.h file should be in the same directory. Since + # the build directory may not be the source directory, we + # must use "srcdir" from the makefile to find the "Include" + # directory. + if plat_specific: + return _sys_home or project_base + else: + incdir = os.path.join(get_config_var('srcdir'), 'Include') + return os.path.normpath(incdir) + python_dir = 'python' + get_python_version() + build_flags + return os.path.join(prefix, "include", python_dir) + elif os.name == "nt": + if python_build: + # Include both the include and PC dir to ensure we can find + # pyconfig.h + return (os.path.join(prefix, "include") + os.path.pathsep + + os.path.join(prefix, "PC")) + return os.path.join(prefix, "include") + else: + raise DistutilsPlatformError( + "I don't know where Python installs its C header files " + "on platform '%s'" % os.name) + + +def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): + """Return the directory containing the Python library (standard or + site additions). + + If 'plat_specific' is true, return the directory containing + platform-specific modules, i.e. any module from a non-pure-Python + module distribution; otherwise, return the platform-shared library + directory. If 'standard_lib' is true, return the directory + containing standard Python library modules; otherwise, return the + directory for site-specific modules. + + If 'prefix' is supplied, use it instead of sys.base_prefix or + sys.base_exec_prefix -- i.e., ignore 'plat_specific'. + """ + if prefix is None: + if standard_lib: + prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX + else: + prefix = plat_specific and EXEC_PREFIX or PREFIX + + if os.name == "posix": + if plat_specific or standard_lib: + # Platform-specific modules (any module from a non-pure-Python + # module distribution) or standard Python library modules. + libdir = sys.platlibdir + else: + # Pure Python + libdir = "lib" + libpython = os.path.join(prefix, libdir, + "python" + get_python_version()) + if standard_lib: + return libpython + else: + return os.path.join(libpython, "site-packages") + elif os.name == "nt": + if standard_lib: + return os.path.join(prefix, "Lib") + else: + return os.path.join(prefix, "Lib", "site-packages") + else: + raise DistutilsPlatformError( + "I don't know where Python installs its library " + "on platform '%s'" % os.name) diff --git a/shared/package-files/d2/d2565692a654374a3a1b92c661660811e89ca48dcdc6f04fedef71dae56953aa/blob b/shared/package-files/d2/d2565692a654374a3a1b92c661660811e89ca48dcdc6f04fedef71dae56953aa/blob new file mode 100644 index 0000000000000000000000000000000000000000..0dfad58d9272ad2d40caf908b159651c02ce8d35 --- /dev/null +++ b/shared/package-files/d2/d2565692a654374a3a1b92c661660811e89ca48dcdc6f04fedef71dae56953aa/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor as_strided_scatter(const at::Tensor & self, const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset=c10::nullopt); +TORCH_API at::Tensor as_strided_scatter_symint(const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset=c10::nullopt); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/d2/d256c7ce99ddcc998ef12e369a5921b33e4d6ef24b402687e4c71ced06510f37/blob b/shared/package-files/d2/d256c7ce99ddcc998ef12e369a5921b33e4d6ef24b402687e4c71ced06510f37/blob new file mode 100644 index 0000000000000000000000000000000000000000..01ed101cd477dfb112616440bdb6a8a54a30cb67 Binary files /dev/null and b/shared/package-files/d2/d256c7ce99ddcc998ef12e369a5921b33e4d6ef24b402687e4c71ced06510f37/blob differ diff --git a/shared/package-files/d2/d25738c9c7692e9ffa515c80512ec06288642ff072ddaf6d9460d120b4cbbcd0/model_config.json b/shared/package-files/d2/d25738c9c7692e9ffa515c80512ec06288642ff072ddaf6d9460d120b4cbbcd0/model_config.json new file mode 100644 index 0000000000000000000000000000000000000000..59f1e32b9bc67348612f043f700b1a41bf1f1c0a --- /dev/null +++ b/shared/package-files/d2/d25738c9c7692e9ffa515c80512ec06288642ff072ddaf6d9460d120b4cbbcd0/model_config.json @@ -0,0 +1,825 @@ +{ + "fingerprint": "Morgan4096-radius2", + "inference_workers": 4, + "mass_coefficient": 0.05, + "mass_parameters": { + "all": { + "offset": 0.0017379104733558116, + "scale": 0.22784726949100334, + "mixture_weights": [ + 0.11348937893654104, + 0.09557863134001011, + 0.010802800714892547, + 0.27844904220265765, + 0.07768452213624864, + 0.1709708948586656, + 0.23702439865382724, + 0.015967743911176686, + 1.7643549236442432e-05, + 7.684451077257689e-06, + 7.259245692855192e-06 + ], + "training_rows": 194119 + }, + "[M+H]+": { + "offset": 0.0026598596314496036, + "scale": 0.15197921970275186, + "mixture_weights": [ + 0.09246832232787215, + 0.15828627244183788, + 0.0065878029959954, + 0.31749453381513637, + 0.06691310191590559, + 0.20675743203186617, + 0.14743426117961617, + 0.004015221453949477, + 2.213631461854741e-05, + 9.515782465935305e-06, + 1.1399740728553998e-05 + ], + "training_rows": 166479 + }, + "[M+H]+|CE_known": { + "offset": -7.5456039222815375e-06, + "scale": 0.1, + "mixture_weights": [ + 0.277957178913776, + 0.10299700301240623, + 0.0450389898293163, + 0.561070127022119, + 9.111299713505526e-05, + 0.0001591517812427008, + 0.01235607944949077, + 2.851234573855838e-05, + 1.577364819830921e-05, + 1.321626436610966e-05, + 0.0002728547362399875 + ], + "training_rows": 99377 + }, + "[M+H]+ Orbitrap|CE_known": { + "offset": -0.0012137828913790357, + "scale": 0.1, + "mixture_weights": [ + 0.06422570221691885, + 0.448900037543551, + 0.007661252708447786, + 0.47892461814762105, + 8.615792199305746e-05, + 4.0539396132119084e-05, + 2.8711619110200728e-05, + 1.9810606333773048e-05, + 1.7376532695294367e-05, + 1.735477812233229e-05, + 7.843852907220662e-05 + ], + "training_rows": 64738 + }, + "[M+H]+|CE_missing": { + "offset": 0.34631438891746547, + "scale": 1.2049855792590873, + "mixture_weights": [ + 0.002400138233077247, + 0.0016321395320094193, + 0.007935572466802954, + 0.01322935406812269, + 0.0377142214937561, + 0.6915743755825599, + 0.17574340475284658, + 0.06967482000584813, + 5.4937143716676695e-05, + 2.249739039877218e-05, + 1.8539330819977017e-05 + ], + "training_rows": 67102 + }, + "[M+H]+ QTOF|CE_missing": { + "offset": 0.31476867963403604, + "scale": 1.1661727787433172, + "mixture_weights": [ + 0.0010564259863848158, + 0.0005894207836781736, + 0.0010816453510932304, + 0.0014685723145067624, + 0.0027053324129020792, + 0.8971739993466411, + 0.09368991441666277, + 0.0014729013755782594, + 0.0003099932328118446, + 0.00015620819002684058, + 0.00029558658971284385 + ], + "training_rows": 11931 + }, + "[M+H]+ |CE_missing": { + "offset": -0.07318393565829291, + "scale": 0.9669946819840058, + "mixture_weights": [ + 0.0005975010441871446, + 0.0006859777656295754, + 0.0010108878159835043, + 0.0022892482602014205, + 0.010457243036413018, + 0.9774313828340385, + 0.003979709831526971, + 0.00164433209849248, + 0.000971841628528598, + 0.0005422099670379036, + 0.000389665717964122 + ], + "training_rows": 3467 + }, + "[M+H]+ Orbitrap|CE_missing": { + "offset": 0.4053671391343552, + "scale": 1.2247049028286892, + "mixture_weights": [ + 5.5786769068857485e-05, + 4.7840000830280644e-05, + 6.842781112965848e-05, + 0.00034816414094056286, + 0.1381743206538106, + 0.5676295325687076, + 0.17214509148968796, + 0.12141581997250234, + 6.588036605044894e-05, + 2.7689857154294105e-05, + 2.144637014122733e-05 + ], + "training_rows": 51704 + }, + "[M+Na]+": { + "offset": -0.18138664899886367, + "scale": 2.7908660677201578, + "mixture_weights": [ + 5.998630184453845e-05, + 8.36197500856792e-05, + 0.00011821210969713358, + 0.00027844880048530075, + 0.11105638319333055, + 0.1848931039119867, + 0.5183319904412221, + 0.18498508263496855, + 0.00010684600001259004, + 4.909043144142321e-05, + 3.7236424932572684e-05 + ], + "training_rows": 27640 + }, + "[M+Na]+|CE_known": { + "offset": -0.01708129304095346, + "scale": 0.1, + "mixture_weights": [ + 0.003595944499122591, + 0.1623511959192979, + 0.5018677991413051, + 0.0028824226296219075, + 0.0022251834365176032, + 0.28281891269752996, + 0.041841418636617694, + 0.0009368414655946452, + 0.0005568817751130254, + 0.0004748236040244341, + 0.00044857619525480734 + ], + "training_rows": 2232 + }, + "[M+Na]+ Orbitrap|CE_known": { + "offset": -0.010102936926932657, + "scale": 0.1, + "mixture_weights": [ + 0.03632723606215987, + 0.47605530075811436, + 0.33081324545080804, + 0.006565277582606766, + 0.0044815548305416055, + 0.13925352868014493, + 0.0030512333502417965, + 0.0011245033501138303, + 0.0008428210239524358, + 0.0007574941685357202, + 0.0007278047427810105 + ], + "training_rows": 1369 + }, + "[M+Na]+|CE_missing": { + "offset": -0.32485984366270015, + "scale": 3.2315997762307016, + "mixture_weights": [ + 0.0010751443741488494, + 0.0004050487037307812, + 0.00035107930250629515, + 0.0006983453580821511, + 0.010157221288322794, + 0.21355002906019704, + 0.5844455008518827, + 0.1891061750400425, + 0.00011738843615020736, + 5.355090812505278e-05, + 4.051667681264271e-05 + ], + "training_rows": 25408 + }, + "[M+Na]+ |CE_missing": { + "offset": -0.0487177506227377, + "scale": 0.5698143697858935, + "mixture_weights": [ + 0.00213607340640689, + 0.0024504632080948074, + 0.002969142135634155, + 0.005503430204804471, + 0.49557919267477807, + 0.47431145653657864, + 0.003877184130713715, + 0.002565579095854207, + 0.0037373083274618952, + 0.0054579028115658785, + 0.001412267468108022 + ], + "training_rows": 825 + }, + "[M+Na]+ Orbitrap|CE_missing": { + "offset": -0.438501156388837, + "scale": 4.0867859774060795, + "mixture_weights": [ + 0.0010685311302348587, + 0.00037235210701107226, + 0.00041440394418946336, + 0.000647241052604937, + 0.0034874889890427045, + 0.06868902310118669, + 0.742584380746082, + 0.18250575670611766, + 0.00012794643078596824, + 5.836019685552822e-05, + 4.451559587891884e-05 + ], + "training_rows": 23085 + }, + "[M+Na]+ QTOF|CE_missing": { + "offset": 0.005669038371233242, + "scale": 0.551818998766307, + "mixture_weights": [ + 0.003590344924033642, + 0.003434455557288551, + 0.0025528055104238495, + 0.003229883750344113, + 0.5243654654252945, + 0.4555929331518605, + 0.002653188498955686, + 0.0015529167638151738, + 0.0012780009121488253, + 0.0010441010613118753, + 0.0007059044445229687 + ], + "training_rows": 1498 + }, + "[M+Na]+ QTOF|CE_known": { + "offset": -0.09100474226353564, + "scale": 0.6701640150891102, + "mixture_weights": [ + 0.02437028407029411, + 0.0035379924881954574, + 0.005693087062529851, + 0.334032458037412, + 0.018330230040587144, + 0.44024191100503046, + 0.16758511259516504, + 0.0024151262729173836, + 0.0014252615507739674, + 0.0012174324980399154, + 0.0011511043790541128 + ], + "training_rows": 863 + }, + "[M+H]+ QTOF|CE_known": { + "offset": 6.490960030784106e-05, + "scale": 0.1, + "mixture_weights": [ + 0.34198423762106916, + 0.00013810361998403017, + 0.0003447224219550764, + 0.5681058015591219, + 0.0002819756030467073, + 0.0008167805840039795, + 0.0876353029655167, + 7.635009465176205e-05, + 4.3482243022034925e-05, + 3.723049222203804e-05, + 0.0005360127953988947 + ], + "training_rows": 34603 + } + }, + "ion_masses": { + "[M+H]+": 1.007276466621, + "[M+Na]+": 22.989220702091 + }, + "mass_conditioning": "energy_presence", + "method": "train-IDF cross-radius score mixture with frozen precursor likelihood", + "score": "cosine_idf_cauchy_mass", + "ensemble_rule": "mixed_radius_candidate_scores", + "members": [ + { + "width": 384, + "depth": 4, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 32, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 384, + "depth": 4, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 64, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 384, + "depth": 4, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 10, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 384, + "depth": 4, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 10, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 384, + "depth": 4, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 10, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 384, + "depth": 4, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 10, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 384, + "depth": 4, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 32, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 384, + "depth": 4, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 10, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 384, + "depth": 4, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 32, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 512, + "depth": 6, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 32, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 384, + "depth": 4, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 32, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 768, + "depth": 8, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 32, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 768, + "depth": 8, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 32, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 768, + "depth": 8, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 32, + "fingerprint": "Morgan4096-radius3", + "score": "cosine_sigmoid" + }, + { + "width": 768, + "depth": 8, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 32, + "fingerprint": "Morgan4096-radius3", + "score": "cosine_sigmoid" + }, + { + "width": 768, + "depth": 8, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 32, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 1024, + "depth": 12, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 32, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 1024, + "depth": 12, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 32, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 384, + "depth": 4, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 32, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + } + ], + "mass_likelihood": "cauchy_mixture", + "mass_scales": [ + 0.003, + 0.01, + 0.03, + 0.1, + 0.3, + 1.0, + 3.0, + 10.0, + 30.0, + 100.0, + 1000.0 + ], + "internal_scores_format": "candidate-score-jsonl/v1", + "score_groups": [ + { + "radius": 2, + "member_indices": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 11, + 11, + 11, + 12, + 12, + 12, + 12, + 15, + 16, + 16, + 16, + 16, + 17, + 17, + 18 + ], + "coefficient": 0.75, + "allow_tf32": false + }, + { + "radius": 3, + "member_indices": [ + 13, + 14 + ], + "coefficient": 0.25, + "allow_tf32": true + } + ], + "molecular_prior": { + "coefficient": 0.03, + "center": -1.6669455338407368, + "scale": 1.1694539926031409, + "clip": 3.0, + "fingerprint": "Morgan4096-radius2", + "invalid_fingerprint_contribution": 0.0, + "training_checkpoint_sha256": "75b233d4751245852d7cb9031684dbfe5392c5c3d268f458e16d65bef11b652e", + "secondary": { + "center": -1.7819357042968937, + "scale": 1.2038746567775631, + "clip": 3.0, + "fingerprint": "Morgan4096-radius3", + "invalid_fingerprint_contribution": 0.0, + "training_checkpoint_sha256": "5cc4719a7e5c234b75d45550e688364d8d9e8cda474fd5d04e0d3cd1b6108c23" + }, + "primary_fraction": 0.5, + "sodium": { + "adduct": "[M+Na]+", + "radius2_fraction": 0.5, + "radius2": { + "center": -1.24472267849336, + "scale": 1.3460053418901774, + "clip": 3.0, + "fingerprint": "Morgan4096-radius2", + "invalid_fingerprint_contribution": 0.0, + "training_checkpoint_sha256": "96dd248d00fc815827cdcc8f9f93bbbfb89327f357b90f50f340d53d7080e0ca", + "TRAIN_molecules": 4821 + }, + "radius3": { + "center": -1.3550505429221078, + "scale": 1.477672477930177, + "clip": 3.0, + "fingerprint": "Morgan4096-radius3", + "invalid_fingerprint_contribution": 0.0, + "training_checkpoint_sha256": "9b45a1e271c747f2cba1d08f82bad9018ae47775c1e69d9234b6b2871ee7dabc", + "TRAIN_molecules": 4821 + } + }, + "descriptor": { + "fraction": 0.25, + "feature_names": [ + "ExactMolWt", + "MolLogP", + "MolMR", + "TPSA", + "HDonors", + "HAcceptors", + "RotatableBonds", + "HeavyAtomCount", + "FractionCSP3", + "AromaticRings", + "AliphaticRings", + "SaturatedRings", + "Heterocycles", + "FormalCharge", + "RadicalElectrons", + "ChiralCenters", + "AtomCount_C", + "AtomCount_N", + "AtomCount_O", + "AtomCount_P", + "AtomCount_S", + "AtomCount_F", + "AtomCount_Cl", + "AtomCount_Br", + "AtomCount_I", + "AtomCount_B", + "AtomCount_Si" + ], + "feature_map": "RDKit27properties; signedlog1p; TRAINfeaturecenter/scale and clip5; linear score; TRAINscorecenter/scale and clip3", + "invalid_structure_contribution": 0.0, + "global": { + "center": 0.03603254879424718, + "scale": 0.9342696472936184, + "clip": 3.0, + "training_checkpoint_sha256": "63db54452099efe3cb2d6f63c8364ae3c51feeea9216448858f7c0338b92fe32", + "TRAIN_molecules": 20979 + }, + "sodium": { + "center": 0.042870073933984044, + "scale": 1.581338729028455, + "clip": 3.0, + "training_checkpoint_sha256": "8d262377b9763576ca87e8dc7e6ba9afc632809873ce4d8818231620cad0f3c2", + "TRAIN_molecules": 4821 + } + }, + "information_scaling": { + "TRAIN_median_effective_fragment_peaks": 5.33006667795596, + "factor_clip": [ + 0.5, + 2.0 + ], + "peak_definition": "positive inrange0..1500/precursor+1; strongest50 first; remove publicprecursor max20ppm/.002Da forbothadducts; expShannonentropy of remainingintensities; empty1", + "TRAIN_source_sha256": "de7f46e91f7b67eb5ca67468381abbdb20a8f739a0ae4b27070276798ecad0fc", + "TRAIN_rows": 194119, + "exponent": 0.5, + "training_checkpoint_sha256": "2396823f16efe6bbdd9c81d41a2343694d5f9635baa494e70f46eaf5b02ca280" + } + }, + "candidate_pool_centering": { + "strength": 1.0, + "geometry": "subtract mean of unit TRAIN-IDF-normalized candidate vectors from query and candidate unit vectors, renormalize, cosine", + "singleton": "original uncentered cosine", + "candidate_order": "candidate_id lexical before arithmetic", + "fitting": false + }, + "conditional_descriptor": { + "coefficient": 0.01, + "source_model_sha256": "970fc10264a1a17b7b941b62b7a9743135dbd2ca95e34949bbc3d52a7275de10", + "public_feature_names": [ + "log_precursor", + "H", + "Na", + "Orbitrap", + "QTOF", + "instrument_missing", + "instrument_other", + "log_positive_peaks", + "log_inrange_peaks", + "moments_0", + "moments_1", + "moments_2", + "moments_3", + "moments_4", + "moments_5", + "moments_6", + "moments_7", + "top_intensity_0", + "top_intensity_1", + "top_intensity_2", + "top_intensity_3", + "top_intensity_4", + "top_intensity_5", + "top_intensity_6", + "top_intensity_7", + "top_intensity_8", + "top_intensity_9", + "cumulative_intensity_0", + "cumulative_intensity_1", + "cumulative_intensity_2", + "cumulative_intensity_3", + "cumulative_intensity_4", + "cumulative_intensity_5", + "relative_mz_quantile_0", + "relative_mz_quantile_1", + "relative_mz_quantile_2", + "relative_mz_quantile_3", + "relative_mz_quantile_4", + "relative_mz_quantile_5", + "relative_mz_quantile_6", + "relative_mz_histogram_0", + "relative_mz_histogram_1", + "relative_mz_histogram_2", + "relative_mz_histogram_3", + "relative_mz_histogram_4", + "relative_mz_histogram_5", + "relative_mz_histogram_6", + "relative_mz_histogram_7", + "relative_mz_histogram_8", + "relative_mz_histogram_9", + "relative_mz_histogram_10", + "relative_mz_histogram_11", + "relative_mz_histogram_12", + "relative_mz_histogram_13", + "relative_mz_histogram_14", + "relative_mz_histogram_15", + "relative_loss_histogram_0", + "relative_loss_histogram_1", + "relative_loss_histogram_2", + "relative_loss_histogram_3", + "relative_loss_histogram_4", + "relative_loss_histogram_5", + "relative_loss_histogram_6", + "relative_loss_histogram_7", + "relative_loss_histogram_8", + "relative_loss_histogram_9", + "relative_loss_histogram_10", + "relative_loss_histogram_11", + "relative_loss_histogram_12", + "relative_loss_histogram_13", + "relative_loss_histogram_14", + "relative_loss_histogram_15", + "absolute_mz_histogram_0", + "absolute_mz_histogram_1", + "absolute_mz_histogram_2", + "absolute_mz_histogram_3", + "absolute_mz_histogram_4", + "absolute_mz_histogram_5", + "absolute_mz_histogram_6", + "absolute_mz_histogram_7", + "absolute_mz_histogram_8", + "absolute_mz_histogram_9", + "absolute_mz_histogram_10", + "absolute_mz_histogram_11", + "energy_known", + "signed_log_energy", + "neutral_loss_H2O", + "neutral_loss_NH3", + "neutral_loss_CO", + "neutral_loss_CO2", + "neutral_loss_CH4", + "neutral_loss_CH2O", + "neutral_loss_CH4O", + "neutral_loss_C2H2", + "neutral_loss_C2H4", + "neutral_loss_C2H6O", + "neutral_loss_CH2O2", + "neutral_loss_HCN", + "neutral_loss_H2S", + "neutral_loss_SO2", + "neutral_loss_SO3", + "neutral_loss_HCl", + "fragment_pair_loss_H2O", + "fragment_pair_loss_NH3", + "fragment_pair_loss_CO", + "fragment_pair_loss_CO2", + "fragment_pair_loss_CH4", + "fragment_pair_loss_CH2O", + "fragment_pair_loss_CH4O", + "fragment_pair_loss_C2H2", + "fragment_pair_loss_C2H4", + "fragment_pair_loss_C2H6O", + "fragment_pair_loss_CH2O2", + "fragment_pair_loss_HCN", + "fragment_pair_loss_H2S", + "fragment_pair_loss_SO2", + "fragment_pair_loss_SO3", + "fragment_pair_loss_HCl" + ], + "descriptor_names": [ + "ExactMolWt", + "MolLogP", + "MolMR", + "TPSA", + "HDonors", + "HAcceptors", + "RotatableBonds", + "HeavyAtomCount", + "FractionCSP3", + "AromaticRings", + "AliphaticRings", + "SaturatedRings", + "Heterocycles", + "FormalCharge", + "RadicalElectrons", + "ChiralCenters", + "AtomCount_C", + "AtomCount_N", + "AtomCount_O", + "AtomCount_P", + "AtomCount_S", + "AtomCount_F", + "AtomCount_Cl", + "AtomCount_Br", + "AtomCount_I", + "AtomCount_B", + "AtomCount_Si" + ], + "description": "TRAIN pairwise bilinear public-spectrum/precursor-loss/fragment-pair-loss x candidate D27 interaction; trained intercept omitted; features standardized by TRAIN statistics and clipped5, score standardized by TRAIN moments and clipped3", + "fitting_at_inference": false + }, + "fingerprint_covariance_transform": { + "score_group_index": 0, + "rank": 256, + "damping": 0.75, + "basis_state_key": "fingerprint_covariance_basis", + "basis_source_sha256": "eae3820a3914ea5c646d5fba0d66397cd0fc975779348b429f96a7af6f4f597a", + "order": "after IDF unit normalization, before candidate-pool centering; renormalize transformed vectors", + "TRAIN_unique_molecules": 25046 + } +} \ No newline at end of file diff --git a/shared/package-files/d2/d25b18b1a87fe7c94c599a94b73d13734448b4636469dd22897b12c928e9e2ff/blob b/shared/package-files/d2/d25b18b1a87fe7c94c599a94b73d13734448b4636469dd22897b12c928e9e2ff/blob new file mode 100644 index 0000000000000000000000000000000000000000..f35fde5c876a00766b8ef71ddbeef18771d259eb --- /dev/null +++ b/shared/package-files/d2/d25b18b1a87fe7c94c599a94b73d13734448b4636469dd22897b12c928e9e2ff/blob @@ -0,0 +1,94 @@ +from ._general import safe_isinstance + +SENTENCEPIECE_TOKENIZERS = [ + "transformers.MarianTokenizer", + "transformers.T5Tokenizer", + "transformers.XLNetTokenizer", + "transformers.AlbertTokenizer", +] + + +def is_transformers_lm(model): + """Check if the given model object is a huggingface transformers language model.""" + if safe_isinstance(model, "transformers.PreTrainedModel") or safe_isinstance( + model, "transformers.TFPreTrainedModel" + ): + from transformers import ( + MODEL_FOR_CAUSAL_LM_MAPPING, + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + ) + + return ( + type(model) in MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.values() + or type(model) in MODEL_FOR_CAUSAL_LM_MAPPING.values() + ) + return False + + +def parse_prefix_suffix_for_tokenizer(tokenizer): + """Set prefix and suffix tokens based on null tokens. + + Example for distillgpt2: null_tokens=[], for BART: null_tokens = [0,2] and for MarianMT: null_tokens=[0] + used to slice tokens belonging to sentence after passing through tokenizer.encode(). + """ + null_tokens = tokenizer("")["input_ids"] + keep_prefix, keep_suffix = None, None + + if len(null_tokens) == 1: + null_token = null_tokens[0] + if hasattr(tokenizer, "special_tokens_map") and hasattr(tokenizer, "decode"): + st_map = tokenizer.special_tokens_map + assert ("eos_token" in st_map) or ("bos_token" in st_map), "No eos token or bos token found in tokenizer!" + if ("eos_token" in st_map) and (tokenizer.decode(null_token) == st_map["eos_token"]): + keep_prefix = 0 + keep_suffix = 1 + # prefix_strlen = 0 + # suffix_strlen = len(tokenizer.decode(null_tokens[-keep_suffix:])) + elif ("bos_token" in st_map) and (tokenizer.decode(null_token) == st_map["bos_token"]): + keep_prefix = 1 + keep_suffix = 0 + # prefix_strlen = len(tokenizer.decode(null_tokens[:keep_prefix])) + # suffix_strlen = 0 + else: + raise Exception( + "The given tokenizer produces one token when applied to the empty string, but " + "does not have a .special_tokens_map['eos_token'] or .special_tokens_map['bos_token'] " + "property (and .decode) to specify if it is an eos (end) of bos (beginning) token!" + ) + else: + assert len(null_tokens) % 2 == 0, "An odd number of boundary tokens are added to the null string!" + keep_prefix = len(null_tokens) // 2 + keep_suffix = len(null_tokens) // 2 + # prefix_strlen = len(tokenizer.decode(null_tokens[:keep_prefix])) + # suffix_strlen = len(tokenizer.decode(null_tokens[-keep_suffix:])) + + return { + "keep_prefix": keep_prefix, + "keep_suffix": keep_suffix, + # 'prefix_strlen' : prefix_strlen, + # 'suffix_strlen' : suffix_strlen, + "null_tokens": null_tokens, + } + + +def getattr_silent(obj, attr): + """This turns of verbose logging of missing attributes for huggingface transformers. + + This is motivated by huggingface transformers objects that print error warnings + when we access unset properties. + """ + reset_verbose = False + if getattr(obj, "verbose", False): + reset_verbose = True + obj.verbose = False + + val = getattr(obj, attr, None) + + if reset_verbose: + obj.verbose = True + + # fix strange huggingface bug where `obj.verbose = False` causes val to change from None to "None" + if val == "None": + val = None + + return val diff --git a/shared/package-files/d2/d25d03089dca20278b894218c2cce3d48000e13b4569809aa17e51ffb792f19f/blob b/shared/package-files/d2/d25d03089dca20278b894218c2cce3d48000e13b4569809aa17e51ffb792f19f/blob new file mode 100644 index 0000000000000000000000000000000000000000..800b027e4695dfbd8647f2582aff5cbea031c3ea --- /dev/null +++ b/shared/package-files/d2/d25d03089dca20278b894218c2cce3d48000e13b4569809aa17e51ffb792f19f/blob @@ -0,0 +1,307 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] + +#include + +#include +#if !(defined(__VSX__) || defined(CPU_CAPABILITY_VSX) || defined(CPU_CAPABILITY_ZVECTOR)) +#include +#include +#include +#include +#include +#include +#include +#include +#elif defined(__VSX__) || defined(CPU_CAPABILITY_VSX) +#include +#else +#include +#include +#endif + +#include +#include +#include +#include +#include + +namespace at::vec { + +// Note [CPU_CAPABILITY namespace] +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// This header, and all of its subheaders, will be compiled with +// different architecture flags for each supported set of vector +// intrinsics. So we need to make sure they aren't inadvertently +// linked together. We do this by declaring objects in an `inline +// namespace` which changes the name mangling, but can still be +// accessed as `at::vec`. +inline namespace CPU_CAPABILITY { + +inline std::ostream& operator<<(std::ostream& stream, const c10::qint32& val) { + stream << val.val_; + return stream; +} +inline std::ostream& operator<<(std::ostream& stream, const c10::qint8& val) { + stream << static_cast(val.val_); + return stream; +} +inline std::ostream& operator<<(std::ostream& stream, const c10::quint8& val) { + stream << static_cast(val.val_); + return stream; +} + +template +std::ostream& operator<<(std::ostream& stream, const Vectorized& vec) { + T buf[Vectorized::size()]; + vec.store(buf); + stream << "vec["; + for (int i = 0; i != Vectorized::size(); i++) { + if (i != 0) { + stream << ", "; + } + stream << buf[i]; + } + stream << "]"; + return stream; +} + + +#if defined(CPU_CAPABILITY_AVX2) && !defined(_MSC_VER) + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CAST (AVX2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +template<> +inline Vectorized cast(const Vectorized& src) { + return _mm256_castpd_ps(src); +} + +template<> +inline Vectorized cast(const Vectorized& src) { + return _mm256_castps_pd(src); +} + +template<> +inline Vectorized cast(const Vectorized& src) { + return _mm256_castsi256_ps(src); +} + +template<> +inline Vectorized cast(const Vectorized& src) { + return _mm256_castsi256_pd(src); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GATHER ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +template +std::enable_if_t> +inline gather(const double* base_addr, const Vectorized& vindex) { + return _mm256_i64gather_pd(base_addr, vindex, scale); +} + +template +std::enable_if_t> +inline gather(const float* base_addr, const Vectorized& vindex) { + return _mm256_i32gather_ps(base_addr, vindex, scale); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MASK GATHER ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +template +std::enable_if_t> +inline mask_gather(const Vectorized& src, const double* base_addr, + const Vectorized& vindex, Vectorized& mask) { + return _mm256_mask_i64gather_pd(src, base_addr, vindex, mask, scale); +} + +template +std::enable_if_t> +inline mask_gather(const Vectorized& src, const float* base_addr, + const Vectorized& vindex, Vectorized& mask) { + return _mm256_mask_i32gather_ps(src, base_addr, vindex, mask, scale); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CONVERT ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +// Only works for inputs in the range: [-2^51, 2^51] +// From: https://stackoverflow.com/a/41148578 +template<> +Vectorized +inline convert_to_int_of_same_size(const Vectorized &src) { + auto x = _mm256_add_pd(src, _mm256_set1_pd(0x0018000000000000)); + return _mm256_sub_epi64( + _mm256_castpd_si256(x), + _mm256_castpd_si256(_mm256_set1_pd(0x0018000000000000)) + ); +} + +template<> +Vectorized +inline convert_to_int_of_same_size(const Vectorized &src) { + return _mm256_cvttps_epi32(src); +} + +// Only works for inputs in the range: [-2^51, 2^51] +// From: https://stackoverflow.com/a/41148578 +template<> +Vectorized +inline convert_to_fp_of_same_size(const Vectorized &src) { + auto x = _mm256_add_epi64(src, _mm256_castpd_si256(_mm256_set1_pd(0x0018000000000000))); + return _mm256_sub_pd( + _mm256_castsi256_pd(x), + _mm256_set1_pd(0x0018000000000000) + ); +} + +template<> +Vectorized +inline convert_to_fp_of_same_size(const Vectorized &src) { + return _mm256_cvtepi32_ps(src); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ INTERLEAVE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +template <> +std::pair, Vectorized> +inline interleave2(const Vectorized& a, const Vectorized& b) { + // inputs: + // a = {a0, a1, a3, a3} + // b = {b0, b1, b2, b3} + + // swap lanes: + // a_swapped = {a0, a1, b0, b1} + // b_swapped = {a2, a3, b2, b3} + auto a_swapped = _mm256_permute2f128_pd(a, b, 0b0100000); // 0, 2. 4 bits apart + auto b_swapped = _mm256_permute2f128_pd(a, b, 0b0110001); // 1, 3. 4 bits apart + + // group cols crossing lanes: + // return {a0, b0, a1, b1} + // {a2, b2, a3, b3} + return std::make_pair(_mm256_permute4x64_pd(a_swapped, 0b11011000), // 0, 2, 1, 3 + _mm256_permute4x64_pd(b_swapped, 0b11011000)); // 0, 2, 1, 3 +} + +template <> +std::pair, Vectorized> +inline interleave2(const Vectorized& a, const Vectorized& b) { + // inputs: + // a = {a0, a1, a2, a3, a4, a5, a6, a7} + // b = {b0, b1, b2, b3, b4, b5, b6, b7} + + // swap lanes: + // a_swapped = {a0, a1, a2, a3, b0, b1, b2, b3} + // b_swapped = {a4, a5, a6, a7, b4, b5, b6, b7} + // TODO: can we support caching this? + auto a_swapped = _mm256_permute2f128_ps(a, b, 0b0100000); // 0, 2. 4 bits apart + auto b_swapped = _mm256_permute2f128_ps(a, b, 0b0110001); // 1, 3. 4 bits apart + + // group cols crossing lanes: + // return {a0, b0, a1, b1, a2, b2, a3, b3} + // {a4, b4, a5, b5, a6, b6, a7, b7} + const __m256i group_ctrl = _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7); + return std::make_pair(_mm256_permutevar8x32_ps(a_swapped, group_ctrl), + _mm256_permutevar8x32_ps(b_swapped, group_ctrl)); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DEINTERLEAVE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +template <> +std::pair, Vectorized> +inline deinterleave2(const Vectorized& a, const Vectorized& b) { + // inputs: + // a = {a0, b0, a1, b1} + // b = {a2, b2, a3, b3} + + // group cols crossing lanes: + // a_grouped = {a0, a1, b0, b1} + // b_grouped = {a2, a3, b2, b3} + auto a_grouped = _mm256_permute4x64_pd(a, 0b11011000); // 0, 2, 1, 3 + auto b_grouped = _mm256_permute4x64_pd(b, 0b11011000); // 0, 2, 1, 3 + + // swap lanes: + // return {a0, a1, a2, a3} + // {b0, b1, b2, b3} + return std::make_pair(_mm256_permute2f128_pd(a_grouped, b_grouped, 0b0100000), // 0, 2. 4 bits apart + _mm256_permute2f128_pd(a_grouped, b_grouped, 0b0110001)); // 1, 3. 4 bits apart +} + +template <> +std::pair, Vectorized> +inline deinterleave2(const Vectorized& a, const Vectorized& b) { + // inputs: + // a = {a0, b0, a1, b1, a2, b2, a3, b3} + // b = {a4, b4, a5, b5, a6, b6, a7, b7} + + // group cols crossing lanes: + // a_grouped = {a0, a1, a2, a3, b0, b1, b2, b3} + // b_grouped = {a4, a5, a6, a7, b4, b5, b6, b7} + // TODO: can we support caching this? + const __m256i group_ctrl = _mm256_setr_epi32(0, 2, 4, 6, 1, 3, 5, 7); + auto a_grouped = _mm256_permutevar8x32_ps(a, group_ctrl); + auto b_grouped = _mm256_permutevar8x32_ps(b, group_ctrl); + + // swap lanes: + // return {a0, a1, a2, a3, a4, a5, a6, a7} + // {b0, b1, b2, b3, b4, b5, b6, b7} + return std::make_pair(_mm256_permute2f128_ps(a_grouped, b_grouped, 0b0100000), // 0, 2. 4 bits apart + _mm256_permute2f128_ps(a_grouped, b_grouped, 0b0110001)); // 1, 3. 4 bits apart +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FLIP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +template<> +inline Vectorized flip(const Vectorized & v) { + const __m256i mask_float = _mm256_set_epi32(0, 1, 2, 3, 4, 5, 6, 7); + return _mm256_permutevar8x32_ps(v, mask_float); +} + +template<> +inline Vectorized flip(const Vectorized & v) { + return _mm256_permute4x64_pd(v, 27); // 27 == _MM_SHUFFLE(0, 1, 2, 3) +} + +template<> +inline Vectorized flip(const Vectorized & v) { + return _mm256_permute4x64_epi64(v, 27); // 27 == _MM_SHUFFLE(0, 1, 2, 3) +} + +template<> +inline Vectorized flip(const Vectorized & v) { + const __m256i mask_int32 = _mm256_set_epi32(0, 1, 2, 3, 4, 5, 6, 7); + return _mm256_permutevar8x32_epi32(v, mask_int32); +} + +template<> +inline Vectorized flip(const Vectorized & v) { + const __m256i mask = _mm256_set_epi8( + 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, + 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14 + ); + auto reversed = _mm256_shuffle_epi8(v, mask); + return _mm256_permute2x128_si256(reversed, reversed, 1); +} + +inline __m256i flip8(const __m256i & v) { + const __m256i mask_int8 = _mm256_set_epi8( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 + ); + auto reversed = _mm256_shuffle_epi8(v, mask_int8); + return _mm256_permute2x128_si256(reversed, reversed, 1); +} + +template<> +inline Vectorized flip(const Vectorized & v) { + return flip8(v); +} + +template<> +inline Vectorized flip(const Vectorized & v) { + return flip8(v); +} + +#endif // (defined(CPU_CAPABILITY_AVX2) && !defined(_MSC_VER) + +}} // namepsace at::vec::CPU_CAPABILITY diff --git a/shared/package-files/d2/d261630f63d0430be5b3ce4fcaca40aa5f7adc122370fa59da386290c55aa56c/blob b/shared/package-files/d2/d261630f63d0430be5b3ce4fcaca40aa5f7adc122370fa59da386290c55aa56c/blob new file mode 100644 index 0000000000000000000000000000000000000000..dc3b3393c5207dec16f1123425ae5f765f8ed6d9 --- /dev/null +++ b/shared/package-files/d2/d261630f63d0430be5b3ce4fcaca40aa5f7adc122370fa59da386290c55aa56c/blob @@ -0,0 +1,44 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Protocol + +from narwhals._compliant.group_by import CompliantGroupBy, ParseKeysGroupBy +from narwhals._compliant.typing import CompliantLazyFrameT, NativeExprT_co +from narwhals._sql.typing import SQLExprT_contra + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + + +class SQLGroupBy( + ParseKeysGroupBy[CompliantLazyFrameT, SQLExprT_contra], + CompliantGroupBy[CompliantLazyFrameT, SQLExprT_contra], + Protocol[CompliantLazyFrameT, SQLExprT_contra, NativeExprT_co], +): + _keys: list[str] + _output_key_names: list[str] + + def _evaluate_expr(self, expr: SQLExprT_contra, /) -> Iterator[NativeExprT_co]: + output_names = expr._evaluate_output_names(self.compliant) + aliases = ( + expr._alias_output_names(output_names) + if expr._alias_output_names + else output_names + ) + native_exprs = expr(self.compliant) + if expr._is_multi_output_unnamed(): + exclude = {*self._keys, *self._output_key_names} + for native_expr, name, alias in zip( + native_exprs, output_names, aliases, strict=True + ): + if name not in exclude: + yield expr._alias_native(native_expr, alias) + else: + for native_expr, alias in zip(native_exprs, aliases, strict=True): + yield expr._alias_native(native_expr, alias) + + def _evaluate_exprs( + self, exprs: Iterable[SQLExprT_contra], / + ) -> Iterator[NativeExprT_co]: + for expr in exprs: + yield from self._evaluate_expr(expr) diff --git a/shared/package-files/d2/d264428cb2b175cbc0a34bc3f82afcd477d15d70a9f63fdc0178cea001ed3c63/blob b/shared/package-files/d2/d264428cb2b175cbc0a34bc3f82afcd477d15d70a9f63fdc0178cea001ed3c63/blob new file mode 100644 index 0000000000000000000000000000000000000000..8a02fa0fc0631dde0b4501c8d1c168b467c0d1a9 --- /dev/null +++ b/shared/package-files/d2/d264428cb2b175cbc0a34bc3f82afcd477d15d70a9f63fdc0178cea001ed3c63/blob @@ -0,0 +1,6 @@ +from typing import Any, Union + +from . import Attribute, _FilterType + +def include(*what: Union[type, str, Attribute[Any]]) -> _FilterType[Any]: ... +def exclude(*what: Union[type, str, Attribute[Any]]) -> _FilterType[Any]: ... diff --git a/shared/package-files/d2/d264fcf6896ea33e65513f1aafab8f892c13201c3231cea81d89eb339418ed5a/blob b/shared/package-files/d2/d264fcf6896ea33e65513f1aafab8f892c13201c3231cea81d89eb339418ed5a/blob new file mode 100644 index 0000000000000000000000000000000000000000..077fcc786e5c04ed9ac26b2bf6589852a76bd14f --- /dev/null +++ b/shared/package-files/d2/d264fcf6896ea33e65513f1aafab8f892c13201c3231cea81d89eb339418ed5a/blob @@ -0,0 +1,139 @@ +""" + pygments.lexers.ride + ~~~~~~~~~~~~~~~~~~~~ + + Lexer for the Ride programming language. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.lexer import RegexLexer, words, include +from pygments.token import Comment, Keyword, Name, Number, Punctuation, \ + String, Text + +__all__ = ['RideLexer'] + + +class RideLexer(RegexLexer): + """ + For `Ride `_ + source code. + + .. versionadded:: 2.6 + """ + + name = 'Ride' + aliases = ['ride'] + filenames = ['*.ride'] + mimetypes = ['text/x-ride'] + + validName = r'[a-zA-Z_][a-zA-Z0-9_\']*' + + builtinOps = ( + '||', '|', '>=', '>', '==', '!', + '=', '<=', '<', '::', ':+', ':', '!=', '/', + '.', '=>', '-', '+', '*', '&&', '%', '++', + ) + + globalVariablesName = ( + 'NOALG', 'MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512', + 'SHA3224', 'SHA3256', 'SHA3384', 'SHA3512', 'nil', 'this', 'unit', + 'height', 'lastBlock', 'Buy', 'Sell', 'CEILING', 'FLOOR', 'DOWN', + 'HALFDOWN', 'HALFEVEN', 'HALFUP', 'UP', + ) + + typesName = ( + 'Unit', 'Int', 'Boolean', 'ByteVector', 'String', 'Address', 'Alias', + 'Transfer', 'AssetPair', 'DataEntry', 'Order', 'Transaction', + 'GenesisTransaction', 'PaymentTransaction', 'ReissueTransaction', + 'BurnTransaction', 'MassTransferTransaction', 'ExchangeTransaction', + 'TransferTransaction', 'SetAssetScriptTransaction', + 'InvokeScriptTransaction', 'IssueTransaction', 'LeaseTransaction', + 'LeaseCancelTransaction', 'CreateAliasTransaction', + 'SetScriptTransaction', 'SponsorFeeTransaction', 'DataTransaction', + 'WriteSet', 'AttachedPayment', 'ScriptTransfer', 'TransferSet', + 'ScriptResult', 'Invocation', 'Asset', 'BlockInfo', 'Issue', 'Reissue', + 'Burn', 'NoAlg', 'Md5', 'Sha1', 'Sha224', 'Sha256', 'Sha384', 'Sha512', + 'Sha3224', 'Sha3256', 'Sha3384', 'Sha3512', 'BinaryEntry', + 'BooleanEntry', 'IntegerEntry', 'StringEntry', 'List', 'Ceiling', + 'Down', 'Floor', 'HalfDown', 'HalfEven', 'HalfUp', 'Up', + ) + + functionsName = ( + 'fraction', 'size', 'toBytes', 'take', 'drop', 'takeRight', 'dropRight', + 'toString', 'isDefined', 'extract', 'throw', 'getElement', 'value', + 'cons', 'toUtf8String', 'toInt', 'indexOf', 'lastIndexOf', 'split', + 'parseInt', 'parseIntValue', 'keccak256', 'blake2b256', 'sha256', + 'sigVerify', 'toBase58String', 'fromBase58String', 'toBase64String', + 'fromBase64String', 'transactionById', 'transactionHeightById', + 'getInteger', 'getBoolean', 'getBinary', 'getString', + 'addressFromPublicKey', 'addressFromString', 'addressFromRecipient', + 'assetBalance', 'wavesBalance', 'getIntegerValue', 'getBooleanValue', + 'getBinaryValue', 'getStringValue', 'addressFromStringValue', + 'assetInfo', 'rsaVerify', 'checkMerkleProof', 'median', + 'valueOrElse', 'valueOrErrorMessage', 'contains', 'log', 'pow', + 'toBase16String', 'fromBase16String', 'blockInfoByHeight', + 'transferTransactionById', + ) + + reservedWords = words(( + 'match', 'case', 'else', 'func', 'if', + 'let', 'then', '@Callable', '@Verifier', + ), suffix=r'\b') + + tokens = { + 'root': [ + # Comments + (r'#.*', Comment.Single), + # Whitespace + (r'\s+', Text), + # Strings + (r'"', String, 'doublequote'), + (r'utf8\'', String, 'utf8quote'), + (r'base(58|64|16)\'', String, 'singlequote'), + # Keywords + (reservedWords, Keyword.Reserved), + (r'\{-#.*?#-\}', Keyword.Reserved), + (r'FOLD<\d+>', Keyword.Reserved), + # Types + (words(typesName), Keyword.Type), + # Main + # (specialName, Keyword.Reserved), + # Prefix Operators + (words(builtinOps, prefix=r'\(', suffix=r'\)'), Name.Function), + # Infix Operators + (words(builtinOps), Name.Function), + (words(globalVariablesName), Name.Function), + (words(functionsName), Name.Function), + # Numbers + include('numbers'), + # Variable Names + (validName, Name.Variable), + # Parens + (r'[,()\[\]{}]', Punctuation), + ], + + 'doublequote': [ + (r'\\u[0-9a-fA-F]{4}', String.Escape), + (r'\\[nrfvb\\"]', String.Escape), + (r'[^"]', String), + (r'"', String, '#pop'), + ], + + 'utf8quote': [ + (r'\\u[0-9a-fA-F]{4}', String.Escape), + (r'\\[nrfvb\\\']', String.Escape), + (r'[^\']', String), + (r'\'', String, '#pop'), + ], + + 'singlequote': [ + (r'[^\']', String), + (r'\'', String, '#pop'), + ], + + 'numbers': [ + (r'_?\d+', Number.Integer), + ], + } diff --git a/shared/package-files/d2/d2652cd14b64fae5bd75e655ddc0544e97d632016f9740f2376f49b8abca332c/blob b/shared/package-files/d2/d2652cd14b64fae5bd75e655ddc0544e97d632016f9740f2376f49b8abca332c/blob new file mode 100644 index 0000000000000000000000000000000000000000..c1af113af0a87e5c96033c83f199161062073bf0 Binary files /dev/null and b/shared/package-files/d2/d2652cd14b64fae5bd75e655ddc0544e97d632016f9740f2376f49b8abca332c/blob differ diff --git a/shared/package-files/d2/d26815d5a6f3f79095bbf349faea6d0adbc4cd442230e89a709bedbaa0a533b3/blob b/shared/package-files/d2/d26815d5a6f3f79095bbf349faea6d0adbc4cd442230e89a709bedbaa0a533b3/blob new file mode 100644 index 0000000000000000000000000000000000000000..e01f4e9b14897e051e15ed0de65a2772ffd46299 --- /dev/null +++ b/shared/package-files/d2/d26815d5a6f3f79095bbf349faea6d0adbc4cd442230e89a709bedbaa0a533b3/blob @@ -0,0 +1,13 @@ +# flake8: noqa: F401 +r"""Quantized Reference Modules. + +This module is in the process of migration to +`torch/ao/nn/quantized/reference`, and is kept here for +compatibility while the migration process is ongoing. +If you are adding a new entry/functionality, please, add it to the +appropriate file under the `torch/ao/nn/quantized/reference`, +while adding an import statement here. +""" + +from torch.ao.nn.quantized.reference.modules.sparse import Embedding +from torch.ao.nn.quantized.reference.modules.sparse import EmbeddingBag diff --git a/shared/package-files/d2/d26a773c901c8c834634b53ca66c80dbfd7c49f18c81537ca7bd90373f937cf5/blob b/shared/package-files/d2/d26a773c901c8c834634b53ca66c80dbfd7c49f18c81537ca7bd90373f937cf5/blob new file mode 100644 index 0000000000000000000000000000000000000000..4319ed46da64065f8b73441592f28000e3f8698d --- /dev/null +++ b/shared/package-files/d2/d26a773c901c8c834634b53ca66c80dbfd7c49f18c81537ca7bd90373f937cf5/blob @@ -0,0 +1,17 @@ +import sys +from tracemalloc import _FrameTupleT, _TraceTupleT +from typing import Optional, Sequence, Tuple + +def _get_object_traceback(__obj: object) -> Optional[Sequence[_FrameTupleT]]: ... +def _get_traces() -> Sequence[_TraceTupleT]: ... +def clear_traces() -> None: ... +def get_traceback_limit() -> int: ... +def get_traced_memory() -> Tuple[int, int]: ... +def get_tracemalloc_memory() -> int: ... +def is_tracing() -> bool: ... + +if sys.version_info >= (3, 9): + def reset_peak() -> None: ... + +def start(__nframe: int = ...) -> None: ... +def stop() -> None: ... diff --git a/shared/package-files/d2/d26b775314cb3cda68cd3bc05e8a211954897c86cd85f39ce55bc5f603ce6733/blob b/shared/package-files/d2/d26b775314cb3cda68cd3bc05e8a211954897c86cd85f39ce55bc5f603ce6733/blob new file mode 100644 index 0000000000000000000000000000000000000000..6973a17453e97c30d821ac367dce752097cacad5 Binary files /dev/null and b/shared/package-files/d2/d26b775314cb3cda68cd3bc05e8a211954897c86cd85f39ce55bc5f603ce6733/blob differ diff --git a/shared/package-files/d2/d26b97ea3fd301cde4363d294faab622c3e76888069c1850ec87363d70a782b7/blob b/shared/package-files/d2/d26b97ea3fd301cde4363d294faab622c3e76888069c1850ec87363d70a782b7/blob new file mode 100644 index 0000000000000000000000000000000000000000..86e3056bf6ead7d394ab6031d514472eac400c0e Binary files /dev/null and b/shared/package-files/d2/d26b97ea3fd301cde4363d294faab622c3e76888069c1850ec87363d70a782b7/blob differ diff --git a/shared/package-files/d2/d26f0c9d2c182d5de700a369a7ba4850be3ccb36bab4936addfc9551ef28526a/blob b/shared/package-files/d2/d26f0c9d2c182d5de700a369a7ba4850be3ccb36bab4936addfc9551ef28526a/blob new file mode 100644 index 0000000000000000000000000000000000000000..0abaf7359565d5b177893357615e4d1e779068e5 Binary files /dev/null and b/shared/package-files/d2/d26f0c9d2c182d5de700a369a7ba4850be3ccb36bab4936addfc9551ef28526a/blob differ diff --git a/shared/package-files/d2/d26f80eceebf1dda1f095bd77008471311634a64e7ba714cc65933fc588e4e05/blob b/shared/package-files/d2/d26f80eceebf1dda1f095bd77008471311634a64e7ba714cc65933fc588e4e05/blob new file mode 100644 index 0000000000000000000000000000000000000000..92400b7a570e09da9ca1065cad038b253250454d --- /dev/null +++ b/shared/package-files/d2/d26f80eceebf1dda1f095bd77008471311634a64e7ba714cc65933fc588e4e05/blob @@ -0,0 +1,91 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::slow_conv_transpose3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & slow_conv_transpose3d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, at::IntArrayRef dilation=1) { + return at::_ops::slow_conv_transpose3d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), c10::fromIntArrayRefSlow(dilation), out); +} +namespace symint { + template ::value>> + at::Tensor & slow_conv_transpose3d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, at::IntArrayRef dilation=1) { + return at::_ops::slow_conv_transpose3d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), c10::fromIntArrayRefSlow(dilation), out); + } +} + +// aten::slow_conv_transpose3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & slow_conv_transpose3d_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef output_padding, at::IntArrayRef dilation, at::Tensor & out) { + return at::_ops::slow_conv_transpose3d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), c10::fromIntArrayRefSlow(dilation), out); +} +namespace symint { + template ::value>> + at::Tensor & slow_conv_transpose3d_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef output_padding, at::IntArrayRef dilation, at::Tensor & out) { + return at::_ops::slow_conv_transpose3d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), c10::fromIntArrayRefSlow(dilation), out); + } +} + +// aten::slow_conv_transpose3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & slow_conv_transpose3d_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)) { + return at::_ops::slow_conv_transpose3d_out::call(self, weight, kernel_size, bias, stride, padding, output_padding, dilation, out); +} +namespace symint { + template ::value>> + at::Tensor & slow_conv_transpose3d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)) { + return at::_ops::slow_conv_transpose3d_out::call(self, weight, kernel_size, bias, stride, padding, output_padding, dilation, out); + } +} + +// aten::slow_conv_transpose3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & slow_conv_transpose3d_symint_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef output_padding, c10::SymIntArrayRef dilation, at::Tensor & out) { + return at::_ops::slow_conv_transpose3d_out::call(self, weight, kernel_size, bias, stride, padding, output_padding, dilation, out); +} +namespace symint { + template ::value>> + at::Tensor & slow_conv_transpose3d_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef output_padding, c10::SymIntArrayRef dilation, at::Tensor & out) { + return at::_ops::slow_conv_transpose3d_out::call(self, weight, kernel_size, bias, stride, padding, output_padding, dilation, out); + } +} + +// aten::slow_conv_transpose3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1) -> Tensor +inline at::Tensor slow_conv_transpose3d(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, at::IntArrayRef dilation=1) { + return at::_ops::slow_conv_transpose3d::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), c10::fromIntArrayRefSlow(dilation)); +} +namespace symint { + template ::value>> + at::Tensor slow_conv_transpose3d(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, at::IntArrayRef dilation=1) { + return at::_ops::slow_conv_transpose3d::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), c10::fromIntArrayRefSlow(dilation)); + } +} + +// aten::slow_conv_transpose3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1) -> Tensor +inline at::Tensor slow_conv_transpose3d_symint(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)) { + return at::_ops::slow_conv_transpose3d::call(self, weight, kernel_size, bias, stride, padding, output_padding, dilation); +} +namespace symint { + template ::value>> + at::Tensor slow_conv_transpose3d(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)) { + return at::_ops::slow_conv_transpose3d::call(self, weight, kernel_size, bias, stride, padding, output_padding, dilation); + } +} + +} diff --git a/shared/package-files/d2/d271ee2c2a99dfa82f0d5685e8fa02efafc9382defe8fff7d747856ae5b56433/blob b/shared/package-files/d2/d271ee2c2a99dfa82f0d5685e8fa02efafc9382defe8fff7d747856ae5b56433/blob new file mode 100644 index 0000000000000000000000000000000000000000..4c4a2210255894d2ccdf8b6f341dcd87cd85f38e --- /dev/null +++ b/shared/package-files/d2/d271ee2c2a99dfa82f0d5685e8fa02efafc9382defe8fff7d747856ae5b56433/blob @@ -0,0 +1,15 @@ +from typing import List + +def mkpath(name: str, mode: int = ..., verbose: int = ..., dry_run: int = ...) -> List[str]: ... +def create_tree(base_dir: str, files: List[str], mode: int = ..., verbose: int = ..., dry_run: int = ...) -> None: ... +def copy_tree( + src: str, + dst: str, + preserve_mode: int = ..., + preserve_times: int = ..., + preserve_symlinks: int = ..., + update: int = ..., + verbose: int = ..., + dry_run: int = ..., +) -> List[str]: ... +def remove_tree(directory: str, verbose: int = ..., dry_run: int = ...) -> None: ... diff --git a/shared/package-files/d2/d2725e8f80fcf7cfc953e8e19627f8e1f476caee3691e2b81a808b3fcd749775/blob b/shared/package-files/d2/d2725e8f80fcf7cfc953e8e19627f8e1f476caee3691e2b81a808b3fcd749775/blob new file mode 100644 index 0000000000000000000000000000000000000000..0547d55fe7bb434f94d02707eab64db010891794 --- /dev/null +++ b/shared/package-files/d2/d2725e8f80fcf7cfc953e8e19627f8e1f476caee3691e2b81a808b3fcd749775/blob @@ -0,0 +1,401 @@ +import numpy as np +from numba.cuda.testing import (unittest, CUDATestCase, skip_unless_cc_53, + skip_on_cudasim) +from numba import cuda +from numba.core.types import f2, b1 +from numba.cuda import compile_ptx +import operator +import itertools +from numba.np.numpy_support import from_dtype + + +def simple_fp16_div_scalar(ary, a, b): + ary[0] = a / b + + +def simple_fp16add(ary, a, b): + ary[0] = a + b + + +def simple_fp16_iadd(ary, a): + ary[0] += a + + +def simple_fp16_isub(ary, a): + ary[0] -= a + + +def simple_fp16_imul(ary, a): + ary[0] *= a + + +def simple_fp16_idiv(ary, a): + ary[0] /= a + + +def simple_fp16sub(ary, a, b): + ary[0] = a - b + + +def simple_fp16mul(ary, a, b): + ary[0] = a * b + + +def simple_fp16neg(ary, a): + ary[0] = -a + + +def simple_fp16abs(ary, a): + ary[0] = abs(a) + + +def simple_fp16_gt(ary, a, b): + ary[0] = a > b + + +def simple_fp16_ge(ary, a, b): + ary[0] = a >= b + + +def simple_fp16_lt(ary, a, b): + ary[0] = a < b + + +def simple_fp16_le(ary, a, b): + ary[0] = a <= b + + +def simple_fp16_eq(ary, a, b): + ary[0] = a == b + + +def simple_fp16_ne(ary, a, b): + ary[0] = a != b + + +@cuda.jit('b1(f2, f2)', device=True) +def hlt_func_1(x, y): + return x < y + + +@cuda.jit('b1(f2, f2)', device=True) +def hlt_func_2(x, y): + return x < y + + +def test_multiple_hcmp_1(r, a, b, c): + # float16 predicates used in two separate functions + r[0] = hlt_func_1(a, b) and hlt_func_2(b, c) + + +def test_multiple_hcmp_2(r, a, b, c): + # The same float16 predicate used in the caller and callee + r[0] = hlt_func_1(a, b) and b < c + + +def test_multiple_hcmp_3(r, a, b, c): + # Different float16 predicates used in the caller and callee + r[0] = hlt_func_1(a, b) and c >= b + + +def test_multiple_hcmp_4(r, a, b, c): + # The same float16 predicates used twice in a function + r[0] = a < b and b < c + + +def test_multiple_hcmp_5(r, a, b, c): + # Different float16 predicates used in a function + r[0] = a < b and c >= b + + +class TestOperatorModule(CUDATestCase): + def setUp(self): + super().setUp() + np.random.seed(0) + + """ + Test if operator module is supported by the CUDA target. + """ + def operator_template(self, op): + @cuda.jit + def foo(a, b): + i = 0 + a[i] = op(a[i], b[i]) + + a = np.ones(1) + b = np.ones(1) + res = a.copy() + foo[1, 1](res, b) + + np.testing.assert_equal(res, op(a, b)) + + def test_add(self): + self.operator_template(operator.add) + + def test_sub(self): + self.operator_template(operator.sub) + + def test_mul(self): + self.operator_template(operator.mul) + + def test_truediv(self): + self.operator_template(operator.truediv) + + def test_floordiv(self): + self.operator_template(operator.floordiv) + + @skip_unless_cc_53 + def test_fp16_binary(self): + functions = (simple_fp16add, simple_fp16sub, simple_fp16mul, + simple_fp16_div_scalar) + ops = (operator.add, operator.sub, operator.mul, operator.truediv) + + for fn, op in zip(functions, ops): + with self.subTest(op=op): + kernel = cuda.jit("void(f2[:], f2, f2)")(fn) + + got = np.zeros(1, dtype=np.float16) + arg1 = np.random.random(1).astype(np.float16) + arg2 = np.random.random(1).astype(np.float16) + + kernel[1, 1](got, arg1[0], arg2[0]) + expected = op(arg1, arg2) + np.testing.assert_allclose(got, expected) + + @skip_on_cudasim('Compilation unsupported in the simulator') + def test_fp16_binary_ptx(self): + functions = (simple_fp16add, simple_fp16sub, simple_fp16mul) + instrs = ('add.f16', 'sub.f16', 'mul.f16') + args = (f2[:], f2, f2) + for fn, instr in zip(functions, instrs): + with self.subTest(instr=instr): + ptx, _ = compile_ptx(fn, args, cc=(5, 3)) + self.assertIn(instr, ptx) + + @skip_unless_cc_53 + def test_mixed_fp16_binary_arithmetic(self): + functions = (simple_fp16add, simple_fp16sub, simple_fp16mul, + simple_fp16_div_scalar) + ops = (operator.add, operator.sub, operator.mul, operator.truediv) + types = (np.int8, np.int16, np.int32, np.int64, + np.float32, np.float64) + for (fn, op), ty in itertools.product(zip(functions, ops), types): + with self.subTest(op=op, ty=ty): + kernel = cuda.jit(fn) + + arg1 = np.random.random(1).astype(np.float16) + arg2 = (np.random.random(1) * 100).astype(ty) + res_ty = np.result_type(np.float16, ty) + + got = np.zeros(1, dtype=res_ty) + kernel[1, 1](got, arg1[0], arg2[0]) + expected = op(arg1, arg2) + np.testing.assert_allclose(got, expected) + + @skip_on_cudasim('Compilation unsupported in the simulator') + def test_fp16_inplace_binary_ptx(self): + functions = (simple_fp16_iadd, simple_fp16_isub, simple_fp16_imul) + instrs = ('add.f16', 'sub.f16', 'mul.f16') + args = (f2[:], f2) + + for fn, instr in zip(functions, instrs): + with self.subTest(instr=instr): + ptx, _ = compile_ptx(fn, args, cc=(5, 3)) + self.assertIn(instr, ptx) + + @skip_unless_cc_53 + def test_fp16_inplace_binary(self): + functions = (simple_fp16_iadd, simple_fp16_isub, simple_fp16_imul, + simple_fp16_idiv) + ops = (operator.iadd, operator.isub, operator.imul, operator.itruediv) + + for fn, op in zip(functions, ops): + with self.subTest(op=op): + kernel = cuda.jit("void(f2[:], f2)")(fn) + + got = np.random.random(1).astype(np.float16) + expected = got.copy() + arg = np.random.random(1).astype(np.float16)[0] + kernel[1, 1](got, arg) + op(expected, arg) + np.testing.assert_allclose(got, expected) + + @skip_unless_cc_53 + def test_fp16_unary(self): + functions = (simple_fp16neg, simple_fp16abs) + ops = (operator.neg, operator.abs) + + for fn, op in zip(functions, ops): + with self.subTest(op=op): + kernel = cuda.jit("void(f2[:], f2)")(fn) + + got = np.zeros(1, dtype=np.float16) + arg1 = np.random.random(1).astype(np.float16) + + kernel[1, 1](got, arg1[0]) + expected = op(arg1) + np.testing.assert_allclose(got, expected) + + @skip_on_cudasim('Compilation unsupported in the simulator') + def test_fp16_neg_ptx(self): + args = (f2[:], f2) + ptx, _ = compile_ptx(simple_fp16neg, args, cc=(5, 3)) + self.assertIn('neg.f16', ptx) + + @skip_on_cudasim('Compilation unsupported in the simulator') + def test_fp16_abs_ptx(self): + args = (f2[:], f2) + ptx, _ = compile_ptx(simple_fp16abs, args, cc=(5, 3)) + + self.assertIn('abs.f16', ptx) + + @skip_unless_cc_53 + def test_fp16_comparison(self): + functions = (simple_fp16_gt, simple_fp16_ge, + simple_fp16_lt, simple_fp16_le, + simple_fp16_eq, simple_fp16_ne) + ops = (operator.gt, operator.ge, operator.lt, operator.le, + operator.eq, operator.ne) + + for fn, op in zip(functions, ops): + with self.subTest(op=op): + kernel = cuda.jit("void(b1[:], f2, f2)")(fn) + + got = np.zeros(1, dtype=np.bool_) + arg1 = np.random.random(1).astype(np.float16) + arg2 = np.random.random(1).astype(np.float16) + + kernel[1, 1](got, arg1[0], arg2[0]) + expected = op(arg1, arg2) + self.assertEqual(got[0], expected) + + @skip_unless_cc_53 + def test_mixed_fp16_comparison(self): + functions = (simple_fp16_gt, simple_fp16_ge, + simple_fp16_lt, simple_fp16_le, + simple_fp16_eq, simple_fp16_ne) + ops = (operator.gt, operator.ge, operator.lt, operator.le, + operator.eq, operator.ne) + types = (np.int8, np.int16, np.int32, np.int64, + np.float32, np.float64) + + for (fn, op), ty in itertools.product(zip(functions, ops), + types): + with self.subTest(op=op, ty=ty): + kernel = cuda.jit(fn) + + got = np.zeros(1, dtype=np.bool_) + arg1 = np.random.random(1).astype(np.float16) + arg2 = (np.random.random(1) * 100).astype(ty) + + kernel[1, 1](got, arg1[0], arg2[0]) + expected = op(arg1, arg2) + self.assertEqual(got[0], expected) + + @skip_unless_cc_53 + def test_multiple_float16_comparisons(self): + functions = (test_multiple_hcmp_1, + test_multiple_hcmp_2, + test_multiple_hcmp_3, + test_multiple_hcmp_4, + test_multiple_hcmp_5) + for fn in functions: + with self.subTest(fn=fn): + compiled = cuda.jit("void(b1[:], f2, f2, f2)")(fn) + ary = np.zeros(1, dtype=np.bool_) + arg1 = np.float16(2.) + arg2 = np.float16(3.) + arg3 = np.float16(4.) + compiled[1, 1](ary, arg1, arg2, arg3) + self.assertTrue(ary[0]) + + @skip_unless_cc_53 + def test_multiple_float16_comparisons_false(self): + functions = (test_multiple_hcmp_1, + test_multiple_hcmp_2, + test_multiple_hcmp_3, + test_multiple_hcmp_4, + test_multiple_hcmp_5) + for fn in functions: + with self.subTest(fn=fn): + compiled = cuda.jit("void(b1[:], f2, f2, f2)")(fn) + ary = np.zeros(1, dtype=np.bool_) + arg1 = np.float16(2.) + arg2 = np.float16(3.) + arg3 = np.float16(1.) + compiled[1, 1](ary, arg1, arg2, arg3) + self.assertFalse(ary[0]) + + @skip_on_cudasim('Compilation unsupported in the simulator') + def test_fp16_comparison_ptx(self): + functions = (simple_fp16_gt, simple_fp16_ge, + simple_fp16_lt, simple_fp16_le, + simple_fp16_eq, simple_fp16_ne) + ops = (operator.gt, operator.ge, operator.lt, operator.le, + operator.eq, operator.ne) + opstring = ('setp.gt.f16', 'setp.ge.f16', + 'setp.lt.f16', 'setp.le.f16', + 'setp.eq.f16', 'setp.ne.f16') + args = (b1[:], f2, f2) + + for fn, op, s in zip(functions, ops, opstring): + with self.subTest(op=op): + ptx, _ = compile_ptx(fn, args, cc=(5, 3)) + self.assertIn(s, ptx) + + @skip_on_cudasim('Compilation unsupported in the simulator') + def test_fp16_int8_comparison_ptx(self): + # Test that int8 can be safely converted to fp16 + # in a comparison + functions = (simple_fp16_gt, simple_fp16_ge, + simple_fp16_lt, simple_fp16_le, + simple_fp16_eq, simple_fp16_ne) + ops = (operator.gt, operator.ge, operator.lt, operator.le, + operator.eq, operator.ne) + + opstring = {operator.gt:'setp.gt.f16', + operator.ge:'setp.ge.f16', + operator.lt:'setp.lt.f16', + operator.le:'setp.le.f16', + operator.eq:'setp.eq.f16', + operator.ne:'setp.ne.f16'} + for fn, op in zip(functions, ops): + with self.subTest(op=op): + args = (b1[:], f2, from_dtype(np.int8)) + ptx, _ = compile_ptx(fn, args, cc=(5, 3)) + self.assertIn(opstring[op], ptx) + + @skip_on_cudasim('Compilation unsupported in the simulator') + def test_mixed_fp16_comparison_promotion_ptx(self): + functions = (simple_fp16_gt, simple_fp16_ge, + simple_fp16_lt, simple_fp16_le, + simple_fp16_eq, simple_fp16_ne) + ops = (operator.gt, operator.ge, operator.lt, operator.le, + operator.eq, operator.ne) + + types_promote = (np.int16, np.int32, np.int64, + np.float32, np.float64) + opstring = {operator.gt:'setp.gt.', + operator.ge:'setp.ge.', + operator.lt:'setp.lt.', + operator.le:'setp.le.', + operator.eq:'setp.eq.', + operator.ne:'setp.neu.'} + opsuffix = {np.dtype('int32'): 'f64', + np.dtype('int64'): 'f64', + np.dtype('float32'): 'f32', + np.dtype('float64'): 'f64'} + + for (fn, op), ty in itertools.product(zip(functions, ops), + types_promote): + with self.subTest(op=op, ty=ty): + arg2_ty = np.result_type(np.float16, ty) + args = (b1[:], f2, from_dtype(arg2_ty)) + ptx, _ = compile_ptx(fn, args, cc=(5, 3)) + + ops = opstring[op] + opsuffix[arg2_ty] + self.assertIn(ops, ptx) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/d2/d27477469f0902246f9603025c4f501bd327760e96c58ecf8dd8649ad3bcb0f5/blob b/shared/package-files/d2/d27477469f0902246f9603025c4f501bd327760e96c58ecf8dd8649ad3bcb0f5/blob new file mode 100644 index 0000000000000000000000000000000000000000..0ad4be0c06370313dec0bb7c1a95daab56184970 --- /dev/null +++ b/shared/package-files/d2/d27477469f0902246f9603025c4f501bd327760e96c58ecf8dd8649ad3bcb0f5/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple unique_consecutive(const at::Tensor & self, bool return_inverse=false, bool return_counts=false, c10::optional dim=c10::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/d2/d274c577af768cabf11e9c249646f3d65441c8f1538ff7f5c66b55b24d238b61/blob b/shared/package-files/d2/d274c577af768cabf11e9c249646f3d65441c8f1538ff7f5c66b55b24d238b61/blob new file mode 100644 index 0000000000000000000000000000000000000000..5da046ab01fdf8fe053b30d6615fb43164a1de4d --- /dev/null +++ b/shared/package-files/d2/d274c577af768cabf11e9c249646f3d65441c8f1538ff7f5c66b55b24d238b61/blob @@ -0,0 +1,1295 @@ +# -*- coding: utf-8 -*- +import codecs +import warnings +import re +from contextlib import contextmanager + +from parso.normalizer import Normalizer, NormalizerConfig, Issue, Rule +from parso.python.tokenize import _get_token_collection + +_BLOCK_STMTS = ('if_stmt', 'while_stmt', 'for_stmt', 'try_stmt', 'with_stmt') +_STAR_EXPR_PARENTS = ('testlist_star_expr', 'testlist_comp', 'exprlist') +# This is the maximal block size given by python. +_MAX_BLOCK_SIZE = 20 +_MAX_INDENT_COUNT = 100 +ALLOWED_FUTURES = ( + 'nested_scopes', 'generators', 'division', 'absolute_import', + 'with_statement', 'print_function', 'unicode_literals', 'generator_stop', +) +_COMP_FOR_TYPES = ('comp_for', 'sync_comp_for') + + +def _get_rhs_name(node, version): + type_ = node.type + if type_ == "lambdef": + return "lambda" + elif type_ == "atom": + comprehension = _get_comprehension_type(node) + first, second = node.children[:2] + if comprehension is not None: + return comprehension + elif second.type == "dictorsetmaker": + if version < (3, 8): + return "literal" + else: + if second.children[1] == ":" or second.children[0] == "**": + return "dict display" + else: + return "set display" + elif ( + first == "(" + and (second == ")" + or (len(node.children) == 3 and node.children[1].type == "testlist_comp")) + ): + return "tuple" + elif first == "(": + return _get_rhs_name(_remove_parens(node), version=version) + elif first == "[": + return "list" + elif first == "{" and second == "}": + return "dict display" + elif first == "{" and len(node.children) > 2: + return "set display" + elif type_ == "keyword": + if "yield" in node.value: + return "yield expression" + if version < (3, 8): + return "keyword" + else: + return str(node.value) + elif type_ == "operator" and node.value == "...": + return "Ellipsis" + elif type_ == "comparison": + return "comparison" + elif type_ in ("string", "number", "strings"): + return "literal" + elif type_ == "yield_expr": + return "yield expression" + elif type_ == "test": + return "conditional expression" + elif type_ in ("atom_expr", "power"): + if node.children[0] == "await": + return "await expression" + elif node.children[-1].type == "trailer": + trailer = node.children[-1] + if trailer.children[0] == "(": + return "function call" + elif trailer.children[0] == "[": + return "subscript" + elif trailer.children[0] == ".": + return "attribute" + elif ( + ("expr" in type_ and "star_expr" not in type_) # is a substring + or "_test" in type_ + or type_ in ("term", "factor") + ): + return "operator" + elif type_ == "star_expr": + return "starred" + elif type_ == "testlist_star_expr": + return "tuple" + elif type_ == "fstring": + return "f-string expression" + return type_ # shouldn't reach here + + +def _iter_stmts(scope): + """ + Iterates over all statements and splits up simple_stmt. + """ + for child in scope.children: + if child.type == 'simple_stmt': + for child2 in child.children: + if child2.type == 'newline' or child2 == ';': + continue + yield child2 + else: + yield child + + +def _get_comprehension_type(atom): + first, second = atom.children[:2] + if second.type == 'testlist_comp' and second.children[1].type in _COMP_FOR_TYPES: + if first == '[': + return 'list comprehension' + else: + return 'generator expression' + elif second.type == 'dictorsetmaker' and second.children[-1].type in _COMP_FOR_TYPES: + if second.children[1] == ':': + return 'dict comprehension' + else: + return 'set comprehension' + return None + + +def _is_future_import(import_from): + # It looks like a __future__ import that is relative is still a future + # import. That feels kind of odd, but whatever. + # if import_from.level != 0: + # return False + from_names = import_from.get_from_names() + return [n.value for n in from_names] == ['__future__'] + + +def _remove_parens(atom): + """ + Returns the inner part of an expression like `(foo)`. Also removes nested + parens. + """ + try: + children = atom.children + except AttributeError: + pass + else: + if len(children) == 3 and children[0] == '(': + return _remove_parens(atom.children[1]) + return atom + + +def _skip_parens_bottom_up(node): + """ + Returns an ancestor node of an expression, skipping all levels of parens + bottom-up. + """ + while node.parent is not None: + node = node.parent + if node.type != 'atom' or node.children[0] != '(': + return node + return None + + +def _iter_params(parent_node): + return (n for n in parent_node.children if n.type == 'param' or n.type == 'operator') + + +def _is_future_import_first(import_from): + """ + Checks if the import is the first statement of a file. + """ + found_docstring = False + for stmt in _iter_stmts(import_from.get_root_node()): + if stmt.type == 'string' and not found_docstring: + continue + found_docstring = True + + if stmt == import_from: + return True + if stmt.type == 'import_from' and _is_future_import(stmt): + continue + return False + + +def _iter_definition_exprs_from_lists(exprlist): + def check_expr(child): + if child.type == 'atom': + if child.children[0] == '(': + testlist_comp = child.children[1] + if testlist_comp.type == 'testlist_comp': + yield from _iter_definition_exprs_from_lists(testlist_comp) + return + else: + # It's a paren that doesn't do anything, like 1 + (1) + yield from check_expr(testlist_comp) + return + elif child.children[0] == '[': + yield testlist_comp + return + yield child + + if exprlist.type in _STAR_EXPR_PARENTS: + for child in exprlist.children[::2]: + yield from check_expr(child) + else: + yield from check_expr(exprlist) + + +def _get_expr_stmt_definition_exprs(expr_stmt): + exprs = [] + for list_ in expr_stmt.children[:-2:2]: + if list_.type in ('testlist_star_expr', 'testlist'): + exprs += _iter_definition_exprs_from_lists(list_) + else: + exprs.append(list_) + return exprs + + +def _get_for_stmt_definition_exprs(for_stmt): + exprlist = for_stmt.children[1] + return list(_iter_definition_exprs_from_lists(exprlist)) + + +def _is_argument_comprehension(argument): + return argument.children[1].type in _COMP_FOR_TYPES + + +def _any_fstring_error(version, node): + if version < (3, 9) or node is None: + return False + if node.type == "error_node": + return any(child.type == "fstring_start" for child in node.children) + elif node.type == "fstring": + return True + else: + return node.search_ancestor("fstring") + + +class _Context: + def __init__(self, node, add_syntax_error, parent_context=None): + self.node = node + self.blocks = [] + self.parent_context = parent_context + self._used_name_dict = {} + self._global_names = [] + self._local_params_names = [] + self._nonlocal_names = [] + self._nonlocal_names_in_subscopes = [] + self._add_syntax_error = add_syntax_error + + def is_async_funcdef(self): + # Stupidly enough async funcdefs can have two different forms, + # depending if a decorator is used or not. + return self.is_function() \ + and self.node.parent.type in ('async_funcdef', 'async_stmt') + + def is_function(self): + return self.node.type == 'funcdef' + + def add_name(self, name): + parent_type = name.parent.type + if parent_type == 'trailer': + # We are only interested in first level names. + return + + if parent_type == 'global_stmt': + self._global_names.append(name) + elif parent_type == 'nonlocal_stmt': + self._nonlocal_names.append(name) + elif parent_type == 'funcdef': + self._local_params_names.extend( + [param.name.value for param in name.parent.get_params()] + ) + else: + self._used_name_dict.setdefault(name.value, []).append(name) + + def finalize(self): + """ + Returns a list of nonlocal names that need to be part of that scope. + """ + self._analyze_names(self._global_names, 'global') + self._analyze_names(self._nonlocal_names, 'nonlocal') + + global_name_strs = {n.value: n for n in self._global_names} + for nonlocal_name in self._nonlocal_names: + try: + global_name = global_name_strs[nonlocal_name.value] + except KeyError: + continue + + message = "name '%s' is nonlocal and global" % global_name.value + if global_name.start_pos < nonlocal_name.start_pos: + error_name = global_name + else: + error_name = nonlocal_name + self._add_syntax_error(error_name, message) + + nonlocals_not_handled = [] + for nonlocal_name in self._nonlocal_names_in_subscopes: + search = nonlocal_name.value + if search in self._local_params_names: + continue + if search in global_name_strs or self.parent_context is None: + message = "no binding for nonlocal '%s' found" % nonlocal_name.value + self._add_syntax_error(nonlocal_name, message) + elif not self.is_function() or \ + nonlocal_name.value not in self._used_name_dict: + nonlocals_not_handled.append(nonlocal_name) + return self._nonlocal_names + nonlocals_not_handled + + def _analyze_names(self, globals_or_nonlocals, type_): + def raise_(message): + self._add_syntax_error(base_name, message % (base_name.value, type_)) + + params = [] + if self.node.type == 'funcdef': + params = self.node.get_params() + + for base_name in globals_or_nonlocals: + found_global_or_nonlocal = False + # Somehow Python does it the reversed way. + for name in reversed(self._used_name_dict.get(base_name.value, [])): + if name.start_pos > base_name.start_pos: + # All following names don't have to be checked. + found_global_or_nonlocal = True + + parent = name.parent + if parent.type == 'param' and parent.name == name: + # Skip those here, these definitions belong to the next + # scope. + continue + + if name.is_definition(): + if parent.type == 'expr_stmt' \ + and parent.children[1].type == 'annassign': + if found_global_or_nonlocal: + # If it's after the global the error seems to be + # placed there. + base_name = name + raise_("annotated name '%s' can't be %s") + break + else: + message = "name '%s' is assigned to before %s declaration" + else: + message = "name '%s' is used prior to %s declaration" + + if not found_global_or_nonlocal: + raise_(message) + # Only add an error for the first occurence. + break + + for param in params: + if param.name.value == base_name.value: + raise_("name '%s' is parameter and %s"), + + @contextmanager + def add_block(self, node): + self.blocks.append(node) + yield + self.blocks.pop() + + def add_context(self, node): + return _Context(node, self._add_syntax_error, parent_context=self) + + def close_child_context(self, child_context): + self._nonlocal_names_in_subscopes += child_context.finalize() + + +class ErrorFinder(Normalizer): + """ + Searches for errors in the syntax tree. + """ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._error_dict = {} + self.version = self.grammar.version_info + + def initialize(self, node): + def create_context(node): + if node is None: + return None + + parent_context = create_context(node.parent) + if node.type in ('classdef', 'funcdef', 'file_input'): + return _Context(node, self._add_syntax_error, parent_context) + return parent_context + + self.context = create_context(node) or _Context(node, self._add_syntax_error) + self._indentation_count = 0 + + def visit(self, node): + if node.type == 'error_node': + with self.visit_node(node): + # Don't need to investigate the inners of an error node. We + # might find errors in there that should be ignored, because + # the error node itself already shows that there's an issue. + return '' + return super().visit(node) + + @contextmanager + def visit_node(self, node): + self._check_type_rules(node) + + if node.type in _BLOCK_STMTS: + with self.context.add_block(node): + if len(self.context.blocks) == _MAX_BLOCK_SIZE: + self._add_syntax_error(node, "too many statically nested blocks") + yield + return + elif node.type == 'suite': + self._indentation_count += 1 + if self._indentation_count == _MAX_INDENT_COUNT: + self._add_indentation_error(node.children[1], "too many levels of indentation") + + yield + + if node.type == 'suite': + self._indentation_count -= 1 + elif node.type in ('classdef', 'funcdef'): + context = self.context + self.context = context.parent_context + self.context.close_child_context(context) + + def visit_leaf(self, leaf): + if leaf.type == 'error_leaf': + if leaf.token_type in ('INDENT', 'ERROR_DEDENT'): + # Indents/Dedents itself never have a prefix. They are just + # "pseudo" tokens that get removed by the syntax tree later. + # Therefore in case of an error we also have to check for this. + spacing = list(leaf.get_next_leaf()._split_prefix())[-1] + if leaf.token_type == 'INDENT': + message = 'unexpected indent' + else: + message = 'unindent does not match any outer indentation level' + self._add_indentation_error(spacing, message) + else: + if leaf.value.startswith('\\'): + message = 'unexpected character after line continuation character' + else: + match = re.match('\\w{,2}("{1,3}|\'{1,3})', leaf.value) + if match is None: + message = 'invalid syntax' + if ( + self.version >= (3, 9) + and leaf.value in _get_token_collection( + self.version + ).always_break_tokens + ): + message = "f-string: " + message + else: + if len(match.group(1)) == 1: + message = 'EOL while scanning string literal' + else: + message = 'EOF while scanning triple-quoted string literal' + self._add_syntax_error(leaf, message) + return '' + elif leaf.value == ':': + parent = leaf.parent + if parent.type in ('classdef', 'funcdef'): + self.context = self.context.add_context(parent) + + # The rest is rule based. + return super().visit_leaf(leaf) + + def _add_indentation_error(self, spacing, message): + self.add_issue(spacing, 903, "IndentationError: " + message) + + def _add_syntax_error(self, node, message): + self.add_issue(node, 901, "SyntaxError: " + message) + + def add_issue(self, node, code, message): + # Overwrite the default behavior. + # Check if the issues are on the same line. + line = node.start_pos[0] + args = (code, message, node) + self._error_dict.setdefault(line, args) + + def finalize(self): + self.context.finalize() + + for code, message, node in self._error_dict.values(): + self.issues.append(Issue(node, code, message)) + + +class IndentationRule(Rule): + code = 903 + + def _get_message(self, message, node): + message = super()._get_message(message, node) + return "IndentationError: " + message + + +@ErrorFinder.register_rule(type='error_node') +class _ExpectIndentedBlock(IndentationRule): + message = 'expected an indented block' + + def get_node(self, node): + leaf = node.get_next_leaf() + return list(leaf._split_prefix())[-1] + + def is_issue(self, node): + # This is the beginning of a suite that is not indented. + return node.children[-1].type == 'newline' + + +class ErrorFinderConfig(NormalizerConfig): + normalizer_class = ErrorFinder + + +class SyntaxRule(Rule): + code = 901 + + def _get_message(self, message, node): + message = super()._get_message(message, node) + if ( + "f-string" not in message + and _any_fstring_error(self._normalizer.version, node) + ): + message = "f-string: " + message + return "SyntaxError: " + message + + +@ErrorFinder.register_rule(type='error_node') +class _InvalidSyntaxRule(SyntaxRule): + message = "invalid syntax" + fstring_message = "f-string: invalid syntax" + + def get_node(self, node): + return node.get_next_leaf() + + def is_issue(self, node): + error = node.get_next_leaf().type != 'error_leaf' + if ( + error + and _any_fstring_error(self._normalizer.version, node) + ): + self.add_issue(node, message=self.fstring_message) + else: + # Error leafs will be added later as an error. + return error + + +@ErrorFinder.register_rule(value='await') +class _AwaitOutsideAsync(SyntaxRule): + message = "'await' outside async function" + + def is_issue(self, leaf): + return not self._normalizer.context.is_async_funcdef() + + def get_error_node(self, node): + # Return the whole await statement. + return node.parent + + +@ErrorFinder.register_rule(value='break') +class _BreakOutsideLoop(SyntaxRule): + message = "'break' outside loop" + + def is_issue(self, leaf): + in_loop = False + for block in self._normalizer.context.blocks: + if block.type in ('for_stmt', 'while_stmt'): + in_loop = True + return not in_loop + + +@ErrorFinder.register_rule(value='continue') +class _ContinueChecks(SyntaxRule): + message = "'continue' not properly in loop" + message_in_finally = "'continue' not supported inside 'finally' clause" + + def is_issue(self, leaf): + in_loop = False + for block in self._normalizer.context.blocks: + if block.type in ('for_stmt', 'while_stmt'): + in_loop = True + if block.type == 'try_stmt': + last_block = block.children[-3] + if ( + last_block == "finally" + and leaf.start_pos > last_block.start_pos + and self._normalizer.version < (3, 8) + ): + self.add_issue(leaf, message=self.message_in_finally) + return False # Error already added + if not in_loop: + return True + + +@ErrorFinder.register_rule(value='from') +class _YieldFromCheck(SyntaxRule): + message = "'yield from' inside async function" + + def get_node(self, leaf): + return leaf.parent.parent # This is the actual yield statement. + + def is_issue(self, leaf): + return leaf.parent.type == 'yield_arg' \ + and self._normalizer.context.is_async_funcdef() + + +@ErrorFinder.register_rule(type='name') +class _NameChecks(SyntaxRule): + message = 'cannot assign to __debug__' + message_none = 'cannot assign to None' + + def is_issue(self, leaf): + self._normalizer.context.add_name(leaf) + + if leaf.value == '__debug__' and leaf.is_definition(): + return True + + +@ErrorFinder.register_rule(type='string') +class _StringChecks(SyntaxRule): + message = "bytes can only contain ASCII literal characters." + + def is_issue(self, leaf): + string_prefix = leaf.string_prefix.lower() + if 'b' in string_prefix \ + and any(c for c in leaf.value if ord(c) > 127): + # b'ä' + return True + + if 'r' not in string_prefix: + # Raw strings don't need to be checked if they have proper + # escaping. + + payload = leaf._get_payload() + if 'b' in string_prefix: + payload = payload.encode('utf-8') + func = codecs.escape_decode + else: + func = codecs.unicode_escape_decode + + try: + with warnings.catch_warnings(): + # The warnings from parsing strings are not relevant. + warnings.filterwarnings('ignore') + func(payload) + except UnicodeDecodeError as e: + self.add_issue(leaf, message='(unicode error) ' + str(e)) + except ValueError as e: + self.add_issue(leaf, message='(value error) ' + str(e)) + + +@ErrorFinder.register_rule(value='*') +class _StarCheck(SyntaxRule): + message = "named arguments must follow bare *" + + def is_issue(self, leaf): + params = leaf.parent + if params.type == 'parameters' and params: + after = params.children[params.children.index(leaf) + 1:] + after = [child for child in after + if child not in (',', ')') and not child.star_count] + return len(after) == 0 + + +@ErrorFinder.register_rule(value='**') +class _StarStarCheck(SyntaxRule): + # e.g. {**{} for a in [1]} + # TODO this should probably get a better end_pos including + # the next sibling of leaf. + message = "dict unpacking cannot be used in dict comprehension" + + def is_issue(self, leaf): + if leaf.parent.type == 'dictorsetmaker': + comp_for = leaf.get_next_sibling().get_next_sibling() + return comp_for is not None and comp_for.type in _COMP_FOR_TYPES + + +@ErrorFinder.register_rule(value='yield') +@ErrorFinder.register_rule(value='return') +class _ReturnAndYieldChecks(SyntaxRule): + message = "'return' with value in async generator" + message_async_yield = "'yield' inside async function" + + def get_node(self, leaf): + return leaf.parent + + def is_issue(self, leaf): + if self._normalizer.context.node.type != 'funcdef': + self.add_issue(self.get_node(leaf), message="'%s' outside function" % leaf.value) + elif self._normalizer.context.is_async_funcdef() \ + and any(self._normalizer.context.node.iter_yield_exprs()): + if leaf.value == 'return' and leaf.parent.type == 'return_stmt': + return True + + +@ErrorFinder.register_rule(type='strings') +class _BytesAndStringMix(SyntaxRule): + # e.g. 's' b'' + message = "cannot mix bytes and nonbytes literals" + + def _is_bytes_literal(self, string): + if string.type == 'fstring': + return False + return 'b' in string.string_prefix.lower() + + def is_issue(self, node): + first = node.children[0] + first_is_bytes = self._is_bytes_literal(first) + for string in node.children[1:]: + if first_is_bytes != self._is_bytes_literal(string): + return True + + +@ErrorFinder.register_rule(type='import_as_names') +class _TrailingImportComma(SyntaxRule): + # e.g. from foo import a, + message = "trailing comma not allowed without surrounding parentheses" + + def is_issue(self, node): + if node.children[-1] == ',' and node.parent.children[-1] != ')': + return True + + +@ErrorFinder.register_rule(type='import_from') +class _ImportStarInFunction(SyntaxRule): + message = "import * only allowed at module level" + + def is_issue(self, node): + return node.is_star_import() and self._normalizer.context.parent_context is not None + + +@ErrorFinder.register_rule(type='import_from') +class _FutureImportRule(SyntaxRule): + message = "from __future__ imports must occur at the beginning of the file" + + def is_issue(self, node): + if _is_future_import(node): + if not _is_future_import_first(node): + return True + + for from_name, future_name in node.get_paths(): + name = future_name.value + allowed_futures = list(ALLOWED_FUTURES) + if self._normalizer.version >= (3, 7): + allowed_futures.append('annotations') + if name == 'braces': + self.add_issue(node, message="not a chance") + elif name == 'barry_as_FLUFL': + m = "Seriously I'm not implementing this :) ~ Dave" + self.add_issue(node, message=m) + elif name not in allowed_futures: + message = "future feature %s is not defined" % name + self.add_issue(node, message=message) + + +@ErrorFinder.register_rule(type='star_expr') +class _StarExprRule(SyntaxRule): + message_iterable_unpacking = "iterable unpacking cannot be used in comprehension" + + def is_issue(self, node): + def check_delete_starred(node): + while node.parent is not None: + node = node.parent + if node.type == 'del_stmt': + return True + if node.type not in (*_STAR_EXPR_PARENTS, 'atom'): + return False + return False + + if self._normalizer.version >= (3, 9): + ancestor = node.parent + else: + ancestor = _skip_parens_bottom_up(node) + # starred expression not in tuple/list/set + if ancestor.type not in (*_STAR_EXPR_PARENTS, 'dictorsetmaker') \ + and not (ancestor.type == 'atom' and ancestor.children[0] != '('): + self.add_issue(node, message="can't use starred expression here") + return + + if check_delete_starred(node): + if self._normalizer.version >= (3, 9): + self.add_issue(node, message="cannot delete starred") + else: + self.add_issue(node, message="can't use starred expression here") + return + + if node.parent.type == 'testlist_comp': + # [*[] for a in [1]] + if node.parent.children[1].type in _COMP_FOR_TYPES: + self.add_issue(node, message=self.message_iterable_unpacking) + + +@ErrorFinder.register_rule(types=_STAR_EXPR_PARENTS) +class _StarExprParentRule(SyntaxRule): + def is_issue(self, node): + def is_definition(node, ancestor): + if ancestor is None: + return False + + type_ = ancestor.type + if type_ == 'trailer': + return False + + if type_ == 'expr_stmt': + return node.start_pos < ancestor.children[-1].start_pos + + return is_definition(node, ancestor.parent) + + if is_definition(node, node.parent): + args = [c for c in node.children if c != ','] + starred = [c for c in args if c.type == 'star_expr'] + if len(starred) > 1: + if self._normalizer.version < (3, 9): + message = "two starred expressions in assignment" + else: + message = "multiple starred expressions in assignment" + self.add_issue(starred[1], message=message) + elif starred: + count = args.index(starred[0]) + if count >= 256: + message = "too many expressions in star-unpacking assignment" + self.add_issue(starred[0], message=message) + + +@ErrorFinder.register_rule(type='annassign') +class _AnnotatorRule(SyntaxRule): + # True: int + # {}: float + message = "illegal target for annotation" + + def get_node(self, node): + return node.parent + + def is_issue(self, node): + type_ = None + lhs = node.parent.children[0] + lhs = _remove_parens(lhs) + try: + children = lhs.children + except AttributeError: + pass + else: + if ',' in children or lhs.type == 'atom' and children[0] == '(': + type_ = 'tuple' + elif lhs.type == 'atom' and children[0] == '[': + type_ = 'list' + trailer = children[-1] + + if type_ is None: + if not (lhs.type == 'name' + # subscript/attributes are allowed + or lhs.type in ('atom_expr', 'power') + and trailer.type == 'trailer' + and trailer.children[0] != '('): + return True + else: + # x, y: str + message = "only single target (not %s) can be annotated" + self.add_issue(lhs.parent, message=message % type_) + + +@ErrorFinder.register_rule(type='argument') +class _ArgumentRule(SyntaxRule): + def is_issue(self, node): + first = node.children[0] + if self._normalizer.version < (3, 8): + # a((b)=c) is valid in <3.8 + first = _remove_parens(first) + if node.children[1] == '=' and first.type != 'name': + if first.type == 'lambdef': + # f(lambda: 1=1) + if self._normalizer.version < (3, 8): + message = "lambda cannot contain assignment" + else: + message = 'expression cannot contain assignment, perhaps you meant "=="?' + else: + # f(+x=1) + if self._normalizer.version < (3, 8): + message = "keyword can't be an expression" + else: + message = 'expression cannot contain assignment, perhaps you meant "=="?' + self.add_issue(first, message=message) + + if _is_argument_comprehension(node) and node.parent.type == 'classdef': + self.add_issue(node, message='invalid syntax') + + +@ErrorFinder.register_rule(type='nonlocal_stmt') +class _NonlocalModuleLevelRule(SyntaxRule): + message = "nonlocal declaration not allowed at module level" + + def is_issue(self, node): + return self._normalizer.context.parent_context is None + + +@ErrorFinder.register_rule(type='arglist') +class _ArglistRule(SyntaxRule): + @property + def message(self): + if self._normalizer.version < (3, 7): + return "Generator expression must be parenthesized if not sole argument" + else: + return "Generator expression must be parenthesized" + + def is_issue(self, node): + arg_set = set() + kw_only = False + kw_unpacking_only = False + for argument in node.children: + if argument == ',': + continue + + if argument.type == 'argument': + first = argument.children[0] + if _is_argument_comprehension(argument) and len(node.children) >= 2: + # a(a, b for b in c) + return True + + if first in ('*', '**'): + if first == '*': + if kw_unpacking_only: + # foo(**kwargs, *args) + message = "iterable argument unpacking " \ + "follows keyword argument unpacking" + self.add_issue(argument, message=message) + else: + kw_unpacking_only = True + else: # Is a keyword argument. + kw_only = True + if first.type == 'name': + if first.value in arg_set: + # f(x=1, x=2) + message = "keyword argument repeated" + if self._normalizer.version >= (3, 9): + message += ": {}".format(first.value) + self.add_issue(first, message=message) + else: + arg_set.add(first.value) + else: + if kw_unpacking_only: + # f(**x, y) + message = "positional argument follows keyword argument unpacking" + self.add_issue(argument, message=message) + elif kw_only: + # f(x=2, y) + message = "positional argument follows keyword argument" + self.add_issue(argument, message=message) + + +@ErrorFinder.register_rule(type='parameters') +@ErrorFinder.register_rule(type='lambdef') +class _ParameterRule(SyntaxRule): + # def f(x=3, y): pass + message = "non-default argument follows default argument" + + def is_issue(self, node): + param_names = set() + default_only = False + star_seen = False + for p in _iter_params(node): + if p.type == 'operator': + if p.value == '*': + star_seen = True + default_only = False + continue + + if p.name.value in param_names: + message = "duplicate argument '%s' in function definition" + self.add_issue(p.name, message=message % p.name.value) + param_names.add(p.name.value) + + if not star_seen: + if p.default is None and not p.star_count: + if default_only: + return True + elif p.star_count: + star_seen = True + default_only = False + else: + default_only = True + + +@ErrorFinder.register_rule(type='try_stmt') +class _TryStmtRule(SyntaxRule): + message = "default 'except:' must be last" + + def is_issue(self, try_stmt): + default_except = None + for except_clause in try_stmt.children[3::3]: + if except_clause in ('else', 'finally'): + break + if except_clause == 'except': + default_except = except_clause + elif default_except is not None: + self.add_issue(default_except, message=self.message) + + +@ErrorFinder.register_rule(type='fstring') +class _FStringRule(SyntaxRule): + _fstring_grammar = None + message_expr = "f-string expression part cannot include a backslash" + message_nested = "f-string: expressions nested too deeply" + message_conversion = "f-string: invalid conversion character: expected 's', 'r', or 'a'" + + def _check_format_spec(self, format_spec, depth): + self._check_fstring_contents(format_spec.children[1:], depth) + + def _check_fstring_expr(self, fstring_expr, depth): + if depth >= 2: + self.add_issue(fstring_expr, message=self.message_nested) + + expr = fstring_expr.children[1] + if '\\' in expr.get_code(): + self.add_issue(expr, message=self.message_expr) + + children_2 = fstring_expr.children[2] + if children_2.type == 'operator' and children_2.value == '=': + conversion = fstring_expr.children[3] + else: + conversion = children_2 + if conversion.type == 'fstring_conversion': + name = conversion.children[1] + if name.value not in ('s', 'r', 'a'): + self.add_issue(name, message=self.message_conversion) + + format_spec = fstring_expr.children[-2] + if format_spec.type == 'fstring_format_spec': + self._check_format_spec(format_spec, depth + 1) + + def is_issue(self, fstring): + self._check_fstring_contents(fstring.children[1:-1]) + + def _check_fstring_contents(self, children, depth=0): + for fstring_content in children: + if fstring_content.type == 'fstring_expr': + self._check_fstring_expr(fstring_content, depth) + + +class _CheckAssignmentRule(SyntaxRule): + def _check_assignment(self, node, is_deletion=False, is_namedexpr=False, is_aug_assign=False): + error = None + type_ = node.type + if type_ == 'lambdef': + error = 'lambda' + elif type_ == 'atom': + first, second = node.children[:2] + error = _get_comprehension_type(node) + if error is None: + if second.type == 'dictorsetmaker': + if self._normalizer.version < (3, 8): + error = 'literal' + else: + if second.children[1] == ':': + error = 'dict display' + else: + error = 'set display' + elif first == "{" and second == "}": + if self._normalizer.version < (3, 8): + error = 'literal' + else: + error = "dict display" + elif first == "{" and len(node.children) > 2: + if self._normalizer.version < (3, 8): + error = 'literal' + else: + error = "set display" + elif first in ('(', '['): + if second.type == 'yield_expr': + error = 'yield expression' + elif second.type == 'testlist_comp': + # ([a, b] := [1, 2]) + # ((a, b) := [1, 2]) + if is_namedexpr: + if first == '(': + error = 'tuple' + elif first == '[': + error = 'list' + + # This is not a comprehension, they were handled + # further above. + for child in second.children[::2]: + self._check_assignment(child, is_deletion, is_namedexpr, is_aug_assign) + else: # Everything handled, must be useless brackets. + self._check_assignment(second, is_deletion, is_namedexpr, is_aug_assign) + elif type_ == 'keyword': + if node.value == "yield": + error = "yield expression" + elif self._normalizer.version < (3, 8): + error = 'keyword' + else: + error = str(node.value) + elif type_ == 'operator': + if node.value == '...': + error = 'Ellipsis' + elif type_ == 'comparison': + error = 'comparison' + elif type_ in ('string', 'number', 'strings'): + error = 'literal' + elif type_ == 'yield_expr': + # This one seems to be a slightly different warning in Python. + message = 'assignment to yield expression not possible' + self.add_issue(node, message=message) + elif type_ == 'test': + error = 'conditional expression' + elif type_ in ('atom_expr', 'power'): + if node.children[0] == 'await': + error = 'await expression' + elif node.children[-2] == '**': + error = 'operator' + else: + # Has a trailer + trailer = node.children[-1] + assert trailer.type == 'trailer' + if trailer.children[0] == '(': + error = 'function call' + elif is_namedexpr and trailer.children[0] == '[': + error = 'subscript' + elif is_namedexpr and trailer.children[0] == '.': + error = 'attribute' + elif type_ == "fstring": + if self._normalizer.version < (3, 8): + error = 'literal' + else: + error = "f-string expression" + elif type_ in ('testlist_star_expr', 'exprlist', 'testlist'): + for child in node.children[::2]: + self._check_assignment(child, is_deletion, is_namedexpr, is_aug_assign) + elif ('expr' in type_ and type_ != 'star_expr' # is a substring + or '_test' in type_ + or type_ in ('term', 'factor')): + error = 'operator' + elif type_ == "star_expr": + if is_deletion: + if self._normalizer.version >= (3, 9): + error = "starred" + else: + self.add_issue(node, message="can't use starred expression here") + else: + if self._normalizer.version >= (3, 9): + ancestor = node.parent + else: + ancestor = _skip_parens_bottom_up(node) + if ancestor.type not in _STAR_EXPR_PARENTS and not is_aug_assign \ + and not (ancestor.type == 'atom' and ancestor.children[0] == '['): + message = "starred assignment target must be in a list or tuple" + self.add_issue(node, message=message) + + self._check_assignment(node.children[1]) + + if error is not None: + if is_namedexpr: + message = 'cannot use assignment expressions with %s' % error + else: + cannot = "can't" if self._normalizer.version < (3, 8) else "cannot" + message = ' '.join([cannot, "delete" if is_deletion else "assign to", error]) + self.add_issue(node, message=message) + + +@ErrorFinder.register_rule(type='sync_comp_for') +class _CompForRule(_CheckAssignmentRule): + message = "asynchronous comprehension outside of an asynchronous function" + + def is_issue(self, node): + expr_list = node.children[1] + if expr_list.type != 'expr_list': # Already handled. + self._check_assignment(expr_list) + + return node.parent.children[0] == 'async' \ + and not self._normalizer.context.is_async_funcdef() + + +@ErrorFinder.register_rule(type='expr_stmt') +class _ExprStmtRule(_CheckAssignmentRule): + message = "illegal expression for augmented assignment" + extended_message = "'{target}' is an " + message + + def is_issue(self, node): + augassign = node.children[1] + is_aug_assign = augassign != '=' and augassign.type != 'annassign' + + if self._normalizer.version <= (3, 8) or not is_aug_assign: + for before_equal in node.children[:-2:2]: + self._check_assignment(before_equal, is_aug_assign=is_aug_assign) + + if is_aug_assign: + target = _remove_parens(node.children[0]) + # a, a[b], a.b + + if target.type == "name" or ( + target.type in ("atom_expr", "power") + and target.children[1].type == "trailer" + and target.children[-1].children[0] != "(" + ): + return False + + if self._normalizer.version <= (3, 8): + return True + else: + self.add_issue( + node, + message=self.extended_message.format( + target=_get_rhs_name(node.children[0], self._normalizer.version) + ), + ) + + +@ErrorFinder.register_rule(type='with_item') +class _WithItemRule(_CheckAssignmentRule): + def is_issue(self, with_item): + self._check_assignment(with_item.children[2]) + + +@ErrorFinder.register_rule(type='del_stmt') +class _DelStmtRule(_CheckAssignmentRule): + def is_issue(self, del_stmt): + child = del_stmt.children[1] + + if child.type != 'expr_list': # Already handled. + self._check_assignment(child, is_deletion=True) + + +@ErrorFinder.register_rule(type='expr_list') +class _ExprListRule(_CheckAssignmentRule): + def is_issue(self, expr_list): + for expr in expr_list.children[::2]: + self._check_assignment(expr) + + +@ErrorFinder.register_rule(type='for_stmt') +class _ForStmtRule(_CheckAssignmentRule): + def is_issue(self, for_stmt): + # Some of the nodes here are already used, so no else if + expr_list = for_stmt.children[1] + if expr_list.type != 'expr_list': # Already handled. + self._check_assignment(expr_list) + + +@ErrorFinder.register_rule(type='namedexpr_test') +class _NamedExprRule(_CheckAssignmentRule): + # namedexpr_test: test [':=' test] + + def is_issue(self, namedexpr_test): + # assigned name + first = namedexpr_test.children[0] + + def search_namedexpr_in_comp_for(node): + while True: + parent = node.parent + if parent is None: + return parent + if parent.type == 'sync_comp_for' and parent.children[3] == node: + return parent + node = parent + + if search_namedexpr_in_comp_for(namedexpr_test): + # [i+1 for i in (i := range(5))] + # [i+1 for i in (j := range(5))] + # [i+1 for i in (lambda: (j := range(5)))()] + message = 'assignment expression cannot be used in a comprehension iterable expression' + self.add_issue(namedexpr_test, message=message) + + # defined names + exprlist = list() + + def process_comp_for(comp_for): + if comp_for.type == 'sync_comp_for': + comp = comp_for + elif comp_for.type == 'comp_for': + comp = comp_for.children[1] + exprlist.extend(_get_for_stmt_definition_exprs(comp)) + + def search_all_comp_ancestors(node): + has_ancestors = False + while True: + node = node.search_ancestor('testlist_comp', 'dictorsetmaker') + if node is None: + break + for child in node.children: + if child.type in _COMP_FOR_TYPES: + process_comp_for(child) + has_ancestors = True + break + return has_ancestors + + # check assignment expressions in comprehensions + search_all = search_all_comp_ancestors(namedexpr_test) + if search_all: + if self._normalizer.context.node.type == 'classdef': + message = 'assignment expression within a comprehension ' \ + 'cannot be used in a class body' + self.add_issue(namedexpr_test, message=message) + + namelist = [expr.value for expr in exprlist if expr.type == 'name'] + if first.type == 'name' and first.value in namelist: + # [i := 0 for i, j in range(5)] + # [[(i := i) for j in range(5)] for i in range(5)] + # [i for i, j in range(5) if True or (i := 1)] + # [False and (i := 0) for i, j in range(5)] + message = 'assignment expression cannot rebind ' \ + 'comprehension iteration variable %r' % first.value + self.add_issue(namedexpr_test, message=message) + + self._check_assignment(first, is_namedexpr=True) diff --git a/shared/package-files/d2/d27828d6a6c64b8ec8b459409cb5e153aefbf09edb570575b888d48838d83740/blob b/shared/package-files/d2/d27828d6a6c64b8ec8b459409cb5e153aefbf09edb570575b888d48838d83740/blob new file mode 100644 index 0000000000000000000000000000000000000000..4e92fb22f840a15c071cc556421a682785820411 --- /dev/null +++ b/shared/package-files/d2/d27828d6a6c64b8ec8b459409cb5e153aefbf09edb570575b888d48838d83740/blob @@ -0,0 +1,122 @@ +import numpy as np +import pytest + +from pandas.core.dtypes.common import is_integer_dtype + +from pandas import ( + DataFrame, + Index, + PeriodIndex, + Series, +) +import pandas._testing as tm + + +@pytest.mark.parametrize("by", ["A", "B", ["A", "B"]]) +def test_size(df, by): + grouped = df.groupby(by=by) + result = grouped.size() + for key, group in grouped: + assert result[key] == len(group) + + +@pytest.mark.parametrize( + "by", + [ + [0, 0, 0, 0], + [0, 1, 1, 1], + [1, 0, 1, 1], + [0, None, None, None], + pytest.param([None, None, None, None], marks=pytest.mark.xfail), + ], +) +def test_size_axis_1(df, axis_1, by, sort, dropna): + # GH#45715 + counts = {key: sum(value == key for value in by) for key in dict.fromkeys(by)} + if dropna: + counts = {key: value for key, value in counts.items() if key is not None} + expected = Series(counts, dtype="int64") + if sort: + expected = expected.sort_index() + if is_integer_dtype(expected.index.dtype) and not any(x is None for x in by): + expected.index = expected.index.astype(int) + + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped = df.groupby(by=by, axis=axis_1, sort=sort, dropna=dropna) + result = grouped.size() + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("by", ["A", "B", ["A", "B"]]) +@pytest.mark.parametrize("sort", [True, False]) +def test_size_sort(sort, by): + df = DataFrame(np.random.default_rng(2).choice(20, (1000, 3)), columns=list("ABC")) + left = df.groupby(by=by, sort=sort).size() + right = df.groupby(by=by, sort=sort)["C"].apply(lambda a: a.shape[0]) + tm.assert_series_equal(left, right, check_names=False) + + +def test_size_series_dataframe(): + # https://github.com/pandas-dev/pandas/issues/11699 + df = DataFrame(columns=["A", "B"]) + out = Series(dtype="int64", index=Index([], name="A")) + tm.assert_series_equal(df.groupby("A").size(), out) + + +def test_size_groupby_all_null(): + # https://github.com/pandas-dev/pandas/issues/23050 + # Assert no 'Value Error : Length of passed values is 2, index implies 0' + df = DataFrame({"A": [None, None]}) # all-null groups + result = df.groupby("A").size() + expected = Series(dtype="int64", index=Index([], name="A")) + tm.assert_series_equal(result, expected) + + +def test_size_period_index(): + # https://github.com/pandas-dev/pandas/issues/34010 + ser = Series([1], index=PeriodIndex(["2000"], name="A", freq="D")) + grp = ser.groupby(level="A") + result = grp.size() + tm.assert_series_equal(result, ser) + + +@pytest.mark.parametrize("as_index", [True, False]) +def test_size_on_categorical(as_index): + df = DataFrame([[1, 1], [2, 2]], columns=["A", "B"]) + df["A"] = df["A"].astype("category") + result = df.groupby(["A", "B"], as_index=as_index, observed=False).size() + + expected = DataFrame( + [[1, 1, 1], [1, 2, 0], [2, 1, 0], [2, 2, 1]], columns=["A", "B", "size"] + ) + expected["A"] = expected["A"].astype("category") + if as_index: + expected = expected.set_index(["A", "B"])["size"].rename(None) + + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean"]) +def test_size_series_masked_type_returns_Int64(dtype): + # GH 54132 + ser = Series([1, 1, 1], index=["a", "a", "b"], dtype=dtype) + result = ser.groupby(level=0).size() + expected = Series([2, 1], dtype="Int64", index=["a", "b"]) + tm.assert_series_equal(result, expected) + + +def test_size_strings(any_string_dtype, using_infer_string): + # GH#55627 + dtype = any_string_dtype + df = DataFrame({"a": ["a", "a", "b"], "b": "a"}, dtype=dtype) + result = df.groupby("a")["b"].size() + exp_dtype = "Int64" if dtype == "string[pyarrow]" else "int64" + exp_index_dtype = "str" if using_infer_string and dtype == "object" else dtype + expected = Series( + [2, 1], + index=Index(["a", "b"], name="a", dtype=exp_index_dtype), + name="b", + dtype=exp_dtype, + ) + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/d2/d2796340e9706f8dba8b2028cb1810222815f35d2adba4daad9b8dfc095eca00/blob b/shared/package-files/d2/d2796340e9706f8dba8b2028cb1810222815f35d2adba4daad9b8dfc095eca00/blob new file mode 100644 index 0000000000000000000000000000000000000000..de70b131d4fc76557b113da55ed322d9d027670f Binary files /dev/null and b/shared/package-files/d2/d2796340e9706f8dba8b2028cb1810222815f35d2adba4daad9b8dfc095eca00/blob differ diff --git a/shared/package-files/d2/d27adaf74ebb18d6964882cf931260331b93ae4b283427f9a0db147a83de1d55/blob b/shared/package-files/d2/d27adaf74ebb18d6964882cf931260331b93ae4b283427f9a0db147a83de1d55/blob new file mode 100644 index 0000000000000000000000000000000000000000..4fd921d695580d913869978074a8bc5f1e6b5b71 --- /dev/null +++ b/shared/package-files/d2/d27adaf74ebb18d6964882cf931260331b93ae4b283427f9a0db147a83de1d55/blob @@ -0,0 +1,52 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset he DAYS_OF_WEEK_ABBREV [list \ + "\u05d0"\ + "\u05d1"\ + "\u05d2"\ + "\u05d3"\ + "\u05d4"\ + "\u05d5"\ + "\u05e9"] + ::msgcat::mcset he DAYS_OF_WEEK_FULL [list \ + "\u05d9\u05d5\u05dd \u05e8\u05d0\u05e9\u05d5\u05df"\ + "\u05d9\u05d5\u05dd \u05e9\u05e0\u05d9"\ + "\u05d9\u05d5\u05dd \u05e9\u05dc\u05d9\u05e9\u05d9"\ + "\u05d9\u05d5\u05dd \u05e8\u05d1\u05d9\u05e2\u05d9"\ + "\u05d9\u05d5\u05dd \u05d7\u05de\u05d9\u05e9\u05d9"\ + "\u05d9\u05d5\u05dd \u05e9\u05d9\u05e9\u05d9"\ + "\u05e9\u05d1\u05ea"] + ::msgcat::mcset he MONTHS_ABBREV [list \ + "\u05d9\u05e0\u05d5"\ + "\u05e4\u05d1\u05e8"\ + "\u05de\u05e8\u05e5"\ + "\u05d0\u05e4\u05e8"\ + "\u05de\u05d0\u05d9"\ + "\u05d9\u05d5\u05e0"\ + "\u05d9\u05d5\u05dc"\ + "\u05d0\u05d5\u05d2"\ + "\u05e1\u05e4\u05d8"\ + "\u05d0\u05d5\u05e7"\ + "\u05e0\u05d5\u05d1"\ + "\u05d3\u05e6\u05de"\ + ""] + ::msgcat::mcset he MONTHS_FULL [list \ + "\u05d9\u05e0\u05d5\u05d0\u05e8"\ + "\u05e4\u05d1\u05e8\u05d5\u05d0\u05e8"\ + "\u05de\u05e8\u05e5"\ + "\u05d0\u05e4\u05e8\u05d9\u05dc"\ + "\u05de\u05d0\u05d9"\ + "\u05d9\u05d5\u05e0\u05d9"\ + "\u05d9\u05d5\u05dc\u05d9"\ + "\u05d0\u05d5\u05d2\u05d5\u05e1\u05d8"\ + "\u05e1\u05e4\u05d8\u05de\u05d1\u05e8"\ + "\u05d0\u05d5\u05e7\u05d8\u05d5\u05d1\u05e8"\ + "\u05e0\u05d5\u05d1\u05de\u05d1\u05e8"\ + "\u05d3\u05e6\u05de\u05d1\u05e8"\ + ""] + ::msgcat::mcset he BCE "\u05dc\u05e1\u05d4\u0022\u05e0" + ::msgcat::mcset he CE "\u05dc\u05e4\u05e1\u05d4\u0022\u05e0" + ::msgcat::mcset he DATE_FORMAT "%d/%m/%Y" + ::msgcat::mcset he TIME_FORMAT "%H:%M:%S" + ::msgcat::mcset he DATE_TIME_FORMAT "%d/%m/%Y %H:%M:%S %z" +} diff --git a/shared/package-files/d2/d27d7ec19ae2025018024d054fb17ac48621457b4ef731c08702be0d51cf832b/blob b/shared/package-files/d2/d27d7ec19ae2025018024d054fb17ac48621457b4ef731c08702be0d51cf832b/blob new file mode 100644 index 0000000000000000000000000000000000000000..5d89faa8708f07b597fc63c0eb7fc1e6b686bf7f Binary files /dev/null and b/shared/package-files/d2/d27d7ec19ae2025018024d054fb17ac48621457b4ef731c08702be0d51cf832b/blob differ diff --git a/shared/package-files/d2/d27dddf51f7cac3a0d2e378ea978a0a1114a4840c6c57082718d03979c13cab4/blob b/shared/package-files/d2/d27dddf51f7cac3a0d2e378ea978a0a1114a4840c6c57082718d03979c13cab4/blob new file mode 100644 index 0000000000000000000000000000000000000000..a700736a4b7e0a59919cd77a6570ff56ccc05649 --- /dev/null +++ b/shared/package-files/d2/d27dddf51f7cac3a0d2e378ea978a0a1114a4840c6c57082718d03979c13cab4/blob @@ -0,0 +1,19 @@ +#pragma once + +// Test these using #if AT_CUDNN_ENABLED(), not #ifdef, so that it's +// obvious if you forgot to include Config.h +// c.f. https://stackoverflow.com/questions/33759787/generating-an-error-if-checked-boolean-macro-is-not-defined +// +// NB: This header MUST NOT be included from other headers; it should +// only be included from C++ files. +#define AT_CUDNN_ENABLED() 1 +#define AT_CUSPARSELT_ENABLED() 1 +#define AT_ROCM_ENABLED() 0 +#define AT_MAGMA_ENABLED() 1 + +// Needed for hipMAGMA to correctly identify implementation +#if (AT_ROCM_ENABLED() && AT_MAGMA_ENABLED()) +#define HAVE_HIP 1 +#endif + +#define NVCC_FLAGS_EXTRA "-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_61,code=sm_61;-gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90" diff --git a/shared/package-files/d2/d27e62ac3471e8be90f0d9510b1abdc3e0e59380e1261886c5b1621533d94a03/blob b/shared/package-files/d2/d27e62ac3471e8be90f0d9510b1abdc3e0e59380e1261886c5b1621533d94a03/blob new file mode 100644 index 0000000000000000000000000000000000000000..0089defc00995d3ba3fc8e009f32f8aa5ee35f4e --- /dev/null +++ b/shared/package-files/d2/d27e62ac3471e8be90f0d9510b1abdc3e0e59380e1261886c5b1621533d94a03/blob @@ -0,0 +1,52 @@ +import array +import threading +import weakref +from queue import Queue as Queue +from typing import Any, Callable, Iterable, List, Mapping, Optional, Sequence + +JoinableQueue = Queue +Barrier = threading.Barrier +BoundedSemaphore = threading.BoundedSemaphore +Condition = threading.Condition +Event = threading.Event +Lock = threading.Lock +RLock = threading.RLock +Semaphore = threading.Semaphore + +class DummyProcess(threading.Thread): + _children: weakref.WeakKeyDictionary[Any, Any] + _parent: threading.Thread + _pid: None + _start_called: int + exitcode: Optional[int] + def __init__( + self, + group: Any = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[str] = ..., + args: Iterable[Any] = ..., + kwargs: Mapping[str, Any] = ..., + ) -> None: ... + +Process = DummyProcess + +class Namespace: + def __init__(self, **kwds: Any) -> None: ... + def __getattr__(self, __name: str) -> Any: ... + def __setattr__(self, __name: str, __value: Any) -> None: ... + +class Value: + _typecode: Any + _value: Any + value: Any + def __init__(self, typecode: Any, value: Any, lock: Any = ...) -> None: ... + +def Array(typecode: Any, sequence: Sequence[Any], lock: Any = ...) -> array.array[Any]: ... +def Manager() -> Any: ... +def Pool( + processes: Optional[int] = ..., initializer: Optional[Callable[..., Any]] = ..., initargs: Iterable[Any] = ... +) -> Any: ... +def active_children() -> List[Any]: ... +def current_process() -> threading.Thread: ... +def freeze_support() -> None: ... +def shutdown() -> None: ... diff --git a/shared/package-files/d2/d27e8640818fb8a53bc80d2d4a9880035524b684a1136bf3780d84aa14192be4/blob b/shared/package-files/d2/d27e8640818fb8a53bc80d2d4a9880035524b684a1136bf3780d84aa14192be4/blob new file mode 100644 index 0000000000000000000000000000000000000000..a3d012c70b22fd8209534a01a51fa9978c705d00 --- /dev/null +++ b/shared/package-files/d2/d27e8640818fb8a53bc80d2d4a9880035524b684a1136bf3780d84aa14192be4/blob @@ -0,0 +1,103 @@ +import csv +import pathlib +from typing import Any, Callable, Optional, Tuple, Union + +import PIL + +from .folder import make_dataset +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class GTSRB(VisionDataset): + """`German Traffic Sign Recognition Benchmark (GTSRB) `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), or ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop``. + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + """ + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + + super().__init__(root, transform=transform, target_transform=target_transform) + + self._split = verify_str_arg(split, "split", ("train", "test")) + self._base_folder = pathlib.Path(root) / "gtsrb" + self._target_folder = ( + self._base_folder / "GTSRB" / ("Training" if self._split == "train" else "Final_Test/Images") + ) + + if download: + self.download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + if self._split == "train": + samples = make_dataset(str(self._target_folder), extensions=(".ppm",)) + else: + with open(self._base_folder / "GT-final_test.csv") as csv_file: + samples = [ + (str(self._target_folder / row["Filename"]), int(row["ClassId"])) + for row in csv.DictReader(csv_file, delimiter=";", skipinitialspace=True) + ] + + self._samples = samples + self.transform = transform + self.target_transform = target_transform + + def __len__(self) -> int: + return len(self._samples) + + def __getitem__(self, index: int) -> Tuple[Any, Any]: + + path, target = self._samples[index] + sample = PIL.Image.open(path).convert("RGB") + + if self.transform is not None: + sample = self.transform(sample) + + if self.target_transform is not None: + target = self.target_transform(target) + + return sample, target + + def _check_exists(self) -> bool: + return self._target_folder.is_dir() + + def download(self) -> None: + if self._check_exists(): + return + + base_url = "https://sid.erda.dk/public/archives/daaeac0d7ce1152aea9b61d9f1e19370/" + + if self._split == "train": + download_and_extract_archive( + f"{base_url}GTSRB-Training_fixed.zip", + download_root=str(self._base_folder), + md5="513f3c79a4c5141765e10e952eaa2478", + ) + else: + download_and_extract_archive( + f"{base_url}GTSRB_Final_Test_Images.zip", + download_root=str(self._base_folder), + md5="c7e4e6327067d32654124b0fe9e82185", + ) + download_and_extract_archive( + f"{base_url}GTSRB_Final_Test_GT.zip", + download_root=str(self._base_folder), + md5="fe31e9c9270bbcd7b84b7f21a9d9d9e5", + ) diff --git a/shared/package-files/d2/d2833c2ed148027946fa568ae968f2925496782181f70752ccaee05546d196c8/blob b/shared/package-files/d2/d2833c2ed148027946fa568ae968f2925496782181f70752ccaee05546d196c8/blob new file mode 100644 index 0000000000000000000000000000000000000000..f3e67d07f6bb2f32be75906fb0696c02aef43da5 --- /dev/null +++ b/shared/package-files/d2/d2833c2ed148027946fa568ae968f2925496782181f70752ccaee05546d196c8/blob @@ -0,0 +1,41 @@ +from paramiko.agent import Agent as Agent, AgentKey as AgentKey +from paramiko.channel import Channel as Channel +from paramiko.client import ( + AutoAddPolicy as AutoAddPolicy, + MissingHostKeyPolicy as MissingHostKeyPolicy, + RejectPolicy as RejectPolicy, + SSHClient as SSHClient, + WarningPolicy as WarningPolicy, +) +from paramiko.common import io_sleep as io_sleep +from paramiko.config import SSHConfig as SSHConfig +from paramiko.dsskey import DSSKey as DSSKey +from paramiko.ecdsakey import ECDSAKey as ECDSAKey +from paramiko.ed25519key import Ed25519Key as Ed25519Key +from paramiko.file import BufferedFile as BufferedFile +from paramiko.hostkeys import HostKeys as HostKeys +from paramiko.message import Message as Message +from paramiko.pkey import PKey as PKey +from paramiko.proxy import ProxyCommand as ProxyCommand +from paramiko.rsakey import RSAKey as RSAKey +from paramiko.server import ServerInterface as ServerInterface, SubsystemHandler as SubsystemHandler +from paramiko.sftp import SFTPError as SFTPError +from paramiko.sftp_attr import SFTPAttributes as SFTPAttributes +from paramiko.sftp_client import SFTP as SFTP, SFTPClient as SFTPClient +from paramiko.sftp_file import SFTPFile as SFTPFile +from paramiko.sftp_handle import SFTPHandle as SFTPHandle +from paramiko.sftp_server import SFTPServer as SFTPServer +from paramiko.sftp_si import SFTPServerInterface as SFTPServerInterface +from paramiko.ssh_exception import ( + AuthenticationException as AuthenticationException, + BadAuthenticationType as BadAuthenticationType, + BadHostKeyException as BadHostKeyException, + ChannelException as ChannelException, + PasswordRequiredException as PasswordRequiredException, + ProxyCommandFailure as ProxyCommandFailure, + SSHException as SSHException, +) +from paramiko.transport import SecurityOptions as SecurityOptions, Transport as Transport + +# Names in __all__ with no definition: +# util diff --git a/shared/package-files/d2/d283d4e508d9e6aff9a89e7870211ad7c65ab3867f20c4d5013d3d8f7f627482/blob b/shared/package-files/d2/d283d4e508d9e6aff9a89e7870211ad7c65ab3867f20c4d5013d3d8f7f627482/blob new file mode 100644 index 0000000000000000000000000000000000000000..528ed7b8762be5f681c759a5ce8a90aa8d4225d7 --- /dev/null +++ b/shared/package-files/d2/d283d4e508d9e6aff9a89e7870211ad7c65ab3867f20c4d5013d3d8f7f627482/blob @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/shared/package-files/d2/d28cc82f1ce8a6b422b858e57818c40caf8faca12fc392a65d33787e678d1cef/blob b/shared/package-files/d2/d28cc82f1ce8a6b422b858e57818c40caf8faca12fc392a65d33787e678d1cef/blob new file mode 100644 index 0000000000000000000000000000000000000000..21f2d6f7aa1e48b28275340948e0a77fc0590a5a --- /dev/null +++ b/shared/package-files/d2/d28cc82f1ce8a6b422b858e57818c40caf8faca12fc392a65d33787e678d1cef/blob @@ -0,0 +1,83 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +namespace symint { + template ::value>> + at::Tensor to_padded_tensor(const at::Tensor & self, double padding, at::OptionalIntArrayRef output_size=c10::nullopt) { + return at::_ops::to_padded_tensor::call(self, padding, output_size.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*output_size)) : c10::nullopt); + } +} + +namespace symint { + template ::value>> + at::Tensor to_padded_tensor(const at::Tensor & self, double padding, at::OptionalSymIntArrayRef output_size=c10::nullopt) { + return at::_ops::to_padded_tensor::call(self, padding, output_size); + } +} + +// aten::to_padded_tensor.out(Tensor self, float padding, SymInt[]? output_size=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & to_padded_tensor_out(at::Tensor & out, const at::Tensor & self, double padding, at::OptionalIntArrayRef output_size=c10::nullopt) { + return at::_ops::to_padded_tensor_out::call(self, padding, output_size.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*output_size)) : c10::nullopt, out); +} +namespace symint { + template ::value>> + at::Tensor & to_padded_tensor_out(at::Tensor & out, const at::Tensor & self, double padding, at::OptionalIntArrayRef output_size=c10::nullopt) { + return at::_ops::to_padded_tensor_out::call(self, padding, output_size.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*output_size)) : c10::nullopt, out); + } +} + +// aten::to_padded_tensor.out(Tensor self, float padding, SymInt[]? output_size=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & to_padded_tensor_outf(const at::Tensor & self, double padding, at::OptionalIntArrayRef output_size, at::Tensor & out) { + return at::_ops::to_padded_tensor_out::call(self, padding, output_size.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*output_size)) : c10::nullopt, out); +} +namespace symint { + template ::value>> + at::Tensor & to_padded_tensor_outf(const at::Tensor & self, double padding, at::OptionalIntArrayRef output_size, at::Tensor & out) { + return at::_ops::to_padded_tensor_out::call(self, padding, output_size.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*output_size)) : c10::nullopt, out); + } +} + +// aten::to_padded_tensor.out(Tensor self, float padding, SymInt[]? output_size=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & to_padded_tensor_symint_out(at::Tensor & out, const at::Tensor & self, double padding, at::OptionalSymIntArrayRef output_size=c10::nullopt) { + return at::_ops::to_padded_tensor_out::call(self, padding, output_size, out); +} +namespace symint { + template ::value>> + at::Tensor & to_padded_tensor_out(at::Tensor & out, const at::Tensor & self, double padding, at::OptionalSymIntArrayRef output_size=c10::nullopt) { + return at::_ops::to_padded_tensor_out::call(self, padding, output_size, out); + } +} + +// aten::to_padded_tensor.out(Tensor self, float padding, SymInt[]? output_size=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & to_padded_tensor_symint_outf(const at::Tensor & self, double padding, at::OptionalSymIntArrayRef output_size, at::Tensor & out) { + return at::_ops::to_padded_tensor_out::call(self, padding, output_size, out); +} +namespace symint { + template ::value>> + at::Tensor & to_padded_tensor_outf(const at::Tensor & self, double padding, at::OptionalSymIntArrayRef output_size, at::Tensor & out) { + return at::_ops::to_padded_tensor_out::call(self, padding, output_size, out); + } +} + +} diff --git a/shared/package-files/d2/d28d3421855c559c0c50a4e21722ca0145814ed50a2742da0cb05a17b51b226e/blob b/shared/package-files/d2/d28d3421855c559c0c50a4e21722ca0145814ed50a2742da0cb05a17b51b226e/blob new file mode 100644 index 0000000000000000000000000000000000000000..5d76a3b2bcd434a468e070bdd52eed2c222f1324 --- /dev/null +++ b/shared/package-files/d2/d28d3421855c559c0c50a4e21722ca0145814ed50a2742da0cb05a17b51b226e/blob @@ -0,0 +1,117 @@ +Metadata-Version: 2.1 +Name: archspec +Version: 0.2.3 +Summary: A library to query system architecture +Home-page: https://github.com/archspec/archspec +License: Apache-2.0 OR MIT +Author: archspec developers +Author-email: maintainers@spack.io +Maintainer: Greg Becker +Maintainer-email: maintainers@spack.io +Requires-Python: >=3.6, !=2.7.*, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.* +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: Science/Research +Classifier: License :: Other/Proprietary License +Classifier: Operating System :: MacOS +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: Unix +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Project-URL: Documentation, https://archspec.readthedocs.io +Project-URL: Repository, https://github.com/archspec/archspec.git +Description-Content-Type: text/markdown + +# Archspec (Python bindings) + +[![CI](https://github.com/archspec/archspec/workflows/Unit%20tests/badge.svg)](https://github.com/archspec/archspec/actions) +[![CodeCov](https://codecov.io/gh/archspec/archspec/branch/master/graph/badge.svg)](https://codecov.io/gh/archspec/archspec) +[![Documentation Status](https://readthedocs.org/projects/archspec/badge/?version=latest)](https://archspec.readthedocs.io/en/latest/?badge=latest) + +Archspec aims at providing a standard set of human-understandable labels for +various aspects of a system architecture like CPU, network fabrics, etc. and +APIs to detect, query and compare them. + +This project grew out of [Spack](https://spack.io/) and is currently under +active development. At present it supports APIs to detect and model +compatibility relationships among different CPU microarchitectures. + +## Getting started with development + +The `archspec` Python package needs [poetry](https://python-poetry.org/) to +be installed from VCS sources. The preferred method to install it is via +its custom installer outside of any virtual environment: + +```console +curl -sSL https://install.python-poetry.org | python3 - +``` + +You can refer to [Poetry's documentation](https://python-poetry.org/docs/#installation) +for further details or for other methods to install this tool. You'll also need `tox` +to run unit test: + +```console +pip install --user tox +``` + +Finally, you'll need to clone the repository: + +```console +git clone --recursive https://github.com/archspec/archspec.git +``` + +### Running unit tests + +Once you have your environment ready you can run `archspec` unit tests +using ``tox`` from the root of the repository: + +```console +$ tox + [ ... ] + py27: commands succeeded + py35: commands succeeded + py36: commands succeeded + py37: commands succeeded + py38: commands succeeded + pylint: commands succeeded + flake8: commands succeeded + black: commands succeeded + congratulations :) +``` + +## Citing Archspec + +If you are referencing `archspec` in a publication, please cite the following +paper: + +* Massimiliano Culpo, Gregory Becker, Carlos Eduardo Arango Gutierrez, Kenneth + Hoste, and Todd Gamblin. + [**`archspec`: A library for detecting, labeling, and reasoning about + microarchitectures**](https://tgamblin.github.io/pubs/archspec-canopie-hpc-2020.pdf). + In *2nd International Workshop on Containers and New Orchestration Paradigms + for Isolated Environments in HPC (CANOPIE-HPC'20)*, Online Event, November + 12, 2020. + +## License + +Archspec is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). Users may choose either license, at their +option. + +All new contributions must be made under both the MIT and Apache-2.0 +licenses. + +See [LICENSE-MIT](https://github.com/archspec/archspec/blob/master/LICENSE-MIT), +[LICENSE-APACHE](https://github.com/archspec/archspec/blob/master/LICENSE-APACHE), +[COPYRIGHT](https://github.com/archspec/archspec/blob/master/COPYRIGHT), and +[NOTICE](https://github.com/archspec/archspec/blob/master/NOTICE) for details. + +SPDX-License-Identifier: (Apache-2.0 OR MIT) + +LLNL-CODE-811653 + diff --git a/shared/package-files/d2/d28f3ae1ff16574453e023a150799ad8ecad1652fd953f903a78f803b74df926/blob b/shared/package-files/d2/d28f3ae1ff16574453e023a150799ad8ecad1652fd953f903a78f803b74df926/blob new file mode 100644 index 0000000000000000000000000000000000000000..bedf8efffea854443847fca1bf7ab8a15dd60bef Binary files /dev/null and b/shared/package-files/d2/d28f3ae1ff16574453e023a150799ad8ecad1652fd953f903a78f803b74df926/blob differ diff --git a/shared/package-files/d2/d28fdb89523ec0b87b91cc3d147bdbc18cb336f3343c8d3a4110f6661883d85b/blob b/shared/package-files/d2/d28fdb89523ec0b87b91cc3d147bdbc18cb336f3343c8d3a4110f6661883d85b/blob new file mode 100644 index 0000000000000000000000000000000000000000..cc352ba7b8f2f5a5548d4d5749d3b48ac838aced --- /dev/null +++ b/shared/package-files/d2/d28fdb89523ec0b87b91cc3d147bdbc18cb336f3343c8d3a4110f6661883d85b/blob @@ -0,0 +1,29 @@ +""" +Helpers for sharing tests between DataFrame/Series +""" +from __future__ import annotations + +from typing import TYPE_CHECKING + +from pandas import DataFrame + +if TYPE_CHECKING: + from pandas._typing import DtypeObj + + +def get_dtype(obj) -> DtypeObj: + if isinstance(obj, DataFrame): + # Note: we are assuming only one column + return obj.dtypes.iat[0] + else: + return obj.dtype + + +def get_obj(df: DataFrame, klass): + """ + For sharing tests using frame_or_series, either return the DataFrame + unchanged or return it's first column as a Series. + """ + if klass is DataFrame: + return df + return df._ixs(0, axis=1) diff --git a/shared/package-files/d2/d2904a766448113ab4a49623c518f7e01d23fa8e7a7f88aacc9cbd2786ee53b5/blob b/shared/package-files/d2/d2904a766448113ab4a49623c518f7e01d23fa8e7a7f88aacc9cbd2786ee53b5/blob new file mode 100644 index 0000000000000000000000000000000000000000..cecfdb785506d1b2f4ef496703c430794f09e589 --- /dev/null +++ b/shared/package-files/d2/d2904a766448113ab4a49623c518f7e01d23fa8e7a7f88aacc9cbd2786ee53b5/blob @@ -0,0 +1,120 @@ +from sympy.core.numbers import (Rational, pi) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.geometry import (Circle, Ellipse, Point, Line, Parabola, + Polygon, Ray, RegularPolygon, Segment, Triangle, Plane, Curve) +from sympy.geometry.entity import scale, GeometryEntity +from sympy.testing.pytest import raises + + +def test_entity(): + x = Symbol('x', real=True) + y = Symbol('y', real=True) + + assert GeometryEntity(x, y) in GeometryEntity(x, y) + raises(NotImplementedError, lambda: Point(0, 0) in GeometryEntity(x, y)) + + assert GeometryEntity(x, y) == GeometryEntity(x, y) + assert GeometryEntity(x, y).equals(GeometryEntity(x, y)) + + c = Circle((0, 0), 5) + assert GeometryEntity.encloses(c, Point(0, 0)) + assert GeometryEntity.encloses(c, Segment((0, 0), (1, 1))) + assert GeometryEntity.encloses(c, Line((0, 0), (1, 1))) is False + assert GeometryEntity.encloses(c, Circle((0, 0), 4)) + assert GeometryEntity.encloses(c, Polygon(Point(0, 0), Point(1, 0), Point(0, 1))) + assert GeometryEntity.encloses(c, RegularPolygon(Point(8, 8), 1, 3)) is False + + +def test_svg(): + a = Symbol('a') + b = Symbol('b') + d = Symbol('d') + + entity = Circle(Point(a, b), d) + assert entity._repr_svg_() is None + + entity = Circle(Point(0, 0), S.Infinity) + assert entity._repr_svg_() is None + + +def test_subs(): + x = Symbol('x', real=True) + y = Symbol('y', real=True) + p = Point(x, 2) + q = Point(1, 1) + r = Point(3, 4) + for o in [p, + Segment(p, q), + Ray(p, q), + Line(p, q), + Triangle(p, q, r), + RegularPolygon(p, 3, 6), + Polygon(p, q, r, Point(5, 4)), + Circle(p, 3), + Ellipse(p, 3, 4)]: + assert 'y' in str(o.subs(x, y)) + assert p.subs({x: 1}) == Point(1, 2) + assert Point(1, 2).subs(Point(1, 2), Point(3, 4)) == Point(3, 4) + assert Point(1, 2).subs((1, 2), Point(3, 4)) == Point(3, 4) + assert Point(1, 2).subs(Point(1, 2), Point(3, 4)) == Point(3, 4) + assert Point(1, 2).subs({(1, 2)}) == Point(2, 2) + raises(ValueError, lambda: Point(1, 2).subs(1)) + raises(ValueError, lambda: Point(1, 1).subs((Point(1, 1), Point(1, + 2)), 1, 2)) + + +def test_transform(): + assert scale(1, 2, (3, 4)).tolist() == \ + [[1, 0, 0], [0, 2, 0], [0, -4, 1]] + + +def test_reflect_entity_overrides(): + x = Symbol('x', real=True) + y = Symbol('y', real=True) + b = Symbol('b') + m = Symbol('m') + l = Line((0, b), slope=m) + p = Point(x, y) + r = p.reflect(l) + c = Circle((x, y), 3) + cr = c.reflect(l) + assert cr == Circle(r, -3) + assert c.area == -cr.area + + pent = RegularPolygon((1, 2), 1, 5) + slope = S.ComplexInfinity + while slope is S.ComplexInfinity: + slope = Rational(*(x._random()/2).as_real_imag()) + l = Line(pent.vertices[1], slope=slope) + rpent = pent.reflect(l) + assert rpent.center == pent.center.reflect(l) + rvert = [i.reflect(l) for i in pent.vertices] + for v in rpent.vertices: + for i in range(len(rvert)): + ri = rvert[i] + if ri.equals(v): + rvert.remove(ri) + break + assert not rvert + assert pent.area.equals(-rpent.area) + + +def test_geometry_EvalfMixin(): + x = pi + t = Symbol('t') + for g in [ + Point(x, x), + Plane(Point(0, x, 0), (0, 0, x)), + Curve((x*t, x), (t, 0, x)), + Ellipse((x, x), x, -x), + Circle((x, x), x), + Line((0, x), (x, 0)), + Segment((0, x), (x, 0)), + Ray((0, x), (x, 0)), + Parabola((0, x), Line((-x, 0), (x, 0))), + Polygon((0, 0), (0, x), (x, 0), (x, x)), + RegularPolygon((0, x), x, 4, x), + Triangle((0, 0), (x, 0), (x, x)), + ]: + assert str(g).replace('pi', '3.1') == str(g.n(2)) diff --git a/shared/package-files/d2/d294380cff65ea0db5ab6023bfa74915158cafd6ae3c64cd57d0666546e880f6/blob b/shared/package-files/d2/d294380cff65ea0db5ab6023bfa74915158cafd6ae3c64cd57d0666546e880f6/blob new file mode 100644 index 0000000000000000000000000000000000000000..4c9a98e85f7849ad262ca9e8a3d43f548234d8bb --- /dev/null +++ b/shared/package-files/d2/d294380cff65ea0db5ab6023bfa74915158cafd6ae3c64cd57d0666546e880f6/blob @@ -0,0 +1,80 @@ +from collections.abc import Iterable +from typing import Any, TypeVar, overload, SupportsIndex + +from numpy import generic +from numpy._typing import ( + NDArray, + ArrayLike, + _ShapeLike, + _Shape, + _ArrayLike +) + +_SCT = TypeVar("_SCT", bound=generic) + +__all__: list[str] + +class DummyArray: + __array_interface__: dict[str, Any] + base: None | NDArray[Any] + def __init__( + self, + interface: dict[str, Any], + base: None | NDArray[Any] = ..., + ) -> None: ... + +@overload +def as_strided( + x: _ArrayLike[_SCT], + shape: None | Iterable[int] = ..., + strides: None | Iterable[int] = ..., + subok: bool = ..., + writeable: bool = ..., +) -> NDArray[_SCT]: ... +@overload +def as_strided( + x: ArrayLike, + shape: None | Iterable[int] = ..., + strides: None | Iterable[int] = ..., + subok: bool = ..., + writeable: bool = ..., +) -> NDArray[Any]: ... + +@overload +def sliding_window_view( + x: _ArrayLike[_SCT], + window_shape: int | Iterable[int], + axis: None | SupportsIndex = ..., + *, + subok: bool = ..., + writeable: bool = ..., +) -> NDArray[_SCT]: ... +@overload +def sliding_window_view( + x: ArrayLike, + window_shape: int | Iterable[int], + axis: None | SupportsIndex = ..., + *, + subok: bool = ..., + writeable: bool = ..., +) -> NDArray[Any]: ... + +@overload +def broadcast_to( + array: _ArrayLike[_SCT], + shape: int | Iterable[int], + subok: bool = ..., +) -> NDArray[_SCT]: ... +@overload +def broadcast_to( + array: ArrayLike, + shape: int | Iterable[int], + subok: bool = ..., +) -> NDArray[Any]: ... + +def broadcast_shapes(*args: _ShapeLike) -> _Shape: ... + +def broadcast_arrays( + *args: ArrayLike, + subok: bool = ..., +) -> list[NDArray[Any]]: ... diff --git a/shared/package-files/d2/d2946128ecc0f8fb5f33233d43a2ac5f0897614f0b1b1bf44d634ff1c4b01ebb/blob b/shared/package-files/d2/d2946128ecc0f8fb5f33233d43a2ac5f0897614f0b1b1bf44d634ff1c4b01ebb/blob new file mode 100644 index 0000000000000000000000000000000000000000..4d9b50d01f3c9d7948f1e57b5037990c786c5050 --- /dev/null +++ b/shared/package-files/d2/d2946128ecc0f8fb5f33233d43a2ac5f0897614f0b1b1bf44d634ff1c4b01ebb/blob @@ -0,0 +1,201 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::randint_like(Tensor self, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor randint_like(const at::Tensor & self, int64_t high, at::TensorOptions options={}, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like::call(self, high, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); +} +namespace symint { + template ::value>> + at::Tensor randint_like(const at::Tensor & self, int64_t high, at::TensorOptions options={}, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like::call(self, high, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); + } +} + +// aten::randint_like(Tensor self, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor randint_like(const at::Tensor & self, int64_t high, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, c10::optional memory_format) { + return at::_ops::randint_like::call(self, high, dtype, layout, device, pin_memory, memory_format); +} +namespace symint { + template ::value>> + at::Tensor randint_like(const at::Tensor & self, int64_t high, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, c10::optional memory_format) { + return at::_ops::randint_like::call(self, high, dtype, layout, device, pin_memory, memory_format); + } +} + +// aten::randint_like(Tensor self, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt high, at::TensorOptions options={}, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like::call(self, high, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); +} +namespace symint { + template ::value>> + at::Tensor randint_like(const at::Tensor & self, c10::SymInt high, at::TensorOptions options={}, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like::call(self, high, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); + } +} + +// aten::randint_like(Tensor self, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt high, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, c10::optional memory_format) { + return at::_ops::randint_like::call(self, high, dtype, layout, device, pin_memory, memory_format); +} +namespace symint { + template ::value>> + at::Tensor randint_like(const at::Tensor & self, c10::SymInt high, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, c10::optional memory_format) { + return at::_ops::randint_like::call(self, high, dtype, layout, device, pin_memory, memory_format); + } +} + +// aten::randint_like.low_dtype(Tensor self, SymInt low, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor randint_like(const at::Tensor & self, int64_t low, int64_t high, at::TensorOptions options={}, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like_low_dtype::call(self, low, high, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); +} +namespace symint { + template ::value>> + at::Tensor randint_like(const at::Tensor & self, int64_t low, int64_t high, at::TensorOptions options={}, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like_low_dtype::call(self, low, high, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); + } +} + +// aten::randint_like.low_dtype(Tensor self, SymInt low, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor randint_like(const at::Tensor & self, int64_t low, int64_t high, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, c10::optional memory_format) { + return at::_ops::randint_like_low_dtype::call(self, low, high, dtype, layout, device, pin_memory, memory_format); +} +namespace symint { + template ::value>> + at::Tensor randint_like(const at::Tensor & self, int64_t low, int64_t high, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, c10::optional memory_format) { + return at::_ops::randint_like_low_dtype::call(self, low, high, dtype, layout, device, pin_memory, memory_format); + } +} + +// aten::randint_like.low_dtype(Tensor self, SymInt low, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt low, c10::SymInt high, at::TensorOptions options={}, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like_low_dtype::call(self, low, high, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); +} +namespace symint { + template ::value>> + at::Tensor randint_like(const at::Tensor & self, c10::SymInt low, c10::SymInt high, at::TensorOptions options={}, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like_low_dtype::call(self, low, high, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); + } +} + +// aten::randint_like.low_dtype(Tensor self, SymInt low, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt low, c10::SymInt high, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, c10::optional memory_format) { + return at::_ops::randint_like_low_dtype::call(self, low, high, dtype, layout, device, pin_memory, memory_format); +} +namespace symint { + template ::value>> + at::Tensor randint_like(const at::Tensor & self, c10::SymInt low, c10::SymInt high, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, c10::optional memory_format) { + return at::_ops::randint_like_low_dtype::call(self, low, high, dtype, layout, device, pin_memory, memory_format); + } +} + +// aten::randint_like.out(Tensor self, SymInt high, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & randint_like_out(at::Tensor & out, const at::Tensor & self, int64_t high, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like_out::call(self, high, memory_format, out); +} +namespace symint { + template ::value>> + at::Tensor & randint_like_out(at::Tensor & out, const at::Tensor & self, int64_t high, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like_out::call(self, high, memory_format, out); + } +} + +// aten::randint_like.out(Tensor self, SymInt high, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & randint_like_outf(const at::Tensor & self, int64_t high, c10::optional memory_format, at::Tensor & out) { + return at::_ops::randint_like_out::call(self, high, memory_format, out); +} +namespace symint { + template ::value>> + at::Tensor & randint_like_outf(const at::Tensor & self, int64_t high, c10::optional memory_format, at::Tensor & out) { + return at::_ops::randint_like_out::call(self, high, memory_format, out); + } +} + +// aten::randint_like.out(Tensor self, SymInt high, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & randint_like_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymInt high, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like_out::call(self, high, memory_format, out); +} +namespace symint { + template ::value>> + at::Tensor & randint_like_out(at::Tensor & out, const at::Tensor & self, c10::SymInt high, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like_out::call(self, high, memory_format, out); + } +} + +// aten::randint_like.out(Tensor self, SymInt high, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & randint_like_symint_outf(const at::Tensor & self, c10::SymInt high, c10::optional memory_format, at::Tensor & out) { + return at::_ops::randint_like_out::call(self, high, memory_format, out); +} +namespace symint { + template ::value>> + at::Tensor & randint_like_outf(const at::Tensor & self, c10::SymInt high, c10::optional memory_format, at::Tensor & out) { + return at::_ops::randint_like_out::call(self, high, memory_format, out); + } +} + +// aten::randint_like.low_dtype_out(Tensor self, SymInt low, SymInt high, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & randint_like_out(at::Tensor & out, const at::Tensor & self, int64_t low, int64_t high, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like_low_dtype_out::call(self, low, high, memory_format, out); +} +namespace symint { + template ::value>> + at::Tensor & randint_like_out(at::Tensor & out, const at::Tensor & self, int64_t low, int64_t high, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like_low_dtype_out::call(self, low, high, memory_format, out); + } +} + +// aten::randint_like.low_dtype_out(Tensor self, SymInt low, SymInt high, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & randint_like_outf(const at::Tensor & self, int64_t low, int64_t high, c10::optional memory_format, at::Tensor & out) { + return at::_ops::randint_like_low_dtype_out::call(self, low, high, memory_format, out); +} +namespace symint { + template ::value>> + at::Tensor & randint_like_outf(const at::Tensor & self, int64_t low, int64_t high, c10::optional memory_format, at::Tensor & out) { + return at::_ops::randint_like_low_dtype_out::call(self, low, high, memory_format, out); + } +} + +// aten::randint_like.low_dtype_out(Tensor self, SymInt low, SymInt high, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & randint_like_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymInt low, c10::SymInt high, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like_low_dtype_out::call(self, low, high, memory_format, out); +} +namespace symint { + template ::value>> + at::Tensor & randint_like_out(at::Tensor & out, const at::Tensor & self, c10::SymInt low, c10::SymInt high, c10::optional memory_format=c10::nullopt) { + return at::_ops::randint_like_low_dtype_out::call(self, low, high, memory_format, out); + } +} + +// aten::randint_like.low_dtype_out(Tensor self, SymInt low, SymInt high, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & randint_like_symint_outf(const at::Tensor & self, c10::SymInt low, c10::SymInt high, c10::optional memory_format, at::Tensor & out) { + return at::_ops::randint_like_low_dtype_out::call(self, low, high, memory_format, out); +} +namespace symint { + template ::value>> + at::Tensor & randint_like_outf(const at::Tensor & self, c10::SymInt low, c10::SymInt high, c10::optional memory_format, at::Tensor & out) { + return at::_ops::randint_like_low_dtype_out::call(self, low, high, memory_format, out); + } +} + +} diff --git a/shared/package-files/d2/d29469a11ed6d4aa7cabff66c58e37ad8c3f45879fdebb89eb15752f061bcf70/blob b/shared/package-files/d2/d29469a11ed6d4aa7cabff66c58e37ad8c3f45879fdebb89eb15752f061bcf70/blob new file mode 100644 index 0000000000000000000000000000000000000000..ce1fe036d3595fed6b78e6d7090b8e5e87b62216 --- /dev/null +++ b/shared/package-files/d2/d29469a11ed6d4aa7cabff66c58e37ad8c3f45879fdebb89eb15752f061bcf70/blob @@ -0,0 +1,96 @@ +""" + pygments.lexers.inferno + ~~~~~~~~~~~~~~~~~~~~~~~ + + Lexers for Inferno os and all the related stuff. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re + +from pygments.lexer import RegexLexer, include, bygroups, default +from pygments.token import Punctuation, Comment, Operator, Keyword, \ + Name, String, Number, Whitespace + +__all__ = ['LimboLexer'] + + +class LimboLexer(RegexLexer): + """ + Lexer for Limbo programming language + + TODO: + - maybe implement better var declaration highlighting + - some simple syntax error highlighting + + .. versionadded:: 2.0 + """ + name = 'Limbo' + url = 'http://www.vitanuova.com/inferno/limbo.html' + aliases = ['limbo'] + filenames = ['*.b'] + mimetypes = ['text/limbo'] + + tokens = { + 'whitespace': [ + (r'^(\s*)([a-zA-Z_]\w*:)(\s*\n)', + bygroups(Whitespace, Name.Label, Whitespace)), + (r'\n', Whitespace), + (r'\s+', Whitespace), + (r'#(\n|(.|\n)*?[^\\]\n)', Comment.Single), + ], + 'string': [ + (r'"', String, '#pop'), + (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|' + r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape), + (r'[^\\"\n]+', String), # all other characters + (r'\\', String), # stray backslash + ], + 'statements': [ + (r'"', String, 'string'), + (r"'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char), + (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+', Number.Float), + (r'(\d+\.\d*|\.\d+|\d+[fF])', Number.Float), + (r'16r[0-9a-fA-F]+', Number.Hex), + (r'8r[0-7]+', Number.Oct), + (r'((([1-3]\d)|([2-9]))r)?(\d+)', Number.Integer), + (r'[()\[\],.]', Punctuation), + (r'[~!%^&*+=|?:<>/-]|(->)|(<-)|(=>)|(::)', Operator), + (r'(alt|break|case|continue|cyclic|do|else|exit' + r'for|hd|if|implement|import|include|len|load|or' + r'pick|return|spawn|tagof|tl|to|while)\b', Keyword), + (r'(byte|int|big|real|string|array|chan|list|adt' + r'|fn|ref|of|module|self|type)\b', Keyword.Type), + (r'(con|iota|nil)\b', Keyword.Constant), + (r'[a-zA-Z_]\w*', Name), + ], + 'statement' : [ + include('whitespace'), + include('statements'), + ('[{}]', Punctuation), + (';', Punctuation, '#pop'), + ], + 'root': [ + include('whitespace'), + default('statement'), + ], + } + + def analyse_text(text): + # Any limbo module implements something + if re.search(r'^implement \w+;', text, re.MULTILINE): + return 0.7 + +# TODO: +# - Make lexers for: +# - asm sources +# - man pages +# - mkfiles +# - module definitions +# - namespace definitions +# - shell scripts +# - maybe keyfiles and fonts +# they all seem to be quite similar to their equivalents +# from unix world, so there should not be a lot of problems diff --git a/shared/package-files/d2/d298eab273c48b59b6eb8e1b961515dc04c90fe6793a4da5acb4f3942a1dcc5e/blob b/shared/package-files/d2/d298eab273c48b59b6eb8e1b961515dc04c90fe6793a4da5acb4f3942a1dcc5e/blob new file mode 100644 index 0000000000000000000000000000000000000000..401c0f867307016cbcc059646523bfb116459357 --- /dev/null +++ b/shared/package-files/d2/d298eab273c48b59b6eb8e1b961515dc04c90fe6793a4da5acb4f3942a1dcc5e/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor atanh(const at::Tensor & self); +TORCH_API at::Tensor & atanh_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & atanh_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & atanh_(at::Tensor & self); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/d2/d299c6557ff37510a25c88b3ccf35efc343cd721d336e53f100047fcf70ea422/blob b/shared/package-files/d2/d299c6557ff37510a25c88b3ccf35efc343cd721d336e53f100047fcf70ea422/blob new file mode 100644 index 0000000000000000000000000000000000000000..b5df19cb3745039ae82a7d3a983e017a9245d8b7 --- /dev/null +++ b/shared/package-files/d2/d299c6557ff37510a25c88b3ccf35efc343cd721d336e53f100047fcf70ea422/blob @@ -0,0 +1,370 @@ +""" +Tests for statsmodels.stats.multivariate_tools + +Regression tests: cc_stats had no test coverage and raised AttributeError on +numpy >= 2.0 because it used the removed alias ``np.product``. cc_ranktest +had no test coverage at all, and could raise TypeError whenever cancorr's +underlying eigenvalue solver returned a complex dtype (which happens for +some inputs even though the canonical correlations are mathematically real). +""" +import numpy as np +from numpy.testing import assert_allclose +import pandas as pd +import pytest +from scipy import stats as sp_stats + +from statsmodels.stats.multivariate_tools import ( + CCRankTestResult, + CCStatsResult, + PartialProjectResult, + cancorr, + cc_ranktest, + cc_stats, + partial_project, +) + + +@pytest.fixture +def data(): + rs = np.random.RandomState(12345) + x1 = rs.standard_normal((200, 3)) + x2 = rs.standard_normal((200, 2)) + return x1, x2 + + +@pytest.fixture +def data_r(): + # Same data used to generate the reference values below with R 4.6.1: + # + # cc <- cancor(x1, x2, xcenter = TRUE, ycenter = TRUE) + # fit <- lm(x1 ~ x2) + # summary(manova(fit))$stats["x2", "Pillai"] + # summary(manova(fit), test = "Wilks")$stats["x2", "Wilks"] + # summary(manova(fit), test = "Hotelling-Lawley")$stats["x2", "Hotelling-Lawley"] + # summary(manova(fit), test = "Roy")$stats["x2", "Roy"] + rs = np.random.RandomState(20260821) + x1 = rs.standard_normal((40, 3)) + x2 = x1[:, :2] * 0.5 + rs.standard_normal((40, 2)) + x2 = np.hstack([x2, rs.standard_normal((40, 1))]) + return x1, x2 + + +# --------------------------------------------------------------------- +# cancorr +# --------------------------------------------------------------------- + +def test_cancorr_perfect_correlation(): + # x with itself has all canonical correlations equal to one, so + # Wilks' Lambda collapses to zero. + rs = np.random.RandomState(12345) + x1 = rs.standard_normal((50, 2)) + assert_allclose(cancorr(x1, x1), np.ones(2), atol=1e-8) + + +def test_cancorr_shape(): + rs = np.random.RandomState(12345) + x1 = rs.standard_normal((50, 2)) + _x2 = x1 * 0.7 + rs.standard_normal((50, 2)) + x2 = np.hstack([_x2, rs.standard_normal((50, 1))]) + cc = cancorr(x1, x2) + assert len(cc) == 2 + + +def test_cancorr_against_r(data_r): + # Reference values from R's base `cancor` function. + x1, x2 = data_r + cc = cancorr(x1, x2) + cc_expected = [0.532338026574400, 0.344170637520608, 0.114617183600323] + assert_allclose(np.real(cc), cc_expected, rtol=1e-7) + + +def test_cancorr_returns_real_dtype(data_r): + # Regression test: eigvals of the (generally non-symmetric) auxiliary + # matrix can come back with complex dtype even though the underlying + # canonical correlations are mathematically real. cancorr must not leak + # that dtype since cc_ranktest feeds the squared values straight into + # scipy.stats.chi2.sf, which raises TypeError on complex input. + x1, x2 = data_r + cc = cancorr(x1, x2) + assert not np.iscomplexobj(cc) + # cc_ranktest must not raise despite this. + cc_ranktest(x1, x2) + + +def test_cancorr_standardize_same_as_demean(): + # Rescaling by the standard deviation should not change the canonical + # correlation coefficients (see docstring). + rs = np.random.RandomState(7) + x1 = rs.standard_normal((80, 2)) * 3 + 1 + x2 = rs.standard_normal((80, 2)) * 0.2 - 4 + cc_demean = cancorr(x1, x2, demean=True, standardize=False) + cc_std = cancorr(x1, x2, demean=True, standardize=True) + assert_allclose(cc_demean, cc_std, rtol=1e-10) + + +def test_cancorr_demean_false_differs(): + # Without demeaning, the location of the data enters the projection and + # generally changes the canonical correlations. + rs = np.random.RandomState(10) + x1 = rs.standard_normal((80, 2)) + 5 + x2 = rs.standard_normal((80, 2)) + 3 + cc_demean = cancorr(x1, x2, demean=True) + cc_raw = cancorr(x1, x2, demean=False) + assert not np.allclose(cc_demean, cc_raw) + + +def test_cancorr_accepts_array_like(): + rs = np.random.RandomState(9) + x1 = rs.standard_normal((40, 2)) + x2 = rs.standard_normal((40, 2)) + cc_ndarray = cancorr(x1, x2) + cc_list = cancorr(x1.tolist(), x2.tolist()) + cc_df = cancorr(pd.DataFrame(x1), pd.DataFrame(x2)) + assert_allclose(cc_list, cc_ndarray, rtol=1e-12) + assert_allclose(cc_df, cc_ndarray, rtol=1e-12) + + +# --------------------------------------------------------------------- +# cc_ranktest +# --------------------------------------------------------------------- + +def test_cc_ranktest_fullrank_univariate_matches_formula(): + # With one variable on each side, the canonical correlation is the + # Pearson correlation (an independent computation via np.corrcoef), and + # the fullrank LM/Wald statistics reduce to simple closed-form + # expressions in that correlation. + rs = np.random.RandomState(11) + x1 = rs.standard_normal((120, 1)) + x2 = x1 * 0.6 + rs.standard_normal((120, 1)) + + r = np.corrcoef(x1.ravel(), x2.ravel())[0, 1] + nobs = x1.shape[0] + expected_lm = nobs * r**2 + expected_wald = nobs * r**2 / (1 - r**2) + expected_df = 1 + + value, pvalue, df, cc, w_value, w_pvalue = cc_ranktest(x1, x2, fullrank=True) + assert_allclose(value, expected_lm, rtol=1e-10) + assert_allclose(w_value, expected_wald, rtol=1e-10) + assert df == expected_df + assert_allclose(pvalue, sp_stats.chi2.sf(expected_lm, expected_df), rtol=1e-10) + assert_allclose(w_pvalue, sp_stats.chi2.sf(expected_wald, expected_df), rtol=1e-10) + assert_allclose(cc, [abs(r)], rtol=1e-10) + + +def test_cc_ranktest_fullrank_matches_smallest_cc(data): + x1, x2 = data + nobs = x1.shape[0] + cc = cancorr(x1, x2) + cc2_min = cc[-1] ** 2 + + value, pvalue, df, cc_out, w_value, w_pvalue = cc_ranktest(x1, x2, fullrank=True) + assert_allclose(value, nobs * cc2_min, rtol=1e-12) + assert_allclose(w_value, nobs * cc2_min / (1 - cc2_min), rtol=1e-12) + assert_allclose(cc_out, cc, rtol=1e-12) + + +def test_cc_ranktest_not_fullrank_matches_cumulative_formula(data): + x1, x2 = data + nobs, k1 = x1.shape + _, k2 = x2.shape + cc = cancorr(x1, x2) + cc2 = cc ** 2 + r = np.arange(min(k1, k2))[::-1] + expected_df = (k1 - r) * (k2 - r) + expected_value = nobs * cc2[::-1].cumsum() + expected_wald = nobs * (cc2 / (1 - cc2))[::-1].cumsum() + + value, pvalue, df, cc_out, w_value, w_pvalue = cc_ranktest(x1, x2, fullrank=False) + assert_allclose(value, expected_value, rtol=1e-12) + assert_allclose(w_value, expected_wald, rtol=1e-12) + assert_allclose(df, expected_df) + assert len(value) == min(k1, k2) + + +@pytest.mark.parametrize("fullrank", [True, False]) +def test_cc_ranktest_return_object(data, fullrank): + x1, x2 = data + legacy = cc_ranktest(x1, x2, fullrank=fullrank) + obj = cc_ranktest(x1, x2, fullrank=fullrank, return_object=True) + + assert isinstance(obj, CCRankTestResult) + slots = obj.__slots__ + for slot, b in zip(slots, legacy, strict=True): + a = getattr(obj, slot) + assert_allclose(a, b, rtol=1e-12) + + assert_allclose(obj.statistic, legacy[0], rtol=1e-12) + assert_allclose(obj.pvalue, legacy[1], rtol=1e-12) + assert_allclose(obj.df, legacy[2], rtol=1e-12) + assert_allclose(obj.ccorr, legacy[3], rtol=1e-12) + assert_allclose(obj.wald_statistic, legacy[4], rtol=1e-12) + assert_allclose(obj.wald_pvalue, legacy[5], rtol=1e-12) + + +def test_cc_ranktest_accepts_array_like(data): + x1, x2 = data + legacy = cc_ranktest(x1, x2) + from_list = cc_ranktest(x1.tolist(), x2.tolist()) + from_df = cc_ranktest(pd.DataFrame(x1), pd.DataFrame(x2)) + for a, b in zip(legacy, from_list, strict=True): + assert_allclose(a, b, rtol=1e-10) + for a, b in zip(legacy, from_df, strict=True): + assert_allclose(a, b, rtol=1e-10) + + +# --------------------------------------------------------------------- +# cc_stats +# --------------------------------------------------------------------- + +def test_cc_stats_runs(data): + x1, x2 = data + res = cc_stats(x1, x2) + expected_keys = { + "canonical correlation coefficient", + "eigenvalues", + "Pillai's Trace", + "Wilk's Lambda", + "Hotelling's Trace", + "Roy's Largest Root", + "df_resid", + "df_m", + } + assert expected_keys == set(res) + assert np.isfinite(res["Wilk's Lambda"]) + + +def test_cc_stats_identities(data): + # The four classical MANOVA statistics are exact functions of the + # squared canonical correlations. + x1, x2 = data + res = cc_stats(x1, x2) + cc2 = cancorr(x1, x2) ** 2 + lam = cc2 / (1 - cc2) + + assert_allclose(res["Wilk's Lambda"], np.prod(1 - cc2), rtol=1e-12) + assert_allclose(res["Pillai's Trace"], cc2.sum(), rtol=1e-12) + assert_allclose(res["Hotelling's Trace"], lam.sum(), rtol=1e-12) + assert_allclose(res["Roy's Largest Root"], lam.max(), rtol=1e-12) + + +def test_cc_stats_univariate_equals_correlation(): + # With one variable on each side the canonical correlation is the + # absolute Pearson correlation and Wilks' Lambda is 1 - r ** 2. + rs = np.random.RandomState(12345) + x1 = rs.standard_normal((100, 1)) + x2 = x1 * 0.7 + rs.standard_normal((100, 1)) + + r = np.corrcoef(x1.ravel(), x2.ravel())[0, 1] + res = cc_stats(x1, x2) + + assert_allclose(res["canonical correlation coefficient"], [abs(r)], rtol=1e-10) + assert_allclose(res["Wilk's Lambda"], 1 - r**2, rtol=1e-10) + assert_allclose(res["Pillai's Trace"], r**2, rtol=1e-10) + + +def test_cc_stats_against_r(data_r): + # Reference values from R's `summary(manova(lm(x1 ~ x2)))` for the four + # classical MANOVA test statistics, which are equivalent to cc_stats + # with demean=True (the default). + x1, x2 = data_r + res = cc_stats(x1, x2) + assert_allclose(res["Pillai's Trace"], 0.414974301044939, rtol=1e-7) + assert_allclose(res["Wilk's Lambda"], 0.623431470196253, rtol=1e-7) + assert_allclose(res["Hotelling's Trace"], 0.543129049437308, rtol=1e-7) + assert_allclose(res["Roy's Largest Root"], 0.395447053063982, rtol=1e-7) + + +def test_cc_stats_demean_false(): + # Not demeaning changes the projection (the mean is no longer + # partialled out), so the results generally differ from demean=True, + # but the returned statistics must still be exact functions of + # cancorr(..., demean=False). + rs = np.random.RandomState(4) + x1 = rs.standard_normal((60, 2)) + 5 + x2 = rs.standard_normal((60, 2)) + 3 + res_demean = cc_stats(x1, x2, demean=True) + res_raw = cc_stats(x1, x2, demean=False) + assert not np.allclose(res_demean["Wilk's Lambda"], res_raw["Wilk's Lambda"]) + + cc2 = cancorr(x1, x2, demean=False) ** 2 + assert_allclose(res_raw["Pillai's Trace"], cc2.sum(), rtol=1e-12) + + +def test_cc_stats_return_object(data): + x1, x2 = data + res_dict = cc_stats(x1, x2) + res_obj = cc_stats(x1, x2, return_object=True) + + assert isinstance(res_obj, CCStatsResult) + assert_allclose(res_obj.ccorr, res_dict["canonical correlation coefficient"]) + assert_allclose(res_obj.eigenvalues, res_dict["eigenvalues"]) + assert_allclose(res_obj.pillai_trace, res_dict["Pillai's Trace"]) + assert_allclose(res_obj.wilks_lambda, res_dict["Wilk's Lambda"]) + assert_allclose(res_obj.hotelling_trace, res_dict["Hotelling's Trace"]) + assert_allclose(res_obj.roys_largest_root, res_dict["Roy's Largest Root"]) + assert res_obj.df_resid == res_dict["df_resid"] + assert res_obj.df_model == res_dict["df_m"] + + +def test_cc_stats_accepts_array_like(data): + x1, x2 = data + res_ndarray = cc_stats(x1, x2) + res_list = cc_stats(x1.tolist(), x2.tolist()) + res_df = cc_stats(pd.DataFrame(x1), pd.DataFrame(x2)) + for key in res_ndarray: + assert_allclose(res_list[key], res_ndarray[key], rtol=1e-12) + assert_allclose(res_df[key], res_ndarray[key], rtol=1e-12) + + +# --------------------------------------------------------------------- +# partial_project +# --------------------------------------------------------------------- + +def test_partial_project_matches_lstsq(): + # Cross-check against numpy's lstsq, an independent least-squares + # implementation, rather than only checking internal consistency. + rs = np.random.RandomState(3) + endog = rs.standard_normal((50, 2)) + exog = np.column_stack([np.ones(50), rs.standard_normal((50, 2))]) + res = partial_project(endog, exog) + assert isinstance(res, PartialProjectResult) + + expected_params = np.linalg.lstsq(exog, endog, rcond=None)[0] + assert_allclose(res.params, expected_params, rtol=1e-10) + assert_allclose(res.fittedvalues, exog.dot(expected_params), rtol=1e-10) + assert_allclose(res.resid, endog - exog.dot(expected_params), rtol=1e-10) + + +def test_partial_project_orthogonality(): + # The projected residual must be orthogonal to every column of exog: + # the defining property of an OLS projection, verified independently of + # the pinv-based implementation. + rs = np.random.RandomState(5) + endog = rs.standard_normal((60, 3)) + exog = np.column_stack([np.ones(60), rs.standard_normal((60, 2))]) + res = partial_project(endog, exog) + cross = exog.T.dot(res.resid) + assert_allclose(cross, np.zeros_like(cross), atol=1e-8) + + +def test_partial_project_accepts_array_like(): + rs = np.random.RandomState(6) + endog = rs.standard_normal((30, 2)) + exog = rs.standard_normal((30, 2)) + res_ndarray = partial_project(endog, exog) + res_list = partial_project(endog.tolist(), exog.tolist()) + res_df = partial_project(pd.DataFrame(endog), pd.DataFrame(exog)) + assert_allclose(res_list.resid, res_ndarray.resid, rtol=1e-10) + assert_allclose(res_df.resid, res_ndarray.resid, rtol=1e-10) + + +def test_partial_project_1d_input(): + # array_like inserts a trailing axis for 1-D input, so a single-column + # endog/exog specified as a plain 1-D array must still work. + rs = np.random.RandomState(8) + endog = rs.standard_normal(40) + exog = rs.standard_normal(40) + res = partial_project(endog, exog) + assert res.params.shape == (1, 1) + assert res.resid.shape == (40, 1) diff --git a/shared/package-files/d2/d29c31bbe224ac446d850af98537143d09d59bbba847da78e43731a9885d9db7/blob b/shared/package-files/d2/d29c31bbe224ac446d850af98537143d09d59bbba847da78e43731a9885d9db7/blob new file mode 100644 index 0000000000000000000000000000000000000000..0ff32c857b7cfe62f09a9543313131e8b3f35db7 --- /dev/null +++ b/shared/package-files/d2/d29c31bbe224ac446d850af98537143d09d59bbba847da78e43731a9885d9db7/blob @@ -0,0 +1,16 @@ +from ...deprecations import deprecated +deprecated.module("23.3", "23.9", addendum="Use `tqdm` instead.") + +from ._monitor import TMonitor, TqdmSynchronisationWarning +from .cli import main # TODO: remove in v5.0.0 +from .std import ( + TqdmDeprecationWarning, TqdmExperimentalWarning, TqdmKeyError, TqdmMonitorWarning, + TqdmTypeError, TqdmWarning, tqdm, trange) +from .version import __version__ + +__all__ = ['tqdm', 'trange', 'main', 'TMonitor', + 'TqdmTypeError', 'TqdmKeyError', + 'TqdmWarning', 'TqdmDeprecationWarning', + 'TqdmExperimentalWarning', + 'TqdmMonitorWarning', 'TqdmSynchronisationWarning', + '__version__'] diff --git a/shared/package-files/d2/d29c818b1a17dfc7e57533ced55c2c862fc7d170400abcfc7ac6282f8a3bd4a2/blob b/shared/package-files/d2/d29c818b1a17dfc7e57533ced55c2c862fc7d170400abcfc7ac6282f8a3bd4a2/blob new file mode 100644 index 0000000000000000000000000000000000000000..1e769f49d942b169a9473ba777b29666355d7062 --- /dev/null +++ b/shared/package-files/d2/d29c818b1a17dfc7e57533ced55c2c862fc7d170400abcfc7ac6282f8a3bd4a2/blob @@ -0,0 +1,47 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# This file is called from a test in test_pandas.py. + +from threading import Thread + +import pandas as pd +from pyarrow.pandas_compat import _pandas_api + +if __name__ == "__main__": + wait = True + num_threads = 10 + df = pd.DataFrame() + results = [] + + def rc(): + while wait: + pass + results.append(_pandas_api.is_data_frame(df)) + + threads = [Thread(target=rc) for _ in range(num_threads)] + + for t in threads: + t.start() + + wait = False + + for t in threads: + t.join() + + assert len(results) == num_threads + assert all(results), "`is_data_frame` returned False when given a DataFrame" diff --git a/shared/package-files/d2/d29d4d8ba5ef935b48099f4b7e5fdd5fe0439676ef959061bbdc02209dc94120/blob b/shared/package-files/d2/d29d4d8ba5ef935b48099f4b7e5fdd5fe0439676ef959061bbdc02209dc94120/blob new file mode 100644 index 0000000000000000000000000000000000000000..bfc57361725f0270bcd6bcb1da8f79bc5de28280 --- /dev/null +++ b/shared/package-files/d2/d29d4d8ba5ef935b48099f4b7e5fdd5fe0439676ef959061bbdc02209dc94120/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor col2im(const at::Tensor & self, at::IntArrayRef output_size, at::IntArrayRef kernel_size, at::IntArrayRef dilation, at::IntArrayRef padding, at::IntArrayRef stride); +TORCH_API at::Tensor col2im_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, at::IntArrayRef kernel_size, at::IntArrayRef dilation, at::IntArrayRef padding, at::IntArrayRef stride); +TORCH_API at::Tensor & col2im_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, at::IntArrayRef kernel_size, at::IntArrayRef dilation, at::IntArrayRef padding, at::IntArrayRef stride); +TORCH_API at::Tensor & col2im_outf(const at::Tensor & self, at::IntArrayRef output_size, at::IntArrayRef kernel_size, at::IntArrayRef dilation, at::IntArrayRef padding, at::IntArrayRef stride, at::Tensor & out); +TORCH_API at::Tensor & col2im_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, at::IntArrayRef kernel_size, at::IntArrayRef dilation, at::IntArrayRef padding, at::IntArrayRef stride); +TORCH_API at::Tensor & col2im_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, at::IntArrayRef kernel_size, at::IntArrayRef dilation, at::IntArrayRef padding, at::IntArrayRef stride, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/d2/d29e6c8acb034858b165e639f4d6ac0201fac003592aaec4effac7e42c987f22/blob b/shared/package-files/d2/d29e6c8acb034858b165e639f4d6ac0201fac003592aaec4effac7e42c987f22/blob new file mode 100644 index 0000000000000000000000000000000000000000..dacd2090a7b719dcd219edcc50d79d6da64857d7 --- /dev/null +++ b/shared/package-files/d2/d29e6c8acb034858b165e639f4d6ac0201fac003592aaec4effac7e42c987f22/blob @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::l1_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor +inline at::Tensor l1_loss(const at::Tensor & self, const at::Tensor & target, int64_t reduction=at::Reduction::Mean) { + return at::_ops::l1_loss::call(self, target, reduction); +} + +} diff --git a/shared/package-files/d2/d29e734b34f3f8cb4a8c2b9305b6e7f378214ecd13928f2671db2c7ee0f7b378/blob b/shared/package-files/d2/d29e734b34f3f8cb4a8c2b9305b6e7f378214ecd13928f2671db2c7ee0f7b378/blob new file mode 100644 index 0000000000000000000000000000000000000000..ca2983e22e8602b865d2d7e6283c8f11e7e8415e --- /dev/null +++ b/shared/package-files/d2/d29e734b34f3f8cb4a8c2b9305b6e7f378214ecd13928f2671db2c7ee0f7b378/blob @@ -0,0 +1 @@ +# Edit this file for local setup changes diff --git a/shared/package-files/d2/d29eaaa46aa0064ca1d5ad091589afc16cbeaa895f1d48396d981d6f8da47dd9/blob b/shared/package-files/d2/d29eaaa46aa0064ca1d5ad091589afc16cbeaa895f1d48396d981d6f8da47dd9/blob new file mode 100644 index 0000000000000000000000000000000000000000..fc412b8c5082dd8c4346711314fc7cc43c1a9ba2 --- /dev/null +++ b/shared/package-files/d2/d29eaaa46aa0064ca1d5ad091589afc16cbeaa895f1d48396d981d6f8da47dd9/blob @@ -0,0 +1,2 @@ +def exportdb_error_message(case_name: str): + return "" diff --git a/shared/package-files/d2/d29f611169355208a35d0ad8e3f84f4158c06253e44b5cfcdb2e2ac5c75e1cbc/blob b/shared/package-files/d2/d29f611169355208a35d0ad8e3f84f4158c06253e44b5cfcdb2e2ac5c75e1cbc/blob new file mode 100644 index 0000000000000000000000000000000000000000..b744da0c27d61d5c1597849c0691396d8a86e56f --- /dev/null +++ b/shared/package-files/d2/d29f611169355208a35d0ad8e3f84f4158c06253e44b5cfcdb2e2ac5c75e1cbc/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API grid_sampler_2d { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, int64_t, int64_t, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::grid_sampler_2d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "grid_sampler_2d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor") + static at::Tensor call(const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners); +}; + +struct TORCH_API grid_sampler_2d_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, int64_t, int64_t, bool, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::grid_sampler_2d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "grid_sampler_2d.out(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/d2/d2a2ded8e020f68ca43337984428da558a6d897ff0dbcfb3ac6c3ff9d25446cf/blob b/shared/package-files/d2/d2a2ded8e020f68ca43337984428da558a6d897ff0dbcfb3ac6c3ff9d25446cf/blob new file mode 100644 index 0000000000000000000000000000000000000000..1c377c88b5764bcf19074a1b9f87c7a91fa43f05 --- /dev/null +++ b/shared/package-files/d2/d2a2ded8e020f68ca43337984428da558a6d897ff0dbcfb3ac6c3ff9d25446cf/blob @@ -0,0 +1,1243 @@ +#!/usr/bin/env python +# Copyright (c) 2017-2023, Intel Corporation +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of Intel Corporation nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#cython: language_level=3 + +# imports +import sys +import numpy as np +from numpy.core._multiarray_tests import internal_overlap +from threading import local as threading_local + +# cimports +cimport numpy as cnp +from libc.string cimport memcpy +cimport cpython.pycapsule +from cpython.exc cimport (PyErr_Occurred, PyErr_Clear) +from cpython.mem cimport (PyMem_Malloc, PyMem_Free) + + +# thread-local storage +_tls = threading_local() + +cdef const char *capsule_name = "dfti_cache" + +cdef void _capsule_destructor(object caps) noexcept: + cdef DftiCache *_cache = NULL + cdef int status = 0 + if (caps is None): + print("CapsuleDestructorInternalError: Nothing to destroy", file=sys.stderr) + return + _cache = cpython.pycapsule.PyCapsule_GetPointer(caps, capsule_name) + status = _free_dfti_cache(_cache) + PyMem_Free(_cache) + if (status != 0): + print("CapsuleDestructorInternalError: Freeing DFTI Cache " + f"returned with error code = '{status}'", file=sys.stderr) + + +def _tls_dfti_cache_capsule(): + cdef DftiCache *_cache_struct + + init = getattr(_tls, 'initialized', None) + if (init is None): + _cache_struct = PyMem_Malloc(sizeof(DftiCache)); + # important to initialized + _cache_struct.initialized = 0 + _cache_struct.hand = NULL + _tls.initialized = True + _tls.capsule = cpython.pycapsule.PyCapsule_New(_cache_struct, capsule_name, &_capsule_destructor) + capsule = getattr(_tls, 'capsule', None) + if (not cpython.pycapsule.PyCapsule_IsValid(capsule, capsule_name)): + raise ValueError("Internal Error: invalid capsule stored in TLS") + return capsule + + +cdef extern from "Python.h": + ctypedef int size_t + + long PyInt_AsLong(object ob) + int PyObject_HasAttrString(object, char*) + + +# These are commented out in the numpy support we cimported above. +# Here I have declared them as taking void* instead of PyArrayDescr +# and object. In this file, only NULL is passed to these parameters. +cdef extern from *: + cnp.ndarray PyArray_CheckFromAny(object, void*, int, int, int, void*) + object PyArray_BASE(cnp.ndarray) + +cdef extern from "src/mklfft.h": + cdef struct DftiCache: + void * hand + int initialized + int _free_dfti_cache(DftiCache *) + int cdouble_mkl_fft1d_in(cnp.ndarray, int, int, double, DftiCache*) + int cfloat_mkl_fft1d_in(cnp.ndarray, int, int, double, DftiCache*) + int float_cfloat_mkl_fft1d_out(cnp.ndarray, int, int, cnp.ndarray, int, double, DftiCache*) + int cfloat_cfloat_mkl_fft1d_out(cnp.ndarray, int, int, cnp.ndarray, double, DftiCache*) + int double_cdouble_mkl_fft1d_out(cnp.ndarray, int, int, cnp.ndarray, int, double, DftiCache*) + int cdouble_cdouble_mkl_fft1d_out(cnp.ndarray, int, int, cnp.ndarray, double, DftiCache*) + + int cdouble_mkl_ifft1d_in(cnp.ndarray, int, int, double, DftiCache*) + int cfloat_mkl_ifft1d_in(cnp.ndarray, int, int, double, DftiCache*) + int float_cfloat_mkl_ifft1d_out(cnp.ndarray, int, int, cnp.ndarray, int, double, DftiCache*) + int cfloat_cfloat_mkl_ifft1d_out(cnp.ndarray, int, int, cnp.ndarray, double, DftiCache*) + int double_cdouble_mkl_ifft1d_out(cnp.ndarray, int, int, cnp.ndarray, int, double, DftiCache*) + int cdouble_cdouble_mkl_ifft1d_out(cnp.ndarray, int, int, cnp.ndarray, double, DftiCache*) + + int double_mkl_rfft_in(cnp.ndarray, int, int, double, DftiCache*) + int double_mkl_irfft_in(cnp.ndarray, int, int, double, DftiCache*) + int float_mkl_rfft_in(cnp.ndarray, int, int, double, DftiCache*) + int float_mkl_irfft_in(cnp.ndarray, int, int, double, DftiCache*) + + int cdouble_double_mkl_irfft_out(cnp.ndarray, int, int, cnp.ndarray, double, DftiCache*) + int cfloat_float_mkl_irfft_out(cnp.ndarray, int, int, cnp.ndarray, double, DftiCache*) + + int cdouble_cdouble_mkl_fftnd_in(cnp.ndarray, double) + int cdouble_cdouble_mkl_ifftnd_in(cnp.ndarray, double) + int cfloat_cfloat_mkl_fftnd_in(cnp.ndarray, double) + int cfloat_cfloat_mkl_ifftnd_in(cnp.ndarray, double) + + int cdouble_cdouble_mkl_fftnd_out(cnp.ndarray, cnp.ndarray, double) + int cdouble_cdouble_mkl_ifftnd_out(cnp.ndarray, cnp.ndarray, double) + int cfloat_cfloat_mkl_fftnd_out(cnp.ndarray, cnp.ndarray, double) + int cfloat_cfloat_mkl_ifftnd_out(cnp.ndarray, cnp.ndarray, double) + + int float_cfloat_mkl_fftnd_out(cnp.ndarray, cnp.ndarray, double) + int double_cdouble_mkl_fftnd_out(cnp.ndarray, cnp.ndarray, double) + int float_cfloat_mkl_ifftnd_out(cnp.ndarray, cnp.ndarray, double) + int double_cdouble_mkl_ifftnd_out(cnp.ndarray, cnp.ndarray, double) + char * mkl_dfti_error(int) + +# Initialize numpy +cdef int numpy_import_status = cnp.import_array() +if numpy_import_status < 0: + raise ImportError("Failed to import NumPy as dependency of mkl_fft") + + +cdef int _datacopied(cnp.ndarray arr, object orig): + """ + Strict check for `arr` not sharing any data with `original`, + under the assumption that arr = asarray(original) + """ + if not cnp.PyArray_Check(orig) and PyObject_HasAttrString(orig, '__array__'): + return 0 + if isinstance(orig, np.ndarray) and (arr is ( orig)): + return 0 + arr_obj = arr + return 1 if (arr_obj.base is None) else 0 + + +def fft(x, n=None, axis=-1, overwrite_x=False, forward_scale=1.0): + return _fft1d_impl(x, n=n, axis=axis, overwrite_arg=overwrite_x, direction=+1, fsc=forward_scale) + + +def ifft(x, n=None, axis=-1, overwrite_x=False, forward_scale=1.0): + return _fft1d_impl(x, n=n, axis=axis, overwrite_arg=overwrite_x, direction=-1, fsc=forward_scale) + + +cdef cnp.ndarray pad_array(cnp.ndarray x_arr, cnp.npy_intp n, int axis, int realQ): + "Internal utility to zero-pad input array along given axis" + cdef cnp.ndarray b_arr "b_arrayObject" + cdef int x_type, b_type, b_ndim, x_arr_is_fortran + cdef cnp.npy_intp *b_shape + + x_type = cnp.PyArray_TYPE(x_arr) + if realQ: + b_type = x_type + else: + b_type = cnp.NPY_CFLOAT if (x_type is cnp.NPY_FLOAT or + x_type is cnp.NPY_CFLOAT) else cnp.NPY_CDOUBLE + b_ndim = cnp.PyArray_NDIM(x_arr) + + b_shape = PyMem_Malloc(b_ndim * sizeof(cnp.npy_intp)) + memcpy(b_shape, cnp.PyArray_DIMS(x_arr), b_ndim * sizeof(cnp.npy_intp)) + b_shape[axis] = n + + # allocating temporary buffer + x_arr_is_fortran = cnp.PyArray_CHKFLAGS(x_arr, cnp.NPY_F_CONTIGUOUS) + b_arr = cnp.PyArray_EMPTY( + b_ndim, b_shape, b_type, x_arr_is_fortran) # 0 for C-contiguous + PyMem_Free(b_shape) + + ind = [slice(0, None, None), ] * b_ndim + ind[axis] = slice(0, cnp.PyArray_DIM(x_arr, axis), None) + bo = b_arr + xo = x_arr + bo[tuple(ind)] = xo + ind[axis] = slice(cnp.PyArray_DIM(x_arr, axis), None, None) + bo[tuple(ind)] = 0.0 + + return b_arr + + +cdef cnp.ndarray __process_arguments(object x, object n, object axis, + object overwrite_arg, object direction, + long *axis_, long *n_, int *in_place, + int *xnd, int *dir_, int realQ): + "Internal utility to validate and process input arguments of 1D FFT functions" + cdef int err + cdef long n_max = 0 + cdef cnp.ndarray x_arr "xx_arrayObject" + + if direction not in [-1, +1]: + raise ValueError("Direction of FFT should +1 or -1") + else: + dir_[0] = -1 if direction is -1 else +1 + + in_place[0] = 1 if overwrite_arg is True else 0 + + # convert x to ndarray, ensure that strides are multiples of itemsize + x_arr = PyArray_CheckFromAny( + x, NULL, 0, 0, + cnp.NPY_ELEMENTSTRIDES | cnp.NPY_ENSUREARRAY | cnp.NPY_NOTSWAPPED, + NULL) + + if x_arr is NULL: + raise ValueError("An input argument x is not an array-like object") + + if _datacopied(x_arr, x): + in_place[0] = 1 # a copy was made, so we can work in place. + + xnd[0] = cnp.PyArray_NDIM(x_arr) # tensor-rank of the array + + err = 0 + axis_[0] = PyInt_AsLong(axis) + if (axis_[0] == -1 and PyErr_Occurred()): + PyErr_Clear() + err = 1 + elif not (-xnd[0] <= axis_[0] < xnd[0]): + err = 1 + + if err: + raise ValueError("Invalid axis (%d) specified." % axis) + + axis_[0] = axis_[0] if axis_[0] >= 0 else xnd[0] + axis_[0] + + if n is None: + n_[0] = x_arr.shape[axis_[0]] + else: + try: + n_[0] = PyInt_AsLong(n) + except: + err = 1 + + if not err: + n_max = cnp.PyArray_DIM(x_arr, axis_[0]) + if n_[0] < 1: + err = 1 + elif n_[0] > n_max: + in_place[0] = 1 # we must copy to pad and will work in-place + x_arr = pad_array(x_arr, n_[0], axis_[0], realQ) + + if err: + raise ValueError("Dimension n should be a positive integer not " + "larger than the shape of the array along the chosen axis") + + return x_arr + + +cdef cnp.ndarray __allocate_result(cnp.ndarray x_arr, long n_, long axis_, int f_type): + """ + An internal utility to allocate an empty array for output of not-in-place FFT. + """ + cdef cnp.npy_intp *f_shape + cdef cnp.ndarray f_arr "ff_arrayObject" + cdef int x_arr_is_fortran + + f_ndim = cnp.PyArray_NDIM(x_arr) + + f_shape = PyMem_Malloc(f_ndim * sizeof(cnp.npy_intp)) + memcpy(f_shape, cnp.PyArray_DIMS(x_arr), f_ndim * sizeof(cnp.npy_intp)) + # if dimension is negative, do not alter the dimension + if n_ > 0: + f_shape[axis_] = n_ + + # allocating output buffer + x_arr_is_fortran = cnp.PyArray_CHKFLAGS(x_arr, cnp.NPY_F_CONTIGUOUS) + f_arr = cnp.PyArray_EMPTY( + f_ndim, f_shape, f_type, x_arr_is_fortran) # 0 for C-contiguous + PyMem_Free(f_shape); + + return f_arr + + +# this routine implements complex forward/backward FFT +# Float/double inputs are not cast to complex, but are effectively +# treated as complexes with zero imaginary parts. +# All other types are cast to complex double. +def _fft1d_impl(x, n=None, axis=-1, overwrite_arg=False, direction=+1, double fsc=1.0): + """ + Uses MKL to perform 1D FFT on the input array x along the given axis. + """ + cdef cnp.ndarray x_arr "x_arrayObject" + cdef cnp.ndarray f_arr "f_arrayObject" + cdef int xnd, err, n_max = 0, in_place, dir_ + cdef long n_, axis_ + cdef int x_type, f_type, status = 0 + cdef int ALL_HARMONICS = 1 + cdef char * c_error_msg = NULL + cdef bytes py_error_msg + cdef DftiCache *_cache + + x_arr = __process_arguments(x, n, axis, overwrite_arg, direction, + &axis_, &n_, &in_place, &xnd, &dir_, 0) + + x_type = cnp.PyArray_TYPE(x_arr) + + if x_type is cnp.NPY_CFLOAT or x_type is cnp.NPY_CDOUBLE: + # we can operate in place if requested. + if in_place: + if not cnp.PyArray_ISONESEGMENT(x_arr): + in_place = 0 if internal_overlap(x_arr) else 1; + elif x_type is cnp.NPY_FLOAT or x_type is cnp.NPY_DOUBLE: + # to work in place we need to cast the input to complex, + # which may be more expensive than creating the output using MKL + in_place = 0 + else: + # we must cast the input and allocate the output, + # so we cast to complex double and operate in place + try: + x_arr = cnp.PyArray_FROM_OTF( + x_arr, cnp.NPY_CDOUBLE, cnp.NPY_BEHAVED | cnp.NPY_ENSURECOPY) + except: + raise ValueError("First argument must be a complex or real sequence of single or double precision") + x_type = cnp.PyArray_TYPE(x_arr) + in_place = 1 + + if in_place: + _cache_capsule = _tls_dfti_cache_capsule() + _cache = cpython.pycapsule.PyCapsule_GetPointer(_cache_capsule, capsule_name) + if x_type is cnp.NPY_CDOUBLE: + if dir_ < 0: + status = cdouble_mkl_ifft1d_in(x_arr, n_, axis_, fsc, _cache) + else: + status = cdouble_mkl_fft1d_in(x_arr, n_, axis_, fsc, _cache) + elif x_type is cnp.NPY_CFLOAT: + if dir_ < 0: + status = cfloat_mkl_ifft1d_in(x_arr, n_, axis_, fsc, _cache) + else: + status = cfloat_mkl_fft1d_in(x_arr, n_, axis_, fsc, _cache) + else: + status = 1 + + if status: + c_error_msg = mkl_dfti_error(status) + py_error_msg = c_error_msg + raise ValueError("Internal error occurred: {}".format(py_error_msg)) + + n_max = cnp.PyArray_DIM(x_arr, axis_) + if (n_ < n_max): + ind = [slice(0, None, None), ] * xnd + ind[axis_] = slice(0, n_, None) + x_arr = x_arr[tuple(ind)] + + return x_arr + else: + f_type = cnp.NPY_CFLOAT if (x_type is cnp.NPY_FLOAT or + x_type is cnp.NPY_CFLOAT) else cnp.NPY_CDOUBLE + f_arr = __allocate_result(x_arr, n_, axis_, f_type); + + # call out-of-place FFT + _cache_capsule = _tls_dfti_cache_capsule() + _cache = cpython.pycapsule.PyCapsule_GetPointer(_cache_capsule, capsule_name) + if f_type is cnp.NPY_CDOUBLE: + if x_type is cnp.NPY_DOUBLE: + if dir_ < 0: + status = double_cdouble_mkl_ifft1d_out( + x_arr, n_, axis_, f_arr, ALL_HARMONICS, fsc, _cache) + else: + status = double_cdouble_mkl_fft1d_out( + x_arr, n_, axis_, f_arr, ALL_HARMONICS, fsc, _cache) + elif x_type is cnp.NPY_CDOUBLE: + if dir_ < 0: + status = cdouble_cdouble_mkl_ifft1d_out( + x_arr, n_, axis_, f_arr, fsc, _cache) + else: + status = cdouble_cdouble_mkl_fft1d_out( + x_arr, n_, axis_, f_arr, fsc, _cache) + else: + if x_type is cnp.NPY_FLOAT: + if dir_ < 0: + status = float_cfloat_mkl_ifft1d_out( + x_arr, n_, axis_, f_arr, ALL_HARMONICS, fsc, _cache) + else: + status = float_cfloat_mkl_fft1d_out( + x_arr, n_, axis_, f_arr, ALL_HARMONICS, fsc, _cache) + elif x_type is cnp.NPY_CFLOAT: + if dir_ < 0: + status = cfloat_cfloat_mkl_ifft1d_out( + x_arr, n_, axis_, f_arr, fsc, _cache) + else: + status = cfloat_cfloat_mkl_fft1d_out( + x_arr, n_, axis_, f_arr, fsc, _cache) + + if (status): + c_error_msg = mkl_dfti_error(status) + py_error_msg = c_error_msg + raise ValueError("Internal error occurred: {}".format(py_error_msg)) + + return f_arr + + +def rfft(x, n=None, axis=-1, overwrite_x=False, forward_scale=1.0): + """Packed real-valued harmonics of FFT of a real sequence x""" + return _rr_fft1d_impl2(x, n=n, axis=axis, overwrite_arg=overwrite_x, fsc=forward_scale) + + +def irfft(x, n=None, axis=-1, overwrite_x=False, forward_scale=1.0): + """Inverse FFT of a real sequence, takes packed real-valued harmonics of FFT""" + return _rr_ifft1d_impl2(x, n=n, axis=axis, overwrite_arg=overwrite_x, fsc=forward_scale) + + +cdef object _rc_to_rr(cnp.ndarray rc_arr, int n, int axis, int xnd, int x_type): + cdef object res + cdef object sl, sl1, sl2 + + inp = rc_arr + + slice_ = [slice(None, None, None)] * xnd + sl_0 = list(slice_) + sl_0[axis] = 0 + + sl_1 = list(slice_) + sl_1[axis] = 1 + if (inp.flags['C'] and inp.strides[axis] == inp.itemsize): + res = inp + res = res.view(dtype=np.single if (x_type == cnp.NPY_FLOAT) else np.double) + res[tuple(sl_1)] = res[tuple(sl_0)] + + slice_[axis] = slice(1, n + 1, None) + + return res[tuple(slice_)] + else: + res_shape = list(inp.shape) + res_shape[axis] = n + res = np.empty(tuple(res_shape), dtype=np.single if (x_type == cnp.NPY_FLOAT) else np.double) + + res[tuple(sl_0)] = inp[tuple(sl_0)].real + sl_dst_real = list(slice_) + sl_dst_real[axis] = slice(1, None, 2) + sl_src_real = list(slice_) + sl_src_real[axis] = slice(1, None, None) + res[tuple(sl_dst_real)] = inp[tuple(sl_src_real)].real + sl_dst_imag = list(slice_) + sl_dst_imag[axis] = slice(2, None, 2) + sl_src_imag = list(slice_) + sl_src_imag[axis] = slice(1, inp.shape[axis] if (n & 1) else inp.shape[axis] - 1, None) + res[tuple(sl_dst_imag)] = inp[tuple(sl_src_imag)].imag + + return res[tuple(slice_)] + +cdef object _rr_to_rc(cnp.ndarray rr_arr, int n, int axis, int xnd, int x_type): + + inp = rr_arr + + rc_shape = list(inp.shape) + rc_shape[axis] = (n // 2 + 1) + rc_shape = tuple(rc_shape) + + rc_dtype = np.cdouble if x_type == cnp.NPY_DOUBLE else np.csingle + rc = np.empty(rc_shape, dtype=rc_dtype, order='C') + + slice_ = [slice(None, None, None)] * xnd + sl_src_real = list(slice_) + sl_src_imag = list(slice_) + sl_src_real[axis] = slice(1, n, 2) + sl_src_imag[axis] = slice(2, n, 2) + + sl_dest_real = list(slice_) + sl_dest_real[axis] = slice(1, None, None) + sl_dest_imag = list(slice_) + sl_dest_imag[axis] = slice(1, (n+1)//2, None) + + sl_0 = list(slice_) + sl_0[axis] = 0 + + rc_real = rc.real + rc_imag = rc.imag + + rc_real[tuple(sl_dest_real)] = inp[tuple(sl_src_real)] + rc_imag[tuple(sl_dest_imag)] = inp[tuple(sl_src_imag)] + rc_real[tuple(sl_0)] = inp[tuple(sl_0)] + rc_imag[tuple(sl_0)] = 0 + if (n & 1 == 0): + sl_last = list(slice_) + sl_last[axis] = -1 + rc_imag[tuple(sl_last)] = 0 + + return rc + + +def _repack_rr_to_rc(x, n, axis): + """Debugging utility""" + cdef cnp.ndarray x_arr + cdef int n_ = n, axis_ = axis + cdef x_type + + x_arr = np.asarray(x) + x_type = cnp.PyArray_TYPE(x_arr) + return _rr_to_rc(x, n_, axis_, cnp.PyArray_NDIM(x_arr), x_type) + + +def _repack_rc_to_rr(x, n, axis): + """Debugging utility""" + cdef cnp.ndarray x_arr + cdef int n_ = n, axis_ = axis + cdef c_type, x_type + + x_arr = np.asarray(x) + c_type = cnp.PyArray_TYPE(x_arr) + x_type = cnp.NPY_DOUBLE if c_type == cnp.NPY_CDOUBLE else cnp.NPY_FLOAT + return _rc_to_rr(x, n_, axis_, cnp.PyArray_NDIM(x_arr), x_type) + + +def _rr_fft1d_impl2(x, n=None, axis=-1, overwrite_arg=False, double fsc=1.0): + """ + Uses MKL to perform real packed 1D FFT on the input array x along the given axis. + + This done by using rfft_numpy and post-processing the result. + Thus overwrite_arg is effectively discarded. + + Functionally equivalent to scipy.fftpack.rfft + """ + cdef cnp.ndarray x_arr "x_arrayObject" + cdef cnp.ndarray f_arr "f_arrayObject" + cdef int xnd, err, n_max = 0, in_place, dir_ + cdef long n_, axis_ + cdef int HALF_HARMONICS = 0 # give only positive index harmonics + cdef int x_type, status, f_type + cdef char * c_error_msg = NULL + cdef bytes py_error_msg + cdef DftiCache *_cache + + x_arr = __process_arguments(x, n, axis, overwrite_arg, (+1), + &axis_, &n_, &in_place, &xnd, &dir_, 1) + + x_type = cnp.PyArray_TYPE(x_arr) + + if x_type is cnp.NPY_FLOAT or x_type is cnp.NPY_DOUBLE: + in_place = 0 + elif x_type is cnp.NPY_CFLOAT or x_type is cnp.NPY_CDOUBLE: + raise TypeError("1st argument must be a real sequence") + else: + try: + x_arr = cnp.PyArray_FROM_OTF( + x_arr, cnp.NPY_DOUBLE, cnp.NPY_BEHAVED | cnp.NPY_ENSURECOPY) + except: + raise TypeError("1st argument must be a real sequence") + x_type = cnp.PyArray_TYPE(x_arr) + in_place = 0 + + f_type = cnp.NPY_CFLOAT if x_type is cnp.NPY_FLOAT else cnp.NPY_CDOUBLE + f_arr = __allocate_result(x_arr, n_ // 2 + 1, axis_, f_type); + + _cache_capsule = _tls_dfti_cache_capsule() + _cache = cpython.pycapsule.PyCapsule_GetPointer(_cache_capsule, capsule_name) + if x_type is cnp.NPY_DOUBLE: + status = double_cdouble_mkl_fft1d_out(x_arr, n_, axis_, f_arr, HALF_HARMONICS, fsc, _cache) + else: + status = float_cfloat_mkl_fft1d_out(x_arr, n_, axis_, f_arr, HALF_HARMONICS, fsc, _cache) + + if (status): + c_error_msg = mkl_dfti_error(status) + py_error_msg = c_error_msg + raise ValueError("Internal error occurred: {}".format(py_error_msg)) + + # post-process and return + return _rc_to_rr(f_arr, n_, axis_, xnd, x_type) + + +def _rr_ifft1d_impl2(x, n=None, axis=-1, overwrite_arg=False, double fsc=1.0): + """ + Uses MKL to perform real packed 1D FFT on the input array x along the given axis. + + This done by using rfft_numpy and post-processing the result. + Thus overwrite_arg is effectively discarded. + + Functionally equivalent to scipy.fftpack.irfft + """ + cdef cnp.ndarray x_arr "x_arrayObject" + cdef cnp.ndarray f_arr "f_arrayObject" + cdef int xnd, err, n_max = 0, in_place, dir_, int_n + cdef long n_, axis_ + cdef int x_type, rc_type, status + cdef int direction = 1 # dummy, only used for the sake of arg-processing + cdef char * c_error_msg = NULL + cdef bytes py_error_msg + cdef DftiCache *_cache + + x_arr = __process_arguments(x, n, axis, overwrite_arg, (-1), + &axis_, &n_, &in_place, &xnd, &dir_, 1) + + x_type = cnp.PyArray_TYPE(x_arr) + + if x_type is cnp.NPY_FLOAT or x_type is cnp.NPY_DOUBLE: + pass + else: + # we must cast the input and allocate the output, + # so we cast to complex double and operate in place + try: + x_arr = cnp.PyArray_FROM_OTF( + x_arr, cnp.NPY_DOUBLE, cnp.NPY_BEHAVED | cnp.NPY_ENSURECOPY) + except: + raise ValueError("First argument should be a real or a complex sequence of single or double precision") + x_type = cnp.PyArray_TYPE(x_arr) + in_place = 1 + + # need to convert this into complex array + rc_obj = _rr_to_rc(x_arr, n_, axis_, xnd, x_type) + rc_arr = rc_obj + + rc_type = cnp.NPY_CFLOAT if x_type is cnp.NPY_FLOAT else cnp.NPY_CDOUBLE + in_place = False + if in_place: + f_arr = x_arr + else: + f_arr = __allocate_result(x_arr, n_, axis_, x_type) + + # call out-of-place FFT + if rc_type is cnp.NPY_CFLOAT: + _cache_capsule = _tls_dfti_cache_capsule() + _cache = cpython.pycapsule.PyCapsule_GetPointer(_cache_capsule, capsule_name) + status = cfloat_float_mkl_irfft_out(rc_arr, n_, axis_, f_arr, fsc, _cache) + elif rc_type is cnp.NPY_CDOUBLE: + _cache_capsule = _tls_dfti_cache_capsule() + _cache = cpython.pycapsule.PyCapsule_GetPointer(_cache_capsule, capsule_name) + status = cdouble_double_mkl_irfft_out(rc_arr, n_, axis_, f_arr, fsc, _cache) + else: + raise ValueError("Internal mkl_fft error occurred: Unrecognized rc_type") + + if (status): + c_error_msg = mkl_dfti_error(status) + py_error_msg = c_error_msg + raise ValueError("Internal error occurred: {}".format(str(py_error_msg))) + + return f_arr + + +# this routine is functionally equivalent to numpy.fft.rfft +def _rc_fft1d_impl(x, n=None, axis=-1, overwrite_arg=False, double fsc=1.0): + """ + Uses MKL to perform 1D FFT on the real input array x along the given axis, + producing complex output, but giving only half of the harmonics. + + cf. numpy.fft.rfft + """ + cdef cnp.ndarray x_arr "x_arrayObject" + cdef cnp.ndarray f_arr "f_arrayObject" + cdef int xnd, err, n_max = 0, in_place, dir_ + cdef long n_, axis_ + cdef int x_type, f_type, status, requirement + cdef int HALF_HARMONICS = 0 # give only positive index harmonics + cdef int direction = 1 # dummy, only used for the sake of arg-processing + cdef char * c_error_msg = NULL + cdef bytes py_error_msg + cdef DftiCache *_cache + + x_arr = __process_arguments(x, n, axis, overwrite_arg, direction, + &axis_, &n_, &in_place, &xnd, &dir_, 1) + + x_type = cnp.PyArray_TYPE(x_arr) + + if x_type is cnp.NPY_CFLOAT or x_type is cnp.NPY_CDOUBLE or x_type is cnp.NPY_CLONGDOUBLE: + raise TypeError("1st argument must be a real sequence 1") + elif x_type is cnp.NPY_FLOAT or x_type is cnp.NPY_DOUBLE: + pass + else: + # we must cast the input to doubles and allocate the output, + try: + requirement = cnp.NPY_BEHAVED | cnp.NPY_ENSURECOPY + if x_type is cnp.NPY_LONGDOUBLE: + requirement = requirement | cnp.NPY_FORCECAST + x_arr = cnp.PyArray_FROM_OTF( + x_arr, cnp.NPY_DOUBLE, requirement) + x_type = cnp.PyArray_TYPE(x_arr) + except: + raise TypeError("1st argument must be a real sequence 2") + + # in_place is ignored here. + # it can be done only if 2*(n_ // 2 + 1) <= x_arr.shape[axis_] which is not + # the common usage + f_type = cnp.NPY_CFLOAT if x_type is cnp.NPY_FLOAT else cnp.NPY_CDOUBLE + f_arr = __allocate_result(x_arr, n_ // 2 + 1, axis_, f_type); + + # call out-of-place FFT + if x_type is cnp.NPY_FLOAT: + _cache_capsule = _tls_dfti_cache_capsule() + _cache = cpython.pycapsule.PyCapsule_GetPointer(_cache_capsule, capsule_name) + status = float_cfloat_mkl_fft1d_out(x_arr, n_, axis_, f_arr, HALF_HARMONICS, fsc, _cache) + else: + _cache_capsule = _tls_dfti_cache_capsule() + _cache = cpython.pycapsule.PyCapsule_GetPointer(_cache_capsule, capsule_name) + status = double_cdouble_mkl_fft1d_out(x_arr, n_, axis_, f_arr, HALF_HARMONICS, fsc, _cache) + + if (status): + c_error_msg = mkl_dfti_error(status) + py_error_msg = c_error_msg + raise ValueError("Internal error occurred: {}".format(str(py_error_msg))) + + return f_arr + + +cdef int _is_integral(object num): + cdef long n + cdef int _integral + if num is None: + return 0 + try: + n = PyInt_AsLong(num) + _integral = 1 if n > 0 else 0 + except: + _integral = 0 + + return _integral + + +# this routine is functionally equivalent to numpy.fft.irfft +def _rc_ifft1d_impl(x, n=None, axis=-1, overwrite_arg=False, double fsc=1.0): + """ + Uses MKL to perform 1D FFT on the real input array x along the given axis, + producing complex output, but giving only half of the harmonics. + + cf. numpy.fft.irfft + """ + cdef cnp.ndarray x_arr "x_arrayObject" + cdef cnp.ndarray f_arr "f_arrayObject" + cdef int xnd, err, n_max = 0, in_place, dir_, int_n + cdef long n_, axis_ + cdef int x_type, f_type, status + cdef int direction = 1 # dummy, only used for the sake of arg-processing + cdef char * c_error_msg = NULL + cdef bytes py_error_msg + cdef DftiCache *_cache + + int_n = _is_integral(n) + # nn gives the number elements along axis of the input that we use + nn = (n // 2 + 1) if int_n and n > 0 else n + x_arr = __process_arguments(x, nn, axis, overwrite_arg, direction, + &axis_, &n_, &in_place, &xnd, &dir_, 0) + n_ = 2*(n_ - 1) + if int_n and (n % 2 == 1): + n_ += 1 + + x_type = cnp.PyArray_TYPE(x_arr) + + if x_type is cnp.NPY_CFLOAT or x_type is cnp.NPY_CDOUBLE: + # we can operate in place if requested. + if in_place: + if not cnp.PyArray_ISONESEGMENT(x_arr): + in_place = 0 if internal_overlap(x_arr) else 1; + else: + # we must cast the input and allocate the output, + # so we cast to complex double and operate in place + try: + x_arr = cnp.PyArray_FROM_OTF( + x_arr, cnp.NPY_CDOUBLE, cnp.NPY_BEHAVED) + except: + raise ValueError("First argument should be a real or a complex sequence of single or double precision") + x_type = cnp.PyArray_TYPE(x_arr) + in_place = 1 + + in_place = 0 + if in_place: + # TODO: Provide in-place functionality + pass + else: + f_type = cnp.NPY_FLOAT if x_type is cnp.NPY_CFLOAT else cnp.NPY_DOUBLE + f_arr = __allocate_result(x_arr, n_, axis_, f_type); + + # call out-of-place FFT + if x_type is cnp.NPY_CFLOAT: + _cache_capsule = _tls_dfti_cache_capsule() + _cache = cpython.pycapsule.PyCapsule_GetPointer(_cache_capsule, capsule_name) + status = cfloat_float_mkl_irfft_out(x_arr, n_, axis_, f_arr, fsc, _cache) + else: + _cache_capsule = _tls_dfti_cache_capsule() + _cache = cpython.pycapsule.PyCapsule_GetPointer(_cache_capsule, capsule_name) + status = cdouble_double_mkl_irfft_out(x_arr, n_, axis_, f_arr, fsc, _cache) + + if (status): + c_error_msg = mkl_dfti_error(status) + py_error_msg = c_error_msg + raise ValueError("Internal error occurred: {}".format(str(py_error_msg))) + + return f_arr + + +def rfft_numpy(x, n=None, axis=-1, forward_scale=1.0): + return _rc_fft1d_impl(x, n=n, axis=axis, fsc=forward_scale) + + +def irfft_numpy(x, n=None, axis=-1, forward_scale=1.0): + return _rc_ifft1d_impl(x, n=n, axis=axis, fsc=forward_scale) + + +# ============================== ND ====================================== # + +# copied from scipy.fftpack.helper +def _init_nd_shape_and_axes(x, shape, axes): + """Handle shape and axes arguments for n-dimensional transforms. + Returns the shape and axes in a standard form, taking into account negative + values and checking for various potential errors. + Parameters + ---------- + x : array_like + The input array. + shape : int or array_like of ints or None + The shape of the result. If both `shape` and `axes` (see below) are + None, `shape` is ``x.shape``; if `shape` is None but `axes` is + not None, then `shape` is ``scipy.take(x.shape, axes, axis=0)``. + If `shape` is -1, the size of the corresponding dimension of `x` is + used. + axes : int or array_like of ints or None + Axes along which the calculation is computed. + The default is over all axes. + Negative indices are automatically converted to their positive + counterpart. + Returns + ------- + shape : array + The shape of the result. It is a 1D integer array. + axes : array + The shape of the result. It is a 1D integer array. + """ + x = np.asarray(x) + noshape = shape is None + noaxes = axes is None + + if noaxes: + axes = np.arange(x.ndim, dtype=np.intc) + else: + axes = np.atleast_1d(axes) + + if axes.size == 0: + axes = axes.astype(np.intc) + + if not axes.ndim == 1: + raise ValueError("when given, axes values must be a scalar or vector") + if not np.issubdtype(axes.dtype, np.integer): + raise ValueError("when given, axes values must be integers") + + axes = np.where(axes < 0, axes + x.ndim, axes) + + if axes.size != 0 and (axes.max() >= x.ndim or axes.min() < 0): + raise ValueError("axes exceeds dimensionality of input") + if axes.size != 0 and np.unique(axes).shape != axes.shape: + raise ValueError("all axes must be unique") + + if not noshape: + shape = np.atleast_1d(shape) + elif np.isscalar(x): + shape = np.array([], dtype=np.intc) + elif noaxes: + shape = np.array(x.shape, dtype=np.intc) + else: + shape = np.take(x.shape, axes) + + if shape.size == 0: + shape = shape.astype(np.intc) + + if shape.ndim != 1: + raise ValueError("when given, shape values must be a scalar or vector") + if not np.issubdtype(shape.dtype, np.integer): + raise ValueError("when given, shape values must be integers") + if axes.shape != shape.shape: + raise ValueError("when given, axes and shape arguments" + " have to be of the same length") + + shape = np.where(shape == -1, np.array(x.shape)[axes], shape) + + if shape.size != 0 and (shape < 1).any(): + raise ValueError( + "invalid number of data points ({0}) specified".format(shape)) + + return shape, axes + + +def _cook_nd_args(a, s=None, axes=None, invreal=0): + if s is None: + shapeless = 1 + if axes is None: + s = list(a.shape) + else: + try: + s = [ a.shape[i] for i in axes ] + except IndexError: + # fake s designed to trip the ValueError further down + s = range(len(axes) + 1) + pass + else: + shapeless = 0 + s = list(s) + if axes is None: + axes = list(range(-len(s), 0)) + if len(s) != len(axes): + raise ValueError("Shape and axes have different lengths.") + if invreal and shapeless: + s[-1] = (a.shape[axes[-1]] - 1) * 2 + return s, axes + + +def _iter_fftnd(a, s=None, axes=None, function=fft, overwrite_arg=False, scale_function=lambda n: 1.0): + a = np.asarray(a) + s, axes = _init_nd_shape_and_axes(a, s, axes) + ovwr = overwrite_arg + for ii in reversed(range(len(axes))): + a = function(a, n = s[ii], axis = axes[ii], overwrite_x=ovwr, forward_scale=scale_function(s[ii])) + ovwr = True + return a + + +def flat_to_multi(ind, shape): + nd = len(shape) + m_ind = [-1] * nd + j = ind + for i in range(nd): + si = shape[nd-1-i] + q = j // si + r = j - si * q + m_ind[nd-1-i] = r + j = q + return m_ind + + +def iter_complementary(x, axes, func, kwargs, result): + if axes is None: + return func(x, **kwargs) + x_shape = x.shape + nd = x.ndim + r = list(range(nd)) + sl = [slice(None, None, None)] * nd + if not np.iterable(axes): + axes = (axes,) + for ai in axes: + r[ai] = None + size = 1 + sub_shape = [] + dual_ind = [] + for ri in r: + if ri is not None: + size *= x_shape[ri] + sub_shape.append(x_shape[ri]) + dual_ind.append(ri) + + for ind in range(size): + m_ind = flat_to_multi(ind, sub_shape) + for k1, k2 in zip(dual_ind, m_ind): + sl[k1] = k2 + np.copyto(result[tuple(sl)], func(x[tuple(sl)], **kwargs)) + + return result + + +def _direct_fftnd(x, overwrite_arg=False, direction=+1, double fsc=1.0): + """Perform n-dimensional FFT over all axes""" + cdef int err + cdef long n_max = 0 + cdef cnp.ndarray x_arr "xxnd_arrayObject" + cdef cnp.ndarray f_arr "ffnd_arrayObject" + cdef int xnd, dir_, in_place, x_type, f_type + + if direction not in [-1, +1]: + raise ValueError("Direction of FFT should +1 or -1") + else: + dir_ = -1 if direction is -1 else +1 + + in_place = 1 if overwrite_arg is True else 0 + + # convert x to ndarray, ensure that strides are multiples of itemsize + x_arr = PyArray_CheckFromAny( + x, NULL, 0, 0, + cnp.NPY_ELEMENTSTRIDES | cnp.NPY_ENSUREARRAY | cnp.NPY_NOTSWAPPED, + NULL) + + if x_arr is NULL: + raise ValueError("An input argument x is not an array-like object") + + if _datacopied(x_arr, x): + in_place = 1 # a copy was made, so we can work in place. + + x_type = cnp.PyArray_TYPE(x_arr) + if (x_type == cnp.NPY_CDOUBLE or x_type == cnp.NPY_CFLOAT or x_type == cnp.NPY_DOUBLE or x_type == cnp.NPY_FLOAT): + pass + else: + x_arr = cnp.PyArray_FROM_OTF( + x_arr, cnp.NPY_CDOUBLE, cnp.NPY_BEHAVED | cnp.NPY_ENSURECOPY) + x_type = cnp.PyArray_TYPE(x_arr) + assert x_type == cnp.NPY_CDOUBLE + in_place = 1 + + if in_place: + in_place = 1 if x_type == cnp.NPY_CDOUBLE or x_type == cnp.NPY_CFLOAT else 0 + + if in_place: + if x_type == cnp.NPY_CDOUBLE: + if dir_ == 1: + err = cdouble_cdouble_mkl_fftnd_in(x_arr, fsc) + else: + err = cdouble_cdouble_mkl_ifftnd_in(x_arr, fsc) + elif x_type == cnp.NPY_CFLOAT: + if dir_ == 1: + err = cfloat_cfloat_mkl_fftnd_in(x_arr, fsc) + else: + err = cfloat_cfloat_mkl_ifftnd_in(x_arr, fsc) + else: + raise ValueError("An input argument x is not complex type array") + + return x_arr + else: + f_type = cnp.NPY_CDOUBLE if x_type == cnp.NPY_CDOUBLE or x_type == cnp.NPY_DOUBLE else cnp.NPY_CFLOAT + f_arr = __allocate_result(x_arr, -1, 0, f_type); + if x_type == cnp.NPY_CDOUBLE: + if dir_ == 1: + err = cdouble_cdouble_mkl_fftnd_out(x_arr, f_arr, fsc) + else: + err = cdouble_cdouble_mkl_ifftnd_out(x_arr, f_arr, fsc) + elif x_type == cnp.NPY_CFLOAT: + if dir_ == 1: + err = cfloat_cfloat_mkl_fftnd_out(x_arr, f_arr, fsc) + else: + err = cfloat_cfloat_mkl_ifftnd_out(x_arr, f_arr, fsc) + elif x_type == cnp.NPY_DOUBLE: + if dir_ == 1: + err = double_cdouble_mkl_fftnd_out(x_arr, f_arr, fsc) + else: + err = double_cdouble_mkl_ifftnd_out(x_arr, f_arr, fsc) + elif x_type == cnp.NPY_FLOAT: + if dir_ == 1: + err = float_cfloat_mkl_fftnd_out(x_arr, f_arr, fsc) + else: + err = float_cfloat_mkl_ifftnd_out(x_arr, f_arr, fsc) + else: + raise ValueError("An input argument x is not complex type array") + + return f_arr + + +def _check_shapes_for_direct(xs, shape, axes): + if len(axes) > 7: # Intel MKL supports up to 7D + return False + if not (len(xs) == len(shape)): + return False + if not (len(set(axes)) == len(axes)): + return False + for xsi, ai in zip(xs, axes): + try: + sh_ai = shape[ai] + except IndexError: + raise ValueError("Invalid axis (%d) specified" % ai) + + if not (xsi == sh_ai): + return False + return True + + +def _output_dtype(dt): + if dt == np.double: + return np.cdouble + if dt == np.single: + return np.csingle + return dt + + +def _fftnd_impl(x, shape=None, axes=None, overwrite_x=False, direction=+1, double fsc=1.0): + if direction not in [-1, +1]: + raise ValueError("Direction of FFT should +1 or -1") + + # _direct_fftnd requires complex type, and full-dimensional transform + if isinstance(x, np.ndarray) and x.size != 0 and x.ndim > 1: + _direct = shape is None and axes is None + if _direct: + _direct = x.ndim <= 7 # Intel MKL only supports FFT up to 7D + if not _direct: + xs, xa = _cook_nd_args(x, shape, axes) + if _check_shapes_for_direct(xs, x.shape, xa): + _direct = True + _direct = _direct and x.dtype in [np.complex64, np.complex128, np.float32, np.float64] + else: + _direct = False + + if _direct: + return _direct_fftnd(x, overwrite_arg=overwrite_x, direction=direction, fsc=fsc) + else: + if (shape is None and x.dtype in [np.csingle, np.cdouble, np.single, np.double]): + x = np.asarray(x) + res = np.empty(x.shape, dtype=_output_dtype(x.dtype)) + return iter_complementary( + x, axes, + _direct_fftnd, + {'overwrite_arg': overwrite_x, 'direction': direction, 'fsc': fsc}, + res + ) + else: + sc = ( fsc)**(1/x.ndim) + return _iter_fftnd(x, s=shape, axes=axes, + overwrite_arg=overwrite_x, scale_function=lambda n: sc, + function=fft if direction == 1 else ifft) + + +def fft2(x, shape=None, axes=(-2,-1), overwrite_x=False, forward_scale=1.0): + return _fftnd_impl(x, shape=shape, axes=axes, overwrite_x=overwrite_x, direction=+1, fsc=forward_scale) + + +def ifft2(x, shape=None, axes=(-2,-1), overwrite_x=False, forward_scale=1.0): + return _fftnd_impl(x, shape=shape, axes=axes, overwrite_x=overwrite_x, direction=-1, fsc=forward_scale) + + +def fftn(x, shape=None, axes=None, overwrite_x=False, forward_scale=1.0): + return _fftnd_impl(x, shape=shape, axes=axes, overwrite_x=overwrite_x, direction=+1, fsc=forward_scale) + + +def ifftn(x, shape=None, axes=None, overwrite_x=False, forward_scale=1.0): + return _fftnd_impl(x, shape=shape, axes=axes, overwrite_x=overwrite_x, direction=-1, fsc=forward_scale) + + +def rfft2_numpy(x, s=None, axes=(-2,-1), forward_scale=1.0): + return rfftn_numpy(x, s=s, axes=axes, fsc=forward_scale) + + +def irfft2_numpy(x, s=None, axes=(-2,-1), forward_scale=1.0): + return irfftn_numpy(x, s=s, axes=axes, fsc=forward_scale) + + +def _remove_axis(s, axes, axis_to_remove): + lens = len(s) + axes_normalized = tuple(lens + ai if ai < 0 else ai for ai in axes) + a2r = lens + axis_to_remove if axis_to_remove < 0 else axis_to_remove + + ss = s[:a2r] + s[a2r+1:] + pivot = axes_normalized[a2r] + aa = tuple(ai if ai < pivot else ai - 1 for ai in axes_normalized[:a2r]) + \ + tuple(ai if ai < pivot else ai - 1 for ai in axes_normalized[a2r+1:]) + return ss, aa + + +cdef cnp.ndarray _trim_array(cnp.ndarray arr, object s, object axes): + """Forms a view into subarray of arr if any element of shape parameter s is + smaller than the corresponding element of the shape of the input array arr, + otherwise returns the input array""" + arr_shape = ( arr).shape + no_trim = True + for si, ai in zip(s, axes): + try: + shp_i = arr_shape[ai] + except IndexError: + raise ValueError("Invalid axis (%d) specified" % ai) + if si < shp_i: + if no_trim: + ind = [slice(None,None,None),] * len(s) + no_trim = False + ind[ai] = slice(None, si, None) + if no_trim: + return arr + return arr[ tuple(ind) ] + + +def _fix_dimensions(cnp.ndarray arr, object s, object axes): + """Pads array arr with zeros to attain shape s associated with axes""" + arr_shape = ( arr).shape + no_trim = True + for si, ai in zip(s, axes): + try: + shp_i = arr_shape[ai] + except IndexError: + raise ValueError("Invalid axis (%d) specified" % ai) + if si > shp_i: + if no_trim: + pad_widths = [(0,0),] * len(arr_shape) + no_trim = False + pad_widths[ai] = (0, si - shp_i) + if no_trim: + return arr + return np.pad(arr, tuple(pad_widths), 'constant') + + +def rfftn_numpy(x, s=None, axes=None, forward_scale=1.0): + a = np.asarray(x) + no_trim = (s is None) and (axes is None) + s, axes = _cook_nd_args(a, s, axes) + la = axes[-1] + # trim array, so that rfft_numpy avoids doing + # unnecessary computations + if not no_trim: + a = _trim_array(a, s, axes) + a = rfft_numpy(a, n = s[-1], axis=la, forward_scale=forward_scale) + if len(s) > 1: + if not no_trim: + ss = list(s) + ss[-1] = a.shape[la] + a = _fix_dimensions(a, tuple(ss), axes) + if len(set(axes)) == len(axes) and len(axes) == a.ndim and len(axes) > 2: + ss, aa = _remove_axis(s, axes, -1) + ind = [slice(None,None,1),] * len(s) + for ii in range(a.shape[la]): + ind[la] = ii + tind = tuple(ind) + a_inp = a[tind] + a_res = _fftnd_impl( + a_inp, shape=ss, axes=aa, + overwrite_x=True, direction=1) + if a_res is not a_inp: + a[tind] = a_res # copy in place + else: + for ii in range(len(axes)-1): + a = fft(a, s[ii], axes[ii], overwrite_x=True) + return a + + +def irfftn_numpy(x, s=None, axes=None, forward_scale=1.0): + a = np.asarray(x) + no_trim = (s is None) and (axes is None) + s, axes = _cook_nd_args(a, s, axes, invreal=True) + la = axes[-1] + if len(s) > 1: + if not no_trim: + a = _fix_dimensions(a, s, axes) + ovr_x = True if _datacopied( a, x) else False + if len(set(axes)) == len(axes) and len(axes) == a.ndim and len(axes) > 2: + # due to need to write into a, we must copy + if not ovr_x: + a = a.copy() + ovr_x = True + ss, aa = _remove_axis(s, axes, -1) + ind = [slice(None,None,1),] * len(s) + for ii in range(a.shape[la]): + ind[la] = ii + tind = tuple(ind) + a_inp = a[tind] + a_res = _fftnd_impl( + a_inp, shape=ss, axes=aa, + overwrite_x=True, direction=-1) + if a_res is not a_inp: + a[tind] = a_res # copy in place + else: + for ii in range(len(axes)-1): + a = ifft(a, s[ii], axes[ii], overwrite_x=ovr_x) + ovr_x = True + a = irfft_numpy(a, n = s[-1], axis=la, forward_scale=forward_scale) + return a diff --git a/shared/package-files/d2/d2a5d64148c153a379ca234ed3d077401f117c088b052089d11e67d04a36fa54/blob b/shared/package-files/d2/d2a5d64148c153a379ca234ed3d077401f117c088b052089d11e67d04a36fa54/blob new file mode 100644 index 0000000000000000000000000000000000000000..ee53bb53d0b0de083d5f5dc168c67e1ba4f5d071 --- /dev/null +++ b/shared/package-files/d2/d2a5d64148c153a379ca234ed3d077401f117c088b052089d11e67d04a36fa54/blob @@ -0,0 +1,172 @@ +from sympy.stats import Expectation, Normal, Variance, Covariance +from sympy.testing.pytest import raises +from sympy.core.symbol import symbols +from sympy.matrices.common import ShapeError +from sympy.matrices.dense import Matrix +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.matrices.expressions.special import ZeroMatrix +from sympy.stats.rv import RandomMatrixSymbol +from sympy.stats.symbolic_multivariate_probability import (ExpectationMatrix, + VarianceMatrix, CrossCovarianceMatrix) + +j, k = symbols("j,k") + +A = MatrixSymbol("A", k, k) +B = MatrixSymbol("B", k, k) +C = MatrixSymbol("C", k, k) +D = MatrixSymbol("D", k, k) + +a = MatrixSymbol("a", k, 1) +b = MatrixSymbol("b", k, 1) + +A2 = MatrixSymbol("A2", 2, 2) +B2 = MatrixSymbol("B2", 2, 2) + +X = RandomMatrixSymbol("X", k, 1) +Y = RandomMatrixSymbol("Y", k, 1) +Z = RandomMatrixSymbol("Z", k, 1) +W = RandomMatrixSymbol("W", k, 1) + +R = RandomMatrixSymbol("R", k, k) + +X2 = RandomMatrixSymbol("X2", 2, 1) + +normal = Normal("normal", 0, 1) + +m1 = Matrix([ + [1, j*Normal("normal2", 2, 1)], + [normal, 0] +]) + +def test_multivariate_expectation(): + expr = Expectation(a) + assert expr == Expectation(a) == ExpectationMatrix(a) + assert expr.expand() == a + + expr = Expectation(X) + assert expr == Expectation(X) == ExpectationMatrix(X) + assert expr.shape == (k, 1) + assert expr.rows == k + assert expr.cols == 1 + assert isinstance(expr, ExpectationMatrix) + + expr = Expectation(A*X + b) + assert expr == ExpectationMatrix(A*X + b) + assert expr.expand() == A*ExpectationMatrix(X) + b + assert isinstance(expr, ExpectationMatrix) + assert expr.shape == (k, 1) + + expr = Expectation(m1*X2) + assert expr.expand() == expr + + expr = Expectation(A2*m1*B2*X2) + assert expr.args[0].args == (A2, m1, B2, X2) + assert expr.expand() == A2*ExpectationMatrix(m1*B2*X2) + + expr = Expectation((X + Y)*(X - Y).T) + assert expr.expand() == ExpectationMatrix(X*X.T) - ExpectationMatrix(X*Y.T) +\ + ExpectationMatrix(Y*X.T) - ExpectationMatrix(Y*Y.T) + + expr = Expectation(A*X + B*Y) + assert expr.expand() == A*ExpectationMatrix(X) + B*ExpectationMatrix(Y) + + assert Expectation(m1).doit() == Matrix([[1, 2*j], [0, 0]]) + + x1 = Matrix([ + [Normal('N11', 11, 1), Normal('N12', 12, 1)], + [Normal('N21', 21, 1), Normal('N22', 22, 1)] + ]) + x2 = Matrix([ + [Normal('M11', 1, 1), Normal('M12', 2, 1)], + [Normal('M21', 3, 1), Normal('M22', 4, 1)] + ]) + + assert Expectation(Expectation(x1 + x2)).doit(deep=False) == ExpectationMatrix(x1 + x2) + assert Expectation(Expectation(x1 + x2)).doit() == Matrix([[12, 14], [24, 26]]) + + +def test_multivariate_variance(): + raises(ShapeError, lambda: Variance(A)) + + expr = Variance(a) + assert expr == Variance(a) == VarianceMatrix(a) + assert expr.expand() == ZeroMatrix(k, k) + expr = Variance(a.T) + assert expr == Variance(a.T) == VarianceMatrix(a.T) + assert expr.expand() == ZeroMatrix(k, k) + + expr = Variance(X) + assert expr == Variance(X) == VarianceMatrix(X) + assert expr.shape == (k, k) + assert expr.rows == k + assert expr.cols == k + assert isinstance(expr, VarianceMatrix) + + expr = Variance(A*X) + assert expr == VarianceMatrix(A*X) + assert expr.expand() == A*VarianceMatrix(X)*A.T + assert isinstance(expr, VarianceMatrix) + assert expr.shape == (k, k) + + expr = Variance(A*B*X) + assert expr.expand() == A*B*VarianceMatrix(X)*B.T*A.T + + expr = Variance(m1*X2) + assert expr.expand() == expr + + expr = Variance(A2*m1*B2*X2) + assert expr.args[0].args == (A2, m1, B2, X2) + assert expr.expand() == expr + + expr = Variance(A*X + B*Y) + assert expr.expand() == 2*A*CrossCovarianceMatrix(X, Y)*B.T +\ + A*VarianceMatrix(X)*A.T + B*VarianceMatrix(Y)*B.T + +def test_multivariate_crosscovariance(): + raises(ShapeError, lambda: Covariance(X, Y.T)) + raises(ShapeError, lambda: Covariance(X, A)) + + + expr = Covariance(a.T, b.T) + assert expr.shape == (1, 1) + assert expr.expand() == ZeroMatrix(1, 1) + + expr = Covariance(a, b) + assert expr == Covariance(a, b) == CrossCovarianceMatrix(a, b) + assert expr.expand() == ZeroMatrix(k, k) + assert expr.shape == (k, k) + assert expr.rows == k + assert expr.cols == k + assert isinstance(expr, CrossCovarianceMatrix) + + expr = Covariance(A*X + a, b) + assert expr.expand() == ZeroMatrix(k, k) + + expr = Covariance(X, Y) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == expr + + expr = Covariance(X, X) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == VarianceMatrix(X) + + expr = Covariance(X + Y, Z) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == CrossCovarianceMatrix(X, Z) + CrossCovarianceMatrix(Y, Z) + + expr = Covariance(A*X, Y) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == A*CrossCovarianceMatrix(X, Y) + + expr = Covariance(X, B*Y) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == CrossCovarianceMatrix(X, Y)*B.T + + expr = Covariance(A*X + a, B.T*Y + b) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == A*CrossCovarianceMatrix(X, Y)*B + + expr = Covariance(A*X + B*Y + a, C.T*Z + D.T*W + b) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == A*CrossCovarianceMatrix(X, W)*D + A*CrossCovarianceMatrix(X, Z)*C \ + + B*CrossCovarianceMatrix(Y, W)*D + B*CrossCovarianceMatrix(Y, Z)*C diff --git a/shared/package-files/d2/d2a5eb21806bc765d8c11af1d4de55e61f47805b5d98ae29cd07c430fafe10f6/blob b/shared/package-files/d2/d2a5eb21806bc765d8c11af1d4de55e61f47805b5d98ae29cd07c430fafe10f6/blob new file mode 100644 index 0000000000000000000000000000000000000000..d50af4345d9fe6037327b5ca8a3380bbf9e991e3 --- /dev/null +++ b/shared/package-files/d2/d2a5eb21806bc765d8c11af1d4de55e61f47805b5d98ae29cd07c430fafe10f6/blob @@ -0,0 +1,5 @@ +from django.dispatch.dispatcher import Signal + +user_logged_in: Signal +user_login_failed: Signal +user_logged_out: Signal diff --git a/shared/package-files/d2/d2a95d5f7550299726ea5827ef31f3f78a11168c3b60f604462aa4aaea263635/blob b/shared/package-files/d2/d2a95d5f7550299726ea5827ef31f3f78a11168c3b60f604462aa4aaea263635/blob new file mode 100644 index 0000000000000000000000000000000000000000..185d33246e395cc9a905bf7a05e5abdf1a1bbe5e --- /dev/null +++ b/shared/package-files/d2/d2a95d5f7550299726ea5827ef31f3f78a11168c3b60f604462aa4aaea263635/blob @@ -0,0 +1,1667 @@ +"""Classes for managing templates and their runtime and compile time +options. +""" +import os +import typing +import typing as t +import weakref +from collections import ChainMap +from functools import lru_cache +from functools import partial +from functools import reduce +from types import CodeType + +from markupsafe import Markup + +from . import nodes +from .compiler import CodeGenerator +from .compiler import generate +from .defaults import BLOCK_END_STRING +from .defaults import BLOCK_START_STRING +from .defaults import COMMENT_END_STRING +from .defaults import COMMENT_START_STRING +from .defaults import DEFAULT_FILTERS +from .defaults import DEFAULT_NAMESPACE +from .defaults import DEFAULT_POLICIES +from .defaults import DEFAULT_TESTS +from .defaults import KEEP_TRAILING_NEWLINE +from .defaults import LINE_COMMENT_PREFIX +from .defaults import LINE_STATEMENT_PREFIX +from .defaults import LSTRIP_BLOCKS +from .defaults import NEWLINE_SEQUENCE +from .defaults import TRIM_BLOCKS +from .defaults import VARIABLE_END_STRING +from .defaults import VARIABLE_START_STRING +from .exceptions import TemplateNotFound +from .exceptions import TemplateRuntimeError +from .exceptions import TemplatesNotFound +from .exceptions import TemplateSyntaxError +from .exceptions import UndefinedError +from .lexer import get_lexer +from .lexer import Lexer +from .lexer import TokenStream +from .nodes import EvalContext +from .parser import Parser +from .runtime import Context +from .runtime import new_context +from .runtime import Undefined +from .utils import _PassArg +from .utils import concat +from .utils import consume +from .utils import import_string +from .utils import internalcode +from .utils import LRUCache +from .utils import missing + +if t.TYPE_CHECKING: + import typing_extensions as te + from .bccache import BytecodeCache + from .ext import Extension + from .loaders import BaseLoader + +_env_bound = t.TypeVar("_env_bound", bound="Environment") + + +# for direct template usage we have up to ten living environments +@lru_cache(maxsize=10) +def get_spontaneous_environment(cls: t.Type[_env_bound], *args: t.Any) -> _env_bound: + """Return a new spontaneous environment. A spontaneous environment + is used for templates created directly rather than through an + existing environment. + + :param cls: Environment class to create. + :param args: Positional arguments passed to environment. + """ + env = cls(*args) + env.shared = True + return env + + +def create_cache( + size: int, +) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]: + """Return the cache class for the given size.""" + if size == 0: + return None + + if size < 0: + return {} + + return LRUCache(size) # type: ignore + + +def copy_cache( + cache: t.Optional[t.MutableMapping], +) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]: + """Create an empty copy of the given cache.""" + if cache is None: + return None + + if type(cache) is dict: + return {} + + return LRUCache(cache.capacity) # type: ignore + + +def load_extensions( + environment: "Environment", + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]], +) -> t.Dict[str, "Extension"]: + """Load the extensions from the list and bind it to the environment. + Returns a dict of instantiated extensions. + """ + result = {} + + for extension in extensions: + if isinstance(extension, str): + extension = t.cast(t.Type["Extension"], import_string(extension)) + + result[extension.identifier] = extension(environment) + + return result + + +def _environment_config_check(environment: "Environment") -> "Environment": + """Perform a sanity check on the environment.""" + assert issubclass( + environment.undefined, Undefined + ), "'undefined' must be a subclass of 'jinja2.Undefined'." + assert ( + environment.block_start_string + != environment.variable_start_string + != environment.comment_start_string + ), "block, variable and comment start strings must be different." + assert environment.newline_sequence in { + "\r", + "\r\n", + "\n", + }, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'." + return environment + + +class Environment: + r"""The core component of Jinja is the `Environment`. It contains + important shared variables like configuration, filters, tests, + globals and others. Instances of this class may be modified if + they are not shared and if no template was loaded so far. + Modifications on environments after the first template was loaded + will lead to surprising effects and undefined behavior. + + Here are the possible initialization parameters: + + `block_start_string` + The string marking the beginning of a block. Defaults to ``'{%'``. + + `block_end_string` + The string marking the end of a block. Defaults to ``'%}'``. + + `variable_start_string` + The string marking the beginning of a print statement. + Defaults to ``'{{'``. + + `variable_end_string` + The string marking the end of a print statement. Defaults to + ``'}}'``. + + `comment_start_string` + The string marking the beginning of a comment. Defaults to ``'{#'``. + + `comment_end_string` + The string marking the end of a comment. Defaults to ``'#}'``. + + `line_statement_prefix` + If given and a string, this will be used as prefix for line based + statements. See also :ref:`line-statements`. + + `line_comment_prefix` + If given and a string, this will be used as prefix for line based + comments. See also :ref:`line-statements`. + + .. versionadded:: 2.2 + + `trim_blocks` + If this is set to ``True`` the first newline after a block is + removed (block, not variable tag!). Defaults to `False`. + + `lstrip_blocks` + If this is set to ``True`` leading spaces and tabs are stripped + from the start of a line to a block. Defaults to `False`. + + `newline_sequence` + The sequence that starts a newline. Must be one of ``'\r'``, + ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a + useful default for Linux and OS X systems as well as web + applications. + + `keep_trailing_newline` + Preserve the trailing newline when rendering templates. + The default is ``False``, which causes a single newline, + if present, to be stripped from the end of the template. + + .. versionadded:: 2.7 + + `extensions` + List of Jinja extensions to use. This can either be import paths + as strings or extension classes. For more information have a + look at :ref:`the extensions documentation `. + + `optimized` + should the optimizer be enabled? Default is ``True``. + + `undefined` + :class:`Undefined` or a subclass of it that is used to represent + undefined values in the template. + + `finalize` + A callable that can be used to process the result of a variable + expression before it is output. For example one can convert + ``None`` implicitly into an empty string here. + + `autoescape` + If set to ``True`` the XML/HTML autoescaping feature is enabled by + default. For more details about autoescaping see + :class:`~markupsafe.Markup`. As of Jinja 2.4 this can also + be a callable that is passed the template name and has to + return ``True`` or ``False`` depending on autoescape should be + enabled by default. + + .. versionchanged:: 2.4 + `autoescape` can now be a function + + `loader` + The template loader for this environment. + + `cache_size` + The size of the cache. Per default this is ``400`` which means + that if more than 400 templates are loaded the loader will clean + out the least recently used template. If the cache size is set to + ``0`` templates are recompiled all the time, if the cache size is + ``-1`` the cache will not be cleaned. + + .. versionchanged:: 2.8 + The cache size was increased to 400 from a low 50. + + `auto_reload` + Some loaders load templates from locations where the template + sources may change (ie: file system or database). If + ``auto_reload`` is set to ``True`` (default) every time a template is + requested the loader checks if the source changed and if yes, it + will reload the template. For higher performance it's possible to + disable that. + + `bytecode_cache` + If set to a bytecode cache object, this object will provide a + cache for the internal Jinja bytecode so that templates don't + have to be parsed if they were not changed. + + See :ref:`bytecode-cache` for more information. + + `enable_async` + If set to true this enables async template execution which + allows using async functions and generators. + """ + + #: if this environment is sandboxed. Modifying this variable won't make + #: the environment sandboxed though. For a real sandboxed environment + #: have a look at jinja2.sandbox. This flag alone controls the code + #: generation by the compiler. + sandboxed = False + + #: True if the environment is just an overlay + overlayed = False + + #: the environment this environment is linked to if it is an overlay + linked_to: t.Optional["Environment"] = None + + #: shared environments have this set to `True`. A shared environment + #: must not be modified + shared = False + + #: the class that is used for code generation. See + #: :class:`~jinja2.compiler.CodeGenerator` for more information. + code_generator_class: t.Type["CodeGenerator"] = CodeGenerator + + concat = "".join + + #: the context class that is used for templates. See + #: :class:`~jinja2.runtime.Context` for more information. + context_class: t.Type[Context] = Context + + template_class: t.Type["Template"] + + def __init__( + self, + block_start_string: str = BLOCK_START_STRING, + block_end_string: str = BLOCK_END_STRING, + variable_start_string: str = VARIABLE_START_STRING, + variable_end_string: str = VARIABLE_END_STRING, + comment_start_string: str = COMMENT_START_STRING, + comment_end_string: str = COMMENT_END_STRING, + line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX, + line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX, + trim_blocks: bool = TRIM_BLOCKS, + lstrip_blocks: bool = LSTRIP_BLOCKS, + newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE, + keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE, + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (), + optimized: bool = True, + undefined: t.Type[Undefined] = Undefined, + finalize: t.Optional[t.Callable[..., t.Any]] = None, + autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False, + loader: t.Optional["BaseLoader"] = None, + cache_size: int = 400, + auto_reload: bool = True, + bytecode_cache: t.Optional["BytecodeCache"] = None, + enable_async: bool = False, + ): + # !!Important notice!! + # The constructor accepts quite a few arguments that should be + # passed by keyword rather than position. However it's important to + # not change the order of arguments because it's used at least + # internally in those cases: + # - spontaneous environments (i18n extension and Template) + # - unittests + # If parameter changes are required only add parameters at the end + # and don't change the arguments (or the defaults!) of the arguments + # existing already. + + # lexer / parser information + self.block_start_string = block_start_string + self.block_end_string = block_end_string + self.variable_start_string = variable_start_string + self.variable_end_string = variable_end_string + self.comment_start_string = comment_start_string + self.comment_end_string = comment_end_string + self.line_statement_prefix = line_statement_prefix + self.line_comment_prefix = line_comment_prefix + self.trim_blocks = trim_blocks + self.lstrip_blocks = lstrip_blocks + self.newline_sequence = newline_sequence + self.keep_trailing_newline = keep_trailing_newline + + # runtime information + self.undefined: t.Type[Undefined] = undefined + self.optimized = optimized + self.finalize = finalize + self.autoescape = autoescape + + # defaults + self.filters = DEFAULT_FILTERS.copy() + self.tests = DEFAULT_TESTS.copy() + self.globals = DEFAULT_NAMESPACE.copy() + + # set the loader provided + self.loader = loader + self.cache = create_cache(cache_size) + self.bytecode_cache = bytecode_cache + self.auto_reload = auto_reload + + # configurable policies + self.policies = DEFAULT_POLICIES.copy() + + # load extensions + self.extensions = load_extensions(self, extensions) + + self.is_async = enable_async + _environment_config_check(self) + + def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None: + """Adds an extension after the environment was created. + + .. versionadded:: 2.5 + """ + self.extensions.update(load_extensions(self, [extension])) + + def extend(self, **attributes: t.Any) -> None: + """Add the items to the instance of the environment if they do not exist + yet. This is used by :ref:`extensions ` to register + callbacks and configuration values without breaking inheritance. + """ + for key, value in attributes.items(): + if not hasattr(self, key): + setattr(self, key, value) + + def overlay( + self, + block_start_string: str = missing, + block_end_string: str = missing, + variable_start_string: str = missing, + variable_end_string: str = missing, + comment_start_string: str = missing, + comment_end_string: str = missing, + line_statement_prefix: t.Optional[str] = missing, + line_comment_prefix: t.Optional[str] = missing, + trim_blocks: bool = missing, + lstrip_blocks: bool = missing, + newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing, + keep_trailing_newline: bool = missing, + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing, + optimized: bool = missing, + undefined: t.Type[Undefined] = missing, + finalize: t.Optional[t.Callable[..., t.Any]] = missing, + autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing, + loader: t.Optional["BaseLoader"] = missing, + cache_size: int = missing, + auto_reload: bool = missing, + bytecode_cache: t.Optional["BytecodeCache"] = missing, + enable_async: bool = False, + ) -> "Environment": + """Create a new overlay environment that shares all the data with the + current environment except for cache and the overridden attributes. + Extensions cannot be removed for an overlayed environment. An overlayed + environment automatically gets all the extensions of the environment it + is linked to plus optional extra extensions. + + Creating overlays should happen after the initial environment was set + up completely. Not all attributes are truly linked, some are just + copied over so modifications on the original environment may not shine + through. + + .. versionchanged:: 3.1.2 + Added the ``newline_sequence``,, ``keep_trailing_newline``, + and ``enable_async`` parameters to match ``__init__``. + """ + args = dict(locals()) + del args["self"], args["cache_size"], args["extensions"], args["enable_async"] + + rv = object.__new__(self.__class__) + rv.__dict__.update(self.__dict__) + rv.overlayed = True + rv.linked_to = self + + for key, value in args.items(): + if value is not missing: + setattr(rv, key, value) + + if cache_size is not missing: + rv.cache = create_cache(cache_size) + else: + rv.cache = copy_cache(self.cache) + + rv.extensions = {} + for key, value in self.extensions.items(): + rv.extensions[key] = value.bind(rv) + if extensions is not missing: + rv.extensions.update(load_extensions(rv, extensions)) + + if enable_async is not missing: + rv.is_async = enable_async + + return _environment_config_check(rv) + + @property + def lexer(self) -> Lexer: + """The lexer for this environment.""" + return get_lexer(self) + + def iter_extensions(self) -> t.Iterator["Extension"]: + """Iterates over the extensions by priority.""" + return iter(sorted(self.extensions.values(), key=lambda x: x.priority)) + + def getitem( + self, obj: t.Any, argument: t.Union[str, t.Any] + ) -> t.Union[t.Any, Undefined]: + """Get an item or attribute of an object but prefer the item.""" + try: + return obj[argument] + except (AttributeError, TypeError, LookupError): + if isinstance(argument, str): + try: + attr = str(argument) + except Exception: + pass + else: + try: + return getattr(obj, attr) + except AttributeError: + pass + return self.undefined(obj=obj, name=argument) + + def getattr(self, obj: t.Any, attribute: str) -> t.Any: + """Get an item or attribute of an object but prefer the attribute. + Unlike :meth:`getitem` the attribute *must* be a string. + """ + try: + return getattr(obj, attribute) + except AttributeError: + pass + try: + return obj[attribute] + except (TypeError, LookupError, AttributeError): + return self.undefined(obj=obj, name=attribute) + + def _filter_test_common( + self, + name: t.Union[str, Undefined], + value: t.Any, + args: t.Optional[t.Sequence[t.Any]], + kwargs: t.Optional[t.Mapping[str, t.Any]], + context: t.Optional[Context], + eval_ctx: t.Optional[EvalContext], + is_filter: bool, + ) -> t.Any: + if is_filter: + env_map = self.filters + type_name = "filter" + else: + env_map = self.tests + type_name = "test" + + func = env_map.get(name) # type: ignore + + if func is None: + msg = f"No {type_name} named {name!r}." + + if isinstance(name, Undefined): + try: + name._fail_with_undefined_error() + except Exception as e: + msg = f"{msg} ({e}; did you forget to quote the callable name?)" + + raise TemplateRuntimeError(msg) + + args = [value, *(args if args is not None else ())] + kwargs = kwargs if kwargs is not None else {} + pass_arg = _PassArg.from_obj(func) + + if pass_arg is _PassArg.context: + if context is None: + raise TemplateRuntimeError( + f"Attempted to invoke a context {type_name} without context." + ) + + args.insert(0, context) + elif pass_arg is _PassArg.eval_context: + if eval_ctx is None: + if context is not None: + eval_ctx = context.eval_ctx + else: + eval_ctx = EvalContext(self) + + args.insert(0, eval_ctx) + elif pass_arg is _PassArg.environment: + args.insert(0, self) + + return func(*args, **kwargs) + + def call_filter( + self, + name: str, + value: t.Any, + args: t.Optional[t.Sequence[t.Any]] = None, + kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + context: t.Optional[Context] = None, + eval_ctx: t.Optional[EvalContext] = None, + ) -> t.Any: + """Invoke a filter on a value the same way the compiler does. + + This might return a coroutine if the filter is running from an + environment in async mode and the filter supports async + execution. It's your responsibility to await this if needed. + + .. versionadded:: 2.7 + """ + return self._filter_test_common( + name, value, args, kwargs, context, eval_ctx, True + ) + + def call_test( + self, + name: str, + value: t.Any, + args: t.Optional[t.Sequence[t.Any]] = None, + kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + context: t.Optional[Context] = None, + eval_ctx: t.Optional[EvalContext] = None, + ) -> t.Any: + """Invoke a test on a value the same way the compiler does. + + This might return a coroutine if the test is running from an + environment in async mode and the test supports async execution. + It's your responsibility to await this if needed. + + .. versionchanged:: 3.0 + Tests support ``@pass_context``, etc. decorators. Added + the ``context`` and ``eval_ctx`` parameters. + + .. versionadded:: 2.7 + """ + return self._filter_test_common( + name, value, args, kwargs, context, eval_ctx, False + ) + + @internalcode + def parse( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> nodes.Template: + """Parse the sourcecode and return the abstract syntax tree. This + tree of nodes is used by the compiler to convert the template into + executable source- or bytecode. This is useful for debugging or to + extract information from templates. + + If you are :ref:`developing Jinja extensions ` + this gives you a good overview of the node tree generated. + """ + try: + return self._parse(source, name, filename) + except TemplateSyntaxError: + self.handle_exception(source=source) + + def _parse( + self, source: str, name: t.Optional[str], filename: t.Optional[str] + ) -> nodes.Template: + """Internal parsing function used by `parse` and `compile`.""" + return Parser(self, source, name, filename).parse() + + def lex( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> t.Iterator[t.Tuple[int, str, str]]: + """Lex the given sourcecode and return a generator that yields + tokens as tuples in the form ``(lineno, token_type, value)``. + This can be useful for :ref:`extension development ` + and debugging templates. + + This does not perform preprocessing. If you want the preprocessing + of the extensions to be applied you have to filter source through + the :meth:`preprocess` method. + """ + source = str(source) + try: + return self.lexer.tokeniter(source, name, filename) + except TemplateSyntaxError: + self.handle_exception(source=source) + + def preprocess( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> str: + """Preprocesses the source with all extensions. This is automatically + called for all parsing and compiling methods but *not* for :meth:`lex` + because there you usually only want the actual source tokenized. + """ + return reduce( + lambda s, e: e.preprocess(s, name, filename), + self.iter_extensions(), + str(source), + ) + + def _tokenize( + self, + source: str, + name: t.Optional[str], + filename: t.Optional[str] = None, + state: t.Optional[str] = None, + ) -> TokenStream: + """Called by the parser to do the preprocessing and filtering + for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. + """ + source = self.preprocess(source, name, filename) + stream = self.lexer.tokenize(source, name, filename, state) + + for ext in self.iter_extensions(): + stream = ext.filter_stream(stream) # type: ignore + + if not isinstance(stream, TokenStream): + stream = TokenStream(stream, name, filename) # type: ignore + + return stream + + def _generate( + self, + source: nodes.Template, + name: t.Optional[str], + filename: t.Optional[str], + defer_init: bool = False, + ) -> str: + """Internal hook that can be overridden to hook a different generate + method in. + + .. versionadded:: 2.5 + """ + return generate( # type: ignore + source, + self, + name, + filename, + defer_init=defer_init, + optimized=self.optimized, + ) + + def _compile(self, source: str, filename: str) -> CodeType: + """Internal hook that can be overridden to hook a different compile + method in. + + .. versionadded:: 2.5 + """ + return compile(source, filename, "exec") + + @typing.overload + def compile( # type: ignore + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: "te.Literal[False]" = False, + defer_init: bool = False, + ) -> CodeType: + ... + + @typing.overload + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: "te.Literal[True]" = ..., + defer_init: bool = False, + ) -> str: + ... + + @internalcode + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: bool = False, + defer_init: bool = False, + ) -> t.Union[str, CodeType]: + """Compile a node or template source code. The `name` parameter is + the load name of the template after it was joined using + :meth:`join_path` if necessary, not the filename on the file system. + the `filename` parameter is the estimated filename of the template on + the file system. If the template came from a database or memory this + can be omitted. + + The return value of this method is a python code object. If the `raw` + parameter is `True` the return value will be a string with python + code equivalent to the bytecode returned otherwise. This method is + mainly used internally. + + `defer_init` is use internally to aid the module code generator. This + causes the generated code to be able to import without the global + environment variable to be set. + + .. versionadded:: 2.4 + `defer_init` parameter added. + """ + source_hint = None + try: + if isinstance(source, str): + source_hint = source + source = self._parse(source, name, filename) + source = self._generate(source, name, filename, defer_init=defer_init) + if raw: + return source + if filename is None: + filename = "